text
stringlengths 37
1.41M
|
---|
import numpy as np
def knn(vector, matrix, k=10):
"""
Finds the k-nearest rows in the matrix with comparison to the vector.
Use the cosine similarity as a distance metric.
Arguments:
vector -- A D dimensional vector
matrix -- V x D dimensional numpy matrix.
Return:
nearest_idx -- A numpy vector consists of the rows indices of the k-nearest neighbors in the matrix
"""
dot_prod = np.matmul(matrix, vector)
norm_matrix = np.linalg.norm(matrix, 2, 1)
norm_vector = np.linalg.norm(vector, 2)
norm_prod = norm_matrix * norm_vector
cosine_sim = dot_prod / norm_prod
np.argpartition(cosine_sim, -k)
nearest_idx = np.argpartition(cosine_sim, -k)[-k:]
return nearest_idx
def test_knn():
"""
Use this space to test your knn implementation by running:
python knn.py
This function will not be called by the autograder, nor will
your tests be graded.
"""
print "Running your tests..."
# YOUR CODE HERE
indices = knn(np.array([0.2, 0.5]), np.array([[0, 0.5], [0.1, 0.1], [0, 0.5], [2, 2], [4, 4], [3, 3]]), k=2)
assert 0 in indices and 2 in indices and len(indices) == 2
# END YOUR CODE
if __name__ == "__main__":
test_knn()
|
#Protein Translation Problem: Translate an RNA string into an amino acid string.
#Input: An RNA string "Pattern"
#Output: The translation of "Pattern" into an amino acid string "Peptide"
def translate(pattern):
translation_table = create_translation_table()
peptide = ""
i = 0
while i < len(pattern) - 2:
current_substring = pattern[i:i+3]
if translation_table[current_substring] == None:
break
peptide += translation_table[current_substring]
i += 3
return peptide
#Creates a table for translating RNA chunks into a peptide string
def create_translation_table():
translation_table = {}
with open('codon_table.txt') as lines:
for line in lines:
tokens = line.split()
codon = tokens[0]
if len(tokens) > 1:
translation = tokens[1]
translation_table[codon] = translation
else:
translation_table[tokens[0]] = None
lines.close()
return translation_table
def test():
RNA_string = "AUGGCCAUGGCGCCCAGAACUGAGAUCAAUAGUACCCGUAUUAACGGGUGA"
expected_peptide = "MAMAPRTEINSTRING"
assert translate(RNA_string) == expected_peptide
if __name__ =="__main__":
test()
|
# class Solution:
# def climbStairs(self, n: int) -> int:
# if n == 1 or n == 2:
# return n
# l = [1 for i in range(n)]
# l[1] = 2
# for i in range(2, n):
# l[i] = l[i - 1] + l[i - 2]
# print(l)
# return l[n - 1]
class Solution:
def climbStairs(self, n: int) -> int:
if n == 1 or n == 2:
return n
a = 1
b = 2
for i in range(2,n):
l = a+b
a = b
b = l
return l
if __name__ == '__main__':
s = Solution()
s.climbStairs(3)
|
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def rightSideView(self, root: TreeNode) -> List[int]:
if root == None:
return []
now_nodes = [root]
next_nodes = []
result = [root.val]
while True:
for nd in now_nodes:
if nd.left != None:
next_nodes.append(nd.left)
if nd.right != None:
next_nodes.append(nd.right)
if next_nodes == []:
return result
else:
result.append(next_nodes[-1].val)
now_nodes = next_nodes
next_nodes = []
|
class Solution:
def exist(self, board, word: str):
n = len(board)
m = len(board[0])
def get_ans(board, i, j, t):
if t == len(word):
return True
if i < 0 or i >= n or j < 0 or j >= m:
return False
if board[i][j] == word[t]:
board[i][j] = None
r = get_ans(board, i, j - 1, t + 1) or get_ans(board, i, j + 1, t + 1) or get_ans(board, i - 1, j,t + 1) or get_ans(board, i + 1, j, t + 1)
board[i][j] = word[t]
return r
for i in range(n):
for j in range(m):
if get_ans(board, i, j, 0):
return True
return False
if __name__ == '__main__':
s = Solution()
r = s.exist([["C", "A", "A"],
["A", "A", "A"],
["B", "C", "D"]], "AAB")
print(r)
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Dec 22 20:50:55 2020
@author: john
"""
class net():
def __init__(self):
self.encoder = Encoder()
self.model = self.create_model()
def create_model(self):
"""function to create a model for making prediction"""
pass
def predict(self, model_input):
"""function to pass input to the model and return its output"""
# Should return a dictionary of move-prior pairs and the value from
# the network's value head
pass
def save_network(self):
# Should save the model and return a string containing a command
# that can be used for creating the correct net object with correct
# Encoder object.
pass
def load_network(self):
pass
def Encoder():
def __init__(self):
pass
def encode(self, game_state):
# Should return a tensor representing the game_state that can be
# passed to the network model as input
pass
def encode_priors(self, priors):
# Should return a tensor representing the given probability
# distribution (created from visit counts) over moves which can be
# used as a training label for the network model
pass
def expand_data(self, X, Y):
# Should increase the size of the training data X and Y using board
# symmeteries. Can just return X, Y to avoid implementing this.
pass
|
import copy
class Grid():
def __init__(self, gridSize):
try:
gridSize = int(gridSize)
except ValueError:
raise ValueError("Error: gridSize is not a number!")
if gridSize <= 1:
raise ValueError("Error: gridSize must be greater then 1!")
self.gridSize = gridSize
self.grid = [[None for _ in range(self.gridSize)] for _ in range(self.gridSize)]
self.reset()
def setPos(self, x, y, value = 0):
self.__checkInput(x, y)
self.grid[int(x)-1][int(y)-1] = value
def getPos(self, x, y):
self.__checkInput(x, y)
return copy.deepcopy(self.grid[int(x)-1][int(y)-1])
def toString(self):
temp = ""
for x in range(0, self.gridSize):
for y in range(0, self.gridSize):
if y != self.gridSize-1:
temp = temp + str(self.grid[x][y]) + "|"
else:
temp = temp + str(self.grid[x][y]) + "\n"
for i in range(0, self.gridSize):
if i != self.gridSize-1:
temp = temp + "-|"
else:
temp = temp + "-\n"
return temp
def reset(self):
for x in range(0, self.gridSize):
for y in range(0, self.gridSize):
self.setPos(x = x+1, y = y+1)
def __checkInput(self, x, y):
#---checking for vaild input---
try:
x = int(x)
except ValueError:
raise ValueError("Error: x is not a number!")
try:
y = int(y)
except ValueError:
raise ValueError("Error: y is not a number!")
if x < 1 or x > self.gridSize:
raise ValueError("Error: x is outside the grid!")
if y < 1 or y > self.gridSize:
raise ValueError("Error: y is outside the grid!")
#---vaild input check done---
if __name__ == "__main__":
raise RuntimeError("Error: Must use this class as a dependent!")
|
# tuples using filter
def Remove(tuples):
tuples = filter(None, tuples)
return tuples
# Driver Code
tuples = [(), ('ram', '15', '8'), (), ('laxman', 'sita'),
('krishna', 'akbar', '45'), ('', ''), ()]
print(Remove(tuples))
|
# To find next gap from current
def getNextGap(gap):
# Shrink gap by Shrink factor
gap = (gap * 10) / 13
if gap < 1:
return 1
return gap
# Function to sort arr[] using Comb Sort
def combSort(arr):
n = len(arr)
# Initialize gap
gap = n
swapped = True
while gap != 1 or swapped == 1:
# Find next gap
gap = getNextGap(gap)
swapped = False
# Compare all elements with current gap
for i in range(0, n - gap):
if arr[i] > arr[i + gap]:
arr[i], arr[i + gap] = arr[i + gap], arr[i]
swapped = True
# Driver code to test above
arr = [8, 4, 1, 3, -44, 23, -6, 28, 0]
combSort(arr)
print("Sorted array:")
for i in range(len(arr)):
print(arr[i])
|
from collections import defaultdict
def end_check(word):
sub1 = word.strip()[0]
sub2 = word.strip()[-1]
temp = sub1 + sub2
return temp
def front_check(word):
sub = word.strip()[1:-1]
return sub
# initializing string
test_str = 'best and bright'
# printing original string
print("The original string is : " + str(test_str))
# Group Similar Start and End character words
# Using defaultdict() + loop
test_list = test_str.split()
res = defaultdict(set)
for ele in test_list:
res[end_check(ele)].add(front_check(ele))
# printing result
print("The grouped dictionary is : " + str(dict(res)))
|
def check(string):
if len(set(string).intersection("AEIOUaeiou")) >= 5:
return ('accepted')
else:
return ("not accepted")
# Driver code
if __name__ == "__main__":
string = "geeksforgeeks"
print(check(string))
|
# list of numbers
list1 = [-10, -21, -4, -45, -66, 93, 11]
pos_count, neg_count = 0, 0
num = 0
# using while loop
while (num < len(list1)):
# checking condition
if list1[num] >= 0:
pos_count += 1
else:
neg_count += 1
# increment num
num += 1
print("Positive numbers in the list: ", pos_count)
print("Negative numbers in the list: ", neg_count)
|
def shellSort(arr):
# Start with a big gap, then reduce the gap
n = len(arr)
gap = n / 2
while gap > 0:
for i in range(gap, n):
temp = arr[i]
j = i
while j >= gap and arr[j - gap] > temp:
arr[j] = arr[j - gap]
j -= gap
# put temp (the original a[i]) in its correct location
arr[j] = temp
gap /= 2
# Driver code to test above
arr = [12, 34, 54, 2, 3]
n = len(arr)
print("Array before sorting:")
for i in range(n):
print(arr[i]),
shellSort(arr)
print("\nArray after sorting:")
for i in range(n):
print(arr[i])
|
# Returns length of string
def findLen(str):
if not str:
return 0
else:
some_random_str = 'py'
return ((some_random_str).join(str)).count(some_random_str) + 1
str = "geeks"
print(findLen(str))
|
def cocktailSort(a):
n = len(a)
swapped = True
start = 0
end = n - 1
while (swapped == True):
swapped = False
for i in range(start, end):
if (a[i] > a[i + 1]):
a[i], a[i + 1] = a[i + 1], a[i]
swapped = True
# if nothing moved, then array is sorted.
if (swapped == False):
break
swapped = False
end = end - 1
for i in range(end - 1, start - 1, -1):
if (a[i] > a[i + 1]):
a[i], a[i + 1] = a[i + 1], a[i]
swapped = True
start = start + 1
# Driver code to test above
a = [5, 1, 4, 2, 8, 0, 2]
cocktailSort(a)
print("Sorted array is:")
for i in range(len(a)):
print("%d" % a[i])
|
l = [l for l in input("List:").split(",")]
print("The list is ", l)
# Assign first element as a minimum.
min1 = l[0]
for i in range(len(l)):
# If the other element is min than first element
if l[i] < min1:
min1 = l[i] # It will change
print("The smallest element in the list is ", min1)
|
import numpy as np
from gensim.models import Word2Vec
def create_word2vec_matrix(data_loader, min_count=20, size=100, window_size=3):
"""
Arguments
---------
`data_loader`: `list`-like
A `list` (or `list` like object), each item of which is itself a list of tokens.
For example:
[
['this', 'is', 'sentence', 'one'],
['this', 'is', 'sentence', 'two.']
]
Note that preprocesisng.DataLoader is exactly this kind of object.
`min_count`: `int`
The minimum count that a token has to have to be included in the vocabulary.
`size`: `int`
The dimensionality of the word vectors.
`window_size`: `int`
The window size. Read the assignment pdf if you don't know what that is.
Returns
-------
`tuple(np.ndarray, dict)`:
The first element will be an (V, `size`) matrix, where V is the
resulting vocabulary size.
The second element is a mapping from `int` to `str` of which word
in the vocabulary corresponds to which index in the matrix.
"""
word2vec_mat = None
word2vec_id_to_tokens = {}
####### Your code here ###############
model = Word2Vec(data_loader, min_count=min_count,size= size,workers=3, window =window_size, sg = 1)
model.save('model.model')
#model = Word2Vec.load("model.model")
vocab = list(model.wv.vocab)
word2vec_mat = model.wv.vectors
i = 0
for item in vocab:
word2vec_id_to_tokens[i] = item
i =i+1
####### End of your code #############
return word2vec_mat, word2vec_id_to_tokens
def create_term_newsgroup_matrix(
newsgroup_and_token_ids_per_post,
id_to_tokens,
id_to_newsgroups,
tf_idf_weighing=False,
):
"""
Arguments
---------
newsgroup_and_token_ids_per_post: `list`
Each item will be a `tuple` of length 2.
Each `tuple` contains a `list` of token ids(`int`s), and a newsgroup id(`int`)
Something like this:
newsgroup_and_token_ids_per_post=[
([0, 54, 3, 6, 7, 7], 0),
([0, 4, 7], 0),
([0, 463, 435, 656, ], 1),
]
The "newsgroup_and_token_ids_per_post" that main.read_processed_data() returns
is exactly in this format.
id_to_tokens: `dict`
`int` token ids as keys and `str` tokens as values.
{ 0: "hi", 1: "hello" ...}
id_to_newsgroups: `dict`
`int` newsgroups ids as keys and `str` newsgroups as values.
{ 0: "comp.graphics", 1: "comp.sys.ibm.pc.hardware" .. }
tf_idf_weighing: `bool`
Whether to use TF IDF weighing in returned matrix.
Returns
-------
`np.ndarray`:
Shape will be (len(id_to_tokens), len(id_to_newsgroups)).
That is it will be a VxD matrix where V is vocabulary size and D is number of newsgroups.
Note, you may choose to remove the row corresponding to the "UNK" (which stands for unknown)
token.
"""
V = len(id_to_tokens)
D = len(id_to_newsgroups)
#print(V,D)
mat = np.zeros((V,D))
#print(mat.shape)
####### Your code here ###############
for item in newsgroup_and_token_ids_per_post:
ngroup = id_to_newsgroups[item[1]]
token = item[0]
for tok_id in token:
mat[tok_id][item[1]] = mat[tok_id][item[1]] + 1
####### End of your code #############
if tf_idf_weighing:
# mat_trim = np.copy(mat[:10,:])
tf_mat = np.copy(mat)
tf_mat[tf_mat > 0] = 1 + np.log(tf_mat[tf_mat > 0])
df = (mat != 0).sum(1)
idf_mat = np.log(len(id_to_newsgroups)/df)
idf_mat = np.reshape(idf_mat, (idf_mat.shape[0], 1))
tf_idf_mat = tf_mat * idf_mat
# print(tf_idf_mat[0:5])
# print(id_to_tokens[2])
# print(id_to_tokens[4])
return tf_idf_mat
return mat
def create_term_context_matrix(
newsgroup_and_token_ids_per_post,
id_to_tokens,
id_to_newsgroups,
ppmi_weighing=False,
window_size=5,
):
"""
Arguments
---------
newsgroup_and_token_ids_per_post: `list`
Each item will be a `tuple` of length 2.
Each `tuple` is a post, contains a `list` of token ids(`int`s), and a newsgroup id(`int`)
Something like this:
newsgroup_and_token_ids_per_post=[
([0, 54, 3, 6, 7, 7], 0),
([0, 4, 7], 0),
([0, 463, 435, 656, ], 1),
]
The "newsgroup_and_token_ids_per_post" that main.read_processed_data() returns
is exactly in this format.
id_to_tokens: `dict`
`int` token ids as keys and `str` tokens as values.
{ 0: "hi", 1: "hello ...}
id_to_newsgroups: `dict`
`int` newsgroups ids as keys and `str` newsgroups as values.
{ 0: "hi", 1: "hello ...}
{ 0: "comp.graphics", 1: "comp.sys.ibm.pc.hardware" .. }
ppmi_weighing: `bool`
Whether to use PPMI weighing in returned matrix.
Returns
-------
`np.ndarray`:
Shape will be (len(id_to_tokens), len(id_to_tokens)).
That is it will be a VxV matrix where V is vocabulary size.
Note, you may choose to remove the row/column corresponding to the "UNK" (which stands for unknown)
token.
"""
V = len(id_to_tokens)
mat = np.zeros((V,V))
####### Your code here ###############
count = 0
for item in newsgroup_and_token_ids_per_post:
item = item[0]
for i in range(len(item)):
low = i - window_size
if(low<0):
low = 0
upper = i + window_size
for j in range(len(item)):
if(j>=low and j<=upper):
if item[i] == item[j]:
#print('is all good',item[i],item[j])
mat[item[i]][item[j]] = 0
else:
mat[item[i]][item[j]] += 1
if ppmi_weighing:
ppmi_mat = np.copy(mat)
total = np.sum(ppmi_mat)
col_sum = ppmi_mat.sum(axis=0)/total
row_sum = ppmi_mat.sum(axis=1)/total
row_sum = np.reshape(row_sum, (row_sum.shape[0], 1))
col_sum = np.reshape(col_sum, (1, col_sum.shape[0]))
ppmi_mat = ppmi_mat/total
ppmi_mat = ppmi_mat/row_sum
ppmi_mat[np.isnan(ppmi_mat)] = 0
ppmi_mat = ppmi_mat/col_sum
ppmi_mat[np.isnan(ppmi_mat)] = 0
ppmi_mat[ppmi_mat == 0] = 0.00000001
ppmi_mat = np.log(ppmi_mat)
ppmi_mat[ppmi_mat < 0] = 0
#print(ppmi_mat)
return ppmi_mat
####### End of your code #############
return mat
def compute_cosine_similarity(a, B):
"""Cosine similarity.
Arguments
---------
a: `np.ndarray`, (M,)
B: `np.ndarray`, (N, M)
Returns
-------
`np.ndarray` (N,)
The cosine similarity between a and every
row in B.
"""
vals = []
####### Your code here ###############
for b in B:
cos = np.dot(a,b) / (np.sqrt(np.dot(a,a)) * np.sqrt(np.dot(b,b)))
vals.append(cos)
return vals
####### End of your code #############
def compute_jaccard_similarity(a, B):
"""
Arguments
---------
a: `np.ndarray`, (M,)
B: `np.ndarray`, (N, M)
Returns
-------
`np.ndarray` (N,)
The Jaccard similarity between a and every
row in B.
"""
####### Your code here ###############
vals = []
for b in B:
s1 = set(a)
s2 = set(b)
sim = len(s1.intersection(s2)) / len(s1.union(s2))
vals.append(sim)
####### End of your code #############
return vals
def compute_dice_similarity(a, B):
"""
stolen : 0.17904197
weapons : 0.17657003
and : 0.27388635
answer : 0.12892626
no : 0.1688911
it : 0.32679212
s : 0.19813703
total : 0.28250358
good : 0.22370566
point : 0.0052258903
Arguments
---------
a: `np.ndarray`, (M,)
B: `np.ndarray`, (N, M)
Returns
-------
`np.ndarray` (N,)
The Dice similarity between a and every
row in B.
"""
val = []
####### Your code here ###############
for b in B:
intersection = np.logical_and(a, b)
sim = 2 * intersection.sum() / (a.sum() + b.sum())
val.append(sim)
####### End of your code #############
return val
|
Python 3.6.8 (tags/v3.6.8:3c6b436a57, Dec 23 2018, 23:31:17) [MSC v.1916 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> print(abs(10))
10
>>> print(abs(-10))
10
>>> steps = -3
>>> is abs(steps) > 0:
SyntaxError: invalid syntax
>>> steps = -3
>>> if abs(steps) > 0:
print('Character is moving')
Character is moving
>>> steps = -3
>>> if steps < 0 or steps > 0:
print('Character is moving')
Character is moving
>>> print(bool(0))
False
>>> print(bool(1))
True
>>> print(bool(1123.23))
True
>>> print(bool(-500))
True
>>> print(bool(None))
False
>>> print(bool('a'))
True
>>> print(npp;s(' '))
SyntaxError: invalid syntax
>>> print(bool(' '))
True
>>> print(bool('What do you call a pig doing karate? Pork Chop!'))
True
>>> my_silly_list = []
>>> print(bool(my_silly_list))
False
>>> my_silly_list = ['s', 'i', 'l', 'l', 'y']
>>> print(bool(my_silly_list))
True
>>> year = input ('Year of birth: ')
Year of birth:
>>> if not bool (year.rstrip()):
print('You need to enter a value for your year of birth')
You need to enter a value for your year of birth
>>>
>>>
>>> dir(['a', 'short', 'list'])
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
>>> dir(1)
['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__', '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floor__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getnewargs__', '__gt__', '__hash__', '__index__', '__init__', '__init_subclass__', '__int__', '__invert__', '__le__', '__lshift__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__round__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'bit_length', 'conjugate', 'denominator', 'from_bytes', 'imag', 'numerator', 'real', 'to_bytes']
>>> popcorn = 'Ilove popcorn!'
>>> dir(popcorn)
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
>>> help(popcorn.upper)
Help on built-in function upper:
upper(...) method of builtins.str instance
S.upper() -> str
Return a copy of S converted to uppercase.
>>>
>>>
>>> eval('10*5')
50
>>> eval('''if True:
print("this won't work at all")''')
Traceback (most recent call last):
File "<pyshell#42>", line 2, in <module>
print("this won't work at all")''')
File "<string>", line 1
if True:
^
SyntaxError: invalid syntax
>>> your_calculation = input('Enter a calculation:')
Enter a calculation:eval(your_calculation)
>>> your_calculation = input('Enter a calculation:')
Enter a calculation:12*52
>>> eval(your_calculation)
624
>>>
>>>
>>> my_small_program = '''print('ham')
print('sandwhich')'''
>>> exec(my_small_program)
Traceback (most recent call last):
File "<pyshell#50>", line 1, in <module>
exec(my_small_program)
File "<string>", line 2
print('sandwhich')
^
IndentationError: unexpected indent
>>> my_small_program = '''print('ham')
print('sandwhich')'''
>>> exec(my_small_program)
ham
sandwhich
>>>
>>>
>>>
>>> float('12')
12.0
>>> float ('123.456789')
123.456789
>>>
>>>
>>> your_age = input('Enter your age:')
Enter your age:20
>>> age = float(your_age)
>>> if age > 13:
print('You are %s years too old' % (age -13))
You are 7.0 years too old
>>>
>>>
>>> int('123')
123
>>> int ('123.456')
Traceback (most recent call last):
File "<pyshell#69>", line 1, in <module>
int ('123.456')
ValueError: invalid literal for int() with base 10: '123.456'
>>> len('this is a test string')
21
>>> creature_list = ['unicorn', 'cyclops', 'fairy', 'elf', 'dragon', 'troll']
>>> print(len(creature_list))
6
>>> enemies_map {'Batman' : 'Joker', 'Superman' : 'Lex Luthor', 'Spiderman' : 'Green Goblin'.}
SyntaxError: invalid syntax
>>> enemies_map = {'Batman' : 'Joker', 'Superman' : 'Lex Luthor', 'Spiderman' : 'Green Goblin'}
>>> print(len(enemies_map))
3
>>> fruit = ['apple', 'banana', 'clementine', 'dragon fruit']
>>> length = len(fruit)
>>> for x in range(0, length):
print('the fruit at index %s is %s' % (x, fruit[x]))
the fruit at index 0 is apple
the fruit at index 1 is banana
the fruit at index 2 is clementine
the fruit at index 3 is dragon fruit
>>>
>>>
>>> numbers = [5, 4, 10, 30, 22]
>>> print(max_numbers))
SyntaxError: invalid syntax
>>> print(max(numbers))
30
>>> strings = 's,t,r,i,n,g,S,T,R,I,N,G'
>>> print(max(strings))
t
>>> print(max(10,300,450,50,90))
450
>>> numbers = [5, 4, 10, 30, 22]
>>> print)min(numbers))
SyntaxError: invalid syntax
>>> print(min(numbers))
4
>>> guess_this_numbers = 61
>>> player_guesses = [12, 15, 70, 45]
>>> if max(player_guesses) > guess_this_number:
print('Boom! You all lose')
else:
print:('You win')
Traceback (most recent call last):
File "<pyshell#98>", line 1, in <module>
if max(player_guesses) > guess_this_number:
NameError: name 'guess_this_number' is not defined
>>> guess_this_number = 61
>>> player_guesses = [12, 15, 70, 45]
>>> if max(player_guesses) > guess_this_number:
print('Boom! You all lose')
else:
print('You win')
Boom! You all lose
>>>
>>>
>>>
>>> for x in range (0,5):
print(x)
0
1
2
3
4
>>> print(list(range(0,5))))
SyntaxError: invalid syntax
>>> print(list(range(0,5)))
[0, 1, 2, 3, 4]
>>> count_by_twos = list(range(0,30,2))
>>> print(count_by_twos)
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28]
>>> countdown_by_twos = list(range(40,10,-2))
>>> print(count_down_by_twos)
Traceback (most recent call last):
File "<pyshell#117>", line 1, in <module>
print(count_down_by_twos)
NameError: name 'count_down_by_twos' is not defined
>>> count_down_by_twos = list(range(40,10,-2))
>>> print(count_down_by_twos)
[40, 38, 36, 34, 32, 30, 28, 26, 24, 22, 20, 18, 16, 14, 12]
>>> my_list_of_numbers = list(range(0,500,50))
>>> print(my_list_of_numbers)
[0, 50, 100, 150, 200, 250, 300, 350, 400, 450]
>>> print(sum(my_list_of_numbers))
2250
>>>
|
Python 3.6.8 (tags/v3.6.8:3c6b436a57, Dec 23 2018, 23:31:17) [MSC v.1916 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> age = 13
>>> if age > 20:
print('You are too old!')
>>> age = 25
>>> if age > 20:
print('You are too old!')
print('Why are you here?')
print('Why aren\'t you mowing the lawn or sorting papers?')
You are too old!
Why are you here?
Why aren't you mowing the lawn or sorting papers?
>>> age = 25
>>> if age > 20:
print('You are too old!')
print('Why are you here?')
print('Why aren\'t you mowing the lawn or sorting papers?')
You are too old!
Why are you here?
Why aren't you mowing the lawn or sorting papers?
>>> if age > 20:
print('You are too old!')
print('Why are you here?')
SyntaxError: unexpected indent
>>> age = 10
>>> if age > 10:
print('You are too old for my jokes!')
>>> age = 10
>>> if age >= 10:
print('You are too old for my jokes!')
You are too old for my jokes!
>>> age = 10
>>> if age 10 == 10:
SyntaxError: invalid syntax
>>> if age == 10:
print('What\'s brown and sticky? A strick!!')
What's brown and sticky? A strick!!
>>> print("Want to hear a dirty joke?")
Want to hear a dirty joke?
>>> age = 12
>>> if age == 12:
print("A pig fell in the mud!")
else:
print("Shh. It's a secret.")
A pig fell in the mud!
>>> print("Want to hear a dirty joke?")
Want to hear a dirty joke?
>>> age = 8
>>> if age == 12:
print("A pig fell in the mud!")
else:
print("Shh. It's a secret.")
Shh. It's a secret.
>>> age = 12
>>> if age == 10:
print("What do you call an unhappy cranberry?")
print("A blueberry!")
elif age == 11:
print("What did the green grape say to the blue grape?")
print("Breathe! Breathe!")
elif age == 12:
print("What did 0 say to 8?")
print("Hi guys!")
elif age == 13:
print("Why wasn't 10 afraid of 7?")
print("Because rather than eating 9, 8 7 pi.")
else:
print("Huh?")
What did 0 say to 8?
Hi guys!
>>>
|
"""
Example: Specific cancer that occurs to 1% of population P(c) = 0.01
Test for this cancer with a 90% chance is positive if you have this cancer (this is sensitivity of the test)
But the test is sometimes is positive even if you don't have a cancer C.
Let's say with another 90% chance is negative if you don't have cancer C (this is specificity of the test)
Question: the prior probability of cancer is 1%, and a sensitivity and specificity are 90%,
what's the probability that someone with a positive cancer test actually has the disease?
Bayes theorem states the following:
Posterior = Prior * Likelihood
This can also be stated as P (A | B) = (P (B | A) * P(A)) / P(B) , where P(A|B) is the probability of A given B, also called posterior.
Prior: Probability distribution representing knowledge or uncertainty of a data object prior or before observing it
Posterior: Conditional probability distribution representing what parameters are likely after observing the data object
Likelihood: The probability of falling under a specific category or class.
Prior MULT Test Evidence ==> Posterior
"""
# Prior
P_c = 0.01
P_nonC = 1 - P_c
print("P(-C) = ", P_nonC)
# Test sensitivity
P_pos_cancer = 0.9
P_pos_nonC = 1 - P_pos_cancer
print("P(Pos/-C) = ", P_pos_nonC)
P_neg_nonC = 0.9
# Posterior cancer JOINT
P_c_pos = P_c * P_pos_cancer
print("P(C/Pos) JOINT = ", P_c_pos)
# Posterior NON cancer
P_nonC_pos = P_nonC * P_pos_nonC
print("P(-C/Pos) JOINT = ", P_nonC_pos)
# Normalizer
Norm = P_c_pos + P_nonC_pos
print("Normalizer = ", Norm)
# Posterior with normalizerRRR
P_c_pos_norm = P_c_pos / Norm
P_nonC_pos_norm = P_nonC_pos / Norm
print("The probability that someone with a positive cancer test actually has the disease P(C/Pos) = ", P_c_pos_norm)
print("P(-C/Pos) = ", P_nonC_pos_norm)
total = P_c_pos_norm + P_nonC_pos_norm
print("Total = ", total)
|
from typing import List
##################################################
# BINARY SEARCH
def search(nums: List[int], target: int) -> int:
"""
704. Binary Search
Given an array of integers nums which is sorted in ascending order,
and an integer target, write a function to search target in nums.
If target exists, then return its index. Otherwise, return -1.
You must write an algorithm with O(log n) runtime complexity.
"""
if nums is None:
return -1
if len(nums) == 1:
if target == nums[0]:
return 0
else:
return -1
left_idx = 0
right_idx = len(nums)
mid_idx = int((left_idx + right_idx) / 2)
while (right_idx != left_idx and mid_idx >= left_idx and mid_idx <= right_idx):
mid_idx = int((left_idx + right_idx) / 2)
print(mid_idx)
if nums[mid_idx] == target:
return mid_idx;
elif target < nums[mid_idx]:
right_idx = right_idx - 1
elif target > nums[mid_idx]:
left_idx = left_idx + 1
return -1
def firstBadVersion(n: int) -> int:
"""
278. First Bad Version
Suppose you have n versions [1, 2, ..., n] and you want to find out the first bad one,
which causes all the following ones to be bad.
You are given an API bool isBadVersion(version) which returns whether version is bad.
Implement a function to find the first bad version. You should minimize the number of calls to the API.
Input: n = 5, bad = 4
Output: 4
Explanation:
call isBadVersion(3) -> false
call isBadVersion(5) -> true
call isBadVersion(4) -> true
Then 4 is the first bad version.
# The isBadVersion API is already defined for you.
# def isBadVersion(version: int) -> bool:
"""
if n == 1:
return (1 if isBadVersion(n) else -1)
low = 1
high = n
while(low <= high):
mid = (low + high)//2
if isBadVersion(mid) and not isBadVersion(mid-1):
return mid
elif isBadVersion(mid) and isBadVersion(mid-1):
high = mid-1
elif not isBadVersion(mid):
low = mid+1
return -1
def searchInsert(self, nums: List[int], target: int) -> int:
"""
Given a sorted array of distinct integers and a target value,
return the index if the target is found. If not, return the index
where it would be if it were inserted in order."""
low = 0
high = len(nums) - 1
while low <= high:
mid= (low + high) // 2
if nums[mid] == target:
return mid
elif target < nums[mid]:
high = mid - 1
else:
low = mid + 1
return low
|
#1. Merge sort
def MergeSort(array):
temp=[0]*len(array) #new a temp list to store temporary result in the merge process
def sort(a,left,right,temp):
if left<right:
mid=(left+right)//2
sort(a,left,mid,temp) #sort the left side
sort(a,mid+1,right,temp) #sort the right side
merge(a,left,mid,right,temp) # merge the left side and right side together
def merge(ar,left,mid,right,temp):
i=left
j=mid+1
tmp_p=0
while(i<=mid and j<=right):
if ar[i]<=ar[j]:
temp[tmp_p]=ar[i]
i+=1
else:
temp[tmp_p]=ar[j]
j+=1
tmp_p+=1
while(i<=mid):
temp[tmp_p]=ar[i]
i+=1
tmp_p+=1
while(j<=right):
temp[tmp_p]=ar[j]
j+=1
tmp_p+=1
for index in range(right-left+1):
ar[left+index]=temp[index]
sort(array,0,len(array)-1,temp)
#2. One-diemensional poset problem---- calculate the number of reverse order pairs(ROP)
# The basic idea is to split into left and right part, then calculate ROP of the left and right and sort them, the sum=left+right+mergeresult
# reference: https://blog.csdn.net/DERRANTCM/article/details/46761051
def CDQReverOrderCal(array):
temp=[0]*len(array)
def CDQ(ar,left,right,temp):
if left<right:
mid=(left+right)//2
leftside=CDQ(ar,left,mid,temp) #reverse order pair number in the left side
rightside=CDQ(ar,mid+1,right,temp) #reverse order pair number in the right side
middle=merge(ar,left,mid,right,temp) # newly generated reverse order pair between left and right side
return leftside+rightside+middle
else:
return 0
def merge(ar,left,mid,right,temp):
p=mid
q=right
tmp_p=len(temp)-1
count=0
while(p>=left and q>=mid+1):
if ar[p]>ar[q]:
count+=q-mid #important, if left pointed value greater than the right pointed value, then the reverse order pair number is the from right pointer to the head of the right part.
temp[tmp_p]=ar[p]
p-=1
else:
temp[tmp_p]=ar[q]
q-=1
tmp_p-=1
while p>=left:
temp[tmp_p]=ar[p]
tmp_p-=1
p-=1
while q>=mid+1:
temp[tmp_p]=ar[q]
tmp_p-=1
q-=1
ar[left:right+1]=temp[tmp_p+1:]
return count
return CDQ(array,0,len(array)-1,temp)
#3. Two-diemensional poset problem---- CDQ divide and conquer algorithm
#def CDQ(left,right):
# if left==right:
# return
# mid=(L+R)//2
# CDQ(left,mid)
# CDQ(mid+1,right)
# Handling the influence of left CDQ to the right part
#4. Binary indexed tree 树状数组 reference: https://blog.csdn.net/Yaokai_AssultMaster/article/details/79492190
class BinaryIndexTree:
def __init__(self,inputlist):
self.ori=inputlist
self.bit=self.construct_tree(self.ori) #binary index tree
def construct_tree(self,input):
ans=[0]+input
for index in range(1,len(ans)):
next=index+(index&(-index))
if next<len(ans):
ans[next]=ans[next]+ans[index]
return ans
def prefixsum(self,idx): # the top idx sum
current=idx
ans=0
while(current>0):
ans+=self.bit[current]
current=current-(current&(-current))
return ans
def update(self,idx,value): #change idx index of origin to value
difference=value-self.bit[idx+1]
current=idx+1
while current<len(self.bit):
self.bit[current]+=difference
current=current+(current&(-current))
def rangesum(self,idx1,idx2):
return self.prefixsum(idx2)-self.prefixsum(idx1)
#5. Segmentation tree 线段树
if __name__=="__main__":
array=[6,9,1,12,4,8,28,0]
array2=[7,5,6,4]
array3=[6, 5, 4, 3, 2, 1]
BITarray=[1,7,3,0,7,8,3,2,6,2,1,1,4,5]
arrayBit=[1,7,3,0,5,8,3,2,6,2,1,1,4,5]
#MergeSort(array)
#print(array)
#print(CDQReverOrderCal(array3))
Bit=BinaryIndexTree(arrayBit)
print(Bit.bit)
Bit.update(4,7)
print(Bit.bit)
|
"""
Various functions for finding/manipulating silence in AudioSegments
"""
import itertools
from .utils import db_to_float
def detect_silence(audio_segment, min_silence_len=1000, silence_thresh=-16, seek_step=1):
"""
Returns a list of all silent sections [start, end] in milliseconds of audio_segment.
Inverse of detect_nonsilent()
audio_segment - the segment to find silence in
min_silence_len - the minimum length for any silent section
silence_thresh - the upper bound for how quiet is silent in dFBS
seek_step - step size for interating over the segment in ms
"""
seg_len = len(audio_segment)
# you can't have a silent portion of a sound that is longer than the sound
if seg_len < min_silence_len:
return []
# convert silence threshold to a float value (so we can compare it to rms)
silence_thresh = db_to_float(silence_thresh) * audio_segment.max_possible_amplitude
# find silence and add start and end indicies to the to_cut list
silence_starts = []
# check successive (1 sec by default) chunk of sound for silence
# try a chunk at every "seek step" (or every chunk for a seek step == 1)
last_slice_start = seg_len - min_silence_len
slice_starts = range(0, last_slice_start + 1, seek_step)
# guarantee last_slice_start is included in the range
# to make sure the last portion of the audio is searched
if last_slice_start % seek_step:
slice_starts = itertools.chain(slice_starts, [last_slice_start])
for i in slice_starts:
audio_slice = audio_segment[i:i + min_silence_len]
if audio_slice.rms <= silence_thresh:
silence_starts.append(i)
# short circuit when there is no silence
if not silence_starts:
return []
# combine the silence we detected into ranges (start ms - end ms)
silent_ranges = []
prev_i = silence_starts.pop(0)
current_range_start = prev_i
for silence_start_i in silence_starts:
continuous = (silence_start_i == prev_i + seek_step)
# sometimes two small blips are enough for one particular slice to be
# non-silent, despite the silence all running together. Just combine
# the two overlapping silent ranges.
silence_has_gap = silence_start_i > (prev_i + min_silence_len)
if not continuous and silence_has_gap:
silent_ranges.append([current_range_start,
prev_i + min_silence_len])
current_range_start = silence_start_i
prev_i = silence_start_i
silent_ranges.append([current_range_start,
prev_i + min_silence_len])
return silent_ranges
def detect_nonsilent(audio_segment, min_silence_len=1000, silence_thresh=-16, seek_step=1):
"""
Returns a list of all nonsilent sections [start, end] in milliseconds of audio_segment.
Inverse of detect_silent()
audio_segment - the segment to find silence in
min_silence_len - the minimum length for any silent section
silence_thresh - the upper bound for how quiet is silent in dFBS
seek_step - step size for interating over the segment in ms
"""
silent_ranges = detect_silence(audio_segment, min_silence_len, silence_thresh, seek_step)
len_seg = len(audio_segment)
# if there is no silence, the whole thing is nonsilent
if not silent_ranges:
return [[0, len_seg]]
# short circuit when the whole audio segment is silent
if silent_ranges[0][0] == 0 and silent_ranges[0][1] == len_seg:
return []
prev_end_i = 0
nonsilent_ranges = []
for start_i, end_i in silent_ranges:
nonsilent_ranges.append([prev_end_i, start_i])
prev_end_i = end_i
if end_i != len_seg:
nonsilent_ranges.append([prev_end_i, len_seg])
if nonsilent_ranges[0] == [0, 0]:
nonsilent_ranges.pop(0)
return nonsilent_ranges
def split_on_silence(audio_segment, min_silence_len=1000, silence_thresh=-16, keep_silence=100,
seek_step=1):
"""
Returns list of audio segments from splitting audio_segment on silent sections
audio_segment - original pydub.AudioSegment() object
min_silence_len - (in ms) minimum length of a silence to be used for
a split. default: 1000ms
silence_thresh - (in dBFS) anything quieter than this will be
considered silence. default: -16dBFS
keep_silence - (in ms or True/False) leave some silence at the beginning
and end of the chunks. Keeps the sound from sounding like it
is abruptly cut off.
When the length of the silence is less than the keep_silence duration
it is split evenly between the preceding and following non-silent
segments.
If True is specified, all the silence is kept, if False none is kept.
default: 100ms
seek_step - step size for interating over the segment in ms
"""
# from the itertools documentation
def pairwise(iterable):
"s -> (s0,s1), (s1,s2), (s2, s3), ..."
a, b = itertools.tee(iterable)
next(b, None)
return zip(a, b)
if isinstance(keep_silence, bool):
keep_silence = len(audio_segment) if keep_silence else 0
output_ranges = [
[ start - keep_silence, end + keep_silence ]
for (start,end)
in detect_nonsilent(audio_segment, min_silence_len, silence_thresh, seek_step)
]
for range_i, range_ii in pairwise(output_ranges):
last_end = range_i[1]
next_start = range_ii[0]
if next_start < last_end:
range_i[1] = (last_end+next_start)//2
range_ii[0] = range_i[1]
return [
audio_segment[ max(start,0) : min(end,len(audio_segment)) ]
for start,end in output_ranges
]
def detect_leading_silence(sound, silence_threshold=-50.0, chunk_size=10):
"""
Returns the millisecond/index that the leading silence ends.
audio_segment - the segment to find silence in
silence_threshold - the upper bound for how quiet is silent in dFBS
chunk_size - chunk size for interating over the segment in ms
"""
trim_ms = 0 # ms
assert chunk_size > 0 # to avoid infinite loop
while sound[trim_ms:trim_ms+chunk_size].dBFS < silence_threshold and trim_ms < len(sound):
trim_ms += chunk_size
# if there is no end it should return the length of the segment
return min(trim_ms, len(sound))
|
'''
2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
@author: Matt
'''
def multiples(n):
for i in range(2,20): # increment by 20, so no need to check for 20. Could count backwards to imrpove response time
if n % (i+1) != 0:
return False
return True
start = 19 # 2nd highest multiple to check
while (True):
if multiples(20*start): # increment by 20
print(20*start)
break
else:
start += 1
|
def add(num1, num2):
return num1+num2
def subs(num1, num2):
return num1-num2
def multi(num1 , num2):
return num1*num2
def div(num1, num2):
return num1/num2
select = input("Select the operation of Calci:")
num1 = int(input("Enter the number 1:"))
num2 = int(input("Enter the number 2:"))
if select == '1':
print(add(num1,num2))
elif select == '2':
print(subs(num1,num2))
elif select == '3':
print(multi(num1, num2))
elif select == '4':
print(div(num1, num2))
else:
print("Invalid Input")
|
#For loop learning
cars = ['Toyota', 'Honda']
for car in cars: #bring Toyota & Honda out
print(car)
names = ['Thomas', 'Jakc', 'Tom']
for name in names:
print(name)
#exercise
students = ['Allen', 'Tom', 'Mayday', 'JJ', 'Jolin', 'Jay', 'Jam']
for student in students:
print('Hi ', student)
#str as list
book = 'Harry'
for c in book: #['H', 'a', 'r', 'r', 'y']
print(c)
|
__author__ = 'Sergey Khrul'
from math import sqrt
def solve (a, b, c):
d = b * b - 4 * a * c
if d < 0:
return "No solution"
elif d == 0:
return "One solution: {}".format(-b / (2 * a))
elif d > 0:
x1 = (-b + sqrt(d)) / (2 * a)
x2 = (-b - sqrt(d)) / (2 * a)
return "Two solutions: {} and {}".format(x1, x2)
else:
return "Exception!!"
print(solve(1, 1, 1))
print(solve(1, 2, 1))
print(solve(1, 5, 6))
|
#!/usr/bin/python
#coding=utf-8
import sys
import os
#python3只有input,由于input返回是string,所以需要用int转
try:
lin1=int(input('请输入第一条边:'))
lin2=int(input('请输入第二条边:'))
lin3=int(input('请输入第三条边:'))
# {}是占位符,format函数对数据格式化
except Exception:
print ("不支持小数")
else:
print('周长是{}'.format(lin1+lin2+lin3))
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Functions for cleaning up text, typically from bad OCR scans."""
import itertools
import string
from typing import Tuple, List, Dict, Set, Iterable, TypeVar
from text_cleanup import parse
from text_cleanup import utils
A = TypeVar('A') # pylint: disable=invalid-name
B = TypeVar('B') # pylint: disable=invalid-name
# These are common substitution errors and we should prefer to stay within the
# group when making corrections.
ERROR_GROUPS = (
'jli!1t',
'aceo',
'3B',
'hmn',
'yug',
'MNH',
'BERPD',
'QO0',
)
def build_index(groups: Iterable[str]) -> Dict[str, str]:
"""Return dict from elem to group, given iter of groups of elems."""
tmp: Dict[str, List[str]] = {}
for group in groups:
for letter in group:
tmp.setdefault(letter, []).append(group)
return {k: ''.join(v) for k, v in tmp.items()}
PREFERRED_ERRORS = build_index(ERROR_GROUPS)
def get_valid_words(filename=None) -> Set[str]:
"""Return set of valid words, read from filename if present."""
with open(filename or '/usr/share/dict/words') as fin:
words = fin.read().splitlines()
# Remove one-letter words that aren't 'a', 'A' or 'I'.
valid = set(w for w in words if len(w) > 1 or w in 'aAI')
# Allow any word to be capitalized, since it might start a sentence.
valid.update(w.capitalize() for w in words if w[0].islower())
return valid
WORDS = get_valid_words()
def spellcheck(wordstr: str) -> bool:
"""Return true if wordstr is made of valid words, else False."""
quick = (
not wordstr or
wordstr.endswith('-') or
parse.NUMBER_RE.fullmatch(wordstr) or
wordstr in WORDS)
if quick:
return True
hyphenated = wordstr.replace('-', ' ').split()
return hyphenated[0] != wordstr and all(map(spellcheck, hyphenated))
def one_space(word: str) -> Iterable[str]:
"""Yield words made by inserting a single space into word."""
for i in range(1, len(word)):
yield word[:i] + ' ' + word[i:]
def one_deletion(word: str) -> Iterable[str]:
"""Yield words made by deleting a single letter from word."""
for i in range(len(word)):
yield word[:i] + word[i+1:]
def one_insertion(word: str) -> Iterable[str]:
"""Yield words made by inserting a single letter into word."""
alphabet = string.ascii_lowercase
# Add letter before current letter
for i in range(len(word)):
for newchar in alphabet:
yield word[:i] + newchar + word[i:]
# Add letter at end
for newchar in alphabet:
yield word + newchar
def one_substitution(word: str) -> Iterable[str]:
"""Yield words made by substituting a single letter in word."""
# Check for any preferred errors before trying brute force substitution
for i, letter in enumerate(word):
for newchar in PREFERRED_ERRORS.get(letter, ''):
if newchar != letter:
yield word[:i] + newchar + word[i+1:]
# No luck... time to brute force
alphabet = string.ascii_lowercase
for i, letter in enumerate(word):
# Change letter by trying entire alphabet
for newchar in alphabet:
if newchar != letter:
yield word[:i] + newchar + word[i+1:]
def one_error(word: str,
space: bool = True,
substitution: bool = True,
insertion: bool = True,
deletion: bool = True) -> Iterable[str]:
"""Yield one-error variations on word."""
# Rewrapping text can leave unnecesarry hyphenations like 'mini-mize'
unhyphenated = word.replace('-', '')
if unhyphenated != word:
yield unhyphenated
# Missing spaces seems most common, so check all possible splits first
if space:
yield from one_space(word)
if substitution:
yield from one_substitution(word)
if deletion:
yield from one_deletion(word)
if insertion:
yield from one_insertion(word)
def correct_misspelling(given: str,
errors=2,
space=True,
avoid_capitalized_words=False,
**kwargs) -> Tuple[bool, str]:
"""Return (bool, guess), True when guess is a known good word."""
first_letter = given[0]
rest = given[1:]
# If it starts with 'I' or 'A', split it if the result is valid.
if rest and space and first_letter in 'IA' and spellcheck(rest):
return True, f'{first_letter} {rest}'
# Ignore other words starting with capital letters
if avoid_capitalized_words:
if first_letter.isupper():
return True, given
if spellcheck(given):
return True, given
# Lazily generate all possible corrections, retuning the first good one.
def func(words):
for word in words:
yield from one_error(word, space=space, **kwargs)
result_iter = utils.iterate(func, iter([given]), errors)
candidates: Iterable[str] = itertools.chain.from_iterable(result_iter)
for word in candidates:
if spellcheck(word):
return True, word
return False, given
def cleanup(given: str, **kwargs) -> str:
"""Return a corrected version of given text."""
# Re-wrapped text can rejoin lines broken at hyphens, but then you have
# extra spaces in there, e.g. "mini- mize"
given = given.replace('- ', '-')
def silent_fix(wordmatch):
return correct_misspelling(wordmatch.group(), **kwargs)[1]
return parse.TOKEN_RE.sub(silent_fix, given)
|
"""
Conversion Utilities
====================
Contains a number of conversion utilities for converting objects.
For example, ``from_dict_to_csv`` will convert a sorted dictionary to a csv file
Notes
------
#. Should These be in files.py?
"""
import csv
import pandas as pd
# ------------- #
# - CSV Files - #
# ------------- #
def from_dict_to_csv(dictionary, fl, header=['key', 'value'], target_dir='csv/'):
"""
Write a sorted Python Dictionary to CSV
Parameters
----------
dictionary : dict
Some dictionary of data
fl : str
Specify a file name
header : list(str), optional(default=['key', 'value'])
Provide Headers for csv file
target_dir : str, optional(default="csv/")
Looks for a local ``csv/`` directory
"""
fl = open(target_dir + fl, 'wb')
writer = csv.writer(fl)
writer.writerow(header)
tmp = []
for key, value in dictionary.items():
tmp.append((key, value))
tmp = sorted(tmp)
for key, value in tmp:
writer.writerow([key, value])
fl.close()
# ------------ #
# - Py Files - #
# ------------ #
def from_series_to_pyfile(series, target_dir='data/', fl=None, docstring=None):
"""
Construct a ``py`` formated file from a Pandas Series Object
This is useful when wanting to generate a python list for inclusion in the package
Parameters
---------
series : pd.Series (that has an index)
The Pandas Series to Convert
target_dir : str, optional(default="data/")
Specify a Target Directory
fl : str, optional(default=None)
specify a filename, otherwise one will be generated
docstring : str, optional(default=None)
specify a docstring at the top of the file
Warning
-------
Ensure `series` is named (using the ``.name`` attribute) what you would like the variable to be named in the file
Example
-------
s = pd.Series([1,2,3,4])
will write a file with: s.name = [ 1,
2,
...
]
Notes
-----
#. Should ``series`` in the function be changed to ``idxseries``?
"""
if type(series) != pd.Series:
raise TypeError("series: must be a pd.Series")
doc_string = u'\"\"\"\n%s\nManual Check: <date>\n\"\"\"\n\n' % docstring # DocString
items = u'%s = [' % series.name.replace(' ', '_') # Replace spaces with _
once = True
for idx, item in enumerate(series.values):
# - Newline and Tabbed Spacing for Vertical List of Items - #
tabs = 4
if once == True:
items += "\n"
once = False
items += '\t'*tabs + '\'' + '%s'%item + '\'' + ',' + '\n'
doc = doc_string + items + ']\n'
if type(fl) in [str, unicode]:
# Write to Disk #
f = open(target_dir+fl, 'w')
f.write(doc)
f.close()
else:
return doc
def from_idxseries_to_pydict(series, target_dir='data/', fl=None, docstring=None, verbose=False):
"""
Construct a ``py`` file containing a Dictionary from an Indexed Pandas Series Object
This is useful when wanting to generate a python list for inclusion in the package
Parameters
---------
series : pd.Series (that has an index)
The Pandas Series to Convert
target_dir : str, optional(default="data/")
Specify a Target Directory
fl : str, optional(default=None)
specify a filename, otherwise one will be generated
docstring : str, optional(default=None)
specify a docstring at the top of the file
Warning
-------
Ensure `series` is named (using the ``.name`` attribute) what you would like the variable to be named in the file
Example
-------
s.name = { index : value,
... etc.
}
"""
if type(series) != pd.Series:
raise TypeError("series: must be a pd.Series with an Index")
docstring = u'\"\"\"\n%s\nManual Check: <date>\n\"\"\"\n\n' % docstring # DocString
items = u'%s = {' % series.name.replace(' ', '_') # Replace spaces with _
once = True
for idx, val in series.iteritems():
# - Newline and Tabbed Spacing for Vertical List of Items - #
tabs = 4
if once == True:
items += "\n"
once = False
items += '\t'*tabs + '\'' + '%s'%idx + '\'' + ' : ' + '\'' + '%s'%str(val).replace("'", "\\'") + '\'' + ',' + '\n' #Repalce Internal ' with \'
doc = docstring + items + '}\n'
if type(fl) in [str, unicode]:
# Write to Disk #
if verbose: print "[INFO] Writing file: %s" % (target_dir+fl)
f = open(target_dir+fl, 'w')
f.write(doc)
f.close()
else:
return doc
|
# Currency converter by Urmil Shroff
import bs4
import requests
res = requests.get("http://dollarrupee.in/")
soup = bs4.BeautifulSoup(res.text, "lxml")
rate = soup.select(".item-page p strong") # selects the ruppee value
rupee = float(rate[0].text)
print("Today's rate: $1 = ₹{}".format(rupee))
print("What do you want to convert?")
print("1. Dollars to Rupees")
print("2. Rupees to Dollars")
choice = int(input())
if(choice == 1):
amount = int(input("Enter amount in USD: "))
print("Today's conversion: ${} = ₹{} (approx.)".format(
amount, round(amount * rupee)))
elif(choice == 2):
amount = int(input("Enter amount in INR: "))
print("Today's conversion: ₹{} = ${} (approx.)".format(
amount, round(amount / rupee)))
else:
print("Bad choice!")
|
"""
Capstone Project. Code to run on a LAPTOP (NOT the robot).
Displays the Graphical User Interface (GUI) and communicates with the robot.
Authors: Your professors (for the framework)
and Zixin Fan.
Spring term, 2018-2019.
"""
# DONE 1: Put your name in the above.
import tkinter
from tkinter import ttk
import mqtt_remote_method_calls as mqtt
import m2_laptop_code as m2
import m3_laptop_code as m3
def get_my_frame(root, window, mqtt_sender):
# Construct your frame:
frame = ttk.Frame(window, padding=10, borderwidth=5, relief="ridge")
frame_label = ttk.Label(frame, text="Zixin")
frame_label.grid()
# DONE 2: Put your name in the above.
# Add the rest of your GUI to your frame:
# DONE: Put your GUI onto your frame (using sub-frames if you wish).
entry_distance = ttk.Entry(frame, width = 8)
entry_distance.grid()
entry_distance.insert(0, '12')
entry_speed = ttk.Entry(frame, width = 8)
entry_speed.grid()
entry_speed.insert(0, '100')
entry_delta = ttk.Entry(frame, width = 8)
entry_delta.grid()
entry_delta.insert(0, 5)
button_forward = ttk.Button(frame, text = "Forward")
button_forward.grid()
button_forward['command'] = lambda: Handle_forward(mqtt_sender, entry_distance, entry_speed, entry_delta)
button_backward = ttk.Button(frame, text = "Backward")
button_backward.grid()
button_backward['command'] = lambda : Handle_backward(mqtt_sender, entry_distance, entry_speed, entry_delta)
entry_until_distance = ttk.Entry(frame, width = 8)
entry_until_distance.grid()
entry_until_distance.insert(0, '40')
button_until_distance = ttk.Button(frame, text = "Go until Distance")
button_until_distance.grid()
button_until_distance['command'] = lambda: Handle_go_until_distance(mqtt_sender, entry_until_distance, entry_speed, entry_delta)
# Return your frame:
return frame
def Handle_forward(mqtt_sender, entry_distance, entry_speed, entry_delta):
distance = int(entry_distance.get())
print('The robot goes forward', distance)
speed = int(entry_speed.get())
print('with speed', speed)
print()
delta = int(entry_delta.get())
mqtt_sender.send_message('Forward_or_Backward', [distance, speed, delta])
def Handle_backward(mqtt_sender, entry_distance, entry_speed, entry_delta):
distance = int(entry_distance.get())
print('The robot goes backward', distance)
speed = int(entry_speed.get())
print('with speed', speed)
print()
delta = int(entry_delta.get())
mqtt_sender.send_message('Forward_or_Backward', [- distance, - speed, delta])
def Handle_go_until_distance(mqtt_sender, entry_until_distance, entry_speed, entry_delta):
until_distance = int(entry_until_distance.get())
print('The robot goes until distance', until_distance)
speed = int(entry_speed.get())
print('with initial speed', speed)
print()
delta = int(entry_delta.get())
mqtt_sender.send_message('Go_until_distance', [until_distance, speed, delta])
class MyLaptopDelegate(object):
"""
Defines methods that are called by the MQTT listener when that listener
gets a message (name of the method, plus its arguments)
from the ROBOT via MQTT.
"""
def __init__(self, root):
self.root = root # type: tkinter.Tk
self.mqtt_sender = None # type: mqtt.MqttClient
def set_mqtt_sender(self, mqtt_sender):
self.mqtt_sender = mqtt_sender
# TODO: Add methods here as needed.
# TODO: Add functions here as needed.
|
# 示例
# a = 1
# while a != 0:
# print("please input")
# a = int(input())
# print("over")
#升级版猜数字
num = 10
print('Guess what I think?')
bingo = False
while bingo == False:
answer = int(input())
if answer < num:
print("Too small!")
elif answer > num:
print("Too big!")
else:
print("Bingo!")
bingo = True
|
'''
http://projecteuler.net/problem=191
Prize Strings
Problem 191
'''
'''
Notes on problem 191():
Combinatorics should be done along the lines of:
http://jsomers.net/blog/project-euler-problem-191-or-how-i-learned-to-stop-counting-and-love-induction
Can't be late twice:
(L,L,*,*,*,...,*) and all it's permutations must be taken out
Can't be Abstent three times in a row
(*,*,A,A,A,*,...,*)
all permutations that keep the 3 A's together
Then remove the intersection of the two.
The naive way can't be improved much.
But, the way to do this is to simplify the naive way until it can be memoize
Which is the final solution.
'''
def problem191():
def count(sofar=()):
if sofar.count('L') == 2:
return 0
if len(sofar) > 2 and sofar[-3:] == ('A', 'A', 'A'):
return 0
if len(sofar) == 4:
return 1
total = 0
for day in ['0', 'A', 'L']:
total += count(sofar + (day,))
return total
return count()
def problem191():
seen = {}
def count(days, daysLate, daysAbsent):
try:
return seen[(days, daysLate, daysAbsent)]
except:
pass
if daysLate > 1 or daysAbsent >= 3:
return 0
if days == 30:
return 1
total = 0
total += count(days + 1, daysLate, 0) # Regular day
total += count(days + 1, daysLate, daysAbsent + 1) # Absent day
total += count(days + 1, daysLate + 1, 0) # Late day
seen[(days, daysLate, daysAbsent)] = total
return total
return count(0, 0, 0)
from cProfile import run
if __name__ == "__main__":
run("problem191()")
print(problem191() == 1918080160)
|
#!/usr/local/bin/python3.3
'''
Prime square remainders
Problem 123
Let pn be the nth prime: 2, 3, 5, 7, 11, ..., and let r be the remainder when (pn−1)n + (pn+1)n is divided by pn2.
For example, when n = 3, p3 = 5, and 43 + 63 = 280 ≡ 5 mod 25.
The least value of n for which the remainder first exceeds 109 is 7037.
Find the least value of n for which the remainder first exceeds 1010.
'''
'''
Notes on problem 123():
'''
from projectEuler import primes
def problem123():
checker = primes(save=True,initial=False)
for n, p in enumerate(checker[0:10**6]):
#print(n+1,p)
if (n+1) % 2 == 1 and 2*(n+1)*p > 10**10:
return n + 1
if __name__ == "__main__":
print(problem123())
|
'''
Problem 24
A permutation is an ordered arrangement of objects. For example, 3124 is one possible permutation of the digits 1, 2, 3 and 4. If all of the permutations are listed numerically or alphabetically, we call it lexicographic order. The lexicographic permutations of 0, 1 and 2 are:
012 021 102 120 201 210
What is the millionth lexicographic permutation of the digits 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9?
'''
from itertools import permutations
from pe.digits import numberFromList
def problem24():
for index, c in enumerate(permutations(range(0, 10))):
if index + 1 == 10 ** 6:
return numberFromList(c)
if __name__ == "__main__":
print(problem24() == 2783915460)
from cProfile import run
run("problem24()")
|
'''
Problem 94
It is easily proved that no equilateral triangle exists with integral length sides and integral area. However, the almost equilateral triangle 5-5-6 has an area of 12 square units.
We shall define an almost equilateral triangle to be a triangle for which two sides are equal and the third differs by no more than one unit.
Find the sum of the perimeters of all almost equilateral triangles with integral side lengths and area and whose perimeters do not exceed one billion (1,000,000,000).
'''
'''
Found triangles
(5, 6)
(65, 66)
(901, 902)
(12545, 12546)
'''
from projectEuler import solveIntegerQuadratic, integerSquare
'''
squares = []
usefullSquares = []
for k in range(1,10**6):
squares.append(k**2)
if (k**2 - 4) % 3 == 0 and (k**2 - 4)//3 in squares:
usefullSquares.append((k**2 - 4)//3)
total = 0
for d2 in usefullSquares:
# 2l + 1, 2l+2 squares
for a in solveIntegerQuadratic(3,-2,-1 -d2):
if a > 0:
if (a+1)*integerSquare(d2) % 4 == 0:
print(a,a+1)
total += 2*a + a+1
for a in solveIntegerQuadratic(3,2,-1 -d2):
if a - 1 > 0:
if (a-1)*integerSquare(d2) % 4 == 0:
print(a,a-1)
total += 2*a + a-1
print(total)
squares = []
for k in range(1,10**6):
squares.append(k**2)
if (k**2 - 4) % 3 == 0 and (k**2 - 4)//3 in squares:
usefullSquares.append((k**2 - 4)//3)
total = 0
squares = []
for k in range(1,10**6):
squares.append(k**2)
if (k**2 - 4) % 3 == 0 and (k**2 - 4)//3 in squares:
d2 = (k**2 - 4)//3
for a in solveIntegerQuadratic(3,-2,-1 -d2):
if a > 0:
if (a+1)*integerSquare(d2) % 4 == 0 and 2*a + a+1 <= 10**12:
print(a,a+1)
total += 2*a + a+1
print(total)
for a in solveIntegerQuadratic(3,2,-1 -d2):
if a - 1 > 0:
if (a-1)*integerSquare(d2) % 4 == 0 and 2*a + a-11 <= 10**12:
print(a,a-1)
total += 2*a + a-1
print(total)
'''
#!/usr/local/bin/python3.3
'''
http://projecteuler.net/problem=94
Almost equilateral triangles
Problem 94
'''
'''
Notes on problem 94():
'''
#https://gist.github.com/jakedobkin/1575590
def problem94():
limit = 10**9
total = 0
# a, a-1
a,c = 1,1
a,c = 7*a-8*c+2, -6*a+7*c-2
while 3*a-1 < limit:
area = (a-1)*c/4
if area == int(area):
total += 3*a-1
a, c = 7*a-8*c+2, -6*a+7*c-2
# a, a+1 case
a,c = 1, 0
a,c = 7*a - 8*c - 2, -6*a + 7*c + 2
while 3*a - 1 < limit:
area = (a+1)*c/4
if area == int(area):
total += 3*a+1
a,c = 7*a - 8*c - 2, -6*a + 7*c + 2
return total-2 # Remove degenerate solutions
from cProfile import run
if __name__ == "__main__":
print(problem94() == 518408346)
run("problem94()")
|
'''
Problem 172
How many 18-digit numbers n (without leading zeros) are there such that no digit occurs more than three times in n?
'''
def binomialCoeff(n, k):
result = 1
for i in range(1, k+1):
result = result * (n-i+1) / i
return result
# There are 9*10**17 possible 18 digits number
total = 9*10**17
# there are 3C18 ways to place 9 digits, plus 3C17 ways of placing 0
total -= 9*binomialCoeff(18,3) + binomialCoeff(17,3)
# but we now removed the way to place 2 sets of 3 digits twice need to use multinomials?
# And now we need to remove the 9 ways of placing 3
|
#!/usr/local/bin/python3.3
'''
Problem 87
The smallest number expressible as the sum of a prime square, prime cube, and prime fourth power is 28. In fact, there are exactly four numbers below fifty that can be expressed in such a way:
28 = 2^2 + 2^3 + 2^4
33 = 3^2 + 2^3 + 2^4
49 = 5^2 + 2^3 + 2^4
47 = 2^2 + 3^3 + 2^4
n = a^2 + b^3 + c^4
How many numbers below fifty million can be expressed as the sum of a prime square, prime cube, and prime fourth power?
'''
'''
Notes on problem 87():
'''
from projectEuler import primes
def problem87():
checker = primes(save=True,initial=False)
seen = []
GOAL = 5*10**7
for c in checker[1:(GOAL - 2**3 - 2**2)**(1/4)]:
for b in checker[1:(GOAL - c**4 - 2)**(1/3)]:
for a in checker[1:(GOAL - c**4 - b**3)**(1/2)]:
seen.append(a**2 + b**3 + c**4)
#print(a**2 + b**3 + c**4)
return len(set(seen))
if __name__ == "__main__":
print(problem87())
|
#!/usr/local/bin/python3.3
'''
Euler's Totient function, φ(n) [sometimes called the phi function], is used to determine the number of positive numbers less than or equal to n which are relatively prime to n. For example, as 1, 2, 4, 5, 7, and 8, are all less than nine and relatively prime to nine, φ(9)=6.
The number 1 is considered to be relatively prime to every positive number, so φ(1)=1.
Interestingly, φ(87109)=79180, and it can be seen that 87109 is a permutation of 79180.
Find the value of n, 1 < n < 107, for which φ(n) is a permutation of n and the ratio n/φ(n) produces a minimum.
'''
'''
Notes on problem 70():
'''
from itertools import combinations
from pe.primes import primesUpTo
from pe.digits import isPermutation
'''
Noticed that all records where the products of two primes, so ran over all candidates
'''
def problem70():
GOAL = 10 ** 7
primes = primesUpTo(2 * int(GOAL ** (1 / 2)))
record = 1000000000
for index, p in enumerate(primes[1:]):
for q in primes[index:]:
if q > GOAL // p:
break
n = p * q
ph = (p - 1) * (q - 1)
if isPermutation(n, ph) and n / ph < record:
record = n / ph
recordN = n
return recordN
if __name__ == "__main__":
print(problem70() == 8319823)
from cProfile import run
run("problem70()")
|
'''
http://projecteuler.net/problem=122
Efficient exponentiation
Problem 122
'''
'''
Notes on problem 122():
'''
def problem122():
m = {}
seen = set()
def gen(current, maximum):
if maximum > 200:
return
if current in seen:
return
if maximum not in m:
m[maximum] = current
else:
if len(current) > len(m[maximum]):
return
if len(current) < len(m[maximum]):
m[maximum] = current
seen.add(current)
b = max(current)
for a in current:
gen(current + (a + b,), max(maximum, a + b))
gen((1,), 1)
total = 0
for n in range(1, 201):
total += len(m[n]) - 1
return total
from cProfile import run
if __name__ == "__main__":
# run("problem122()")
print(problem122() == 1582)
|
#!/usr/local/bin/python3.3
'''
It is possible to write ten as the sum of primes in exactly five different ways:
7 + 3
5 + 5
5 + 3 + 2
3 + 3 + 2 + 2
2 + 2 + 2 + 2 + 2
What is the first value which can be written as the sum of primes in over five thousand different ways?
'''
'''
Notes on problem 77():
'''
from PE_primes import primesUpTo
from itertools import count
def problem77():
primes = primesUpTo(100)
for target in count(11):
ways = [1] + [0] * target
for prime in primes:
for j in range(prime, target + 1):
ways[j] += ways[j - prime]
if ways[target] > 5000:
return target
from cProfile import run
if __name__ == "__main__":
run("problem77()")
print(problem77() == 71)
|
'''
http://projecteuler.net/problem=232
The Race
Problem 232
'''
'''
Notes on problem 232():
'''
from itertools import count, combinations
import random
import math
def problem232():
games = 0
while True:
A_score = 0
B_score = 0
for r in count():
if A_score >= 100 or B_score >= 100:
print(A_score, B_score)
if B_score > A_score:
return
break
# A's turn
if random.choice(['H','T']) == 'H':
A_score += 1
T = random.randint(1, int(math.log(100-B_score,2)))
if random.choice([c for c in combinations(['H','T']*T, T)]) == ('T',)*T:
B_score += 2**(T-1)
from cProfile import run
if __name__ == "__main__":
#run("problem232()")
print(problem232())
|
#!/usr/local/bin/python3.3
'''
Summation of primes
Problem 10
The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
Find the sum of all the primes below two million.
'''
from pe.primes import primesUpTo
def problem10():
return sum(primesUpTo(2*10**6))
from cProfile import run
if __name__ == "__main__":
print(problem10() == 142913828922)
run("problem10()")
|
'''
Problem 117
Using a combination of black square tiles and oblong tiles chosen from: red tiles measuring two units, green tiles measuring three units, and blue tiles measuring four units, it is possible to tile a row measuring five units in length in exactly fifteen different ways.
How many ways can a row measuring fifty units in length be tiled?
NOTE: This is related to problem 116.
'''
from math import factorial
n = 50
total = 0
for d in range(0,n//4+1):
for c in range(0,(n-4*d)//3+1):
for b in range(0,(n-4*d-3*c)//2+1):
a = n - 4*d - 3*c - 2*b
f = factorial(a+b+c+d)//( factorial(a)*factorial(b)*factorial(c)*factorial(d))
total += f
print(total)
|
#!/usr/local/bin/python3.3
'''
Problem 53
There are exactly ten ways of selecting three from five, 12345:
123, 124, 125, 134, 135, 145, 234, 235, 245, and 345
In combinatorics, we use the notation, 5C3 = 10.
In general,
nCr =
n!
r!(n−r)!
,where r ≤ n, n! = n×(n−1)×...×3×2×1, and 0! = 1.
It is not until n = 23, that a value exceeds one-million: 23C10 = 1144066.
How many, not necessarily distinct, values of nCr, for 1 ≤ n ≤ 100, are greater than one-million?
'''
'''
Notes on problem 53():
'''
from pe.basic import nCk
def problem53():
count = 0
# 7 is a naive lower bound on nCk, i.e. cNk(n,k) ≥ (n/k)^k applying it to n = 2m, k = m we get this lower bound
for n in range(7,100+1):
# we can play similiar games on how small and how large k can be, but we do not get very good bounds
for k in range(4,n-3):
if nCk(n,k) >= 10**6:
# we account for the entire row
count += n - 2*k + 1
break
return count
def test():
for m in range(2,15):
print(m, (m+1)**m)
from cProfile import run
if __name__ == "__main__":
print(problem53() == 4075)
run("problem53()")
|
#!/usr/local/bin/python3.3
'''
http://projecteuler.net/problem=115
Counting block combinations II
Problem 115
'''
'''
Notes on problem 115():
'''
def problem115():
def numberOfSolutions(minlength,numBlocks,soFar=0,d={}):
if (minlength,numBlocks) not in d:
count = 1 # Everything is blank
for length in range(minlength,numBlocks + 1): # we can have blocks of length 3 to max length
for placement in range(0, numBlocks-length+1):
count += numberOfSolutions(minlength, numBlocks - placement - length - 1)
d[(minlength,numBlocks)] = count
return d[(minlength,numBlocks)]
from itertools import count
for n in count():
if numberOfSolutions(50,n) > 10**6:
return n
from cProfile import run
if __name__ == "__main__":
run("problem115()")
print(problem115())
|
#!/usr/local/bin/python3.3
'''
http://projecteuler.net/problem=127()
abc-hits
Problem 127
The radical of n, rad(n), is the product of distinct prime factors of n. For example, 504 = 23 × 32 × 7, so rad(504) = 2 × 3 × 7 = 42.
We shall define the triplet of positive integers (a, b, c) to be an abc-hit if:
GCD(a, b) = GCD(a, c) = GCD(b, c) = 1
a < b
a + b = c
rad(abc) < c
For example, (5, 27, 32) is an abc-hit, because:
GCD(5, 27) = GCD(5, 32) = GCD(27, 32) = 1
5 < 27
5 + 27 = 32
rad(4320) = 30 < 32
It turns out that abc-hits are quite rare and there are only thirty-one abc-hits for c < 1000, with ∑c = 12523.
Find ∑c for c < 120000.
'''
'''
Notes on problem 127():
Very slow
'''
from PE_factors import genFactors
from PE_basic import product
def problem127():
GOAL = 120000
rad = {} # rad[6] = {2,3}, radn[8] = {2}
for primes in genFactors(GOAL):
rad[product(primes)] = (set(primes), product(set(primes)))
def relprime(s, t):
return s & t == set()
found = 0
total = 0
for b in range(1, GOAL):
for a in range(1, min(b, GOAL - b)):
c = a + b
x, y, z = rad[a], rad[b], rad[c]
if x[0] & y[0] != set():
continue
if x[1] * y[1] * z[1] < c:
found += 1
total += c
return total
if __name__ == "__main__":
print(problem127() == 18407904)
|
'''
http://projecteuler.net/problem=128
Notes on problem 128():
'''
from PE_primes import isPrime
def problem128():
count = 1
limit = 2000
n = 0
number = 0
while count < limit:
n += 1
if (isPrime(6 * n - 1) and isPrime(6 * n + 1) and isPrime(12 * n + 5)):
count += 1;
number = (3 * n * n - 3*n + 2)
if (count >= limit):
break
if (isPrime(6 * n + 5) and isPrime(6 * n - 1) and isPrime(12 * n - 7) and n != 1):
count += 1
number = (3 * n * n + 3*n + 1)
return number
from cProfile import run
if __name__ == "__main__":
#run("problem128()")
print(problem128())
|
'''
Problem 116
A row of five black square tiles is to have a number of its tiles replaced with coloured oblong tiles chosen from red (length two), green (length three), or blue (length four).
If red tiles are chosen there are exactly seven ways this can be done.
If green tiles are chosen there are three ways.
And if blue tiles are chosen there are two ways.
Assuming that colours cannot be mixed there are 7 + 3 + 2 = 12 ways of replacing the black tiles in a row measuring five units in length.
How many different ways can the black tiles in a row measuring fifty units in length be replaced if colours cannot be mixed and at least one coloured tile must be used?
NOTE: This is related to problem 117.
'''
from operator import mul # or mul=lambda x,y:x*y
from fractions import Fraction
from functools import reduce
def nCk(n,k):
return int( reduce(mul, (Fraction(n-i, i+1) for i in range(k)), 1) )
n = 50
# Number of red bars
sumOfReds = 0
for b in range(1,n//2+1):
a = n - 2*b
sumOfReds += nCk(a+b,a)
sumOfGreens = 0
for b in range(1,n//3+1):
a = n - 3*b
sumOfGreens += nCk(a+b,a)
sumOfBlues = 0
for b in range(1,n//4+1):
a = n - 4*b
sumOfBlues += nCk(a+b,a)
print(sumOfReds + sumOfGreens + sumOfBlues)
# Number of green bars
# Numbers of blue bars
|
import unittest
class YearTestCase(unittest.TestCase):
def test_year_leap(self):
for year in (2000, 2016, 1916):
with self.subTest(year=year):
self.assertTrue(is_year_leap(year),
"{} на самом деле високосный".format(year))
def test_year_notleap(self):
for year in (1900, 2014, 2001):
with self.subTest(year=year):
self.assertFalse(is_year_leap(year),
"{} на самом деле не високосный".format(year))
def is_year_leap(year):
if year % 100 != 0:
if year % 4 == 0:
return True
else:
if year % 400 == 0:
return True
return False
if __name__ == "__main__":
unittest.main()
|
"""Используйте names.txt, текстовый файл размером 46 КБ, содержащий
более пяти тысяч имен. Начните с сортировки в алфавитном порядке. Затем
подсчитайте алфавитные значения каждого имени и умножьте это значение на
порядковый номер имени в отсортированном списке для получения количества
очков имени.
Какова сумма очков имен в файле?
"""
def names_scores(filename):
summary = 0
sum_ord = 0
with open(filename) as names:
a = names.read().strip('"')
list_of_names = sorted(a.split('","'))
for i, name in enumerate(list_of_names, 1):
for char in name:
sum_ord += ord(char) - 64
summary += i * sum_ord
sum_char = 0
return summary
if __name__ == "__main__":
print(names_scores("names.txt"))
|
a = list()
a.append(list(input()))
a.append(list(input()))
while a[-1][0] != "-":
a.append(list(input()))
ans = 0
for i in range(len(a)):
for j in range(len(a[0])):
if a[i][j] == "#" and a[i-1][j] != "#" and a[i][j-1] != "#":
ans += 1
print(ans)
|
#This code is from cisco PRNE course
from pprint import pprint
import re
#create regular expression to match ethernet interface names
eth_pattern = re.compile('Ethernet[0-9]')
routes = {}
#read all lines of IP routing information
file = open('ip-routes','r')
for line in file:
match = eth_pattern.search(line)
#check to see if we match ethernet string
if match:
intf = match.group(0) #get the interface from match
print intf
routes[intf] = routes[intf]+1 if intf in routes else 1
else:
continue
print ''
print "number of routes per interface"
print '------------------------------'
pprint(routes)
|
#模块 放在 包 下面
#文件夹 一般存放 一些配置文件等。
def sum(a,b):
print (a+b)
#内置变量 __name__
#运行本模块,该模块的__name__ 就是 __main__ 相当于程序的入口
# print (__name__) #打印结果为: __main__
#如果模块被其他模块调用, __name__ 就是该模块的模块名
if __name__ == '__main__': #这条语句的作用:1、程序的入口 2、调试时使用 #这条语句 在本模块被其他模块调用时也不需要删除。
sum(2,3)
|
import time
import threading
def foo(something):
for i in range(10):
time.sleep(1)
print (something)
#创建线程 --本质是 创建了一个实例,因为 Thread() 是一个类。
t1 = threading.Thread(target=foo,args=('看电影',))
t2 = threading.Thread(target=foo,args=('听音乐111111',))
#声明守护线程
t1.setDaemon(True)
# t2.setDaemon(True)
#启动线程
t1.start() #start() 是 Thread() 类中的一个方法。
t2.start()
#阻塞线程
# t1.join()
for i in range(5):
time.sleep(1)
print ('消费数据')
print ('结束了------------------------')
threading.RLock()
|
#!/usr/local/bin/python
# encoding=utf-8
file_obj = open('a.txt', 'r')
line1 = file_obj.readline() # 读取一行
line1 = line1.rstrip() #strip() 函数的作用是去掉
print(line1)
line2 = file_obj.readlines() # 读取多行
#lines2 = line2.strip() #readlines has no attribute of 'strip()'
print(type(line2))
boys = ['Mike', 'Jhon', 'Tom']
girls = ['Lisa', 'Linda', 'Mary']
for girl in girls:
for boy in boys:
print(girl, '<->', boy)
beforetax = [15000, 12000, 13000]
aftertax = []
for one in beforetax:
aftertax.append(int(one * 0.9)) # append()函数的用法:
print(aftertax)
aList = [3,5,7,2]
newList = []
# for i in range(0,len(aList)-1):
# for j in range(0,len(aList)-1-i):
# if aList[j] < aList[j+1]:
# aList[j],aList[j+1] = aList[j+1],aList[j]
# newList.append(aList[len(aList)-1:len(aList)])
# print (newList)
for i in aList:
newList.append(min(aList))
aList.remove(min(aList))
print (aList)
print (newList)
# bList = [2,5,3,0,9]
# bList.sort(reverse=True) #降序排序 sort() 函数默认 是降序排序
# print (bList)
# bList.sort(reverse=False) #升序排序
# print (bList)
|
import threading,time
def foo(something,num):
for i in range(num):
time.sleep(1)
'''写上面这行代码的原因是 2个线程是并发执行,且因为 资源竞争,导致 2 个线程之间,
其中一个线程还没有执行完,CPU就被另外一个线程抢走了,
所以会出现 打印结果为 “CPU正在CPU正在 处理迅雷的任务处理Pycharm的任务”这样的情况。
如何解决 资源竞争,这里就用到了 同步锁 。'''
print ('CPU正在',something)
time.sleep(1) #写这行代码的原因与上面的一样。
t1 = threading.Thread(target=foo,args=['处理迅雷的任务',5]) #处理迅雷的任务 传给了foo函数中的something,5传给了num。
t2 = threading.Thread(target=foo,args=('处理Pycharm的任务',5))
t1.start()
t2.start()
|
# Diagonal Difference
# n = int(input().strip())
# arr = []
# for _ in range(n):
# arr.append(list(map(int, input().rstrip().split())))
def diagonalDifference(arr):
""" Calculates the absolute difference between
the sums of its diagonals """
sum1 = 0
sum2 = 0
counter = 0
for i in arr:
sum1 += i[counter]
sum2 += i[-(counter+1)]
counter += 1
return abs(sum1 - sum2)
# Running some tests..
print(diagonalDifference([
[11,2,4],
[4,5,6],
[10,8,-12]
]) == 15)
|
# %%
# Compare the Triplets
def compareTriplets(a, b):
""" Determines their respective comparison points """
alice = 0;
bob = 0;
for i in range(len(a)):
if a[i] > b[i]:
alice += 1
elif a[i] < b[i]:
bob += 1
return alice,bob
# Running some tests..
print(compareTriplets([5,6,7], [3,6,10]) == (1, 1))
|
# Mini-Max Sum
# arr = list(map(int, input().rstrip().split()))
def miniMaxSum(arr):
""" Finds the minimum and maximum values that can be
calculated by summing exactly four of the five integers """
sum_min = 0
sum_max = 0
for i in range(4):
sum_min += sorted(arr)[i]
sum_max += sorted(arr, reverse=True)[i]
return print(sum_min, sum_max)
miniMaxSum([1,2,3,4,5]) # 10 14
|
import time
import pygame
from datetime import date
import keyboard
#Get Todays Date And Weekday Number
today = date.today()
day = date.isoweekday(today)
#Get Current Time In Hours And Minutes
def currentTime():
hour = time.strftime("%H")
current_hour = int(hour)
minutes = time.strftime("%M")
current_minutes = int(minutes)
current_status = time.strftime("%p")
return current_hour , current_minutes , current_status
(current_hour , current_minutes , current_status) = currentTime()
#Get User Input At Which He Wants Alarm To Be Set
def getUserInput():
hour_user_input = input("Enter The Time in Hr :")
minutes_user_input = input("Enter The Time in Min :")
status_user_input = raw_input("Enter Status :")
if status_user_input == 'PM' and hour_user_input < 12 :
hour_user_input = hour_user_input + 12
if status_user_input =='AM' and hour_user_input == 12 :
hour_user_input = 0
minutes_user_input = 0
return hour_user_input , minutes_user_input , status_user_input
#Alarm Sound Regarding Functions
def alarm_sounder():
pygame.mixer.init()
pygame.mixer.get_init()
pygame.mixer.music.load('path to \123.mp3')
pygame.mixer.music.play(-1)
def alarm_stopper():
pygame.mixer.music.stop()
pygame.mixer.quit()
#Get The Time Remaining For Alarm
def alarm_timeleft(hour_user_input , minutes_user_input , status_user_input):
hours_left=0
minutes_left=0
if (status_user_input == 'AM' and current_status == 'AM') or (status_user_input == 'PM' and current_status == 'PM'):
print "First if"
if (current_hour >= hour_user_input) and (current_minutes >= minutes_user_input):
print "First if"
tot_minutes = current_hour*60 + current_minutes - hour_user_input*60 - minutes_user_input
tot_minutes = 24*60 - tot_minutes
hours_left = tot_minutes/60
minutes_left = tot_minutes%60
elif (current_hour == hour_user_input) and (current_minutes == minutes_user_input) :
hours_left = 24
minutes_left = 0
else :
tot_minutes = hour_user_input*60 + minutes_user_input - current_hour*60 - current_minutes
hours_left = tot_minutes/60
minutes_left = tot_minutes%60
if (status_user_input == 'PM' and current_status == 'AM') :
print "second if"
tot_minutes = hour_user_input*60 + minutes_user_input - current_hour*60 - current_minutes
hours_left = tot_minutes/60
minutes_left = tot_minutes%60
if (status_user_input == 'AM' and current_status == 'PM'):
print "Third if"
tot_minutes = 24*60 + hour_user_input*60 + minutes_user_input - current_hour*60 - current_minutes
hours_left = tot_minutes/60
minutes_left = tot_minutes%60
print "Time Remaining : %s hrs %s minutes" %(hours_left , minutes_left)
#Alarm Snoozing
def alarm_snoozer(hour_input,minutes_input,status,flag):
Snoozefor = input("Number of Minutes:")
tot_minutes_user_input = Snoozefor + minutes_input + hour_input*60
hour_user = tot_minutes_user_input/60
minutes_user = tot_minutes_user_input%60
if status == 'AM' and hour_user == 12 :
status = 'PM'
if status == 'PM' and hour_user == 24 :
hour_user = 0
status = 'AM'
print hour_user , minutes_user
pygame.mixer.music.stop()
pygame.quit()
alarmCheck(hour_user,minutes_user,status,flag)
return False
#Set Alarm ON Or OFF
def alarm_toggle(flag):
while True :
if keyboard.is_pressed('space'):
flag = not flag
if flag:
print "Alarm is ON"
return True
else:
return False
#Comparing With Current Time
def compareWithCurrentTime(hour_input,minutes_input,status_input):
#print "It Came Here"
(current_hour , current_minutes , current_status) = currentTime()
if status_input == 'AM' and current_status == 'AM':
if hour_input == current_hour and minutes_input == current_minutes :
return True
elif status_input == 'PM' and current_status == 'PM':
if hour_input == current_hour and minutes_input == current_minutes :
return True
return False
#####################################--------------Alarm Ready---------------#########################################
def alarmCheck(hour_input,minutes_input,status,flag):
while True :
#print "Entererrrrrrrrrr"
if compareWithCurrentTime(hour_input,minutes_input,status) :
while True :
# print "Enterrtry"
print flag
if flag :
alarm_sounder()
while True:
store = raw_input("Do You Want To snooze or TurnOff Alarm")
if store == 's':
flag = alarm_snoozer(hour_input,minutes_input,status,flag)
return
if store == 'f':
alarm_stopper()
flag = False
return
else :
print "Alarm is off"
break
def alarmset():
flag = False
while True :
(hour_user_input , minutes_user_input , status_user_input) = getUserInput()
alarm_timeleft(hour_user_input , minutes_user_input , status_user_input)
flag = alarm_toggle(flag)
alarmCheck(hour_user_input , minutes_user_input , status_user_input,flag)
|
#!/usr/bin/env python
import sys
g_sqSize = -1 # the board size, passed at runtime
g_board = [] # the board will be constructed as a list of lists
def main():
global g_sqSize
if len(sys.argv) != 2:
g_sqSize = 8 # Default: Fill the normal 8x8 chess board
else:
try: g_sqSize = int(sys.argv[1]) # or, the NxN the user wants
except:
print("Usage: " + sys.argv[0] + " <squareSize>")
sys.exit(1)
for i in range(0, g_sqSize):
g_board.append(g_sqSize*[0]) # Fill the board with zeroes
Fill(0,0,1) # Start the recursion with a 1 in the upper left
print("No solution found") # if the recursion returns, it failed
def InRangeAndEmpty(ty,tx): # check if coordinates are within the board
return ty>=0 and tx>=0 and ty<g_sqSize and tx<g_sqSize \
and g_board[ty][tx] == 0 # and the square is empty
def Fill(y,x,counter): # The recursive function that fills the board
assert g_board[y][x] == 0
g_board[y][x] = counter # Fill the square
if counter == g_sqSize*g_sqSize: # Was this the last empty square?
PrintBoard() # Yes, print the board...
sys.exit(1) # ...and exit
jumps = ((-2,1),(-1,2),(1,2),(2,1),(2,-1),(1,-2),(-1,-2),(-2,-1))
for jump in jumps: # otherwise, try all the empty neighbours in turn
ty,tx = y+jump[0], x+jump[1]
if InRangeAndEmpty(ty,tx):
Fill(ty,tx,counter+1) # *** RECURSION! ***
g_board[y][x] = 0 # if we get here, all the neighbours failed,
# so reset the square and return
def PrintBoard(): # print the board using nice ASCII art ('+' and '-')
scale = len(str(g_sqSize*g_sqSize))
print(g_sqSize*("+" + scale*"-") + "+")
for line in g_board:
for elem in line:
sys.stdout.write("|%*d" % (scale,elem))
print("|\n"+g_sqSize*("+" + scale*"-") + "+")
if __name__ == "__main__":
main()
|
import numpy as np
print("3)")
s = [2, 3.6667, 5, 7.2, 10]
n = [50, 100, 200, 500, 1000]
def dzeta_f_single(s, n):
total_sum = np.float32(0)
for k in range(1, n + 1):
total_sum += np.float32(1) / np.float32(k) ** np.float32(s)
return total_sum
def dzeta_b_single(s, n):
total_sum = np.float32(0)
for k in range(n, 0, -1):
total_sum += np.float32(1) / np.float32(k) ** np.float32(s)
return total_sum
def dzeta_f_double(s, n):
total_sum = np.float64(0)
for k in range(1, n + 1):
total_sum += np.float64(1) / np.float64(k) ** np.float64(s)
return total_sum
def dzeta_b_double(s, n):
total_sum = np.float64(0)
for k in range(n, 0, -1):
total_sum += np.float64(1) / np.float64(k) ** np.float64(s)
return total_sum
print("\n\tDZETA:\n")
for sx in s[::]:
for nx in n[::]:
print("s = " + str(sx) + ", n = " + str(nx) + ":"
+ "\ndzeta single precision forward: " + str(dzeta_f_single(sx, nx))
+ "\ndzeta single precision backward: " + str(dzeta_b_single(sx, nx))
+ "\ndzeta double precision forward: " + str(dzeta_f_double(sx, nx))
+ "\ndzeta double precision backward: " + str(dzeta_b_double(sx, nx))
+ "\n")
def eta_f_single(s, n):
total_sum = np.float32(0)
for k in range(1, n + 1):
total_sum += (np.float32(-1) ** (np.float32(k) - np.float32(1))) * np.float32(1) / (np.float32(k) ** np.float32(s))
return total_sum
def eta_b_single(s, n):
total_sum = np.float32(0)
for k in range(n, 0, -1):
total_sum += (np.float32(-1) ** (np.float32(k) - np.float32(1))) * np.float32(1) / (np.float32(k) ** np.float32(s))
return total_sum
def eta_f_double(s, n):
total_sum = np.float64(0)
for k in range(1, n + 1):
total_sum += (np.float64(-1) ** (np.float64(k) - np.float64(1))) * np.float64(1) / (np.float64(k) ** np.float64(s))
return total_sum
def eta_b_double(s, n):
total_sum = np.float64(0)
for k in range(n, 0, -1):
total_sum += (np.float64(-1) ** (np.float64(k) - np.float64(1))) * np.float64(1) / (np.float64(k) ** np.float64(s))
return total_sum
print("\n\tETA:\n")
for sx in s[::]:
for nx in n[::]:
print("s = " + str(sx) + ", n = " + str(nx) + ":"
+ "\neta single precision forward: " + str(eta_f_single(sx, nx))
+ "\neta single precision backward: " + str(eta_b_single(sx, nx))
+ "\neta double precision forward: " + str(eta_f_double(sx, nx))
+ "\neta double precision backward: " + str(eta_b_double(sx, nx))
+ "\n")
|
#!/usr/bin/env python3
""" Find a given entry_name in the given or stored index
"""
def show_map(name_2_path):
""" Show the whole name_2_path index of this collection.
"""
from pprint import pprint
pprint(name_2_path)
def byquery(query, name_2_path, collections_searchpath, __entry__=None, __kernel__=None):
""" Find all objects matching the query
Usage examples:
clip byquery dictionary,-english ,{ get_path # tag 'dictionary' is present while tag 'english' is absent
clip byquery key1.key2.key3==1234 ,{ get_name # the value of key1.key2.key3 equals 1234
clip byquery key1.key2.key3!=1234 ,{ get_path # does not equal 1234
clip byquery key1.key2.key3<1234 ,{ get_name # is less than 1234
clip byquery key1.ind2.key3>1234 ,{ get_path # is greater than 1234
clip byquery key1.ind2.key3<=1234 ,{ get_name # is less than or equal to 1234
clip byquery key1.ind2.key3>=1234 ,{ get_path # is greater than or equal to 1234
clip byquery solar.planets:Mars ,{ get_path # is a list and contains the value Mars
clip byquery solar.planets!:Titan ,{ get_path # is a list and does not contain the value Titan
clip byquery key1.key2.key3. ,{ get_name # the path key1.key2.key3 exists
clip byquery key1.ind2.key3? ,{ get_path # the path key1.ind2.key3 converts to True (Python rules)
"""
def traverse_and_apply(key_path, fun, against=None):
""" Finally, a useful real-life example of closures:
captures both *fun* and *against* in the internal function.
"""
def traverse(entry):
struct_ptr = entry.parameters_loaded()
for key_syllable in key_path:
if type(struct_ptr)==dict and (key_syllable in struct_ptr):
struct_ptr = struct_ptr[key_syllable] # iterative descent
elif type(struct_ptr)==list:
idx = None
try:
idx = int(key_syllable)
except:
pass
if type(idx)==int and 0<=idx<len(struct_ptr):
struct_ptr = struct_ptr[idx]
else:
return None
else:
return None
return fun(struct_ptr, against)
return traverse
def to_num_or_not_to_num(x):
"Convert the parameter to a number if it looks like it"
try:
x_int = int(x)
if type(x_int)==int:
return x_int
except:
try:
x_float = float(x)
if type(x_float)==float:
return x_float
except:
pass
return x
## Forming the query:
#
if type(query)==dict: # an already parsed query
parsed_query = query
positive_tags_set = parsed_query.get('positive_tags_set', set())
negative_tags_set = parsed_query.get('negative_tags_set', set())
check_list = parsed_query.get('check_list', [])
else: # parsing the query for the first time
positive_tags_set = set()
negative_tags_set = set()
check_list = []
parsed_query = {
'positive_tags_set': positive_tags_set,
'negative_tags_set': negative_tags_set,
'check_list': check_list,
}
conditions = query.split(',')
import re
for condition in conditions:
binary_op_match = re.match('([\w\.]*\w)(=|==|!=|<>|<|>|<=|>=|:|!:)(-?[\w\.]+)$', condition)
if binary_op_match:
key_path = binary_op_match.group(1).split('.')
test_val = to_num_or_not_to_num(binary_op_match.group(3))
if binary_op_match.group(2) in ('=', '=='):
check_list.append( traverse_and_apply(key_path, lambda x, y : x==y, test_val) )
elif binary_op_match.group(2) in ('!=', '<>'):
check_list.append( traverse_and_apply(key_path, lambda x, y : x!=y, test_val) )
elif binary_op_match.group(2)=='<':
check_list.append( traverse_and_apply(key_path, lambda x, y : x!=None and x<y, test_val) )
elif binary_op_match.group(2)=='>':
check_list.append( traverse_and_apply(key_path, lambda x, y : x!=None and x>y, test_val) )
elif binary_op_match.group(2)=='<=':
check_list.append( traverse_and_apply(key_path, lambda x, y : x!=None and x<=y, test_val) )
elif binary_op_match.group(2)=='>=':
check_list.append( traverse_and_apply(key_path, lambda x, y : x!=None and x>=y, test_val) )
elif binary_op_match.group(2)==':':
check_list.append( traverse_and_apply(key_path, lambda x, y : type(x)==list and y in x, test_val) )
elif binary_op_match.group(2)=='!:':
check_list.append( traverse_and_apply(key_path, lambda x, y : type(x)==list and y not in x, test_val) )
else:
unary_op_match = re.match('([\w\.]*\w)(\.|\?)$', condition)
if unary_op_match:
key_path = unary_op_match.group(1).split('.')
if unary_op_match.group(2)=='.':
check_list.append( traverse_and_apply(key_path, lambda x, y: x!=None) )
elif unary_op_match.group(2)=='?':
check_list.append( traverse_and_apply(key_path, lambda x, y: bool(x)) )
else:
tag_match = re.match('([!^-])?(\w+)$', condition)
if tag_match:
if tag_match.group(1):
negative_tags_set.add( tag_match.group(2) )
else:
positive_tags_set.add( tag_match.group(2) )
else:
raise(SyntaxError("Could not parse the condition '{}'".format(condition)))
objects_found = []
# Applying the query:
#
for relative_path in name_2_path.values():
full_path = __entry__.get_path(relative_path)
candidate_object = __kernel__.bypath(full_path)
candidate_tags_set = set(candidate_object['tags'] or [])
if (positive_tags_set <= candidate_tags_set) and negative_tags_set.isdisjoint(candidate_tags_set):
candidate_still_ok = True
for check in check_list:
if not check(candidate_object):
candidate_still_ok = False
break
if candidate_still_ok:
objects_found.append( candidate_object )
# Recursion into collections:
#
if collections_searchpath:
for subcollection_name in collections_searchpath:
if subcollection_name.find('/')>=0:
subcollection_object = __kernel__.bypath(subcollection_name)
else:
subcollection_local = name_2_path.get(subcollection_name)
subcollection_object = __kernel__.byname(subcollection_name, __entry__ if subcollection_local else None)
objects_found_in_subcollection = subcollection_object.call('byquery', { 'query': parsed_query })
objects_found.extend( objects_found_in_subcollection )
return objects_found
def byname(entry_name, name_2_path, collections_searchpath, __entry__=None, __kernel__=None):
""" Find a relative path of the named entry in this collection entry's index.
"""
relative_path = name_2_path.get(entry_name)
if relative_path:
return __kernel__.bypath( __entry__.get_path(relative_path) )
# Recursion into collections:
#
elif collections_searchpath:
print("COLLECTION.byname({}) recursing ...".format(entry_name))
for subcollection_name in collections_searchpath:
print("COLLECTION.byname({}) checking in {}...".format(entry_name, subcollection_name))
if subcollection_name.find('/')>=0:
subcollection_object = __kernel__.bypath(subcollection_name)
else:
subcollection_local = name_2_path.get(subcollection_name)
subcollection_object = __kernel__.byname(subcollection_name, __entry__ if subcollection_local else None)
found_object = __kernel__.byname(entry_name, subcollection_object)
if found_object:
return found_object
return None
def add_entry(entry_name, data=None, __entry__=None, __kernel__=None):
"""
Usage example:
clip byname --entry_name=words_collection add_entry --entry_name=xyz --data.foo.bar=1234 --data.baz=alpha
"""
import os
# Create the physical directory for the new entry:
new_entry_full_path = __entry__.get_path(entry_name)
print("add_entry: new_entry_full_path="+new_entry_full_path)
os.makedirs(new_entry_full_path) # FIXME: fail gracefully if directory path existed
# Add the new entry to collection:
__entry__.parameters_loaded()['name_2_path'][entry_name] = entry_name
__entry__.update()
if data==None:
data = {}
# Update parameters of the new entry:
new_entry = __kernel__.bypath(new_entry_full_path)
new_entry.update( data )
return new_entry
def delete_entry(entry_name, __entry__=None, __kernel__=None):
"""
Usage example:
clip byname --entry_name=words_collection delete_entry --entry_name=xyz
"""
import shutil
name_2_path = __entry__.parameters_loaded()['name_2_path']
old_entry_full_path = __entry__.get_path(name_2_path[entry_name])
print("delete_entry: old_entry_full_path="+old_entry_full_path)
# Remove the old entry from collection:
del name_2_path[entry_name]
__entry__.update()
# Remove the physical directory of the old entry:
shutil.rmtree(old_entry_full_path)
return __entry__
if __name__ == '__main__':
# When the entry's code is run as a script, perform local tests:
#
show_map({"alpha" : 10, "beta" : 200})
returned_path = byname('second', { "first" : "relative/path/to/the/first", "second" : "relative/path/to/the/second" })
print("returned_path = {}\n".format(returned_path))
|
# The try block will raise an error when trying to write to a read-only file:
try:
f = open("demoFile.txt")
f.write("Welcome")
except Exception as e:
print(e)
print("Something went wrong when writing to the file")
finally:
f.close()
# The program can continue, without leaving the file object open
print('------------------------------------')
x = -1
if x < 0:
raise Exception("Sorry, no numbers below zero")
|
def test(temperature):
assert(temperature > 0), "Colder than absolute zero!"
return (temperature - 273)*1.8 + 32
def fun(level):
if level < 0:
raise Exception(level)
return level
try:
print(test(10))
print(test(-10))
except Exception as arg:
print('hhh', arg)
try:
print(fun(10))
print(fun(-10))
except Exception as e:
print('exception: ', e.args[0])
# print(test(10))
# print(test(-10))
|
#Developer: Gabriel Yugo Nascimento Kishida
#Contact: [email protected]
#Date: January/2021
#Description : Algorithm that applies the method of LU decomposition to solve linear systems.
import numpy as np
#Functionality: this function calculates the sum of a multiplication, a value useful to the decomposition.
#l is the upper triangle matrix, u the lower, and i,j the line and row indexes.
def sumMultiplication(l,u,i,j) :
result = 0
for k in range(j) :
result += l[i][k]*u[k][j]
return result
#Functionality: this function subtracts a linear proportion (equal to coef) of a maintaned line
#from an eliminated line, making one element (matrix[lineEliminated][lineMaintaned]) equal to 0.
def lineElimination(matrix,lineMaintained,lineEliminated):
if (matrix[lineMaintained][lineMaintained] != 0):
coef = -(matrix[lineEliminated][lineMaintained]/matrix[lineMaintained][lineMaintained])
matrix[lineEliminated] = matrix[lineEliminated] + matrix[lineMaintained]*coef
#Functionality: receives decomposition lu and answers b to the linear system, and solves it.
#This is probably optimizable. I've made several "for i in range(n)" statements that can be reduced.
def luSolver(l,u,b,n) :
lb = np.zeros((n,n+1))
for i in range(n) :
lb[i] = np.hstack((l[i],b[i]))
for i in range(n) :
for j in range(i+1,n) :
lineElimination(lb,i,j)
ux = np.zeros((n,n+1))
x = np.zeros(n)
for i in range(n) :
ux[i] = np.hstack((u[i],lb[i][n]))
for i in range(n-1,-1,-1):
for j in range(i-1,-1,-1):
lineElimination(ux,i,j)
ux[i] = ux[i]/ux[i][i]
x[i] = ux[i][n]
return x
#Functionality: this function receives a matrix (n)x(n+1) and solves it using LU decomposition.
def luDecomposition(matrix) :
n = len(matrix)
u = np.zeros((n,n))
l = np.zeros((n,n))
for j in range(n) :
u[0][j] = matrix[0][j]
for i in range(n) :
l[i][0] = matrix[i][0]/u[0][0]
for i in range(1,n) :
for j in range(i+1) :
if (i == j) :
l[i][i] = 1
else :
l[i][j] = (matrix[i][j] - sumMultiplication(l,u,i,j))/u[j][j]
for j in range(i,n) :
u[i][j] = matrix[i][j] - sumMultiplication(l,u,i,j)
b = np.zeros(n)
for i in range(n):
b[i] = matrix[i][n]
return luSolver(l,u,b,n)
matrix = np.array([[1.0,1.0,2.0,0.0,1.0],[2.0,-1.0,0.0,1.0,-2.0],[1.0,-1.0,-1.0,-2.0,4.0],[2.0,-1.0,2.0,-1.0, 0.0]])
print("Expected values: x1 = 1, x2 = 2, x3 = -1, x4 = -2")
print(luDecomposition(matrix))
|
"""
It takes a url and get that page. From that page it gets all the links that start with start_str.
"""
def getPage(url):
"""
it returns the page data
"""
import urllib2
f = urllib2.urlopen(url)
return f.read().decode('utf-8')
def getLinks(string):
from BeautifulSoup import BeautifulSoup
soup = BeautifulSoup(string)
return [anchor['href'] for anchor in soup.findAll('a')]
def startWith(seq, start):
"""return a list from given sequence
"""
return [s for s in seq if s.startswith(start)]
|
# Python3 program to swap first and last element of a list
Examples:
Input : [12, 35, 9, 56, 24]
Output : [24, 35, 9, 56, 12]
Input : [1, 2, 3]
Output : [3, 2, 1]
----------------------------------------
Approach #1: Find the length of the list and simply swap the first element with (n-1)th element.
# Swap function
def swapList(newList):
size = len(newList)
# Swapping
temp = newList[0]
newList[0] = newList[size - 1]
newList[size - 1] = temp
return newList
# Driver code
newList = [12, 35, 9, 56, 24]
print(swapList(newList))
-------------------------------------
Approach #2: The last element of the list can be referred as list[-1]. Therefore, we can simply swap list[0] with list[-1].
# Swap function
def swapList(newList):
newList[0], newList[-1] = newList[-1], newList[0]
return newList
# Driver code
newList = [12, 35, 9, 56, 24]
print(swapList(newList))
----------------------------------------
Approach #3: Swap the first and last element is using tuple variable. Store the first and last element as a pair in a tuple variable, say get, and unpack those elements with first and last element in that list. Now, the First and last values in that list are swapped.
# Swap function
def swapList(list):
# Storing the first and last element
# as a pair in a tuple variable get
get = list[-1], list[0]
# unpacking those elements
list[0], list[-1] = get
return list
# Driver code
newList = [12, 35, 9, 56, 24]
print(swapList(newList))
OUTPUT: [24, 35, 9, 56, 12]
----------------------------------------
Approach #4: Using * operand.
# Python3 program to illustrate
# the usage of * operarnd
list = [1, 2, 3, 4]
a, *b, c = list
print(a)
print(b)
print(c)
OUTPUT:
1
[2, 3]
4
-----------------------------------------
Approach #5: Swap the first and last elements is to use inbuilt function list.pop().
# Swap function
def swapList(list):
first = list.pop(0)
last = list.pop(-1)
list.insert(0, last)
list.append(first)
return list
# Driver code
newList = [12, 35, 9, 56, 24]
print(swapList(newList))
OUTPUT:
|
Python code using ord function :
ord() : It coverts the given string of length one, return an integer representing the unicode code point of the character. For example, ord(‘a’) returns the integer 97.
# Python program to print
# ASCII Value of Character
# In c we can assign different
# characters of which we want ASCII value
c = 'g'
# print the ASCII value of assigned character in c
print("The ASCII value of '" + c + "' is", ord(c))
OUTPUT:
The ASCII value of g is 103
|
def recursion(k):
if(k > 0):
result = k + recursion(k - 1)
print(result)
else:
result = 0
return result
print("\n\nRecursion Example Results")
recursion(6)
OUTPUT:
Recursion Example Results
1
3
6
10
15
21
|
from PIL import Image
nb=int(input("How much red or blue do you want ? -0 : total blue, 250 : total red and 100 the middle"))
img = Image.open("avantages-quil-y-a-a-grandir-dans-un-petit-village.jpg")
pixels = img.load()
for i in range(img.width):
for j in range(img.height):
r, g, b = pixels[i, j]
z = (r + g + b) // 3
if nb > z:
pixels[i, j] = (237, 28, 28)
else:
pixels[i, j]=(7, 13, 58)
img.show()
|
class Solution(object):
def searchRange(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
if target not in nums:
return [-1,-1]
else:
where = []
# Search from the left side
for i in range(len(nums)):
if nums[i] == target:
where.append(i)
break
# Search from right side
for i in range(len(nums))[::-1]:
if nums[i] == target:
where.append(i)
break
return where
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Nov 15 21:47:23 2019
"""
import time
import asyncio
import cozmo
from cozmo.util import degrees, Pose
from cozmo.util import distance_mm, speed_mmps
def find_face(robot: cozmo.robot.Robot):
global pose
print ("cozmo is looking for a human face")
face = None
# two cubes spotted, the robot will find the human face and approach it.
while True:
if face and face.is_visible:
robot.drive_straight(distance_mm(150), speed_mmps(50)).wait_for_completed()
robot.say_text("Hello Human.How are you today? I am excited to play a game with you. Are u ready? Let's start").wait_for_completed()
robot.go_to_pose(Pose(0.0, 0.0, 0.0, angle_z=degrees(0)), relative_to_robot=False).wait_for_completed()
break
else:
robot.turn_in_place(degrees(30)).wait_for_completed()
# Wait until we we can see another face
try:
face = robot.world.wait_for_observed_face(timeout=2)
print(face)
except asyncio.TimeoutError:
print("Didn't find a face.")
# return
time.sleep(1)
return face
|
def get_tokens(file_name="res/02.txt"):
with open(file_name) as f:
lines = f.readlines()
tokens = [l.strip() for l in lines]
return [t for t in tokens if t]
def hash(token: str):
letters = set(token)
counts = {
letter: len([l for l in token if l == letter]) for letter in letters
}
twos = [l for l, c in counts.items() if c == 2]
threes = [l for l, c in counts.items() if c == 3]
return len(twos) > 0, len(threes) > 0
def part1():
tokens = get_tokens()
hashes = [hash(token) for token in tokens]
twos = len([True for h2, h3 in hashes if h2])
threes = len([True for h2, h3 in hashes if h3])
print(twos * threes)
def part2():
tokens = get_tokens()
for c1 in tokens:
for c2 in tokens:
diff = [l1 for l1, l2 in zip(c1, c2) if l1 == l2]
if len(diff) == len(c1) - 1:
print("".join(diff))
return
part1()
part2()
|
#function to get initials of name.
def to_initials(name):
li = name.split(" ")
initials = ""
for ele in li:
initials += ele[0][0]
return initials
#print(to_initials("Kelvin Bridges"))
#print(to_initials("Michaela Yamamoto"))
#print(to_initials("Mary La Grange"))
# finding the element that appears first in the array.
def first_in_array(arr, el1,el2):
for ele in arr:
if ele == el1:
return el1
if ele == el2:
return el2
return none
#print(first_in_array(["a", "b", "c", "d"], "d", "b"))
#print(first_in_array(["cat", "bird" ,"dog", "mouse" ], "dog", "mouse"))
#abbreviate sentence by removing the vowels if the length of the word is greater than 4.
def abbreviate_sentence (sent):
list = sent.split(" ")
vowels = ['a','e','i', 'o','u']
result = []
for ele in list:
if len(ele) > 4:
temp = []
for i in range(len(ele)):
if ele[i] not in vowels:
temp.append(ele[i])
fstr = "".join(temp)
result.append(fstr)
else:
result.append(ele)
final = ''
final = " ".join(result)
return final
#print(abbreviate_sentence("follow the yellow brick road"))
#print(abbreviate_sentence("what a wonderful life"))
def format_name(str):
list = str.split(" ")
final = []
for ele in list:
l_letter = []
word = format_word(ele)
final.append(word)
ffinal = " ".join(final)
return ffinal
def format_word(word):
list = []
for i in range(len(word)):
list.append(word[i])
list[0] = list[0].upper()
for i in range(1,len(list)):
list[i] = list[i].lower()
final = "".join(list)
return final
#print(format_word('musTAfa'))
#print(format_name("chase WILSON"))
#print(format_name("brian CrAwFoRd scoTT"))
def is_valid_name(str):
cond1 = True
cond2 = True
list = str.split(" ")
if len(list) < 2:
cond1 = False
return False
for ele in list:
if valid_word(ele) == False:
cond2 = False
return False
if cond1 == True and cond2 == True:
return True
else:
return False
def valid_word(word):
bool = True
list = []
for i in range(len(word)):
list.append(word[i])
if list[0] != list[0].upper():
return false
for i in range(1,len(list)):
if list[i] != list[i].lower():
bool = False
return False
return bool
#print(is_valid_name("Kush Patel"))
#print(is_valid_name("Daniel"))
#print(is_valid_name("Robert Downey Jr"))
#print(is_valid_name("ROBERT DOWNEY JR"))
def is_valid_email(str):
cond1 = True
cond2 = True
cond3 = True
list = str.split('@')
if len(list) != 2:
cond1 = False
return False
bef_at = list[0]
for l in bef_at:
if l != l.lower():
cond2 = False
return False
if l.isnumeric() == True:
cond2 = False
return False
dots = 0
aft_at = list[1]
for c in aft_at:
if c == ".":
dots += 1
if dots != 1:
cond3 = False
return False
return True
#print(is_valid_email("[email protected]")) # => true
#print(is_valid_email("[email protected]")) # => true
#print(is_valid_email("jdoe@[email protected]")) # => false
#print(is_valid_email("[email protected]")) # => false
#print(is_valid_email("jdoegmail.com")) # => false
#print(is_valid_email("az@email")) # => false
def array_translate(array):
final = ""
for i in range(0, len(array), 2):
final += array[i] * array[i+1]
return final
#print(array_translate(["Cat", 2, "Dog", 3, "Mouse", 1]))
#print(array_translate(["red", 3, "blue", 1]))
def reverse_words(sent):
final = []
list = sent.split(" ")
for ele in list:
rword = reverse_word(ele)
final.append(rword)
ffinal = " ".join(final)
return ffinal
def reverse_word(word):
result = ""
for i in range(len(word)-1, -1, -1):
result += word[i]
return result
#print(reverse_words("keep coding"))
#print(reverse_words("simplicity is prerequisite for reliability"))
#rotating array method 1
def rotate_array(arr, num):
for i in range(num):
arr = rotate(arr)
return arr
def rotate(arr):
new_arr = []
new_arr.append(arr[len(arr)-1])
for i in range(len(arr)-1):
new_arr.append(arr[i])
arr = new_arr
return arr
#print(rotate(["a", "b", "c", "d" ]))
#print(rotate_array([ "Matt", "Danny", "Mashu", "Matthias" ], 1))
#print(rotate_array([ "a", "b", "c", "d" ], 2))
#rotating array method 2
def rotate_array(arr, num):
for i in range(num):
arr = rotate(arr)
return arr
def rotate(arr):
new_arr = []
new_arr.append(arr[len(arr)-1])
new_arr = new_arr + arr[:len(arr)-1]
arr = new_arr
return arr
#print(rotate(["a", "b", "c", "d" ]))
#print(rotate_array([ "Matt", "Danny", "Mashu", "Matthias" ], 1))
#print(rotate_array([ "a", "b", "c", "d" ], 2))
def pig_latin_word(word):
result = ""
vowels = ['a','e','i','o','u']
st = 'yay'
if word[0] in vowels:
result = word + st
return result
else:
ind = 0
for i in range(len(word)):
if word[i] in vowels:
ind = i
break
result = word[i:len(word)]
result += word[:i]
result += 'ay'
return result
#print(pig_latin_word("apple")) # => "appleyay"
#print(pig_latin_word("eat")) # => "eatyay"
#print(pig_latin_word("banana")) # => "ananabay"
#print(pig_latin_word("trash")) # => "ashtray"
def combinations(arr):
result = []
for i in range(len(arr)):
for j in range(len(arr)):
if j > i:
result.append([arr[i],arr[j]])
return result
#print(combinations(["a", "b", "c"]))
#print(combinations([0, 1, 2, 3]))
#find the number of pairs whos sum is equal to zero.
def opposite_count(nums):
pairs = 0
for i in range(len(nums)):
for j in range(len(nums)):
if j > i:
if nums[i] + nums[j] == 0:
pairs += 1
return pairs
#print(opposite_count([ 2, 5, 11, -5, -2, 7 ]))
#print(opposite_count([ 21, -23, 24 -12, 23 ]))
def two_d_sum(arr):
sum = 0
for i in range(len(arr)):
for j in range(len(arr[i])):
sum += arr[i][j]
return sum
array_1 = [
[4, 5],
[1, 3, 7, 1]
]
array_2 = [
[3, 3],
[2],
[2, 5]
]
#print(two_d_sum(array_1))
#print(two_d_sum(array_2))
def two_d_translate(arr):
result = []
for i in range(len(arr)):
for j in range(arr[i][1]):
result.append(arr[i][0])
return result
arr_1 = [
['boot', 3],
['camp', 2],
['program', 0]
]
arr_2 = [
['red', 1],
['blue', 4]
]
#print(two_d_translate(arr_1))
#print(two_d_translate(arr_2))
def get_double_age(hash):
for k in hash:
if k == "age":
return hash[k] * 2
#print(get_double_age({"name":"App Academy", "age":5}))
#print(get_double_age({"name":"Ruby", "age":23}))
def get_full_name(hash):
str = ""
str += hash['first'] + " "
str += hash['last']
str += ", "
str += hash['title']
return str
hash1 = {"first":"Michael", "last":"Jordan", "title": "GOAT"}
#print(get_full_name(hash1)) # => "Michael Jordan, the GOAT"
hash2 = {"first":"Fido", "last":"McDog", "title": "Loyal"}
#print(get_full_name(hash2)) #
def word_lengths(sentence):
hash = {}
words = sentence.split(" ")
for word in words:
hash[word] = len(word)
return hash
#print(word_lengths("this is fun")) #=> {"this"=>4, "is"=>2, "fun"=>3}
#print(word_lengths("When in doubt, leave it out")) #=> {"When"=>4, "in"=>2, "doubt,"=>6, "leave"=>5, "it"=>2, "out"=>3}
def retrieve_values(hash1, hash2, key):
result = []
for k in hash1:
if k == key:
result.append(hash1[k])
for k in hash2:
if k == key:
result.append(hash2[k])
return result
dog1 = {"name":"Fido", "color":"brown"}
dog2 = {"name":"Spot", "color":"white"}
#print(retrieve_values(dog1, dog2, "name"))
#print(retrieve_values(dog1, dog2, "color"))
def cat_builder(name_str, color_str, age_num):
d = {}
d['name'] = name_str
d['color'] = color_str
d['age'] = age_num
return d
#print(cat_builder("Whiskers", "orange", 3))
#print(cat_builder("Salem", "black", 100))
def ae_count(str):
a = 0
e = 0
d = {}
for l in str:
if l == 'a':
a += 1
if l == 'e':
e += 1
d["a"] = a
d["e"] = e
return d
#print(ae_count("everyone can program"))
#print(ae_count("keyboard"))
def element_count(arr):
hash = {}
for ele in arr:
c = 0
for val in arr:
if ele == val:
c += 1
if ele not in hash:
hash[ele] = c
return hash
#print(element_count(["a", "b", "a", "a", "b"]))
#print(element_count(["red", "red", "blue", "green"]))
def select_upcase_keys(hash):
d = {}
for key in hash:
if key == key.upper():
d[key] = hash[key]
return d
#print(select_upcase_keys({"make":"Tesla", "MODEL":"S", "Year": 2018, "SEATS": 4}))
#print(select_upcase_keys({"DATE":"July 4th","holiday": "Independence Day", "type":"Federal"}))
def hand_score(hand):
score = 0
hash = {"A":4,"K":3,"Q":2,"J":1}
for c in hand:
score += hash[c.upper()]
return score
#print(hand_score("AQAJ"))
#print(hand_score("jJka"))
def frequent_letters(string):
result = []
hash = {}
for l in string:
n = 0
for c in string:
if c == l:
n += 1
if l not in hash:
hash[l] = n
for k,i in hash.items():
if i > 2:
result.append(k)
return result
#print(frequent_letters('mississippi'))
#print(frequent_letters('bootcamp'))
def hash_to_pairs(hash):
result = []
for k,i in hash.items():
result.append([k,i])
return result
#print(hash_to_pairs({"name":"skateboard", "wheels":4, "weight":"7.5 lbs"}))
#print(hash_to_pairs({"kingdom":"animalia", "genus":"canis", "breed":"German Shepherd"}))
def unique_elements(arr):
result = []
hash = {}
for l in arr:
if l not in hash:
n = 0
for c in arr:
if c == l:
n += 1
hash[l] = n
for k,v in hash.items():
result.append(k)
return result
#print(unique_elements(['a', 'b', 'a', 'a', 'b', 'c']))
def element_replace(arr, hash):
for i in range(len(arr)):
if arr[i] in hash:
arr[i] = hash[arr[i]]
return arr
arr1 = ["LeBron James", "Lionel Messi", "Serena Williams"]
hash1 = {"Serena Williams":"tennis", "LeBron James":"basketball"}
#print(element_replace(arr1, hash1))
arr2 = ["dog", "cat", "mouse"]
hash2 = {"dog":"bork", "cat":"meow", "duck":"quack"}
#print(element_replace(arr2, hash2))
def map_by_name(arr):
result = []
for hash in arr:
result.append(hash["name"])
return result
pets = [
{"type":"dog", "name":"Rolo"},
{"type":"cat", "name":"Sunny"},
{"type":"rat", "name":"Saki"},
{"type":"dog", "name":"Finn"},
{"type":"cat", "name":"Buffy"}
]
#print(map_by_name(pets))
def isPrime(num):
p = True
if num < 2:
return False
for i in range(2,num):
if num%i != 0:
p = True
else:
p = False
return p
return p
def next_prime(num):
f = False
p = 0
while f == False:
num += 1
if isPrime(num) == True:
p = num
f = True
return p
def rep_prime(xs):
for i in range(len(xs)):
if isPrime(xs[i]):
x = next_prime(xs[i])
xs[i] = x
return xs
xs = [1,3,5,4,7]
#print(rep_prime(xs))
def map_by_key(arr, key):
result = []
for hash in arr:
result.append(hash[key])
return result
locations = [
{"city":"New York City", "state":"New York", "coast":"East"},
{"city":"San Francisco", "state":"California", "coast":"West"},
{"city":"Portland", "state":"Oregon", "coast":"West"},
]
#print(map_by_key(locations, "state"))
def yell_sentence(sent):
str = ""
list = sent.split(" ")
new = []
for i in range(len(list)):
temp = list[i].upper() + "!"
new.append(temp)
str = " ".join(new)
return str
#print(yell_sentence("I have a bad feeling about this"))
#Have to use Hash.
def whisper_words(words):
hash = {}
li = []
for i in range(len(words)):
hash[words[i].lower()] = "..."
for k,v in hash.items():
li.append(k+v)
return li
#print(whisper_words(["KEEP", "The", "NOISE", "down"]))
def o_words(sentence):
list = []
li = sentence.split(" ")
for el in li:
if "o" in el:
list.append(el)
return list
#print(o_words("How did you do that?"))
'''
def last_index(str, char):
index = -1
for i in range(len(str)):
if str[i] == char:
index = i
return index
'''
def last_index(str, char):
index = -1
for i in range(len(str) - 1, -1, -1):
if str[i] == char:
index = i
break
return index
#print(last_index("abca", "a"))
#print(last_index("mississipi", "i"))
#print(last_index("octagon", "o"))
#print(last_index("programming", "m"))
def most_vowels(sentence):
vowels = ['a', 'e', 'i', 'o', 'u']
list = sentence.split(" ")
hash = {}
for word in list:
vow = 0
for i in range(len(word)):
if word[i] in vowels:
vow += 1
hash[word] = vow
max = ""
cou = 0
for k,v in hash.items():
if v > cou:
cou = v
max = k
return max
#print(most_vowels("what a wonderful life"))
def prime(num):
for i in range(2,num):
if num%i == 0:
return False
return True
def pick_primes(numbers):
list = []
for num in numbers:
if isPrime(num) == True:
list.append(num)
return list
#print(pick_primes([2, 3, 4, 5, 6]))
#print(pick_primes([101, 20, 103, 2017]))
def prime_factors(nums):
prime_fac = []
for i in range(2,nums):
if prime(i) == True:
if nums%i == 0:
prime_fac.append(i)
return prime_fac
#print(prime_factors(24))
#print(prime_factors(60))
def even(num):
if num%2 == 0:
return True
return False
def greatest_factor_array(arr):
for i in range(len(arr)):
if even(arr[i]) == True:
arr[i] = arr[i]//2
return arr
#print(greatest_factor_array([16, 7, 9, 14]))
#print(greatest_factor_array([30, 3, 24, 21, 10]))
def perfect_square(num):
bool = False
for i in range(1,num//2):
if i * i == num:
bool = True
return bool
return bool
#print(perfect_square(5))
#print(perfect_square(12))
#print(perfect_square(30))
#print(perfect_square(9))
#print(perfect_square(25))
def triple_sequence(start, length):
result = [start]
i = 0
while i < length-1:
result.append(result[i] * 3)
i += 1
return result
#print(triple_sequence(2,4))
#print(triple_sequence(4,5))
def summation_sequence(start, length):
result = []
result.append(start)
k = 0
while k < length-1:
ele = 0
for i in range(result[-1] + 1):
ele += i
result.append(ele)
k += 1
return result
#print(summation_sequence(3, 4))
#print(summation_sequence(5, 3))
def fibonacci(length):
if length == 0:
return []
if length == 1:
return [1]
if length == 2:
return [1,1]
result = [1,1]
a = 1
b = 1
i = 0
while i < length-2:
result.append(result[i]+result[i+1])
i += 1
return result
#print(fibonacci(0))
#print(fibonacci(1))
#print(fibonacci(6))
#print(fibonacci(8))
def caesar_cipher(str, num):
result = ""
abc = "abcdefghijklmnopqrstuvwxyz"
for i in range(len(str)):
for j in range(len(abc)):
if str[i] == abc[j]:
if (j+num) >= len(abc):
nind = (j+num) - 26
result += abc[nind]
else:
result += abc[j+num]
return result
#print(caesar_cipher("apple", 1))
#print(caesar_cipher("bootcamp", 2))
#print(caesar_cipher("zebra", 4))
def vowel_cipher(string):
result = ""
vowels = ['a','e','i','o','u']
hash = {'a':'e', 'e':'i','i':'o','o':'u', 'u':'a'}
for i in range(len(string)):
if string[i] in vowels:
result += hash[string[i]]
else:
result += string[i]
return result
#print(vowel_cipher("bootcamp"))
#print(vowel_cipher("paper cup"))
def double_letter_count(string):
counter = 0
for i in range(len(string) - 1):
l = string[i]
if l == string[i+1]:
counter += 1
return counter
#print(double_letter_count("the jeep rolled down the hill"))
#print(double_letter_count("bootcamp"))
def adjacent_sum(arr):
result = []
for i in range(len(arr)-1):
result.append(arr[i] + arr[i+1])
return result
#print(adjacent_sum([3, 7, 2, 11]))
#print(adjacent_sum([2, 5, 1, 9, 2, 4]))
def uplevel(arr):
r = []
for i in range(len(arr)-1):
r.append(arr[i] + arr[i+1])
return r
def pyramid_sum(base):
result = [base]
i = 1
while i < len(base):
temp = uplevel(result[0])
result.insert(0, temp)
i += 1
return result
#print(pyramid_sum([1, 4, 6]))
#print(pyramid_sum([3, 7, 2, 11]))
def all_else_equal(arr):
s = sum(arr)
for num in arr:
if num == s/2:
return num
return None
#print(all_else_equal([2, 4, 3, 10, 1]))
#print(all_else_equal([6, 3, 5, -9, 1]))
#print(all_else_equal([1, 2, 3, 4]))
def anagrams(word1, word2):
if len(word1) != len(word2):
return False
hash1 ={}
hash2 ={}
for i in range(len(word1)):
if word1[i] in hash1:
hash1[word1[i]] = hash1[word1[i]] + 1
else:
hash1[word1[i]] = 1
for i in range(len(word2)):
if word2[i] in hash2:
hash2[word2[i]] = hash2[word2[i]] + 1
else:
hash2[word2[i]] = 1
# print(hash1)
# print(hash2)
for k,v in hash1.items():
if k in hash2:
if v != hash2[k]:
return False
else:
return False
return True
#print(anagrams("cat", "act"))
#print(anagrams("restful", "fluster"))
#print(anagrams("cat", "dog"))
#print(anagrams("boot", "bootcamp"))
def consonant_cancel(str):
result = ""
vowels = ['a','e','i','o','u']
list = str.split(" ")
for word in list:
for i in range(len(word)):
if word[i] in vowels:
result += word[i:]
result += " "
break
return result
#print(consonant_cancel("down the rabbit hole"))
#print(consonant_cancel("writing code is challenging"))
def same_char_collapse(str):
col = True
s = str
while col == True:
for i in range(len(s)-1):
t = str[i]
if t != str[i+1]:
col = False
else:
col = False
s = ""
s += s[:i] + s[:i+2]
#print(s)
break
return s
def same_char_collapse(str):
chars = list(str)
print(chars)
colapsing = True
i = 0
while i < (len(chars) - 1):
print(chars[i], chars[i+1], i)
if chars[i] == chars[i+1]:
chars.pop(i)
chars.pop(i)
if i != 0:
i -= 1
else:
i += 1
return "".join(chars)
#print(same_char_collapse("zzzxaaxy"))
#print(same_char_collapse("uqrssrqvtt"))
def generate(num):
triangle = [[1],[1,1]]
row = []
return 0
def t(n):
tri = []
for n in range(1, n+1):
row = [1]
for i in range(1,n-1):
row.append(0)
row.append(1)
tri.append(row)
return tri
def pas(n):
tri = t(n)
for i in range(len(tri)):
for j in range(len(tri[i])):
if tri[i][j] == 0:
tri[i][j] = tri[i-1][j-1] + tri[i-1][j]
return tri
print(pas(4))
|
#Class to represent a Room object
class Room:
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
print("-> Room generated with dimensions x: {0}, y: {1}, z: {2}".format(x, y, z))
|
import geopandas as gpd
from shapely.geometry import Point
def spatial_join_zipcode(df, communities):
"""
Function to spatially join communities data to a dataframe with latitude and longitude.
Note: "lat_long" column must be of tuple type with first element being latitude
and second element being longitude
df: pandas dataframe with "lat_long" column
communities: geopandas dataframe with polygon geometry
"""
df["geometry"] = df["lat_long"].apply(lambda x: Point(tuple(reversed(eval(x)))))
if hasattr(df, 'crs'):
df = df.to_crs(communities.crs)
else:
df.crs = communities.crs
df = gpd.sjoin(df, communities, how="inner", op='intersects')
del df["index_right"]
return df
|
import random
class Esqueleto():
'''Representa el esqueleto interno del Gunpla.'''
def __init__(self):
'''Inicializa los atributos de un Esqueleto'''
self.velocidad = random.randint(-25, 50)
self.energia = random.randint(1000,2000)
self.movilidad = random.randint(1000,1500)
self.slots = random.randint(3, 5)
def __str__(self):
'''Devuelve una cadena que representa las estadisticas del esqueleto'''
cadena = ("\n----Esqueleto----\n")
cadena+= (" Velocidad: {}\n".format(self.velocidad))
cadena+= (" Energia: {}\n".format(self.energia))
cadena+= (" Movilidad: {}\n".format(self.movilidad))
cadena+= (" Slots: {}\n".format(self.Slots))
return cadena
def get_velocidad(self):
'''Devuelve la velocidad del esqueleto. Es un valor fijo'''
return self.velocidad
def get_energia(self):
'''Devuelve la energía del esqueleto. Es un valor fijo'''
return self.energia
def get_movilidad(self):
'''Devuelve la movilidad del esqueleto. Es un valor fijo'''
return self.movilidad
def get_cantidad_slots(self):
'''Devuelve la cantidad de slots (ranuras) para armas que tiene el esqueleto.
Es un valor fijo'''
return self.slots
|
import sys
import turtle
wn = turtle.Screen()
s = turtle.Turtle()
mylist=[-3,-5,0,2,3,7,11,12]
wordlist=["How", "many" ,"fish" ,"does" ,"the" ,"little", "child", "kid", "have"]
samlist={"How", "sam", "many", "fish", "does", "the", "little" ,"kid","have?"}
def test(did_pass):
""" Print the result of a test. """
linenum = sys._getframe(1).f_lineno # Get the caller's line number.
if did_pass:
msg = "Test at line {0} ok.".format(linenum)
else:
msg = ("Test at line {0} FAILED.".format(linenum))
print(msg)
def test_suite():
"""run the suite of tests for code in this module (this file)"""
print("tests for 5 words")
print("\ncount_odd")
test(count_odd(mylist)==5)
print("\nsum_even")
test(sum_even(mylist)==14)
print("\nsum negative")
test(sum_negative(mylist)==-8)
print("test for number of words that have wordlength 5")
test(word_length(wordlist) == 1)
print("test for sum of even exept first one (#5)")
test(sum_element(mylist) == -8)
print("test for sam")
test(word_sam(samlist) == 1)
print("\nis_prime")
test(is_prime(11))
test(not is_prime(35))
test(is_prime(19911121))
test(is_prime(19701013))
"""Write a function to count how many odd numbers are in a list."""
def count_odd(numlist):
count = 0
for i in numlist:
if i%2 != 0:
count += 1
return count
print(count_odd(mylist))
"""Sum up all the even numbers in a list."""
def sum_even(numlist):
mysum=0
for i in numlist:
if i%2 == 0:
mysum = mysum +i
return mysum
print(sum_even(mylist))
"""Sum up all the negative numbers in a list."""
def sum_negative(numlist):
mysum = 0
for i in numlist:
if i < 0:
mysum = mysum + i
return mysum
print(sum_negative(mylist))
"""Count how many words in a list have length 5"""
def word_length(list):
words=0
for i in list:
if 5 == len(i):
words += 1
return words
print(word_length(wordlist))
"""Sum all the elements in a list up to but not including the first even number.
(Write your unit tests. What if there is no even number?)
"""
def sum_element(list):
mysum=0
for i in list:
if i%2 == 0:
break
else:
mysum +=i
return mysum
print(sum_element(mylist))
"""Count how many words occur in a list up to and including the first occurrence
1of the word “sam”. (Write your unit tests for this case too. What if “sam” does notoccur?)"""
def word_sam(list):
count =0
for i in samlist:
if i == "sam":
count += 1
break
count += 1
return count
print(word_sam(samlist))
def sqrt(n):
"""Ex 7:Newtons square root function -"""
approx = n/2.0 # Start with some or other guess at the answer
while True:
better = (approx + n/approx)/2.0
print("better",better)
if abs(approx - better) < 0.001:
return better
approx = better
print("sqrt",sqrt(36.0))
def is_prime(n):
"""Write a function, is_prime, which takes a single integer
argument and returns True when the argument is a prime number and False otherwise"""
for i in range(2,n):
if n % i == 0:
return False
return True
"""Revisit the drunk pirate problem from the exercises in chapter 3. This time,
the drunk pirate makes a turn, and then takes some steps forward, and repeats this.
Our social science student now records pairs of data: the angle of each turn, and the
number of steps taken after the turn. Her experimental data is [(160, 20), (-43, 10),
(270, 8), (-43, 12)]. Use a turtle to draw the path taken by our drunk friend.
"""
import turtle
wn = turtle.Screen()
fun = turtle.Turtle()
steps = [(160, 20), (-43, 10), (270, 8), (-43, 12)]
for (angle, moves) in steps:
fun.right(angle)
fun.forward(moves)
"""Many interesting shapes can be drawn by the turtle by giving a list of pairs like we did
above, where the first item of the pair is the
angle to turn, and the second item is the distance to move forward. Set up a list of pairs
so that the turtle draws a house with a cross through the centre, as show here. This should
be done without going over any of the lines / edges more than once, and without lifting your
pen."""
import turtle
wn = turtle.Screen()
fun = turtle.Turtle()
fun.pensize(10)
house = [(270,50), (30, 50), (120,50), (120,50), (225,70.1), (225,50), (225,70.1), (225,50) ]
for (angle,moves) in house:
fun.right(angle)
fun.forward(moves)
test_suite()
|
"""1. Add some new key bindings to the first sample program:
Pressing keys R, G or B should change tess’ color to Red, Green or Blue.
Pressing keys + or - should increase or decrease the width of tess’ pen. Ensure that the pen size stays between 1 and 20 (inclusive).
Handle some other keys to change some attributes of tess, or attributes of the window, or to give her new behaviour that can be controlled from the keyboard."""
import turtle
turtle.setup(400, 500) # Determine the window size
wn = turtle.Screen() # Get a reference to the window
wn.title("Handling keypresses!") # Change the window title
wn.bgcolor("lightgreen") # Set the background color
tess = turtle.Turtle() # Create our favorite turtle
tess_size = 3
tess_size = tess.pensize(tess_size)
# The next four functions are our "event handlers".
def h1():
tess.forward(30)
def h2():
tess.left(45)
def h3():
tess.right(45)
def h4():
wn.bye()
def red():
tess.color("red")
def green():
tess.color('green')
def blue():
tess.color('blue')
sz = 1
def h8():
global sz
sz += 1
if sz > 20:
sz = 20
tess.pensize(sz)
def h9():
global sz
sz -= 1
if sz<1:
sz=1
def h10():
tess.circle(20)
wn.onkey(h1, "Up")
wn.onkey(h2, "Left")
wn.onkey(h3, "Right")
wn.onkey(h4, "q")
wn.onkey(red, "r")
wn.onkey(green, "g")
wn.onkey(blue, "b")
wn.onkey(h8, "=")
wn.onkey(h9, "-")
wn.onkey(h10, "c")
wn.listen()
wn.mainloop()
|
revenue = [14574.49, 7606.46, 8611.41, 9175.41, 8058.65, 8105.44, 11496.28, 9766.09, 10305.32, 14379.96, 10713.97, 15433.50]
expense = [12051.82, 5695.07, 12319.20, 12089.72, 8658.57, 840.20, 3285.73, 5821.12, 6976.93, 16618.61, 10054.37, 3803.96]
profit = []
for i in range(12):
profit.append(revenue[i]-expense[i])
print("Profit : %s"%(profit))
tax =[]
for i in range(12):
tax.append(0.3*profit[i])
taxround=[]
for i in range(12):
taxround.append(round(tax[i]))
print("\nTax : %s"%(taxround))
pat=[]
for i in range(12):
pat.append(profit[i]-taxround[i])
print("\nProfit After Tax : %s"%(pat))
profitmargin=[]
for i in range(12):
profitmargin.append(pat[i]/revenue[i]*100)
pmr=[]
for i in range(12):
pmr.append(round(profitmargin[i]))
print("\nProfit Margin : %s" %(pmr))
mean=sum(pat)/len(pat)
print("\nGood Months:")
for i in range(12):
if mean>pat[i]:
print(i,end=",")
print("\nBad Months:")
for i in range(12):
if mean<pat[i]:
print(i,end=",")
|
def fib_rec (n):
if n<=1:
return n
else:
return fib_rec(n-1)+fib_rec(n-2)
n=int(input("Enter a number : "))
while n <=0:
n=int(input("Please enter a positive integer : "))
print("Fibonacci series of",n,"is :")
for i in range(n):
print(fib_rec(i))
|
import random
import hashlib
def main():
print('starting the search')
searches = 0
matches = list()
try:
while True:
searches += 1
string = makeString()
if isMatch(string):
print('We have success! ' + string + ' is the winner!')
matches.append(string, searches)
else:
print
if searches%100000 == 0:
print("still looking after " +str(searches))
except KeyboardInterrupt:
print("\nUser aborted process.")
if len(matches) > 0:
print("Matches found: ")
print(matches)
else:
print("No matches found. :(")
def makeString():
string=''
alphabet = 'abcdef1234567890'
for count in range(0,32):
for x in random.sample(alphabet, 1):
string += x
return bytes(string, encoding='utf-8')
def isMatch(string):
digested_string = hashlib.md5(string).digest()
if (digested_string == string):
return True
else:
return False
if __name__ == "__main__":
main()
|
import re
from functools import reduce
def doCode():
m = re.compile("(\w+):")
soln = 0
x = 0
d = set()
f = open("input", "r+")
lines = f.readlines()
for i in lines:
if i.strip() == "":
x += 1
if not checkValid(d):
print(f"invalid: {d}")
else:
print(f" valid: {d}")
soln += checkValid(d)
d = set()
continue
match = m.finditer(i)
for i in match:
f = i.group(1)
print(f)
d.add(f)
def checkValid(d):
fields = {"byr", "iyr", "eyr", "hgt", "hcl", "ecl", "pid"}
for f in fields:
if f not in d:
return False
return True
print(f"answer: {doCode()}")
|
from homework1.task05 import find_maximal_subarray_sum
def test_empty_list_case():
"""Testing that function returns 0 if list is empty"""
assert find_maximal_subarray_sum([], 3) == 0
def test_all_negative_case():
"""Testing that function returns correct answer with negative only"""
assert find_maximal_subarray_sum([-1, -2, -3, -4, -10], 4) == -1
def test_pos_neg_case():
"""Testing that returns correct with positive and negative integers"""
assert find_maximal_subarray_sum([1, 3, -1, -3, 5, 3, 6, 7], 3) == 16
|
"""
Необходимо создать 3 класса и взаимосвязь между ними (Student, Teacher,
Homework)
Наследование в этой задаче использовать не нужно.
Для работы с временем использовать модуль datetime
1. Homework принимает на вход 2 атрибута: текст задания и количество дней
на это задание
Атрибуты:
text - текст задания
deadline - хранит объект datetime.timedelta с количеством
дней на выполнение
created - c точной датой и временем создания
Методы:
is_active - проверяет не истекло ли время на выполнение задания,
возвращает boolean
2. Student
Атрибуты:
last_name
first_name
Методы:
do_homework - принимает объект Homework и возвращает его же,
если задание уже просрочено, то печатет 'You are late' и возвращает None
3. Teacher
Атрибуты:
last_name
first_name
Методы:
create_homework - текст задания и количество дней на это задание,
возвращает экземпляр Homework
Обратите внимание, что для работы этого метода не требуется сам объект.
PEP8 соблюдать строго.
Всем перечисленным выше атрибутам и методам классов сохранить названия.
К названием остальных переменных, классов и тд. подходить ответственно -
давать логичные подходящие имена.
"""
import datetime
class Homework:
"""This is a class which contains homework description
and the number of days given to complete the task
with checking expiration of deadline.
:param text: Description of homework
:type text: str
:param deadline_days: The number of days given to complete the task
:type deadline_days: int
"""
def __init__(self, text: str, deadline_days: int):
"""Constructor method"""
self.text = text
self.deadline_days = datetime.timedelta(days=deadline_days)
self.created = datetime.datetime.now()
def is_active(self) -> bool:
"""This function checks whether homework deadline is active or expired
:return: `True` if homework is active (deadline not expired) `False` otherwise
:rtype: bool
"""
return self.created + self.deadline_days > datetime.datetime.now()
class Student:
"""This is a class which contains full name of a student
and allows to check deadline expiration of some homework.
:param first_name: First name of a student
:type first_name: str
:param last_name: Last name of a student
:type last_name: str
"""
def __init__(self, first_name: str, last_name: str):
"""Constructor method"""
self.last_name = last_name
self.first_name = first_name
@staticmethod
def do_homework(homework: Homework) -> Homework:
"""This function returns homework expired or not.
:param homework: object with homework description
and number of days given to complete the task
:type homework: Homework
:return: homework if homework is active and None otherwise.
In the latter case prints 'You are late!'
:rtype: Homework
"""
if homework.is_active():
return homework
print("You are late")
class Teacher:
"""This is a class which contains full name of a teacher
and allows to create some homework.
:param first_name: First name of a teacher
:type first_name: str
:param last_name: Last name of a teacher
:type last_name: str
"""
def __init__(self, first_name: str, last_name: str):
self.last_name = last_name
self.first_name = first_name
@staticmethod
def create_homework(text: str, deadline_days: int) -> Homework:
"""This function creates homework with text and deadline days given
:param text: Description of the homework
:type text: str
:param deadline_days: The number of days given to complete the task
:type deadline_days: int
:return: homework
:rtype: Homework
"""
return Homework(text, deadline_days)
|
EMPTY_CELL = ' '
class Field:
def __init__(self):
self._field = [[EMPTY_CELL for _ in range(3)] for _ in range(3)]
def __str__(self):
return '\n'.join('|'.join(cell for cell in row) for row in self._field)
def set_symbol(self, x, y, symbol):
"""
>>> f = Field()
>>> f.set_symbol(0, 0, 'X')
>>> f._field[0][0]
'X'
>>> f = Field()
>>> f.set_symbol(0, 0, 'X')
>>> f.set_symbol(0, 0, 'X')
Traceback (most recent call last):
...
ValueError
"""
if self._field[x][y] != EMPTY_CELL:
raise ValueError
self._field[x][y] = symbol
def _test_rows(self, field):
for row in field:
if row[0] != EMPTY_CELL and row == [row[0]]*3:
return True
return False
def _game_over_by_rows_(self):
"""
>>> f = Field()
>>> f._game_over_by_rows_()
False
>>> f = Field()
>>> f._field[0] = ['X', 'X', 'X']
>>> f._game_over_by_rows_()
True
"""
return self._test_rows(self._field)
def _game_over_by_columns(self):
"""
>>> f = Field()
>>> f._game_over_by_columns()
False
>>> f = Field()
>>> f._field[0][0] = ['X']
>>> f._field[1][0] = ['X']
>>> f._field[2][0] = ['X']
>>> f._game_over_by_columns()
True
"""
field = list(zip(*self._field))
return self._test_rows(field)
def game_over(self):
pass
if __name__ == '__main__':
f = Field()
f.set_symbol(2, 2, 'X')
f.set_symbol(2, 1, '0')
print(f)
|
class A:
def __init__(self):
self.__a = 1
def f(self):
return self.__a
a = A()
print(vars(a))
class B(A):
def __init__(self):
super().__init__()
self.__a = 2
b = B()
print(b.f())
|
import streamlit as st
from model import get_model
import numpy as np
from PIL import Image
import cv2
face_cascade = cv2.CascadeClassifier(
cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
model = get_model(pretrained=True, dataset_name="RAFDB")
basic_emotions = ['surprise', 'fear', 'disgust',
'happy', 'sad', 'angry', 'neutral']
def detect_faces(our_image):
img = np.array(our_image)
# Detect faces (not able to detect faces for the images which contains face image only)
# faces = face_cascade.detectMultiScale(img, 1.1, 4)
# # Draw rectangle around the faces
# for (x, y, w, h) in faces:
# To draw a rectangle in a face
# cv2.rectangle(img, (x, y), (x + w, y + h), (255, 255, 0), 2)
# face = img[y:y+h, x:x+w]
face_resized = cv2.resize(img, (50, 50))
try:
gray = cv2.cvtColor(face_resized, cv2.COLOR_BGR2GRAY)
except:
gray = face_resized.copy()
gray_three = cv2.merge([gray, gray, gray])
inp = np.expand_dims(gray_three, axis=0)
preds = model.predict(inp) # predicts [emotion, gender, race, age]
pred = preds[0]
emotion = basic_emotions[np.argmax(pred)]
# cv2.putText(img, emotion, (20, 0 + 20 ),
# cv2.FONT_HERSHEY_COMPLEX_SMALL, 2.0, (0, 0, 255))
return emotion
def main():
html_temp = """
<body>
<div style="padding:10px">
<h2 style="text-align:center;">Face Recognition WebApp</h2>
</div>
</body>
"""
st.markdown(html_temp, unsafe_allow_html=True)
image_file = st.file_uploader("Upload Image", type=['jpg', 'png', 'jpeg'])
if image_file is not None:
data_load_state = st.text('Predicting...')
with open("style.css") as f:
st.markdown('<style>{}</style>'.format(f.read()),
unsafe_allow_html=True)
our_image = Image.open(image_file)
st.image(our_image, width=250)
emotion = detect_faces(our_image)
st.write(f"Prediction : {emotion}")
data_load_state.text("")
if __name__ == '__main__':
main()
|
# -*- coding: utf-8 -*-
"""
Created on Wed Jul 15 17:37:47 2020
@author: singh
"""
# 2. Read or convert the columns ‘Created Date’ and Closed Date’ to datetime datatype and create a new column ‘Request_Closing_Time’ as the time elapsed between request creation and request closing.
import datetime as dt
import datetime, time
df['Created Date'] = pd.to_datetime(df['Created Date'])
print(df['Created Date'].dtype)
df['Closed Date'] = pd.to_datetime(df['Closed Date'])
print(df['Closed Date'].dtype)
df['Request_Closing_Time'] = df['Closed Date'] - df['Created Date']
print(df['Request_Closing_Time'].head())
|
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
df=pd.read_csv("C:/Users/mahid/ML LAB/Logistic Regression/insurance_data.csv")
plt.scatter(df.age,df.bought_insurance)
data_train,data_test,tar_train,tar_test=train_test_split(df.age,df.bought_insurance,test_size=0.25,random_state=10)
data_train1=data_train.values.reshape(-1,1)
data_test1=data_test.values.reshape(-1,1)
tar_train1=tar_train.values.reshape(-1,1)
tar_test1=tar_test.values.reshape(-1,1)
model=LogisticRegression()
model.fit(data_train1,tar_train1)
print(model.predict(data_test1))
plt.xlabel("age")
plt.ylabel("bought or not")
plt.plot(data_test1,model.predict(data_test1))
|
#!/usr/bin/python
#!encoding: UTF-8
import matplolib,pyplot as pl
import sys
import modulo
import time
startubuntu=time.time()
startcpu=time.clock()
t=[]
argumentos = sys.argv[1:]
if (len(argumentos) == 8):
n = int (argumentos[0])
aproximaciones = int (argumentos[1])
umbral = []
for i in range (2,7):
umbral.append(float (argumentos[i]))
nombre_fichero = argumentos[7]
else:
print "Introduzca el numero de intervalos (n > 0):"
n = int (raw_input ());
print "Introduzca el numero de aproximaciones:"
aproximaciones = int (raw_input ());
print "Introduzca 5 umbrales de error:"
umbral = []
for i in range (5):
print "Introduzca el umbral", i, ":"
umbral.append(float (raw_input ()));
print "Introduzca el nombre del fichero para almacenar los resultados:"
nombre_fichero = raw_input ();
if (n > 0):
startubuntu=time.time()
startcpu=time.clock()
# Una forma de averiguar si un fichero existe o no puede ser esta
# debemos de incluir el paquete os.path
# if os.path.isfile(nombre_fichero):
# fichero = open (nombre_fichero, "a")
# else:
# fichero = open (nombre_fichero, "w")
#Otra forma puede ser mediante excepciones, como vemos a continuacion
try:
fichero = open (nombre_fichero, "a")
except:
fichero = open (nombre_fichero, "w")
fichero.write ("Nº de intervalos: %d\n" % (n))
for i in range (5):
porcentaje = modulo.error (n, aproximaciones, umbral[i])
t=t+[porcentaje]
fichero.write ("%2.2f%% de fallos para el umbral %2.5f\n" % (porcentaje, umbral[i]))
pl.plot(x,umbral)
pl.show(x,umbral)
finishubuntu=time.time()
finishcpu=time.clock()
timecpu=finishcpu-startcpu
timeubuntu=finishubuntu-startubuntu
fichero.write ("Tiempo Ubuntu:%2.10f \n Tiempo CPU: %2.10f" %(timeubuntu,timecpu))
fichero.close ()
else:
print "El valor de los intervalos debe ser mayor que 0"
|
import coffee_shop
from coffee_shop import add_milk
print("Welcome to", coffee_shop.shop_name)
print("Available sizes: \n", "\n".join(coffee_shop.coffee_sizes))
print("Available roasts: \n", "\n ".join(coffee_shop.coffee_roasts))
print("Available milks: \n", "\n".join(coffee_shop.milk_type))
order_size = input("What size would you like? ")
order_roast = input("What kind of roast do you want? ")
shop_says = coffee_shop.order_coffee(order_size, order_roast, add_milk)
print(shop_says)
add_milk_response = input("Do you wanna add milk? y/n")
if "y" in add_milk_response.lower():
print("Available milks: \n", "\n".join(coffee_shop.milk_type))
milk_type = input('What type of milk? ')
print(shop_says)
|
from copy import deepcopy
class Queue:
"""A basic Stack implementation using lists""" # docstring
def __init__(self):
self.items = []
def enqueue(self, item):
self.items.append(item)
def dequeue(self):
return self.items.pop(0) # If no index is specified, a.pop() removes and returns the last item in the list.
def size(self):
return len(self.items)
def isEmpty(self):
return len(self.items) == 0
def compare(self, otherStack):
return self.items == otherStack.items
def reverse(self):
self.items.reverse()
def getNewReversedQueue(self):
temp = deepcopy(self)
temp.reverse()
return temp
def printItems(self):
print(self.items)
|
"""
剑指 Offer 26. 树的子结构
输入两棵二叉树 A和 B,判断 B是不是 A的子结构。(约定空树不是任意一个树的子结构)
B是 A的子结构, 即 A中有出现和 B相同的结构和节点值。
例如:
给定的树 A:
3
/ \
4 5
/ \
1 2
给定的树 B:
4
/
1
返回 true,因为 B 与 A 的一个子树拥有相同的结构和节点值。
示例 1:
输入:A = [1,2,3], B = [3,1]
1 3
/ \ /
2 3 1
输出:false
示例 2:
输入:A = [3,4,5,1,2], B = [4,1]
3 4
/ \ /
4 5 1
/ \
1 2
输出:true
限制:0 <= 节点个数 <= 10000
date : 12-23-2020
"""
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def isSubStructure(self, A: TreeNode, B: TreeNode) -> bool:
"""
思路:递归 + 回溯
循环匹配 A 树中的节点和 B 树中的节点,当匹配上时,继续判断左子树和右子树是否相等
:param A:
:param B:
:return:
"""
def isEqual(node_A: TreeNode, node_B: TreeNode) -> bool:
# B 树为空说明匹配完成
if not node_B:
return True
# A 为空或当前两个节点的值不相等说明匹配失败
if not node_A or node_A.val != node_B.val:
return False
# 当前节点相同则继续判断两树的左子树和右子树
return isEqual(node_A.left, node_B.left) and isEqual(node_A.right, node_B.right)
if not A or not B:
return False
return isEqual(A, B) or self.isSubStructure(A.left, B) or self.isSubStructure(A.right, B)
if __name__ == '__main__':
"""
输入:A = [3,4,5,1,2], B = [4,1]
3 4
/ \ /
4 5 1
/ \
1 2
输出:true
"""
A = TreeNode(3)
A.left = TreeNode(4)
A.right = TreeNode(5)
A.left.left = TreeNode(1)
A.left.right = TreeNode(2)
B = TreeNode(4)
B.left = TreeNode(1)
print(Solution().isSubStructure(A, B))
|
"""
面试题03. 题目2: 不修改数组找出重复的数字
在一个长度为 n + 1 的数组中所有的数字都在 1 ~ n 的范围内,所以数组中至少存在一个重复数字。
请找出数组中的任意一个重复数字,但不能修改输入的数组。
例如,如果输入长度为 8 的数组 [2, 3, 5, 4, 3, 2, 6, 7], 那么对应的输出是重复的数字 2 或 3
date : 9-17-2020
"""
def findDuplication(nums, length):
box = set()
repeat = None
for i in range(length):
if not box.add(nums[i]):
repeat = nums[i]
break
return repeat
def count(nums, length, start, end):
"""
:param nums:
:param length:
:param start:
:param mid:
:return:
"""
if nums is None:
return 0
count = 0
for i in range(length):
if start <= nums[i] <= end:
count += 1
return count
def getDuplication(nums, length):
"""
:param nums:
:param length:
:return:
"""
if nums is None:
return 0
start = 1
end = length - 1
while start < end:
mid = int((start + end) / 2)
countt = count(nums, length, start, mid)
if end == start:
if countt > 1:
return start
else:
break
if countt > mid - start + 1:
end = mid
else:
start = mid + 1
return -1
nums = [2, 3, 5, 4, 3, 2, 2, 6, 7]
length = 9
print(getDuplication(nums, length))
print(findDuplication(nums, length))
|
"""
51. N 皇后
n 皇后问题研究的是如何将 n 个皇后放置在 n×n 的棋盘上,并且使皇后彼此之间不能相互攻击。
给定一个整数 n,返回所有不同的 n 皇后问题的解决方案。
每一种解法包含一个明确的 n 皇后问题的棋子放置方案,该方案中 'Q' 和 '.' 分别代表了皇后和空位。
提示:
皇后彼此不能相互攻击,也就是说:任何两个皇后都不能处于同一条横行、纵行或斜线上。
示例
输入:4
输出:[
[".Q..", // 解法 1
"...Q",
"Q...",
"..Q."],
["..Q.", // 解法 2
"Q...",
"...Q",
".Q.."]
]
解释: 4 皇后问题存在两个不同的解法。
"""
class Solution:
def solveNQueens(self, n: int):
"""
:param n: int
:return: List[List[str]]
"""
def generateBoard():
board = list()
for i in range(n):
row[queens[i]] = "Q"
board.append("".join(row))
row[queens[i]] = "."
return board
def backtrack(row: int):
if row == n:
board = generateBoard()
solutions.append(board)
else:
for i in range(n):
if i in columns or row - i in diagonal1 or row + i in diagonal2:
continue
queens[row] = i
columns.add(i)
diagonal1.add(row - i)
diagonal2.add(row + i)
backtrack(row + 1) # 为什么会跳到这里来? -> 递归,返回上一层
columns.remove(i)
diagonal1.remove(row - i)
diagonal2.remove(row + i)
solutions = list()
queens = [-1] * n
columns = set()
diagonal1 = set() # 左上角到右下角对角线
diagonal2 = set() # 右上角到左下角对角线
row = ["."] * n
backtrack(0)
return solutions
s = Solution()
print(s.solveNQueens(4))
|
"""
剑指 Offer 55 - I. 二叉树的深度
输入一棵二叉树的根节点,求该树的深度。
从根节点到叶节点依次经过的节点(含根、叶节点)形成树的一条路径,最长路径的长度为树的深度。
例如:
给定二叉树 [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回它的最大深度 3 。
date: 2021年2月26日
"""
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def maxDepth(self, root: TreeNode) -> int:
# if not root:
# return 0
# deep_left = self.maxDepth(root.left)
# deep_right = self.maxDepth(root.right)
# return deep_left+1 if deep_left > deep_right else deep_right+1
if not root:
return 0
return max(self.maxDepth(root.left), self.maxDepth(root.right)) + 1
a,b,c,d,e,f,g = TreeNode(1), TreeNode(2), TreeNode(3), TreeNode(4), TreeNode(5), TreeNode(6), TreeNode(7)
a.left, a.right = b, c
b.left, b.right = d, e
c.right = f
e.left = g
print(Solution().maxDepth(a))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.