blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
5106f81f58237ea7f4d845d8f60b39823a051c62
syuuhei-yama/python_01
/datetime_sample.py
994
3.765625
4
from datetime import datetime, timedelta,timezone, date import time my_date = datetime(2020,11,11,18,15,25) print(my_date, type(my_date)) now_datetime = datetime.now() utc_datetime = datetime.utcnow() print(now_datetime,utc_datetime) print(now_datetime.year, now_datetime.month,now_datetime.microsecond) #文字列から変換 timestr = '2020/12/12 16:40' dt = datetime.strptime(timestr, '%Y/%m/%d %H:%M') print(dt,type(dt)) #文字列へ変換 date_str = dt.strftime('%Y/%m/%d') print(date_str, type(date_str)) print(datetime.now() - timedelta(days=10)) my_date = datetime(2020,11,11,18,15,25) local_date = my_date.replace(tzinfo=timezone.utc).astimezone() print(my_date, local_date) #date => datetime date_obj = date.today() datetime_obj = datetime(date_obj.year,date_obj.month, date_obj.day) print(datetime_obj) datetime_obj = datetime.now() date_obj = datetime_obj.date() print(date_obj) #timeモジュール print(time.time()) for x in range(10): print(x) time.sleep(1)
fb930b03f42024b5b150fb545eb4829534465421
Hanniwell/Final-Project
/python/Player.py
4,615
3.53125
4
""" ------------------------------------------------------- [Program Description] ------------------------------------------------------- Author: Einstein Oyewole ID: 180517070 Email: oyew7070@mylaurier.ca __updated__ = "" ------------------------------------------------------- """ # Import import random from copy import deepcopy from tic_tac_toe import * from Utility import min_val, max_val from math import exp # Constants INITIAL_LR = 0.9 class Player: PLAYER_TYPE = "RL" exploration_rate = 0.3 learning_rate = 0.9 discount_factor = 0.8 def __init__(self, symbol): assert symbol in ["x", "y"], "Symbol has to be 'x' or 'y'" self.symbol = symbol self.previous_states = [] self.Q = {} # Q[s,a] = Q[s'] where s' = s after action a def nextAction(self, board): """ :rtype: list :type board: tic_tac_toe """ actions = board.get_action() if random.uniform(0, 1) < self.exploration_rate: """ Explore: select a random action """ action = random.choice(actions) else: """ Exploit: select the action with max value (future reward) """ values = [] for pos_action in actions: temp = deepcopy(board) index = temp.results(pos_action, self.symbol) index = str(index) value = 0 if self.Q.get(index) is None else self.Q.get(index) values.append(value) max_val = max(values) index = [i for i, x in enumerate(values) if x == max_val] board.best_actions = [actions[i] for i in index] # print([actions[i] for i in index]) # print(values) rand_i = random.choice(index) action = board.best_action = actions[rand_i] return action def rewards(self, board): """ At the end of the game we go back and reward the actions :type board: tic_tac_toe """ winner = board.utility() if (winner == 1 and self.symbol == "x") or (winner == -1 and self.symbol == "y"): self.propagate_reward(1) # reward 1 : win elif (winner == -1 and self.symbol == "x") or (winner == 1 and self.symbol == "y"): # reward -1 : loss self.propagate_reward(-1) else: self.propagate_reward(0) # reward 0 : tie def propagate_reward(self, reward): self.Q[self.previous_states[-1]] = reward # reward player: 1 for j in range(len(self.previous_states) - 2, -1, -1): i = self.previous_states[j] if self.Q.get(i) is None: self.Q[i] = 0 self.Q[i] = self.Q[i] + self.learning_rate * ( reward + self.discount_factor * (self.Q[self.previous_states[j + 1]]) - self.Q[i]) reward = self.Q[i] def exponential_decay(self, epoch): decay = 0.8 self.learning_rate = INITIAL_LR * exp(-decay / (epoch + 1)) class MinimaxPlayer: PLAYER_TYPE = "Minimax" def __init__(self, symbol): assert symbol in ["x", "y"], "Symbol has to be 'x' or 'y'" self.symbol = symbol def nextAction(self, board): if board.get_state() == [[None, None, None], [None, None, None], [None, None, None]]: action = [1,1] else: if self.symbol == "y": min_val(board, self.symbol) else: max_val(board, self.symbol) action = board.best_action return action def exponential_decay(self, epoch): pass class HumanPlayer: PLAYER_TYPE = "Human" def __init__(self, symbol): assert symbol in ["x", "y"], "Symbol has to be 'x' or 'y'" self.symbol = symbol def nextAction(self, board): print("You are ", self.symbol) while True: try: input_action_1 = int(input("Enter row:")) input_action_2 = int(input("Enter column:")) assert input_action_1 in [1, 2, 0] and input_action_2 in [1, 2, 0] assert [input_action_1, input_action_2] in board.get_action() break except: print("Input error has to be within 0 and 2 inclusive") action = [input_action_1, input_action_2] return action def exponential_decay(self, epoch): pass def move(player, board): action = player.nextAction(board) board.results(action, player.symbol)
1f6a4532ffdd302083c2a0a4cb14a077fe25cbae
HamzhSuilik/data-structures-and-algorithms
/python/challenges/tree_intersection/tree_intersection.py
1,171
3.671875
4
try: from tree import BinaryTree,TNode,Stack from hashtable import Hashtable except: from challenges.tree_intersection.tree import BinaryTree,TNode,Stack from challenges.tree_intersection.hashtable import Hashtable def tree_intersection(tree_1,tree_2=0): arr = [] hashtable = Hashtable() top = tree_1.preOrder().top while top : if not hashtable.contains(top.value) : hashtable.add(0,top.value) top = top.next top = tree_2.preOrder().top while top : if hashtable.contains(top.value) : arr.append(int(top.value)) top = top.next return arr if __name__ == "__main__": node1 = TNode(1) node1.left = TNode(2) node1.right = TNode(3) node1.right.left = TNode(5) node1.right.right = TNode(4) node1.left.right = TNode(6) node1.left.left = TNode(7) # 1 # | # -------- # | | # 2 3 # | | # ---- ----- # | | | | # 7 6 5 4 binary_tree = BinaryTree(node1) p = tree_intersection(binary_tree) print (p.get('5')) x =[3,1,2] y= [2,1,3] print(set(x) == set(y)) print('')
85b1fd9507fada4bf97c9641e9d69244a4341e96
rainvestige/pytorch_tutorials
/intro_to_pytorch.py
3,428
4.15625
4
# coding=utf-8 '''What is pytorch? It's a python-based scientific computing packages targeted at two sets of audiences: - A replacement for Numpy to use the power of GPUS - A deep learning research platform that provides maximum flexibility and speed ''' '''Tensors Tensors are similar to numpy's ndarrays, with the addition being that Tensors can also be used on a GPU to accelerate computing. ''' import torch # Construct a 5x3 matrix, uninitialized: x = torch.empty(5, 3) print(x) # Construct a randomly initialized matrx: x = torch.rand(5, 3) print(x) # Construct a matrix filled zeros and of dtype long: x = torch.zeros(5, 3, dtype=torch.long) print(x) # construct a tensor directly from data: x = torch.tensor([5.5, 3]) print(x) # create a tensor based on an existing tensor. These methods will reuse # properties of the input tensor, e.g.dtype, unless new values are # provided by user x = x.new_ones(5, 3, dtype=torch.double) # new_* methods take in sizes print(x) x = torch.randn_like(x, dtype=torch.float) # override dtype print(x) # result has the same size print(x.size()) # `torch.Size` is in fact a tuple, so it supports all tuple operations. '''Operations There are multiple syntaxes for operations. In the following example, we will take a look at the addition operation. ''' # Addition: syntax 1 y = torch.rand(5,3) print(x + y) # Addition: syntax 2 print(torch.add(x, y)) # Addition: providing an output tensor as argument result = torch.empty(5, 3) torch.add(x, y, out=result) print(result) # Addition: in-place # adds x to y '''NOTE Any operations that mutates a tensor in-place is post-fixed with an `_` For example: x.copy_(y), x.t_(), will chage x. ''' y.add_(x) print(y) # You can use standart NumPy-like indexing with all bells and whistles! print(x[:, 1]) # the second column of x tensor # Resizing: if you want to resize/reshape tensor, you can use `torch.view`: x = torch.randn(4, 4) y = x.view(16) z = x.view(-1, 8) # the size -1 is inferred from other dimensions(auto computed) print(x.size(), y.size(), z.size()) # If you have a one element tensor, use `.item` to get the value as a Python number x = torch.randn(1) print(x) print(x.item()) '''NumPy Bridge Converting a Torch Tensor to a NumPy array and vice versa is a breeze. The torch tensor and numpy array will share their underlying memory locations(if the Torch Tensor is on CPU), and changing one will change the other - All the tensors on the CPU except a Char Tensor support converting to NumPy and back ''' # converting a torch tensor to a numpy array a = torch.ones(5) print(a) b = a.numpy() print(b) a.add_(1) print(a) print(b) # converting numpy array to torch tensor import numpy as np a = np.ones(5) b = torch.from_numpy(a) np.add(a, 1, out=a) print(a) print(b) '''CUDA Tensors Tensors can be moved onto any device using the `.to` method. ''' # let us run this cell only if CUDA is available # we will use ``torch_device`` object to move tensors in and out of GPU if torch.cuda.is_available(): device = torch.device("cuda") # a CUDA device object y = torch.ones_like(x, device=device) # directly create a tensor on GPU x = x.to(device) # of just use strings ``.to("cuda")`` z = x + y print(z) print(z.to("cpu", torch.double)) # ``.to`` can also change dtype together!
4dbd2b0178d8e56d04c2d23399984ebdfab54ba6
Serhii999/Homework
/DZ5/avgmark.py
516
3.875
4
students = {"Karenov_S":[80,70,75, 60, 75], "Kalaychev_G":[80, 90, 80, 75, 85], "Drulev_D":[60, 50, 45, 70, 65], "Khamza_I":[75, 90, 75, 70, 85], "Gerasimenko_M":[70, 65, 80, 75, 60]} avg =[] for name, marks in students.items(): avg.append(sum(marks)/len(marks)) s =(sum(marks)/len(marks)) print(name,', ' "Average mark =", s) print() if len(avg)==5: print("Max average =", max(avg)) if len(avg)==5: print("Min average =", min(avg)) input()
1ded2100d8a70309310efdbbef7e29ff3095aeab
ChawinTan/algorithms-and-data-structures
/Dynamic_programming/unique_path_2.py
2,681
3.765625
4
#forward solution class Solution(object): def uniquePathsWithObstacles(self, obstacleGrid): """ :type obstacleGrid: List[List[int]] :rtype: int """ col, row = len(obstacleGrid[0]), len(obstacleGrid) if (len(obstacleGrid[0]) == 1 and obstacleGrid[0][0] == 1) or obstacleGrid[-1][-1] == 1: return 0 for i in range(row): for j in range(col): if obstacleGrid[i][j] == 1: obstacleGrid[i][j] = "x" for i in range(col): if obstacleGrid[0][i] == "x": break else: obstacleGrid[0][i] = 1 for i in range(row): if obstacleGrid[i][0] == "x": break else: obstacleGrid[i][0] = 1 for i in range(1, row): for j in range(1, col): if obstacleGrid[i][j] == "x": continue elif obstacleGrid[i][j-1] == "x" and obstacleGrid[i-1][j] != "x": obstacleGrid[i][j] = obstacleGrid[i-1][j] elif obstacleGrid[i-1][j] == "x" and obstacleGrid[i][j-1] != "x": obstacleGrid[i][j] = obstacleGrid[i][j-1] elif obstacleGrid[i-1][j] != "x" and obstacleGrid[i][j-1] != "x": obstacleGrid[i][j] = obstacleGrid[i-1][j] + obstacleGrid[i][j-1] return obstacleGrid[-1][-1] #backwards solution ''' This solution is more effecient since we know straight away which route is not possible as we traverse backwards ''' def uniquePathsWithObstacles(self, obstacleGrid): """ :type obstacleGrid: List[List[int]] :rtype: int """ # initialize memo array rows,cols = len(obstacleGrid), len(obstacleGrid[0]) memo = [[0] * cols for i in range(rows)] # go through each row, m-1 --> 0 for r in range(rows-1, -1, -1): # go through each col, n-1 --> 0 for c in range(cols-1, -1, -1): # if it's not an obstacle if obstacleGrid[r][c] == 0: # base case -> at the end if r == rows-1 and c == cols-1: memo[r][c] = 1 # can go down if r+1 < rows: memo[r][c] += memo[r+1][c] # can go right if c+1 < cols: memo[r][c] += memo[r][c+1] # solve original problem --> starting point = (0,0) return memo[0][0]
410c08cdecae9799af600b010a3e710a20837b59
SanmatiM/practice_problem_sets
/elesearch.py
184
3.90625
4
lst=[] strg=input("Enter the elements") lst=strg.split() search=input("Enter the element to be searched") for ele in lst: if ele==search: print("True") break else: print("False")
17670f05f2bfad3310c4af50859d500fc382c090
lakshyatyagi24/daily-coding-problems
/python/18.py
1,879
4.0625
4
# ------------------------- # Author: Tuan Nguyen # Date: 20190531 #!solutions/18.py # ------------------------- """ Given an array of integers and a number k, where 1 <= k <= length of the array, compute the maximum values of each subarray of length k. For example, given array = [10, 5, 2, 7, 8, 7] and k = 3, we should get: [10, 7, 8, 8], since: 10 = max(10, 5, 2) 7 = max(5, 2, 7) 8 = max(2, 7, 8) 8 = max(7, 8, 7) Do this in O(n) time and O(k) space. You can modify the input array in-place and you do not need to store the results. You can simply print them out as you compute them. """ # library import collections def slidingWindowMaximum(arr, k): # input: list of ints arr & window-sized int k # output: sliding window of size k maximum from arr # method: double-ended queue "deq" slidingWindowMax = [] # init returned list deq = collections.deque() # init double-ended queue to store index # 1st window for i in range(k): # remove indexes of smaller values in 1st window if the later index comes a bigger value while deq and (arr[i] > arr[deq[0]]): deq.pop() deq.append(i) # add current-element index into deq # rest for i in range(k, len(arr)): slidingWindowMax.append(arr[deq[0]]) # add max value of previous window, aka index 0 in deq, into output # remove all previous indexes not in current window while deq and (deq[0] <= i-k): deq.popleft() # remove all indexes of smaller values in current window while deq and (arr[i] > arr[deq[-1]]): deq.pop() deq.append(i) # add current-element index into deq slidingWindowMax.append(arr[deq[0]]) # add max value of last window into output return slidingWindowMax def slidingWindowMaximum_test(arr, k): print(arr, k, slidingWindowMaximum(arr, k)) if __name__ == '__main__': slidingWindowMaximum_test([10, 5, 2, 7, 8, 7], 3) # return [10, 7, 8, 8]
7af7b7675df0088f0f2501c5f40e30521dc9354a
eriklau/Mercedes-Car-Price-Prediction
/LinearModel.py
1,389
3.9375
4
import pandas as pd import matplotlib.pyplot as plt import predictor as data import numpy as np dataset = data.DataCleaner().process_data() X = dataset.iloc[:, 1].values dataset_result = data.DataCleaner().process_data() y = dataset.iloc[:, 0].values # Splitting the dataset into the Training set and Test set from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 1/3, random_state = 0) X_train = X_train.reshape(-1, 1) y_train = y_train.reshape(-1, 1) print(X_train) print(y_train) # Training the Simple Linear Regression model on the Training set from sklearn.linear_model import LinearRegression regressor = LinearRegression() regressor.fit(X_train, y_train) # Predicting the Test set results y_pred = regressor.predict(X_test.reshape(-1, 1)[:200]) # Visualising the Training set results plt.scatter(X_train[:200], y_train[:200], color = 'red') plt.plot(X_train, regressor.predict(X_train), color = 'blue') plt.title('Miles Per Gallon vs Price In Euros') plt.xlabel('Miles Per Gallon (MPG)') plt.ylabel('Price') plt.show() # Visualising the Test set results plt.scatter(X_test[:200], y_test[:200], color = 'red') plt.plot(X_train, regressor .predict(X_train), color = 'blue') plt.title('Miles Per Gallon vs Price In Euros') plt.xlabel('Miles Per Gallon (MPG)') plt.ylabel('Price') plt.show()
cf12876fca1e11bebde977057ab2f204c2a78c96
python15/homework
/4/sunyuanjun/zuoye.py
526
4.25
4
numbers = [2,1,3,5,8,7] group = {8,3,1} def sort_priority(numbers,group=None): if group == None: group = [] target1 = [] target2 = [] for i in numbers: target1.append(i) if i in group else target2.append(i) target1.sort() target2.sort() new_num = [i for i in target1] for i in target2: new_num.append(i) return new_num print(sort_priority(numbers,group)) # 同样,写出来已经很不错了,不过这个还有更好的方法,元组排序和lambda 函数
084dd9af3fbd97e4025b2d9848409ebec869db05
okccc/python
/basic/06_迭代器和生成器.py
2,511
4.25
4
# coding=utf-8 """ 可迭代对象:可以作用于for循环的对象,包含iter()方法,可用isinstance(**, Iterable)判断 迭代器:有返回值的可迭代对象,包含iter()和next()方法,可用isinstance(**, Iterator)判断 iter():迭代器一定是可迭代对象但可迭代对象不一定是迭代器,iter函数可以将可迭代对象变成迭代器 生成器:使用yield关键字的函数不再是普通函数,调用该函数不会立即执行而是创建一个生成器对象,调用next()时运行 yield作用:中断函数并返回后面的值,然后在下一次执行next()方法时从当前位置继续运行,减少内存占用 优点:列表和字典等容器是先生成数据再调用,迭代器和生成器不保存数据而是保存数据的生成方式,调用时才生成极大节省内存空间 """ from collections import Iterable from collections import Iterator import sys def iterator(): # isinstance()判断是否是可迭代对象 print(isinstance(100, Iterable)) # False print(isinstance('abc', Iterable)) # True print(isinstance((), Iterable)) # True print(isinstance([], Iterable)) # True print(isinstance({}, Iterable)) # True print(isinstance((i for i in range(1, 10)), Iterable)) # True # isinstance()判断是否是迭代器 print(isinstance(100, Iterator)) # False print(isinstance('abc', Iterator)) # False print(isinstance((), Iterator)) # False print(isinstance([], Iterator)) # False print(isinstance({}, Iterator)) # False print(isinstance((i for i in range(1, 10)), Iterator)) # True(生成器一定是迭代器) # iter()方法将可迭代对象变成迭代器通过next()不断调用取值,迭代器就是有返回值的可迭代对象 a = [11, 22, 33] print(isinstance(a, Iterator)) # False b = iter(a) print(isinstance(b, Iterator)) # True print(next(b)) # 11 print(next(b)) # 22 print(next(b)) # 33 def fibonacci(n): a, b, count = 0, 1, 0 while count < n: a, b = b, a + b count += 1 yield a f = fibonacci(10) print(f) # <generator object fibonacci at 0x0000023738144308> print(isinstance(f, Iterator)) # True --> 说明生成器也是迭代器 while True: try: print(next(f), end=" ") # 1 1 2 3 5 8 13 21 34 55 except StopIteration: # StopIteration异常用于标识迭代的完成,防止出现无限循环的情况 sys.exit() # 退出python解释器,后续代码不会再执行
909ebc59829e66a55dc147364fade884f6b36562
oumingwang/----Python
/PycharmProjects/91个建议/cookbook/数据结构/collections_deque.py
2,561
3.984375
4
#coding:utf8 #简单匹配行,输出匹配 from collections import deque ''' def search(lines,pattern,history = 5): pre_lines = deque(maxlen=history) for line in lines: if pattern in line: yield line,pre_lines pre_lines.append(line) if __name__ == '__main__': with open('hello.txt') as f : for line , pre_lines in search(f,'python',5): for pline in pre_lines: print pline print line print '_'*20 ''' #deque的用途 q = deque(maxlen=3) q.append(1) q.append(2) q.append(3) print q q.append(4) print q q.appendleft(5) print q q.pop() print q q.popleft() print q #一个键值对应多个值(list or set) from collections import defaultdict d = defaultdict(list) d['a'].append(1) d['a'].append(2) print d d['b'].append(3) print d s = defaultdict(set) s['a'].add(1) s['a'].add(2) s['a'].add(1) s['b'].add(2) print s d = {} d.setdefault('a',set()).add(1) d.setdefault('a',set()).add(1) d.setdefault('b',[]).append(2) print d #字典的排序 zip()构建字典 dict_test = { 'a':1, 'b':2, 'c':3, 'd':4, } dicta = zip(dict_test.values(),dict_test.keys()) print dicta print min(dicta),max(dicta) print sorted(dicta,reverse=True) #find keys in common a = { 'x':1, 'y':2, 'z':8 } b = { 'x':11, 'y':2, 'w':10 } dicta = set(a.keys()) & set(b.keys()) print dicta print set(a.keys()) - set(b.keys()) print set(a.items()) & set(b.items()) #切片对象 slice_test = [0,1,2,3,4,5,6,7,8] a = slice(2,4) print slice_test[2:4] print slice_test[a] slice_test[a] = [10,11] print slice_test del slice_test[a] print slice_test s ='helloworld' print a.indices(len(s)) from collections import Counter from operator import itemgetter word = ['a', 'b', 'c', 'a', 'b', 'b'] word_counter = Counter(word) print word_counter #two_max = word_counter.most_common(1) #print two_max num_index = {} for num in word: if num not in num_index: num_index[num] = 1 else: num_index[num] += 1 dict_test = zip(num_index.values(),num_index.keys()) print sorted(dict_test,reverse=True) #将名字映射到序列的元素中 from collections import namedtuple Subscribe = namedtuple('Subscribe',['addr','joined']) sub = Subscribe('oumingwang@163.com','2012-12-12') print sub print len(sub) addr,joined = sub print addr,joined """from collections import ChainMap a = {'a':1,'z':2} b = {'b':2,'z':3} c = ChainMap(a,b) #first a next b 字典合并 """ a = {'a':1,'z':2} b = {'b':2,'z':3} b.update(a) print b
0c11f5021004b46aae7f4032c3694eaeb94aadb3
subedibimal/iw-assignments
/assignment/5.py
197
3.515625
4
my_info = ("Bimal", "Subedi", 20) people = [] people.append(my_info) people.append(("Sagar", "Karki", 20)) people.append(("Susan", "Shakya", 20)) people.sort(key=lambda x: x[-1]) print(people)
8416c807ac7fbf9e56d7a82d04ff9235e12022f7
hz336/Algorithm
/LeetCode/DP/M Perfect Squares.py
607
3.9375
4
""" Given a positive integer n, find the least number of perfect square numbers (for example, 1, 4, 9, 16, ...) which sum to n. Example 1: Input: n = 12 Output: 3 Explanation: 12 = 4 + 4 + 4. Example 2: Input: n = 13 Output: 2 Explanation: 13 = 4 + 9. """ import math """ Time Complexity: O(n * sqrt(n)) """ class Solution(object): def numSquares(self, n): f = [float('inf')] * (n + 1) f[0] = 0 for curr in range(1, n + 1): for prev in range(1, int(math.sqrt(curr)) + 1): f[curr] = min(f[curr], f[curr - prev * prev] + 1) return f[n]
f0716450d6565c7715f6caf6078c4e0f7d338ccc
dsli208/ScriptingLanguages
/hw1/Py3_David_Li_110328771_HW1/hw1_q5_p1.py
1,853
3.953125
4
def passwordCheck(s): # define tests the password must pass to be deemed string lengthTestValue = lengthTest(s) numTestValue = False alphaTestValue = False specialTestValue = False noIncValTestValue = True distinctCharTestValue = False # Numeric, alphabet, and special test # Also tests for no previous character, more than two consecutive times increasingChars = 1 previousChar = '\0' previousCharOccurrences = 0 distinctChars = [] for c in s: if c >= '0' and c <= '9': numTestValue = True elif (c >= 'A' and c <= 'Z') or (c >= 'a' and c <= 'z'): alphaTestValue = True else: specialTestValue = True # Test for previous character equivalence to current one if previousChar != '\0': if c == previousChar: previousCharOccurrences += 1 if previousCharOccurrences > 2: return False else: previousCharOccurrences = 1 previousChar = c if c not in distinctChars: distinctChars.extend(c) # Check for consecutive ASCII/ord value if ord(c) - ord(previousChar) == 1: increasingChars += 1 else: increasingChars = 1 # Increasing value pattern test if increasingChars > 3: noIncValTestValue = False else: previousChar = c distinctChars.extend(c) # Distinct character test if len(distinctChars) >= (int)(len(s) / 2): distinctCharTestValue = True return lengthTestValue and numTestValue and alphaTestValue and specialTestValue and noIncValTestValue and distinctCharTestValue # Test length def lengthTest(s): return len(s) >= 8
0991fc9c42caf60963563cfa2b9aff53ca883461
JustWon/MyKakaoCodingTestSolution
/Quiz3/Quiz3.py
2,750
3.609375
4
class Node: def __init__(self, _key, _val, _prev=None, _next=None): self.key = _key self.val = _val self.prev = _prev self.next = _next class LRUCache: # @param capacity, an integer def __init__(self, capacity): self.counter = 0 self.capacity = capacity self.dic = dict() self.head = Node(None, None) # OLD(least recent) self.tail = Node(None, None) # MOST RECENT self.head.next = self.tail self.tail.prev = self.head # @return an integer def get(self, key): ret = -1 if key in self.dic: t_node = self.dic[key] ret = t_node.val if t_node != self.tail.prev: # 현재 노드 제거 t_prev_node = t_node.prev t_next_node = t_node.next t_prev_node.next = t_next_node t_next_node.prev = t_prev_node # 맨 뒤에 붙인다. most_recent_node = self.tail.prev most_recent_node.next = t_node t_node.prev = most_recent_node self.tail.prev = t_node t_node.next = self.tail return ret # @param key, an integer # @param value, an integer # @return nothing def set(self, key, value): if key in self.dic: target_node = self.dic[key] target_node.val = value t_prev_node = target_node.prev t_next_node = target_node.next t_prev_node.next = t_next_node t_next_node.prev = t_prev_node else: target_node = Node(key, value) # 자료구조에 넣는다. self.dic[key] = target_node self.counter += 1 # 맨 뒤에 붙인다. most_recent_node = self.tail.prev most_recent_node.next = target_node target_node.prev = most_recent_node self.tail.prev = target_node target_node.next = self.tail if self.counter > self.capacity: most_old_node = self.head.next most_old_node.prev = None self.head.next = most_old_node.next self.head.next.prev = self.head most_old_node.next = None self.dic.pop(most_old_node.key) self.counter -= 1 # 출처:[LeetCode OJ] LRU Cache - Hard def Quiz2Solver(cacheSize, cities): if (not (0 <= cacheSize and cacheSize <=30)): print("invalid cache size") return lru = LRUCache(cacheSize) cities = [c.lower() for c in cities] cache_hit = 1 cache_miss = 5 elapsed_time = 0 for i, city in enumerate(cities): if (i < cacheSize): # initial caching lru.set(city, city) elapsed_time += cache_miss # print("%s cache init" % city) else: if(lru.get(city) != -1): # cache hit lru.set(city,city) elapsed_time += cache_hit # print("%s cache hit" % city) else: # cache miss lru.set(city, city) elapsed_time += cache_miss # print("%s cache miss" % city) return elapsed_time
a9078a18657923ff24ef0b066d73183af07ba487
bobyaaa/Competitive-Programming
/CCC/CCC '06 J2 Roll the Dice.py
355
3.78125
4
#Solution by Andrew Huang dice1 = input() dice2 = input() total = 0 fails = 0 for x in range(dice1): for y in range(dice2): if x+y == 10: total += 1 else: fails +=1 if total == 1: print 'There are '+ str(total) + ' ways to get the sum 10.' else: print 'There is '+ str(total) + ' way to get the sum 10.'
dd9a4940acf27314c110da47f0522d72c09366c6
vijayjag-repo/LeetCode
/Python/LC_Sum_of_Left_Leaves.py
719
3.828125
4
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def sumOfLeftLeaves(self, root): """ :type root: TreeNode :rtype: int """ self.ans = 0 def helper(root): if not root: return(0) elif(root.left and not root.left.left and not root.left.right): self.ans+=root.left.val helper(root.left) helper(root.right) helper(root) return(self.ans)
8b1c61df388e942cdd272cdc8ba5d79fc943f4b4
pavanimallem/pavs4
/guvi31ply.py
171
3.765625
4
string=raw_input() a=0 b=0 length=len(string) for i in range(0,length): if(string[i]==')'): a+=1 elif(string[i]=='('): b+=1 if(a-b==0): print"yes" else: print"no"
772c0267444435ccfc9e73aeef94ff74ef031f46
hoi-nx/Python_Core
/Helloworld/For.py
245
3.609375
4
#range(begin,end,step) step bước nhẩy range(10) range(1,10) range(1,10,2) range(10,0,-1) #for ngược n=10 s=0 if n%2==0: for x in range(2,n+1,2): s=s+x else: for x in range(1,n+1,2): s=s+x print("Tổng s= ",s)
36661e997c38bae86272e0174f36951022ac4958
gabriellaec/desoft-analise-exercicios
/backup/user_195/ch47_2019_03_19_18_40_55_134564.py
195
3.734375
4
pergunta=input("Qual o mês?") i=0 L=["janeiro","fevereiro","março","abril","maio","junho","julho","agosto","setembro","outubro","novembro","dezembro"] while pergunta!=L[i]: i+=1 print (i+1)
5274217eed60d74967edb7d62a4525e973f83434
fernandochimi/Intro_Python
/Exercícios/057_Media_Listas_Digitadas.py
216
3.5
4
notas=[0,0,0,0,0,0,0] soma=0 x=0 while x < 7: notas[x] = float(input("Nota %d: " % x)) soma += notas[x] x += 1 x = 0 while x < 7: print("Nota %d: %6.2f" % (x, notas[x])) x += 1 print("Média: %5.2f" % (soma/x))
375a05197e7b9b943561add6fd5731233599febf
HernandezCesar/Firework-hw-due-9-29-17
/lab 6
2,637
4.78125
5
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Sep 27 08:37:09 2017 Lab 6. . Main objective: creating and working with lists. . Other objecives: working with random numbers, defining and calling function @author: Alvaro Monge alvaro.monge@csulb.edu @author: Cesar Hernandez hernandezcesar746@gmail.com @author: Mario Bajenting mariobajenting@gmail.com """ import random # module defining functions to generate random numbers made = [] def generate_random_values(length, mean, standard_deviation): '''(int, float, float) Returns a list of random float values from a Gaussian distribution. Args: length: the length of the list (the number of values the list is to contain) mean: the mean value of the Gaussian distribution standard_deviation: the standard deviation of the Gaussian distribution Returns: A list of float values from a Gaussian distribution with given mean and standard deviation ''' # TODO: below this comment, enter the instruction used to create an empty list # that is to be used in the rest of this function #made = [] # TODO: Next, design and write a loop that generates random float values and # adds these to the list. The float values should come from a Gaussian # distribution # If needed, see section 3.2 on adding elements to a list # Also, see: https://docs.python.org/3/library/random.html#random.gauss i = 0 while i < length: made.append(random.gauss(mean, standard_deviation)) i += 1 return made # TODO: The last instruction of this function should return the list of values # i = 0 # made_sum = 0 # while i < length: # made_sum += made[i] # # made_average = made_sum/length # main ... the instructions after all function definitions ''' TODO: call the function to create a list of 25 values from a Guassian distribution with a mean of 80 and a standard deviation of 10.5. Context: each value in the list represents a grade. Use a loop to print the first list in reverse order (from the last element to the first) and to find the average of these values. Print the average. ''' #while made.len print ("list 1: ", generate_random_values(25, 80, 10.5)) print ("list 1 reversed: ", generate_random_values(25, 80, 10.5)) ''' TODO: call the function to create a second list. This list should have 10 values, with a mean of 159.8 and a standard deviation of 7.5. Use loops to print all the values and to find the average of these values. Print the average. ''' print ("\nlist 2: ", generate_random_values(10, 159.8, 7.5))
11b834f225f09e4f9687961ebbc5b26e95916e30
MTGTsunami/LeetPython
/src/leetcode/bfs/286. Walls and Gates.py
1,884
4.03125
4
""" You are given a m x n 2D grid initialized with these three possible values. -1 - A wall or an obstacle. 0 - A gate. INF - Infinity means an empty room. We use the value 231 - 1 = 2147483647 to represent INF as you may assume that the distance to a gate is less than 2147483647. Fill each empty room with the distance to its nearest gate. If it is impossible to reach a gate, it should be filled with INF. Example: Given the 2D grid: INF -1 0 INF INF INF INF -1 INF -1 INF -1 0 -1 INF INF After running your function, the 2D grid should be: 3 -1 0 1 2 2 1 -1 1 -1 2 -1 0 -1 3 4 """ from collections import deque class Solution: def wallsAndGates(self, rooms: List[List[int]]) -> None: """ Do not return anything, modify rooms in-place instead. """ queue = deque() for i in range(len(rooms)): for j in range(len(rooms[0])): if rooms[i][j] == 0: queue.append((i, j, 0)) while queue: i, j, val = queue.popleft() if i - 1 >= 0 and rooms[i - 1][j] != -1: if val + 1 < rooms[i - 1][j]: rooms[i - 1][j] = val + 1 queue.append((i - 1, j, val + 1)) if i + 1 < len(rooms) and rooms[i + 1][j] != -1: if val + 1 < rooms[i + 1][j]: rooms[i + 1][j] = val + 1 queue.append((i + 1, j, val + 1)) if j - 1 >= 0 and rooms[i][j - 1] != -1: if val + 1 < rooms[i][j - 1]: rooms[i][j - 1] = val + 1 queue.append((i, j - 1, val + 1)) if j + 1 < len(rooms[0]) and rooms[i][j + 1] != -1: if val + 1 < rooms[i][j + 1]: rooms[i][j + 1] = val + 1 queue.append((i, j + 1, val + 1))
95b01387d6b6294e0d3b67539ee3f003ad73055d
PLUTOLEARNS/computerprogramsreal
/randomfunction07072020.py
264
3.890625
4
"""i school fest , three randomly chosen students out of 100 students have to present bouquets to guests """ import random s1 = random.randint(1,100) s2 = random.randint(1,100) s3 = random.randint(1,100) print ("The selected students are : " ,s1,s2,s3)
2dbdd93450eb80452f0a4eedb64e7786106366f7
wizardlancet/ICS-Fall-2014
/ICS-Lab2/fizzbuzz/fizzbuzz-students.py
497
4.4375
4
""" The FizzBuzz Problem ==================== Write a program that prints the numbers from 1 to 100. But for multiples of three, print “Fizz” instead of the number. For the multiples of five, print “Buzz” instead of the number. For numbers which are multiples of both three and five, print “FizzBuzz”. """ for x in range(1,101): if x % 3 == 0: print("Fizz",end="") if x % 5 == 0: print("Buzz",end="") elif x % 3 != 0 : print(x,end="") print()
835270726e65a3a75fd5bb630f329fcdc5deabc5
nobe0716/problem_solving
/leetcode/people-whose-list-of-favorite-companies-is-not-a-subset-of-another-list.py
1,102
3.625
4
from typing import List class Node: def __init__(self, fc): self.idx = fc[0] self.v = set(fc[1]) self.child = [] def try_insert(self, node): if self.v.intersection(node.value) != node.value: return False if any(e.try_insert(node) for e in self.child): return True self.child.append(node) return True class Solution: def peopleIndexes(self, favoriteCompanies: List[List[str]]) -> List[int]: sorted_list = sorted(enumerate(favoriteCompanies), key=lambda x: len(x[1]), reverse=True) max_len = len(sorted_list[0][1]) roots = [Node(sorted_list[0])] for i, e in sorted_list[1:]: new_node = Node((i, e)) if len(e) != max_len and any(e.try_insert(new_node) for e in roots): continue roots.append(new_node) return sorted(e.idx for e in roots) s = Solution() ans = s.peopleIndexes( [["leetcode", "google", "facebook"], ["google", "microsoft"], ["google", "facebook"], ["google"], ["amazon"]]) assert ans == [0, 1, 4]
38ecb19b0e45c28001e107ffc1ed6fc18eb118ea
IgoryanM/Python
/les_2/2_2.py
564
3.71875
4
my_list = [] new_list = [] while True: value = input('Enter some data or type esc for quit: ') if value == 'esc': break else: my_list.append(value) print(my_list, '- your list') if len(my_list) % 2 == 0: for i in range(0, len(my_list), 2): new_list.append(my_list[i + 1]) new_list.append(my_list[i]) else: for i in range(0, len(my_list) - 1, 2): new_list.append(my_list[i + 1]) new_list.append(my_list[i]) new_list.append(my_list[len(my_list)-1]) print(new_list)
d16b156a874e9179f71688e9a4693e49a3367de6
csernazs/misc
/aoc/2018/aoc02b.py
605
3.53125
4
#!/usr/bin/python3 def common_letters(str1, str2): for c1, c2 in zip(str1, str2): if c1 == c2: yield c1 def difference(str1, str2): retval = 0 for c1, c2 in zip(str1, str2): if c1 != c2: retval += 1 return retval lines = [x.strip() for x in open("aoc02.txt")] sol1 = sol2 = None for line1 in lines: for line2 in lines: if line1 == line2: continue if difference(line1, line2) == 1: print(line1, line2) sol1, sol2 = line1, line2 if sol1: print("".join(common_letters(sol1, sol2)))
0be64ec96a954dc8e5085204e060866097af81e1
Snehagit6/G-Pythonautomation_softwares-Sanfoundry_programs
/Basic_Programs/Decorators/higher_functions.py
358
3.75
4
# def outer(x, y): # # def inner1(): # return x+y # # def inner2(z): # return inner1() + z # # return inner2 # # # f = outer(10, 25) # # print(f(15)) def outer(x, y): def inner1(): return x+y def inner2(): return x*y return (inner1, inner2) (f1, f2) = outer(10, 25) print(f1()) print(f2())
e31d8bb975f1f86d799643910402ee387e0417da
jz33/LeetCodeSolutions
/T-1277 Count Square Submatrices with All Ones.py
1,441
3.765625
4
''' 1277. Count Square Submatrices with All Ones https://leetcode.com/problems/count-square-submatrices-with-all-ones/ Given a m * n matrix of ones and zeros, return how many square submatrices have all ones. Example 1: Input: matrix = [ [0,1,1,1], [1,1,1,1], [0,1,1,1] ] Output: 15 Explanation: There are 10 squares of side 1. There are 4 squares of side 2. There is 1 square of side 3. Total number of squares = 10 + 4 + 1 = 15. Example 2: Input: matrix = [ [1,0,1], [1,1,0], [1,1,0] ] Output: 7 Explanation: There are 6 squares of side 1. There is 1 square of side 2. Total number of squares = 6 + 1 = 7. ''' class Solution: def countSquares(self, matrix: List[List[int]]) -> int: ''' Similar to 221. Maximal Square ''' if not matrix or not matrix[0]: return 0 rowCount = len(matrix) colCount = len(matrix[0]) # dp[i][j] keeps the size of maximal square on (i,j) dp = [[0] * colCount for _ in range(rowCount)] for i in range(rowCount): for j in range(colCount): if matrix[i][j] == 1: if i > 0 and j > 0: dp[i][j] = min(dp[i-1][j], dp[i][j-1], dp[i-1][j-1]) + 1 else: dp[i][j] = 1 return sum(dp[i][j] for i in range(rowCount) for j in range(colCount))
56ed05a6fc29fca3547142b6603e74a0f6951bd1
poliwal/DSA-Practice
/Array/Longest Peak.py
556
3.828125
4
# O(n) time | O(1) space def longestPeak(array): longestPeakLength = 0 i = 1 while i < len(array)-1: if array[i-1] < array[i] and array[i] > array[i+1]: left = i - 2 while left >= 0 and array[left] < array[left+1]: left -= 1 right = i + 2 while right < len(array) and array[right] < array[right-1]: right += 1 currentPeakLength = right - left - 1 longestPeakLength = max(longestPeakLength, currentPeakLength) i = right else: i += 1 return longestPeakLength print(longestPeak([1,2,3,3,4,0,10,6,5,-1,-3,2,3]))
bd01642f900443a34614eef8604be8bbe6aad543
ar012/python
/learning/function_def.py
646
3.921875
4
# Defining the function named hello def hello(): print("Hello World") #print(2+8) # Calling the function hello to use it hello() # Again calling the function hello hello() # Defining the function area def area(): PI = 3.14159 redius = 2 print("Area of the circle:", PI*redius*redius, "unit") # Calling the function area area() # defining the function show_double def show_double(x): print(x*2) # Calling the function show_double show_double(10) show_double(100) # Defining the function make_sum def make_sum(x, y): z = x+y print(z) # Calling the function make_sum make_sum(2, 10) make_sum(100, 500) print(z)
c0fc73e28d94cb7ae25761f4b80aaa5d59865f85
yogendratamang48/secured_communication_fibonacci
/decrypt.py
746
3.53125
4
import json import encrypt FILE_TO_DECODE = 'message.txt' def start_decript(rawSecurityCode): asciiLetters = encrypt.getAsciiLetters() encoded_hexes = eval(open(FILE_TO_DECODE, 'r').read()) if len(rawSecurityCode)==1 and rawSecurityCode[0] in asciiLetters: _decimals = [int(_hex, 16) for _hex in encoded_hexes] decoded_message = encrypt.getDecodedMessage(rawSecurityCode, _decimals) print("Decoding...") # print(decoded_message) return decoded_message else: print("Wrong Security Key") if __name__=='__main__': rawSecurityCode = input("Enter Security Code: ") mess = start_decript(rawSecurityCode) print(mess) # Single Character Validation # Reading file
269055cbca853f415b04dc48865e8dc4a1322fc0
jetboom1/python_projects
/kr1/Franko_KR1_1_Variant1.py
462
4.09375
4
x = float(input('Введите первое число')) y = float(input('Введите второе число')) z = float(input('Введите третье число')) if x+y+z<1 and x<y and y<z: x = (y+z)/2 print(x,y,z) if x+y+z<1 and y<x and x<z: y = (z+x)/2 print(x,y,z) if x+y+z<1 and z<y and y<x: z = (y+x)/2 print(x,y,z) if x+y+z>=1 and x<y: x = (y+z)/2 print(x,y,z) else: y = (x+z)/2 print(x,y,z)
b689d2d94469d38fad83eb3ab1e13ba816f87b68
xuzuoyang/mypackage
/mypackage/core.py
586
3.84375
4
from copy import deepcopy def dict_substract(dict1, dict2): '''Substract dict2 from dict1 and return dict1. Args: dict1: supposed to be the minuend. dict2: supposed to be the subtrahend. Returns: difference dict from the substraction. ''' if isinstance(dict1, dict) and isinstance(dict2, dict): dict_diff = deepcopy(dict1) for k, v in dict2.items(): if dict_diff.get(k) == v: del dict_diff[k] return dict_diff else: raise ValueError('Only do substraction between two dicts!')
4691e76e6f3ad884548ed71b699ee234755e43aa
ramona-2020/Python-OOP
/06. Iterators and Generators/05. Fibonacci Generator.py
327
4.21875
4
def fibonacci(): current_num = 1 previous_num = 0 yield previous_num yield current_num while True: next_num = previous_num + current_num yield next_num previous_num = current_num current_num = next_num generator = fibonacci() for i in range(5): print(next(generator))
e53577147aeff98db68c83767085e43d57c103e6
standy66/h2-async-benchmarks
/curio_server.py
2,548
3.8125
4
#!/usr/bin/env python3.5 # -*- coding: utf-8 -*- """ curio-server.py ~~~~~~~~~~~~~~ A fully-functional HTTP/2 server written for curio. Requires Python 3.5+. """ import mimetypes import os import sys from curio import Event, spawn, socket, ssl, run import h2.config import h2.connection import h2.events # The maximum amount of a file we'll send in a single DATA frame. READ_CHUNK_SIZE = 8192 def create_listening_socket(address): """ Create and return a listening TLS socket on a given address. """ sock = socket.socket() sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.bind(address) sock.listen() return sock async def h2_server(address): """ Create an HTTP/2 server at the given address. """ sock = create_listening_socket(address) print("Now listening on %s:%d" % address) async with sock: while True: client, _ = await sock.accept() server = H2Server(client) await spawn(server.run()) class H2Server: """ A basic HTTP/2 file server. This is essentially very similar to SimpleHTTPServer from the standard library, but uses HTTP/2 instead of HTTP/1.1. """ def __init__(self, sock): config = h2.config.H2Configuration( client_side=False, header_encoding='utf-8' ) self.sock = sock self.conn = h2.connection.H2Connection(config=config) async def run(self): """ Loop over the connection, managing it appropriately. """ self.conn.initiate_connection() await self.sock.sendall(self.conn.data_to_send()) while True: # 65535 is basically arbitrary here: this amounts to "give me # whatever data you have". data = await self.sock.recv(65535) if not data: break events = self.conn.receive_data(data) for event in events: if isinstance(event, h2.events.RequestReceived): data = b"Hello, world" response_headers = ( (':status', '200'), ('content-length', str(len(data))), ) self.conn.send_headers(event.stream_id, response_headers) self.conn.send_data(event.stream_id, data, end_stream=True) await self.sock.sendall(self.conn.data_to_send()) if __name__ == '__main__': port = int(sys.argv[1]) run(h2_server(("localhost", port)))
9d27b7f19491915f1c783dd5753587597a1e9f05
buzumka/GB_Python
/l3_ex3.py
448
4.28125
4
""" Реализовать функцию my_func(), которая принимает три позиционных аргумента и возвращает сумму наибольших двух аргументов. """ def my_func(num_1, num_2, num_3): """ возвращаем сумму наибольших двух аргументов""" return (num_1 + num_2 + num_3 - min(num_1, num_2, num_3)) print(my_func(10, 20, 15))
6c5b6e85993b5da846fa996ced0dff56bc318381
Dimitarleomitkov/Obirah
/Obirah/RngPatchTileGenerator.py
455
3.515625
4
import sys import random # Count the characters on a line and the lines if (len(sys.argv) != 3): print ("You need to provide width and height."); exit(); width = sys.argv[1]; height = sys.argv[2]; usable_tiles = ["T", "*", "~", " "]; new_file_name = "z_rngterrain.txt" fw = open (f"{new_file_name}", "w"); for i in range (int(height)): for j in range (int(width)): fw.write (f"{random.choice(usable_tiles)} "); fw.write ("\n"); print ("Done");
b0b6eef61fa74968fa7f825698ded7eb004d0654
JCGit2018/python
/HomeTask5/SwapStrings.py
196
4.1875
4
# 1. WAP to input 2 strings and swap the strings s1 = input('Enter the 1st string: ') s2 = input('Enter the 2nd string: ') print(s1) print(s2) temp = s1 s1 = s2 s2 = temp print(s1) print(s2)
95ef5bbec568f499553b2ca1ed6ea9abd0f10038
IdenTiclla/guess
/main.py
1,055
4.03125
4
from colorama import Fore, Style import random def main(): min_number = 1 max_number = 20 guess_taken = 0 username = input("Hello what is your name?: ") random_number = random.randint(min_number, max_number) print(Fore.YELLOW + f"Well, {username}. I am thinking in a number between {min_number} and {max_number}") print(Style.RESET_ALL) while guess_taken < 6: guess = int(input("Take a guess: ")) guess_taken += 1 if guess < random_number: print(Fore.RED + "Your guess is too Low.") print(Style.RESET_ALL) elif guess > random_number: print(Fore.RED + "Your guess is too High.") print(Style.RESET_ALL) else: print(Fore.GREEN + f"Good Job, {username}! you guessed my number in {guess_taken}") print(Style.RESET_ALL) break if guess_taken == 6: print(Fore.RED + f"No the number I was thinking of was {random_number}") print(Style.RESET_ALL) if __name__ == "__main__": main()
a13d4cf552632ed6284afe9f877e0f804b46d8b3
bitoffdev/Learn-Python
/15-1.py
555
4.4375
4
#This line imports the arguments given to the program at start using sys module from sys import argv #This line puts argv values into two variables script, filename = argv #This line opens the file given to the program using argv txt = open(filename) #This line outputs the argv filename input print "Here's your file %r:" % filename #This line prints the file print txt.read() #The following lines do the same thing without using argv: print "Type the filename again:" file_again = raw_input("> ") txt_again = open(file_again) print txt_again.read()
5997a28d146fb769a216097207930a74e002ac65
PedroSDD/Python-challenges
/CheckPair.py
585
3.71875
4
#INPUT SAMPLE: Your program should accept as its first argument a filename. # This file will contain a comma separated list of sorted numbers and then the sum 'X', separated by semicolon. #Ignore all empty lines. If no pair exists, print the string NULL import itertools def fileReader(path): with open(path) as file: for line in file: checkPair(line) def checkPair(line): line = line.strip().split(";") column_value = line[-1] line = line[:-1] def pairMaker(line, column_value): for i in line: fileReader("/Users/Dias/Desktop/test.txt")
80538107e0223af517b7124ccd1de0b2d8a70af2
mertcanozturk/HumanPoseEstimationAndUnityIntegration
/PythonScript/sendData.py
1,489
3.59375
4
import socket def sending_and_reciveing(): s = socket.socket() print('socket created ') port = 1234 s.bind(('127.0.0.1', port)) #bind port with ip address print('socket binded to port ') s.listen(5)#listening for connection print('socket listensing ... ') while True: c, addr = s.accept() #when port connected print("\ngot connection from ", addr) de=c.recv(1024).decode("utf-8") #Collect data from port and decode into string print('Getting Data from the Unity : ',de) list=de.split(',') #cominda data is postion so we split into list on basis of , UpdateValue="" for value in list: #loop for each value in the string single value=str(value)#sonvet list value into string if '(' in value or ')' in value: #coming data in to form of (1.0,2.2,3.0),when split then we check each value dosnt contan '(' or ')' value=value.replace('(','') #if it ( contain any one of these we remove it value=value.replace(')', '')#if it ) contain any one of these we remove it C_value=float(value) #convert string value into float UpdateValue=UpdateValue+(str(C_value+3.0))+" " #add 3.0 into float value and put it in a string print('After changing data sending back to Unity') c.sendall(UpdateValue[:-1].encode("utf-8"))#then encode and send taht string back to unity c.close() sending_and_reciveing()#calling the function to run server
a5e23138b12ba9ca50eaa8e3346810946edba92b
astrodoo/pyds
/tools/today.py
501
3.84375
4
""" filename: today.py PURPOSE: generate the string that indicates the today with the format of "yymmdd_" Written by: Doosoo Yoon University of Amsterdam History: Written, 1 October 2018 """ import datetime class today: """ generate the string that indicates the today with the format of "yymmdd_" ex) from pyds.tools import today print(today.datestr) """ datestr = datetime.datetime.now().strftime("%y%m%d") + '_'
0931417feb07eac9cd1cc47cadada8633ce28308
parutechie/Python
/app.py
369
4.21875
4
#Simple Python Program for Converting KiloGram(kg) to Pounds or Converting Pounds to KiloGram(kg) Using "if else statement" weight = int(input("Weight: ")) unit = input("(L)bs or (k)g: ") if unit.upper() == "L": converter = weight * 0.45 print(f"yor are {converter} Kilos") else: converter = weight // 0.45 print(f"you are {converter} pounds")
439e1c218953f39922d7c6c302a412c3fd184b89
adimanea/sla
/1-nlp/lab1/python_list_categ.py
638
3.53125
4
############################################################ # Se dă o listă de cuvinte. Să se afișeze cuvintele, # împreună cu numărul aparițiilor lor (case insensitive). ############################################################ lista = ["haha", "poc", "Poc", "POC", "haHA", "hei", "hey", "HahA", "poc", "Hei"] aparitii = {} listaLower = [None]*len(lista) for i in range(0, len(lista)): listaLower[i] = lista[i].lower() for cuvint in listaLower: if cuvint not in aparitii: aparitii[cuvint] = 0 aparitii[cuvint] += 1 for (k, v) in aparitii.items(): print("aparitii[{}] = {}".format(k, v))
c9c34f695e793a93fde90b89a9b0ef57afbed88b
Drlilianblot/tpop
/TPOP Python 3.x Practicals/huffman.py
3,737
3.578125
4
''' Created on 17 Nov 2016 @author: lb1008 ''' class HuffmanTree(object): ''' classdocs ''' def __init__(self, left = None, right = None, symbol = None, frequency = 0): ''' Constructor ''' self._right = right self._left = left self._frequency = frequency self._symbol = symbol self._encoding = None def __str__(self): if self._symbol is None: symbol = "*" else: symbol = self._symbol if self._left is None and self._right is None: # a leaf return ("<("+str(symbol) + ":" + str(self._frequency) +")>") else: return ("<("+str(symbol) + ":" + str(self._frequency) +") " + str(self._left)+ " | " + str(self._right) + ">") def __repr__(self): return self.__str__() def _get_frequency(self): return self._frequency def build_tree(self, frequencies): leaves = [] for symbol in frequencies: leaves.append(HuffmanTree(symbol = symbol, frequency = frequencies[symbol])) tree = self._build_tree(leaves) self._right = tree._right self._left = tree._left self._frequency = tree._frequency self._symbol = tree._symbol def _build_tree(self, list_tree): if not list_tree: raise ValueError("need at least one tree in the list!") elif len(list_tree) == 1: print("end recursion", list_tree) return list_tree[0] else: sorted_trees = sorted(list_tree, key = HuffmanTree._get_frequency, reverse = True) print(sorted_trees) left = sorted_trees.pop() right = sorted_trees.pop() tree = HuffmanTree(left = left, right = right, frequency = left._frequency + right._frequency) sorted_trees.append(tree) return self._build_tree(sorted_trees) def _is_leaf(self): return self._left is None and self._right is None def get_encoding(self): def _build_encoding_rec(tree, dico, code): if tree._is_leaf(): dico[tree._symbol] = code if tree._left is not None: _build_encoding_rec(tree._left, dico, code+"0") if tree._right is not None: _build_encoding_rec(tree._right, dico, code+"1") if self._encoding is None: self._encoding = {} _build_encoding_rec(self, self._encoding, "") return self._encoding def encode(self,word): output = "" if self._encoding is None: self.get_encoding() for symbol in word: output += self._encoding[symbol] return output def decode(self, code): output = "" def _decode(tree, code): if tree._is_leaf(): return code, tree._symbol elif code == "": raise ValueError("invalid code entry!") elif code[0] == "0": return _decode(tree._left, code[1:]) elif code[0] == "1": return _decode(tree._right, code[1:]) while code != "": code, symbol = _decode(self, code) output += symbol return output tree = HuffmanTree() tree.build_tree({"a":3, "b":2, "c":2, "d":3}) print(tree) print(tree.get_encoding()) print(tree.encode("abcd")) print(tree.decode(tree.encode("abcd"))) print(tree.decode("1000011"))
679e27b7ef3c88a19f88dc9ded1965195210ca90
zzztpppp/TicTacToe-AI
/in_game_types.py
459
3.5625
4
# Chess piece data type is defined in this file from typing import NewType ChessPiece = NewType('ChessPiece', int) CIRCLE = ChessPiece(1) CROSS = ChessPiece(-1) Reward = NewType('Reward', int) WINNING_REWARD = 2 # Reward for winning a game DRAWING_REWARD = 0.5 # Reward for a tied game LOSING_REWARD = 0 # Reward for losing a game PLAIN_REWARD = 0.01 # Reward for an ordinary move INVALID_MOVE_REWARD = -0.2 # Reward(penalty) for a invalid move
bba1c9d6dfbdf552ffedb0a9d3a9eda286d440ad
DikijXoloDilnik/Learning-repo
/lesson1/Hw1_ex3.py
408
3.921875
4
# Узнайте у пользователя число n. Найдите сумму чисел n + nn + nnn. # Например, пользователь ввёл число 3. Считаем 3 + 33 + 333 = 369 var = input('Введите число n: ') result = int(var) + int(var * 2) + int(var * 3) print(f'после преобразования из числа n получилось - {result}')
41d345d3b16d902b4ff11e454a11a6cf098da68d
So-so1/My-first-blog-
/scripts.py
479
3.984375
4
print('Hello world!') age = 17 #Teste sur les conditions if age >= 18 : print("Vous êtes majeur, merci.") else: print("Vous êtes mineur, merci.") age = 7 #Teste de plusieurs conditions en un même temps,interval if(age > 10 and age <= 16): print(" et en même temps adolescent :).") elif (age > 16 and age <= 35): print("et en même temps jeunes :).") else: print("et en même temps vieux :).") def bonjour (name): print("Bonjour "+ name) bonjour("Za")
bcc3be48390e2da4ce04c64e37a961e60a0ad0ac
ronaldoedicassio/Pyhthon
/Arquivos Exercicios/Exercicios/Ex046.py
176
3.5625
4
""" Faça programa que conte regresivamente de 10 ate 0, e com uma pausa de 1 segundo """ import time for c in range(10,-1,-1): print(c) time.sleep(1) print("Uhuuuuuu")
e9b48e0f43358f39a251734e4f5aef93646fd2d6
Mercrist/Intermediate-Python-Solutions
/slopes.py
1,209
4.46875
4
class Point: """ Point class represents and manipulates x,y coords. """ def __init__(self, x=0, y=0): """ Create a new point """ self.x = x self.y = y def distance_from_origin(self): """ Compute my distance from the origin """ return ((self.x ** 2) + (self.y ** 2)) ** 0.5 def __str__(self): return "("+str(self.x)+","+str(self.y)+")" def halfway(self, target): """ Return the halfway point between myself and the target """ mx = (self.x + target.x)/2 my = (self.y + target.y)/2 return Point(mx, my) def slope(self, other): """ Returns the slope from self to other """ if other.x == self.x: return 'undefined' return (other.y - self.y) / (other.x - self.x) def is_on (self, point1, point2): if self.slope (point1) == self.slope (point2): #if the slope between the first point and self and the second point and self is the same return True else: return False # test cases p = Point(0,0) q = Point(3,6) r = Point(1,2) s = Point(2,3) print(r.is_on(p,q)) # should be True print(s.is_on(p,q)) # should be False
5af61be3efc4ad70ea9dd5075719328807c5d9f1
Amfeat/Python_learning
/lesson_002/04_my_family.py
992
3.671875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Создайте списки: # моя семья (минимум 3 элемента, есть еще дедушки и бабушки, если что) my_family = ['Дима', 'Марина', 'Арина'] # список списков приблизителного роста членов вашей семьи my_family_height = [ # ['имя', рост], [my_family[0], 178], [my_family[1], 179], [my_family[2], 180], ] # Выведите на консоль рост отца в формате # Рост отца - ХХ см print('Рост отца - ', my_family_height[0][1], ' см') # Выведите на консоль общий рост вашей семьи как сумму ростов всех членов # Общий рост моей семьи - ХХ см print('Общий рост моей семьи - ', my_family_height[0][1] + my_family_height[1][1] + my_family_height[1][1], ' см')
0a2b398d96a42150fc062314f3db51cadc2e597c
PitPietro/python-project
/math_study/numpy_basics/numpy_array/array_information.py
2,279
4.65625
5
import numpy as np from array_creation import py_arrays def number_of_axes(array): """ Parameters ---------- array Python array Returns ------- Number of axes (dimensions) of the array. """ return np.array(array).ndim def shape(array): """ The dimension of the array is a tuple of integers indicating the size of the array in each dimension. For a matrix with n rows and m columns, shape will be (n,m). The length of the shape tuple is therefore the number of axes, ndim. Parameters ---------- array Python array Returns ------- Dimensions of the array. """ return np.array(array).shape def size(array): """ Parameters ---------- array Python array Python array Returns ------- Total number of elements of the array. It is equal to the product of the elements of shape. """ return np.array(array).size def dtype(array): """ One can create or specify dtype's using standard Python types. NumPy provides types of its own. numpy.int32, numpy.int16, and numpy.float64 are some examples. Parameters ---------- array Python array Returns ------- Object describing the type of the elements in the array. """ return np.array(array).dtype def item_size(array): """ Parameters ---------- array Python array Returns ------- Size in bytes of each element of the array. """ return np.array(array).itemsize def data(array): """ Parameters ---------- array Python array Returns ------- The buffer containing the actual elements of the array. You do not usually need to use this attribute: you will access the elements in an array using indexing facilities. """ return np.array(array).data if __name__ == '__main__': print('Numpy Array - Info\n') print('number of axes: ' + str(number_of_axes(py_arrays))) print('shape: ' + str(shape(py_arrays))) print('n° of elements: ' + str(size(py_arrays))) print('dtype: ' + str(dtype(py_arrays))) print('item size: ' + str(item_size(py_arrays))) print('data: ' + str(data(py_arrays))) # switch-case: https://www.simplifiedpython.net/python-switch-case-statement/
420a258fa6ff51e48320b8ef074133a3aad4b9a7
CamilliCerutti/Python-exercicios
/Curso em Video/ex077.py
419
3.953125
4
# CONTANDO VOGAIS EM TUPLA # Crie um programa que tenha uma tupla com várias palavras (não usar acentos). Depois disso, você deve mostrar, para cada palavra, quais são as suas vogais. palavras = ('exceto', 'cinico', 'idoneo', 'ambito', 'nescio', 'merito') for p in palavras: print(f'\nNa palavra {p} temos ', end='') for letra in p: if letra.lower() in 'aeiou': print(letra, end= ' ')
32fb12f02af038a5abc5d1d4d6522cfc097c881f
heyalexchoi/fun_exercises
/knn/knn.py
4,404
4.21875
4
import os import csv import random import math import operator from collections import namedtuple, defaultdict """ following along with https://machinelearningmastery.com/tutorial-to-implement-k-nearest-neighbors-in-python-from-scratch/ to implement K-nearest neighbors. format of iris.data: ➜ knn head iris.data 5.1,3.5,1.4,0.2,Iris-setosa 4.9,3.0,1.4,0.2,Iris-setosa 4.7,3.2,1.3,0.2,Iris-setosa 4.6,3.1,1.5,0.2,Iris-setosa """ Dataset = namedtuple('Dataset', ['training_set', 'test_set']) Neighbor = namedtuple('Neighbor', ['instance', 'distance']) def loadDataset(filename, split): """ loads dataset from filename. splits dataset according to given split ratio (decimal proportion) resulting in split proportion being allocated to the training set. returns `Dataset` containing `training_set` and `test_set """ training_set = [] test_set = [] with open(filename, 'r') as csvfile: lines = csv.reader(csvfile) dataset = list(lines) for x in range(len(dataset) - 1): for y in range(4): dataset[x][y] = float(dataset[x][y]) if random.random() < split: training_set.append(dataset[x]) else: test_set.append(dataset[x]) return Dataset(training_set=training_set, test_set=test_set) def euclideanDistance(instance1, instance2, length): """ calculates euclidean distance between two instances of arbitrary dimensionality. the instances are assumed to be lists of measurements. euclidean distance uses length number of dimensions to calculate. """ def squared_difference(first, second): return (first - second) ** 2 summed_squares = 0 for x in range(length): summed_squares += squared_difference(first=instance1[x], second=instance2[x]) return math.sqrt(summed_squares) def getNeighbors(training_set, test_instance, k): """ given a training set and test instance, returns the k-nearest neighbors from the test instance """ # distances will become a list of tuples # each tuple containing (a_row_of_from_training_set, distance_from_test_instance) neighbors = [] length = len(test_instance) - 1 for training_instance in training_set: distance = euclideanDistance(test_instance, training_instance, length) neighbors.append(Neighbor(instance=training_instance, distance=distance)) # fun fact: python list sort uses TimSort # https://en.wikipedia.org/wiki/Timsort # https://hg.python.org/cpython/file/tip/Objects/listsort.txt neighbors.sort(key=lambda neighbor: neighbor.distance) k_nearest = neighbors[0:k] return k_nearest def getResponse(neighbors): """ condense results via a vote assuming the class is the last attribute of each neighbor, tallies up the occurrences of each class and returns the class with the highest vote """ class_votes = defaultdict(int) for neighbor in neighbors: instance_class = neighbor.instance[-1] class_votes[instance_class] += 1 winner = max(class_votes.keys(), key=(lambda class_vote_key: class_votes[class_vote_key])) return winner def getAccuracy(test_set, predictions): correct = [test_instance for index, test_instance in enumerate(test_set) if test_instance[-1] == predictions[index]] accuracy = 100 * float(len(correct)) / float(len(test_set)) return accuracy def main(): # prepare data dataset = loadDataset( filename=os.path.join(os.path.dirname(__file__), 'iris.data'), split=0.67 ) training_set, test_set = dataset.training_set, dataset.test_set print('Training set len: ' + repr(len(training_set))) print('Test set len: ' + repr(len(test_set))) # generate predictions predictions=[] k = 3 print(f"k: {k}") for test_instance in test_set: neighbors = getNeighbors( training_set=training_set, test_instance=test_instance, k=k ) result = getResponse(neighbors=neighbors) predictions.append(result) print(f""" prediction: {result} actual: {test_instance[-1]} correct: {result == test_instance[-1]} """) accuracy = getAccuracy(test_set=test_set, predictions=predictions) print(f"accuracy: {accuracy}%") if __name__ == '__main__': main()
46a6dafa451c14c30530840f24c033a75b425334
obedmr/smart_parking
/json_loader/loader.py
302
3.515625
4
import json # JSON to dict Converter from file def json_to_dict(filename): dictionary = None try: with open(filename) as filename: dictionary = json.loads(filename.read()) except IOError: print("Cannot open file {}".format(filename)) return dictionary
053bdbff49d803cb173b1e161c11d0b098a330b3
yqz/myalgoquestions
/lowest_free_id.py
2,714
3.703125
4
#!/usr/bin/python """ QUESTION: Give an array of ids, find the minimum non-negative id that is not in the array. Example: [3,1,0,2,5], the min value should 4 that is not in the list. """ def partition(a, l, h, x): """ Partition function that will make elements that are less than x on one side of the array. And the other side will be greater or equal to x. return the index of first element on the right side""" i = j = l # [l, j) contains elemnts less than x. # [j, i) contains elements greater or equal to x for i in range(l, h): if a[i] <= x: temp = a[i] a[i] = a[j] a[j] = temp j += 1 return j def _lowest_free_id(a, s, h): if s==h: return s mid = (s + h)/2 p = partition(a, s, h, mid) if p - s < mid - s + 1: return _lowest_free_id(a, s, p) elif p - s == mid - s + 1: return _lowest_free_id(a, p, h) else: assert False def lowest_free_id(a): return _lowest_free_id(a, 0, len(a)) import unittest class MyUnitTest(unittest.TestCase): def setUp(self): pass def test_func(self): a = [0,1,2,3,4,5,6,7] self.assertEqual(partition(a, 0, 8, 4), 5) self.assertEqual(0, len([x for x in a[0:5] if x > 4])) self.assertEqual(0, len([x for x in a[5:] if x <= 4])) a.sort() self.assertEqual([0,1,2,3,4,5,6,7], a) a = [1,0,3,2,4,6,7,5] self.assertEqual(partition(a, 0, 8, 4), 5) self.assertEqual(0, len([x for x in a[0:5] if x > 4])) self.assertEqual(0, len([x for x in a[5:] if x <= 4])) a.sort() self.assertEqual([0,1,2,3,4,5,6,7], a) def test_func2(self): #import random #a = [0,2,3,4,5,6,7,8] #self.assertEqual(1, lowest_free_id(a)) #for i in range(10): # random.shuffle(a) # self.assertEqual(1, lowest_free_id(a)) #a = [1,2,3] #self.assertEqual(0, lowest_free_id(a)) #for i in range( 0): # random.shuffle(a) # self.assertEqual(0, lowest_free_id(a)) #a = [3,5,6,7,1,2] #self.assertEqual(0, lowest_free_id(a)) a = [3,0,5,6,7,1,2] self.assertEqual(4, lowest_free_id(a)) #a = [3,0,5,6,7,1,2,4] #self.assertEqual(8, lowest_free_id(a)) #a = [0,2] #self.assertEqual(1, lowest_free_id(a)) #a = [100,12,2,3,0,1,7,6,] #self.assertEqual(4, lowest_free_id(a)) #a = [100,99,98,97] #self.assertEqual(0, lowest_free_id(a)) if __name__ == '__main__': unittest.main()
9c4d833668ad43480c2055e96b7adad916e133f5
tec109/Physo
/conversion.py
1,828
3.671875
4
units = {} class Unit: def __init__(self, unit_type, standard): self.unit_type = unit_type self.standard = standard self.variations = {} def add_variation(self, variation, conversion): self.variations[variation] = conversion def get_conversion(self, variation): return self.variations[variation] def check_valid(self, unit_type, variation): if unit_type == self.unit_type and (variation in self.variations or self.standard == variation): return True else: return False def get_unit_type(self): return self.unit_type def get_standard(self): return self.standard def setup_conversion(): time = Unit('time', 'seconds') time.add_variation('minutes', 60) time.add_variation('hours', 3600) time.add_variation('days', 86400) units['time'] = time distance = Unit('distance', 'meters') distance.add_variation('feet', 0.3048) distance.add_variation('miles', 1609.344) distance.add_variation('kilometer', 1000) units['distance'] = distance def check_valid_unit(unit_type, variation): if units[unit_type].check_valid(unit_type, variation): return True else: return False def convert(unit_type, value, current_unit, end_unit): result = value if check_valid_unit(unit_type, current_unit) and check_valid_unit(unit_type, end_unit): working_unit = units[unit_type] if current_unit != working_unit.get_standard(): result = result * working_unit.get_conversion(current_unit) if end_unit == working_unit.get_standard(): return result return result / working_unit.get_conversion(end_unit) else: print("Units are not valid") return 0 def parse(unit_string):
ee93458fbb3edd1d53ef97e897d2f380a03610f6
lungen/Project_Euler
/p15_lattice_paths_01.py
239
4
4
# -*- coding: utf-8 -*- def factorial(n): num = 1 while n >= 1: num = num * n n = n - 1 return num zaehler = factorial(40) nenner1 = factorial(20) nenner2 = factorial(20) print(zaehler / (nenner1 * nenner2))
d25e7f26e82e87a7b33e54f3d46406c79f7926ea
wduffell/cmpt120duffell
/table2.py
129
3.6875
4
# table 2 def main(): temp = "{:d} {:5b} {:5o} {:5x}" for i in range(1,21): print(temp.format(i,i,i,i)) main()
99ea204bbf14490758932a0ec092a193f8ffbd6c
ArthurBottcher/simulador_fa
/simulado_drives.py
903
3.515625
4
def drive(pi, pqb, nd, oj): from random import randint inicio_jogada = pi - pqb #de onde a bola sai jardas_ganhas = randint(0, 10) #quantia de jardas ganhas pf = inicio_jogada + jardas_ganhas objetivo = oj print("Será first down na linha de {} jardas".format(objetivo)) if pf >= objetivo: print("Conseguiu o first down") print("\nO ataque termiou na linha de {} jardas".format(pf)) elif pf < objetivo and nd != 4: nd += 1 print("A jogada terminou na linha de {}".format(pf)) print("vai para o {}° down".format(nd)) print("\nIniciando na linha de {} jardas".format(pf)) drive(pf, 0, nd, objetivo) else: print("turnover on downs") print("\nO ataque termiou na linha de {} jardas".format(pf)) pos_incial=int(input("Em que jarda o ataque inicia?")) num_drive = 1 objetivo = pos_incial + 10 drive(pos_incial, 0, num_drive, objetivo)
4e8aeb5154285d54806776a5de52938a80a4fa00
bookhub97/pythonproject
/Data Files/Ch_07_Student_Files/randomwalk.py
457
4.25
4
""" File: randomwalk.py A turtle takes a random walk. """ from turtle import Turtle import random def randomWalk(t, turns, distance = 20): for count in range(turns): degrees = random.randint(0, 270) if count % 2 == 0: t.left(degrees) else: t.right(degrees) t.forward(distance) def main(): t = Turtle() t.shape("turtle") randomWalk(t, 40, 30) if __name__ == "__main__": main()
769874043a86c67556dd961eefe10c9691dd0bf4
CucumentoJolaz/delayed-fluorescense-analysis
/test.py
276
3.53125
4
from matplotlib import pyplot as plt plt.ion() plt.plot([1,2,3]) # h = plt.ylabel('y') # h.set_rotation(0) plt.ylabel(-0.1, 0.5, 'Y label', rotation=90, verticalalignment='center', horizontalalignment='right', transform=plt.ylabel.transAxes) plt.draw()
8786be597cb08d22b49e903f4e0a7c77e6c75807
EricaEmmm/CodePython
/TEST/趋势科技2_凑零钱找组合_改OK暴力.py
848
3.5625
4
# 凑零钱找组合 # 输入: # 6 5 4 3 2 1 # 11 # 输出: # 12 def process(ChargeNum, targetNum): # ChargeSet = [1, 5, 10, 20, 50, 100] # ChargeList = {} # for i in range(len(ChargeNum)): # ChargeList[ChargeSet[i]] = ChargeNum[i] res = 0 for i in range(ChargeNum[0]+1): for j in range(ChargeNum[1]+1): for k in range(ChargeNum[2]+1): for m in range(ChargeNum[3]+1): for n in range(ChargeNum[4]+1): for l in range(ChargeNum[5]+1): if i+j*5+k*10+m*20+n*50+l*100 == targetNum: res += i+j+k+m+n+l return res if res else -1 if __name__ == '__main__': ChargeNum = list(map(int, input().split())) targetNum = int(input()) print(process(ChargeNum, targetNum))
ee5d93f698866e629aa092544838094fe51c7a2d
matthewzapata/python-exercises
/4.4_function_exercises.py
8,178
4.21875
4
# Define a function named is_two. It should accept one input and return True # if the passed input is either the number or the string 2, False otherwise. def is_two(x): if x == '2' or x == 2: return True else: return False print(is_two(2)) print(is_two('2')) print(is_two(3)) print('------------------') # Define a function named is_vowel. It should return True if the passed string is a vowel, False otherwise. def is_vowel(x): vowels = ['a', 'e', 'i', 'o', 'u'] if x in vowels: return True else: return False print(is_vowel('a')) print(is_vowel('o')) print(is_vowel('f')) print('--------------') # Define a function named is_consonant. It should return True if the passed string is a consonant, # False otherwise. Use your is_vowel function to accomplish this. def is_consonant(x): if is_vowel(x) == True: return False else: return True print(is_consonant('d')) print(is_consonant('c')) print(is_consonant('i')) print('---------------') # Define a function that accepts a string that is a word. # The function should capitalize the first letter of the word if the word starts with a consonant. def capital_if_con(x): if is_consonant(x[0]) == True: return x.capitalize() else: return 'Does not start with a consonant.' print(capital_if_con('hello')) print(capital_if_con('eagle')) print(capital_if_con('igloo')) print('---------------') # Define a function named calculate_tip. It should accept a tip percentage (a number between 0 and 1) # and the bill total, and return the amount to tip. def calculate_tip(bill, tip = 0.18): return '${:2f}'.format(tip * bill) print(calculate_tip(10, 0.2)) print(calculate_tip(50)) print(calculate_tip(30)) print('--------------') # Define a function named apply_discount. It should accept an original price, # and a discount percentage, and return the price after the discount is applied. def apply_discount(price, discount): sale_price = price - (price * discount) return 'The sale price of the item is ${:2f}'.format(sale_price) print(apply_discount(100, .20)) print(apply_discount(50, .10)) print(apply_discount(20, .50)) print('-----------------') # Define a function named handle_commas. It should accept a string that is a # number that contains commas in it as input, and return a number as output. def handle_commas(x): return int(x.replace(',', '')) print(handle_commas('1,000,000')) print(handle_commas('1,236,200')) print(handle_commas('1,497')) print('------------------') # Define a function named get_letter_grade. # It should accept a number and return the letter grade associated with that number (A-F). def get_letter_grade(x): if x > 88: return 'A' elif x > 80: return 'B' elif x > 67: return 'C' elif x > 60: return 'D' else: return 'F' print(get_letter_grade(88)) print(get_letter_grade(65)) print(get_letter_grade(78)) print('-----------------') # Define a function named remove_vowels that accepts a string and returns a string # with all the vowels removed. def remove_vowels(word): for letter in word: if is_vowel(letter) == True: word = word.replace(letter, '') return word print(remove_vowels('caterpillar')) print('--------------------') # Define a function named normalize_name. # It should accept a string and return a valid python identifier, that is: # anything that is not a valid python identifier should be removed # leading and trailing whitespace should be removed # everything should be lowercase # spaces should be replaced with underscores # for example: # Name will become name # First Name will become first_name # % Completed will become completed def normalize_name(name): import re name = re.sub(r'([^\s\w]|_)+', '', name) name = name.strip() name = name.lower() name = name.replace(' ', '_') return name # or this works too LETTERS = '_abcdefghijklmnopqrstuvwxyz0123456789' def normalize_name(name): name = name.lower() valid_characters = [] for character in name: if character in LETTERS: valid_characters.append(character) return ''.join(valid_characters).strip().replace(' ', '') print(normalize_name('Matthew Zapata ')) print(normalize_name('214123@#$@#$@$ksfonsondf jn jn n j j nj')) print(normalize_name('asd234*&^$%$%&(^^%*jnkb*&%^$hgjhR')) print('----------------------') # Write a function named cumsum that accepts a list of numbers and # returns a list that is the cumulative sum of the numbers in the list. def cumsum(numbers): cum_list = [] n = 0 for i in numbers: cum_list.extend([sum(numbers[0:(n + 1)])]) n += 1 return cum_list x = [1, 2, 3, 4] print(cumsum(x)) y = [1, 1, 1] print(cumsum(y)) z = [2, 4, 6, 8] print(cumsum(z)) print('-----------------------') # BONUS # Create a function named twelveto24. It should accept a string in the format 10:45am or 4:30pm # and return a string that is the representation of the time in a 24-hour format. # Bonus write a function that does the opposite. def twelveto24(time): if (time[-2] + time[-1]) == 'pm': split_time = time.split(':') if int(split_time[0]) == 12: new_time = ':'.join(split_time) new_time_no_letters = new_time.replace('pm', '') return new_time_no_letters else: new_hour = str(int(split_time[0]) + 12) split_time[0] = new_hour new_time = ':'.join(split_time) new_time_no_letters = new_time.replace('pm', '') return new_time_no_letters elif (time[-2] + time[-1]) == 'am' and (time[0] + time[1]) == '12': split_time = time.split(':') new_hour = str(int(split_time[0]) - 12) split_time[0] = new_hour new_time = ':'.join(split_time) new_time_no_letters = new_time.replace('am', '') return new_time_no_letters else: new_time_no_letters = time.replace('am', '') return new_time_no_letters print(twelveto24('11:30pm')) print('-------------------------') def twentyfourto12(time): time_split_to_list = time.split(':') if int(time_split_to_list[0]) == 0: new_hour = str(int(time_split_to_list[0]) + 12) time_split_to_list[0] = new_hour new_time = ':'.join(time_split_to_list) new_time_with_letters = new_time + 'am' return new_time_with_letters elif int(time_split_to_list[0]) == 12: new_time_with_letters = time + 'pm' return new_time_with_letters elif int(time_split_to_list[0]) == 24: new_hour = str(int(time_split_to_list[0]) - 12) time_split_to_list[0] = new_hour new_time = ':'.join(time_split_to_list) new_time_with_letters = new_time + 'am' return new_time_with_letters elif int(time_split_to_list[0]) > 12: new_hour = str(int(time_split_to_list[0]) - 12) time_split_to_list[0] = new_hour new_time = ':'.join(time_split_to_list) new_time_with_letters = new_time + 'pm' return new_time_with_letters else: new_time_with_letters = time + 'am' return new_time_with_letters print(twentyfourto12('11:00')) print('--------------------------') # Create a function named col_index. It should accept a spreadsheet column name, # and return the index number of the column. # col_index('A') returns 1 # col_index('B') returns 2 # col_index('AA') returns 27 def col_index(x): alpha_dict = {'A':1, 'B':2, 'C':3, 'D':4, 'E':5, 'F':6, 'G':7, 'H':8, 'I':9, 'J':10, 'K':11, 'L':12, 'M':13, 'N':14, 'O':15, 'P':16, 'Q':17, 'R':18, 'S':19, 'T':20, 'U':21, 'V':22, 'W':23, 'X':24, 'Y':25, 'Z':26} if len(x) > 1: col_index_mult = (len(x) - 1) * 26 n = 0 for letter in x: if letter != 'A': col_index_add = col_index_mult + (26 ** int(alpha_dict[x[n]])) n += 1 col_final = col_index_add + alpha_dict[x[-1]] return col_final else: col_final = alpha_dict[x[0]] return col_final print(col_index('A'))
a7b5facc15e7e239df0bbecbee41b74f9dddf714
maelizarova/python_geekbrains
/lesson_2/task_1/main.py
147
3.75
4
a = [1, 10] data = [1, '1', {'one': 1, 'two': 10}, (1, 10), set(a)] for el in data: print(f'Type of element {el} in data is {type(el)}')
2ddd048c20129df609d29c18a41d772352bbe52a
Luolingwei/LeetCode
/Tree/Q144_Binary Tree Preorder Traversal.py
670
3.859375
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: # Solution 1 iterative # def preorderTraversal(self, root): # return [] if not root else [root.val] + self.preorderTraversal(root.left) + self.preorderTraversal(root.right) # Solution 2 iterative def preorderTraversal(self, root): stack,ans=[root],[] while stack: node=stack.pop() if node: ans.append(node.val) stack.append(node.right) stack.append(node.left) return ans
e9ed1a3c54078a49751d065d86b0b28b4501b594
ibrahim85/match
/Lexile/lexile.py
2,359
3.84375
4
import re from collections import defaultdict from math import log from statistics import mean from nltk import sent_tokenize, regexp_tokenize class Lexile: def __init__(self, string): self.sentences = sent_tokenize(string.lower()) self.words = regexp_tokenize(string.lower(), "\w+") self.wordsFreq = defaultdict(int) self.get_frequencies() def mean_sentence_length(self): return mean([len(regexp_tokenize(i, "\w+")) for i in self.sentences]) def mean_word_freq(self): return log(mean([self.wordsFreq[i] for i in self.words]), 10) def word_count(self): return len(self.words) def get_frequencies(self): f = open("freq.txt", encoding="ISO-8859-1") while True: line = f.readline().strip() if line == '': break else: splitted = line.split(" ") self.wordsFreq[splitted[0]] = int(splitted[1]) return self.wordsFreq def get_score(self): sentence_len = self.mean_sentence_length() word_frequency = self.mean_word_freq() return 582 + 1768 * log(sentence_len, 10) - 386 * word_frequency if __name__ == "__main__": l = Lexile( """The Lexile Analyzer uses an algorithm to evaluate the reading demand — or text complexity — of books, articles and other materials. The Lexile Analyzer measures the complexity of the text by breaking down the entire piece and studying its characteristics, such as sentence length and word frequency, which represent the syntactic and semantic challenges that the text presents to a reader. The outcome is the text complexity, expressed as a Lexile measure, along with information on the word count, mean sentence length and mean log frequency. Generally, longer sentences and words of lower frequency lead to higher Lexile measures; shorter sentences and words of higher frequency lead to lower Lexile measures. Texts such as lists, recipes, poetry and song lyrics are not analyzed because they lack conventional punctuation.""") print("Lexile measure: ", l.get_score()) print("Mean Sentence Length: ", l.mean_sentence_length()) print("Mean Log Word Frequency: ", l.mean_word_freq()) print("Word Count: ", l.word_count())
6a4a13d3a1ca8135d6d1d16d1bc4dac2508cbd1a
GuiMarthe/olcourses
/PFE/Course2/maxemail.py
1,366
3.75
4
## Write a program to read through the mbox-short.txt and figure out who has ## the sent the greatest number of mail messages. The program looks for ## 'From ' lines and takes the second word of those lines as the person ## who sent the mail. The program creates a Python dictionary that maps the ## sender's mail address to a count of the number of times they appear in the file. ## After the dictionary is produced, the program reads through the dictionary ## using a maximum loop to find the most prolific committer. name = raw_input("Enter file:") if len(name) < 1 : name = "mbox-short.txt" file = open(name) lemails = dict() ll = list() for line in file : ## Creating a list if line.strip().startswith("From ") : ll.append(line.split()[1]) for email in ll: ## adding the elements from the list in the dictionary. if email in lemails : lemails[email] = lemails[email] + 1 else : lemails[email] = 1 ## Following there are tow different methods for getting the maximum "key , value" in a dictionary. The first one seems more elegant. ## Method 1 high_value = max(lemails, key=lemails.get) print high_value, lemails[high_value] ## Method 2 max_value = 0 for key in lemails : if max_value < lemails[key] : max_value = lemails[key] max_key = key print max_key, max_value
57214a3f98f652ca3204df0c4770967d2f57c984
kdunn13/Project-Euler-and-Topcoder-Solutions
/Euler-Solutions/Euler4.py
269
3.515625
4
def isPalindrome(num): num = str(num); numCopy = num; numCopy = numCopy[::-1] if(numCopy == num): return 1; return 0; max = 0; for i in range(100, 1000): for j in range(100, 1000): num = i * j if(isPalindrome(num) and num > max): max = num; print max;
fd2153cfdc6290f7079b55710f20639842e3c9dd
daniel-reich/ubiquitous-fiesta
/MbPpxYWMRihFeaNPB_9.py
142
3.96875
4
def sum_of_evens(lst): even_sum = 0 for i in lst: for x in i: if x % 2 == 0: even_sum = even_sum +x return even_sum
29cec421dd42b7f0909d04cc162afb6fecf5bb49
vikramforsk2019/FSDP_2019
/day02/sorting.py
424
3.78125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Jun 6 08:05:11 2019 @author: vikram """ student_list = [] while True: user_input = input("Enter name, age and score: ") if not user_input: break name, age, marks = user_input.split(",") print(name) student_list.append( (name, int(age), int(marks) ) ) #print(student_list) student_list.sort() print (student_list)
270dca5a2b9e70054a0086803f999a3c3ff9b0d2
JheisonBeltran/Taller-Excerism
/taller2.py
5,986
3.5625
4
# -*- coding: utf-8 -*- """ Created on Mon Apr 5 17:49:01 2021 @author: Jbeltrant """ # TALLER DE EXCERISM - CORTE 2 # EJERCICIO 1 - Binary # Convierta un número binario, representado como una cadena. def binarizar(decimal): binario = '' while decimal // 2 != 0: binario = str(decimal % 2) + binario decimal = decimal // 2 return str(decimal) + binario numero = int(input('Ingresar el número a convertir a número binario: ')) print(binarizar(numero)) # EJERCICIO 2 - Acronym # Convierte una frase en su acrónimo. def abbreviate(words, acronimo=""): """ El metodo Convierte una frase a su acrónimo. Parameters words : Palabra a abreviar Returns Retorna las siglas de las iniciales de la frase ingresada """ if "'" in words: words = words.replace("'", "") words = words.title() for letras in words: if letras.isalpha and letras.isupper(): acronimo = acronimo + letras[0].upper() return acronimo # EJERCICIO 3 - Hamming # Calcula la diferencia de Hamming entre dos hebras de ADN. def distance(strand_a, strand_b, distancia=0): """ El metodo calcula la distancia de Hamming de dos cadenas de ADN Parameters ---------- strand_a : cadena de adn strand_b : cadena de adn Returns Este metodo retorna un numero el cual es la distancia de hamming de las dos cadenas """ if len(strand_a) != len(strand_b): raise ValueError("ValueError") else: for x in range(len(strand_a)): if strand_a[x] != strand_b[x]: distancia += 1 return distancia # EJERCICIO 4 - Raindrops # Convierta un número en una cadena que depende de los factores del número. # Si el número tiene 3 como factor, salida 'Pling'. # Si el número tiene 5 como factor, salida 'Plang'. # Si el número tiene 7 como factor, salida 'Plong'. # Si el número no tiene 3, 5 o 7 como factor, # simplemente pase los dígitos del número directamente a través. def convert(number, result=""): """ El metodo convierte un número en una cadena que contenga sonidos de gotas de lluvias correspondientes a factores potenciales. Parameters ---------- number = numero a convertir. Returns Retorna una cadena de PlingPlongPlang o en su caso el mismo número """ if number % 3 == 0: result = result + "Pling" if number % 5 == 0: result = result + "Plang" if number % 7 == 0: result = result + "Plong" if number % 3 != 0 and number % 5 != 0 and number % 7 != 0: result = f"{number}" return result # EJERCICIO 5 - Scrabble Score # Con una palabra, calcule la puntuación de scrabble para esa palabra. # Letter Value # A, E, I, O, U, L, N, R, S, T 1 # D, G 2 # B, C, M, P 3 # F, H, V, W, Y 4 # K 5 # J, X 8 # Q, Z 10 def score(word, puntaje=0): """ Este Metodo calcula un puntaje para una palabra, tomando puntos por letras Parameters word : palabra a calcular puntaje Returns retorna el puntaje de la palabra ingresada """ for le in word.lower(): if le in "aeioulnrst": puntaje = puntaje + 1 if le in "dg": puntaje = puntaje + 2 if le in "bcmp": puntaje = puntaje + 3 if le in "fhvwy": puntaje = puntaje + 4 if le in "k": puntaje = puntaje + 5 if le in "jx": puntaje = puntaje + 8 if le in "qz": puntaje = puntaje + 10 return puntaje # EJERCICIO 6 Pangram # Determine si una oración es un pangrama. def es_pangrama(cadena): import string cadena = cadena.lower() alfabeto = string.ascii_lowercase for letra in alfabeto: if letra not in cadena: return False return True # EJERCICIO 7 - Accumulate # Determinar correctamente el menor número de monedas que se deben dar a un # cliente de tal forma que la suma del valor de las monedas equivaldría # a la cantidad correcta de cambio. def vueltasRec(listaValoresMonedas, vueltas): minMonedas = vueltas if vueltas in listaValoresMonedas: return 1 else: for i in [m for m in listaValoresMonedas if m <= vueltas]: numeroMonedas = 1 + vueltasRec(listaValoresMonedas, vueltas-i) if numeroMonedas < minMonedas: minMonedas = numeroMonedas return minMonedas print(vueltasRec([1, 5, 10, 25], 63)) # EJERCICIO 8 - Sieve # Utilice el Tamiz de Eratosthenes para encontrar todos los primos # de 2 a un número dado. pp = 2 ps = [pp] lim = raw_input("Quieres generar números primos hasta qué número: ") while pp < int(lim): pp += 1 for a in ps: if a*a > pp: ps.append(pp) break if pp % a == 0: break # EJERCICIO 9 - Isogram # Determine si una palabra o frase es un isograma. def is_isogram(string): """ El metodo indica si una palabra es un isograma o no lo es. Parameters ---------- string : Palabra a definir Returns Retorna un true si la palabra es un isograma o false si no lo es. """ string = string.lower() for x in range(len(string)): for i in range(len(string)): if x != i and string[x] == string[i] and string[x].isalpha(): return False return True # EJERCICIO 10 - Leap # Dado un año, informe si es un año bisiesto. def bisiesto(año): if año % 4 == 0 and (año % 100 != 0 or año % 400 == 0): return 'El año %d es bisiesto.' % año else: return 'El año %d no es bisiesto.' % año try: año = int(raw_input('Ingresa un número de año: ')) print bisiesto(año) # JABT
58227893a19ef8a5c22290e46207529435254a70
pascalmcme/myprogramming
/week3/testTypes.py
604
3.859375
4
aninteger = 5 afloat = 6.7 aboolean = True astring = "hello world!" alist = ["Monday","Tuesday","Wednesday"] print("variable {} is of type: {} and the value is {}" . format('aninteger',type(aninteger),aninteger) ) print("variable {} is of type: {} and the value is {}" . format('afloat',type(afloat),afloat) ) print("variable {} is of type: {} and the value is {}" . format('aboolean',type(aboolean),aboolean) ) print("variable {} is of type: {} and the value is {}" . format('astring',type(astring),astring) ) print("variable {} is of type: {} and the value is {}" . format('alist',type(alist),alist) )
406b4b1f38f3eae373cd437d5882aa4fc499c18e
kritikyadav/Practise_work_python
/simple-basic/11.py
116
3.59375
4
a=int(input("devisor= ")) b=int(input("divident= ")) c=a//b ##where c is qutient d=a-b*c print("Reminder= ",d)
b4831b59c783594f575970e5e3def1eb2f572ab2
JLtheking/cpy5python
/promopractice/3.4.2.py
2,556
3.609375
4
def HashKey(ThisCountry): mySum = 0 for i in range(len(ThisCountry)): mySum = mySum + ord(ThisCountry[i]) ans = mySum % 373 + 1 return ans def CreateCountry(): with open("COUNTRIES.txt","r") as infile: line = infile.readline() countryArr = [] while line != "": for i in range(len(line)): if 48 <= ord(line[i]) <= 57: #check if place is digit myCountry = line[:i-1] myPopulation = line[i:] myPopulation = myPopulation[:len(myPopulation) - 2] break country = [] myHash = HashKey(myCountry) country.append(myHash) country.append(myCountry) country.append(myPopulation) countryArr.append(country) line = infile.readline() #countryArr = quick_sort(countryArr) #arrange all elements in order to their hash positions newfileArr = [] collidedArr = [] for i in range(373): newfileArr.append(" \n") for country in countryArr: #all countries currHash = country[0] if newfileArr[currHash] == " \n": #check if there is collision currCountry = country[1] currPopulation = country[2] string = currCountry + " " + currPopulation numSpaces = 49 - len(string) for i in range(numSpaces): string += " " string += "\n" #for i in range(numSpaces): # string += " " newfileArr[currHash] = string #if no collision, insert correct string into correct slot else: #collision collidedArr.append(country) for country in collidedArr: #all country objects which have collision currHash = country[0] currCountry = country[1] currPopulation = country[2] overflow = 1 overflowCheck = 1 collisionFixed = False while not collisionFixed: if (currHash + overflow) > 373: overflow = overflow - 373 #loop overflow back to start if overflowCheck > 373: print("Not enough area to store country!") quit() if newfileArr[currHash + overflow] == " \n": #check if overflow area is full string = currCountry + " " + currPopulation numSpaces = 49 - len(string) for i in range(numSpaces): string += " " string += "\n" newfileArr[currHash + overflow] = string #insert string into overflow area collisionFixed = True else: overflow = overflow + 1 overflowCheck = overflowCheck + 1 with open("NEWFILE2","w") as outfile: for line in newfileArr: outfile.write(line) ##main CreateCountry()
b0731a0db4fb006660391fb18530de1aa50f6a5b
frank217/Summer-Coding-2018
/Regular practice/ World CodeSprint 13/ Group Formation.py
4,090
3.6875
4
""" World Code sprint 13 Group formation(medium) Detail : https://www.hackerrank.com/contests/world-codesprint-13/challenges/group-formation/problem Expected output: C D E _______ C D E F G _______ no groups _______ Hulk IronMan SpiderMan Thor """ """ Runs in assessing input is O(n) making group: for each value in m Case 1: Student in same group. DO nothing O(0) Case 2: Converging two group if condition met (both student in different group) Maximum groupsize + constant addtion and look up in set O(b) + O(1) = O(b) Case 3: Add a student to a group (one is in the group the other is not) constant look up in the set and ditionary O(1) Case 4: Make a new group (Both not in same group) Constant time to make a new group O(1) So runtime analysis give about O(m * b) in the worst case which is 5 * 10^4 * 200 = 10^7 which is fast enough. """ def membersInTheLargestGroups(n, m, a, b, f, s, t): """ n = number of """ grade = {} group = {} gnum = 0 ass = {} gradeEval = {"1" : f, "2" : s,"3" : t} for i in range(n): person, g = input().split() grade[person] = g ass[person] = -1 for i in range(m): person, desire = input().split() # print(person,desire) py = ass[person] dy = ass[desire] # print (py, dy) # Both assigned to same group if py != -1 and py == dy: # print ("case 1") continue # Both assigned but to different group. Converge if possible elif py!= -1 and dy !=-1: # print("case 2") # sum of two group is less then max group count if (len(group[py]["set"]) + len(group[dy]["set"])) <= b: #Converge the two gadd = group[dy] gori = group[py] if gadd["1"] + gori["1"] > f: break if gadd["2"] + gori["2"] > s: break if gadd["3"] + gori["3"] > t: break gori["set"] = gori["set"] | gadd["set"] gori["1"] += gadd["1"] gori["2"] += gadd["2"] gori["3"] += gadd["3"] del group[dy] # Condition failed along the way move on continue # If one is already in the group and the other is not elif py!= -1 or dy !=-1: # print("case 3") # Decide which one is in the group if py != -1: gori = group[py] sadd = desire yy = py else: gori = group[dy] sadd = person yy = dy #Break condition 1 : group is at maximum count if len(gori["set"]) >= b: continue #Break condition 2 : grade is at maximum count if gori[grade[sadd]] >= gradeEval[grade[sadd]]: continue # Good to add this student to set and add 1 to grade gori["set"].add(sadd) gori[grade[sadd]] += 1 ass[sadd] = yy # Both is not in the group. Make a new group else: # print("case 4") group[gnum] = {"set": set([person,desire]),"1":0,"2":0,"3":0} group[gnum][grade[person]] += 1 group[gnum][grade[desire]] += 1 ass[person] = gnum ass[desire] = gnum gnum += 1 # print (group) #Now loop through group that satifiest the condition(max student count and above min) maxcount = 0 result = [] for i in group.values(): lset = len(i["set"]) if lset > maxcount: maxcount = lset result = [i["set"]] elif lset == maxcount: result.append(i["set"]) if maxcount < a: print ("no groups") return ans =[] for i in result: ans += list(i) ans.sort() for i in ans: print(i) return ans
9609e0b4452511e9981ab059ff0c4cee727f1524
Jeblii/Rush-Hour---Heuristics
/RushHour-Heuristics/rush_hour/main.py
2,168
3.75
4
from vehicle import Vehicle from vehicle_2 import Vehicle_2 from boards import Board from algorithms.breadth_first import breadth_first_search from algorithms.best_first import best_first_search from algorithms.random import random_search from setup import * from visualization import visualization from datetime import datetime def run_algorithm(algorithm): start_time = datetime.now() result = algorithm(init_board) stop_time = datetime.now() elapsed_time = stop_time - start_time print('Elapsed Time:', elapsed_time) return result, elapsed_time def create_board(grid, size): """ This function puts the four attributes of each vehicle in an array and loads them into the class board """ vehicles = [] for count in range(len(grid)): if size > 20: #with this number of cars, we can assume that we are dealing with a 9x9 or 12x12 x = Vehicle_2(int(grid[count][0]), int(grid[count][1]), int(grid[count][2]), int(grid[count][3])) vehicles.append(x) else: x = Vehicle(int(grid[count][0]), int(grid[count][1]), int(grid[count][2]), int(grid[count][3])) vehicles.append(x) new_board = Board(vehicles) return new_board grid = user_setup() size = len(grid) #reads the number of lines of mylist init_board = create_board(grid, size) #puts all the vehicles into a generated board algorithm = int(input("What Algorithm would you like to use: " "\nType Number 1 for Breadth First\nType Number 2 for Best First\nType Number 3 for Random\n")) if algorithm == 1: result, elapsed_time = run_algorithm(breadth_first_search) if len(result[0].get_board()) == 6: visualization(result[0], result[1], elapsed_time, 'Breadth First Search') elif algorithm == 2: result, elapsed_time = run_algorithm(best_first_search) if len(result[0].get_board()) == 6: visualization(result[0], result[1], elapsed_time, 'Best First Search') elif algorithm == 3: run_algorithm(random_search) else: print("Invalid value, please try again")
b70046a8af64c21d1d74ce1d0a140a5126911d7b
Sahilpatkar/Ethans
/KeychainShopGui.py
1,413
3.875
4
import tkinter import math L=0 def add(): global L x=int(addkey.get()) L+=x print(L) SetLabel.delete(0,L) SetLabel.insert(0,L) def remove(): global L x=int(removekey.get()) L=L-x if L>=0: print(L) SetLabel.delete(0,L) SetLabel.insert(0, L) elif L<=0: SetLabel.delete(0, L) SetLabel.insert(0,"no keys") def display(): print(L) displaykey.delete(0, L) displaykey.insert(0, L) m=tkinter.Tk() m.title("Keychain Store") label1=tkinter.Label(m,text="number of keychains to Add:",bg="crimson") label1.grid(row=0,column=1) addkey=tkinter.Entry(m) addkey.grid(row=0,column=2) button1 = tkinter.Button(m,text="Add",width=10,command=add).grid(row=0,column=3) label2=tkinter.Label(m,text="number of keychains to remove:",bg="yellow") label2.grid(row=1,column=1) removekey=tkinter.Entry(m) removekey.grid(row=1,column=2) button2 = tkinter.Button(m,text="remove",width=10,command=remove).grid(row=1,column=3) label3=tkinter.Label(m,text="number of keychains :",bg="red") label3.grid(row=2,column=1) displaykey=tkinter.Entry(m) displaykey.grid(row=2,column=2) button3 = tkinter.Button(m,text="display",width=10,command=display).grid(row=2,column=3) Input7 = tkinter.Label(m,text="keychains Updated to:",bg="lime").grid(row=4,column=1) SetLabel = tkinter.Entry(m) SetLabel.grid(row=4,column=2) m.mainloop()
9e3f58141a03f2a0441261498a75c7926b826245
k-e-v-i-n17/KevCode
/HeadsTails.py
247
3.84375
4
def heads_or_tails(text): import random #text = raw_input("start?") st= 'heads', 'tails' x=st y='Coin Flipped: ' for j in range(0,1): y+=random.choice(x) return y #if file == __main__: for i in range(0,1): print(heads_or_tails('aaa'))
c64d0705276295dd14e22a8d772d212bd187e22c
tsonnen/GMSuite
/markov.py
1,352
3.59375
4
''' 8/11/2016 Generates a name based on a list of strings using a Markov chain algorithm ''' import random class markovname: def __init__(self, nameList, order = 3): self.nameList = nameList self.table = dict() self.order = order for i in self.nameList: i = "\x02{0}\x03".format(i) self.load(i.lower()) def load(self, s): for i in range(len(s) - self.order): try: self.table[s[i:i + self.order]] except KeyError: self.table[s[i:i + self.order]] = [] self.table[s[i:i + self.order]] += s[i + self.order] def generate(self, start = None, max_length = 20): if start == None: s = "s" while(s[0] != "\x02"): s = random.choice(list(self.table.keys())) else: s = start try: nextVal = "nextVal" while len(s) < max_length: nextVal = random.choice(self.table[s[-self.order:]]) print(self.table[s[-self.order:]]) if(nextVal != "\x03"): s += nextVal else: break print(s) s = s.replace("\x02", "") except KeyError: pass return s.capitalize()
12b9e8001d934fe7a4b23ac15d1e99ca30ed2dd5
ShourjaMukherjee/Dummy
/11thcodes/Functions/ASSIGN 41 - FUNCTIONS - Prime or not (1).py
358
3.921875
4
def countf(n): count=0 for i in range(2,n/2+1): if n%i==0: count+=1 return count def prime(m): flag=False x=countf(m) if x==0: flag=True return flag m=int(raw_input("Enter Number:- ")) z=prime(m) if z==True: print m,"is a prime number." else: print m,"is not a prime number."
c8dfb4a66332126723ac0ea2da34d40628760e53
XUAN-CW/python_learning
/sundry/io/file05-文件读取-read([size]).py
535
4.15625
4
#测试文件读取 ''' 文件的读取一般使用如下三个方法: 1. read([size]) 从文件中读取 size 个字符,并作为结果返回。如果没有 size 参数,则读取整个文件。 读取到文件末尾,会返回空字符串。 2. readline() 读取一行内容作为结果返回。读取到文件末尾,会返回空字符串。 3. readlines() 文本文件中,每一行作为一个字符串存入列表中,返回该列表 ''' with open(r"e.txt","r",encoding="utf-8") as f: str = f.read(3) print(str)
59b4488c96dec07897fcaa79951a712d9f4aa40c
MananKavi/lab-practical
/src/practicals/set3/secondProg.py
445
3.921875
4
def match_word(words): wordsWithCharacter = [] for word in words: if len(word) <= 5 and (word[0] == 'm' or word[0] == 'M'): wordsWithCharacter.append(word) return wordsWithCharacter wordsList = [] listSize = int(input("Enter size of list : ")) while listSize > 0: wordsToAdd = str(input("Enter a string to add in list : ")) wordsList.append(wordsToAdd) listSize -= 1 print(match_word(wordsList))
be31e0570c295fe7bb8eefb0a0058f708e323ab4
kidddw/Item-Build-Prescriber-for-Dota-2
/training/Dota_webscraper.py
14,223
3.546875
4
#!/usr/bin/python -tt """Dota Webscraper - Import match data from www.dotabuff.com - Latest 50 matches frome the currently highest rated players - Info on - Player Name - Match Index (for url identification) - Result (Win / Loss) - Match Duration - Player Hero - List of Heroes on Both Teams - List of Final Items used by Player - List of Skills Chosen at Each Level - html read via Beautiful Soup - html parsed via regular expression searches - data dumped into a pandas dataframe and written to excel spreadsheet file """ # import libraries import urllib2 from bs4 import BeautifulSoup import time import sys import re import numpy as np import pandas as pd def read_page(url): """ Given input "url", return html as text file via Beautiful Soup """ # change user agent string hdr = { 'User-Agent' : 'Dota bot' } req = urllib2.Request(url, headers = hdr) resolve_redirects(req) # query the website and return the html to the variable 'page' page = urllib2.urlopen(req).read() # parse the html using beautiful soup and store in variable 'soup' return BeautifulSoup(page, 'html.parser') def resolve_redirects(url): """ If site returns error code 429, wait 5 seconds and try again """ try: return urllib2.urlopen(url).geturl() except urllib2.HTTPError as e: print e.code if e.code == 429: time.sleep(5); return resolve_redirects(url) raise print 'what?' def print_warning(player, url, message): """ Print a warning message related to a match with questionable data """ warning_file.write(player + '\n') warning_file.write(url + '\n') warning_file.write(message + '\n') warning_file.write('\n') def get_column_labels(): """ Return column labels used in spreadsheet """ column_labels = ['Player Name', 'Match Index', 'Result', 'Match Duration', 'Player Hero', 'Player Team'] for i in range(5): column_labels.append('Radiant Hero ' + str(i+1)) for i in range(5): column_labels.append('Dire Hero ' + str(i+1)) for i in range(5): column_labels.append('Player Item ' + str(i+1)) for i in range(25): column_labels.append('Skill Level ' + str(i+1)) return column_labels def get_info_list(player_name, match_index, match_result, match_duration, player_hero, player_team, radiant_heroes, dire_heroes, skill_levels): """ Return data associated with specific columns Note: must match order used in "get_column_labels" """ info = [player_name, match_index, match_result, match_duration, player_hero, player_team] for i in range(5): info.append(radiant_heroes[i]) for i in range(5): info.append(dire_heroes[i]) for i in range(5): info.append(item_names[i]) for i in range(25): not_found = True for j in range(4): if (i+1) in skill_levels[j]: info.append(j+1) not_found = False if not_found: info.append(0) return info def get_num_date(date): """ Return a numerical value for the date input (tuple of ints): day (ex. 2), month (ex. 12), year (ex. 2017) """ day = date[0] month = date[1] year = date[2] days_index = 10000 * year + 100 * month + day return days_index def date_string(date): string = str(date[1]) + '/' + str(date[0]) + '/' + str(date[2]) return string def get_num_month(month_abb): if month_abb == 'Jan': month = 1 if month_abb == 'Feb': month = 2 if month_abb == 'Mar': month = 3 if month_abb == 'Apr': month = 4 if month_abb == 'May': month = 5 if month_abb == 'Jun': month = 6 if month_abb == 'Jul': month = 7 if month_abb == 'Aug': month = 8 if month_abb == 'Sep': month = 9 if month_abb == 'Oct': month = 10 if month_abb == 'Nov': month = 11 if month_abb == 'Dec': month = 12 return month # =========================================================================== # # Get data for top players # =========================================================================== # # initialize dataframe, xlsx spreadsheet file, and warning log file df_matches = pd.DataFrame(columns=get_column_labels()) writer = pd.ExcelWriter('Dota_raw_data.xlsx') warning_file = open('warnings.log', 'w') # number of player pages (50 per) num_player_pages = 10 # number of match pages (50 per) num_match_pages = 10 # skip matches before most recent patch date (Day, Month, Year) patch_date = (17, 11, 2017) print # =========================================================================== # # Get indices of top {50 x num_pages} players # =========================================================================== # ind = -1 player_names = [] player_indices = [] player_names_dict = {} for i in range(1,num_player_pages+1): print 'reading leaderboard page ' + str(i) # specify the url leaderboard_page = 'https://www.dotabuff.com/players/leaderboard?page=' + str(i) # parse the html using beautiful soup soup = read_page(leaderboard_page) # get names of each player tuples = re.findall(r'(data-value=")([^"]+)(")', str(soup)) for tuple in tuples: player_names.append(tuple[1]) # search for player indices tuples = re.findall(r'(link-type-player" href="/players/)(\d+)', str(soup)) for tuple in tuples: ind = ind + 1 player_indices.append(tuple[1]) player_names_dict[tuple[1]] = player_names[ind] player_list_fname = 'player_list.dat' player_list_file = open(player_list_fname, 'w') for player_index in player_indices: player_list_file.write(player_names_dict[player_index] "\n") player_list_file.close() print for player_index in player_indices: # =========================================================================== # # Get indices of matches since latest patch (max of {50 x num_match_pages}) # =========================================================================== # match_indices = [] # get player name player_name = player_names_dict[player_index] dates = [] match_dates = {} dates_ind = -1 before_patch = True match_page_index = 0 while before_patch and (match_page_index + 1) <= num_match_pages: match_page_index = match_page_index + 1 print 'reading matches page ' + str(match_page_index) + ' of ' + player_name # specify the url matches_page = 'https://www.dotabuff.com/players/' + str(player_index) + '/matches?enhance=overview&page=' + str(match_page_index) # parse the html using beautiful soup soup = read_page(matches_page) # split into segments around the body of the page body_segments = re.split(r'tbody', str(soup)) # determine the dates of each match -- return as tuple: Day, Month, Year tuples = re.findall(r'(datetime="[^"]+" title="\w\w\w,\s)(\d\d)(\s)(\w\w\w)(\s)(\d\d\d\d)', body_segments[3]) for tuple in tuples: dates.append((int(tuple[1]), get_num_month(tuple[3]), int(tuple[5]))) # determine match indices and define dictionary for dates of each match index tuples = re.findall(r'(<a href="/matches/)(\d+)', str(soup)) for tuple in tuples: dates_ind = dates_ind + 1 match_indices.append(tuple[1]) match_dates[tuple[1]] = dates[dates_ind] # if last match occured before patch date, stop reading match list pages last_match_index = match_indices[-1] if get_num_date(match_dates[last_match_index]) <= get_num_date(patch_date): before_patch = False # =========================================================================== # # Get features from each match # =========================================================================== # for match_index in match_indices: # check if match occured after patch date if get_num_date(match_dates[match_index]) <= get_num_date(patch_date): continue # specify the url match_page = 'https://www.dotabuff.com/matches/' + str(match_index) + '/builds' # parse the html using beautiful soup soup = read_page(match_page) # separate html by segments related to each player player_segments = re.split(r'performance-artifact', str(soup)) # =========================================================================== # # Get list of heroes # =========================================================================== # # get heroes in match hero_index = -1 heroes = [] player_team = 'none' player_hero = 'none' player_info = 'none' for segment in player_segments: hero_index = hero_index + 1 # skip first segment which is header info if hero_index == 0: continue # read hero names from segments tuples = re.findall(r'(href="/heroes/)([\w-]+)', segment) if len(tuples) < 1 or len(tuples[0]) < 2: print_warning(player_name, match_page, 'no hero name') else: heroes.append(tuples[0][1]) # choose segment related to specified player as 'player_info' if re.search(player_index, segment): player_info = segment if not(len(tuples) < 1 or len(tuples[0]) < 2): player_hero = tuples[0][1] if hero_index <= 5: player_team = 'radiant' else: player_team = 'dire' # separate into Radiant (first 5) and Dire (latter 5) and sort alphabetically radiant_heroes = heroes[:5] radiant_heroes.sort() dire_heroes = heroes[5:] dire_heroes.sort() # replace all missing heroes with string label "none" while len(radiant_heroes) < 5: radiant_heroes.append('none') while len(dire_heroes) < 5: dire_heroes.append('none') # =========================================================================== # # Get win/loss result # =========================================================================== # tuples = re.findall(r'(match-result team )(\w+)', str(soup)) if len(tuples) != 1: print_warning(player_name, match_page, 'too many/few win statements found') else: winning_team = tuples[0][1] if player_team == winning_team: match_result = 'win' else: match_result = 'loss' # =========================================================================== # # Get match duration # =========================================================================== # tuples = re.findall(r'(duration">)([\d:]+)(<)', str(soup)) if len(tuples) != 1: print_warning(player_name, match_page, 'match duration not found') else: match_duration = tuples[0][1] if len(match_duration) == 5: match_duration = '0:' + match_duration # =========================================================================== # # Get (final build) items as 'item_names' # =========================================================================== # # separate final build items from all items bought (using skills section identifier) item_grouping_segments = re.split(r'skill-choices', player_info) # separate player segment by (final build) item item_segments = re.split(r'image-container-bigicon', item_grouping_segments[0]) # identify (final build) item names item_names = [] for item in item_segments: tuples = re.findall(r'(/items/)([\w-]+)(/)', item) if len(tuples) > 1: print_warning(player_name, match_page, 'too many items found') if len(tuples) == 1: item_names.append(tuples[0][1]) if len(item_names) == 0: print_warning(player_name, match_page, 'no items found') item_names.sort() # add string label "none" for no item appearing while len(item_names) < 5: item_names.append('none') # =========================================================================== # # Get skill choices # =========================================================================== # # separate player segment by skill skill_segments = re.split(r'class="skill"', player_info) # identify levels at which given skill was selected as 'skill_levels' # list of lists -- first index is which skill, second is a list of # levels that skill was chosen at skill_levels = [] for skill in skill_segments: # determine at what levels this skill was chosen tuples = re.findall(r'(class="entry\s)(\w+)(")', skill) levels_chosen = [] level = 0 for tuple in tuples: level = level + 1 if tuple[1] == 'choice': levels_chosen.append(level) if len(tuples) == 25: skill_levels.append(levels_chosen) # add empty list for a skill that was never taken while len(skill_levels) < 4: skill_levels.append([]) # =========================================================================== # # Append new match data to dataframe and update Excel spreadsheet file # =========================================================================== # print player_name, player_hero, date_string(match_dates[match_index]) print match_page print match_data = get_info_list(player_name, match_index, match_result, match_duration, player_hero, player_team, radiant_heroes, dire_heroes, skill_levels) df_match = pd.DataFrame([match_data], columns = get_column_labels()) df_matches = df_matches.append(df_match, ignore_index = True) df_matches.to_excel(writer,'Sheet1') writer.save()
893a4f0ee78caa71658281840fedcd087d90ccfb
TanyaMozoleva/python_practice
/Lectures/Lec4/p23.py
179
3.578125
4
''' complete the output ''' s = 'Dogs have masters. Cats have staff.' print('1.', s[1: 6]) print('2.', s[:2] * 3) print('3.', s[-3]) print('4.', s[4] + s[1]) print('5.', s[-4:])
2545de1cc4f615545f5a2c81cb9365de8300a3cd
sabrinayeh/hw-9
/solution.py
580
3.703125
4
destinations = [ "Space Needle", "Crater Lake", "Golden Gate Bridge", "Yosemite National Park", "Las Vegas, Nevada", "Grand Canyon National Park", "Aspen, Colorado", "Mount Rushmore", "Yellowstone National Park", "Sandpoint, Idaho", "Banff National Park", "Capilano Suspension Bridge", ] import geocoder # Declare destinations list here. # Loop through each destination. for point in destinations: g = geocoder.arcgis(point) print(point, " is located at ", g.latlng) # Get the lat-long coordinates from `geocoder.arcgis`. # Print out the place name and the coordinates.
eea2513ebd950622197e3cb6dbe909c9889a05d0
ildarkit/hw1
/deco.py
3,267
3.75
4
#!/usr/bin/env python # -*- coding: utf-8 -*- from functools import update_wrapper def disable(func): ''' Disable a decorator by re-assigning the decorator's name to this function. For example, to turn off memoization: >>> memo = disable ''' return func def decorator(deco): ''' Decorate a decorator so that it inherits the docstrings and stuff from the function it's decorating. ''' def wrapper(func): update_wrapper(deco, func) return deco return wrapper def countcalls(func): '''Decorator that counts calls made to the function decorated.''' def countwrapper(*args): countwrapper.calls += 1 return func(*args) countwrapper.calls = 0 update_wrapper(countwrapper, func) return countwrapper def memo(func): ''' Memoize a function so that it caches all return values for faster future lookups. ''' results = {} def memowrapper(*args): if not args in results: results[args] = func(*args) if hasattr(func, 'calls'): setattr(memowrapper, 'calls', func.calls) return results[args] update_wrapper(memowrapper, func) return memowrapper def n_ary(func): ''' Given binary function f(x, y), return an n_ary function such that f(x, y, z) = f(x, f(y,z)), etc. Also allow f(x) = x. ''' def wrapper(*args): length = len(args) if length > 2: return func(args[0], wrapper(*args[1:])) elif length == 2: return func(args[0], args[1]) elif length == 1: return args[0] update_wrapper(wrapper, func) return wrapper def trace(s): '''Trace calls made to function decorated. @trace("____") def fib(n): .... >>> fib(3) --> fib(3) ____ --> fib(2) ________ --> fib(1) ________ <-- fib(1) == 1 ________ --> fib(0) ________ <-- fib(0) == 1 ____ <-- fib(2) == 2 ____ --> fib(1) ____ <-- fib(1) == 1 <-- fib(3) == 3 ''' def deco(func): def tracewrapper(*args): tracewrapper.i += 1 a = ', '.join(map(repr, args)) print ''.join([s * tracewrapper.i, ' --> ', func.__name__, '(', a, ')'] ) res = func(*args) print ''.join([s * tracewrapper.i, ' <-- ', func.__name__, '(', a, ')', ' == ', str(res)] ) tracewrapper.i -= 1 return res update_wrapper(tracewrapper, func) tracewrapper.i = -1 return tracewrapper return deco @memo @countcalls @n_ary def foo(a, b): return a + b @countcalls @memo @n_ary def bar(a, b): return a * b @countcalls @trace("####") @memo def fib(n): """Some doc""" return 1 if n <= 1 else fib(n-1) + fib(n-2) def main(): print foo(4, 3) print foo(4, 3, 2) print foo(4, 3) print "foo was called", foo.calls, "times" print bar(4, 3) print bar(4, 3, 2) print bar(4, 3, 2, 1) print "bar was called", bar.calls, "times" print fib.__doc__ fib(3) print fib.calls, 'calls made' if __name__ == '__main__': main()
2597820425f822f4945723377071b4d032a7e390
Aakashdeveloper/Python_shaheela
/eightfunction.py
472
3.90625
4
def addition(a,b): print(a+b) def aakash(name): print("SayHi "+name) def addtion(a,b): return a+b def addition1(a,b): if a == 1: return a+b else: return a-b print(addition1(8,9)) #you have make function #that will take input from the user #and tell the user given value is odd or even #you have one list of names #you have to verify the user #if user is part of list you say welcom #else you have to say sorry not allowed
a32318dd906d0ba7d9a3d827e09f8b5912f9b20c
hatimmohammed369/py_string_numbers
/arithmetic.py
19,634
3.578125
4
def split_number(a): if not isinstance(a, str): raise TypeError('non-string value for parameter (a),' ' parameter (a) type:'+str(type(a))) if len(a) == 0: a = '0.0' if not a.__contains__('.'): a = a + '.0' decimal_point_index = a.find('.') return [a[0:decimal_point_index], decimal_point_index, a[decimal_point_index+1:]] def remove_zeros_from(s, where): if not isinstance(s, str): raise TypeError('non-string value for parameter (s), parameter (s) type:'+str(type(s))) if not isinstance(where, str): raise TypeError('non-string value for parameter (where), parameter (where) type:'+str(type(where))) if where != 'left' and where != 'right': raise ValueError('(where) is (left) or (right) only:'+where) if len(s) == s.count('0'): return '0' if where == 'left' and s.startswith('0'): for i in range(0, len(s)): if s[i] != '0': return s[i:] if where == 'right' and s.endswith('0'): for i in range(len(s)-1, -1, -1): if s[i] != '0': return s[0:i+1] return s def remove_all_zeros(s, is_number): if not isinstance(s, str): raise TypeError('non-string value for parameter (s), parameter (s) type:'+str(type(s))) if not isinstance(is_number, bool): raise TypeError('non-bool value for parameter (is_number), ' 'parameter (is_number) type:'+str(type(is_number))) if is_number: l = split_number(s) l[0] = remove_zeros_from(l[0], 'left') l[2] = remove_zeros_from(l[2], 'right') return l[0] + '.' + l[2] return remove_zeros_from(remove_zeros_from(s, 'right'), 'left') def number_string_type(s): if not isinstance(s, str): raise TypeError('non-string value for parameter (s), parameter (s) type:'+str(type(s))) if len(s) == 0: raise ValueError('empty string (s)') def is_real_number_string(s): if not isinstance(s, str): raise TypeError('non-string value for parameter (s), parameter (s) type:' + str(type(s))) if len(s) == 0: raise ValueError('empty string (s)') for c in s: if (c != '+') and (c != '-') and (c != '.') and \ (c != '0') and (c != '1') and (c != '2') and \ (c != '3') and (c != '4') and (c != '5') and \ (c != '6') and (c != '7') and (c != '8') and (c != '9'): return False return True if s.__contains__('.') and is_real_number_string(s): return 'R' if not s.__contains__('.') and is_real_number_string(s): return 'Z' return 'non-numeric' def fill(s, where, length): if not isinstance(s, str): raise TypeError('non-string value for parameter (s), parameter (s) type:'+str(type(s))) if not isinstance(where, str): raise TypeError('non-string value for parameter (where), parameter (where) type::'+str(type(where))) if not isinstance(length, int): raise TypeError('non-integer value for parameter (length),' ' parameter (length) type:'+str(type(length))) if where != 'left' and where != 'right': raise ValueError('(where) is (left) or (right) only:'+where) if length < len(s): raise ValueError('length can not be less than '+str(len(s))) while True: if len(s) == length: return s if where == 'left': s = '0' + s else: s = s + '0' def realize_fill(a, int_part_length, decimal_part_length): if not isinstance(a, str): raise TypeError('non-string value for parameter (a), parameter (a) type:' + str(type(a))) if number_string_type(a) == 'non-numeric': raise ValueError('string ' + a + ' contains non-numeric characters') if len(a) == 0: return ( int_part_length * '0' ) + '.' + ( decimal_part_length * '0' ) l = split_number(a) l[0] = fill(l[0], 'left', int_part_length) l[2] = fill(l[2], 'right', decimal_part_length) return l[0] + '.' + l[2] def compare(a, b): if not isinstance(a, str): raise TypeError('non-string value for parameter (a), parameter (a) type:'+str(type(a))) if not isinstance(b, str): raise TypeError('non-string value for parameter (b), parameter (b) type:'+str(type(b))) if len(a) == 0: raise ValueError('empty string (a)') if len(b) == 0: raise ValueError('empty string (b)') if number_string_type(a) == 'non-numeric': raise ValueError('string ' + a + ' contains non-numeric characters') if number_string_type(b) == 'non-numeric': raise ValueError('string ' + b + ' contains non-numeric characters') a_negative = a.startswith('-') if a_negative: a = a[1:] b_negative = b.startswith('-') if b_negative: b = b[1:] if not a.__contains__('.'): a = a + '.0' if not b.__contains__('.'): b = b + '.0' a = remove_all_zeros(a, True) b = remove_all_zeros(b, True) if a == '0.0' and b == '0.0': return 0 elif a == '0.0' and b != '0.0': return 1 if b_negative else -1 elif b == '0.0' and a != '0.0': return -1 if a_negative else 1 if not a_negative and b_negative: return 1 elif a_negative and not b_negative: return -1 a_decimal_point_index = a.find('.') b_decimal_point_index = b.find('.') int_max = max( len(a[0:a_decimal_point_index]) , len(b[0:b_decimal_point_index]) ) decimal_max = max( len(a[a_decimal_point_index+1:]) , len(b[b_decimal_point_index+1:]) ) a = realize_fill(a, int_max, decimal_max) b = realize_fill(b, int_max, decimal_max) def compare_int(n, m): for i in range(0, len(n)): n_digit = int(n[i]) m_digit = int(m[i]) if n_digit < m_digit: return -1 elif n_digit > m_digit: return 1 return 0 la = split_number(a) lb = split_number(b) int_compare = compare_int(la[0], lb[0]) if int_compare == -1: # |a| < |b| return 1 if a_negative else -1 elif int_compare == 1: # |a| > |b| return -1 if a_negative else 1 decimal_compare = compare_int(la[2], lb[2]) if decimal_compare == -1: # |a| < |b| return 1 if a_negative else -1 elif decimal_compare == 1: # |a| > |b| return -1 if a_negative else 1 return 0 def add(a, b): if not isinstance(a, str): raise TypeError('non-string value for parameter (a), parameter (a) type:'+str(type(a))) if not isinstance(b, str): raise TypeError('non-string value for parameter (b), parameter (b) type:'+str(type(b))) if len(a) == 0: raise ValueError('empty string (a)') if len(b) == 0: raise ValueError('empty string (b)') if number_string_type(a) == 'non-numeric': raise ValueError('string ' + a + ' contains non-numeric characters') if number_string_type(b) == 'non-numeric': raise ValueError('string ' + b + ' contains non-numeric characters') a_negative = a.startswith('-') if a_negative: a = a[1:] b_negative = b.startswith('-') if b_negative: b = b[1:] if not a.__contains__('.'): a = a + '.0' if not b.__contains__('.'): b = b + '.0' a = remove_all_zeros(a, True) b = remove_all_zeros(b, True) if a == '0.0' and b == '0.0': return '0.0' elif a == '0.0' and b != '0.0': return ('-' if b_negative else '') + b elif b == '0.0' and a != '0.0': return ('-' if a_negative else '') + a a_decimal_point_index = a.find('.') b_decimal_point_index = b.find('.') int_max = max(len(a[0:a_decimal_point_index]), len(b[0:b_decimal_point_index])) decimal_max = max(len(a[a_decimal_point_index + 1:]), len(b[b_decimal_point_index + 1:])) a = realize_fill(a, int_max, decimal_max) b = realize_fill(b, int_max, decimal_max) result = '' if a_negative == b_negative: carry = 0 for i in range(len(a)-1, -1, -1): if a[i] == '.': result = '.' + result continue x = str(carry + int(a[i]) + int(b[i])) if i == 0: result = x + result break if len(x) == 1: x = '0' + x result = x[1] + result carry = int(x[0]) return (a_negative * '-') + remove_all_zeros(result, True) c = compare(a, b) sign = ((c == 1 and a_negative) or (c == -1 and b_negative)) * '-' if c == -1: # |a| < |b| a, b = b, a a_map = {} for i in range(0, len(a)): if a[i] == '.': continue a_map[i] = int(a[i]) for i in range(len(a)-1, -1, -1): if a[i] == '.': result = '.' + result continue a_digit = a_map[i] b_digit = int(b[i]) if a_digit >= b_digit: result = str(a_digit - b_digit) + result else: for j in range(i, -1, -1): if a[j] == '.': continue if j == i: a_map[j] = a_map[j] + 10 result = str(a_map[j] - b_digit) + result elif a_map[j] == 0: a_map[j] = a_map[j] + 9 elif a_map[j] != 0: a_map[j] = a_map[j] - 1 break return sign + remove_all_zeros(result, True) def sub(a, b): if b.startswith('-'): b = b[1:] else: b = '-' + b return add(a, b) def mul(a, b): if not isinstance(a, str): raise TypeError('non-string value for parameter (a), parameter (a) type:'+str(type(a))) if not isinstance(b, str): raise TypeError('non-string value for parameter (b), parameter (b) type:'+str(type(b))) if len(a) == 0: raise ValueError('empty string (a)') if len(b) == 0: raise ValueError('empty string (b)') if number_string_type(a) == 'non-numeric': raise ValueError('string ' + a + ' contains non-numeric characters') if number_string_type(b) == 'non-numeric': raise ValueError('string ' + b + ' contains non-numeric characters') a_negative = a.startswith('-') if a_negative: a = a[1:] b_negative = b.startswith('-') if b_negative: b = b[1:] sign = (a_negative != b_negative) * '-' if not a.__contains__('.'): a = a + '.0' if not b.__contains__('.'): b = b + '.0' if compare(a, '0') == 0 or compare(b, '0') == 0: return '0.0' a = remove_all_zeros(a, True) la = split_number(a) n = 0 if la[2] == '0': for i in range(len(la[0])-1, -1, -1): if (la[0])[i] != '0': break n = n + 1 if la[2] != '0': n = -len(la[2]) b = remove_all_zeros(b, True) lb = split_number(b) m = 0 if lb[2] == '0': for i in range(len(lb[0]) - 1, -1, -1): if (lb[0])[i] != '0': break m = m + 1 if lb[2] != '0': m = -len(lb[2]) exponent = n + m a = remove_all_zeros(a.replace('.', ''), False) b = remove_all_zeros(b.replace('.', ''), False) c = compare(a, b) if c == -1: # |a| < |b| b, a = a, b result = '0' if a == '1' or b == '1': result = a if b == '1' else b else: for i in range(0, len(b)): if b[i] == '.' or b[i] == '0': continue b_digit = int(b[i]) inner_carry = 0 inner_result = (len(b) - (i + 1)) * '0' for j in range(len(a)-1, -1, -1): if a[j] == '.': continue x = str(inner_carry + b_digit * int(a[j])) if len(x) == 1: x = '0' + x inner_result = x[1] + inner_result inner_carry = int(x[0]) inner_result = ((inner_carry != 0) * str(inner_carry)) + inner_result result = add(result, inner_result) result = remove_zeros_from(result[0:result.find('.')], 'left') if exponent > 0: return sign + remove_all_zeros(result + (exponent * '0') + '.0', True) elif exponent < 0: exponent = -exponent if len(result) <= exponent: return remove_all_zeros(sign + '0.' + fill(result, 'left', exponent), True) for i in range(len(result)-1, -1, -1): if (len(result) - (i + 1)) == exponent: result = sign + result[0:i+1] + '.' + result[i+1:] if not result.__contains__('.'): result = result + '.0' return remove_all_zeros(result, True) return sign + result + '.0' def int_reciprocal(n, decimal_part_length): if not isinstance(n, str): raise TypeError('parameter (n) must be of type str, provided type:'+str(type(n))) if number_string_type(n) != 'Z' or n.__contains__('-') or n.__contains__('.'): raise TypeError('string '+n+' is not a positive integer string') if not isinstance(decimal_part_length, int): raise TypeError('parameter (decimal_part_length) must be of type int,' ' provided type:' + str(type(decimal_part_length))) if decimal_part_length < 0: raise ValueError('parameter (decimal_part_length) must be a positive integer') negative = n.startswith('-') if negative: n = n[1:] n = remove_zeros_from(n, 'left') if n == '0': raise ZeroDivisionError() if n == '1': return (negative * '-') + '1.0' one = '1' result = '' while True: if len(result) > decimal_part_length or one == '0': return (negative * '-') + '0.' + result[0:decimal_part_length+1] zeros = 0 while compare(one, n) == -1: # while one < n one = one + '0' zeros = zeros + 1 result = result + ((zeros-1) * '0') r = '0.0' while compare(one, n) != -1: one = sub(one, n) r = add(r, '1') r = r[0:r.find('.')] one = remove_all_zeros(one, True) if one.__contains__('.'): one = one[0:one.find('.')] result = result + r def div(a, b, decimal_part_length): if not isinstance(a, str): raise TypeError('non-string value for parameter (a), parameter (a) type:'+str(type(a))) if not isinstance(b, str): raise TypeError('non-string value for parameter (b), parameter (b) type:'+str(type(b))) if len(a) == 0: raise ValueError('empty string (a)') if len(b) == 0: raise ValueError('empty string (b)') if number_string_type(a) == 'non-numeric': raise ValueError('string ' + a + ' contains non-numeric characters') if number_string_type(b) == 'non-numeric': raise ValueError('string ' + b + ' contains non-numeric characters') a_negative = a.startswith('-') if a_negative: a = a[1:] b_negative = b.startswith('-') if b_negative: b = b[1:] if not a.__contains__('.'): a = a + '.0' if not b.__contains__('.'): b = b + '.0' a = remove_all_zeros(a, True) b = remove_all_zeros(b, True) if b == '0.0': raise ZeroDivisionError() sign = (a_negative != b_negative) * '-' if b == '1.0': return sign + a if a == '0.0': return '0.0' if a[a.find('.')+1:] == '0' and b[b.find('.')+1:] == '0': a = a[0:a.find('.')] b = b[0:b.find('.')] div_list = floordiv(a, b) return add(div_list[0], mul(div_list[1], int_reciprocal(b, decimal_part_length)) ) b_decimal_part = b[b.find('.')+1:] if b_decimal_part == '0': b = b[0:b.find('.')] return sign + mul(a, int_reciprocal(b, decimal_part_length)) new_decimal_part_length = len(b_decimal_part) if b[0:b.find('.')] == '0': b = b[b.find('.')+1:] else: b = b.replace('.', '') return sign + mul(div(a, b, decimal_part_length) , '1' + (new_decimal_part_length * '0')) def floordiv(dividend, divisor): """ Division of 2 positive integers :return: a list of the form [integer result, remainder] """ if divisor == '0': raise ZeroDivisionError() if compare(dividend, divisor) == -1: # dividen < divisor, e.g. 2/3 return ['0', dividend] if dividend == '0': return ['0', '0'] if divisor == '1': return [dividend, '0'] if dividend == divisor: return ['1', '0'] exp = 0 dividend_first_non_zero_value_index_from_left = len(dividend) - 1 divisor_first_non_zero_value_index_from_left = len(divisor) - 1 if dividend.endswith('0') or divisor.endswith('0'): dividend_exponent = 0 for i in range(len(dividend)-1, -1, -1): if dividend[i] != '0': dividend_first_non_zero_value_index_from_left = i break dividend_exponent += 1 divisor_exponent = 0 for i in range(len(divisor)-1, -1, -1): if divisor[i] != '0': divisor_first_non_zero_value_index_from_left = i break divisor_exponent += 1 exp = dividend_exponent - divisor_exponent del dividend_exponent, divisor_exponent if exp >= 0: # things like 10000/100, which equals 100/1 if dividend_first_non_zero_value_index_from_left != len(dividend) - 1: dividend = dividend[0:dividend_first_non_zero_value_index_from_left + 1] + (exp * '0') if divisor_first_non_zero_value_index_from_left != len(divisor) - 1: divisor = divisor[0:divisor_first_non_zero_value_index_from_left + 1] del dividend_first_non_zero_value_index_from_left, divisor_first_non_zero_value_index_from_left if divisor == '1': return [dividend, '0'] # things like 9999/100, exp = -2 # exp < 0, division must be done manually del exp result = '' dividend_copy = dividend x = dividend_copy[0] index = 0 while True: if compare(x, divisor) == -1: result = result + '0' if index + 1 < len(dividend_copy): x = x + dividend_copy[index+1] else: r = '0.0' while compare(x, divisor) != -1: x = add(x, '-' + divisor) r = add(r, '1') r = r[0:r.find('.')] x = x[0:x.find('.')] if x == '0': x = '' result = result + r if index + 1 < len(dividend_copy): x = x + dividend_copy[index + 1] index += 1 if index == len(dividend_copy): return [remove_zeros_from(result, 'left'), remove_zeros_from(x, 'left')]
353b76dcd5e2de7edb82ca6acc976933511e6c80
BryanBattershill/HelperScripts
/Compound interest.py
738
3.75
4
while (True): base = float(input("Base amount?")) interestRate = float(input("Interest rate?")) compound = input("Compound rate? (m/y value)") duration = input("Duration? (m/y value)") if (compound[0] == "y"): compound = int(compound[2:])*12 else: compound = int(compound[2:]) if (duration[0] == "y"): duration = int(duration[2:])*12 else: duration = int(duration[2:]) pastPayment = base; for x in range(duration//compound): thisPayment = base*(1+(interestRate*compound/12))**(x+1) print("Payment " + str(x) + ": " + str(thisPayment-pastPayment)) pastPayment = thisPayment print(base*(1+(interestRate*compound/12))**(duration//compound))
2fe9615c88fe18de01f2a08ad20eb29953776c5d
LisandroGuerra/zombies1
/Lista4/questao04.py
734
4
4
import string texto = '''The Python Software Foundation and the global Python community welcome and encourage participation by everyone. Our community is based on mutual respect, tolerance, and encouragement, and we are working to help each other live up to these principles. We want our community to be more diverse: whoever you are, and whatever your background, we welcome you.'''.lower() for x in string.punctuation: texto = texto.replace(x, " ") lista = [] for palavra in texto.split(): if palavra[0] in 'python' or palavra[-1] in 'python': lista.append(palavra) print(lista) print () print () lista = [palavra for palavra in texto.split() if palavra[0] in 'python' or palavra[-1] in 'python'] print(lista)
ccefa2e5c18ebef83ed5a95e2e308271fda298a4
rrabit42/Python-Programming
/문제해결과SW프로그래밍/Lab9-Python Function 2(random, callback)/lab9-1.py
825
3.765625
4
import turtle import random def drawSquare(): length = random.randint(50,100) for i in range(4): t.forward(length) t.left(90) def movePoint(): x = random.randrange(-300,301) y = random.randrange(-200,201) t.up() t.goto(x,y) t.down() t=turtle.Turtle() t.shape("turtle") for i in range(10): movePoint() drawSquare() ''' or import turtle import random def drawSquare(length): for i in range(4): t.forward(length) t.left(90) def movePoint(x,y): t.up() t.goto(x,y) t.down() t=turtle.Turtle() t.shape("turtle") for i in range(10): length = random.randint(50,100) x = random.randrange(-300,301) y = random.randrange(-200,201) movePoint(x,y) drawSquare(length) '''
d8496404c860e3e445ac905400299284e1a8cadb
JoeshGichon/News-App
/tests/news_articles_test.py
907
3.640625
4
import unittest from app.models import News_Articles class ArticleTest(unittest.TestCase): ''' Test Class to test the behaviour of the News_article class ''' def setUp(self): ''' Set up method that will run before every Test ''' self.new_article = News_Articles("The Associated Press","Man attacked by alligator in Hurricane Ida's floodwaters","https://abcnews.go.com/US/wireStory/man-attacked-alligator-hurricane-idas-floodwaters-79746310","https://s.abcnews.com/images/GMA/210831_gma_zee_0713_hpMain_16x9_992.jpg","2021-08-31T15:39:13Z","SLIDELL, La. -- A man was attacked by a large alligator while walking through floodwaters from Hurricane Ida and is now missing, a Louisiana sheriff said.\r\nThe 71-year-old mans wife told sheriffs dep… [+1041 chars]") def test_instance(self): self.assertTrue(isinstance(self.new_article,News_Articles))
f24a97ce06b9a0f5db26b5981338c2dbe6df06cc
archer-yang-lab/manim
/project/start.py
1,393
3.640625
4
from manimlib import * class TextExample(Scene): def construct(self): text = Text("Here is a text", font="Consolas", font_size=90) difference = Text( """ The most important difference between Text and TexText is that\n you can change the font more easily, but can't use the LaTeX grammar """, font="Arial", font_size=24, t2c={"Text": BLUE, "TexText": BLUE, "LaTeX": ORANGE} ) text2 = Tex(r'\sum_{1}^{n}\sin(x_i)') VGroup(text, difference).arrange(DOWN, buff=1) self.play(Write(text)) self.play(Write(text2)) self.play(FadeIn(difference, UP)) self.wait(3) fonts = Text( "And you can also set the font according to different words", font="Arial", t2f={"font": "Consolas", "words": "Consolas"}, t2c={"font": BLUE, "words": GREEN} ) slant = Text( "And the same as slant and weight", font="Consolas", t2s={"slant": ITALIC}, t2w={"weight": BOLD}, t2c={"slant": ORANGE, "weight": RED} ) VGroup(fonts, slant).arrange(DOWN, buff=0.8) self.play(FadeOut(text), FadeOut(difference, shift=DOWN)) self.play(Write(fonts)) self.wait() self.play(Write(slant)) self.wait()
69e5a2fa2725a0a5ebaaf0f0a13f21170b708e02
createnewdemo/istudy_test
/1.py
1,112
3.59375
4
# encoding: utf-8 # -*- coding: gbk -*- import time def display_time(func): # 装饰器 也是一个函数 接下来要运行func这个函数 def wrapper(*args): # 这个函数要写的内容是要运行的内容 :做一下计时 可传入参数 t1 = time.time() # 截取时间 result = func(*args) # 运行我要走的函数 可写返回值 t2 = time.time() # 截取另一段时间 print("Total time:{:.4}".format(t2 - t1)) # 打印总时间 return result # 返回函数结果 return wrapper def is_prime(num): if num < 2: return False elif num == 2: return True else: for i in range(2, num): if num % i == 0: return False return True @display_time def count_prime_nums(maxnum): count = 0 for i in range(2, maxnum): if is_prime(i): count = count + 1 return count count = count_prime_nums(5000) # 程序运行到这的时候 会先调用@display_time 然后运行wrapper里面的内容,然后运行本函数prime——nums print(count)
b88ce86f72c75ef8889df369918f63b612eda013
caseymacphee/Data-structures
/heap.py
2,244
3.84375
4
class Min_heap(object): def __init__(self, iterable = None): self._pile = [] self._pile.insert(0, None) self.current_size = 0 if iterable is not None: try: populate_iterable = iter(iterable) try: iterate = True while iterate: self.push(populate_iterable.next()) except StopIteration: print "Min heap populated" except: raise Exception("Object must be iterable to populate min heap") def push(self, val): if val is None: raise Exception('None type is not sortable') if '__cmp__' not in dir(val): raise Exception('Object must be comparable') self.current_size += 1 self._pile.append(val) index = len(self._pile) - 1 while self._pile[index/2] is not None and val < self._pile[index/2]: swap = self._pile[index/2] self._pile[index] = swap self._pile[index/2] = val index = index/2 def pop(self): if len(self._pile) == 1: return None elif len(self._pile) == 2: self.current_size -= 1 return self._pile.pop() else: self.current_size -= 1 min = self._pile[1] lastelement = self._pile.pop() self._pile[1] = lastelement index = 1 while (index * 2) < len(self._pile): current = self._pile[index] if (index * 2) + 1 < len(self._pile): if self._pile[index] > self._pile[index*2]: if self._pile[index] > self._pile[index*2 + 1]: if self._pile[index * 2] > self._pile[index * 2 + 1]: self._pile[index] = self._pile[index*2 + 1] self._pile[index*2 + 1] = current index = index * 2 + 1 else: self._pile[index] = self._pile[index * 2] self._pile[index * 2] = current index = index * 2 else: self._pile[index] = self._pile[index*2] self._pile[index*2] = current index = index * 2 elif self._pile[index] > self._pile[index * 2 + 1]: self._pile[index] = self._pile[index*2 + 1] self._pile[index*2 + 1] = current index = (index * 2) + 1 else: break else: if self._pile[index] > self._pile[index * 2]: self._pile[index] = self._pile[index*2] self._pile[index*2] = current index = index * 2 else: break return min def size(self): return self.current_size