text stringlengths 37 1.41M |
|---|
a,b,c = map(int, input("세 정수를 입력하시오: ").split())
if a>b:
if a>c:
if b>c:
print(a,b,c)
else:
print(a,c,b)
else:
print(c,a,b)
else:
if b>c:
if a>c:
print(b,a,c)
else:
print(b,c,a)
else:
print(c,b,a)
|
x1 = int(input("x1: "))
y1 = int(input("y1: "))
x2 = int(input("x2: "))
y2 = int(input("y2: "))
def abs(x,y):
if x - y > 0:
return x-y
else:
return y - x
def distance(x1, y1, x2, y2):
r = ((abs(x1,x2))**2 + (abs(y1,y2))**2)**0.5
return r
print("두 점 사이의 거리는", distance(x1, y1, x2, y2))
... |
import math
def circle(r):
area = math.pi * r * r
circum = 2 * math.pi * r
return area, circum
radius = int(input("반지름을 입력하세요: "))
(x, y) = circle(radius)
print("원의 넓이는 {}이고 원의 둘레는 {}이다.".format(x, y))
|
s = input("알파벳을 입력하시오: ")
if s in ["a","e","i","o","u"]:
print(s,"은(는) 모음입니다.")
else:
print(s,"은(는) 자음입니다.")
|
import turtle
t = turtle.Turtle()
t.shape("turtle")
i = 0
while i < 5:
t.forward(50)
t.left(144)
i = i + 1
|
nlist = input("문자열을 입력하세요: ")
for i in range(len(nlist)):
print(nlist[:i])
for i in range(len(nlist)):
print(nlist[:len(nlist)-i])
|
money = int(input("투입한 돈: "))
price = int(input("물건값: "))
change = money - price
print("거스름돈: ", change)
cash = change // 1000
coin500 = change % 1000 // 500
coin100 = change % 500 // 100
coin50 = change % 100 // 50
coin10 = change % 100 % 50 // 10
print("1000원: {0}개".format(cash))
print("500원: {0}개".format(coin500... |
import numpy as np
x = np.array([['a','b','c','d'],['c','c','g','h']])
print(x[x == 'c'])
mat_a = np.array([[10,20,30],[10,20,30]])
mat_b = np.array([[2,2,2],[1,2,3]])
print(mat_a-mat_b)
|
import re
while True:
password = input("패스워드를 입력하세요: ")
if (len(password)< 8) \
or not (re.search('[A-Z]', password)) \
or not(re.search('[a-z]', password)) \
or not (re.search('[0-9]', password)) \
or not(re.search('[\_\@\$\!]', password)):
print("유효하지 않은 패스워드")
e... |
import turtle
t = turtle.Turtle()
t.shape("turtle")
t.color("blue")
t.fillcolor("red")
t.pensize(3)
t.speed(0)
t.right(90)
mylist = [120,56,309,156,23,98]
for i in range(len(mylist)):
t.begin_fill()
t.left(180)
t.forward(mylist[i])
t.right(90)
t.write(mylist[i])
t.forward(15)
t.right(90)... |
list1 = [3,5,7]
list2 = [2,3,4,5,6]
for i in range(len(list1)):
for j in range(len(list2)):
print(list1[i],"x",list2[j], "=", list1[i]*list2[j])
|
import random
n1 = random.randint(0,9)
n2 = random.randint(0,9)
n3 = random.randint(0,9)
n = [n1,n2,n3]
x,y,z = map(int,input("세 복권번호를 입력하시오: ").split())
print("복권번호:",n1,n2,n3)
if (x in n) and (y in n) and (z in n):
print("상금 1억원")
elif (x in n and y in n) or (x in n and z in n) or (y in n and z in n):
pri... |
# -*- coding: utf-8 -*-
"""
Created on Fri Nov 23 11:56:50 2018
@author: gy15js
"""
'''NEED TO COMMENT OUT THIS SECTION OF CODE'''
#changing the values given what the levels of food are
#use an if command so if store is lower than '' eat
#https://dadaromeo.github.io/posts/mesa-a-library-for-agent-based-mo... |
# - hash function + array = hash table
# -array full of linked lists
# index Chain
# 0 None
# 1 None
# 2 None
# 3 None
# 4 None
# 5 None
# put('foo', 12) # hash to 1
# put('baz', 13) # hash to 3
# put('bar', 23) # hash to 1
# get('bar')
# How do we do a g... |
#%%
n = int(input("principle quantum number? "))
if n>=0:
E = (n+1/2)
E = str(E)
print(E+"h")
else:
print("input a posivite value u dumbell")
|
import numpy as np
arr1 = np.arange(10)
print(arr1.shape)
# 수직축 추가
arr2 = arr1[:, np.newaxis]
print(arr2.shape)
# 수평축 추가
arr3 = arr1[np.newaxis, :]
print(arr3.shape)
print(arr3) |
command = input("Enter a command > ")
while command:
print(f"You entered command: {command}")
command = input("Enter a command > ")
|
0;136;0c"""
File: proj1.py
Author: Rooklyn Kline
Date: 10/25/19
Section: 15
E-mail: rkline2@umbc.edu
Description:
This program is a baking sim where each player has to
bake baguettes, macarons, and croissants. They must go to
the grocery store to purchase ingredients. If they don't have enough
ingredients or they ... |
a = 1
while a == 1:
num = int(input("\nDigite um numero: "))
if num < 0:
print("NEGATIVO")
else:
print("POSITIVO")
|
#Faça um programa que calcule o volume de um cilindro area = raio * raio * 3.14 volume = area * altura
raio = float(input("Digite o raio: "))
altura = float(input("Digite a altura: "))
area = raio * raio * 3.14
volume = area * altura
print("O volume do seu cilindro é de: {}m³".format(volume)) |
# -*- coding: utf-8 -*-
"""68"""
import pymongo
def main():
client = pymongo.MongoClient()
db = client.monDB
col = db.artist_data
artists = col.find({u'tags.value':"dance"}).sort('rating.count',pymongo.DESCENDING).limit(10)
for i,artist in enumerate(artists, start=1):
print '{}\t{}\t{}'.f... |
# 05
# -*- coding: utf-8 -*-
#terminal入力
#s = raw_input('Please input string > ')
#n = input('Please input n > ')
s = 'I am an NLPer'
n = 2
def w_n_gram(s,n):
w_list = s.split( )
w_gram = []
for i in range(len(w_list)):
w_gram.append(w_list[i:i+n])
return w_gram
def c_n_gram(s,n):
c_gram = []
for i in rang... |
str1="yogeeeshijaa"
print(str1.count("e"))
print(str1.count("a"))
print(str1.count("i"))
print(str1.count("o"))
print(str1.count("u")) |
base,height=input("Enter base,height : ").split(",")
base,height=int(base),int(height)
print(0.5*base*height) |
"""
import re
compile : understand the pattern
search : finding something into a slelected string
findall : find all matching values
"""
import re
ob= re.compile(r'\d\d-\d"{10}')
result=ob.search(" hello 91-9166371779")
#print(result.group())
link="adhdf,fflgcgjlgjcfg;fkgmc,www.google.com,fjdslgdrgjrdlog... |
num=int(input("Enter the number :"))
fact =1
while num:
fact*=num
num=num-1
print(fact) |
from math import atan, inf, degrees, sqrt, acos, pi
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
class Vector2D:
def __init__(self, x, y):
self.x = x
self.y = y
def mag(self):
return sqrt(dot(self, self))
def dir(self):
return Vecto... |
'''
Problem 1
If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.
'''
def sum_of_div_by_3_and_5(limit=1000):
return sum(x for x in range(limit) if div_by_3_and_5(x))
def div_by_... |
#author: vysakh
# for using creation of complex objects
# Have 4 parts
#1. Director
#2. Abstract Class
#3. Concrete Class
#4. Product
class Director():
"""Director Class"""
def __init__(self, builder):
self._builder = builder
def create_car(self):
self._builder.create_new_car()
self._builder.add_model()
... |
'''
author: SryMkr
date: 2021.10.12
The library consists of some basic functions to
support Snake Game
'''
# import packages
import pygame
import random
import numpy as np
from Snake_food_library import MySprite_food
# 26 alphabet
ALPHABET_LIST = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', '... |
# -*- coding: utf-8 -*-
import unittest
import main
class MyTest(unittest.TestCase):#继承unittest.TestCase
def setUp(self):
print("正在建立初始化连接......")
print("")
def tearDown(self):
print("")
print(u"该条用例执行完毕,启动退出程序")
#球员升级
def test_PlayerUpgrade(self):
try:
... |
## String Pattern Matching ##
# Time: O(mn) worst case; O(m+n) avg case
# Space: O(1)
def match(text, pattern):
for i in range(0, len(text)-len(pattern)):
j = 0
while j < len(pattern) and text[i+j]==pattern[j]:
j += 1
if j == len(pattern):
return i
return -1
p... |
class Solution:
def shortestDistance(self, words: List[str], word1: str, word2: str) -> int:
word1_instances = []
word2_instances = []
for i in range(0, len(words)):
if words[i] == word1:
word1_instances.append(i)
if words[i] == word2:
... |
import time
import datetime
def agent(LinkedList):
'''
Agent function that traverses a linked list and sets the status
of all nodes with TTL <= 0 to inactive
'''
while True:
time.sleep(2)
if LinkedList.startNode is None:
return
else:
n = LinkedList.st... |
"""
1. Initialize the cells in the grid.
2. At each time step in the simulation, for each
cell (i, j) in the grid, do the following:
a. Update the value of cell (i, j) based on
its neighbors, taking into account the
boundary conditions.
b. Update the display of grid values.
extras-toroidal boundary conditi... |
'''
Grouping the data based on the Columns and performing Aggregate Functions over it.
Aggregate Functions like sum,avg,min,max,count,mean etc
'''
from pyspark.sql import SparkSession
from pyspark.sql.functions import sum, avg, max, min, mean, count, col
if __name__ == "__main__":
spark = SparkSession.builder \
... |
def new_alph(ch):
ch = ch.lower()
alph = 'abcdefghijklmnopqrstuvwxyz'
new_alph = alph[alph.index(ch):] + alph[:alph.index(ch)]
return new_alph
def encrypt(text, big_key):
res = ''
alph = 'abcdefghijklmnopqrstuvwxyz'
i = 1
for char in big_key:
new = new_alph(char)
for t in... |
def areAscendingNumbers(txt, numdigits):
first = int(txt[0:numdigits])
for i in range(1, len(txt)//numdigits):
if int(txt[i*numdigits:(i+1)*numdigits]) != (first + i):
return False
return True
def ascending(txt):
if len(txt) <= 1:
return False
for numdigits in range(1, len(txt)//2 + 1):
if len(txt) % nu... |
def drawboard(ashish):
ashish = int(ashish)
i = 0
ho = "--- "
ve = "| "
ho = ho * ashish
ve = ve * (ashish+1)
while i < ashish+1:
print(ho)
if not (i == ashish):
print(ve)
i += 1
|
def jumping_frog(n, stones):
jumps = {0: 1}
queue = [0]
while len(queue) > 0:
cur = queue.pop(0)
jump = stones[cur]
if cur + jump >= n:
return jumps[cur] + 1
if cur + jump == n - 1:
return jumps[cur] + 2
if cur + jump not in jumps:
... |
def digits(number):
if number == 1:
return 0
a = 0
myans = 0
while number > 1:
if number <= 9*10**a:
myans += (a+1)*(number-1)
number -= number*10**a
else:
myans += (a+1)*9*10**a
number -= 9*10**a
a += 1
return myans
|
# Uses python3
import sys
def get_change(money):
coin_number = 0
while money > 0:
if money >= 10:
money = money - 10
print('in 10', coin_number)
elif money >= 5:
money = money - 5
print('in 5', coin_number)
else:
money = money... |
words = []
result = []
import itertools
from itertools import chain
with open("e8.txt") as file:
for line in file:
#lines.append(line.split())
#words = list(itertools.chain.from_iterable(lines))
words = line.strip().split()
for element in words:
if element not in resu... |
xh = float(input ("Enter Hours: "))
xr = float(input ("Enter Rate: "))
if xh > 40:
bonus_hr = xh - 40.0
bonus = bonus_hr * xr * 0.5
xp = xh * xr + bonus
else :
xp = xh * xr
print("Pay : " , xp)
|
"""
Irj programot, mely beker egy egesz szamot: n. Feltetelezhetjuk, hogy ez pozitiv.
Ezt kovetoen kerjen be egesz szamokat addig, amig n db nemnegativ szamot nem kapott.
A program a futasa vegen irja ki egy listaban ezeket a szamokat.
Pelda bemenet:
3
1
2
3
Pelda kimenet:
[1, 2, 3]
Pelda bemenet:
3
-1
0
-44
35
-1... |
"""
Problem 1
Floating Point Operations Per Second
"""
from time import time
from numpy.random import random
def flops(seconds):
"""calculates the number of operations performed in some length of time:
returns a tuple (
time_counting_operations,
number_of_operations,
operations_per_... |
"""
Newman 9.7
The Relaxation Method for Ordinary Differential Equations
"""
import numpy as np
import matplotlib.pyplot as plt
# Constant Declaration
m = 1 # kg
g = 9.81 # m/s^2
tstart = 0 # seconds
tstop = 10 # seconds
N = 100 # number of points
eps = 1.e-6 # desired accuracy... |
import numpy as np
import matplotlib.pyplot as plt
def mandelbrot(divs, number):
# initialize array of complex numbers
complex_numbers = np.empty((divs, divs), dtype = np.complex128)
temp = np.linspace(-number, number, divs).astype(np.complex128)
# adding real numbers to array
for i in range(div... |
"""
Problem #4
Orthog Modification #3
"""
import numpy as np
from numpy.linalg import norm
def orthog():
"""finds a vector that is:
- Orthogonal to a
- Same magnitude as b
- In plane made by a & b
"""
global cross
global a
global b
global dot_product
# user input... |
# Uses python3
from math import sqrt
def fib_naive(n):
if (n <= 1):
return n
return fib_naive(n - 1) + fib_naive(n - 2)
def fib_fast(n):
if n <= 1:
return n
previous = 0
current = 1
for _ in range(n - 1):
previous, current = current, previous + current
return ... |
from random import randint
from timeit import timeit
from week1_programming_challenges.max_pairwise_product \
import max_pairwise_product as fast_implementation
def slow_implementation(num_array):
product = num_array[0] * num_array[1]
for i in range(len(num_array)):
for j in range(i + 1, len(num... |
def f():
yield 1
return "hello"
print(next(f()))
f = f()
try:
print(next(f))
print(next(f))
print(next(f))
print(next(f))
except StopIteration as e:
print(e)
|
"""
生成器
"""
# 生成一个列表
L = [x for x in range(10)]
# 打印一下列表的内容和数据
print(L, type(L))
# 生成生成器
G = (x for x in range(10))
# 打印生成器内容
print(G, type(G))
# 需要用next方法获取
print(G.__next__())
print(next(G))
# for 循环获取
for x in G:
print(x)
# 使用yield得到函数生成器,内部储存斐波拉契数列
def red(num):
a = 0
b = 1
# 计数参数默认值为0
index =... |
# coding=utf-8
# 进阶Python
# 高阶函数
import math
def add(x, y, f):
return f(x) + f(y)
print(add(25, 9, math.sqrt))
# map()函数应用,capitalize()首字母大写的函数
def format_name(s):
return s.capitalize()
print(list(map(format_name, ['adam', 'LISA', 'barT'])))
# 用reduce()函数求积
from functools import reduce
def prod(x, y... |
# 返回函数值mul()
def count():
L = []
for i in range(1, 4):
def mul():
return i * i
L.append(mul())
return L
a, b, c = count()
print(count())
print(a, b, c)
# 返回函数mul,调用的函数并没有进行计算
def count():
L = []
for i in range(1, 4):
def mul():
return i * i
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import zipfile, os
def backupTozip(folder):
# 保存整个“folder”的目录到ZIP文件
folder = os.path.abspath(folder)
number = 1
while True:
zipFilename = os.path.basename(folder) + '_' + str(number) + '.zip'
if not os.path.exists(zipFilename):
... |
import math, random
import numpy as np
P = 1
def activation(value):
#Map the output to a curve between 0 and 1
#output = 1/(1+e^(-a/p))
try:
return 1/(1+math.exp(-value/P))
except OverflowError:
return 1/(1+math.exp(700/P))
class Neuron(object):
def reset(self):
return
... |
import numpy as np
from matplotlib import pyplot as plt
'Esta funcion calcula el RMS de una señal'
def RMS(xn):
n=len(xn)
rms=np.sqrt((1/n)*sum(np.square(abs(xn))))
return(rms)
|
#!/usr/bin/env python
def is_odd(n):
return n % 2 ==1
print filter(is_odd,[1, 2, 3, 4, 5, 6, 9, 10, 15])
|
#!/usr/bin/env python
L = range(1,101)
L = range(1,101)
def is_s(n):
if n ==1:
return False
if n==2:
return True
else:
for i in range(2,n):
if n%i==0:
return False
return True
print filter(is_s,L)
|
import random
import time
def insertionsort(mylist):
n=len(mylist)
for i in range(1,n):
key=mylist[i]
j=i-1
while mylist[j]>key and j>-1:
mylist[j+1]=mylist[j]
j=j-1
mylist[j+1]=key
def bubblesort(mylist):
n=len(myli... |
'''
The classification module allows users to evaluate and visualize classifiers
'''
import logging
import os
import numpy as np
import sklearn.metrics as metrics
import matplotlib.pyplot as plt
_logger = logging.getLogger()
def evaluate_model(fitted_model, X_test: np.array, y_test: np.array, show_roc: bool = Fal... |
# -*- coding: utf-8 -*-
"""
Created on Thu Nov 23 15:54:58 2017
@author: Edu
Description:
Bamboo is a Pandas DataFrame wrapper used for RedPandas. In adition of having
the raw DataFrame, it also stores aditionally information.
A Bamboo object contains:
A pandas DataFrame "dataFrame" which represents the dat... |
"""
URL: https://leetcode.com/problems/regular-expression-matching/
Description:
Given an input string (s) and a pattern (p), implement regular expression matching with support for '.' and '*'.
'.' Matches any single character.
'*' Matches zero or more of the preceding element.
The matching should cover the entire in... |
import inputs
import turtle as t
t.setup(700,700)
t.shape("turtle")
t.color("red")
while True:
events = inputs.get_gamepad()
for event in events:
if event.code == 'BTN_SOUTH' and event.state == 1:
print('Equis!')
t.forward(50)
if event.code == 'BTN_NORTH' and... |
for a in range(1,1000):
for b in range(1,1000):
for c in range(1,1000):
if (a**2)+(b**2) == (c**2):
if a+b+c == 1000:
print(a*b*c) |
import random
import tkinter
from PIL import ImageTk, Image
import time
from simpleimage import SimpleImage
DEFAULT_FILE = 'images/fam.jpg'
CANVAS_WIDTH = 700
CANVAS_HEIGHT = 600
def main():
keep_going = True
filename = get_file()
image = SimpleImage(filename)
canvas = make_canvas(CANVAS_WIDTH, CANV... |
# -*- coding: utf-8 -*-
"""
Created on Mon Jul 13 11:36:38 2020
@author: Harry
"""
import heapq
import numpy as np
import random as rr
import IPython
class Node:
def __init__(self, parent=None, pos=None):
self.parent = parent
self.pos = pos
self.f = 0
self.manhattan... |
#imports
import json
#dictionaries
rules = {}
first = {}
follow = {}
def get_rules_line(operator, line):
if '|' in line:
for part in line.split('|'):
get_rules_line(operator, part)
else:
rules[operator].append(line)
def get_first(operator, rule):
if rule[0].islower() or rule[0] == '0':
... |
#comments in python
#print("start print- first Hellooo")
#i=input("enter you name")
#print("your name" +i)
#readData = input("enter name2"); print(readData)
#datatypes in python
#Numer, string, list, tuples, dictionary
#working on variables
#i=10
#print(i)
#i="name"
#print(i)
# exercise 1
#name = input("Enter Name")... |
str1 =" testing world "
#print(str1[6])
#print(str1[1:5])
#print(len(str1))
#print(str1.upper())
#print(str1.lower())
#print(str1.capitalize())
#print(len(str1.strip()))
#print(str1.replace("t","s"))
"""
count=0
for i in str1:
if(i =='t'):
count +=1
print(count)
"""
print(reversed(str1)) |
import numpy
puzzle = [
[0,0,0,0,1,0,0,7,0],
[0,0,4,0,6,5,0,9,0],
[8,0,6,0,0,0,0,0,0],
[2,0,7,0,9,3,1,0,0],
[0,9,0,8,0,1,0,4,0],
[0,0,3,7,5,0,9,0,2],
[0,0,0,0,0,0,8,0,7],
[0,7,0,6,4,0,5,0,0],
[0,3,0,0,8,0,0,0,0]
]
def checkcell(x,y,test_num):
global puzzle
# find which cel... |
import pandas as pd
from pyTruthTable import * #Import all methods from pyTruthTable
# intialise firs columns.
df = pd.DataFrame({'A':[True, True, False, False],
'B':[True, False, True, False]})
# Create other collumns of the dataframe calling methods
df = df.join(l_implies(df, 0 ,1)) # Thrid col... |
from common.util import *
from typing import List
# --- Day 6: Custom Customs ---
# As your flight approaches the regional airport where you'll switch to a much larger plane,
# customs declaration forms are distributed to the passengers.
# The form asks a series of 26 yes-or-no questions marked a through z.
# All you... |
print(1 + 1)
print(3 - 2)
print(5 * 2)
print(6 / 3)
print("-" * 15)
print(2 ** 3) # 2^3 = 8
print(5 % 3)
print(5 // 3) # 1
print(10 // 3) # 3
print("-" * 15)
print(10 > 3) # True
print(4 >= 7)
print(3 == 3)
print(3 != 5)
print(3 + 4 == 7)
print("-" * 15)
print(not (1 != 3))
print((3 > 0) and (3 < 5))
print((3 > ... |
# 표준 체중 구하기
# def std_weight(height, gender):
# if gender == "man":
# weight = round(float(height * height * 22/10000), 2)
# elif gender == "woman":
# weight = round(float(height * height * 21/10000), 2)
# result = "키 {0}cm {1}의 표준 체중은 {2}kg 입니다.".format(height, gender, weight)
# return... |
import numpy as np
import collections
def khatrirao(matrices, skip_matrix=None, reverse=False):
"""Khatri-Rao product of a list of matrices
This can be seen as a column-wise kronecker product.
(see [1]_ for more details).
Parameters
----------
:param matrices: ndarray list
li... |
import sqlite3
conn = sqlite3.connect('rpg_db.sqlite3')
cur = conn.cursor()
# How many total Characters are there?
result_1 = cur.execute("SELECT COUNT(*) FROM charactercreator_character;").fetchall()[0][0]
print(f" How many total Characters are there? Answer: {result_1}")
# How many of each specific subclass?
resul... |
#!/usr/bin/env python
""" IN COLLABORATION WITH AKHIL DATLA """
import arcade as game
import sys
import time
import math
import random
"""AKHIL'S CODE: SHAPE LOGIC"""
# dist returns the distance between two points
def dist(x1, y1, x2, y2):
d = math.sqrt((x2 - x1)**2 + (y2 - y1)**2)
return d
# slope retur... |
import math
a = float(input('Längd katet 1: ').replace(',', '.'))
b = float(input('Längd katet 2: ').replace(',', '.'))
c = math.sqrt(a**2 + b**2)
print(f'Hypotenusan är {c}')
|
import os
INSTRUCTIONS = '''Welcome to 'Who wants to be a millionaire'!
This came consists of 15 questions, that gets progressively harder, but also
comes with greater rewards.
As long as you answer correctly you earn more money, but if you answer wrong,
you lose what you have earned.
After questions 5 and 10 you ... |
import math
def mean(array):
return sum(array) / len(array)
def variance(array):
m = mean(array)
diffs = [(n - m) ** 2 for n in array]
return mean(diffs)
def stddev(array):
return math.sqrt(variance(array))
|
from typing import Union, Literal
class A:
...
# value undefined
a = c # E Cannot determine type of 'c'(unresolved reference 'c')
# any
a = 1
a = "s" # ok
b: int = "hjzs" # E Incompatible type in assignment(expression has type 'Literal['hjzs']', variable has type 'int')
b = a # E Incompatible type in assi... |
import hashlib
import os
def hashFile(path):
"""Hashes a file and returns the hashvalue"""
m = hashlib.md5()
try:
file = open(path, "r")
for chunk in iter(lambda: file.read(4096), b""):
m.update(chunk)
return m.hexdigest()
except Exception as e:
print e
... |
class HistoryManager():
def __init__(self, maxSize=100):
""" Initialize HistoryManager which saved maximal maxSize states.
The maxSize+1 insertion removes the first
"""
self.history = []
# Position is a value contains the index of the state in a continues way.
# T... |
def countingValleys(steps: int, path: str) -> int:
"""
:param steps: the number of steps on the hike
:param path: a string describing the path
:return: the number of valleys traversed
"""
level, valleys = 0, 0
for i in range(steps):
if path[i] == 'U':
level += 1
... |
from bisect import bisect_left, insort_left
from typing import List
def median(arr: List[int], days: int) -> int:
"""
:return: median of arr
"""
return arr[days // 2] if days % 2 else ((arr[days // 2] + arr[days // 2 - 1]) / 2)
def activityNotifications(expenditure: List[int], d: int) -> int:
""... |
from typing import List
def maximumToys(prices: List[int], k: int) -> int:
"""
:param prices: the toy prices
:param k: Mark's budget
:return: the maximum number of toys
"""
maximum_toys = 0
prices.sort()
for maximum_toys in range(len(prices)):
if k > prices[maximum_toys]:
... |
from Calculator.Calculator import addition
from Calculator.Calculator import division
import getSamp
#Pulled From Example Files
def sample_mean(data, sample_size):
if(sample_size>0) and (sample_size <= data.len()):
total = 0
# check that get sample returns the proper number of samples
# che... |
'''
Created on Nov 27, 2016
@author: Marlon_2
'''
name = input("What is your name? ")
if name == "Alice":
print ("Good morning", name + "!")
elif name == "Bob":
print ("Good morning", name + "!")
else:
print ("Who are you?", "I don't know", name + ".")
|
import sys
input = sys.stdin.readline
def union(a, b):
a = find(a)
b = find(b)
if a > b:
arr[a] = b
else:
arr[b] = a
return
def find(num):
if arr[num] == num:
return num
num = find(arr[num])
return num
n, m = map(int, input().split())
arr = [i for i in range(... |
"""
Name: Celeste Sila
Date: April 27, 2021
Module: 9.3
Description: Update and delete records from pysports database.
GitHub Repository: https://github.com/celestesila/csd-310
"""
import mysql.connector
#from mysql.connector import errorcode
config = {
"user": "pysports_use... |
# Update the appointments
from tkinter import *
import tkinter.messagebox
import sqlite3
#Connect to database
conn = sqlite3.connect('database.db')
#Cursor to move around the database
c = conn.cursor()
class Application1:
def __init__(self, master):
self.master = master
#Creating ... |
'''
Define a Python function descending(l) that returns True if each element in its input list is at most as big as the one before it. For instance:
>>> descending([])
True
>>> descending([4,4,3])
True
>>> descending([19,17,18,7])
False
'''
#Program
def descending(l):
x=0
if len(l)<=1... |
'''
A list rotation consists of taking the first element and moving it to the end. For instance, if we rotate the list [1,2,3,4,5], we get [2,3,4,5,1]. If we rotate it again, we get [3,4,5,1,2].
Write a Python function rotatelist(l,k) that takes a list l and a positive integer k and returns the list l after k rotation... |
#simple solution
def isAnagram1(str1,str2):
str1 = str1.replace(' ','').lower()
str2 = str2.replace(' ','').lower()
return sorted(str1) == sorted(str2)
# solution interviewer looking for by appying the logic
def isAnagram2(str1,str2):
str1 = str1.replace(' ','').lower()
str2 = str2.replace(' ','... |
"""
Simple crypto voting based on paillier crypto system
based on http://security.hsr.ch/msevote/seminar-papers/HS09_Homomorphic_Tallying_with_Paillier.pdf
Implemented by Nur (nur858@gmail.com)
For purely educational purpose.
"""
import paillier
def cast_vote(choice,pk, tally):
c = paillier.encrypt(pk, choice)
... |
# -*- coding: utf-8 -*-
"""
Created on Sat Sep 5 12:25:59 2020
@author: Hillina Mesfin
#This program prompts the user to enter their first and last name
#At the end the code will print out a greeting
"""
first_name = input ("What is your first name? ")
last_name = input ("What is your last name? ")
prin... |
class Bottles:
def song(self):
return self.verses(99,0)
def verses(self, last, first):
o = self.verse(last)
for i in range (last-1, first-1, -1):
o += "\n" + self.verse (i)
return o
def verse(self, number = None):
bottle_number = self.bottleNumberFactor... |
def encipher():
print('Enter your text to be ciphered:')
message = list(input())
print('Enter your shift')
c = int(input())
cipher=[]
for x in range(message.__len__()):
if ord(message[x]) == 0:
cipher.append(" ")
elif ord(message[x]) in range(65,90):
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.