text
stringlengths
37
1.41M
#Write a recursive function which calculates the factorial of a given number. # Use exception handling to raise an appropriate exception if the input parameter is not a # positive integer, but allow the user to enter floats as long as they are whole numbers. import math def factorial( n ): if n ==0: # base case ...
battleship_guesses = { (3, 4): False, (2, 6): True, (2, 5): True, } surnames = {} # this is an empty dictionary surnames["John"] = "Smith" surnames["John"] = "Doe" print(surnames) # we overwrote the older surname marbles = {"red": 34, "green": 30, "brown": 31, "yellow": 29 } marbles["blue"] = 30 # this wi...
temperature=float(input()) if temperature < 0: print("Below freezing") elif temperature < 10: print("Very cold") elif temperature < 20: print("Chilly") elif temperature < 30: print("Warm") elif temperature < 40: print("Hot") else: print("Too hot")
''' Given an m x n integer matrix heightMap representing the height of each unit cell in a 2D elevation map, return the volume of water it can trap after raining. Input: heightMap = [[1,4,3,1,3,2],[3,2,1,3,2,4],[2,3,3,2,3,1]] Output: 4 Explanation: After the rain, water is trapped between the blocks. We have two small ...
#This is a guess the number game import random secretNumber=random.randint(1, 20) print('I am thinking of a number between 1 to 20.') for guessesTaken in range(1,7): print('Guess my number') guess=int(input()) if guess < secretNumber: print('The number guessed is lower than my number') elif guess > secretNumb...
course = "Python Programming" print(course.upper()) print(course.lower()) print(course.title()) course = " Python Programming" print(course) print(course.strip()) print(course.find("Pro")) print(course.find("pro")) print(course.replace("P", "-")) print("Programming" in course) print("Programming" not in course)
def repeat_to_length(string_to_expand, length): return (string_to_expand * (int(length/len(string_to_expand))+1))[:length] def xor_crypt(text, key): expanded_key = repeat_to_length(key, len(text)) index = 0 encrypted_string = "" for char in text: original_char_ascii = ord(char) key...
def HammingDistance(string1, string2): if len(string1) != len(string2): raise Exception("Lengths of strings are not equal") string1_hex_value = bytearray.fromhex(string1.encode("utf-8").hex()) string2_hex_value = bytearray.fromhex(string2.encode("utf-8").hex()) xor_result = bytes(a ^ b for (a, b...
#update memo:时间需要自动更新到今天的日期,并且显示出来 #获取的数据是否是复权数据 import tushare as ts from decimal import Decimal import time import sys sys.path.append('/home/alzer/PycharmProjects/THShelper/utils') from myTushare import getTuShareService #input validation def exCompletion(ex): if(len(ex) != 6 ): print('ex code %s err...
''' #taking input x = input('Enter name:') print ('Name',x) ''' #import module import statistics example_list = [5,2,5,6,1,2,6,7,2,6,3,5,5] #list print(statistics.mean(example_list)) from statistics import mean # so here, we've imported the mean function only. print(mean(example_list)) # and again we can do as fro...
# Written by Austin Staton # Used to demonstrate the use of OOP in Python. class University: def __init__(self, name, location): self._name = name self._location = location def getName(self): return self._name def getLocation(self): return self._location def getUniversity(self): return self.getName() ...
'''This program works like the Engima machine. It utilized the Ceaser encryption method along with a few advanced tweaks that make sure that the encrypted message is not easy to crack To us this: 1) To encrypt a message: >python3 encrypter.py -e then enter an integer key followed by a message 2) To ...
#!/usr/bin/env python # -*- coding: utf-8 -*- """unit conversions""" import numbers #Define exceptions class ConversionNotPossible(Exception): pass def convert(fromUnit,toUnit,value): if not isinstance(value, numbers.Number) or isinstance(value, bool): raise ConversionNotPossible, "non number entered" ...
# -*- coding: utf-8 -*- """ Created on Fri Sep 22 07:10:09 2017 @author: shrey """ import numpy as np import matplotlib.pyplot as plt import pandas as pd from pca import do_pca #read the data data=pd.read_csv("/home/shrey/Desktop/ml/dataset_1.csv") #fetch the three variables x=data['x'] y=data['y'] z=data['z'] #...
import pandas as pd import sqlite3 import matplotlib.pyplot as plt import folium def q1(qq1,connection): start_year= input('Enter start year(YYYY) ') end_year = input('Enter end year(YYYY) ') crime_type = input('Enter crime type ') df = pd.read_sql('select month1,count(Incidents_Count) from (select dist...
words = "It's thanksgiving day. It's my birthday, too!" print words.find("day") print words.replace("day", "month") myList = [2,54,-2,7,12,98] print max(myList) print min(myList) x = ["hello",2,54,-2,0.5,7,12,98,"world"] print x[0::len(x)-1] #prints the first and last item :: skips numbers in between print x[0], ...
def is_constant(const): '''returns True if const is constant, False if it const is folder const is a dict with the following keys: {'id': 'math', 'name': 'Mathematics', 'parent_id': '', \ 'value': '', 'unit': '', 'unit_system': ''} ''' if const == None: return None ret...
""" Simple prime number practice program. Solution for: http://www.practicepython.org/exercise/2014/04/16/11-check-primality-functions.html """ from InputHandler import inputintgen # strong probable prime def is_sprp(n, b=2): """Returns True if n is prime. Code borrowed from: https://codegolf...
# -*- coding:UTF-8 -*- import sys reload(sys) sys.setdefaultencoding('utf-8') import random import time from fractions import Fraction #getsymbol函数,返回一个运算符号 def getoperators(): operatorslist=('+','-','×','÷','+','-') operators=random.choice(operatorslist) if operators=='×': length=2 ...
def calculate1(data:list, waypoint = (0,1)): """Calculate the values""" '''Direction 1: North 2: East 3: South 4: West ''' waypoint_map = { 'N': lambda x,y: (x, y), 'E': lambda x,y: (y, -x), 'S': lambda x,y: (-x, -y), 'W': lambda x,y: (-y,...
import os import pandas as pd import sqlite3 CSV_FILEPATH = os.path.join(os.path.dirname(__file__), "..", "data", "buddymove_holidayiq.csv") DB_FILEPATH = os.path.join(os.path.dirname(__file__), "..", "data", "buddymove_holidayiq.db") connection = sqlite3.connect(DB_FILEPATH) table_name = "reviews2" df = pd.read_cs...
from help import RemoveWhiteSpaces from help import Space_Out def PART_1_OF_FINAL_PROJECT_CPSC_323(): print("\n\nWHITE SPACE AND COMMENT REMOVEAL\n\n") infile = open('finalp1.txt','r') whole = infile.read() number_of_lines = whole.count('\n') infile.close() file1 = open('fina...
# Lightly modified from from https://scipython.com/book/chapter-8-scipy/additional-examples/the-sir-epidemic-model/ # Goal is to learn the beta and gamma parameters from socio-economic facotrs import numpy as np from scipy.integrate import odeint import matplotlib.pyplot as plt class SIRmodel(): def __init__(sel...
from abc import ABC, abstractmethod class Distribution(ABC): def __init__(self): super().__init__() @abstractmethod def mean(self): pass @abstractmethod def update(self): pass @abstractmethod def sample(self): pass @abstractmethod def get_para...
# program of a terminal calculator a = int(input("Enter first number : ")) b = int(input("Enter second number : ")) print( "Welcome! \n \n Select an option \n 1 for addition \n 2 for subtraction \n 3 for multiplication \n 4 for division \n q for quitting") ch = input() while True: if ch == "1": print(...
import sys str = sys.argv[1] st = str.strip() i = str.find("_",0,len(str)) j = str.find("_",i+1,len(str)) #f.write(str + "\n") newStr = str[j+1:] + " of " + str[i+1:j] newStr = newStr.strip() print newStr.upper()
""" This module implement a rainbow effect. It will send color messages to pass through all rainbow colors : red, yellow, green, turquoise, blue, purple. """ import threading import colorsys class RainbowThread(threading.Thread): """docstring for RainbowThread""" def __init__(self, connection, lights, stop_eve...
# ---------------------------------------------------------------------------- # 8-7. Album: Write a function called make_album() that builds a dictionary # describing a music album. The function should take in an artist name and an # album title, and it should return a dictionary containing these two pieces of # infor...
import unittest from hash_table_with_separate_chaining import HashTable class TestWithSeparateChaining(unittest.TestCase): def test_init(self): """ Test new Node initialization """ ht = HashTable() self.assertIsInstance(ht, HashTable) self.assertEqual(ht.size, 9) ...
import copy import itertools import random def first(iterable): return next(iter(iterable)) def pairwise(iterable): first, second = itertools.tee(iterable) next(second, None) return itertools.zip_longest(first, second) def prepend(first, iterable): yield first for item in iterable: yield item def random_ite...
Nama_Teman = ['Fagih','Raka','Alif','Ano','Rizal','Nauval','Ahnaf','Jefri','Rafli','Hasan'] print('Nama Teman_Semula:', Nama_Teman) print ("Nama Teman[4]:", Nama_Teman[4]) print ("Nama Teman[6]:", Nama_Teman[6]) print ("Nama Teman[7]:", Nama_Teman[7]) Nama_Teman[3] = ('Akrom') Nama_Teman[5] = ('Rara') Nama_Tem...
import numpy as np import pandas as pd from pandas.api.types import is_datetime64_any_dtype as is_datetype def drop_n_rows(df, n): """Drop first n rows from data. Args: df: DataFrame to be modified. n: number of rows to drop. """ if (not isinstance(n, int)) or (n < 0): raise...
#average N = int(input()) numbers = list(map(int, input().split())) total=0 for i in numbers: total+=i avg=total/N print(avg) #median numbers.sort() if N % 2 != 0 : med = numbers[((N-1)//2)+1] else: med = (numbers[(N-1)//2]+numbers[((N-1)//2)+1])/2 print(med) #Mode mode=max(numbers, key=numbers.count) ...
def list_item (list, value): """a function to find all indices of a given value in a list.""" indices =[] # Iterate through list to for i in range(len(liste)): if liste[i] == value: indices.append([i]) # if list contain other list elif type(liste[i]) is list: # using recursive method to find index...
# # @lc app=leetcode.cn id=94 lang=python3 # # [94] 二叉树的中序遍历 # # @lc code=start # Definition for a binary tree node. from typing import List class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def inorderTraversal(self, root: TreeNode)...
import unittest import isprime class TestStringMethods(unittest.TestCase): def test_two_is_prime(self): self.assertTrue(isprime.isPrime(2)) def test_one_is_not_prime(self): self.assertFalse(isprime.isPrime(1)) def test_three_is_prime(self): self.assertTrue(isprime.isPrime(3)) def test_four_is_not_prime(...
#!/usr/bin/env python # -*- encoding: utf-8 -*- # @Author : Ren Qiang # ACtion2 互补DNA 其中,A与T互补,C与G互补编写函数DNA_strand(dna) # %% 自己的做法 def DNA_strand(dna): out = '' for i in dna: # print(i) if i == 'A': out += 'T' elif i == 'T': out += 'A' elif i == 'C': ...
for i in range(1,5): for j in range(4-i): print(" ",end="") for j in range(i*2-1): print("*",end="") print("") for i in range(5,8): for j in range(i-4): print(" ",end="") for j in range(15-2*i): print("*",end="") print("")
def mult(n): res = 1 for i in range(1,n+1): res *= i return res sum = 0 for i in range(1,21): sum += mult(i) print(mult(i),sum)
a = [1,2,3,4,10,12] num = int(input("num:")) res = [] for i in range(len(a)): if num >= a[i]: res.append(a[i]) if i == len(a)-1: res.append(num) else: res.append(num) for j in range(i,len(a)): res.append(a[j]) break print(res)
list = [] for i in range(5): str = input() list.append(str) print(list)
class student: name = "" age = 0 score = 0 def input(self): self.name = input("name:") self.age = int(input("age:")) self.score = int(input("score:")) def output(self): print("name:",self.name) print("age:",self.age) print("score:",self.score) if __...
# 递归 def fib(n): if n == 1 or n == 2: return 1 else: return fib(n-1)+fib(n-2) # 非递归 def fib1(n): a,b = 0,1 for i in range(0,n-1): a,b = b,a+b return b print(fib(10)) print(fib1(10))
str1 = "hello" str2 = "wujue" str = str1 + str2 print(str)
class Solution: #define if A win score = 100, else A lose (i.e B wins) score = -100 #define winning scenario for A's round (when player = A and remain = 1 to 3) Turn_A_Score={ 1:100, 2:100, 3:100 } #define winning scenario for B's round (when player = B and rem...
#Base Tasks #Task 1 home_tube_station='southwark' print(home_tube_station.title()) kcl_tube_station='temple' print('I cannot go from ' + home_tube_station.title() + ' to ' + kcl_tube_station.title() + ' in one go') #Task 2 elizabeth_line=['Southwark', 'Temple', 'Dilly', 'Campfire', 'Wonderland', 'Asterix', 'SevenEleve...
stack=[] stack.append('apple') stack.extend(['pear', 'banana', 'tomato']) print (stack) print(stack.pop(1)) letters = ['a', 'b', 'c', 'd'] new_list_1 = letters new_list_2 = letters[:] letters[2] = 'e' print(new_list_1) print(new_list_2) x = [1, 2] y = [1, 2] print(x == y) print(x is y) x=y print(x is y)
def split_and_reverse(string): length = (len(string) // 2) - 1 a, b = string[length::-1], string[:length:-1] return a + b print(split_and_reverse('privet'))
import pygame class Button(pygame.sprite.Sprite): def __init__(self, text, game, x, y, color): super().__init__() self.text = text self.width = 150 self.height = 50 self.game = game self.image = pygame.Surface([self.width, self.height]) self.image.fill(color)...
run = True users = [] while run: command = input("command >> ") if command == "exit": run = False if command == "new user": name = input("Nome: ") users.append(name) if command == "list users": for user in users: print(user) if command == "sh...
length = int(input(f"Введите длину массива: ")) array = [] for item in range(length): number = int(input(f"Введите элемент массива: ")) array.append(number) def sum_and_mult(array): summ = 0 mult = 1 for item in array: summ += item mult *= item return { "summ": summ, ...
string = input(f'Введите буквы: ') def str_compress(string): result = string[0] counter = 1 for i in range(len(string) - 1): if string[i] == string[i + 1]: counter += 1 else: if counter > 1: result += str(counter) result += string[i + 1] ...
# В строке, состоящей из слов, разделенных пробелом, найти самое длинное слово. # Строка вводится с клавиатуры. string = input('Введите слова через пробел: ') def long_substr(string): array = string.split(' ') result = '' for item in array: if len(item) > len(result): result = item ...
def remove_duplicates(array): result = [] for item in array: if item not in result: result.append(item) return result print(remove_duplicates([1, 1, 1, 2, 3, 2, 3]))
# Найти максимальный элемент среди минимальных элементов строк матрицы. def min_to_max(matrix): min_row = [] for item in matrix: min_row.append(min(item)) return f'Max element is {max(min_row)}' print(min_to_max([[1, 2, 3], [4, 5, 6], [100, -800, 99]]))
str1 = input(f'Введите слово 1-е: ') str2 = input(f'Введите слово 2-е: ') def anagram_str(str1, str2): str1 = str1.upper() str2 = str2.upper() if str1 == str2 or len(str1) != len(str2): return False for char in str1: if str1.count(char) != str2.count(char): return False ...
# Дан лист. Вернуть лист, состоящий из элементов, которые меньше среднего арифметического исходного листа. # С.а. = сумма элементов разделить на количество. def arr_less_average(arr): result = [] avr = sum(arr) / len(arr) for i in arr: if i < avr: result.append(i) return result pri...
def pair_sum(arr, k): result = [] i = 0 while i < len(arr): ii = 0 while ii < len(arr): if arr[i] + arr[ii] == k and i != ii: find = sorted([arr[i], arr[ii]]) if find not in result: result.append(find) ii += 1 ...
def help_bob(string): result = '' for char in string: if char.isdigit() or char.isalpha(): result += char # print(result) return len(result) print(help_bob("!2jh$%#%3g"))
def convert_housing_data_to_quarters(): '''Converts the housing data to quarters and returns it as mean values in a dataframe. This dataframe should be a dataframe with columns for 2000q1 through 2016q3, and should have a multi-index in the shape of ["State","RegionName"]. Note: Quarters...
"""Q1. Define a class called Bike that accepts a string and a float as input, and assigns those inputs respectively to two instance variables, color and price. Assign to the variable testOne an instance of Bike whose color is blue and whose price is 89.99. Assign to the variable testTwo an instance of Bike whose co...
# Operadores Aritmeticos soma = "+" subt = "-" mult = "*" div = "/" exponenciacao = "**" parte_inteira = "//" soma_exe = 2 + 2 #= 4 ok subt_exe = 2 - 2 #= 0 ok mult_exe = 2 * 2 #= 4 ok div_exe = 2 / 2 #= 1 ok expo_exe = 2 ** 2 #= 4 ok parte_inteira_exe = 2 // 2 #= 1 ok print(som...
# -*- coding:UTF-8 -*- class Pizza(): name, dough, sauce, toppings = None, None, None, [] def prepare(self): print 'Preparing' + self.name print 'tossing dough...' print 'Adding sauce' print 'Adding toppings: ' for each in self.toppings: print " " + each ...
""" Author: Ramiz Raja Created on: 11/01/2020 Problem 3: Rearrange Array Elements Rearrange Array Elements so as to form two number such that their sum is maximum. Return these two numbers. You can assume that all array elements are in the range [0, 9]. The number of digits in both the numbers cannot differ by more tha...
from turtle import Screen, Turtle from paddle import Paddle from ball import Ball from scoreboard import Scoreboard import time screen = Screen() screen.tracer(0) screen.bgcolor("black") screen.setup(width=800, height=600) screen.title("pong") player_1=screen.textinput("PLAYER DETAILS","PLAYER 1 NAME") player_2=scree...
# geringoso.py # Alumna: Julieta Bloise # Ejercicio 1.18: # Usá una iteración sobre el string cadena para agregar la sílaba 'pa', 'pe', 'pi', 'po', o 'pu' según corresponda luego de cada vocal. cadena = input("Escribí la palabra que quieras traducir a geringoso: ") capadepenapa = '' for c in cadena: if c == "a"...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Sep 14 20:09:09 2021 @author: bloisejuli """ # bbin.py #%% # Ejercicio 6.15: # Usando lo que hiciste en el Ejercicio 6.14, agregale al archivo bbin.py una función insertar(lista, x) que reciba una lista ordenada # y un elemento. Si el elemento se en...
length, width = 18, 7 def find_perimeter(l, w): return (l * 2) + (w * 2) def find_area(l, w): return l * w perimeter = find_perimeter(length, width) area = find_area(length, width) print("The perimeter is: {}".format(perimeter)) print("The area is: {}".format(area))
# Uses python3 def calc_fib(n): if n==0: return 0 if n==1: return 1 a = [0,1] for i in range(2,n+1): a.append(a[i-1]+a[i-2]) return a[-1] n = int(input()) print(calc_fib(n))
#Recurssive function for multiples of three def f(n): 'Please enter a positive number. n > 0.' if n > 0: if n == 1: return 3 else: return f(n-1) + 3 else: print('Please introduce a positive number')
#Local vs Global variable print('The global variable is x = 5 and the x inside the function is the local variable. Try to run the function with divide(x) and the program will automatically consider x = 5 as the value of x') x = 5 def divide(x): print(x/2)
#Function that tells the strength of an acid def ph_level(x): if x>=0 and x<=4: print('It is a strong acid.') if x>=5 and x<=6: print('It is a weak acid.') if x==7: print('It is neutral') if x>=8 and x<=9: print('It is a weak base') if x>=10 and x<=14: print('...
#Multiplying a number by 2 print('Enter even_number(n) for multiplying 2 times the number n') def even_number(x): y = x * 2 print(y)
#Reviewing properties of dictionnaries Month_of_Year={'January': 1, 'February' : 2, 'March': 3, 'April' : 4} M2={'May': 5, 'June' : 6,} #Take april out of the dictionary Month_of_Year.pop('April') print(Month_of_Year) #Add M2 to Month_of_Year Month_of_Year.update(M2) print(Month_of_Year) #Print strings in dictionary Mo...
#try-except exercise try: while True: x = input('Enter your area-code: ') y = int(x) print('Your code-area is {}'.format(y)) break except: print('Only numbers accepted 0-9')
# 扁平化的处理嵌套型序列 # 例如将嵌套的list解析成单个的元素,忽略掉字符串 from collections import Iterable def flatten(items, ignore_type = (str,bytes)): for x in items: if isinstance(x, Iterable) and not isinstance(x,ignore_type): yield from flatten(x) else: yield x items = [1,2, [3,4, [5, 6],8],10] fo...
# 避免出现重复的属性方法 # 在初始化的时候会被调用,所以要用到self def type_property(name,expected_type): storage_name='_'+name @property def prop(self): print('ok') return getattr(self,storage_name) @prop.setter def prop(self,value): print('ok1') if not isinstance(value,expected_type): ...
# 对固定大小的文件进行迭代 from functools import partial RECORD_SIZE = 32 with open('data.bin','rb') as f: records = iter(partial(f.read,RECORD_SIZE),b'') for i in records: print(i)
# 找出当月的日期范围 from datetime import datetime,date,timedelta import calendar def get_month_range(start_date = None): if start_date is None: start_date = date.today().replace(day = 1) _,dates_in_month = calendar.monthrange(year=start_date.year, month= start_date.month) end_date = start_date + timedelta(d...
# 使用生成器作为线程的替代 # 即协程或者用户级线程,绿色线程 def foo(): while True: x = yield print("value:",x) g = foo() # g是一个生成器 # 程序运行到yield就停住了,等待下一个next g.send(None) # 我们给yield发送值1,然后这个值被赋值给了x,并且打印出来,然后继续下一次循环停在yield处 g.send(2) # 同上 next(g) # 没有给x赋值,执行print语句,打印出None,继续循环停在yield处 # 错误提示:不能传递一个非空值给一个未启动的生成器。 # ####...
# 避免死锁 # 如果一个线程需要获取不止一把锁,则可能会出现死锁 # 解决方案:给每一个锁分配一个数字序号,并且在获取多个锁的时候,只能按升序的方式来获取 import threading from contextlib import contextmanager _local = threading.local() @contextmanager def acquire(*locks): locks = sorted(locks,key=lambda x:id(x)) acquired = getattr(_local,'acquired',[]) if acquired and max(id(lo...
# 从序列中随机出元素 import random values = [1,2,3,4,5,6] print(random.choice(values)) # 取出N个元素 print(random.sample(values,2)) # 打乱元素的顺序,原地打乱 random.shuffle(values) print(values) # 产生随机数 print(random.randint(0,10)) # 产生0到1之间的浮点数 print(random.random()) # 产生N个随机byte位表示的整数 print(random.getrandbits(200)) # random模块采用的是确定性算法,...
"""Calculator >>> calc("+ 1 2") # 1 + 2 3 >>> calc("* 2 + 1 2") # 2 * (1 + 2) 6 >>> calc("+ 9 * 2 3") # 9 + (2 * 3) 15 Let's make sure we have non-commutative operators working: >>> calc("- 1 2") # 1 - 2 -1 >>> calc("- 9 * 2 3") # 9 - (2 * 3) 3 >>> calc("/ 6 - 4 ...
import re def parse(s): s = s.strip() s = s.strip("{") s = s.strip("}") return set(re.split("[ \t,]+",s)) def output(s): return "{" + ", ".join(s) + "}" with open("rosalind_seto.txt","r") as f: n = int(f.readline()) s1 = parse(f.readline()) s2 = parse(f.readline()) print(output(...
# age=25 # # count=0 # while count<=5: # guest = int(input('输入年龄:')) # count+=1 # # if guest>age: # print('大了') # elif guest<age: # print('小了') # else: # print('正好') # break # for i in range(0,100,2): print(i)
#!/usr/bin/python import sys crypt = [] special=["35","97","37","74","99","38","37"] for i in range(len(special)): special[i]=int(special[i]) special_index=0 password=list(sys.argv[6]) length=len(password) key_index=1 for i in range(length): password[i] = ord(password[i]) for i in range(length): if key_index == 6: ...
def area(radius): return 3.14*(radius**2) r=int(input("Enter radius of circle :")) print(f"Area of Circle is ",area(r))
# I take no responsibility for the correctness of the test cases. # Test cases may included goals unreachable from start point, in which case the result for each search is an empty list # ~ST let me know if any of the test cases are wrong :3 #import Assignment2 import PESU-MI_0110_0285_0328 file = open("mi_tes...
from utils import time_it import sys primes = [2, 3] class PrimeListTooShortException(Exception): def __init__(self): self.msg = 'Prime list is not long enough to test this number' def is_prime(p, prime_list=primes): """ :param p: Number to be tested :param prime_list: lista de primos a usa...
# Uses python3 import sys def optimal_weight(W,n,w,value_dic): if (W==0) or (n==0): return 0 if (W,n) in value_dic: return value_dic[(W,n)] for i in range(1,n+1): #金条数组 for j in range(1,W+1): #总重量 #print ("kkk") value_dic...
#Uses python3 import sys import math import heapq def dijkstra(adj,cost,s): dist=[[100000,1] for i in range(len(adj))] #set distance to infinite,count to 1 prev=[-1]*len(adj) #parents dist[s][0]=0 #first vertex pair=[] ...
""" Handling missing values Generally, there are two strategies involved: 1. Masking :It involve appropriation of one bit in the data representation to locally indicate the null status of a value. 2. Choosing a sentinel value that indicate a missing value like putting -999 or anything else. """ import ...
#importing modules (pygame,random,randint,time,os) import pygame ,random from random import randint #The randint() method returns an integer number selected element from the specified range import time import os #The OS module in python provides functions for interacting with the operating system. #initialize al...
''' Given a binary tree, find its maximum depth. The maximum depth of a binary tree is the number of nodes along the longest path from the root node down to the farthest leaf node. ''' ### COMPARE WITH crackingCode : 4.1_isBalancedBinaryTree class Node: def __init__(self,item): self.val=item self....
''' Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses of length 2*n.\ For example, given n = 3, a solution set is: "((()))", "(()())", "(())()", "()(())", "()()()" Make sure the returned list of strings are sorted. https://www.youtube.com/watch?v=LxwiwlUDOk4 https:...
''' *LinkedList 1) data structure linked with Nodes 2) create Node class, LinkedList class 3) [tip] save head (don't use directly) ex) cur = self.head 4) [initialize] linkedlist = LinkedList(1) (linkedlist = LinkedList() (X)) 5) remove method : 5-1) the target is self.head 5-2) the target is in between 5-3) the target...
''' Given n non-negative integers a1, a2, ..., an, where each represents a point at coordinate (i, ai). 'n' vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water. Your progr...
''' Implement wildcard pattern matching with support for '?' and '*'. '?' : Matches any single character. '*' : Matches any sequence of characters (including the empty sequence). The matching should cover the entire input string (not partial). The function prototype should be: int isMatch(const char *s, const char *...
''' Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000. ex) babad -> bab (aba) babaab, babab cbbd -> bb baabdd -> baab babababab ''' ## SHOULD USE DYNAMIC PROGRAMMING! class Solution(object): #use dict to save the first visited index def longes...
''' Given a 2D board and a word, find if the word exists in the grid. The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once. Example: board = [ ['A','B','C','E'], ['S','F'...