text
stringlengths
37
1.41M
# https://leetcode.com/problems/merge-intervals/ class Solution: def merge(self, intervals: List[List[int]]) -> List[List[int]]: l = len(intervals) intervals.sort() # print(intervals) if(intervals == []): return([]) final = [] s...
# Este programa determina si a una persona se le otorga una licencia de conducir o no def main(): edad = int(input("Ingresa tu edad: ")) if edad >= 18: print(' Primera verifivación pasada con éxito ') elif edad <0: print(' Respuesta incorrecta ') else: print(' Licencia deneg...
# f 字符串时 Python 3.6 引入的。 # Python 3.5 或更早的版本没需要使用 format() 方法 first_name = 'ada' last_name = 'lovelace' full_name = f'{first_name} {last_name}' print(full_name) print(f'{first_name.title()} {last_name}') print('{} {}'.format(first_name, last_name))
# 关键字实参是传递给函数的名称值对 # 全都使用关键字实参时,与键值顺序无关 # 混合使用时,位置实参必须放在前面,关键字实参必须放在后面,不可重复,不可穿插 def describe_pat(animal_type, pet_name): """显示宠物的信息""" print(f"\nI have a {animal_type}") print(f"My {animal_type}'s name is {pet_name.title()}") describe_pat(animal_type='hamster', pet_name='harry') # 全都使用关键字实参时,与键值顺序无关 des...
import random money = 100 #Write your game of chance functions here def coin_flip(coin, bet): global money comp = None while coin != 'quit': random_coin_flip = random.randint(1,2) if random_coin_flip == 1: comp = 'heads' else: comp = 'tails' while str(coin) != 'heads' and str(coin)...
n = int(input()) parking = [] for _ in range(n): data = input().split(", ") directions, car_number = data if directions == "IN": parking.append(car_number) elif directions == "OUT": parking.remove(car_number) parking = set(parking) if parking: for el in parking: p...
import numpy as np # Numpy Basic Operations # Convert from list to ndarray numpy_array = np.array([5, 2]) print(numpy_array) # Generating random ndarray # Example 1 rarray = np.random.rand(2,2) # 2x2 array of number from 0 to 1 print(rarray) # Example 2 rarray = np.random.rand(3,2)*15 # 3x2 array of number from 0 to...
# # @lc app=leetcode id=513 lang=python3 # # [513] Find Bottom Left Tree Value # # https://leetcode.com/problems/find-bottom-left-tree-value/description/ # # algorithms # Medium (63.07%) # Total Accepted: 133.5K # Total Submissions: 211.7K # Testcase Example: '[2,1,3]' # # Given the root of a binary tree, return th...
# # @lc app=leetcode id=554 lang=python3 # # [554] Brick Wall # # https://leetcode.com/problems/brick-wall/description/ # # algorithms # Medium (51.70%) # Total Accepted: 88.2K # Total Submissions: 170.6K # Testcase Example: '[[1,2,2,1],[3,1,2],[1,3,2],[2,4],[3,1,2],[1,3,1,1]]' # # There is a rectangular brick wall...
# # @lc app=leetcode id=525 lang=python3 # # [525] Contiguous Array # # https://leetcode.com/problems/contiguous-array/description/ # # algorithms # Medium (43.78%) # Total Accepted: 190.7K # Total Submissions: 434.7K # Testcase Example: '[0,1]' # # Given a binary array nums, return the maximum length of a contiguo...
""" Given s1, s2, s3, find whether s3 is formed by the interleaving of s1 and s2. For example, Given: s1 = "aabcc", s2 = "dbbca", When s3 = "aadbbcbcac", return true. When s3 = "aadbbbaccc", return false. "aabc" "abad" "aabcabad" "cbcccbabbccbbcccbbbcabbbabcababbbbbbaccaccbabbaacbaabbbc" "abcbbcaababccacbaaaccbabaab...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list. You may assume the two numbers do not contain an...
# # @lc app=leetcode id=208 lang=python3 # # [208] Implement Trie (Prefix Tree) # # https://leetcode.com/problems/implement-trie-prefix-tree/description/ # # algorithms # Medium (53.18%) # Total Accepted: 430K # Total Submissions: 803.2K # Testcase Example: '["Trie","insert","search","search","startsWith","insert",...
""" Given n, how many structurally unique BST's (binary search trees) that store values 1...n? For example, Given n = 3, there are a total of 5 unique BST's. 1 3 3 2 1 \ / / / \ \ 3 2 1 1 3 2 / / \ \ 2 1 ...
# # @lc app=leetcode id=712 lang=python3 # # [712] Minimum ASCII Delete Sum for Two Strings # # https://leetcode.com/problems/minimum-ascii-delete-sum-for-two-strings/description/ # # algorithms # Medium (59.81%) # Total Accepted: 48.5K # Total Submissions: 81K # Testcase Example: '"sea"\n"eat"' # # Given two strin...
# # @lc app=leetcode id=697 lang=python3 # # [697] Degree of an Array # # https://leetcode.com/problems/degree-of-an-array/description/ # # algorithms # Easy (54.67%) # Total Accepted: 113.3K # Total Submissions: 207.1K # Testcase Example: '[1,2,2,3,1]' # # Given a non-empty array of non-negative integers nums, the...
# # @lc app=leetcode id=643 lang=python3 # # [643] Maximum Average Subarray I # # https://leetcode.com/problems/maximum-average-subarray-i/description/ # # algorithms # Easy (42.17%) # Total Accepted: 103K # Total Submissions: 243.9K # Testcase Example: '[1,12,-5,-6,50,3]\n4' # # You are given an integer array nums...
""" Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2). Find the minimum element. You may assume no duplicate exists in the array. """ class Solution(object): def findMinHelper(self, nums, start_index, end_index): ...
# # @lc app=leetcode id=695 lang=python3 # # [695] Max Area of Island # # https://leetcode.com/problems/max-area-of-island/description/ # # algorithms # Medium (65.75%) # Total Accepted: 287.2K # Total Submissions: 430.8K # Testcase Example: '[[0,0,1,0,0,0,0,1,0,0,0,0,0],[0,0,0,0,0,0,0,1,1,1,0,0,0],[0,1,1,0,1,0,0,0...
import numpy import cv2 # Create an empty white canvas img = numpy.full((800,800,3), 255, dtype=numpy.uint8) rows, columns, channels = img.shape print(rows, columns, channels) # Intervals for patching hinterval = 100 # height winterval = 100 # width # Switching for changing from black patch to white patch alternate...
#def myFun1(**kwargs): # for key, value in kwargs.items(): # print("%s == %s" % (key, value)) #myFun1(first='Geeks', mid='for', last='Geeks') def myfun2(arg1,arg2,arg3): try: print("arg1:", arg1) print("arg2:", arg2) print("arg3:", arg3) except Exception: return 0 try: arg ...
''' 作者:lg 日期:2019/11/23 文件描述: 缺陷: ''' # 广义上面向对象的封装 :代码的保护,面向对象的思想本身就是一种 # 只让自己的对象能调用自己类中的方法 # 狭义上的封装 —— 面向对象的三大特性之一 # 属性 和 方法都藏起来 不让你看见 class Person(): miyao = 'ABC' # 私有静态属性 def __init__(self, name, sex): self.name = name self.__sex = sex # 私有属性 def get_sex(self): return sel...
''' 作者:lg 日期:2019/10/2 文件描述: 缺陷: ''' # lambda函数的格式: # 函数名 = lambda关键字 参数 : 返回值 add_f = lambda a, b: a + b print(add_f) # 把一般函数用lambda方法写: def add(x, y): return x + y add_func = lambda x, y: x + y # 例题:按照字典的Value值进行排序 # 注意:max方法按照Key的assci码值排序,并且只返回Key值!! dic1 = {'k1': 10, 'k2': 100, 'k3': 30} print(max(dic1))...
# def range2(n): # count =0 # while count < n: # print('count',count) # count += 1 # sign = yield count # print('-------sign',sign) # return 333 # # new_range = range2(3) # n1 = next(new_range) # # print('do sth else') # new_range.send('stop!') #yield关键字的另外一种使用形式:表达式形式的yield...
''' 作者:lg 日期:2019/11/2 文件描述: 缺陷: ''' class Course(): language = 'Chinese' hobbies = ['pingpong'] def __init__(self, teacher, course, period): self.teacher = teacher self.course = course self.period = period def func(self): pass py = Course('egon', 'python', '6 month...
''' 作者:lg 日期:2019/10/13 文件描述:用正则表达式模拟计算器 缺陷: ''' # 去掉所有的空格 # 加减乘除 括号 # 先算括号里的乘除,再算括号里的加减 # 从括号里取值 == 正则表达式 # ss = '9-2*5/3 + 7 /3*99/4*2998 +10 * 568/14' # 从一个没有括号的表达式中取 */法 == 正则表达式 # 总体步骤: # 每次脱去一个括号,计算括号里面的内容,先算乘除再算加减,把结果替换到原来的字符串中,之后,执行一次操作:把'+-'替换成'-','--'替换成'+' import re def replace_symbol(str_num): str...
#很重要 #read一般不能放在循环里,read会一直读取文件内容,读完了就会读取空格 #用int前一定要注意 字符串一定不能为空,不能为字母 #if 和 else要一一对应;第一个if条件满足吼,不再执行后面的elif语句,甚至判断语句都不执行 #while循环里,如果有变量赋值的语句,一定要注意 goods = [ {"name": "电脑", "price": 1999}, {"name": "鼠标", "price": 10}, {"name": "游艇", "price": 20}, {"name": "美女", "price": 998},] flag_buy = 1 # 1:默认读取文件余额直接购买; 0:文件...
''' 作者:lg 日期:2019/10/20 文件描述: 缺陷: ''' import re ret = re.findall('a', 'eva egon yuan a') # 返回所有满足匹配条件的结果,放在列表里 print(ret) # 结果:['a', 'a', 'a'] ret = re.search('a', 'eva egon yuan a').group() print(ret) # 结果:a # 函数会在字符串内查找模式匹配,只到找到第一个匹配然后返回一个包含匹配信息的对象, # 该对象可以通过调用group()方法得到匹配的字符串,如果字符串没有匹配,则返回None。 ret = re.match(...
''' 作者:lg 日期:2019/9/6 文件描述:is 与 == 的区别 缺陷: ''' # is 是的意思 判断两个变量地址是不是一样 # == 判断两个变量的值是不是相等 # 小数据池 # python解释器为了节省内存,给 整形 与 字符串做了优化 # -5 ~ 256 # 字符串中如果有特殊字符,则内存地址不一样 # 字符串中 单个字符 * 20 以内,他们的内存地址一样 # 错误,因为是三个字符 a = 'abc' * 20 b = 'abc' * 20 print(a is b) print('\u4e00')
#对于从文件里读出来的字符串,可以用 strip,split函数操作,变成列表,是序列化的体现 #原因分析:每次k迭代出一行内容,包括换行符,k相当于一个字符串,就具有strip,split方法 with open('用户密码表.txt', 'r') as f: for k in f: print(k.strip().split())
# Find the longest sequence using a starting number under one million. # The following iterative sequence is defined for the set of positive integers: # n n/2 (n is even) # n 3n + 1 (n is odd) # # Using the rule above and starting with 13, we generate the following sequence: # 13 40 20 10 5 16 8 4 2 1 # # I...
# Starting in the top left corner in a 20 by 20 grid, how many routes are there to the bottom right corner? def pascal_triangle(n): t = [1] for _ in range(n): t = [sum(i) for i in zip([0]+t, t+[0])] # zips [0, 1, 2, 1] with [1, 2, 1, 0] to get [(0, 1), (1, 2), (2, 1), (1, 0)] # and then sums to get ne...
# 145 is a curious number, as 1! + 4! + 5! = 1 + 24 + 120 = 145. # Find the sum of all numbers which are equal to the sum of the factorial of their digits. # Note: as 1! = 1 and 2! = 2 are not sums they are not included. from math import factorial def is_sum_of_digits(num): digits_fact = map(factorial, map(int, st...
import random import sys juegadaJugador = sys.argv[1] jugadaMaquina = random.choice['piedra','papel','tijera'] if juegadaJugador == jugadaMaquina: print("empate") else: if juegadaJugador == 'piedra': if jugadaMaquina == 'papel': print ("pierdes") else: print("ganaste"...
import random #Importing random module def star(func): #DECORATORS def body(*args,**kwargs): print("*"*20) func(*args,**kwargs) print("*"*20) return body def per(func)...
import random def intro(): print('Welcome to the random number guessing game created by Vikram Nadathur in Python.') print('Would you like to play? Reply Y/n') ans=input() if ans == 'Y': pass else: print('Have a good day') quit() def params(): #Ask user for parameter...
from Card import Card playerhand=[] dealerhand=[] money=1000 def intro(): ''' Checks whether the user wants to play and what they wish to bet ''' global money print('Do you want to play blackjack?') try: ans = input() ans=ans.strip() ans = ans.upper() except Keyboa...
# Comment with # # A comment is a piece of text in your program that is ignored by the Python interpreter. # Continue Lines with \ alphabet = 'abcdefg' + \ 'hijklmnop' + \ 'qrstuv' + \ 'wxyz' print(alphabet) alphabet = 'abcdefg' + \ 'hijklmnop' + \ 'qrstuv' + \ 'wxyz' print(alphabet) # Compare with if, elif, ...
""" Задание 2. Приведен код, который формирует из введенного числа обратное по порядку входящих в него цифр. Задача решена через рекурсию Сделайте замеры времени выполнения кода с помощью модуля timeit Попробуйте оптимизировать код, чтобы снизить время выполнения Проведите повторные замеры Подсказка: примените мемо...
n = input() div_n = n.replace('',' ').split() if '7' in div_n: print('Yes') else: print('No')
name = input("What is your name: ") age = int(input("How old are you: ")) number = int(input("enter how many time the answer will repeat")) year = str((2014 - age)+100) print(((name + " will be 100 years old in the year " + year ) + "\n") * number)
# def board_graphic(): # i = 0 # grid = [["X", "O", "X"], # [" ", " ", " "], # [" ", " ", " "]] # # h = " ---" * 3 # # # while i < 3: # v = " | " + grid[i][0] + " | " + grid[i][1] + " | " + grid[i][2] + " | " # print(" " + h, end="\n") # print(v, end="\n")...
import random list1 = [random.randint(0, 10) for x in range(1, random.randint(0,9))] print(list1) def sets(l): return set(l) def sets2(l): list2 = [] for x in l: if x not in list2: list2.append(x) return list2 print(sets(list1)) print(sets2(list1))
# O PRINT() ABAIXO DE CADA EXERCICIO SERVE PARA DAR ESPAÇAMENTO DE LINHA NA HORA DE RODAR O PROGRAMA # 33.Faça um Programa que peça os 3 lados de um triângulo. O programa deverá informar se os valores podem ser um triângulo. # Indique, caso os lados formem um triângulo, se o mesmo é: equilátero, isósceles ou escaleno...
# O PRINT() ABAIXO DE CADA EXERCICIO SERVE PARA DAR ESPAÇAMENTO DE LINHA NA HORA DE RODAR O PROGRAMA # 42.Faça um Programa que leia 2 números e em seguida pergunte ao usuário qual operação ele deseja realizar. # O resultado da operação deve ser acompanhado de uma frase que diga se o número é: # par ou ímpar; # posi...
from Operation import Operation class Column: """ A column in the truth table """ def __init__(self, header, operation=None): """ Create a column with the given header, and an operation if the column is operating off another. """ self.operation = operation self.va...
""" https://projecteuler.net/problem=234 For an integer n ≥ 4, we define the lower prime square root of n, denoted by lps(n), as the largest prime ≤ √n and the upper prime square root of n, ups(n), as the smallest prime ≥ √n. So, for example, lps(4) = 2 = ups(4), lps(1000) = 31, ups(1000) = 37. Let us call an integer...
""" Project 7: https://projecteuler.net/problem=7 By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13 We can see that the 6th prime is 13. What is the Nth prime number? """ import itertools import math def prime_check(number: int) -> bool: """Determines whether a given number is prime or not""" ...
#!/usr/bin/python """ Author: OMKAR PATHAK """ class Graph: def __init__(self): self.vertices = {} def printGraph(self): """prints adjacency list representation of graaph""" for i in self.vertices.keys(): print(i, " : ", " -> ".join([str(j) for j in self.vertices[i]])) ...
import sys import csv def main(): # Check for number of arguments if len(sys.argv) != 3: print("Usage: python dna.py data.csv sequence.txt") exit(1) # Init list of STRs and ppl in the database profiles = [] STRs = [] # Read database into memory with open(sys.argv[1], "r")...
from ulinalg import * from umatrix import * import math as m """ This function takes in two vectors (intended to be the accelerometer data and magnetometer data) with three dimensions. It then finds the appropriate rotation matrix to rotate one vector (the accelerometer data) to [0,0,1], such that the entirety ...
print("What is your Name : ") name = input() print(f"Hi there, {name}")
# reponding to the requested problems: import numpy as np import pandas as pd import sys def q1(): # import the data into a panda dataframe: data = pd.read_csv('example_data.csv') predict = [] # preform the loop over all rows and compute abs diff for j in np.arange(250): store = [] #temp arrray to sto...
from tkinter import * import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BCM) GPIO.setup(27,GPIO.OUT) servoX = servoY = p = GPIO.PWM(27,50) p.start(7.5) HEIGHOFSCREEN = 600 WIFTHOFSCREEN = 600 def moveServo(): def convertPWM(x,y): pwmX = 2.5+(x/(WIFTHOFSCREEN/10)) pwmY = 2...
import torch # tensors 4-way calculation: add subtraction multiple and divide # the method with "_" (for example, add_) means in place operation # init a = torch.rand(2, 3) b = torch.rand(2, 3) print('a=', a) print('b=', b) # add print('a + b:') print(a + b) print(a.add(b)) print(torch.add(a, b)) print(a) print(a.ad...
# perceptron.py # --------------- # Licensing Information: You are free to use or extend this projects for # educational purposes provided that (1) you do not distribute or publish # solutions, (2) you retain this notice, and (3) you provide clear # attribution to the University of Illinois at Urbana-Champaign # # Cre...
# if语句 ''' cars = ['bmw','audi','subaru','toyota'] for car in cars: if car == 'bmw': print(car.upper()) else: print(car.title()) car = '籍' print(car=='籍') age1 = 22 age2 = 10 print(age1 > 20 and age2 < 18) numbers = ['1','2','6','6','5','4'] print('3' in numbers) print('3' n...
# 列表 bicycle = ['terk','cannondale','readline','specialized'] print(bicycle) print(bicycle[0].title) print(bicycle[-1]) massage = "My first bicycle was"+bicycle[0]+"." print(massage) names = ['籍','王','段','娄','唐'] print(names) massage = "Hello "+names[0]+"." print(massage) way = ['foot','car','bicycle']...
def print_call(func): def inner(*args, **kwargs): print("calling {0} with {1} {2}".format(func.__name__, args, kwargs)) result = func(*args, **kwargs) print("result was {0}".format(result)) return result return inner @print_call def incr(x): return x + 1 val = incr(4) # ca...
""" By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13. What is the 10 001st prime number? """ def is_prime(n): return not (n < 2 or any(n % x == 0 for x in xrange(2, int(n**0.5) + 1))) def solve_problem(): largest = 0 primes = 0 i = 0 ...
""" 2^15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26. What is the sum of the digits of the number 2^1000? """ def solve_problem(): number = str(2**1000) sum = 0 for x in range(len(number)): sum += int(number[x]) return sum if __name__ == '__main__': print(solve_pro...
#!/usr/bin/python """Solution to the reversebinary problem presented at http://www.spotify.com/se/jobs/tech/reversed-binary/""" __author__ = "Gustaf Hallberg" __copyrights__ = "Copyright 2013, Gustaf Hallberg" __email__ = "ghallberg@gmail.com" import sys def reverse(input, previous = None): if previous == None: ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Sep 4 14:25:52 2019 @author: swilson5 """ import math class Calculator: def __init__(self, data): self.data = data; self.mean = self.__calc_mean() def __calc_mean(self): mean = sum(self.data)/len(self.data) r...
def f(n): ans=0 while(n): ans+=n%10 n//=10 print(ans) a = 2 b = 3 x = 2 for i in range(3,101): if i%3==0: a = x*b + a x+=2 else: a = b + a a^=b b^=a a^=b print(b) f(b)
import math import random def sieve(n): flag = [True]*n flag[0]=flag[1]=False for (i,isprime) in enumerate(flag): if isprime: yield i for j in range(i*i,n,i): flag[j]=False def power(x,y,p): res=1 x = x%p while y>0: if y&1: res ...
#Kullanıcıdan iki tane sayı isteyin ve bu sayıların değerlerini birbirleriyle değiştirin. a = int(input("Lütfen bir sayı giriniz:")) b = int(input("Lütfen bir sayı giriniz:")) print("İlk sayı:" "{}\n" "İkinci Sayı:" "{}\n" .format(a,b)) a,b = b,a print("Sayılar değiştiriliyor...") print("İlk sayı:" "{}\n" "İkinci Sa...
toplam=0 while True: sayı=input("Lütfen bir sayı giriniz: ") if(sayı =='q'): print("Programdan çıkılıyor...") break sayı=int(sayı) toplam+=sayı print("Toplam:",toplam)
def game(): board_arr = [" "]*9 count = 0 while True: create_board(board_arr) pos = input("Player 1 move: ") if count%2 == 0 else input("Player 2 move: ") if not pos.isdigit() or int(pos) > 9 or int(pos) < 1 : print("Please enter a valid value") continue ...
from random import SystemRandom import string def random_string(length): """Return a random string using the system's RNG.""" rng = SystemRandom() return ''.join(rng.choice(string.printable) for i in range(length))
class Binomial(object): def __init__(self, slop=1, y_intercept=0): self.slop = slop self.y_intercept = y_intercept def iter_range(self, start, stop): cur = start while cur < stop: yield (cur, self(cur)) cur += 1 def __str__(self): return "{sl...
# O(n^2) def bubble_sort(ls): for i in range(len(ls)): for j in range(len(ls) - i - 1): if ls[j] > ls[j+1]: ls[j], ls[j+1] = ls[j+1], ls[j] return ls assert bubble_sort([5, 8, 4, 9, 1]) == [1, 4, 5, 8, 9] assert bubble_sort([10, 0, 97, -30, 5]) == [-30, 0, 5, 10, 97] pri...
# https://leetcode.com/problems/copy-list-with-random-pointer/ # two-pass, duplicate list with random pointers as null # build map of nodes Old -> New, use map to populate random pointers on second pass # extra space required for map, size n # better solution: modify original list # interleave new nodes and old nodes...
# https://app.codesignal.com/arcade/intro/level-2/bq2XnSr5kbHqpHGJC # Ratiorg got statues of different sizes as a present from CodeMaster for his birthday, each statue having an non-negative integer size. Since he likes to make things perfect, he wants to arrange them from smallest to largest so that each statue will ...
# https://www.hackerrank.com/challenges/2d-array/problem def hourglassSum(arr): sums = [] n_rows, n_cols = len(arr), len(arr[0]) for row in range(n_rows - 2): for col in range(n_cols - 2): r1, r2, r3 = arr[row], arr[row+1], arr[row+2] c1, c2, c3 = col, col+1, col+2 ...
# Given three strings A, B and C. Write a function that checks whether C is an interleaving of A and B. It may be assumed that there is no common character between A and B (Please see this for an extended solution that handles common characters also), C is said to be interleaving A and B, if it contains all characters ...
# https://www.hackerrank.com/challenges/ctci-array-left-rotation/problem def rotLeft(a, d): return a[d:] + a[:d] # tests test_a = [1, 2, 3, 4, 5] test_d = 4 expected_output = [5, 1, 2, 3, 4] print('Passes:', rotLeft(test_a, test_d) == expected_output)
# https://leetcode.com/problems/intersection-of-two-linked-lists/ # no. 1 # implement k from last function # get last nodes # if last nodes differ, no intersection # else increment k until nodes differ # return last shared node # O(1) space # O(n^2) time # no. 2 # use hash set to store each node in list A # iterate o...
# https://leetcode.com/problems/spiral-matrix/ from typing import List class Solution: def spiralOrder(self, matrix: List[List[int]]) -> List[int]: # O(n) time/space, n = count of elements in matrix spiral = [] if not matrix: return spiral top = left = 0 bott...
def reverse(head): previous = None current = head following = head while current != None: following = following.next current.next = previous previous = current current = following return previous
# Matrix Spiral Copy # Given a 2D array(matrix) `inputMatrix` of integers, create a function # `spiralCopy` that copies `inputMatrix`’s values into a 1D array in a clockwise # spiral order. Your function then should return that array. inputMatrix = [ [1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15]...
import math def isPrime(number): boundary = math.floor(math.sqrt(number)) for i in range(2, boundary+1): if number % i == 0: return False return number >= 2 def isPrime2(number): # here we avoid using any external functions # i * i <= number equivalent to i <= sqrt(num) ...
def conditinals(n): w = 'Weird' nw = 'Not Weird' is_even = n % 2 == 0 if not is_even: print('1') return w if (2 <= n and n <= 5): print('2') return nw if (6 <= n and n <= 20): print('3') return w if n > 20: print('4') return nw ...
# https://leetcode.com/problems/count-primes/ # count all prime numbers less than n # need a function to determine if a number is prime class Solution: def countPrimes(self, n: int) -> int: # too slow for large inputs def is_prime(num): i = 2 while i * i <= num: ...
# https://leetcode.com/problems/count-and-say/ def count_vals(say_str): result = '' val = say_str[0] freq = 1 for i in range(1, len(say_str)): curr = say_str[i] if curr == val: freq += 1 else: result += f'{freq}{val}' val = curr f...
import random class QuickSort(object): @classmethod def partition(cls, arr, low, high): i, j = low + 1, high while True: while arr[i] < arr[low]: i += 1 if i >= high: break ...
from animals.animal import Animal class Cat(Animal): pass def make_sound(self): return "Meow meow!" class Kitten(Cat): def __init__(self, name, age): super(Kitten, self).__init__(name, age, "Female") def make_sound(self): return "Meow" class Tomcat(Cat): ...
def check_if_prime(num): factor = 2 if num > 1: while factor < num: if num % factor == 0: return False factor += 1 return True def get_primes(list_given): list_of_all_primes = [el for el in list_given if check_if_prime(el)] index = 0 ...
class Student: def __init__(self, name, age): self.name = name self.age = age Kiro = Student("Kiroo", 22) print(Kiro.age)
#guess syllables of gibberish i.e. "da dadum dum dum dee do" "shoobee doowah" "boo boo kachu" import sys def gib_syls(aWord): n = 3 sylz = 0 characters = list(aWord) #test first letter if not_a_vowel(characters[0]): sylz = 0 else: sylz = 1 #test ngrams for c in range(len(characters) - n+1): gram = tup...
import math # Complete the solve function below. def solve(n): a = 5*n*n + 4 b = 5*n*n - 4 testA = math.sqrt(a) testB = math.sqrt(b) if testA == math.ceil(testA) or testB == math.ceil(testB): return "IsFibo" elif testA == math.floor(testA) or testB == math.floor(testB)...
import math import os import random import re import sys # # Complete the 'diagonalDifference' function below. # # The function is expected to return an INTEGER. # The function accepts 2D_INTEGER_ARRAY arr as parameter. # def diagonalDifference(arr): # Write your code here sum = 0 for ...
#!/bin/python3 import math import os import random import re import sys # Complete the jumpingOnClouds function below. def jumpingOnClouds(c): s1 = "".join([str(elem) for elem in c]) x = s1.split('1') jumps = len(x) for i in range(len(x)): jumps += math.floor(len(x[i])/2) ...
import math # Complete the counterGame function below. def counterGame(n): count = 0 while n != 1: test = n != 0 and ((n & (n - 1)) == 0) if test == 1: n = math.floor(n/2) print(n) else: n = n - 2**math.floor(math.log2(n)) ...
import math import os import random import re import sys # Complete the findDigits function below. def findDigits(n): temp = n count = 0 while temp > 0: d = temp % 10 if d > 0 and n % d == 0: count += 1 temp = (temp - d) / 10 return count ...
import sys from typing import List from time import time def binary_search_contains(sorted_entries: List[int], begin_index: int, end_index: int, target_int: int) -> bool: if begin_index == end_index: return sorted_entries[begin_index] == target_int elif begin_index > end_index: return False ...
import sys from typing import List def get_row_of_seat(seat: str): row = 0 for i in range(0, 7): if seat[i] == 'B': row += 2 ** (6 - i) return row def get_column_of_seat(seat: str): column = 0 for i in range(7, 10): if seat[i] == 'R': column += 2 ** (9 - i...
#Binary Search #array -not ordered def seq_search(arr,ele): pos = 0 found = False while pos < len(arr) and not found: if arr[pos] == ele: found = True else: pos +=1 return found #array ordered; We can stop searching when the ele...
def check_connection(friends,p1,p2): for conn in friends: pair = conn.split('-') other = '' if p1 == pair[0] : other = pair[1] if p1 == pair[1] : other = pair[0] if other != '': if p2 == other : return True else : return check_connection(friends, other, ...
# 插入排序 # 最优时间复杂度:O(n) # 最坏时间复杂度:O(n^2) # 稳定性:稳定 def insert_sort(alist): n = len(alist) for i in range(1,n): for j in range(i,0,-1): if alist[j] < alist[j-1]: alist[j],alist[j-1] = alist[j-1],alist[j] else: break alist1 = [54,26,93,17,...
class Dqueue(): '''双端队列''' def __init__(self): self._list = [] def add_front(self, item): '''从头部添加一个item元素''' self._list.insert(0,item) def add_rear(self,item): '''从尾部添加一个元素''' self._list.append(item) def pop_front(self): '''从头部弹出元素'...