text stringlengths 37 1.41M |
|---|
'''
https://leetcode.com/problems/largest-palindrome-product/discuss/276101/Python3-Math-and-Non-math-solutions-with-detailed-explanation
**Math solution:**
Let Palindrome = X * Y, both have n digits, and assume they are very close to 10^n
Denote X = 10^n - i, Y = 10^n - j, with assumption: i*j < 10^n
Palindrome = upp... |
# 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 reverseOddLevels(self, root: 'Optional[TreeNode]') -> 'Optional[TreeNode]': # O( N | N )
def fla... |
class TicTacToe:
def __init__(self, n: int):
"""
Initialize your data structure here.
"""
self.grid = [[-1 for _ in range(n)] for _ in range(n)]
def move(self, row: int, col: int, player: int) -> int:
"""
Player {player} makes a move at ({row}, {col}).
@... |
class LockingTree:
def __init__(self, parent: 'List[int]'):
self.tree = parent
self.p_node = {}
for i, p in enumerate(parent):
if p not in self.p_node:
self.p_node[p] = []
self.p_node[p].append(i)
self.locked = {}
#print(self.p_node)... |
class Solution:
def findRotation(self, mat: 'List[List[int]]', target: 'List[List[int]]') -> bool:
def rotate(mat):
output = [[None for c in range(len(mat[0]))] for r in mat]
for r in range(len(mat)):
for c in range(len(mat)):
output[r][c] = mat[c]... |
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def deleteDuplicates(self, head: ListNode) -> ListNode:
if head == None:return None
else:
node = head
start = o_node = ListNode(node.... |
# 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 hasPathSum(self, root: 'Optional[TreeNode]', targetSum: int) -> bool: # O( N | 1 )
def helper(no... |
class Solution:
def check(self, nums: 'List[int]') -> bool:
if len(nums) < 2:
return True
else:
for i in range(1, len(nums)):
if nums[i] < nums[i-1]: # find the pivot point
arr = nums[i:] + nums[:i] #move the elements before pivot to the en... |
class Solution:
def findDifference(self, nums1: 'List[int]', nums2: 'List[int]') -> 'List[List[int]]':
nums1 = set(nums1) # make it a set to speed up the look up
nums2 = set(nums2) # make it a set to speed up the look up
return [[i for i in nums1 if i not in nums2], [i for i in nums2 if i no... |
import datetime
class Solution:
def daysBetweenDates(self, date1: str, date2: str) -> int:
d1 = date1.split('-')
d2 = date2.split('-')
from_date = datetime.date(int(d1[0]), int(d1[1]), int(d1[2]) )
to_date = datetime.date(int(d2[0]), int(d2[1]), int(d2[2]))
return abs... |
class Solution:
def canPlaceFlowers(self, flowerbed: 'List[int]', n: int) -> bool:
if len(flowerbed) == 1:
return (flowerbed[0] == 0 and n <= 1) or (n == 0)
slot = 0
for i in range(len(flowerbed)): #look around to see if can be placed here. if can, mark it as 1
... |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def mergeInBetween(self, list1: 'ListNode', a: int, b: int, list2: 'ListNode') -> 'ListNode':
output = node = list1
cnt = 0
w... |
class Solution:
def reverseVowels(self, s: str) -> str: # O( N | N )
s = list(s)
l = 0
r = len(s)-1
while l <= r: # check vowels from start
if s[l].lower() in "aeiou": # meet vowel
while r >= l: # searching for the counterpart from the end, and swap
... |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reverseEvenLengthGroups(self, head: 'Optional[ListNode]') -> 'Optional[ListNode]':
arr = []
while head: #flat, transform accordin... |
class CombinationIterator:
def __init__(self, characters: str, combinationLength: int):
def combo(output, arr, curr, v):
if len(curr)==v:
output.append(curr)
for i in range(len(arr)):
combo(output, arr[i+1:], curr+arr[i], v)
arr = sor... |
def countBattleships(board: 'List[List[str]]'):
output = 0
for i in board:
for j in i:
if j == "X":
output+=1
for i in range(len(board)):
s="".join(board[i])
for x in range(len(s)-1):
if s[x] + s[x+1] =='XX':
output-=1
for... |
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def balanceBST(self, root: TreeNode) -> TreeNode:
def dfs(flat, node):
if node.left == node.right == None:
flat... |
# 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 minimumOperations(self, root: 'Optional[TreeNode]') -> int: # O( NlogN | N )
def flat(hmp, lvl, ... |
class Solution:
def searchMatrix(self, matrix: 'List[List[int]]', target: int) -> bool: # O( M+N | 1 ), M is len(matrix), N is len(matrix[0])
r = len(matrix)-1
c = 0
while r > -1 and c < len(matrix[0]): #since both rows and columns are sorted, we can go from bottom->top->right to find the ta... |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reorderList(self, head: 'Optional[ListNode]') -> None:
"""
Do not return anything, modify head in-place instead.
"""
... |
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def reverseList(self, head: 'Optional[ListNode]') -> 'Optional[ListNode]':
def helper(node):
if node.next == None:
retur... |
class Solution:
def isRobotBounded(self, instructions: str) -> bool:
direct = [[-1, 0], [0, 1], [1, 0], [0, -1]] #up, right, down, left
d = 0 # initial was facing up
x = y = 0
for i in instructions:
if i == "G":
x += direct[d][0]
y += direc... |
class Solution:
def isValidSudoku(self, board: 'List[List[str]]') -> bool: # O( MN | MN )
for r in board: # check rows
curr = set()
for c in r:
if c != ".":
if c in curr:
return False
curr.add(c)
... |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def middleNode(self, head: 'Optional[ListNode]') -> 'Optional[ListNode]': # O( N | 1 )
def helper(output, node, idx):
if node.ne... |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def hasCycle(self, head: 'Optional[ListNode]') -> bool:
fast = slow = head
while fast and fast.next and fast.next.next:
fast = fast.next.... |
class Solution:
def isCircularSentence(self, sentence: str) -> bool: # O( N | N )
arr = sentence.split(' ')
if len(arr) == 1: # only 1 word in the sentence
return arr[0][0] == arr[0][-1]
else:
for i in range(1, len(arr)):
if arr[i][0] != arr[i-1][-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 buildTree(self, preorder: 'List[int]', inorder: 'List[int]') -> 'Optional[TreeNode]': # O( N**2 | N )
... |
class SeatManager:
def __init__(self, n: int):
self.heap = [] #store the unreserved seats
heapq.heapify(self.heap)
self.curr = 0
def reserve(self) -> int:
if len(self.heap) == 0 : #no seat has been unreserved
self.curr+=1
return self.curr
else:
... |
# 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 bstFromPreorder(self, preorder: 'List[int]') -> 'Optional[TreeNode]':
def helper(node, leftRange... |
def is_selfDivide(num):
output = 1
temp = str(num)
for i in range(0, len(temp)):
if int(temp[i])==0:
output = 0
break
else:
if num%int(temp[i])==0:
output = 1
else:
output = 0
break
return out... |
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def sumEvenGrandparent(self, root: TreeNode) -> int:
def dfs(node, output):
curr = 0
if node.left != None:
... |
class Solution:
def checkMove(self, board: 'List[List[str]]', rMove: int, cMove: int, color: str) -> bool:
direction = [[1, -1], [-1, -1], [-1, 1], [1, 1], [1, 0], [0, -1], [-1, 0], [0, 1]]
for a, b in direction:
cnt = 1
c = cMove + a
r = rMove + b
las... |
class Solution(object):
def sortArray(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
self.quickSort(nums, 0, len(nums)-1)
return nums
def quickSort(self, nums, start, end):
if start >= end:
return
... |
class Solution(object):
def gardenNoAdj(self, n, paths):
"""
:type n: int
:type paths: List[List[int]]
:rtype: List[int]
"""
graph = defaultdict(set)
for u, v in paths:
graph[u].add(v)
graph[v].add(u)
res= [0] * (n ... |
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def constructFromPrePost(self, pre, post):
"""
:type pre: List[int]
... |
class Solution(object):
def rotate(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: None Do not return anything, modify matrix in-place instead.
"""
"""
reverse it then transport it
reverse:
7 8 9
4 5 6
1 2 3
... |
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def getAllElements(self, root1, root2):
"""
:type root1: TreeNode
:t... |
"""
# Definition for a Node.
class Node(object):
def __init__(self, val=None, children=None):
self.val = val
self.children = children
"""
class Solution(object):
def levelOrder(self, root):
"""
:type root: Node
:rtype: List[List[int]]
"""
output = []
... |
import itertools
import random
import unittest
from assignment3 import *
from copy import deepcopy
def flatten(lst):
return [item for sublist in lst for item in sublist]
def random_str(length):
return "".join(chr(i) for i in random.choices(range(97, 123), k=length))
def format_build_substr(S, T):
res... |
# Python RSA implementation 10/01/2020
# Key generation
import random
import json
import os
import math
import functools
import numpy as np
import os
YAFU_EXEC = "yafu\\yafu.exe"
def primality_test(n):
# too slow for big numbers
# trial division method
if n <= 3:
return n > 1
elif n % 2 == 0 o... |
def main(n):
listA = [0] * (n + 1)
return Fibonacci(n,listA)
def Fibonacci(n,listA):
if listA[n] != 0:
pass
elif n <= 2:
listA[n] = 1
else:
listA[n] = Fibonacci(n-1,listA) + Fibonacci(n-2,listA)
return listA[n]
if __name__ == "__main__":
print(main(500))
|
def move_disk(pegs,disk,source,destination):
pegs[destination].append(pegs[source].pop())
print(disk, source,destination)
def move_tower(pegs,disk,source,destination):
spare = 3 - source - destination
if disk == 0:
move_disk(pegs,disk,source,destination)
else:
move_tower(pe... |
class person:
def __init__(self, name, age):
self.name = name
self.age = age
def speak(self):
print("{} is {}".format(self.name, self.age))
class baby(person):
def __init__(self, food):
self.food = food
print(f"baby eats {food}")
mike = baby("banana")
mike.speak(... |
# -*- coding: utf-8 -*-
"""
Created on Wed Mar 11 19:40:03 2020
@author: Naomi
"""
#Define the function
def collatz(number):
if number%2==0:
number=number/2
print(number//2)
else:
number=3*number+1
print(number)
return number
#Start
print ('Collatz sequence:')
t... |
# -*- coding: utf-8 -*-
"""
Created on Wed Apr 1 21:02:33 2020
@author: Naomi
"""
seq ='ATGCGACTACGATCGAGGGCCAT'
#Define an empty string to store the complementary sequence
cDNA=""
#Loop through the sequence
for i in seq:
#if the character is 'A'
if i=="A":
#Store 'T' to the string cDN... |
class Node:
"""
A node of a tree that is being used to encode and compress data into symbols.
"""
def __init__(self, symbol=None, weight=0, left=None, right=None):
self.left = left
self.right = right
self.symbol = symbol
self.weight = weight
class HEncoder:... |
# Module for Oxford's 'Introduction to Python' course
__author__ = 'tomi'
def bubble_sort(alist):
""" A modifier function that sorts a list, using the bubble method
:param alist: a list of numbers
:return: the same list of numbers, but sorted
"""
return bubble_sort_iterative(alist)
def bubble_so... |
# Recognise faces using some classification algorithm
#like logistic ,KNN,SVM etc
# 1. load the training data (numpy array of all the persons)
# x- values are stored in the numpy arrays
# y-values we need to assign for each person
# 2. Read a video stream using opencv
# 3. extract faces out of it
# 4. use... |
"""A helper module to generate fake records for testing.
"""
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from __future__ import unicode_literals
import os
import sys
import re
import json
import argparse
import random
from faker import Faker
fake = Fake... |
from firebase import firebase
import tkinter as tk
end = 1
start = -1
last = -1
counter = -1
def bfs_paths(graph, start, goal):
queue = [(start, [start])]
while queue:
(vertex, path) = queue.pop(0)
for next in graph[vertex] - set(path):
if next == goal:
yield path ... |
# Combiner List: Create a function named combiner that takes a single argument, which will be a list made up of strings and numbers.
# Return a single string that is a combination of all of the strings in the list and then the sum of all of the numbers. For example, with the input ["apple", 5.2, "dog", 8], combiner wo... |
# Author: Muhammed Rahmetullah Kartal
# This code implements a one hidden layered neural network in given data
import numpy as np
import pandas as pd
from sklearn.metrics import f1_score
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.metrics import mean_squared_error
# normalizing a column with mi... |
import pygame
import itertools
import pieces
import board
from pieces import *
from board import *
pygame.init()
(width, height) = (480, 480)
screen = pygame.display.set_mode((width, height), pygame.SRCALPHA)
pygame.display.set_caption("CHESS AI - LET'S DO THIS!")
board_size = 480
block_size = int(board_size / 8)
... |
# Step 1 - have the library psycopg2 installed. done
import psycopg2
# Credential:
dbname = 'tpeczybx'
user = 'tpeczybx'
password = 'hehehe...'
host = 'isilo.db.elephantsql.com'
# Connect to pg
pg_conn = psycopg2.connect(dbname=dbname, user=user,
password=password, host... |
# -*- coding: utf-8 -*-
"""
Created on Mon Feb 11 2019
@author: narayanatantry
"""
import random
def choose():
words=[]
n = input("enter the number of words")
for i in range(n):
t = input("enter the words \n")
words.append(t)
pick=random.choice(words)
def jumbleword(... |
class SudokuGame(object):
"""Represents a Sudoku game: abstracts the grid and offer an automated way to solve it"""
_rows = 'ABCDEFGHI'
_cols = '123456789' #doubles as digits
_assignments = []
_strategies = []
def __init__ (self, serialized_grid):
self._boxes = self.cross(self.... |
"""Functions for interacting with a pidfile."""
import atexit
import os
def write_pidfile(pidfile_path):
"""Write a pidfile for the current process.
Will also remove the pidfile at process exit-time.
Args:
pidfile_path: the path where the PID should be written.
Returns:
Nothing
Th... |
import unittest
def multiply(a, b):
return a * b
def divide(a, b):
try:
return a / b
except ZeroDivisionError:
return 'you can not do it moron!'
def growing(a):
return a + 1
class TestClass(unittest.TestCase):
def test_multiply(self):
self.assertEqual(multiply(3, 9), ... |
# 코드 3-24 : range() 함수를 이용한 for 문의 제어와 간격값 사용법
## "으뜸 파이썬", p. 153
# 표현식 1 : 2에서 5-1까지 연속값 2, 3, 4 출력
for i in range(2, 5):
print(i, end = ' ')
print()
# 표현식 2 : 간격 값을 사용하여 0, 2, 4, 6, 8 출력
for i in range(0, 10, 2):
print(i, end = ' ')
print()
# 표현식 3 : 음수 간격 값 사용, -2, -4, -6, -8 출력
for i in ra... |
# 코드 4-13 : 두 개의 값을 튜플로 반환하는 방법과 전달 받는 방법
## "으뜸 파이썬", p. 214
def get_root(a, b, c):
r1 = (-b + (b ** 2 - 4 * a * c) ** 0.5) / (2 * a)
r2 = (-b - (b ** 2 - 4 * a * c) ** 0.5) / (2 * a)
return r1, r2
# 함수 호출시 인자를 상수 값을 사용함
# result1, result2를 이용해서 결과 값을 반환 받아온다.
result1, result2 = get_root(1, 2... |
# 코드 5-4 : 리스트 내부에 값이 존재하는가를 확인하는 기능
## "으뜸 파이썬", p. 285
n_list = [11, 22, 33, 44, 55, 66]
print(88 in n_list) # 88은 n_list에 없음
print(55 in n_list) # 55는 n_list에 있음
|
# 코드 4-23 : 직사각형과 원의 면적을 구하는 함수의 구현
## "으뜸 파이썬", p. 229
def func(shape, width=1, height=1, radius=1):
if shape == 0 : # shape 값이 0이면 사각형의 면적을 반환
return width * height
if shape == 1 : # shape 값이 1이면 원의 면적을 반환
return 3.14 * radius ** 2
print("rect area =", func(0, width=10, height=2))
... |
# 코드 10-28 : OddCounter 클래스와 StopIteration 예외 생성기능
## "으뜸 파이썬", p. 607
class OddCounter:
def __init__(self, n = 1):
self.n = n
def __iter__(self):
return self
def __next__(self):
if self.n < 20: # 반복자가 수행되는 조건
t = self.n
self.n += 2
... |
# 코드 8-21 : 파일 열기와 쓰기, 파일 닫기의 표현 2
## "으뜸 파이썬", p. 505
f = open('hello.txt', 'w') # 파일 열기
try:
f.write('Hello World!') # hello.txt 파일에 쓰기
finally:
f.close() # 파일을 닫는다.
|
# 코드 6-2 : 딕셔너리의 항목 삭제와 dic[1] 항목의 변화 여부
## "으뜸 파이썬", p. 338
dic = {0:11, 1:22, 2:33, 3:44, 4:55}
# 딕셔너리의 (키,값) 튜플쌍을 반환하는 items() 함수로 항목 출력
print('pop(0) 이전 :', dic.items())
print('pop(0) 이전 dic[1] = ', dic[1])
dic.pop(0) # 키 0을 이용하여 (0, 11) 항목을 삭제하였음
print('pop(0) 이후 :', dic.items())
print('pop(0) 이후 dic[1]... |
# 코드 3-27 : 사용자로부터 입력을 받은 후 누적 합계 값 구하기
## "으뜸 파이썬", p. 157
n = int(input('합계를 구할 수를 입력하세요 : '))
s = 0
for i in range(0, n) :
s = s + (i+1)
print('1부터 {}까지의 합은 {}'.format(n, s))
|
# 코드 8-19 : try-except 문을 사용한 파일 입출력
## "으뜸 파이썬", p. 502
import sys
fname = input('입력할 파일의 이름 : ')
try :
f = open(fname, 'r', encoding = 'UTF8') # 파일 열기
except IOError:
print('Could not read file:', fname)
sys.exit()
except:
print('Unexpected error:', sys.exc_info()[0])
sys.exit()
... |
# 코드 8-12 : read() 메소드를 이용하여 지정된 문자 크기만큼 읽기
## "으뜸 파이썬", p. 494
f = open('hello.txt', 'r') # 파일을 연다.
s = f.read(5) # hello.txt 파일의 다섯 문자를 읽는다.
print(s) # 파일의 내용을 출력한다.
f.close() # 파일을 닫는다.
|
# 코드 3-1 : 순차적 실행 구조를 이용한 변수의 덧셈
## "으뜸 파이썬", p. 114
num = 100
print('num = ', num) # 100이 출력됨
num = num + 100
print('num = ', num) # num에 100이 더해져 200이 출력됨
num = num + 100
print('num = ', num) # num에 다시 100이 더해져 300이 출력됨
|
# 코드 6-1 : 리스트의 항목 삭제와 lst[1] 항목의 변화 여부
## "으뜸 파이썬", p. 337
lst = [11, 22, 33, 44, 55]
print('pop(0) 이전 :', lst)
print('pop(0) 이전 lst[1] = ', lst[1])
lst.pop(0) # 인덱스 0을 이용하여 리스트의 첫 항목을 삭제한다
print('pop(0) 이후 :', lst)
print('pop(0) 이후 lst[1] = ', lst[1])
|
def swap_case(s):
diff = ord('a') - ord('A')
res = ""
for i in s:
val = i
if i >= 'a' and i <= 'z':
val = chr(ord(i) - diff)
elif i >= 'A' and i <= 'Z':
val = chr(ord(i) + diff)
res += val
return(res)
if __name__ == '__main__':
s = input()
... |
from calendar import weekday
m, d, y = map(int, input().split())
days = {0: 'MONDAY', 1: 'TUESDAY', 2: 'WEDNESDAY', 3: 'THURSDAY', 4: 'FRIDAY', 5: 'SATURDAY', 6: 'SUNDAY'}
print(days[weekday(y, m, d)])
|
import re
for _ in range(int(input())):
n = input()
print(bool(re.match('^\+[0-9]*\.[0-9]+$', n)) or bool(re.match('^[0-9]*\.[0-9]+$', n) or bool(re.match('^\-[0-9]*\.[0-9]+$', n))))
|
chessboard = [[]]
chessboard = [[0 for i in range(3)] for j in range(3)] # 0 indicates queen not placed at the (i,j)th position
def check_attack(i, j):
for k in range(3):
if chessboard[k][j] == 1:
return True # check for queen vertically
for x in range(3):
for ... |
#!/usr/bin/python
#-*-coding:utf8-*-
from __future__ import print_function
class Node(object):
data = None
next_ = None
def __init__(self, num):
self.data = num
class LinkedList(object):
first = None
def add_node(self, num):
node = Node(num)
if self.first is None:
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Apr 28 11:11:27 2018
@author: maadland
"""
def add_vectors(a_list, b_list):
"""adds two lists together
"""
c_list = []
for index, element in enumerate(a_list):
current_item = element + b_list[index]
c_list.append(current... |
"""
Wolf, Goat and Cabbage Puzzle in Python
By Robin Andrews - https://compucademy.co.uk/
"""
import os # Only needed in console version
import time # Only needed in console version
names = {"F": "Farmer",
"W": "Wolf",
"G": "Goat",
"C": "Cabbage"}
forbidden_states = [{"W", "G"}, {"G", "C"}... |
def min_refills(n, a, dist_with_full_tank):
num_refills = 0
current_refills = 0
last_refills = 0
#print("Stops where you need to get refilling:")
while current_refills < (n - 1):
last_refills = current_refills
while ((a[current_refills + 1] - a[last_refills]) <= dist_with_full_tank):... |
def menu_opcoes():
print("\n" * 100)
while True:
print("\n OPÇÕES DISPONÍVEIS NO BD:\n 1 - INSERIR\n 2 - PESQUISAR\n 3 - ALTERAR\n 4 - EXCLUIR\n 5 - LISTAR\n 6 - SAIR\n")
opcao = int(input("DÍGITE SUA OPÇÃO > "))
if opcao == 1:
... |
# bank = 'pi'
# way = account or card
# money = cash or check
bank = 'pi'
way = 'card'
money = 'check'
if bank == 'pi' and ((way == 'account') or (way == 'card')) and money == 'cash':
print("입금할 수 있다.")
else :
print("입금할 수 없다.")
|
def print_list(num_list) :
for n in num_list :
if (n != 0) :
print(n, end=',')
else:
break
print(print_list([1,2,3,0]))
|
menu = {'Americano':'2000원','Cafe latte':'2500원','Green Tea latte':'3000원','Mocha latte':"3500원"}
print("Menu: Americano")
if 'Americano' in menu:
print("Price:", menu['Americano'])
else:
print("This menu does not exit")
print("Menu: Vanila latte")
if 'Vanila latte' in menu:
print("Price:", menu['Va... |
current = int(input("현재 전기 용량: "))
total = int(input("전체 전기 용량: "))
if current < total*0.3 :
print("전체 전기 총량의 30%보다 현재 전기량이 적으니, 휘발유로 주행해야 한다.")
|
hour = int(input("시각을 입력하시오. :"))
minute = int(input("분을 입력하시오. :"))
second = int(input("초를 입력하시오. :"))
total_second = hour*3600 + minute*60 + second
print(total_second, "초")
|
import sys
import cv2
import numpy as np
import math
def cross_correlation_2d(img, kernel):
'''Given a kernel of arbitrary m x n dimensions, with both m and n being
odd, compute the cross correlation of the given image with the given
kernel, such that the output is of the same dimensions as the image and ... |
# 1) Every four years, the summer Olympics are held in a different country. Add a key-value pair to the dictionary places that reflects that the 2016 Olympics were held in Brazil. Do not rewrite the entire dictionary to do this!
places = {"Australia":2000, "Greece":2004, "China":2008, "England":2012}
places ['Brazi... |
import os
class Game:
def __init__(self):
self.wordlist_file = os.environ["GGEUTMARITGI_DIR"] + '/../data/wordlist.txt'
self.load_wordlist()
def load_wordlist(self):
with open(self.wordlist_file, 'r') as f:
wordlist_lines = f.readlines()
wordlist = []
for... |
import math
import operator as op
import re
import os
import random
import functools
# TODO
# How to do panning ?
# how to add multiple pars to sc
# how to do more feedback delays
# have chuck based loops:
#while (true) {
# action
# second => now;
# action
# second => now;
# action;
#}
# eval should re... |
def space_efficient(string: str) -> int:
balance = 0
added = 0
for item in string:
if item == "(":
balance += 1
else:
balance -= 1
if balance == -1:
balance += 1
added += 1
return added + balance
def get_num_paranthesis_required... |
# https://practice.geeksforgeeks.org/problems/first-and-last-occurrences-of-x/0
T = 2
S = [(9, 5, [1, 3, 5, 5, 5, 5, 67, 123, 125]),
(9, 7, [1, 3, 5, 5, 5, 5, 7, 123, 125])]
def bsearch(x, _max, _min, idx):
mid = (_min + _max) // 2
if x > mid:
# Go right
return bsearch(x, _max, mid)
... |
# https://www.geeksforgeeks.org/find-expression-duplicate-parenthesis-not/
def check(n):
stack = []
is_last_poped_parenthesis = False
for i in n:
print(n, stack, i, is_last_poped_parenthesis)
if i == ")":
_i = stack.pop()
if is_last_poped_parenthesis and _i == "(":
... |
"""
Bubble Sort
Iterate through list of numbers by comparing them in pairs and keeping smaller elements on left side by swapping them.
Do this till there is no swap in one complete iteration.
"""
import random
import copy
def get_random_numbers(length=10):
return random.sample(range(1, 100), length)
def sort(num... |
"""
This problem was asked by Facebook.
Given the mapping a = 1, b = 2, … z = 26, and an encoded message, count the number of ways it can be decoded.
For example, the message ‘111’ would give 3, since it could be decoded as ‘aaa’, ‘ka’, and ‘ak’.
You can assume that the messages are decodable. For example, ‘001’ is ... |
import heapq
import sys
from typing import List, Tuple, NewType
EdgesType = NewType("EdgesType", List[Tuple[int]])
def priority_queue_solution(vertices: int, edges: EdgesType) -> int:
graph = {idx: [] for idx in range(vertices + 1)}
for (u, v, w) in edges:
graph[u].append((v, w))
graph[v].ap... |
#!/usr/bin/env python
if __name__ == "__main__":
N = int(raw_input())
for i in range(N):
print(pow(i,2))
|
# https://leetcode.com/problems/contains-duplicate/
# Neetcode - Arrays & Hashing
from typing import List
def contains_dups(nums: List[int]) -> bool:
hm = set()
for n in nums:
if n not in hm:
hm.add(n)
else:
return True
return False
testcases = [
([1,2,3,1], True),
([1,2,3,4], False),
([1,1,1,3,3,4... |
"""
Insertion Sort
Sorts the way we sort playing cards
"""
from bubble_sort import get_random_numbers
def sort(numbers):
count = len(numbers)
for i in range(1, count):
is_swapped = True
for j in range(i, 0, -1):
if numbers[j] < numbers[j-1]:
numbers[j], number... |
# Author : Rajat Mhetre
# follow and drop me a line at @rajat_mhetre
t = int(input())
for _ in range(t):
cycle_count = int(input())
height = 1
for i in range(cycle_count):
if(i%2 == 0):
height *= 2
else:
height += 1
print(height)
|
#!/usr/bin/python3
# service_lane.py
# Author : Rajat Mhetre
# follow and drop me a line at @rajat_mhetre
n,t = map(int, input().split())
width = list(map(int, input().split()))
for _ in range(t):
i,j = map(int, input().split())
vehicle = min(width[segment] for segment in range(i,j+1))
print(vehicle)
|
#leetcode
#question - 1512. Number of Good Pairs
#level=Easy
nums=[1,2,3]
pairs=[]
for i in range(0,len(nums)):
# print(nums[i])
for j in range(i+1,len(nums)):
if nums[i]==nums[j]:
pairs.append([i,j])
print(len(pairs)) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.