text stringlengths 37 1.41M |
|---|
#!/usr/bin/python3
import sys
s = input("Enter input:")
print ("You entered:", s)
r = input("Enter another line:")
words = r.split(' ')
print ("The first word is:", words[0])
print ("The second word is:", words[1])
rest = (' '.join(words[2: ]))
print ("The rest of the line is:", rest)
sys.exit() #normal exit status
|
import tkinter as tk
from tkinter import ttk
# This computes the Celsius temperature from the Fahrenheit.
def findcel():
famt = ftmp.get()
if famt == '': #not double quote, 2 single quotes
cent.configure(text='')
else:
famt = float(famt)
camt = ... |
from typing import List
class Solution:
def lemonadeChange(self, bills: List[int]) -> bool:
billchange = dict(zip([5, 10, 20], [0] * 3))
for b in bills:
billchange[b] += 1
change = b - 5
while change >= 10 and billchange[10] > 0:
change -= 10
bi... |
import functools
def compare(a, b):
if a[0] != b[0]: return a[0] - b[0]
else:
return a[1] - b[1]
n = int(input())
coords = []
for i in range(n):
coords.append(list(map(int, input().split())))
for c in sorted(coords, key=functools.cmp_to_key(compare)):
print(" ".join(map(str, c))) |
def getAvailableLetters(lettersGuessed):
'''
lettersGuessed: list, what letters have been guessed so far
returns: string, comprised of letters that represents what letters have not
yet been guessed.
'''
# FILL IN YOUR CODE HERE...
b=""
temp="abcdefghijklmnopqrstuvwxyz"
for... |
import math
import numpy as np
import matplotlib.pyplot as plt
#Square Wave approximation by Fourier Series:
#y=4/pi*(sin(x) + sin(3x)/3 + sin(5x)/5 + ... sin(nx)/n) terms
n = 100
# generate x's to calculate the points.
x = np.arange(0,360,1)
#generate the odd numbers to add the sines terms
odd = np.arange(1,n+2,2)
... |
print ("hello word, how are you")
feel = input("how is are you?")
if feel == "good":
print("do your work")
elif feel== "fine":
print("nice")
else:
print("do something good")
|
from collections import deque
def depthFirstSearch(graph, start):
#Have a list to keep track of where to go next
toVisit = deque()
#A set to keep track of where you've already been
visited = set()
toVisit.append(start)
visited.add(start)
while (not len(toVisit) == 0):
currentNode = toVisit.pop()
print(cu... |
import redis
import sys
import json
import string
def is_json(myjson):
try:
json_object=json.loads(myjson)
except ValueError,e:
return False
return True
#opening the file to be read
file=open('../nutrition.json','r')
#linking up with redis
red_access=redis.StrictRedis(host='localhost',port=63... |
# Write a class to hold player information, e.g. what room they are in
# currently.
class Player:
def __init__(self, name, current_room):
self.name = name
self.current_room = current_room
self.items = []
def get(self, item):
self.items.append(item)
print(f'\nYou ... |
""" 1. Ler 5 notas e informar a média """
nota = media = soma = 0
for i in range(1, 6):
nota = float(input(f'Digite a nota {i}: '))
soma += nota
media = soma / 5
print('A média é: ', media)
""" 2. Imprimir a tabuada do número 3 (3 x 1 = 1 - 3 x 10 = 30) """
i = 1
while i <= 10:
print(f'3 x {i}= ', i*3)
... |
# --- PRIMEIRO EXEMPLO ---
# executa 11 passos - passando o número 10
# BIG O(n) - de acordo com o valor de N que for passado
def soma1(n):
soma = 0
for i in range(n+1):
soma += i
return soma
%timeit soma1(10)
# --- SEGUNDO EXEMPLO ---
#sempre executará 3 passos
# BIG O(3) - sempre executará 3 ações
def ... |
class Triangulo:
#construtor
def __init__ (self, lado1, lado2, lado3, base, altura):
self.lado1 = lado1
self.lado2 = lado2
self.lado3 = lado3
self.base = base
self.altura = altura
#funções de triangulo
def area(self):
return (self.base * self.altura) / 2
t1 = Triangulo(2,1,3,4,3)
pr... |
# -*- coding: UTF-8 -*-
'''=================================================
@Project -> File :learnOpenCV -> select_roi
@IDE :PyCharm
@Author :QiangZiBro
@Date :2020/12/6 8:54 下午
@Desc :
=================================================='''
import cv2
if __name__ == '__main__' :
im = cv2.imread("image.jp... |
#!/usr/bin/env python3
def edit_distance(s1: str, s2: str) -> int:
n = len(s1)
m = len(s2)
edit = [[None for i in range(1 + m)] for j in range(1 + n)]
for i in range(1 + m):
edit[0][i] = i
for i in range(1, 1 + n):
edit[i][0] = i
for j in range(1, 1 + m):
replace... |
#!/usr/bin/env python3
def coinChange(coins, amount):
if amount < 0:
return -1
dp = [(1 + amount) for i in range(1 + amount)]
dp[0] = 0
for i in range(1, 1 + amount):
for coin in coins:
if coin > i: break
dp[i] = min(dp[i], 1 + dp[i - coin])
if dp[amount] > a... |
class Node:
def __init__(self, data):
self.data = data
self.next = None
class Solution:
def insert(self, head, data):
p = Node(data)
if head == None:
head = p
elif head.next == None:
head.next = p
else:
start = head
... |
def is_prime(n):
"""Returns True if n is prime."""
if n == 1:
return False
if n == 2:
return True
if n == 3:
return True
if n % 2 == 0:
return False
if n % 3 == 0:
return False
i = 5
w = 2
count = 0
while i * i <= n:
print('{}: ... |
def is_closer(a, b, c, key):
dx1 = (b[0] - a[0]) ** 2
dy1 = (b[1] - a[1]) ** 2
dx2 = (c[0] - a[0]) ** 2
dy2 = (c[1] - a[1]) ** 2
return dx1 + dy1 < dx2 + dy2
def is_in_line(a, b, c):
if a[0] == b[0] and a[1] == b[1]:
return False
ax = c[0] - a[0]
ay = c[1] - a[1]
cx = b... |
#!/bin/python3
import math
import os
import random
import re
import sys
'''
5 / 2 = 1
2 / 2 = 0
1
'''
def get_bin(n):
binary = []
while n > 1:
bit = n % 2
binary.append(bit)
n = n // 2
binary.append(n)
return binary
def consecutive_one(binary):
best_ones = 0
... |
# Joining tables
# source: https://stackoverflow.com/questions/44327999/python-pandas-merge-multiple-dataframes/44338256
# :data_frames: :list of pandas data frames:
# :byvars: :list of size 1 with the element as string name of id variable in all datasets:
def merge_dfs(data_frames,**kwargs):
from functools import ... |
import os
import random
import struct
import sys
import zlib
MAX_HEIGHT = 2000
MAX_WIDTH = 2000
# ERROR CHECKING ARGUMENTS
# check for 2 command line arguments
if len(sys.argv) != 3:
print("Usage: randompic.py width height")
for arg in sys.argv:
print(arg)
exit()
# check dimensions are bet... |
import numpy as np
import re
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
# A function to compute the cosine similarity between two vectors.
#
# Returns: A number in the range [0,1] indicating the similarity between the
# two vectors.
def cosine_similarity(v1, v2):
dot_product = np.dot... |
#!/usr/bin/python
import sys
if sys.version[0]>="3": raw_input = input
filename = raw_input("full path and file name, then press ENTER:- ")
binary = open(filename, "rb+")
length = len(binary.read())
array = ""
for position in range(0, length, 1):
binary.seek(position)
char = hex(ord(binary.read(1)))[2:]
... |
import json
import math
#this function reads content from the json file 'customers.json'. Could easily be modified to parse json data queried from an API.
def get_json_contents():
customers={}
try:
f = open(input('Please enter filename: '), 'r')
s = f.read()
customers = json.lo... |
c=input()
li=['a','e','i','o','u']
if(c>='a' and c<='z'):
if(c in li):
print("Vowel")
else:
print("Consonant")
else:
print("invalid")
|
from abc import ABC, abstractmethod
from math import inf
def check_version(from_version, to_version):
if from_version < 0:
raise ValueError("Initial version is less than zero")
if to_version < 0:
raise ValueError("Final version is less than zero")
if to_version < from_version:
rais... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from fractions import Fraction
__all__ = ['desbovesp', 'DesbovesCurvePoint']
def gcd(a, b):
while b != 0:
a, b = b, a-(a//b)*b
return a
def desboves_tangent(x, y, z):
"""
Return the third point of intersection of the tangent
to x^3 + y^3 = ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import numpy as np
from utilities import isprime, factorize2, sqrtInt
from itertools import chain
def primesum_naive(n):
"""
A slow, reference implementation. Add up
the all of the primes in the range [0, n]
"""
retval = 0
k = 2
while k <= n:... |
#!/usr/bin/env python
#
"""
Routines for looping over numbers formed from a
given sequence of primes below a fixed bound.
"""
from utilities import sqrtInt, prod
def bps(xs, n):
"""
For an increasing sequence xs of relatively
prime numbers and an upper bound n>=1, compute
all of the products <=n of s... |
class Solution:
def rotate(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: void Do not return anything, modify matrix in-place instead.
"""
n = len(matrix)
for k in range(n // 2):
for j in range(n - k - k - 1):
r = [[k, k +... |
class Solution:
def canMeasureWater(self, x, y, z):
"""
:type x: int
:type y: int
:type z: int
:rtype: bool
"""
def gcd(a, b):
return b if a % b == 0 else gcd(b, a % b)
if z == 0: return True
elif x == 0 or y == 0 or (z > x... |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def rob(self, root):
"""
:type root: TreeNode
:rtype: int
"""
f = dict()
def tohash(root,... |
print('\n','*************NUMPY INDEXING AND SELECTION*****************','\n')
import numpy as np
arr = np.arange(0,11)
print(arr) #[ 0 1 2 3 4 5 6 7 8 9 10]
print(arr[8]) # 8
print(arr[1:5]) #[1 2 3 4]
print(arr[0:6]) #[0 1 2 3 4 5]
print(arr[5:]) #[ 5 6 7 8 9 10]
print('\n',... |
def say(number):
number_spoken = ''
saynum = {
'0' : 'zero', '1' : 'one', '2' : 'two', '3' : 'three',
'4' : 'four', '5' : 'five', '6' : 'six', '7' : 'seven',
'8' : 'eight', '9' : 'nine', '10': 'ten', '11': 'eleven',
'12': 'twelve', '13': 'thirteen', '14': 'fourteen', '15': 'fift... |
def find_anagrams(word: str, candidates: list[str]):
return [i for i in candidates if sorted(word.lower()) == sorted(i.lower()) and word.lower() != i.lower()]
|
import string
def pangram(sentence=None):
return is_pangram(sentence)
def is_pangram(sentence):
pangramFlag = True
aleph = list(string.ascii_lowercase)
for letter in aleph:
if letter not in sentence.lower():
pangramFlag = False
break
return pangramFlag
|
import random
rand= random.randint(1,9)
chances=0
while(chances<5):
number= input("Guess a number 1-9")
print('Enter guess:', number)
if (number<rand):
print("Guess higher!")
elif(number>rand):
print("Guess Lower!")
else:
print("You Won!!")
chances+=1
if not chances <5:
... |
# works but too inefficient
def josephus(n, k):
if not type(n) == list:
raise TypeError
increment = k - 1
tracker = 0
result = []
index = []
# len inefficient for string lists
# lazy, trying to speed up
try:
if type(n[0]) == int or type(n[0] == bool):
len_n =... |
"""
A "True Rectangle" is a rectangle with two different dimensions and four equal angles.
We want to decompose a given true rectangle into the minimum number of squares.
Then aggregate these generated squares together to form all the possible true rectangles.
You should take each square with its all adjacent squares... |
# my solution
def pig_it(text):
text_list = text.split(" ")
empty_list = []
for i in text_list:
if i.isalnum():
i = i[1:] + i[0] + "ay"
empty_list.append(i)
else:
empty_list.append(i)
return " ".join(empty_list)
# list comprehension again
def pig... |
#
# Work out the first ten digits of the sum of the following one-hundred
# 50-digit numbers.
#
def main():
total = 0
with open("digits.txt", "r") as txt:
for rivi in txt.readlines():
tmp = ""
for numero in rivi.replace("\n", ""):
tmp += numero
total... |
#
# 2520 is the smallest number that can be divided by each of the numbers
# from 1 to 10 without any remainder.
#
# What is the smallest positive number that is evenly divisible by all of
# the numbers from 1 to 20?
#
def divi20(x):
for i in range(1, 21):
if(x % i != 0):
return False
retur... |
#
# The sum of the squares of the first ten natural numbers is,
# 1^2 + 2^2 + ... + 10^2 = 385
#
# The square of the sum of the first ten natural numbers is,
# (1 + 2 + ... + 10)^2 = 552 = 3025
#
# Hence the difference between the sum of the squares of the first ten natural
# numbers and the square of the sum is 3025 −... |
import matplotlib.pyplot as plt
import numpy as np
def plot_data(X, y):
plt.figure()
# ===================== Your Code Here =====================
# Instructions : Plot the positive and negative examples on a
# 2D plot, using the marker="+" for the positive
# examples ... |
import transportation_tutorials as tt
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import warnings
warnings.filterwarnings('ignore')
bridge = pd.read_csv(tt.data('FL-BRIDGES'))
print(bridge.info())
print(bridge.head())
print(bridge['SD #'])
print(bridge['County'])
# Whi... |
limit = int(input("Enter the limit :"))
looplimit = 2*(limit+1)+1
for i in range(1,looplimit):
if i<limit+1 :
for j in range(1,i-1):
print(j,end=" ")
else:
for j in range(1,looplimit-i):
print(j,end=" ")
print(" ")
|
class Node:
def __init__(self, key):
self.left = None
self.right = None
self.val = key
def printpostorder(root):
if root:
# First recur on left child
printpostorder(root.left)
# the recur on right child
printpostorder(root.right)
... |
# # Negative indexes
# spam = ['cat', 'bat', 'rat', 'elephant']
# spam[-1] # elephant
# print(spam[-1])
# # Slices
# spam[1:3]
# print(spam[1:3])
# # length
# print(len(spam))
# *********************************** For loops ***********************************
# for i in range(4):
# print(i)
# for i in [5, ... |
def edad(edadActual, añoActual):
if edadActual > 0:
if añoActual > 0:
años = 2025 - añoActual
edadNueva = edadActual + años
return edadNueva
else:
print("El año ingresado es negativo")
else:
print("La edad ingresada es negativa")
def num... |
print('*'*30)
print ('欢迎进入游戏')
print ('*'*30)
import random
username=input('请输入你的用户民:')
money=0
answer=input ('确定进入游戏吗?(y/n):')
if answer=='y':
while money<2:
n=int(input('金币不足,请充值(100块钱30个币,充值必须是100的倍数):'))
if n%100==0 and n>0:
money=(n//100)*30
print('当前剩余游戏币是:{},玩一局游戏扣除2个币'.forma... |
from random import randint
randVal = randint(0,100)
while(True):
guess = int(input("Enter your guess: "))
if guess == randVal:
break
elif guess<randVal:
print("Your guess was too loo")
else:
print("Too high")
print("You guessed correctly with:",guess)
from random import random... |
from enum import Enum
import itertools
import random
class CombatEventCode(Enum):
DAMAGE = 1
DEATH = 2
ESCAPE = 3
FAIL_TO_ESCAPE = 4
JOIN = 5
VICTORY = 6
class DeathReason(Enum):
COMBAT = 1
OUT_OF_FUEL = 2
class CombatAction(Enum):
FIGHT = 1
FLEE = 2
... |
from enum import Enum
import random
class EventProfile:
"""Class that defines under what circumstances something happens."""
def __init__(self, name, percentChance, dynamicFunc=None, description=None, nodes=(), edges=(), duration=1):
"""
name - name of the event.
percentChance... |
"""
The factory pattern is a means to create new objects, without explicitly having to
specify the exactly class or object that will be created. Typically this is handled
via calling a factory function/method (either through an interface implementation or overriding
a method in a derived class.
An example is outlined... |
# -*- coding: utf-8 -*-
print "numero primo o no primo"
class a:
def b(self):
numero = int(raw_input("numero:"))
return numero
def c(self, numero):
i = 1
for i in range(1):
contador = numero % 2
if contador == 1:
print "el numero es primo"
elif contador > 1:
contador = numero % i
elif con... |
from termcolor import colored
from pyfiglet import figlet_format
import requests
import random
figlettext = figlet_format("Dad Jokinator 1.1","slant")
color_figlettext = colored(figlettext,"cyan")
print(color_figlettext)
k = 0
while k == 0:
user_input = input("Take your daily dad joke dose. Give me a topic: "... |
class Node:
def __init__(self, data):
self.value = data
self.next = None
class LinkList:
def __init__(self):
self.head = None
def print_list(self):
curr = self.head
while curr is not None:
print(curr.value)
curr = curr.next
def add_va... |
class Node:
def __init__(self, data):
self.value = data
self.next = None
class LinkList:
def __init__(self):
self.head = None
def print_list(self):
curr = self.head
while curr is not None:
print(curr.value)
curr = curr.next
def revers... |
# coding=utf8
import sys
import re
#regex = r"[-'a-zA-ZÀ-ÖØ-öø-ÿ]+" # raw string
#regex = r"[-'a-zA-ZÀ-ÖØ-öø-ÿ0-9]+" # raw string
#regex = r"1. PARA QUE ESTE MEDICAMENTO É INDICADO?"
regex = r"INDICADO\?(?s)(.*?)2\."
if __name__ == '__main__':
fileName = sys.argv[1]
document = open(fileName,'r')
co... |
Word=input("enter the string ")
def most_frequent(string):
d=dict()
for key in string:
if key not in d:
d[key]=1
else:
d[key]+=1
return d
#using the most frequent function
output = most_frequent(Word)
frequency = dict( sorted(output.items(),
key... |
# time complextiy: o(n)
# leetcode: accepted
# explainatin: since it is a binarry tree, the left subtree can have values ranging
# from (-infintiy, root.val), beacse the left subtree should always be smaller than the root valuw and
# the right subtree can have values ranging from (roor.val,+ infinity) . right subtree s... |
#resultado igual ao exemplo-revert.py
pal = raw_input("Digite uma palavra: ")
aux = ""
for i in range(len(pal)):
aux = pal[i] + aux
print aux
|
'''
作者:Jing
date:2020-08-15
功能:计算第几天,需要分辨是否闰年
用list
'''
from datetime import datetime
def is_leap_year(year):
'''
判断是否闰年,是返回True,不是返回False
'''
is_leap = False
if (year % 400 == 0) or ((year % 4 == 0) and (year % 100 != 0)):
is_leap = True
return is_leap
def ma... |
'''
developer: Wendy
date: Aug 29,2020
version: 9.0
function: 数据处理 pandas
'''
import pandas as pd
def main():
aqi_data = pd.read_csv('china_city_aqi.csv')
# print('基本信息:')
# print(aqi_data.info())
#
# print('数据预览;')
# print(aqi_data.head()) #print first 5 rows
#如果是数字可以m... |
# Practice python in 16 days
# https://clock.kaiwenba.com/clock/course?sn=ExhvY&course_id=23
'''
选择要爬取故事的网站
爬取网页内容
提取网页中故事主体内容
发送邮件
'''
# 下面的这段代码用来构建爬取函数,读入url,返回url中的内容。
import requests
def getHTMLText(url):
headers = {'User-Agent':'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_8; en-us) AppleW... |
'''Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, determine if s can be segmented into a space-separated sequence of one or more dictionary words.
Note:
The same word in the dictionary may be reused multiple times in the segmentation.
You may assume the dictionary does not ... |
'''You are driving a vehicle that has capacity empty seats initially available for passengers. The vehicle only drives east (ie. it cannot turn around and drive west.)
Given a list of trips, trip[i] = [num_passengers, start_location, end_location] contains information about the i-th trip: the number of passengers tha... |
'''Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary).
You may assume that the intervals were initially sorted according to their start times.'''
class Solution:
def insert(self, intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]:
re... |
class Stack:
def __init__(self):
self.container = []
def push(self, elem):
self.container.append(elem)
def pop(self):
return self.container.pop()
def peeK(self):
return self.container[-1]
def show(self):
return self.container
obj = Stack()
obj.push(5)
o... |
name = "Srini"
age = 43
print("Hello World!!")
print(f"Name is {name} \nage is {age}")
if age > 40:
print("Getting Older")
else:
print("You are Young")
name_list=["srini","vikas","srini","landry"]
name_list.remove("srini")
print(name_list)
|
class RemoveDuplicate:
def remove_duplicate(self, nums):
j = 0
for i in range(0, len(nums) -1):
# print (len(nums) -1 )
if nums[i] == nums[i+1]:
j += 1
return len(nums) - j
def removeDuplicates(arr, n):
if n == 0 or n == 1:
r... |
class Node:
def __init__(self, value):
self.val = value
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def traverse(self, head):
#node = head
while head:
print ("node_value: ", head.val)
head = head.next
retur... |
def fibonacci(n):
fib = [0, 1]
if n >= 2:
for i in range(2, n+1):
fib.append(fib[i-1] + fib[i-2])
return fib[n]
if __name__ == '__main__':
print(fibonacci(0))
print(fibonacci(1))
print(fibonacci(2))
print(fibonacci(10))
|
#!usr/bin/python
from urllib.request import urlopen
import hashlib
from termcolor import colored
sha1hash = input('[*] Enter SHA1 hash: ')
passlist = str(urlopen('https://raw.githubusercontent.com/iryndin/10K-Most-Popular-Passwords/master/passwords.txt').read(), 'utf-8')
for password in passlist.split('\n'):
ha... |
num = -10
iflag = ""
if (num < 0):
num *= -1
iflag = "i"
for i in range(1,num):
if i**2 == num:
print("Square root is",i)
break
elif i**2 > num:
print("Square root is about :",(i-1),end=iflag)
break |
def factorial(n):
if n==0:
return 1
return n*factorial(n-1)
x = int(raw_input("enter a no:"))
print factorial(x)
|
from ...point import Point
INIT_ERROR_MSG = ('HorizontalMembers can only be instantiated with either a '
'length value or with points')
class HorizontalMember:
"""Base class for joists, beams, and girders
Parameters
----------
length : float
Length of member
points : l... |
def stringMatch(text, pattern):
n = len(text)
m = len(pattern)
for s in range(n-m+1):
for t in range(m):
if(text[s+t]!=pattern[t]):
break
else:
print("Match found at " + str(s))
text = input("Text: ")
pattern = input("Pattern: ")
stringMatch(text, pattern)
|
import random
def gcd(x, y):
while(y):
x, y = y, x % y
return x
def powerMod(x, y, p):
res = 1
x = x % p
while(y > 0):
if((y & 1) == 1):
res = (res * x) % p
y = y >> 1
x = (x * x) % p
return res
def isPrime(n):
if (n <= 1 or n%2 == 0):
return False
for k in range(50):
while T... |
num = input("결제 금액을 입력하세요: ")
if num.isdigit():
num=num[::-1]
ret = ''
for i, c in enumerate(num):
i+=1
if i !=len(num) and i%3 ==0:
ret +=( c + ',')
else:
ret +=c
ret = ret[::-1]
print(ret + "원" )
else:
print('입력한 내용 %s는 숫자가 아닙니... |
def countBirth():
ret=[]
for y in range(1980,2016):
countM=0 #누계변수는 초깃값 0으로 꼭 해주기
countF=0;
filename = 'names/yob%d.txt' %y #이거중요 !
with open(filename , 'r') as f: #이거중요 !
data =f.readlines()
for d in data:
if d[-1] == '\n' : #-1은 젤 ... |
"""
append()함수의 중요성
"""
import numpy as np
#리스트 append
list_data = []
year = 2018
total_sales = 150000000
list_data.append((year, total_sales)) #안에괄호는 튜플, 밖에 괄호는 함수괄호 , append 함수는 반드시 하나의 인자만 넣어야한다.
print(list_data)
#배열만들기
arr1= np.arange(15)
arr2= np.arange(1,10,0.5) #10 보다 작은 0.5까지
print(arr1)
print... |
import math
def calcCube():
a = input("Please enter the height of the side in cm:")
return round(float(a) ** 3, 2)
def calcTetrahedron():
side = input("Please enter the height of the side in cm:")
return round(float(side) ** 3 / (6 * math.sqrt(2)), 2)
def main():
while True:
print("Cho... |
import sys,os,random,pdb
class Node:
def __init__(self,data):
self.data = data
self.next = None
class Circular_list:
def __init__(self):
self.head = None
self.tail = self.head
def insert(self, data):
curr = self.head
newnode = Node(data)
... |
import unittest
from solutions._1_two_sum import Solution
class TestMainMethod(unittest.TestCase):
def test_when_the_pair_exists(self):
target = Solution()
actual = target.main([1, 3, 5, 9, 2], 6)
expected = [0, 2]
self.assertListEqual(actual, expected)
def test_when_the_pai... |
#!/usr/bin/env python2
# DB- API Code to connect to PostgreSQL database
import psycopg2
# Top 3 articles query
top_three_article_query = """select ar.title, count(*) as num from log l,
articles ar where ar.slug = substring(l.path,10)
and status = '200 OK' group by ar.t... |
import sys
DEFAULT_CELLS = 100
numberOfCells = DEFAULT_CELLS
cells = [0]
ptr = 0
loopStack = []
# @return array
# This method prompts the user for a file name and then attempts to open it. If the file is not found, it throws an
# error. It returns a list of all the data in the file. A line in the file is a cell in th... |
# Created on: 11th September, 2021
# Author: Bharadwaj Yellapragada
# Day 2: Is that a leap year??
# Language: Python
import datetime
def main():
try:
year = int(input("Enter Year: "))
if year <= 0:
raise ValueError
except ValueError:
print("Please enter only a number gre... |
# Problem:
# Given an array with 3 elements, return k-th numbers.
# Condition(s):
# 1. First 2 elements mean the range of slicing.
# 2. Third element means the number of k-th after sorting.
# My Solution:
def solution(array, commands):
answer = []
for command in commands:
temp = array[command[0] - 1:c... |
# Problem:
# Given the number of tiles, Return the circumference length of the tile.
# Condition(s):
# 1. The tile ornament was made with a square tile, starting with a square tile with one side, and gradually adding larger tiles.
# My Solution:
def solution(N):
x = y = 1
for i in range(1, N):
if i % 2... |
# Problem:
# Print the average excluding the maximum and minimum values.
# My Solution:
T = int(input())
for i in range(T):
temp = list(map(int, input().split()))
print("#{}".format(i + 1), end=" ")
print(int(round((sum(temp) - max(temp) - min(temp)) / (len(temp) - 2),0)))
|
# Problem:
# Given N scores as input, print the median value.
# Condition(s):
# 1. Numbers are odd numbers between 1 and 199.
# My Solution:
N = int(input())
temp = sorted(list(map(int, list(input().split()))))
print(temp[len(temp) // 2])
|
# Problem:
# Return what day of the week 'a' month 'b' is when January 1, 2016 is Friday.
# My Solution:
def solution(a, b):
days = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
day = -1
for i in range(a - 1):
day += days[i]
day += b
mod = day % 7
if mod == 0:
answer = 'FRI'... |
# Problem:
# In number baseball game, return the number of possible cases.
# Condition(s):
# 1. The number is a triple digit and each number is between 1 and 9 with no redundancy.
# 2. Strike if the number has a number with same position.
# 3. Ball if the number has a number with different position.
# 4. Out if the num... |
# Problem:
# Given the commands of max heap, print the output.
# Condition(s):
# 1. 1 means push.
# 2. 2 means pop.
# My Solution:
import heapq
answer = []
for i in range(int(input())):
N = int(input())
comm = []
heap = []
out = []
for j in range(N):
comm.append(tuple(map(int, input().spli... |
# Problem:
# Given costs of brdige constructions among islands, return the minimum costs of brdiges satisfying that all islands are connected.
# Condition(s):
# There is only one bridge among two islands at most.
# My Solution:
def solution(n, costs):
answer = 0
costs.sort(reverse=True, key=lambda x: x[2])
... |
# Problem:
# Given a string, return the middle character.
# Condition:
# 1. If the length of string is even number, return 2 characters.
# My Solution:
def solution(s):
length = len(s)
if length % 2 == 0:
answer = s[length // 2 - 1:length // 2 + 1]
else:
answer = s[length // 2]
return a... |
# Problem:
# Print the grade of the nth student.
# Condition(s):
# 1. Grades are given in order of total score.
# 2. The total score is calculated by adding up 35% of the midterm score, 45% of the final test score, and 20% of the assignment score.
# 3. The same grade can be given as the number of students/10.
# My Sol... |
# Problem:
# Given a list of scores, print the mode value.
# My Solution:
from collections import Counter
T = int(input())
for i in range(T):
N = int(input())
scores = list(map(int, input().split()))
print("#{}".format(N), end=" ")
cnt = Counter(scores)
print(cnt.most_common()[0][0])
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.