text stringlengths 37 1.41M |
|---|
# Helper functions
import re
from MathematicalOperations import *
def EvaluateParentheses(string): # Evaluates all the expressions inside parentheses
parenthetical_ops = [] # stores all the sums inside parentheses
parenthetical_results = [] # stores the results of the sums inside the parenth... |
number1 = int(input("First number: "))
number2 = int(input("Second number: "))
operation = input("Operation [+, -, *, /]: ")
if operation == "+":
combination = number1 + number2
elif operation == "-":
combination = number1 - number2
elif operation == "*":
combination = number1 * number2
e... |
def self_powers(number):
return sum(n ** n for n in range(1, number + 1))
def test_self_powers():
assert self_powers(10) == 10405071317
print(str(self_powers(1000))[-10:])
|
import itertools
def is_magic(ring):
groups = ring_groups(ring)
return all(sum(group) == sum(groups[0]) for group in groups)
def ring_groups(ring):
length = len(ring) // 2
outer = ring[:length]
inner = ring[length:]
return [[outer[i], inner[i], inner[(i + 1) % length]] for i in range(length)... |
visited = {}
def step(x, y, size):
if (x, y) in visited:
return visited[(x, y)]
right = down = final = 0
if x < size:
right = step(x+1, y, size)
if y < size:
down = step(x, y+1, size)
if x == size and y == size:
final = 1
visited[(x, y)] = right + down + final
... |
import turtle
turtle.shape("turtle")
turtle.color("pink")
turtle.width("10")
turtle.penup()
turtle.home()
def thing(that):
turtle.right(90)
turtle.forward(that*2)
turtle.right(90)
turtle.forward(that*1.5)
turtle.left(180)
turtle.pendown()
turtle.circle(that)
turtle.penup()
turtle.for... |
import numpy as np
import nnfs
from nnfs.datasets import spiral_data
#axis 0 means row wise and 1 means columns wise
nnfs.init()
# Dense layer
class Layer_Dense:
# Layer initialization
def __init__(self, n_inputs, n_neurons):
# Initialize weights and biases
self.weights = 0.01 * np.random.... |
# Functions with Inputs
def personal_greeting(name):
print(f"Hello {name} 👋")
personal_greeting("Hannah")
# Positional vs. Keyword Arguments
def greet_with(name, location):
print(f"Hello {name} 👋")
print(f"What is it like in {location}? 🌍")
greet_with("Hannah", "Gold Goast")
# Positional Arguments
greet_wit... |
# (nested) if-else statements, comparison operators (>, <, <=, >=, ==, !=)
# elif
# Multiple conditions (multiple if statements in succession)
print("Welcome to the rollercoaster 🎢")
height = int(input("What is your height in cm? "))
bill = 0
if height >= 120:
print("You can ride the rollercoaster!")
age = int(in... |
class Node:
def __init__(self, item, next=None):
self.item = item
self.next = next
class Queue:
def __init__(self):
self.queueFront = None
self.queueBack = None
self.size = 0
def destroyQueue(self):
self.queueFront = None
self.queueBack = None
... |
import time
from colorama import init, Fore
init(autoreset=True)
'''Stretch goal explanation:
Write a program to determine if a number, given on the command line, is prime.
1. How can you optimize this program?
2. Implement [The Sieve of
Eratosthenes](https://en.wikipedia.org/wiki/Sieve_of_Eratosthe... |
"""My calculator object"""
class Calculator:
"""My constant #1"""
CONSTANT_VAR = 4
"""My constant #2"""
CONSTANT_VAR_2 = 5
def __init__(self):
"""Initialization funciton"""
self.public_var = 1
self._protected_var = 2
self.__private_var = 3
def _protected_functi... |
'''
References:
https://stackoverflow.com/questions/6545023/how-to-sort-ip-addresses-stored-in-dictionary-in-python/6545090#6545090
https://stackoverflow.com/questions/20944483/python-3-sort-a-dict-by-its-values
https://docs.python.org/3.3/tutorial/datastructures.html
https://www.quora.com/How-do-I-write-a-dictionary-t... |
# process CSV files
# find rank 1~3 for all subjects
def get_top_threes(file_in,file_out):
# sort by last name
def sort_lastname(ls):
if len(ls) == 1:
return ls
else:
r = []
for name in ls:
sep = name.split(' ')
sep.reverse()
... |
#basic numeric operations
a = 10
b = 20
print(a+b)
print(a-b)
print(a*b)
print(a/b)
my_salary = 10000
tax_percentage = 0.2
taxes = my_salary * tax_percentage
print(taxes)
|
from ..preprocessing import preprocess_text
import pandas as pd
from sklearn.feature_extraction.text import TfidfVectorizer
# sample documents
# change these to see what happens to the cell values
document_1 = "This is a sample sentence!"
document_2 = "I love to code."
document_3 = "Jesus loves you!"
# corpus of docu... |
import functools
def average(sample: list) -> float:
sum = functools.reduce(lambda previous, actual: previous + actual, sample)
return sum / len(sample)
def median(sample: list) -> float:
sample.sort()
index = len(sample) // 2
if (len(sample) % 2) == 0:
return average([sample[index - 1],... |
#1:
#这是一个将函数里所有传进来的参数相加的函数
def test(a,b,*args):#末尾参数前加一个×号
print(a)
print(b)
print(*args)
sum=a+b
for i in args:
sum+=i
print(sum)
# args是一个元组
#元组若是元素为一个,后面要跟一个逗号,否则不为元组
#2:
def test(a,b,*args,**kwargs):#kwargs 用字典存带名字的多余参数
print(a)
print(b)
print(args)
print(kwargs)
test(1,2,3,5,5,66,4,9,8,2,5,58,5,5)
#te... |
# -*- coding: utf-8 -*-
"""
Created on 2019/10/2
@author: yhy
类定义:
1.cell类
2.strip类
3.rectangle类
4.grid类,也是就是图像类,用来创建一个多边形和其所在网格(grid)
存在问题2020.3.4:
如果一个grid类在定义的时候,给定的在多边形内部的hole如果是有一条边与多边形的边重叠的话
此时多边形的边应该更新为hole中不与其重叠的另外三个边。多边形的顶点也应该发生变化。
然而,该程序目前并不能完成这一功能,也就是说系统依然判定,多边形的被重叠边为多边形边界
总而言之就是存在hole与多边形有边... |
# here is example to use Experiment Collector with tensorflow 2.0
# load tensorflow and Experimental Collector
import tensorflow as tf
from experimentcollector import ExperimentCollector
# create Collector object
# database will be store into memory by default
collector = ExperimentCollector()
# define tensorflow's... |
"""Code Challenge: Solve the Eulerian Cycle Problem.
Input: The adjacency list of an Eulerian directed graph.
Output: An Eulerian cycle in this graph.
"""
def eulerianCycle(graph):
#First, we are going to store for each node the number of edges that are emerging from them
#That's why we'll need a dictio... |
import sys
import math
import time
class Vertex:
def __init__(self, id, x, y):
self.id = id
self.x = x
self.y = y
class Graph:
def __init__(self):
# list of cities
self.vertices = []
# 2D matrix of distances between city pairs
self.distances = []
... |
'''\033[1;31;45m] #\codigo de cor[estilo;texto;background m]'''
print('\033[7;30mOlá mundo\033[m')
print('\033[0;33;44mOlá mundo\033[m')
print('\33[34mOlá mundo!\033[m')
print('\033[31mOlá mundo!')
cor = {'a' : '\033[34m', 'vm' : '\033[31m', 's' :'\033[m'}
print(f"{cor['a']}Arthur{cor['vm']} amaral {cor['a']}de {cor['... |
import random
l = input('primeiro:')
j = input('Segundo: ')
p = input('Terceiro: ')
a = input('Quarto: ')
r = [l, j, p, a]
random.shuffle(r)
print(f'O aluno escolhido foi {random.choice(r)}')
print(f'A ordem de apresentação dos trabalhos {r}') #OU
print(f'A ordem de apresentação dos trabalhos {random.sample(r,k=4)}')
... |
def main():
text = input("Text: ")
letters = 0
words = 1
sentences = 0
for c in text:
if ord(c.lower()) >= ord("a") and ord(c.lower()) <= ord("z"):
letters += 1
if c == " ":
words += 1
if(c == '.' or c == '?' or c == '!'):
sentences += 1
... |
countNum = 0
somaNum = 0
menorNum = pow(1000, 1000)
maiorNum = -1
escolha = "S"
while escolha != "N":
num = int(input("Digite um número: "))
countNum += 1
somaNum += num
if num < menorNum:
menorNum = num
if num > maiorNum:
maiorNum = num
escolha = input("Deseja continuar? [S / N... |
import math
num = float(input('Digite um número real: '))
print('Sua parte inteira é {}'.format(math.floor(num)))
|
times = ("Athlético PR", "Atlético GO", "Atlético MG", "Bahia", "Botafogo", "RB Bragantino", "Ceará", "Corinthians", "Coritiba", "Flamengo", "Fluminense", "Fortaleza", "Goiás", "Grêmio", "Internacional", "Palmeiras", "Santos", "São Paulo", "Sport", "Vasco")
print(f"Os 20 times do Brasileirão 2020 são: {times}")
print(f... |
'''
num = int(input("Digite o primeiro termo para uma P.A.: "))
razao = int(input("Digite a razão da P.A.: "))
n = 1
while n < 11:
if n == 1:
print(num)
else:
num = num + razao
print(num)
n = n + 1
'''
num = int(input("Digite o primeiro termo para uma P.A.: "))
razao = int(input("Di... |
cidade = input("Digite o nome de uma cidade: ").strip()
print("SANTO" in cidade.split()[0].upper())
|
from datetime import datetime
ano = int(input("Digite seu ano de nascimento: "))
now = datetime.now()
anoAtual = now.year
idade = anoAtual - ano
if idade == 18:
print("Está na hora de você se alistar para o exército")
elif idade < 18:
print("Ainda não chegou a hora de você se alistar para o exército. Faltam {... |
lista = []
decisao = "S"
while decisao.upper() == "S":
num = int(input("Digite um valor inteiro para adicionar à lista: "))
if num in lista:
print(f"O valor {num} já está na lista.")
else:
lista.append(num)
decisao = input("Deseja continuar? ")
lista.sort()
print(f"Lista final: {lista}"... |
soma = 0
for i in range(1, 10):
if i % 2 != 0 and i % 3 == 0:
soma += i
print("O resultado da soma é {}".format(soma))
|
palavras = ('programar', 'phyton', 'logica', 'desenvolvimento',
'string', 'curso', 'video', 'codificar',
'algoritmo', 'linguagem', 'programacao', 'pratica',
'teoria', 'javascript', 'automatizar', 'aprendizado')
for p in palavras:
print(f"\nNa palavra {p.upper()}, temos: ", end="... |
numOriginal = int(input("Digite um número: "))
num = numOriginal
fatorial = num
while num > 1:
fatorial = fatorial * (num - 1)
num = num - 1
print("A fatorial de {} é igual a {}".format(numOriginal, fatorial))
|
def mapear(funcao, lista):
'''
aplica uma função a cada elemento da lista
'''
return list(funcao(elemento) for elemento in lista)
def quadrado(x):
'''
eleva o numero ao quadrado
'''
return x**2
def raiz(x):
'''
calcula a raiz quadrada do numero
'''
return x**0.5
def di... |
def dice():
import random
min = 1
max = 6
roll_again = "yes"
while roll_again == "yes" or roll_again == "y":
print("Rolling the dices...")
print("The values are....")
print(random.randint(min, max))
print(random.randint(min, max))
roll_again = input("Roll t... |
import os
# création d'un dictionnaire avec des clés de type string
mondictionnaire = {}
mondictionnaire["pseudo"] = "Prolixe"
mondictionnaire["mot de passe"] = "*"
print(mondictionnaire)
# Ca fonctionne aussi avec d'autres type pour les clé
mon_dictionnaire = {}
mon_dictionnaire[0] = "a"
mon_dictionnaire[... |
# Runtime: O(n); beats 96.2%
# Space: O(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
class Solution:
def rob(self, root: TreeNode) -> int:
def post(node=root)... |
# Runtime: O(n); beats 552.13%
# Space: O(n)
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def rotateRight(self, head: ListNode, k: int) -> ListNode:
if not head or not k: return head
... |
# 953. Verifying an Alien Dictionary - EASY
# https://leetcode.com/problems/verifying-an-alien-dictionary/
# In an alien language, surprisingly they also use english lowercase letters, but possibly in a different order. The order of the alphabet is some permutation of lowercase letters.
# Given a sequence of words wr... |
# 234. Palindrome Linked List
# https://leetcode.com/problems/palindrome-linked-list/
# Given a singly linked list, determine if it is a palindrome.
# Example 1:
# Input: 1->2
# Output: false
# Example 2:
# Input: 1->2->2->1
# Output: true
# Follow up:
# Could you do it in O(n) time and O(1) space?
class ListNode... |
# 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
class Solution:
def pseudoPalindromicPaths (self, root: TreeNode) -> int:
def palindrome(node=root, has=set()):
... |
#
# @lc app=leetcode id=1455 lang=python3
#
# [1455] Check If a Word Occurs As a Prefix of Any Word in a Sentence
#
# @lc code=start
class Solution:
def isPrefixOfWord(self, sentence: str, searchWord: str) -> int:
for i, word in enumerate(sentence.split(' ')):
if len(searchWord) <= len(word) an... |
# Runtime: O(n); beats 56.74%
# Space: O(n)
"""
# Definition for a Node.
class Node:
def __init__(self, val: int = 0, left: 'Node' = None, right: 'Node' = None, next: 'Node' = None):
self.val = val
self.left = left
self.right = right
self.next = next
"""
class Solution:
def conn... |
# 47. Permutations II
# https://leetcode.com/problems/permutations-ii/
# Given a collection of numbers that might contain duplicates, return all possible unique permutations.
# Example:
# Input: [1,1,2]
# Output:
# [
# [1,1,2],
# [1,2,1],
# [2,1,1]
# ]
from typing import List
from copy import deepcopy
class So... |
# 104. Maximum Depth of Binary Tree - EASY
# https://leetcode.com/problems/maximum-depth-of-binary-tree/
# Given a binary tree, find its maximum depth.
# The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
# Note: A leaf is a node with no children.
# Ex... |
# 1048. Longest String Chain - MEDIUM
# https://leetcode.com/problems/longest-string-chain/
# Given a list of words, each word consists of English lowercase letters.
# Let's say word1 is a predecessor of word2 if and only if we can add exactly one letter anywhere in word1 to make it equal to word2. For example, "abc... |
# 704. Binary Search - EASY
# https://leetcode.com/problems/binary-search/
# Given a sorted(in ascending order) integer array nums of n elements and a target value, write a function to search target in nums. If target exists, then return its index, otherwise return -1.
# Example 1:
# Input: nums = [-1, 0, 3, 5, 9, ... |
# 63. Unique Paths II - MEDIUM
# https://leetcode.com/problems/unique-paths-ii/
# A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).
# The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (mark... |
# 463. Island Perimeter - EASY
# https://leetcode.com/problems/island-perimeter/
# You are given a map in form of a two-dimensional integer grid where 1 represents land and 0 represents water.
# Grid cells are connected horizontally/vertically (not diagonally). The grid is completely surrounded by water, and there is... |
# Runtime: O(nlogn); beats 98.66
# Space: O(n)
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def insertionSortList(self, head: ListNode) -> ListNode:
if not head: return head
dum... |
class Vehicle:
def __init__(self,make,mileage,capacity):
self.make=make
self.mileage=mileage
self.capacity=capacity
#def get_fare(self):
#print("fare of parent class")
# raise NotImplementedError("must implement get fare method")
#class Scooter(Vehicle):
#def __i... |
import random
from datetime import datetime
def randomNumArrayGen(max, length):
arr = []
for count in range(length):
arr.append(int(round(random.random()*max)))
return arr
def bubbleSort():
unsorted = randomNumArrayGen(10000,100)
endCheck = 1
#FOR TIMING
# var d = new Date();
# var startTime = d.... |
"""
A connection designed for connecting and disconnecting other connections
"""
__author__ = "Ron Remets"
import queue
from communication.connection import Connection
class Connector(Connection):
"""
A connection designed for connecting and disconnecting other
connections
"""
def __init__(self... |
"""
A class to organize a connection
"""
__author__ = "Ron Remets"
import enum
import logging
import threading
class ConnectionStatus(enum.Enum):
"""
The possible statuses of a connection
"""
NOT_STARTED = enum.auto()
CONNECTING = enum.auto()
CONNECTED = enum.auto()
DISCONNECTING = enum.a... |
# Comments in python. As you may have notice this line starts with a hash sign (#).
# Hash signs are not processed by the python interpreter. You can use hash signs to create comments
# in your program to explain specific parts of the program, to creates notes, or to troubleshoot and/or
# test parts of the program.
... |
#Binary Converter
import program_exit
n= 0
while n < 10:
byte = input("Byte: ")
byte = byte.lower()
while len(byte) == 8:
decimal = 0
for num in byte:
decimal = decimal*2 + int(num)
print(decimal)
break
if byte.lower() in ('exit'):
print("Exiting softw... |
"""
7. В одномерном массиве целых чисел определить два наименьших элемента.
Они могут быть как равны между собой (оба минимальны), так и различаться.
"""
# Preprocess
import random
A = [random.randint(0, 10) for _ in range(10)]
print(A)
first_i = 0
second_i = 1
for i in range(len(A)):
if A[first_... |
"""
3. Сформировать из введенного числа обратное по порядку входящих в него цифр и вывести на экран.
Например, если введено число 3486, надо вывести 6843.
"""
num = input("Введите число: ")
mun = ''
for i in num:
mun = i + mun
print(mun)
|
"""
2. По введенным пользователем координатам двух точек вывести уравнение прямой вида
y = kx + b,
проходящей через эти точки.
"""
print('Введите кординаты 2 точек')
a = input('координаты a = ')
b = input('координаты b = ')
x1, y1 = map(int, a.split(','))
x2, y2 = map(int, b.split(','))
k = (y1 - y2) ... |
"""
3. Массив размером 2m + 1, где m — натуральное число, заполнен случайным образом.
Найдите в массиве медиану. Медианой называется элемент ряда, делящий его на две равные части:
в одной находятся элементы, которые не меньше медианы, в другой — не больше медианы.
Примечание: задачу можно решить без сортировки ис... |
def cube(v):
return v*v*v
x= int(input("Enter a number: "))
print("From def() : " +str(cube(x)))
c = lambda x: x*x*x
print("From lambda : "+ str(c(x))) |
class Person:
#name = "sample"
#age = 0
def __init__(self,name,age):
self.name = name
self.age = age
ame=input("enter your name: ")
ge=int(input("enter your age: "))
p1 = Person(ame,ge)
page = 2119 - p1.age
print("Hey",p1.name,",you will score century in year:",page)
... |
statement=input("enter string: ")
count1 = 0
count2 = 0
for i in range(len(statement)-1):
count1 += statement[i:i+4] == 'Emma'
for i in range(len(statement)-1):
count2 += statement[i:i+4] == 'emma'
count = count1 + count2
print("Emma appeared ", count, "times") |
# 5.Write a program that prompts the user to enter an integer for today�s day of the week (Sunday is 0, Monday is 1, ..., and Saturday is 6).
# Also prompt the user to enter the number of days after today for a future day and display the future day of the week.
def dayfinder(dk):
switcher={
0: 'Sunday',
... |
# 11:07 PM, Feb 9th, @ dormitory
# 面向对象,类的继承
# 继承 inherit
# 类的继承基本理解,还要多写代码练习加深印象
class SchoolMember:
def __init__(self, name, age):
self.name = name
self.age = age
print('(Initilized SchoolMember: {0})'.format(self.name))
def tell(self):
print('Name:{0} Age:{... |
/**
Program use for sorting array using selection sort.
Write two method for swapping and find minimum value
of a array.Then call these methods while looping
through array elements.
**/
def swap(array, i, j):
temp = array[i]
array[i] = array[j]
array[j] = temp
def find_min_index(array, start_index... |
###############################################################################
"""
Question:
LintCode: http://www.lintcode.com/en/problem/maximum-depth-of-binary-tree/
Given a binary tree, find its maximum depth.
The maximum depth is the number of nodes along the longest path from the
root node down... |
###############################################################################
"""
Question:
LintCode: http://www.lintcode.com/en/problem/search-in-rotated-sorted-array/
Suppose a sorted array is rotated at some pivot unknown to you beforehand.
(i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).
You are... |
from abc import ABCMeta, abstractmethod
class AbstractGraph(metaclass=ABCMeta):
@abstractmethod
def insert_vertex(self, vertex):
pass
@abstractmethod
def insert_edge(self, edge):
pass
@abstractmethod
def vertices_adjacent(self, v1, v2):
pass
@abstractmethod
d... |
DATA_DIR = "../data/"
def parse_google_analogies(filename, anlgtype=None):
""" Parse file and return a list of dicts.
Google's analogy data has 4 space separated words per line,
except for lines starting with ":", which indicate types of analogy.
"""
analogy_dicts = []
analogy_tupls = []
a... |
MyList=["pink","blue","green"]
print(MyList)
MyList.append("yellow")
print(MyList) |
from random import shuffle
class Solution(object):
def __init__(self, rects):
"""
:type rects: List[List[int]]
"""
self.points = []
for rect in rects:
width_start = rect[0]
height_start = rect[1]
for width in xrange(abs(rect[0] - rect[2... |
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def kthSmallest(self, root, k):
"""
:type root: TreeNode
:type k: int
:rtype: int
"""
... |
class Solution(object):
def asteroidCollision(self, asteroids):
"""
:type asteroids: List[int]
:rtype: List[int]
"""
stack = []
for ast in asteroids:
if stack and stack[-1] > 0 and ast < 0:
abs_ast = abs(ast)
... |
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def removeNthFromEnd(self, head, n):
"""
:type head: ListNode
:type n: int
:rtype: ListNode
"""
last = tail =... |
class Solution:
def tribonacci(self, n: int) -> int:
if n == 0:
return 0
elif n == 1:
return 1
elif n == 2:
return 1
else:
t = [0, 1, 1]
i = -1
while n > 2:
i += 1
t[i... |
class Solution:
def findIntegers(self, num):
"""
:type num: int
:rtype: int
"""
x, y = 1, 2
res = 1
while num:
if num & 3 == 3:
res = 0
res += x * (num & 1)
num >>= 1
x, y = y, x + y... |
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def findSecondMinimumValue(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if not ro... |
class Solution(object):
def isPalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
left = 0
right = len(s) - 1
dic = '0123456789abcdefghijklmnopqrstuvwxyz'
while right > left:
temp_left = s[left].lower()
if temp_left not in ... |
class Solution(object):
def arrayPairSum(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
nums.sort()
idx = 0
res = 0
len_nums = len(nums)
while idx < len_nums:
res += nums[idx]
idx += 2
return res
sol ... |
class Solution(object):
def searchMatrix(self, matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: bool
"""
if not matrix or not matrix[0] or target is None:
return False
def bin_search(target, arr):
left = 0
... |
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string.
:type root: TreeNode
:rtype: str
""... |
class Solution(object):
def totalHammingDistance(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums:
return 0
res = 0
max_num = max(nums)
temp = 1
while temp <= max_num:
zeros = ones = 0
... |
class Solution(object):
def maxNumber(self, nums1, nums2, k):
"""
:type nums1: List[int]
:type nums2: List[int]
:type k: int
:rtype: List[int]
"""
def prep(nums, k):
extra = len(nums) - k
if extra == 0:
return nums
... |
class Solution:
def bulbSwitch(self, n: int) -> int:
bound = 1 << n
bulbs = bound - 1
curr = 1
res = 0
for step in range(2, n + 1):
toggle = bound >> step
while toggle > 0:
bulbs ^= toggle
toggle >>... |
class Solution(object):
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
a, b, ca, cb = 0, 0, 0, 0
for num in nums:
if num == a:
ca += 1
elif num == b:
cb += 1
elif ca... |
"""
Valid Anagram
"""
class Solution(object):
def isAnagram(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
dict = {}
for ch in s:
if ch in dict:
dict[ch] += 1
else:
dict[ch] = 1
... |
class Solution(object):
def triangleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums or len(nums) < 3:
return 0
nums = sorted(nums)
len_nums = len(nums)
count = 0
for i in range(2, len_nums):
f... |
class MyHashSet(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.hash = [[0] * 1000 for _ in range(1000)]
def add(self, key):
"""
:type key: int
:rtype: void
"""
self.hash[key // 1000][key % 1000] = ... |
class Solution:
def validPalindrome(self, s: str) -> bool:
def recurse(l, r, d):
while l < r:
if s[l] == s[r]:
l += 1
r -= 1
else:
if d:
return False
else:
... |
# traffic light simulation
from time import sleep
class Counter:
def __init__(self):
self.n = 0
def tick(self):
self.n += 1
return self.n
def reset(self):
self.n = 0
def getNumber(self):
return self.n
transferTable = {}
transferTable['Red'] = {'wait':5, 'next':'Green'}
transfe... |
# 使用矩陣快速冪計算費氏數列
import time
def timing(func):
def wrapper(*args, **kwargs):
start_time = time.time()
result = func(*args, **kwargs)
end_time = time.time()
print(f"{func.__name__} took {(end_time - start_time)*1000:.0f} ms to execute")
return result
return wrapper
class... |
# Vending machine simulation
from time import sleep
from random import random, choice
class Machine:
priceList = {'A':10, 'B':15, 'C':20}
def __init__(self, items=None, deposit=50):
self.income = 0
self.items = items or {'A':5, 'B':5, 'C':5}
self.deposit = deposit
def insertCoin(self, n):
pri... |
"""
Cameron Bates AY250 homework 5
This is a set of functions to load the data provided from intrade about the republican
nomination, the republican VP nomination and the presidential election into a sqlite3
database. It provides tow functions to retrieve data from this database mdall and pall
mdall successively plots ... |
# coding=utf-8
import time
import math
import numpy as np
from scipy.integrate import odeint
import matplotlib.pyplot as plt
class cls_Environment:
"""
The environment class
"""
def __init__(self):
"""init function, called then object is created"""
self._t0 = time.clock() # get curren... |
class Student(object):
def __init__(self,subject, name, roll, marks):
self.name = name
self.subject = subject
self.roll = roll
self.marks = marks
def getsubject(self):
return self.subject
def getmarks(self):
return self.marks
def getroll(se... |
"""
https://leetcode.com/problems/longest-substring-without-repeating-characters/
Example 1:
Input: s = "abcabcbb"
Output: 3
Explanation: The answer is "abc", with the length of 3.
Example 2:
Input: s = "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.
Example 3:
Input: s = "pwwkew"
Output: ... |
"""
https://leetcode.com/problems/flatten-a-multilevel-doubly-linked-list/
Input: head = [1,2,3,4,5,6,null,null,null,7,8,9,10,null,null,11,12]
Output: [1,2,3,7,8,11,12,9,10,4,5,6]
Input: head = [1,2,null,3]
Output: [1,3,2]
"""
def flatten(head):
curnode = head
while curnode:
childnode = curno... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.