{"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'] \n \"\"\"\n if not isinstance(seq, (list, tuple)):\n raise TypeError(\"param 'seq' must be a list or tuple\")\n\n if not isinstance(remove_indices, (list, tuple, set)):\n raise TypeError(\"param 'remove_indices' must be a list, tuple, or set\")\n\n for index in remove_indices:\n if not isinstance(index, int) or index < 0:\n raise ValueError(\n \"param 'remove_indices' must contain only positive integers\"\n )\n\n index = 0\n while index < len(seq):\n if not index in remove_indices:\n yield seq[index]\n index = index + 1\n"} {"doc_id": "01b9b98e195c93cc88bc3657a3138c41", "text": "\n## Python Crash Course\n\n# Exercise 3.7: Shrinking Guest List: \n# You just found out that your new dinner table won\u2019t arrive in time for the dinner, and you have space for only two guests.\n# \u2022 Start with your program from Exercise 3-6. Add a new line that prints a message saying that you can invite only two people for dinner.\n# \u2022 Use pop() to remove guests from your list one at a time until only two names remain in your list. \n# Each time you pop a name from your list, print a message to that person letting them know you\u2019re sorry you can\u2019t invite them to dinner.\n# \u2022 Print a message to each of the two people still on your list, letting them know they\u2019re still invited .\n# \u2022 Use del to remove the last two names from your list, so you have an empty list. \n# Print your list to make sure you actually have an empty list at the end of your program .\n\n\ndef main():\n \n # Prepare empty list for invitees \n dinnerInvitees = []\n\n # Add invitees one by one in the invitees list\n dinnerInvitees.append('Andrew Ng')\n dinnerInvitees.append('Narendra Modi')\n dinnerInvitees.append('Jordon')\n sendInvites(dinnerInvitees)\n \n # Following person cant make it to the dinner party\n personWhoCantMake = dinnerInvitees.pop(1)\n\n # Print that one of the Guests cant make it to the party\n print(personWhoCantMake,\"can't make it to the birthday party!\")\n\n # Following person is the new guest to the party\n anotherGuestToInvite = 'Abdul Kalam'\n print(anotherGuestToInvite,\"is coming to the party!!\")\n print(\"Sending second set of invites..\")\n\n # Add new gues to the list\n dinnerInvitees.insert(1, anotherGuestToInvite)\n \n # Send another set of invites\n sendInvites(dinnerInvitees)\n\n # Insert one guest at the top of the list\n dinnerInvitees.insert(0, 'Aryabhatta')\n\n # Insert one guest in the middle of the list\n dinnerInvitees.insert(2, 'Ramanujan')\n\n # Append one guest to the end of the list\n dinnerInvitees.append('ShriKrishna')\n\n # Send invitations one last time\n sendInvites(dinnerInvitees)\n\n # Bigger dinner table is not available and only 2 invitees can join\n for i in range(len(dinnerInvitees)):\n if len(dinnerInvitees) > 2:\n nameOfPerson = dinnerInvitees.pop()\n print(\"Hello\", nameOfPerson, \", my apologies for invitation that I sent out, but the dinner table is not available for now.\"\n \" We will go for dinner some other day!\")\n # Send invite to only 2 guests that will be joining party\n sendInvites(dinnerInvitees)\n\n # Delete name of all guests and make the list empty\n for m in range(len(dinnerInvitees)):\n del dinnerInvitees[0]\n\n # Print list to ensure that list is empty\n print(\"Following is the list at the end of exercise 3.7:\")\n print(dinnerInvitees)\n\n\ndef sendInvites(dinnerInvitees):\n \n # Send invitation to invitees\n for i in range(len(dinnerInvitees)):\n \n # Generic greeting message\n greetingMessage = \"Hi \" + str(dinnerInvitees[i]) + \", it's my birthday today, would you join us for the dinner? \" \\\n \"\\nWe also have following guests joining us: \"\n \n # Create list of other guests at the dinner \n listOfInvitees = dinnerInvitees.copy()\n del listOfInvitees[i]\n \n # Print invitation\n print(\"\\n### \\t Birthday Bash \\t ###\")\n print(greetingMessage)\n\n # Print list of other guests\n for x in range(len(listOfInvitees)):\n print(listOfInvitees[x])\n\n # Print end of invitation \n print(\"\\n###########################\\n\\n\") \n\n\nif __name__ == '__main__':\n main()\n\n"} {"doc_id": "01f1b8cf04a1962c880bad675bb47c51", "text": "# Strong Password Generator in Python\n# A strong password is the one which contains combination of signs, symbols, special characters, numbers and alphabets.\n# This program will help the user to generate a strong password of the given length.\n\n# Developed by Irshan Akhtar - @cybernaut01 for HacktoberFest 2020\n\nimport random\nimport array\n\n#Accepting the maximum length of the password as required by the user.\nlength = input(\"Please Enter the length of the Password : \")\n\ndigits = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']\nlowercase = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']\nuppercase = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']\nsymbols = ['@', '#', '$', '%', '=', ':', '?', '.', '/', '|', '~', '>', '*', '(', ')', ]\n\n#Creating a combined list of all characters.\ncombined_list = digits+lowercase+uppercase+symbols\n\n#Now with the help of random library selecting at least one character from the above four lists.\nrand_digit = random.choice(digits)\nrand_lower = random.choice(lowercase)\nrand_upper = random.choice(uppercase)\nrand_symbol= random.choice(symbols)\n\n#Now combining all the 4 characters to form the initial strong password.\ntemp_pass = rand_digit+rand_lower+rand_upper+rand_symbol\n\n#Now after getting 4 characters from all the lists, we can add more characters to complete our password.\nlt = int(length)\nfor i in range(lt-4):\n temp_pass = temp_pass + random.choice(combined_list)\n\n #Adding the temp_pass variable to an array named temp_pass_ar\n temp_pass_ar = array.array('u',temp_pass)\n #Shuffling the list so that the consistent pattern in the array is dissolved\n\n random.shuffle(temp_pass_ar)\n\n#Now, Finally creating the password and displaying the output to the user.\n\npassword = \"\"\nfor pass_li in temp_pass_ar:\n password = password+pass_li\n\nprint(\"Password : \"+password)\n"} {"doc_id": "0217eeb13cb66f6c85885349f4d24286", "text": "\"\"\"\nAuthor: Scott C Gramig\nProgram: Recursively calculates the Nth Fibonacci number\n\"\"\"\n\ndef fibo(n):\n\tresult = []\n\tif n == 1 or n == 2:\n\t\treturn 1\n\treturn fibo(n-1) + fibo(n-2)\n\nprint \"-------- The Nth Fibonacci Number Calculator --------\"\nn = int(raw_input(\"Enter the Nth number: \"))\n\nprint fibo(n)\n"} {"doc_id": "024a44b0e600ce4d1256b48560858caa", "text": "# Ex: 098 - Fa\u00e7a um programa que tenha uma fun\u00e7\u00e3o chamada contador(), que \n# receba tr\u00eas par\u00e3mentros: in\u00edcio, fim e passo e ralize a contagem. Seu \n# programa tem que realizar tr\u1ebds contagens atrav\u00e9s da fun\u00e7\u00e3o criada: \n# A- De 1 at\u00e9 10, de 1 em 1; \n# B- De 10 at\u00e9 0, de 2 em 2; \n# C- Uma contagem personalizada.\n\nfrom time import sleep\n\n\ndef contador(inicio, fim, passo): \n print(f\"--Contagem de {inicio} at\u00e9 {fim} de {passo} em {passo}.\")\n sleep(2)\n \n if inicio >= fim and passo > 0:\n passo *= -1\n fim -= 2\n \n elif inicio >= fim:\n fim -= 2\n \n if passo == 0 and inicio > fim:\n passo = -1\n \n elif passo == 0 and inicio < fim:\n passo = 1\n \n for x in range(inicio, fim + 1, passo):\n print(x, end=' | ', flush=True)\n sleep(0.5)\n \n print(\"FIM!\\n\")\n\nprint('''\n-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-\n--Seja bem-vindo! \n--Exerc\u00edcio 098\n-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-\n''')\n\ncontador(1, 10, 1)\ncontador(10, 0, 2)\n\nprint(\"--Tente voc\u00ea tamb\u00e9m!! \")\ninicio = int(input(\"In\u00edcio: \"))\nfim = int(input(\"Fim: \"))\npasso = int(input(\"Passo: \"))\ncontador(inicio, fim, passo)\n\nprint('''\n-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-\n--Obrigado pelo uso!\n--Desenvolvido por Thalles Torres\n-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-''')\n"} {"doc_id": "0263a98bd54692966cc53021246bd02b", "text": "def find_item(list, item):\r\n #Returns True if the item is in the list, False if not.\r\n if len(list) == 0:\r\n return False\r\n \r\n # In order to use binary search, list needs to be sorted\r\n list.sort()\r\n\r\n #Is the item in the center of the list?\r\n middle = len(list)//2\r\n if list[middle] == item:\r\n return True\r\n\r\n #Is the item in the first half of the list? \r\n if item < list[middle]:\r\n #Call the function with the first half of the list\r\n return find_item(list[:middle], item)\r\n else:\r\n #Call the function with the second half of the list\r\n return find_item(list[middle+1:], item)\r\n\r\n return False\r\n\r\n#Do not edit below this line - This code helps check your work!\r\nlist_of_names = [\"Parker\", \"Drew\", \"Cameron\", \"Logan\", \"Alex\", \"Chris\", \"Terry\", \"Jamie\", \"Jordan\", \"Taylor\"]\r\n\r\nprint(find_item(list_of_names, \"Alex\")) # True\r\nprint(find_item(list_of_names, \"Andrew\")) # False\r\nprint(find_item(list_of_names, \"Drew\")) # True\r\nprint(find_item(list_of_names, \"Jared\")) # False"} {"doc_id": "0263cb8fcd371dd87ae4bc5a39e0224a", "text": "\"\"\"\r\nFile: shrink.py\r\nAuthor: Jade Yeh\r\n-------------------------------\r\nCreate a new \"out\" image half the width and height of the original.\r\nSet pixels at x=0 1 2 3 in out , from x=0 2 4 6 in original,\r\nand likewise in the y direction.\r\n\"\"\"\r\n\r\nfrom simpleimage import SimpleImage\r\n\r\n\r\ndef shrink(filename):\r\n \"\"\"\r\n :param filename: SimpleImage, the original image\r\n :return img: SimpleImage, every four pixels in original image are condensed in a corresponding pixel of new image\r\n \"\"\"\r\n # The original image\r\n old_img = SimpleImage(filename)\r\n # Create a new, blank image with half width and half height as the original image\r\n new_img = SimpleImage.blank(old_img.width // 2, old_img.height // 2)\r\n # (x, y) represent every pixel in the new image\r\n for x in range(new_img.width):\r\n for y in range(new_img.height):\r\n # get pixel at (x, y) in new, blank image\r\n p_new = new_img.get_pixel(x, y)\r\n # p_old_'no.' represent pixels all corresponding to (x, y) for the proportional scaling\r\n p_old_1 = old_img.get_pixel(2 * x, 2 * y)\r\n p_old_2 = old_img.get_pixel(2 * x, 2 * y + 1)\r\n p_old_3 = old_img.get_pixel(2 * x + 1, 2 * y)\r\n p_old_4 = old_img.get_pixel(2 * x + 1, 2 * y + 1)\r\n # replace R-value at (x, y) with the average R-value of all corresponding points\r\n p_new.red = (p_old_1.red + p_old_2.red + p_old_3.red + p_old_4.red) // 4\r\n # replace G-value at (x, y) with the average G-value of all corresponding points\r\n p_new.green = (p_old_1.green + p_old_2.green + p_old_3.green + p_old_4.green) // 4\r\n # replace B-value at (x, y) with the average B-value of all corresponding points\r\n p_new.blue = (p_old_1.blue + p_old_2.blue + p_old_3.blue + p_old_4.blue) // 4\r\n # return the shrink image\r\n return new_img\r\n\r\n\r\ndef main():\r\n \"\"\"\r\n User import a image.\r\n Coder will proportional scale the original image to a new image with half size.\r\n \"\"\"\r\n # Import a image\r\n original = SimpleImage(\"images/poppy.png\")\r\n # Show the original image\r\n original.show()\r\n after_shrink = shrink(\"images/poppy.png\")\r\n # Show the shrink image\r\n after_shrink.show()\r\n\r\n\r\nif __name__ == '__main__':\r\n main()\r\n"} {"doc_id": "028e5eb1ecb1252f089e3e9adae91b56", "text": "\"\"\"\nPurpose: Given a binary matrix of N*M order where 0 is the wall and 1 is way.\n Find the shortest distance from a source cell to a destination cell,\n traversing through limited cells only. Also you can move only\n up, down, left and right. If found then print the distance and\n path in separate lines, else return -1.\n\"\"\"\n\nfrom heapq import heappop, heappush\n\n# Manhattan Distance for heuristic functionn\n\n\ndef heuristic_function(p1, p2):\n x1, y1 = p1\n x2, y2 = p2\n return abs(x1 - x2) + abs(y1 - y2)\n\n\ndef Astar(maze, src, des, way=1):\n\n # Base Case: If there is no way from the source, returnn False\n if(maze[src[0]][src[1]] != 1):\n return False\n\n # Dimention of the maze\n n = len(maze)\n m = len(maze[0])\n\n hp = []\n count = 0\n x, y = src\n\n # To keep a track of visited nodes, also mark source as visited\n visited = [[False] * m for i in range(n)]\n visited[x][y] = True\n\n # All possible moves from a cell\n moves = {(1, 0): 'D', (-1, 0): 'U', (0, 1): 'R', (0, -1): 'L'}\n parent = {}\n\n # Initilize the heap with the source cell\n heappush(hp, [0, count, src])\n\n # Initilze the G_score for each node to infinity\n # And G_score of source is 0\n g_score = [[float('inf')] * m for i in range(n)]\n g_score[x][y] = 0\n\n # Initilze the F_score for each node to infinity\n # And F score of source is 1\n # F_source = G_score + heuristic function\n f_score = [[float('inf')] * m for i in range(n)]\n f_score[x][y] = 1\n\n while hp:\n cur_pos = heappop(hp)[2]\n # print(cur_pos)\n xx, yy = cur_pos\n\n if cur_pos == des:\n path = ''\n\n # Calculate the path by backtracking with the parent dict\n while cur_pos != src:\n print(cur_pos)\n prev_move = parent[cur_pos]\n m = (cur_pos[0] - prev_move[0], cur_pos[1] - prev_move[1])\n path += moves[m]\n cur_pos = prev_move\n\n # Return the distance and path\n return len(path), path[::-1]\n\n for i in moves.keys():\n r = xx + i[0]\n c = yy + i[1]\n\n # If the next node inside the maze , has a way and not yet visited\n # then mark it visited and push it in the queue\n if 0 <= r < n and 0 <= c < m and maze[r][c] == way and not visited[r][c]:\n temp = g_score[xx][yy] + 1\n if temp < g_score[r][c]:\n parent[(r, c)] = (xx, yy)\n g_score[r][c] = temp\n\n # F_source = G_score + heuristic function\n f_score[r][c] = temp + heuristic_function(des, (r, c))\n\n count += 1\n heappush(hp, [f_score[r][c], count, (r, c)])\n visited[r][c] = 1\n\n return False\n\n\n# --------------------------------DRIVER CODE ---------------------------------\n\n\nif __name__ == \"__main__\":\n\n N, M = map(int, input(\"Enter the Dimension of the maze:- \").split())\n print(\"Enter the Maze: \")\n maze = []\n\n # Input the Maze\n for _ in range(N):\n maze.append([int(i) for i in input().split()])\n\n src = tuple(map(int, input(\"Enter the Source cell: \").split()))\n des = tuple(map(int, input(\"Enter the Destination cell: \").split()))\n ans = Astar(maze, src, des)\n\n # If ans is false, i.e. no way is possible, else print distance and path\n if ans is False:\n print(\"No Path exists between\", src, \"and\", des)\n else:\n dist = ans[0]\n path = ans[1]\n print(\"Disance= \", dist)\n print(\"Path: \", path)\n\n\n\"\"\"\n\nTime Compexity: O(N*M)\nSpace Complexity: O(N*M)\n\nSample Input / Output\n\nEnter the Dimension of the maze:- 5 5\nEnter the Maze:\n1 0 1 1 1\n1 0 1 0 1\n1 0 1 0 1\n1 0 0 0 1\n1 1 1 1 1\nEnter the Source cell: 0 0\nEnter the Destination cell: 4 4\nDisance= 8\nPath: DDDDRRRR\n\n\nEnter the Dimension of the maze:- 5 5\nEnter the Maze:\n1 0 1 1 1\n1 0 1 0 1\n1 0 0 0 1\n1 0 1 0 1\n1 1 1 0 1\nEnter the Source cell: 0 0\nEnter the Destination cell: 4 4\nNo Path exists between (0, 0) and (4, 4)\n\n\nEnter the Dimension of the maze:- 5 8\nEnter the Maze:\n1 0 1 1 1 1 1 1\n1 0 1 0 0 0 0 1\n1 0 1 1 1 1 0 1\n1 0 0 0 0 1 0 1\n1 1 1 1 1 1 0 1\nEnter the Source cell: 0 0\nEnter the Destination cell: 4 7\nDisance= 25\nPath: DDDDRRRRRUULLLUURRRRRDDDD\n\"\"\"\n\n"} {"doc_id": "02d159ae22fa1f111a45cb4058704bf9", "text": "\"\"\"\nDijkstra's shortest path algorithm\n-----------------------------------\n- a greedy algorithm; it finds the shortest distance from a source to all other nodes or vertices in a graph.\n\nThe worst-case running time: O(|E| + |V| log |V|), where |V| is the number of vertices and |E| is the number of edges.\n\"\"\"\n\n# Dijkstra - finding the shortest path algorithm\n#################################################\n\n# begin with a dictionary representation of the table (table enables tracking the changes in the graph)\n# Each key in the dictionary maps to a list.\n# [1st index of the list - stores the shortest distance from the source A, 2nd index - stores the previous node]\ntable = dict()\ntable = {'A': [0, None],\n 'B': [float(\"inf\"), None],\n 'C': [float(\"inf\"), None],\n 'D': [float(\"inf\"), None],\n 'E': [float(\"inf\"), None],\n 'F': [float(\"inf\"), None]}\n\n# DISTANCE: references the shortest path column's index, PREVIOUS_NODE: references the previous node column's index\nDISTANCE = 0\nPREVIOUS_NODE = 1\nINFINITY = float(\"inf\")\n\n\ndef find_shortest_path(graph, table, origin):\n visited_nodes = []\n current_node = origin\n starting_node = origin\n\n while True:\n # obtain the current node in the graph we want to investigate\n adjacent_nodes = graph[current_node]\n # find out whether all the adjacent nodes of current_node have been visited\n if set(adjacent_nodes).issubset(set(visited_nodes)):\n pass\n else:\n # returns the nodes that have not been visited\n unvisited_nodes = set(adjacent_nodes).difference(set(visited_nodes))\n\n for vertex in unvisited_nodes:\n distance_from_starting_node = get_shortest_distance(table, vertex)\n\n if distance_from_starting_node == INFINITY and current_node == starting_node:\n # get the value (distance) of the edge between vertex and current_node\n total_distance = get_distance(graph, vertex, current_node)\n else:\n # sum(distance from the starting node to current_node, distance between current_node and vertex)\n total_distance = get_shortest_distance(table, current_node) + get_distance(graph, current_node, vertex)\n\n # if total distance < the existing data in the shortest distance column in our table\n if total_distance < distance_from_starting_node:\n # update the row\n set_shortest_distance(table, vertex, total_distance)\n set_previous_node(table, vertex, current_node)\n\n visited_nodes.append(current_node)\n\n # If all nodes have been visited, exit the while loop.\n if len(visited_nodes) == len(table.keys()):\n break\n\n # fetch the next node to visit\n current_node = get_next_node(table, visited_nodes)\n return current_node\n\n\n# returns the value stored in the 0th index of the table, which\n# stores the shortest distance from the starting node up to vertex\ndef get_shortest_distance(table, vertex):\n shortest_distance = table[vertex][DISTANCE]\n return shortest_distance\n\n\n# finds the distance between any two nodes\ndef get_distance(graph, first_vertex, second_vertex):\n return graph[first_vertex][second_vertex]\n\n\ndef set_shortest_distance(table, vertex, new_distance):\n table[vertex][DISTANCE] = new_distance\n\n\n# When we update the shortest distance of a node, we update its previous node\ndef set_previous_node(table, vertex, previous_node):\n table[vertex][PREVIOUS_NODE] = previous_node\n\n\n# finds the minimum value in the shortest distance column from the starting nodes using the table.\ndef get_next_node(table, visited_nodes):\n unvisited_nodes = list(set(table.keys()).difference(set(visited_nodes)))\n # assumed to be the smallest in the shortest distance column of table\n assumed_min = table[unvisited_nodes[0]][DISTANCE]\n min_vertex = unvisited_nodes[0]\n for node in unvisited_nodes:\n # If a lesser value is found, update the min_vertex\n if table[node][DISTANCE] < assumed_min:\n assumed_min = table[node][DISTANCE]\n min_vertex = node\n # returns min_vertex as the unvisited vertex or node with the smallest shortest distance from the source.\n return min_vertex\n\n\n# The adjacency list for the diagram and table:\n# The nested dictionary holds the adjacent nodes and the distance.\ngraph = dict()\ngraph['A'] = {'B': 5, 'D': 9, 'E': 2}\ngraph['B'] = {'A': 5, 'C': 2}\ngraph['C'] = {'B': 2, 'D': 3}\ngraph['D'] = {'A': 9, 'F': 2, 'C': 3}\ngraph['E'] = {'A': 2, 'F': 3}\ngraph['F'] = {'E': 3, 'D': 2}\n\n# To print the table\nshortest_distance_table = find_shortest_path(graph, table, 'A')\nfor k in sorted(shortest_distance_table):\n print(\"{} - {}\".format(k, shortest_distance_table[k]))"} {"doc_id": "02d849c1424df72acc0fc39394309dd5", "text": "\"\"\"\nBuild a Pyramid - SOLUTION\n\"\"\"\n\n# Use a while loop to print a 5-level pyramid of stars that looks like this:\n\n\"\"\"\n *\n ***\n *****\n *******\n*********\n\"\"\"\n\nstars = 1\nrows = 5\nchars = (rows - 1) + rows\n\nwhile stars <= chars:\n if stars % 2 != 0:\n spaces = int((chars - stars) / 2)\n print(' '*spaces+'*' * stars+' '*spaces)\n stars += 1\n\nwhile stars >= 1:\n\n\n# PREVIEW!\n\n# Here's what it would look like if we defined a function called pyramid and told it to make that 5-level pyramid. \n\n# def pyramid(levels):\n# \tstars = 1\n# \trows = levels\n# \tchars = (rows - 1) + rows\n\n# \twhile stars <= chars:\n# \t if stars % 2 != 0:\n# \t spaces = int((chars - stars) / 2)\n# \t print(' '*spaces+'*' * stars+' '*spaces)\n# \t stars += 1\n\n# pyramid(5)"} {"doc_id": "02e8e432e3a68af2de5db0bd4b97c9a3", "text": "# Directions: The goal of this exercise is to create\n# a game where the user has to guess a certain password that\n# you set and see how many tries it takes for that user to guess correctly\n\n# start with assigning the password to some variable\npas = \"password\"\n\n# set an input so it will appear in the console and ask the user\nguess = input(\"Enter the password:\")\n\n# set a counter to count the number of guesses\ncounter = 1\n\n# set a while loop to check if the user guess correctly and count the number of guesses\nwhile guess != pas:\n guess = input(\"Incorrect Password. Try Again:\")\n counter += 1\n\n# print the results\nprint(f\"Nice Job. Unlocked. It took you {str(counter)} tries\")\n"} {"doc_id": "030c82f114c84faf3c4097e3cac5febd", "text": "# this is a commend\nprint(\"This is my first code line in python 3\")\n\n#types in python\nmy_data = [1.2, 1.3, 1.4, 1.5, 1.6]\n\nfor i in my_data:\n print(i)\n\nprint(\"This is a string\")\n# castings\nx = 24\ny = float(x)\nprint(y)\n\nprint(type(True))\n\nis_checked = True\nis_c_int = int(is_checked)\nprint(is_c_int)\n\n# expressions and variables\narithmetic = 34+54+34+34 * 5.0\nprint(arithmetic)\n\nprint(\"Float division: \")\nprint(25/6)\n\nprint(\"Integer division: \")\nprint(25//6)\n\n# order operation\nprint((2 * 60) + 30)\n\nx = 25\nprint(x)\n\nx = x/5\nprint(x)\n\n# strings\n\nname = \"Michael Jackson\"\n\nprint(name)\nprint(name[1])\n\n# getting last element in name\nprint(name[-1])\nprint(name[-2]+ \"\\n\")\n\n# lets do something using string\nsome_name = \"Eduardo Rasgado Ruiz\"\n\nfor i in range(len(some_name)):\n # printing some-name in a reverse way\n print(some_name[len(some_name)-i-1])\n\nprint(\"-----------------\\n\")\n\nfor i in range(len(some_name)):\n reverse_num = -len(some_name) + i\n print(some_name[reverse_num])\n #print(reverse_num)\n\n\n# getting just a range from string: slicing\n\n#getting first place in which space is\nspace = 0\nfor i in range(len(some_name)):\n if some_name[i] == \" \":\n space = i\n break\nprint(\"space is {}\".format(space))\nprint(some_name[0:7])\n\n# STRIDE: slicing with a range\n# printing each 2 letters\nprint(some_name[::2])\n\n#printing each 2 lette until get the 7th element in the string\nprint(some_name[:7:2])\n\nsomename_3 = some_name*3\nprint(somename_3)\n\n# strings in python are inmutable\n# this is permitted\nsome_name = \"ssssss\"\nprint(some_name)\n\n#this is not\n#some_name[3] = \"s\"\n\n# Escape sequences\n\nprint(\"Mozart is \\tthe best\")\nprint(\"Mozart is \\n the best\")\nprint(\"Mozart is \\\\the best\")\nprint(r\"Mozart is the best\")\n\n# STRING METHODS =======================\nprint(\"--------------------------------\")\n#Sequence methods and string methods\n\na_good_phrase = \"Thriller us the sxth studio album\"\n\n# split method\nprint(\"Split: \")\nphrase_list = a_good_phrase.split(\" \")\nfor i in phrase_list:\n print(i)\n\n# join method\nprint(\"Join: \")\nphrase_string_again = \" \".join(phrase_list)\nprint(phrase_string_again)\n\n# upper method\nprint(\"Upper: \")\nupper_phrase = a_good_phrase.upper()\nprint(upper_phrase)\n\nprint(\"LOwer: \")\nlower_phrase = upper_phrase.lower()\nprint(lower_phrase)\n\n#replace\nprint(\"Replace method: \")\n# to be replace, new value to be assigned\nreplaced_phrase = a_good_phrase.replace(\" \", \"-\")\nprint(replaced_phrase)\n\nname = \"Eduardo Rasgado\"\n\n#find\nprint(\"Find: \")\nfound_e = name.find(\"as\")\n\nprint(found_e)\n\nif found_e != -1:\n print(name[found_e:11])\nelse:\n print(\"NOT FOUND\")"} {"doc_id": "0316492a1aac9f295f2f7875d5114349", "text": "import math\r\nimport cmath\r\nimport datetime\r\nfrom math import sqrt\r\nimport random\r\n\r\n#For Loops Challenge 11: Binary Hexadecimal Converter App\r\nprint(\"Welcome to the Binary/Hexadecimal Converter App\")\r\n\r\nvalue = int(input(\"\\nCompute binary and hexadecimal values up to the following decimal number: \"))\r\nprint(\"Gererating lists... complete!\")\r\ndecimal_values = list(range(1, value))\r\nbinary_values = []\r\nhexadecimal_values = []\r\nfor i,y in zip(decimal_values,decimal_values):\r\n binary_values.append(bin(i))\r\n hexadecimal_values.append(hex(y))\r\nprint(\"\\nUsing slices, we will now show you a portion of each list.\")\r\ndec_num1 = int(input(\"What decimal number would you like to start at: \"))\r\ndec_num2 = int(input(\"What decimal number would you like to stop at: \"))\r\n\r\n\r\nprint(\"\\nDecimal values from \" + str(dec_num1) + \" to \" + str(dec_num2)+\":\")\r\nfor x in decimal_values[(dec_num1-1):dec_num2]:\r\n print(x)\r\n\r\nprint(\"\\nBinary values from \"+str(dec_num1) +\" to \" +str(dec_num2)+\": \")\r\nfor x in binary_values[(dec_num1-1):dec_num2]:\r\n print(x)\r\n\r\nprint(\"\\nHexadecimal values from \"+str(dec_num1)+\" to \"+str(dec_num2)+\":\")\r\nfor x in hexadecimal_values[(dec_num1-1):dec_num2]:\r\n print(x)\r\n\r\ninput(\"Press Enter to see all values from 1 to 12\")\r\nprint(\"Decimal----Binary----Hexadecimal\")\r\nprint(\"---------------------------------\")\r\nfor a,b,c in zip(decimal_values,binary_values,hexadecimal_values):\r\n print(str(a)+\"----\"+str(b)+\"----\"+str(c))\r\n"} {"doc_id": "0323e7ebd7dce2f3495b59530db82cf6", "text": "'''\r\nWant to give it a go yourself? Be my guest! Modify the first_and_last function so that it returns True if the first letter of\r\nthe string is the same as the last letter of the string, False if they\u2019re different. Remember that you can access characters\r\nusing message[0] or message[-1]. Be careful how you handle the empty string, which should return True since nothing is equal\r\nto nothing.\r\n'''\r\n\r\ndef first_and_last(message):\r\n if len(message) == 0:\r\n return True\r\n elif message[0] == message[-1]:\r\n return True\r\n else:\r\n return False\r\n\r\nprint(first_and_last(\"else\"))\r\nprint(first_and_last(\"tree\"))\r\nprint(first_and_last(\"\"))\r\n\r\nprint(\"-------------------------\")\r\nword = \"supercalifragilisticexpialidocious\"\r\nprint(word.index('x'))\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n"} {"doc_id": "03415be96f8fe35610bac8a611807b76", "text": "\"\"\"\nFile: quadratic_solver.py\nName: Fenny\n-----------------------\nThis program should implement a console program\nthat asks 3 inputs (a, b, and c)\nfrom users to compute the roots of equation\nax^2 + bx + c = 0\nOutput format should match what is shown in the sample\nrun in the Assignment 2 Handout.\n\n\"\"\"\n\nimport math\n\n\ndef main():\n\t\"\"\"\n\tThe program will calculate Quadratic Equation\n\tand tell the user how many roots are there\n\t\"\"\"\n\tprint('stanCode Quadratic Solver!')\n\ta = int(input('Enter a: '))\n\tb = int(input('Enter b: '))\n\tc = int(input('Enter c: '))\n\tdiscriminant = calculate(a, b, c)\n\n\tif discriminant < 0:\n\t\tprint('No real roots')\n\telif discriminant == 0:\n\t\tequal = -b / (2*a)\n\t\tprint('One root: '+str(equal))\n\telse:\n\t\troot = math.sqrt(discriminant)\n\t\tbigger1 = (-b+root) / (2*a)\n\t\tbigger2 = (-b-root) / (2*a)\n\t\tprint('Two roots: ' + str(bigger1) + ' , ' + str(bigger2))\n\n\ndef calculate(a,b,c):\n\t\"\"\"\n\t:param a: the first number to be input\n\t:param b: the second number to be input\n\t:param c: the third number to be input\n\t:return: the result of the formula\n\t\"\"\"\n\tdiscriminant = b*b-4*a*c\n\treturn discriminant\n\n\n\n###### DO NOT EDIT CODE BELOW THIS LINE ######\n\nif __name__ == \"__main__\":\n\tmain()\n"} {"doc_id": "03ca0393208f2a61ebd4cda41388f755", "text": "num = int(input())\nwhile num != -1:\n print('\u041a\u0432\u0430\u0434\u0440\u0430\u0442 \u0432\u0430\u0448\u0435\u0433\u043e \u0447\u0438\u0441\u043b\u0430 \u0440\u0430\u0432\u0435\u043d:', num * num)\n num = int(input())\n\nprint(\"@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\")\n\n# \u0438\u0441\u043f\u043e\u043b\u044c\u0437\u0443\u0435\u043c for\nfor i in range(101):\n print(i)\n\nprint(\"@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\")\n\n# \u0438\u0441\u043f\u043e\u043b\u044c\u0437\u0443\u0435\u043c while\ni = 0\nwhile i < 101:\n print(i)\n i += 1\n\nprint(\"@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\")\n\n# \u041d\u0430\u043f\u0438\u0448\u0435\u043c \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0443 \u0432\u044b\u0432\u043e\u0434\u044f\u0449\u0443\u044e \u0432\u0441\u0435 \u0447\u0438\u0441\u043b\u0430 \u043a\u0440\u0430\u0442\u043d\u044b\u0435 3 \u0438\u0441\u043f\u043e\u043b\u044c\u0437\u0443\u044f \u0446\u0438\u043a\u043b for \u0438 while:\n# \u0438\u0441\u043f\u043e\u043b\u044c\u0437\u0443\u0435\u043c for\nfor i in range(0, 100, 3):\n print(i)\n\nprint(\"@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\")\n\n# \u0438\u0441\u043f\u043e\u043b\u044c\u0437\u0443\u0435\u043c while\ni = 0\nwhile i < 100:\n print(i)\n i += 3\n\nprint(\"@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\")\n# \u0421\u0447\u0438\u0442\u044b\u0432\u0430\u043d\u0438\u0435 \u0434\u0430\u043d\u043d\u044b\u0445 \u0434\u043e \u0441\u0442\u043e\u043f \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u044f\n\ntext = input(\"\u043d\u0430\u0447\u0438\u043d\u0430\u0439 \u0432\u0432\u043e\u0434\u0438\u0442\u044c \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u044f, \u043a\u0430\u043a \u0437\u0430\u043a\u043e\u043d\u0447\u0438\u0448\u044c, \u043d\u0430\u0431\u0435\u0440\u0438 [stop]: \")\ntotal = 0\nwhile text != 'stop':\n num = int(text)\n total += num\n text = input()\nprint('\u0421\u0443\u043c\u043c\u0430 \u0447\u0438\u0441\u0435\u043b \u0440\u0430\u0432\u043d\u0430', total)\n\n"} {"doc_id": "041f2b95572696e5c07877f212559a8b", "text": "class Note:\n \"\"\"A class representing a musical note.\n\n The `Note` class consists of notation A-G with optional unicode accidental symbols \\u266d, \\u266f, \\U0001D12B, or \\U0001D12A. It is created by the `NoteEditor`. When printed, only the `value` of the `Note` is displayed.\n\n Parameters\n ----------\n letter : str\n The letter part of the `Note`'s notation. Consists of A-G.\n symbol : str\n The accidental part of the `Note`'s notation. Consists of the unicode characters \\u266d, \\u266f, \\U0001D12B, or \\U0001D12A. If there are no accidentals, it is an empty string.\n\n Attributes\n ----------\n letter : str\n The letter part of the `Note`'s notation.\n symbol : str\n The accidental part of the `Note`'s notation.\n\n \"\"\"\n\n _flat = '\\u266d'\n _sharp = '\\u266f'\n _doubleflat = '\\U0001D12B'\n _doublesharp = '\\U0001D12A'\n _symbols = {\n -1: _flat, -2: _doubleflat,\n +1: _sharp, +2: _doublesharp,\n 0: '',\n }\n _symbol_signs = {\n _flat: -1, _doubleflat: -2,\n _sharp: 1, _doublesharp: 2,\n '': 0,\n }\n _note_values = { # Basis: C = 0\n 'C': 0,\n 'D': 2,\n 'E': 4,\n 'F': 5,\n 'G': 7,\n 'A': 9,\n 'B': 11,\n }\n _notes_tuple = (\n 'C', 'D', 'E', 'F', 'G', 'A', 'B',\n 'C', 'D', 'E', 'F', 'G', 'A', 'B',\n )\n _sharp_tuple = (\n ('C', ''), ('C', '\\u266f'), ('D', ''), ('D', '\\u266f'), ('E', ''),\n ('F', ''), ('F', '\\u266f'), ('G', ''), ('G', '\\u266f'), ('A', ''),\n ('A', '\\u266f'), ('B', ''),\n )\n _flat_tuple = (\n ('C', ''), ('D', '\\u266d'), ('D', ''), ('E', '\\u266d'), ('E', ''),\n ('F', ''), ('G', '\\u266d'), ('G', ''), ('A', '\\u266d'), ('A', ''),\n ('B', '\\u266d'), ('B', ''),\n )\n\n def __init__(self, letter, symbol):\n self.letter = letter\n self.symbol = symbol\n\n @property\n def value(self):\n \"\"\"str: The full notation of the `Note`.\"\"\"\n return self.letter + self.symbol\n\n def num_value(self):\n \"\"\"Return the `Note`'s numerical value (basis: C = 0).\n\n The numerical value is based on the number of semitones above C.\n\n Returns\n -------\n int\n The numerical value.\n\n Examples\n --------\n >>> NE = NoteEditor()\n >>> d = NE.create_note(\"D\")\n >>> d.num_value()\n 2\n\n \"\"\"\n num = (self.letter_value() + self.symbol_value()) % 12\n return num\n\n def letter_value(self):\n \"\"\"Return the `Note`'s letter as an integer value (basis: C = 0).\n\n The value is based on the number of scale degrees above C.\n\n Returns\n -------\n int\n The letter's value.\n\n Examples\n --------\n >>> NE = NoteEditor()\n >>> d = NE.create_note(\"D\")\n >>> d.letter_value()\n 1\n\n \"\"\"\n return Note._note_values[self.letter]\n\n def symbol_value(self):\n \"\"\"Return the `Note`'s symbol as an integer value (basis: natural = 0).\n\n The value is based on the number of semitones away from the natural `Note`.\n\n Returns\n -------\n int\n The symbol's value.\n\n Examples\n --------\n >>> NE = NoteEditor()\n >>> d_sharp = NE.create_note(\"D#\")\n >>> d_sharp.symbol_value()\n 1\n\n \"\"\"\n return Note._symbol_signs[self.symbol]\n\n def accidental(self, value):\n \"\"\"Change a `Note`'s accidental by specifying a `value` from -2 to 2.\n\n The range of `values` [-2, 2] correspond to the values a symbol can take, from doubleflat (-2) to doublesharp (2).\n\n Parameters\n ----------\n value : int\n The accidental's integer value.\n\n Raises\n ------\n ValueError\n If `value` is not in the range of [-2, 2].\n\n Examples\n --------\n >>> NE = NoteEditor()\n >>> d_sharp = NE.create_note(\"D#\")\n >>> d_sharp.accidental(-1)\n D\\u266d note\n\n \"\"\"\n if value not in range(-2, 3):\n raise ValueError(\n \"Only integers between -2 and 2 are accepted\"\n )\n self.symbol = Note._symbols[value]\n return self\n\n def shift_s(self, value):\n \"\"\"Shift a `Note`'s accidental.\n\n The `Note`'s `symbol_value()` must be in the range of [-2, 2] after the shift, which corresponds to the values a symbol can take from doubleflat (-2) to doublesharp (2).\n\n Parameters\n ----------\n value : int\n The value of the shift in accidentals.\n\n Raises\n ------\n ValueError\n If the `Note`'s `symbol_value()` is not in the range of [-2, 2] after the shift.\n\n Examples\n --------\n >>> NE = NoteEditor()\n >>> d_sharp = NE.create_note(\"D#\")\n >>> d_sharp.shift_s(-1)\n D note\n\n \"\"\"\n value += self.symbol_value()\n if value not in range(-2, 3):\n raise ValueError(\n \"Only symbols up to doublesharps and doubleflats are accepted\"\n )\n self.symbol = Note._symbols[value]\n return self\n\n def shift_l(self, value):\n \"\"\"Shift a `Note`'s letter.\n\n The `value` corresponds to the change in scale degree of the `Note`.\n\n Parameters\n ----------\n value : int\n The value of the letter shift.\n\n Examples\n --------\n >>> NE = NoteEditor()\n >>> d_sharp = NE.create_note(\"D#\")\n >>> d_sharp.shift_l(3)\n G\\u266f note\n\n \"\"\"\n pos = (Note._notes_tuple.index(self.letter) + value) % 7\n new_letter = Note._notes_tuple[pos]\n self.letter = new_letter\n return self\n\n def transpose(self, semitones, letters):\n \"\"\"Transpose a `Note` according to semitone and letter intervals.\n\n Parameters\n ----------\n semitones\n The difference in semitones to the new transposed `Note`.\n letters\n The difference in scale degrees to the new transposed `Note`.\n\n Examples\n --------\n >>> NE = NoteEditor()\n >>> c = NE.create_note(\"C\")\n >>> c.transpose(6, 3)\n F\\u266f note\n >>> c.transpose(0, 1)\n G\\u266d note\n\n \"\"\"\n new_val = (self.num_value() + semitones) % 12\n self.shift_l(letters)\n curr_val = self.num_value()\n shift = (new_val - curr_val) % 12\n shift = shift - 12 if shift > 6 else shift # shift downwards if closer\n self.shift_s(shift)\n return self\n\n def transpose_simple(self, semitones, use_flats=False):\n \"\"\"Transpose a `Note` according to semitone intervals.\n\n Parameters\n ----------\n semitones : int\n The difference in semitones to the new transposed `Note`.\n use_flats : boolean, Optional\n Selector to use flats or sharps for black keys. Default False when optional.\n\n Examples\n --------\n >>> NE = NoteEditor()\n >>> c = NE.create_note(\"C\")\n >>> c.transpose_simple(6)\n F\\u266f note\n >>> c.transpose(2, use_flats=True)\n A\\u266d note\n\n \"\"\"\n if use_flats:\n note_list = Note._flat_tuple\n else:\n note_list = Note._sharp_tuple\n self.letter, self.symbol = note_list[\n (self.num_value() + semitones) % 12\n ]\n return self\n\n def __repr__(self):\n return self.value + \" note\"\n\n def __str__(self):\n return self.value\n\n def __eq__(self, other):\n \"\"\"Compare between other `Notes` and strings.\n\n Checks if the other `Note`'s value or the string is the same as this `Note`.\n\n Parameters\n ----------\n other\n The object to be compared with.\n\n Returns\n -------\n boolean\n The outcome of the `value` comparison.\n\n Examples\n --------\n >>> NE = NoteEditor()\n >>> d = NE.create_note(\"D\")\n >>> d2 = NE.create_note(\"D\")\n >>> d_str = \"D\"\n >>> d == d2\n True\n >>> d == d_str\n True\n\n Note that symbols are converted to their unicode characters when a `Note` is created.\n\n >>> NE = NoteEditor()\n >>> ds = NE.create_note(\"D#\")\n >>> ds_str = \"D#\"\n >>> ds_str_2 = \"D\\u266f\"\n >>> ds == ds_str\n False\n >>> ds == ds_str_2\n True\n\n \"\"\"\n if isinstance(other, Note):\n return self.value == other.value\n elif isinstance(other, str):\n return self.value == other\n else:\n return NotImplemented\n"} {"doc_id": "043374f69f177a38612020f9b502221c", "text": "\"\"\"\nFile: hailstone.py\nName: Rita Tang\n-----------------------\nThis program should implement a console program that simulates\nthe execution of the Hailstone sequence, defined by Douglas\nHofstadter. Output format should match what is shown in the sample\nrun in the Assignment 2 Handout.\n\"\"\"\n\n\ndef main():\n \"\"\"\n This program computes Hailstone sequences and count the steps it takes\n \"\"\"\n print('This program computes Hailstone sequences.')\n print('\\n')\n number = int(input('Enter a number: '))\n # to count steps\n steps = 0\n if number == 1:\n print('It took 0 steps to reach 1.')\n else:\n while True:\n if number == 1:\n break\n elif (number % 2) == 0:\n print(str(number)+' is even, so I take half: '+str(int(number/2)))\n number = int(number/2)\n steps += 1\n elif (number % 2) != 0:\n print(str(number)+' is odd, so I make 3n+1: '+str(int(number*3+1)))\n number = int(number*3+1)\n steps += 1\n print('It took '+str(steps)+' steps to reach 1.')\n\n\n\n###### DO NOT EDIT CODE BELOW THIS LINE ######\n\nif __name__ == \"__main__\":\n main()\n"} {"doc_id": "045be33fbc2a0d6a5d761d33b1cae950", "text": "\"\"\"\n

Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.

\n\n

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).”

\n\n

Given the following binary tree:  root = [3,5,1,6,2,0,8,null,null,7,4]

\n\n
\n        _______3______\n       /              \\\n    ___5__          ___1__\n   /      \\        /      \\\n   6      _2       0       8\n         /  \\\n         7   4\n
\n\n

Example 1:

\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 5 and 1 is 3.\n
\n\n

Example 2:

\n\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 5 and 4 is 5, since a node can be a descendant of itself\n             according to the LCA definition.
\n\n

Note:

\n\n\n

\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

\n\n

\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”

\n\n

\u4f8b\u5982\uff0c\u7ed9\u5b9a\u5982\u4e0b\u4e8c\u53c9\u6811:  root = [3,5,1,6,2,0,8,null,null,7,4]

\n\n
        _______3______\n       /              \\\n    ___5__          ___1__\n   /      \\        /      \\\n   6      _2       0       8\n         /  \\\n         7   4\n
\n\n

\u793a\u4f8b 1:

\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 5 \u548c\u8282\u70b9 1 \u7684\u6700\u8fd1\u516c\u5171\u7956\u5148\u662f\u8282\u70b9 3\u3002\n
\n\n

\u793a\u4f8b 2:

\n\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 5 \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\n

\u8bf4\u660e:

\n\n\n

\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

\n\n

\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”

\n\n

\u4f8b\u5982\uff0c\u7ed9\u5b9a\u5982\u4e0b\u4e8c\u53c9\u6811:  root = [3,5,1,6,2,0,8,null,null,7,4]

\n\n
        _______3______\n       /              \\\n    ___5__          ___1__\n   /      \\        /      \\\n   6      _2       0       8\n         /  \\\n         7   4\n
\n\n

\u793a\u4f8b 1:

\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 5 \u548c\u8282\u70b9 1 \u7684\u6700\u8fd1\u516c\u5171\u7956\u5148\u662f\u8282\u70b9 3\u3002\n
\n\n

\u793a\u4f8b 2:

\n\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 5 \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\n

\u8bf4\u660e:

\n\n\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

\nInitially on a notepad only one character 'A' is present. You can perform two operations on this notepad for each step: \n

    \n
  1. Copy All: You can copy all the characters present on the notepad (partial copy is not allowed).
  2. \n
  3. Paste: You can paste the characters which are copied last time.
  4. \n
\n

\n\n

\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

\n\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
  1. The n will be in the range [1, 1000].
  2. \n
\n

\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\n
    \n\t
  1. Copy 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)\u3002
  2. \n\t
  3. Paste (\u7c98\u8d34) : \u4f60\u53ef\u4ee5\u7c98\u8d34\u4f60\u4e0a\u4e00\u6b21\u590d\u5236\u7684\u5b57\u7b26\u3002
  4. \n
\n\n

\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

\n\n

\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\n
    \n\t
  1. n \u7684\u53d6\u503c\u8303\u56f4\u662f [1, 1000] \u3002
  2. \n
\n

\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\n
    \n\t
  1. Copy 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)\u3002
  2. \n\t
  3. Paste (\u7c98\u8d34) : \u4f60\u53ef\u4ee5\u7c98\u8d34\u4f60\u4e0a\u4e00\u6b21\u590d\u5236\u7684\u5b57\u7b26\u3002
  4. \n
\n\n

\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

\n\n

\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\n
    \n\t
  1. n \u7684\u53d6\u503c\u8303\u56f4\u662f [1, 1000] \u3002
  2. \n
\n\"\"\"\n\n\nclass Solution(object):\n def minSteps(self, n):\n \"\"\"\n :type n: int\n :rtype: int\n \"\"\"\n "} {"doc_id": "04fb837c342fd13535bf5b59872156d7", "text": "\"\"\"\n

\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

\n\n

\nSuppose n lights are labeled as number [1, 2, 3 ..., n], function of these 4 buttons are given below:\n\n

    \n
  1. Flip all the lights.
  2. \n
  3. Flip lights with even numbers.
  4. \n
  5. Flip lights with odd numbers.
  6. \n
  7. Flip lights with (3k + 1) numbers, k = 0, 1, 2, ...
  8. \n
\n

\n\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

\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

\n\n

\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

\n\n
    \n\t
  1. \u5c06\u6240\u6709\u706f\u6ce1\u7684\u72b6\u6001\u53cd\u8f6c\uff08\u5373\u5f00\u53d8\u4e3a\u5173\uff0c\u5173\u53d8\u4e3a\u5f00\uff09
  2. \n\t
  3. \u5c06\u7f16\u53f7\u4e3a\u5076\u6570\u7684\u706f\u6ce1\u7684\u72b6\u6001\u53cd\u8f6c
  4. \n\t
  5. \u5c06\u7f16\u53f7\u4e3a\u5947\u6570\u7684\u706f\u6ce1\u7684\u72b6\u6001\u53cd\u8f6c
  6. \n\t
  7. \u5c06\u7f16\u53f7\u4e3a 3k+1 \u7684\u706f\u6ce1\u7684\u72b6\u6001\u53cd\u8f6c\uff08k = 0, 1, 2, ...)
  8. \n
\n\n

\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].

\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

\n\n

\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

\n\n
    \n\t
  1. \u5c06\u6240\u6709\u706f\u6ce1\u7684\u72b6\u6001\u53cd\u8f6c\uff08\u5373\u5f00\u53d8\u4e3a\u5173\uff0c\u5173\u53d8\u4e3a\u5f00\uff09
  2. \n\t
  3. \u5c06\u7f16\u53f7\u4e3a\u5076\u6570\u7684\u706f\u6ce1\u7684\u72b6\u6001\u53cd\u8f6c
  4. \n\t
  5. \u5c06\u7f16\u53f7\u4e3a\u5947\u6570\u7684\u706f\u6ce1\u7684\u72b6\u6001\u53cd\u8f6c
  6. \n\t
  7. \u5c06\u7f16\u53f7\u4e3a 3k+1 \u7684\u706f\u6ce1\u7684\u72b6\u6001\u53cd\u8f6c\uff08k = 0, 1, 2, ...)
  8. \n
\n\n

\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].

\n\"\"\"\n\n\nclass Solution(object):\n def flipLights(self, n, m):\n \"\"\"\n :type n: int\n :type m: int\n :rtype: int\n \"\"\"\n "} {"doc_id": "05055954eb1d8f05951b0182552dd264", "text": "# Question 3 - Implement function to check password validity\r\n# Asmit De\r\n# 04/28/2017\r\n\r\n\r\n## Function definition for isValid ----##\r\n# Parameters: password (string)\r\n# Return: True or False (Boolean) - True if password is valid, False otherwise\r\n#\r\ndef isValid(password):\r\n \r\n # If length of password is less than 7,\r\n # password is invalid - return false. Function terminates\r\n if len(password) < 7:\r\n return False\r\n\r\n # Initialize two counters for uppercase letters and digits\r\n count_uc = 0\r\n count_dig = 0\r\n\r\n # Run loop through the characters in the password\r\n for ch in password:\r\n\r\n # If character is uppercase, increase count_uc\r\n if 'A' <= ch <= 'Z':\r\n count_uc += 1\r\n\r\n # else if character is digit, increase count_dig\r\n elif '0' <= ch <= '9':\r\n count_dig += 1\r\n\r\n # else if the character is not lowercase (meaning,\r\n # it must be a special character). Password is invalid - return false\r\n elif not('a' <= ch <= 'z'):\r\n return False\r\n\r\n # If we reach this point, it means that we have only found upper/lowercase letters or digits.\r\n # Check if there are at least one uppercase letter and one digit. If so, all our checks have\r\n # passed - return True, else return False\r\n if count_uc > 0 and count_dig > 0:\r\n return True\r\n else:\r\n return False\r\n\r\n##---- Function definition ends ##\r\n\r\n\r\n## Main program code ##\r\n\r\n# Enter password from the user\r\npwd = input('Enter password: ')\r\n\r\n# Call the isValid function with pwd as argument\r\n# and check the returned value for validity of password.\r\n# Print accordingly.\r\nif isValid(pwd):\r\n print('The password is valid')\r\nelse:\r\n print('The password is invalid')\r\n"} {"doc_id": "053066d8d29e4aab62b8890d20b05724", "text": "#Programmet finnre ut om personene t\u00e5ler maten.\n#Programmet er ogs\u00e5 dynamisk slik at man kan legge til nye matretter og nye personer med allergier.\n\n#Starter med \u00e5 opprette to ordb\u00f8ker, en for hver av personene som har allergier, og hvilke allergier de har.\nallergier = {\"Anne\": \"gluten\", \"Ola\": \"melk\", \"Kari\": \"laktose\"}\n\n#Denne ordboken inneholder m\u00e5ltidene, og det dem inneholder som allergikere kan reagere p\u00e5.\nmat = {\"br\u00f8d\": {\"gluten\"}, \"gr\u00f8t\": {\"melk\"}, \"pannekaker\": {\"gluten\", \"melk\"}}\n\n#Bruker en for-l\u00f8kke for \u00e5 traversjere gjennom alle matrettene i ordboken.\nfor x in mat:\n print(\"----------------------\")\n print(\"Det er\", x, \"til mat. \")\n\n #For hver matrett kj\u00f8rer denne for-l\u00f8kken. Denne for-l\u00f8kken tester om noen av personene ikke t\u00e5ler matrett x.\n for i in allergier:\n if allergier[i] in mat[x]:\n print(i,\"kan ikke spise\", x, \". Personen t\u00e5ler ikke\", allergier[i], \".\")\n"} {"doc_id": "05ad8e445043e1de7135fe8421f69448", "text": "\"\"\"\nFile: quadratic_solver.py\nName: Wilson Wang\n-----------------------\nThis program should implement a console program\nthat asks 3 inputs (a, b, and c)\nfrom users to compute the roots of equation\nax^2 + bx + c = 0\nOutput format should match what is shown in the sample\nrun in the Assignment 2 Handout.\n\n\"\"\"\n\nimport math\n\n\ndef main():\n\t\"\"\"\n\tThis program should implement a console program\n\tthat asks 3 inputs (a, b, and c)\n\tfrom users to compute the roots of equation\n\tax^2 + bx + c = 0\n\tOutput format should match with 3 conditions, which have different number of root .\n\t\"\"\"\n\tprint('stanCode Quadratic Solver')\n\ta = int(input('Enter a:'))\n\tb = int(input('Enter b:'))\n\tc = int(input('Enter c:'))\n\n\tif b*b - 4*a*c > 0:\n\t\t# This equation should compute the roots of ax^2 + bx + c = 0\n\t\td = math.sqrt(b ** 2 - 4 * a * c)\n\t\t# answer1 and answer3 are for the condition of 2 roots (d>0)\n\t\tanswer1 = (-b + d) / (2 * a)\n\t\tanswer3 = (-b - d) / (2 * a)\n\t\t# this code should show two roots when d > 0\n\t\tprint('two roots: '+str(answer1)+' , '+str(answer3))\n\telif b*b - 4*a*c == 0:\n\t\t# answer2 is for the condition of 1 root(d=0)\n\t\tanswer2 = -b / (2 * a)\n\t\t# this code should show one roots when d = 0\n\t\tprint('one roots: '+str(answer2))\n\telse:\n\t\t# this condition shoe when d < 0\n\t\tprint('no real roots')\n\n\n\n###### DO NOT EDIT CODE BELOW THIS LINE ######\n\nif __name__ == \"__main__\":\n\tmain()\n"} {"doc_id": "05b2b5b1c4e6e5f4b38bf194438dd901", "text": "def cipher(text, shift, encrypt=True):\n \"\"\"Cipher function to encrypt and decrypt a string .\n\n Parameters\n ----------\n text: str\n A string variable that is a text.\n shift: int\n The number of postions we would like to shift along the alphabet string.\n encrypt: bool\n Whether to encrypt or decrypt the string text.\n\n Returns\n -------\n str\n The new text string after being enctypted or decrypted.\n\n Examples\n --------\n >>> cipher('data',1)\n 'ebub'\n\n \"\"\"\n\n alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'\n new_text = ''\n for c in text:\n index = alphabet.find(c)\n if index == -1:\n new_text += c\n else:\n new_index = index + shift if encrypt == True else index - shift\n new_index %= len(alphabet)\n new_text += alphabet[new_index:new_index+1]\n return new_text\n"} {"doc_id": "05be9bc368204d55a84eec20aff429e4", "text": "from collections import deque\n\n\nclass TabuList(object):\n \"\"\"Implements a tabu list for use with TabuSearch.\n\n When using big items, it would be wise to save space by hashing them.\n\n Parameters\n ----------\n length : int\n The maximal amount of items in the tabu list.\n\n Attributes\n ----------\n _list : deque\n A list that contains hashes of all the items that are considered part\n of the tabu list.\n\n Examples\n --------\n A simple example, the lists are converted to tuples, because they're\n mutable objects and thus can't be hashed with the default implementation of\n hash:\n\n .. doctest::\n\n >>> from lclpy.localsearch.tabusearch.tabu_list import TabuList\n >>> test = TabuList(3)\n >>> test.add(tuple([0, 1, 2]))\n >>> test.add(tuple([1, 0, 2]))\n >>> test.add(tuple([0, 2, 1]))\n >>> test.add(tuple([2, 1, 0]))\n >>> test.contains(tuple([0, 1, 2]))\n False\n >>> test.contains(tuple([1, 0, 2]))\n True\n >>> test.contains(tuple([0, 2, 1]))\n True\n >>> test.contains(tuple([2, 1, 0]))\n True\n\n \"\"\"\n\n def __init__(self, length):\n super().__init__()\n self._list = deque(maxlen=length)\n\n def add(self, item):\n \"\"\"Adds an item to the tabu list.\n\n Parameters\n ----------\n item\n A hashable, immutable object.\n\n \"\"\"\n\n self._list.append(item)\n\n def contains(self, item):\n \"\"\"A method that checks if an item is in the tabu list.\n\n Parameters\n ----------\n item\n A hashable, immutable object.\n\n Returns\n -------\n bool\n Will return true if the item is in the tabu list, false if it\n isn't in the tabu list.\n\n \"\"\"\n return item in self._list\n"} {"doc_id": "05c243b96fca4e49517525fe46bfb6cc", "text": "import heapq\n\n# \u67e5\u627e\u65b9\u6848\n# \u96c6\u5408\u4e2d\u67e5\u627e\u6700\u5c0f\u7684\u6216\u8005\u6700\u5927\u7684N\u4e2a\u5143\u7d20\nnums = [1, 7, 8, 5, 34, 35, 75, 1, 45, 23, 454, 12, 9, 43]\n\n# 1\n# \u5982\u679c\u67e5\u627e\u7684N>1\u4f46\u53c8\u4e0d\u4f1a\u592a\u5927\u65f6\uff0c\u4f7f\u7528\u51fd\u6570 nlargest() \u548c nsmallest() \u662f\u5f88\u5408\u9002\u7684\nprint(heapq.nlargest(3, nums))\nprint(heapq.nsmallest(3, nums))\n\nportfolio = [\n {'name': 'IBM', 'shares': 100, 'price': 91.1},\n {'name': 'AAPL', 'shares': 50, 'price': 543.22},\n {'name': 'FB', 'shares': 200, 'price': 21.09},\n {'name': 'HPQ', 'shares': 35, 'price': 31.75},\n {'name': 'YHOO', 'shares': 45, 'price': 16.35},\n {'name': 'ACME', 'shares': 75, 'price': 115.65}\n]\n\ncheap = heapq.nsmallest(3, portfolio, key=lambda s: s['price'])\nexpensive = heapq.nlargest(3, portfolio, key=lambda s: s['price'])\nprint(cheap)\nprint(expensive)\n\n# 2\n# \u5982\u679cN=1\u65f6\uff0cmin\u548cmax\u5408\u9002\nprint('--------2--------')\nprint(min(nums))\nprint(max(nums))\n\n# 3\n# \u5982\u679c N \u7684\u5927\u5c0f\u548c\u96c6\u5408\u5927\u5c0f\u63a5\u8fd1\u7684\u65f6\u5019\uff0c\u901a\u5e38\u5148\u6392\u5e8f\u8fd9\u4e2a\u96c6\u5408\u7136\u540e\u518d\u4f7f\u7528\u5207\u7247\u64cd\u4f5c\u4f1a\u66f4\u5feb\u70b9\nprint('-------3---------')\nprint(sorted(nums)[:6])\nprint(sorted(nums)[-6:])\n\n# 4\n# \u53e6\u4e00\u79cd\u6392\u5e8f\nprint('--------4--------')\nheap = list(nums)\n# \u5c06\u6570\u636e\u6392\u5e8f\u7136\u540e\u653e\u8fdb\u4e00\u4e2a\u5217\u8868\u4e2d\nheapq.heapify(heap)\nprint(heap)\nprint(type(heap))\n\n# \u63d0\u53d6\u6700\u5c0f\u7684\u5143\u7d20,\u64cd\u4f5c\u7684\u65f6\u95f4\u590d\u6742\u5ea6\u4e3a O(log N)\uff0cN \u662f\u5806\u5927\u5c0f\uff0c\u6709\u70b9\u50cf\u628a\u5217\u8868\u961f\u5217\u5904\u7406\u4e86\nprint(heapq.heappop(heap))\nprint(heap)\nprint(heapq.heappop(heap))\nprint(heap)"} {"doc_id": "05e34f97fde960d412ff21d455b02a13", "text": "'''\n\nDescription:\n\nGiven a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.\n\nFor this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.\n\nExample:\n\nGiven the sorted linked list: [-10,-3,0,5,9],\n\nOne possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST:\n\n 0\n / \\\n -3 9\n / /\n -10 5\n\n'''\n\n\n\n# Definition for singly-linked list.\nclass ListNode:\n def __init__(self, x):\n self.val = x\n self.next = None\n\n# Definition for a binary tree node.\nclass TreeNode:\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\nfrom typing import List\nclass Solution:\n def sortedListToBST(self, head: ListNode) -> TreeNode:\n \n\n def linked_lsit_to_array( head: ListNode ):\n '''\n Input: head of of sorted linked list\n Output: a list with sorted value from linked list\n '''\n \n nonlocal sequence\n cur = head\n \n while cur:\n sequence.append( cur.val)\n cur = cur.next\n \n \n \n #def array_to_BST( sequence: List , left: int, right: int ) -> TreeNode:\n def array_to_BST( left: int, right: int ) -> TreeNode:\n '''\n Input: a list with sorted value\n Output: root node of balanced binary search tree\n '''\n \n if left > right:\n return None\n \n else:\n nonlocal sequence\n mid = left + (right-left) // 2\n \n root = TreeNode( sequence[mid] )\n \n root.left = array_to_BST( left, mid-1)\n root.right = array_to_BST( mid+1, right)\n \n return root\n \n # ----------------------------------------------\n sequence = []\n root_of_BST = None\n \n linked_lsit_to_array( head )\n root_of_BST = array_to_BST( 0 , len(sequence)-1 )\n return root_of_BST\n\n\n\n\n# n : number of nodes in linked list\n\n## Time Complexity: O( n )\n#\n# For linked_lsit_to_array(),\n# it takes O( n ) to convert linked list to array.\n#\n# For array_to_BST(),\n# it takes T( n ) = 2T( n / 2) + O( 1 ), T( n ) is of O( n ).\n\n## Space Complexity: O( n )\n#\n# The overhead in space is the storage for temporary array, and binary search tree, which is of O( n ).\n\n\n\ndef link_list_factory( sequence: List[int] ):\n\n size = len(sequence)\n last_one = None\n\n # build linked list from tail to head\n for node_value in reversed(sequence):\n node = ListNode( node_value )\n\n if last_one is not None:\n node.next = last_one\n\n last_one = node\n\n head = last_one\n return head\n\n\n\ndef inorder_print( node: TreeNode):\n\n if node:\n inorder_print( node.left )\n print(f'{node.val} ', end = '')\n inorder_print( node.right )\n\n\ndef test_bench():\n\n test_data = [-10, -3, 0, 5, 9]\n\n # expected output:\n '''\n -10 -3 0 5 9 \n '''\n\n # head node of linked list\n head_node = link_list_factory( test_data )\n\n # Test the conversion of sorted linked list to binary search tree\n root_node = Solution().sortedListToBST(head_node)\n\n # print the inorder traversal of output BST\n inorder_print( root_node )\n\n return \n\n\n\nif __name__ == '__main__':\n\n test_bench()"} {"doc_id": "05fd35724f782a79eb7c6e418ac29706", "text": "\"\"\"\nFile: boggle.py\nName: David\n----------------------------------------\nThis file recursively find the answers of the boggle game whose\n4x4 letters board will be entered by users.\n\"\"\"\n\nimport time\n\n# This is the file name of the dictionary txt file\n# we will be checking if a word exists by searching through it\nFILE = 'dictionary.txt'\n\n\ndef main():\n \"\"\"\n After users enter 4x4 boggle board, this function finds all correct answers\n of it.\n \"\"\"\n print(\"Welcome to boggle!\")\n print(\"Please enter 4 letters in one row and every letter should \"\n \"be separated from each others by a single space. \")\n # Create boggle board\n board = {}\n # Determine if a game should be started\n start = True\n # Enter the letters\n for i in range(4):\n row = input(str(i+1)+\" row of letters: \")\n if format_correct(row):\n # Count the number of the letters in the same row\n count = 0\n for ch in row:\n if ch.isalpha():\n # Case-insensitive\n ch = ch.lower()\n index = str(i)+str(count) # The first digit is its y-index, and the second digit is its x-index\n board[index] = ch\n count += 1\n else:\n print(\"Illegal input\")\n start = False\n break\n if start:\n start = time.time()\n # Find answers recursively\n boggle(board)\n end = time.time()\n print('----------------------------------')\n print(f'The speed of your boggle algorithm: {end - start} seconds.')\n\n\ndef format_correct(row):\n \"\"\"\n This function help determine if users enter the boggle board in a correct format.\n :param row: string, Entered row of letters\n :return: Boolean, return True if the entered row is in correct format\n \"\"\"\n if len(row) != 7:\n return False\n else:\n for i in range(len(row)):\n if i % 2 == 0:\n if not row[i].isalpha():\n return False\n elif i % 2 == 1:\n if row[i] != \" \":\n return False\n return True\n\n\ndef read_dictionary():\n \"\"\"\n This function reads file \"dictionary.txt\" stored in FILE\n and appends words in each line into a Python dictionary.\n The dictionary is categorized by the first two letters of a word.\n \"\"\"\n dic = {}\n alphabet = [\"a\", \"b\", \"c\", \"d\", \"e\", \"f\", \"g\", \"h\", \"i\", \"j\", \"k\", \"l\", \"m\", \"n\", \"o\",\n \"p\", \"q\", \"r\", \"s\", \"t\", \"u\", \"v\", \"w\", \"x\", \"y\", \"z\"]\n # Loop over 26 alphabets to create all possibilities of letters combination\n for i in range(len(alphabet)):\n for j in range(len(alphabet)):\n for k in range(len(alphabet)):\n head = alphabet[i] + alphabet[j] + alphabet[k]\n # Make the keys of the dictionary\n dic[head] = []\n # Put words into the specific list\n with open(FILE, \"r\") as f:\n for line in f:\n word = line.replace(\"\\n\", \"\")\n if len(word) >= 4:\n dic[word[:3]].append(word)\n return dic\n\n\ndef boggle(board):\n \"\"\"\n This function finds every possible answer of the boggle game.\n :param board: dict, the boggle board including letters (value) and their indexes (key)\n \"\"\"\n dic = read_dictionary()\n ans_lst = []\n # Loop every letters as the first character of a word\n for key in board:\n current_str = board[key]\n used_letters = [key]\n # Use helper function to find answers recursively\n boggle_helper(dic, board, current_str, ans_lst, used_letters)\n print(\"There are \"+str(len(ans_lst))+\" words in total.\")\n\n\ndef boggle_helper(dic, board, current_str, ans_lst, used_letters):\n \"\"\"\n This is the helper function of boggle(board).\n :param dic: dict, the dictionary read from FILE\n :param board: dict, the boggle board including letters (value) and their indexes (key)\n :param current_str: str, current sting\n :param ans_lst: list, list of found answers\n :param used_letters: list, list of the indexes of used letters\n \"\"\"\n # Current string is a word in the dictionary\n if len(current_str) >= 4:\n if current_str in dic[current_str[:3]]:\n if current_str not in ans_lst:\n ans_lst.append(current_str)\n print('Found \"'+current_str+'\"')\n # Current string is not a word in the dictionary but there are words start with current string\n if has_prefix(current_str, dic):\n # Find neighbors\n neighbor = find_neighbor(used_letters)\n # Loop over all the found neighbors\n for index in neighbor:\n # choose\n current_str += board[index]\n used_letters.append(index)\n # explore\n boggle_helper(dic, board, current_str, ans_lst, used_letters)\n # un_choose\n current_str = current_str[:len(current_str)-1]\n used_letters.pop()\n\n\ndef find_neighbor(used_letters):\n \"\"\"\n This function help find the current position's neighbors that have not been used previously.\n :param used_letters: list, list of the indexes of used letters\n :return: list, list of indexes that are current position's neighbors and not have been used\n \"\"\"\n neighbor = []\n center = used_letters[len(used_letters)-1] # Current position\n # x-index and y-index of current position\n x = int(center[1])\n y = int(center[0])\n # Find neighbors\n for i in range(x-1, x+2):\n if 0 <= i <= 3:\n for j in range(y-1, y+2):\n if 0 <= j <= 3:\n index = str(j) + str(i)\n if index not in used_letters:\n neighbor.append(index)\n return neighbor\n\n\ndef has_prefix(sub_s, dic):\n \"\"\"\n :param dic: dict, the dictionary read from FILE\n :param sub_s: (str) A substring that is constructed by neighboring letters on a 4x4 square grid\n :return: (bool) If there is any words with prefix stored in sub_s\n \"\"\"\n if len(sub_s) <= 2:\n return True\n else:\n # Loop over the dictionary\n for word in dic[sub_s[:3]]:\n if word.startswith(sub_s):\n return True\n return False\n\n\nif __name__ == '__main__':\n main()\n"} {"doc_id": "0652646558678f0a7ffab5a4f1f23a76", "text": "#!/usr/bin/env python\n\"\"\"\n--- Day 8: Memory Maneuver ---\n\nThe sleigh is much easier to pull than you'd expect for something its weight. Unfortunately, neither you nor the Elves know which way the North Pole is from here.\n\nYou check your wrist device for anything that might help. It seems to have some kind of navigation system! Activating the navigation system produces more bad news: \"Failed to start navigation system. Could not read software license file.\"\n\nThe navigation system's license file consists of a list of numbers (your puzzle input). The numbers define a data structure which, when processed, produces some kind of tree that can be used to calculate the license number.\n\nThe tree is made up of nodes; a single, outermost node forms the tree's root, and it contains all other nodes in the tree (or contains nodes that contain nodes, and so on).\n\nSpecifically, a node consists of:\n\n A header, which is always exactly two numbers:\n The quantity of child nodes.\n The quantity of metadata entries.\n Zero or more child nodes (as specified in the header).\n One or more metadata entries (as specified in the header).\n\nEach child node is itself a node that has its own header, child nodes, and metadata. For example:\n\n2 3 0 3 10 11 12 1 1 0 1 99 2 1 1 2\nA----------------------------------\n B----------- C-----------\n D-----\n\nIn this example, each node of the tree is also marked with an underline starting with a letter for easier identification. In it, there are four nodes:\n\n A, which has 2 child nodes (B, C) and 3 metadata entries (1, 1, 2).\n B, which has 0 child nodes and 3 metadata entries (10, 11, 12).\n C, which has 1 child node (D) and 1 metadata entry (2).\n D, which has 0 child nodes and 1 metadata entry (99).\n\nThe first check done on the license file is to simply add up all of the metadata entries. In this example, that sum is 1+1+2+10+11+12+2+99=138.\n\nWhat is the sum of all metadata entries?\n\n--- Part Two ---\n\nThe second check is slightly more complicated: you need to find the value of the root node (A in the example above).\n\nThe value of a node depends on whether it has child nodes.\n\nIf a node has no child nodes, its value is the sum of its metadata entries. So, the value of node B is 10+11+12=33, and the value of node D is 99.\n\nHowever, if a node does have child nodes, the metadata entries become indexes which refer to those child nodes. A metadata entry of 1 refers to the first child node, 2 to the second, 3 to the third, and so on. The value of this node is the sum of the values of the child nodes referenced by the metadata entries. If a referenced child node does not exist, that reference is skipped. A child node can be referenced multiple time and counts each time it is referenced. A metadata entry of 0 does not refer to any child node.\n\nFor example, again using the above nodes:\n\n Node C has one metadata entry, 2. Because node C has only one child node, 2 references a child node which does not exist, and so the value of node C is 0.\n Node A has three metadata entries: 1, 1, and 2. The 1 references node A's first child node, B, and the 2 references node A's second child node, C. Because node B has a value of 33 and node C has a value of 0, the value of node A is 33+33+0=66.\n\nSo, in this example, the value of the root node is 66.\n\nWhat is the value of the root node?\n\n\"\"\"\nfrom __future__ import print_function\nimport os\n\nmetadata_value = 0\n\n\ndef parse_node(node):\n \"\"\"Recursively parse a node's header, metadata & children\"\"\"\n global metadata_value\n # print('new node', node)\n child_count = node[0]\n metadata_count = node[1]\n parsed = 2\n # print(f\"child count: {child_count}, metadata count: {metadata_count}\")\n # print(\"children\", node[2:])\n\n children = []\n for _ in range(child_count):\n # print(\"parse child from\", node[parsed:])\n child = parse_node(node[parsed:])\n parsed += child[\"len\"]\n children.append(child)\n # print(\"children\", children)\n\n metadata = node[parsed:parsed + metadata_count]\n metadata_value += sum(metadata)\n\n value = 0\n if child_count == 0:\n value = sum(metadata)\n else:\n for idx in metadata:\n if idx > len(children):\n continue\n value += children[idx - 1][\"value\"]\n\n length = parsed + metadata_count\n node_info = {\"len\": length, \"child_count\": child_count, \"metadata_count\": metadata_count, \"metadata\": metadata, \"children\": children, \"value\": value}\n # print('node info', node_info)\n return node_info\n\n\ndef solve(data, flag=False):\n data = list(map(int, data.split()))\n root_node = parse_node(data)\n\n if not flag:\n return metadata_value\n if flag:\n return root_node[\"value\"]\n\n\nif __name__ == \"__main__\":\n this_dir = os.path.dirname(__file__)\n with open(os.path.join(this_dir, \"day8.input\")) as f:\n data = f.read().strip()\n print(\"The sum of all the metadata entries is\", solve(data, False))\n print(\"The value of the root node is\", solve(data, True))\n"} {"doc_id": "06999156d548c5d6e488701b8853619a", "text": "# Fa\u00e7a um programa que leia um numero de 0 a 9999 e mostre cada um dos digitos\n# EX digite um n\u00famero 1834, unidade 4, dezena 3, centena 8 e milhar 1\n\nfrom math import trunc\n# Lendo o n\u00famero\nn = int(input('Informe um n\u00famero de at\u00e9 4 digitos: '))\nprint('An\u00e1lisando o n\u00famero digitado ....................')\n\n# Atrav\u00e9s do recusso da divis\u00e3o inteira \"//\" e do resto da divis\u00e3o \"%\" obtemos o valor desejado\nm = n // 1000 % 10\nc = n // 100 % 10\nd = n // 10 % 10\nu = n // 1 % 10\n\n#Mostrando na tela os valores obtidos\nprint('Unidade {}\\nDezena {}\\nCentena {}\\nMilhar {} '.format(u, d, c, m))\n\n#Desafio conclu\u00eddo"} {"doc_id": "06fc15a7db21531e0c6dadec67618195", "text": "import sympy as sym\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\nclass Newton():\n\n def __init__(self, f='x**2', max_iter=1e6, eps=1e-14):\n \"\"\" Newton method class to find the solution\n\n Attributes:\n f (str) representing the function\n max_iter (int) representing the maximum number of iterations to find the solution\n eps (float) representing stopping criteria abs(f(x)) < epsilon\n \n Examples\n --------\n >>> f = '2*x**2 - 50'\n >>> newton = Newton(f)\n >>> newton.find_solution(1)\n x = 13.0, f(x) = 288.0, iteration #1\n x = 7.461538461538462, f(x) = 61.349112426035504, iteration #2\n x = 5.406026962727994, f(x) = 8.45025504348412, iteration #3\n x = 5.015247601944898, f(x) = 0.3054170176281019, iteration #4\n x = 5.000023178253949, f(x) = 0.00046356615344222973, iteration #5\n x = 5.000000000053723, f(x) = 1.0744685141617083e-09, iteration #6\n x = 5.0, f(x) = 0.0, iteration #7\n \n Solution found at 5.0 with 7 iterations\n\n \"\"\"\n\n self.f = f # Symbolic expression of the function\n self.max_iter = max_iter\n self.eps = eps\n x = sym.symbols('x') # Define x as mathematical symbol\n self.x = x\n\n def calculate_f_value(self, x):\n \"\"\" Function to evaluate function for given x\n\n Args:\n x (float): x value\n\n Returns:\n f(x) (float): value of the function for the given x\n\n \"\"\"\n\n # lambdify provides a bridge from Sympy expression to numerical libraries\n f = sym.lambdify([self.x], self.f)\n return f(x)\n\n def calculate_derivative(self, x):\n \"\"\" Function to find the derivative and calculate the dfdx value for given x\n\n Args:\n x (float): x value\n\n Returns:\n dfdx(x) (float): derivate of f(x) at given x\n \"\"\"\n\n self.dfdx_expr = sym.diff(self.f, self.x)\n dfdx = sym.lambdify([self.x], self.dfdx_expr)\n\n return dfdx(x)\n\n def plot_function(self, a=-10, b=10):\n \"\"\" Function to plot the given function\n\n Args:\n a, b (float) [optional]: intervals\n\n Returns:\n None\n \"\"\"\n x = np.linspace(a, b, 100)\n y = sym.lambdify([self.x], self.f)(x)\n\n fig = plt.figure()\n ax = fig.add_subplot(1, 1, 1)\n ax.spines['left'].set_position('center')\n ax.spines['bottom'].set_position('zero')\n ax.spines['right'].set_color('none')\n ax.spines['top'].set_color('none')\n ax.xaxis.set_ticks_position('bottom')\n ax.yaxis.set_ticks_position('left')\n plt.plot(x, y)\n plt.show()\n\n def find_solution(self, x0):\n \"\"\" Function to approximate solution of f(x)=0 by Newton's method\n\n Args:\n x0 (float): initial guess for a solution f(x)=0\n\n Returns:\n xn (float): intercept (solution) by the formula x = xn - f(xn)/dfdx(xn)\n\n \"\"\"\n xn = x0\n iter_counter = 0\n f_value = self.calculate_f_value(xn)\n while abs(f_value) > self.eps and iter_counter < self.max_iter:\n try:\n xn = xn - float(f_value) / self.calculate_derivative(xn)\n except ZeroDivisionError:\n # Handling ZeroDivisonError - if the derivative of the initial guess is 0, increment x0\n print(\n \"Error! - derivative zero for x = {}. Incrementing by 1...\".format(xn))\n xn += 1\n f_value = self.calculate_f_value(xn)\n iter_counter += 1\n\n print(\"x = {}, f(x) = {}, iteration #{}\".format(\n xn, f_value, iter_counter))\n\n print(\"Solution found at {} with {} iterations\".format(xn, iter_counter))\n if abs(f_value) > self.eps:\n print(\"Solution not found! Try changing the initial guess\")\n iter_counter = -1\n xn = None\n \n return xn\n"} {"doc_id": "071546c52781769162caaee59709ce47", "text": "\"\"\"\r\nFile: draw_line.py\r\nName:Fei\r\n-------------------------\r\nTODO: When an odd click sets a point, when even click, draw a line.\r\n\"\"\"\r\n\r\nfrom campy.graphics.gobjects import GOval, GLine\r\nfrom campy.graphics.gwindow import GWindow\r\nfrom campy.gui.events.mouse import onmouseclicked\r\n\r\nSIZE = 30\r\nwindow = GWindow() # initiate the window\r\npoint = GOval(SIZE, SIZE) # initiate the point\r\n\r\n\r\ndef main():\r\n \"\"\"\r\n This program creates lines on an instance of GWindow class.\r\n There is a circle indicating the user\u2019s first click. A line appears\r\n at the condition where the circle disappears as the user clicks\r\n on the canvas for the second time.\r\n \"\"\"\r\n onmouseclicked(set_point)\r\n\r\n\r\ndef set_point(e):\r\n window.add(point, x=e.x, y=e.y) # add a point while on the first click\r\n onmouseclicked(line) # call line function\r\n\r\n\r\ndef line(f):\r\n n_line = GLine(point.x, point.y, f.x, f.y) # draw a line while on the second click\r\n window.remove(point) # remove the point\r\n window.add(n_line) # add a line\r\n onmouseclicked(set_point) # call set_point function\r\n\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n"} {"doc_id": "0719073adbc07497d8150b7812e2420f", "text": "\"\"\"\n\n***********************************************\nAuthor: Mark Arakaki\nOctober 15, 2017\nPersonal Practice Use\n***********************************************\n\n\tAsk the user for a number. Depending on whether the number is\n\teven or odd, print out an appropriate messsage to the user.\n\n\tExtras:\n\t1) if the number is a multiple of 4, print out a different message\n\t2) ask the user for two numbers one number to check (call it num) and one number to divide by (check). If check divides evenly into num, tell that to the user. If not, print a different appropriate message.\n\n\"\"\"\n\nprint(\"\\nBEGIN PART 1\\n\")\n\nnum = input(\"Please enter in a number: \")\n\nif num == 0:\n \n\tprint(\"\\nThe number you have entered is a zero, which is neither even nor odd...\")\n\nelif num % 2 == 0:\n\t\n\tprint (\"The number you have entered (\" + str(num) + \") is even!\")\n\t\n\tif num % 4 == 0:\n\n \tprint (\"The number you have entered (\" + str(num) + \") is a multiple of 4 as well!\")\nelse:\n\n\tprint(\"\\nThe number you have entered (\" + str(num) + \") is odd!\")\n\n#######################################################################################################\n\nprint(\"\\nBEGIN PART 2\\n\")\n\nnum = input (\"Please enter in a number that you want to be divided by another number: \")\n\ncheck = input (\"\\nPlease enter in a number that will divide the original number by: \")\n\nif num == 0:\n\tprint(\"\\nYou cannot divide zero by another number. You literally created a black hole... Congratulations.\")\nelif num % check == 0:\n\tprint(\"\\n\" + str(num) + \" divides evenly with \" + str(check) + \"!\")\nelse:\n\tprint(\"\\n\" + str(num) + \" does not divide evenly with \" + str(check) + \"!\")\n"} {"doc_id": "0719f63c1e64e1bd263b6347997713db", "text": "\"\"\"\n

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\n

Note:

\n\n\n\n

Example 1:

\n\n
\nInput:\ns = "catsanddog"\nwordDict = ["cat", "cats", "and", "sand", "dog"]\nOutput:\n[\n  "cats and dog",\n  "cat sand dog"\n]\n
\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\n\n

\u793a\u4f8b 1\uff1a

\n\n
\u8f93\u5165:\ns = "catsanddog"\nwordDict = ["cat", "cats", "and", "sand", "dog"]\n\u8f93\u51fa:\n[\n  "cats and dog",\n  "cat sand dog"\n]\n
\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\n\n

\u793a\u4f8b 1\uff1a

\n\n
\u8f93\u5165:\ns = "catsanddog"\nwordDict = ["cat", "cats", "and", "sand", "dog"]\n\u8f93\u51fa:\n[\n  "cats and dog",\n  "cat sand dog"\n]\n
\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 entre 4 e 9.')\n print('-----------------------------------------------------------------')\n continue\nprint('=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=')\n\nlista = []\nfor i in range(n):\n if i==3:\n lista.append('TESTE')\n print(f'O \u00edndice [{i}] foi preenchido automaticamente com: \"TESTE\".')\n else:\n nome = str(input(f'Digite um nome para o \u00edndice [{i}] da lista: ')).upper()\n lista.append(nome)\n\nprint('\\n=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=')\nprint(f'Lista ap\u00f3s o prenchimento inicial com {n} nomes:\\n{lista}')\n\nprint('\\n=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=')\nexc = lista[2]\ndel lista[2]\nprint(f'Lista ap\u00f3s a exclus\u00e3o do ind\u00edce [2] => \"{exc}\" da lista:\\n{lista}')\n\nprint('\\n=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=')\nana = lista.count('ANA')\n\nif ana>0:\n print(f'O nome \"ANA\" aparece {ana} vez(es) na lista.')\n print(f'Sendo apresentado pela primeira vez na posi\u00e7\u00e3o [{lista.index(\"ANA\")}] da lista.')\nelse:\n print('O nome \"ANA\" n\u00e3o existe na lista.')\n\nprint('\\n=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=')\nlista.sort()\nprint('Lista em ordem alfab\u00e9tica: ', end='')\nfor pos,p in enumerate(lista):\n if pos == len(lista)-1:\n print(p, end='.')\n elif pos == len(lista)-2:\n print(p, end=' e ')\n else:\n print(p, end=', ')\nprint('\\n=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=')\n"} {"doc_id": "0d68bea51610706698603951ed805b6e", "text": "\"\"\"\n

Write a program to check whether a given number is an ugly number.

\n\n

Ugly numbers are positive numbers whose prime factors only include 2, 3, 5.

\n\n

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: 14 is not ugly since it includes another prime factor 7.\n
\n\n

Note:

\n\n
    \n\t
  1. 1 is typically treated as an ugly number.
  2. \n\t
  3. Input is within the 32-bit signed integer range: [−231,  231 − 1].
  4. \n
\n

\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

\n\n

\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: 14 \u4e0d\u662f\u4e11\u6570\uff0c\u56e0\u4e3a\u5b83\u5305\u542b\u4e86\u53e6\u5916\u4e00\u4e2a\u8d28\u56e0\u6570 7\u3002
\n\n

\u8bf4\u660e\uff1a

\n\n
    \n\t
  1. 1 \u662f\u4e11\u6570\u3002
  2. \n\t
  3. \u8f93\u5165\u4e0d\u4f1a\u8d85\u8fc7 32 \u4f4d\u6709\u7b26\u53f7\u6574\u6570\u7684\u8303\u56f4: [−231,  231 − 1]\u3002
  4. \n
\n

\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

\n\n

\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: 14 \u4e0d\u662f\u4e11\u6570\uff0c\u56e0\u4e3a\u5b83\u5305\u542b\u4e86\u53e6\u5916\u4e00\u4e2a\u8d28\u56e0\u6570 7\u3002
\n\n

\u8bf4\u660e\uff1a

\n\n
    \n\t
  1. 1 \u662f\u4e11\u6570\u3002
  2. \n\t
  3. \u8f93\u5165\u4e0d\u4f1a\u8d85\u8fc7 32 \u4f4d\u6709\u7b26\u53f7\u6574\u6570\u7684\u8303\u56f4: [−231,  231 − 1]\u3002
  4. \n
\n\"\"\"\n\n\nclass Solution:\n def isUgly(self, num):\n \"\"\"\n :type num: int\n :rtype: bool\n \"\"\""} {"doc_id": "0d6e2c5dafb8f9dc8985694acd682ed2", "text": "\"\"\"\nValid Passwords - SOLUTION\n\"\"\"\n\n# Check the validity of password input by users based on the below security requirements. If the password doesn't meet the requirements, print \"Please enter a valid password.\"\n\n\"\"\"\nAt least 1 letter between [a-z] and 1 letter between [A-Z].\nAt least 1 number between [0-9].\nAt least 1 character from [$#@].\nMinimum length 6 characters.\nMaximum length 16 characters.\n\"\"\"\n\n# Hint: Look up the documentation for the \"re\" library and it's \".search()\" method.\n\nimport re\n\np = input(\"Input your password: \")\nx = True\nwhile x: \n if (len(p)<6 or len(p)>12):\n break\n elif not re.search(\"[a-z]\",p):\n break\n elif not re.search(\"[0-9]\",p):\n break\n elif not re.search(\"[A-Z]\",p):\n break\n elif not re.search(\"[$#@]\",p):\n break\n elif re.search(\"\\s\",p):\n break\n else:\n print(\"Valid Password\")\n x=False\n break\n\nif x:\n print(\"Please enter a valid password.\")"} {"doc_id": "0de3dbfb0d2c1a8055d65a54db1278ec", "text": "# Definition for singly-linked list.\nclass ListNode:\n def __init__(self, val=0, next=None):\n self.val = val\n self.next = next\n\n# *********\u9898\u76ee\u63cf\u8ff0******************\n# \u7ed9\u5b9a\u4e00\u4e2a\u5355\u94fe\u8868 L\uff1aL0\u2192L1\u2192\u2026\u2192Ln-1\u2192Ln \uff0c\n# \u5c06\u5176\u91cd\u65b0\u6392\u5217\u540e\u53d8\u4e3a\uff1a L0\u2192Ln\u2192L1\u2192Ln-1\u2192L2\u2192Ln-2\u2192\u2026\n#\n# \u4f60\u4e0d\u80fd\u53ea\u662f\u5355\u7eaf\u7684\u6539\u53d8\u8282\u70b9\u5185\u90e8\u7684\u503c\uff0c\u800c\u662f\u9700\u8981\u5b9e\u9645\u7684\u8fdb\u884c\u8282\u70b9\u4ea4\u6362\u3002\n#\n# \u793a\u4f8b 1:\n#\n# \u7ed9\u5b9a\u94fe\u8868 1->2->3->4, \u91cd\u65b0\u6392\u5217\u4e3a 1->4->2->3.\n# \u793a\u4f8b 2:\n#\n# \u7ed9\u5b9a\u94fe\u8868 1->2->3->4->5, \u91cd\u65b0\u6392\u5217\u4e3a 1->5->2->4->3.\n\n\nclass Solution:\n def reorderList(self, head):\n \"\"\"\n Do not return anything, modify head in-place instead.\n \"\"\"\n if not head:\n return None\n mid_node = self.find_mid(head)\n new_head = self.reverse_list(mid_node.next)\n mid_node.next = None\n\n ret = head\n while new_head:\n iter_new_node = new_head\n new_head = new_head.next\n iter_new_node.next = head.next\n head.next = iter_new_node\n head = head.next.next\n return ret\n\n @staticmethod\n def find_mid(head):\n if not head:\n return None\n\n slow = head\n fast = head.next\n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n return slow\n\n @staticmethod\n def reverse_list(head):\n if not head:\n return None\n\n new_head = tail = None\n tail = head\n while tail.next:\n tail = tail.next\n\n new_head = tail\n while head != new_head:\n tmp_node = head\n head = head.next\n tmp_node.next = new_head.next\n new_head.next = tmp_node\n\n return new_head\n\n\n\n\n"} {"doc_id": "0e112cd3732a9534da204bb0397ff3ee", "text": "def tree(label, branches=[]):\n \"\"\"Construct a tree with the given label value and a list of branches.\"\"\"\n for branch in branches:\n assert is_tree(branch), 'branches must be trees'\n return [label] + list(branches)\n\ndef label(tree):\n \"\"\"Return the label value of a tree.\"\"\"\n return tree[0]\n\ndef branches(tree):\n \"\"\"Return the list of branches of the given tree.\"\"\"\n return tree[1:]\n\ndef is_tree(tree):\n \"\"\"Returns True if the given tree is a tree, and False otherwise.\"\"\"\n if type(tree) != list or len(tree) < 1:\n return False\n for branch in branches(tree):\n if not is_tree(branch):\n return False\n return True\n\ndef is_leaf(tree):\n \"\"\"Returns True if the given tree's list of branches is empty, and False\n otherwise.\n \"\"\"\n return not branches(tree)\n\ndef print_tree(t, indent=0):\n \"\"\"Print a representation of this tree in which each node is\n indented by two spaces times its depth from the root.\n\n >>> print_tree(tree(1))\n 1\n >>> print_tree(tree(1, [tree(2)]))\n 1\n 2\n >>> numbers = tree(1, [tree(2), tree(3, [tree(4), tree(5)]), tree(6, [tree(7)])])\n >>> print_tree(numbers)\n 1\n 2\n 3\n 4\n 5\n 6\n 7\n \"\"\"\n print(' ' * indent + str(label(t)))\n for b in branches(t):\n print_tree(b, indent + 1)\n\ndef copy_tree(t):\n \"\"\"Returns a copy of t. Only for testing purposes.\n\n >>> t = tree(5)\n >>> copy = copy_tree(t)\n >>> t = tree(6)\n >>> print_tree(copy)\n 5\n \"\"\"\n return tree(label(t), [copy_tree(b) for b in branches(t)])\n\n#############\n# Questions #\n#############\n\ndef replace_leaf(t, old, new):\n \"\"\"Returns a new tree where every leaf value equal to old has\n been replaced with new.\n\n >>> yggdrasil = tree('odin',\n ... [tree('balder',\n ... [tree('thor'),\n ... tree('loki')]),\n ... tree('frigg',\n ... [tree('thor')]),\n ... tree('thor',\n ... [tree('sif'),\n ... tree('thor')]),\n ... tree('thor')])\n >>> laerad = copy_tree(yggdrasil) # copy yggdrasil for testing purposes\n >>> print_tree(replace_leaf(yggdrasil, 'thor', 'freya'))\n odin\n balder\n freya\n loki\n frigg\n freya\n thor\n sif\n freya\n freya\n >>> laerad == yggdrasil # Make sure original tree is unmodified\n True\n \"\"\"\n def helper(t, old, new):\n for b in branches(t):\n if not is_leaf(b):\n helper(b, old, new)\n elif is_leaf(b) and label(b) == old:\n b[0] = new # technically we shouldn't be dealing with the internal implementation directly,\n # but I don't see a function for setting the label of a tree or leaf, so whatever \u00af\\_(\u30c4)_/\u00af\n return t\n return helper(copy_tree(t), old, new)\n\ndef print_move(origin, destination):\n \"\"\"Print instructions to move a disk.\"\"\"\n print(\"Move the top disk from rod\", origin, \"to rod\", destination)\n\ndef move_stack(n, start, end):\n \"\"\"Print the moves required to move n disks on the start pole to the end\n pole without violating the rules of Towers of Hanoi.\n\n n -- number of disks\n start -- a pole position, either 1, 2, or 3\n end -- a pole position, either 1, 2, or 3\n\n There are exactly three poles, and start and end must be different. Assume\n that the start pole has at least n disks of increasing size, and the end\n pole is either empty or has a top disk larger than the top n start disks.\n\n >>> move_stack(1, 1, 3)\n Move the top disk from rod 1 to rod 3\n >>> move_stack(2, 1, 3)\n Move the top disk from rod 1 to rod 2\n Move the top disk from rod 1 to rod 3\n Move the top disk from rod 2 to rod 3\n >>> move_stack(3, 1, 3)\n Move the top disk from rod 1 to rod 3\n Move the top disk from rod 1 to rod 2\n Move the top disk from rod 3 to rod 2\n Move the top disk from rod 1 to rod 3\n Move the top disk from rod 2 to rod 1\n Move the top disk from rod 2 to rod 3\n Move the top disk from rod 1 to rod 3\n \"\"\"\n assert 1 <= start <= 3 and 1 <= end <= 3 and start != end, \"Bad start/end\"\n\n middle = 6 - end - start\n if n == 1:\n print_move(start, end)\n else:\n # The idea is to move a tower of n-1 height to the middle, move the largest\n # disc to the end, and them move the middle tower to the end. By also splitting\n # the tower into smaller versions, we can recursively move the towers and still\n # obey the rules of the game. Basically, don't overthink this solution\n move_stack(n - 1, start, middle)\n print_move(start, end)\n move_stack(n - 1, middle, end)\n\n\n###########\n# Mobiles #\n###########\n\ndef mobile(left, right):\n \"\"\"Construct a mobile from a left side and a right side.\"\"\"\n return tree('mobile', [left, right])\n\ndef is_mobile(m):\n return is_tree(m) and label(m) == 'mobile'\n\ndef sides(m):\n \"\"\"Select the sides of a mobile.\"\"\"\n assert is_mobile(m), \"must call sides on a mobile\"\n return branches(m)\n\ndef is_side(m):\n return not is_mobile(m) and not is_weight(m) and type(label(m)) == int\n\ndef side(length, mobile_or_weight):\n \"\"\"Construct a side: a length of rod with a mobile or weight at the end.\"\"\"\n return tree(length, [mobile_or_weight])\n\ndef length(s):\n \"\"\"Select the length of a side.\"\"\"\n assert is_side(s), \"must call length on a side\"\n return label(s)\n\ndef end(s):\n \"\"\"Select the mobile or weight hanging at the end of a side.\"\"\"\n assert is_side(s), \"must call end on a side\"\n return branches(s)[0]\n\ndef weight(size):\n \"\"\"Construct a weight of some size.\"\"\"\n assert size > 0\n return tree(size)\n\ndef size(w):\n \"\"\"Select the size of a weight.\"\"\"\n return label(w)\n\ndef is_weight(w):\n \"\"\"Whether w is a weight, not a mobile.\"\"\"\n return not is_mobile(w) and is_leaf(w) and type(label(w)) == int\n\ndef examples():\n t = mobile(side(1, weight(2)),\n side(2, weight(1)))\n u = mobile(side(5, weight(1)),\n side(1, mobile(side(2, weight(3)),\n side(3, weight(2)))))\n v = mobile(side(4, t), side(2, u))\n return (t, u, v)\n\n\ndef total_weight(m):\n \"\"\"Return the total weight of m, a weight or mobile.\n\n >>> t, u, v = examples()\n >>> total_weight(t)\n 3\n >>> total_weight(u)\n 6\n >>> total_weight(v)\n 9\n \"\"\"\n if is_weight(m):\n return size(m)\n else:\n assert is_mobile(m), \"must get total weight of a mobile or a weight\"\n return sum([total_weight(end(s)) for s in sides(m)])\n\ndef balanced(m):\n \"\"\"Return whether m is balanced.\n\n >>> t, u, v = examples()\n >>> balanced(t)\n True\n >>> balanced(v)\n True\n >>> w = mobile(side(3, t), side(2, u))\n >>> balanced(w)\n False\n >>> balanced(mobile(side(1, v), side(1, w)))\n False\n >>> balanced(mobile(side(1, w), side(1, v)))\n False\n \"\"\"\n # 1. The torque applied by its left side is equal to that applied by its right side.\n # Torque of the left side is the length of the left rod multiplied by the total weight\n # hanging from that rod (a similar calculation is used for the right side).\n # 2. Each of the submobiles hanging off its sides is balanced.\n\n def torque(side):\n return length(side) * total_weight(end(side))\n\n # we first check if the nested mobiles are balanced or not\n if False in [balanced(end(s)) for s in sides(m) if not is_weight(end(s))]:\n return False\n left, right = sides(m)\n return torque(left) == torque(right)\n\n\n#######\n# OOP #\n#######\n\nclass Account:\n \"\"\"An account has a balance and a holder.\n\n >>> a = Account('John')\n >>> a.deposit(10)\n 10\n >>> a.balance\n 10\n >>> a.interest\n 0.02\n\n >>> a.time_to_retire(10.25) # 10 -> 10.2 -> 10.404\n 2\n >>> a.balance # balance should not change\n 10\n >>> a.time_to_retire(11) # 10 -> 10.2 -> ... -> 11.040808032\n 5\n >>> a.time_to_retire(100)\n 117\n \"\"\"\n\n interest = 0.02 # A class attribute\n\n def __init__(self, account_holder):\n self.holder = account_holder\n self.balance = 0\n\n def deposit(self, amount):\n \"\"\"Add amount to balance.\"\"\"\n self.balance = self.balance + amount\n return self.balance\n\n def withdraw(self, amount):\n \"\"\"Subtract amount from balance if funds are available.\"\"\"\n if amount > self.balance:\n return 'Insufficient funds'\n self.balance = self.balance - amount\n return self.balance\n\n def time_to_retire(self, amount):\n \"\"\"Return the number of years until balance would grow to amount.\"\"\"\n assert self.balance > 0 and amount > 0 and self.interest > 0\n # This is in a function to prevent overriding self.balance\n # Vars in python are refs (I think)\n def calc(start, end, interest):\n years = 0\n while start < amount:\n start *= 1 + interest\n years += 1\n return calc(self.balance, amount, self.interest)\n\nclass FreeChecking(Account):\n \"\"\"A bank account that charges for withdrawals, but the first two are free!\n\n >>> ch = FreeChecking('Jack')\n >>> ch.balance = 20\n >>> ch.withdraw(100) # First one's free\n 'Insufficient funds'\n >>> ch.withdraw(3) # And the second\n 17\n >>> ch.balance\n 17\n >>> ch.withdraw(3) # Ok, two free withdrawals is enough\n 13\n >>> ch.withdraw(3)\n 9\n >>> ch2 = FreeChecking('John')\n >>> ch2.balance = 10\n >>> ch2.withdraw(3) # No fee\n 7\n >>> ch.withdraw(3) # ch still charges a fee\n 5\n >>> ch.withdraw(5) # Not enough to cover fee + withdraw\n 'Insufficient funds'\n \"\"\"\n withdraw_fee = 1\n free_withdrawals = 2\n def withdraw(self, amount):\n if self.free_withdrawals > 0:\n self.free_withdrawals -= 1\n return Account.withdraw(self, amount)\n return Account.withdraw(self, amount + self.withdraw_fee)\n\n############\n# Mutation #\n############\n\ndef make_counter():\n \"\"\"Return a counter function.\n\n >>> c = make_counter()\n >>> c('a')\n 1\n >>> c('a')\n 2\n >>> c('b')\n 1\n >>> c('a')\n 3\n >>> c2 = make_counter()\n >>> c2('b')\n 1\n >>> c2('b')\n 2\n >>> c('b') + c2('b')\n 5\n \"\"\"\n counter_store = {}\n def helper(s):\n if s not in counter_store:\n counter_store[s] = 1\n else:\n counter_store[s] += 1\n return counter_store[s]\n return helper\n\ndef make_fib():\n \"\"\"Returns a function that returns the next Fibonacci number\n every time it is called.\n\n >>> fib = make_fib()\n >>> fib()\n 0\n >>> fib()\n 1\n >>> fib()\n 1\n >>> fib()\n 2\n >>> fib()\n 3\n >>> fib2 = make_fib()\n >>> fib() + sum([fib2() for _ in range(5)])\n 12\n \"\"\"\n fibb = []\n def helper():\n l = len(fibb)\n if l == 0:\n fibb.append(0)\n elif l == 1:\n fibb.append(1)\n else:\n fibb.append(fibb[l-2] + fibb[l-1])\n return fibb[l]\n return helper\n\ndef make_withdraw(balance, password):\n \"\"\"Return a password-protected withdraw function.\n\n >>> w = make_withdraw(100, 'hax0r')\n >>> w(25, 'hax0r')\n 75\n >>> error = w(90, 'hax0r')\n >>> error\n 'Insufficient funds'\n >>> error = w(25, 'hwat')\n >>> error\n 'Incorrect password'\n >>> new_bal = w(25, 'hax0r')\n >>> new_bal\n 50\n >>> w(75, 'a')\n 'Incorrect password'\n >>> w(10, 'hax0r')\n 40\n >>> w(20, 'n00b')\n 'Incorrect password'\n >>> w(10, 'hax0r')\n \"Your account is locked. Attempts: ['hwat', 'a', 'n00b']\"\n >>> w(10, 'l33t')\n \"Your account is locked. Attempts: ['hwat', 'a', 'n00b']\"\n >>> type(w(10, 'l33t')) == str\n True\n \"\"\"\n incorrect_inputs = []\n def helper(withdraw, input_pass):\n nonlocal balance\n if len(incorrect_inputs) >= 3:\n return \"Your account is locked. Attempts: %s\" % incorrect_inputs\n elif input_pass != password and len(incorrect_inputs) < 3:\n incorrect_inputs.append(input_pass)\n return 'Incorrect password'\n elif balance < withdraw:\n return 'Insufficient funds'\n else:\n balance -= withdraw\n return balance\n return helper\n\n\ndef make_joint(withdraw, old_password, new_password):\n \"\"\"Return a password-protected withdraw function that has joint access to\n the balance of withdraw.\n\n >>> w = make_withdraw(100, 'hax0r')\n >>> w(25, 'hax0r')\n 75\n >>> make_joint(w, 'my', 'secret')\n 'Incorrect password'\n >>> j = make_joint(w, 'hax0r', 'secret')\n >>> w(25, 'secret')\n 'Incorrect password'\n >>> j(25, 'secret')\n 50\n >>> j(25, 'hax0r')\n 25\n >>> j(100, 'secret')\n 'Insufficient funds'\n\n >>> j2 = make_joint(j, 'secret', 'code')\n >>> j2(5, 'code')\n 20\n >>> j2(5, 'secret')\n 15\n >>> j2(5, 'hax0r')\n 10\n\n >>> j2(25, 'password')\n 'Incorrect password'\n >>> j2(5, 'secret')\n \"Your account is locked. Attempts: ['my', 'secret', 'password']\"\n >>> j(5, 'secret')\n \"Your account is locked. Attempts: ['my', 'secret', 'password']\"\n >>> w(5, 'hax0r')\n \"Your account is locked. Attempts: ['my', 'secret', 'password']\"\n >>> make_joint(w, 'hax0r', 'hello')\n \"Your account is locked. Attempts: ['my', 'secret', 'password']\"\n \"\"\"\n init_res = withdraw(0, old_password)\n if type(init_res) == str:\n return init_res\n def helper(take_amt, input_pass):\n if input_pass == new_password:\n input_pass = old_password\n return withdraw(take_amt, input_pass)\n return helper\n\n\n\n###################\n# Extra Questions #\n###################\n\ndef interval(a, b):\n \"\"\"Construct an interval from a to b.\"\"\"\n return [a, b]\n\ndef lower_bound(x):\n \"\"\"Return the lower bound of interval x.\"\"\"\n return x[0]\n\ndef upper_bound(x):\n \"\"\"Return the upper bound of interval x.\"\"\"\n return x[1]\n\ndef str_interval(x):\n \"\"\"Return a string representation of interval x.\"\"\"\n return '{0} to {1}'.format(lower_bound(x), upper_bound(x))\n\ndef add_interval(x, y):\n \"\"\"Return an interval that contains the sum of any value in interval x and\n any value in interval y.\"\"\"\n lower = lower_bound(x) + lower_bound(y)\n upper = upper_bound(x) + upper_bound(y)\n return interval(lower, upper)\n\ndef mul_interval(x, y):\n \"\"\"Return the interval that contains the product of any value in x and any\n value in y.\"\"\"\n p1 = lower_bound(x) * lower_bound(y)\n p2 = lower_bound(x) * upper_bound(y)\n p3 = upper_bound(x) * lower_bound(y)\n p4 = upper_bound(x) * upper_bound(y)\n return interval(min(p1, p2, p3, p4), max(p1, p2, p3, p4))\n\ndef sub_interval(x, y):\n \"\"\"Return the interval that contains the difference between any value in x\n and any value in y.\"\"\"\n return interval(lower_bound(x) - upper_bound(y), upper_bound(x) - lower_bound(y))\n\ndef div_interval(x, y):\n \"\"\"Return the interval that contains the quotient of any value in x divided by\n any value in y. Division is implemented as the multiplication of x by the\n reciprocal of y.\"\"\"\n # if the signs are different, the interval 'y' encompasses 0, which isn't allowed\n assert (lower_bound(y) > 0) == (upper_bound(y) > 0)\n reciprocal_y = interval(1/upper_bound(y), 1/lower_bound(y))\n return mul_interval(x, reciprocal_y)\n\ndef par1(r1, r2):\n return div_interval(mul_interval(r1, r2), add_interval(r1, r2))\n\ndef par2(r1, r2):\n one = interval(1, 1)\n rep_r1 = div_interval(one, r1)\n rep_r2 = div_interval(one, r2)\n return div_interval(one, add_interval(rep_r1, rep_r2))\n\ndef check_par():\n \"\"\"Return two intervals that give different results for parallel resistors.\n\n >>> r1, r2 = check_par()\n >>> x = par1(r1, r2)\n >>> y = par2(r1, r2)\n >>> lower_bound(x) != lower_bound(y) or upper_bound(x) != upper_bound(y)\n True\n \"\"\"\n r1 = interval(2, 1) # Replace this line!\n r2 = interval(1, 2) # Replace this line!\n return r1, r2\n\ndef multiple_references_explanation():\n return \"\"\"Yes, because the more times you use an uncertain value, the greater the error bounds become\"\"\"\n\n# custom function to check if a number is within an interval\ndef is_bounded(intval, num):\n return lower_bound(intval) < num and num < upper_bound(intval)\n\ndef quadratic(x, a, b, c):\n \"\"\"Return the interval that is the range of the quadratic defined by\n coefficients a, b, and c, for domain interval x.\n\n >>> str_interval(quadratic(interval(0, 2), -2, 3, -1))\n '-3 to 0.125'\n >>> str_interval(quadratic(interval(1, 3), 2, -3, 1))\n '0 to 10'\n \"\"\"\n # basically find the range interval of f(t) = a*t^2 + b*t + c within the domain interval 'x'\n fn = lambda t: a * t ** 2 + b * t + c\n xtreme_point, left_point, right_point = fn(-b / (2 * a)), fn(lower_bound(x)), fn(upper_bound(x))\n if is_bounded(x, xtreme_point):\n # check if extreme point is higher than left and right endpoints\n if max([xtreme_point, left_point, right_point]) == xtreme_point:\n return interval(min(left_point, right_point), xtreme_point)\n else:\n return interval(xtreme_point, max(left_point, right_point))\n else:\n return interval(min(left_point, right_point), max(left_point, right_point))\n\ndef polynomial(x, c):\n \"\"\"Return the interval that is the range of the polynomial defined by\n coefficients c, for domain interval x.\n\n >>> str_interval(polynomial(interval(0, 2), [-1, 3, -2]))\n '-3 to 0.125'\n >>> str_interval(polynomial(interval(1, 3), [1, -3, 2]))\n '0 to 10'\n >>> str_interval(polynomial(interval(0.5, 2.25), [10, 24, -6, -8, 3]))\n '18.0 to 23.0'\n \"\"\"\n # the simple (and cheesy) strat is to compute all values of the given polynomal and\n # find the interval from the min and max of the y values\n\n # returns a lambda that allows computing values of the polynomial\n # coefficients are related from highest to lowest exponent\n def get_poly_fn(coeffs):\n exponents = [*range(len(coeffs) - 1, -1, -1)]\n pairs = [*zip(coeffs, exponents)]\n return lambda t: sum([coeff * t ** expo for coeff, expo in pairs])\n\n #used for computing the number of steps and the rounding precision\n precision = 4\n\n low_x, high_x = lower_bound(x), upper_bound(x)\n\n # real_type is used to alter the final type of the lower and upper bounds of the answer,\n # mainly because the autograder is quite picky about it\n # if interval 'c' has floats, the resulting interval with have floats; otherwise, it will have ints\n real_type = float if float in [type(low_x), type(high_x)] else int\n\n # this is used for generating the x values to test\n num_steps = 10 ** precision\n step = (high_x - low_x) / num_steps\n\n # the range function doesn't work for stepping through decimal values\n all_x_vals = [low_x + n * step for n in range(num_steps + 1)]\n\n # we take the reverce array of the coeffs, since get_poly_fn\n # processes them from highest exponent to lowest\n fn = get_poly_fn(c[::-1])\n all_y_vals = [round(fn(x), precision) for x in all_x_vals]\n\n small, big = min(all_y_vals), max(all_y_vals)\n\n # correct the type for the autograder\n big = real_type(big) if big == real_type(big) else big\n small = real_type(small) if small == real_type(small) else small\n\n return interval(small, big)"} {"doc_id": "0e14e25b1a644b63f679f9cbc081f60b", "text": "\"\"\"\nFile: caesar.py\nName: Isabelle\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 User input the secret number and the string.\n The program will shift ALPHABET as cipher table and then encrypt the string.\n \"\"\"\n n=int(input('Secret number: '))\n s=input(\"What's the ciphered string? \").upper()\n new_alphabet=alphabet(n)\n decipher(s,new_alphabet)\n\ndef alphabet(n):\n \"\"\"\n Shift the ALPHABET as cipher table.\n :param n: int, necessary number to shift ALPHABET as cipher table\n :return: str, cipher table\n \"\"\"\n a=''\n for i in range((26-n),26):\n a+=ALPHABET[i]\n for i in range(26-n):\n a+=ALPHABET[i]\n return a\n\ndef decipher(s,x):\n \"\"\"\n Encrypt the string the user input\n :param s: str, string being encrypted\n :param x: str, cipher table\n \"\"\"\n b=''\n for i in s:\n ch=x.find(i)\n if ch==-1:\n # When there is ' ' in the string.\n b+=i\n else:\n b+=ALPHABET[ch]\n print('The deciphered string is: '+b)\n\n##### DO NOT EDIT THE CODE BELOW THIS LINE #####\nif __name__ == '__main__':\n main()\n"} {"doc_id": "0e2da6649aea183546e41448a8c1703b", "text": "'''\nTAO YICHEN\nytao15@binghamton.edu\nLab9\nLab section: B56\nCA: Paul Maino\nLab9,Part1\nPhone: 6079532749\n'''\n#-----------------Part1\na = [1, 2, 3]\nb = a[:]\nb[0] = 5\nprint(a)\nprint(b)\nprint(\"id of a: %d\\nid of %db\\n\"%(id(a),id(b)))\nanswer = a is b\nprint(\"a is b:\",answer)\nprint(\"id of second character of a and b: %d %d\\n\"%(id(a[1]),id(b[1])))\nanswer = a[1] is b[1]\nprint(\"a is b:\",answer)\n\n#-------------------Part2\nmyList=[]\nmyList[len(myList):] =[76]\nmyList[len(myList):] =[92.3]\nmyList[len(myList):] =[\"hello\"]\nmyList[len(myList):] =[True]\nmyList[len(myList):] =[4]\nmyList[len(myList):] =[76]\nprint(myList)\n\n#------------------Part3\n#a. Append \u201capple\u201d and 76 to the list.\nmyList[len(myList):] =[\"apple\",76]\nprint(myList)\n#b. Insert the value \u201ccat\u201d at position 3\nmyList.insert(3,\"cat\")\nprint(myList)\n#c. Insert the value 99 at the start of the list.\nmyList[0] = 99\nmyList.insert(0,99)\nprint(myList)\n#d. Find the index of \u201chello\u201d.\nindex = myList.index(\"hello\")\nprint(index)\n#e. Count the number of 76s in the list.\nprint(myList.count(\"hello\"))\n#f. Remove the first occurrence of 76 from the list.\nmyList.remove(\"hello\")\nprint(myList)\n#g. Remove True from the list using pop and index.\nmyList.pop(myList.index(True))\nprint(myList)\n"} {"doc_id": "0e5ecf323e6c92001f4b1c24c1fe61c9", "text": "\"\"\"\nLinked List Cycle II\n\nGiven a linked list, return the node where the cycle begins. If there is no cycle, return null.\nThere is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next pointer.\nInternally, pos is used to denote the index of the node that tail's next pointer is connected to. Note that pos is not passed as a parameter.\nNotice that you should not modify the linked list\nhttps://leetcode.com/problems/linked-list-cycle-ii/\n\"\"\"\n\n\nclass Solution:\n def detectCycle(self, head):\n if not head:\n return None\n\n fast = head\n slow = head\n\n # find cycle\n while True:\n if fast is None or fast.next is None:\n return None\n\n slow = slow.next\n fast = fast.next.next\n\n if slow == fast:\n break\n\n one = head\n two = fast\n # find cycle start\n while one != two:\n one = one.next\n two = two.next\n return one\n\n\n\"\"\"\nFind Loop:\nWrite a function that takes in the head of a Singly Linked List that contains a loop \n(in other words, the list's tail node points to some node in the list instead of None / null). \nThe function should return the node (the actual node--not just its value) from which the loop originates in constant space.\nEach LinkedList node has an integer value as well as a next node pointing to the next node in the list.\n\nSample Input\n head = 0 -> 1 -> 2 -> 3 -> 4 -> 5 -> 6 // the head node with value 0\n ^ v\n 9 <- 8 <- 7\nSample Output\n 4 -> 5 -> 6 // the node with value 4\n ^ v\n 9 <- 8 <- 7\nhttps://www.algoexpert.io/questions/Find%20Loop\n\"\"\"\n\n\n# This is an input class. Do not edit.\nclass LinkedList:\n def __init__(self, value):\n self.value = value\n self.next = None\n\n\ndef findLoop(head):\n # .next to allow the first loop to work\n p_one = head.next\n p_two = head.next.next\n\n # find meeting point\n while p_two != p_one:\n p_one = p_one.next\n p_two = p_two.next.next\n\n # find start of cycle\n p_one = head\n while p_two != p_one:\n p_one = p_one.next\n p_two = p_two.next\n\n return p_one\n"} {"doc_id": "0e86fea0a11f76e452141a6c39098ab3", "text": "\"\"\"\nFile: weather_master.py\nName:Cherry\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\"\"\"\nLEAVING = -1\n\n\ndef main():\n\t\"\"\"\n\tTODO(step):\n\t1.Let user input one data.If the data is LEAVING,there are no temperatures.\n\t2.Define variables:highest,lowest,average,amount,and cold_day.\n\t3.Let user continuously input data until the data is LEAVING.(while)\n\t4.Redefine the variables.\n\t5.Print the results:Highest temperature,Lowest temperature,Average,and cold day(s).\n\t\"\"\"\n\tprint('stanCode \"Weather Master 4.0\"!')\n\t# step1.Let user input one data.\n\tdata = int(input('Next Temperature: (or -100 to quit)? '))\n\t# If the data is LEAVING,there are no temperatures.\n\tif data == LEAVING:\n\t\tprint('No temperatures were entered.')\n\telse:\n\t\t# step2.Define variables:highest,lowest,average,amount,and cold_day.\n\t\thighest = data\n\t\tlowest = data\n\t\taverage = float(data)\n\t\tamount = 1\n\t\tif data < 16:\n\t\t\tcold_day = 1\n\t\telse:\n\t\t\tcold_day = 0\n\t\twhile True:\n\t\t\t# step3.Let user continuously input data until the data is LEAVING.\n\t\t\tdata = int(input('Next Temperature: (or -100 to quit)? '))\n\t\t\tif data == LEAVING:\n\t\t\t\tbreak\n\t\t\telse:\n\t\t\t\t# step4.Redefine the variables.\n\t\t\t\taverage = average*amount + data\n\t\t\t\tamount += 1\n\t\t\t\taverage = average/amount\n\t\t\t\tif data > highest:\n\t\t\t\t\thighest = data\n\t\t\t\tif data < lowest:\n\t\t\t\t\tlowest = data\n\t\t\t\tif data < 16:\n\t\t\t\t\tcold_day += 1\n\t\t# step5.Print the results:Highest temperature,Lowest temperature,Average,and cold day(s).\n\t\tprint('Highest temperature = ' + str(highest))\n\t\tprint('Lowest temperature = ' + str(lowest))\n\t\tprint('Average = ' + str(average))\n\t\tprint(str(cold_day) + ' cold day(s)')\n\n\n###### DO NOT EDIT CODE BELOW THIS LINE ######\n\nif __name__ == \"__main__\":\n\tmain()\n"} {"doc_id": "0e9277bdac6af5eb125712b0ddd12247", "text": "'''\nExercise 24 from practicepython.org\nThis exercise is Part 1 of 4 of the Tic Tac Toe exercise series. The other exercises are: Part 2, Part 3, and Part 4.\n\nTime for some fake graphics! Let\u2019s say we want to draw game boards that look like this:\n\n --- --- --- \n| | | | \n --- --- --- \n| | | | \n --- --- --- \n| | | | \n --- --- --- \nThis one is 3x3 (like in tic tac toe). Obviously, they come in many other sizes (8x8 for chess, 19x19 for Go, and many more).\n\nAsk the user what size game board they want to draw, and draw it for them to the screen using Python\u2019s print statement.\n'''\n\ndef draw_board(columns, rows):\n def draw_horizontal_dividers(how_many):\n out = \"\"\n for _ in range(how_many):\n out += \" ---\"\n print(out)\n\n def draw_vertical_dividers(how_many):\n out = \"\"\n for _ in range(how_many):\n out += \"\u00a6 \"\n out += \"\u00a6\"\n print(out)\n\n for row in range(rows):\n draw_horizontal_dividers(columns)\n draw_vertical_dividers(columns)\n\n draw_horizontal_dividers(columns)\n\nif __name__ == \"__main__\":\n columns = int(input(\"How many columns? \"))\n rows = int(input(\"How many rows? \"))\n draw_board(columns, rows)"} {"doc_id": "0ea984909d3099d546251357ac65cfe2", "text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n#Author:Winston.Wang\nfrom functools import reduce\nprint(\"---------------\u5f00\u59cbmap\u4e4b\u65c5-------------\")\n'''\nmap()\u51fd\u6570\u63a5\u6536\u4e24\u4e2a\u53c2\u6570\uff0c\u4e00\u4e2a\u662f\u51fd\u6570\uff0c\u4e00\u4e2a\u662fIterable\uff0c\nmap\u5c06\u4f20\u5165\u7684\u51fd\u6570\u4f9d\u6b21\u4f5c\u7528\u5230\u5e8f\u5217\u7684\u6bcf\u4e2a\u5143\u7d20\uff0c\n\u5e76\u628a\u7ed3\u679c\u4f5c\u4e3a\u65b0\u7684Iterator\u8fd4\u56de\n\u6211\u4eec\u6709\u4e00\u4e2a\u51fd\u6570f(x)=x2\uff0c\n\u628a\u8fd9\u4e2a\u51fd\u6570\u4f5c\u7528\u5728\u4e00\u4e2alist [1, 2, 3, 4, 5, 6, 7, 8, 9]\u4e0a\uff0c\n\u5c31\u53ef\u4ee5\u7528map()\u5b9e\u73b0\u5982\u4e0b\n'''\n\ndef m2(x):\n\treturn x*x;\nL = [1, 2, 3, 4, 5, 6, 7, 8, 9]\n#\u53ef\u4ee5\u5c06\u83b7\u53d6\u5230\u7684\u6570\u636e\u4f5c\u4e3a\u4e00\u4e2alist\uff0c\u5b9a\u4e49\u4e00\u4e2a\u89e3\u6790\u7684\u51fd\u6570\u8fdb\u884c\u89e3\u6790\nfor x in map(m2,L):\n\tprint(x);\n#\u628a\u8fd9\u4e2alist\u6240\u6709\u6570\u5b57\u8f6c\u4e3a\u5b57\u7b26\u4e32\nprint(list(map(str,L)));\n'''\n\u518d\u770breduce\u7684\u7528\u6cd5\u3002reduce\u628a\u4e00\u4e2a\u51fd\u6570\u4f5c\u7528\u5728\u4e00\u4e2a\u5e8f\u5217[x1, x2, x3, ...]\u4e0a\uff0c\n\u8fd9\u4e2a\u51fd\u6570\u5fc5\u987b\u63a5\u6536\u4e24\u4e2a\u53c2\u6570\uff0creduce\u628a\u7ed3\u679c\u7ee7\u7eed\u548c\u5e8f\u5217\u7684\u4e0b\u4e00\u4e2a\u5143\u7d20\u505a\u7d2f\u79ef\u8ba1\u7b97\n\uff0c\u5176\u6548\u679c\u5c31\u662f\uff1a\nreduce(f, [x1, x2, x3, x4]) = f(f(f(x1, x2), x3), x4)\n'''\n#\u6c42\u548c\ndef sum(x,y):\n\n\treturn x+y;\nreduceL = list(range(1,100))\nprint(reduce(sum,reduceL))\n# \u628a\u5e8f\u5217[1, 3, 5, 7, 9]\u53d8\u6362\u6210\u6574\u657013579\uff0creduce\u5c31\u53ef\u4ee5\u6d3e\u4e0a\u7528\u573a\ndef change(x,y):\n\treturn x*10+y;\nprint(reduce(change,[1, 3, 5, 7, 9]))\n\n'''\n\u5229\u7528map()\u51fd\u6570\uff0c\u628a\u7528\u6237\u8f93\u5165\u7684\u4e0d\u89c4\u8303\u7684\u82f1\u6587\u540d\u5b57\uff0c\u53d8\u4e3a\u9996\u5b57\u6bcd\u5927\u5199\uff0c\u5176\u4ed6\u5c0f\u5199\u7684\u89c4\u8303\u540d\u5b57\u3002\n\u8f93\u5165\uff1a['adam', 'LISA', 'barT']\uff0c\n\u8f93\u51fa\uff1a['Adam', 'Lisa', 'Bart']\uff1a\n'''\n\ndef normalize(name):\n\treturn name.lower().capitalize();\nprint(list(map(normalize,['adam', 'LISA', 'barT'])))"} {"doc_id": "0eb8348933a4eebf630338be85875d51", "text": "#!/usr/bin/python3.6\n\n\"\"\" functional programming \"\"\"\n# https://maryrosecook.com/blog/post/a-practical-introduction-to-functional-programming\n# https://codesachin.wordpress.com/2016/04/03/a-practical-introduction-to-functional-programming-for-python-coders/\n# https://www.ibm.com/developerworks/library/l-prog/\n\nfrom functools import reduce\n\n\ndef print_list_info(lst_name: str, lst: []) -> None:\n print(\"{0} : {1}\".format(lst_name, lst))\n print(\"length = {0}\".format(len(lst)))\n print('---------------------------------')\n\n\ndef square(x):\n return (x, x**2)\n\n\ndef is_square_even(pair):\n return pair[1]%2 == 0\n\n# zip\nzip_list = list(zip(range(1,10), range(11, 20)))\nprint_list_info(\"zip_list\", zip_list)\n\n\n# map\n# print name length\nname_list = [\"Mary\", \"Isla\", \"Fisher\"]\nname_lengths = list(map(len, name_list))\nprint_list_info(\"name_lengths\", name_lengths)\nname_and_lengths = list(zip(name_list, map(len, name_list)))\nprint_list_info(\"name_and_lengths\", name_and_lengths)\n\nmain_list = range(1, 11)\n\n# square all items in a given list\nsquare_old_way = [(x, x**2) for x in main_list]\nprint_list_info(\"square_old_way\", square_old_way)\n\nsquare_using_map_lambda = list(map(lambda x: (x, x ** 2), main_list))\nprint_list_info(\"square_using_map\", square_using_map_lambda)\n\nsquare_using_map_1 = list(map(square, main_list))\nprint_list_info(\"square_using_map_1\", square_using_map_1)\n### map ###\n\n\n# reduce\nsum = str(reduce(lambda x, a: x + a, main_list, 0))\nprint(\"sum: \" + sum)\n\nproduct = str(reduce((lambda x, y: x * y), main_list, 1))\nprint(\"product: \" + product)\n### reduce ###\n\n\n# filter\neven_squares_lambda = list(filter((lambda x: x[1] % 2 == 0), square_using_map_1))\nprint_list_info(\"even_squares_lambda\", even_squares_lambda)\n\neven_squares_func = list(filter(is_square_even, square_using_map_1))\nprint_list_info(\"even_squares_func\", even_squares_func)\n### filter ###\n"} {"doc_id": "0f37f314a4908dc6b9e53abf13ec26fe", "text": "# Copyright \u00a9 2018 by Shun Huang. All rights reserved.\n# Licensed under MIT License.\n# See LICENSE in the project root for license information.\n\n\"\"\"A binary tree example to demonstrate different tree traversal,\nincluding in-order, pre-order, post-order, and level-order.\n\"\"\"\n\nimport enum # Enum to define traversal types.\n\nfrom typing import NoReturn # For type hints\n\nclass TraversalType(enum.Enum):\n IN_ORDER = enum.auto()\n PRE_ORDER = enum.auto()\n POST_ORDER = enum.auto()\n LEVEL_ORDER = enum.auto()\n\nclass _Node:\n \"\"\"Basic data structure to build a binary tree. This is a private\n class should be used within this module.\n \n Attributes\n ----------\n left: _Node or None\n A pointer points to the left child. If there is no child on the\n left, the value is `None`.\n right: _Node or None\n A pointer points to the right child. If there is no child on\n the right, the value is `None`.\n data: int\n Data of the node.\n \"\"\"\n def __init__(self, data: int):\n self.left = None\n self.right = None\n self.data = data\n\nclass BinaryTree:\n \"\"\"A binary tree with different types of tree traversal.\n\n Methods\n -------\n insert(data: int)\n Inset an item into a binary tree.\n traverse(traversal_type: TraversalType)\n Traverse the tree based on different tree traversals.\n\n Examples\n --------\n >>> from my_package.my_data_structure import my_tree\n >>> tree = my_tree.BinaryTree(data=30)\n >>> tree.insert(10)\n >>> tree.insert(20)\n >>> tree.insert(40)\n >>> tree.insert(50)\n >>> tree.traverse(traversal_type=my_tree.TraversalType.IN_ORDER)\n 10 20 30 40 50\n >>> tree.traverse(traversal_type=my_tree.TraversalType.PRE_ORDER)\n 30 10 20 40 50\n >>> tree.traverse(traversal_type=my_tree.TraversalType.POST_ORDER)\n 20 10 50 40 30\n >>> tree.traverse(traversal_type=my_tree.TraversalType.LEVEL_ORDER)\n 30 10 40 20 50\n \"\"\"\n def __init__(self, data: int):\n self._root = _Node(data=data)\n\n def _insert(self, data: int, node: _Node) -> NoReturn:\n \"\"\"The real implementation of tree insertion.\n\n Parameters\n ----------\n data: int\n The data to be inserted into the tree.\n node: _Node\n The parent node of the input data.\n\n Raises\n ------\n ValueError\n If the input data has existed in the tree, `ValueError`\n will be thrown.\n \"\"\"\n if data == node.data:\n raise ValueError(\"Duplicate value\")\n elif data < node.data:\n if node.left != None:\n self._insert(data=data, node=node.left)\n else:\n node.left = _Node(data=data)\n elif data > node.data:\n if node.right != None:\n self._insert(data=data, node=node.right)\n else:\n node.right = _Node(data=data)\n\n def _inorder_traverse(self, node: _Node):\n \"\"\"In-order traversal.\n\n Parameters\n ----------\n node: _Node\n The parent node of the inseration node.\n\n Notes\n -----\n In-order means Left subtree, current node, right subtree (LDR)\n \"\"\"\n if node:\n self._inorder_traverse(node.left)\n print(node.data, end=\" \")\n self._inorder_traverse(node.right)\n\n def _preorder_traverse(self, node: _Node):\n \"\"\"Pre-order traversal.\n\n Parameters\n ----------\n node: _Node\n The parent node of the inseration node.\n\n Notes\n -----\n Pre-order means Current node, left subtree, right subtree (DLR)\n \"\"\"\n if node:\n print(node.data, end=\" \")\n self._preorder_traverse(node.left)\n self._preorder_traverse(node.right)\n\n\n def _postorder_traverse(self, node: _Node):\n \"\"\"Post-order traversal.\n\n Parameters\n ----------\n node: _Node\n The parent node of the inseration node.\n\n Notes\n -----\n Post-order means Left subtree, right subtree, current node\n (LRD)\n \"\"\"\n if node:\n self._postorder_traverse(node.left)\n self._postorder_traverse(node.right)\n print(node.data, end=\" \")\n\n def _levelorder_traverse(self):\n \"\"\"Level-order traversal.\n\n Parameters\n ----------\n node: _Node\n The parent node of the inseration node.\n\n Notes\n -----\n In-order means Level by level, from left to right, starting\n from the root node.\n \"\"\"\n queue = [self._root]\n\n while len(queue) > 0:\n\n temp = queue.pop(0)\n print(temp.data, end=\" \")\n\n if temp.left:\n queue.append(temp.left)\n\n if temp.right:\n queue.append(temp.right)\n\n def insert(self, data: int) -> NoReturn:\n \"\"\"Insert an item into a binary tree.\n\n Parameters\n ----------\n data: int\n The data to be inserted into the tree.\n\n Raises\n ------\n ValueError\n If the input data has existed in the tree, `ValueError`\n will be thrown.\n \"\"\"\n self._insert(data=data, node=self._root)\n\n def traverse(self, traversal_type: TraversalType) -> NoReturn:\n \"\"\"Traverse the tree based on traversal types.\n\n Parameters\n ----------\n traversal_type: TraversalType\n The type of traversals.\n \n See Also\n --------\n TraversalType : The definition of traversal type\n \"\"\"\n if traversal_type == TraversalType.IN_ORDER:\n self._inorder_traverse(self._root)\n elif traversal_type == TraversalType.PRE_ORDER:\n self._preorder_traverse(self._root)\n elif traversal_type == TraversalType.POST_ORDER:\n self._postorder_traverse(self._root)\n elif traversal_type == TraversalType.LEVEL_ORDER:\n self._levelorder_traverse()\n else:\n raise ValueError(f\"{traversal_type} is invalid\")\n"} {"doc_id": "0f3d4fbdb262ff08a5edf0030db448f0", "text": "\"\"\" A varied but not exhaustive set of the string type and string \n formatting examples.\n\n These examples only get into builtin and standard library\n string formatting in Python.\n \n With the inclusion of third party libraries you will have even more\n templating options.\n\"\"\"\n\n\n# There is a string module, although you probably won't use it much.\nimport string\n# Perhaps the most useful thing on it are the lists of characters, example:\nprint string.letters\nprint string.digits\n\n\n\n# Strings are immutable, iterable lists of characters.\n# All of the strings are equivalent. Strings use backslashes to escape.\nprint \"hello\\nworld\"\nprint 'hello\\nworld'\nprint \"\"\"hello\nworld\"\"\"\n# This unicode string is equivalent visually...\nprint u'hello\\u000Aworld'\n# ...but not type wise.\nprint \"Unicode equal to ascii?\", type(u'hello\\u000Aworld') == ('hello\\nworld')\n# Raw strings prevent escape sequences, good for regular expressions.\nprint r'hello\\nworld'\n# Sample string.\ns = \"i'm a lumberjack and i'm okay\"\n# Strings support index reference and slicing.\nprint \"First letter:\", s[0]\nprint \"First word:\", s[0:3]\nprint \"Last word:\", s[-4:]\nprint \"Copy of the string:\", s[:]\n# Strings cannot be mutated.\ntry:\n s[0] = \"o\"\nexcept TypeError as err:\n print \"Can't change a string:\", err\n# Strings are objects and have methods.\nprint \"Yelling:\", s.upper()\nprint \"Split on ' character:\", s.split(\"'\")\nprint s.replace(\"lumberjack\", \"programmer\")\n# The string calling join is the conjunction.\nprint 'programmer'.join(s.split(\"lumberjack\"))\nprint \"Lumberjack starts at index:\", s.find('lumberjack')\n# There is also strip() and lstrip().\nprint \"No extra newlines\\n\\n\\n\\n\\n\\n\".rstrip()\n\n\n\n# printf style formatting.\nprint 'I would rather be in %s.' % 'Amsterdam'\n# Multiple inputs wrapped in tuple.\nprint \"We always write %s %s!\" % (\"hello\", \"world\")\n# Floating point formatting, here zero filled, 6 total characters,\n# precision of 3.\nprint \"A formatted float: %06.3f\" % 10.5\n# Can also use a dict, which allows mapping by name.\n# dog left justified in a min field of 10 chars.\n# num right justified in a minimum field of 24 chars, explicitly signed.\nprint \"%(dog)-10s -> likes the number -> %(num)+24d\" % {\"dog\": \"fido\", \"num\": 42}\n\n\n\n# .format() style formatting.\n# Implicit argument references.\nprint \"Count to {} then to {}\".format(10, 42)\n# Explicit reference to the second argument (the first arg is not used).\nprint \"Count to {1} then to {1}\".format(10, 42)\n# Note: must use explicit or implicit references, not both.\ntry:\n print \"Count to {} then to {1}\".format(10, 42)\nexcept ValueError as err:\n print \"Error:\", err\n# Data type formatting (using a multiline string).\nprint \"\"\"int: {0:d}\nfloat: {0:f} \nhex: {0:x}\noct: {0:o} \nbin: {0:b}\"\"\".format(42)\n# References labeled argument.\n\"My quest is to find the golden {name}\".format(name=\"nosehairs\")\n# Can reference object and type attributes by name.\nclass Orc(object):\n color = \"green\"\n pass \no = Orc()\n# Implicit reference to the first argument passed in.\nprint \"The orc has {.color} skin\".format(o)\n# First indexed element of keyword argument 'players'.\n\"Good guys eaten by orcs: {goodguys[0]}\".format(goodguys=[42])\n# Left aligned in field of 30.\nprint '{:<30}'.format('left aligned')\n# Right aligned in field of 30.\nprint '{:>30}'.format('right aligned')\n# Centered in a field of 30.\nprint '{:^30}'.format('centered')\n# Centered in a field of 30, white space filled with asterisks.\nprint '{:*^30}'.format('centered') \n# Forced stringification vs. forced pretty printing.\n# (Note: objects may output the same thing. Strings have an obvious\n# difference and are demonstrative of the potential difference.)\nprint \"Stringified object: {!s}\".format(\"hello world\")\nprint \"Pretty printed object: {!r}\".format(\"hello world\")\n\n\n\n# $token string (UNIX shell like substitution).\n# Class from the string module.\nfrom string import Template\n# Need to escape dollar signs. \n# Curly brackets for when delimiter not obvious.\nt = Template('Owner of /$HOME/${user}dir owes $$$cost')\nprint t.substitute(HOME=\"Users\", user=\"lucy\", cost=\"100.00\")\n# dicts can also be passed in.\nd = {\"HOME\":\"Users\", \"cost\":\"OneMillion\"}\n# Error if we're missing some using normal substitue.\ntry:\n print t.substitute(d)\nexcept KeyError as err:\n print \"Substitute error on token:\", err\n# Following does not throw an error, leaves unreplacted tokens.\nprint t.safe_substitute(d)\n\n"} {"doc_id": "0f999234c3d525886faf191bd8492458", "text": "#pembuatan fungsi\r\ndef hitung_gaji():\r\n\tnama=(input(\"masukan Nama anda\"))\r\n\tgol =(input(\"masukan golongan:\"))\r\n\tif gol ==\"1\":\r\n\t\t\tgaji=1000000\r\n\t\t\ttunjungan = 250000\r\n\t\t\ttotal=gaji+tunjangan\r\n\t\t\tprint(f\"Total gaji yang anda terima {total}\")\r\n\telif gol == \"2\":\r\n\t\t\t gaji=2000000\r\n\t\t\t tunjangan = 500000\r\n\t\t\t total=gaji+tunjangan\r\n\t\t\t print(f\"Total gaji yang anda terima {total}\")\r\n\telif gol == \"3\":\r\n\t\t\t gaji=3000000\r\n\t\t\t tunjangan = 700000\r\n\t\t\t total=gaji+tunjangan\r\n\t\t\t print(f\"Total gaji yang anda terima {total}\")\r\n\telse:\r\n\t\t\t print(\"mohon masukan golongan anda\")\r\n\t\t\t \r\n\t#pemanggilan fungsi\r\n\tprint(\"Selamat Datang di Program Hitung Gaji\")\r\n\tprint(\"--------------------------\")\r\n\tdevisi=input(\"masukan devisi anda:\")\r\n\tif devisi == \"kantor\":\r\n\t\t hitung_gaji()\r\n\telif devisi ==\"lapangan\":\r\n\t\thitung_gaji()\r\n\t\ttransportasi=100000\r\n\t\tprint(\"tambahan tunjangan lapangan\",transportasi)\r\n\telse:\r\n\t\tprint(\"devisi yang ada masukan salah\")"} {"doc_id": "1035f4a89343f54ef69efa66f86545c6", "text": "name = input(\"What is your name? \")\nmyAgeStr = input(\"What is your age? \")\nmyAgeInt = int(myAgeStr)\nprint(name, \"next year you will be\", myAgeInt+1)"} {"doc_id": "103e29d4f3a24f0724c13652b4fc80ad", "text": "\n# PROBLEM P5.1\nfrom typing import final\n\n\ndef smallest(x,y,z):\n args=[]\n args.append(x,y,z)\n return min(args)\n\ndef avg(x,y,z):\n return (x + y + z) / 3\n\n# PROBLEM P5.6\ndef countVowels(string):\n vowels = []\n string = string.lower()\n for x in string:\n if x == \"a\":\n vowels.append(x)\n elif x == \"e\":\n vowels.append(x)\n elif x == \"i\":\n vowels.append(x)\n elif x == \"o\":\n vowels.append(x)\n elif x == \"u\":\n vowels.append(x)\n\n return vowels\n\n\n# PROBLEM P5.20\ndef isLeapYear(year):\n if year % 4 != 0:\n return False\n elif year % 100 != 0:\n return True \n elif year % 400 != 0:\n return False\n else:\n return True\n\n\n# PROBLEM P5.28\ndef finnacialAssistance(income, children):\n if income >= 30000 and income <= 40000 and children >= 3:\n return 1000\n elif income >= 20000 and income <= 30000 and children >= 2:\n return 1500\n elif income <= 20000:\n return 2000\n\n# PROBLEM P5.30\ndef strongPassword(string):\n stringLen = len(string) >= 8\n upper = any(x.isupper() for x in string)\n lower = any(x.islower() for x in string)\n digit = any(x.isdigit() for x in string)\n if upper and lower and digit and stringLen:\n return True\n \n\n# PROBLEM P5.6\nprint(\"PROBLEM P5.6\")\nvowels = countVowels(\"EUOUAE\")\nprint(len(vowels)) #should return 6\n\n# PROBLEM P5.20\nprint(\"PROBLEM P5.20\")\nyear = 0\nwhile year != -1:\n year = int(input(\"Enter a year (yyyy): \"))\n Tf = isLeapYear(year)\n if Tf == True:\n print(\"{} is Leap Year!\".format(year))\n else:\n print(\"{} is not a Leap Year!\".format(year))\n\n# PROBLEM P5.28\nprint(\"PROBLEM P5.28\")\nincome = 0\nwhile income != -1 or children != -1:\n income = int(input(\"Enter your income: \"))\n children = int(input(\"Enter how many childs you have: \"))\n if income == -1 or children == -1:\n print(\"Program Terminated!\")\n income, children= -1, -1\n else:\n help = finnacialAssistance(income, children)\n if help == None:\n print(\"You can aquire no finnancial aid.\")\n else:\n print(\"You can aquire {} in finnancial Aid\".format(help))\n \n#PROBLEM P5.30\nprint(\"PROBLEM P5.30\")\nfinished = False\nwhile finished == False:\n password = input(\"Enter a password (must have upper, lower, digit, and be greater than 8 chars): \")\n confirmation = input(str(\"Confirm password: \"))\n if password != confirmation:\n print(\"[!] Passwords do not match [!]\")\n else:\n if strongPassword(password) == True:\n print(\"Your Password is Strong!\")\n finished = True\n else:\n print(\"[!] Your Password is Not Strong Enough [!]\")\n finished = True # uncomment to loop until password is strong\n\n \n"} {"doc_id": "108e9c3fa8e024c9ed2c58b72019f4d7", "text": "\"\"\"OOP examples for module 2\"\"\"\n\nimport pandas as pd\n\nclass MyDataFrame(pd.DataFrame): #inheritance notation, from the pandas library\n def num_cells(self):\n return self.shape[0] * self.shape[1] #this is a method, so we don't need a constructor\n \"\"\"returns number of cells in a dataframe\"\"\"\n\nclass BareMinimumClass: #Capitalize first letter of each word for every class\n pass #we're not doing anything now, don't return any errors\n\nclass Complex:\n def __init__(self, realpart, imagpart):#init = constructor\n \"\"\"\n Constructor for complex numbers.\n Complex numbers have a real part and imaginary part.\n \"\"\"\n self.r = realpart #object created from class template has attribute r. Self referencing the object.\n self.i = imagpart #these are attributes that you can now call\n\n def add(self, other_complex): #create a method\n self.r += other_complex.r\n self.i += other_complex.i\n\n def __repr__(self):\n return '({}, {})'.format(self.r, self.i) #brackets will fill in self.r and self.i, respectively\n \"\"\"\n shows values of self.r and self.i class\n \"\"\"\n\nclass SocialMediaUser:\n def __init__(self, name, location, upvotes=0):\n self.name = str(name)\n self.location = location\n self.upvotes = int(upvotes)\n\n def receive_upvotes(self, num_upvotes=1)\n self.upvotes += num_upvotes\n\n def is_popular(self): #boolean true/false, so used 'is'\n return self.upvotes > 100\n\n\nclass Animal:\n \"\"\"General Representation of Animals\"\"\"\n def __init__(self, name, weight, diet_type):\n self.name = str(name)\n self.weight = float(weight)\n self.diet_type = diet_type\n\n def run(self):\n return \"Vroom, Vroom, I go quick\"\n\n def eat(self, food):\n return \"Huge fan of that \" + str(food)\n\nclass Sloth(Animal): #inheriting Animal to the Sloth class\n def __init__(self, name, weight, diet_type, num_naps_):\n super().__init__(name, weight, diet_type) #super refers to the parent class\n self.num_naps = int(num_naps)\n\n def say_somthing(self):\n return \"This is a sloth of typing\"\n\n def run(self):\n return \"I am a slow sloth guy\" #this will override the Animal class run()\n\nif __name__ == '__main__': #tells python the code inside here should only be executed if we run this module oop_example.py\"\n num1 = Complex(3, 5) #created two objects\n num2 = Complex(4, 2)\n num1.add(num2)\n print(num1.r, num1.i)\n\n user1 = SocialMediaUser('Justin','Provo')\n user2 = SocialMediaUser('Nick','Logan',200)\n user3 = SocialMediaUser('Carl','Costa Rica',upvotes=100000)\n user4 = SocialMediaUser('George Washington','Djibouti', 2)\n print('name: {}, is popular: {}, num upvotes: {}'.format(user4.name, user4.ispopular(), user4.upvotes))\n #.is_popular() needs parentheses, .upvotes doesn't need it.\n #diff between method() and attribute.\n print('name: {}, is popular: {}, num upvotes: {}'.format(user3.name, user3.is_popular(), user3.upvotes))"} {"doc_id": "10a19641b8028263e1396fef7afa966b", "text": "from collections import deque\nimport asyncio\n\n__version__ = '0.2.0'\n\n\nclass HistoryQueue:\n def __init__(self, history_size=None, max_backlog=0, loop=None):\n \"\"\"``asyncio.Queue`` with history.\n\n Objects put on a ``HistoryQueue`` are gathered in tuples,\n with the first element being the next item on the queue,\n followed by items add previously.\n\n ``HistoryQueue`` can also be thought of as as asynchronous ``collections.deque``,\n with ``put`` analogous to ``deque.appendleft``\n and ``get`` returning the entire deque (as a tuple).\n\n Up to ``history_size + 1`` items are returned in each tuple.\n If `history_size` is ``None``, then each tuple will contain the entire history of the queue.\n\n If `max_backlog` is less than or equal to zero, the queue size is infinite.\n If it is an integer greater than ``0``,\n then ``await put()``will block when the queue contains `max_backlog` items,\n until an item is removed by ``get``.\n\n If the queue is empty, ``await get()`` will block until an item is added to the queue.\n\n Parameters\n ----------\n history_size : int, optional\n The number of items, in addition to the \"current\" item, to return from ``get``.\n When `history_size` is ``None``, then entire history is returned.\n Serves a similar purpose as ``collections.deque.maxlen``.\n max_backlog : int, optional\n The number of items to save before the queue is considered full.\n If `max_backlog` is ``0``, the queue is never full.\n Analogous to ``asyncio.Queue.maxsize``.\n loop : ``asyncio.BaseEventLoop``, optional\n The event loop that will be managing the queue.\n\n Attributes\n ----------\n history_size\n max_backlog\n\n Raises\n ------\n ``QueueEmpty``\n When ``get_nowait`` is called on an empty queue.\n ``QueueFull``\n When ``put_nowait`` is called on a full queue.\n\n See Also\n --------\n ``asyncio.Queue``\n ``collections.deque``\n\n Notes\n -----\n This class is ``not thread safe``.\n\n Examples\n --------\n For ease of illustration, in these examples we use ``put_nowait`` and ``get_nowait``,\n the synchronous counterparts of ``put`` and ``wait``, respectively.\n In a coroutine, ``await put()`` could be used to block until the queue is not full,\n and ``await get()`` to block until there is an item in the queue.\n\n >>> from hqueue import HistoryQueue\n >>> hq = HistoryQueue(history_size=2)\n >>> hq.put_nowait(0)\n >>> hq.put_nowait(1)\n >>> hq.get_nowait()\n (0,)\n >>> hq.get_nowait()\n (1, 0)\n >>> hq.put_nowait(2)\n >>> hq.put_nowait(3)\n >>> hq.put_nowait(4)\n >>> hq.get_nowait()\n (2, 1, 0)\n >>> hq.get_nowait()\n (3, 2, 1)\n\n \"\"\"\n self.history_size = history_size\n self.max_backlog = max_backlog\n\n self._deque = deque(maxlen=history_size if history_size is None else history_size + 1)\n self._queue = asyncio.Queue(maxsize=max_backlog, loop=loop)\n\n def backlog_empty(self):\n \"\"\"Return ``True`` if the queue is empty ,``False`` otherwise.\n\n Returns\n -------\n bool\n\n \"\"\"\n return self._queue.empty()\n\n def backlog_full(self):\n \"\"\"\n Return ``True`` if there are `max_backlog` items in the queue.\n\n Returns\n -------\n bool\n\n \"\"\"\n return self._queue.full()\n\n def history_full(self):\n \"\"\"Return ``True`` if at least ``history_size + 1`` items have been put on the queue.\n\n Returns\n -------\n bool\n\n \"\"\"\n return len(self._deque) == self._deque.maxlen\n\n async def get(self):\n \"\"\"Return the current item on the queue, with history (if any).\n If queue is empty, wait until an item is available.\n\n Returns\n -------\n tuple\n\n \"\"\"\n return await self._queue.get()\n\n def get_nowait(self):\n \"\"\"Return the current item on the queue, with history (if any).\n If no item is immediately available, raise |QueueEmpty|.\n\n Returns\n -------\n tuple\n\n \"\"\"\n return self._queue.get_nowait()\n\n async def put(self, item):\n \"\"\"Put an item into the queue.\n If the queue is full, wait until a free slot is available.\n\n Parameters\n ----------\n item\n\n \"\"\"\n self._deque.appendleft(item)\n await self._queue.put(self._as_tuple())\n\n def put_nowait(self, item):\n \"\"\"Put an item into the queue.\n If no slot is immediately available, raise |QueueFull|.\n\n Parameters\n ----------\n item\n\n \"\"\"\n initial_deque = self._deque.copy()\n self._deque.appendleft(item)\n try:\n self._queue.put_nowait(self._as_tuple())\n except asyncio.QueueFull:\n # If the QueueFull exception is caught, pretend nothing happened.\n self._deque = initial_deque\n raise\n\n def backlog_size(self):\n \"\"\"Number of items in the queue.\n\n Returns\n -------\n int\n\n \"\"\"\n return self._queue.qsize()\n\n def clear_history(self):\n \"\"\"\"Clears the history.\n All items already put on the queue will remain,\n but the next item put on the queue will have no history associated with it\n when it is eventually returned.\n\n \"\"\"\n self._deque = deque(maxlen=self.history_size + 1)\n\n def _as_tuple(self):\n return tuple(self._deque)\n\n def __repr__(self):\n return '<{} at {} history_size={}, max_backlog={}>'.format(\n type(self).__name__, hex(id(self)), self.history_size, self.max_backlog,\n )\n"} {"doc_id": "10eabd33a8f2d5ef69424a5bd821e840", "text": "class Calculator:\n \"\"\"\n A class used for basic mathematical functions.\n\n ...\n\n Attributes\n ----------\n None\n\n Methods\n -------\n memory():\n Returns value of memory.\n memory_reset():\n Resets value of memory.\n add(a, b=None):\n Adds two integer numbers.\n subract(a, b=None):\n Subtracts two integer numbers.\n multiplicate(a, b=None):\n Multiplicates two integer numbers.\n divide(a, b=None):\n Divides two integer numbers.\n root(root, num=None)\n Takes (num) root of number.\n \"\"\" \n\n def __init__(self) -> None:\n self.__memory = 0\n \n @property\n def memory(self):\n \"\"\"\n Returns value of memory.\n\n Parameters\n ----------\n None\n\n Returns\n ------\n self.__memory : int\n Current value of memory.\n \"\"\"\n return self.__memory\n\n def memory_reset(self):\n \"\"\"\n Resets value of memory to 0 (zero).\n\n Parameters\n ----------\n None\n\n Returns\n ------\n None\n \"\"\"\n self.__memory = 0\n\n def add(self, a: int, b: int = None) -> int:\n \"\"\"\n Adds two integer numbers.\n\n If the argument \"b\" isn't passed in, the value of memory is used. \n\n Parameters\n ----------\n a : int\n A decimal integer.\n b : int, optional\n Another decimal integer (default is None).\n\n Returns\n ------\n result : int\n Sum of a and b.\n \"\"\"\n if b == None:\n result = self.__memory + a\n self.__memory = result\n return result\n else:\n result = a + b\n self.__memory = result\n return result\n\n def subtract(self, a: int, b: int = None) -> int:\n \"\"\"\n Subtracts two integer numbers.\n\n If the argument \"b\" isn't passed in, the value of memory is used.\n\n Parameters\n ----------\n a : int\n A decimal integer.\n b : int, optional\n Another decimal integer (default is None).\n\n Returns\n ------\n result : int\n Result of subtraction of a and b.\n \"\"\"\n if b == None:\n result = self.__memory - a\n self.__memory = result\n return result\n else:\n result = a - b\n self.__memory = result\n return result\n\n def multiplicate(self, a: int, b: int = None) -> int:\n \"\"\"\n Multiplicates two integer numbers.\n\n If the argument \"b\" isn't passed in, the value of memory is used.\n\n Parameters\n ----------\n a : int\n A decimal integer.\n b : int, optional\n Another decimal integer (default is None).\n\n Returns\n ------\n result : int\n Result of multiplication of a and b.\n \"\"\"\n if b == None:\n result = self.__memory * a\n self.__memory = result\n return result\n else:\n result = a * b\n self.__memory = result\n return result\n\n def divide(self, a: int, b: int = None) -> float:\n \"\"\"\n Divides two integer numbers.\n\n If the argument \"b\" isn't passed in, the value of memory is used.\n\n Parameters\n ----------\n a : int\n A decimal integer.\n b : int, optional\n Another decimal integer (default is None).\n\n Returns\n ------\n result : float\n Result of division of a and b.\n Error handling : str\n \"You cannot divide by zero!\" string if catches ZeroDivisionError,\n when trying to divide by zero. \n \"\"\"\n try:\n if b == None:\n result = self.__memory / a\n self.__memory = result\n return result\n else:\n result = a / b\n self.__memory = result\n return result\n except ZeroDivisionError:\n return \"You cannot divide by zero!\"\n\n def root(self, root: int, num: int = None) -> float:\n \"\"\"\n Takes (nth) root of number.\n\n If the argument \"num\" isn't passed in, the value of memory is used.\n\n Parameters\n ----------\n root : int\n The number (degree) of root.\n b : int, optional\n Decimal integer (default is None).\n\n Returns\n ------\n result : float\n Result of (nth) root of number.\n \"\"\"\n if num == None:\n result = self.__memory ** (1 / root)\n self.__memory = result\n return result\n else:\n result = num ** (1 / root)\n self.__memory = result\n return result"} {"doc_id": "11056eb48ef5147f82388600195cafe2", "text": "print('====== DESAFIO 30 ======')\nnum = int(input('Digite um um n\u00famero: '))\ncalc = num % 2\nif calc == 0:\n print('O N\u00famero {} \u00e9: PAR'.format(num))\nelse:\n print('O N\u00famero \u00e9: \u00cdMPAR'.format(num))"} {"doc_id": "112813b9a729f96203ccc1ee4802807d", "text": "\"\"\"\n

In a given integer array nums, there is always exactly one largest element.

\n\n

Find whether the largest element in the array is at least twice as much as every other number in the array.

\n\n

If it is, return the index of the largest element, otherwise return -1.

\n\n

Example 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\n
    \n\t
  1. nums will have a length in the range [1, 50].
  2. \n\t
  3. Every nums[i] will be an integer in the range [0, 99].
  4. \n
\n\n

 

\n

\u5728\u4e00\u4e2a\u7ed9\u5b9a\u7684\u6570\u7ec4nums\u4e2d\uff0c\u603b\u662f\u5b58\u5728\u4e00\u4e2a\u6700\u5927\u5143\u7d20 \u3002

\n\n

\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\n
    \n\t
  1. nums \u7684\u957f\u5ea6\u8303\u56f4\u5728[1, 50].
  2. \n\t
  3. \u6bcf\u4e2a nums[i] \u7684\u6574\u6570\u8303\u56f4\u5728 [0, 99].
  4. \n
\n

\u5728\u4e00\u4e2a\u7ed9\u5b9a\u7684\u6570\u7ec4nums\u4e2d\uff0c\u603b\u662f\u5b58\u5728\u4e00\u4e2a\u6700\u5927\u5143\u7d20 \u3002

\n\n

\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\n
    \n\t
  1. nums \u7684\u957f\u5ea6\u8303\u56f4\u5728[1, 50].
  2. \n\t
  3. \u6bcf\u4e2a nums[i] \u7684\u6574\u6570\u8303\u56f4\u5728 [0, 99].
  4. \n
\n\"\"\"\n\n\nclass Solution(object):\n def dominantIndex(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n "} {"doc_id": "112873923126ea28ba5c9f11a0cd92a9", "text": "\"\"\"\n

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.

\n

\nFind the maximum area of an island in the given 2D array.\n(If there is no island, the maximum area is 0.)\n

\n

Example 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\n

Example 2:
\n

[[0,0,0,0,0,0,0,0]]
\nGiven the above grid, return 0.\n

\n\n

Note:\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

\n\n

\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

\n\n

\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

\n\n

\u6ce8\u610f: \u7ed9\u5b9a\u7684\u77e9\u9635grid \u7684\u957f\u5ea6\u548c\u5bbd\u5ea6\u90fd\u4e0d\u8d85\u8fc7 50\u3002

\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

\n\n

\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

\n\n

\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

\n\n

\u6ce8\u610f: \u7ed9\u5b9a\u7684\u77e9\u9635grid \u7684\u957f\u5ea6\u548c\u5bbd\u5ea6\u90fd\u4e0d\u8d85\u8fc7 50\u3002

\n\"\"\"\n\n\nclass Solution:\n def maxAreaOfIsland(self, grid):\n \"\"\"\n :type grid: List[List[int]]\n :rtype: int\n \"\"\"\n "} {"doc_id": "11843e4f4fcca6df5f4a3b65423d79c0", "text": "# Patient Class initialised with name, age, gender\n# addSymptom expects a symptom object created elsewhere, and adds it to a list of symptoms\n# patientInfo() prints out the patient name and each symptom and its info...\n\nclass patient:\n def __init__(self, name, age, gender):\n self.name = str(name)\n self.age = int(age)\n self.gender = str(gender)\n self.symptoms = []\n\n def addSymptom(self, symptom):\n self.symptoms.append(symptom)\n\n def getAge(self):\n return self.age\n\n def getSymptoms(self):\n return list(self.symptoms)\n\n def getName(self):\n return self.name\n\n def getGender(self):\n return self.gender\n\n def patientInfo(self):\n print(\"--------- START OF PATIENT ---------\")\n print((\"PATIENT INFO: \" + \"Name: \" + self.name + \" Age: \" + str(self.age) + \" Gender: \" + self.gender))\n for i in self.symptoms:\n print(i.toString())\n print(\"--------- END OF PATIENT ---------\")\n\n\n\n\n\n"} {"doc_id": "119ba7acd7b4b6f3eac3e1d239164495", "text": "class Point:\n def __init__(self, x, y):\n self.x = x\n self.y = y\n\n def setX(self, newX):\n self.x = newX\n\n def display(self):\n print(\"({},{})\".format(self.x, self.y), end='')\n\n def __repr__(self) -> str:\n return \"({},{})\".format(self.x, self.y)\n\nclass LabeledPoint(Point):\n def __init__(self, x, y, label):\n #self.x = x\n #self.y = y\n super().__init__(x, y)\n self.label = label\n\n def display(self):\n super().display()\n print(self.label)\n\n def __repr__(self) -> str:\n s = super().__repr__() # call parent's repr\n return \"{} {}\".format(s, self.label)\n\n def getLabel(self) -> str:\n return self.label\n\np = Point(5, 10)\np.display()\nprint(\"\\n----------------\")\nlp = LabeledPoint(20, 30, \"Bravo\")\nlp.display()\n\npoints = [Point(5, 10), Point(20, 30), LabeledPoint(20, 30, \"Bravo\"), Point(6, 7)]\n\nfor p in points:\n p.setX(p.x + 10)\n if isinstance(p, LabeledPoint):\n print(p.getLabel())\n\nprint(points)"} {"doc_id": "11a74adfafc08202404a8db4ae7577c3", "text": "\"\"\"\n

Given an input string (s) and a pattern (p), implement regular expression matching with support for '.' and '*'.

\n\n
\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\n

Note:

\n\n\n\n

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

\n\n
'.' \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

\n\n

\u8bf4\u660e:

\n\n\n\n

\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

\n\n
'.' \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

\n\n

\u8bf4\u660e:

\n\n\n\n

\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.
\n# __Follow the instructions__ and insert your code! You are either requested to \n# - Complete the Code and __Fill in the gaps__. Gaps are marked with \"__---__\" and are __placeholders__ for your code fragment. \n# - Write Code completely __on your own__ \n\n# In some exercises, you will find questions that can only be answered, if your code is correct and returns the right output! The correct answer is provided below your coding cell. There you can check whether your code is correct.\n\n# If you need a hint, check the __Hints Section__ at the end of this Notebook. Exercises and Hints are numerated accordingly.\n\n# If you need some further help or if you want to check your code, you can also check the __solutions notebook__.\n\n# ### Have Fun!\n\n# --------------------------------------------------------------------------------------------------------------\n\n# ## Option 1: Self_guided\n\n# __Import__ the cars dataset from the csv-file __cars_unclean.csv__ and inspect. Then, __clean up__ the dataset:\n# \n# - Identify and handle __inconsistent data__\n# - Each column/feature should have the __appropriate/most functional datatype__\n# - Identify and handle __missing values__\n# - Identify and handle __duplicates__\n# - Have a closer look into columns with __strings__ and clean up\n# - Identify and handle __erroneous outliers__ in numerical columns\n# (hint: there might be a \"fat finger\" issue in one column and some value(s) in the mpg column could be in \"gallons per mile\" units)\n# - __Save and export__ the cleaned dataset in a new csv-file (cars_clean.csv)\n# - Change the datatype of appropriate columns to __categorical__.\n\n# --------------------------\n\n# ## Option 2: Guided and Instructed\n\n# # STOP HERE, IF YOU WANT TO DO THE EXERCISE ON YOUR OWN!\n\n# +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n\n# In[ ]:\n\n\n# run the cell!\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\n# In[ ]:\n\n\n# run the cell!\ncars = pd.read_csv(\"cars_unclean.csv\")\n\n\n# __Inspect__ the DataFrame and identify obviously __inconsistent data__!\n\n# In[ ]:\n\n\n# run the cell!\ncars.head(20)\n\n\n# In[ ]:\n\n\n# run the cell!\ncars.tail(10)\n\n\n# In[ ]:\n\n\n# run the cell! \ncars.info()\n\n\n# 85. __Identify__ one __column label__ that should be changed and adjust/__rename__ the column label! __Fill in the gaps__!\n\n# In[ ]:\n\n\ncars.rename(columns = {\"model year\": \"model_year\"}, inplace = True)\n\n\n# 86. Have a closer look to the __origin__ column by analyzing the __frequency/count__ of unique values! Can you find __any inconsistency__?\n\n# In[ ]:\n\n\ncars.origin.value_counts()\n\n\n# There are the values ... usa and United States\n\n# 87. __Replace__ the value __\"United States\"__ in the origin column! __Save__ the change!\n\n# In[ ]:\n\n\ncars.origin.replace(\"United States\", \"usa\", inplace = True)\n\n\n# Inspect and __identify__ the __problem__ in the column __horsepower__!\n\n# In[ ]:\n\n\n# run the cell!\ncars.horsepower.head()\n\n\n# Datatype should be ... numerical. But first of all, we need to remove...?\n\n# 88. Apply the appropriate __string operation__ to __remove \"hp\"__ from the horsepower column! Pay attention to __whitespaces__! __Overwrite__ the horsepower column!\n\n# In[ ]:\n\n\ncars.horsepower = cars.horsepower.str.replace(\" hp\", \"\")\n\n\n# In[ ]:\n\n\n# run the cell and inspect!\ncars.head()\n\n\n# Run and inspect, anything __strange__?\n\n# In[ ]:\n\n\n#run the cell!\npd.options.display.min_rows = None\n\n\n# In[ ]:\n\n\n# run the cell!\ncars.horsepower.value_counts()\n\n\n# There are 6 entries with the value ... \"Not available\"\n\n# 89. Create __\"real\" missing values__ in the column horsepower! __Save__ the change! __Fill in the gaps__!\n\n# In[ ]:\n\n\ncars.horsepower.replace(\"Not available\", np.nan, inplace = True)\n\n\n# 90. Now you can __convert the datatype__ in the column __horsepower__! __Overwrite__ the column!\n\n# In[ ]:\n\n\ncars.horsepower = cars.horsepower.astype(\"float\")\n\n\n# Inspect!\n\n# In[ ]:\n\n\n# run the cell!\ncars.info()\n\n\n# In[ ]:\n\n\n# run the cell!\ncars.head(7)\n\n\n# Any __inconsistencies__ in the column __name__? Inspect one element! \n\n# In[ ]:\n\n\n#run the cell!\ncars.loc[4, \"name\"]\n\n\n# It seems like some names are uppercase, while others are lowercase. And there are some excess whitespaces in the strings.\n\n# 91. __Convert__ all names to __lowercase__ and __remove all whitespaces__ on the left ends and right ends!\n\n# In[ ]:\n\n\ncars.name = cars.name.str.lower().str.strip()\n\n\n# Run the next two cells and identify (erroneous) outliers in the numercial columns!\n\n# In[ ]:\n\n\n# run the cell!\ncars.describe()\n\n\n# In[ ]:\n\n\n# run the cell!\ncars.plot(subplots = True, figsize = (15,12))\nplt.show()\n\n\n# 92. Inspect the column __model_year__ in more detail by analyzing the __frequency/counts__ of unique values! Anything __strange__?\n\n# In[ ]:\n\n\ncars.model_year.value_counts()\n\n\n# There are 5 entries with ... 1973 instead of 73. \n\n# 93. __Replace__ the value __1973__! __Save__ the change!\n\n# In[ ]:\n\n\ncars.model_year.replace(1973, 73, inplace = True)\n\n\n# 94. Inspect the column __weight__ by __sorting__ the values from __high to low__. Can you see the __extreme value__?\n\n# In[ ]:\n\n\ncars.weight.sort_values(ascending = False)\n\n\n# The by far highest value is ... 23000 lbs. Must be an error!\n\n# 95. __Select__ the complete __row__ of the outlier with the method __idxmax()__!\n\n# In[ ]:\n\n\ncars.loc[cars.weight.idxmax()]\n\n\n# It\u00b4s an opel manta ... could be a \"fat finger\" problem, weight could be 2300 instead of 23000.\n# \n\n# 96. __Overwrite__ the erroneous outlier! __Fill in the gaps__!\n\n# In[ ]:\n\n\ncars.loc[cars.weight.idxmax(), \"weight\"] = 2300\n\n\n# Inspect the column __mpg__! Any strange __outlier__?\n\n# In[ ]:\n\n\n# run the cell!\ncars.mpg.sort_values()\n\n\n# An mpg of ... 0.060606 cannot be correct...\n\n# 97. __Select__ the complete __row__ of the outlier with the method __idxmin()__!\n\n# In[ ]:\n\n\ncars.loc[cars.mpg.idxmin()]\n\n\n# 98. After some research we have found out that this extreme value is in __\"gallons per mile\"__ units instead of \"miles per gallon\".
\n# __Convert__ to __\"miles per gallon\"__ units! __Fill in the gaps__!\n\n# In[ ]:\n\n\ncars.loc[cars.mpg.idxmin(), \"mpg\"] = 1/cars.loc[cars.mpg.idxmin(), \"mpg\"]\n\n\n# 99. Next, select all __rows__ with at least one __missing__/na value! __Fill in the gaps__!\n\n# In[ ]:\n\n\ncars.loc[cars.isna().any(axis = 1)]\n\n\n# There are 6 cars, where the horsepower is unknown.\n\n# 100. As horsepower is an important feature in the cars dataset, we decide to remove all 6 rows. __Remove__ and __save__ the change!\n\n# In[ ]:\n\n\ncars.dropna(inplace= True)\n\n\n# Now let\u00b4s find __duplicates__. First, we need to understand __which columns__ we have to take into consideration to identify duplicates.\n\n# 101. The first __naive assumption__ is that two cars cannot have the __same name__. Let\u00b4s count the number of __name-duplicates__. __Fill in the gaps__!\n\n# In[ ]:\n\n\ncars.duplicated(subset = [\"name\"]).sum()\n\n\n# There are ... 86 potential duplicates to remove.\n\n# 102. Let\u00b4s inspect the __duplicated pairs__ by selecting __all instances__ of a name duplicate! __Fill in the gaps__!
\n# Should the __name__ be the __only criteria__ to identify duplicates?\n\n# In[ ]:\n\n\ncars.loc[cars.duplicated(subset = [\"name\"], keep = False)].sort_values(\"name\")\n\n\n# No! Cars can have several vintages/model_year and several variants with different technical specifications (e.g. weight, horsepower) \n\n# 103. To be on the safe side, let\u00b4s include __all columns__ to identify duplicates. __Count__ the number of duplicates! __Fill in the gaps__!\n\n# In[ ]:\n\n\ncars.duplicated().sum()\n\n\n# There are ... 10 potential duplicates.\n\n# 104. Let\u00b4s inspect the __duplicated pairs__ by selecting __all instances__ of a duplicate! __Fill in the gaps__!\n\n# In[ ]:\n\n\ncars.loc[cars.duplicated(keep = False)].sort_values(\"name\")\n\n\n# All pairs seem to be real duplicates.\n\n# 105. __Drop one instance__ of each duplicated pair! __Save__ the change!\n\n# In[ ]:\n\n\ncars.drop_duplicates(inplace = True)\n\n\n# In[ ]:\n\n\n# run the cell\ncars.head()\n\n\n# In[ ]:\n\n\n# run the cell!\ncars.info()\n\n\n# 106. Our dataset seems to be pretty clean now! __Save__ and __export__ to a new csv-file (cars_clean.csv)! Do not export the RangeIndex!\n\n# In[ ]:\n\n\ncars.to_csv(\"cars_clean.csv\", index= False)\n\n\n# Call the __describe()__ method on all __non-numerical columns__!\n\n# In[ ]:\n\n\n# run the cell!\ncars.describe(include = \"O\")\n\n\n# Are there any __categorical features__ (only few unique values) where the datatype could be __converted to \"category\"__?
\n# 107. If so, __convert__ and __overwrite__ the column(s)!\n\n# In[ ]:\n\n\ncars.origin = cars.origin.astype(\"category\")\n\n\n# __Inspect__. Did we __reduce memory usage__?\n\n# In[ ]:\n\n\n#run the cell!\ncars.info()\n\n\n# Yes, we reduced memory usage!\n\n# # Well Done!\n\n# -----------------------------------------\n\n# # Hints (Spoiler!)\n\n# 85. rename() method, column \"model year\"\n\n# 86. value_counts() method\n\n# 87. replace() method\n\n# 88. string(str) method replace(), \" hp\"\n\n# 89. replace() method, np.nan\n\n# 90. astype() method, \"float\"\n\n# 91. string(str) methods lower() and strip()\n\n# 92. value_counts() method\n\n# 93. replace() method\n\n# 94. sort_values() method\n\n# 95. Filter cars with cars.weight.idxmax()\n\n# 96. cars.weight.idxmax(), \"weight\"\n\n# 97. Filter cars with cars.mpg.idxmin()\n\n# 98. cars.mpg.idxmin(), \"mpg\", 1/x\n\n# 99. methods isna() and any()\n\n# 100. dropna() method\n\n# 101. subset parameter, \"name\"\n\n# 102. keep parameter\n\n# 103. methods duplicated() and sum()\n\n# 104. keep parameter\n\n# 105. drop_duplicates() method\n\n# 106. to_csv() method\n\n# 107. astype() method\n"} {"doc_id": "11e1a0f3fc535c2d6407256dbe793599", "text": "\"\"\"\nFile: complement.py\nName: Po Kai Feng\n----------------------------\nThis program uses string manipulation to\ntackle a real world problem - finding the\ncomplement strand of a DNA sequence.\nTHe program asks uses for a DNA sequence as\na python string that is case-insensitive.\nYour job is to output the complement of it.\n\"\"\"\n\n\ndef main():\n \"\"\"\n User will key in a DNA strand, then this code will give him the DNA's complement.\n \"\"\"\n dna = input('Please give me a DNA strand and I\\'ll find the complement: ')\n dna = dna.upper()\n # Makes case insensitive.\n print('The complement of ' + dna + ' is ' + build_complement(dna))\n\n\ndef build_complement(dna):\n \"\"\"\n :param dna: str, the DNA strand that user gives(all letters are upper case)\n :return: str, the complement of dna\n \"\"\"\n new_dna = ''\n for base in dna:\n if base == 'A':\n new_dna += 'T'\n elif base == 'T':\n new_dna += 'A'\n elif base == 'G':\n new_dna += 'C'\n elif base == 'C':\n new_dna += 'G'\n return new_dna\n\n\n###### DO NOT EDIT CODE BELOW THIS LINE ######\nif __name__ == '__main__':\n main()\n"} {"doc_id": "1232e13fae0caac34ff44e32946b8235", "text": "\"\"\"\n insertion_sort.py\n\n This module implements insertion sort on an unsorted list and returns a sorted list.\n\n Insertion Sort Overview:\n ------------------------\n Uses insertion of elements in to the list to sort the list.\n\n Pre: an unsorted list[0,...,n] of integers.\n\n Post: returns a sorted list[0,...,n] in ascending order.\n\n Time Complexity: O(n^2)\n\n Space Complexity: O(n) total\n\n Stable: Yes\n\n Psuedo Code: CLRS. Introduction to Algorithms. 3rd ed.\n\n insertion_sort.sort(list) -> sorted_list\n\"\"\"\n\n\ndef sort(seq):\n for n in range(1, len(seq)):\n item = seq[n]\n hole = n\n while hole > 0 and seq[hole - 1] > item:\n seq[hole] = seq[hole - 1]\n hole = hole - 1\n seq[hole] = item\n return seq\n"} {"doc_id": "1238e5c8f02784b44aa746417c179511", "text": "\"\"\"\nCrie um programa que leia dois valores e mostre um menu como o abaixo na tela:\n[ 1 ] Somar\n[ 2 ] Multiplicar\n[ 3 ] Maior\n[ 4 ] Novos N\u00fameros\n[ 5 ] Sair do Programa\nSeu programa dever\u00e1 realizar a opera\u00e7\u00e3o solicitada em cada caso.\n\"\"\"\n\nnum1 = int(input('Digite um valor: '))\nnum2 = int(input('Digite outro valor: '))\n\n\nwhile True:\n print('----------------------------------')\n resp = int(input('O que deseja fazer: \\n' \n'[ 1 ] Somar\\n'\n'[ 2 ] Multiplicar\\n'\n'[ 3 ] Maior\\n'\n'[ 4 ] Novos N\u00fameros\\n'\n'[ 5 ] Sair do Programa\\n'\n'RESPOSTA: '))\n\n if resp == 1:\n print(f'A soma foi: {num1 + num2}.')\n elif resp == 2:\n print(f'O produto foi: {num1 * num2}.')\n elif resp == 3:\n if num1 > num2:\n print(f'O {num1} \u00e9 maior que o {num2}.')\n else:\n print(f'O {num2} \u00e9 maior que o {num1}.')\n elif resp == 4:\n num1 = int(input('Digite um valor: '))\n num2 = int(input('Digite outro valor: '))\n elif resp == 5:\n print('FINALIZANDO...')\n break\n else:\n print('Digite um n\u00famero de 1 a 5!')\n"} {"doc_id": "124c5f1ac8bbee403d31a160a1535a2a", "text": "#!/usr/bin/env python\n# coding: utf-8\n\n# In[ ]:\n\n\n### Welcome to the Noah's Black Jack Game\n\n'''\nCreate a deck of 52 cards\nShuffle the deck\nAsk the Player for their bet\nMake sure that the Player's bet does not exceed their available chips\n\nDeal two cards to the Dealer and two cards to the Player\nShow only one of the Dealer's cards, the other remains hidden\nShow both of the Player's cards\nAsk the Player if they wish to Hit, and take another card\nIf the Player's hand doesn't Bust (go over 21), ask if they'd like to Hit again.\nIf a Player Stands, play the Dealer's hand. The dealer will always Hit until the Dealer's value meets or exceeds 17\nDetermine the winner and adjust the Player's chips accordingly\nAsk the Player if they'd like to play again\n\n'''\nimport random\nimport time\nfrom IPython.display import clear_output\n\nall_cards = []\n\nsuits = ('Hearts', 'Diamonds', 'Spades', 'Clubs')\n\nranks = ('Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Jack', 'Queen', 'King', 'Ace')\n\nvalues = {'Two':2, 'Three':3, 'Four':4, 'Five':5, 'Six':6, 'Seven':7, 'Eight':8, \n 'Nine':9, 'Ten':10, 'Jack':10, 'Queen':10, 'King':10, 'Ace':11}\n\nclass Card():\n\n def __init__(self,suit,rank):\n \n self.suit = suit\n self.rank = rank\n self.value = values[rank]\n\n def __str__(self):\n return(self.rank + \" of \" + self.suit)\n\nclass Deck():\n \n def __init__(self):\n \n for suit in suits:\n for rank in ranks: \n newcard = Card(suit,rank) \n all_cards.append(newcard)\n \n def deal_one(self):\n \n return all_cards.pop(0)\n \n def shuffle(self):\n \n random.shuffle(all_cards)\n \nclass Bank():\n \n def __init__(self,balance):\n \n self.balance=balance\n self.bet_amount=0\n self.userBet = 0\n def bet(self,amount):\n \n while True:\n if amount > self.balance:\n print(\"\\nInsufficent Funds!\\n\")\n print (\"How much would you like to bet?\\n\")\n amount = user_input()\n \n else:\n self.userBet = amount\n self.balance = self.balance - amount\n self.bet_amount = amount\n break\n \n def win(self):\n \n self.balance = self.balance + (self.userBet*2)\n \n def draw(self):\n self.balance = self.balance + self.userBet\n \ndef user_input():\n \n while True:\n try:\n Balance = int(input())\n\n except :\n print(\"Whoops! Assure your input was an Integer! \")\n\n else:\n return Balance\n \n\nclass GameLogic():\n\n \n \n def __init__(self):\n \n newDeck = Deck()\n newDeck.shuffle()\n roundNumber=1\n playerCards=[]\n playerValue = 0\n computerCards=[]\n self.UsersCards=[]\n time.sleep(.75)\n \n choice = ''\n i=2\n r=2\n choices = ['Y','y','N','n']\n time.sleep(2)\n\n print(f\"Welcome to Noah's Black Jack Game!\\n\")\n time.sleep(1)\n\n print(\"Lets start by creating you a Casino Bank Account!\\n\")\n\n print(\"How much would you like to deposit into casino account?\" )\n \n balance = user_input()\n BankAccount=Bank(balance)\n\n print(f\"\\nYour casino balance is ${BankAccount.balance}! \")\n\n choice = ''\n i=2\n r=2\n choices = ['Y','y','N','n']\n time.sleep(2)\n\n\n\n\n\n time.sleep(.25)\n \n def printTable(self):\n \n print(\"Your Cards: The dealers cards:\")\n print(\" \")\n playerCards.append(newDeck.deal_one())\n playerCards.append(newDeck.deal_one())\n\n computerCards.append(newDeck.deal_one())\n computerCards.append(newDeck.deal_one())\n\n print(f\"{playerCards[0]} ({playerCards[0].value}) {computerCards[0]} ({computerCards[0].value})\")\n print(f\"{playerCards[1]} ({playerCards[1].value}) (The other card is Hidden)\")\n \n \n def printDashboard(self):\n \n print(f\"\\nCurrent Bet: ${BankAccount.bet_amount} | Current Round: Round {roundNumber} | Current Balance: ${BankAccount.balance}\\n\")\n \n def calculateUserTotal(self):\n total=0\n i=0\n \n for x in playerCards:\n total = total + playerCards[i].value\n i+=1\n \n return total\n \n def calculateComputerTotal(self):\n total=0\n i=0\n \n for x in computerCards:\n total = total + computerCards[i].value\n i+=1\n \n return total\n \n \n while BankAccount.balance != 0:\n \n BankAccount.bet_amount=0\n i=2\n r=2\n \n \n playerCards=[]\n playerValue = 0\n computerCards=[]\n newDeck.shuffle()\n choice =''\n clear_output()\n time.sleep(0.5)\n printDashboard(self)\n print (\"How much would you like to bet?\")\n bet = user_input()\n BankAccount.bet(bet)\n clear_output()\n\n printDashboard(self)\n print(\"--------------------------------------------------------------------------------\")\n printTable(self)\n playerValue=calculateUserTotal(self)\n computerValue=calculateComputerTotal(self)\n gameOn= True\n\n\n while gameOn == True:\n\n\n while choice != 'n' and playerValue < 21:\n\n\n time.sleep(1)\n choice = input((\"Would you like to hit? Y/N\\n\"))\n\n while choice not in choices:\n\n print(\"Assure your choice was either Y or N\")\n choice = input((\"Would you like to hit? Y/N\\n\"))\n\n if choice == 'Y' or choice == 'y':\n \n playerCards.append(newDeck.deal_one())\n \n if playerCards[-1].rank == 'Ace' and playerValue > 10:\n \n print(f\"{playerCards[-1]} (1)\")\n playerValue+=1\n playerCards.pop(-1)\n playerValue=calculateUserTotal(self)\n\n else:\n\n print(f\"{playerCards[-1]} ({playerCards[-1].value})\")\n\n playerValue=calculateUserTotal(self)\n\n print(playerValue)\n\n elif choice == 'N' or choice == 'n':\n choice = 'n'\n break\n playerValue=calculateUserTotal(self)\n\n if playerValue >21:\n\n print(\"You Busted! Dealer Wins!\")\n roundNumber+=1\n gameOn==False\n\n break \n\n\n while computerValue<=17:\n\n print(\"\\nDealer Decides to Hit.\")\n time.sleep(1)\n computerValue=calculateComputerTotal(self)\n\n computerCards.append(newDeck.deal_one())\n\n\n if computerCards[-1].rank == 'Ace' and computerValue > 10:\n computerValue+=1\n print(f\"Dealer gets the {computerCards[r]} ({computerCards[r].value})\")\n computerCards.pop()\n computerValue=calculateComputerTotal(self)\n\n\n else:\n\n computerValue=calculateComputerTotal(self)\n time.sleep(.5)\n print(f\"Dealer gets the {computerCards[r]} ({computerCards[r].value})\")\n\n r+=1\n\n computerValue=calculateComputerTotal(self)\n\n if computerValue > 21:\n time.sleep(1)\n print(\"Dealer Busts! You win!\")\n time.sleep(.5)\n print (f\"\\nHis hidden card was the {computerCards[1]}\")\n gameOn==False\n roundNumber+=1\n BankAccount.win()\n break\n\n time.sleep(1)\n\n print(\"\\nDealer Decides to stay\")\n\n\n if computerValue>=17 and computerValue <= 21:\n\n if 21 - computerValue > 21 - playerValue:\n time.sleep(1)\n print(\"\\nYou Win!\")\n\n print (f\"\\nHis hidden card was the {computerCards[1]}\")\n BankAccount.win()\n gameon=False\n roundNumber+=1\n\n\n\n if 21 - computerValue < 21 - playerValue:\n time.sleep(1)\n print(f\"\\nDealer Wins! {computerValue}\") \n print (f\"\\nHis hidden card was the {computerCards[1]}\")\n gameon=False\n roundNumber+=1\n Bank\n\n if 21 - computerValue == 21 - playerValue:\n time.sleep(1)\n print(\"The round was a draw!\")\n print (f\"\\nHis hidden card was the {computerCards[1]}\")\n BankAccount.draw()\n gameon=False\n roundNumber+=1\n break\n \n if BankAccount.balance == 0:\n time.sleep(2)\n clear_output()\n print(\"Your out of money!\")\n break\n\n else:\n \n playagain = input((\"Would you like to play another round? Y/N\\n\"))\n\n while choice not in choices:\n\n print(\"Assure your choice was either Y or N\")\n choice = input((\"Would you like to hit? Y/N\\r\"))\n\n if playagain == 'Y' or playagain == 'y':\n\n clear_output()\n gameOn==True\n\n else:\n print(\"Game Over\\n\")\n\n break\n \n time.sleep(3)\n print(\"Thanks for Playing!\")\n\n\ndef black_jack():\n #new Deck Created and then Shuffled:\n\n GameLogic()\n \n \nblack_jack()\n\n\n# \n"} {"doc_id": "12a5ed028a1dc2d37e9c8068f8e73d75", "text": "# -*- coding: UTF-8 -*-\nimport hashlib,random\n\n'''\nPython\u7684hashlib\u63d0\u4f9b\u4e86\u5e38\u89c1\u7684\u6458\u8981\u7b97\u6cd5\uff0c\u5982MD5\uff0cSHA1\u7b49\u7b49\u3002\n\n\u4ec0\u4e48\u662f\u6458\u8981\u7b97\u6cd5\u5462\uff1f\u6458\u8981\u7b97\u6cd5\u53c8\u79f0\u54c8\u5e0c\u7b97\u6cd5\u3001\u6563\u5217\u7b97\u6cd5\u3002\u5b83\u901a\u8fc7\u4e00\u4e2a\u51fd\u6570\uff0c\u628a\u4efb\u610f\u957f\u5ea6\u7684\u6570\u636e\u8f6c\u6362\u4e3a\u4e00\u4e2a\u957f\u5ea6\u56fa\u5b9a\u7684\u6570\u636e\u4e32\uff08\u901a\u5e38\u752816\u8fdb\u5236\u7684\u5b57\u7b26\u4e32\u8868\u793a\uff09\u3002\n\n\u4e3e\u4e2a\u4f8b\u5b50\uff0c\u4f60\u5199\u4e86\u4e00\u7bc7\u6587\u7ae0\uff0c\u5185\u5bb9\u662f\u4e00\u4e2a\u5b57\u7b26\u4e32'how to use python hashlib - by Michael'\uff0c\u5e76\u9644\u4e0a\u8fd9\u7bc7\u6587\u7ae0\u7684\u6458\u8981\u662f'2d73d4f15c0db7f5ecb321b6a65e5d6d'\u3002\u5982\u679c\u6709\u4eba\u7be1\u6539\u4e86\u4f60\u7684\u6587\u7ae0\uff0c\u5e76\u53d1\u8868\u4e3a'how to use python hashlib - by Bob'\uff0c\u4f60\u53ef\u4ee5\u4e00\u4e0b\u5b50\u6307\u51faBob\u7be1\u6539\u4e86\u4f60\u7684\u6587\u7ae0\uff0c\u56e0\u4e3a\u6839\u636e'how to use python hashlib - by Bob'\u8ba1\u7b97\u51fa\u7684\u6458\u8981\u4e0d\u540c\u4e8e\u539f\u59cb\u6587\u7ae0\u7684\u6458\u8981\u3002\n\n\u53ef\u89c1\uff0c\u6458\u8981\u7b97\u6cd5\u5c31\u662f\u901a\u8fc7\u6458\u8981\u51fd\u6570f()\u5bf9\u4efb\u610f\u957f\u5ea6\u7684\u6570\u636edata\u8ba1\u7b97\u51fa\u56fa\u5b9a\u957f\u5ea6\u7684\u6458\u8981digest\uff0c\u76ee\u7684\u662f\u4e3a\u4e86\u53d1\u73b0\u539f\u59cb\u6570\u636e\u662f\u5426\u88ab\u4eba\u7be1\u6539\u8fc7\u3002\n\n\u6458\u8981\u7b97\u6cd5\u4e4b\u6240\u4ee5\u80fd\u6307\u51fa\u6570\u636e\u662f\u5426\u88ab\u7be1\u6539\u8fc7\uff0c\u5c31\u662f\u56e0\u4e3a\u6458\u8981\u51fd\u6570\u662f\u4e00\u4e2a\u5355\u5411\u51fd\u6570\uff0c\u8ba1\u7b97f(data)\u5f88\u5bb9\u6613\uff0c\u4f46\u901a\u8fc7digest\u53cd\u63a8data\u5374\u975e\u5e38\u56f0\u96be\u3002\u800c\u4e14\uff0c\u5bf9\u539f\u59cb\u6570\u636e\u505a\u4e00\u4e2abit\u7684\u4fee\u6539\uff0c\u90fd\u4f1a\u5bfc\u81f4\u8ba1\u7b97\u51fa\u7684\u6458\u8981\u5b8c\u5168\u4e0d\u540c\u3002\n\n\u6211\u4eec\u4ee5\u5e38\u89c1\u7684\u6458\u8981\u7b97\u6cd5MD5\u4e3a\u4f8b\uff0c\u8ba1\u7b97\u51fa\u4e00\u4e2a\u5b57\u7b26\u4e32\u7684MD5\u503c\uff1a\n\n'''\nmd5 = hashlib.md5()\n#md5.update('how to use md5 in python hashlib?'.encode('utf-8'))\nmd5.update('how to use md5 in '.encode('utf-8'))\nmd5.update('python hashlib?'.encode('utf-8'))\nprint(md5.hexdigest())\n\n\n'''\n\u8bd5\u8bd5\u6539\u52a8\u4e00\u4e2a\u5b57\u6bcd\uff0c\u770b\u770b\u8ba1\u7b97\u7684\u7ed3\u679c\u662f\u5426\u5b8c\u5168\u4e0d\u540c\u3002\nMD5\u662f\u6700\u5e38\u89c1\u7684\u6458\u8981\u7b97\u6cd5\uff0c\u901f\u5ea6\u5f88\u5feb\uff0c\u751f\u6210\u7ed3\u679c\u662f\u56fa\u5b9a\u7684128 bit\u5b57\u8282\uff0c\u901a\u5e38\u7528\u4e00\u4e2a32\u4f4d\u768416\u8fdb\u5236\u5b57\u7b26\u4e32\u8868\u793a\u3002\n\u53e6\u4e00\u79cd\u5e38\u89c1\u7684\u6458\u8981\u7b97\u6cd5\u662fSHA1\uff0c\u8c03\u7528SHA1\u548c\u8c03\u7528MD5\u5b8c\u5168\u7c7b\u4f3c\uff1a \n'''\n\nsha1 = hashlib.sha1()\nsha1.update('how to use sha1 in '.encode('utf-8'))\nsha1.update('python hashlib?'.encode('utf-8'))\nprint(sha1.hexdigest())\n\n'''\nSHA1\u7684\u7ed3\u679c\u662f160 bit\u5b57\u8282\uff0c\u901a\u5e38\u7528\u4e00\u4e2a40\u4f4d\u768416\u8fdb\u5236\u5b57\u7b26\u4e32\u8868\u793a\u3002\n\u6bd4SHA1\u66f4\u5b89\u5168\u7684\u7b97\u6cd5\u662fSHA256\u548cSHA512\uff0c\u4e0d\u8fc7\u8d8a\u5b89\u5168\u7684\u7b97\u6cd5\u4e0d\u4ec5\u8d8a\u6162\uff0c\u800c\u4e14\u6458\u8981\u957f\u5ea6\u66f4\u957f\u3002\n\u6709\u6ca1\u6709\u53ef\u80fd\u4e24\u4e2a\u4e0d\u540c\u7684\u6570\u636e\u901a\u8fc7\u67d0\u4e2a\u6458\u8981\u7b97\u6cd5\u5f97\u5230\u4e86\u76f8\u540c\u7684\u6458\u8981\uff1f\u5b8c\u5168\u6709\u53ef\u80fd\uff0c\u56e0\u4e3a\u4efb\u4f55\u6458\u8981\u7b97\u6cd5\u90fd\u662f\u628a\u65e0\u9650\u591a\u7684\u6570\u636e\u96c6\u5408\u6620\u5c04\u5230\u4e00\u4e2a\u6709\u9650\u7684\u96c6\u5408\u4e2d\u3002\u8fd9\u79cd\u60c5\u51b5\u79f0\u4e3a\u78b0\u649e\uff0c\u6bd4\u5982Bob\u8bd5\u56fe\u6839\u636e\u4f60\u7684\u6458\u8981\u53cd\u63a8\u51fa\u4e00\u7bc7\u6587\u7ae0'how to learn hashlib in python - by Bob'\uff0c\n\u5e76\u4e14\u8fd9\u7bc7\u6587\u7ae0\u7684\u6458\u8981\u6070\u597d\u548c\u4f60\u7684\u6587\u7ae0\u5b8c\u5168\u4e00\u81f4\uff0c\u8fd9\u79cd\u60c5\u51b5\u4e5f\u5e76\u975e\u4e0d\u53ef\u80fd\u51fa\u73b0\uff0c\u4f46\u662f\u975e\u5e38\u975e\u5e38\u56f0\u96be\u3002\n'''\n\n'''\n\u7ec3\u4e60\n\u6839\u636e\u7528\u6237\u8f93\u5165\u7684\u53e3\u4ee4\uff0c\u8ba1\u7b97\u51fa\u5b58\u50a8\u5728\u6570\u636e\u5e93\u4e2d\u7684MD5\u53e3\u4ee4\uff1a\n'''\n\ndb = {\n\n 'michael': 'e10adc3949ba59abbe56e057f20f883e',\n 'bob': '878ef96e86145580c38c87f0410ad153',\n 'alice': '99b1c2188db85afee403b1536010c2c9'\n\n}\ndef cale_md5(password):\n md5 = hashlib.md5()\n md5.update(password.encode('utf-8'))\n return md5.hexdigest()\n \n\ndef login(user,password):\n hex = db[user]\n phex = cale_md5(password)\n if hex == phex:\n print('\u767b\u9646\u6210\u529f')\n else:\n print('\u5bc6\u7801\u9519\u8bef')\n\nlogin(user='michael',password='123456')\nlogin(user='bob',password='abc999')\nlogin(user='alice',password='alice2008')\n\n\n'''\n \u91c7\u7528MD5\u5b58\u50a8\u53e3\u4ee4\u662f\u5426\u5c31\u4e00\u5b9a\u5b89\u5168\u5462\uff1f\u4e5f\u4e0d\u4e00\u5b9a\u3002\u5047\u8bbe\u4f60\u662f\u4e00\u4e2a\u9ed1\u5ba2\uff0c\u5df2\u7ecf\u62ff\u5230\u4e86\u5b58\u50a8MD5\u53e3\u4ee4\u7684\u6570\u636e\u5e93\uff0c\u5982\u4f55\u901a\u8fc7MD5\u53cd\u63a8\u7528\u6237\u7684\u660e\u6587\u53e3\u4ee4\u5462\uff1f\u66b4\u529b\u7834\u89e3\u8d39\u4e8b\u8d39\u529b\uff0c\u771f\u6b63\u7684\u9ed1\u5ba2\u4e0d\u4f1a\u8fd9\u4e48\u5e72\u3002\n \n \u8003\u8651\u8fd9\u4e48\u4e2a\u60c5\u51b5\uff0c\u5f88\u591a\u7528\u6237\u559c\u6b22\u7528123456\uff0c888888\uff0cpassword\u8fd9\u4e9b\u7b80\u5355\u7684\u53e3\u4ee4\uff0c\u4e8e\u662f\uff0c\u9ed1\u5ba2\u53ef\u4ee5\u4e8b\u5148\u8ba1\u7b97\u51fa\u8fd9\u4e9b\u5e38\u7528\u53e3\u4ee4\u7684MD5\u503c\uff0c\u5f97\u5230\u4e00\u4e2a\u53cd\u63a8\u8868\uff1a\n \n 'e10adc3949ba59abbe56e057f20f883e': '123456'\n '21218cca77804d2ba1922c33e0151105': '888888'\n '5f4dcc3b5aa765d61d8327deb882cf99': 'password'\n \u8fd9\u6837\uff0c\u65e0\u9700\u7834\u89e3\uff0c\u53ea\u9700\u8981\u5bf9\u6bd4\u6570\u636e\u5e93\u7684MD5\uff0c\u9ed1\u5ba2\u5c31\u83b7\u5f97\u4e86\u4f7f\u7528\u5e38\u7528\u53e3\u4ee4\u7684\u7528\u6237\u8d26\u53f7\u3002\n \n \u5bf9\u4e8e\u7528\u6237\u6765\u8bb2\uff0c\u5f53\u7136\u4e0d\u8981\u4f7f\u7528\u8fc7\u4e8e\u7b80\u5355\u7684\u53e3\u4ee4\u3002\u4f46\u662f\uff0c\u6211\u4eec\u80fd\u5426\u5728\u7a0b\u5e8f\u8bbe\u8ba1\u4e0a\u5bf9\u7b80\u5355\u53e3\u4ee4\u52a0\u5f3a\u4fdd\u62a4\u5462\uff1f\n \n \u7531\u4e8e\u5e38\u7528\u53e3\u4ee4\u7684MD5\u503c\u5f88\u5bb9\u6613\u88ab\u8ba1\u7b97\u51fa\u6765\uff0c\u6240\u4ee5\uff0c\u8981\u786e\u4fdd\u5b58\u50a8\u7684\u7528\u6237\u53e3\u4ee4\u4e0d\u662f\u90a3\u4e9b\u5df2\u7ecf\u88ab\u8ba1\u7b97\u51fa\u6765\u7684\u5e38\u7528\u53e3\u4ee4\u7684MD5\uff0c\u8fd9\u4e00\u65b9\u6cd5\u901a\u8fc7\u5bf9\u539f\u59cb\u53e3\u4ee4\u52a0\u4e00\u4e2a\u590d\u6742\u5b57\u7b26\u4e32\u6765\u5b9e\u73b0\uff0c\u4fd7\u79f0\u201c\u52a0\u76d0\u201d\uff1a\n \n def calc_md5(password):\n return get_md5(password + 'the-Salt')\n \u7ecf\u8fc7Salt\u5904\u7406\u7684MD5\u53e3\u4ee4\uff0c\u53ea\u8981Salt\u4e0d\u88ab\u9ed1\u5ba2\u77e5\u9053\uff0c\u5373\u4f7f\u7528\u6237\u8f93\u5165\u7b80\u5355\u53e3\u4ee4\uff0c\u4e5f\u5f88\u96be\u901a\u8fc7MD5\u53cd\u63a8\u660e\u6587\u53e3\u4ee4\u3002\n \n \u4f46\u662f\u5982\u679c\u6709\u4e24\u4e2a\u7528\u6237\u90fd\u4f7f\u7528\u4e86\u76f8\u540c\u7684\u7b80\u5355\u53e3\u4ee4\u6bd4\u5982123456\uff0c\u5728\u6570\u636e\u5e93\u4e2d\uff0c\u5c06\u5b58\u50a8\u4e24\u6761\u76f8\u540c\u7684MD5\u503c\uff0c\u8fd9\u8bf4\u660e\u8fd9\u4e24\u4e2a\u7528\u6237\u7684\u53e3\u4ee4\u662f\u4e00\u6837\u7684\u3002\u6709\u6ca1\u6709\u529e\u6cd5\u8ba9\u4f7f\u7528\u76f8\u540c\u53e3\u4ee4\u7684\u7528\u6237\u5b58\u50a8\u4e0d\u540c\u7684MD5\u5462\uff1f\n \n \u5982\u679c\u5047\u5b9a\u7528\u6237\u65e0\u6cd5\u4fee\u6539\u767b\u5f55\u540d\uff0c\u5c31\u53ef\u4ee5\u901a\u8fc7\u628a\u767b\u5f55\u540d\u4f5c\u4e3aSalt\u7684\u4e00\u90e8\u5206\u6765\u8ba1\u7b97MD5\uff0c\u4ece\u800c\u5b9e\u73b0\u76f8\u540c\u53e3\u4ee4\u7684\u7528\u6237\u4e5f\u5b58\u50a8\u4e0d\u540c\u7684MD5\u3002\n \n def calc_md5(password):\n return get_md5(password + 'the-Salt')\n \n'''\n\n'''\n \u6839\u636e\u7528\u6237\u8f93\u5165\u7684\u767b\u5f55\u540d\u548c\u53e3\u4ee4\u6a21\u62df\u7528\u6237\u6ce8\u518c\uff0c\u8ba1\u7b97\u66f4\u5b89\u5168\u7684MD5\uff1a\n'''\n\ndef get_md5(s):\n return hashlib.md5(s.encode('utf-8')).hexdigest()\n\nclass User(object):\n def __init__(self, username, password):\n self.username = username\n self.salt = username.join([chr(random.randint(48, 122)) for i in range(20)])\n self.password = get_md5(password + self.salt)\n\ndb2 = {\n 'michael': User('michael', '123456'),\n 'bob': User('bob', 'abc999'),\n 'alice': User('alice', 'alice2008')\n}\n\ndef login2(username, password):\n user = db2[username]\n if user.password == get_md5(password+user.salt):\n print(\"\u767b\u9646\u6210\u529f2\")\n else:\n print(\"\u5bc6\u7801\u9519\u8bef2\") \n\nlogin2('michael', '123456')"} {"doc_id": "12d78bb4d598dd8b25f8bfd30e12a2de", "text": "\"\"\"\nFile: hailstone.py\nName: An Lee\n-----------------------\nThis program should implement a console program that simulates\nthe execution of the Hailstone sequence, defined by Douglas\nHofstadter. Output format should match what is shown in the sample\nrun in the Assignment 2 Handout.\n\"\"\"\n\nFINAL = 1\nimport time\n\ndef main():\n \"\"\"\n User enter a number, and this program will compute Hailstone sequences.\n Hailstone Sequences follow rules:\n If a number is odd, multiply it by 3 and add 1.\n If a number is even, divide it by 2\n pre-condition: Waiting user to input a number.\n post-condition: Show user how many the steps are took to reach 1.\n \"\"\"\n print('This program computes Hailstone sequences.')\n data = int(input('Enter a number: '))\n start = time.time()\n n = data\n steps = 0\n # Check if the number is 1 or not.\n if n == FINAL:\n print('It took ' + str(steps) + ' steps to reach 1.')\n # If the number is not 1, we have to start calculating until it reach 1.\n else:\n while True:\n # Every time, check if the number is 1(stop) or not.\n if n == FINAL:\n break\n # If a number is odd, multiply it by 3 and add 1.\n if data % 2 == 1:\n n = 3*n+1\n print(str(data) + ' is odd, so I make 3n+1: ' + str(n))\n # If a number is even, divide it by 2.\n if data % 2 == 0:\n n = n//2\n print(str(data) + ' is even, so I take half: ' + str(n))\n data = n\n steps += 1\n print('It took ' + str(steps) + ' steps to reach 1.')\n end = time.time()\n print(\"The time of execution of above program is :\", end - start)\n\n###### DO NOT EDIT CODE BELOW THIS LINE ######\n\nif __name__ == \"__main__\":\n main()\n"} {"doc_id": "132302787ea1b0ef9a4b90f9a6b01cd4", "text": "#Desenvolva um programa que leia o comprimento de tr\u00eas retas e diga ao usu\u00e1rio se elas podem ou n\u00e3o formar um tri\u00e2ngulo.\nfrom time import sleep\nprint('\\033[31m-------------ANALISADOR DE TRI\u00c2NGULOS-----------\\033[m') #titulo\nr1 = float(input('Primeiro segmento: ')) #input do comprimento da primeira reta na variavel r1\nr2 = float(input('Segundo segmento: ')) #input do comprimento da segunda reta na variavel r2\nr3 = float(input('Terceiro segmento: ')) #inpur do comprimento da terceira reta na variavel r3\nprint('\\033[33mANALISANDO...\\033[m')\nsleep(1)\nif r1 < r2 + r3 and r2 < r1 + r3 and r3 < r1 + r2: #se r1 for menor que a soma de r2 e r3 e r2 for menor que a soma de r1 e re e r3 for menor que a soma de r1 e r2\n print('Os segmentos acima \\033[4;33mPODEM FORMAR\\033[m um tri\u00e2ngulo!') #mensagem caso o if seja verdadeiro\nelse:\n print('Os segmentos acima \\033[4;31mN\u00c3O PODEM FORMAR\\033[m um tri\u00e2ngulo.') #mensagem caso o if seja falso\n"} {"doc_id": "13268d3c4ab90160ccfa7bc2c90d22f3", "text": "print('============ Exibindo o maior e o menor n\u00famero =============')\nnum1 = int(input('Primeiro n\u00famero '))\nnum2 = int(input('Segundo n\u00famero '))\nnum3 = int(input('Terceiro n\u00famero '))\n\n#aplication condition\nif num1 > num2 and num1 > num3:\n print('{} maior n\u00famero '.format(num1))\nelif num2 > num3:\n print('{} maior n\u00famero '.format(num2))\nelse:\n print('{} maior n\u00famero '.format(num3))\n\n#low number\nif num1 < num2 and num1 < num3:\n print('{} menor n\u00famero '.format(num1))\nelif num2 < num3:\n print('{} menor n\u00famero '.format(num2))\nelse:\n print('{} menor n\u00famero '.format(num3))\n"} {"doc_id": "132eadbb3c2aa68637e3828246d71f7f", "text": "import educative.course1.stacks_queues.queue as q\nimport educative.course1.graphs.graph as g\n\ninput_num_vertices = 5\ninput_edges = {0: [1, 2], 1: [3, 4]}\nexpected_output = \"01234\"\n\n\n# this code implements Breadth First Traversal in a graph. Each element in the graph's adjacency list\n# represents a list of nodes directly connected to the current element. Each of these lists represent\n# levels in the graph. We traverse all nodes in a certain level, before moving to the next one.\n# --------------\n# For traversal:\n# --------------\n# 1. We first enqueue the root node in a queue and mark it visited.\n# 2. Now we get the list of adjacent nodes from the root node and enqueue all adjacent nodes in the list\n# to the queue.\n# 3. As we are adding the adjacent nodes to the queue, we mark them as visited.\n# 4. Simultaneously, we dequeue the nodes from the queue and append the node's value to the result\n# --------------\ndef bfs_traversal(graph, root):\n result = \"\"\n visited = [False] * graph.num_vertices\n queue = q.Queue(graph.num_vertices, True) # supress_printing = True\n\n queue.enqueue(root)\n visited[root] = True\n\n while not queue.is_empty():\n g_node = queue.dequeue()\n result += str(g_node)\n\n dll = graph.adjacency_list[g_node]\n if dll is not None:\n current = dll.head\n while current:\n if not visited[current.value]:\n queue.enqueue(current.value)\n visited[current.value] = True\n current = current.next\n\n return result\n\n\ndef main():\n # create a graph from input data\n graph = g.Graph(input_num_vertices, True) # suppress_printing = True\n for x in input_edges.keys():\n for y in input_edges[x]:\n graph.add_edge(x, y)\n\n # set a starting point for traversal\n root = 0\n\n print(\"Input:\")\n print(\"Graph in Adjacency List Representation:\")\n print(str(graph.prettify()))\n\n print(\"Expected: \" + str(expected_output))\n print(\"Output: \" + str(bfs_traversal(graph, root)))\n\n\nif __name__ == '__main__':\n main()\n"} {"doc_id": "137885645750eb398c00eda7ce571dd9", "text": "found = False\ncount = 0\nlow = 1\nhigh = 100\nprint(\"Pick a number between 1 and 100\")\nwhile not found and low <= high: # the low <= high isn't necessary\n guess = (low + high) // 2\n answer = input(\"Is your number \" + str(guess) + \"? \")\n \n if answer.lower() == \"yes\":\n found = True\n else:\n answer = input(\"Is it higher or lower? \")\n if answer.lower() == \"higher\":\n low = guess + 1\n else:\n high = guess - 1\n \n count += 1\n \n\nprint(\"I guessed correctly in\",count,\"tries.\")\n\n "} {"doc_id": "13926f3772856dfc546ac733c83f6600", "text": "class CaesarCipher:\n \"\"\"\n A class for the Caesar Cipher.\n\n Attributes\n -----------\n alphabet : str\n A string that stores the working alphabet.\n shift : int\n The value by which the alphabet is shifted to\n the right for encryption (default is +3).\n Negative values indicate left shift.\n\n Methods\n --------\n encrypt(plaintext)\n Encrypts plaintext to produce ciphertext\n decrypt(ciphertext)\n Decrypts ciphertext to produce plaintext\n \"\"\"\n\n alphabet = \"abcdefghijklmnopqrstuvwxyz0123456789\"\n\n def __init__(self, shift = 3):\n \"\"\"\n Parameters\n -----------\n shift : int\n The value by which the alphabet is shifted to\n the right for encryption (default is +3).\n Negative values indicate left shift.\n \"\"\"\n try:\n int(shift)\n except ValueError as e:\n print(\"Invalid shift entered, resetting shift to 3\")\n shift = 3\n self.shift = int(shift)\n\n def encrypt(self, plaintext):\n \"\"\"Function to encrypt strings using Caesar Cipher.\n\n The encryption works on only the alphanumeric English\n characters, any other characters present in the text\n are removed from the encrypted file.\n\n Parameters\n -----------\n plaintext : str\n The plaintext phrase to be encrypted.\n\n Returns\n --------\n str\n The encrypted ciphertext.\n \"\"\"\n ciphertext = \"\"\n for letter in plaintext.lower():\n if letter in self.alphabet:\n letter_index = self.alphabet.index(letter)\n cipher_index = (letter_index + self.shift) % len(self.alphabet)\n ciphertext += self.alphabet[cipher_index]\n return ciphertext\n\n def decrypt(self, ciphertext):\n \"\"\"Function to decrypt strings using Caesar Cipher.\n\n The decryption works on only the alphanumeric English\n characters, any other characters present in the text\n are removed from the decrypted file.\n\n Parameters\n -----------\n ciphertext : str\n The ciphertext phrase to be decrypted.\n\n\n Returns\n --------\n str\n The decrypted plaintext message.\n \"\"\"\n plaintext = \"\"\n for letter in ciphertext.lower():\n if letter in self.alphabet:\n letter_index = self.alphabet.index(letter)\n cipher_index = (letter_index - self.shift) % len(self.alphabet)\n plaintext += self.alphabet[cipher_index]\n return plaintext\n"} {"doc_id": "14665251577b0befbb5de57f777f7dba", "text": "\"\"\"\nFile: anagram.py\nName: Dennis Hsu\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' # Code to stop the loop\nDATABASE = [] # Used to stored candidate words.\nALL_CHAR = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u',\n 'v', 'w', 'x', 'y', 'z'] # All english alphabet.\n\n\ndef main():\n \"\"\"\n Check if input is quit code.\n If not, then star load dictionary and search anagram.\n \"\"\"\n while True:\n word = input('Welcome to stanCode \"Anagram Generator\" (or -1 to quit)\\nFind anagrams for:')\n word = word.lower()\n if word == '-1': # quit code\n return\n else:\n if read_dictionary(word):\n if word in DATABASE:\n ans_list = [] # reset answer list when change input word.\n find_anagrams(word, ans_list)\n else:\n print('This word not exists, pleas enter again.')\n\n\ndef read_dictionary(word):\n global DATABASE\n with open(FILE, 'r') as f:\n for line in f:\n word_data = line.strip()\n DATABASE.append(word_data) # load file.\n\n if word in DATABASE:\n trim_dictionary(word) # cut down searching range.\n return True\n else:\n return False\n\n\ndef trim_dictionary(word):\n global DATABASE\n print('read')\n char_list = [] # store character from destructed input word.\n word_len = len(word)\n\n for char in word:\n char_list.append(char)\n\n another_char = list(filter(lambda e: e not in char_list, ALL_CHAR)) # all character not inside boggle board.\n\n for char in another_char:\n DATABASE = list(filter(lambda e: char not in e, DATABASE)) # filter words which contain another_char.\n\n DATABASE = list(filter(lambda e: len(e) >= word_len, DATABASE)) # filter words shorter than input word units.\n\n\ndef find_anagrams(s, ans_list):\n \"\"\"\n :param ans_list: (list) used to store anagram words.\n :param s: (string) resource word input from user.\n \"\"\"\n find_anagrams_helper(s, '', ans_list)\n print(f'{len(ans_list)} anagram:', ans_list)\n\n\ndef find_anagrams_helper(s, sub_s, ans_list):\n \"\"\"\n Do recursion until find all anagram words.\n :param s: (string) resource word input from user.\n :param sub_s: (string) sub_string of resource word.\n :param ans_list: (list) used to store anagram words.\n :return:\n \"\"\"\n if len(s) == len(sub_s): # base point.\n if sub_s in DATABASE: # check answer.\n if sub_s not in ans_list: # prevent from repeat answer.\n print('Found:', sub_s)\n print('Searching...')\n ans_list.append(sub_s)\n pass\n else:\n for char in s:\n if char in sub_s and sub_s.count(char) == s.count(char): # avoid to use over times of any char.\n pass\n else:\n sub_s = sub_s + char # combine next character as sub_string.\n if has_prefix(sub_s): # check whether are words start with sub_s.\n find_anagrams_helper(s, sub_s, ans_list)\n sub_s = sub_s[0:len(sub_s) - 1]\n else: # no word start with sub_s\n sub_s = sub_s[0:len(sub_s) - 1]\n\n\ndef has_prefix(sub_s):\n \"\"\"\n Test possibility of sub_s before doing recursion.\n :param sub_s: sub_string of input word from its head.\n :return: (boolean) whether word stars with sub_s.\n \"\"\"\n for word in DATABASE:\n if word.startswith(sub_s):\n return True\n\n\nif __name__ == '__main__':\n main()\n"} {"doc_id": "1471baf12e16f4459fa3336d1c58d45b", "text": "class MaxHeap():\r\n def __init__(self, l):\r\n self.heap = l\r\n self.heapify()\r\n\r\n def child_ids(self, i):\r\n left = 2 * i + 1\r\n right = 2 * i + 2\r\n return left, right\r\n\r\n def parent_ids(self, i):\r\n return (i - 1) // 2\r\n\r\n def heapify(self):\r\n for i in range(len(self.heap)-1, -1, -1):\r\n parent = self.parent_ids(i)\r\n if parent == -1:\r\n break\r\n if self.heap[i] > self.heap[parent]:\r\n self.heap[i], self.heap[parent] = self.heap[parent], self.heap[i]\r\n\r\n print(self.heap)\r\n\r\n def pop(self):\r\n if self.heap == []:\r\n return None\r\n max_element = self.heap[0]\r\n self.heap = self.heap[1:]\r\n self.heapify()\r\n return max_element\r\n\r\n def peek(self):\r\n if self.heap == []:\r\n return None\r\n return self.heap[0]\r\n\r\ndef rearrange_digits(input_list):\r\n \"\"\"\r\n Rearrange Array Elements so as to form two number such that their sum is maximum.\r\n\r\n Args:\r\n input_list(list): Input List\r\n Returns:\r\n (int),(int): Two maximum sums\r\n \"\"\"\r\n if not input_list or input_list == []:\r\n return [0, 0]\r\n max_heap = MaxHeap(input_list)\r\n n1 = 0\r\n n2 = 0\r\n round = 0\r\n while max_heap.peek():\r\n max_element = max_heap.pop()\r\n if round % 2 == 0:\r\n n1 = n1 * 10 + max_element\r\n else:\r\n n2 = n2 * 10 + max_element\r\n round += 1\r\n return [n1, n2]\r\n\r\ndef test_function(test_case):\r\n output = rearrange_digits(test_case[0])\r\n print(output)\r\n solution = test_case[1]\r\n if sum(output) == sum(solution):\r\n print(\"Pass\")\r\n else:\r\n print(\"Fail\")\r\n\r\ntest_function([[1, 2, 3, 4, 5], [542, 31]])\r\ntest_case = [[4, 6, 2, 5, 9, 8], [964, 852]]\r\n\r\nprint(\"Test Case 1 - empty array\")\r\ninput_list = []\r\nsolution = 0\r\noutput = sum(rearrange_digits(input_list))\r\nprint(\"Output: {0}\".format(output))\r\nassert(output == solution)\r\nprint(\"TestCase 1 passed! - Given output {0}; Expected output {1}\".format(output, solution))\r\nprint(\"---------------------------\")\r\nprint(\"Test Case 2 - only 0s\")\r\ninput_list = [0, 0, 0, 0]\r\nsolution = 0\r\noutput = sum(rearrange_digits(input_list))\r\nprint(\"Output: {0}\".format(output))\r\nassert(output == solution)\r\nprint(\"TestCase 2 passed! - Given output {0}; Expected output {1}\".format(output, solution))\r\nprint(\"---------------------------\")\r\nprint(\"Test Case 3 - 1, 2, 3, 4, 5, 6\")\r\ninput_list = [1, 2, 3, 4, 5, 6]\r\nsolution = 1173 # 642 + 531\r\noutput = sum(rearrange_digits(input_list))\r\nprint(\"Output: {0}\".format(output))\r\nassert(output == solution)\r\nprint(\"TestCase 3 passed! - Given output {0}; Expected output {1}\".format(output, solution))\r\n"} {"doc_id": "148321b089a05af462829f84272467d5", "text": "\"\"\"\nDescription\n===========\nGiven an array of positive numbers and a postive number k, find the maximum\nsum of any contiguous subarry of size k.\n\nExample #1\n----------\nInput: arr=[2, 1, 5, 1, 3, 2], k=3\nOutput: 9\nExplanation: Subarray with maximum sum is [5, 1, 3].\n\nExample #2\n----------\nInput: arr=[2, 3, 4, 1, 5], k=2\nOutput: 7\nExplanation: Subarray with maximum sum is [3, 4]\n\n\"\"\"\n\n\ndef max_sum_subarray(arr, k):\n \"\"\"Find maximum sum of any contiguous subarray of size k.\n\n Time: O(n)\n Space: O(1)\n \"\"\"\n max_sum = win_sum = 0\n win_start = 0\n for win_end in range(len(arr)):\n win_sum += arr[win_end]\n if win_end >= k - 1:\n max_sum = max(max_sum, win_sum)\n win_sum -= arr[win_start]\n win_start += 1\n return max_sum\n\n"} {"doc_id": "148608c51fa51490790869db4843c367", "text": "\"\"\"\nFind Minimum in Rotated Sorted Array\n------------------------------------\n\nSuppose an array sorted in ascending order is rotated at some pivot\nunknown to you beforehand.\n\n(i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]).\n\nFind the minimum element.\n\nYou may assume no duplicate exists in the array.\n\nExample 1:\n - Input: [3,4,5,1,2]\n - Output: 1\n\nExample 2:\n - Input: [4,5,6,7,0,1,2]\n - Output: 0\n\nReference:\n - https://algorithm.yuanbin.me/zh-hans/binary_search/find_minimum_in_rotated_sorted_array.html\n - https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/\n - https://www.lintcode.com/problem/find-minimum-in-rotated-sorted-array/\n\"\"\"\n\nimport unittest\n\n\ndef find_min(nums):\n \"\"\"\n Find minimum element in rotated sorted array\n\n :param nums: given array\n :type nums: list[int]\n :return: minimum element\n :rtype: int\n \"\"\"\n left, right = 0, len(nums) - 1\n while left + 1 < right:\n mid = (left + right) // 2\n if nums[mid] < nums[right]:\n right = mid\n else:\n left = mid\n if nums[left] < nums[right]:\n return nums[left]\n else:\n return nums[right]\n\n\nclass TestFindMinimumElementInRotatedSortedArray(unittest.TestCase):\n def test_find_minimum_element_in_rotated_sorted_array(self):\n self.assertEqual(1, find_min([3, 4, 5, 1, 2]))\n self.assertEqual(0, find_min([4, 5, 6, 7, 0, 1, 2]))\n\n\nif __name__ == '__main__':\n unittest.main()\n"} {"doc_id": "14b224e4fd591d1c80a6d7388e3df3c3", "text": "#Booleans\n\"\"\"\nprint(10 > 9)\n\nprint(10 == 9)\n\nprint( 10 < 9)\n\n\na = 300\nb = 33000\n\nif b > a:\n print(\"b e maior que a\")\nelse:\n print(\"b e menor que a\")\n\"\"\"\n\"\"\"\n#A maioria dos valores s\u00e3o verdadeiros\nx = \"hello\"\ny = 15\nprint(bool(x))\n\nprint(bool(y))\n\n####################################\n\n\n\"\"\"\n\n#Alguns valores s\u00e3o falsos\n\"\"\"\nprint(bool(False))\nprint(bool(None))\nprint(bool(0))\nprint(bool(\"\"))\nprint(bool(()))\nprint(bool([]))\nprint(bool({}))\n\"\"\"\n\n\"\"\"\"\"\n#exercicio\nclass myclass():\n def __len__(self):\n return 0\n\nmyobj = myclass()\n\nprint(())\n\n\n\"\"\"\"\"\n\"\"\"\"\"\n#Fun\u00e7\u00f5es podem retornar um booleano\n\ndef myFunction():\n return True\n\nprint(myFunction())\n\n\n\ndef myFunction():\n return False\n\nif myFunction():\n print(\"Sim\")\nelse:\n print(\"Nao\")\n\n\"\"\"\"\"\n\nx = 200\n\nprint(isinstance(x, str))"} {"doc_id": "155266da8b9507a4bd530fadde2e28c2", "text": "__source__ = 'https://leetcode.com/problems/unique-morse-code-words/'\n# Time: O()\n# Space: O()\n#\n# Description: Leetcode # 804. Unique Morse Code Words\n#\n# International Morse Code defines a standard encoding where each letter is mapped to a series of dots and dashes,\n# as follows: \"a\" maps to \".-\", \"b\" maps to \"-...\", \"c\" maps to \"-.-.\", and so on.\n#\n# For convenience, the full table for the 26 letters of the English alphabet is given below:\n#\n# [\".-\",\"-...\",\"-.-.\",\"-..\",\".\",\"..-.\",\"--.\",\"....\",\"..\",\".---\",\"-.-\",\".-..\",\"--\",\"-.\",\"---\",\".--.\",\"--.-\",\".-.\",\"...\",\"-\",\"..-\",\"...-\",\".--\",\"-..-\",\"-.--\",\"--..\"]\n# Now, given a list of words, each word can be written as a concatenation of the Morse code of each letter.\n# For example, \"cba\" can be written as \"-.-.-....-\", (which is the concatenation \"-.-.\" + \"-...\" + \".-\").\n# We'll call such a concatenation, the transformation of a word.\n#\n# Return the number of different transformations among all words we have.\n#\n# Example:\n# Input: words = [\"gin\", \"zen\", \"gig\", \"msg\"]\n# Output: 2\n# Explanation:\n# The transformation of each word is:\n# \"gin\" -> \"--...-.\"\n# \"zen\" -> \"--...-.\"\n# \"gig\" -> \"--...--.\"\n# \"msg\" -> \"--...--.\"\n#\n# There are 2 different transformations, \"--...-.\" and \"--...--.\".\n# Note:\n#\n# The length of words will be at most 100.\n# Each words[i] will have length in range [1, 12].\n# words[i] will only consist of lowercase letters.\n#\nimport unittest\n\n# 24ms, 87.72%\nclass Solution(object):\n def uniqueMorseRepresentations(self, words):\n \"\"\"\n :type words: List[str]\n :rtype: int\n \"\"\"\n MORSE = [\".-\",\"-...\",\"-.-.\",\"-..\",\".\",\"..-.\",\"--.\",\n \"....\",\"..\",\".---\",\"-.-\",\".-..\",\"--\",\"-.\",\n \"---\",\".--.\",\"--.-\",\".-.\",\"...\",\"-\",\"..-\",\n \"...-\",\".--\",\"-..-\",\"-.--\",\"--..\"]\n\n seen = {\"\".join(MORSE[ord(c) - ord('a')] for c in word) for word in words}\n return len(seen)\n\nclass TestMethods(unittest.TestCase):\n def test_Local(self):\n self.assertEqual(1, 1)\n\n\nif __name__ == '__main__':\n unittest.main()\n\nJava = '''\n# Thought: https://leetcode.com/problems/unique-morse-code-words/solution/\n# Approach #1: Hash Set [Accepted]\n#\n# Time Complexity: O(S), where S is the sum of the lengths of words in words.\n# We iterate through each character of each word in words.\n# Space Complexity: O(S)\n#\n# 100% 5ms\nclass Solution {\n public int uniqueMorseRepresentations(String[] words) {\n String[] MORSE = new String[]{\".-\",\"-...\",\"-.-.\",\"-..\",\".\",\"..-.\",\"--.\",\n \"....\",\"..\",\".---\",\"-.-\",\".-..\",\"--\",\"-.\",\n \"---\",\".--.\",\"--.-\",\".-.\",\"...\",\"-\",\"..-\",\n \"...-\",\".--\",\"-..-\",\"-.--\",\"--..\"};\n\n Set seen = new HashSet<>();\n for (String word : words) {\n StringBuilder code = new StringBuilder();\n for (char c: word.toCharArray()) {\n code.append(MORSE[c - 'a']);\n }\n seen.add(code.toString());\n }\n return seen.size();\n }\n}\n\n# 90.28% 6ms\nclass Solution {\n public int uniqueMorseRepresentations(String[] words) {\n String alphabet = \"abcdefghijklmnopqrstuvwxyz\";\n String [] morse = {\".-\",\"-...\",\"-.-.\",\"-..\",\".\",\"..-.\",\"--.\",\"....\",\"..\",\".---\",\"-.-\",\".-..\",\"--\",\"-.\",\"---\",\".--.\",\"--.-\",\".-.\",\"...\",\"-\",\"..-\",\"...-\",\".--\",\"-..-\",\"-.--\",\"--..\"} ;\n HashMap table = new HashMap();\n for (int i =0 ; i int:\n pick = choices(self.indices, self.w, k=1)[0]\n return pick\n \n\n\n# Your Solution object will be instantiated and called as such:\n# obj = Solution(w)\n# param_1 = obj.pickIndex()"} {"doc_id": "15da8d911b4e927b3e003db2e4fa9222", "text": "#Programming I\n\n########################\n# Mission 5.2 #\n# Loop even integers #\n########################\n\n#Background\n#==========\n#Write a program that uses while loop to total up the even integers from 1 to 20.\n\n\n#Important Notes\n#===============\n#You MUST use the following variables\n# - total\n# - number\n\n\n\n#START CODING FROM HERE\n#======================\n\n#Set number value\nnumber = 20\n\n\n#Check closest object\ndef total_num(number):\n total = 0\n i=0\n while i<=number:\n if i % 2 == 0:\n total += i\n i+=1\n else:\n i+=1\n \n print('The total is {}'.format(total)) #Modify to display the total\n \n return total #Do not remove this line\n\n \n#Do not remove the next line\ntotal_num(number)\n\n\n#output 110\n"} {"doc_id": "15dfaabae0139836cce49943b75dd4ed", "text": "# Approach: Look at conceptual overview. Simply followed definition of Suffix Trie\n# Construction: Create double loop to go over the suffixes in the described fashion. Assign current_dict back to root on every inner loop. Initialize current_dict[character] = {} or get existing current_dict[character] for every character depending on whether it exists or not. In the end of the inner loop, add * in the end\n# Contains: Until there are characters in the string, check that the current_dict can follow same character starting from root. If at any point it doesn't, return False. If all characters passed through, the current_dict should have a * for it to be a suffix\n\n# Analysis: \n# Construction: O(n*n) space & O(n*n) time\n# Contains: O(m) time (where m is the length of the target string) & O(1) space\n\n# Learning: \n# 1. If you understand the concept well, you will code well. Understand the question super well. Draw it out\n# 2. Then while coding, keep the drawing / conceptual overview / sample input/output in front of you for ease of visualizing test cases\n\n# Do not edit the class below except for the\n# populateSuffixTrieFrom and contains methods.\n# Feel free to add new properties and methods\n# to the class.\n\nclass SuffixTrie:\n def __init__(self, string):\n self.root = {}\n self.endSymbol = \"*\"\n self.populateSuffixTrieFrom(string)\n\n def populateSuffixTrieFrom(self, string):\n length = len(string)\n\t\tfor i in range(length):\n\t\t\t# get back to root for every suffix start\n\t\t\tcurrent_dict = self.root\n\t\t\tfor j in range(i,length):\n\t\t\t\tif string[j] not in current_dict:\n\t\t\t\t\t# if dictionary for a character doesn't exist, create it\n\t\t\t\t\tcurrent_dict[string[j]] = {}\n\t\t\t\tcurrent_dict = current_dict[string[j]]\n\t\t\t# add * at the end of a suffix\n\t\t\tcurrent_dict[self.endSymbol] = True\n\n def contains(self, string):\n current_dict = self.root\n for char in string:\n if char not in current_dict:\n return False\n current_dict = current_dict[char]\n if self.endSymbol in current_dict:\n return True\n return False\n\n"} {"doc_id": "16492f0e5343b7b1fc4d42b047e3d63e", "text": "\"\"\"\nBinary Tree Postorder Traversal\n-------------------------------\n\nGiven a binary tree, return the postorder traversal of its nodes' values.\n\nExample:\n - Input:\n 1\n \\\n 2\n /\n 3\n - Output: [3,2,1]\n\nFollow up: Recursive solution is trivial, could you do it iteratively?\n\nReference:\n - https://algorithm.yuanbin.me/zh-hans/binary_tree/binary_tree_postorder_traversal.html\n - https://leetcode.com/problems/binary-tree-postorder-traversal/\n - https://www.lintcode.com/problem/binary-tree-postorder-traversal/\n\"\"\"\n\nimport unittest\n\nfrom utils import TreeNode\n\n\ndef postorder_traversal_recursive(root):\n \"\"\"\n Return the postorder traversal of nodes' values.\n\n - Worst Time complexity: O(n)\n - Worst Space complexity: O(n)\n\n :param root: root node of given binary tree\n :type root: TreeNode or None\n :return: postorder traversal of nodes' values\n :rtype: list[int]\n \"\"\"\n # basic case\n if root is None:\n return []\n\n # inorder traversal: left + root + right\n left = postorder_traversal_recursive(root.left)\n right = postorder_traversal_recursive(root.right)\n\n return left + right + [root.val]\n\n\ndef postorder_traversal_iterative(root):\n \"\"\"\n Return the postorder traversal of nodes' values.\n\n - Worst Time complexity: O(n)\n - Worst Space complexity: O(n)\n\n :param root: root node of given binary tree\n :type root: TreeNode or None\n :return: postorder traversal of nodes' values\n :rtype: list[int]\n \"\"\"\n # basic case\n if root is None:\n return []\n\n # use stack to traverse\n result = []\n stack = [root]\n prev = None\n while len(stack) != 0:\n curr = stack[-1]\n no_child = curr.left is None and curr.right is None\n child_visited = prev is not None and \\\n (curr.left == prev or curr.right == prev)\n if no_child or child_visited:\n result.append(curr.val)\n stack.pop()\n prev = curr\n else:\n if curr.right is not None:\n stack.append(curr.right)\n if curr.left is not None:\n stack.append(curr.left)\n\n return result\n\n\nclass TestPostorderTraversal(unittest.TestCase):\n def test_postorder_traversal(self):\n # 1\n # \\\n # 2\n # /\n # 3\n root = TreeNode(1)\n root.right = TreeNode(2)\n root.right.left = TreeNode(3)\n self.assertListEqual([3, 2, 1], postorder_traversal_recursive(root))\n self.assertListEqual([3, 2, 1], postorder_traversal_iterative(root))\n\n\nif __name__ == '__main__':\n unittest.main()\n"} {"doc_id": "16906c0730a705b52ff5c9f7d4377028", "text": "# The while Loop in Action\nn = 2 # Could be any number\npower = 0\nval = n\nwhile val < 1000:\n power += 1\n val *= n\nprint(power)\n\n# =================\nn = 249\nlast = n % 10 # Finding the last number is easy\n\nfirst = n # Set it to `n` initially\nwhile first >= 10:\n first //= 10 # Keep dividing by 10 until the leftmost digit is reached.\n\nresult = first + last\nprint(result)\n\n# Cautionary Measures\n# while (True):\n# print(\"Hello World\")\n\nx = 1\nwhile (x > 0):\n x += 5\n"} {"doc_id": "16ae9d3294f0ca23ab4d4d9eeed8290e", "text": "\"\"\"\nQuestion 04: Partition\n\nWrite code to partition a linked list around a value x, such that all nodes less\nthan x come before all nodes greater than or equal to x. If x is contained\nwithin the list, the values of x only need to be after the elements less than x\n(see below). The partition element x can appear anywhere in the \"right\npartition\"; it does not need to appear between the left and right partitions.\n\nExample:\n\nPartition: 15\nInput : [6, 14, 6, 7, 14, 17, 16, 19, 14, 16, 14, 19, 7, 15, 14]\nOutput: [6, 14, 6, 7, 14, 14, 7, 14, 14, 16, 19, 19, 16, 15, 17]\n |------------- < 15 -----------| |------- >= 15 -------|\n\n\"\"\"\n\nimport random\n\n\ndef partition(my_list: list, part: int) -> list:\n \"\"\" Function which performs Partition \"\"\"\n begin = 0\n end = len(my_list) - 1\n while begin < end:\n check_lower = my_list[begin] < part\n check_higher = my_list[end] >= part\n\n if not check_lower and not check_higher:\n # Swap\n my_list[begin], my_list[end] = my_list[end], my_list[begin]\n else:\n if check_lower:\n begin += 1\n if check_higher:\n end -= 1\n\n return my_list\n\n\ndef main():\n # Example of input\n my_list = random.choices(range(20), k=15)\n idx_to_part = random.choice(range(20))\n print(\"Partition:\", idx_to_part)\n print(\"Input :\", my_list)\n print(\"Output:\", partition(my_list, idx_to_part))\n\n\nif __name__ == '__main__':\n main()\n"} {"doc_id": "16bbba7cb9b45107bf863840755cf280", "text": "'''\nWrite a password generator in Python.\nBe creative with how you generate passwords.\nStrong passwords have a mix of lowercase letters,uppercase letters,numbers,and symbols.\nThe passwords should be random, generating a new password every time the user asks for a new password.\nInclude your run-time code in a main method.\n'''\n\nimport random\nimport string\n\nch = 'y'\n\nwhile ch =='y':\n print(\"enter the type of password preferred\")\n ch = int(input(\"1.Weak password\"+\"\\n\"+\"2.Strong Password\"))\n length = int(input(\"enter the length of password: \"))\n password = []\n\n if ch==1:\n for i in range(1,length+1):\n alp = random.choice('abcdefghijklmnopqrstuvwxyz')\n password.append(alp)\n password=''.join(password)\n print(password)\n\n if ch==2:\n for i in range(1,length+1):\n alpnum = random.choice(string.ascii_uppercase+string.ascii_lowercase+string.digits+string.punctuation)\n password.append(alpnum)\n password=''.join(password)\n print(password)\n ch = input(\"do you want to continue (y/n)?\")\n"} {"doc_id": "16ca5d6d80414b36f47a8ac8cdfbd76e", "text": "# countCharsInString.py\r\n\r\n\"\"\"\r\nTitle: Count the Characters in a String \r\nPurpose: Simple Python script to count the characters in a string of text. For example, string **aaabbdcccccf** should yield ***a3b2d1c5f1*** . Similarly, string **hhhhhqqlllllllhhhppp** should yield ***h5q2l7h3p3*** BUT NOT ***h8q2l7p3***.\r\nCoder: Ryan Hunter | GitHub handle: SystemsVanguard | ryan@RyanHunter.org dated 2019-Feb-05\r\n\"\"\"\r\n# use a collections.Counter to automatically iterate through the array & count the number of occurrences per character.\r\nfrom collections import Counter\r\n\r\nmyStartingString = 'aaabbdcccccf'\r\n# myStartingString = \"hhhhhqqlllllllhhhppp\" \r\n# Error! This yields 'h8q217p3' I will fix this very soon.\r\n\r\n\r\nmyCounter = Counter(myStartingString)\r\n# --------->\r\n\r\n# Next, create an ordered list with duplicates removed\r\norderListNoDuplicates = ''.join([j for i,j in enumerate(myStartingString) if j not in myStartingString[:i]])\r\n\r\n# --------->\r\n# for testing only; commented out\r\n# print(\"Ordered List with no duplicates\")\r\n# print(orderListNoDuplicates)\r\n# --------->\r\n\r\nprint(\"--- Step 1A ----> \")\r\nprint('The starting string is \"%s\" , and with duplicates removed and order kept, it is \"%s\". Now we will count the character occurences! ' % (myStartingString, orderListNoDuplicates) )\r\nprint(\" \") # for aesthetics only\r\n\r\n# ------------->\r\n# for testing only. Commented out.\r\n# print(\"--- Step 1B ----> \")\r\n# print(myCounter['a']) # count the number of occurences of the letter 'a'.\r\n\r\n\"\"\"\r\nprint(\"--- Step 1C ----> \")\r\nfor eachLetter in orderListNoDuplicates:\r\n print('%s%d' % (eachLetter, myCounter[eachLetter]) )\r\n\"\"\"\r\n\t\r\nprint(\" \")\r\nprint(\"--- Step 2A ----> \")\r\n# Get the array. Put the members in a horizontal line. Remove the spaces.\r\nfinalOutput = ' '.join(str( '%s%d' % (eachLetter, myCounter[eachLetter]) ) for eachLetter in orderListNoDuplicates).replace(\" \", \"\") \r\n\r\n\r\nprint(finalOutput)\r\n# --- END ---> \r\n\r\n\r\n"} {"doc_id": "16e5bccce265e5f1312b61a848f15d09", "text": "class myClass():\r\n def __init__(self, a, b):\r\n self.a = a\r\n self.b = b\r\n\r\n x = 100\r\n y = 'asbc'\r\n\r\n def test(self):\r\n print('x=', self.x, 'y=', self.y, 'a=', self.a, 'b=', self.b)\r\n return self.x + 1\r\n\r\n\r\nc = myClass(-200, 'hell world-c')\r\nd = myClass(200, 'hello world-d')\r\nprint(c.__init__)\r\nprint(c.__class__)\r\nc.x += 1\r\nprint(c.x, c.y)\r\nprint(d.x, d.y)\r\nc.test()\r\nd.test()\r\n\r\nprint('===========================')\r\n\r\n\r\nclass person:\r\n name = ''\r\n age = 0\r\n __weight = 0 # \u79c1\u6709\u6210\u5458\u53d8\u91cf\r\n\r\n def __init__(self, n, a, w, g):\r\n self.name = n\r\n self.age = a\r\n self.__weight = w\r\n self.__gender = g\r\n\r\n def speak(self):\r\n print(\"{0} say: I am {1}, age is {2} and weight is {3}\".format(self.name, self.__gender, self.age, self.__weight))\r\n\r\n\r\np = person('Jack', 20, 200, 'boy')\r\np.speak()\r\nprint('self.name = ', p.name)\r\ntry:\r\n print('self.__gender = ', p.__weight)\r\nexcept AttributeError:\r\n print(\"Not allowed to externally call a private member '__weight' of the calss \")\r\nelse:\r\n pass\r\n"} {"doc_id": "16f118109d972d7da99c2c451aa2878e", "text": "#the program checks the age, it can be any age you want, if it is less than what you determined it will not let the person in, if it is equal or greater it will\r\n\r\n\r\nfrom time import sleep #importing the sleep library to give a certain time\r\n\r\nprint(\"hello user, enter your name, password and age\")\r\nname=input(\"enter your name: \")\r\nsleep(1) #will wait 1 second\r\npassword=input(\"enter your password: \")\r\nsleep(1) #will wait 1 second\r\nage=int(input(\"enter your age: \"))\r\n\r\nif age<18:\r\n print(\"hi {}, you don't come\".format(name))\r\nif age>=18:\r\n print(\"hi {}, you goes into\".format(name))\r\n\r\n"} {"doc_id": "172dd649e94896f3caf6fca74a18edf4", "text": "\"\"\"\n

Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive.

\n\n

The update(i, val) function modifies nums by updating the element at index i to val.

\n\n

Example:

\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
    \n\t
  1. The array is only modifiable by the update function.
  2. \n\t
  3. You may assume the number of calls to update and sumRange function is distributed evenly.
  4. \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\n

update(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\n
Given nums = [1, 3, 5]\n\nsumRange(0, 2) -> 9\nupdate(1, 2)\nsumRange(0, 2) -> 8\n
\n\n

\u8bf4\u660e:

\n\n
    \n\t
  1. \u6570\u7ec4\u4ec5\u53ef\u4ee5\u5728 update \u51fd\u6570\u4e0b\u8fdb\u884c\u4fee\u6539\u3002
  2. \n\t
  3. \u4f60\u53ef\u4ee5\u5047\u8bbe update \u51fd\u6570\u4e0e sumRange \u51fd\u6570\u7684\u8c03\u7528\u6b21\u6570\u662f\u5747\u5300\u5206\u5e03\u7684\u3002
  4. \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\n

update(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\n
Given nums = [1, 3, 5]\n\nsumRange(0, 2) -> 9\nupdate(1, 2)\nsumRange(0, 2) -> 8\n
\n\n

\u8bf4\u660e:

\n\n
    \n\t
  1. \u6570\u7ec4\u4ec5\u53ef\u4ee5\u5728 update \u51fd\u6570\u4e0b\u8fdb\u884c\u4fee\u6539\u3002
  2. \n\t
  3. \u4f60\u53ef\u4ee5\u5047\u8bbe update \u51fd\u6570\u4e0e sumRange \u51fd\u6570\u7684\u8c03\u7528\u6b21\u6570\u662f\u5747\u5300\u5206\u5e03\u7684\u3002
  4. \n
\n\"\"\"\n\n\nclass NumArray(object):\n\n def __init__(self, nums):\n \"\"\"\n :type nums: List[int]\n \"\"\"\n \n\n def update(self, i, val):\n \"\"\"\n :type i: int\n :type val: int\n :rtype: void\n \"\"\"\n \n\n def sumRange(self, i, j):\n \"\"\"\n :type i: int\n :type j: int\n :rtype: int\n \"\"\"\n \n\n\n# Your NumArray object will be instantiated and called as such:\n# obj = NumArray(nums)\n# obj.update(i,val)\n# param_2 = obj.sumRange(i,j)"} {"doc_id": "173751291a9bc309b519234eebfc219a", "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\"\"\"\nSTOP = -100\n\ndef main():\n\t\"\"\"\n\tThe program will print out the highest temperature, the lowest temperature and the average temperature.\n\tAlso, it will print out how many cold days are there.\n\t\"\"\"\n\tprint('stanCode \\\"Weather Master 4.0\\\"! ')\n\tdata = int(input('Next Temperature: (or ' + str(STOP) + ' to quit)? '))\n\tif data == STOP:\n\t\tprint('No temperatures were entered.')\n\telse:\n\t\tmax = data\n\t\tmin = data\n\t\ttotal = data\n\t\tcount = 1 \t#to record how many pieces of data have been entered\n\t\tcoldday = 0\t\t#to record how many days of cold days(temperature < 16)\n\n\t\tif data < 16:\t#to identify whether the first input temperature is a cold day\n\t\t\tcoldday += 1\n\n\t\twhile True:\n\t\t\ttemp = int(input('Next Temperature: (or ' + str(STOP) + ' to quit)? '))\n\t\t\tif temp == STOP:\n\t\t\t\tbreak\n\t\t\telif temp > max:\n\t\t\t\tmax = temp\n\t\t\telif temp < min:\n\t\t\t\tmin = temp\n\n\t\t\tif temp < 16:\n\t\t\t\tcoldday += 1\n\t\t\ttotal = sum(total, temp)\n\t\t\tcount += 1\n\t\taverage = total / count\n\n\t\tprint('Highest temperature: ' + str(max))\n\t\tprint('Lowest temperature: ' + str(min))\n\t\tprint('Average: ' + str(average))\n\t\tprint(str(coldday) + ' cold day(s)')\n\n\ndef sum(total,temp):\n\t\"\"\"\n\t:param total: the total amount of previously input temperatures\n\t:param temp: the temperature that the user input\n\t:return: total plus temp\n\t\"\"\"\n\tsum = total + temp\n\treturn sum\n\n\n\n\n\n\n\n###### DO NOT EDIT CODE BELOW THIS LINE ######\n\nif __name__ == \"__main__\":\n\tmain()\n"} {"doc_id": "1742e257be0379d1b7013ce6f42aff62", "text": "class Car: # \u041e\u0431\u044a\u044f\u0432\u043b\u0435\u043d\u0438\u0435 \u043a\u043b\u0430\u0441\u0441\u0430 Human\n \"\"\"Car class\"\"\"\n wheels = 4\n\n def drive(self):\n print(\"Car is driving\")\n\n def stop(self):\n print(\"Car stopped\")\n\n\nclass Animal: # \u041e\u0431\u044a\u044f\u0432\u043b\u0435\u043d\u0438\u0435 \u043a\u043b\u0430\u0441\u0441\u0430 Animal\n \"\"\"Animal class\"\"\"\n legs = 4\n\n def make_sound(self):\n print(\"I'm Animal\")\n\n def sleep(self):\n print(\"Animal start sleeping\")\n\n\nprint(\"======= Cars =======\")\n# \u0421\u043e\u0437\u0434\u0430\u0435\u043c \u043e\u0431\u044a\u0435\u043a\u0442\u044b Car\ntoyota = Car()\nhonda = Car()\n\ntoyota.drive()\nhonda.stop()\nprint(honda.wheels)\nprint(toyota.wheels)\n\nprint(\"======= Animals =======\")\n# \u0421\u043e\u0437\u0434\u0430\u0435\u043c \u043e\u0431\u044a\u0435\u043a\u0442\u044b Animal\ndog = Animal()\nlion = Animal()\nprint(dog.legs)\n"} {"doc_id": "1779096e77e6bd819339c3efd909b5c8", "text": "\"\"\"\r\n Selection Sort\r\n --------------\r\n A sorting that uses in-place comparison.\r\n\r\n Time Complexity: O(n**2)\r\n\r\n Space Complexity: O(1) Auxiliary\r\n\r\n Stable: Yes\r\n\r\n Psuedo Code: http://en.wikipedia.org/wiki/Selection_sort\r\n\r\n\"\"\"\r\n\r\n\r\ndef sort(seq):\r\n \"\"\"\r\n Takes a list of integers and sorts them in ascending order. This sorted\r\n list is then returned.\r\n\r\n :param seq: A list of integers\r\n :rtype: A list of sorted integers\r\n \"\"\"\r\n for i in range(0, len(seq)):\r\n iMin = i\r\n for j in range(i+1, len(seq)):\r\n if seq[iMin] > seq[j]:\r\n iMin = j\r\n if i != iMin:\r\n seq[i], seq[iMin] = seq[iMin], seq[i]\r\n\r\n return seq\r\n"} {"doc_id": "17a71342a5dab694aa5653af7419710d", "text": "\"\"\"\nCrie um programa que solicita v\u00e1rios n\u00fameros inteiros ao usu\u00e1rio,\npergunte se ele quer continuar digitando e caso responda n\u00e3o,\ninforme o total de n\u00fameros digitados, o menor, o maior e a\nm\u00e9dia entre eles.\n\"\"\"\n\ntotal = soma = maior = 0\nmenor = 9999999999999999\nresposta = 'S'\n\nwhile resposta in 'S':\n num = int(input('Digite um n\u00famero: '))\n total += 1\n soma += num\n\n if num > maior: # 30 > 0\n maior = num\n\n if num < menor: # 30 < 99999999999999\n menor = num\n\n resposta = str(input('\\033[32mQuer continuar? \\033[m')).upper().strip()\n if resposta == 'N':\n print('Encerrando o sistema')\n print()\n\n# fora do while ------------------------\nprint(f'Total de n\u00famero inseridos: {total}\\nSoma dos n\u00fameros inseridos: {soma}\\n'\n f'M\u00e9dia dos n\u00fameros inseridos: {soma / total:.1f}\\nMaior n\u00famero inserido: {maior}\\n'\n f'Menor n\u00famero inserido: {menor}')\n\n0\n2\n\n0\n\n\n\n1000.0\ntodos = []\n\nwhile True:\n todos.append(int(input('Digite um n\u00famero: ')))\n\n resposta = str(input('Quer continuar: ')).strip().upper()\n\n if resposta == 'N':\n break\n\n if 15 in todos:\n print('Achei')\n\nprint(f'Total de n\u00famero inseridos: {todos}\\nSoma dos n\u00fameros inseridos: {sum(todos)}\\n'\n f'M\u00e9dia dos n\u00fameros inseridos: {sum(todos) / len(todos)}\\nMaior n\u00famero inserido: {max(todos)}\\n'\n f'Menor n\u00famero inserido: {min(todos)}')\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"} {"doc_id": "17b5b4f44552ad008ca4f517e80ade3d", "text": "\"\"\"This module implements higher order functions found in languages\nlike Haskell.\n\n* compose compose a list of functions\n* flip create a function with reversed arguments of another function\n* foldl left-associative reduce\n* foldr right-associatve reduce\n\"\"\"\n\n\nfrom functools import reduce\n\nfrom .utils import last, init\n\n\ndef foldl(function, acc, xs):\n \"\"\"Reduces a sequence with a function in a left-associative manner.\n\n\n It is helpful to visualize the left-fold as the following transformation.\n\n foldl f acc [1, 2, 3, 4, 5]\n\n + f\n / \\ / \\ \n [1] + f 5\n / \\ / \\ \n [2] + f 4\n / \\ / \\ \n [3] + f 3\n / \\ / \\ \n [4] + f 2\n / \\ / \\ \n [5] [] acc 1\n\n Parameters\n ----------\n function : def function(x: B, y: A) -> B\n The combining function.\n acc : B\n The accumulating value.\n xs : Sequence[A]\n The sequence to fold.\n\n Returns\n -------\n B\n The reduced value.\n\n Examples\n --------\n >>> result = foldl(lambda x, y: x-y, 0, [1, 2, 3, 4, 5])\n >>> result == (((((0 - 1) - 2) - 3) - 4) - 5)\n True\n \"\"\"\n return reduce(function, xs, acc)\n\n\ndef foldr(function, acc, xs):\n \"\"\"Reduces a sequence with a function in a right-associative manner.\n\n\n It is helpful to visualize the right-fold as the following transformation.\n\n foldr f acc [1, 2, 3, 4, 5]\n\n + f\n / \\ / \\ \n [1] + 1 f\n / \\ / \\ \n [2] + 2 f\n / \\ / \\ \n [3] + 3 f\n / \\ / \\ \n [4] + 4 f\n / \\ / \\ \n [5] [] 5 acc\n\n Parameters\n ----------\n function : def function(x: A, y: B) -> B\n The combining function.\n acc : B\n The accumulating value.\n xs : Sequence[A]\n The sequence to fold.\n\n Returns\n -------\n B\n The reduced value.\n\n Examples\n --------\n >>> result = foldr(lambda x, y: x-y, 0, [1, 2, 3, 4, 5])\n >>> result == (1 - (2 - (3 - (4 - (5 - 0)))))\n True\n \"\"\"\n return reduce(lambda x, y: function(y, x), reversed(xs), acc)\n\n\ndef compose(*functions):\n \"\"\"Composes a list of function.\n \n Parameters\n ----------\n functions : list\n A list of callables. The argument of the nth function should be of\n the same type as the return type of the n+1th function.\n\n Returns\n -------\n function\n A new function created by composing all the functions.\n\n Examples\n --------\n >>> double = lambda x: x*2\n >>> square = lambda x: x**2\n >>> compose(square, double)(3)\n 36\n >>> (3 * 2) ** 2\n 36\n \"\"\"\n def composed(*args, **kwargs):\n acc = last(functions)(*args, **kwargs)\n return foldr(lambda f, v: f(v), acc, init(functions))\n return composed\n\n\ndef flip(func):\n \"\"\"Reverses the arguments of a function.\n\n Parameters\n ----------\n func : function\n The original function.\n\n Returns\n -------\n function\n A function identical to `func` except it expects arguments in reverse.\n \"\"\"\n def flipped(*args):\n return func(*args[::-1])\n return flipped\n"} {"doc_id": "18275cfd790e09a475fdce2efdb19684", "text": "'''\nProgramma di Nomenclatura dei Composti Binari\n----------------------------------------------------------\nIl programma interpreta una scritta tipo \"HCl\" e visualizza come risultato:\n\"Nomenclatura IUPAC: Cloruro di Idrogeno\n Nomenclatura Tradizionale: Acido Cloridrico\"\n'''\n\n#File utile per i nomi degli elementi\nwith open(\"elementi.txt\", \"r\") as nomi_el:\n #Dizionario che contiene I simboli e i nomi degli elementi\n dic = {}\n #Popolo il dizionario\n while True:\n #Linea di testo estratta\n l = nomi_el.readline()\n\n #Se mi trovo alla fine esco dal ciclo\n if not l:\n break;\n\n #Splitto per \"spazio\" la stringa e inserisco i valori in una lista(simbolo, nome, gruppo, elettronegativita'\n #eventuale suffiso 'uro')\n valori = l.split()\n\n #Inserisco per ogni elemento i valori nel dizionario\n dic[valori[0]] = (valori[1], valori[2], valori[3], valori[4])\n\n#formula chimica nel formato \"PCl3\" (elemento-indice)\nwhile True:\n ins_form = input(\"|Inserisci la formula chimica|: \")\n #se la stringa inserita ha una lunghezza uguale a zero ritorna un messaggio d'errore\n if len(ins_form) == 0:\n print(\"---!Il campo non pu\u00f2 rimanere vuoto!---\\n\")\n #se la lunghezza \u00e8 maggiore di zero, rompe il while True\n else:\n break\n\n#Lista che contiene gli elementi scritti nella formula\nelementi = []\n\n#lista che contiene gli indici degli elementi\nindici = []\n\n#Leggo ogni lettera in formula\nfor i in range(len(ins_form)):\n if ins_form[i].isupper() == True: #Controllo se la lettera e' maiuscola o minuscola per memorizzare l'elemento\n if (len(ins_form) - 1) == i: #Se mi trovo a fine riga\n elementi.append(ins_form[i]) #Inserisco l'elemento nella lista per evitare che il programma vada a cercare nel carattere successivo della lista (che non esiste)\n indici.append(1) #L'indice e' necessariamente 1\n else: #Non mi trovo a fine riga\n if ins_form[i+1].isupper() == True: #Se anche quella dopo e' maiuscola la memorizzo nella lista\n elementi.append(ins_form[i])\n indici.append(1) #Aggiungo l'indice \"1\" alla lista\n elif ins_form[i+1].islower() == True:\n elementi.append(ins_form[i] + ins_form[i + 1]) #Se la lettera dopo e' minuscola inserisco entrambe le lettere nella lista\n #Controllo se dopo c'e' un indice\n if (i + 1) == (len(ins_form) - 1): #Se questo era l'ultimo carattere\n indici.append(1) #L'indice e' necessariamente 1\n elif ins_form[i+2].isdigit() == True: #Controllo l'indice\n indici.append(int(ins_form[i+2]))\n elif ins_form[i+2].isupper() == True: #Altrimenti la lettera dopo e' maiuscola e l'indice e' 1\n indici.append(1)\n\n elif ins_form[i+1].isdigit() == True: #Se la lettera dopo e' una cifra (indice)\n elementi.append(ins_form[i]) #Aggiungo il primo elemento alla lista\n indici.append(int(ins_form[i+1])) #Aggiungo l'indice del primo elemento alla lista\n\n\n'''Nomenclatura IUPAC'''\n\n#Nome finale IUPAC\nnomeIupac = \"\"\n\n#Prefissi della IUPAC\nprefissi = [\"Mono\", \"Di\", \"Tri\", \"Tetra\", \"Penta\", \"Esa\", \"Epta\", \"Octo\", \"Enna\", \"Deca\"]\n\n'''Ossidi IUPAC'''\n#Per essere un Ossido binario il composto deve avere al suo interno l'Ossigeno\nfor i in range(len(elementi)):\n if elementi[i] == \"O\":\n #Indice ossigeno\n ind_oss = indici[i]\n #Trovo l'indice dell'altro elemento.\n for x in range(len(indici)):\n if x != i:\n #indice altro elemento\n ind_2 = indici[x]\n #Simbolo altro elemento\n elem_2 = elementi[x]\n #formula IUPAC dell'Ossido (la lista prefissi e' sfalsata di 1 rispetto agli indici degli elementi)\n nomeIupac = f\"{prefissi[ind_oss - 1]}ossido di {prefissi[ind_2 - 1]}{dic[elem_2][0]}\"\n\n\n'''Idruri e Idrossidi IUPAC '''\n#Per essere un idruro il composto binario deve avere al suo Interno l'Idrogeno e l'altro elemento\n#Non deve appartenere ai gruppi 16-17, viceversa e' un idrossido\nfor i in range(len(elementi)):\n if elementi[i] == \"H\":\n #Indice Idrogeno\n ind_idr = indici[i]\n #Trovo l'indice dell'altro elemento.\n for x in range(len(indici)):\n if x != i:\n #indice altro elemento\n ind_2 = indici[x]\n #Simbolo altro elemento\n elem_2 = elementi[x]\n\n #Verifico che l'elemento non faccia parte del gruppo 16-17\n if (dic[elem_2][1] not in (\"16\", \"17\")):\n nomeIupac = f\"{prefissi[ind_idr - 1]}idruro di {prefissi[ind_2 - 1]}{dic[elem_2][0]}\"\n else:#Idracido\n nomeIupac = f\"{dic[elem_2][3]} di {prefissi[ind_idr - 1]}idrogeno\"\n\n\nprint(f\"formula IUPAC: {nomeIupac}\")\n"} {"doc_id": "1856bbf93b87cc5b1bf6d896f9c69056", "text": "'''\n# F\u00f3rmula de Bhaskara\n\nLeia 3 valores de ponto flutuante e efetue o c\u00e1lculo das ra\u00edzes da equa\u00e7\u00e3o de Bhaskara. Se n\u00e3o for poss\u00edvel calcular as ra\u00edzes, mostre a mensagem correspondente \u201cImpossivel calcular\u201d, caso haja uma divis\u00e3o por 0 ou raiz de numero negativo.\n\n**Input**\nLeia tr\u00eas valores de ponto flutuante (double) A, B e C.\n\n**Output**\nSe n\u00e3o houver possibilidade de calcular as ra\u00edzes, apresente a mensagem \"Impossivel calcular\". Caso contr\u00e1rio, imprima o resultado das ra\u00edzes com 5 d\u00edgitos ap\u00f3s o ponto, com uma mensagem correspondente conforme exemplo abaixo. Imprima sempre o final de linha ap\u00f3s cada mensagem.\n\n| Input Sample | Output Samples |\n| -------------- | ------------------- |\n| 10.0 20.1 5.1 | R1 = -0.29788 |\n| | R2 = -1.71212 |\n| 0.0 20.0 5.0 | Impossivel calcular |\n| 10.3 203.0 5.0 | R1 = -0.02466 |\n| | R2 = -19.68408 |\n| 10.0 3.0 5.0 | Impossivel calcular |\n'''\n\nv = input().split()\na, b, c = v\n\na = float(a)\nb = float(b)\nc = float(c)\n\nif a == 0.0 or (b ** 2 - 4 * a * c) < 0:\n print('Impossivel calcular')\nelse:\n x1 = (- b + (b ** 2 - 4 * a * c) ** (1/2) )/(2 * a)\n x2 = (- b - (b ** 2 - 4 * a * c) ** (1/2) )/(2 * a)\n print('R1 = {:.5f}'.format(x1))\n print('R2 = {:.5f}'.format(x2))"} {"doc_id": "1899fb9d1dc1e731e02e0d661b727471", "text": "# https://www.geeksforgeeks.org/inorder-successor-in-binary-search-tree/\r\n\r\nclass TreeNode:\r\n def __init__(self, data, left=None, right=None):\r\n self.data = data\r\n self.left = left\r\n self.right = right\r\n\r\n def inorder_traversal_recursive(self, root):\r\n if not root:\r\n return\r\n self.inorder_traversal_recursive(root.left)\r\n print (root.data, end = ' -> ')\r\n self.inorder_traversal_recursive(root.right)\r\n\r\n def inorder_successor(self, root, data):\r\n if not root:\r\n return\r\n\r\n next = None\r\n while root:\r\n if root.data > data:\r\n next = root\r\n root = root.left\r\n else:\r\n root = root.right\r\n return next.data\r\n\r\n def inorder_traversal_iterative(self, root):\r\n if not root:\r\n return\r\n stack, current = [root], root\r\n while stack or current:\r\n if current:\r\n stack += current,\r\n current = current.left\r\n else:\r\n popped = stack.pop()\r\n print (popped.data, end = ' -> ')\r\n current = popped.right\r\n return\r\n\r\n def preorder_traversal_iterative(self, root):\r\n if not root:\r\n return\r\n stack = [root]\r\n while stack:\r\n popped = stack.pop()\r\n print (popped.data, end = ' -> ')\r\n if popped.right:\r\n stack += popped.right,\r\n if popped.left:\r\n stack += popped.left,\r\n return\r\n\r\n def postorder_traversal_iterative(self, root):\r\n if not root:\r\n return\r\n stack, stack_reverse = [root], []\r\n while stack:\r\n popped = stack.pop()\r\n stack_reverse += popped,\r\n if popped.left:\r\n stack += popped.left,\r\n if popped.right:\r\n stack += popped.right,\r\n\r\n while stack_reverse:\r\n print (stack_reverse.pop().data, end = ' -> ')\r\n return\r\n\r\n def inorder_successor_iterative(self, root, data):\r\n if not root or not data:\r\n return\r\n stack, current = [root], root\r\n flag = False\r\n while stack or current:\r\n if current:\r\n stack += current,\r\n current = current.left\r\n else:\r\n popped = stack.pop()\r\n if flag:\r\n return popped.data\r\n elif popped.data == data:\r\n flag = True\r\n current = popped.right\r\n return\r\n\r\nif __name__ == '__main__':\r\n root = TreeNode(20)\r\n root.left = TreeNode(8)\r\n root.left.left = TreeNode(4)\r\n root.left.right = TreeNode(12)\r\n root.left.right.left = TreeNode(10)\r\n root.left.right.right = TreeNode(14)\r\n\r\n root.right = TreeNode(22)\r\n root.inorder_traversal_recursive(root)\r\n print ()\r\n\r\n # Printing the inorder successor\r\n print (\"Inorder Successor: \", root.inorder_successor(root, 8))\r\n print (\"Inorder Successor: \", root.inorder_successor(root, 10))\r\n print (\"Inorder Successor: \", root.inorder_successor(root, 14))\r\n\r\n # Exploring various traversals\r\n print (\"Inorder Traversal : \")\r\n root.inorder_traversal_iterative(root)\r\n print ()\r\n\r\n print (\"Preorder Traversal : \")\r\n root.preorder_traversal_iterative(root)\r\n print ()\r\n\r\n print (\"Postorder Traversal : \")\r\n root.postorder_traversal_iterative(root)\r\n print ()\r\n\r\n print ('--------------------------------------')\r\n # Printing the inorder successor\r\n print (\"Inorder Successor: \", root.inorder_successor_iterative(root, 8))\r\n print (\"Inorder Successor: \", root.inorder_successor_iterative(root, 10))\r\n print (\"Inorder Successor: \", root.inorder_successor_iterative(root, 14))\r\n"} {"doc_id": "189b3af44e0e27d057d1f2ee04aedbcc", "text": "'''\nA password is said to be strong if it satisfies all the following criteria:\n\nIt has at least 8 characters.\nIt contains at least one lowercase letter.\nIt contains at least one uppercase letter.\nIt contains at least one digit.\nIt contains at least one special character. The special characters are the characters in the following string: \"!@#$%^&*()-+\".\nIt does not contain 2 of the same character in adjacent positions (i.e., \"aab\" violates this condition, but \"aba\" does not).\nGiven a string password, return true if it is a strong password. Otherwise, return false.\n'''\n\nclass Solution:\n def strongPasswordCheckerII(self, password: str) -> bool:\n p = password\n if len(p) < 8:\n return False\n low = 0\n for i in p:\n if i.islower():\n low +=1\n if low == 0:\n return False\n up = 0\n for i in p:\n if i.isupper():\n up+=1\n if up == 0:\n return False\n\n dig = 0\n for i in p:\n if i.isdigit():\n dig+=1\n if dig == 0:\n return False\n spec = 0\n for i in p:\n if i in \"!@#$%^&*()-+\":\n spec+=1\n if spec == 0:\n return False\n\n for i in range(len(p)-1):\n if p[i] == p[i+1]:\n return False\n return True\n \n---------------------------------\nclass Solution(object):\n def strongPasswordCheckerII(self, password):\n \"\"\"\n :type password: str\n :rtype: bool\n \"\"\"\n n = len(password)\n hasLower = False\n hasUpper = False\n hasDigit = False\n specialChar = False\n spcl_char= \"!@#$%^&*()-+\"\n for i in range(n):\n if password[i].islower():\n hasLower = True\n if password[i].isupper():\n hasUpper = True\n if password[i].isdigit():\n hasDigit = True\n if password[i] in spcl_char:\n specialChar = True\n for i in range(1,n):\n if(password[i-1]==password[i]):\n return False\n \n if (hasLower and hasUpper and hasDigit and specialChar and n >= 8):\n return True\n else:\n return False\n"} {"doc_id": "18c585536d2b28a043806d5d4ef4f7a9", "text": "\"\"\"\nRemove Duplicates from Sorted Array\n-----------------------------------\n\nGiven a sorted array nums, remove the duplicates in-place such that\neach element appear only once and return the new length.\n\nDo not allocate extra space for another array, you must do this by\nmodifying the input array in-place with O(1) extra memory.\n\nExample 1:\n - Given nums = [1,1,2],\n - Your function should return length = 2, with the first two\n elements of nums being 1 and 2 respectively.\n - It doesn't matter what you leave beyond the returned length.\n\nExample 2:\n - Given nums = [0,0,1,1,1,2,2,3,3,4],\n - Your function should return length = 5, with the first five\n elements of nums being modified to 0, 1, 2, 3, and 4 respectively.\n - It doesn't matter what values are set beyond the returned length.\n\nClarification:\n Confused why the returned value is an integer but your answer is an array?\n Note that the input array is passed in by reference, which means\n modification to the input array will be known to the caller as well.\n\nReference:\n - https://algorithm.yuanbin.me/zh-hans/integer_array/remove_duplicates_from_sorted_array.html\n - https://leetcode.com/problems/remove-duplicates-from-sorted-array/\n - https://www.lintcode.com/problem/remove-duplicates-from-sorted-array/\n\"\"\"\n\nimport unittest\n\n\ndef remove_duplicates(nums):\n \"\"\"\n Remove the duplicates in the given sorted array in-place\n\n :param nums: given array\n :type nums: list[int]\n :return: new length\n :rtype: int\n \"\"\"\n if len(nums) <= 1:\n return len(nums)\n new_length = 0\n for i in range(len(nums)):\n if nums[i] != nums[new_length]:\n new_length += 1\n nums[new_length] = nums[i]\n return new_length + 1\n\n\nclass TestRemoveDuplicatesFromSortedArray(unittest.TestCase):\n def test_remove_duplicates_from_sorted_array(self):\n nums = [1, 1, 2]\n self.assertEqual(2, remove_duplicates(nums))\n self.assertListEqual([1, 2], nums[:2])\n\n nums = [0, 0, 1, 1, 1, 2, 2, 3, 3, 4]\n self.assertEqual(5, remove_duplicates(nums))\n self.assertListEqual([0, 1, 2, 3, 4], nums[:5])\n\n\nif __name__ == '__main__':\n unittest.main()\n"} {"doc_id": "18ef4763e8ae22b1cc9c4c5169c44566", "text": "# Somethings wrong getting constant indent and capt errors that I am not executing.\n# !! : you defined a function at the top of your file (main) with nothing in it so the IDE is teling you to put something in the function \n\n# def main():\n\n# Problem 1\n# Create a printNumbers function to print integers from -25 to 20 to the console (print in the function)\ndef print_numbers(): # !! : you never call this function \n x = range(-25,20)\n for idx in x:\n return idx \n\n# Problem 2\n# Create a function called checkPassword. Send two string variables to the checkPassword function to check if the strings are equal. Return true if they are equal and false if they are not equal. Print the function's return value.\n# !! : SEND two string variables to the checkPassword function\ndef checkPassword(): # !! : you never call this function \n askUser = int(input(\"Enter Password: \"))\n askUser2 = int(input(\"Enter another pw: \"))\n if askUser == askUser2:\n return (\"Correct\")\n else:\n return(askUser2)\n\n# Problem 3\n#\n# Write a function that determines if a number passed to it is odd or even. Pass a number of your choosing (using input a good idea) and then using the result from the function, print if the number was even or not.\n#\n# examples:\n# The number 12 is an even number!\n# The number 5 is an odd number!\n\n\n# main()"} {"doc_id": "191b1c4e94129b3a11555913670b4978", "text": "'''\nCalculate Area of Polygon\n\nGiven ordered coordinates of a polygon with n vertices. Find area of the polygon.\nHere ordered mean that the coordinates are given either in clockwise manner or anticlockwise from first vertex to last.\n\nInput: [(0, 0), (3, 0), (3, 2), (0, 2)]\nOutput: 6.0\nOutput explanation: The polygon is a 3x2 rectangle parallel with the X axis. The area is 6 (3*2).\n\n=========================================\nUse Shoelace formula (https://en.wikipedia.org/wiki/Shoelace_formula).\nabs( 1/2 ((X1Y2 + X2Y3 + ... + Xn-1Yn + XnY1) - (X2Y1 + X3Y2 + ... + XnYn-1 + X1Yn)) )\n Time Complexity: O(N)\n Space Complexity: O(1)\n'''\n\n\n############\n# Solution #\n############\n\ndef calculate_area_of_polygon(polygon):\n n = len(polygon)\n prev = polygon[-1]\n area = 0\n\n for curr in polygon:\n area += (prev[0] + curr[0]) * (prev[1] - curr[1])\n prev = curr\n\n return abs(area / 2) # return absolute value\n\n\n###########\n# Testing #\n###########\n\n# Test 1\n# Correct result => 6.0\nprint(calculate_area_of_polygon([(0, 0), (3, 0), (3, 2), (0, 2)]))"} {"doc_id": "1924edc57c127e55fcb889cf757314ba", "text": "\n# coding: utf-8\n\n# # Introducing Pandas\n# \n# From the [docs](http://pandas.pydata.org/pandas-docs/stable/index.html):\n# \n# > A Python package providing fast, flexible, and expressive data structures designed to make working with \u201crelational\u201d or \u201clabeled\u201d data both easy and intuitive.\n# \n# We also use [matplotlib](http://matplotlib.org/):\n# \n# > A Python 2D plotting library which produces publication quality figures in a variety of hardcopy formats and interactive environments across platforms.\n# \n# Requirements:\n# \n# ```\n# (venv) $ pip install pandas matplotlib\n# ```\n# \n# We're going to see a sliver of the functionality provided by these packages.\n\n# In[1]:\n\nimport pandas as pd\npd.options.display.max_rows = 20\n\nget_ipython().magic('matplotlib inline')\n\n\n# ## Introducing `DataFrame`\n\n# From the [docs](http://pandas.pydata.org/pandas-docs/stable/dsintro.html#dataframe):\n# \n# > __DataFrame__ is a 2-dimensional labeled data structure with columns of potentially different types. You can think of it like a spreadsheet or SQL table. It is generally the most commonly used pandas object.\n# \n# There are many ways to get a `DataFrame`, but we'll start with a list of dictionaries.\n\n# In[2]:\n\ndf = pd.DataFrame([\n {'integer': 1, 'float': 1.0, 'string': 'one'},\n {'integer': 2, 'float': 2.0, 'string': 'two'},\n {'integer': 2, 'float': 2.0, 'string': 'two'},\n {'integer': 3, 'float': 3.0, 'string': 'three'},\n])\n\n# Print some details about the DataFrame\ndf.info()\ndf\n\n\n# The Jupyter Notebook automatically renders `DataFrame` as HTML!\n# \n# Note the first column; this is an `Index`, and is an essential component of `DataFrame`. Here, it was auto-generated, but we can also set it:\n\n# In[3]:\n\ndf_index = df.set_index('string')\ndf_index\n\n\n# The `Index` plays a key role in slicing the `DataFrame`:\n\n# In[4]:\n\n# Slice by label\ndf_index.loc['two']\n\n\n# In[5]:\n\n# Slice by position\ndf_index.iloc[-2:]\n\n\n# We can also get individual columns:\n\n# In[6]:\n\nfloats = df_index['float']\nfloats\n\n\n# This is a `Series`, which is essentially a one-dimensional `DataFrame`, with a defined data type. Put another way, a `DataFrame` is a collection of `Series`.\n# \n# Note that the `Series` retained the `Index` of our `DataFrame`, so we can use similar slicing:\n\n# In[7]:\n\nfloats['two']\n\n\n# `Series` and `DataFrame` support element-wise operations:\n\n# In[8]:\n\ndf_index['float'] * df_index['integer']\n\n\n# In[9]:\n\ndf_index * df_index\n\n\n# In[10]:\n\nnumber_format = 'Number {}'.format\ndf_index['integer'].apply(number_format)\n\n\n# In[11]:\n\ndf_index.applymap(number_format)\n\n\n# ## Using `DataFrame` with Django\n\n# Django gives us a handy way to build a list of dictionaries:\n\n# In[12]:\n\ngig_values = Gig.objects.past().published().values('date', 'venue__name', 'venue__city')\ngig_values[:5]\n\n\n# `DataFrame` doesn't know what to do with a `QuerySet`; it wants something that looks more like a list. \n# We could use `list(gig_values)`, but `gig_values.iterator()` is more efficient.\n\n# In[13]:\n\ngigs = pd.DataFrame(gig_values.iterator())\ngigs.info()\ngigs\n\n\n# This is a good place to start, and we've already got the answer to \"How many gigs have we played\"?\n# \n# However, there are a few ways we can make this easier to work with:\n# \n# - Shorter column names\n# - Predictable column order\n# - Indexed and sorted by date\n# \n# For more control, we'll use a list of tuples to initialize the DataFrame.\n\n# In[14]:\n\ngig_values = Gig.objects.past().published().values_list('date', 'venue__name', 'venue__city')\ngig_values[:5]\n\n\n# In[15]:\n\ngigs = pd.DataFrame(gig_values.iterator(), columns=['date', 'venue', 'city'])\n\ngigs['date'] = pd.to_datetime(gigs['date'])\ngigs = gigs.set_index('date').sort_index()\n\ngigs.info()\ngigs.head()\n\n\n# The previous cell demonstrates a good practice: make all of your modifications to a variable in one cell. This will help prevent surprises when you execute cells out of order as you play with code. If you need to make modifications later in the notebook, assign the result to a new variable.\n\n# ## Answering questions\n# \n# \n# ### What gigs did we play last year?\n\n# Using the date as the `Index` allows for fast slicing:\n\n# In[16]:\n\ngigs.loc['2016']\n\n\n# ### How many gigs have we played each year?\n\n# The date `Index` also allows for fast aggregration:\n\n# In[17]:\n\n# resample('A') creates year-end groups like '2005-12-31'\n# to_period() turns that into '2005'\nyears = gigs.resample('A').size().to_period()\nyears\n\n\n# In[18]:\n\nyears.plot.bar()\n\n\n# ### What are our most active months?\n\n# Get the dates as a `Series`:\n\n# In[19]:\n\ngig_dates = gigs.reset_index()['date']\ngig_dates\n\n\n# Convert those to sortable month names:\n\n# In[20]:\n\n# Series.dt gives us access to date-related methods\ngig_months = gig_dates.dt.strftime('%m %b')\ngig_months\n\n\n# Count the unique values:\n\n# In[21]:\n\nmonths = gig_months.value_counts()\nmonths\n\n\n# In[22]:\n\n# matplotlib has lots of options for customization\nax = months.sort_index().plot.bar(table=True, figsize=(10,5))\nax.get_xaxis().set_visible(False)\n\n\n# ### What cities have we played?\n\n# In[23]:\n\ngig_cities = gigs['city']\ngig_cities\n\n\n# In[24]:\n\ncities = gig_cities.value_counts()\ncities\n\n\n# In[25]:\n\ncities.describe()\n\n\n# In[26]:\n\n# Adding the ; suppresses ``\ncities[:10].sort_values().plot.barh();\n\n\n# When did we play in Pittsburgh?\n# \n# We can use a `Series` of boolean values to slice our `DataFrame`:\n\n# In[27]:\n\n# Series.str gives us access to string methods\nin_pgh = gig_cities.str.contains('Pittsburgh')\nin_pgh\n\n\n# In[28]:\n\ngigs[in_pgh]\n\n\n# ### What states have we played?\n# \n# The `Gig` model doesn't have a `state` field, so we need to parse it out. In vanilla Python, we'd do:\n\n# In[29]:\n\n'Boston, MA'.split(',')[1].strip()\n\n\n# With pandas, we can do the same thing for every `Series` element:\n\n# In[30]:\n\nstates = gig_cities.str.split(',').str.get(1).str.strip().value_counts()\nstates\n\n\n# In[31]:\n\nstates.describe()\n\n\n# In[32]:\n\n# Don't rotate the x-axis labels\nstates[:5].plot.bar(rot=0);\n\n\n# ### What venues have we played?\n\n# `DataFrame` has powerful grouping and aggregration functionality:\n\n# In[33]:\n\nvenues = gigs.groupby(['venue', 'city']).size()\nvenues\n\n\n# This `Series` has a `MultiIndex`. Very useful, but beyond the scope of this presentation...\n\n# In[34]:\n\nvenues.describe()\n\n\n# In[35]:\n\ntop_venues = venues.nlargest(10)\ntop_venues\n\n\n# In[36]:\n\ntop_venues.sort_values().plot.barh();\n\n\n# In[ ]:\n\n\n\n"} {"doc_id": "19428b1de0c6cd39c848746b8a3275d1", "text": "\"\"\"\nFile: hangman_\u8b1d\u6fe1\u99ff.py\n-----------------------------\nThis program plays hangman game.\nUsers sees a dashed word, trying to\ncorrectly figure the un-dashed word out\nby inputting one character each round.\nIf the user input is correct, show the\nupdated word on console. Players have N_TURNS\nto try in order to win this game.\n\"\"\"\n\n\nimport random\n\n\n# This constant controls the number of guess the player has\nN_TURNS = 7\n# This constant allows the game to be extended to use the words with more characters.\nN_GUESSES = 100\n\n\ndef main():\n \"\"\"\n crucial point is using string substitution technique to piece the answer together\n \"\"\"\n w = random_word()\n ans = '-' * len(w) # Let ans as a word filled with blank.\n print('The word looks like: ' + ans)\n print('You have ' + str(N_TURNS) + ' guesses left.')\n n = N_TURNS\n for i in range(N_GUESSES): # Allows longer word to be guessed.\n a = input('Your guess: ')\n ua = a.upper() # check case-insensitive\n if w.find(ua) == -1:\n print('There is no ' + ua + 's in the word.')\n n -= 1\n if n == 0:\n print('You are completely hung :(')\n print('The word was: ' + w)\n break\n else:\n print('You have ' + str(n) + ' guesses left.')\n else:\n for j in range(len(w)):\n ch = w[j]\n if ua == ch:\n ans = ans[0:j] + ch + ans[j+1:]\n else:\n ans = ans[0:j] + ans[j] + ans[j+1:]\n print('You are correct!')\n if ans == w: # check if the game still on\n print('You win!!')\n print('The word was: ' + w)\n break\n else:\n print('The word looks like: ' + ans)\n\n\ndef random_word():\n num = random.choice(range(9))\n if num == 0:\n return \"NOTORIOUS\"\n elif num == 1:\n return \"GLAMOROUS\"\n elif num == 2:\n return \"CAUTIOUS\"\n elif num == 3:\n return \"DEMOCRACY\"\n elif num == 4:\n return \"BOYCOTT\"\n elif num == 5:\n return \"ENTHUSIASTIC\"\n elif num == 6:\n return \"HOSPITALITY\"\n elif num == 7:\n return \"BUNDLE\"\n elif num == 8:\n return \"REFUND\"\n\n\n##### DO NOT EDIT THE CODE BELOW THIS LINE #####\nif __name__ == '__main__':\n main()\n"} {"doc_id": "194d2fb557d8635bf40b3d4c7a3ddd58", "text": "\"\"\"\n

Given 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\n

Words 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\n
    \n\t
  • 1 <= paragraph.length <= 1000.
  • \n\t
  • 1 <= banned.length <= 100.
  • \n\t
  • 1 <= banned[i].length <= 10.
  • \n\t
  • The answer is unique, and written in lowercase (even if its occurrences in paragraph may have uppercase symbols, and even if it is a proper noun.)
  • \n\t
  • paragraph only consists of letters, spaces, or the punctuation symbols !?',;.
  • \n\t
  • Different words in paragraph are always separated by a space.
  • \n\t
  • There are no hyphens or hyphenated words.
  • \n\t
  • Words only consist of letters, never apostrophes or other punctuation symbols.
  • \n
\n\n

 

\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\n
    \n\t
  • 1 <= \u6bb5\u843d\u957f\u5ea6 <= 1000.
  • \n\t
  • 1 <= \u7981\u7528\u5355\u8bcd\u4e2a\u6570 <= 100.
  • \n\t
  • 1 <= \u7981\u7528\u5355\u8bcd\u957f\u5ea6 <= 10.
  • \n\t
  • \u7b54\u6848\u662f\u552f\u4e00\u7684, \u4e14\u90fd\u662f\u5c0f\u5199\u5b57\u6bcd (\u5373\u4f7f\u5728 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)
  • \n\t
  • paragraph \u53ea\u5305\u542b\u5b57\u6bcd\u3001\u7a7a\u683c\u548c\u4e0b\u5217\u6807\u70b9\u7b26\u53f7!?',;.
  • \n\t
  • paragraph \u91cc\u5355\u8bcd\u4e4b\u95f4\u90fd\u7531\u7a7a\u683c\u9694\u5f00\u3002
  • \n\t
  • \u4e0d\u5b58\u5728\u6ca1\u6709\u8fde\u5b57\u7b26\u6216\u8005\u5e26\u6709\u8fde\u5b57\u7b26\u7684\u5355\u8bcd\u3002
  • \n\t
  • \u5355\u8bcd\u91cc\u53ea\u5305\u542b\u5b57\u6bcd\uff0c\u4e0d\u4f1a\u51fa\u73b0\u7701\u7565\u53f7\u6216\u8005\u5176\u4ed6\u6807\u70b9\u7b26\u53f7\u3002
  • \n
\n

\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\n
    \n\t
  • 1 <= \u6bb5\u843d\u957f\u5ea6 <= 1000.
  • \n\t
  • 1 <= \u7981\u7528\u5355\u8bcd\u4e2a\u6570 <= 100.
  • \n\t
  • 1 <= \u7981\u7528\u5355\u8bcd\u957f\u5ea6 <= 10.
  • \n\t
  • \u7b54\u6848\u662f\u552f\u4e00\u7684, \u4e14\u90fd\u662f\u5c0f\u5199\u5b57\u6bcd (\u5373\u4f7f\u5728 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)
  • \n\t
  • paragraph \u53ea\u5305\u542b\u5b57\u6bcd\u3001\u7a7a\u683c\u548c\u4e0b\u5217\u6807\u70b9\u7b26\u53f7!?',;.
  • \n\t
  • paragraph \u91cc\u5355\u8bcd\u4e4b\u95f4\u90fd\u7531\u7a7a\u683c\u9694\u5f00\u3002
  • \n\t
  • \u4e0d\u5b58\u5728\u6ca1\u6709\u8fde\u5b57\u7b26\u6216\u8005\u5e26\u6709\u8fde\u5b57\u7b26\u7684\u5355\u8bcd\u3002
  • \n\t
  • \u5355\u8bcd\u91cc\u53ea\u5305\u542b\u5b57\u6bcd\uff0c\u4e0d\u4f1a\u51fa\u73b0\u7701\u7565\u53f7\u6216\u8005\u5176\u4ed6\u6807\u70b9\u7b26\u53f7\u3002
  • \n
\n\"\"\"\n\n\nclass Solution:\n def mostCommonWord(self, paragraph, banned):\n \"\"\"\n :type paragraph: str\n :type banned: List[str]\n :rtype: str\n \"\"\"\n "} {"doc_id": "1992d43fb4b9d6204b95f2ac4bb8aea6", "text": "\"\"\"\nFile: caesar.py\nName: Elven Liu\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\ndef main():\n \"\"\"\n Users will enter a number to shift all ALPHABET. Then users will enter a ciphered string and the program\n will translate the ciphered string to the deciphered one.\n \"\"\"\n\n number = int(input('Secret number: '))\n word = input(\"What's the ciphered string? \")\n word = word.upper()\n\n ans = \"\"\n for i in range(len(word)):\n # for sentences with blanks to print \" \"\n if word[i] == \" \":\n ans += \" \"\n else:\n p = ALPHABET.find(word[i])\n # for the scenario that p can be found in the ALPHABET\n if p != -1:\n if p + number >= len(ALPHABET):\n ans += ALPHABET[p + number - len(ALPHABET)]\n else:\n ans += ALPHABET[p + number]\n # to print the punctuation marks(, . ! ?)\n else:\n ans += word[i]\n\n print('The deciphered string is: ' +str(ans))\n\n\n##### DO NOT EDIT THE CODE BELOW THIS LINE #####\nif __name__ == '__main__':\n main()\n"} {"doc_id": "19a40df5adbee3ce6286c627248f49dc", "text": "# https://www.hackerrank.com/challenges/python-string-split-and-join/problem\n\n# this is a string => this-is-a-string\n# 123 456 789 => 123-456-789\n# ... ... ... => ...-...-...\n\ndef split_and_join(line):\n new_line = ''\n\n for c in line:\n if c == ' ':\n new_line += '-'\n else:\n new_line += c\n\n return new_line\n\nprint(split_and_join('this is a string'))\nprint(split_and_join('123 456 789'))\nprint(split_and_join('... ... ...'))\nprint(split_and_join('... ... ... '))\n"} {"doc_id": "19a6d221b8380a12be2587be9161f214", "text": "\"\"\"\nFile: similarity.py\nName: Cage\n----------------------------\nThis program compares short dna sequence, s2,\nwith sub sequences of a long dna sequence, s1\nThe way of approaching this task is the same as\nwhat people are doing in the bio industry.\n\"\"\"\n\n\ndef main():\n \"\"\"\n TODO:\n If s2 is within s1, return it directly.\n If not, use (len(s1) - len(s2) + 1) to obtain how many sets of sequence to compare.\n Then, use if statement of s1[i+j] == s2[j] to check how many match in each set.\n Last, calculate which set has the highest correct ratio and indicate it in the variable match_set.\n \"\"\"\n s1 = input(\"Please give me a DNA sequence to search: \")\n s1 = s1.upper()\n s2 = input(\"What DNA sequence would you like to match? \")\n s2 = s2.upper()\n ans = ''\n if s1.find(s2) != -1:\n ans += s2\n print('The best match is ' + str(ans))\n else:\n ratio = 0\n match_set = 0\n # (len(s1) - len(s2) + 1) sets to compare\n for i in range(len(s1) - len(s2) + 1):\n count = 0\n correct = 0\n for j in range(len(s2)):\n count += 1\n # s1[i + j] would allow us to move to next sets in s1 each round\n if s1[i + j] == s2[j]:\n correct += 1\n # obtain the match set\n if correct / count > ratio:\n ratio = correct / count\n match_set = i\n # if no match at all, use match_set = -1 to separate it.\n else:\n match_set = -1\n if match_set != -1:\n ans += s1[match_set:(match_set + len(s2))]\n print('The best match is ' + str(ans))\n else:\n print('There is no match in the sequence')\n\n\n###### DO NOT EDIT CODE BELOW THIS LINE ######\nif __name__ == '__main__':\n main()\n"} {"doc_id": "19fda3acce9401ed1148aab86579568b", "text": "\"\"\"\r\n Sieve of Eratosthenes\r\n ---------------------\r\n Is a simple, ancient algorithm for finding all prime numbers\r\n up to any given limit. It does so by iteratively marking as composite\r\n (i.e. not prime) the multiples of each prime, starting with the multiples\r\n of 2.\r\n\r\n The sieve of Eratosthenes is one of the most efficient ways\r\n to find all of the smaller primes (below 10 million or so).\r\n\r\n Time Complexity: O(n log log n)\r\n\r\n Pseudocode: https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes\r\n\"\"\"\r\n\r\n\r\ndef eratosthenes(end, start=2, return_boolean=False):\r\n \"\"\"\r\n Finds all primes < `end`.\r\n\r\n :param end: An integer. The upper limit of the range to look for primes.\r\n :param start: An integer. The start of the range to look for primes.\r\n :param return_boolean: A boolean. Represents the type of return type.\r\n :rtype: Depending on `return_boolean` either returns boolean and primes or\r\n just the primes.\r\n \"\"\"\r\n primes = []\r\n if end < start or end < 2:\r\n return []\r\n is_prime = [True for i in range(end + 1)]\r\n is_prime[0] = is_prime[1] = False\r\n for i in range(2, end + 1):\r\n if not is_prime[i]:\r\n continue\r\n if start <= i <= end:\r\n primes.append(i)\r\n j = i * i\r\n while j <= end:\r\n is_prime[j] = False\r\n j += i\r\n if return_boolean:\r\n return primes, is_prime\r\n return primes\r\n"} {"doc_id": "1a15ffab7cbcc9276d762f1cf0a476f9", "text": "#!/usr/bin/env python\n\"\"\"Miscellaneous functions that don't seem to fit elsewhere\n\n:py:func:`guess_formatter`\n Convert string into primitive data type it probably encoded before `str`\n was called on it\n\n:py:func:`number`\n Convert string into numerical data type, trying `bool`, `int`, `float`,\n then `str`\n\"\"\"\nimport numpy\n\n\ndef guess_formatter(inp):\n \"\"\"Guesses the format of input, trying `bool`, `int`, `float`, then `str`.\n Correctly parses `nan`s and `Inf`s. Converts `None` to `nan`\n\n\n Parameters\n ----------\n inp : str\n input\n\n\n Returns\n -------\n boolean, number, or string\n \"\"\"\n if inp.lower() == \"true\":\n return True\n elif inp.lower() == \"false\":\n return False\n else:\n try:\n return number(inp)\n except ValueError:\n return str(inp)\n\n\ndef number(inp):\n \"\"\"Parses numbers from strings, preferring int over float.\n Parses `nan`, `Nan`, `None`, `none`, `inf`, and `-inf`\n\n\n Parameters\n ----------\n inp : str\n string input\n\n\n Returns\n -------\n float, numpy.nan, numpy.inf, or -numpy.inf, or str if no conversion found\n\n\n Raises\n ------\n ValueError\n if `inp` cannot be converted to a number\n \"\"\"\n if inp in (\"nan\", \"NaN\", \"na\", \"None\", \"none\"):\n return numpy.nan\n elif inp in (\"inf\", \"Inf\"):\n return numpy.inf\n elif inp in (\"-inf\", \"-Inf\"):\n return -numpy.inf\n else:\n try:\n # note: in python bools are also ints!\n # isinstance(True,int) == True\n val = int(inp)\n except ValueError:\n val = float(inp)\n return val\n"} {"doc_id": "1a7415c2afd44a8e70e7109ef9b060d9", "text": "# -*- coding:utf-8 -*-\n\"\"\"\n@Author\uff1aCharles Van\n@E-mail: williananjhon@hotmail.com\n@Time\uff1a2019-07-31 15:39\n@Project:InterView_Book\n@Filename:basicDataType1.py\n@description:\n \u57fa\u7840\u6570\u636e\u7c7b\u578b\u4e2d\u4e8c\u8fdb\u5236\u4f4d\u7684\u64cd\u4f5c\u7b97\u6cd5\n\"\"\"\n\n\nif __name__ == \"__main__\":\n\t# \u6574\u578b\u53d8\u91cf\u503c\u4e92\u6362\n\ta = 1234\n\tb = 5678\n\tprint(\"Binary before swap,a:{0},b{1}\".format(bin(a),bin(b)))\n\t# \u8fde\u7eed\u4e09\u6b21\u5f02\u6216\u64cd\u4f5c\u53ef\u4ee5\u4e92\u6362\u4e24\u53d8\u91cf\u503c\n\ta = a ^ b\n\tb = a ^ b\n\ta = a ^ b\n\tprint(\"Binary after swap,a:{0},b{1}\".format(bin(a),bin(b)))\n\tprint(\"====================================================\")\n\n\t'''\n\t\u5e38\u7528\u7684\u4e8c\u8fdb\u5236\u4f4d\u64cd\u4f5c\n\t'''\n\tdef swapBit(x,i,j):\n\t\t# \u5982\u679c\u7b2ci\u4f4d\u4e0e\u7b2cj\u4f4d\u4e0a\u7684\u6570\u7ec4\u76f8\u540c\u90a3\u5c31\u6ca1\u6709\u5fc5\u8981\u8fdb\u884c\u64cd\u4f5c\n\t\tif ((x >> i) & 1) != ((x >> j) & 1):\n\t\t\tx ^= ((1 << i) | (1 << j))\n\t\treturn x\n\tx = 0b100100\n\ti = 2\n\tj = 3\n\tprint(\"binary format of x before swap bit of {0} and {1} is {2}\".format(i,j,bin(x)))\n\tx = swapBit(x,i,j)\n\tprint(\"binary format of x after swap bit of {0} and {1} is {2}\".format(i,j,bin(x)))\n\tprint(\"---------------------------------------------------------\")\n\n\t\"\"\"\n\t\u5bf9\u4e8e64\u4f4d\u621632\u4f4d\u65e0\u7b26\u53f7\u6574\u578b\u6570x\uff0c\u5728\u5b83\u7684\u4e8c\u8fdb\u5236\u8868\u793a\u4e2d\uff0c\u628a1\u7684\u4e2a\u6570\u6210\u4e3ax\u7684\u6743\u91cd\u3002\u7528S(k)\u8868\u793a64\u4f4d\u621632\u4f4d\u65e0\u7b26\u53f7\u6574\u578b\u6570\u4e2d\uff0c\u6743\u91cd\n\t\u662fk\u7684\u6240\u6709\u6574\u6570\u7684\u96c6\u5408\uff0c\u5176\u4e2dk\u4e0d\u7b49\u4e8e0,64,32\u3002\u7ed9\u5b9a\u4e00\u4e2a\u6574\u578b\u6570x,\u5047\u5b9a\u5b83\u5c5e\u4e8e\u96c6\u5408S(k)\uff0c\u8981\u6c42\u627e\u5230\u53e6\u4e00\u4e2a\u5c5e\u4e8eS(k)\u7684\u6574\u6570y\uff0c\u4f7f\u5f97\n\t|x - y|\u7684\u503c\u6700\u5c0f\n\t\"\"\"\n\tdef closestWithTheSameWeight(x):\n\t\t# \u5047\u8bbex\u662f64\u4f4d\u6574\u578b\u6570\n\t\tfor i in range(64):\n\t\t\t# \u4ece\u4f4e\u4f4d\u5411\u9ad8\u4f4d\u626b\u63cf\uff0c\u627e\u5230\u76f8\u90bb\u4f46\u503c\u4e0d\u540c\u7684\u6bd4\u7279\u4f4d\n\t\t\tif ((x >> i) & 1) ^ ((x >> (i+1)) & 1):\n\t\t\t\t# \u4ea4\u6362\u4e24\u4e2a\u76f8\u90bb\u7684\u6bd4\u7279\u4f4d\n\t\t\t\tx ^= (1 << i) | (1 << (i+1))\n\t\t\t\treturn x\n\tx = 0b11011\n\ty = closestWithTheSameWeight(x)\n\tprint(\"integer closest to x with the same weight is {0}\".format(bin(y)))"} {"doc_id": "1a8df618a00c12331e24be3bfb792e9d", "text": "#!/usr/bin/env python\n# coding: utf-8\n\n# In[ ]:\n\n# Python Basic - PyBank\n\n# Create Python script that analyzes the records to calculate each of the following:# The total number of months included in the dataset\n# The net total amount of \"Profit/Losses\" over the entire period\n# The average of the changes in \"Profit/Losses\" over the entire period\n# The greatest increase in profits (date and amount) over the entire period\n# The greatest decrease in losses (date and amount) over the entire period\n\n# Import the data \nimport os\nimport csv\n\nprint(os.path.join(\".\", \"Assignment_3\", \"budget_data.csv\"))\npybank = os.path.join(\".\", \"Assignment_3\", \"budget_data.csv\")\n\nwith open(pybank, newline='') as csvfile:\n csv_reader = csv.reader(csvfile, delimiter=',')\n header = next(csv_reader)\n print(header)\n# print(csvreader)\n# print(\"CSV Data\")\n# for row in csvreader:\n# print(row)\n\n# Find the total number of months in the data\n# Alternate to count number of rows, \"print(sum(1 for line in csvfile))\"\"\n months = 0\n profit = 0\n profit_list = []\n profit_change = [867884]\n sum_change = 0\n avg_profit = 0\n rows = 0\n i = 0\n \n for row in csv_reader:\n months += 1\n# Find the total amount of profit / losses over the entire period\n profit += float(row[1])\n# print(profit)\n# print(month)\n# List all profit / losses in an array called \"profit_list\"\n profit_change.append(row[1])\n change = int(profit_change[rows + 1]) - int(profit_change[rows])\n profit_list.append(change)\n \n#print(profit_list[0])\n#print(profit_list[1])\n# Find the greatest increase in profit with date and amount\n max_profit = max(profit_list)\n if profit_list[rows] == max_profit:\n max_date = row[0]\n \n# Find the greatest decrease in losses with data and amount\n min_profit = min(profit_list)\n if profit_list[rows] == min_profit:\n min_date = row[0]\n# Find sum of changes \n changes = int(profit_list[rows])\n sum_change += changes \n \n# Move to the next row in profit list\n rows += 1\n# print(max_date)\n# print(min_date)\n# print(max_profit)\n# print(min_profit)\n\n# Find the average of the changes in profit / losses \navg_profit = round(sum_change / (months - 1), 2)\nprint(avg_profit)\n\n# Create a financial analysis summary table,\nprint(\"Financial Analysis\")\nprint(\"---------------------------------------\")\nprint(\"Total Months: \" + str(months))\nprint(\"Average Change: \" + \"$\" + str(avg_profit))\nprint(\"Greatest Increase in Profits: \" + max_date + \" (\" + max_profit + \")\")\nprint(\"Greatest Decrease in Profits: \" + min_date + \" (\" + min_profit + \")\")\n\n"} {"doc_id": "1a922e4bd0cadf5e68306b72b0bc84a1", "text": "\"\"\"A small set of utility functions for changing the xterm.\n\nA set of functions to temporarily alter various properties in Linux's\nxterm. This includes changes to the title, text color, background color,\ntext modifiers (bold, italics), etc.\n\nFunctions\n---------\nchange_title(title=\"\")\n Changes the title of the current xterm window.\nchange_text_color(r=-1, g=-1, b=-1, hex=\"\")\n Changes the text color of following print statements.\nchange_text_background_color(r=-1, g=-1, b=-1, hex=\"\")\n Changes the text background of following print statements.\nset_text_modifiers(bold=False, italics=False, underline=False)\n Sets text modifiers for following print statements.\n\"\"\"\n\n\n\ndef change_title(title=\"\"):\n \"\"\"Changes the title of the current xterm window.\n\n This will set the title of the current xterm window to the specified\n title. Leaving the title at a default will restore to the default\n title, which is usually \"Terminal\".\n\n Notes\n -----\n - If the title was never changed from the default, and you\n try to change it back to default, nothing will happen.\n - This function directly changes $PS1 but it only lasts as long as the\n Python script or application does.\n\n Parameters\n ----------\n title : str, optional\n The title you want the current window to be set to (default\n restores the title to the default title).\n\n Usage Examples\n --------------\n change_title(\"Hello, world!\")\n # Insert your code here\n change_title()\n \"\"\"\n\n # Use an escape sequence to change the title\n print(\"\\033]0;{}\\a\".format(title), end=\"\", flush=True)\n\n\n\ndef change_text_color(rgb=(-1, -1, -1), hex=\"\"):\n \"\"\"Changes the text color of following print statements.\n\n Sets the text color for following terminal output. If no parameters\n are specified, the color will return to default.\n\n Notes\n -----\n - If the color was never changed from the default and you try to\n restore to default, nothing will happen.\n - If both the hex and rgb are specified, the code will default to rgb.\n - Any invalid inputs will cause the code to revert to default.\n - If rgb is used and any values are left at -1, they will be treated\n as 0.\n - The default text color is whatever the system deems the default\n text color\n\n Parameters\n ----------\n rgb: (int, int, int), optional\n The RGB touple to set the text color to.\n hex: str, optional\n The hex string to set the text color to.\n\n Usage Examples\n --------------\n change_text_color(rgb=(120, 120, 40))\n # Insert your code here\n change_text_color()\n\n change_text_color(rgb(120, -1, -1))\n # Insert your code here\n change_text_color()\n\n change_text_color(hex=\"#C0FFEE\")\n # Insert your code here\n change_text_color()\n \"\"\"\n\n # First, parse out the arguments to determine which source to use\n rgb_given = (rgb != (-1, -1, -1) and len(rgb) == 3)\n hex_given = (hex != \"\")\n\n # Next, ensure that the values given are valid\n if rgb_given:\n for val in rgb:\n if (val < -1 or val > 255):\n rgb_given = False\n if hex_given:\n if len(hex) != 7 or hex[0] != \"#\":\n hex_given = False\n for i in hex[1:].lower():\n if i not in \"0123456789abcdef\":\n hex_given = False\n\n # The boolean checks are correct at this point\n\n # Complete the operation given which sources are available\n esc = \"\\033[\"\n if rgb_given:\n r, g, b = map(lambda x: x if x != -1 else 0, rgb)\n esc += \"38;2;{};{};{}m\".format(r, g, b)\n elif hex_given:\n r, g, b = map(lambda i: int(hex[i:i+2], 16), (1, 3, 5))\n esc += \"38;2;{};{};{}m\".format(r, g, b)\n else: # Revert to default then\n esc += \"39m\"\n\n # Print out the escape sequence to set the new text color\n print(esc, end=\"\", flush=True)\n\n\n\ndef change_text_background_color(rgb=(-1, -1, -1), hex=\"\"):\n \"\"\"Changes the text background of following print statements.\n\n Sets the text background color for following terminal output. If no\n parameters are specified, the color will return to default.\n\n Notes\n -----\n - If the color was never changed from the default and you try to\n restore to default, nothing will happen.\n - If both the hex and rgb are specified, the code will default to rgb.\n - Any invalid inputs will cause the code to revert to default.\n - If rgb is used and any values are left at -1, they will be treated\n as 0.\n - The default background color is whatever the system deems the default\n background color\n\n Parameters\n ----------\n rgb: (int, int, int), optional\n The RGB touple to set the text background color to.\n hex: str, optional\n The hex string to set the text background color to.\n\n Usage Examples\n --------------\n change_text_background_color(rgb=(120, 120, 40))\n # Insert your code here\n change_text_background_color()\n\n change_text_background_color(rgb(120, -1, -1))\n # Insert your code here\n change_text_background_color()\n\n change_text_background_color(hex=\"#C0FFEE\")\n # Insert your code here\n change_text_background_color()\n \"\"\"\n\n # First, parse out the arguments to determine which source to use\n rgb_given = (rgb != (-1, -1, -1) and len(rgb) == 3)\n hex_given = (hex != \"\")\n\n # Next, ensure that the values given are valid\n if rgb_given:\n for val in rgb:\n if (val < -1 or val > 255):\n rgb_given = False\n if hex_given:\n if len(hex) != 7 or hex[0] != \"#\":\n hex_given = False\n for i in hex[1:].lower():\n if i not in \"0123456789abcdef\":\n hex_given = False\n\n # The boolean checks are correct at this point\n\n # Complete the operation given which sources are available\n esc = \"\\033[\"\n if rgb_given:\n r, g, b = map(lambda x: x if x != -1 else 0, rgb)\n esc += \"48;2;{};{};{}m\".format(r, g, b)\n elif hex_given:\n r, g, b = map(lambda i: int(hex[i:i+2], 16), (1, 3, 5))\n esc += \"48;2;{};{};{}m\".format(r, g, b)\n else: # Revert to default then\n esc += \"49m\"\n\n # Print out the escape sequence to set the new background color\n print(esc, end=\"\", flush=True)\n\n\n\ndef set_text_modifiers(bold=False, italics=False, underline=False):\n \"\"\"Sets text modifiers for following print statements.\n\n Sets the text modifiers for any following print statements. These\n include bold, italics, and underline. Multiple may be specified. If\n none are specified, the text will have no modifiers.\n\n Parameters\n ----------\n bold: bool, optional\n Whether the following text should be bold.\n italics: bool, optional\n Whether the following text should be italicized.\n underline: bool, optional\n Whether the following text should be underlined.\n\n Usage Examples\n --------------\n set_text_modifiers(bold=True, underline=True)\n # Insert your code here\n set_text_modifiers()\n\n set_text_modifiers(italics=True)\n # Insert your code here\n set_text_modifiers()\n \"\"\"\n\n esc = \"\\033[\" # Start of the escape sequence\n args = [] # To keep track of arguments\n\n # Add corresponding escape arguments\n if bold:\n args.append(\"1\")\n else:\n args.append(\"22\")\n\n if italics:\n args.append(\"3\")\n else:\n args.append(\"23\")\n\n if underline:\n args.append(\"4\")\n else:\n args.append(\"24\")\n\n # Construct the final escape sequence. If there are no arguments, all\n # escape arguments will be the reset codes\n esc += \";\".join(args)+\"m\"\n\n # Print the escape sequence to change the modifier settings\n print(esc, end=\"\", flush=True)\n"} {"doc_id": "1b16fd299737a8593d11519921cf2da6", "text": "\"\"\"\r\nFile: Draw line\r\nName: \u6d2a\u798e\u851a\r\n-------------------------\r\nThis program creates lines on an instance of GWindow class.\r\nThere is a circle indicating the user\u2019s first click. A line appears\r\nat the condition where the circle disappears as the user clicks\r\non the canvas for the second time.\r\n\"\"\"\r\n\r\nfrom campy.graphics.gobjects import GOval, GLine\r\nfrom campy.graphics.gwindow import GWindow\r\nfrom campy.gui.events.mouse import onmouseclicked\r\n\r\n# Constants control the diameter of the circle\r\nSIZE = 5\r\n\r\n# Global variables\r\nbg = GWindow()\r\n# the times of mouseclick\r\nn = 0\r\n# the position of the circle's center\r\nclick_x = 0\r\nclick_y = 0\r\n\r\n\r\ndef main():\r\n \"\"\"\r\n TODO: draw a circle for the odd clicks,\r\n then erase the circle as well as\r\n draw a line that starts from last click and ends at this click\r\n for the even clicks\r\n \"\"\"\r\n onmouseclicked(circle_line)\r\n\r\n\r\ndef circle_line(m):\r\n global n, click_x, click_y\r\n # The even click\r\n if n % 2 == 0:\r\n click = GOval(SIZE, SIZE, x=m.x - SIZE/2, y=m.y - SIZE/2)\r\n bg.add(click)\r\n n += 1\r\n click_x = m.x - SIZE/2\r\n click_y = m.y - SIZE/2\r\n # The odd click\r\n else:\r\n line = GLine(click_x + SIZE / 2, click_y + SIZE / 2, m.x, m.y)\r\n click = bg.get_object_at(click_x + SIZE/2, click_y)\r\n bg.remove(click)\r\n bg.add(line)\r\n n += 1\r\n\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n"} {"doc_id": "1b29be15673f92030d29452a637f7217", "text": "\"\"\"\nFile: caesar.py\nName: David\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 program decipher the Caesar Cipher.\n \"\"\"\n while True:\n # Ensure the secret number inputted is an integer.\n secret_number = input(\"Secret number: \")\n if secret_number.isdigit():\n secret_number = int(secret_number)\n break\n print(\"Sorry. The secret number must be an integer!\")\n # If the secret number is not an integer, ask users to enter again.\n new_set = new_alphabet(secret_number)\n # Create the alphabet with the new order decided by the secret number.\n ciphered_string = input(\"What's the ciphered string? \")\n ciphered_string = ciphered_string.upper()\n # Case-insensitive\n print(\"The deciphered string is: \"+str(decipher(ciphered_string, new_set)))\n # Use decipher() function to decipher the string.\n\n\ndef new_alphabet(secret_number):\n \"\"\"\n Create the alphabet with the new order.\n :param secret_number: the number of translation\n :return: the alphabet with the new order\n \"\"\"\n new = \"\"\n for i in range(len(ALPHABET)-secret_number, len(ALPHABET)):\n # Concatenate the alphabets translated to the front of the alphabet string.\n new += ALPHABET[i]\n for j in range(len(ALPHABET)-secret_number):\n # Concatenate the remaining alphabets.\n new += ALPHABET[j]\n return new\n\n\ndef decipher(ciphered_string, new_set):\n \"\"\"\n :param ciphered_string: the string to be deciphered\n :param new_set: the alphabets string with the new order.\n :return: deciphered string\n \"\"\"\n ans = \"\"\n for i in range(len(ciphered_string)):\n if ciphered_string[i].isalpha():\n # Decipher the string only when the element is an alphabet.\n w = new_set.find(ciphered_string[i])\n # Find the new position of the alphabet.\n ans += ALPHABET[w]\n # Concatenate the original alphabet.\n else:\n # The elements that are not alphabets remain the same.\n ans += ciphered_string[i]\n return ans\n\n\n# DO NOT EDIT THE CODE BELOW THIS LINE #####\nif __name__ == '__main__':\n main()\n"} {"doc_id": "1b47541c4dd528a452fb058748674020", "text": "def party_planner(cookies, people):\n leftovers = None\n num_each = None\n try:\n num_each = cookies // people\n leftovers = cookies % people\n except ZeroDivisionError:\n print(\"Oops, you entered 0 people will be attending.\")\n print(\"Please enter a good number of people for a party.\")\n\n return(num_each, leftovers)\n\n# The main code block is below; do not edit this\nlets_party = 'y'\nwhile lets_party == 'y':\n\n cookies = int(input(\"How many cookies are you baking? \"))\n people = int(input(\"How many people are attending? \"))\n\n cookies_each, leftovers = party_planner(cookies, people)\n\n if cookies_each: # if cookies_each is not None\n message = \"\\nLet's party! We'll have {} people attending, they'll each get to eat {} cookies, and we'll have {} left over.\"\n print(message.format(people, cookies_each, leftovers))\n\n lets_party = input(\"\\nWould you like to party more? (y or n) \")\n"} {"doc_id": "1b5917a9b6605a74b236ce911916a450", "text": "# This code contains simple examples about working with files in Python.\n\n# Reading an Entire File\n# Let's do a simple example. In the nest session, we want to open a \n# file named pi_digits.txt. This file contains the numerical value of pi. \n# Let's get read this number in the file and display in the screen. \n# First, we open the file inside a context manager. \n# A context manager is constructed using the word 'with', inside a context\n# manager exists some variables specific for this context \n# (block of code), hence the name 'context manager'.\n# \n# In this example we use the open() function with the file name as \n# parameter. We put the return from the open() function into the file_object\n# variable and use into the idented space. \n# Into the idented space (block of code/context manager) we can read the \n# content from the file using the function read(). The return value from\n# this function is the content from the file 'pi_digits.txt', stored into\n# the 'contents' variable. \nwith open('pi_digits.txt') as file_object:\n contents = file_object.read()\n print(contents)\n\n# File Path\n# To open a file we need to give a the file location inside your \n# operational system(OS). To access some file in your OS, you can pass\n# into the open() function the absolute file location or the \n# relative file location. In a Linux system you can discover the actual \n# folder path using 'pwd'. The relative location from the\n# folder that your python script is stored. \n\nwith open('./pi_digits.txt') as file_object:\n contents = file_object.read()\n print(contents)\n\n# Reading Line by Line\nwith open('pi_digits.txt') as file_object:\n for line in file_object:\n print('-------------------')\n print(line.rstrip())\n \n print('-------------------')\n\n# Making a List of Lines from File \nfilename = 'pi_digits.txt'\n\nwith open(filename) as file_object:\n lines = file_object.readlines()\n\nfor line in lines:\n print(line.rstrip())\n\n# Working with a File's Contents\npi_string = ''\nfor line in lines:\n pi_string += line.rstrip()\n\nprint(pi_string)\n\n# Large Files: One Million Digits\nfilename = 'pi_million_digits.txt'\n\nwith open(filename) as file_object:\n lines = file_object.readlines()\n\npi_string = ''\n\nfor line in lines:\n pi_string += line.strip()\n\nprint(pi_string[:52]+ '...')\nprint(len(pi_string))\n\n# Is Your Birthday Contained in Pi?\nbirthday = input('Enter your birthday, in the form mmddyy: ')\nif birthday in pi_string:\n print('Your birthday appears in the first million digits of pi!')\nelse: \n print('Your birthday does not appear in the first million digits of pi.')\n\n"} {"doc_id": "1b7cd1cd5f8dd20f40053b00d533d63c", "text": "\"\"\"\nQueue - FIFO data structure\n----------------------------\n- Another special type of list; e.g. stay in line at an airport/ to be served your favorite burger at the shop\n\n- a very fundamental and important concept to grasp since many other data structures are built on them.\n- The way a queue works: the first person to join the queue usually gets served first, all things being equal.\n\n- FIFO: first in, first out - E.g. people standing in a queue waiting for their turn to be served; service is only\nrendered at the front of the queue; The only time people exit the queue - when they have been served (which occurs only\nat the very front of the queue); it is illegal for people to join the queue at the front where people are being served.\n\nTo join the queue, participants must first move behind the last person in the queue - length of the queue doesn't matter\n\n2 operations:\n- enqueue: to add an element to the queue enqueue; anytime an element is enqueued, the length or size of the queue += 1\n- dequeue: to remove an element from the queue; dequeuing items reduce the number of elements in the queue -= 1\n\n\"\"\"\n\n# I. List based queue\n\n\nclass ListBasedQueue:\n def __init__(self):\n # queue is empty when created\n self.items = []\n self.size = 0\n\n # Enqueue: inserts items/data at index 0 - 1st position\n # (could have used Python's shift method on the list as another way of implementing the \"insert at 0\")\n def enqueue(self, data):\n self.items.insert(0, data)\n self.size += 1\n\n # Dequeue: removes items from the queue\n # capture the point where we serve the customer who joined the queue first and also waited the longest\n # pop - Removes the last item from the list & Returns the removed item from the list back to the user\n def dequeue(self):\n # The last item in the list is popped & saved in the data variable\n data = self.items.pop()\n self.size -= 1\n return data\n\n\n# II. Stack-based queue - implementation of a queue using two stacks - interview question !!!!\nclass StackBasedQueue:\n def __init__(self):\n # 2 stacks = empty lists that allow us to call push and pop methods on them\n self.inbound_stack = [] # store elements that are added to the queue\n self.outbound_stack = []\n\n # enqueue: adds elements to the queue\n # append method used to mimic the push operation, which pushes elements to the top of the stack.\n def enqueue(self, data):\n self.inbound_stack.append(data)\n\n # dequeue\n def dequeue(self):\n # if the outbound_stack is empty, all the elements in the inbound_stack are moved to the outbound_stack\n if not self.outbound_stack:\n # as long as there are elements in the inbound_stack\n while self.inbound_stack:\n # self.inbound_stack.pop() will remove the latest element that was added to the inbound_stack\n # & immediately pass the popped data to the self.outbound_stack.append() method call.\n self.outbound_stack.append(self.inbound_stack.pop())\n # If not empty, remove the element at the front of the queue\n return self.outbound_stack.pop()\n\n\n# III. Node-based queue - implementation by utilizing our knowledge of pointer structures, using a doubly linked list\n# insertion and deletion operations on this data structure have a time complexity of O(1).\n# The doubly linked list can be treated as a queue if it enables a FIFO data access: 1st element added, 1st to remove.\n\n# uses the double-linked-list node\nclass Node:\n # The prev variable holds a reference to the previous node, the next variable holds a reference to the next node\n def __init__(self, data=None, next=None, prev=None):\n self.data = data\n self.next = next\n self.prev = prev\n\n\nclass NodeBasedQueue:\n def __init__(self):\n self.head = None\n self.tail = None\n self.count = 0 # To count the number of nodes in Queue\n\n # enqueue: nodes are added to the queue - same append operation from doubly linked list\n def enqueue(self, data):\n new_node = Node(data, None, None)\n if self.head is None:\n self.head = new_node\n self.tail = self.head\n else:\n new_node.prev = self.tail\n self.tail.next = new_node\n self.tail = new_node\n\n self.count += 1\n\n # def dequeue: removes the node at the front of the queue\n def dequeue(self):\n current = self.head\n if self.count == 1:\n self.count -= 1\n self.head = None\n self.tail = None\n elif self.count > 1:\n self.head = self.head.next\n self.head.prev = None\n self.count -= 1\n\n\nlqueue = ListBasedQueue()\nlqueue.enqueue(1)\nlqueue.enqueue(2)\nlqueue.enqueue(3)\nlqueue.enqueue(4)\nfor item in lqueue.items:\n print(item)\nprint('size of the queue is: {}'.format(lqueue.size),'\\n')\nlqueue.dequeue()\nfor item in lqueue.items:\n print(item)\nprint('size of the queue is: {}'.format(lqueue.size), '\\n')\n\nsqueue = StackBasedQueue()\nsqueue.enqueue(5)\nsqueue.enqueue(6)\nsqueue.enqueue(7)\nprint(squeue.inbound_stack)\nsqueue.dequeue()\nprint(squeue.inbound_stack)\nprint(squeue.outbound_stack)\nsqueue.dequeue()\nprint(squeue.outbound_stack)"} {"doc_id": "1b8c0f9dc96e9c7b36b18f1d099e4636", "text": "# \u30ad\u30fc\u30ef\u30fc\u30c9\u5f15\u6570\n# \u95a2\u6570\u547c\u3073\u51fa\u3057\u306e\u969b\u3001\u5f15\u6570\u540d\u3092\u6307\u5b9a\u3067\u304d\u308b\uff01\ndef func_calc(num1 = 1, oparator = \"+\", num2 = 1):\n\tif oparator == \"-\":\n\t\treturn num1 - num2\n\telif oparator == \"/\":\n\t\treturn num1 / num2\n\telif oparator == \"%\":\n\t\treturn num1 % num2\n\telif oparator == \"*\":\n\t\treturn num1 * num2\n\telif oparator == \"**\":\n\t\treturn num1 ** num2\n\telse:\n\t\treturn num1 + num2\n\n# \u5f15\u6570\u540d\u3092\u6307\u5b9a\u3057\u306a\u3044\u3068\u3001\u9806\u756a\u306b\u8a2d\u5b9a\u3055\u308c\u308b\nprint(func_calc(1, \"*\", 10)) # -> 1 * 10\n\n# \u5f15\u6570\u540d\u3092\u6307\u5b9a\u3059\u308c\u3070\u3001\u305d\u306e\u5f15\u6570\u306b\u5024\u304c\u4ee3\u5165\u3055\u308c\u308b\uff01\nprint(func_calc(num2 = 10, oparator = \"/\")) # -> 1 / 10\n\n# \u53ef\u5909\u9577\u5f15\u6570\u3068\u7d44\u307f\u5408\u308f\u305b\u3089\u308c\u308b\u304b\u306a\u2026\ndef func_set_va(*v_arg, arg = 0):\n\tprint(\"arg: {}\".format(arg))\n\tprint(\"v_arg: {}\".format(v_arg))\n\n# \u3075\u3064\u3046\u306e\u5f15\u6570\u3092\u5f8c\u306b\u6307\u5b9a\u3057\u3066\u304a\u304f\u3068\u3001\u5148\u306b\u53ef\u5909\u9577\u5f15\u6570\u306e\u5024\u3092\u53d6\u3063\u3066\u304f\u308c\u308b\u3088\u3046\u306b\u306a\u308b\nprint(\"-------- func_set_va() --------\")\nfunc_set_va()\nprint(\"-------- func_set_va(1, 2, 3) --------\")\nfunc_set_va(1, 2, 3)\nprint(\"-------- func_set_va(1, 2, 3, arg = 100) --------\")\nfunc_set_va(1, 2, 3, arg = 100)\n\n# \u53ef\u5909\u9577\u5f15\u6570\u3088\u308a\u3082\u5f8c\u308d\u306b\u6307\u5b9a\u3055\u308c\u305f\u5f15\u6570\u306f\u3001\u5f15\u6570\u540d\u3092\u6307\u5b9a\u3057\u3066\uff08\u30ad\u30fc\u30ef\u30fc\u30c9\u5f15\u6570\u3068\u3057\u3066\uff09\n# \u5024\u3092\u6e21\u3055\u306a\u3044\u3068\u3044\u3051\u306a\u304f\u306a\u308b\u304c\u2026\n# \u3061\u306a\u307f\u306b\u3001\u3053\u3046\u3044\u3046\u30c6\u30af\u30cb\u30c3\u30af\u3092\u30ad\u30fc\u30ef\u30fc\u30c9\u9650\u5b9a\u5f15\u6570\u3068\u304b\u8a00\u3046\u3089\u3057\u3044\n# \u3042\u3068\u3001\u3055\u3063\u304d\u304b\u3089\u300c\u3075\u3064\u3046\u306e\u5f15\u6570\u300d\u3068\u547c\u3093\u3067\u3044\u305f\u3082\u306e\u306f\u3001\u300c\u4f4d\u7f6e\u5f15\u6570\u300d\u3068\u540d\u524d\u304c\u3064\u3051\u3089\u308c\u3066\u3044\u308b\n# \u5f15\u6570\u3092\u6307\u5b9a\u3057\u305f\u9806\u756a\uff08\u4f4d\u7f6e\uff09\u304c\u3001\u95a2\u6570\u306e\u4e2d\u3067\u306e\u51e6\u7406\u306e\u3055\u308c\u65b9\u3068\u7d50\u3073\u3064\u3044\u3066\u3044\u308b\u304b\u3089\u3001\u3068\u3044\u3046\u3053\u3068\u3060\u308d\u3046\u304b\u2026"} {"doc_id": "1b90c8719afebd22e7f03afac1295434", "text": "# Coding Challenge 4\r\n\r\n#The cipher using a 2d array\r\ncipherUpper = [['A', 'M'], ['B', 'H'], ['C', 'T'], ['D','F'], ['E', 'G'], ['F', 'K'], ['G', 'B'], ['H', 'P'], ['I', 'J'], ['J', 'W'], ['K', 'E'], ['L', 'R'], ['M', 'Q'], ['N', 'S'], ['O', 'L'], ['P', 'N'], ['Q', 'I'], ['R', 'U'], ['S', 'O'], ['T', 'X'], ['U', 'Z'], ['V', 'Y'], ['W', 'V'], ['X', 'D'], ['Y', 'C'], ['Z', 'A']]\r\ncipherLower = [['a', 'm'], ['b', 'h'], ['c', 't'], ['d', 'f'], ['e', 'g'], ['f', 'k'], ['g', 'b'], ['h', 'p'], ['i', 'j'], ['j', 'e'], ['k', 'e'], ['l', 'r'], ['m', 'q'], ['n', 's'], ['o', 'l'], ['p', 'n'], ['q', 'i'], ['r', 'u'], ['s', 'o'], ['t', 'x'], ['u', 'z'], ['v', 'y'], ['w', 'v'], ['x', 'd'], ['y', 'c'], ['z', 'a']]\r\n\r\n\r\n#Encryption function\r\ndef encryptString(string):\r\n encryptionList = []\r\n for x in string:\r\n #print(\"x is\",x)\r\n for y in range (0, 26):\r\n if x == cipherUpper[y][0]:\r\n #print(cipherUpper[y][1])\r\n encryptionList.append(cipherUpper[y][1])\r\n elif x == cipherLower[y][0]:\r\n #print(cipherLower[y][1])\r\n encryptionList.append(cipherLower[y][1])\r\n answer = ''.join(encryptionList)\r\n print(answer, encryptionList)\r\n return answer\r\n \r\n#Decryption function\r\ndef decryptString(string):\r\n encryptionList = []\r\n for x in string:\r\n #print(\"x is\",x)\r\n for y in range (0, 26):\r\n if x == cipherUpper[y][1]:\r\n #print(cipherUpper[y][1])\r\n encryptionList.append(cipherUpper[y][0])\r\n elif x == cipherLower[y][1]:\r\n #print(cipherLower[y][1])\r\n encryptionList.append(cipherLower[y][0])\r\n answer = ''.join(encryptionList)\r\n print(answer, encryptionList)\r\n return answer\r\n\t\r\n#defining the main function\r\ndef myMain():\r\n\r\n #asking the user wehter they want to decrypt or encrypt\r\n while True:\r\n try:\r\n choice = str(input(\"Enter 'e' to encrypt or 'd' to decrypt.\\n\"))\r\n except ValueError:\r\n print(\"Please enter the letters 'e' or 'd'.\\n\")\r\n if choice != 'e' and choice != 'd':\r\n print(\"Please enter the letters 'e' or 'd'.\\n\")\r\n elif choice == 'e': #asking for the string they want to encrypt\r\n encrypt = str(input(\"Enter password: \"))\r\n break\r\n elif choice == 'd': #asking for the string they want to decrypt\r\n decrypt = str(input(\"Enter password: \"))\r\n break\r\n \r\n if choice == 'e':\r\n output = encryptString(encrypt)\r\n\r\n elif choice == 'd':\r\n output = decryptString(decrypt)\r\n\r\n print(\"Your password is now\", output) \r\n\r\n\r\nmyMain()\r\n"} {"doc_id": "1bf0fd323eaa767b0369bc1fd74767d4", "text": "## Queue Implementation\nimport numpy as np\n# FIFO Structure -> First in First Out\nclass Queue:\n\tdef __init__(self,maxlen=1e9):\n\t\tself.queue = []\n\t\tself.maxlen = maxlen\n\n\tdef isEmpty(self):\n\t\treturn self.queue == []\n\n\tdef sizeQueue(self):\n\t\treturn len(self.queue)\n\n\t# # Main Methods: Enqueue Dequeue Peel\n\tdef enqueue(self,data):\n\t\tif self.sizeQueue() < self.maxlen: \n\t\t\tself.queue.append(data)\n\t\telse:\n\t\t\tself.dequeue()\n\t\t\tself.queue.append(data)\n\n\tdef dequeue(self):\n\t\tdata = self.queue[0]\n\t\tdel self.queue[0]\n\t\treturn data\n\n\tdef peek(self):\n\t\treturn self.queue[0]\n\n\tdef to_array(self):\n\t\treturn np.array(self.queue)\n\nif __name__ == \"__main__\":\n\tqueue = Queue()\n\tqueue.enqueue(10)\n\tqueue.enqueue(330)\n\tqueue.enqueue(20)\n\tqueue.enqueue(40)\n\tprint(\"Size of the Queue is %d.\" % queue.sizeQueue())\n\tprint(\"Dequeue: %d\" % queue.dequeue())\n\tprint(\"Dequeue: %d\" % queue.dequeue())\n\tprint(\"Size of the Queue is %d.\" % queue.sizeQueue())\n"} {"doc_id": "1c04efad721c390f78e2660d6f39a10c", "text": "\"\"\"\nFile: similarity.py\nName: Po Kai Feng\n----------------------------\nThis program compares short dna sequence, s2,\nwith sub sequences of a long dna sequence, s1\nThe way of approaching this task is the same as\nwhat people are doing in the bio industry.\n\"\"\"\n\n\ndef main():\n \"\"\"\n User will types a long DNA sequence. Then user will type a short DNA\n sequence to match the long DNA sequence. Finally the code will calculate\n and return the homology of two DNA sequences.\n \"\"\"\n long_seq = input('Please give me a DNA sequence to search: ')\n short_seq = input('What DNA sequence would you like to match? ')\n print('The best match is '+find_homology(long_seq.upper(), short_seq.upper()))\n\n\ndef find_homology(long_seq, short_seq):\n \"\"\"\n :param long_seq: str, the base DNA sequence user wants to search in with all upper case characters\n :param short_seq: str, the DNA sequence user wants to match with all upper case characters\n :return: the homology in long_seq\n \"\"\"\n homology = ''\n similarity = 0\n for i in range(len(long_seq) - len(short_seq) + 1):\n # Search from [0] to [long_seq - short_seq] in long_seq\n new_homology = ''\n new_similarity = 0\n for j in range(i, i + len(short_seq)):\n # Get the similarity of short_seq and the string from long_seq[i] to long_seq[i+len(short_seq)-1]\n if long_seq[j] == short_seq[j - i]:\n # The two DNA match and should add up similarity\n new_similarity += 1\n else:\n pass\n if new_similarity > similarity:\n # The new DNA section in long_seq has more similarity and should replace the homology\n similarity = new_similarity\n for k in range(i, i + len(short_seq)):\n # Assign new homology\n new_homology += long_seq[k]\n homology = new_homology\n return homology\n\n\n###### DO NOT EDIT CODE BELOW THIS LINE ######\nif __name__ == '__main__':\n main()\n"} {"doc_id": "1c396b1d4c75386cb238d892ca120283", "text": "\"\"\"\nFile: quadratic_solver.py\nName: Jade Yeh\n-----------------------\nThis program should implement a console program\nthat asks 3 inputs (a, b, and c)\nfrom users to compute the roots of equation\nax^2 + bx + c = 0\nOutput format should match what is shown in the sample\nrun in the Assignment 2 Handout.\n\n\"\"\"\n\nimport math\n\n\ndef main():\n\t\"\"\"\n\tUser give 3 inputs (a, b, and c) for a quadratic equation: ax^2 + bx + c = 0.\n\tCoder will find the solutions of x for that quadratic equation.\n\t\"\"\"\n\tprint('stanCode Quadratic Solver!')\n\t# ax^2 + bx + c = 0\n\ta = float(input('Enter a: '))\n\tb = float(input('Enter b: '))\n\tc = float(input('Enter c: '))\n\t# this value determine the number of root\n\tdiscriminant = b * b - 4 * a * c\n\tif discriminant >= 0:\n\t\t# >= 0 -> roots: x1 and x2\n\t\tx1 = (-b + math.sqrt(discriminant)) / 2 / a\n\t\tx2 = (-b - math.sqrt(discriminant)) / 2 / a\n\t\tif x1 != x2:\n\t\t\t# > 0 -> two roots: x1 and x2\n\t\t\tprint('Two roots: ' + str(x1) + ' , ' + str(x2))\n\t\telse:\n\t\t\t# = 0 -> one root: x1 = x2\n\t\t\tprint('One root: ' + str(x1))\n\telse:\n\t\t# < 0 -> no real root\n\t\tprint('No real roots')\n\n\n###### DO NOT EDIT CODE BELOW THIS LINE ######\n\nif __name__ == \"__main__\":\n\tmain()\n"} {"doc_id": "1c504691a39fb89bb1cb8de3b29d95dd", "text": "\"\"\"\n

In 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\n

The 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\n

Example 1:
\n

\nInput: \nnums = \n[[1,2],\n [3,4]]\nr = 1, c = 4\nOutput: \n[[1,2,3,4]]\nExplanation:
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
\n

\n\n

Example 2:
\n

\nInput: \nnums = \n[[1,2],\n [3,4]]\nr = 2, c = 4\nOutput: \n[[1,2],\n [3,4]]\nExplanation:
There is no way to reshape a 2 * 2 matrix to a 2 * 4 matrix. So output the original matrix.\n
\n

\n\n

Note:
\n

    \n
  1. The height and width of the given matrix is in range [1, 100].
  2. \n
  3. The given r and c are all positive.
  4. \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

\n\n

\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

\n\n

\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

\n\n

\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
    \n\t
  1. \u7ed9\u5b9a\u77e9\u9635\u7684\u5bbd\u548c\u9ad8\u8303\u56f4\u5728 [1, 100]\u3002
  2. \n\t
  3. \u7ed9\u5b9a\u7684 r \u548c c \u90fd\u662f\u6b63\u6570\u3002
  4. \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

\n\n

\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

\n\n

\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

\n\n

\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
    \n\t
  1. \u7ed9\u5b9a\u77e9\u9635\u7684\u5bbd\u548c\u9ad8\u8303\u56f4\u5728 [1, 100]\u3002
  2. \n\t
  3. \u7ed9\u5b9a\u7684 r \u548c c \u90fd\u662f\u6b63\u6570\u3002
  4. \n
\n\"\"\"\n\n\nclass Solution(object):\n def matrixReshape(self, nums, r, c):\n \"\"\"\n :type nums: List[List[int]]\n :type r: int\n :type c: int\n :rtype: List[List[int]]\n \"\"\"\n "} {"doc_id": "1c50bb00cd5b6fb79a330a47ae99bf67", "text": "# This file contains the function definition for timerator()\n\ndef timerator(time):\n \"\"\"\n This function converts a timestamp from one format to another.\n\n Parameters:\n time (str) : a timestamp, formatted thusly: MM/DD/YYYY HH:MM AM\n or thusly: MM/DD/YYYY H:MM AM\n\n Returns:\n time (str) : a timestamp, formatted thusly: YYYY-MM-DD_HH:MM\n \"\"\"\n\n # Ensure the hour is being represented with two characters\n if (time[12] == ':'):\n # prepend the single hour character with a \"0\"\n time = time[slice(0, 11)] + \"0\" + time[slice(11, 18)]\n\n ############# Begin handling of AM/PM confusion #############\n meridian = slice(-2, 20)\n hour_str = slice(11, 13)\n\n # midnight\n if (time[meridian] == 'AM') and (time[hour_str] == '12'):\n # Make the hours 00 and toss the AM\n time = time[slice(0, 11)] + '00' + time[slice(13, -3)]\n # all non-noon pm\n elif (time[meridian] == 'PM') and (time[hour_str] != '12'):\n hours = time[hour_str]\n hours = int(hours) + 12\n # Add 12 to the hours and toss the PM\n time = time[slice(0, 11)] + str(hours) + time[slice(13, -3)]\n else:\n # Just toss the AM/PM\n time = time[slice(0, -3)]\n ############# End handling of AM/PM confusion #############\n\n # Move numbers around. Add underscore. Add hyphens.\n time = time[slice(6, 10)] + '-' + time[slice(0, 2)] + '-' +\\\n time[slice(3, 5)] + '_' + time[slice(11, 13)] + ':' +\\\n time[slice(14, 16)]\n\n return time\n"} {"doc_id": "1cb87e3ae3e235b1c717158ff9d6a022", "text": "\"\"\"This module prints lists that may or may not contain nested lists\"\"\"\r\n\r\n\r\ndef print_lol(the_list):\r\n \"\"\"This function takes a positional argument: called \"the_list\", which is any\r\nPython list which may include nested lists. Each data item in the provided lists\r\nrecursively printed to the screen on its own line.\"\"\"\r\n for each_item in the_list:\r\n if isinstance(each_item,list):\r\n print_lol(each_item)\r\n else:\r\n print(each_item)\r\n \r\n"} {"doc_id": "1cf213943f52fd71a4fed7eea4b0b895", "text": "class CaesarCipher:\n \"\"\"Class for encryption & decryption using Caesar cipher\"\"\"\n\n def __init__(self, shift):\n \"\"\"Construct Caeser cipher using integer shift for rotation\"\"\"\n encoder = [None] * 26\n decoder = [None] * 26\n for k in range(26):\n encoder[k] = chr((k+shift) % 26 + ord('A')) \n decoder[k] = chr((k -shift) % 26 + ord('A'))\n self._forward = ''.join(encoder) # will store as string\n self._backward = ''.join(decoder) # use it for decoding\n \n def encrypt(self, message):\n \"\"\"Return encryted message string\"\"\"\n return self._transform(message, self._forward)\n \n def decrypt(self, secret_message):\n \"\"\"Return decryted message string\"\"\"\n return self._transform(secret_message, self._backward) \n \n def _transform(self, original, code):\n msg_char_list = list(original)\n for k in range(len(msg_char_list)):\n if msg_char_list[k].isupper():\n # find index of that char of msg in the enoded/decoded char list\n j = ord(msg_char_list[k]) - ord('A')\n msg_char_list[k] = code[j]\n return ''.join(msg_char_list)\n \nif __name__ == \"__main__\":\n caesar_cipher = CaesarCipher(shift=3)\n message = \"THE EAGLE IS IN PLAY; MEET AT JOE S.\"\n encrypted_message = caesar_cipher.encrypt(message)\n print(\"Secret:\", encrypted_message)\n decrypted_message = caesar_cipher.decrypt(encrypted_message)\n print(\"Message:\", decrypted_message)\n\n"} {"doc_id": "1d461ee170254cc3ab876d90db292064", "text": "import random\n\n\nprint(\"\\U0001f608\\U0001f608\")\nprint(\"\\U0001f607\\U0001f607\\U0001f607\")\ndef hangman_game():\n # Initialize \n words = [\"UBUNTU\", \"PYTHON\", \"VISHAL\", \"LOVE\", \"NODE\"]\n word = random.choice(words)\n print(word)\n guess = \"-\" * len(word)\n wrong_letters = \"\"\n\n # Print header\n print(\"HANGMAN\\n\")\n print(\"\"\"\n +-------\n | \n | \n | \n | \n |\n +---------\"\"\")\n\n # Main game loop\n while True:\n print(f\"\\U0001f608\\U0001f608 Current Guess: {guess} \\U0001f608\\U0001f608\")\n print(f\"\\U0001f608\\U0001f608 Wrong Guesses: {wrong_letters} \\U0001f608\\U0001f608\")\n letter = input(\"\\n \\U0001f608\\U0001f608 Please enter a letter. => \").upper()\n\n # Check if the letter is in the word\n if letter in word:\n temp = \"\"\n for index in range(len(word)):\n if letter == word[index]:\n temp += letter\n elif guess[index] != \"-\":\n temp += guess[index]\n else:\n temp += \"-\"\n guess = temp \n else:\n wrong_letters += letter\n\n # Check for a winner\n if word == guess:\n print(\"You win! And you live to play another day!\")\n print(\"\"\"\n O\n \\|/\n |\n / \\\\\n ----------\n \"\"\")\n break\n\n # Print the hangman\n if len(wrong_letters) == 0:\n print(\"\"\"\n +------\n | \n | \n | \n | \n |\n +---------\"\"\")\n\n if len(wrong_letters) == 1:\n print(\"\"\"\n +------+\n | |\n | O\n | \n | \n |\n +---------\"\"\")\n\n if len(wrong_letters) == 2:\n print(\"\"\"\n +------+\n | |\n | O\n | |\n | | \n | \n +---------\"\"\")\n\n if len(wrong_letters) == 3:\n print(\"\"\"\n +------+\n | |\n | O\n | \\|/\n | |\n | \n +---------\"\"\")\n\n if len(wrong_letters) == 4:\n print(\"\"\"\n +------+\n | |\n | O\n | \\|/\n | |\n | / \\\\\n +---------\"\"\")\n\n if len(wrong_letters) == 5:\n print(\"\"\"\n +------\n | |\n | O\n | /|\\\\\n | |\n | | |\n +---------\"\"\")\n\n # Check for a loser\n if len(wrong_letters) == 5:\n print(\"You lose! Sorry sucker!\")\n print(f\"The word was {word}\")\n break\nwhile True:\n hangman_game()\n user=input(\"Do you want play again this game: press (Y/N) : \").lower()\n if user==\"y\":\n continue\n else:\n break\n\n\n"} {"doc_id": "1dc6d058d944fc98522c82451093582b", "text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nModule devoted to ships positioning.\n\"\"\"\nimport random\n\n\ndef placeShipH(row: int, col: int, lg: int, grid: list, symbol: str) -> bool:\n \"\"\"\n Place the ship horizontally if possible.\n\n Parameters\n ----------\n row : int\n Row number.\n col : int\n Column number.\n lg : int\n Number of cells occupied by the ship that is tried to be placed.\n grid : list\n Battleship grid.\n symbol : str\n Character that represents the ship.\n\n Returns\n -------\n bool\n True if the ship is placed, False otherwise.\n\n \"\"\"\n shipInPlace = True\n if col+lg>10:\n shipInPlace = False\n else:\n for count in range(lg):\n if grid[row][col+count]!=\"E\":\n shipInPlace = False\n if shipInPlace:\n for count in range(lg):\n grid[row][col+count] = symbol\n return shipInPlace\n\n\ndef placeShipV(row: int, col: int, lg: int , grid: list, symbol: str) -> bool:\n \"\"\"\n Place the ship vertically if possible.\n\n Parameters\n ----------\n row : int\n Row number.\n col : int\n Column number.\n lg : int\n Number of cells occupied by the ship that is tried to be placed.\n grid : list\n Battleship grid.\n symbol : str\n Character that represents the ship.\n\n Returns\n -------\n bool\n True if the ship is placed, False otherwise.\n\n \"\"\"\n shipInPlace = True\n if row+lg>10:\n shipInPlace = False\n else:\n for count in range(lg):\n if grid[row+count][col]!=\"E\":\n shipInPlace = False\n if shipInPlace:\n for count in range(lg):\n grid[row+count][col] = symbol\n return shipInPlace\n\n\ndef randomShipLocation(lg: int, grid: list, symbol: str) -> bool:\n \"\"\"\n Try to place randomly a ship.\n \n Choose randomly a cell.\n Choose randomly to place the ship horizontally or vertically.\n Try to place the ship using placeShipH (horizontally) or placeShipV (vertically).\n\n Parameters\n ----------\n lg : int\n Number of cells occupied by the ship that must be placed.\n grid : list\n Battleship grid.\n symbol : str\n Character that represents the ship.\n\n Returns\n -------\n bool\n True if the ship is placed, False otherwise.\n\n \"\"\"\n indiceL = random.randint(0,9)\n indiceC = random.randint(0,9)\n shipInPlace = True\n # Choose randomly to place the ship horizontally or vertically.\n posHorV = random.randint(0,1)\n if posHorV==0:\n shipInPlace = placeShipH(indiceL,indiceC,lg,grid,symbol)\n else:\n shipInPlace = placeShipV(indiceL,indiceC,lg,grid,symbol)\n return shipInPlace"} {"doc_id": "1dc838edf412172e3a8a9f525e739429", "text": "\"\"\"\nFile: quadratic_solver.py\nName: Po Kai Feng\n-----------------------\nThis program should implement a console program\nthat asks 3 inputs (a, b, and c)\nfrom users to compute the roots of equation:\nax^2 + bx + c = 0\nOutput format should match what is shown in the sample\nrun in the Assignment 2 Handout.\n\"\"\"\n\nimport math\n\n\ndef main():\n\t\"\"\"\n\tUser will input three int: a, b, and c. Then he will get the root(s)\n\tof equation: ax^2+bx+c=0.\n\t\"\"\"\n\tprint('stanCode Quadratic Solver!')\n\ta = int(input('Enter a: '))\n\t# a!=0\n\tb = int(input('Enter b: '))\n\tc = int(input('Enter c: '))\n\tdiscriminant = b*b - 4*a*c\n\tif discriminant < 0:\n\t\t# The square root of discriminant is not real number.\n\t\tprint('No real roots')\n\telif discriminant == 0:\n\t\t# The square root of discriminant is zero and there is only one root.\n\t\tprint('One root: '+str((0-b)/2/a))\n\telse:\n\t\t# There are two roots.\n\t\tprint('Two roots: '+str((0-b+math.sqrt(discriminant))/2/a)+' , '+str((0-b-math.sqrt(discriminant))/2/a))\n\n\n###### DO NOT EDIT CODE BELOW THIS LINE ######\n\nif __name__ == \"__main__\":\n\tmain()\n"} {"doc_id": "1ddfb9f5b1385cd64a1ecfad98f3978a", "text": "# Design patterns zijn vernoemd naar de principes waarop ze gebaseerd zijn.\n# Als je deze patterns bij naam kent, kun je gebruik maken van dat gedeelde\n# vocabulaire waar andere programmeurs ook mee communiceren.\n\n# Creational design patterns\n\t# Dit soort design patterns beschrijven systematische creatie van objecten\n\n\t## 1. Factory pattern\n\t\t# met een factory kun je objecten aanmaken d.m.v. een functie\n\t\t# Ik begrijp niet waarom je dit zou gebruiken maar ik heb geleerd hoe je een klasse\n\t\t# schrijft in python.\nclass Dog:\n\tdef __init__(self, name):\n\t\tself._name = name\n\tdef speak(self):\n\t\treturn \"Woef!\"\n\nclass Cat:\n\tdef __init__(self, name):\n\t\tself._name = name\n\tdef speak(self):\n\t\treturn \"Miauw!\"\n\ndef getPet(pet):\n\t\"\"\"Haal dynamisch een dier op\"\"\"\n\tpets = dict(dog=Dog(\"Bertus\"), cat=Cat(\"Otje\"))\n\treturn pets[pet]\n\notje = getPet(\"cat\")\nbertus = getPet(\"dog\")\n\nprint(otje.speak()) # Miauw!\nprint(bertus.speak()) # Woef!\n\t\n\t## 2. Singleton pattern\n\t\t# Een singleton is een enkele instantie van een klasse,\n\t\t# waardoor er global state gedeeld kan worden als object i.p.v. gewone variables.\n\t\t# Ook hier ontgaat mij het nut. Er mist uitleg waarom dit nuttig is, en ik ben\n\t\t# van mening dat een global dict precies hetzelfde werkt zonder onnodige poespas\nclass Secrets:\n\t_sharedState = {}\n\tdef __init__(self):\n\t\tself.__dict__ = self._sharedState\n\nclass Singleton(Secrets):\n\t\"\"\"Deze klasse omvat alle variables uit Secrets\"\"\"\n\tdef __init__(self, **kwargs):\n\t\tself._sharedState.update(kwargs)\n\tdef __str__(self):\n\t\treturn str(self._sharedState)\n\nx = Singleton(secret=\"Mijn sokken zijn blauw.\")\n\nprint(x) # {'secret': 'Mijn sokken zijn blauw.'}\n\n\t## 3. Builder pattern\n\t\t# Een builder hakt het cre\u00ebren van een object in kleinere stukjes via methods op een klasse.\n\t\t# Interessante manier van objects aanmaken. Mijn voorkeur gaat naar object literals met\n\t\t# nauwe verwerking in een type system, maar ik snap dat je dat in python niet zal krijgen.\nclass Car:\n\tdef __init__(self):\n\t\tself.brand = None\n\t\tself.model = None\n\t\tself.russian = None\n\tdef __str__(self):\n\t\treturn \"Car brand: {}, model: {}, Russian?: {}\".format(self.brand, self.model, self.russian and \"DA BLYAT\" or \"NJET PIZDEC\")\n\nclass CarBuilder:\n\tdef __init__(self):\n\t\tself.car = Car()\n\tdef addBrand(self, brand):\n\t\tself.car.brand = brand\n\t\treturn self\n\tdef addModel(self, model):\n\t\tself.car.model = model\n\t\treturn self\n\tdef addRussian(self, russian):\n\t\tself.car.russian = russian\n\t\treturn self\n\tdef build(self):\n\t\treturn self.car\n\ncar = CarBuilder().addBrand(\"Lada\").addModel(\"Niva Urban\").addRussian(True).build()\nprint(car) # Car brand: Lada, model: Niva Urban, Russian?: DA BLYAT\n\n\t## 4. Prototype pattern\n\t\t# Prototypes zijn een soort factory. Javascript gebruikt deze prototypes voor klassen.\n\t\t# python heeft geen ingebouwde hi\u00ebrarchie\u00ebn, dus moet je zelf d.m.v. klassen iets soortgelijks\n\t\t# implementeren (als je zoiets wil).\n\t\t# In python is dit compleet overbodig omdat classes bestaan.\nimport copy\ndef makePrototype(klass):\n\treturn copy.deepcopy(klass)\npipiProto = makePrototype(Cat(\"Pipi\"))\nprint(pipiProto.speak()) # Miauw!\n\n# Structural design patterns\n\t# Dit soort design patterns beschrijven de structuur van objecten\n\n\t## 1. Decorators\n\t\t# Een decorator is een functie die een object uitbreidt.\n\t\t# Hele moeilijke manier, ik denk dat ik het wel begrijp.\n\t\t# Gek om een functional programming pattern te zien in een voornamelijk OOP tutorial\ndef makeAnchor(fun):\n\tdef decorator():\n\t\treturn \"{}\".format(fun())\n\treturn decorator\n\n@makeAnchor\ndef makeText():\n\treturn \"Hello, world!\"\n\nprint(makeText()) # Hello, world!\n\n\t## 2. Proxy\n\t\t# Een proxy is een object dat doet alsof het een ander object is.\n\t\t# Volgens de uitleg van deze man is het niet hetzelfde als wat ik ken als PRoxy,\n\t\t# namelijk de ingebouwde proxy-constructor van javascript.\n\t\t# Of ik begrijp hem niet goed, kan ook.\ntest = dict(test=\"test\")\n\nclass Proxy:\n\tdef __init__(self, target):\n\t\tself._target = target\n\tdef get(self, key, otherwise = \"nothing\"):\n\t\tif key in self._target:\n\t\t\treturn self._target[key]\n\t\telse:\n\t\t\treturn otherwise\n\ntest2 = Proxy(test)\nprint(test[\"test\"], test2.get(\"test\"), test2.get(\"tosti\")) # test test nothing\n\n# Behavioural design patterns\n\t# Dit soort design patterns beschrijven het gedrag van objecten\n\n\t## 1. Observer\n\t\t# Een observer observeert veranderingen binnen een object en geeft\n\t\t# mogelijkheden om daarop te reageren.\n\t\t# OOP mensen hebben functions as values ontdekt. Duidelijk.\nclass Subject:\n\t_listeners = []\n\tdef listen(self, listener):\n\t\tself._listeners.append(listener)\n\t\treturn self\n\tdef emit(self, value):\n\t\tfor listener in self._listeners:\n\t\t\tlistener(value)\n\nbroadcaster = Subject()\nbroadcaster.listen(print)\nbroadcaster.emit(\"BOODSCHAP!\") # prints \"BOODSCHAP!\"\n\n\t## 2. Visitor\n\t\t# Een visitor is een manier om een klasse uit te breiden zonder de code direct\n\t\t# aan te pakken. Dit is een welbekend pattern, maar niet om de jusite reden.\n\t\t# OOP heeft nogal wat problemen, waaronder moelijke refactoring. Alles hangt\n\t\t# nauw samen dus je wil niks veranderen. Om dat op te lossen gebruiken ze\n\t\t# dan visitors, maar de juiste oplossing is om niet zulke slecht refactorable code te schrijven.\n\t\t# Je kunt bijvoorbeeld functionele compositie gebruiken:\ndef compose(funs):\n\tdef inner(x):\n\t\tfor fun in funs:\n\t\t\tx = fun(x)\n\t\treturn x\n\treturn inner\n\ndef mult(a):\n\tdef inner(b):\n\t\treturn a * b\n\treturn inner\n\ndouble = mult(2)\nquadrupleAndPrint = compose([double, double, print])\nsayEight = quadrupleAndPrint(2) # 8\n\n\t## 2. Iterator\n\t\t# Een iterator is een functie/object dat een interface biedt om over waardes te itereren.\ndef countTo(n):\n\tx = 1\n\twhile x <= n:\n\t\tyield x\n\t\tx = x + 1\n\nfor num in countTo(5): # telt op van 1 tot 5\n\tprint(num)"} {"doc_id": "1de6144127bd8e5e83faa93d4b517fc3", "text": "\"\"\"\nDemonstrates While Loops\n\"\"\"\n\ndone = False #Declares a variable named done and assign it the value False\n\nwhile not done : #A while loop that iterates as long as done is not equal to True\n entry = input(\"Enter a value (x to exit): \") #Declares a variable named entry and prompt the user to enter any value.\n\n if entry == \"x\" : #If the user entered the letter x, sets the done variable to True\n done = True\n else : #Otherwise, prints the value of the entry variable.\n print(\"You entered: \" + entry)\n\nprint(\"Thank you!\")\n\nprint()\n\n\"\"\"\n#Declares a variable named userNum and prompt the user\n#to enter a number between 1 and 10.\n#Assigns the user's input to the userNum variable.\nuser_number = int(input(\"Enter a number between 1 and 10: \"))\n\n#Begins a while loop. It must iterate as long as the user enters a number\n#outside of the 1-10 range.\nwhile user_number < 1 or user_number > 10 :\n\n #Prompts the user to try entering a number again\n #Assigns their input to user_number.\n user_number = int(input(\"Try again. Enter a number between 1 and 10: \"))\n\n#An else clause that prints a thank you message.\nelse :\n print(\"Thank you!\")\n\"\"\"\n\n#********************************#\nprint()\n\n\"\"\"\n#Declares a variable named password.\npassword = \"P@55w0Rd\"\n\n#Prompts the user to enter the password.\n#Assigns the user's input to a variable named userPW\nuser_pw = input(\"Enter password: \")\n\n#Declares a variable named attempts and assigns it the value 1\nattempts = 1\n\n#Begins a while loop.\n#Iterates as long as userPW is not equal to the value in\n#the password variable\nwhile user_pw != password :\n\n #If the user has made 5 attempts, prints an error message and\n #stops the program by calling the exit() function.\n if attempts == 5 :\n print(\"Too many incorrect attempts.\")\n exit()\n\n #Prompts the user to try entering the password again.\n #Assigns the new input to the userPW variable\n user_pw = input(\"Retry password: \")\n\n #Adds one to the value of attempts\n attempts += 1\n\n#An else clause that prints \"Access Granted!\"\nelse :\n print(\"Access Granted\")\n\"\"\"\n"} {"doc_id": "1e8402d19653ba36b111b74855ac0136", "text": "print(\"\ubaa8\ub4e0 \uac83\uc744 \uc5f0\uc2b5\ud574 \ubd05\uc2dc\ub2e4.\")\nprint('\\\\\ub97c \uc774\uc6a9\ud574 \\n \uc0c8\uc904\uc774\ub098 \\t \ud0ed\uc744 \ud558\ub294 \ud0c8\ucd9c\uc21c\uc11c\uc5f4\uc5d0 \ub300\ud574 \\'\uc54c\uc544\uc57c\ub9cc\\' \ud569\ub2c8\ub2e4.')\n\npoem = \"\"\"\n\\tThe lovely world\nwith logic so firmly planted\ncannot discern \\n the needs of love\nnor comprehend passion from intuition\nand requires an explanation\n\\n\\t\\twhere there is none.\n\"\"\"\n\nprint(\"--------------\")\nprint(poem)\nprint(\"--------------\")\n\n\nfive = 10 - 2 + 3 - 6\nprint(\"\uc774 \uac12\uc740 \ub2e4\uc12f\uc785\ub2c8\ub2e4: %s\" % five)\n\ndef secret_formula(started):\n jelly_beans = started * 500\n jars = jelly_beans / 1000\n crates = jars / 100\n return jelly_beans, jars, crates\n\n\nstart_point = 10000\nbeans, jars, crates = secret_formula(start_point)\n\n# remember that this is another way to format a string\nprint(f\"\uc2dc\uc791\uc810: {}\".format(start_point))\n# it's just like with an f\"\" string\nprint(f\"{beans}\uc54c, {jars}\uadf8\ub987, {crates}\uc0c1\uc790\uac00 \uc788\uc2b5\ub2c8\ub2e4.\")\n\nstart_point = start_point / 10\n\nprint(\"\uc774\ub807\uac8c \ud560 \uc218\ub3c4 \uc788\uc2b5\ub2c8\ub2e4.\")\n# \ub9ac\uc2a4\ud2b8\ub97c \ud3ec\ub9f7 \ubb38\uc790\uc5f4\uc5d0 \uc801\uc6a9\ud558\ub294 \uc26c\uc6b4 \ubc29\ubc95\uc774\uc9c0\uc694\nprint(\"\uc824\ub9ac {}\uac1c, {}\uadf8\ub987, {}\uc0c1\uc790\uac00 \uc788\uc2b5\ub2c8\ub2e4.\".format(*formula))"} {"doc_id": "1f006904e0cbce9569da1ec44873972f", "text": "\"\"\"\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\n

Example 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\n

Example 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

    \n
  1. bottom will be a string with length in range [2, 8].
  2. \n
  3. allowed will have length in range [0, 200].
  4. \n
  5. Letters in all strings will be chosen from the set {'A', 'B', 'C', 'D', 'E', 'F', 'G'}.
  6. \n
\n

\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

\n\n

\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\n
    \n\t
  1. bottom \u7684\u957f\u5ea6\u8303\u56f4\u5728 [2, 8]\u3002
  2. \n\t
  3. allowed \u7684\u957f\u5ea6\u8303\u56f4\u5728[0, 200]\u3002
  4. \n\t
  5. \u65b9\u5757\u7684\u6807\u8bb0\u5b57\u6bcd\u8303\u56f4\u4e3a{'A', 'B', 'C', 'D', 'E', 'F', 'G'}\u3002
  6. \n
\n

\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

\n\n

\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\n
    \n\t
  1. bottom \u7684\u957f\u5ea6\u8303\u56f4\u5728 [2, 8]\u3002
  2. \n\t
  3. allowed \u7684\u957f\u5ea6\u8303\u56f4\u5728[0, 200]\u3002
  4. \n\t
  5. \u65b9\u5757\u7684\u6807\u8bb0\u5b57\u6bcd\u8303\u56f4\u4e3a{'A', 'B', 'C', 'D', 'E', 'F', 'G'}\u3002
  6. \n
\n\"\"\"\n\n\nclass Solution:\n def pyramidTransition(self, bottom, allowed):\n \"\"\"\n :type bottom: str\n :type allowed: List[str]\n :rtype: bool\n \"\"\""} {"doc_id": "1f1d57ea4791aab19573c1094c08e8de", "text": "class ToDoList(object):\n def __init__(self):\n self.data = []\n\n def addItem(self, item):\n if item not in self.data:\n self.data.append(item)\n print(\"Item added.\")\n else :\n print(\"Item already exists.\")\n\n def deleteItem(self, item):\n try:\n self.data.remove(item)\n print(\"Item deleted.\")\n except ValueError:\n print(\"Item was not found.\")\n\n def view(self):\n print(\"--------------TO-DO LIST--------------\")\n for i, item in enumerate(self.data, 1):\n print(str(i) + '\\t' + item)\n\nif __name__ == \"__main__\":\n verbose = False\n todolist = ToDoList()\n todolist.addItem(\"Make a better to-do list.\")\n todolist.addItem(\"Seriously.\")\n todolist.deleteItem(\"Make a better to-do list.\")\n todolist.deleteItem(\"Seriously.\")\n todolist.addItem(\"This is the best to-do list ever!!\")\n todolist.view()"} {"doc_id": "1f2d59c3ac615a8f44f0dd6f4993e33d", "text": "# 5.6.0 Multidimensional Data Sets\n\nclass TicTacToe:\n \"\"\"Management of a Tic-Tac-Toe game (does not do strategy).\"\"\"\n\n def __init__(self):\n \"\"\"Start a new game.\"\"\"\n self._board = [[' '] * 3 for j in range(3)]\n self._player = 'X'\n\n def mark(self,i,j):\n \"\"\"Put an X or O mark at position (i,j) for next player's turn.\"\"\"\n if not (0 <= i <= 2 and 0 <= j <= 2):\n raise ValueError('Invalid board position')\n if self._board[i][j] != ' ':\n raise ValueError('Board position occupied')\n if self.winner() is not None:\n raise ValueError('Game is already complete')\n self._board[i][j] = self._player\n if self._player == 'X':\n self._player = 'O'\n else:\n self._player = 'X'\n\n def _is_win(self,mark):\n \"\"\"Check whether the board configuration is a win for the given player.\"\"\"\n board = self._board # local variable for shorthand\n return (mark == board[0][0] == board[0][1] == board[0][2] or # row 0\n mark == board[1][0] == board[1][1] == board[1][2] or # row 1\n mark == board[2][0] == board[2][1] == board[2][2] or # row 2\n mark == board[0][0] == board[1][0] == board[2][0] or # column 0\n mark == board[0][1] == board[1][1] == board[2][1] or # column 1\n mark == board[0][2] == board[1][2] == board[2][2] or # column 2\n mark == board[0][0] == board[1][1] == board[2][2] or # diagonal\n mark == board[0][2] == board[1][1] == board[2][0]) # rev diag\n\n def winner(self):\n \"\"\"Reurn mark of winning player, or None to indicate a tie.\"\"\"\n for mark in 'XO':\n if self._is_win(mark):\n return mark\n return None\n\n def __str__(self):\n \"\"\"Return string representation of current game board.\"\"\"\n rows = ['|'.join(self._board[r]) for r in range(3)]\n return '\\n-----\\n'.join(rows)\n\n#----------------------------- my main function -----------------------------\n\nB = TicTacToe()\nB.mark(0,0)\nB.mark(1,0)\nB.mark(0,1)\nB.mark(1,1)\nB.mark(0,2)\nprint('X is the winner?',B._is_win('X'))\nprint('\\nThe board is as follows:')\nprint(B.__str__())\n"} {"doc_id": "1f4b59018d19893555015e466bc62450", "text": "# Surasith Boonaneksap File Created Aug 3rd 2021\r\n\r\nfrom math import cos, sin, radians\r\n\r\nclass Turtle:\r\n \"\"\"\r\n A class keeping a state of a turtle\r\n\r\n A turtle is an object used to represent a pen\r\n on a drawing board. It always move in a straight\r\n line according to its heading.\r\n\r\n Attributes\r\n ----------\r\n heading : float\r\n The current heading (degrees) of the turtle\r\n pos : tuple of ints\r\n The current coordinates, (x,y), of the turtle\r\n \"\"\"\r\n\r\n def __init__(self, heading = 90, pos = (0,0)):\r\n \"\"\"\r\n Initializing the turtle state\r\n\r\n Parameters\r\n ----------\r\n heading : float or int, default = 90\r\n The initial heading\r\n pos : tuple of ints, default = (0,0)\r\n The initial position\r\n \"\"\"\r\n \r\n self.heading = heading % 360\r\n self.pos = pos # x, y\r\n \r\n def __eq__(self, obj):\r\n \"\"\"Two Turtle objects are equal if all its attributes are equal\"\"\"\r\n \r\n return (self.heading == obj.heading and \r\n self.pos[0] == obj.pos[0] and\r\n self.pos[1] == obj.pos[1])\r\n\r\n def forward(self, dist = 1):\r\n \"\"\"\r\n Moving the turtle forward [dist] pixels in the heading direction\r\n \r\n Parameters\r\n ----------\r\n dist : float or int, default = 1\r\n The distance (pixels) that will be traveled\r\n \"\"\"\r\n\r\n rad = radians(self.heading)\r\n self.pos = (self.pos[0] + cos(rad)*dist, \r\n self.pos[1] + sin(rad)*dist)\r\n \r\n def turn(self, deg = 90):\r\n \"\"\"\r\n Change the heading of the turtle\r\n\r\n Parameters\r\n ----------\r\n deg : float or int, default: 90\r\n The angle (degrees) to change the current heading\r\n\r\n Notes\r\n -----\r\n The heading will always have a value between [0,360]\r\n \"\"\"\r\n\r\n self.heading = (self.heading + deg) % 360"} {"doc_id": "1f98984cc9052d1927f9d24002a7b2af", "text": "def check_in(a_element, b_iterable, param_name):\n \"\"\"\n Checks if a_element is in b_iterable. If not,\n the message is shown.\n\n Parameters:\n -----------\n\n a_element: object\n object whose presence in some iterable will be\n checked.\n\n b_iterable: iterable\n iterable where the presence of element is checked.\n\n param_name:\n Name of the parameter being checked.\n \"\"\"\n\n if a_element in b_iterable:\n return\n\n raise ValueError(\n \"%s should be one of %s, but got %s.\" % (param_name, a_element, b_iterable)\n )\n\ndef check_rng(a_element, b_rng, param_name):\n \"\"\"\n Checks if a_element is in range b_rng. If not,\n the message is shown.\n\n Parameters:\n -----------\n\n a_element: object\n object whose presence in some iterable will be\n checked.\n\n b_rng: iterable of form [a, b]\n feasible interval. Upper and lower bounds included.\n\n param_name:\n Name of the parameter being checked.\n \"\"\"\n\n if b_rng[0] <= a_element <= b_rng[1]:\n return\n\n raise ValueError(\n \"%s should be in the interval %s, but got %s.\" % (param_name, a_element, b_rng)\n )\n\ndef check_true(cond, error_message):\n \"\"\"\n Checks if cond. If not,\n the message is shown.\n\n Parameters:\n -----------\n\n cond: boolean\n condition to be checked.\n \"\"\"\n\n if cond:\n return\n\n raise AssertionError(\n error_message\n )\n\ndef check_isinst(example, clazz, param_name):\n \"\"\"\n Checks if example is an instance of example.\n If not, the message is shown.\n\n Parameters:\n -----------\n\n example: object\n object whose type will be checked.\n\n clazz: iterable\n class type.\n\n error_message:\n Error message to be shown.\n \"\"\"\n\n if isinstance(example, clazz):\n return\n\n raise ValueError(\n \"%s parameter should be of type: %s, but got type: %s\" % (param_name, clazz, type(example))\n )"} {"doc_id": "1ffa54f18ca83aec1dcd2058b9fdc210", "text": "# -*- codiing:utf-8 -*-\n\"\"\"os example\"\"\"\n__author__=\"aaron.qiu\"\n\nimport os\nfrom collections import deque\nfrom math import pi\n\ndef dictShowcase():\n \"\"\"dict example\"\"\"\n tel = {'jack': 4098, 'sape': 4139}\n print(tel['jack'])\n print(tel)\n del tel['sape']\n print(tel)\n dict1 = dict([('sape', 4139), ('guido', 4127), ('jack', 4098)])\n print(dict1)\n print({x: x**2 for x in (2, 4, 6)})\n print(dict(sape=4139, guido=4127, jack=4098))\n #loop\n knights = {'gallahad': 'the pure', 'robin': 'the brave'}\n for k, v in knights.items():\n print(k, v)\n\n for i, v in enumerate(['tic', 'tac', 'toe']):\n print(i, v)\n\n #\u591a\u4e2a\u961f\u5217\u5faa\u73af\n questions = ['name', 'quest', 'favorite color']\n answers = ['lancelot', 'the holy grail', 'blue']\n for q, a in zip(questions, answers):\n print('What is your {0}? It is {1}.'.format(q, a))\n\n #\u53cd\u8f6c\u961f\u5217\n for i in reversed(range(1, 10, 2)):\n print(i)\n\n basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']\n #\u6392\u5e8f\n for f in sorted(set(basket)):\n print(f)\n\n\ndef listShowcase():\n fruits = ['orange', 'apple', 'pear', 'banana', 'kiwi', 'apple', 'banana']\n #\u7edf\u8ba1\n print(fruits.count('apple'))\n print(fruits.index('banana'))\n print(fruits.index('banana', 4))\n fruits.reverse()\n print(fruits)\n fruits.sort()\n print(fruits)\n print(fruits.pop())\n\n #Using Lists as Stacks\n stack = [3, 4, 5]\n stack.append(6)\n stack.append(7)\n print(stack)\n print(stack.pop())\n\n #Using Lists as Queues first-in, first-out\n queue = deque([\"Eric\", \"John\", \"Michael\"])\n queue.append(\"Terry\") # Terry arrives\n queue.append(\"Graham\") # Graham arrives\n print(queue.popleft()) # The first to arrive now leaves\n print(queue)\n\n squares = []\n for x in range(10):\n squares.append(x ** 2)\n print(squares)\n\n print(\"===================\")\n squares = list(map(lambda x: x ** 2, range(10))) #equivalently: squares = [x**2 for x in range(10)]\n print(squares)\n\n condictionList = [(x, y) for x in [1, 2, 3] for y in [3, 1, 4] if x != y]\n print(condictionList)\n\n print([str(round(pi, i)) for i in range(1, 6)])\n\n #Nested List Comprehensions\n matrix = [\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n [9, 10, 11, 12],\n ]\n print([[row[i] for row in matrix] for i in range(4)])\n\ndef tupleShowcase():\n \"\"\"A tuple consists of a number of values separated by commas\"\"\"\n t = 12345, 54321, 'hello!'\n print(t[0])\n print(t)\n\n # Tuples may be nested:\n u = t, (1, 2, 3, 4, 5)\n print(u)\n\ndef setShowcase():\n basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}\n print(basket)\n # fast membership testing\n print('orange' in basket)\n a = set('abracadabra')\n b = set('alacazam')\n print(a)\n print(b)\n print(\"============================\")\n print(a-b) # letters in a but not in b\n print(a|b) # letters in a or b or both\n print(a&b) # letters in both a and b\n print(a^b) # letters in a or b but not both\n\n a = {x for x in 'abracadabra' if x not in 'abc'}\n print(a)\n\nif __name__ == \"__main__\":\n #dictShowcase()\n #listShowcase()\n #tupleShowcase()\n setShowcase()"} {"doc_id": "201432509504ac07996b13822804aafb", "text": "\"\"\"\n

Given 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\n

Example 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

    \n
  1. The value in the given matrix is in the range of [0, 255].
  2. \n
  3. The length and width of the given matrix are in the range of [1, 150].
  4. \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\n
    \n\t
  1. \u7ed9\u5b9a\u77e9\u9635\u4e2d\u7684\u6574\u6570\u8303\u56f4\u4e3a [0, 255]\u3002
  2. \n\t
  3. \u77e9\u9635\u7684\u957f\u548c\u5bbd\u7684\u8303\u56f4\u5747\u4e3a [1, 150]\u3002
  4. \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\n
    \n\t
  1. \u7ed9\u5b9a\u77e9\u9635\u4e2d\u7684\u6574\u6570\u8303\u56f4\u4e3a [0, 255]\u3002
  2. \n\t
  3. \u77e9\u9635\u7684\u957f\u548c\u5bbd\u7684\u8303\u56f4\u5747\u4e3a [1, 150]\u3002
  4. \n
\n\"\"\"\n\n\nclass Solution(object):\n def imageSmoother(self, M):\n \"\"\"\n :type M: List[List[int]]\n :rtype: List[List[int]]\n \"\"\"\n "} {"doc_id": "20509c20b036f14a4cc85aeafcb19cab", "text": "'''\nFile name: pythonpractice.py\nAuthor: Hannah Lewis\nDate created: 07/17/2020\nDate last modified: 08/03/2020\nPython Version: 3.7\n\nThese are a bunch of silly practice problems from practicepython.org.\n'''\n\ndef char_input():\n '''\n Create a program that asks the user to enter their name and their age. Print out a message addressed to them that tells them the year that they will turn 100 years old.\n\n Extras:\n Add on to the previous program by asking the user for another number and printing out that many copies of the previous message.\n Print out that many copies of the message on separate lines.\n '''\n import time\n \n print(\"This exercise tells you in what year you will turn 100.\\n\")\n \n name = input(\"What is your name?: \") # Get name\n age = int(input(\"And (we know it's not polite to ask but...) what is your age (as a whole number, please)?: \")) # Get age\n \n year, _, _, _, _ = map(int, time.strftime(\"%Y %m %d %H %M\").split()) # Get current year\n year_100 = year - age + 100 # Calculate what year they'll turn 100\n \n times = int(input(\"How many times would you like to see the message I'm about to print out?: \"))\n \n for i in range(times):\n print(\"Hello, \" + name + \"! You will turn 100 years old in the year \" + str(year_100) + \". Happy birthday!\")\n i += 1 # Print message again\n \n return year_100\n \ndef odd_even():\n '''\n Ask the user for a number. Depending on whether the number is even or odd, print out an appropriate message to the user.\n\n Extras:\n If the number is a multiple of 4, print out a different message.\n Ask the user for two numbers: one number to check (call it num) and one number to divide by (check). If check divides evenly into num, tell that to the user. If not, print a different appropriate message.\n '''\n \n print(\"This exercise will tell you if a number is even or odd, and if it is divisible by another integer.\\n\")\n \n num = int(input(\"Give me an integer, please!: \")) # Get number\n check = int(input(\"What number do you want to divide {} by?: \".format(num))) # Get divisor\n \n assert num > check, \"We're only doing integer division here! The divisor you gave is larger than the dividend.\"\n \n if num % 4 == 0: # If mod4 is 0, the number is divisible by 4\n print(str(num) + \" is a multiple of 4.\")\n elif num % 2 == 0: # If mod2 is 0, the number is even\n print(str(num) + \" is an even number!\")\n elif num % 2 == 1: # If mod2 is 1, the number is odd\n print(str(num) + \" is an odd number!\")\n \n if num % check == 0: # Check if number is divisible by the given divisor\n print(\"And it's also divisible by \" + str(check) + \".\")\n elif num % check == 1:\n print(\"It's not divisible by \" + str(check) + \" though.\")\n \n return\n \ndef list_less_than():\n '''\n Take a list and write a program that prints out all the elements of the list that are less than 5.\n\n Extras:\n Instead of printing the elements one by one, make a new list that has all the elements less than 5 from this list in it and print out this new list.\n Write this in one line of Python.\n Ask the user for a number and return a list that contains only elements from the original list a that are smaller than that number given by the user.\n '''\n \n print(\"This exercise will tell you, from a predefined list of numbers, which ones are less than another number.\\n\")\n \n a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] # Sample list here, can be substituted/changed\n \n num = int(input(\"Give me an integer, please!: \"))\n \n b = [x for x in a if x < num] # List with numbers smaller than the input\n \n print(\"Here is the original list: \", a)\n print(\"From this list, {} are all less than {}.\".format(b,num))\n \n return b\n \ndef divisors():\n '''\n Create a program that asks the user for a number and then prints out a list of all the divisors of that number.\n '''\n \n import numpy as np\n \n print(\"This exercise will give you all the divisors of a number.\\n\")\n \n num = int(input(\"Give me an integer, please!: \"))\n \n x = np.arange(1,num+1) # Generate an array of numbers between 1 and the input number\n \n div = []\n for n in x:\n if num % n == 0: # If modn is 0, the number is divisible by n\n div.append(n)\n else:\n continue\n \n print(\"{} is divisible by {}.\".format(num,div))\n \n return div\n \ndef list_overlap():\n '''\n Take two lists and write a program that returns a list that contains only the elements that are common between the lists (without duplicates). Make sure your program works on two lists of different sizes.\n\n Extras:\n Randomly generate two lists to test this\n '''\n \n import random\n \n print(\"This exercise will generate two random lists of random lengths, and then tell you their intersection.\\n\")\n \n n1 = random.randint(1,20) # Random length of first list\n a = sorted(random.sample(range(0, 50), n1)) # First list of random length and random numbers\n\n n2 = random.randint(1,20) # Random length of second list\n b = sorted(random.sample(range(0, 50), n2)) # Second list of random length and random numbers\n \n #list_overlap = []\n #for i in a:\n #if i in b and i not in list_overlap: # Find intersection/overlap\n #list_overlap.append(i)\n \n b = list(set(a))\n \n print(\"Here are the original lists:\")\n print(a)\n print(b)\n if len(list_overlap) > 0:\n print(\"The intersection of these two lists is {}.\".format(list_overlap))\n else:\n print(\"The intersection of these two lists is the null set.\")\n \n return list_overlap\n \ndef string_list():\n '''\n Ask the user for a string and print out whether this string is a palindrome or not.\n '''\n \n print(\"This exercise will tell you if a word is a palindrome!\\n\")\n \n word = input(\"Input a word, and I'll check to see if it is a palindrome: \")\n \n backwards = word[::-1] # Get the word, backwards\n\n if word.lower() == backwards.lower(): # Compares the strings, ignoring case\n pal = True\n print(\"{} is a palindrome!\".format(word))\n else:\n pal = False\n print(\"{} is not a palindrome.\".format(word))\n \n return pal\n \ndef list_comp():\n '''\n Write one line of Python that takes a list and makes a new list that has only the even elements of this list in it.\n '''\n \n print(\"This exercise will tell you all the even elements of a predefined list.\\n\")\n \n a = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]\n b = [x for x in a if x % 2 == 0] # Get even elements\n \n print(\"Here is the original array: \", a)\n print(\"Here are the even elements from that array: \", b)\n \n return b\n \ndef rps():\n '''\n Make a two-player Rock-Paper-Scissors game.\n \n I'm actually going to make this a one-player vs. CPU game with random throws from the CPU\n\n Remember the rules:\n\n Rock beats scissors\n Scissors beats paper\n Paper beats rock\n '''\n \n import random\n \n print(\"This exercise is an infinite game of Rock, Paper, Scissors between the player and the CPU.\\n\")\n \n game_dict = {'rock': 1, 'scissors': 2, 'paper': 3}\n \n while True:\n \n player = input(\"Rock, paper, scissors. Shoot! (enter your throw): \") # Get player throw\n \n n_rps = random.randint(0,2)\n rps_array = ['rock', 'scissors', 'paper']\n CPU_rps = rps_array[n_rps] # Get CPU throw\n \n assert player.lower() in rps_array, \"Enter rock, paper, or scissors.\"\n \n a = game_dict.get(player.lower())\n b = game_dict.get(CPU_rps.lower())\n \n dif = a - b\n \n print(\"CPU threw \" + CPU_rps + \".\")\n \n if dif in [-1,2]: # Compare throws to find winner\n print(\"Player wins!\")\n elif dif in [-2,1]: # Compare throws to find winner\n print(\"CPU wins!\")\n else: # Or tie\n print(\"It's a tie!\")\n \n again = input(\"Do you want to play another game, yes or no?: \").lower()\n if again == 'yes' or again == 'y':\n continue\n else:\n print(\"Good game!\")\n break\n \n return\n \ndef guessing_game():\n '''\n Generate a random number between 1 and 10 (including 1 and 10). Ask the user to guess the number, then tell them whether they guessed too low, too high, or exactly right.\n\n Extras:\n Keep the game going until the user types 'exit'\n Keep track of how many guesses the user has taken, and when the game ends, print this out.\n '''\n \n import random\n \n print(\"This exercise will ask you to guess what number the CPU has thought of.\\n\")\n \n print(\"You can type 'exit' at any time to end the game.\")\n \n num = random.randint(1,10) # Get random number\n \n guess = input(\"Guess a number between 1 and 10: \") # Get first guess\n count = 0\n \n guessing = True\n \n while guessing:\n \n if guess == 'exit': # Player can exit at any time\n break\n \n count += 1 # Count how many guesses the player takes\n \n if num > int(guess):\n guess = input(\"Too low! Guess again: \")\n elif num < int(guess):\n guess = input(\"Too high! Guess again: \")\n elif num == int(guess):\n if count == 1:\n print(\"You got it on the first try!\")\n guessing = False\n if count > 1:\n print(\"You got it! It took you\", count, \"tries.\")\n guessing = False\n elif guess.lower() == 'exit':\n print(\"Better luck next time.\")\n guessing = False\n \n return\n \ndef list_overlap_v2():\n '''\n Take two lists and write a program that returns a list that contains only the elements that are common between the lists (without duplicates). Make sure your program works on two lists of different sizes. Write this in one line of Python.\n\n Extra:\n Randomly generate two lists to test this\n '''\n \n import random\n \n print(\"This exercise will generate two random lists of random lengths, and then tell you their intersection, using sets instead of list comprehension.\\n\")\n\n n1 = random.randint(1,20) # Random length of first list\n a = set(random.sample(range(0, 50), n1)) # First set of random length and random numbers\n\n n2 = random.randint(1,20) # Random length of second list\n b = set(random.sample(range(0, 50), n2)) # Second set of random length and random numbers\n \n list_overlap = sorted(list(a & b)) # Find intersection/overlap\n \n print(\"Here are the original lists:\")\n print(a)\n print(b)\n if len(list_overlap) > 0:\n print(\"The intersection of these two lists is {}.\".format(list_overlap))\n else:\n print(\"The intersection of these two lists is the null set.\")\n \n return list_overlap\n \ndef check_prime():\n '''\n Ask the user for a number and determine whether the number is prime or not.\n '''\n \n import numpy as np\n \n print(\"This exercise will tell you if a number is a prime number.\\n\")\n \n div = divisors() # Run divisors exercise\n \n if len(div) == 2: # Prime if only divisible by 1 and itself\n print(\"So it is a prime number!\")\n else:\n print(\"It's NOT a prime number.\")\n \n return div\n \ndef first_last():\n '''\n Write a program that takes a list of numbers and makes a new list of only the first and last elements of the given list.\n '''\n \n print(\"This exercise returns an array of the first and last elements of a predefined list.\\n\")\n \n a = [5, 10, 15, 20, 25, 30, 35, 40, 45, 50]\n \n b = [a[0], a[-1]] # Create list of first and last elements\n \n print(\"Here is the original array: \", a)\n print(\"Here are the first and last elements from that array: \", b)\n \n return b\n \ndef fib():\n '''\n Write a program that asks the user how many Fibonnaci numbers to generate and then generates them.\n '''\n \n print(\"This exercise returns list of Fibonacci numbers.\\n\")\n \n num = int(input(\"How many Fibonacci numbers would you like to generate?: \"))\n \n i = 1\n \n if num == 0: # Generate the first few Fibonacci numbers manually\n f = []\n elif num == 1:\n f = [1]\n elif num == 2:\n f = [1, 1]\n else: # Then just take the sum of the previous two numbers\n f = [1, 1]\n while i < (num-1):\n f.append(f[i] + f[i-1])\n i += 1\n \n print(\"Here are the first {} Fibonnaci numbers: {}\".format(num, f))\n \n return f\n \ndef remove_duplicates():\n '''\n Write a program (function!) that takes a list and returns a new list that contains all the elements of the first list minus all the duplicates.\n\n Extras:\n Write two different functions to do this - one using a loop and constructing a list, and another using sets.\n Go back and do Exercise 5 using sets, and write the solution for that in a different function.\n '''\n \n import random\n \n print(\"This exercise returns a unique list of numbers from a list.\\n\")\n \n n1 = random.randint(1,20) # Random length of list\n a = random.choices(range(1, 25), k=n1) # First list of random length and random numbers\n \n #b = []\n #for i in a:\n #if i not in b:\n #b.append(i)\n \n b = list(set(a))\n \n print(\"Here is the original array: \", a)\n print(\"Here are the unique elements from that array: \", b)\n \n return b\n \ndef reverse_word():\n '''\n Write a program that asks the user for a long string containing multiple words. Print back to the user the same string, except with the words in backwards order.\n '''\n \n print(\"This exercise returns words in a sentence in the reverse order.\\n\")\n \n sentence = input(\"Write a sentence, without punctuation:\\n\")\n \n print(' '.join(sentence.split(' ')[::-1])) # Get the sentence, backwards\n \n return ' '.join(sentence.split(' ')[::-1])\n \ndef pass_gen():\n '''\n Write a password generator in Python. Be creative with how you generate passwords - strong passwords have a mix of lowercase letters, uppercase letters, numbers, and symbols. The passwords should be random, generating a new password every time the user asks for a new password.\n '''\n \n import string\n import random\n \n print(\"This exercise returns a randomly generated password.\\n\")\n \n length = int(input(\"How many characters do you want in your password? \"))\n \n chars = string.ascii_letters + string.digits + string.punctuation # Which characters to choose from\n \n password = ''.join(random.choice(chars) for _ in range(length)) # Get random characters\n\n print(\"Here's your password: \", password)\n \n return password\n \ndef read_web_page():\n '''\n Use the BeautifulSoup and requests Python packages to print out a list of all the article titles on the New York Times homepage.\n '''\n \n import requests\n from bs4 import BeautifulSoup\n \n print(\"This exercise returns a list of articles on the NYT homepage.\\n\")\n \n headers = {'User-Agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_2) AppleWebKit/601.3.9 (KHTML, like Gecko) Version/9.0.2 Safari/601.3.9'} # Pretend to be a browser\n \n site = 'https://www.nytimes.com/' # Which website to scrape?\n \n response = requests.get(site,headers=headers)\n soup = BeautifulSoup(response.content, 'lxml') # Get soup\n for item in soup.select('.assetWrapper'):\n try:\n print('---------------------')\n headline = item.find('h2').get_text() # Headlines, delineated by 'h2' as of August 2020, these are all specific to the NYT homepage and probably vary from site to site\n link = item.find('a')['href'] # URLs, 'a'\n summary = item.find('p').get_text() # Brief summary, 'p'\n print(headline) # Print all this info to the terminal, a later exercise sends all of this info to a txt file\n print(link)\n print(summary)\n except Exception as e: #raise exception\n print('')\n \n return\n \ndef cows_bulls():\n '''\n Create a program that will play Cows and Bulls with the user.\n '''\n \n import random\n \n print(\"This exercise is a game of Cow-Bull.\\n\")\n print(\"You will try to guess a random 4-digit number.\")\n print(\"A 'cow' is a correct digit in the correct place.\")\n print(\"A 'bull' is a correct digit in the wrong place.\")\n print(\"The game ends when you get 4 cows!\\n\")\n \n print(\"You can type 'exit' at any time to end the game.\\n\")\n \n num = str(random.randint(10000, 99999))[1:5] # Get random number, remove first digit so that first digit can be 0\n \n guess = input(\"Give me your best guess: \") # Get first guess\n \n count = 0\n cow = 0\n bull = 0\n \n guessing = True\n \n while guessing:\n \n assert len(guess) == 4, \"Input must be 4-digits long.\"\n \n if guess == 'exit': # Player can exit at any time\n guessing = False\n break\n \n count += 1\n \n for i in range(0,4): # Compare digits\n if num[i] == guess[i]:\n cow+=1\n elif num[i] in guess:\n bull+=1\n print(\"You got {} cows, and {} bulls.\".format(cow,bull)) # How many cows and bulls\n \n if cow == 4: # If all digits are correct\n if count == 1:\n print(\"You got it on the first try!\")\n guessing = False\n if count > 1:\n print(\"You got it! It took you\", count, \"tries.\")\n print(\"The number was \" + str(num) + \".\")\n guessing = False\n elif guess.lower() == 'exit': # If player wants to exit\n print(\"The number was \" + str(num) + \".\")\n print(\"Better luck next time.\")\n guessing = False\n break\n else: # Guess again\n cow = bull = 0\n guess = input(\"Guess again: \")\n \n return\n \ndef read_web_page_v2():\n '''\n Using the requests and BeautifulSoup Python libraries, print to the screen the full text of the article on this website: http://www.vanityfair.com/society/2014/06/monica-lewinsky-humiliation-culture.\n\n The article is long, so it is split up between 4 pages. Your task is to print out the text to the screen so that you can read the full article without having to click any buttons.\n\n This will just print the full text of the article to the screen. It will not make it easy to read, so next exercise we will learn how to write this text to a .txt file.\n '''\n \n import requests\n from bs4 import BeautifulSoup\n import csv\n \n print(\"This exercise prints the text of an article at a predefined URL.\\n\")\n \n headers = {'User-Agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_2) AppleWebKit/601.3.9 (KHTML, like Gecko) Version/9.0.2 Safari/601.3.9'} # Pretend to be a browser\n \n site = 'http://www.vanityfair.com/society/2014/06/monica-lewinsky-humiliation-culture' # Which article to get?\n \n response = requests.get(site,headers=headers)\n soup = BeautifulSoup(response.text, 'html.parser') # Get soup\n \n article = soup.select('p') # Get full article text\n cleaned = []\n\n for i in article: # Remove containers\n temp = i.text.replace(\"\",\"\")\n cleaned.append(temp)\n \n print(cleaned) # Print all this info to the terminal, a later exercise sends all of this info to a txt file\n \n return cleaned\n \ndef elem_search():\n '''\n Write a function that takes an ordered list of numbers (a list where the elements are in order from smallest to largest) and another number. The function decides whether or not the given number is inside the list and returns an appropriate boolean.\n '''\n \n import random\n \n print(\"This exercise tells you if a number is in a random list of numbers.\\n\")\n \n num = int(input(\"Give me an integer, please! (between 1 and 100): \"))\n\n n1 = random.randint(10,20) # Random length of list\n a = sorted(random.sample(range(1, 100), n1)) # List of random length and random numbers\n \n print(\"Here is the original array: \", a)\n print(\"{} is in that array. {}\".format(num, num in a))\n \n return num in a\n \ndef read_web_page_v3():\n '''\n Take the code from the How To Decode A Website exercise, and instead of printing the results to a screen, write the results to a txt file. In your code, just make up a name for the file you are saving to.\n\n Extras:\n Ask the user to specify the name of the output file that will be saved.\n '''\n\n import requests\n from bs4 import BeautifulSoup\n import csv\n\n print(\"This exercise returns the text of an article at a predefined URL to a text file named based on user input.\\n\")\n\n headers = {'User-Agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_2) AppleWebKit/601.3.9 (KHTML, like Gecko) Version/9.0.2 Safari/601.3.9'} # Pretend to be a browser\n \n site = 'http://www.vanityfair.com/society/2014/06/monica-lewinsky-humiliation-culture' # Which article to get?\n \n response = requests.get(site,headers=headers)\n soup = BeautifulSoup(response.text, 'html.parser') # Get soup\n\n article = soup.select('p') # Get full article text\n cleaned = []\n \n name = input(\"What do you want the file to be called?: \") # Get name of output file\n\n for i in article: # Remove containers\n temp = i.text.replace(\"\",\"\")\n cleaned.append(temp)\n\n with open(name + '.txt','w') as txt: # Write all this info to a txt file\n for line in cleaned:\n txt.write(line) # Write lines\n \n return cleaned\n \ndef read_file():\n '''\n Given a txt file that has a list of names, count how many of each name there are in the file, and print out the results to the screen.\n\n Extra:\n Instead of using the txt file from above, take this txt file, and count how many of each \u201ccategory\u201d of each image there are. This text file is actually a list of files corresponding to the SUN database scene recognition database, and lists the file directory hierarchy for the images. Once you take a look at the first line or two of the file, it will be clear which part represents the scene category. To do this, you\u2019re going to have to remember a bit about string parsing in Python 3.\n '''\n \n print(\"This exercise opens a predefined text file, reads the rows, and returns how many of each thing are in the file.\\n\")\n \n names_dict = {}\n with open('ref_files/nameslist.txt','r') as f: # Open the file of names\n line = f.readline() # Read line\n while line:\n line = line.strip()\n if line in names_dict:\n names_dict[line] += 1 # Add to count if name is already in the dictionary\n else:\n names_dict[line] = 1 # Start count if name isn't already in the dictionary\n line = f.readline() # Read next line\n \n print(names_dict)\n \n scenes_dict = {}\n with open('ref_files/SUNscenes.txt','r') as f: # Open the SUN database\n line = f.readline() # Read line\n while line:\n line = line[3:-26] # Crop off the random digits at the end\n if line in scenes_dict:\n scenes_dict[line] += 1 # Add to count if image catagory is already in the dictionary\n else:\n scenes_dict[line] = 1 # Start count if image category isn't already in the dictionary\n line = f.readline() # Read next line\n \n print(scenes_dict)\n \n return names_dict, scenes_dict\n\ndef file_overlap():\n '''\n Given two txt files that have lists of numbers in them, find the numbers that are overlapping. One txt file has a list of all prime numbers under 1000, and the other txt file has a list of happy numbers up to 1000.\n '''\n\n print(\"This exercise opens two text files, containing lists of prime numbers and happy numbers, and finds the overlap of the numbers in the files.\\n\")\n \n primes = []\n with open('ref_files/primes.txt','r') as f: # Open the primes txt file\n line = f.readline() # Read line\n while line:\n primes.append(int(line)) # Add to the list of primes\n line = f.readline() # Read line\n primes = set(primes) # Make the list a set\n \n happy = []\n with open('ref_files/happy.txt','r') as f: # Open the happy txt files\n line = f.readline() # Read line\n while line:\n happy.append(int(line)) # Add to the list of happy numbers\n line = f.readline() # Read line\n happy = set(happy) # Make the list a set\n \n overlap = sorted(list(primes & happy)) # Find intersection/overlap\n \n print(overlap)\n \n return overlap\n \ndef draw_gameboard():\n '''\n This exercise is Part 1 of 4 of the Tic Tac Toe exercise series.\n\n Time for some fake graphics! Let\u2019s say we want to draw game boards that look like this:\n --- --- ---\n | | | |\n --- --- ---\n | | | |\n --- --- ---\n | | | |\n --- --- ---\n This one is 3x3 (like in tic tac toe). Obviously, they come in many other sizes (8x8 for chess, 19x19 for Go, and many more).\n\n Ask the user what size game board they want to draw, and draw it for them to the screen using Python\u2019s print statement.\n '''\n\n print(\"This exercise prints a square 2-D game board based on user input.\\n\")\n \n size = int(input(\"How large do you want your game board to be?: \"))\n\n for x in range(size):\n print(' ---' * size)\n print('| ' * (size+1))\n print(' ---' * size)\n \n return\n \ndef guessing_game_v2():\n '''\n In a previous exercise, we\u2019ve written a program that \"knows\" a number and asks a user to guess it.\n\n This time, we\u2019re going to do exactly the opposite. You, the user, will have in your head a number between 0 and 100. The program will guess a number, and you, the user, will say whether it is too high, too low, or your number.\n\n At the end of this exchange, your program should print out how many guesses it took to get your number.\n '''\n\n import random\n import time\n\n print(\"This exercise will ask you to think of a number, and the CPU will try to guess the number.\\n\")\n\n print(\"You can type 'exit' at any time to end the game.\\n\")\n \n min = 1\n max = 100\n\n print(\"You have 5 seconds to think of a number between {} and {}...\".format(min, max))\n \n time.sleep(5) # Wait 5 seconds\n \n count = 0\n CPU = random.randint(min,max) # Generate the first guess\n print(\"Okay, the CPU has the first guess: {}\".format(CPU))\n \n answering = True\n\n while answering:\n \n ans = input(\"Is this the number you were thinking of? (yes, high, or low): \")\n \n if ans == 'exit': # Player can exit at any time\n print(\"Better luck next time, CPU!\")\n break\n \n count += 1\n \n if ans.lower() == 'yes':\n if count == 1:\n print(\"The CPU got it on the first try!\")\n answering = False\n if count > 1:\n print(\"The CPU got it! It took\", count, \"tries.\")\n answering = False\n elif ans.lower() == 'high':\n max = CPU-1\n CPU = random.randint(min,max) # Based on high guess, set new upper limit, and generate the next guess\n print(\"Guess: {}\".format(CPU))\n answering = True\n elif ans.lower() == 'low':\n min = CPU+1\n CPU = random.randint(min,max) # Based on low guess, set new lower limit, and generate the next guess\n print(\"Guess: {}\".format(CPU))\n answering = True\n elif ans.lower() == 'exit':\n print(\"Better luck next time, CPU!\")\n answering = False\n \n return\n \ndef check_tic_tac_toe():\n '''\n We will simply focus on checking whether someone has WON a game of Tic Tac Toe, not worrying about how the moves were made.\n\n If a game of Tic Tac Toe is represented as a list of lists, like so:\n game = [[1, 2, 0],\n [2, 1, 0],\n [2, 1, 1]]\n where a 0 means an empty square, a 1 means that player 1 put their token in that space, and a 2 means that player 2 put their token in that space.\n\n Your task: given a 3 by 3 list of lists that represents a Tic Tac Toe game board, tell me whether anyone has won, and tell me which player won, if any. A Tic Tac Toe win is 3 in a row - either in a row, a column, or a diagonal. Don\u2019t worry about the case where TWO people have won - assume that in every board there will only be one winner.\n '''\n \n print(\"This exercise checks the winner of a game of tic-tac-toe.\")\n \n def check_grid(grid): # Set winner to something other than None when one of the players wins\n \n for x in range(0,3): # Define what a win looks like in a row\n row = set([grid[x][0],grid[x][1],grid[x][2]])\n if len(row) == 1 and grid[x][0] != 0:\n return grid[x][0]\n\n for x in range(0,3): # Define what a win looks like in a column\n column = set([grid[0][x],grid[1][x],grid[2][x]])\n if len(column) == 1 and grid[0][x] != 0:\n return grid[0][x]\n\n diag1 = set([grid[0][0],grid[1][1],grid[2][2]])\n diag2 = set([grid[0][2],grid[1][1],grid[2][0]]) # Define what a win looks like on a diagonal\n if len(diag1) == 1 or len(diag2) == 1 and grid[1][1] != 0:\n return grid[1][1]\n \n return None\n \n # A few checks to make sure the check_grid function is getting the right answer\n \n winner_is_1 = [[1, 2, 0],\n [2, 1, 0],\n [2, 1, 1]]\n winner_is_also_1 = [[0, 1, 0],\n [2, 1, 0],\n [2, 1, 1]]\n winner_is_2 = [[2, 2, 0],\n [2, 1, 0],\n [2, 1, 1]]\n no_winner = [[1, 2, 0],\n [2, 1, 0],\n [2, 1, 2]]\n also_no_winner = [[1, 2, 0],\n [2, 1, 0],\n [2, 1, 0]]\n first_move = [[0, 0, 0],\n [0, 1, 0],\n [0, 0, 0]]\n \n assert check_grid(winner_is_1) == 1, \"Got the wrong winner\"\n assert check_grid(winner_is_also_1) == 1, \"Got the wrong winner\"\n assert check_grid(winner_is_2) == 2, \"Got the wrong winner\"\n assert check_grid(no_winner) == None, \"Got the wrong winner\"\n assert check_grid(also_no_winner) == None, \"Got the wrong winner\"\n \n print(check_grid(first_move))\n \n return\n \ndef tic_tac_toe_input():\n '''\n The next logical step is to deal with handling user input. When a player (say player 1, who is X) wants to place an X on the screen, they can\u2019t just click on a terminal. So we are going to approximate this clicking simply by asking the user for a coordinate of where they want to place their piece.\n\n As a reminder, our tic tac toe game is really a list of lists. The game starts out with an empty game board like this:\n game = [[0, 0, 0],\n [0, 0, 0],\n [0, 0, 0]]\n The computer asks Player 1 (X) what their move is (in the format row,col), and say they type 1,3. Then the game would print out\n game = [[0, 0, X],\n [0, 0, 0],\n [0, 0, 0]]\n Then ask Player 2 for their move, printing an O in that place.\n '''\n \n print(\"This exercise is a game of tic-tac-toe!\\n\")\n \n print(\"You can type 'exit' at any time to end the game.\\n\")\n \n def check_grid(grid): # Set winner to something other than None when one of the players wins\n\n for x in range(0,3): # Define what a win looks like in a row\n row = set([grid[x][0],grid[x][1],grid[x][2]])\n if len(row) == 1 and grid[x][0] != 0:\n return grid[x][0]\n\n for x in range(0,3): # Define what a win looks like in a column\n column = set([grid[0][x],grid[1][x],grid[2][x]])\n if len(column) == 1 and grid[0][x] != 0:\n return grid[0][x]\n\n diag1 = set([grid[0][0],grid[1][1],grid[2][2]])\n diag2 = set([grid[0][2],grid[1][1],grid[2][0]]) # Define what a win looks like on a diagonal\n if len(diag1) == 1 or len(diag2) == 1 and grid[1][1] != 0:\n return grid[1][1]\n \n return None\n \n def check_winner(grid):\n winner = check_grid(grid)\n return winner\n \n turn = 0 # Count the cells on the board that are filled to determine when the gameboard is full and the game ends\n winner = None\n game = [[0, 0, 0], # Define the empty game board\n [0, 0, 0],\n [0, 0, 0]]\n \n playing = True # Set playing to False if there is a winner or if one of the players enters 'exit'\n\n while playing and winner == None:\n \n if turn % 2 == 0: # Player 1 goes on even numbered turns (0,2,4...), Player 2 goes on even numbered turns (1,3,5...)\n player_turn = '1'\n else:\n player_turn = '2'\n \n if turn % 2 == 0: # Player 1 is Xs, Player 2 is Os\n player_s = 'X'\n else:\n player_s = 'O'\n \n play = input(\"Player {}, your turn! Where would you like to place your {} (row, col): \".format(player_turn, player_s)) # Ask for player input\n \n if play == 'exit': # Player can exit at any time\n print(\"Play again soon!\")\n playing = False\n break\n \n col, row = play.split(',')\n col = int(col) # Get player-input column\n row.strip(' ')\n row = int(row) # Get player-input row\n \n if game[col-1][row-1] != 0: # If the player chooses a cell on the board that's already filled, let them try again\n print('\\nMust select an empty space which is not occupied by a player')\n continue\n else:\n game[col-1][row-1] = str(player_s) # Otherwise, place an X or O in the cell\n \n print(game[0], '\\n', game[1], '\\n', game[2]) # Print the board\n \n winner = check_winner(game) # Check for a winner\n \n if turn == 8 and winner == None: # If the board is full and there is no winner, end the game\n print(\"No winner. Play again soon!\")\n playing = False\n break\n \n turn += 1 # Increase the count of cells on the board that are filled to determine when the gameboard is full and the game ends\n \n if winner != None: # End the game when one of the players wins\n print(\"Player {} wins!\".format(player_turn))\n \n return\n \ndef max_of_three():\n '''\n Implement a function that takes as input three variables, and returns the largest of the three. Do this without using the Python max() function!\n '''\n \n print(\"This exercise finds the largest of three numbers in a list, without using the max() function.\")\n \n list = input(\"Give a list of 3 numbers, separated by commas: \")\n \n n1, n2, n3 = list.split(',') # Separate the numbers at the commas\n n1 = float(n1.strip(' '))\n n2 = float(n2.strip(' '))\n n3 = float(n3.strip(' '))\n \n max = n1 # Set initial maximum\n \n if n2 > max: # Go through other numbers and change max if greater than current max\n max = n2\n if n3 > max:\n max = n3\n\n print(str(max) + \" is the largest number in the list you gave.\")\n \n return max\n\ndef tic_tac_toe():\n '''\n This exercise is Part 4 of 4 of the Tic Tac Toe exercise series.\n\n The final step is to put all these three components together to make a two-player Tic Tac Toe game! Your challenge in this exercise is to use the functions from those previous exercises all together in the same program to make a two-player game that you can play with a friend.\n '''\n \n import tic_tac_toe # Made a nicer version in a separate python file, so import from there\n \n tic_tac_toe.main()\n \ndef pick_word():\n '''\n This exercise is Part 1 of 3 of the Hangman exercise series.\n \n In this exercise, the task is to write a function that picks a random word from a list of words from the SOWPODS dictionary. Download this file and save it in the same directory as your Python code. This file is Peter Norvig\u2019s compilation of the dictionary of words used in professional Scrabble tournaments. Each line in the file contains a single word.\n\n Hint: use the Python random library for picking a random word.\n '''\n \n print(\"This exercise opens the SOWPODS dictionary, reads the rows, and picks a random word from it.\\n\")\n \n import random\n \n words = []\n with open('ref_files/sowpods.txt','r') as f: # Open the SOWPODS dictionary txt files\n line = f.readline() # Read line\n while line:\n words.append(line) # Add to the list of words\n line = f.readline() # Read line\n \n random_word = random.choice(words) # Choose a random word\n \n #print(\"Here's your random word: \", random_word)\n \n return random_word\n \ndef letters():\n '''\n This exercise is Part 2 of 3 of the Hangman exercise series.\n\n In the game of Hangman, a clue word is given by the program that the player has to guess, letter by letter. The player guesses one letter at a time until the entire word has been guessed. (In the actual game, the player can only guess 6 letters incorrectly before losing).\n\n For this exercise, write the logic that asks a player to guess a letter and displays letters in the clue word that were guessed correctly. For now, let the player guess an infinite number of times until they get the entire word. As a bonus, keep track of the letters the player guessed and display a different message if the player tries to guess that letter again. Remember to stop the game when all the letters have been guessed correctly!\n '''\n \n print(\"This exercise is a game of hangman!\\n\")\n \n print(\"You can type 'exit' at any time to end the game.\")\n \n def print_hangman(wrong): # Graphics\n gallows = [[' ---- '],\n ['| | '],\n ['| '],\n ['| '],\n ['| '],\n ['| ']]\n \n if wrong > 0:\n gallows[2] = ['| O ']\n if wrong > 1:\n gallows[3] = ['| | ']\n if wrong > 2:\n gallows[3] = ['| /| ']\n if wrong > 3:\n gallows[3] = ['| /|\\\\']\n if wrong > 4:\n gallows[4] = ['| / ']\n if wrong > 5:\n gallows[4] = ['| / \\\\']\n \n for i in gallows:\n print(''.join(i))\n \n return\n \n random_word = list(pick_word().strip('\\n')) # Remove new line and make word into a list\n \n guessed = list('_'*len(random_word)) # Make blanks\n \n guessed_list = [] # List of guessed letters\n \n wrong = 0 # Count the number of wrong guesses to determine when the hangman is complete and the game is lost\n \n playing = True\n \n print(' '.join(guessed)) # Print out the blanks\n\n while playing:\n \n letter = input(\"Guess a letter: \") # Get player guess\n \n if letter == 'exit': # Player can exit at any time\n print(\"Play again soon!\")\n playing = False\n break\n \n if letter.upper() in guessed: # Don't allow a letter to be guessed twice\n letter = ''\n print(\"You already guessed that letter!\")\n continue\n \n elif letter.upper() in random_word: # Letter in word, fill in blank, and add to guessed letters list\n for idx, l in enumerate(random_word): # Iterate through all the letters in the word in case the letter is used multiple times\n if letter.upper() == l: # Get indices\n guessed[idx] = letter.upper() # Fill in blank corresponding to index\n guessed_list.append(letter.upper()) # Add letter to guessed letters list\n print(' '.join(guessed)) # Print out the blanks and letters\n print_hangman(wrong) # Show graphics\n print(\"\\n\\n\")\n \n else: # Letter not in word, add to guessed letters list and add to wrong guess count\n if letter.isalpha():\n guessed_list.append(letter.upper()) # Add letter to guessed letters list\n print(\"{} is not in the word!\\n\".format(letter.upper()))\n print(' '.join(guessed)) # Print out the blanks and letters\n wrong += 1 # Add to wrong guess count\n print_hangman(wrong) # Show graphics\n print(\"\\n\\n\")\n else:\n print(\"Input must be a single letter, not a number or symbol.\\n\")\n continue\n \n if wrong == 6: # The hangman is complete\n print(\"Uh oh! You ran out of tries. The word was {}.\".format(''.join(random_word)))\n playing = False\n break\n \n if '_' not in guessed:\n print(\"You got it!\")\n playing = False\n break\n \n \ndef hangman():\n '''\n This exercise is Part 3 of 3 of the Hangman exercise series.\n\n In this exercise, we will finish building Hangman. In the game of Hangman, the player only has 6 incorrect guesses (head, body, 2 legs, and 2 arms) before they lose the game.\n\n In Part 1, we loaded a random word list and picked a word from it. In Part 2, we wrote the logic for guessing the letter and displaying that information to the user. In this exercise, we have to put it all together and add logic for handling guesses.\n\n Copy your code from Parts 1 and 2 into a new file as a starting point. Now add the following features:\n\n Only let the user guess 6 times, and tell the user how many guesses they have left.\n Keep track of the letters the user guessed. If the user guesses a letter they already guessed, don\u2019t penalize them - let them guess again.\n '''\n \n print(\"This exercise is a game of hangman!\\n\")\n \n print(\"You can type 'exit' at any time to end the game.\")\n \n letters()\n \ndef birthday_dictionary(birthdays=None):\n '''\n This exercise is Part 1 of 4 of the birthday data exercise series.\n\n For this exercise, we will keep track of when our friend\u2019s birthdays are, and be able to find that information based on their name. Create a dictionary (in your file) of names and birthdays. When you run your program it should ask the user to enter a name, and return the birthday of that person back to them.\n '''\n \n print(\"This exercise defines a dictionary of birthdays and prints one birthday, picked by the user.\\n\")\n \n if birthdays == None: # Function can take an input dictionary, if not, define a new one\n birthdays = {\n \"Albert Einstein\": '03/14/1879',\n \"Benjamin Franklin\": '01/17/1706',\n \"Ada Lovelace\": '12/10/1815'\n }\n \n print(\"The dictionary currently contains the birthdays of: \")\n for name in birthdays: # Print names already in the dictionary\n print(name)\n \n name = input(\"\\nWho's birthday would you like to know?: \") # Ask which birthday to print\n \n if name in birthdays: # Print birthday\n print(\"{}'s birthday is {}.\".format(name, birthdays[name]))\n else:\n print(\"Sorry, I don't know {}'s birthday.\".format(name))\n \n return name, birthdays[name]\n\n \ndef birthday_json():\n '''\n This exercise is Part 2 of 4 of the birthday data exercise series.\n\n In the previous exercise we created a dictionary of famous scientists\u2019 birthdays. In this exercise, modify your program from Part 1 to load the birthday dictionary from a JSON file on disk, rather than having the dictionary defined in the program.\n\n Bonus: Ask the user for another scientist\u2019s name and birthday to add to the dictionary, and update the JSON file you have on disk with the scientist\u2019s name. If you run the program multiple times and keep adding new names, your JSON file should keep getting bigger and bigger.\n '''\n \n print(\"This exercise lets you add to a previously defined dictionary of birthdays.\\n\")\n \n import json\n\n birthdays = dict()\n \n with open('ref_files/birthdays.json', 'r') as f: # Open the birthday file\n birthdays = json.load(f) # Read data\n \n what_to_do = input(\"Do you want to ADD a birthday to the dictionary or GET a birthday already in the dictionary? (ADD or GET): \")\n \n if what_to_do.lower() == 'get': # Use function that lets you pick which birthday to print\n name, bday = birthday_dictionary(birthdays)\n elif what_to_do.lower() == 'add': # Add a new person and birthday to the file\n name = input(\"Who's birthday would you like to add?: \")\n bday = input(\"When is their birthday?: \")\n birthdays[name] = bday\n with open('ref_files/birthdays.json', 'w') as f: # Open the birthday file\n json.dump(birthdays, f) # Write the new dictionary with the added birthday\n \n return name, bday\n \ndef birthday_months():\n '''\n This exercise is Part 3 of 4 of the birthday data exercise series.\n\n In the previous exercise we saved information about famous scientists\u2019 names and birthdays to disk. In this exercise, load that JSON file from disk, extract the months of all the birthdays, and count how many scientists have a birthday in each month.\n '''\n \n print(\"This exercise gets the months from a previously defined dictionary of birthdays.\\n\")\n \n import json\n from collections import Counter\n \n month_to_string = { # Numbers corresponding to months\n 1: \"January\",\n 2: \"February\",\n 3: \"March\",\n 4: \"April\",\n 5: \"May\",\n 6: \"June\",\n 7: \"July\",\n 8: \"August\",\n 9: \"September\",\n 10: \"October\",\n 11: \"November\",\n 12: \"December\"\n }\n\n birthdays = dict()\n \n with open('ref_files/birthdays.json', 'r') as f: # Open the birthday file\n birthdays = json.load(f) # Read data\n \n months = []\n for name,bday in birthdays.items():\n month = int(bday.split('/')[0]) # Remove slashes between MM/DD/YYYY\n months.append(month_to_string[month]) # Append MM to list\n \n print(Counter(months)) # Use Counter to count how many birthdays are in each month\n \n return month_to_string, Counter(months)\n \ndef birthday_plots():\n '''\n This exercise is Part 4 of 4 of the birthday data exercise series.\n\n In the previous exercise we counted how many birthdays there are in each month in our dictionary of birthdays.\n\n In this exercise, use the bokeh Python library to plot a histogram of which months the scientists have birthdays in!\n '''\n \n from bokeh.plotting import figure, show, output_file\n import math\n \n print(\"This exercise makes a histogram of the months from a previously defined dictionary of birthdays.\\n\")\n \n month_to_string, data = birthday_months() # Use function that counts how many birthdays are in each month\n \n x = []\n y = []\n for key,value in data.items(): # Append months as numbers (x) and counts (y)\n x.append(key)\n y.append(value)\n \n output_file(\"birthday_hist.html\") # Name output file\n \n months = []\n for key,value in month_to_string.items(): # Append months as names\n months.append(value)\n \n p=figure(x_range=months, # Label x, y axes\n x_axis_label = 'Month',\n y_axis_label = 'Count')\n p.xaxis.major_label_orientation = math.pi/4 # Rotate tick labels\n p.vbar(x=x,top=y,width=0.75, color='blue') # Make vertical bar plot\n \n show(p) # Show plot, opens in browser\n\nif __name__ == '__main__':\n\n function_dict = {'1':char_input, '2':odd_even, '3':list_less_than, '4':divisors, '5':list_overlap,\n '6':string_list, '7':list_comp, '8':rps, '9':guessing_game, '10':list_overlap_v2,\n '11':check_prime, '12':first_last, '13':fib, '14':remove_duplicates, '15': reverse_word,\n '16':pass_gen, '17':read_web_page, '18':cows_bulls, '19':read_web_page_v2, '20':elem_search,\n '21':read_web_page_v3, '22':read_file, '23':file_overlap, '24':draw_gameboard, '25':guessing_game_v2,\n '26':check_tic_tac_toe, '27':tic_tac_toe_input, '28':max_of_three, '29': tic_tac_toe, '30':pick_word,\n '31':letters, '32':hangman, '33':birthday_dictionary, '34':birthday_json, '35':birthday_months,\n '36':birthday_plots} # What exercise corresponds to each function\n\n print(\"Go to practicepython.org to see which function number corresponds to which exercise.\")\n exercise = input(\"Which exercise do you want to run? (1-36): \")\n print(\"Exercise \" + exercise)\n\n function_dict[exercise]() # Runs exercise\n \n"} {"doc_id": "20675c7b4001586fb60744f267b006e9", "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# Type this number to stop\nGG = -100\n\n\ndef main():\n\t\"\"\"\n\tEnter numbers as temperature to calculate the highest, lowest and average temperature of the list\n\tfunction also counts the number of cold day(s), defined as temperature <16\n\t\"\"\"\n\tprint('StanCode \\\"Weather Master 4.0\"!')\n\tdata = float(input('temperature'))\n\tcount = 0\n\taverage = 0\n\tcold_days = 0\n\tif data == GG:\n\t\tprint('No temperature was entered')\n\telse:\n\t\tHighest_temperature = data\n\t\tLowest_temperature = data\n\t\tif data < 16:\n\t\t\tcold_days += 1\n\t\twhile True:\n\t\t\tdata = float(input('Next temperature: (or -100 to quit)?'))\n\t\t\tif data != GG:\n\t\t\t\taverage = (average * count + data)/(count + 1)\n\t\t\t\tcount += 1\n\t\t\t\tif data < 16:\n\t\t\t\t\tcold_days += 1\n\t\t\tif data >= Highest_temperature and data != GG:\n\t\t\t\tHighest_temperature = data\n\t\t\tif data <= Lowest_temperature and data != GG:\n\t\t\t\tLowest_temperature = data\n\t\t\tif data == GG:\n\t\t\t\tprint('Highest temperature= '+str(Highest_temperature))\n\t\t\t\tprint('Lowest temperature= '+str(Lowest_temperature))\n\t\t\t\tprint('Average= '+str(average))\n\t\t\t\tprint('Cold Day(s)= '+str(cold_days))\n\t\t\t\tbreak\n\n\n\n\n\n###### DO NOT EDIT CODE BELOW THIS LINE ######\n\nif __name__ == \"__main__\":\n\tmain()\n"} {"doc_id": "208d5b65402c5fb21c150511fa7c125c", "text": "#Dictoinary startercode\r\n#Opens a file. You can now look at each line in the file individually with a statement like \"for line in f:\r\nf = open(\"dictionary.txt\",\"r\")\r\n\r\nprint(\"Can your password survive a dictionary attack?\")\r\n\r\n#Take input from the keyboard, storing in the variable test_password\r\n#NOTE - You will have to use .strip() to strip whitespace and newlines from the file and passwords\r\ntest_password = input(\"Type in a trial password: \")\r\n\r\n#Write logic to see if the password is in the dictionary file below here:\r\n"} {"doc_id": "209eb02648f2c8dcb828a8533d75ede8", "text": "\"\"\"\nFile: anagram.py\nName: Serena Liu\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\ndictionary = []\n\n\ndef main():\n print(\"Welcome to stanCode \\\"Anagram Generator\\\" (or -1 to quit)\")\n global dictionary\n while True:\n word = str(input(\"Find anagrams for: \"))\n word = word.lower()\n if word == EXIT:\n break\n else:\n letters = []\n dictionary = read_dictionary()\n for i in range(len(word)):\n if word[i] not in letters:\n letters += word[i]\n sub_dict = []\n for w in dictionary:\n for letter in letters:\n if w.startswith(letter) and len(w) == len(word):\n sub_dict += [w]\n dictionary = sub_dict\n find_anagrams(word)\n\n\ndef find_anagrams(s):\n \"\"\"\n :param s: str, the word input by user\n \"\"\"\n anagrams = []\n num = [0]\n print('Searching...')\n helper(s, '', [], anagrams, num)\n print(str(num[0]) + ' anagrams: ' + str(anagrams))\n\n\ndef helper(s, current_lst, index_lst, anagrams, num):\n if len(current_lst) == len(s):\n if current_lst in dictionary and current_lst not in anagrams:\n anagrams += [current_lst]\n num[0] += 1\n print('Found: ' + current_lst)\n print('Searching...')\n else:\n for i in range(len(s)):\n if len(current_lst) >= 1 and has_prefix(current_lst) is False:\n break\n if i not in index_lst:\n index_lst.append(i)\n current_lst += s[i]\n\n helper(s, current_lst, index_lst, anagrams, num)\n\n index_lst.pop()\n current_lst = current_lst[:len(current_lst)-1]\n\n\ndef read_dictionary():\n d = []\n with open(FILE, 'r') as f:\n for line in f:\n d += [line.strip('\\n')]\n return d\n\n\ndef has_prefix(sub_s):\n \"\"\"\n :param sub_s: first letters of the word\n \"\"\"\n for word in dictionary:\n if word.startswith(sub_s):\n return True\n return False\n\n\nif __name__ == '__main__':\n main()\n"} {"doc_id": "215e273135487cb1bdec81b3d6fc385a", "text": "#!/usr/bin/env python3\n\"\"\"\nCreated on Sun Jan 14 14:54:16 2018\n\n@author: Swathi\n\"\"\"\n'''Write a password generator in Python. Be creative with how you generate passwords - strong passwords have a mix of \nlowercase letters, uppercase letters, numbers, and symbols. The passwords should be random, generating a new password \nevery time the user asks for a new password. Include your run-time code in a main method.\n\nAsk the user how strong they want their password to be. For weak passwords, pick a word or two from a list.\n'''\nimport random\nimport string\n\ndef generate_strong_password(length): \n splchars = '@&$!#'\n char = string.ascii_letters + string.digits + splchars\n pwd = random.sample(char, length)\n \n #Checking to confirm if the generated password has at least one digt and one special character\n if any(char.isdigit() for char in pwd) == False or any(char in splchars for char in pwd) == False:\n return generate_strong_password(length)\n else:\n return \"\".join(pwd)\n\n \ndef generate_weak_password():\n pwds = ['Itis1Apple', 'Password123', 'Ch@ngeme']\n return random.choice(pwds)\n\ndef main():\n while (True):\n usr_choice = input(\"Type 1 for strong password\\n2 for a weak password\\nq to Quit: \\n\")\n if usr_choice == '1':\n length = int(input(\"Enter the length of your password: \"))\n print (\"Password is: {}\".format(generate_strong_password(length)))\n elif usr_choice == '2':\n print (\"Password is: {}\".format(generate_weak_password()))\n elif usr_choice == 'q':\n print (\"Quitting. Bye !\\n\") \n break\n else:\n print (\"Incorrect input. Try again.\")\n \nif __name__ == '__main__':\n main()\n\n \n "} {"doc_id": "21667c425af7d716eefc1b6a5638ae1c", "text": "def chance_game():\n secret = \"1537\"\n anzahl = 0\n anzahlf = 0\n raten = \"\"\n # will contain the positions of found numbers, to make sure that one number isn't found twice\n found = \"\"\n while not raten == secret:\n raten = input(\"Guess the secret: \")\n for i in range(4):\n\n if secret[i] == raten[i]:\n anzahl = anzahl + 1\n # decreasing half correct counter in the case that a number was \"found\" at the wrong spot\n # but later found in the right spot -> right spot is more important that false spot\n if str(i) in found:\n anzahlf -= 1\n # storing number at this position was found\n found += str(i)\n\n # checking that this position wasn't found earlier\n elif (\n not -1 == secret.find(raten[i])\n and str(secret.find(raten[i])) not in found\n ):\n anzahlf = anzahlf + 1\n found += str(\n secret.find(raten[i])\n ) # storing number at this position was found\n\n if not anzahl == 0:\n print(str(anzahl) + \"characters are right.\")\n\n if not anzahlf == 0:\n print(str(anzahlf) + \" characters are right BUT in the wrong position!\")\n\n if anzahlf == 0 and anzahl == 0:\n print(\"All characters are wrong!\")\n\n anzahlf = 0\n anzahl = 0\n found = \"\"\n\n print(\"You guessed right!\")\n\n\nchance_game()"} {"doc_id": "217bd1097f52d000384f0cf6fdb15155", "text": "\"\"\"\r\nA python module for converting temperatures between celsius and fahrenheit\r\n\r\n\"\"\"\r\nimport numpy as np\r\n\r\ndef fahrenheit_to_celsius(fahrenheit_temp):\r\n \"\"\"Calculate celsius temperature from fahrenheit\r\n\r\n PARAMETERS\r\n ----------\r\n fahrenheit_temp : float\r\n A temperature in degrees\r\n\r\n RETURNS\r\n -------\r\n temperature : float\r\n \"\"\"\r\n\r\n # apply formula\r\n return (fahrenheit_temp - 32)*(5/9)\r\n\r\ndef celsius_to_fahrenheit(celsius_temp):\r\n \"\"\"Calculate fahrenheit temperature from celsius\r\n\r\n PARAMETERS\r\n ----------\r\n celsius_temp : float\r\n A temperature in degrees\r\n\r\n RETURNS\r\n -------\r\n temperature : float\r\n \"\"\"\r\n\r\n # apply formula\r\n return (celsius_temp * (9/5)) + 32\r\n"} {"doc_id": "2185f4814885f0762c5d8ed0698ee361", "text": "\"\"\"\nFile: hailstone.py\n-----------------------\nThis program should implement a console program that simulates\nthe execution of the Hailstone sequence, as defined by Douglas\nHofstadter. Output format should match what is shown in the sample\nrun in the Assignment 2 Handout.\n\"\"\"\n\n\ndef main():\n \"\"\"\n This function will simulate the execution of the Hailstone sequence.\n if n is odd, n -> 3n+1,\n if n is even, n -> n/2,\n until n = 1.\n \"\"\"\n print('This program computes Hailstone sequences.')\n print('')\n a = 0 # 'a' used to count how many steps happen.\n x = int(input('Enter a number: '))\n while True:\n if x == 1:\n print('It took '+str(a)+' steps to reach 1.')\n break\n elif x % 2 == 1: # x is odd.\n print(str(x)+' is odd, so I make 3n+1: '+str(3*x+1))\n x = 3*x+1\n else: # x is even.\n print(str(x)+' is even, so I take half: '+str(x//2))\n x = x//2\n a += 1\n\n\n###### DO NOT EDIT CODE BELOW THIS LINE ######\n\nif __name__ == \"__main__\":\n main()\n"} {"doc_id": "2194c0365db970b2e0ca50520651d8bb", "text": "# main.py\n# Small program that aims at helping humans doing the analysis of a given text.\n\n# The program prompts the user to enter the path to the directory where a given .txt UTF-8\n# encoded text file is located.\n# Please note that the user must enter the full path.\n\n# The program asks the name of the file. Please include the extension.\n\n# Afterwards, the program process the text file using the libraries re and nltk\n\n# The program prompts the user to split the text in a given number of parts. The program\n# will then proceed in looking up the context using the nltk library of a given list of\n# words. The user can be helped in choosing these words if she chooses to look at a list\n# of the 10 most frequent words present in the text.\n\n# The program prints the context of the words and ends.\n\nfrom __future__ import division\n\nimport nltk\nimport os\nimport nltk.corpus\nfrom nltk.corpus import stopwords\n\nimport re\nimport nltk.text\n\ndef main():\n print '------------------ PROGRAM START ---------------------'\n print ' Please enter the PATH to the directory where the text file is located.'\n path = raw_input()\n print ' Please enter the name of the text file. The text file must be encoded in UTF-8.'\n nom = raw_input()\n dir = os.path.dirname(path)\n text_file = os.path.join(dir, nom)\n raw = open(text_file).read()\n \n text = process_text(raw)\n\n print 'In how many parts do you want to split the text?'\n n = int(raw_input())\n\n print 'Begin analysis...'\n raw_input(\"Press Enter to continue...\")\n\n print 'Would you like to have help in finding the most frequent words? Type 1 for yes'\n answer = int(raw_input())\n\n if answer == 1:\n fdist = nltk.FreqDist(text)\n print 'Here is the list of the ten most common words:'\n print fdist.most_common(10)\n\n most_common_words(text = text, n = n)\n\n print 'Thank you for using our program! :)'\n\ndef process_text(raw):\n\n text = re.split(r'\\W+', raw)\n punct = [' ','!','?',';',':',',','.',]\n clean_text = [word for word in text if word not in punct]\n lower_text = [word.lower() for word in clean_text]\n stopword = stopwords.words(\"english\")\n\n text = [word for word in lower_text if word not in stopword]\n return text;\n\ndef most_common_words(text,n):\n\n stop = len(text)\n stop = stop/n\n stop = int(stop)\n\n print 'How many words do you want to look for their context?'\n number_word = int(raw_input())\n lookout_list = list()\n\n for i in range(1,number_word+1):\n print \"Please enter the next word to look for\"\n lookout_list.append(raw_input())\n\n for i in range(0,n):\n part_text = nltk.Text(word for word in text[((i*1)+1):i*stop])\n\n print \"Starting the next part analysis...\"\n enter = raw_input(\"Press Enter to continue.\")\n \n for j in range(0,number_word):\n print \"Looking for context of word\", lookout_list[j]\n context = nltk.text.ContextIndex([word.lower() for word in part_text])\n print 'The context is: '\n print context.similar_words(lookout_list[j]) \n\n print 'The analysis is over!' \n\nmain()\n\n\n\n\n"} {"doc_id": "21a2b75d0da2d9bdb433e4ebb78308c1", "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\ndef main():\n\t\"\"\"\n\tEnable the user to input the temperatures. If the user input -100, it will stop and show\n\tthe highest, the lowest and average temperature. Eventually, it'll show the days that under 16 degrees.\n\t\"\"\"\n\tintro()\n\tTemperature()\n\n\ndef intro():\n\tprint(\"stanCode \\\"Weather Master 4.0\\\"!\")\n\ndef Temperature():\n\tinput_list=[] # create a list for input\n\tn=int(input(\"Next temperature(or-100 to quit)?\"))\n\tinput_list.append(n) # append the first input\n\n\tif n==(-100):\n\t\tprint(\"No temperatures were entered\")\n\twhile n >(-100):\n\t\tn=int(input(\"Next temperature(or -100 to quit)?\"))\n\t\tinput_list.append(n) # append the inputs\n\n\tinput_list_new=input_list[0:(len(input_list)-1)] # the list which -100 is excluded\n\n\tprint(\"Highest temperature:\"+str(max(input_list_new))) # highest temperature\n\tprint(\"Lowest temperature:\"+str(min(input_list_new))) # lowest temperature\n\n\tsum=0\n\ttime = 0\n\tfor i in range(len(input_list_new)):\n\t\tsum+=input_list_new[i] # average temperature\n\t\tif input_list_new[i]<16: # find cold day(s)\n\t\t\ttime+=1\n\tprint(\"Average:\"+str(sum/len(input_list_new)))\n\tprint(str(time) + \" cold day(s)\")\n\n\n\n\n\n\n\n\n###### DO NOT EDIT CODE BELOW THIS LINE ######\n\nif __name__ == \"__main__\":\n\tmain()\n"} {"doc_id": "21ce54ae426a55ca39a3e02f39fb0ea5", "text": "from typing import List, Tuple\nfrom math import floor\nfrom random import shuffle, seed\n\n\ndef swap(original: List[str], orig: int, dest: int) -> str:\n \"\"\"Swaps the element from position orig to destiny from the puzzle\n\n Parameters\n ----------\n original : List[str]\n A linear representation of a 8-puzzle board\n orig : int\n Origin position\n dest : int\n Destiny position\n\n Returns\n -------\n str\n The new board after the swap of the elements\n \"\"\"\n action = original.copy()\n action[orig], action[dest] = action[dest], action[orig]\n return \"\".join(action)\n\n\ndef pretty(states: List[str]) -> None:\n \"\"\"Pretty print of one or more 8-puzzle boards\n\n Parameters\n ----------\n states : List[str]\n List of linear representations of 8-puzzle boards\n \"\"\"\n for state in states:\n print(state[:3])\n print(state[3:6])\n print(state[6:])\n print()\n\n\ndef possible_plays(state: str) -> List[int]:\n \"\"\"Return possible plays from a given state\n\n Assuming the actions 0 to 3 to be top, right, bottom, left action, where\n the blank piece is moved to the given direction, this function returns the\n possible actions of a given state.\n\n Parameters\n ----------\n state : str\n A linear representation of a 8-puzzle board\n\n Returns\n -------\n List[int]\n List of possible actions from the given puzzle state.\n\n Raises\n ------\n ValueError\n It raises an error if there is no blank piece to move\n \"\"\"\n states: List[Tuple[str, int]] = []\n\n pos_1d = state.find(\" \")\n if pos_1d == -1:\n raise ValueError(\"There should be a space block\")\n\n pos = (pos_1d % 3, floor(pos_1d / 3))\n if pos[1] > 0:\n states.append(0)\n if pos[0] < 2:\n states.append(1)\n if pos[1] < 2:\n states.append(2)\n if pos[0] > 0:\n states.append(3)\n\n return states\n\n\ndef play(state: str, action: int) -> str:\n \"\"\"It plays the given action with the given state\n\n The action being one of these: up, right, down, left (0, 1, 2, 3) is applied\n to the puzzle, returning the resulting state, or raising an error if action\n is invalid.\n\n Parameters\n ----------\n state : str\n A linear representation of a 8-puzzle board\n action : int\n Either up, right, down or left (respectively 0, 1, 2, 3)\n\n Returns\n -------\n str\n Resulting linear representation of a 8-puzzle board\n\n Raises\n ------\n ValueError\n [description]\n \"\"\"\n list_state = list(state)\n pos_1d = state.find(\" \")\n\n if action == 0 and pos_1d >= 3:\n return swap(list_state, pos_1d, pos_1d - 3)\n elif action == 1 and pos_1d <= 7:\n return swap(list_state, pos_1d, pos_1d + 1)\n elif action == 2 and pos_1d <= 6:\n return swap(list_state, pos_1d, pos_1d + 3)\n elif action == 3 and pos_1d >= 1:\n return swap(list_state, pos_1d, pos_1d - 1)\n\n raise ValueError(f\"Unknown or Invalid action {action} on {state}\")\n\n\ndef states_from(state: str) -> List[str]:\n \"\"\"Generates list of possible states from original state for the 8-puzzle\n game.\n\n Parameters\n ----------\n state : str\n A linear representation of a 8-puzzle board\n\n Returns\n -------\n List[str]\n List of possible states from actions on the given puzzle state.\n \"\"\"\n plays = possible_plays(state)\n return [play(state, action) for action in plays]\n\n\ndef action_of(origin: str, destination: str) -> int:\n \"\"\"Finds which action was taken from origin to destination.\n\n If the states origin and destination are separated by one action, it returns\n the numeric value of the action taken (0 = up, 1 = right, 2 = down, 3 = left).\n It returns -1 if they are separated by more than one action.\n\n Parameters\n ----------\n origin : str\n A linear representation of a 8-puzzle board, original state\n destination : str\n A linear representation of a 8-puzzle board, the resulting state\n\n Returns\n -------\n int\n Action taken from origin to destination, or -1 if there isn't a single\n action between the states\n \"\"\"\n if sum([i == j for (i, j) in zip(list(origin), list(destination))]) == 7:\n pos_orig = origin.find(\" \")\n pos_dest = destination.find(\" \")\n\n diff = pos_dest - pos_orig\n\n if diff == 3:\n return 2\n elif diff == -3:\n return 0\n elif diff == 1:\n return 1\n elif diff == -1:\n return 3\n return -1\n\n\ndef is_solvable(state: str) -> bool:\n \"\"\"Returns whether the puzzle is solvable\n\n The 8-puzzle game is solvable if and only if the parity of the inversion\n count is even, where one inversion is counted for each pair of elements\n in the linear representation of a 8-puzzle board where the leftmost has\n a bigger value than the rightmost being compared.\n\n Parameters\n ----------\n state : str\n A linear representation of a 8-puzzle board\n\n Returns\n -------\n bool\n Whether it's solvable or not\n \"\"\"\n list_state = list(state)\n inversions = 0\n for i in range(9):\n for j in range(i + 1, 9):\n if (\n list_state[i] != \" \"\n and list_state[j] != \" \"\n and list_state[i] > list_state[j]\n ):\n inversions = inversions + 1\n return inversions % 2 == 0\n\n\ndef generate_solvable_state() -> str:\n \"\"\"It generates a solvable 8-puzzle state\n\n Returns\n -------\n str\n A solvable linear representation of a 8-puzzle board\n \"\"\"\n seed()\n\n puzzle = [\"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \" \"]\n solvable = False\n\n while not solvable:\n shuffle(puzzle)\n solvable = is_solvable(\"\".join(puzzle))\n\n return \"\".join(puzzle)\n"} {"doc_id": "21f9690c658c2e1696459b32e8b92252", "text": "'''\nCoin Change\n\nYou are given coins of different denominations and a total amount of money amount.\nWrite a function to compute the fewest number of coins that you need to make up that amount.\nIf that amount of money cannot be made up by any combination of the coins, return -1.\n\nInput: coins = [1, 2, 5], amount = 11\nOutput: 3\n\nInput: coins = [2], amount = 3\nOutput: -1\n\n=========================================\nDynamic programming solution 1\n Time Complexity: O(A*C) , A = amount, C = coins\n Space Complexity: O(A)\nDynamic programming solution 2 (don't need the whole array, just use modulo to iterate through the partial array)\n Time Complexity: O(A*C) , A = amount, C = coins\n Space Complexity: O(maxCoin)\n'''\n\n\n##############\n# Solution 1 #\n##############\n\ndef coin_change_1(coins, amount):\n if amount == 0:\n return 0\n if len(coins) == 0:\n return -1\n\n max_value = amount + 1 # use this instead of math.inf\n dp = [max_value for i in range(max_value)]\n dp[0] = 0\n\n for i in range(1, max_value):\n for c in coins:\n if c <= i:\n # search on previous positions for min coins needed\n dp[i] = min(dp[i], dp[i - c] + 1)\n\n if (dp[amount] == max_value):\n return -1\n return dp[amount]\n\n\n##############\n# Solution 2 #\n##############\n\ndef coin_change_2(coins, amount):\n if amount == 0:\n return 0\n if len(coins) == 0:\n return -1\n\n max_value = amount + 1\n max_coin = min(max_value, max(coins) + 1)\n dp = [max_value for i in range(max_coin)]\n dp[0] = 0\n\n for i in range(1, max_value):\n i_mod = i % max_coin\n dp[i_mod] = max_value # reset current position\n\n for c in coins:\n if c <= i:\n # search on previous positions for min coins needed\n dp[i_mod] = min(dp[i_mod], dp[(i - c) % max_coin] + 1)\n\n if (dp[amount % max_coin] == max_value):\n return -1\n return dp[amount % max_coin]\n\n\n###########\n# Testing #\n###########\n\n# Test 1\n# Correct result => 3\ncoins = [1, 2, 5]\namount = 11\nprint(coin_change_1(coins, amount))\nprint(coin_change_2(coins, amount))\n\n# Test 2\n# Correct result => -1\ncoins = [2]\namount = 3\nprint(coin_change_1(coins, amount))\nprint(coin_change_2(coins, amount))\n"} {"doc_id": "224e96702248dfa5f6dc3318ad4e65e1", "text": " \"\"\"\nFile: complement.py\nName: Andrew Chao\n----------------------------\nThis program uses string manipulation to\ntackle a real world problem - finding the\ncomplement strand of a DNA sequence.\nTHe program asks uses for a DNA sequence as\na python string that is case-insensitive.\nYour job is to output the complement of it.\n\"\"\"\n\n\ndef main():\n \"\"\"\n This program allows users to transfer the original sequence to its complement one.\n \"\"\"\n sequence = input('Please give me a DNA strand and I\\'ll find the complement: ')\n\n # Case-insensitive: reassign the sequence by making it to the upper-case one\n upper_sequence = sequence.upper()\n\n ans = build_complement(upper_sequence)\n print('The complement of ' + sequence + ' is ' + ans)\n\n\ndef build_complement(input_sequence):\n \"\"\"\n :param input_sequence: str, allow users to input a sequence that is going to\n be built complement.\n :return: str, this function will return a sequence that is the complement of\n the input sequence.\n \"\"\"\n output_sequence = ''\n for s in input_sequence:\n if s == 'A':\n output_sequence += 'T'\n elif s == 'T':\n output_sequence += 'A'\n elif s == 'G':\n output_sequence += 'C'\n else:\n output_sequence += 'G'\n\n return output_sequence\n\n\n###### DO NOT EDIT CODE BELOW THIS LINE ######\nif __name__ == '__main__':\n main()\n"} {"doc_id": "227be381f4be03b33d42196fa7cd0645", "text": "\"\"\"\nto choose random char you'll need import the random module\n\"\"\"\nimport random\n\"\"\"\nnow u will choose a random char from the list and store it in a variable called\npassword\"\"\"\nchars= 'abcdefghijklmnopqrstuvwxyz@#$^&ABCDEFGHI1234567890'\n# enter the size of password as urs requriment\nlength=input('Enter the size of password:')\n#use int() to turn the user's input into a whole number\nlength=int(length)\n# add this code to create 3 passwords\nfor p in range(3):\n password=''\n for c in range(length):\n password +=random.choice(chars)\n print(password)\n\n"} {"doc_id": "2289e0db859d738ea673b5535c886cf4", "text": "\"\"\"\nGiven a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.\n\nExample 1:\n\nInput: \"babad\"\nOutput: \"bab\"\nNote: \"aba\" is also a valid answer.\nExample 2:\n\nInput: \"cbbd\"\nOutput: \"bb\"\n\"\"\"\n\n\nclass Solution:\n @staticmethod\n def longest_palindrome(s: str) -> str:\n \"\"\"[summary]\n \n Parameters\n ----------\n s : str\n [description]\n \n Returns\n -------\n str\n [description]\n \"\"\"\n if s is None or len(s) < 2:\n return s\n result = s[:1]\n for i in range(len(s)):\n l1 = self.extend_the_center(s, i, i)\n l2 = self.extend_the_center(s, i, i + 1)\n l = l1 if len(l1) > len(l2) else l2\n if len(l) > len(result):\n result = l\n return result\n\n @staticmethod\n def extend_the_center(s: str, left: int, right: int) -> int:\n \"\"\"Get longest length of palindrome expanding from current left and right indices\n \n Parameters\n ----------\n s : str\n [description]\n left : int\n [description]\n right : int\n [description]\n \n Returns\n -------\n int\n length of longest palindrome from left and right\n \"\"\"\n while left >= 0 and right < len(s) and s[left] == s[right]:\n left -= 1\n right += 1\n return s[left+1:right]\n\n @staticmethod\n def longest_palindrome_2(s: str) -> str:\n \"\"\"Dynamic programming implementation\n \n Parameters\n ----------\n s : str\n [description]\n \n Returns\n -------\n str\n [description]\n \"\"\"\n length = len(s)\n\n # dp[i][j] = True if s[i] -> s[j] is a palindrome otherwise False\n dp = [[False for _ in range(length)] for _ in range(length)]\n dp[length-1][length-1] = True\n for cell in range(length - 1):\n dp[cell][cell] = True\n dp[cell][cell+1] = s[cell] == s[cell+1]\n\n longestLength = 1\n\n startIndex = endIndex = 0\n\n for i in range(length):\n for j in range(i+1, length):\n if s[i] == s[j] and dp[i+1][j-1] is True:\n dp[i][j] = True\n newPalindromeLength = j - i + 1\n if longestLength < newPalindromeLength:\n startIndex, endIndex = i, j\n longestLength = newPalindromeLength\n \n return s[startIndex:endIndex+1]"} {"doc_id": "22b14950d6d4164c84a20d852dbb6098", "text": "#!/usr/local/bin/python3.9\n\n# Filnamn: \u00f6vn 14.6, sid. 38 - datorn gissar ett tal.py\n\n# S\u00f6kning\n# Programmerings\u00f6vningar till kapitel 14\n\n# Programmet l\u00e5ter dig t\u00e4nka p\u00e5 ett tal mellan 1 och 99. \n# F\u00f6rsta g\u00e5ngen gissar datorn p\u00e5 talet i mitten utifr\u00e5n det givna intervallet 1 \n# till 99. Dvs. talet 50. Svarar anv\u00e4ndaren at det \u00e4r f\u00f6r h\u00f6gt \n# gissar dator p\u00e5 nedre halvans mitt, dvs 25, sedan tillfr\u00e5gas anv\u00e4ndaren igen.\n# \n\n# Import av modul\nfrom random import randint\n\n# Funktionsdefinitioner\ndef binGissning(ngr\u00e4ns, \u00f6gr\u00e4ns):\n return (\u00f6gr\u00e4ns - ngr\u00e4ns) // 2\n\n# Huvudprogram\ndef main():\n\n # Variabeldeklarationer och initieringar\n # Talet som datorn tror m\u00e4nniskan t\u00e4nker p\u00e5\n talM\u00e4nniska = 0\n \n # Antal gissningar som datorn gjort\n gissningar = 1\n\n # Talgr\u00e4nser\n nedre = 1\n \u00f6vre = 100\n\n # Svar som ska anges av anv\u00e4ndaren\n svar = ''\n # Skriv ut en programrubrik\n print('Jag gissar vilket tal du t\u00e4nker p\u00e5') \n print('==================================\\n')\n print('F\u00e5r jag be dig att t\u00e4nka p\u00e5 ett tal mellan 1 och 100.')\n\n # Gissa i mitten av talgr\u00e4nserna\n talM\u00e4nniska = binGissning(nedre, \u00f6vre)\n \n # Skriv ut gissningen\n print('Jag gissar att du t\u00e4nker p\u00e5 talet ' + str(talM\u00e4nniska) + '.')\n\n # Fr\u00e5ga anv\u00e4ndaren om det \u00e4r r\u00e4tt, f\u00f6r h\u00f6gt eller l\u00e5gt \n svar = input('\u00c4r det [r]\u00e4tt, f\u00f6r [h]\u00f6gt eller [l]\u00e5gt: ')\n while svar not in ['r', 'r\u00e4tt']:\n if svar in ['h', 'h\u00f6gt']:\n \u00f6vre = talM\u00e4nniska - 1\n oldtal = talM\u00e4nniska\n talM\u00e4nniska -= binGissning(nedre, \u00f6vre)\n if oldtal == talM\u00e4nniska:\n talM\u00e4nniska -= 1\n\n if svar in ['l', 'l\u00e5gt']:\n nedre = talM\u00e4nniska + 1\n oldtal = talM\u00e4nniska\n talM\u00e4nniska += binGissning(nedre, \u00f6vre)\n if oldtal == talM\u00e4nniska:\n talM\u00e4nniska += 1\n\n # \u00d6ka antal gissningar\n gissningar += 1\n\n # Skriv ut gissningen\n print('Jag gissar att du t\u00e4nker p\u00e5 talet ' + str(talM\u00e4nniska) + '.')\n\n # Och fr\u00e5ga anv\u00e4ndaren \u00e5terigen om det \u00e4r r\u00e4tt, f\u00f6r h\u00f6gt eller l\u00e5gt\n svar = input('\u00c4r det [r]\u00e4tt, f\u00f6r [h]\u00f6gt eller [l]\u00e5gt: ')\n\n print('Jag gissat r\u00e4tt efter ' + str(gissningar) + ' f\u00f6rs\u00f6k.')\n \n# Huvudprogram anropas \nmain()"} {"doc_id": "22c5a3d23d5fa44857fd2e9ef36333fb", "text": "\"\"\"Password generator allows you to generate a random password of length N.\"\"\"\nfrom random import choice, shuffle\nfrom string import ascii_letters, digits, punctuation\n\n\ndef password_generator(length=8):\n \"\"\"\n >>> len(password_generator())\n 8\n >>> len(password_generator(length=16))\n 16\n >>> len(password_generator(257))\n 257\n >>> len(password_generator(length=0))\n 0\n >>> len(password_generator(-1))\n 0\n \"\"\"\n chars = tuple(ascii_letters) + tuple(digits) + tuple(punctuation)\n return \"\".join(choice(chars) for x in range(length))\n\n\n# ALTERNATIVE METHODS\n# ctbi= characters that must be in password\n# i= how many letters or characters the password length will be\ndef alternative_password_generator(ctbi, i):\n # Password generator = full boot with random_number, random_letters, and\n # random_character FUNCTIONS\n # Put your code here...\n i = i - len(ctbi)\n quotient = int(i / 3)\n remainder = i % 3\n # chars = ctbi + random_letters(ascii_letters, i / 3 + remainder) +\n # random_number(digits, i / 3) + random_characters(punctuation, i / 3)\n chars = (\n ctbi\n + random(ascii_letters, quotient + remainder)\n + random(digits, quotient)\n + random(punctuation, quotient)\n )\n chars = list(chars)\n shuffle(chars)\n return \"\".join(chars)\n\n # random is a generalised function for letters, characters and numbers\n\n\ndef random(ctbi, i):\n return \"\".join(choice(ctbi) for x in range(i))\n\n\ndef random_number(ctbi, i):\n pass # Put your code here...\n\n\ndef random_letters(ctbi, i):\n pass # Put your code here...\n\n\ndef random_characters(ctbi, i):\n pass # Put your code here...\n\n\ndef main():\n length = int(input(\"Please indicate the max length of your password: \").strip())\n ctbi = input(\n \"Please indicate the characters that must be in your password: \"\n ).strip()\n print(\"Password generated:\", password_generator(length))\n print(\n \"Alternative Password generated:\", alternative_password_generator(ctbi, length)\n )\n print(\"[If you are thinking of using this passsword, You better save it.]\")\n\n\nif __name__ == \"__main__\":\n main()\n"} {"doc_id": "22c681c2edd864d7fc2271d6d5db355d", "text": "#!/usr/bin/env python3\n\n# Remember quadratic equations?\n# See\n# https://www.khanacademy.org/math/algebra/quadratics/solving-quadratics-using-the-quadratic-formula/a/discriminant-review\n# to refresh your knowledge.\n\n\n# 1. Assign values 6, 10, -1 to variables a, b, and c.\nXXX # <-- your code goes here\n\n\n# 2. Calculate the discriminant.\nD = XXX\n\n\n# 3. Define the `discriminant` function, whose 3 real arguments are\n# coefficients of a quadratic equation.\ndef discriminant():\n pass\n\n\n# ---------- Ignore the rest of the file ----------\nassert(a + b + c == 15)\nassert(D == 124)\nassert(discriminant(a, b, c) == D)\nassert(discriminant(1, 2, 3) == -8)\nprint('You did it! \\o/')\n"} {"doc_id": "22d64e77028aafadac1ec1fd28b2d6c9", "text": "\"\"\"\nFile: weather_master.py\nName:\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\nQUIT = -1\n\n\ndef main():\n\t\"\"\"\n\tinput each day's temperature and output maximum, minimum, average and how many cold days\n\t\"\"\"\n\tprint('stanCode \\\"Weather Master 4.0\\\"!')\n\tfirst_temperature = int(input('Next temperature: (or ' + str(QUIT) + ' to quit)? '))\n\tif first_temperature == QUIT:\n\t\tprint('No temperatures were entered.')\n\tif first_temperature != QUIT:\n\t\tif first_temperature < 16:\n\t\t\t# if the temperature is lower than 16 (but don't equal 16 and str(QUIT) then cold_day +1.\n\t\t\tcold_day = 1\n\t\telse:\n\t\t\tcold_day = 0\n\t\tcount = 1\n\t\ttotal = first_temperature\n\t\tmaximum = first_temperature\n\t\tminimum = first_temperature\n\t\twhile True:\n\t\t\t# compare the temperature with QUIT, maximum and minimum\n\t\t\ttemperature = int(input('Next temperature: (or ' + str(QUIT) + ' to quit)? '))\n\t\t\tif temperature == QUIT:\n\t\t\t\tbreak\n\t\t\tif temperature != QUIT:\n\t\t\t\tif temperature < 16:\n\t\t\t\t\tcold_day += 1\n\t\t\t\tif temperature > maximum:\n\t\t\t\t\tmaximum = temperature\n\t\t\t\tif temperature < minimum:\n\t\t\t\t\tminimum = temperature\n\t\t\t\tcount += 1\n\t\t\t\ttotal += temperature\n\t\tprint('Highest temperature = ' + str(maximum))\n\t\tprint('Lowest temperature = ' + str(minimum))\n\t\tprint('Average = ' + str(float(total/count)))\n\t\tprint(str(cold_day) + ' cold day(s)')\n\n\n\n\n\n\n\n###### DO NOT EDIT CODE BELOW THIS LINE ######\n\nif __name__ == \"__main__\":\n\tmain()\n"} {"doc_id": "23115b1ac6883ac62e1d526a07487577", "text": "#!/usr/bin/env python\n# coding: utf-8\n\n# Making multipanel plots with matplotlib\n\n# First, we import numpy and matplotlib as usual\n\n# In[5]:\n\n\nget_ipython().run_line_magic('matplotlib', 'inline')\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\n# Then we define an aray of angle, and their sines and cosines using numpy. This time we will use linspace\n\n# In[7]:\n\n\nx = np.linspace(0,2*np.pi,100)\nprint(x[-1],2*np.pi)\n\ny = np.sin(x)\nz = np.cos(x)\nw = np.sin(4*x)\nv = np.cos(4*x)\n\n\n# Now lets make a two panel plot\n\n# In[13]:\n\n\n#call sublots to genrate a multipanel figure. This means 1 row, 2 colums of figure\nf, axarr = plt.subplots(1,2)\n\n#treat axarr as an array, from left to right\n\n#first panel\naxarr[0].plot(x, y)\naxarr[0].set_xlabel('x')\naxarr[0].set_ylabel('sin(x)')\naxarr[0].set_title(r'$\\sin(x)$')\n#second panel\naxarr[1].plot(x, z)\naxarr[1].set_xlabel('x')\naxarr[1].set_ylabel('cos(x)')\naxarr[1].set_title(r'$\\cos(x)$')\n\n#add more space between the figures\nf.subplots_adjust(wspace=0.4)\n\n#fix the axis ratio\n#here are two possible options\naxarr[0].set_aspect('equal') #make the ratio of the tick units equal, a bit counter intuitive\naxarr[1].set_aspect(np.pi) #make a square by setting the aspect to be the ratio of the tick unit range\n\n\n# In[ ]:\n\n\n\n\n"} {"doc_id": "234add22575bc7a9b81a8d28627ee9c7", "text": "# -*- coding: utf-8 -*-\n\ndef otra():\n\t\n\tprint('Ejecutamos la funcion otra')\n\t\n\tdef interna_otra():\n\t\tprint('Ejecutamos la funcion interna_otra')\n\t\treturn 3\n\t\n\treturn interna_otra\n\t\ndef numero():\n\treturn 1\n\ndef run():\n\tfuncion_run = 'Soy funci\u00f3n run'\n\tprint('Soy imprimir dentro de run, Ejecutamos la funci\u00f3n run')\n\treturn funcion_run\n\nif __name__ == '__main__':\n\tprint('------run()--------')\n\trun()\n\tprint('------run--------')\n\tprint(run)\n\tprint('''\n\t\trun()-> Es la ejecuci\u00f3n de la funci\u00f3n y entrega un retorno, un resultado\n\t\trun -> Es la funci\u00f3n en s\u00ed, el objeto funci\u00f3n, su c\u00f3digo\n\t\t''')\n\tprint('========= run = otra () ================')\n\trun = otra()\n\tprint('------run()--------')\n\trun()\n\tprint('------run--------')\n\tprint(run)\n\tprint('-----otra()---------')\n\totra()\n\tprint('-----otra---------')\n\tprint(otra)\n\tprint('''\n\t\tAl asignar run = otra() ,\n\t\tSe ejecuta otra(), por lo que ejecuta su c\u00f3digo interno y el resultado (que en este caso es una funcion [interna_otra]) es almacenada en run.\n\t\tComo run es otra funci\u00f3n, se le puede asignar otra funcion\n\n\t\tPor lo tanto, al ejecutar:\n\t\trun() -> Ejecutra la funci\u00f3n run(), que en este caso ahora es la funcion interna_otra, por lo que en realidad se est\u00e1 ejecutando interna_otra()\n\t\t\t\tLo que da como muestra: Ejecutamos la funcion interna_otra y retorna 3, que en este caso no es alamcenado ni impreso\n\t\t\n\t\trun -> Es la funci\u00f3n interna_otra en s\u00ed\n\n\t\totra() -> Ejecuta la funci\u00f3n otra(), por lo que imprime: Ejecutamos la funci\u00f3n otra, y retorna la funci\u00f3n interna_otra, que en este caso no es alamcenado ni ejecutado\n\n\t\totra -> Es la funci\u00f3n otra en s\u00ed, el objeto funci\u00f3n\n\n\t\t\n\t\t''')\n\tprint('======== run = otra =================')\n\trun = otra\n\tprint('-----otra()---------')\n\totra()\n\tprint('------run()--------')\n\trun()\n\tprint('------run--------')\n\tprint(run)\n\tprint('------otra--------')\n\tprint(otra)\n\tprint('''\n\t\t\tAl asignar run = otra\n\t\t\tAsignamos la funci\u00f3n otra a run, como las dos son funciones run ahora es igual a otra\n\t\t\t\n\t\t\totra() -> Ejecuta la funci\u00f3n otra(), por lo que imprime: Ejecutamos la funci\u00f3n otra, y retorna la funci\u00f3n interna_otra, que en este caso no es alamcenado ni ejecutado\n\t\t\t\n\t\t\trun() -> como run = otra, Ejecuta la funci\u00f3n otra(), por lo que imprime: Ejecutamos la funci\u00f3n otra\n\t\t\t\n\t\t\trun -> como run = otra, Es la funci\u00f3n otra en s\u00ed\n\n\t\t\totra -> Es la funci\u00f3n otra en s\u00ed, el objeto funci\u00f3n\n\t\t''')\n\n\t"} {"doc_id": "2372ab1b9e14523f3e5a71d8a772a5ee", "text": "\"\"\"\nstring_math.py\nA sample repository for the MOLSSI workshop at UF.\n\nSome string functions.\n\"\"\"\n\n\ndef title_case(sentence):\n \"\"\"\n make the string title cased\n\n Parameters\n ----------\n sentence : string\n The string to make the title case of\n\n Returns\n ----------\n ret : string\n Title cased string\n\n Example\n ----------\n >>> title_case('ThiS is A StrinG')\n 'This Is A String'\n \"\"\"\n\n # check the input is string\n if not isinstance(sentence, str):\n raise TypeError('Invalid input %s - Input must be type string' % (sentence))\n\n if len(sentence) == 0:\n raise ValueError('Cannot apply title_case to empty string')\n\n ret = sentence[0].upper()\n\n for i in range(1, len(sentence)):\n if sentence[i - 1] == ' ':\n ret += sentence[i].upper()\n\n else:\n ret += sentence[i].lower()\n\n return ret\n"} {"doc_id": "2378ab235b413c94f887db8cbe9f9628", "text": "#INVARIANTS\n\n# an empty linked list always looks like (root=EmptyValue, rest=None)\n# an non-empty linked list always looks like (root=, rest=)\n# guarantees no 'NoneType' erros with recursive methods.\n\n\n# Empty Trees: (root=EmptyValue, subtrees=[])\n# No empty trees in subtrees!\n\n# -------------------------------------\n\n# searching for an item:\n# In a list? [5, 4, 3, 10, -1, 0]\n# In a tree?\n# 5\n# / \\ \\\n# 4 -1 0\n# / \\\n# 3 10\n\n# worst case: linear time\n# but searching in a sorted list is more efficient in general (half!)\n\n# what if we search in a 'sorted tree'?\n\n#BINARY SEARCH TREE\n\n# binary: each node has at most 2 subtrees (i.e. it could have 1 subtree only or none at all)\n\n# class BinarySearchTree:\n# - self.root (object)\n# - self.left (BinarySearchTree)\n# - self.right (BinarySearchTree)\n\n# BST Property: each item is >= all items in left subtree, < all items in right subtree.\n\n# Warning: this must be true for all items, not just the root! (Recursive)\n\n# 10\n# / \\\n# 3 20\n# / \\ / \\\n# 1 4 15 30\n# / \\ \\\n# 4 6 40\n# this is a BST\n\nclass EmptyValue:\n pass\n\nclass BinarySearchTree:\n \n # Attributes:\n # - root (object): the root value stored in the BST, or EmptyValue if the tree is empty\n # - left (BinarySearchTree): the left subtree, or None if the ENTIRE tree is empty\n # - right (BinarySearchTree): the right subtree, or None if the ENTIRE tree is empty\n \n def __init__(self, root=EmptyValue):\n self.root = root\n if self.is_empty():\n self.left = None\n self.right = None\n else:\n self.left = BinarySearchTree()\n self.right = BianrySearchTree()\n \n def is_empty(self):\n return self.root is EmptyValue\n \n def print_tree(self, depth=0):\n if not self.is_empty():\n print(depth * ' ' + str(self.root))\n self.left.print_tree(depth + 1)\n self.right.print_tree(depth + 1)\n \n def __contains__(self, item):\n # the fact that you only need to check one tree each time comes from the property of BST\n if self.is_empty():\n return False\n elif item == self.root:\n return True\n elif item < self.root:\n return self.left.__contains__(item)\n else:\n return self.right.__contains__(item) # or 'return item in self.right', because __contains__ is a special form of 'in'\n"} {"doc_id": "239d5b8ff23876fad599cbbc95ac813a", "text": "# Iterative binary search\ndef binarySearchIterative(arr, num):\n low = 0\n high = len(arr) - 1\n \n while low <= high:\n mid = int((low + high) / 2)\n\n if num < arr[mid]:\n high = mid - 1\n elif num > arr[mid]:\n low = mid + 1\n else:\n return mid\n \n return -1\n\n# Recursive binary search\ndef binarySearchRecursive(arr, num):\n return binarySearchRecursiveAux(arr, num, 0, len(arr) - 1)\n\n# Recursive binary search helper\ndef binarySearchRecursiveAux(arr, num, low, high):\n mid = int((low + high) / 2)\n\n if low > high:\n return -1\n \n if num < arr[mid]:\n return binarySearchRecursiveAux(arr, num, low, mid - 1)\n elif num > arr[mid]:\n return binarySearchRecursiveAux(arr, num, mid + 1, high)\n else:\n return mid\n \n\n# ---------------\n# Demo code\n# ---------------\narray = [1,2,3,4,5,6]\nprint(\"Does the array contain 4?\")\nprint(binarySearchIterative(array, 4))\nprint(\"Does the array contain 2?\")\nprint(binarySearchRecursive(array, 2))\n"} {"doc_id": "23af0f88f0d6d2746d282def3f8274a8", "text": "\"\"\"\n\nTema: Cadenas.\nCurso: Pensamiento computacional.\nPlataforma: Platzi.\nProfesor: David Aroesti.\nAlumno: @edinsonrequena.\n\n---------------------------------------\n\nlen(longitud)\n\nidenxing(indexacion)\n\nslicing(rebanadas)\n my_str[comienzo:fin:pasos]\n\n\"\"\"\n\n# Accediendo a la longitud del string\nmy_str = 'Platzi'\nlen(my_str)\n\n# Accediendo a un indice especifico del string\nmy_str[0] # P\nmy_str[2] # a\n\n# Notacion de slicing\nmy_str[2:] # atzi\nmy_str[:3] # Pla\nmy_str[:-2] # Plat\nmy_str[::2] # Paz\n\n# Concatenacion\n'Yo amo a ' + my_str # Yo amo a platzi\nf'Yo amo a {my_str}' # Yo amo a platzi\nf'Yo amo a {my_str}, ' * 100 # Yo amo a platzi, Yo amo a platzi, Yo amo a platzi, Yo amo a platzi,\n\n\"\"\"\n\n1) Los objetos de tipo str pueden representarse con comillas simples o dobles\n\n2) El operador de + tiene diferente significado segun el tipo de dato (overload). Con cadenas significa concatenacion.\n\n3) El operador * es el operador de repeticion con cadenas\n\n4) Las cadenas son inmutables. Esto quiere decir que cuando concatenamos un valor a una variable de tipo str se genera un nuevo espacio en memoria.\n\n\"\"\"\n\n\"\"\"\n\nEntradas (inputs)\n\n1) Python tiene la funcion interna llamada input para recibir datos del usuario.\n\n2) Input siempre regresa cadena, por lo que si queremos utilizar otro tipo, tenemos que hacer type casting\n\n\"\"\"\n\nname = input('Cual es tu nombre?: ')\nprint(name)\nprint(f'Tu nombre es {name}')\n\n# Tipo str\nnumber = input('Escribe un numero: ')\nprint(type(number))\n\n# Tipo int\nnumber = int(input('Escribe un numero: '))\nprint(type(number))\n\n# Tipo float\nnumber = float(input('Escribe un numero: '))\nprint(type(number))\n\n\n"} {"doc_id": "2400dca8e1f1b88bffb6f03b6c9ed706", "text": "# Assignment 2 - Challenge 8\n# Print an array\n# Given an array of integers print all the elements one per line.\n# This is a little bit different as there is no need for a 'return' statement just to print and recurse.\n\ndef printStr(nums):\n # Base case: if nums is empty, print blank line to terminate\n if(len(nums) == 0):\n print()\n # if nums contains integers, print the first digit to screen and make recursive call\n # pass int array, with first element removed\n # continue until base case reached\n # return nested results back up the chain of recursive calls\n else:\n print(nums[0])\n printStr(nums[1:])\n\n# -----\n# test\n# -----\n\nprint(\"Test 1:\\n\")\nprint(\"----------\")\nprintStr([])\nprint(\"Test 2:\\n\")\nprint(\"----------\")\nprintStr([0,1,2,3,4,5])"} {"doc_id": "241e31f6028f28ac02fb95059f1c1715", "text": "from collections import deque\n\nclass Queue():\n '''\n Thread-safe, memory-efficient, maximally-sized queue supporting queueing and\n dequeueing in worst-case O(1) time.\n '''\n\n\n def __init__(self, max_size = 10):\n '''\n Initialize this queue to the empty queue.\n\n Parameters\n ----------\n max_size : int\n Maximum number of items contained in this queue. Defaults to 10.\n '''\n\n self._queue = deque(maxlen=max_size)\n\n\n def enqueue(self, item):\n '''\n Queues the passed item (i.e., pushes this item onto the tail of this\n queue).\n\n If this queue is already full, the item at the head of this queue\n is silently removed from this queue *before* the passed item is\n queued.\n '''\n\n self._queue.append(item)\n\n\n def dequeue(self):\n '''\n Dequeues (i.e., removes) the item at the head of this queue *and*\n returns this item.\n\n Raises\n ----------\n IndexError\n If this queue is empty.\n '''\n\n return self._queue.pop()\n"} {"doc_id": "242fb3be4e84da07c77f3629288c9e5b", "text": "#Fundamental Data Types in Python\n#int\n#float\n#bool\n#str\n#list\n#tuple\n#set\n#dict\n#complex\n\n\n#Classes -> Custom Data Types\n\n#Specialized Data Types\n\n#None: absence of value\n\n#printing type of output\nprint(type(2+4))#\nprint(type(2-4))#\nprint(type(2*4))#\nprint(type(2/4))#\nprint(type(20+0.44))#\nprint(2 ** 3)#ie 2^3=8\nprint(2 // 4)#0\nprint(type(2 // 4))#\nprint(5 // 4)#1\nprint(bin(5))#returns binary num ie 0b101\nprint(int('0b101',2))#returns decimal and 2 here is for binary num\n\n#math function\nprint(round(3.1))#3\nprint(round(3.9))#4\nprint(abs(-20))#20\n\n#order of precedence in python basics\n# ()\n# ** power\n# * /\n# + -\n\n#multiple declairation\na,b,c = 1,2,3\nprint(a);\nprint(b);\nprint(c);\n#output\n#1\n#2\n#3\n\n#storing and operating\ndiff = a/b\nprint(diff)\n# we can only concatinate str with str.\n#long string - \n#tripple quote to use multiline display\nlong_string = '''\nWOW\n0 0\n___\n'''\n#concatinating two strings - only works with string. No int float ...\nf_name = 'Sudeep'\nl_name = 'Swain'\nfull_name = f_name + ' ' + l_name\nprint(full_name)\n\n#typecasting\nprint(type(str(100.12)))\nprint(type(int(str(100))))\n#print(type(int(str(100.20)))) error!!\na = str(100)\nb = int(a)\nc = type(b)\nprint(c)\n\n#escape sequence\nweather = 'It\\'s sunny'\n#here so as to print 's we need \\' which is the escape sequence. ie whatever comes after \\ it's gonna accept the string whatever comes after this.\nprint(weather)\n#\\t = tab before printing\n#\\n = new license\n\n#Formatted String\nf_name = 'Sudeep'\nl_name = 'Swain'\nage = 20\nprint('Hey! My name is ' + f_name + l_name + ' and I\\'m' + str(age) + ' old.')\n#str(age) because the print can only concatinate strings together.\n#Type - 2\nprint(f'Hey! My name is {f_name} {l_name} and I\\'m {age} old.')\n#Type - 3\nprint('Hey! My name is {} {} and I\\'m {} old.'.format(f_name, l_name, age))\n#Type - 4 The nos indicate the value passed as parameter\nprint('Hey! My name is {1} {0} and I\\'m {2} old.'.format(f_name, l_name, age))\n#display a char in a string\nfull_name = 'Sudeep Rn Swain'\nprint(full_name[5])\n#print a selected nos of string\n\n#[start:stop]\nprint(full_name[0:8])\n\n#[start:stop:stepover]\n#default stepover is 1 bcoz we are jummping 1 by 1.\n#here stepover is 2 ie jumps strings by 2.\nprint(full_name[0:8:2])\nprint(full_name[0:]) #go all the way to the end from first string.\nprint(full_name[:5]) #default 0 till 5\nprint(\n full_name[-1]\n) # (-) means the string starts printed from the backward like here the bakward string is 'n' and it's printed\nprint(full_name[::-2]) #will be printed from back to front skipping 2 digits\n#full_name[0] = 'B'#error!!, because we cann't change the value in the string; the only way is to re-assign.\n\n#len()-used to find the len of the string.\nprint(len('Hello'))\n\n#Type-2\ngreet = 'Hello! Welcome to BBSR'\nprint(greet[0:len(greet)])\n\n#upper() makes string CAPTALIZE\n#Type-1\nprint(greet.upper())\n#Type-2\nprint(greet.capitalize())\n#lower\nprint(greet.lower())\n\n#find()-finds the position\nprint(greet.find('to'))\n\n#replace('s1','s2')- replaces the string with the given string. First string is the word to be replaced and the second string is the word that has to be written to be replace.\ngreet2 = greet.replace('BBSR', 'CTC')\nprint(greet2)\n\n#boolean\nname = 'Sudeep'\nis_intelligent = False\nprint(name + ' is genius: ' + str(is_intelligent))\nis_intelligent = True\nprint(name + ' is humble: ' + str(is_intelligent))\nprint(bool(0)) #retuns False\nprint(bool(1)) #returns True\n\n#input complications\n#birth_year=input('What\\'s your birth year: ')#input string is always assigned after getting converted into str format\n#current_age = 2020 - int(birth_year)#type casting the birth year to int to perform mathematical operation on it.\n#print(f'Your age is {current_age}')\n\n#password checker\n#print('*' * 10)# * is printed 10X\n#username = input('Username: ')\n#password = input('Password: ')\n#print(f'{username}, your password, {password}, is {len(password)} letters long')\n#Type-2\n#username = input('Username: ')\n#password = input('Password: ')\n#password_len = len(password)\n#hidden_password = '*' * password_len\n#print(f'{username}, your password, {hidden_password}, is {password_len} letters long')\n\n#Lists\nli1 = [1, 2, 3, 4, 5]\nli2 = ['a', 'b', 'c']\nli3 = [1, 2, 3, 'a', 'b', True, False]\n# Lists are like Arrays.\namazon_cart = ['Mobile', 'Dumbell', 'Beauty']\nprint(amazon_cart)\nprint(amazon_cart[2])\n\n#List Slicing\nprint(amazon_cart[0:2]) #from 0 - 1 not including 2\nprint(amazon_cart[0::2]) #print all stepping two indexes.\n#changing the lists in the cart ie...\namazon_cart[0] = 'Laptop'\nprint(amazon_cart[0]) #1st index changed to Laptop.\n#assigning amazon_cart to a new list named as new_cart ie\nnew_cart = amazon_cart\n#here new_cart is echoed** to amazon_cart ie any changes made will reflect in amazon_cart. We didn't copy. But...we need to copy. Let's ee how below.\nnew_cart[0] = 'groceries'\nprint(new_cart)\nprint(amazon_cart)\n#value changes in both the string IMP!!!\n\n#But below we need are copying the value. SO this is how it's done\namazon_cart = ['Mobile', 'Dumbell', 'Beauty']\nnew_cart = amazon_cart[:]\n#above the value is copied ie no change will be reflected in the amazon_cart\nnew_cart[0] = 'groceries'\nprint(new_cart)\nprint(amazon_cart)\n#above we saw the value changed is reflected in new_cart but not in amazon_cart\n\n#Matrix: array with another array inside it.\nmatrix = [[1, 2, 3], [3, 4, 5], [6, 7, 8]]\nprint(matrix)\nprint(matrix[0][1]) #prints (0,1) array pos value\n\n#adding in to the Arrays by using append()\n#append() adds element to the last of the matrix\nbasket = [1, 2, 3, 4, 5]\nbasket.append(100) #1st append or add 100 to the list\nnew_list = basket #then, assign basket to new_list; else it may display an error!!\nprint(basket)\nprint(new_list)\n\n#insert\nbasket.insert(\n 4, 100\n) #we can insert anywhere. Here we've inserted in position 4 the string 100\n#inserts add n increases the len of array\nprint(basket)\n\n#extend: adds value at end of array\nbasket = [1, 2, 3, 4, 5]\nbasket.extend([100])\nprint(basket)\n\n#pop() ele\nbasket.pop() #pops out the last element\nnew_list = basket.pop(0) #pops 0th index\nprint(basket)\nprint(new_list) #prints the pop out element.\n\n#remove ele\nnew_list = basket.remove(4) #remove 4th ele\nprint(new_list)\n\n#compile\nnew_list = basket[:] #remove the entire new_list\nnew_list.clear()\nprint(new_list)\n\n#array.index(): finds the index of the mentioned string in the braces, suppose...\nvowel = ['a', 'e', 'i', 'o', 'u']\nprint('Index of e is: ' + str(vowel.index('e')))\n#print('Index of e is: ' + str(vowel.index('e',0,1)))\n#above displays error!! because the content 'e' ain't there in the list betwwen 0th and 1th index.\n\nprint(\n 'd' in vowel\n) #if 'd' is present it would have return true but here as it isn't here then it return false.\n\n#array.count()\nprint(\n vowel.count('e')\n) # as there is one 'e' it will return the output as 1. Basically returns the number of ocurrances of the string.\n\n#array.sort()\nvowel.sort()\nprint(vowel)\n#this will sort the list.\n\n#array.sorted()\nvowel.sort()\nprint(\n sorted(vowel)\n) #doesn't affect the array, ie array remains intact. Does the same as sort()\n\n#copy(): just copies the list for us.\nnew_vowel = vowel.copy()\n\n#array.reverse():simply reverses the content in the index.\nvowel.reverse()\nprint(vowel)\n\n#Reversing the list using stepover [::-1]\nvowel = ['a', 'e', 'i', 'o', 'u']\nprint(vowel[::-1]) #stepover is -1 ie it prints from the backward direction.\n\n#prints from 1-100\nprint(list(range(1, 100)))\n#Type-2\nprint(list(range(101)))\n#the value of range should be the range ie to be displayed plus 1. Hence it will prnt from 1-100.\n\n#joining the lists into a string\n#Type-1\nsentence = ' ' #empty string\nnew_sentence = sentence.join(['hi', 'my', 'name', 'is', 'sudeep'])\nprint(new_sentence)\n#Type-2\nnew_sentence = ' '.join(['hi', 'my', 'name', 'is', 'sudeep'])\nprint(new_sentence)\n\n#list unpacking\na, b, c, *others, d = [1, 2, 3, 4, 5, 6, 7, 8, 9]\nprint('Unpacked lists mentioned below- ')\nprint(a) #prints first item\nprint(b) #prints second item\nprint(c) #prints third item\nprint(others) #prints rest of the items after the thirs item in the list\nprint(d) #prints the last string in the item ie 9.\n#if there won't hve been any d element then the element or the var 'others' would have print from 4-9, but as there's an element or var after others then it didn't print the last element.\n\n#None = nothing\nanyone = None\nprint('Anyone: ' + str(anyone))\n\n#Dictonary\ndictionary = {'a': [1, 2, 3], 'b': 2, 'c': True}\n\nprint(dictionary['b']) #displays the value stored in b ie 2\n#displys the way values are assigned to dictionary\nprint(dictionary)\n\n#Type-2\ndictionary2 = [{\n 'a': [1, 2, 3],\n 'b': 'hello',\n 'c': True\n}, {\n 'a': [4, 5, 6],\n 'b': 'hello',\n 'c': True\n}]\nprint(dictionary2[0]['a'][2])\n#here 0 = 1st braces in dictionary2 Arrays\n#here 'a' denotes the 'a' variable.\n#here 2 denotes 3rd elemnt in 'a' array\n\n#from dictionary list above to the prev.\nprint(dictionary['a'][1])\n# returns the 'a' var 2nd obj ie 2.\n\n#Developer Fundamental-II\n#Till now we have only used string to denote key\n#We can use the number and predefined values to denaote the string even. Let's check out how...\ndictionary3 = {\n 123: [1, 2, 3],\n #[100] : 2,\n #error in this line bcoz it ain't immutable\n True: True\n}\n\nprint(dictionary3[123]) #Works\n#print(dictionary3[100])#ERROR!! Doesn't work. Unhashable type list: this key is not immutable ie the value cannt be changed but a list can be changed.\nprint(dictionary3[True]) #Works\n\n#Dictonary Word\n#Suppose\ndictionary4 = {'a': [1, 2, 3], 'b': 2, 'c': True, True: False}\n#Case-1\n#print(dictionary['d'])\n#this will result into an error because there's no 'd' keyword\n#Case-2\nprint(dictionary4.get('d'))\n#above won't display an error rather it would display 'none'\n#Case-3\nprint(dictionary4.get('d', 25022000))\n#above would display 25022000 as there is no defined keyword in dictionary4.\n#Case-4\n#dict build in function\n\nf_name = dict(name='Sudeep')\nprint(f_name)\n#Here name do not need to be kept with quotes as keywords doesn't require quotes when declared under dict() predefined function.\n\nprint('a' in dictionary4) #true\nprint('d' in dictionary4) #false\n#return true if exist else false.\n\n#keys()\nprint('a' in dictionary4.keys()) #returns true as 'a' is a keyword\nprint(2 in dictionary4.\n keys()) #returns false as '2' is a value in 'b' not a keyword\n\n#values()\nprint('b' in dictionary4.values()) #returns false as 'b' is a keyword\nprint(2 in dictionary4.values()) #returns true as 2 is a value in 'b'.\n\n#items()\nprint(dictionary4.items())\n#as items represent all included so we write in this way.\n\n#Let's confuse\nprint('TRUE' in dictionary4.keys()) #False\n\nprint('TRUE' in dictionary4.items()) #False\n\n#clear()\n#dictionary4.clear()#clears content in the list\n#print(dictionary4)\n\n#copy()\ndictionary5 = dictionary4.copy() #copies one list to other\nprint(dictionary5)\n\n#pop()\nprint(\n dictionary5.pop(True)\n) #displays the pop items of the key popped(mostly pops the last ele or keys and values).\n#Type-2\nprint(dictionary5.popitem())\n#randomly pops a keys and values\n\n#update()\nprint(dictionary5.update({'c': 20}))\nprint(dictionary5) #prints the updated list\n#updates the value of c = 20\n\n#Tuple\nmy_tuple = (1, 2, 3, 4, 5)\n#my_tuple[1] = 'z'#ERROR!! Because tuple doesn't support assignment.\nprint(my_tuple[1]) #printing a tuple\n\n#Normal dictionary\nuser = {\n 'a': ['a', 'b', 'c'],\n 'ABC': ['A', 'B', 'C'],\n 123: [1, 2, 3],\n False: False,\n age: 20\n}\n\n#Let's dictionary using tuple\nuser_tuple = {\n 'a': ['a', 'b', 'c'],\n 'ABC': ['A', 'B', 'C'],\n (1, 2): [1, 2, 3],\n False: False,\n age: 20\n}\nprint(user_tuple[(1, 2)])\n#tuple is same as lists.\n\n#tuple has two methods\n#count()\n#index()\n\nmy_tuple = (1, 2, 3, 4, 5, 5)\n\nprint(my_tuple.count(5)) #displays 2 as there are 2 5's in the tuple\n\nprint(\n my_tuple.index(5)\n) #displays 4 as there are 2 5's in the tuple and pos of 1st 5 is 4th pos.\n\nprint(len(my_tuple))\n#displays the len of the my_tuple ie 6\n\n#set datatype and data structure\n#set : unorder collection of unique objects. represented within curly braces\nmy_set = {1, 2, 3, 4, 5, 5}\nprint('Length of org set is: ' + str(len(my_set))) #prints len of original set\nprint(\n my_set\n) #As set is a unique collection of objects hence here n my_set we have two nos of '5' and as 5 = 5 hence it will only display one 5 in time\n# we cann't add multiple same values in the set even though we are able to add 100.my_set\n\nmy_set.add(100)\nmy_set.add(2) #doesn't even add 2 as there is a 2 present in the set.\nprint('Length of org set is: ' + str(\n len(my_set))) #prints len of set after addition\nprint(my_set)\n\n#Given a list of repeated element, print it in such a way that elemnts don't repeat.\nmy_list = [1, 2, 2, 3, 4, 5, 5]\nprint(my_list) #prints repeated element\nprint(\n set(my_list)\n) #On conversion to set it discards the repeated element and pritns the list\n\nmy_set = {1, 2, 2, 3, 4, 5, 5}\n#print(my_set[0])#ERROR!! Cann't access\n\nprint(list(my_set)) #covertion of set to list\n\n#methods of set\nmy_set = {1, 2, 2, 3, 4, 5, 5}\nyour_set = {4, 5, 6, 7, 8, 9, 10}\n\n#difference()\nprint(my_set.difference(your_set))\n#shows the difference between two sets ie which element are same in my_set get discarded and the rest others which ain't present are diplayed.\n\n#discard(X):discards X from the set.\nprint(my_set.discard(5))\nprint(my_set)\n\n#difference_update(X):X is removed\nprint(my_set.difference_update(\n your_set)) #here 4,5 will be removed as it is present in the ypur_set\nprint(my_set)\n\n#set.intersection\nmy_set = {1, 2, 2, 3, 4, 5, 5}\nyour_set = {4, 5, 6, 7, 8, 9, 10}\nprint(my_set.intersection(\n your_set)) #displays the common element in both the set\n\n#set.isdisjoint()\nprint(my_set.isdisjoint(your_set)\n ) #displays True if the set doesn't have any common element else False\n\n#.issubset()\nprint(my_set.issubset(your_set)\n ) #If my_set is the subset of your_set then it returns true else False\n\n#.issuperset()\nprint(my_set.issuperset(your_set)\n ) #If my_set is the superset of your_set then it returns True else False\n\n#.union()\nprint(my_set.union(your_set)) #returns the union of two sets\n#Deletes duplicate and returned new txt\n#Type-2\nprint(my_set | your_set)\n\n#.intersection()\nprint(my_set & your_set)\n\n#Boolean\nis_old = False\nis_license = True\n\n#below condition checks True.\nif is_old:\n print('You are old enough to drive a car.'\n ) #stmnt comes under if condition. Here indentation matters.\n\n#else if condition\nelif is_license:\n print('You are not old enough to carry a license.')\n\n#below condition checks or outputs the False condition.\nelse:\n print('You can\\'t drive a car and rush to RTO for your license.')\n\nprint('checked') #independent stmt\n\n#converting & into a statement\nif is_old and is_license:\n print('You can\\'t drive') #because is_old is False and is_licence is True\n\n#THE ABOVE INDENTATION IS FOR THE COMPILER/INTERPRETER TO UNDERSTAND THAT THE CONTENT IS WITHIN THE PARTICAL CONDITON\n\n#Thruthy and Falsy\n#Thruthy value\nis_cond1 = bool(True)\nis_cond2 = bool('abc')\nis_cond3 = bool(5)\nis_cond4 = bool(False)\nis_cond5 = bool(0)\nis_cond6 = bool(-5)\nis_cond7 = bool(None)\n\nprint(is_cond1)\nprint(is_cond2)\nprint(is_cond3)\nprint(is_cond4)\nprint(is_cond5)\nprint(is_cond6)\nprint(is_cond7)\n\n#Ternary operator\n#cond_if_true if cond else cond_if_else\nis_friend = True #condition is true\ncan_message = 'message allowed' if is_friend else 'message not allowed'\n\nprint(can_message) #as the condition is true hence it prints message allowed\n\n#Short Circuiting\nis_friend2 = True\nis_user2 = False\n#and operator\nprint('Result: ' + str(is_friend2 and is_user2)\n ) #boolean value has also to be converted into string before printing.\n#or operator\nprint(is_friend2 or is_user2)\n\n#logical operator\nprint(str(4 == 5))\nprint('a' > 'A')\nprint(1 < 2 > 3 < 4)\n\n#using not : prints opposite to the input given\nprint(not (True))\n\n#Some test case-\nprint('Test cases-\\n')\nprint(True == 1)\nprint('1' == 1)\nprint([] == 1)\nprint(10 == 10.0)\nprint([] == [])\n\n#Module 4.9 --- IMPORTANT\nprint('\\n')\n#print(True is 1) #replace 1 with True for dsplaying result as True\n#print('1' is 1) #replace 1 with '1' the value will go true\n#print([] is 1) #replace 1 with [] as both are same ie empty list and same m/m locataion\nprint(10 is 10.0) #\nprint([] is [])\n\n# '=' checks for the equality in value\n# 'is' checks whether the location in m/m where the value is stored is same or not'\n\n#Loops\nfor item in 'Welcome to BBSR.':\n print(item)\n #remember to align properly.\n\n#iterable - list, tuples, set, string, dictionary.\n#for list\nfor item in [1, 2, 3, 4, 5]:\n print(item)\nprint('\\n')\n#for set\nfor item in {1, 2, 3, 4, 5}:\n print(item)\nprint('\\n')\n#for tuple\nfor item in (1, 2, 3, 4, 5):\n print(item)\nprint('\\n')\n\n#multiline loops\nfor item in (1, 2, 3, 4, 5):\n print('\\n')\n for ch in ['a', 'b', 'c']:\n print(item, ch)\n\nprint('\\n')\n\n#items(), values(), keys() iterate over dictonary. Below are examples.\n\nuser = {'name': 'Sudeep', 'age': 20, 'is_undergraduate': True}\n\nfor item in user.items():\n print(item)\n\nprint('\\n')\n\nfor item in user.values():\n print(item)\n\nprint('\\n')\n\nfor item in user.keys():\n print(item)\n\nprint('\\n')\n\n#Type-1 of printing the key and value\nfor item in user.items():\n key, value = item\n print(key, value)\n\nprint('\\n')\n\n#Type-2\nfor key, value in user.items():\n print(key, value)\n\nprint('\\n')\n\n#iterating a list using counter variable\nmy_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\ncounter = 0\nfor item in my_list:\n counter = counter + item\nprint('Sum: ', str(counter)) #printing the sum of element in the array\nprint('\\n')\n#range(x,y,z):creates a special kind of object to iterate over. x =starting string, y=end string, z=stepover\n#printing from foreward ie 0-10\nfor number in range(0, 10, 1):\n print('Person: ', str(number))\n#The last index is not included ie 10.\nprint('\\n')\n#printing from backwward ie 10 - 0\nfor number in range(10, 0, -1):\n print('Person: ', str(number))\n#The last index is not included ie 0.\n\n#enumerate: is usefull if we need index count alongisde printing the output\nfor i, char in enumerate('Hello!!'):\n print(i, char)\n\nfor i, char in enumerate(list(range(100))):\n print(i, char)\n if char == 50:\n print(f'index of 50 is:', i)\n\n#while Loop\ni = 0\nwhile i < 50:\n print(i)\n i = i + 1\n\nelse:\n print('done with all the work'\n ) #This case pops in console when condition is 50.\n\nmy_list = [1, 2, 3, 4]\nfor item in my_list:\n print(item)\n\ni = 0\nwhile i < len(my_list):\n print(my_list[i])\n i = i + 1\n\n#break, continue and pass are even included in python\n\n#GUI - Caution: not!! Working\npicture = [[0, 0, 0, 1, 0, 0, 0], [0, 0, 1, 1, 1, 0, 0], [0, 1, 1, 1, 1, 1, 0],\n [1, 1, 1, 1, 1, 1, 1], [0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0]]\n#iterate over picture\n#if 0-> print empty space\n#else if 1 -> print *\n\nfor image in picture:\n for pixel in image:\n if (pixel == 1):\n print('*', end='')\n else:\n print(' ', end='')\n print('')\n\n#check for duplicates\na_list = [\n 'a',\n 'b',\n 'c',\n 'd',\n 'e',\n 'f',\n 'd',\n 'a',\n]\n\nduplicate = []\nfor value in a_list:\n if a_list.count(value) > 1:\n #this will print all the duplicate even the multiple repeated value will be displayed but...\n if value not in duplicate:\n #this displayes the only values which are duplicated.\n duplicate.append(value)\n\nprint(duplicate)\n\n#Function\n\n\ndef say_hello():\n #function defined\n print('Function called: hello') #function operation performed\n\n\nsay_hello() #function call\n\n\ndef func1(a, b): #parameter passed\n print('Sum: ', str(a + b)) #operation performed\n\n\nfunc1(30, 40) #arguements passed\n\na = 10\nb = 20\nfunc1(a, b)\n\n#EEEEEEEEEEEEEERRRRRRRRRRROOOOOOOOORRRRRRRRRR!!\n#4.22\n\n\ndef func2(f_name, l_name):\n print(f'Hello!! {f_name} {l_name}')\n\n\nfunc2('Hello', ' World')\n\n\ndef sum(num1, num2):\n print(f'Sum: {num1} + {num2}')\n\n\nsum(10, 20)\n\n\n#return statement\ndef sum(num1, num2):\n return (num1 + num2)\n\n\nprint(f'Function returns: {sum(40,15)}')\n\n#if not returned in the above case then it would have return none.\n\n\ndef sum(num1, num2):\n def another_func(num1, num2):\n return (num1 + num2)\n\n return another_func(\n num1, num2) #without this statement the value return will be none\n return 5 #doesn't print this because this line exceeds the function\n print('hello'\n ) # doesn't print because this line is excedded out of the function\n\n\ntotal = sum(29, 20)\nprint(f'Total: {total}')\n\n#Methods vs Funcions\n#list()\n#print()\n#max()\n#min()\n#input()\n\n\n#Docstring\ndef test(a):\n '''\n Info: This function tests and prints param a\n '''\n print(a)\n\n\ntest('!!!!') #prints output\nhelp(test) #whatever is printed within tripple quote it is printed\nprint(test.__doc__) #same thing as above.\n\n\n#clean code\ndef is_odd_or_even(num):\n if num % 2 == 0:\n return True\n else:\n return False\n\n\nprint(f'is_odd_or_even: {is_odd_or_even(25)}')\n\ndef highest_even(li):\n evens = []\n for items in li:\n if items % 2 == 0:\n evens.append(item)\n return max(evens)\nprint(f'Ans: {highest_even([10,2,3,1,8,11])}')\n\n#OOP\nclass BigObj:\n pass\n \nobj1 = BigObj()\nprint(type(obj1))\n\n"} {"doc_id": "247404719d1fb7c0c3626072b94d829f", "text": "\"\"\"\nFile: hailstone.py\n-----------------------\nThis program should implement a console program that simulates\nthe execution of the Hailstone sequence, as defined by Douglas\nHofstadter. Output format should match what is shown in the sample\nrun in the Assignment 2 Handout.\n\"\"\"\n\n\ndef main():\n \"\"\"\n Calculate the number of steps to make n reach 1 and show a process of calculation.\n \"\"\"\n print('This program computes Hailstone sequences.')\n print(' ')\n n=int(input('Enter a number: '))\n x=0\n #x stands for the number of steps to make n reach 1.\n if n==1:\n print('It took 0 step to reach 1.')\n else:\n while True:\n if n==1:\n break\n elif n%2==1:\n #n is odd.\n x+=1\n n=int(3*n+1)\n a=int((n-1)/3)\n print(str(a) + ' is odd, so I make 3n+1: ' + str(n))\n else:\n #n is even.\n x+=1\n n=int(n/2)\n b=2*n\n print(str(b) + ' is even, so I take half: ' + str(n))\n print('It took '+str(x)+' steps to reach 1.')\n\n\n\n\n\n\n###### DO NOT EDIT CODE BELOW THIS LINE ######\n\nif __name__ == \"__main__\":\n main()\n"} {"doc_id": "2491ceb50f2ccccf39621ce1eda921ed", "text": "print(\"Let's practive everything.\")\nprint('You\\'d need to know bout escapes with \\\\ that do:')\nprint('\\n newlines and \\t tabs.')\n\npoem = \"\"\"\n\\t The lovely world\nwith logic so firmly planted\ncannot discern \\n the needs of love\nnor comprehend passion from intuition\nand requires an explanation \n\\n\\t\\twhere there is none.\n\"\"\"\n\nprint(\"-----------\")\nprint(poem)\nprint(\"------------\")\n\n\nfive = 10 - 2 + 3 - 6\nprint(\"This should be five :%r \"%five)\n\ndef secret_formula(started):\n jelly_beans = started * 500\n jars = jelly_beans / 1000\n crates = jars / 100\n return jelly_beans , jars , crates\n\nstart_point = 10000\nbeans , jars , crates = secret_formula(start_point)\n\nprint(\"With a starting point of : {}\".format(start_point))\n"} {"doc_id": "24ceeb49bebc6642fa6a4ae0eee29c07", "text": "# brick.py\n\n\nclass LegoBrick(object):\n \"\"\"\n A class used to represent a Lego brick.\n\n Methods\n -------\n setId(width: int)\n Sets the ID of the Lego brick.\n getId() -> int:\n Gets the ID of the LEGO brick.\n setWidth(width: int)\n Sets the width of the Lego brick.\n getWidth() -> int:\n Gets the width of the LEGO brick.\n setHeight(height: int)\n Sets the height of the Lego brick.\n getHeight() -> int:\n Gets the height of the LEGO brick.\n getArea() -> int:\n Gets the area of the LEGO brick,\n area calculation is with width * height.\n copy() -> LegoBrick :\n Gets a LegoBrick instance with the same attributes.\n \"\"\"\n\n NONE_ID = -1\n\n def __init__(self, width: int, height: int, id: int = NONE_ID):\n \"\"\"\n LegoBrick constructor.\n\n Parameters\n ----------\n width : int\n The brick width.\n height : int\n The brick height.\n\n Raises\n ------\n ValueError\n If the width or the height isn't bigger then 0.\n \"\"\"\n self.setWidth(width)\n self.setHeight(height)\n self.__id = id\n\n def setId(self, id: int):\n \"\"\"\n Sets the id of the Lego brick.\n\n Parameters\n ----------\n id : int\n The brick ID.\n\n \"\"\"\n self.__id = id\n\n def getId(self) -> int:\n \"\"\"\n Gets the ID of the LEGO brick.\n\n Returns\n -------\n int\n the ID of the LEGO brick.\n \"\"\"\n return self.__id\n\n def setWidth(self, width: int):\n \"\"\"\n Sets the width of the Lego brick.\n\n Parameters\n ----------\n width : int\n The brick width.\n\n Raises\n ------\n ValueError\n If the width isn't bigger then 0.\n \"\"\"\n if (width < 1):\n raise ValueError(\"width must be bigger then 1!\")\n self.__width = width\n\n def getWidth(self) -> int:\n \"\"\"\n Gets the width of the LEGO brick.\n\n Returns\n -------\n int\n the width of the LEGO brick.\n \"\"\"\n return self.__width\n\n def setHeight(self, height: int):\n \"\"\"\n Sets the height of the Lego brick.\n\n Parameters\n ----------\n height : int\n The brick width.\n\n Raises\n ------\n ValueError\n If the height isn't bigger then 0.\n \"\"\"\n if (height < 1):\n raise ValueError(\"height must be bigger then 1!\")\n self.__height = height\n\n def getHeight(self) -> int:\n \"\"\"\n Gets the height of the LEGO brick.\n\n Returns\n -------\n int\n the height of the LEGO brick.\n \"\"\"\n return self.__height\n\n def getArea(self) -> int:\n \"\"\"\n Gets the area of the LEGO brick,\n area calculation is with width * height.\n\n Returns\n -------\n int\n the area of the LEGO brick.\n \"\"\"\n return self.__height * self.__width\n\n def copy(self):\n \"\"\"\n Gets a LegoBrick instance with the same attributes.\n\n Returns\n -------\n LegoBrick\n copied instance.\n \"\"\"\n return LegoBrick(self.__width, self.__height, self.__id)\n\n def __eq__(self, other):\n return self.__dict__ == other.__dict__\n\n def __str__(self):\n return self.__toString()\n\n def __repr__(self):\n return self.__toString()\n\n def __toString(self) -> str:\n return \"LegoBrick[id=%d, width=%d, height=%d, area=%d]\" % (\n self.getId(), self.getWidth(), self.getHeight(), self.getArea())\n"} {"doc_id": "24d92669eb13cb16cae7dc0ce4506028", "text": "# Pig Latin is a language constructed by transforming English words. \n# While the origins of the language are unknown, it is mentioned in at least two documents \n# from the nineteenth century, suggesting that it has existed for more than 100 years. \n# The following rules are used to translate English into Pig Latin:\n# If the word begins with a consonant (including y), then all letters at the beginning of the word, \n# up to the \n# first vowel (excluding y), are removed and then added to the end of the word, followed by ay. \n# For example, computer becomes omputercay and think becomes inkthay.\n\n# If the word begins with a vowel (not including y), then way is added to the end of the word. \n# For example, algorithm becomes algorithmway and office becomes officeway.\n\n# Write a program that reads a line of text from the user. \n# Then your program should translate the line into Pig Latin and display the result. \n# You may assume that the string entered by the user only contains lowercase letters and spaces.\n\n# Initialize two lists: one containing consonants and one containing vowels\nvowels = [\"a\", \"e\", \"i\", \"o\", \"u\"]\nconsonants = [\"b\", \"c\", \"d\", \"f\", \"g\", \"h\", \"j\", \"k\", \"l\", \"m\", \"n\", \"p\", \"q\", \"r\", \"s\", \"t\", \"v\", \"w\", \"x\", \"y\", \"z\"]\n#######################\nay = \"ay\" # For concatenation\nway = \"way\"# For concatenation\npiglatin = [] # list to hold the converted values of input string\n\nwords = input(\"Please enter a word or phrase: \") #ask user for string to convert \nwordsList = words.split() # Split the string input from user into parts in a list\n\nfor word in wordsList: # Iterate through the words from User string and apply Pig Latin Rules\n if word[:1] in consonants:\n wordLength = len(word)\n removeLetters = word[1:wordLength]\n pigword = removeLetters + word[:1] + ay\n piglatin.append(pigword)\n elif word[:1] in vowels:\n wordLength = len(word)\n pigword = word + way\n piglatin.append(pigword)\n\nformat_list = [\"{} \" for item in piglatin] # Initial formatting to contain all values from piglatin\n\npigLatinString = \" \".join(format_list).format(*piglatin) # join all values in piglatin as a string\n\nprint(pigLatinString) # print the result\n\n"} {"doc_id": "2500011e303b4979058262504ebbf036", "text": "def getHammingDistance(str1, str2):\n hammingDistance = 0\n\n if len(str1) == len(str2):\n for index in range(len(str1)):\n if ord(str1[index]) != ord(str2[index]):\n hammingDistance += 1\n return hammingDistance\n else:\n return None\n\ndef countSubstrPattern(str1, str2):\n count = 0\n index = 0\n\n if len(str2) < len(str1):\n while index < len(str1):\n if str1.find(str2, index, index + len(str2)) != -1:\n count += 1\n index += 1\n return count\n else :\n return None\n\ndef isValidString(str1, str2):\n check = 0\n\n for index in range(len(str1)):\n ch = str1[index]\n for index1 in range(len(str2)):\n if ord(str1[index]) == ord(str2[index1]):\n check += 1\n if check == len(str1):\n return True\n else :\n return False\n\ndef getSkew(str1,n):\n index = 0\n g = 0\n c = 0\n\n while index < n:\n if ord(str1[index]) == ord('G'):\n g += 1\n if ord(str1[index]) == ord('C'):\n c += 1\n index += 1\n\n return g-c\n\ndef getMaxSkew(str1,n):\n max = getSkew(str1,n)\n\n if n > 0:\n for index in range(n):\n if max < getSkew(str1,n-index):\n max = getSkew(str1,n-index)\n return max\n\ndef getMinSkew(str1,n):\n min = getSkew(str1,n)\n\n if n > 0:\n for index in range(n):\n if min > getSkew(str1,n-index):\n min = getSkew(str1,n-index)\n return min\n\ndef printMenu():\n print \"===========================\"\n print \"[3] Check String\"\n print \"[1] Get Hamming Distance\"\n print \"[2] Count Substring Pattern\"\n print \"[4] Get Skew\"\n print \"[5] Get Maximum Skew\"\n print \"[6] Get Minimum Skew\"\n print \"[7] Exit\"\n print \"===========================\"\n\n return input(\"CHOICE: \")\n\n\n#MAIN FUNCTION\nchoice = 0\nn = 0\nwhile choice != 7:\n choice = printMenu()\n if choice == 1:\n str1 = raw_input(\"First string: \")\n str2 = raw_input(\"Second string: \")\n ans = getHammingDistance(str1,str2)\n if ans != None:\n print \"\\n\\nHamming Distance: %d\\n\\n\" % ans\n else :\n print \"\\n\\nString lengths do not MATCH!!\\n\\n\"\n elif choice == 2:\n str1 = raw_input(\"String: \")\n str2 = raw_input(\"Substring: \")\n ans = countSubstrPattern(str1,str2)\n if ans != None:\n print \"\\n\\nSubstrings: %d\\n\\n\" % ans\n else :\n print \"\\n\\nSubstring's length is larger than original String!\\n\\n\"\n elif choice == 3:\n str1 = raw_input(\"String: \")\n str2 = raw_input(\"Library: \")\n ans = isValidString(str1, str2)\n if ans == True:\n print \"VALID\"\n else:\n print \"INVALID\"\n elif choice == 4:\n str1 = raw_input(\"String: \")\n while n <= 0 or n > len(str1):\n n = int(raw_input(\"Starting index: \"))\n if n <= 0:\n print \"Index starts at 1!\"\n if n > len(str1):\n print \"Index is greater than the length of the string!\"\n ans = getSkew(str1,n)\n n = 0\n print \"\\n\\nSkew: %d\\n\\n\" % ans\n elif choice == 5:\n str1 = raw_input(\"String: \")\n while n <= 0 or n > len(str1):\n n = int(raw_input(\"Starting index: \"))\n if n <= 0:\n print \"Index starts at 1!\"\n if n > len(str1):\n print \"Index is greater than the length of the string!\"\n ans = getMaxSkew(str1,n)\n n = 0\n print \"\\n\\nSkew: %d\\n\\n\" % ans\n elif choice == 6:\n str1 = raw_input(\"String: \")\n while n <= 0 or n > len(str1):\n n = int(raw_input(\"Starting index: \"))\n if n <= 0:\n print \"Index starts at 1!\"\n if n > len(str1):\n print \"Index is greater than the length of the string!\"\n ans = getMinSkew(str1,n)\n n = 0\n print \"\\n\\nSkew: %d\\n\\n\" % ans\n"} {"doc_id": "252c0d095ce3b7efa3738617692a560e", "text": "\"\"\"\nFile: tree.py\nName: \n-------------------------\nThis file shows the basic concepts for binary trees.\nAfter constructing a tree, we will do 3 traversal examples:\nPre-order\nIn-order \nPost-order\n\"\"\"\n\nclass Tree:\n\tdef __init__(self, left, tree_value, right):\n\t\tself.left = left\n\t\tself.tree_value = tree_value\n\t\tself.right = right\n\n\ndef main():\n\tleaf1 = Tree(None, 2, None)\n\tleaf2 = Tree(None, 6, None)\n\tleaf3 = Tree(None, 18, None)\n\tleaf4 = Tree(None, 40, None)\n\tnode1 = Tree(leaf1, 4, leaf2)\n\tnode2 = Tree(leaf3, 19, leaf4)\n\troot = Tree(node1, 17, node2)\n\tpre_order(root)\n\tin_order(root)\n\tpost_order(root)\n\ndef traversal(root):\n\n\tif root is None:\n\t\tpass\n\n\telse:\n\t\tprint(root.tree_value)\n\t\ttraversal(root.left)\n\t\ttraversal(root.right)\n\n\ndef pre_order(root):\n\n\tif root is None:\n\t\tpass\n\n\telse:\n\t\tprint(root.tree_value)\n\t\tpre_order(root.left)\n\t\tpre_order(root.right)\n\n\ndef in_order(root):\n\tif root is None:\n\t\tpass\n\n\telse:\n\n\t\tin_order(root.left)\n\t\tprint(root.tree_value)\n\t\tin_order(root.right)\n\n\ndef post_order(root):\n\tif root is None:\n\t\tpass\n\telse:\n\n\t\tpost_order(root.left)\n\t\tpost_order(root.right)\n\t\tprint(root.tree_value)\n\n\t\n\nif __name__ == '__main__':\n\tmain()\n"} {"doc_id": "2547b3818d236ce7da68e9dee2ee45af", "text": "\"\"\"\n53. Maximum Subarray\nGiven an integer array nums, find the contiguous subarray (containing at least one\nnumber) which has the largest sum and return its sum.\n\nA subarray is a contiguous part of an array.\n\nExamples\n--------\nExample 1:\n Input: nums = [-2,1,-3,4,-1,2,1,-5,4]\n Output: 6\n Explanation: [4,-1,2,1] has the largest sum = 6.\n\nExample 2:\n Input: nums = [1]\n Output: 1\n\nExample 3:\n Input: nums = [5,4,-1,7,8]\n Output: 23\n\nConstraints\n-----------\n* 1 <= nums.length <= 105\n* -104 <= nums[i] <= 104\n\"\"\"\n\ndef initial_pass(nums: list[int]) -> int:\n # Check each subarray from size 1 to size n\n max_sum = -105 * 106 # Ensures we start at a value that can be overwritten \n for i in range(1, len(nums)+1):\n start_index = 0\n end_index = i\n while end_index <= len(nums):\n max_sum = max(max_sum, sum(nums[start_index:end_index]))\n start_index += 1\n end_index += 1\n\n return max_sum\n"} {"doc_id": "254aa0c0ba505f68e322ae64203bcd2c", "text": "\"\"\"Day 1 Solution\"\"\"\nimport itertools\nimport operator\nfrom functools import reduce\nfrom typing import List\n\n\ndef compute_product(number_list: List[int], num_summands: int) -> int:\n \"\"\"Get the numbers which sum to 2020 and return their product\n\n Parameters\n ----------\n number_list : List\n List of numbers read from the input\n num_summands : int\n Number of summands - 2 or 3\n\n Returns\n -------\n int\n The product of the numbers\n \"\"\"\n iter = itertools.combinations(number_list, num_summands)\n for it in iter:\n if sum(it) == 2020:\n return reduce(operator.mul, it, 1)\n\n\ndef read_number_list(input_file: str) -> List[int]:\n \"\"\"Read a file of numbers and load the contents in a list\n\n Parameters\n ----------\n input_file : str\n input file\n\n Returns\n -------\n List\n List of integers\n \"\"\"\n content = open(input_file).readlines()\n return [int(num) for num in content]\n\n\nif __name__ == \"__main__\":\n read_number_list(\"data_input.txt\")\n print(compute_product(read_number_list(\"data_input.txt\"), 2))\n print(compute_product(read_number_list(\"data_input.txt\"), 3))\n"} {"doc_id": "25ac7b3a4d8f33dd402f91f95633fb4c", "text": "some_string = 'hello there'\r\nprint(type(some_string))\r\n\r\nuser_name = \"supercoder\"\r\npassword = \"supersecret\"\r\n\r\nlong_string = '''\r\nWOW\r\n0 0\r\n---\r\n\r\n'''\r\nprint('this is your name '+ user_name)\r\nprint('this is your password '+password)\r\nprint(long_string)\r\n\r\nfirst_name = \"Al-hassan\"\r\nlast_name = \"Abdul Rafik\"\r\n\r\nfull_name = first_name + ' ' + last_name\r\nprint(full_name)\r\n\r\n#String Concatenation (adding of strings together)\r\nprint(100)\r\nprint(type(str(100)))\r\nprint(type(int(str(1000))))\r\n\r\n#Escape Sequence \r\nweather = \"It's \\\"kind of\\\" sunny today\"\r\nprint(weather)\r\n\r\n\r\n#Formatted Strings \r\n\r\nname = 'Johnny'\r\nage = 55\r\nprint('hi ' + name + ' you are '+ str(age) + ' years old')\r\n\r\n# or the formaatted way best practice \r\n\r\nprint(f'hi {name}, You are {age} years old')\r\n\r\n#another way of using formatted method \r\n\r\nprint('hi {}. You are {} of age'.format(name,age))\r\n\r\n#String Indexes \r\n\r\nselfish = '0123456789'\r\n # 01234567\r\n#selfish['start', 'end', 'stepover']\r\nprint(selfish[0:5:2])\r\n\r\n# another way reversing using indexes\r\nprint(selfish[::-1])\r\n\r\n##Immutabilty\r\n#strings in python are immutable == they cant be changed \r\n\r\n"} {"doc_id": "25ce4a39ba4ce70c007c1a6f73cd512f", "text": "\"\"\"\nBriefly: The groupby() function takes two arguments: (1) the data to group and\n(2) the function to group it with. \n\nMake an iterator that returns consecutive keys and groups from the iterable.\nThe key is a function computing a key value for each element. If not specified\nor is None, key defaults to an identity function and returns the element\nunchanged. Generally, the iterable needs to already be sorted on the same key\nfunction.\n\nThe operation of groupby() is similar to the uniq filter in Unix. It generates\na break or new group every time the value of the key function changes (which\nis why it is usually necessary to have sorted the data using the same key\nfunction). That behavior differs from SQL\u2019s GROUP BY which aggregates common\nelements regardless of their input order.\n\nThe returned group is itself an iterator that shares the underlying iterable\nwith groupby(). Because the source is shared, when the groupby() object is\nadvanced, the previous group is no longer visible. So, if that data is needed\nlater, it should be stored as a list.\n\"\"\"\n\nimport itertools \n \nL = [(\"a\", 1), (\"a\", 2), (\"b\", 3), (\"b\", 4)] \n \n# Key function \nkey_func = lambda x: x[0] \n \nfor key, group in itertools.groupby(L, key_func): \n print(key + \" :\", list(group))\n\n## a : [('a', 1), ('a', 2)]\n## b : [('b', 3), ('b', 4)]\n\nprint('---------------------------')\n\na_list = [(\"Animal\", \"cat\"), \n (\"Bird\", \"peacock\"),\n (\"Animal\", \"dog\"),\n (\"Bird\", \"pigeon\")] \n\n''' list should be sorted before applying groupby '''\n \nan_iterator = itertools.groupby(a_list, lambda x : x[0]) \n \nfor key, group in an_iterator: \n key_and_group = {key : list(group)} \n print(key_and_group)\n\n## {'Animal': [('Animal', 'cat')]}\n## {'Bird': [('Bird', 'peacock')]}\n## {'Animal': [('Animal', 'dog')]}\n## {'Bird': [('Bird', 'pigeon')]}\n\nprint('---------------------------')\n\n''' using sorted list '''\n\na_list.sort()\nan_iterator = itertools.groupby(a_list, lambda x : x[0]) \n \nfor key, group in an_iterator: \n key_and_group = {key : list(group)} \n print(key_and_group)\n\n## {'Animal': [('Animal', 'cat'), ('Animal', 'dog')]}\n## {'Bird': [('Bird', 'peacock'), ('Bird', 'pigeon')]}\n\n''' Example from Stackoverflow\n\ngroups = []\nuniquekeys = []\nfor k, g in itertools.groupby(data, keyfunc):\n groups.append(list(g)) # Store group iterator as a list\n uniquekeys.append(k)\n\n\nk is the current grouping key, and g is an iterator that you can use to iterate\nover the group defined by that grouping key. In other words, the groupby\niterator itself returns iterators.\n'''\n"} {"doc_id": "261825809d93b938b0c5bd8c5e3b68b6", "text": "# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT license.\n\n\"\"\"\n## Overview\n\nThis part of the documentation covers the __advanced usage__ of Infinibatch by assembling __custom data loading pipelines__.\nBefore you continue, please go through the tutorial on the top-level of the documentation of the `infinibatch` module.\n\nTwo of the main features of Infinibatch are __lazy evaluation__ through the use of __iterators__\nand built-in support for __checkpointing__.\nIn this section, we give an introduction to these features and the basic usage of the Infinibatch iterator library.\n\n\n### Iterators\n\nAs a Python programmer, you are probably familiar with the concept of iterators.\nAccording to the [Python documentation](https://docs.python.org/3.5/glossary.html#term-iterator),\nan iterator is an object representing a stream of data,\nand repeated calls to the iterator's `__next__()` method (or passing it to the built-in function `next()`)\nreturn successive items in the stream.\nIt is important not to confuse an [iterator](https://docs.python.org/3.5/glossary.html#term-iterator)\nwith an [iterable](https://docs.python.org/3.5/glossary.html#term-iterable).\nFor more information on this subject, please follow the links above.\n\nThe Python standard library contains a module of iterators called `itertools`\nthat bears some resembles to Infinibatch.\nInfinibatch differs from `itertools` in two ways:\n\n1. Infinibatch provides iterators specifically for the purpose of creating __randomized batches of data for machine learning__.\n2. All iterators in Infinibatch support __checkpointing__ (see the following section).\n\nInfinibatch iterators are not directly compatible with itertools due to the checkpointing requirement.\n\nInfinibatch enables you to build complex data loaders by combining iterators from this module into a pipeline.\nTo give you a high-level idea of how this is works, we provide a very simple example.\nNote that this example is completely artificial and does not solve any useful task.\nIts only purpose is to demonstrate the behavior of a pipeline of iterators.\nWe provide a more realistic example in a later section.\n\nFirst, we create a small test data set.\n>>> dataset = list(range(6)) # 0, 1, 2, 3, 4, 5\n\nWe can turn this data set into an Infinibatch iterator by wrapping it in a `NativeCheckpointableIterator`.\n>>> it = NativeCheckpointableIterator(dataset) # 0, 1, 2, 3, 4, 5\n\nWe can then transform the data items using a `MapIterator`,\nwhich applies a given function to each individual data item.\nFor example, we can multiply each data item by 2.\n>>> it = MapIterator(it, lambda n: 2 * n) # 0, 2, 4, 6, 8, 10\n\nWe can restructure the data set by batching together pairs of data items into lists using a `FixedBatchIterator`.\n>>> it = FixedBatchIterator(it, batch_size=2) # [0, 2], [4, 6], [8, 10]\n\nUsing another `MapIterator`, we can reduce each of these lists to its second element.\n>>> it = MapIterator(it, lambda l: l[1]) # 2, 6, 10\n\nFinally, we can use the resulting iterator `it` just like any standard Python iterator.\n```py\n>>> for item in it:\n... print(item)\n2\n6\n10\n\n```\n\nBy using iterators, Infinibatch operates in a __lazy__ fashion:\nIt generally doesn't apply operations to an entire data set at once,\nbut rather operates on individual data items on-the-fly as they are consumed.\nWhen used correctly, this allows Infinibatch to have a low start-up time and low memory overhead.\nFor more detail on this, please consult the section on performance considerations below.\n\n\n### Checkpointing\n\nThe main features that sets Infinibatch iterators apart from standard Python iterators is that they support __checkpointing__.\nA checkpoint encapsulates the internal state of an entire pipeline of iterators at a specific point while iterating through a data set.\nOnce you retrieve a checkpoint, you can later use it to reset the pipeline of iterators to the exact state it was in\nwhen the checkpoint was created.\nCheckpoints can easily be serialized and stored to disk using [Pythons `pickle` module](https://docs.python.org/3.5/library/pickle.html).\nInfinibatch's checkpointing feature is particularly useful when you're training large deep neural network models over days or weeks,\nand you want to make sure that, in case your training is interrupted for any reason, __you can pick up your training exactly where you left off__.\n\nThe checkpointing interface consists of two functions `getstate` and `setstate` that are defined in `CheckpointableIterator`,\nthe common base class of all iterators in this module.\nAs the names suggest `getstate` returns a checkpoint object that represents the state of a pipeline at the time the function is called,\nand 'setstate' receives a checkpoint object to reset the state of a pipeline.\n`setstate` also accepts `None`, which resets a pipeline to the __beginning__ of the iteration,\ni.e. the state of the pipeline immediately after its construction.\n\nIt is important to realize that __a checkpoint represents the state of a complete pipeline of iterators__.\nIf you have a pipeline consisting of a sequence of iterators, you only have to call `getstate` on the __last__ iterator in the sequence\nto capture the state of the entire pipeline.\nInternally, this is achieved by recursive calls that traverse the entire data loading pipeline to collect the state of every iterator in it.\nSimilarly, when you want to reset a pipeline to a previous state, you only have to call `setstate` on the __last__ iterator in the pipeline.\n\n\nTo demonstrate this, we recreate the pipeline from the previous section.\n>>> dataset = list(range(6)) # 0, 1, 2, 3, 4, 5\n>>> it = NativeCheckpointableIterator(dataset) # 0, 1, 2, 3, 4, 5\n>>> it = MapIterator(it, lambda n: 2 * n) # 0, 2, 4, 6, 8, 10\n>>> it = FixedBatchIterator(it, batch_size=2) # [0, 2], [4, 6], [8, 10]\n>>> it = MapIterator(it, lambda l: l[1]) # 2, 6, 10\n\nSince `it` behaves just like a standard Python iterator, we can call `next` to retrieve its first element.\n>>> next(it)\n2\n\nWe can now call `getstate` on `it` (which is the last `MapIterator` in the pipeline)\nto get a checkpoint of the internal state of the entire data loading pipeline.\n>>> checkpoint = it.getstate()\n\nNote that the checkpoint represents the internal state of the pipeline after the data item `2` has been retrieved.\nUsing the checkpoint, we can always return to this __exact__ point in the data set.\nTo show this, let's exhaust the iterator by casting it to a list.\n>>> list(it)\n[6, 10]\n\nSince the iterator is now exhausted, calling `next` raises a `StopIteration` exception.\n```\n>>> next(it)\nTraceback (most recent call last):\n ...\nStopIteration\n\n```\n\nWe can now reset the pipeline to the checkpoint using `setstate`.\n>>> it.setstate(checkpoint)\n\nThis recovers the state of the pipeline after the data item `2` has been retrieved.\nThereby, we expect the next element to be `6`.\n>>> next(it)\n6\n\n\n## Types of Iterators\n\nThis section provides a brief overview of the different types of iterators in Infinibatch.\n\n\n### Classes and Factory Functions\n\nMost iterators in this module are implemented as classes that inherit from the abstract base class `CheckpointableIterator`.\nHowever, some iterators (such as the `BlockwiseShuffleIterator`) are simple combinations of other iterators.\nThese iterators are implemented as __factory functions__ that construct a pipeline of iterators\nand return the last iterator in the pipeline.\nFor consistency with class-based iterators,\nwe name these factory function using CamelCase instead of the more pythonic use_of_underscores.\n\n.. todo::\n We currently also have one factory function that actually looks like one: `create_source_iterator`.\n Provide a comment on this describing why that is.\n\n\n### Source Iterators\n\nThere are three iterators that are intended to go at the __beginning__ of a data loading pipeline:\n\n- `InfinitePermutationSourceIterator`:\nThis iterator accepts a list, shuffles it, and yields its elements.\nIt repeats this infinitely, shuffling the list after each pass.\nThereby, __this iterator is infinte and cannot be exhausted__.\nThis iterator is meant to be used as the first iterator in a training scenario\nand supports splitting the data for multi-GPU training.\n- `ChunkedSourceIterator`:\nThis iterator accepts a list and yields its elements.\nIt is meant to be used as the first iterator in an inference or validation scenario\nand supports splitting the data for mult-GPU inference.\n- `NativeCheckpointableIterator`:\nThis iterator wraps a Python iterable and makes it checkpointable.\nIt is mainly intended for demonstration and debugging purposes.\n\n\n### Shuffling\n\n.. todo:: Describe `BufferedShuffleIterator` and `BlockwiseShuffleIterator`.\n\n\n### Batching, SelectMany, and Windowing\n\n.. todo:: Describe `FixedBatchIterator`, `SelectManyIterator`, and `WindowedIterator`.\n\n\n### Mapping\n\n.. todo:: Describe `MapIterator`, `ParallelMapIterator`, `RecurrentIterator`, and `SamplingRandomMapIterator`.\n\n\n### Other Iterators\n\n.. todo:: Describe `ZipIterator`, `PrefetchIterator`, and `BucketedReadaheadBatchIterator`.\n\n\n## Complete Example\n\n.. todo::\n Give a more realistic example following, in broad strokes, the ChunkedDataset including:\n\n - use gzip chunks\n - training pipeline example\n - inference pipeline example\n - pipeline that can do both\n - etc.\n\n## Performance Considerations\n\n.. todo::\n Describe what parameters influence performance measures such as memory usage and start-up time.\n\"\"\"\n\nfrom abc import abstractmethod\nimport collections\nimport copy\nimport gzip\nfrom itertools import cycle, islice\nimport math\nfrom multiprocessing import Pool\nimport os\nfrom queue import Full, Queue\nfrom random import Random\nfrom threading import Thread\nfrom typing import (\n Any,\n Callable,\n Dict,\n Generator,\n Iterable,\n Iterator,\n List,\n Optional,\n Tuple,\n Union,\n)\n\n\nfrom .closablequeue import ClosableQueue, ClosedException\n\n\n# TODO for next release:\n# - benchmark the accuracy when using BlockwiseShuffleIterator vs. the BufferedShuffleIterator\n# - change all convenience functions back to true classes, using a wrapper class\n\n# TODO later:\n# - make iterator pipeline work for streaming data\n\n\ndef _advance_iterator(iterator: Iterator, n: int):\n \"\"\"Little helper to advance an iterator by n items\"\"\"\n for _ in range(n):\n next(iterator)\n return n\n\n\nclass CheckpointableIterator(collections.abc.Iterator):\n \"\"\"\n Abstract base class that defines the interface for checkpointing.\n\n The interface (getstate, setstate) is inspired by Python's random package.\n \"\"\"\n\n def __iter__(self):\n return self\n\n @abstractmethod\n def getstate(self) -> Dict:\n \"\"\"\n Get checkpoint of current state of iterator\n\n In a pipeline of iterators, this function __recursively__ calls itself on the preceeding iterator\n and includes the gathered information in the returned checkpoint.\n Thereby, to obtain a checkpoint of the state of an entire pipeline of iterators\n you only have to call this function on the __last__ iterator in the pipeline.\n A checkpoint is represented as a `dict`,\n but the caller should treat a checkpoint as an opaque object\n and not make any assumptions about the existence or meaning of the `dict` entries.\n \"\"\"\n pass\n\n @abstractmethod\n def setstate(self, checkpoint: Optional[Dict]):\n \"\"\"\n Set state of iterator to given checkpoint\n\n In a pipeline of iterators, this function __recursively__ calls itself on the preceeding iterator.\n Thereby, to set the state of an entire pipeline of iterators to a given checkpoint\n you only have to call this function on the __last__ iterator in the pipeline.\n\n Args:\n checkpoint: Checkpoint that should be used to reset the state of the iterator (or pipeline).\n If this is __None__, the state of the iterator (or pipeline) is reset to the initial\n state immediately after construction.\n \"\"\"\n pass\n\n def __getstate__(self) -> Dict: # implementation of pickle Protocol\n return self.getstate()\n\n def __setstate__(self, checkpoint: Optional[Dict]):\n self.setstate(checkpoint)\n\n @abstractmethod\n def __next__(self):\n pass\n\n\nclass NativeCheckpointableIterator(CheckpointableIterator):\n \"\"\"\n Simple wrapper class that turns a Python Iterable into a CheckpointableIterator\n\n When calling setstate on this class, it simply replays the iterator all the way to the checkpoint one element at a time,\n which makes it generally inefficient.\n\n Warning: This class cannot be used with Iterators (as opposed to Iterables), which have an `__iter__` function that simply returns self, but does not reset.\n \"\"\"\n\n def __init__(self, iterable: Iterable):\n # check whether iterable is iterable or iterator:\n # if the variable iterable contains an iterator, the function __iter__ returns self\n # if the variable iterable is an actual iterator, it should not return self\n if iter(iterable) is iterable:\n raise ValueError(\n \"It looks like you are passing an iterator instead of an iterable. This is not supported and can cause undefined behavior when used with checkpointing.\"\n )\n self._input_iterable = iterable\n self.setstate(None)\n\n def getstate(self) -> Dict:\n return {\"num_items_yielded\": self._num_items_yielded}\n\n def setstate(self, checkpoint: Optional[Dict]):\n self._iterator = iter(self._input_iterable)\n self._num_items_yielded = (\n _advance_iterator(self._iterator, checkpoint[\"num_items_yielded\"])\n if checkpoint is not None\n else 0\n )\n\n def __next__(self):\n item = next(\n self._iterator\n ) # call this before increasing _num_items_yielded to correctly handle the case when a StopIteration exception is thrown\n self._num_items_yielded += 1\n return item\n\n\ndef create_source_iterator(\n source_items: List,\n train: bool = True,\n seed: Optional[int] = None,\n shuffle: bool = True,\n num_instances: int = 1,\n instance_rank: int = 0,\n):\n if not train and shuffle:\n raise ValueError(\"shuffling is not supported when train=False\")\n if train:\n return InfinitePermutationSourceIterator(\n source_items,\n seed=seed,\n shuffle=shuffle,\n num_instances=num_instances,\n instance_rank=instance_rank,\n )\n else:\n return ChunkedSourceIterator(\n source_items, num_instances=num_instances, instance_rank=instance_rank\n )\n\n\ndef ChunkedSourceIterator(\n source_items: List, num_instances: int = 1, instance_rank: int = 0\n):\n \"\"\"\n Cuts source list into chunks, one per instance, and serves out items in chunk corresponding to instance_rank\n\n This is a source iterator:\n It is meant to be used at the beginning of a data loading pipeline.\n As such, it takes a list as its source and not a CheckpointableIterator.\n\n Args:\n source_items: input list, must not be empty and must be small enough to fit into RAM entirely, ownership of the list and the data goes to the iterator, do not modify it!\n num_instances: number of instances of this iterator. Meant for use with multi-process data loading, e.g., in distributed training.\n instance_rank: rank of this instance of the iterator. Meant for use with multi-process data loading, e.g., in distributed training.\n \"\"\"\n # heuristic: assuming blocks are all of the same size, math.ceil should give us the shortest makespan\n chunk_size = math.ceil(len(source_items) / num_instances)\n # this does not cause any out-of-bounds issues:\n # a slice with a start-index beyong the end of the list is empty,\n # and an end-index of a slice is capped at the end of the list\n chunk = source_items[instance_rank * chunk_size : (instance_rank + 1) * chunk_size]\n return NativeCheckpointableIterator(chunk)\n\n\nclass InfinitePermutationSourceIterator(CheckpointableIterator):\n \"\"\"\n Infinitely generates permutations of the items in the given list.\n\n This is a source iterator:\n It is meant to be used at the beginning of a data loading pipeline.\n As such, it takes a list as its source and not a CheckpointableIterator.\n The given list is loaded completely into RAM.\n\n For example, this is used for randomizing the pathnames of data blocks read by ChunkedReadlinesIterator.\n \"\"\"\n\n def __init__(\n self,\n source_items: List,\n seed: Optional[int] = None,\n shuffle: bool = True,\n num_instances: int = 1,\n instance_rank: int = 0,\n ):\n \"\"\"\n Args:\n source_items: input list, must not be empty and must be small enough to fit into RAM entirely, ownership of the list and the data goes to the iterator, do not modify it!\n seed: random seed used for shuffling (or None)\n shuffle: set False to bypass the shuffling. Then this is just a checkpointed version of itertools.cycle(). (Default: True)\n num_instances: number of instances of this iterator. Meant for use with multi-process data loading, e.g., in distributed training.\n instance_rank: rank of this instance of the iterator. Meant for use with multi-process data loading, e.g., in distributed training.\n \"\"\"\n self._source_items = source_items\n if not self._source_items:\n raise ValueError(\"InfinitePermutationIterator: source must not be empty\")\n self._shuffle = shuffle\n self._seed = seed\n self._num_instances = num_instances\n self._instance_rank = instance_rank\n self.setstate(None)\n\n def getstate(self) -> Dict:\n return {\n \"random_state\": self._random_state, # state of random generator before generating the current shuffling of the sequence\n \"num_items_yielded\": self._num_items_yielded,\n } # how many items have already been iterated over in the current shuffling\n\n def setstate(self, checkpoint: Optional[Dict]):\n # set iteration state. Do this outside the generator below in case getstate() is called before ever iterating\n self._random_state = checkpoint[\"random_state\"] if checkpoint else None\n self._num_items_yielded = checkpoint[\"num_items_yielded\"] if checkpoint else 0\n # We define the iteration itself as a generator for ease of implementation.\n # We could as well just have used an explicit state machine represented by class members.\n def _generate() -> Iterator:\n # create and reset random generator\n random = Random(self._seed)\n if self._random_state is not None: # restore the random generator's state\n random.setstate(self._random_state)\n skip_to_checkpoint = (\n self._num_items_yielded\n ) # items to skip in order to advance to checkpoint\n # main outer loop for infinite passes over items (reshuffle before each pass)\n while True:\n # (re-)shuffle all items\n self._random_state = (\n random.getstate()\n ) # remember random state before shuffling\n self._num_items_yielded = 0\n shuffled_items = self._source_items[\n :\n ] # note: if underlying iterator is checkpointable, use setstate(checkpoint['nested_state']) on it\n if self._shuffle:\n random.shuffle(shuffled_items)\n shuffled_iterator = iter(shuffled_items)\n # skip initial items when restarting from checkpoint\n if (\n skip_to_checkpoint\n ): # @TODO: find a way to abstract this more, so that we can plug it into the 'for' statement directly\n self._num_items_yielded += _advance_iterator(\n shuffled_iterator, skip_to_checkpoint\n )\n skip_to_checkpoint = 0 # done skipping\n # main inner loop over items\n for item in shuffled_iterator:\n self._num_items_yielded += 1 # record how many items we have iterated over in this pass over the items\n if (\n self._num_items_yielded - 1\n ) % self._num_instances == self._instance_rank: # build-in islice facility\n yield item\n\n self._iterator = _generate()\n\n def __next__(self):\n return next(self._iterator)\n\n\nclass SelectManyIterator(CheckpointableIterator):\n \"\"\"\n Projects each element of a source sequence to a sequence and flattens the resulting sequences into one sequence.\n \"\"\"\n\n def __init__(\n self,\n source_iterator: CheckpointableIterator,\n collection_selector: Optional[Callable[[Any], Iterator]] = None,\n ):\n \"\"\"\n Args:\n source_iterator: iterator over the items to pass to collection_selector()\n collection_selector: user callback that maps an item into an Iterable, whose items will be yielded.\n The returned Iterator is used only once. Hence, it is also allowed to\n return self-iterables, such as iterators and generator expressions.\n If None is given, no callback is applied.\n \"\"\"\n if not isinstance(source_iterator, CheckpointableIterator):\n raise ValueError(\"source_iterator has to be a CheckpointableIterator\")\n self._source_iterator = source_iterator # type: CheckpointableIterator\n self._collection_selector = (\n collection_selector\n ) # type: Callable[[Any], Iterator]\n self.setstate(None)\n\n def getstate(self) -> Dict:\n return {\n \"source_state\": self._source_state,\n \"flattened_items_yielded\": self._flattened_items_yielded,\n }\n\n def setstate(self, checkpoint: Optional[Dict]):\n self._source_state = checkpoint[\"source_state\"] if checkpoint else None\n self._flattened_items_yielded = (\n checkpoint[\"flattened_items_yielded\"] if checkpoint else 0\n )\n self._source_iterator.setstate(self._source_state)\n\n def _generate():\n skip_to_checkpoint = self._flattened_items_yielded\n # main loop over source source_items\n for source_item in self._source_iterator:\n if self._collection_selector is not None:\n data = iter(self._collection_selector(source_item))\n else:\n data = iter(source_item)\n self._flattened_items_yielded = 0\n if skip_to_checkpoint:\n # print(\"Skipping to index\", skip_to_checkpoint, file=sys.stderr)\n self._flattened_items_yielded += _advance_iterator(\n data, skip_to_checkpoint\n )\n skip_to_checkpoint = 0\n # main loop over lines\n for item in data:\n self._flattened_items_yielded += 1\n yield item\n self._source_state = self._source_iterator.getstate()\n\n self._iterator = _generate()\n\n def __next__(self):\n return next(self._iterator)\n\n\nclass BufferedShuffleIterator(CheckpointableIterator):\n \"\"\"\n Shuffles given iterable using a limited buffer.\n \"\"\"\n\n def __init__(\n self, source_iterator: CheckpointableIterator, buffer_size: int, seed: int = 0\n ):\n \"\"\"\n Args:\n source_iterator: checkpointable iterator or restartable iterable over input items to shuffle\n buffer_size: size of the buffer in number of items used for shuffling\n seed: random seed used for shuffling (or None)\n \"\"\"\n if not isinstance(source_iterator, CheckpointableIterator):\n raise ValueError(\"source_iterator has to be a CheckpointableIterator\")\n self._source_iterator = source_iterator\n self._buffer = [\n None for _ in range(buffer_size)\n ] # maybe do this lazily? --Yes, since user may set state immediately, then this is not needed here\n self._random = Random(seed)\n self.setstate(None)\n\n def getstate(self) -> Dict:\n return {\n \"source_state\": self._source_iterator.getstate(),\n \"buffer\": copy.deepcopy(self._buffer),\n \"random_state\": self._random.getstate(),\n }\n\n def setstate(self, checkpoint: Optional[Dict]):\n if checkpoint:\n self._source_iterator.setstate(checkpoint[\"source_state\"])\n self._buffer = checkpoint[\"buffer\"]\n self._random.setstate(checkpoint[\"random_state\"])\n # @TODO: Can we add a comment how the flush part is handled?\n else:\n self._source_iterator.setstate(None)\n self._iterator = self._generate()\n\n def _generate(self) -> Iterator:\n # shuffle data with a buffer:\n # this is similar to what the Fisher-Yates shuffle does,\n # but modified to run with a constant-size buffer\n # see https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle\n # this was inspired by an algorithm implemented in Kaldi\n # see https://kaldi-asr.org/doc/nnet-shuffle-egs_8cc.html\n for item in self._source_iterator:\n index = self._random.randrange(0, len(self._buffer))\n result = None\n if self._buffer[index] is not None:\n result = self._buffer[index]\n self._buffer[index] = item\n # only yield value once buffer is updated to allow for correct checkpointing!\n if result is not None:\n yield result\n\n # flush buffer\n while self._buffer:\n item = self._buffer.pop()\n if item is not None:\n yield item\n\n def __next__(self):\n return next(self._iterator)\n\n\nclass MapIterator(CheckpointableIterator):\n \"\"\"\n Applies given tranform to each data item\n \"\"\"\n\n def __init__(\n self, source_iterator: CheckpointableIterator, transform: Callable[[str], Any]\n ):\n \"\"\"\n Args:\n source_iterator: checkpointable iterator\n transform: function to be applied to each data item\n \"\"\"\n if not isinstance(source_iterator, CheckpointableIterator):\n raise ValueError(\"source_iterator has to be a CheckpointableIterator\")\n self._source_iterator = source_iterator\n self._transform = transform\n\n def getstate(self) -> Dict:\n return self._source_iterator.getstate()\n\n def setstate(self, checkpoint: Optional[Dict]):\n self._source_iterator.setstate(checkpoint)\n\n def __next__(self):\n return self._transform(next(self._source_iterator))\n\n\ndef ParallelMapIterator(\n source_iterator: CheckpointableIterator,\n transform: Callable[[str], Any],\n num_processes: int,\n num_items_per_process: int,\n):\n \"\"\"\n Applies given transform to each data item\n\n Behaves the same as MapIterator, but applies transform in parallel using multiple processes in a parallel map operation.\n\n Warning:\n The transform function has to be pickleable because it is sent across process boundaries.\n To achieve this, transform should be a top-level function.\n\n Args:\n source_iterator: checkpointable iterator\n transform: function to be applied to each data item, has to be pickleable, see above\n num_processes: number of processes to use for parallel map\n num_items_per_process: number of data items each process operates on\n \"\"\"\n # divide stream of data items into batches\n batched_samples = FixedBatchIterator(\n source_iterator, num_processes * num_items_per_process\n )\n # create process pool and capture it in closure that performs parallel map\n p = Pool(num_processes)\n\n def parallel_map_transform(buffer):\n return p.map(transform, buffer)\n\n # apply transform in parallel to data items in a batch\n batched_transformed_samples = MapIterator(batched_samples, parallel_map_transform)\n # unpack batches to go back to stream of (now transformed) data items\n transformed_samples = SelectManyIterator(batched_transformed_samples)\n return transformed_samples\n\n\nclass ZipIterator(CheckpointableIterator):\n \"\"\"\n Zips items from all given iterators, like the Python standard function zip().\n\n Like Python's build-in zip(), the iteration stops when the shortest input iterable is exhausted.\n \"\"\"\n\n def __init__(self, *source_iterators: CheckpointableIterator):\n \"\"\"\n Args:\n source_iterators: list of iterators to zip, item by item\n \"\"\"\n for source_iterator in source_iterators:\n if not isinstance(source_iterator, CheckpointableIterator):\n raise ValueError(\n \"all iterators in source_iterators have to be CheckpointableIterator\"\n )\n self._source_iterators = source_iterators # type: List[CheckpointableIterator]\n\n def getstate(self) -> Dict:\n return {\n \"input_states\": tuple(\n iterator.getstate() for iterator in self._source_iterators\n )\n }\n\n def setstate(self, checkpoint: Optional[Dict]):\n if checkpoint is None:\n for iterator in self._source_iterators:\n iterator.setstate(None)\n else:\n for iterator, state in zip(\n self._source_iterators, checkpoint[\"input_states\"]\n ):\n iterator.setstate(state)\n\n def __next__(self):\n res = (\n []\n ) # (note: can't use a generator expression, as it gets confused when a next() call raises StopIteration)\n for iterator in self._source_iterators:\n res.append(next(iterator))\n return tuple(res)\n\n\n# @TODO: The yield makes a (shallow) copy of the window, which has complexity O(width * length). In some cases,\n# we don't actually need to consume all items in the window. Hence, to make this faster, we should use\n# double-buffering and return a slice view (which we'd have to write).\nclass WindowedIterator(CheckpointableIterator):\n \"\"\"\n Yields 'width' consecutive items in a sliding window.\n\n E.g. [1, 2, 3, 4, 5, 6] with width = 3 will yield\n [[1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5, 6]]\n \"\"\"\n\n def __init__(self, source_iterator: CheckpointableIterator, width: int):\n \"\"\"\n Args:\n source_iterator: checkpointable input iterators\n \"\"\"\n if not isinstance(source_iterator, CheckpointableIterator):\n raise ValueError(\"source_iterator has to be a CheckpointableIterator\")\n self._source_iterator = source_iterator # type: CheckpointableIterator\n self._width = width # type: int\n self.setstate(None)\n\n def getstate(self) -> Dict:\n return {\n \"source_state\": self._source_state, # state for first item in FIFO\n \"item_index\": self._item_index,\n } # index of next item to serve\n\n def setstate(self, checkpoint: Optional[Dict]):\n self._source_state = checkpoint[\"source_state\"] if checkpoint else None\n self._item_index = checkpoint[\"item_index\"] if checkpoint else 0\n self._source_iterator.setstate(self._source_state)\n self._iterator = self._generate()\n\n def _fifo_slice(self, i): # returns a window into the FIFO beginning at i\n # @TODO: for efficiency, make this a slice view\n return tuple(self._fifo[i : i + self._width])\n\n def _generate(self) -> Iterator:\n self._source_state = self._source_iterator.getstate()\n self._fifo = list(islice(self._source_iterator, self._width))\n # we do this in overlapping blocks of length 2*width, for easier checkpointing and potential efficiency\n while len(self._fifo) == self._width:\n # we got 'width' items; append another 'width' (or less if at end)\n next_input_state = self._source_iterator.getstate()\n self._fifo.extend(islice(self._source_iterator, self._width))\n # now serve all positions in first half (last = width - 1). If at end, then limit accordingly.\n last = min(self._width - 1, len(self._fifo) - self._width)\n while self._item_index <= last:\n window = self._fifo_slice(self._item_index)\n self._item_index += 1\n yield window\n # drop all we just served; if < width left, we have hit the end\n self._fifo = self._fifo[\n last + 1 :\n ] # Note: This must be a new list, since the old might still be in a slice view.\n self._source_state = (\n next_input_state # this reflects now the first element in the FIFO\n )\n self._item_index = 0\n\n def __next__(self):\n return next(self._iterator)\n\n\n# @TODO: research on whether this operation has a well-known name\nclass FixedBatchIterator(CheckpointableIterator):\n \"\"\"\n Batches N consecutive items into a single item that is a list of these items.\n\n E.g. [1, 2, 3 4, 5, 6, 7, 8] with batch_size = 3 will yield\n [(1, 2, 3), (4, 5, 6), (7, 8)]\n \"\"\"\n\n def __init__(self, source_iterator: CheckpointableIterator, batch_size: int):\n \"\"\"\n Args:\n source_iterator: checkpointable input iterators\n batch_size: number of items per batch\n \"\"\"\n if not isinstance(source_iterator, CheckpointableIterator):\n raise ValueError(\"source_iterator has to be a CheckpointableIterator\")\n self._source_iterator = source_iterator # type: CheckpointableIterator\n self._batch_size = batch_size # type: int\n self.setstate(None)\n\n def getstate(self) -> Dict:\n return {\n \"source_state\": self._source_iterator.getstate()\n } # state for first item in next batch\n\n def setstate(self, checkpoint: Optional[Dict]):\n self._source_state = checkpoint[\"source_state\"] if checkpoint else None\n self._source_iterator.setstate(self._source_state)\n self._iterator = self._generate()\n\n def _generate(self) -> Iterator:\n while True:\n batch = list(islice(self._source_iterator, self._batch_size))\n if not batch:\n break\n yield batch\n\n def __next__(self):\n return next(self._iterator)\n\n\nclass RandomIterator(CheckpointableIterator):\n \"\"\"\n Iterator to generate uniformly distributed random numbers in the interval [0,1).\n Very similar to Random.random(), except that random numbers are\n obtained via next().\n \"\"\"\n\n def __init__(self, seed: Optional[int] = None):\n \"\"\"\n Args:\n seed: Random seed.\n \"\"\"\n self._random = Random() # type: Random\n if seed is not None:\n self._random.seed(seed)\n\n def getstate(self) -> Dict:\n return {\"random_state\": self._random.getstate()}\n\n def setstate(self, checkpoint: Optional[Dict]):\n self._random.setstate(checkpoint[\"random_state\"] if checkpoint else None)\n\n def __next__(self):\n return self._random.random()\n\n\nclass RecurrentIterator(CheckpointableIterator):\n \"\"\"\n Iterates statefully over a step function. The step function accepts a state and a new item,\n and returns a new state and an output item, which is yielded.\n \"\"\"\n\n def __init__(\n self,\n source_iterator: CheckpointableIterator,\n step_function: Callable[[Any, Any], Tuple[Any, Any]],\n initial_state: Any = None,\n ):\n \"\"\"\n Args:\n source_iterator: checkpointable iterator to recur over\n step_function: user-supplied function with signature step_function(state, item) -> (new_state, output)\n initial_state: initial state to be passed to the step_function upon first invocation\n \"\"\"\n if not isinstance(source_iterator, CheckpointableIterator):\n raise ValueError(\"source_iterator has to be a CheckpointableIterator\")\n self._source_iterator = source_iterator # type: CheckpointableIterator\n self._step_function = step_function # type: Callable[[Any,Any], Tuple[Any,Any]]\n self._initial_state = initial_state # type: Any\n self.setstate(None)\n\n def getstate(self):\n return {\n \"recurrent_state\": self._recurrent_state,\n \"source_state\": self._source_iterator.getstate(),\n }\n\n def setstate(self, checkpoint):\n self._recurrent_state = (\n checkpoint[\"recurrent_state\"] if checkpoint else self._initial_state\n )\n self._source_iterator.setstate(\n checkpoint[\"source_state\"] if checkpoint else None\n )\n\n def _generate():\n for item in self._source_iterator:\n self._recurrent_state, output = self._step_function(\n self._recurrent_state, item\n )\n yield output\n\n self._iterator = _generate()\n\n def __next__(self):\n return next(self._iterator)\n\n\ndef SamplingRandomMapIterator(\n source_iterator: CheckpointableIterator,\n transform: Callable[[Random, Any], Any],\n seed: Optional[int] = None,\n):\n \"\"\"\n An iterator that calls a transform function on each item, while also passing a checkpointed\n random generator.\n\n Args:\n source_iterator: checkpointable iterator to recur over\n step_function: user-supplied function with signature step_function(random, item) -> result_item\n seed: random seed\n \"\"\"\n _random = Random()\n if seed is not None:\n _random.seed(seed)\n\n def _step_function(state, item):\n _random.setstate(state)\n output = transform(_random, item)\n return _random.getstate(), output\n\n return RecurrentIterator(\n source_iterator, _step_function, initial_state=_random.getstate()\n )\n\n\ndef BlockwiseShuffleIterator(\n source_iterator: CheckpointableIterator, block_size: int, seed: int = 0\n):\n \"\"\"\n Shuffles a sequence of items by grouping consecutive items in blocks of fixed size, shuffling\n each block, and yielding the shuffled items of all blocks as a flat sequence.\n\n E.g. [1, 2, 3, 4, 5, 6, 7, 8] with block_size = 3 may yield [3, 1, 2, 4, 6, 5, 8, 7].\n\n Args:\n source_iterator: checkpointable iterator or restartable iterable over input items to shuffle\n block_size: size of the buffer in number of items used for shuffling\n seed: random seed used for shuffling (or None)\n \"\"\"\n # This is implemented as a pipeline:\n # - group N consecutive items together\n # - shuffle them\n # - flatten the result\n blocks = FixedBatchIterator(source_iterator, batch_size=block_size)\n\n def shuffle_block_fn(random: Random, block: List):\n random.shuffle(block)\n return block\n\n shuffled_blocks = SamplingRandomMapIterator(\n blocks, transform=shuffle_block_fn, seed=seed\n )\n samples = SelectManyIterator(\n shuffled_blocks, collection_selector=lambda shuffled_block: iter(shuffled_block)\n )\n return samples\n\n\nclass PrefetchIterator(CheckpointableIterator):\n \"\"\"\n An iterator prefetching data into a buffer on a seperate thread to smooth out IO latency.\n\n Args:\n source_iterator: checkpointable iterator to recur over\n buffer_size: size of the queue between the threads\n \"\"\"\n\n def __init__(\n self, source_iterator: CheckpointableIterator, buffer_size: int = 1000\n ):\n if not isinstance(source_iterator, CheckpointableIterator):\n raise ValueError(\"source_iterator has to be a CheckpointableIterator\")\n self._source_iterator = source_iterator # type:CheckpointableIterator\n self._buffer_size = buffer_size # type: int\n self._queue = None # type: Optional[ClosableQueue]\n self._thread = None # type: Optional[Thread]\n self.setstate(None)\n\n def getstate(self) -> Dict:\n return {\"source_state\": self._source_state, \"item_offset\": self._item_offset}\n\n def setstate(self, checkpoint: Optional[Dict]):\n if (\n self._thread is not None\n ): # if there is a prefetching thread running, close the queue and wait for the thread to terminate\n assert self._queue is not None\n self._queue.close()\n self._thread.join()\n\n self._source_state = (\n checkpoint[\"source_state\"] if checkpoint is not None else None\n )\n self._item_offset = checkpoint[\"item_offset\"] if checkpoint is not None else 0\n\n self._source_iterator.setstate(self._source_state)\n\n self._queue = ClosableQueue(maxsize=self._buffer_size) # clear queue\n # make thread daemonic so it is killed when the main program terminates\n self._thread = Thread(\n target=self._prefetch_thread_fn,\n args=(\n self._source_iterator,\n self._item_offset,\n self._buffer_size,\n self._queue,\n ),\n daemon=True,\n )\n self._thread.start()\n\n @staticmethod\n def _prefetch_thread_fn(\n source, item_offset, buffer_size, queue\n ): # behavior of the prefetching thread, only call from that thread!\n _advance_iterator(source, item_offset) # skip to checkpoint\n\n while True:\n try:\n item = next(source)\n except StopIteration:\n queue.close()\n return\n\n if (\n item_offset == buffer_size - 1\n ): # send a new source state a the END of each window of length _buffer_size\n source_state = (\n source.getstate()\n ) # this is the state for retrieving the NEXT element, i.e. the first element of the next buffer\n item_offset = 0\n else:\n source_state = None\n item_offset += 1\n msg = (item, source_state)\n\n try:\n queue.put(msg)\n except ClosedException:\n return\n\n def __next__(self):\n try:\n msg = self._queue.get()\n except ClosedException:\n raise StopIteration\n\n item, prefetch_source_state = msg\n if prefetch_source_state is not None:\n assert (\n self._item_offset == self._buffer_size - 1\n ) # we expect a new source state at then END of each window of length _buffer_size\n self._source_state = prefetch_source_state\n self._item_offset = 0\n else:\n self._item_offset = self._item_offset + 1\n assert self._item_offset < self._buffer_size\n return item # for debugging, its useful to return msg instead of item\n\n def __del__(\n self,\n ): # note: this is often not called. If you really need it, gc.collect() will do the trick.\n if self._thread is not None:\n assert self._queue is not None\n self._queue.close()\n try:\n self._thread.join()\n except:\n pass\n\n\nclass BucketedReadaheadBatchIterator(CheckpointableIterator):\n \"\"\"\n Iterates over items from a checkpointable iterator and groups items of similar length into batches.\n\n The algorithm reads a head a certain number of lines (e.g. 10 million), sorts them by\n length, and them groups them into batches from start to end. The sort is stable, such\n that prior randomization is not undone (except for the length grouping). The batch size\n is dynamic, and determined by a user-provided callback.\n\n This is based on Marian NMT's BatchGenerator.\n \"\"\"\n\n def __init__(\n self,\n source_iterator: CheckpointableIterator,\n read_ahead: int,\n key: Callable[[Any], Any],\n batch_size: Union[int, Callable[[Any], int]],\n shuffle: bool = True,\n seed: Optional[int] = None,\n ):\n \"\"\"\n Args:\n source_iterator: The data set that is read from. Typically this is an infinite source.\n read_ahead: Number of items to fetch ahead for grouping purposes.\n key: User-provided callback to define how data is sorted for purpose of batching.\n batch_size: Batch size in number of items. Either an integer or a callback to determine batch size for a given first batch item.\n shuffle: Pass False to not randomize the batches. (default: True)\n seed: Random seed for batch shuffling.\n \"\"\"\n if not isinstance(source_iterator, CheckpointableIterator):\n raise ValueError(\"source_iterator has to be a CheckpointableIterator\")\n # keep arguments\n self._key = key # type: Callable[[Any], Any]\n self._batch_size = batch_size # type: Union[int,Callable[[Any], int]]\n self._read_ahead = read_ahead # type: int\n # initialize state\n self._random = None\n if shuffle:\n self._random = Random() # type: Random\n if seed is not None:\n self._random.seed(seed)\n self._source_iterator = iter(source_iterator) # type: CheckpointableIterator\n self.setstate(None)\n\n def getstate(self):\n return {\n \"source_state\": self._source_state,\n \"random_state\": self._random_state,\n \"num_served\": self._num_batches_yielded,\n }\n\n def setstate(self, checkpoint: Optional[Dict]):\n self._source_state = (\n checkpoint[\"source_state\"] if checkpoint else None\n ) # type: Dict -- state of input before reading the current set of batches\n self._random_state = (\n checkpoint[\"random_state\"] if checkpoint else None\n ) # type: Any -- state of random generator at _source_state\n self._num_batches_yielded = (\n checkpoint[\"num_served\"] if checkpoint else 0\n ) # type: int -- number of batches served from the current set of batches\n # checkpointing: restore to start of current set of batches\n self._source_iterator.setstate(self._source_state)\n if self._random_state:\n self._random.setstate(self._random_state)\n self._source_exhausted = (\n False\n ) # type: bool -- set to True once we hit StopIteration on source\n\n def _generate():\n skip_to_checkpoint = self._num_batches_yielded\n source_exhausted = False\n while not source_exhausted:\n # prefetch the readahead buffer\n self._source_state = self._source_iterator.getstate()\n self._random_state = self._random.getstate() if self._random else None\n items = list(islice(self._source_iterator, self._read_ahead))\n source_exhausted = len(items) < self._read_ahead\n # create batches\n batches = self._create_batches(items)\n # shuffle the batches\n if self._random:\n self._random.shuffle(batches)\n # on first loop iteration, restore iterator inside batches from checkpoint\n batches = iter(batches)\n self._num_batches_yielded = _advance_iterator(\n batches, skip_to_checkpoint\n )\n skip_to_checkpoint = 0\n # main loop over batches in current read-ahead section\n for batch in batches:\n self._num_batches_yielded += 1\n yield batch\n\n self._iterator = (\n _generate()\n ) # type: Iterator -- iterator into current set of batches\n\n def _create_batches(\n self, items: List[Any]\n ) -> List[List[Any]]: # helper to form batches from a list of items\n # sort by length, longest first\n if self._key:\n items.sort(\n key=self._key, reverse=True\n ) # note: sort() is stable, so we won't undo any randomization besides the bucketing\n # group into batches\n cur_batch = None\n batches = []\n for item in items:\n if not cur_batch:\n batch_size = (\n self._batch_size\n if isinstance(self._batch_size, int)\n else self._batch_size(item)\n )\n cur_batch = []\n cur_batch.append(item)\n if len(cur_batch) >= batch_size: # this batch is full\n batches.append(cur_batch)\n cur_batch = None\n if cur_batch:\n batches.append(cur_batch)\n return batches\n\n def __next__(self):\n return next(self._iterator)\n"} {"doc_id": "2622b52173ae027bde1f1edd354a29b7", "text": "'''\n04 - Explore the LED digits dataset\n\nIn the following exercises, you'll use NMF to decompose grayscale images into \ntheir commonly occurring patterns. Firstly, explore the image dataset and see \nhow it is encoded as an array. You are given 100 images as a 2D array samples, \nwhere each row represents a single 13x8 image. The images in your dataset are \npictures of a LED digital display.\n\nINSTRUCTIONS:\n\n- Import matplotlib.pyplot as plt.\n- Select row 0 of samples and assign the result to digit. For example, to select\n column 2 of an array a, you could use a[:,2]. Remember that since samples is a \n NumPy array, you can't use the .loc[] or iloc[] accessors to select specific \n rows or columns.\n- Print digit. This has been done for you. Notice that it is a 1D array of 0s and 1s.\n- Use the .reshape() method of digit to get a 2D array with shape (13, 8). Assign the\n result to bitmap.\n- Print bitmap, and notice that the 1s show the digit 7!\n- Use the plt.imshow() function to display bitmap as an image.\n'''\n# Import pyplot\nfrom matplotlib import pyplot as plt\n\n# Select the 0th row: digit\ndigit = samples[0,:]\n\n# Print digit\nprint(digit)\n\n# Reshape digit to a 13x8 array: bitmap\nbitmap = digit.reshape(13, 8)\n\n# Print bitmap\nprint(bitmap)\n\n# Use plt.imshow to display bitmap\nplt.imshow(bitmap, cmap='gray', interpolation='nearest')\nplt.colorbar()\nplt.show()\n\n'''\n output:\n [0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 1. 1. 1. 1. 0. 0. 0. 0. 0. 0. 0. 0. 1. 0.\n 0. 0. 0. 0. 0. 0. 1. 0. 0. 0. 0. 0. 0. 0. 1. 0. 0. 0. 0. 0. 0. 0. 1. 0.\n 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 1. 0. 0. 0. 0. 0. 0. 0. 1. 0.\n 0. 0. 0. 0. 0. 0. 1. 0. 0. 0. 0. 0. 0. 0. 1. 0. 0. 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. 0. 0.]\n [[0. 0. 0. 0. 0. 0. 0. 0.]\n [0. 0. 1. 1. 1. 1. 0. 0.]\n [0. 0. 0. 0. 0. 0. 1. 0.]\n [0. 0. 0. 0. 0. 0. 1. 0.]\n [0. 0. 0. 0. 0. 0. 1. 0.]\n [0. 0. 0. 0. 0. 0. 1. 0.]\n [0. 0. 0. 0. 0. 0. 0. 0.]\n [0. 0. 0. 0. 0. 0. 1. 0.]\n [0. 0. 0. 0. 0. 0. 1. 0.]\n [0. 0. 0. 0. 0. 0. 1. 0.]\n [0. 0. 0. 0. 0. 0. 1. 0.]\n [0. 0. 0. 0. 0. 0. 0. 0.]\n [0. 0. 0. 0. 0. 0. 0. 0.]]\n'''\n"} {"doc_id": "263aec149f07caca391fdd0cce3f7ee5", "text": "'''\nYou start at the cell (rStart, cStart) of an rows x cols grid facing east. The northwest corner is at the first row and column in the grid, and the southeast corner is at the last row and column.\n\nYou will walk in a clockwise spiral shape to visit every position in this grid. Whenever you move outside the grid's boundary, we continue our walk outside the grid (but may return to the grid boundary later.). Eventually, we reach all rows * cols spaces of the grid.\n\nReturn an array of coordinates representing the positions of the grid in the order you visited them.\n\n \n '''\n\nExplanation\nStarting with a step length of 1, move one time to right, then turn; move one time to below\nIncrease step length, 1 + 1 = 2, move 2 times to left, then turn; move 2 times to above\nSo, for each step length, we will move step for 2 directions, then increase step by one; and repeat\nTo summarize:\nStep == 1, move*step, turn, move*step, turn\nStep += 1, move*step, turn, move*step, turn\nStep += 1, move*step, turn, move*step, turn\n... ... repeat\nImplementation\nclass Solution:\n def spiralMatrixIII(self, rows: int, cols: int, rStart: int, cStart: int) -> List[List[int]]:\n total, cnt, step, i = rows * cols, 1, 1, 0\n ans = [[rStart, cStart]]\n direction = {0: (0, 1), 1: (1, 0), 2: (0, -1), 3: (-1, 0)} # setup direction movements\n while cnt < total:\n for k in range(step):\n rStart, cStart = rStart+direction[i][0], cStart + direction[i][1]\n if 0 <= rStart < rows and 0 <= cStart < cols:\n ans.append([rStart, cStart])\n cnt += 1 # count visited \n i = (i + 1) % 4 # changing direction\n step += not i % 2 # increase step every 2 directions\n return ans\n \n-------------------------------------------------\n\nclass Solution:\n def spiralMatrixIII(self, rows: int, cols: int, rStart: int, cStart: int) -> List[List[int]]:\n ans = [[rStart, cStart]]\n val = 1\n i, j = rStart, cStart\n def is_valid(i, j):\n if 0 <= i < rows and 0 <= j < cols:\n return True\n return False\n \n while True:\n if len(ans) == rows * cols:\n return ans\n \n # go right val times\n for _ in range(val):\n j+=1\n if is_valid(i,j):\n ans.append([i,j])\n # go bottom val times\n for _ in range(val):\n i+=1\n if is_valid(i,j):\n ans.append([i,j])\n # go left val+1 times\n for _ in range(val+1):\n j-=1\n if is_valid(i,j):\n ans.append([i,j])\n # go up val+1 times\n for _ in range(val+1):\n i-=1\n if is_valid(i,j):\n ans.append([i,j])\n val+=2\n"} {"doc_id": "26547e560ac4566e79a28ad7dbdf2351", "text": "import numpy as np\r\nfrom math import pi\r\n\r\n\r\nclass Haversine:\r\n \"\"\"\r\n The Haversine class is used to calculate the haversine distance between two geolocation points denoted by\r\n latitude and longitude.\r\n\r\n The haversine function returns the distance between two points on the surface of a sphere, such as the earth.\r\n\r\n This class receives two pairs of coordinates and returns a class object with attributes for the\r\n haversine distance available in kilometers and miles.\r\n\r\n Example::\r\n\r\n distances = Haversine(lat_1, lat_2, lon_1, lon_2)\r\n distances.miles\r\n \"\"\"\r\n\r\n def __init__(self, lat_1, lat_2, lon_1, lon_2):\r\n \"\"\"\r\n\r\n :param lat_1: Latitude for location 1\r\n :param lat_2: Latitude for location 2\r\n :param lon_1: Longitude for location 1\r\n :param lon_2: Longitude for location 2\r\n \"\"\"\r\n\r\n R = 6371000 # Radius of earth\r\n\r\n phi_1 = lat_1 * (pi / 180)\r\n phi_2 = lat_2 * (pi / 180)\r\n\r\n delta_phi = (lat_2 - lat_1) * (pi / 180)\r\n delta_lambda = (lon_2 - lon_1) * (pi / 180)\r\n\r\n a = (np.sin(delta_phi / 2) * np.sin(delta_phi / 2)) + \\\r\n (np.cos(phi_1) * np.cos(phi_2)) * \\\r\n (np.sin(delta_lambda / 2) * np.sin(delta_lambda / 2))\r\n\r\n c = 2 * np.arctan2(np.sqrt(a), np.sqrt(1 - a))\r\n\r\n d = R * c # Distance in meters\r\n\r\n self.km = d / 1000 # Conversion to kilometers\r\n self.miles = d * 0.000621371 # Conversion to miles\r\n"} {"doc_id": "26a5373cf5cd523665fd02d3aecb882d", "text": "\"\"\"\n Author: shikechen\n Function: Check password strength\n Version: 1.0\n Date: 2019/2/1\n\"\"\"\n\n\ndef check_number_exist(password_str):\n for n in password_str:\n if n.isnumeric():\n return True\n return False\n\n\ndef check_letter_exist(password_str):\n for l in password_str:\n if l.isalpha():\n return True\n return False\n\n\ndef main():\n password = input('Input password: ')\n\n strength_level = 0\n\n # Rule 1: length >= 8\n if len(password) >= 8:\n strength_level += 1\n else:\n print('Password length too short, at least 8 digits')\n\n # Rule 2: contain number\n if check_number_exist(password):\n strength_level += 1\n else:\n print('Password must be contain number')\n\n # Rule 3: contain letter\n if check_letter_exist(password):\n strength_level += 1\n else:\n print('Password must be contain letter')\n\n if strength_level == 3:\n print('Password OK')\n else:\n print('Sorry')\n\n\nif __name__ == '__main__':\n main()\n"} {"doc_id": "26c5d74a348365f00ffc141ab58302b4", "text": "#!/usr/bin/env python\n\"\"\"\n--- Day 21: Scrambled Letters and Hash ---\n\nThe computer system you're breaking into uses a weird scrambling function to store its passwords. It shouldn't be much trouble to create your own scrambled password so you can add it to the system; you just have to implement the scrambler.\n\nThe scrambling function is a series of operations (the exact list is provided in your puzzle input). Starting with the password to be scrambled, apply each operation in succession to the string. The individual operations behave as follows:\n\n swap position X with position Y means that the letters at indexes X and Y (counting from 0) should be swapped.\n swap letter X with letter Y means that the letters X and Y should be swapped (regardless of where they appear in the string).\n rotate left/right X steps means that the whole string should be rotated; for example, one right rotation would turn abcd into dabc.\n rotate based on position of letter X means that the whole string should be rotated to the right based on the index of letter X (counting from 0) as determined before this instruction does any rotations. Once the index is determined, rotate the string to the right one time, plus a number of times equal to that index, plus one additional time if the index was at least 4.\n reverse positions X through Y means that the span of letters at indexes X through Y (including the letters at X and Y) should be reversed in order.\n move position X to position Y means that the letter which is at index X should be removed from the string, then inserted such that it ends up at index Y.\n\nFor example, suppose you start with abcde and perform the following operations:\n\n swap position 4 with position 0 swaps the first and last letters, producing the input for the next step, ebcda.\n swap letter d with letter b swaps the positions of d and b: edcba.\n reverse positions 0 through 4 causes the entire string to be reversed, producing abcde.\n rotate left 1 step shifts all letters left one position, causing the first letter to wrap to the end of the string: bcdea.\n move position 1 to position 4 removes the letter at position 1 (c), then inserts it at position 4 (the end of the string): bdeac.\n move position 3 to position 0 removes the letter at position 3 (a), then inserts it at position 0 (the front of the string): abdec.\n rotate based on position of letter b finds the index of letter b (1), then rotates the string right once plus a number of times equal to that index (2): ecabd.\n rotate based on position of letter d finds the index of letter d (4), then rotates the string right once, plus a number of times equal to that index, plus an additional time because the index was at least 4, for a total of 6 right rotations: decab.\n\nAfter these steps, the resulting scrambled password is decab.\n\nNow, you just need to generate a new scrambled password and you can access the system. Given the list of scrambling operations in your puzzle input, what is the result of scrambling abcdefgh?\n\n--- Part Two ---\n\nYou scrambled the password correctly, but you discover that you can't actually modify the password file on the system. You'll need to un-scramble one of the existing passwords by reversing the scrambling process.\n\nWhat is the un-scrambled version of the scrambled password fbgdceah?\n\n\"\"\"\nfrom __future__ import print_function\n\nimport collections\nimport os\n\ndef swap_pos(password, idx, idy):\n password[idx], password[idy] = password[idy], password[idx]\n return password\n\ndef swap_val(password, val1, val2):\n def swap(x):\n if x == val1:\n return val2\n elif x == val2:\n return val1\n else:\n return x\n password = [swap(x) for x in password]\n return password\n\ndef rotate(password, dir, amount, unscramble=False):\n if not unscramble and dir == 'left':\n amount *= -1\n if unscramble and dir == 'right':\n amount *= -1\n deq = collections.deque(password)\n deq.rotate(amount)\n return list(deq)\n\ndef rotate_val(password, letter, unscramble=False):\n idx = password.index(letter)\n if unscramble:\n rotated_correctly = []\n for i in range(len(password)):\n test_val = rotate(password, 'left', i)\n rotated = rotate_val(test_val, letter) # Normal op\n if password == rotated:\n rotated_correctly.append(test_val)\n if len(rotated_correctly) == 1:\n return rotated_correctly[0]\n else: # This is an error but never occurs in my input\n print('ERROR unscramble rotate by value', password)\n return rotated_correctly[0]\n else:\n if idx >= 4:\n idx += 1\n idx += 1\n return rotate(password, 'right', idx)\n\ndef reverse_range(password, start, end):\n password = password[:start] + list(reversed(password[start:end + 1])) + password[end + 1:]\n return password\n\ndef move(password, move_from, move_to, unscramble=False):\n if unscramble:\n move_from, move_to = move_to, move_from\n val = password.pop(move_from)\n password.insert(move_to, val)\n return password\n\n\ndef solve(data, password='abcdefgh', unscramble=False):\n password = list(password)\n if unscramble:\n data = reversed(data)\n for row in data:\n row = row.split()\n if row[0] == 'swap' and row[1] == 'position':\n password = swap_pos(password, int(row[2]), int(row[-1]))\n elif row[0] == 'swap' and row[1] == 'letter':\n password = swap_val(password, row[2], row[-1])\n elif row[0] == 'rotate' and row[1] in ('right', 'left'):\n password = rotate(password, row[1], int(row[2]), unscramble=unscramble)\n elif row[0] == 'rotate' and row[1] == 'based':\n password = rotate_val(password, row[-1], unscramble=unscramble)\n elif row[0] == 'reverse':\n password = reverse_range(password, int(row[2]), int(row[-1]))\n elif row[0] == 'move':\n password = move(password, int(row[2]), int(row[-1]), unscramble=unscramble)\n else:\n print('ERROR', row)\n return ''.join(password)\n\nif __name__ == '__main__':\n this_dir = os.path.dirname(__file__)\n with open(os.path.join(this_dir, 'day21.input')) as f:\n data = f.read().splitlines()\n\n print('The scrambled password is', solve(data))\n print('The unscramble password is', solve(data, password='fbgdceah', unscramble=True))\n"} {"doc_id": "273a5fc056adf9d82b7a37a1d1c1ef6b", "text": "\"\"\"\nFile: quadratic_solver.py\n-----------------------\nThis program should implement a console program\nthat asks 3 inputs (a, b, and c)\nfrom users to compute the roots of equation\nax^2 + bx + c = 0\nOutput format should match what is shown in the sample\nrun in the Assignment 2 Handout.\n\n\"\"\"\n\nimport math\n\n\ndef main():\n\t\"\"\"\n\tWhen user input a,b,c variables, the app will show the roots of equation ax^2 + bx + c = 0\n\t\"\"\"\n\tprint('Hi, welcome to stanCode Quadratic Solver!')\n\tprint('let me help you calculate the roots of equation ax^2 + bx + c = 0 ')\n\tprint('Give me a,b,c')\n\ta = int(input('your a ?'))\n\tb = int(input('your b ?'))\n\tc = int(input('your c ?'))\n\n\tdiscriminant = b*b - 4 * a * c\n\tif discriminant < 0:\n\t\tprint('sorry! No real roots')\n\telif discriminant == 0:\n\t\tx = -b/(2*a)\n\t\tprint('one root: ' + str(x))\n\telse:\n\t\tdiscriminant_root = math.sqrt(discriminant)\n\t\tx1 = (-b + discriminant_root)/(2*a)\n\t\tx2 = (-b - discriminant_root)/(2*a)\n\t\tprint('Two roots: ' + str(x1) + ' & ' + str(x2))\n\n\n\n###### DO NOT EDIT CODE BELOW THIS LINE ######\n\nif __name__ == \"__main__\":\n\tmain()\n"} {"doc_id": "2756d24094759cc0efa78b6a3d8079ab", "text": "'''\nSecret Santa\n\nSecret Santa is a game in which a group of friends or colleagues exchange Christmas presents anonymously,\neach member of the group being assigned another member for whom to provide a small gift.\nYou're given a list of names, make a random pairs (each participant should have another name as pair).\nReturn an array with pairs represented as tuples.\n\nInput: ['a', 'b', 'c']\nOutput: This is a nondeterministic algorithm, more solutions exists, here are 2 possible solutions:\n [('a', 'b'), ('b', 'c'), ('c', 'a')], [('a', 'c'), ('c', 'b'), ('b', 'a')]\n\n=========================================\nShuffle the array (this algorithm is explained in shuffle_array.py) and pair the current element\nwith the next element (neighbouring).\n Time Complexity: O(N)\n Space Complexity: O(N)\n'''\n\n\n############\n# Solution #\n############\n\nfrom random import randint\n\ndef secret_santa(names):\n # or use shuffle method from random module (from random import shuffle)\n shuffle_array(names)\n pairs = []\n\n n = len(names)\n prev = names[-1] # or names[n - 1]\n\n for curr in names:\n pairs.append((prev, curr))\n prev = curr\n\n return pairs\n\ndef shuffle_array(arr):\n n = len(arr)\n\n for i in range(n):\n rand = randint(i, n - 1) # or randint(0, i) it's same\n arr[i], arr[rand] = arr[rand], arr[i] # swap elements\n\n # the original arr is already changed\n return arr\n\n\n###########\n# Testing #\n###########\n\n# Test 1\n# Correct result => nondeterministic algorithm, many solutions exist\nprint(secret_santa(['a', 'b', 'c']))"} {"doc_id": "276f817552a2c6dd01de25b8af1e3057", "text": "\"\"\"\nFile: quadratic_solver.py\nName:\n-----------------------\nThis program should implement a console program\nthat asks 3 inputs (a, b, and c)\nfrom users to compute the roots of equation:\nax^2 + bx + c = 0\nOutput format should match what is shown in the sample\nrun in the Assignment 2 Handout.\n\n\"\"\"\n\nimport math\n\n\ndef main():\n\tprint('stanCode Quadratic Solver! ')\n\ta = int(input('Enter a: '))\n\tb = int(input('Enter b: '))\n\tc = int(input('Enter c: '))\n\n\ty = b*b - 4*a*c\n\tif y < 0:\n\t\tprint('No real roots')\n\telif y == 0:\n\t\tx2 = (-b + math.sqrt(y)) / (2 * a)\n\t\tprint('One root: '+str(x2))\n\telif y > 0:\n\t\tx1 = (-b + math.sqrt(y)) / (2 * a)\n\t\tx2 = (-b + math.sqrt(y)) / (2 * a)\n\t\tprint('Two real roots: ' + str(x1) + ',' + str(x2))\n\n\n\n\n###### DO NOT EDIT CODE BELOW THIS LINE ######\n\nif __name__ == \"__main__\":\n\tmain()\n"} {"doc_id": "280816508bf46e557a0b158fe87c97d7", "text": "\"\"\"\r\nGet a sorted list of any iterable object\r\n----------------------------------------\r\n\r\nInput: (iterable) original iterable\r\n (boolean) reverse True -> descending order\r\n False -> ascending order\r\n default: False\r\n (boolean) key: Any function to decide the sorting order.\r\n\r\nReturn: (list) sorted iterable\r\n\"\"\"\r\n\r\n# Sort words\r\ncars = [\"Ford\", \"Audi\", \"BMW\", \"Chrysler\", \"Dodge\"]\r\nprint('Original list: {}\\nSorted list:{}'.format(cars, sorted(cars)))\r\n\r\n# Sort numbers\r\nnumbers = [6, 5, 2, -1, 0, 1, 2, 3, 4, 5]\r\nprint('\\nNumbers: {}\\nSorted numbers: {}'.format(numbers, sorted(numbers)))\r\n\r\n# Sort floats\r\nfloats = [6.0, 5.1, 2.0, -1.0, 0.5, 1.9, 2.8, 3.4, 4.6, 5.1]\r\nprint('\\nFloats: {}\\nSorted floats: {}'.format(floats, sorted(floats)))\r\n\r\n# Sort words descending\r\ncars = [\"Ford\", \"Audi\", \"BMW\", \"Chrysler\", \"Dodge\"]\r\nprint('Original list: {}\\nSorted list (descending):{}'.format(cars, sorted(cars, reverse=True)))\r\n\r\n# Sort numbers descending\r\nnumbers = [6, 5, 2, -1, 0, 1, 2, 3, 4, 5]\r\nprint('\\nNumbers: {}\\nSorted numbers (descending): {}'.format(numbers, sorted(numbers, reverse=True)))\r\n\r\n# Sort floats descending\r\nfloats = [6.0, 5.1, 2.0, -1.0, 0.5, 1.9, 2.8, 3.4, 4.6, 5.1]\r\nprint('\\nFloats: {}\\nSorted floats (descending): {}'.format(floats, sorted(floats, reverse=True)))\r\n\r\n# sorted() function using on list is similat like list.sort()\r\n# However, list.sort() method can be used only on list, sorted() function\r\n# accepts any iterable."} {"doc_id": "281d023a4ca0c6d1b0bc75f435741048", "text": "def futureValue_simple():\n \"\"\"\\nThis funtion calculates the future value\\nwith simple interset rate of present value.\\nThis will be a financial program!\\n\"\"\"\n\n # taking input from the user\n presentValue = int(input(\"What is your present value:\\n\"))\n interestRate = float(input(\"What is your interst rate?\\nDo not use '%':\"))\n time = int(input(\"For how many years or months do you want to invest:\\n\"))\n\n # Calculations\n rate = (1 + interestRate/100) ** time\n result = rate * presentValue\n\n # printing out the results\n return \"The future value of {} of {} years is %.3f\".format(\n presentValue, time) % result\n\n\ndef futureValue_compound():\n \"\"\"\\nThis funtion calculates the future value\\nwith compound interset rate of present value.\\nThis will be a financial tool!\\n\"\"\"\n\n # taking input from the user\n presentValue = int(input(\"What is your present value:\\n\"))\n interestRate = float(input(\"What is your interst rate?\\nDo not use '%':\"))\n time = int(input(\"For how many years or months do you want to invest:\\n\"))\n compound = int(input(\"How many time in a year do you need interest:\\n\"))\n\n # Calculations\n rate = (1 + (interestRate/100)/compound) ** (time*compound)\n result = rate * presentValue\n\n # printing out the results\n return \"The future value of {} of {} years is %.3f\".format(\n presentValue, time) % result\n\n\ndef effecticeInterestRate():\n \"\"\"\n This program help you to find the effective interest rate!\n \"\"\"\n rate = float(input(\"What is your interest rate:\\n\"))\n compound = int(input(\"How many times in a year you give interest:\\n\"))\n\n EIR = (1 + ((rate/100)/compound))**compound - 1\n eir = EIR*100\n return \"Your effective interest rate is: %.3f\" % eir\n"} {"doc_id": "2842d41886cbc7bfde61d6fe5376ba76", "text": "\"\"\"\n comb_sort.py\n\n This module implements comb sort on an unsorted list and returns a sorted list.\n\n Comb Sort Overview:\n -------------------\n Improves on bubble sort by using a gap sequence to remove turtles.\n\n Pre: an unsorted list[0,...,n] of integers.\n\n Post: returns a sorted list[0,...,n] in ascending order.\n\n Time Complexity: O(n^2)\n\n Space Complexity: O(n) total\n\n Stable: Yes\n\n Psuedo code: http://en.wikipedia.org/wiki/Comb_sort\n\n comb_sort.sort(list) -> sorted_list\n\n\"\"\"\n\n\ndef sort(seq):\n gap = len(seq)\n swap = True\n\n while gap > 1 or swap:\n gap = max(1, int(gap / 1.25))\n swap = False\n for i in range(len(seq) - gap):\n if seq[i] > seq[i + gap]:\n seq[i], seq[i + gap] = seq[i + gap], seq[i]\n swap = True\n return seq\n"} {"doc_id": "28563832942478898b850a9738ffd919", "text": "#Escreva uma programa que pergunte o s\u00e1lario de um funcion\u00e1rio e calcule o valor de seu aumento.\n#Para sal\u00e1rios superiores a R$1.250,00, calcule um aumento de 10%. Para os inferiores ou iguais, o aumento \u00e9 de 15%.\nfrom time import sleep\nprint('\\033[31m----------------AUMENTO SALARIAL----------------\\033[m') #tit\u00falo\nsalario = float(input('Qual o valor do sal\u00e1rio do funcion\u00e1rio? R$')) #input do sal\u00e1rio atual do funcionario na variavel salario\nprint('\\033[33mPROCESSANDO...\\033[m')\nsleep(1)\nif salario <= 1250: #se o valor do input for menor ou igual a 1250\n novo = salario + (salario * 15 / 100) #o aumento ser\u00e1 de 15%\nelse: #se o valor do input for superior a 1250\n novo = salario + (salario * 10 / 100) #o aumento ser\u00e1 de 10%\nprint(f'Quem ganhava R${salario:.2f} passa a ganhar \\033[4;33mR${novo:.2f}\\033[m') #mostra o novo sal\u00e1rio\n"} {"doc_id": "28aa76264c9b23b8f9e70808ea2c096d", "text": "# List examples\nlist1 = [45]\nprint(list1)\nlist1 = [22, 32, 44, 22, 12, 76, 56, 99, 0]\nprint(\"Items in the list are: \", list1)\nprint(\"5th Item in the List is:\", list1[4])\nprint(\"-2th Item in the List is:\", list1[-2])\n# Print list length\nprint(\"Length: \", len(list1))\n# Change an element in a list\nprint(\"Before: \", list1)\nlist1[0] = 33\nprint(\"After:\", list1)\n\n# # Print n items from a list from different starting point\nprint(list1[:3]) # Print first 3 items\nprint(list1[1:]) # Print items 2 to end\nprint(list1[2:4]) # Print 3 and 4; last index is exclusive\n#\n# # List of Strings\nlist2 = ['pheobe', 'rachel', 'monica', 'emily', 'janet', 'mona']\nprint(list2[:3]) # Print first 3 items\nprint(list2[1:]) # Print items 2 to end\nprint(list2[2:4]) # Print 3 and 4; last index is exclusive\nprint(\"Length: \", len(list2))\nprint(\"Length: \", len(list2[3]))\nprint(list2[-2])\n#\n# # Compare Lists\nlist3 = ['pheobe', 'rachel', 'monica', 'emily', 'amanda', 'linda']\nprint(list2 == list3)\nprint(\"Addition:\", list2 + list3)\n#\n# # Versatile data-type\nlist4 = [2, 66, 'Ronny', 'Mo', [\"Mel\", 788, 10.5]]\nprint(\"List4: \", list4)\n\n'''\n\nOutput:\n----------------------------------------\n45\nItems in the list are: [22, 32, 44, 22, 12, 76, 56, 99, 0]\n5th Item in the List is: 12\n-2th Item in the List is: 99\nLength: 9\nBefore: [22, 32, 44, 22, 12, 76, 56, 99, 0]\nAfter: [33, 32, 44, 22, 12, 76, 56, 99, 0]\n[33, 32, 44]\n[32, 44, 22, 12, 76, 56, 99, 0]\n[44, 22]\n['pheobe', 'rachel', 'monica']\n['rachel', 'monica', 'emily', 'janet', 'mona']\n['monica', 'emily']\nLength: 6\nLength: 5\njanet\nFalse\nAddition: ['pheobe', 'rachel', 'monica', 'emily', 'janet', 'mona', 'pheobe', 'rachel', 'monica', 'emily', 'amanda', 'linda']\n[2, 66, 'Ronny', 'Mo']\n\n'''"} {"doc_id": "28ba7f8b92868109513232987524bf61", "text": "\"\"\" Prolem Set 3 - Problem 4 - The Game\n\nNow you will implement the function hangman, which takes one parameter - the secretWord the user is to guess. \nThis starts up an interactive game of Hangman between the user and the computer. \nBe sure you take advantage of the three helper functions, isWordGuessed, getGuessedWord, and getAvailableLetters, that you've defined in the previous part.\n\nNote that if you choose to use the helper functions isWordGuessed, getGuessedWord, or getAvailableLetters, you do not need to paste your definitions in the box. \nWe have supplied our implementations of these functions for your use in this part of the problem. If you use additional helper functions, you will need to paste those definitions here.\n\nYour function should include calls to input to get the user's guess.\n\"\"\"\n\ndef hangman(secretWord):\n '''\n secretWord: string, the secret word to guess.\n\n Starts up an interactive game of Hangman.\n\n * At the start of the game, let the user know how many \n letters the secretWord contains.\n\n * Ask the user to supply one guess (i.e. letter) per round.\n\n * The user should receive feedback immediately after each guess \n about whether their guess appears in the computers word.\n\n * After each round, you should also display to the user the \n partially guessed word so far, as well as letters that the \n user has not yet guessed.\n\n Follows the other limitations detailed in the problem write-up.\n '''\n\n lettersGuessed = []\n count = 8\n flag = \"Sorry, you ran out of guesses. The word was else. \"\n print(\"Welcome to the game, Hangman!\")\n print(\"I am thinking of a word that is \" + str(len(secretWord)) + \" letters long.\")\n print(\"-----------\")\n \n while (count > 0):\n \n print(\"You have \" + str(count) + \" guesses left.\")\n print(\"Available letters: \" + getAvailableLetters(lettersGuessed))\n guess = input(\"Please guess a letter: \")\n guessLowerCase = guess.lower()\n if guessLowerCase not in lettersGuessed:\n lettersGuessed += guessLowerCase\n if guessLowerCase in secretWord:\n print(\"Good guess: \" + getGuessedWord(secretWord, lettersGuessed))\n print(\"-----------\")\n elif guessLowerCase not in secretWord:\n print(\"Oops! That letter is not in my word: \" + getGuessedWord(secretWord, lettersGuessed))\n print(\"-----------\")\n count -= 1\n elif guessLowerCase in lettersGuessed:\n print(\"Oops! You've already guessed that letter: \" + getGuessedWord(secretWord, lettersGuessed))\n print(\"-----------\")\n if getGuessedWord(secretWord, lettersGuessed) == secretWord:\n flag = \"Congratulations, you won!\"\n break\n return print(flag)\n"} {"doc_id": "28da4dc80869018ce7bdcaed1d282e9b", "text": "# Title: vigenere.py\n# Version: 1.0.4\n# Description: A simple class that implements the Vigenere cipher.\n# Note: Valid Passwords MUST be at least one letter long. Otherwise the class\n# will throw an error. Numbers and symbols are not valid characters in\n# passwords and are ignored.\n\nclass Vigenere:\n ## Initialize the Vigenere object\n # @param password a string to use as a password\n def __init__(self, password = \"Hello world\"):\n # create a variable to hold the password and set it\n self.vigPass = \"\"\n self.setPassword(password)\n\n\n ## Takes a letter from the user and turns it into a number between\n # 0 and 25 to use as a key for encryption or decryption\n # @param char a character to use as a key\n # @return an integer between 0 and 25\n #\n def chToKey(self, char):\n if char.isupper():\n return(ord(char) - ord(\"A\"))\n elif char.islower():\n return(ord(char) - ord('a'))\n else:\n # Not a letter\n return None\n\n\n ## Removes all characters not found in the alphabet from an input\n # string and converts all characters to uppercase.\n # @param text the string to be converted\n # @return newText The new all uppercase, alpha only string.\n #\n def convertStr(self, text):\n newText = \"\"\n for char in text:\n if char.isalpha():\n newText += char.upper()\n\n return(newText)\n\n\n ## Formats a string into blocks of five characters\n # @param string the string to modify\n # @returns a new string grouping characters into sets of 5 characters\n #\n def formatStr(self, string):\n new = \"\"\n for i in range(len(string)):\n if(i != 0 and i % 5 == 0):\n new += \" \"\n new += string[i]\n\n return(new)\n\n\n ## Encrypts/decrypts upper- and lowercase characters using the\n # Caesar cipher algorithm\n # @param ch the letter to be encrypted/decrypted\n # @param key a integer representing the key to use as a shift value\n # @param mode a character that determines the operation\n # E for encryption, and D for decryption\n # @return the encrypted/decrypted letter\n #\n def crypt(self, ch, key, mode):\n\n if ch.isupper():\n offset = ord(\"A\")\n elif ch.islower():\n offset = ord('a')\n else:\n return(ch)\n\n enc = \"\"\n\n if mode.upper() == \"E\":\n enc = chr((ord(ch) + key - offset) % 26 + offset)\n elif mode.upper() == \"D\":\n enc = chr((ord(ch) - key - offset) % 26 + offset)\n else:\n return(ch)\n\n return(enc)\n\n\n ## Decrypts a message with the Vigenere cipher\n # @param string the string to decrypt\n # @return the decrypted string\n #\n def decrypt(self, string):\n new = \"\"\n tempKey = 0\n j = 0\n\n for char in string:\n if(not char.isalpha()):\n new += char\n continue\n\n tempKey = self.chToKey(self.vigPass[j % len(self.vigPass)])\n new += self.crypt(char, tempKey, \"D\")\n j += 1\n\n\n return(new)\n\n ## Encrypts a message with the Vigenere cipher\n # @param string the string to encrypt\n # @return the encrypted string\n #\n def encrypt(self, string):\n convString = self.convertStr(string)\n new = \"\"\n tempKey = 0\n j = 0\n\n for char in convString:\n tempKey = self.chToKey(self.vigPass[j % len(self.vigPass)])\n new += self.crypt(char, tempKey, \"E\")\n j += 1\n\n return(self.formatStr(new))\n\n\n ## Sets a new password to be used for encryption/decryption\n # @param newPass a string to be used as the password\n #\n def setPassword(self, newPass):\n tmp = self.convertStr(newPass)\n if len(tmp) == 0:\n raise IndexError(\"Error: Bad password. Password must contain only letters\")\n else:\n self.vigPass = tmp\n"} {"doc_id": "28ed6bb38d6619007e59665e865983e5", "text": "print(\"Hello World\", end=\"***\")\nprint(\"Where does this line go?\")\n\nprint(\"Hello World!\", end=\" \")\nprint(\"Where does this line go?\")\n\nprint(\"Hello World!\", end =\"\")\n\nprint(\"I love\" + \"naps.\")\nprint(\"I love\", \"naps\")\n\nprint(\"\\\"Python\\\" comes from a 1970s comedy series\")\n\n\n\nage = 10\nname = \"Sophie\"\nchanceOfRain = 0.8\nisItRaining = True\n\nlanguage = \"Python\"\nmessage = \"I love programming in \" + language\nprint(message)\n\nlastName = \"Steinbeck\"\nprint(lastName)\nprint(lastName.upper())\n\n\n-----Input-------\nname = input(\"What's your name?\")\nprint(\"hi\", name)\n\n#sum two number\nnum1 = int(input(\"Enter a number: \"))\nnum2 = int(input(\"Enter another number\"))\nprint(num1+num2)\n\n#password\npassword = input(\"Enter your password:\")\nif password == \"secret\":\n print(\"Access Granted\")\nelse:\n print(\"Access Denied\")\n\n#vote\nage = int(input(\"Enter your age: \"))\nif age >= 18:\n print(\"You can vote\")\n\nelse:\n print(\"You can't vote yet\")\n\n#vote and disaply the years\nage = int(input(\"Enter your age: \"))\nif age >= 18:\n print(\"You can vote\")\n\nelse:\n years = 18 - age\n print(\"You can vote in\" + str(years) + \" years!\")\n\n#fav topping\nfavFood = input(\"Enter favorite food: \")\nif favFood == \"pizza\":\n print(\"Your favorite food is pizza!\")\n favTopping = input(\"Enter favorite topping: \")\n if favTopping == \"sausage\":\n print(\"Your favorite topping is sausage\")\n print(\"Me too\")\nelse:\n print(\"something\")\nprint(\"Have a great day\")\n\n#score for the midterm\nscoreOnMidtermExam = int(input(\"What is the score on the midterm exam?\"))\nif scoreOnMidtermExam >= 90:\n scoreOnMidtermExam = \"A\"\nelif scoreOnMidtermExam >= 80:\n scoreOnMidtermExam = \"B\"\nprint(scoreOnMidtermExam)\n\n#pick a number 1-10, display even or odd and error checking\ninput = int(input(\"Pick a number: \"))\nif input < 1 or input > 10:\n print(\"You must enter a number between 1 and 10!\")\nelif input % 2 != 0:\n print(str(number) + \" is an odd number.\")\nelse:\n print(str(number) + \" is an even number.\")\n\n#bottle-loops\nnumBottles = 99\nwhile numBottles > 0:\n print(numBottles, \"bottles of cold brew on the wall\")\n print(\"Take one down and pass it around\")\n numBottles = numBottles - 1\n\nprint(\"Cold brew is all gone\")\n\n#error checking loop\nanswer = input(\"Do you want cream(y/n)?\")\nwhile answer != \"y\" or answer != \"n\":\n answer = input(\"Do you want cream(y/n)?\")\nif answer == \"y\":\n print(\"You added cream\")\nelif answer == \"n\":\n print(\"You did not add the cream\")\n\n#another example\nsum = 0\nareMore = True\nprint(\"Enter positive numbers or -1 to quit\")\nwhile areMore == True:\n nextNum = int(input(\"Enter a number: \"))\n if nextNum < 0:\n areMOre = False\n else:\n sum = sum + nextNum\nprint(\"The sum is \" + str(sum))\n\n#for loop\nfor num in range(3):\n print(num + 2)\n\nprint(\"done\")\n\n#mix\nmix = [1, \"a\", 2, \"b\"]\nprint(mix[1])\nprint(mix[-3])\nprint(mix[:2])\nprint(mix[2:])\nprint(mix[1:3])\nprint(mix[::-1])\n\n#num list\nnum = [1, 2]\n\nprint(num)\n\nnum.append(3)\nprint(num)\n\nletter = [\"a\", \"b\", \"c\"]\nnum.extend(letter)\nprint(num)\n\nnum.insert(1, \"x\")\nprint(num)\n\nnum.remove(\"x\")\nprint(num)\n\n#\nnum = [1, 2, 3]\nletter = [\"a\", \"b\", \"c\"]\n\nnum.sort()\nprint(num)\n\nletter.sort()\nprint(letter)\n\nmix.sort()\nprint(mix) #this is an error\n\n#some functions\nx = [2, 40, 21, 5, 103]\n#mean\nsum(x)/len(x)\n\n---module---\nimport random\nnumber = random.randrange(6) + 1\nprint(number)\n\n\n\n\n"} {"doc_id": "29033103b9363426a02fd18c086a04f5", "text": "# 1.while\u5faa\u73af\u8bed\u4e49\r\nindex = 1\r\nwhile (index <= 10):\r\n print(\"\u5faa\u73af\u6253\u5370\u7b2c%d\" % index)\r\n index += 1\r\n\r\n# 2.break/continue\r\n# break:\u7ec8\u6b62\u5faa\u73af\uff0c\u5305\u62ecwhile\uff0cfor\r\n# continue:\u7ec8\u6b62\u5f53\u524d\u4e00\u6b21\u5faa\u73af\uff0c\u8fd8\u4f1a\u6267\u884c\u4e0b\u4e00\u6b21\u5faa\u73af,\u5305\u62ec\uff08while,for\uff09\r\nindex = 1\r\nwhile index < 100:\r\n print(\"***\u6253\u5370\u7b2c%d\u6b21\" % index)\r\n if index == 50:\r\n print(\"index==%d,\u8df3\u51fa\u5faa\u73af\" % index)\r\n break\r\n index += 1\r\n\r\nindex = 1\r\nwhile index < 10:\r\n print(\"+++++\u6253\u5370\u7b2c%d\u6b21++++\" % index)\r\n if index == 6:\r\n print(\"index==%d,\u7ed3\u675f\u672c\u6b21\u5faa\u73af,\u7ee7\u7eed\u4e0b\u6b21\u5faa\u73af...\" % index)\r\n index += 1\r\n continue\r\n index += 1\r\n\r\n# 3.while\u5d4c\u5957\r\n# 99\u4e58\u6cd5\u8868\r\nprint(\"\\n***************99\u4e58\u6cd5\u8868*************\")\r\ni = 1\r\nwhile i <= 9:\r\n j = 1\r\n while j <= i:\r\n print(f\"{j}x{i}={i * j}\", end=\"\\t\")\r\n j += 1\r\n i += 1\r\n print(\"\")\r\n\r\n# 4.while / else\r\n# else\u91cc\u9762\u7684\u4ee3\u7801\u662f\u5728\u5faa\u73af\u6267\u884c\u5b8c\u6bd5\u4e4b\u540e\u5728\u6267\u884c.\r\n# \u6ce8\u610f\uff1a\u5982\u679c\u662fbreak\u7ec8\u6b62\u5faa\u73af\u662f\u4e0d\u4f1a\u6267\u884c\u7684\r\n\r\nindex = 1\r\nwhile index <= 10:\r\n print(\"+++++\u6253\u5370\u7b2c%d\u6b21++++\" % index)\r\n index += 1\r\nelse:\r\n print(\"10\u6b64\u5faa\u73af\u6253\u5370\u5b8c\u6210\u540e\u6267\u884c\u7684\u4ee3\u7801...\")\r\n\r\nindex = 1\r\nwhile index <= 10:\r\n print(\"ssssss\u6253\u5370\u7b2c%d\u6b21++++\" % index)\r\n if index == 5:\r\n print(\"index=5,\u7ed3\u675f\u5faa\u73af...,\u4e0d\u4f1a\u5230else\u8bed\u53e5...\")\r\n break\r\n index += 1\r\nelse:\r\n print(\"10\u6b64\u5faa\u73af\u6253\u5370\u5b8c\u6210\u540e\u6267\u884c\u7684\u4ee3\u7801...\")\r\n"} {"doc_id": "29405c05d09ed4b723a87d4001be86ce", "text": "\"\"\"\nFile: quadratic_solver.py\nName: Calvin Chen\n-----------------------\nThis program should implement a console program\nthat asks 3 inputs (a, b, and c)\nfrom users to compute the roots of equation\nax^2 + bx + c = 0\nOutput format should match what is shown in the sample\nrun in the Assignment 2 Handout.\n\n\"\"\"\n\nimport math\n\n\ndef main():\n\t\"\"\"\n\tpre-condition: enter a, b, and c\n\tpost-condition: answer of the quadratic and how many roots\n\t\"\"\"\n\tprint(\"stanCode Quadratic Solver!\")\n\ta = int(input('Enter a: '))\n\tb = int(input('Enter b: '))\n\tc = int(input('Enter c: '))\n\tdisc = b * b - 4 * a * c # disc = discriminant\n\n\tif disc > 0:\n\t\ty = math.sqrt(disc)\n\t\troot1 = (-b + y) / 2 * a\n\t\troot2 = (-b - y) / 2 * a\n\t\tprint('Two roots: ' + str(root1) + ' , ' + str(root2))\n\telif disc == 0:\n\t\troot1 = -b / 2 * a\n\t\tprint('One root: ' + str(root1))\n\telse:\n\t\tprint('No real roots')\n\n\n###### DO NOT EDIT CODE BELOW THIS LINE ######\n\nif __name__ == \"__main__\":\n\tmain()\n"} {"doc_id": "297b4270cbf168726dbd01ab2e0ed9db", "text": "# game.py\n\n#IMPORTS\n\nimport random\n\n#INTRODUCTION\n\nprint(\"Rock, Paper, Scissors, Shoot!\")\n\nprint(\" \")\n\n# CAPTURE INPUTS\n\nuser_choice = input(\"Please choose one of the following options: 'rock', 'paper' or 'scissors' (without the quotes) \")\n\nprint(\"------------------\")\nprint(\"You chose:\", user_choice)\n\nprint(\" \")\n\n# VALIDATE INPUTS\n\noptions = [\"rock\", \"paper\", \"scissors\"]\n\nif user_choice not in options:\n print(\"Invalid selection. Please, try again\")\n exit() \n\n# GENERATE COMPUTER SELECTION\n\ncomputer_choice = random.choice(options)\n\nprint(\"------------------\")\nprint(\" \")\n\nprint(\"Generating...\")\n\nprint(\" \") \n\nprint(\"Computer chose:\", computer_choice)\n\nprint(\" \")\n\n# DETERMINE THE WINNER\n ### rock beats scissors, paper beats rock and scissors beat paper\n ### or same is a tie\n\nif user_choice == computer_choice:\n print(\"Tie!\")\n\n\nelif user_choice == \"rock\" and computer_choice == \"paper\":\n print(\"Computer wins!\")\nelif user_choice == \"rock\" and computer_choice == \"scissors\":\n print(\"You win!\")\n\n\n\nelif user_choice == \"paper\" and computer_choice == \"rock\":\n print(\"You win!\")\nelif user_choice == \"paper\" and computer_choice == \"scissors\":\n print(\"Computer wins!\")\n\n\n\nelif user_choice == \"scissors\" and computer_choice == \"rock\":\n print(\"Computer wins!\")\nelif user_choice == \"scissors\" and computer_choice == \"paper\":\n print(\"You win!\")\n\n\n# DISPLAY FINAL OUTPUTS / OUTCOMES\n\n"} {"doc_id": "29abb5cd9076a34c7eb2b2f8423049c1", "text": "i = 3\r\nwhile(i):\r\n a = input(\"Enter the username:\")\r\n if a == \"admin\":\r\n i = 3\r\n while(i):\r\n b = input(\"Enter the password:\")\r\n if b == \"password\":\r\n print(\"Login successful\")\r\n a = int(input(\"Enter the source in kilometers:\"))\r\n b = int(input(\"Enter the destination in kilometers:\"))\r\n print(\"The distance of the travel is\",b-a,\"kms\")\r\n i =0\r\n break\r\n else:\r\n print(\"Password incorrect\")\r\n i = i -1\r\n else:\r\n print(\"Username not valid\")\r\n i = i -1\r\n"} {"doc_id": "29fd610d59992ed2343e447b9d0a0796", "text": "\"\"\"\n

We 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.

\n\n

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\n

For 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.

\n\n

Return the lowest number of moves to acquire all keys.  If it's impossible, return -1.

\n\n

 

\n\n
\n

Example 1:

\n\n
\nInput: ["@.a.#","###.#","b.A.B"]\nOutput: 8\n
\n\n
\n

Example 2:

\n\n
\nInput: ["@..aA","..B#.","....b"]\nOutput: 6\n
\n
\n\n

 

\n\n

Note:

\n\n
    \n\t
  1. 1 <= grid.length <= 30
  2. \n\t
  3. 1 <= grid[0].length <= 30
  4. \n\t
  5. grid[i][j] contains only '.', '#', '@', 'a'-'f' and 'A'-'F'
  6. \n\t
  7. The number of keys is in [1, 6].  Each key has a different letter and opens exactly one lock.
  8. \n
\n
\n

\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

\n\n

\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

\n\n

\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

 

\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\n
    \n\t
  1. 1 <= grid.length <= 30
  2. \n\t
  3. 1 <= grid[0].length <= 30
  4. \n\t
  5. grid[i][j] \u53ea\u542b\u6709 '.', '#', '@', 'a'-'f' \u4ee5\u53ca 'A'-'F'
  6. \n\t
  7. \u94a5\u5319\u7684\u6570\u76ee\u8303\u56f4\u662f [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
  8. \n
\n

\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

\n\n

\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

\n\n

\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

 

\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\n
    \n\t
  1. 1 <= grid.length <= 30
  2. \n\t
  3. 1 <= grid[0].length <= 30
  4. \n\t
  5. grid[i][j] \u53ea\u542b\u6709 '.', '#', '@', 'a'-'f' \u4ee5\u53ca 'A'-'F'
  6. \n\t
  7. \u94a5\u5319\u7684\u6570\u76ee\u8303\u56f4\u662f [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
  8. \n
\n\"\"\"\n\n\nclass Solution(object):\n def shortestPathAllKeys(self, grid):\n \"\"\"\n :type grid: List[str]\n :rtype: int\n \"\"\"\n "} {"doc_id": "2a4d186429f2a1a85c47bee05be59b35", "text": "#\u0417\u0430\u0434\u0430\u0447\u0438 \u043d\u0430 \u0446\u0438\u043a\u043b\u044b \u0438 \u043e\u043f\u0435\u0440\u0430\u0442\u043e\u0440 \u0443\u0441\u043b\u043e\u0432\u0438\u044f------\n#----------------------------------------\n\n'''\n\u0417\u0430\u0434\u0430\u0447\u0430 1\n\n\u0412\u044b\u0432\u0435\u0441\u0442\u0438 \u043d\u0430 \u044d\u043a\u0440\u0430\u043d \u0446\u0438\u043a\u043b\u043e\u043c \u043f\u044f\u0442\u044c \u0441\u0442\u0440\u043e\u043a \u0438\u0437 \u043d\u0443\u043b\u0435\u0439, \u043f\u0440\u0438\u0447\u0435\u043c \u043a\u0430\u0436\u0434\u0430\u044f \u0441\u0442\u0440\u043e\u043a\u0430 \u0434\u043e\u043b\u0436\u043d\u0430 \u0431\u044b\u0442\u044c \u043f\u0440\u043e\u043d\u0443\u043c\u0435\u0440\u043e\u0432\u0430\u043d\u0430.\n'''\n# noll = '000000'\n# for i in range(1,6):\n# print(i, noll, sep = ' ')\n'''\n\u0417\u0430\u0434\u0430\u0447\u0430 2\n\n\u041f\u043e\u043b\u044c\u0437\u043e\u0432\u0430\u0442\u0435\u043b\u044c \u0432 \u0446\u0438\u043a\u043b\u0435 \u0432\u0432\u043e\u0434\u0438\u0442 10 \u0446\u0438\u0444\u0440. \u041d\u0430\u0439\u0442\u0438 \u043a\u043e\u043b\u0438\u0447\u0435\u0441\u0442\u0432\u043e \u0432\u0432\u0435\u0434\u0435\u043d\u044b\u0445 \u043f\u043e\u043b\u044c\u0437\u043e\u0432\u0430\u0442\u0435\u043b\u0435\u043c \u0446\u0438\u0444\u0440 5.\n'''\n# a = 0\n# for i in range(10):\n# answer = input('\u0412\u0432\u0435\u0434\u0438\u0442\u0435 \u0447\u0438\u0441\u043b\u043e:')\n# answer = int(answer)\n# if answer == 5:\n# a = a + 1\n# print(a)\n'''\n\u0417\u0430\u0434\u0430\u0447\u0430 3\n\n\u041d\u0430\u0439\u0442\u0438 \u0441\u0443\u043c\u043c\u0443 \u0440\u044f\u0434\u0430 \u0447\u0438\u0441\u0435\u043b \u043e\u0442 1 \u0434\u043e 100. \u041f\u043e\u043b\u0443\u0447\u0435\u043d\u043d\u044b\u0439 \u0440\u0435\u0437\u0443\u043b\u044c\u0442\u0430\u0442 \u0432\u044b\u0432\u0435\u0441\u0442\u0438 \u043d\u0430 \u044d\u043a\u0440\u0430\u043d.\n'''\n# sum = 0\n#\n# for i in range(1,101):\n# sum+=i\n# print(sum)\n\n'''\n\u0417\u0430\u0434\u0430\u0447\u0430 4\n\n\u041d\u0430\u0439\u0442\u0438 \u043f\u0440\u043e\u0438\u0437\u0432\u0435\u0434\u0435\u043d\u0438\u0435 \u0440\u044f\u0434\u0430 \u0447\u0438\u0441\u0435\u043b \u043e\u0442 1 \u0434\u043e 10. \u041f\u043e\u043b\u0443\u0447\u0435\u043d\u043d\u044b\u0439 \u0440\u0435\u0437\u0443\u043b\u044c\u0442\u0430\u0442 \u0432\u044b\u0432\u0435\u0441\u0442\u0438 \u043d\u0430 \u044d\u043a\u0440\u0430\u043d.\n'''\n# proizvedenie = 1\n# for i in range(1,6):\n# proizvedenie*=i\n# print(proizvedenie)\n'''\n\u0417\u0430\u0434\u0430\u0447\u0430 5\n\n\u0412\u044b\u0432\u0435\u0441\u0442\u0438 \u0446\u0438\u0444\u0440\u044b \u0447\u0438\u0441\u043b\u0430 \u043d\u0430 \u043a\u0430\u0436\u0434\u043e\u0439 \u0441\u0442\u0440\u043e\u0447\u043a\u0435.\n'''\n\n# integer_number = 2129\n#\n# #print(integer_number%10,integer_number//10)\n#\n# while integer_number>0:\n# print(integer_number%10)\n# integer_number = integer_number//10\n\n# \u0432 \u043e\u0431\u0440\u0430\u0442\u043d\u043e\u043c \u043f\u043e\u0440\u044f\u0434\u043a\u0435 1 \u0432\u0430\u0440\u0438\u0430\u043d\u0442\n\n# integer_number = 2129\n# n2 = 0\n# while integer_number > 0:\n# \tdigit = integer_number % 10 # \u043d\u0430\u0445\u043e\u0434\u0438\u043c \u043e\u0441\u0442\u0430\u0442\u043e\u043a - \u043f\u043e\u0441\u043b\u0435\u0434\u043d\u044e\u044e \u0446\u0438\u0444\u0440\u0443 \u0447\u0438\u0441\u043b\u0430\n# \tinteger_number = integer_number // 10 # \u0434\u0435\u043b\u0438\u043c \u043d\u0430\u0446\u0435\u043b\u043e - \u0443\u0431\u0438\u0440\u0430\u0435\u043c \u0438\u0437 \u0447\u0438\u0441\u043b\u0430 \u043f\u043e\u0441\u043b\u0435\u0434\u043d\u044e\u044e \u0446\u0438\u0444\u0440\u0443\n# \tn2 = n2 * 10 # \u0443\u0432\u0435\u043b\u0438\u0447\u0438\u0432\u0430\u0435\u043c \u0440\u0430\u0437\u0440\u044f\u0434\u043d\u043e\u0441\u0442\u044c \u0432\u0442\u043e\u0440\u043e\u0433\u043e \u0447\u0438\u0441\u043b\u0430\n# \tn2 = n2 + digit # \u0434\u043e\u0431\u0430\u0432\u043b\u044f\u0435\u043c \u043e\u0447\u0435\u0440\u0435\u0434\u043d\u0443\u044e \u0446\u0438\u0444\u0440\u0443\n#\n# while n2>0:\n# print(n2%10)\n# n2 = n2//10\n\n# \u0412 \u043e\u0431\u0440\u0430\u0442\u043d\u043e\u043c \u043f\u043e\u0440\u044f\u0434\u043a\u0435 2 \u0432\u0430\u0440\u0438\u0430\u043d\u0442\n\n# c = integer_number\n# a = 0\n# #print(integer_number%10,integer_number//10)\n#\n# while c>0:\n# # print(integer_number%10)\n# c = c//10\n# a+=1\n# b = int(10**(a-1))\n# while 1 <= b:\n# print(integer_number//b)\n# integer_number = int(integer_number%b)\n# b = int(b/10)\n\n# integer_number = integer_number/b\n# b = b/10\n\n'''\n\u0417\u0430\u0434\u0430\u0447\u0430 6\n\n\u041d\u0430\u0439\u0442\u0438 \u0441\u0443\u043c\u043c\u0443 \u0446\u0438\u0444\u0440 \u0447\u0438\u0441\u043b\u0430.\n'''\n# integer_number = 2129\n#\n# #print(integer_number%10,integer_number//10)\n# a = 0\n# while integer_number>0:\n# a = a + (integer_number%10)\n# integer_number = integer_number//10\n# print(a)\n'''\n\u0417\u0430\u0434\u0430\u0447\u0430 7\n\n\u041d\u0430\u0439\u0442\u0438 \u043f\u0440\u043e\u0438\u0437\u0432\u0435\u0434\u0435\u043d\u0438\u0435 \u0446\u0438\u0444\u0440 \u0447\u0438\u0441\u043b\u0430.\n'''\n\n# integer_number = 2129\n#\n# a = 1\n# while integer_number>0:\n# a = a * (integer_number%10)\n# integer_number = integer_number//10\n# print(a)\n\n'''\n\u0417\u0430\u0434\u0430\u0447\u0430 8\n\n\u0414\u0430\u0442\u044c \u043e\u0442\u0432\u0435\u0442 \u043d\u0430 \u0432\u043e\u043f\u0440\u043e\u0441: \u0435\u0441\u0442\u044c \u043b\u0438 \u0441\u0440\u0435\u0434\u0438 \u0446\u0438\u0444\u0440 \u0447\u0438\u0441\u043b\u0430 5?\n'''\n# integer_number = 213413\n# while integer_number>0:\n# if integer_number%10 == 5:\n# print('Yes')\n# break\n# integer_number = integer_number//10\n# else: print('No')\n\n'''\n\u0417\u0430\u0434\u0430\u0447\u0430 9\n\n\u041d\u0430\u0439\u0442\u0438 \u043c\u0430\u043a\u0441\u0438\u043c\u0430\u043b\u044c\u043d\u0443\u044e \u0446\u0438\u0444\u0440\u0443 \u0432 \u0447\u0438\u0441\u043b\u0435\n'''\n# integer_number = 8212712\n#\n# max = integer_number%10\n# while integer_number>0:\n# integer_number = integer_number//10\n# if max < integer_number%10:\n# max = integer_number%10\n# print(max)\n\n'''\n\u0417\u0430\u0434\u0430\u0447\u0430 10\n\n\u041d\u0430\u0439\u0442\u0438 \u043a\u043e\u043b\u0438\u0447\u0435\u0441\u0442\u0432\u043e \u0446\u0438\u0444\u0440 5 \u0432 \u0447\u0438\u0441\u043b\u0435\n'''\n# integer_number = 8521552712\n#\n# count_five = 0\n# while integer_number>0:\n# if integer_number%10 == 5:\n# count_five+=1\n# integer_number = integer_number//10\n# print(count_five)"} {"doc_id": "2a4e0336e0364c512df03f4700989b06", "text": "\"\"\"\n

A character is unique in string S if it occurs exactly once in it.

\n\n

For example, in string S = "LETTER", the only unique characters are "L" and "R".

\n\n

Let's define UNIQ(S) as the number of unique characters in string S.

\n\n

For example, UNIQ("LETTER") =  2.

\n\n

Given a string S, calculate the sum of UNIQ(substring) over all non-empty substrings of S.

\n\n

If there are two or more equal substrings at different positions in S, we consider them different.

\n\n

Since the answer can be very large, retrun the answer modulo 10 ^ 9 + 7.

\n\n

 

\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

\n\n

\u4f8b\u5982\uff0c\u5728\u5b57\u7b26\u4e32 S = "LETTER" \u4e2d\uff0c"L" \u548c "R" \u53ef\u4ee5\u88ab\u79f0\u4e3a\u72ec\u7279\u5b57\u7b26\u3002

\n\n

\u6211\u4eec\u518d\u5b9a\u4e49 UNIQ(S) \u4f5c\u4e3a\u5b57\u7b26\u4e32 S \u4e2d\u72ec\u7279\u5b57\u7b26\u7684\u4e2a\u6570\u3002

\n\n

\u90a3\u4e48\uff0c\u5728 S = "LETTER" \u4e2d\uff0c UNIQ("LETTER") =  2\u3002

\n\n

\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

\n\n

\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

\n\n

\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

\n

\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

\n\n

\u4f8b\u5982\uff0c\u5728\u5b57\u7b26\u4e32 S = "LETTER" \u4e2d\uff0c"L" \u548c "R" \u53ef\u4ee5\u88ab\u79f0\u4e3a\u72ec\u7279\u5b57\u7b26\u3002

\n\n

\u6211\u4eec\u518d\u5b9a\u4e49 UNIQ(S) \u4f5c\u4e3a\u5b57\u7b26\u4e32 S \u4e2d\u72ec\u7279\u5b57\u7b26\u7684\u4e2a\u6570\u3002

\n\n

\u90a3\u4e48\uff0c\u5728 S = "LETTER" \u4e2d\uff0c UNIQ("LETTER") =  2\u3002

\n\n

\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

\n\n

\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

\n\n

\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

\n\"\"\"\n\n\nclass Solution(object):\n def uniqueLetterString(self, S):\n \"\"\"\n :type S: str\n :rtype: int\n \"\"\"\n "} {"doc_id": "2a8abf2111897cde97fae53ffb4317d1", "text": "# Name: \n# Course: CPE 202\n# Instructor: Daniel Kauffman\n# Assignment: Problem Set III\n# Term: Spring 2021\n\nfrom typing import Optional\n\n\n# do not modify this class\nclass ListNode:\n\n def __init__(self, val: int, ref: Optional[\"ListNode\"]) -> None:\n self.val = val\n self.ref = ref\n\n def __eq__(self, other: \"ListNode\") -> bool:\n \"\"\"\n Return True if the two given lists have the same number of ListNodes and\n the same ListNode val at each respective position and False otherwise.\n\n >>> xs = ListNode(1, ListNode(2, ListNode(3, None)))\n >>> ys = ListNode(1, ListNode(2, ListNode(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 linked list. String\n representations of objects are useful for reading test suite errors.\n\n >>> xs = ListNode(1, ListNode(2, ListNode(3, None)))\n >>> str(xs)\n \"1-2-3\"\n \"\"\"\n list_str = str(self.val)\n while True:\n self = self.ref\n if self is None:\n return list_str\n list_str += \"-\" + str(self.val)\n\n\n\n\ndef mul(x: int, y: int) -> int:\n \"\"\"\n Return the product of x and y without using the multiplication operator.\n\n >>> mul(-2, -3)\n 6\n \"\"\"\n\n\n\n\ndef exp(x: int, y: int) -> int:\n \"\"\"\n Return the result of taking x to the y power without using the\n multiplication or exponentiation operators. Assume y is non-negative.\n\n >>> exp(-2, 3)\n -8\n \"\"\"\n\n\n\n\ndef fac(n: int) -> int:\n \"\"\"\n Return n factorial without using the multiplication operator. Assume n is\n non-negative.\n\n >>> fac(5)\n 120\n \"\"\"\n\n\n\n\ndef fibonacci(n: int, a: int, b: int) -> int:\n \"\"\"\n Return an integer representing the Fibonacci Sequence at the given nth\n position. Each integer in this sequence is the sum of the previous two\n integers (except for the first two integers, 0 and 1, which are base values\n not derived from adding other integers). Assume n is positive.\n\n Use the a and b parameters to keep track of the previous two values in the\n sequence. These two values should always start as 0 and 1, respectively.\n\n >>> fibonacci(8, 0, 1)\n 13\n \"\"\"\n\n\n\n\ndef make_substring(string: str, start: int, stop: int, step: int) -> str:\n \"\"\"\n Return a substring of the given string that begins at the start index\n (inclusive) and ends at the stop index (exclusive), increasing step\n characters each iteration. Assume start and stop are non-negative and step\n is positive.\n\n >>> make_substring(\"COMPUTER\", 0, 10, 3)\n \"CPE\"\n \"\"\"\n\n\n\n\ndef is_palindrome(chars: str) -> bool:\n \"\"\"\n Return True if the given string is a palindrome and False otherwise. A\n palindrome is a symmetric sequence of characters, reading the same forward\n and backward.\n\n Use make_substring to modify the string for each recursive call.\n\n >>> is_palindrome(\"tacocat\")\n True\n >>> is_palindrome(\"palindrome\")\n False\n \"\"\"\n\n\n\n\ndef swap_chars(chars: str) -> str:\n \"\"\"\n Return a string in which each pair of adjacent characters in the given\n string have switched positions. If the number of characters in the string\n is odd, leave the position of the final character unchanged.\n\n Use make_substring to modify the string on each recursive call.\n\n >>> swap_chars(\"AaBbCcD\")\n \"aAbBcCD\"\n \"\"\"\n\n\n\n\ndef length(head: Optional[ListNode]) -> int:\n \"\"\"\n Return the number of nodes in the given linked list.\n\n >>> length(ListNode(1, ListNode(2, ListNode(3, None))))\n 3\n \"\"\"\n\n\n\n\ndef find_max(head: ListNode) -> int:\n \"\"\"\n Return the highest integer in the given linked list. Assume the linked list\n is not empty.\n\n >>> find_max(ListNode(2, ListNode(3, ListNode(4, ListNode(1, None)))))\n 4\n \"\"\"\n\n\n\n\ndef reverse(head: Optional[ListNode],\n acc: Optional[ListNode]) -> Optional[ListNode]:\n \"\"\"\n Return the reverse of the given linked list.\n\n Use the accumulator to build the reversed list as an argument to the\n recursive calls, instead of building the reversed list after each recursive\n call returns.\n\n >>> reverse(ListNode(1, ListNode(2, ListNode(3, None))), None)\n ListNode(3, ListNode(2, ListNode(1, None)))\n \"\"\"\n\n\n\n\nclass NestingDoll:\n\n def __init__(self, count: int) -> None:\n \"\"\"\n Representation of a nesting (Matryoshka) doll, with count specifying\n how many dolls are to be created. Each NestingDoll should have exactly\n one attribute, inner, which is either a NestingDoll or, if it is the\n innermost doll, None. Do not add an attribute for the count parameter.\n\n >>> doll = NestingDoll(3)\n >>> doll.inner.inner.inner == None\n True\n \"\"\"\n\n\n\n\n def __eq__(self, other: \"NestingDoll\") -> bool:\n \"\"\"\n Return True if both NestingDoll objects have the same number of nested\n dolls and False otherwise.\n\n >>> NestingDoll(1) == NestingDoll(1)\n True\n >>> NestingDoll(1) == NestingDoll(2)\n False\n \"\"\"\n\n\n\n\n def __repr__(self) -> str:\n \"\"\"\n Return a string representing the structure of the NestingDoll, using\n nested parentheses for each outer doll and 8 (the number eight) for the\n innermost doll.\n\n >>> doll = NestingDoll(3)\n >>> str(doll)\n \"((8))\"\n \"\"\"\n\n"} {"doc_id": "2a96ba170795787269c54b1af41f31dd", "text": "#!/usr/local/bin/python3.9\n\n# Filnamn: \u00f6vn 4.6 - kreditv\u00e4rdig - kap 4, sid. 8.py\n\n# Skapa program eller skript\n# Programmerings\u00f6vningar till kapitel 4 - Arbetsbok\n\n# Programmet fr\u00e5gar efter \u00e5lder, \u00e5rsinkomst samt ev. kreditanm\u00e4rkningar och \n# informerar sedan anv\u00e4ndaren om hen beviljas betala med faktura eller inte\n\n# Skriv ut programmets rubrik\nprint('Kreditv\u00e4rdighetskontroll')\nprint('========================\\n')\n\n# Fr\u00e5ga anv\u00e4ndaren hur gammal hen \u00e4r\n\u00e5lder = int(input('Ange din \u00e5lder: '))\n\n# Fr\u00e5ga anv\u00e4ndaren om dennes brutto \u00e5rsinkomst\n\u00e5rsInkomst = int(input('Ange din brutto \u00e5rsinkomst: '))\n\n# Fr\u00e5ga anv\u00e4ndaren om hen har n\u00e5gon betalningsanm\u00e4rkning\nanm\u00e4rkning = input('Har du n\u00e5gon betalningsanm\u00e4rkning (j/n): ')\n\n# Kontrollera om anv\u00e4ndaren \u00e4r 18 \u00e5r eller \u00e4ldre och om hen tj\u00e4nar 120000 eller mer samt att hen inte har n\u00e5gon betalningsanm\u00e4rkning\nif \u00e5lder >= 18 and \u00e5rsInkomst >= 120000 and (anm\u00e4rkning == 'n' or anm\u00e4rkning == 'N'):\n print('Fakturabetalning beviljad!')\nelse:\n print('Tyv\u00e4rr kan vi inte bevilja fakturabetalning!')\n"} {"doc_id": "2afe21cf40db7394166b0948d49d0464", "text": "import math\n\nclass Board(object):\n '''\n CLASS DESCRIPTION:\n An object class to maintain the attributes of the Battlesnake game board.\n\n ----------\n ATTRIBUTES:\n width - width of the game board.\n height - height of the game board.\n food - list of x & y tuples that describe the coordinates of all food on the board.\n grid - a 2D list of values describing the objects on the board at all coordinates.\n \n ----------\n METHODS:\n __init__(self, width, height, food):\n Creates an instance of a Battlesnake game board.\n\n get_grid_space(self, x, y):\n Returns the value (string) occupying the tile at the x & y coordinates of the grid.\n '''\n \n def __init__(self, width, height, food, grid, turn):\n self.width = width\n self.height = height\n self.food = food\n self.grid = grid\n self.turn = turn\n\n def get_grid_space(self, x, y):\n try:\n row = y\n col = x\n grid_space = self.grid[row][col]\n\n except IndexError:\n return ''\n return grid_space\n\n\nclass Snake(object):\n '''\n CLASS DESCRIPTION:\n An object class for instances of snakes.\n\n ----------\n ATTRIBUTES:\n body - list of x & y tuples that form the body of a snake, with the head being first tuple\n (x, y) - tuple holding the x & y coordinates of a portion of the snake\n \n health - integer representing the remaining health of the snake\n\n states - list of strings containing the important states of the snake on a current move\n\n ----------\n METHODS:\n __init__(self, body, health):\n Creates an instance of an existing snake in the arena.\n\n get_head(self):\n Returns the head of the snake, even if it doesn't have a head attribute.\n\n get_length(self):\n Returns the total length of the snake.\n\n get_invalid_dir(self):\n Returns the direction, from the head, where the snake cannot travel, determined by\n the location of its next body part. This also decribes the\n direction that the snake selected on the previous turn.\n\n get_distance_to(self, target):\n Returns the direct distance (float) to the passed target object by using Pythagorus.\n Does not worry about direction or order of moves. Target object is a set of x & y coordinates.\n\n dirs_towards(self, target):\n Returns all valid directions (list of strings) towards approaching the passed target.\n Target object is a set of x & y coordinates.\n \n '''\n def __init__(self, body, health):\n self.body = body\n self.health = health\n\n self.states = []\n\n def get_head(self):\n return tuple(self.body[0])\n\n def get_tail(self):\n return tuple(self.body[len(self.body) - 1])\n\n def get_length(self):\n return len(self.body)\n\n def get_invalid_dir(self):\n try:\n x, y = self.body[0]\n body_x, body_y = self.body[1]\n\n except IndexError:\n return \"\"\n\n if x == body_x and y < body_y:\n return \"down\"\n \n elif x == body_x and y > body_y:\n return \"up\"\n\n elif y == body_y and x > body_x:\n return \"left\"\n\n return \"right\"\n\n def get_distance_to(self, target):\n x, y = self.get_head()\n target_x, target_y = target\n return float(math.sqrt( abs((x - target_x)^2) + abs((y - target_y)^2) ))\n\n def dirs_towards(self, target):\n target_x, target_y = target\n x, y = self.get_head()\n directions = []\n if y > target_y:\n directions.append(\"up\")\n if y < target_y:\n directions.append(\"down\")\n if x > target_x:\n directions.append(\"left\")\n if x < target_x:\n directions.append(\"right\")\n return directions\n\n def add_state(self, state):\n self.states.append(state)\n \n\n\nclass Influence(object):\n '''\n CLASS DESCRIPTION:\n An object class to maintain the calculation of influences to determine game movement.\n\n ----------\n ATTRIBUTES:\n move_up - total of influences towards moving up (-y)\n\n move_down - total of influences towards moving down (+y)\n\n move_left - total of influences towards moving left (-x)\n\n move_right - total of influences towards moving right (+x)\n\n ----------\n METHODS:\n __init__(self):\n Creates an instance of an influence tracker.\n\n inc_up(self, multiple):\n Increments the influence towards moving up by the passed amount.\n\n inc_down(self, multiple):\n Increments the influence towards moving down by the passed amount.\n\n inc_left(self, multiple):\n Increments the influence towards moving left by the passed amount.\n\n inc_right(self, multiple):\n Increments the influence towards moving right by the passed amount.\n '''\n def __init__(self):\n self.move_up = 0\n self.move_down = 0\n self.move_left = 0\n self.move_right = 0\n\n def inc_up(self, multiple):\n self.move_up += 1 * multiple\n\n def inc_down(self, multiple):\n self.move_down += 1 * multiple\n\n def inc_left(self, multiple):\n self.move_left += 1 * multiple\n\n def inc_right(self, multiple):\n self.move_right += 1 * multiple"} {"doc_id": "2b4c7ac753da71f99f4593989350c3b5", "text": "# for loop - will stop once x goes through all the values of range() or an array, range being a function that makes an array of numbers\n\"\"\"\nfor x in range(5):\n print(x)\n\nprint(\"\")\n\n# while loop - will stop once a reaches the same value as b\na = 3\nb = 8\nwhile (a != b):\n print(\"Still true!\")\n a += 1\n\nprint(\"\")\n\n## break & continue statements\n# break will exit any kind of loops\ncount = 0\nwhile True:\n print(count)\n count += 1\n if count >= 3:\n break\n\nprint(\"\")\n\n# whereas continue will skip the current loop and go back to the for or while statement\nfor x in range(12):\n # Checking if x is an even number\n if x % 2 == 0:\n continue\n print(x)\n\nprint(\"\")\n\"\"\"\n\n# Loops\n# -------------------\n\n# While\ncondition = True\nwhile(condition):\n print(\"True!\")\nelse:\n print(\"Not True anymore...\")\n\n"} {"doc_id": "2c04d5deeddec74b6ad814e44e69c163", "text": "\n\n'''number = [0,1,2,3,4,5,6,7,8,9,10]\n\nfor num in number:\n\tif num == 0:\n\t\tpass\n\n\telif num % 2 == 0:\n\t\tprint(\"The number {} is an even number\". format(num))\n\n\telse:\n\t\tprint(\"The number {} is an odd number\". format(num))'''\n \n'''real_pass = \"*tech_studio\"\n\ncount = 3\n\nwhile count > 0:\n\tuser = input(\"Enter the password:\")\n\n\t\n\n\n\tif real_pass == user:\n\t\tprint(\"You got the password, access granted\")\n\t\tcount = 0\n\n\telse:\n\t\tprint(\"Wrong password, access denied\")\n\t\tprint(\"You have {} more tries\". format(count - 1))\n\t\tcount = count - 1'''\n\n\n#real_pass = str(5)\n\n##count = 3\n\n\"\"\"while count > 0:\n\tuser = input(\"Guess the number:\")\n\n\tif real_pass == user:\n\t\tprint(\"You got the number, you are a genius\")\n\t\tcount = 0\n\n\telse:\n\t\tprint(\"Too bad you got the number wrong\")\n\t\tprint(\"You have {} more tries\". format(count - 1))\n\t\tcount = count - 1\n\n\nnumber =[1,2,3,4,5,6,7,8,9,10,11,12]\ny = []\nfor x in numbers\nprint(x)\nnumber = x * 4\nprint(number)\ny.append(number)\nprint(\"\")\nprint(\"the multiplication table 4 is: \",y)\"\"\"\n\n\"\"\"def main():\n\t\ta = int(input(\"Enter a number here: \"))\n\t\tb = int(input(\"Enter another number here: \"))\n\n\t\tsums = addTwo(a,b)\n\t\tminus = subTwo(a,b)\n\t\tmuls = mulTwo(a,b)\n\t\tdivs = divTwo(a,b)\n\t\tprint(\"sum:{}, subs:{}, multi:{}, division:{}\". format(sums,minus,muls,divs))\n\ndef addTwo(x,y):\n\t\tsums = x + y\n\t\treturn sums\n \ndef subTwo(x,y):\n \tsubs = x - y\n \treturn subs\n\ndef mulTwo(x,y):\n \tmuls = x * y\n \treturn muls\n\ndef divTwo(x,y):\n \tdivs = x/y\n \treturn divs\n\nmain()\"\"\"\n \n\"\"\"data = input(\"Enter words: \")\nspot = []\nfor item in data:\n\tif item in spot:\n\t\tprint(\"not isogram\")\n\t\tbreak\n\telse:\n\t\tspot.append(item)\"\"\"\n\n\na = 60\nb = 6\nprint(a*b)\n\nimport math\nprint(math.cos(80))\n\nimport random\n\nprint(random.randrange(1, 10))\n\na = \"Hello, World!\"\nprint(a[7])\n\nnumber = [1,2,3,4,5,6,7,8,9,10]\ny = []\nfor x in number\nprint(x)\nnumber = x * 4\nprint(number)\ny.append(number)\nprint(\"\")\nprint(\"the multiplication table 4 is:\", y)\n"} {"doc_id": "2c58f66948cae373247199d147181947", "text": "# --------------- Section 2 --------------- #\n\n# Relevant Documentation\n# print()\n# python.org | https://docs.python.org/3/library/functions.html#print\n# W3Schools | https://www.w3schools.com/python/ref_func_print.asp\n\n# Read about the sep argument on the W3Schools documentation. sep is an optional argument. One that can be set if we\n# we want to. To set an optional argument, we specify its name, or its identifier. Then we use the equals sign,\n# followed by a string that will act as the separator.\n\nprint('Separating', 'words', 'with', 'something', 'new!', sep='@')\n\n# When specifying the sep argument, you must set it as the last argument in the function.\n\n# Project 2.1\n# 1) Print your first and last name separated with _ by using the sep argument.\n# 2) Print the date in numerical form, using the / as the sep argument for the separator between the numbers.\n# 3) Print abc separated with ### between each letter.\n#\n# Example Output\n# elia_deppe\n# 06/13/21\n# a###b###c\n#\n# WRITE CODE BELOW\n\n"} {"doc_id": "2c6afcea9cf81b4cf8ab9aea5be17005", "text": "# Create a Python script file named data_types_and_variables.py. Inside it, write some \n# Python code, that is, variables and operators, to describe the following scenarios. \n# Do not worry about the real operations to get the values, the goal of these exercises \n# is to understand how real world conditions can be represented with code.\n\n\n# You have rented some movies for your kids: The little mermaid (for 3 days), Brother \n# Bear (for 5 days, they love it), and Hercules (1 day, you don't know yet if they're \n# going to like it). If price for a movie per day is 3 dollars, how much will you have \n# to pay?\n\nlittle_mermaid_days = 3 #Variables hold nouns\nbrother_bear_days = 5\nhercules_days = 1\nprice_per_movie = 3\n\n\nprint(3 * (little_mermaid + brother_bear + hercules))\n\n-- 27\n\n# Suppose you're working as a contractor for 3 companies: Google, Amazon and Facebook, \n# they pay you a different rate per hour. Google pays 400 dollars per hour, Amazon 380,\n# and Facebook 350. How much will you receive in payment for this week? You worked 10 \n# hours for Facebook, 6 hours for Google and 4 hours for Amazon.\n\ngoogle_rate = 400\namazon_rate = 380\nfacebook_rate = 350\ngoogle_hours = 6\namazon_hours = 4\nfacebook_hours = 10\namazon_subtotal = amazon_hours * amazon_rate\ngoogle_subtotal = google_hours * google_rate\nfacebook_subtotal = facebook_hours * facebook_rate\ntotal = amazon_subtotal + facebook_subtotal + google_subtotal\n\nf\"${total} is the total of consulting with these companies\"\n\n-- '$7420 is the total of consulting with these companies'\n\n\n# A student can be enrolled to a class only if the class is not full and the class schedule\n# does not conflict with her current schedule.\n\nclass_has_space = True\nschedule_works = True\ncan_be_enrolled = class_has_space and schedule_works\ncan_be_enrolled \n\n-- True\n# A product offer can be applied only if people buys more than 2 items, and the offer has not\n# expired. Premium members do not need to buy a specific amount of products.\n\nhas_not_expired = True\nbuys_two_or_more = True\nis_premium_member = True\noffer_available = has_not_expired and (buys_two_or_more or is_premium_member)\noffer_available\n\n-- True\n\n\n# Use the following code to follow the instructions below:\n\n# username = 'codeup'\n# password = 'notastrongpassword'\n# Create a variable that holds a boolean value for each of the following conditions:\n\n-- the password must be at least 5 characters\n-- the username must be no more than 20 characters\n-- the password must not be the same as the username\n-- bonus neither the username or password can start or end with whitespace\n#~~~~~~~~~~~~~~~~~~~~\nif username[0] != ' ' and username[-1] != ' '\nand password[0] != ' ' and password[0] != ' '\n#~~~~~~~~~~~~~~~~~~~\n\npw_is_at_least_five_characters = len(password) >= 5\nusername_less_than_twenty == len(username) <= 20\npassword_differs_from_username = username != password\npassword_no_begin_or_end_whitespace = password == password.strip()\nusername_no_begin_or_end_whitespace = username == username.strip()"} {"doc_id": "2c8ae1186e86165c3dd52e0e81750bf5", "text": "# Escreva um programa para aprovar o empr\u00e9stimo banc\u00e1rio para a compra de uma casa.\n# O programa vai perguntar o valor da casa, o sal\u00e1rio do comprador e em quantos anos ele vai pagar.\n# Calcule o valor da presta\u00e7\u00e3o mensal, sabendo que ela n\u00e3o pode exceder 30% do sal\u00e1rio ou ent\u00e3o o empr\u00e9stimo ser\u00e1 negado.\n\nfrom time import sleep\n\ncolors = {\n 'clear': '\\033[m',\n 'txtRedBold': '\\033[1:31m',\n 'txtGreenBold': '\\033[1:32m',\n 'txtYellowBold': '\\033[1:33m',\n 'txtBlueBold': '\\033[1:34m',\n}\n\nprint('{}====================={}' .format(colors['txtYellowBold'], colors['clear']))\nprint('{} EMPR\u00c9STIMO BANC\u00c1RIO{}' .format(colors['txtYellowBold'], colors['clear']))\nprint('{}====================={}' .format(colors['txtYellowBold'], colors['clear']))\n\nhouseValue = float(input('Valor da casa: R$ '))\nbuyerSalary = float(input('Sal\u00e1rio do comprador: R$ '))\nfinancingYears = int(input('Quantos anos de financiamento? '))\n\nprint('\\n{}Aguarde!{}' .format(colors['txtYellowBold'], colors['clear']))\nprint('{}Calculando valor da presta\u00e7\u00e3o mensal....{}' .format(colors['txtBlueBold'], colors['clear']))\nsleep(1)\n\nfinancingValue = houseValue / (financingYears * 12)\nthirtyPercentSalary = (buyerSalary / 100) * 30\n\nprint('\\nPara pagar uma casa de R$ {:.2f} em {} anos, a presta\u00e7\u00e3o ser\u00e1 de R$ {:.2f}.' .format(houseValue, financingYears, financingValue))\n\nif financingValue <= thirtyPercentSalary:\n print('\\n{}Empr\u00e9stimo pode ser CONCEDIDO!{}'.format(colors['txtGreenBold'], colors['clear']))\nelse:\n print('\\n{}Empr\u00e9stimo NEGADO!{}'.format(colors['txtRedBold'], colors['clear']))\n"} {"doc_id": "2c91887db8ec1f1bd4fff55a6a70a001", "text": "import secrets\nfrom random import shuffle\nfrom string import ascii_letters, ascii_lowercase, ascii_uppercase, digits, punctuation\n\n\ndef password_generator(length: int = 8) -> str:\n \"\"\"\n Password Generator allows you to generate a random password of length N.\n\n >>> len(password_generator())\n 8\n >>> len(password_generator(length=16))\n 16\n >>> len(password_generator(257))\n 257\n >>> len(password_generator(length=0))\n 0\n >>> len(password_generator(-1))\n 0\n \"\"\"\n chars = ascii_letters + digits + punctuation\n return \"\".join(secrets.choice(chars) for _ in range(length))\n\n\n# ALTERNATIVE METHODS\n# chars_incl= characters that must be in password\n# i= how many letters or characters the password length will be\ndef alternative_password_generator(chars_incl: str, i: int) -> str:\n # Password Generator = full boot with random_number, random_letters, and\n # random_character FUNCTIONS\n # Put your code here...\n i -= len(chars_incl)\n quotient = i // 3\n remainder = i % 3\n # chars = chars_incl + random_letters(ascii_letters, i / 3 + remainder) +\n # random_number(digits, i / 3) + random_characters(punctuation, i / 3)\n chars = (\n chars_incl\n + random(ascii_letters, quotient + remainder)\n + random(digits, quotient)\n + random(punctuation, quotient)\n )\n list_of_chars = list(chars)\n shuffle(list_of_chars)\n return \"\".join(list_of_chars)\n\n # random is a generalised function for letters, characters and numbers\n\n\ndef random(chars_incl: str, i: int) -> str:\n return \"\".join(secrets.choice(chars_incl) for _ in range(i))\n\n\ndef random_number(chars_incl, i):\n pass # Put your code here...\n\n\ndef random_letters(chars_incl, i):\n pass # Put your code here...\n\n\ndef random_characters(chars_incl, i):\n pass # Put your code here...\n\n\n# This Will Check Whether A Given Password Is Strong Or Not\n# It Follows The Rule that Length Of Password Should Be At Least 8 Characters\n# And At Least 1 Lower, 1 Upper, 1 Number And 1 Special Character\ndef is_strong_password(password: str, min_length: int = 8) -> bool:\n \"\"\"\n >>> is_strong_password('Hwea7$2!')\n True\n >>> is_strong_password('Sh0r1')\n False\n >>> is_strong_password('Hello123')\n False\n >>> is_strong_password('Hello1238udfhiaf038fajdvjjf!jaiuFhkqi1')\n True\n >>> is_strong_password('0')\n False\n \"\"\"\n\n if len(password) < min_length:\n # Your Password must be at least 8 characters long\n return False\n\n upper = any(char in ascii_uppercase for char in password)\n lower = any(char in ascii_lowercase for char in password)\n num = any(char in digits for char in password)\n spec_char = any(char in punctuation for char in password)\n\n return upper and lower and num and spec_char\n # Passwords should contain UPPERCASE, lowerase\n # numbers, and special characters\n\n\ndef main():\n length = int(input(\"Please indicate the max length of your password: \").strip())\n chars_incl = input(\n \"Please indicate the characters that must be in your password: \"\n ).strip()\n print(\"Password generated:\", password_generator(length))\n print(\n \"Alternative Password generated:\",\n alternative_password_generator(chars_incl, length),\n )\n print(\"[If you are thinking of using this passsword, You better save it.]\")\n\n\nif __name__ == \"__main__\":\n main()\n"} {"doc_id": "2cae8081d1e524adb40f166e38d9c0a4", "text": "\"\"\"\nThe six most commonly used letters in the English language can be remembered with\nthe mnemonic \u201cetaoin\u201d. Write a Python script that takes a\nsentence (string) as input and returns a simple bar chart\u2013type display\n\"\"\"\n\n\ndef alphabet_bar_chart(sentence: str):\n \"\"\"\n The function creates an alphabet bar chart from a sentence.\n Parameters\n ----------\n sentence: str\n A sentence.\n Returns\n -------\n Dictionary\n A dictionary of lists, with alphabets as keys.\n \"\"\"\n sentence = sentence.lower()\n dictionary = {}\n for letter in sorted(list(sentence)):\n if letter.isalpha():\n if letter in dictionary:\n dictionary[letter].append(letter)\n else:\n dictionary[letter] = [letter]\n return dictionary\n\n\nif __name__ == \"__main__\":\n SEN = \"\"\"\n The six most commonly used letters in the English language can be remembered with the mnemonic \u201cetaoin\u201d.\n \"\"\"\n print(alphabet_bar_chart(SEN))\n"} {"doc_id": "2cbb0be89020f0bd6a6e0e06c90b6b91", "text": "#!/usr/bin/env python3\n\n#Assignement:\n# Create a program that accepts a float as input and then convert it from km/h to m/s or vice versa\n# Have a menu that allows the user to choose between the two function and contains enough information\n#for a good user experience\n# Print the answers with 2 decimals\n# Use try-except when applicable\n# Have fun!\n\nimport time\n\nvac_speed_of_light_mps = 299792458 #Speed of light in metres per second. We want to warn anyone who moves faster than this\n\ndef convert_kmph_to_mps(): #Asks for user input and then converts kilometres per hour to metres per second\n try:\n kmph = float(input(\"Hur m\u00e5nga km/h vill du konvertera till m/s? \"))\n mps = round(kmph / 3.6, 2) #Converts and rounds to 2 decimals\n if mps > vac_speed_of_light_mps:\n warp_speed(mps)\n print(\"\\nMed det sagt s\u00e5 \u00e4r \" + str(kmph) + \" km/h samma sak som \" + str(mps) + \" m/s.\\n\")\n else:\n print(\"\\n\" + str(kmph) + \" km/h \u00e4r samma sak som \" + str(mps) + \" m/s.\\n\")\n except ValueError: #Catch when an incorrectly formatted value is written or when letters are used\n print(\"Du m\u00e5ste ange en hastighet med hj\u00e4lp av siffor, kom ih\u00e5g att anv\u00e4nda dig av \\\".\\\" som skiljetecken.\\n\")\n except: #Quit gracefully when unforseen exceptions are thrown and inform the user on how to report them\n critical_error()\n\ndef convert_mps_to_kmph(): #Asks for user input and then converts metres per second to kilometres per hour\n try:\n mps = float(input(\"Hur m\u00e5nga m/s vill du konvertera till km/h? \"))\n kmph = round(mps * 3.6, 2) #Converts and rounds to 2 decimals\n if mps > vac_speed_of_light_mps:\n warp_speed(mps)\n print(\"\\nMed det sagt s\u00e5 \u00e4r \" + str(mps) + \" m/s samma sak som \" + str(kmph) + \" km/h.\\n\")\n else:\n print(\"\\n\" + str(mps) + \" m/s \u00e4r samma sak som \" + str(kmph) + \" km/h.\\n\")\n except ValueError: #Catch when an incorrectly formatted value is written or when letters are used\n print(\"Du m\u00e5ste ange en hastighet med hj\u00e4lp av siffor, kom ih\u00e5g att anv\u00e4nda dig av \\\".\\\" som skiljetecken.\\n\")\n except: #Quit gracefully when unforseen exceptions are thrown and inform the user on how to report them\n critical_error()\n\ndef warp_speed(mps): #We call this when people move faster than light\n diff = round(mps - vac_speed_of_light_mps, 2)\n print(\"\\nF\u00f6rhoppningsvis \u00e4r hastigheten du matade in inte en del av en st\u00f6rre ber\u00e4kning?\\n\\\nDin hastighet \u00e4r \" + str(diff) + \" m/s h\u00f6gre \u00e4n ljusets hastighet i vakuum och s\u00e5 fort kan inget k\u00e4nt f\u00f6rem\u00e5l r\u00f6ra sig.\\n\\\nOm du har gjort korrekta ber\u00e4kningar och/eller st\u00f6tt p\u00e5 n\u00e5got som r\u00f6r sig s\u00e5 h\u00e4r fort rekommenderar jag att du kontaktar ESA\")\n\ndef critical_error(): #We call this when an unknown exception is thrown\n print(\"\"\"N\u00e5gonting gick v\u00e4ldigt fel. Om felet \u00e4r m\u00f6jligt att reproducera v\u00e4nligen skapa ett \u00e4rende p\u00e5 f\u00f6ljande sida:\\n https://github.com/Dazpoet/Learning-python/issues\"\"\")\n print(\"Programmet avslutas om: \")\n \n counter = 5\n while counter > 0: #Give the user a few seconds to consider the error before quitting, prevents window from closing prematurely\n print(counter)\n time.sleep(1)\n counter -= 1\n \n quit()\n\ndef easter_egg(): #Easter egg for the initiated\n print (\"\\n\\nDu hittade den magiska Dazrullen!\")\n print(\"\"\" _\n .--\"\"--.___.._\n ( <__> ) `-.\n |`--..--'| <|\n | :| /\n | :|--\"\"-./\n `.__ __;' o!O\n \"\" \n\n------------------------------------------------\nThis ASCII art was fetched from http://www.ascii-art.de/ascii/t/toiletpaper.txt\nArtist: Ojoshiro\n\nIf you are the copyright-holder of this art and would like it removed please open an issue at:\nhttps://github.com/Dazpoet/Learning-python/issues and it will be removed with due haste.\n\"\"\")\n\ndef main(): #Open a menu and call relevant functions depending on the choice made\n print(\"\"\"\\nV\u00e4lkommen till Willes enhetskonverterare!\\n\\n\\\nMed detta smarta program beh\u00f6ver du aldrig igen oroa dig \u00f6ver hur man konverterar mellan km/h och m/s eftersom programmet g\u00f6r det \u00e5t dig.\\n\"\"\")\n \n menu = True\n while menu:\n try:\n answer = int(input(\"\"\"Vad vill du g\u00f6ra?\n 1. Konvertera km/h till m/s\n 2. Konvertera m/s till km/h\n 3. Avsluta programmet\n \"\"\"))\n if answer == 1:\n convert_kmph_to_mps()\n elif answer == 2:\n convert_mps_to_kmph()\n elif answer == 3:\n menu = False\n elif answer == 99:\n easter_egg()\n else:\n print(\"Du m\u00e5ste ange 1, 2 eller 3 f\u00f6r att komma vidare\\n\")\n except ValueError:\n print(\"\"\"Du m\u00e5ste ange en siffra: helst 1, 2 eller 3 men kanske finns det ett fj\u00e4rde alternativ?\\nMan kan aldrig vara riktigt hundra...\\n\"\"\")\n except:\n critical_error()\n\nmain()"} {"doc_id": "2cca8e8e4d706060fb971e2802637445", "text": "#--------------------Value Errors -------------------#\r\n\r\n################### Example 1 ########################\r\n#ValueError: invalid literal for int() with base 10: ' '\r\n#Cause: trying to convert something to an integer\r\n#that doesn't represent an integer\r\n\r\n#To generate this error, run the program and put a\r\n#letter, punctuation, space, etc. in the input field\r\n\r\n\r\nimport simplegui\r\n\r\ndef input_guess(guess):\r\n print int(guess)\r\n text_field.set_text(\"\")\r\n\r\n\r\n# Create a frame and assign callbacks to event handlers\r\nframe = simplegui.create_frame(\"Value Error #1\", 300, 200)\r\ntext_field = frame.add_input(\"Put a non-digit character here and press enter: \", input_guess, 100)\r\n\r\n# Start the frame animation\r\nframe.start()\r\n\r\n#This program will function correctly if you enter a \r\n#digit in the text box, and error out otherwise. That's\r\n#because while digits can be represented as integers,\r\n#other characters, like a, b, c, etc., cannot*. When \r\n#Python tries to convert 'a' into an integer, it finds\r\n#that there is no associated value for it, and errors out.\r\n#This error could have been generated in just one line,\r\n#but I wanted to put it in a format that was more like \r\n#what you would see in the mini project (namely, GTN).\r\n\r\n\r\n#Ok, so other characters can and are represented as integers.\r\n#It's called ASCII, and each character has a corresponding\r\n#integer value. However, int() does not take that value\r\n#into account, so we still get an error. \r\n"} {"doc_id": "2d06c60aa295cd6dbf7b6929090f4ec3", "text": "\"\"\"\nFile: weather_master.py\nName: Andrew Chao\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\nEXIT = -1\n\n\ndef main():\n\tprint('stanCode \"Weather Master 4.0\"!')\n\n\ttemp = int(input('Next Temperature: (or ' + str(EXIT) + ' to quit)?'))\n\n\t# Initial values for the Weather Master 4.0\n\tmax_temp = temp\n\tmin_temp = temp\n\tday = 1\n\tsum_temp = temp\n\n\t# Check whether the first temperature is under 16 degrees\n\tif temp < 16:\n\t\tcold_day = 1\n\telse:\n\t\tcold_day = 0\n\n\tif temp == EXIT:\n\t\t# Program will stop if the first temperature is equal to EXIT number\n\t\tprint('No temperatures were entered.')\n\n\telse:\n\t\t# Allow more temperatures to be entered by users\n\t\twhile True:\n\t\t\ttemp = int(input('Next Temperature: (or' + str(EXIT) + 'to quit)?'))\n\t\t\tif temp == EXIT:\n\t\t\t\tbreak\n\t\t\telse:\n\t\t\t\t# Find the highest temperature\n\t\t\t\tif temp > max_temp:\n\t\t\t\t\tmax_temp = temp\n\n\t\t\t\t# Find the lowest temperature\n\t\t\t\tif temp < min_temp:\n\t\t\t\t\tmin_temp = temp\n\n\t\t\t\t# Count days\n\t\t\t\tday += 1\n\n\t\t\t\t# Sum temperatures\n\t\t\t\tsum_temp += temp\n\n\t\t\t\t# Count cold days\n\t\t\t\tif temp < 16:\n\t\t\t\t\tcold_day += 1\n\n\t\tprint('Highest temperature = ' + str(max_temp))\n\t\tprint('Lowest temperature = ' + str(min_temp))\n\t\tprint('Average = '+str(sum_temp / day))\n\t\tprint(str(cold_day) + ' cold day(s)')\n\n\n###### DO NOT EDIT CODE BELOW THIS LINE ######\n\nif __name__ == \"__main__\":\n\tmain()\n"} {"doc_id": "2d77543477596c2ddf471a27e57d514c", "text": "# https://docs.python.org/3/library/functions.html\n\n# absoluten Wert\nmy_number = -10.2\nprint(abs(my_number))\n\nprint(\"----------\")\n\nmy_experiment = [True, True, True]\n# wenn mind. 1 True -> True\nprint(any(my_experiment))\n# wenn alle True -> True sonst False\nprint(all(my_experiment))\n\nmy_numbers = [-1, 1, 2]\nprint(all(my_numbers))\n\nprint(\"----------\")\n\nmy_character = 'J'\n# Nummer des Characters\nprint(ord(my_character))\n# Character der Nummer\nprint(chr(74))\n\nprint(\"----------\")\n\n# Integerdivision und Rest\nprint(divmod(10, 3)) # Integerdivision: 10 // 3, und Rest: 10 % 3\n\nprint(\"----------\")\n\n# Liste \"umdrehen\"\nprint(list(reversed(my_numbers)))"} {"doc_id": "2dd4d335e41fc4b0b233982adb2ac235", "text": "\"\"\"\nFile: similarity.py\nName:Cherry\n----------------------------\nThis program compares short dna sequence, s2,\nwith sub sequences of a long dna sequence, s1\nThe way of approaching this task is the same as\nwhat people are doing in the bio industry.\n\"\"\"\n\n\ndef main():\n \"\"\"\n TODO:\n step:\n 1.cut the long_sequence to become cut_sequence\n 2.comparing the similarity between cut_sequence and short_sequence\n considering:\n 1.How many variables I need? # (\u6709\u591a\u5c11\u8b8a\u6578\uff1f\u88ab\u5207\u5206\u7684\u6bb5\u3001\u6700\u9ad8\u5206\u7684\u6bb5\u3001\u76f8\u4f3c\u5ea6\u5206\u6578\u3001\u6700\u9ad8\u5206)\n (1)cut_sequence (2)best_sequence (3)similarity (4)highest_similarity\n 2.What fixed number I would usually need? # (\u56fa\u5b9a\u7684\u6578\uff1flong\u7684\u9577\u5ea6\u3001short\u7684\u9577\u5ea6(\u6bcf\u4e00\u6bb5\u6bd4\u8f03\u591a\u5c11\u6b21)\u3001\u6bd4\u8f03\u591a\u5c11\u6bb5)\n (1)len(long_sequence)\n (2)len(short_sequence) == the times of comparing each cut_sequence\n (3)the amount of cut_sequence == len(long_sequence)-len(short_sequence)+1\n \"\"\"\n long_sequence = input('Please give me a DNA sequence to search: ')\n short_sequence = input('What DNA sequence would you like to match?')\n long_sequence = long_sequence.upper()\n short_sequence = short_sequence.upper()\n best_sequence = ''\n highest_similarity = 0\n for i in range(len(long_sequence)-len(short_sequence)+1): # repeat comparing different cut_sequence(\u6bd4\u8f03\u591a\u5c11\u6bb5)\n # step1.cut the long_sequence to become cut_sequence\n cut_sequence = '' # make new variable of cut_sequence(\u65b0\u7af9\u7c64\u300c\u88ab\u5207\u5206\u7684\u6bb5\u300d)\n while len(cut_sequence) != len(short_sequence): # (\u4e00\u500b\u500b\u5b57\u6bcd\u4e32\u4e0a\u53bb\uff0c\u76f4\u5230\u7af9\u7c64\u9577\u5ea6\u7b49\u65bcshort_sequence)\n for k in range(len(short_sequence)): # (\u6bcf\u6bb5\u8d77\u59cb\u4e32\u7684\u4f4d\u7f6e)\n cut_sequence += long_sequence[i+k]\n # get cut_sequence!!! # (\u5c31\u6703\u5f97\u5230\u300c\u88ab\u5207\u5206\u7684\u6bb5\u300d)\n if i == 0:\n best_sequence = cut_sequence # get best_sequence!(\u5f97\u5230\u300c\u6700\u9ad8\u5206\u7684\u6bb5\u300d)\n similarity = 0 # get similarity!(\u8b8a\u6578\u300c\u76f8\u4f3c\u5ea6\u5206\u6578\u300d)\n highest_similarity = similarity # get highest_similarity!(\u5f97\u5230\u300c\u6700\u9ad8\u5206\u300d)\n # step2.comparing the similarity between cut_sequence and short_sequence\n similarity = 0\n for j in range(len(short_sequence)): # (\u6bcf\u4e00\u6bb5\u6bd4\u8f03\u591a\u5c11\u6b21)\n if cut_sequence[j] == short_sequence[j]: # (\u7576\u540c\u500b\u4f4d\u7f6e\u4e0a\uff0c\u300c\u88ab\u5207\u5206\u7684\u6bb5\u300d=short_sequence)\n similarity += 1 # (\u8b8a\u6578\u300c\u76f8\u4f3c\u5ea6\u5206\u6578\u300d+1)\n # according to the newest comparing renew the variables(\u4f9d\u64da\u6700\u65b0\u7684\u6bd4\u8f03\uff0c\u66f4\u65b0\u300c\u6700\u9ad8\u5206\u7684\u6bb5\u300d\u8207\u300c\u6700\u9ad8\u5206\u300d)\n if similarity > highest_similarity:\n best_sequence = cut_sequence\n highest_similarity = similarity\n print('The best match is ' + str(best_sequence))\n\n\n###### DO NOT EDIT CODE BELOW THIS LINE ######\nif __name__ == '__main__':\n main()\n"} {"doc_id": "2e1440d2573b69ec1bfea6418b2cfa68", "text": "#!/usr/bin/python3\n\"\"\"\nPacking and unpacking\n---------------------\nWrite a function which returns a tuple of first 10 and last 10 characters of an\ninput string. Use an output of that function to print the first 10, the last 10\ncharacters of some string and their concatenation.\n\"\"\"\n\n\ndef get_input_string():\n \"\"\"Read input string, and return it.\"\"\"\n return input(\"Enter input string: \")\n\n\ndef get_first_and_last(input_string):\n \"\"\"Get the first 10, and last 10 characters,\n and returns them as a tuple\n\n Args:\n input_string (str): string that will be used as source\n\n Returns:\n (str, str): tuple of first and last 10 chars in specified string\n \"\"\"\n return input_string[0: 10], input_string[-10:]\n\nif __name__ == '__main__':\n first, last = get_first_and_last(get_input_string())\n print(\"First: {}\".format(first))\n print(\"Last: {}\".format(last))\n print(\"Concatenation: {}\".format(\"\".join((first, last))))\n"} {"doc_id": "2e2e4d0395b3038cd959e6168bb12d07", "text": "\"\"\"\nFile: hangman.py\nName: Po Kai Feng\n-----------------------------\nThis program plays hangman game.\nUsers sees a dashed word, trying to\ncorrectly figure the un-dashed word out\nby inputting one character each round.\nIf the user input is correct, show the\nupdated word on console. Players have N_TURNS\nchances to try and win this game.\n\"\"\"\n\n\nimport random\n\n\n# This constant controls the number of guess the player has.\nN_TURNS = 7\n\n\ndef main():\n \"\"\"\n First print the dashed_word based on the length of answer.\n While user give a legal guess, check if the guess character is in answer.\n If the guess is correct, uncover the dashed_word with the guess.\n Or if the guess is wrong, makes guess_times plus one.\n While there were no dash in dashed_word or there is no chance to try, end game\n and show whether user win or lose and print the answer\n \"\"\"\n answer = random_word().upper()\n dashed_word = ''\n for i in range(len(answer)):\n dashed_word += '-'\n guess_times = 0\n while True:\n if guess_times == N_TURNS:\n # This is the last chance to guess and user failed\n print('You are completely hung :\\'(')\n break\n print('The word looks like: ' + dashed_word + '\\nYou have ' + str(N_TURNS - guess_times) + ' guesses left.')\n guess = input('Your Guess: ')\n if len(guess) == 1 and guess.isalpha():\n # Legal format\n guess = guess.upper()\n if answer.find(guess) != -1:\n # The guess is correct and should uncover the dashed_word\n print('You are correct!')\n dashed_word = uncover_dash(guess, answer, dashed_word)\n if not dashed_word.find('-') > -1:\n # No dash left.\n print('You win!!')\n break\n else:\n # Wrong guess\n guess_times += 1\n print('There is no ' + guess + '\\'s in the word.')\n else:\n print('Illegal format')\n print('The word was: ' + answer)\n\n\ndef random_word():\n num = random.choice(range(9))\n if num == 0:\n return \"NOTORIOUS\"\n elif num == 1:\n return \"GLAMOROUS\"\n elif num == 2:\n return \"CAUTIOUS\"\n elif num == 3:\n return \"DEMOCRACY\"\n elif num == 4:\n return \"BOYCOTT\"\n elif num == 5:\n return \"ENTHUSIASTIC\"\n elif num == 6:\n return \"HOSPITALITY\"\n elif num == 7:\n return \"BUNDLE\"\n elif num == 8:\n return \"REFUND\"\n\n\ndef uncover_dash(guess, answer, dashed_word):\n \"\"\"\n :param guess: str, the character that user type and has been converted to upper case\n :param answer: str, the answer word\n :param dashed_word: str, the present dashed_word\n :return: str, the new_dashed_word with all correct guess been shown in dashed_word\n \"\"\"\n new_dashed_word = ''\n for i in range(len(answer)):\n if guess == answer[i]:\n new_dashed_word += guess\n else:\n new_dashed_word += dashed_word[i]\n return new_dashed_word\n\n\n##### DO NOT EDIT THE CODE BELOW THIS LINE #####\nif __name__ == '__main__':\n main()\n"} {"doc_id": "2e5d8dee8c4bc34fa2175f4000881226", "text": "#################################################################\n# CSE 231 Project 4\n#\n# Functions\n# Defines functions for 5 different shapes\n# Creates 4 flags using mentioned shapes\n# Asks for a selection\n# If selection is invalid, asks for selection again\n# If selection is valid, runs the corresponding function\n# When finished, can input 'Q' to quit the program\n#################################################################\n\n#Import\nimport turtle\n\n#Input\nFLAG = '''\nSelect one of the following options:\n TUN: Tunisia\n LBY: Libya\n TUR: Turkey\n SGP: Singapore\n ALL: All flags\n Q: Quit\n'''\n\n#Rectangle Function\ndef rectangle(x,y,length,height,color): #Defines function 'rectangle'\n location = (x,y) #Sets location equal to first 2 given variables\n turtle.goto(location) #Goes to location specified above\n turtle.color(color) #Changes fill color to specified color above\n turtle.down() #Puts the pen down\n turtle.pencolor('black') #Changes pen color to black (Outline color)\n turtle.begin_fill() #Begins fill so created rectangle will be filled\n for r in range(2): #Starts a for loop to execute 2 times\n turtle.forward(length) #Moves turtle forward the length specified above\n turtle.left(90) #Turns turtle to left 90 degrees\n turtle.forward(height) #Moves turtle forward the height specified above\n turtle.left(90) #Turns turtle to left 90 degrees again\n turtle.end_fill() #Ends the fill\n turtle.up() #Lifts the pen up\n\n#Circle Function\ndef circle(x,y,radius,color): #Defines function 'circle'\n location = (x,y) #Sets location equal to first 2 given variables\n turtle.goto(location) #Goes to location specificed above\n turtle.color(color) #Changes fill color to specified color above\n turtle.down() #Puts the pen down\n turtle.begin_fill() #Begins fill so created circle will be filled\n turtle.circle(radius) #Creates a circle with radius specified above\n turtle.end_fill() #Ends the fill\n turtle.up() #Lifts the pen up\n\n#Crescent Function\ndef crescent(x1,y1,x2,y2,R1,R2,color1,color2): #Defines function 'crescent'\n c1_location = (x1,y1) #Creates variable for location of first circle\n c2_location = (x2,y2) #Creates variable for location of second circle\n turtle.goto(c1_location) #Moves turtle to location for first circle\n turtle.color(color1) #Changes fill color to color for first circle\n turtle.down() #Puts the pen down\n turtle.begin_fill() #Begins fill so created circle will be filled\n turtle.circle(R1) #Creates first circle with the specified radius\n turtle.end_fill() #Ends the fill\n turtle.up() #Lifts the pen up\n turtle.goto(c2_location) #Moves turtle to location for second circle\n turtle.color(color2) #Changes fill color to color for second circle\n turtle.down() #Puts the pen down again\n turtle.begin_fill() #Begins fill so created circle will be filled\n turtle.circle(R2) #Creates second circle with specified radius\n turtle.end_fill() #Ends the fill\n turtle.up() #Lifts pen up\n\n#Star Function\ndef star(x,y,size,color,theta): #Defines function 'star'\n location = (x,y) #Sets location equal to first 2 given variables\n turtle.up() #Lifts the pen up\n turtle.goto(location) #Goes to location specified above\n turtle.color(color) #Changes fill color to specified color above\n turtle.down() #Puts the pen down\n turtle.begin_fill() #Begins fill so created star will be filled\n turtle.right(200) #Changes starting direction of turtle\n for s in range(5): #Starts a for loop to execute 5 times\n turtle.forward(size) #Moves turtle forward specified amount\n turtle.right(theta) #Turns turtle to the right by specified amount\n turtle.forward(size) #Moves turtle forward again\n turtle.right(72 - theta) #Turns turtle to the right by half the amount\n turtle.end_fill() #Ends the fill\n turtle.up() #Lifts the pen up\n \n#Multi_Star Function\ndef multi_star(x,y,size,color): #Defines function 'multi_star'\n A = 240 #Sets A equal to 240\n location = (x,y) #Sets location equal to first 2 given variables\n turtle.goto(location) #Goes to location specified above\n turtle.color(color) #Changes fill color to color specified above\n turtle.down() #Puts pen down\n turtle.begin_fill() #Begins fill so created stars will be filled\n turtle.right(90) #Turns turtle to right 90 degrees\n star(x+(A/3),y+(A/2)+(A/4)+(A/16),size,color,144) #Creates a star\n turtle.right(90) #Turns turtle to right 90 degrees\n star(x+(A/3)+(A/40),y+(A/2)+(A/6),size,color,144) #Creates a star\n turtle.right(90) #Turns turtle to right 90 degrees\n star(x+(A/3)+(A/6),y+(A/2)+(A/8),size,color,144) #Creates a star\n turtle.right(90) #Turns turtle to right 90 degrees\n star(x+(A/3)+(A/4),y+(A/2)+(A/4),size,color,144) #Creates a star\n turtle.right(90) #Turns turtle to right 90 degrees\n star(x+(A/3)+(A/7),y+(A/2)+((A*2)/5.5),size,color,144) #Creates a star\n turtle.end_fill() #Ends the fill\n turtle.up() #Lifts pen up\n\n#Tunisian Flag Function\ndef Tun_flag(x,y,height): #Defines function 'Tun_flag'\n A = height #Sets A equal to the height\n rectangle(x,y,A*1.5,height,'red') #Creates the base of the flag\n circle(x+((1.5*A)/2),y+(A/4),A/4,'white') #Creates white circle in middle\n crescent(x+((1.5*A)/2),y+((A/4)+(A/16)),x+(((1.5*A)/2)+(A/20)),\\\n y+((A/4)+(A/16)+(A/32)),((3*A)/8)/2,((3*A)/10)/2,'red','white')\n #Creates a crescent in center of flag\n star(x+(((1.5*A)/2)+(A/40)),y+((A/2)-(A/40)),((9*A)/40)/3,'red',144)\n #Creats a star a little to the right of center\n\n#Libya Flag Function\ndef Lby_flag(x,y,height): #Defines function 'Lby_flag'\n A = height #Sets A equal to the height\n rectangle(x,y,1.5*A,A/4,'green') #Creates the bottom base of the flag\n rectangle(x,y+(A/4),1.5*A,A/2,'black') #Creates the middle base of the flag\n rectangle(x,y+((A*3)/4),1.5*A,A/4,'red') #Creates the top base of the flag\n crescent(x+((1.5*A)/2),y+((A/4)+(A/8)),x+(((1.5*A)/2)+(A/24)),\\\n y+((A/4)+(A/8)+(A/32)),(A/4)/2,(A/5)/2,'white','black')\n #Creates a crescent in the center of the flag\n star(x+((1.5*A)+(A/8)-((A*1.5)/2)),y+((A/4)+((2*A)/8)),(A/8)/3,'white',144)\n #Creates a star to the right of the crescent\n\n#Turkey Flag Function\ndef Tur_flag(x,y,height): #Defines function 'Tur_flag'\n A = height #Sets A equal to the height\n rectangle(x,y,1.5*A,height,'red') #Creates the base of the flag\n rectangle(x,y,A/30,height,'white') #Creates the flag pole on left of flag\n crescent(x+(A/2),y+(A/4),x+((A/2)+(A/16)),y+((A/4)+(A/20)),(A/2)/2,\\\n ((2*A)/5)/2,'white','red') #Creates the crescent in center of flag\n star(x+(((2*A)/3)+(A/8)),y+(A/2),(A/4)/3,'white',144)\n #Creates a white star to the right of the crescent\n \n#Singapore Flag Function\ndef Sgp_flag(x,y,height): #Defines function 'Sgp_flag'\n A = height #Sets A equal to the height\n rectangle(x,y,1.5*A,A/2,'white') #Creates the lower base of the flag\n rectangle(x,y+(A/2),1.5*A,A/2,'red') #Creates the upper base of the flag\n crescent(x+(A/3),y+((A/2)+(A/16)),x+((A/3)+(A/10)),y+((A/2)+(A/16)),\\\n ((10*A)/27)/2,((2*A)/5)/2,'white','red') #Creates crescent\n multi_star(x,y,((4*A)/45)/3,'white') #Creates 5 stars to left of crescent\n \n\n#Main While Loop\nwhile True:\n selection = input(FLAG).upper() #Asks for user input\n \n if selection == 'Q': #If user inputs 'Q'\n print('Bye') #Tells the user bye\n break #Breaks the while loop\n \n if selection == 'TUN': #If user inputs 'TUN'\n turtle.reset() #Clears previous drawing\n turtle.speed(100) #Sets draw speed to 100\n Tun_flag(0,0,240) #Draws Tunisian Flag\n turtle.hideturtle() #Hides turtle after finishing flag\n \n if selection == 'LBY': #If user inputs 'LBY'\n turtle.reset() #Clears previous drawing\n turtle.speed(100) #Sets draw speed to 100\n Lby_flag(0,0,240) #Draws Libya flag\n turtle.hideturtle() #Hides turtle after finishing flag\n \n if selection == 'TUR': #If user inputs 'TUR'\n turtle.reset() #Clears previous drawing\n turtle.speed(100) #Sets draw speed to 100\n Tur_flag(0,0,240) #Draws Turkey flag\n turtle.hideturtle() #Hides turtle after finishing flag\n \n if selection == 'SGP': #If user inputs 'SGP'\n turtle.reset() #Clears previous drawing\n turtle.speed(100) #Sets draw speed to 100\n Sgp_flag(0,0,240) #Draws Singapore flag\n turtle.hideturtle() #Hides turtle after finishing flag\n \n if selection == 'ALL': #If user inputs 'ALL'\n turtle.reset() #Clears previous drawing\n turtle.speed(100) #Sets draw speed to 100\n Tur_flag(50,50,240) #Draws Turkey flag\n \n turtle.speed(100) #Sets draw speed to 100\n turtle.home() #Sets turtle back to initial position\n Sgp_flag(50,-250,240) #Draws Singapore flag\n \n turtle.speed(100)#Sets draw speed to 100\n turtle.home() #Sets turtle back to inital position\n Lby_flag(-400,-250,240) #Draws Libya flag\n \n turtle.speed(100) #Sets draw speed to 100\n turtle.home() #Sets turtle back to inital position\n Tun_flag(-400,50,240) #Draws Turkey flag\n turtle.hideturtle() #Hides turtle after drawing all 4 flags\n \n else: #If user doesn't input a valid input\n print('Please choose a valid input.') #Asks user to choose valid input\n continue #Continues while loop back to the top\n\nturtle.exitonclick() #Closes turtle window when red 'x' at top right is clicked\nturtle.bye() #Closes turtle window"} {"doc_id": "2e8c6a24d5f0101f4c6dcde9bd95dee0", "text": "\"\"\"\nFile: weather_master.py\nName: \u9ec3\u79d1\u8afa\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\nEXIT = -100\n\"\"\"\nEXIT: When the value assigned to EXIT is entered, input of the data set is completed and the results will show.\n\"\"\"\n\n\ndef main():\n\t\"\"\"\n\tInput: Various amount of temperature data\n\tOutput: The highest temperature, lowest temperature, average, and cold days of the data set of input(s)\n\t\"\"\"\n\tprint('stanCode \\\"Weather Master 4.0\\\"!')\n\tdata=int(input('Next Temperature: '+'(or '+str(EXIT)+' to quit)? '))\n\tif data == EXIT:\n\t\tprint('No temperatures were entered.')\n\telse:\n\t\tmaximum = data\n\t\tminimum = data\n\t\tsum = data\n\t\tdays = 1\n\t\taverage = float(data)\n\t\tcold_days = 0\n\t\tif data < 16:\n\t\t\tcold_days = int(cold_days + 1)\n\t\twhile True:\n\t\t\tdata = int(input('Next Temperature: '+'(or '+str(EXIT)+' to quit)? '))\n\t\t\tif data == EXIT:\n\t\t\t\tbreak\n\t\t\tif data < 16:\n\t\t\t\tcold_days = int(cold_days+1)\n\t\t\tif data > maximum:\n\t\t\t\tmaximum = data\n\t\t\tif data < minimum:\n\t\t\t\tminimum = data\n\t\t\tsum = float(sum + data)\n\t\t\tdays = int(days+1)\n\t\t\taverage = sum/days\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\n###### DO NOT EDIT CODE BELOW THIS LINE ######\n\nif __name__ == \"__main__\":\n\tmain()\n"} {"doc_id": "2e8ca30d1a449b593a6d40281e65d989", "text": "from sympy import *\n \ndef deg2rad(angle):\n \"\"\"\n Converts degrees to radians\n \n Parameters\n ----------\n angle : float, int\n Angle in degrees\n \n \n Returns\n -------\n ar : float\n Angle in radians\n \n \n Examples\n --------\n >>> deg2rad(30)\n 0.523598775598299\n >>> deg2rad(90)\n 1.57079632679490\n >>> deg2rad(180)\n 3.14159265358979\n \"\"\"\n ar = ( (angle)*(pi/180) ).evalf()\n return ar\n \n \ndef rad2deg(angle):\n \"\"\"\n Converts radians to degrees\n \n Parameters\n ----------\n angle : float, int\n Angle in radians\n \n \n Returns\n -------\n ad : float\n Angle in radians\n \n \n Examples\n --------\n >>> rad2deg(pi)\n 180.000000000000\n >>> rad2deg(pi/2)\n 90.0000000000000\n >>> rad2deg(2*pi)\n 360.000000000000\n \n \"\"\"\n ad = ( (angle)*(180/pi) ).evalf()\n return ad\n\n\nif __name__==\"__main__\":\n print(deg2rad(90))\n print(rad2deg(pi/4))\n\n"} {"doc_id": "2eb33dd868e51e6c9de2eeeba419b98b", "text": "\"\"\"\nThis code is for part one the AI Class optional Natural Language Processing\nprogramming assignment. See youtu.be/KuSg1wcty3s for the complete problem\ndefinition.\n\nWe are given a string which has been encoded with a Caesar cipher:\nhttp://en.wikipedia.org/wiki/Caesar_cipher, and our job is to decode it.\nYou could do this by brute force, simply print out each shift of the letters\nand look for the correct one by eye.\n\nHowever, a much nicer idea is to implement a language model so that your\ncomputer program can decide whether the decoded string looks like regular\nEnglish and only print the strings that pass your test.\n\nFor this program my language model is simple: each word must contain a vowel.\n\nThe encoded string is:\n\nesp qtcde nzyqpcpynp zy esp ezatn zq lcetqtntlw tyepwwtrpynp hld \nspwo le olcexzfes nzwwprp ty estd jplc\n\nThe string decodes to:\n\nthe first conference on the topic of artificial intelligence was \nheld at dartmouth college in this year\n\nSee http://www.livinginternet.com/i/ii_ai.htm for the answer.\n\n\nTo run this program simply type 'python nlp1.py' at the command line.\n\nAuthor\n------\n@jiffyclub\ngit.io/jiffyclub\n\n\"\"\"\n\nimport string\n\nS = \"\"\"esp qtcde nzyqpcpynp zy esp ezatn zq lcetqtntlw tyepwwtrpynp hld \nspwo le olcexzfes nzwwprp ty estd jplc\"\"\"\n\nVOWELS = \"aeiou\"\n\n\ndef make_trans(n):\n \"\"\"\n Make a translation by shifting string.lowercase `n` places to the left.\n \n Parameters\n ----------\n n : int\n Number of places to shift the alphabet.\n \n Returns\n -------\n Translation table made by `string.maketrans`.\n \n \"\"\"\n new_lowercase = string.lowercase[n:] + string.lowercase[:n]\n \n return string.maketrans(string.lowercase, new_lowercase)\n \n \ndef translate(s,n):\n \"\"\"\n Decode a string `s` using a cipher that shifts the alphabet\n `n` places to the left.\n \n Parameters\n ----------\n s : str\n String to be decoded.\n \n n : int\n Number of places to shift the alphabet for shift cipher.\n \n Returns\n -------\n d : str\n Decoded string.\n \n \"\"\"\n trans = make_trans(n)\n \n return string.translate(s, trans)\n\n\ndef check_for_vowels(s):\n \"\"\"\n Split a string on spaces and check that every word contains\n a vowel ('aeiou'). Returns True if every word contains a vowel,\n False otherwise.\n \n Parameters\n ----------\n s : str\n String to check.\n \n Returns\n -------\n all : bool\n True if every word contains vowels, False otherwise.\n \n \"\"\"\n split = s.split()\n \n for word in split:\n num = len([c for c in word if c in VOWELS])\n \n if num == 0:\n return False\n \n return True\n\n\ndef main():\n \"\"\"\n Go through all shifts of the alphabet and print the decoded S for\n shifts that result in cases where every word contains a vowel.\n \n \"\"\"\n for i in range(26):\n s = translate(S, i)\n \n if check_for_vowels(s):\n print s\n\n\nif __name__ == '__main__':\n main()\n"} {"doc_id": "2edfaa5efc9424269f2d781c2b649952", "text": "import math\nimport sys\n\nresults = [] # Results list\nlastResult = float(0) # Last Result\nresult = float(0) # Current Result\n\n#Prints the Menu\ndef printMenu():\n print(\"Calculator Menu\")\n print(\"---------------\")\n print(\"0. Exit Program\")\n print(\"1. Addition\")\n print(\"2. Subtraction\")\n print(\"3. Multiplication\")\n print(\"4. Division\")\n print(\"5. Exponentiation\")\n print(\"6. Logarithm\")\n print(\"7. Display Average\")\n\n#Gets Input\ndef getInput():\n print(\"\")\n x = int(input(\"Enter Menu Selection: \"))\n if(x > 0 and x < 7):\n a = input(\"Enter first operand: \")\n b = input(\"Enter second operand: \")\n if(a == 'RESULT'):\n a = float(lastResult)\n if(b == 'RESULT'):\n b = float(lastResult)\n a = float(a)\n b = float(b) \n else:\n a = 0\n b = 0\n return x, a, b\n\n# 0: Exit\ndef exit(a, b):\n print(\"\")\n print(\"Thanks for using this calculator. Goodbye!\")\n sys.exit()\n\n# 1: Add\ndef add(a, b):\n return a + b\n\n# 2: Subtract\ndef sub(a, b):\n return a - b\n\n# 3: Multiply\ndef mult(a, b):\n return a * b\n\n# 4: Divide\ndef div(a, b):\n return a / b\n\n# 5: Exponent\ndef exp(a, b):\n return a ** b\n\n# 6: Logarithm\ndef log(a, b):\n return math.log(b,a)\n\n# 7: Average\ndef avg(a,b):\n\n if(len(results) == 0):\n print(\"\")\n print(\"Error: no calculations yet to average!\")\n else:\n sum = 0\n\n for num in results:\n sum = sum + num\n\n numCalc = len(results)\n avg = sum / numCalc\n\n return sum, numCalc, round(avg, 2)\n\n#Invalid Input\ndef invalidInput(a,b):\n print(\"\")\n print(\"Error: Invalid selection!\")\n\n#Switch dictionary\nswitch = {\n 0: exit,\n 1: add,\n 2: sub,\n 3: mult,\n 4: div,\n 5: exp,\n 6: log,\n 7: avg\n}\n\n#Initial start of program\nx = 0\n\nprint(\"Current Result: \" + str(result))\nprint(\"\")\n\nprintMenu()\n\n#Program Loop\nwhile(True):\n if(x > 0 and x < 7): printMenu()\n x, a, b = getInput()\n func = switch.get(x, invalidInput)\n result = func(a, b)\n if(x > 0 and x < 7):\n results.append(result)\n lastResult = result\n print(\"\")\n print(\"Current Result: \" + str(result))\n print(\"\")\n else:\n if result is not None:\n print(\"\")\n print(\"Sum of calculations: \" + str(result[0]))\n print(\"Number of calculations: \" + str(result[1]))\n print(\"Average of calculations: \" + str(result[2]))\n\n"} {"doc_id": "2f3a50f90281e74bae9e292875e6f61e", "text": "\"\"\"\n

We are given a binary tree (with root node root), a target node, and an integer value `K`.

\n\n

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

 

\n\n
    \n
\n\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\"\"\nNote that the inputs "root" and "target" are actually TreeNodes.\nThe descriptions of the inputs above are just serializations of these objects.\n\n
\n\n

Note:

\n\n
    \n\t
  1. The given tree is non-empty.
  2. \n\t
  3. Each node in the tree has unique values 0 <= node.val <= 500.
  4. \n\t
  5. The target node is a node in the tree.
  6. \n\t
  7. 0 <= K <= 1000.
  8. \n
\n

\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

\n\n

\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

 

\n\n
    \n
\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\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

 

\n\n

\u63d0\u793a\uff1a

\n\n
    \n\t
  1. \u7ed9\u5b9a\u7684\u6811\u662f\u975e\u7a7a\u7684\uff0c\u4e14\u6700\u591a\u6709 K \u4e2a\u7ed3\u70b9\u3002
  2. \n\t
  3. \u6811\u4e0a\u7684\u6bcf\u4e2a\u7ed3\u70b9\u90fd\u5177\u6709\u552f\u4e00\u7684\u503c 0 <= node.val <= 500 \u3002
  4. \n\t
  5. \u76ee\u6807\u7ed3\u70b9 target \u662f\u6811\u4e0a\u7684\u7ed3\u70b9\u3002
  6. \n\t
  7. 0 <= K <= 1000.
  8. \n
\n

\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

\n\n

\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

 

\n\n
    \n
\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\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

 

\n\n

\u63d0\u793a\uff1a

\n\n
    \n\t
  1. \u7ed9\u5b9a\u7684\u6811\u662f\u975e\u7a7a\u7684\uff0c\u4e14\u6700\u591a\u6709 K \u4e2a\u7ed3\u70b9\u3002
  2. \n\t
  3. \u6811\u4e0a\u7684\u6bcf\u4e2a\u7ed3\u70b9\u90fd\u5177\u6709\u552f\u4e00\u7684\u503c 0 <= node.val <= 500 \u3002
  4. \n\t
  5. \u76ee\u6807\u7ed3\u70b9 target \u662f\u6811\u4e0a\u7684\u7ed3\u70b9\u3002
  6. \n\t
  7. 0 <= K <= 1000.
  8. \n
\n\"\"\"\n\n\n# Definition for a binary tree node.\n# class TreeNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nclass Solution(object):\n def distanceK(self, root, target, K):\n \"\"\"\n :type root: TreeNode\n :type target: TreeNode\n :type K: int\n :rtype: List[int]\n \"\"\"\n "} {"doc_id": "2f76514e4122a0997750cd1dae1ed4f5", "text": "\"\"\"\nFile: caesar.py\nName: Justin Kao\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 The encrypted string will be shifted back by Caesar Cipher method,\n then we'll find out the true string.\n \"\"\"\n dspc = int(input(\"Secret number: \"))\n encrypt = input(\"What's the ciphered string: \")\n encrypt = encrypt.upper()\n new_s = decipher_define(dspc)\n ans = decipher(encrypt, new_s)\n print(\"The deciphered string is:\", ans)\n\n\ndef decipher_define(dspc):\n \"\"\"\n Define the new ALPHEBET order.\n :param dspc: The displacement need to shift.\n :return: new_s\n \"\"\"\n new_s = \"\"\n divide = len(ALPHABET) - dspc\n new_s = ALPHABET[divide:] + ALPHABET[:divide]\n return new_s\n\n\ndef decipher(encrypt, new_s):\n \"\"\"\n Find out the original string by look up to the position in new ALPHABET order,\n and correspond to the original ALPHABET by the same position.\n :param encrypt:\n :param new_s:\n :return: ans(the original string)\n \"\"\"\n ans = \"\"\n for ch in encrypt:\n if ch in ALPHABET:\n ans += ALPHABET[new_s.find(ch)]\n else: # assign punctuation marks directly.\n ans += ch\n return ans\n\n\n\n##### DO NOT EDIT THE CODE BELOW THIS LINE #####\nif __name__ == '__main__':\n main()\n"} {"doc_id": "2f7a37e9533ca699c62852791a6f8276", "text": "#\u0417\u0430\u0434\u0430\u0447\u0438 \u043d\u0430 \u0446\u0438\u043a\u043b\u044b \u0438 \u043e\u043f\u0435\u0440\u0430\u0442\u043e\u0440 \u0443\u0441\u043b\u043e\u0432\u0438\u044f------\n#----------------------------------------\n\n'''\n\u0417\u0430\u0434\u0430\u0447\u0430 1\n\u0412\u044b\u0432\u0435\u0441\u0442\u0438 \u043d\u0430 \u044d\u043a\u0440\u0430\u043d \u0446\u0438\u043a\u043b\u043e\u043c \u043f\u044f\u0442\u044c \u0441\u0442\u0440\u043e\u043a \u0438\u0437 \u043d\u0443\u043b\u0435\u0439, \u043f\u0440\u0438\u0447\u0435\u043c \u043a\u0430\u0436\u0434\u0430\u044f \u0441\u0442\u0440\u043e\u043a\u0430 \u0434\u043e\u043b\u0436\u043d\u0430 \u0431\u044b\u0442\u044c \u043f\u0440\u043e\u043d\u0443\u043c\u0435\u0440\u043e\u0432\u0430\u043d\u0430.\n'''\nfor i in range(1, 6):\n print(i, str(0))\n'''\n\u0417\u0430\u0434\u0430\u0447\u0430 2\n\u041f\u043e\u043b\u044c\u0437\u043e\u0432\u0430\u0442\u0435\u043b\u044c \u0432 \u0446\u0438\u043a\u043b\u0435 \u0432\u0432\u043e\u0434\u0438\u0442 10 \u0446\u0438\u0444\u0440. \u041d\u0430\u0439\u0442\u0438 \u043a\u043e\u043b\u0438\u0447\u0435\u0441\u0442\u0432\u043e \u0432\u0432\u0435\u0434\u0435\u043d\u044b\u0445 \u043f\u043e\u043b\u044c\u0437\u043e\u0432\u0430\u0442\u0435\u043b\u0435\u043c \u0446\u0438\u0444\u0440 5.\n'''\ncount = 0\nfor i in range(10):\n integer_number = int(input(\"\u0412\u0432\u0435\u0434\u0438\u0442\u0435 \u0447\u0438\u0441\u043b\u043e = \"))\n while integer_number > 0:\n number = integer_number%10\n if number == 5:\n count +=1\n integer_number//=10\nprint(\"\u041a\u043e\u043b\u0438\u0447\u0435\u0441\u0442\u0432\u043e \u0446\u0438\u0444\u0440 5 \u0432\u0432\u0435\u0434\u0435\u043d\u043d\u044b\u0445 \u043f\u043e\u043b\u044c\u0437\u043e\u0432\u0430\u0442\u0435\u043b\u0435\u043c =\", count)\n'''\n\u0417\u0430\u0434\u0430\u0447\u0430 3\n\u041d\u0430\u0439\u0442\u0438 \u0441\u0443\u043c\u043c\u0443 \u0440\u044f\u0434\u0430 \u0447\u0438\u0441\u0435\u043b \u043e\u0442 1 \u0434\u043e 100. \u041f\u043e\u043b\u0443\u0447\u0435\u043d\u043d\u044b\u0439 \u0440\u0435\u0437\u0443\u043b\u044c\u0442\u0430\u0442 \u0432\u044b\u0432\u0435\u0441\u0442\u0438 \u043d\u0430 \u044d\u043a\u0440\u0430\u043d.\n'''\nsum = 0\n\nfor i in range(1,101):\n sum+=i\nprint(sum)\n'''\n\u0417\u0430\u0434\u0430\u0447\u0430 4\n\u041d\u0430\u0439\u0442\u0438 \u043f\u0440\u043e\u0438\u0437\u0432\u0435\u0434\u0435\u043d\u0438\u0435 \u0440\u044f\u0434\u0430 \u0447\u0438\u0441\u0435\u043b \u043e\u0442 1 \u0434\u043e 10. \u041f\u043e\u043b\u0443\u0447\u0435\u043d\u043d\u044b\u0439 \u0440\u0435\u0437\u0443\u043b\u044c\u0442\u0430\u0442 \u0432\u044b\u0432\u0435\u0441\u0442\u0438 \u043d\u0430 \u044d\u043a\u0440\u0430\u043d.\n'''\nmultiplication = 1\n\nfor i in range(1,11):\n multiplication*=i\nprint(\"\u041f\u0440\u043e\u0438\u0437\u0432\u0435\u0434\u0435\u043d\u0438\u0435 \u0446\u0438\u0444\u0440 \u043e\u0442 1 \u0434\u043e 10 =\", multiplication)\n'''\n\u0417\u0430\u0434\u0430\u0447\u0430 5\n\u0412\u044b\u0432\u0435\u0441\u0442\u0438 \u0446\u0438\u0444\u0440\u044b \u0447\u0438\u0441\u043b\u0430 \u043d\u0430 \u043a\u0430\u0436\u0434\u043e\u0439 \u0441\u0442\u0440\u043e\u0447\u043a\u0435.\n'''\ninteger_number = 2129\n\n#print(integer_number%10,integer_number//10)\n\nwhile integer_number>0:\n print(integer_number%10)\n integer_number = integer_number//10\n'''\n\u0417\u0430\u0434\u0430\u0447\u0430 6\n\u041d\u0430\u0439\u0442\u0438 \u0441\u0443\u043c\u043c\u0443 \u0446\u0438\u0444\u0440 \u0447\u0438\u0441\u043b\u0430.\n'''\ninteger_number = int(input(\"\u0412\u0432\u0435\u0434\u0438\u0442\u0435 \u0447\u0438\u0441\u043b\u043e = \"))\nsum = 0\nwhile integer_number>0:\n a = integer_number%10\n integer_number = integer_number//10\n sum +=a\nprint(\"\u0421\u0443\u043c\u043c\u0430 \u0446\u0438\u0444\u0440 \u044d\u0442\u043e\u0433\u043e \u0447\u0438\u0441\u043b\u0430 \u0440\u0430\u0432\u043d\u0430 \", sum)\n'''\n\u0417\u0430\u0434\u0430\u0447\u0430 7\n\u041d\u0430\u0439\u0442\u0438 \u043f\u0440\u043e\u0438\u0437\u0432\u0435\u0434\u0435\u043d\u0438\u0435 \u0446\u0438\u0444\u0440 \u0447\u0438\u0441\u043b\u0430.\n'''\ninteger_number = int(input(\"\u0412\u0432\u0435\u0434\u0438\u0442\u0435 \u0447\u0438\u0441\u043b\u043e = \"))\nmultiplication = 1\nwhile integer_number>0:\n a = integer_number%10\n integer_number = integer_number//10\n multiplication*=a\nprint(\"\u041f\u0440\u043e\u0438\u0437\u0432\u0435\u0434\u0435\u043d\u0438\u0435 \u0446\u0438\u0444\u0440 \u044d\u0442\u043e\u0433\u043e \u0447\u0438\u0441\u043b\u0430 \u0440\u0430\u0432\u043d\u043e \", multiplication)\n'''\n\u0417\u0430\u0434\u0430\u0447\u0430 8\n\u0414\u0430\u0442\u044c \u043e\u0442\u0432\u0435\u0442 \u043d\u0430 \u0432\u043e\u043f\u0440\u043e\u0441: \u0435\u0441\u0442\u044c \u043b\u0438 \u0441\u0440\u0435\u0434\u0438 \u0446\u0438\u0444\u0440 \u0447\u0438\u0441\u043b\u0430 5?\n'''\ninteger_number = 213413\nwhile integer_number>0:\n if integer_number%10 == 5:\n print('Yes')\n break\n integer_number = integer_number//10\nelse: print('No')\n'''\n\u0417\u0430\u0434\u0430\u0447\u0430 9\n\u041d\u0430\u0439\u0442\u0438 \u043c\u0430\u043a\u0441\u0438\u043c\u0430\u043b\u044c\u043d\u0443\u044e \u0446\u0438\u0444\u0440\u0443 \u0432 \u0447\u0438\u0441\u043b\u0435\n'''\ninteger_number = int(input(\"\u0412\u0432\u0435\u0434\u0438\u0442\u0435 \u0447\u0438\u0441\u043b\u043e: \"))\na = integer_number%10\ninteger_number = integer_number//10\nwhile integer_number > 0:\n if integer_number%10 > a:\n a = integer_number%10\n integer_number = integer_number//10\nprint(\"\u041c\u0430\u043a\u0441\u0438\u043c\u0430\u043b\u044c\u043d\u0430\u044f \u0446\u0438\u0444\u0440\u0430 \u0432 \u0447\u0438\u0441\u043b\u0435 =\", a)\n'''\n\u0417\u0430\u0434\u0430\u0447\u0430 10\n\u041d\u0430\u0439\u0442\u0438 \u043a\u043e\u043b\u0438\u0447\u0435\u0441\u0442\u0432\u043e \u0446\u0438\u0444\u0440 5 \u0432 \u0447\u0438\u0441\u043b\u0435\n'''\ninteger_number = int(input(\"\u0412\u0432\u0435\u0434\u0438\u0442\u0435 \u0447\u0438\u0441\u043b\u043e = \"))\ncount = 0\nwhile integer_number > 0:\n number = integer_number%10\n if number == 5:\n count +=1\n integer_number//=10\nprint(\"\u041a\u043e\u043b\u0438\u0447\u0435\u0441\u0442\u0432\u043e \u0446\u0438\u0444\u0440 5 \u0432\u0432\u0435\u0434\u0435\u043d\u043d\u044b\u0445 \u043f\u043e\u043b\u044c\u0437\u043e\u0432\u0430\u0442\u0435\u043b\u0435\u043c =\", count)\n"} {"doc_id": "2fba4095bd260508a8c4a3c2711d3f75", "text": "#!/usr/bin/env python\n# coding: utf-8\n\n# # Visualizing Naive Bayes\n# \n# In this lab, we will cover an essential part of data analysis that has not been included in the lecture videos. As we stated in the previous module, data visualization gives insight into the expected performance of any model. \n# \n# In the following exercise, you are going to make a visual inspection of the tweets dataset using the Na\u00efve Bayes features. We will see how we can understand the log-likelihood ratio explained in the videos as a pair of numerical features that can be fed in a machine learning algorithm. \n# \n# At the end of this lab, we will introduce the concept of __confidence ellipse__ as a tool for representing the Na\u00efve Bayes model visually.\n\n# In[1]:\n\n\nimport numpy as np # Library for linear algebra and math utils\nimport pandas as pd # Dataframe library\n\nimport matplotlib.pyplot as plt # Library for plots\nfrom utils import confidence_ellipse # Function to add confidence ellipses to charts\n\n\n# ## Calculate the likelihoods for each tweet\n# \n# For each tweet, we have calculated the likelihood of the tweet to be positive and the likelihood to be negative. We have calculated in different columns the numerator and denominator of the likelihood ratio introduced previously. \n# \n# $$log \\frac{P(tweet|pos)}{P(tweet|neg)} = log(P(tweet|pos)) - log(P(tweet|neg)) $$\n# $$positive = log(P(tweet|pos)) = \\sum_{i=0}^{n}{log P(W_i|pos)}$$\n# $$negative = log(P(tweet|neg)) = \\sum_{i=0}^{n}{log P(W_i|neg)}$$\n# \n# We did not include the code because this is part of this week's assignment. The __'bayes_features.csv'__ file contains the final result of this process. \n# \n# The cell below loads the table in a dataframe. Dataframes are data structures that simplify the manipulation of data, allowing filtering, slicing, joining, and summarization.\n\n# In[2]:\n\n\ndata = pd.read_csv('bayes_features.csv'); # Load the data from the csv file\n\ndata.head(5) # Print the first 5 tweets features. Each row represents a tweet\n\n\n# In[3]:\n\n\n# Plot the samples using columns 1 and 2 of the matrix\n\nfig, ax = plt.subplots(figsize = (8, 8)) #Create a new figure with a custom size\n\ncolors = ['red', 'green'] # Define a color palete\n\n# Color base on sentiment\nax.scatter(data.positive, data.negative, \n c=[colors[int(k)] for k in data.sentiment], s = 0.1, marker='*') # Plot a dot for each tweet\n\n# Custom limits for this chart\nplt.xlim(-250,0)\nplt.ylim(-250,0)\n\nplt.xlabel(\"Positive\") # x-axis label\nplt.ylabel(\"Negative\") # y-axis label\n\n\n# # Using Confidence Ellipses to interpret Na\u00efve Bayes\n# \n# In this section, we will use the [confidence ellipse]( https://matplotlib.org/3.1.1/gallery/statistics/confidence_ellipse.html#sphx-glr-gallery-statistics-confidence-ellipse-py) to give us an idea of what the Na\u00efve Bayes model see.\n# \n# A confidence ellipse is a way to visualize a 2D random variable. It is a better way than plotting the points over a cartesian plane because, with big datasets, the points can overlap badly and hide the real distribution of the data. Confidence ellipses summarize the information of the dataset with only four parameters: \n# \n# * Center: It is the numerical mean of the attributes\n# * Height and width: Related with the variance of each attribute. The user must specify the desired amount of standard deviations used to plot the ellipse. \n# * Angle: Related with the covariance among attributes.\n# \n# The parameter __n_std__ stands for the number of standard deviations bounded by the ellipse. Remember that for normal random distributions:\n# \n# * About 68% of the area under the curve falls within 1 standard deviation around the mean.\n# * About 95% of the area under the curve falls within 2 standard deviations around the mean.\n# * About 99.7% of the area under the curve falls within 3 standard deviations around the mean.\n# \n# \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\n`_ python\nmodule::\n\n from functools import partial\n\n def my_callback(value, key, *largs):\n pass\n\n Clock.schedule_interval(partial(my_callback, 'my value', 'my key'), 0.5)\n\nConversely, if you want to schedule a function that doesn't accept the dt\nargument, you can use a `lambda\n`_ expression\nto write a short function that does accept dt. For Example::\n\n def no_args_func():\n print(\"I accept no arguments, so don't schedule me in the clock\")\n\n Clock.schedule_once(lambda dt: no_args_func(), 0.5)\n\n.. note::\n\n You cannot unschedule an anonymous function unless you keep a\n reference to it. It's better to add \\*args to your function\n definition so that it can be called with an arbitrary number of\n parameters.\n\n.. important::\n\n The callback is weak-referenced: you are responsible for keeping a\n reference to your original object/callback. If you don't keep a\n reference, the ClockBase will never execute your callback. For\n example::\n\n class Foo(object):\n def start(self):\n Clock.schedule_interval(self.callback, 0.5)\n\n def callback(self, dt):\n print('In callback')\n\n # A Foo object is created and the method start is called.\n # Because no reference is kept to the instance returned from Foo(),\n # the object will be collected by the Python Garbage Collector and\n # your callback will be never called.\n Foo().start()\n\n # So you should do the following and keep a reference to the instance\n # of foo until you don't need it anymore!\n foo = Foo()\n foo.start()\n\n\n.. _schedule-before-frame:\n\nSchedule before frame\n---------------------\n\n.. versionadded:: 1.0.5\n\nSometimes you need to schedule a callback BEFORE the next frame. Starting\nfrom 1.0.5, you can use a timeout of -1::\n\n Clock.schedule_once(my_callback, 0) # call after the next frame\n Clock.schedule_once(my_callback, -1) # call before the next frame\n\nThe Clock will execute all the callbacks with a timeout of -1 before the\nnext frame even if you add a new callback with -1 from a running\ncallback. However, :class:`Clock` has an iteration limit for these\ncallbacks: it defaults to 10.\n\nIf you schedule a callback that schedules a callback that schedules a .. etc\nmore than 10 times, it will leave the loop and send a warning to the console,\nthen continue after the next frame. This is implemented to prevent bugs from\nhanging or crashing the application.\n\nIf you need to increase the limit, set the :attr:`max_iteration` property::\n\n from kivy.clock import Clock\n Clock.max_iteration = 20\n\n.. _triggered-events:\n\nTriggered Events\n----------------\n\n.. versionadded:: 1.0.5\n\nA triggered event is a way to defer a callback exactly like schedule_once(),\nbut with some added convenience. The callback will only be scheduled once per\nframe even if you call the trigger twice (or more). This is not the case\nwith :meth:`Clock.schedule_once`::\n\n # will run the callback twice before the next frame\n Clock.schedule_once(my_callback)\n Clock.schedule_once(my_callback)\n\n # will run the callback once before the next frame\n t = Clock.create_trigger(my_callback)\n t()\n t()\n\nBefore triggered events, you may have used this approach in a widget::\n\n def trigger_callback(self, *largs):\n Clock.unschedule(self.callback)\n Clock.schedule_once(self.callback)\n\nAs soon as you call `trigger_callback()`, it will correctly schedule the\ncallback once in the next frame. It is more convenient to create and bind to\nthe triggered event than using :meth:`Clock.schedule_once` in a function::\n\n from kivy.clock import Clock\n from kivy.uix.widget import Widget\n\n class Sample(Widget):\n def __init__(self, **kwargs):\n self._trigger = Clock.create_trigger(self.cb)\n super(Sample, self).__init__(**kwargs)\n self.bind(x=self._trigger, y=self._trigger)\n\n def cb(self, *largs):\n pass\n\nEven if x and y changes within one frame, the callback is only run once.\n\n.. note::\n\n :meth:`ClockBase.create_trigger` also has a timeout parameter that\n behaves exactly like :meth:`ClockBase.schedule_once`.\n\n'''\n\n__all__ = ('Clock', 'ClockBase', 'ClockEvent', 'mainthread')\n\nfrom sys import platform\nfrom os import environ\nfrom kivy.context import register_context\nfrom kivy.weakmethod import WeakMethod\nfrom kivy.config import Config\nfrom kivy.logger import Logger\nimport time\n\ntry:\n import ctypes\n if platform in ('win32', 'cygwin'):\n # Win32 Sleep function is only 10-millisecond resolution, so\n # instead use a waitable timer object, which has up to\n # 100-nanosecond resolution (hardware and implementation\n # dependent, of course).\n\n _kernel32 = ctypes.windll.kernel32\n\n class _ClockBase(object):\n def __init__(self):\n self._timer = _kernel32.CreateWaitableTimerA(None, True, None)\n\n def usleep(self, microseconds):\n delay = ctypes.c_longlong(int(-microseconds * 10))\n _kernel32.SetWaitableTimer(\n self._timer, ctypes.byref(delay), 0,\n ctypes.c_void_p(), ctypes.c_void_p(), False)\n _kernel32.WaitForSingleObject(self._timer, 0xffffffff)\n\n _default_time = time.clock\n else:\n if platform == 'darwin':\n _libc = ctypes.CDLL('libc.dylib')\n else:\n _libc = ctypes.CDLL('libc.so')\n _libc.usleep.argtypes = [ctypes.c_ulong]\n _libc_usleep = _libc.usleep\n\n class _ClockBase(object):\n def usleep(self, microseconds):\n _libc_usleep(int(microseconds))\n\n _default_time = time.time\n\nexcept (OSError, ImportError):\n # ImportError: ctypes is not available on python-for-android.\n # OSError: if the libc cannot be readed (like with buildbot: invalid ELF\n # header)\n\n _default_time = time.time\n _default_sleep = time.sleep\n\n class _ClockBase(object):\n def usleep(self, microseconds):\n _default_sleep(microseconds / 1000000.)\n\n\ndef _hash(cb):\n try:\n return cb.__name__\n except:\n # if a callback with partial is used... use func\n try:\n return cb.func.__name__\n except:\n # nothing work, use default hash.\n return 'default'\n\n\nclass ClockEvent(object):\n\n def __init__(self, clock, loop, callback, timeout, starttime, cid):\n self.clock = clock\n self.cid = cid\n self.loop = loop\n self.weak_callback = None\n self.callback = callback\n self.timeout = timeout\n self._is_triggered = False\n self._last_dt = starttime\n self._dt = 0.\n\n def __call__(self, *largs):\n # if the event is not yet triggered, do it !\n if self._is_triggered is False:\n self._is_triggered = True\n events = self.clock._events\n cid = self.cid\n if cid not in events:\n events[cid] = []\n events[cid].append(self)\n # update starttime\n self._last_dt = self.clock._last_tick\n return True\n\n def get_callback(self):\n callback = self.callback\n if callback is not None:\n return callback\n callback = self.weak_callback\n if callback.is_dead():\n return None\n return callback()\n\n @property\n def is_triggered(self):\n return self._is_triggered\n\n def cancel(self):\n if self._is_triggered:\n events = self.clock._events\n cid = self.cid\n if cid in events and self in events[cid]:\n events[cid].remove(self)\n self._is_triggered = False\n\n def do(self, dt):\n callback = self.get_callback()\n if callback is None:\n return False\n callback(dt)\n\n def release(self):\n self.weak_callback = WeakMethod(self.callback)\n self.callback = None\n\n def tick(self, curtime):\n # timeout happened ? (check also if we would miss from 5ms) this\n # 5ms increase the accuracy if the timing of animation for\n # example.\n if curtime - self._last_dt < self.timeout - 0.005:\n return True\n\n # calculate current timediff for this event\n self._dt = curtime - self._last_dt\n self._last_dt = curtime\n\n # get the callback\n callback = self.get_callback()\n if callback is None:\n self._is_triggered = False\n return False\n\n # if it's a trigger, allow to retrigger inside the callback\n if not self.loop:\n self._is_triggered = False\n\n # call the callback\n ret = callback(self._dt)\n\n # if it's a once event, don't care about the result\n # just remove the event\n if not self.loop:\n return False\n\n # if the user returns False explicitly,\n # remove the event\n if ret is False:\n return False\n\n return True\n\n def __repr__(self):\n return '' % self.get_callback()\n\n\nclass ClockBase(_ClockBase):\n '''A clock object with event support.\n '''\n __slots__ = ('_dt', '_last_fps_tick', '_last_tick', '_fps', '_rfps',\n '_start_tick', '_fps_counter', '_rfps_counter', '_events',\n '_frames', '_frames_displayed',\n '_max_fps', 'max_iteration')\n\n MIN_SLEEP = 0.005\n SLEEP_UNDERSHOOT = MIN_SLEEP - 0.001\n\n def __init__(self):\n super(ClockBase, self).__init__()\n self._dt = 0.0001\n self._start_tick = self._last_tick = _default_time()\n self._fps = 0\n self._rfps = 0\n self._fps_counter = 0\n self._rfps_counter = 0\n self._last_fps_tick = None\n self._frames = 0\n self._frames_displayed = 0\n self._events = {}\n self._max_fps = float(Config.getint('graphics', 'maxfps'))\n\n #: .. versionadded:: 1.0.5\n #: When a schedule_once is used with -1, you can add a limit on\n #: how iteration will be allowed. That is here to prevent too much\n #: relayout.\n self.max_iteration = 10\n\n @property\n def frametime(self):\n '''Time spent between the last frame and the current frame\n (in seconds).\n\n .. versionadded:: 1.8.0\n '''\n return self._dt\n\n @property\n def frames(self):\n '''Number of internal frames (not necesseraly drawed) from the start of\n the clock.\n\n .. versionadded:: 1.8.0\n '''\n return self._frames\n\n @property\n def frames_displayed(self):\n '''Number of displayed frames from the start of the clock.\n '''\n return self._frames_displayed\n\n def tick(self):\n '''Advance the clock to the next step. Must be called every frame.\n The default clock has a tick() function called by the core Kivy\n framework.'''\n\n self._release_references()\n if self._fps_counter % 100 == 0:\n self._remove_empty()\n\n # do we need to sleep ?\n if self._max_fps > 0:\n min_sleep = self.MIN_SLEEP\n sleep_undershoot = self.SLEEP_UNDERSHOOT\n fps = self._max_fps\n usleep = self.usleep\n\n sleeptime = 1 / fps - (_default_time() - self._last_tick)\n while sleeptime - sleep_undershoot > min_sleep:\n usleep(1000000 * (sleeptime - sleep_undershoot))\n sleeptime = 1 / fps - (_default_time() - self._last_tick)\n\n # tick the current time\n current = _default_time()\n self._dt = current - self._last_tick\n self._frames += 1\n self._fps_counter += 1\n self._last_tick = current\n\n # calculate fps things\n if self._last_fps_tick is None:\n self._last_fps_tick = current\n elif current - self._last_fps_tick > 1:\n d = float(current - self._last_fps_tick)\n self._fps = self._fps_counter / d\n self._rfps = self._rfps_counter\n self._last_fps_tick = current\n self._fps_counter = 0\n self._rfps_counter = 0\n\n # process event\n self._process_events()\n\n return self._dt\n\n def tick_draw(self):\n '''Tick the drawing counter.\n '''\n self._process_events_before_frame()\n self._rfps_counter += 1\n self._frames_displayed += 1\n\n def get_fps(self):\n '''Get the current average FPS calculated by the clock.\n '''\n return self._fps\n\n def get_rfps(self):\n '''Get the current \"real\" FPS calculated by the clock.\n This counter reflects the real framerate displayed on the screen.\n\n In contrast to get_fps(), this function returns a counter of the\n number of frames, not the average of frames per second.\n '''\n return self._rfps\n\n def get_time(self):\n '''Get the last tick made by the clock.'''\n return self._last_tick\n\n def get_boottime(self):\n '''Get the time in seconds from the application start.'''\n return self._last_tick - self._start_tick\n\n def create_trigger(self, callback, timeout=0):\n '''Create a Trigger event. Check module documentation for more\n information.\n\n .. versionadded:: 1.0.5\n '''\n cid = _hash(callback)\n ev = ClockEvent(self, False, callback, timeout, 0, cid)\n ev.release()\n return ev\n\n def schedule_once(self, callback, timeout=0):\n '''Schedule an event in seconds. If is unspecified\n or 0, the callback will be called after the next frame is rendered.\n\n .. versionchanged:: 1.0.5\n If the timeout is -1, the callback will be called before the next\n frame (at :meth:`tick_draw`).\n\n '''\n if not callable(callback):\n raise ValueError('callback must be a callable, got %s' % callback)\n cid = _hash(callback)\n event = ClockEvent(\n self, False, callback, timeout, self._last_tick, cid)\n events = self._events\n if not cid in events:\n events[cid] = []\n events[cid].append(event)\n return event\n\n def schedule_interval(self, callback, timeout):\n '''Schedule an event to be called every seconds.'''\n if not callable(callback):\n raise ValueError('callback must be a callable, got %s' % callback)\n cid = _hash(callback)\n event = ClockEvent(\n self, True, callback, timeout, self._last_tick, cid)\n events = self._events\n if not cid in events:\n events[cid] = []\n events[cid].append(event)\n return event\n\n def unschedule(self, callback):\n '''Remove a previously scheduled event.\n '''\n events = self._events\n if isinstance(callback, ClockEvent):\n # already done, nothing to schedule\n if callback.is_done:\n return\n cid = callback.cid\n if cid in events:\n for event in events[cid][:]:\n if event is callback:\n events[cid].remove(event)\n else:\n cid = _hash(callback)\n if cid in events:\n for event in events[cid][:]:\n if event.get_callback() == callback:\n events[cid].remove(event)\n\n def _release_references(self):\n # call that function to release all the direct reference to any\n # callback and replace it with a weakref\n events = self._events\n for cid in list(events.keys())[:]:\n [x.release() for x in events[cid] if x.callback is not None]\n\n def _remove_empty(self):\n # remove empty entry in the event list\n events = self._events\n for cid in list(events.keys())[:]:\n if not events[cid]:\n del events[cid]\n\n def _process_events(self):\n events = self._events\n for cid in list(events.keys())[:]:\n for event in events[cid][:]:\n if event.tick(self._last_tick) is False:\n # event may be already removed by the callback\n if event in events[cid]:\n events[cid].remove(event)\n\n def _process_events_before_frame(self):\n found = True\n count = self.max_iteration\n events = self._events\n while found:\n count -= 1\n if count == -1:\n Logger.critical(\n 'Clock: Warning, too much iteration done before'\n ' the next frame. Check your code, or increase'\n ' the Clock.max_iteration attribute')\n break\n\n # search event that have timeout = -1\n found = False\n for cid in list(events.keys())[:]:\n for event in events[cid][:]:\n if event.timeout != -1:\n continue\n found = True\n if event.tick(self._last_tick) is False:\n # event may be already removed by the callback\n if event in events[cid]:\n events[cid].remove(event)\n\n\ndef mainthread(func):\n '''Decorator that will schedule the call of the function in the\n mainthread. It can be useful when you use\n :class:`~kivy.network.urlrequest.UrlRequest` or when you do Thread\n programming: you cannot do any OpenGL-related work in a thread.\n\n Please note that this method will return directly and no result can be\n returned::\n\n @mainthread\n def callback(self, *args):\n print('The request succedded!'\n 'This callback is call in the main thread')\n\n self.req = UrlRequest(url='http://...', on_success=callback)\n\n .. versionadded:: 1.8.0\n '''\n def delayed_func(*args, **kwargs):\n def callback_func(dt):\n func(*args, **kwargs)\n Clock.schedule_once(callback_func, 0)\n return delayed_func\n\nif 'KIVY_DOC_INCLUDE' in environ:\n #: Instance of :class:`ClockBase`.\n Clock = None\nelse:\n Clock = register_context('Clock', ClockBase)\n"} {"doc_id": "36335f507b23022b57f50fbf9eae5851", "text": "'''\nAuthor: \nDate: <2018.5.13>\nClass: ISTA 130\nSection Leader: \n\nDescription:\n\n'''\n\n# put all of your import statements below this line and then delete this comment\ndef word_length(str,int):\n '''\n Two parameters. The first will be a string and the second will be an integer. The\n function first prints a message about the relationship between the length of the word and the\n integer, as shown in the following examples.\n\n word_length('liversnaps', 7)\n Longer than 7 characters: liversnaps\n\n word_length('earwax', 5)\n Longer than 5 characters: earwax\n\n word_length('chickenfat', 10)\n Exactly 10 characters: chickenfat\n\n word_length('Gross!', 13)\n Shorter than 13 characters: Gross!\n\n '''\n if len(str) > int:\n print(\"Longer than\",int,\"characters:\",str)\n\n elif len(str) < int:\n print(\"Shorter than\",int,\"characters:\",str)\n\n else:\n print(\"Exactly\",int,\"characters:\",str)\n\n\ndef stop_light(current_color,duration):\n '''\n determines whether a stop light should change color,and, if so, what color it should change to.\n It takes two arguments. The value of the first will be either \"green\", \"yellow\", or \"red\".\n This represents the stop light's current color. The second parameter tells the function how long\n this color has been showing.\n\n 1.If green has been showing longer than 60 seconds, return \"yellow\".\n 2.If yellow has been showing longer than 5 seconds, return \u201cred\u201d.\n 3.If red has been showing longer than 55 seconds, return \u201cgreen\u201d.\n If the color hasn\u2019t been showing long enough (e.g. green has\n been showing for 17 seconds), return the current color.\n\n EX:\n stop_light('green', 61) --> 'yellow'\n stop_light('yellow', 5) --> 'yellow'\n stop_light('yellow', 6) --> 'red'\n stop_light('red', 12) --> 'red'\n stop_light('red', 56) --> 'green'\n '''\n if current_color == 'green':\n if duration > 60:\n return 'yellow'\n return current_color #else contain will return current_color\n elif current_color == 'yellow':\n if duration > 5:\n return 'red'\n return current_color\n else:\n if duration > 55:\n return 'green'\n return current_color\n\ndef is_normal_blood_pressure(systolic_blood_pressure, diastolic_blood_pressure):\n '''\n Two integer parameters.\n The first represents systolic blood pressure (the top number in a blood pressure reading). The\n second represents diastolic blood pressure (the bottom number in a blood pressure reading).\n The function should return True if systolic is less than 120 and diastolic is less than 80 (i.e.\n blood pressure is normal). Otherwise it returns False.\n\n EX:\n is_normal_blood_pressure(120, 80) --> False\n is_normal_blood_pressure(119, 80) --> False\n is_normal_blood_pressure(119, 79) --> True\n is_normal_blood_pressure(120, 79) --> False\n '''\n if systolic_blood_pressure < 120 and diastolic_blood_pressure < 80:\n return True\n return False\n\ndef doctor():\n '''\n The function will ask the user to enter his/her systolic blood pressure reading(int).\n It will then ask for the diastolic reading(int). The function then prints either\n \u201cYour blood pressure is normal.\u201d or \u201cYour blood pressure is high.\u201d depending\n on the values entered. This function should use the function you wrote in the previous\n question\n '''\n user_systolic_blood_pressure=int(input(\"systolic blood pressure: \"))\n user_diastolic_blood_pressure=int(input(\"Enter your diastolic reading: \"))\n if is_normal_blood_pressure(user_systolic_blood_pressure,user_diastolic_blood_pressure):\n print(\"Your blood pressure is normal.\")\n else:\n print(\"Your blood pressure is high.\")\n\n\ndef pants_size(user_waist_inches):\n '''\n Only a single parameter (the value will be an integer)\n representing a person\u2019s waist size in inches. The function returns a string.\n The string returned will be either \"small\", \"medium\", or \"large\" depending\n on the parameter value.\n @@Regulations:\n 1.Waist measurements that are 34 inches or larger should return large.\n 2.Measurements that are 30 inches or larger, but not large enough to be in the large category,\n should return medium.\n 3.Anything smaller should return small.\n --------------------------------------------------------------------------------------------\n EX:\n pants_size(38) --> 'large'\n pants_size(34) --> 'large'\n pants_size(33) --> 'medium'\n pants_size(29) --> 'small'\n pants_size(-20) --> 'small'\n pants_size(2000) --> 'large'\n\n '''\n if user_waist_inches >= 34:\n return 'large'\n elif user_waist_inches >= 30:\n return 'medium'\n else:\n return 'small'\n\ndef pants_fitter():\n '''\n No arguments. The function should first ask the user for his/her name.\n It then greets the user by name. Next it asks the user for his/her\n waist size in inches (a positive integer). It then asks the user how many pairs of pants he/she\n would like to buy (a positive integer). Next it asks what type of pants the user wants to buy\n (either \u201cregular\u201d or \u201cfancy\u201d). Next it calculates the cost of the pants (integer). Regular pants\n cost $40 per pair. Fancy pants cost $100 per pair. Finally it prints out the number of pairs, the\n size, the type, and the total cost. The following examples show the format that your prompts\n and output should be in. This function should use the function you wrote in the previous\n question.\n '''\n user_name=input(\"Enter your name: \")\n print(\"Greetings\",user_name,\"welcome to Pants-R-Us\")\n waist_size=int(input(\"Enter your waist size in inches: \"))\n num_pairs=int(input(\"How many pairs of pants would you like: \"))\n #pants_type=input(\"Would you like regular or fancy pants? \")\n cost=0\n is_legitimate_type=True\n\n while is_legitimate_type:\n pants_type=input(\"Would you like regular or fancy pants? \")\n if pants_type == 'regular':\n cost=num_pairs*40\n break\n elif pants_type == 'fancy':\n cost=num_pairs*100\n break\n else:\n print(\"Please try again!\")\n\n print(num_pairs,\"pairs of\",pants_size(waist_size),pants_type,\"pants: $\",cost)\n\ndef digdug(int_num):\n '''\n Takes a single argument number (assume it will always be a positive integer).\n For every integer from 1 up to and including number, the function will print a\n message if warranted.\n If the integer is evenly divisible by 3 the function will print \"dig\".\n If the integer is evenly divisible by 5 it prints \"dug\".\n If the integer is evenly divisible by both 3 and 5 , it prints \"digdug\".\n If the integer is not divisible by either 3 or 5 it does not print anything.\n '''\n i=1\n while i < int_num:\n i += 1\n if i%15 == 0:\n print(i,\": digdug\")\n elif i%3 == 0:\n print(i,\": dig\")\n elif i%5 == 0:\n print(i,\": dug\")\n\ndef beef_type(percent_lean):\n '''\n Takes a single parameter, percent_lean(float).\n 1.If the value of percent_lean is less than 78%, return \"Hamburger\".\n 2.If it is at least 78% and less than 85%, then return \"Chuck\".\n 3.At least 85% but less than 90% return \"Round\".\n 4.90-95% inclusive return \"Sirloin\".\n 5.If percent_lean doesn\u2019t fall within one of these ranges,return \"Unknown\".\n '''\n if percent_lean < 78:\n return \"Hamburger\"\n elif percent_lean < 85:\n return \"Chuck\"\n elif percent_lean < 90:\n return \"Round\"\n elif percent_lean <= 95:\n return \"Sirloin\"\n else:\n return \"Unknown\"\n\ndef species_height(species,height):\n '''\n Takes 2 arguments:\n The first is either \"Human\" or \"Klingon\".\n The second is a positive float representing the height (in inches) of\n this human or Klingon. In this homework assignment, the average human height is 67 inches.\n The average Klingon height is 71 inches. For the parameters given, print out if it is above, below\n or at the average height for its species.\n\n EX:\n species_height(\"Human\", 62.1)\n Below Average\n\n species_height(\"Klingon\", 73)\n Above Average\n\n species_height(\"Klingon \", 71)\n Average\n '''\n if species in ' Human ':\n if height == 67:\n print(\"Average\")\n elif height > 67:\n print(\"Above Average\")\n else:\n print(\"Below Average\")\n elif species in ' Klingon ':\n if height == 71:\n print(\"Average\")\n elif height > 71:\n print(\"Above Average\")\n else:\n print(\"Below Average\")\n\ndef sooner_date(month,day,month1,day1):\n '''\n There are 4 integer parameters:\n The first is a number between 1 and 12 (inclusive) that represents a month. 1 is January, 2 is February, etc.\n The second is a number between 1 and 31 (inclusive) that represents a day.\n The third parameter is another integer representing a month.\n The fourth is another integer parameter representing a day.\n So essentially you have 2 dates (the first 2 parameters and the second 2 parameters).\n Figure out which date would come sooner, then print out that date in the format month / day.\n\n EX:\n sooner_date(1, 1, 1, 2)\n >>1 / 1\n sooner_date(2, 5, 1, 3)\n >>1 / 3\n sooner_date(8, 25, 7, 30)\n >>7 / 30\n '''\n if month > month1:\n print(month1,\"/\",day1)\n elif month < month1:\n print(month,\"/\",day)\n else:\n if day > day1:\n print(month1,\"/\",day1)\n else:\n print(month,\"/\",day)\n\n# put all of your function definitions below this line and then delete this comment\n\n\n\n#==========================================================\ndef main():\n '''\n Write a description of what happens when you run\n this file here.\n '''\n '''\n word_length('liversnaps', 7)\n word_length('earwax', 5)\n word_length('chickenfat', 10)\n word_length('Gross!', 13)\n '''\n '''\n print(stop_light('green', 61))\n print(stop_light('yellow', 5))\n print(stop_light('yellow', 6))\n print(stop_light('red', 12))\n print(stop_light('red', 56))\n '''\n\n '''\n print(is_normal_blood_pressure(120, 80))\n print(is_normal_blood_pressure(119, 80))\n print(is_normal_blood_pressure(119, 79))\n print(is_normal_blood_pressure(120, 79))\n '''\n '''\n doctor()\n '''\n '''\n print(pants_size(38))\n print(pants_size(34))\n print(pants_size(33))\n print(pants_size(29))\n print(pants_size(-20))\n print(pants_size(2000))\n '''\n '''\n pants_fitter()\n '''\n '''\n digdug(15)\n '''\n '''\n print(beef_type(91.2))\n print(beef_type(78))\n print(beef_type(87))\n print(beef_type(95.1))\n '''\n '''\n species_height(\"Human\", 62.1)\n species_height(\"Klingon\", 73)\n species_height(\"Klingon \", 71)\n '''\n\n sooner_date(1, 1, 1, 2)\n sooner_date(2, 5, 1, 3)\n sooner_date(8, 25, 7, 30)\n # put main code here, make sure each line is indented one level, and delete this comment\n\n\n\n #input('Press enter to end.') # keeps the turtle graphics window open\n\nif __name__ == '__main__':\n main()\n"} {"doc_id": "36b7c50328516230161e3a0ddfeef39e", "text": "from collections import defaultdict\n\n\nclass TrieNode:\n def __init__(self: object) -> None:\n \"\"\"Constructor.\n \"\"\"\n\n self.children: defaultdict = defaultdict(TrieNode)\n self.is_word: bool = False\n\n\nclass Trie(object):\n def __init__(self: object) -> None:\n \"\"\"Constructor.\n \"\"\"\n self.root: TrieNode = TrieNode()\n\n def insert(self: object, word: str) -> None:\n \"\"\"Add a word to the trie.\n\n Time Complexity = O(len(word))\n Space Complexity = O(len(word))\n\n Parameters\n ----------\n word : str, required\n The word to add.\n \"\"\"\n\n if not word:\n return None\n if not isinstance(word, str):\n raise TypeError(\"Input word has to be of type str...\")\n if len(word) == 0:\n return None\n\n current_node: TrieNode = self.root\n\n for char in word:\n current_node = current_node.children[char]\n\n current_node.is_word = True\n\n def find(self: object, prefix: str) -> TrieNode:\n \"\"\"Find the Trie node that represents this prefix.\n\n Time Complexity = O(len(prefix))\n Space Complexity = O(1)\n\n Parameters\n ----------\n prefix : str, required\n The prefix to find the Trie node for.\n\n Returns\n ----------\n TrieNode\n Returns the Trie node for the prefix.\n \"\"\"\n if not prefix:\n return None\n if not isinstance(prefix, str):\n raise TypeError(\"Input word has to be of type str...\")\n if len(prefix) == 0:\n return None\n\n current_node: TrieNode = self.root\n\n for char in prefix:\n if char in current_node.children:\n current_node = current_node.children[char]\n else:\n return None\n\n return current_node\n\n def suffixes(\n self: object,\n prefix: str) -> set:\n \"\"\"Find all suffixes starting from a given Trie node that together with the prefix represented by the Trie node are a complete word.\n\n Time Complexity = O(len(prefix)) + O()\n Space Complexity = O()\n\n Parameters\n ----------\n prefix : str, required\n The prefix to find the Trie node for.\n\n Returns\n ----------\n set\n Returns a set with the existing suffixes.\n \"\"\"\n\n if not prefix or len(prefix) == 0:\n return []\n\n prefix_node: TrieNode = self.find(prefix)\n if not prefix_node:\n return []\n\n suffixes: set = set()\n\n def suffixes_helper(\n current_node: TrieNode,\n suffix: str = \"\") -> None:\n\n if current_node.is_word:\n if suffix != \"\":\n suffixes.add(suffix)\n\n for char in current_node.children:\n next_node: TrieNode = current_node.children[char]\n suffixes_helper(next_node, suffix + char)\n\n suffixes_helper(prefix_node)\n\n return suffixes\n"} {"doc_id": "36d9190bfec82463c04a6a1c9d1c504b", "text": "# -*- encoding: utf-8 -*-\n'''\n@project : LeetCode\n@File : replaceWords.py\n@Contact : 9824373@qq.com\n@Desc :\n\n \u5728\u82f1\u8bed\u4e2d\uff0c\u6211\u4eec\u6709\u4e00\u4e2a\u53eb\u505a\u00a0\u8bcd\u6839(root)\u7684\u6982\u5ff5\uff0c\u5b83\u53ef\u4ee5\u8ddf\u7740\u5176\u4ed6\u4e00\u4e9b\u8bcd\u7ec4\u6210\u53e6\u4e00\u4e2a\u8f83\u957f\u7684\u5355\u8bcd\u2014\u2014\u6211\u4eec\u79f0\u8fd9\u4e2a\u8bcd\u4e3a\u00a0\u7ee7\u627f\u8bcd(successor)\u3002\u4f8b\u5982\uff0c\u8bcd\u6839an\uff0c\u8ddf\u968f\u7740\u5355\u8bcd\u00a0other(\u5176\u4ed6)\uff0c\u53ef\u4ee5\u5f62\u6210\u65b0\u7684\u5355\u8bcd\u00a0another(\u53e6\u4e00\u4e2a)\u3002\n\n \u73b0\u5728\uff0c\u7ed9\u5b9a\u4e00\u4e2a\u7531\u8bb8\u591a\u8bcd\u6839\u7ec4\u6210\u7684\u8bcd\u5178\u548c\u4e00\u4e2a\u53e5\u5b50\u3002\u4f60\u9700\u8981\u5c06\u53e5\u5b50\u4e2d\u7684\u6240\u6709\u7ee7\u627f\u8bcd\u7528\u8bcd\u6839\u66ff\u6362\u6389\u3002\u5982\u679c\u7ee7\u627f\u8bcd\u6709\u8bb8\u591a\u53ef\u4ee5\u5f62\u6210\u5b83\u7684\u8bcd\u6839\uff0c\u5219\u7528\u6700\u77ed\u7684\u8bcd\u6839\u66ff\u6362\u5b83\u3002\n\n \u4f60\u9700\u8981\u8f93\u51fa\u66ff\u6362\u4e4b\u540e\u7684\u53e5\u5b50\u3002\n\n \u793a\u4f8b 1:\n\n \u8f93\u5165: dict(\u8bcd\u5178) = [\"cat\", \"bat\", \"rat\"]\n sentence(\u53e5\u5b50) = \"the cattle was rattled by the battery\"\n \u8f93\u51fa: \"the cat was rat by the bat\"\n \u6ce8:\n\n \u8f93\u5165\u53ea\u5305\u542b\u5c0f\u5199\u5b57\u6bcd\u3002\n 1 <= \u5b57\u5178\u5355\u8bcd\u6570 <=1000\n 1 <=\u00a0 \u53e5\u4e2d\u8bcd\u8bed\u6570\u00a0<= 1000\n 1 <= \u8bcd\u6839\u957f\u5ea6 <= 100\n 1 <= \u53e5\u4e2d\u8bcd\u8bed\u957f\u5ea6\u00a0<= 1000\n\n \u6765\u6e90\uff1a\u529b\u6263\uff08LeetCode\uff09\n \u94fe\u63a5\uff1ahttps://leetcode-cn.com/problems/replace-words\n\n@Modify Time @Author @Version @Desciption\n------------ ------- -------- -----------\n2020-03-13 zhan 1.0 None\n'''\nfrom collections import defaultdict\nfrom typing import List\n\nclass TriNode:\n def __init__(self):\n self.is_word = False\n self.children = defaultdict(TriNode)\n\nclass Trie:\n def __init__(self):\n self.root = TriNode()\n\n def insert(self,word):\n '''\n \u5f80\u5b57\u5178\u6811\u4e2d\u63d2\u5165\u5355\u8bcdword\n :param word: str \u7c7b\u578b\n :return:\n '''\n curNode = self.root\n for char in word:\n curNode = curNode.children[char]\n\n curNode.is_word = True\n\n def search(self,word):\n '''\n \u641c\u7d22word\u662f\u5426\u5728trie\u5b57\u5178\u6811\u79cd\n :param word: str\u7c7b\u578b\n :return:\n '''\n curNode = self.root\n for char in word:\n curNode = curNode.children[char]\n if curNode is None: return False\n return curNode.is_word\n\n def startswith(self, prefix):\n '''\n Returns if there is any word in the trie that starts with the given prefix.\n :param prefix:str\u7c7b\u578b\n :return:\n '''\n curNode = self.root\n for char in prefix:\n curNode = curNode.children[char]\n if curNode is None: return False\n return True\n\n def get_prefix(self,word):\n '''\n \u67e5\u627eword \u5728trie\u4e2d\u51fa\u73b0\u7684\u6700\u77ed\u524d\u7f00\n :param word:\n :return:\n '''\n curNode = self.root\n for i, letter in enumerate(word):\n curNode = curNode.children[letter]\n if curNode is not None and curNode.is_word == True:\n return word[:i+1]\n return ''\n\nclass Solution:\n def replaceWords(self, dict: List[str], sentence: str) -> str:\n trie = Trie()\n for word in dict:\n trie.insert(word)\n\n ans = ''\n for word in sentence.split():\n rStr = trie.get_prefix(word)\n if rStr: ans += rStr + ' '\n else:ans += word + ' '\n\n return ans[:-1]\n\nif __name__ == '__main__':\n dict = [\"cat\", \"bat\", \"rat\"]\n sentence = \"the cattle was rattled by the battery\"\n\n ans = Solution().replaceWords(dict, sentence)\n print(ans)\n\n\n"} {"doc_id": "36f04d81035edf138dd1024ff3b919ae", "text": "\"\"\"\nRemove Duplicates from Sorted List II\n-------------------------------------\n\nGiven a sorted linked list, delete all nodes that have duplicate numbers,\nleaving only distinct numbers from the original list.\n\nExample 1:\n Input: 1->2->3->3->4->4->5\n Output: 1->2->5\n\nExample 2:\n Input: 1->1->1->2->3\n Output: 2->3\n\nReference:\n - https://algorithm.yuanbin.me/zh-hans/linked_list/remove_duplicates_from_sorted_list_ii.html\n - https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii/\n - https://www.lintcode.com/problem/remove-duplicates-from-sorted-list-ii/\n\"\"\"\n\nfrom utils import ListNode, LinkedList\nimport unittest\n\n\ndef delete_duplicates(head):\n \"\"\"\n Remove all duplicates in given linked list, leaving only distinct numbers\n\n :param head: head node of given linked list\n :type head: ListNode\n :return: head node of operated linked list\n :rtype: ListNode\n \"\"\"\n if head is None:\n return head\n\n dummy_head = ListNode(None)\n dummy_head.next = head\n curr = dummy_head\n\n while curr.next is not None and curr.next.next is not None:\n if curr.next.val == curr.next.next.val:\n val = curr.next.val\n while curr.next is not None and curr.next.val == val:\n tmp = curr.next\n curr.next = curr.next.next\n del tmp\n else:\n curr = curr.next\n\n return dummy_head.next\n\n\nclass TestRemoveDuplicatesFromSortedListII(unittest.TestCase):\n def test_remove_duplicates_from_sorted_list_ii(self):\n def assert_operation(val_list, result_list):\n linked_list = LinkedList(singly=True)\n linked_list.append_val_list(val_list)\n head = delete_duplicates(linked_list.get_head())\n linked_list.set_head(head)\n self.assertListEqual(result_list, linked_list.to_list())\n\n assert_operation([], [])\n assert_operation([1, 2, 3, 3, 4, 4, 5], [1, 2, 5])\n assert_operation([1, 1, 1, 2, 3], [2, 3])\n\n\nif __name__ == '__main__':\n unittest.main()\n"} {"doc_id": "37026eb5645bbd4d3966660b8441477c", "text": "# author: \n# date: \n#\n# description: \n\n# --------------- Section 1 --------------- #\n\n# 1.1 | Variable Creation | Strings\n#\n# Relevant Documentation\n# - https://www.w3schools.com/python/python_variables.asp\n# - https://www.w3schools.com/python/python_variables_names.asp\n#\n# Variables\n# 1) Create a variable that holds your name.\n# 2) Create a variable that holds your birthday.\n# 3) Create a variable that holds the name of an animal you like.\n#\n# Print\n# 4) Print each variable, describing it when you print it.\n#\n# Example Code\nexample_name = 'elia'\nprint('EXAMPLE: my name is', example_name)\n\n# WRITE CODE BELOW\nmy_name='isaiah'\nprint('my name is',my_name)\nmy_birthday='october 20'\nprint('my birthday is',my_birthday)\nmy_animal='lion'\nprint('my favorite animal is',my_animal)\n# 1.2 | Variable Creation | Integers / Floats\n#\n# Relevant Documentation\n# - https://www.w3schools.com/python/python_variables.asp\n# - https://www.w3schools.com/python/python_variables_names.asp\n#\n# All variables created in this section should hold either an integer or float.\n#\n# Variables\n# 1) Create a variable that holds your favorite number.\n# 2) Create a variable that holds the day of the month of your birthday.\n# 3) Create a variable that holds a negative number.\n# 4) Create a variable that holds a floating (decimal) point number.\n#\n# Print\n# 5) Print each variable, describing the value you print.\n\n# WRITE CODE BELOW\nmy_number='12'\nprint('my favorite number is',my_number)\nmy_negative=-11\nprint('my favorite negative number',my_negative)\n\n# 1.3 | Overwriting Variables\n#\n# Relevant Documentation\n# - https://www.w3schools.com/python/python_variables.asp\n# - https://www.w3schools.com/python/python_variables_names.asp\n#\n# Variables\n# 1) Overwrite the variable holding your name, and save a different name to it.\n# 2) Overwrite the variable holding birthday with the day you think would be best to have a birthday on.\n# 3) Overwrite the variable holding your favorite number and set it to a number you think is unlucky.\n#\n# Print\n# 4) Print the variables you've overwritten, describing the values you print.\n#\n# Example Code\nexample_name = 'lucia'\nprint('EXAMPLE: my new name is', example_name)\n\n# WRITE CODE BELOW\n\n\n\n# 1.4 | Operations\n#\n# Relevant Documentation\n# - https://www.w3schools.com/python/python_variables.asp\n# - https://www.w3schools.com/python/python_variables_names.asp\n#\n# Variables\n# 1) Create a variable that is the sum of two numbers.\n# 2) Create a variable that is the product of three numbers.\n# 3) Create a variable by dividing the previously created sum, with the previously created product.\n#\n# 4) Create a variable that is the concatenation of your name and an animal you like (use the variables!)\n# 5) Create a variable that is an acronym (like 'lol') multiplied by your birth day.\n#\n# 6) Create a variable that is difference of itself minus the number you think is unlucky.\n# 7) Overwrite the lucky variable with the itself squared.\n#\n# Print\n# 7) Print all the new variables you've created along with what the represent\n#\n# Example Code\nexample_sum = 11 + 21\nprint('EXAMPLE: the sum of 11 and 21 is', example_sum)\n\n# WRITE CODE BELOW\n"} {"doc_id": "3759df783e401866664b0393b2abc538", "text": "\"\"\"Codewars: More Zeros than Ones\n6 kyu\n\nURL:https://www.codewars.com/kata/5d41e16d8bad42002208fe1a/train/python\n\nCreate a moreZeros function which will receive a string for input, and \nreturn an array containing only the characters from that string whose \nbinary representation of its ASCII value consists of more zeros than \nones.\n\nYou should remove any duplicate characters, keeping the first \noccurence of any such duplicates, so they are in the same order in the\nfinal array as they first appeared in the input string.\n\nExamples\n'abcde' === [\"1100001\", \"1100010\", \"1100011\", \"1100100\", \"1100101\"]\n True True False True False\n\n --> ['a','b','d']\n\n'DIGEST'--> ['D','I','E','T']\n\nAll input will be valid strings of length > 0. Leading zeros in binary \nshould not be counted.\n\"\"\"\n\n\ndef _new_s(s):\n s_lst = []\n length = len(s)\n for i in range(length):\n if s[i] not in s_lst:\n s_lst.append(s[i])\n return s_lst\n\n\ndef _ascii_value(s):\n s_ascii_value = []\n for x in _new_s(s):\n ascii_value = ord(x)\n s_ascii_value.append(ascii_value)\n return s_ascii_value\n\n \ndef _binary(s):\n binary_lst = []\n for i in _ascii_value(s):\n binary = bin(i)[2:]\n binary_lst.append(binary)\n return binary_lst\n\n\ndef _count_1_0_True_False(s):\n lst = []\n binary_s = _binary(s)\n length = len(binary_s)\n num = 0\n while num < length:\n count_1 = 0\n count_0 = 0\n for i in binary_s[num]: \n if int(i) == 1:\n count_1 += 1\n else:\n count_0 += 1\n if count_1 < count_0:\n lst.append('True')\n else:\n lst.append('False')\n num += 1\n return lst\n\n\ndef more_zeros(s):\n lst = _count_1_0_True_False(s)\n length = len(lst)\n new_s = _new_s(s)\n result = []\n for i in range(length):\n if lst[i] == 'True':\n result.append(new_s[i])\n return result\n\n\n# --------------------------------------------------\n\n\ndef _dedup(s):\n \"\"\"Step 2: Deduplicate string in the same order.\"\"\"\n # Use set seens to memorize seen chars.\n s_dedup_ls = []\n seens = set()\n for c in s:\n if c not in seens:\n seens.add(c)\n s_dedup_ls.append(c)\n return s_dedup_ls\n\n\ndef _compute_n_zeros_ones(c):\n \"\"\"Step 3: Compute number of zeros & ones.\"\"\"\n # Compute ascii's binary string, e.g. 0b100.\n bin_c = bin(ord(c))\n\n # Count how many ones in binary string.\n bin_str = bin_c[2:]\n return bin_str.count('0'), bin_str.count('1')\n\n\ndef more_zeros2(s):\n \"\"\"Step 1: main function.\"\"\"\n # Deduplicate chars in the same order.\n s_dedup_ls = _dedup(s)\n\n # Iterate through chars, compute its ascii's #0s/#1s.\n n_zeros_ls = []\n n_ones_ls = [] \n for c in s_dedup_ls:\n n_zeros, n_ones = _compute_n_zeros_ones(c)\n n_zeros_ls.append(n_zeros)\n n_ones_ls.append(n_ones)\n\n # Filter only chars with more zeros.\n result = []\n for i in range(len(s_dedup_ls)):\n if n_zeros_ls[i] > n_ones_ls[i]:\n result.append(s_dedup_ls[i])\n return result\n\n\n#------------------------------------------------------------------\n\n\ndef _dedup(s):\n \"\"\"Step 2: Deduplicate string in the same order.\"\"\"\n # Use set seens to memorize seen chars.\n s_dedup_ls = []\n seens = set()\n for c in s:\n if c not in seens:\n seens.add(c)\n s_dedup_ls.append(c)\n return s_dedup_ls\n\n\ndef _compute_n_zeros_ones(c):\n \"\"\"Step 3: Compute number of zeros & ones.\"\"\"\n # Compute ascii's binary string, e.g. 0b100.\n bin_c = bin(ord(c))\n bin_str = bin_c[2:]\n return bin_str.count('0'), bin_str.count('1')\n\n\ndef more_zeros3(s):\n \"\"\"Step 1: main function.\"\"\"\n # Deduplicate chars in the same order.\n s_dedup_ls = _dedup(s)\n\n # Iterate through chars, compute its ascii's #0s/#1s.\n result = []\n for c in s_dedup_ls:\n n_zeros, n_ones = _compute_n_zeros_ones(c)\n if n_zeros > n_ones:\n result.append(c)\n\n return result\n\n\ndef more_zeros4(s):\n result = []\n for i in s:\n bin_str = bin(ord(i))[2:]\n if bin_str.count('0') > bin_str.count('1') and i not in result:\n result.append(i)\n return result\n\n\ndef main():\n # # Output: ['a', 'b', 'd']\n # s = 'abbcde'\n # s = 'thequickbrownfoxjumpsoverthelazydog'\n # print(_new_s(s))\n # print(_ascii_value(s))\n # print(_binary(s))\n # print(_count_1_0_True_False(s))\n # print(more_zeros4(s))\n\n assert more_zeros('abcde') == ['a', 'b', 'd']\n assert more_zeros('thequickbrownfoxjumpsoverthelazydog') == ['h', 'b', 'p', 'a', 'd']\n assert more_zeros('THEQUICKBROWNFOXJUMPSOVERTHELAZYDOG') == ['T', 'H', 'E', 'Q', 'I', 'C', 'B', 'R', 'F', 'X', 'J', 'P', 'L', 'A', 'D']\n assert more_zeros('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890_') == ['a', 'b', 'd', 'h', 'p', 'A', 'B', 'C', 'D', 'E', 'F', 'H', 'I', 'J', 'L', 'P', 'Q', 'R', 'T', 'X', '0']\n assert more_zeros('DIGEST') == ['D', 'I', 'E', 'T']\n\n assert more_zeros2('abcde') == ['a', 'b', 'd']\n assert more_zeros2('thequickbrownfoxjumpsoverthelazydog') == ['h', 'b', 'p', 'a', 'd']\n assert more_zeros2('THEQUICKBROWNFOXJUMPSOVERTHELAZYDOG') == ['T', 'H', 'E', 'Q', 'I', 'C', 'B', 'R', 'F', 'X', 'J', 'P', 'L', 'A', 'D']\n assert more_zeros2('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890_') == ['a', 'b', 'd', 'h', 'p', 'A', 'B', 'C', 'D', 'E', 'F', 'H', 'I', 'J', 'L', 'P', 'Q', 'R', 'T', 'X', '0']\n assert more_zeros2('DIGEST') == ['D', 'I', 'E', 'T']\n\n assert more_zeros3('abcde') == ['a', 'b', 'd']\n assert more_zeros3('thequickbrownfoxjumpsoverthelazydog') == ['h', 'b', 'p', 'a', 'd']\n assert more_zeros3('THEQUICKBROWNFOXJUMPSOVERTHELAZYDOG') == ['T', 'H', 'E', 'Q', 'I', 'C', 'B', 'R', 'F', 'X', 'J', 'P', 'L', 'A', 'D']\n assert more_zeros3('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890_') == ['a', 'b', 'd', 'h', 'p', 'A', 'B', 'C', 'D', 'E', 'F', 'H', 'I', 'J', 'L', 'P', 'Q', 'R', 'T', 'X', '0']\n assert more_zeros3('DIGEST') == ['D', 'I', 'E', 'T']\n\n assert more_zeros4('abcde') == ['a', 'b', 'd']\n assert more_zeros4('thequickbrownfoxjumpsoverthelazydog') == ['h', 'b', 'p', 'a', 'd']\n assert more_zeros4('THEQUICKBROWNFOXJUMPSOVERTHELAZYDOG') == ['T', 'H', 'E', 'Q', 'I', 'C', 'B', 'R', 'F', 'X', 'J', 'P', 'L', 'A', 'D']\n assert more_zeros4('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890_') == ['a', 'b', 'd', 'h', 'p', 'A', 'B', 'C', 'D', 'E', 'F', 'H', 'I', 'J', 'L', 'P', 'Q', 'R', 'T', 'X', '0']\n assert more_zeros4('DIGEST') == ['D', 'I', 'E', 'T']\n\n\nif __name__ == '__main__':\n main()\n\n"} {"doc_id": "378bc6509936ddf0134ddcdc7bca4b5d", "text": "# -*- coding: utf-8 -*-\n\n# Aprimore a classe do exerc\u00edcio anterior para adicionar o m\u00e9todo aumentarSalario (porcentualDeAumento)\n# que aumente o sal\u00e1rio do funcion\u00e1rio em uma certa porcentagem.\n\n\nclass Funcionario(object):\n def __init__(self, nome, salario):\n self.nome = nome.title()\n self.salario = salario\n\n def aumentar_salario(self, porcentagem):\n self.salario += self.salario * (porcentagem / 100)\n\n def __str__(self):\n return \"\"\"\n\u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2564\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557\n\u2551 Nome \u2502 Salario(R$) \u2551\n\u255f\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2562\n\u2551 {:<6.6} \u2502 {:<11.2f} \u2551\n\u255a\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2567\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255d\n\"\"\".format(self.nome, self.salario)\n\n\nif __name__ == '__main__':\n nome = input('Nome: ')\n salario = float(input('Sal\u00e1rio: '))\n funcionario = Funcionario(nome, salario)\n\n porcentagem = int(input('Aumentar o sal\u00e1rio em: '))\n funcionario.aumentar_salario(porcentagem)\n\n print(funcionario)\n"} {"doc_id": "37978febf0c29f840393fd6a76b8cb5c", "text": "\"\"\"\nAuthor Samuel Souik\n\nLicense MIT.\n\nfill.py\n\"\"\"\nfrom itertools import islice\nfrom .concat import concat\n\n\ndef fill(seq, value, start=0, end=None):\n \"\"\"\n Description\n ----------\n Fill the sequence with a value.\n\n Parameters\n ----------\n seq : (list or tuple or set or string) - sequence to fill\\n\n value : any - value to fill the sequence with\\n\n start : int, optional - starting index (default is 0)\\n\n end : int, optional - ending index (not included) (default vlaue is None = len(seq))\n Returns\n ----------\n generator - a generator with the sequence filled\n\n Examples\n ----------\n >>> lst = [1, 2, 3, 4, 5]\n >>> fill(lst, '*')\n -> ['*', '*', '*', '*', '*'] \n >>> fill(lst, -1, 1, 3)\n -> [1, -1, -1, 4, 5]\n \"\"\"\n if not isinstance(seq, (list, tuple, set, str)):\n raise TypeError(\"param 'seq' must be a list, tuple, set, or string\")\n\n if not isinstance(start, int):\n raise TypeError(\"params 'start' must be an integer\")\n\n if end is None:\n end = len(seq)\n\n if not isinstance(end, int):\n raise TypeError(\"param 'end' must be an integer\")\n\n if start < 0 or end < 0 or start > end:\n raise ValueError(\n \"params 'start' and 'end' must be greater than or equal to 0\",\n \"'end' must be greater than or equal to 'start'\",\n )\n\n lst1 = islice(seq, 0, start)\n lst3 = islice(seq, end, len(seq))\n\n lst2 = []\n append = lst2.append\n while start < end:\n append(value)\n start = start + 1\n return concat(lst1, lst2, lst3)\n"} {"doc_id": "37a3ef2437b09546cb9a9b58facfc8b9", "text": "\"\"\"\nFile: weather_master.py\nName: Wilson Wang\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# The value to stop program\nEXIT = -100\n\n\ndef main():\n\t\"\"\"\n\tThis program should implement a console program\n\tthat asks weather data from user to compute the\n\taverage, highest, lowest, cold days among the inputs.\n\t\"\"\"\n\n\tprint(\"stanCode \\\"weather master 4.0\")\n\tnew_data = int(input('Next temperature: (or '+str(EXIT)+' to quit)?'))\n\t# no temperature enter\n\tif new_data == EXIT:\n\t\tprint('No temperature were entered')\n\t# first temperature enter\n\telse:\n\t\tmaximum = new_data\n\t\tminimum = new_data\n\t\ttotal = new_data\n\t\tdays = 0\n\t\t# determine whether first temperature is cold day\n\t\tif new_data\t< 16:\n\t\t\tdays = 1\n\t\ttimes = 1\n\t\twhile True:\n\t\t\t# second temperature enter\n\t\t\tnew_data = int(input('Next temperature: (or ' + str(EXIT) + ' to quit)?'))\n\t\t\t# no temperature enter\n\t\t\tif new_data == EXIT:\n\t\t\t\tbreak\n\t\t\t# new temperature would become maximum\n\t\t\tif new_data > maximum:\n\t\t\t\tmaximum = new_data\n\t\t\t# new temperature would counts as cold day\n\t\t\tif new_data < 16:\n\t\t\t\tdays += 1\n\t\t\t# new temperature would become minimum\n\t\t\tif new_data < minimum:\n\t\t\t\tminimum = new_data\n\t\t\t# total and times are made for counting average of all temperatures\n\t\t\ttotal = new_data + total\n\t\t\ttimes += 1\n\n\t\taverage = total / times\n\n\t\tprint('Highest temperature = '+str(maximum))\n\t\tprint('Lowest temperature ='+str(minimum))\n\t\tprint('Average ='+str(average))\n\t\tprint(str(days)+' cold day(s)')\n\n\n###### DO NOT EDIT CODE BELOW THIS LINE ######\n\nif __name__ == \"__main__\":\n\tmain()\n"} {"doc_id": "37beca29c521a4da125ddf27df31a601", "text": "\nclass Chapter8:\n \"\"\"\n \u7b2c8\u7ae0 \u63d0\u5347\u65b9\u6cd5\n \"\"\"\n def __init__(self):\n \"\"\"\n \u7b2c8\u7ae0 \u63d0\u5347\u65b9\u6cd5\n \"\"\"\n pass\n\n def note(self):\n \"\"\"\n chapter8 note\n \"\"\"\n print('\u7b2c8\u7ae0 \u63d0\u5347\u65b9\u6cd5')\n print('\u63d0\u5347(boosting)\u65b9\u6cd5\u662f\u4e00\u79cd\u5e38\u7528\u7684\u7edf\u8ba1\u5b66\u4e60\u65b9\u6cd5,\u5e94\u7528\u5e7f\u6cdb\u4e14\u6709\u6548.',\n '\u5728\u5206\u7c7b\u95ee\u9898\u4e2d,\u901a\u8fc7\u6539\u53d8\u8bad\u7ec3\u6837\u672c\u7684\u6743\u91cd,\u5b66\u4e60\u591a\u4e2a\u5206\u7c7b\u5668,',\n '\u5e76\u5c06\u8fd9\u4e9b\u5206\u7c7b\u5668\u7ebf\u6027\u7ec4\u5408,\u63d0\u9ad8\u5206\u7c7b\u7684\u6027\u80fd')\n print('8.1 \u63d0\u5347\u65b9\u6cd5AdaBoost\u7b97\u6cd5')\n print('8.1.1 \u63d0\u5347\u65b9\u6cd5\u7684\u57fa\u672c\u601d\u8def')\n print('\u63d0\u5347\u65b9\u6cd5\u57fa\u4e8e\u8fd9\u6837\u4e00\u79cd\u601d\u60f3:\u5bf9\u4e8e\u4e00\u4e2a\u590d\u6742\u4efb\u52a1\u6765\u8bf4,',\n '\u5c06\u591a\u4e2a\u4e13\u5bb6\u7684\u5224\u65ad\u8fdb\u884c\u9002\u5f53\u7684\u7efc\u5408\u6240\u5f97\u51fa\u7684\u5224\u65ad.',\n '\u8981\u6bd4\u5176\u4e2d\u4efb\u4f55\u4e00\u4e2a\u4e13\u5bb6\u5355\u72ec\u7684\u5224\u65ad\u597d.',\n '\u7c7b\u4f3c\u201c\u4e09\u4e2a\u81ed\u76ae\u5320\u9876\u4e2a\u8bf8\u845b\u4eae\u201d')\n print('\u201c\u5f3a\u53ef\u5b66\u4e60\u201d\u548c\u201c\u5f31\u53ef\u5b66\u4e60\u201d.',\n '\u5728\u6982\u7387\u8fd1\u4f3c\u6b63\u786e(PAC)\u5b66\u4e60\u6846\u67b6\u4e2d,\u4e00\u4e2a\u6982\u5ff5(\u4e00\u4e2a\u7c7b),\u5982\u679c\u5b58\u5728\u4e00\u4e2a\u591a\u9879\u5f0f\u7684\u5b66\u4e60\u7b97\u6cd5\u80fd\u591f\u5b66\u4e60\u5b83',\n '\u5e76\u4e14\u6b63\u786e\u7387\u5f88\u9ad8,\u90a3\u4e48\u5c31\u79f0\u8fd9\u4e2a\u6982\u5ff5\u662f\u5f3a\u53ef\u5b66\u4e60\u7684;\u4e00\u4e2a\u6982\u5ff5,',\n '\u5982\u679c\u5b58\u5728\u4e00\u4e2a\u591a\u9879\u5f0f\u7684\u5b66\u4e60\u7b97\u6cd5\u80fd\u591f\u5b66\u4e60\u5b83,\u5b66\u4e60\u7684\u6b63\u786e\u7387\u4ec5\u6bd4\u968f\u673a\u731c\u6d4b\u7565\u597d,',\n '\u90a3\u4e48\u5c31\u79f0\u8fd9\u4e2a\u6982\u5ff5\u662f\u5f31\u53ef\u5b66\u4e60\u7684.')\n print('\u5728PAC\u5b66\u4e60\u7684\u6846\u67b6\u4e0b,\u4e00\u4e2a\u6982\u5ff5\u662f\u5f3a\u53ef\u5b66\u4e60\u7684\u5145\u5206\u5fc5\u8981\u6761\u4ef6\u662f\u8fd9\u4e2a\u6982\u5ff5\u662f\u5f31\u53ef\u5b66\u4e60\u7684.')\n print('\u5bf9\u4e8e\u5206\u7c7b\u95ee\u9898\u800c\u8a00,\u7ed9\u5b9a\u4e00\u4e2a\u8bad\u7ec3\u6837\u672c\u96c6,\u6c42\u6bd4\u8f83\u7c97\u7cd9\u7684\u5206\u7c7b\u89c4\u5219(\u5f31\u5206\u7c7b\u5668)\u8981\u6bd4\u6c42\u7cbe\u786e\u7684\u5206\u7c7b\u89c4\u5219(\u5f3a\u5206\u7c7b\u5668)',\n '\u5bb9\u6613\u7684\u591a,\u63d0\u5347\u65b9\u6cd5\u5c31\u662f\u4ece\u5f31\u5b66\u4e60\u7b97\u6cd5\u51fa\u53d1,\u53cd\u590d\u5b66\u4e60,\u5f97\u5230\u4e00\u7cfb\u5217\u5f31\u5206\u7c7b\u5668(\u53c8\u79f0\u4e3a\u57fa\u672c\u5206\u7c7b\u5668),',\n '\u7136\u540e\u7ec4\u5408\u8fd9\u4e9b\u5f31\u5206\u7c7b\u5668,\u6784\u6210\u4e00\u4e2a\u5f3a\u5206\u7c7b\u5668.\u5927\u591a\u6570\u63d0\u5347\u65b9\u6cd5\u90fd\u662f\u6539\u53d8\u8bad\u7ec3\u6570\u636e\u7684\u6982\u7387\u5206\u5e03(\u8bad\u7ec3\u6570\u636e\u7684\u6743\u503c\u5206\u5e03)',\n '\u9488\u5bf9\u4e0d\u540c\u7684\u8bad\u7ec3\u6570\u636e\u5206\u5e03\u8c03\u7528\u5f31\u5b66\u4e60\u7b97\u6cd5\u5b66\u4e60\u4e00\u7cfb\u5217\u5f31\u5206\u7c7b\u5668')\n print('AdaBoost\u7b97\u6cd5\u505a\u6cd5\u662f:\u63d0\u9ad8\u90a3\u4e9b\u88ab\u524d\u4e00\u8f6e\u5f31\u5206\u7c7b\u5668\u9519\u8bef\u5206\u7c7b\u6837\u672c\u7684\u6743\u503c,',\n '\u800c\u964d\u4f4e\u90a3\u4e9b\u88ab\u6b63\u786e\u5206\u7c7b\u6837\u672c\u7684\u6743\u503c,\u8fd9\u6837\u4e00\u6765,\u90a3\u4e9b\u6ca1\u6709\u5f97\u5230\u6b63\u786e\u5206\u7c7b\u7684\u6570\u636e,',\n '\u7531\u4e8e\u5176\u6743\u503c\u7684\u52a0\u5927\u800c\u53d7\u5230\u540e\u4e00\u8f6e\u7684\u5f31\u5206\u7c7b\u5668\u7684\u66f4\u5927\u5173\u6ce8.')\n print('\u4e8e\u662f,\u5206\u7c7b\u95ee\u9898\u88ab\u4e00\u7cfb\u5217\u7684\u5f31\u5206\u7c7b\u5668\u201c\u5206\u800c\u6cbb\u4e4b\u201d.\u5f31\u5206\u7c7b\u5668\u7684\u7ec4\u5408,',\n 'AdaBoost\u91c7\u53d6\u52a0\u6743\u591a\u6570\u8868\u51b3\u7684\u65b9\u6cd5.\u5177\u4f53\u5730,\u52a0\u5927\u5206\u7c7b\u8bef\u5dee\u7387\u5c0f\u7684\u5f31\u5206\u7c7b\u5668\u7684\u6743\u503c,',\n '\u4f7f\u5176\u5728\u8868\u51b3\u4e2d\u8d77\u8f83\u5927\u7684\u4f5c\u7528,\u51cf\u5c0f\u5206\u7c7b\u8bef\u5dee\u7387\u5927\u7684\u5f31\u5206\u7c7b\u5668\u7684\u6743\u503c,\u4f7f\u5176\u5728\u8868\u51b3\u4e2d\u8d77\u8f83\u5c0f\u7684\u4f5c\u7528.',\n 'AdaBoost\u7684\u5de7\u5999\u4e4b\u5904\u5c31\u5728\u4e8e\u5b83\u5c06\u8fd9\u4e9b\u60f3\u6cd5\u81ea\u7136\u4e14\u6709\u6548\u5730\u5b9e\u73b0\u5728\u4e00\u79cd\u7b97\u6cd5\u91cc')\n print('8.1.2 AdaBoost\u7b97\u6cd5')\n print('\u5047\u8bbe\u7ed9\u5b9a\u4e00\u4e2a\u4e8c\u7c7b\u5206\u7c7b\u7684\u8bad\u7ec3\u6570\u636e\u96c6T={(x1,y1),(x2,y2),...,(xn,yn)}.',\n '\u5176\u4e2d,\u6bcf\u4e2a\u6837\u672c\u70b9\u7531\u5b9e\u4f8b\u4e0e\u6807\u8bb0\u7ec4\u6210.\u5b9e\u4f8bxi\u2208X\u2208R^n,\u6807\u8bb0yi\u2208Y={-1,+1},',\n 'X\u662f\u5b9e\u4f8b\u7a7a\u95f4,Y\u662f\u6807\u8bb0\u96c6\u5408.AdaBoost\u5229\u7528\u4e00\u4e0b\u7b97\u6cd5,\u4ece\u8bad\u7ec3\u6570\u636e\u4e2d\u5b66\u4e60\u4e00\u7cfb\u5217\u5f31\u5206\u7c7b\u5668\u6216\u57fa\u672c\u5206\u7c7b\u5668',\n '\u5e76\u5c06\u8fd9\u4e9b\u5f31\u5206\u7c7b\u5668\u7ebf\u6027\u7ec4\u5408\u6210\u4e3a\u4e00\u4e2a\u5f3a\u5206\u7c7b\u5668')\n print('\u7b97\u6cd58.1 (AdaBoost)')\n print('\u8f93\u5165:\u8bad\u7ec3\u6570\u636e\u96c6T={(x1,y1),(x2,y2),...,(xn,yn)},\u5176\u4e2dxi\u2208X\u2208R^n,yi\u2208Y={-1,+1};\u5f31\u5b66\u4e60\u7b97\u6cd5;')\n print('\u8f93\u51fa:\u6700\u7ec8\u5206\u7c7b\u5668G(x)')\n print('(1) \u521d\u59cb\u5316\u8bad\u7ec3\u6570\u636e\u7684\u6743\u503c\u5206\u5e03D1=(w11,...,w1i,...,w1N),w1i=1/N,w1i=1/N,i=1,2,...,N')\n print('(2) \u5bf9m=1,2,...,M')\n print(' (a) \u4f7f\u7528\u5177\u6709\u6743\u503c\u5206\u5e03Dm\u7684\u8bad\u7ec3\u6570\u636e\u96c6\u5b66\u4e60,\u5f97\u5230\u57fa\u672c\u5206\u7c7b\u5668Gm(x)=X->{-1,+1}')\n print(' (b) \u8ba1\u7b97Gm(x)\u5728\u8bad\u7ec3\u6570\u636e\u96c6\u4e0a\u7684\u5206\u7c7b\u8bef\u5dee\u7387')\n print(' (c) \u8ba1\u7b97Gm(x)\u7684\u7cfb\u6570am=0.5log(1-em)/em')\n print(' (d) \u66f4\u65b0\u8bad\u7ec3\u6570\u636e\u96c6\u7684\u6743\u503c\u5206\u5e03')\n print('(3) \u6784\u5efa\u57fa\u672c\u5206\u7c7b\u5668\u7684\u7ebf\u6027\u7ec4\u5408f(x)=\u2211amGm(x)')\n print('\u6700\u7ec8\u5f97\u5230\u5206\u7c7b\u5668:G(x)=sign(f(x))=sign(\u2211amGm(x))')\n print('\u6b65\u9aa4(1) \u5047\u8bbe\u8bad\u7ec3\u6570\u636e\u96c6\u5177\u6709\u5747\u5300\u7684\u6743\u503c\u5206\u5e03,\u5373\u6bcf\u4e2a\u8bad\u7ec3\u6837\u672c\u5728\u57fa\u672c\u5206\u7c7b\u5668\u7684\u5b66\u4e60\u4e2d\u4f5c\u7528\u76f8\u540c,',\n '\u8fd9\u4e00\u5047\u8bbe\u4fdd\u8bc1\u7b2c1\u6b65\u80fd\u591f\u5728\u539f\u59cb\u6570\u636e\u4e0a\u5b66\u4e60\u57fa\u672c\u5206\u7c7b\u5668G1(x).')\n print('\u6b65\u9aa4(2) AdaBoost\u53cd\u590d\u5b66\u4e60\u57fa\u672c\u5206\u7c7b\u5668,\u5728\u6bcf\u4e00\u8f6em=1,2,...,M\u987a\u6b21\u5730\u6267\u884c\u4e0b\u5217\u64cd\u4f5c\uff1a')\n print(' (a) \u4f7f\u7528\u5f53\u524d\u5206\u5e03Dm\u52a0\u6743\u7684\u8bad\u7ec3\u6570\u636e\u96c6,\u5b66\u4e60\u57fa\u672c\u5206\u7c7b\u5668Gm(x)')\n print(' (b) \u8ba1\u7b97\u57fa\u672c\u5206\u7c7b\u5668Gm(x)\u5728\u52a0\u6743\u8bad\u7ec3\u6570\u636e\u96c6\u4e0a\u7684\u5206\u7c7b\u8bef\u5dee\u7387:')\n print('\u8fd9\u91cc,wmi\u8868\u793a\u7b2cm\u8f6e\u4e2d\u7b2ci\u4e2a\u5b9e\u4f8b\u7684\u6743\u503c,\u2211wmi=1.')\n print('Gm(x)\u5728\u52a0\u6743\u7684\u8bad\u7ec3\u6570\u636e\u96c6\u4e0a\u7684\u5206\u7c7b\u8bef\u5dee\u7387\u662f\u88abGm(x)\u8bef\u5206\u7c7b\u6837\u672c\u7684\u6743\u503c\u4e4b\u548c,',\n '\u7531\u6b64\u53ef\u4ee5\u770b\u51fa\u6570\u636e\u6743\u503c\u5206\u5e03Dm\u4e0e\u57fa\u672c\u5206\u7c7b\u5668Gm(x)\u7684\u5206\u7c7b\u8bef\u5dee\u7387\u7684\u5173\u7cfb')\n print(' (c) \u8ba1\u7b97\u57fa\u672c\u5206\u7c7b\u5668Gm(x)\u7684\u7cfb\u6570am\u00b7am\u8868\u793aGm(x)\u5728\u6700\u7ec8\u5206\u7c7b\u5668\u4e2d\u7684\u91cd\u8981\u6027.',\n '\u5f53em<=0.5\u65f6,am>=0,\u5e76\u4e14am\u968f\u7740em\u7684\u51cf\u5c0f\u800c\u589e\u5927,',\n '\u6240\u4ee5\u5206\u7c7b\u8bef\u5dee\u7387\u8d8a\u5c0f\u7684\u57fa\u672c\u5206\u7c7b\u5668\u5728\u6700\u7ec8\u5206\u7c7b\u5668\u7684\u4f5c\u7528\u8d8a\u5927')\n print(' (d) \u66f4\u65b0\u8bad\u7ec3\u6570\u636e\u7684\u6743\u503c\u5206\u5e03\u4e3a\u4e0b\u4e00\u8f6e\u4f5c\u51c6\u5907.')\n print('\u7531\u6b64\u53ef\u77e5,\u88ab\u57fa\u672c\u5206\u7c7b\u5668Gm(x)\u8bef\u5206\u7c7b\u6837\u672c\u7684\u6743\u503c\u5f97\u4ee5\u6269\u5927,\u800c\u88ab\u6b63\u786e\u5206\u7c7b\u6837\u672c\u7684\u6743\u503c\u5374\u5f97\u4ee5\u7f29\u5c0f.',\n '\u4e24\u76f8\u6bd4\u8f83,\u8bef\u5206\u7c7b\u6837\u672c\u7684\u6743\u503c\u88ab\u653e\u5927.\u56e0\u6b64,\u8bef\u5206\u7c7b\u6837\u672c\u5728\u4e0b\u4e00\u8f6e\u5b66\u4e60\u4e2d\u8d77\u66f4\u5927\u7684\u4f5c\u7528.',\n '\u4e0d\u6539\u53d8\u6240\u7ed9\u7684\u8bad\u7ec3\u6570\u636e,\u800c\u4e0d\u65ad\u6539\u53d8\u8bad\u7ec3\u6570\u636e\u6743\u503c\u7684\u5206\u5e03,\u4f7f\u5f97\u8bad\u7ec3\u6570\u636e\u5728\u57fa\u672c\u5206\u7c7b\u5668\u7684\u5b66\u4e60\u4e2d\u8d77\u4e0d\u540c\u7684\u4f5c\u7528,',\n '\u8fd9\u662fAdaBoost\u7684\u4e00\u4e2a\u7279\u70b9.')\n print('\u6b65\u9aa4(3) \u7ebf\u6027\u7ec4\u5408f(x)\u5b9e\u73b0M\u4e2a\u57fa\u672c\u5206\u7c7b\u5668\u7684\u52a0\u6743\u8868\u51b3.\u7cfb\u6570am\u8868\u793a\u4e86\u57fa\u672c\u5206\u7c7b\u5668Gm(x)\u7684\u91cd\u8981\u6027',\n '\u8fd9\u91cc,\u6240\u6709am\u4e4b\u548c\u5e76\u4e0d\u4e3a1.f(x)\u7684\u7b26\u53f7\u51b3\u5b9a\u5b9e\u4f8bx\u7684\u7c7b,f(x)\u7684\u7edd\u5bf9\u503c\u8868\u793a\u5206\u7c7b\u7684\u786e\u4fe1\u5ea6.',\n '\u5229\u7528\u57fa\u672c\u5206\u7c7b\u5668\u7684\u7ebf\u6027\u7ec4\u5408\u6784\u5efa\u6700\u7ec8\u5206\u7c7b\u5668\u662fAdaBoost\u7684\u53e6\u4e00\u7279\u70b9.')\n print('8.1.3 AdaBoost\u4f8b\u5b50')\n print('\u4f8b\u5b508.1 \u7ed9\u5b9a\u5982\u88688.1\u6240\u793a\u7684\u8bad\u7ec3\u6570\u636e.\u5047\u8bbe\u5f31\u5206\u7c7b\u5668\u7531xv\u4ea7\u751f,',\n '\u5176\u9608\u503cv\u4f7f\u8be5\u5206\u7c7b\u5668\u5728\u8bad\u7ec3\u6570\u636e\u96c6\u4e0a\u5206\u7c7b\u8bef\u5dee\u7387\u6700\u4f4e',\n '\u8bd5\u7528AdaBoost\u7b97\u6cd5\u5b66\u4e60\u4e00\u4e2a\u5f3a\u5206\u7c7b\u5668')\n print('\u89e3\uff1a\u521d\u59cb\u5316\u6570\u636e\u6743\u503c\u5206\u5e03D1=(w11,w12,...,wl10),w1i=0.1,i=1,2,...,10.',\n '\u5bf9m=1')\n print(' (a) \u5728\u6743\u503c\u5206\u5e03\u4e3aD1\u7684\u8bad\u7ec3\u6570\u636e\u4e0a,\u9608\u503cv\u53d62.5\u65f6\u5206\u7c7b\u8bef\u5dee\u7387\u6700\u4f4e,\u6545\u57fa\u672c\u5206\u7c7b\u5668\u4e3a',\n 'G1(x)=1 x<2.5, G1(x)=-1 x>2.5')\n print(' (b) G1(x)\u5728\u8bad\u7ec3\u6570\u636e\u96c6\u4e0a\u7684\u8bef\u8bef\u5dee\u7387e1=P(G1(xi)!=yi)=0.3')\n print(' (c) \u8ba1\u7b97G1(x)\u7684\u7cfb\u6570:a1=0.5log(1-e1)/e1=0.4236')\n print(' (d) \u66f4\u65b0\u8bad\u7ec3\u6570\u636e\u7684\u6743\u503c\u5206\u5e03:D2=(w21,...,w2i,...,w110)',\n 'w2i=w1i/Z1exp(-a1yiG1(xi)),i=1,2,...,10')\n print(' D2=(0.0715m0.0715m0.0715,...)')\n print(' f1(x)=0.4236G1(x)')\n print('\u5206\u7c7b\u5668sign[f1(x)]\u5728\u8bad\u7ec3\u6570\u636e\u96c6\u4e0a\u67093\u4e2a\u8bef\u5206\u7c7b\u70b9')\n print('\u5bf9m=2,')\n print(' (a) \u5728\u6743\u503c\u5206\u5e03\u4e3aD2\u7684\u8bad\u7ec3\u6570\u636e\u4e0a,\u9608\u503cv\u662f8.5\u65f6\u5206\u7c7b\u8bef\u5dee\u7387\u6700\u4f4e,\u57fa\u672c\u5206\u7c7b\u5668\u4e3a\uff1a',\n 'G2(x)=1, x<8.5; G2(x)=-1, x>8.5')\n print(' (b) G2(x)z\u5728\u8bad\u7ec3\u6570\u636e\u96c6\u4e0a\u7684\u8bef\u5dee\u7387e2=0.2143')\n print(' (c) \u8ba1\u7b97a2=0.6496')\n print(' (d) \u66f4\u65b0\u8bad\u7ec3\u6570\u636e\u6743\u503c\u5206\u5e03:D3=(...),f(2)=0.4236G1(x)+0.6496G2(x); f2(x)',\n '\u5206\u7c7b\u5668sign[f2(x)]\u5728\u8bad\u7ec3\u6570\u636e\u96c6\u4e0a\u67093\u4e2a\u8bef\u5206\u7c7b\u70b9')\n print('\u5bf9m=3,\u540c\u7406\u53ef\u5f97.')\n print('8.2 AdaBoost\u7b97\u6cd5\u7684\u8bad\u7ec3\u8bef\u5dee\u5206\u6790.')\n print('\u5b9a\u74068.1(AdaBoost\u7684\u8bad\u7ec3\u8bef\u5dee) \u8bad\u7ec3\u8bef\u5dee\u754c\u4e3a:')\n print(' 1/N\u2211I(G(xi)!=yi)<=1/N\u2211exp(-yi,f(xi))=\u220fZm')\n print('\u8fd9\u4e00\u5b9a\u7406\u8bf4\u660e,\u53ef\u4ee5\u5728\u6bcf\u4e00\u8f6e\u9009\u53d6\u9002\u5f53\u7684Gm\u4f7f\u5f97Zm\u6700\u5c0f,\u4ece\u800c\u4f7f\u8bad\u7ec3\u8bef\u5dee\u4e0b\u964d\u6700\u5feb.')\n print('\u5b9a\u74068.2(\u4e8c\u7c7b\u5206\u7c7b\u95ee\u9898AdaBoost\u7684\u8bad\u7ec3\u8bef\u5dee\u754c)')\n print(' \u220fZm=\u220f[2sqrt(em(1-em))]=\u220fsqrt(1-4ym^2)<=exp(-2\u2211ym^2),\u8fd9\u91ccym=0.5-em')\n print('\u63a8\u8bba8.1 \u5982\u679c\u5b58\u5728y>0,\u5bf9\u6240\u6709m\u6709ym>=y,\u52191/N\u2211I(G(xi)!=yi)<=exp(-2My^2)')\n print(' \u8868\u660eAdaBoost\u7684\u8bad\u7ec3\u8bef\u5dee\u662f\u4ee5\u6307\u6570\u901f\u7387\u4e0b\u964d\u7684.')\n print('\u6ce8\u610f:AdaBoost\u7b97\u6cd5\u4e0d\u9700\u8981\u77e5\u9053\u4e0b\u754cy.\u4e0e\u4e00\u4e9b\u65e9\u671f\u7684\u63d0\u5347\u65b9\u6cd5\u4e0d\u540c,AdaBoost\u5177\u6709\u9002\u5e94\u6027,',\n '\u5373\u5b83\u80fd\u9002\u5e94\u5f31\u5206\u7c7b\u5668\u5404\u81ea\u7684\u8bad\u7ec3\u8bef\u5dee\u7387.Ada\u662fAdaptive(\u9002\u5e94)\u7684\u7b80\u5199.')\n print('8.3 AdaBoost\u7b97\u6cd5\u7684\u89e3\u91ca')\n print('AdaBoost\u7b97\u6cd5\u8fd8\u6709\u53e6\u4e00\u89e3\u91ca,\u5373\u53ef\u4ee5\u8ba4\u4e3aAdaBoost\u7b97\u6cd5\u662f\u6a21\u578b\u4e3a\u52a0\u6cd5\u6a21\u578b\u3001\u635f\u5931\u51fd\u6570\u4e3a\u6307\u6570\u51fd\u6570\u3001',\n '\u5b66\u4e60\u7b97\u6cd5\u4e3a\u524d\u5411\u5206\u6b65\u7b97\u6cd5\u65f6\u7684\u4e8c\u7c7b\u5206\u7c7b\u5b66\u4e60\u65b9\u6cd5.')\n print('8.3.1 \u524d\u5411\u5206\u5e03\u7b97\u6cd5')\n print('\u8003\u8651\u52a0\u6cd5\u6a21\u578b:f(x)=\u2211bmb(x;ym).\u5176\u4e2d,b(x;ym)\u4e3a\u57fa\u51fd\u6570,bm\u4e3a\u57fa\u51fd\u6570\u7684\u7cfb\u6570.',\n '\u663e\u7136\u5f0f(8,6)\u662f\u4e00\u4e2a\u52a0\u6cd5\u6a21\u578b.')\n print('\u5728\u7ed9\u5b9a\u8bad\u7ec3\u6570\u636e\u53ca\u635f\u5931\u51fd\u6570L(y,f(x))\u7684\u6761\u4ef6\u4e0b,\u5b66\u4e60\u52a0\u6cd5\u6a21\u578bf(x)\u6210\u4e3a\u7ecf\u9a8c\u98ce\u9669\u6781\u5c0f\u5316\u5373\u635f\u5931\u51fd\u6570\u6781\u5c0f\u5316\u95ee\u9898\uff1a',\n 'min \u2211L(yi,\u2211bmb(xi;ym))')\n print('\u901a\u5e38\u8fd9\u662f\u4e00\u4e2a\u590d\u6742\u7684\u4f18\u5316\u95ee\u9898.\u524d\u5411\u5206\u5e03\u7b97\u6cd5(forward stagewise algorithm)\u6c42\u89e3',\n '\u8fd9\u4e00\u4f18\u5316\u95ee\u9898\u7684\u60f3\u6cd5\u662f:\u56e0\u4e3a\u5b66\u4e60\u7684\u662f\u52a0\u6cd5\u6a21\u578b,\u5982\u679c\u80fd\u591f\u4ece\u524d\u5411\u540e,\u6bcf\u4e00\u6b65\u53ea\u5b66\u4e60\u4e00\u4e2a\u57fa\u51fd\u6570\u53ca\u5176\u7cfb\u6570,',\n '\u9010\u6b65\u903c\u8fd1\u4f18\u5316\u76ee\u6807\u51fd\u6570\u5f0f,\u90a3\u4e48\u5c31\u53ef\u4ee5\u7b80\u5316\u4f18\u5316\u7684\u590d\u6742\u5ea6.\u5177\u4f53\u5730,\u6bcf\u6b65\u53ea\u9700\u4f18\u5316\u7684\u590d\u6742\u5ea6.',\n '\u5177\u4f53\u5730,\u6bcf\u6b65\u53ea\u9700\u4f18\u5316\u5982\u4e0b\u635f\u5931\u51fd\u6570:min\u2211L(yi,bb(xi;y))')\n print('\u7ed9\u5b9a\u8bad\u7ec3\u6570\u636e\u96c6T={(x1,y1),(x2,y2),...,(xn,yn)},xi\u2208X\u2208R^n,',\n 'yi\u2208Y={-1,+1}.\u635f\u5931\u51fd\u6570L(y,f(x));\u57fa\u51fd\u6570\u96c6{b(x;y)};')\n print('\u8f93\u51fa\uff1a\u52a0\u6cd5\u6a21\u578bf(x).')\n print('(1) \u521d\u59cb\u5316f0(x)=0')\n print('(2) \u5bf9m=1,2,...,M')\n print(' (a) \u6781\u5c0f\u5316\u635f\u5931\u51fd\u6570(bm,ym)=argmin\u2211L(yi,f(m-1)(xi)+bb(xi;y))',\n '\u5f97\u5230\u53c2\u6570bm,ym')\n print(' (b) \u66f4\u65b0fm(x)=f(m-1)(x)+bmb(x;ym)')\n print('(3) \u5f97\u5230\u52a0\u6cd5\u6a21\u578b:f(x)=fM(x)=\u2211bmb(x;ym)')\n print('\u8fd9\u6837,\u524d\u5411\u5206\u5e03\u7b97\u6cd5\u5c06\u540c\u65f6\u6c42\u89e3\u4ecem=1\u5230M\u6240\u6709\u53c2\u6570bm,ym\u7684\u4f18\u5316\u95ee\u9898.')\n print('8.3.2 \u524d\u5411\u5206\u5e03\u7b97\u6cd5\u4e0eAdaBoost')\n print('\u5b9a\u74068.3 AdaBoost\u7b97\u6cd5\u662f\u524d\u5411\u5206\u5e03\u52a0\u6cd5\u7b97\u6cd5\u7684\u7279\u4f8b.\u8fd9\u65f6,\u6a21\u578b\u662f\u7531\u57fa\u672c\u5206\u7c7b\u5668\u7ec4\u6210\u7684\u52a0\u6cd5\u6a21\u578b,',\n '\u635f\u5931\u51fd\u6570\u662f\u6307\u6570\u51fd\u6570.')\n print('\u8bc1\u660e:\u524d\u5411\u5206\u5e03\u7b97\u6cd5\u5b66\u4e60\u7684\u662f\u52a0\u6cd5\u6a21\u578b,\u5f53\u57fa\u51fd\u6570\u4e3a\u57fa\u672c\u5206\u7c7b\u5668\u65f6,',\n '\u8be5\u52a0\u6cd5\u6a21\u578b\u7b49\u4ef7\u4e8eAdaBoost\u7684\u6700\u7ec8\u5206\u7c7b\u5668 f(x)=\u2211amGm(x)')\n print('\u7531\u57fa\u672c\u5206\u7c7b\u5668Gm(x)\u53ca\u5176\u7cfb\u6570am\u7ec4\u6210,m=1,2,...,M.\u524d\u5411\u5206\u5e03\u7b97\u6cd5\u9010\u4e00\u5b66\u4e60\u57fa\u51fd\u6570,',\n '\u8fd9\u4e00\u8fc7\u7a0b\u4e0eAdaBoost\u7b97\u6cd5\u9010\u4e00\u5b66\u4e60\u57fa\u672c\u5206\u7c7b\u5668\u7684\u8fc7\u7a0b\u4e00\u81f4.')\n print('\u524d\u5411\u5206\u5e03\u7b97\u6cd5\u7684\u635f\u5931\u51fd\u6570\u662f\u6307\u6570\u635f\u5931\u51fd\u6570L(y,f(x))=exp[-yf(x)]')\n print('8.4 \u63d0\u5347\u6811')\n print('\u63d0\u5347\u6811\u662f\u4ee5\u5206\u7c7b\u6811\u6216\u56de\u5f52\u6811\u4e3a\u57fa\u672c\u5206\u7c7b\u5668\u7684\u63d0\u5347\u65b9\u6cd5.',\n '\u63d0\u5347\u6811\u88ab\u8ba4\u4e3a\u662f\u7edf\u8ba1\u5b66\u4e60\u4e2d\u6027\u80fd\u6700\u597d\u7684\u65b9\u6cd5\u4e4b\u4e00')\n print('8.4.1 \u63d0\u5347\u6811\u6a21\u578b')\n print('\u63d0\u5347\u65b9\u6cd5\u5b9e\u9645\u91c7\u7528\u52a0\u6cd5\u6a21\u578b(\u5373\u57fa\u51fd\u6570\u7684\u7ebf\u6027\u7ec4\u5408)\u4e0e\u524d\u5411\u5206\u5e03\u7b97\u6cd5,',\n '\u4ee5\u51b3\u7b56\u6811\u4e3a\u57fa\u51fd\u6570\u7684\u63d0\u5347\u65b9\u6cd5\u79f0\u4e3a\u63d0\u5347\u6811(boosting tree).',\n '\u5bf9\u5206\u7c7b\u95ee\u9898\u51b3\u7b56\u6811\u662f\u4e8c\u53c9\u5206\u7c7b\u6811',\\\n '\u5bf9\u56de\u5f52\u95ee\u9898\u51b3\u7b56\u6811\u662f\u4e8c\u53c9\u56de\u5f52\u6811.')\n print('\u5728\u4f8b8.1\u4e2d\u770b\u5230\u7684\u57fa\u672c\u5206\u7c7b\u5668xv,\u53ef\u4ee5\u770b\u505a\u662f\u7531\u4e00\u4e2a\u6839\u7ed3\u70b9\u76f4\u63a5\u8fde\u63a5\u4e24\u4e2a\u53f6\u7ed3\u70b9\u7684\u7b80\u5355\u51b3\u7b56\u6811',\n '\u5373\u6240\u8c13\u7684\u51b3\u7b56\u6811\u6869.\u63d0\u5347\u6811\u6a21\u578b\u53ef\u4ee5\u8868\u793a\u4e3a\u51b3\u7b56\u6811\u7684\u52a0\u6cd5\u6a21\u578b:fM(x)=\u2211T(x;\u0398m)')\n print('\u5176\u4e2d,T(x;\u0398m)\u8868\u793a\u51b3\u7b56\u6811;\u0398m\u4e3a\u51b3\u7b56\u6811\u7684\u53c2\u6570;M\u4e3a\u6811\u7684\u4e2a\u6570.')\n print('8.4.2 \u63d0\u5347\u6811\u7b97\u6cd5')\n print('\u63d0\u5347\u6811\u7b97\u6cd5\u91c7\u7528\u524d\u5411\u5206\u6b65\u7b97\u6cd5.\u9996\u5148\u786e\u5b9a\u521d\u59cb\u63d0\u5347\u6811f0(x)=0,\u7b2cm\u6b65\u7684\u6a21\u578b\u662f\uff1a')\n print('fm(x)=fm-1(x)+T(x;\u0398m)')\n print('\u5176\u4e2d,fm-1(x)\u4e3a\u5f53\u524d\u6a21\u578b,\u901a\u8fc7\u7ecf\u9a8c\u98ce\u9669\u6781\u5c0f\u5316\u786e\u5b9a\u4e0b\u4e00\u68f5\u51b3\u7b56\u6811\u7684\u53c2\u6570\u0398m')\n print(' \u0398m=argmin\u2211L(yi,fm-1(xi)+T(xi;\u0398m))')\n print('\u7531\u4e8e\u6811\u7684\u7ebf\u6027\u7ec4\u5408\u53ef\u4ee5\u5f88\u597d\u5730\u62df\u5408\u6570\u636e,\u5373\u4f7f\u6570\u636e\u4e2d\u7684\u8f93\u5165\u4e0e\u8f93\u51fa\u4e4b\u95f4\u7684\u5173\u7cfb\u5f88\u590d\u6742\u4e5f\u662f\u5982\u6b64,',\n '\u6240\u4ee5\u63d0\u5347\u6811\u662f\u4e00\u4e2a\u9ad8\u529f\u80fd\u7684\u5b66\u4e60\u7b97\u6cd5.')\n print('\u9488\u5bf9\u4e0d\u540c\u95ee\u9898\u7684\u63d0\u5347\u6811\u5b66\u4e60\u7b97\u6cd5,\u5176\u4e3b\u8981\u533a\u522b\u5728\u4e8e\u4f7f\u7528\u7684\u635f\u5931\u51fd\u6570\u4e0d\u540c.',\n '\u5305\u62ec\u7528\u5e73\u65b9\u8bef\u5dee\u635f\u5931\u51fd\u6570\u7684\u56de\u5f52\u95ee\u9898,\u7528\u6307\u6570\u635f\u5931\u51fd\u6570\u7684\u5206\u7c7b\u95ee\u9898,',\n '\u4ee5\u53ca\u7528\u4e00\u822c\u635f\u5931\u51fd\u6570\u7684\u4e00\u822c\u51b3\u7b56\u95ee\u9898.')\n print('\u5bf9\u4e8e\u4e8c\u7c7b\u5206\u7c7b\u95ee\u9898,\u63d0\u5347\u6811\u7b97\u6cd5\u53ea\u9700\u5c06AdaBoost\u7b97\u6cd58.1\u4e2d\u7684\u57fa\u672c\u5206\u7c7b\u5668\u9650\u5236\u4e3a\u4e8c\u7c7b\u5206\u7c7b\u6811\u5373\u53ef,',\n '\u53ef\u4ee5\u8bf4\u8fd9\u65f6\u63d0\u5347\u6811\u7b97\u6cd5\u662fAdaBoost\u7b97\u6cd5\u7684\u7279\u6b8a\u60c5\u51b5.')\n print('\u5df2\u77e5\u4e00\u4e2a\u8bad\u7ec3\u6570\u636e\u96c6T={(x1,y1),(x2,y2),...,(xn,yn)},',\n 'xi\u2208X\u2208R^n,X\u4e3a\u8f93\u5165\u7a7a\u95f4,yi\u2208Y\u2208R,Y\u4e3a\u8f93\u5165\u7a7a\u95f4')\n print('\u5982\u679c\u5c06\u8f93\u5165\u7a7a\u95f4X\u5212\u5206\u4e3aJ\u4e2a\u4e92\u4e0d\u76f8\u4ea4\u7684\u533a\u57dfR1,R2,...,RJ,\u5e76\u4e14\u5728\u6bcf\u4e2a\u533a\u57df\u4e0a\u786e\u5b9a\u8f93\u51fa\u7684\u5e38\u91cfcj,',\n '\u90a3\u4e48\u6811\u53ef\u8868\u793a\u4e3aT(x;\u0398)=\u2211cjI(x\u2208Rj)')\n print('\u5176\u4e2d,\u53c2\u6570\u0398={(R1,c1),(R2,c2),...,(RJ,cJ)}\u8868\u793a\u6811\u7684\u533a\u57df\u5212\u5206\u548c\u5404\u533a\u57df\u4e0a\u7684\u5e38\u6570.',\n 'J\u662f\u56de\u5f52\u6811\u7684\u590d\u6742\u5ea6\u5373\u53f6\u7ed3\u70b9\u4e2a\u6570.')\n print('\u56de\u5f52\u95ee\u9898\u63d0\u5347\u6811\u4f7f\u7528\u4e00\u4e0b\u524d\u5411\u5206\u5e03\u7b97\u6cd5:')\n print(' f0(x)=0')\n print(' fm(x)=fm-1(x)+T(x;\u0398),m=1,2,...,M')\n print(' fM(x)=\u2211T(x;\u0398m)')\n print('\u5728\u524d\u5411\u5206\u5e03\u7b97\u6cd5\u7684\u7b2cm\u6b65,\u7ed9\u5b9a\u5f53\u524d\u6a21\u578bfm-1(x),\u9700\u6c42\u89e3')\n print(' \u0398m=argmin\u2211L(yi,fm-1(xi)+T(x;\u0398m))')\n print('\u5f97\u5230\u0398m,\u5373\u7b2cm\u68f5\u6811\u7684\u53c2\u6570.')\n print('\u5f53\u91c7\u7528\u5e73\u65b9\u8bef\u5dee\u635f\u5931\u51fd\u6570\u65f6,L(y,f(x))=(y-f(x))^2')\n print('\u5176\u635f\u5931\u53d8\u4e3a:')\n print('L(y,fm-1(x)+T(x;\u0398m))=[y-fm-1(x)-T(x;\u0398m)]^2=[r-T(x;\u0398m)]')\n print('\u8fd9\u91cc,r=y-fm-1(x)')\n print('\u662f\u5f53\u524d\u6a21\u578b\u62df\u5408\u6570\u636e\u7684\u6b8b\u5dee(residual).\u6240\u4ee5,\u5bf9\u56de\u5f52\u95ee\u9898\u7684\u63d0\u5347\u6811\u7b97\u6cd5\u6765\u8bf4,',\n '\u53ea\u9700\u7b80\u5355\u5730\u62df\u5408\u5f53\u524d\u6a21\u578b\u7684\u6b8b\u5dee.')\n print('\u7b97\u6cd58.3(\u56de\u5f52\u95ee\u9898\u7684\u63d0\u5347\u6811\u7b97\u6cd5)')\n print('\u8f93\u5165\uff1a\u8bad\u7ec3\u6570\u636e\u96c6T={(x1,y1),(x2,y2),...,(xn,yn)},xi\u2208\u2208R^n,yi\u2208Y\u2208R;')\n print('\u8f93\u51fa\uff1a\u63d0\u5347\u6811fM(x)')\n print('(1) \u521d\u59cb\u5316f0(x)=0')\n print('(2) \u5bf9m=1,2,...M)')\n print(' (a) \u8ba1\u7b97\u6b8b\u5dee rmi=yi-fm-1(xi),i=1,2,...,N')\n print(' (b) \u62df\u5408\u6b8b\u5deermi\u5b66\u4e60\u4e00\u4e2a\u56de\u5f52\u6811,\u5f97\u5230T(x;\u0398m)')\n print(' (c) \u66f4\u65b0fm(x)=fm-1(x)+T(x;\u0398m)')\n print('(3) \u5f97\u5230\u56de\u5f52\u95ee\u9898\u63d0\u5347\u6811fM(x)=\u2211T(x;\u0398m)')\n print('\u4f8b8.2 \u5982\u8868\u6240\u793a\u7684\u8bad\u7ec3\u6570\u636e,x\u7684\u53d6\u503c\u8303\u56f4\u4e3a\u533a\u95f4[0.5,10.5],',\n 'y\u7684\u53d6\u503c\u8303\u56f4\u4e3a\u533a\u95f4[5.0,10.0],\u5b66\u4e60\u8fd9\u4e2a\u56de\u5f52\u95ee\u9898\u7684\u63d0\u5347\u6811\u6a21\u578b,\u8003\u8651\u53ea\u7528\u6811\u6869\u4f5c\u4e3a\u57fa\u51fd\u6570.')\n print('\u89e3\uff1a\u6309\u7167\u7b97\u6cd58.3 \u7b2c1\u6b65\u6c42f1(x)\u5373\u56de\u5f52\u6811T1(x),\u9996\u5148\u6c42\u89e3\u4ee5\u4e0b\u4f18\u5316\u95ee\u9898:',\n 'R1={x|x<=s},R2={x|x>s}')\n print('\u5bb9\u6613\u6c42\u5f97\u5728R1,R2\u5185\u90e8\u4f7f\u5e73\u65b9\u635f\u5931\u8bef\u5dee\u8fbe\u5230\u6700\u5c0f\u503c\u7684c1,c2\u4e3a:')\n print(' c1=1/N1\u2211yi, c2=1/N2\u2211yi')\n print(' \u8fd9\u91ccN1,N2\u662fR1,R2\u7684\u6837\u672c\u70b9\u6570.')\n print('\u6c42\u8bad\u7ec3\u6570\u636e\u7684\u5207\u5206\u70b9.\u6839\u636e\u6240\u7ed9\u6570\u636e,\u8003\u8651\u5982\u4e0b\u5207\u5206\u70b9:',\n '1.5,2.5,3.5,4.5,5.5,6.5,7.5,8.5,9.5')\n print('\u5bf9\u5404\u5207\u5206\u70b9,\u4e0d\u96be\u6c42\u51fa\u76f8\u5e94\u7684R1,R2,c1,c2\u53ca')\n print(' m(s)=min\u2211(yi-ci)^2+min\u2211(yi-ci)^2')\n print('\u4f8b\u5982,\u5f53s=1.5\u65f6,R1={1},R2={2,3,...,10},c1=5.56,c2=7.50')\n print('m(s)=min\u2211(yi-ci)^2+min\u2211(yi-c2)^2=0+15.72=15.72')\n print('\u73b0\u5c06s\u53cam(s)\u7684\u8ba1\u7b97\u7ed3\u679c\u5217\u8868')\n print('\u7531\u8868\u53ef\u77e5,\u5f53s=6.5\u65f6m(s)\u8fbe\u5230\u6700\u5c0f\u503c,\u6b64\u65f6R1={1,2,...,6},R2={7,8,9,10},',\n 'c1=6.24,c2=8.91,\u6240\u4ee5\u56de\u5f52\u6811T1(x)\u4e3a\uff1aT1(x)=6.24, x<6.5; T1(x)=8.91, x>=6.5')\n print('\u7528f1(x)\u62df\u5408\u8bad\u7ec3\u6570\u636e\u7684\u5e73\u65b9\u635f\u5931\u8bef\u5dee:L(y,f1(x))=\u2211(yi-f1(xi))^2=1.93')\n print('\u7b2c2\u6b65\u6c42T2(x).\u65b9\u6cd5\u4e0e\u6c42T1(x)\u4e00\u6837,\u53ea\u662f\u62df\u5408\u7684\u6570\u636e\u662f\u8868\u7684\u6b8b\u5dee,\u53ef\u4ee5\u5f97\u5230:',\n 'T2(x)=-0.52, x<3.5; T2(x)=0.22, x>=3.5')\n print('f2(x)=f1(x)+T2(x),\u7528f2(x)\u62df\u5408\u8bad\u7ec3\u6570\u636e\u7684\u5e73\u65b9\u635f\u5931\u8bef\u5dee\u662f\uff1aL(y,f2(x))=\u2211(yi-f2(xi))^2=0.79')\n print('\u53ef\u4ee5\u7ee7\u7eed\u6c42\u5f97T3(x),T4(x),T5(x),T6(x)')\n print('f6(x)=f5(x)+T6(x)=T1(x)+...+T5(x)+T6(x)')\n print('\u7528f6(x)\u62df\u5408\u8bad\u7ec3\u6570\u636e\u7684\u5e73\u65b9\u635f\u5931\u8bef\u5dee\u662fL(y,f6(x))=\u2211(yi-f6(xi))^2=0.17')\n print('\u5047\u8bbe\u6b64\u65f6\u5df2\u6ee1\u8db3\u8bef\u5dee\u8981\u6c42,\u90a3\u4e48f(x)=f6(x)\u5373\u4e3a\u6240\u6c42\u63d0\u5347\u6811')\n print('8.4.3 \u68af\u5ea6\u63d0\u5347')\n print('\u63d0\u5347\u6811\u5229\u7528\u52a0\u6cd5\u6a21\u578b\u4e0e\u524d\u5411\u5206\u5e03\u7b97\u6cd5\u5b9e\u73b0\u5b66\u4e60\u7684\u4f18\u5316\u8fc7\u7a0b.\u5f53\u635f\u5931\u51fd\u6570\u662f\u5e73\u65b9\u635f\u5931\u548c\u6307\u6570\u635f\u5931\u51fd\u6570\u65f6,',\n '\u6bcf\u4e00\u6b65\u4f18\u5316\u90fd\u662f\u5f88\u7b80\u5355\u7684.\u4f46\u5bf9\u4e00\u822c\u635f\u5931\u51fd\u6570\u800c\u8a00,\u5f80\u5f80\u6bcf\u4e00\u6b65\u4f18\u5316\u5e76\u4e0d\u662f\u90a3\u4e48\u5bb9\u6613.',\n 'Freidman\u63d0\u51fa\u4e86\u68af\u5ea6\u63d0\u5347\u7b97\u6cd5.\u662f\u5229\u7528\u6700\u901f\u4e0b\u964d\u6cd5\u7684\u8fd1\u4f3c\u65b9\u6cd5,',\n '\u5176\u5173\u952e\u662f\u5229\u7528\u635f\u5931\u51fd\u6570\u7684\u8d1f\u68af\u5ea6\u5728\u5f53\u524d\u6a21\u578b\u7684\u503c-[dL(y,f(xi))/df(xi)]f(x)=fm-1(x)')\n print('\u4f5c\u4e3a\u56de\u5f52\u95ee\u9898\u63d0\u5347\u6811\u7b97\u6cd5\u4e2d\u7684\u6b8b\u5dee\u7684\u8fd1\u4f3c\u503c,\u62df\u5408\u4e00\u4e2a\u56de\u5f52\u6811')\n print('\u7b97\u6cd58.4(\u68af\u5ea6\u63d0\u5347\u7b97\u6cd5)')\n print('\u8f93\u5165:\u8bad\u7ec3\u6570\u636e\u96c6T={(x1,y1),(x2,y2),...,(xn,yn)},xi\u2208X\u2208R^n,yi\u2208Y\u2208R^n;',\n '\u635f\u5931\u51fd\u6570L(y,f(x))')\n print('\u8f93\u51fa:\u56de\u5f52\u6811f(x)')\n print('(1) \u521d\u59cb\u5316 f0(x)=argmin \u2211L(yi,c)')\n print('(2) \u5bf9m=1,2,...,M')\n print(' (a) \u5bf9i=1,2,...,N,\u8ba1\u7b97rmi=-[dL(y,f(xi))/df(xi)]f(x)=fm-1(x)')\n print(' (b) \u5bf9rmi\u62df\u5408\u4e00\u4e2a\u56de\u5f52\u6811,\u5f97\u5230\u7b2cm\u68f5\u6811\u7684')\n print(' (c) \u5bf9j=1,2,...,J,\u8ba1\u7b97 cmj=argmin\u2211L(yi,fm-1(xi)+c)')\n print(' (d) \u66f4\u65b0fm(x)=fm-1(x)+\u2211cmjI(x\u2208Rmj)')\n print('(3) \u5f97\u5230\u56de\u5f52\u6811 f(x)=fM(x)=\u2211\u2211cmjI(x\u2208Rmj)')\n print('\u7b97\u6cd5\u7b2c1\u6b65\u521d\u59cb\u5316,\u4f30\u8ba1\u4f7f\u635f\u5931\u51fd\u6570\u6781\u5c0f\u5316\u7684\u5e38\u6570\u503c,\u5b83\u662f\u53ea\u6709\u4e00\u4e2a\u6839\u7ed3\u70b9\u7684\u6811.',\n '\u7b2c2(a)\u6b65\u8ba1\u7b97\u635f\u5931\u51fd\u6570\u7684\u8d1f\u68af\u5ea6\u5728\u5f53\u524d\u6a21\u578b\u7684\u503c,\u5c06\u5b83\u4f5c\u4e3a\u6b8b\u5dee\u7684\u4f30\u8ba1.',\n '\u5bf9\u4e8e\u5e73\u65b9\u635f\u5931\u51fd\u6570,\u5c31\u662f\u901a\u5e38\u6240\u8bf4\u7684\u6b8b\u5dee;\u5bf9\u4e8e\u4e00\u822c\u635f\u5931\u51fd\u6570,\u5c31\u662f\u6b8b\u5dee\u7684\u8fd1\u4f3c\u503c.')\n print('\u7b2c2(b)\u6b65\u4f30\u8ba1\u56de\u5f52\u6811\u53f6\u7ed3\u70b9\u533a\u57df,\u4ee5\u62df\u5408\u6b8b\u5dee\u7684\u8fd1\u4f3c\u503c.\u7b2c2(c)\u6b65\u5229\u7528\u7ebf\u6027\u641c\u7d22\u4f30\u8ba1\u53f6\u7ed3\u70b9\u533a\u57df\u7684\u503c,',\n '\u4f7f\u635f\u5931\u51fd\u6570\u6781\u5c0f\u5316.\u7b2c2(d)\u6b65\u66f4\u65b0\u56de\u5f52\u6811.\u7b2c3\u6b65\u5f97\u5230\u8f93\u51fa\u7684\u6700\u7ec8\u6a21\u578bf(x)')\n print('\u672c\u7ae0\u6982\u8981')\n print('1.\u63d0\u5347\u65b9\u6cd5\u662f\u5c06\u5f31\u5b66\u4e60\u7b97\u6cd5\u63d0\u5347\u4e3a\u5f3a\u5b66\u4e60\u7b97\u6cd5\u7684\u7edf\u8ba1\u5b66\u4e60\u65b9\u6cd5.',\n '\u5728\u5206\u7c7b\u5b66\u4e60\u4e2d,\u63d0\u5347\u65b9\u6cd5\u901a\u8fc7\u53cd\u590d\u4fee\u6539\u8bad\u7ec3\u6570\u636e\u7684\u6743\u503c\u5206\u5e03,\u6784\u5efa\u4e00\u7cfb\u5217\u7684\u57fa\u672c\u5206\u7c7b\u5668(\u5f31\u5206\u7c7b\u5668)',\n '\u5e76\u5c06\u8fd9\u4e9b\u57fa\u672c\u5206\u7c7b\u5668\u7ebf\u6027\u7ec4\u5408,\u6784\u6210\u4e00\u4e2a\u5f3a\u5206\u7c7b\u5668.\u4ee3\u8868\u6027\u7684\u63d0\u5347\u65b9\u6cd5\u662fAdaBoost\u65b9\u6cd5')\n print('2.AdaBoostu\u7b97\u6cd5\u7684\u7279\u70b9\u662f\u901a\u8fc7\u8fed\u4ee3\u6bcf\u6b21\u5b66\u4e60\u7684\u4e00\u4e2a\u57fa\u672c\u5206\u7c7b\u5668.',\n '\u6bcf\u6b21\u8fed\u4ee3\u4e2d,\u63d0\u9ad8\u90a3\u4e9b\u88ab\u524d\u4e00\u8f6e\u5206\u7c7b\u5668\u9519\u8bef\u5206\u7c7b\u6570\u636e\u7684\u6743\u503c,',\n '\u800c\u964d\u4f4e\u90a3\u4e9b\u88ab\u6b63\u786e\u5206\u7c7b\u7684\u6570\u636e\u7684\u6743\u503c.\u6700\u540e,AdaBoost\u5c06\u57fa\u672c\u5206\u7c7b\u5668\u7684\u7ebf\u6027\u7ec4\u5408\u4f5c\u4e3a\u5f3a\u5206\u7c7b\u5668,',\n '\u5176\u4e2d\u7ed9\u5206\u7c7b\u8bef\u5dee\u7387\u5c0f\u7684\u57fa\u672c\u5206\u7c7b\u5668\u4ee5\u5927\u7684\u6743\u503c,\u7ed9\u5206\u7c7b\u8bef\u5dee\u7387\u5927\u7684\u57fa\u672c\u5206\u7c7b\u5668\u4ee5\u5c0f\u7684\u6743\u503c.')\n print('3.AdaBoost\u7684\u8bad\u7ec3\u8bef\u5dee\u5206\u6790\u8868\u660e,AdaBoost\u7684\u6bcf\u6b21\u8fed\u4ee3\u53ef\u4ee5\u51cf\u5c11\u5b83\u5728\u8bad\u7ec3\u6570\u636e\u96c6\u4e0a\u7684\u5206\u7c7b\u8bef\u5dee\u7387,',\n '\u8fd9\u8bf4\u660e\u4e86\u5b83\u4f5c\u4e3a\u63d0\u5347\u65b9\u6cd5\u7684\u6709\u6548\u6027.')\n print('4.AdaBoost\u7b97\u6cd5\u7684\u4e00\u4e2a\u89e3\u91ca\u662f\u8be5\u7b97\u6cd5\u5b9e\u9645\u662f\u524d\u5411\u5206\u5e03\u7b97\u6cd5\u7684\u4e00\u4e2a\u5b9e\u73b0.',\n '\u5728\u8fd9\u4e2a\u65b9\u6cd5\u91cc,\u6a21\u578b\u662f\u52a0\u6cd5\u6a21\u578b,\u635f\u5931\u51fd\u6570\u662f\u6307\u6570\u635f\u5931,\u7b97\u6cd5\u662f\u524d\u5411\u5206\u5e03\u7b97\u6cd5.',\n '\u6bcf\u4e00\u6b65\u4e2d\u6781\u5c0f\u5316\u635f\u5931\u51fd\u6570(bm,ym)=argmin\u2211L(yi,fm-1(xi)+bmb(xi;y))',\n '\u5f97\u5230\u53c2\u6570bm,ym')\n print('5.\u63d0\u5347\u6811\u662f\u4ee5\u5206\u7c7b\u6811\u6216\u56de\u5f52\u6811\u4e3a\u57fa\u672c\u5206\u7c7b\u5668\u7684\u63d0\u5347\u65b9\u6cd5.\u63d0\u5347\u6811\u88ab\u8ba4\u4e3a\u662f\u7edf\u8ba1\u5b66\u4e60\u4e2d\u6700\u6709\u6548\u7684\u65b9\u6cd5\u4e4b\u4e00.')\n print('\u51b3\u7b56\u6811\u3001SVM\u3001AdaBoost\u7684\u6bd4\u8f83')\n print('\u51b3\u7b56\u6811')\n print(' \u771f\u5b9e\u5e94\u7528\u573a\u666f\uff1a\u91d1\u878d\u65b9\u9762\u4f7f\u7528\u51b3\u7b56\u6811\u5efa\u6a21\u5206\u6790\uff0c\u7528\u4e8e\u8bc4\u4f30\u7528\u6237\u7684\u4fe1\u7528\uff0c\u7535\u5546\u63a8\u8350\u7cfb\u7edf')\n print(' \u4f18\u52bf\uff1a\u6613\u4e8e\u5b9e\u73b0\u548c\u7406\u89e3\uff0c\u6570\u636e\u51c6\u5907\u5de5\u4f5c\u7b80\u5355\uff0c\u540c\u65f6\u5904\u7406\u591a\u79cd\u6570\u636e\u7c7b\u578b\uff0c\u901a\u8fc7\u9759\u6001\u6d4b\u8bd5\u6765\u5bf9\u6a21\u578b\u8868\u73b0\u8fdb\u884c\u8bc4\u4ef7;',\n '\u53ef\u4ee5\u5728\u8f83\u77ed\u65f6\u95f4\u5185\u5bf9\u5927\u91cf\u6570\u636e\u505a\u51fa\u975e\u5e38\u597d\u7684\u7ed3\u679c,\u51b3\u7b56\u6811\u53ef\u4ee5\u5f88\u597d\u5730\u6269\u5c55\u5230\u5927\u578b\u6570\u636e\u4e2d,',\n '\u540c\u65f6\u51b3\u7b56\u6811\u7684\u5927\u5c0f\u72ec\u7acb\u4e8e\u6570\u636e\u5e93\u7684\u5927\u5c0f.\u8ba1\u7b97\u590d\u6742\u5ea6\u4f4e,\u7ed3\u679c\u6613\u4e8e\u7406\u89e3,\u5bf9\u90e8\u5206\u6570\u636e\u635f\u5931\u4e0d\u654f\u611f.')\n print(' \u8868\u73b0\u6700\u597d\u7684\u60c5\u51b5:\u5b9e\u4f8b\u662f\u7531\u201c\u5c5e\u6027-\u503c\u201d\u5bf9\u8868\u793a\u7684;\u76ee\u6807\u51fd\u6570\u5177\u6709\u79bb\u6563\u7684\u8f93\u51fa\u503c;\u8bad\u7ec3\u6570\u636e\u96c6\u5305\u542b\u5206\u5e03\u9519\u8bef',\n '(\u51b3\u7b56\u6811\u5bf9\u9519\u8bef\u6709\u9002\u5e94\u6027),\u8bad\u7ec3\u6570\u636e\u7f3a\u5c11\u5c11\u91cf\u5c5e\u6027\u7684\u5b9e\u4f8b')\n print(' \u7f3a\u70b9:\u6613\u4e8e\u51fa\u73b0\u8fc7\u62df\u5408\u95ee\u9898;\u5ffd\u7565\u4e86\u6570\u636e\u96c6\u4e2d\u5c5e\u6027\u4e4b\u95f4\u7684\u76f8\u5173\u6027;',\n '\u5bf9\u4e8e\u7c7b\u6bd4\u4e0d\u4e00\u81f4\u7684\u6837\u672c,\u51b3\u7b56\u6811\u7684\u4fe1\u606f\u589e\u76ca\u503e\u5411\u4e8e\u90a3\u4e9b\u6570\u636e\u503c\u8f83\u591a\u7684\u7279\u5f81;')\n print(' \u4ec0\u4e48\u6761\u4ef6\u8868\u73b0\u5f88\u5dee:\u51b3\u7b56\u6811\u5339\u914d\u6570\u636e\u8fc7\u591a\u65f6,\u5206\u7c7b\u7684\u7c7b\u522b\u8fc7\u4e8e\u590d\u6742;\u6570\u636e\u7684\u6811\u5f62\u4e4b\u95f4\u5177\u6709\u975e\u5e38\u5f3a\u7684\u5173\u8054')\n print(' \u6a21\u578b\u9002\u5e94\u95ee\u9898:\u4e0d\u9700\u8981\u51c6\u5907\u592a\u591a\u7684\u8bad\u7ec3\u6570\u636e,\u4e0d\u9700\u8981\u5bf9\u6570\u636e\u8fc7\u591a\u7684\u5904\u7406\u5982\u5220\u9664\u7a7a\u767d',\n '\u8be5\u95ee\u9898\u662f\u975e\u7ebf\u6027\u95ee\u9898,\u51b3\u7b56\u6811\u80fd\u591f\u5f88\u597d\u5730\u89e3\u51b3\u975e\u7ebf\u6027\u95ee\u9898.\u7b97\u6cd5\u7684\u6267\u884c\u6548\u7387\u9ad8,\u5bf9\u673a\u5668\u7684\u8981\u6c42\u5c0f')\n print('\u652f\u6301\u5411\u91cf\u673aSVM')\n print(' \u771f\u5b9e\u5e94\u7528\u573a\u666f\uff1a\u6587\u672c\u548c\u8d85\u6587\u672c\u7684\u5206\u7c7b,\u7528\u4e8e\u56fe\u50cf\u5206\u7c7b,\u7528\u4e8e\u624b\u5199\u4f53\u8bc6\u522b')\n print(' \u4f18\u52bf\uff1a\u5206\u7c7b\u6548\u679c\u597d;\u53ef\u4ee5\u6709\u6548\u5730\u5904\u7406\u9ad8\u7ef4\u7a7a\u95f4\u7684\u6570\u636e,\u53ef\u4ee5\u6709\u6548\u5730\u5904\u7406\u53d8\u91cf\u4e2a\u6570\u5927\u4e8e\u6837\u672c\u4e2a\u6570\u7684\u6570\u636e',\n '\u53ea\u662f\u4f7f\u7528\u4e86\u4e00\u90e8\u5206\u5b50\u96c6\u6765\u8fdb\u884c\u8bad\u7ec3\u6a21\u578b,\u6240\u4ee5SVM\u6a21\u578b\u4e0d\u9700\u8981\u592a\u5927\u7684\u5185\u5b58;',\n '\u53ef\u4ee5\u63d0\u9ad8\u6cdb\u5316\u80fd\u529b,\u65e0\u5c40\u90e8\u6781\u5c0f\u503c\u95ee\u9898.')\n print(' \u8868\u73b0\u6700\u597d\u7684\u60c5\u51b5:\u6570\u636e\u7684\u7ef4\u5ea6\u8f83\u9ad8,\u9700\u8981\u6a21\u578b\u5177\u6709\u975e\u5e38\u5f3a\u7684\u6cdb\u5316\u80fd\u529b;\u6837\u672c\u6570\u636e\u91cf\u8f83\u5c0f\u65f6',\n '\u89e3\u51b3\u975e\u7ebf\u6027\u95ee\u9898')\n print(' \u7f3a\u70b9:\u65e0\u6cd5\u5904\u7406\u5927\u89c4\u6a21\u7684\u6570\u636e\u96c6,\u7b97\u6cd5\u9700\u8981\u7684\u65f6\u95f4\u8f83\u957f\u7684\u8bad\u7ec3\u65f6\u95f4.',\n '\u65e0\u6cd5\u6709\u6548\u5730\u5904\u7406\u5305\u542b\u566a\u58f0\u592a\u591a\u7684\u6570\u636e\u96c6;SVM\u6a21\u578b\u6ca1\u6709\u76f4\u63a5\u7ed9\u51fa\u6982\u7387\u7684\u4f30\u8ba1\u503c,\u800c\u662f\u5229\u7528\u4ea4\u53c9\u9a8c\u8bc1\u7684\u65b9\u5f0f\u4f30\u8ba1,',\n '\u8fd9\u79cd\u65b9\u5f0f\u8017\u65f6\u8f83\u957f;\u5bf9\u7f3a\u5931\u6570\u636e\u654f\u611f;\u5bf9\u4e8e\u975e\u7ebf\u6027\u95ee\u9898,\u6709\u65f6\u5f88\u96be\u627e\u5230\u4e00\u4e2a\u5408\u9002\u7684\u6838\u51fd\u6570')\n print(' \u4ec0\u4e48\u6761\u4ef6\u8868\u73b0\u5f88\u5dee:\u6570\u636e\u96c6\u7684\u6570\u636e\u91cf\u8fc7\u5927;\u6570\u636e\u96c6\u4e2d\u542b\u6709\u566a\u58f0;\u6570\u636e\u96c6\u4e2d\u7684\u7f3a\u5931\u8f83\u591a\u7684\u6570\u636e;',\n '\u5bf9\u7b97\u6cd5\u7684\u8bad\u7ec3\u6548\u7387\u8981\u6c42\u8f83\u9ad8.')\n print(' \u6a21\u578b\u9002\u5e94\u95ee\u9898:\u8be5\u9879\u76ee\u6240\u63d0\u4f9b\u7684\u6837\u672c\u6570\u636e\u76f8\u5bf9\u8f83\u5c11;\u8be5\u95ee\u9898\u662f\u5c5e\u4e8e\u975e\u7ebf\u6027\u95ee\u9898;\u6570\u636e\u96c6\u7ecf\u8fc7\u201c\u8bfb\u70ed\u7f16\u7801\u201d\u540e,\u7ef4\u5ea6\u8f83\u9ad8')\n print('\u9002\u5e94\u63d0\u5347\u65b9\u6cd5AdaBoost')\n print(' \u771f\u5b9e\u5e94\u7528\u573a\u666f\uff1a\u4e8c\u5206\u7c7b\u6216\u591a\u5206\u7c7b\u95ee\u9898,\u7528\u4e8e\u7279\u5f81\u9009\u62e9,\u591a\u6807\u7b7e\u95ee\u9898,\u56de\u5f52\u95ee\u9898.')\n print(' \u4f18\u52bf\uff1aAdaBoost\u662f\u4e00\u79cd\u7cbe\u5ea6\u975e\u5e38\u9ad8\u7684\u5206\u7c7b\u5668,\u53ef\u4ee5\u4e0e\u5404\u79cd\u65b9\u6cd5\u6784\u5efa\u5b50\u5206\u7c7b\u5668,Adaboost\u7b97\u6cd5\u63d0\u4f9b\u4e00\u79cd\u8ba1\u7b97\u6846\u67b6;',\n '\u5f31\u5206\u7c7b\u5668\u7684\u6784\u9020\u65b9\u6cd5\u6bd4\u8f83\u7b80\u5355;\u7b97\u6cd5\u6613\u4e8e\u7406\u89e3,\u4e0d\u7528\u505a\u7279\u5f81\u7b5b\u9009,\u4e0d\u6613\u53d1\u751f\u8fc7\u62df\u5408.\u6613\u4e8e\u7f16\u7801')\n print(' \u8868\u73b0\u6700\u597d\u7684\u60c5\u51b5:\u7528\u4e8e\u89e3\u51b3\u4e8c\u5206\u7c7b\u95ee\u9898,\u89e3\u51b3\u5927\u7c7b\u5355\u6807\u7b7e\u95ee\u9898;\u5904\u7406\u591a\u7c7b\u5355\u6807\u7b7e\u95ee\u9898;\u5904\u7406\u56de\u5f52\u76f8\u5173\u7684\u95ee\u9898.')\n print(' \u7f3a\u70b9:AdaBoost\u7b97\u6cd5\u7684\u8fed\u4ee3\u6b21\u6570\u4e0d\u597d\u8bbe\u5b9a,\u9700\u8981\u4f7f\u7528\u4ea4\u53c9\u9a8c\u8bc1\u7684\u65b9\u5f0f\u6765\u8fdb\u884c\u786e\u5b9a;',\n '\u6570\u636e\u96c6\u7684\u4e0d\u5e73\u8861\u5206\u5e03\u5bfc\u81f4\u5206\u7c7b\u5668\u7684\u5206\u7c7b\u7cbe\u5ea6\u4e0b\u964d;\u8bad\u7ec3\u6bd4\u8f83\u8017\u8d39\u65f6\u95f4;\u5bf9\u5f02\u5e38\u503c\u6bd4\u8f83\u654f\u611f.')\n print(' \u4ec0\u4e48\u6761\u4ef6\u8868\u73b0\u5f88\u5dee:\u6570\u636e\u96c6\u5206\u5e03\u975e\u5e38\u4e0d\u5747\u5300,\u6570\u636e\u96c6\u4e2d\u542b\u6709\u8f83\u591a\u7684\u5f02\u5e38\u503c,\u5bf9\u7b97\u6cd5\u7684\u8bad\u7ec3\u7684\u6548\u7387\u8981\u6c42\u6bd4\u8f83\u9ad8')\n print(' \u6a21\u578b\u9002\u5e94\u95ee\u9898:\u8be5\u6570\u636e\u96c6\u53ef\u4ee5\u5f52\u5c5e\u4e3a\u591a\u6807\u7b7e\u5206\u7c7b\u95ee\u9898;\u6570\u636e\u96c6\u4e2d\u5f02\u5e38\u503c\u8f83\u5c11;',\n '\u5bf9\u7b97\u6cd5\u6a21\u578b\u7684\u51c6\u786e\u7387\u8981\u6c42\u8f83\u9ad8.') \n\nchapter8 = Chapter8()\n\ndef main():\n chapter8.note()\n\nif __name__ == '__main__':\n main()"} {"doc_id": "37c803eafa5b97c0de535fcaa8d5f6ae", "text": "\"\"\"\r\nCounting elements in a collection with a specific value\r\n-------------------------------------------------------\r\nInput: (object) Any type of input object: list, tuple, string\r\n (value) The value to search for.\r\n Any type: list, tuple, string, number,\r\n\r\nReturn: (int) number of items\r\n\"\"\"\r\n\r\n# Numbers in a list\r\nnumbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 8, 9, 8, 0]\r\nsearch_value = 9\r\nreturnvalue = numbers.count(search_value)\r\nprint('\\nNumbers: {}\\nSearch value: {}\\nCount: {}'\r\n .format(numbers, search_value, returnvalue))\r\n\r\n# Cars in a list\r\ncars = [\"Audi\", \"BMW\", \"Chrysler\", \"Dodge\", \"Ford\", \"Ford\"]\r\nsearch_value = 'Ford'\r\nreturnvalue = cars.count(search_value)\r\nprint('\\nCars: {}\\nSearch value: {}\\nCount: {}'\r\n .format(cars, search_value, returnvalue))\r\n\r\n# Sentence\r\nsentence = 'This is an \"I\" letter.'\r\nsearch_value = 'i'\r\nreturnvalue = sentence.count(search_value)\r\nprint('\\nSentence: {}\\nSearch value: {}\\nCount: {}'\r\n .format(sentence, search_value, returnvalue))\r\n\r\n# Sentence\r\nsentence = 'This is an \"I\" letter.'\r\nsentence = sentence.lower()\r\nsearch_value = 'i'\r\nreturnvalue = sentence.count(search_value)\r\nprint('\\nSentence: {}\\nSearch value: {}\\nCount: {}'\r\n .format(sentence, search_value, returnvalue))\r\n\r\n# Sentence\r\nsentence = 'This is an \"I\" letter.'\r\nsearch_value = 'is'\r\nreturnvalue = sentence.count(search_value)\r\nprint('\\nSentence: {}\\nSearch value: {}\\nCount: {}'\r\n .format(sentence, search_value, returnvalue))\r\n\r\n# Sentence\r\nsentence = 'This is an \"I\" letter.'\r\nsearch_value = 'an'\r\nreturnvalue = sentence.count(search_value)\r\nprint('\\nSentence: {}\\nSearch value: {}\\nCount: {}'\r\n .format(sentence, search_value, returnvalue))"} {"doc_id": "37d489aad2f79e04d0c05feecf402526", "text": "# --------------\n# Loan Status\r\n# Loan Status\r\n# Let's start with the simple task of visualizing the company's record with respect to loan approvals.\r\n\r\n#Importing header files\r\nimport pandas as pd\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\n# The path to the dataset has been stored in a variable path\r\n# Load the dataframe using pd.read_csv() and store the dataframe in a variable called data.\r\n\r\ndata = pd.read_csv(path)\r\nprint(data)\r\n\r\n\r\n\r\n# Save the value counts of Loan_Status in a variable called loan_status using value_counts()\r\n\r\nloan_status = data[\"Loan_Status\"].value_counts()\r\nprint(loan_status)\r\n\r\n\r\n# Plot a bar graph of loan_status\r\n\r\nloan_status.plot(kind= \"bar\" , figsize=(10,10))\r\n\r\nplt.title('visualizing the companys record with respect to loan approvals')\r\n\r\nplt.xlabel('Loan Status of approval')\r\n\r\nplt.ylabel('VALUES')\r\n\r\nplt.show()\r\n\r\n\r\n\r\n\r\n#Code starts here\n\n\n# --------------\n# Everyone needs money\r\n# Everyone needs money\r\n# The company provides financial assistance across the different regions of the country. One interesting statistic that stakeholders want to see is the loan approval distribution across the regions.\r\n\r\n\r\n#Code starts here\r\n\r\n# Group the 'data' dataframe by Property_Area and Loan_Status and store it in a variable called 'property_and_loan'\r\n\r\nproperty_and_loan = data.groupby([\"Property_Area\" , \"Loan_Status\"]).size().unstack()\r\n\r\nprint(property_and_loan)\r\n\r\n\r\n# Use the .size() method on 'property_and_loan' and then use .unstack() and save it back to 'property_and_loan'\r\n\r\nproperty_and_loan = data.groupby([\"Property_Area\" , \"Loan_Status\"]).size().unstack()\r\n\r\nprint(property_and_loan)\r\n\r\n\r\n# Plot an unstacked bar plot of property_and_loan (It is similar to creating a stacked bar plot except change the parameter 'stacked' to False)\r\n\r\nproperty_and_loan.plot(kind=\"bar\" , stacked = False , figsize=(20,20))\r\n\r\nplt.xlabel(\"Property Area\")\r\n\r\nplt.ylabel(\"Loan Status\")\r\n\r\nplt.xticks(rotation=45)\r\n\r\nplt.show()\r\n\r\n\r\n\r\n\n\n\n# --------------\n# Expensive Education\r\n# Expensive Education\r\n# Higher education has always been an expensive endeavour for people but it results in better career opportunities and stability in life. But does higher education result in a better guarantee in issuing loans?\r\n\r\n\r\n#Code starts here\r\n\r\n# Group the 'data' dataframe by Education and Loan_Status and store it in a variable called 'education_and_loan'\r\n\r\neducation_and_loan = data.groupby([\"Education\" , \"Loan_Status\"])\r\n\r\nprint(education_and_loan)\r\n\r\n\r\n\r\n# Use the .size() method on 'education_and_loan' and then use .unstack() and save it back to 'education_and_loan'\r\n\r\n\r\neducation_and_loan = data.groupby([\"Education\" , \"Loan_Status\"]).size().unstack()\r\n\r\nprint(education_and_loan)\r\n\r\n\r\n# Plot an stacked bar plot of education_and_loan\r\n\r\neducation_and_loan.plot(kind=\"bar\" , figsize=(20,20))\r\n\r\n\r\n\r\n# Name the x-axis as Education Status\r\n\r\nplt.xlabel(\"Education Status\")\r\n\r\n\r\n# Name the y-axis as Loan Status\r\n\r\nplt.ylabel(\"Loan Status\")\r\n\r\n\r\n# Rotate the labels of x-axis by 45o\r\n\r\nplt.xticks(rotation=45)\r\n\r\n\r\n\r\nplt.show()\r\n\r\n\r\n\n\n\n# --------------\n# Smarter and Richer?\r\n# Smarter and Richer?\r\n# After seeing the loan status distribution, let's check whether being graduate or not also leads to different loan amount distribution by plotting an overlapping density plot of two values\r\n\r\n#Code starts here\r\n\r\n\r\n# Create a dataframe called 'graduate' which is a subset of 'data' dataframe with the condition \"data['Education'] == 'Graduate'\"\r\n\r\ngraduate = pd.DataFrame(data[data[\"Education\"]==\"Graduate\"])\r\nprint(graduate)\r\n\r\n#graduate=data[data['Education']=='Graduate']\r\n#print(graduate)\r\n\r\n\r\n# Create a dataframe called 'not_graduate' which is a subset of 'data' dataframe with the condition \"data['Education'] == 'Not Graduate'\"\r\n\r\nnot_graduate = pd.DataFrame(data[data[\"Education\"]==\"Not Graduate\"])\r\nprint(not_graduate)\r\n\r\n\r\n\r\n\r\n\r\n# Plot a density plot LoanAmount of 'graduate' dataframe using \"Series.plot()\" and pass the parameter kind='density' and label='Graduate'\r\n\r\ngraduate[\"LoanAmount\"].plot(kind=\"density\" , label=\"Graduate\" , figsize=(20,20))\r\n\r\n\r\n# Do the same for LoanAmount of 'not_graduate' dataframe but with label='Not Graduate'\r\n\r\n\r\nnot_graduate[\"LoanAmount\"].plot(kind=\"density\" , label=\"Not_graduate\" , figsize=(20,20))\r\n\r\n\r\n\r\n\r\n#Code ends here\r\n\r\n#For automatic legend display\r\nplt.legend()\n\n\n# --------------\n# Income vs Loan\r\n# Income vs Loan\r\n# For any financial institution to be successful in its loan lending system, there has to be a correlation between the borrower's income and loan amount he is lent. Let's see how our company fares in that respect:\r\n\r\n#Code starts here\r\n\r\n# Create three subplots with (nrows = 3 , ncols = 1) and store it in variable's fig ,(ax_1,ax_2,ax_3)\r\n\r\nfig ,(ax_1,ax_2,ax_3) = plt.subplots(nrows = 3 , ncols = 1)\r\n\r\n\r\n# Since both are continuous variables, plot scatter plot between 'ApplicantIncome' and LoanAmount using ax_1. Set axis title as Applicant Income\r\n\r\n\r\nax_1.scatter(data[\"CoapplicantIncome\"] , data[\"LoanAmount\"])\r\n\r\nax_1.set(title=\"Applicant Income\")\r\n\r\n\r\n# Plot scatter plot between 'CoapplicantIncome' and LoanAmount using ax_2. Set axis title as Coapplicant Income\r\n\r\n\r\nax_2.scatter(data[\"CoapplicantIncome\"] , data[\"LoanAmount\"])\r\n\r\nax_2.set(title=\"Coapplicant Income\")\r\n\r\n\r\n\r\n\r\n# Create a new column in the dataframe called 'TotalIncome' which is a sum of the values of columns ApplicantIncome and CoapplicantIncome\r\n\r\n\r\ndata[\"TotalIncome\"] = data[\"ApplicantIncome\"] + data[\"CoapplicantIncome\"]\r\n\r\n\r\n\r\n\r\n# Plot scatter plot between 'TotalIncome' and LoanAmount using ax_3. Set axis title as Total Income\r\n\r\nax_3.scatter(data[\"TotalIncome\"] , data[\"LoanAmount\"])\r\n\r\nax_3.set(title=\"Total Income\")\r\n\n\n\n"} {"doc_id": "37e01002cfe6fc2b7d556af568173d1b", "text": "def arth(a, b):\n if (b == 0):\n return a\n return arth(b, a % b)\n\ndef main():\n print(\"Welcome to Euclidean algorithm solver!\")\n print(\"=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\")\n \n width = int(input(\"Please insert the width: \"))\n height = int(input(\"Please insert the height: \"))\n \n result = arth(width, height)\n print(\"We've got the results for the perfect square!\")\n print(\"Width: {width}\".format(width = result))\n print(\"Height: {height}\".format(height = result))\n \nif __name__ == \"__main__\":\n main()\n"} {"doc_id": "381710d5d111231b3d7cc10a86854519", "text": "\"\"\"\nFile: anagram.py\nName: Pei-Feng (Kevin) Ma\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\n# Global variables\ndict_lst = [] # this list stores all the words in the dictionary.\n#found_anagrams_lst = [] # this list stores all the anagrams that we found.\n\n\ndef main():\n \"\"\"\n This program allows user input words and it will find all the\n anagrams of it.\n \"\"\"\n\n read_dictionary(FILE)\n\n print('Welcome to stanCode \"Anagram Generator\" (or -1 to quit)')\n s = input('Find anagrams for: ')\n if s != EXIT:\n print('searching...')\n find_anagrams(s)\n while True:\n s = input('Find anagrams for: ')\n if s != EXIT:\n print('searching...')\n find_anagrams(s)\n else:\n break\n\n\ndef read_dictionary(filename):\n \"\"\"\n This function will read the dictionary file and store it in a\n list called dict_lst as a list data type.\n :param filename: a text file that contains dictionary\n \"\"\"\n global dict_lst\n with open(filename, 'r') as f:\n for line in f:\n dict_lst += line.split()\n\n\ndef find_anagrams(s):\n \"\"\"\n This function will call a helper function to find anagrams recursively.\n :param s: str, the word that user inputs.\n \"\"\"\n find_anagrams_helper(s, '', [], [])\n\n\ndef find_anagrams_helper(s, current_word, found_index, found_anagrams_lst):\n \"\"\"\n This function will find all the anagrams recursively and print it our at the\n console.\n :param found_anagrams_lst:\n :param s: string, the word that user inputs.\n :param current_word: string, a string that stores current word searching in current layer.\n :param found_index: list, a list that we been search in current and previous layer.\n \"\"\"\n # Base Case. If the length of current word == len(s), check if it is the word exist in dictionary.\n if len(s) == len(current_word):\n if current_word in dict_lst and current_word not in found_anagrams_lst:\n found_anagrams_lst.append(current_word)\n print(current_word)\n print('searching...')\n else:\n print(f'{len(found_anagrams_lst)} anagrams: {found_anagrams_lst}')\n return\n # Recursive case\n else:\n if not has_prefix(current_word):\n return\n for i in range(len(s)):\n if i in found_index:\n continue\n else:\n found_index.append(i)\n find_anagrams_helper(s, current_word + s[i], found_index, found_anagrams_lst)\n found_index.pop()\n\n\ndef has_prefix(sub_s):\n \"\"\"\n This function will search it a part of string matches with words in the dictionary.\n :param sub_s: str, a part of string which is the current word\n :return: boolean, tells if a sub string matches words in the dictionary.\n \"\"\"\n for word in dict_lst:\n if word.startswith(sub_s):\n return True\n return False\n\n\nif __name__ == '__main__':\n main()\n"} {"doc_id": "38191c3ed6a5a7367b7674224cb5b5e1", "text": "\"\"\"\n[\n [\"00\",\"01\",\"02\",\"03\"],\n [\"10\",\"11\",\"12\",\"13\"],\n [\"20\",\"21\",\"22\",\"23\"],\n]\n\"\"\"\nclass Vector2:\n \"\"\"\n \u4e8c\u7ef4\u5411\u91cf\n \u53ef\u4ee5\u8868\u793a\u4f4d\u7f6e/\u65b9\u5411\n \"\"\"\n def __init__(self,x,y):\n self.x = x\n self.y = y\n\n # \u9759\u6001\u65b9\u6cd5\uff1a\u8868\u793a\u5de6\u8fb9\u65b9\u5411\n @staticmethod\n def left():\n return Vector2(0,-1)\n # \u9759\u6001\u65b9\u6cd5\uff1a\u8868\u793a\u53f3\u8fb9\u65b9\u5411\n @staticmethod\n def right():\n return Vector2(0,1)\n # \u9759\u6001\u65b9\u6cd5\uff1a\u8868\u793a\u4e0a\u8fb9\u65b9\u5411\n @staticmethod\n def up():\n return Vector2(-1, 0)\n # \u9759\u6001\u65b9\u6cd5\uff1a\u8868\u793a\u4e0a\u8fb9\u65b9\u5411\n @staticmethod\n def down():\n return Vector2(1, 0)\nclass DoubleListHelper:\n @staticmethod\n def get_elements(target, vect_pos, vect_dir, count):\n \"\"\"\n \u5728\u4e8c\u7ef4\u5217\u8868\u4e2d\u83b7\u53d6\u7684\u6307\u5b9a\u4f4d\u7f6e\uff0c\u6307\u5b9a\u65b9\u5411\u7684\uff0c\u6307\u5b9a\u6570\u91cf\u7684\u5143\u7d20\n :param target: \u4e8c\u7ef4\u5217\u8868\u4e2d\n :param vect_pos: \u6307\u5b9a\u4f4d\u7f6e\n :param vect_dir: \u6307\u5b9a\u65b9\u5411\n :param count: \u6307\u5b9a\u6570\u91cf\n :return:\n \"\"\"\n list_result = []\n for i in range(count):\n vect_pos.x += vect_dir.x\n vect_pos.y += vect_dir.y\n element = target[vect_pos.x][vect_pos.y]\n list_result.append(element)\n return list_result\n\n# --------------------\u6d4b\u8bd5\u4ee3\u7801------------------\nlist01 = [\n [\"00\",\"01\",\"02\",\"03\"],\n [\"10\",\"11\",\"12\",\"13\"],\n [\"20\",\"21\",\"22\",\"23\"],\n]\n# \u5728 \u4e8c\u7ef4\u5217\u8868\u4e2d\uff0c\u83b7\u53d613\u4f4d\u7f6e\uff0c\u5411\u5de6 \uff0c3\u4e2a\u5143\u7d20\nresult = DoubleListHelper.get_elements(list01,Vector2(1,3),Vector2.left(),3)\nfor item in result:\n print(item)\n# \u5728 \u4e8c\u7ef4\u5217\u8868\u4e2d\uff0c\u83b7\u53d622\u4f4d\u7f6e\uff0c\u5411\u4e0a \uff0c2\u4e2a\u5143\u7d20\nresult = DoubleListHelper.get_elements(list01,Vector2(2,2),Vector2.up(),2)\nfor item in result:\n print(item)\n# \u5728 \u4e8c\u7ef4\u5217\u8868\u4e2d\uff0c\u83b7\u53d603\u4f4d\u7f6e\uff0c\u5411\u4e0b \uff0c2\u4e2a\u5143\u7d20\nresult = DoubleListHelper.get_elements(list01,Vector2(0,3),Vector2.down(),2)\nfor item in result:\n print(item)"} {"doc_id": "38405a937932f94e54b67915264b9f81", "text": "\"\"\"\n

Given a list of positive integers, the adjacent integers will perform the float division. For example, [2,3,4] -> 2 / 3 / 4.

\n\n

However, 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\n

Example:
\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, 
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
\n

\n\n

Note:\n

    \n
  1. The length of the input array is [1, 10].
  2. \n
  3. Elements in the given array will be in range [2, 1000].
  4. \n
  5. There is only one optimal division for each test case.
  6. \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\n
    \n\t
  1. \u8f93\u5165\u6570\u7ec4\u7684\u957f\u5ea6\u5728 [1, 10] \u4e4b\u95f4\u3002
  2. \n\t
  3. \u6570\u7ec4\u4e2d\u6bcf\u4e2a\u5143\u7d20\u7684\u5927\u5c0f\u90fd\u5728 [2, 1000] \u4e4b\u95f4\u3002
  4. \n\t
  5. \u6bcf\u4e2a\u6d4b\u8bd5\u7528\u4f8b\u53ea\u6709\u4e00\u4e2a\u6700\u4f18\u9664\u6cd5\u89e3\u3002
  6. \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\n
    \n\t
  1. \u8f93\u5165\u6570\u7ec4\u7684\u957f\u5ea6\u5728 [1, 10] \u4e4b\u95f4\u3002
  2. \n\t
  3. \u6570\u7ec4\u4e2d\u6bcf\u4e2a\u5143\u7d20\u7684\u5927\u5c0f\u90fd\u5728 [2, 1000] \u4e4b\u95f4\u3002
  4. \n\t
  5. \u6bcf\u4e2a\u6d4b\u8bd5\u7528\u4f8b\u53ea\u6709\u4e00\u4e2a\u6700\u4f18\u9664\u6cd5\u89e3\u3002
  6. \n
\n\"\"\"\n\n\nclass Solution:\n def optimalDivision(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: str\n \"\"\"\n "} {"doc_id": "3844cbff5bea504aadf2db7d7e6ac744", "text": "\"\"\"\nFile: quadratic_solver.py\nName: Tao-Ke Chorng\n-----------------------\nThis program should implement a console program\nthat asks 3 inputs (a, b, and c)\nfrom users to compute the roots of equation\nax^2 + bx + c = 0\nOutput format should match what is shown in the sample\nrun in the Assignment 2 Handout.\n\n\"\"\"\n\nimport math\n\n\n\ndef main():\n\t\"\"\"\n\tThe program help user to find out roots of a quadratic function\n\t\"\"\"\n\tprint(\"stanCode Quadratic Solver!\")\n\t# Ask user to enter three integers\n\ta = int(input(\"Enter a: \"))\n\tb = int(input(\"Enter b: \"))\n\tc = int(input(\"Enter c: \"))\n\tdiscriminant = b ** 2 - 4 * a * c\n\t# Use discriminant method to find out the combination of numbers can have 1, 2 or no real roots.\n\tif discriminant < 0:\n\t\tprint(\"No real roots.\")\n\tif discriminant > 0:\n\t\tx1 = (-b + math.sqrt(discriminant)) / 2 * a\n\t\tx2 = (-b - math.sqrt(discriminant)) / 2 * a\n\t\tprint(\"Two roots: \"+str(x1)+\", \"+str(x2))\n\tif discriminant == 0:\n\t\tx1 = (-b + math.sqrt(discriminant)) / 2 * a\n\t\tx2 = (-b - math.sqrt(discriminant)) / 2 * a\n\t\tprint(\"one root: \"+str(x1))\n\n\n\n###### DO NOT EDIT CODE BELOW THIS LINE ######\n\nif __name__ == \"__main__\":\n\tmain()\n"} {"doc_id": "385a488dd4c3222569f6e1359ee17a45", "text": "from collections import defaultdict\nimport random\n\n\"\"\"\nSecret String\n\nThere is a secret string which is unknown to you. Given a collection of random triplets from the string, recover the original string.\nA triplet here is defined as a sequence of three letters such that each letter occurs somewhere before the next in the given string. \"whi\" is a triplet for the string \"whatisup\".\nAs a simplification, you may assume that no letter occurs more than once in the secret string. You can assume nothing about the triplets given to you other than that they are valid\ntriplets and that they contain sufficient information to deduce the original string. In particular, this means that the secret string will never contain letters that do not occur in one of the triplets given to you.\n\nsecret_1 = \"whatisup\"\ntriplets_1 = [\n ['t','u','p'],\n ['w','h','i'],\n ['t','s','u'],\n ['a','t','s'],\n ['h','a','p'],\n ['t','i','s'],\n ['w','h','s']\n]\n\nTo run: python secret_string.py\n\"\"\"\n\n\nclass Graph(object):\n \"\"\"A wrapper for representing an acyclic dependency graph\"\"\"\n\n def __init__(self, triplets):\n \"\"\"Constructs a new Graph from an array of triplets.\"\"\"\n self.graph = defaultdict(set)\n self.nodes = set()\n self.destination_nodes = set()\n\n for triplet in triplets:\n self._add_triplet(triplet)\n self.nodes.update(triplet)\n\n # Pruning Optimization: If (A, B) and (A, C) but also (B, C) then (A, C) is irrelevent\n for node in self.nodes:\n for child in list(self.graph[node]):\n self.graph[node] = self.graph[node] - self.graph[child]\n\n def _add_triplet(self, triplet):\n \"\"\"Adds a triplet to the dependency graph\"\"\"\n node_1, node_2, node_3 = triplet\n\n # Node 1 appears before node 2\n self.destination_nodes.add(node_2)\n self.graph[node_1].add(node_2)\n\n # Node 2 appears before node 3\n self.graph[node_2].add(node_3)\n self.destination_nodes.add(node_3)\n\n @property\n def source_node(self):\n \"\"\"The source node is the only node that is not a destination node\"\"\"\n return list(self.nodes - self.destination_nodes)[0]\n\n @property\n def longest_path_length(self):\n return len(self.nodes)\n\n def construct_longest_path(self, source_node, visited):\n \"\"\"Construct a longest path of nodes in the graph recursively using Depth First Search\"\"\"\n visited = visited + [source_node]\n destination_nodes = self.graph[source_node]\n\n # Recursive case: Visit destination nodes\n for destination_node in destination_nodes:\n result = self.construct_longest_path(destination_node, visited)\n\n # Base case: we've found the longest path\n if len(result) == self.longest_path_length:\n return result\n\n # Base case: We've exhausted this path\n return visited\n\n\ndef parse_secret_string(triplets):\n graph = Graph(triplets)\n path_nodes = graph.construct_longest_path(graph.source_node, [])\n return ''.join(path_nodes)\n\n\ndef run_test(secret, triplets):\n print(\"Testing secret: {}\".format(secret))\n assert parse_secret_string(triplets) == secret, \"It should return the expected answer of `{}`\".format(secret)\n print(\"Passed.\\n\")\n\n\ndef test_provided_case():\n secret = \"whatisup\"\n triplets = [\n ['t','u','p'],\n ['w','h','i'],\n ['t','s','u'],\n ['a','t','s'],\n ['h','a','p'],\n ['t','i','s'],\n ['w','h','s']\n ]\n\n run_test(secret, triplets)\n\n\ndef test_random_triplets(secret):\n \"\"\"Generate many random triplets for the provided secret\"\"\"\n letters = [letter for letter in secret]\n\n triplets = []\n for i in range(1, 1000):\n random_indicies = random.sample(range(len(letters)), 3)\n random_triplet = [letters[i] for i in sorted(random_indicies)]\n triplets.append(random_triplet)\n\n run_test(secret, triplets)\n\n\nif __name__ == '__main__':\n test_provided_case()\n test_random_triplets(\"upiswhat\")\n test_random_triplets(\"abcdefghijklmnopqrstuvwxyz\")\n test_random_triplets(\"zyxwvutsrqponmlkjihgfedcba\")\n print(\"All tests passed.\")\n"} {"doc_id": "388083a727bf07d43627d220047b59a8", "text": "# -*- coding: utf-8 -*-\n\"\"\"Module responsible for grid information.\n\"\"\"\n\n\n\nclass InputException(Exception):\n \"\"\"Exception raised for errors in the input.\n\n Attributes:\n expression -- input expression in which the error occurred\n message -- explanation of the error\n \"\"\"\n\n def __init__(self, expression, message):\n self.expression = expression\n self.message = message\n\n\nclass Grid(object):\n \"\"\"Represents the grid that the robots move around in.\"\"\"\n\n def __init__(self, width, height):\n \"\"\"Grid constructor.\n\n Parameters\n ----------\n width: int\n The width of the grid, max of 50.\n height: int\n The height of the grid, max of 50.\n \"\"\"\n self.width = width\n self.height = height\n if self.width > 50:\n raise InputException(self.width, \"Width must be less than 50\")\n if self.height > 50:\n raise InputException(self.height, \"Height must be less than 50\")\n self.scents = [] # no scents detected.\n\n def check_for_scent(self, x, y):\n \"\"\"Determines if a robot has already been lost at coordinates.\n Parameters\n ----------\n x: int\n The x coordinate of the grid to be checked.\n y: int\n The y coordinate of the grid to be checked.\n\n Returns\n -------\n bool\n True if a scent is detected, False otherwise.\n \"\"\"\n if len(self.scents) == 0:\n return False\n scent_found = [tup for tup in self.scents if tup[0] == x and tup[1] == y]\n if scent_found:\n return True\n else:\n return False\n\n def check_for_lost_robot(self, x, y):\n \"\"\"Determines if a robot is lost at coordinates.\n\n Will add coordinates to scents\n\n Parameters\n ----------\n x: int\n The x coordinate of the grid to be checked.\n y: int\n The y coordinate of the grid to be checked.\n\n Returns\n -------\n bool\n True if the robot is lost, False otherwise.\n \"\"\"\n if x > self.width or y > self.height:\n self.scents.append((x, y))\n return True\n else:\n return False\n"} {"doc_id": "388273b6ed3dce5d918942d58e730ffa", "text": "\"\"\"\nA python module for converting temperatures\n\"\"\"\n\ndef fahrenheit_to_celsius(temperature_in_f):\n \"\"\"Convert temperature from fahrenheit to celsius\n\n PARAMETERS\n ----------\n temperature_in_f : float\n A temperature in degrees Fahrenheit\n\n RETURNS\n -------\n temperature_in_c : float\n A temperature in degrees Celsius\n \"\"\"\n temperature_in_c = 5/9*(temperature_in_f-32)\n print(temperature_in_c)\n return temperature_in_c\n\ndef celsius_to_fahrenheit(temperature_in_c):\n \"\"\"Convert temperature from celsius to fahrenheit\n\n PARAMETERS\n ----------\n temperature_in_c : float\n A temperature in degrees Celsius\n\n RETURNS\n -------\n temperature_in_f : float\n A temperature in degrees Fahrenheit\n \"\"\"\n temperature_in_f = 9/5*temperature_in_c+32\n print(temperature_in_f)\n return temperature_in_f\n\n"} {"doc_id": "388549117ec1ad46de88f23582581d1a", "text": "\"\"\"\nApplication of queues\n----------------------\nQueues - used to implement a variety of functionalities in computer land:\n- instead of providing each computer on a network with its own printer, a network of computers can be made to share one\nprinter by queuing what each printer wants to print. When the printer is ready to print, it will pick one of the items\n(jobs) in the queue to print out.\n\n- Operating systems also queue processes to be executed by the CPU.\n\nMedia player queue - implement a playlist queue that plays songs in the FIFO manner\n------------------\nMost music player software allows users to add songs to a playlist. Upon hitting the play button, all the songs in the\nmain playlist are played one after the other. The sequential playing of the songs can be implemented with queues because\nthe first song to be queued is the first song that is played => FIFO\n\nMedia player queue will only allow: the addition of tracks & a way to play all the tracks in the queue\nThe media player queue is made up of nodes.\nWhen a track is added to the queue, the track is hidden in a newly created node and associated with the data attribute\nof the node. That explains why we access a node's track object through the data property of the node which is returned\nby the call to dequeue. Instead of our node object just storing just any data, it stores tracks in this case.\n\n\"\"\"\n\nfrom random import randint\nimport time\n\n\n# The class represents any MP3 track or file that contains music\n# Each track holds a reference to the title & the length of the song\n\n# uses the double-linked-list node\nclass Node:\n # The prev variable holds a reference to the previous node, the next variable holds a reference to the next node\n def __init__(self, data=None, next=None, prev=None):\n self.data = data\n self.next = next\n self.prev = prev\n\n\nclass NodeBasedQueue:\n def __init__(self):\n self.head = None\n self.tail = None\n self.count = 0 # To count the number of nodes in Queue\n\n # enqueue: nodes are added to the queue - same append operation from doubly linked list\n def enqueue(self, data):\n new_node = Node(data, None, None)\n if self.head is None:\n self.head = new_node\n self.tail = self.head\n else:\n new_node.prev = self.tail\n self.tail.next = new_node\n self.tail = new_node\n\n self.count += 1\n\n # def dequeue: removes the node at the front of the queue\n def dequeue(self):\n current = self.head\n if self.count == 1:\n self.count -= 1\n self.head = None\n self.tail = None\n elif self.count > 1:\n self.head = self.head.next\n self.head.prev = None\n self.count -= 1\n\n\nclass Track:\n def __init__(self, title=None):\n self.title = title\n self.length = randint(5, 10) # random length simulates the number of seconds it takes to play a song or track\n\n\n# MediaPlayerQueue class - inherit from the queue class\n# is a queue that holds a number of track objects in a queue\nclass MediaPlayerQueue(NodeBasedQueue):\n def __init__(self):\n super(MediaPlayerQueue, self).__init__()\n\n # add tracks to the queue\n # it creates a Node using the track object (as the node's data) & points to the tail if the queue is not empty,\n # or both head & tail if the queue is empty, to this new node.\n def add_track(self, track):\n self.enqueue(track)\n\n # Assuming the tracks in the queue are played sequentially from the first track added to the last\n # (FIFO), the play function has to loop through the elements in the queue:\n def play(self):\n while self.count > 0:\n current_track_node = self.dequeue()\n print(\"Now playing {}\".format(current_track_node.data.title))\n time.sleep(current_track_node.data.length)\n\n\ntrack1 = Track(\"white whistle\")\ntrack2 = Track(\"gold butter\")\ntrack3 = Track(\"Oh black star\")\ntrack4 = Track(\"Watch that chicken\")\ntrack5 = Track(\"Don't go\")\nprint(track1.length, track2.length, track3.length, track4.length, track5.length)\n\n# tracks are played in the order in which they were queued\n# When playing the track, the system also pauses for the number of seconds equal to that of the length of the track\nmedia_player = MediaPlayerQueue()\nmedia_player.add_track(track1)\nmedia_player.add_track(track2)\nmedia_player.add_track(track3)\nmedia_player.add_track(track4)\nmedia_player.add_track(track5)\nmedia_player.play()\n\n\n\n\n"} {"doc_id": "38b54387b8c77f92baafeebcd9eb010a", "text": "def reversedigit():\r\n a = int(input(\"Enter The Number You Want To Reverse => \")) \r\n reversed_number = 0\r\n while (a > 0): \r\n remainder = a % 10 \r\n reversed_number = (reversed_number * 10) + remainder \r\n a = a // 10\r\n print(\"The Reversed Number is : {}\".format(reversed_number))\r\n\r\ndef pronicnum():\r\n a = int(input(\"Enter The number => \"))\r\n f = 0\r\n for i in range(a):\r\n if i * (i + 1) == a:\r\n f = 1\r\n break\r\n if f==1:\r\n print(\"The Number Is Pronic\")\r\n else:\r\n print(\"The Number Is Not Pronic\")\r\n\r\ndef infinitenum():\r\n x = 0\r\n while True:\r\n print (x)\r\n x+=1\r\n\r\ndef numbercheck():\r\n a=int(input(\"Enter the number you want to check ->\"))\r\n if a>0:\r\n print(\"Number Is Positive\")\r\n elif a==0:\r\n print(\"Zero\")\r\n else:\r\n print(\"Number Is Negative\")\r\n\r\ndef fibonacci():\r\n a = int(input(\"Enter The Level Upto Which You Want To Get The Fobonacci Series => \"))\r\n b = 0\r\n c = 1\r\n d = 0\r\n print(b)\r\n print(c)\r\n for i in range(1 , a+1):\r\n d= b+c\r\n print(d)\r\n b = c\r\n c = d\r\n\r\ndef factorial():\r\n a = int(input(\"Enter The Number => \"))\r\n b = 1\r\n for i in range(1 , a+1):\r\n b = b*i\r\n print(f\"The Factorial Of {a} is :\", b)\r\n\r\ndef buzznumber():\r\n a = int(input(\"Enter The Number Which You Want To Check => \"))\r\n if a % 10 == 7 or a % 7 == 0:\r\n print(\"The Number Is a Buzz Number\")\r\n else:\r\n print(\"The Number Is Not a Buzz Number\")\r\n\r\ndef biggeroftwonum():\r\n a = input(\"Enter The First Number => \")\r\n b = input(\"Enter The Second Number => \")\r\n if a>b:\r\n print(a, \"Is Greater Than\", b)\r\n else:\r\n print(b, \"Is Greater Than\", a)\r\n\r\ndef passdigitverif4():\r\n a = int(input(\"Enter The Password => \"))\r\n ab = str(a)\r\n if len(ab)==4:\r\n print(\"You have Entered a 4 Digit Password :\", a)\r\n print(\"Access Granted\")\r\n else:\r\n print(\"You have Entered a Password More Than 4 Digits :\", a)\r\n print(\"Access Denied\")\r\n\r\ndef swapthenums():\r\n a=int(input(\"Enter the first number :-\"))\r\n b=int(input(\"Enter the second number :-\"))\r\n print(\"The original value of a is :-\" , a)\r\n print(\"The original value of b is :-\" , b)\r\n a,b=b,a\r\n print(\"The swapped value of a is :-\" , a)\r\n print(\"The swapped value of b is :-\" , b)\r\n\r\ndef divisible2():\r\n a = int(input(\"Enter The Number You Want To Check => \"))\r\n if a % 2 == 0:\r\n print(f\"The Number {a} is Divisible By 2\")\r\n else:\r\n print(f\"The Number {a} is Not Divisible By 2\")\r\n\r\ndef divisible3():\r\n a = int(input(\"Enter The Number You Want To Check => \"))\r\n if a % 3 == 0:\r\n print(f\"The Number {a} is Divisible By 3\")\r\n else:\r\n print(f\"The Number {a} is Not Divisible By 3\")\r\n\r\ndef divisible5():\r\n a = int(input(\"Enter The Number You Want To Check => \"))\r\n if a % 5 == 0:\r\n print(f\"The Number {a} is Divisible By 5\")\r\n else:\r\n print(f\"The Number {a} is Not Divisible By 5\")\r\n\r\ndef divisible7():\r\n a = int(input(\"Enter The Number You Want To Check => \"))\r\n if a % 7 == 0:\r\n print(f\"The Number {a} is Divisible By 7\")\r\n else:\r\n print(f\"The Number {a} is Not Divisible By 7\")\r\n\r\ndef divisible11():\r\n a = int(input(\"Enter The Number You Want To Check => \"))\r\n if a % 11 == 0:\r\n print(f\"The Number {a} is Divisible By 11\")\r\n else:\r\n print(f\"The Number {a} is Not Divisible By 11\")\r\n\r\ndef divisible13():\r\n a = int(input(\"Enter The Number You Want To Check => \"))\r\n if a % 13 == 0:\r\n print(f\"The Number {a} is Divisible By 13\")\r\n else:\r\n print(f\"The Number {a} is Not Divisible By 13\")"} {"doc_id": "38b6739c0bc037b6aa114281b0242c7a", "text": "class Animal():\n name = 'monkey'\n age = 10\n\n __nick_name = \"something just like this\"\n\n def __get_nike_name(self):\n return self.__nick_name\n\n def show_nick_name(self):\n print('\u6635\u79f0 :' + self.__get_nike_name())\n\n def show_nick_name_for_other(self, abc):\n self.show_nick_name()\n print(\"it's a secret:\" + str(abc))\n\n def add_num(self, *nums):\n print(*nums)\n print(nums)\n result = 0\n for i in nums:\n result += i\n return result\n\n # \u6784\u9020\u65b9\u6cd5\uff0c\u6539\u53d8\u79c1\u6709\u5c5e\u6027\n def change_nike_name(self, name):\n self.__nick_name = name\n return self.__nick_name\n\n def show(self):\n print(self.name)\n print(self.age)\n\n\nclass Human(Animal):\n name = 'laowang'\n score = 60\n\n\n# \u5b9e\u4f8b\u5bf9\u8c61\u4fee\u6539\u7684\u5c5e\u6027\u4f18\u5148\u7ea7\u9ad8\n# human = Human()\n# print(human.name+','+str(human.age))\n#\n# Human.name = 'cls_new_laowang' # \u901a\u8fc7\u7c7b\u5bf9\u8c61\u4fee\u6539\u5c5e\u6027\n# print(human.name)\n#\n# human.name = 'obj_new_laowang' # \u5b9e\u4f8b\u5bf9\u8c61\u4fee\u6539\u5c5e\u6027\n# print(human.name)\n#\n# Human.name = 'cls_new_laowang2' # \u7c7b\u5bf9\u8c61\u4fee\u6539\u5c5e\u6027\n# print(human.name)\n#\n# human2 = Human() # \u521b\u5efa\u5b9e\u529b\u5bf9\u8c61human2\n# print(human2.name)\n\nani = Animal()\n# ani.show()\n# ani.show_nick_name()\n# ani.show_nick_name_for_other('snake')\n# sum = ani.add_num(1, 2, 3, 4, 5)\n# print(sum)\nani.show_nick_name()\nani.change_nike_name('snake')\nani.show_nick_name()"} {"doc_id": "38e730a477f239c921451abf6301bedc", "text": "# Exerc\u00edcio 5 - Crie uma vari\u00e1vel chamada temperatura e atribua o valor 40. Enquanto temperatura for maior que 35, \n# imprima as temperaturas na tela\n \n''' \n***** CORRE\u00c7\u00c2O *****\n\ntemperatura = 40 \nwhile temperatura > 35: \n print(temperatura)\n temperatura = temperatura - 1\n40\n39\n38\n37\n36\n**********************'''\n \ntemperatura = float(input('Digite a temperatura do dia!: '))\n\nif temperatura > 35 :\n print(f'{temperatura}\u00b0C, Temperatura insuport\u00e1vel!')\n\nelif temperatura > 27 and temperatura < 35:\n print(f'{temperatura}\u00b0C, Temperatura Quente!')\n\nelif temperatura < 27 and temperatura > 15:\n print(f'{temperatura}\u00b0C, Temperatura Agradavel')\n\nelif temperatura < 15 and temperatura > 10:\n print(f'{temperatura}\u00b0C, Temperatura Esfrio Bastante')\n\nelse:\n print(f'{temperatura}\u00b0C, A temperatura est\u00e1 muito Frio')"} {"doc_id": "3918cf536b84c4d3577349fa054ba97e", "text": "# Ex: 044 - Elaborar um programa que calcule o valor a ser pago por um\r\n# produto, considerando o seu pre\u00e7o normal e conde\u00e7\u00e3o de pagamento:\r\n# \u00c0 vista dinheiro/cheque - 10% de desconto; \u00c0 vista no cart\u00e3o - 5% de\r\n# desconto; Em at\u00e9 2x no cart\u00e3o - pre\u00e7o normal; 3x ou mais no cart\u00e3o -\r\n# 20% de juros.\r\n\r\nprint('''\r\n-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-\r\n--Seja bem-vindo! \r\n--Exerc\u00edcio 044\r\n-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-\r\n''')\r\n\r\nprint('--Valor Final da Mercadoria\\n'\r\n '--Preencha os Dados')\r\nvalor_produto = float(input('Valor do Produto: R$'))\r\nprint('''\\nFormas de Pagamento:\r\n [ 1 ] \u00c0 vista (dinheiro/cheque) = 10% de desconto \r\n [ 2 ] \u00c0 vista (cart\u00e3o) = 5% de desconto\r\n [ 3 ] Em at\u00e9 2x no cart\u00e3o = Pre\u00e7o normal\r\n [ 4 ] 3x ou mais no cart\u00e3o = 20% de juros''')\r\ncondicao_pagamento = int(input('Digite a op\u00e7\u00e3o: '))\r\nprint('')\r\n\r\nif condicao_pagamento > 4:\r\n print('Condi\u00e7\u00e3o Inv\u00e1lida. Tente Novamente.')\r\n\r\nelse:\r\n if condicao_pagamento == 1:\r\n desconto = valor_produto * 10 / 100\r\n valor_final = valor_produto - desconto\r\n print(f'--Dados Finais\\n'\r\n f'Pre\u00e7o Inicial: R${valor_produto}\\n'\r\n f'Desconto: R${desconto:.2f}\\n'\r\n f'Pre\u00e7o Final: R${valor_final:.2f}')\r\n\r\n elif condicao_pagamento == 2:\r\n desconto = valor_produto * 5 / 100\r\n valor_final = valor_produto - desconto\r\n print(f'--Dados Finais\\n'\r\n f'Pre\u00e7o Inicial: R${valor_produto}\\n'\r\n f'Desconto: R${desconto:.2f}\\n'\r\n f'Pre\u00e7o Final: R${valor_final:.2f}')\r\n\r\n elif condicao_pagamento == 3:\r\n desconto = 0\r\n valor_final = valor_produto\r\n preco_parcelado = valor_final / 2\r\n print(f'--Dados Finais\\n'\r\n f'Pre\u00e7o Inicial: R${valor_produto}\\n'\r\n f'Desconto: Sem Desconto\\n'\r\n f'Pre\u00e7o das Parcelas: R${preco_parcelado:.2f} (2x)\\n'\r\n f'Pre\u00e7o Final: R${valor_final:.2f}')\r\n\r\n else:\r\n parcelas = int(input('Quantidade de parcelas: '))\r\n juros = valor_produto * 20 / 100\r\n valor_final = valor_produto + juros\r\n preco_parcelado = valor_final / parcelas\r\n print(f'--Dados Finais\\n'\r\n f'Pre\u00e7o Inicial: R${valor_produto}\\n'\r\n f'Total de Juros: R${juros:.2f}\\n'\r\n f'Pre\u00e7o das Parcelas: R${preco_parcelado:.2f} ({parcelas}x)\\n'\r\n f'Pre\u00e7o Final: R${valor_final:.2f}')\r\n\r\nprint('''\r\n-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-\r\n--Obrigado pelo uso!\r\n--Desenvolvido por Thalles Torres\r\n-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-''')\r\n"} {"doc_id": "391c16314f19165444bdf1473a37f244", "text": "# While loop - body is true, expresses condition \n# For loop is an iterator - executes each item in the sequence\n\n# While loop should have a statement that will result in true to close the loop\nsecret = \"swordfish\"\npw = ''\n\nwhile pw != secret:\n pw = input(\"what's the secret word ? \")\n\n\n# Continue (Testing condition again), else (only if the loop ends normally) and break (stopping loop prematurely)\nsecret = \"swordfish\"\npw = ''\nauth = False\ncount = 0\nmax_attempt = 5\n\nwhile pw != secret:\n count += 1\n if count > max_attempt: break\n if count == 3: continue\n pw = input(f\"{count}: what's the secret word ? \")\n\nelse:\n auth = True\nprint(\"Authorized\" if auth else \"Calling the FBI ...\")\n\n\n# For loop\n\nanimals = ('bear', 'bunny', 'dog', 'cat')\n\nfor pet in animals:\n if pet == 'dog':continue\n # if pet == 'cat': break\n print(pet)\nelse:\n print('that is all of the animals')\n\n\n\n"} {"doc_id": "39279664bee0e01cec3c2cd1a51dcb4c", "text": "import random\nfrom lclpy.localsearch.move.abstract_move \\\n import AbstractMove\n\n\nclass ArrayReverseOrder(AbstractMove):\n \"\"\"Implements a reverse order move function for 1 dimensional numpy arrays.\n\n The move function performs and generates moves that reverses the order of\n values in an interval of a one-dimensional array. Note that a move is\n represented as a tuple of int. The move (x, y) represents reversing of the\n order of the values in the interval of indices [x, y] of the array.\n Note that the moves are equivalent to 2-opt.\n\n Parameters\n ----------\n size : int\n The size of the numpy array that will be altered.\n\n Attributes\n ----------\n _size : int\n The size of the numpy array that is altered.\n\n Examples\n --------\n Get all possible moves, you should NEVER do this. You should evaluate only\n one move at a time. This example is simply to show the behaviour of\n get_moves and how to perform and undo a move:\n\n .. doctest::\n\n >>> import numpy\n >>> from lclpy.localsearch.move.array_reverse_order \\\\\n ... import ArrayReverseOrder\n ... # init array, a move will be performed on this array\n >>> array = numpy.array([0, 1, 2, 3, 4])\n ... # init\n >>> reverse = ArrayReverseOrder(len(array))\n ... # get all possible moves in all_moves\n >>> all_moves = []\n >>> for move in reverse.get_moves():\n ... all_moves.append(move)\n >>> all_moves\n [(0, 1), (0, 2), (0, 3), (0, 4), (1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]\n >>> # picking an arbitrary move\n >>> # Never pick a move like this yourself. It only is done here for\n >>> # the sake of showing you a clear example.\n >>> a_move = all_moves[2]\n >>> a_move\n (0, 3)\n >>> # performing the move on the array\n >>> reverse.move(array, a_move)\n >>> array\n array([3, 2, 1, 0, 4])\n >>> # undoing the move on the array\n >>> reverse.undo_move(array, a_move)\n >>> array\n array([0, 1, 2, 3, 4])\n\n An example of generating some random moves with get_random_move:\n\n .. doctest::\n\n >>> import random\n >>> from lclpy.localsearch.move.array_reverse_order \\\\\n ... import ArrayReverseOrder\n ... # set seed random\n ... # not needed, is only used here to always get the same moves.\n >>> random.seed(0)\n ... # init\n >>> reverse = ArrayReverseOrder(10)\n ... # tests\n >>> reverse.get_random_move()\n (0, 6)\n >>> reverse.get_random_move()\n (4, 8)\n >>> reverse.get_random_move()\n (6, 7)\n >>> reverse.get_random_move()\n (4, 7)\n\n \"\"\"\n\n def __init__(self, size):\n super().__init__()\n self._size = size\n\n def get_move_type(self):\n \"\"\"Returns the move type.\n\n Returns\n -------\n str\n The move type.\n\n \"\"\"\n\n return 'array_reverse_order'\n\n def move(self, array, move):\n \"\"\"Performs the move asked.\n\n Parameters\n ----------\n array : numpy.ndarray\n The array that will be altered.\n move : tuple of int\n Represents 1 unique move. Valid moves can be retrieved by using\n get_random_move and get_move.\n\n \"\"\"\n\n (index_1, index_2) = move\n\n # calulate the mean of index_1 and index_2\n middle = (index_1 + index_2) / 2\n\n # swap all pairs in the range [index_1, index_2].\n # This will change the order of the values in the range.\n while(index_1 < middle):\n\n array[index_1], array[index_2] = array[index_2], array[index_1]\n\n index_1 += 1\n index_2 -= 1\n\n def undo_move(self, array, move):\n \"\"\"Undoes the move asked.\n\n Parameters\n ----------\n array : numpy.ndarray\n The array that will be altered.\n move : tuple of int\n Represents 1 unique move. Valid moves can be retrieved by using\n get_random_move and get_move.\n\n \"\"\"\n\n self.move(array, move)\n\n def get_moves(self):\n \"\"\"Iterate over all valid moves.\n\n Yields\n ------\n tuple of int\n The next valid move.\n\n \"\"\"\n\n for i in range(self._size):\n for j in range(i + 1, self._size):\n yield (i, j)\n\n def get_random_move(self):\n \"\"\"This method is used to generate one random move.\n\n Returns\n -------\n tuple of int\n A random valid move.\n\n \"\"\"\n\n # It's possible to simply generate an i and then generate a bigger j,\n # but this wouldn't give us a proper distribution. Moves with a bigger\n # i would have a higher chance to be chosen than those with a smaller\n # i.\n\n # generate random numbers\n i = random.randrange(self._size)\n j = random.randrange(self._size)\n\n # ensure the number are different\n while i == j:\n j = random.randrange(self._size)\n\n # Puts the smallest number first, not needed, but ensures that every\n # move will have only 1 representation that will be used.\n if j < i:\n i, j = j, i\n\n return (i, j)\n"} {"doc_id": "39279d4d4db4d150cd9c9ffeb2d42bbe", "text": "def cipher(text, shift, encrypt=True):\n \"\"\"\n Conducts the traditional caesar cipher on the string text.\n\n Parameters\n ----------\n text:\n Any python string value\n shift:\n Any python integer value\n encrypt:\n Default value is left shift, but setting it to False will create a right shift. \n\n -------\n The new string text after the caesar cipher has been applied to it.\n\n Examples\n --------\n >>> from cipher_pvp2108 import cipher\n >>> cipher('Pooja', -1)\n 'OnniZ'\n >>> cipher('OnniZ', -1, False)\n 'Pooja'\n \"\"\"\n alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'\n new_text = ''\n for c in text:\n index = alphabet.find(c)\n if index == -1:\n new_text += c\n else:\n new_index = index + shift if encrypt == True else index - shift\n new_index %= len(alphabet)\n new_text += alphabet[new_index:new_index+1]\n return new_text\n\n"} {"doc_id": "393a64089ead947afa8123c010feae95", "text": "# hello = \"Hello World\"\n#\n# print(hello[0:11:2])\n#\n# new_hello = hello[:]\n# print(len(new_hello))\n# new_string = new_hello + \" \" + new_hello * 2\n# print(new_string)\n#\n# new_new_string = new_string * 3\n# print(new_new_string)\n#\n#\n# ord(66)\n# print(ord)\n\n####1. Write a program to print each char from a str on a\n#### single line\n\n# string = \"This is my practice string\"\n# print(string)\n\n\n####2. Write a program that will calculte the length of a str.\n# count = 0\n# string = \"This is my practice string\"\n# for x in string:\n# if x.isalpha():\n# count += 1\n# print(count)\n\n####Shortened simple version:\n# print(len(input(\"Enter a string: \")))\n\n####improved answer:\n# string = str(input(\"Please enter a string to be measured: \"))\n# count = 0\n# for i in string:\n# if i.isdigit():\n# print(\"Only characters can be counted, not digits. \")\n# break\n#\n# elif i.lower().isalpha() or i.isspace():\n# count += 1\n# print(count)\n\n\n####3. Write a program that reads a string and prints a string\n####that is made up of the first and last two chars.\n#### if str lenght is less than 4 ask for a new input\n#### example \"hello there\" will produce: \"here\"\n\n# string = input(\"Please enter some letters: \")\n# if len(string) < 4:\n# print(\"That string is too short, dickhead!! \")\n# string_1 = (string[0:2])\n# string_2 = (string[-2:])\n# print(string_1 + string_2)\n\n\n# string = str(input(\"Please enter some letters: \"))\n# if len(string) < 4:\n# print(\"That string is to short\")\n# elif len(string) > 4:\n# new_str = string[2:4] + string[-4:-2]\n# print(new_str)\n\n####Improved Version\n# string = str(input(\"Enter a string: \"))\n# complete = False\n#\n# while complete is False:\n#\n# if len(string) <= 4:\n# print(\"That string is too short. \")\n# string = str(input(\"Enter a string: \"))\n# continue\n#\n# elif len(string) > 4:\n# final = string[0:2] + string[-2:]\n# print(final)\n# complete = True\n\n####4. Write a program that will reverse a string (using a loop)\n\n####3 Original, messy solutions.\n# string = \"Hello World\"\n# new_str = \"\"\n# for i in range(len(string)-1, -1, -1):\n# new_str = new_str + string[i]\n# print(new_str)\n#\n# s = \"hello\"\n# new_str = \"\"\n# for c in s:\n# new_str = new_str + c\n# ####OR####\n# # new_str = c + new_str\n# print(new_str)\n#\n# s = \"hello\"\n# i = len(s) - 1\n# new_str = \"\"\n# while i >= 0:\n# new_str = new_str + s[i]\n# i = i - 1\n# print(new_str)\n\n#### Improved solution with function:\n# str_in = input(str(\"Please enter a string: \"))\n#\n# def str_loop_convert(string):\n# str_out = \"\"\n# for i in string:\n# str_out = string[::-1]\n# return str_out\n#\n#\n# print(str_loop_convert(str_in))\n\n\n####5. Write a program that will 'encrypt' a string. Add 1 to the\n####ASCII code ('a' becomes 'b')\n####use ord + chr\n\n# new_string = \"\"\n# string = input(\"Please enter a string: \")\n# for c in string:\n# new_string = new_string + chr(ord(c) + 1)\n# print(new_string)\n\n\n####6. Write a program that will swap 2 random letters in a string\n#### Hint random means random index\n\n\n\n\n####Extra 1. Check if a string is a valid password. It should contain\n#### one upper, one lower, one special (+-%$!@) and be between\n#### 6 and 10 chars long\n\n# pwd = input (\"Input password:\")\n#\n# import re\n# flag = 0\n# while True:\n# if (len(pwd) < 6):\n# flag = -1\n# break\n# elif (len(pwd) > 10):\n# flag = -1\n# break\n# elif not re.search(\"[a-z]\", pwd):\n# flag = -1\n# break\n# elif not re.search(\"[A-Z]\", pwd):\n# flag = -1\n# break\n# elif not re.search(\"[0-9]\", pwd):\n# flag = -1\n# break\n# elif not re.search(\"[_@$]\", pwd):\n# flag = -1\n# break\n# elif re.search(\"\\s\", pwd):\n# flag = -1\n# break\n# else:\n# flag = 0\n# print(\"Valid Password\")\n# break\n#\n# if flag == -1:\n# print(\"Not a Valid Password\")\n\n\n####Extra 2. Write a program that counts how many times the string\n####'hi' is contained in another string for example:\n#### 'hi there, the sky is high, but the moon is higher' should\n#### print 3.\n\n# mystring = \"Hi there, the sky is high, but the moon is higher\"\n# substring = \"hi\"\n# count = mystring.count(substring)\n#\n# for i in mystring:\n# if i == str('hi'):\n# count = count + 1\n#\n# print(\"Count of\", substring, \"in your string is : \"\n# + str(count))\n\n\n"} {"doc_id": "39470586fd577651e1eb35c032959e4d", "text": "'''\nTrata de crear un script que guarde una lista de nombres en un archivo ya existente que\ncontenga una lista, leyendo previamente la lista. Inicialmente tendremos que abrir el archivo\ncon cuidado de que, en caso de no existir, Python nos dar\u00e1 un error (prueba con un try -\nexcept).\nEl script nos tendr\u00e1 que dar la opci\u00f3n de utilizar los nombres existentes en la lista y seguir\nincorporando nuevos o bien eliminarlos todos y empezar de cero.\n'''\n'''\nPodria hacerlo con un if\nimport os\nprint(\"El fichero existe.\") if os.path.exists(\n \"fichero.txt\") else print(\"Fichero no existe.\")\n'''\nrepetir = True # Variable para controlar el bucle\nlist = []\n\ntry: # Intentamos abrir el fichero.\n # Abrimos el fichero para extraer la lista de nombres.\n archivo = open(\"./000 Retos/fichero.txt\", \"r\")\n for linea in archivo:\n linea = linea.replace(\"\\n\",\"\")\n list.append(linea)\n archivo.close()\nexcept: # Si no es posible creamos un nuevo fichero.\n archivo = open(\"./000 Retos/fichero.txt\", \"w\") # Creamos el fichero\n archivo.close()\n\n\ndef Salir():\n global repetir, list\n print(\"Salir\")\n archivo = open(\"./000 Retos/fichero.txt\", \"w\") # Creamos el fichero\n for linea in list:\n archivo.write(linea +\"\\n\")\n archivo.close()\n repetir = False\n\n\ndef Agregar():\n print(\"Agregar\")\n list.append(input(\"Introduce nombre: \"))\n\n\ndef Imprimir():\n print(\"Imprimir\")\n print(list)\n\n\ndef Eliminar():\n print(\"Eliminar\")\n\n\n# Creamos un diccionario con las elecciones posibles.\nelecciones = {0: Salir, 1: Agregar, 2: Eliminar, 3: Imprimir}\nwhile repetir == True: # Comprobamos que la variable se correcta.\n print('''\n ##### Gestion Agenda #####\n # 0.- Salir. #\n # 1.- Agregar. #\n # 2.- Eliminar. #\n # 3.- Imprimir. #\n #############################\n ''')\n try:\n seleccion = int(input('Escoge una opcion: '))\n except:\n print(\"Utilicen los numeros\")\n elecciones[seleccion]() if (0 <= seleccion & 3 >= seleccion) else print(\n \"Selecciona una de las opciones\")\n\n"} {"doc_id": "3965132dd1d21fa48d6190a8ceeb290f", "text": "import educative.course1.stacks_queues.stack as s\nimport educative.course1.graphs.graph as g\n\ninput_num_vertices = 5\ninput_edges = {0: [1, 2], 1: [3, 4]}\nexpected_output = \"02143 or 02134 or 01432 or 01342\"\n\n\n# this code implements Depth First Traversal in a graph. Each element in the graph's adjacency list\n# represents a list of nodes directly connected to the current element. Each of these lists represent\n# levels in the graph. We traverse all the nodes from root node to last node first, then we back-track\n# to the last visited common node and then we take second branch from there, until we back-track to root node\n# and no branches are left unvisited.\n# --------------\n# For traversal:\n# --------------\n# 1. We first push the root node in a stack and mark it visited.\n# 2. Now we get the list of adjacent nodes from the root node and push all adjacent nodes in the list\n# to the stack.\n# 3. As we are pushing the adjacent nodes to the stack, we mark them as visited.\n# 4. Simultaneously, we pop the nodes from the stack and append the node's value to the result\n# --------------\ndef bfs_traversal(graph, root):\n result = \"\"\n visited = [False] * graph.num_vertices\n\n stack = s.Stack(graph.num_vertices, True) # suppress_printing = True\n stack.push(root)\n\n while not stack.is_empty():\n g_node = stack.pop()\n result += str(g_node)\n\n dll = graph.adjacency_list[g_node]\n if dll is not None:\n current = dll.head\n while current:\n if not visited[current.value]:\n stack.push(current.value)\n visited[current.value] = True\n current = current.next\n\n return result\n\n\ndef main():\n # create a graph from input data\n graph = g.Graph(input_num_vertices, True) # suppress_printing = True\n for x in input_edges.keys():\n for y in input_edges[x]:\n graph.add_edge(x, y)\n\n # set a starting point for traversal\n root = 0\n\n print(\"Input:\")\n print(\"Graph in Adjacency List Representation:\")\n print(str(graph.prettify()))\n\n print(\"Expected: \" + str(expected_output))\n print(\"Output: \" + str(bfs_traversal(graph, root)))\n\n\nif __name__ == '__main__':\n main()\n\n"} {"doc_id": "39927dda72d63e0615a330f03932fea2", "text": "\"\"\"\nList Data Type(list):\n- Just Like Array following indexing\n- **Unlike Arrays, list can hold HETEROGENEOUS DATA TYPE\n- Repetition allowed\n- Multi Dimensional\n\"\"\"\n\n# Creating a Multi-Dimensional List\n\nprint(\" \\n-------CREATE---------- \")\nList = [['Hitesh', 'kumar', 'Sahu'], [29]]\nthislist = [\"0\", \"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\"]\nfruitList = list((\"apple\", \"banana\", \"cherry\"))\n\nprint(List)\n\n\nprint(\" \\n-------READ---------- \")\nprint(\"List[1]: \", List[1])\nprint(\"List[0][0]: \", List[0][0])\nprint(\"List[0][-2]: \", List[0][-2]) # negative index start from -1\n\nfor x in thislist:\n print(\"Element\", x)\n\nprint(thislist)\nprint(\"LENGTH\", len(thislist))\nprint(\"MAX\", max(thislist))\nprint(\"MIN\", min(thislist))\n\n\nprint(\"thislist[:4]: \", thislist[:4])\nprint(\"thislist[2:]: \", thislist[2:])\n\n\nprint(\" \\n-------UPDATE---------- \")\n\nthislist[1] = \"9\"\nprint(thislist)\n\nprint(\"\\nTraversing Elements\")\nif \"9\" in thislist:\n print(\"Yes, '9' is in the list\")\n\nthislist.reverse()\nprint(\"Reverse\", thislist)\n\nthislist.sort()\nprint(\"Sorted\", thislist)\n\nthislist.append(\"10\")\nprint(\"Append 10:\", thislist)\n\nthislist.insert(7, \"8\")\nprint(\"Insert 8:\", thislist)\n\nthislist.insert(1, \"1\")\nprint(\"Insert 1:\", thislist)\n\nprint(\" \\n-------DELETE---------- \")\n\nthislist.remove(\"10\")\nprint(\"remove 10:\", thislist)\n\nthislist.pop(9)\nprint(\"pop 9:\", thislist)\n\ndel thislist[8]\nprint(\"del 8:\", thislist)\n\nthislist.clear()\nprint(\"clear:\", thislist)"} {"doc_id": "39fabf752eeeec153de9ce301cbe77ac", "text": "#######################\n#Willard Wider\n#7/11/18\n#ELEC4400\n#Lab 9\n#######################\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom scipy.fftpack import fft\nfrom scipy.io import wavfile\nimport time\n\ndef myOwnDFT(u):\n N = len(u)\n Un = []\n for n in np.arange(0,N):\n Uk=0\n for k in np.arange(0,N):\n Uk+=u[k]*np.exp((-1*2j*np.pi*k*n)/N)\n Un.append(Uk)\n return Un\n\nif __name__ == \"__main__\":\n #specify the stype of the plot to use\n plt.style.use('ggplot')\n #make a sine wave, duration 1s\n x_index = np.linspace(0,1,500)\n x_index_frequnecy = np.arange(len(x_index))\n print(\"making sine wave 10hz...\")\n y_values_10 = np.sin(2*np.pi*10*x_index)\n fourier_10 = myOwnDFT(y_values_10)\n print(\"making sine wave 20hz...\")\n y_values_20 = np.sin(2*np.pi*20*x_index)\n fourier_20 = myOwnDFT(y_values_20)\n print(\"making sine wave 30hz...\")\n y_values_30 = np.sin(2*np.pi*30*x_index)\n fourier_30 = myOwnDFT(y_values_30)\n\n #create the three graphs for fourier frequency plotting\n f,xarr = plt.subplots(3)\n xarr[0].set_title('10-30Hz analysis')\n xarr[0].plot(x_index_frequnecy, fourier_10)\n xarr[1].plot(x_index_frequnecy, fourier_20)\n xarr[2].plot(x_index_frequnecy, fourier_30)\n plt.show()\n\n #show how long it takes for each sample ammount\n samples_array = [200,400,600,800,1000]\n time_array = []\n for i in samples_array:\n time_x_index = np.linspace(0,1,i)\n #https://docs.python.org/3/tutorial/inputoutput.html\n print(f'running transform for {i} samples...')\n time_y_values = np.sin(2*np.pi*10*time_x_index)\n #start the timer\n start_time = time.time()#time since epoch\n time_fourier = myOwnDFT(time_y_values)\n time_array.append(time.time()-start_time)\n plt.plot(samples_array,time_array)\n plt.title('time of running each transform')\n plt.show()\n\n #estimate how long it will abe to run a transform of the wave file we used\n print(f'it took {time_array[4]} to run a fourier transform of {samples_array[4]} samples')\n fs, data = wavfile.read('kpt.wav')\n print(f'the wavefile from previous lab is {len(data)} sampels...') #should be 561,152\n ratio = time_array[4] / samples_array[4]\n print(f'thus it will take {ratio*len(data)} to complete this one')\n \n #analyse the smaller sample to find the wave used\n print('analysing the smaller sample...')\n #https://stackoverflow.com/questions/2060628/reading-wav-files-in-python\n fs, data = wavfile.read('kpt1note2k.wav')\n #fast fourier transform of the data\n #fftOut = fft(data)\n fftOut = myOwnDFT(data)\n #total ammount of time in the recording\n length = len(data) / fs\n #a list of sample indicies, probably audio frames\n n = np.arange(len(data))\n #fs the the sampling frequency, the number of samples per second\n #we need the duration of time between samples\n #time between is 1 (sec) divided by frequency\n total_frequencies = n / length\n plt.plot(total_frequencies,np.abs(fftOut))\n #limit the plot\n plt.xlim(([0,4186]))\n plt.title(\"Piano Note Analysis\")\n plt.xlabel(\"frequency (Hz)\")\n plt.ylabel(\"amplitude (Db)\")\n plt.show()\n print('results show that it was 462Hz, close to 450Hz, A4')\n"} {"doc_id": "3a23c03da93bc120c5ed02905c2e91dd", "text": "\"\"\"\nFile: caesar.py\nName: Po Kai Feng\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 User will give a cipher number to create new alphabet first.\n Then user will type a cipher_string. Finally the code will decipher it.\n \"\"\"\n cipher_num = int(input('Secret number: '))\n ciphered_str = input('What\\'s the ciphered string? ')\n print('The deciphered string is: ' + decipher(ciphered_str.upper(), cipher_num))\n\n\ndef decipher(ciphered_str, cipher_num):\n \"\"\"\n :param ciphered_str: str, the string that has been ciphered\n :param cipher_num: int, the cipher number\n :return: str, deciphered string\n \"\"\"\n new_alphabet = ''\n deciphered_str = ''\n for i in range(26 - cipher_num, 26):\n new_alphabet += ALPHABET[i]\n for j in range(0, 26 - cipher_num):\n new_alphabet += ALPHABET[j]\n # Now new_alphabet is wrapped\n for k in range(0, len(ciphered_str)):\n if new_alphabet.find(ciphered_str[k]) == -1:\n # It's not alphabet and doesn't need to decipher\n deciphered_str += ciphered_str[k]\n else:\n deciphered_str += ALPHABET[new_alphabet.find(ciphered_str[k])]\n return deciphered_str\n\n\n##### DO NOT EDIT THE CODE BELOW THIS LINE #####\nif __name__ == '__main__':\n main()\n"} {"doc_id": "3a314973b8510894ea1d1272708c2410", "text": "# Interactive test program creating a dictionary of accounts\n# Version 4, with an interactive menu\n\nfrom Account import *\n\naccountsDict = {}\nnextAccountNumber = 0\n\n# Build some starting accounts for testing\noAccount = Account('Joe', 100, 'JoesPassword')\naccountsDict[nextAccountNumber] = oAccount\nprint('Account number for Joe is:', nextAccountNumber)\n# increment the account number after assignment\nnextAccountNumber = nextAccountNumber + 1\n\noAccount = Account('Mary', 12345, 'MarysPassword')\naccountsDict[nextAccountNumber] = oAccount\nprint('Account number for Mary is:', nextAccountNumber)\nnextAccountNumber = nextAccountNumber + 1\n\nwhile True:\n print()\n print('Press b to get the balance')\n print('Press d to make a deposit')\n print('Press o to open a new account')\n print('Press w to make a withdrawal')\n print('Press s to show all accounts')\n print('Press q to quit')\n print()\n\n action = input('What do you want to do? ')\n action = action.lower()\n action = action[0] # grab the first letter\n print()\n \n if action == 'b':\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 = accountsDict[userAccountNumber]\n theBalance = oAccount.getBalance(userAccountPassword)\n if theBalance is not None:\n print('Your balance is:', theBalance)\n\n elif action == 'd':\n print('*** Deposit ***')\n userAccountNumber = input('Please enter the account number: ')\n userAccountNumber = int(userAccountNumber)\n userDepositAmount = input('Please enter amount to deposit: ')\n userDepositAmount = int(userDepositAmount)\n userPassword = input('Please enter the password: ')\n oAccount = accountsDict[userAccountNumber]\n theBalance = oAccount.deposit(userDepositAmount, userPassword)\n if theBalance is not None:\n print('Your new balance is:', theBalance)\n \n elif action == 'o':\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 is the password you want to use for this account? ')\n oAccount = Account(userName, userStartingAmount, userPassword)\n accountsDict[nextAccountNumber] = oAccount\n print('Your new account number is:', nextAccountNumber)\n nextAccountNumber = nextAccountNumber + 1\n print()\n\n elif action == 's':\n print('Show:')\n for userAccountNumber in accountsDict:\n oAccount = accountsDict[userAccountNumber]\n print(' Account number:', userAccountNumber)\n oAccount.show()#userAccountNumber)\n\n elif action == 'q':\n break\n\n elif action == 'w':\n print('*** Withdraw ***')\n userAccountNumber = input('Please enter your account number: ')\n userAccountNumber = int(userAccountNumber)\n userWithdrawalAmount = input('Please enter the amount to withdraw: ')\n userWithdrawalAmount = int(userWithdrawalAmount)\n userPassword = input('Please enter the password: ')\n oAccount = accountsDict[userAccountNumber]\n theBalance = oAccount.withdraw(userWithdrawalAmount, userPassword)\n if theBalance is not None:\n print('Withdrew:', userWithdrawalAmount)\n print('Your new balance is:', theBalance)\n\n else:\n print('Sorry, that was not a valid action. Please try again.')\n\nprint('Done')\n"} {"doc_id": "3a49555ad0ca68a15f1dfdf4ba1312c5", "text": "print(\"---SALARIO---\")\n\ndef salarioBruto(salarioHora, horasMes):\n return salarioHora * horasMes\n\ndef irrf(brutoMes):\n return brutoMes * (11/100)\n\ndef inss(brutoMes):\n return brutoMes * (8/100)\n\ndef sindicato(brutoMes):\n return brutoMes * (5/100)\n\ndef main():\n nome = str(input(\"Digite seu nome: \"))\n matricula = int(input(\"Digite sua matricula: \"))\n salarioHora = float(input(\"Informe sua remunera\u00e7\u00e3o por hora: R$ \"))\n horasMes = float(input(\"Horas trabalhadas no m\u00eas (hrs.min): \"))\n salarioBrutoMes = salarioBruto(salarioHora, horasMes)\n valorDescontado = irrf(salarioBrutoMes) + inss(salarioBrutoMes) + sindicato(salarioBrutoMes)\n salarioLiquido = salarioBrutoMes - valorDescontado\n\n print(\"\\n\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022EXTRATO\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\".format())\n print(\"Nome: {} - Matricula: {}\".format(nome, matricula))\n print(\"\u25baProventos\u25c4\")\n print(\"Sal\u00e1rio Bruto: R$ {:.2f}\".format(salarioBrutoMes))\n print(\"\u25baDescontos\u25c4\")\n print(\"IPRF: R$ {:.2f} - INSS: R$ {:.2f} - Sindicato: R$ {:.2f}\".format(irrf(salarioBrutoMes),\n inss(salarioBrutoMes),sindicato(salarioBrutoMes)))\n print(\"Total descontos: R$ {:.2f}\".format(valorDescontado))\n print(\"\\nSal\u00e1rio liquido: R$ {:.2f}\".format(salarioLiquido))\nmain()\n"} {"doc_id": "3a840540e48a034c4b6796fb31dcd064", "text": "#Create a Python script file named data_types_and_variables.py. Inside it, write some Python code, that is, variables and operators, to describe the following scenarios. Do not worry about the real operations to get the values, the goal of these exercises is to understand how real world conditions can be represented with code.\n\n#You have rented some movies for your kids: The little mermaid (for 3 days), Brother Bear (for 5 days, they love it), and Hercules (1 day, you don\u2019t know yet if they\u2019re going to like it). If price for a movie per day is 3 dollars, how much will you have to pay?\nprice = 3\n\nlittle_mermaid = 3\nbrother_bear = 5\nhercules = 1\n\ntotal = (little_mermaid + brother_bear + hercules) * 3\n\nprint(total)\n\n\n#Suppose you\u2019re working as a contractor for 3 companies: Google, Amazon and Facebook, they pay you a different rate per hour. Google pays 400 dollars per hour, Amazon 380, and Facebook 350. How much will you receive in payment for this week? You worked 10 hours for Facebook, 6 hours for Google and 4 hours for Amazon.\n\ngoogle = 400\namazon = 380\nfacebook = 350\n\ntotal_pay = (facebook * 10) + (google * 6) + (amazon * 4)\n\nprint (total_pay)\n\n\n#A student can be enrolled to a class only if the class is not full and the class schedule does not conflict with her current schedule.\n\nclass_has_space = True\nschedule_works = False\ncan_be_enrolled = class_has_space and schedule_works\ncan_be_enrolled\n\n#A product offer can be applied only if people buys more than 2 items, and the offer has not expired. Premium members do not need to buy a specific amount of products.\n\npremium_member = True\n\nnumber_of_items = 5\n\noffer_not_expired = True\n\ncan_apply_offer = (number_of_items > 2 or premium_member) and offer_not_expired\n\ncan_apply_offer\n\n#Class Review\n\nis_premium_member = False\npurchasing_more_than_two_items = True\noffer_valid = True\noffer_can_be_applied = offer_valid and (is_premium_member or purchasing_more_than_two_items)\noffer_can_be_applied\n\n\n#Use the following code to follow the instructions below:\n #username = \u2018codeup\u2019\n #password = \u2018notastrongpassword\u2019\n\n\n#Create a variable that holds a boolean value for each of the following conditions:\n #the password must be at least 5 characters\n #the username must be no more than 20 characters\n #the password must not be the same as the username\n #bonus neither the username or password can start or end with whitespace\n\nusername = 'codeup'\npassword = 'notastrongpassword'\n\npassword_is_at_least_5_characters = len(password) >= 5\nusername_less_than_twenty_characters = len(username) <= 20\npassword_different_than_username = username != password\n\n#bonus\n\npassword_has_no_whitespace = password == password.strip()\nusername_has_no_whitespace = username == username.strip()\n\nis_valid_username_and_password = (password_is_at_least_5_characters\n and username_less_than_twenty_characters\n and password_different_than_username\n and password_has_no_whitespace\n and username_has_no_whitespace)\n\nis_valid_username_and_password"} {"doc_id": "3a9eb497c7167d4b188dfdcb84c01665", "text": "\"\"\"\nFile: boggle.py\nName: Karnen Huang\n----------------------------------------\nThis file helps user find word whose length is more than 4 and in dictionary by using 16 characters entered\nby user.\n\"\"\"\n\n# This is the file name of the dictionary txt file\n# we will be checking if a word exists by searching through it\nFILE = 'dictionary.txt'\n\n# global variable\ndic = []\t # contains all the word found in the dictionary txt file\n\n\ndef main():\n\t\"\"\"\n\tThis function helps user find word whose length is more than 4 and in dictionary by using 16 letters entered\n\tby user.\n\t\"\"\"\n\tread_dictionary()\n\twhile True:\n\t\tch_lst = []\n\t\tfor i in range(4):\n\t\t\trow = input(str(i+1) + ' row of letters: ').lower()\n\t\t\tif not correct_format(row):\n\t\t\t\tprint('Illegal input')\n\t\t\t\treturn\n\t\t\tch = row.split()\n\t\t\tch_lst.append(ch)\n\n\t\tword_lst = [] \t\t\t\t# contains all the word found in dic based on the letters entered by user\n\t\tnum_lst = [0]\t\t\t\t# records the number of word has printed\n\n\t\t# Make every letter entered by user become starting point\n\t\tfor x in range(len(ch_lst)):\n\t\t\tfor y in range(len(ch_lst)):\n\t\t\t\tfind_boggle('', ch_lst, x, y, [(x, y)], word_lst, num_lst) # start recursion\n\t\tprint('There are', num_lst[0], 'words in total.')\n\t\tbreak\n\n\ndef correct_format(row):\n\t\"\"\"\n\t:param row: str, the data entered by user\n\t:return: bool, if the format of the data is correct\n\t\"\"\"\n\tif row[1] is not ' ' or row[3] is not ' ' or row[5] is not ' ':\n\t\treturn False\n\telse:\n\t\treturn True\n\n\ndef find_boggle(current_s, ch_lst, x, y, use_lst, word_lst, num_lst):\n\t\"\"\"\n\t:param current_s: str, contains the letters we choose and create a word\n\t:param ch_lst: lst, contains all the letters entered by user\n\t:param x: int, the position of the letter\n\t:param y: int, the position of the letter\n\t:param use_lst: lst, contains the position of letters contain in current_s\n\t:param word_lst: lst, contains all the word found in dic based on the letters entered by user\n\t:param num_lst: lst, records the number of word has printed\n\t:return: show all the word found in dic based on the letters entered by user in console\n\t\"\"\"\n\t# when length of current_s is more than 4, consider to print current_s\n\tif len(current_s) >= 4:\n\t\tif current_s in dic:\n\t\t\tif current_s not in word_lst:\n\t\t\t\tprint('Found \"'+current_s+'\"')\n\t\t\t\tword_lst.append(current_s)\n\t\t\t\tnum_lst[0] += 1\n\t\t\t\t\n\t# find the letter next to the current position\n\tfor i in range(-1, 2):\n\t\tfor j in range(-1, 2):\n\t\t\tif 0 <= x + i < 4:\n\t\t\t\tif 0 <= y + j < 4:\n\t\t\t\t\t# Choose\n\t\t\t\t\tif (x+i, y+j) not in use_lst:\n\t\t\t\t\t\tcurrent_s += ch_lst[x+i][y+j]\n\t\t\t\t\t\tuse_lst.append((x+i, y+j))\n\t\t\t\t\t\t# Explore\n\t\t\t\t\t\tif has_prefix(current_s):\n\t\t\t\t\t\t\tfind_boggle(current_s, ch_lst, x+i, y+j, use_lst, word_lst, num_lst)\n\t\t\t\t\t\t# Un-choose\n\t\t\t\t\t\tcurrent_s = current_s[:-1]\n\t\t\t\t\t\tuse_lst.pop()\n\n\ndef read_dictionary():\n\t\"\"\"\n\tThis function reads file \"dictionary.txt\" stored in FILE\n\tand appends words in each line into a Python list\n\t\"\"\"\n\twith open(FILE, 'r') as f:\n\t\tfor line in f:\n\t\t\tline = line.strip()\n\t\t\tdic.append(line)\n\n\ndef has_prefix(sub_s):\n\t\"\"\"\n\t:param sub_s: (str) A substring that is constructed by neighboring letters on a 4x4 square grid\n\t:return: (bool) If there is any words with prefix stored in sub_s\n\t\"\"\"\n\tfor word in dic:\n\t\tif word.startswith(sub_s):\n\t\t\treturn True\n\n\nif __name__ == '__main__':\n\tmain()\n"} {"doc_id": "3abb985af1ef03404104ae72a00e0576", "text": "\"\"\"\n

Median 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:
\n

[2,3,4] , the median is 3

\n

[2,3], the median is (2 + 3) / 2 = 2.5

\n\n

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\n

For example,
\nGiven nums = [1,3,-1,-3,5,3,6,7], and k = 3.

\n\n
\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].

\n\n

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

\n\n

[2,3]\uff0c\u4e2d\u4f4d\u6570\u662f (2 + 3) / 2 = 2.5

\n\n

\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\n
\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

\n\n

\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.

\n

\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

\n\n

[2,3]\uff0c\u4e2d\u4f4d\u6570\u662f (2 + 3) / 2 = 2.5

\n\n

\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\n
\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

\n\n

\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.

\n\"\"\"\n\n\nclass Solution:\n def medianSlidingWindow(self, nums, k):\n \"\"\"\n :type nums: List[int]\n :type k: int\n :rtype: List[float]\n \"\"\"\n "} {"doc_id": "3ac9105645abf28503ac14fb1a3fba95", "text": "# -*- coding: utf-8 -*-\r\nfrom random import randint, choice\r\n\r\n#-------------------------------------------------------------------------\r\ndef isWinner(bo, le):\r\n # Given a board and a player\u2019s letter, this function returns True if that player has won.\r\n # We use bo instead of board and le instead of letter so we don\u2019t have to type as much.\r\n return ((bo[6] == le and bo[7] == le and bo[8] == le) or # across the top\r\n (bo[3] == le and bo[4] == le and bo[5] == le) or # across the middle\r\n (bo[0] == le and bo[1] == le and bo[2] == le) or # across the bottom\r\n (bo[6] == le and bo[3] == le and bo[0] == le) or # down the left side\r\n (bo[7] == le and bo[4] == le and bo[1] == le) or # down the middle\r\n (bo[8] == le and bo[5] == le and bo[2] == le) or # down the right side\r\n (bo[6] == le and bo[4] == le and bo[2] == le) or # diagonal\r\n (bo[8] == le and bo[4] == le and bo[0] == le)) # diagonal\r\n\r\ndef getBoardCopy(board):\r\n # Make a duplicate of the board list and return it the duplicate.\r\n dupeBoard = []\r\n\r\n for i in board:\r\n dupeBoard.append(i)\r\n\r\n return dupeBoard\r\n\r\ndef isSpaceFree(board, move):\r\n # Return true if the passed move is free on the passed board.\r\n return board[move] == 0\r\n \r\ndef chooseRandomMoveFromList(board, movesList):\r\n # Returns a valid move from the passed list on the passed board.\r\n # Returns None if there is no valid move.\r\n possibleMoves = []\r\n for i in movesList:\r\n if isSpaceFree(board, i):\r\n possibleMoves.append(i)\r\n\r\n if len(possibleMoves) != 0:\r\n return choice(possibleMoves)\r\n else:\r\n return None \r\n \r\ncomputerLetter = 1\r\nplayerLetter = 2 \r\n \r\ndef getComputerMove(board, computerLetter):\r\n # Given a board and the computer's letter, determine where to move and return that move.\r\n\r\n\r\n # Here is our algorithm for our Tic Tac Toe AI:\r\n # First, check if we can win in the next move\r\n for i in range(0, 9):\r\n copy = getBoardCopy(board)\r\n if isSpaceFree(copy, i):\r\n makeMove(copy, computerLetter, i)\r\n if isWinner(copy, computerLetter):\r\n return i\r\n\r\n # Check if the player could win on their next move, and block them.\r\n for i in range(0, 9):\r\n copy = getBoardCopy(board)\r\n if isSpaceFree(copy, i):\r\n makeMove(copy, playerLetter, i)\r\n if isWinner(copy, playerLetter):\r\n return i\r\n\r\n \r\n # Try to take the center, if it is free.\r\n if isSpaceFree(board, 4):\r\n return 4\r\n\r\n # Try to take one of the corners, if they are free.\r\n move = chooseRandomMoveFromList(board, [0, 2, 6, 8])\r\n if move != None:\r\n return move\r\n\r\n\r\n # Move on one of the sides.\r\n return chooseRandomMoveFromList(board, [1, 3, 5, 7])\r\n\r\ndef isBoardFull(board):\r\n # Return True if every space on the board has been taken. Otherwise return False.\r\n for i in range(0, 9):\r\n if isSpaceFree(board, i):\r\n return False\r\n return True\r\n \r\ndef makeMove(board, letter, move):\r\n board[move] = letter\r\n#----------------------------------------------------------------------------------\r\n\r\ndef OandX(i):\r\n if grid[i] == 1:\r\n return \"X\"\r\n if grid[i] == 0:\r\n return \" \"\r\n if grid[i] == 2:\r\n return \"O\"\r\n\r\nfor game in range(1000):\r\n grid = [0 for x in range(9)]\r\n print OandX(0),\"|\",OandX(1),\"|\",OandX(2)\r\n print \" ------- \"\r\n print OandX(3),\"|\",OandX(4),\"|\",OandX(5)\r\n print \" -------\"\r\n print OandX(6),\"|\",OandX(7),\"|\",OandX(8)\r\n print \" \"\r\n print \"Player1's turn\"\r\n \r\n firstplayer = 1\r\n occupyNum = 0\r\n count = 0\r\n end = 0\r\n win = 0\r\n grid.append(0)\r\n while count in range(0, 9) and end == 0:\r\n notOccupied = 1\r\n if firstplayer > 0:\r\n while notOccupied > 0:\r\n x= randint(0,8)\r\n grid[9] = x\r\n \r\n \r\n if grid[x] == 0:\r\n grid[x] = 1\r\n notOccupied *= -1\r\n occupyNum+=1\r\n print OandX(0),\"|\",OandX(1),\"|\",OandX(2)\r\n print \"-----------\"\r\n print OandX(3),\"|\",OandX(4),\"|\",OandX(5)\r\n print \"-----------\"\r\n print OandX(6),\"|\",OandX(7),\"|\",OandX(8)\r\n \r\n if (((grid[0] == grid[1] == grid[2]) and grid[0] != 0)or (grid[0] == grid[3] == grid[6] and grid[0] != 0) or (grid[0] == grid[4] == grid[8] and grid[0] !=0) or (grid[1] == grid[4] == grid[7] and grid [1] != 0)or (grid[2] == grid[5] == grid[8] and grid[2] != 0) or (grid[3] == grid[4] == grid[5] and grid[3] !=0) or (grid[6] == grid[7] == grid[8] and grid[6] != 0) or (grid[2] == grid[4] == grid[6] and grid[2] != 0)):\r\n print \" \"\r\n print(\"Player 1 Wins!\")\r\n print \"==============================\"\r\n print \" \"\r\n end = 1\r\n win = 1\r\n break\r\n elif occupyNum==9 and win!=1 and win !=2:\r\n win = 0\r\n print\" \"\r\n print\"Draw!\"\r\n print(\"==============================\")\r\n print(\" \")\r\n else: \r\n print \" \"\r\n print \"Player2's turn\"\r\n \r\n else:\r\n while notOccupied > 0:\r\n x = getComputerMove(grid, 'X')\r\n grid[9] = x\r\n f = open('data.txt', 'a')\r\n f.writelines(\"%s\" % item for item in grid)\r\n f.writelines(\"\\n\")\r\n f.close()\r\n if grid[x] == 0:\r\n grid[x] = 2\r\n notOccupied = notOccupied * -1\r\n occupyNum+=1\r\n print OandX(0),\"|\",OandX(1),\"|\",OandX(2)\r\n print \"-----------\"\r\n print OandX(3),\"|\",OandX(4),\"|\",OandX(5)\r\n print \"-----------\"\r\n print OandX(6),\"|\",OandX(7),\"|\",OandX(8)\r\n if (((grid[0] == grid[1] == grid[2]) and grid[0] != 0)or (grid[0] == grid[3] == grid[6] and grid[0] != 0) or (grid[0] == grid[4] == grid[8] and grid[0] !=0) or (grid[1] == grid[4] == grid[7] and grid [1] != 0)or (grid[2] == grid[5] == grid[8] and grid[2] != 0) or (grid[3] == grid[4] == grid[5] and grid[3] !=0) or (grid[6] == grid[7] == grid[8] and grid[6] != 0) or (grid[2] == grid[4] == grid[6] and grid[2] != 0)):\r\n print \" \"\r\n print(\"Player 2 Wins!\")\r\n print(\"==============================\")\r\n print(\" \")\r\n end = 1\r\n win = 2\r\n break\r\n elif occupyNum==9 and win !=1 and win !=2:\r\n win = 0\r\n print\" \"\r\n print\"Draw!\"\r\n print(\"==============================\")\r\n print(\" \")\r\n else:\r\n print \" \"\r\n print \"Player1's turn\"\r\n \r\n firstplayer = firstplayer * -1\r\n count = count+1\r\n \r\n\r\n \r\n\r\n"} {"doc_id": "3b557e9825aa7b267d57558b8dc6edf4", "text": "\"\"\"\nFile: caesar.py\nName: Charlie Liu\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 STEP 1 - get the secret number\n STEP 2 - get the ciphered string\n STEP 3 - use the secret number to reconstruct the new alphabet\n STEP 4 - solve the ciphered string\n STEP 5 - print the result\n \"\"\"\n shift_step = int(input('Secret Number is : '))\n secret = input('What\\'s the ciphered string ')\n secret_cap = secret.upper() # transfer into capital character\n new_alphabet = ALPHABET[(len(ALPHABET)-shift_step):]+ALPHABET[:(len(ALPHABET)-shift_step)]\n \"\"\"\n based on the secret number, we can shift the alphabet sequence to get the new alphabet sequence\n \"\"\"\n secret_solve = caesar_secret(secret, new_alphabet, secret_cap)\n print(secret_solve)\n\n\ndef caesar_secret(secret, new_alphabet, secret_cap):\n \"\"\"\n if the character in the secret_cap and new_alphabet is same, use the index system to pick the same index in alphabet\n and renew the secret_solve\n :param secret: is string, the ciphered string\n :param new_alphabet: the new alphabet order we change based on the secret number\n :param secret_cap: the secret word we input with capital character\n :return: string, the answer of ciphered string\n \"\"\"\n secret_solve = ''\n for i in range(len(secret)):\n for j in range(len(new_alphabet)):\n if secret_cap[i] == new_alphabet[j]: # secret_cap equal new_alphabet\n secret_solve = secret_solve + ALPHABET[j] # use the index find the word in alphabet and renew\n elif secret_cap[i] == ' ': # if we have empty string like space\n secret_solve = secret_solve + str(' ') # just direct add it for once\n break\n elif new_alphabet.find(secret_cap[i]) == -1: # if we can't find the sting, it might be special, like !\n secret_solve = secret_solve + secret_cap[i] # also direct add it once\n break\n return secret_solve # return secret_solve, the answer\n\n\n##### DO NOT EDIT THE CODE BELOW THIS LINE #####\nif __name__ == '__main__':\n main()\n"} {"doc_id": "3b6f2f3a376381c743484652d3054da5", "text": "\"\"\"Can You Exit the Maze?\nA maze can be represented by a 2D matrix, where 0s represent walkeable areas, and 1s represent walls. \nYou start on the upper left corner and the exit is on the most lower right cell.\n\nCreate a function that returns true if you can walk from one end of the maze to the other. \nYou can only move up, down, left and right. You cannot move diagonally.\n\ncan_exit([\n [0, 1, 1, 1, 1, 1, 1],\n [0, 0, 1, 1, 0, 1, 1],\n [1, 0, 0, 0, 0, 1, 1],\n [1, 1, 1, 1, 0, 0, 1],\n [1, 1, 1, 1, 1, 0, 0]\n]) -> true\n\nNotes\n\nIn a maze of size m x n, you enter at [0, 0] and exit at [m-1, n-1].\nThere can be dead ends in a maze - one exit path is sufficient.\n\"\"\"\n\ndef adj_list(pos, maze):\n a = pos[0]\n b = pos[1]\n return [(a+x, b+y) for x in range(-1, 2) for y in range(-1, 2) if 0 <= a+x and a+x < len(maze) and 0 <= b+y and b+y < len(maze[a+x]) and maze[a+x][b+y] == 0]\n\n\ndef can_exit(maze):\n start = (0, 0)\n end = (len(maze) - 1, len(maze[0]) - 1)\n queue = [start]\n visited = [start]\n while len(queue) > 0:\n current = queue.pop(0)\n adj = adj_list(current, maze)\n for next in adj:\n if next not in visited:\n queue.append(next)\n visited.append(next)\n if next == end: \n return True \n return False\n\n\nif __name__ == '__main__':\n assert can_exit([\n [0, 1, 1, 1, 1, 1, 1],\n [0, 0, 1, 1, 0, 1, 1],\n [1, 0, 0, 0, 0, 1, 1],\n [1, 1, 1, 1, 0, 0, 1],\n [1, 1, 1, 1, 1, 0, 0]\n ]) == True\n assert can_exit([\n [0, 1, 1, 1, 1, 1, 1],\n [0, 0, 1, 0, 0, 1, 1],\n [1, 0, 0, 0, 0, 1, 1],\n [1, 1, 0, 1, 0, 0, 1],\n [1, 1, 0, 0, 1, 1, 1]\n ]) == False # This maze only has dead ends!\n assert can_exit([\n [0, 1, 1, 1, 1, 0, 0],\n [0, 0, 0, 0, 1, 0, 0],\n [1, 1, 1, 0, 0, 0, 0],\n [1, 1, 1, 1, 1, 1, 0],\n [1, 1, 1, 1, 1, 1, 1]\n ]) == False # Exit only one block away, but unreachable!\n assert can_exit([\n [0, 1, 1, 1, 1, 0, 0],\n [0, 0, 0, 0, 1, 0, 0],\n [1, 1, 1, 0, 0, 0, 0],\n [1, 0, 0, 0, 1, 1, 0],\n [1, 1, 1, 1, 1, 1, 0]\n ]) == True\n print(\"All cases passed!\")\n"} {"doc_id": "3ba031809934d1d1d4feda203dfea412", "text": "import unittest\n\n\n# This is an input class. Do not edit.\nclass BinaryTree:\n def __init__(self, value, left=None, right=None, parent=None):\n self.value = value\n self.left = left\n self.right = right\n self.parent = parent\n\n# O(h) time | O(1) space\ndef findSuccessor(tree, node):\n # since we are following the sequence left - root - right, we know for a fact\n\t# that the next node to be visited is going to the leftmost node of the right subtree. This\n\t# will always be the case. If we don't have a child node, that means the parent is the successor.\n\t# However, we need to make sure that the parent is not already being visited; we can do this by\n\t# simply doing an IF condition: if node.parent.right = node then node = node.parent and repeat logic\n\t\n\tif node.right is not None:\n\t\treturn getLeftmostChild(node)\n\t\n\treturn getRightmostParent(node)\n\ndef getLeftmostChild(node):\n\tcurrentNode = node.right\n\t\n\t# we will recursively check the leftmost child of the right subtree (since we are doing in-order, we need to get the one of the left)\n\twhile currentNode.left is not None:\n\t\tcurrentNode = currentNode.left\n\t\n\treturn currentNode\n\ndef getRightmostParent(node):\n\tcurrentNode = node\n\t\n\t# First check if we have a parent; if not, we return None. otherwise, check also\n\t# that the currentnode is not the right of the parent. if it is, then keep bubbling up\n\twhile currentNode.parent is not None and currentNode.parent.right == currentNode:\n\t\tcurrentNode = currentNode.parent\n\t\n\t# return parent, since when we break the condition it didnt update the value\n\t# AND it will return none if parent is empty anyways\n\treturn currentNode.parent\n\n\n# O(n) time | O(n) space\ndef findSuccessor2(tree, node):\n # node: the node we want to find]\n\t\n\t# perform in order traversal (left-node-right)\n\tinOrderTraversalOrder = getInOrderTraversal2(tree)\n\t\n\tfor idx, currentNode in enumerate(inOrderTraversalOrder):\n\t\tif currentNode != node:\n\t\t\tcontinue\n\t\t\n\t\t# -1 because there won't be any successor (remeber previous condition)\n\t\tif idx == len(inOrderTraversalOrder) -1 :\n\t\t\treturn None\n\t\t\n\t\t# if not reaching the guards, we will return the next value\n\t\treturn inOrderTraversalOrder[idx+1]\n\ndef getInOrderTraversal2(node, order=[]):\n\tif node is None:\n\t\treturn order\n\t\n\t# We store the nodes in the order where are visited. So we will traverse to the left, then\n\t# there's no more nodes we simply return and add to our list the current node visited. we\n\t# traverse to the right following the same logic (not storing since we just want to keep looping)\n\tgetInOrderTraversal2(node.left, order)\n\t\n\t# we append the node, not the value - to compare it directly as a node object\n\torder.append(node)\n\tgetInOrderTraversal2(node.right, order)\n\t\n\t# doesnt matter if we keep it or not, since we just mutate the list over and over\n\treturn order\n\nclass TestProgram(unittest.TestCase):\n def test_case_1(self):\n root = BinaryTree(1)\n root.left = BinaryTree(2)\n root.left.parent = root\n root.right = BinaryTree(3)\n root.right.parent = root\n root.left.left = BinaryTree(4)\n root.left.left.parent = root.left\n root.left.right = BinaryTree(5)\n root.left.right.parent = root.left\n root.left.left.left = BinaryTree(6)\n root.left.left.left.parent = root.left.left\n node = root.left.right\n expected = root\n actual = findSuccessor(root, node)\n self.assertEqual(actual, expected)\n\nif __name__ == \"__main__\":\n unittest.main()\n"} {"doc_id": "3c11c57238a2e8361ada8f3f64114918", "text": "# have to import because you need it!\nimport numpy as np\n\ndef calculate_distance(pointA, pointB):\n \"\"\"\n This function calculates the distance between two points.\n\n Parameters\n ----------\n pointA, pointB: np.ndarray\n The coordinates of each point.\n\n Returns\n -------\n distance : float\n The distance between two points.\n\n Examples\n --------\n >>> r1 = np.array([0,0,0])\n >>> r2 = np.array([3,0,0])\n >>> calculate_distance(r1,r2)\n 3.0\n \"\"\"\n \n dist_vec = (pointA - pointB)\n distance = np.linalg.norm(dist_vec)\n return distance\n\ndef calculate_angle(pointA, pointB, pointC, degrees = False):\n # Calculate the angle between three points. Answer is given in radians by default, but can be given in degrees\n # by setting degrees = True\n AB = pointB - pointA\n BC = pointB - pointC\n theta = np.arccos(np.dot(AB, BC) / (np.linalg.norm(AB) * np.linalg.norm(BC)))\n\n if degrees:\n return np.degrees(theta)\n else:\n return theta\n"} {"doc_id": "3c3b8c876b2213c567ca0f55bf7839c2", "text": "'''\nGiven two strings s and t, each of which represents a non-negative rational number, return true if and only if they represent the same number. The strings may use parentheses to denote the repeating part of the rational number.\n\nA rational number can be represented using up to three parts: , , and a . The number will be represented in one of the following three ways:\n\n\nFor example, 12, 0, and 123.\n<.>\nFor example, 0.5, 1., 2.12, and 123.0001.\n<.><(><)>\nFor example, 0.1(6), 1.(9), 123.00(1212).\nThe repeating portion of a decimal expansion is conventionally denoted within a pair of round brackets. For example:\n\n1/6 = 0.16666666... = 0.1(6) = 0.1666(6) = 0.166(66).\n \n '''\n\n def isRationalEqual(self, S, T):\n def f(s):\n i = s.find('(')\n if i >= 0:\n s = s[:i] + s[i + 1:-1] * 20\n return float(s[:20])\n return f(S) == f(T)\n \n------------------------------------------\nclass Solution:\n # inspired from:\n # https://coolconversion.com/math/recurring-decimals-as-a-fraction/\n # to which we wouldn't have access during interview.\n\n import typing\n def isRationalEqual(self, s: str, t: str) -> bool:\n\n # intuition:\n # write each numbes as fraction: num / den\n # then compare the two fractions.\n \n num1, den1 = self.toFraction(s)\n num2, den2 = self.toFraction(t)\n \n return den1 * num2 == den2 * num1\n \n def toFraction(self, s: str) -> typing.Tuple[int, int]:\n if \".\" not in s:\n return int(s), 1\n \n intp, frac = s.split(\".\")\n # decimal dot, but no repeating part:\n # xyz.abc = xyzabc / 1000\n if \"(\" not in frac:\n ifrac = int(frac) if len(frac) > 0 else 0\n num = int(intp) * (10 ** len(frac)) + ifrac\n den = 10 ** len(frac)\n return num, den\n \n # this is for cases like a.b(c)\n # let n = a.b(c) \n # then, 10^(len(b+c)) * n = abc.(c)\n # and 10^(len(b)) * n = ab.(c)\n # subtract the two, and solve for n:\n # n = (abc - ab) / (10^len(b + c) - 10^len(b))\n frac, repfrac = frac.split(\"(\")\n repfrac = repfrac[:-1]\n \n iintp = int(intp)\n ifrac = int(frac) if len(frac) > 0 else 0\n irep = int(repfrac)\n \n return (\n (iintp * (10 ** (len(frac + repfrac))) + ifrac * 10 ** len(repfrac) + irep) - (iintp * 10 ** len(frac) + ifrac),\n (10** len(frac+repfrac) - 10 **len(frac))\n )\n"} {"doc_id": "3c41a1afca77339338dc44764f958488", "text": "from .Node import TreeNode\n\n\nclass BinaryTree:\n \"\"\"\n A custom class for a BinaryTree\n\n Methods\n -------\n isEmpty()\n Return true if tree is empty else false.\n\n add(element)\n Add element to tree.\n\n getRoot()\n Get the root value.\n\n getMaxValue()\n Get the rightmost subtree.\n\n getMinValue()\n Get the leftmost subtree.\n\n preOrder(function)\n Do preorder tree traversal, starting from the root and further from the left subtree followed by the right.\n\n Algorithm Preorder(tree)\n 1. Visit the root.\n 2. Traverse the left subtree, i.e., call preOrder(left-subtree)\n 3. Traverse the right subtree, i.e., call preOrder(right-subtree)\n\n inOrder(function)\n Do inorder tree traversal\n Algorithm Inorder(tree)\n 1. Traverse the left subtree, i.e., call Inorder(left-subtree)\n 2. Visit the root.\n 3. Traverse the right subtree, i.e., call Inorder(right-subtree)\n\n postOrder(function)\n Do postorder tree traversal, starting with the leftmost child and gradually moving to the rightmost child.\n\n Algorithm Postorder(tree)\n 1. Traverse the left subtree, i.e., call Postorder(left-subtree)\n 2. Traverse the right subtree, i.e., call Postorder(right-subtree)\n 3. Visit the root.\n\n print()\n Print out the current queue to the console in inOrder traveling.\n \"\"\"\n\n def __init__(self, rootValue=None) -> None:\n \"\"\"If initialized using root, the rest of the descendants will branch out from it.\n\n Parameters\n ----------\n rootValue : any\n The root value of Tree.\n \"\"\"\n self.__root = None if rootValue is None else TreeNode(rootValue)\n\n def isEmpty(self) -> bool:\n \"\"\"\n Verify that the tree is empty.\n\n Returns\n -------\n bool :\n whether the tree is empty or not\n \"\"\"\n return self.__root is None\n\n def getRoot(self):\n \"\"\"\n Get the root value.\n \n Returns\n -------\n root value.\n \"\"\"\n if self.__root is None:\n return None\n return self.__root.data\n\n def getMaxValue(self):\n \"\"\"\n Get the value of the rightmost node in the tree.\n\n Returns\n -------\n maximum value in tree.\n \"\"\"\n if self.__root is None:\n return None\n return self.__root.getMaxValue()\n\n def getMinValue(self):\n \"\"\"\n Get the value of the leftmost node in the tree.\n\n Returns\n -------\n minimum value in tree.\n \"\"\"\n if self.__root is None:\n return None\n return self.__root.getMinValue()\n\n def preOrder(self, function) -> None:\n \"\"\"\n Do preorder tree traversal, starting from the root and further from the left subtree followed by the right.\n\n Algorithm Preorder(tree)\n 1. Visit the root.\n 2. Traverse the left subtree, i.e., call preOrder(left-subtree)\n 3. Traverse the right subtree, i.e., call preOrder(right-subtree)\n\n Parameters\n ----------\n function : \n Function with one argument to apply on each element of the tree.\n \"\"\"\n current = self.__root\n\n if current is None:\n return\n else:\n self.__preOrder(current, function)\n\n def __preOrder(self, node: TreeNode, function) -> None:\n \"\"\"\n Do preorder tree traversal, starting from the root and further from the left subtree followed by the right.\n\n Parameters\n ----------\n node : TreeNode\n current node (subtree) in tree.\n\n function : \n function with one argument to apply on each element of the tree.\n \"\"\"\n if node is None:\n return\n\n function(node.data)\n self.__preOrder(node.left, function)\n self.__preOrder(node.right, function)\n\n def inOrder(self, function) -> None:\n \"\"\"\n Do inorder tree traversal\n\n Algorithm Inorder(tree)\n 1. Traverse the left subtree, i.e., call Inorder(left-subtree)\n 2. Visit the root.\n 3. Traverse the right subtree, i.e., call Inorder(right-subtree)\n\n Parameters\n ----------\n function\n function with one argument to apply on each element of the tree.\n \"\"\"\n current = self.__root\n\n if current is None:\n return\n else:\n self.__inOrder(current, function)\n\n def __inOrder(self, node: TreeNode, function) -> None:\n \"\"\"\n Do inorder tree traversal\n\n Parameters\n ----------\n node : TreeNode\n current node (subtree) in tree.\n\n function\n function with one argument to apply on each element of the tree.\n \"\"\"\n if node is None:\n return\n\n self.__inOrder(node.left, function)\n function(node.data)\n self.__inOrder(node.right, function)\n\n def postOrder(self, function) -> None:\n \"\"\"\n Do postorder tree traversal, starting with the leftmost child and gradually moving to the rightmost child.\n\n Algorithm Postorder(tree)\n 1. Traverse the left subtree, i.e., call Postorder(left-subtree)\n 2. Traverse the right subtree, i.e., call Postorder(right-subtree)\n 3. Visit the root.\n\n Parameters\n ----------\n function\n function with one argument to apply on each element of the tree.\n \"\"\"\n current = self.__root\n\n if current is None:\n return\n else:\n self.__postOrder(current, function)\n\n def __postOrder(self, node: TreeNode, function) -> None:\n \"\"\"\n Do postorder tree traversal, starting with the leftmost child and gradually moving to the rightmost child.\n\n Parameters\n ----------\n node : TreeNode\n current node (subtree) in tree.\n\n function\n function with one argument to apply on each element of the tree.\n \"\"\"\n if node is None:\n return\n\n self.__postOrder(node.left, function)\n self.__postOrder(node.right, function)\n function(node.data)\n\n def add(self, element) -> bool:\n \"\"\"\n Add an element to the tree.\n\n Parameters\n ----------\n element : any\n element to add to the tree.\n\n Returns\n -------\n bool\n whether the element is added to tree or not\n \"\"\"\n if element is None:\n return False\n elif type(element) is not TreeNode:\n element = TreeNode(element)\n\n if self.__root is None:\n self.__root = element\n return True\n\n self.__root.add(element)\n\n def print(self) -> None:\n \"\"\"\n Print out the current queue to the console in inOrder traveling.\n \"\"\"\n\n self.__print(self.__root, 0)\n\n def __print(self, node, numberChildInTree) -> None:\n \"\"\"\n Print out the current queue to the console in inOrder traveling.\n\n Parameters\n ----------\n node : TreeNode\n current node (subtree) in tree.\n\n numberChildInTree\n node number in the tree to output characters to the console.\n \"\"\"\n if node is None:\n return\n\n self.__print(node.left, numberChildInTree + 1)\n for _ in range(numberChildInTree):\n print('-', end='')\n print(node.data)\n self.__print(node.right, numberChildInTree + 1)\n"} {"doc_id": "3c4fa5b3e8c46c86a91f97514e2a17c7", "text": "\"\"\"\nFile: hailstone.py\nName: \u9ec3\u79d1\u8afa\n-----------------------\nThis program should implement a console program that simulates\nthe execution of the Hailstone sequence, defined by Douglas\nHofstadter. Output format should match what is shown in the sample\nrun in the Assignment 2 Handout.\n\"\"\"\n\n\ndef main():\n \"\"\"\n Input: A natural number\n Output: Print all the Hailstone sequences the number gone through and the steps it took to reach 1\n \"\"\"\n pass\n print('This program computes Hailstone sequences.')\n print('')\n number = int(input('Enter a number: '))\n if number==1:\n print('It took 0 steps to reach 1.')\n else:\n steps=0\n while True:\n if number%2==1:\n odd_number=int(number*3+1)\n print(str(number)+' is odd, so I make 3n+1: '+str(odd_number))\n number=odd_number\n steps = int(steps+1)\n else:\n even_number=int(number/2)\n print(str(number)+' is even, so I take half: '+str(even_number))\n number=even_number\n steps = int(steps+1)\n if number==1:\n print('It took '+str(steps)+' steps to reach 1.')\n break\n\n\n\n###### DO NOT EDIT CODE BELOW THIS LINE ######\n\nif __name__ == \"__main__\":\n main()\n"} {"doc_id": "3c8d097c3e82e0aa31f0be02529ead56", "text": "\"\"\"\nFile: caesar.py\nname : Che-Hsien, Chiu\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 decipher a secret string\n \"\"\"\n n = int(input ('Secret number: '))\n secret_string = input('What\\'s the ciphered string: ')\n print('The deciphered string is :' +decipher(secret_string, n))\n\n\ndef decipher(secret_string, n):\n \"\"\"\n translating old alphabet to new alphabet by shifting n position\n :param secret_string: string\n :param n: integer\n :return: string\n \"\"\"\n # create empty string\n deciphered_string = ''\n\n # convert every character in secret string\n for i in secret_string:\n if i.isalpha():\n # find i's position in ALPHABET with case-insensitive way\n position = ALPHABET.find(i.upper())\n deciphered_string += ALPHABET[(position+n)%26] # use the remainder to find the character\n else:\n deciphered_string += i\n return deciphered_string\n\n\n##### DO NOT EDIT THE CODE BELOW THIS LINE #####\nif __name__ == '__main__':\n# n = 7\n# secret_string = 'rHn TKx MAx UXlM!'\n main()\n"} {"doc_id": "3c92af788f3f26902d5183a60de4220f", "text": "\"\"\"\n

Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2, also represented as a string.

\n\n

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\n
    \n\t
  1. The length of both num1 and num2 is < 110.
  2. \n\t
  3. Both num1 and num2 contain only digits 0-9.
  4. \n\t
  5. Both num1 and num2 do not contain any leading zero, except the number 0 itself.
  6. \n\t
  7. You must not use any built-in BigInteger library or convert the inputs to integer directly.
  8. \n
\n

\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

\n\n

\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\n
    \n\t
  1. num1 \u548c num2 \u7684\u957f\u5ea6\u5c0f\u4e8e110\u3002
  2. \n\t
  3. num1 \u548c num2 \u53ea\u5305\u542b\u6570\u5b57 0-9\u3002
  4. \n\t
  5. num1 \u548c num2 \u5747\u4e0d\u4ee5\u96f6\u5f00\u5934\uff0c\u9664\u975e\u662f\u6570\u5b57 0 \u672c\u8eab\u3002
  6. \n\t
  7. \u4e0d\u80fd\u4f7f\u7528\u4efb\u4f55\u6807\u51c6\u5e93\u7684\u5927\u6570\u7c7b\u578b\uff08\u6bd4\u5982 BigInteger\uff09\u6216\u76f4\u63a5\u5c06\u8f93\u5165\u8f6c\u6362\u4e3a\u6574\u6570\u6765\u5904\u7406\u3002
  8. \n
\n

\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

\n\n

\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\n
    \n\t
  1. num1 \u548c num2 \u7684\u957f\u5ea6\u5c0f\u4e8e110\u3002
  2. \n\t
  3. num1 \u548c num2 \u53ea\u5305\u542b\u6570\u5b57 0-9\u3002
  4. \n\t
  5. num1 \u548c num2 \u5747\u4e0d\u4ee5\u96f6\u5f00\u5934\uff0c\u9664\u975e\u662f\u6570\u5b57 0 \u672c\u8eab\u3002
  6. \n\t
  7. \u4e0d\u80fd\u4f7f\u7528\u4efb\u4f55\u6807\u51c6\u5e93\u7684\u5927\u6570\u7c7b\u578b\uff08\u6bd4\u5982 BigInteger\uff09\u6216\u76f4\u63a5\u5c06\u8f93\u5165\u8f6c\u6362\u4e3a\u6574\u6570\u6765\u5904\u7406\u3002
  8. \n
\n\"\"\"\n\n\nclass Solution:\n def multiply(self, num1, num2):\n \"\"\"\n :type num1: str\n :type num2: str\n :rtype: str\n \"\"\"\n "} {"doc_id": "3ca511502c9a75965ae957ad3269aadb", "text": "from board import Board\nfrom card import Card\n\nclass Game():\n\n def __init__(self):\n self.board = Board()\n print(self.board)\n\n def play(self):\n while True:\n print(\"=======================================\")\n print(\"\\t1. Pick card from stock\")\n print(\"\\t2. Pick card from waste\")\n print(\"\\t3. Pick card from tableau\")\n print(\"\\t4. Pick card from foundation\")\n print(\"\\t99. Quit\")\n print(\"\\n\")\n\n choice = raw_input(\"What to do?\")\n\n if (choice == \"1\"):\n self.board.pickCardFromStock()\n elif (choice == \"2\"):\n destination = raw_input(\"Where do you want to put the card? (H/C/S/D/1-7) :\")\n self.board.moveCardFromWaste(destination)\n elif (choice == \"3\"):\n print(\"select a card\")\n value = raw_input(\"value (1-10/J/Q/K) :\")\n symbol = raw_input(\"Symbole (H/S/C/D) :\") \n card = Card(symbol, value)\n destination = raw_input(\"Where do you want to put the card? (H/C/S/D/1-7) :\")\n self.board.moveCardFromTableau(card, destination)\n elif (choice == \"4\"):\n foundation = raw_input(\"select a color (H/S/C/D) :\")\n destination = raw_input(\"Where do you want to put the card? (1-7) :\")\n self.board.moveCardFromFoundation(foundation, destination)\n elif (choice == \"99\"):\n break\n else:\n print(\"Incorrect choice\")\n\n print(self.board)\n\n"} {"doc_id": "3d0ac239b24e7ffdf79a7f5789729b79", "text": "# Title: player.py\n# Description: Contains the Player class for Super Square Boy 2.\n# Author: Alexander Marcozzi\n# Date: 06/12/2021\n\nimport pygame\nfrom game.block import Block\nfrom game.blocktype import BlockType\n\nclass Player(Block):\n \"\"\"\n A class representing the player. Inherits from Block.\n\n All \"magic numbers\" and formulas were acquired from manual testing.\n\n ...\n\n Attributes\n ----------\n max_speed : int\n the maximum speed achievable (essentially terminal velocity)\n base_image : pygame image surface\n the image representing the player\n total_angle : int\n the angle that the player's block should be rotate\n\n Methods\n -------\n update(dt)\n Updates the position of the player\n draw(screen, fade_pct)\n Draws the player onto the screen\n rotate(angle)\n Rotates the player clockwise a specified number of degrees\n resetRotation()\n Resets the player's rotation angle back to 0\n jump()\n Increases the player's vertical speed, simulating a jump\n \"\"\"\n\n def __init__(self, blockrect, speed, image_path):\n \"\"\"\n Parameters\n ----------\n blockrect : pygame.Rect\n A pygame rectangle object that holds the positional and spatial\n information of the block\n speed : float\n The speed at which the block will move in the X and Y directions\n image_path : str\n The file path of the player image\n \"\"\"\n Block.__init__(self, blockrect, speed, (0,0,0), BlockType.BLOCK)\n self.max_speed = blockrect.width / 20\n self.base_image = pygame.image.load(image_path)\n self.base_image = pygame.transform.smoothscale(\n self.base_image, (blockrect.width, blockrect.height))\n self.total_angle = 0\n\n def update(self, dt):\n \"\"\"\n Updates the position of the player.\n\n Each call, the player's vertical speed will be reduced, until a certain\n point, simulating gravity.\n\n Parameters\n ----------\n dt : int\n The clock's tick rate\n \"\"\"\n Block.update(self, dt)\n if (self.speed[1] < self.max_speed):\n self.speed[1] += (dt / 3200.0) * self.blockrect.width # gravity\n\n def draw(self, screen, fade_pct):\n \"\"\"\n Draws the player onto the screen.\n\n Adjusts the image's alpha based on the passed in fade percentage.\n\n Parameters\n ----------\n screen : pygame display surface\n The screen to draw onto\n fade_pct : float\n The amount the block should appear faded. 0 being no fade and 1\n being fully faded\n \"\"\"\n image = pygame.transform.rotate(self.base_image, self.total_angle)\n new_rect = image.get_rect(center = self.blockrect.center)\n image.set_alpha(255 * (1 - fade_pct))\n screen.blit(image, new_rect)\n\n def rotate(self, angle):\n \"\"\"\n Rotates the player clockwise a specified number of degrees.\n\n Parameters\n ----------\n angle: int\n The angle the player should be rotated\n \"\"\"\n self.total_angle += angle\n\n def resetRotation(self):\n \"\"\"\n Resets the player's rotation angle back to 0.\n \"\"\"\n self.total_angle = 0\n \n def jump(self):\n \"\"\"\n Increases the player's vertical speed, simulating a jump.\n \"\"\"\n self.speed[1] = -self.max_speed\n"} {"doc_id": "3d23dc277048074fd848c5ebd2e0620c", "text": "# Intermediate Programming in python\n# This source code is my practical learning programming in python\n# Muhammad Adisatriyo Pratama - October 2020\n\n\n# (1) Import statement and working with dates (use and format date)\n\n# import datetime module in python\nfrom datetime import datetime\nfrom datetime import date\n\nimport math # import library in python\n# another example\nfrom math import pi # (only import certain module)\nstring = 'Hello World'\nprint(string.upper()) # example of a built in function in python\nprint(math.pi, math.cos(1)) # usage of the math library in python\n\n\ndef area_of_circle(r):\n return r*r*pi # using 'pi' instead of math.pi\n\n\nprint(f'Area of a circle with 10 radius = {area_of_circle(10)}')\nprint('================')\n\n\n# Dates\nprint(datetime.now()) # print current date and time\nprint(date.today()) # print current date\nprint(datetime.now().time()) # print current time\nprint('================')\n\n\n# Formatting dates\n# %d = date of month, %m = month(num), %b = month name (short),\n# %B = month name, %Y = year, %M = minutes, %S = seconds\nnow = datetime.now().strftime(\"%d/%m/%Y %H:%M:%S\") # dd/mm/YYYY HH:MM:SS\nnow2 = datetime.now().strftime(\"%d-%b-%Y %H:%M:%S\") # dd-bbb-YYYY HH:MM:SS\nprint(now)\nprint(now2)\n"} {"doc_id": "3d259f69f084cea557d5809355261730", "text": "'''\n==============\nPython File IO\n==============\nFiles are one of the building blocks of persistend storage in Computers\nWe will see some of the basic files handling methods in Python\n'''\n\n'''\n1. File name and Path\n=====================\nA typical file in any computing platform will have a name (w/ extension),\nand a path to reach the file from root file system.\nThis is same for python as well. When we create a file,\nthe path and file name coexist.\n'''\n# somefile = '/home/catman/Downloads/catman.txt'\n\n'''\n2. OS module\nThe OS module of python helps work with file paths and a lot of cool features\nthat OS already has to operate with on files.\nSay like, rename, move, path, checking if a file exists and so on.\n'''\n# import os\n\n# print('You application is currently running at path: %s' % os.getcwd())\n# print('Catman file exists? %s' % os.path.exists(somefile))\n# print('catman.txt is actually a file? %s' % os.path.isfile(somefile))\n\n'''\n1. Create, write and read\n=========================\nYou can create a file just by using a random name.\nLet's do it a bit professionally, so that no matter from where you run, the path is \nalways relative to the working directory\n\nFile modes:\n-----------\n'r' This is the default mode. It Opens file for reading.\n\n'w' This Mode Opens file for writing.\n If file does not exist, it creates a new file.\n If file exists it truncates the file.\n\n'x' Creates a new file. If file already exists, the operation fails.\n\n'a' Open file in append mode.\n If file does not exist, it creates a new file.\n\n't' This is the default mode. It opens in text mode.\n\n'b' This opens in binary mode.\n\n'+' This will open a file for reading and writing (updating)\n\neg.: \n\nourfile = open(filename, mode)\n'''\n# somefile_path = os.path.join(os.getcwd(), 'catman.txt')\n'''\nCreate if not exist with any mode that involves a or w to \n'''\n# somefile = open(somefile_path, 'w+')\n\n'''\nRead when opened with mode r or + \n'''\n# print('Empty file ready: \\n%s' % somefile.read())\n\n'''\nWrite\n'''\n# lorem_ipsum = \"Lorem ipsum dolor sit amet, consectetur adipiscing elit,\"\\\n# \" sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.\"\\\n# \" Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris \"\\\n# \"nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in \"\\\n# \"reprehenderit in voluptate velit esse cillum dolore eu fugiat \"\\\n# \"nulla pariatur. Excepteur sint occaecat cupidatat non proident, \"\\\n# \"sunt in culpa qui officia deserunt mollit anim id est laborum.\"\n\n# somefile.write(lorem_ipsum)\n# somefile.close()\n\n'''\nFile context and 'with'\n\nContext is like a closed scope area in python which closes itself outside\nthe indendation of the code snippet\n'''\n# with open(somefile_path, 'w+') as somefile:\n# lorem_ipsum = \"Lorem ipsum dolor sit amet, consectetur adipiscing elit,\"\\\n# \" sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.\"\\\n# \" Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris \"\\\n# \"nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in \"\\\n# \"reprehenderit in voluptate velit esse cillum dolore eu fugiat \"\\\n# \"nulla pariatur. Excepteur sint occaecat cupidatat non proident, \"\\\n# \"sunt in culpa qui officia deserunt mollit anim id est laborum.\"\n\n# somefile.write(lorem_ipsum)\n\n'''\nNote that we did not use a .close() as the with context will close the file as soon\nas it gets out of context we are using 'somefile'\n'''\n"} {"doc_id": "3d548c7a46c3479ba5724aefc44ec670", "text": "'''\n\ub144, \uc6d4, \uc77c\uc744 \uc785\ub825\ubc1b\uc73c\uba74 \uc694\uc77c\uc744 \ucd9c\ub825\ud574\uc8fc\ub294 \ud504\ub85c\uadf8\ub7a8\n'''\n\nimport sys\nimport pytest\n\n\ndef is_leap_year(year):\n if year % 4 == 0:\n if year % 100 != 0:\n return True\n elif year % 400 == 0:\n return True\n\n return False\n\n\ndef test_find_day_string():\n assert 'Tuesday' == find_day_string(2019, 1, 1)\n assert 'Sunday' == find_day_string(2019, 4, 28)\n assert 'Wednesday' == find_day_string(2018, 10, 17)\n\n\ndef find_day_string(year, month, date):\n\n # 2019/1/1: Tuesday\n day_string = [\n 'Tuesday',\n 'Wednesday',\n 'Thursday',\n 'Friday',\n 'Saturday',\n 'Sunday',\n 'Monday',\n ]\n\n days = 0\n y = beforeYear = min(year, 2019)\n afterYear = max(year, 2019)\n\n while (y < afterYear):\n if is_leap_year(y):\n days += 366\n\n else:\n days += 365\n\n y += 1\n\n if year < 2019:\n days = -days\n\n m = 1\n while (m < month):\n if m == 2:\n if is_leap_year(year):\n days += 29\n\n else:\n days += 28\n\n elif m == 1:\n days += 31\n\n elif m == 3:\n days += 31\n\n elif m == 5:\n days += 31\n\n elif m == 7:\n days += 31\n\n elif m == 8:\n days += 31\n\n elif m == 10:\n days += 31\n\n elif m == 12:\n days += 31\n\n else:\n days += 30\n\n m += 1\n\n days += date - 1\n\n return day_string[days % 7]\n\n\nif __name__ == \"__main__\":\n if len(sys.argv) - 1 != 3:\n print(\"give 3 integers for year, month, date as arguments.\")\n\n else:\n year, month, date = map(int, sys.argv[1:])\n\n print(find_day_string(year, month, date))\n"} {"doc_id": "3d76fbe2da0ba7589ec2d09ea005839b", "text": "\"\"\"\nFile: anagram.py\nName:\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\"\"\"\nimport time\n# Constants\nFILE = 'dictionary.txt' # This is the filename of an English dictionary\nEXIT = '-1' # Controls when to stop the loop\n\n# Global variable\npython_dict = {}\n\n\ndef main():\n print(f'Welcome to stanCode \"Anagram Generator\" (or {EXIT} to quit)')\n count = 0\n while True:\n searching = case_insensitive(input('Find anagrams for: '))\n\n # Timer\n t1 = time.time()\n\n # read_dictionary\n read_dictionary(searching)\n\n # If -1, quit\n if searching == EXIT:\n break\n\n # Print\n print('Searching...')\n ans_lst = find_anagrams(searching)[0]\n for anagram in ans_lst:\n print('Found: ', anagram)\n print('Searching...')\n print(f'{len(ans_lst)} anagrams:', ans_lst)\n print(find_anagrams(searching)[1])\n # Timer\n t2 = time.time()\n print(t2-t1)\n\n\ndef check_dict_word(word, target):\n \"\"\"\n Check dict word. If one character not in searching word, then not add the word to python_dict.\n :param word: str, word in dictionary.txt.\n :param target: str, the searching word\n :return: True, all character within are in searching word.\n \"\"\"\n # Level one: check len\n if len(word) == len(target):\n # Check all the word: contains -> contains, contais\n for ch in word:\n if ch not in target:\n return False\n else:\n if ch == word[len(word)-1]:\n return True\n\n\ndef read_dictionary(target):\n \"\"\"\n Read the dictionary.txt and turn it into a list.\n :return: list, a python list.\n \"\"\"\n count_dic_lst = [0]\n with open(FILE, 'r') as f:\n for line in f:\n word = line.strip()\n # All character within are in searching word\n if check_dict_word(word, target):\n # Create key for dict\n if len(word) == 1: # One character\n dict_key = word\n else:\n dict_key = word[0:2] # The first two word\n # Add word to python_dict\n if dict_key in python_dict:\n python_dict[dict_key].append(word)\n else:\n python_dict[dict_key] = [word]\n return python_dict\n\n\ndef find_anagrams(s):\n \"\"\"\n :param s: str, searching word.\n :return: list, find all the anagram.\n \"\"\"\n ans_lst = []\n count_lst = [0]\n duplicate_lst = []\n # Make the string become a list\n s_lst = []\n for i in s:\n s_lst.append(i)\n ans_len = len(s)\n # Sort the lst\n # s_lst.sort()\n # Helper\n helper(s_lst, '', ans_lst, ans_len, count_lst, duplicate_lst)\n return ans_lst, count_lst\n\n\ndef helper(word, anagram_word, ans_lst, ans_len, count_lst, duplicate_lst):\n \"\"\"\n :param word: str, the searching word.\n :param anagram_word: str, anagram.\n :param ans_lst: list, all the anagrams.\n :param ans_len: int, the length of the original word.\n :param count_lst: list, count how many time helper has been called.\n :param duplicate_lst\n :return: list, all anagram.\n \"\"\"\n count_lst[0] += 1\n\n if len(anagram_word) == ans_len:\n if len(anagram_word) > 2:\n if anagram_word in python_dict[anagram_word[:2]]:\n ans_lst.append(anagram_word)\n else:\n # Pruning\n if has_prefix(anagram_word):\n # Choose\n for i in range(len(word)):\n ch = word[i]\n # Pruning\n if duplicate(duplicate_lst, ch, anagram_word):\n break\n word.pop(i)\n # Explore\n helper(word, anagram_word+ch, ans_lst, ans_len, count_lst, duplicate_lst)\n # Un-choose\n word.insert(i, ch)\n # Sort is to make append back to the original place to make it self-similar\n\n\n # for ch in word:\n # anagram_word.append()\n\n\ndef has_prefix(sub_s):\n \"\"\"\n Everytime add a ch to the str, check if the current str in dictionary.\n :param sub_s: The first few words from all the possible two-words from searching word.\n :return: True or False, No word in the dictionary starts with sub_s, vice versa.\n \"\"\"\n # find everytime version\n if len(sub_s) <= 1:\n return True\n if len(sub_s) == 2:\n return sub_s in python_dict\n # Already confirm key in python_dict\n elif len(sub_s) > 2:\n checking_lst = python_dict[sub_s[:2]]\n for dict_word in checking_lst:\n if dict_word.startswith(sub_s):\n return True\n\n\ndef duplicate(duplicate_lst, ch, sub_s):\n \"\"\"\n True means sub_s+ch is already run.\n :param duplicate_lst: list, the sub_s may be duplicated.\n :param ch: str, ch about to add into sub_s.\n :param sub_s: str, current_s.\n :return: True.\n \"\"\"\n new_sub_s = sub_s+ch\n if new_sub_s in duplicate_lst:\n return True\n # If the word has the same element, add it to duplicate_lst\n elif ch in sub_s:\n duplicate_lst.append(new_sub_s)\n return False\n\n\ndef case_insensitive(string):\n \"\"\"\n :param string: str, a character.\n :return: lst, a lower character lst.\n \"\"\"\n new_string = ''\n for ch in string:\n if ch.islower():\n new_string += ch\n else:\n new_string += ch.lower()\n return new_string\n\n\n\n\nif __name__ == '__main__':\n main()\n"} {"doc_id": "3db3bb6cd0c86bf13f9b2e205bb54a46", "text": "\"\"\"cicero.py em 2018-10-04. Projeto Practice Python.\n\nFun\u00e7\u00f5es para uso geral\n\n\"\"\"\n\n\ndef so_numero(mensagem: str) -> int:\n \"\"\" Verifica se a entrada \u00e9 um valor inteiro\n\n :param mensagem: string com uma mensagem\n :type mensagem: str\n :return: valor inteiro ou mensagem de erro\n :rtype: int\n \"\"\"\n while True:\n try:\n entrada_usuario = int(input(mensagem))\n except ValueError:\n print('Digite um n\u00famero inteiro. Tente novamente!')\n continue\n else:\n return entrada_usuario\n\n\ndef cabecalho(titulo: str, caracteres: int = 50, tipo: str = '='):\n \"\"\"Imprime um cabe\u00e7alho\n\n :param titulo: t\u00edtulo\n :type titulo: str\n :param caracteres: n\u00famero de caracteres do t\u00edtulo\n :type caracteres: int\n :param tipo: tipo de caracter de prenchimento\n :type tipo: str\n \"\"\"\n print()\n print(f' {titulo} '.title().center(caracteres, tipo))\n print()\n\n\ndef cores(cor: str) -> str:\n \"\"\"dicion\u00e1rio com c\u00f3digos de escape sequence ANSI para configurar cores\n\n :param cor: nome da cor\n :type cor: str\n :return: cor do dicion\u00e1rio\n :rtype: str\n \"\"\"\n dicionario = {'limpa': '\\033[m',\n 'vermelho': '\\033[1;31m',\n 'verde': '\\033[1;32m',\n 'amarelo': '\\033[1;33m',\n 'azul': '\\033[1;34m',\n 'sublinhado': '\\033[4m',\n 'bold': '\\033[1;30m',\n 'pretoBranco': '\\033[7;30m'}\n return dicionario[cor]\n\n\n# -------------------- programa de teste --------------------\n\ndef _gerador_teste(n, funcao, args):\n from time import time\n print(n, 'vezes', funcao.__name__)\n t0 = time()\n for i in range(n):\n funcao(*args)\n t1 = time()\n print(round(t1 - t0, 3), 'segundos,')\n\n\ndef _teste(n=2000):\n _gerador_teste(n, so_numero, 'Digite um n\u00famero: ')\n\n\nif __name__ == '__main__':\n print(f'{cores(\"sublinhado\")}teste{cores(\"limpa\")}')\n print(f'{cores(\"azul\")}teste{cores(\"limpa\")}')\n print(f'{cores(\"pretoBranco\")}teste{cores(\"limpa\")}')\n print(__doc__)\n print()\n print(so_numero.__name__)\n print(so_numero.__doc__)\n print(f'Defaults: {so_numero.__defaults__}')\n print()\n print(cabecalho.__name__)\n print(cabecalho.__doc__)\n print(f'Defaults: {cabecalho.__defaults__}')\n print()\n print(cores.__name__)\n print(cores.__doc__)\n print(f'Defaults: {cores.__defaults__}')\n # _teste()\n"} {"doc_id": "3dc8fa1924aadd761be6e4351d90e8f4", "text": "\"\"\"\r\nPassword Validator\r\n\r\nA valid password is the one that conforms to the following rules:\r\n - Minimum length is 5;\r\n - Maximum length is 10;\r\n - Should contain at least one number;\r\n - Should contain at least one special character (such as &, +, @, $, #, %, etc.);\r\n - Should not contain spaces.\r\n\r\nExamples:\r\nInput: \"Sololearn\"\r\nOutput: false\r\n\r\nInput: \"John Doe\"\r\nOutput: false\r\n\r\nInput: \"$ololearn7\"\r\nOutput: true\r\n\r\nWrite a program to checks if the user input is a valid password or not.\r\n\"\"\"\r\nimport string #imports string module\r\n\r\np=input('Enter the password: ')\r\n\r\nprint((4 0:\n level, parent, u = queue.popleft()\n if u in levels:\n continue\n else:\n levels[u] = level\n parents[u] = parent\n for v in adjacency_list[u]:\n queue.append((level + 1, u, v))\n return (levels, parents)\n\n"} {"doc_id": "3dfd128b0f4a463a8222002eb342a7cd", "text": "\"\"\"Stack-like data structures.\n\nClasses\n-------\n\nStack:\n Basic stack data structure.\n\nTypeRestrictedStack:\n Stack that only allow instances of a certain class to be\n pushed.\n\"\"\"\n\n__all__ = ['Stack', 'TypeRestrictedStack']\n\nimport inspect\nfrom typing import NoReturn, Any, Type, Optional\nfrom data_structures.elements import Number\n\n\nclass Stack:\n \"\"\"Basic stack data structure.\n\n Stacks are a type data structures that contains items with the\n following two rules:\n - items can only be added to the stack from the \"top\"\n - items can only be removed from the stack from the \"top\"\n\n Methods\n -------\n push:\n Push a new item to the top of the stack.\n\n pop:\n Removes the top item from the stack and returns it.\n\n peak:\n Returns the top item of the stack without removing it.\n\n size:\n Length of the list of items currently in the stack.\n \"\"\"\n\n def __init__(self) -> NoReturn:\n \"\"\"Initializes an empty items list for the stack.\"\"\"\n\n self._items = []\n\n def push(self, new_item: Any) -> NoReturn:\n \"\"\"Push a new item to the top of the stack.\n\n Parameters\n ----------\n new_item: any\n An item to push to the top to the stack, could be anything.\n \"\"\"\n\n self._items.append(new_item)\n\n def pop(self) -> Any:\n \"\"\"Removes the top item from the stack and returns it.\n\n Returns\n -------\n top_item: Any\n The item at the top of the stack, prior to removal.\n\n Raises\n ------\n IndexError:\n When the stack is empty.\n \"\"\"\n\n try:\n top_item = self._items.pop()\n return top_item\n except IndexError:\n raise IndexError(\"Empty Stack\")\n\n def peak(self) -> Any:\n \"\"\"Returns the top item of the stack without removing it.\n\n Returns\n -------\n top_item: Any\n The item at the top of the stack.\n\n Raises\n ------\n IndexError:\n When the stack is empty.\n \"\"\"\n\n try:\n top_item = self._items[-1]\n return top_item\n except IndexError:\n raise IndexError(\"Empty Stack\")\n\n def size(self) -> int:\n \"\"\"Length of the list of items currently in the stack.\"\"\"\n\n return len(self._items)\n\n def __repr__(self) -> str:\n if self.size() == 0:\n return \"Empty \" + str(self.__class__.__name__)\n print_val = (\"Stack Elements: \"\n + \"; \".join([str(item) for item in self._items]))\n return print_val\n\n\nclass TypeRestrictedStack(Stack):\n \"\"\"Stack that only allow instances of a certain class to be pushed.\n\n Properties\n ----------\n acceptable_class: any class\n This is an immutable property, any new item pushed to the stack\n must be an instance of the acceptable class.\n\n Methods\n -------\n push:\n Push a new item to the top of the stack, must be an instance of\n the acceptable class.\n\n pop:\n Removes the top item from the stack and returns it.\n\n peak:\n Returns the top item of the stack without removing it.\n\n size:\n Length of the list of items currently in the stack.\n\n type_verification:\n Checks that an item is an instance of the acceptable class.\n\n verify_types:\n Verifies that all items in the stack are valid.\n \"\"\"\n\n def __init__(self,\n acceptable_class: Optional[Type[Any]] = Number) -> NoReturn:\n \"\"\"A stack that only allows items of a certain class.\n\n Parameters\n ----------\n acceptable_class: any class, optional\n Any class, this will be an immutable property. All items\n pushed to this stack will be checked to be an instance of\n that class. The default value is the class Number from the\n data_structures.elements module.\n\n Raises\n ------\n AssertionError:\n If the value of the acceptable_class parameter is not a\n class.\n \"\"\"\n\n msg = \"TypeRestrictedStacks should be restricted with a class.\"\n assert inspect.isclass(acceptable_class), msg\n super().__init__()\n self.__acceptable_class = acceptable_class\n\n @property\n def acceptable_class(self) -> Type[Any]:\n \"\"\"The class that is restricting items of the stack.\"\"\"\n\n return self.__acceptable_class\n\n def type_verification(self, item: Any) -> NoReturn:\n \"\"\"Checks that an item is an instance of the acceptable class\n\n Parameter\n ---------\n item: any\n Any object.\n\n Raises\n ------\n ValueError:\n If item is not an instance of the acceptable class.\n \"\"\"\n\n if not isinstance(item, self.acceptable_class):\n raise ValueError(\"items in the stack must be an instance of \"\n + self.acceptable_class.__name__)\n\n def verify_types(self) -> NoReturn:\n \"\"\"Verifies that all items in the stack are valid.\n\n Raises\n ------\n ValueError:\n If any item in the stack is not an instance of the\n acceptable class.\n \"\"\"\n\n for item in self._items:\n self.type_verification(item)\n\n def push(self, new_item: Any) -> NoReturn:\n \"\"\"Push a new item to the top of the stack.\n\n Parameters\n ----------\n new_item: instance of the acceptable class\n An item to push to the top to the stack, it must be an\n instance of the acceptable class.\n\n Raises\n ------\n ValueError:\n If the new_item is not an instance of the acceptable class.\n \"\"\"\n\n self.type_verification(new_item)\n super().push(new_item)\n"} {"doc_id": "3e55b290f33f43273119808a8594e469", "text": "# Time complexity is O(n)\r\n\r\n\r\ndef largest_number_possible(iterable):\r\n \"\"\"\r\n Largest_number is defined as the largest number formed by arranging the elements of the iterable\r\n :param iterable: It is of type list or tuple accepting only non-negative integers\r\n :return: The largest number possibly formed from the given iterable\r\n\r\n Eg: largest_number_possible([98, 9, 26]) returns 99826\r\n Here 99826 is the largest element possible after arranging the elements adjacent to each other.\r\n\r\n \"\"\"\r\n\r\n # To check whether the given iterable is list or tuple\r\n if type(iterable) == list or type(iterable) == tuple:\r\n pass\r\n else:\r\n raise TypeError(\"Iterable should be of either list or tuple\")\r\n\r\n # To check whether all the given items in the iterable are numbers only\r\n for item in iterable:\r\n if not isinstance(item, int):\r\n raise ValueError(\"Only numbers are accepted in the iterable\")\r\n\r\n # To check whether all the elements are non-negative integers\r\n for item in iterable:\r\n if item < 0:\r\n raise ValueError(\"Negative values not allowed\")\r\n\r\n # Finding number of digits in the larger number\r\n lar_size = len(str(max(iterable))) + 1\r\n\r\n # Iterable for storing the numbers in the string format\r\n str_iterable = []\r\n\r\n for i in range(len(iterable)):\r\n str_iterable.append(((str(iterable[i]) * lar_size)[:lar_size], i))\r\n\r\n str_iterable.sort(reverse=True)\r\n\r\n # resultant number for storing the larger number from the iterable\r\n result = \"\"\r\n\r\n # Appending all the elements based on their index positions\r\n for item in str_iterable:\r\n result += str(iterable[item[1]])\r\n\r\n return int(result)\r\n"} {"doc_id": "3f336188d8360636398f4c9e0f77a0f9", "text": "# Using collections, write a program that will ask for a user name and password at most three times.\n# If a correct pair of user name and password is entered, it will print 'You may enter.' and stop asking for user name and password.\n# If an incorrect pair of user name and password is entered three times, it will print 'Begone!' and stop asking for user name and password.\n\n# Define the passwords dictionary mapping user names to their passwords. \npasswords = {\n\t'Noel': 'Pay',\n\t'Yap': 'Leon'\n}\n\n# Try at most three times.\nfor i in range(3):\n\tuser = input('User name:')\n\tpassword = input('Password:')\n\t\n\t# If the user name that was entered is in the password dictionary and the password entered matches the one in the dictionary, succeed.\n\tif user in passwords.keys() and passwords[user] == password:\n\t\tprint 'You may enter.'\n\t\t\n\t\tbreak\nelse:\n\t# If the wrong user name and password pair has been entered incorrectly three times, fail.\n\tprint 'Begone!'"} {"doc_id": "3f4d6936e0c370c424615528da9112a3", "text": "info = \"\"\"\nIn Python, functions are the first class objects, which means that:\n-Functions are objects; they can be referenced to, passed to a variable and returned from other functions as well.\n-Functions can be defined inside another function and can also be passed as argument to another function.\n\n* Python has an interesting feature called decorators to add functionality to an existing code.\n* This is also called metaprogramming because a part of the program tries to modify another part of the program at compile time.\n* Decorators allow us to wrap another function in order to extend the behavior of wrapped function,without permanently modifying it.\n* In Decorators, functions are taken as the argument into another function and then called inside the wrapper function.\n* Such functions that take other functions as arguments are also called higher order functions.\n\"\"\"\nprint(info)\n\nprint(\"###nested function###\")\n\n\ndef outer_function():\n print(\"outer function started\")\n\n def inner_funtion():\n print(\"inner function started\")\n\n print(\"inner funtion ended\")\n print(\"outer function ended\")\n\n\nouter_function() # inner function didn't invoked\nprint(\"\\n###nested function with function arguments###\\n\")\n\n\ndef outer_function(function):\n print(\"outer function started\")\n print(\"argument function started in outer function\")\n function()\n print(\"argument function ended in outer function\")\n\n def inner_funtion():\n print(\"inner function started\")\n print(\"argument function started inside inner function\")\n function()\n print(\"argument function ended inside inner function\")\n\n print(\"This is before calling inner function\")\n inner_funtion()\n print(\"inner funtion ended\")\n print(\"outer function ended\")\n\n\ndef arg_fun():\n print(\"argument function is working\")\n\n\n# outer_function(arg_fun()) # it will give error\nouter_function(arg_fun)\n\nprint(\"\\n###python closure###\\n\")\n\n\ndef outer_func():\n message = \"Hello from Masum Bhai\"\n\n def inner_func():\n print(\"inner func is invoked\")\n print(message)\n\n # return inner_func() # inner function will invoke\n return inner_func # this will give address of inner func() as object\n\n\nmy_variable = outer_func()\nprint(my_variable) # it will print address\nmy_variable() # it will invoke outer_func()\nprint(\"----------------------\")\nnew_my_variable = my_variable()\n# new_my_variable() # it will give error\nnew_my_variable # now it will act as my_variable()\nprint(\"----------------------\")\n\n\ndef outer_func(message):\n def inner_func():\n print(\"inner func is invoked\")\n print(message)\n\n return inner_func\n\n\nsecond_variable = outer_func(\"Masum The Hero from zero\")\nsecond_variable()\n\nprint(\"\"\"\\n###Decorator###\\n\"\"\")\n\n\ndef old_deccorator(old_function):\n def inner_old_function():\n print(\"i'm inside inner_old_function\")\n return old_function()\n\n return inner_old_function\n\n\ndef new_decorator(new_function):\n def wrapper_func():\n print(\"i'm inside wrapper function\")\n return new_function()\n\n return wrapper_func\n\n\n@old_deccorator\n@new_decorator\ndef super_fun():\n print(\"Hail Hydra\")\n\n\nsuper_fun()\n\nprint(\"\"\"\\n###Word count programme using Decorator###\"\"\")\n\n\ndef split_string(name):\n def wrapper():\n split = name().split()\n return len(split)\n\n return wrapper\n\n\n@split_string\ndef normal_string():\n str = input(\"Enter sentence or paragraph to count it's word (no enter key allowed):\\n\")\n return str\n\n\nprint(\"Total word count:\", normal_string())\n"} {"doc_id": "3f8b3efc055bd1b39f1744c4460edfda", "text": "# LOGICAL OPERATORS\n\n# and or not\n\nprint(True and True)\nprint(True and False)\nprint(False and True) # order does not matter\nprint(False and False)\n\nprint(\"------------\")\n\nprint(True or True)\nprint(True or False)\nprint(False or True) # order does not matter\nprint(False or False)\n\nprint(\"------------\")\n\nprint(not True)\nprint(not False)\n\n\n\nprint(\"Yo! Give me a number between 10 and 20\")\nn = int(input(\"> \")) # n 9\n\nif n >= 10 and n <= 20:\n print(\"Thank you for complying!\")\nelse:\n print(\"Maybe it's time for you to start looking jor a job elsewhere!\")\n"} {"doc_id": "3fa916343125fe90484bc0d5962848f5", "text": "# ---------- CALCULATOR ----------\n# Receive 2 numbers separated by an operator and show a result\n# Sample\n# Enter Calculation: 5 * 6\n# 5 * 6 = 30\n\n# Store the user input of 2 numbers and the operator\n\n\n# Convert the strings into integers\n\n\n# if + then we need to provide output based on addition\n# Print the result\n# If, else if (elif) and else execute different code\n# depending on a condition\n\n\n# If the 1st condition wasn't true check if this one is true\n\n\n# If none of the above conditions were true ten execute this by default\n\n\n\n\n\n\n"} {"doc_id": "3fbe83fb74b1e13800645d1646f25d87", "text": "class Orange:\n priceOfOranges = 5\n stock = 30\n def __init__(self, quantityToBuy):\n self.quantityToBuy = quantityToBuy\n\n def OrangeSelling(self):\n if int(self.quantityToBuy) > Orange.stock:\n print(\"We do not have enough oranges, Please select a lesser quantity.\")\n else:\n Receipt = int(self.quantityToBuy) * Orange.priceOfOranges\n Orange.stock = Orange.stock - int(self.quantityToBuy)\n print (f\"Your amount to pay is {int(self.quantityToBuy) * Orange.priceOfOranges} and we have {Orange.stock} oranges left.\")\n\nBuyer1 = Orange(input(\"Please input quantity to buy:\"))\nBuyer1.OrangeSelling()"} {"doc_id": "405061812f1bec96b7d997fa1c05ebe4", "text": "# Copyright (C) 2018 Garth N. Wells\n#\n# SPDX-License-Identifier: MIT\n\"\"\"Utility functions.\"\"\"\n\n\ndef sorted_by_key(x, i, reverse=False):\n \"\"\"For a list of lists, return list sorted by the ith component of list.\n\n E.g.\n Sort on first entry of tuple:\n\n > sorted_by_key([(1, 2), (5, 1]), 0)\n >>> [(1, 2), (5, 1)]\n\n Sort on second entry of tuple:\n\n > sorted_by_key([(1, 2), (5, 1)], 1)\n >>> [(5, 1), (1, 2)]\n\n\n Parameters\n ----------\n x : list[list/tuples]\n i : int\n ith component of lists to sort from.\n reverse : bool, optional\n reverse sorted list. The default is False.\n\n Returns\n -------\n list[list/tuples]\n sorted list of lists/tuples.\n\n \"\"\"\n # Sort by distance\n def key(element):\n return element[i]\n\n return sorted(x, key=key, reverse=reverse)\n\n\ndef map(x, in_range, out_range):\n \"\"\"Linearly map a value of x from an input range to an output range.\n\n Note that the value is not constrained to the output range,\n nor does x need to be constrained to the input range\n\n Parameters\n ----------\n x : float\n the input value.\n in_range : (float, float)\n tuple of the input range.\n out_range : (float float)\n tuple of output range.\n\n Returns\n -------\n float\n the mapped value.\n\n \"\"\"\n return ((x - in_range[0]) / (in_range[1] - in_range[0])) * \\\n (out_range[1] - out_range[0]) + out_range[0]\n"} {"doc_id": "4081474e77ee4eca8bcad99ccea79fbb", "text": "\"\"\" Module FSA -- methods to manipulate finite-state automata\n\nCreated by: Oliver Steele // Modified and enlarged by: Roser Sauri\n\n\nThis module defines an FSA class, for representing and operating on\nfinite-state automata (FSAs). FSAs can be used to represent regular expressions\nand to test sequences for membership in the languages described by regular\nexpressions.\n\nFSAs can be deterministic or nondeterministic, and they can contain epsilon\ntransitions. Methods to determinize an automaton (also eliminating its epsilon\ntransitions), and to minimize an automaton, are provided.\n\nThe transition labels for an FSA can be symbols from an alphabet, as in the\nstandard formal definition of an FSA, but they can also be instances which\nrepresent predicates. If these instances implement instance.matches(), then the\nFSA nextState() function and accepts() predicate can be used. If they implement\ninstance.complement() and instance.intersection(), the FSA can be be\ndeterminized and minimized, to find a minimal deterministic FSA that accepts an\nequivalent language.\n\n\n===============\n Quick Start\n===============\n\n ---------------------------\n1. Creating FSAs out of labels:\n ---------------------------\n \nInstances of FSA can be created out of labels (for instance, strings) by the\nsingleton() function, and combined to create more complex FSAs through the\ncomplement(), closure(), concatenation(), union(), and other constructors. For\nexample, concatenation(singleton('a'), union(singleton('b'),\nclosure(singleton('c')))) creates an FSA that accepts the strings 'a', 'ab',\n'ac', 'acc', 'accc', and so on.\n\n --------------------------------------\n2. Creating FSAs using function compileRE:\n --------------------------------------\n\nInstances of FSA can also be created with the compileRE(regex) function, which\ncompiles a simple regular expression (using only '*', '?', '+', '.', '|', '(', and\n')' as metacharacters) into an FSA. For example, compileRE('a(b|c*)') returns\nan FSA equivalent to the example in the previous paragraph.\n\n --------------------------------------\n3. Creating FSAs using function compileOP:\n --------------------------------------\n\nFinally, instances of FSA can also be generated using the function\ncompileOP(list), which stands for 'compile Object Pattern'. It allows\nfor creating FSAs out of string of characters (as with 'compileRE'\nfunction), but also out of sequences of other kinds. Here is the list of\nformats it accepts as input:\n\n(a) Strings of characters. E.g., fsa1 = compileOP('a(b|c*)')\n ;;;;;;;;;;;;;;;;;;;;;\n\n(b) Lists of characters. E.g., fsa2 = compileOP( [ 'a','(','b','|','c','*',')' ] )\n ;;;;;;;;;;;;;;;;;;;\n\nIn essence, options (a) and (b) above are equivalent to using the\ncompileRE function.However, compileRE is faster, so best practice is\nusing compileRE whenever possible.\n\nIn addition to (a) and (b), compileOP also allows as input sequences\nof lexical items or chunks, which can be represented either as\nsequences of characters strings (c), or sequences of grammatical\nobjects (d).\n\n(c) Lists of characters strings. E.g.,\n ;;;;;;;;;;;;;;;;;;;;;;;;;;;\n\n fsa3 = compileOP(['(','a','|','the',')', 'very', '*', '(', 'boring','|','nice', ')', '+', 'movie'])\n\n(d) Lists of grammatical objects represented as Python dictionaries. E.g.,\n ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\n\n fsa4 = compileOP( [ {'nodeType': 'Token', 'text': ['is','was','were','am','be',\\\"'s\\\", 'are', \\\"'re\\\",\\\"'m\\\",'been', 'being']',\n '(',\n {'nodeType':'Token', 'text': 'being'}, # Passive, PROGRESSIVE \n {'nodeType':'Token', 'pos': ['VBD', 'VBN']}, # E.g., 'is being eaten' \n '|',\n {'nodeType':'Token', 'pos': 'VBG'}, # Active, PROGRESSIVE (infinitive). E.g., '[be] eating'\n '|',\n {'nodeType':'Token', 'pos': ['VBD', 'VBN']}, # Passive, NONE. E.g. '[is] eaten'\n ')'\n ] )\n\n In other words, the elements of the FSA vocabulary can be\n conceived as clusters of attribute-value pairs, and represented\n using python dictionars. The format of the value in each key-value\n pair can be:\n\n -- An atomic element. E.g., {..., 'headForm':'is', ...}\n\n -- A list of possible values. E.g., {..., headForm': ['have',\n 'has', 'had'], ...} In this case, it is checked whether the value\n of the input is included within that list of value candidates.\n\n -- A negated value or list of values. Negation is represented by\n means of a 2-place tuple, whose initial position is the caret\n symbol '^', and its second position is either an atomic value or a\n list of atomic values that need not match the value of the input\n object. E.g.,\n {..., 'headPos':('^', 'MD') ...}, or\n {..., 'headPos':('^', ['MD', 'RB']) ...}\n\n On the other hand, input objects can be represented as:\n\n -- Python dictionaries, like the FSA vocabulary. \n\n -- Instances of classes describing grammatical objects, customized\n by the particular application using the current FSA module. E.g.,\n Noun Chunks, Verb Chunks, Lexical tokens, etc, in Evita. In this\n case, the only additional requirement is creating, within the\n class, a method capable of mapping the FSA vocabulary items (of\n the format described above) into your instance. As example, refer\n to the use of the function _matchChunk, specific for Evita, which\n is called from labelMatches function (this module) and described\n in the Chunk class (Chunk.py)).\n\n \nAdditional notes on the use of compileOP:\n;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\n\nThe metacharacters allowed here are the same as for compileRE: '*',\n'?', '+', '.', '|', '(', and '). Note however that these\nmetacharacters need to be represented as independent items of the\nlist. This could be improved, but we leave it for later when we are\nall unemployed and bored to death.\n\n -------------------\n4. Accepting sequences\n -------------------\n\nWe can check whether a FSA accepts or rejects a sequence using the\nfollowing methods:\n\n(a) accepts: \n ;;;;;;;\n Taking as argument an input sequence and returning True or False.\n E.g., using fsa3 compiled in (c) above:\n \n >>> fsa3.accepts(['a', 'very', 'very', 'very', 'boring', 'movie'])\n 1\n >>> fsa3.accepts(['a', 'very', 'movie'])\n 0\n >>> fsa3.accepts(['a', 'very', 'nice', 'movie', 'theater'])\n 0\n\n(b) acceptsSubstringOf:\n ;;;;;;;;;;;;;;;;;;\n Taking as argument an input sequence, and returning the length of\n the longest subsequence being accepted by the FSA.\n E.g., using fsa3 compiled in (c) above:\n\n >>> fsa3.acceptsSubstringOf(['a', 'very', 'very', 'very', 'boring', 'movie'])\n 6\n >>> fsa3.acceptsSubstringOf(['a', 'very', 'movie'])\n 0\n >>> fsa3.acceptsSubstringOf(['a', 'very', 'nice', 'movie', 'theater'])\n 4\n \nBoth functions, accepts and acceptsSubstringOf, can be used with any\nof the FSA vocabulary and input format described in (a)-(d) sections\nabove.\n\n ---------------------------------\n5. Determinizing and minimizing FSAs\n ---------------------------------\n\nFSAs can be determinized, to create equivalent FSAs (FSAs accepting\nthe same language) with unique successor states for each input, and\nminimized, to create an equivalent deterministic FSA with the smallest\nnumber of states. FSAs can also be complemented, intersected, unioned,\nand so forth as described under 'FSA Functions' below.\n\n\n=======================\n Module Description\n=======================\n\n ------------\n* FSA Methods\n ------------\n\nThe class FSA defines the following methods.\n\nAcceptance:\n - fsa.nextStates(state, input) returns a list of states\n - fsa.nextState(state, input) returns None or a single state if\n |nextStates| <= 1, otherwise it raises an exception\n - fsa.nextStateSet(states, input) returns a list of states\n - fsa.accepts(sequence) returns true or false\n - fsa.acceptsSubstringOf(list) returns the lentgh of the\n longest sublist accepted.\n\nAccessors and predicates:\n - isEmpty() returns true iff the language accepted by the FSA is the empty language\n - labels() returns a list of labels that are used in any transition\n - nextAvailableState() returns an integer n such that no states in the FSA\n are numeric values >= n\n\nReductions:\n - sorted(initial=0) returns an equivalent FSA whose states are numbered\n upwards from 0\n - determinized() returns an equivalent deterministic FSA\n - minimized() returns an equivalent minimal FSA\n - trimmed() returns an equivalent FSA that contains no unreachable or dead\n states\n\nPresentation:\n - toDotString() returns a string suitable as *.dot file for the 'dot'\n program from AT&T GraphViz\n - view() views the FSA with a gs viewer, if gs and dot are installed\n\n \n --------------\n* FSA Functions\n --------------\n\nConstruction from FSAs:\n- complement(a) returns an fsa that accepts exactly those sequences that it's\n argument does not\n- closure(a) returns an fsa that accepts sequences composed of zero or more\n concatenations of sequences accepted by the argument\n- concatenation(a, b) returns an fsa that accepts sequences composed of a\n sequence accepted by a, followed by a sequence accepted by b\n- containment(a, occurrences=1) returns an fsa that accepts sequences that\n contain at least occurrences occurrences of a subsequence recognized by the\n argument.\n- difference(a, b) returns an fsa that accepts those sequences accepted by a\n but not b\n- intersection(a, b) returns an fsa that accepts sequences accepted by both a\n and b\n- iteration(a, min=1, max=None) returns an fsa that accepts sequences\n consisting of from min to max (or any number, if max is None) of sequences\n accepted by its first argument\n- option(a) is equivalent to union(a, EMPTY_STRING_FSA)\n- reverse(a) returns an fsa that accepts strings whose reversal is accepted by\n the argument\n- union(a, b) returns an fsa that accepts sequences accepted by both a and b\n\nPredicates:\n- equivalent(a, b) returns true iff a and b accept the same language\n\nReductions (these equivalent to the similarly-named methods):\n- determinize(fsa) returns an equivalent deterministic FSA\n- minimize(fsa) returns an equivalent minimal FSA\n- sort(fsa, initial=0) returns an equivalent FSA whose states are numbered from\n initial\n- trim(fsa) returns an equivalent FSA that contains no dead or unreachable\n states\n\nConstruction from labels:\n- compileRE(string) returns an FSA that accepts the language described by\n string, where string is a list of symbols and '*', '+', '?', and '|' operators,\n with '(' and ')' to control precedence.\n- sequence(sequence) returns an fsa that accepts sequences that are matched by\n the elements of the argument. For example, sequence('abc') returns an fsa that\n accepts 'abc' and ['a', 'b', 'c'].\n- singleton(label) returns an fsa that accepts singletons whose elements are\n matched by label. For example, singleton('a') returns an fsa that accepts only\n the string 'a'.\n\n --------------\n* FSA Constants\n --------------\n\nEMPTY_STRING_FSA is an FSA that accepts the language consisting only of the\nempty string.\n\nNULL_FSA is an FSA that accepts the null language.\n\nUNIVERSAL_FSA is an FSA that accepts S*, where S is any object.\n\n ----------------------\n* FSA instance creation\n ----------------------\n\nFSA is initialized with a list of states, an alphabet, a list of transition, an\ninitial state, and a list of final states. If fsa is an FSA, fsa.tuple()\nreturns these values in that order, i.e. (states, alphabet, transitions,\ninitialState, finalStates). They're also available as fields of fsa with those\nnames.\n\nEach element of transition is a tuple of a start state, an end state, and a\nlabel: (startState, endSTate, label).\n\nIf the list of states is None, it's computed from initialState, finalStates,\nand the states in transitions.\n\nIf alphabet is None, an open alphabet is used: labels are assumed to be objects\nthat implements label.matches(input), label.complement(), and\nlabel.intersection() as follows:\n - label.matches(input) returns true iff label matches input\n - label.complement() returnseither a label or a list of labels which,\n together with the receiver, partition the input alphabet\n - label.intersection(other) returns either None (if label and other don't\n both match any symbol), or a label that matches the set of symbols that\n both label and other match\n\nAs a special case, strings can be used as labels. If a strings 'a' and 'b' are\nused as a label and there's no alphabet, '~a' and '~b' are their respective\ncomplements, and '~a&~b' is the intersection of '~a' and '~b'. (The\nintersections of 'a' and 'b', 'a' and '~b', and '~a' and 'b' are, respectively,\nNone, 'a', and 'b'.)\n\n\n=========\n Goals\n=========\n\nDesign Goals:\n - easy to use\n - easy to read (simple implementation, direct expression of algorithms)\n - extensible\n\nNon-Goals:\n - efficiency\n\n\n================================================ \n Chronology of modifications and enlargements \n================================================ \n\nFebrary 2005:\n\n- Fixed bugs in compileRE and related functions (Roser)\n\nApril 2005:\n\n- Added functionality of compileOP and related functions (Roser)\n- Enlarged module documentation. (Roser)\n \n\"\"\"\n\n\nfrom __future__ import absolute_import\nfrom __future__ import print_function\nimport string, os, tempfile\nfrom types import InstanceType, ListType, TupleType, IntType, LongType, DictType, StringType\nfrom six.moves import map\nfrom six.moves import filter\nfrom six.moves import range\nfrom functools import reduce\n\nIntegerTypes = (IntType, LongType)\n\ntry:\n import NumFSAUtils\nexcept ImportError:\n NumFSAUtils = None\n\nANY = 'ANY'\nEPSILON = None\n\nTRACE_LABEL_MULTIPLICATIONS = 0\nNUMPY_DETERMINIZATION_CUTOFF = 50\n\n\n#debugFile = open(os.getcwd()+'/FSAdebugOutput.txt', 'w') \n\nclass FSA(object):\n def __init__(self, states, alphabet, transitions, initialState, finalStates, arcMetadata=[]):\n if states == None:\n states = self.collectStates(transitions, initialState, finalStates)\n else:\n assert not list(filter(lambda s, states=states:s not in states, self.collectStates(transitions, initialState, finalStates)))\n self.states = states\n self.alphabet = alphabet\n self.transitions = transitions\n self.initialState = initialState\n self.finalStates = finalStates\n self.setArcMetadata(arcMetadata)\n \n \n #\n # Initialization\n #\n def makeStateTable(self, default=None):\n for state in self.states:\n if type(state) != IntType:\n return {}\n if reduce(min, self.states) < 0: return {}\n if reduce(max, self.states) > max(100, len(self.states) * 2): return {}\n return [default] * (reduce(max, self.states) + 1)\n \n def initializeTransitionTables(self):\n self._transitionsFrom = self.makeStateTable()\n for s in self.states:\n self._transitionsFrom[s] = []\n for transition in self.transitions:\n s, _, label = transition\n self._transitionsFrom[s].append(transition)\n \n def collectStates(self, transitions, initialState, finalStates):\n states = finalStates[:]\n if initialState not in states:\n states.append(initialState)\n for s0, s1, _ in transitions:\n if s0 not in states: states.append(s0)\n if s1 not in states: states.append(s1)\n return states\n \n def computeEpsilonClosure(self, state):\n states = [state]\n index = 0\n while index < len(states):\n state, index = states[index], index + 1\n for _, s, label in self.transitionsFrom(state):\n if label == EPSILON and s not in states:\n states.append(s)\n states.sort()\n return states\n \n def computeEpsilonClosures(self):\n self._epsilonClosures = self.makeStateTable()\n for s in self.states:\n self._epsilonClosures[s] = self.computeEpsilonClosure(s)\n \n \n #\n # Copying\n #\n def create(self, *args):\n return self.__class__(*args)\n \n def copy(self, *args):\n fsa = self.__class__(*args)\n if hasattr(self, 'label'):\n fsa.label = self.label\n return fsa\n \n def creationArgs(self):\n return self.tuple() + (self.getArcMetadata(),)\n \n def coerce(self, klass):\n return klass(*self.creationArgs())\n \n \n #\n # Accessors\n #\n def epsilonClosure(self, state):\n try:\n return self._epsilonClosures[state]\n except AttributeError:\n self.computeEpsilonClosures()\n return self._epsilonClosures[state]\n \n def labels(self):\n \"\"\"Returns a list of transition labels.\"\"\"\n labels = []\n for (_, __, label) in self.transitions: #added underscore\n if label and label not in labels:\n labels.append(label)\n return labels\n \n def nextAvailableState(self):\n return reduce(max, [s for s in self.states if type(s) in IntegerTypes], -1) + 1\n \n def transitionsFrom(self, state):\n try:\n return self._transitionsFrom[state]\n except AttributeError:\n self.initializeTransitionTables()\n return self._transitionsFrom[state]\n \n def tuple(self):\n return self.states, self.alphabet, self.transitions, self.initialState, self.finalStates\n \n \n #\n # Arc Metadata Accessors\n #\n def hasArcMetadata(self):\n return hasattr(self, '_arcMetadata')\n \n def getArcMetadata(self):\n return list(getattr(self, '_arcMetadata', {}).items())\n \n def setArcMetadata(self, list):\n arcMetadata = {}\n for (arc, data) in list:\n arcMetadata[arc] = data\n self._arcMetadata = arcMetadata\n \n def addArcMetadata(self, list):\n for (arc, data) in list:\n self.addArcMetadataFor(arc, data)\n \n def addArcMetadataFor(self, transition, data):\n if not hasattr(self, '_arcMetadata'):\n self._arcMetadata = {}\n oldData = self._arcMetadata.get(transition)\n if oldData:\n for item in data:\n if item not in oldData:\n oldData.append(item)\n else:\n self._arcMetadata[transition] = data\n \n def setArcMetadataFor(self, transition, data):\n if not hasattr(self, '_arcMetadata'):\n self._arcMetadata = {}\n self._arcMetadata[transition] = data\n \n def getArcMetadataFor(self, transition):\n #debugFile.write( \"\\n--------------> TRANSITION!!!!: \"+str(transition)+\"\\n\\t\\t\"+str((str(transition[0]), str(transition[1]),str(transition[2]))))\n ar=getattr(self, '_arcMetadata', {})\n #debugFile.write( \"\\n--------------> getattr(self, '_arcMetadata': \"+str(ar))\n #debugFile.write( \"\\n--------------> ALL together: \"+ar.get(transition))\n myTransition = (transition[0], transition[1], str(transition[2]))\n try:\n return getattr(self, '_arcMetadata', {}).get(transition)\n except:\n return getattr(self, '_arcMetadata', {}).get(myTransition)\n \n \n \n #\n # Predicates\n #\n def isEmpty(self):\n return not self.minimized().finalStates\n \n def isFSA(self):\n return 1\n \n \n #\n # Accepting\n #\n def labelMatches(self, label, input):\n #debugFile.write( \"\\n\\nPASS: ...labelMatches 1: \"+str(input))\n #print \"\\n\\nPASS: ...LABEL:\", label, \"INPUT:\", input\n return labelMatches(label, input)\n \n def nextStates(self, state, input):\n #debugFile.write( \"\\n\\nPASS: ...nextStates 1: \"+str(input))\n states = []\n for _, sink, label in self.transitionsFrom(state):\n #print \"\\tMY LABEL:\"+str(label)\n if self.labelMatches(label, input):\n #print \"\\t\\tPASSED first test\"\n if sink not in states:\n #print \"\\t\\tCHECK case 1\"\n states.extend(self.epsilonClosure(sink))\n elif label == 'ALL': \n #print \"\\t\\tCHECK case ALL\"\n #debugFile.write( \"\\n--------------> ANY condition found here!!\") \n states.extend(self.epsilonClosure(sink)) \n elif label[0] == '^': \n label = label[1:] \n #print \"\\t\\tLABEL MUST NOT MATCH\", label\n if (not self.labelMatches(label, input)) and sink not in states: \n states.extend(self.epsilonClosure(sink))\n #else:\n #print \"\\t\\tMISSED\"\n return states\n \n def nextState(self, state, input):\n #debugFile.write( \"\\n\\nPASS: ...nextState 1: \"+str(input))\n states = self.nextStates(state, input)\n assert len(states) <= 1\n return states and states[0]\n \n def nextStateSet(self, states, input):\n # debugFile.write( \"\\n\\nPASS: ...nextStateSet 1: \"+str(input))\n successors = []\n for state in states:\n for _, sink, label in self.transitionsFrom(state):\n if self.labelMatches(label, input) and sink not in successors:\n successors.append(sink)\n return successors\n \n def accepts(self, sequence):\n #print \"SEQUENCE:\", sequence\n states = [self.initialState]\n for item in sequence:\n newStates = []\n for state in states:\n #debugFile.write( \"\\n\\nPASS: ...accepts 1: \"+str(item))\n for s1 in self.nextStates(state, item):\n if s1 not in newStates:\n newStates.append(s1)\n states = newStates\n \n \"\"\"Returning the length of the list containing all states s in states\n that are also in self.finalStates\"\"\"\n return len(list(filter(lambda s, finals=self.finalStates: s in finals, states))) > 0\n #return len(filter(lambda s: s in self.finalStates, states)) > 0\n\n def acceptsSubstringOf(self, sequence): #looking for Longest Subsequence\n \"\"\" As accepts() method, but accepting also substrings of sequence.\n Returning length of longest piece of sequence that has been matched\"\"\"\n# print \"\\n........Entering acceptsSubstringOf......\\n\"\n stateSequences = self.findSubstringsOf(sequence, self.initialState, [])\n return self.longestSequence(stateSequences)[0] \n\n def acceptsShortestSubstringOf(self, sequence):\n \"\"\" As accepts() method, but accepting also substrings of sequence.\n Returning length of shortest piece of sequence that has been matched\"\"\"\n print(\"\\n........Entering acceptsSubstringOf......\\n\")\n stateSequences = self.findSubstringsOf(sequence, self.initialState, [])\n #log(\"\\n\\nSUBSTRINGS: \"+str(stateSequences))\n return self.shortestSequence(stateSequences)[0] \n \n def findSubstringsOf(self, sequence, state, visitedStates): \n \"\"\"Returning a list of state sequences matching pattern \"\"\"\n #debugFile.write( \"\\n\\nInitialStates: \"+str(state))\n stateSequences = []\n #print self\n for i in range(len(sequence)):\n #print sequence[i].pp()\n #log(\"\\n NEW i:\"+str(i))\n #log(\"\\nstateSequences:\"+str(stateSequences))\n #log(\"\\nvisitedStates:\"+str(visitedStates))\n if i > 0 and (not visitedStates or\n visitedStates[-1] != state): #Hacking, but oh well... \n #log(\"\\nHACKING here\") #Hacking, but oh well...\n visitedStates.append(state) #Hacking, but oh well... \n #if i > 0 and not visitedStates: #Hacking, but oh well... \n # return self.updateStateSequences(visitedStates, stateSequences)\n #else:\n #log(\"\\n\"+25*\"=\")\n #log(\"\\nITEM: \"+str(sequence[i].getText())+\" || type:\"+sequence[i].nodeType+\" \\n\\tCURRENT STATE:\"+str(state))\n nextStateList = self.nextStates(state, sequence[i])\n #log(\"\\n\\tVISITED STATES: \"+str(visitedStates))\n #log(\"\\n\\tNEXT STATES: \"+str(nextStateList))\n if len(nextStateList) == 0:\n #log(\"\\n\\nRETURNING HERE 1\")\n #print \"\\n....len(nextStateList) == 0\"\n #print \"visitedStates:\",visitedStates\n return self.updateStateSequences(visitedStates, stateSequences)\n elif len(nextStateList) == 1:\n #print \"\\n....len(nextStateList) == 1\"\n nextState = nextStateList[0] \n #debugFile.write( \"\\n\\tself.nextState: \"+str(nextState))\n #print \"\\n\\tself.nextState: \"+str(nextState)\n visitedStates.append(nextState)\n #print \"visitedStates:\",visitedStates \n state = nextState\n else: \n #log(\"\\n....len(nextStateList) == \"+str(len(nextStateList)))\n if len(sequence) > i+1:\n c = len(nextStateList) #DEBUG\n #print \"\\n\\t....len(sequence) > i+1\"\n for state in nextStateList:\n localVisitedStates = visitedStates+[state]\n #log(\"\\nAPPLYING HERE sub-3, COUNTER:\"+str(c)) #DEBUG\n c = c+1 #DEBUG\n moreSequences = self.findSubstringsOf(sequence[i+1:], state, localVisitedStates)\n #print \"moreSequences\", moreSequences\n stateSequences = stateSequences + moreSequences\n #print \"stateSequences\", stateSequences\n else:\n #log(\"\\n\\nRETURNING HERE sub-3\")\n #print \"\\n\\t....ELSE: len(sequence) \"\n return self.updateStateSequences(visitedStates, stateSequences)\n #debugFile.write(\"\\n\\nRETURNING HERE 2\")\n #log(\"\\nRETURNING HERE 2\")\n #debugFile.write(\"\\nvisited states:\"+str(visitedStates))\n #print \"\\nvisited states: \"+str(visitedStates)\n return self.updateStateSequences(visitedStates, stateSequences) \n\n def shortestSequence(self, stateSequences):\n \"\"\"Return lists containing (len(shortestSubsequence), shortestSubsequence) \"\"\"\n #debugFile.write(\"\\nSTATE SUBSEQUENCE CANDIDATES:\"+str(stateSequences))\n lenStateSubsequences = []\n for subsequence in stateSequences:\n lenStateSubsequences.append([len(subsequence), subsequence])\n #debugFile.write(\"\\tSORTED: \"+str(lenStateSubsequences.reverse()))\n if lenStateSubsequences:\n lenStateSubsequences.sort()\n #print \"STATE SUBSEQUENCE:\"+str(lenStateSubsequences)+\" \"+str(type(lenStateSubsequences))\n return lenStateSubsequences[0]\n else:\n return [0, None] \n \n def longestSequence(self, stateSequences):\n \"\"\"Return lists containing (len(longestSubsequence), longestSubsequence) \"\"\"\n #debugFile.write(\"\\nSTATE SUBSEQUENCE CANDIDATES:\"+str(stateSequences))\n lenStateSubsequences = []\n for subsequence in stateSequences:\n lenStateSubsequences.append([len(subsequence), subsequence])\n #debugFile.write(\"\\tSORTED: \"+str(lenStateSubsequences.reverse()))\n if lenStateSubsequences:\n lenStateSubsequences.sort()\n #print \"STATE SUBSEQUENCE:\"+str(lenStateSubsequences)+\" \"+str(type(lenStateSubsequences))\n return lenStateSubsequences[-1]\n else:\n return [0, None]\n \n def indexOfLastVisitedFinalState(self, visitedStates):\n \"\"\"Return position+1 or 0\"\"\"\n for i in range(len(visitedStates)-1, -1, -1):\n if visitedStates[i] in self.finalStates:\n #print \"FINAL STATE in pos:\", i+1, \"for\", visitedStates\n return i+1\n else:\n #print \"FINAL STATE: next, for\", visitedStates\n return self.indexOfLastVisitedFinalState(visitedStates[:-1])\n else:\n #print \"FINAL STATE: none, for:\", visitedStates\n return 0\n \n def updateStateSequences(self, visitedStates, stateSequences):\n #log(\"\\nentering updateStateSequences:\")\n #log(\"\\n\\t\\tvisited states:\"+str(visitedStates))\n #log(\"\\n\\t\\tstateSequences:\"+str(stateSequences))\n lengthMatched = self.indexOfLastVisitedFinalState(visitedStates)\n if lengthMatched:\n stateSequences.append(visitedStates[:lengthMatched])\n #log(\"\\n\\t\\tnow stateSequences:\"+str(stateSequences))\n return stateSequences\n \n #\n # FSA operations\n #\n def complement(self):\n states, alpha, transitions, start, finals = completion(self.determinized()).tuple()\n return self.create(states, alpha, transitions, start, list(filter(lambda s,f=finals:s not in f, states)))#.trimmed()\n \n \n #\n # Reductions\n #\n def sorted(self, initial=0):\n if hasattr(self, '_isSorted'):\n# print \"\\nALREADY SORTED!!!\\n\" \n return self\n else:\n# print \"\\nNOT SORTED YET\\n\"\n return self.sortedObligatory(initial)\n\n def sortedObligatory(self, initial):\n stateMap = {}\n nextState = initial\n states, index = [self.initialState], 0\n while index < len(states) or len(states) < len(self.states):\n if index >= len(states):\n for state in self.states:\n if stateMap.get(state) == None:\n break\n states.append(state)\n state, index = states[index], index + 1\n new, nextState = nextState, nextState + 1\n stateMap[state] = new\n for _, s, _ in self.transitionsFrom(state):\n if s not in states:\n states.append(s)\n states = list(stateMap.values())\n transitions = list(map(lambda (s0,s1,l),m=stateMap:(m[s0], m[s1], l), self.transitions))\n arcMetadata = list(map(lambda ((s0, s1, label), data), m=stateMap: ((m[s0], m[s1], label), data), self.getArcMetadata()))\n copy = self.copy(states, self.alphabet, transitions, stateMap[self.initialState], list(map(stateMap.get, self.finalStates)), arcMetadata)\n copy._isSorted = 1\n return copy\n \n def trimmed(self):\n \"\"\"Returns an equivalent FSA that doesn't include unreachable states,\n or states that only lead to dead states.\"\"\"\n if hasattr(self, '_isTrimmed'):\n return self\n states, alpha, transitions, initial, finals = self.tuple()\n reachable, index = [initial], 0\n while index < len(reachable):\n state, index = reachable[index], index + 1\n for (_, s, _) in self.transitionsFrom(state):\n if s not in reachable:\n reachable.append(s)\n endable, index = list(finals), 0\n while index < len(endable):\n state, index = endable[index], index + 1\n for (s0, s1, _) in transitions:\n if s1 == state and s0 not in endable:\n endable.append(s0)\n states = []\n for s in reachable:\n if s in endable:\n states.append(s)\n if not states:\n if self.__class__ == FSA:\n return NULL_FSA\n else:\n return NULL_FSA.coerce(self.__class__)\n transitions = list(filter(lambda (s0, s1, _), states=states:s0 in states and s1 in states, transitions))\n arcMetadata = list(filter(lambda ((s0, s1, _), __), states=states: s0 in states and s1 in states, self.getArcMetadata())) #R: added underscore\n result = self.copy(states, alpha, transitions, initial, list(filter(lambda s, states=states:s in states, finals)), arcMetadata).sorted()\n result._isTrimmed = 1\n return result\n \n def withoutEpsilons(self):\n # replace each state by its epsilon closure\n states0, alphabet, transitions0, initial0, finals0 = self.tuple()\n initial = self.epsilonClosure(self.initialState)\n initial.sort()\n initial = tuple(initial)\n stateSets, index = [initial], 0\n transitions = []\n while index < len(stateSets):\n stateSet, index = stateSets[index], index + 1\n for (s0, s1, label) in transitions0:\n if s0 in stateSet and label:\n target = self.epsilonClosure(s1)\n target.sort()\n target = tuple(target)\n transition = (stateSet, target, label)\n if transition not in transitions:\n transitions.append(transition)\n if target not in stateSets:\n stateSets.append(target)\n finalStates = []\n for stateSet in stateSets:\n if list(filter(lambda s, finalStates=self.finalStates:s in finalStates, stateSet)):\n finalStates.append(stateSet)\n copy = self.copy(stateSets, alphabet, transitions, stateSets[0], finalStates).sorted()\n copy._isTrimmed = 1\n return copy\n \n def determinized(self):\n \"\"\"Returns a deterministic FSA that accepts the same language.\"\"\"\n #debugFile.write( \"\\n\\nEntering determinized............\")\n if hasattr(self, '_isDeterminized'):\n #debugFile.write( \"\\n..............already determinzed\")\n return self\n if len(self.states) > NUMPY_DETERMINIZATION_CUTOFF and NumFSAUtils and not self.getArcMetadata():\n #debugFile.write( \"\\n..............determinzed option 1\")\n data = NumFSAUtils.determinize(*self.tuple() + (self.epsilonClosure,))\n result = apply(self.copy, data).sorted()\n result._isDeterminized = 1\n return result\n transitions = []\n stateSets, index = [tuple(self.epsilonClosure(self.initialState))], 0\n arcMetadata = []\n while index < len(stateSets):\n #debugFile.write( \"\\n..............determinzed option 2\")\n stateSet, index = stateSets[index], index + 1\n localTransitions = list(filter(lambda (s0,s1,l), set=stateSet:l and s0 in set, self.transitions))\n if localTransitions:\n #debugFile.write( \"\\n..............determinzed option 2.1\")\n localLabels = [_____label[2] for _____label in localTransitions] #R: added an underscore\n #debugFile.write( \"\\n..............determinzed option 2.1.1\")\n labelMap = constructLabelMap(localLabels, self.alphabet)\n #debugFile.write( \"\\n..............determinzed option 2.1.2\")\n labelTargets = {} # a map from labels to target states\n for transition in localTransitions:\n #debugFile.write( \"\\n..............determinzed option 2.2\")\n _, s1, l1 = transition\n for label, positives in labelMap:\n #debugFile.write( \"\\n..............determinzed option 2.3\")\n #debugFile.write( \"\\n POSITIVES:\"+str(positives))\n #debugFile.write( \"\\n l1\"+l1)\n if l1 in positives:\n #debugFile.write( \"\\n..............determinzed option 2.4\")\n successorStates = labelTargets[label] = labelTargets.get(label) or []\n for s2 in self.epsilonClosure(s1):\n #debugFile.write( \"\\n..............determinzed option 2.5\")\n if s2 not in successorStates:\n #debugFile.write( \"\\n..............determinzed option 2.6\")\n successorStates.append(s2)\n if self.getArcMetadataFor(transition):\n #debugFile.write( \"\\n..............determinzed option 2.7\")\n arcMetadata.append(((stateSet, successorStates, label), self.getArcMetadataFor(transition)))\n for label, successorStates in labelTargets.items():\n #debugFile.write( \"\\n..............determinzed option 2.8\")\n successorStates.sort()\n successorStates = tuple(successorStates)\n transitions.append((stateSet, successorStates, label))\n if successorStates not in stateSets:\n #debugFile.write( \"\\n..............determinzed option 2.9\")\n stateSets.append(successorStates)\n finalStates = []\n for stateSet in stateSets:\n #debugFile.write( \"\\n..............determinzed option 3\")\n if list(filter(lambda s,finalStates=self.finalStates:s in finalStates, stateSet)):\n #debugFile.write( \"\\n..............determinzed option 3.1\")\n finalStates.append(stateSet)\n if arcMetadata:\n #debugFile.write( \"\\n..............determinzed option 4\")\n def fixArc(pair):\n (s0, s1, label), data = pair\n s1.sort()\n s1 = tuple(s1)\n return ((s0, s1, label), data)\n arcMetadata = list(map(fixArc, arcMetadata))\n result = self.copy(stateSets, self.alphabet, transitions, stateSets[0], finalStates, arcMetadata).sorted()\n result._isDeterminized = 1\n result._isTrimmed = 1\n return result\n \n def minimized(self):\n \"\"\"Returns a minimal FSA that accepts the same language.\"\"\"\n if hasattr(self, '_isMinimized'):\n return self\n #debugFile.write( \"\\n\\tTRIMMED:\\n\\t\\t\"+str(self.trimmed()))\n #debugFile.write( \"\\n\\tDETERMINED:\\n\\t\\t\" + str(self.trimmed().determinized()))\n self = self.trimmed().determinized()\n states0, alpha0, transitions0, initial0, finals0 = self.tuple()\n sinkState = self.nextAvailableState()\n labels = self.labels()\n states = [_f for _f in [\n tuple(filter(lambda s, finalStates=self.finalStates:s not in finalStates, states0)),\n tuple(filter(lambda s, finalStates=self.finalStates:s in finalStates, states0))] if _f]\n labelMap = {}\n for state in states0:\n for label in labels:\n found = 0\n for s0, s1, l in self.transitionsFrom(state):\n if l == label:\n assert not found\n found = 1\n labelMap[(state, label)] = s1\n changed = 1\n iteration = 0\n while changed:\n changed = 0\n iteration = iteration + 1\n #print 'iteration', iteration\n partitionMap = {sinkState: sinkState}\n for set in states:\n for state in set:\n partitionMap[state] = set\n #print 'states =', states\n for index in range(len(states)):\n set = states[index]\n if len(set) > 1:\n for label in labels:\n destinationMap = {}\n for state in set:\n nextSet = partitionMap[labelMap.get((state, label), sinkState)]\n targets = destinationMap[nextSet] = destinationMap.get(nextSet) or []\n targets.append(state)\n #print 'destinationMap from', set, label, ' =', destinationMap\n if len(list(destinationMap.values())) > 1:\n values = list(destinationMap.values())\n #print 'splitting', destinationMap.keys()\n for value in values:\n value.sort()\n states[index:index+1] = list(map(tuple, values))\n changed = 1\n break\n transitions = removeDuplicates(list(map(lambda (s0,s1,label), m=partitionMap:(m[s0], m[s1], label), transitions0)))\n arcMetadata = list(map(lambda ((s0, s1, label), data), m=partitionMap:((m[s0], m[s1], label), data), self.getArcMetadata()))\n if not alpha0:\n newTransitions = consolidateTransitions(transitions)\n if arcMetadata:\n newArcMetadata = []\n for transition, data in arcMetadata:\n s0, s1, label = transition\n for newTransition in newTransitions:\n \n if (newTransition[0] == s0 and newTransition[1] == s1):\n# if labelIntersection(newTransition[2], label):\n# debugFile.write( \"\\n\\nEntered HERE (10)\\n\")\n newArcMetadata.append((newTransition, data))\n arcMetadata = newArcMetadata\n transitions = newTransitions\n initial = partitionMap[initial0]\n finals = removeDuplicates(list(map(lambda s, m=partitionMap:m[s], finals0)))\n result = self.copy(states, self.alphabet, transitions, initial, finals, arcMetadata).sorted()\n result._isDeterminized = 1\n result._isMinimized = 1\n result._isTrimmed = 1\n return result\n \n \n #\n # Presentation Methods\n #\n def __repr__(self):\n if hasattr(self, 'label') and self.label:\n return '<%s on %s>' % (self.__class__.__name__, self.label)\n else:\n return '<%s.%s instance>' % (self.__class__.__module__, self.__class__.__name__)\n \n def __str__(self):\n output = []\n output.append('%s {' % (self.__class__.__name__,))\n output.append('\\tname = %s;' % (self.fsaname,))\n output.append('\\tinitialState = ' + repr(self.initialState) + ';')\n if self.finalStates:\n output.append('\\tfinalStates = ' + string.join(list(map(str, self.finalStates)), ', ') + ';')\n transitions = list(self.transitions)\n transitions.sort()\n for transition in transitions:\n (s0, s1, label) = transition\n additionalInfo = self.additionalTransitionInfoString(transition)\n output.append('\\t%s -> %s %s%s;' % (s0, s1, labelString(label), additionalInfo and ' ' + additionalInfo or ''));\n output.append('}');\n return string.join(output, '\\n')\n \n def additionalTransitionInfoString(self, transition):\n if self.getArcMetadataFor(transition):\n return '<' + string.join(list(map(str, self.getArcMetadataFor(transition))), ', ') + '>'\n \n def stateLabelString(self, state):\n \"\"\"A template method for specifying a state's label, for use in dot\n diagrams. If this returns None, the default (the string representation\n of the state) is used.\"\"\"\n return None\n \n def toDotString(self):\n \"\"\"Returns a string that can be printed by the DOT tool at\n http://www.research.att.com/sw/tools/graphviz/ .\"\"\"\n output = []\n output.append('digraph finite_state_machine {');\n if self.finalStates:\n output.append('\\tnode [shape = doublecircle]; ' + string.join(list(map(str, self.finalStates)), '; ') + ';' );\n output.append('\\tnode [shape = circle];');\n output.append('\\trankdir=LR;');\n output.append('\\t%s [style = bold];' % (self.initialState,))\n for state in self.states:\n if self.stateLabelString(state):\n output.append('\\t%s [label = \"%s\"];' % (state, string.replace(self.stateLabelString(state), '\\n', '\\\\n')))\n transitions = list(self.transitions)\n transitions.sort()\n for (s0, s1, label) in transitions:\n output.append('\\t%s -> %s [label = \"%s\"];' % (s0, s1, string.replace(labelString(label), '\\n', '\\\\n')));\n output.append('}');\n return string.join(output, '\\n')\n \n def view(self):\n view(self.toDotString())\n\n\n#\n# Recognizers for special-case languages\n#\n\nNULL_FSA = FSA([0], None, [], 0, [])\nEMPTY_STRING_FSA = FSA([0], None, [], 0, [0])\nUNIVERSAL_FSA = FSA([0], None, [(0, 0, ANY)], 0, [0])\n\n\n#\n# Utility functions\n#\n\ndef removeDuplicates(sequence):\n result = []\n for x in sequence:\n if x not in result:\n result.append(x)\n return result\n\ndef toFSA(arg):\n if hasattr(arg, 'isFSA') and arg.isFSA:\n #debugFile.write(\"\\nIS FSA: \"+str(arg))\n #print \"\\nIS FSA: \"+str(arg)\n return arg\n else:\n #debugFile.write(\"\\nIS NOT FSA: \"+str(arg))\n #print \"\\nIS NOT FSA: \"+str(arg)\n return singleton(arg)\n\ndef view(str):\n dotfile = tempfile.mktemp()\n psfile = tempfile.mktemp()\n open(dotfile, 'w').write(str)\n dotter = 'dot'\n psviewer = 'gv'\n psoptions = '-antialias'\n os.system(\"%s -Tps %s -o %s\" % (dotter, dotfile, psfile))\n os.system(\"%s %s %s&\" % (psviewer, psoptions, psfile))\n\n\n#\n# Operations on languages (via their recognizers)\n# These generally return nondeterministic FSAs.\n#\n\ndef closure(arg):\n fsa = toFSA(arg)\n states, alpha, transitions, initial, finals = fsa.tuple()\n final = fsa.nextAvailableState()\n transitions = transitions[:]\n for s in finals:\n transitions.append((s, final, None))\n transitions.append((initial, final, None))\n transitions.append((final, initial, None))\n return fsa.create(states + [final], alpha, transitions, initial, [final], fsa.getArcMetadata())\n\ndef complement(arg):\n \"\"\"Returns an FSA that accepts exactly those strings that the argument does\n not.\"\"\"\n return toFSA(arg).complement()\n\ndef concatenation(a, *args):\n \"\"\"Returns an FSA that accepts the language consisting of the concatenation\n of strings recognized by the arguments.\"\"\"\n a = toFSA(a)\n for b in args:\n b = toFSA(b).sorted(a.nextAvailableState())\n states0, alpha0, transitions0, initial0, finals0 = a.tuple()\n states1, alpha1, transitions1, initial1, finals1 = b.tuple()\n a = a.create(states0 + states1, alpha0, transitions0 + transitions1 + list(map(lambda s0, s1=initial1:(s0, s1, EPSILON), finals0)), initial0, finals1, a.getArcMetadata() + b.getArcMetadata())\n return a\n\ndef containment(arg, occurrences=1):\n \"\"\"Returns an FSA that matches sequences containing at least _count_\n occurrences\n of _symbol_.\"\"\"\n arg = toFSA(arg)\n fsa = closure(singleton(ANY))\n for i in range(occurrences):\n fsa = concatenation(fsa, concatenation(arg, closure(singleton(ANY))))\n return fsa\n\ndef difference(a, b):\n \"\"\"Returns an FSA that accepts those strings accepted by the first\n argument, but not the second.\"\"\"\n return intersection(a, complement(b))\n\ndef equivalent(a, b):\n \"\"\"Return true ifff a and b accept the same language.\"\"\"\n return difference(a, b).isEmpty() and difference(b, a).isEmpty()\n\ndef intersection(a, b):\n \"\"\"Returns the intersection of two FSAs\"\"\"\n #debugFile.write(\"\\n\\nEntering intersection..............\")\n #debugFile.write(\"\\n\\nB DETERMINIZED(): \"+str(b.determinized()))\n a, b = completion(a.determinized()), completion(b.determinized()) #***FALLA AQUI, accio sobre b\n #debugFile.write(\"\\n\\nA DETERMINIZED: \"+str(a))\n #debugFile.write(\"\\n\\nB DETERMINIZED: \"+str(b))\n states0, alpha0, transitions0, start0, finals0 = a.tuple()\n states1, alpha1, transitions1, start1, finals1 = b.tuple()\n states = [(start0, start1)]\n index = 0\n transitions = []\n arcMetadata = []\n buildArcMetadata = a.hasArcMetadata() or b.hasArcMetadata()\n while index < len(states):\n state = states[index]\n index = index + 1\n for sa0, sa1, la in a.transitionsFrom(state[0]):\n for sb0, sb1, lb in b.transitionsFrom(state[1]):\n label = labelIntersection(la, lb)\n# debugFile.write( \"\\n\\nEntered HERE (20)\\n\")\n if label:\n s = (sa1, sb1)\n transition = (state, s, label)\n transitions.append(transition)\n if s not in states:\n states.append(s)\n if buildArcMetadata:\n if a.getArcMetadataFor((sa0, sa1, la)):\n arcMetadata.append((transition, a.getArcMetadataFor((sa0, sa1, la))))\n if b.getArcMetadataFor((sa0, sa1, la)):\n arcMetadata.append((transition, b.getArcMetadataFor((sa0, sa1, la))))\n finals = list(filter(lambda (s0, s1), f0=finals0, f1=finals1:s0 in f0 and s1 in f1, states))\n return a.create(states, alpha0, transitions, states[0], finals, arcMetadata).sorted()\n\ndef iteration(fsa, min=1, max=None):\n \"\"\"\n >>> equivalent(iteration(singleton('a', 0, 2)), compileRE('|a|aa'))\n >>> equivalent(iteration(singleton('a', 1, 2)), compileRE('a|aa'))\n >>> equivalent(iteration(singleton('a', 1)), compileRE('aa*'))\n \"\"\"\n if min:\n return concatenation(fsa, iteration(fsa, min=min - 1, max=(max and max - 1)))\n elif max:\n return option(concatenation(fsa), iteration(fsa, min=min, max=max - 1))\n else:\n return closure(fsa)\n\ndef option(fsa):\n return union(fsa, EMPTY_STRING_FSA)\n\ndef reverse(fsa):\n states, alpha, transitions, initial, finals = fsa.tuple()\n newInitial = fsa.nextAvailableState()\n return fsa.create(states + [newInitial], alpha, [(s0_s1_l[1], s0_s1_l[0], s0_s1_l[2]) for s0_s1_l in transitions] + list(map(lambda s1, s0=newInitial:(s0, s1, EPSILON), finals)), [initial])\n\ndef union(*args):\n initial = 1\n final = 2\n states = [initial, final]\n transitions = []\n arcMetadata = []\n for arg in args:\n #debugFile.write(\"\\nARG (1): \"+str(arg))\n #if arg: print \"\\nARG (1):\", arg.tuple()\n #arg = toFSA(arg).sorted(reduce(max, states) + 1)\n arg = toFSA(arg).sortedObligatory(reduce(max, states) + 1)\n #debugFile.write(\"\\nARG (2): \"+str(arg))\n #if arg: print \"\\n\\tARG (2):\", arg.tuple()\n states1, alpha1, transitions1, initial1, finals1 = arg.tuple()\n states.extend(states1)\n #print \"STATES:\", states\n transitions.extend(list(transitions1))\n transitions.append((initial, initial1, None))\n #print \"TRANSITIONS:\", transitions\n for s in finals1:\n transitions.append((s, final, None))\n arcMetadata.extend(arg.getArcMetadata())\n if len(args):\n #print \"RETURN 1:\"\n newFSA= toFSA(args[0]).create(states, alpha1, transitions, initial, [final], arcMetadata)\n #print \"\\t\", newFSA\n return newFSA\n else:\n #print \"RETURN 2\"\n return FSA(states, alpha1, transitions, initial, [final])\n\n\n#\n# FSA Functions\n#\n\ndef completion(fsa):\n \"\"\"Returns an FSA that accepts the same language as the argument, but that\n lands in a defined state for every input.\"\"\"\n states, alphabet, transitions, start, finals = fsa.tuple()\n transitions = transitions[:]\n sinkState = fsa.nextAvailableState()\n for state in states:\n labels = [_____label1[2] for _____label1 in fsa.transitionsFrom(state)] #added underscore insecond argument\n for label in complementLabelSet(labels, alphabet):\n transitions.append((state, sinkState, label)) #added parenthesis pair \n if alphabet:\n transitions.extend(list(map(lambda symbol, s=sinkState:(s, s, symbol), alphabet)))\n else:\n transitions.append((sinkState, sinkState, ANY))\n return fsa.copy(states + [sinkState], alphabet, transitions, start, finals, fsa.getArcMetadata())\n\ndef determinize(fsa):\n return fsa.determinized()\n\ndef minimize(fsa):\n return fsa.minimized()\n\ndef sort(fsa):\n return fsa.sorted()\n\ndef trim(fsa):\n return fsa.trimmed()\n\n\n#\n# Label operations\n#\n\nTRACE_LABEL_OPERATIONS = 0\n\ndef labelComplements(label, alphabet):\n #debugFile.write( \"\\n\\nEntering labelComplementSSS...........\")\n complement = labelComplement(label, alphabet) or []\n if TRACE_LABEL_OPERATIONS:\n pass\n #log('complement(%s) = %s' % (label, complement))\n if type(complement) != ListType:\n complement = [complement]\n return complement\n\ndef labelComplement(label, alphabet):\n #debugFile.write( \"\\n\\nEntering labelComplement...........\")\n if type(label) == InstanceType:\n #debugFile.write( \"\\nHERE.......1\")\n return label.complement()\n elif alphabet:\n #debugFile.write( \"\\nHERE.......2\")\n return list(filter(lambda s, s1=label:s != s1, alphabet))\n elif label == ANY:\n #debugFile.write( \"\\nHERE.......3\")\n return None\n else:\n #debugFile.write( \"\\nHERE.......4\")\n return symbolComplement(label)\n\ndef labelIntersection(l1, l2):\n intersection = _labelIntersection(l1, l2)\n if TRACE_LABEL_OPERATIONS:\n pass\n #log('intersection(%s, %s) = %s' % (l1, l2, intersection))\n return intersection\n\ndef _labelIntersection(l1, l2):\n# debugFile.write( \"\\n\\n--------\\nLABELS:\"+ l1 +\" \" + l2 + \"\\n--------\\n\")\n if l1 == l2:\n #if l1 == l2 or l1 == ANY: \n# debugFile.write( \"\\n\\nSOLUTION 1\")\n return l1\n #todo: is the following ever true\n elif not l1 or not l2:\n# debugFile.write( \"\\n\\nSOLUTION 2\")\n return None\n elif l1 == ANY:\n# debugFile.write( \"\\n\\nSOLUTION 3\")\n return l2\n elif l2 == ANY:\n# debugFile.write( \"\\n\\nSOLUTION 4\")\n return l1\n elif type(l1) == InstanceType:\n# debugFile.write( \"\\n\\nSOLUTION 5\")\n return l1.intersection(l2)\n elif type(l2) == InstanceType:\n# debugFile.write( \"\\n\\nSOLUTION 6\")\n return l2.intersection(l1)\n else:\n# debugFile.write( \"\\n\\nSOLUTION 7\")\n return symbolIntersection(l1, l2)\n\ndef labelString(label):\n return str(label)\n\ndef labelDict(label):\n \"\"\"Given a dict that at some point was string-ified (str(dict)),\n return it into a python dictionary \"\"\"\n return eval(label)\n\ndef labelMatches(label, input):\n #log( \"\\n\\nLABEL MATCHES:\"+label+\" \"+ str(input)+\"?\")\n #print \"LABEL MATCHES:\"+label+\" \"+ str(input)+\"?\"\n if (type(label) is StringType and (label[0] == '{' or label[-1] == '}')):\n \"\"\"Pattern expression has been given in a Python dictionary format \"\"\"\n label = labelDict(label)\n #print \"LABEL in FSA (1): \"+str(label)\n #log(\"\\tMATCH (0.1), STRING:\"+str(input))\n #print \"\\t\\tINPUT class name: \"+str(input.__class__.__name__)\n if (type(input) is InstanceType and\n input.__class__.__name__ in ['Constituent', 'Chunk', 'NounChunk',\n 'VerbChunk', 'Token', 'AdjectiveToken',\n 'EventTag', 'TimexTag']):\n \"\"\"Specific for Evita\"\"\"\n #print \"EVITA: LABEL in FSA (2): \"+str(label)\n return input._matchChunk(label)\n elif type(input) is DictType:\n \"\"\" Open to other dictionary-based object matching applications\"\"\"\n #print \"NON-EVITA: LABEL in FSA (2): \"+str(label)\n return matchDict(label, input)\n else:\n #print \"LABEL:\", label, \"\\nINPUT:\", input.nodeType\n raise Exception(\"ERROR: possibly label is in dict format, but not the input\")\n elif type(label) == InstanceType and hasattr(label, 'matches'):\n #debugFile.write(\"\\n\\tMATCH (1)\")\n #print \"\\n\\tMATCH (1)\"\n return label.matches(input)\n else:\n #debugFile.write(\"\\n\\tMATCH (2)\")\n #print \"\\n\\tMATCH (2)\"\n return label == input \n \ndef matchDict(label, input):\n \"\"\"Match input to the pattern described by label.\n Both label and input are dictionaries with keys-values pairs.\n\n The format of the value in each key-value pair of label can be:\n - an atomic element. E.g., {..., 'headForm':'is', ...} \n - a list of possible values. E.g., {..., headForm': ['have', 'has', 'had'], ...} \n In this case, matchDict checks whether the input value is\n included within this list.\n - a negated value. Negation is represented by means of a\n 2-place tuple, whose initial position is the caret symbol,\n and its second position is the atomic value or list of atomic values\n that need to be negated: '^'. E.g., {..., 'headPos': ('^', 'MD') ...}\n \"\"\" \n labelKeys = list(label.keys())\n inputKeys = list(input.keys())\n for key in labelKeys:\n #print \"KEY:\", key, \"VALUE:\", label[key]\n if key in inputKeys:\n value = label[key]\n if type(value) is TupleType:\n #print \"\\t\\t......TUPLE TYPE\"\n if value[0] == '^':\n value = value[1]\n if type(value) is ListType:\n if input[key] in value:\n return 0\n else:\n if input[key] == value:\n return 0\n else:\n raise Exception(\"ERROR specifying description of pattern\")\n elif type(value) is ListType:\n #print \"\\t\\t......LIST TYPE\"\n if input[key] not in value:\n return 0\n\n else:\n #print \"\\t\\t......ATOMIC TYPE\" \n if input[key] != label[key]:\n return 0\n else: return 0\n else: return 1\n \n#\n# Label set operations\n#\n\nTRACE_LABEL_SET_OPERATIONS = 0\n\ndef complementLabelSet(labels, alphabet=None):\n if not labels:\n return alphabet or [ANY]\n result = labelComplements(labels[0], alphabet)\n for label in labels[1:]:\n result = intersectLabelSets(labelComplements(label, alphabet), result)\n if TRACE_LABEL_SET_OPERATIONS:\n pass\n #log('complement(%s) = %s' % (labels, result))\n return result\n\ndef intersectLabelSets(alist, blist):\n clist = []\n for a in alist:\n for b in blist:\n c = labelIntersection(a, b)\n# debugFile.write( \"\\n\\nEntered HERE (30)\\n\")\n if c:\n clist.append(c)\n if TRACE_LABEL_SET_OPERATIONS:\n pass\n #log('intersection%s = %s' % ((alist, blist), clist))\n return clist\n\ndef unionLabelSets(alist, blist, alphabet=None):\n result = complementLabelSet(intersectLabelSets(complementLabelSet(alist, alphabet), complementLabelSet(blist, alphabet)), alphabet)\n if TRACE_LABEL_SET_OPERATIONS:\n pass\n #log('union%s = %s' % ((alist, blist), result))\n return result\n\n\n#\n# Transition and Label utility operations\n#\n\nTRACE_CONSOLIDATE_TRANSITIONS = 0\nTRACE_CONSTRUCT_LABEL_MAP = 0\n\ndef consolidateTransitions(transitions):\n result = []\n for s0, s1 in removeDuplicates([(s0_s1__[0],s0_s1__[1]) for s0_s1__ in transitions]):\n labels = []\n for ss0, ss1, label in transitions:\n if ss0 == s0 and ss1 == s1:\n labels.append(label)\n if len(labels) > 1:\n reduced = reduce(unionLabelSets, [[label] for label in labels])\n if TRACE_LABEL_OPERATIONS or TRACE_CONSOLIDATE_TRANSITIONS:\n pass\n #log('consolidateTransitions(%s) -> %s' % (labels, reduced))\n labels = reduced\n for label in labels:\n result.append((s0, s1, label))\n return result\n\ndef constructLabelMap(labels, alphabet, includeComplements=0):\n \"\"\"Return a list of (newLabel, positives), where newLabel is an\n intersection of elements from labels and their complemens, and positives is\n a list of labels that have non-empty intersections with newLabel.\"\"\"\n label = labels[0]\n #if hasattr(label, 'constructLabelMap'):\n # return label.constructLabelMap(labels)\n #debugFile.write( \"\\n\\nEntered HERE (130)\\n\")\n complements = labelComplements(label, alphabet)\n #debugFile.write( \"\\n\\nEntered HERE (140)\\n\")\n if len(labels) == 1:\n #debugFile.write( \"\\n\\nEntered HERE (150)\\n\")\n results = [(label, [label])]\n if includeComplements:\n #debugFile.write( \"\\n\\nEntered HERE (160)\\n\")\n #debugFile.write( \"\\nCOMPLEMENTS: \"+str(complements))\n for complement in complements:\n #debugFile.write( \"\\n\\nEntered HERE (170)\\n\")\n results.append((complement, []))\n return results\n results = []\n for newLabel, positives in constructLabelMap(labels[1:], alphabet, includeComplements=1):\n #debugFile.write( \"\\n\\nEntered HERE (180)\\n\")\n newPositive = labelIntersection(label, newLabel)\n #debugFile.write( \"\\n\\nEntered HERE (40)\\n\")\n if newPositive:\n results.append((newPositive, [label] + positives))\n for complement in complements:\n if positives or includeComplements:\n newNegative = labelIntersection(complement, newLabel)\n #debugFile.write( \"\\n\\nEntered HERE (50)\\n\")\n if newNegative:\n results.append((newNegative, positives))\n if TRACE_CONSTRUCT_LABEL_MAP:\n pass\n #log('consolidateTransitions(%s) -> %s' % (labels, results))\n return results\n\n\n#\n# Symbol operations\n#\n\ndef symbolComplement(symbol):\n #debugFile.write( \"\\nSYMBOL: \"+str(symbol))\n if type(symbol) is not StringType:\n symbol = str(symbol)\n\n if '&' in symbol:\n #debugFile.write( \"\\nSYMBOL .........1\")\n return list(map(symbolComplement, string.split(symbol, '&')))\n elif symbol[0] == '~':\n #debugFile.write( \"\\nSYMBOL .........2\")\n return symbol[1:]\n else:\n #debugFile.write( \"\\nSYMBOL .........3\")\n return '~' + str(symbol)\n \n \n\ndef symbolIntersection(s1, s2):\n if type(s1) is StringType: set1 = string.split(s1, '&')\n else: set1 = [str(s1)]\n\n if type(s2) is StringType: set2 = string.split(s2, '&')\n else: set2 = [str(s2)]\n \n for symbol in set1:\n if symbolComplement(symbol) in set2:\n return None\n for symbol in set2:\n if symbol not in set1:\n set1.append(symbol)\n \n if type(s1) is StringType:\n #debugFile.write( \"\\nS1:\"+s1)\n nonNegatedSymbols = [s for s in set1 if s[0] != '~']\n else:\n nonNegatedSymbols = set1\n \n if len(nonNegatedSymbols) > 1:\n return None\n if nonNegatedSymbols:\n return nonNegatedSymbols[0]\n set1.sort()\n return string.join(set1, '&')\n\n\n#\n# Construction from labels\n#\n\ndef singleton(symbol, alphabet=None, arcMetadata=None):\n #debugFile.write( \"\\nSINGLETON\")\n fsa = FSA([0,1], alphabet, [(0, 1, symbol)], 0, [1])\n if arcMetadata:\n fsa.setArcMetadataFor((0, 1, symbol), arcMetadata)\n fsa.label = repr(symbol)\n return fsa\n\ndef sequence(sequence, alphabet=None):\n fsa = reduce(concatenation, list(map(lambda label, alphabet=alphabet:singleton(label, alphabet), sequence)), EMPTY_STRING_FSA)\n fsa.label = repr(sequence)\n return fsa\n\n\n#\n# Compiling Object Patterns represented a la Regular Expressions \n#\n\"\"\"\nprint compileRE('') => compileOP([''])\nprint compileRE('a') => compileOP(['a'])\nprint compileRE('a?') => compileOP(['a'])\nprint compileRE('a+') => compileOP(['a'])\nprint compileRE('a*') => compileOP(['a'])\n\nprint compileRE('ab') => compileOP(['a', 'b'])\nprint compileRE('ab?') => compileOP(['a', 'b'])\nprint compileRE('ab+') => compileOP(['a', 'b'])\nprint compileRE('ab*') => compileOP(['a', 'b'])\nprint compileRE('a?b') => compileOP(['a', 'b'])\nprint compileRE('a+b') => compileOP(['a', 'b'])\nprint compileRE('a*b') => compileOP(['a', 'b'])\n\nprint compileRE('abc') => compileOP(['a', 'b', 'c'])\nprint compileRE('a?bc') => compileOP(['a', 'b', 'c'])\nprint compileRE('a+bc') => compileOP(['a', 'b', 'c'])\nprint compileRE('a*bc') => compileOP(['a', 'b', 'c'])\nprint compileRE('ab?c') => compileOP(['a', 'b','?', 'c'])\nprint compileRE('ab+c') => compileOP(['a', 'b', '+', 'c'])\nprint compileRE('ab*c') => compileOP(['a', 'b', '*', 'c'])\nprint compileRE('abc?') => compileOP(['a', 'b', 'c'])\nprint compileRE('abc+') => compileOP(['a', 'b', 'c'])\nprint compileRE('abc*') => compileOP(['a', 'b', 'c'])\n\nprint compileRE('ab|c') => compileOP(['a', 'b', '|' 'c']) \nprint compileRE('a(b|c)') => compileOP(['a', '(', 'b', '|', 'c', ')'])\n\n\nprint FSA_test.compileOP(['a', 'd', '*', '(', 'b', '|', 'c', ')'])\nprint FSA_test.compileOP(['a', 'd', '+', 'e', '(', 'b', '|', 'c', ')'])\nprint FSA_test.compileOP(['a', 'd', '+', 'e', '(', 'b', '|', 'c', ')', 'f'])\nprint FSA_test.compileOP(['a', 'd', '+', 'e', '(', 'b', '|', 'c', ')', '(', 'f', '*', 'g', '|', 'h', ')'])\nprint FSA_test.compileOP(['a', 'd', '+', 'e', '(', 'b', '|', 'c', ')', '(', 'f', '*', 'g', '|', 'h', ')', 'i'])\n\"\"\"\n\nclass Sequence(object):\n\n def __init__(self, pattern):\n# print \"\\nENTERING SEQUENCE............\\n\"\n self.sequence = pattern\n self.bordersDict = {}\n self.buildBordersDict()\n\n def __getitem__(self, index):\n if index < len(self.sequence):\n return self.sequence[index]\n else:\n return\n\n def __getslice__(self, i, j):\n return self.sequence[i:j]\n\n def __len__(self):\n return len(self.sequence)\n\n \n def buildBordersDict(self):\n \"\"\"*** COMMENT needs to be added ***\"\"\"\n previousBorder = {}\n currentSubpattern = 0\n previousBorder[currentSubpattern] = 0 # Index of previous bar in currentSubpattern\n for i in range(len(self.sequence)):\n #print \"ITEM:\", i, self.sequence[i], \"CURRENT SUBPATTERN:\", currentSubpattern\n if type(self.sequence[i]) is StringType : \n if self.sequence[i] == '(':\n currentSubpattern = currentSubpattern+1\n #print \"\\tCURRENT SUBPATTERN:\", currentSubpattern\n \n elif self.sequence[i][0] == ')':\n try:\n previousBorderIndex = previousBorder[currentSubpattern]\n self.bordersDict[previousBorderIndex] = i\n except: pass\n\n previousBorder[currentSubpattern] = None\n if currentSubpattern:\n currentSubpattern = currentSubpattern-1\n else:\n \"\"\"currentSubpattern may be 0 either because there is an error,\n or because we are in a subpattern that resetted\n the currentSubpattern variable to 0 \"\"\"\n if self.__class__.__name__ == \"Sequence\": pass\n else: raise Exception(\"ERROR (1): expression missing at least one '('\")\n \n elif self.sequence[i] == '|':\n try:\n previousBorderIndex = previousBorder[currentSubpattern]\n self.bordersDict[previousBorderIndex] = i\n except: pass\n previousBorder[currentSubpattern] = i\n if currentSubpattern != 0:\n raise Exception(\"ERROR (2): expression missing at least one ')'\")\n \n def getNextBorder(self, index):\n try: return self.bordersDict[index]\n except: return -1 \n\nclass SyntaxSequence(Sequence):\n\n def __init__(self, description):\n #print \"\\nENTERING SYNTAX SEQUENCE............\\n\"\n Sequence.__init__(self, description)\n self.description = description\n self.label = string.join(str(self.description), '_')\n self.sequence = self.atomizeDescription()\n\n def atomizeDescription(self):\n #print \"ATOMIZING descriotion...\\n\"\n res = []\n for item in self.description:\n #debugFile.write( \"\\nITEM: \"+str(item))\n if len(item) > 1:\n #if type(item) is StringType:\n if type(item) is not StringType:\n item = str(item)\n \n if item[0] in ['(','[','|']:\n #print \"SIT 1\"\n if len(item) > 1:\n raise Exception('ERROR (1): check syntax for pattern: '+ str(self.description))\n else:\n res.append(item)\n if item[0] == '~':\n #print \"SIT 2\"\n res.append(item[0])\n res.append(item[1:])\n\n elif item[-1] in ['(','[','|']:\n #print \"SIT 3\"\n if len(item) > 1:\n raise Exception('ERROR (2): check syntax for pattern: '+ str(self.description))\n else:\n pass\n elif item[-1] in [')',']']:\n #print \"SIT 4\"\n if len(item) > 1:\n raise Exception('ERROR (3): check syntax for pattern: '+ str(self.description))\n else:\n res.append(item)\n elif item[-1] in ['*','+','?']:\n #print \"SIT 5\"\n res.append(item[:-1])\n res.append(item[-1])\n else:\n #print \"SIT 6\"\n res.append(item)\n\n# else:\n# #debugFile.write( \"\\nAPPENDING...(1)\"+str(item))\n# res.append(item)\n else:\n #debugFile.write( \"\\nAPPENDING...(2)\"+str(item))\n res.append(str(item))\n return res\n\n\n \n\ndef compileOP(description, **options):\n \"\"\"description is a list of labels describing constituents,\n where each constituent can be a lexical item (token)\n or a chunk. *** CONTINUAR\n\n Labels in description CAN NOT use '_' (underscore)\n \"\"\"\n\n pattern = SyntaxSequence(description)\n #debugFile.write( \"\\nENTIRE PATTERN: \"+str(pattern.sequence))\n \n fsa, index = compileOPExpr(pattern, 0, options)\n #debugFile.write( \"PATERN:\"+str(pattern)+\"INDEX:\"+str(index))\n\n\n if index < len(pattern):\n raise Exception('extra character in pattern (possibly \")\" )')\n fsa.label = pattern.label\n #debugFile.write( \"\\n=\\n\\tFSA MINIMIZED:\\n\\t\\t\")\n #debugFile.write(str(fsa.minimized()))\n fsa_min = fsa.minimized()\n #print \"FSA min:\\n\\t\"+str(fsa_min)\n #debugFile.close()\n fsa_min.fsaname = options.get('name')\n #print fsa_min\n return fsa_min\n\ndef compileOPExpr(pattern, index, options):\n #debugFile.write( \"\\n\\nCOMPILE OP EXPR\")\n barFlag = 0\n fsa = None\n while index < len(pattern) and pattern[index] != ')':\n #debugFile.write( \"\\ncompileOPExpr_while\")\n\n if pattern[index] == '|':\n index = index + 1\n endIndex = pattern.getNextBorder(index-1)\n if endIndex == -1:\n pattern2 = Sequence(pattern[index:])\n #debugFile.write( \"\\nSUBPATTEW 1:\"+str(pattern[index:]))\n #print \"SUBPATTEW 1:\"+str(pattern[index:])\n else:\n pattern2 = Sequence(pattern[index:endIndex])\n #debugFile.write( \"\\nSUBPATTEW 2:\"+str( pattern[index:endIndex]))\n #print \"SUBPATTEW 2:\"+str( pattern[index:endIndex])\n #debugFile.write( \"\\nINDEX:\"+str(index))\n #print \"INDEX:\"+str(index)\n #debugFile.write( \"\\nNEXT BORDER\"+str(pattern.getNextBorder(index-1)))\n #print \"NEXT BORDER\"+str(pattern.getNextBorder(index-1))\n\n fsa2, index2 = compileOPExpr(pattern2, 0, options)\n index = index + index2\n\n else:\n fsa2, index = compileConjunctionOP(pattern, index, options)\n \n #debugFile.write( \"\\nFSA_compileOPExpr:\\n\\t\\t\"+str(fsa))\n #if fsa: debugFile.write(\"\\nvoc: \"+str(fsa.states)+\" \"+str(fsa.alphabet)+\" \"+str(fsa.transitions)+\" \"+str(fsa.initialState)+\" \"+str(fsa.finalStates)+\" \")#+str(fsa.arcMetadata))\n \n #debugFile.write( \"\\nFSA2_compileOPExpr:\\n\\t\\t\"+str(fsa2))\n #if fsa2: debugFile.write(\"\\nvoc: \"+str(fsa2.states)+\" \"+str(fsa2.alphabet)+\" \"+str(fsa2.transitions)+\" \"+str(fsa2.initialState)+\" \"+str(fsa2.finalStates)+\" \")#+str(fsa2.arcMetadata))\n fsa3= union(fsa, fsa2) ##debug\n #debugFile.write( \"\\nFSA_compileOPExpr_Union:\\n\\t\\t\"+str(fsa3))\n #print \"UNION:\", union(fsa, fsa2)\n\n fsa = (fsa and union(fsa, fsa2)) or fsa2\n #debugFile.write( \"\\nFSA_Result :\\n\\t\\t\"+str(fsa))\n fsa4 = fsa.minimized() #debug\n #debugFile.write( \"\\nFSA_Result min:\\n\\t\\t\"+str(fsa4))\n #print \"MINIMIZD:\", fsa.minimized()\n \n return (fsa or EMPTY_STRING_FSA), index\n\ndef compileConjunctionOP(pattern, index, options):\n #debugFile.write( \"\\n\\n\\tCOMPILE CONJUNCTION OP\")\n fsa = UNIVERSAL_FSA\n while pattern[index] and pattern[index] not in [')','|']:\n #debugFile.write( \"\\n\\tcompileConjunctionOP_while\")\n conjunct, index = compileSequenceOP(pattern, index, options)\n if pattern[index] == '&':\n index = index + 1\n #debugFile.write( \"\\n\\tFSA_compileConjunctionOP:\\n\\t\\t\"+str(fsa))\n #debugFile.write( \"\\n\\tFSA_Conjunct:\\n\\t\\t\"+str(conjunct))\n \n fsa = intersection(fsa, conjunct) #*** lo que falla es crida aqui\n #debugFile.write( \"\\n\\tFSA_Result :\\n\\t\\t\"+str(fsa))\n #debugFile.write( \"\\n\\tFSA_Result min:\\n\\t\\t\"+str(fsa.minimized()))\n return fsa, index\n\ndef compileSequenceOP(pattern, index, options):\n ##debugFile.write( \"\\n\\n\\t\\tCOMPILE SEQUENCE OP\")\n fsa = EMPTY_STRING_FSA\n while pattern[index] and pattern[index] not in [')','|','&']:\n ##debugFile.write( \"\\n\\n\\n======================================\\n\")\n ##debugFile.write( \"\\n======================================\\n\")\n ##debugFile.write( \"\\n\\t\\tcompileSequenceOP_while\")\n ##debugFile.write( \"\\n\\t\\tcompileSequenceOP_Index1:\"+ str(index))\n ##debugFile.write( \"\\n\\t\\tcompileSequenceOP_pattern[index]:\"+ str(pattern[index]))\n fsa2, index = compileItemOP(pattern, index, options)\n ##debugFile.write( \"\\n\\t\\tcompileSequenceOP_FSA:\\n\\t\\t\"+str(fsa))\n ##debugFile.write( \"\\n\\t\\tFcompileSequenceOP_SA2:\\n\\t\\t\"+str(fsa2))\n fsa = concatenation(fsa, fsa2)\n ##debugFile.write( \"\\n\\t\\t===============================>>>>>>> FSA_Concat:\\n\\t\\t\"+str(fsa))\n ##debugFile.write( \"\\n\\tcompileSequenceOP_FSA_Concat min:\\n\\t\\t\"+str(fsa.minimized()))\n return fsa, index\n\ndef compileItemOP(pattern, index, options):\n ##debugFile.write( \"\\n\\n\\t\\t\\tCOMPILE ITEM OP\")\n c = pattern[index]\n index = index + 1\n while c == ' ':\n ##debugFile.write( \"\\nHERE 1:\")\n c = pattern[index]\n index = index + 1\n if c == '(':\n ##debugFile.write( \"\\nHERE 2:\")\n fsa, index = compileOPExpr(pattern, index, options)\n assert pattern[index] == ')'\n index = index + 1\n elif c == '.':\n ##debugFile.write( \"\\nHERE 3:\")\n fsa = singleton('ALL') #fsa = singleton(ANY) \n elif c == '~':\n ##debugFile.write( \"\\nHERE 4:\")\n fsa, index = compileItemOP(pattern, index, options)\n #print \"SO FAR FSA:\", fsa\n fsa = complement(fsa)\n #print \"ITS COMPLEMENT:\", fsa\n else:\n ##debugFile.write( \"\\nHERE 5:\")\n# #debugFile.write( \"\\nC:\", c)\n label = c\n if options.get('multichar'):\n # #debugFile.write( \"\\nHERE 6:\")\n while ((pattern[index] in string.letters or pattern[index] in string.digits) and\n index < len(pattern)): ### CAL CANVIAR CONDICIONS string.letter!!!\n # #debugFile.write( \"\\nHERE 7:\")\n label = label + pattern[index]\n index = index + 1\n if pattern[index] == ':':\n # #debugFile.write( \"\\nHERE 8:\")\n index = index + 1\n upper = label\n lower = pattern[index]\n index = index + 1\n if upper == '0':\n # #debugFile.write( \"\\nHERE 9:\")\n upper = EPSILON\n if lower == '0':\n # #debugFile.write( \"\\nHERE 10:\")\n lower = EPSILON\n label = (upper, lower)\n fsa = singleton(label)\n while pattern[index] in ['?','*','+']:\n ##debugFile.write( \"\\nHERE 11:\")\n c = pattern[index]\n index = index + 1\n if c == '*':\n fsa = closure(fsa)\n elif c == '?':\n fsa = union(fsa, EMPTY_STRING_FSA)\n elif c == '+':\n fsa = iteration(fsa)\n else:\n raise Exception('unimplemented')\n return fsa, index\n\n\n#\n# Compiling Regular Expressions\n#\n\ndef compileRE(s, **options):\n if not options.get('multichar'):\n s = string.replace(s, ' ', '')\n fsa, index = compileREExpr(s + ')', 0, options)\n if index < len(s):\n raise Exception('extra ' + repr(')'))\n fsa.label = str(s)\n return fsa.minimized()\n\ndef compileREExpr(str, index, options):\n fsa = None\n while index < len(str) and str[index] != ')':\n fsa2, index = compileConjunction(str, index, options)\n if str[index] == '|': index = index + 1\n fsa = (fsa and union(fsa, fsa2)) or fsa2\n return (fsa or EMPTY_STRING_FSA), index\n\ndef compileConjunction(str, index, options):\n fsa = UNIVERSAL_FSA\n while str[index] not in ')|':\n conjunct, index = compileSequence(str, index, options)\n if str[index] == '&': index = index + 1\n fsa = intersection(fsa, conjunct)\n return fsa, index\n\ndef compileSequence(str, index, options):\n fsa = EMPTY_STRING_FSA\n while str[index] not in ')|&':\n fsa2, index = compileItem(str, index, options)\n fsa = concatenation(fsa, fsa2)\n return fsa, index\n\ndef compileItem(str, index, options):\n c , index = str[index], index + 1\n while c == ' ':\n c, index = str[index], index + 1\n if c == '(':\n fsa, index = compileREExpr(str, index, options)\n assert str[index] == ')'\n index = index + 1\n elif c == '.':\n fsa = singleton('ALL')\n elif c == '~':\n fsa, index = compileItem(str, index, options)\n fsa = complement(fsa)\n else:\n label = c\n if options.get('multichar'):\n ##debugFile.write( \"\\nMULTICHAR!\")\n while str[index] in string.letters or str[index] in string.digits:\n label, index = label + str[index], index + 1\n if str[index] == ':':\n index = index + 1\n upper = label\n lower, index = str[index], index + 1\n if upper == '0':\n upper = EPSILON\n if lower == '0':\n lower = EPSILON\n label = (upper, lower)\n fsa = singleton(label)\n while str[index] in '?*+':\n c, index = str[index], index + 1\n if c == '*':\n fsa = closure(fsa)\n elif c == '?':\n fsa = union(fsa, EMPTY_STRING_FSA)\n elif c == '+':\n fsa = iteration(fsa)\n else:\n raise Exception('unimplemented')\n return fsa, index\n\n\"\"\"\nTRACE_LABEL_OPERATIONS = 1\nTRACE_LABEL_OPERATIONS = 0\n\nprint compileRE('')\nprint compileRE('a')\nprint compileRE('ab')\nprint compileRE('abc')\nprint compileRE('ab*')\nprint compileRE('a*b')\nprint compileRE('ab*c')\nprint compileRE('ab?c')\nprint compileRE('ab+c')\nprint compileRE('ab|c')\nprint compileRE('a(b|c)')\n\nprint compileRE('abc').accepts('abc')\nprint compileRE('abc').accepts('ab')\n\nprint singleton('1', alphabet=['1']).minimized()\nprint complement(singleton('1')).minimized()\nprint singleton('1', alphabet=['1'])\nprint completion(singleton('1'))\nprint completion(singleton('1', alphabet=['1']))\nprint complement(singleton('1', alphabet=['1']))\nprint complement(singleton('1', alphabet=['1', '2']))\nprint complement(singleton('1', alphabet=['1', '2'])).minimized()\n\nprint intersection(compileRE('a*b'), compileRE('ab*'))\nprint intersection(compileRE('a*cb'), compileRE('acb*'))\nprint difference(compileRE('ab*'), compileRE('abb')).minimized()\n\nprint compileRE('n.*v.*n')\nprint compileRE('n.*v.*n&.*n.*n.*n.*')\n\nprint intersection(compileRE('n.*v.*n'), compileRE('.*n.*n.*n.*'))\nprint difference(compileRE('n.*v.*n'), compileRE('.*n.*n.*n.*'))\nprint difference(difference(compileRE('n.*v.*n'), compileRE('.*n.*n.*n.*')), compileRE('.*v.*v.*'))\n\nprint compileRE('a|~a').minimized()\n\n\nprint containment(singleton('a'), 2).minimized()\nprint difference(containment(singleton('a'), 2), containment(singleton('a'), 3)).minimized()\nprint difference(containment(singleton('a'), 3), containment(singleton('a'), 2)).minimized()\n\nprint difference(compileRE('a*b'), compileRE('ab*')).minimized()\n\n\"\"\"\n"} {"doc_id": "4085f2bf1d631a07c02e6ff17219f9bc", "text": "'''\nWith a function we actually have special variables we use, which\nare *args and **kwargs.\n\nIf we have to give more than 1 positional argument to a \nfunction, we use *args. For example, the following code will \nraise a TypeError:\n\n def super_func(args):\n return sum(args)\n\n super_func(1,2,3,4,5)\n\nError description: \nTypeError: super_func() takes in 1 positional argument but 5 were given\n\n\nNow, for any function to take in a variable amount of arguments, \nwe've to pass the arguments to *args in the function as shown \nbelow:\n'''\n\ndef super_func(*args):\n print(args) # (1, 2, 3, 4, 5) <- tuple\n print(*args) # 1 2 3 4 5 <- tuple unpacked and spaced\n return sum(args)\n\nprint(super_func(1, 2, 3, 4, 5)) # 15 \n\n\n'''\nWe can see that *args as the parameter to the super_func \nfunction takes in the parameters as a tuple. We generally name it\nas *args, but we can technically name it as any name we want.\n\nMoving on to **kwargs, (which stands for \"Keyword Arguments\") it \nis used for defining parameters while calling the function.\n\nWe can see the example below which uses both *args and **kwargs:\n'''\n\ndef super_function(*args, **kwargs):\n print(args) # (1, 2, 3, 4, 5) <- tuple\n print(kwargs) # {'num1': 5, 'num2': 10} <- dict\n total = 0\n for items in kwargs.values():\n total += items\n return sum(args) + total\n\nprint(super_function(1, 2, 3, 4, 5, num1=5, num2=10))\n\n\n\"\"\"\nPTR: There's an actual ordering recommended by python3 docs for \ndefining the parameters in a function definition/call and it is:\n\n --------------first to last-------------------->\ndef func(positional_params, *args, default_args, **kwargs):\n # your code\n\"\"\""} {"doc_id": "4099aca61309d3b66cbcf41ada578acf", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time : 2018/3/6 11:30\n# @Author : yulu\n# @File : iter_study\nimport sys\n\n# \u751f\u6210\u5668\u51fd\u6570\n# \u5b9e\u73b0\u6590\u6ce2\u7eb3\u5951\u6570\u5217\ndef fibonacci(n):\n # \u521d\u59cb\u5316\u53d8\u91cf\n a, b, count = 0, 1, 0\n\n while True:\n if count > n:\n return\n\n yield a\n\n a, b = b, b + a\n count = count + 1\n\nif __name__ == \"__main__\":\n\n seq_tuple = (1, 2, 3, 4, 5)\n\n # \u521b\u5efa\u8fed\u4ee3\u5668\n seq_it = iter(seq_tuple)\n\n # \u8bbf\u95ee\u7b2c\u4e00\u4e2a\u5143\u7d20\n print(\"\u7b2c\u4e00\u4e2a\u5143\u7d20\uff1a %s\" % next(seq_it))\n\n # \u8bbf\u95ee\u7b2c\u4e8c\u4e2a\u5143\u7d20\n print(\"\u7b2c\u4e8c\u4e2a\u5143\u7d20\uff1a %s\" % next(seq_it))\n\n # \u8bbf\u95ee\u7b2c\u4e09\u4e2a\u5143\u7d20\n print(\"\u7b2c\u4e09\u4e2a\u5143\u7d20\uff1a %s\" % next(seq_it))\n\n # \u8bbf\u95eefor\u5faa\u73af\u6765\u904d\u5386\u8fed\u4ee3\u5668\u5bf9\u8c61\n print(\"\\nfor\u5faa\u73af\u8fed\u4ee3\u5668\u5bf9\u8c61\uff1a \")\n for_it = iter(seq_tuple)\n for i in for_it:\n print(i, end=\" \")\n\n # \u4f7f\u7528 while \u7ed3\u5408next\u904d\u5386\u8fed\u4ee3\u5668\u5bf9\u8c61\n\n print(\"\\nwhile & next\u904d\u5386\u8fed\u4ee3\u5668\u5bf9\u8c61\uff1a \")\n while_it = iter(seq_tuple)\n while True:\n try:\n print(next(while_it))\n except StopAsyncIteration:\n sys.exit()\n\n print(\"-----------------------------\")\n\n f = fibonacci(10)\n while True:\n try:\n print(next(f), end=\" \")\n except StopAsyncIteration:\n sys.exit(0)\n\n # \u4e3a\u4ec0\u4e48\u62a5\u9519\u662f\u6b63\u5e38\u7684\uff1f\uff1f\uff1f"} {"doc_id": "40a314141c3a577f39103800a3cc08f2", "text": "'''\n\nDescription:\n\nGiven the root of a binary tree and two integers val and depth, add a row of nodes with value val at the given depth depth.\n\nNote that the root node is at depth 1.\n\nThe adding rule is:\n\nGiven the integer depth, for each not null tree node cur at the depth depth - 1, create two tree nodes with value val as cur's left subtree root and right subtree root.\ncur's original left subtree should be the left subtree of the new left subtree root.\ncur's original right subtree should be the right subtree of the new right subtree root.\nIf depth == 1 that means there is no depth depth - 1 at all, then create a tree node with value val as the new root of the whole original tree, and the original tree is the new root's left subtree.\n \n\nExample 1:\n\n\nInput: root = [4,2,6,3,1,5], val = 1, depth = 2\nOutput: [4,1,1,2,null,null,6,3,1,5]\n\n\n\nExample 2:\n\n\nInput: root = [4,2,null,3,1], val = 1, depth = 3\nOutput: [4,2,null,1,1,3,null,null,1]\n \n\nConstraints:\n\nThe number of nodes in the tree is in the range [1, 104].\nThe depth of the tree is in the range [1, 104].\n-100 <= Node.val <= 100\n-105 <= val <= 105\n1 <= depth <= the depth of tree + 1\n\n'''\n\nfrom typing import List\n\nclass TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\n\nclass Solution:\n\n def addOneRow(self, root: TreeNode, v: int, d: int) -> TreeNode:\n\n if not root:\n\n # bcase case: empty tree\n return None\n\n elif d == 1:\n\n # base case: add one row above original root\n return TreeNode(v, left=root, right=None)\n\n elif d == 2:\n\n # base case: add one row below original root\n root.left = TreeNode(v, left=root.left, right=None)\n root.right = TreeNode(v, left=None, right=root.right)\n\n return root\n else:\n\n # general case: depth >= 3\n # do it in DFS with common pattern\n root.left = self.addOneRow(root.left, v, d-1)\n root.right = self.addOneRow(root.right, v, d-1)\n\n return root\n\n\n\n# n : the number of nodes\n\n## Time Complexity: O( n )\n#\n# The overhead in time is the cost of DFS, which is of O( n )\n\n## Space Complexity: O( n )\n#\n# The overhead in space is the storage for recursion, which is of O( n )\n\n\ndef levelOrder( root: TreeNode) -> List[List[int]]:\n \n \n if not root:\n # Quick response for empty tree\n return []\n \n traversal_queue, result = [root], []\n \n # level order traversal\n while traversal_queue:\n \n # add current level into result\n result.append([node.val for node in traversal_queue])\n \n # record current level child nodes\n child_pair = [(node.left, node.right) for node in traversal_queue]\n \n # update traversal queue with next level nodes\n traversal_queue = [ child for pair in child_pair for child in pair if child ]\n \n return result\n\n# ----------------------------------------\n\nimport unittest\n\nclass Testing( unittest.TestCase ):\n\n def test_case_1(self):\n\n root = TreeNode(4)\n\n root.left = TreeNode(2)\n root.right = TreeNode(6)\n\n root.left.left = TreeNode(3)\n root.left.right = TreeNode(1)\n\n root.right.left = TreeNode(5)\n\n root = Solution().addOneRow(root, v=1, d=2)\n result = levelOrder(root)\n self.assertEqual(result, [[4], [1,1], [2,6], [3,1,5]])\n\n\n def test_case_2(self):\n\n root = TreeNode(4)\n\n root.left = TreeNode(2)\n\n root.left.left = TreeNode(3)\n root.left.right = TreeNode(1)\n\n root = Solution().addOneRow(root, v=1, d=3)\n result = levelOrder(root)\n self.assertEqual(result, [[4], [2], [1,1], [3,1]])\n\n\nif __name__ == '__main__':\n\n unittest.main()"} {"doc_id": "40ac1ba5fae2015211ed8046da42d714", "text": "# -*- coding: utf-8 -*-\r\n\"\"\"Language Tour: Class\"\"\"\r\nimport abc\r\n\r\n\r\n# Class\r\nclass Complex:\r\n \"\"\"A class supposed to be a complex, but lost his meaning of life.\r\n\r\n Parameters\r\n ----------\r\n realpart : float\r\n Partie r\u00e9elle\r\n imagpart : float\r\n Partie imaginaire\r\n\r\n Attributes\r\n ----------\r\n public_property : str\r\n Propri\u00e9t\u00e9 publique, accessible partout\r\n _protected_property : str\r\n Propri\u00e9t\u00e9 prot\u00e9g\u00e9, accessible pour ses subclasses\r\n __encrypted_password : str\r\n Propri\u00e9t\u00e9 priv\u00e9e, accessible uniquement sur soi\r\n \"\"\"\r\n public_property = \"Hey i'm public\" # Read and write everywhere\r\n _protected_property = \"Hey i'm protected\" # Read and write from subclass\r\n __private_property = \"Hey i'm private\" # Read and write self\r\n __get_only_m8 = \"README\" # Read only self\r\n __encrypted_password = \"setmein\" # Read, Write throught getter/setter self\r\n\r\n def __init__(self, realpart: float, imagpart: float): # Constructor\r\n if realpart == 0:\r\n raise ValueError(\"This is retarded but 0 is not allowed\")\r\n self.realpart = realpart # instance var \u00e0 initialiser\r\n self.imagpart = imagpart\r\n\r\n def method(self):\r\n \"\"\"do\"\"\"\r\n\r\n # Getter : Read only use case\r\n # getter\r\n @property\r\n def readme(self) -> str:\r\n \"\"\"doc\"\"\"\r\n return self.__get_only_m8\r\n\r\n # Getter, Setter: Calculus use case\r\n # getter\r\n @property\r\n def password(self) -> str:\r\n \"\"\"doc\"\"\"\r\n print(\"Decrypting...\")\r\n return self.__encrypted_password\r\n\r\n # setter\r\n @password.setter\r\n def password(self, value: str) -> str:\r\n \"\"\"doc\"\"\"\r\n print(\"Encrypting... Get some salt...\")\r\n self.__encrypted_password = value\r\n\r\n @staticmethod\r\n def static_func(arg: int) -> int: # static\r\n \"\"\"doc\"\"\"\r\n print(Complex.__private_property)\r\n return arg\r\n\r\n @classmethod\r\n def named_contructor(\r\n cls,\r\n complex_var: complex,\r\n ): # Constructor with a name\r\n \"\"\"doc\"\"\"\r\n return cls(complex_var.real, complex_var.imag)\r\n\r\n @abc.abstractmethod\r\n def abstract_func(self, arg: int):\r\n \"\"\"doc\"\"\"\r\n raise NotImplementedError\r\n\r\n\r\nclass HeritFrom(Complex):\r\n \"\"\"Empty caus' don't want to fill\"\"\"\r\n\r\n def abstract_func(self, arg: int):\r\n \"\"\"I'm an implemented function.\"\"\"\r\n return arg\r\n\r\n\r\nif __name__ == \"__main__\":\r\n complex_class = Complex(1, 2)\r\n complex_class = Complex.named_contructor(complex(1, 2))\r\n\r\n print(complex_class.public_property)\r\n print(complex_class.realpart)\r\n print(complex_class.imagpart)\r\n complex_class.password = \"my password\"\r\n print(complex_class.password)\r\n print(complex_class.readme)\r\n try:\r\n complex_class.abstract_func(10) # => NotImplementedError\r\n except NotImplementedError as error:\r\n print(error)\r\n print(Complex.static_func(100))\r\n\r\n complex_class2 = HeritFrom(1, 2)\r\n print(complex_class2.abstract_func(10)) # => 10\r\n"} {"doc_id": "40b1290204b45b17749bb41c91b7cc07", "text": "#04 - Utilizando fun\u00e7\u00f5es e listas fa\u00e7a um programa que receba uma data no formato DD/MM/AAAA e devolva uma string no formato DD de mesPorExtenso de AAAA. Opcional: valide a data e retorne 'data inv\u00e1lida' caso a data seja inv\u00e1lida.\n\nfrom os import system\n\ndef mesPorExtenso():\n system('cls') # limpa o prompt de comando\n dia = int(input('Digite o dia[DD]: ')) # usu\u00e1rio digita um dia v\u00e1lido [1 - 31]\n mes = int(input('Digite o m\u00eas[MM]: ')) # usu\u00e1rio digita um mes v\u00e1lido [1 - 12]\n ano = int(input('Digite o ano[AAAA]: ')) # usu\u00e1rio digita um ano v\u00e1lido\n meses = ['Janeiro', 'Fevereiro', 'Mar\u00e7o', 'Abril', 'Maio', 'Junho', 'Julho', 'Agosto', 'Setembro', 'Outubro', 'Novembro', 'Dezembro'] # lista com todos os meses, por extenso\n\n for i, m in enumerate(meses): # i = \u00edndice , m = meses por extenso\n if mes == i +1: # se o mes for igual a i + 1...\n mes = m # mes recebe o mes por extenso correspondente ao seu i\n\n if dia > 29 and mes == 'Fevereiro': # se o dia for maior que 29 e o mes for fevereiro... \n print('\\nData Inv\u00e1lida! Fevereiro s\u00f3 pode ter at\u00e9 29 dias!\\n')\n\n elif dia > 31: # se o dia for maior que 31 ...\n print('\\nData Inv\u00e1lida! Os meses s\u00f3 podem ter at\u00e9 31 dias (exceto fevereiro)\\n')\n \n elif mes not in meses: # se o mes n\u00e3o estiver dentro da lista de meses...\n print('\\nData inv\u00e1lida! Meses s\u00f3 v\u00e3o at\u00e9 12!\\n')\n\n elif ano < 0: # se o ano for negativo...\n print(f'\\n-=-=-=-=-=-=-=-=-=-\\n{dia} de {mes} de {ano * -1} a.C\\n=-=-=-=-=-=-=-=-=-\\n')\n \n else: # se nenhuma das condi\u00e7\u00f5es acima for atendida ...\n print(f'\\n-=-=-=-=-=-=-=-=-=-\\n{dia} de {mes} de {ano}\\n=-=-=-=-=-=-=-=-=-\\n')\n\n\nmesPorExtenso()\n\n"} {"doc_id": "40efd3623fcdd60e3bc563ecb9b03eb9", "text": "\"\"\"\nBinary search trees are a data structure that enforce an ordering over \nthe data they store. That ordering in turn makes it a lot more efficient \nat searching for a particular piece of data in the tree. \n\nThis part of the project comprises two days:\n1. Implement the methods `insert`, `contains`, `get_max`, and `for_each`\n on the BSTNode class.\n2. Implement the `in_order_print`, `bft_print`, and `dft_print` methods\n on the BSTNode class.\n\"\"\"\nclass BSTNode:\n def __init__(self, value):\n self.value = value\n self.left = None\n self.right = None\n\n # Insert the given value into the tree\n # Return statements technically aren't needed\n def insert(self, value):\n if value >= self.value:\n if self.right is None:\n self.right = BSTNode(value)\n return\n else:\n self = self.right\n return self.insert(value)\n\n elif value < self.value:\n if self.left is None:\n self.left = BSTNode(value)\n return\n else:\n self = self.left\n return self.insert(value)\n\n # Return True if the tree contains the value\n # False if it does not\n def contains(self, target):\n if self.value == target:\n return True\n\n elif target > self.value:\n if self.right is None:\n return False\n else:\n self = self.right\n return self.contains(target)\n\n else: \n if self.left is None:\n return False\n else:\n self = self.left\n return self.contains(target)\n\n # Return the maximum value found in the tree\n def get_max(self):\n # If the root value is the highest, just return the value\n if self.right is None:\n return self.value\n else:\n # Move along to the next subtree that has the higher value and repeat\n self = self.right\n return self.get_max()\n\n # Call the function `fn` on the value of each node\n def for_each(self, fn):\n # Why is this the first line?\n # \n fn(self.value)\n\n if self.right is not None:\n self.right.for_each(fn)\n if self.left is not None:\n self.left.for_each(fn)\n\n # Part 2 -----------------------\n\n # Print all the values in order from low to high\n # Hint: Use a recursive, depth first traversal\n # Lowest number is always the furthest to the left\n def in_order_print(self, node):\n # Base Case\n if node is None:\n if node.left:\n node.in_order_print(node.left)\n \n print(node.value)\n\n if node.right:\n node.in_order_print(node.right)\n\n # Print the value of every node, starting with the given node,\n # in an iterative breadth first traversal\n # Use a Queue\n def bft_print(self, node):\n stack = [node]\n\n while stack != []:\n look = stack[0]\n\n if look.right:\n stack.append(look.right)\n if look.left:\n stack.append(look.left)\n\n print(look.value)\n stack = stack[1:]\n\n # Print the value of every node, starting with the given node,\n # in an iterative depth first traversal\n def dft_print(self, node):\n stack = [node]\n\n while stack != []:\n \n look = stack[-1]\n print(look.value)\n stack = stack[0:-1]\n if look.right is not None:\n stack.append(look.right)\n \n if look.left is not None:\n stack.append(look.left)\n\n # Use a stack with the root node\n # \n\n # Stretch Goals -------------------------\n # Note: Research may be required\n\n # Print Pre-order recursive DFT\n def pre_order_dft(self, node):\n if node:\n print(node.value),\n \n\n node.pre_order_dft(node.left)\n\n node.pre_order_dft(node.right)\n\n # Print Post-order recursive DFT\n def post_order_dft(self, node):\n if node:\n node.post_order_dft(node.left)\n node.post_order_dft(node.right)\n print(node.value)\n"} {"doc_id": "4154a9d96219e81f022d15839a598609", "text": "#! usr/bin/env python\n# -*- coding:utf-8 -*-\n\n'''\nclass \u540e\u9762\u7d27\u63a5\u7740\u662f\u7c7b\u540d\uff0c\u5373 Student \uff0c\u7c7b\u540d\u901a\u5e38\u662f\u5927\u5199\u5f00\u5934\u7684\u5355\u8bcd\uff0c\n\u7d27\u63a5\u7740\u662f (object) \uff0c\u8868\u793a\u8be5\u7c7b\u662f\u4ece\u54ea\u4e2a\u7c7b\u7ee7 \u627f\u4e0b\u6765\u7684\uff0c\u7ee7\u627f\u7684\u6982\u5ff5\u6211\u4eec\u540e\u9762\u518d\u8bb2\uff0c\n\u901a\u5e38\uff0c\u5982\u679c\u6ca1\u6709\u5408\u9002\u7684\u7ee7\u627f\u7c7b\uff0c\u5c31\u4f7f\u7528 object \u7c7b\uff0c\u8fd9\u662f\u6240\u6709\u7c7b\u6700\u7ec8\u90fd\u4f1a\u7ee7\u627f \u7684\u7c7b\u3002\n'''\n\n'''\n\u6ce8\u610f\u5230 __init__ \u65b9\u6cd5\u7684\u7b2c\u4e00\u4e2a\u53c2\u6570\u6c38\u8fdc\u662f self \uff0c\u8868\u793a\u521b\u5efa\u7684\u5b9e\u4f8b\u672c\u8eab\uff0c\n\u56e0\u6b64\uff0c\u5728 __init__ \u65b9\u6cd5\u5185\u90e8\uff0c\n\u5c31\u53ef\u4ee5\u628a\u5404 \u79cd\u5c5e\u6027\u7ed1\u5b9a\u5230 self \uff0c\u56e0\u4e3a self \u5c31\u6307\u5411\u521b\u5efa\u7684\u5b9e\u4f8b\u672c\u8eab\n'''\n\n'''\n\u548c\u666e\u901a\u7684\u51fd\u6570\u76f8\u6bd4\uff0c\u5728\u7c7b\u4e2d\u5b9a\u4e49\u7684\u51fd\u6570\u53ea\u6709\u4e00\u70b9\u4e0d\u540c\uff0c\u5c31\u662f\u7b2c\u4e00\u4e2a\u53c2\u6570\u6c38\u8fdc\u662f\u5b9e\u4f8b\u53d8\u91cf self \uff0c\u5e76\u4e14\uff0c\u8c03\u7528\u65f6\uff0c\u4e0d\u7528 \u4f20\u9012\u8be5\u53c2\u6570\u3002\n\u9664\u6b64\u4e4b\u5916\uff0c\u7c7b\u7684\u65b9\u6cd5\u548c\u666e\u901a\u51fd\u6570\u6ca1\u6709\u4ec0\u4e48\u533a\u522b\uff0c\n\u6240\u4ee5\uff0c\u4f60\u4ecd\u7136\u53ef\u4ee5\u7528\u9ed8\u8ba4\u53c2\u6570\u3001\u53ef\u53d8\u53c2\u6570\u548c\u5173\u952e\u5b57\u53c2 \u6570\u3002\n'''\n\n'''\n\u548c\u9759\u6001\u8bed\u8a00\u4e0d\u540c\uff0cPython\u5141\u8bb8\u5bf9\u5b9e\u4f8b\u53d8\u91cf\u7ed1\u5b9a\u4efb\u4f55\u6570\u636e\uff0c\n\u4e5f\u5c31\u662f\u8bf4\uff0c\u5bf9\u4e8e\u4e24\u4e2a\u5b9e\u4f8b\u53d8\u91cf\uff0c\u867d\u7136\u5b83\u4eec\u90fd\u662f\u540c\u4e00\u4e2a\u7c7b\u7684 \u4e0d\u540c\u5b9e\u4f8b\uff0c\u4f46\u62e5\u6709\u7684\u53d8\u91cf\u540d\u79f0\u90fd\u53ef\u80fd\u4e0d\u540c(\u5c5e\u6027\u540d\u79f0\u53ef\u80fd\u4f1a\u4e0d\u540c)\n'''\nclass Student(object):\n\tdef __init__(self,name,score):\n\t\tself.name = name \n\t\tself.score = score \n\t# \u7c7b\u7684\u65b9\u6cd5\n\tdef print_score(self): \n\t\tprint '%s: %s' %(self.name, self.score)\n\nzuocaisong = Student('zcs', 27)\nlisa = Student('lisa', 87)\n\nzuocaisong.print_score()\nlisa.print_score()\n\n\n''' \n\u5982\u679c\u8981\u8ba9\u5185\u90e8\u5c5e\u6027\u4e0d\u88ab\u5916\u90e8\u8bbf\u95ee\uff0c\u53ef\u4ee5\u628a\u5c5e\u6027\u7684\u540d\u79f0\u524d\u52a0\u4e0a\u4e24\u4e2a\u4e0b\u5212\u7ebf __ \uff0c\u5728Python\u4e2d\uff0c\u5b9e\u4f8b\u7684\u53d8\u91cf\u540d\u5982\u679c\n\u4ee5 __ \u5f00\u5934\uff0c\u5c31\u53d8\u6210\u4e86\u4e00\u4e2a\u79c1\u6709\u53d8\u91cf(private)\uff0c\u53ea\u6709\u5185\u90e8\u53ef\u4ee5\u8bbf\u95ee\uff0c\u5916\u90e8\u4e0d\u80fd\u8bbf\u95ee\uff0c\u6240\u4ee5\uff0c\u6211\u4eec\u628aStudent\u7c7b\u6539\u4e00 \u6539:\n'''\nclass Person(object):\n\tdef __init__(self, sex):\n\t\tself.__sex = sex\n\n\tdef print_PerInfo(self):\n\t\tprint self.__sex\n\nboy = Person(\"Man\")\nboy.print_PerInfo()\n\n# print boy.__sex ,\u4f1a\u62a5\u9519\uff1a\u786e\u4fdd\u4e86\u5916\u90e8\u4ee3\u7801\u4e0d\u80fd\u968f\u610f\u4fee\u6539\u5bf9\u8c61\u5185\u90e8\u7684\u72b6\u6001\uff0c\u8fd9\u6837\u901a\u8fc7\u8bbf\u95ee\u9650\u5236\u7684\u4fdd\u62a4\uff0c\u4ee3\u7801\u66f4\u52a0\u5065\u58ee\u3002\n\n# \u7ed9\u4e00\u4e2aget\u65b9\u6cd5\uff0c\u8ba9\u4ed6\u53bb\u8bbf\u95ee\n\nclass Car(object):\n\tdef __init__(self, color):\n\t\tself.__color = color\n\n\tdef get_clolor(self):\n\t\treturn self.__color\n\nbus = Car(\"white\")\nprint bus.get_clolor()\n\n\n# \u5982\u679c\u53c8\u8981\u5141\u8bb8\u5916\u90e8\u4ee3\u7801\u4fee\u6539score\u600e\u4e48\u529e?\u53ef\u4ee5\u7ed9Student\u7c7b\u589e\u52a0 set_score \u65b9\u6cd5:\n\nclass Car(object):\n\tdef __init__(self, color):\n\t\tself.__color = color\n\n\tdef set_color(self,color):\n\t\tself.__color = color\n\n\tdef get_clolor(self):\n\t\treturn self.__color\n\nbus = Car(\"white\")\nprint bus.get_clolor()\n\nbus.set_color(\"red\")\nprint bus.get_clolor()\n\n\n'''\n\u53cc\u4e0b\u5212\u7ebf\u5f00\u5934\u7684\u5b9e\u4f8b\u53d8\u91cf\u662f\u4e0d\u662f\u4e00\u5b9a\u4e0d\u80fd\u4ece\u5916\u90e8\u8bbf\u95ee\u5462?\u5176\u5b9e\u4e5f\u4e0d\u662f\u3002\u4e0d\u80fd\u76f4\u63a5\u8bbf\u95ee __name \u662f\u56e0\u4e3aPython\u89e3\u91ca\u5668\u5bf9 \u5916\u628a __name \u53d8\u91cf\u6539\u6210\u4e86 _Student__name \uff0c\u6240\u4ee5\uff0c\u4ecd\u7136\u53ef\u4ee5\u901a\u8fc7 _Student__name \u6765\u8bbf\u95ee __name \u53d8\u91cf:\n \n\u5916\u628a __name \u53d8\u91cf\u6539\u6210\u4e86 _Student__name \uff0c\u6240\u4ee5\uff0c\u4ecd\u7136\u53ef\u4ee5\u901a\u8fc7 _Student__name \u6765\u8bbf\u95ee __name \u53d8\u91cf:\n\n\u4f46\u662f\u5f3a\u70c8\u5efa\u8bae\u4f60\u4e0d\u8981\u8fd9\u4e48\u5e72\uff0c\u56e0\u4e3a\u4e0d\u540c\u7248\u672c\u7684Python\u89e3\u91ca\u5668\u53ef\u80fd\u4f1a\u628a __name \u6539\u6210\u4e0d\u540c\u7684\u53d8\u91cf\u540d\u3002\n\u603b\u7684\u6765\u8bf4\u5c31\u662f\uff0cPython\u672c\u8eab\u6ca1\u6709\u4efb\u4f55\u673a\u5236\u963b\u6b62\u4f60\u5e72\u574f\u4e8b\uff0c\u4e00\u5207\u5168\u9760\u81ea\u89c9\u3002\n'''\n\n# \u7ee7\u627f\n'''\n\u7ee7\u627f\u6709\u4ec0\u4e48\u597d\u5904?\u6700\u5927\u7684\u597d\u5904\u662f\u5b50\u7c7b\u83b7\u5f97\u4e86\u7236\u7c7b\u7684\u5168\u90e8\u529f\u80fd\u3002\u7531\u4e8eAnimial\u5b9e\u73b0\u4e86 run() \u65b9\u6cd5\uff0c\u56e0\u6b64\uff0cDog\u548cCat\u4f5c\u4e3a\n\u5b83\u7684\u5b50\u7c7b\uff0c\u4ec0\u4e48\u4e8b\u4e5f\u6ca1\u5e72\uff0c\u5c31\u81ea\u52a8\u62e5\u6709\u4e86 run() \u65b9\u6cd5:\n\n\u5f53\u5b50\u7c7b\u548c\u7236\u7c7b\u90fd\u5b58\u5728\u76f8\u540c\u7684 run() \u65b9\u6cd5\u65f6\uff0c\u6211\u4eec\u8bf4\uff0c\u5b50\u7c7b\u7684 run() \u8986\u76d6\u4e86\u7236\u7c7b\u7684 run() \uff0c\n\u5728\u4ee3\u7801\u8fd0\u884c\u7684\u65f6\u5019\uff0c\u603b\u662f \u4f1a\u8c03\u7528\u5b50\u7c7b\u7684 run() \u3002\u8fd9\u6837\uff0c\u6211\u4eec\u5c31\u83b7\u5f97\u4e86\u7ee7\u627f\u7684\u53e6\u4e00\u4e2a\u597d\u5904:\u591a\u6001\u3002\n'''\n# \u8bb2\u5230\u591a\u6001\u65f6\uff0c\u5148\u4ecb\u7ecd\u4e00\u4e0b\u7c7b\u578b\u7684\u5224\u65ad\nprint isinstance(bus, Car) # bus \u662fcar\u7c7b\u578b\n\n'''\n\u6240\u4ee5\uff0c\u5728\u7ee7\u627f\u5173\u7cfb\u4e2d\uff0c\u5982\u679c\u4e00\u4e2a\u5b9e\u4f8b\u7684\u6570\u636e\u7c7b\u578b\u662f\u67d0\u4e2a\u5b50\u7c7b\uff0c\n\u90a3\u5b83\u7684\u6570\u636e\u7c7b\u578b\u4e5f\u53ef\u4ee5\u88ab\u770b\u505a\u662f\u7236\u7c7b\u3002\u4f46\u662f\uff0c\u53cd\u8fc7\u6765\n\u5c31\u4e0d\u884c:\n\u5373\uff1a a = A(\"xx\") \uff0ca\u662fA\u8fd9\u4e2a\u7c7b\u751f\u6210\u7684\u5bf9\u8c61,A\u7ee7\u627f\u4e8eB\uff0c\u5219a\u662fA\u7c7b\u578b\uff0c\u540c\u65f6a\u4e5f\u662fB\u7c7b\u578b\n'''\n\n\n#\u83b7\u53d6\u5bf9\u8c61\u4fe1\u606f\n# \u5f53\u6211\u4eec\u62ff\u5230\u4e00\u4e2a\u5bf9\u8c61\u7684\u5f15\u7528\u65f6\uff0c\u5982\u4f55\u77e5\u9053\u8fd9\u4e2a\u5bf9\u8c61\u662f\u4ec0\u4e48\u7c7b\u578b\u3001\u6709\u54ea\u4e9b\u65b9\u6cd5\u5462?\n\n#\u57fa\u672c\u7c7b\u578b\u90fd\u53ef\u4ee5\u7528 type() \u5224\u65ad:\nprint type(123)\n\n#:\u5982\u679c\u4e00\u4e2a\u53d8\u91cf\u6307\u5411\u51fd\u6570\u6216\u8005\u7c7b\uff0c\u4e5f\u53ef\u4ee5\u7528 type() \u5224\u65ad:\n\nprint type(abs)\nprint type(bus)\n\n'''\n\u4f46\u662f type() \u51fd\u6570\u8fd4\u56de\u7684\u662f\u4ec0\u4e48\u7c7b\u578b\u5462?\u5b83\u8fd4\u56detype\u7c7b\u578b\u3002\n\u5982\u679c\u6211\u4eec\u8981\u5728 if \u8bed\u53e5\u4e2d\u5224\u65ad\uff0c\u5c31\u9700\u8981\u6bd4\u8f83\u4e24\u4e2a\u53d8\u91cf\u7684typ e\u7c7b\u578b\u662f\u5426\u76f8\u540c:\n'''\nprint type(123) == type(456)\n\n#\u4f46\u662f\u8fd9\u79cd\u5199\u6cd5\u592a\u9ebb\u70e6\uff0cPython\u628a\u6bcf\u79cdtype\u7c7b\u578b\u90fd\u5b9a\u4e49\u597d\u4e86\u5e38\u91cf\uff0c\u653e\u5728 types \u6a21\u5757\u91cc\uff0c\u4f7f\u7528\u4e4b\u524d\uff0c\u9700\u8981\u5148\u5bfc\u5165:\nimport types\nprint types.StringType == type(\"zcs\")\ntype(u'abc')==types.UnicodeType\ntype([]) == types.ListType\ntype(str)==types.TypeType #\u6700\u540e\u6ce8\u610f\u5230\u6709\u4e00\u79cd\u7c7b\u578b\u5c31\u53eb TypeType \uff0c\u6240\u6709\u7c7b\u578b\u672c\u8eab\u7684\u7c7b\u578b\u5c31\u662f TypeType \n\n'''\n\u5bf9\u4e8eclass\u7684\u7ee7\u627f\u5173\u7cfb\u6765\u8bf4\uff0c\u4f7f\u7528type()\u5c31\u5f88\u4e0d\u65b9\u4fbf\u3002\u6211\u4eec\u8981\u5224\u65adclass\u7684\u7c7b\u578b\uff0c\u53ef\u4ee5\u4f7f\u7528 isinstance() \u51fd\u6570\u3002\n\u5e76\u4e14\u8fd8\u53ef\u4ee5\u5224\u65ad\u4e00\u4e2a\u53d8\u91cf\u662f\u5426\u662f\u67d0\u4e9b\u7c7b\u578b\u4e2d\u7684\u4e00\u79cd\uff0c\u6bd4\u5982\u4e0b\u9762\u7684\u4ee3\u7801\u5c31\u53ef\u4ee5\u5224\u65ad\u662f\u5426\u662fstr\u6216\u8005unicode:\n'''\nprint\"-------\"\nprint isinstance(123,(str,unicode,int))\n\n# \u4f7f\u7528dir()\n\n'''\n\u5982\u679c\u8981\u83b7\u5f97\u4e00\u4e2a\u5bf9\u8c61\u7684\u6240\u6709\u5c5e\u6027\u548c\u65b9\u6cd5\uff0c\u53ef\u4ee5\u4f7f\u7528 dir() \u51fd\u6570\uff0c\u5b83\u8fd4\u56de\u4e00\u4e2a\u5305\u542b\u5b57\u7b26\u4e32\u7684list\uff0c\u6bd4\u5982\uff0c\u83b7\u5f97\u4e00\u4e2astr\u5bf9\n\u8c61\u7684\u6240\u6709\u5c5e\u6027\u548c\u65b9\u6cd5:\n\n\u7c7b\u4f3c __xxx__ \u7684\u5c5e\u6027\u548c\u65b9\u6cd5\u5728Python\u4e2d\u90fd\u662f\u6709\u7279\u6b8a\u7528\u9014\u7684\uff0c\u6bd4\u5982 __len__ \u65b9\u6cd5\u8fd4\u56de\u957f\u5ea6\u3002\n\u5728Python\u4e2d\uff0c\u5982\u679c\u4f60\u8c03 \u7528 len() \u51fd\u6570\u8bd5\u56fe\u83b7\u53d6\u4e00\u4e2a\u5bf9\u8c61\u7684\u957f\u5ea6\uff0c\u5b9e\u9645\u4e0a\uff0c\u5728 len() \u51fd\u6570\u5185\u90e8\uff0c\u5b83\u81ea\u52a8\u53bb\u8c03\u7528\u8be5\u5bf9\u8c61\u7684 __len__() \u65b9\u6cd5\uff0c\n\u6240 \u4ee5\uff0c\u4e0b\u9762\u7684\u4ee3\u7801\u662f\u7b49\u4ef7\u7684\n'''\n\nprint len(\"abc\") \nprint \"abc\".__len__()\n\n#\u6211\u4eec\u81ea\u5df1\u5199\u7684\u7c7b\uff0c\u5982\u679c\u4e5f\u60f3\u7528 len(myObj) \u7684\u8bdd\uff0c\u5c31\u81ea\u5df1\u5199\u4e00\u4e2a __len__() \u65b9\u6cd5:\n\nclass MyObject(object):\n\t\"\"\"docstring for myObject\"\"\"\n\tdef __init__(self, arg):\n\t\tself.arg = arg\n\t\t\n\tdef __len__(self):\n\t\treturn 100\n\nobj = MyObject(13)\nprint len(obj)\n\n'''\n\u914d\u5408 getattr() \u3001 setattr() \u4ee5\u53ca hasattr() \uff0c\u6211\u4eec\u53ef\u4ee5\u76f4\u63a5\u64cd\u4f5c\u4e00\u4e2a\u5bf9\u8c61\u7684 \u72b6\u6001:\n'''\n\nclass MyObject1(object):\n\tdef __init__(self):\n\t\tself.x = 9\n\tdef power(self):\n\t\treturn self.x * self.x \n\nobj = MyObject1()\nprint(\"hasattr\")\nprint hasattr(obj, \"x\") #obj\u6709\u5c5e\u6027'x'\u5417?\n\nprint hasattr(obj, \"y\") #obj\u6709\u5c5e\u6027'y'\u5417?\n\nsetattr(obj, 'y', 19) #\u8bbe\u7f6e\u4e00\u4e2a\u5c5e\u6027'y',\u503c\u4e3a19\nprint hasattr(obj, \"y\") #obj\u6709\u5c5e\u6027'y'\u5417?\n\nprint getattr(obj,\"y\")\n\n'''\n\u6ce8\u610f\uff1a \u5982\u679c\u8bd5\u56fe\u83b7\u53d6\u4e0d\u5b58\u5728\u7684\u5c5e\u6027\uff0c\u4f1a\u629b\u51faAttributeError\u7684\u9519\u8bef:\n\u53ef\u4ee5\u4f20\u5165\u4e00\u4e2adefault\u53c2\u6570\uff0c\u5982\u679c\u5c5e\u6027\u4e0d\u5b58\u5728\uff0c\u5c31\u8fd4\u56de\u9ed8\u8ba4\u503c:\n'''\n\nprint getattr(obj,'z', 404)\n\n# \u4e5f\u53ef\u4ee5\u83b7\u5f97\u5bf9\u8c61\u7684\u65b9\u6cd5:\nprint hasattr(obj, 'power')\n\nfn = getattr(obj,'power')\nprint fn() # \u8c03\u7528fn()\u4e0e\u8c03\u7528obj.power()\u662f\u4e00\u6837\u7684\n\n'''\n\u5c0f\u7ed3: \u53ef\u4ee5\u76f4\u63a5\u8bbf\u95ee\uff08obj.x obj.power()\uff09\uff0c\u5c3d\u91cf\u4e0d\u8981\u7528\u8fd9\u79cd\u65b9\u5f0f\u8bbf\u95ee\u5c5e\u6027\uff0c\u548c\u65b9\u6cd5\u3002\n'''\n\n\n# \u52a8\u6001\u7ed1\u5b9a\u65b9\u6cd5\uff0c\u548c\u5c5e\u6027\n\nclass Student(object):\n\tpass\n\ns = Student()\ns.name = 'Michael' # \u52a8\u6001\u7ed9\u5b9e\u4f8b\u7ed1\u5b9a\u4e00\u4e2a\u5c5e\u6027\nprint s.name\n\n# \u7ed9\u5b9e\u4f8b\u7ed1\u5b9a\u4e00\u4e2a\u65b9\u6cd5\ndef set_age(self, age):\n\tself.age = age\n\nfrom types import MethodType\ns.set_age = MethodType(set_age, s, Student) # \u7ed9\u5b9e\u4f8b\u7ed1\u5b9a\u4e00\u4e2a\u65b9\u6cd5\n\ns.set_age(25) # \u8c03\u7528\u5b9e\u4f8b\u65b9\u6cd5\nprint s.age # \u6d4b\u8bd5\u7ed3\u679c\n\n'''\n\u4f46\u662f\uff0c\u7ed9\u4e00\u4e2a\u5b9e\u4f8b\u7ed1\u5b9a\u7684\u65b9\u6cd5\uff0c\u5bf9\u53e6\u4e00\u4e2a\u5b9e\u4f8b\u662f\u4e0d\u8d77\u4f5c\u7528\u7684:\u53ea\u4f5c\u7528\u5f53\u524d\u5b9e\u4f8bs\u3002\n\n\u4e3a\u4e86\u7ed9\u6240\u6709\u5b9e\u4f8b\u90fd\u7ed1\u5b9a\u65b9\u6cd5\uff0c\u53ef\u4ee5\u7ed9class\u7ed1\u5b9a\u65b9\u6cd5:\n\u7ed9class\u7ed1\u5b9a\u65b9\u6cd5\u540e\uff0c\u6240\u6709\u5b9e\u4f8b\u5747\u53ef\u8c03\u7528:\n\u52a8\u6001\u7ed1\u5b9a\u5141\u8bb8\u6211\u4eec\u5728\u7a0b\u5e8f\u8fd0\u884c\u7684\u8fc7\u7a0b\u4e2d\u52a8\u6001\u7ed9class \u52a0\u4e0a\u529f\u80fd\uff0c\u8fd9\u5728\u9759\u6001\u8bed\u8a00\u4e2d\u5f88\u96be\u5b9e\u73b0\u3002\n'''\n\ndef set_Score(self, score):\n\tself.score = score\n\nStudent.set_Score = MethodType(set_Score, None, Student)\n\ns.set_Score(100)\nprint s.score\n\n\n'''\n\u53ea\u5141\u8bb8\u5bf9Student\u5b9e\u4f8b\u6dfb\u52a0 name \u548c age \u5c5e\u6027\u3002\n\u4e3a\u4e86\u8fbe\u5230\u9650\u5236\u7684\u76ee\u7684\uff0cPython\u5141\u8bb8\u5728\u5b9a\u4e49class\u7684\u65f6\u5019\uff0c\u5b9a\u4e49\u4e00\u4e2a\u7279\u6b8a\u7684 __slots__ \u53d8\u91cf\uff0c\u6765\u9650\u5236\u8be5class\u80fd\u6dfb\u52a0\u7684\u5c5e \u6027:\n\n\u4f7f\u7528 __slots__ \u8981\u6ce8\u610f\uff0c __slots__ \u5b9a\u4e49\u7684\u5c5e\u6027\u4ec5\u5bf9\u5f53\u524d\u7c7b\u8d77\u4f5c\u7528\uff0c\u5bf9\u7ee7\u627f\u7684\u5b50\u7c7b\u662f\u4e0d\u8d77\u4f5c\u7528\u7684:\n\u9664\u975e\u5728\u5b50\u7c7b\u4e2d\u4e5f\u5b9a\u4e49 __slots__ \uff0c\u8fd9\u6837\uff0c\u5b50\u7c7b\u5141\u8bb8\u5b9a\u4e49\u7684\u5c5e\u6027\u5c31\u662f\u81ea\u8eab\u7684 __slots__ \u52a0\u4e0a\u7236\u7c7b\u7684 __slots__ \u3002\n'''\nclass Student(object):\n\t__slots__ = ('name', 'age') # \u7528tuple\u5b9a\u4e49\u53ea\u80fd\u5141\u8bb8\u7ed1\u5b9a\u7684\u5c5e\u6027\u540d\u79f0\n\ns = Student()\n#s.score = 90\n# print s.score : error: Student' object has no attribute 'score'\n\nclass GraduateStudent(Student):\n\t__slots__ = (\"score\")\n\ng = GraduateStudent()\ng.name = \"xiaoming\"\nprint g.name\n\n\n# @property\nclass Student(object):\n\n \tdef get_score(self):\n \t\treturn self._score\n # \u73b0\u5728\uff0c\u5bf9\u4efb\u610f\u7684Student\u5b9e\u4f8b\u8fdb\u884c\u64cd\u4f5c\uff0c\u5c31\u4e0d\u80fd\u968f\u5fc3\u6240\u6b32\u5730\u8bbe\u7f6escore\u4e86:\n \tdef set_score(self, value):\n \t\tif not isinstance(value, int):\n \t\t\traise ValueError('score must be an integer!')\n \t\telif value <0 or value> 100:\n \t\t\traise ValueError('score must between 0 ~ 100!')\n \t\telse:\n \t\t\tself.score = value\n\n#\u6b64\u65f6\u64cd\u4f5c\u8d4b\u503c\u4e3a\uff1a\ns = Student()\ns.set_score(60)\n\n'''\n# Python\u5185\u7f6e \u7684 @property \u88c5\u9970\u5668\u5c31\u662f\u8d1f\u8d23\u628a\u4e00\u4e2a\u65b9\u6cd5\u53d8\u6210\u5c5e\u6027\u8c03\u7528\u7684:\n@property \u7684\u5b9e\u73b0\u6bd4\u8f83\u590d\u6742\uff0c\u6211\u4eec\u5148\u8003\u5bdf\u5982\u4f55\u4f7f\u7528\u3002\u628a\u4e00\u4e2agetter\u65b9\u6cd5\u53d8\u6210\u5c5e\u6027\uff0c\u53ea\u9700\u8981\u52a0\u4e0a @property \u5c31\u53ef\u4ee5 \u4e86\uff0c\n\u6b64\u65f6\uff0c @property \u672c\u8eab\u53c8\u521b\u5efa\u4e86\u53e6\u4e00\u4e2a\u88c5\u9970\u5668 @score.setter \uff0c\u8d1f\u8d23\u628a\u4e00\u4e2asetter\u65b9\u6cd5\u53d8\u6210\u5c5e\u6027\u8d4b\u503c\uff0c\n\u4e8e\u662f\uff0c\u6211 \u4eec\u5c31\u62e5\u6709\u4e00\u4e2a\u53ef\u63a7\u7684\u5c5e\u6027\u64cd\u4f5c:\n\n\u6ce8\u610f\u5230\u8fd9\u4e2a\u795e\u5947\u7684 @property \uff0c\u6211\u4eec\u5728\u5bf9\u5b9e\u4f8b\u5c5e\u6027\u64cd\u4f5c\u7684\u65f6\u5019\uff0c\u5c31\u77e5\u9053\u8be5\u5c5e\u6027\u5f88\u53ef\u80fd\u4e0d\u662f\u76f4\u63a5\u66b4\u9732\u7684\uff0c\u800c\u662f\u901a\u8fc7gett er\u548csetter\u65b9\u6cd5\u6765\u5b9e\u73b0\u7684\u3002\n#\u8fd8\u53ef\u4ee5\u5b9a\u4e49\u53ea\u8bfb\u5c5e\u6027\uff0c\u53ea\u5b9a\u4e49getter\u65b9\u6cd5\uff0c\u4e0d\u5b9a\u4e49setter\u65b9\u6cd5\u5c31\u662f\u4e00\u4e2a\u53ea\u8bfb\u5c5e\u6027:\n\n'''\n\nclass Student(object):\n\n\t@property \n\tdef score(self):\n\t\treturn self._score \n\n\n\t@score.setter\n\tdef score(self,value):\n\t\tif not isinstance(value, int):\n\t\t\traise ValueError('score must be an integer')\n\t\telif value < 0 or value > 100:\n\t\t\traise ValueError('score must between 0 ~100!')\n\t\telse:\n\t\t\tself._score = value\n\ns = Student()\ns.score = 99\nprint s.score\n\n'''\n\u8fd8\u53ef\u4ee5\u5b9a\u4e49\u53ea\u8bfb\u5c5e\u6027\uff0c\u53ea\u5b9a\u4e49getter\u65b9\u6cd5\uff0c\u4e0d\u5b9a\u4e49setter\u65b9\u6cd5\u5c31\u662f\u4e00\u4e2a\u53ea\u8bfb\u5c5e\u6027:\n'''\nclass Student(object):\n\t@property \n\tdef birth(self):\n\t\treturn self._birth\n\t@birth.setter\n\tdef birth(self,value):\n\t\tself._birth = value\n\n\t@property\n\tdef age(self):\n\t\treturn 2014 - self._birth\n#\u800c age \u5c31\u662f\u4e00\u4e2a\u53ea\u8bfb\u5c5e\u6027\uff0c\u56e0\u4e3a age \u53ef\u4ee5\u6839\u636e birth \u548c\u5f53\u524d\u65f6\u95f4\u8ba1\u7b97\u51fa\u6765\u3002\n\n\n# \u91cd\u65b0\u5b9a\u4e49\u6253\u5370\u5bf9\u8c61,\u53ea\u9700\u8981\u5b9a\u4e49\u597d __str__() \u65b9\u6cd5\uff0c\u8fd4\u56de\u4e00\u4e2a\u597d\u770b\u7684\u5b57\u7b26\u4e32\u5c31\u53ef\u4ee5\u4e86:\n\n'''\n\u56e0\u4e3a\u76f4\u63a5\u663e\u793a\u53d8\u91cfs \u8c03\u7528\u7684\u4e0d\u662f __str__() \uff0c\u800c\u662f __repr__() \uff0c\n\u4e24\u8005\u7684\u533a\u522b\u662f __str__() \u8fd4\u56de\u7528\u6237\u770b\u5230\u7684\u5b57\u7b26 \u4e32\uff0c\n\u800c __repr__() \u8fd4\u56de\u7a0b\u5e8f\u5f00\u53d1\u8005\u770b\u5230\u7684\u5b57\u7b26\u4e32\uff0c\n\u4e5f\u5c31\u662f\u8bf4\uff0c __repr__() \u662f\u4e3a\u8c03\u8bd5\u670d\u52a1\u7684\u3002\n\n\u89e3\u51b3\u529e\u6cd5\u662f\u518d\u5b9a\u4e49\u4e00\u4e2a __repr__() \u3002\n\u4f46\u662f\u901a\u5e38 __str__() \u548c __repr__() \u4ee3\u7801\u90fd\u662f\u4e00\u6837\u7684\uff0c\n\u6240\u4ee5\uff0c\u6709\u4e2a\u5077\u61d2\u7684\u5199 \u6cd5: __repr__ = __str__\n'''\nclass Student(object):\n\tdef __init__(self, name):\n\t\tself.name = name\n\tdef __str__(self):\n\t\treturn 'Student object (name: %s)' % self.name\n\t__repr__ = __str__\nStudent('Michael')\nprint Student('Michael')\n\n\n\nprint \"------------ __iter__ -------------\"\n'''\n\u5982\u679c\u4e00\u4e2a\u7c7b\u60f3\u88ab\u7528\u4e8e for ... in \u5faa\u73af\uff0c\u7c7b\u4f3clist\u6216tuple\u90a3\u6837\uff0c\u5c31\u5fc5\u987b\u5b9e\u73b0\u4e00\u4e2a __iter__() \u65b9\u6cd5\uff0c\u8be5\u65b9\u6cd5\u8fd4\u56de\u4e00\u4e2a\u8fed \u4ee3\u5bf9\u8c61\uff0c\n\u7136\u540e\uff0cPython\u7684for\u5faa\u73af\u5c31\u4f1a\u4e0d\u65ad\u8c03\u7528\u8be5\u8fed\u4ee3\u5bf9\u8c61\u7684 next() \u65b9\u6cd5\u62ff\u5230\u5faa\u73af\u7684\u4e0b\u4e00\u4e2a\u503c\uff0c\u76f4\u5230\u9047\u5230StopIterati on\u9519\u8bef\u65f6\u9000\u51fa\u5faa\u73af\n'''\nclass Fib(object):\n\tdef __init__(self):\n\t\tself.a, self.b = 0, 1 # \u521d\u59cb\u5316\u4e24\u4e2a\u8ba1\u6570\u5668a\uff0cb\n\n\tdef __iter__(self):\n\t\treturn self #\u5b9e\u529b\u672c\u8eab\u5c31\u662f\u8fed\u4ee3\u5bf9\u8c61\uff0c\u5bf9\u8fd4\u56de\u81ea\u5df1\n\n\tdef next(self):\n\t\tself.a, self.b = self.b, self.a + self.b # \u8ba1\u7b97\u4e0b\u4e00\u4e2a\u503c\n\t\tif self.a > 1000: #\u9000\u51fa\u5faa\u73af\u6761\u4ef6\n\t\t\traise StopIteration();\n\t\treturn self.a\n\n\nfor n in Fib():\n\tprint n\n\nprint \"------------ __getitem__ -------------\"\n\n#Fib\u5b9e\u4f8b\u867d\u7136\u80fd\u4f5c\u7528\u4e8efor\u5faa\u73af\uff0c\u770b\u8d77\u6765\u548clist\u6709\u70b9\u50cf\uff0c\u4f46\u662f\uff0c\u628a\u5b83\u5f53\u6210list\u6765\u4f7f\u7528\u8fd8\u662f\u4e0d\u884c\uff0c\u6bd4\u5982\uff0c\u53d6\u7b2c5\u4e2a\u5143\u7d20:\n#\u8981\u8868\u73b0\u5f97\u50cflist\u90a3\u6837\u6309\u7167\u4e0b\u6807\u53d6\u51fa\u5143\u7d20\uff0c\u9700\u8981\u5b9e\u73b0 __getitem__() \u65b9\u6cd5:\nclass Fib(object):\n\tdef __getitem__(self, n):\n\t\ta, b = 1, 1\n\t\tfor x in range(n):\n\t\t\ta, b = b, a + b\n\t\treturn a\nf = Fib()\nprint f[5]\n\n\n'''\n\u6b63\u5e38\u60c5\u51b5\u4e0b\uff0c\u5f53\u6211\u4eec\u8c03\u7528\u7c7b\u7684\u65b9\u6cd5\u6216\u5c5e\u6027\u65f6\uff0c\u5982\u679c\u4e0d\u5b58\u5728\uff0c\u5c31\u4f1a\u62a5\u9519\u3002\u6bd4\u5982\u5b9a\u4e49 Student \u7c7b:\n \n'''\nprint \" __getattr__ \"\n\nclass Student(object):\n\tdef __init__(self):\n\t\tself.name = 'Michael'\ns = Student()\nprint s.name\n\n'''\nPython\u8fd8\u6709\u53e6\u4e00\u4e2a\u673a\u5236\uff0c\u90a3\u5c31\u662f\u5199\u4e00\u4e2a __getattr__() \u65b9\n\u6cd5\uff0c\u52a8\u6001\u8fd4\u56de\u4e00\u4e2a\u5c5e\u6027\u3002\u4fee\u6539\u5982\u4e0b:\n'''\nclass Student100(object):\n\tdef __init__(self):\n\t\tself.name = 'Michael'\n\n\tdef __getattr__(self, attr):\n\t\tif attr == 'score':\n\t\t\treturn 99\n'''\n\u5f53\u8c03\u7528\u4e0d\u5b58\u5728\u7684\u5c5e\u6027\u65f6\uff0c\n\u6bd4\u5982 score \uff0cPython\u89e3\u91ca\u5668\u4f1a\u8bd5\u56fe\u8c03\u7528 __getattr__(self, 'score') \u6765\u5c1d\u8bd5\u83b7\u5f97\u5c5e\u6027\uff0c\n\u8fd9 \u6837\uff0c\u6211\u4eec\u5c31\u6709\u673a\u4f1a\u8fd4\u56de score \u7684\u503c:\n\n\u6ce8\u610f\uff1a\n\u53ea\u6709\u5728\u6ca1\u6709\u627e\u5230\u5c5e\u6027\u7684\u60c5\u51b5\u4e0b\uff0c\u624d\u8c03\u7528 __getattr__ \uff0c\u5df2\u6709\u7684\u5c5e\u6027\uff0c\u6bd4\u5982 name \uff0c\u4e0d\u4f1a\u5728 __getattr__ \u4e2d\u67e5 \u627e\u3002\n\u6b64\u5916\uff0c\u6ce8\u610f\u5230\u4efb\u610f\u8c03\u7528\u5982 s.abc \u90fd\u4f1a\u8fd4\u56de None \uff0c\u8fd9\u662f\u56e0\u4e3a\u6211\u4eec\u5b9a\u4e49\u7684 __getattr__ \u9ed8\u8ba4\u8fd4\u56de\u5c31\u662f None \u3002\n\u8981\u8ba9class \u53ea\u54cd\u5e94\u7279\u5b9a\u7684\u51e0\u4e2a\u5c5e\u6027\uff0c\u6211\u4eec\u5c31\u8981\u6309\u7167\u7ea6\u5b9a\uff0c\u629b\u51fa AttributeError \u7684\u9519\u8bef\n'''\n\ns = Student100()\nprint s.name\nprint s.score\n\nprint s.shdfs\n\n\n\n\nprint \"----------------- __call__---------------\"\n'''\n\u4e00\u4e2a\u5bf9\u8c61\u5b9e\u4f8b\u53ef\u4ee5\u6709\u81ea\u5df1\u7684\u5c5e\u6027\u548c\u65b9\u6cd5\uff0c\u5f53\u6211\u4eec\u8c03\u7528\u5b9e\u4f8b\u65b9\u6cd5\u65f6\uff0c\u6211\u4eec\u7528 instance.method() \u6765\u8c03\u7528\u3002\u80fd\u4e0d\u80fd\u76f4\u63a5\u5728 \u5b9e\u4f8b\u672c\u8eab\u4e0a\u8c03\u7528\u5462?\u7c7b\u4f3c instance() ?\u5728Python\u4e2d\uff0c\u7b54\u6848\u662f\u80af\u5b9a\u7684\u3002\n\u4efb\u4f55\u7c7b\uff0c\u53ea\u9700\u8981\u5b9a\u4e49\u4e00\u4e2a __call__() \u65b9\u6cd5\uff0c\u5c31\u53ef\u4ee5\u76f4\u63a5\u5bf9\u5b9e\u4f8b\u8fdb\u884c\u8c03\u7528\u3002\u8bf7\u770b\u793a\u4f8b:\n'''\n\n\nclass StudentCall(object):\n\tdef __init__(self,name):\n\t\tself.name = name\n\n\tdef __call__(self):\n\t\tprint(\"my name is %s\" % self.name)\n\n\ns = StudentCall(\"jeck\")\nprint s()\n\n'''\n\u600e\u4e48\u5224\u65ad\u4e00\u4e2a\u53d8\u91cf\u662f\u5bf9\u8c61\u8fd8\u662f\u51fd\u6570\u5462\n\n\n\u5176\u5b9e\uff0c\u66f4\u591a\u7684\u65f6\u5019\uff0c\u6211\u4eec\u9700\u8981\u5224\u65ad\u4e00\u4e2a\u5bf9\u8c61\u662f\u5426\u80fd\u88ab\u8c03\u7528\uff0c\u80fd\u88ab\u8c03\u7528 \u7684\u5bf9\u8c61\u5c31\u662f\u4e00\u4e2a Callable \u5bf9\u8c61\uff0c\u6bd4\u5982\u51fd\u6570\u548c\u6211\u4eec\u4e0a\u9762\u5b9a\u4e49\u7684\u5e26\u6709 __call()__ \u7684\u7c7b\u5b9e\u4f8b:\n\n\u901a\u8fc7 callable() \u51fd\u6570\uff0c\u6211\u4eec\u5c31\u53ef\u4ee5\u5224\u65ad\u4e00\u4e2a\u5bf9\u8c61\u662f\u5426\u662f\u201c\u53ef\u8c03\u7528\u201d\u5bf9\u8c61\u3002\n'''\n\nprint callable(s) # true\n\nprint callable('str') #false\n"} {"doc_id": "415c75e4268f30f31e75e76b98394089", "text": "import getpass\n__author__ = 'sekely'\n\n\n'''\n1)\nlook back on exercise 1, on the user and password input.\nwrite 2 methods:\nthe first method should accept user and password\nthe second one should check that the password is not \"simple\" password, and print warning.\nsimple password is \"123456\"\n\n2) medium\nwrite a short code that prints all the even numbers up to 20\n\n3) hard\nwithout running it, what does this code do?\n\nfor x in range(10):\n for y in range(10):\n print(x * y, end=' ')\n print()\n\nHINTS:\nprint(x * y, end=' ') won't print in a new line\nprint() will just create a new line\n'''\n\n# 1)\nusername = input('please enter user name: ')\npassword = getpass.getpass('enter password: ')\nif password == '123456':\n print(\"please don't use simple passwords\")\n\n# 2)\nfor x in range (20):\n if x % 2 == 0:\n print(x)\n\n# 3) this will print the multiplication board\n"} {"doc_id": "416fdfe69ae0b8c7b7c383aec0c261a0", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Jan 24 18:24:34 2019\n\n@author: Luis Cobian \nPractica: 007 Ciclos FOR\n\"\"\"\nlista = [3,56,2,23,1,6,43,2,31,23]\n#iterando una lista de valores \nfor valor in lista: \n print(valor)\n\nprint(\"-----------------------\") \nnueva_lista = range(5,20,3)\nfor valor in nueva_lista:\n print(valor)\n\nprint(nueva_lista)\n\n#uso de enumerate \nfor indice, valor in enumerate(nueva_lista):\n print(valor, \" tiene el indice \", indice)\n \nprint(\"Numero de elementos \", len(lista))\n#Recorrer un diccionario\ndiccionario = {'nombre':'Luis Cobian', 1:'prueba'}\nfor llave,valor in diccionario.items():\n print(llave, \" => \", valor)\n\n#Otra forma \nfor llave,valor in diccionario.items():\n print(f\"{llave} => {valor}\")\n \nfor i in range(10):\n print(i)\n \n#python comprenhesion \nlista = [valor for valor in range(101)]\nprint(lista)"} {"doc_id": "418bbb9e13bc27bd9c6064f88e402083", "text": "'''\nConstruct Tree Using Inorder and PostOrder\n\nFor a given postorder and inorder traversal of a Binary Tree of type integer stored in an array/list, create the binary tree using the given two arrays/lists. You just need to construct the tree and return the root.\n\nNote:\nAssume that the Binary Tree contains only unique elements. \n\nInput Format:\nThe first line of input contains an integer N denoting the size of the list/array. It can also be said that N is the total number of nodes the binary tree would have.\n\nThe second line of input contains N integers, all separated by a single space. It represents the Postorder-traversal of the binary tree.\n\nThe third line of input contains N integers, all separated by a single space. It represents the inorder-traversal of the binary tree.\n\nOutput Format:\nThe given input tree will be printed in a level order fashion where each level will be printed on a new line. \nElements on every level will be printed in a linear fashion. A single space will separate them.\n\nConstraints:\n1 <= N <= 10^4\nWhere N is the total number of nodes in the binary tree.\n\nTime Limit: 1 sec\n\nSample Input 1:\n7\n4 5 2 6 7 3 1 \n4 2 5 1 6 3 7 \n\nSample Output 1:\n1 \n2 3 \n4 5 6 7 \n\nSample Input 2:\n6\n2 9 3 6 10 5 \n2 6 3 9 5 10 \n\nSample Output 2:\n5 \n6 10 \n2 3 \n9 \n'''\n\nfrom sys import stdin, setrecursionlimit\nimport queue\n\nsetrecursionlimit(10 ** 6)\n\n\n#Following is the structure used to represent the Binary Tree Node\nclass BinaryTreeNode:\n def __init__(self, data):\n self.data = data\n self.left = None\n self.right = None\n\n\n\ndef buildTreeFromPostIn(post, inorder) :\n\t#Your code goes here\n if len(post) == 0:\n return None\n rootData = post[-1]\n root = BinaryTreeNode(rootData)\n \n rootIndexInInorder = -1\n for i in range(0, len(inorder)):\n if inorder[i] == rootData:\n rootIndexInorder = i\n break\n if rootIndexInorder == -1:\n return None\n \n leftInorder = inorder[0:rootIndexInorder]\n rightInorder = inorder[rootIndexInorder + 1:]\n\n lenLeftSubtree = len(leftInorder)\n\n leftPostorder = post[:lenLeftSubtree]\n rightPostorder = post[lenLeftSubtree:len(post) - 1]\n\n leftChild = buildTreeFromPostIn(leftPostorder, leftInorder)\n rightChild = buildTreeFromPostIn(rightPostorder, rightInorder)\n\n root.left = leftChild\n root.right = rightChild\n return root\n\n\n\n'''-------------------------- Utility Functions --------------------------'''\n\ndef printLevelWise(root):\n if root is None :\n return\n\n pendingNodes = queue.Queue()\n pendingNodes.put(root)\n pendingNodes.put(None)\n\n while not pendingNodes.empty(): \n frontNode = pendingNodes.get()\n \n if frontNode is None :\n print()\n \n if not pendingNodes.empty() :\n pendingNodes.put(None)\n \n else :\n print(frontNode.data, end = \" \")\n \n if frontNode.left is not None :\n pendingNodes.put(frontNode.left)\n \n \n if frontNode.right is not None :\n pendingNodes.put(frontNode.right)\n\n\n \n\n#Taking level-order input using fast I/O method\ndef takeInput():\n n = int(stdin.readline().strip())\n\n if n == 0 :\n return list(), list(), 0\n\n postOrder = list(map(int, stdin.readline().strip().split(\" \")))\n inOrder = list(map(int, stdin.readline().strip().split(\" \")))\n\n return postOrder, inOrder, n\n\n\n# Main\npostOrder, inOrder, n = takeInput()\nroot = buildTreeFromPostIn(postOrder, inOrder)\nprintLevelWise(root)"} {"doc_id": "41983d0ba089fec4610e060300d49a4a", "text": "#--------------Expressions Part 1\n#constants: 1, 2, 3 ...\n#reserved words: cannot be used for functions, variables, classes etc.\n#reserved words examples: break, if, False, True, None, as, except, else ...\n\n#variable: named place in the memory where you can store data\n\n#find a place in the memory, label it \"x\" and put 12.2 in it\nx=12.2\n\n#override the previous value with the label \"x\" with 100\nx=100\n\n#variables are case sensitive: spam, Spam, SPAM are different variables\n\n#mnemonic variables: variables with describing or sensible names\nhours = 35.0\nrate = 12.50\npay = hours * rate\nprint(pay)\n\n#assignment: x=1 does not mean \"equal\" it is just assigning \n# a value i.e. 1 to the label in the memory \n\n\n#--------------Expressions Part 2\n#Sequence of evaluation: \n#1. Paranthesis (Klammern)\n#2. Power (Exponent)\n#3. Multiplication \n#4. Addition\n#5. Left to Right\n\n#function type(variable) gives you the type of a variable\n\n#differnece between floating points and integers: \n# floating points have more range but less precision\n\n#function input() waits for the user input which is called a prompt\n# and returns the user input as a string \n\n\n#--------------Expressions Part 3\n#converting user input example\n\n#convert elevator floors\neu_floor = input(\"Europe floor? \")\nus_floor = int(eu_floor) + 1\nprint(us_floor)"} {"doc_id": "41a47f0a3fde8c158daf908c78d71d1a", "text": "\"\"\"Core module from real_fractions package.\n\nClasses:\n Fractions: Base real_fraction class.\n\"\"\"\n\n\nclass Fractions:\n \"\"\"Base class from real_fractions.\n\n Methods:\n separate_numbers(fraction):\n Separate fraction into numerator and denominator.\n sign_checker(fraction): Check sign of maximum fraction.\n simplify(fraction): Simplify fraction to his minimum expresion.\n add_zero_checker(fraction1, fraction2):\n Check if in an addition of two fractions returns zero.\n sub_zero_checker(fraction1, fraction2):\n Check if in a substraction of two fractions returns zero.\n \"\"\"\n\n @classmethod\n def separate_numbers(cls, fraction):\n \"\"\"Separate fraction into numerator and denominator.\n\n Args:\n fraction (str): Fraction to separate numbers\n\n Returns:\n\n int: Numerator of the fraction\n int: Denominator of the fraction\n \"\"\"\n\n if not isinstance(fraction, str): # Discard invalid argument types\n print(\"The argument isn't a fraction\")\n return None\n\n try:\n numbers = fraction.split(\"/\") # Separate numerator and denominator\n numerator = int(numbers[0])\n denominator = int(numbers[1])\n return numerator, denominator\n\n except ValueError: # Discard invalid string arguments\n print(\"The argument isn't a fraction\")\n\n @classmethod\n def sign_checker(cls, fraction):\n \"\"\"Check sign of maximum fraction.\n\n Args:\n fraction (str): Fraction to check his sign\n\n Returns:\n str: Real fraction sign\n \"\"\"\n\n if not isinstance(fraction, str): # Discard invalid argument types\n print(\"The argument isn't a fraction\")\n return None\n\n try:\n numerator, denominator = cls.separate_numbers(fraction)\n\n if numerator > 0 > denominator: # Check if its negative\n fraction = str(-(numerator)) + \"/\" + str(abs(denominator))\n\n elif numerator < 0 and denominator < 0: # Check if its positive\n fraction = str(abs(numerator)) + \"/\" + str(abs(denominator))\n\n elif denominator == 0: # ZeroDivision Error\n print(\"Can't be divided by zero!\")\n return None\n\n else:\n fraction = str(numerator) + \"/\" + str(denominator)\n\n return fraction\n\n except TypeError: # Discard invalid string arguments\n print(\"The argument isn't a fraction\")\n\n @classmethod\n def simplify(cls, fraction):\n \"\"\"Simplify fraction to his minimum expresion.\n\n Args:\n fraction (str): Fraction to simplify\n\n Returns:\n str: Simplified fraction\n \"\"\"\n\n\n if not isinstance(fraction, str) and fraction != 0: # Discard invalid argument types\n print(\"The argument isn't a fraction\")\n return None\n elif fraction == 0:\n return fraction\n\n try:\n numerator, denominator = cls.separate_numbers(fraction)\n res = 0\n maximum = abs(max(numerator, denominator))\n minimum = abs(min(numerator, denominator))\n\n while minimum != 0: # Calculate M.C.D\n res = minimum\n minimum = maximum % minimum\n maximum = res\n\n numerator = str(int(numerator / maximum))\n denominator = str(int(denominator / maximum))\n fraction = numerator + \"/\" + denominator\n fraction = cls.sign_checker(fraction)\n return fraction\n\n except TypeError: # Discard invalid string argument\n print(\"The argument isn't a fraction\")\n\n @classmethod\n def add_zero_checker(cls, fraction1, fraction2):\n \"\"\"Check if in an addition of two fractions returns zero.\n\n Args:\n fraction1 (str): First fraction in the addition\n fraction2 (str): Second fraction in the addition\n\n Returns:\n bool: If false the addition of the fractions returns zero, if is\n true the addition don't return zero\n \"\"\"\n\n # Discard invalid arguments type\n # First argument\n if not isinstance(fraction1, str) and fraction1 != 0:\n print(\"The first argument isn't a fraction\")\n return None\n\n # Second argument\n elif not isinstance(fraction2, str) and fraction2 != 0:\n print(\"The second argument isn't a fraction\")\n return None\n\n # Check the sign of the fractions\n if (\n \"-\" in fraction1\n and \"-\" not in fraction2\n and fraction1.replace(\"-\", \"\") == fraction2\n ): # First case in which the sum gives zero\n not_zero = False\n\n elif (\n \"-\" not in fraction1\n and \"-\" in fraction2\n and fraction1 == fraction2.replace(\"-\", \"\")\n ): # Second case in which the sum gives zero\n not_zero = False\n\n elif (\n cls.simplify(fraction1) is None\n or cls.simplify(fraction2) is None\n ): # Invalid arguments\n return None\n\n else: # Other cases when the addition doesn't return zero\n not_zero = True\n\n return not_zero\n\n @classmethod\n def sub_zero_checker(cls, fraction1, fraction2):\n \"\"\"Check if in an substraction of two fractions returns zero.\n\n Args:\n fraction1 (str): First fraction in the substraction\n fraction2 (str): Second fraction in the substraction\n\n Returns:\n bool:\n If false the substraction of the fractions returns zero, if is\n true the substraction don't return zero\n \"\"\"\n\n # Discard invalid arguments type\n # First argument\n if not isinstance(fraction1, str) and fraction1 != 0:\n print(\"The first argument isn't a fraction\")\n return None\n\n # Second argument\n elif not isinstance(fraction2, str) and fraction2 != 0:\n print(\"The second argument isn't a fraction\")\n return None\n\n # Check the sign of the fractions\n if (\n fraction1 == fraction2\n ): # First case in which the substraction gives zero\n not_zero = False\n\n elif (\n cls.simplify(fraction1) is None\n or cls.simplify(fraction2) is None\n ): # Invalid arguments\n return None\n\n else: # Other cases when the substraction doesn't return zero\n not_zero = True\n\n return not_zero\n"} {"doc_id": "41bdab243f9804fd9e27b99bcd8203cf", "text": "#Damos la bienvenida y pedimos un valor\nprint(\"\\tWelcome to the Binary/Hexadecimal Converter App\")\nnum = int(input(\"\\nCompute binary and hexadecimal values up to the following decimal number: \"))\n#Creamos una lista en blanco para despues llenarla con los valores decimales\nlista = []\nfor i in range(0,num+1):\n lista.append(i)\nprint(\"Generating lists....complete!\")\n#Ahora creamos las listas para los valores en base binaria y hexadecimal\nhe = []\nfor i in range(0,num+1):\n he.append(hex(i))\nbi = []\nfor i in range(0,num+1):\n bi.append(bin(i))\n#Ahora de una porci\u00f3n de la lista de numeros decimales, mostramos sus respectivos valores en las otras bases\nprint(\"\\nUsing slices, we will now show a portion of each list.\")\na = int(input(\"What decimal number would you like to start at: \"))\nb = int(input(\"What decimal number would you like to stop at: \"))\nprint(\"\\nDecimal values from \",a,\"to\",b,\":\")\nfor i in range(lista[a],lista[b]+1):\n print(i,\"\\n\")\nprint(f\"\\nBinary values from \",a,\" to \",b,\":\")\nfor i in range(a,b+1):\n print(bi[i],\"\\n\")\nprint(f\"\\nHexadecimal values from \",a,\" to \",b,\":\")\nfor i in range(a,b+1):\n print(he[i],\"\\n\")\n#Finalmente, mostramos todos los valores en las tres bases\nprint(\"Press Enter to see all values from 1 to\",num,\".\")\ninput(\"\")\nprint(\"Decimal----Binary----Hexadecimal\")\nprint(\"----------------------------------\")\nfor i in range(0,10): \n print(lista[i],\"----\",bi[i],\"----\",he[i])\n"} {"doc_id": "42017dd40e174b98505f28fe81927cc7", "text": "\"\"\"\n[2016-11-02] Challenge #290 [Intermediate] Blinking LEDs\n\nhttps://www.reddit.com/r/dailyprogrammer/comments/5as91q/20161102_challenge_290_intermediate_blinking_leds/\n\n# Description\nMark saw someone doing experiments with blinking LEDs (imagine something like\n[this](http://www.batsocks.co.uk/readme/XMegaExamples.htm#Sweep) ) and became fascinated by it.\nHe wants to know more about it. He knows you are good with computers, so he comes to\nyou asking if you can teach him how it works. You agree, but as you don't have any\nLEDs with you at the moment, you suggest: \"Let's build an emulator with which we can\nsee what's happening inside\". And that's today's challenge.\n**1st Part**\nThe 1st part should be easy, even though the description is rather verbose. If you want\nmore challenge try the 2nd part afterwards.\nOur system has 8 LEDs, we represent their state with a text output. When\nall LEDs are off, it is printed as string of eight dots \"........\". When a led is on,\nit is printed as \"\\*\". LED-0 is on the right side (least significant bit), LED-7 is on the\nleft side. Having LEDs 0 and 1 on and all others off is written as \"......\\**\"\nOn input you get a sequence of lines forming a program. Read all lines of the input (detect\nEOF, or make the first line contain number of lines that follow, whichever is more convenient\nfor you). Afterwards, print LED states as they are whenever the program performs an out instruction.\nEach line is in the following format:\n : |\n \n : ld a, |\n out (0),a\n<whitespace> is one or more of characters \" \" or \"\\t\". <num> is a number between 0 and 255.\nInstruction ld a,<num> sets internal 8-bit register A to the given number.\nInstruction out (0),a updates the LEDs according to the current number in A.\nThe LED-0's state corresponds to bit 0 of number in A, when that number is represented\nin binary. For example, when A = 5, the LED state after out instruction is \".....\\*.*\".\nYou should output the LED states after each out instruction.\nChallenge input 1:\n ld a,14\n out (0),a\n ld a,12\n out (0),a\n ld a,8\n out (0),a\n out (0),a\n ld a,12\n out (0),a\n ld a,14\n out (0),a\nExpected output:\n ....***.\n ....**..\n ....*...\n ....*...\n ....**..\n ....***.\n**2nd Part**\nWe will extend our programming language, so that we can do more updates without\nwriting out instruction for each of them. We will have loops.\nEach line has the following format:\n : |\n