text stringlengths 37 1.41M |
|---|
'''
Reference: https://www.quora.com/Given-n-how-many-structurally-unique-BSTs-binary-search-trees-that-store-values-1-to-n-are-there
'''
import math
def bsts(n):
if n == 0:
return 1
dp = [0 for _ in range(n+1)]
dp[0], dp[1] = 1, 1
for i in range(2,n+1):
for j in range(1,i+1):
... |
#import pdb
def find(arr):
''' Find all triples (x, y, z) that meet the form x + y = z. '''
sort_arr = sorted(arr)
result = []
#pdb.set_trace()
# For each element in an array we find the corresponding x and y by two pointers.
for i, ele in enumerate(sort_arr):
p1 = 0
p2 = len(arr... |
#http://introtopython.org/classes.html
class Rocket():
def __init__(self):
#The First thing you have to do is to define the __init__() method
#The __init__ () method sets the values for any parameters that need to be defined when an object is first created.
self.x = 0
self.y = 0
def mo... |
#Text + Variable
x = "awesome"
print("Python is " + x)
#Variable + Variable
x = "Python is "
y = "awesome"
z = x + y
print(z)
#Number + Number = Sum
x = 5
y = 10
print(x + y) #output = 15
#Integer + String = Impossible / Integer + Text(keine Variable) = Impossible
x = 5
y = "John"
print(x + y)
#ERROR
|
import sqlite3
def insertUser(email, password):
conn = sqlite3.connect('signup.db')
cur = conn.cursor()
if isTaken(email, cur):
return False
else:
cur.execute("INSERT INTO user (email,password) VALUES (?,?)",(email, password) )
cur.execute("INSERT INTO preferences (user_e... |
import numpy as np
def frange(start, end=None, inc=None):
"""A range function, that does accept float increments..."""
import math
if end == None:
end = start + 0.0
start = 0.0
else: start += 0.0 # force it to be a float
if inc == None:
inc = 1.0
count = int(math.ceil(... |
#!/usr/bin/python3
# -*- coding:utf-8 -*-
# @Time : 2019/5/11 9:06
# @Author : robert
# @FileName : calculator.py
# @Software : PyCharm
import re
class Calculator(object):
def add(self,arg_a,arg_b):
return arg_a + arg_b
def sub(self,arg_a,arg_b):
return arg_a - arg_b
def d... |
# '''
# for i in range(1,10):
# for j in range(10):
# for k in range(10):
# sum1 = 100 * i + 10 * j + k
# sum2 = i * i * i + j * j * j + k * k * k
# if sum1 == sum2:
# print(sum1)
# '''
# '''
# print('red\tyellow\tblue')
# for red in range(0, 10):
# f... |
# coding=utf-8
class Node(object):
"""节点类"""
def __init__(self, val=-1, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Tree(object):
"""树类"""
def __init__(self):
self.root = Node()
def add(self, val):
"""为树添加节点"""
... |
import urllib
import urllib2
import BeautifulSoup
import re
name=str(raw_input('enter your codeforces Id !!'))
mainURL="http://www.codeforces.com/contests/with/" + name
print mainURL
response = urllib2.urlopen(mainURL)
soup = BeautifulSoup.BeautifulSoup(str(response.read()))
tab = 1
for grab in soup.findAll('a', ... |
'''
this program will create in the current directory a simple XML file and then immediately read it, giving us some information.
'''
#creating xml file to system from python
import xml.etree.ElementTree as et
menu_str = '''
<?xml version="1.0"?>
<menu>
<breakfast hours="7-11">
<item price="$6.00">burritos</... |
# week 1 homework
# Stanley Lim
# Data Mining
# Everything should work correctly
tuple1 = (1, 2, 3, 4, 5)
list1 = [6,7,8,9,10]
print ("tuple1: ", tuple1)
print ("list1: ", list1)
print("adding tuple[0] to list1[4]")
list1[4] = list1[4] + tuple1[0]
print ("new list1: ", list1)
# convert tuple to list in order to a... |
#class 1
class Person:
#init constructor used
def __init__(self,name,email):
self.name = name
self.email = email
def display(self):
print("Name: ", self.name)
print("Email: ", self.email)
#class 2(inherited)
class Student(Person):
StudentCount = 0
def __init__(self... |
import numpy as np
"""
使用take函数获取索引的值
通过索引访问矩阵的值,类似数组访问,不过区别是:
如果只提供行的索引,会返回整行
如果想要获得列可以先转置,然后提供行的索引
"""
a = np.arange(0, 20).reshape((4, 5))
# 只提供行
print(a)
print(a[3])
print(a[1, 4])
print(a.T[1])
# 通过索引访问矩阵的值
# x为行数,索引/列数
# y为列数,索引%列数
# 或者使用take(矩阵,索引)函数访问
print(a)
x = int(np.argmax(a) / 5)
y = np.argmax(a) % 5
... |
#!/usr/bin/env python
"""
@author: metalcorebear
"""
# Determine word affect based on the NRC emotional lexicon
# Library is built on TextBlob
from textblob import TextBlob
from collections import Counter
from nltk.stem.snowball import SnowballStemmer
stemmer = SnowballStemmer("english")
def build_word_... |
#!/usr/local/bin/python3.6
print('Python算术运算符')
print('+ 加 - 两个对象相加')
print('- 减 - 得到负数或是一个数减去另一个数')
print('* 乘 - 两个数相乘或是返回一个被重复若干次的字符串')
print('/ 除 - x 除以 y')
print('% 取模 - 返回除法的余数')
print('** 幂 - 返回x的y次幂')
print('// 取整除 - 返回商的整数部分')
print('')
a = 21
b = 10
c = 0
c = a + b
print('a + b c = ', c)
c = a - b
print('a... |
import math
def my_sqrt(a):
epsilon = 0.0000001
x = a
while True:
y = (x + a/x)/2.0
if abs(y - x) < epsilon:
break
x = y
return y
def test_sqrt():
a = 1
while a<26:
diff = my_sqrt(a) - math.sqrt(a)
print('a=', a, '|my_sqrt(a=)', my_sqrt(a), '|m... |
def isPalindrome(n):
num = n
reversed_digit = 0
while (num>0):
digit = num%10
reversed_digit=reversed_digit*10 + digit
num = num//10
print (n, reversed_digit)
if reversed_digit == n:
return True
else:
return False
def main():
print (isPalindrome(12... |
from collections import Counter
from collections import defaultdict
def main():
s = "hello"
d = defaultdict(int)
for char in s:
d[char] += 1
print (d)
if __name__ == "__main__":
main() |
from DataStructures.DoublyLinkedList import DoublyLinkedList
def mth_to_last(n, ll):
if ll.head == None:
raise ValueError("Empty LinkedList")
else:
count = 0
curr = ll.head
trail = None
while (curr):
#print (count,n)
if count == n:
... |
#ESC180 Lab 1
# Connected Cows
# DO NOT modify any function or argument names
import math
def find_euclidean_distance(x1, y1, x2, y2):
'''
(float)->float
find_euclidean_distance calculates the euclidean distance between
two given 2D points P(x1,y1) and Q(x2,y2), and returs its Euclidean_distance
''... |
from abc import ABCMeta, abstractmethod
import random
class GhostStrategy(object):
__metaclass__ = ABCMeta
@abstractmethod
def get_move(self, winners, losers):
"""Returns the next letter to be played using the
current strategy.
Args:
winners: dict whose keys are letter... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# 如果给定一个list或tuple,我们可以通过for循环来遍历这个list或tuple,这种遍历我们称为迭代(Iteration)。
# 因为dict的存储不是按照list的方式顺序排列,所以,迭代出的结果顺序很可能不一样。
# 遍历字典
d = {'a': 1, 'b': 2, 'c': 3}
for key in d:
print(key)
# 默认情况下,dict迭代的是key。如果要迭代value,可以用for value in d.values(),如果要同时迭代key和value,可以用for k, v in ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
List = ['Michael', 'Sarah', 'Tracy', 'Bob', 'Jack']
print('集合的长度 %s ' % len(List))
print('获取集合的第一个元素 %s ' % List[0])
print('获取集合的最后一个元素 %s ' % List[-1])
print('向集合中添加元素:%s ' % List.append('Marry'))
print('获取集合元素 %s ' % List)
List2 = ['Michael', 'Sarah', ['Tracy', 'Tom']... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# 判断对象类型,使用type()函数
sf = type(123)
print(sf)
# 判断基本数据类型可以直接写int,str等,但如果要判断一个对象是否是函数怎么办?可以使用types模块中定义的常量:
import types
def fun():
pass
if type(fun) == types.FunctionType:
print('fn 是函数!')
# 使用isinstance()
# 对于class的继承关系来说,使用type()就很不方便。我们要判断class的类型,可以使用is... |
if __name__ == "__main__":
num_array = list()
num = input("Enter how many elements you want:")
print ('Enter numbers in array: ')
for i in range(int(num)):
n = input("num :")
num_array.append(int(n))
print ('Array: ',num_array)
for i in range(1,int(num)):
d=i
while (d > 0 and num_array[d] < num_array[d... |
# Create a Python list to store your grocery list
grocery_list = ['milk', 'bacon', 'eggs', 'steak', 'peanut butter', 'jelly']
# Print the grocery list
print(grocery_list)
# Change "Peanut Butter" to "Almond Butter" and print out the updated list
grocery_list[4] = 'Almond Butter'
print(grocery_list)
# Remove "Jelly" fro... |
def part1():
valid_passwords = 0
with open('inputs/day2.txt') as f:
for line in f:
line = line.strip('\n')
lowerRange = int(line.split('-')[0])
upperRange = int(line.split('-')[1].split(' ')[0])
letter = line.split('-')[1].split(' ')[1].strip(':')
word = line.split('-')[1].split(' '... |
def check_validity(passport):
"""
check_validity checks is a passport is valid or not, returning True if it is and False if not
:param passport: the string representation of a passport
"""
data = {}
valid = True
if "byr:" not in passport \
or "iyr:" not in passport \
or "eyr:" not in passport \
or "hgt:" not ... |
class product:
def __init__(self,price,id1,quantity):
self.price=price
self.id1=id1
self.quantity=quantity
class inventory:
item={}
quant={}
def __init__(self):
self.item={}
self.quant={}
def add(self,product):
if product.id1 in self.item.keys():
self.quant[product.... |
# Printing
print("Hello World")
print("Day 1 - Python Print Function")
print("The function is declared like this:")
print("print('what to print')")
# String manipulation
print("Hello World!\nNew Line, baybyyyy")
print("Hello" + " Elias")
# Input
# name = input("What is your name? ")
# print(name)
# length = len(name... |
import math
def greet(name):
print(f"hey {name}")
print(f"hi {name}")
print(f"hello {name}")
greet('Eli')
def greet_with(name, location):
print(f"Greetings {name} from {location}!")
greet_with('Elias','Jupiter')
greet_with(name='Jupiter', location='Elias')
# paint can exercise
def paint_calc(height... |
import email.Utils
def tokensplit(s, splitchars=None, quotes='"\''):
"""Split a string into tokens at every occcurence of splitchars.
splitchars within quotes are disregarded.
"""
if splitchars is None:
import string
splitchars = string.whitespace
inquote = None
l = []; token ... |
import random
class CodeGenerator:
def __init__(self):
# Using ASCII characters as the code for encryption
self.__FIRST_ASCII = 33
self.__LAST_ASCII = 126
# Create empty dictionary to hold the encryption codes
self.__encryption_codes = {}
def generate_code(self):
... |
get_even_list = [1, 2, 5, -10, 9, 6]
even_list =[get_even_list for get_even_list in get_even_list if get_even_list % 2 ==0]
if set(even_list) == set([2, -10, 6]):
print("Your function is correct")
else:
print("Ooops, bugs detected")
|
def numerical_diff(f, x):
h = 1e-4 #0.0001
return (f(x+h) - f(x-h)) / (2*h)
def function_1(x):
return 0.01*x**2 + 0.1*x
import numpy as np
import matplotlib.pylab as plt
x = np.arange(0.0, 20.0, 0.1)
y = function_1(x)
plt.xlabel("x")
plt.ylabel("f(x)")
plt.plot(x, y)
plt.show()
def fu... |
import numpy as np
import matplotlib.pyplot as plt
# define helper functions
def sigmoid(x):
return 1 / (1 + np.exp(-x))
def score(x, y, w):
return y * (x @ w)
def compute_loss(x, y, w):
log_loss = - sum(np.log(sigmoid(score(x, y, w)))) / len(y)
return log_loss
def compute_gradients(x, y, w):
... |
'''
Време + 15 минути
Да се напише програма, която чете час и минути от 24-часово денонощие, въведени от потребителя и изчислява колко ще е часът след 15 минути.
Резултатът да се отпечата във формат часове:минути. Часовете винаги са между 0 и 23, а минутите винаги са между 0 и 59.
Часовете се изписват с една или две ... |
'''
Пари, нужни за екскурзията - реално число;
Налични пари - реално число.
След това многократно се четат по два реда:
Вид действие – текст с две възможности: "spend" или "save";
Сумата, която ще спести/похарчи - реално число.
'''
holiday_cost = int(input())
current_money = int(input())
is_spending=0
days_gone=... |
height = int(input()) # in cm
width = int(input()) # in cm
length = int(input()) # in cm
volume_taken_perc = float(input())
volume = height * width * length *0.001 # in litres
volume_taken = volume * (1- volume_taken_perc/100)
print (f" количеството литри са { volume - volume_taken : .3f} ") |
#!/usr/bin/python
import time
import random
#variables
playersChoice = ''
computerChoice = ''
numOfRounds = 0
computerScore = 0
playerScore = 0
choices = ['paper', 'scissors', 'rock']
#game:
print("\nWelcome! You are playing 'rock paper scissors' with the computer!")
print("How many rounds of 'rock paper scissors' d... |
import re
import string
alphabet = string.ascii_letters
o_phrase = raw_input('Phrase to encrypt: ')
has_letter = re.search('[A-Za-z]', o_phrase)
if has_letter:
e_phrase = ''
for char in o_phrase:
if char not in alphabet:
e_phrase = e_phrase + char
... |
# pylint: enable-msg=C0103
# pylint: disable=C0103
es_verdadero=True
es_falso=False
def evaluacion(argumento):
"""Evalua el argumento y retorna true o false"""
if argumento in ("verdadero","Verdadero","VERDADERO"):
return es_verdadero
#elif algo<algo2<algo3:
pass
else:
return es... |
# TIME - O(l1 + l2)
def sortedMerge(A,B):
index = len(A)+len(B)-1
a = len(A)-1
b = len(B)-1
while a>=0 and b >=0:
if A[a] > B[b]:
A[index] = A[a]
a -= 1
else:
A[index] = B[b]
b -= 1
index -=1
while b >= 0:
A[index] = B[b]
index -= 1
b -= 1
return A
... |
# TIME - O(log(smallerNumber))
def multiply(m,n):
if m > n:
return multiplyHelper(n,m)
return multiplyHelper(m,n)
def multiplyHelper(m,n):
if m == 2:
return n+n
elif m == 1:
return n
halfProduct = multiplyHelper(m/2,n)
if m % 2:
return halfProduct+halfProduct+... |
# TIME - O(n)
# SPACE - O(1)
class Tree:
def __init__(self, data, left = None, right = None):
self.data= data
self.left = left
self.right = right
def minimalTree(arr,start,end)
if start > end:
return None
mid = (start+end)//2
tree = Tree(arr[mid])
tree.left = self.minimalTree(arr[start:mid-1], s... |
import collections
class Graph:
def __init__(self):
self.visited = {}
self.edges = collections.defaultdict(list)
self.answer = False
self.vertices = []
# TIME - O(V)
# SPACE - O(d) (maximal depth of tree)
def routeNodesDFS(self,node1, node2):
if node1 == node2:
self.answer = ... |
from typing import List
def busyStudent(startTime: List[int], endTime: List[int], queryTime: int):
count = 0
for i in range(len(startTime)):
start = startTime[i]
if (start == queryTime):
count += 1
elif (start < queryTime and endTime[i] >= queryTime ):
count += 1
return count
print(busySt... |
import random
print('wlocome to the magic eight ball! enter to start!')
q = input('what would you like to ask?')
answer = random.randint(1,4)
if answer == 1:
print('the answer is yes.')
elif answer == 2:
print('the answer is no.')
elif answer == 3:
print('cannot predict now')
else:
print('ask again late... |
a = True
b = False
if a and b:
b = 3
else:
b = True
if a and b:
a = 1
b = 2
print(a)
print(b)
|
def BinarySearch(A,key):
low = 0
high = len(A) - 1
while low <= high:
mid = (low + high) // 2
if key == A[mid]:
return True
elif key < A[mid]:
high = mid -1
else:
low = mid + 1
return False
A = [15,22,47,84,96]
found = BinarySearch(A... |
from time import time as detak
from random import shuffle as kocok
import time
def swap(A,p,q):
tmp = A[p]
A[p] = A[q]
A[q] = tmp
def cariPosisiYangTerkecil(A, dariSini, sampaiSini):
posisiYangTerkecil = dariSini
for i in range(dariSini+1, sampaiSini):
if A[i] < A[posisiYangTer... |
# Request price from user
price = input("Enter the price of a meal: ")
# Calculate tip and total
tip = float(price) * 0.16
total = float(price) + tip
# Return tip and total to user
print("A 16% tip would be", "{:.2f}".format(tip))
print("The total including tip would be", '{:.2f}'.format(total))
|
#Autor: BAQUE PILOSO JORGE LUIS
#METODO ESQUINA NOROESTE.
matriz = []
matriz2= []
filas = int(input('Ingrese el numero de filas. ')) +1
columnas = int(input('Ingrese el numero de columnas. ')) +1
for i in range(filas):
matriz.append([0]*columnas)
matriz2.append([0]*columnas)
print('Ingrese Oferta... |
"""
This module is a collection of sorting techniques
"""
class PySort():
"""
This class contains the different sorting methods supported
"""
SORTS = {
"0": "merge_sort",
"1": "bubble_sort",
"2": "selection_sort",
"3": "insertion_sort",
"4": "shell_sort",
... |
import getch
while(True):
a = getch.getch()
if(a == 'w'):
msg = 'up'
elif(a == 's'):
msg = 'down'
elif (a == 'a'):
msg = 'left'
elif(a == 'd'):
msg = 'right'
print(msg)
|
'''
ball
====
This class denotes the Bullet of the dragon enemy
Ice ball is an obstacle with the ability to move only backward (the BOSS is backward in both thinking and working)
It inherits from obstacle class.
Additional Data Members
-----------------------
- exist
This variable is 1 if the ball has already been... |
'''
obj
===
This class denotes any object, be it an obstacle or a person, that can be rasterised on the board, or can be directly printed to the screen
This is a base class, from which obstacle and person are inherited
Data Members
-------------
- x
denotes the starting x coordinate of the object
Note that x axis ... |
#!/usr/bin/env python3.6
import unittest # Importing the unittest module
from user import User # Importing the user class
from password import Password
import pyperclip
class TestPassword(unittest.TestCase):
def setUp(self):
self.new_profile = Password("Melissa", "Moringa", "10")
self.new_user = Us... |
import random
from phrasehunter.phrase import Phrase
# Create your Game class logic in here.
class Game():
def __init__(self, phrases, life = 5):
self.phrases = [Phrase(phrase) for phrase in phrases]
self.current_phrase = ''
self.life = life
print(self.phrases)
def set_active_... |
import random
main_num, guess_num = random.randint (1, 9), 0
while main_num != guess_num:
guess_num = int(input("You are to guess a number between 1 and 9 until you get it right : "))
if guess_num > 9:
print("wrong guess, try again!")
continue
if guess_num < 9:
print(... |
""" Arithmetic_Operators
Assignment_Operator
Comparision_Operators
Logical_Operators
Identity_Operators
Membership_Operators
Bitwise_Operators"""
#Arithmetic_Operators
print("Arithmetic_Operators")
print("4*2=",4*2)
print("4+2=",4+2)
print("4-2=",4-2)
print("4/2=",4/2)
print("4**2=",4**2)
print("4//2=",4//2)
pri... |
# linear-regression-using-least-squares-
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
df=pd.read_csv("/home/charan/Downloads/Deep-Learning-Linear-Regression-master/data.csv")
x,y=df['x'],df['y']
x_mean=x.mean()
y_mean=y.mean()
b_1=sum((x-x_mean)*(y-y_mean))/sum((x-x_mean)**2)
b_0=y_mean-... |
# author: Zuolin Liu
from .utils.load_data import *
from decision_metrics import *
import random
class node:
"""Class to represent a single node in a decision tree."""
def __init__(self, left, right, decision_function, label=None):
"""Create a decision function to select between left and right nodes... |
#convert file from xlsx to csv
def convertxlsxtocsv(filename):
pass
import xlrd
import unicodecsv as csv
def replacefilenameext(filename,sheetname,origext=".xlsx",newext=".csv"):
filename = filename.replace(origext,"")
filename = filename + "_" + sheetname ;
filename = filename + newext
return fi... |
# Advent of Code 2017, Day Two
# Python 3.6
# --- Day 2: Corruption Checksum ---
#
# As you walk through the door, a glowing humanoid shape yells in your direction. "You there! Your state appears to be
# idle. Come help us repair the corruption in this spreadsheet - if we take another millisecond, we'll have to
# disp... |
######################################################################
def series_list_drawing(): # declaration draw Series list function
if ListWidth % 2 == 0: #
print("|{}Series{}|".format(" " * int((ListWidth - 3) / 2), " " * int((ListWidth - 3) / 2 + 1))) #
else: #
print("|{}Series{}|".... |
import pickle
import os
import re
class People(object):
"""utilize a class of People to store peoples' information"""
def __init__(self, name, adress, email, phonenumber):
self.name=name
self.adress=adress
self.email=email
self.phonenumber=phonenumber
#load function load a pickle instance once a time,so we ... |
import random
def main():
number_guesser()
main_test = 0
while main_test == 0 :
userAnswer = input("play again?")
if userAnswer.upper() == "NO":
print("Have a great day!")
main_test = 1
else:
number_guesser()
def number_guesser():
"""a funct... |
class Money:
def __init__(self, amount, currency):
self.amount = amount
self.currency = currency
def __str__(self):
return "{} {}".format(self.amount, self.currency)
def __gt__(self, other):
return self.wallet_value() > other.wallet_value()
def __lt__(self, other):
... |
from collections import Counter
def part1(data):
__import__('time').sleep(1)
# Data is automatically read from 06.txt
data = data.split("\n")
group = getNextGroup(data)
total=0
while group != -1:
#find sum and add it to total
#print("StartLoop")
total += findSum(group)
data = removeNextGrou... |
import pygame
class player(object):
def __init__(self, x, y, width, height, obstacle_speed):
self.x = int(x)
self.y = int(y)
self.width = int(width)
self.height = int(height)
self.vel = 3
self.score = 0
self.obstacle_speed = obstacle_speed
self.dead ... |
# coding: utf-8
# In[12]:
# Question 1: Write a function to compute 5/0 and use try/except to catch the exceptions
def DivideByZero(x,y):
try:
x/y
except ZeroDivisionError as e:
print("An interger/number can't be divisible by Zero")
print("An execption has been occured as, ",e, " a... |
#!/bin/python3
import os
# Complete the twoStrings function below.
def twoStrings(s1, s2):
result = "NO"
mySet = {*()} #An empty set that it is going to be used in order not to get timeout errors
for i in range(0, len(s1)):
if not(s1[i] in mySet):
mySet.update(s1[i])
for j ... |
"""
builder.py
Wordt gebruikt om een wijkindeling samen te stellen die aan de vereisten voldoet.
Programmeertheorie
Universiteit van Amsterdam
Jop Rijksbaron, Robin Spiers & Vincent Kleiman
"""
import pandas as pd
from code.classes.objects import Water, House
from code.helpers.location import location_checker
from... |
def bubble(list_a):
# SCan not apply comparision starting with last item of list (No item to right)
indexing_length = len(list_a) - 1
sorted = False # Create variable of sorted and set it equal to false
while not sorted: # Repeat until sorted = True
sorted = True # Break the while loop whene... |
from stack import Stack
def reverse_string (argument):
reversed_string = ''
stack_object = Stack()
for character in argument:
stack_object.push(character)
while not stack_object.isEmpty():
reversed_string = reversed_string + str(stack_object.pop())
return True if argument == rev... |
# More strings and text
# Program will say, "There are 10 types of peoples."
x = "There are %d types of peoples." % 10
# Program defines binary
binary = "binary"
# Program defines doNot
doNot = "don't"
# Program will say, "Those who know binary and those who don't"
y = "Those who know %s and those who %s" % (binary, d... |
import numpy as np
import matplotlib.pyplot as plt
import numpy as np
from numpy import linalg as la
epsilon = 0.0001
def reLu(x):
return 0.5*(x + np.sqrt(x**2 + epsilon))
def sigmoid(x):
return 1/(1+np.exp(-1*x))
class Layer():
def __init__(self, n_values, func = "none"):
self.n_values = ... |
#!/usr/bin/python
import sys
#entrada de stdin
for line in sys.stdin:
#remove espaços em branco
line = line.strip()
#quebra linha em palavras
words = line.split()
for word in words:
print('%s\t%s' % (word.lower(), 1)) |
'''
los datos dados en el csv, representa el numero de cambios de aceite al año y costo
de la reparacion (en miles de soles), de una muestra de 20 autos de una cierta marca y modelo
a. realiza la grafica de dispersion
'''
import csv
import matplotlib.pyplot as plt
import numpy as np
costo=[]#variable dependiente y
cam... |
"""class DoubleIntegral:
USED TO CALCULATE DOUBLE INTEGRALS - CAIGE MIDDAUGH
def __init__(self, m, n,a,b,c,d,function):
self.m=m
self.n=n
self.a=a
self.b=b
self.c=c
self.d=d
self.function=function
self.deltaX=(b-a)/m
self.deltaY=... |
#20103323 김태욱 Day05(0828) - homework2 : 도서관리 프로그램을 tkinter와 sqlite3를 이용하여 만들기
from tkinter import *
import sqlite3
#UI class
class BookManageUI:
#Constructor에서 DB파일을 만들고 manageStart로 UI 시작
def __init__(self, master):
#Open db
self.con = sqlite3.connect('bookDB.db')
self.cur = self.con.c... |
import numpy as np
import einops
def derive_rotation_matrices(order: int) -> np.ndarray:
"""Calculate a set of rotation matrices for a cyclic symmetry.
Axis of rotation is the Z axis.
Matrices are defined
Rz = [[cos(t), -sin(t), 0],
[sin(t), cos(t), 0],
[ 0, 0, ... |
import sqlite3
conexao = sqlite3.connect("aula_banco_py.db")
c = conexao.cursor()
cpf = input("Digite o CPF da pessoa: ")
rg = int(input("Digite o novo RG da pessoa: "))
nome = input("Digite o novo nome da pessoa: ")
c.execute("update pessoa set nome = ?, rg = ? where cpf = ?", (nome, rg, cpf))
print("Linhas atualiz... |
'''Lista de exercicio programacao para redes
Questao 1
Faça um Programa que peça 2 números inteiros e
um número real. Calcule e mostre:
a. O produto do dobro do primeiro com metade do segundo.
b. A soma do triplo do primeiro com o terceiro.
c. O terceiro elevado ao cubo.'''
print("Programa para calcular")
num1=int(inpu... |
import c_function
#menu da aplicação
resposta = c_function.home()
print(resposta['serviço'])
print(resposta['descrição'])
opcoes = {1: "Adicionar Contato", 2: "Consultar Contato", 3: "Remover Contato"}
while True:
print("\nOpções:")
print("0 - Encerrar o programa")
for opcao in opcoes:
print("{} ... |
import math
#Determine 2 raizes de uma equação do 2º grau Y=a^2 + b + c.
a = int(input("Digite A: "))
b = int(input("Digite B: "))
c = int(input("Digite C: "))
#Calcula o delta
delta = int(((b**2) - (4 * a * c)))
#Calcula o x1
x1 = int((((-b) + (math.sqrt(delta)))/(a*2)))
#Calcula o x2
x2 = int((((-b) - (math... |
import matplotlib.pyplot as plt
list = {}
x_values = range(7,16)
init_split = range(30,70,10)
colors = ['b', 'g', 'r', 'c', 'm', 'y', 'k']
for tr in init_split:
y_values = []
te = 100-tr
for j in x_values:
p = float(100)/float(tr+(te/j));
new_tr = (p*float(tr))
y_values.append(... |
"""
ref: https://leetcode.com/problems/number-complement/#/description
Given a positive integer, output its complement number. The complement strategy is to flip the bits of its binary representation.
Note:
The given integer is guaranteed to fit within the range of a 32-bit signed integer.
You could assume no leading... |
## Predicting medical expenses ##
# Importing packages #
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
from sklearn.linear_model import LinearRegression
from sklearn.tree import DecisionTreeRegressor, plot_tree
from sklearn.ensemble import RandomForestRegressor
from sklearn.model_selectio... |
''' # Python
-Variables and data types-
print(" /|")
print(" / |")
print(" / |")
print(" /___|")
character_name = "Sam"
character_age = "23"
print("There once was a man named " + character_name+".")
print("He did not like being " + character_age+".")
-Booleans-
is_male = True
is_male = False
-Working with... |
from collections import deque
import unittest
def bfs(graph, start, search):
queue = deque()
visited = set()
queue += start
while queue:
vertice = queue.popleft()
if vertice not in visited:
visited.add(vertice)
if vertice == search:
return visited
else:
diff = graph... |
class AppendDict:
def __init__(self):
self.val={}
def __getitem__(self,key):
if key not in self.val.keys():
raise KeyError
elif len(self.val[key]) == 1:
return self.val[key][0]
else:
return self.val[key]
def __setitem__(self,key,value):
if key in self.val.keys():
if val... |
def quickSort(list, first, last):
if first < last:
splitPoint = partition(list, first, last)
quickSort(list, first, splitPoint-1)
quickSort(list, splitPoint+1, last)
def partition(list, first, last):
leftMark = first+1
rightMark = last
exchange = False
while not exchange:
... |
# https://leetcode.com/problems/russian-doll-envelopes/description/
# import bisect
# class Solution(object):
# def maxEnvelopes(self, envelopes):
# """
# :type envelopes: List[List[int]]
# :rtype: int
# """
# if len(envelopes) < 2:
# return len(envelopes)
# ... |
# https://leetcode.com/problems/linked-list-cycle/description/
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def hasCycle(self, head):
"""
:type head: ListNode
:rtype: bool
... |
#!/usr/bin/python3
class customer():
CustomerID=0
custname=0
address=0
contactdetails=0
def __init__(self):
#print("\nNow in Customer class")
pass
def add_customer_details(self,cust_id=0,cust_name=0,cust_add=0,cust_contact=0):
customer.CustomerID = cust_id
... |
from __future__ import print_function
try:
input = raw_input
except NameError:
pass
import webbrowser
import time
from .api import Fanfou, json
from .oauth import OAuth, write_token_file
def get_oauth_pin(oauth_url, open_browser=True):
"""Prompt the user for the OAuth PIN.
By default, a browser wi... |
#assigning an string variable
x = "starbucks" #notice no semi-colons
#assigning a integer variable
x = 4 #note python has dynamic variable types
#the previous value of x, "starbucks", has now been overwritten
#arithmetic operations
print x + 1 #output: 5
x = x - 1 #the result of x-1 was stored back in x
print... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.