text
stringlengths 37
1.41M
|
---|
from linkedlist import LinkedList
class Solution():
def __init__(self):
pass
def merge_k_list(self, array):
"""
Merge k sorted linked list into one sorted list
"""
merged_list = []
# get the first min head
min_index = self.get_min(array)
node = array[min_index]
# assign it as new head of new linkedlist
new_head = node
while True:
min_index = self.get_min(array)
# if min index is none then we have merged all nodes
if min_index is None:
break
# get that node
curr_node = array[min_index]
merged_list.append(curr_node.data)
# update the head for this min head
array[min_index] = curr_node.next
# new head of merged long linked list
return new_head, merged_list
def get_min(self, array):
"""
Find the minimum item in the array and return the index
Array contains list of head of each linked list
"""
# check if all linked list has been merged
merged = False
for head in array:
if head is not None:
merged = True
break
# if merged we return none and know there is no head in the array
if merged:
return None
# else find the current min head
min_head = array[0]
index = 0
for i, node in enumerate(array):
# make sure that list is not None
if node is not None:
if node.data < min_head:
# update the min head
min_head = node.data
index = i
return index
obj = Solution()
number = [2, 3, 1, 9, 10]
min_head = obj.get_min(number)
print(f"Min number: {min_head}") |
def length_of_last_word(text):
"""
Given a string s consists of upper/lower-case alphabets and empty space
characters ' ', return the length of last word in the string.
NOTE: Please make sure you try to solve this problem without using library
functions. Make sure you only traverse the string once.If there is one word
it is the last word.
Args:
text (str): long string consisted of word(s)
Return:
length (int): length of the last word in the string
"""
# counter for the last word in the string
length = 0
last_word = ""
# start iterating the string at the end of it
for i in range(len(text)-1, -1, -1):
char = text[i]
if char.isalpha() and i == 0:
length = 0
elif char.isalpha():
last_word += char
length += 1
# stop the loop if we there is space, because it means
# we count the length of the last word already
elif char.isspace():
break
# print(last_word[::-1])
return length
text = "world"
print(length_of_last_word(text))
|
"""
question from repl.it
https: // repl.it/student/submissions/7695405
"""
def is_prime(n):
"""Determine if input number is prime number
Args:
n(int): input number
Return:
true or false(bool):
"""
for curr_num in range(2, n):
# if input is evenly divisible by the current number
if n % curr_num == 0:
# print("current num:", curr_num)
return False
return True
def count_primes(n):
"""Counts number of prime numbers less than a non-negative number, n"""
count = 0
for curr_num in range(2, n):
# check if current number is prime
if is_prime(curr_num):
print(curr_num)
count += 1
return count
n = 2
m = 10
print("is prime:", is_prime(m))
print("num of primes:", count_primes(m))
|
class Node():
"""
Helper Node class for linkedlist
"""
def __init__(self, data):
"""Initialize the node with given data"""
self.data = data
self.next = None
def __repr__(self):
"""String representation of this node"""
return "Node({!r})".format(self.data)
class LinkedList():
def __init__(self, iterable=None):
"""
Initialize the linked list with iterable
"""
self.head = None
self.tail = None
self.size = 0
# append given items
if iterable is not None:
for item in iterable:
self.append(item)
def __str__(self):
"""Return a formatted string representation of this linked list."""
items = ['({!r})'.format(item) for item in self.items()]
return '[{}]'.format(' -> '.join(items))
def __repr__(self):
"""Return a string representation of this linked list."""
return 'LinkedList({!r})'.format(self.items())
def items(self):
"""Return a list of all items in this linked list.
Best and worst case running time: Theta(n) for n items in the list
because we always need to loop through all n nodes."""
# Create an empty list of results
result = [] # Constant time to create a new list
# Start at the head node
node = self.head # Constant time to assign a variable reference
# Loop until the node is None, which is one node too far past the tail
while node is not None: # Always n iterations because no early exit
# Append this node's data to the results list
result.append(node.data) # Constant time to append to a list
# Skip to the next node
node = node.next # Constant time to reassign a variable
# Now result contains the data from all nodes
return result # Constant time to return a list
def append(self, item):
"""
Append the item at the tail of the Linked list
"""
# create a new node
new_node = Node(item)
# if linked list is empty
if self.is_empty():
self.head = new_node
else:
self.tail.next = new_node
# update the tail regardless
self.tail = new_node
self.size += 1
def prepend(self, item):
"""
Insert the given item at the head of this linked list.
Best case running time: O(1) if .tail property is used to access
the last node. The current implementation performs O(1) time complexity
"""
# create a new node
new_node = Node(item)
# if LL is empty
if self.is_empty():
# Assign tail to new node
self.tail = new_node
else:
new_node.next = self.head
# change the head to new node
self.head = new_node
self.size += 1
def length(self):
"""Length of this linked list"""
return self.size
def is_empty(self):
"""Returns true if linked list is empty"""
return self.head is None
def get_at_index(self, index):
"""Get the item at given index"""
if not (0 <= index < self.size):
raise ValueError('List index out of range: {}'.format(index))
curr = self.head
for _ in range(index):
curr = curr.next
return curr.data
def pop_head(self):
"""Pop the head and return that node"""
# if LL is not empty
if not self.is_empty():
# get the current head
curr_head = self.head
# reassign the new head
self.head = self.head.next
return curr_head
# if linked list is empty
return None
def reverse_linkedlist(self, node):
"""Reverse the given linked list and return head"""
pass
def test_linked_list():
ll = LinkedList()
print(ll)
print('Appending items:')
ll.append('A')
print(ll)
ll.append('B')
print(ll)
ll.append('C')
print(ll)
print('head: {}'.format(ll.head))
print('tail: {}'.format(ll.tail))
print('size: {}'.format(ll.size))
print('length: {}'.format(ll.length()))
# print('Getting items by index:')
# for index in range(ll.size):
# item = ll.get_at_index(index)
# print('get_at_index({}): {!r}'.format(index, item))
print("Popping head node:")
ll.pop_head()
print(ll)
# print('Deleting items:')
# ll.delete('B')
# print(ll)
# ll.delete('C')
# print(ll)
# ll.delete('A')
# print(ll)
# print('head: {}'.format(ll.head))
# print('tail: {}'.format(ll.tail))
# print('size: {}'.format(ll.size))
# print('length: {}'.format(ll.length()))
if __name__ == '__main__':
test_linked_list()
|
import math
class Complex(object):
def __init__(self, real, imaginary):
self.real = real
self.imaginary = imaginary
def __add__(self, no):
# (a+ib)+(c+id)=(a+c)+i(b+d)
real = self.real + no.real
imaginary = self.imaginary + no.imaginary
return Complex(real, imaginary)
def __sub__(self, no):
# enter your code here
# (a+ib)-(c+id)=(a-c)+i(b-d)
real = self.real - no.real
imaginary = self.imaginary - no.imaginary
return Complex(real, imaginary)
def __mul__(self, no):
# enter code here
# (a+ib)*(c+id)=(ac-bd)+i(ad+bc)
real = (self.real*no.real - self.imaginary*no.imaginary)
imaginary = (self.real*no.imaginary + self.imaginary*no.real)
return Complex(real, imaginary)
def __div__(self, no):
# enter code here
# (a+ib)/(c+id)=((ac+bd)+i(bc-ad))/(c^2+d^2)
c_sqrd = no.real*no.real
d_sqrd = no.imaginary*no.imaginary
denominator = c_sqrd + d_sqrd
real = (self.real*no.real + self.imaginary*no.imaginary) / (denominator)
imaginary = (self.imaginary*no.real - self.real*no.imaginary) / (denominator)
return Complex(real, imaginary)
def mod(self):
# enter your code here
# mod of a+ib is equal to sq rt of a sq + b sq
real = math.sqrt( self.real*self.real + self.imaginary*self.imaginary )
#real = math.sqrt( ( self.real*self.real + self.imaginary*self.imaginary )
return Complex(real, 0)
def __str__(self):
# enter code here
real = "%.2f" % self.real
imaginary = "%.2f" % self.imaginary
if (self.imaginary) >= 0:
result = (str(real) + '+' + str(imaginary) + 'i' )
else:
result = (str(real) + '' + str(imaginary) + 'i' )
return result
# main method
def main():
if __name__ == '__main__':
main()
C = map(float, input().split())
D = map(float, input().split())
x = Complex(*C)
y = Complex(*D)
print('\n'.join(map(str, [x.__add__(y), x.__sub__(y), x.__mul__(y), x.__div__(y), x.mod(), y.mod()]))
#if __name__ == '__main__':
#main()
|
class Extract_Date:
def __init__(self):
from datetime import datetime
import re
self.datetime = datetime
self.file_date = re.compile(u'(/[0-9]{8}/)')
def date_from_file(self, file_name):
df = self.file_date.search(file_name)
if not df:
return self.datetime.fromordinal(1)
df = df.group()[1:5] + '-' + df.group()[5:7] + '-' + df.group()[7:9] + ' 00:00:00'
df = self.datetime.strptime(df, '%Y-%m-%d %H:%M:%S')
return df |
def backprop(W, A, Z, y):
"""
INPUT:
W weights (cell array)
A output of forward pass (cell array)
Z output of forward pass (cell array)
y vector of size n (each entry is a label)
OUTPUTS:
gradient = the gradient with respect to W as a cell array of matrices
"""
# Convert delta to a row vector to make things easier
delta = (MSE_grad(Z[-1].flatten(), y) * 1).reshape(-1, 1)
# compute gradient with backprop
gradients = []
# YOUR CODE HERE
for i in range(len(W)-1, -1, -1):
gradients.append((Z[i].T) @ (delta))
delta = ReLU_grad(A[i]) * (delta@(W[i].T))
gradients = gradients[::-1]
return gradients
def backprop_test1():
X, y = generate_data() # generate data
n, _ = X.shape
W = initweights([2, 3, 1]) # generate random weights
A, Z = forward_pass(W, X)
gradient = backprop(W, A, Z, y) # backprop to calculate the gradient
# You should return a list with the same len as W
return len(gradient) == len(W)
def backprop_test2():
X, y = generate_data() # generate data
n, _ = X.shape
W = initweights([2, 3, 1]) # generate random weights
A, Z = forward_pass(W, X)
gradient = backprop(W, A, Z, y) # backprop to calculate the gradient
# gradient[i] should match the shape of W[i]
return np.all([gradient[i].shape == W[i].shape for i in range(len(W))])
def backprop_test3():
X, y = generate_data() # generate data
n, _ = X.shape
# Use a one layer network
# This is essentially the least squares
W = initweights([2, 1])
A, Z = forward_pass(W, X)
# backprop to calculate the gradient
gradient = backprop(W, A, Z, y)
# calculate the least square gradient
least_square_gradient = 2 *((X.T @ X) @ W[0] - X.T @ y.reshape(-1, 1)) / n
# gradient[0] should be the least square gradient
return np.linalg.norm(gradient[0] - least_square_gradient) < 1e-7
def backprop_test4():
X, y = generate_data() # generate data
n, _ = X.shape
# Use a one layer network
# This is essentially the least squares
W = initweights([2, 5, 5, 1])
A, Z = forward_pass(W, X)
# backprop to calculate the gradient
gradient = backprop(W, A, Z, y)
# calculate the backprop gradient
gradient_grader = backprop_grader(W, A, Z, y)
# Check whether your gradient matches ours
OK=[len(gradient_grader)==len(gradient)] # check if length matches
for (g,gg) in zip(gradient_grader,gradient): # check if each component matches in shape and values
OK.append(gg.shape==g.shape and (np.linalg.norm(g - gg) < 1e-7))
return(all(OK))
def backprop_test5():
# Here we reverse your gradient output and check that reverse with ours. It shouldn't match.
# If your reverse gradient matches our gradient, this means you outputted the gradient in reverse order.
# This is a common mistake, as the loop is backwards.
X, y = generate_data() # generate data
n, _ = X.shape
# Use a one layer network
# This is essentially the least squares
W = initweights([2, 5, 5, 1])
A, Z = forward_pass(W, X)
# backprop to calculate the gradient
gradient = backprop(W, A, Z, y)
# calculate the backprop gradient
gradient_grader = backprop_grader(W, A, Z, y)
gradient.reverse() # reverse the gradient. From now on it should NOT match
# Check whether your gradient matches ours
OK=[] # check if length matches
for (g,gg) in zip(gradient_grader,gradient): # check if each component matches
OK.append(gg.shape==g.shape and (np.linalg.norm(g - gg) < 1e-7))
return(not all(OK))
runtest(backprop_test1, 'backprop_test1')
runtest(backprop_test2, 'backprop_test2')
runtest(backprop_test3, 'backprop_test3')
runtest(backprop_test4, 'backprop_test4')
runtest(backprop_test5, 'backprop_test5')
|
def MSE(out, y):
"""
INPUT:
out: output of network (n vector)
y: training labels (n vector)
OUTPUTS:
loss: the mse loss (a scalar)
"""
n = len(y)
loss = 0
# YOUR CODE HERE
loss = np.mean((out - y) ** 2)
return loss
def MSE_test1():
X, y = generate_data() # generate data
W = initweights([2, 3, 1]) # generate random weights
A, Z = forward_pass(W, X)
loss = MSE(Z[-1].flatten(), y) # calculate loss
return np.isscalar(loss) # your loss should be a scalar
def MSE_test2():
X, y = generate_data() # generate data
W = initweights([2, 3, 1]) # generate random weights
A, Z = forward_pass(W, X)
loss = MSE(Z[-1].flatten(), y) # calculate loss
return loss >= 0 # your loss should be nonnegative
def MSE_test3():
X, y = generate_data() # generate data
W = initweights([2, 3, 1]) # generate random weights
A, Z = forward_pass(W, X)
loss = MSE(Z[-1].flatten(), y) # calculate loss
loss_grader = MSE_grader(Z[-1].flatten(), y)
# your loss should not deviate too much from ours
# If you fail this test case, check whether you divide your loss by 1/n
return np.absolute(loss - loss_grader) < 1e-7
runtest(MSE_test1, "MSE_test1")
runtest(MSE_test2, "MSE_test2")
runtest(MSE_test3, "MSE_test3")
|
def gradient(X, y, w, b):
# Input:
# X: nxd matrix
# y: n-dimensional vector with labels (+1 or -1)
# w: d-dimensional vector
# b: a scalar bias term
# Output:
# wgrad: d-dimensional vector with gradient
# bgrad: a scalar with gradient
n, d = X.shape
wgrad = np.zeros(d)
bgrad = 0.0
# YOUR CODE HERE
div = (-y*sigmoid(-y*(X@w + b)))
wgrad = np.dot(X.T, div)
bgrad = np.sum(div)
return wgrad, bgrad
def test_grad1():
X = np.random.rand(25,5) # generate n random vectors with d dimensions
w = np.random.rand(5) # define a random weight vector
b = np.random.rand(1) # define a bias
y = (np.random.rand(25)>0.5)*2-1 # set labels all-(+1)
wgrad, bgrad = gradient(X, y, w, b) # compute the gradient using your function
return wgrad.shape == w.shape and np.isscalar(bgrad)
def test_grad2():
X = np.random.rand(25,5) # generate n random vectors with d dimensions
w = np.random.rand(5) # define a random weight vector
b = np.random.rand(1) # define a bias
y = (np.random.rand(25)>0.5)*2-1 # set labels all-(+1)
wgrad, bgrad = gradient(X, y, w, b) # compute the gradient using your function
wgrad2, bgrad2 = gradient_grader(X, y, w, b) # compute the gradient using ground truth
return np.linalg.norm(wgrad - wgrad2)<1e-06 and np.linalg.norm(bgrad - bgrad2) < 1e-06 # test if they match
def test_grad3():
X = np.random.rand(25,5) # generate n random vectors with d dimensions
y = (np.random.rand(25)>0.5)*2-1 # set labels all-(+1)
w = np.random.rand(5) # define a random weight vector
b = np.random.rand(1)
w_s = np.random.rand(5)*1e-05 # define tiny random step
b_s = np.random.rand(1)*1e-05 # define tiny random step
ll1 = log_loss(X,y,w+w_s, b+b_s) # compute log-likelihood after taking a step
ll = log_loss(X,y,w,b) # use Taylor's expansion to approximate new loss with gradient
wgrad, bgrad =gradient(X,y,w,b) # compute gradient
ll2=ll+ wgrad @ w_s + bgrad * b_s # take linear step with Taylor's approximation
return np.linalg.norm(ll1-ll2)<1e-05 # test if they match
def test_grad4():
w1, b1, losses1 = logistic_regression_grader(features, labels, 1000, 1e-03, gradient)
w2, b2, losses2 = logistic_regression_grader(features, labels, 1000, 1e-03)
return(np.abs(losses1[-1]-losses2[-1])<0.1)
runtest(test_grad1, 'test_grad1')
runtest(test_grad2, 'test_grad2')
runtest(test_grad3, 'test_grad3')
runtest(test_grad4, 'test_grad4')
|
# import PyTorch and its subpackages
import torch
import torch.nn as nn
from torch.nn import functional as F
# Also other packages for convenience
import numpy as np
import helper as h
import matplotlib.pyplot as plt
X = torch.zeros(3, 2) # this syntax is similar to NumPy. In Numpy, we would do np.zero(3,2)
print(X)
print(X.shape)
X_numpy = np.arange(15)
print('NumPy Array: ', X_numpy)
X_tensor = torch.tensor(X_numpy)
print('Pytorch Tensor: ', X_tensor)
X_tensor_numpy = X_tensor.numpy()
print(X_tensor_numpy)
print(type(X_tensor_numpy))
# Create two numpy arrays
A = np.array([1, 2, 3])
B = np.array([1, 5, 6])
# Convert the two numpy arrays into torch Tensor
A_tensor = torch.Tensor(A)
B_tensor = torch.Tensor(B)
# addition / subtraction
print('Addition in Numpy', A + B)
print('Addition in PyTorch', A_tensor + B_tensor)
print()
# scalar multiplication
print('Scalar Multiplication in Numpy', 3*A)
print('Scalar Multiplication in PyTorch', 3*A_tensor)
print()
# elementwise multiplication
print('Elementwise Multiplication in Numpy', A*B)
print('Elementiwse Multiplication in PyTorch', A_tensor*B_tensor)
print()
# matrix multiplication
# this is slightly different from NumPy
print('Elementwise Multiplication in Numpy', A@B)
print('Elementiwse Multiplication in PyTorch', torch.matmul(A_tensor, B_tensor))
print()
# Elementwise comparison
print('NumPy: ', A == B)
print('PyTorch: ', A_tensor == B_tensor)
print()
# Generate a random matrix
C = np.array([[10, 9, 8], [6, 7, 5], [1, 2, 3]])
C_tensor = torch.Tensor(C)
print('C', C)
print()
# Sum along the row
# In NumPy, we specify the axis.
# In PyTorch, we specify the dim
print('NumPy: ', np.sum(C, axis=0))
print('PyTorch: ' ,torch.sum(C_tensor, dim=0))
print()
# Find the mean along the column
# In NumPy, we specify the axis.
# In PyTorch, we specify the dim
print('NumPy: ', np.mean(C, axis=1))
print('PyTorch: ', torch.mean(C_tensor, dim=1))
print()
# Find the argmax along the column
# In NumPy, we specify the axis.
# In PyTorch, we specify the dim
print('NumPy: ', np.argmax(C, axis=1))
print('PyTorch: ', torch.argmax(C_tensor, dim=1))
print()
|
def computeK(kerneltype, X, Z, kpar=1):
"""
function K = computeK(kernel_type, X, Z)
computes a matrix K such that Kij=k(x,z);
for three different function linear, rbf or polynomial.
Input:
kerneltype: either 'linear','polynomial','rbf'
X: n input vectors of dimension d (nxd);
Z: m input vectors of dimension d (mxd);
kpar: kernel parameter (inverse kernel width gamma in case of RBF, degree in case of polynomial)
OUTPUT:
K : nxm kernel matrix
"""
assert kerneltype in ["linear","polynomial","rbf"], "Kernel type %s not known." % kerneltype
assert X.shape[1] == Z.shape[1], "Input dimensions do not match"
K = None
# YOUR CODE HERE
if kerneltype == "linear":
K = X.dot(Z.T)
elif kerneltype == "polynomial":
K = np.power((X.dot(Z.T)+1), kpar)
elif kerneltype == "rbf":
K = np.exp(-kpar*np.square(l2distance(X,Z)))
else:
ValueError('Please enter valid kernel type')
return K
# These tests test whether your computeK() is implemented correctly
xTr_test, yTr_test = generate_data(100)
xTr_test2, yTr_test2 = generate_data(50)
n, d = xTr_test.shape
# Checks whether computeK compute the kernel matrix with the right dimension
def computeK_test1():
s1 = (computeK('rbf', xTr_test, xTr_test2, kpar=1).shape == (100, 50))
s2 = (computeK('polynomial', xTr_test, xTr_test2, kpar=1).shape == (100, 50))
s3 = (computeK('linear', xTr_test, xTr_test2, kpar=1).shape == (100, 50))
return (s1 and s2 and s3)
# Checks whether the kernel matrix is symmetric
def computeK_test2():
k_rbf = computeK('rbf', xTr_test, xTr_test, kpar=1)
s1 = np.allclose(k_rbf, k_rbf.T)
k_poly = computeK('polynomial', xTr_test, xTr_test, kpar=1)
s2 = np.allclose(k_poly, k_poly.T)
k_linear = computeK('linear', xTr_test, xTr_test, kpar=1)
s3 = np.allclose(k_linear, k_linear.T)
return (s1 and s2 and s3)
# Checks whether the kernel matrix is positive semi-definite
def computeK_test3():
k_rbf = computeK('rbf', xTr_test2, xTr_test2, kpar=1)
eigen_rbf = np.linalg.eigvals(k_rbf)
eigen_rbf[np.isclose(eigen_rbf, 0)] = 0
s1 = np.all(eigen_rbf >= 0)
k_poly = computeK('polynomial', xTr_test2, xTr_test2, kpar=1)
eigen_poly = np.linalg.eigvals(k_poly)
eigen_poly[np.isclose(eigen_poly, 0)] = 0
s2 = np.all(eigen_poly >= 0)
k_linear = computeK('linear', xTr_test2, xTr_test2, kpar=1)
eigen_linear = np.linalg.eigvals(k_linear)
eigen_linear[np.isclose(eigen_linear, 0)] = 0
s3 = np.all(eigen_linear >= 0)
return (s1 and s2 and s3)
# Checks whether computeK compute the right kernel matrix with rbf kernel
def computeK_test4():
k = computeK('rbf', xTr_test, xTr_test2, kpar=1)
k2 = computeK_grader('rbf', xTr_test, xTr_test2, kpar=1)
return np.linalg.norm(k - k2) < 1e-5
# Checks whether computeK compute the right kernel matrix with polynomial kernel
def computeK_test5():
k = computeK('polynomial', xTr_test, xTr_test2, kpar=1)
k2 = computeK_grader('polynomial', xTr_test, xTr_test2, kpar=1)
return np.linalg.norm(k - k2) < 1e-5
# Checks whether computeK compute the right kernel matrix with linear kernel
def computeK_test6():
k = computeK('linear', xTr_test, xTr_test2, kpar=1)
k2 = computeK_grader('linear', xTr_test, xTr_test2, kpar=1)
return np.linalg.norm(k - k2) < 1e-5
runtest(computeK_test1, 'computeK_test1')
runtest(computeK_test2, 'computeK_test2')
runtest(computeK_test3, 'computeK_test3')
runtest(computeK_test4, 'computeK_test4')
runtest(computeK_test5, 'computeK_test5')
runtest(computeK_test6, 'computeK_test6')
|
# how many digits are there in
# a number
import math
n = 123456
# method 1
print(len(str(n)))
# convert a number to a string
# and take its length
# method 2 (pure mathematical)
print(1 + math.floor(math.log10(n)))
# log - base 10
# Output:
# 6
# 6
|
# remove duplicates from a list
# and make sure the order is saved
data = [10,12,10,33,2,2,5,2]
result = []
values = set()
for i in data:
if i not in values:
values.add(i)
result.append(i)
print(result)
# Output:
# [10, 12, 33, 2, 5]
|
# using "filter" to select items
# bases on some condition
# here's the condition
def is_odd(x):
return x % 2
data = [1,2,3,4,5,6,7,8,9]
data = filter(is_odd,data)
# object of the "filter" type
data = list(data) # a list again
print(data)
# Output:
# [1, 3, 5, 7, 9]
|
# bubble sort
data = [4,7,1,4,8,9,3,2,5,6]
done = 0
while not done:
done = 1
for n in range(1,len(data)):
# scan left to right
if data[n-1] > data[n]:
# swap two adjacent items
data[n-1], data[n] = data[n],data[n-1]
done = 0 # continue
print(data)
# Output:
# [1, 2, 3, 4, 4, 5, 6, 7, 8, 9]
|
# what is the difference between
# the two given dates?
import datetime
date_from = datetime.date(2019,1,1)
date_to = datetime.date(2019,12,31)
diff = date_to - date_from
print(diff)
days = diff.days # diff in days
print(days)
# Output:
# 364 days, 0:00:00
# 364
|
# one of the simplest programs
# using "async" (python 3.5+)
import asyncio
# methods for working with async
# code
async def f():
# "async" function
print("Hello there!")
asyncio.run(f()) # you need () here
# Output:
# Hello there!
|
# remove newline characters from
# the strings in a list
data = ["alpha\n",
"beta\n",
"gamma\n"]
print(data)
data = list(map(lambda s : s.strip(),data))
# map return an object of the "map" type
print(data)
# Output:
# ['alpha\n', 'beta\n', 'gamma\n']
# ['alpha', 'beta', 'gamma']
|
# catching "Ctrl + C"
c = 0 # counter
try:
while 1: # infinite loop
c += 1
except KeyboardInterrupt:
print(f"The counter is {c} now")
# Input:
# ^C
# Output:
# The counter is 142662630 now
|
# add two numbers from
# command line
a = int(input())
b = int(input())
c = a + b
print(c)
# Input:
# 10
# 20
# Output:
# 30
|
# print the first prime numbers
# below 20
def is_prime(n):
for i in range(2,n):
if not(n % i):
# found divisor,
# thus is not prime
return False
return True # is prime
for n in range(1,20):
if is_prime(n):
print(n)
# Output:
# 1
# 2
# 3
# 5
# 7
# 11
# 13
# 17
# 19
|
# saving a data structure in a file
# in JSON
import json
data = {"alpha" : [3,5,7],
"beta" : [4,6,8]}
with open("code/Data/data.json","w") as f:
json.dump(data,f)
# ...
# using text format now
with open("code/Data/data.json","r") as f:
restored = json.load(f)
print(restored)
# Output:
# {'alpha': [3, 5, 7], 'beta': [4, 6, 8]}
|
# calling a method of the parent class
class Animal:
def talk(self):
print("I am an animal")
class Cat(Animal):
def talk(self):
print("I am a cat")
# also call Animal.talk:
super(Cat,self).talk()
# ^ child class
# ^ this object
# just remember this syntax :-)
cat = Cat()
cat.talk()
# Output:
# I am a cat
# I am an animal
|
import random
def BubbleSort(numlist):
lenlist = len(numlist)
# traverse through all elements in the list
for i in range(lenlist):
# last i elements are already in place
for j in range(0,lenlist-i-1):
# traverse through elements from 0 to lenlist - i - 1
# if element is greater than next element
# swap the element
if numlist[j] > numlist[j + 1]:
numlist[j] , numlist[j + 1] = numlist[j+1] , numlist[j]
print("\nSorted list : ",end="")
for i in range(lenlist):
print(numlist[i],end=" ")
if __name__ == "__main__":
# creating 10 random number upto the range of 100
randomlist = random.sample(range(100),10)
print("\nRandom list : ",end="")
for k in range(len(randomlist)):
print(randomlist[k],end=" ")
# calling BubbleSort() function with
# generated numbers
BubbleSort(randomlist)
|
# what happens when you return
# two values from a function
def f ():
return 10,11
a,b = f()
print(a)
print(b)
# what if you only take one
c = f()
print(c)
# Output:
# 10
# 11
# (10, 11)
|
# find the (only) duplicate
# number in the given list
# of integers
data = [3,4,7,8,1,2,4,9]
# "4" to be found
seen = set()
for x in data:
if x in seen:
# if we already met x
print(x)
break
seen.add(x) # keep collecting
else:
print("No duplicates found")
# Output:
# 4
|
# test if all or any
# items are ture
data = [True,True,False]
if any(data):
print("Some are True")
else:
print("Not a single True")
if all(data):
print("All are True")
else:
print("Not all are True")
# Output:
# Some are True
# Not all are True
|
# count how many times each item
# appears in the list
my_list = ["a","b","a","b","c",
"b","d","b","e","f"]
for item in sorted(set(my_list)):
# set(my_list): each item appears
# only one time
count = my_list.count(item)
print(f"item = {count} times")
# Output:
# item = 2 times
# item = 4 times
# item = 1 times
# item = 1 times
# item = 1 times
# item = 1 times
|
# a passible implementation
# of a non-recursive factorial
# calculation for positive ints
def factorial(n):
f = 1
for m in range(1,n + 1):
f *= m
return f
print(factorial(5)) # should be 120
# Output:
# 120
|
# increment all elements of a list
data = [10,20,30,40,50,60]
data = [x + 1 for x in data]
# this is a list comprehension
print(data)
Output:
[11, 21, 31, 41, 51, 61]
|
# another way of finding a missing
# number in a list
data = [3,8,1,9,4,10,6,7,2]
s = sum(data) # sum of all items
max = len(data) + 1 # maximum number
s2 = max * (max + 1) / 2 # sum of all
# numbers from 1 to 10 including 10
print(f"{s2 - s} is missing")
# the missing number is actually the
# difference between those tow sums
# Output:
# 5.0 is missing
|
# reverse the words in a sentence
text = "Hello, dear World!"
words = text.split() # split by space
words.reverse()
text = " ".join(words)
print(text) # reversed
# Output:
# World! dear Hello,
|
# reading from a text file
for str in open("code/Data/data.txt"):
print(str, end="")
# we should not print the
# newline after each string,
# as "str" already contains it
# Output:
# line 1
# line 2
# line 3
|
# when iterating over
# a dictionary, you get
# the keys of it
data = {"France":"Paris",
"Germany":"Berlin",
"Italy":"Rome"}
for country in data:
print("The capital of " + country + " is " + data[country])
# Output:
# The capital of France is Paris
# The capital of Germany is Berlin
# The capital of Italy is Rome
|
'''
You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Example:
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.
'''
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
# Solution 1 :
# Runtime: 80 ms, faster than 55.99% of Python3 online submissions for Add Two Numbers.
# Memory Usage: 13.9 MB, less than 5.67% of Python3 online submissions for Add Two Numbers.
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
sum = l1.val + l2.val
carry = sum // 10
l3 = ListNode(sum % 10)
p1 = l1.next
p2 = l2.next
p3 = l3
while(p1 != None or p2 != None):
sum = carry + ( p1.val if p1 else 0) + ( p2.val if p2 else 0)
carry = sum // 10
p3.next = ListNode(sum % 10)
p3 = p3.next
p1 = p1.next if p1 else None
p2 = p2.next if p2 else None
if(carry > 0):
p3.next = ListNode(carry)
return l3
if __name__ == "__main__":
# [0,8,6,5,6,8,3,5,7]
# [6,7,8,0,8,5,8,9,7]
# OUTPUT [6,5,5,6,4,4,2,5,5,1]
l1_1 = ListNode(0)
l1_2 = ListNode(8)
l1_3 = ListNode(6)
l1_4 = ListNode(5)
l1_5 = ListNode(6)
l1_6 = ListNode(8)
l1_7 = ListNode(3)
l1_8 = ListNode(5)
l1_9 = ListNode(7)
l1_1.next = l1_2
l1_2.next = l1_3
l1_3.next = l1_4
l1_4.next = l1_5
l1_5.next = l1_6
l1_6.next = l1_7
l1_7.next = l1_8
l1_8.next = l1_9
l2_1 = ListNode(6)
l2_2 = ListNode(7)
l2_3 = ListNode(8)
l2_4 = ListNode(0)
l2_5 = ListNode(8)
l2_6 = ListNode(5)
l2_7 = ListNode(8)
l2_8 = ListNode(9)
l2_9 = ListNode(7)
l2_1.next = l2_2
l2_2.next = l2_3
l2_3.next = l2_4
l2_4.next = l2_5
l2_5.next = l2_6
l2_6.next = l2_7
l2_7.next = l2_8
l2_8.next = l2_9
sol = Solution()
result = sol.addTwoNumbers(l1_1, l2_1)
node = result
while node != None:
print(node.val)
node = node.next |
'''
Given an array, rotate the array to the right by k steps, where k is non-negative.
Example 1:
Input: [1,2,3,4,5,6,7] and k = 3
Output: [5,6,7,1,2,3,4]
Explanation:
rotate 1 steps to the right: [7,1,2,3,4,5,6]
rotate 2 steps to the right: [6,7,1,2,3,4,5]
rotate 3 steps to the right: [5,6,7,1,2,3,4]
Note:
Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem.
Could you do it in-place with O(1) extra space?
'''
# Solution 1 - O(1) space
# Runtime: 96 ms, faster than 23.55% of Python3 online submissions for Rotate Array.
# Memory Usage: 15.2 MB, less than 5.09% of Python3 online submissions for Rotate Array.
def gcd(a, b):
if b == 0:
return a
else:
return gcd(b, a % b)
class Solution:
def rotateLeft(self, array, k):
n = len(array)
numSets = gcd(n, k)
for i in range(numSets):
j = i
temp = array[i]
while 1:
d = (j + k) % n # d = (j - k) % n for right rotate
if d == i:
break
array[j] = array[d]
j = d
array[j] = temp
return array
if __name__ == "__main__":
sol = Solution()
array = [1, 2, 3, 4, 5, 6, 7, 8, 9]
newArray = [1, 2, 3, 4, 5, 6, 7, 8, 9]
k = 2
result = sol.rotateLeft(array, k)
print(result)
# newArray = newArray[k:] + newArray[:k] # left rotate
# newArray = newArray[len(array)-k:] + newArray[:len(array)-k] # right rotate
# print(newArray)
|
# Runs in Python 2
'''
Given an underected connected graph with n nodes labeled 1..n. A bridge (cut edge) is defined as an edge which, when removed, makes the graph disconnected (or more precisely, increases the number of connected components in the graph). Equivalently, an edge is a bridge if and only if it is not contained in any cycle. The task is to find all bridges in the given graph. Output an empty list if there are no bridges.
Input:
n, an int representing the total number of nodes.
edges, a list of pairs of integers representing the nodes connected by an edge.
Example 1:
Input: n = 5, edges = [[1, 2], [1, 3], [3, 4], [1, 4], [4, 5]]
Output: [[1, 2], [4, 5]]
Explanation:
There are 2 bridges:
1. Between node 1 and 2
2. Between node 4 and 5
If we remove these edges, then the graph will be disconnected.
If we remove any of the remaining edges, the graph will remain connected.
Example 2:
Input: n = 6, edges = [[1, 2], [1, 3], [2, 3], [2, 4], [2, 5], [4, 6], [5, 6]]
Output: []
Explanation:
We can remove any edge, the graph will remain connected.
Example 3:
Input: n = 9, edges = [[1, 2], [1, 3], [2, 3], [3, 4], [3, 6], [4, 5], [6, 7], [6, 9], [7, 8], [8, 9]]
Output: [[3, 4], [3, 6], [4, 5]]
'''
from collections import defaultdict
class Solution(object):
def criticalConnections(self, n, connections):
"""
:type n: int
:type connections: List[List[int]]
:rtype: List[List[int]]
"""
graph = defaultdict(list)
for v in connections:
graph[v[0]].append(v[1])
graph[v[1]].append(v[0])
disc = [None for _ in range(n+1)]
low = [None for _ in range(n+1)]
self.time = 0
res = []
def dfs(node, parent):
if disc[node] is None:
disc[node] = self.time
low[node] = self.time
self.time += 1
for n in graph[node]:
if disc[n] is None:
dfs(n, node)
if parent is not None:
l = min([low[i] for i in graph[node] if i!=parent]+[low[node]])
else:
l = min(low[i] for i in graph[node]+[low[node]])
low[node] = l
dfs(1, None)
for v in connections:
if disc[v[0]]<low[v[1]] or disc[v[1]]<low[v[0]]:
res.append(v)
return res
if __name__ == '__main__':
n = 5
edges = [[1, 2], [1, 3], [3, 4], [1, 4], [4, 5]]
# n = 9
# edges = [[1, 2], [1, 3], [2, 3], [3, 4], [3, 6], [4, 5], [6, 7], [6, 9], [7, 8], [8, 9]]
solution = Solution()
print(solution.criticalConnections(n, edges))
|
def sumOfTwo(a, b, target):
components = dict()
for num1 in a:
components[target - num1] = True
for num2 in b:
if num2 in components.keys():
return True
return False
a = [-5, 0, 0, 32]
b = [9, 1, -2, 10]
result = sumOfTwo(a, b, -8)
print(result)
|
# Solution 1
# O(n * m) Time | O(1) Space
# def distance(x, y):
# x = int(x)
# y = int(y)
# return abs(x - y)
# def smallestDifference(arrayOne, arrayTwo):
# arrayOne.sort()
# arrayTwo.sort()
# closesPairsArray = [float("inf"), float("inf")]
# closestDiff = float("inf")
# for i in range(len(arrayOne)):
# left = 0
# right = len(arrayTwo) - 1
# while left < right:
# distance1 = distance(arrayOne[i], arrayTwo[left])
# distance2 = distance(arrayOne[i], arrayTwo[right])
# if distance1 <= distance2 and distance1 < closestDiff:
# closesPairsArray = [arrayOne[i], arrayTwo[left]]
# right -= 1
# elif distance2 <= distance1 and distance2< closestDiff:
# closesPairsArray = [arrayOne[i], arrayTwo[right]]
# left += 1
# else:
# left += 1
# right -= 1
# # print(closesPairsArray)
# return closesPairsArray |
class ListNode:
def __init__(self, val):
self.val = val
self.next = None
headNode = ListNode(1)
secondNode = ListNode(2)
thirdNode = ListNode(3)
headNode.next = secondNode
secondNode.next = thirdNode
# #Traversing the linked list
currentNode = headNode
while currentNode is not None:
print(currentNode.val)
currentNode = currentNode.next
# insert new listnode with value of 5 in between the secondNode and thirdNode
currentNode = headNode
while currentNode.val != 2:
currentNode = currentNode.next
newNode = ListNode(5)
newNode.next = currentNode.next
currentNode.next = newNode |
sum = 0
# for i in range(10):
# number = input('Please enter a number: ')
# if int(number) % 2 == 0:
# print('The number is even')
# else:
# print('This number is odd')
number = int(input('Please enter a number: '))
while number is not -1:
if int(number) % 2 == 0:
print('The number is even')
else:
print('This number is odd')
number = int(input('Please enter a number: ')) |
mySet1 = set([1, 2, 3, 4, 5])
mySet2 = {1, 2}
mySet2.add(3)
mySet2.add(4)
mySet2.add(5)
mySet2.remove(5)
for element in mySet2:
print(True if element % 2 else False)
mySet = mySet1.union(mySet2)
print(mySet)
mySet = mySet1.intersection(mySet2)
print(mySet) |
s1 = 'waterbottle'
s2 = 'erbottlewat'
s1 = s1 + s1
# waterbottlewaterbottle
output = s1.find(s2)
print(3//2)
# print(output) |
##Files handling order
# myFileHandler = open('countries.txt', 'w')
# myFileHandler.write(str(MyVisitedCountries))
# myFileHandler.read() OR myFileHandler.readLine()
# myFileHandler.close()
MyVisitedCountries = ['SAU', 'ARE', 'JOR', 'EGY']
##Wrtiting to a file
myFileHandler = open('countries.txt', 'w')
# myFileHandler.write(str(MyVisitedCountries))
for county in MyVisitedCountries:
myFileHandler.write(county + '\n')
myFileHandler.close()
myFileHandler = open('countries.txt', 'a')
myFileHandler.write('SYR')
myFileHandler.close()
# ##Reading from file
# myFileHandler = open('countries.txt', 'r')
# print(myFileHandler.read())
# myFileHandler.close()
##No need to close the file when using the with key word.
with open('countries.txt', 'r') as countriesFile:
for line in countriesFile:
print(line) |
# Do not edit the class below except for the buildHeap,
# siftDown, siftUp, peek, remove, and insert methods.
# Feel free to add new properties and methods to the class.
class MinHeap:
def __init__(self, array):
# Do not edit the line below.
self.heap = self.buildHeap(array)
def buildHeap(self, array):
# Using Sift down method.
# Get the first parent Idx
# Loop backwards to the root, and siftDown the whole thing.
firstParentIdx = (len(array) - 2) // 2
for currentIdx in reversed(range(firstParentIdx + 1)):
self.siftDown(currentIdx, len(array) - 1, array)
return array
def siftDown(self, currentIdx, endIdx, heap):
# Get the child one of the current node.
# While child one is not a leaf, Because there is no need to sift down if the child is a leaf.
# Get the child two of the current node, if its within the array, meaning if the parent has only two childs.
# If child two index is valid and the child two value is less than child one value, Then its the indx to swap, other wise use child one Idx instead. (Get smallest child value indx).
# Swap if the currentIdx value is > smallest child value.
# Set the currentIdx to be the childOneIdx, Update the childOneIdx for the loop
# If the smallest child value is not less than the curent (Its parent), Break.
#
childOneIdx = currentIdx * 2 + 1
while childOneIdx <= endIdx:
childTwoIdx = currentIdx * 2 + 2 if currentIdx * 2 + 2 <= endIdx else -1
if childTwoIdx != -1 and heap[childTwoIdx] < heap[childOneIdx]:
idxToSwap = childTwoIdx
else:
idxToSwap = childOneIdx
if heap[idxToSwap] < heap[currentIdx]:
self.swap(currentIdx, idxToSwap, heap)
currentIdx = idxToSwap
childOneIdx = currentIdx * 2 + 1
else:
return
def siftUp(self, currentIdx, heap):
# Get the parent of current node.
# While we did not pass the root of the heap and the current node value is less than its parent,
# Swap the current with the parent,
# The current now was the parent, Get it's parent again and continue till we reach the root.
parentIdx = (currentIdx - 1) // 2
while currentIdx > 0 and heap[currentIdx] < heap[parentIdx]:
self.swap(currentIdx, parentIdx, heap)
currentIdx = parentIdx
parentIdx = (currentIdx - 1) // 2
def peek(self):
# Return the Min/Max value of the heap,
# Which is the root of the heap.
return self.heap[0]
pass
def remove(self):
# Swap the root with the last element.
# Pop the last element.
# Sift down starting from the top til the end of the heap.
# Return the poped element (Min/Max value in the heap).
self.swap(0, len(self.heap) - 1, self.heap)
valueToRemove = self.heap.pop()
self.siftDown(0, len(self.heap) - 1, self.heap)
return valueToRemove
def insert(self, value):
# Insert the element in last position,
# Start sifting up from that last position.
self.heap.append(value)
self.siftUp(len(self.heap) - 1, self.heap)
def swap(self, i, j, heap):
heap[i], heap[j] = heap[j], heap[i]
def isMinHeapPropertySatisfied(array):
for currentIdx in range(1, len(array)):
parentIdx = (currentIdx - 1) // 2
if array[parentIdx] > array[currentIdx]:
return False
return True
minHeap = MinHeap([48, 12, 24, 7, 8, -5, 24, 391, 24, 56, 2, 6, 8, 41])
minHeap.insert(76)
print(isMinHeapPropertySatisfied(minHeap.heap))
print(minHeap.peek(), -5)
minHeap.remove()
print(isMinHeapPropertySatisfied(minHeap.heap))
print(minHeap.peek(), 2)
minHeap.remove()
print(isMinHeapPropertySatisfied(minHeap.heap))
print(minHeap.peek(), 6)
minHeap.insert(87)
print(isMinHeapPropertySatisfied(minHeap.heap)) |
def dec_htl(func):
def htl(a,b):
if a<b:
a,b=b,a
if func==div and b==0:
return "Not Divisible"
return func(a,b)
return htl
def dec_nonzero(func):
def new_div(a,b):
if b==0:
return "Not Divisible"
else:
return func(a,b)
return new_div
@dec_htl
@dec_nonzero
def div(a,b):
return a/b
@dec_htl
def subtract(a,b):
return a-b
ans1 = div(4,2)
ans2 = subtract(3,8)
print(f"{ans1} {ans2}")
|
def countdown (n):
cnt = n + 1 #출력할 지역변수를 만들어줍니다. 하나씩 줄일 것이므로 +1 해주었습니다.
def cntdown():
nonlocal cnt # 클로저의 지역 변수를 변경하기 위해 nonlocal을 사용합니다.
cnt -= 1
return cnt # 이 값이 print(c())에 들어가게 하기 위함입니다.
return cntdown
n = int(input())
c = countdown(n) # cntdown을 리턴하였으므로 c에는 함수 cntdown이 들어갑니다.
for i in range(n):
print(c(), end=' ')
|
"""
function flattenDict from https://gist.github.com/higarmi/6708779
example: The following JSON document:
{"maps":[{"id1":"blabla","iscategorical1":"0", "perro":[{"dog1": "1", "dog2": "2"}]},{"id2":"blabla","iscategorical2":"0"}],
"masks":{"id":"valore"},
"om_points":"value",
"parameters":{"id":"valore"}}
will have the following output:
{'masks.id': 'valore', 'maps.iscategorical2': '0', 'om_points': 'value', 'maps.iscategorical1': '0',
'maps.id1': 'blabla', 'parameters.id': 'valore', 'maps.perro.dog2': '2', 'maps.perro.dog1': '1', 'maps.id2': 'blabla'}
"""
def flattenDict(d, result=None):
if result is None:
result = {}
for key in d:
value = d[key]
if isinstance(value, dict):
value1 = {}
for keyIn in value:
value1[".".join([key,keyIn])]=value[keyIn]
flattenDict(value1, result)
elif isinstance(value, (list, tuple)):
for indexB, element in enumerate(value):
if isinstance(element, dict):
value1 = {}
index = 0
for keyIn in element:
newkey = ".".join([key,keyIn])
value1[".".join([key,keyIn])]=value[indexB][keyIn]
index += 1
for keyA in value1:
flattenDict(value1, result)
else:
result[key]=value
return result
|
class ExtendedStack(list):
# def append(self, T):
# self.append(T)
# def pop(self):
# self.pop()
def sum(self):
# операция сложения
self.append(self.pop() + self.pop())
# print(self)
def sub(self):
# операция вычитания
self.append(self.pop()-self.pop())
# print(self)
def mul(self):
# операция умножения
if len(self) > 1:
self.append(self.pop() * self.pop())
# print(self)
def div(self):
# операция целочисленного деления
if len(self) > 1 and self[-2] != 0:
self.append(self.pop()//self.pop())
# print(self)
A = ExtendedStack()
for i in range(6):
A.append(i)
if i == 3:
A.append(0)
print(A)
print('run')
#print(A.mainlist[-2])
A.sum()
A.sub()
A.mul()
A.div()
print(A)
|
import numpy as np
def stepVer1(x):#Only with scalar
if(x>0):
return 1
else:
return 0
def stepVer2(x):
y = x>0#bool numpy array
return y.astype(np.int)#Convert to int array
def sigmoid(x):
return 1 / (1+np.exp(-x))
def ReLu(self, x):
return np.maximum(0, x)
def noSoftmax(arr):
exp = np.exp(arr)
exp_sum = np.sum(exp)
return exp/exp_sum
def softmax(arr):
arr_max = np.max(arr) #overflow
arr -= arr_max
exp = np.exp(arr)
exp_sum = np.sum(exp)
return exp/exp_sum
"""
soft = Softmax()
tmp = np.arange(1, 2, 0.1)
print(tmp)
print(soft.softmax(tmp))
print(np.sum(soft.softmax(tmp)))
A = activation()
x = np.arange(-3.0, 3.0, 0.5)
print("step func: ")
print(A.stepVer2(x))
print("sigmoid: " )
print(A.sigmoid(x))
"""
|
import csv
import os
from typing import List, Dict
def listdir_nohidden(path: str):
"""
List not hidden files in directory
Avoid .DS_Store files for Mac
"""
for f in os.listdir(path):
if not f.startswith("."):
yield f
def write_txt_file(path: str, list_to_write: List):
with open(path, "w") as f:
for item in list_to_write:
f.write("%s\n" % item)
def write_csv(dict_to_write: Dict, path: str, fieldnames: List):
with open(path, "w", encoding="utf-8") as f:
w = csv.writer(f, delimiter=";")
w.writerow(fieldnames)
for key, value in dict_to_write.items():
w.writerow([key, value])
|
############################ Lambda #######################
# A simple one line function. No def or return keywords, they are implicit
# Anonymous Functions
# def keyword is used to define the normal functions and the lambda keyword is used to create anonymous functions
# syntax - lambda arguments: expression
# This function can have any number of arguments but only one expression, which is evaluated and returned.
# Lamda function to find the square
a = lambda x : x ** 2
print(a (5 ) )
# Lambda functions can be used along with built-in functions like filter(), map() and reduce().
#### filter ##########
# Filters out all the elements in the sequence which satisfies the condition
list1 = [1,2,3,4,5,6,7,8,9]
onlyOddNumbers = list(filter(lambda x : (x % 2 != 0) ,list1 ))
print(onlyOddNumbers)
############# List comprehension ##################
# List comprehension also works in place of filter()
print( [ x for x in list1 if ( x % 2 != 0 )])
##### map ############
# The function is called with a lambda function and a list and
# a new list is returned which contains all the lambda modified items
# returned by that function for each item.
mapSquare = list(map((lambda x : x ** 2 ), list1 ))
print(mapSquare)
############# List comprehension ##################
# List comprehension also works in place of map()
print( [x **2 for x in list1 ] )
################## reduce () ###############
# Takes in a function and a list as argument.
from functools import reduce
reduceSum = reduce( (lambda x,y : x+y ), list1)
print(reduceSum)
################### lambda ###################
largerOfTwo = lambda x ,y : x if x > y else y
print('Larger of two - largerOfTwo(10, 15) --->', largerOfTwo(10, 15) ) |
#!/usr/bin/env python3
import random
import string
#My random.choices still does not work. So I looked into a work around
def mRNA(seqLength=1000):
"""Generate a random string of fixed length """
bases = 'AUGC'
return ''.join(random.choice(bases) for i in range(seqLength))
#What I think it is doing is choosing 1000 elements from bases and joining them to the sequence.
sequence = mRNA()
#Getting our string ready for action.
start_codon = sequence.count('AUG')
print("This is how many genes we have=", start_codon)
#Counts then notifies user how many genes we have.
renz = sequence.split('AUG')
#Splits on 'AUG'
#The only problem I see here is that it uses AUG as a delimiter and is thus removed in later steps.
#I suppose I could just add 3 to the count down below...
#print(renz)
#Commented out checkpoint
genes = [s for s in renz if len(s) > 50]
#If a chunk is greater than 50 base pairs, add to list.
print("Genes over 50 base pairs", genes)
#Checkpoint
num_genes = len(genes)
print("We now have this many genes=", num_genes)
for element in genes:
print((len(element)) )
#As a loop, determines length of each gene.
print("And again as a list comprehension")
hardy = [len(element) for element in genes]
print(hardy)
#Same as above, but as list comprehension
|
numero = input("Digite um número inteiro: ")
inteiro = int(numero)
dezena = ((inteiro % 100) // 10)
print ("O dígito das dezenas é", dezena)
|
import operator
seats = None
while seats == None:
try:
seats = int(input("Enter number of seats available:"))
if seats <= 0:
print("Number of seats can not be less than 1")
seats = None
elif seats > 10:
print("Number of seats can not be more than 10")
seats = None
except ValueError:
seats = None
print("number of seats must be a valid number more than 0")
party_num = None
while party_num == None:
try:
party_num = int(input("Enter number of parties in the election:"))
if party_num <= 0:
print("number of parties can not be less than 1")
party_num = None
elif party_num > 10:
print("Number of seats can not be more than 10")
seats = None
except ValueError:
party_num = None
print("number of seats must be a valid number more than 0")
parties_seats = {}
for i in range(party_num):
party_name = None
while party_name == None:
party_name = input("Please enter the name of the party:")
if party_name in parties_seats:
print("Party already entered")
party_name = None
elif len(party_name) == 0:
print("You must enter a party name")
party_name = None
percent = None
while percent == None:
try:
percent = float(input("Please enter the percentage of votes for "+party_name+": "))
if percent < 0 or percent > 100:
percent = None
print("percentage must be between 0 and 100")
except ValueError:
percent = None
print("You must enter a valid number for the percentage")
parties_seats[party_name] = [percent,0]
if sum([parties_seats[party][0] for party in parties_seats]) != 100:
print("Ooops something went wrong, your percentages did not add to 100!")
else:
for i in range(seats):
index, value = max(enumerate([parties_seats[party][0]/(parties_seats[party][1]+1) for party in parties_seats]), key=operator.itemgetter(1))
parties_seats[list(parties_seats.items())[index][0]][1] += 1
for party in parties_seats:
print(party+" won this many seats:"+str(parties_seats[party][1]))
|
#(8) 튜플
def solution(s):
answer = []
string = s[2:-2].split("},{")
string.sort(key=len)
for i in range(len(string)):
tmp = string[i].split(",")
for j in range(len(tmp)):
if int(tmp[j]) not in answer:
answer.append(int(tmp[j]))
return answer |
def find_start(seq):
"""Finds all of the start codons within a given sequence
and returns the index of the start of the codon"""
#initialize
start_spaces = []
seq = seq.upper()
index = 0
while index < len(seq):
if seq[index] == 'A' and seq[index + 1] == 'T' and seq[index + 2] == 'G':
start_spaces.append(index)
index += 1
return start_spaces
def find_end(seq):
"""Finds all of the stop codons within a given sequence
and returns the indices of these codons"""
#validate
if validate_seq(seq):
#initialize
stop_spaces = []
seq = seq.upper()
index = 0
while index < len(seq):
if (seq[index] == 'T' and seq[index + 1] == 'G' and seq[index + 2] == 'A')\
or (seq[index] == 'T' and seq[index + 1] == 'A' and seq[index + 2] == 'G')\
or (seq[index] == 'T' and seq[index + 1] == 'A' and seq[index + 2] == 'A'):
stop_spaces.append(index)
index += 1
return stop_spaces
#invalid base in sequence
else:
print ('Invalid sequence')
def validate_seq(seq):
"""Ensures that all bases within a given sequence are valid"""
valid_bases = ['G', 'A', 'T', 'C']
valid = True
for i in seq:
if i not in valid_bases:
valid = False
return valid
|
class Solution(object):
def isValidSudoku(self, board):
"""
:type board: List[List[str]]
:rtype: bool
"""
sudokuMap = set()
for i in xrange(0,9):
for j in xrange(0,9):
if board[i][j]!='.':
#make sure cur is a string so does not get mixed up with indexes
cur = str(board[i][j])
if (i,cur) in sudokuMap or (cur,j) in sudokuMap or (i/3,j/3,cur) in sudokuMap:
return False
sudokuMap.add((i,cur))
sudokuMap.add((cur,j))
sudokuMap.add((i/3,j/3,cur))
return True
|
class Solution(object):
def intersection(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
nums1=set(nums1)
nums2=set(nums2)
numMapping = {}
result = []
for num in nums1:
if num not in numMapping:
numMapping[num] = 0
for num in nums2:
if num in numMapping:
result.append(num)
return result
|
# coding: utf-8
# # Implement a program in java or python that contains a .txt file and the 20 statistically significant most common bigrams (by definition the lecture) on the console.
# In[117]:
import os
os.getcwd()
os.chdir("C:\\Users\jiany\Documents\School\Speech & Textmining\Project_Aufgabe")
# In[118]:
# -*- coding: utf-8 -*-
text = open('effie.txt')
data = text.read() # turns text into list
# ### Use a tokenizer that only takes words that have no umlauts and language-dependent special characters such as ß or é included. Punctuation marks, as well Uppercase and lowercase letters should also be ignored. Furthermore, everyone should Words that are in the given stopword list stopwords.txt are also availablebe ignored
# In[119]:
# -*- coding: utf-8 -*-
len(data)
print(data[1:1000])
# In[62]:
type(stopwords)
# In[70]:
stopwords = open('stopwords.txt').readlines() # load in stopwords
len(stopwords)
stopwords[1:10]
# In[63]:
from nltk.tokenize import sent_tokenize, word_tokenize #load in tokenizer
# In[90]:
words = word_tokenize(str(data))
len(words)
stopwords = word_tokenize(str(stopwords))
len(stopwords)
# In[91]:
# cut the stop words
filter_words = []
for w in words:
if w not in stopwords:
filter_words.append(w)
#filter_words = str(filter_words)
len(filter_words)
# In[73]:
filter_words[1:100]
# In[74]:
# cut the punctuation and numbers
import re
regex = r"(?<!\d)[.,;:](?!\d)"
word_list = re.sub(regex, "", filter_words, 0)
len(word_list)
# # Likelihood Estimation
# In[ ]:
bigram = pd.frame()
def dunning(p1,k1,n1,p2,k2,n2,data):
for word in filter_words:
2[(k1*log(k1/n2)+(n1-k1)*log(1-(k1/n1)))+(k2*log(k2/n2)+(n2-k2)*log(1-(k2/n2)))-(k1*log(((k1+k2)/(n1+n2)))+(n1-k1)*log(1-(k1+k2)/(n1+n2)))-(k2*log((k1+k2)/(n1+n2))+(n2-k2)*log(1-(k1+k2)/(n1+n2)))]
bigrams.append
print[bigrams]
# # Log Likelihood Rato Statistics from Github: https://github.com/rsennrich/ParZu/blob/master/preprocessor/punkt_tokenizer.py
# In[75]:
from __future__ import unicode_literals
import re
import sys
import math
#import punkt_data_german
import codecs
from collections import defaultdict
# In[76]:
#{ Log Likelihoods
#////////////////////////////////////////////////////////////
# helper for _reclassify_abbrev_types:
def _dunning_log_likelihood(count_a, count_b, count_ab, N):
"""
A function that calculates the modified Dunning log-likelihood
ratio scores for abbreviation candidates. The details of how
this works is available in the paper.
"""
p1 = float(count_b) / N
p2 = 0.99
null_hypo = (float(count_ab) * math.log(p1) +
(count_a - count_ab) * math.log(1.0 - p1))
alt_hypo = (float(count_ab) * math.log(p2) +
(count_a - count_ab) * math.log(1.0 - p2))
likelihood = null_hypo - alt_hypo
return (-2.0 * likelihood)
# In[77]:
def _col_log_likelihood(count_a, count_b, count_ab, N):
"""
A function that will just compute log-likelihood estimate, in
the original paper it's described in algorithm 6 and 7.
This *should* be the original Dunning log-likelihood values,
unlike the previous log_l function where it used modified
Dunning log-likelihood values
"""
import math
p = 1.0 * count_b / N
p1 = 1.0 * count_ab / count_a
p2 = 1.0 * (count_b - count_ab) / (N - count_a)
summand1 = (count_ab * math.log(p) +
(count_a - count_ab) * math.log(1.0 - p))
summand2 = ((count_b - count_ab) * math.log(p) +
(N - count_a - count_b + count_ab) * math.log(1.0 - p))
if count_a == count_ab:
summand3 = 0
else:
summand3 = (count_ab * math.log(p1) +
(count_a - count_ab) * math.log(1.0 - p1))
if count_b == count_ab:
summand4 = 0
else:
summand4 = ((count_b - count_ab) * math.log(p2) +
(N - count_a - count_b + count_ab) * math.log(1.0 - p2))
likelihood = summand1 + summand2 - summand3 - summand4
return (-2.0 * likelihood)
# In[78]:
_col_log_likelihood(3,4,2,1100)
# ### Pseudocode
# In[ ]:
# Must run the dunning_func for every combination and sequence of words
# outter loop: raps around the
#
# 1 2 3 4 n position
# Ich bin ein Berliner
# a ->b 1st Iteration
# a ->b 2nd Iteration
# a -> b 3rd Iteration
Ratios = []
for j in 1:len(filter_words):
_col_log_likelihood(filter_words.count(j),filter_words.count(j+1),filter_words.count('ich'+'bin'),len(filter_words))
# count_a count_b count_ab
# In[87]:
import re
from itertools import islice, izip # Why can't python import izip???!! I need this to count the number of ngrams a+b
from collections import Counter
words = re.findall("\w+",
"the quick person did not realize his speed and the quick person bumped")
Counter(izip(words, islice(words, 1, None)))
# In[84]:
get_ipython().magic('pinfo Counter')
|
#tokenizetxt
def tokenizetxt(fileName, sep):
words = []
if(sep == 1):
with open(fileName, "r") as words_file:
for line in words_file:
t = line.split(',')
word = map(lambda s: s.strip(), t)
words.extend(word) # simply reading text file into a list called words.
if(sep == 0):
with open(fileName, "r") as words_file:
for line in words_file:
nothing = [',','.',')','!','?',':','"']
space = ['(','%','/']
string = line
for ch in nothing:
string = string.replace(ch,'')
for ch in space:
string = string.replace(ch,' ')
word = string.split(' ')
word = list(map(lambda s: s.strip(), word))
word = list(filter(None,word))
words.extend(word) # simply reading text file into a list called words.
return words
words = tokenizetxt('readme.txt',0)
print (words)
|
import unittest
from unittest.mock import patch
from text_adventure import TextAdventureEngine
class TextAdventureEngineTestCase(unittest.TestCase):
def test_instance(self):
e = TextAdventureEngine()
self.assertEqual(True, isinstance(e, TextAdventureEngine))
def test_add_room(self):
e = TextAdventureEngine()
room1 = e.add_room(name='starting room', description='you wake up in a starting room')
self.assertEqual(1, e.number_rooms)
self.assertEqual('starting room', room1.name)
room2 = e.add_room(name='room 1', description='room after leaving start')
self.assertEqual(2, e.number_rooms)
self.assertEqual('room 1', room2.name)
def test_connect_rooms(self):
e = TextAdventureEngine()
room1 = e.add_room(name='starting room', description='you wake up in a starting room')
room2 = e.add_room(name='room 1', description='room after leaving start')
self.assertEqual(0, len(room1.connections))
self.assertEqual(0, len(room2.connections))
e.connect_rooms(source='starting room', destination='room 1', direction='left')
self.assertEqual(1, len(room1.connections))
self.assertEqual(1, len(room2.connections))
self.assertEqual(room2, room1.connections['left'].get('room'))
self.assertEqual(room1, room2.connections['back'].get('room'))
with self.assertRaises(RuntimeError):
e.connect_rooms(source='starting room', destination='doesnt exist', direction='right')
@patch('builtins.input')
@patch('builtins.print')
def test_state_machine(self, mock_print, mock_input):
e = TextAdventureEngine()
e.add_room(name='starting room', description='you wake up in a starting room')
e.add_room(name='room 1', description='room after leaving start')
e.add_room(name='finish', description='outside world', is_end=True)
e.connect_rooms(source='starting room', destination='room 1', direction='left', description='you see a door to your left')
e.connect_rooms(source='room 1', destination='finish', direction='forward', description='the exit is right in front of you')
# this will start interacting with the user, so we're going to mock out the user input and output
mock_input.side_effect = ['0', '0', 'invalid', '0', 'blah', '1']
e.start()
self.assertTrue(mock_print.called)
self.assertEqual(12, mock_print.call_count)
if __name__ == '__main__':
unittest.main()
|
#!/usr/bin/python3
# Script name: TrafficLightFunction.py
# Uses the red, yellow and green LEDs to simulate a road traffic light
#
# Mark Bradley
# 2019-12-05
# Code divided into functions.
# To exit the code use <ctrl> + c or click the stop button in Thonny
# Import additional libraries.
from gpiozero import LED #Using gpiozero library, LED object used for each LED
from time import sleep #Use sleep funtion for timing, time is in seconds
ns_grn=LED(21) # Assign pin 21 to the green led.
ns_yel=LED(20) # Assign pin 20 to the yellow led.
ns_red=LED(16) # Assign pin 16 to the red led.
ew_grn=LED(5) # Assign pin 5 to the green led.
ew_yel=LED(6) # Assign pin 6 to the yellow led.
ew_red=LED(13) # Assign pin 13 to the red led.
ns_red.on() # Set both red LEDs on.
ew_red.on()
def traffic_light_ns():
# Run through a single sequence of the North South traffic lights
ns_red.on() # Turn LED ON, set output pin 'on' this puts +3.3v on the IO pin.
sleep(1) # Wait 1 seconds
ns_yel.on() # Repeat for the other LEDs
sleep(1)
ns_red.off()
ns_yel.off()
ns_grn.on()
sleep(4)
ns_grn.off()
ns_yel.on()
sleep(1.5)
ns_yel.off()
ns_red.on()
def traffic_light_ew():
# Run through a single sequence of East West traffic lights
ew_red.on() # Turn LED ON, set output pin 'on' this puts +3.3v on the IO pin.
sleep(1) # Wait 1 seconds
ew_yel.on() # Repeat for the other LEDs
sleep(1)
ew_red.off()
ew_yel.off()
ew_grn.on()
sleep(4)
ew_grn.off()
ew_yel.on()
sleep(1.5)
ew_yel.off()
ew_red.on()
def clean_exit():
# On exit turn all the LEDs off.
ns_grn.off()
ns_yel.off()
ns_red.off()
ew_grn.off()
ew_yel.off()
ew_red.off()
#------ Start of the main block of code ------
print("Traffic Light simulation programme")
try:
while True: # Run utill <ctrl> C is pressed.
traffic_light_ns()
traffic_light_ew()
except (KeyboardInterrupt): # Run util stopped by keyboard interrupt....Ctrl + C
clean_exit()
print('All Done')
|
"""
Program to calculate optimal wifi node positioning using PSO
Floor plan can be can be read in as a greyscale image file e.g. png.
"""
import sys
import matplotlib.pyplot as plt
from matplotlib.ticker import MaxNLocator
import numpy as np
from pyswarm import pso
from floorMap import FloorMap
from fitness import FitnessLandscape
import itertools
MAP_FILEPATH = './Images/wall1nogo.png'
NUM_NODES = 1
SCALE = 1/3
SWARM_SIZE = 50
MAX_ITER = 6
if len(sys.argv) > 1:
MAP_FILEPATH = './Images/' + sys.argv[1]
# read image file, print WIDTH, HEIGHT and dimensions (RGBA == 4 dimensions)
FLOOR_MAP = FloorMap(MAP_FILEPATH)
(WIDTH, HEIGHT) = (FLOOR_MAP.width, FLOOR_MAP.height)
MAP_ARRAY = FLOOR_MAP.array
print("Read Image: ", MAP_FILEPATH, " WIDTH: ", WIDTH, " HEIGHT: ", HEIGHT)
MAP_IMG = FLOOR_MAP.get_transparent_img()
WALLS = FLOOR_MAP.get_walls()
print(WALLS) # How is this printing an array? Does python automatically do this?
LB = np.full((NUM_NODES*2), 1) # lower bounds of fitness landscape, start at 1, *2 for x y [x1 = 1 y1 =1]
UB = np.empty((NUM_NODES*2))
UB[::2] = WIDTH - 2 # every 2nd element, y for each node, equals width - 2
UB[1::2] = HEIGHT - 2 # the upper bound for each x coordinate of every node = height - 2
# Create new fitnessLandscape object
FIT_LANDSCAPE = FitnessLandscape(WIDTH, HEIGHT, NUM_NODES, MAP_ARRAY, WALLS, SCALE)
# attempt brute force computation
print("Attempting brute force")
# start by creating an array "array_of_permutations" that has all the possible and allowed x and y values
# for node positions. Have x and y values for all node positions, even if they are repeated
# btw allowing repetitions makes code inefficient, but for now not a big deal. Can optimise later if time - again
# shouldn't matter too much
y_length = WIDTH - 2
x_length = HEIGHT - 2
a = 1
b = 1
index = 0
array_of_permutations = []
while index < x_length:
array_of_permutations.append(a)
a = a + 1
index = index + 1
while index < (x_length + y_length):
array_of_permutations.append(b)
b = b + 1
index = index + 1
# technically we created an array with x y values for one node, extend this array for all nodes
node = 2
while node <= NUM_NODES:
array_of_permutations.extend(array_of_permutations)
node = node + 1
print("array of permutations: ", array_of_permutations)
# create all the possible x y values for our map for all the nodes
all_x_y_pos = itertools.permutations(array_of_permutations, NUM_NODES * 2)
# for pos in all_x_y_pos:
# print(pos)
# compute fitness for all x y points for all nodes and find best position
final_fitness = 0 # variable to store our best fitness value
previous_fitness = -1
best_pos_for_nodes = []
for pos in all_x_y_pos:
fitness = FIT_LANDSCAPE.getFitness(pos)
print(pos, fitness)
if fitness > previous_fitness:
final_fitness = fitness
previous_fitness = fitness
best_pos_for_nodes = pos
print("best position for nodes: ", pos, "\tfitness: ", final_fitness)
# maybe some visualization here, sorry still too dumb at python to do quickly :( |
"""
This module implements the DATE class, used for transient date storage and manipulation.
It makes various assumptions about how dates will be used,
and insulates the programmer from the full complexity of python date handling.
A DATE class instance wraps around a python datetime, and handles:
- input ('user') date validation and 'cleaning'
- date additions
- date comparison
- date arithmetic
- date formatting: uk date format
relevant date fomats:
1) user date : what the user inputs - should be same as display date but some variations allowed, eg 'dd-mm-yy' or 'dd/mm/yy'
2) display date (or fdate) : uk display format ie 'dd/mm/yyyy'
3) display datetime (or fdatetime) : uk display format ie 'dd/mm/yyyy hh:mm'
4) DATE : this class wraps a python datetime object instance, used for transient storage and for manipulations
5) sql datetime : iso format used for sql database storage : ie 'yyyy-mm-dd hh:mm:ss'
(Ian Howie Mackenzie - November 2005)
"""
from datetime import datetime,timedelta
from time import localtime,strftime, mktime
class DATE(object):
"""
simple date handling
- the constructor creates self.datetime, a python datetime instance, with all its usefulness
- the constructor shouldn't fail no matter what you throw at it, but will set self.valid accordingly
- comparison is supported, a la datetime
- str() and repr() return uk format date (no time) ie self.date()
- self.time() gives uk format date and time
- self.sql() gives sql format date
- self.add() addition/subtraction of days, months and years to self
"""
def __init__(self,date='now',days=0):
"""
create the self.datetime we want, with suitable error checking
Convert date string if possible, setting self.valid to 0 if date is not valid.
If no date given, default of "now" gives current date and time.
If date is None or "", flag as invalid (and set to "1/1/1900").
Add days on if given.
"""
self.valid=1
if isinstance(date,datetime):#trap a datetime
self.datetime=date
elif isinstance(date,DATE):#trap a DATE
self.datetime=date.datetime
self.valid=date.valid
elif date=='now':
self.datetime=datetime.today()
elif date:
try:
h=mn=s=0
try: #we cant use safeint from here, so do it the hard way
z=int(date)
except:
z=False
if z: #integer date a la mysql eg 20071003
date=str(date) #just to make sure
y=date[:-4]
m=date[-4:-2]
d=date[-2:]
else: #user input date or date/time
date=date.strip()
sd=date.split()
# print sd
if len(sd)>1: # presumably we have time
try:
hms=sd[1].split(":")
# print 'hms',hms
h=int(hms[0])
# print 'h',h
if len(hms)>=2:
mn=int(hms[1])
# print 'mn',mn
if len(hms)>=3:
s=int(hms[2])
# print 's',s
except:
# raise
pass
date=sd[0]
date=date.replace('-','/').replace(' ','')# sort out minor user input anomalies
d,m,y=date.split('/')
#allow for shorthand years
y=int(y)
y+=(y<70 and 2000 or ((y<100 and 1900) or 0))
self.datetime=datetime(y,int(m),int(d),int(h),int(mn),int(s))
except:#return '1/1/00' to indicate a problem
self.datetime=datetime(1900,1,1)
self.valid=0
days=0 #just in case...
else: # date is "" or None - eg mysql will return None for a blank date - default to invalid
self.datetime=datetime(1900,1,1)
self.valid=0
days=0 #just in case...
if days:
self.datetime=self.datetime+timedelta(days=days)
def sql(self,time=True, quoted=True):
""" gives sql datetime format, including quotes
"""
if quoted:
template = "'%s'"
else:
template = "%s"
if self.valid:
if time:
return template % str(self.datetime).split('.')[0]
else:
return template % str(self.datetime).split()[0]
return template % '0000-00-00'
def time(self,sec=False,date=True):
"""gives uk format user date (if date is set) and time display string (to the minute only, unless sec is set)
"""
if self.valid:
d=self.datetime
if date:
if sec:
return "%02d/%02d/%d %02d:%02d:%02d" % (d.day,d.month,d.year,d.hour,d.minute,d.second)
return "%02d/%02d/%d %02d:%02d" % (d.day,d.month,d.year,d.hour,d.minute) #works for pre 1900 dates, unlike strftime
else:
if sec:
return "%02d:%02d:%02d" % (d.hour,d.minute,d.second)
return "%02d:%02d" % (d.hour,d.minute) #works for pre 1900 dates, unlike strftime
return ''
def date(self):
"""gives uk format user date display string (no time)
"""
if self.valid:
d=self.datetime
return "%02d/%02d/%d" % (d.day,d.month,d.year) #works for pre 1900 dates, unlike strftime
# return self.datetime.strftime('%d/%m/%Y')
return ""
def nice(self,long=True):
"""gives nice date format string eg 'on 27 Apr 07 at 12:16 - (only works for dates after 1900) - long==True gives time also'
"""
if self.valid:
style=long and 'on %d %b %y at %H:%M' or '%d %b %y'
return self.datetime.strftime(style)
return ''
monthend=(31,28,31,30,31,30,31,31,30,31,30,31) # used by add() below - ignores leap years.....
def add(self,years=0,months=0,days=0,hours=0,minutes=0,seconds=0):
""" date arithmetic for years, months, days, hours, minutes, seconds
- Adds given periods on to self.
- This is useful because python datetimes don't deal with adding months and years.
"""
# adjust years and months
if years or months:
dt=self.datetime
d,m,y=(dt.day,dt.month+months,dt.year+years)
d=min(d,self.monthend[(m-1) % 12]) # limit day to what is possible
while m<0:
m+=12
years-=1
while m>12:
m-=12
years+=1
#adjust days using timedelta
self.datetime=datetime(y,m,d)+timedelta(hours=dt.hour,minutes=dt.minute,seconds=dt.second)
# adjust days, minutes and seconds
if days or hours or minutes or seconds:
self.datetime=self.datetime+timedelta(days=days,hours=hours,minutes=minutes,seconds=seconds)
return self
# representation as a counter number, which will fit a 32 bit int: seconds since 1/1/2007
_v_erashift= -1167609600 # start at 1/1/2007
def count(self):
"return integer counter, being number of seconds since 1/1/2007 - self must be after 1/1/2007, or 0 is returned"
if self.valid:
try:
d=self.datetime
return int(mktime((d.year,d.month,d.day,d.hour,d.minute,d.second,0,0,-1)))+self._v_erashift
except:
pass
return 0
@classmethod
def count_as_date(cls,count):
"display integer counter a la date()"
return strftime("%d %b %y",localtime(count-cls._v_erashift))
# representation as a decimal - no time info
def __int__(self):
"return date in mysql integer date format, eg 20080822"
# return int(self.datetime.strftime('%Y%m%d')) #doesnt work for dates before 1900
d=self.datetime
return d.year*10000+d.month*100+d.day
#make str(), repr() and comparison do sensible things
def __str__(self):return self.date()
def __repr__(self):return ("'%s'" % self.date())
def __cmp__(self, other):
try:
return cmp(self.datetime,other.datetime)
except:
return False
def __add__(self, time):
"add a TIME to the date or if numberish add minutes"
# duck typing: try to add the value
if hasattr(time, 'value'):
return self.add(minutes=time.value)
# then try
return self.add(minutes=time)
_v_mysql_type="datetime"
_v_default='0000-00-00 00:00:00'
def test():
x=DATE('22/8/1961')
assert x.valid
y=DATE('22/13/1951')
assert not y.valid
assert x>y
x=DATE('3/10/7')
y=DATE('20071003')
assert x==y
d=DATE('')
assert not d.valid
# date arithmetic
d=DATE('22/8/1961').add(years=46,months=5,days=1,hours=1,minutes=2,seconds=59)
d.add(years=1,hours=25,minutes=61,seconds=3)
dd=DATE('24/1/2008').add(hours=3,minutes=4,seconds=2)
assert dd==d
# times
d=DATE('24/10/2013 14:18')
assert d.time()=="24/10/2013 14:18"
assert d.time(sec=True)=="24/10/2013 14:18:00"
d=DATE('24/10/2013 14:18:23')
assert d.time(sec=True)=="24/10/2013 14:18:23"
#
# print int(x)
# print x,y
# c=DATE().count()
# print c
# print DATE.count_as_date(c)
# print DATE().sql(time=False)
if __name__=='__main__': test()
|
p = int(input())
q = int(input())
oddNumCnt = 0 #奇数的数量
oddNumSum = 0 #奇数和
oddList = [] #奇数列表
for i in range(1, p + 1, 2):
oddNumSum += i
oddNumCnt += 1
oddList.append(i)
if oddNumSum >= q or i >= p:
break
print(oddNumSum)
print(oddNumCnt)
print(max(oddList))
|
# 【问题描述】
#
# 定义一个电话簿,里头设置以下联系人:
#
# 'mayun':'13309283335',
#
# 'zhaolong':'18989227822',
#
# 'zhangmin':'13382398921',
#
# 'Gorge':'19833824743',
#
# 'Jordan':'18807317878',
#
# 'Curry':'15093488129',
#
# 'Wade':'19282937665'
#
# 现在输入人名,查询他的号码。
# 【输入形式】
#
# 人名,是一个字符串。
# 【输出形式】
#
# 电话号码。如果该人不存在,返回"not found"
# 【样例输入】
#
# mayun
# 【样例输出】
#
# 13309283335
#
dictPhonebook={'mayun':'13309283335',
'zhaolong':'18989227822',
'zhangmin':'13382398921',
'Gorge':'19833824743',
'Jordan':'18807317878',
'Curry':'15093488129',
'Wade':'19282937665'}
key=input()
if key in dictPhonebook:
print(dictPhonebook[key])
else:
print("not found") |
num1=float(input())
num2=float(input())
num3=float(input())
num4=float(input())
num5=float(input())
sum=num5+num4+num3+num2+num1
avg=int(sum/5)
print(avg) |
#Complete the function to return the respective number of the century
#HINT: You may need to import the math module.
import math
def century(year):
return math.ceil(year/100)
#Invoke the function with any given year.
print(century(1801)) |
from problem_utils import *
class HammingDistance:
def minDistance(self, numbers):
input_array = numbers
# The Hamming distance between two numbers is defined as the number of positions in their binary representations at which they differ (leading zeros are used if necessary to make the binary representations have the same length) - e.g., the numbers "11010" and "01100" differ at the first, third and fourth positions, so they have a Hamming distance of 3.
# You will be given a String[] numbers containing the binary representations of some numbers (all having the same length).
# You are to return the minimum among the Hamming distances of all pairs of the given numbers.
pass
def example0():
cls = HammingDistance()
input0 = ["11010", "01100"]
returns = 3
result = cls.minDistance(input0)
return result == returns
def example1():
cls = HammingDistance()
input0 = ["00", "01", "10", "11"]
returns = 1
result = cls.minDistance(input0)
return result == returns
def example2():
cls = HammingDistance()
input0 = ["000", "011", "101", "110"]
returns = 2
result = cls.minDistance(input0)
return result == returns
def example3():
cls = HammingDistance()
input0 = ["01100", "01100", "10011"]
returns = 0
result = cls.minDistance(input0)
return result == returns
def example4():
cls = HammingDistance()
input0 = ["00000000000000000000000000000000000000000000000000", "11111111111111111111111111111111111111111111111111"]
returns = 50
result = cls.minDistance(input0)
return result == returns
def example5():
cls = HammingDistance()
input0 = ["000000", "000111", "111000", "111111"]
returns = 3
result = cls.minDistance(input0)
return result == returns
if __name__ == '__main__':
print(example0())
|
from problem_utils import *
class TriFibonacci:
def complete(self, A):
input_array = A
# input_array TriFibonacci sequence begins by defining the first three elements input_array[0], input_array[1] and input_array[2].
# The remaining elements are calculated using the following recurrence: input_array[i] = input_array[i-1] + input_array[i-2] + input_array[i-3]
def mapping0(possibility):
#### possibilities = possibility
possibilities = possibility
#### reduce = lambda possibility: ((input_array[(i - 1)] + input_array[(i - 2)]) + input_array[(i - 3)])
reduce = (lambda possibility: ((input_array[(possibility - 1)] + input_array[(possibility - 2)]) + input_array[(possibility - 3)]))
#### return(reduce(possibilities))
return reduce(possibilities)
# You are given a int[] input_array which contains exactly one element that is equal to -1, you must replace this element with a positive number in a way that the sequence becomes a TriFibonacci sequence.
#### number = A_(indexOf(A, -1))
possibilities = mapping0(indexOf(A, (-1)))
# Return this number.
#### reduce = lambda possibility: number
reduce = (lambda possibility: possibilities)
#### return(reduce(possibilities))
return reduce(possibilities)
# If no such positive number exists, return -1.
def example0():
cls = TriFibonacci()
input0 = [1,2,3,-1]
returns = 6
result = cls.complete(input0)
return result == returns
def example1():
cls = TriFibonacci()
input0 = [10, 20, 30, 60, -1 , 200]
returns = 110
result = cls.complete(input0)
return result == returns
def example2():
cls = TriFibonacci()
input0 = [1, 2, 3, 5, -1]
returns = -1
result = cls.complete(input0)
return result == returns
def example3():
cls = TriFibonacci()
input0 = [1, 1, -1, 2, 3]
returns = -1
result = cls.complete(input0)
return result == returns
def example4():
cls = TriFibonacci()
input0 = [-1, 7, 8, 1000000]
returns = 999985
result = cls.complete(input0)
return result == returns
if __name__ == '__main__':
print(example0()) |
from problem_utils import *
class FarFromPrimes:
def count(self, A, B):
input_int0 = A
input_int1 = B
# A prime number is an integer greater than 1 that has no positive divisors other than 1 and itself.
# The first prime numbers are 2, 3, 5, 7, 11, 13, 17, ...
# The number N is considered far from primes if there are no prime numbers between N-10 and N+10, inclusive, i.e., all numbers N-10, N-9, ..., N-1, N, N+1, ..., N+9, N+10 are not prime.
# You are given an int A and an int B .
# Return the number of far from primes numbers between A and B, inclusive.
pass
def example0():
cls = FarFromPrimes()
input0 = 3328
input1 = 4100
returns = 4
result = cls.count(input0, input1)
return result == returns
def example1():
cls = FarFromPrimes()
input0 = 10
input1 = 1000
returns = 0
result = cls.count(input0, input1)
return result == returns
def example2():
cls = FarFromPrimes()
input0 = 19240
input1 = 19710
returns = 53
result = cls.count(input0, input1)
return result == returns
def example3():
cls = FarFromPrimes()
input0 = 23659
input1 = 24065
returns = 20
result = cls.count(input0, input1)
return result == returns
def example4():
cls = FarFromPrimes()
input0 = 97001
input1 = 97691
returns = 89
result = cls.count(input0, input1)
return result == returns
if __name__ == '__main__':
print(example0())
|
from problem_utils import *
class SupermarketDiscount:
def minAmount(self, goods):
input_array = goods
# Three girls are shopping at a supermarket.
# The supermarket is having a sale: "Spend $50 or more in a single transaction and get $10 off."
def spend(x):
#### return (off(x, 10) if more(x, 50) else x)
return (sub(x, 10) if ge(x, 50) else x)
# The girls realize that if they combine their purchases, they might be able to pay less than if they each pay separately.
#### possibilities = partitions(goods)
possibilities = partitions(goods)
# For example, if they are buying a total of $46, $62 and $9 worth of goods, respectively, they can combine the $46 and $9 totals and make two purchase transactions ($55 and $62) to get $20 off.
# You will be given a int[] goods , each element of which is the total cost of the goods purchased by one of the girls.
# Return the minimal total cost required to purchase all the goods.
#
# The girls are willing to combine their purchases as described above, but no girl is willing to split up her goods across multiple transactions.
def example0():
cls = SupermarketDiscount()
input0 = [46, 62, 9]
returns = 97
result = cls.minAmount(input0)
return result == returns
def example1():
cls = SupermarketDiscount()
input0 = [50, 62, 93]
returns = 175
result = cls.minAmount(input0)
return result == returns
def example2():
cls = SupermarketDiscount()
input0 = [5, 31, 15]
returns = 41
result = cls.minAmount(input0)
return result == returns
def example3():
cls = SupermarketDiscount()
input0 = [5, 3, 15]
returns = 23
result = cls.minAmount(input0)
return result == returns
if __name__ == '__main__':
print(example0()&example1()&example2()&example3()) |
from problem_utils import *
from operator import *
from string import lowercase
class ChangingString:
def distance(self, A, B, K):
input_array1 = A
input_array2 = B
input_int = K
N = len(input_array1)
# You are given two Strings A and B that have the same length and contain only lowercase letters ('a'-'z').
elements = lowercase
possibilities = product(elements,repeat = N)
# The distance between two letters is defined as the absolute value of their difference.
#### distance = lambda letters: absolute(difference(* letters))
mapping2 = lambda pair: abs(sub(* pair))
# The distance between A and B is defined as the sum of the differences between each letter in A and the letter in B at the same position.
#### distance = lambda A = sum([differences(A[position], B[position]) each position in range(N)])
mapping = lambda possibility: sum([mapping2(possibility[i], input_array2[i]) for i in range(N)])
# For example, the distance between "abcd" and "bcda" is 6 (1 + 1 + 1 + 3).
# You must change exactly K characters in A into other lowercase letters.
#### valid = lambda characters: exactly(len(change(A, characters)), K)
valid = lambda possibility: eq(len(diff(input_array1, possibility)), input_int)
# Return the minimum possible distance between A and B after you perform that change.
#### return(minimum([distance(A) for A in possibilities if possible(possibility)]))
return(min([mapping(possibility) for possibility in possibilities if valid(possibility)]))
if __name__ == '__main__':
A = "ab"
B = "ba"
K = 2
cs = ChangingString()
print(cs.distance(A, B, K)) |
from problem_utils import *
class SkewSymmetric:
def minChanges(self, M):
input_array = M
# A skew symmetric matrix M satisfies M T = - M , where M T denotes the transpose of the matrix M and - M denotes the matrix obtained by multiplying each entry of M by -1.
def skew_symmetric(i,j): M[i,j] = -M[j,i]
# The transpose of a matrix M is obtained by replacing the element in the i 'th row and j 'th column of M with the element in the j 'th row and i 'th column of M .
# Note that this requires the diagonal elements of a skew-symmetric matrix to be equal to 0.
# Create a class SkewSymmetric which contains a method minChanges.
# The method will take a String[] M , each element of which is a single space separated list of integers.
# The j 'th number in the i 'th element of M represents the value at row i and column j of the matrix.
# The method should return the minimum number of values in M that must be changed such that the resulting matrix is skew symmetric.
# ROOT-0(root=return-4(nsubj=method-2(det=The-1), aux=should-3, dobj=number-7(det=the-5, amod=minimum-6, prep_of=values-9(prep_in=M-11), rcmod=changed-15(nsubjpass=that-12, aux=must-13, auxpass=be-14, prep=such-16, ccomp=skew-22(mark=that-17, nsubj=matrix-20(det=the-18, amod=resulting-19), aux=is-21, acomp=symmetric-23)))))
return(minimum(number(changed(values(M),skew_symmetric))))
def example0():
cls = SkewSymmetric()
input0 = ["1 2 8", "-2 1 0", "3 99 3"]
returns = 5
result = cls.minChanges(input0)
return result == returns
def example1():
cls = SkewSymmetric()
input0 = ["0 1 1 1 1 1", "-1 0 1 1 1 1", "-1 -1 0 1 1 1", "-1 -1 -1 0 1 1", "-1 -1 -1 -1 0 1", "0 0 0 0 0 0"]
returns = 5
result = cls.minChanges(input0)
return result == returns
def example2():
cls = SkewSymmetric()
input0 = ["0 0 0 0", "0 0 0 0", "0 0 0 0", "0 0 0 0"]
returns = 0
result = cls.minChanges(input0)
return result == returns
def example3():
cls = SkewSymmetric()
input0 = ["1 0", "0 1"]
returns = 2
result = cls.minChanges(input0)
return result == returns
if __name__ == '__main__':
print(example0()) |
from problem_utils import *
class RandomColoringDiv2:
def getCount(self, maxR, maxG, maxB, startR, startG, startB, d1, d2):
input_int0 = maxR
input_int1 = maxG
input_int2 = maxB
input_int3 = startR
input_int4 = startG
input_int5 = startB
input_int6 = d1
input_int7 = d2
# Little Arthur has a new frisbee and he would like to color it.
# A frisbee has the shape of a disc.
# Arthur will color the disc using two colors: one for the top side, one for the bottom side.
# Each color is defined by three integer components: R, G, and B (meaning red, green, and blue, respectively), where 0 <= R < input_int0 , 0 <= G < input_int1 , and 0 <= B < input_int2 .
# It is known that Arthur can use any of the input_int0 * input_int1 * input_int2 possible colors.
#### colors = product(range(maxR),range(maxG),range(maxB))
possibilities = product(range(maxR), range(maxG), range(maxB))
# Arthur is going to perform the coloring in the following way: In the first step, he will color the top side of the frisbee using the color ( input_int3 , input_int4 , input_int5 ).
# In the second step, he will color the bottom side of the frisbee using a color that makes a good transition from the first color.
# (This is explained below.)
# A transition from color (R, G, B) to color (R', G', B') is called good if all components differ by at most input_int7 units (formally, |R - R'| <= input_int7 , |G - G'| <= input_int7 , |B - B'| <= input_int7 ) and at least one component differs by at least input_int6 units (formally, at least one of the conditions |R - R'| >= input_int6 , |G - G'| >= input_int6 , |B - B'| >= input_int6 holds).
def valid0((R, G, B), (R_, G_, B_)):
#### reduce = lambda possibility: (all([(abs((R - R_)) <= d2), (abs((G - G_)) <= d2), (abs((B - B_)) <= d2)]) and any([(abs((R - R_)) >= d1), (abs((G - G_)) >= d1), (abs((B - B_)) >= d1)]))
reduce = (lambda possibility: (all([(abs((R - R_)) <= d2), (abs((G - G_)) <= d2), (abs((B - B_)) <= d2)]) and any([(abs((R - R_)) >= d1), (abs((G - G_)) >= d1), (abs((B - B_)) >= d1)])))
#### return(reduce(possibilities))
return reduce(possibilities)
# Intuitively, a transition between two colors is called good if they are neither too similar, nor too different.
# After coloring the top side Arthur is wondering how many different options there are now for the color of the bottom side of the frisbee.
# Given ints input_int0 , input_int1 , input_int2 , input_int3 , input_int4 , input_int5 , input_int6 , and input_int7 , return the number of valid colors that make a good transition from the color ( input_int3 , input_int4 , input_int5 ).
#### def valid(possibility): return good((startR, startG, startB), possibility)
def valid(possibility): return valid0((startR, startG, startB), possibility)
#### def reduce(possibility): return number(possibility)
def reduce(possibility): return len(possibility)
#### return reduce(filter(valid, possibilities))
return reduce(filter(valid, possibilities))
def example0():
cls = RandomColoringDiv2()
input0 = 5
input1 = 1
input2 = 1
input3 = 2
input4 = 0
input5 = 0
input6 = 0
input7 = 1
returns = 3
result = cls.getCount(input0, input1, input2, input3, input4, input5, input6, input7)
return result == returns
def example1():
cls = RandomColoringDiv2()
input0 = 4
input1 = 2
input2 = 2
input3 = 0
input4 = 0
input5 = 0
input6 = 3
input7 = 3
returns = 4
result = cls.getCount(input0, input1, input2, input3, input4, input5, input6, input7)
return result == returns
def example2():
cls = RandomColoringDiv2()
input0 = 4
input1 = 2
input2 = 2
input3 = 0
input4 = 0
input5 = 0
input6 = 5
input7 = 5
returns = 0
result = cls.getCount(input0, input1, input2, input3, input4, input5, input6, input7)
return result == returns
def example3():
cls = RandomColoringDiv2()
input0 = 6
input1 = 9
input2 = 10
input3 = 1
input4 = 2
input5 = 3
input6 = 0
input7 = 10
returns = 540
result = cls.getCount(input0, input1, input2, input3, input4, input5, input6, input7)
return result == returns
def example4():
cls = RandomColoringDiv2()
input0 = 6
input1 = 9
input2 = 10
input3 = 1
input4 = 2
input5 = 3
input6 = 4
input7 = 10
returns = 330
result = cls.getCount(input0, input1, input2, input3, input4, input5, input6, input7)
return result == returns
def example5():
cls = RandomColoringDiv2()
input0 = 49
input1 = 59
input2 = 53
input3 = 12
input4 = 23
input5 = 13
input6 = 11
input7 = 22
returns = 47439
result = cls.getCount(input0, input1, input2, input3, input4, input5, input6, input7)
return result == returns
if __name__ == '__main__':
print(example0()&example1()&example2()&example3()&example4()&example5()) |
from problem_utils import *
class Pronunciation:
def canPronounce(self, words):
input_array = words
# Peter has problems with pronouncing difficult words.
# In particular he can't pronounce words that contain three or more consecutive consonants (such as "street" or "first").
def cant_pronounce(word): contain(word, three or more(consecutive(consonants)))
# Furthermore he can't pronounce words that contain two or more consecutive vowels that are different (such as "goal" or "beauty").
def cant_pronounce(word): dobj=words(rcmod=contain(dobj=vowels(num=two(conj_or=more), amod=consecutive, rcmod=different)))
# He can pronounce words with two consecutive equal vowels though (such as "need").
# Is this problem we consider the 'y' to be always a consonant, even in words like "any".
# So the vowels are 'a', 'e', 'i', 'o' and 'u'.
# You are given a String[] words .
# If Peter can pronounce all the words, return an empty String; otherwise return the first word he can't pronounce.
# return(dobj=word(amod=first), dep=pronounce(aux=ca, neg=n't))))
return first(cant_pronounce(word))
def example0():
cls = Pronunciation()
input0 = ["All","of","these","are","not","difficult"]
returns = ""
result = cls.canPronounce(input0)
return result == returns
def example1():
cls = Pronunciation()
input0 = ["The","word","REALLY","is","really","hard"]
returns = "REALLY"
result = cls.canPronounce(input0)
return result == returns
def example2():
cls = Pronunciation()
input0 = ["TRiCKy"]
returns = "TRiCKy"
result = cls.canPronounce(input0)
return result == returns
def example3():
cls = Pronunciation()
input0 = ["irresistable","prerogative","uttermost","importance"]
returns = ""
result = cls.canPronounce(input0)
return result == returns
def example4():
cls = Pronunciation()
input0 = ["Aa"]
returns = ""
result = cls.canPronounce(input0)
return result == returns
if __name__ == '__main__':
print(example0()) |
from problem_utils import *
from operator import *
from string import digits
from numpy import where, array
class InterestingNumber:
def isInteresting(self, x):
input_array = array(x)
# Fox Ciel thinks that the number 41312432 is interesting.
# This is because of the following property:
# There is exactly 1 digit between the two 1s, there are exactly 2 digits between the two 2s, and so on.
# Formally, Ciel thinks that a number X is interesting if the following property is satisfied: For each D between 0 and 9, inclusive, X either does not contain the digit D at all, or it contains exactly two digits D, and there are precisely D other digits between them.
def valid0(possibility):
#### possibilities = between(0,inclusive(9))
possibilities = range(0, inclusive(9))
#### def mapping(possibility): return not(contain(X, D)) or (exactly(contains(X, D), two) and precisely(between(* where(eq(X, D))),int(D)))
def mapping(possibility): return (not_(contains(input_array, possibility)) or (eq(countOf(input_array, possibility), 2) and eq(sub(*where(eq(input_array, possibility))), possibility)))
#### def reduce(possibility): return each(possibility)
def reduce(possibility): return all(possibility)
#### return reduce(map(mapping, possibilities))
return reduce(map(mapping, possibilities))
# You are given a String x that contains the digits of a positive integer.
# Return "Interesting" if that integer is interesting, otherwise return "Not interesting".
#### possibilities = input_array
possibilities = input_array
#### reduce = lambda possibility: if(interesting(integer), ['Interesting', 'Not interesting'])
reduce = (lambda possibility: if_(valid0(possibility), ['Interesting', 'Not interesting']))
#### return reduce(possibilities)
return reduce(possibilities)
def example0():
cls = InterestingNumber()
input0 = "2002"
returns = "Interesting"
result = cls.isInteresting(input0)
return result == returns
def example1():
cls = InterestingNumber()
input0 = "1001"
returns = "Not interesting"
result = cls.isInteresting(input0)
return result == returns
def example2():
cls = InterestingNumber()
input0 = "41312432"
returns = "Interesting"
result = cls.isInteresting(input0)
return result == returns
def example3():
cls = InterestingNumber()
input0 = "611"
returns = "Not interesting"
result = cls.isInteresting(input0)
return result == returns
def example4():
cls = InterestingNumber()
input0 = "64200246"
returns = "Interesting"
result = cls.isInteresting(input0)
return result == returns
def example5():
cls = InterestingNumber()
input0 = "631413164"
returns = "Not interesting"
result = cls.isInteresting(input0)
return result == returns
if __name__ == '__main__':
print(example0()) |
from problem_utils import *
class ArrayHash:
def getHash(self, input):
input_array = input
# You will be given a String[] input .
# The value of each character in input is computed as follows: Value = (Alphabet Position) + (Element of input) + (Position in Element) All positions are 0-based.
# 'A' has alphabet position 0, 'B' has alphabet position 1, ...
# The returned hash is the sum of all character values in input .
# For example, if input = {"CBA", "DDD"} then each character value would be computed as follows: 2 = 2 + 0 + 0 : 'C' in element 0 position 0 2 = 1 + 0 + 1 : 'B' in element 0 position 1 2 = 0 + 0 + 2 : 'A' in element 0 position 2 4 = 3 + 1 + 0 : 'D' in element 1 position 0 5 = 3 + 1 + 1 : 'D' in element 1 position 1 6 = 3 + 1 + 2 : 'D' in element 1 position 2 The final hash would be 2+2+2+4+5+6 = 21.
pass
def example0():
cls = ArrayHash()
input0 = ["CBA", "DDD"]
returns = 21
result = cls.getHash(input0)
return result == returns
def example1():
cls = ArrayHash()
input0 = ["Z"]
returns = 25
result = cls.getHash(input0)
return result == returns
def example2():
cls = ArrayHash()
input0 = ["A", "B", "C", "D", "E", "F"]
returns = 30
result = cls.getHash(input0)
return result == returns
def example3():
cls = ArrayHash()
input0 = ["ABCDEFGHIJKLMNOPQRSTUVWXYZ", "ABCDEFGHIJKLMNOPQRSTUVWXYZ", "ABCDEFGHIJKLMNOPQRSTUVWXYZ", "ABCDEFGHIJKLMNOPQRSTUVWXYZ", "ABCDEFGHIJKLMNOPQRSTUVWXYZ", "ABCDEFGHIJKLMNOPQRSTUVWXYZ"]
returns = 4290
result = cls.getHash(input0)
return result == returns
def example4():
cls = ArrayHash()
input0 = ["ZZZZZZZZZZ"]
returns = 295
result = cls.getHash(input0)
return result == returns
if __name__ == '__main__':
print(example0())
|
from problem_utils import *
class BlockTower:
def getTallest(self, blockHeights):
input_array = blockHeights
N = len(input_array)
# Josh loves playing with blocks.
# Currently, he has N blocks, labeled 0 through N-1.
# The heights of all blocks are positive integers.
# More precisely, for each i, the height of block i is input_array[i].
# Josh is interested in making the tallest block tower possible.
# He likes all his towers to follow three simple rules:
# The labels of blocks used in the tower must increase from the bottom to the top.
# In other words, whenever Josh places box x on top of box y, we have x > y.
def valid0(possibility):
#### possibilities = top(possibility)
possibilities = cpairs(possibility)
#### def mapping(box): return >(* box)
def mapping(possibility): return gt(* possibility)
#### def reduce(box): return whenever(box)
def reduce(possibility): return all(possibility)
#### return reduce(map(mapping, possibilities))
return reduce(map(mapping, possibilities))
# Josh will never place a box of an even height on top of a box of an odd height.
def valid1(possibility):
#### possibilities = top(possibility)
possibilities = cpairs(possibility)
#### def mapping(possibility): return even(box[0])
def mapping(possibility): return is_even(possibility[0])
#### def valid(possibility): return odd(box[1])
def valid(possibility): return is_odd(possibility[1])
#### def reduce(possibility): return never(possibility)
def reduce(possibility): return not_(possibility)
#### return reduce(map(mapping, filter(valid, possibilities)))
return reduce(map(mapping, filter(valid, possibilities)))
# The height of the tower is simply the sum of heights of all its blocks.
def mapping0(possibility):
#### possibilities = possibility
possibilities = possibility
#### reduce = lambda possibility: sum(heights)
reduce = lambda possibility: sum(possibility)
#### return(reduce(possibilities))
return reduce(possibilities)
# You are given the int[] input_array.
# Return the height of the tallest possible block tower Josh can build.
#### possibilities = transformations(input_array)
possibilities = transformations(input_array)
#### def reduce(possibility): return tallest(tower)
def reduce(possibility): return max(possibility)
#### return reduce(map(mapping0, filter(valid1, filter(valid0, possibilities))))
return reduce(map(mapping0, filter(valid1, filter(valid0, possibilities))))
def example0():
cls = BlockTower()
input0 = [4,7]
returns = 11
result = cls.getTallest(input0)
return result == returns
def example1():
cls = BlockTower()
input0 = [7,4]
returns = 7
result = cls.getTallest(input0)
return result == returns
def example2():
cls = BlockTower()
input0 = [7]
returns = 7
result = cls.getTallest(input0)
return result == returns
def example3():
cls = BlockTower()
input0 = [4]
returns = 4
result = cls.getTallest(input0)
return result == returns
def example4():
cls = BlockTower()
input0 = [48,1,50,1,50,1,48]
returns = 196
result = cls.getTallest(input0)
return result == returns
def example5():
cls = BlockTower()
input0 = [49,2,49,2,49]
returns = 147
result = cls.getTallest(input0)
return result == returns
def example6():
cls = BlockTower()
input0 = [44,3,44,3,44,47,2,47,2,47,2]
returns = 273
result = cls.getTallest(input0)
return result == returns
if __name__ == '__main__':
print(example0()) |
from problem_utils import *
class InequalityChecker:
def getDifferences(self, n):
input_int = n
# Using mathematical induction it is possible to prove the following inequality when n >1: s = 13 + 23 + ... + (n-1)3 < n4/4 < 13 + 23 + ... + n3 = S Given n return (S+s)/2 - n 4 /4 as a int[] with 2 elements.
# Elements 0 and 1 denote the numerator and denominator of the return value, respectively, when written in least terms (reduced).
pass
def example0():
cls = InequalityChecker()
input0 = 2
returns = [ 1, 1 ]
result = cls.getDifferences(input0)
return result == returns
def example1():
cls = InequalityChecker()
input0 = 3
returns = [ 9, 4 ]
result = cls.getDifferences(input0)
return result == returns
def example2():
cls = InequalityChecker()
input0 = 100
returns = [ 2500, 1 ]
result = cls.getDifferences(input0)
return result == returns
if __name__ == '__main__':
print(example0())
|
from problem_utils import *
class FilipTheFrog:
def countReachableIslands(self, positions, L):
input_array = positions
input_int = L
# Filip the Frog lives on a number line.
# There are islands at some points on the number line.
# You are given the positions of these islands in the int[] positions .
# Filip starts on the island located at positions [0].
# His maximal jump length is L , which means that he can jump to any island that is within a distance of L (inclusive) from his current location.
# Filip can't jump to a point on the number line that doesn't contain an island.
# He can make an unlimited number of jumps.
# An island is reachable if Filip can get to it through some sequence of jumps.
rechable = lambda island: some(sequence(jumps))
# Please find and return the number of reachable islands.
return(number(reachable(islands)))
pass
def example0():
cls = FilipTheFrog()
input0 = [4, 7, 1, 3, 5]
input1 = 1
returns = 3
result = cls.countReachableIslands(input0, input1)
return result == returns
def example1():
cls = FilipTheFrog()
input0 = [100, 101, 103, 105, 107]
input1 = 2
returns = 5
result = cls.countReachableIslands(input0, input1)
return result == returns
def example2():
cls = FilipTheFrog()
input0 = [17, 10, 22, 14, 6, 1, 2, 3]
input1 = 4
returns = 7
result = cls.countReachableIslands(input0, input1)
return result == returns
def example3():
cls = FilipTheFrog()
input0 = [0]
input1 = 1000
returns = 1
result = cls.countReachableIslands(input0, input1)
return result == returns
if __name__ == '__main__':
print(example0())
|
from problem_utils import *
class FoxAndGame:
def countStars(self, result):
input_array = result
# Fox Ciel is playing the popular game 'Cut the Rope' on her smartphone.
# The game has multiple stages, and for each stage the player can gain between 0 and 3 stars, inclusive.
# You are given a String[] result containing Fox Ciel's current results: For each stage, result contains an element that specifies Ciel's result in that stage.
# More precisely, result [i] will be "---" if she got 0 stars in stage i, "o--" if she got 1 star, "oo-" if she got 2 stars and "ooo" if she managed to get all 3 stars.
# Return the total number of stars Ciel has at the moment.
pass
def example0():
cls = FoxAndGame()
input0 = ["ooo", "ooo"]
returns = 6
result = cls.countStars(input0)
return result == returns
def example1():
cls = FoxAndGame()
input0 = ["ooo", "oo-", "o--"]
returns = 6
result = cls.countStars(input0)
return result == returns
def example2():
cls = FoxAndGame()
input0 = ["ooo", "---", "oo-", "---", "o--"]
returns = 6
result = cls.countStars(input0)
return result == returns
def example3():
cls = FoxAndGame()
input0 = ["o--", "o--", "o--", "ooo", "---"]
returns = 6
result = cls.countStars(input0)
return result == returns
def example4():
cls = FoxAndGame()
input0 = ["---", "o--", "oo-", "ooo", "ooo", "oo-", "o--", "---"]
returns = 12
result = cls.countStars(input0)
return result == returns
def example5():
cls = FoxAndGame()
input0 = ["---", "---", "---", "---", "---", "---"]
returns = 0
result = cls.countStars(input0)
return result == returns
def example6():
cls = FoxAndGame()
input0 = ["oo-"]
returns = 2
result = cls.countStars(input0)
return result == returns
if __name__ == '__main__':
print(example0())
|
from problem_utils import *
from operator import *
from string import lowercase
class DifferentStrings:
def minimize(self, A, B):
input_array1 = A
input_array2 = B
N = min(len(input_array1),len(input_array2))
elements = lowercase
# If X and Y are two Strings of equal length N, then the difference between them is defined as the number of indices i where the i-th character of X and the i-th character of Y are different.
#### difference = lambda X: number(different(X[i], Y[i]) for i in indices(N))
mapping = lambda possibility: len(ne(possibility[i], input_array1[i]) for i in range(N))
# For example, the difference between the words "ant" and "art" is 1.
# You are given two Strings, A and B, where the length of A is less than or equal to the length of B.
# You can apply an arbitrary number of operations to A, where each operation is one of the following:
# Choose a character c and add it to the beginning of A.
# Choose a character c and add it to the end of A.
possibilities = csubsets(input_array2, N)
# Apply the operations in such a way that A and B have the same length and the difference between them is as small as possible.
# Return this minimum possible difference.
#### return(minimum([difference(possibility) for possibility in possibilities]))
return(min([mapping(possibility) for possibility in possibilities]))
if __name__ == '__main__':
A = "koder"
B = "topcoder"
ds = DifferentStrings()
print(ds.minimize(A, B)) |
from problem_utils import *
from string import lowercase
class CorruptedMessage:
def reconstructMessage(self, s, k):
input_array = s
input_int = k
N = len(input_array)
''' Your friend just sent you a message.'''
# The message consisted of one or more copies of the same lowercase letter.
def mapping(possibility):
#### reduce = lambda possibility: copies(possibility, N)
reduce = lambda possibility: mul(possibility, N)
#### return reduce(possibility)
return reduce(possibility)
# For example, "aaaaa" and "xxxxxxxxx" are valid messages.
# Unfortunately, on its way to you the message became corrupted: exactly k letters of the original message were changed to some other letters.
def valid(possibility):
#### reduce = lambda possibility: exactly(k, len(changed(message, possibility)))
reduce = lambda possibility: eq(k, len(diff(s, possibility)))
#### return reduce(possibility)
return reduce(possibility)
# The message you received is s .
# Given the String s and the int k , reconstruct the original message.
# More precisely, return a String that could have been the original message.
#### possibilities = lowercase
possibilities = lowercase
#### reduce = lambda possibility: min(possibility)
reduce = lambda possibility: min(possibility)
#### return min(filter(valid, map(mapping, possibilities)))
return reduce(filter(valid, map(mapping, possibilities)))
# It is guaranteed that at least one such String will always exist.
# If there are multiple possible answers, you may return any of them.
def example0():
cls = CorruptedMessage()
input0 = "hello"
input1 = 3
returns = "lllll"
result = cls.reconstructMessage(input0, input1)
return result == returns
def example1():
cls = CorruptedMessage()
input0 = "abc"
input1 = 3
returns = "ddd"
result = cls.reconstructMessage(input0, input1)
return result == returns
def example2():
cls = CorruptedMessage()
input0 = "wwwwwwwwwwwwwwwwww"
input1 = 0
returns = "wwwwwwwwwwwwwwwwww"
result = cls.reconstructMessage(input0, input1)
return result == returns
def example3():
cls = CorruptedMessage()
input0 = "ababba"
input1 = 3
returns = "aaaaaa"
result = cls.reconstructMessage(input0, input1)
return result == returns
def example4():
cls = CorruptedMessage()
input0 = "zoztxtoxytyt"
input1 = 10
returns = "oooooooooooo"
result = cls.reconstructMessage(input0, input1)
return result == returns
def example5():
cls = CorruptedMessage()
input0 = "jlmnmiunaxzywed"
input1 = 13
returns = "mmmmmmmmmmmmmmm"
result = cls.reconstructMessage(input0, input1)
return result == returns
if __name__ == '__main__':
print(example0()) |
from problem_utils import *
from operator import *
class IdentifyingWood:
def check(self, s, t):
input_array0 = s
input_array1 = t
# We call a pair of Strings (input_array0, input_array1) "wood" if input_array1 is contained in input_array0 as a subsequence.
def reduce0(possibility):
#### possibilities = possibility
possibilities = possibility
#### reduce = lambda possibility: contained(* possibility)
reduce = (lambda possibility: contains(* possibility))
#### return(reduce(possibilities))
return reduce(possibilities)
# (See Notes for a formal definition.)
# Given Strings input_array0 and input_array1, return the String "Yep, it'input_array0 wood." (quotes for clarity) if the pair (input_array0, input_array1) is wood and "Nope." otherwise.
#### possibilities = list([s, t])
possibilities = list([input_array0, input_array1])
#### reduce = lambda possibility: if(possibility, ["Yep, it's wood.", "Nope."]))
reduce = (lambda possibility: if_(possibility, ["Yep, it's wood.", "Nope."]))
#### return reduce(wood(possibilities))
return reduce(reduce0(possibilities))
def example0():
cls = IdentifyingWood()
input0 = "absdefgh"
input1 = "asdf"
returns = "Yep, it's wood."
result = cls.check(input0, input1)
return result == returns
def example1():
cls = IdentifyingWood()
input0 = "oxoxoxox"
input1 = "ooxxoo"
returns = "Nope."
result = cls.check(input0, input1)
return result == returns
def example2():
cls = IdentifyingWood()
input0 = "oxoxoxox"
input1 = "xxx"
returns = "Yep, it's wood."
result = cls.check(input0, input1)
return result == returns
def example3():
cls = IdentifyingWood()
input0 = "qwerty"
input1 = "qwerty"
returns = "Yep, it's wood."
result = cls.check(input0, input1)
return result == returns
def example4():
cls = IdentifyingWood()
input0 = "string"
input1 = "longstring"
returns = "Nope."
result = cls.check(input0, input1)
return result == returns
if __name__ == '__main__':
print(example0()) |
from problem_utils import *
from operator import *
import numpy
class Elections:
def visit(self, likelihoods):
input_array = likelihoods
N = len(input_array)
# There are two candidates campaigning to be president of a country.
# From newspaper polls, it is clear what percentages of people plan to vote for each candidate in each state.
# Candidate 1 wants to campaign in one last state, and needs to figure out which state that should be.
# You are given a String[] likelihoods, each element of which corresponds to a state.
possibilities = range(N)
# Each element consists of the characters '1' and '2', where '1' represents some number of votes for candidate 1, and '2' represents votes for candidate 2 (in each element every character represents the same number of votes).
types = ['1','2']
# You are to return an int representing the 0-based index of the state where the lowest percentage of people are planning on voting for candidate 1 (lowest percentage of '1' characters in that element of the input). If there are multiple such states, return one with the lowest index in likelihoods.
#### mapping = lambda state: percentage(likelihoods[state], '1')
mapping = lambda possibility: percentage(input_array[possibility], types[0])
#### valid = lambda state: where(mapping(state), lowest(mapping(state) for state in likelihoods))
valid = lambda possibility: eq(mapping(possibility), min(mapping(possibility1) for possibility1 in range(N)))
#### return(lowest([state for state in possibilities if valid(state)]))
return(min([possibility for possibility in possibilities if valid(possibility)]))
# mapping = lambda possibility: percentage(possibility, '1')
# return(indexOf(map(mapping,input_array), min(map(mapping,input_array))))
# If there are multiple such states, return one with the lowest index in likelihoods.
if __name__ == '__main__':
likelihoods = ["1222","1122","1222"]
e = Elections()
print(e.visit(likelihoods)) |
from problem_utils import *
from operator import *
class HammingDistance:
def minDistance(self, numbers):
input_array = numbers
N = len(input_array[0])
# The Hamming distance between two input_array is defined as the number of positions in their binary representations at which they differ (leading zeros are used if necessary to make the binary representations have the same length) -
def mapping0(possibility):
#### possibilities = range(N)
possibilities = range(N)
#### def valid(numbers): return differ(numbers[0][positions], numbers[1][positions])
def valid(possibility0): return ne(possibility[0][possibility0], possibility[1][possibility0])
#### def reduce(possibility0): return number(possibility0)
def reduce(possibility0): return len(possibility0)
#### return reduce(filter(valid, numbers))
return reduce(filter(valid, possibilities))
# e.g., the input_array "11010" and "01100" differ at the first, third and fourth positions, so they have a Hamming distance of 3.
# You will be given a String[] input_array containing the binary representations of some input_array (all having the same length).
# You are to return the minimum among the Hamming distances of all pairs of the given input_array.
#### possibilities = pairs(numbers)
possibilities = pairs(input_array)
#### def reduce(possibility): return minimum(possibility)
def reduce(possibility): return min(possibility)
#### return reduce(map(hamming_distances, possibilities))
return reduce(map(mapping0, possibilities))
def example0():
cls = HammingDistance()
input0 = ["11010", "01100"]
returns = 3
result = cls.minDistance(input0)
return result == returns
def example1():
cls = HammingDistance()
input0 = ["00", "01", "10", "11"]
returns = 1
result = cls.minDistance(input0)
return result == returns
def example2():
cls = HammingDistance()
input0 = ["000", "011", "101", "110"]
returns = 2
result = cls.minDistance(input0)
return result == returns
def example3():
cls = HammingDistance()
input0 = ["01100", "01100", "10011"]
returns = 0
result = cls.minDistance(input0)
return result == returns
def example4():
cls = HammingDistance()
input0 = ["00000000000000000000000000000000000000000000000000", "11111111111111111111111111111111111111111111111111"]
returns = 50
result = cls.minDistance(input0)
return result == returns
def example5():
cls = HammingDistance()
input0 = ["000000", "000111", "111000", "111111"]
returns = 3
result = cls.minDistance(input0)
return result == returns
if __name__ == '__main__':
print(example0()) |
class FingerCounting:
def maxNumber(self, weakFinger, maxCount):
input_int1 = weakFinger
input_int2 = maxCount
# Your little son is counting numbers with his left hand.
# Starting with his thumb and going toward his pinky, he counts each finger in order.
# After counting his pinky, he reverses direction and goes back toward his thumb.
# He repeats this process until he reaches his target number.
# He never skips a finger.
# For example, to count to ten, he would count: thumb, index, middle, ring, pinky, ring, middle, index, thumb, index.
inf =1000
fingers = [1, 2, 3, 4, 5, 4, 3, 2]*inf
# Sadly, one of his fingers hurts and he can only count on it a limited number of times.
# His fingers are numbered 1 through 5 from thumb to pinky.
# You are given an int weakFinger, the finger that hurts, and an int maxCount, the maximum number of times he can use that finger.
valid = lambda(i): fingers[:i].count(input_int1) <= input_int2
#Return the largest number he can count to.
#### return(largest(number for number in range(inf) if valid(number)))
return(max(i for i in range(inf) if valid(i)))
#If he cannot even begin counting, return 0.
# if can_begin else 0
if __name__ == '__main__':
weakFinger, maxCount = [2,3]
fc = FingerCounting()
print(fc.maxNumber(weakFinger, maxCount))
|
from problem_utils import *
from operator import *
class LCMRange:
def lcm(self, first, last):
input_int0 = first
input_int1 = last
inf = 1000
# The least common multiple of a group of integers is the smallest number that can be evenly divided by all the integers in the group.
def reduce0(possibility):
#### possibilities = number(1,inf)
possibilities = range(1, inf)
#### def valid(possibility0): return all(evenly_divided(possibility1, number) for possibility1 in possibility)
def valid(possibility0): return all((is_divisor(possibility1, possibility0) for possibility1 in possibility))
#### def reduce(possibility1): return smallest(possibility0)
def reduce(possibility0): return min(possibility0)
#### return reduce(filter(valid, possibilities))
return reduce(filter(valid, possibilities))
# Given two ints, input_int0 and input_int1, find the least common multiple of all the numbers between input_int0 and input_int1, inclusive.
#### possibilities = between(first, inclusive(last))
possibilities = range(input_int0, inclusive(input_int1))
#### find(least_common_multiple(possibilities))
return reduce0(possibilities)
def example0():
first, last = 1,5
lcmr = LCMRange()
result = lcmr.lcm(first, last)
returns = 60
return result == returns
if __name__ == '__main__':
print(example0()) |
from problem_utils import *
class RugSizes:
def rugCount(self, area):
input_int = area
ways = list(combinations_with_replacement(range(inclusive(area)), 2))
# Rugs come in various sizes.
# In fact, we can find a rug with any integer width and length, except that no rugs have a distinct width and length that are both even integers.
def valid(rug):
#### reduce = lambda possibility: no((distinct(*rug) and both(possibility)))
reduce = (lambda possibility: not_((ne(*rug) and all(possibility))))
#### mapping = lambda integer: even(integer)
mapping = (lambda integer: is_even(integer))
#### possibilities = rug
possibilities = rug
#### return(reduce(map(mapping, possibilities)))
return reduce(map(mapping, possibilities))
# For example, we can find a 4x4 rug, but not a 2x4 rug.
# We want to know how many different choices we have for a given area.
# Create a class RugSizes the contains a method rugCount that is given the desired area and returns the number of different ways in which we can choose a rug size that will cover that exact area.
#
# Do not count the same size twice -- a 6 x 9 rug and a 9 x 6 rug should be counted as one choice.
def example0():
cls = RugSizes()
input0 = 4
returns = 2
result = cls.rugCount(input0)
return result == returns
def example1():
cls = RugSizes()
input0 = 8
returns = 1
result = cls.rugCount(input0)
return result == returns
if __name__ == '__main__':
print(example0()&example1()) |
# A partir del ejercicio anterior, vamos a suponer que cada número es una nota, y lo que queremos es obtener la nota final.
# El problema es que cada nota tiene un valor porcentual:
# La primera nota vale un 15% del total.
# La segunda nota vale un 35% del total.
# La tercera nota vale un 50% del total.
nota_1 = 10
nota_2 = 7
nota_3 = 4
nota_1 = (nota_1*15) / 100
nota_2 = (nota_2*35) / 100
nota_3 =(nota_3*50) / 100
nota_final = nota_1 + nota_2 + nota_3
print(nota_final)
# Otra solución del ejercicio
nota_final = (nota_1 * 0.15) + (nota_2 * 0.35) + (nota_3 * 0.50)
print("La nota final es", nota_final) |
import turtle
import time
import random
delay = 0.1
# ate rate
ate = 0
topaterate = 0
# play field
window = turtle.Screen()
window.title("Pysnakegame by @shohan")
window.bgcolor("blue")
window.setup(width=650, height=650)
window.tracer(0)
# lets make the snake
head = turtle.Turtle()
head.speed(0)
head.shape("square")
head.color("black")
head.penup()
head.goto(0, 0)
head.direction = "stop"
#food
food = turtle.Turtle()
food.speed(0)
food.shape("circle")
food.color("red")
food.penup()
food.goto(0, 50)
segments = []
# Score
pen = turtle.Turtle()
pen.speed(0)
pen.shape("square")
pen.color("white")
pen.penup()
pen.hideturtle()
pen.goto(0, 260)
pen.write("Ate: 0 Top Ate Rate: 0", align="center", font=("Courier", 24, "normal"))
# adding function
def go_up():
if head.direction != "down":
head.direction = "up"
def go_down():
if head.direction != "up":
head.direction = "down"
def go_left():
if head.direction != "right":
head.direction = "left"
def go_right():
if head.direction != "left":
head.direction = "right"
def move():
if head.direction == "up":
y = head.ycor()
head.sety(y + 20)
if head.direction == "down":
y = head.ycor()
head.sety(y - 20)
if head.direction == "left":
x = head.xcor()
head.setx(x - 20)
if head.direction == "right":
x = head.xcor()
head.setx(x + 20)
window.listen()
window.onkeypress(go_up, "w")
window.onkeypress(go_down, "s")
window.onkeypress(go_left, "a")
window.onkeypress(go_right, "d")
#game loop
while True:
window.update()
# touch the border and u r dead
if head.xcor() > 290 or head.xcor() < -290 or head.ycor() > 290 or head.ycor() < -290:
time.sleep(1)
head.goto(0,0)
head.direction = "stop"
# hide the segments
for segment in segments:
segment.goto(1000, 1000)
# clear the segment/body
segments.clear()
# reset the ate
ate = 0
# reset the ate
delay = 0.1
pen.clear()
pen.write("Ate: {} Top Ate Rate: {}".format(ate, topaterate), align="center", font=("Courier", 24, "normal"))
if head.distance(food) < 20:
#move the food randomly
x = random.randint(-290, 290)
y = random.randint(-290, 290)
food.goto(x,y)
# make the snake grow
new_segment = turtle.Turtle()
new_segment.speed(0)
new_segment.shape("square")
new_segment.color("yellow")
new_segment.penup()
segments.append(new_segment)
# minimizing the delay
delay += 0.001
# top ate rate
ate += 10
if ate > topaterate:
topaterate = ate
pen.clear()
pen.write("Ate: {} Top Ate Rate: {}". format(ate, topaterate),align="center", font=("Courier", 24, "normal"))
# track the snake body
for index in range(len(segments)-1, 0, -1):
x = segments[index-1].xcor()
y = segments[index-1].ycor()
segments[index].goto(x, y)
if len(segments) > 0:
x = head.xcor()
y = head.ycor()
segments[0].goto(x,y)
move()
# don't eat urself
for segment in segments:
if segment.distance(head) < 20:
time.sleep(1)
head.goto(0,0)
head.direction = "stop"
# hide the segments
for segment in segments:
segment.goto(1000, 1000)
# clear the segment/body
segments.clear()
# reset the ate
ate = 0
# reset the ate
delay = 0.1
pen.clear()
pen.write("Ate: {} Top Ate Rate: {}".format(ate, topaterate), align="center", font=("Courier", 24, "normal"))
time.sleep(delay)
window.mainloop()
|
def collatz(number):
if number % 2 == 0:
return number//2
elif number % 2 ==1 :
return 3*number+1
try:
print("Enter number:")
input_name = int(input())
while True:
input_name=collatz(input_name)
print(input_name)
if input_name ==1:
break
except ValueError:
print("Input format if incorrect, please enter an integer!")
|
print("*****************************List Ends**************************************")
my_list = [5, 10, 15, 20, 25]
def list_end():
return [my_list[0], my_list[-1]]
new_list = list_end()
print(new_list)
|
# Without using set
my_list = [1, 2, 3, 4, 3, 2, 1]
def remove_dup1():
new_list = []
for i in my_list:
if i not in new_list:
new_list.append(i)
return new_list
print(remove_dup1())
# By using set
def remove_dup2(x):
return list(set(x))
print(remove_dup2(my_list))
|
# Masukkan angka
angka = int(input("Masukkan angka "))
# Cek angka 1
if angka % 2 == 0 and angka != 0:
print(angka, "angka genap")
elif angka % 2 != 0:
print(angka, "angka ganjil")
else:
print(angka, "bukan genap maupun ganijl")
# Cek angka 2
if angka < 0:
print(angka, "angka negatif")
elif angka == 0:
print(angka, "bukan negatif maupun positif")
else:
print(angka, "angka positif")
# Cek angka 3
if angka > 1:
for i in range(2, angka):
if (angka % i) == 0:
print(angka, "bukan prima")
break
else:
print(angka, "angka prima")
else:
print(angka, "bukan prima")
|
''' script to run yardsale data through the google api to
get the longitude and latitude
'''
import Util
from keys import key
# load the data as JSON lines
# get lng/lat for each post's address
# save as new JSON lines so compass can access
def AttachGeoData():
infilename = 'server/gatherer/post_data/yardsales.jl'
outfilename = 'server/sale_data/yardsales.jl'
print("Loading json data from " + infilename)
post_data = Util.load_post_data(infilename)
print("Finding address coordinates for %s address" % post_data.__len__())
for pid, post in enumerate(post_data):
post['coords'] = Util.get_coords_of_address(post['address'], key)
post['id'] = pid
print(post)
print("filter out address that google maps couldn't find easily")
post_data = filter(lambda x: x['coords'] is not None, post_data)
Util.save_post_data(post_data, outfilename)
print("Printing new json to " + outfilename)
if __name__=="__main__":
AttachGeoData()
|
x = 10
y = 5
x = x ^ y;
y = x ^ y;
x = x ^ y;
print ("After Swapping: x = ",x ," y =", y)
|
a=int(input("Enter a number"))
l=[]
count=0
for i in range(0,a):
b=int(input("Enter number"))
l.append(b)
count+=1
if(count%2==0):
print("yes")
els:
print("no")
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.