text
stringlengths
37
1.41M
N=int(input('Введите сколько прошло секунд с начала суток: ')) x = N % 3600 x = N // 60 if N > 3600: x = x % 60 print('Количество полных минут, прошедших с начала последнего часа: ',x)
from math import* x = float(input('Введите число: ')) if x >= 0.2 and x <= 0.9 : f = sin(x) else: f = 1 print (round(f,3))
def Quatro (a,b,c): Quat = (a+b+c)/3 return Quat a,b,c = map(int,input('Введите три числа:').split()) print (Quatro (a,b,c))
import random # THE PLANNING PHASE # Dealer cards dealer_cards = [] # Player cards player_cards = [] # Deal the cards # Display the cards # Dealer Cards while len(dealer_cards) != 2: dealer_cards.append(random.randint(1, 11)) if len(dealer_cards) == 2: print("Dealer has X &", dealer_cards[1]) # P...
# This is Exercise 6 : Strings and Text # Variable including how many type of people with sentence. x = "There are %d types of people." % 10 # Store strings in Variable binary = "binary" # Again store strings in variable. do_not = "don't" # Store a sentence with above two variables in variable. y = "Those who know ...
# this is exercise 33: while loop i = 0 # a variable storing "0" numbers = [] # a variable storing empty arrays # while runt till 6 while i < 6: print "At the top i is %d" % i numbers.append(i) i = i + 1 print "Numbers now: ", numbers print "At the bottom i is %d" % i print "The numbers: " for num in number...
# This is Exercise 15: Reading Files # Import sys modules and argv is an argument variable # which holds arguments that you pass on Pyhton script from sys import argv # Unpacking and assing value to variables script, filename = argv # A variable storing function to open file. txt = open(filename) # Printing a sente...
# This is Exercise 18 : Names, Variables, Code, Funcions # this one is like your script with argv def print_two(*args): # two argv is equal to one argv arg1, arg2 = args # print both argv print "arg1: %r, arg2: %r" % (arg1, arg2) # ok, that *args is actually pointless, we can to this def print_two_again(arg1, arg...
import sys import numpy import math chartext=list(input('Entr the text to be encrypted:')) #only capital letters. No spaces print('the text entered is:',chartext) asciitext=[] for d in range(len(chartext)): asciitext.append(ord(chartext[d])) asciitext=numpy.asarray(asciitext) asciitext=asciitext-65 print('the numeric ...
def make_matrix(A, matrix): dummy_matrix = [[0 for _ in range(N)] for _ in range(N)] for i in range(N): for j in range(N): for k in range(N): dummy_matrix[i][j] += (matrix[i][k] * A[k][j]) dummy_matrix[i][j] %= 1000 return dummy_matrix def matmul(A, B): ...
import sys sys.stdin = open('input.txt') n = int(input()) dic = dict() for i in range(n): a,b = map(str, input().split()) if b == "leave": dic[a] = False else: dic[a] = True dic = sorted(dic.items(),key = lambda x:x[0],reverse = True) for name, check in dic: if check: print(name...
import sys sys.stdin = open('input.txt') a = int(input()) operate = input() b = int(input()) if(operate == '+'): print(a+b) elif(operate == '*'): print(a*b)
a = int(input()) result = 0 for i in range(1, a+1): result = result + i print(result)
#coding:utf-8 #图形的缩放 import cv2 as cv import numpy as np img = cv.imread("D:/python_file/Opencv3_study_file/images/!face.png") height,width = img.shape[:2] res1 = cv.resize(img, (int(width/2), int(height/2)), interpolation=cv.INTER_CUBIC) res2 = cv.resize(img,(2*width,2*height),interpolation = cv.INTER_CUBIC) cv.i...
from collections import OrderedDict class CircularOrderedDict: def __init__(self, maxsize): """A dictionary that never exceeds a given size. If the size limit is reached, the least recently inserted element is removed. Args: maxsize (int): Maximum size of the dictionary. ...
from random import randint print('--- LOTTO simulator ---') print('-- Pick 6 numbers in range of 1-49 --') lotto_numbers = [] for _ in range(6): n = randint(1, 49) if n in lotto_numbers: n = randint(1, 49) lotto_numbers.append(n) converting = True while converting: try: player_numbers...
# Listelerin eleman sayısına ulaşmak için İngilizce uzunluk anlamına gelen # length kelimesinin kısaltması olan len() fonksiyonu kullanılır sayi=[20, 40, 60, 80] print(len(sayi)) print('{0} adet sayı vardır'.format(len(sayi))) listem=[5,9,10,"altan",82.5] print(len(listem)) # eleman sayısının 1 eksiği...
# maaş zam hesaplama yeniMaas=0 maas=float(input("Maaşı Gir : ")) zam=float(input("Zam Oranı(%) : ")) zamoranı=maas*(zam/100) yeniMaas=maas+zamoranı print("Zamlı Maaş :",yeniMaas)
a=6 b=4 print("karşılaştırma operatörleri:eşit değil mi?") print (a!=b) # true döner # Programlama dilinde gerçekleştirilen karşılaştırmalar # doğru ise True yanlış ise False değerlerini döndürür.
sayi1=input("Birinci sayı:") sayi2=input("İkinci sayı:") toplam=sayi1+sayi2 print(toplam) # ekrana sayıları bitişik yazar çünkü int kullanmadık!!! #doğrusu x=int(input("Birinci sayı:")) y=int(input("İkinci sayı:")) toplam2=x+y print(toplam2)
""" C6H12O6 formülü şekerin formülüdür. Buna göre ; C=12.01 H=1.00 O=15.99 şekerin mole kütlesini hesapla """ C=12.01 H=1.00 O=15.99 molkutlesi=C*6+H*12+O*6 print("C6H12O6 formülünün mol kütlesi {0} dır".format(molkutlesi)) # diğer örnek """ suyun fomülü H2O dur. H=1.00 O=15.99 olduğuna göre molekül...
# Listeden belli bir aralık almak # liste[başlangıç indeksi:bitiş indeksi] yapısı kullanılır asal_sayilar=[2, 3, 5, 7, 11, 13, 17, 19, 23] print(asal_sayilar[0:3]) # [2, 3, 5] print(asal_sayilar[1:4]) ''' indeksi 1 olan elemandan başlayarak indeksi 4 olan elemana (4 dâhil değil) kadar ekrana yazdırır. Dol...
negatifSay = 0 pozitifSay = 0 while True: x = int(input("bir sayı gir: ")) if x ==0: break if x<0: negatifSay = negatifSay + 1 else: pozitifSay = pozitifSay + 1 print("Toplam negatif sayı:",negatifSay) print("Toplam pozitif sayı:",pozitifSay)
#sayılar #aşağıdaki komutları terminalde deneyiniz >>> 23 23 >>> 4567 4567 #type komutu >>> type(2.3) <class 'float'> >>> type("altan") <class 'str'> >>> type(23) <class 'int'> >>> type('karaalp') <class 'str'> >>> type(10+2j) <class 'complex'> >>> # yukarıdakiler birer tamsayıdır. İngilizcede ...
#!usr.bin/python3 # Accepts a .csv file (or list of tiles) and does the following: # - Adds column TITLE_NAME, which contains organizations' names # in title case with special cases addressed (special cases # are outlined in function documentation and are easily edited) # - Writes new dataframe back to .csv of sa...
class Dog: role = "dog" def __init__(self, name, breed, attack_val): self.name = name self.breed = breed self.attack_val = attack_val self.life_val = 100 def bite(self, person): person.life_val -= int(self.attack_val) print("狗[%s]咬了人[%s],人掉血[%s], 还剩血量[%s]。。"...
name = "小猿圈" def change(): name = "小猿圈,自学编程" def change2(): name = "小猿圈,自学编程不要钱" print("第3层打印", name) change2() print("第2层打印", name) change() print("第1层打印", name) print("----------------") res = map(lambda x: x ** 2, [1, 5, 7, 4, 8]) # 匿名函数,省去指定函数名的过程 for i in res: print(i) p...
# 爬取肯德基餐厅查询http://www.kfc.com.cn/kfccda/index.aspx中指定地点的餐厅数据 import requests if __name__ == "__main__": url = 'http://www.kfc.com.cn/kfccda/ashx/GetStoreList.ashx?op=keyword' headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.18...
class Dog: def __init__(self, name, breed, attack_val): self.name = name self.breed = breed self.attack_val = attack_val self.life_val = int(100) def bite(self, person): person.life_val -= self.attack_val print("狗[%s]咬了人[%s],人掉血[%s],还剩血量[%s]..." % (self.name, pe...
# 开启新线程开销远远小于开启新进程 from multiprocessing import Process def work(): print('hallo') if __name__ == '__main__': # 在主进程下开启子进程 p = Process(target=work) p.start() print('主进程') # # from threading import Thread # # # def work(): # print('hallo') # # # if __name__ == '__main__': # t = Thread(tar...
# 写一个程序,要求用户输入用户名和密码,要求密码长度不少于6个字符,且必须以字母开头, # 如果密码合法,则将该密码使用md5算法加密后的十六进制概要值存入名为password.txt的文件,超过三次不合法则退出程序 def start(): count = 3 while count > 0: name = input(">>").strip() pwd = input(">>").strip() if len(pwd) >= 6 and pwd[0].isalpha(): pwd_md5 = hashlib.md5(pwd.encode("...
import math def area(item, *args): def roundness(R): dimension = math.pi * (R ** 2) return dimension def square(A): dimension = A ** 2 return dimension def rectangle(L, W): dimension = L * W return dimension if item == "圆形": print(roundness(*a...
# 写一个程序,包含十个线程,子线程必须等待主线程sleep 10秒钟之后才执行,并打印当前时间 from threading import Thread, Event, currentThread import time, datetime def task(): print(f"{currentThread().getName()}等待") event.wait() print(f"{currentThread().getName()}, {datetime.datetime.now()} is running") if __name__ == "__main__": event = Ev...
# 逗号分隔值(Comma-Separated Values,CSV # 有时也称为字符分隔值,因为分隔字符也可以不是逗号) # 其文件以纯文本形式存储表格数据(数字和文本) import csv # f = open("ex4") # reader = csv.reader(f) # for line in reader: # print(line) # csv模块读取csv文件 with open("ex4") as f: lines = list(csv.reader(f)) # 变成字典 header, values = lines[0], lines[1:] # 第一行变成列名 data_dict ...
from tkinter import * from tkinter import ttk import os version = "v2.1" Birthday_book = dict() date_list = list() def clear(): input_date.delete(0, END) input_last_name.delete(0, END) input_first_name.delete(0, END) input_patronymic.delete(0, END) def add(): date = input_date.get() if dat...
from datetime import datetime import ast class Restaurant: """ Authors: Dean, Tony and Hashir. Class defining Restaurant object. Holds all relevant information. Attributes: name - string - name of restaurant address - string - street address of restaurant coordinates - tuple c...
''' Effort to make this look similar to OSX calculator with equation string shown ''' from tkinter import * from tkinter import font class App(): def __init__(self, master): button_color = "gray27" operator_color = "dark orange" self.current_string = StringVar() self.current_strin...
#!/usr/bin/env python3 """ Author : lia Date : 2020-02-17 Purpose: Accept input text from the command line or a file Change strings to uppercase Print output to command line or a file to be created Make plain text behave like a file handle """ import argparse import os import sys...
#!/usr/bin/python3 # coding=utf-8 import sqlite3 # 连接 # 表 # 录入学生信息 # 选课 # 查询学生信息 # 按学生查询选课 # 按课程查询课程信息 # 查询选择课程的学生列表 class Student: def __init__(self): pass def dbaccess(self): connect = sqlite3.connect('studb.sqlite', timeout=3) return connect def createdb(self): sql =...
import math def binary_search(seq, target): low = 0 high = len(seq) - 1 while low <= high: mid = low + (high - low) / 2 mid = int(math.floor(mid)) if (seq[mid] == target): return mid elif (seq[mid] < target): low = mid + 1 else: high = mid - 1 A = [1, 3, 5, 7, 9, 11, 13, 1...
#coding=utf-8 ''' Created on 2016年3月10日 @author: makao ''' class User_Relation(object): ''' aapr | Marco Mike John Lily ''' def __init__(self,name): ''' Constructor ''' self.name=name self.follower=[] def setFollower(self,follower): self.fo...
# -*- coding: utf-8 -*- """ Created on Mon Jul 12 21:10:55 2021 @author: ssing """ #count numbers = (1, 8, 7, 8, 7, 5, 4, 6, 8, 5, 9) cnt1 = numbers.count(5) cnt2 = numbers.count(8) cnt3 = numbers.count(7) print(cnt1) print(cnt2) print(cnt3) #index x = numbers.index(9) print(x)
import pyttsx3 #text to speech import datetime #for using datetime functions import speech_recognition as sr #speech to text import wikipedia #for using wikipedia import webbrowser #for using webbrowser import os # for using os releated calls engine = pyttsx3.init("sapi5")#pyttsx3.init([driverName : string, de...
b_amt = int(input("Enter the bill amt:\n")) q = input("Do you have a membership?\n") if q == "Y": dis = b_amt * 0.1 n_amt = b_amt - dis print(f"Thank You! Your total bill amount is Rs{b_amt}, discount is Rs{dis} and net amount payable is Rs{n_amt}") elif q == "N": dis = b_amt * 0.03 n_amt = ...
#!/usr/bin/python # -- encoding: utf-8 -- if not "raw_input" in dir(__builtins__): raw_input = input def blocoToValue(b): if not len(b): return [] r = [] for k in range(max(b.keys())+1): if k in b.keys(): r.append(int(b[k])) else: r.append(3) return r ''' A simplificação de função boo...
n = input("введите 8 цифр о 0 до 9") n = list(n) a = (int(n[0]) + int(n[1]) + int(n[2]) + int(n[3])) b = (int(n[4]) + int(n[5]) + int(n[6]) + int(n[7])) if a == b: print("lucky") else: print("no lucky") print(n) print(a) print(b)
def rom_arab(roman): numeric = {"I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000} arabic = 0 for d in range(len(roman)): try: if numeric[roman[d]] < numeric[roman[d + 1]]: arabic -= numeric[roman[d]] else: arabic += numeric[roman...
# -*- coding: utf-8 -*- #Problem 1 : Write a Python program to convert degree to radian pi=22/7 degree = float(input("Input degrees: ")) radian = degree*(pi/180) print(radian) #Problem 2 : Write a Python program to calculate the area of a trapezoid base_1 = 5 base_2 = 6 height = float(input("Height of trapezoid: ")) b...
"""Abstraction.""" from enum import Enum class Strategy: """ Given a time series, a strategy is a way of deciding whether or not we need to start panicking. """ def __init__(self, source): self.source = source def run(self): """Run the strategy and return the decision (Strate...
# import dependencies from src.CardStack import CardStack class CardSequence(CardStack): """ A class that represents the face-up sequence of cards at the top of a Tableau. Primarily used to transfer cards to-and-between tableaus. Data definition is as follows: - A CardSequence is a card, attac...
number_first = int(input("Введите первое число: ")) number_second = int(input("Введите второе число: ")) number_third = int(input("Введите третье число: ")) def my_func(*args): my_list = list(args) my_list.sort() if len(my_list) > 2: print(my_list[-2] + my_list[-1]) my_func(number_first, number_...
# Personal Project by Bailey Schena # Calculator # Taking in a number print("Please enter the first number") numberOneInput = input("") numberOne = int(numberTwoInput) # Taking in a second number print("Please enter the second number") numberTwoInput = input("") numberTwo = int(numberTwoInput) # Choosing the operati...
# -*- coding: utf-8 -*- """ @author: Nellman1508 """ import numpy as np def bubble_sort(x): """Implementation of Bubble sort. Takes integer list as input, returns sorted list.""" print("Starting Bubble sort on following list:\n", x) loop = 0 unsorted = True while(unsorted): loop ...
from numpy import array from keras.models import Sequential from keras.layers import Dense, LSTM import numpy as np #1. 데이터 x = array([[1,2,3], [2,3,4], [3,4,5], [4,5,6], [5,6,7], [6,7,8], [7,8,9], [8,9,10], [9,10,11], [10,11,12], [20,30,40], [30,40,50], [40,50,60]]) y = array([4,5,6,7,8,9,10,11,12,13,50,60,70]...
# 第七章 # 1.自定义一个序列,该序列按顺序包含52张扑克牌,分别是黑桃,红心,草花,方块的2-A。要求:提供序列的各种操做方法 ''' 序列相关的方法 __len__(self) __getitem__(self, key) __contains__(self, item) 可直接用in __setitem__(self,item) __delitem__(self, key) ''' ''' def check_key(key): if not isinstance(key, int):raise TypeError("索引值必须是整数") if key < 0: raise IndexError("索引值...
""" 这是geomotry模块的文档说明 1.开始 2.结束 """ def print_triangle(n): """ 这是print_triangle(n)函数的文档说明 在控制台用星号打印三角形 """ print("这是三角形,参数:", n) def print_diamand(n): """ 这是print_diamand(n)函数的文档说明 在控制台用星号打印菱形 """ print("这是菱形,参数:", n)
#CTI-110 #M2HW1 - Distance Traveled #Jenaya Curry #17 September 2017 #This program calculates the distance traveled based on speed and time variables. SPEED = 70 distance6hours = SPEED * 6 distance10hours = SPEED * 10 distance15hours = SPEED * 15 print ('The car will travel', distance6hours,'miles in 6 hou...
#CTI 110 #M5HW2 - Running Total #Jenaya Curry #16 October 2017 #Takes user input of grades, calculates the average, and displays a letter grade. def main (): total = 0 numberInput = float(input('Enter a number? ')) while numberInput > -1: total = total + numberInput numberInput...
#This file was used to practice various methods to aggregate CSV data to list, dictionairies, etc... import csv with open('budget_data_1.csv', mode = 'r') as infile: reader=csv.reader(infile) with open('newbudget_data_1.csv', mode = 'w') as outfile: writer = csv.writer(outfile) mydict ...
from microbit import * # standard Micro:Bit libraries from array import * # to use an array import random # generate random numbers count = 0 # initialise counter to 0 wait = 500 # initialise wait ...
import random import sys def choiceFirstPlayer(): randomChoice = random.randint(0, 1) if randomChoice == 0: print('You begins first') else: print('Computer begins first') print() return randomChoice def showBoard(currentBoard): row3 = ' ' + currentBoard[6] + ' | ' + currentB...
class Solution: def maxDistToClosest(self, seats: list[int]) -> int: l, r, ans = -1, 0, 0 for r in range(0, len(seats)): if seats[r] == 1: if l < 0: ans = max(ans, r) else: ans = max(ans, (r - l) // 2) ...
from typing import List class Solution: def totalNQueens(self, n: int) -> int: ans = 0 def dfs(queens: List[int], xydiff: List[int], xysum: List[int]) -> None: """ queens: column index of placed queens from row [0, n) xydiff: coordinate diffs have been occupied...
from typing import List class Solution: def threeEqualParts(self, arr: List[int]) -> List[int]: N, n_of_ones = len(arr), sum(arr) # check for corner cases if n_of_ones == 0: return [0, N - 1] if n_of_ones % 3 != 0: return [-1, -1] # Find the beginnin...
class Solution: def detectCapitalUse(self, word: str) -> bool: if len(word) <= 1: return True if word[0].isupper(): return word[1:].isupper() or word[1:].islower() else: return word[1:].islower() def detectCapitalUseV1(self, word: str) -> bool: ...
from typing import List class Solution: def setZeroes(self, matrix: List[List[int]]) -> None: """ Do not return anything, modify matrix in-place instead. """ # cell[0][0] is used twice for row and col flags, we need an extra flag # to indicate if col 0 should be set zeroes ...
from typing import List class Solution: def numSubarrayProductLessThanK(self, nums: List[int], k: int) -> int: if k <= 0: return 0 l, r, prod, ans = 0, 0, 1, 0 while r < len(nums): prod *= nums[r] while l <= r and prod >= k: prod /= nums[...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right from typing import Tuple from local_packages.binary_tree import TreeNode class Solution: def subtreeWithAllDeepest(self, r...
import string class Solution: def ladderLength( self, beginWord: str, endWord: str, wordList: list[str] ) -> int: wordset = set(wordList) if not endWord in wordset: return 0 queue = [(endWord, 1)] wordset.remove(endWord) while queue: w, d...
from typing import List class Solution: def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]: ans = [] for p in sorted(people, key=lambda hk: (-hk[0], hk[1])): ans.insert(p[1], p) return ans # TESTS for people, expected in [ ([], []), ([[7, 0]], [[7,...
class Solution: def partition(self, s: str) -> list[list[str]]: ans = [] def dfs(s: str, path: list[str]) -> None: if not s: ans.append(path[:]) else: for i in range(1, len(s) + 1): if s[:i] == s[:i][::-1]: ...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right from typing import List from local_packages.binary_tree import TreeNode class Solution: def buildTree(self, inorder: List[...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right from local_packages.binary_tree import TreeNode from typing import Optional class Solution: def isCompleteTree(self, root:...
from typing import List class Solution: def pancakeSort(self, A: List[int]) -> List[int]: N, ans = len(A), [] for n in range(N, 1, -1): k = A.index(n) if k < n - 1: # not already sorted ans.extend([k + 1, n]) A = A[:k:-1] + A[:k] return ...
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None from local_packages.list import ListNode class Solution: def hasCycle(self, head: ListNode) -> bool: slow, fast = head, head while fast and fast.next: s...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right from local_packages.binary_tree import TreeNode from typing import Optional class Solution: def tree2str(self, root: Optio...
from collections import defaultdict class Trie: def __init__(self): """ Initialize your data structure here. """ self.links = defaultdict(Trie) self.is_end = False def insert(self, word: str) -> None: """ Inserts a word into the trie. """ ...
class MapSumV1: def __init__(self): """ Initialize your data structure here. """ self.d = dict() def insert(self, key: str, val: int) -> None: self.d[key] = val def sum(self, prefix: str) -> int: return sum(self.d[key] for key in self.d if key.startswith(pre...
from typing import List class Solution: def validateStackSequencesV1(self, pushed: List[int], popped: List[int]) -> bool: stack, i, j, n = [], 0, 0, len(pushed) while j < n: if len(stack) == 0 or stack[-1] != popped[j]: if i == n: return False ...
from cmath import exp from collections import Counter from curses.ascii import SO class Solution: def isAnagram(self, s: str, t: str) -> bool: return Counter(s) == Counter(t) for s, t, expected in [ ["rat", "cat", False], ["eat", "tea", True], ["anagram", "nagaram", True], ["成功", "功成", T...
from typing import Tuple class Solution: def complexNumberMultiply(self, num1: str, num2: str) -> str: parse = lambda num: map(int, num[:-1].split("+", 1)) r1, i1 = parse(num1) r2, i2 = parse(num2) return f"{r1 * r2 - i1 * i2}+{r1 * i2 + r2 * i1}i" # TESTS for num1, num2, expecte...
class Solution: def makeGood(self, s: str) -> str: stack = [] for c in s: if stack and stack[-1] == c.swapcase(): stack.pop() else: stack.append(c) return "".join(stack) # TESTS for s, expected in [ ("leEeetcode", "leetcode"), ...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right from local_packages.binary_tree import TreeNode class Solution: def insertIntoBST(self, root: TreeNode, val: int) -> TreeN...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None from local_packages.binary_tree import TreeNode class Solution: def getTargetCopyV1( self, original: TreeNode, cloned: TreeNode, target: TreeNod...
from typing import List from random import random import math class Solution: def __init__(self, radius: float, x_center: float, y_center: float): self.rad = radius self.x, self.y = x_center, y_center def randPoint(self) -> List[float]: rad = self.rad * math.sqrt(random()) the...
from typing import List class Solution: def canVisitAllRooms(self, rooms: List[List[int]]) -> bool: visited = {0} def dfs(i: int) -> None: for k in rooms[i]: if k not in visited: visited.add(k) dfs(k) dfs(0) retu...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right from local_packages.binary_tree import TreeNode from typing import Optional from collections import defaultdict class Solution...
from typing import List class Solution: def getRow(self, rowIndex: int) -> List[int]: row = [1] while rowIndex > 0: row = [0] + row for i in range(len(row) - 1): row[i] += row[i + 1] rowIndex -= 1 return row # TESTS tests = [ (0, [1...
from typing import List from collections import defaultdict class Solution: def leastBricks(self, wall: List[List[int]]) -> int: edge_count, max_count = defaultdict(int), 0 for row in wall: s = 0 for brick in row[0:-1]: s += brick edge_count[...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None from local_packages.binary_tree import TreeNode from collections import defaultdict class Solution: def distanceK(self, root: TreeNode, target: TreeNode...
from typing import List from collections import defaultdict class Solution: def diagonalSort(self, mat: List[List[int]]) -> List[List[int]]: ans = [[0 for _ in r] for r in mat] m, n = len(mat), len(mat[0]) diag = defaultdict(list) for i in range(m): for j in range(n): ...
from math import sqrt class Solution: def countPrimes(self, n: int) -> int: if n < 2: return 0 is_prime = [0, 0] + [1] * (n - 2) for i in range(2, int(n ** 0.5) + 1): if is_prime[i]: is_prime[i * i : n : i] = [0] * len(is_prime[i * i : n : i]) ...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right from typing import List, Optional from collections import defaultdict from local_packages.binary_tree import TreeNode class So...
class Solution: def simplifyPath(self, path: str) -> str: stack = [] for token in path.split("/"): if token == "." or token == "": continue elif token == "..": if stack: stack.pop() else: stack.ap...
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None from local_packages.list import ListNode class Solution: def detectCycle(self, head: ListNode) -> ListNode: slow = fast = entry = head while fast and fast.next: ...
from functools import reduce class Solution: def backspaceCompare(self, s: str, t: str) -> bool: func = lambda res, c: res[:-1] if c == "#" else res + [c] return reduce(func, s, []) == reduce(func, t, []) # TESTS for s, t, expected in [ ("ab#c", "ad#c", True), ("ab##", "c#d#", True), ...
class Solution: def hammingDistanceV1(self, x: int, y: int) -> int: ans, xor = 0, x ^ y while xor: ans += 1 if xor & 1 else 0 xor >>= 1 return ans def hammingDistanceV2(self, x: int, y: int) -> int: ans, xor = 0, x ^ y while xor: ans +...
from typing import List class Solution: def searchRange(self, nums: List[int], target: int) -> List[int]: def binarySearch(l: int, r: int, first: bool) -> int: nonlocal target while l <= r: mid = l + (r - l) // 2 if nums[mid] < target: ...
from collections import Counter class Solution: def findTheDifference(self, s: str, t: str) -> str: diff = Counter(t) - Counter(s) return list(diff.keys())[0] def findTheDifferenceXor(self, s: str, t: str) -> str: code = 0 for ch in s + t: code ^= ord(ch) r...
from typing import List class Solution: def asteroidCollision(self, asteroids: List[int]) -> List[int]: stack = [] for n in asteroids: while n < 0 and stack and stack[-1] > 0: if n + stack[-1] == 0: stack.pop() break ...