text stringlengths 37 1.41M |
|---|
from Tkinter import *
root = Tk()
root.title('Canvas')
canvas = Canvas(root, width =400, height=400)
xy = 10, 105, 100, 200
canvas.create_arc(xy, start=0, extent=270, fill='gray60')
canvas.pack()
root.mainloop() |
import math
class NegativeNumberError( ArithmeticError ):
pass
def squareRoot( number ):
if number < 0:
raise NegativeNumberError, "Square root of negative number not permitted"
return math.sqrt( number )
while 1:
try:
userValue = float( raw_input( "\nPlease enter a number: " ) )
print ... |
class Fruit:
def __init__(self, type):
self.type = type
class Fruits:
def __init__(self):
self.types = {}
def get_fruit(self, type):
if type not in self.types:
self.types[type] = Fruit(type)
return self.types[type]
if __name__ == '__main__':
fruits = F... |
counters = [1, 2, 3, 4]
updated = []
for x in counters:
updated.append(x + 10) # add 10 to each item
print(updated)
def inc(x): return x + 10 # function to be run
print(list(map(inc, counters))) # collect results
print(list(map((lambda x: x + 3), counters))) ... |
print("Hello world")
print("I have %d cats and %d dogs" %(5,6))
print("Here are the numbers! \n"
"The first is {0:d} The second is {1:4d} ".format(7,8))
##input함수는 String을 반환함-> int로 형변환하여 연산
#salary=int(input("please enter your salary: "))
#bonus=int(input("Please enter your bonus: "))
#payCheck=salary+bonus
#pr... |
#class A():
# def __init__(self,a):
# self.a=a
# def show(self):
# print('show:',self.a)
#class B(A):
# def __init__(self,b,**arg):
# super().__init__(**arg)
# self.b=b
# def show(self):
# print('show:',self.b)
# super().show()
#class C(A):
# def __init__(self,c... |
#The following code describes a simple 1D random walk
#where the walker can move either forwards or backwards. There is an
#equal probability to move either forwards or backwards with each step.
#Numeric Python library
import numpy as np
#Random number library
import random
#Plotting libary
from matplotlib impo... |
#test.py
r = int(input("반지름을 입력하세요"))
h = int(input("높이를 입력하세요"))
print("r :", r)
print("h :", h)
p = 3.14
int(p)
v =r**2*h*p
print("원기둥의 부피 :",v)
|
"""
[21-01-29] 114. Flatten Binary Tree to Linked List
https://leetcode.com/problems/flatten-binary-tree-to-linked-list/
"""
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
cl... |
"""
[21-01-04] 314. Binary Tree Vertical Order Traversal
https://leetcode.com/problems/binary-tree-vertical-order-traversal/
"""
class Solution:
def verticalOrder(self, root: TreeNode, col = 0) -> List[List[int]]:
result = {}
def dfs(root: TreeNode, row, col):
if root is None: ... |
"""
[21-01-04] 559. Maximum Depth of N-ary Tree
https://leetcode.com/problems/maximum-depth-of-n-ary-tree/
"""
"""
# Definition for a Node.
class Node:
def __init__(self, val=None, children=None):
self.val = val
self.children = children
"""
class Solution:
def maxDepth(self, root: 'Node') -> i... |
"""
[21-07-23] 98. Validate Binary Search Tree
https://leetcode.com/problems/validate-binary-search-tree/
"""
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
... |
def lines_are_paralel(l1,l2):
if l1[0] == l2[0]:
return True
else:
return False
def main():
a, b, c = input ("Digit the values for 'a', 'b' and 'c' of the first line ax + b = c: ").split()
d, e, f = input ("Digit the values for 'd', 'e' and 'f' of the second line dx + e = f: ").split()... |
'''
Пошук підрядка в рядку
'''
a = input('Введіть рядок: ') #вводимо рядок
b = input('Введіть шуканий підрядок: ') #вводимо шуканий підрядок
i = a.find(b)
k = 0
if i >= 0: #функція find поветрає індекс елемента або -1, якщо збігів немає
print(f'Збіг знайдено на {i} позиції')
k = i+len(b)
'''
к-сть перев... |
# Data.py
#
#
# This will be the module that handles the data we need for testing and training our neural network.
# It will also deal with the extracted objects of the actual data
#
#
# load necessary libraries
# from scipy import ndimage
# from scipy import misc
# import matplotlib.pyplot as plt
# import os
import nu... |
'''
Constraints are a simple library of checks for validating simple attributes in model objects.
Created on Oct 24, 2014
@author: vsam
'''
#
# Constraint checking classes
#
class ConstraintViolation(ValueError):
"""Thrown by Constraint objects when the constraint is not true.
"""
def __init__(self,... |
import numpy as np
from scipy import stats
class n_armed_bandit(object):
'''
Class that simulates a n-armed bandit problem. (https://en.wikipedia.org/wiki/Multi-armed_bandit)
On this implementation, all the n armed bandits give rewards generated from normal distributions.
'''
def __init__(self, n... |
"""
题目描述:
依次给出n个正整数A1,A2,… ,An,将这n个数分割成m段,每一段内的所有数的和记为这一段的权重,
m段权重的最大值记为本次分割的权重。问所有分割方案中分割权重的最小值是多少?
"""
#考虑如果最多可以将这n个数分割成n段,最小就先是1段吧,然后就可以开始二分查找了
#利用二分逼近法来求解:用x
def S(arr, m):
#最小值为max(arr),即分割长度为1
left = max(arr)
right = sum(arr)
while left < right:
mid = (left + right)>>1
sets = 1
... |
#法一:回溯法,好像时间通不过
class Solution1:
def canJump(self, nums:[int]) -> bool:
length = len(nums)
flag1 =False
def backtrace(k):
if k >=length-1:
return True
for i in reversed(range(nums[k])):
flag2 = backtrace(k+i+1)
if flag2:
return True
return False
flag1 = backtrace(0)
return flag1... |
"""
快速排序,paritition 非递归版本实现,
"""
def quicksort(alist,start,end):
#如果只剩一个或0个元素,返回
if start>=end:
return
m = start
for i in range(start+1,end+1):
#因为m记录的是从左往右的第一个大于start的下标的前面一个位置
#如果alist[i]小于中枢元素,那么肯定被交换到前面了
if alist[i] <alist[start]:
m+=1
alist[i],alist[m] = alist[m],alist[i]
alist[start],alist[m]... |
#Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def hasPathSum(self, root: TreeNode, sum: int) -> bool:
if not root:
return False
sum-=root.val
if not root.left and not root.right and sum == 0:
return True
... |
def pluswithout(num1,num2):
while True:
sum = num1 ^num2
#一定不要忘记这里的左移一位
carry = (num1 & num2) <<1
num1= sum
num2 = carry
if num2 ==0:
break
return num1
print(pluswithout(2,1))
|
import random
class Solution:
def __init__(self, nums):
self.init = list(nums)
self.nums = nums
self.length = len(nums)
def reset(self) -> [int]:
"""
Resets the array to its original configuration and return it.
"""
self.nums = list(self.init)
return self.nums
def shuffle(self):
"""
Returns a r... |
# class Solution:
# def combinationSum(self, candidates, target: int):
# result = []
# def backtrace(candidates=candidates,target=target,tmp=[]):
# if target == 0:
# result.append(tmp)
# return
# for i in candidates:
# if (target-i)>=0:
# backtrace(candidates,target-i,tmp+[i])
# else:
# ... |
#Función por cada uno de los puntos#
##devolver número elevado al cuadrado
def numeroalCuadrado (numero):
return numero**2
num1= numeroalCuadrado(6)
print (f"El número dado elevado a la dos es {num1}")
##devolver número elevado a la 3
def numeroalCubo (numero):
return numero**3
num2= numeroalCubo(6)
print (f... |
def sumar (valor1=0, valor2=0):
return valor1+ valor2
def restar (valor1=0, valor2=0):
return valor1 - valor2
def multiplicar (valor1=0, valor2=1):
return valor1 * valor2
def dividir (valor1=0, valor2=1):
return valor1 / valor2
def calculadora (accion, valor1, valor2):
print (accion(valor1, valo... |
#https://checkio.org/
#https://www.codewars.com/
#https://ru.khanacademy.org/
#https://ide.c9.io/tolearn/ruby
foo=lambda a,b:a+b
print foo(10,20)
fooKub=lambda a:a*a*a
print fooKub(10)
print foo
print (lambda x:x**3)(10)
def foo(n):
def foo2(m):
return n+m
return foo2
f=foo(100)
print f(1),f(2)... |
l=[1,2,1,3,2]
n=[]
h=[]
for i in l:
if not i in n:
n.append(i)
print n
#def foo():
# a,b=10,20
# c=a+b
# print c
#for i in range(2):
# foo()
#def foo(a,b):
# print a+b
#foo(2,4)
#foo(5,6)
#for k in range(10):
# foo(k,k+1)
def foo(a,b)... |
def recursive_min(nested_num_list):
"""
>>> recursive_min([2, 9, [1, 13], 8, 6])
1
>>> recursive_min([2, [[100, 1], 90], [10, 13], 8, 6])
1
>>> recursive_min([2, [[13, -7], 90], [1, 100], 8, 6])
-7
>>> recursive_min([[[-13, 7], 90], 2, [1, 100], 8, 6])
-13
"""
... |
def is_divisible_by_n(x, n):
if x % n == 0:
print "Yes,", x, "is divisible by", n
else:
print "No," x, "is not divisible by", n
|
#!/usr/bin/env python
from gasp import *
PLAYER_1_WINS = 1
PLAYER_2_WINS = 0
QUIT = -1
# def distance(x1, y1, x2, y2):
# return ((x2 - x1)**2 + (y2 - y1)**2)**0.5
def hit(bx, by, r, px, py, h):
"""
>>> hit(760, 100, 10, 780, 100, 100)
False
>>> hit(770, 100, 10, 780, 100, 100)
... |
"""
This tester script checks if our machine learning model predicts the sentiments accurately or not!
Steps:
1. Load the model from the pickle file
2. Get the user input, preprocess it (using helper script) and vectorize using TF-IDF
3. Check the model prediction on the result of step 2
a. Counter... |
import os
import math
p = int(input('Enter the perpendicular'))
b = int(input('Enter the breadth'))
mcb = math.degrees(math.atan(p/b))
print('mcb',mcb)
|
import networkx as nx
graph = nx.Graph()
with open("input.txt") as file:
edges = int(file.readline().split()[1])
for e in range(edges):
u, v = (int(i) for i in file.readline().split())
graph.add_edge(u, v)
subgraphs = list(graph.subgraph(c) for c in nx.biconnected_components(graph))
for su... |
#!/usr/bin/python3
import sys
u = int(sys.argv[1])
v = int(sys.argv[2])
while v:
t = u
u = v
v = t % v
if u < 0:
u = -u
print("The gcd of", sys.argv[1], "and", sys.argv[2], "is", u);
|
## import modules here
################# Question 0 #################
def add(a, b): # do not change the heading of the function
return a + b
################# Question 1 #################
def nsqrt(x): # do not change the heading of the function
if x == 1:
return 1
start = 1
end = x
w... |
''' Program for entering tasks into database '''
import sqlite3
from sqlite3 import Error
import itertools
from os.path import expanduser, join
from pprint import pprint
print('Enter tasks: ')
print('''
("commit" to commit to db,
"clear" to delete tasks in buffer,
"print" to show tasks in buffer,
Ctrl-C to quit)''')
... |
# url: https://www.coursera.org/learn/programming-in-python/programming/0664k/diekorator-to-json
from functools import wraps
import json
def to_json(func):
@wraps(func)
def wrapped(*args, **kwargs):
result = func(*args, **kwargs)
json_result = json.dumps(result)
return json_result... |
# -*- coding: utf-8 -*-
"""
Obtained from: https://gist.github.com/butla/2d9a4c0f35ea47b7452156c96a4e7b12
"""
import time
import socket
def wait_for_port(port, host='localhost', timeout=5.0):
"""Wait until a port starts accepting TCP connections.
Args:
port (int): Port number.
host (str): Host... |
'''
Output
----------------------------------------------
without 0 : The RGB image will get displayed ,
with 0 : The GrayScale image will get displayed
'''
import cv2
import numpy as np
from PIL import Image
# When the image file is read with the OpenCV function imread(),
# the order of colors is BGR (blue, green, ... |
import numpy as np
# Sigmoid function
def sigmoid(Z):
A = 1/(1 + np.exp(-Z))
cache = Z
return A, cache
# Relu function
def relu(Z):
A = np.maximum(0, Z)
cache = Z
return A, cache
"""
Used in backpropagation
dA -- post-activation gradient, of any shape
dZ -- Gradient of the c... |
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def swapPairs(self, head: ListNode) -> ListNode:
if not head or not head.next:
return head
_next = head.next
_next.next = head
head.next = self.swapPairs(_next.next)
... |
from random import random
import math
TRAIN_LOOP = 3
TIME_PER_NEURON = 100 #time is a social construct. We don't need units!
TIME_DIFF = 0.01
LOW_CURR = 2e-3
HIGH_CURR = 5e-3
ON_TRAIN = 1
OFF_TRAIN = -100
case_rates = {}
negativeWeightCtr = 0
CTR = 100
def currToRate(curr):
m = 3124.674377412921
b = 1... |
# if x > 10:
# add 2 to it
# else:
# multipy by 2
#
def random(x) :
return x + 2
print(random(10))
def number(x) :
return x * 2
print(number(1)) |
'''
Created on Mar 4, 2014
@author: kylerogers
'''
class PageHelper:
@staticmethod
def get_request_count(request, default_count_per_page, max_count_per_page):
'''
Finds the requested number of brothers and corrects it if there are any issues
If the number is invalid, it will retur... |
#!/usr/bin/env python
def sink(alist, start, end):
root = start
while 2*root + 1 <= end:
child = 2*root + 1
swap = root
if alist[swap] <= alist[child]:
swap = child
if child+1 <= end and alist[swap] < alist[child+1]:
swap = child + 1
if swap != ... |
# -*- coding: utf-8 -*-
"""
Created on Sun Dec 8 11:42:04 2019
@author: MaxFelius
TOOLBOX
function to automatically create latex and csv tables
Also flexibel to add and remove rows
TODO
-finish script
-automatically copy the output table to clipboard
TODO Class
-finish empty functi... |
'''
3-6. 더 많은 손님
식당에서 예약 인원을 늘릴 수 있다 하여 손님을 더 초대할 수 있습니다. 저녁에 초대할 사람을 세 명 더 생각하세요.
- 연습문제 3-4나 3-5에서 프로그램을 시작하세요. 프로그램 마지막에 print문을 추가해 사람들에게 더 큰 저녁 식탁을 발견했다고 알리세요.
- insert()를 써서 새 손님 한 명을 리스트 맨 앞에 추가하세요.
- insert()를 써서 새 손님 한 명을 리스트 중간에 추가하세요.
- append()를 써서 새 손님 한 명을 리스트 마지막에 추가하세요.
- 리스트에 있는 각 손님 앞으로 새 초대 메시지를 출력하세... |
'''
4-7. 3배수
3부터 30까지 3의 배수로 리스트를 만드세요. for 루프를 써서 각 숫자를 출력하세요.
Output:
3
6
9
12
15
18
21
24
27
30
'''
threes = list(range(3, 31, 3))
for number in threes:
print(number)
|
'''
3-2. 단순한 메시지들
연습문제 3-1의 리스트를 활용합니다. 이번에는 바로 출력하지 말고 문장을 만드세요. 각 문장의 텍스트는 사람 이름만 다르고 나머지는 같게 해봅시다. 예를 들어 다음과 같이 출력하세요.
Output:
Hello, ron!
Hello, tyler!
Hello, dani!
'''
names = ['ron', 'tyler', 'dani']
msg = 'Hello, ' + names[0] + '!'
print(msg)
msg = 'Hello, ' + names[1] + '!'
print(msg)
msg = 'Hello, ' + nam... |
import intCodeProgram
import matplotlib.pyplot as plt
NORTH = 1
SOUTH = 2
WEST = 3
EAST = 4
DIRECTIONS = [NORTH, SOUTH, WEST, EAST]
WALL = 0
MOVED = 1
MOVED_AND_GOAL = 2
def solve(intCode, mazeDict, wasHereDict, correctPathDict, directionIndex, x=0, y=0, ptr=0, relativeBase=0):
outputVal, ptr, relativeBase = int... |
#logistic Regression As a Neural Network
#Note:
#This is a basic perceptron
#perception comes with stimulation. when an eye see the light, eye get stimulated and build the perception called vision
#This gets a stimulus and percive value of the summation
#What does the logictic regression mean
#Logistic regression is... |
'''
Program: quadratic.py
Written by: Elayna Ridley
Purpose: To calculate the value of x.
How to use: Enter three numbers eperated by a comma when prompted.
Input: three numbers seperated by a comma.
Output: The value x
'''
import math
print("Type in A, B, C ... |
# << Swami Shreeji >>
# 4 Jan 2018
# You have a list of integers, and for each index you want to find the product
# of every integer except the integer at that index. Write a function
# get_products_of_all_ints_except_at_index() that takes a list of integers
# and returns a list of the products.
# Given:
#... |
# Swami Shreeji
# 7 Feb 2018
# Sorting names, instead of numbers. And get the most frequent name at the start
def sortNames(names):
# Check if in dict, increment if yes. Else, add to dict
myDict = {}
for elem in names:
if elem in myDict:
myDict[elem] += 1
else:
myDict[elem] = 1
# Reverse sort and retur... |
# << Swami Shreeji >>
# 7 Jan 2018
# TASK: Using 2016_general.csv
# Get the candidate with the most votes.
# Get the votes of all candidates who ran for president and vp
# NOTE: The csv data is raw. This means duplicates of candidates exist.
# But those duplicates will have some differences - like votes across row... |
# << Swami Shreeji >>
# 21 Nov 2017
# Algo --> Implementation --> Encryption
import sys
import string
import math
# Cases
case0 = "ifmanwasmeanttostayonthegroundgodwouldhavegivenusroots" # 54 PASS
case1 = "haveaniceday" # 12 PASS
case2 = "feedthedog" # 10 PASS
case3 = "chillout" # 8 FAILS
def encrypt(args):
# Step... |
# Swami Shreeji
# 7 Feb 2018
# Determine whether a string is a "lovely" string, meaning its characters are not repeated.
# i.e. 123 is lovely, but nishant is not
# NOTE: The answer is function is case sensitive. Add a lowercase if needed, use a set
def lovely(case):
answer = {}
for elem in case:
if len(set(elem... |
'''
对内存操作——有操作字符串和二进制两种
字符串——StringIO
二进制——BytesIO
stream position——流位置的概念,当初始化传入字符串的时候stream position的位置是0,当写入字符串的时候stream position的位置是写入字符串的长度
1. 可以通过tell()方法查看stream position的值
2. 可以通过seek(position)方法设置值,当设置position后,则read()方法从该position位置往后读取
3. 当调用write方法写入数据后stream position的值是根据写入的字符串长度变化的
4. 调用... |
'''
多重继承——一个子类可以同时获得多个父类的所有功能
注意:多重继承时,如果后一个父类中有和前一个父类中同名的属性/方法,最终继承的是前一个父类的属性/方法
'''
class Animal(object):
def __init__(self, name):
self.name = name
class Bird(Animal):
def __init__(self, name):
Animal.__init__(self, name)
def catchWorm(self):
print('I\'m catching worms!')
class Mammal(Animal):
... |
#!/usr/bin/env python
# coding: utf-8
# In[ ]:
import math
e= input('Enter e:')
e = int(e)
x = input('Enter x:')
x = int(x)
e**(-4)/(5math.tan(x))+math.tan(math.log10(x**3)/3)
print(x)
|
import csv
with open('Crew.csv', mode = 'r') as csvfile:
readCSV = csv.reader(csvfile, delimiter = ',')
ssn = []
employee_list = []
header = next(readCSV)
for row in readCSV:
ssn = row[0]
emp_name = row[1]
emp_role = row[2]
emp_rank = row[3]
emp_licenc... |
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import style
import warnings
from collections import Counter
import pandas as pd
import random
style.use( 'fivethirtyeight')
# define k nearest neighbors function
def k_nearest_neighbors(data, predict, k = 3):
if len(data) > k:
warnings("T... |
# Madison Fletcher
# 1868748
class ItemToPurchase:
def __init__(self, item_name="none", item_quantity=0, item_price=0):
self.item_name = item_name
self.item_quantity = item_quantity
self.item_price = item_price
def print_item_cost(self):
print(self.item_name, self.item_... |
# Madison Fletcher
# 1868748
class Team:
def __init__(self):
self.team_name = 'none'
self.team_wins = 0
self.team_losses = 0
def get_win_percentage(self):
return self.team_wins / (self.team_wins + self.team_losses)
if __name__ == "__main__":
team = Team()
... |
# Madison Fletcher
# 1868748
word = input()
word2 = word.replace(' ', '')
if word2 == word2[::-1]:
print(word, "is a palindrome")
else:
print(word, "is not a palindrome")
|
# coding: utf-8
"""階段を登りつめる方法を考えるプログラム
"""
CACHE = {}
def climbup(nsteps):
"""再帰でやるその1
"""
if CACHE.get(nsteps) is not None:
return CACHE[nsteps]
if nsteps == 0:
return 1
if nsteps < 0:
return 0
CACHE[nsteps] = climbup(nsteps-1) + climbup(nsteps-2) + climbup(nsteps-3)
... |
# coding: utf-8
class Node(object):
def __init__(self, data):
self.data = data
self.__left = None
self.__right = None
def put(self, node):
if node.data <= self.data:
if self.__left is None:
self.__left = node
else:
self.__... |
# coding: utf-8
def search_rotated_index(rotated, left, right):
if left == right:
return -1
if rotated[left] > rotated[right]:
mid = (left + right) / 2
l = search_rotated_index(rotated, left, mid)
r = search_rotated_index(rotated, mid + 1, right)
if l == -1 and r == -1:... |
# coding; utf-8
import math
all_patterns = []
def add_columns(row, columns):
if row == len(columns):
all_patterns.append(columns[:])
for col in range(len(columns)):
if check_valid(row, col, columns):
columns[row] = col
add_columns(row + 1, columns)
def check_valid(row... |
def permutation(string1, string2):
counts = {}
for c in string1:
cnt = counts.get(c,0)
counts[c] = cnt+1
for c in string2:
cnt = counts.get(c, 0)
cnt -= 1
if cnt < 0:
return False
counts[c] = cnt
return True
if __name__ == "__main__":
str... |
import scipy
# ==================================
# === Error function definitions ===
# ==================================
def gradient(x, x_min, x_max):
"""
Gradient scaling function. The gradient is computed
to result in +/-1 scales at x_max and x_min correspondingly.
Parameters
----------
... |
#initializing variables
n = 10
i =1
while i <= 10 :
summation_of_numbers = 1/(i**2)
sum_of_num = summation_of_numbers + 1/(i**2)
i = i + 1
print( sum_of_num)
|
import streamlit as st
import pandas as pd
from sklearn.model_selection import train_test_split
from joblib import load
st.image('imagem.png', width=1000)
#use_column_width=False, clamp=False, width=1000
st.title("Detectando Fake News de COVID-19")
st.subheader("Está em dúvida se a notícia é verdadeira o... |
"""
Game gunting batu kertas sederhana.
User vs BOT(random).
User akan memasukkan nama dan pilihan tangan(0 = gunting, 1 = batu dan 2 = kertas),
sementara BOT akan memilih tangan secara acak(0-2)
"""
import utils
import random
print('--------------------------------------')
print('Memulai permainan Gunting B... |
import random
from state import GameState as gameState
import math
#global variables
# q_table = [list([0, 0, 0])] * 10369
# N= [list([0, 0, 0])] * 10369
q_table = {}
N = {}
epsilon = 0.05
# This function udpates the ball position and checks the bounce/termination conditions. Returns a state
def play_game(state, act... |
"""
Sun
Class to calculate the approximate position of the sun at a particular time.
"""
import numpy
_deg2rad = numpy.pi/180.0
_rad2deg = 180.0/numpy.pi
_MJD2000 = 51544.5
class Sun():
def __init__(self):
"""Instantiate the Sun object."""
return
def getLon(self, mjd):
"""Calcula... |
# --------------
#Importing header files
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
#Reading the file
data=pd.read_csv(path)
#Code starts here
# Step 1
#Reading the file
#Creating a new variable to store the value counts
loan_status=data['Loan_Status'].value_counts()
#Plotting bar p... |
import numpy as np
def sigmoid(x, deriv=False):
if(deriv==True):
return x*(1-x)
return 1/(1+np.exp(-x))
np.random.seed(1)
class TwoLayerNN:
"""Neural Network with no hidden layers."""
def __init__(self):
self.syn0 = 2*np.random.random((3,1)) - 1 #randomly initialise weights with mean 0
def train(self, t_in... |
def add_my_function(num1,num2):
sum1=num1+num2
print(sum1,"=total of sum")
add_my_function(67,78)
# def my_multiple_function(num,num1):
# sum2=num+num1
# print("total sum=",sum2)
# my_multiple_function(9,3) |
# isEven()
# def isEven():
# if(12%2==0):
# print("Even Number")
# else:
# print("Old Number")
# isEven()
# numbers_list = [1, 2, 3, 4, 5, 6, 7, 10, -2]
# print (max(numbers_list))
# a=[1,2,3,4,5,6]
# print(len(a))
def say_hello(name):
print ("Hello ", name)
print ("Aap kaise ho?")
s... |
import unittest
import time
from src.MyHashMap import MyHashMap
class TestHashMap(unittest.TestCase):
def test_speed(self):
t0 = time.time()
hmap = MyHashMap(size=100)
for i in range(40):
hmap.set("t" + str(i), i)
hmap.get("t2")
hmap.get("t3")
t1 = time... |
import sys
def reverse_words():
words = sys.argv[1:]
output_words = reverse_words[::-1]
print( " ".join(output_words))
if __name__ == '__main__':
reverse_words()
# SAMPLE STRATEGY
# >>> y
# [8, 7, 6, 5, 4, 3, 2, 1, 0]
# >>> x = range(9)
# >>> x
# [0, 1, 2, 3, 4, 5, 6, 7, 8]
# >>> y=x[::-1]
# >>> y
... |
a = float(input('Quanto de dinheiro você tem? '))
dolar = 3.27
b= a / dolar
print('Você tem R$ {:.2f} em carteira e pode comprar $ {:.2f} dolares'. format(a, b)) |
from player import Player
class Detective(Player):
def __init__(self, index, start_position, num_taxi_tickets=11, num_bus_tickets=8, num_metro_tickets=4,
needs_tickets=True, color='red'):
# Call init-function of abstract player to set the current and previous position
Player.__ini... |
from collections import defaultdict
import sys
def is_wall(x, y, n):
v = x*x + 3*x + 2*x*y + y + y*y + n
o = format(v, "b").count("1")
if o % 2 == 0:
return False
else:
return True
def get_neighbours(x,y):
return [(x-1,y),(x+1,y),(x,y-1),(x,y+1)]
def print_grid(grid):
for y in... |
# using expressions / statements
# know slice
# with statement
# slicing someline[start:end] a list with index
# list
a = ['a','b','c','d']
# print(a[:])
# slice someindex[start:end:stride]
# print(a[3::2])
# enumerate a list over range
|
"""
Dynamic Programming Algorithm (Optimal, inefficient)
Held-Harp dynamic programming is an algorithm for finding optimal tours, not approximate ones, so it is not appropriate for large n.
But even in its simplest form, without any programming tricks, it can go quite a bit further than alltours.
Because, alltouts wast... |
# # penggunaan end
# print('A', end='')
# print('B', end='')
# print('C', end='')
# print()
# print('X')
# print('Y')
# print('Z')
# # pengggunaan separtor
# w, d, y, z = 10, 15, 20, 25
# print(w, d, y, z)
# print(w, d, y, z, sep='+')
# print(w, d, y, z, sep='x')
# print(w, d, y, z, sep=':')
# print(w, d, y, z, sep=... |
def matrix_mul(m_a,m_b):
a_row = len(m_a)
if a_row < 1:
return None
a_col = len(m_a[0])
if a_col < 1:
return None
b_row = len(m_b)
if b_row < 1:
return None
b_col = len(m_b[0])
if b_col < 1:
return None
if a_col != b_row:
return None
ans ... |
def overlap(list1,list2):
dict1 = {}
for i in list1:
dict1[i] = 1
ans = []
for ii in list2:
if ii in dict1:
ans.append(ii)
return ans
|
def tonydumbdumb(words):
if len(words) > 0:
print "Oh dear, that was pretty dumb."
return True
else:
print "Bliss!"
return False
words = raw_input("What did Tonez say? ")
tonydumbdumb(words)
|
import basicdp
import math
from examples import __build_intervals_set__
from functools import partial
# TODO check endpoints of interval along the code
def evaluate(data, range_max_value, quality_function, quality_promise, approximation, eps, delta,
intervals_bounding, max_in_interval, use_exponential=Tr... |
"""
json解析 ---非json格式不能用json解析
"""
import requests
import json
url = "http://127.0.0.1:8000/api/departments/"
num = {
"data": [
{
"dep_id": "T02",
"dep_name": "Test学院",
"master_name": "Test-Master",
"slogan": "Here is Slogan"
}
]
}
r = requests... |
# EXERCÍCIO 01 - LISTA 08 - CLASSES
print('Classe Bola')
print('###########')
class Bola():
def __init__(self, cor, circunferencia, material):
self.cor = cor
self.circunferencia = circunferencia
self.material = material
def troca_cor(self,nova_cor):
self.cor = nova_cor
def m... |
# EXERCÍCIO Nº 38 - LISTA 03 - ESTRUTURA DE REPETIÇÃO
print('\nReajuste de salários')
print('####################\n')
ano_atual=1997
salário = float(input('Insira seu salário:R$ '))
while salário<=0:
print('O salário deve ser maior que zero')
salário = float(input('Insira seu salário:R$ '))
while a... |
#EXERCÍCIO Nº 04 - LISTA 03 - ESTRUTURA DE REPETIÇÃO
print('\nCrescimento Populacional')
print('########################\n')
habitantes_A=80000
taxa_anual_A=0.03
habitantes_B=200000
taxa_anual_B=0.015
i=1
a=80000
b=200000
while a<=b:
a=int(a+a*taxa_anual_A)
b=int(b+b*taxa_anual_B)
i+=1
... |
# EXERCÍCIO Nº 30- LISTA 03 - ESTRUTURA DE REPETIÇÃO
print('\nPanificadora Pão de Ontem')
print('#########################\n')
preço_do_pão=0
while preço_do_pão<=0:
preço_do_pão=float(input('Insira o preço do pão:R$ '))
if preço_do_pão<=0:
print('O preço do pão deve ser maior que zero')
... |
# EXERCÍCIO Nº 02- LISTA 06 - STRINGS
print('\n Nome ao Contrário')
print('##################\n')
nome=input('Insira o seu nome: ').upper()
print(nome[::-1])
|
# EXERCÍCIO Nº 47 - LISTA 03 - ESTRUTURA DE REPETIÇÃO
print('\nCompetição de Ginática')
print('######################\n')
ginasta='ginasta'
while ginasta!='':
ginasta = input('Ginasta: ')
if ginasta!='':
nota1 = float(input('Insira a 1º nota: '))
nota2 = float(input('Insira a 2º nota: ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.