text stringlengths 37 1.41M |
|---|
#!/usr/bin/env python
# A simple run-once(throwaway) scrip to create and set up database with afew entries
import apsw
# Open/Create DB
connection = apsw.Connection("recipebook.db3")
cursor = connection.cursor()
# Sqlite3 Table
sql = 'CREATE TABLE Recipes(pkid INTEGER PRIMARY KEY, name TEXT, \
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function
from pathlib import Path
import pathlib
import os
p_file = Path(__file__)
p_dir = p_file.parent
def is_exist():
assert p_file.exists() is True
assert p_dir.exists() is True
p = Path("file_not_exist.py")
assert p... |
numero = int(input())
horas = int(input())
recebe = float(input())
salario = float(horas * recebe)
print ("NUMBER = %i" %numero)
print ("SALARY = U$ %0.2f" % salario)
|
#!/usr/bin/env python
# coding:utf-8
import datetime
import time
TIME_STAMP = "%Y%m%d%H%M%S"
class TimeUtils:
# @staticmethod
# def comparetime(targettime, *time):
# if len(time) == 1:
# return TimeUtils.comparetime1(targettime, time[0])
# elif len(time) == 2:
# return T... |
fname = input("Enter file name: ")
fh = open(fname)
lst = list()
final = list()
x = 0
i = 0
for line in fh:
stuff = line.split()
x = 0
for i in stuff:
lst.append(stuff[x])
x = x + 1
lst.sort() #The list lst is sorted.
#Now look for duplicates and remove them.
#x = 0
#i = 0
#for z in lst:
for i in range(len(lst... |
EMPTY = 0
BOARD_DIMENSION = 9
class Board:
def __init__(self, board: [list]):
''' Initializes a board object that represents the sudoku board. '''
self.board = board
def get_board(self) -> [list]:
''' Returns the 2d array of the board. '''
return self.board
def solved... |
def recurMul(a, b):
"""recurMul(a, b): b is an integer and greater than or equal to 1"""
if b == 1:
return a
else:
return a + recurMul(a, b-1)
def main():
print "recurMul(4, 5) : ", recurMul(4, 5)
print "recurMul(-7, 4) : ", recurMul(-7, 4)
print "recurMul(30, 10) : ", rec... |
class SayHello:
GREETING_MESSAGE = "Hello {} {}, how are you doing ?"
def __init__(self, fullName):
self.firstName, self.lastName = fullName.split(' ')
def greet(self):
return self.GREETING_MESSAGE.format(self.firstName, self.lastName)
s = SayHello('Philippe Brolly')
print(s.greet()) |
import sqlite3
class Database:
def __init__(self, config):
self.name = 'books'
self.connection = sqlite3.connect(config['DATABASE_FILE_PATH'])
self.cursor = self.connection.cursor()
self.__create__()
self.edited = True
self.item_amount = self.count()
def __del_... |
def add(n, m):
return n + m
def multiply(n, m):
return n*m
def subtract(n, m):
return n - m
def divide(n,m):
return n/m
# Testing
x = add(4,5)
print("4 + 5 =", x)
if (x == 9):
print("Working!")
else:
print("ERROR!")
x = multiply(4,5)
print("4 * 5 =", x)
if (x == 20):
print("Working!")... |
pares=[]
sumatoria=0
num=-1
while ( num!=0 ) :
num=int(input("ingrese el numero "))
sumatoria=num+sumatoria
if (num % 2) == 0:
pares.append(num)
print("Suma de todos los valores ingreados= ",sumatoria)
print(pares) |
'''
Intragração Numérica
Regra dos trapézios
Divide-se a área num número n de trapézios
intregral(x0 -> xn) y. dx = h/2 (y(0) + 2*y(1) + 2*y(2) + ... + 2* y(n-1) + y(n-1))
intregral(x0 -> x) y. dx = h/2 (y(0) + 2*somatório(1 -> n-1) y(i) + y(n-1))
sin(x)(0->pi):
n 4 8 16 32
h pi/4 pi/8 ... |
# for item in range(10):
# print(item)
# total = 0
# prices = [10, 20, 30]
# for item in prices:
# total += item
# print(f"total = {total}")
# nested loops
# for x in range(3):
# for y in range(2):
# print(f'({x},{y})')
numbers = [2, 2, 2, 2, 7]
for item in numbers:
output... |
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def traverse(self):
temp = self.head
data = []
while (temp):
data.append(temp.data)
temp = temp.next
return data
def search(self,item):
temp = self.head
i = 0
... |
# Problem Domain
Extend the binary tree class with a funciton that traverses a tree object using the breadth-first approach.
# Edge Cases
Tree has no nodes
# Visualization
# / -> {1} < -\
# {2} < -- / | \- -> {3}
# |______________|_____________|
# |
[1, 2, 3]
# Big O
Time: O(N)
Space: O(1)
# A... |
from hashtable.linked_list import LinkedList
class Hashtable:
def __init__(self, size=128):
self._size = size
# None can be replaced with LinkedList() at higher initial setup cost
self._buckets = size * [None]
def _hash(self, key):
sum = 0
for character in key:
... |
def multi_bracket_validation(string):
open_brackets = ('(', '[', '{')
close_brackets = (')', ']', '}')
brackets = [
character for character in string if character in open_brackets or character in close_brackets]
# First-glance fail conditions
if len(brackets) < 2 or brackets[0] in close_bra... |
# Implemetation Example
def FibonacciDP(n):
# Setting up a memoization table
dictFiboncci = {}
dictFiboncci[0] = 0
dictFiboncci[1] = 1
#building up a bigger solutions
for itr in range(2, n + 1):
dictFiboncci[itr] = dictFiboncci[itr - 1] + dictFiboncci[itr - 2]
return dictFiboncci[n]
... |
def bubble_sort(arr):
import matplotlib.pyplot as plt
fig = plt.figure()
#creating a subplot
ax1 = fig.add_axes([1,1,1,1])
def update_plot(arr):
xaxis = [x for x in range(0,len(arr))]
plt.bar(xaxis, height=arr)
plt.xlabel("Position")
plt.ylabel("Value")
... |
"""This program finds the discriminant, the number of solutions in a quadratic
equation, and it also solves for it's solutions given the values of
a, b, and c"""
def discriminant(a,b,c):
"""Calculates the discriminant"""
D = b ** 2 - 4 * a * c
return D
def num_solutions(a,b,c):
... |
import numpy as np
from util import *
def binarization(image, threshold):
result=image.copy()
result[image<threshold]=0
result[image>=threshold]=255
return result
if __name__ == '__main__':
path=load_gui()
Image=readImage(path)
value=int(input('Input Threshold value to binarization : '... |
change = int(raw_input("How much: "))
q = 25
d = 10
n = 5
p = 1
Q = 0
D = 0
N = 0
P = 0
while change > 0:
if change >= q:
change = change -q
Q = Q + 1
elif change >= d:
change = change - d
D = D + 1
elif change >= n:
change = change - n
N = N... |
n = 10
a = 0
b = 0
c = 0
for i in range(n):
c += 1
print 'c',c
for i in range (n):
b += 1
print 'b',b
for i in range (n):
a += 1
print 'a',a
div = (6*a + 9*b + 20*c)
print div
|
def playHand(hand, wordList, n):
wordScore = 0
finalScore = 0
while calculateHandlen(hand) != 0:
print 'Current hand:',displayHand(hand)
word = raw_input('Enter word, or a "." to indicate that you are finished: ')
if word == '.':
print 'Goodbye! Total sco... |
import random
print "Type Q to end\n"
right = 0
wrong = 0
while True:
i = random.randrange(3, 15)
j = random.randrange(6, 15)
multi = i*j
print "What is", i, "times", j, "?"
answer = input()
if answer == "Q":
break
elif answer == multi:
print "\nYES!"
right +... |
# -*- coding: utf-8 -*-
s = "this a test string"
i = 0 #initalize index position
ans = 0 #initalize answer variable
while i < len(s): #stop when have tested all chars in input string (provided)
if s[i] == 'a': #test if character in index position is the char ‘a’
ans = ans + 1 #if find an ‘a’ increment ... |
n = int(input("Enter value of n"))
list1 = list(map(int,input("\nEnter list:").strip().split()))[:n]
new_list = []
for i in range(0,n):
mx = 0
for j in range(len(list1)):
if (list1[j] > mx):
mx = list1[j]
list1.remove(mx)
new_list.append(mx)
print(new_list) |
from typing import List
import copy
class Solution:
def coinChange(self, coins: List[int], amount: int) -> int:
if amount==0:
return 0
explored = set()
explored.add(amount)
curr_amount = -1
sorted_coins = list(sorted(coins))
while curr_a... |
from typing import List
from functools import lru_cache
# paste solution method definition here
@lru_cache(maxsize=None)
def sets_are_equal(s1, s2):
return set(s1) == set(s2)
@lru_cache(maxsize=None)
def is_scrambled(s1, s2):
print("Scrambled: ", s1, s2)
if set(s1) != set(s2):
return False
el... |
from typing import List
# paste solution method definition here
class Solution:
def canCross(self, stones: List[int]) -> bool:
if len(stones) < 2 or stones[1] != 1:
return False
elif len(stones) == 2:
return True
paths = [{'last_k': 1, 'stones': stones[1:]}]
... |
# Write a function that takes an integer as input, and returns the number of bits
# that are equal to one in the binary representation of that number.
# You can guarantee that input is non-negative.
#
# Example: The binary representation of 1234 is 10011010010,
# so the function should return 5 in this case
n = 1234
... |
# Welcome.
# In this kata you are required to, given a string, replace every letter with its position in the alphabet.
# If anything in the text isn't a letter, ignore it and don't return it.
# "a" = 1, "b" = 2, etc.
# Example
# alphabet_position("The sunset sets at twelve o' clock.")
# Should return "20 8 5 19 21 14 1... |
# Move the first letter of each word to the end of it, then add "ay"
# to the end of the word. Leave punctuation marks untouched.
text = 'Aaa ! Hallo a A world ?'
def pig_it(text):
pig_text = []
for latin in text.split():
if latin.isalpha():
pig_text.append(latin[1:] + latin[0] + 'ay')
... |
"""
A pawn is generally a weak unit, but we have 8 of them which we can use to build a pawn defense wall.
With this strategy, one pawn defends the others. A pawn is safe if another pawn can capture a unit on that square.
We have several white pawns on the chess board and only white pawns. You should design your code to... |
"""
In this mission you should check if all elements in the given list are equal.
"""
from typing import List, Any
def all_the_same(elements: List[Any]) -> bool:
res = True
if elements:
a = elements[0]
x = [a == element for element in elements]
return all(x)
return res
if __name... |
"""
Problem #18 Square Root
http://www.codeabbey.com/index/task_view/square-root
Many mathematical problems are solved in programming not precisely, but approximately, by several computations
of the result, each of which is more and more close to the goal.
Let us practice the method of approximate calculation of the... |
"""
Problem #13 Weighted sum of digits
http://www.codeabbey.com/index/task_view/weighted-sum-of-digits
This program resembles more complex algorithms for calculation CRC and other checksums and also hash-functions on
character strings. Besides it will provide you with one more exercise on splitting values to decimal ... |
from random import randint
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
new_list = [item for item in set(a) if item in b]
print(new_list)
# Extra 1 & 2
a = [randint(0, 50) for _ in range(0, 20)]
b = [randint(0, 50) for _ in range(0, 40)]
new_list = [item for item in set(... |
#
# Autor: Pablo García Morales, A01745530
# Descripcion: Programa para calcular el valor de la comida con su propina, iva y el total.
subtotal= int(input("costo de su comida"))
propina= subtotal*.12
iva= (subtotal*.16)
total= (subtotal+propina+iva)
print(subtotal)
print(propina)
print(iva)
print(total)
|
#!/usr/bin/python
# Filename: ex3.py
print "I will now count my chickens:"
print "Hens", 25+30/6
print "Roosters", 100-25*3%4
print "Now I will count the eggs:"
print 3+2 + 1 - 5 +4%2 - 1 / 4 + 6
print "Is it ture that 3+2<5-7?"
print 3 + 2 < 5 - 7
print "What is 3 + 2?", 3 + 2
print "What is 5 - 7?", 5 - 7
pr... |
FirstName=input("what is your firsta name?")
lastName=input("what is your last name?")
location=input("what is your location?")
age=input("what is your age?")
space=" "
print("hi"+space+FirstName+space+lastName+space+"! your location is"+space+location+space+"and you are"+space+age+space+"years old")
|
"""
Function checks the ratio of air-fuel mixture and classify them as the Lean or Rich mixture.
1. When the oxygen value in the sensor is less than 0.1, it is classified as the Lean mixture.
2. When the O2 value is between 0.9 to 1.0, it is classified as the Rich mixture.
"""
import pandas as pd
def FuelMixt... |
import requests
import json
import pprint
barcode = 9320123006002
#barcode = input("Scan product barcode: ")
#Convert barcode to string
sku = str(barcode)
#Store URL concat with SKU to get URL for product
url = 'https://*.vendhq.com/api/products?sku='+sku
#Use Requests library to get JSON object for product
r = req... |
now = int(input('С какой скоростью может бежать спортсем СЕЙЧАС? '))
want = int(input('С какой скоростью ДОЛЖЕН БУДЕТ бежать спортсем? '))
day = 1
while now < want :
now = now*1.1
print ("Прошел", day, "день")
day = day+1
print ('Скорость', now)
print("К", day-1,"дню скорость спортсема составила", now) |
from abc import *
class Expression(metaclass=ABCMeta):
@abstractmethod
def reduce(self, to): pass
class Bank:
def reduce(self, source, to):
return source.reduce(to)
class Sum(Expression):
def __init__(self, augend, addend):
self.augend = augend
self.addend = addend
def r... |
def binary_search(ls, item):
"""An O(log n) search algrithm."""
ls.sort()
low = 0
high = len(ls) - 1
while low <= high:
mid = int((low + high) / 2)
guess = ls[mid]
if guess == item:
print("Item found!")
return mid
if guess > item:
... |
import random
answer = int(input("Попробуйте отгадать число от 1 до 4: "))
number = random.randint(1, 4)
print(number)
if answer > number:
print("Ваш ответ больше введенного числа")
elif answer < number:
print("Ваш ответ меньше введенного числа")
else:
print("Победа")
|
import random
attnum = 3
answer = random.randint(1,10)
print('Компьютер загадал число.\nУ вас есть', attnum, 'попытки. Удачи!')
while True:
att = input('Попробуйте угадать: ')
if att == 'Выход':
break
try:
att = int(att)
except:
continue
if att == answer:
print('... |
from collections import deque
food_quantity = int(input())
order_quantities = deque(map(int, input().split()))
print(max(order_quantities))
while food_quantity > 0 and order_quantities:
if order_quantities[0] > food_quantity:
print(f"Orders left: {' '.join(map(str, order_quantities))}")
break
... |
from triangle_print import print_line
def print_triangle(n):
[print_line(1, x + 1) for x in range(n)]
[print_line(1, x + 1) for x in range(n - 2, -1, -1)]
|
def reverse_string(text):
stack = []
for char in text:
stack.append(char)
reversed_text = []
while stack:
char = stack.pop()
reversed_text.append(char)
return "".join(reversed_text)
string = input()
print(reverse_string(string))
|
numbers_dictionary = {}
try:
line = input()
while not line == "Search":
num_str = line
num = int(input())
numbers_dictionary[num_str] = num
line = input()
line = input()
while not line == "Remove":
searched_num = line
print(numbers_dictionary[searched_nu... |
from collections import deque
def perform_calculation(nums, operator):
result = nums[0]
nums = nums[1:]
for num in nums:
if operator == "+":
result += num
elif operator == "-":
result -= num
elif operator == "*":
result *= num
elif opera... |
def get_phonebook_info():
phonebook = {}
entry = input()
while not entry.isdigit():
name, number = entry.split("-")
phonebook[name] = number
entry = input()
n = int(entry)
return phonebook, n
def search_phonebook_contacts(phonebook, n):
for _ in range(n):
na... |
def find_free_hall(halls, char, capacity, overflown_halls):
for hall, people in halls.items():
if sum(people) + char <= capacity:
return hall, overflown_halls
else:
overflown_halls.append(hall)
return None, overflown_halls
def check_hall_overflow(overflown_halls, halls)... |
def find_symbol(matrix, symbol):
for row in range(matrix_size):
for col in range(matrix_size):
curr_symbol = matrix[row][col]
if curr_symbol == search_symbol:
return row, col
matrix_size = int(input())
matrix = []
for _ in range(matrix_size):
row = list(input(... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
review numpy array
"""
import numpy as np
data = np.array([1, 2, 3, 4, 5])
dataq = np.array([[1, 2, 3], [3, 3, 3]])
print(dataq.shape[0])
print(dataq.shape[1])
data = data.reshape((data.shape[0], 1))
|
from itertools import *
def manhattanDistance(p1,p2):
"""
Renvoie la distance de Manhattan entre les points p1 et p2
"""
(x1,y1) = p1
(x2,y2) = p2
return abs(x1 - x2) + abs(y1 - y2)
def partition(tasks):
"""
Cacule toutes les partitions possibles étant donné un ensemble de tâches.
"""
... |
import numpy as np
# Write a function that takes as input a list of numbers, and returns
# the list of values given by the softmax function.
def softmax(L):
expL = np.exp(L)
sumExpL = sum(expL)
results = []
for i in expL:
results.append(1.0*i/sumExpL)
return results
# Note: The function ... |
# Random algorithms using arrays
# Given an array of n integers which has both positive and negative integers,
# sort this array such that the negative integers should in the front
# and the positive integers should in the back. The relative position should not be changed.
# eg. -1 1 3 -2 2 ans: -1 -2 1 3 2.
def putNe... |
class Busqueda:
def __init__(self,listas=None):
self.__lista= listas
@property
def lista(self):
if self.__lista != None:
return self.__lista
else:
print("Lista esta vacia")
def busquedaLineal(self,buscado):
lon = len(self,... |
# Exercício 2: Jogo da palavra embaralhada. Desenvolva um jogo em que a pessoa usuária tenha que adivinhar uma palavra que será mostrada com as letras embaralhadas. O programa terá uma lista de palavras e escolherá uma aleatoriamente. O jogador terá três tentativas para adivinhar a palavra. Ao final a palavra deve ser ... |
# Добавяме всички числа в numbers
# След което търсим най-малкото
n = input("Enter n: ")
n = int(n)
start = 0
numbers = []
while start < n:
number = input()
number = int(number)
numbers = numbers + [number]
start += 1
# Най-малкото ни число е първото число в списъка
# След което обхождаме спис... |
from random import randint
n = input("Enter sides: ")
n = int(n)
dice_roll_1 = randint(1, n)
dice_roll_2 = randint(1, n)
print(dice_roll_1 + dice_roll_2)
|
def head(items):
return items[0]
# Брои от 0!
def last(items):
last_index = len(items) - 1
return items[last_index]
def tail(items):
result = []
for index in range(1, len(items)):
item = items[index]
result += [item]
return result
def equal_lists(l1, l2):
if len(l1) !... |
# Четем число от потребителя
# Ако е четно и > 20, значи всичко е наред.
n = input("Enter number: ")
n = int(n)
if n % 2 == 0 and n > 20:
print("Yes, it is!")
else:
print("No, it isn't!")
|
a = input("Enter a:")
b = input("Enter b:")
operation = input("Enter operation:")
a = int(a)
b = int(b)
result = 0
if operation == "+":
result = a + b
elif operation == "*":
result = a * b
elif operation == "-":
result = a - b
elif operation == "/":
result = a / b
else:
print("Unknown operation: "... |
# Тук ползваме следната идея
# Ако имаме едно число n
# n % 10 ни дава последната цифра на това число
# n // 10 ни дава числото без последната цифра
# Ако n е само 1 цифра, n // 10 ще даде 0. Това е и условието за край на цикъла
n = input("Enter number: ")
n = int(n)
while n != 0:
digit = n % 10
print(dig... |
# age.py
age = input("What is your age?")
age = int(age)
if age < 18:
print("This is a retricted area.")
|
# Проблемът на тази задача е, че не знаем горната граница на интервала
# Например, не знае първите 4 перфектни числа в какъв интервал са
# За това подхождаме по следния начин - while True:
# За всяко число +1 гледаме дали е перфектно
# Aко намерим перфектно, намаляваме търснеата бройка с 1
# Когато търсената бройка ста... |
# Използваме факта, че in може да търси дали низ се намира в низ
# В случая имаме един низ с всички възможни гласни
# И като ходим character по character, просто сравняваме там
vowels = "aeiouyAEIOUY"
count = 0
string = input("Enter string: ")
for ch in string:
if ch in vowels:
count += 1
print(count)
|
# Создать класс Point, описывающий точку(атрибуты: x, y). Создать класс
# Figure. Создать три дочерних класса Circle(атрибуты: координаты
# центра(тип Point), длина радиуса; методы: нахождение периметра и
# площади окружности), Triangle(атрибуты: три точки, методы: нахождение
# площади и периметра), Square(атрибуты: дв... |
__author__ = 'hanxuan'
"""
Given a collection of numbers that might contain duplicates, return all possible unique permutations.
For example,
[1,1,2] have the following unique permutations:
[1,1,2], [1,2,1], and [2,1,1].
"""
def permute_unique(nums):
"""
:param nums: List[int]
:return: List[List[int]]
... |
__author__ = 'hanxuan'
"""
Write a function that takes an unsigned integer and returns the number of ’1' bits
it has (also known as the Hamming weight).
For example, the 32-bit integer ’11' has binary representation
00000000000000000000000000001011, so the function should return 3.
"""
def hammingWeight(n):
retu... |
__author__ = 'hanxuan'
"""
:param n: int
:return: int
You are climbing a stair case. It takes n steps to reach to the top.
Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?
"""
def climbingStairsV1(n):
if n == 1:
return 1
if n == 2:
... |
__author__ = 'hanxuan'
"""
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
For example, given n = 3, a solution set is:
"((()))", "(()())", "(())()", "()(())", "()()()"
"""
def generate_parenthesis(n):
"""
:param n: int
:return: List[string]
... |
__author__ = 'hanxuan'
"""
Given two words (beginWord and endWord), and a dictionary's word list, find the length of shortest transformation
sequence from beginWord to endWord, such that:
Only one letter can be changed at a time
Each intermediate word must exist in the word list
For example,
Given:
beginWord = "hit... |
__author__ = 'hanxuan'
"""
Given a linked list, return the node where the cycle begins. If there is no cycle, return null.
Note: Do not modify the linked list.
Follow up:
Can you solve it without using extra space?
"""
from llinkedList.ListNode import ListNode
def detectCycle(head):
"""
:param head:
... |
__author__ = 'hanxuan'
"""
Follow up for "Unique Paths":
Now consider if some obstacles are added to the grids. How many unique paths would there be?
An obstacle and empty space is marked as 1 and 0 respectively in the grid.
For example,
There is one obstacle in the middle of a 3x3 grid as illustrated below.
[
... |
"""
Given a 2D binary matrix filled with 0's and 1's, find the largest square containing all 1's and return its area.
For example, given the following matrix:
1 0 1 0 0
1 0 1 1 1
1 1 1 1 1
1 0 0 1 0
Return 4.
"""
def maximalSquare(matrix):
"""
:type matrix: List[List[str]]
:rtype: int
"""
if not... |
__author__ = 'hanxuan'
"""
Given a sorted array of integers, find the starting and ending position of a given target value.
Your algorithm's runtime complexity must be in the order of O(log n).
If the target is not found in the array, return [-1, -1].
For example,
Given [5, 7, 7, 8, 8, 10] and target value 8,
retu... |
__author__ = 'hanxuan'
'''
I = 1;
V = 5;
X = 10;
L = 50;
C = 100;
D = 500;
M = 1000;
I placed before V or X indicates one less, so four is IV (one less than five) and nine is IX (one less than ten)
X placed before L or C indicates ten less, so forty is XL (ten less than fifty) and ninety is XC (ten less than a
... |
__author__ = 'hanxuan'
"""
Given a string s, partition s such that every substring of the partition is a palindrome.
Return all possible palindrome partitioning of s.
For example, given s = "aab",
Return
[
["aa","b"],
["a","a","b"]
]
"""
# def partition(s):
# """
# :type s: str
# :rtype: ... |
__author__ = 'hanxuan'
'''
Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = target?
Find all unique quadruplets in the array which gives the sum of target.
Note:
Elements in a quadruplet (a,b,c,d) must be in non-descending order. (ie, a ≤ b ≤ c ≤ d)
The solution set mu... |
__author__ = 'hanxuan'
"""
Count the number of prime numbers less than a non-negative number, n.
"""
def countPrimes(n):
"""
:param n: int >= 0
:return:
"""
if n <= 2:
return 0
x = 0
for i in range(2, n):
if isPrime(i):
x += 1
return x
def isPrime(n):
... |
__author__ = 'hanxuan'
"""
Given a set of candidate numbers (C) and a target number (T), find all unique combinations in C
where the candidate numbers sums to T.
The same repeated number may be chosen from C unlimited number of times.
Note:
All numbers (including target) will be positive integers.
Elements in a com... |
__author__ = 'hanxuan'
"""
Given a column title as appear in an Excel sheet, return its corresponding column number.
For example:
A -> 1
B -> 2
C -> 3
...
Z -> 26
AA -> 27
AB -> 28
"""
def titleToNumber(s):
"""
:param s: string
:return: int
"""
uppercase = 'abcdefghi... |
__author__ = 'hanxuan'
"""
Clone an undirected graph. Each node in the graph contains a label and a list of its neighbors.
OJ's undirected graph serialization:
Nodes are labeled uniquely.
We use # as a separator for each node, and , as a separator for node label and each neighbor of the node.
As an example, consid... |
__author__ = 'hanxuan'
"""
Given inorder and postorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
"""
from ltree.TreeNode import TreeNode
def buildTree(inorder, postorder):
if inorder:
ind = inorder.index(postorder.pop())
root... |
"""
Using turtle to draw corona virus in python
"""
from turtle import *
#Select color and background color
color('green')
bgcolor('black')
#Select speed of motion of turtle and hide it
speed(11)
hideturtle()
#Set the position you want. This works best for me
goto(25, 152)
#Use looping for shape
b = 0
while b < 200:
... |
import Input
#To use the Input moduel, you must first coppy what you see in the built in functions keyPressed() and keyReleased(). due to the fact that these functions will only run in the main moduel, this is the only way to get around it.
#once you create a newControler, you can add 'buttons' to it using the method... |
def binary_search(arr, value):
def loop(x, y):
if x < y:
h = (x + y) // 2
return loop(h + 1, y) if arr[h] < value else loop(x, h)
return x if arr[x] == value else None
return loop(0, len(arr) - 1)
arr = list(range(10))
assert binary_search(arr, 10) == None
assert bin... |
import pygame
from constants import GREY, GREEN, BLUE, RED, ORANGE, YELLOW
class Spot():
def __init__(self, row, column, width=40):
self.color = GREY
self.row = row
self.width = width
self.column = column
self.x = column*width
self.y = row*width
... |
#实现类Point
#使其满足
#1.二维空间
#2.实现方法reflect_x 和reflect_y, 分别返回按X/Y轴进行对称的点
#3.实现横纵坐标的 setter 和 getter
class Point():
'''Create a new Point, at coordinates x and y.'''
def __init__(self, x = 0, y = 0):
'''Create a new point at x, y'''
self.x = x
self.y = y
#Add a method reflect_x to Point wh... |
#!/bin/bash/python3
"""
Given an array of integers, find the first missing positive integer in linear
time and constant space. In other words, find the lowest positive integer that
does not exist in the array. The array can contain duplicates and negative numbers as well.
For example, the input [3, 4, -1, 1] should g... |
# [string] 두 정수 사이의 합 - 프로그래머스 1단계
def solution(a, b):
answer = 0
if (b < a):
a, b = b, a
if (a == b):
return a
for i in range(a, b + 1):
answer = answer + i
return answer |
# [정렬] 버블정렬 - 이것이 코딩테스트다
array = [7,5,9,0,3,1,6,2,4,8]
#
def bubbleSort(arr):
for i in range(len(arr)):
print(arr)
bubbleSort(array) |
# [Numeric] 8진수 2진수 - 백준 1212
# 8 진수를 입력 받아 2진수로 표현
import sys
num = sys.stdin.readline().strip() # 8진수로된 정수 값을 받아옴
# print(num)
num = '0o' + num # 8진수 표현식으로 변경
# print(num)
num = int(num,8) # 8진수 표현식을 정수로 변경
# print(num)
num = bin(num) # 8진수 정수를 2진수로 변경
# print(num)
for i in range(2,len(num)):
print(num[i],end... |
a = [3,6,9]
for i in a:
if i == 3:
print(i)
continue
if i == 3:
print('3입니다.')
print('pass') |
# [String] 문자열 내 p와 y의 개수 - 프로그래머스 1단계
S = "pPoooyY"
def solution(s):
answer = True
numP = 0
numY = 0
for i in s:
if(i == 'p' or i == 'P'):
numP += 1
elif(i == 'y' or i == 'Y'):
numY += 1
if(numY != numP):
answer = False
return answer
resul... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.