Dataset Viewer
Auto-converted to Parquet Duplicate
text
stringlengths
100
3.06M
# -*- coding: utf-8 -*- """ Created on Wed Sep 18 13:13:09 2019 Psudo : 1.Get a Dataset 2.arbitarily choose K centroids in random 3.Assign the closest data points by distance to a centroid/cluster 4.Compute mean of the datapoints in the clusters excluding the centroids 5.The mean would be the new centroid and repeat from step 3 until the centroid doesnt change. @author: Ravi """ from copy import deepcopy import numpy as np import pandas as pd from matplotlib import pyplot as plt plt.rcParams['figure.figsize'] = (16, 9) plt.style.use('ggplot') # Importing the data sets data = pd.read_csv('data.csv') #print(data.shape) data.head() #Plotting the values d1= data['Dset1'].values d2= data['Dset2'].values X=np.array(list(zip(d1,d2))) print('x iss',X) plt.scatter(d1, d2, c='blue', s=7) #Distance def dist(a, b, ax=1): return np.linalg.norm(a-b, axis=ax) #Picking centroids at random k=4 C_x = np.random.randint(0, np.max(X)-20, size=k) C_y = np.random.randint(0, np.max(X)-20, size=k) C= np.array(list(zip(C_x, C_y)), dtype=np.float32) print(C) #plotting with cetroids plt.scatter(d1,d2, c ='#050505', s=7) plt.scatter(C_x, C_y, marker='*', s=200, c='g') #Storing the value of centroids when it updates C_old = np.zeros(C.shape) #print(C_old) clusters = np.zeros(len(X)) #distance between the new centroid and old centroid Cdist = dist(C,C_old, None) while Cdist != 0 : for i in range(len(X)): print( 'x i is',X[i]) distances = dist(X[i], C) print(distances) cluster = np.argmin(distances) clusters[i] = cluster #storing the old centroid C_old = deepcopy(C) #finding the new centroids by taking the average value for i in range(k): points = [X[j] for j in range(len(X)) if clusters[j] == i] #print(points) C[i] = np.mean(points, axis=0) Cdist = dist(C, C_old, None) colors = ['r','g','b','y','c','m'] fig, ax = plt.subplots() for i in range(k): points = np.array([X[j] for j in range(len(X))if clusters[j] == i]) ax.scatter(points[:, 0], points[:,1], s=7, c=colors[i]) ax.scatter(C[:,0], C[:, 1], marker='*', s=200, c='#050505')
n1=int(input('digite seu numero: ')) n2= n1*2 n3= n1*3 n4= n1**(1/2) print(f'o dobro do seu numero e {n2} o triplo e {n3} a raiz quadrada dele e {n4}')
import unittest from problems.FibonacciGenerator import FibonacciGenerator class TestFibonacciGenerator(unittest.TestCase): def test_Fibonacci(self): self.assertEqual(0, fibonacci(1)) self.assertEqual(1, fibonacci(2)) self.assertEqual(1, fibonacci(3)) self.assertEqual(2, fibonacci(4)) self.assertEqual(3, fibonacci(5)) self.assertEqual(5, fibonacci(6)) def test_nextFibonacci(self): fg = FibonacciGenerator() self.assertEqual(fibonacci(1), fg.next()) self.assertEqual(fibonacci(2), fg.next()) self.assertEqual(fibonacci(3), fg.next()) self.assertEqual(fibonacci(4), fg.next()) self.assertEqual(fibonacci(5), fg.next()) self.assertEqual(fibonacci(6), fg.next()) def test_fibonacciOverflow(self): with self.assertRaises(OverflowError): list(FibonacciGenerator()) def fibonacci(n): if n <= 0: print("Incorrect input") # First Fibonacci number is 0 elif n == 1: return 0 # Second Fibonacci number is 1 elif n == 2: return 1 else: return fibonacci(n - 1) + fibonacci(n - 2) if __name__ == '__main__': unittest.main()
import find_min def secondsmallestNumber(array): v = find_min.findMin(array) for i in array: if v == i: array.remove(i) maxi = find_min.findMin(array) return maxi array = [3,1,6,9,3] print(secondsmallestNumber(array))
# Python Unittest # unittest.mock � mock object library # unittest.mock is a library for testing in Python. # It allows you to replace parts of your system under test with mock objects and make assertions about how they have been used. # unittest.mock provides a core Mock class removing the need to create a host of stubs throughout your test suite. # After performing an action, you can make assertions about which methods / attributes were used and arguments they were called with. # You can also specify return values and set needed attributes in the normal way. # # Additionally, mock provides a patch() decorator that handles patching module and class level attributes within the scope of a test, along with sentinel # for creating unique objects. # # Mock is very easy to use and is designed for use with unittest. Mock is based on the �action -> assertion� pattern instead of �record -> replay� used by # many mocking frameworks. # # # patch methods: start and stop. # All the patchers have start() and stop() methods. # These make it simpler to do patching in setUp methods or where you want to do multiple patches without nesting decorators or with statements. # To use them call patch(), patch.object() or patch.dict() as normal and keep a reference to the returned patcher object. # You can then call start() to put the patch in place and stop() to undo it. # If you are using patch() to create a mock for you then it will be returned by the call to patcher.start. # patcher _ patch('package.module.ClassName') ____ package ______ module original _ module.ClassName new_mock _ patcher.start() a.. module.ClassName __ no. original a.. module.ClassName __ new_mock patcher.stop() a.. module.ClassName __ original a.. module.ClassName __ no. new_mock # # A typical use case for this might be for doing multiple patches in the setUp method of a TestCase: # c_ MyTest(T.. ___ setUp patcher1 _ patch('package.module.Class1') patcher2 _ patch('package.module.Class2') MockClass1 _ patcher1.start() MockClass2 _ patcher2.start() ___ tearDown patcher1.stop() patcher2.stop() ___ test_something a.. package.module.Class1 __ MockClass1 a.. package.module.Class2 __ MockClass2 MyTest('test_something').run() # # Caution: # If you use this technique you must ensure that the patching is �undone� by calling stop. # This can be fiddlier than you might think, because if an exception is raised in the setUp then tearDown is not called. # unittest.TestCase.addCleanup() makes this easier: # c_ MyTest(T.. ___ setUp patcher _ patch('package.module.Class') MockClass _ patcher.start() addCleanup(patcher.stop) ___ test_something a.. package.module.Class __ MockClass
# coding:utf-8 # python3 # original: u"杨仕航" # modified: @kevinqqnj import logging import numpy as np from queue import Queue, LifoQueue import time import copy # DEBUG INFO WARNING ERROR CRITICAL logging.basicConfig(level=logging.WARN, format='%(asctime)s %(levelname)s %(message)s') # format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)-7s %(message)s') logger = logging.getLogger(__name__) class Record: point = None # 进行猜测的点 point_index = 0 # 猜测候选列表使用的值的索引 value = None # 回溯记录的值 class Sudo: def __init__(self, _data): # 数据初始化(二维的object数组) self.value = np.array([[0] * 9] * 9, dtype=object) # 数独的值,包括未解决和已解决的 self.new_points = Queue() # 先进先出,新解(已解决值)的坐标 self.record_queue = LifoQueue() # 先进后出,回溯器 self.guess_times = 0 # 猜测次数 self.time_cost = '0' # 猜测time self.time_start = time.time() self.guess_record = [] # 记录猜测,用于回放 # 九宫格的基准列表 self.base_points = [[0, 0], [0, 3], [0, 6], [3, 0], [3, 3], [3, 6], [6, 0], [6, 3], [6, 6]] # 整理数据 self.puzzle = np.array(_data).reshape(9, -1) for r in range(0, 9): for c in range(0, 9): if self.puzzle[r, c]: # if not Zero # numpy default is int32, convert to int self.value[r, c] = int(self.puzzle[r, c]) # 新的确认的值添加到列表中,以便遍历 self.new_points.put((r, c)) # logger.debug(f'init: answer={self.value[r, c]} at {(r, c)}') else: # if Zero, guess no. is 1-9 self.value[r, c] = [1, 2, 3, 4, 5, 6, 7, 8, 9] # self.guess_record.append({'value':eval(f'{self.value.tolist()}'),'desc':f'载入数据'}) # 剔除数字 def _cut_num(self, point): r, c = point val = self.value[r, c] remove_r = remove_c = remove_b = False value_snap = eval(f'{self.value.tolist()}') point_snap = value_snap[r][c] # 行 for i, item in enumerate(self.value[r]): if isinstance(item, list): if item.count(val): item.remove(val) remove_r = True # 判断移除后,是否剩下一个元素 if len(item) == 1: self.new_points.put((r, i)) # 添加坐标到“已解决”列表 logger.debug(f'only one in row: answer={self.value[r, i]} at {(r, i)}') self.value[r, i] = item[0] # if remove_r: self.guess_record.append({'value':self.value.tolist(),'desc':'排除同一行已有的数字'}) # 列 for i, item in enumerate(self.value[:, c]): if isinstance(item, list): if item.count(val): item.remove(val) remove_c = True # 判断移除后,是否剩下一个元素 if len(item) == 1: self.new_points.put((i, c)) logger.debug(f'only one in col: answer={self.value[i, c]} at {(i, c)}') self.value[i, c] = item[0] # if remove_c: self.guess_record.append({'value':self.value.tolist(),'desc':'排除同一列已有的数字'}) # 所在九宫格(3x3的数组) b_r, b_c = map(lambda x: x // 3 * 3, point) # 九宫格基准点 for m_r, row in enumerate(self.value[b_r:b_r + 3, b_c:b_c + 3]): for m_c, item in enumerate(row): if isinstance(item, list): if item.count(val): item.remove(val) remove_b = True # 判断移除后,是否剩下一个元素 if len(item) == 1: r = b_r + m_r c = b_c + m_c self.new_points.put((r, c)) logger.debug(f'only one in block: answer={self.value[r, c]} at {(r, c)}') self.value[r, c] = item[0] if remove_b or remove_c or remove_r: self.guess_record.append({ 'value': value_snap, 'desc':f'排除同一行、列、九宫格: {point_snap}', 'highlight': point}) # 同一行、列或九宫格中, List里,可能性只有一个的情况 def _check_one_possbile(self): # 同一行只有一个数字的情况 for r in range(0, 9): # 只取出是这一行是List的格子 values = list(filter(lambda x: isinstance(x, list), self.value[r])) for c, item in enumerate(self.value[r]): if isinstance(item, list): for value in item: if sum(map(lambda x: x.count(value), values)) == 1: self.value[r, c] = value self.new_points.put((r, c)) logger.debug(f'list val is only one in row: answer={self.value[r, c]} at {(r, c)}') return True # 同一列只有一个数字的情况 for c in range(0, 9): values = list(filter(lambda x: isinstance(x, list), self.value[:, c])) for r, item in enumerate(self.value[:, c]): if isinstance(item, list): for value in item: if sum(map(lambda x: x.count(value), values)) == 1: self.value[r, c] = value self.new_points.put((r, c)) logger.debug(f'list val is only one in col: answer={self.value[r, c]} at {(r, c)}') return True # 九宫格内的单元格只有一个数字的情况 for r, c in self.base_points: # reshape: 3x3 改为1维数组 values = list(filter(lambda x: isinstance(x, list), self.value[r:r + 3, c:c + 3].reshape(1, -1)[0])) for m_r, row in enumerate(self.value[r:r + 3, c:c + 3]): for m_c, item in enumerate(row): if isinstance(item, list): for value in item: if sum(map(lambda x: x.count(value), values)) == 1: self.value[r + m_r, c + m_c] = value self.new_points.put((r + m_r, c + m_c)) logger.debug(f'list val is only one in block: answer={self.value[r + m_r, c +m_c]} at ' f'{(r + m_r, c +m_c)}') return True # 同一个九宫格内数字在同一行或同一列处理(同行列隐性排除) def _check_implicit(self): for b_r, b_c in self.base_points: block = self.value[b_r:b_r + 3, b_c:b_c + 3] # 判断数字1~9在该九宫格的分布情况 _data = block.reshape(1, -1)[0] for i in range(1, 10): result = map(lambda x: 0 if not isinstance(x[1], list) else x[0] + 1 if x[1].count(i) else 0, enumerate(_data)) result = list(filter(lambda x: x > 0, result)) r_count = len(result) if r_count in [2, 3]: # 2或3个元素才有可能同一行或同一列 rows = list(map(lambda x: (x - 1) // 3, result)) cols = list(map(lambda x: (x - 1) % 3, result)) if len(set(rows)) == 1: # 同一行,去掉其他行的数字 result = list(map(lambda x: b_c + (x - 1) % 3, result)) row = b_r + rows[0] for col in range(0, 9): if col not in result: item = self.value[row, col] if isinstance(item, list): if item.count(i): item.remove(i) # 判断移除后,是否剩下一个元素 if len(item) == 1: self.new_points.put((row, col)) logger.debug( f'block compare row: answer={self.value[row, col]} at {(row, col)}') self.guess_record.append({ 'value':eval(f'{self.value.tolist()}'), 'desc':f'九宫格隐性排除row: {i}', 'highlight': (row, col)}) self.value[row, col] = item[0] return True elif len(set(cols)) == 1: # 同一列 result = list(map(lambda x: b_r + (x - 1) // 3, result)) col = b_c + cols[0] for row in range(0, 9): if row not in result: item = self.value[row, col] if isinstance(item, list): if item.count(i): item.remove(i) # 判断移除后,是否剩下一个元素 if len(item) == 1: self.new_points.put((row, col)) logger.debug( f'block compare col: answer={self.value[row, col]} at {(row, col)}') self.guess_record.append({ 'value':eval(f'{self.value.tolist()}'), 'desc':f'九宫格隐性排除col: {i}', 'highlight': (row, col)}) self.value[row, col] = item[0] return True # 排除法解题 def sudo_exclude(self): implicit_exist = True new_point_exist = True while implicit_exist: while new_point_exist: # 剔除数字 while not self.new_points.empty(): point = self.new_points.get() # 先进先出 self._cut_num(point) # 检查List里值为单个数字的情况,如有新answer则加入new_points Queue,立即_cut_num new_point_exist = self._check_one_possbile() # 检查同行或列的情况 implicit_exist = self._check_implicit() new_point_exist = True # 得到有多少个确定的数字 def get_num_count(self): return sum(map(lambda x: 1 if isinstance(x, int) else 0, self.value.reshape(1, -1)[0])) # 评分,找到最佳的猜测坐标 def get_best_point(self): best_score = 0 best_point = (0, 0) for r, row in enumerate(self.value): for c, item in enumerate(row): point_score = self._get_point_score((r, c)) if best_score < point_score: best_score = point_score best_point = (r, c) return best_point # 计算某坐标的评分 def _get_point_score(self, point): # 评分标准 (10-候选个数) + 同行确定数字个数 + 同列确定数字个数 r, c = point item = self.value[r, c] if isinstance(item, list): score = 10 - len(item) score += sum(map(lambda x: 1 if isinstance(x, int) else 0, self.value[r])) score += sum(map(lambda x: 1 if isinstance(x, int) else 0, self.value[:, c])) return score else: return 0 # 验证有没错误 def verify_value(self): # 行 r = 0 for row in self.value: nums = [] lists = [] for item in row: (lists if isinstance(item, list) else nums).append(item) if len(set(nums)) != len(nums): # logger.error(f'verify failed. dup in row {r}') logger.debug(f'verify failed. dup in row {r}') self.guess_record.append({ 'value':eval(f'{self.value.tolist()}'), 'desc':f'验证错误 in row: {r+1}' }) return False # 数字要不重复 if len(list(filter(lambda x: len(x) == 0, lists))): return False # 候选列表不能为空集 r += 1 # 列 for c in range(0, 9): nums = [] lists = [] col = self.value[:, c] for item in col: (lists if isinstance(item, list) else nums).append(item) if len(set(nums)) != len(nums): logger.debug(f'verify failed. dup in col {c}') self.guess_record.append({ 'value':eval(f'{self.value.tolist()}'), 'desc':f'验证错误 in col: {c+1}' }) return False # 数字要不重复 if len(list(filter(lambda x: len(x) == 0, lists))): return False # 候选列表不能为空集 # 九宫格 for b_r, b_c in self.base_points: nums = [] lists = [] block = self.value[b_r:b_r + 3, b_c:b_c + 3].reshape(1, -1)[0] for item in block: (lists if isinstance(item, list) else nums).append(item) if len(set(nums)) != len(nums): logger.debug(f'verify failed. dup in block {b_r, b_c}') self.guess_record.append({ 'value':eval(f'{self.value.tolist()}'), 'desc':f'验证错误 in block: {b_r+1, b_c+1}' }) return False # 数字要不重复 if len(list(filter(lambda x: len(x) == 0, lists))): return False # 候选列表不能为空集 return True def add_to_queue(self, point, index): record = Record() record.point = point record.point_index = index # recorder.value = self.value.copy() #numpy的copy不行 record.value = copy.deepcopy(self.value) self.record_queue.put(record) items = self.value[point] self.value[point] = items[index] self.new_points.put(point) return items def sudo_solve_iter(self): # 排除法解题 self.sudo_exclude() # logger.debug(f'excluded, current result:\n{self.value}') if self.verify_value(): if self.get_num_count() == 81: # solve success self.time_cost = f'{time.time() - self.time_start:.3f}' self.guess_record.append({ 'value':self.value.tolist(), 'desc':f'恭喜你,solved!' }) return else: logger.info(f'current no. of fixed answers: {self.get_num_count()}') point = self.get_best_point() index = 0 items = self.add_to_queue(point, index) logger.info(f'add to LIFO queue and guessing {items[index]}/{items}: ' f'{[x.point for x in self.record_queue.queue]}') self.guess_times += 1 self.guess_record.append({ 'value':self.value.tolist(), 'desc':f'第{self.guess_times}次猜测, 从{items}里选 {items[index]}', 'highlight': point, 'highlight_type': 'assume', 'type': 'assume', }) return self.sudo_solve_iter() while True: if self.record_queue.empty(): # raise Exception('Sudo is wrong, no answer!') self.time_cost = f'{time.time() - self.time_start:.3f}' logger.error(f'Guessed {self.guess_times} times. Sudo is wrong, no answer!') exit() # check value ERROR, need to try next index or rollback record = self.record_queue.get() point = record.point index = record.point_index + 1 items = record.value[point] self.value = record.value logger.info(f'Recall! Pop previous point, {items} @{point}') # 判断索引是否超出范围 # if not exceed,则再回溯一次 if index < len(items): items = self.add_to_queue(point, index) logger.info(f'guessing next index: answer={items[index]}/{items} @{point}') self.guess_times += 1 self.guess_record.append({ 'value':self.value.tolist(), 'desc':f'回溯, 第{self.guess_times}次猜测, 从{items}里选 {items[index]}', 'highlight': point, 'highlight_type': 'assume', 'type': 'assume', }) return self.sudo_solve_iter() if __name__ == '__main__': # 数独题目 http://cn.sudokupuzzle.org/ # data[0]: 号称最难的数独 data = [[8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 6, 0, 0, 0, 0, 0, 0, 7, 0, 0, 9, 0, 2, 0, 0, 0, 5, 0, 0, 0, 7, 0, 0, 0, 0, 0, 0, 0, 4, 5, 7, 0, 0, 0, 0, 0, 1, 0, 0, 0, 3, 0, 0, 0, 1, 0, 0, 0, 0, 6, 8, 0, 0, 8, 5, 0, 0, 0, 1, 0, 0, 9, 0, 0, 0, 0, 4, 0, 0], [0, 0, 0, 0, 5, 0, 2, 0, 0, 0, 9, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 4, 0, 6, 0, 8, 0, 0, 0, 7, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 0, 9, 4, 2, 0, 1, 0, 7, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 0, 0, 0]] # try: t1 = time.time() puzzle = data[0] sudo = Sudo(puzzle) sudo.sudo_solve_iter() logger.warning(f'Done! guessed {sudo.guess_times} times, in {sudo.time_cost}sec') logger.warning(f'Puzzle:\n{sudo.puzzle}\nAnswer:\n{sudo.value}') # except: # logger.error(f'ERROR: {sudo.value}', exc_info=True)
class Track(): """creates the tracks for all of the cars""" # makes sure pixel resolution is high def __init__(self, rows, cols, width, height, timeStep): self.rows = rows # number of horizontal lanes self.cols = cols # number of vertical lanes self.width = width # pixels wides self.height = height # pixels high ####################################################### # returns the number of horizontal lanes on the track def getRows(self): return self.rows # returns the number of vertical lanes on the track def getCols(self): return self.cols # returns the width of the track in pixels def getWidth(self): return self.width # returns the height of the track in pixels def getHeight(self): return self.height # returns the number of pixels between each row def getRowSpacing(self): rowSpacing = (self.height-self.rows)/(self.rows+1) return rowSpacing # returns the number of pixels between each column def getColSpacing(self): colSpacing = (self.width-self.cols)/(self.cols+1) return colSpacing # returns a list of tuples, with the x and y coordinate of each intersection contained in the tuple def getIntersections(self): intersections = [] for i in range(self.rows): for j in range(self.cols): # account fot the width of each lane # determine the coordinate of each intersection x_intersect = (j+1)*self.getColSpacing() + i y_intersect = (i+1)*self.getRowSpacing() + j intersection = [(x_intersect, y_intersect)] intersections += intersection return intersections
# Tuples are immutable print("============ tuples ============") print() tuples = (12345, 54321, 'hello!') print(tuples) u = tuples, (1, 2, 3, 4, 5) print(u) # The statement t = 12345, 54321, 'hello!' is an example of tuple packing: # the values 12345, 54321 and 'hello!' # are packed together in a tuple. The reverse operation is also possible x, y, z = tuples print(x, y, z)
class Solution(object): def intersectionSizeTwo(self, intervals): """ :type intervals: List[List[int]] :rtype: int """ intervals.sort() filtered_intervals=[] #print intervals for interval in intervals: while filtered_intervals and filtered_intervals[-1][1]>=interval[1]: filtered_intervals.pop() filtered_intervals.append(interval) result=0 p1,p2=float('-inf'),float('-inf') #print filtered_intervals for interval in filtered_intervals: condition1=interval[0]<=p1<=interval[1] condition2=interval[0]<=p2<=interval[1] if condition1 and condition2: continue elif condition1: p2=interval[1] result+=1 elif condition2: p1=interval[1] result+=1 else: p2=interval[1] p1=p2-1 result+=2 return result s=Solution() print s.intersectionSizeTwo([[1, 3], [1, 4], [2, 5], [3, 5]]) print s.intersectionSizeTwo([[1, 2], [2, 3], [2, 4], [4, 5]]) print s.intersectionSizeTwo([[1,24],[10,16],[14,25],[0,18],[16,17]])
""" Ejercicio 4.1: Debugger Ingresá y corré el siguiente código en tu IDE: def invertir_lista(lista): '''Recibe una lista L y la develve invertida.''' invertida = [] i=len(lista) while i > 0: # tomo el último elemento i=i-1 invertida.append (lista.pop(i)) # return invertida l = [1, 2, 3, 4, 5] m = invertir_lista(l) print(f'Entrada {l}, Salida: {m}') Deberías observar que la función modifica el valor de la lista de entrada. Eso no debería ocurrir: una función nunca debería modificar los parámetros salvo que sea lo esperado. Usá el debugger y el explorador de variables para determinar cuál es el primer paso clave en el que se modifica el valor de esta variable. """ def invertir_lista(lista): '''Recibe una lista L y la develve invertida.''' invertida = [] i=len(lista) while i > 0: # tomo el último elemento i=i-1 invertida.append(lista[i]) # la función pop quita return invertida l = [1, 2, 3, 4, 5] m = invertir_lista(l) print(f'Entrada {l}, Salida: {m}')
import game, population import random # config parameters # Population n_cars = 10 start = (50,50) # Brain layers = 10 neurons = 20 # evolution mutation_rate = 0.10 parents_to_keep = 0.33 # generate the brains # brains = [] # for i in range(0, n_cars): # seed = random.random() # brains += [population.NeuronBrain(1,1,layers,neurons, seed)] # print seed brains = [population.NeuronBrain(5,2,layers,neurons, random.random()) for i in range(0,n_cars)] cars = [population.CarSpecimen(start[0],start[1], brain=brains[i], name="Car {0}".format(i)) for i in range(0,n_cars)] # # # nparents to keep # for b in brains: # print b.dimension() # parents = cars[1:int(n_cars * parents_to_keep)] # parent_brains = [x.brain for x in parents] # mutation_func = lambda l: population.mutate(l, mutation_rate, 0.5) # nbrains = population.breed(parent_brains, n_cars, mutation_func, True) # print nbrains # print [x in nbrains for x in parent_brains] # create the application # print cars app = game.App(players=cars) app.on_execute()
sq1 = raw_input("inserer une sequence ADN :") i=0 n=len(sq1)-1 x=0 while i<n : if sq1[i]==sq1[n] : x=x+1 i=i+1 if x == (len(sq1)-1)/2 : print "cette sequence est un palindrome" else : print"cette sequence n'est pas un palindrome"
import gensim import numpy as np import copy from tqdm.auto import tqdm from utils import log, intersection_align_gensim from gensim.matutils import unitvec class GlobalAnchors(object): def __init__(self, w2v1, w2v2, assume_vocabs_are_identical=False): if not assume_vocabs_are_identical: w2v1, w2v2 = intersection_align_gensim(copy.copy(w2v1), copy.copy(w2v2)) self.w2v1 = w2v1 self.w2v2 = w2v2 def __repr__(self): return "GlobalAnchors" def get_global_anchors(self, word: str, w2v: gensim.models.KeyedVectors): """ This takes in a word and a KeyedVectors model and returns a vector of cosine distances between this word and each word in the vocab. :param word: :param w2v: :return: np.array of distances shaped (len(w2v.vocab),) """ word_vector = w2v.get_vector(word) similarities = gensim.models.KeyedVectors.cosine_similarities(word_vector, w2v.vectors) return unitvec(similarities) def get_score(self, word: str): w2v1_anchors = self.get_global_anchors(word, self.w2v1) w2v2_anchors = self.get_global_anchors(word, self.w2v2) score = np.dot(w2v1_anchors, w2v2_anchors) return score def get_changes(self, top_n_changed_words: int): """ This method uses approach described in Yin, Zi, Vin Sachidananda, and Balaji Prabhakar. "The global anchor method for quantifying linguistic shifts and domain adaptation." Advances in Neural Information Processing Systems. 2018. It can be described as follows. To evaluate how much the meaning of a given word differs in two given corpora, we take cosine distance from the given word to all words in the vocabulary; those values make up a vector with as many components as there are words in the vocab. We do it for both corpora and then compute the cosine distance between those two vectors :param top_n_changed_words: we will output n words that differ the most in the given corpora :return: list of pairs (word, score), where score indicates how much a word has changed """ log('Doing global anchors') result = list() for word in tqdm(self.w2v1.wv.vocab.keys()): score = self.get_score(word) result.append((word, score)) result = sorted(result, key=lambda x: x[1]) result = result[:top_n_changed_words] log('\nDone') return result
#!/usr/bin/env python # coding: utf-8 # # IBM HR Employee Attrition & Performance. # ## [Please star/upvote in case you find it helpful.] # In[ ]: from IPython.display import Image Image("../../../input/pavansubhasht_ibm-hr-analytics-attrition-dataset/imagesibm/image-logo.png") # ## CONTENTS ::-> # [ **1 ) Exploratory Data Analysis**](#content1) # [ **2) Corelation b/w Features**](#content2) # [** 3) Feature Selection**](#content3) # [** 4) Preparing Dataset**](#content4) # [ **5) Modelling**](#content5) # # Note that this notebook uses traditional ML algorithms. I have another notebook in which I have used an ANN on the same dataset. To check it out please follow the below link--> # # https://www.kaggle.com/rajmehra03/an-introduction-to-ann-keras-with-ibm-hr-dataset/ # [ **6) Conclusions**](#content6) # <a id="content1"></a> # ## 1 ) Exploratory Data Analysis # ## 1.1 ) Importing Various Modules # In[ ]: # Ignore the warnings import warnings warnings.filterwarnings('always') warnings.filterwarnings('ignore') # data visualisation and manipulation import numpy as np import pandas as pd import matplotlib.pyplot as plt from matplotlib import style import seaborn as sns import missingno as msno #configure # sets matplotlib to inline and displays graphs below the corressponding cell. style.use('fivethirtyeight') sns.set(style='whitegrid',color_codes=True) #import the necessary modelling algos. from sklearn.linear_model import LogisticRegression from sklearn.svm import LinearSVC from sklearn.svm import SVC from sklearn.neighbors import KNeighborsClassifier from sklearn.ensemble import RandomForestClassifier from sklearn.tree import DecisionTreeClassifier from sklearn.ensemble import GradientBoostingClassifier from sklearn.naive_bayes import GaussianNB #model selection from sklearn.model_selection import train_test_split from sklearn.model_selection import KFold from sklearn.metrics import accuracy_score,precision_score,recall_score,confusion_matrix,roc_curve,roc_auc_score from sklearn.model_selection import GridSearchCV from imblearn.over_sampling import SMOTE #preprocess. from sklearn.preprocessing import MinMaxScaler,StandardScaler,Imputer,LabelEncoder,OneHotEncoder # ## 1.2 ) Reading the data from a CSV file # In[ ]: df=pd.read_csv(r"../../../input/pavansubhasht_ibm-hr-analytics-attrition-dataset/WA_Fn-UseC_-HR-Employee-Attrition.csv") # In[ ]: df.head() # In[ ]: df.shape # In[ ]: df.columns # ## 1.3 ) Missing Values Treatment # In[ ]: df.info() # no null or 'Nan' values. # In[ ]: df.isnull().sum() # In[ ]: msno.matrix(df) # just to visualize. one final time. # ## 1.4 ) The Features and the 'Target' # In[ ]: df.columns # In[ ]: df.head() # In all we have 34 features consisting of both the categorical as well as the numerical features. The target variable is the # 'Attrition' of the employee which can be either a Yes or a No. This is what we have to predict. # **Hence this is a Binary Classification problem. ** # ## 1.5 ) Univariate Analysis # In this section I have done the univariate analysis i.e. I have analysed the range or distribution of the values that various features take. To better analyze the results I have plotted various graphs and visualizations wherever necessary. Univariate analysis helps us identify the outliers in the data. # In[ ]: df.describe() # Let us first analyze the various numeric features. To do this we can actually plot a boxplot showing all the numeric features. Also the distplot or a histogram is a reasonable choice in such cases. # In[ ]: sns.factorplot(data=df,kind='box',size=10,aspect=3) # Note that all the features have pretty different scales and so plotting a boxplot is not a good idea. Instead what we can do is plot histograms of various continuously distributed features. # # We can also plot a kdeplot showing the distribution of the feature. Below I have plotted a kdeplot for the 'Age' feature. # Similarly we plot for other numeric features also. Similarly we can also use a distplot from seaborn library which combines most.. # In[ ]: sns.kdeplot(df['Age'],shade=True,color='#ff4125') # In[ ]: sns.distplot(df['Age']) # Similarly we can do this for all the numerical features. Below I have plotted the subplots for the other features. # In[ ]: warnings.filterwarnings('always') warnings.filterwarnings('ignore') fig,ax = plt.subplots(5,2, figsize=(9,9)) sns.distplot(df['TotalWorkingYears'], ax = ax[0,0]) sns.distplot(df['MonthlyIncome'], ax = ax[0,1]) sns.distplot(df['YearsAtCompany'], ax = ax[1,0]) sns.distplot(df['DistanceFromHome'], ax = ax[1,1]) sns.distplot(df['YearsInCurrentRole'], ax = ax[2,0]) sns.distplot(df['YearsWithCurrManager'], ax = ax[2,1]) sns.distplot(df['YearsSinceLastPromotion'], ax = ax[3,0]) sns.distplot(df['PercentSalaryHike'], ax = ax[3,1]) sns.distplot(df['YearsSinceLastPromotion'], ax = ax[4,0]) sns.distplot(df['TrainingTimesLastYear'], ax = ax[4,1]) plt.tight_layout() print() # Let us now analyze the various categorical features. Note that in these cases the best way is to use a count plot to show the relative count of observations of different categories. # In[ ]: cat_df=df.select_dtypes(include='object') # In[ ]: cat_df.columns # In[ ]: def plot_cat(attr,labels=None): if(attr=='JobRole'): sns.factorplot(data=df,kind='count',size=5,aspect=3,x=attr) return sns.factorplot(data=df,kind='count',size=5,aspect=1.5,x=attr) # I have made a function that accepts the name of a string. In our case this string will be the name of the column or attribute which we want to analyze. The function then plots the countplot for that feature which makes it easier to visualize. # In[ ]: plot_cat('Attrition') # **Note that the number of observations belonging to the 'No' category is way greater than that belonging to 'Yes' category. Hence we have skewed classes and this is a typical example of the 'Imbalanced Classification Problem'. To handle such types of problems we need to use the over-sampling or under-sampling techniques. I shall come back to this point later.** # **Let us now similalry analyze other categorical features.** # In[ ]: plot_cat('BusinessTravel') # The above plot clearly shows that most of the people belong to the 'Travel_Rarely' class. This indicates that most of the people did not have a job which asked them for frequent travelling. # In[ ]: plot_cat('OverTime') # In[ ]: plot_cat('Department') # In[ ]: plot_cat('EducationField') # In[ ]: plot_cat('Gender') # Note that males are present in higher number. # In[ ]: plot_cat('JobRole') # ** Similarly we can continue for other categorical features. ** # **Note that the same function can also be used to better analyze the numeric discrete features like 'Education','JobSatisfaction' etc... # In[ ]: # just uncomment the following cell. # In[ ]: # num_disc=['Education','EnvironmentSatisfaction','JobInvolvement','JobSatisfaction','WorkLifeBalance','RelationshipSatisfaction','PerformanceRating'] # for i in num_disc: # plot_cat(i) # similarly we can intrepret these graphs. # <a id="content2"></a> # ## 2 ) Corelation b/w Features # # In[ ]: #corelation matrix. cor_mat= df.corr() mask = np.array(cor_mat) mask[np.tril_indices_from(mask)] = False fig=plt.gcf() fig.set_size_inches(30,12) # ###### SOME INFERENCES FROM THE ABOVE HEATMAP # # 1. Self relation ie of a feature to itself is equal to 1 as expected. # # 2. JobLevel is highly related to Age as expected as aged employees will generally tend to occupy higher positions in the company. # # 3. MonthlyIncome is very strongly related to joblevel as expected as senior employees will definately earn more. # # 4. PerformanceRating is highly related to PercentSalaryHike which is quite obvious. # # 5. Also note that TotalWorkingYears is highly related to JobLevel which is expected as senior employees must have worked for a larger span of time. # # 6. YearsWithCurrManager is highly related to YearsAtCompany. # # 7. YearsAtCompany is related to YearsInCurrentRole. # # # **Note that we can drop some highly corelated features as they add redundancy to the model but since the corelation is very less in genral let us keep all the features for now. In case of highly corelated features we can use something like Principal Component Analysis(PCA) to reduce our feature space.** # In[ ]: df.columns # <a id="content3"></a> # ## 3 ) Feature Selection # # ## 3.1 ) Plotting the Features against the 'Target' variable. # #### 3.1.1 ) Age # Note that Age is a continuous quantity and therefore we can plot it against the Attrition using a boxplot. # In[ ]: sns.factorplot(data=df,y='Age',x='Attrition',size=5,aspect=1,kind='box') # Note that the median as well the maximum age of the peole with 'No' attrition is higher than that of the 'Yes' category. This shows that people with higher age have lesser tendency to leave the organisation which makes sense as they may have settled in the organisation. # #### 3.1.2 ) Department # Note that both Attrition(Target) as well as the Deaprtment are categorical. In such cases a cross-tabulation is the most reasonable way to analyze the trends; which shows clearly the number of observaftions for each class which makes it easier to analyze the results. # In[ ]: df.Department.value_counts() # In[ ]: sns.factorplot(data=df,kind='count',x='Attrition',col='Department') # In[ ]: pd.crosstab(columns=[df.Attrition],index=[df.Department],margins=True,normalize='index') # set normalize=index to view rowwise %. # Note that most of the observations corresspond to 'No' as we saw previously also. About 81 % of the people in HR dont want to leave the organisation and only 19 % want to leave. Similar conclusions can be drawn for other departments too from the above cross-tabulation. # #### 3.1.3 ) Gender # In[ ]: pd.crosstab(columns=[df.Attrition],index=[df.Gender],margins=True,normalize='index') # set normalize=index to view rowwise %. # About 85 % of females want to stay in the organisation while only 15 % want to leave the organisation. All in all 83 % of employees want to be in the organisation with only being 16% wanting to leave the organisation or the company. # #### 3.1.4 ) Job Level # In[ ]: pd.crosstab(columns=[df.Attrition],index=[df.JobLevel],margins=True,normalize='index') # set normalize=index to view rowwise %. # People in Joblevel 4 have a very high percent for a 'No' and a low percent for a 'Yes'. Similar inferences can be made for other job levels. # #### 3.1.5 ) Monthly Income # In[ ]: sns.factorplot(data=df,kind='bar',x='Attrition',y='MonthlyIncome') # Note that the average income for 'No' class is quite higher and it is obvious as those earning well will certainly not be willing to exit the organisation. Similarly those employees who are probably not earning well will certainly want to change the company. # #### 3.1.6 ) Job Satisfaction # In[ ]: sns.factorplot(data=df,kind='count',x='Attrition',col='JobSatisfaction') # In[ ]: pd.crosstab(columns=[df.Attrition],index=[df.JobSatisfaction],margins=True,normalize='index') # set normalize=index to view rowwise %. # Note this shows an interesting trend. Note that for higher values of job satisfaction( ie more a person is satisfied with his job) lesser percent of them say a 'Yes' which is quite obvious as highly contented workers will obvioulsy not like to leave the organisation. # #### 3.1.7 ) Environment Satisfaction # In[ ]: pd.crosstab(columns=[df.Attrition],index=[df.EnvironmentSatisfaction],margins=True,normalize='index') # set normalize=index to view rowwise %. # Again we can notice that the relative percent of 'No' in people with higher grade of environment satisfacftion which is expected. # #### 3.1.8 ) Job Involvement # In[ ]: pd.crosstab(columns=[df.Attrition],index=[df.JobInvolvement],margins=True,normalize='index') # set normalize=index to view rowwise %. # #### 3.1.9 ) Work Life Balance # In[ ]: pd.crosstab(columns=[df.Attrition],index=[df.WorkLifeBalance],margins=True,normalize='index') # set normalize=index to view rowwise %. # Again we notice a similar trend as people with better work life balance dont want to leave the organisation. # #### 3.1.10 ) RelationshipSatisfaction # In[ ]: pd.crosstab(columns=[df.Attrition],index=[df.RelationshipSatisfaction],margins=True,normalize='index') # set normalize=index to view rowwise %. # ###### Notice that I have plotted just some of the important features against out 'Target' variable i.e. Attrition in our case. Similarly we can plot other features against the 'Target' variable and analye the trends i.e. how the feature effects the 'Target' variable. # ## 3.2 ) Feature Selection # The feature Selection is one of the main steps of the preprocessing phase as the features which we choose directly effects the model performance. While some of the features seem to be less useful in terms of the context; others seem to equally useful. The better features we use the better our model will perform. **After all Garbage in Garbage out;)**. # # We can also use the Recusrive Feature Elimination technique (a wrapper method) to choose the desired number of most important features. # The Recursive Feature Elimination (or RFE) works by recursively removing attributes and building a model on those attributes that remain. # # It uses the model accuracy to identify which attributes (and/or combination of attributes) contribute the most to predicting the target attribute. # # We can use it directly from the scikit library by importing the RFE module or function provided by the scikit. But note that since it tries different combinations or the subset of features;it is quite computationally expensive and I shall ignore it here. # In[ ]: df.drop(['BusinessTravel','DailyRate','EmployeeCount','EmployeeNumber','HourlyRate','MonthlyRate','NumCompaniesWorked','Over18','StandardHours', 'StockOptionLevel','TrainingTimesLastYear'],axis=1,inplace=True) # # <a id="content4"></a> # ## 4 ) Preparing Dataset # # ## 4.1 ) Feature Encoding # I have used the Label Encoder from the scikit library to encode all the categorical features. # In[ ]: def transform(feature): le=LabelEncoder() df[feature]=le.fit_transform(df[feature]) print(le.classes_) # In[ ]: cat_df=df.select_dtypes(include='object') cat_df.columns # In[ ]: for col in cat_df.columns: transform(col) # In[ ]: df.head() # just to verify. # ## 4.2 ) Feature Scaling. # The scikit library provides various types of scalers including MinMax Scaler and the StandardScaler. Below I have used the StandardScaler to scale the data. # In[ ]: scaler=StandardScaler() scaled_df=scaler.fit_transform(df.drop('Attrition',axis=1)) X=scaled_df Y=df['Attrition'].as_matrix() # ## 4.3 ) Splitting the data into training and validation sets # In[ ]: x_train,x_test,y_train,y_test=train_test_split(X,Y,test_size=0.25,random_state=42) # <a id="content5"></a> # ## 5 ) Modelling # # ## 5.1 ) Handling the Imbalanced dataset # Note that we have a imbalanced dataset with majority of observations being of one type ('NO') in our case. In this dataset for example we have about 84 % of observations having 'No' and only 16 % of 'Yes' and hence this is an imbalanced dataset. # # To deal with such a imbalanced dataset we have to take certain measures, otherwise the performance of our model can be significantly affected. In this section I have discussed two approaches to curb such datasets. # ## 5.1.1 ) Oversampling the Minority or Undersampling the Majority Class # # # In an imbalanced dataset the main problem is that the data is highly skewed ie the number of observations of certain class is more than that of the other. Therefore what we do in this approach is to either increase the number of observations corressponding to the minority class (oversampling) or decrease the number of observations for the majority class (undersampling). # # Note that in our case the number of observations is already pretty low and so oversampling will be more appropriate. # # Below I have used an oversampling technique known as the SMOTE(Synthetic Minority Oversampling Technique) which randomly creates some 'Synthetic' instances of the minority class so that the net observations of both the class get balanced out. # # One thing more to take of is to use the SMOTE before the cross validation step; just to ensure that our model does not overfit the data; just as in the case of feature selection. # In[ ]: oversampler=SMOTE(random_state=42) x_train_smote, y_train_smote = oversampler.fit_sample(x_train,y_train) # ## 5.1.2 ) Using the Right Evaluation Metric # Another important point while dealing with the imbalanced classes is the choice of right evaluation metrics. # # Note that accuracy is not a good choice. This is because since the data is skewed even an algorithm classifying the target as that belonging to the majority class at all times will achieve a very high accuracy. # For eg if we have 20 observations of one type 980 of another ; a classifier predicting the majority class at all times will also attain a accuracy of 98 % but doesnt convey any useful information. # # Hence in these type of cases we may use other metrics such as --> # # # **'Precision'**-- (true positives)/(true positives+false positives) # # **'Recall'**-- (true positives)/(true positives+false negatives) # # **'F1 Score'**-- The harmonic mean of 'precision' and 'recall' # # '**AUC ROC'**-- ROC curve is a plot between 'senstivity' (Recall) and '1-specificity' (Specificity=Precision) # # **'Confusion Matrix'**-- Plot the entire confusion matrix # ## 5.2 ) Building A Model & Making Predictions # In this section I have used different models from the scikit library and trained them on the previously oversampled data and then used them for the prediction purposes. # In[ ]: def compare(model): clf=model clf.fit(x_train_smote,y_train_smote) pred=clf.predict(x_test) # Calculating various metrics acc.append(accuracy_score(pred,y_test)) prec.append(precision_score(pred,y_test)) rec.append(recall_score(pred,y_test)) auroc.append(roc_auc_score(pred,y_test)) # In[ ]: acc=[] prec=[] rec=[] auroc=[] models=[SVC(kernel='rbf'),RandomForestClassifier(),GradientBoostingClassifier()] model_names=['rbfSVM','RandomForestClassifier','GradientBoostingClassifier'] for model in range(len(models)): compare(models[model]) d={'Modelling Algo':model_names,'Accuracy':acc,'Precision':prec,'Recall':rec,'Area Under ROC Curve':auroc} met_df=pd.DataFrame(d) met_df # ## 5.3 ) Comparing Different Models # In[ ]: def comp_models(met_df,metric): sns.factorplot(data=met_df,x=metric,y='Modelling Algo',size=5,aspect=1.5,kind='bar') sns.factorplot(data=met_df,y=metric,x='Modelling Algo',size=7,aspect=2,kind='point') # In[ ]: comp_models(met_df,'Accuracy') # In[ ]: comp_models(met_df,'Precision') # In[ ]: comp_models(met_df,'Recall') # In[ ]: comp_models(met_df,'Area Under ROC Curve') # The above data frame and the visualizations summarize the resuts after training different models on the given dataset. # <a id="content6"></a> # ## 6) Conclusions # # ###### Hence we have completed the analysis of the data and also made predictions using the various ML models. # In[ ]: # In[ ]: Image("../../../input/pavansubhasht_ibm-hr-analytics-attrition-dataset/imagesibm/image-hr.jpg") # In[ ]: # # THE END. # ## [Please star/upvote if u found it helpful.]## # In[ ]:
import re v=input("Enter the password to check:") if(len(v)>=8): if(bool(re.match('((?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[!@#$%^&*]).{8,30})',v))==True): print("Good going Password is Strong.") elif(bool(re.match('((\d*)([a-z]*)([A-Z]*)([!@#$%^&*]*).{8,30})',v))==True): print("try Something stronger!!") else: print("You have entered an invalid password.")
number = 0 variables = "" def fizz_buzz(num, var): fizzarray = [] # doneTODO: Create an empty array outside the loop to store data var = variables num = number while num < 100: # Reset var to prevent issues of adding buzz to buzz or buzz to fizzbuz var = "" #print(num) num += 1 # if num % 3 == 0 and num % 5 == 0: # var = "fizz_buzz" # continue # DONE: Depending on which conditions are met set var to either the number of fizz or buzz or both if num % 3 == 0: var = "fizz" if num % 5 == 0: var += "buzz" # else statement used in this instance will cause overwrighting of saved fizz data, must use if statement. if var == "": var = num # doneTODO: add var to the end of the array fizzarray.append(var) # look up storing as list in an array return fizzarray def print_array(arr): for item in arr: print(item) def out_put(fizzarray): # for idx, x in enumerate(fizzarray): # #print(idx, x) for ind, x in enumerate(fizzarray): if (ind + 1) % 2 == 0: print("\t" + str(x)) else: print(x) #results.append(fizzarray) #print(fizzarray) # TODO: if the index is odd no indent # TODO: if the index is even indent # while i < fizzarray.len(): # # instead of x you would use: # fizzarray[i] # i = i + 1 fizzarray = fizz_buzz(number, variables) # print_array(fizzarray) out_put(fizzarray)
# 반복문 a = ['cat', 'cow', 'tiger'] for animal in a: print(animal, end=' ') else: print('') # 복합 자료형을 사용하는 for문 l = [('루피', 10), ('상디', 20), ('조로', 30)] for data in l: print('이름: %s, 나이: %d' % data) for name, age in l: print('이름: {0}, 나이: {1}'.format(name, age)) l = [{'name': '루피', 'age': 30}, {'name': '루', 'age': 31}, {'name': '피', 'age': 32}] for data in l: print('이름: %(name)s, 나이: %(age)d' % data) # 1 ~ 10 합 구하기 s = 0 for i in range(1, 11): s += i else: print(s) # break for i in range(10): if i > 5: break print(i, end=' ') else: print('') print('') print('----------------') # continue for i in range(10): if i < 5: continue print(i, end=' ') else: print() # 구구단 for x in range(1, 10): for y in range(1, 10): print(str(y) + ' * ' + str(x) + ' = ' + str(x*y).rjust(2), end='\t') else: print('')
import open3d as o3d import numpy as np def degraded_copy_point_cloud(cloud, normal_radius, n_newpc): """ 与えられた点群データからPoisson表面を再構成し、頂点データからランダムに点を取り出して 新たな点群を作成する. Parameters ---------- cloud : open3d.geometry.PointCloud 入力点群 normal_radius : float 法線ベクトル計算時の近傍半径(Poisson表面構成では必要なので).既に法線ベクトルが 計算されていれば無視される. n_newpc : int 新しい点群データに含まれる点の数 """ if np.asarray(cloud.normals).shape[0] == 0: cloud.estimate_normals(o3d.geometry.KDTreeSearchParamHybrid(radius=normal_radius, max_nn=30)) # Poisson表面作成 mesh, densities = o3d.geometry.TriangleMesh.create_from_point_cloud_poisson(cloud, depth=9) # 密度値が低い所の面を削除 mesh.remove_vertices_by_mask(densities < np.quantile(densities, 0.1)) # メッシュの頂点データから入力の点群と同じ数の点を取り出す(randomで) n_vertic = np.asarray(mesh.vertices).shape[0] if n_vertic > n_newpc: indices = np.random.choice(np.arange(n_vertic), size=n_newpc, replace=False) points = np.asarray(mesh.vertices)[indices] else: print("Warning: Mesh vertices is {} (< {}).".format(n_vertic, n_newpc)) points = np.asarray(mesh.vertices) # 新たな点群を作成する newcl = o3d.geometry.PointCloud() newcl.points = o3d.utility.Vector3dVector(points) return newcl if __name__ == '__main__': cloud = o3d.io.read_point_cloud("surface.ply") print("Original Point Cloud") print(cloud) print(np.asarray(cloud.normals).shape) degcl = degraded_copy_point_cloud(cloud, 0.2, 10000) degcl.paint_uniform_color([1, 0.706, 0]) o3d.visualization.draw_geometries([cloud, degcl])
class Parent: def printlastname(self): print('Aggarwal') class Child(Parent): #inherited Parent class def print_name(self): print('Rohan') def printlastname(self): #overwriting parent function print('Aggar') bucky=Child() bucky.print_name() bucky.printlastname()
from __future__ import print_function class Node: def __init__(self, value, next=None): self.value = value self.next = next def print_list(self): temp = self while temp is not None: print(temp.value, end=" ") temp = temp.next print() def reverse_every_k_elements2(head, k): ''' Given the head of a LinkedList and a number ‘k’, reverse every ‘k’ sized sub-list starting from the head. If, in the end, you are left with a sub-list with less than ‘k’ elements, reverse it too. ''' if k <= 1 or head is None: return head curr, prev, new_head = head, None, False while True: last_node_of_previous_part = prev last_node_of_sub_list = curr counter = 0 while counter < k and curr is not None: next = curr.next curr.next = prev prev = curr curr = next counter += 1 # connect with the previous part if last_node_of_previous_part is not None: last_node_of_previous_part.next = prev if new_head == False: new_head = True head = prev # connect with the next part last_node_of_sub_list.next = curr if curr is None: break prev = last_node_of_sub_list return head def reverse_every_k_elements3(head, k): ''' Given the head of a LinkedList and a number ‘k’, reverse every ‘k’ sized sub-list starting from the head. If, in the end, you are left with a sub-list with less than ‘k’ elements, reverse it too. ''' if k <= 1 or head is None: return head counter, prev, curr = 0, None, head is_new_head = False while True: link = prev tail = curr counter = 0 while counter < k and curr is not None: counter += 1 next = curr.next curr.next = prev prev = curr curr = next if is_new_head == False: head = prev is_new_head = True if link is not None: link.next = prev tail.next = curr if curr is None: break prev = tail return head def reverse_every_k_elements(head, k): ''' Given the head of a LinkedList and a number ‘k’, reverse every ‘k’ sized sub-list starting from the head. If, in the end, you are left with a sub-list with less than ‘k’ elements, reverse it too. ''' if head is None or k <= 0: return head prev, curr = None, head is_new_head = False while True: tail_of_first_part = prev tail_of_second_part = curr counter = 0 while counter < k and curr is not None: next = curr.next curr.next = prev prev = curr curr = next counter += 1 if is_new_head == False: is_new_head = True head = prev if tail_of_first_part is not None: tail_of_first_part.next = prev tail_of_second_part.next = curr if curr is None: break prev = tail_of_second_part return head def main(): head = Node(1) head.next = Node(2) head.next.next = Node(3) head.next.next.next = Node(4) head.next.next.next.next = Node(5) head.next.next.next.next.next = Node(6) head.next.next.next.next.next.next = Node(7) head.next.next.next.next.next.next.next = Node(8) print("Nodes of original LinkedList are: ", end='') head.print_list() result = reverse_every_k_elements(head, 3) print("Nodes of reversed LinkedList are: ", end='') result.print_list() main()
sumofsquares = 0 squareofsum = 0 for x in range(1,101): sumofsquares = sumofsquares + (x**2) squareofsum = squareofsum + x squareofsum = squareofsum ** 2 print( squareofsum - sumofsquares) #269147
import re def headers_to_dict(data): global headers for value in data: try: hea_data = re.findall(r'(.*?): (.*?)\n', value)[0] headers.setdefault(hea_data[0], hea_data[1]) except IndexError: hea_data = value.split(': ', 1) headers.setdefault(hea_data[0], hea_data[1]) headers = {} res = input('请输入你所复制的请求头:>>>\n') headers_to_dict(res) print(headers)
# 输入:input() #name = input() #print(name) #name = input('请输入你的名字:') #阻塞式 #print(name) ''' 练习: 游戏:捕鱼达人 输入参与游戏者用户名 输入密码: 充值: 500 ''' print(''' ********************* 捕鱼达人 ********************* ''') username = input('请输入参与游戏者的用户名:\n') password = input('输入密码:\n') print('%s请充值才能进入游戏\n' %username) coins = input('请充值:\n') # input键盘输入的都是字符串类型 print(type(coins)) coins = int(coins) print('%s充值成功!当前游戏币是:%d'%(username, coins))
import numpy as np import pandas as pd from os import system class Table(): def __init__(self): self.table = [[' ',' ',' '], [' ',' ',' '], [' ',' ',' ']] def getMoves(self): moves = [] for x in range(3): for y in range(3): if self.table[x][y] == ' ': moves.append((x,y)) return moves def insertarMarca(self,pos,marca): #método para insertar una marca self.table[pos[0]][pos[1]] = marca #función que me muestra el tablero def mostrarTablero(self): salida = "" for fila in self.table: salida+= repr(fila)+"\n" print(salida) class SuperTable(): tablero = np.zeros((3,3)).astype('object') def __init__(self): self.crearTablero() def crearTablero(self): for row in range(self.tablero.shape[0]): for column in range(self.tablero.shape[1]): self.tablero[row,column] = Table() def mostrarTablero(self): salida = "" matriz = "" for fila in self.tablero: for i in range(3): for tablero in fila: salida += repr(tablero.table[i])+" " matriz+=salida+"\n" salida = "" matriz+="\n" print(matriz) def numeroMovimientos(self): count = 0 for fila in self.tablero: for table in fila: count+=len(table.getMoves()) return count #método para obtener la posición def obtenerTablero(opcion, tablero): i = 0 for row in range(tablero.tablero.shape[0]): for column in range(tablero.tablero.shape[1]): if i==opcion-1: return (row,column) i+=1 return None #método para validar la jugada def validarJugada(pos, tablero): if pos in tablero.getMoves(): return True return False def seleccionarMovimiento(pos, tablero, jugador): print("\nTablero: ", pos) #tablero.tablero[pos].mostrarTablero() print(tablero.tablero[pos].mostrarTablero()) print('\nMovimientos disponibles: ', tablero.tablero[pos].getMoves()) coordenada = input('Seleccione la el movimiento que desea realizar(x y): ') posicion = coordenada.split(' ') posicion = (int(posicion[0]), int(posicion[1])) #recibe la posicion while not validarJugada(pos, tablero.tablero[pos]): print('Por favor, digite un movimiento correspondiente') print('\nMovimientos disponibles: ', tablero[pos].getMoves()) coordenada = input('Seleccione la el movimiento que desea realizar(x y): ') posicion = coordenada.split(' ') posicion = (int(posicion[0]), int(posicion[1])) #recibe la posicion tablero.tablero[pos].insertarMarca(posicion, jugador['marca']) return tablero, posicion # implementación def turnoJugador(jugador): pass # implementación def turnoMaquina(maquina): pass if __name__ =='__main__': system('clear') #primero se crea un tablero tablero = SuperTable() tablero.mostrarTablero() print('Numero de movimientos: ',tablero.numeroMovimientos()) jugadores = [{'nombre':'Eduardo','movimientos':[], 'marca':'X','tipo':'normal'},{'nombre':'bot','movimientos':[],'marca':'O','tipo':'IA'}] #generarTurnoAleatorio jugador = jugadores[np.random.randint(len(jugadores))] opcion = int(input('Seleccione un tablero(1:9): ')) #valida la opción while (opcion-1 <0) or (opcion-1>8): print('Por favor, seleccione un tablero: ') opcion = int(input('Seleccione un tablero(1:9): ')) #posición del tablero pos = obtenerTablero(opcion, tablero) tablero, pos = seleccionarMovimiento(pos, tablero, jugador) tablero.mostrarTablero()
import pytest import serverly.utils from serverly.utils import * def test_parse_role_hierarchy(): e1 = { "normal": "normal", "admin": "normal" } e2 = { "normal": "normal", "admin": "normal", "staff": "admin", "root": "staff", "god": "staff", } e3 = { "normal": "normal", "admin": "normal", "staff": "normal", "root": {"admin", "staff"}, "god": "root" } r1 = parse_role_hierarchy(e1) r2 = parse_role_hierarchy(e2) r3 = parse_role_hierarchy(e3) assert r1 == {"normal": {"normal"}, "admin": {"normal"}} assert r2 == {"normal": {"normal"}, "admin": {"normal"}, "staff": { "admin", "normal"}, "root": {"admin", "normal", "staff"}, "god": {"admin", "normal", "staff"}} assert r3 == {"normal": {"normal"}, "admin": {"normal"}, "staff": {"normal"}, "root": {"admin", "normal", "staff"}, "god": {"admin", "normal", "staff", "root"}} def test_ranstr(): s = [] for _ in range(10000): r = ranstr() assert len(r) == 20 assert not r in s s.append(r) def test_guess_response_headers(): c1 = "<html lang='en_US'><h1>Hello World!</h1></html>" h1 = {"content-type": "text/html"} assert guess_response_headers(c1) == h1 c2 = "Hello there!" h2 = {"content-type": "text/plain"} assert guess_response_headers(c2) == h2 c3 = {"hello": True} h3 = {"content-type": "application/json"} assert guess_response_headers(c3) == h3 c4 = {"id": 1, "password": "totallyhashed", "salt": "totallyrandom", "username": "oh yeah!"} h4 = {"content-type": "application/json"} assert guess_response_headers(c4) == h4 c5 = open("test_utils.py", "r") h5 = {"content-type": "text/x-python"} assert guess_response_headers(c5) == h5 c5.close() c6 = open("temporary.notanactualfilenamesomimetypescantguessit", "w+") h6 = {"content-type": "text/plain"} assert guess_response_headers(c6) == h6 c6.close() os.remove("temporary.notanactualfilenamesomimetypescantguessit") c7 = bytes("hello world", "utf-8") h7 = {"content-type": "application/octet-stream"} assert guess_response_headers(c7) == h7 def test_get_server_address(): valid = ("localhost", 8080) assert get_server_address(("localhost", 8080)) == valid assert get_server_address("localhost,8080") == valid assert get_server_address("localhost, 8080") == valid assert get_server_address("localhost;8080") == valid assert get_server_address("localhost; 8080") == valid assert get_server_address("localhost:8080") == valid assert get_server_address("localhost::8080") == valid assert get_server_address("localhost|8080") == valid assert get_server_address("localhost||8080") == valid def test_get_server_address_2(): valid = ("localhost", 20000) typy_errory = [True, {"hostname": "localhost", "port": 20000}, 42] value_errory = [(True, "localhost"), ("whats", "up"), (42, 3.1415926535)] assert get_server_address((20000, "localhost")) == valid for i in typy_errory: with pytest.raises(TypeError): get_server_address(i) for i in value_errory: with pytest.raises(ValueError): get_server_address(i) def test_get_server_address_3(): valid = ("localhost", 8080) with pytest.raises(Exception): with pytest.warns(UserWarning): serverly.Server._get_server_address((8080, "local#ost")) def test_check_relative_path(): falsy_values = ["hello", "whatsupp", ""] typy_errors = [bytes("hello there", "utf-8"), open("test_utils.py", "r"), True, 23.7] goodish_ones = ["/hello", "/hello-world", "/whatss/up"] for i in falsy_values: with pytest.raises(ValueError): check_relative_path(i) for i in typy_errors: with pytest.raises(TypeError): check_relative_path(i) for i in goodish_ones: assert check_relative_path(i) def test_check_relative_file_path(): with pytest.raises(FileNotFoundError): check_relative_file_path( "definetelynotafile.definetelynotafile.definetelynotafile!") bad_ones = [True, open("test_utils.py", "r"), 42] for i in bad_ones: with pytest.raises(TypeError): check_relative_file_path(i) assert check_relative_file_path("test_utils.py") == "test_utils.py" def test_get_http_method_type(): false_ones = ["GETT", "PooST", "puUT", "DEL", "del", "head", "CONNECT", "options", "TRACE", "patch"] good_ones = {"GET": "get", "PoSt": "post", "Put": "put", "DelEtE": "delete"} for i in false_ones: with pytest.raises(ValueError): get_http_method_type(i) for k, v in good_ones.items(): assert get_http_method_type(k) == v def test_parse_scope_list(): assert parse_scope_list("hello;world;whatsup") == [ "hello", "world", "whatsup"] assert parse_scope_list("19;") == ['19'] assert parse_scope_list("42;1829;sajki;") == ["42", "1829", "sajki"] assert parse_scope_list("") == [] def test_get_scope_list(): assert get_scope_list("admin") == "admin" assert get_scope_list(["admin", "financial"]) == "admin;financial" assert get_scope_list("") == "" def test_get_chunked_response(): r = serverly.objects.Response(body="Hello world") assert get_chunked_response(r) == ["Hello world"] r.bandwidth = 4 assert get_chunked_response(r) == ["Hell", "o wo", "rld"] def test_lowercase_dict(): d = {"Hello World": True, "WhatssUpp": "Yoo"} assert lowercase_dict(d) == {"hello world": True, "whatssupp": "Yoo"} assert lowercase_dict(d, True) == {"hello world": True, "whatssupp": "yoo"} def test_get_bytes(): assert get_bytes("hello world") == bytes("hello world", "utf-8") assert get_bytes( "hello world", "application/octet-stream") == b"hello world" assert get_bytes( {"helele": 42}, "application/octet-stream") == {"helele": 42} assert get_bytes(True) == True
class Solution(object): def toHex(self, num): """ :type num: int :rtype: str """ if num == 0: return '0' # letter map mp = '0123456789abcdef' ans = '' for _ in range(8): # get last 4 digits # num & 1111b n = num & 15 # hex letter for current 1111 c = mp[n] ans = c + ans # num = num / 16 num = num >> 4 #strip leading zeroes return ans.lstrip('0') # def toHex(self, num): # def tohex(val, nbits): # return hex((val + (1 << nbits)) % (1 << nbits)) # return tohex(num, 32)[2:] # def toHex(self, num, h=''): # return (not num or h[7:]) and h or self.toHex(num / 16, '0123456789abcdef'[num % 16] + h)
import math from random import randint import pygame as pg from pygame import mixer as mx """ INITIALISING PYGAME """ pg.init() """ CREAITNG SCREEN """ screen = pg.display.set_mode((800, 600)) """ BACKGROUND MUSIC """ # mx.music.load('lofi_background.wav') # mx.music.set_volume(0.8) # mx.music.play(-1) background_music = mx.Sound("lofi_background.wav") background_music.set_volume(0.8) background_music.play() """ TITLE """ pg.display.set_caption("ChristmasGame") """ CREATING BACKGROUND IMAGE """ background = pg.image.load('bg.jpg') """ CREATING PLAYER """ playerImg = pg.image.load("player.png") playerX = 52 playerY = 5 playerX_change = 0 playerY_change = 0 """ CREATING CANDY """ candy = pg.image.load("candy.png") candyX = randint(0,750) candyY = randint(0,550) score = 0 font = pg.font.Font("freesansbold.ttf",32) over_text = pg.font.Font("freesansbold.ttf",64) time_left = pg.font.Font("freesansbold.ttf",32) """ SHOWING SCORE """ def show_score(): score_text = font.render(f"Score : {score}",True, (255,255,255)) screen.blit(score_text,(10,10)) """ SHOWING DEATH SCREEN """ def show_death(score): won = score>=15 # if not done:win_music() text = "You Won!" if won else "You lose" over_text = font.render(text, True, (255,255,255)) screen.blit(over_text, (300,300)) """ UPDATING THE PLAYER POSITION """ def player(x, y): screen.blit(playerImg,(x, y)) ticks = pg.time.get_ticks() player_alive = True """ GAME LOOP """ running = True while running: screen.fill((0, 0, 0)) #FILLING BACKGROUND WITH BLACK, CHANGING THIS SPOILS EVERYTHING screen.blit(background,((0,0))) screen.blit(candy, (candyX,candyY)) """ COLLISION """ if math.sqrt((candyX-playerX)**2+(candyY-playerY)**2)<=40: candyX=randint(0,750) candyY=randint(0,550) score += 1 # print(score) """ O(n^2) stuff """ for event in pg.event.get(): if player_alive or event.type == pg.QUIT: if event.type == pg.KEYDOWN: if event.key == pg.K_SPACE: playerY_change=-0.4 if event.key == pg.K_LEFT: playerX_change = -0.5 if event.key == pg.K_RIGHT: playerX_change = 0.5 if event.type == pg.KEYUP: if event.key == pg.K_LEFT or event.key == pg.K_RIGHT: playerX_change = 0 """ QUITTING GAME ON EXIT BUTTON """ if event.type == pg.QUIT:running = False """ FAKE GRAVITY """ playerY_change+=0.0009 playerY+=playerY_change if playerY>=540:playerY=540 if playerY<=5:playerY=5 """ MOVING LEFT OR RIGHT """ playerX+=playerX_change if playerX<=0: playerX=0 elif playerX>=736: playerX=736 show_score() """ CHANGING POSITION OF PLYER""" player(playerX, playerY) seconds = (pg.time.get_ticks()-ticks)/1000 if seconds>20: player_alive = False show_death(score) pg.display.update()
""" This is an interactive demonstration for information retrieval. We will encode a large corpus with 500k+ questions. This is done once and the result is stored on disc. Then, we can enter new questions. The new question is encoded and we perform a brute force cosine similarity search and retrieve the top 5 questions in the corpus with the highest cosine similarity. For larger datasets, it can make sense to use a vector index server like https://github.com/spotify/annoy or https://github.com/facebookresearch/faiss """ from sentence_transformers import SentenceTransformer, util import os from zipfile import ZipFile import pickle import time model_name = 'distilbert-base-nli-stsb-quora-ranking' embedding_cache_path = 'quora-embeddings-{}.pkl'.format(model_name.replace('/', '_')) max_corpus_size = 100000 model = SentenceTransformer(model_name) #Check if embedding cache path exists if not os.path.exists(embedding_cache_path): # Check if the dataset exists. If not, download and extract dataset_path = 'quora-IR-dataset' if not os.path.exists(dataset_path): print("Dataset not found. Download") zip_save_path = 'quora-IR-dataset.zip' util.http_get(url='https://public.ukp.informatik.tu-darmstadt.de/reimers/sentence-transformers/datasets/quora-IR-dataset.zip', path=zip_save_path) with ZipFile(zip_save_path, 'r') as zip: zip.extractall(dataset_path) corpus_sentences = [] with open(os.path.join(dataset_path, 'graph/sentences.tsv'), encoding='utf8') as fIn: next(fIn) #Skip header for line in fIn: qid, sentence = line.strip().split('\t') corpus_sentences.append(sentence) if len(corpus_sentences) >= max_corpus_size: break print("Encode the corpus. This might take a while") corpus_embeddings = model.encode(corpus_sentences, show_progress_bar=True) print("Store file on disc") with open(embedding_cache_path, "wb") as fOut: pickle.dump({'sentences': corpus_sentences, 'embeddings': corpus_embeddings}, fOut) else: print("Load pre-computed embeddings from disc") with open(embedding_cache_path, "rb") as fIn: cache_data = pickle.load(fIn) corpus_sentences = cache_data['sentences'][0:max_corpus_size] corpus_embeddings = cache_data['embeddings'][0:max_corpus_size] ############################### print("Corpus loaded with {} sentences / embeddings".format(len(corpus_sentences))) while True: inp_question = input("Please enter a question: ") start_time = time.time() question_embedding = model.encode(inp_question) hits = util.information_retrieval(question_embedding, corpus_embeddings) end_time = time.time() hits = hits[0] #Get the hits for the first query print("Input question:", inp_question) print("Results (after {:.3f} seconds):".format(end_time-start_time)) for hit in hits[0:5]: print("\t{:.3f}\t{}".format(hit['score'], corpus_sentences[hit['corpus_id']])) print("\n\n========\n")
#!/usr/bin/env python3 # # Copyright (C) 2020-2022 by # David Turner, Robert Wilhelm, and Werner Lemberg. # # This file is part of the FreeType project, and may only be used, modified, # and distributed under the terms of the FreeType project license, # LICENSE.TXT. By continuing to use, modify, or distribute this file you # indicate that you have read the license and understand and accept it # fully. """Extract the FreeType version numbers from `<freetype/freetype.h>`. This script parses the header to extract the version number defined there. By default, the full dotted version number is printed, but `--major`, `--minor` or `--patch` can be used to only print one of these values instead. """ from __future__ import print_function import argparse import os import re import sys # Expected input: # # ... # #define FREETYPE_MAJOR 2 # #define FREETYPE_MINOR 10 # #define FREETYPE_PATCH 2 # ... RE_MAJOR = re.compile(r"^ \#define \s+ FREETYPE_MAJOR \s+ (.*) $", re.X) RE_MINOR = re.compile(r"^ \#define \s+ FREETYPE_MINOR \s+ (.*) $", re.X) RE_PATCH = re.compile(r"^ \#define \s+ FREETYPE_PATCH \s+ (.*) $", re.X) def parse_freetype_header(header): major = None minor = None patch = None for line in header.splitlines(): line = line.rstrip() m = RE_MAJOR.match(line) if m: assert major == None, "FREETYPE_MAJOR appears more than once!" major = m.group(1) continue m = RE_MINOR.match(line) if m: assert minor == None, "FREETYPE_MINOR appears more than once!" minor = m.group(1) continue m = RE_PATCH.match(line) if m: assert patch == None, "FREETYPE_PATCH appears more than once!" patch = m.group(1) continue assert ( major and minor and patch ), "This header is missing one of FREETYPE_MAJOR, FREETYPE_MINOR or FREETYPE_PATCH!" return (major, minor, patch) def main(): parser = argparse.ArgumentParser(description=__doc__) group = parser.add_mutually_exclusive_group() group.add_argument( "--major", action="store_true", help="Only print the major version number.", ) group.add_argument( "--minor", action="store_true", help="Only print the minor version number.", ) group.add_argument( "--patch", action="store_true", help="Only print the patch version number.", ) parser.add_argument( "input", metavar="FREETYPE_H", help="The input freetype.h header to parse.", ) args = parser.parse_args() with open(args.input) as f: header = f.read() version = parse_freetype_header(header) if args.major: print(version[0]) elif args.minor: print(version[1]) elif args.patch: print(version[2]) else: print("%s.%s.%s" % version) return 0 if __name__ == "__main__": sys.exit(main())
""" Rosechelle Joy C. Oraa 2013-11066 CMSC 128 AB-3L """ import sys """ numToWords() accepts an input number and outputs its equivalent in words temp_num : input by the user """ def numToWords(temp_num): if len(temp_num)>7: #if number inputed is greater than 7 digits: invalid print 'Invalid: input can only have at most 7 digits' return str_num = '' #word equivalent of temp_num length = len(temp_num) #input length pos =0 #current position j=0 str_form = '' for i in range(6, -1, -1): #places input value in an array of 7 elements(for each digit) if i>length-1: #if current length is less than current max number of digits str_num=str_num+'0' else: while j!=length: #while input is not fully transferred to str_num str_num=str_num+temp_num[j] j=j+1 x=str_num #holds input in its 7 digit representation while pos < 7 : if pos == 4 and (x[pos-1]!='0' or x[pos-2]!='0' or x[pos-3]!='0') and length>3: str_form = str_form+'thousand ' #if at 4th pos and 3 previous digits are not == 0 if x[pos]=='0': #if number is 0 if pos == 6 and length == 1: str_form = str_form + 'zero' elif pos != 2 and pos != 5: #ones digit if x[pos]=='1': str_form = str_form+'one ' elif x[pos]=='2': str_form=str_form+'two ' elif x[pos]=='3': str_form=str_form+'three ' elif x[pos] =='4': str_form=str_form+'four ' elif x[pos]=='5': str_form=str_form+'five ' elif x[pos]=='6': str_form=str_form+'six ' elif x[pos]=='7': str_form=str_form+'seven ' elif x[pos]=='8': str_form=str_form+'eight ' elif x[pos]=='9': str_form=str_form+'nine ' if pos == 0: str_form = str_form+'million ' elif pos == 1 or pos == 4: str_form = str_form+'hundred ' else: #tens digit if pos == 2 or pos == 5: if x[pos]== '1': pos=pos+1 if x[pos]== '0': str_form = str_form+'ten ' elif x[pos]== '1': str_form = str_form+'eleven ' elif x[pos]== '2': str_form = str_form+'twelve ' elif x[pos]== '3': str_form = str_form+'thirteen ' elif x[pos]== '4': str_form = str_form+'fourteen ' elif x[pos]== '5': str_form = str_form+'fifteen ' elif x[pos]== '6': str_form = str_form+'sixteen ' elif x[pos]== '7': str_form = str_form+'seventeen ' elif x[pos]== '8': str_form = str_form+'eighteen ' elif x[pos]== '9': str_form = str_form+'nineteen ' elif x[pos]== '2': str_form = str_form+'twenty ' elif x[pos]== '3': str_form = str_form+'thirty ' elif x[pos]== '4': str_form = str_form+'forty ' elif x[pos]== '5': str_form = str_form+'fifty ' elif x[pos]== '6': str_form = str_form+'sixty ' elif x[pos]== '7': str_form = str_form+'seventy ' elif x[pos]== '8': str_form = str_form+'eighty ' elif x[pos]== '9': str_form = str_form+'ninety ' if pos == 2 or pos == 5: pos= pos+1 if x[pos]=='1': #single digit after tens str_form = str_form+'one ' elif x[pos]=='2': str_form=str_form+'two ' elif x[pos]=='3': str_form=str_form+'three ' elif x[pos] =='4': str_form=str_form+'four ' elif x[pos]=='5': str_form=str_form+'five ' elif x[pos]=='6': str_form=str_form+'six ' elif x[pos]=='7': str_form=str_form+'seven ' elif x[pos]=='8': str_form=str_form+'eight ' elif x[pos]=='9': str_form=str_form+'nine ' pos = pos+1 #increment pos print str_form #print word representation return """ wordsToNum() accepts word(s) then prints its numerical equivalent word - string input """ def wordsToNum(word): word = word.split() #word- list of words from word gen_num = 0 #total value temp = 0 #current integer mill_num=0 #total million value of word hund_thou = 0 #total hundred thousand value of word hund = 0 #total hundred value of word wLen = len(word)# number of words in word flag=0 # is equal to 1 if there should be no more thousands i=0 while i < wLen: #iterates through each word in word(list) if word[i] == 'one': temp+=1 elif word[i] == 'two': temp+=2 elif word[i] == 'three': temp+=3 elif word[i] == 'four': temp+=4 elif word[i] == 'five': temp+=5 elif word[i] == 'six': temp+=6 elif word[i] == 'seven': temp+=7 elif word[i] == 'eight': temp+=8 elif word[i] == 'nine': temp+=9 elif word[i] == 'ten': temp += 10 elif word[i] == 'eleven': temp += 11 elif word[i] == 'twelve': temp += 12 elif word[i] == 'thirteen': temp += 13 elif word[i] == 'fourteen': temp += 14 elif word[i] == 'fifteen': temp += 15 elif word[i] == 'sixteen': temp += 16 elif word[i] == 'seventeen': temp += 17 elif word[i] == 'eighteen': temp += 18 elif word[i] == 'nineteen': temp += 19 elif word[i] == 'twenty': temp += 20 elif word[i] == 'thirty': temp += 30 elif word[i] == 'forty': temp += 40 elif word[i] == 'fifty': temp += 50 elif word[i] == 'sixty': temp += 60 elif word[i] == 'seventy': temp += 70 elif word[i] == 'eighty': temp += 80 elif word[i] == 'ninety': temp += 90 elif word[i] == 'million': #multiply previous number(temp) to 1000000 mill_num= temp*1000000 #place in mill_num temp=0 elif word[i] == 'hundred': #multiply value in temp to 100 temp= temp*100 elif word[i] == 'thousand': #multiply hund to 1000 then place in hund_thou hund_thou = hund*1000 hund=0 temp=0 hund = temp; i+=1 #increment i then next iteration gen_num= mill_num+hund_thou+hund #gen_num= accumulated value of millions, hundred thousands, and hundreds print gen_num #print total number return """ wordsToCurrency() accepts two inputs then generates string in number form with given currency word - number in words inputed by the user cur- currency given by the user """ def wordsToCurrency(word, cur): if cur=='USD' or cur=='JPY' or cur == 'PHP': #checks if currency given is valid sys.stdout.write(cur) #print currency wordsToNum(word) #print word in its numerical value else: print 'Invalid!' return """ numberDelimitered() accepts three inputs then prints the number with a delimiter in the position given by the user temp - number delimiter - delimiter given by the user jumps - # of jumps from the right """ def numberDelimitered(temp, delimiter, jumps): temp= str(temp) #typecast temp to a string rev='' #will hold temp in reverse i=0 if len(temp) > 7: print 'Invalid!: exceeded max no. of digits' return for i in range(0, len(temp)): #reverse number input rev=temp[i]+rev temp='' for i in range(0, len(rev)): #iterates through all digits in rev if jumps== i: #if i == jumps temp= delimiter+temp #concatenate delimiter with temp temp= rev[i]+temp #concatenate rev[i] with temp print temp return """ prints menu and lets the user choose feature to be used """ print 'MENU' print '[1] Number to Word' print '[2] Word to Number' print '[3] Word to Currency' print '[4] Number Delimitered ' ch = input('choice: ') if(ch==1): #number to words temp_num = raw_input('Enter number: ') numToWords(temp_num); elif(ch==2): #word to number word= raw_input("Enter input: ") wordsToNum(word); elif(ch==3): #number to currency word= raw_input("Enter number in words: ") cur= raw_input("Enter currency: ") wordsToCurrency(word, cur) elif(ch==4): #number delimitered temp = raw_input('Enter number: ') delimiter = raw_input('Enter delimiter: ') jumps = input('Enter # of jumps: ') numberDelimitered(temp, delimiter, jumps); else: print 'Invalid!'
from collections import defaultdict from math import exp, log import pandas as pd # optional class Elo: """Base class to generate elo ratings Includes the ability for some improvements over the original methodology: * k decay: use a higher update speed early in the season * crunch/carryover: shift every team's ratings closer to the mean between seasons * interstate and home_advantage * optimised initial ratings Hyperparameters can be fit with a grid search, eg. sklearn.model_selection.GridSearchCV Initial ratings can be fit with a logistic regression (equivalent to a static elo) eg. sklearn.linear_model.LogisticRegression By default assumes a logistic distribution of ratings """ def __init__(self, k=30, home_advantage=20, interstate_advantage=5, width=400/log(10), carryover=0.75, k_decay=0.95, initial_ratings=None, mean_rating=1500, target='home_win_draw_loss'): self.k = k self.home_advantage = home_advantage self.interstate_advantage = interstate_advantage self.width = width self.carryover = carryover self.k_decay = k_decay self.mean_rating = mean_rating self.initial_ratings = initial_ratings or {} self.target = target # home_win_draw_loss, home_points_ratio, home_squashed_margin def iterate_fixtures(self, fixtures, as_dataframe=True): """ Parameters ---------- fixtures : list of dict or pd.DataFrame Must be ordered. Each record (row) must have (columns): home_team, away_team, round_number, is_interstate, <self.target> Prefer a list of records as it's much faster We use the python stdlib math.exp which seems faster in single computation than numpy's version and therefore speeds up parameter fitting Profile code with lprun: %load_ext line_profiler elo = Elo() %lprun -f elo.iterate_fixtures elo.iterate_fixtures(fxtrain, as_dataframe=True) """ # new teams are given self.initial_ratings self.current_ratings_ = defaultdict(lambda: self.mean_rating, self.initial_ratings) if isinstance(fixtures, pd.DataFrame): # A list of records is faster and less prone to errors on update than a DataFrame fixtures = fixtures.reset_index().to_dict('records') for fx in fixtures: home_team = fx['home_team'] away_team = fx['away_team'] home_actual_result = fx[self.target] round_number = fx['round_number'] is_interstate = fx['is_interstate'] # home_expected_result = self.predict_result(home_team, away_team, is_interstate, round_number) # ------- home_rating_pre = self.current_ratings_[home_team] away_rating_pre = self.current_ratings_[away_team] if round_number == 1: # Crunch the start of the season # Warning: this will make an in-place change the current ratings for the end of season # TODO: don't crunch the first round of training home_rating_pre = self.carryover*home_rating_pre + (1-self.carryover)*self.mean_rating away_rating_pre = self.carryover*away_rating_pre + (1-self.carryover)*self.mean_rating ratings_diff = home_rating_pre - away_rating_pre + self.home_advantage + self.interstate_advantage*is_interstate home_expected_result = 1.0 / (1 + exp(-ratings_diff/self.width)) # self.update_ratings(home_actual_result, home_expected_result, round_number) # ------ change_in_home_elo = self.k*self.k_decay**round_number*(home_actual_result - home_expected_result) home_rating_post = home_rating_pre + change_in_home_elo away_rating_post = away_rating_pre - change_in_home_elo # update ratings self.current_ratings_[home_team] = home_rating_post self.current_ratings_[away_team] = away_rating_post fx['home_rating_pre'] = home_rating_pre fx['away_rating_pre'] = away_rating_pre fx['home_expected_result'] = home_expected_result # proba # fx['binary_expected_home_result'] = int(expected_home_result > 0.5) # prob if as_dataframe: # return pd.DataFrame(fixtures, columns=['matchid', 'home_expected_result']).set_index('matchid') return pd.DataFrame(fixtures).set_index('matchid') return fixtures def fit(self, X): # the only thing we really need to store is the *latest* rating (the system is memoryless) # self.teams_ = ['myteam'] # self.current_ratings_ = {'myteam': 1500} return X def predict_proba(self): return expected_home_result def predict(self): return int(expected_home_result > 0.5)
class Human(object): def __init__(self, name): self.name = name def walk(self): print (self.name + " is walking") def get_name(self): return (self. name) def set_name(self, name): if len(name) <= 10: self.name = name human_a = Human("alan") print (human_a.name) human_a.set_name('bob') print(human_a.name) xy = Human('noah') print (xy.name) xy.walk() xy.set_name('nova') xy.walk()
#!/usr/bin/python import urllib2 site = raw_input("site : ") # http://www.google.com/ ---> this must be in this form list = open((raw_input("list with folders : "))) # a textfile , one folder/line for folder in list : try : url = site+folder urllib2.urlopen(url).read() msg = "[-] folder " + folder + " exist" print msg except : msg = "[-] folder " + folder + "does not exist" print msg print "" print "[-] done"
#INPUT """Our input is the fahrenheit temperature from the woman""" fahrenheit_value = float(input("Please Enter the Fahrenheit temperature: \n")) #PROCESSING """The conversion from fahrenheit to celsius""" celsius_value = (fahrenheit_value - 32) * (5/9) print(round(celsius_value, 2)) #OUTPUT """Output is the equivalent celsius temperature""" number = 98.76453 new_number = round(number, 2) print(new_number) range() print('all even numbers from 1 to 10') print(range(0, 10, 2))
adj=[] row, col = key // n, key % n if (col - 1) >= 0: adj.append((row*n) + (col - 1)) if (col + 1) < n: adj.append((row*n) + (col + 1)) if (row - 1) >= 0: adj.append((row-1)*n + col) if (row + 1) < n: adj.append((row + 1)*n + col) return adj def find_path(source, arr, n): visited = [False] * pow(n, 2) queue = [] queue.append(source) while queue: popped = queue.pop(0) visited[popped] = True for i in adjacent(popped, arr, n): if arr[i] == 2: return 1 elif arr[i] == 3 and visited[i] == False: queue.append(i) return 0 t = int(input()) for i in range(t): n = int(input()) arr = map(int, input().split()) x = list(arr) source = x.index(1) print (find_path(source, x, n))
#!/usr/bin/env python3 ''' @author Michele Tomaiuolo - http://www.ce.unipr.it/people/tomamic @license This software is free - http://www.gnu.org/licenses/gpl.html ''' import sys class TicTacToe: NONE = '.' PLR1 = 'X' PLR2 = 'O' DRAW = 'None' OUT = '!' def __init__(self, side=3): self._side = side self._matrix = [TicTacToe.NONE] * (self._side * self._side) self.clear() def clear(self): for i in range(len(self._matrix)): self._matrix[i] = TicTacToe.NONE self._turn = 0 def play_at(self, x: int, y: int): if self.get(x, y) == TicTacToe.NONE: i = x + y * self._side if self._turn % 2 == 0: self._matrix[i] = TicTacToe.PLR1 else: self._matrix[i] = TicTacToe.PLR2 self._turn += 1 def get(self, x: int, y: int) -> str: if 0 <= x < self._side and 0 <= y < self._side: return self._matrix[x + y * self._side] else: return TicTacToe.OUT def _check_line(self, x: int, y: int, dx: int, dy: int) -> bool: '''Check a single line, starting at (x, y) and advancing for `side` steps in direction (dx, dy). If a single player occupies all cells, he's won.''' player = self.get(x, y) if player == TicTacToe.NONE: return False for i in range(self._side): if self.get(x + dx * i, y + dy * i) != player: return False return True def winner(self) -> str: '''Check all rows, columns and diagonals. Otherwise, check if the game is tied.''' for x in range(self._side): if self._check_line(x, 0, 0, 1): return self.get(x, 0) for y in range(self._side): if self._check_line(0, y, 1, 0): return self.get(0, y) if self._check_line(0, 0, 1, 1): return self.get(0, 0) if self._check_line(self._side - 1, 0, -1, 1): return self.get(self._side - 1, 0) if self._turn == self._side * self._side: return TicTacToe.DRAW return TicTacToe.NONE def side(self) -> int: return self._side def __str__(self): out = '' # Using a StringIO is more efficient for y in range(self._side): for x in range(self._side): out += self._matrix[y * self._side + x] out += '\n' return out def main(): game = TicTacToe(4) print(game) x = int(input('x? ')) y = int(input('y? ')) while x >= 0 and y >= 0: game.play_at(x, y) print(game) winner = game.winner() if winner != TicTacToe.NONE: print('Game finished.', winner, 'has won!') game.clear() print(game) x = int(input('x? ')) y = int(input('y? ')) if __name__ == '__main__': main()
from django import template register = template.Library() @register.filter(name='star_multiply') def star_multiply(value, arg: str = '★', sep: str = ' ') -> str: """ Размножитель символов :param value: количество символов в пакете :param arg: повторяемый символ :param sep: разделитель между символами :return: пакет символов """ return sep.join(arg * int(value)) @register.filter def tour_min(dictionary, key): return min([dictionary[i][key] for i in dictionary]) @register.filter def tour_max(dictionary, key): return max([dictionary[i][key] for i in dictionary])
n = int(input()) s = [input() for _ in range(3)] ans = 0 for v in zip(*s): len_ = len(set(v)) ans += len_ - 1 # if len_ == 3: # ans += 2 # elif len_ == 2: # ans += 1 # else: # # len_ == 1 # ans += 0 print(ans)
#Nhap vao ba so a, b, c a = int(input(" Nhap vao gia tri a=")); b = int(input(" nhap vao gia trị b =")); c = int(input(" nhap vao gia trị c =")); if a <= b <= c: print("%d %d %d" % (a, b, c)) elif a <= c <= b: print("%d %d %d" % (a, c, b)) elif b <= a <= c: print("%d %d %d" % (b, a, c)) elif b <= c <= a: print("%d %d %d" % (b, c, a)) elif c <= a <= b: print("%d %d %d" % (c, a, b)) else: # c <= b <= a print("%d %d %d" % (c, b, a))
print "Each game console cost 22000" money = input("How much money do you have in your account now? Php ") y=(money)/22000 print "The number of game consoles with a price of Php 22000 you can buy is ", y n = (money) - y*22000 print "After buying the consoles, you will have", n,"pesos left on your account" e = 22000 - n print "You will need an additional amount of at least", e,"pesos to buy a new console"
""" Merge k sorted arrays <3,5,7> <0,6> <0,6,28> Approach 1 : merge sort Approach 2 : use a min heap(size<=k) to keep current min elements from each array Each node in the heap is a tuple (value, array_index, element_index) : pop min element from min heap to add to output array : push the element at next index of popped element in the same array """ import heapq as hq def merge_k_sorted_arrays(sorted_arrays): output = [] # add min/first element from each array into the heap h = [] for array_index, current_array in enumerate(sorted_arrays): if len(current_array) > 1: hq.heappush(h, (current_array[0], array_index, 0))
# -*- coding: utf-8 -*- """ Created on Tue May 30 17:49:57 2017 @author: brummli """ import matplotlib as mpl mpl.use('Agg') import numpy as np import matplotlib.pyplot as plt from dataLoader import dataPrep """ Calculates standard statistics :params: data: numpy array containing the data of form (examples,timesteps,dims) :return: tuple containing (mean,var,min,max) """ def totalStats(data): mean = np.mean(data) var = np.var(data) minimum = np.min(data) maximum = np.max(data) return (mean,var,minimum,maximum) """ Calculates example wise standard statistics :params: data: numpy array containing the data of form (examples,timesteps,dims) :return: tuple containing (mean,var,min,max) """ def exampleStats(data): if len(data.shape) == 3: mean = np.mean(data,axis=(1,2)) var = np.var(data,axis=(1,2)) minimum = np.min(data,axis=(1,2)) maximum = np.max(data,axis=(1,2)) elif len(data.shape) == 2: mean = np.mean(data,axis=(1)) var = np.var(data,axis=(1)) minimum = np.min(data,axis=(1)) maximum = np.max(data,axis=(1)) else: #Make sure there are values to return so that plotting doesn't produce an error mean = 0 var = 0 minimum = 0 maximum = 0 return (mean,var,minimum,maximum) """ Calculates time wise standard statistics :params: data: numpy array containing the data of form (examples,timesteps,dims) :return: tuple containing (mean,var,min,max) """ def timeStats(data): if len(data.shape) == 3: mean = np.mean(data,axis=(0,2)) var = np.var(data,axis=(0,2)) minimum = np.min(data,axis=(0,2)) maximum = np.max(data,axis=(0,2)) else: #Make sure there are values to return so that plotting doesn't produce an error mean = 0 var = 0 minimum = 0 maximum = 0 return (mean,var,minimum,maximum) """ Calculates feature wise standard statistics :params: data: numpy array containing the data of form (examples,timesteps,dims) :return: tuple containing (mean,var,min,max) """ def featureStats(data): if len(data.shape) == 3: mean = np.mean(data,axis=(0,1)) var = np.var(data,axis=(0,1)) minimum = np.min(data,axis=(0,1)) maximum = np.max(data,axis=(0,1)) elif len(data.shape) == 2: mean = np.mean(data,axis=(0)) var = np.var(data,axis=(0)) minimum = np.min(data,axis=(0)) maximum = np.max(data,axis=(0)) else: #Make sure there are values to return so that plotting doesn't produce an error mean = 0 var = 0 minimum = 0 maximum = 0 return (mean,var,minimum,maximum) def producePlot(func,data,descString,log=True): processed = func(data) fig = plt.figure() if log: plt.yscale('log') plt.plot(processed[0],'go-',label='mean') plt.plot(processed[1],'ro-',label='var') plt.plot(processed[2],'bo-',label='min') plt.plot(processed[3],'ko-',label='max') plt.legend() plt.savefig('stats/'+descString+'_'+func.__name__+'.png') plt.close(fig) def plotWrapper(data,descString,log=True): producePlot(totalStats,data,descString,log=log) producePlot(exampleStats,data,descString,log=log) producePlot(timeStats,data,descString,log=log) producePlot(featureStats,data,descString,log=log) if __name__ == '__main__': loader = dataPrep() dev_data_x,dev_data_y = loader.prepareDevTestSet(loader.devData) train_data_x,train_data_y = loader.prepareTrainSet(loader.augment(loader.trainData,0.8,1.2,3,0.8,1.2,3)) fig = plt.figure(1) plt.boxplot(np.mean(np.mean(train_data_x,axis=1),axis=1)) fig.show() fig = plt.figure(2) plt.boxplot(np.mean(train_data_x,axis=1).T) fig.show()
''' You've built an inflight entertainment system with on-demand movie streaming. Users on longer flights like to start a second movie right when their first one ends, but they complain that the plane usually lands before they can see the ending. So you're building a feature for choosing two movies whose total runtimes will equal the exact flight length. Write a function that takes an integer flight_length (in minutes) and a list of integers movie_lengths (in minutes) and returns a boolean indicating whether there are two numbers in movie_lengths whose sum equals flight_length. When building your function: - Assume your users will watch exactly two movies - Don't make your users watch the same movie twice - Optimize for runtime over memory ''' # My solution # Build a dictionary by iterating through the array # Then check every element in the list until one satisfies the requirements # We can do this in O(n) time, where n is the length of movie_lengths. def has_two_movies_with_good_runtime(flight_length, movie_lengths): movie_map = {} # Build Map for length in movie_lengths: movie_map[length] = movie_map[length] + 1 if length in movie_map else 1 # Check for valid cases for movie in movie_lengths: minutes_needed = flight_length - movie if (minutes_needed <= 0) or ((minutes_needed in movie_map) and (minutes_needed != movie or movie_map[movie] > 1)): return True return False # Interview cake solution def can_two_movies_fill_flight(movie_lengths, flight_length): # Movie lengths we've seen so far movie_lengths_seen = set() for first_movie_length in movie_lengths: matching_second_movie_length = flight_length - first_movie_length if matching_second_movie_length in movie_lengths_seen: return True movie_lengths_seen.add(first_movie_length) # We never found a match, so return False return False print(has_two_movies_with_good_runtime(40, [20, 20, 40]))
import time stat1=dict() stat2=dict() #numbers_sizes = (i*10**exp for exp in range(4, 8, 1) for i in range(1, 11, 5)) numbers_sizes = [10**exp for exp in range(4, 10, 1)] print(str(numbers_sizes)) for input in numbers_sizes: # prog 1 start_time=time.time() cube_numbers=[] for n in range(0,input): if n % 2 == 1: cube_numbers.append(n**3) process_time=time.time()-start_time print('Process1 time for', input, '\tis', time.time()-start_time) stat1[str(input)]=process_time # prog 2 cube_numbers=[] start_time=time.time() cube_numbers = [n**3 for n in range(0,input) if n%2 == 1] process_time=time.time()-start_time print('Process2 time for', input, '\tis', time.time()-start_time) stat2[str(input)]=process_time for i in numbers_sizes: print('Input:',i,'\t',stat1[i],'\t', stat2[i],'\t', stat2[i]-stat1[i])
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from numpy import random, exp, dot, array #%% Neural Network class Neural_Network(): #%% Sigmoid function def φ(self, x): return 1/(1 + exp(-x)) # Sigmoid function's derivative def dφ(self, x): return exp(x)/ (1 + exp(x))**2 #%% Let's train our Neuron def __init__(self, x, y, lr, epochs): ''' x: training input (dimentions: parameters* data) y: training output (dimentions: parameters* data) lr: learning rate epochs: iterations ''' # same random number random.seed(1) # weights (dimentions: perceptrons* parameters) self.w = 2* random.random( (1,3) ) - 1 print('Initial weights: ', self.w) for epoch in range(epochs): # learning output Y = self.φ( dot(self.w, x) ) # error = training output - learning output error = y - Y # adjustments to minimize the error adjustments = error* self.dφ(Y) # adjusted weights self.w += lr* dot(adjustments, x.T) print('Trained weights: ', self.w) #%% I shall give a problem def think(self, inputs): return self.φ( dot(self.w, inputs) ) #%% Main file if __name__ == '__main__': #%% Train the neuron first # 3 rows means 3 input types i.e. 3 xi training_inputs = array([[0, 1, 1, 0], [0, 1, 0, 1], [1, 1, 1, 1] ]) # each output correspondces to input 1 row training_outputs = array([ [0, 1, 1, 0] ]) # object created NN = Neural_Network(training_inputs, training_outputs, 0.1, 10000) #%% Now guess the output Guess_Input = array([ [0], [0], [1] ]) print('Guessed output is...') print( NN.think(Guess_Input))
#! /usr/bin/python # -*- coding: utf-8 -*- import numpy as np data = np.array([[5., 7., 12.], [6., 5., 10.], [3., 4., 8.], [2., 4., 6.]]) s_mean = np.zeros(data.shape) for i in range(data.shape[1]): s_mean[:, i] = data[:, i].mean() print("水準平均 " + str(s_mean)) kouka = s_mean - np.ones(data.shape) * data.mean() print("水準間偏差(因子の効果) := 水準平均 - 全体平均 " + str(kouka)) Q1 = (kouka * kouka).sum() print("水準間変動(効果の偏差平方和(SS)) " + str(Q1)) f1 = data.shape[1] - 1 print("自由度 " + str(f1)) V1 = Q1 / f1 print("水準間偏差(効果)の平均平方(MS)(不変分散) " + str(V1)) error = data - s_mean print("水準内偏差(統計誤差) " + str(error)) Q2 = (error * error).sum() print("誤差の偏差平方和(SS) " + str(Q2)) f2 = (data.shape[0] - 1) * data.shape[1] print("自由度(DF) " + str(f2)) V2 = Q2 / f2 print("水準内偏差(誤差)の平均平方(MS)(不変分散) " + str(V2)) F = V1 / V2 print("分散比(F値) " + str(F))
import asyncio import sys async def on_recv(reader, writer, name, loop): i = 0 while True: data = await reader.read(100) if data == b'stop': break data = data.decode() print(f'{name}-{i}: {data}') await asyncio.sleep(1.0) resp = f'{name}-{i}-{data}' writer.write(resp.encode()) await writer.drain() i += 1 writer.close() loop.stop() async def on_connect(name: str, loop): path = "/tmp/iiss.sock" reader, writer = await asyncio.open_unix_connection(path, loop=loop) loop.create_task(on_recv(reader, writer, name, loop=loop)) def main(): if len(sys.argv) == 0: return print(f'Usage: {sys.argv[0]} <name>') name = sys.argv[1] loop = asyncio.get_event_loop() try: loop.create_task(on_connect(name, loop)) loop.run_forever() except KeyboardInterrupt: pass finally: loop.close() if __name__ == '__main__': main()
# Question 1 # i=1 # while i<=1000: # if i%2==0: # print("nav") # if i%7==0: # print("gurukul") # if i%21==0: # print("navgurukul") # i=i+1 # Question 2 # Number_of_students=input("enter a name:") # Ek_student_ka_kharcha=int(input("enter a spending amount:")) # if Ek_student_ka_kharcha<=50000: # print("Hum budget ke andar hain") # else: # print(" hum budget ke bahar hain") # # Question 3 password=input("enter your sakht password:") if len(password)>6 or len(password)>16: if "$" in password: if 2 or 8 in password: if "A" or "Z" in password: print("it is Strong password") else: print("it is Weak password") # Question 4 # num1=int(input("enter a first numbers:")) # num2=int(input("enter a second numbers:")) # num3=int(input("enter a third numbers:")) # if num1>num2: # print(num1,"is highst") # elif num2>num1: # print(num2,"is highst") # elif num3>num1: # print(num3,"is highst") # elif num3>num2: # print(num3,"is highst") # elif num2>num3: # print(num2,"is highst") # elif num1>num3: # print(num1,"is highst") # else: # ("nothing") # Question 5 # Question 6 # string_list = ["Rishabh", "Rishabh", "Abhishek", "Rishabh", "Divyashish", "Divyashish"] # new_list=[ ] # index=0 # while index<len(string_list): # if string_list[index] not in new_list: # new_list.append(string_list[index]) # index=index+1 # print(new_list) # Question 7 # list1 = [1, 342, 75, 23, 98] # list2 = [75, 23, 98, 12, 78, 10, 1] # new_list=[ ] # index=0 # while index<len(list1): # if list1[index] in list2: # new_list.append(list1[index]) # index=index+1 # print(new_list) # Question 8 # list1 = [1, 5, 10, 12, 16, 20] # list2 = [1, 2, 10, 13, 16] # list3=[ ] # index=0 # while index<len(list1): # list2.append(list1[index]) # index=index+1 # print(list2) # j=0 # while j<len(list2): # if list2[j] not in list3: # list3.append(list2[j]) # j=j+1 # print(list3) # # Question 9 # # def is_harshad_number(num): # # numbers=(input("enter a number:")) # # x=numbers.split() # print(x) # Question 10 # numbers= [[45, 21, 42, 63], [12, 42, 42, 53], [42, 90, 78, 13], [94, 89, 78, 76], [87, 55, 98, 99]] # index=0 # while index<len(numbers): # print(max(numbers[index])) # index=index+1 # # numbers= [[45, 21, 42, 63], [12, 42, 42, 53], [42, 90, 78, 13], [94, 89, 78, 76], [87, 55, 98, 99]] # index=0 # maxi=[] # while index<len(numbers): # j=0 # maximum=0 # while j<len(numbers[index]): # if numbers[index][j]>maximum: # maximum = numbers[index][j] # j=j+1 # maxi.append(maximum) # index=index+1 # print(maxi) # Question 11 # words = "navgurukul is great" # counter = 0 # while counter < len(words): # print (words[counter]) # counter=counter+1
################## #time_test #Author:@Rooobins #Date:2019-01-03 ################## import time a = "Sat Mar 28 22:24:24 2016" print(time.time()) print(time.localtime(time.time())) print(time.asctime(time.localtime(time.time()))) print(time.strftime("%Y-%m-%d %H:%M:%S",time.localtime())) print(time.strftime("%a %b %d %H:%M:%S",time.localtime())) print(time.strptime(a,"%a %b %d %H:%M:%S %Y")) print(time.mktime(time.strptime(a,"%a %b %d %H:%M:%S %Y")))
class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None def com_bv(node): #print node.val if node.left is None and node.right is None: node.bv=0 elif node.left is None and node.right is not None: node.bv=com_bv(node.right)+1 elif node.left is not None and node.right is None: node.bv=com_bv(node.left)+1 else: left_n=com_bv(node.left) right_n=com_bv(node.right) node.bv=left_n+1 if left_n>right_n else right_n+1 return node.bv p1=TreeNode(1) p2=TreeNode(2) p3=TreeNode(3) p4=TreeNode(4) p5=TreeNode(5) p6=TreeNode(6) p7=TreeNode(7) p8=TreeNode(8) p9=TreeNode(9) p5.left=p2 p5.right=p7 p2.left=p1 p2.right=p4 p4.left=p3 p7.left=p6 p7.right=p9 p9.left=p8 stack=[] r_node=p5 a=com_bv(p5) while r_node is not None or stack: print str(r_node.val)+' '+str(r_node.bv) if r_node.right is not None: stack.append(r_node.right) r_node=r_node.left if r_node is None and stack: r_node=stack.pop() a=com_bv(p5)
salário = float(input('Digite o valor do salário: R$')) if salário <= 1250: salário *= 1.15 else: salário *= 1.10 print('O salário inicial será aumentado para R${:.2f}'.format(salário))
class Solution(object): def threeSum(self, nums): result = [] nums.sort() #중복제거 간소화 하기 위해 정렬 for i in range(len(nums)-2): #중복 일 경우 건너 뜀 if i > 0 and nums[i] == nums[i - 1]: continue left, right = i + 1, len(nums) - 1 while left < right: sum = nums[i] + nums[left] + nums[right] if sum < 0: left += 1 elif sum > 0: right -= 1 else: result.append([nums[i], nums[left], nums[right]]) #정답에 중복이 들어가면 X => 중복처리 while left < right and nums[left] == nums[left + 1]: left += 1 while left < right and nums[right] == nums[right - 1]: right -= 1 #정답일 경우 투 포인터 이동 left += 1 right -= 1 return result
from sklearn import datasets, neighbors import numpy as np # Load iris data from 'datasets module' iris = datasets.load_iris() # Get data-records and record-labels in arrays X and Y X = iris.data y = iris.target # Create an instance of KNeighborsClassifier and then fit training data clf = neighbors.KNeighborsClassifier() clf.fit(X, y) # Make class predictions for all observations in X Z = clf.predict(X) # Compare predicted class labels with actual class label accuracy = clf.score(X, y) print("Predicted model accuracy: "+ str(accuracy)) # Add a row of predicted classes to y-array for ease of comparison A = np.vstack([y, Z]) print(A)
s = input() dic = [] i0 = 0 st = False for i in range(len(s)): if s[i].islower(): continue if st: dic.append(s[i0 : i + 1]) st = False else: i0 = i st = True dic = [w.lower() for w in dic] dic.sort() for w in dic: w_ls = list(w) w_ls[0] = w_ls[0].upper() w_ls[len(w_ls) - 1] = w_ls[len(w_ls) - 1].upper() print("".join(w_ls), end="") print()
even_message = "an even number: " odd_message = "an odd number: " numbers = range(1, 10) finished = False for i in numbers: print ("processing number " , i, ", finished: ", finished) if i % 2 == 0: print (even_message, i) else: print (odd_message, i) finished = True print ("all numbers processed, finished: ", finished)
#!/usr/bin/env python3 from librip.gens import gen_random from librip.iterators import Unique data1 = [1, 1, 1, 1, 1, 2, 2, 2, 2, 2] data2 = gen_random(1, 3, 10) data3 = gen_random(1,9,15) data = ['a', 'A', 'b', 'B'] # Реализация задания 2 for i in Unique(data1): print(i, end=', ') print() #for i in data2: # print(i, end=', ') #print() for i in Unique(data2): #print('a') print(i, end = ', ') print() for i in Unique(data3): #print('a') print(i, end = ', ') print() for i in Unique(data): print(i, end=', ') print() for i in Unique(data, ignore_case=True): print(i, end=', ')
from person import Pessoa class Medico(Pessoa): __crm: str = '' __salario: int = 0 __especialidades: [str] = [] def __init__( self, nome: str, rg: str, cpf: str, crm: str, telefone: str, salario: int, especialidades: [str] ): super().__init__(nome, rg, cpf, telefone) self.__crm = crm self.__salario = salario self.__especialidades = especialidades def get_crm(self) -> str: return self.__crm def get_especialidade_principal(self) -> str: if (len(self.__especialidades) > 0): return self.__especialidades[0] else: return '' def get_nome(self) -> str: return super().get_nome() def get_salario(self) -> int: return self.__salario def get_todas_especialidades(self) -> [str]: return self.__especialidades def set_nova_especialidade(self, especialidade: str): self.__especialidades.append(especialidade) def set_salario(self, valor: int) -> None: self.__salario = valor def edit_crm(self, crm: str) -> None: self.__crm = crm def substituir_especialidades(self, especialidades: [str]): self.__especialidades = especialidades def remover_especialidade(self, especialidade: str) -> None: if especialidade in self.__especialidades: self.__especialidades.remove(especialidade)
v= raw_input().rstrip() evenB = oddB = '' for l, m in enumerate(v): if l & 1 == 0: evenB += m else: oddB += m print(evenB + " " + oddB)
# write a programm to print the multiplication table of the number entered by the user. number=int(input("enter the number")) i=1 while i<=10: print(i*number) i=i+1 # ask the user to enter 10 number using only one input statement and add them to the list list=[] for name in range(10): number=input("enter the number:") list.append(number) print(list) else: print("that's all") # from a list of numbers make a new list containing only the even numbers. x=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19] print("the value of x",x) list=[] for i in x: if i%2==0: list.append(i) print("even numbers are:",list) # from a list separate the integer,string and floats elements into three different lists. list=[1,"egg",2.50,5,"fish",3.9,6,"hen",6.9] print("list:",list) integer=[] string_list=[] float_value=[] for i in list: if type(i)==str: string_list.append(i) if type(i)==int: integer.append(i) if type(i)==float: float_value.append(i) print(integer) print(string_list) print(float_value) # from a list ask the user the number he wants to remove from the list and then print the list. list=[1,2,3,4,5,6,7,8,9,10] print("list is",list) n=int(input("enter the number want to remove from list")) list.remove(n) print("our new list",list) # make a calculator a=int(input("enter the number")) b=int(input("enter the number")) ch=input("a-Addition\n s-subtract\n m-multiplication\n d-division\n Q-quit") while ch!='q': if ch=='a': print("the sum of two number is",a+b) if ch=='s': print("the subtract of two number is",a-b) if ch=='m': print("the multiplication of two number is",a*b) if ch=='d': print("the division of two number is",a/b) if ch=='Q': print("quit") ch=input("enter choice again\n a-Addition\n s-subtract\n m-multiplay\n d-division\n Q-quit")
################### ## Variable Domains ################### domain = (1,2,3,4) ###################################################### ## Definition of a state (i.e., what the variables are ###################################################### start_state = [ None,1 ,None,3 , 4 ,None,None,2 , None,2 ,None,None, 3 ,None,2 ,1 ] def display_solution (state): print ("[{},{},{},{},".format(state[0],state[1],state[2],state[3])) print (" {},{},{},{},".format(state[4],state[5],state[6],state[7])) print (" {},{},{},{},".format(state[8],state[9],state[10],state[11])) print (" {},{},{},{}]".format(state[12],state[13],state[14],state[15])) ########################################## ## Functions related to the problem domain ########################################## def is_goal(state): if 0 in state: return False if not satisfy_constraints(state): return False return True ########################################## ## Constraints ########################################## # If either is None (unassigned), or the two are not the same def check_constraint_1 (x, y): if x!=y: return True else: return False def satisfy_constraints(state): for i in range(16): j=i%4 h=i//4 if state[i]!= 0: for z in range(4): if (4*h+z == i): z+=1 elif (state[i] == state[4*h+z]): return False for g in range(4): if (4*g+j == i): g+=1 elif ( state[i] == state[4*g+j]): return False return True ################## ## Search Function ################## def find_children(state): if 0 in state: children=[] none_idx = state.index(0) for value in domain: child = state.copy() child[none_idx] = value children.append(child) return children else: return 0 def csp_search(start_state): to_visit = [] next_state = start_state end = False while not end: if is_goal(next_state): display_solution (next_state) print("Solution Found!") end = True else: for child_state in find_children(next_state): if satisfy_constraints(child_state): to_visit.append(child_state) if to_visit: next_state=to_visit.pop() else: print("Failed to find a goal state") end=True ################## ## Main ################## x=[] for i in range(1, 5): a = input("Enter {} row (enter 0 for space): ".format(i)) x += a.split( ) x= list(map(int, x)) csp_search(x) input()
import random print(" I will flip a coin 1000 times. Guess how many times it will comp up heads. (Press Enter to begin") input() flips = 0 # a counter variable to keep track of how many flips has been made heads = 0 # another counter variable to keep track of how many heads pop from the while loop in the if statement. while flips < 1000: # if the flip is less then a 1000 cycles when true it recycles if false the program continues to line 20 if random.randint(0,1) == 1: # two options for 0 = tail 1 = heads heads += 1 # if line 7 is true where random = 1 it will go to line 8 where heads = heads + 1 line 5 get updated flips += 1 # regardless of line 7 is true or false the counter for flips is still added to line 4 if flips == 900: #once the flip count reach 900 the program will print line 12 print(" 900 flips and there have been {h} heads.".format(h = heads)) if flips == 100: print(" 100 flips and there have been {h} heads".format(h = heads)) if flips == 500: print(" 500 flips your halfway there and there have been {h} heads".format(h = heads)) print() print("Out of 1000 tosses, heads came up {h} heads times.".format(h = heads)) print("Where you close?")
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.11.0 # kernelspec: # display_name: drlnd # language: python # name: drlnd # --- # # Navigation # # --- # # In this notebook, you will learn how to use the Unity ML-Agents environment for the first project of the [Deep Reinforcement Learning Nanodegree](https://www.udacity.com/course/deep-reinforcement-learning-nanodegree--nd893). # # ### 1. Start the Environment # # We begin by importing some necessary packages. If the code cell below returns an error, please revisit the project instructions to double-check that you have installed [Unity ML-Agents](https://github.com/Unity-Technologies/ml-agents/blob/master/docs/Installation.md) and [NumPy](http://www.numpy.org/). from unityagents import UnityEnvironment import numpy as np import sys # Next, we will start the environment! **_Before running the code cell below_**, change the `file_name` parameter to match the location of the Unity environment that you downloaded. # # - **Mac**: `"path/to/Banana.app"` # - **Windows** (x86): `"path/to/Banana_Windows_x86/Banana.exe"` # - **Windows** (x86_64): `"path/to/Banana_Windows_x86_64/Banana.exe"` # - **Linux** (x86): `"path/to/Banana_Linux/Banana.x86"` # - **Linux** (x86_64): `"path/to/Banana_Linux/Banana.x86_64"` # - **Linux** (x86, headless): `"path/to/Banana_Linux_NoVis/Banana.x86"` # - **Linux** (x86_64, headless): `"path/to/Banana_Linux_NoVis/Banana.x86_64"` # # For instance, if you are using a Mac, then you downloaded `Banana.app`. If this file is in the same folder as the notebook, then the line below should appear as follows: # ``` # env = UnityEnvironment(file_name="Banana.app") # ``` env = UnityEnvironment(file_name="Banana.app") # Environments contain **_brains_** which are responsible for deciding the actions of their associated agents. Here we check for the first brain available, and set it as the default brain we will be controlling from Python. # get the default brain brain_name = env.brain_names[0] brain = env.brains[brain_name] # ### 2. Examine the State and Action Spaces # # The simulation contains a single agent that navigates a large environment. At each time step, it has four actions at its disposal: # - `0` - walk forward # - `1` - walk backward # - `2` - turn left # - `3` - turn right # # The state space has `37` dimensions and contains the agent's velocity, along with ray-based perception of objects around agent's forward direction. A reward of `+1` is provided for collecting a yellow banana, and a reward of `-1` is provided for collecting a blue banana. # # Run the code cell below to print some information about the environment. # + # reset the environment env_info = env.reset(train_mode=True)[brain_name] # number of agents in the environment print('Number of agents:', len(env_info.agents)) # number of actions action_size = brain.vector_action_space_size print('Number of actions:', action_size) # examine the state space state = env_info.vector_observations[0] print('States look like:', state) state_size = len(state) print('States have length:', state_size) # - # ### 4. It's Your Turn! # # Now it's your turn to train your own agent to solve the environment! When training the environment, set `train_mode=True`, so that the line for resetting the environment looks like the following: # ```python # env_info = env.reset(train_mode=True)[brain_name] # ``` from src.dqn_agent import Agent agent = Agent(state_size, action_size, 1) def monitor(env, agent, n_episodes=1000): """Run the agent and monitor its performance""" scores = [] best_score = -np.inf for episode in range(n_episodes): env_info = env.reset(train_mode=True)[brain_name] state = env_info.vector_observations[0] score = 0 while True: action = agent.act(state, 1/(episode+1)) env_info = env.step(action)[brain_name] next_state = env_info.vector_observations[0] reward = env_info.rewards[0] done = env_info.local_done[0] agent.step(state, action, reward, next_state, done) score += reward state = next_state if done: scores.append(score) break if np.mean(scores[-100:]) > best_score: best_score = np.mean(scores[-100:]) print("\rEpisode {} || Best average reward {}".format(episode, best_score), end="") sys.stdout.flush() if (episode+1) % 50 == 0: print("\rEpisode: {} Mean score: {} ".format(episode+1, np.mean(scores[-50:]))) if np.mean(scores[-100:]) > 13: print("\rEnvironment solved in {} episodes! ".format(episode+1)) break return scores agent.load("checkpoints/") agent.set_mode("eval") score = monitor(env, agent, 1000) import seaborn as sns sns.lineplot(x=range(len(score)), y=np.array(score))
import sys #Recursive function that returns a generator with all combinations def get_all_splits(array): if len(array) > 1: for sub in get_all_splits(array[1:]): yield [' '.join([array[0],sub[0]])] + sub[1:] yield [array[0]] + sub else: yield array def get_max_font(wide, height, words): max_found = 1 for words in get_all_splits(words): j=1 length_words = [len(word) for word in words] #Let's find the max font size while max(length_words)*j <= wide and (len(words)*j) <= height: if j > max_found: max_found = j j+=1 return max_found def process_file(filename): file = open("output.txt","w") with open(filename, "r") as input: lines = input.read().split("\n") for i, line in enumerate(lines[1:]): size = [int(item) for item in line.split()[:2]] sentence = " ".join(line.split()[2:]) print("Case #{}: {}".format(i, get_max_font(size[0], size[1], sentence.split()))) file.write("Case #{}: {}".format(i, get_max_font(size[0], size[1], sentence.split()))+"\n") file.close() process_file(sys.argv[1])
def words(sentence): lib = {} count = 0 sentence_list = sentence.split() length = len(sentence_list) for word in sentence_list: for i in range(length): if sentence_list[i].isdigit() == True: if sentence_list[i] == word: count+=1 lib[int(sentence_list[i])] = count else: if sentence_list[i] == word: count+=1 lib[sentence_list[i]] = count count = 0 return lib words('This is a test')
#!/usr/bin/python # @BEGIN_OF_SOURCE_CODE # @SPOJ BISHOPS C++ "Simple Math" from sys import stdin while True: line = stdin.readline() if line == '': break; n = int(line) if n == 1: print 1 else: print 2*n-2 # @END_OF_SOURCE_CODE
import unittest from src.guest import Guest from src.room import Room from src.song import Song class TestGuest(unittest.TestCase): def setUp(self): self.guest = Guest("Katy", 20) def test_guest_has_name(self): self.assertEqual("Katy", self.guest.guest_name) def test_guest_has_cash(self): self.assertEqual(20, self.guest.cash) def test_guest_pays_entry_fee(self): entry_fee = Room("lounge", 8, 100, 5) self.guest.pay_entry_fee(entry_fee) self.assertEqual(15, self.guest.cash)
""" link: https://leetcode.com/problems/find-k-pairs-with-smallest-sums problem: 用 nums1, nums2 中元素组成元素对 (u,v), 其中 u ∈ nums1,v ∈ nums2,求所有元素对中和最小的前 k 对 solution: 小根堆。因为 (nums[i], nums[j]) < (nums[i], nums[j+1]),可以肯定前者未出堆时后者入堆也没有意义,在前者出堆再将后者入堆 保持堆大小为 n,而不需要 mn,时间复杂度(klogn) """ class Solution: def kSmallestPairs(self, nums1: List[int], nums2: List[int], k: int) -> List[List[int]]: class T: def __init__(self, a: int, b: int, i: int): self.a = a self.b = b self.i = i def __lt__(self, t): return self.a + self.b < t.a + t.b if not nums1 or not nums2: return [] n, m = len(nums1), len(nums2) h = [] for i in range(n): heapq.heappush(h, T(nums1[i], nums2[0], 0)) res = [] for i in range(k): if not h: break t = heapq.heappop(h) res.append([t.a, t.b]) if t.i + 1 < m: heapq.heappush(h, T(t.a, nums2[t.i + 1], t.i + 1)) return res
# ch2_01_numeric.py # print("숫자형: 정수") a = 123 a = -178 a = 0 print("숫자형: 실수") a = 1.2 a = -3.48 a = 4.24e10 a = 4.24e-10 print("숫자형: 8진수와 16진수") a = 0o177 a a = 0x8FF a a = 0xABC a print("숫자형: 연산자와 연산") a = 3 b = 4 a + b a * b a / b a ** b a % b a // b 14 // 3 14 % 3 """ Author: redwoods 파이썬 코드: ch2_01_numeric.py """
lists1 = [] n = 0 var_1 = int(input("Введите число: ")) var_lenth = int(len(str(var_1))) while n < var_lenth: var_01 = var_1 % 10 lists1.insert(n, var_01) var_1 = var_1 // 10 n += 1 print(max(lists1))
""" POO - Herança Múltipla É a possibilidade de uma classe herdar de múltiplas classes. Desse modo, a classe filha herda todos os atributos e métodos das super classes. OBS: A Herança Múltipla pode ser feita de duas maneiras: - Multiderivação Direta; - Multiderivação Indireta. # Exemplo de Multiderivação Direta class Base1(): pass class Base2(): pass class Base3(): pass class Multipladerivacao(Base1, Base2, Base3): # Note q a herança é dada diretamente na classe Multipladerivacao pass # Exemplo de Multipladerivação Indireta class Base1(): pass class Base2(Base1): pass class Base3(Base2): pass class Multipladerivacao(Base3): # Note q a classe Multipladerivacao herda de modo indiretamente as classe Base2 e Base 1 pass # OBS: N importa se a classe herdar diretamente ou n outra classe, a mesma herdará todos os atributos e métodos das super classes. """ # EX de Herança Múltipla class Animal: def __init__(self, nome): self.__nome = nome @property def nome(self): return self.__nome def cumprimentar(self): return f'Olá. Meu nome é {self.nome}.' class Terrestre(Animal): def __init__(self, nome): super().__init__(nome) def cumprimentar(self): return f'Olá. Meu nome é {self.nome} da Terra.' def andar(self): return f'{self.nome} está andando.' class Aquatico(Animal): def __init__(self, nome): super().__init__(nome) def cumprimentar(self): return f'Olá. Meu nome é {self.nome} do mar.' def nadar(self): return f'{self.nome} está nadando.' class TerestreAquatico(Aquatico, Terrestre): # Retornará: "Olá. Meu nome é pinguim do mar.". Isso pq a classe Aquatico foi chamada antes da Terrestre. def __init__(self, nome): super().__init__(nome) tatu = Terrestre('Tatu') print(tatu.cumprimentar()) print(tatu.andar()) print() tubarao = Aquatico('Tubarão') print(tubarao.cumprimentar()) print(tubarao.nadar()) print() pinguim = TerestreAquatico('Pinguim') print(pinguim.cumprimentar()) # Aparece pinguim do mar e não pinguim da terra. Isso pq a primeira classe está primeiro à esquerda na chamada de herança. print(pinguim.andar()) print(pinguim.nadar()) print() # Saber se um objeto é uma instância de uma classe print(f'Pinguim é instância de Terrestre? : {isinstance(pinguim, Terrestre)}') # True print(f'Tatu é instância de Aquatico? : {isinstance(tatu, Aquatico)}') # False print(f'Tubarão é instância de objeto? : {isinstance(tubarao, object)}') # True (todos as classes são instâncias de object).
class AhoNode: def __init__(self): self.goto = {} self.out = [] self.fail = None def aho_create_forest(patterns): root = AhoNode() for path in patterns: node = root for symbol in path: node = node.goto.setdefault(symbol, AhoNode()) node.out.append(path) return root def aho_create_statemachine(patterns): root = aho_create_forest(patterns) queue = [] for node in root.goto.values(): queue.append(node) node.fail = root while len(queue) > 0: rnode = queue.pop(0) for key, unode in rnode.goto.items(): queue.append(unode) fnode = rnode.fail while fnode != None and not (key in fnode.goto): fnode = fnode.fail unode.fail = fnode.goto[key] if fnode else root unode.out += unode.fail.out return root def aho_find_all(s, root, callback): node = root for i in range(len(s)): while node != None and not (s[i] in node.goto): node = node.fail if node == None: node = root continue node = node.goto[s[i]] for pattern in node.out: callback(i - len(pattern) + 1, pattern) ############################ # Demonstration of work def on_occurence(pos, patterns): print("At pos: " + str(pos) + " found pattern: " + str(patterns) ) # patterns = ['a', 'ab', 'abc', 'bc', 'c', 'cba'] patterns = ['an', 'ant', 'cant', 'deca', 'decant', 'plant'] s = "ant" print("Input:", s) root = aho_create_statemachine(patterns) aho_find_all(s, root, on_occurence) # TESTE: ['an', 'ant', 'cant', 'deca', 'decant', 'plant'] # [ 1 , 2 , 3, , - , 4 , - ] # https://en.wikipedia.org/wiki/Trie # https://www.geeksforgeeks.org/aho-corasick-algorithm-pattern-searching/ # Para aplicar: ##### O aho-corasick deve ser aplicado sobre o proprio dicionário # Input: decant # At pos: 0 found pattern: deca # At pos: 3 found pattern: an # At pos: 0 found pattern: decant # At pos: 2 found pattern: cant # At pos: 3 found pattern: ant # Se você ordenar pelo patters, se cada elemento perte
# -*- coding: utf-8 -*- import appex import unicodedata import clipboard def erase_dakuten(char: chr) -> chr: myDict = { 'が': 'か', 'ぎ': 'き', 'ぐ': 'く', 'げ': 'け', 'ご': 'こ', 'ざ': 'さ', 'じ': 'し', 'ず': 'す', 'ぜ': 'せ', 'ぞ': 'そ', 'だ': 'た', 'ぢ': 'ち', 'づ': 'つ', 'で': 'て', 'ど': 'と', 'ば': 'は', 'び': 'ひ', 'ぶ': 'ふ', 'べ': 'へ', 'ぼ': 'ほ', 'ガ': 'カ', 'ギ': 'キ', 'グ': 'ク', 'ゲ': 'ケ', 'ゴ': 'コ', 'ザ': 'サ', 'ジ': 'シ', 'ズ': 'ス', 'ゼ': 'セ', 'ゾ': 'ソ', 'ダ': 'タ', 'ヂ': 'チ', 'ヅ': 'ツ', 'デ': 'テ', 'ド': 'ト', 'バ': 'ハ', 'ビ': 'ヒ', 'ブ': 'フ', 'ベ': 'ヘ', 'ボ': 'ホ', } if char in myDict.keys(): return myDict[char] else: return char def cnv_mr_fujiwara(str: str) -> str: cnvStr = '' for char in str: cnvStr += erase_dakuten(char) if char not in ['、', '。', '!', '?', '!', '?', 'ぱ', 'ぴ', 'ぷ', 'ぺ', 'ぽ', 'っ', 'パ', 'ピ', 'プ', 'ペ', 'ポ', 'ッ']: cnvStr += '゛' return cnvStr if __name__ == "__main__": input = appex.get_text() chars = list(input) output = cnv_mr_fujiwara(chars) print(output) clipboard.set(output)
# Tram a = int(input()) inputs = [input() for i in range(a)] min_cap = 0 num = 0 for i in inputs: c = i.split() num += int(c[1]) - int(c[0]) if num > min_cap: min_cap = num print(min_cap)
#This python script automatically arranges the files in your folder #The files will be grouped according to their file type #The file type that can be grouped are audios, videos, images, and documents import os from pathlib import Path FILETYPE = { "AUDIO":['.m4a','.m4b','.mp3','.wav','.flac','.cda'], "DOCUMENTS": ['.pdf','.rtf','.txt','.odt','.ppt'], "VIDEOS": ['.mov','.avi','.mp4','.wmv','.flv','.ogv','.mkv','.m4v','.3gp'], "IMAGES": ['.jpg','.jpeg','.png'] } def SELECTFILETYPE(value): for file_format, extensions in FILETYPE.items():#This line is used to assign variables to the key and values in the dictionary for extension in extensions : if extension == value : return file_format return 'MISC' #This is for if the filetype and file extension is not added to the dictionary def ORGANIZEFILE(): for item in os.scandir():#scandir() calls the OS directory iteration system calls to get the names of the files in the given path if item.is_dir():#is_dir is basically used to check if the given path is an existing directory or not continue filePath = Path(item) filetype = filePath.suffix.lower() directory = SELECTFILETYPE(filetype) directoryPath = Path(directory) if directoryPath.is_dir() != True: directoryPath.mkdir() filePath.rename(directoryPath.joinpath(filePath)) ORGANIZEFILE()
class Stack(): def __init__(self,items=[]): self.items = [] def push(self,data): i = self.items.append(data) return i def pop(self): i = self.items.pop() return i def is_empty(self): return len(self.items)==0 def peek(self): if not self.is_empty(): return self.items[-1] def get_stack(self): return self.items
# Create a program that prints the average of the values in the list: # a = [1, 2, 5, 10, 255, 3] a = [1, 2, 5, 10, 255, 3] sum = 0 for count in a: sum += count avg = sum / len(a) print avg
import numpy as np import math # Gaussian Elimination Partial Pivoting # Input GEPP(Ax = b) def GEPP(A, b): n = len(A) if b.size != n: raise ValueError("Invalid argument: incompatible sizes between A & b.", b.size, n) for k in xrange(n-1): maxindex = abs(A[k:,k]).argmax() + k if A[maxindex, k] == 0: raise ValueError("Matrix is singular.") if maxindex != k: A[[k,maxindex]] = A[[maxindex, k]] b[[k,maxindex]] = b[[maxindex, k]] for row in xrange(k+1, n): multiplier = A[row][k]/A[k][k] A[row][k] = multiplier for col in xrange(k + 1, n): A[row][col] = A[row][col] - multiplier*A[k][col] b[row] = b[row] - multiplier*b[k] #print A #print b x = np.zeros(n) k = n-1 x[k] = b[k]/A[k,k] while k >= 0: x[k] = (b[k] - np.dot(A[k,k+1:],x[k+1:]))/A[k,k] k = k-1 return x # Bilinear Interpolate # Input bilinear(Matrix Image, Position y, Position x) def bilinear(mat, posy, posx): if posx>mat.shape[1]-1 or posy>mat.shape[0]-1: return mat[math.floor(posy)][math.floor(posx)] f00 = mat[math.floor(posy),math.floor(posx)] f01 = mat[math.floor(posy),math.ceil(posx)] f10 = mat[math.ceil(posy),math.floor(posx)] f11 = mat[math.ceil(posy),math.ceil(posx)] a = f01 - f00 b = f10 - f00 c = f11 + f00 - f01 - f10 d = f00 posx = posx-math.floor(posx) posy = posy-math.floor(posy) return a*posx + b*posy + c*posx*posy + d def rms(F, G): h = F.shape[0] w = F.shape[1] s = 0.0 for i in range(0,h): for j in range(0,w): s +=(F[i,j]-G[i,j])**2 return math.sqrt(s/(h*w))
from room import Room from character import Character def battle(player, npc): fighting = True print("You are now battling " + npc.name) while fighting: user_input = input("What would you like to do?") if user_input == 'fight': npc.take_damage(player.attack) print(npc.name + " took " + str(player.attack) + ' damage') if npc.health <= 0: print("You have defeated " + npc.name) fighting = False def players_room(player, player_room): input_strings = [] player_room.things_in_room() while True: user_input = input("What would you like to do? ") user_input = user_input.lower() input_strings = user_input.split() if 'down' in input_strings and 'stairs' in input_strings or 'downstairs' in input_strings: return 2 def players_home(player, player_home): input_strings = [] player_home.things_in_room() while True: user_input = input() user_input = user_input.lower() input_strings = user_input.split() if 'talk' in input_strings and player_home.characters[0].name.lower() in input_strings: player_home.characters[0].speak() if 'fight' in input_strings and player_home.characters[0].name.lower() in input_strings: battle(player, player_home.characters[0]) user_input = 1 turns = 0 stranger = Character('Stranger') player = Character() player_room = Room("This is your room, you recognize all the things in it as being your own. There is a staircase in this room leading downstairs.") player_home = Room("This is your living room, there is a door leading outside and a staircase leading up stairs to your room.") player_home.add_character(stranger) while True: if user_input ==1: user_input = players_room(player, player_room) elif user_input ==2: user_input = players_home(player, player_home)
""" Testing for Hilbert transform methods that use wavelets at their core Using the math relation a^2 / (a^2 + x^2) (Lorentz/Cauchy) has an analytical Hilbert transform: x^2 / (a^2 + x^2) """ import numpy as np from numpy.testing import assert_array_almost_equal from hilbert.wavelet import hilbert_haar, _haar_matrix import pytest def test_haar(): # Not power-of-2 n = np.linspace(-100, 100, 1000) x = 2/(2**2 + n**2) hilb_x = hilbert_haar(x) hilb_x_analytical = n/(2**2 + n**2) assert_array_almost_equal(hilb_x_analytical, hilb_x, decimal=1) # Power-of-2 n = np.linspace(-100, 100, 1024) x = 2/(2**2 + n**2) hilb_x = hilbert_haar(x) hilb_x_analytical = n/(2**2 + n**2) assert_array_almost_equal(hilb_x_analytical, hilb_x, decimal=1) # 2D version x2 = np.vstack((x, x/2)) hilb_x = hilbert_haar(x2) hilb_x_analytical = np.vstack((n/(2**2 + n**2), 0.5*n/(2**2 + n**2))) assert_array_almost_equal(hilb_x_analytical, hilb_x, decimal=1) def test_haar_errors(): n = np.linspace(-100, 100, 1000) x = 2/(2**2 + n**2) # Wrong axis with pytest.raises(NotImplementedError): _ = hilbert_haar(x, axis=0) # > 2 dimensions with pytest.raises(ValueError): _ = hilbert_haar(np.random.randn(3,3,3)) def test_haar_matrix(): hm, hilb_hm = _haar_matrix(4) assert hm.shape == (4,4) assert hilb_hm.shape == (4,4) # Wrong dimensionsal size with pytest.raises(ValueError): _haar_matrix(3)
import paho.mqtt.client as mqtt import sys import json local_broker = "broker" # broker is host name local_port = 1883 # standard mqtt port local_topic = "signs" # topic is image with open("keys.json") as json_file: keys = json.load(json_file) # dictionary of signs signs = { "30": { "label": "30_kph", "speed":30 }, "50": { "label": "50_kph", "speed":50 }, "60": { "label": "60_kph", "speed": 60 }, "70": { "label": "70_kph", "speed": 70 }, "80": { "label": "80_kph", "speed": 80 }, "100": { "label": "100_kph", "speed": 100 }, "120": { "label": "120_kph", "speed": 120 }, "Deer": { "label": "Deer", "speed": 0 }, "Stop": { "label": "Stop", "speed": 0 }, "Yield": { "label": "Yield", "speed": 0 } } car_status = { 1: "staying the same speed", 2: "speeding up", 3: "slowing down", 4: "stopping" } class Car: """ class the simulates are self driving car """ def __init__(self): """ initiation class for self driving car sets speed to 0 mph and status as staying the same speed """ self.speed = 0 self.status = 1 return None def new_status(self, input): """ setter that allows for the self driving car to change state based on inputs :param input: integer from mqtt :return: None """ print("The sign seen is ", signs[input]["label"]) new_speed = signs[input]["speed"] if new_speed < self.speed: print("slowing down") self.status = 3 elif new_speed == self.speed: print("staying the same speed") self.status = 1 elif new_speed == 0: print("stopping the car") self.status = 4 else: print("speeding up") self.status = 2 self.speed = new_speed return None # end new status def on_connect_local(client, userdata, flags, rc): print("connected to local broker with rc: " + str(rc)) client.subscribe("signs") # subscribe to local topic return None # end function def on_message(client,userdata, msg): try: print("message received!") msg = msg.payload.decode("utf-8") # create message #print(msg) # confirm message receipt, turn off for production #print("The corresponding key is ") new_status = keys[msg] #print(new_status) car.new_status(new_status) # change car status except: print("Unexpected error:", sys.exc_info()[0]) car = Car() local_mqttclient = mqtt.Client() # instantiate local client local_mqttclient.on_connect = on_connect_local # connect using function call local_mqttclient.connect("broker", local_port, 240) # connect with inputs local_mqttclient.on_message = on_message # execute when message is received # go into a loop local_mqttclient.loop_forever()
from flask import Flask from flask.globals import request app = Flask(__name__) productList = [ {'id': 1, 'name': 'IPhone X', 'price': 10500000}, {'id': 2, 'name': 'IPhone 11', 'price': 11500000}, {'id': 3, 'name': 'IPhone 12', 'price': 12500000}, ] @app.route('/') def index(): html = '<ul>' for p in productList: pid = p['id'] html += f'<li><a href="/view-product-detail?id={pid}"> {p["name"]} </a></li>' html += '</ul>' return html #http://127.0.0.1:5000/view-product-detail?id=1 @app.route('/view-product-detail') def viewProduct(): productId = int(request.args.get('id', -1)) if productId < 1 or productId > len(productList): return 'Not found' p = productList[productId-1] return f''' <div> <p>Sản phẩm: <b> {p['name']} </b> </p> <p>Đơn giá : <b> {p['price']} đ </b> </p> </div> ''' app.run(debug=True) # hot reload
def get_primes(n): numbers = set(range(n, 1, -1)) primes = [] while numbers: p = numbers.pop() primes.append(p) numbers.difference_update(set(range(p*2, n+1, p))) return primes def pfactorize(a,primes,b,pfactors = []): if a==1: return pfactors if a==2: pfactors.append(2) return pfactors if a==3: pfactors.append(3) return pfactors for x in primes: if a%x==0: pfactors.append(x) prod = 1 for y in pfactors: prod *= y if not prod == b: pfactorize(b/prod,primes,b,pfactors) return pfactors primes = get_primes(1000000) count = 0 fourfact = [] for x in range(133000,1000000): numfactors = len(list(set(pfactorize(x,primes,x,[])))) if x in primes: continue if numfactors == 4: count += 1 else: count = 0 if count == 4: print x-3 break
# \r sirve para eliminar lo anterior escrito print("Hola \r mundo") # \n sirve para generar un salto de linea print("Hola \n mundo") # \t sirve para una tabulacion print("\tHola mundo") # \\ si queremos usar el caracter \ o algun caracter especial print("Hola \\ mundo")
class Participants(): ## Constants used for validation MINIMUM_NAME_LENGTH = 3 # Used to validate team member's name MAXIMUM_NAME_LENGTH = 10 MINIMUM_HOUSEHOLD_SIZE = 2 MAXIMUM_HOUSEHOLD_SIZE = 5 ## Constructor for the set containing participant's names. # @param the_participants a set containing the names # def __init__(self, the_participants) : self.participants = the_participants ## Return the participants' list. # @property def participants(self): return self._participants ## Sets the participants' list attribute. # @param name the participants set # @exception ValueError raised if: # - any of the names in the list are invalid # - the set is too long or too short @participants.setter def participants(self, the_participants) : try : self.valid_participants(the_participants) self._participants = the_participants except (ValueError,TypeError) as err : raise def __str__(self): participant_length = len(self.participants) i = 1 participant_string = "" for participant in self.participants : participant_string = participant_string + str(participant) if i < participant_length : participant_string = participant_string + ", " i = i + 1 return participant_string ## Check the set of participants. # Verifies that the set of partcipants is a valid length. # Verifies that each participants is valid. # # @param the_participants the set of participants to be validated # @return True if the set conforms to the validation conditions # and raise exception if it does not. # @staticmethod def valid_participants(the_participants) : # check that the the_participants is a set if not isinstance(the_participants, set) : raise TypeError("List of particpants is not a set.") try : Participants.is_valid_length(the_participants) Participants.is_valid_name_set(the_participants) except (ValueError,TypeError) as err : raise return True ## Check the name contains only alphanumeric characters and check that it is the right length. # # @param name the string to be validated # @return True if the string conforms to the validation conditions and # generate an exception if not. # @staticmethod def is_valid_name_set(name) : for i in name: if len(i) < Participants.MINIMUM_NAME_LENGTH \ or len(i) > Participants.MAXIMUM_NAME_LENGTH : raise ValueError(("Participant Name: {}, is not valid. It should be " + "more than {} characters long " + "and less than {} characters long.") .format(i, Participants.MINIMUM_NAME_LENGTH, Participants.MAXIMUM_NAME_LENGTH)) if not i.isalnum(): raise ValueError(("{}, is not valid. Names in the ParticipantList should be " + "alphanumeric.").format(i)) return True @staticmethod def is_valid_name_indiv(name) : if len(name) < Participants.MINIMUM_NAME_LENGTH \ or len(name) > Participants.MAXIMUM_NAME_LENGTH : raise ValueError(("Participant Name: {}, is not valid. It should be " + "more than {} characters long " + "and less than {} characters long.") .format(name, Participants.MINIMUM_NAME_LENGTH, Participants.MAXIMUM_NAME_LENGTH)) for i in name: if not i.isalnum(): raise ValueError(("{}, is not valid. Names in the ParticipantList should be " + "alphanumeric.").format(name)) return True ## Check the number of participants in the set is the right length. # # @return True if valid and generate an exception if not. # @staticmethod def is_valid_length(the_participants) : if len(the_participants) < Participants.MINIMUM_HOUSEHOLD_SIZE or \ len(the_participants) > Participants.MAXIMUM_HOUSEHOLD_SIZE : raise ValueError (("\n\t\tThe number of participants in the household must be" + " be more than {} and less than {}.") .format(Participants.MINIMUM_HOUSEHOLD_SIZE - 1, Participants.MAXIMUM_HOUSEHOLD_SIZE + 1)) # If we reached this point then the checks passed return True @staticmethod def is_valid_participant(the_participants) : for participant in the_participants : if not isinstance(participant, Participants) : raise TypeError ("The ParticipantList does not contain objects which are Participants.") # If we reached this point, the participants are valid. return True ## main method # # Contains some simple tests # def main(): print("Test 1: Create a valid participants list") try: names = set(["personA","personB","personC"]) p1 = Participants(names) print("\n\tVALID: ", p1) except Exception as err: print("\tERROR: ", err) print("\nTest 2: Create a set of participants with the wrong data type: list") try: names = ["personA","personB","personC"] p2 = Participants(names) print("\tVALID: ", p2) except Exception as err: print("\tERROR: ", err) print("\nTest 3: Create a set of participants which is too short") try: names = set(["personA"]) p2 = Participants(names) print("\tVALID: ", p2) except Exception as err: print("\tERROR: ", err) print("\nTest 4: Create a set of participants which is too long") try: names = set(["personA","personB","personC", "personD", "personE", "personF"]) p = Participants(names) print("\tVALID: ", p) except Exception as err: print("\tERROR: ", err) print("\nTest 5: Create a set of participants with invalid name, punctuation character") try: names = set(["***","personB","personC"]) p = Participants(names) print("\tVALID: ", p) except Exception as err: print("\tERROR: ", err) print("\nTest 6: Create a set of participants with name too long") try: names = set(["tooooooolongggggg","personB","personC"]) p = Participants(names) print("\tVALID: ", p) except Exception as err: print("\tERROR: ", err) if __name__ == "__main__": main()
wagons_n = int(input()) train = [0] * wagons_n while True: command = input() if command == 'End': break tokens = command.split(" ") instructions = tokens[0] if instructions == 'add': count = int(tokens[1]) train[-1] += count elif instructions == 'insert': index = int(tokens[1]) count = int(tokens[2]) train[index] += count elif instructions == 'leave': index = int(tokens[1]) count = int(tokens[2]) # Code sanitalization: if count <= train[index]: train[index] -= count print(train)
''' We do not need it in Python, but... ''' class Stack: def __init__(self): self._data = [] self._top = 0 def __len__(self): return self._top def __repr__(self): return f"<Stack: [{', '.join([str(i) for i in self._data[:self._top]])}]>" def push(self, item): self._top += 1 self._data += [item] def pop(self): if self._top == 0: raise Exception('Stack has 0 elements') self._top -= 1 last_item = self._data[-1] self._data = self._data[:-1] return last_item # # test stack = Stack() print("1)", stack) assert len(stack) == 0 stack.push(89) stack.push(False) stack.push("I am in stack :)") stack.push(120) assert len(stack) == 4 print("2)", stack) stack.pop() stack.pop() assert len(stack) == 2 print("3)", stack)
''' Created on 25 Nov 2020 @author: aki ''' """ import tkinter as tk root = tk.Tk() root.title("image demonstration") #iconbitmap only works with black and white images # root.iconbitmap("/home/aki/Downloads/icons/antenna.xbm") img = tk.PhotoImage(file='/home/aki/Downloads/icons/antenna.png') root.tk.call('wm', 'iconphoto', root._w, img) """ """ This is an old question, and there is lots of stuff written about it on the web, but all of it is either incorrect or incomplete, so having gotten it to work I thought it would be good to record my actual working code here. First, you'll need to create an icon and save it in two formats: Windows "ico" and Unix "xbm". 64 x 64 is a good size. XBM is a 1-bit format--pixels just on or off, so no colors, no grays. Linux implementations of tkinter only accept XBM even though every Linux desktop supports real icons, so you're just out of luck there. Also, the XBM spec is ambiguous about whether "on" bits represent black or white, so you may have to invert the XBM for some desktops. Gimp is good for creating these. Then to put the icon in your titlebar, use this code (Python 3): """ #""" import os, sys from tkinter import * from tkinter.ttk import * root = Tk() root.title("My Application") if "nt" == os.name: root.wm_iconbitmap(bitmap = "myicon.ico") else: root.wm_iconbitmap(bitmap = "/home/aki/Downloads/icons/antenna.xbm") root.mainloop() #""" """ #something else to try import sys, os from tkinter import * root = Tk() root.title("My Application") program_directory="/home/aki/Downloads/icons" root.iconphoto(True, PhotoImage(file=os.path.join(program_directory, "antenna.png"))) """ root.mainloop()
def fibTab(n): table=[0]*(n+1) table[1]=1 i,j,k=0,1,2 while (k<=n+1): if k==n+1: table[j]+=table[i] break table[j]+=table[i] table[k]+=table[i] i+=1;j+=1;k+=1 return table[n] print(fibTab(50)) # Time and space Complexity O(n)
"""DXF Ruler Generator. This module generates DXF files for laser cutting and engraving custom sized rulers, which can be easily manufactured at the nearest FabLab. Example ------- Generate a 7cm ruler: $ python -m dxf_ruler_generator 7 This will create a 'ruler_7cm.dxf' on the current working directory. """ import os.path from argparse import ArgumentParser import ezdxf parser = ArgumentParser(description="Generate rulers for digital fabrication.") parser.add_argument("length", metavar="L", type=int, help="an integer for the ruler's length, in centimeters.") parser.add_argument("width", metavar="W", type=int, nargs="?", default=30, help="an integer for the ruler's width, in milimeters.") parser.add_argument("tick_width", metavar="TW", type=float, nargs="?", default=.25, help="a float for the tick's width, in milimeters.") args = parser.parse_args() def run(): """Draw the ruler.""" dwg = ezdxf.new('R2010') dwg.layers.new(name='CUT', dxfattribs={'color': 7}) dwg.layers.new(name='SCAN', dxfattribs={'color': 5}) msp = dwg.modelspace() ruler_outline = [(0, 0), (10*(args.length+1), 0), (10*(args.length+1), args.width), (0, args.width), (0, 0)] msp.add_lwpolyline(ruler_outline, dxfattribs={'layer': 'CUT'}) for mm in range(10*args.length+1): x = mm + 5 - args.tick_width / 2 if mm == 0 or mm % 10 == 0: tick_height = args.width / 3 msp.add_text( str(mm//10), dxfattribs={'rotation': 90, 'height': 2, 'layer': 'SCAN'} ).set_pos((x-1, args.width-tick_height)) elif mm % 5 == 0: tick_height = args.width / 6 else: tick_height = args.width / 12 ruler_tick = [(x, args.width), (x, args.width-tick_height), (x+.25, args.width-tick_height), (x+.25, args.width), (x, args.width)] msp.add_lwpolyline(ruler_tick, dxfattribs={'layer': 'SCAN'}) filename = f'ruler_{args.length}cm.dxf' dwg.saveas(filename) print(os.path.abspath(filename), end='') if __name__ == "__main__": run()
class MyClass (object): # class MyClass and, by default, inherits from object pass class Person: def __init__(self, name, age): self.name = name self.age = age def __repr__(self): return 'Person: {} - Age: {}'.format(self.name, self.age) class PF(Person): def __init__(self, cpf, name, age): Person.__init__(self, name, age) self.cpf = cpf class PJ(Person): def __init__(self, cnpj, name, age): Person.__init__(self, name, age) self.cnpj = cnpj pf = PF('00000000000', 'Severo', 29) print(pf.name) print(pf.age) print(pf.cpf) print(pf) pj = PJ('0000000000000', 'Severo Ltda', 1) print(pj.name) print(pj.age) print(pj.cnpj) print(pj)
#!/usr/bin/env python import datetime import pandas as pd from tabulate import tabulate class TravelRoute: def __init__(self, destination, dangerous, urgency, dimension, weight): self.destination = destination self.dangerous = dangerous self.urgency = urgency self.dimension = float(dimension) self.weight = float(weight) def __str__(self): return str(self.charge) class Air(TravelRoute): def __init__(self, destination, dangerous, urgency, dimension, weight): super().__init__(destination, dangerous, urgency, dimension, weight) def charge(self): if self.dangerous == "unsafe": return 0 elif self.weight*10 > self.dimension*20: return float(self.weight*10) else: return float(self.dimension * 20) class Truck(TravelRoute): def __init__(self, destination, dangerous, urgency, dimension, weight): super().__init__(destination, dangerous, urgency, dimension, weight) def charge(self): if self.destination == 'overseas': return 0 elif self.urgency == 'urgent': return 45 else: return 25 class Boat(TravelRoute): def __init__(self, destination, dangerous, urgency, dimension, weight): super().__init__(destination, dangerous, urgency, dimension, weight) def charge(self): if self.destination == 'in-country': return 0 elif self.urgency == 'urgent': return 0 else: return 30 def urgent_check(delivery_date): future = datetime.datetime.today() + datetime.timedelta(days=3) if delivery_date > future: return "not urgent" else: return "urgent" def destination_check(): while True: dest = input("Is this package remaining in (c)ountry, or (o)verseas: ").lower() if dest == 'c': return 'in-country' elif dest == 'o': return 'overseas' else: print("Use 'c' or 'o'.") def danger_check(): while True: danger = input("Does the package contain anything dangerous (y/n): ").lower() if danger == 'n': return 'Safe' elif danger == 'y': return 'unsafe' else: print("Is it safe or unsafe? (y/n)") def next_customer(): next_c = input("Is there another customer: (y/n)").lower() if next_c == 'y': return True else: return False def delivery_options(destination, dangerous, urgency, dimension, weight): options = {} air_option = Air(destination, dangerous, urgency, dimension, weight) truck_option = Truck(destination, dangerous, urgency, dimension, weight) boat_option = Boat(destination, dangerous, urgency, dimension, weight) if air_option.charge() > 0.0: options['Air'] = air_option.charge() if truck_option.charge() > 0.0: options['Truck'] = truck_option.charge() if boat_option.charge() > 0.0: options['Boat'] = boat_option.charge() df2 = pd.DataFrame(list(options.items()), columns=['Option', 'Cost']) print(tabulate(df2, tablefmt='psql')) selection = 0 while selection == 0: try: delivery_choice = input("Choose the delivery method:") delivery_choice = int(delivery_choice) if delivery_choice < 0 or delivery_choice > df2.last_valid_index(): print("Please select a valid method of transport") else: selection = 1 except ValueError: print('Please enter a valid shipping option') df2_option = df2.at[delivery_choice, 'Option'] df2_cost = df2.at[delivery_choice, 'Cost'] return df2_option, df2_cost def print_customer(df): row = df.tail(1).transpose() print("Order ID:", df.last_valid_index()) print(tabulate(row, tablefmt='psql')) def get_name(): while True: try: name = input("Please enter customer name: ") if not name: raise ValueError("Please enter a valid name. Cannot be blank") else: break except ValueError as e: print(e) return name def get_description(): while True: try: description = input("General description of package: ") if not description: raise ValueError("Please enter a description. Cannot be blank") else: break except ValueError as e: print(e) return description def get_delivery_date(): day = 0 while day == 0: d_date = input("When do they want the package to arrive: yyyy/dd/mm ") try: d_date = datetime.datetime.strptime(d_date, '%Y/%m/%d') if d_date <= datetime.datetime.today(): print("Please enter a delivery date at least one day in advance.") else: day = 1 except ValueError: print("Incorrect date format, should be YYYY/MM/DD.") return d_date def get_dimensions(): print("Minimum dimension size is 0.1 meter.\n " "Anything smaller should be rounded up to 0.1.\n" "Minimum overall size is 0.5m") while True: try: length = float(input("L: ")) if not length: raise ValueError("Please enter a length.") elif length < 0.1: print("Please enter a dimension greater than 0.0999.") else: break except ValueError as e: print(e) while True: try: width = float(input("W: ")) if not width: raise ValueError("Please enter a width.") elif width < 0.1: print("Please enter a dimension greater than 0.0999.") else: break except ValueError as e: print(e) while True: try: height = float(input("H: ")) if not height: raise ValueError("Please enter a height.") elif height < 0.1: print("Please enter a dimension greater than 0.0999.") else: break except ValueError as e: print(e) if length*width*height < 0.5: dimension = 0.5 else: dimension = length*width*height return dimension def size_check(dimension): if dimension > 124.999: print("Sorry, but this package is too large to be shipped by our methods. Please reduce the size to less " "than 5x5x5") return False else: return True def get_weight(): while True: try: weight = float(input("How many kilograms does it weigh: ")) if not weight: raise ValueError("Please enter a weight. Cannot be blank") elif weight <= 0: print("Please enter a positive weight.") else: break except ValueError as e: print(e) return weight def weight_check(weight): if weight > 9.999: print("Sorry, but this package weighs too much. Please reduce the weight to under 10kg") return False else: return True def main(): customer = True while customer: customer_name = get_name() destination = destination_check() package_desc = get_description() dangerous = danger_check() delivery_date = get_delivery_date() urgency = urgent_check(delivery_date) weight = get_weight() weight_check(weight) dimension = get_dimensions() df = pd.read_csv('booking_quotes.csv', index_col=0) df.index.name = 'ID' df = df.reset_index(drop=True) new_row = {'Customer_Name': customer_name.title(), 'Destination': destination, 'Package_desc': package_desc, 'Dangerous': dangerous, 'Delivery_date': delivery_date.date(), 'Urgency': urgency, 'Weight': weight, 'Size': round(dimension,2), 'Shipping_option': '', 'Cost': ''} df = df.append(new_row, ignore_index=True) print_customer(df) d_option, d_cost = delivery_options(destination, dangerous, urgency, dimension, weight) df.at[df.last_valid_index(), 'Shipping_option'] = d_option df.at[df.last_valid_index(), 'Cost'] = d_cost df.to_csv('booking_quotes.csv', index=True) print_customer(df) customer = next_customer() if __name__ == "__main__": main()
import re from collections import Counter from aoc_utils import aoc_utils from tests import cases def find_all_coordinates(x1, y1, x2, y2, part_one=False): points = [] dx = x1 - x2 dy = y1 - y2 # Like 2,2 -> 2,1 if dx == 0: for y in range(min([y2, y1]), max([y2, y1]) + 1): points.append(str([x1, y])) # Like 0,9 -> 5,9 if dy == 0: for x in range(min([x2, x1]), max([x2, x1]) + 1): points.append(str([x, y1])) if part_one: return points # Like 1,1 -> 3,3 if dx < 0 and dy < 0: for i in range(abs(dx) + 1): points.append(str([x1 + i, y1 + i])) # Like 3,3 -> 1,1 if dx > 0 and dy > 0: for i in range(abs(dx) + 1): points.append(str([x1 - i, y1 - i])) # Like 9,7 -> 7,9 if dx > 0 and dy < 0: for i in range(abs(dx) + 1): points.append(str([x1 - i, y1 + i])) # Like 7,9 > 9,7 if dx < 0 and dy > 0: for i in range(abs(dx) + 1): points.append(str([x1 + i, y1 - i])) return points def horrizontal_points(x1, y1, x2, y2): points = [] if x1 - x2 == 0: for y in range(min([y2, y1]), max([y2, y1]) + 1): points.append(str([x1, y])) if y1 - y2 == 0: for x in range(min([x2, x1]), max([x2, x1]) + 1): points.append(str([x, y1])) return points def answer(problem_input, level, test=False): coordinates = [] for line in problem_input.splitlines(): coords = [int(i) for i in re.findall(r'(\d+)', line)] if level == 1: coordinates += find_all_coordinates(*coords, part_one=True) else: coordinates += find_all_coordinates(*coords) return len([k for k,v in Counter(coordinates).items() if v > 1]) aoc_utils.run(answer, cases)
End of preview. Expand in Data Studio
README.md exists but content is empty.
Downloads last month
43