text stringlengths 37 1.41M |
|---|
# 2019-01-31
# number sorting and reading in list
number = [4, 6, 2, 7, 1, 8, 9, 0, 3, 5]
number.sort()
print(number[0])
print(number[9])
print(number[len(number) - 1])
print(number[-1])
|
# problem 7: expression calculator
# change minus to negative value with the integer
exp = input("Enter an expression: ").replace(" ", '').replace("-", "+-").split('+')
result = 0
for number in exp:
result += int(number)
print("=", result)
|
# 2019-01-29
# money rate calculator
money = int(input("Account balance: "))
rate = int(input("Rate (%): "))
year = int(input("Simulation year: "))
for i in range(year):
money += money*(rate/100)
print("Year " + str(i + 1) + ", balance is " + str(int(money)))
|
# problem 5: 5 word shiritori
f = open('dict_test.TXT', 'r', encoding='utf-8')
words = []
for line in f:
word = line.split(" : ", 1)[0]
if len(word) == 5:
if " n." in line:
words.append(word)
f.close()
previous = "apple"
used_words = [previous]
while True:
while True:
word =... |
import random
import math
print("\n-------- CONFIG YOUR GAME -------- \n")
lower = int(input("ENTER LOWER BOUND: "))
upper = int(input("ENTER UPPER BOUND: "))
print("\n--------- START THE GAME --------- \n")
x = random.randint(lower, upper)
print("\nYOU HAVE ONLY", round(math.log(upper - lower + 1, 2)), "CHANCES ... |
import itertools
valid = "Valid"
notValid= "Not Valid"
cardNumber = input("Enter your card number ")
def checkCard(cardNumber):
cardNumber=str(cardNumber)
if (len(cardNumber.split('-')) == 1 and len(cardNumber) == 16) or (len(cardNumber.split('-')) == 4 and all(len(i) == 4 for i in cardNumber.split("-... |
import codecademylib
from matplotlib import pyplot as plt
unit_topics = ['Limits', 'Derivatives', 'Integrals', 'Diff Eq', 'Applications']
middle_school_a = [80, 85, 84, 83, 86]
middle_school_b = [73, 78, 77, 82, 86]
def create_x(t, w, n, d):
return [t*x + w*n for x in range(d)]
# Make your chart here
school_a_x =... |
def multi_table(a):
for i in range(1,11):
print('{0} × {1} = {2}'.format(a,i,i*a))
if __name__ == '__main__':
a=input('Enter a number: ')
multi_table(float(a))
|
customer = ['fullname', 'type of account',500]
balance= customer.pop(2)
def deposit(balance,Amnt_deposit):
balance = balance + Amnt_deposit
return balance
def withdrawal(balance,Wid_Amnt):
balance = balance -Wid_Amnt
return balance
print('your balance after deposit is',deposit( balance,500))
print('you... |
import pandas as pd
import numpy as np
wine = pd.read_csv("C:\\Users\\cawasthi\\Desktop\\Data Science\\R ML Code\\dimensionality reduction\\wine.csv")
wine.describe()
wine.head()
'''
Perform Principal component analysis and perform clustering using first
3 principal component scores (both heirarchial and k mea... |
__author__ = 'student'
print('Hello World')
c = 10
print(c)
S = str(input())
print(S.replace('','*')[1:-1])
начальное_значение = 1
конечное_значение = 10
i = начальное_значение
while i < конечное_значение:
print(i,i*2,sep=',')
i += 1
print(1, 2, 3)
print(1, 2, 3, sep='')
print(1, 2, 3, sep='~')
print(4, 5,... |
from tkinter import *
from rwFileTest import *
import rwFileTest
root = Tk()
list = readfile()
createTree(list)
searchenty = StringVar()
outputlbl = StringVar()
insertentry= StringVar()
deleteentry = StringVar()
sizelbl=StringVar()
heightlbl=StringVar()
sizetext = "Dictionary Size",rwFileTest.size
depthtext = "Height ... |
# クラスの作成 コンストラクタ(インスタンス生成の初期設定メソッド) デクストラクタ(メモリ開放メソッド)
class Color:
def __init__(self, text="red"):
self.text = text
def __del__(self):
print(str(self) + "が破棄されました")
# デクストラクタは必須ではない
color = Color()
print(color.text)
print(color)
color2 = Color("green")
print(color2.text)
print(color2)
|
# 複数インスタンスの生成
class Color:
def __init__(self, r_name="red", g_name="green", b_name="blue"):
self.r_name = r_name
self.g_name = g_name
self.b_name = b_name
def name_p(self, delim=","):
r, g, b = self.r_name, self.g_name, self.b_name
print(f"{r}{delim}{g}{delim}{b}")
col... |
# クラスメソッド
class MyClass1:
def __init__(self, a="abc"):
self.a = a
# インスタンス変数
def print_a(self):
print(self.a)
# インスタンス変数aを持つメソッド
def print_hello(self):
print("hello")
# インスタンス変数を持たないメソッド
# クラスメソッドとして定義できる。
@classmethod
def print_bye(cls):
... |
# 子クラスにコントラクタを定義するとき、super関数を用いる super().親のコンストラクタ
class Parent:
parent_static_v = "親の静的変数"
def __init__(self, parent_self_v="親インスタンス変数"):
print("親のコンストラクタ")
self.parent_self_v = parent_self_v
def func_parent(self):
print("親のメソッド")
class Child(Parent):
child_static_v = "子の静的変... |
# メソッドの定義
class Color:
def __init__(self, r_name="red", g_name="green", b_name="blue"):
self.r_name = r_name
self.g_name = g_name
self.b_name = b_name
def name_p(self, delim=","):
r, g, b = self.r_name, self.g_name, self.b_name
print(f"{r}{delim}{g}{delim}{b}")
def ... |
def func(_):
return int(_) * 5
print(func(5))
print((lambda _: _*5)(5))
def func_conv(_):
if " " in _:
res = _.title()
else:
res = _.upper()
return res
print(func_conv("helloworld"))
print(func_conv("hello world"))
print((lambda _: _.title() if " " in _ else _.upper())("helloworld... |
# 変数のスコープ(範囲) if文と for文
global_v = "global"
# if文と変数
if True:
# ifブロックからでもグローバル変数は参照できる
print("0:{0}".format(global_v))
# ifブロックからでもグローバル変数を変更できる
global_v = "if1_local"
# ifブロックからローカル変数を設定できるし、当然に変更できる
local_v = "if2_local"
print("1:{0}".format(global_v))
print("2:{0}".format(local_v))
... |
import pandas as pd
from io import StringIO
import string
def topic(s):
if isinstance(s, float) or len(s) < 2 or "), (" not in s:
return ""
arr = s.split("), (")
tmp = arr[0].split(',')
text = tmp[0][3:len(tmp[0]) - 1]
num = tmp[1][1:len(tmp[1]) - 1]
# print(num)
return text
def ... |
def main():
word = input("Please enter a sentence: ")
count(word)
def count(word):
x = word.split()
length = len(x)
print(length)
return length
#def main():
#word = input("Please enter a sentence")
#print(count(word)
if __name__ == "__main__":
main()
|
"""Analyses a ciphertext and predicts whether ciphtext is a transpostion or substitution cipher
Applies letter frequency analysis to predict cipher type.
Compares ciphertext letter frequency against letter frequency proportion from military messages.
Letter frequency is unchanged for a letter transposition cipher (po... |
"""
Python provides a number of ways to perform printing. Research
how to print using the printf operator, the `format` string
method, and by using f-strings.
"""
x = 10
y = 2.24552
z = "I like turtles!"
# # print integer and float value
# print("Geeks : % 2d, Portal : % 5.2f" %(1, 05.333))
# # print integer value
# ... |
num = 2
name = 'Rabindra'
numType = type(num)
nameType = type(name)
typeType = type(nameType)
print('Number is ' + str(numType) )
# Number is <class 'int'>
print('Name is ' + str(nameType) )
# Name is <class 'str'>
print('Type is ' + str(typeType) )
# Type is <class 'type' |
print("Hello")
userInput='abc'
option=input("d or e?")
print("User input?",userInput)
incBy=input("key?")
key=int(incBy)
if option is 'e':
encryptedOutput=''
for ch in userInput:
asc=ord(ch)
asc=asc+key
newCh=chr(asc)
encryptedOutput= encryptedOutput+newCh
print("Enc... |
#Write a program which can compute the factorial of a given numbers.
#he results should be printed in a comma-separated sequence on a single line.
#Suppose the following input is supplied to the program:
a=8
total=0
while (a<1):
total=a*(a-1)
a=a-1
print(total)
|
import random
list_a = []
list_b = []
list_c = []
#length_a = int(input('enter the length of first list: '))
#length_b = int(input('enter the length of second list: '))
length_a = 50000
length_b = 50000
random_low = 0
random_high = 20000
while length_a > 0:
list_a.append(random.randint(random_low, rand... |
'''
Any generator also is an iterator(not vice versa). Any generator, therefore is a factory that lazily produces values. Here is
the same Fibonacci sequence factory, but written as a generator
'''
# Generator Function
from itertools import islice
def fib():
prev, curr = 0, 1
while True:
yield curr
# Yield fir... |
#Write a program which accepts a sequence of comma-separated numbers from
# console and generate a list and a tuple which contains every number.
num=input("Enter a number")
a=num.split(',')
print(a)
print(tuple(a))
##########teacher solution
num=input("Enter a number")
a=num.split(',')
#a = [item for item in a]
#... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
name = "Rabindra"
print("Your name is " + name)
name = input("Enter your name: ")
print(f"Your name is: {name}")
num = str(2)
print('My number is '+ num)
|
checkIn = [1,3,5]
checkOut = [2, 6, 8]
room = 1
r = 0
x = len(checkIn)
for j in range(0,x):
for i in range(0,x):
if (checkOut[j] >= checkIn[i+1]):
r+=1
if(room >= r):
r=0
else:
print("impossible")
|
a = int(input())
y=2*a
x =" minutos"
print(format(y)+x) |
a= float(input())
b= int(input())
c= int(input())
tip = (a * (b/100))
x= tip
tax = (a * (c/100))
total = a+ x+ tax
print(round(total))
|
def array(ara):
c = 1
for i in range(1, len(ara)):
if (ara[i] != ara[i - 1]):
ara[c] = ara[i]
c += 1
return c
if __name__== "__main__":
ara=[1,2,3,3,4,4,5,6]
x = array(ara)
print(ara[:x])
|
number = input("Enter the value :")
data_mapping = {
"1" : "One",
"2" : "two",
"3" : "Three"
}
output=""
for ch in number:
print(data_mapping.get(ch,ch))
hey = input("Enter a sentence")
x = input("enter your spilt char :")
print(hey.split(x))
|
def date_fashion(eu, par):
if eu <= 2 or par <= 2:
return 0
elif eu >= 8 or par >= 8:
return 2
else:
return 1 |
def string_permutation(str1,str2):
str_len1=len(str1)
str_len2=len(str2)
ascii_dict = dict.fromkeys([i for i in range(256)],0)
if (str_len1 != str_len2):
return False
for c in str1:
ascii_dict[ord(c)]+=1
for ch in str2:
ascii_dict[ord(ch)]-=1
for key in ascii_dict:
... |
def find_largest(numbers):
if len(numbers) == 1:
return numbers[0]
else:
m = find_largest(numbers[1:])
return m if m > numbers[0] else numbers[0]
|
from itertools import izip
from textwrap import wrap
# FASTA functions and classes
def fasta_itr(f) :
'''Returns a generator that iterates through a FASTA formatted file.
*f* may be either a text or gzipped file, or a file-like python object
representing either of these. Records are returned in the order ... |
#!/usr/bin/env python
import sys
import math
import random
import hashlib
SQRT_MAX_PRIME = 45
MAX_PRIME = SQRT_MAX_PRIME ** 2
HASH_SIZE = 20
STRING_SIZE = HASH_SIZE * 2
PRIME_SIZE = STRING_SIZE * 8 / 2
# https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
def generate_primes():
arr: list = [True for i in range(M... |
class Solution(object):
def reconstructQueue(self, people):
"""
:type people: List[List[int]]
:rtype: List[List[int]]
"""
#sort by height first and then by indexes
dic = dict()
height = []
for h,i in people:
if h not in dic:
... |
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string.
:type root: TreeNode
:rtype: str
... |
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def zigzagLevelOrder(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
... |
# Создать несколько переменных, вывести на экран.
# Запросить у пользователя несколько чисел и строк и сохранить в переменные. Вывести на экран.
name = 'Кеша'
age = 4
print('Переменные: ', name, age)
number = int(input('Введите любое число '))
print('Пользователь ввел число', number)
number1 = int(input('Введите дру... |
"""
CNN on mnist data using fluid api of paddlepaddle
"""
import paddle.v2 as paddle
import paddle.fluid as fluid
# Plot data
from paddle.v2.plot import Ploter
import matplotlib
matplotlib.use('Agg')
step = 0
def mnist_cnn_model(img):
"""
Mnist cnn model
Args:
img(Varaible): the input image to ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Sep 12 13:38:05 2017
@author: khushalidave
"""
"""
Reads a list of reviews and return the count of positive words in reviews.
"""
#function that loads a lexicon of positive words to a set and returns the set
def loadLexicon(fname):
newLex=set()
... |
known_users = ["Alice","Bob","Claire","Dan","Emma","Fred","Georgie","Harry","Holger","Holk"]
print(len(known_users))
while True:
print ("Hi! My Name is Travis")
name = input ("Wie ist dein name? ").strip().capitalize()
print (name)
if name in known_users:
print ("Hello {} wie gehts?... |
student_number = 12
# 학생의 번호를 출력합니다.
print('학생번호 : ', student_number)
# print(student_number)
st_number_str=str(student_number) # 문자열로 변경해주는 형변환 함수 str
print(type(student_number)) # 변수의 타입 확인
print(type(st_number_str)) # 변수의 타입 확인
number_list1 = range(10) # 0~9까지의 숫자 리스트 반환
number_list2 = range(5, 10) # 5~9까... |
#---------------------------------------------------------------
# Title: Assignment07
# Developer: Thivanka Samaranayake
# Date June01 2020
# Changelog:
# Thivanka, June01 2020, Created Pickling Script
# Thivanka, June02 2020, Created Exception Handling Script
#---------------------------------------------... |
class Date:
def __init__(self, date):
self.date = date
def get_date(self):
print('getting the date...')
return self.date
# csak egy fv a classon belül, nem kell hozzá a self, példány
@staticmethod
def to_dash_date(date):
return date.replace('/', '-')
@classmethod
def extra_year(cls, dat... |
from functools import wraps
def max_grade(max_grade_value):
'''Adds the 'max_grade' annotation'''
def max_grade_decorator(func):
'''Adds the 'max_grade' attribute to the specified function'''
func.max_grade = max_grade_value
@wraps(func)
def _wrapper(*args, **kwargs):
... |
#动态规划,大规模的问题,能由小问题推出;
#建立动态方程 f(x) = g(f(x-1)), 存储中间解, 按顺序从小往大算
#动态规划:求最长子序列
def lis(d):
b = []
for i,v in enumerate(d):
if i==0:
b.append(v)
if d[i] < b[-1]:
for k,bv in enumerate(b):
if d[i] > v:
b = b[0:k]
if d[i] > b[-1]:
b.append(d[i])
return b
#动态规划:斐波那契数列
def fib(n):
#缓存结果
results ... |
# KNN algorithm example
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# importing the dataset
url = "https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data"
# assign column names to the dataset
names = ['sepal-length', 'sepal-width', 'petal-length', 'petal-width', 'Class']... |
a = 9
b = 7
# ADD 2 NUMBERS
print(a + b)
# MULTIPLY 2 NUMBERS
c = a * b
print(c)
# DIVIDE 2 NUMBERS
d = a / b
print (d)
# INTEGER DIVISION
e = a // b
print(e)
# EXPONENT: b squared
print(b ** 2)
# MODULUS - remainder of a division
print(b % 3)
print(a % 4)
# EVEN? OR ODD - USE MOD
print(a % 2 == 0)
print(14 % 2 ... |
"""
Given a array of positive numbers and a positive number S, find the length of the smallest
contiguous subarray whose sum is greater than or equal to S.
Return 0, if no such subarray exist.
"""
import numpy
def smallest_subarray_with_given_sum(s, arr):
j = 0
ssum = 0
import math
length=math.inf
... |
## Caterpillar method
class Solution(object):
def lengthOfLongestSubstring(self, s):
"""
type s: str
rtype: int
"""
length = 0
#print(len(s))
chars = set()
left,right=0,0
while left < len(s) and right < len(s):
#if s[right] in cha... |
from utils import *
from constants import *
def process_words(word_list_file):
"""
This function reads a file of words and produces word-level and character-level information.
:param word_list_file: a file of words, one per line. '#' and '//' are used for comments.
:return: a list of unique words, a li... |
#!/bin/env python3
n = int(input())
print(*[num**2 for num in range(n)], sep="\n")
|
def display_board(board_state):
"""
Displays the given state string in a 3 X 3 tic tac toe board
"""
if type(board_state) != str:
raise TypeError('Given board input must be String')
if len(board_state) != 9:
raise Exception("Input board string length is not 9")
counter = ... |
number = 5
while number < 50:
number += 1
if number > 8:
print(number)
|
#!/usr/bin/python
# What is the largest prime factor of the number 600851475143
nums = [13195, 600851475143]
def is_prime(num):
if num == 1:
return False
if num % 2 == 0:
return False
for jakaja in range(3,int(num**0.5)+1, 2):
if num % jakaja =... |
def rob(nums):
even = sum(nums[1::2])
odd = sum(nums[0::2])
"""
if len(nums) % 2: # odd number of houses
#even = sum([i for i in range(len(nums)) if i % 2 == 1])
even = sum(nums[1::2])
#odd = sum([i for i in nums[:-1] if i % 2])
odd = sum(nums[0::2])
if len(nums) % ... |
print("Welcome to BMI calculator!")
height = float(input("enter your height in m: "))
weight = float(input("enter your weight in kg: "))
BMI = round(weight/height**2)
a = (f"Your BMI is {BMI}.")
if BMI<=18.5:
print(a, "You are underweight.")
elif BMI<25:
print(a, "You are normal weight.")
elif BMI<30:
p... |
import numpy as np
from scipy import optimize as opt
from back_propagation import back_propagation
from cost_function import cost_function
from cost_function import unroll_params
from feed_forward import feed_forward
def train(init_params, x, y, y_map, hyper_p=0, iters=100):
""" Trains a Neural Network, compares... |
import torch.nn.functional as F
import torch.nn as nn
class BinaryClassifier(nn.Module):
"""
Define a neural network that performs binary classification.
The network should accept your number of features as input, and produce
a single sigmoid value, that can be rounded to a label: 0 or 1, as out... |
# Author: Nick Zwart
# Date: 2013oct18
# Exercise 2:
# Make the port labeled 'in-data' require a 2-D float (64bit) array only.
# Set the output port to only post 1D arrays (modify the algorithm
# accordingly).
#
# Hint: Type-attributes can also be found in the Node Developer's Guide.
# Multi-dimensional ar... |
import unittest
from src.drink import Drink
class DrinkTest(unittest.TestCase):
def setUp(self):
self.drink1 = Drink("orange juice", 2.50, 0)
self.drink2 = Drink("beer", 6, 2)
def test_drink_has_name(self):
self.assertEqual("orange juice", self.drink1.name)
def test_drink_has_pri... |
from tkinter import *
class LoanCompare:
def __init__(self):
window = Tk()
window.title("Loan Compare")
frame1 = Frame(window)
frame1.pack()
Label(frame1, text = "Loan Amount").pack(side = LEFT)
self.amount = StringVar()
Entry(frame1, textvariable = self.amo... |
from tkinter import *
class MouseClicker:
def __init__(self):
window = Tk()
window.title("Mouse Position")
self.canvas = Canvas(window, height = 100, width = 250, bg = "white")
self.canvas.pack()
self.canvas.bind("<Button-1>", self.processMouseEvent)
window.mainlo... |
class Rectangle2D:
def __init__(self, x, y, width, height):
self.__x = x
self.__y = y
self.__width = width
self.__height = height
def getX(self):
return self.__x
def setX(self, x):
self.__x = x
def getY(self):
return self.__y
def setY(self,... |
"""
This is a class hierarchy of animals.
"""
# classes of vertebrates
class Animal:
def __init__(self, class_name, habitat):
self.class_name = class_name
self.habitat = habitat
def info(self):
print(f'In total, there are 5 classes of vertebrates. It is a {self.class_name}.')
... |
# put your code here.
our_file = open("test.txt")
#our_bigger_file =open("twain.txt")
#pseudo code
#open file
#create a function
#we want the function to take the body of text inside file and counts how many times
#each word occurs separated by spaces
#we need a empty dictionary to store word count
# create for loop ... |
class TreeMapNode:
__slots__ = 'key', 'val', 'left', 'right'
def __init__(self, key, val=None, left=None, right=None):
self.key = key
self.val = val
self.left = left
self.right = right
def __iter__(self):
if self:
if self.left:
for elem i... |
__author__ = 'MrBIGL'
from sys import argv
from os.path import exists
script, from_file, to_file = argv
print "Copying from %s to %s" % (from_file, to_file)
# we could do these two on one line, how?
# in_file = open(from_file) # open from file
# indata = in_file.read() # reads the data in the from file
# the in... |
from unittest import TestCase
class BasicTests(TestCase):
status = "Not Testing"
class_status = "Not Constructed"
@classmethod
def setUpClass(cls):
cls.class_status = "Set Up"
def setUp(self):
if self.class_status != "Set Up":
raise Exception("BasicTests was not \'Se... |
"""Database Functions
The functions that interacts with replit's builtin database named "db".
"""
from replit import db
def insert_testcase(uid, typ, idx, name, tc_in, tc_out):
"""Inserts the test case into the database.
Parameters
uid : int
The unique identification number of the test case
typ : str
... |
# Sebastian Raschka, 03/2014
# Date and Time in Python
import time
# print time HOURS:MINUTES:SECONDS
# e.g., '10:50:58'
print(time.strftime("%H:%M:%S"))
# print current date DAY:MONTH:YEAR
# e.g., '06/03/2014'
print(time.strftime("%d/%m/%Y"))
|
# Sebastian Raschka, 03/2014
# Getting the positions of min and max values in a list
import operator
values = [1, 2, 3, 4, 5]
min_index, min_value = min(enumerate(values), key=operator.itemgetter(1))
max_index, max_value = max(enumerate(values), key=operator.itemgetter(1))
print('min_index:', min_index, 'min_value:... |
from sympy import diff,symbols,hessian,poly,matrix2numpy,eye
from numpy import matrix,squeeze,asarray
from numpy.linalg import inv
global epsilon
epsilon = 1E-5
def fValue(f,x0,X):
"""
Description : Returns the value of the function f evaluated at point x0
Parameters:
1. f : sym... |
# on 2D array with 0 and 1 return array of sizes of all connected 1s,
# where connection is up/down left/right, but not diagonal
# [[1,0,0,1,0]
# [1,0,1,1,0]] => [2,3]
# O(rc) time | O(rc) space
def riverSize(matrix):
size = []
visited = [[False for value in row] for row in matrix] # 2D with all false
for ... |
class Solution(object):
def findRepeatNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
for i in range(len(nums)):
while i != nums[i]:
temp = nums[i]
# 似乎不能用:nums[i], nums[nums[i]] = nums[nums[i]], nums[i] 因为交换过程中nums[i]... |
a = 5
b = 3
print(f"{a} + {b} = {a+b}")
print(f"{a} - {b} = {a-b}")
print(f"{a} * {b} = {a*b}")
print(f"{a} / {b} = {a/b}")
print(f"{a} % {b} = {a%b}")
print(f"{a} ** {b} = {a**b}")
print(f"{a} // {b} = {a//b}")
|
import unittest
from app.models import Review,User
from app import db
class MovieTest(unittest.TestCase):
'''
Test Class to test the behaviour of the Movie class
'''
def setUp(self):
'''
Set up method that will run before every Test
'''
self.user_Mugera = User(username ... |
# Time Complexity :
# Space Complexity :
# Did this code successfully run on Leetcode :
# Any problem you faced while coding this :
# Your code here along with comments explaining your approach
class linkedListNode:
def __init__(self, k, v):
self.key = k
self.value = v
se... |
import sys
def binary_search(start,end,array):
if end<start:
return False
mid=(start+end)//2
if array[mid]==mid:
return mid
elif array[mid]<mid:
return binary_search(mid+1,end,array)
else:
return binary_search(start,mid-1,array)
n=int(input())
array=list(map(int,sys... |
def solution(s):
answer=''
if s[0].isalpha():
answer+=s[0].upper()
else:
answer+=s[0]
for i in range(1,len(s)):
if s[i].isalpha() and s[i-1]==' ':
answer+=s[i].upper()
elif s[i].isalpha() and s[i-1]!=' ':
answer+=s[i].lower()
else:
... |
from itertools import permutations
n = int(input())
numbers = [x for x in range(1,n+1)]
candidates = list(permutations(numbers, n))
candidates.sort()
for value in candidates:
for idx in range(n):
print(value[idx],end = ' ')
print()
|
while True:
try:
sentence = input()
if sentence == '':
break
lower, upper, number, blank = (0, 0, 0, 0) #순서대로 소문자 대문자 숫자 공백
for string in sentence:
if string.islower():
lower += 1
elif string.isupper():
upper += 1
... |
number=list(map(int,input()))
if len(number)==1:
print(number[0])
else:
result=0
if 0 in number[:2] or 1 in number[:2]:
result=number[0]+number[1]
else:
result=number[0]*number[1]
for i in range(2,len(number)):
if number[i]<=1:
result+=number[i]
else:
... |
def repeatedString(s, n):
if len(s)==1:
if s[0]=='a':
return n
else:
return 0
else:
count=s.count('a')*(n//len(s))
if n%len(s)==0:
return count
else:
count+=s[:n%len(s)].count('a')
return count
|
import sys
input = sys.stdin.readline
prime_numbers = set()
for number in range(2,(2*123456)+1):
check = True
for target in range(2,int(number**(1/2))+1):
if number % target == 0:
check = False
break
if check:
prime_numbers.add(number)
def count_decimal(n):
cou... |
def find_parent(parent, x):
if parent[x] != x:
parent[x] = find_parent(parent, parent[x])
return parent[x]
def union_parent(parent, a, b):
parent_a = find_parent(parent, a)
parent_b = find_parent(parent, b)
if parent_a < parent_b:
parent[parent_a] = parent_b
else:
parent... |
from itertools import combinations
def solution(nums):
answer = 0
combi = list(combinations(nums,3))
for value in combi:
current = sum(value)
check = True
for num in range(2,int(current**(1/2))+1):
if current % num == 0:
check = False
... |
'''여기서 핵심은 answer.sort(key=lamba x: x*3,reverse=True)라고 생각한다.
가장 이해가 안가는 부분이기도 하고....
일단 key를 사용하면 정렬할 기준을 설정할 수 있다고 한다.
예를 들어 여러 단어들이 담긴 리스트가 있다고 가정했을 때 만약 단어의 길이를 기준으로
리스트를 정렬하고 싶다면, list.sort(key=lambda x:len(x) 처럼 작성해야한다.
즉 이 문제에서는 x*3을 기준으로 정렬하기로 한거고, x*3인 이유는 문제 조건에서
numbers의 원소가 1000이하의 숫자라고 했기 때문이다.
이렇게 정렬한 것을 ... |
#!/usr/bin/python
import MySQLdb
# Function for connecting to the MySQL database
def mySQLConnect():
try:
# Open the database connection
conn = MySQLdb.connect("localhost", "root", "myPassword", "CSR")
print("A MySQL connection has been opened!")
return conn
except MySQLdb.Error as err:
print("Error while ... |
#aumento salarial conforme valor do salário
salario = float(input('Digite o valor do salário: R$'))
if salario > 1250.00:
aumento = (salario * 0.1) + salario
print('O valor do salário com aumento é: R${:.2f}'.format(aumento))
else:
aumento = (salario * 0.15) + salario
print('O valor do salário com aum... |
#multa acima do limite de velocidade
velocidade = float(input('Digite a velocidade do veículo: ')) #solicita a velocidade do veículo pelo usuário
#caso a velocidade seja superior ao permitido calcula a multa para o usuário
if velocidade > 80:
multa = (velocidade - 80) * 7.00
print('Você estava dirigindo a {}k... |
#aprovação de empréstimo para imóvel
valor = float(input('Valor do imóvel: R$ '))
salario = float(input('Valor do salário do comprador: R$ '))
periodo = int(input('Quantos anos vai pagar: '))
prestacao = valor / (periodo * 12)
print('Empréstimo de R${:.2f} em {} pestações o valor da prestação fica R${:.2f}'.format(val... |
#converter ºC em ºF
temperatura = float(input('Digite uma temperatura em ºC:'))
fahrenheit = (temperatura * 9 / 5) + 32
print('A temperatura é {}ºF'.format(fahrenheit)) |
#mostrar o primeiro e ultimo nome
nome = str(input('Digite seu nome completo: ')).strip()
novo = nome.split()
print('Primeiro nome: {}'.format(novo[0]))
print('Último nome: {}'.format(novo[-1])) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.