text stringlengths 5 121k |
|---|
sum=0
s=input('輸入五張牌:')
list_s=s.split(" ")
for i in range(5):
if (list_s[i]=="j" or list_s[i]=="J"):
sum+=11
elif(list_s[i]=="q" or list_s[i]=="Q"):
sum+=12
elif(list_s[i]=="k" or list_s[i]=="K"):
sum+=13
elif(list_s[i]=="a" or list_s[i]=="A"):
sum+=1
else:
s... |
a=input("請輸入string_a:")
b=input("請輸入string_b:")
a=set(a)
b=set(b)
c=sorted(a&b)
if (c==[]):
print("N")
else:
print(c) |
import pygame
import math
class Ball(pygame.sprite.Sprite):
def __init__(self, bg_size):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load('image\\ball.png').convert_alpha()
self.rect = self.image.get_rect()
self.width, self.height = bg_size[0], bg_size[1]... |
import re
import os
"""
re 模块的测试
"""
def test_compile():
str1 = 'food'
m1 = re.match('foo', str1)
print(m1)
print(m1.group())
print(m1.groups())
m = re.compile('foo')
m2 = m.match(str1)
print(m2)
print(m2.group())
print(m2.groups())
def test_search():
m = re.match('foo',... |
import numpy as np
def delannoy_num(m, n):
"""
Number of paths from the southwest corner (0, 0) of a rectangular grid to
the northeast corner (m, n), using only single steps north, northeast, or
east.
Named after French army officer and amateur mathematician Henri Delannoy.
Parameters
... |
print('Hello World!')
name = "Col-R"
print('Hello', name)
print('Hello ' + name)
number = 24
print('Hello', number)
print('Hello '+ str(number))
fave_food1 = "ramen"
fave_food2 = "cake"
print("I love to eat {} and {}".format(fave_food1, fave_food2))
print(f'I love to eat {fave_food1} and {fave_food2}')
eats... |
x = 10
if x > 50:
print("bigger than 50")
else:
print("smaller than 50")
class EmptyClass:
pass
for val in my_string:
pass
is_hungry = True
has_freckles = False
age = 35
weight = 160.57
name = "joe blue"
dog = ('Bruce', 'cocker spaniel', 19, False)
p... |
print('this is a sample string')
name = "Zen"
print("My name is", name)
name = "Zen"
print("My name is " + name)
number = 5
print('My number is', number)
print("Hello" + str(42))
total = 35
user_val = "26"
total = total + int(user_val)
first_name = "Zen"
last_name = "Coder"
age = 27
print(f"My name is... |
i = float(input("Enter number of interior walls: "))
e = float(input("Enter number of Exterior Walls: "))
for a in range(0,i):
si = (input("Enter Surface Area of Interior Walls:"))
for b in range(0,e):
se = (input("Enter Surface Area of Exterior Walls:"))
total = sum([a*18 for a in si])+sum([b*18 for b... |
li = [int(i) for i in input().split()]
m = int(input())
sum = maxSum = 0
for i in range(len(li)):
if(i < m):
sum += li[i]
else:
sum -= li[i - m]
sum += li[i]
if(sum > maxSum):
maxSum = sum
print(maxSum) |
import numpy as np
trial = [9,6,8,9,3,4,1,11,3,4,9,0]
def insertionSort(A, *args, **kwargs):
res = A
for j in range(1, len(A)):
key = A[j]
i = j-1
while (i >= 0) and (A[i] > key):
A[i+1] = A[i]
i -= 1
A[i+1] = key
return res
print(insertion... |
sent = set(input('Text to do stuff on: '))
chars = sorted(list(sent.difference('aeiou')))
print(chars)
|
tasks = []
def add_task(tasks):
name = input("\nEnter the name of your task: ")
priority = input("\nEnter priority of task: ")
task = {"Task": name, "Priority": priority}
tasks.append(task)
return tasks
def delete_task(tasks):
for index in range(len(tasks)):
print(f"{index + 1... |
from Functions import *
"""
Notes:
Need to figure out how to make Dialog Box bigger
Need to understand what size_of_user_input means
Why does sys.getsizeof always return 24?
What does named argument mean? Why can't i put *default_value? Can I make this box show up with no value in Box?
"""
TITLE = 'Find Item L... |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
def plot_temperature(months, time_bounds=None, y_bounds=None):
"""Plots the temperatures of given months vs years
Args:
months (string): The month for witch temperature values to plot. Can
also be list of strings with ... |
name = input("What is your name?\n")
age = input("How old are you?\n")
live_in = input("Where do you live?\n")
string = "Hello {}! Good to know you are {} years old and live in {}"
print(string.format(name, age, live_in)) |
print("give me a string: ")
string=input()
L=len(string)
if L>3:
print(string[0]+string[1]+string[L-2]+string[L-1])
else:
print("you have to enter a string longer than 3 characters") |
import random
class Card:
"""Initialize cards"""
def __init__(self, suit, rank):
self.suit = suit
self.rank = rank
def __str__(self):
return f'{self.rank}{self.suit}'
class Deck:
"""Create deck"""
def __init__(self):
self.deck = []
for suit in su... |
'''
You are given a perfect binary tree where all leaves are on the same level, and every parent has two children.
The binary tree has the following definition:
struct Node {
int val;
Node *left;
Node *right;
Node *next;
}
Populate each next pointer to point to its next right node. If there is no next right n... |
'''
Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
Example 1:
Input: "babad"
Output: "bab"
Note: "aba" is also a valid answer.
Example 2:
Input: "cbbd"
Output: "bb"
'''
'''
Approach 1: find the longest common substring between the string and its r... |
'''
Given an array nums and a value val, remove all instances of that value in-place and return the new length.
Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
The order of elements can be changed. It doesn't matter what you leave beyond th... |
my_list = [1,2,3,4,5,6]
print(my_list[0])
str = "Hello world"
print(str[1])
print(3 in my_list)
print('H' in str)
print(my_list.index(5))
characters = list("abcdef")
print(characters)
words = "Hello world는 프로그래밍을 배우기에 아주 좋은 사이트 입니다."
world_list = words.split()
print(world_list)
time = "10:35:59"
time_list = ti... |
import numpy as np
def sigmoid(x):
return 1.0/(1+ np.exp(-x))
def sigmoid_derivative(x):
return x * (1.0 - x)
class NeuralNetwork:
def __init__(self, x, y):
self.input = x
self.weights1 = np.random.rand(self.input.shape[1],1)
self.weights2 = np.random.rand(1,... |
import os,re,sys,commands,glob
reload(sys)
sys.setdefaultencoding("utf-8")
def reverseWords(s):
l = [x for x in s.strip().split(' ') if x]
l.reverse()
return " ".join(l)
class Solution:
def reverseWords(self, s):
return reverseWords(s)
def sp(x, y):
assert Solution().reverseW... |
import os,re,sys,commands,glob,json,collections,random
from random import randint
from LeetCodeUtils import *
def f(num):
r = []
while num > 0:
if num % 26 == 0:
r.append('Z')
num -= 26
else:
r.append(chr(num%26 + ord('A')-1))
num /= 26
r.re... |
import os,re,sys,commands,glob,json,collections,random
from random import randint
from LeetCodeUtils import *
class TreeNode:
def __init__(self, x, left=None, right=None):
self.val = x
self.left = left
self.right = right
def __repr__(self):
return str(self.val)
p... |
try:
print()
except Exception as e:
print()
try:
print()
except Exception as e:
print()
else:
print()
try:
print()
except Exception as e:
print()
else:
print()
finally:
print()
try:
a = []
print(a[3])
except Exception as e:
print(e)
el... |
class Group(object):
def __init__(self, _name):
self.name = _name
self.groups = []
self.users = []
def add_group(self, group):
self.groups.append(group)
def add_user(self, user):
self.users.append(user)
def get_groups(self):
return self.groups
def get_users(self):
return se... |
print('Give it to me!:')
number = int(input())
if number>=10:
print ("Thanks, man!")
elif 10 < number < 100:
print("OK : (")
else:
print ("Whaat???!!")
if number > 1000:
print ("!!!Wooowww!!!")
|
a = 10
def test():
global a
a = 5
test()
dict1 = {'name': 'lin', 'ID': 1}
del dict1['name']
dict2 = {'test': 'fan'}
dict1.update(dict2)
list1 = [3, 2, 1]
list2 = []
i = 2
for i in range(2, 100):
j = 2
for j in range(2, i):
if i % j == 0:
break
else:
list2.a... |
import sys
class Node:
def __init__(self):
self.left = None
self.right = None
def preOrder(node):
if node == -1:
return
print(chr(node + ord('A')), end='')
preOrder(tree[node].left)
preOrder(tree[node].right)
def inOrder(node):
if node == -1:
return
inOr... |
budget = float(input())
season = input()
destination = ""
place = ""
price = 0
if budget <= 100:
destination = "Bulgaria"
if season == "summer":
place = "Camp"
price = budget - (budget * 0.7)
elif season == "winter":
place = "Hotel"
price = budget - (budget * 0.3)... |
book_name = input()
current_book = input()
book_count = 0
is_book_found = False
while current_book != "No More Books":
if current_book == book_name:
is_book_found = True
break
else:
book_count += 1
current_book = input()
if is_book_found:
print(f"You checked {bo... |
pens_count = int(input())
markers_count = int(input())
chemical_for_cleaning_desk_by_liter = float(input())
discount_in_percent = int(input())
discount_in_percent1 = discount_in_percent * 0.01
pens_price = pens_count * 5.80
markers_price = markers_count * 7.20
chemical_price = chemical_for_cleaning_desk_by_liter... |
brand = 'Apple'
exchangeRate = 1.235235245
message = 'The price of this %s laptop is %d USD and the exchange rate is %4.2f USD to 1 EUR' %( brand, 1299, exchangeRate)
print (message)
myList = [1, 2, 3, 4, 5]
myList.append("How are you?")
print(myList)
print(myList[-1])
yourName = input("Please enter your name:")
prin... |
'''tests/validate.py'''
import unittest
from application.views.validate import Validate
class ValidateTestCase(unittest.TestCase):
'''class representing Validate test case'''
def setUp(self):
self.validate = Validate()
def test_validate_email(self):
'''test to validate email'''
... |
def get_result(begin, end):
s = [x for x in range(begin, end + 1) if x % 11 == 0 and x % 3 != 0]
return '; '.join(str(x) for x in s)
def reverse_number(x):
return int("".join(reversed(str(x))))
def get_dictionary(n):
result = {}
for i in range(0, n):
result[i] = reverse_number(i * i)
... |
import os
print(os.getcwd())
command = "cd"
filename = "abc.txt"
dir_name = "abc"
parent_dir = os.getcwd()
if command == "mkdir":
path = os.path.join(parent_dir, dir_name)
try:
os.mkdir(path)
print("created: " + path)
except FileExistsError:
print("path already exists:... |
def findRepitition(input):
"""
If repetition found, returns the starting and ending index of the repeated values
:return:
"""
prev = None
count = 0
start = -1
end = -1
for i, x in enumerate(input):
if x == prev:
count += 1
else:
if count > 2... |
"""Given an array of integers, return a new array such that each element at index i of the new array
is the product of all the numbers in the original array except the one at i.
For example, if our input was [1, 2, 3, 4, 5], the expected output would be [120, 60, 40, 30, 24].
If our input was [3, 2, 1], ... |
from math import gcd
import random
def isPrime(x):
return 2 in [x,2**x%x]
def coprime(a, b):
return gcd(a, b) == 1
def modinv(e, phi):
d_old = 0; r_old = phi
d_new = 1; r_new = e
while r_new > 0:
a = r_old // r_new
(d_old, d_new) = (d_new, d_old - a * d_new)
(r_ol... |
import pandas as pd
def BoroClean(y):
cleandata = pd.read_csv("cleanliness.csv",usecols = ['Month', 'Borough', 'Acceptable Streets %', 'Acceptable Sidewalks %'])
cleandata = cleandata.rename(columns = {'Acceptable Streets %': 'clean%','Borough':'boro'})
cleandata['boro']=cleandata['boro'].str.upper()... |
import pandas as pd
def BoroAge():
popdata = pd.read_csv("age.csv", usecols = ['Borough','Age','2010','2015'])
popdata = popdata.rename(columns = {'Borough':'boro'})
popdata['boro'] = popdata['boro'].str.upper()
popdata = popdata[~popdata['boro'].isin(['NYC TOTAL'])]
popdata = popdata[~popdata['Age... |
from turtle import Turtle
ALIGNMENT="center"
FONT=("Courier", 18, "normal")
class Scoreboard(Turtle):
def __init__(self):
super().__init__()
self.score=0
self.goto(0,270)
self.hideturtle()
self.color("white")
self.write(f"Score: {self.score}",ali... |
from sklearn.neighbors import KNeighborsClassifier
import numpy as np
from . import AbstractLearner
class KNNLearner(AbstractLearner):
def __init__(self):
self.knn_classifier = KNeighborsClassifier(n_neighbors=10)
def classifier(self):
return self.knn_classifier
def tune(s... |
import sqlite3
books_file = 'books.txt'
def create_book_table():
connection = sqlite3.connect('data.db')
cursor = connection.cursor()
cursor.execute('CREATE TABLE IF NOT EXISTS books(name text primary key, author text, read integer)')
connection.commit()
connection.close()
de... |
raise Exception
print("I raised an exception!")
raise Exception('I raised an exception!')
try:
print(a)
except NameError:
print("oops name error")
except:
print("oops")
finally:
print("Yes! I did it!")
for i in range(1,10):
if i==5:
print("I found five!")
continue
print("Here is five!")
else:
pr... |
import os
import csv
csvpath = os.path.join("Resources","Election_Data.csv")
Vote_Totals = 0
List_of_Candidates = []
List_of_Votes_Counted = []
Data_File_List = ["Resources/Election_Data.csv"]
for file in Data_File_List:
print(csvpath)
with open(csvpath, newline = '') as csvfile:
csvfile.... |
"""
This module takes a data input as a csv file, and converts it to
a sqlite3 dbfile.
"""
import pandas as pd
import sqlite3
import sys
import re
import os
def convert_csv(path, dbfile):
"""
Path is entered as a command-line argument.
"""
conn = sqlite3.connect(dbfile)
... |
'''
正则使用方法:
-match:从开始位置开始查找,一次匹配
-search:从任何位置查找,一次匹配
-finall:把符合条件的全部查找出来
'''
import re
s = r'([a-z]+)([a-z]+)'
pattern = re.compile(s,re.I)
m = pattern.match("hello world wide web")
all =pattern.findall("hello world wide web")
print(all)
print(type(all))
for i in all:
print(i)
s = m.group(0)
print(s)
... |
from collections import Iterable
from collections import Iterator
ll =[1,2,3,4,5]
print(isinstance(ll,Iterable))
print(isinstance(ll,Iterator))
l = [x*x for x in range(5)]
g = (x*x for x in range(5))
print(type(l))
print(type(g)) |
import mysql.connector
db = mysql.connector.connect(user='root', password='',host='127.0.0.1',database='quiz')
cursor = db.cursor()
try:
print('\n\t\t~:LOGIN PAGE:~')
New=input("\n\t\t ARE YOU NEW USER??? <<<(Type Y/N)>>>")
if New =='Y' or New=='y':
import SIGNUP
if New =='N' or N... |
import random
class Deck:
id = 0
deck_list = []
def __init__(self):
ranks = list("A23456789TJQK")
ranks[ranks.index("T")] = "10"
suits = list("HSCD")
self.cards = []
for i in suits:
for j in ranks:
self.cards.append(j + i)
self.... |
import numpy as np
import math
import random
import pandas as pd
import matplotlib.pyplot as plt
def generating_points_on_perimeter_circle():
k=random.choices([1,0,2])[0]
if k==1:
x=random.uniform(-1,1)
y =math.sqrt(1-(x**2))
elif k==0:
y=random.uniform(-1,1)
x =math.sqrt(1... |
def julian_date(day, month, year, hour, minute, second):
'''(int, int, int, int, int, int) -> float
Returns the Julian Date (as used in astronomy), given a Gregorian date and time. If given an invalid date/time, returns None. In the NASA calculations this is known as the JDUT.'''
a = (14 - month)//12
y ... |
import sys
def sort(array):
length = len(array)
for i in range(0, length - 1):
for j in range(0, length - 1):
if array[j] > array[ j + 1 ]:
tag = array[j]
array[j] = array[j + 1]
array[j + 1] = tag
def main():
grades = [85, 90, 65, 70, 9... |
sentence_list = str(input('please enter a sentence: ')).split(' ')
def generate_histogram(sentence):
word_hist_dict = {}
for word in sentence_list:
try:
word_hist_dict[word]
except:
word_hist_dict[word] = 0
finally:
word_hist_dict[word] += 1
retu... |
from sklearn.datasets import load_iris
iris_dataset = load_iris()
'''
The data itself is contained in the target and data fields. data contains the numeric measurements of sepal length, sepal width, petal length, and petal width in a NumPy array
'''
print("dir on iris_dataset: \n{}".format(dir(iris_dataset)))
print("... |
def greet_with(name,location):
print(f"Hello {name}")
print(f"what is it like in {location}")
greet_with('yuvraj','mumbai')
greet_with(location='mumbai',name='yuvraj') |
import math
def distance(x1, y1, x2, y2):
u = (x2-x1)**2
v = (y2-y1)**2
return math.sqrt(u+v)
def circleArea(radius):
return math.pi * radius**2
def printCircleArea(radius):
print(math.pi * radius**2)
if __name__=='__main__':
a = circleArea(10)
b = distance(0, 0, 3, 4)
printCircleAre... |
import heapq
def kth_largest(numbers, k):
"""
See https://leetcode.com/problems/kth-largest-element-in-an-array/
>>> kth_largest([3, 2, 1, 5, 6, 4], 2)
5
>>> kth_largest([3, 2, 3, 1, 2, 4, 5, 5, 6], 4)
4
>>> kth_largest([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 2)
9
>>> kth_largest([10, 9, ... |
def main(text: str) -> bool:
"""
Implement a function which will check if it is possible to build a valid
palindrome from a sequence of letters. Only permutations are allowed.
>>> main("anna")
True
>>> main("nana")
True
>>> main("nanam")
True
>>> main("dogo")
False... |
"""
https://www.codewars.com/kata/love-vs-friendship/train/python
"""
import string
def words_to_marks(word):
alphabet = {
char: i
for i, char in enumerate(string.ascii_lowercase, start=1)
}
values = [alphabet[letter] for letter in word if letter in alphabet]
return sum(values)
|
import numpy as np
import matplotlib.pyplot as plt
def f(x):
return np.exp(-x ** 2)
x = np.linspace(-1, 3, 100)
plt.plot(x, f(x), color='red', linestyle='', marker='o')
plt.plot(x, 1 - f(x), c='g', ls='--')
plt.show() |
import numpy as np
import pandas as pd
df = pd.DataFrame(np.random.randn(3,4), index=['2','4','8'], columns=list('ABCD'))
print(df)
print(df.T) |
def sumatorio_tope(tope):
"""
Va sumando números naturales hasta llegar al tope.
Ejemplos
--------
>>> sumatorio_tope(9)
6
# 1 + 2 + 3
>>> sumatorio_tope(10)
10 # 1 + 2 + 3 + 4
>>> sumatorio_tope(12)
10 # 1 + 2 + 3 + 4
>>> sumatorio_tope(16)
1... |
class Item:
pass
class Box:
pass
class ListBox(Box):
pass
class DictBox(Box):
pass
i1 = Item("Item 1", 1)
i2 = Item("Item 2", 2)
i3 = Item("Item 3", 3)
listbox = ListBox()
dictbox = DictBox()
listbox.add(i1, i2, i3)
dictbox.add(i1)
dictbox.add(i2)
dictbox.add(i3)
assert(listb... |
class Shape:
pass
class Rectangle(Shape):
pass
newRectangle = Rectangle(12, 10)
print(newRectangle.area)
print(newRectangle.perimeter)
newRectangle.width = 5
newRectangle.height = 8
print(newRectangle.area)
print(newRectangle.perimeter)
newRectangle.width = -10
|
class Item:
def __init__(self, name, value):
self.name = name
self.value = value
def __str__(self):
return "{} => {}".format(self.name, self.value)
class Box:
def add(self, *items):
raise NotImplementedError()
def empty(self):
raise NotImplementedError()
d... |
import multiprocessing
def worker(num):
return num*2
nums = [1,2,3,4,5,6,7,8,9]
values = None
assert(values == [2, 4, 6, 8, 10, 12, 14, 16, 18])
print(values) |
class Point:
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
def __eq__(self, other):
return (epsilon_eq(self.x, other.x)
and epsilon_eq(self.y, other.y)
and epsilon_eq(self.z, other.z))
class Vector:
def __init__(self, x, y, z):
self.x = x
... |
from typing import Dict
import re
from molecular.monitoring.log import get_logger
logger = get_logger()
class MoleculeParser:
"""
This class allows to parse molecules, and get the number of atoms that compose it.
It is mainly string operations.
See documentation used : https://docs.python.org/3/lib... |
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def how_far_from(self, point):
if self.x == point.x:
return 0
higher_point, lower_point = (self, point) if self.y > point.y else (point, self)
distance = ((higher_point.x - lower_point.x) ** 2 + (higher_point.y - lower_point.y) ** 2) ... |
import random
def aiChoice():
x = random.randint(0,2)
if x == 0:
choice = "rock"
if x == 1:
choice = "paper"
if x == 2:
choice = "scissors"
return choice
def gameLoop(choice):
playerChoice = input("Choose Rock, Paper or Scissors ")
playerChoice = playerChoice.lo... |
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(0,10)
y1 = 0.08*x**2
y2 = 0.03*x**2
plt.fill_between(x,y1,y2, 'r-')
plt.plot(x,y1, 'r-')
plt.plot(x,y2, 'b-')
plt.show() |
symbols = '~!@#$%^&*()_=-/,.?<>;:[]{}\|'
number = '123456789'
character = 'abcdefghijklmnopqrstuvwxyz'
password = input('請輸要入要設置的密碼 : ')
def check_len(passwoard) :
if 0<len(password) <= 8 :
return 0
elif 8<len(password)<=16 :
return 1
else :
return 2
def char(password)... |
import os
import csv
budget_csv = os.path.join('..', 'PyBank', 'Resources', 'budget_data.csv')
with open(budget_csv) as csvfile:
csvreader = csv.reader(csvfile, delimiter= ",")
csv_header = next(csvreader)
total = 0
total_months = 0
total_change = 0
datelist = []
pl_list = []
f... |
"""Tweets out a random city name + the phrase."""
import csv
import twitter
import os
import random
import time
numRows = 15633
cities = []
with open('cities.csv', 'rt') as csvfile:
reader = csv.reader(csvfile, delimiter=',')
for row in reader:
cities.append(row[0])
consumer_key = os.environ['CONSU... |
def rotated_substr(word, rotat):
if len(word) != len(rotat):
return False
rotat_conc = rotat + rotat
return word in rotat_conc
if __name__ == "__main__":
print(rotated_substr("thisis", "isthis"))
print(rotated_substr("hihiho", "hihole")) |
from linked_list import LinkedList
class ExtLinkedList(LinkedList):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def remove_dup(self):
curr = self.head
if not (curr and curr.next): return
prev = None
elems = set()
while curr:
... |
username = input("用户名")
password = input("密码")
while (username !="zz" or password != "123"):
username = input("用户名")
password = input("密码") |
persons = [
{"name": "zhangsan", "age": 18, "gender": "female"},
{"name": "lisi", "age": 20, "gender": "male"},
{"name": "jack", "age": 30, "gender": "unknow"},
{"name": "kevin", "age": 29, "gender": "female"}
]
new_person = [person for person in persons if person['gender'] != "unknow"... |
list1 = [10, 20, 4, 45, 99]
mx = max(list1[0], list1[1])
secondmax = min(list1[0], list1[1])
n = len(list1)
for i in range(2, n):
if list1[i] > mx:
secondmax = mx
mx = list1[i]
elif list1[i] > secondmax and \
mx != list1[i]:
secondmax = list1[i]
print("Second h... |
from collections import Counter
import nltk
from nltk.corpus import stopwords
def text_to_word_count(text):
text = text.lower()
words = nltk.word_tokenize(text)
words = filter_stop_words(words)
return dict(Counter(words).most_common())
def filter_stop_words(words):
stop_words = set(stopwor... |
def bagdiff(xs, ys):
""" bagdiff for the first list."""
result = []
xi = 0
yi = 0
while True:
if xi >= len(xs):
return result
if yi >= len(ys):
result.extend(xs[xi:])
return result
if xs[xi] < ys[yi]:
result.... |
class Point():
def __init__(self, x, y):
self.x = x
self.y = y
def get_line_to(self, other_point):
slope = (other_point.y-self.y)/(other_point.x-self.x)
linear_coef = self.y - slope*self.x
return (slope, linear_coef)
print(Point(4, 11).get_line_to(Point(6, 15))) |
from threading import Thread, Lock
import time
import random
shared_item = 0
itens_done = 0
available = False
class Producer(Thread):
global shared_item
global available
def __init__(self, lock):
Thread.__init__(self)
self.lock = lock
self.produced = False
def run(self):
... |
import turtle
def star(t):
for i in range(5):
t.forward(100)
t.right(144)
wn = turtle.Screen()
wn.bgcolor('lightgreen')
pen = turtle.Pen()
pen.color('purple')
for i in range(5):
star(pen)
pen.forward(100)
pen.penup()
pen.forward(350)
pen.pendown()
pen.right(144)
wn.mainlo... |
"""
Created on Fri Nov 23 14:49:13 2018
@author: aliao
"""
class Employee():
def __init__(self, first_name, last_name, salary):
self.first_name = first_name
self.last_name = last_name
self.salary = salary
def give_raise(self, boost=5000):
self.boost = boost
s... |
"""
Starter code for exploring the Enron dataset (emails + finances);
loads up the dataset (pickled dict of dicts).
The dataset has the form:
enron_data["LASTNAME FIRSTNAME MIDDLEINITIAL"] = { features_dict }
{features_dict} is a dictionary of features associated with that person.
You shoul... |
"""
This is the code to accompany the Lesson 2 (SVM) mini-project.
Use a SVM to identify emails from the Enron corpus by their authors:
Sara has label 0
Chris has label 1
J.A. Korten Sept 2018
See: http://scikit-learn.org/stable/modules/svm.html
Excercise 3.47
There are over 1... |
import numpy
import sys
def featureScaling(arr):
minF = 0
maxF = 0
feature = 0
if len(arr) == 3:
minF = min(arr)
maxF = max(arr)
for item in arr:
if (item != minF) and (item != maxF):
feature = item
rescaledFeature = (feature - minF) / (maxF... |
import math
import unittest
from collections import defaultdict
class Agreement:
"""
Class for computing inter-rater reliability
"""
def __init__(self, rater_responses):
"""
Arguments:
rater_responses -- a list of maps of item labels. ex. [{'item1':1, 'item2':5}, {'item1':2}]... |
class Trajectory:
def __init__(self, start):
"""
trajectory object is a collection of connections
"""
self.start = start
self.end = start
self.connections = []
self.itinerary = [start.name]
self.total_time = 0
self.score = 0
... |
"""
递归动态规划
"""
class Solution(object):
def canJump(self,nums):
if len(nums) == 1:
return True
for i in range(1,nums[0]+1):
if i <= len(nums):
if self.canJump(nums[i:]):
return True
else:
return True
retur... |
"""
Given two strings s1 and s2, write a function to return true if s2 contains the permutation of s1. In other words, one of the first string's permutations is the substring of the second string.
Example1:
Input: s1 = "ab" s2 = "eidbaooo"
Output: True
Explanation: s2 contains one permutation of s1 ("ba").
... |
print("Konversi jam ke detik")
jam = int(input("Masukan Jam : "))
menit = int(input("Masukan Menit : "))
detik = int(input("Masukan Detik : "))
total_detik = ((jam * 3600) + (menit * 60) + detik)
print(str(jam) + ":" + str(menit) + ":" + str(detik) + " Sama dengan " +
str(total_detik) + " detik")
|
import csv
class Customer:
def __init__(self, first_name, family_name, age):
self.first_name = first_name
self.family_name = family_name
self.age = age
def full_name(self):
return f"{self.first_name} {self.family_name}"
def age(self):
return self.age
def entry_... |
a = '1'
b = ''
for i in range(0, 30):
j = 0
k = 0
while j < len(a):
while k < len(a) and a[k] == a[j]: k += 1
b += str(k - j) + a[j]
j = k
print(b)
a = b
b = ''
print(len(a))
import re
... |
import numpy as np
from sklearn.neighbors import NearestNeighbors
from scipy.spatial import distance
def NLC(X_train, y_train, query_vec, k):
centroidDists = []; n_classes = len(set(y_train))
for j in range(n_classes):
classSubset = X_train[y_train == j,:]
neighbors = NearestNeig... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.