text
stringlengths
37
1.41M
''' Given a list of non-overlapping axis-aligned rectangles rects, write a function pick which randomly and uniformily picks an integer point in the space covered by the rectangles. Note: - An integer point is a point that has integer coordinates. - A point on the perimeter of a rectangle is included in the space cov...
''' Give a binary string s, return the number of non-empty substrings that have the same number of 0's and 1's, and all the 0's and all the 1's in these substrings are grouped consecutively. Substrings that occur multiple times are counted the number of times they occur. ''' class Solution: # Time: O(n) # Spac...
''' You are given the head of a linked list, and an integer k. Return the head of the linked list after swapping the values of the kth node from the beginning and the kth node from the end (the list is 1-indexed). ''' from leetcode import * # Time: O(n). From Leetcode, this can be done in a single pass by maintaining...
from typing import List, Tuple, Set, Any, Optional, Dict from collections import deque, Counter, defaultdict import threading import math import random import heapq class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right # Defini...
''' You are given a 2D integer array logs where each logs[i] = [birthi, deathi] indicates the birth and death years of the ith person. The population of some year x is the number of people alive during that year. The ith person is counted in year x's population if x is in the inclusive range [birthi, deathi - 1]. Note...
''' Given a string s and a dictionary of strings wordDict, return true if s can be segmented into a space-separated sequence of one or more dictionary words. Note that the same word in the dictionary may be reused multiple times in the segmentation. ''' from leetcode import * class Solution: # DP with top-down ap...
import sys import re # Look at the images showing what these regexes do for more details. # It's not as complex as it looks. def detect(html): # (?is): i means regex should be case-insensitive # and s means '.' could stand for a newline character as well # '?' after * means be non-greedy (i.e. don't go as ...
''' Implement pow(x, n), which calculates x raised to the power n. ''' class Solution: # Recursive approach # Time: O(log(n)) # Space: O(log(n)) def myPow(self, x: float, n: int) -> float: def helper(x, n): if n == 0: return 1 result = helper(x, n // 2) ...
# Global variable to store the vowels. vowels = ['a', 'e', 'i', 'o', 'u'] # Time complexity: O(n*log(n)) where n is the length of the string S. # Space complexity: O(n) where n is the length of the string S. def solution(S): N = len(S) # Base cases if N == 0: return 0 elif N == 1: retur...
''' Given an integer array nums, return the number of longest increasing subsequences. Notice that the sequence has to be strictly increasing. ''' from leetcode import * class Solution: # Bottom-up DP approach # Time: O(n^2) # Space: O(n) def findNumberOfLIS(self, nums: List[int]) -> int: dp =...
''' Given the root of a Binary Search Tree (BST), convert it to a Greater Tree such that every key of the original BST is changed to the original key plus the sum of all keys greater than the original key in BST. ''' from leetcode import * # From leetcode, there's an O(n) time and O(1) space solution using Morris in-o...
#!/usr/bin/env python def P(gc): """ Returns the chance that two randomly chosen letters are equal, taken from two strings with equal GC-content. """ CG = gc/2.0; AT = (1.0-gc)/2.0; return 2.0 * (CG*CG + AT*AT) def E(gc,m,n): """ Given two strings of lengths m and n, m<n, returns the expected number...
#!/usr/bin/env python import yaml import json def printlist(nm,lst): ''' This function prints a list after a banner with the list name using pprint the list and name are passes as parameters ''' from pprint import pprint as pp banner = "*"*10 nl="\n" print banner*5,nl print banner,...
def sort(array): if len(array) <= 1: return array else: firsthalf = array[:len(array)/2] secondhalf = array[len(array)/2:] return merge(sort(firsthalf), sort(secondhalf)) def merge(array1, array2): p1, p2 = 0, 0 array3 = [] while True: if array1[p1] <= array...
#!/usr/bin/env python # return the index of first pairs that add up to target def complementary_pair(target, data): memo = {} for idx, num in enumerate(data): com = target - num memo[com] = idx if num in memo: if memo[num] == idx: continue return "%s + %s = %s at [%s, %s] of %s" % (com, num...
#!/usr/bin/env python # -*- coding: utf-8 -*- class PostingsListNode: def __init__(self, label, nxxt=None, jump=None): self.label = label self.order = -1 self.next = nxxt self.jump = jump def to_string(self): memo = "[%s:%d]→ " % (self.label, self.order) if self.next: memo += self.ne...
s=input() rev = s[::-1] even = s[::2] print('Here is the reverse:',rev) print('Here are chars with even index:',even)
class Shape(object): def __init__(self): pass def area(self): return 88 class Square(Shape): def __init__(self, l): Shape.__init__(self) # do you need that? self.length = l def area(self): return self.length * self.length # overwriting the area method from...
def fib(n): if n == 0: return 0 elif n == 1: return 1 else: return fib(n-1) + fib(n-2) n = int(input("Give me the number: ")) print("Here is the list of firts %d finobacci numbers: " %n) list_fib = [str(fib(x)) for x in range(1, n+1)] print(','.join(list_fib)) print("Here is enumer...
def check(str): tmp = 0 for c in str: if c == '(': tmp +=1 elif c == ')': tmp -=1 if tmp < 0: return 'NO' if tmp == 0: return 'YES' else: return 'NO' for i in range(int(input())): print(check(input()))
from collections import deque d = deque() dic = {'size':lambda x:print(len(d)), 'empty':lambda x:print(0 if d else 1), 'front':lambda x:print(d[0] if d else -1), 'back':lambda x:print(d[-1] if d else -1), 'push_front':d.appendleft, 'push_back':d.append, 'pop_front':lambda x:print(d.popleft() if ...
N = int(input()) for i in range(1,10): print("{N} * {i} = {Ni}".format(N=N,i=i,Ni=N*i))
from gcd_iter import GCD_iter from functools import reduce def LCM(a, b): """returns the least common multiple (LCM) of two integers a & b""" assert isinstance(a, int) and isinstance(b, int), "Given arguments have to be integer!" assert a > 0 and b > 0, "Both arguments need to be different than...
def fac_iter(n): """returns a factorial (n!) of the natural number n (iterative way)""" assert isinstance(n, int), "The given number has to be integer!" assert n >= 0, "Factorial is defined for natural numbers!" n_factorial = 1 for i in range(1, n+1): n_factorial *= i return...
# Solution for: https://www.hackerrank.com/challenges/string-validators/problem?isFullScreen=true&h_r=next-challenge&h_v=zen&h_r=next-challenge&h_v=zen def has_alphanumeric(string): if(len(string) == 1): return string.isalnum() if(string.isalnum()): return True center = len(string)//2 ...
# =================== # Imports # =================== import pandas as pd import numpy as np import seaborn as sb from seaborn import countplot import matplotlib.pyplot as plt from matplotlib.pyplot import figure,show from sklearn.model_selection import train_test_split from sklearn.linear_model import Logist...
########################################################################### # #Author:Manali Milind Kulkarni #Date:15 June 2021 #About: Wine Predictor using K Nearest Neighbour Algorithm. # ########################################################################### #Required Python Package from sklearn import...
contas = [] depositos= [] saldo = [] while True: def saquei(s): print('voce recebeu seu dinheiro com nota(s)') nota_cem = s // 100 s = s % 100 nota_cinquenta = s // 50 s = s % 50 no...
class Element(object): """ This class defines a dataset element. Attributes: - values (list): Element values. """ def __init__(self, values): self.values = values @property def values(self): """Get or set the element values.""" return self._values @val...
class ProvenanceObject(object): """ This class defines a basic provenance object with a tag and a json representation. Attributes: - tag (str): ProvenanceObject tag. """ def __init__(self, tag): self._tag = tag.lower() def get_specification(self, prefix="_"): """ G...
import random number = random.randint(1, 9) chances = 0 print("❓🧠The Number Guesser - a math riddle based game🎲🧮") print("Welcome to The Number Guesser. Here you will be shown a riddle and solving it will give you a numerical answer. Type that in the space given and pass the test. You have 5 chances to guess...
def read_file(): """ Converts file in list of lines and checks size of field >read_file() >> %lines%, True """ temp = False i = 0 with open("file.txt", "r") as f: lines = f.readlines() if len(lines) > 10: return temp else: while i < 10: ...
numero=input('Digite um número de 3 algarismos:') c=int(numero)/100 if int(c)%2==0: print('O algarimos das centenas é par',c) else: print('O algarismo das centenas é impar',c)
print ('10:00') Min=10 Seg=60 while int(Min)!=9: Min=int(Min)-1 while int(Seg)!=30: Seg=int(Seg)-1 print (Min,':',Seg)
tipo=input('Seleccione o tipo de carro(A/B/C)') percurso=input('Insira o número de Km que deseja efectuar:') if str(tipo)=='C' or str(tipo)=='c': consumo=int(percurso)/12 elif str(tipo)=='B' or str(tipo)=='b': consumo=int(percurso)/10 elif str(tipo)=='A' or str(tipo)=='a': consumo=int(percurso)/8 el...
saldo=input('Introduza o saldo:') nsaldo=float(saldo)*1.01 print('O novo saldo é:',int(nsaldo))
c=input('Introduza o valor em graus centigrados:') f=(9*float(c)+160)/5 print('Graus farenheit= ',int(f))
print('Introduza dois valores') a=input('a:') b=input('b:') quadif=(float(a)-float(b))**2 print('O quadrado da diferença=',int(quadif))
factorial=1 i=1 numero= input('Digite um numero:') while i<(int(numero)+1): factorial=factorial*i i=i+1 print(numero,'!=',factorial)
n=input('Introduza um número: ') j=n i=0 while int(i)<int(n) and int(j)>=1: i=int(i)+1 j=int(j)-1 print(i,j)
preco=input('Digite o valor do produto:') npreco=float(preco)*0.91 print('Preço com desconto:',float(npreco))
num=input('Introduza um número:') soma=0 produto=1 n=1 while int(n)<=int(num): soma=soma+n n=n+1 while int(n)<=int(num): produto=produto*n n=n*1 break print('Soma=',soma,'Produto=',produto)
# # Lists # # Earlier when discussing strings we introduced the concept of a "sequence" in # Python. Lists can be thought of the most general version of a "sequence" in # Python. Unlike strings, they are mutable, meaning the elements inside a list can be changed! # # In this section we will learn about: # # 1.) Cre...
# You are given two integer arrays nums1 and nums2, sorted in non-decreasing order, # and two integers m and n, representing the number of elements in nums1 and nums2 respectively. # # # Merge nums1 and nums2 into a single array sorted in non-decreasing order. # # # The final sorted array should not be returned by the ...
# Given an integer array nums and an integer val, remove all occurrences of val in nums in-place. # The relative order of the elements may be changed. # Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. # More form...
def create(): stack = [] return stack def isEmpty(stack): return len(stack)==0 def push(stack,value): stack.append(value) return stack def pop(stack): if(isEmpty(stack)): return "Empty" stack.pop() if __name__ == "__main__": stack = create(...
import math result1 = 0 result2 = 0 result3 = 0 for a in range (1,101): result1 += a result1 = result1 ** 2 for a in range (1,101): result2 += a ** 2 result3 = result1 - result2 print(result1) print(result2) print(result3)
""" algorithms.py Prime number generation algorithms @author: Dan Batiste """ import random as rand from math import * import time import numpy as np # Prime checker def is_prime(n): """Checks all possible factors up to floor(sqrt(n))""" if n == 2: return True upperbound = sqrt(n)/...
import collections # Named tuples for holding add, change, and remove operations Add = collections.namedtuple('Add', ['path', 'newval']) Change = collections.namedtuple('Change', ['path', 'oldval', 'newval']) Remove = collections.namedtuple('Remove', ['path', 'oldval']) def paths(data, base=None): '''Walk a data ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Python weekend Kiwi.com - Entry task https://gist.github.com/martin-kokos/6ccdeeff45a33bce4849567b0395526c Usage: python find_combinations.py < flights.csv > output.txt cat flights.csv | find_combinations.py """ __author__ = "Jan Kammermayer" __email__ = ...
# Ejercicio 11: # Crear un programa que almacene la cadena de caracteres contraseña en una variable, # pregunte al usuario por la contraseña e imprima por pantalla si la contraseña # introducida por el usuario coincide con la guardada en la variable. password = "calabaza" passwd_pedido = input("Enter your password: "...
# Ejercicio 8: # Crear un programa que pregunte al usuario una cantidad a invertir, el interés anual y el # número de años, y muestre por pantalla el capital obtenido en la inversón. inversion = float(input("Ingrese la cantidad a invertir: ")) interes = float(input("Ingrese el interés anual: ")) anos = int(input("In...
# Ejercicio 19: # Crear un programa en el que se pregunte al usuario por una frase y una letra, y # muestre por pantalla el número de veces que aparece la letra en la frase. frase = input("Ingrese una frase: ") letra = input("Ingrese una letra a buscar: ") def busqueda(): print("La letra", letra, "aparece", f...
from book import Book import json def get_menu(): print('Press 1 to add a new book') print('Press 2 to save books') print('Press 3 to load books') print('Press 4 to find a book') print('Press 5 to issue a book') print('Press 6 to return a book') print('Press 7 to show books') print('Pres...
""" practical week 7 """ from Programming_Language import ProgrammingLanguage ruby = ProgrammingLanguage("Ruby", "Dynamic", True, 1995) python = ProgrammingLanguage("Python", "Dynamic", True, 1991) visual_basic = ProgrammingLanguage("Visual Basic", "Static", False, 1991) print(ruby.is_dynamic()) #...
import nltk,re def f1(h,t): ''' Check if first is capital ''' if (h[2][h[3]].istitle()) and (t == "PERSON" or t == "ORGANIZATION" or t == "GPE"): return 1 else: return 0 def f2(h,t): ''' use dictionary for organization enumeration ''' dic = ["alcatel","amazon","apple","asus","blackberry","byond","cool...
# increase_5 print("Addition of 5 to 3 numbers you enter...") input("If ok, press RETURN ") i = 0 j = 0 k = 0 while i == 0: try: a = int(input("Enter the first number : ")) i += 1 except ValueError: print("It's not a number. Try again ") first = a while j == 0: try: b = int(i...
import math def MaxRectange(lenstr): """ Base on the original string, it will be divided into a rectange with the max column and row """ MAXROW = math.sqrt(lenstr) if MAXROW > int(math.sqrt(lenstr)): MAXCOL = int(math.sqrt(lenstr)) + 1 MAXROW = int(math.sqrt(lenstr)) # p...
#!/usr/bin/python """This is a utility program to help anonymize dates within a dataset. The concept is that the relationships between events in a clinical trial are important, but it creates an opportunity for patient re-identification if correlated with external data that includes dates and times. This tool fin...
def int_num(n_num): x = (int(str(n_num) + str(n_num))) + (int(str(n_num) + str(n_num) + str(n_num))) return x + n_num n_num = int(input("please input something: ")) print(int_num(n_num))
user_input = int(input("items count you want: ")) user_items = [] market_stock = ["item1", "item2", "item3"] available_items = [] for i in range(user_input): it_em = input("enter name: ") user_items.append(it_em) for it_em in user_items: if it_em in market_stock: available_items.append(it_em) print(available_i...
user_name = input("Please enter your name: ") print(user_name) user_age = input("Please enter your age: ") print(user_age) var_age = int(user_age) var_years_old = 100 - var_age var_year = 2020 + var_years_old print("In", var_year, "you will be 100 years old.")
import sqlite3 conn = sqlite3.connect('bank_account.db') c = conn.cursor() c.execute("""CREATE TABLE IF NOT EXISTS bank_account ( name text, social integer, account_number integer PRIMARY KEY, balance integer )""") c.execute("""CREATE TABLE IF NOT EXISTS...
num1 = int(input('Введите первое число: ')) num2 = int(input('Введите второе число: ')) arith_arg = input('Что с ними делать? (+ для сложения, - для вычитания, * для умножения, / для деления, % для выделения целого остатка): ') if arith_arg == '+': final = num1+num2 print('Ответ: '+str(final)) elif arith_...
# 문제 01. 2단 출력 def GuGu(n): result = [] for i in range(9): result.append(n*(i+1)) return result print(GuGu(2)) # 문제 02. 3과 5의 배수 합하기 def sumAll(number): sumi = [] sumj = [] i = number // 3 j = number // 5 for i in range(i): sumi.append(3*(i+1)) for j in range(j): ...
print("hello world") station = ["사당", "신도림", "인천공항"] num=[0,1,2] for i in num: print(station[i]+"행 열차가 들어오고 있습니다.")
import turtle #Define the functino squal #Crate n squares increasing the angle def draw_square(form): i = 1 while i < 5: form.forward(100) form.right(90) i = i +1 def draw_art(): window = turtle.Screen() window.bgcolor("navy") angie = turtle.Turtle() angi...
a = int(input()) fat = 1 for x in range(1,a+1): fat*=x print(fat)
a = 21 b = 10 c = 0 print (a ** c) print (a // b) print (a % b) print (a / b) #Python logical operators print (a and b) print (c and b) print (a or b) print (c or b) print (not(c or b)) i = 2 j = 2 print(i % j) print(i % j == 0) print (not(i % j)) #If Loop var = 100 if ( var == 100 ): print ("变量 var 的值为100") ...
# str = input("Please input a long string: ") # str = "Tina Love Bobby" # new_str = str.split(" ") # output_list = [] # i = len(new_str) -1 # while i >= 0: # output_list.append(new_str[i]) # i -= 1 # a = [0,1,2] # print(output_list) # print(" ".join(output_list[i] for i in a)) def reverse_string(): str...
import csv from collections import Counter with open("data.csv") as f: reader=csv.reader(f) file_data=list(reader) file_data.pop(0) #print(file_data) # sorting data to get the height of people new_data=[] for i in range(len(file_data)): n_num=file_data[i][2] new_data.append(float(n_nu...
#!/usr/bin/env python """ modified from https://github.com/bozhu/RC4-Python """ import binascii class rc4: """ Class for RC4""" def __init__(self): """ The constructor @param self The object """ self.key = 'Key' # default key is 'Key' self.infile = '' ...
"""Class definitions for musical objects""" from lib import defineChord as dc """ Matrix = [measure][voice][Cell] getNotes() composes for Cells, not measure by measure, and not beat by beat for now, the matrix isn't broken into beats, cells are the smallest part, each cell has 1 chord Class Hierarchy Music = key, ma...
"""Converts distance value (0-87, 88=rest) to pitch ('a','cs','ef', etc)""" def distanceToPitch(distance): # if a rest if distance == 88: return 'r' # if not a rest else: distance %= 12 pitchArray = ['a','bf','b','c','cs','d','ef','e','f','fs','g','af'] return pitchArr...
# node colors RED = 'red' BLACK = 'black' class Node(object): def __init__(self, data, parent = None, color = RED): self.color = color self.data = data self.leftChild = None self.rightChild = None self.parent = parent def changeColor(self): if self.color == RED: self.color = BLACK ...
""" Advent of Code 2020 - Day 9 Part 1 - December 16, 2020 """ # initialized variables nums = [] previousNums = [] difference = 0 counter = 0 invalid = 0 # reads text file of input data = open('Raw Data\Day09input.txt', 'r') # stores each line of text file in a list for line in data: nums.append(line[:-1]) # it...
""" Advent of Code 2020 - Day 9 Part 2 - December 16, 2020 """ # initialized variables nums = [] previousNums = [] difference = 0 counter = 0 sum = 0 total = 0 elementsList = [] answer = 0 count = 0 search = True # reads text file of input data = open('Raw Data\Day09input.txt', 'r') # stores each line of text file i...
#Author: SanipRijal #this program fetches the live data from the nepalstockmarket.com.np from bs4 import BeautifulSoup as soup import urllib.request import urllib.parse as uparse from pandas import DataFrame, read_csv import pandas as pd from datetime import datetime import time #define the columns for the pandas Da...
#alphabitical order n=int(input()) l=list(map(str,input().split()))[:n] dic={} for i in range(n): dic[l[i]]=list(map(int,input().split())) for i in sorted(dic.keys()): for j in range(len(dic[i])): print(dic[i][j],end=' ') print('')
#!/usr/bin/python3 import cgi import HTML print("Content-type: text/html\n\n") HTML.getHead("Process") HTML.getHeader() print(""" <div class="container-float"> <div class="row"> <div class="col-xs-12"> <div class="row"> <div class="col-xs-1 col-md-2"> <a...
stringVariable = "hello"; strinSingleQuote = 'Strings can have single quotes'; #print(stringVariable); def myPrintMethod (myParameter): print(myParameter) print('World') myPrintMethod('Puta') def myMultiplyMethod(arg1, arg2): return arg1 * arg2 print(myMultiplyMethod(5, 3)) grades = [5, 10, 25, 30, ...
def printMove(fr, to): print("move from " + str(fr) + " to " + str(to)) def towersn(n, fr, to, spare): if n == 1: return printMove(fr, to) else: towersn(n-1, fr, spare, to) towersn(1, fr, to, spare) towersn(n-1, spare, to, fr) print(str(towersn(3, 2, 1, 3)))
def oweAmount(b0, r, m): return (b0-(b0*m))*(1+(r/12)) total = 0 balance = 4213 annualInterestRate = 0.2 monthlyPaymentRate = 0.04 for month in range(12): print("Month: " + str(month+1)) z = oweAmount(balance, annualInterestRate, monthlyPaymentRate) print("Minimum monthly payment: " + str(round(balance*monthlyPa...
import math def lcm(a, b): return abs(a*b) // math.gcd(a, b) for _ in range(int(input())): s1 = input() s2 = input() l = lcm(len(s1), len(s2)) if s1 * (l // len(s1)) == s2 * (l // len(s2)): print(s1 * (l // len(s1))) else: print(-1)
import math def sum_digits(n): r = 0 while n: r, n = r + n % 10, n // 10 return r for _ in range(int(input())): n = int(input()) while math.gcd(n, sum_digits(n)) <= 1: n += 1 print(n)
print 'enter grade' grade = raw_input() str(grade) marks = {} marks['4+'] = '97' marks['4'] = '90' marks['4-'] = '83' marks['3+'] = '76' marks['3'] = '74' marks['3-'] = '71' marks['2+'] = '68' marks['2'] = '64' marks['2-'] = '61' marks['1+'] = '58' marks['1'] = '54' marks['r'] = '30' marks['1-'] = '51' marks['ne'] = ...
def is_prime(n): if n < 2: return False; if n % 2 == 0: return n == 2 # return False k = 3 while k*k <= n: if n % k == 0: return False k += 2 return True numbers = [] num = 1 while (len(numbers) < 10001): s = str(num) if(is_prime(num) == Tru...
def isEven(n): if(n % 2 == 0): return True else: return False def CollatzSeq(n): CollatzSeq = [] CollatzSeq.append(n) Flag = False while (n != 1): if(isEven(n)): n = n // 2 CollatzSeq.append(n) else: n = (3 * n) + 1 ...
# https://www.interviewbit.com/problems/matrix-median/ # Matrix Median # Given a matrix of integers A of size N x M in which each row is sorted. # Find an return the overall median of the matrix A. # class Solution: # # @param A : list of list of integers # # @return an integer # def findMedian(self, A):...
# https://www.interviewbit.com/problems/repeat-and-missing-number-array/ # Repeat and Missing Number Array # Input:[3 1 2 5 3] Output:[3, 4] A = 3, B = 4 class Solution: # @param A : tuple of integers # @return a list of integers def repeatedNumber(self, arr): repeated =0 missing =0 ...
# https://www.interviewbit.com/problems/all-factors/ # All Factors import math def printDivisors(self,n) : l = [] i = 1 while i <= math.sqrt(n): if (n % i == 0) : if (n / i == i) : l.append(i) else : l.append(i) l.append...
# https://www.interviewbit.com/problems/max-sum-contiguous-subarray/ # Max Sum Contiguous Subarray class Solution: # @param A : list of integers # @return a list of integers def maxset(A): i = 0; maxi = -1; index = 0; a = [] while i < len(A): while i < ...
# https://www.interviewbit.com/problems/set-matrix-zeros/ # Set Matrix Zeros # Input 1: # [ [1, 0, 1], # [1, 1, 1], # [1, 1, 1] ] # Output 1: # [ [0, 0, 0], # [1, 0, 1], # [1, 0, 1] ] # Input 2: # [ [1, 0, 1], # [1, 1, 1], # [1, 0, 1] ] # Out...
# https://www.interviewbit.com/problems/prime-numbers/ # Prime Numbers class Solution: # @param A : integer # @return a list of integers def sieve(self,A): prime = [1] * A prime[0] = 0 prime[1] = 0 for i in range(2,A): if prime[i] == 1: j = 2 ...
# https://www.interviewbitcom/problems/grid-unique-paths/ # Grid Unique Path # Input : A = 2, B = 2 # Output : 2 # 2 possible routes : (0, 0) -> (0, 1) -> (1, 1) # OR : (0, 0) -> (1, 0) -> (1, 1) class Solution: # @param A : integer # @param B : integer # @return an integer def uniqu...
import re def hey(text): word = re.sub('[^a-zA-Z0-9?]+', '', text) if not word: return 'Fine. Be that way!' elif word.isupper(): return 'Whoa, chill out!' elif word.endswith('?'): return 'Sure.' else: return 'Whatever.'
import datetime from calendar import monthrange, day_name def meetup_day(year, month, name, desc): day = next(number for number, day_n in enumerate(day_name, start=1) if day_n == name) description = { 'teenth': 13, '1st': 1, '2nd': 8, '3rd': 15, ...
# import the pygame module, so you can use it import pygame # define a main function def main(): # initialize the pygame module pygame.init() # load and set the logo logo = pygame.image.load("Logo.PNG") pygame.display.set_icon(logo) pygame.display.set_caption("Scott Chang looks for his son")...
#Solving simulataneous equations with 3 unknowns def three_x_three(): print("Type in first equation in format below") a1 = int(input("X coefficient:")) b1 = int(input("Y Coefficient:")) c1 = int(input("Z Coefficient:")) ans1 = int(input("Answer:")) print("Now the second equation") a2 = int...
# coding=utf-8 # 日期:2020-03-12 # 作者:YangZai # 功能:测试employee.py代码 import unittest from employee import Employee # Employee类测试 class TestEmployee(): """针对Employee类测试""" def setUp(self): self.employee_1 = Employee('Guang', 'Chen', 6000) self.salary = 6000 def test_give_default_raise(self): self.employee_1.gi...