text stringlengths 5 121k |
|---|
def trimBST(self, root, L, R):
"""
:type root: TreeNode
:type L: int
:type R: int
:rtype: TreeNode
"""
def trim(root):
if not root:
return None
if root.val > R:
return trim(root.left)
if root.val < L:
return trim(root.right)
... |
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
res = ListNode(0)
cur = res
flag = 0
while l1 or l2:
if l1 and l2:
flag, tmp = divmod(l1.val + l2.val + flag, 10)
elif l1:
flag, tmp = divmod(l1.val... |
def addStrings(num1, num2):
"""
:type num1: str
:type num2: str
:rtype: str
"""
res = ""
tmp = 0
while num1 or num2 or tmp != 0:
if num1:
tmp += (ord(num1[-1]) - ord("0"))
if num2:
tmp += (ord(num2[-1]) - ord("0"))
res += str(tmp % 10)
... |
def climbStairs(self, n):
"""
:type n: int
:rtype: int
"""
res = [1, 2]
while len(res) < n:
res.append(res[-1] + res[-2])
return res[n - 1] |
def lemonadeChange(bills):
"""
:type bills: List[int]
:rtype: bool
"""
res = {5: 0, 10: 0}
for b in bills:
if b == 5:
res[5] += 1
elif b == 10:
if res[5] == 0:
return False
else:
res[10] += 1
res[... |
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: None Do not return anything, modify nums in-place instead.
"""
n = len(nums)
t = 1
i = 0
while t <= n:
if nums[i] == 0:
nums.append(nums.pop(i))
else:
i += 1
t += 1 |
import queue
def click_internal(field, num_rows, num_cols, given_i, given_j):
field[given_i][given_j] = -2
for i in range(given_i - 1, given_i + 2):
for j in range(given_j - 1, given_j + 2):
if 0 <= i < num_rows and 0 <= j < num_cols and field[i][j] == 0:
click_internal(f... |
from collections import defaultdict
def fibonacci_recursive(n):
if n <= 0:
return 0
if n == 1:
return 1
else:
return fibonacci_recursive(n-1) + fibonacci_recursive(n-2)
def dyna_fibonacci(n, state):
if n <= 0:
state[0] = 0
if n == 1:
state[n] = 1
if s... |
import unittest
class Node:
def __init__(self):
self.left = None
self.right = None
self.value = None
def is_unival(root):
return unival_helper(root, root.value)
def unival_helper(root, value):
if root is None:
return True
if root.value == value:
return unival... |
import heapq
if __name__ == '__main__':
candidates =[2,3,6,7]
target = 7
res = []
resList = []
heapq.heappop()
def backtracking(start, rest):
if rest == 0:
temp = resList[:]
res.append(temp)
for i in range(start, len(candidates)):
if (candi... |
import unittest
from collections import deque
class Node:
def __init__(self, value):
self.left = None
self.right = None
self.value = value
def path_to_x(node: Node, x):
if not node:
return None
if node.value == x:
stack = deque()
stack.append(x)
re... |
class Node:
def __init__(self, value, child=None):
self.value = value
self.child = child
def __str__(self):
return str(self.value)
def nth_from_last(head, n):
left = head
right = head
for i in range(n):
if right is None:
return None
right = righ... |
import unittest
from collections import defaultdict, deque
import sys
def minimumBribes(q):
moves = 0
for pos, val in enumerate(q):
d = (val - 1) - pos
if d > 2:
return "Too chaotic"
start = max(0, val - 2)
end = pos + 1
for j in range(start, end):
... |
import unittest
def anagram_substring(target, base):
if not base or not target:
return False
state = dict()
for c in base:
state[c] = 1
for c in target:
if c not in state:
return False
return True
class Test(unittest.TestCase):
def test_case(self):... |
if __name__ == '__main__':
nums = [7, 1, 5, 3, 6, 4]
max_profit = 0
for i in range(len(nums) - 1):
for j in range(1, len(nums)):
if nums[i] < nums[j]:
profit = nums[j] - nums[i]
if max_profit < profit:
max_profit = profit
print(max... |
import unittest
def is_unique(target):
temp = ""
for c in target:
if c in temp:
return False
else:
temp += c
return True
def check_permutation(str_a, str_b):
longest = None
shortest = None
if len(str_a) >= len(str_b):
longest = str_a
... |
import unittest
def move(target, index, anchor):
pivot = index
while pivot < anchor - 1:
temp = target[pivot]
target[pivot] = target[pivot + 1]
target[pivot + 1] = temp
pivot += 1
def move_zeros(target):
if not target or len(target) == 1:
return target
... |
import unittest
def count_sets(arr, target):
state = dict()
return recursive(arr, target, len(arr)-1, state)
def recursive(arr, total, i, state):
key = '{}-{}'.format(total, i)
if key in state:
return state[key]
if total == 0:
result = 1
elif total < 0:
result = 0
... |
import unittest
import random
def get_rand_number(min_value, max_value):
"""
This function gets a random number from a uniform distribution between
the two input values [min_value, max_value] inclusively
Args:
- min_value (float)
- max_value (float)
Return:
- Random number betw... |
"""
Spyder Editor
This is a temporary script file.
"""
import pandas as pd
import matplotlib.pyplot as plt
plt.style.use('fivethirtyeight')
plt.rcParams['figure.figsize'] = (6, 4)
plt.rcParams['font.size'] = 9
yelp = pd.read_csv('yelp.csv', header=0)
yelp.head()
yelp.columns
yelp.dtypes
yelp5_1 = yelp[(yel... |
import numpy
import random
import pygame
class Grid:
def __init__(self):
self.grid = []
self.next_grid = []
self.display = Display()
self.create_random_grid()
self.display.main_display_loop(self)
def create_random_grid(self, grid_dimension=None):
if grid_dimens... |
n = int(input())
array = []
for i in range(n):
num = int(input())
array.append(num)
def quick_sort(array):
if len(array) <= 1:
return array
pivot = array[0]
tail = array[1:]
left = [x for x in tail if x < pivot]
right = [x for x in tail if x > pivot]
return l... |
class Money():
def __init__(self, amount=0, currency="RUR"):
self._amount = amount
self._currency = currency
def __eq__(self, money):
return self._amount == money._amount and self._currency == money._currency
def __ne__(self, money):
return self._amoun... |
from collections import deque
def solution(priorities, location):
answer = 0
index_queue = deque(range(len(priorities)))
priorities_queue = deque(priorities)
while True:
max_priorities = max(priorities_queue)
priorities_head = priorities_queue.popleft()
index_head = index_queue... |
def solution(array, commands):
answer = []
for i in range(len(commands)):
start = commands[i][0]
end = commands[i][1]
cut = array[start-1:end]
cut.sort()
place = commands[i][2]
num = cut[place-1]
answer.append(num)
return answer |
def iterative_solution(numbers, target):
result_list = [0]
for i in range(len(numbers)):
temp_list = []
for j in range(len(result_list)):
temp_list.append(result_list[j] - numbers[i])
temp_list.append(result_list[j] + numbers[i])
result_list = temp_list
... |
class Solution:
def numOfBurgers(self, tomatoSlices: int, cheeseSlices: int):
low, high = 0, tomatoSlices // 4
print(low, high)
while low <= high:
mid = (low + high) // 2
tomatos, cheeses = tomatoSlices - mid*4, cheeseSlices - ... |
class Solution:
def findOcurrences(self, text: str, first: str, second: str):
words = text.split(' ')
res = []
wlen = len(words)
for i in range(0, wlen - 2):
if words[i] == first and words[i + 1] == second:
res.append(words[i + 2])
... |
"""
Created on Thu Mar 26 18:03:04 2020
@author: douzi
"""
class Solution:
def longestPalindrome(self, s: str) -> str:
length = len(s)
result = ""
for i in range(length):
sum1 = ""
sum2 = ""
for str1 in s[i:]:
sum1 = sum1 +... |
"""
Created on Thu Apr 16 01:34:53 2020
@author: douzi
"""
class Solution:
def sortArrayByParityII(self, A):
Alen = len(A)
res = [0] * Alen
even, odd = 0, 1
for e in A:
if e % 2 == 0:
res[even] = e
even = even + 2
... |
"""
Created on Tue Apr 14 19:47:00 2020
@author: douzi
"""
class Solution:
def distributeCandies(self, candies) -> int:
clen = len(candies)
ave = clen // 2
cset = set()
for e in candies:
cset.add(e)
if len(cset) == ave:
... |
class Solution:
def isValid(self, s: str) -> bool:
ans = []
for e in s:
if e in ['(', '[', '{']:
ans.append(e)
elif e == ')':
if ans:
t = ans.pop()
if t != '(':
return... |
class Solution:
def detectCycle(self, head: ListNode) -> ListNode:
if head == None or head.next == None:
return None
fast, slow = head, head
while True:
if not (fast and fast.next):
return None
slow, fast = slow.nex... |
class Solution:
def isPerfectSquare(self, num: int) -> bool:
for i in range(1, num+1):
if i**2 == num:
return True
elif i**2 > num:
return False
s = Solution()
print(s.isPerfectSquare(16))
print(s.isPerfectSquare(1)) |
class Solution:
def distanceBetweenBusStops(self, distance, start: int, destination: int) -> int:
forward = 0
backward = 0
dlen = len(distance)
for i in range(0, dlen):
forward += distance[(start + i) % dlen]
if (start + i + 1) % dlen == d... |
import re
def strip_xml(mystring):
return(re.sub('<[^>]*>', '', mystring))
def get_all_none_indiv(question):
ans = ''
while (ans.upper() != ('A' or 'N' or 'I')):
print(question,end="")
ans = input()
if ans.upper() == 'A':
return 'All'
... |
from keras.models import Sequential
from keras.layers import Dense
print(train_data.shape)
model = Sequential()
model.add(Dense(10, activation='relu',
input_shape=(784,)))
model.add(Dense(10, activation='relu'))
model.add(Dense(10, activation='relu'))
model.add(Dense(3, activation='softmax'))
mode... |
x = int(input('Digite um inteiro: '))
if x % 3 == 0 and x % 5 == 0 :
print('FizzBuzz')
else:
print(x) |
'''
mixers.py
Classes to wrap motor controllers into a functional drive unit.
'''
import time
import sys
from donkey import actuators
class BaseMixer():
def update_angle(self, angle):
pass
def update_throttle(self, throttle):
pass
def update(self, throttle=0, angle=0):
'''Conv... |
from tkinter import *
root = Tk()
v = IntVar()
v.set(1)
languages = [ ("Python",1), ("Perl",2), ("Java",3), ("C++",4), ("C",5)]
def ShowChoice():
print (v.get())
Label(root,text="""Choose your favourite programming language:""",
justify = LEFT, padx = 20).pack()
for txt, val in languages:
Radiobutton(... |
i = 2
i != 6
"ACDC" != "Michael Jackson"
'B' > 'A'
age = 19
if age > 18:
print("you can enter" )
print("move on")
album_year = 1990
if(album_year < 1980) or (album_year > 1989):
print ("Album was not made in the 1980's")
else:
print("The Album was made in the ... |
f = open("C/input.txt", "r")
words = f.read().strip().split()
f.close()
count = {}
maxval = -1
tmp = ""
for i in words:
if i not in count:
count[i] = 0
count[i] += 1
if count[i] > maxval:
maxval = count[i]
tmp = i
most_frequent_words = []
for i, j in count.items():
if ... |
def right_bin_search(left, right, check, checkparams):
while left < right:
middle = (left + right + 1) // 2
if check(middle, checkparams):
left = middle
else:
right = middle - 1
return left
def checklength(x, params):
arr, k = params
summ = 0
for wi... |
def binary(arr, val) :
if len (arr) >= 1 :
mid = len (arr) // 2
if arr[mid] == val :
return True
elif val > arr[mid] :
return binary (arr[mid + 1 :len (arr)], val)
else :
return binary (arr[0 :mid], val)
else :
return False
... |
"""Book examples for basic testing"""
from implementmodule import Vertex, breadth_first_search, depth_first_search, print_path
VERTEXR = Vertex('R')
VERTEXV = Vertex('V')
VERTEXS = Vertex('S')
VERTEXW = Vertex('W')
VERTEXT = Vertex('T')
VERTEXU = Vertex('U')
VERTEXY = Vertex('Y')
VERTEXX = Vertex('X')
VERTEXZ = Vertex... |
import math
from copy import deepcopy
import random
import numpy as np
class State:
def __init__(self):
raise NotImplementedError
def mutate(self):
raise NotImplementedError
class MyState(State):
def __init__(self, placing_order):
self.placing_order = placing_order
@staticm... |
''' RPi_Testing.py
Purpose: Basic code for running Xbee, and illustrating code behavior.
Sets up Xbee;
IMPORTANT: Must be run using Python 3 (python3)
Last Modified: 6/30/2021
By: Jamez White
'''
import serial
import time
import RPi.GPIO as GPIO
import math
global Xbee
Xbee = serial.Serial('/dev/ttyUSB0', 11520... |
from tkinter import *
from back import Database
from tkinter import messagebox
class MainWindow(object):
def __init__(self, window):
self.window = window
self.window.title("Book database")
self.window.geometry("500x370")
lbl_title = Label(self.window, text="Tytu... |
from collections import deque
class Grafo(object):
def __init__(self):
self.relaciones = {}
def __str__(self):
return str(self.relaciones)
def agregar(grafo, elemento):
grafo.relaciones.update({elemento:[]})
def relacionar(grafo, origen, destino):
grafo.relaciones[orige... |
import abc
import re
class Person:
__id = 0
list_phone = []
address = []
@staticmethod
def generatId(self):
self.__id += 1
@staticmethod
def validEmail(email):
fields = email.split("@")
if len(fields) != 2:
return False
else:
regex ... |
import shelve
with shelve.open("cave data") as data:
loc = 1
while True:
availableExits = ", ".join(data["locations"][loc]["exits"].keys())
print(data["locations"][loc]["desc"])
if loc == 0:
break
else:
allExits = data["locations"][loc]["exi... |
class Solution:
def isSymmetric(self, root) -> bool:
if not root:
return True
return self.isMirror(root.left, root.right)
def isMirror(self, t1, t2) -> bool:
if t1 and t2:
return t1.val == t2.val and self.isMirror(t1.right, t2.left) and self.isMirr... |
def is_fasta(name):
if not isinstance(name, str):
raise TypeError('ERROR: is_fasta requires string inpute.')
elif len(name) <= 10:
return False
elif name[-10:] == '.fasta.txt':
return True
else:
return False
def open_fasta(file_name):
if not ... |
def read_input():
with open('input.txt', 'r') as f:
lines = f.readlines()
lines = [line.strip() for line in lines]
return lines
def check_sum(arr, num):
for i in range(len(arr)):
for j in range(i + 1, len(arr)):
if arr[i] + arr[j] == num:
ret... |
def read_input():
with open('input.txt', 'r') as f:
lines = f.readlines()
lines = [line.strip() for line in lines]
return lines
def run_program(lines, op_to_switch=None):
visited = set()
accumulator = 0
current_idx = 0
finished_normally = False
while current_idx not in v... |
def computeProb(counterWon, counterWS, counterGame):
pb = counterWS / counterGame
paib = counterWon / counterGame
if pb == 0:
pab = 0
else:
pab = paib / pb
return pab
import pandas as pd
df = pd.read_csv("modifiedWinStreaks - good.csv")
streaks = df["Numeric Win Streak"]
maxS... |
def duplicate_encode(word):
word = word.lower()
lst = [str(i) for i in word]
res = []
for x in range(0, len(lst)):
if word.count(lst[x]) > 1:
res.append(")")
else:
res.append("(")
print("".join(res))
duplicate_encode("(( @")
|
add = __import__("add_4").add
def addition():
"""calls the add function passing with the value of a and b"""
a = 1
b = 2
print("{} + {} = {}".format(a, b, add(a, b)))
"""not executed when imported"""
if __name__ == "__main__":
addition()
|
import csv
from algorithm.sort import *
from algorithm.search import *
result = []
key = []
with open("unsorted.csv", 'r') as p_file:
csv_data = csv.reader(p_file)
for row in csv_data:
row = [int(i) for i in row]
key.append(row[len(row)-1])
row.pop()
row = insertion_sort(ro... |
"""
This code includes functions to preprocess text in gutenberg dataset.
Especially, for certain book.
Download
--------
Project Gutenberg.
https://www.gutenberg.org/ebooks/
Base datapath: '~~~/data/'
Additional folder structure: '~~~/data/gutenberg/alice_in_wonderland.txt'
SAVE THE TEXT TO ANSI FORMAT.
"""
import t... |
'''
Program Mini-Kuis DDP1
Program untuk mengerjakan kuis yang berisi 4 buah pertanyaan yang meminta
user untuk mengkonversi bilangan biner ke bilangan desimal.
'''
def cetak_pertanyaan(urutan, angka_biner):
'''
Mencetak pertanyaan
'''
print("Soal {}: Berapakah angka desimal dari bilangan b... |
'''
Program gambar bentuk anak tangga
Menggambar 3 buah anak tangga dengan panjang anak tangga berdasarkan input dari
user. Penggambaran dilakukan menggunakan Turtle Graphics.
'''
import turtle
kura = turtle.Turtle()
sisi = int(input("Masukkan panjang sisi anak tangga: "))
kura.pendown()
kura.color('yello... |
'''
Using Turtle Graphics to draw a blue polygon with customizable number and
length of sides according to user's input.
'''
import turtle
sides = int(input("Number of sides: "))
distance = int(input("Side's length: "))
turtle.color('blue')
turtle.pendown()
deg = 360 / sides
for i in ran... |
import math
class Dijkstra2:
"""
Class used to get the shortest path or the largest path of two given nodes
Attributes------------------------
unvisited_nodes : graph, graph given by parameter
shortest_distance : dictionary, stores the shortest distance
route : list, gives the route of the ... |
def theft(amountOfMoneyInLand):
x = list(zip(*amountOfMoneyInLand))
currentIndex=0
result=0
for i in range(0,len(x[0])):
currentIndex=i
genelIndis = 1
resultTemp=x[0][i]
for m in range(genelIndis,len(x)):
t1 = currentIndex-1
t2 = currentIndex
... |
print('Saifullah, 18B-092-CS, A')
print('1st Detailed Assignment, Problem 3.24')
words = eval(input('Enter list of word: '))
for word in words:
if word != 'secret':
print(word)
|
print('Saifullah, 18B-092-CS, A')
print('1st Detailed Assignment, Problem 3.31')
x = eval(input('Enter x: '))
y = eval(input('Enter y: '))
r = 5
if x<r and x<r:
print('It is in!')
|
print('Saifullah, 18B-092-CS, A')
print('1st Detailed Assignment, Ex. 3.23')
print('\nEx. 3.23(a)')
for i in range(0,2):
print(i)
print('\nEx. 3.23(b)')
for x in range(0,1):
print(x)
print('\nEx. 3.23(c)')
for y in range(3,7):
print(y)
print('\nEx. 3.23(d)')
for m in range(1,2):
print(m... |
import sys
import nmap
scan_row = []
input_data = input('Please input hosts and port: ')
scan_row = input_data.split(' ')
if len(scan_row) != 2:
print("Input errors, example \"192.168.209.0/24 80,443,22 \"")
sys.exit(0)
hosts = scan_row[0]
port = scan_row[1]
try:
nm = nmap.PortScanner()
except n... |
class LeapYear:
def __init__(self):
while True:
self.option = int(input("Enter option 1:[A.D.] or 2:[B.E.]: "))
self.statement = {
1: self.calculator_leap_year,
2: self.buddhist_era
}
try:
self.statement[self.op... |
def replaceWord(string, old_word, new_word):
return string.replace(old_word, new_word)
print(replaceWord('Hello world 123 world 123', 'world', 'bug'))
|
def listMulThree():
for num in range(1000):
if (num % 3 == 0):
print(num)
def listMulFive():
for num in range(1000):
if (num % 5 == 0):
print(num)
def addMuls():
sum = 0
for num in range(1000):
if (num % 3) == 0:
sum += num
if (num % ... |
"""
不可变类型
如果改变了类型的数据的值,地址 也发生了变化,这种类型的数据,是不可变类型的数据
常见类型
int float bool str tuple
可变类型
如果改变了该类型的数据的值,地址,没有 发生了变化,这种类型的数据,是可变类型的数据
常见类型
列表,字典,set集合
"""
a = 10
print(id(a))
a = 20
print(id(a))
print("*" * 50)
str1 = "hello"
print(id(str1))
str1 = "python"
print(id(str1))
print(... |
"""
and x and y 布尔"与": 并且的意思
如果 x 为 False,x and y 返回 False,否则它返回 y 的值。
True and False, 返回 False。
or x or y 布尔"或":
如果 x 是 True,它返回 True,否则它返回 y 的值。
False or True, 返回 True。
not not x 布尔"非":
如果 x 为 True,返回 False 。
如果 x 为 False,它返回 True。
not True 返回 False, not False 返回 True
"""
a = 10
b ... |
s1 = "hello python"
print(s1.find("aa"))
print(s1.find("o",6,11))
print(s1.find("pyt"))
print(s1.rfind("pyt"))
"""
index()方法,找不到将会报错
"""
print(s1.count("o"))
print(s1.count("o",6,12))
s2 = "hello python android"
list1 = s2.split(" ")
print(list1)
print(type(list1))
list2 = s2.partition(" ")
print(... |
import os
def rename():
path = "D:\\work\\nzpt\\new\\1"
file_list = os.listdir(path)
for files in file_list:
print("原来文件名字是是:", files)
old_name = os.path.join(path, files)
if os.path.isdir(old_name):
continue
file_name = os.path.splitext(files)[0]
... |
class FizzBuzz(object):
def __init__(self, number):
if FizzBuzz.is_valid_number(number):
self.number = number
@property
def result(self):
if self.number % 3 == 0 and self.number % 5 == 0:
return "FizzBuzz"
elif self.number % 3 == 0:
return "Fizz"
... |
def gravity(N, lst):
max_height = 0
for i in range(N-1):
count = 0
for j in range(i+1, N):
if lst[i] <= lst[j]:
count += 1
if max_height < N - (i+1) - count:
max_height = N - (i+1) - count
return max_height
N = int(input())
he... |
def Parentheses(arr):
stack = []
P = {'(': ')', '{': '}', '[': ']'}
for i in arr:
if i in P:
stack.append(i)
elif i in P.values():
if stack:
s = stack.pop()
if P[s] != i:
return 0
else:
... |
def Memory(bit):
count = 0
current = '0'
other = '1'
for i in bit:
if i != current:
current, other = other, current
count += 1
return count
T = int(input())
for test in range(1, T+1):
bit = input()
print(f'#{test}', Memory(bit)) |
def Factorization(N):
F = [2, 3, 5, 7, 11]
answer = []
for i in F:
count = 0
while N % i == 0:
count += 1
N //= i
answer.append(count)
return answer
T = int(input())
for test in range(1, T+1):
N = int(input())
result = Factorization(N)
print(f... |
dx = [1, -1, 0, 0]
dy = [0, 0, 1, -1]
def DFS(x, y):
global answer
if arr[x][y] == '3':
answer = 1
else:
arr[x][y] = '1'
for k in range(4):
ax = x + dx[k]
ay = y + dy[k]
if 0 <= ax < N and 0 <= ay < N and arr[ax][ay] != '1':
DFS(ax,... |
def my_circle(r):
return 3.14*r*r
def my_square(s):
return s**2
def my_rectange(b,h):
return b*h/2
choice = int(input("enter 1. Area of circle \n 2. Area of square \n 3. Area of rectangle \n 0. To exit"))
if choice==1:
var = eval(input("What is r? "))
print ("Area of Circle is : ",my_circle(var))
elif choice=... |
print(" -📋YOU HAVE TO DO✅- ")
options=["edit - add" , "delete"]
tasks_for_today=input("enter the asks you want to do today - ")
to_do=[]
to_do.append(tasks_for_today)
print("would you like to do modifications with your tasks? ")
edit=input("say yes if you would like edit your tasks - ")
if edit=="ye... |
"""
Given a sorted array nums, remove the duplicates in-place such that each element
appear only once and return the new length. Do not allocate extra space for
another array, you must do this by modifying the input array in-place with O(1)
extra memory
"""
class Solution:
def removeDuplicates(self, nums):
... |
"""
A class to hold a bunch of simple, commonly-used utility functions.
"""
class Utils(object):
def __init__(self):
pass
def revcomp( self, seq ):
"""
Produce a reverse complement of the sequence.
"""
if 'U' in seq and not 'T' in seq:
return self... |
"""
Solution to Rosalind challenge "MRNA: Inferring mRNA from Protein"
See http://rosalind.info/problems/mrna for details.
Attention ROSALIND competitor: if you have not solved this particular
problem yet, it would be unfair to all the other competitoris if you
peruse this code, so please refrain from doing so.
... |
class Node:
def __init__(self,key,left=None,right=None,parent=None):
self.key = key
self.left = left
self.right = right
self.parent = parent
class BinarySearchTree:
def __init__(self):
self.root = None
def predecessor(self,key):
temp = self._predecessor(self._search(self.root,key))
... |
class Stack:
def __init__(self):
self.S = []
def push(self, a):
self.S.append(a)
|
class MaxPriorityQueue:
def __init__(self):
self.heap = []
def parent(self,i):
return i/2
def left(self,i):
return 2*i
def right(self,i):
return 2*i+1
def heap_size(self):
return len(self.heap)
def max_heap_insert(self,key):
self.heap.append(-9999999999)
self.heap_increase_key(self.h... |
class Queue:
def __init__(self):
self.Q = []
def isEmpty(self):
return self.Q == []
|
print ("Program To Find Sum of Three Digits")
def addition (a,b,c):
result=(a+b+c)
return result
a= int(input("Enter num one: "))
b= int(input("Enter num one: "))
c= int(input("Enter num one: "))
add_result= addition(a,b,c)
print(add_result)
|
'''
Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.
A subarray is a contiguous part of an array.
Example 1:
Input: nums = [-2,1,-3,4,-1,2,1,-5,4]
Output: 6
Explanation: [4,-1,2,1] has the largest sum = 6.
Example 2:
Input: nums ... |
'''
We define the usage of capitals in a word to be right when one of the following cases holds:
All letters in this word are capitals, like "USA".
All letters in this word are not capitals, like "leetcode".
Only the first letter in this word is capital, like "Google".
Given a string word, return true if the usage of ... |
from getpass import getpass
print("Welcome to Hang Man Game!")
word = ""
while word == "": word = getpass("Guess a word: ").lower()
word = list(word); word_pop = word.copy()
targeted = []
hint = input("later you want thow show : ").lower()
if hint != "":
for w in word:
if hint[0] == w: targeted.append(hi... |
def karatsuba_mult2(x,y):
if x < 10 or y < 10:
return x * y
else:
sx, sy = str(x), str(y)
m2 = max(len(sx), len(sy)) // 2
ix = len(sx) - m2
iy = len(sy) - m2
a, b = int(sx[:ix]), int(sx[ix:])
c, d = int(sy[:iy]), int(sy[iy:])
... |
wishlist = ["Microphone", "Monitor", "Camera", "Camera Lens"]
wishlist.append("Keyboard")
print(wishlist)
for x in wishlist:
print(x) |
""" function that adds a new attribute
to an object if it’s possible
"""
def add_attribute(self, name, new):
"""adds a new attribute to an object"""
try:
self.name = new
except:
raise TypeError('can\'t add new attribute')
|
if __name__ == '__main__':
f = [2]
for i in range(33):
f += [1, 2 * i + 2, 1]
up, down = 1, 1
for i in range(len(f) - 2, -1, -1):
newup = up + down * f[i]
up = down
down = newup
print(sum(map(int, list(str(down))))) |
import os
import csv
month_count = 0
net_revenue = 0
profit = 0
max_rev = 0
min_rev = 0
monthly_change = 0
dates = []
revenue = []
data_csv = os.path.join( "Resources", "budget_data.csv")
with open(data_csv) as csvfile:
csv_reader = csv.reader(csvfile, delimiter=",")
csv_header = next(csv_reader)
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.