text
stringlengths
37
1.41M
""" Normal if statement. The unique difference is that no specification means if its true """ im_male = True if im_male: print("im male XD") else: print("im not male XD")
""" A function is a piece of code that will be repeated when needed. Its very useful """ def first_function(): #we have to type the colons print("Hello, you used a function! :D") def second_function(Name): #We have to tell python what variables will be using (Basically for specifying when used the function), w...
class user: def __init__(self, name, password): self.name = name self.password = password admin = user("root", "123456") # 系统初始化用户 '*** 让用户输入功能选项,输入1启动登录功能 ***' '*** 输入2启动注册功能,输入3退出系统 ***' order = input('1:登录,2:注册(退出输入exit):') '*** 使用字典保存注册过的用户信息 ***' '*** 注意,字典元素的key是用户名,value是用户对象 ***' userIn...
#This program is determining the avergae grade for the user. def read_file(scores): score_arr = [] first = 'y' file = open(scores, "r") for line in file: line = line.strip() if first == 'y': first = 'n' else: scores = get_score(line) score_ar...
#This program displays the users input in a different order the it is recieved. def get_name(): while True: print("Enter name (First Last):") name = input() error_1 = get_error_1(name) if error_1 == "n": error_2 = get_error_2(name) if error_2 == "n": ...
def processSize(shoeSize): size = shoeSize if size < 6: print("your shoe size is small!") else: if size < 9: print("your shoe size is medium!") else: if size < 12: print("your shoe size is large!") return size # Main print("What is yo...
# Author: Abigail Bowen aeb6095@psu.edu def getGradePoint(lettergrade): if lettergrade == "A": return 4.0 elif lettergrade == "A-": return 3.67 elif lettergrade == "B+": return 3.33 elif lettergrade == "B": return 3.0 elif lettergrade == "B-": return 2.67 elif lette...
#!/usr/bin/env python3 #-*- coding: utf-8 -*- import re pattern1 = 'p.*y' # 贪婪模式 pattern2 = 'p.*?y' # 懒惰模式 string = 'abcdfphp345Pythony_py' result1 = re.search(pattern1,string, re.I) result2 = re.search(pattern2,string, re.I) print(result1) print(result2)
""" Sample module to demonstrate implementation of OOP properties. 1. Abstraction. 2. Encapsulation. 3. Inheritance. 4. Methods 5. Overloading """ class BaseUser(object): def __init__(self, first_name, last_name): self.first_name = first_name self.last_name = last_name ##########################...
# Import matplotlib import matplotlib.pyplot as plt # Load the image data = plt.imread('bricks.png') # Set the red channel in this part of the image to 1 data[:10, :10, 0] = 1 # Set the green channel in this part of the image to 0 data[:10, :10, 2] = 0 # Set the blue channel in this part of the image to 0 data[:10,...
'''########################################### CS221 Final Project: Heuristic Controller Implementation Authors: Kongphop Wongpattananukul (kongw@stanford.edu) Pouya Rezazadeh Kalehbasti (pouyar@stanford.edu) Dong Hee Song (dhsong@stanford.edu) ###########################################''' # impor...
import re pattern = r"a" if re.match(pattern, "Ivan Santiago De Jesus"): print("Match") else: print("No match") if re.search(pattern, "Ivan Santiago De Jesus"): print("Search match") else: print("No search match") find_all = re.findall(pattern, "Ivan Santiago De Jesus") print(find_all...
class Equipo(object): def __init__(self, n, c, cam, nj): #Atributos de estudiante con los valores enviados desde el archivo self.nombre = n self.ciudad = c self.campeonatos = int(cam) self.numJugadores = int(nj) #Metodos agregar y obtener def agregar_nombre(self, n): ...
def recursivBinarySearch(A, left, right, item): if right < left: return -1 center = (left + right) // 2 if A[center] == item: return center elif A[center] > item: return recursivBinarySearch(A, left, center - 1, item) else: return recursivBinarySearch(A, center...
""" Created on Mon Sep 24 12:10:05 2018 @author: BrianRG """ def weird(a,b): if(not a or not b): return (a,b) if(a>=2*b): a%=(2*b) return weird(a,b) if(b>=2*a): b%=(2*a) return weird(a,b) return(a,b) """ def weirdo(a,b): while(a and b): ...
""" 下面的文件将会从csv文件中读取读取短信与电话记录, 你将在以后的课程中了解更多有关读取文件的知识。 """ import csv with open('texts.csv', 'r') as f: reader = csv.reader(f) texts = list(reader) with open('calls.csv', 'r') as f: reader = csv.reader(f) calls = list(reader) """ 任务1: 短信和通话记录中一共有多少电话号码?每个号码只统计一次。 输出信息: "There are <count> different te...
import requests import json import sys import argparser URL="http://api.openweathermap.org/data/2.5/weather?q=" class Weather(): def get_json(self,ciudad): r=requests.get(URL+ciudad) return r.content def print_weather(self, ciudad, unidad): j = self.get_json(ciudad) r = json.loads(j) temperatura = r...
# # @lc app=leetcode id=887 lang=python3 # # [887] Super Egg Drop # # @lc code=start import math class Solution: def superEggDrop(self, K: int, N: int) -> int: # dp[M][K]means that, given K eggs and M moves, # what is the maximum number of floor that we can check # dp[m][k] = dp[m - 1][k -...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Aug 5 20:48:47 2019 @author: damienrigden Examples of strings encrypted using polymorph. Feel free to make more requests """ encrypt = polymorph("Hello world!") print(encrypt) [[{'%'}, ['VY]V\\\\VWVV]YVWYVU]VXWV]\\V^UV]YV\\[Y[', 101, 114, 112, 115, 1...
import math a = int(input()) b = int(input()) for i in range(a, b+1): c = int(math.sqrt(i)) if c*c == i: print(i)
def min(a,b,c,d): min = float('inf') if min > a: min = a if min > b: min = b if min > c: min = c if min > d: min = d print(min) m = [] s = input() m = s.split() a = int(m[0]) b = int(m[1]) c = int(m[2]) d = int(m[3]) min(a,b,c,d)
# def unique_string(x): dict1 = {} for char in range(len(x)): if x[char] in dict1.values(): print("False") else: dict1[char] = x[char] print("True") print("unique elements in dictionary", dict1) unique_string("shikshiha")
__author__ = 'Joel' def collatz_conjecture(n): return n / 2 if n % 2 == 0 else 3 * n + 1 visited_map = {} def get_iterations_of_collatz(start_val): if start_val in visited_map: return visited_map.get(start_val) count = 1 val = start_val while val != 1: val = collatz_conjecture(...
from sympy import symbols, sqrt, Matrix, mpmath, Line3D, Segment3D, Point3D, Plane from sympy import srepr def dist_between_points(point1, point2): """ Expects input as tuple(x,y)""" x1,x2,y1,y2= symbols("x1 x2 y1 y2") distance= sqrt( (x2-x1)**2 + (y2-y1)**2) x1,y1,z2 = point1 x2,y2,z2 = point2 ...
x = 1 x += 2 print('Value of x:') print(x)
number_one = input('Enter number one: ') number_two = input('Enter number two: ') sum_number = float(number_one) + float(number_two) if sum_number > 5: print('The sum is greater than 5') elif sum_number < 5: print('The sum is less than 5') else: print('The sum is equal to 5')
n=int(input("enter the number")) if (n>0): print("the number is possitive") else: print("the number negative")
#Bloco de importação ########################## import random # from sklearn import tree # ########################## #Criação da matriz de pacientes e da matriz com os tipos de diabetes que é nossa variável resposta pacientes = [] tipos = [] for i in range(1501): sexo = random.choice(["Home...
import math h = 0.1 t = 0.1 eps = 0.1 N = int(1/h) a = 0.5 def simpson(y): return (h/3)*(y[0] + y[-1] + 2*sum(y[2:-1:2]) + 4*sum(y[1:-1:2])) def y_f(a): y = [0, a] for i in range(2, N): y.append(h*h*h*(i-1)*math.sqrt(y[i-1])/2 + 2*y[i-1] - y[i-2]) return y def fitness(a): return simpson...
#Prime numbers upto a limit print("Jaswanth sai - 121910313044") lower = int(input("Enter the lower limit:")) higher = int(input("Enter the higher limit:")) #logic begins here for a in range(lower,higher): if a>1: for i in range(2,a): if(a%i==0): break ...
#To Find the Samllest among the three numbers num1 = float(input("Enter first number: ")) num2 = float(input("Enter second number: ")) num3 = float(input("Enter third number: ")) #Logic begins here smallest = num1 if (num2 < num1) and (num2 < num3): smallest = num2 elif (num3 < num1): smallest = n...
i = 1 while i == 1: tanishq = input("please enter the number: ") swastik = input("please enter the operand: ") diwakar = input("please enter the number: ") pankaj = input("please enter the operand:") if '*' in swastik or pankaj: product = int(tanishq) * int(diwakar) if '/' in swastik ...
# Insert Data Program import pymongo fruit_dict = { "type": "bananas", "cost": 45, "stock": 67 } # Store record in the db client = pymongo.MongoClient("mongodb://localhost:27017/") fruit_db = client["fruits2_db"] fruit_col = fruit_db["fruits"] x = fruit_col.insert_one(fruit_dict) print(x)
import os import csv # Path to collect data from the Resources folder wrestling_csv = os.path.join('Resources', 'WWE-Data-2016.csv') # Define the function and have it accept the 'wrestlerData' as its sole parameter def print_percentages(wrestler): # Find the total number of matches wrestled total = int(wrestler[1...
#You are given two integer arrays of size X and X ( & are rows, and is the column). Your task is to concatenate the arrays along 0 axis . ''' Two or more arrays can be concatenated together using the concatenate function with a tuple of the arrays to be joined: import numpy array_1 = numpy.array([1,2,3]) array_2 =...
#program to demonstrate functionality of transpose and flatten functions of numpy module import numpy list1=input().strip().split() x,y=list(map(int,list1)) list2=[input().split() for i in range(x)] list3=[i for item in list2 for i in item] nparray=numpy.array(list3,int) npshapedarray=numpy.reshape(nparray,(x,y)) nptra...
#swap the case of letters from lower to upper and vice versa def swap_case(s): new_string="" for letter in s: if letter==letter.lower(): new_string+=letter.upper() else: new_string+=letter.lower() return new_string if __name__=="__main__": s=input() result=s...
#program to demonstrate functionality of zeros and ones functions of numpy module import numpy list1=input().strip().split() tuple1=tuple([int(x) for x in list1]) print(numpy.zeros(tuple1,dtype=numpy.int)) print(numpy.ones(tuple1,dtype=numpy.int)) ''' Sample Input 0 3 3 3 #first 3 is for number of arrays to be print...
#program to demonstrate functionality of identity and eye functions of numpy module import numpy #print(numpy.identity(3)) #print(numpy.eye(8, 7, k = -1,dtype=numpy.int)) #Diagonal we require; k>0 means diagonal above main diagonal or vice versa. numpy.set_printoptions(legacy='1.13') list1=input().strip().split() tuple...
#program to count strings starting with vowels and consonant in a given string and deciding the winner def minion_game(string): string=string.lower() dict1={} dict2={} vowels=['a','e','i','o','u'] vcounter=0; ccounter=0; for index in range(len(string)): if string[index] in vowels: ...
#Collier, R. "Lectures Notes for COMP1405B – Introduction to Computer Science I" [PDF document]. #Retrieved from cuLearn: https://www.carleton.ca/culearn/ (Fall 2015). #Gaddis, T. "Starting Out With Python 2nd ed"[PDF document] (Pearson, 2012) (Fall 2015). #Title and introduction print(" ⋆ ✢ ✣ ✤ ✥ ✦ ...
# I'm going to integrate three files ("Crimes_-_2001_to_present.csv", # "population_by_community_area.csv", and "SelectedIndicators.csv") into one # file ("processed_data.csv"). import pandas as pd # This file is from City of Chicago Data Portal. Read the csv file into a dataframe # with selected variables. df_crime ...
"""test for Python 2 string formatting error """ from __future__ import unicode_literals # pylint: disable=line-too-long __revision__ = 1 def pprint_bad(): """Test string format """ "{{}}".format(1) # [too-many-format-args] "{} {".format() # [bad-format-string] "{} }".format() # [bad-format-s...
""" This a test string to work on in the labs""" name = input("What is your name?") while len(name)== 0: name = input("What is your name?") for i in range(0, len(name,2): print(name[ : :2])
# -*- coding: utf-8 -*- # neural network from abc import ABC from collections.abc import Iterable class Connectable(Iterable, ABC): def connect_to(self, other): if self == other: return for s in self: # Iterable for o in other: # Iterable s.outputs.append(o...
# -*- coding: utf-8 -*- # How to build a factory that auto increment from unittest import TestCase class Person: def __init__(self, id, name): self.id = id self.name = name class PersonFactory: id = 0 def create_person(self,name): p = Person(PersonFactory.id, name) PersonFactory.id +=1 retur...
# Hello World program in Python print "Hello World!\n" mylist = [1,2, 3, 4,5 ] print mylist print mylist[3:5] mylist[3:4] = [0,1] print mylist[:] ll = [1,3,4,4,6,10,11,8] print ll def sort(ll): for i in range(len(ll)): for j in range(len(ll) - 1): if( ll[i] < ll[j] ): ...
# coding = utf-8 __author__ = "LY" __time__ = "2018/5/8" class CycleQueue(object): """docstring for CircleQueue""" def __init__(self, maxsize, front=0, rear=0): '''循环队列有空间大小限制''' self.maxsize = maxsize self.items = [None] * self.maxsize self.front = 0 self.rear = 0 def inQueue(self, data): '''入队列(头出尾进...
import datetime date = datetime.date(*[int(i) for i in input().split(" ")]) date += datetime.timedelta(int(input())) print(date.year, date.month, date.day)
#Number 1 i = 0 for x in range(10): if x % 2 != 0: i += x print(x) print(i) #Number 2 def function1(): answer1 = int(input("Give me a number")) answer2 = int(input("Give me another number")) print(answer1+answer2) #Number 3 def greetings(): print("Hello, world") greetings() displa...
import random class RandomQueue: def __init__(self): self.items = [] def __str__(self): return str(self.items) def insert(self, item): self.items.append(item) def remove(self): # zwraca losowy element rand_idx = random.randrange(len(self.items)) ...
print "Enter customer details" print "name of the customer" x= raw_input(str) print "meter number" z=raw_input(int) print"Enter the units consumed" y=raw_input(int) units=int(y)f(units<=100): print 'Dear',name print "Your Meter Number is: ",meter_no print "You have Consumed %d units" % (units) print "Total Price is...
def part_one(nums, set_nums): for num in nums: if 2020 - num in set_nums: return num * (2020 - num) def part_two(nums, set_nums): for num in nums: for num2 in nums: if (2020 - num - num2) in set_nums: return num * (2020 - num - num2) * num2 with open("...
import re # start from designated index (from jump) and go through instructions until next jump when recursion is called def jump_to(start,code_list,accnum,called): for i in range(start,len(code_list)): instr = re.search("([a-z]*) ([+-][0-9]*)$",code_list[i]) if instr: if i not in calle...
import requests from bs4 import BeautifulSoup #Entra no site principal site = 'https://saryalternativestore.loja2.com.br' html_site = requests.get(site) soup = BeautifulSoup(html_site.content, "html.parser") #abre o arquivo txt arquivo = open('produtos.txt','w',encoding='utf-8') #identifica as categor...
import unittest from Bowling import Bowling class MyTestCase(unittest.TestCase): def setUp(self) -> None: self.bowling_game = Bowling() @unittest.skip def test_environment(self): self.assertEqual(True, False) def test_score_zero(self): self.assertEqual(0, self.bowling_game.g...
#_*_coding:utf-8_*_ ''' @project: Exuding @author: exudingtao @time: 2019/12/23 11:26 下午 ''' def strStr(haystack, needle): len_n = len(needle) len_h = len(haystack) if len_h == 0 and len_n == 0: return 0 if haystack == needle: return 0 for i in range(len_h - len_n+1): print...
#_*_coding:utf-8_*_ ''' @project: DailyAlgorithm @author: exudingtao @time: 2019/12/14 3:27 下午 ''' #方法一 遍历上次的组合结果,逐个合并 def letterCombinations(digits): KEY = {'2': ['a', 'b', 'c'], '3': ['d', 'e', 'f'], '4': ['g', 'h', 'i'], '5': ['j', 'k', 'l'], '6': ['m', 'n', 'o'], ...
class Solution: def longestCommonPrefix(self, strs: List[str]) -> str: if not strs: return "" res = "" for j in range(len(strs[0])): c = strs[0][j] for i in range(1, len(strs)): if j >= len(strs[i]) or strs[i][j] != c: return res ...
#!/usr/bin/env python3 #-*- coding: utf-8 -*- def commas(N): digits = str(N) assert(digits.isdigit()) result = '' while digits: digits, last3 = digits[:-3], digits[-3:] result = (last3 + ',' + result) if result else last3 return result def money(N, width=0): sign = '-' if N < 0...
#!/usr/bin/env python3 #-*- coding: utf-8 -*- """ L = [1, 2, 4, 8, 16, 32, 64] X = 5 found = False i = 0 while not found and i < len(L): if 2 ** X == L[i]: found = True else: i = i+1 if found: print('at index', i) else: print(X, 'not found') """ # a. 首先,以while循环else分句重写这个代码来消除found标志...
# Python的循环有两种,一种是for...in循环,依次把list或tuple中的每个元素迭代出来,看例子: names = ['lizhenye','buxizhou','peakli'] for name in names: print(name) # 所以for x in ...循环就是把每个元素代入变量x,然后执行缩进块的语句。 sum = 0 for x in [1,2,3,4,5,6,7,8,9]: sum=sum+x print(sum) # 注意一句话 有冒号的下一行往往要缩进,该缩进就缩进 # range(start, stop[, step]) # start: 计数从 start 开始。默认是从 0...
#INPUT #1 candy name #2 price per pound #3 numbers sold #PROCESS #1 determine if is best seller #2 if candy is best seller (2000 pounds per month) #OUTPUT #display item data def main(): isValid = False while not isValid: candy = input("Please enter candy. Either Hersheys, Sni...
name = 'abc def ghi' characters = list(name) # print(name) # print(characters) a1 = 'abc,def,ghi' a2 = a1.split(",") print(a2)
items = ['14', '-46', '5', '123', '-8'] i = int(input("Enter a number") if i in items: print("found, ", position) elif not i in items: print("not found in list")
items = ['abc', 'def', 'ghi'] items = [item.capitalize() for item in items] print(items)
import os from datetime import datetime # Targil: # 1. add to file print the size of each file # 2. add to file print the last modified of each file # 3. read input file name from the user - print in which folder it exist, or not exist # *etgar read only part of file name or i.e. *.txt # 4. read extension from the us...
from datetime import * class HashtagGraphEdges: """ Double linked list method is used to build the Twitter hashtag graph. The double linked list stands for the structure of the hashtags according. The keys of dictionary are the edges of two hastags(hashtage_pair in hashtage_pair_list) and the coressponding values...
def payingDebtOffInOneYear(balance, annualInterestRate, monthlyPaymentRate, months=12): """ Write a program to calculate the credit card balance after one year if a person only pays the minimum monthly payment required by the credit card company each month. """ def pay_monthly(balance, annualInterestRat...
# ------------------------------------------------------------- # Метод подсчёта прироста def Bank(Money,Percent): return (Money / 100) * Percent # ------------------------------------------------------------- # Главный метод def main(): print("Задача с банком") # Начальные условия M...
from Tkinter import * ''' Author: Federico Terzi This module just display a basic window to show the output of the "start.py" module This is a work in progress.... ''' class TextWindow: def __init__(self, master): self.root = master frame = Frame(master) frame.pack() master.title(...
#!/usr/bin/env python3 #-*- coding: utf-8 -*- import pygame from punto import Punto from variables import (TRAYECTORIA_COLOR, TRAYECTORIA_GROSOR) class Trayectoria: """Una Trayectoria representa la trayectoria de una partícula, almacenando los datos más relevantes de su movimiento: puntos en x e y, velocidades e...
# Scipy # Numpy provides a high-performance multidimensional array and # basic tools to compute with and manipulate these arrays. # Scipy builds on this, and provides a large number of functions # that operate on numpy arrays and are useful for different types # of scientific and engineering applications. # Image oper...
import json class JsonIO: """Class Performs JSON IO""" @staticmethod def read_json_file(path) -> []: """Reads in JSON File""" with open(path) as f: return json.load(f) @staticmethod def write_json_file(path, data): """Writes Data JSON File Using Dump""" ...
from turtle import * speed('fastest') hideturtle() # The original challenge was to make a Sierpinski drawer that was iterative # instead of recursive in order to cope with Python's recursion depth limit, # but after failing to find a way after considerable effort I conjectured that # it was impossible to convert the r...
''' Given the root of a binary tree, return the maximum average value of a subtree of that tree. A subtree of a tree is any node of that tree plus all its descendants. The average value of a tree is the sum of its values, divided by the number of nodes. ''' from leetcode import * class Solution: # Time: O(n) ...
''' You are given an array points representing integer coordinates of some points on a 2D-plane, where points[i] = [xi, yi]. The cost of connecting two points [xi, yi] and [xj, yj] is the manhattan distance between them. Return the minimum cost to make all points connected. All points are connected if there is exactl...
''' Write a function to find the longest common prefix string amongst an array of strings. If there is no common prefix, return an empty string "". ''' from leetcode import * # Time: O(n * |s_min|) where |s_min| is the length of the shortest string in the array, Space: O(n * |s_min|) because # you could keep taking th...
''' Given an array of meeting time intervals where intervals[i] = [starti, endi], determine if a person could attend all meetings. ''' from leetcode import * # Time: O(nlog(n)) # Space: O(1) class Solution: def canAttendMeetings(self, intervals: List[List[int]]) -> bool: intervals.sort() for i in r...
''' Return the root node of a binary search tree that matches the given preorder traversal. Note: - The values of preorder are distinct. ''' from leetcode import * # Time: O(n), Space: O(n). # I thought it might be O(n^2) in the worst case, but you do not visit a node more than twice so it's linear. def bst_from_pre...
from leetcode import * class Solution: # Time: O(n). # Space: O(n). def calPoints(self, ops: List[str]) -> int: record = [] for i in ops: if i == '+': record.append(record[-1] + record[-2]) elif i == 'D': record.append(2*record[-1]) ...
''' Given the root of a binary search tree, rearrange the tree in in-order so that the leftmost node in the tree is now the root of the tree, and every node has no left child and only one right child. ''' from leetcode import * class Solution: # Space: O(n). # Time: O(n). def increasingBST(self, root: Tree...
''' Given a circle represented as (radius, x_center, y_center) and an axis-aligned rectangle represented as (x1, y1, x2, y2), where (x1, y1) are the coordinates of the bottom-left corner, and (x2, y2) are the coordinates of the top-right corner of the rectangle. Return True if the circle and rectangle are overlapped o...
from leetcode import * # Level order representation approach similar to how Leetcode represents trees. # Time: O(n) for both operations where n is the number of nodes in the tree. # Space: O(n) for both operations where n is the number of nodes in the tree. # From Leetcode, you could also do a preorder DFS representat...
''' Suppose an array of length n sorted in ascending order is rotated between 1 and n times. For example, the array nums = [0,1,2,4,5,6,7] might become: [4,5,6,7,0,1,2] if it was rotated 4 times. [0,1,2,4,5,6,7] if it was rotated 7 times. Notice that rotating an array [a[0], a[1], a[2], ..., a[n-1]] 1 time results in ...
from leetcode import * class Solution: # Recursion # Time: O(H), so O(n) in worst-case and O(log(n)) in average-case. # Space: O(H) def insertIntoBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]: if root is None: return TreeNode(val) elif root.val < val: ...
''' Write a function that takes an unsigned integer and returns the number of '1' bits it has (also known as the Hamming weight). ''' class Solution: def hammingWeight(self, n: int) -> int: oneBits = 0 while n > 0: if n & 1: oneBits += 1 n >>= 1 retur...
''' You are given an integer n and an array of unique integers blacklist. Design an algorithm to pick a random integer in the range [0, n - 1] that is not in blacklist. Any integer that is in the mentioned range and not in blacklist should be equally likely to be returned. Optimize your algorithm such that it minimize...
''' Write a function that reverses a string. The input string is given as an array of characters s. ''' from leetcode import * # Time: O(n). # Space: O(1). class Solution: # Time: O(n) # Space: O(1) def reverseString(self, s: List[str]) -> None: halfLen = len(s) // 2 i = 0 while i <...
''' Given a collection of candidate numbers (candidates) and a target number (target), find all unique combinations in candidates where the candidate numbers sum to target. Each number in candidates may only be used once in the combination. Note: The solution set must not contain duplicate combinations. ''' from leet...
''' Given a roman numeral, convert it to an integer. ''' class Solution: # Time: O(n) # Space: O(1) def romanToInt(self, s: str) -> int: integer = 0 numerals = {'I': 1, 'IV': 4, 'V': 5, 'IX': 9, 'X': 10, 'XL': 40, 'L': 50, 'XC': 90, 'C': 100, 'CD': 40...
''' Given the root of a binary tree, invert the tree, and return its root. ''' from leetcode import * class Solution: # Recursive approach # Time: O(n) where n are the number of nodes in the tree. # Space: O(H) where H is the height of the tree. def invertTree(self, root: Optional[TreeNode]) -> Optiona...
''' Same description as word_ladder.py except: Given two words, beginWord and endWord, and a dictionary wordList, return all the shortest transformation sequences from beginWord to endWord, or an empty list if no such sequence exists. Each sequence should be returned as a list of the words [beginWord, s1, s2, ..., sk...
''' Given an integer array nums of unique elements, return all possible subsets (the power set). The solution set must not contain duplicate subsets. Return the solution in any order. ''' from leetcode import * class Solution: # Backtracking approach # Time: O(n*(2^n)) where n is the number of elements in num...
''' You are given an m x n integer matrix points (0-indexed). Starting with 0 points, you want to maximize the number of points you can get from the matrix. To gain points, you must pick one cell in each row. Picking the cell at coordinates (r, c) will add points[r][c] to your score. However, you will lose points if ...
''' Given an integer array nums, move all 0's to the end of it while maintaining the relative order of the non-zero elements. Note that you must do this in-place without making a copy of the array. ''' from leetcode import * class Solution: # Time: O(n^2) # Space: O(1) def moveZeroes(self, nums: List[int]...
# Input: # s: a string to repeat (1 <= |s| <= 100) # n: the number of chars to consider (1 <= n <= 10^12) # Output: an integer denoting the number of letter a's in the first # n letters of the infinite string created by repeating s infinitely many times # Algorithm runs in O(1) time def repeatedString(s, n): size =...
''' Given a list of intervals, remove all intervals that are covered by another interval in the list. Interval [a,b) is covered by interval [c,d) if and only if c <= a and b <= d. After doing so, return the number of remaining intervals. Assume there is at least one interval given. ''' from leetcode import * # Time...
''' The n-queens puzzle is the problem of placing n queens on an n x n chessboard such that no two queens attack each other. Given an integer n, return all distinct solutions to the n-queens puzzle. You may return the answer in any order. ''' from leetcode import * class Solution: # Backtracking approach # Ti...
''' Given two strings ransomNote and magazine, return true if ransomNote can be constructed from magazine and false otherwise. Each letter in magazine can only be used once in ransomNote. ''' from leetcode import * class Solution: # Time: O(m) where m is the length of magazine. # Space: O(1) since the counter...