blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
7b68aa8a5333bc5a7b27b6aaf6db413119d9244f
timManas/PythonProgrammingRecipes
/project/src/Functions/ReturnMultipleValues.py
1,107
4.25
4
class TestObject: def __init__(self): self.str = "HelloWorld" self.x = 10 self.y = 20 self.z = 30 pass pass def usingObject(): print("\nReturn multiple values using Object") testObj = TestObject() print("Str: ", testObj.str) print("X: ", testObj.x) print("Y: ", testObj.y) print("Z: ", testObj.z) pass def usingTuple(): print("\nReturn multiple values using Tuple") str = "Hello World" X = 10 Y = 20 Z = 30 return str, X, Y, Z # Notice how we can return multiple values in the "Return" statement def usingList(): print("\nReturn mutliple values using List") str = "Hello World" X = 10 Y = 20 Z = 30 return [str, X, Y, Z] def usingDict(): print("\nReturn multiple values using Dictionary") dict1 = dict() dict1["str"] = "Hello World" dict1["X"] = 10 dict1["Y"] = 20 dict1["Z"] = 30 return dict1 def main(): usingObject() print(usingTuple()) print(usingList()) print(usingDict()) if __name__ == '__main__': main()
485edcf3a9e86352bcb7ecacd38f3dc0613cbd14
bran0144/lab-exercise-2
/solution/solution/further-study/calculator.py
2,072
4.125
4
"""CLI application for a prefix-notation calculator.""" from arithmetic import (add, subtract, multiply, divide, square, cube, power, mod, ) def my_reduce(func, items): result = func(items[0], items[1]) for item in items[2:]: result = (func(result, item)) return result while True: try: user_input = input('Enter your equation > ') except EOFError: print('End of file! Goodbye~') break tokens = user_input.split(' ') if 'q' in tokens: print('You will exit.') break operator, *num_tokens = tokens # We have to cast each value we pass to an arithmetic function from a # a string into a numeric type. If we use float across the board, all # results will have decimal points, so let's do that for consistency. nums = [] try: for num in num_tokens: nums.append(float(num)) except ValueError: print('Error: one or more of your operands was not a number') continue # Make sure user enteres correct amount of operands if ( (operator not in ['square', 'cube'] and len(nums) < 2) or (operator == 'x+' and len(nums) < 3) ): print('Error: you did not enter enough operands') continue # A place to store the return value of the math function we call, # to give us one clear place where that result is printed. result = None if operator == '+': result = my_reduce(add, nums) elif operator == '-': result = my_reduce(subtract, nums) elif operator == '*': result = my_reduce(multiply, nums) elif operator == '/': result = my_reduce(divide, nums) elif operator == 'square': result = square(nums[0]) elif operator == 'cube': result = cube(nums[0]) elif operator == 'pow': result = my_reduce(power, nums) elif operator == 'mod': result = my_reduce(mod, nums) else: print('Error: you gave an invalid operator. Try again.') print(result)
01c1e9293b639a1c219eba7419233de92cec25ad
czx94/Algorithms-Collection
/Python/JianzhiOffer/question65_1.py
389
3.5625
4
''' construct a func add without +-*/ leetcode 371 ''' import random def solution1(n1, n2): while n2: sum = n1 ^ n2 carry = (n1 & n2) << 1 n1 = sum n2 = carry return n1 if __name__ == '__main__': for i in range(5): n1 = random.randint(0, 20) n2 = random.randint(0, 20) sum = solution1(n1, n2) print(n1, n2, sum)
cc8084e3ac3a171d74554b8c84330654009ed58f
gaohongsong/flush_me
/1.设计一个有getMin功能的栈_1.py
3,698
3.71875
4
# -*- coding:utf-8 -*- """ 题目:实现一个特殊的栈,在实现栈的基本功能的基础上,再实现返回栈中最小元素 要求: 1.pop、push、getMin操作的时间复杂度都是O(1) 2.设计的栈类型可以使用现成的栈结构 """ class MyStack(object): """ 解法二:基本栈进出操作的同时,选择性进出最小栈 入栈基本元素的同时,如果基本元素小于等于最小栈的栈顶元素,则同时入栈当前元素到最小栈 出栈基本元素的同时,如果基本元素等于(不会小于)最小栈的栈顶元素,则同时从最小栈出栈当前元素 备注:这里使用的python列表具有栈的功能,支持pop操作 """ def __init__(self): self._stack = [] self._stk_min = [] def _peek(self, stk_list): """获取栈顶元素,也就是列表最后一个元素""" return stk_list[len(stk_list) - 1] def peek(self): """返回栈顶元素""" return self._peek(self._stack) def push(self, item): """ 选择性的入栈: 入栈基本元素的同时,如果基本元素小于等于最小栈的栈顶元素,则同时入栈当前元素到最小栈 """ # 元素小于等于最小栈的栈顶元素 if not self._stk_min or item <= self._peek(self._stk_min): self._stk_min.append(item) self._stack.append(item) def pop(self): """ 选择性的出栈: 出栈基本元素的同时,如果基本元素等于最小栈的栈顶元素,则同时从最小栈出栈当前元素 """ if self.is_empty(): raise IndexError item = self._stack.pop() if item == self._peek(self._stk_min): self._stk_min.pop() return item def min(self): """ 获取栈内最小值 """ if self.is_empty(): raise IndexError return self._peek(self._stk_min) def size(self): """ 栈大小 """ return len(self._stack) def is_empty(self): """ 栈判空 """ # 这是个坑~ # return self._stack is [] return self._stack == [] def print_stack(self): """ 打印栈 """ try: print '{} --> {} --> {}'.format(self._stack, self._stk_min, self.min()) except IndexError: pass if __name__ == '__main__': """ $ python q1_stack_getMin_1.py [33] --> [33] --> 33 [33, 76] --> [33] --> 33 [33, 76, 29] --> [33, 29] --> 29 [33, 76, 29, 75] --> [33, 29] --> 29 [33, 76, 29, 75, 75] --> [33, 29] --> 29 [33, 76, 29, 75, 75, 48] --> [33, 29] --> 29 [33, 76, 29, 75, 75, 48, 51] --> [33, 29] --> 29 [33, 76, 29, 75, 75, 48, 51, 3] --> [33, 29, 3] --> 3 [33, 76, 29, 75, 75, 48, 51, 3, 25] --> [33, 29, 3] --> 3 [33, 76, 29, 75, 75, 48, 51, 3, 25, 78] --> [33, 29, 3] --> 3 [33, 76, 29, 75, 75, 48, 51, 3, 25] --> [33, 29, 3] --> 3 [33, 76, 29, 75, 75, 48, 51, 3] --> [33, 29, 3] --> 3 [33, 76, 29, 75, 75, 48, 51] --> [33, 29] --> 29 [33, 76, 29, 75, 75, 48] --> [33, 29] --> 29 [33, 76, 29, 75, 75] --> [33, 29] --> 29 [33, 76, 29, 75] --> [33, 29] --> 29 [33, 76, 29] --> [33, 29] --> 29 [33, 76] --> [33] --> 33 [33] --> [33] --> 33 """ import random s = MyStack() for i in range(10): s.push(random.randint(0, 100)) s.print_stack() while not s.is_empty(): s.pop() s.print_stack()
1af3d40db65c153853de89a98f726384ebde38aa
YuedaLin/python
/StudentManagerSystem/managerSystem.py
5,714
3.953125
4
# 需求:系统循环使用,用户输入不同的功能序号执行不同的功能 """ 步骤: 一、.定义程序入口函数 1.加载数据 2.显示功能菜单 3.用户输入功能序号 4.根据用户输入的功能序号执行不同的功能 二、.定义系统功能函数,添加、删除学院等 """ from student import * class StudentManager(): def __init__(self): # 存储数据所用的列表 self.student_list = [] # 一、程序入口函数,启动程序后执行的函数 def run(self): # 1.加载学员信息 self.load_student() while True: # 2.显示功能菜单 self.show_menu() # 3.用户输入功能序号 menu_num = int(input(('请输入您需要的功能序号:'))) # 4.根据用户输入的徐奥执行不同的功能 if menu_num == 1: # 添加学学员 self.add_student() elif menu_num == 2: # 删除学员 self.del_student() elif menu_num == 3: # 修改学员信息 self.modify_student() elif menu_num == 4: # 查询学员信息 self.search_student() elif menu_num == 5: # 显示所有学员信息 self.show_student() elif menu_num == 6: # 保存学员信息 self.save_student() elif menu_num == 7: # 退出系统 break # 二、系统功能函数 # 2.1 显示功能菜单 -- 打印序号的功能对应关系 -- 静态方法 @staticmethod def show_menu(): print('请选择如下功能:') print('1.添加学员') print('2.删除学员') print('3.修改学员信息') print('4.查询学员信息') print('5.显示所有学员信息') print('6.保存学员信息') print('7.推出系统') # 2.2添加学员 def add_student(self): # 1.用户输入姓名,性别,手机号 name = input('请输入您的姓名:') gender = input('请输入您的性别:') tel = input('请输入您的手机号码:') # 2.创建学员对象 --类在student文件里面,先导入student模块,再创建对象 student = Student(name, gender, tel) # 3.将对象添加到学员列表 self.student_list.append(student) # 测试是否添加成功 print(self.student_list) print(student) # 2.3删除学员:删除指定姓名学员 def del_student(self): # 1.用户输入目标学员姓名 del_name = input('请输入要删除的学员姓名:') # 2.如果目标学院存在则删除,否则提示学员不存在 for i in self.student_list: if i.name == del_name: self.student_list.remove(i) break else: print('查无此人') # 打印学员列表,验证删除功能 print(self.student_list) # 2.4修改学员信息 def modify_student(self): # 1.输入要修改信息的学员姓名 modify_name = input('请输入您要修改的学员的姓名:') # 2.遍历列表,有则改,无则提示 for i in self.student_list: if i.name == modify_name: i.name = input('请输入学员姓名:') i.gender = input('请输入学员性别:') i.tel = input('请输入学员手机号:') print(f'修改该学员信息成功,姓名:{i.name},性别{i.gender},手机号{i.tel}') break else: print('查无此人') # 打印学员列表,验证修改功能 print(self.student_list) # 2.5查询学员信息 def search_student(self): search_name = input('请输入您要查询的学员姓名:') for i in self.student_list: if i.name == search_name: print(f'该学员的姓名:{i.name},性别{i.gender},手机号{i.tel}') break else: print('查无此人') # 2.6显示所有学员信息 def show_student(self): # 打印表头 print('姓名\t性别\t手机号') # 打印学员数据 for i in self.student_list: print(f'{i.name}\t{i.gender}\t{i.tel}') # 2.7保存学员信息 def save_student(self): # 1.打开文件 f = open('student.data', 'w') # 2.文件写入学员数据 # 注意1:文件写入的数据不能是学员对象的内存的地址,需要把学员数据转换成列表字典数据再存储 new_list = [i.__dict__ for i in self.student_list] # [{'name': 'aa', 'gender': 'nv', 'tel': '111'}] # 注意2.文件内数据要求为字符串类型,故需要先转换数据类型为字符串才能文件写入数据 f.write(str(new_list)) # 3.关闭文件 f.close() # 2.8加载学员信息 def load_student(self): # 1.打开文件 try: f = open('student.data', 'r') except: f = open('student.data', 'w') else: # 2.读取数据:文件读取的数据是字符串,还原列表类型:[{}] 转换[学员对象] data = f.read() # 字符串 new_list = eval(data) self.student_list = [Student(i['name'], i['gender'], i['tel']) for i in new_list] finally: # 3.关闭文件 f.close()
d1aa5baa2a2eef7390ddd58720bc0d0c283327c6
lxyxl0216/sword-for-offer-solution
/codes/python/28-对称的二叉树.py
732
3.90625
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 isSymmetric(self, root): """ :type root: TreeNode :rtype: bool """ # 先写递归终止条件 if root is None: return True return self.__helper(root.left, root.right) def __helper(self, p1, p2): if p1 is None and p2 is None: return True if p1 is None or p2 is None: return False return p1.val == p2.val and self.__helper(p1.left, p2.right) and self.__helper(p1.right, p2.left)
0bcea099f189dbf2d06626999ed0d2d0d2d431d8
georgeteo/Coding_Interview_Practice
/chapter_11/11.2.py
886
4
4
''' CCC 11.2: Write a method to sort an array of strings so that all anagrams are next to each other. ''' from collections import defaultdict class anagram_hash: def __init__(self): self.dictionary = defaultdict(list) def hash_word(self, word): ''' Time Complexity: O(nlogn) # Merge sort Space Complexity: O(n) ''' key = ''.join(sorted(list(word))) self.dictionary[key].append(word) def to_list(self): ''' Time Complexity: O(n) Space Complexity: O(n) ''' master_list = [] for sublist in self.dictionary.values(): master_list = master_list + sublist return master_list if __name__=="__main__": test_list = ["abc", "cba", "bca", "def", "cde"] AH = anagram_hash() for word in test_list: AH.hash_word(word) print AH.to_list()
12d1395cb6e410c7d5856e6aabd85e746756e806
pingjuiliao/solver
/n_queen/constraint.py
1,102
3.578125
4
#!/usr/bin/python import sys from z3 import * def solve_n_queens(n) : ## message out print "solving %d queens problem" % n ## create symbols symbols = [Int("q_%d" % i) for i in range(n)] bounds_c = [ And(0 <= symbols[i], symbols[i] < n ) for i in range(n) ] rows_c = [ Distinct(symbols) ] slope_c = [ symbols[i] - symbols[j] != i - j for i in range(n-1) for j in range(i+1, n) ] slope2_c= [ symbols[j] - symbols[i] != i - j for i in range(n-1) for j in range(i+1, n) ] # solve(bounds_c + rows_c + slope_c) s = Solver() s.add(bounds_c + rows_c + slope_c + slope2_c) if s.check() == sat : m = s.model() result = [m.evaluate(symbols[i]) for i in range(n)] print result board = [["x" if result[c] == r else "o" for c in range(n)] for r in range(n) ] for row in board : print " ".join(row) else : print "UNSAT" def main() : if len(sys.argv) >= 2 : queens = int(sys.argv[1]) else : queens = 8 solve_n_queens(queens) if __name__ == '__main__' : main()
41f8299540dcbb0de546348d07f39c9a3ce15d26
meppps/PyJunk
/fourth_file.py
191
3.859375
4
user_play = "y" while user_play == "y": user_number = int(input("How many numbers? ")) for x in range(user_number): print(x) user_play = input("Continue: (y)es or (n)o")
9cea8f08ea6f044800bf331733884b59494cac76
Questandachievement7Developer/q7os
/module/Assistant/extension/WeatherPredictPythonML/aa.py
26,940
4.03125
4
#!/usr/bin/env python # coding: utf-8 # # Using Machine Learning to Predict the Weather: Part 3 # # This is the final article on using machine learning in Python to make predictions of the mean temperature based off of meteorological weather data retrieved from [Weather Underground](www.weatherunderground.com) as described in [part one](http://stackabuse.com/using-machine-learning-to-predict-the-weather-part-1/) of this series. The topic of this final article will be a to build a neural network regressor using Google's Open Source [TensorFlow](www.tensorflow.org). For a general introduction into TensorFlow as well a discussion of installation methods please see Mihajlo Pavloski's excellent post [TensorFlow Neural Network Tutorial](http://stackabuse.com/tensorflow-neural-network-tutorial/). Topics I will be covering in this article include: # # * Wrapping Your Head Around Artificial Neural Network Theory # * TensorFlow's High Level Estimator API and Pre-canned Models # * Building a DNNRegressor to Predict the Weather # ### Wrapping Your Head Around Artificial Neural Networks Theory # # In the [last article](http://stackabuse.com/using-machine-learning-to-predict-the-weather-part-2/) I described the process of building a linear regression model, a venerable machine learning technique that underlies many others, to predict the mean daily temperature in Lincoln, Nebraska. Linear regression models are extremely powerful and have been used to make numerical as well as categorical predictions since well before the term machine learning was ever coined. However, the technique has some criticisms mostly around its ridged assumption of a linear relationship between the dependent variable and the independent variable(s). # # An uncountable number of other algorithms exist in the data science and machine learning industry which overcome this assumption of linearity. One of the more popular areas of focus in recent years has been to apply [neural networks](https://en.wikipedia.org/wiki/Artificial_neural_network) to a vast array of machine learning problems. Neural networks have a powerful way of utilizing learning techniques based on both linear and non-linear operations. # # Neural networks are inspired by biological neurons in the brain which work in a complex network of interactions to transmit, collect, and learn information based off a history of the information that has been collected. The computational neural networks we are interested in are similar to the neurons of the brain in that they are a collection of neurons (nodes) that receive input signals (numerical quantities), process the input and, transmits the processed signals to other downstream agents in the network. The processing of signals as numerical quantities that pass through the neural network is a very powerful feature that is not limited to linear relationships. # # In this series I have been focusing on a specific type of machine learning called supervised learning which simply means that the models being trained are built using data that has known target outcomes that the model is trying to learn to predict. Furthermore, the type of predictions being made are numerical real values which means we are dealing with *regressor* prediction algorithms. # # Graphically, a neural network similar to the one being described in this article is shown in the image below. # # ![NeuralNetwork%20%283%29.png](attachment:NeuralNetwork%20%283%29.png) # The neural network depicted above contains an input layer on the far left representing two features, x1 and x2, that are feeding the neural network. Those two features are fed into the neural network which are processed and transmitted through two layers of neurons which are referred to as hidden layers. This depiction shows two hidden layers with each layer containing three neurons (nodes). The signal then exits the neural network and is aggregated at the output layer as a single numerical predicted value. # # Let me take a moment to explain the meaning behind the arrows signifying data being processed from node to node across the layers. Each arrow represents a mathematical transformation of a value beginning at the arrow's base which is then multiplied by a weight specific to that path. Each node within a layer will be fed a value in this way. Then all the values converging at the node are summed. It is this aggregate of multiplying by weights and summing the products that define the linear operations of a neural network I mentioned earlier. # # ![ActivationFunction%20%281%29.png](attachment:ActivationFunction%20%281%29.png) # # After summation is carried out at each node a special, non-linear, function is applied to the sum which is depicted in the image above as **Fn(...)**. This special function that introduces non-linear characteristics into a neural network is called an activation function. It is this non-linear characteristic brought about by activation functions that give multilayer neural networks their power. If it was not for the non-linearity added to the process then all layers would effectively just algebraically combine into one constant operation consisting of multiplying the inputs by some flat coefficient value (ie, a linear model). # # Alright, so that is all fine and dandy but, I hope you are wondering in the back of your mind ... ok, Adam, but how does this translate into a learning algorithm? Well the most straight forward answer to that is to evaluate the predictions being made, the output of the model y, to the actual expected values (the targets) and make a series of adjustments to the weights in a manner that improves the overall prediction accuracy. # # In the world of regressor machine learning algorithms one evaluates the accuracy by using a cost (aka, loss, or objective) function, namely the sum of squared errors (SSE). Notice that I generalized that statement to the whole continuum of machine learning, not just neural networks. In the prior article the Ordinary Least Squares algorithm accomplished just that, it found the combinations of coefficients that minimized the sum of the squared errors (ie, least squares). Our neural network regressor will do the exact same thing. It will iterate over the training data feeding in feature values, calculate the cost function (SSE) and make adjustments to the weights in a way that minimizes the cost function. This process of iteratively pushing features through the algorithm and evaluating how to adjust the weights based off the cost function is, in essence, what is known as model optimization. # # Model optimization algorithms are very important in building robust neural networks. As examples are fed through the networks architecture (ie, the width and depth) then evaluated against the cost function, the weights are adjusted. The models is said to be learning when the optimizer function identifies that a weight adjustment was made in a way that does not improve (lower) the cost function which is registered with the optimizer so that it does not adjust the weights in that direction again. # ### TensorFlow's High Level Estimator API and Pre-canned Models # # Google's TensorFlow library consists a few API's with the most popular being the Core API which gives the user a low level set of tools to define and train essentially any machine learning algorithm using symbolic operations. This is referred to as TensorFlow Core. While TensorFlow Core is an amazing API with vast application capability I will be focusing on a newer, higher level, API the TensorFlow team developed that is collectively referred to as the Estimator API. # # The TensorFlow team developed the Estimator API to make the library more accessible to the everyday developer. This high level API provides a common interface to `train(...)` models, `evaluate(...)` models, and `predict(...)` outcomes of unknown cases similar to (and influenced by) the popular Sci-Kit Learn library which is accomplished by implementing a common interface. Also, built into the high level API are a load of machine learning best practices, abstractions, and ability for scalability. # # All of this machine learning goodness brings about a set of tools implemented in the base Estimator class as well as multiple pre-canned model types that lowers the barrier to entry for using TensorFlow so it can be applied to a host of everyday problems (or opportunities). By abstracting away much of the mundane and manual aspects of things like writing training loops or dealing with sessions the developer is able to focus on more important things like rapidly trying multiple models and model architectures to find the one that best fits their need. I will be describing how to use one of the very powerful deep neural network estimators, the DNNRegressor. # ### Building a DNNRegressor to Predict the Weather # # Let me start by importing a number of different libraries that I will use to build the model # In[16]: import pandas as pd import numpy as np import tensorflow as tf from sklearn.metrics import explained_variance_score, mean_absolute_error, median_absolute_error from sklearn.model_selection import train_test_split # Now let us get our hands on the data and take a couple of peaks at it again to familiarize ourselves with it. I have placed all the code and data in my GitHub repo [here](https://github.com/amcquistan/WeatherPredictPythonML) so that readers can follow along. # In[3]: # read in the csv data into a pandas data frame and set the date as the index df = pd.read_csv('end-part2_df.csv').set_index('date') # execute the describe() function and transpose the output so that it doesn't overflow the width of the screen df.describe().T # In[4]: # execute the info() function df.info() # Note that we have just under a 1000 records of meteorological data and that all the features are numerical in nature. Also, because of our hard work in the first article, all of the records are complete in that they are not missing (no non-nulls) any values. # # Now I will remove the mintempm and maxtempm columns as they have no meaning in helping us predict the average mean temperatures, we are predicting the future so we obviously can not have data about the future. I will also separate out the features (X) from the targets (y). # In[5]: # First drop the maxtempm and mintempm from the dataframe df = df.drop(['mintempm', 'maxtempm'], axis=1) # X will be a pandas dataframe of all columns except meantempm X = df[[col for col in df.columns if col != 'meantempm']] # y will be a pandas series of the meantempm y = df['meantempm'] # As with all supervised machine learning applications, I will be dividing my dataset into training and testing sets. However, to better explain the iterative process of training this neural network I will be using an additional dataset I will refer to as a validation set. For the training set I will be utilizing 80 percent of the data and for the testing and validation set they will each be 10% of the remaining data. To split out this data I will again be using Sci-Kit Learn's `train_test_split(...)`. # In[6]: # split data into training set and a temporary set using sklearn.model_selection.traing_test_split X_train, X_tmp, y_train, y_tmp = train_test_split(X, y, test_size=0.2, random_state=23) # In[7]: # take the remaining 20% of data in X_tmp, y_tmp and split them evenly X_test, X_val, y_test, y_val = train_test_split(X_tmp, y_tmp, test_size=0.5, random_state=23) X_train.shape, X_test.shape, X_val.shape print("Training instances {}, Training features {}".format(X_train.shape[0], X_train.shape[1])) print("Validation instances {}, Validation features {}".format(X_val.shape[0], X_val.shape[1])) print("Testing instances {}, Testing features {}".format(X_test.shape[0], X_test.shape[1])) # The first step to take in building a neural network model is to instantiate the `tf.estimator.DNNRegressor(...)` class. The class constructor has multiple parameters but I will be focusing on the following: # # * feature_columns: list-like structure containing a definition of the name and data types for the features being fed into the model # * hidden_units: list-like structure containing a definition of the number width and depth of the neural network # * optimizer: an instance of tf.Optimizer subclass which optimizes the model's weights during training; has a default is the AdaGrad optimizer. # * activation_fn: an activation function used to introduce non-linearity into the network at each layer; the default is ReLU # * model_dir: a directory to be created that will contain metadata and other checkpoint saves for the model # # I will begin by defining a list of numeric feature columns. To do this I use the `tf.feature_column.numeric_column()` function which returns a `FeatureColumn` instance for numeric, continuous, valued features. # In[8]: feature_cols = [tf.feature_column.numeric_column(col) for col in X.columns] # With the feature columns defined I can now instantiate the DNNRegressor class and store it in the regressor variable. I specify that I want a neural network that has two layers deep where both layers have a width of 50 nodes. I also indicate that I want my model data stored in a directory called *tf_wx_model*. # In[9]: regressor = tf.estimator.DNNRegressor(feature_columns=feature_cols, hidden_units=[50, 50], model_dir='tf_wx_model') # The next thing that I want to do is to define a reusable function that is generically referred to as an input function which I will call `wx_input_fn(...)`. This function will be used to feed data into my neural network during the training and testing phases. There are many different ways to build input functions but, I will be describing how to define and use one based off the `tf.estimator.inputs.pandas_input_fn(...)` since my data is in pandas data structures. # In[10]: def wx_input_fn(X, y=None, num_epochs=None, shuffle=True, batch_size=400): return tf.estimator.inputs.pandas_input_fn(x=X, y=y, num_epochs=num_epochs, shuffle=shuffle, batch_size=batch_size) # Notice that this `wx_input_fn(...)` function takes in one mandatory and four optional parameters which are then handed off to a TensorFlow input function specifically for pandas data which is returned. This is a very powerful feature of the tensorflow API (and Python and other languages that treat functions as first class citizens). # # The parameters to the function are defined as follows: # * X: the input features to be fed into one of the three DNNRegressor interface methods `train`, `evaluate`, and `predict` # * y: the target values of X, which are optional and will not be supplied to the `predict` call # * num_epochs: optional parameter. An epoch occurs when the algorithm executes over the entire dataset one time. # * shuffle: optional, specifies whether to randomly select a batch (subset) of the dataset each time the algorithm executes # * batch_size: the number of samples to include each time the algorithm executes # With our input function defined we can now train our neural network on our training dataset. For readers who are familiar with the TensorFlow high level API you will probably notice that I am being a little unconventional about how I am training my model. That is, at least from the prespective of the current tutorials on the TensorFlow website and other tutorials on the web. # # Normally you will see something like the following when one trains one of these high level API pre-canned models. # # ```(python) # regressor.train(input_fn=input_fn(training_data, num_epochs=None, shuffle=True), steps=some_large_number) # # ..... # lots of log info # .... # ``` # # Then the author will jump right into demontrating the `evaluate(...)` function and barely hint at describing what it does or why this line of code exists. # # # ```(python) # regressor.evaluate(input_fn=input_fn(eval_data, num_epochs=1, shuffle=False), steps=1) # # ..... # less log info # .... # ``` # # And after this jump straight into executing the `predict(...)` function assuming all is perfect with the trained model. # # ```(python) # predictions = regressor.predict(input_fn=input_fn(pred_data, num_epochs=1, shuffle=False), steps=1) # ``` # # For the ML newcomer reading this type of a tutorial I cringe. There is so much more thought that goes into those three lines of code that warrants more attention. This, I feel, is the only downside to having a high level API, it becomes very easy to throw together a model without understanding the key points. I hope to provide a reasonable explanation of how to train and evaluate this neural network in a way that will minimize the risk of dramatically under fitting or overfitting this model to the training data. # # So, without further delay let me define a simple training loop to train the model on the training data and evaluate it periodically on the evaluation data. # In[11]: evaluations = [] STEPS = 400 for i in range(100): regressor.train(input_fn=wx_input_fn(X_train, y=y_train), steps=STEPS) evaluation = regressor.evaluate(input_fn=wx_input_fn(X_val, y_val, num_epochs=1, shuffle=False), steps=1) evaluations.append(regressor.evaluate(input_fn=wx_input_fn(X_val, y_val, num_epochs=1, shuffle=False))) # The above loop iterates 100 times. In the body of the loop I call the `train(...)` method of the regressor object passing it my reusable `wx_input_fn(...)` which is in turn passed my training feature set and targets. I purposefully left the default parameters `num_epochs` equal to `None` which basically says, I don't care how many times you pass over the training set just keep going training the algorithm against each default `batch_size` of `400` (roughly half the size of the training set). I also left the `shuffle` parameter equal to its default value of `True` so that while training the data is selected randomly to avoid any sequential relationships in the data. The final parameter to the `train(...)` method is `steps` which I set to 400 which means the training set will be batched 400 times per loop. # # This gives me a good time to explain in a more concrete numerical way what the meaning of an epoch is. Recall from the bullets above that an epoch occurs when all the records of a training set is passed through the neural network to train exactly one time. So, if we have about 800 (797 to be exact) records in our training set and each batch selects 400 then for every two batches we have accomplished one epoch. Thus, if we iterate over the over the training set for 100 iterations of 400 steps each with a batch size of 400 (one half an epoch per batch) we get (100 x 400 / 2) 20,000 epochs. # # Now you might be wondering why I executed and `evaluate(...)` method for each iteration of the loop and captured its output in a list. First let me explain what happens each time time the `train(...)` method is fired. It selects a random batch of training records and pushes them through the network until a prediction is made, and for each record the loss function is calculated. Then based off the loss calculated the weights are adjusted according to the optimizer's logic which does a pretty good job at making adjustments towards the direction that reduces the overall loss for the next iteration. These loss values, in general as long as the learning rate is small enough, decline over time with each iteration or step. # # However, after a certain amount of these learning iterations the weights start to be influenced not just by the overall trends in the data but, also by the uninformative noise inherit in virtually all real data. At this point the network is over influenced by the idiosyncrasies of the training data and becomes unable to gereralize predictions about the overall population of data (ie, data it has not yet seen). # # This relates to the issue I mentioned earlier where many other tutorials on the high level TensorFlow API have fallen short. It is quite important to break periodically during training and evaluate how the model is generalizing to an evaluation, or validation, dataset. Lets take a moment to look at what the `evaluate(...)` function returns by looking at the first loop iteration's evaluation output. # In[12]: evaluations[0] # As you can see it outputs the average loss (Mean Squared Error) and the total loss (Sum of Squared Errors) for the step in training which for this one is the 400th step. What you will normally see in a highly trained network is a trend where both the training and evaluation losses more or less constantly decline in parallel. However, in an overfitted model at some point in time, actually at the point where over fitting starts to occur, the validation training set will cease to see reductions in the output of its `evaluate(...)` method. This is where you want to stop further training the model, preferably right before that change occurs. # # Now that we have a collection of evaluations for each of the iterations let us plot them as a function of training steps to ensure we have not over trained our model. To do so I will use a simple scatter plot from matplotlib's `pyplot` module. # In[13]: import matplotlib.pyplot as plt get_ipython().run_line_magic('matplotlib', 'inline') # manually set the parameters of the figure to and appropriate size plt.rcParams['figure.figsize'] = [14, 10] loss_values = [ev['loss'] for ev in evaluations] training_steps = [ev['global_step'] for ev in evaluations] plt.scatter(x=training_steps, y=loss_values) plt.xlabel('Training steps (Epochs = steps / 2)') plt.ylabel('Loss (SSE)') plt.show() # Cool! From the chart above it looks like after all those iterations I have not overfitted the model because the evaluation losses never exhibit a significant change in direction toward an increasing value. Now I can safely move on to making predictions based off my remaining test dataset and assess how the model does as predicting mean weather temperatures. # # Similar to the other two regressor method I have demonstrated, the `predict(...)` method requires an input_fn which I will pass in using the reusable `wx_input_fn(...)` handing it the test dataset, specifying the num_epochs to be one and shuffle to be false so that it is sequentially feed all the data to test against. # # Next I do some formating of the iterable of dicts that are returned from the `predict(...)` method so that I have a numpy array of predictions. I then use the array of predictions with the sklearn methods `explained_variance_score(...)`, `mean_absolute_error(...)`, and `median_absolute_error(...)` to measure how well the predictions fared in relation to the known targets `y_test`. This tells the developer what the predictive capabilities of the model are. # In[14]: pred = regressor.predict(input_fn=wx_input_fn(X_test, num_epochs=1, shuffle=False)) predictions = np.array([p['predictions'][0] for p in pred]) print("The Explained Variance: %.2f" % explained_variance_score( y_test, predictions)) print("The Mean Absolute Error: %.2f degrees Celcius" % mean_absolute_error( y_test, predictions)) print("The Median Absolute Error: %.2f degrees Celcius" % median_absolute_error( y_test, predictions)) # I have used the same metrics as the previous article covering the Linear Regression technique so that we can not only evaluate this model but, we can also compare them. As you can see the two models performed quite similarly with the more simple Linear Regression model being slightly better. However, an astute practitioner would certainly run several experiments varying the hyperparameters (learning rate, width and, depth) of this neural network to fine tune it a bit but, in general this is probably pretty close to the optimal model. # # This brings up a point worth mentioning, it is rarely the case, and definitely not advisable, to simply rely on one model or the most recent hot topic in the machine learning community. No two datasets are identical and no one model is king. The only way to determine the best model is to actually try them out. Then once you have identified the best model there are other trade offs to account for such as interpretability. # ### Conclusion # # This article has demonstrated how to use the TensorFlow high level API for the pre-canned Estimator subclass DNNRegressor. Along the way I have described, in a general sense, the theory of neural networks, how they are trained, and the importance of being cognizant of the dangers of overfitting a model in the process. # # To demonstrate this process of building neural networks I have built a model that is capable of predicting the mean temperature for the next day based off numerical features collected in the first article of this series. That being said, I would like to take a moment to clarify my intentions for this series. My primary objective has been not to actually build state of the art forecasting models in either the Linear Regresson article or the current one on neural networks but, my goals have been to accomplish the following: # # 1. Demonstrate the general process for undertaking an analytics (machine learning, data science, whatever...) project from data collection, data processing, exploratory data analysis, model selection, model building, and model evaluation. # 2. Demonstrate how to select meaningful features that do not violate key assumptions of the Linear Regression technique using two popular Python libraries, StatsModels and Scikit Learn. # 3. Demonstrate how to use the high level TensorFlow API and give some intuition into what is happening under all those layers of abstraction. # 4. Discuss the issues associated with over fitting a model. # 5. Explain the importance of experimenting with more than one model type to best solve a problem. # # Thank you for reading. I hope you enjoyed this series as much as I did and, as always I welcome comments and criticism. # In[ ]:
444f1b1197e7bb61bda7aaf5dfffc7edaa15cf6b
khsc96/Sudoku
/Sudoku.py
4,159
3.828125
4
# Sudoku game and solver using python # solver uses backtracking algorithm import pprint from random import shuffle, randint from copy import deepcopy board = [ [7, 8, 0, 4, 0, 0, 1, 2, 0], [6, 0, 0, 0, 7, 5, 0, 0, 9], [0, 0, 0, 6, 0, 1, 0, 7, 8], [0, 0, 7, 0, 4, 0, 2, 6, 0], [0, 0, 1, 0, 5, 0, 9, 3, 0], [9, 0, 4, 0, 6, 0, 0, 0, 5], [0, 7, 0, 3, 0, 0, 0, 1, 2], [1, 2, 0, 0, 0, 7, 4, 0, 0], [0, 4, 9, 2, 0, 6, 0, 0, 7]] empty_board = [ [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0] ] counter = 0 # Make a new game with new board def generate_filled_board(bo): empty_slot = find_empty_slot(empty_board) if not empty_slot: return True row, col = empty_slot number_list = list(range(1,10)) shuffle(number_list) for value in number_list: if (valid_input(bo, value, empty_slot)): bo[row][col] = value if generate_filled_board(bo): return True bo[row][col] = 0 print("unable to solve") return False # Solve the game def solver(bo): global counter empty_slot = find_empty_slot(bo) if not empty_slot: # Finish solving Sudoku return True row, col = empty_slot for i in range(1, 10): if valid_input(bo, i, empty_slot): bo[row][col] = i if solver(bo): return True bo[row][col] = 0 return False def find_empty_slot(bo): for i in range(len(bo)): for j in range(len(bo[0])): if bo[i][j] == 0: return (i, j) return None def valid_input(bo, input, pos): row_pos = pos[0] col_pos = pos[1] for i in range(len(bo[0])): if col_pos != i and bo[row_pos][i] == input: return False if row_pos != i and bo[i][col_pos] == input: return False box_row_pos = pos[0] // 3 box_col_pos = pos[1] // 3 for i in range(box_row_pos * 3, box_row_pos * 3 + 3): for j in range(box_col_pos * 3, box_col_pos * 3 + 3): if input == bo[i][j] and (i, j) != pos: return False return True def print_board(bo): for i in range(len(bo)): if i % 3 == 0 and i != 0: print("- - - - - - - - - - - - ") for j in range(len(bo[0])): if j % 3 == 0 and j != 0: print(" | ", end="") if j == 8: print(bo[i][j]) else: print(str(bo[i][j]) + " ", end="") def insert_number(bo, input, pos): row = pos[0] col = pos[1] if bo[row][col] != 0: print("Position filled, try another position") else: if valid_input(bo, input, pos): bo[row][col] = input else: print("Invalid input, try another number") def remove_number(bo, pos): row = pos[0] col = pos[1] number_being_removed = bo[row][col] bo[row][col] = 0 return number_being_removed # Try to make an empty half-filled board def generate_playable_board(bo): attempts = 5 global counter while attempts > 0: row, col = (randint(0,8), randint(0,8)) while bo[row][col] == 0: row, col = (randint(0,8), randint(0,8)) back_up = remove_number(bo, (row, col)) copy_board = deepcopy(bo) counter = 0 solver(copy_board) if counter != 1: bo[row][col] = back_up attempts -= 1 print_board(bo) generate_filled_board(empty_board) playable_board = deepcopy(empty_board) generate_playable_board(playable_board) print("===================================") print_board(playable_board) # print(counter) # solver(board) # print(counter) # print_board(board)
52f5de7bc705e86a0992a0ced83ca9f8b3398fef
Rider66code/PythonForEverybody
/bin/p3p_c2w4_ex_015.py
357
4.125
4
#Create a function called mult that has two parameters, the first is required and should be an integer, the second is an optional parameter that can either be a number or a string but whose default is 6. The function should return the first parameter multiplied by the second. def mult(num,sattr=6): mul_num=num*sattr return mul_num print(mult(5))
e1ebd94938b64474d79abcde011d26ba994920f4
TrySickle/Saugus
/Euler/euler7.py
508
4.0625
4
import math def isPrime(x): if x == 2 or x == 3: return True if x % 2 == 0: return False for y in range(3, x / 2, 2): if x % y == 0: return False return True counter = 2 check = 6 while True: if isPrime(check - 1): counter += 1 if counter == 10001: print check - 1 break if isPrime(check + 1): counter += 1 if counter == 10001: print check + 1 break check += 6
8cbf818524307d7f1aa7d3f1e5f8e98a9eb39d88
EliRuan/ifpi-ads-algoritmos2020
/LISTA Fábio 01_Parte 01/f1_q21.py
188
3.859375
4
#entrada temp_fahr = float(input('Digite a temperatura em °F: ')) #processamento temp_celsius = (5 * temp_fahr -160) / 9 #saída print('A temperatura em °C é:', temp_celsius)
1676ecd2614a5b80cc654a915ba5a666019ec7e6
rcmckee/InvalidPatents
/loopthroughURLlist.py
791
3.75
4
#https://docs.python.org/2.7/library/fileinput.html #file_input = testUrlList.txt #import fileinput #for line in fileinput.input(testUrlList.txt): # process(line) # print line #https://stackoverflow.com/questions/19140375/python-how-to-loop-through-a-text-file-of-urls-and-pass-all-the-urls-into-a-re #filename = testUrlList.txt #def get_lots_of_urls(filename): # with open(filename) as infile: # return [get_redirect_url(url.strip()) for url in infile] #for redirect_url in get_lots_of_urls('testUrlList.txt'): # print redirct_url #https://stackoverflow.com/questions/11726349/python-looping-through-input-file input_file = open('testUrlList.txt', 'r') count_lines = 0 for line in input_file: print line count_lines += 1 print 'number of lines:', count_lines
91767dbc91951f8a111c7947367f8ab57d3c02e5
omkar1117/pythonpractice
/user_data_list.py
862
4.34375
4
import sys name = input("Enter your First Name:") lname = input("Enter your Last Name:") email = input("Enter a valid Email:") mobile = input("Enter a Valid No:") if not name or not lname or not email or not mobile: print("You need to enter all values") sys.exit(0) l=[name, lname, email, mobile] print("Your values have been registered") print("Values Here:", l) gender = input("Enter Your Gender in the Values of M/F ::") l.append(gender) print("Values Updated Here", l) # First - Last (0 - 9) List with 10 elements. # Last - First (-10 - -1) If we have a list with 10 elements. x = l[-1] print("Element as Last index of List:", x) # pop element from Last index of List l.pop() print("Data after removing last element in List:", l) #Inserting element Gender at Starting Point of List l.insert(0, x) print("After entering data to List:", l)
9c1a126b42e855a236793ad486f6e11da92ed493
PSY31170CCNY/Class
/Justin Pearce/Final project-location.py
1,401
4.03125
4
from collections import Counter # Tried to use csv to make it easier to manage data but it can use without. e=open('data.csv','a') columnTitleRow = 'data' e.write(columnTitleRow) e=open('data.csv','r') w=e.readlines() data_set = "BRONX BROOKLYN BROOKLYN BRONX QUEENS MANHATTAN BROOKLYN MANHATTAN MANHATTAN STATEN ISLAND MANHATTAN MANHATTAN BROOKLYN QUEENS MANHATTAN BROOKLYN QUEENS BRONX BROOKLYN BROOKLYN BROOKLYNQUEENS QUEENS STATEN ISLAND QUEENS BROOKLYN QUEENS STATEN ISLAND QUEENS BROOKLYN BROOKLYN BROOKLYN QUEENS STATEN ISLAND QUEENS QUEENS QUEENS STATEN ISLAND BROOKLYN BROOKLYN BRONX BROOKLYN BROOKLYN QUEENS QUEENS BROOKLYN BRONX BRONX BROOKLYN QUEENS QUEENS BROOKLYN BRONX BROOKLYN BROOKLYN BROOKLYN STATEN ISLAND BROOKLYN" # split() returns list of all the words in the string split_it = data_set.split() # Pass the split_it list to instance of Counter class. Counter = Counter(split_it) # most_common() produces k frequently encountered # input values and their respective counts. most_occur = Counter.most_common(4) print(most_occur) # Using python I analyzed the data based on the most used location where accidents happen in the list. The data was on nyc motor vehicle collisions. Based on the data and code I concluded that most motor vehicle accidents happened in Brooklyn 22 accidents followed by Queens with 15 accidents bronx had 7 and Manhattan had 6.
fe54141115a590bbe560602ca8fec3ce9d00cd1f
Toofifty/project-euler
/python/007.py
382
3.734375
4
""" By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13. What is the 10 001st prime number? """ import timer @timer.many(5) def main(): i = 3 n = 1 while n < 10001: if not any(d for d in range(2, 2 + int(i ** 0.5)) if not i % d): n += 1 i += 2 return i - 2 main() # 104743 # 248.4870ms
7a4fcb2f35adeb7e9a356c46cf9a794512b15c4d
yichenluan/LeetCodeSolution
/backup/Python/282.py
789
3.53125
4
class Solution(object): def addOperators(self, num, target): def handler(num, candidate): if not num: if eval(candidate) == target: res.append(candidate) return for i in range(1, len(num) + 1): if num[0] == '0' and i > 1: continue handler(num[i:], candidate + '+' + num[:i]) handler(num[i:], candidate + '-' + num[:i]) handler(num[i:], candidate + '*' + num[:i]) res = list() for i in range(1, len(num) + 1): handler(num[i:], num[:i]) return res if __name__ == '__main__': num = '123' target = 6 case = Solution() print case.addOperators(num, target)
ee884175d5241aec3000ead6c27b84a08a5e1600
CSheets3/HudlPartB
/TestAPI.py
2,015
3.78125
4
import unittest import main # You could also import Json for this project and sift through the information that way # On success all cases would throw a 200 code class APITest(unittest.TestCase): def test_get_request(self): # If this test succeeds then the user would be able to look at the team information in the object # If this test does NOT succeed then the user wouldn't be able to see anything and an error would pop up if main.hudl_get_response() == 200: print('Code 200 - Test Success') def test_put_request(self): # If this test succeeds then the user would be able to create / update the object # If this test throw a 404 error then the object won't be updated. # You can call the same Put requests multiple times and get the SAME result if main.hudl_put_response() == 404: print('Code 404 - Not Found') def test_post_request(self): # If this test succeeds then the user would also be able to create / update the object # If this tests throws a 404 error then the object won't be updated # The data sent to the server with Post is stored within the request body of the http request # You can call the same Post request multiple times but will NOT get the same result if main.hudl_put_response() == 404: print ('Code 404 - Not Found') def test_delete_request(self): # If this tests succeeds then the user could delete the specified object # If this test doesn't succeed then the user would not be able to delete anything # This might throw up a 401 error as the user wouldn't be authorized to delete anything, only change it. # It may also throw up a 403 error as it's forbidden to delete the object. if main.hudl_delete_response() == 404: print('Code 404 - Not Found') # I know how API's work, but I wasn't exactly sure what Part B was asking for so I made this program in hope that # it's close
513167af78eb7771c8595f450dd004ec19863273
kennethisma/App_Brewery_Projects
/Day22_Pingpong_game/My Solution/ball.py
637
3.875
4
from turtle import Turtle import random POSITIONS = [10, -10] class Ball(Turtle): def __init__(self): super().__init__() self.shape("circle") self.color("white") self.penup() # Random start position of ball. self.yball_pos = POSITIONS[0] self.xball_pos = POSITIONS[1] self.random_position() def move(self): new_y = self.ycor() + self.yball_pos new_x = self.xcor() + self.xball_pos self.goto(new_x, new_y) def random_position(self): self.yball_pos = random.choice(POSITIONS) self.xball_pos = random.choice(POSITIONS)
2fe8907240fd02ad467312f713b5c263419d124c
Haruka0522/AtCoder
/ABC/ABC134-C.py
475
3.5
4
'''TLE解答 N = int(input()) A = [] for i in range(N): A.append(int(input())) for num,a in enumerate(A): del A[num] print(max(A)) A.insert(num,a) ''' '''TLE解答 A = [int(input()) for i in range(int(input()))] for i in range(len(A)): print(max(A[:i]+A[i+1:])) ''' #解説を見て A = [int(input()) for i in range(int(input()))] first = max(A) second = sorted(A)[-2] for i in A: if i == first: print(second) else: print(first)
5f6324aac4e9b5db450213bdf8c10966a0f445d1
nfonsang/circles
/circle.py
521
4.03125
4
# Developer A ## Create a function that computes the area of a circle def circle_area(radius): pi = 3.14 area = pi*(radius)**2 return area print("Testing the area function:") print("The area of a circle with radius=10 is: ", circle_area(10)) print("The area of a circle with radius=15 is: ", circle_area(15)) # Develope a test function for the circle_area function def test(): assert circle_area(20)==1256 print(test()) # Developer B ## Create a function that computes the circumference of a circle
0337a500938f15a2e0a714d4390024ce0ed6e2df
GeoffreyRe/Project_3_macgyver
/Map.py
2,222
3.640625
4
import pygame import json import random # class that contains methods and attributes linked with the map list class Map(object): def __init__(self): with open("ressource/map.json") as f: # transform an json file into a python object self.map_list = json.load(f) # method that find the index of the player def find_player(self): for index_line, line in enumerate(self.map_list): for index_sprite, sprite in enumerate(line): if sprite == 2: position_player_index = [index_sprite, index_line] position_player_px = [index_sprite * 56, index_line * 45] return position_player_index, position_player_px # idem for the jailer def find_jailer(self): for index_line, line in enumerate(self.map_list): for index_sprite, sprite in enumerate(line): if sprite == 3: position_jailer_index = [index_sprite - 1, index_line] return position_jailer_index # when the player moves, it changes the map list def change_map(self, previous_position, new_position): previous_position_y = previous_position[1] previous_position_x = previous_position[0] new_position_y = new_position[1] new_position_x = new_position[0] self.map_list[previous_position_y][previous_position_x] = 0 self.map_list[new_position_y][new_position_x] = 2 # "delete" the item on the map list when it is taken by the player def delete_item(self, item): self.map_list[item.index_value[1]][item.index_value[0]] = 0 # method that finds index positions which are not occupied (= 0) def random_position(self): accepted = False while not accepted: # method that gives a int between 1 and 13 position_index_x = random.randint(1, 13) position_index_y = random.randint(1, 13) if self.map_list[position_index_y][position_index_x] == 0: accepted = True return (position_index_x, position_index_y) def put_item_on_map(self, item): self.map_list[item.index_value[1]][item.index_value[0]] = item.value
e8c7b968d9da165c75348cee504db62c877eddd1
ziyuan-shen/leetcode_algorithm_python_solution
/medium/ex1344.py
267
3.578125
4
class Solution: def angleClock(self, hour: int, minutes: int) -> float: minute_angle = 360 * minutes / 60 hour_angle = (hour % 12 / 12) * 360 + 30 * minutes / 60 angle = abs(minute_angle - hour_angle) return min(angle, 360 - angle)
df9bfa0e65d4d9e90311101bde0eb90e494be895
saehyuns/hw2
/hw2n1/parDBd.py
1,527
3.734375
4
# Importing all the necessary libraries. import socket import sqlite3 from sqlite3 import Error import sys from sys import argv # A main function that takes in two commandline arguments. def Main(argv): host = argv[1]; port = argv[2]; # Store data received into datas array. datas = []; mySocket = socket.socket() mySocket.bind((str(host),int(port))) mySocket.listen(100) while(1): conn, addr = mySocket.accept() # print ("Server: Connection from " + str(addr)) data = conn.recv(1024).decode() # print("DATA:", data); if not data: return # print ("Server: recv " + str(data)); datas.append(data.split("$")[0]); datas.append(data.split("$")[1]); # Connect to sqlite database in node1 directory and execute DDL command. try: condb = sqlite3.connect(datas[0].strip('/')); cur = condb.cursor(); cur.execute(datas[1]); message = "./books.sql success.$" + host + ":" + str(port) + "$" + datas[0] + "$" + str(cur.fetchall()); condb.commit(); conn.send(message.encode()); # If there is an error, send a message back to client that it was a failure. except Error as e: print(e); message = "./books.sql failure.$" + host + ":" + str(port) + "$" + datas[0]; conn.send(message.encode()); conn.close(); # After everything, finally close the db and the connection between client / server. finally: conn.close(); # Run main function with argv parameters (commandline arguments) Main(argv);
871fe8dd09b9f625c8c41714de7d2c79fa7c5157
sp2301-bot/CSES-Python-Solutions
/Introductory Problems/Palindrome Reorder.py
644
3.53125
4
s = input() first = "" second = "" res1 = set() odd = False count = 0 for i in s: res1.add(i) for i in res1: x = s.count(i) if(x & 1): count+=1 oddc = i oddcount = x odd = True if(odd): s = s.replace(oddc,'', oddcount) oddc = oddc*oddcount if(count>1): print("NO SOLUTION") else: s = sorted(s) y = -1 j = 0 for i in range(len(s)): if(i & 1): second = second + s[i] else: first = first + s[i] second = second[::-1] if(odd): print(first + oddc + second) else: print(first + second)
b164c78326a3133b83951afdd109b2e43127c59c
daniel-reich/ubiquitous-fiesta
/F77JQs68RSeTBiGtv_17.py
299
3.65625
4
def diamond_sum(num): if num == 1: return 1 ​ mid1 = (num + 1) // 2 mid2 = ((num ** 2 - num + 1) + (num ** 2)) // 2 res = mid1 + mid2 ​ for i in range(num - 2): s = num + (num * i) + 1 e = s + num - 1 res = res + (s + e) ​ return res
c64426fd7b0eb7c726bd6c27c1209085fb776f4e
itsolutionscorp/AutoStyle-Clustering
/all_data/exercism_data/python/word-count/79ba2c6fc511491ea60fd6b8f3c99bba.py
510
3.65625
4
# wordcount.py import string def word_count(phrase): returnDict={} for word in phrase.split(): # split by spaces word=word.strip(' \n\r\t'+string.punctuation) # strip whitespace and punctuation word=word.lower() # lowercase everything if len(word)==0: # if there is nothing left, continue on to next case continue if word in returnDict.keys(): # add word to count returnDict[word] = returnDict[word] + 1 else: # add word to dictionary returnDict[word]=1 return returnDict
0900358769f1d3f70c5b1d5f50985bb4fbb13b0c
mangesh-kurambhatti/Python-Programms
/Basic_Programs/36_isArmstrong.py
449
3.84375
4
def isArmstrong(num): remiander=0; sum1=0 num1=num while num>0: remainder=num%10 sum1=sum1+(remainder*remainder*remainder) num=num//10 if num1==sum1: return True #print("Success") else: return False #print("fail") def main(): num=eval(input("Enter the number :")) if isArmstrong(num): print("{} is armstrong number".format(num)) else: print("{} is not Armstrong number".format(num)) if __name__=='__main__': main()
3ff87386a371a07b0c241d5608128b1551c1d507
tomparrish/Sandbox
/hangman.py
2,566
3.671875
4
# A Hangman style program that uses m-w.com's word of the day from urllib.request import urlopen from bs4 import BeautifulSoup import time def getword(): soup = BeautifulSoup(urlopen("https://www.merriam-webster.com/word-of-the-day"), "lxml") phrase = soup.title.string word = phrase.split()[4] word = word.lower() return word def intro_to_game(): print ("Guess mw.com's Word of the Day") print ("") time.sleep(0.5) print ("I'll give you 10 guesses.") time.sleep(0.5) def play(word): guesses = '' turns = 10 while turns > 0: failed = 0 drawFigure(turns) for char in word: if char in guesses: print (char, end = ""), else: print ("_ ", end = ""), failed += 1 print() print ("Your guesses so far: " + guesses) if failed == 0: print ("You win!") break print() guess = input("guess! ") guess = guess.lower() guesses += guess print() if guess not in word: turns -= 1 print ("Wrong") print ("You have", + turns, 'more guesses') print() return turns def drawFigure(turns): body_parts = [" | O", " | |", " | /|", " | /|\\", " | /", " | / \\"] empty_scaffold = [" +---+\n | |", " |", " |\n========="] print(empty_scaffold[0]) match turns: case 5: print(body_parts[0], empty_scaffold[1], empty_scaffold[1],sep='\n') case 4: print(body_parts[0],body_parts[1], empty_scaffold[1],sep='\n') case 3: print(body_parts[0],body_parts[2], empty_scaffold[1],sep='\n') case 2: print(body_parts[0],body_parts[3], empty_scaffold[1],sep='\n') case 1: print(body_parts[0],body_parts[3],body_parts[4],sep='\n') case 0: print(body_parts[0],body_parts[3],body_parts[5],sep='\n') case _: print(empty_scaffold[1],empty_scaffold[1],empty_scaffold[1],sep='\n') print(empty_scaffold[2]) def endgame(turns, word): if turns == 0: drawFigure(turns) print ("say uncle if you would like to see the word") answer=input() if "uncle" in answer.lower(): print() print("M-W's Word of the Day is: " + word) print() def main(): word = getword() intro_to_game() turns = play(word) endgame(turns,word) main()
33051c63776b5a4323320d4fd184d78c5915b979
rafaelperazzo/programacao-web
/moodledata/vpl_data/148/usersdata/264/86624/submittedfiles/testes.py
360
3.859375
4
# -*- coding: utf-8 -*- #COMECE AQUI ABAIXO n= int(input('Digite o número de temos:')) numerador=1 denominador=1 soma=0 while numerador<n: if numerador%2==0: soma=soma-(numerador)/(denominador**2) else: soma=soma+(numerador)/(denominador**2) numerador= numerador+1 denominador= (denominador+1)**2 print ('%.5f' %soma)
f3330eca916c4e8fe1eb620b91eef5999504b690
anarsultani97/neural-networks
/machine-learning/multiple-linear-regression/example-2-car-prices/multiple-linear-regression.py
2,154
3.8125
4
# pandas library to get the data out of csv file import pandas as pd # datetime to get the current year import datetime # PyPlot to visualize the results import matplotlib.pyplot as plt # train_test_split method from cross validation library to split the dataset into train and test parts from sklearn.cross_validation import train_test_split # label encoder and one hot encoder, to encode the categorical variables from sklearn.preprocessing import LabelEncoder, OneHotEncoder # Linear Regression model from sklearn.linear_model import LinearRegression # import the dataset # it contains non-utf-8 chars, so we gotta change encoding df = pd.read_csv('./car_ad.csv', encoding="ISO-8859-1") # remove the rows with non-utf-8 chars which is in 'model' column df = df[df['model'].str.isalnum()] # remove NaN contained rows df.dropna(inplace=True) # split the data into feature matrix and target vector # save the PRICE column to a vector TARGET_VECTOR = df['price'].values # drop PRICE column from the data frame and save it as feature matrix FEATURE_MATRIX = df.drop('price', axis=1) # convert year to age # current year year = datetime.datetime.now().year # convert years to ages FEATURE_MATRIX['year'] = year - FEATURE_MATRIX['year'] # DataFrame to multidimensional array FEATURE_MATRIX = FEATURE_MATRIX.values # ENCODING Categorical Variable # the indices of categorical variables category_indices = (0, 1, 4, 5, 7, 8) # encode labels for i in category_indices: label_encoder_X = LabelEncoder() FEATURE_MATRIX[:, i] = label_encoder_X.fit_transform(FEATURE_MATRIX[:, i]) # One hot encode the categorical values one_hot_encoder = OneHotEncoder(categorical_features=category_indices) # Encode and save it as an array FEATURE_MATRIX = one_hot_encoder.fit_transform(FEATURE_MATRIX).toarray() # split into test and train X_train, X_test, y_train, y_test = train_test_split(FEATURE_MATRIX, TARGET_VECTOR, test_size=1/4, random_state=42) # initializing Linear Model model = LinearRegression() # fitting model.fit(X_train, y_train) # predict predictions = model.predict(X_test) # visualize plt.scatter(y_test, predictions) plt.show()
3965974695dbf3444df66b78117facc5c8dcf430
motiondepp/SmallReptileTraining
/ConcurrentSpider/demo_thread.py
1,173
3.734375
4
import _thread import time ''' Python 3.X _thread 模块演示 Demo 当注释掉 self.lock.acquire() 和 self.lock.release() 后运行代码会发现最后的 count 为 467195 等,并发问题。 当保留 self.lock.acquire() 和 self.lock.release() 后运行代码会发现最后的 count 为 1000000,锁机制保证了并发。 time.sleep(5) 就是为了解决 _thread 模块的诟病,注释掉的话子线程没机会执行了 ''' class ThreadTest(object): def __init__(self): self.count = 0 self.lock = None def runnable(self): self.lock.acquire() print('thread ident is '+str(_thread.get_ident())+', lock acquired!') for i in range(0, 100000): self.count += 1 print('thread ident is ' + str(_thread.get_ident()) + ', pre lock release!') self.lock.release() def test(self): self.lock = _thread.allocate_lock() for i in range(0, 10): _thread.start_new_thread(self.runnable, ()) if __name__ == '__main__': test = ThreadTest() test.test() print('thread is running...') time.sleep(5) print('test finish, count is:' + str(test.count))
3a98718ac3346b15849cb4c79987afc72b0ff8f1
gpuweb/gpuweb
/tools/extract-idl-index.py
2,165
3.515625
4
#!/usr/bin/env python3 # Extracts the text from the "IDL Index" section of a Bikeshed HTML file. # Does so by first finding the "IDL Index" header <h2> element, then printing # all the text inside the following <pre> element. import argparse from datetime import date from html.parser import HTMLParser HEADER = """ // Copyright (C) [{year}] World Wide Web Consortium, // (Massachusetts Institute of Technology, European Research Consortium for // Informatics and Mathematics, Keio University, Beihang). // All Rights Reserved. // // This work is distributed under the W3C (R) Software License [1] in the hope // that it will be useful, but WITHOUT ANY WARRANTY; without even the implied // warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. // // [1] http://www.w3.org/Consortium/Legal/copyright-software // **** This file is auto-generated. Do not edit. **** """.lstrip().format(year=date.today().year) class IDLIndexPrinter(HTMLParser): def __init__(self): super().__init__() # 0 = haven't found idl index yet # 1 = found idl index <h2> header # 2 = inside the <pre> block of the index # 3 = pre block ended self.search_state = 0 def handle_starttag(self, tag, attrs): if self.search_state == 0: if tag == 'h2' and ('id', 'idl-index') in attrs: self.search_state = 1 elif self.search_state == 1: if tag == 'pre': self.search_state = 2 def handle_endtag(self, tag): if self.search_state == 2: if tag == 'pre': self.search_state = 3 def handle_data(self, data): if self.search_state == 2: print(data, end='') if __name__ == '__main__': args_parser = argparse.ArgumentParser( 'Extract WebIDL from the HTML output of Bikeshed') args_parser.add_argument('htmlfile', type=argparse.FileType('r'), help='HTML output file from Bikeshed') args = args_parser.parse_args() print(HEADER) parse_and_print = IDLIndexPrinter() parse_and_print.feed(args.htmlfile.read())
b8345eba7203b7813d64ed29b968ca1a0d39f39f
MalachiBlackburn/CSC221
/Blackburn_CW_3-27-18.py
888
3.640625
4
def main(): ## my_string= "One two three four" ## #print(my_string) ## ## word_list = my_string.split() ## ## print(word_list) ## date_string = "03/27/2018" ## ## date_list = date_string.split('/') ## print(date_list) ## print("Month:", date_list[0]) ## print("Day:", date_list[1]) ## print("Year:", date_list[2]) with open('names.txt') as infile: for line in infile: line = line.rstrip('\n') line = line.strip(' ') #print(line) fName = line[0:10] lName = line[10:20] idNum = line[20: ] print(fName) print(lName) print(idNum) with open('accounts.txt', 'w')as outfile: outfile.write(fName) main()
490b086dc08524fb64bd20e4f0f74b4481469dd1
cclindsay/py3-twentyone
/blackjack.py
1,975
3.703125
4
# BlackJack Simulation - Main User Interface # Cameron Lindsay, COSC 1336 021 # December 2016 #!python3 def main(): import playhand title() playAgain = True winCount = 0 lossCount = 0 gameCount = 0 while playAgain: if playhand.PlayHand(): winCount += 1 else: lossCount += 1 gameCount += 1 choice = str(input('Would you like to play another hand? (Y/N)')) if choice[0].upper() != 'Y': playAgain = False winPercent = int((float(winCount) / float(gameCount)) * 100.0) print('That was a fun game! Thank you for playing!') print() print('Here are you Game Stats:') print() print('Total Games Played:', gameCount) print('Games Won:', winCount) print('Games Lost:', lossCount) print() print('Percentage of Games Won:', str(winPercent)+'%') if gameCount >= 5: if winPercent > 25: print('Wow, you had a solid streak there!') if winPercent > 50: print("Lady Luck is really on your side, isn't she?") if winPercent > 75: print('Were you counting cards or something??!') def title(): titles = [] titles.append('Welcome to Python3 BlackJack, by Cameron') titles.append('An ACC COSC 1336 Fall 2016 Production!') # padCount = 0 # Not used, currently using hard-coded spacing print('/'+('-'*78)+'\\') print('|'+('\\/'*39)+'|') fillGen(4) print('|'+('/\\'*8), ' '*44, ('/\\'*8)+'|') print('|'+('\\/'*8), ' '*44, ('\\/'*8)+'|') print('|'+('/\\'*8), ' ', titles[0],' ', ('/\\'*8)+'|') print('|'+('\\/'*8), ' '*44, ('\\/'*8)+'|') fillGen(4) print('|'+('/\\'*8), ' '*44, ('/\\'*8)+'|') print('|'+('\\/'*8), ' ', titles[1], ' ', ('\\/'*8)+'|') print('|'+('/\\'*8), ' '*44, ('/\\'*8)+'|') print('|'+('\\/'*8), ' '*44, ('\\/'*8)+'|') fillGen(4) print('|'+('/\\'*39)+'|') print('\\'+('-'*78)+'/') def fillGen(count): for line in range(count): if line % 2 == 0: print('|'+('/\\'*39)+'|') else: print('|'+('\\/'*39)+'|') main()
7e9f0c8c4801bcd3ead02a66213d51c50ea1abd6
xixixixixiC/LeetCode_explore
/math/13_roman_integer.py
523
3.765625
4
class solution: def reverse(self,s:str)->int: dict={'I':1,'V':5,'X':10,'L':50,'C':100,'D':500,'M':1000} s=s.replace('IV','IIII').replace('IX','VIIII') s=s.replace('XL','XXXX').replace('XC','LXXXX') s=s.replace('CD','CCCC').replace('CM','DCCCC') sum=0 for i in s: sum=sum+dict[i] return print(sum) origi=input("Give a Ramans number:") solu=solution() solu.reverse(origi) #runtime:60ms #memory:13.4MB #why input use "" double quate only instead of ''
b8d4aabf4d7ffd6d560182886b08c565aaebeafd
Deepak11python/Python_Code
/ex1_variable.py
314
3.84375
4
## Date : 01-APR-2019 ## Variable, accept input from users ## ## ## ## Name = str(input("Enter your name:")) Age = int(input("Enter your age:")) Ht = int(input("Enter your Height in cms:")) wt = int(input("Enter your Weight in KG:")) print ("Welcome Mr.", Name, "Your age is ", Age, "weight,height are", wt,Ht)
4a7104c35965d9ac751e47c80304d17675704b77
zupercat/python-projects
/weektwo/day1/zodiaccalc.py
1,957
3.984375
4
print("Hello and welcome to zupercat's almighty zodiac calculator.") while True: birth_year = input("Please state your birth year.") if birth_year.isdigit(): break print("Calculating...Beep boop...") def calculate_zodiac(birth_year): remainder = int(birth_year)%12 if remainder == 0: zodiac = "Monkey" elif remainder == 1: zodiac = "Rooster" elif remainder == 2: zodiac = "Dog" elif remainder == 3: zodiac = "Pig" elif remainder == 4: zodiac = "Mouse" elif remainder == 5: zodiac = "Ox" elif remainder == 6: zodiac = "Tiger" elif remainder == 7: zodiac = "Rabbit" elif remainder == 8: zodiac = "Dragon" elif remainder == 9: zodiac = "Snake" elif remainder == 10: zodiac = "Horse" elif remainder == 11: zodiac = "Sheep" else: zodiac = "Non existant thing" return (zodiac) def display_photo(animal): from PIL import Image if animal=="Monkey": im = Image.open("zodiacpic/monkey.png") im.show() elif animal=="Rooster": im = Image.open("zodiacpic/rooster.png") im.show() elif animal=="Dog": im = Image.open("zodiacpic/dog.png") im.show() elif animal=="Pig": im = Image.open("zodiacpic/pig.png") im.show() elif animal=="Mouse": im = Image.open("zodiacpic/mouse.png") im.show() elif animal=="Ox": im = Image.open("zodiacpic/ox.png") im.show() elif animal=="Tiger": im = Image.open("zodiacpic/tiger.png") im.show() elif animal=="Rabbit": im = Image.open("zodiacpic/rabbit.png") im.show() elif animal=="Dragon": im = Image.open("zodiacpic/dragon.png") im.show() elif animal=="Snake": im = Image.open("zodiacpic/snake.png") im.show() elif animal=="Horse": im = Image.open("zodiacpic/horse.png") im.show() elif animal=="Sheep": im = Image.open("zodiacpic/sheep.png") im.show() else: print("You don't have a photo.") zodiac = calculate_zodiac(birth_year) print(" ") print("You are born in the year of the", zodiac+"!") print(" ") display_photo(zodiac)
282ece308538c6a47e39d90207863a358d2f0905
bakunobu/exercise
/python_programming /Chapter_1.3/checker_board.py
600
4.21875
4
""" Составьте программу checkerboardру, получающую один аргумент ко­мандной строки n и использующую вложенный цикл для вывода двумер­ного узора n х n, наподобие шахматной доски с чередующимися пробела­ми и звездочками. """ def checker_board(n): for x in range(n): if x % 2 == 0: print(* list('*' * n), sep=' ') else: print(' ', end='') print(* list('*' * (n - 1)), sep=' ')
be03b82424accd320e3c1d62b54225cf929f3a48
Danieldev28/Leap_year
/my_test.py
533
3.8125
4
# # test to check if two values are equal # def test(actual,expected): # assert actual == expected, "So here {} was not equal to {} as expected".format(actual,expected) # print("passed all tests!") assert leap_year("") == False, "not an even number" assert leap_year("somthing") == False, "Please enter a number" assert leap_year([1,2,3,4,5]) == False,"numbers exceed number limit" assert leap_year(-1567) == False, "This is a negeative number" assert leap_year(1234.5) == False, "No decimals allowed" print("all tests passed!")
f4a1641318e9fd9896775ab1a9a9997d504bc7ce
dbsehgus94/Pythonstudy
/PythonTest/test_281-290.py
1,545
4
4
class Car: def __init__(self, wheel, price): self.wheel = wheel self.price = price def info(self): print("바퀴수", self.wheel) print("가격", self.price) #car = Car(2, 1000) #print(car.wheel) #print(car.price) class Bicycle(Car): def __init__(self, wheel, price, drivetrain): super().__init__(wheel, price) # = Car.__init__(wheel, price) #self.wheel = wheel #self.price = price self.drivetrain = drivetrain def info(self): super().info() print("구동계", self.drivetrain) class Autocar(Car): def __init__(self, wheel, price): super().__init__(wheel, price) #bicycle = Bicycle(2, 100, "시마노") #print(bicycle.drivetrain) #print(bicycle.price) car = Autocar(4, 1000) car.info() bicycle = Bicycle(2, 100, "시마노") bicycle.info() class 부모: def 호출(self): print("부모호출") class 자식(부모): def 호출(self): print("자식호출") def 부모호출(self): super().호출() 나 = 자식() 나.호출() class 부모: def __init__(self): print("부모생성") class 자식(부모): def __init__(self): print("자식생성") #self.손자 = 손자 #print(self.손자) 나 = 자식() class 부모: def __init__(self): print("부모생성") class 자식(부모): def __init__(self): print("자식생성") super().__init__() 나 = 자식()
b63ca0fb6d9b54a0bf8a11b16f442411be373069
elp2/advent_of_code_2019
/6/6.py
2,123
3.921875
4
class Orbits: def __init__(self, filename): self.planets = {} self.add_orbits(filename) def add_orbits(self, filename): lines = open(filename).readlines() for line in lines: line = line.strip() [parent, child] = line.split(')') p = self.add_planet(parent) c = self.add_planet(child) p['children'].append(c) c['parent'] = p def add_planet(self, planet): if planet not in self.planets: self.planets[planet] = {'name': planet, 'children': []} return self.planets[planet] def count_orbits(self): return self.count_orbits_recursively(self.planets['COM'], 0) def count_orbits_recursively(self, planet, depth): child_orbits = 0 for child in planet['children']: child_orbits += self.count_orbits_recursively(child, depth+1) return child_orbits + depth def san_orbits(self, planet): for child in planet['children']: if child['name'] == 'SAN': return True return False def distance_to_san(self): return self.distance_to_san_recurse(self.planets['YOU'], 0) - 1 def distance_to_san_recurse(self, planet, distance): if 'visited' in planet: return -1 planet['visited'] = True if self.san_orbits(planet): return distance if 'parent' in planet: parent_distance = self.distance_to_san_recurse(planet['parent'], distance + 1) if parent_distance != -1: return parent_distance for child in planet['children']: child_distance = self.distance_to_san_recurse(child, distance + 1) if child_distance != -1: return child_distance return -1 def test(): orbits = Orbits('6/sample') print(orbits.count_orbits()) # test() def part1(): orbits = Orbits('6/input') print(orbits.count_orbits()) # part1() # 314702 def part2(): orbits = Orbits('6/input') print(orbits.distance_to_san()) # 440 too high. part2()
c9f770222d1b994cc2e306b9fa64cfa15779c8a4
alineberry/alcore
/alcore/data/vocab.py
2,784
3.65625
4
from ..utils import * from collections import Counter from itertools import chain import copy def calc_token_freq(series): """Function to quickly compute all token frequencies in a corpus. Assumes the text has already been tokenized. Args: series (iterable): An iterable (typically a pandas series) containing the document corpus Returns: A Counter object """ return Counter(chain.from_iterable(map(str.split, series))) class Vocab: """Basic vocabulary that creates forward and backward mappings between the tokens themselves (i.e., strings) and their assigned indices. Also allows for a maximum vocabulary size. """ def __init__(self, text, vocab_size=None, unk_idx:int=0, pad_idx:int=1): """ Args: text (iterable): Typically a pandas series containing the document corpus vocab_size (int): Number of tokens to include in the vocabulary. The top `vocab_size` tokens by frequency will be included. unk_idx (int): The vocabulary index corresponding to the "unknown" token pad_idx (int): The vocabulary index corresponding to the "padding" token """ self.unk = "__UNK__" self.pad = "__PAD__" self.unk_idx:int = unk_idx self.pad_idx:int = pad_idx token_counts = calc_token_freq(text) # if a max vocab size is specified, create the vocab this way if vocab_size is not None: toks = [x[0] for x in token_counts.most_common(vocab_size)] # if no max vocab size is specified, create it this way else: toks = list(token_counts.keys()) # insert "unknown" and "padding" tokens into the vocabulary toks = [None, None] + toks toks[unk_idx] = self.unk toks[pad_idx] = self.pad # create forward and backward mappings self.w2i = DictWithDefaults({w: i for i, w in enumerate(toks)}, default=unk_idx) self.i2w = {i: w for w, i in self.w2i.items()} # dict with word frequencies in the same order as the core mappings self.w2freq = DictWithDefaults({w:token_counts[w] for w,_ in self.w2i.items()}, default=0) self.w2proba = self._compute_prob_dist() def __len__(self): return len(self.w2i) def _compute_prob_dist(self): """ Computes the empirical discrete probability distribution over the vocabulary, based on frequencies of occurrence in the text Returns: (dict): Dictionary where keys are words and values are probabilities """ bg_freq = copy.deepcopy(self.w2freq) Z = sum(bg_freq.values()) for key in bg_freq: bg_freq[key] = bg_freq[key] / Z return bg_freq
76a97dfec25d11326eefadf7b850694e0d361ba7
utkarsh192000/PythonBasic
/211membershipOperator.py
292
3.8125
4
# in and not in are membership operator a=[10,20,30,40,50] b={1,2,3,4} c=(1,2,36,8) stu={ 101:"Rahul", 102:"raj", 103:"Sonam", } print(10 in a) print(10 not in a) print(1 in b) print(10 not in b) print(36 in c) print(101 in stu) print("Rahul" in stu) print("Suresh" not in stu)
3260dc202a1f0df2621ffc621a1a6c31d979cdad
clarkngo/python-projects
/archive-20200922/leetcode-contests/diagonal_sort.py
938
3.984375
4
# Sort the Matrix Diagonally # User Accepted:1012 # User Tried:1103 # Total Accepted:1020 # Total Submissions:1432 # Difficulty:Medium # Given a m * n matrix mat of integers, sort it diagonally in ascending order from the top-left to the bottom-right then return the sorted array. # Example 1: # Input: mat = [[3,3,1,1],[2,2,1,2],[1,1,1,2]] # Output: [[1,1,1,1],[1,2,2,2],[1,2,3,3]] # Constraints: # m == mat.length # n == mat[i].length # 1 <= m, n <= 100 # 1 <= mat[i][j] <= 100 class Solution(object): def diagonalSort(self, A): R, C = len(A), len(A[0]) vals = collections.defaultdict(list) for r, row in enumerate(A): for c,v in enumerate(row): vals[r-c].append(v) for row in vals.values(): row.sort(reverse=True) for r, row in enumerate(A): for c,v in enumerate(row): A[r][c] = vals[r-c].pop() return A
7190828dd59e7883559730d316eb796b3831cd1e
anuragseven/coding-problems
/online_practice_problems/Circular and doubly linked list/Doubly linked list Insertion at given position.py
350
3.96875
4
# Given a doubly-linked list, a position p, and an integer x. The task is to add a new node with value x at the position just after pth node in the doubly linked list. def addNode(head, p, data): p1=head while p1.next is not None and p!=0: p1=p1.next p-=1 t=Node(data) t.next=p1.next p1.next=t t.prev=p1
f6dd773ad1114493bf81279f06bc447d8eaa7db1
aruba8/packetfabric-test
/util.py
2,254
3.640625
4
import base64 import codecs import configparser import hashlib import hmac from urllib.parse import quote_plus def generate_hash(key_secret, query_string=None): """ key_secret: The secret key associated with the API key you'll be passing in the `api_key` parameter. It is a tuple with the following format: (KEY_ID, KEY_SECRET) query_string: A URL query string query_string format: "param1=value1&param2=value2&api_key=API_KEY" Note that this does not have the leading "?" and that the api_key is included """ hash = hmac.new(codecs.encode(key_secret[1]), codecs.encode(query_string), hashlib.sha256).digest() hash = base64.b64encode(hash) hash = quote_plus(hash) return hash def generate_full_endpoint(api_url, endpoint, key_secret=None, query_string=None): """Build the full API end point with query string and auth hash api_url: The base URL for the API endpoint: The URL that will be queried key_secret: The key associated with the user making this call. It is a tuple with the following format: (KEY_ID, KEY_SECRET) query_string: The query string that will be used to make this call Returns the full URL of the API, with auth_hash, query string and api_key for this call """ if query_string: query_string = "{query_string}&".format(query_string=query_string) else: query_string = "" if key_secret: query_string += "api_key={api_key}".format(api_key=key_secret[0]) query_string += "&auth_hash={hash}".format( hash=generate_hash(key_secret, query_string)) query_string = "?{query_string}".format(query_string=query_string) url = "{api}{endpoint}{query_string}".format( api=api_url, endpoint=endpoint, query_string=query_string) return url def get_secrets(): config = configparser.ConfigParser() config.read('secrets.ini') return config['DEFAULT'] def generate_url(endpoint, query_params=None): secrets = get_secrets() key_id = secrets['key_id'] key_secret = secrets['key_secret'] api_url = secrets['api_url'] return generate_full_endpoint(api_url, endpoint, key_secret=(key_id, key_secret), query_string=query_params)
61487b9cf0841b277e4a0e4a1baf951f5ef20208
AbhishekTiwari0812/python_codes
/BucketSort.py
604
3.828125
4
import pdb def InsertionSort(bucket): for i in range(len(bucket)): pivot=bucket[i] j=i-1 while j>=0 and bucket[j]>pivot: A[j+1]=A[j] j-=1 A[j+1]=pivot def BucketSort(A): #pdb.set_trace() B=[[]]*len(A) #make all the elements ranging from 0 to 1 MAX=max(A) MAX+=1 for i in range(len(A)): A[i]/=MAX for i in range(len(A)): B[(int(A[i]*len(B)))].append(A[i]) C=[] for i in range(len(B)): InsertionSort(B[i]) #C+=B[i] print B import random A=[] for i in range(10): A.append(random.random()*100) #print A BucketSort(A) #print A
08dceffe39e75c55ae69cc9c66c7a558c79fa15d
reedx8/Python-Demonstrations
/series_sum.py
632
3.9375
4
'''Sum of the first nth term of Series''' from decimal import Decimal def series_sum(x): series = [] b = 1.00 # series must start with '1' number, so I hardcoded it in. c = 1 # increments the denominator thru each iteration. See c in loop below. for series_number in range(0,x): series.append(("%.2f" % b)) # adds b to list & rounds it off @ 2 dec points b = 1/(c+3) # renames b as a fraction from here on out. Incr.'s w/ c. c += 3 print("b =", b) print("c =", c) print(series) print(sum(series)) number = int(input("Give me a number: ")) series_sum(number)
1a64000c3659b602d6e3a192cff55dbea389171c
hwadhwani77/python_lab
/dp.py
596
3.6875
4
def fib_dp(n: int, memo: list): result = 0 if memo[n] != None: return memo[n] if n == 1 or n==2: result = 1 else: result = fib_dp(n-1, memo) + fib_dp(n-2, memo) memo[n] = result print(memo) return result def fib_bottom_up(n): if n ==1 or n ==2: return 1 else: bottom = [None] *(n+1) bottom[1] = bottom[2] = 1 for i in range(3, n+1): bottom[i] = bottom[i-1] + bottom[i-2] print(bottom) return bottom[n] n = 15 print(fib_dp(n, [None]*(n+1))) print(fib_bottom_up(n))
d6267d9b4c9ae3cd79b9b6a3e40b32f139e08fa3
SaiRithvik/Python_mycaptain
/triangle.py
335
4.15625
4
a = float(input()) b = float(input()) c = float(input()) if(a==b and a==c): print("the triangle with length of sides as a,b,c is EQUILATERAL ") elif(a==b or b==c or c==a): print("the triangle with length of sides as a,b,c is ISOSCELES ") else: print("the triangle with length of sides as a,b,c is SCAELENE ")
bcf2c82d4fa2eb1159e635122d8a63ebae4efbb4
SixuLi/Leetcode-Practice
/First Session(By Tag)/Hash Table/138.Copy List with Random Pointer.py
1,882
3.875
4
# Definition for a Node. class Node: def __init__(self, x: int, next: 'Node' = None, random: 'Node' = None): self.val = int(x) self.next = next self.random = random # Solution 1: Hash Table # We solve this problem in two loops: # In the first loop, we scan the original linked list and make a copy of each node, # and use hash table to connect the original node and copy node. # In the second loop, we scan the original linked list and connect all the copy node. # Time Complexity: O(N) # Space Complexity: O(N) class Solution: def copyRandomList(self, head: 'Node') -> 'Node': if not head: return None p = head Dict = dict() while p: node = Node(p.val) Dict[p] = node p = p.next res = Dict[head] q = res while head: if head.next: Next = Dict[head.next] q.next = Next if head.random: q.random = Dict[head.random] q = q.next head = head.next return res # Solution 2: Constant Space # Time Complexity: O(N) # Space Complexity: O(1) class Solution: def copyRandomList(self, head: 'Node') -> 'Node': if not head: return None p = head while p: node = Node(p.val) node.next = p.next p.next = node p = p.next.next p = head while p: if p.random: p.next.random = p.random.next p = p.next.next p = head p_old = head p_new = head.next res = p_new while p_old: p_old.next = p_old.next.next p_new.next = p_new.next.next if p_new.next else None p_old = p_old.next p_new = p_new.next return res
63385330ac70bdb875cbc6ff178d687872846f9a
theomeli/Mathesis-apps
/diavgeia app/diavgeia app.py
5,017
3.703125
4
# mathesis.cup.gr course with title "Introduction to Python" # Final Project: Data retrieval from diavgeia.gov.gr import re import urllib.request import urllib.error authorities = {} def rss_feed(url): ''' Opening of rss feed, :param url: the address of rss feed. This function creates a file with the contents of the rss_feed having as name the rss_feed's address. It calls the function process_feed which chooses and prints content. ''' url += r"/rss" req = urllib.request.Request(url) filename = url.replace('/', '_').replace('.', '_') + '.rss' filename = filename[8:] try: with urllib.request.urlopen(req) as response: char_set = response.headers.get_content_charset() html = response.read().decode(char_set) with open(filename, "w", encoding = char_set) as p: p.write(html) except urllib.error.HTTPError as e: #print('Σφάλμα HTTP:', e.code) print('HTTP Error:', e.code) except urllib.error.URLError as e: #print('Αποτυχία σύνδεσης στον server') #print('Αιτία: ', e.reason) print('Fail to connect to server') print('Reason: ', e.reason) else: process_feed(filename) def process_date(date): ''' The function formats the greek date of rss_feed: In rss file the date has the form: Wed, 14 Jun 2017 17:21:16 GMT and it should be formatted in a greek date, i.e. Τετ, 14 Ιουν 2017 :param date: :return: the greek date ''' daysEngToGr = {'Mon': 'Δευ', 'Tue': 'Τρι', 'Wed': 'Τετ', 'Thu': 'Πεμ', 'Fri': 'Παρ', 'Sat': 'Σαβ', 'Sun': 'Κυρ'} monthsEngToGr = {'Jan': 'Ιαν', 'Feb': 'Φεβ', 'Mar': 'Μαρ', 'Apr': 'Απρ', 'May': 'Μαι', 'Jun': 'Ιουν', 'Jul': 'Ιουλ', 'Aug': 'Αυγ', 'Sep': 'Σεπ', 'Oct': 'Οκτ', 'Nov': 'Νοε', 'Dec': 'Δεκ'} dayMonth = re.findall(r'(\b[\w]{3}\b)', date) date = re.sub(dayMonth[0], daysEngToGr[dayMonth[0]], date) date = re.sub(dayMonth[1], monthsEngToGr[dayMonth[1]], date) return date[:17] def process_feed(filename): ''' A function that opens a file with the rss feed and it prints the date and the titles of postings that contain. ''' date_tag = 'lastBuildDate' title_tag = 'title' text = '' with open(filename, "r", encoding = 'utf-8') as f: text = f.read() date = re.findall(r'<' + date_tag + r'\b[^>]*>(.*?)</' + date_tag + r'>', text, re.I) print(process_date(date[0])) titles = re.findall(r'<' + title_tag + r'\b[^>]*>(.*?)</' + title_tag + r'>', text, re.I) i = 1 print('*** {} ***'.format(titles[0].strip())) for j in range(1, len(titles)): print (i, titles[j]) i = i + 1 print('\n') def search_authorities(authority): ''' searching of authority name which fits to the user's criteria ''' tonoi = ('αά', 'εέ', 'ηή', 'ιί', 'οό', 'ύυ', 'ωώ') n_phrase = '' for c in authority: char = c for t in tonoi: if c in t: char = '[' + t + ']' n_phrase += char pattern = '.*' + n_phrase + '.*' result = [] for k, v in authorities.items(): w = re.findall(pattern, k, re.I) for r in w: result.append(r) return result def load_authorities(): ''' It loads the authorities to the dictionaty authorities{} ''' try: with open("500_authorities.csv", "r", encoding = "utf-8") as f: for line in f: line = line.strip() authority = line.split(';') authorities[authority[0]] = authority[1] except IOError as e: print(e) ######### main ############### ''' the main program manages the interraction with the user ''' load_authorities() while True : #authority = input(50 * "^" + "\nΟΝΟΜΑ ΑΡΧΗΣ:(τουλάχιστον 3 χαρακτήρες), ? για λίστα: ") authority = input(50 * "^" + "\nAUTHORITY NAME:(at least 3 characters), ? for list: ") if authority == '': break elif authority == "?": # it presents the authorities names for k,v in authorities.items(): print (k,v) elif len(authority) >= 3 : # it searches an authority name that fits to user's criteria result = search_authorities(authority) for r in result: print (result.index(r)+1, r, authorities[r]) while result: #choice = input("ΕΠΙΛΟΓΗ....") choice = input("CHOICE....") if choice == "": break elif choice.isdigit() and 0 < int(choice) < len(result) + 1: choice = int(choice) url = authorities[result[choice - 1]] print(url) # it calls the function that loads the file rss: rss_feed(url) else: continue else : continue
a83d1dc7a1835e3e29e27b86f585735b5ef6f48d
mkarimi20/python
/while_loop.py
1,344
4.28125
4
# count = 0 # while(count < 9): # print('the count it: ', count) # count = count+1 # print('Out of loop') # The Infinite Loop # A loop becomes infinite loop if a condition never becomes FALSE. You must be cautious # when using while loops because of the possibility that this condition never resolves to a # FALSE value. This results in a loop that never ends. Such a loop is called an infinite loop. # count = 0 # while count < 10: # print(count, 'the number is less than 10') # count = count + 1 # what if we remove this line? # else: # print(count, " is not less than 10") # i = 1 # while i < 6: # print(i) # if (i == 3): # break # i += 1 # With the continue statement we can stop the current iteration, and continue with the next: # i = 1 # while i < 6: # i += 1 # if(i == 3): # continue # print(i) # else: # pass # i = 1 # while i < 6: # print(i) # i += 1 # else: # print("i is no longer less than 6") # flag = 1 # while (flag): # print('Given flag is really true!') # Guess what happens? # print("Good bye!") # nested loops # while expression: # while expression: # statement(s) # statement(s) # for i in range(1, 11): # for j in range(1, 11): # k = i*j # print(k, end=' ') # print('out of four loops')
c5449a4b765d6bb700ef2eeaf68736c1e4d08cbf
ywtail/codeforces
/112_785A.py
450
3.6875
4
# coding=utf-8 # 785A. Anton and Polyhedrons 安东和多面体 n = int(raw_input()) re = {'Tetrahedron': 4, 'Cube': 6, 'Octahedron': 8, 'Dodecahedron': 12, 'Icosahedron': 20} ans = 0 for i in range(n): polyhedron = raw_input() ans += re[polyhedron] print ans """ input 4 Icosahedron Cube Tetrahedron Dodecahedron output 42 input 3 Dodecahedron Octahedron Octahedron output 28 给出多面体数量和名称,求一共多少个面。 """
868b429f6a19a26596684c5d7515818acd47688d
syeluru/MIS304
/Notes/HW2/CompoundInterest.py
943
3.9375
4
# Program to compute compound interest import math import tkinter.messagebox def main(): a = 1000 #Initial amount n = 10 #Number of years r = 5 #first rate of interest final_message = '' final_message += print_header_line() + '\n' line = "----------" final_message += "----%12s%12s%12s%12s%12s%12s\n\n" % (line, line, line, line, line, line) for year in range(1,11): message_header = "%4d" % year message = '' for rate in range(5,11): amount = a * math.pow((1.0 + rate/100), year) message += ('%12.2f' % amount) final_message += message_header + message + '\n' print (final_message) tkinter.messagebox.showinfo("Compound Interest", final_message) def print_header_line(): message = "Year" for rate in range(5,11): amount_header = "Amount<%d%%>" % rate message += "%12s" % amount_header return (message) main()
78d8c53b9c5da1b557ec9ec694221ea201625c5c
mindovermiles262/codecademy-python
/11 Introduction to Classes/05_instantiating_your_first_object.py
396
4.34375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Jan 8 08:23:11 2017 @author: mindovermiles262 Codecademy Python Outside the Animal class definition, create a variable named zebra and set it equal to Animal("Jeffrey"). Then print out zebra's name. """ class Animal(object): def __init__(self, name): self.name = name zebra = Animal("Jeffrey") print zebra.name
e8b123973285dad6fb2f3e5a8eb8993bfd7ed464
yz830620/oop_prctice
/chapter3/house_project/propety/propety.py
3,098
3.765625
4
"""file define class which define propety""" def get_valid_input(input_string, valid_options): response = input(f"{input_string}({', '.join(valid_options)}) ") while response.lower() not in valid_options: print(f"please choose within ({', '.join(valid_options)}) ") response = input(input_string) return response class Propety: """class which define propety""" def __init__(self, square_feet='', num_bedroom='', num_bathroom='', **kwargs): super().__init__(**kwargs) self.square_feet = square_feet self.num_bedroom = num_bedroom self.num_bathroom = num_bathroom def display(self): print("PROPERTY DETAILS") print("================") print(f"square footage: {self.square_feet}") print(f"bedrooms: {self.num_bedroom}") print(f"bathrooms: {self.num_bathroom}") print() @staticmethod def prompt_init(): return dict(square_feet = input("Enter the square feet: "), beds=input("Enter number of bedrooms: "), baths=input("Enter number of baths: ")) class House(Propety): """class to describe house""" valid_garage = ("attached", "detached", "none") valid_fenced = ("yes", "no") def __init__(self, num_stories='', garage='', fenced_yard='', **kwargs): super().__init__(**kwargs) self.num_stories = num_stories self.garage = garage self.fenced_yard = fenced_yard def display(self): super().display() print("House Details") print(f"number of stories: {self.num_stories}") print(f"garage: {self.garage}") print(f"fence yard: {self.fenced_yard}") @staticmethod def prompt_init(): parent_init = Propety.prompt_init() num_stories = input("How many stories? ") fenced = get_valid_input("Is there yard fenced? ", House.valid_fenced) garage = get_valid_input("Is there a garage? ", House.valid_garage) parent_init.update({"fenced": fenced, "garage": garage, "num_stories": num_stories }) return parent_init class Apartment(Propety): """class to describe apartment""" valid_laundries = ("coin", "ensuite", "none") valid_balconies = ("yes", "no", "solarium") def __init__(self, balcony='', laundry='', **kwargs): super().__init__(**kwargs) self.balcony = balcony self.laundry = laundry def display(self): super().display() print("Apartment Details") print(f"balcony: {self.balcony}") print(f"has laundry: {self.laundry}") @staticmethod def prompt_init(): parent_init = Propety.prompt_init() balcony = get_valid_input("Is there balcony? ", House.valid_fenced) laundry = get_valid_input("Is there a laundry? ", House.valid_garage) parent_init.update({"balcony": balcony, "laundry": laundry }) return parent_init
a274a778cd4a281359b940c8e06d079c15f6e97a
lcwspr/Python
/999_test/python复习/python 基础/8 python 函数/4 高阶函数.py
869
3.734375
4
""" a, b 形参 , 2 变量 传递数据 就是指 给变量赋值 def test(a, b): print(a + b) 其实函数名也是一个变量名 开辟空间 将函数体拷贝到内存出 键地址赋给 2 变量 函数本身也可以作为数据 传递给一个变量 概念 当一个函数A的参数 接受的又是另一个函数时 则把这个函数A称为高阶函数 例如 sorted 函数 案例 动态的计算两个数据 比较列表中的字典 """ l = [{"name": "sz", "age": 28}, {"name": "sz2", "age": 48}, {"name": "se", "age": 14}] def getKey(x): return x["age"] resule = sorted(l, key=getKey) print(resule) # 动态计算两个数据 def caculate(num1, num2, caculateFunc): print(caculate(num1, num2)) def sum(a, b): return a + b def sub(a, b): return a - b
e1618bbf96246099811f4e6e56112301acd78ca6
plcx/python-
/静态方法.py
279
3.84375
4
class Person(object): __count = 0 @staticmethod def how_many(): return Person.__count def __init__(self, name): self.name = name Person.__count = Person.__count + 1 print(Person.how_many()) p1 = Person('Bob') print(Person.how_many())
0b8f395421c478cc39f1d771d056b7f7c75ccccd
droy78/Leetcode
/70.ClimbStairs.py
1,792
3.84375
4
class Solution(object): #As a lazy manager, I just want to focus on the number of ways a person can reach #my level i. There are actually just 2 possible ways someone can reach at level i : By #taking 1 step from level i-1 or by taking 2 steps from level i-2. I am assuming that #the no. of ways of reaching level i-1 would have been calculated by my predecessor and #the no. of ways of reaching level i-2 would have been calculated by his predecessor. I just #need to take the 2 values and add them up. #We just need 3 spaces : One to store the solution solved by manager at level i-1, one to store #the solution solved by the manager at level i-2 and one to be used by the current lazy manager #at level i who is going to add his predecessor's numbers def climbStairs(self, n): """ :type n: int :rtype: int """ #We initialize a table array with 3 indexes representing level 0, 1 and 2 #You already start with level 0. So 0 ways of reaching there #Level 1 can be reached only one way by taking a single step from level 0 #Level 2 can be reached 2 ways : #Way1 - 1 step from level 0 + 1 step from level 1 #Way2 - 2 steps from level 0 table = [0, 1, 2] #We iterate over all the levels starting with level 3 for i in range(3, n+1): #The lazy manager computes his solution for level i by adding the solutions #calculated by his predecessor's at level i-1 and i-2 #The first lazy manager, therefore, will fill up the solution for level 3 and #store it at index 3%3 => index 0 table[i%3] = table[(i-1)%3] + table[(i-2)%3] return table[n%3]
08d455f445ba10a25c0a08c4f28e65ad4e9e1cc0
getachew67/CSE-163-Education
/CSE 168 - Intermediate Data Programming/Homework/hw2/hw2_manual.py
3,616
4.125
4
def parse(file_name, int_cols): """ Parses the CSV file specified by file_name and returns the data as a list of dictionaries where each row is represented by a dictionary that has keys for each column and value which is the entry for that column at that row. Also takes a list of column names that should have the data for that column converted to integers. All other data will be str. """ data = [] with open(file_name) as f: headers = f.readline().strip().split(',') num_cols = len(headers) for line in f.readlines(): row_data = line.strip().split(',') row = {} for i in range(num_cols): if headers[i] in int_cols: row[headers[i]] = int(row_data[i]) else: row[headers[i]] = row_data[i] data.append(row) return data def species_count(data): """ This function returns the number of unique species of Pokemon, using the name attribute (column). """ species = set() for line in data: species.add(line['name']) return len(species) def max_level(data): """ This function returns the Pokemon with the highest level. """ level = 0 name = '' for line in data: if line['level'] > level: level = line['level'] name = line['name'] return (name, level) def filter_range(data,low,high): ''' This function returns all Pokemon whose attack and defense are within the selected range (inclusive). ''' pokemon = [] for i in data: if i['level'] in range(low, high): pokemon.append(i['name']) return pokemon def mean_attack_for_type(data,attack): ''' This function takes a Pokemon type as an argument and returns the average attack stat for all the Pokemon in the dataset with that type. ''' total = 0 count = 0 for i in data: if i['type'] == attack: total += i['atk'] count += 1 return total/count def count_types(data): ''' This function returns a dictionary with keys that are Pokemon types and values that are the number of times that type appears in the dataset. ''' result = {} for i in data: p_type = i['type'] if p_type in result.keys(): result[p_type] += 1 else: result[p_type] = 1 return result def highest_stage_per_type(data): ''' This function calculates the largest stage reached for each type of Pokemon in the dataset. ''' result = {} for i in data: p_type = i['type'] if p_type in result.keys(): if result[p_type] < i['stage']: result[p_type] = i['stage'] else: result[p_type] = i['stage'] return result def mean(values): ''' Take list like datastructure and return its mean. ''' return sum(values) / len(values) def mean_attack_per_type(data): ''' This function calculates the average attack for every type of Pokemon in the dataset, returning a dictionary that has keys that are the Pokemon types and values that are the average attack for that Pokemon type. ''' result = {} for i in data: p_type = i['type'] if p_type in result.keys(): result[p_type].append(i['atk']) else: result[p_type] = [i['atk']] result_mean = {k: round(mean(v), 2) for k, v in result.items()} return result_mean
23aaf3c7e5ca46f25bc0730c6b9453331ee4bf7d
lumbduck/euler-py
/p060.py
3,282
4.0625
4
""" Prime Pair Sets The primes 3, 7, 109, and 673, are quite remarkable. By taking any two primes and concatenating them in any order the result will always be prime. For example, taking 7 and 109, both 7109 and 1097 are prime. The sum of these four primes, 792, represents the lowest sum for a set of four primes with this property. Find the lowest sum for a set of five primes for which any two primes concatenate to produce another prime. """ from collections import defaultdict from itertools import chain from prime import is_prime, primes, sieve_primes from common import elapsed, split_timer target_set_size = 5 # For each prime, p, keep a set of primes, q with p > q, for which (p, q) satisfy the pair_primality test. prime_pairs = defaultdict(set) def populate_prime_pairs(p, q): """Return True if concatening m and n in both orders produces two primes.""" if p in prime_pairs and q in prime_pairs[p]: return True elif is_prime(int(str(p) + str(q))) and is_prime(int(str(q) + str(p))): prime_pairs[p].add(q) return True def get_connected_set(p_pairs, n): """Return a set of n primes from the set p_pairs for which all pairs satisfy pair primality with each other, if such a set exists.""" if len(p_pairs) >= n: if n == 1: # Done return p_pairs # Starting from large prime in p_pairs, start checking for pair primes all the way down # stopping only if there are not enough primes left to reach n, # or if we have found n pairwise connected primes p_pairs = sorted(p_pairs, reverse=True) for i in range(len(p_pairs) - n + 1): q = p_pairs[i] if q in prime_pairs: # Recurse q_set = get_connected_set(prime_pairs[q].intersection(p_pairs[i + 1:]), n - 1) if q_set: q_set.add(q) return q_set elif q == 3 and n == 2: # Backup base case, since 3 will never be added to prime_pairs dict return {3} return set() def solve_by_pairing(target_size=target_set_size): # This algorithm will populate prime_pairs with each prime (key) pointing to a set of all # smaller primes that form a valid prime pair with it. # Each of these is then checked by get_connected_set to see if there are enough pairwise # connections to complete the problem. # NOTE: prime index starts from 3 to avoid primes 2 and 5, which cannot be part of any prime pair. # 3 is chained into the inner loop, but not the outer loop because no valid primes are less than 3. log_step = 1000 next_step = 0 for p in primes(step=10000, start_index=3): for q in chain(reversed(sieve_primes(max_prime=p)[3:-1]), [3]): populate_prime_pairs(p, q) if p > next_step: split_timer() print(f"Reached p > {next_step} -- {p}: {prime_pairs.get(p)}") next_step += log_step if p in prime_pairs: p_set = get_connected_set(prime_pairs[p], target_size - 1) if p_set: p_set.add(p) return sorted(p_set)[:target_size] print(solve_by_pairing(5)) elapsed() # Around 20 minutes!
e4cf3137b728a344099302db43d1a24087784ce3
kbcmdba/pcc
/ch9/ex9-6.py
1,942
4.71875
5
# Ice Cream Stand: An ice cream stand is a specific kind of restaurant. Write a # class called IceCreamStand that inherits from the Restaurant class you wrote # in Exercise 9-1 or Exercise 9-4. Either version of the class will work; just # pick the one you like better. Add an attribute called flavors that stores a # list of ice cream flavors. Write a method that displays these flavors. # Create an instance of IceCreamStand, and call this method. class Restaurant(): """A simple restaurant model""" def __init__(self, restaurant_name, cuisine_type): """Initialize restaurant_name and cuisine_type attributes""" self.restaurant_name = restaurant_name self.cuisine_type = cuisine_type self.number_served = 0 def describe_restaurant(self): """Print the restaurant attributes""" print(self.restaurant_name + " has served " + str(self.number_served) + " customers " + self.cuisine_type + ".") def open_restaurant(self): """Really?""" print(self.restaurant_name + " is now open.") def set_number_served(self, number_served): """Setter""" self.number_served = number_served def increment_number_served(self, increment_by): """Modifier""" self.number_served += increment_by class IceCreamStand(Restaurant): """An Ice Cream Stand is a special kind of restaurant.""" def __init__(self, restaurant_name, cuisine_type, flavors): """ Initialize restaurant_name, cuisine_type and flavors attributes """ super().__init__(restaurant_name, cuisine_type) self.flavors = flavors def display_flavors(self): print(self.flavors) icecreamstand = IceCreamStand("Hairy Queen", "Ice Cream Stand", ['Vanilla', 'Chocolate', 'Strawberry', 'Butter Pecan']) icecreamstand.display_flavors()
b095a8285577eb3c9f26ed70d918059d04b77897
niteesh2268/coding-prepation
/leetcode/Problems/709--To-Lower-Case-Easy.py
318
3.515625
4
class Solution: def toLowerCase(self, str: str) -> str: answer = '' for ch in str: if ord(ch) <= ord('Z') and ord(ch) >= ord('A'): answer += chr(ord(ch) - ord('A') + ord('a')) else: answer += ch return answer
7a0dde25fc8ef1e272ee9e1ccde7bb575684c20f
tanu312000/Python
/QuickSort.py
620
3.984375
4
def partition(A, p, r): i = (p - 1) # index of smaller element x = A[r] # last element for j in range(p, r-1): if A[j] <= x: i = i + 1 A[i], A[j] = A[j], A[i] A[i + 1], A[r] = A[r], A[i + 1] return (i + 1) # Function to do Quick sort def quickSort(A, p, r): if p < r: # q is partitioning index, A[p] is now # at right place q = partition(A, p, r) quickSort(A, p, q - 1) quickSort(A, q + 1, r) A=[20, 28, 25, 19, 11, 15] partition(A,0,5) quickSort(A,0,5) n = len(A) quickSort(A,0,n-1) print("Sorted Array is",A)
2abd6277a89395ac7e5b2a561e20ff0e535dc486
fandoghi/lambda
/main.py
377
4
4
double = lambda x : x *2 x=double(5) print(x) double = lambda x : x +2 x=double(5) print(x) double = lambda x : x -2 x=double(5) print(x) double = lambda x : x /2 x=double(5) print(x) double = lambda x : x *2 x=double(5) print(x) double = lambda x : x %2 x=double(5) print(x) double = lambda x : x //2 x=double(5) print(x) double = lambda x : x **2 x=double(5) print(x)
5154433717b1223ec523fd81077b32a4f150c402
Saradippity26/Beginning-Python
/functions.py
848
4.21875
4
"""Learn about functions/(python: Definitions) use the keywords: def <name> (parameters): ((function skeleton)) Between functions you should have two spaces of blank lines """ def even_or_odd(number): #should return the string even or odd """ Find if number is even or odd print "even" on even numbers "odd" on odd numbers :param number: input number """ #pass #dummy statement in python, meets requirement that you need at least one statement if number % 2 == 0: print("even") else: print("odd") def main(): #main is not a keyword in python """Test function :return nothing """ #call functions print(__name__) #two underscore and keyword name: python console -> import functions even_or_odd(89) even_or_odd(22) if __name__ == "__main__": main() exit(0)
09bf6505cd40db0a087d79e1906009003737658e
EduardoMachadoCostaOliveira/Python
/CEV/ex005.py
225
3.96875
4
#Faça um programa que leia um número Inteiro e mostre na tela o seu sucessor e seu antecessor n1 = int(input('Digite um número: ')) print(f'O sucessor de {n1} é {n1+1}', end='. ') print(f'O antecessor de {n1} é {n1-1}')
176af8c6492e40cb1072c08f41157d371a7a3f75
jinleiTessie/Citadel_DataOpen
/resources/models/Data_Preparation.py
492
3.5625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Sep 16 20:43:38 2019 @author: jinlei """ import pandas as pd def load_data(path): return pd.read_excel(path) df=pd.read_excel(r"..//data//testing//Color.xlsx") print (df.head()) print (df.shape) print (df.describe()) dummy_df=pd.get_dummies(df) print (dummy_df) dummy_df=dummy_df.drop(["Color_Black","Color_Yellow"],axis=1)#drop columns print (dummy_df) dummy_df=dummy_df.drop([0,2],axis=0)#drop rows print (dummy_df)
13fc764102ea38b6381c7ffc7f9bd137094f7a01
jingrui/leetcode_python
/ReorderList.py
2,394
4.0625
4
# Definition for singly-linked list. def printList(head): while head!=None: print head.val,'->', head = head.next print class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: # @param head, a ListNode # @return nothing def findMid(self,head): head1 = head slow = head prev = None fast = head while fast.next!=None and fast.next.next!=None: prev = slow slow = slow.next fast = fast.next.next if fast.next != None: head2 = slow.next slow.next = None else: head2 = slow prev.next = None return head1, head2 def reverseList(self,head): prev = None while head.next != None: next = head.next head.next = prev prev = head head = next head.next = prev return head def merge(self,l1, l2): # print "merge" # printList(l1) # printList(l2) # no need to check the l1 since it is the head of the original list res = l1 cur = l1 l1 = l1.next # print while l1!=None or l2!=None: # print "start" # printList(res) if l2!= None: cur.next = l2 cur = cur.next l2 = l2.next if l1!=None: cur.next = l1 l1 = l1.next cur = cur.next # print "end" # printList(res) # if l1 != None: # print l1.val # else: # print l1 # if l2 != None: # print l2.val # else: # print l2 return res def reorderList(self, head): if head == None or head.next == None or head.next.next == None: return head start1,start2 = self.findMid(head) # print start1.val,start2.val start2 = self.reverseList(start2) # print "reversed" # printList(start2) return self.merge(start1,start2) l = ListNode(1) head = l for i in range(2,6): l.next = ListNode(i) l = l.next a = Solution() printList(head) # printList(head) a.reorderList(head) printList(head)
b3c2975d24f4e26bdc13a895110b8030b189a676
ChenSaijilahu/Adjusting-Traffic-Flow-Optimization
/FullGraph.py
2,036
3.703125
4
class AdjacencyGraph(): def __init__(self, edges, n_vertices, directed=False): self.edges = [True]*len(edges) self.vertices = [] self.directed = directed self.visited = [False]*n_vertices for i in range(n_vertices): self.vertices.append([]) for j in range(n_vertices): self.vertices[i].append(0) for e in edges: self.vertices[e[0]][e[1]] = e[2] def _topo_sort(self, node=0, reverse=False): nodes=[node] index = 1 self.visited[node] = True if reverse: for i in range(len(self.vertices)): if self.vertices[i][node] > 0: next_node = i if self.visited[next_node]: continue temp = self._topo_sort(next_node, reverse) for i in range(len(temp)): nodes.insert(index+i, temp[i]) else: for i, e in enumerate(self.vertices[node]): if e > 0: next_node = i if self.visited[next_node]: continue temp = self._topo_sort(next_node) for i in range(len(temp)): nodes.insert(index+i, temp[i]) return nodes def topo_sort(self, reverse=False): topo = [] for i in range(len(self.vertices)): if self.visited[i]==False: temp = self._topo_sort(i, reverse) temp.extend(topo) topo = temp self.visited = [False for i in self.visited] return topo def strongly_connected(self): sort_topo = self.topo_sort(True) scc = [] for i in sort_topo: if self.visited[i]: continue scc.append(self._topo_sort(i)) self.visited = [False for i in self.visited] return scc
e3befb922f421d30c6b2fd0cfab1120767688c56
albertogcmr/data-analytics-examples-lessons-stuff
/unittesting/main.py
1,097
3.90625
4
import unittest from functions import suma from random import randint class TestStringMethods(unittest.TestCase): def test_upper(self): self.assertEqual('foo'.upper(), 'FOO') def test_isupper(self): self.assertTrue('FOO'.isupper()) self.assertFalse('Foo'.isupper()) def test_split(self): s = 'hello world' self.assertEqual(s.split(), ['hello', 'world']) # check that s.split fails when the separator is not a string with self.assertRaises(TypeError): s.split(2) class TestSuma(unittest.TestCase): def _suma_test(self, a, b): return a + b def test_suma(self): a = 10 b = 12 self.assertEqual(suma(a, b), self._suma_test(a, b)) class TestSuma2(unittest.TestCase): def _suma_test(self, a, b): return a + b def test_multiple_suma(self): for _ in range(100): a = randint(-100, 100) b = randint(-100, 100) self.assertEqual(suma(a, b), self._suma_test(a, b)) if __name__ == '__main__': unittest.main()
93924247145ad3aa523ea9210b3572f0f2ec824c
maiman-1/hackerrank-dump
/Getting started/Sales by Match.py
2,475
4.1875
4
""" Objective: Given an array of integers representing the color of each sock, determine how many pairs of socks with matching colors there are. Example: 7 socks, [1,2,1,2,1,3,2]. There's 1 pair of 1s and 1 pair of 2s. So, it should output number of pairs = 2. """ """ Original Code: #!/bin/python3 import math import os import random import re import sys # Complete the sockMerchant function below. def sockMerchant(n, ar): if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') n = int(input()) ar = list(map(int, input().rstrip().split())) result = sockMerchant(n, ar) fptr.write(str(result) + '\n') fptr.close() """ #!/bin/python3 import math import os import random import re import sys # Complete the sockMerchant function below. def sockMerchant(n, ar): """ Return an integer representing the number of matching pairs of socks that are available. :param n: Integer: the number of socks in the pile :param ar: List(Integer): the colors of each sock :return: Integer: The number of matching pairs of socks that are available Steps: 1. Loops through list 2. Stores the first element and it's index 3. Loops through rest of list 4. If there is another copy of the element: - Stores the copy's index - add one to number of pairs - Removes elements and both index - breaks the loop 5. Continues for the rest of the elements on the list num_pairs = 0 i = 0 while i < len(ar): ele = ar[i] index_par = i for j in range(i, len(ar)): if ele == ar[j]: index_child = j del ar[index_child] del ar[index_par] break i += 1 """ # Initialize the number to be outputted num_pairs = 0 colors = set() for i in range(n): if ar[i] not in colors: colors.add(ar[i]) else: num_pairs += 1 colors.remove(ar[i]) return num_pairs if __name__ == '__main__': """ fptr = open(os.environ['OUTPUT_PATH'], 'w') n = int(input()) ar = list(map(int, input().rstrip().split())) result = sockMerchant(n, ar) fptr.write(str(result) + '\n') fptr.close() """ n = 10 ar = [1, 1, 3, 1, 2, 1, 3, 3, 3, 3] print(sockMerchant(n, ar))
ae3c6407a8e87d878b7008d4735520517e0dfcfd
pravin-asp/Python-Learnings
/ExceptionHandling.py
2,542
4.3125
4
# Exception Handling # Error: # Syntax Error and Exception is different # print(10 / 0) this is an exception '''try: n1 = int(input()) n2 = int(input()) print(n1 / n2) # risky code except ZeroDivisionError: print('Check It seems like zeor in denominator') except ValueError: print('Check the numbers') print('Hi')''' # Runtime Error --> Exception # In python, Everything is Object # whenever exception occurs, the corresponding exception object will give / throw to the end user # Object - memory reference of a class / instance of a class # 1. Every Exception in python is a class # 2. All Exception classes are child / Sub classes of BaseException class # 3. During runtime, if exception occurs, Python will throw us the exception class name and stops the program immediately / abruptly. # Exception Handling ''' def division(): try : a = int(input()) b = int(input()) print(a / b) except ValueError: # Handling code print('Something went wrong') #division() except: print('An Error Occured') #division() finally: # cleanup code print('Check I am in finally') division() ''' # Nested Exception Handling try: a = int(input()) b = int(input()) try: print(a / b) except ZeroDivisionError: print('Zero is in the denominator') finally: print('Inner Finally') except ValueError: print('Check the numbers') finally: print('Outer Finally') # Using else in try and except print() try: print('Try Block') print(int(input())/ int(input())) except: print('Exception Occurs') else: # Else part gets executed when no except print('Else part') finally: print('In Finally') # User Defined Exception '''class InsufficientBalanceException(Exception): def __init__(self): print('Check your balacne') balance = 1000 amount = int(input('Enter amount to withdraw:')) if amount > balance: raise InsufficientBalanceException() ''' class InsufficientBalanceException(Exception): def __init__(self, message): #self.msg = message pass balance = 1000 amount = int(input('Enter amount to withdraw:')) if amount > balance: raise InsufficientBalanceException('Check your balance') '''class InsufficientBalanceException(Exception): def __init__(self, msg): self.msg = msg try: balance = 1000 amount = int(input('Enter amount to withdraw:')) if amount > balance: raise InsufficientBalanceException('Check your balance') except InsufficientBalanceException: print('Insufficient Balance in your Account') print('Enter an amount less than your balance in multiples of 100')'''
1d588a1fd2364c689f30aa83ea8d318756d3161f
maelic13/beast
/src/heuristic/piece_values.py
627
3.734375
4
from chess import BISHOP, KNIGHT, PAWN, QUEEN, ROOK class PieceValues: """ Values of chess pieces based on human theory. """ PAWN_VALUE = 100 KNIGHT_VALUE = 350 BISHOP_VALUE = 350 ROOK_VALUE = 525 QUEEN_VALUE = 1000 @classmethod def as_dict(cls) -> dict[int, int]: """ Return piece values as dictionary. :return: piece types and their values """ return { PAWN: cls.PAWN_VALUE, KNIGHT: cls.KNIGHT_VALUE, BISHOP: cls.BISHOP_VALUE, ROOK: cls.ROOK_VALUE, QUEEN: cls.QUEEN_VALUE }
8c5e007963af73ff8cd8eeb9dc028e8476829f40
Mreggsoup/Python3
/virus.py
469
3.796875
4
import time mylist = ["MUSIC", "BURGER"] one = input("MUSIC y/n:") two = input("BURGER y/n:") view = input("View Survey Results y/n:") if view == "y": mylist.insert(1, one) mylist.insert(2, two) print(mylist) for i in mylist: mylist.append(one) mylist.append(two) time.sleep(0) print("Final results", mylist) time.sleep(0) with open('your_file.txt', 'w') as f: for item in mylist: f.write("%s\n" % item)
7d07c4ba40d7165d5883adc4d06eabc3038e7ef0
elizazhang21/LeetCode
/0034. First and Last Position of Element in Sorted Array.py
923
3.515625
4
# 34. Find First and Last Position of Element in Sorted Array.py class Solution: def searchRange(self, nums: List[int], target: int) -> List[int]: if not nums: return [-1,-1] # binary search l = 0 r = len(nums) - 1 while l <= r: mid = (l + r) // 2 if nums[mid] == target: left = mid right = mid while left > l: if nums[left-1] == target: left -= 1 else: break while right < r: if nums[right+1] == target: right +=1 else: break return left, right elif target > nums[mid]: l = mid + 1 else: r = mid -1 return [-1, -1]
a49a249ebb0928e3f3920941a93fbbd4982b17b1
mrizwan18/Data-Science
/Data Science/Linear Regression/gradient_descent.py
8,074
3.890625
4
import time import matplotlib.pyplot as plot # To plot the data import numpy as np import pandas as pd # For reading data from file def read_data(path): """[Function to read data from txt file] Arguments: path {[String]} -- [relative path to the dataset.txt] Returns: [Pandas Dataframe] -- [Dataframe contains columns of data] """ # Reading Data data = pd.read_csv(path, sep=",", header=None) return data def plot_data(data): """[Function to plot 2D scatter plot] Arguments: data {[Pandas dataframe]} -- [Works only on 2D or 2 feature data] """ plot.scatter(data.iloc[:, 0], data.iloc[:, 1], color='r', marker='x', label='Training Data') plot.title('Data Plot') plot.xlabel("Population of City in 10,000's") plot.ylabel('Profit in $10,000s') plot.show() def plot_prediction(thetas, x, data): """[Function to plot predicted hyperplane with respect to original data] Arguments: thetas {[array/list of thetas]} -- [Optimal thetas obtained after gradient descent] x {[input vector]} -- [Input/population vector that will help in plotting line] """ plot.scatter(data.iloc[:, 0], data.iloc[:, 1], color='r', marker='x', label='Training Data') # predicted response vector y_pred = np.dot(x, thetas) x = x[:, 1] # removing the one extra column of all 1 # plotting the regression line plot.plot(x, y_pred, color="b", label='Linear Regression') plot.legend(loc="lower right") plot.title('Prediction Model') plot.xlabel("Population of City in 10,000's") plot.ylabel('Profit in $10,000s') # function to show plot plot.show() def normalize_features(data): """[To normalize all features so that no single feature dominates] Arguments: data {[pandas dataframe]} -- [contains the columns of dataset2.txt] Returns: [array/list] -- [array of normalized data, array of std_deviation, means of all features] """ feature = data.iloc[:, :].to_numpy() mean = (sum(feature) / len(feature)) std = np.std(feature, axis=0) feature = (feature - mean) feature /= std return [pd.DataFrame(feature), mean, std] def normal_equation(x, y): """[Implementation of normal eq, theta= (X^T . X)^-1 . X^T . Y] Arguments: x {[matrix]} -- [vectoized input matrix] y {[matrix]} -- [vectoized output matrix] Returns: [list] -- [returns a list of thetas] """ # Takes 0.01s for dataset1 :O and 0.006 for dataset 2 x_trans = np.transpose(x) x_trans_x = np.dot(x_trans, x) x_trans_y = np.dot(x_trans, y) inverse = np.linalg.inv(x_trans_x) return np.dot(inverse, x_trans_y) def vectorize_data(data, thetas, n): """[function to vectorize data so that iterations are avoided] Arguments: data {[pandas dataframe]} -- [contains original data] thetas {list} -- [contains all thetas ] n {[int]} -- [indicates columns of dataset/features of dataset] Returns: [array] -- [vectorized x, y and thetas] """ x = data.iloc[:, :len(data.columns) - 1].to_numpy() # converting all columns except last one to numpy array x = np.insert(x, 0, 1, axis=1) # appending an all 1 column to start y = data.iloc[:, len(data.columns) - 1:].to_numpy() # converting last one to numpy array thetas = thetas.reshape(n, 1) return [x, y, thetas] def calculate_error(thetas, x, y): """[function to calculate objective function/loss] Arguments: thetas {[list]} -- [contains thetas] x {[input vector/matrix]} -- [contains vectorized matrix of input] y {[Y/output matrix]} -- [contains vector of output feature] Returns: [int] -- [returns sum of errors for all samples] """ m = len(data) prediction = np.dot(x, thetas) error = prediction - y error = np.dot(np.transpose(error), error) return (1 / (2 * m)) * error def update_thetas(thetas, alpha, x, y, n): """[function to update theta/gradient descent] Arguments: thetas {[list]} -- [contains list of thetas to be updated] alpha {[float]} -- [learning rate] x {[input vector/matrix]} -- [vectorized input matrix] y {[output vector]} -- [vectorized output matrix] n {[int]} -- [no. of columns in dataset] Returns: [list] -- [returns updated thetas] """ N = len(x) prediction = np.dot(x, thetas) error = (prediction - y) * x error = sum(error) error = error.reshape(n, 1) thetas = thetas - (alpha / N) * error return thetas def linear_regression_normal_eq(data): """[Function to update thetas in one go using normal eq] Arguments: data {[dataframe]} -- [original dataframe] Returns: [list] -- [returns a list of optimal thetas and vectorized input] """ n = len(data.columns) thetas = np.zeros(n) # array of thetas x, y, thetas = vectorize_data(data, thetas, n) thetas = normal_equation(x, y) return [thetas, x] def linear_regression_with_gradient(data): """[driver function for linear regression with gradient_descent] Arguments: data {[pandas dataframe]} -- [contains original data] Returns: [list] -- [returns optimal thetas and vectorized input] """ n = len(data.columns) thetas = np.zeros(n) # array of thetas alpha = 0.01 # optimal alpha when while loop convergence is used, outputs in 1 seconds # i = 0 prev_err = 10000000 # dummy error var to check convergence # iterations = 100000 # 90 seconds for 100k iterations # costs = np.zeros(iterations) x, y, thetas = vectorize_data(data, thetas, n) # Gradient Descent Method start ## while calculate_error(thetas, x, y) - prev_err < 0: prev_err = calculate_error(thetas, x, y) # costs = np.insert(costs, i, prev_err, axis=0) thetas = update_thetas(thetas, alpha, x, y, n) # to plot iterations vs cost function # costs = costs[:iterations, ] # plot.plot(list(range(iterations)), costs, '-r') # plot.show() # Gradient Descent Method End ## return [thetas, x] def prediction_test(means, std_d, thetas): """[To test the prediction on test data] Arguments: means {[list]} -- [list of means for all features when normalized] std_d {[list]} -- [list of std_deviation for all features when normalized] thetas {[list]} -- [list of thetas] """ x1 = float(input("Enter size of house: ")) x2 = float(input("Enter bedrooms of house: ")) x1 = (x1 - means[0]) x1 /= std_d[0] x2 = (x2 - means[1]) x2 /= std_d[1] x = np.array([x1, x2]) x = np.insert(x, 0, 1, axis=0) profit = np.dot(x, thetas) profit *= std_d[2] profit += means[2] # $293081.4643349 by normal eq and $293081.46845345 by gradient for size=1650, beds=3 print("Price is: ${0}".format(profit)) # descent def prediction_test_with_normal(thetas): x1 = float(input("Enter size of house: ")) x2 = float(input("Enter bedrooms of house: ")) x_pred = np.array([x1, x2]) x_pred = np.insert(x_pred, 0, 1, axis=0) profit = np.dot(x_pred, thetas) # $293081.4643349 by normal eq and $293081.46845345 by gradient for size=1650, beds=3 print("Price is: ${0}".format(profit)) if __name__ == '__main__': data = read_data("data/data1.txt") plot_data(data) start_time = time.time() # Normalize when dataset 2 is to be used # data, means, std_d = normalize_features(data) thetas, x = linear_regression_normal_eq(data) # thetas, x = linear_regression_with_gradient(data) print("--- %s seconds ---" % (time.time() - start_time)) # print(thetas) # To check if our predictions are correct for dataset 1 plot_prediction(thetas, x, data) # prediction_test_with_normal(thetas) # for dataset 2 # prediction_test(means, std_d, thetas) # for dataset 2
abb1d8e27c20dea40645bd86898ae8e465ce6083
abhimaprasad/Python
/Python/ObjectOrientedProgramming/DemoPrograms/Employeedemo.py
1,702
3.921875
4
from functools import * class Employee: def __init__(self, employid, name, salary, experience, designation): self.id = employid self.name = name self.salary = salary self.experience = experience self.designation = designation def printstudent(self): print("The employ id is ", self.id) print("The NAME IS", self.name) print("the salary is", self.salary) print("the experience ", self.experience) print("he designation is", self.designation) def __str__(self): return self.name li = [] file = open("EmpFile", "r") for line in file: data = line.rstrip("\n").split(",") print(data) id = data[0] name = data[1] salary = int(data[2]) experience = data[3] designation = data[4] obj = Employee(id, name, salary, experience, designation) li.append(obj) # list all employee whose designation is developer # # position="developer" # for obj in li: # if obj.designation==position: # print(obj.name) data = list(filter(lambda obj: obj.designation == "developer", li)) for each in data: print(each) # convert all employee names to upper case data = list(map(lambda obj: obj.name.upper(), li)) print(data) data1 = reduce(lambda salary1, salary2: salary1 if salary1 > salary2 else salary2, list(map(lambda obj: obj.salary, li))) print(data1) total = reduce(lambda salary1, salary2: salary1+salary2, list(map(lambda obj: obj.salary, li))) print(total) # list all employee whose designation is developer # convert all employee names to upper case # find total salary of all employees-->reduce # find highest salary from an employe--->reduce
0a57c8ecc5c85953b11d734dd3dea4b0212c6c57
dailesjsu/python_study
/diagonals.py
587
3.9375
4
#Given a square matrix, calculate the absolute difference between the sums of its diagonals. import os import random import re import sys def diagonalDifference(arr): sum1=0 sum2=0 for i in range(0,n): for j in range(0,n): if i==j: sum1=sum1+arr[i][j] if i== n - j - 1: sum2=sum2+arr[i][j] print(abs(sum1-sum2)) if __name__ == '__main__': n = int(input().strip()) arr = [] for _ in range(n): arr.append(list(map(int, input().rstrip().split()))) result = diagonalDifference(arr)
c23e599084c0dc0fb02568d5a2a3535dd24781d5
RRisto/learning
/algorithms_learn/what_can_be_computed/src/multiply.py
648
3.859375
4
# SISO program multiply.py # Computes the product of two integers provided as input. # inString: a string consisting of two integers separated by whitespace. # returns: The product of the input integers. import utils; from utils import rf def multiply(inString): (M1, M2) = [int(x) for x in inString.split()] product = M1 * M2 return str(product) def testMultiply(): testVals = [('4 5', 4*5), ('100 10000', 100*10000), ('1024 256', 1024*256)] for (inString, solution) in testVals: val = multiply(inString) utils.tprint (inString, val) assert int(val) == solution
fa771c9ec2d8614d27b589e30c0afe286f0e1140
vanonselenp/Learning
/Python/LPTHW/ex12.py
156
3.5
4
age = raw_input("age:") height = raw_input("height:") weight = raw_input("weight:") print "entered(age, height, weight): %s, %s, %s" % (age, height, weight)
e7cb6140348156333a2c3f553c83909c1fa4031e
MohamadShafeah/python
/Day1/02Formatting/O004formattingBasics.py
339
3.65625
4
# 1 classical printf emulate frm_str = "Hello Mr.%s %s talented Guy" val_info = ('Scahin', "Super") print(frm_str % val_info) val_info = ('Scahin', 1000) # 1000 convered as string print(frm_str % val_info) frm_str = "Hello Mr.%s %.3f talented Guy" val_info = ('Scahin', 1000) # 1000 taken as float print(frm_str % val_info)
7a4029dfea981a1d4ba85655b6b3c5bde9c73309
kevinshenyang07/Data-Structures-and-Algorithms
/algorithms/dfs/reconstruct_itinerary.py
995
3.6875
4
from heapq import heappush, heappop # Reconstruct Itinerary # the tickets belong to a man who departs from JFK # each ticket is an array of [from, to] # get the itinerary with the smallest lexical ordering # approach: dfs and build the Eulerian path backwards when the search returns # assume there's at least one valid itinerary class Solution(object): def findItinerary(self, tickets): """ :type tickets: List[List[str]] :rtype: List[str] """ self.result = [] self.mapping = collections.defaultdict(list) for dep, arr in tickets: heappush(self.mapping[dep], arr) self.dfs('JFK') return self.result # a valid path must be a line with 0 or some cycles on certain nodes # => add none-cycle partial path to result first def dfs(self, dep): pq = self.mapping[dep] # arrivals while pq: self.dfs(heappop(pq)) self.result.insert(0, dep) # O(n) time and space
7d791ca320b2e7d7a0f602ae65715b38ca614294
harashtaht/FundamentalExercise
/PCC/Part_1_Basics/ch5.py
2,357
4.21875
4
# -- Part 5 : If Statements -- # cars = ['audi', 'bmw', 'subaru', 'toyota'] # for car in cars: # if car == 'bmw': # print(car.upper()) # else: # print(car.title()) # a - Conditional Tests ''' At the heart of every if statement is an expression that can be evaluated as True or False and is called a conditional test. Testing for equality is case sensitive in Python. ''' # car = 'Audi' # print(car.lower() == 'audi') #True # print(car == 'audi') #False # requested_topping = 'mushrooms' # if requested_topping != 'anchovies': # print("Hold the anchovies") age_0 = 22 age_1 = 18 # print((age_0>=21) and (age_1<=21)) requested_topping = ['mushrooms', 'onions', 'pineapple'] # print('mushrooms' in requested_topping) # banned_users = ['andrew', 'carolina', 'david'] # user = ['marie', 'andrew'] # for i in user: # if i not in banned_users: # print(i.title()+", you can post a response if you wish") # else: # print("shut the fuck up, " + i.title() + ". You're motherfucking banned, you bitch.") # age = int(input("What's your age? ")) # if age < 4: # print(f"The fee is free for a {age} years old. Enjoy!") # elif 4 <= age < 18: # print(f"For a {age} years old, the fee for an entry will be 5$.") # else: # print(f"The fee will be 10$ for a {age} years old.") # if age <4: # price = 0 # elif age <18: # price = 5 # else: # price = 10 # print(f"Your admission cost is $ {price}") # requested_topping = ['mushrooms', 'extra cheese'] # if 'mushrooms' in requested_topping: # print('Adding mushrooms.') # if 'pepperoni' in requested_topping: # print('Adding pepperoni.') # if 'extra cheese' in requested_topping: # print('Adding extra cheese.') # print('\n Finished making your pizza! Enjoy.') # requested_topping = [] # cond = input("Would you like to request toppings? [Y/N]").lower() # if cond == 'y': # tops = input("What would it be? ") # requested_topping.append(tops) # cond2 = input("Anything else? [Y/N] ").lower() # if cond2 == 'y': # tops2 = input("What else, sir? ") # requested_topping.append(tops2) # cond2 = input("Anything else? [Y/N] ").lower() # elif cond =='n': # print("Please wait...") # for i in requested_topping: # print(f"Adding {i}.") # print("Finished making your pizza!")
a4a0e1cea5aba959a5a0d49df0ba1dcb96cc40da
omidziaee/DataStructure
/Algorithm_And_Data_Structure/backtracking_dp/partition_equal_subset_sum.py
1,224
3.859375
4
''' Created on Oct 10, 2019 @author: omid Given a non-empty array containing only positive integers, find if the array can be partitioned into two subsets such that the sum of elements in both subsets is equal. Note: Each of the array element will not exceed 100. The array size will not exceed 200. Example 1: Input: [1, 5, 11, 5] Output: true Explanation: The array can be partitioned as [1, 5, 5] and [11]. Example 2: Input: [1, 2, 3, 5] Output: false Explanation: The array cannot be partitioned into equal sum subsets. ''' class Solution(object): def canPartition(self, nums): """ :type nums: List[int] :rtype: bool """ if not nums: return True nums.sort() sum_total = sum(nums) if sum_total % 2 != 0: return False return self.dfs(nums, sum_total / 2, 0) def dfs(self, nums, target, start): if target == 0: return True for i in range(start, len(nums)): if i > start and nums[i] == nums[i - 1]: continue if target >= 0: if self.dfs(nums, target - nums[i], i + 1): return True return False
7b84c7846ea81d76866f8e477316d0a6928a2f94
EmmanuelPure0x1/Python_Projects
/dictionaries.py
2,084
4.65625
5
# What is a Dictionary ? # Dictionary is a set of data which operate as a Key Value Pair # Dictionaries (arrays) is another way of managing data but more dynamically. # Syntax: {"key":"value", key:"value"} # What type of data can we store/manage # Dictionary #1 devops_student_data = { "name": "Emmanuel", "stream": "tech", "completed_lessons": 4, "completed_lesson_name": ["operators", "data_types", "variables"] } print(type(devops_student_data)) print(devops_student_data) # Name print(devops_student_data["name"]) # changing name value devops_student_data["name"] = "BabaJide" devops_student_data["completed_lessons"] = 5 print(devops_student_data["name"]) print(devops_student_data["completed_lessons"]) print("\n") # print keys or values from dict print(devops_student_data.keys()) print(devops_student_data.values()) print(devops_student_data.items()) print("\n") # How can we fetch the value called data types print(devops_student_data["completed_lesson_name"][2]) print(devops_student_data["completed_lesson_name"][:1]) print(devops_student_data["completed_lesson_name"][:]) print("\n") # Looping through the dictionary values for key, value in devops_student_data.items(): print(key + ':', value) # TASK: # create a new dict # name, dob, address, course, grades # create a list of hobbies of at least 3 items # methods of dictionary remove, add, replace # display data in reverse order of hobby list new_dict = { "name":"Emmanuel", "dob":"12/12/12", "address":"Bromley rd", "course":"DevOps", "grades":"A", "hobbies":["table tennis", "manga", "football"] } # add new_dict["new val"] = "hello world!" # replace new_dict["name"] = "john" # reverse list print(new_dict["hobbies"][::-1]) # remove new_dict.pop("grades") # dict_print print(new_dict) print("\n") # loop print for key, value in new_dict.items(): print(key + ':', value) print("\n") # adding and removing item inside the dictionary list new_dict["hobbies"].append("running") print(new_dict) new_dict["hobbies"].remove("running") print(new_dict)
f644625592e271fa67a67e38f66ba59b91bfa2ea
tcbegley/advent-of-code
/2015/day05.py
858
3.671875
4
import re import sys from string import ascii_lowercase DOUBLE_PAIR = re.compile(r"([a-z]{2}).*(\1)") SANDWICH = re.compile(r"([a-z]).(\1)") def load_data(path): with open(path) as f: return f.read().strip().split("\n") def is_nice_1(s): vowel_count = sum(s.count(c) for c in "aeiou") >= 3 repeated_letter = any((2 * c in s for c in ascii_lowercase)) no_disallowed = all((c not in s for c in ("ab", "cd", "pq", "xy"))) return all((vowel_count, repeated_letter, no_disallowed)) def is_nice_2(s): return all([DOUBLE_PAIR.search(s), SANDWICH.search(s)]) def part_1(strings): return sum(map(is_nice_1, strings)) def part_2(key): return sum(map(is_nice_2, strings)) if __name__ == "__main__": strings = load_data(sys.argv[1]) print(f"Part 1: {part_1(strings)}") print(f"Part 2: {part_2(strings)}")
f32381bc5aff7590162964b0b268fab61450643d
mauriciocabreira/Udacity_DAND_Project_1_Create_report_cities
/project1v1.py
561
3.5
4
# We import Pandas as pd into Python import pandas as pd Temperatures = pd.read_csv('./temp_data_from_db.csv') print("data is of type:", type(Temperatures)) print("Temperature shape: ", Temperatures.shape) print(Temperatures) print(Temperatures.head(10)) print(Temperatures.tail(20)) print(Temperatures.isnull().any()) print("Describe: ", Temperatures.describe()) #print("Describe YEAR: ", Temperatures['Year'].describe()) print("Describe Guarulhos: ", Temperatures['Guarulhos'].describe()) #print("Describe Global: ", Temperatures['Global'].describe())
45ddf3072090e3b28cf58a838e2ee8ce8c0de918
emrehaskilic/tekrar
/introduction/lesson4/set.py
267
3.71875
4
# .set() unique değer tutar myset = set() print(myset) myset.add(1) myset.add(2) myset.add(3) print(myset) myset.add(1) myset.add(2) myset.add(3) print(myset) #set() unique deger tuttugu için 1,2,3 elemanlarını yalnızca 1 kere yazacak tekrarlamayacaktır
ba77ead3ff503e00b305d87bc294b902243d1abe
jiewu-stanford/leetcode
/393. UTF-8 Validation.py
999
3.640625
4
''' Title : 393. UTF-8 Validation Problem : https://leetcode.com/problems/utf-8-validation/ ''' ''' Reference: https://leetcode.com/problems/utf-8-validation/discuss/87494/Short'n'Clean-12-lines-Python-solution ''' class Solution: def validUtf8(self, data: List[int]) -> bool: def check(data, startindex, size): for i in range(startindex+1, startindex+size+1): if i >= len(data) or (data[i]>>6) != 0b10: return False return True if not data: return False start = 0 while start < len(data): first = data[start] if (first >> 3) == 0b11110 and check(data, start, 3): start += 4 elif (first >> 4) == 0b1110 and check(data, start, 2): start += 3 elif (first >> 5) == 0b110 and check(data, start, 1): start += 2 elif (first >> 7) == 0: start += 1 else: return False return True
0bb3d894c5d0f77dba078b40ba9e598799834182
max-graham/knn_from_scratch
/knn/knn.py
2,833
3.6875
4
import numpy as np from scipy import stats def main(k: int): # dummy data, replace with data from file(s) train = np.arange(4 * 4).reshape((4, 4)) train_labels = np.array(['a', 'b', 'c', 'd']) test = np.arange(2 * 4).reshape((2, 4)) test_labels = np.array(['a', 'b']) predicted = knn(k=k, test=test, train=train, train_labels=train_labels) accuracy = calculate_accuracy(predicted=predicted, actual=test_labels) print(f'Model accuracy was: {accuracy}') def knn(k: int, test: np.ndarray, train: np.ndarray, train_labels: np.ndarray) -> np.ndarray: """ Performs the K-nearest neighbors algorithm. Args: k: int, how many neighbors to consider test: np.array of samples to be classified, with shape (test_rows, features) train: np.array of samples with known labels, with shape (train_rows, features) train_labels: np.array of labels for the training samples, with shape (train_rows, 1) Returns: np.array with shape (test_rows, 1), indicating the most common label of the K nearest neighbors for each testing sample. """ distances = calculate_distances(train=train, test=test) # find the K closest training samples neighbor_indices = np.argpartition(distances, kth=k, axis=1)[:, :k] # get the labels of the K closest training samples k_closest_labels = train_labels[neighbor_indices] # get the most frequent label of the nearest points labels, counts = stats.mode(k_closest_labels, axis=1) return labels def calculate_distances(train: np.ndarray, test: np.ndarray) -> np.ndarray: """ Calculates the distance between each test point and all training points. Args: train: np.array of shape (num_train_points, num_features) test: np.array of shape (num_test_points, num_features) Returns: np.array of shape (num_test_points, num_train_points) containing the euclidean distance from each test observation to each training observation. """ vector_diff = test[:, np.newaxis] - train distances = np.linalg.norm(vector_diff, ord=2, axis=2) return distances def calculate_accuracy(predicted: np.ndarray, actual: np.ndarray) -> float: """ Given two vectors, returns the percentage of values that match between the two, element-wise. Args: predicted: np.array containing the predicted labels actual: np.array containing the actual labels Returns: float, the percentage of predictions that matched the actual label. """ predicted = predicted.reshape((-1,)) actual = actual.reshape((-1,)) matches = np.where(predicted == actual, 1, 0) return np.sum(matches) / len(matches) if __name__ == '__main__': main(k=2)
1597b0d21ba315b0d54fe6f0cd13a6068847c982
thedarkknight513v2/daohoangnam-codes
/C4E18 Sessions/Homework/Session_1/four_ex.py
133
3.625
4
# for i in range (2, 10, 3): # print(i) # print(*range(5)) # Cac so chan nho hon 100 for i in range (0, 100,2): print (i)
f88b98d49ded4384c1dbbf9b79a9c0445ed11cb2
TheSchnoo/gridgame
/character.py
7,021
3.640625
4
import random EMPTY_SPACE = 0 def print_attacks(attacks): for attack_key in attacks: print(attack_key + ": " + str(attacks.get(attack_key))) class Character(object): def __init__(self, name, pos, token, attack, defense, speed, endurance, health, strategy): self.name = name self.pos = pos self.token = token self.attack = attack self.defense = defense self.speed = speed self.endurance = endurance self.health = health self.max_endurance = endurance self.strategy = strategy self.blocking = False # ============= DEFENSE ============= def take_damage(self, damage): # if blocking, reduce damage taken if self.blocking: damage /= (10*self.defense) self.blocking = False # if defense high enough, get a chance of missing if is_chosen(self.defense/50): # chance of getting a miss if is_chosen(0.5): return self.health self.health -= damage return self.health # ============= OFFENSE ============= def find_target(self, players, board): for key in players: if not players.get(key) == self: if board.is_adjacent(self.pos, players.get(key).pos) \ and players.get(key).health > 0: return players.get(key) return def calculate_damage(self, damage): # randomizing factor endurance_penalty = 0 miss_penalty = 0 if not self.endurance == self.max_endurance: if is_chosen(0.1): endurance_penalty = 1-(self.max_endurance/100)*(5/self.endurance) if is_chosen(1-(2*self.attack/100)): miss_penalty = 0.5 if is_chosen(endurance_penalty + miss_penalty): return 0 return calculate_attack(damage) def choose_attack(self, target): attacks = {'1': self.attack} print_attacks(attacks) # list_attacks selected_attack = input("Which attack? ") # damage = select attacks from list damage = 0 if attacks.get(selected_attack): damage = attacks.get(selected_attack) self.deal_damage(damage, target) def deal_damage(self, damage, player_target): self.face(player_target.pos) attack = self.calculate_damage(damage) # if defender is significantly faster than attacker, no directional effect if not player_target.speed >= self.speed * 2: if is_attack_from_side(self.token, player_target.token): attack *= 1.5 elif is_attack_from_behind(self.token, player_target.token): attack *= 2.0 if attack == 0: print("ATTACK IS 0!") print(self.name + " attacks! --> target health: " + str(player_target.health)) print(player_target.take_damage(attack)) player_target.face(self.pos) # ============= POSITIONING ============= def face(self, position): if position == self.pos + 1: self.token = '>' elif position == self.pos - 1: self.token = '<' elif position > self.pos + 1: self.token = 'V' elif position < self.pos - 1: self.token = '^' def move_east(self, board): start = self.pos self.token = '>' target_space = start + 1 if start % board.x_dim == board.x_dim - 1 and target_space > start: print("NO!") elif board.board[target_space] == EMPTY_SPACE: board.board[start] = EMPTY_SPACE board.board[target_space] = self.token self.pos = target_space return target_space return start def move_west(self, board): start = self.pos self.token = '<' target_space = start - 1 if start % board.x_dim == 0 and target_space < start: print("NO!") elif board.board[target_space] == EMPTY_SPACE: board.board[start] = EMPTY_SPACE board.board[target_space] = self.token self.pos = target_space return target_space return start def move_north(self, board): start = self.pos self.token = '^' target_space = start - board.x_dim if target_space < 0: print("NO!") elif board.board[target_space] == EMPTY_SPACE: board.board[start] = EMPTY_SPACE board.board[target_space] = self.token self.pos = target_space return target_space return start def move_south(self, board): start = self.pos self.token = 'V' target_space = start + board.x_dim if target_space > len(board.board): print("NO!") elif board.board[target_space] == EMPTY_SPACE: board.board[start] = EMPTY_SPACE board.board[target_space] = self.token self.pos = target_space return target_space return start def move_x(self, board, horiz_dist): if horiz_dist >= 0: return self.move_east(board) else: return self.move_west(board) def move_y(self, board, vert_dist): if vert_dist >= 0: return self.move_south(board) else: return self.move_north(board) def follow(self, target, board): self_p = board.get_x_y(self.pos) target_p = board.get_x_y(target.pos) if abs(target_p.x - self_p.x) > abs(target_p.y - self_p.y): return self.move_x(board, target_p.x - self_p.x) else: return self.move_y(board, target_p.y - self_p.y) def travel(self, first_step, board): move_list = [first_step] steps = 1 while steps < self.speed: next_move = input('And? ') move_list.append(next_move) steps += 1 for move in move_list: if move == 'u': self.move_north(board) elif move == 'd': self.move_south(board) elif move == 'r': self.move_east(board) elif move == 'l': self.move_west(board) # ============= HELPERS ============= def is_chosen(probability): return random.random() < probability def calculate_attack(attack): if is_chosen(0.10): return attack*1.20 elif is_chosen(0.10): return attack*.80 return attack def is_attack_from_side(attacker, defender): if ((attacker == '>' or attacker == '<') and (defender == 'V' or defender == '^')) \ or ((attacker == 'V' or attacker == '^') and (defender == '>' or defender == '<')): print("attack from side!") return True return False def is_attack_from_behind(attacker, defender): if attacker == defender: print("attack from behind!") return True return False
e5439b891e9c81193823092916303152b11587d5
manudeepsinha/daily_commit
/2021/01/python/12_queue.py
1,912
4.03125
4
''' the following code is of queue and if I add some new methods to the class i'll post in a what's new section. what's new: Queue class with following methods: add add_all pop pop_all print_que check_empty pending: ''' class Queue: def __init__ (self): self.queue = [] def add (self,val): if val not in self.queue: self.queue.insert(0,val) print(f'{val} is added in the queue.') return print(f'{val} is already in the queue.') return def add_all (self): que = input("Enter the elements space seperated: ") que = que.split() count = 0 for item in que: self.queue.append(item) count += 1 print(f"Added {count} elements in the queue.") return def pop (self): if self.check_empty(): return print(f'Popped item is: {self.queue.pop()}') return def pop_all (self): if self.check_empty(): return iterate = len(self.queue) for item in range(iterate): self.queue.pop() return def print_que (self): if self.check_empty(): return print(self.queue[::-1]) return def check_empty (self): if len(self.queue) == 0: print("Queue is empty!\nAdd some elements using add method.") return True return False #test code my_que = Queue() my_que.add(40) my_que.add(30) my_que.add(20) my_que.add(10) my_que.print_que() my_que.pop() my_que.pop() my_que.pop() my_que.pop() my_que.pop() my_que.check_empty() my_que.add_all() my_que.print_que() my_que.pop_all() my_que.print_que()
c688f064e3435389b8bdf99ed8a6c336f804c70c
Dis-count/Python_practice
/Practice/code_class/Crossin-practices/python_weekly_question/eqip.py
2,112
3.71875
4
from itertools import combinations_with_replacement from itertools import permutations from itertools import combinations, product import itertools items = [ {'name':'影者之足','price':'690'}, {'name':'巨人之握','price':'1500'}, {'name':'破甲弓','price':'2100'}, {'name':'泣血之刃','price':'1740'}, {'name':'无尽战刃','price':'2140'}, {'name':'贤者的庇护','price':'2080'}, ] ''' 在不考虑装备重复的情况之下,即可以多次购买一件装备,要填满六格物品栏, 有多少种购买方式?写一个程序,输出所有可行的购买组合。 ''' def one(items, bound): count = 0 for p in combinations_with_replacement(items, 6): sum_price = [] for f in p: sum_price.append(int(f['price'])) if sum(sum_price) < bound: count += 1 # print(p, '总计金额:%s' % sum(sum_price)) print('总共有%s种购买方式' % count) ''' 如果没有6格物品栏限制,有多少种购买方式? ''' def two(item, bound): price_list = [] for price in item: price_list.append(int(price['price'])) max_length = bound // min(price_list) count = 0 for n in range(1, max_length+1): for c in itertools.combinations_with_replacement(price_list,n): if sum(c) <= bound: count += 1 # print('+'.join(map(str, c))) print('共有%s种购买方式' %count ) ''' 在 1 的前提下,影忍之足最多购买一次,现在有多少种购买方式? ''' def three(item, bound): price_list = [] for price in item: price_list.append(int(price['price'])) max_length = bound // min(price_list) count = 0 for n in range(1, max_length+1): for c in itertools.combinations_with_replacement(price_list,n): if sum(c) <= bound: string = '+'.join(map(str, c)) if string.count('690') < 1: count += 1 print('共有%s种购买方式' %count ) one(items,10000) two(items,10000) three(items, 10000)
5f1a98b30e386ba5b1250e18d897b654ae15b102
jyabka/PythonExam
/15.TryToDestroyTheWorld.py
196
3.8125
4
def DivideByZero(_number): try: _number = _number / 0 except ZeroDivisionError: print("Error! Attempt to divide by zero!!") num = input() DivideByZero(int(num)) input()