text stringlengths 37 1.41M |
|---|
'''
1217. Play with Chips
There are some chips, and the i-th chip is at position chips[i].
You can perform any of the two following types of moves any number of times
(possibly zero) on any chip:
Move the i-th chip by 2 units to the left or to the right with a cost of 0.
Move the i-th chip by 1 unit to the left or t... |
'''
784. Letter Case Permutation
Given a string S, we can transform every letter individually to be lowercase or
uppercase to create another string. Return a list of all possible strings we
could create.
Examples:
Input: S = "a1b2"
Output: ["a1b2", "a1B2", "A1b2", "A1B2"]
Input: S = "3z4"
Output: ["3z4", "3Z4"]
... |
'''
138. Copy List with Random Pointer
A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null.
Return a deep copy of the list.
'''
# Definition for singly-linked list with a random pointer.
class RandomListNode(object):
def __init__(self,... |
'''
676. Implement Magic Dictionary
Implement a magic directory with buildDict, and search methods.
For the method buildDict, you'll be given a list of non-repetitive words to build
a dictionary.
For the method search, you'll be given a word, and judge whether if you modify
exactly one character into another charac... |
'''
671. Second Minimum Node In a Binary Tree
Given a non-empty special binary tree consisting of nodes with the non-negative
value, where each node in this tree has exactly two or zero sub-node. If the node
has two sub-nodes, then this node's value is the smaller value among its two
sub-nodes. More formally, the p... |
'''
824. Goat Latin
A sentence S is given, composed of words separated by spaces. Each word consists of lowercase
and uppercase letters only.
We would like to convert the sentence to "Goat Latin" (a made-up language similar to Pig Latin.)
The rules of Goat Latin are as follows:
If a word begins with a vowel (a, e, i... |
'''
429. N-ary Tree Level Order Traversal
Given an n-ary tree, return the level order traversal of its nodes' values. (ie,
from left to right, level by level).
Note:
The depth of the tree is at most 1000.
The total number of nodes is at most 5000.
'''
'''
ALGORITHM:
Same approach as Level order traversal for Binary ... |
'''
1047. Remove All Adjacent Duplicates In String
Given a string S of lowercase letters, a duplicate removal consists of choosing
two adjacent and equal letters, and removing them.
We repeatedly make duplicate removals on S until we no longer can.
Return the final string after all such duplicate removals have been m... |
'''
500. Keyboard Row
Given a List of words, return the words that can be typed using letters of
alphabet on only one row's of American keyboard.
Example:
Input: ["Hello", "Alaska", "Dad", "Peace"]
Output: ["Alaska", "Dad"]
Note:
You may use one character in the keyboard more than once.
You may assume the input st... |
'''
997. Find the Town Judge
In a town, there are N people labelled from 1 to N. There is a rumor that one
of these people is secretly the town judge.
If the town judge exists, then:
The town judge trusts nobody.
Everybody (except for the town judge) trusts the town judge.
There is exactly one person that satisfies ... |
'''
744. Find Smallest Letter Greater Than Target
Given a list of sorted characters letters containing only lowercase letters, and
given a target letter target, find the smallest element in the list that is
larger than the given target.
Letters also wrap around. For example, if the target is target = 'z' and
lette... |
'''
914. X of a Kind in a Deck of Cards
In a deck of cards, each card has an integer written on it.
Return true if and only if you can choose X >= 2 such that it is possible to split the entire deck into 1 or more groups of cards, where:
Each group has exactly X cards.
All the cards in each group have the same integ... |
'''
228. Summary Ranges
Given a sorted integer array without duplicates, return the summary of its ranges.
Example 1:
Input: [0,1,2,4,5,7]
Output: ["0->2","4->5","7"]
Explanation: 0,1,2 form a continuous range; 4,5 form a continuous range.
Example 2:
Input: [0,2,3,4,6,8,9]
Output: ["0","2->4","6","8->9"]
Explanat... |
'''
1038. Binary Search Tree to Greater Sum Tree
Given the root of a binary search tree with distinct values, modify it so that
every node has a new value equal to the sum of the values of the original tree
that are greater than or equal to node.val.
As a reminder, a binary search tree is a tree that satisfies these... |
'''
707. Design Linked List
Design your implementation of the linked list. You can choose to use the singly
linked list or the doubly linked list. A node in a singly linked list should have
two attributes: val and next. val is the value of the current node, and next is
a pointer/reference to the next node. If you w... |
'''
41. First Missing Positive
Given an unsorted integer array, find the smallest missing positive integer.
Example 1:
Input: [1,2,0]
Output: 3
Example 2:
Input: [3,4,-1,1]
Output: 2
Example 3:
Input: [7,8,9,11,12]
Output: 1
Note:
Your algorithm should run in O(n) time and uses constant extra space.
'''
'''
ALGO... |
'''
258. Add Digits
Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.
Example:
Input: 38
Output: 2
Explanation: The process is like: 3 + 8 = 11, 1 + 1 = 2.
Since 2 has only one digit, return it.
'''
class Solution(object):
def addDigits(self, num):
""... |
'''
1413. Minimum Value to Get Positive Step by Step Sum
Given an array of integers nums, you start with an initial positive value
startValue. In each iteration, you calculate the step by step sum of startValue
plus elements in nums (from left to right).
Return the minimum positive value of startValue such that the ... |
'''
2164. Sort Even and Odd Indices Independently
You are given a 0-indexed integer array nums. Rearrange the values of nums
according to the following rules:
Sort the values at odd indices of nums in non-increasing order.
For example, if nums = [4,1,2,3] before this step, it becomes [4,3,2,1] after.
The values at ... |
'''
674. Longest Continuous Increasing Subsequence
Given an unsorted array of integers, find the length of longest continuous
increasing subsequence (subarray).
Example 1:
Input: [1,3,5,4,7]
Output: 3
Explanation: The longest continuous increasing subsequence is [1,3,5], its length
is 3.
Even though [1,3,5,7] is a... |
'''
1018. Binary Prefix Divisible By 5
Given an array A of 0s and 1s, consider N_i: the i-th subarray from A[0] to A[i]
interpreted as a binary number (from most-significant-bit to
least-significant-bit.)
Return a list of booleans answer, where answer[i] is true if and only if N_i is
divisible by 5.
Example 1:
Inp... |
'''
967. Numbers With Same Consecutive Differences
Return all non-negative integers of length N such that the absolute difference
between every two consecutive digits is K.
Note that every number in the answer must not have leading zeros except for the
number 0 itself. For example, 01 has one leading zero and is in... |
'''
318. Maximum Product of Word Lengths
Given a string array words, find the maximum value of length(word[i]) * length(word[j])
where the two words do not share common letters. You may assume that each word
will contain only lower case letters. If no such two words exist, return 0.
Example 1:
Input: ["abcw","baz",... |
'''
809. Expressive Words
Sometimes people repeat letters to represent extra feeling, such as
"hello" -> "heeellooo", "hi" -> "hiiii". In these strings like "heeellooo", we
have groups of adjacent letters that are all the same: "h", "eee", "ll", "ooo".
For some given string S, a query word is stretchy if it can b... |
'''
965. Univalued Binary Tree
A binary tree is univalued if every node in the tree has the same value.
Return true if and only if the given tree is univalued.
Example 1:
Input: [1,1,1,1,1,null,1]
Output: true
Example 2:
Input: [2,2,2,5,2]
Output: false
Note:
The number of nodes in the given tree will be in the ra... |
'''
1122. Relative Sort Array
Given two arrays arr1 and arr2, the elements of arr2 are distinct, and all
elements in arr2 are also in arr1.
Sort the elements of arr1 such that the relative ordering of items in arr1 are
the same as in arr2. Elements that don't appear in arr2 should be placed at the
end of arr1 in ... |
'''
190. Reverse Bits
Reverse bits of a given 32 bits unsigned integer.
Example:
Input: 43261596
Output: 964176192
Explanation: 43261596 represented in binary as 00000010100101000001111010011100,
return 964176192 represented in binary as 00111001011110000010100101000000.
Follow up:
If this function is c... |
'''
1200. Minimum Absolute Difference
Given an array of distinct integers arr, find all pairs of elements with the
minimum absolute difference of any two elements.
Return a list of pairs in ascending order(with respect to pairs), each pair
[a, b] follows
a, b are from arr
a < b
b - a equals to the minimum absolute... |
'''
853. Car Fleet
N cars are going to the same destination along a one lane road. The destination is target miles away.
Each car i has a constant speed speed[i] (in miles per hour), and initial position position[i] miles towards the target along the road.
A car can never pass another car ahead of it, but it can ca... |
'''
530. Minimum Absolute Difference in BST
Given a binary search tree with non-negative values, find the minimum absolute difference between values of any two nodes.
Example:
Input:
1
\
3
/
2
Output:
1
Explanation:
The minimum absolute difference is 1, which is the difference between 2 and 1 (... |
'''
1323. Maximum 69 Number
Given a positive integer num consisting only of digits 6 and 9. Return the
maximum number you can get by changing at most one digit (6 becomes 9, and 9
becomes 6).
Example 1:
Input: num = 9669
Output: 9969
Explanation:
Changing the first digit results in 6669.
Changing the second digit ... |
'''
260. Single Number III
Given an array of numbers nums, in which exactly two elements appear only once
and all the other elements appear exactly twice. Find the two elements that
appear only once.
Example:
Input: [1,2,1,3,2,5]
Output: [3,5]
Note:
The order of the result is not important. So in the above example... |
'''
1299. Replace Elements with Greatest Element on Right Side
Given an array arr, replace every element in that array with the greatest element
among the elements to its right, and replace the last element with -1.
After doing so, return the array.
Example 1:
Input: arr = [17,18,5,4,6,1]
Output: [18,6,6,6,1,-1]
C... |
'''
61. Rotate List
Given a linked list, rotate the list to the right by k places, where k is non-negative.
Example 1:
Input: 1->2->3->4->5->NULL, k = 2
Output: 4->5->1->2->3->NULL
Explanation:
rotate 1 steps to the right: 5->1->2->3->4->NULL
rotate 2 steps to the right: 4->5->1->2->3->NULL
Example 2:
Input: 0->1->... |
'''
2078. Two Furthest Houses With Different Colors
There are n houses evenly lined up on the street, and each house is beautifully
painted. You are given a 0-indexed integer array colors of length n, where
colors[i] represents the color of the ith house.
Return the maximum distance between two houses with different... |
'''
905. Sort Array By Parity
Given an array A of non-negative integers, return an array consisting of all the
even elements of A, followed by all the odd elements of A. You may return any
answer array that satisfies this condition.
Example 1:
Input: [3,1,2,4]
Output: [2,4,3,1]
The outputs [4,2,3,1], [2,4,1,3], an... |
'''
695. Max Area of Island
Given a 2d grid map of '1's (land) and '0's (water), count the number of islands.
An island is surrounded by water and is formed by connecting adjacent lands
horizontally or vertically. You may assume all four edges of the grid are all
surrounded by water.
Example 1:
Input:
11110
11010
... |
'''
80. Remove Duplicates from Sorted Array II
Given a sorted array nums, remove the duplicates in-place such that duplicates
appeared at most twice and return the new length. Do not allocate extra space
for another array, you must do this by modifying the input array in-place with
O(1) extra memory.
Example 1:
Gi... |
digit = [
'0' , '1' , '2' , '3' , '4' ,
'5' , '6' , '7' , '8' , '9' ,
'A' , 'B' , 'C' , 'D' , 'E', 'F' ]
def inputInteger ( message ):
while True:
try:
str = input ( message )
if str == 'q':
exit(0)
num = int ( str )
... |
if __name__ == '__main__':
# Tree contains 12 nodes.
tree_names = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L']
T = []
for i in range(len(tree_names)):
T.append(i)
# Relationship between nodes.
R = [
[1, 2, 3], # 0 A
[4, 5], ... |
#Return Statement
def calc(x,y):
z = x + y
z1 = x - y
z2 = x / y
z3 = x * y
#print(z)
return z,z1,z2,z3
a,*b = calc(3,4)
print(a,b)
|
#Benjamin Helm, 2/13/2014
#Comp 23 Lab 2
def main():
""" Prints out all the possible IPv4 addresses """
for a in range (0,256):
for b in range (0,256):
for c in range (0,256):
for d in range (0,256):
print str(a) + "." + str(b) + "." + \
... |
words = list(input())
reversed_words = []
while words:
reversed_words.append(words.pop())
print("".join(reversed_words))
|
num = int(input("Enter the number to find the factorial of :"))
fact = 1
for i in range (1, num+1):
fact *= i
print("The factorial of the given number is :", fact)
|
def answer(names):
# 'cost' of the letter
charCostDictionary = { 'a': 1,
'b': 2,
'c': 3,
'd': 4,
'e': 5,
'f': 6,
'g': 7,
... |
# 题目:暂停一秒输出。
# 程序分析:使用 time 模块的 sleep() 函数。
import time
a = [1, 2, 3]
for i in a:
print(time.ctime())
print(i)
time.sleep(1)
print(time.ctime()) |
#Check a number is armstrong or not !
num = int(input("Enter a number : "))
save = num
sum = 0
c = 0
while num>0 :
num = num /10
c=c+1
num = save
for i in range(0,c):
num = num % 10
sum = sum + num
if (sum == save) :
print ("{0} is an Armstrong no.").format(save)
else:
print ("{0} is not an Armstrong no.").fo... |
print ("Reverse a string")
def reverse_str(l):
if len(l) < 1:
return l
else:
return (reverse_str(l[1:]) + l[0])
s = raw_input("Enter a string : ")
print ("Reverse of {0} is {1}").format(s, reverse_str(s))
|
"""
Some functions are own by BYU-Idaho.
This is intended only to be for teaching purposes.
"""
class BST:
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def __init__(self):
self.root = None
def insert(self,... |
from matplotlib.pyplot import plot,show
from numpy import linspace
N=5
a=-1
b=1
L=(b-a)/N
split=25
xi=[]
for i in range(N+1):
xi.append(a+i*L)
def spline(xi,xinext,f,fnext,m,mnext,x):
global L
return ((xinext-x)**2*(2*(x-xi)+L)*f)/(L**3)\
+((x-xi)**2*(2*(xinext-x)+L)*fnext)/(L**3)\
... |
# This Model represents one CITY ################################################################################
# City Model
class City:
#the model contains the following parameters:
#the object contains the following parameters:
myCityID = 0 # INT - an ID that is assigned for the city (se... |
# https://py.checkio.org/en/mission/non-unique-elements/
'''
You are given a non-empty list of integers (X). For this task, you should return a list consisting of only the non-unique elements in this list.
To do so you will need to remove all unique elements (elements which are contained in a given list only once... |
# https://py.checkio.org/en/mission/popular-words/
'''
In this mission your task is to determine the popularity of certain words in the text.
At the input of your function are given 2 arguments: the text and the array of words the popularity of which you need to determine.
When solving this task pay attention... |
a = 2
b = 3
c = a+b
print(c)
a=2
c=2*a
print(c)
a=2
c=a*a
print(c)
print('2+2')
print(2+2)
print(type(2+2))
print(type('zahra'))
a = 12.5
print(type(a))
print(40/60)
a='hello'
b='zahra'
print(a+b)
import math
print(math.sin(30))
# print(range(1,10))
for i in range(1,10):
print(i)
def zahra(x):
print('salam')
pri... |
max = 5
print('Hello, welcome to the game. You will be choosing a number between 1 and 9.')
print('You can only guess up to', max, 'times. \n')
import random
attempts = 0
a = random.randint(1,9)
while True:
guess = int(input('please enter an interger to guess\n'))
attempts += 1
if guess == a:
print('exec... |
#!/usr/bin/env python3
"""
Skriv en funktion som --med hjälp av rekursion-- tar en listparameter och ger
True om alla element i listan är positiva tal, False annars.
"""
def is_all_positive_numbers(seq):
if len(seq) == 0:
return True
return seq[0] >= 0 and is_all_positive_numbers(seq[1:])
def test_is_... |
import random
class BilFabrik():
def __init__(self):
self.list_of_names = ["volvo", "toyota", "tesla", "bmw", "wolksvagen", "edison"]
self.list_of_colors = ["röd", "inte röd", "blå"]
def get_random_bil(self):
random_namn = random.choice(self.list_of_names)
random_farg = random.... |
def is_sorted(seq):
"""Returns True if all elements in seq is in order,
e.g. seq[i] <= seq[i+1] for each element i = 0..len(seq) exclusive
"""
if len(seq) >= 2:
return seq[0] <= seq[1] and is_sorted(seq[1:])
else:
return True
def test_is_sorted():
assert is_sorted([3, 4, 5... |
#!/usr/bin/env python3
"""
SyntaxError: invalid syntax
Och något mer.
"""
password = input("Vad är det hemliga lösenordet? ")
if password == "bapelsin"
print("Korrekt!")
else:
print("Korrekt!")
|
#!/usr/bin/env python3
"""
4. Skriv en funktion som tar en strängparameter som kan vara en lång text som
består av många ord.
* Låt funktionen beräkna och returnera längden av det
längsta ordet.
* Ett ord är en följd av bokstäver.
* Alla tecken som inte är bokstäver betraktas som avskiljare mellan orden.
* Använd f... |
def recursive_reverse(seq):
if len(seq) > 1:
head, tail = seq[0], seq[1:]
return recursive_reverse(tail) + [head]
return seq
print(recursive_reverse([3, 4, 5]))
|
print("Det här programmet kommer att beräkna antalet termer N som behövs för att summan av 1/i för i = 1..N ska nå upp till ett visst mål")
target_sum = int(input("Vad är ditt slutmål?"))
term_sum = 0.0
i = 1
while term_sum < target_sum:
term = 1 / i
term_sum += term
i += 1
number_of_terms = i - 1
pr... |
# Merging Dictionaries
dict_1 = {'key1': 1, 'key2': 2}
dict_2 = {'key3': 3, 'key4': 4}
print(dict(dict_1, ** dict_2))
print(dict(**dict_1, ** dict_2))
|
# finding the largest number in the list
largest_number = [12, 22, 30, 31, 100]
position = largest_number[0]
for i in largest_number:
if i>position:
position=i
print(f'The largest value in the list is:- {position} ') |
'''
Example for round function
'''
floating_point_number = float(input("Enter a floating point number to round up:- "))
print(round(floating_point_number)) |
# loop a list
fruits = ["apple", "banana", "orange"]
for i in fruits:
print(i)
# to check whether a specified sequence item is present or not in a list using 'in membership operator'
fruits = ["apple", "banana", "orange"]
for i in fruits:
if "orange" in i:
print("Yes, it is in fruits")
else:
... |
'''
Write a Python program to calculate compound interest?
Formula to calculate compound interest annually is given by:
Compound Interest = P(1 + R/100)r
Where,
P is principle amount
R is the rate and
T is the time span
'''
def compound_interest(p, r, t):
return p * (1+r/100) * r
print(compound_interes... |
# Copy a list
list = ['Devops', 'powerbi', 'R']
my_list = list.copy() # copy method is used to make copy a another list
print(my_list)
print(list)
|
'''
Identity operator
Return's True, if both variables are the same objects
'''
x = ['hello', 'world']
y = [1,2,3,4]
z = x
if z is x:
print('Return\'s True, if both variables are the same objects')
else:
print('It\'s not a Identity operator')
|
# Change a values in a dict.
this_dict = {
"name":"gunasekhar R",
'age':23,
'door_no': 20.3,
'boo':True
}
this_dict['age'] = 22 # changed age 23 to 22
print(this_dict)
# the update() method will update the dictionary with the items from the given argument.
this_dict = {
"name":"gunasekhar R",
'age':23,
... |
'''
Write a python program to check wheather a given year is leap year or not?
'''
def leap_year(year): # def keyword is used to define a function
if year % 4 == 0 and year % 100 != 0 or year % 400 == 0:
print("Yes, it is a Leap Year! ")
else:
print("It's not a Leap Year!")
year = int(input('Enter a Year ... |
# Reverse a string using functions
def my_function(x): #def is the keyword used to define a function.
return x[::-1]
mytxt = my_function("I wonder how this text looks like backwards")
print(mytxt)
|
# string format combines the string's and integer's
'''
format method takes the passed arguments, formats them,
and place them in the string where the placeholers {} are.
'''
age = 23
name = "Gunasekhar r is {} year old"
print(name.format(age))
# format method takes unlimited number of arguments
python = 100
Linu... |
# A tuple is a collection which is ordered, unchangeable, and allow duplicate values.
# create a tuple
this_tuple = ('mango', "apple", 'orange')
print(this_tuple)
print(type(this_tuple))
# Tuple items are indexed, index starts from [0] position.
# Tuple allows duplicate values.
this_tuple = ('mango', "apple", 'orang... |
# string methods
# .title()
# converts first character of each word into uppercase.
txt = "welcome to my world"
print(txt.title())
# .isupper returns True or False.
txt = "welcome to my world"
print(txt.isupper())
# .islower also returns True or False.
txt = "welcome to my world"
print(txt.islower())
#isalpha (Retur... |
# You can't access a sets by using their index or key
# but you can loop through sets
fruits = {"apple","mango", 'mango', 1, 1}
for i in fruits:
print(i)
# Check the specific value is present or not using in data type.
fruits = {"apple","mango", 'mango', 1, 1}
print("apple" in fruits) |
# Write a program to check whether user_input method exists in lists or not?
list_methods = ['append', 'insert', 'extend', 'pop', 'remove', 'copy', 'count', 'index', 'clear', 'sort', 'reverse']
user_input = input("enter a method to check whether it belongs to list or not:- ")
for i in list_methods: # in operator is us... |
# write a code to display current version of python
import sys # sys is the module.
def version():
print('Python version: ')
print(sys.version)
print('version information: ')
print(sys.version_info)
version()
|
# logical operators exercise:-
is_magician = True
is_expert = False
# check if magician and expert : 'you are a master magician'
if is_magician and is_expert:
print('you are a master magicain')
# check if magician but not expert: 'at least you are getting there'
elif is_magician == True and is_expert != True:
... |
# Strings in python
'''
A sequence of character's is know as strings.
'''
# Single line string
x = 'one'
print(x)
print(type(x))
# Multiline strings
y = """ so this is about multiline strings in python.
python is a dynamically typed programming language """
print(y)
print(type(y))
# Strings are arrays
'''
Like ma... |
# A dictionary is a collection, which is ordered, indexed, and won't allow duplicate values
# Note: As of Python 3.7 version dictionaries are ordered. In python below 3.6 are earlier or un-ordered.
this_dict = {"name":"gunasekhar R", 'age':23, 'address':'andhra pradesh'}
print(this_dict)
#dict()
this_dict = {"name":... |
from tinydb import Query
import dbparam
class Sites(dbparam.DbParam):
"""
Sites worker to operate DB on table sites (list, add, modify and delete methods).
Site name has to be alphanumeric and less than 20 characters. At the DB all the spaces ``" "`` will be replaced
by underscores ``"_"``.
"""
... |
"""
Jogo da Forca ASCII
===================
Módulo lógico feito por Ana Carolina Erthal, Eduardo Adame, Murilo Calegari, Rodrigo Pintucci, Tiago Barradas e Vinicius Hedler.
Módulo gráfico entregue por Juan, Lucas, Yasmin, Nicole e Carlos.
Utilizamos a função ``randbelow()`` da biblioteca padrão do python secrets pa... |
"""
Implementation of chess game.
@author: DiTurr
"""
import chess
from .model import AlphaZeroModel
from .board import ChessBoard
import torch.optim as optim
class ChessGame:
def __init__(self, path_load_model, func_emit=None):
"""
"""
print("[INFO] Generating and loading model ...")... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#Вычислить сумму всех -значных чисел, кратных ( 1<=n<=4 ) .
if __name__ == '__main__':
k = int(input('Введите кратное число -->'))
s = 0
for i in range(1, 5):
if i % k == 0:
s += i
print(s)
|
"""
Implement a watchdog
"""
import constants
import os
from os.path import isfile, join
from pathlib import Path
import shutil
import time
def name_changed(old_list_of_files: list, new_list_of_files: list) -> None:
"""
Check if a file was changed by it's name between to lists of file names
:param old_... |
import random
def max_heapify(arr, size, root):
child = root * 2 # 부모로부터 왼쪽 자식 노드 찾기
while child <= size: # 배열의 인덱스 범위 초과되는걸 방지
# 오른쪽 자식이 존재하고, 왼쪽 자식이 오른쪽 자식 값보다 작다면
# 오른쪽 값이 큰 노드가 되도록 1을 더함
if child < size and arr[child - 1] < arr[child]:
child += 1
# 부모와 자식 노드 값... |
import sys
prime_list = [False] * 2 + [True] * 100000
for (index, value) in enumerate(prime_list):
if value:
for true_index in range(index * 2, len(prime_list), index):
prime_list[true_index] = False
# 숫자 뒤집기
def reverse(num):
return num[::-1].lstrip("0")
# 소수 판별
def isPrime(num):
r... |
import sys
standard_coord = [[1, 1], [1, 4], [1, 7], [4, 1], [4, 4], [4, 7], [7, 1], [7, 4], [7, 7]]
around_coord = [[-1, -1], [0, -1], [1, -1], [-1, 0], [1, 0], [-1, 1], [0, 1], [1, 1]]
sudoku_board = [list(map(str, sys.stdin.readline().split())) for _ in range(9)]
check = True
# 가로 세로 체크
for first_index in range(l... |
import sys
def DFS(index):
global count
if index == size: # 모든 퀸을 다 배치한 경우
count += 1
return
for i in range(size):
# 모든 경우에서 0인 경우
if row[i] + left[index + i] + right[size - 1 + index - i] == 0:
row[i] = left[index + i] = right[size - 1 + index - i] = 1
... |
import sys
for _ in range(int(sys.stdin.readline())):
word = list(map(str, sys.stdin.readline().strip()))
while len(word) != 0:
if word[0] == ")" or not "(" in word or not ")" in word:
break
elif word[0] == "(":
if ")" in word:
word.remove(")")
... |
def pow(A, m):
# 기저 사례 : 제곱 수가 0이면 배열의 크기를 return
if m == 0:
return A
# 제곱 수를 2로 나눌 때 0이 아닐 경우
if m % 2 != 0:
# 짝수 갯수가 분할 정복 되도록 하나를 떼어놓음
return pow(A, m - 1) * A
# 제곱 수 분할
half = pow(A, m / 2)
return half * half
# 첫번째 값은 배열의 크기(5x5 = 25), 두번째 값은 배열의 제곱 수((5x5)^2 = 6... |
import sys
def getParent(x):
if cities[x] == x: return x
cities[x] = getParent(cities[x])
return cities[x]
def unionParent(a, b):
a = getParent(a)
b = getParent(b)
if a < b:
cities[b] = a
else:
cities[a] = b
def findParent(a, b):
a = getParent(a)
b = getParent(b... |
arr = []
for i in range(9):
arr.append(int(input()))
a = max(arr)
print(a)
print(arr.index(a)+1)
|
import sys
size = int(sys.stdin.readline())
array = [False] * 2 + [True] * (size - 1)
for (index, item) in enumerate(array):
if item:
for trueIndex in range(2 * index, len(array), index):
array[trueIndex] = False
print(array.count(True)) |
num = 10
result = 0
# 반복 함수
for i in range(1, num+1):
result += i
print(result)
# 재귀 함수
def recursiveSum(num):
if num == 1: # 더 이상 쪼개지지 않는 최소한의 작업에 도달했을 때, 답을 반호나하는 조건문을 포함해야 함
return 1
return num + recursiveSum(num-1)
print(recursiveSum(num))
|
import math
def RootsSearch (a,b,c):
d = (b**2)-(4*a*c)
if d > 0:
x1 = ((-b + math.sqrt(d)) / (2*a))
x2 = ((-b - math.sqrt(d)) / (2*a))
print(x1,x2)
elif d == 0:
x = -b / 2*a
print(x)
else:
print("Корней нет")
def ... |
import time
def create_set():
a = {i**2 for i in range(10)}
print(type(a))
print(a)
return a
def add_elem_in_set(Set):
elem = 100
start_time = time.time()
Set.add(elem)
print(Set)
print("--- %s seconds ---" % (time.time() - start_time))
def find_elem_in_set(Set):
elem = 100... |
import datetime
import calendar
def convert_to_epoch(date):
#date format=MM/DD/YYYY
day=int(date[3:5])
month=int(date[0:2])
year=int(date[6:10])
time=datetime.datetime(year,month,day,0,0)
time=calendar.timegm(time.timetuple())
return time
#print(convert_to_epoch("04/01/2012"))
|
from tkinter import *
counter = 0
def counter_label(label):
def count():
global counter
counter += 1
label.config(text=counter)
label.after(1000, count)
count()
def space():
l.config(fg="blue")
root = Tk()
root.title("Counting seconds")
root.configure(bg="black")
root.bind... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.