text
stringlengths
37
1.41M
class Calculation(object): def getInput(self): inputtext = input("Enter numbers with arithmetic operator: ") if (eval(inputtext)) != None: print(eval(inputtext)) calc = Calculation() try: calc.getInput() except: print("lololol") calc.getInput()
class Node: def __init__(self, value, next=None): self.value = value self.next = next def __repr__(self): return self.value n3 = Node("third") n2 = Node("second") n1 = Node("first") # n1.next = n2 # n2.next = n3 # n3.next = None n1.next = n2 n2.next = n3 n3.next = n1 # loop def h...
class Node: def __init__(self, value, left=None, right=None): self.value = value self.right = right self.left = left # right n0 = Node(value=0) n1 = Node(value=1) n6 = Node(value=6, left=n0, right=n1) n2 = Node(value=2, left=None, right=None) # left n103 = Node(value=3) n14 = Node(value...
contador = 0 while contador <= 100: resultado = 2 ** contador print(f"2 elevado a {contador} es {resultado}") contador += 1
print("Ejercicio 3 - Km/h a cm/s") print("*********************") kilometros = float(input("Ingrese la cantidad de Km/h: ")) cant_en_centimetros = int(round( kilometros * 27.778 ,2)) print (f"Los kilometros {kilometros} convertido a centimetros es {cant_en_centimetros}")
print("Ejercicio 2 - Area/Perimetro de un poligono") print("********************************************") mensaje = """Elija una de estas 2 opciones: 1 = Area del Cuadrado 2 = Perimetro del Rectangulo""" print(mensaje) opcion = int(input("Ingrese una opción: ")) def area_poligono (): print("Area de un cuadrad...
print("CUARTO EJERCICIO - RECIBIR NOMBRE") print("***********************************") print("Ingrese su nombre:") nombre = input() print("hola, "+nombre)
def invalid_opt(): print("Invalid choice") def Menu_turma(t): options = {"A":["Adicionar Aluno", t.f_adicionar_aluno], "B":["Remover Aluno",t.f_remover_aluno], "C":["Adiocionar Professor",t.f_adicionar_professor], "D": ["Listar alunos", t.f_alunos_ordem_alfabetica], "E": ["Dar nota aos alunos da turma", t.f...
from datetime import datetime class Person: def __init__(self, f_name, l_name, date_of_birth, email, country, phone, address): self.FirstName = f_name self.LastName = l_name self.DateOfBirth = date_of_birth self.Email = email self.Country = country self.Phone = phone...
def Remove(duplicate): my_array= [] for num in duplicate: if num not in my_array: my_array.append(num) return my_array duplicate = [6,7,8,6,8] print(Remove(duplicate))
def checking_the_number(number2): user_input = list(map(int, str(number2))) print(user_input) user_input1 = list(map(int, str(number2))) print(user_input1) user_input.sort() print(user_input) if user_input == user_input1: print("yes") else: print("no") number1 = 1234 n...
def birthdayCakeCandles(array): maximum=array[0] count=0 for i in range(0,len(array)): if array[i]>maximum: maximum=array[i] for i in range(0,len(array)): if max==array[i]: count+=1 return count print(birthdayCakeCandles())
def caesar(): inputs=int(input("enter the number")) char=(input("enter the character")) print(chr(ord(char)+inputs)) print(caesar())
def bird_migration(array): count = 0 for i in range(0, len(array)): for j in range(i + 1, len(array)): if array[i] == array[j]: count = count + 1 print(count) # print(count.index(result)) array = [1, 4, 4, 4, 5, 3] bird_migration(array)
def length_of_element(length): return length a=[] n=int(input("Enter number of elements:")) for i in range(1,n+1): b=input("Enter element:") a.append(b) a.sort(key=length_of_element) print(a) print(print())
def find_the_legs_and_chick(number_of_legs, number_of_heads): for number_of_chicks in range(0, number_of_heads + 1): number_of_rabbit = number_of_heads - number_of_chicks total = 4 * number_of_rabbit + 2 * number_of_chicks if total == number_of_legs: return [number_of_rabbit, num...
# # dict1 = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5} # # for (k, v) in dict1.items(): # # dict1[k*2] = v # # print(dict1) # # Take user input # number = 2 # # # Condition of the while loop # while number < 5 : # print("Thank you") # # Increment the value of the variable "number by 1" # number = number+1...
def equal_elements(array): count_list = [] for i in range(0, len(array)): count_list.append(array.count(array[i])) maximum = max(count_list) result = len(array) - maximum print(result) array = [3, 3, 2, 1, 3] equal_elements(array)
get_the_list_digit = [] # get the count of the number number_count = 2 # get the number from the user number = 1012 # split the number into a single digit and replace the O with empty space for i in str(number).replace('0', ''): get_the_list_digit.append(int(i)) count=0 # check collect each and every item from the...
def minimum_distance(array): array_list = [] for i in range(0, len(array)): for j in range(i + 1, len(array)): if array[i] == array[j]: array_list.append(abs(i - j)) if len(array_list) == 0: print(-1) else: print(min(array_list)) array = [7, 1, 3, 4,...
def reverse_of_number(): starting = 20 ending = 23 reverse = 0 for i in range(starting, ending + 1): if (i - int(str(i)[::-1])) % 6 == 0: reverse = reverse + 1 print(reverse) reverse_of_number()
def pattern8(row): space = row - 1 star = 1 for i in range(0, row): for j in range(0, space - i): print("-", end='') for k in range(0, star): print("*", end='-') star += 1 print() row = 4 pattern8(4)
import turtle # creating turtle pen t = turtle.Turtle() # taking input for the side of the triangle s = int(input("Enter the length of the side of the triangle: ")) # taking the input for the color col = input("Enter the color name or hex value of color(# RRGGBB): ") #https://www.geeksforgeeks.org/draw-c...
from lesson16.person import Person class Teacher(Person): def __init__(self, first_name, last_name, gender, age, subject, wage): super().__init__(first_name, last_name, gender, age) self._subject = subject self._wage = wage def __repr__(self): return f"{self._first_name} {self._...
"""Napisać program znajdujący wszystkie najdłuższe łańcuchy znaków na danej liście i wypisujący je w kolejności alfabetycznej""" strings = ['ABC', 'GFG', 'CDA', 'a', 'b', 'c', 'FGL'] alphabet_string = [] for idx, string in enumerate(strings): if idx == 0: current_max_len = len(string) if current_max_l...
"""Simulates the popular 'Twenty One' card trick. 1. 21 cards selected from the deck. 2. Cards are dealt into 3 columns of 7. 3. Participant selects a card. 4. Participent points to the pile which contains their card. 5. Cards are picked up with the selected pile sandwiched between the others. 6. Steps 2-5 are repeate...
""" Given an integer array, nums, return an array containing its running sum at every index. Ex: Given the following nums… nums = [1, 2, 3], return [1, 3, 6]. Ex: Given the following nums… nums = [10], return [10]. """ class Solution: def runningSum(self, nums: list[int]) -> list[int]: for i in range(1...
# This problem was recently asked by Apple: # Create a class that initializes with a list of numbers and has one method called sum. # sum should take in two parameters, start_idx and end_idx and return the sum of the list from start_idx (inclusive) to end_idx` # (exclusive). # You should optimize for the sum method....
""" This question is asked by Facebook. Given N points on a Cartesian plane, return the minimum time required to visit all points in the order that they’re given. Note: You start at the first point and can move one unit vertically, horizontally, or diagonally in a single second. Ex: Given the following points… points...
""" Given the reference to a binary tree, return the length of the longest path in the tree that contains consecutive values. Note: The path must move downward in the tree. Ex: Given the following binary tree… 1 \ 2 \ 3 return 3. Ex: Given the following binary tree… 1 / \ 2 2 / \ / \...
""" This question is asked by Facebook. Given an undirected graph determine whether it is bipartite. Note: A bipartite graph, also called a bigraph, is a set of graph vertices decomposed into two disjoint sets such that no two graph vertices within the same set are adjacent. Ex: Given the following graph... graph = [...
""" Given a list of words, return all the words that require only a single row of a keyboard to type. Note: You may assume that all words only contain lowercase alphabetical characters. Ex: Given the following list of words… words = ["two", "dad", "cat"], return ["two", "dad"]. Ex: Given the following list of words… ...
""" This question is asked by Amazon. Given a string s remove all the vowels it contains and return the resulting string. Note: In this problem y is not considered a vowel. Ex: Given the following string s… s = "aeiou", return "" Ex: Given the following string s… s = "byte", return "byt" Ex: Given the following st...
""" Given an array of integers, nums, return the “equality index” if it exists and negative one otherwise. Note: The equality index of the array is the index where the sum of all elements to the left of the index is equal to the sum of all elements to the right of the index. Ex: Given the following nums… nums = [1, 2...
""" This question is asked by Google. A ball is dropped into a special Galton board where at each level in the board the ball can only move right or down. Given that the Galton board has M rows and N columns, return the total number of unique ways the ball can arrive at the bottom right cell of the Galton board. Ex: ...
# This problem was recently asked by Amazon: # Given a binary tree, flatten the binary tree using inorder traversal. Instead of creating a new list, reuse the nodes, # where the list is represented by following each right child. As such the root should always be the first element in the list # so you do not need to re...
# This problem was recently asked by Uber: # Given a string s and a character c, find the distance for all characters in the string to the character c in the string s. # You can assume that the character c will appear at least once in the string. def shortest_dist(S, X): # Fill this in. prev = float("-inf") ...
""" Given a reference to a linked list, return whether or not it forms a palindrome. Ex: Given a reference to the following linked list... head = 1->3->1, return true. Ex: Given a reference to the following linked list... head = 1->7, return false. """ from typing import Optional class ListNode: def __init__...
# This problem was recently asked by Amazon: # Given a binary tree and a given node value, return all of the node's cousins. # Two nodes are considered cousins if they are on the same level of the tree with different parents. # You can assume that all nodes will have their own unique value. class Node(object): d...
""" This question is asked by Amazon. Given the root of a binary tree where every node’s value is either 0 or 1 remove every subtree that does not have a 1 in it. Ex: Given the following binary tree… 1 / \ 1 0 Return the tree such that it’s been modified to look as follows… 1 / ...
# This problem was recently asked by Microsoft: # Given a list of numbers of size n, where n is greater than 3, find the maximum and minimum of the list # using less than 2 * (n - 1) comparisons. def find_min_max(nums): # Fill this in. n = len(nums) if n % 2 == 0: mx = max(nums[0], nums[1]) ...
# This problem was recently asked by LinkedIn: # You are only allowed to perform 2 operations, multiply a number by 2, or subtract a number by 1. Given a number x and a number y, # find the minimum number of operations needed to go from x to y. def min_operations(x, y): # Fill this in. if x == y: ret...
""" Given a two-dimensional NxN integer array, matrix, return the sum of all values along its two diagonals. Note: If a value appears in both diagonals it should only be added to your sum once. Ex: Given the following matrix… matrix = [ [1, 2], [2, 1] ], return 6 (1 + 1 + 2 + 2). Ex: Given the following matrix… ...
""" This question is asked by Amazon. Given a string representing your stones and another string representing a list of jewels, return the number of stones that you have that are also jewels. Ex: Given the following jewels and stones... jewels = "abc", stones = "ac", return 2 jewels = "Af", stones = "AaaddfFf", retur...
""" Given an integer, num, that consists of only two digits, sixes and nines, return the largest number you can create by modifying one digit to be a six or a nine. Ex: Given the following num… num = 669, return 969. Ex: Given the following num… num = 9969, return 9999. """ class Solution: def maximum69Number(...
# This problem was recently asked by Twitter: # You are given the root of a binary tree. Find and return the largest subtree of that tree, which is a valid binary search tree. class TreeNode: def __init__(self, key): self.left = None self.right = None self.key = key def __str__(self)...
# This problem was recently asked by Google: # There are n people lined up, and each have a height represented as an integer. # A murder has happened right in front of them, and only people who are taller than everyone in front of them are able to # see what has happened. How many witnesses are there? def witnesses(h...
''' Given a binary tree, return the sum of all left leaves of the tree. Ex: Given the following tree… 5 / \ 2 12 / \ 3 8 return 5 (i.e. 2 + 3) Ex: Given the following tree… 2 / \ 4 2 / \ 3 9 return 3 ''' class BinaryTree: def __init__(self, val): self...
# This problem was recently asked by Facebook: # You are given a list of numbers, and a target number k. Return whether or not there are two numbers in the list that add up to k. # Try to do it in a single pass of the list. def two_sum(list1, k): for i in list1: complementary = k - i if complement...
# This problem was recently asked by Microsoft: # Given a binary tree, find the level in the tree where the sum of all nodes on that level is the greatest. class Node: def __init__(self, val, left=None, right=None): self.val = val self.left = left self.right = right def __repr__(self...
# This problem was recently asked by Uber: # Given a square 2D matrix (n x n), rotate the matrix by 90 degrees clockwise. def rotate(mat): # Fill this in. N = len(mat[0]) for i in range(N // 2): for j in range(i, N - i - 1): temp = mat[i][j] mat[i][j] = mat[N - 1 - j][i] ...
""" Given an integer array, nums, return all pairs of numbers whose difference equals the minimum difference in the array. Ex: Given the following nums… nums = [4, 2, 3], return [[2, 3], [3, 4]] (the minimum difference between any two elements is one and 3 - 2 = 1 and 4 - 3 = 1). Ex: Given the following nums… nums =...
# This problem was recently asked by Uber: # Given a number of integers, combine them so it would create the largest number. from itertools import permutations def largestNum(nums): # Fill this in. lst = ["".join(map(str, i)) for i in permutations(nums, len(nums))] return max(lst) print(largestNum([17...
""" You are given an integer array, magnets where each value in the array represents the size of a particular magnet. You goal is to connect all the magnets together to form a single magnet. Every time you connect two magnets, a and b together, you pay a cost of a + b. Return the minimum cost to connect all the magnets...
# This problem was recently asked by Twitter: # Given an array of integers of size n, where all elements are between 1 and n inclusive, # find all of the elements of [1, n] that do not appear in the array. Some numbers may appear more than once. class Solution(object): def findDisappearedNumbers(self, nums): ...
""" You are given the list of prices of a particular stock. Each element in the array represents the price of the stock at a given second throughout the current day. Return the maximum profit you can make trading this stock. Note: You may only ever buy and sell a single share of the stock, but you may make multiple tra...
# LinkedIn: Given a binary tree, find the most frequent subtree sum. class Node: def __init__(self, value, left=None, right=None): self.val = value self.left = left self.right = right def most_freq_subtree_sum(root): # fill this in. if root is None: return dist = {} ...
""" Given a list of integers, nums, return a list containing all triplets that sum to zero. Ex: Given the following nums... nums = [0], return []. Ex: Given the following nums... nums = [0, -1, 1, 1, 2, -2], return [[-2,0,2],[-2,1,1],[-1,0,1]]. """ class Solution: def threeSum(self, nums): nums.sort() ...
""" You are given an integer, n, and a binary number represented as an integer array, binary. Each of the one bits in binary must be separated by at least one zero bit otherwise the bits become angry. Return whether or not it’s possible to flip at least n zero bits to one bits without making the bits angry. Ex: Given ...
""" Given an array, nums, every value appears twice except for one which only appears once. The value that only appears once is the lucky number. Return the lucky number. Ex: Given the following nums… nums = [1, 2, 1], return 2. Ex: Given the following nums… nums = [1, 3, 1, 2, 2], return 3. """ class Solution: ...
""" You are building a pool in your backyard and want to create the largest pool possible. The largest pool is defined as the pool that holds the most water. The workers you hired to dig the hole for your pool didn’t do a great job and because of this the depths of the pool at different areas are not equal. Given an in...
""" Given an integer array, nums, return the length of the longest increasing subarray. Note: The subarray must be strictly increasing. Ex: Given the following nums. nums = [1, 2, 3], return 3. Ex: Given the following nums. nums = [3, 4, 1, 2, 8], return 3. """ class Solution: def lengthOfLIS(self, nums: list[...
""" This question is asked by Facebook. Given a string, return whether or not it forms a palindrome ignoring case and non-alphabetical characters. Note: a palindrome is a sequence of characters that reads the same forwards and backwards. Ex: Given the following strings... "level", return true "algorithm", return fals...
""" Given a list of nums and a target, return all the unique combinations of nums that sum to target. Ex: Given the following nums and target... nums = [8, 2, 2, 4, 5, 6, 3] target = 9 return [[2,2,5],[2,3,4],[3,6],[4,5]]. """ class Solution: def combinationSum2(self, numbers: list[int], target: int) -> list[li...
# This problem was recently asked by Twitter: # Given a string with the initial condition of dominoes, where: # . represents that the domino is standing still # L represents that the domino is falling to the left side # R represents that the domino is falling to the right side # Figure out the final position of the ...
""" A restaurant offers two potential sides to their dishes, soup or salad. You are given two integer arrays, customers and sides. The customers array contains only ones and zeroes where v represents the ith customer’s choice: zero being a preference of soup and one being a preference of salad. Similarly, the sides arr...
""" Given an integer array nums and a value, val, remove all instances of val in-place and return the length of the new array. Note: It does not matter what values you leave in the array beyond the array’s new length. Ex: Given the following nums and val... nums = [1, 2, 3], val = 2, return 2 (after your modification...
""" This question is asked by Google. Given an array, nums, and an integer k, return whether or not two unique indices exist such that nums[i] = nums[j] and the two indices i and j are at most k elements apart. Ex: Given the following array nums and value k… nums = [1, 2, 1], k = 1, return false. Ex: Given the follo...
""" Given a binary search tree that contains unique values and two nodes within the tree, a, and b, return their lowest common ancestor. Note: the lowest common ancestor of two nodes is the deepest node within the tree such that both nodes are descendants of it. Ex: Given the following tree... 7 / \ 2...
""" You are given two bounds, lower and upper and a sorted integer array, nums. Return a list of strings that represents the missing ranges between lower and upper that are not covered in nums. Ex: Given the following nums, lower, and upper… nums = [2, 5, 7], lower = 0, upper = 10, return ["0->1","3->4","6","8->10"] ...
""" Given two non-negative integers low and high, return the total count of odd numbers between them (inclusive). Ex: Given the following low and high… low = 1, high = 3, return 2 (1 and 3 are both odd). Ex: Given the following low and high… low = 1, high = 10, return 5. """ class Solution: def countOdds(self,...
# This problem was recently asked by Google: # Given a sorted list of numbers, and two integers low and high representing the lower and upper bound of a range, # return a list of (inclusive) ranges where the numbers are missing. # A range should be represented by a tuple in the format of (lower, upper). def missing_...
""" Given a paragraph and a list of banned words, return the most frequently occurring word that is not banned. Treat words case insensitively and ignore punctuation. Ex: Given the following paragraph and list of banned words... paragraph = "The daily, the byte Daily.", banned = [“the”], return “daily”. """ import r...
# This problem was recently asked by Facebook: # You are given the root of a binary tree. Find the path between 2 nodes that maximizes the sum of all the nodes in the path, # and return the sum. The path does not necessarily need to go through the root. class Node: def __init__(self, val): self.val = val...
# This problem was recently asked by Uber: # Given a linked list, determine if the linked list has a cycle in it. # For notation purposes, we use an integer pos which represents the zero-indexed position where the tail connects to. class ListNode(object): def __init__(self, x): self.val = x self...
""" This question is asked by Amazon. Given an integer array, two players take turns picking the largest number from the ends of the array. First, player one picks a number (either the left end or right end of the array) followed by player two. Each time a player picks a particular numbers, it is no longer available to...
""" Given an array of integers, nums, and a value k, return the number of continuous sub-arrays that sum to k. Ex: Given the following nums and k… nums = [1,1,4], k = 5, return 1. Ex: Given the following nums and k… nums = [3, 2, 2, 1, 1, 1], k = 5, return 3. """ class Solution: def subarraySum(self, nums: lis...
""" Given a binary string, binary, return the maximum score of the string. The score of a string is given by splitting the string at a specific index and summing the total number of zeroes in the left substring and the total number of ones in the right substring. Note: Both the left and right substring after the split ...
# This problem was recently asked by Microsoft: # Given a string, determine if there is a way to arrange the string such that the string is a palindrome. # If such arrangement exists, return a palindrome (There could be many arrangements). Otherwise return None. from itertools import permutations import numpy as np ...
""" This question is asked by Amazon. Given two strings s and t, which represents a sequence of keystrokes, where # denotes a backspace, return whether or not the sequences produce the same result. Ex: Given the following strings... s = "ABC#", t = "CD##AB", return true s = "como#pur#ter", t = "computer", return true...
# This problem was recently asked by Apple: # You are given the root of a binary tree, along with two nodes, A and B. Find and return the lowest common ancestor of A and B. # For this problem, you can assume that each node also has a pointer to its parent, along with its left and right child. class TreeNode: def...
""" Given three integer arrays, nums1, nums2, and nums3, sorted in ascending order, return a list containing all integers that are common to all three arrays. Note: There are no duplicate values in any of the arrays. Ex: Given the following nums1, nums2, and nums3… nums1 = [1, 2, 3], nums2 = [1, 2], nums3 = [1], ret...
""" Given a value, N, you are asked to form a staircase. The number of elements in each row of the staircase must match the current row. Return the total number of full staircase rows you can create. Ex: Given the following N... N = 3 return 2. * * * (this staircase has two rows) Ex: Given the following N... N = 7 r...
""" This question is asked by Microsoft. Given a message that is encoded using the following encryption method… A -> 1 B -> 2 C -> 3 ... Z -> 26 Return the total number of ways it can be decoded. Note: ‘0’ has no mapping and a character following a ‘0’ also has no mapping (i.e. “03”) Ex: Given the following messag...
"""Given the reference to a binary search tree, “level-up” the tree. Leveling-up the tree consists of modifying every node in the tree such that every node’s value increases by the sum of all the node’s values that are larger than it. Note: The tree will only contain unique values and you may assume that it is a valid ...
""" You are given two integer arrays, A and B. B is an anagram of A meaning that B contains all the same elements of A but in a different order. Return an array that represents a mapping from every element in A to which index it occurs at in B. Note: You may assume every element in A is unique. Ex: Given the following...
# This problem was recently asked by Amazon: # You are given an array of integers. Return an array of the same size where the element at each index # is the product of all the elements in the original array except for the element at that index. def products(nums): # Fill this in. prod = 1 for i in nums: ...
""" Given a 2D matrix, return a list containing all of its element in spiral order. Ex: Given the following matrix... matrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ], return [1, 2, 3, 6, 9, 8, 7, 4, 5]. """ class Solution: def spiralOrder(self, matrix: list[list[int]]) -> list[int]: if not matrix: ...
""" You are given an array of interval objects, which each consist of a start time and an end time. Each interval object represents when a particular meeting starts and ends. Return whether or not someone could attend every meeting. Ex: Given the following intervals... intervals = [[1, 3], [5, 10]], return true. Ex: ...
""" Given a binary tree, returns of all its levels in a bottom-up fashion (i.e. last level towards the root). Ex: Given the following tree… 2 / \ 1 2 return [[1, 2], [2]] Ex: Given the following tree… 7 / \ 6 2 / \ 3 3 return [[3, 3], [6, 2], [7]] """ class Binary...
# This problem was recently asked by Amazon: # You are given a 2D array of characters, and a target string. Return whether or not the word target word exists in the matrix. # Unlike a standard word search, the word must be either going left-to-right, or top-to-bottom in the matrix. def word_search(matrix, word): ...
# This problem was recently asked by Microsoft: # Given a list of strings, find the longest common prefix between all strings. def findMinLength(arr, n): min = len(arr[0]) for i in range(1, n): if len(arr[i]) < min: min = len(arr[i]) return min def longest_common_prefix(strs): ...
""" This question is asked by Google. Given two integer arrays, return their intersection. Note: the intersection is the set of elements that are common to both arrays. Ex: Given the following arrays... nums1 = [2, 4, 4, 2], nums2 = [2, 4], return [2, 4] nums1 = [1, 2, 3, 3], nums2 = [3, 3], return [3] nums1 = [2,...
""" Given a number n, return a list containing specific outputs for each value between one and n. For any number, if it is divisible by three and it is divisible by five, append “FizzBuzz” to your list. If it is divisible by only three, append “Fizz” to your list. If it is divisible by only five, append “Buzz” to your ...
""" Given a string S that contains only lowercase letters, return a list containing the intervals of all the bunches. A bunch is a set of contiguous characters (larger than two) that are all the same. An interval that represents a bunch contains the starting index of the bunch and the ending index of the bunch. Note: T...
# This problem was recently asked by AirBNB: # Given two strings, determine the edit distance between them. # The edit distance is defined as the minimum number of edits (insertion, deletion, or substitution) needed to change one string to the other. def distance(s1, s2): # Fill this in. m = len(s1) n = l...
class LinkedList(): def __init__(self, value=None): self.value = value self.before = None self.behind = None def __str__(self): if self.value is not None: return str(self.value) else: return 'None' def init(): return LinkedList('HEAD') de...
""" 背包问题 题目 有一个背包能装10kg的物品,现在有6件物品分别为: 物品名称 重量 物品0 1kg 物品1 8kg 物品2 4kg 物品3 3kg 物品4 5kg 物品5 2kg 编写找出所有能将背包装满的解,如物品1+物品5。 """ def knapsack(package, items): n = len(items) # 可选物品的数量 stack = [] # 创建一个栈 index = 0 # 当前所选择的物品游标 while stack or index < n: # print('current stack') # print(s...
""" 题目 计算一个表达式时,编译器通常使用后缀表达式,这种表达式不需要括号: 中缀表达式 后缀表达式 2 + 3 * 4 2 3 4 * + ( 1 + 2 ) * ( 6 / 3 ) + 2 1 2 + 6 3 / * 2 + 18 / ( 3 * ( 1 + 2 ) ) 18 3 1 2 + * / 编写程序实现后缀表达式求值函数。 思路 建立一个栈来存储待计算的操作数; 遍历字符串,遇到操作数则压入栈中,遇到操作符号则出栈操作数(n次),进行相应的计算,计算结果是新的操作数压回栈中,等待计算 按上述过程,遍历完整个表达式,栈中只剩下最终结果; """ operator = { '+': lambda x,...
# -*- coding: utf-8 -*- """ Tim Petersen 10/31/18 Merge Sort Best Case: O(nlogn) Average Case: O(nlogn) Worst Case: O(nlogn) Space Complexity: O(n) Stability: Yes """ def MergeSort(arr): if len(arr) > 1: m = len(arr)//2 # int division cause if its odd # Split the array into two temporary ...