text stringlengths 5 121k |
|---|
class Solution:
"""
@param colors: A list of integer
@param k: An integer
@return: nothing
"""
def sortColors2(self, colors, k):
... |
"""
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
this.val = val
this.left, this.right = None, None
"""
class Solution:
"""
@param a, b, the root of binary trees.
@return true if they are tweaked identical, or false.
"""
def isTweakedIdentical(self, a, b):
... |
"""
Definition of ListNode
class ListNode(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
"""
class Solution:
"""
@param head: The first node of linked list.
@return: The head of linked list.
"""
def insertionSortList(self, head):
d... |
import heapq
class Solution:
"""
@param {int} n an integer.
@return {int} the nth prime number as description.
"""
def nthUglyNumber(self, n):
ans = [1]
factors = [2, 3, 5]
times = [0] * len(factors)
values = []
for i in range(len(factors)):
... |
"""
Definition of Interval.
class Interval(object):
def __init__(self, start, end):
self.start = start
self.end = end
"""
class Solution:
def countOfAirplanes(self, airplanes):
airs = []
for interval in airplanes:
s, e = interval.start, interval.e... |
import random
class Solution:
def sortNutsAndBolts(self, nuts, bolts, compare):
def helper(left, right, nuts, bolts, compare):
if left >= right:
return
boltIndex = random.randint(left, right)
target = nuts[boltIndex]
... |
class Solution:
"""
@param x: An integer
@return: The sqrt of x
"""
def sqrt(self, x):
left, right = 0, x
while left + 1 < right:
mid = left + (right - left) / 2
if mid * mid <= x:
left = mid
else:
... |
class Solution:
"""
@param A : an integer ratated sorted array and duplicates are allowed
@param target : an integer to be searched
@return : a boolean
"""
def search(self, A, target):
if not A:
return False
left, right = 0, len(A) - 1
while left + 1... |
"""
Definition of ListNode
class ListNode(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
"""
class Solution:
"""
@param hashTable: A list of The first node of linked list
@return: A list of The first node of linked list which have twice size
"""
def... |
"""
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
class Solution:
"""
@param root: The root of binary tree.
@return: Preorder in ArrayList which contains node values.
"""
def preorderTraversal(self, root):... |
"""
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
class Solution:
"""
@param inorder : A list of integers that inorder traversal of a tree
@param postorder : A list of integers that postorder traversal of a tree
... |
class Teacher(object):
__slots__ = ('name', 'age')
pass
def set_name(self, name):
self.name = name
def set_age(self, age):
self.age = age
if __name__ == '__main__':
teacher = Teacher()
from types import MethodType
teacher.set_name = MethodType(set_name, teacher)
teach... |
'''
__author__ = 'sunp'
__date__ = '2019/1/27'
Given a list of bytes a, each representing one byte of a larger integer (ie. {0x12, 0x34, 0x56, 0x78} represents the integer 0x12345678), and an integer b, find a % b.
mod({0x03, 0xED}, 10) = 5
'''
def mod(bits, num):
res = 0
for bit in bits:
res = (r... |
'''
__author__ = 'sunp'
__date__ = '2019/2/17'
Given a binary tree, write a function to determine whether the tree is balanced.
- all branches are same height(±1).
- all subtrees are balanced.
'''
class TreeNode(object):
def __init__(self, val, left=None, right=None):
self.val = val
self.left ... |
'''
__author__ = 'sunp'
__date__ = '2019/1/26'
Given a stack, sort the elements in the stack using one additional stack.
'''
def sort1(stack):
buf1, buf2 = [], []
while stack:
top = stack.pop()
while buf1 and buf1[-1] > top:
buf2.append(buf1.pop())
buf1.append(top)
... |
'''
__author__ = 'sunp'
__date__ = '2019/1/24'
Given a boolean matrix, update it so that if any cell is true, all the cells in that row and column are true.
[true, false, false] [true, true, true ]
[false, false, false] -> [true, false, false]
[false, false, false] [true, false, false]
'''
def ze... |
'''
__author__ = 'sunp'
__date__ = '2019/1/27'
Given two integers, write a function that swaps them without using any temporary variables.
'''
def swap1(num1, num2):
num1 = num1 ^ num2
num2 = num1 ^ num2
num1 = num1 ^ num2
return num1, num2
def swap2(num1, num2):
num1 = num1 + num2
num2 =... |
'''
__author__ = 'sunp'
__date__ = '2019/1/24'
Given a 2D array of 1s and 0s, find the largest square subarray of all 1s.
subarray([1, 1, 1, 0]
[1, 1, 1, 1]
[1, 1, 0, 0]) = 2
'''
def subarray1(matrix):
if not matrix or not matrix[0]:
return 0
m, n = len(matrix), len(matrix[0... |
import Divider
import Gange
import Plus
import Minus
while(True):
print("[1] Divider")
print("[2] Gange")
print("[3] Plus")
print("[4] Minus")
Choice = input("Please choose an option")
if Choice == "1":
number1 = int(input("Choose the first number"))
number2 = int(input("Choose t... |
import unittest
from calculator import Calculator
calculator = Calculator()
class TestCalculator(unittest.TestCase):
def test_calculate0(self):
question = "1+2+3+5+7"
self.assertEqual(calculator.calculate(question), eval(question))
def test_calculate01(self):
question = "11.5+12.5+3... |
import math
def pearsons(r, i, j, num_items):
""" Computes pearsons similarity coefficient
parameters
r -- vector of ratings, where r[i][k] represents the rating user i gave to item k
i -- user i
j -- user j
num_items -- number of items
"""
... |
def Collatz_Sequence(num):
Result = [num]
while num != 1:
if num % 2 == 0:
num = num/2
else:
num = 3*num+1
Result.append(num)
return Result
if __name__ == "__main__":
num = int(input("Enter a Number: "))
print(Collatz_Sequence(num)) |
def Remove_Tuple(Test_list, K):
return [elements for elements in Test_list if len(elements) != K]
Test_list = [(4, 5), (4, ), (8, 6, 7), (1, ), (3, 4, 6, 7)]
K = int(input("Enter K: "))
print(Remove_Tuple(Test_list, K))
|
import calendar
def Leap_Year(Test_input):
count = 0
Result = []
while count < 15:
if calendar.isleap(Test_input):
Result.append(Test_input)
count += 1
Test_input += 1
return Result
Test_input = int(input("Enter Year: "))
print(Leap_Year(Test_inpu... |
import re
def String_start_with_Substring(Test_string, Test_sample):
Result = "^"+Test_sample
if re.search(Result, Test_string):
return "True"
else:
return "False"
Test_string = "100 Days of Code Challenge makes your basic clear"
Test_sample = "100"
print(String_start_with_S... |
from collections import Counter
def Max_Anagram(Test_string):
for i in range(0, len(Test_string.split(" "))):
Test_string[i] = ''.join(sorted(Test_string[i]))
Dict_Frequency = Counter(Test_string)
return max(Dict_Frequency.values())
if __name__ == "__main__":
Test_string = 'ant ma... |
import math
def check_Perfect_Square(m):
semifinal = int(math.sqrt(m))
if pow(semifinal, 2) == m:
return True
return False
def fibo(n):
t1 = 5*n*n+4
t2 = 5*n*n-4
if check_Perfect_Square(t1) or check_Perfect_Square(t2):
return True
else:
return False
a = int(input... |
def Final_Product(Check_list):
Prod = 1
for ele in Check_list:
Prod *= ele
return Prod
def Product_Matrix(Test_list):
Semi_Result = Final_Product(
[element for ele in Test_list for element in ele])
return Semi_Result
Test_list = [[1, 4, 5], [7, 3], [4], [46, 7, 3]]
... |
def Remove_Duplicates(Test_string):
Test_list = []
for elements in Test_string.split(" "):
if ((Test_string.count(elements) > 1 or Test_string.count(elements) == 1) and elements not in Test_list):
Test_list.append(elements)
return Test_list
Test_string = input("Enter a String: ... |
def divisor(num):
Result = []
for i in range(1, int(num)):
if num % i == 0:
Result.append(i)
return Result
def triangular_number(num):
count = True
natural = 1
while count:
ctr = (natural*(natural+1))/2
if len(divisor(ctr)) >= num:
... |
import re
def Starts_End(Pattern, Test_string):
if re.search(Pattern, Test_string):
print("Valid...")
else:
print("Invalid...")
if __name__ == "__main__":
Pattern = r'^[a-z]$|^([a-z]).*\1$'
Test_string = "abba"
Starts_End(Pattern, Test_string)
|
import re
def Vowel_String(Test_string):
pattern = "^[aeiouAEIOU][a-zA-Z0-9]*"
if re.search(pattern, Test_string):
print("Accepted")
else:
print("Discarded")
Test_string1 = "code"
Test_string2 = "expression20"
Vowel_String(Test_string1)
Vowel_String(Test_string2)
|
def solve(heads, legs):
error_msg = "No solution"
chicken_count = 0
rabbit_count = 0
if legs % 2 != 0:
print("No Solution")
else:
rabbit_count = (legs-2*heads)/2
chicken_count = (4*heads-legs)/2
print(int(chicken_count))
print(int(rabbit_count))
... |
from collections import Counter
def Check_Binary_Representation(Num_1, Num_2):
Bin_1 = bin(Num_1)[2:]
Bin_2 = bin(Num_2)[2:]
Zeroes = abs(len(Bin_1)-len(Bin_2))
if len(Bin_2) > len(Bin_1):
Bin_1 = Zeroes*'0'+Bin_1
else:
Bin_2 = Zeroes*'0'+Bin_2
Dict_1 = Counter(Bin_1... |
import sys
Tuple_1 = ("A", 1, "B", 2, "C", 3)
Tuple_2 = ("Geek1", "Satyam", "hey you yeah you", "Tushar", "Geek3", "Aditya")
Tuple_3 = ((1, "Lion"), (2, "Tiger"), (3, "Fox"), (4, "Wolf"))
print(f"Size of Tuple_1: {str(sys.getsizeof(Tuple_1))} bytes")
print(f"Size of Tuple_2: {str(sys.getsizeof(Tuple_2))} bytes")
... |
def Counting_the_frequency(Test_list):
Test_dict = {}
for items in Test_list:
Test_dict[items] = Test_list.count(items)
for key, value in Test_dict.items():
print(f"{key} : {value}")
Test_list = [1, 1, 1, 5, 5, 3, 1, 3, 3, 1, 4, 4, 4, 2, 2, 2, 2]
Counting_the_frequency(Test_list) |
def encode(Test_string):
count = 1
Result = ""
for i in range(len(Test_string)):
if (i+1) < len(Test_string) and (Test_string[i] == Test_string[i+1]):
count += 1
else:
Result += str(count)+Test_string[i]
count = 1
return Result
print(enco... |
from operator import itemgetter
def Sort_list_Name_and_Age(Test_list):
Test_list.sort(key=itemgetter("Age", "Name"))
return Test_list
def Sort_list_Age(Test_list):
Test_list.sort(key=itemgetter('Age'))
return Test_list
Test_list = [{"Name": "Tushar", "Age": 20},
{"Name":... |
def Sort_Tuple(Test_list):
Test_list.sort(key=lambda Sub: max(Sub), reverse=True)
return Test_list
Test_list = [(4, 5, 5, 7), (1, 3, 7, 4), (19, 4, 5, 3), (1, 2)]
print(Sort_Tuple(Test_list))
|
from collections import defaultdict
def Join_Tuples(Test_list):
Result = defaultdict(list)
for key, value in Test_list:
Result[key].append(value)
return [(key, *value) for key, value in Result.items()]
Test_list = [(5, 6), (5, 7), (6, 8), (6, 10), (7, 13)]
print(Join_Tuples(Test_list)... |
def Maximum_Key(Test_list):
Result = {}
for dictionary in Test_list:
for key, value in dictionary.items():
if key in Result:
Result[key] = max(Result[key], value)
else:
Result[key] = value
return Result
Test_list = [{"Days": 8, "Co... |
def Palindrome(Test_String):
if Test_String == Test_String[::-1]:
return True
else:
return False
Test_String = input("Enter a String: ")
print(Palindrome(Test_String))
|
def Remove_Keys(Test_dict, Remove_Value):
return {key: value for key, value in Test_dict.items() if key != Remove_Value}
N_value = int(input("Enter n: "))
Test_dict = {}
for i in range(N_value):
key = input("Key: ")
Value = int(input("Value: "))
Test_dict[key] = Value
Remove_Value = input("W... |
def Extract_Dictionary_Values(Test_dict):
return [sorted({numbers for ele in Test_dict.values() for numbers in ele})]
Test_dict = {'Challenges': [5, 6, 7, 8],
'are': [10, 11, 7, 5],
'best': [6, 12, 10, 8],
'for': [1, 2, 5]}
print(*(Extract_Dictionary_Values(Test_dict... |
def insertar():
lista = []
b = True
while b:
dato = input("Ingrese un dato para agregar a la lista: ")
cond = input("Desea ingresar otro valor y/n: ")
lista.append(dato)
b = True if cond == "y" else print(lista)
insertar()
|
from random import randint as ri
computador = ri(1,6)
usuario = int(input('Dame un numero entre el 1 y el 6:\n'))
print(f'El computador saco: {computador}')
if computador == usuario:
print('\n**********')
print('Hay un empate')
print('**********')
elif computador > usuario:
print('\n*******... |
def main(inFileStr):
inFile = open(inFileStr, "r")
numVec = inFile.readline()
if numVec == 0:
return "YES"
else:
return addVectors(int(numVec), inFile)
def addVectors(numVec, inFileObj):
x, y, z = 0, 0, 0
for i in range(numVec - 1, -1, -1):
xi, yi, zi = divideInputs(inFileObj)
if i =... |
import sys
def print_tables(objects, colnames, formatter):
formatter.headings(colnames)
for obj in objects:
rowdata = [str(getattr(obj, colname)) for colname in colnames]
formatter.row(rowdata)
class TableFormatter(object):
def __init__(self, outfile=None):
if outfile... |
from Vector import Vector
vec=Vector(1.356,2.434)
print("vec:",vec)
print('vec.__repr__():',vec.__repr__())
vec2=Vector(3.65576,1.4785)
vec3 = vec + vec2
print(vec,'+',vec2,'=',vec3)
vec3 = vec - vec2
print(vec,'-',vec2,'=',vec3)
vec4 = vec * 3
print(vec,'* 3 =',vec4)
vec4 = 3 * vec
pr... |
import numpy as np
import util
import pandas as pd
import matplotlib.pyplot as plt
def main(lr, train_path, eval_path, save_path):
"""Problem: Poisson regression with gradient ascent.
Args:
lr: Learning rate for gradient ascent.
train_path: Path to CSV file containing dataset for tra... |
from nltk.corpus import wordnet as wn
import string
import numpy
import matplotlib.pyplot as plt
goodDays = 0
badDays = 0
neutralDays = 0
goodWords = 0
badWords = 0
neutralWords = 0
kfile = open("tests/keywords.txt", "r", encoding="utf‐8")
dictk = {}
words = kfile.readlines()
for i in range(len(words)... |
from .actor import Actor
class Enemy(Actor):
def __init__(self, pos, radius, color, max_health, pcb1, pcb2, pcb3, img=None):
super().__init__(pos=pos, radius=radius, color=color, img=img)
self.health = max_health
self.max_health = max_health
self.phase = 0
self.damage = 0
... |
import random
movi = ["baghi","ddlj","raazi","parmanu","newton"]
actor = ["hritik","varun","sidharth","arjun"]
profession = ["student","teacher","enterpreneur","farmer","pilote"]
fastfood = ["choumin","springroll","sandwich","noodles","burger"]
list_of_list = [movi,actor,profession,fastfood]
def shuffel_and_choos... |
phonebook = {
'John':999,
'Jack':888,
'Jill':777
}
print(phonebook)
for name,tel in phonebook.items():
print('%s has phone number is %s' %(name,tel))
print('Delete item')
del phonebook['Jill']
print(phonebook)
print('Update and Add item')
phonebook.update({'AAA':222})
phonebook.update({'Jack':555}... |
"""
@Author : ziheng.ni
@Time : 2021/2/7 16:57
@Contact : nzh199266@163.com
@Desc :
"""
from __future__ import annotations
from abc import ABC, abstractmethod
from create_mode.factory_method.product import Product, Truck, Ship
class Creator(ABC):
"""
构造器抽象类。
factory_method方法用于所有子类提供实例化后的对象。
... |
SUPPORTED = set('/*-+')
OPERATORS = {
'/': lambda a, b: a / b,
'*': lambda a, b: a * b,
'-': lambda a, b: a - b,
'+': lambda a, b: a + b,
}
class Node(object):
"""Tree node"""
def __init__(self, data):
self.l = None
self.r = None
self.data = data
... |
import math
class Vector3:
x = y = z = 0.0
def __init__(self, x=0.0, y=0.0, z=0.0):
self.x = x
self.y = y
self.z = z
def __add__(self, other):
return Vector3(self.x + other.x, self.y + other.y, self.z + other.z)
def __sub__(self, other):
return Vector3(s... |
desired_total = 200
denominations = (1,2,5,10,20,50,100,200)
def resolve(solutions):
additions = set()
deletions = set()
for solution in solutions:
current_total = sum(solution)
if current_total < desired_total:
deletions.add(solution)
for coin in denominations:
... |
class Fraction:
def __init__(self, numerator, denominator):
self.numerator = numerator
self.denominator = denominator
def __eq__(self, other):
return self.numerator == other.numerator and self.denominator == other.denominator
def __str__(self):
return '{}/{}'.format(self.nu... |
sum_of_squares = 0
sum_to_be_squared = 0
for i in range(1, 101):
sum_of_squares += i ** 2
sum_to_be_squared += i
difference = (sum_to_be_squared ** 2) - sum_of_squares
print("sum square difference is: ", difference)
|
from functools import reduce
def sum_digits(n):
i = [int(d) for d in str(n)]
result = reduce(lambda x, y: x+y, i)
return result
if __name__ == '__main__':
num = 2**1000
answer = sum_digits(num)
print(answer)
|
import time
import functools
def memoize(func):
"""Wrapper function to cache function results"""
memo = {}
@functools.wraps(func)
def wrapper(key):
if key in memo:
return memo[key]
else:
memo[key] = func(key)
return memo[key]
return wrapper
de... |
MAX_PRIME = 1000000
sieve = [None] * MAX_PRIME
sieve[0] = False
sieve[1] = False
for x in range(2,MAX_PRIME):
if sieve[x] is None:
sieve[x] = True
for y in range(x*2, MAX_PRIME, x):
sieve[y] = False
primes = set(n for n,is_prime in enumerate(sieve) if is_prime)
def truncate(d, revers... |
import time
def fibsumeven(x):
res1 = 1
res2 = 1
evens = 0
sum = 0
while sum < 4000000:
sum = res1 + res2
res1, res2 = res2, sum
if (sum % 2 == 0):
evens += sum
return evens
start = time.time()
print (fibsumeven(35))
end = time.time()
print(end - start)
|
class Student(object):
def __init__(self, name, score):
self.__name = name
self.__score = score
def print_score(self):
print('%s: %s' %(self.__name, self.__score))
def get_name(self):
return self.__name;
def get_score(self):
return self.__score;
def set_na... |
a = 10;
b = 10;
if a > b :
print("a > b")
elif (a == b):
print ("a = b")
else:
print ("a < b") |
def countdown(n):
print("Count down!");
while n > 0:
yield (n)
n -= 1;
for i in countdown(10):
print(i);
|
from collections import Iterable
d= {'a':1,'b':2,'c':3,'d':4}
for key in d:
print(key, d.get(key))
for k,v in d.items():
print("key:"+k,v);
for ch in 'ABCD':
print(ch)
print(isinstance('abc',Iterable))
print(isinstance([1,2,3],Iterable))
for i, va in enumerate(['A','b','d']):
print(i, va)
print("... |
def concat(*args , sep ='/'):
return sep.join(args);
result = concat("earth","mars","venus");
print(result);
result1 = concat("earth","mars","venus",sep =".");
print(result1);
list1 = list(range(3,6))
print(list1);
args = [3,6]
list2 = list(range(*args))
print(list2);
def make_inc(n):
return lambda x: ... |
while True:
try:
x = int(input(("please enter a num:")))
break
except ValueError:
print("Oops! That was no valud num. try again...") |
'''
File Name: Main.py
Author: Hemang Shimpi
Date Created: 12/19/20
Date last modified: 12/25/20
Language: Python
Gui: Tkinter
'''
from tkinter import *
from tkinter import ttk
from tkinter import messagebox
from LoginPage import LoginPage
def main():
window = Tk()
window.re... |
import shutil
import os
import re
def main():
date_pattern = re.compile(r"""~(.*?)
((0|1)?\d)-
((0|1|2|3)?\d)-
(.*?)$
""", re.VERBOSE)
for amer_filename in os.listdir('.'):
mo = date_pattern.search(amer_filename)
if mo == None:
continue
before_part = m... |
import os
import zipfile
from pathlib import Path
def backup_to_zip(folder):
folder = Path(folder).absolute
number = 1
while True:
zip_filename = Path(f'{folder}_{str(number)}.zip')
if not Path(zip_filename).exists:
break
number = number + 1
print(f'Creating{zip... |
'''
Created on 2015年4月11日
@author: Rong
'''
movies = ["a", "b", ["c", ["d", "e"]]]
for eachitem in movies:
if isinstance(eachitem, list) == False:
print(eachitem)
else:
for a in eachitem:
if isinstance(a, list) ==False:
print (a)
... |
"""
Problem Link: https://www.hackerrank.com/challenges/migratory-birds
Time Complexity : O(N)
Space Complexity: O(M) ; M : Distinct Numbers
"""
def migratoryBirds(arr):
count = [0]*6
for i in arr:
count[i] += 1
return count.index(max(count))
if __name__ == "__main__":
... |
import string
letters = string.ascii_lowercase + string.ascii_uppercase
strng = """The stump thunk the skunk stunk and the skunk thunk the stump stunk."""
def count(p):
counter = 0
e = 0
for char in p:
if char in letters:
counter = counter + 1
if char == "e" or char... |
import turtle
import time
def draw_triangle(points,color,t):
t.fillcolor(color)
t.up()
t.goto(points[0][0],points[0][1])
t.down()
t.begin_fill()
t.goto(points[1][0],points[1][1])
t.goto(points[2][0],points[2][1])
t.goto(points[0][0],points[0][1])
t.end_fill()
def get_mid(p1, p2):
... |
import tkinter as tk
from tkinter import ttk
from tkinter import messagebox
from tkinter import simpledialog
window = tk.Tk()
answer = simpledialog.askstring("input", "WHat is your first name?", parent=window)
if answer is not None:
print("Hello ", answer)
else:
print("hello annonymous user")
an... |
import string
book = open("alice_in_wonderland.txt", "r")
count = {}
longest_word = ""
for line in book:
for word in line.split():
word = word.replace('_', '').replace('"', '').replace(',', '').replace('.', '')
word = word.replace('-', '').replace('?', '').repl... |
import turtle
import random
def branch_width(branchLen, t):
if branchLen > 60:
t.width(6)
elif branchLen > 45:
t.width(4)
elif branchLen > 30:
t.width(3)
elif branchLen > 15:
t.width(2)
def draw_leaves(branchLen, t, color, degrees):
t.fi... |
from random import randint
n = (randint(1, 10), randint(1, 10), randint(1, 10), randint(1, 10), randint(1, 10))
print(f"Eu sorteei os valores {n}")
print(f"O maior valor sorteado foi {max(n)}")
print(f"O menor valor sorteado foi {min(n)}") |
tabuada = int(input("Tabuada do numero: "))
for c in range(1, 11):
print("{} X {} = {}".format(tabuada, c, tabuada*(c)))
|
double = lambda x: x * 2
triple = lambda x: x * 3
square_root = lambda x: x * x
print(double(10) == 20)
print(double(5) == 10)
print(triple(10) == 30)
print(square_root(10) == 100) |
students = []
def titlecase(element: str) -> str:
to_return = []
words = element.split(" ")
for word in words:
titlecased = word[0].upper() + word[1:].lower()
to_return.append(titlecased)
return " ".join(to_return)
def add_student(name:str, student_id:int = -1):
student = {
... |
students = [
{"name":"majid hussain khattak","id":1},
{"name":"majid","id":2},
{"name":"h","id":3},
{"name":"MAJID HUSSAIN KHATTAK","id":4}
]
countIndex = 0
def get_student_titlecase(students):
titledcased = []
for student in students:
print(student)
return titledcased
def titleca... |
a=1
b="abc"
print(type(1))
print(type(int))
print(type(b))
print(type(str))
class Student:
pass
print(type(Student))
a=[1,2]
print(type(a))
print(type(list))
print(Student.__bases__)
class My_Student(Student):
pass
print(My_Student.__bases__)
print(type(object))
print(type(int.__bases__))
print(type(tupl... |
class Company(object):
def __init__(self,employee_list):
self.employee = employee_list
def __len__(self):
return len(self.employee)
com = Company(["TT1","TT2","TT3"])
from collections.abc import *
print(isinstance(com,Sized))
import abc
import abc
class CacheBase(m... |
import threading
from threading import Lock,RLock
total = 0
lock = RLock()
def add():
global lock
global total
for i in range(1000000):
lock.acquire()
lock.acquire()
total += 1
lock.release()
lock.release()
def desc():
global lock
global total
for i in ra... |
import bisect
inter_list = []
bisect.insort(inter_list,3)
bisect.insort(inter_list,2)
bisect.insort(inter_list,5)
bisect.insort(inter_list,1)
bisect.insort(inter_list,6)
print(bisect.bisect_left(inter_list,3))
print(inter_list) |
from turtle import Turtle, Screen
from snake import Snake
from food import Food
from scoreboard import Scoreboard
import time
"""Screen setup"""
screen = Screen()
screen.setup(width=600,height=600)
screen.bgcolor("black")
screen.title("Timmy Snake Game")
screen.tracer(0)
"""Initial 3 segments of snake named Timmy""... |
class Operations:
def __init__(self):
pass
def aboveBelow(self, values, comparison):
dict = {"above": 0, "below": 0}
if not isinstance(comparison, int) or not isinstance(values, list):
return False
for value in values:
if not isinstan... |
kanye_quote = ('My greatest pain in life is that I will never '
'be able to see myself perform live.')
print(kanye_quote)
hamilton_quote = 'Well, the word got around, they said, "This kid is insane, man"'
print(hamilton_quote)
print(kanye_quote.upper())
print(kanye_quote.lower())
print("ok fine".replace("fine", ... |
import threading
import time
class MyThread(threading.Thread):
def __init__(self, threadID, name, counter):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
self.counter = counter
def run(self):
print("Starting", self.name, "\n")
thread_lock.acquire()
print_time(s... |
import numpy as np
def celebrity():
n = int(input("Enter the number of people"))
matrix = []
for i in range(n):
a = []
for j in range(n):
k = int(input())
val = check(k)
a.append(val)
matrix.append(a)
for i in range(n):
for j ... |
"""
Exam 3, problem 2.
Authors: Vibha Alangar, Aaron Wilkin, David Mutchler, Dave Fisher,
Matt Boutell, Amanda Stouder, their colleagues and
Daniel Su. January 2019.
"""
def main():
""" Calls the TEST functions in this module. """
run_test_shape()
def run_test_shape():
""" T... |
'''
Determine if any 3 integers in an array sum to 0.
For example, for array [4, 3, -1, 2, -2, 10], the function
should return true since 3 + (-1) + (-2) = 0. To make things simple,
each number can be used at most once.
'''
'''
1. Naive Solution is to test every 3 numbers to test if it is zero
2. is it possible to c... |
"""
Definition of ListNode
class ListNode(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
"""
class Solution:
"""
@param head: The head of linked list
@param m: start position
@param n: end position
"""
def reverseBetween(self, head, m, n):... |
class Solution:
"""
@param S: The set of numbers.
@return: A list of lists. See example.
"""
def subsets(self, S):
res = []
S.sort()
self.search(S, [], 0, res)
return res
def search(self, nums, temp, index, res):
if index == len(nums):
... |
class Solution:
"""
@param matrix, a list of lists of integers
@param target, an integer
@return a boolean, indicate whether matrix contains target
"""
def searchMatrix(self, matrix, target):
for row in matrix:
if target in row:
return True
re... |
class Solution:
def swapNodes(self, head, v1, v2):
if not head:
return head
dummyhead = ListNode("#")
dummyhead.next = head
ptr1 = dummyhead
while ptr1.next and ptr1.next.val != v1:
ptr1 = ptr1.next
ptr2 =... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.