blob_id
stringlengths
40
40
repo_name
stringlengths
5
119
path
stringlengths
2
424
length_bytes
int64
36
888k
score
float64
3.5
5.22
int_score
int64
4
5
text
stringlengths
27
888k
1e3d745bddc1d6af8510431dec4dff27f1f08db1
nimishbongale/5th-Sem-ISE
/SEE/Scripting/2/2b/2b.py
2,243
3.75
4
import pandas as pd from pandas import Series, DataFrame import numpy as np import matplotlib.pyplot as plt import seaborn as sns student_df = pd.read_csv("StudentsPerformance.csv") print("======Data Headers=======") student_df.head() print("=====Data Decription=====") student_df.info() student_df.describe() student_df1 = student_df.drop(['lunch', 'test preparation course'], axis=1) student_df1.head() student_df1["parental level of education"] = student_df1["parental level of education"].fillna("high school") print(student_df1["parental level of education"]) # student_df1["race/ethnicity"] = student_df1['race/ethnicity'].map({ # "group A": "Asian Students", # "group B": "African Students", # "group C": "Afro-Asian Students", # "group D": "American Students", # "group E": "European Students" # }) print(student_df1.head(10)) ax = sns.countplot(x="test preparation course", hue="gender", palette="Set1", data=student_df) ax.set(title="Test Preparation", xlabel="Course", ylabel="Total") plt.show() # ax = sns.countplot(x="race/ethnicity", hue="gender", palette="Set1", data=student_df1) # ax.set(title="Students according to each group", xlabel="Ethnicity", ylabel="Total") # plt.show() # marks_intervals = [0, 40, 50, 60, 75] # categories = ['failed', 'second class', 'first class', 'distinction'] # student_df1['Marks_Categories_math'] = pd.cut(student_df1.mathscore, marks_intervals, labels=categories) # ax = sns.countplot(x="Marks_Categories_math", hue="gender", palette="Set1", data=student_df1) # ax.set(title="Math Marks Grouping", xlabel="Marks Groups", ylabel="Total") # plt.show() # student_df1['Marks_Categories_reading'] = pd.cut(student_df1.readingscore, marks_intervals, labels=categories) # ax = sns.countplot(x="Marks_Categories_reading", hue="gender", palette="Set1", data=student_df1) # ax.set(title="Reading Marks Grouping", xlabel="Marks Groups", ylabel="Total") # plt.show() # student_df1['Marks_Categories_writing'] = pd.cut(student_df1.writingscore, marks_intervals, labels=categories) # ax = sns.countplot(x="Marks_Categories_writing", hue="gender", palette="Set1", data=student_df1) # ax.set(title="Writing Marks Grouping", xlabel="Marks Groups", ylabel="Total") # plt.show()
604708a7ada56fe57a4eb440cf1bf606c6da4619
omaransarispi/Towel
/src/Utils/Token/Tokenizer.py
2,078
3.859375
4
from abc import ABC, abstractmethod from typing import Optional from src.Utils.Token.Tokens import Tokens class Tokenizer(ABC): """The Tokenizer abstract class""" MAP_TO_ROMAN_NUMERAL_PATTERN = "MapToRomanNumeralPattern" INITIALIZE_CURRENCY_RATE_PATTERN = "InitializeCurrencyRatePattern" CONVERT_TO_ARABIC_NUMERAL_PATTERN = "ConvertToArabicNumeralPattern" CONVERT_MONEY_PATTERN = "ConvertMoneyPattern" INVALID_PATTERN = "InvalidPattern" def tokenize(self, query: str) -> Tokens: """Method that resolves the query to a command type""" token = self.tokenize_for_map_to_roman_numeral_pattern(query) if token: return token token = self.tokenize_for_initialize_currency_rate_pattern(query) if token: return token token = self.tokenize_for_convert_to_arabic_numeral_pattern(query) if token: return token token = self.tokenize_for_convert_money_pattern(query) if token: return token return self.tokenize_for_invalid_pattern(query) @abstractmethod def tokenize_for_map_to_roman_numeral_pattern(self, query: str) -> Optional[Tokens]: """Attempts to tokenize values for mapping to roman numeral pattern""" pass @abstractmethod def tokenize_for_initialize_currency_rate_pattern(self, query: str) -> Optional[Tokens]: """Attempts to tokenize values for initialize currency rate pattern""" pass @abstractmethod def tokenize_for_convert_to_arabic_numeral_pattern(self, query: str) -> Optional[Tokens]: """Attempts to tokenize values for convert to arabic numeral pattern""" pass @abstractmethod def tokenize_for_convert_money_pattern(self, query: str) -> Optional[Tokens]: """Attempts to tokenize values for initialize currency rate commands""" pass @abstractmethod def tokenize_for_invalid_pattern(self, query: str) -> Tokens: """Attempts to tokenize values for initialize currency rate commands""" pass
f606c84b1771a68afdf6ea8fafb01d8655710eae
monk-after-90s/python
/producer_consumer_while.py
510
3.53125
4
import time from datetime import datetime def consumer(): temp_task = None while True: temp_task = yield f'{temp_task}完成,time:{datetime.now()}' print(f'\n处理{temp_task},time:{datetime.now()}') time.sleep(1) print(f'完成{temp_task},time:{datetime.now()}') task_handler = consumer() task_handler.send(None) n = 1 while True: task = f'{n}号任务' print(f'发送{task},time:{datetime.now()}') print(task_handler.send(task)) n += 1
570803f08e14d1da71aac928d7cff5c8165c88f4
RakibRyan/nand2tetris-1
/Hack assembler/convert.py
1,374
3.625
4
""" Convert mnemonics into machine code @author:shubham1172 """ def dest(mnemonic): """ :param mnemonic: in original command :return: code for it """ data = ['', 'M', 'D', 'MD', 'A', 'AM', 'AD', 'AMD'] return bin(data.index(mnemonic))[2:].zfill(3) def comp(mnemonic): """ :param mnemonic: in original command :return: code for it """ data = { "": "0000000", "0": "0101010", "1": "0111111", "-1": "0111010", "D": "0001100", "A": "0110000", "!D": "0001101", "!A": "0110001", "-D": "001111", "-A": "0110011", "D+1": "0011111", "A+1": "0110111", "D-1": "0001110", "A-1": "0110010", "D+A": "0000010", "D-A": "0010011", "A-D": "0000111", "D&A": "0000000", "D|A": "0010101", "M": "1110000", "!M": "1110001", "-M": "1110011", "M+1": "1110111", "M-1": "1110010", "D+M": "1000010", "D-M": "1010011", "M-D": "1000111", "D&M": "1000000", "D|M": "1010101" } return data[mnemonic] def jump(mnemonic): """ :param mnemonic: in original command :return: code for it """ data = ["", "JGT", "JEQ", "JGE", "JLT", "JNE", "JLE", "JMP"] return bin(data.index(mnemonic))[2:].zfill(3)
a9803600c015f01638000f9c589612d351668616
mturpin1/CodingProjects
/Python/madlib.py
1,921
4.25
4
import os def madLibs(): words = [] input('Hello, and welcome to Mad Libs! Press \'Enter\' to continue...') input('''Instructions-The program will ask you for 15 words(noun, adjective, verb, etc.) After you have given all 15 words, the program will print a story, using the random words you have chosen. Hold on to your hat, you may create some interesting stories! Press \'Enter\' to continue...\n''') os.system('cls') words.append(input('Please type an adjective: ')) words.append(input('Please type an adjective: ')) words.append(input('Please type an adjective: ')) words.append(input('Please type a type of bird: ')) words.append(input('Please type a room in the house: ')) words.append(input('Please type a verb (past tense): ')) words.append(input('Please type a verb: ')) words.append(input('Please type a relative\'s name: ')) words.append(input('Please type a noun: ')) words.append(input('Please type a liquid: ')) words.append(input('Please type averb ending in -ing: ')) words.append(input('Please type apart of the body (plural): ')) words.append(input('Please type a plural noun: ')) words.append(input('Please type averb ending in -ing: ')) words.append(input('Please type a noun: ')) os.system('cls') print(f'''It was a {words[0]}, cold {words[1]} day. I woke up to the {words[2]} smell of {words[3]} roasting in the {words[4]} downstairs. I {words[5]} down the stairs to see if I could help {words[6]} the dinner. My mom said, \"See if {words[7]} needs a fresh {words[8]}.\" So I carried a tray of glasses full of {words[9]} into the {words[10]} room. When I got there, I couldn\'t believe my {words[11]}! There were {words[12]} {words[13]} on the {words[14 ]}!''') restart = input('Would you like to restart? (Y/N): ') if restart == 'Y' or restart == 'y': madLibs() else: exit() madLibs()
31dd023d8efa2107effc92321cdff0153df215b2
Cheng0639/CodeFights_Python
/Python/82_sortCodeFighters.py
1,693
3.640625
4
def sortCodefighters(codefighters): res = [CodeFighter(*codefighter) for codefighter in codefighters] res.sort(reverse=True) return list(map(str, res)) class CodeFighter(object): def __init__(self, username, id, xp): self.username = username self.id = int(id) self.xp = int(xp) def __lt__(self, other): return self.id > other.id if self.xp == other.xp else self.xp < other.xp def __str__(self): return "(user name = {name}, id = {id}, xp = {xp})".format(name=self.username, id=self.id, xp=self.xp) print(sortCodefighters([["warrior", "1", "1050"], ["Ninja!", "21", "995"], ["recruit", "3", "995"]])) # print(sortCodefighters([["Na", "59", "3"], # ["Huey", "5", "2"], # ["Elizabeth", "46", "8"], # ["Kelsi", "25", "7"], # ["Myrtice", "53", "2"], # ["Gene", "44", "3"], # ["Season", "77", "4"], # ["James", "20", "9"], # ["Kandy", "86", "1"], # ["Charise", "54", "10"], # ["Lanita", "91", "1"], # ["Jessie", "85", "4"], # ["Shantelle", "60", "6"], # ["Shad", "9", "5"], # ["Doretha", "68", "1"], # ["Jung", "57", "5"], # ["Linwood", "19", "8"], # ["Brynn", "2", "4"], # ["Lupe", "33", "2"], # ["Wilfred", "66", "10"]]))
01bc5a10ad8558364f65ce8f1fcc52b55f47633b
jaechoi15/CodingDojoAssignments
/Python/PythonOOP/self_init.py
435
3.859375
4
# class User(object): # name = "Anna" # anna = User() # print "Anna's name:", anna.name # User.name = "Bob" # print "Anna's name after change:", anna.name # bob = User() # print "Bob's name:", bob.name class User(object): def __init__(self, name, email): self.name = name self.email = email self.logged = False user1 = User("Anna Propas", "anna@anna.com") print user1.name print user1.logged print user1.email
16896a65d972a80731959d6189e5a3962fe772ac
fsouza/fisl_concorrencia_paralelismo
/sum.py
414
3.875
4
# Copyright 2013 Francisco Souza. All rights reserved. # Use of this source code is governed by a BSD-style # license that can be found in the LICENSE file. import multiprocessing def power(value): return value * value if __name__ == "__main__": numbers = xrange(1, 20001) pool = multiprocessing.Pool(20) powers = pool.map(power, numbers) sum = 0 for n in powers: sum += n print sum
be2a55a6e97e56ea7d4933b1486ae4e1317c8105
pavipr/pavi-codekata
/iso.py
110
3.671875
4
n=input().split() for i in n: m=set(i) if len(n)==len(m): print("Yes") else: print("No")
1ed1246fa3c70f8faace6c7a2e087eb93d0dd3d3
mazh661/distonslessons
/Lesson5/ex7.py
212
3.65625
4
arr=[ [0,1,1], [1,0,0] ] # arr=[1,2,3] count=0 #take array for i in range(len(arr)): temparr = arr[i] #go into array for j in temparr: if j == 1: count=count+1 print(count)
7ae0deeeee344565c97681aeb58c1327ee8a427e
tacongnam/oneshotAC
/extra/scrape_cf_contest_writers.py
1,504
3.546875
4
"""This script scrapes contests and their writers from Codeforces and saves them to a JSON file. This exists because there is no way to do this through the official API :( """ import json import urllib.request from lxml import html URL = 'https://codeforces.com/contests/page/{}' JSONFILE = 'contest_writers.json' def get_page(pagenum): url = URL.format(pagenum) with urllib.request.urlopen(url) as f: text = f.read().decode() return html.fromstring(text) def get_contests(doc): contests = [] rows = doc.xpath('//div[@class="contests-table"]//table[1]//tr')[1:] for row in rows: contest_id = int(row.get('data-contestid')) name, writers, start, length, standings, registrants = row.xpath('td') writers = writers.text_content().split() contests.append({'id': contest_id, 'writers': writers}) return contests print('Fetching page 1') page1 = get_page(1) lastpage = int(page1.xpath('//span[@class="page-index"]')[-1].get('pageindex')) contests = get_contests(page1) print(f'Found {len(contests)} contests') for pagenum in range(2, lastpage + 1): print(f'Fetching page {pagenum}') page = get_page(pagenum) page_contests = get_contests(page) print(f'Found {len(page_contests)} contests') contests.extend(page_contests) print(f'Found total {len(contests)} contests') with open(JSONFILE, 'w') as f: json.dump(contests, f) print(f'Data written to {JSONFILE}')
f7348b13a294674fac9db9bc9f27ff5f00caa2f4
viver2003/school
/whole_or_decimal.py
300
4.34375
4
import math x=float(input('number')) if x == 0: print 'This number is niether positive nor negative!' elif x > 0: print 'This number is a positive number!' else: print 'This number is a negative number!' if x%2: print 'This is a even number!' else: print 'This is an odd number!'
fe9f8a1ae39343ed9fd54eb5851575e7726cdef5
drunkwater/leetcode
/hard/python/c0153_798_smallest-rotation-with-highest-score/00_leetcode_0153.py
1,600
3.53125
4
# DRUNKWATER TEMPLATE(add description and prototypes) # Question Title and Description on leetcode.com # Function Declaration and Function Prototypes on leetcode.com #798. Smallest Rotation with Highest Score # Given an array A, we may rotate it by a non-negative integer K so that the array becomes A[K], A[K+1], A{K+2], ... A[A.length - 1], A[0], A[1], ..., A[K-1]. Afterward, any entries that are less than or equal to their index are worth 1 point. #For example, if we have [2, 4, 1, 3, 0], and we rotate by K = 2, it becomes [1, 3, 0, 2, 4]. This is worth 3 points because 1 > 0 [no points], 3 > 1 [no points], 0 <= 2 [one point], 2 <= 3 [one point], 4 <= 4 [one point]. #Over all possible rotations, return the rotation index K that corresponds to the highest score we could receive. If there are multiple answers, return the smallest such index K. #Example 1: #Input: [2, 3, 1, 4, 0] #Output: 3 #Explanation: #Scores for each K are listed below: #K = 0, A = [2,3,1,4,0], score 2 #K = 1, A = [3,1,4,0,2], score 3 #K = 2, A = [1,4,0,2,3], score 3 #K = 3, A = [4,0,2,3,1], score 4 #K = 4, A = [0,2,3,1,4], score 3 #So we should choose K = 3, which has the highest score. # Example 2: #Input: [1, 3, 0, 2, 4] #Output: 0 #Explanation: A will always have 3 points no matter how it shifts. #So we will choose the smallest K, which is 0. #Note: #A will have length at most 20000. #A[i] will be in the range [0, A.length]. #class Solution(object): # def bestRotation(self, A): # """ # :type A: List[int] # :rtype: int # """ # Time Is Money
a72b9fcd754bb72e541bca208f3bcec9fee3c5c7
Vdknet/python_graph
/algorithms/dijkstra/dijkstra.py
945
3.515625
4
from structures.simple import Node, Edge def list_to_node_graph(g): graph = [] for i in range(len(g)): graph.append(Node(i)) for i in range(len(graph)): for e in g[i].keys(): val = g[i].get(e) edge = Edge(e, val, graph[e]) reverse_edge = Edge(i, val, graph[i]) if edge not in graph[i].adj: graph[i].adj.append(edge) if reverse_edge not in graph[e].adj: graph[e].adj.append(reverse_edge) return graph def extract_min(arr): arr.sort(key=lambda item: item.d) return arr.pop(0) def relax(a, b, w): if b.d > a.d + w: b.d = a.d + w b.parent = a def dijkstra(g, s): done_nodes = [] q = list_to_node_graph(g) q[s].d = 0 while q: u = extract_min(q) done_nodes.append(u) for adj in u.adj: relax(u, adj.node, adj.val) return done_nodes
a6ebe746f4ec6aee2c6be01c02e9167cd48e3a42
houcha/the-lord-of-the-strategy
/windows/image_states.py
1,034
3.546875
4
""" This module contains window image states (constant and temporary). """ from abc import ABC import time import pygame # State pattern. class ImageState(ABC): """ Base class of image states. """ def __init__(self, window): self.window = window def update(self): """ Is called to check whether image should be changed or not. """ class ConstantImageState(ImageState): """ Class represents `constant` (simple) image state. """ class TemporaryImageState(ImageState): """ Class represents `temporary` image state. """ def __init__(self, window, tmp_image: pygame.Surface, delay: float): ImageState.__init__(self, window) self._previous_image = window.image self._delay = delay self._set_time = time.time() window.reset_image(tmp_image) def update(self): if time.time() - self._set_time > self._delay: self.window.reset_image(self._previous_image) self.window._image_state = ConstantImageState(self.window)
792a79c9939f7caf1846023ea5839502ad6d7d80
bweedop/housingPrices
/housingPrice.py
12,923
3.671875
4
from sklearn.model_selection import train_test_split from sklearn import datasets, linear_model, tree from sklearn.linear_model import LinearRegression, LassoCV from sklearn.metrics import mean_squared_error, r2_score from sklearn.preprocessing import StandardScaler, Imputer from sklearn.neural_network import MLPRegressor from sklearn.ensemble import RandomForestRegressor import pandas as pd import csv import matplotlib.pyplot as plt import numpy as np from scipy import stats from scipy.stats import norm from array import array import seaborn as sns #Load the training and test data into pandas dataframes. train = pd.read_csv('train.csv') preTest = pd.read_csv('test.csv') #Take a look at what the data consists of... train.columns() pd.DataFrame.head(train) np.shape(train) #...wow #Let's take a look at a summary and the distribution of the sale prices. train['SalePrice'].describe() train['SalePrice'].skew() train['SalePrice'].kurt() sns.distplot(train.SalePrice) plt.show() #The sale price is skewed to the the right, # mean at about 180k, shows peakedness and positive skew. #Now, let's look at how SalePrice responds to some of the explanatory variables. explanatory1 = 'GrLivArea' data = pd.concat([train['SalePrice'], train[explanatory1]], axis=1) data.plot.scatter(x=explanatory1, y='SalePrice', ylim=(0,800000)) plt.show() explanatory2 = 'TotalBsmtSF' data = pd.concat([train['SalePrice'], train[explanatory2]], axis=1) data.plot.scatter(x=explanatory2, y='SalePrice', ylim=(0,800000)) plt.show() #Nice boxplot examples. explanatory3 = 'OverallQual' data = pd.concat([train['SalePrice'], train[explanatory3]], axis=1) f, ax = plt.subplots(figsize=(8, 6)) fig = sns.boxplot(x=explanatory3, y="SalePrice", data=data) fig.axis(ymin=0, ymax=800000) plt.show() explanatory4 = 'YearBuilt' data = pd.concat([train['SalePrice'], train[explanatory4]], axis=1) f, ax = plt.subplots(figsize=(16, 8)) fig = sns.boxplot(x=explanatory4, y="SalePrice", data=data) fig.axis(ymin=0, ymax=800000) plt.xticks(rotation=90) plt.show()#We can clearly see that SalePrice increases as the overall quality of the # house increases and the newer the house...no surprises here ;). #Now that we have seen some of the explanatory variables and how SalePrice # responds to those, how about we check how the others make SalePrice squirm? # First, we will make a correlation matrix heatmap... corrmat = train.corr() f, ax = plt.subplots(figsize=(12, 9)) sns.heatmap(corrmat, vmax=.8, square=True) plt.show() #SalePrice is obviously correlated with variables such as OverallQual, GrLivArea, # 1stFlrSF, Garage(x), etc. Also, we can see that with these explanatory variables # we have multicollinearity and therefore repetitive information. #Now, let's just look at the variables that have the highest correlations with # SalePrice. k = 10 #number of variables for heatmap cols = corrmat.nlargest(k, 'SalePrice')['SalePrice'].index cm = np.corrcoef(train[cols].values.T) sns.set(font_scale=1.25) hm = sns.heatmap(cm, cbar=True, annot=True, square=True, fmt='.2f', annot_kws={'size': 10}, yticklabels=cols.values, xticklabels=cols.values) plt.show() #'GarageCars' and 'GarageArea' are also some of the most strongly correlated variables. # However, as we discussed in the last sub-point, the number of cars that fit into the # garage is a consequence of the garage area. 'GarageCars' and 'GarageArea' are like twin brothers. # You'll never be able to distinguish them. Therefore, we just need one of these variables in our # analysis (we can keep 'GarageCars' since its correlation with 'SalePrice' is higher). # We could say the same for TotalBsmtSF and 1stFloorSF. #Maybe we should do some time-series analysis to get YearBuilt right? Let's do that now! #Okay now that we have some features selected, let's look at the correlation matrix #but this time we will use scatterplots... sns.set() cols = ['SalePrice', 'OverallQual', 'GrLivArea', 'GarageCars', 'TotalBsmtSF', 'FullBath', 'YearBuilt'] sns.pairplot(train[cols], size = 2.5) plt.show() #Here we can see some relationships that might have been obvious before but now we have empirical data # to backup our intuition that you probably aren't going to buy a house that has a larger basement area # than GrLivArea...unless you're a prepper. #Let's deal with our missing data now...Is there a lot missing data? Is there a pattern of data missing? #sum up all the missing data points from each of the variables... total = train.isnull().sum().sort_values(ascending=False) #Find the percentage of missing data pts for each of the variables... percent = (train.isnull().sum()/train.isnull().count()).sort_values(ascending=False) missing_data = pd.concat([total, percent], axis=1, keys=['Total', 'Percent']) missing_data.head(20) #Now, we should not even try to impute values for variables that have 15% or more data pts missing # and therefore we should probably just act like these variables never even existed...sshhh. #We can also see that some of the Garage(x) variables are missing a good amount of data as well. #However, we already decided that GarageCar expresses the most important information. #Regarding 'MasVnrArea' and 'MasVnrType', we can consider that these variables are not essential. # Furthermore, they have a strong correlation with 'YearBuilt' and 'OverallQual' which are already # considered. Thus, we will not lose information if we delete 'MasVnrArea' and 'MasVnrType'. #Finally, we have one missing observation in 'Electrical'. Since it is just one observation, # we'll delete this observation and keep the variable. train = train.drop((missing_data[missing_data['Total'] > 1]).index,1) #Getting all the variables # that we found had more than one missing data point and drops them from the train dataset. train = train.drop(train.loc[train['Electrical'].isnull()].index)#Dropping the one data pt which is missing # from the Electrical variable. train.isnull().sum().max() #We can check that there's no missing data left... #Scaling our data to look for any outliers in the SalePrice... saleprice_scaled = StandardScaler().fit_transform(train['SalePrice'][:,np.newaxis]) #Low and high ranges of our newly scaled data... low_range = saleprice_scaled[saleprice_scaled[:,0].argsort()][:10] high_range= saleprice_scaled[saleprice_scaled[:,0].argsort()][-10:] #Looks like there might be two in the high_range but we will simply keep an eye on these. #Now we will deal with some of the outliers that maybe you noticed earlier on in the variables such as GrLivArea... #deleting points. #Getting the IDs of the data points which should be deleted... train.sort_values(by = 'GrLivArea', ascending = False)[:2] #Ahh ID:1299 and 524 are the troublemakers... train = train.drop(train[train['Id'] == 1299].index) train = train.drop(train[train['Id'] == 524].index) #Now we will transform our data to meet statistical assumptions... #We should be meeting four(4) different statistical assumptions in our response and explanatory variables: #These assumptions are: (1)normality, (2)homoscedasticity, (3)linearity, and (4)absence of multicollinearity and correlated errors. #Lets start off with SalePrice... #Raw SalePrice histogram and normal probability plot sns.distplot(train['SalePrice'], fit=norm) pricePlot = stats.probplot(train['SalePrice'], plot=plt) plt.show()#Okay, not normal but that's fine...this is why we have tranformations... train['SalePrice'] = np.log(train['SalePrice']) #transformed SalePrice histogram and normal probability plot sns.distplot(train['SalePrice'], fit=norm) fig = stats.probplot(train['SalePrice'], plot=plt) scatter(train.SalePrice) plt.show() #Raw GrLivArea histogram and normal probability plot sns.distplot(train['GrLivArea'], fit=norm) plt.show() livPlot = stats.probplot(train['GrLivArea'], plot=plt) plt.show()#Not normal... #data transformation for GrLivArea train['GrLivArea'] = np.log(train['GrLivArea']) #Transformed GrLivArea histogram and normal probability plot... sns.distplot(train['GrLivArea'], fit=norm) fig = stats.probplot(train['GrLivArea'], plot=plt) plt.show()#Normal. Check! #Raw TotalBsmtSF histogram and normal probability plot sns.distplot(train['TotalBsmtSF'], fit=norm) plt.show() fig = stats.probplot(train['TotalBsmtSF'], plot=plt) plt.show()#Wow...well let's try to sort this out... #create column for new variable (one is enough because it's a binary categorical feature) #if area>0 it gets 1, for area==0 it gets 0 train['HasBsmt'] = pd.Series(len(train['TotalBsmtSF']), index=train.index) train['HasBsmt'] = 0 train.loc[train['TotalBsmtSF']>0,'HasBsmt'] = 1 train.loc[train['HasBsmt'] == 1,'TotalBsmtSF'] = np.log(train['TotalBsmtSF']) #histogram and normal probability plot sns.distplot(train[train['TotalBsmtSF']>0]['TotalBsmtSF'], fit=norm) plt.show() stats.probplot(train[train['TotalBsmtSF']>0]['TotalBsmtSF'], plot=plt) plt.show()#Looks sufficient to me...at least better than what it was... #Now let's check homoscedasticy... plt.scatter(train['GrLivArea'], train['SalePrice']) plt.scatter(train[train['TotalBsmtSF']>0]['TotalBsmtSF'], train[train['TotalBsmtSF']>0]['SalePrice']) plt.show() #Dummy variables for all of the categorical variables... train = pd.get_dummies(train) explanatory1 = 'GrLivArea' data = pd.concat([train['SalePrice'], train[explanatory1]], axis=1) data.plot.scatter(x=explanatory1, y='SalePrice', ylim=(0,20)) plt.show() explanatory2 = 'TotalBsmtSF' data = pd.concat([train['SalePrice'], train[explanatory2]], axis=1) data.plot.scatter(x=explanatory2, y='SalePrice', ylim=(0,20)) plt.show() #Nice boxplot examples. explanatory3 = 'OverallQual' data = pd.concat([train['SalePrice'], train[explanatory3]], axis=1) f, ax = plt.subplots(figsize=(8, 6)) fig = sns.boxplot(x=explanatory3, y="SalePrice", data=data) fig.axis(ymin=0, ymax=20) plt.show() explanatory4 = 'YearBuilt' data = pd.concat([train['SalePrice'], train[explanatory4]], axis=1) f, ax = plt.subplots(figsize=(16, 8)) fig = sns.boxplot(x=explanatory4, y="SalePrice", data=data) fig.axis(ymin=0, ymax=20) plt.xticks(rotation=90) plt.show() #Now let's get to the fun stuff... #Let's set aside the response variable... target = "SalePrice" #And the predictor variables... predictors = [x for x in cols if x not in target] X_train, X_test, y_train, y_test = train_test_split(train[predictors], train[target], test_size=0.3) print(X_train.shape, y_train.shape) print(X_test.shape, y_test.shape) model = LinearRegression() model.fit(X_train, y_train) test = preTest[predictors] test['GrLivArea'] = np.log(test['GrLivArea']) test['HasBsmt'] = pd.Series(len(test['TotalBsmtSF']), index=test.index) test['HasBsmt'] = 0 test.loc[test['TotalBsmtSF']>0,'HasBsmt'] = 1 test.loc[test['HasBsmt']==1,'TotalBsmtSF'] = np.log(test['TotalBsmtSF']) test = pd.get_dummies(test) test = test.drop('HasBsmt', axis = 1) imp = Imputer(missing_values='NaN', strategy='mean', axis=0) imp.fit(test) test = imp.transform(test) test = pd.DataFrame(data = test, columns=predictors) predictions = model.predict(test) predictions = list(np.exp(predictions)) submission = pd.DataFrame({"Id":list(preTest.Id), "SalePrice":predictions}) submission.to_csv('submission.csv', sep = ',', index=False) model = RandomForestRegressor(n_estimators=200, min_samples_leaf=5, max_features=0.2, random_state=1) model.fit(train[predictors], train[target]) predictions = model.predict(test) predictions = list(np.exp(predictions)) submission = pd.DataFrame({"Id":list(preTest.Id), "SalePrice":predictions}) submission.to_csv('submission.csv', sep = ',', index=False) nnModel = MLPRegressor( hidden_layer_sizes=(5,), activation='relu', solver='adam', alpha=0.001, batch_size='auto', learning_rate='constant', learning_rate_init=0.01, power_t=0.5, max_iter=1000, shuffle=True, random_state=9, tol=0.0001, verbose=False, warm_start=False, momentum=0.9, nesterovs_momentum=True, early_stopping=False, validation_fraction=0.1, beta_1=0.9, beta_2=0.999, epsilon=1e-08) nnFit = nnModel.fit(train[predictors], train[target]) nnPredictions = nnModel.predict(test) nnPredictions = list(np.exp(nnPredictions)) submission = pd.DataFrame({"Id":list(preTest.Id), "SalePrice":nnPredictions}) submission.to_csv('submission.csv', sep = ',') import itertools leafs = list(range(1,21)) feats=[x / 100.0 for x in range(1, 21)] rs = list(range(1,21)) params = [leafs, feats, rs] score = [] for i in itertools.product(*params): param = i model = RandomForestRegressor(n_estimators=200, min_samples_leaf=param[0], max_features=param[1], random_state=param[2]) model.fit(X_train, y_train) predictions = model.predict(X_test) score.append(model.score(X_test, y_test)) results = [] for i in itertools.product(*params): results.append(i) opt = score.index(max(score)) optParams = results[opt] scale_LCV.fit(train_unskew.drop(['SalePrice','Id'], axis = 1), train_unskew['SalePrice'])
3ab1f0e168c80a9f70f9337b55f158f21d972b5b
sookoor/PythonInterviewPrep
/BinaryTree.py
10,125
3.84375
4
import sys class Node(object): def __init__(self, data = None): self.data = data self.children = [None, None] self.parent = None class BinaryTree(object): def __init__(self): self.root = None def _insert_node(self, root, data): if root is None: root = Node(data) else: child = data > root.data root.children[child] = self._insert_node(root.children[child], data) root.children[child].parent = root return root def insert_node(self, data): self.root = self._insert_node(self.root, data) def _in_order(self, root): if root is not None: self._in_order(root.children[0]) print(root.data) self._in_order(root.children[1]) def in_order(self): self._in_order(self.root) def _pre_order(self, root): if root is not None: print(root.data) self._pre_order(root.children[0]) self._pre_order(root.children[1]) def pre_order(self): self._pre_order(self.root) def _post_order(self, root): if root is not None: self._post_order(root.children[0]) self._post_order(root.children[1]) print(root.data) def post_order(self): self._post_order(self.root) def _level_order_linked_lists(self, root, level, list_collection): if root is not None: if len(list_collection) <= level: list_collection.append([root]) else: list_collection[level].append(root) if root.children[0]: self._level_order_linked_lists(root.children[0], level + 1, list_collection) if root.children[1]: self._level_order_linked_lists(root.children[1], level + 1, list_collection) def level_order_linked_lists(self): list_collection = [] self._level_order_linked_lists(self.root, 0, list_collection) return list_collection def _insert_node(self, root, data, bst): if root is None: root = Node(data) else: if bst == True: child = data > root.data else: child = data < root.data root.children[child] = self._insert_node(root.children[child], data, bst) root.children[child].parent = root return root def insert_node(self, data, bst = True): self.root = self._insert_node(self.root, data, bst) def build_binary_tree(self, array, bst = True): mid = len(array) / 2 self.insert_node(array[mid], bst) left = array[:mid] if left: self.build_binary_tree(left, bst) right = array[mid+1:] if right: self.build_binary_tree(right, bst) def max_depth(self, root): if root is None: return 0 return 1 + max(self.max_depth(root.children[0]), self.max_depth(root.children[1])) def min_depth(self, root): if root is None: return 0 return 1 + min(self.min_depth(root.children[0]), self.min_depth(root.children[1])) def check_balanced(self): return self.max_depth(self.root) - self.min_depth(self.root) <= 1 def next_node(self, node): if node is None: return elif node.children[1]: next_node = node.children[1] while next_node.children[0] is not None: next_node = next_node.children[0] return next_node elif node.parent: next_node = node.parent while node.parent and next_node.children[0] != node: node = next_node next_node = next_node.parent if next_node is not None and next_node.children[0] == node: return next_node def _LCA(self, root, p, q): if root is None: return None elif root == p or root == q: return root else: left = self._LCA(root.children[0], p, q) right = self._LCA(root.children[1], p, q) # If p and q are on either side of root if left and right: return root elif left: return left else: return right def LCA(self, p, q): return self._LCA(self.root, p, q) def _is_identical(self, root1, root2): if root1 is None and root2 is None: return True elif root1 is None or root2 is None: return False else: return root1.data == root2.data and self._is_identical(root1.children[0], root2.children[0]) and self._is_identical(root1.children[1], root2.children[1]) def _is_subtree(self, root, target): if root is None: return False elif target is None or self._is_identical(root, target): return True else: return self._is_subtree(root.children[0], target) or self._is_subtree(root.children[1], target) def is_subtree(self, target): return self._is_subtree(self.root, target.root) def _check_sum(self, root, value, paths, cur_path=None): if cur_path is None: cur_path = [] if root is not None: if root.data == value: cur_path = [] paths.append([root.data]) elif root.data > value: cur_path = [] elif root.data + sum(cur_path) < value: cur_path.append(root.data) elif root.data + sum(cur_path) == value: paths.append(cur_path + [root.data]) cur_path = [] elif root.data + sum(cur_path) > value: cur_path = [root.data] self._check_sum(root.children[0], value, paths, cur_path) self._check_sum(root.children[1], value, paths, cur_path) def check_sum(self, value): paths = [] self._check_sum(self.root, value, paths) return paths def _longest_bst(self, root): if root is None: return 0 else: left_size = self._longest_bst(root.children[0]) right_size = self._longest_bst(root.children[1]) max_child_size = max(abs(left_size), abs(right_size)) if left_size == 0 and right_size == 0: return 1 elif left_size < 0 or right_size < 0: return - max_child_size elif left_size == 0: if root.data < root.children[1].data: return 1 + right_size else: return -right_size elif right_size == 0: if root.data >= root.children[0].data: return 1 + left_size else: return -left_size elif root.data >= root.children[0] and root.data < root.children[1]: return 1 + max_child_size else: return -max_child_size def longest_bst(self): return abs(self._longest_bst(self.root)) def _is_bst(self, root): if root is None: return True else: left = self._is_bst(root.children[0]) if root.children[0] is not None: left = left and root.children[0].data <= root.data right = self._is_bst(root.children[1]) if root.children[1] is not None: right = right and root.children[1].data > root.data return left and right def is_bst(self): return self._is_bst(self.root) if __name__ == "__main__": binary_tree = BinaryTree() data = [5, 2, 8, 4, 9, 3, 1, 7, 6] for d in data: binary_tree.insert_node(d) print 'In-order' binary_tree.in_order() print '---' print 'Pre-order' binary_tree.pre_order() print '---' print 'Post-order' binary_tree.post_order() print '---' assert(binary_tree.check_balanced() == True) unbalanced_tree = BinaryTree() unbalanced_data = [2, 1, 3, 4, 6] for d in unbalanced_data: unbalanced_tree.insert_node(d) assert (unbalanced_tree.check_balanced() == False) built_tree = BinaryTree() built_tree.build_binary_tree(sorted(data)) print 'Built tree: ' list_collection = built_tree.level_order_linked_lists() for level, node_list in enumerate(list_collection): print "Level " + str(level) for node in node_list: print node.data cur_node = built_tree.root.children[1].children[0].children[0] next_node = built_tree.next_node(cur_node) if next_node: print "Next node of " + str(cur_node.data) + " is " + str(next_node.data) else: print "Node " + str(cur_node.data) + " does not have an in-order successor" p = built_tree.root.children[0].children[0] q = built_tree.root.children[1] lca = built_tree.LCA(p, q) if lca: print "The LCA of " + str(p.data) + " and " + str(q.data) + " is " + str(lca.data) else: print str(p.data) + " and " + str(q.data) + " do not have an LCA" s = [6, 7, 8, 9] t = [2, 3, 4] subtree = BinaryTree() subtree.build_binary_tree(s) not_subtree = BinaryTree() not_subtree.build_binary_tree(t) assert (binary_tree.is_subtree(subtree) == True) assert (binary_tree.is_subtree(not_subtree) == False) print built_tree.check_sum(5) print built_tree.check_sum(6) print built_tree.check_sum(17) bt = [5, 6, 12, 8, 9, 10] bin_tree = BinaryTree() bin_tree.build_binary_tree(bt) bin_tree.in_order() print bin_tree.longest_bst() assert binary_tree.is_bst() == True not_bst = BinaryTree() not_bst.build_binary_tree(s, False) lists = not_bst.level_order_linked_lists() for li in lists: for l in li: sys.stdout.write(str(l.data) + " ") print " " assert not_bst.is_bst() == False
345eea86c2944cf1e104d933ed8ad6fbe6eb820f
JuDa-hku/ACM
/leetCode/110BalancedBinaryTree.py
1,243
3.828125
4
# Definition for a binary tree node class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: # @param root, a tree node # @return a boolean def calculateHeight(self, root): if root == None: return 0 if root.right == None and root.left==None: return 1 height = max(self.calculateHeight(root.right), self.calculateHeight(root.left)) + 1 return height def checkOne(self, root): value = self.calculateHeight(root.right)-self.calculateHeight(root.left) if value==-1 or value == 1 or value==0: return True else: return False def isBalanced(self, root): if root == None: return True if root.right == None and root.left == None: return True if not self.checkOne(root): return False result = self.isBalanced(root.left) and self.isBalanced(root.right) return result s = Solution() a1 = TreeNode(1) a2 = TreeNode(2) a3 = TreeNode(3) a4 = TreeNode(4) a5 = TreeNode(5) a1.left = a2 # a2.left = a3 # a3.left = a5 a1.right = a4 print s.isBalanced(a1)
98e3a1bed80597b5e7b612ce9bc137fc9d695462
dvincelli/scalene
/scalene/reservoir.py
1,056
3.8125
4
import math import random class reservoir(): """Implements reservoir sampling to achieve the effect of a uniform random sample.""" sample_array = [] total_samples = 0 max_samples = 0 next_random_choice = 1 def __init__(self, size=0): self.max_samples = size self.total_samples = 0 self.sample_array = [] def add(self, value): self.total_samples += 1 if self.total_samples <= self.max_samples: self.sample_array.append(value) else: assert self.max_samples == len(self.sample_array) self.next_random_choice -= 1 #p = random.randint(0, self.total_samples - 1) if self.next_random_choice <= 0: # p < self.max_samples: # self.sample_array[p] = value self.sample_array[random.randint(0, self.max_samples - 1)] = value self.next_random_choice = round(random.expovariate(self.max_samples / self.total_samples), 0) def get(self): return self.sample_array
c27771c971d25aaee04c402b81652af414e968e4
ynonp/python-examples
/05_syntax_lab/03.py
534
4.09375
4
""" Write a program that generates a random number between 1 and 10,000, and prints the sum of its digits. For example if the number was: 2345 the result should be: 14. """ from random import randint num = randint(1,10000) print "Starting with: %d" % num # Numeric calculation num_i = num sum_d = 0 while num_i != 0: digit = num_i % 10 sum_d += digit num_i /= 10 print "Total sum of digits =", sum_d # String calculation num_s = str(num) total = 0 for digit in num_s: total += int(digit) print "Total = ",total
dd44b2e6833089f7ae941c4c7d5aa17a8f0cde65
dannydoyunkim/mytask
/Python_Practice/Python실습-김도연/제공/M3/example/m3_3_breakTest_001.py
237
3.5
4
count = 1 result = 0 limit = int(input("어디까지 더할까요? ")) while count <= 1000: result = result + count count = count + 1 if count == limit: break print("1부터 %d까지의 합은: %d"% (count,result))
17cfded552b023bb7bf7f213f4425e6f939b4b1d
alzheimeer/holbertonschool-higher_level_programming
/0x03-python-data_structures/7-add_tuple.py
333
3.734375
4
#!/usr/bin/python3 def add_tuple(tuple_a=(), tuple_b=()): a = list(tuple_a) b = list(tuple_b) la = len(a) lb = len(b) if la < 2: for i in range(la, 2): a.append(0) if lb < 2: for i in range(lb, 2): b.append(0) nt = [a[0] + b[0], a[1] + b[1]] return (tuple(nt))
2f16cec1cec7ce7b890042ab0c709368c341f288
Mohamedabdeltawab86/integration_vs_git
/algorithms - Harmash/evenBlock.py
282
4.21875
4
#take input from the user n = 0 m = 0 while n<=0 or m<=0: n = int(input('Enter a number of columns between 1-8: ')) m = int(input('Enter a number of hashes between 1-8: ')) #simple increasing block for i in range(1, n+1): print(" " * (n-i), end="") print("#" * m)
b0714244dd12fc90c710191bd24ce11da3027baa
sepehrs1378/CompilerFall2020
/Assignments/HW3/code.py
627
3.609375
4
def parseE(): parseT() parseEp() if tokern == "\$": return "success" else: return "error" def parseEp(): if token == "+": token = nextToken() parseE() elif token == "-": token = nextToken() parseE() elif token == "\$": return else: return "error" def pareT(): parseB() parseT() def parseB(): if token == "1": token = nextToken() parseC() else: return "error" def parseC(): if token == "1" or token == "0": token = nextToken() return else: return "error"
59bb871db2fce0918657725714bddae33494d7f5
urbaneriver426/OrderedList
/OrderedList.py
3,578
3.875
4
class Node: def __init__(self, v): self.value = v self.prev = None self.next = None class OrderedList: def __init__(self, asc): self.head = None self.tail = None self.__ascending = asc def compare(self, v1, v2): if v1 < v2: return -1 elif v1 == v2: return 0 else: return +1 def add(self, value): if self.head is None: self.head = Node(value) self.tail = self.head else: if self.__ascending == True: currNode = self.head prevNode = None cont = True while cont == True and currNode is not None: x = self.compare(value, currNode.value) if x == 1: currNode, prevNode = currNode.next, currNode else: cont = False if currNode is None: self.tail = Node(value) self.tail.prev, prevNode.next = prevNode, self.tail else: if currNode is self.head: currNode.prev = Node(value) currNode.prev.next, self.head = self.head, currNode.prev else: currNode.prev = Node(value) prevNode.next = currNode.prev currNode.prev.prev, currNode.prev.next = prevNode, currNode else: currNode = self.tail prevNode = None cont = True while cont == True and currNode is not None: x = self.compare(value, currNode.value) if x != -1: currNode, prevNode = currNode.prev, currNode else: cont = False if currNode is None: self.head = Node(value) self.head.next, prevNode.prev = prevNode, self.head else: if currNode is self.tail: currNode.next = Node(value) currNode.next.prev, self.tail = self.tail, currNode.next else: currNode.next = Node(value) prevNode.prev = currNode.next currNode.next.next, currNode.next.prev = prevNode, currNode def find(self, val): if self.len() == 0: return None else: if self.__ascending == True: currNode = self.head while currNode is not None: x = self.compare(currNode.value, val) if x == 1: return None elif x == 0: return currNode else: currNode = currNode.next if self.__ascending == False: currNode = self.tail while currNode is not None: x = self.compare(currNode.value, val) if x == 1: return None elif x == 0: return currNode else: currNode = currNode.prev if currNode == None: return None def delete(self, val): currNode = self.head prevNode = None if self.head is None: return None else: if self.head.value == val: if self.len() == 1: self.head = None self.tail = None return else: currNode = self.head.next self.head = currNode currNode.prev = None return while currNode is not None: if currNode.value == val: prevNode.next = currNode.next if currNode is self.tail: self.tail = prevNode else: currNode.next.prev = prevNode return else: prevNode = currNode currNode = currNode.next def clean(self, asc): self.head = None self.tail = None self.__ascending = asc def len(self): currNode = self.head count = 0 while currNode is not None: currNode = currNode.next count += 1 return count def get_all(self): r = [] node = self.head while node != None: r.append(node) node = node.next return r class OrderedStringList(OrderedList): def __init__(self, asc): super(OrderedStringList, self).__init__(asc) def compare(self, v1, v2): test_string1 = v1.strip() test_string2 = v2.strip() if v1 < v2: return -1 elif v1 == v2: return 0 else: return +1
905db15d8313e14cdbaca48a206f2ea9c986f273
balibuxiaxue/python_study
/findstr().py
209
3.5625
4
def findstr(): a=input('请输入目标字符串:') b=input('请输入子字符串(两个字符):') a.count(b) print('子字符串在目标字符串中共出现', a.count(b) ,'次')
6c716afb8855aa3fd6ab658fbb8e408f3a1fb9ec
yaggul/Programming0
/week1/3-And-Or-Not-In-Problems/evenover20.py
224
3.96875
4
print() print('Welcome to even and over 20') print() num=int(input("please insern a number: ")) if num%2==0 and num>20: print() print("Yes it is!") print() else: print() print("No it isn't!") print()
e8e98e10ee2e0d87549d87a825616a92dc9fb7d6
AlexKaravaev/ifmo
/bachelor/SPO/lab4/task3/stability.py
1,726
3.71875
4
# Вывод матрицы def out(matrix): if matrix: for i in range (0, rows(matrix)): print(matrix[i]) return " " def rows(matrix): return len(matrix) # Проверка устойчивости по Гурвицу def gur(A): koef = [] k1 = -A[0][0]*A[1][1]*A[2][2]+A[0][0]*A[2][1]*A[1][2]+A[1][0]*A[2][2]*A[0][1]-A[1][0]*A[0][2]*A[2][1]-A[2][0]*A[0][1]*A[1][2]+A[0][2]*A[1][1]*A[2][0] koef.append(k1) k2 = A[1][1]*A[2][2]-A[2][1]*A[1][2]+A[0][0]*A[2][2]+A[0][0]*A[1][1]-A[1][0]*A[0][1]-A[2][0]*A[0][2] koef.append(k2) k3 = -A[0][0]-A[1][1]-A[2][2] koef.append(k3) koef.append(1) print ("Характеристический полином:") print (str(koef[3])+'s^3+' + str(koef[2])+'s^2+'+str(koef[1])+'s+'+str(koef[0])+'=0') print('\n') matrix = [[koef[2],koef[0],0],[koef[3],koef[1],0],[0,koef[2],koef[0]]] print ("Матрица Гурвица:") print (out(matrix)) if (koef[2] > 0) and (koef[1]*koef[2]-koef[0]*koef[3] > 0) and (koef[0]>0): return "Система устойчива (по Гурвицу)" if (koef[2] > 0) and (koef[1]*koef[2]-koef[0]*koef[3] > 0) and (koef[0]==0): return "Система на апериодической гнанице устойчивости (по Гурвицу)" if (koef[2] > 0) and (koef[1]*koef[2]-koef[0]*koef[3] == 0) and (koef[0]>0): return "Система на колебательной гнанице устойчивости (по Гурвицу)" if (koef[2] < 0) or (koef[1]*koef[2]-koef[0]*koef[3] < 0) or (koef[0]<0): return "Система неустойчива (по Гурвицу)" if __name__ == '__main__': A = [[0,1,0],[0,0,1],[-1,-1,-3]] print("Матрица А:") print(out(A)) print('\n') print(gur(A))
3333a54dfac2b98cdccd24d8e65d32a6ee47b828
Neha-kumari200/python-Project2
/Count_freq_list.py
384
4.09375
4
#Counting the frequencies in the list using dictionary in python def CountFrequency(my_list): freq = {} for item in my_list: if item in freq: freq[item] += 1 else: freq[item] = 1 for key, value in freq.items(): print("%d : %d"%(key, value)) my_list = [1, 1, 1, 5, 5, 3, 3, 3, 6, 7, 8, 8, 8, 2, 2] CountFrequency(my_list)
bfc6e7438acee469fa3f1966a3471bcd834d4901
jimwaldo/HarvardX-Tools
/src/main/python/classData/user.py
4,317
3.578125
4
#!/usr/bin/env python """ Object definition and utility functions for the course users (students) file Contains a definition of a user object, that holds all of the information found in the users file for each entry. There is a function that will build a dictionary, keyed by the user id, for all of those entries. There is also a function that will remove any mal-formed entries in the file. Created on Feb 20, 2013 @author: waldo """ from convertfiles import xmltocsv import json class user(object): """ Representation of the data stored in the auth_user files This object contains all of the fields that are reported in a single entry from the auth_user extraction from the databases. These fields are self- reported, and not all of the fields are required, so they are often not all filled in. Further, a number of these fields are no longer used or reported, and so are ignored. """ def __init__(self, id, username, email, is_staff, is_active, is_super, last_l, date_j): """ Constructor for a user object This constructor creates and initializes the user object, using only the fields that are currently active. """ self.id = id self.username = username self.email = email self.is_staff = is_staff self.is_active = is_active self.is_super = is_super self.last_l = last_l self.data_j = date_j def builddict(f): """ Build a dictionary of user information, indexed by user_id Builds a dictionary of user information from a csv file. If any line in the file is not of the correct length, the line number will be printed and the information discarded. Parameters --------------- f: csv.reader An open csv.reader containing the authorized user data """ retdict = {} lineno = 0; #remove the header information from the dictionary f.next() for line in f: lineno += 1 if len(line) != 22: print ('bad line length at line' + str(lineno)) print ('expected 22, got ' + str(len(line))) continue [id, username, first, last, em, passwd, staff, active, \ super, lastl, djoin, status, emkey, avatar, country, shc, \ dob, inttags, igntags, emailt, displayt, concecdays] = line if id not in retdict: rec = user(id, username, em, staff, active, super, lastl, djoin) retdict[id] = rec return retdict def readdict(fin): """ Reconstruct a user dictionary from an open .csv file previously created by writedict Reads the contents of a csv file containing the dump of a user dictionary, and creates a dictionary containing the user data that is currently active. Input is a csv.reader object. Returns a dictionary, indexed by user id, where each line is a user object. """ retDict = {} fin.next() for id, uname, email, is_staff, is_active, is_super, last_l, date_j in fin: retDict[id] = user(id, uname, email, is_staff, is_active, is_super, last_l, date_j) return retDict def writedict(fout, udict): """ Save a user dictionary to an open .csv file, to be written by readdict Writes the contents of a user dictionary to an open csv file. The file will have a human-readable header placed on it that will need to be skipped on reading. """ fout.writerow(['User id', 'User name', 'email', 'Is Staff', 'Is active', 'Is superuser', 'Last Log', 'Date joined']) for u in iter(udict): ent = udict[u] fout.writerow([ent.id, ent.username, ent.email, ent.is_staff, ent.is_active, ent.is_super, ent.last_l, ent.date_j]) def scrubfile(f1, f2): """ Traverse a csv file, copying lines with the right number of entries to a second csv file Parameters: -------------- f1: csv.reader An open csv.reader object, containing the raw data f2: csv.writer An open csv.writer object, to which the scrubbed data will be written """ xmltocsv.scrubcsv(f1, f2, 22)
ca18ac4ee8c0ced3454a103ed3d64ac2723c79f4
Dynamonic/Slicer
/SliceTest/shape.py
5,360
3.6875
4
from SliceTest.point import Point from SliceTest.edge import Edge class Shape(object): MAX_X = 250 # USED FOR INTERSECTION ALGORITHM MAX_Y = 250 def __init__(self, data): self.points = data self.edges = [] self._gen_edges(self.points) def _gen_edges(self, lop): """generates a list of edges: edges are two connected points""" for i in range(len(lop)): if i != len(lop)-1: edge = Edge(lop[i], lop[i+1]) self.edges.append(edge) def get_edges(self): return self.edges def get_points(self): return self.points def get_size(self): # [min x, max x, min y, max y] vals = [10000, 0, 10000, 0] for point in self.points: if float(point.x) < float(vals[0]): vals[0] = point.x if float(point.x) > float(vals[1]): vals[1] = point.x if float(point.y) < float(vals[2]): vals[2] = point.y if float(point.y) > float(vals[3]): vals[3] = point.y return vals def in_shape(self, point): """determines if a given point lies inside the Shape object (note: a point lies inside a shape if a line extended to infinity in any direction from the point intersects with an odd number of the Shape's edges""" x = point.x y = point.y z = point.z x2 = point.x + self.MAX_X y2 = point.y z2 = point.z x3 = point.x y3 = point.y + self.MAX_Y z3 = point.z p1 = Point(x, y, z) # Create edge that is the point extended out to "infinity" in the X+ direction p2 = Point(x2, y2, z2) # Create edge that is the point extended out to "infinity" in the Y+ direction p3 = Point(x3, y3, z3) # if the point lies on one of the shapes edges then it is in the shape for edge in self.edges: if edge.point_on_line(p1): return True # end point check # Count the number of times that the extended line intersects with the edges of the shape count1 = 0 count2 = 0 for edge in self.edges: if self._intersect(edge, Edge(p1, p2)): count1 += 1 if self._intersect(edge, Edge(p1, p3)): count2 += 1 if count1 == count2 and count1 % 2 == 1: return True elif count1 != count2: # helps prevent errors with counting points between edges return True return False def _intersect(self, line1, line2): """ determines if two lines intersect line: [point1, point2] :param line1: First line :param line2: Second Line :return: True if intersecting, False otherwise """ # if either line has no length check if the point lies on the other line if line1.line_length() == 0: return line2.point_on_line(line1.point1) if line2.line_length() == 0: return line1.point_on_line(line2.point1) # check if endpoints of the line lie on the line (colinear) if line2.point_on_line(line1.point1): return True if line2.point_on_line(line1.point2): return True if line1.point_on_line(line2.point1): return True if line1.point_on_line(line2.point2): return True # Check if line segments are parallel s1 = line1.slope() s2 = line2.slope() if s1 == s2: return False # End Parallel check # Calculates intersect point assuming segments are lines if s1 is not None and s2 is not None: # Solve linear eqns b1 = float(line1.y_intercept()) b2 = float(line2.y_intercept()) if s1 != s2: x = (b2-b1)/(s1-s2) y = s1 * x + b1 else: return False elif s1 is not None: # this means s2 has one x value x = line2.point1.x y = s1 * x + line1.y_intercept() else: # s1 has one x value x = line1.point1.x y = s2 * x + line2.y_intercept() # Line segment stuff: # this checks the interval that would have the intersection # if calculated x and y are in the interval then the SEGMENTS intersect at point (x,y) x_vals = [line1.point1.x, line1.point2.x, line2.point1.x, line2.point2.x] y_vals = [line1.point1.y, line1.point2.y, line2.point1.y, line2.point2.y] x_vals.sort() y_vals.sort() x_int = [x_vals[1], x_vals[2]] y_int = [y_vals[1], y_vals[2]] if min(x_int) <= x <= max(x_int) and min(y_int) <= y <= max(y_int): return True else: return False if __name__ == "__main__": """USED FOR TESTING""" # IN_SHAPE() TESTS data = [Point(0, 0), Point(0, 12), Point(12, 12), Point(12, 0), Point(0, 0)] # 12x12 box shape1 = Shape(data) point1 = Point(24, 30) point2 = Point(10, 10) if not shape1.in_shape(point1): print("Test 1 passed") else: print("Test 1 failed") if shape1.in_shape(point2): print("Test 2 passed") else: print("Test 2 failed")
08dedad167a35d0ddf353de0ee4e7cf6e2f3ca3c
ricardroberg/fullstack_bootcamp
/0 - DJANGO_COURSE_FILES/13-Python_Level_Two/part8.py
3,342
3.59375
4
import re patterns = ['term1', 'term2'] text = 'This is a string with term1, not not the other!' # for pattern in patterns: # print(f"I'm searching for {pattern}") # # if re.search(pattern, text): # print("MATCH!") # else: # print("NO MATCH!") match = re.search('term1', text) print(type(match)) # <class 're.Match'> print(match.start()) # 22 - indice onde inicia o termo print(match.end()) # 27 - indice onde termina o termo split_term = '@' email = 'user@email.com' print(re.split(split_term, email)) # ['user', 'email.com'] print(re.findall('match', 'test phrase match in match middle')) # ['match', 'match'] #### def multi_re_find(patterns, phrase): for pat in patterns: print(f"Searching for pattern {pat}") print(re.findall(pat, phrase)) print("\n") test_phrase = 'sdsd..sssddd..sdddsddd...dsds...dssssss...sddddd' test_patterns = ['sd*'] # 0 ou mais test_patterns2 = ['sd+'] # 1 ou mais test_patterns3 = ['sd?'] # 0 ou 1 test_patterns4 = ['sd{3}'] # seguido de 3 test_patterns5 = ['sd{2,3}'] # seguido de 2 a 3 test_patterns6 = ['s[sd]+'] # busca 1 ou mais S ou D multi_re_find(test_patterns, test_phrase) # ['sd', 'sd', 's', 's', 'sddd', 'sddd', 'sddd', 'sd', 's', 's', 's', 's', 's', 's', 's', 'sddddd'] multi_re_find(test_patterns2, test_phrase) # ['sd', 'sd', 'sddd', 'sddd', 'sddd', 'sd', 'sddddd'] multi_re_find(test_patterns3, test_phrase) # ['sd', 'sd', 's', 's', 'sd', 'sd', 'sd', 'sd', 's', 's', 's', 's', 's', 's', 's', 'sd'] multi_re_find(test_patterns4, test_phrase) # ['sddd', 'sddd', 'sddd', 'sddd'] multi_re_find(test_patterns5, test_phrase) # ['sddd', 'sddd', 'sddd', 'sddd'] multi_re_find(test_patterns6, test_phrase) # ['sdsd', 'sssddd', 'sdddsddd', 'sds', 'ssssss', 'sddddd'] test_phrase2 = 'This is a string! But is has punctuation. How can we remove it?' test_patterns7 = ['[^!;?]+'] test_patterns8 = ['[a-z]+'] test_patterns9 = ['[A-Z]+'] multi_re_find(test_patterns7, test_phrase2) # ['This is a string', ' But is has punctuation. How can we remove it'] multi_re_find(test_patterns8, test_phrase2) # ['his', 'is', 'a', 'string', 'ut', 'is', 'has', 'punctuation', 'ow', 'can', 'we', 'remove', 'it'] multi_re_find(test_patterns9, test_phrase2) # ['T', 'B', 'H'] ### test_phrase3 = 'This is a string with numbers 12312 and a symbol #hashtag' test_patterns10 = [r'\d+'] # only numbers test_patterns11 = [r'\D+'] # only strings test_patterns12 = [r'\s+'] # spaces test_patterns13 = [r'\S+'] # non spaces test_patterns14 = [r'\w+'] # alphanumerics test_patterns15 = [r'\W+'] # non alphanumerics multi_re_find(test_patterns10, test_phrase3) # ['12312'] multi_re_find(test_patterns11, test_phrase3) # ['This is a string with numbers ', ' and a symbol #hashtag'] multi_re_find(test_patterns12, test_phrase3) # [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '] multi_re_find(test_patterns13, test_phrase3) # ['This', 'is', 'a', 'string', 'with', 'numbers', '12312', 'and', 'a', 'symbol', '#hashtag'] multi_re_find(test_patterns14, test_phrase3) # ['This', 'is', 'a', 'string', 'with', 'numbers', '12312', 'and', 'a', 'symbol', 'hashtag'] multi_re_find(test_patterns15, test_phrase3) # [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' #']
6aec09f3626d51fe389a5f6de34ea38ae8fa39e7
shuw/euler
/python/p23.py
2,126
3.90625
4
from math import * # Returns hash of prime factors + their power def findPrimeFactors(n, factors): if n == 1: return; secondLargestPrimeFactor = int(sqrt(n)) i = 2; while True: if i == n or i > secondLargestPrimeFactor: power = factors.get(n) if power == None: factors[n] = 0 factors[n] += 1 return if (n / float(i)) % 1 == 0: x = findPrimeFactors(i, factors) y = findPrimeFactors(n / i, factors) return i = i + 1 class PrimePart: def __init__(self, prime, power): self.prime = prime self.power = power def __repr__(self): return str(self.prime) + "^" + str(self.power) def divisorsRecursive(primes, index, product, divisors): if index == len(primes): divisors.append(product) return divisorsRecursive(primes, index + 1, product, divisors) primePart = primes[index] for i in range(primePart.power): product = product * primePart.prime divisorsRecursive(primes, index + 1, product, divisors) def properDivisorsSum(n): factors = {} findPrimeFactors(n, factors) primes = [] for i in factors: primes.append(PrimePart(i, factors[i])) divisors = [] divisorsRecursive(primes, 0, 1, divisors) sum = 0 for d in divisors: sum += d sum -= n # subtract the number itself because divisorsRecursive includes n as a divisor return sum def abundantNumbers(n): result = [] for n in range(2, n): dSum = properDivisorsSum(n) if dSum > n: # abundant number found result.append(n) return result def abundantNumberSums(abundantNumbers): results = {} for n1 in abundantNumbers: for n2 in abundantNumbers: results[n1 + n2] = True return results abundantNumbers = abundantNumbers(28123) sums = abundantNumberSums(abundantNumbers) answer = 0 for n in range(28123): if sums.get(n) == None: answer += n print answer
862c729de4ac49f69f67baebdeba0e1c67b5b4b8
GuillaumeJouetp/Compression_de_texte
/huffman_VF.py
10,675
3.734375
4
# ALGRORITHME DE HUFFMAN : COMPRESSION DE DONNEES def TableDeFrequence (texte): """ Construction d'une table de fréquences @ Entrée: un texte @ type: string @ Sortie: un dictionnaire qui pour chaque caractère présent dans le texte lui associe sa fréquence @ type: dict """ table={} # crée un dictionnaire vide for c in texte: # pour chaque caractère dans le texte if c in table: # si le caractère est déjà dans le texte table[c]=table[c]+1 # la valeur de la clef [nom du caractère] est incrémanté de 1 else: table[c]=1 # sinon crée la clef [nom du caractère] et l'assimile a la valeur = 1 return table # cette fonction crée une clef pour chaque caractère different def Arbre(table): """ Construction d'un arbre de Huffman @ Entrée: un dictionnaire (la table de fréquence) . les clefs sont les caractères, les valeurs sont leur fréquence @ type: dict @ Sortie: un dictionnaire structuré sous forme d'arbre binaire. les feuilles sont les caractères @ type: dict """ if table=={}: return {} else: tas = [] for k in table: # transforme le dictionnaire de fréquences en liste de fréquences. tas.append((table[k], k)) # ce qui permet d'utiliser les index du type list # cette liste est composée de couples de la forme (fréquence,caractère). tas = sorted(tas) # trie la liste par ordre croissant de fréquence # construction de l'arbre, un couple correspond à un noeud while len(tas) >= 2: # arrêt à 1 car un arbre binaire ne contient qu'un seul noeud père (freq1, LettreGauche) = tas[0] del tas[0] # supprime le couple de plus petite frequence du tas (car la tas est triée) (freq2, LettreDroite) = tas[0] del tas[0] # supprime le nouveau couple de plus petite frequence du tas SF = freq1+freq2 Noeud = {0: LettreGauche,1: LettreDroite} tas.append((SF, Noeud)) # ajoute au tas le couple composé des sommes de frequences des plus 'petits' couples (index 1 du couple) # et qui a chacune des 2 lettres associe leur placement dans l'arbre (fils gauche/droit) (index2 du couple) import operator tas.sort(key=operator.itemgetter(0)) # trie la liste par ordre croissant de fréquence (car certains tuples de la liste sont de la forme # (int,dict) et d'autre de la forme (int,string) # <!> le module operator permet donc de ne comparer que les premiers éléments du couple entre eux afin de les trier # necessaire car python ne peut comparer un type dict et un type string arbre = tas[0][1] return arbre ####################################################################################### # Les deux prochaines fonctions sont dépendantes l'une de l'autre def ParcoursArbre(arbre): """ fonction qui associe à chaque caractere son code @ Entrée : un dictionnaire stucturé sous forme d'arbre binaire @ type: dict @ Sortie: dictionnaire du type clefs = code d'un caractere, valeur = ce caractere on a donc type(clef) = string, type(valeur) = string @ type: dict """ code = {} SousParcours(arbre,'',code) # parcours l'arbre en associant à chaque caractère son code return code def SousParcours(arbre, pref, code): """ fonction permettant de parcourir l'arbre <!> cette fonction ne fait que calculer de maniere recursive, elle ne renvoie rien, d'ou sa dépendance avec la fonction précédente @ Entrées: @ arbre : un dictionnaire stucturé sous forme d'arbre binaire @ type: dict @ pref : une chaîne de caractère initialement vide, dans la recursivité : enregistre le chemin pris pour arriver à un caractère @ type : string @ code : un dictionnaire initialement vide, dans la résurvité : enregistre les différents codes de chaque caractères @ type : dict """ for k in arbre: # pour k parcourant les CLEFS de l'arbre if isinstance(arbre[k], str) == True: # si la valeur de la clef k est une chaine de caractère ClefCaractere = pref + str(k) # le code de ce caractère est défini comme le chemin parcouru + l'endroit où l'on se situe code[ClefCaractere] = arbre[k] # le dictionnaire 'code' enregistre donc ce code else: # si la valeur de la clef k est un dictionnaire NoeudSuivant = arbre [k] # on se place dans le noeud suivant NouveauPrefixe = pref + str(k) # on enregistre le chemin prit dans l'arbre SousParcours(NoeudSuivant,NouveauPrefixe,code) # on refais la même chose dans le nouveau noeud # La fonction s'arrête lorsque tous les noeuds ont été explorés # Fin de la dépendance ############################################################################## def encodage(texte,code): """ fonction qui transforme le texte en texte binaire suivant la méthode de Huffman @ Entrées : @ texte : un texte @ type : string @ code : un dictionnaire du type clefs = code d'un caractère, valeur = ce caractere type(clefs) = string, type(valeur) = string @ type : dict @ Sortie: le texte binaire correspondant au texte alphabétique @ type: string """ codeInverse = DictionnaireInverse(code) # inverse les clefs et les valeurs du dictionnaire de code texteBinaire = '' # car on cherche a acceder aux clefs for k in texte: # pour une variable k parcourant chaque caractère du texte alphabétique texteBinaire = texteBinaire + codeInverse[k] # ajoute le code de k au texte binaire (concatène les strings) return texteBinaire def DictionnaireInverse(d): """ fonction qui inverse les clefs et les valeurs d'un dictionnaire @ Entrée : un dictionnaire @ Type : dict @ Sortie : le même dictionnaire avec les clefs et valeurs inversées @ Type : dict (ou string si la fonction est utilisé dans un autre cadre que le code d'Huffman) """ D_inverse = {} for k in d: # pour k parcourant le dictionnaire valeur = d[k] if valeur not in D_inverse: # si la valeur de la clef k n'est pas dans le dictionnaire inverse D_inverse[valeur] = k # crée le dictionnaire inverse en associant les clefs aux valeurs et les valeurs aux clefs else : # pas besoin de definir un else car toutes les valeurs sont différentes return 'deux valeurs du dictionnaire sont identiques' return D_inverse def decodage(code, texteBinaire): """ fonction qui retranspose le texte binaire en son texte alphabétique d'origine @ Entrées : @ texteBinaire : le texte binaire résultant de la fonction encodage (suite de 0 et 1) @ type : string @ code : dictionnaire du type clefs = code d'un caractére, valeur = ce caractère type(clefs) = string, type(valeur) = string @ type : dict @ Sortie: le texte correspondant au texte binaire @ type: string """ texte = '' clef = '' for k in texteBinaire: # pour une variable parcourant le texte binaire clef = clef+k # on construit une clef a partir du premier bit du texte binaire if clef in code: # on test si la clef appartient au dictionnaire representant le code texte = texte+code[clef] # dans l'affirmative on ajoute au texte la lettre correspondante a la clef, sinon on ajoute le 2ème bit a la clef et on retest clef = '' # reinitialisation de la clef return texte def CodeHuffman(texte): """ Fonction qui associe à un texte son texte binaire selon la méthode de Huffman @ Entree: un texte @ type: string @ Sortie: le texte en binaire @ type: string """ t = TableDeFrequence(texte) a = Arbre(t) c = ParcoursArbre(a) e = encodage(texte, c) return e def decodeHuffman(texte,texte_binaire): """ Fonction qui associe à un texte binaire son texte d'origine selon la méthode d'Huffman @ Entrée: un texte binaire @ type: string @ Sortie: le texte correspondant @ type: string """ t = TableDeFrequence(texte) a = Arbre(t) c = ParcoursArbre(a) d = decodage(c, texte_binaire) return d def TexteAleatoire(n) : import random Alphabet = "abcdefghijklmnopqrstuvwxyz " texte = "" for k in range(n): texte = texte + Alphabet[random.randint(0, len(Alphabet) - 1)] return texte import random NombreAleatoire = (random.randint(1, 1000)) TexteAleatoire = TexteAleatoire(NombreAleatoire) texte = TexteAleatoire def H(t): import math H = 0 for k in t : p1 = t[k] p2 = len(texte) p = p1/p2 H = H + p*math.log(1/(p),2) return H t = TableDeFrequence(texte) a = Arbre(t) c = ParcoursArbre(a) e = encodage(texte,c) d = decodage(c,e) H = H(t) if len(texte) == 0 : l= 0 else : l = len(e)/len(texte) NbitASCII = 8 * len(texte) if len(texte) == 0 : TC = 0 else : TC = (1 - (len(e) / NbitASCII)) * 100 print(texte) print(CodeHuffman(texte)) texteBinaire = (CodeHuffman(texte)) print(decodeHuffman(texte,texteBinaire)) print('') print('longueur du texte : ',len(texte)) print('') print('Taux de compression : ',TC,'%') print('Entropie = ',H) print('longueur moyenne de la séquence = ',l)
80c0c78be87ef72de59b615edbc412e2fa61499e
UWPCE-PythonCert-ClassRepos/Self_Paced-Online
/students/AlyssaHong/Lesson10/mailroom_fp.py
6,156
4.03125
4
""" Author: Alyssa Hong Date: 1/12/2019 Update: Lesson10 Assignments > Mailroom, Object Oriented Mailroom """ #!/usr/bin/env python3 import os class Donor: def __init__(self, first_name, last_name, donations = None): self.first = first_name self.last = last_name self.donations = donations @property def full_name(self): return "{} {}".format(self.first, self.last) def add_donations(self, new_donations): return self.donations.append(new_donations) def total_donations(self): return sum(self.donations) def multi_donations(self, factor, donations_list): return list(map(lambda x: x * factor, donations_list)) def min_max_donations(self, min_donations, max_donations): return list(filter(lambda x: min_donations < x < max_donations, self.donations)) def donations_less_than_value(self, value): return list(filter(lambda x: x < value, self.donations)) def donations_more_than_value(self, value): return list(filter(lambda x: x > value, self.donations)) def donor_input(): return input("Type the donor's name: ") def donations_input(): return float(input("Type your donations: ")) def donate_times_input(): return int(input("How many times will you challenge to donate?: ")) def min_donations_input(): return float(input("How much is the minimum donations?: ")) def max_donations_input(): return float(input("How much is the maximum donations?: ")) class DornorList: def __init__(self, donors = None): if donors is None: self.donors = [] else: self.donors = donors def new_donor(self, donor): self.donors.append(donor) def check_donor_list(self): return [donor.full_name for donor in self.donors] def send_thanks(self): donor_name = None while not donor_name: donor_name = donor_input() if donor_name.lower() == "list": print(self.check_donor_list()) donations = None while not donations: try: donations = donations_input() except ValueError: print("Please enter a number: ") if donor_name not in self.check_donor_list(): try: first, last = donor_name.split(" ") self.new_donor(Donor(first, last, [donations])) except ValueError: print("Please type the full name") else: for donor in self.donors: if donor.full_name == donor_name: donor.add_donations(donations) print('\n' + 'Dear {:s}, thank you for your ${:.2f} donations!'.format(donor_name, donations) + '\n') def donations_report(self): reports = [] for donor in self.donors: reports.append([donor.full_name, sum(donor.donations), len(donor.donations)]) return reports def create_report(self): print('{:<20} | {:^10} | {:^10} | {:^10}'.format(*list_col)) print('{}'.format("-"*63)) for donor_report in self.donations_report(): print('{:<20} | {:^10} | {:^10} | {:^10}'.format(donor_report[0], donor_report[1], donor_report[2], donor_report[1] / donor_report[2])) def send_letters(self): for donor in self.donors: file_name = donor.full_name + '.txt' with open(file_name, "w") as f: # f.write(letter_content(i, j)) f.write('Dear {},'.format(donor.full_name) + '\n'*2 + '\t'*1 + 'Thank you for your donations of ${:.2f}.'.format(sum(donor.donations))+ '\n' + '\t'*1 + 'It will be put to very good use.\n'+'\t'*5 +'Sincerely,\n' + '\t'*5 +'-The Team') def challenge(self): factor = donate_times_input() min_donations = min_donations_input() max_donations = max_donations_input() for donor in self.donors: new_dh.append(Donor(donor.full_name, donor.multi_donations(factor, donor.min_max_donations(min_donations, max_donations)))) print("{}:{}".format(donor.full_name, donor.multi_donations(factor, donor.min_max_donations(min_donations, max_donations)))) def projections(self): for donor in self.donors: d_double = donor.donations_less_than_value(100)*2 d_triple = donor.donations_more_than_value(50)*3 print("{}'s current donations is {}".format(donor.full_name, donor.donations)) print("(a) what {}'s total contribution would come to in dollars if they were to double contributions under $100: {}".format(donor.full_name, sum(d_double))) print("(b) what {}'s total contribution would come to in dollars if they were to triple contributions under $50: {}".format(donor.full_name, sum(d_triple))) list_col = ['Donor Name','Total Given','Num Gifts','Average Gift'] d1 = Donor('Fred', 'Lillywhite', [70,450]) d2 = Donor('Alex', 'Kim', [300,300,100]) d3 = Donor('Henry', 'Ford', [50]) d4 = Donor('Alyssa', 'Hong', [120,300,400]) d5 = Donor('Leo', 'Jeon', [107,53]) dh = DornorList([d1, d2, d3, d4, d5]) new_dh = [] def main(): while True: print('\n' 'Choose an action\n' '1 - Send a Thank you\n' '2 - Create a Report\n' '3 - Send letters to everyone\n' '4 - Challenge the donors\n' '5 - Donations Projections \n' '6 - Quit') try: choice_action = int(input(': ')) except ValueError: print("Your choice was wrong.\n""Choose an action again!") else: pass if choice_action == 1: dh.send_thanks() elif choice_action == 2: dh.create_report() elif choice_action == 3: dh.send_letters() elif choice_action == 4: dh.challenge() elif choice_action == 5: dh.projections() elif choice_action == 6: print('Quit current task!') break if __name__ == '__main__': main()
6147a3c4f0795100d24d465c6d0bff777ceb2138
pkc-3/Python_Q100
/Q1~Q50/Q5.py
203
3.640625
4
a = 10 b = 2 for i in range(1, 5, 2): a += i print(a+b) # i의 범위는 1~4까지 2씩 증가 i=1이고 그다음은 i=3 이고 끝 # 1일때 a= 11 b = 2 a+b = 13 # 3일때 a= 14 b = 2 a+b = 16
ae5e40fb4c0f91bc0e8bd684ee4b823e821b6ba6
AyaanShaikh1/Project-100-Class-Python
/biodata.py
322
3.828125
4
class Data : def __init__(self,name,age,hobby): self.name = name self.age = age self.hobby = hobby def greet(self) : print(f'Hello {self.name}') obj = Data(input('What is your name? : '),input('What is your age? : '),input('What is your hobby? : ')) obj.greet()
fd4865220d7f895e2ad88baabff2f38b8b2e5b3a
Prashantkankaria/learnpython_edx_Gtech
/GTx _CS1301xI/test_code_problem_7.py
804
3.5
4
current_hour = 5 current_minute = 32 current_section = "AM" due_hour = 6 due_minute = 0 due_section = "PM" #You may modify the lines of code above, but don't move them! #When you Submit your code, we'll change these lines to #assign different values to the variables. #Given the current time and deadline time represented by the #variables above, determine if an assignment is still eligible #for submission. An assignment is eligible if the time #represented by current_hour, current_minute, and #current_section is before the time represented by due_hour, #due_minute, and due_section. #Add your code here! #s1 = current_section <= due_section #m1 = (current_hour == 12 and due_hour == 12 and current_minute <= due_minute) or \ # (current_minute <= due_minute) #h1 = current_hour <= due_hour
c61ba444d1b99ed26e9b52936eaf0302b72691f3
djjohns/pysqlite3
/txt2csv.py
918
4.03125
4
#!/usr/bin/python #txt2csv.py written by David J. Johns II to aid in converting a tab #dilimited text file into a csv file for easier data manipulation #https://github.com/djjohns #import the csv library import csv #Prompts user for file name #if user presses enter, program will open specified txt file FileName = raw_input('Enter file name:') if len(FileName) < 1 : FileName = 'SampleData.txt' #Program will try to open users requested file into file handler try: fh_in = FileName #Error message to inform of bad input except: print 'File could not be found: ',FileName #File handler for the output file fh_out = r'LogFile.csv' #txt_in reads the input file, csv_out writes to specified file #'b' imporves portablity to windows reading in binary txt_in = csv.reader(open(fh_in, 'rb'), delimiter='\t') csv_out = csv.writer(open(fh_out,'wb'),delimiter=',') #Writes out file given in file csv_out.writerows(txt_in)
82c4d935534c2355bb5bd1391097a0684656e90d
Barabasha/pythone_barabah_hw
/task14.py
429
3.984375
4
def print_task(n) : print ('====================Task'+str(n)+'====================') return #===========================task14=========================== def is_even (number): if number % 2 == 0: return True else : return False print_task(14) number = int (input ("Input number: ")) if is_even(number) == True : print ("Number is even") else: print ("Number is not even")
935dc5f40e4e1025286125e13a8afa71f034d593
daniel-reich/ubiquitous-fiesta
/iuenzEsAejQ4ZPqzJ_13.py
127
3.703125
4
def mystery_func(num): s, mult = "", 1 while mult < num: mult *= 2 s += "2" return int(s[1:]+str(num-mult//2))
46dc7fe39f30aebb8d23c33f922e92e2edd5b129
cpr2mc/Programming101
/resources/example_lessons/unit_3/unit_3_lesson.py
4,328
4.4375
4
''' Programming 101 Unit 3 ''' # Datatype: boolean (bool) # True / False a = True b = False # print(a, type(a)) # True <class 'bool'> # print(b, type(b)) # False <class 'bool'> # in Python, booleans are capitalized # b = true # NameError: name 'true' is not defined # --------------------------------------------------------------------------------------------------- # # Comparison Operators - compare two pieces of data and result in a boolean x = 5 y = 5 # = is the assignment operator # print(x == y) # == check equality - True # print(x != y) # != check inequality - False # print(x < y) # < 'strictly' less than - False # print(x <= y) # <= less than or equal to - True # print(x > y) # > 'strictly' greater than - False # print(x >= y) # >= greater than or equal to - True # check the result of some math # print(x / 2 == 2.5) # True # check for a particular value in a variable # print(x == 5) # True # print(x == 99) # False # ----------------------------------------------------------------------- # # other datatypes can be compared as well # can't compare unlike datatypes word_1 = 'catt' word_2 = 'catt' # print(word_1 == word_2) # True # print(word_1 == 'cat') # False # ----------------------------------------------------------------------- # # Logical Operators - combine the results of two comparisons into a single boolean # and, or, not x = 5 y = 3 # and - True only if BOTH comparisons result in True # print(x == 5 and y == 3) # True - both comparisons result in True # print(x == 5 and x == y) # False - right comparison (x == y) results in False # or - True if at least ONE comparison is True # print(x == 5 or x == y) # True - left comparison (x == 5) results in True # print(x == 1 or x == y) # False - both comparisons result in False # not - flip a boolean # print(x < 0) # False # print(not x < 0) # True # ------------------------------------------------------------------------------------ # # 'not' is often used with the keyword 'in' to determine if an item is 'in' a sequence (list, string, etc...) word = 'book' # print('k' in word) # True # print('z' not in word) # True # ------------------------------------------------------------------------------------ # ''' Conditional Statements - if / elif / else Run different code blocks based on the outcome of comparisons. Code Block ---------- A section of code that executed together. In Python, code blocks are defined using horizontal indentation - must start with if - every single if statement will be checked - elif will only be checked if the preceding if and other elifs were False - if/elif will only be checked until a True condition is found - else will be run if all other conditions were False ''' # ------------------------------------------------------------------------------------- # light_switch = 'ON' if light_switch == 'ON': # colon signifies the beginning of a code block # first line in a code block determines the indentation for the block message = 'I can see!' elif light_switch == 'OFF': message = "It's dark in here!" elif light_switch == 'DIM': message = 'The light is dim...' else: message = 'The light is broken...' # print(message) # -------------------------------------------------------------------------------------- # x = 10 y = 10 if x < y: output = f"{x} is less than {y}" elif x == 14: output = "x is 14" elif x > y: output = f"{x} is greater than {y}" else: output = f"x and y are both {x}" # print(output) # ---------------------------------------------------------------------------------- # ### TALK ABOUT FLOWCHARTS, IF TIME ALLOWS # pretend this is line 1 of the file (imports are always at the top) import random # set the secret number 1-10 # secret = 5 # generate a secret number 1-10 secret = random.randint(1, 10) # ask the user to guess a number guess = input('Guess a number between 1 and 10: ') # convert the guess to an integer guess = int(guess) # compare the guess to the secret if guess == secret: print(f"Congratulations! You guessed the secret number: {secret}!") elif guess < secret: print(f"Oops! Your guess of {guess} was too low! The secret number was {secret}...") elif guess > secret: print(f"Oops! Your guess of {guess} was too high! The secret number was {secret}...")
89592b47de91b974e4deceb1eace4264f836ca84
WojciechBogobowicz/Unit_Test-Example
/bank.py
4,068
3.75
4
from bankaccount import BankAccount from random import randint, seed class Bank: def __init__(self, name): self.name = name self.accounts = {} self.account_num = 0 self.used_ibans = [] with open("iban.txt") as f: for line in f: line = line.strip() bank_id, bank_name = line.split(":") if bank_name == self.name: return None raise ValueError(f"Cannot find bank named {self.name}") def make_account(self, balance=0): self.account_num = self.generate_IBAN() while self.account_num in self.accounts.keys() or self.account_num in self.used_ibans: self.account_num = self.generate_IBAN() number = self.account_num account = BankAccount(number, balance) self.accounts[number] = account return account def get_account(self, number): if number not in self.accounts: raise ValueError('No account with number {}'.format(number)) return self.accounts[number] def del_account(self, number): if number not in self.accounts.keys(): raise ValueError('No account with number {}'.format(number)) del self.accounts[number] self.used_ibans.append(number) def money_in_the_bank(self): return sum([i.balance for i in self.accounts.values()]) def withdraw_all(self): saldo = self.money_in_the_bank() for account in self.accounts.values(): account.withdraw(account.balance) return saldo def merge_all(self, account): account.deposit(self.withdraw_all()) def move_to(self, other): for account in self.accounts.values(): other.make_account(account.balance) self.accounts = {} def get_bank_number(self): with open("iban.txt") as f: for line in f: line = line.strip() bank_id, bank_name = line.split(":") if bank_name == self.name: return bank_id raise ValueError(f"Cannot find bank named {self.name}") def get_user_number(self): user_number = "" seed() for i in range(16): user_number += str(randint(0, 9)) return user_number def add_control_sum(self, iban): number = int(iban + "252100") number += 98 - number % 97 number = str(number) number = "PL" + number[-2:] + number[:-6] return number def generate_IBAN(self): #https://direct.money.pl/numerkonta/?account_number=54215000003292293856381773 iban = self.get_bank_number() + self.get_user_number() iban = self.add_control_sum(iban) return iban if __name__ == "__main__": mbank = Bank("mBank Hipoteczny Spółka Akcyjna") bnp = Bank("BNP Paribas Bank Polska Spółka Akcyjna") basia = mbank.make_account(100) bartek = mbank.make_account(0) print(mbank.accounts.values()) print(bnp.accounts.values()) mbank.move_to(bnp) print(mbank.accounts.values()) print(bnp.accounts.values()) """ bank1 = Bank("PL1") bank1.make_account(1000) bank1.make_account(2000) bank2 = Bank("DE2") account1 = bank1.get_account("PL1-1") account2 = bank2.make_account(3000) account2.merge_to(account1) print(account1.balance) """ """ bank = Bank("cokolwiek") bank2 = Bank("szwajcaria") acc1 = bank.make_account(1000) acc2 = bank.make_account(2000) bank.del_account("cokolwiek-2") acc3 = bank.make_account(3000) # print(bank.money_in_the_bank(), "tyle mamy kasy") machlojki = bank2.make_account(0) # bank.merge_all(machlojki) # print(machlojki.balance, "tyle ukradlismy") #print(bank.money_in_the_bank(), "tyle zostalo ludziom") print(bank.accounts, "<- bank") print(bank2.accounts, "<- bank2") bank.move_to(bank2) print("po przejsciu") print(bank.accounts, "<- bank") print(bank2.accounts, "<- bank2") """
0507c0ae1a5e5cec82c8c973c0a5fbc6d1941c58
deepshringi/queensproblem
/Eightqueen.py
4,308
4.0625
4
#import random to generate random population import random #import sleep to slow down computation from time import sleep class EightQueens: #solution - one of the pre-defined soution to 8-Queen's problem solution = [3, 6, 2, 7, 1, 4, 0, 5] #computed_solution - this list will have the final computed solution to 8-Queen's problem computed_solution = [None] * len(solution) #GlobalPopulation - List of all elements with fitness/score not equal to 0/ GlobalPopulation = [] #Function to generate initial population(of 5 members) having length as that of the solution def generatePopulation(self): population = [] for i in range(0,5): element = [] while len(element) < len(self.solution): number = random.randint(0,len(self.solution)) if number not in element: element.append(number) population.append(element) return population #Function to score the population and store the list along-with score in a dictionary def scorePopulation(self,population,solution): score_dict = {} for i in range(0,len(population)): score = 0 current_pop = population[i] for j in range(0,len(population[i])): if solution[j] == population[i][j]: score += 1 if score > 0: self.GlobalPopulation.append(population[i]) score_dict[tuple(current_pop)] = score return score_dict '''Below is the Function for Crossover and Mutation Crossover : An element with highest score is selected as Pivot and is combined with other elements in population Mutation : One unmatched element in pivot is mutated or altered to have a value from the actual solution ''' def crossoverAndMutation(self,score_dict): sorted_dict = sorted(score_dict.items(),key = lambda kv : (kv[1],kv[0]),reverse=True) newPopulation = [] pivot = list(sorted_dict[0][0]) print("Pivot: {}\n".format(pivot)) flag = [False] * len(pivot) for i in range(0,len(pivot)): if pivot[i] != self.solution[i]: pivot[i] = self.solution[i] flag[i] == True break for i in range(0,len(pivot)): if pivot[i] == self.solution[i]: flag[i] = True for j in range(1,len(score_dict)): element = [] for i in range(0,len(pivot)): if flag[i] == True: element.append(pivot[i]) continue else: element.append(list(sorted_dict[j][0])[i]) self.GlobalPopulation.append(element) return self.GlobalPopulation #Function to check if new popuation contains the solution, if yes it returns true. def check(self,newPopulation1,solution): for i in range(0,len(newPopulation1)): if newPopulation1[i]==solution: self.computed_solution = newPopulation1[i] return True #Creating object of the EightQueens class. eq = EightQueens() #Calling generatePopulation function to generate initail population population = eq.generatePopulation() print("Population : {}\n".format(population)) #Calling the scorePopulation to calculate the score of initial population score_dict = eq.scorePopulation(population,eq.solution) #Calling Mutation and crossover function newPop= eq.crossoverAndMutation(score_dict) #checking if the population has the solution answer = eq.check(newPop,eq.solution) #while population does not have the solution, run the above steps on repeat while not answer: score_dictionary = eq.scorePopulation(newPop,eq.solution) newPopulation = eq.crossoverAndMutation(score_dictionary) print("Population : {}\n".format(newPopulation)) answer = eq.check(newPopulation,eq.solution) sleep(7) #When population has the solution, the problem is solved eventually if answer: print("Solution arrived! This is the solution: {}\n".format(eq.computed_solution))
c89b47bbd248f5eaea15b37ca6f615225387ac4d
UConn-UPE/tutorials
/CSE2050/Unit_Testing/test_example_functions.py
1,321
3.765625
4
import unittest from example_functions import * class TestExampleFunctions(unittest.TestCase): def setUp(self): print('Start of a test method') def tearDown(self): print('End of a test method') @classmethod def setUpClass(cls): print('Start of a class') @classmethod def tearDownClass(cls): print('End of a class') def test_absolute_value(self): print('test_absolute_value_method') self.assertEqual(absolute_value(2), 2) self.assertEqual(absolute_value(0), 0) self.assertEqual(absolute_value(3.14), 3.14) self.assertEqual(absolute_value(-1), 1) self.assertEqual(absolute_value(-2.5), 2.5) with self.assertRaises(TypeError) as _: absolute_value('test') absolute_value([1, 2, 3]) absolute_value({1, 2, 3}) def test_square(self): print('test_square_method') self.assertEqual(square(3), 9) self.assertEqual(square(0), 0) self.assertAlmostEqual(square(.2), .04) self.assertEqual(square(-1), 1) self.assertAlmostEqual(square(-2.5), 6.25) with self.assertRaises(TypeError): square('test') square([1, 2, 3]) square({1, 2, 3}) if __name__ == '__main__': unittest.main()
b95ffddc4accc6176ada2bd6ed98d30aa4e23a14
YuweiHuang/DSAA-Notes
/linklist/lc_19_delete_last_nnode_linklist.py
919
3.59375
4
# https://blog.csdn.net/qq_17550379/article/details/80717212 # Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def removeNthFromEnd(self, head, n): """ :type head: ListNode :type n: int :rtype: ListNode """ # 双指针法 # 0.注意head不是第一个元素,是一个空节点,结构:head->1->2->3->None # 1.让快指针先走N步骤 # 2.快慢指针同时走 # 3.快指针到达尾部的时候,慢指针指向的下一个就是要删除的节点 h = ListNode(-1) h.next = head fp = h sp = h for _ in range(n): fp = fp.next while fp and fp.next: fp = fp.next sp = sp.next sp.next = sp.next.next return h.next
4d2741408dbb38883178bd71f22ab50e88f757cd
kirthikartm/guvi
/natural.py
63
3.625
4
a=int(input("")) s=0 for i in range(1,a+1): s=s+i print(s)
2fe6fe78c213c50801bd38d957900a01dc9bd2e2
cmychina/Leetcode
/leetcode_回溯_子集.py
510
3.953125
4
""" 给定一组不含重复元素的整数数组 nums,返回该数组所有可能的子集(幂集)。 说明:解集不能包含重复的子集。 """ class Solution: def subsets(self, nums): res=[] n=len(nums) def backtrack(i,tmp): res.append(tmp) for j in range(i,n): backtrack(j+1,tmp+[nums[j]]) backtrack(0,[]) return res if __name__ == "__main__": s = Solution() nums=[1,2,3] print(s.subsets(nums))
b2fc3b7602fdc97c345bb294c4b185f36acd2293
joao-felipe-santoro/data_sci_bikeshare
/chicago_bikeshare.py
10,551
4.03125
4
# coding: utf-8 # Here goes the imports import csv import matplotlib.pyplot as plt # Let's read the data as a list print("Reading the document...") with open("chicago.csv", "r") as file_read: reader = csv.reader(file_read) data_list = list(reader) print("Ok!") # Let's check how many rows do we have print("Number of rows:") print(len(data_list)) # Printing the first row of data_list to check if it worked. print("Row 0: ") print(data_list[0]) # It's the data header, so we can identify the columns. # Printing the second row of data_list, it should contain some data print("Row 1: ") print(data_list[1]) input("Press Enter to continue...") # TASK 1 print("\n\nTASK 1: Printing the first 20 samples") # Let's change the data_list to remove the header from it. data_list = data_list[1:] # We can access the features through index # E.g. sample[6] to print gender or sample[-2] print(data_list[:20]) input("Press Enter to continue...") # TASK 2 print("\nTASK 2: Printing the genders of the first 20 samples") for sample in data_list[:20]: print(sample[6]) input("Press Enter to continue...") # TASK 3 def column_to_list(data: list, index: int) -> list: """ Function to extract a data set column as list Args: data: Data set in question. index: Column of the the given data set to extract. Returns: List of values """ list_to_return = [] for entry in data: list_to_return.append(entry[index]) return list_to_return # Let's check with the genders if it's working (only the first 20) print("\nTASK 3: Printing the list of genders of the first 20 samples") print(column_to_list(data_list, -2)[:20]) # ------------ DO NOT CHANGE ANY CODE HERE ------------ assert type(column_to_list(data_list, -2)) is list, "TASK 3: Wrong type returned. It should return a list." assert len(column_to_list(data_list, -2)) == 1551505, "TASK 3: Wrong lenght returned." assert column_to_list(data_list, -2)[0] == "" and column_to_list(data_list, -2)[1] == "Male", \ "TASK 3: The list doesn't match." # ----------------------------------------------------- input("Press Enter to continue...") # Now we know how to access the features, let's count how many Males and Females the dataset have # TASK 4 male = 0 female = 0 for sample in data_list: if sample[6] == 'Male': male = male + 1 elif sample[6] == 'Female': female = female + 1 # Checking the result print("\nTASK 4: Printing how many males and females we found") print("Male: ", male, "\nFemale: ", female) # ------------ DO NOT CHANGE ANY CODE HERE ------------ assert male == 935854 and female == 298784, "TASK 4: Count doesn't match." # ----------------------------------------------------- input("Press Enter to continue...") # Why don't we create a function to do that? # TASK 5 def count_gender(list_to_handle: list) -> [str, str]: """ Function to count data entries based on gender Args: list_to_handle: Data set in question. Returns: Tuple with genders count """ male_count = 0 female_count = 0 for entry in list_to_handle: if entry[6] == 'Male': male_count = male_count + 1 elif entry[6] == 'Female': female_count = female_count + 1 return [male_count, female_count] print("\nTASK 5: Printing result of count_gender") print(count_gender(data_list)) # ------------ DO NOT CHANGE ANY CODE HERE ------------ assert type(count_gender(data_list)) is list, "TASK 5: Wrong type returned. It should return a list." assert len(count_gender(data_list)) == 2, "TASK 5: Wrong length returned." assert count_gender(data_list)[0] == 935854 and count_gender(data_list)[1] == 298784, "TASK 5: Returning wrong result!" # ----------------------------------------------------- input("Press Enter to continue...") # Now we can count the users, which gender use it the most? # TASK 6 def most_popular_gender(list_to_handle: list) -> str: """ Function to return most popular gender. Args: list_to_handle: Data set in question. Returns: Most popular gender. """ genders = count_gender(list_to_handle) if genders[0] > genders[1]: return 'Male' elif genders[0] < genders[1]: return 'Female' else: return 'Equal' print("\nTASK 6: Which one is the most popular gender?") print("Most popular gender is: ", most_popular_gender(data_list)) # ------------ DO NOT CHANGE ANY CODE HERE ------------ assert type(most_popular_gender(data_list)) is str, "TASK 6: Wrong type returned. It should return a string." assert most_popular_gender(data_list) == "Male", "TASK 6: Returning wrong result!" # ----------------------------------------------------- # If it's everything running as expected, check this graph! types = ["Male", "Female"] quantity = count_gender(data_list) y_pos = list(range(len(types))) plt.bar(y_pos, quantity) plt.ylabel('Quantity') plt.xlabel('Gender') plt.xticks(y_pos, types) plt.title('Quantity by Gender') plt.show(block=True) input("Press Enter to continue...") # TASK 7 def count_types(list_to_handle: list) -> [int, int]: """ Function to count data entries based on user types Args: list_to_handle: Data set in question. Returns: List of user types count """ subscriber = 0 customer = 0 for entry in list_to_handle: if entry[5] == 'Subscriber': subscriber = subscriber + 1 elif entry[5] == 'Customer': customer = customer + 1 return [subscriber, customer] print("\nTASK 7: Check the chart!") types = ["Subscriber", "Customer"] quantity = count_types(data_list) y_pos = list(range(len(types))) plt.bar(y_pos, quantity) plt.ylabel('Quantity') plt.xlabel('User Type') plt.xticks(y_pos, types) plt.title('Quantity by User Type') plt.show(block=True) input("Press Enter to continue...") # TASK 8 male, female = count_gender(data_list) print("\nTASK 8: Why the following condition is False?") print("male + female == len(data_list):", male + female == len(data_list)) answer = "There are users that did not fill in gender information" print("Answer:", answer) # ------------ DO NOT CHANGE ANY CODE HERE ------------ assert answer != "Type your answer here.", "TASK 8: Write your own answer!" # ----------------------------------------------------- input("Press Enter to continue...") # Let's work with the trip_duration now. We cant get some values from it. # TASK 9 def get_trip_values(list_to_handle: list) -> list: """ Function to convert data entries str to int Args: list_to_handle: Data set in question. Returns: List of trip durations """ return list(map(int, list_to_handle)) def mean_trip_value(int_list: list) -> float: """ Function to calculate trip durations mean value. Args: int_list: Trip durations list. Returns: Trip duration mean value """ total_sum = 0. for entry in int_list: total_sum = total_sum + entry return total_sum / len(int_list) def min_trip_value(int_list: list) -> int: """ Function to calculate trip durations minimum value. Args: int_list: Trip durations list. Returns: Trip duration minimum value """ min_value = int_list[0] for entry in int_list: if entry < min_value: min_value = entry return min_value def max_trip_value(int_list: list) -> int: """ Function to calculate trip durations maximum value. Args: int_list: Trip durations list. Returns: Trip duration maximum value """ max_value = int_list[0] for entry in int_list: if entry > max_value: max_value = entry return max_value def median_trip_value(int_list): """ Function to calculate trip durations median value. Args: int_list: Trip durations list. Returns: Trip duration median value """ sorted_list = int_list sorted_list.sort() list_len = len(sorted_list) if list_len % 2 == 0: return (sorted_list[list_len / 2] + sorted_list[list_len - 1]) / 2 else: return sorted_list[round(list_len / 2)] trip_duration_values = get_trip_values(column_to_list(data_list, 2)) min_trip = min_trip_value(trip_duration_values) max_trip = max_trip_value(trip_duration_values) mean_trip = mean_trip_value(trip_duration_values) median_trip = median_trip_value(trip_duration_values) print("\nTASK 9: Printing the min, max, mean and median") print("Min: ", min_trip, "Max: ", max_trip, "Mean: ", mean_trip, "Median: ", median_trip) # ------------ DO NOT CHANGE ANY CODE HERE ------------ assert round(min_trip) == 60, "TASK 9: min_trip with wrong result!" assert round(max_trip) == 86338, "TASK 9: max_trip with wrong result!" assert round(mean_trip) == 940, "TASK 9: mean_trip with wrong result!" assert round(median_trip) == 670, "TASK 9: median_trip with wrong result!" # ----------------------------------------------------- input("Press Enter to continue...") # TASK 10 start_stations = set(column_to_list(data_list, 3)) print("\nTASK 10: Printing start stations:") print(len(start_stations)) print(start_stations) # ------------ DO NOT CHANGE ANY CODE HERE ------------ assert len(start_stations) == 582, "TASK 10: Wrong len of start stations." # ----------------------------------------------------- input("Press Enter to continue...") # TASK 11 input("Press Enter to continue...") # TASK 12 - Challenge! (Optional) print("Will you face it?") answer = "yes" def count_items(list_to_handle: list) -> [list, list]: """ Function to extract a column set value and count it's items. Args: list_to_handle: List to be worked on. Returns: A tuple containing the column set and it's respective entries count """ items_dict = {} keys = set(list_to_handle) for x in keys: items_dict[x] = 0 for x in column_list: items_dict[x] = items_dict[x] + 1 return list(items_dict.keys()), list(items_dict.values()) if answer == "yes": # ------------ DO NOT CHANGE ANY CODE HERE ------------ column_list = column_to_list(data_list, -2) types, counts = count_items(column_list) print("\nTASK 11: Printing results for count_items()") print("Types:", types, "Counts:", counts) assert len(types) == 3, "TASK 11: There are 3 types of gender!" assert sum(counts) == 1551505, "TASK 11: Returning wrong result!" # -----------------------------------------------------
b57eaffe6dfa4be2bf99770a3ba2b24baf056b00
YanceyZhangDL/Python_LearnDemo
/prac_5/prac_5_1.py
956
3.84375
4
#!/usr/bin/env python #coding:utf-8 #################################################### # Copyrignt (py) YanceyZ. All rights reserved. # # Author: YanceyZ # Mail: yanceyzhang2013@gmail.com # Description: #################################################### while True: try: summ = 0 iterr = 0 num = raw_input("Enter a number:") while num != "done": num = float(num) summ += num iterr += 1 num = raw_input("Enter a number:") print "总和:",summ,"个数:",iterr,"平均值:",summ/iterr break except: print "Error:请输入数字" ''' summ = 0 iterr = 0 num = raw_input("Enter a number:") while num != "done": #这里不能用is not,is是看两个标识符是不是引自同一对象 num = float(num) summ += num iterr += 1 num = raw_input("Enter a number:") print "总和:",summ,"个数:",iterr,"平均值:",summ/iterr '''
2cf3fe5973e00ff63d730eb0905981600ce511d6
johnreyev/supercode-get-sheets-list
/main.py
1,154
3.515625
4
""" Import required libraries """ import json import requests URL = "https://sheets.googleapis.com/v4/spreadsheets/{spreadsheet_id}?&fields=sheets.properties&key={google_key}" def main(spreadsheet_id, google_key): """ Get spreadsheet list of sheets information. """ response = {} response["type"] = "error" headers = {"Content-Type": "application/json"} try: result = requests.get( URL.format( spreadsheet_id=spreadsheet_id, google_key=google_key ), headers=headers) result_json = json.loads(result.text) if result.status_code == 200: response["type"] = "success" response["data"] = result_json elif result.status_code in [400, 404]: response["error"] = {} response["error"]["message"] = result_json["detail"] except requests.exceptions.HTTPError as err: response["error"] = {} response["error"]["message"] = "Failed to connect." except Exception as err: response["error"] = {} response["error"]["message"] = str(err) return response
9a068c074d546c64fc653505a12d855b84cacc45
J4TJR/RPC
/1.py
2,423
4.0625
4
import random import time #test for commit # Initialize Variables def isValidEntry(): invalid_entry = True while invalid_entry: user_choice = input('Rock? Paper? Scissors? ') if user_choice == 'Rock' or user_choice == 'Paper' or user_choice == 'Scissors': return user_choice if user_choice != 'Rock' or user_choice != 'Paper' or user_choice != 'Scissors': print('Invalid Input Detected.\n') invalid_entry = True # 1=Rock/ 2=Paper/ 3=Scissors def computer_throw(comp_Choice): if comp_Choice == 1: print("The computer chooses Rock") if comp_Choice == 2: print('The computer chooses Paper') if comp_Choice == 3: print('The computer chooses Scissors') # 1=Rock/ 2=Paper/ 3=Scissors def versus(cc, uc): if cc == 1 and uc == "Rock": # Rock vs Rock print('Rock vs Rock \nTIE GAME') if cc == 2 and uc == "Rock": # Paper vs Rock print('Paper vs Rock \nPaper Wins...\nYOU LOSE!') if cc == 3 and uc == "Rock": # Scissors vs Rock print('Scissors vs Rock \nRock Wins...\nCONGRATS YOU BEAT THE COMPUTER!') if cc == 1 and uc == "Paper": # Rock vs Paper print('Rock vs Paper \nPaper Wins\nCONGRATS YOU BEAT THE COMPUTER!') if cc == 2 and uc == "Paper": # Paper vs Paper print('Paper vs Paper \nTIE GAME!') if cc == 3 and uc == "Paper": # Scissors vs Paper print('Scissors vs Paper \nScissors Win\nYOU LOSE!') if cc == 1 and uc == "Scissors": # Rock vs Scissors print('Rock vs Scissors \nRock Wins\nYOU LOSE!') if cc == 2 and uc == "Scissors": # Paper vs Scissors print('Paper vs Scissors \nScissors Win\nCONGRATS YOU BEAT THE COMPUTER!') if cc == 3 and uc == "Scissors": # Scissors vs Scissors print('Scissors vs Scissors \nTIE GAME!') #Both Choose Rock, Paper or Scissors. Computer choice uses a random integer declaration compChoice = random.randint(1, 3) userChoice = isValidEntry() computer_throw(compChoice) time.sleep(2) versus(compChoice, userChoice) reply = input('Play Again? ') #Replay Loop while reply == 'yes' or reply == 'y': compChoice = random.randint(1, 3) userChoice = isValidEntry() computer_throw(compChoice) time.sleep(2) #DRAMATIC EFFECT versus(compChoice, userChoice) reply = input('Play Again? \n')
75142b32ac7373d7256b0b5160aed46a6f257b18
rajui67/learnpython
/python_code_exaples/others/typename.py
1,030
3.84375
4
''' Function to return the typename of an object/instance ''' # from typing import Any # def typename(derive_the_typename_of_this_instance: Any,/) -> str: import typing def typename(derive_the_typename_of_this_instance: typing.Any,/) -> str: ''' Given a varaible of any type, returns the type name of the variable. e.g.: Note the function parmater is position only typename(derive_the_typename_of_this_instance = "") TypeError: typename() got some positional-only arguments passed as keyword arguments: 'derive_the_typename_of_this_instance' ''' typeof =str(type(derive_the_typename_of_this_instance)) split_it_up = typeof.split("'") intermediate_name_derived = split_it_up[1] final_name_derived = intermediate_name_derived.split(".")[-1] return final_name_derived # The same functionally implemented in an extremely cryptic form can be: # def typename(derive_the_typename_of_this_instance): return str(type(derive_the_typename_of_this_instance)).split("'")[1].split(".")[-1]
b934d6599f01a28f1b3ddc3f149d3b6ab517ff4d
rehan-prass/tugas-pkl-pyhton
/kasir2.py
593
3.75
4
print("Source Code Kasir Dengan Python") x=str(input("Nama Barang : ")) y=int(input("Harga : ")) z=int(input("Jumlah Jual : ")) v=0 w=0 if (z in range (0,5)): v = 0 print("Tidak ada diskon") elif (z in range (5,11)): v = 5/100 print("Discount 5%") elif (z in range ( 11,21)): v = 10/100 print("Discount 10%") elif (z in range ( 21,31)): v = 15/100 print("Discount 15%") else: v = 20/100 print("Discount 20%") w = (y*z)-(y*z*v) print ("Nama Barang : ",x) print ("Harga : ",y) print ("Jumlah Jual : ",z) print ("Total Harga : ",w)
4baa9edde7c2de03c0bf63b04de1123779d566d4
blhwong/algos_py
/leet/reorder_list/main.py
678
3.640625
4
from data_structures.list_node import ListNode class Solution: def reorderList(self, head: ListNode) -> None: """ Do not return anything, modify head in-place instead. """ arr = [] if not head: return None curr = head while curr: arr.append(curr) curr = curr.next start, end = 0, len(arr) - 1 while start < end: arr[start].next, arr[end].next = arr[end], arr[start + 1] start += 1 end -= 1 if len(arr) % 2 == 0: arr[start].next = None else: arr[end].next = None return head
2f06f8a4cef3b86f3bdfb86cf8b29bbc6aa2d9fb
amantyagi95/python-beginner-projects
/Hangman/hangman.py
2,357
3.984375
4
from random import choice from string import ascii_lowercase FILENAME = 'Hangman\\sowpods.txt' def get_rand_word(filename): with open(filename, 'r') as f: return choice([x.strip() for x in f]).lower() def print_game(wrong, word, letters): # Print wrong guesses print('\nWrong guess:', end=' ') for i in range(len(wrong)): if i != 0: print(',', end=' ') print(wrong[i], end='') print() # Print letters for i in letters: if i is None: print(' ', end=' ') else: print(i, end=' ') print() # Print dashes for i in word: if i != ' ': print('-', end=' ') else: print(' ', end=' ') print() def get_letter(attempt, guess): user_input = input(f'> Guess a letter ({attempt} attempts left): ').lower() # Make sure if the user input is a letter and not in the guess list if len(user_input) != 1 or user_input not in ascii_lowercase: print(f"> Please input a letter!") elif user_input in guess: print(f"> You have guessed '{user_input}' before") else: return user_input def play(word): attempt = 6 guess, guess_wrong = [], [] letters = [] for i in word: # Assign None to letters if i is not a space otherwise assign space # instead i = None if i != ' ' else i letters.append(i) while attempt > 0: print_game(guess_wrong, word, letters) if None not in letters: print('> You win!') break user_letter = get_letter(attempt, guess) # Make sure get_letter is returning the user input if user_letter is not None: # Search trough the word and assign user_letter to letters[i] if # the user_letter match a character in word[i] for i in range(len(word)): if user_letter == word[i]: letters[i] = user_letter guess.append(user_letter) if user_letter not in letters: guess_wrong.append(user_letter) attempt -= 1 else: print_game(guess_wrong, word, letters) print('> You lose...') print(f'> Answer: {word.capitalize()}') if __name__ == "__main__": word = get_rand_word(FILENAME) play(word)
37a5a4ad1b5499d4286a9b1549d8247380838235
gurguration/python_course
/all.py
11,999
3.703125
4
# from abc import ABC, abstractmethod # class InvalidOperationError(Exception): # pass # class Stream(ABC): # def __init__(self): # self.opened = False # @abstractmethod # def read(self): # pass # def open(self): # if self.opened: # raise InvalidOperationError('File Stream already opened') # self.opened = True # def close(self): # if not self.opened: # raise InvalidOperationError('File Stream already closed') # self.opened = False # class FileStream(Stream): # def read(self): # print("reading data from a file") # class NetworkStream(Stream): # def read(self): # print("reading data from network") # class MemoryStream(Stream): # def read(self): # print("Reading data from a memory stream.") # mem = MemoryStream() # net = NetworkStream() # fil = FileStream() # net.read() # fil.read() # mem.read() # class UIControl(ABC): # def draw(self): # print("TextBox") # class DropDownList(UIControl): # def draw(self): # print("DropDownList") # def draw(controls): # for control in controls: # control.draw() # textbox = UIControl() # ddl = DropDownList() # draw([ddl, textbox]) # print(isinstance(ddl, UIControl)) # class Text(str): # def duplicate(self): # return self + self # text = Text("Python") # print(text.duplicate()) # class TrackableList(list): # def append(self, object): # print("append called ") # super().append(object) # xlist = TrackableList() # xlist.append('x') # print(xlist) # from collections import namedtuple # Point = namedtuple("Point", ["x", "y"]) # p1 = Point(1, 2) # p2 = Point(1, 2) # print(p1 == p2) # print(p1.x, p2.y) # from time import ctime # import sys # from pathlib import Path # path = Path(r"C:\Users\g\Desktop\python_course") # print(path.is_file()) # print(path.exists()) # print(path.name) # print(path.stem) # print(path.suffix) # print(path.parent) # print(path.absolute()) # for p in path.iterdir(): # print(p) # print(ctime(path.stat().st_ctime)) # from zipfile import ZipFile # zip = ZipFile('./Files.zip', 'w') # for p in Path('c:/Users/g/Desktop/python_course').rglob("*.*"): # zip.write(p) # zip.close() # with ZipFile(r'c:/Users/g/Desktop/python_course/Files.zip') as zip: # print(zip.namelist()) # info = zip.getinfo('Files') # print(info.file_size) # print(info.compress_size) # import csv # with open("datacsv.csv", "w") as file: # writer = csv.writer(file) # writer.writerow(["transaction_id", "product_id", "price"]) # writer.writerow([1001, 2, 15]) # with open('datacsv.csv', 'r') as file: # reader = csv.reader(file) # print(list(reader)) # import json # from pathlib import Path # movies = [ # {"id": 1, "title": "terminator", "year": 1989}, # {"id": 1, "title": "terminator", "year": 1989} # ] # data = json.dumps(movies) # Path("movies.json").write_text(data) # from json import loads # from pathlib import Path # data = Path('movies.json').read_text() # movies = loads(data) # print(movies) # import sqlite3 # import json # from pathlib import Path # movies = json.loads(Path("movies.json").read_text()) # print(movies) # with sqlite3.connect('db.sqlite3') as conn: # command = "INSERT INTO Movies VALUES(?,?,?)" # for movie in movies: # conn.execute(command, tuple(movie.values())) # break # conn.commit() # with sqlite3.connect('db.sqlite3') as conn: # command = 'SELECT * FROM Movies' # cursor = conn.execute(command) # for row in cursor: # print(row) # conn.commit() # import time # print(time.time()) # def send_emails(): # for i in range(100000000): # pass # start = time.time() # send_emails() # end = time.time() # print('Duration: ', start - end) # import webbrowser # from random import randint, choice, choices, random, shuffle # from datetime import datetime, timedelta # import time # import string # dt = datetime(2018, 1, 1) # dt = datetime.now() # dt2 = datetime.strptime("2018/01/01", "%Y/%m/%d") # print(dt.month) # diff = (dt-dt2) # print("days", diff) # print("seconds", diff.total_seconds()) # dt = datetime.fromtimestamp(time.time()) # print(dt.day) # print(f'{dt.year, dt.hour}') # print(choices((1, 2, 3, 4, 5, 6), k=2)) # print(random()) # # generate random passsowrd # dictionary = 'abcdevfghighlkmopqrstuvxyz123456789' # def generate_password(klen=6): # return ''.join(choices(dictionary, k=klen)) # def generate_password2(klen=6): # return ''.join(choices(string.ascii_letters + string.digits, k=klen)) # def random_shuffle(): # shuffled = list([string.digits+string.ascii_letters][0]) # shuffle(shuffled) # return ''.join(shuffled) # print(generate_password()) # print(generate_password2()) # print(random_shuffle()) # webbrowser.open('google.com') # from email.mime.multipart import MIMEMultipart # from email.mime.text import MIMEText # import smtplib # message = MIMEMultipart() # message['from'] = "Gentoer" # message['to'] = 'testuser@gmail.com' # message['subject'] = 'This is a test' # message.attach(MIMEText('Body', 'plain')) # with smtplib.SMTP(host='smtp.gmail.com', port=587) as smtp: # smtp.ehlo() # smtp.starttls() # smtp.login("testuser@codewithme.com", 'todayskyisblue1234') # smtp.send_message(message) # print('Sent...') # from email.mime.multipart import MIMEMultipart # from email.mime.text import MIMEText # from email.mime.image import MIMEImage # from pathlib import Path # from string import Template # import smtplib # template = Template(Path("template.html").read_text()) # message = MIMEMultipart() # message['from'] = "Gentoer" # message['to'] = 'testuser@gmail.com' # message['subject'] = 'This is a test' # body = template.substitute({'name': "John"}) # message.attach(MIMEText(body, 'html')) # message.attach(Path("testimage.png").read_bytes()) # with smtplib.SMTP(host='smtp.gmail.com', port=587) as smtp: # smtp.ehlo() # smtp.starttls() # smtp.login("testuser@codewithme.com", 'todayskyisblue1234') # smtp.send_message(message) # print('Sent...') # import sys # print(sys.argv) # if len(sys.argv) == 1: # print("USAGE: python3 classses.py <password>") # else: # password = sys.argv[1] # print("Password: ", password) # import requests # import subprocess # import platform # if platform.system() in 'Windows': # result = subprocess.run(['explorer', 'C:'], capture_output=False) # print('args: ', result.args) # print('returncode: ', result.returncode) # print('stderr: ', result.stderr) # print('stdout: ', result.stdout) # print(type(result)) # elif platform.system() in 'Linux': # result = subprocess.run(['ls', '-l'], capture_output=True, # text=True) # print('args: ', result.args) # print('returncode: ', result.returncode) # print('stderr: ', result.stderr) # print('stdout: ', result.stdout) # print(type(result)) # IF CHECK=TRUE THAN SUBPROCCESS.RUN WILL AUTOMATICALLY WILL RISE AN EXCEPTION! # if platform.system() in 'Windows': # result = subprocess.run( # ['python', # '-u', # r'c:\Users\g\Desktop\python_course\other.py'], # text=True, # capture_output=True) # print('args: ', result.args) # print('returncode: ', result.returncode) # print('stderr: ', result.stderr) # print('stdout: ', result.stdout) # print(type(result)) # elif platform.system() in 'Linux': # result = subprocess.run(['ls', '-l'], capture_output=True, # text=True) # print('args: ', result.args) # print('returncode: ', result.returncode) # print('stderr: ', result.stderr) # print('stdout: ', result.stdout) # print(type(result)) # if platform.system() in 'Windows': # try: # result = subprocess.run( # ['python', # '-u', # r'c:\Users\g\Desktop\python_course\other.py'], # text=True, # check=True, # capture_output=True) # print('args: ', result.args) # print('returncode: ', result.returncode) # print('stderr: ', result.stderr) # print('stdout: ', result.stdout) # print(type(result)) # except subprocess.CalledProcessError as e: # print('Called proccess exited with error') # print(e) # elif platform.system() in 'Linux': # try: # result = subprocess.run(['ls', '-l'], capture_output=True, # text=True, # check=True) # print('args: ', result.args) # print('returncode: ', result.returncode) # print('stderr: ', result.stderr) # print('stdout: ', result.stdout) # print(type(result)) # except subprocess.CalledProcessError as e: # print('Called proccess exited with error') # print(e) # import requests # # print(response) # url = 'https://api.yelp.com/v3/businesses/search' # response = requests.get(url) # print(response.text) # from bs4 import BeautifulSoup # import requests # url = 'https://stackoverflow.com/questions' # response = requests.get(url) # soup = BeautifulSoup(response.text, features='html.parser') # questions = soup.select('.question-summary') # print(questions[0].get('id', 0)) # cls_selected = questions[0].select_one('.question-hyperlink') # # print(cls_selected.getText()) # for question in questions: # print(question.select_one('.question-hyperlink').getText()) # print(question.select_one('.vote-count-post').getText()) # import bs4 # from selenium import webdriver # browser = webdriver.Chrome() # browser.get('https://github.com/login') # signin_link = browser.find_element_by_id('login_field') # username_box = browser.find_element_by_id("login_field") # username_box.send_keys("gurguration") # password_box = browser.find_element_by_id("password") # password_box.send_keys("yourpassword") # password_box.submit() # profile_link = browser.find_element_by_class_name('user-profile-link') # link_label = profile_link.get_attribute('innerHTML') # assert 'gurguration' in link_label # browser.quit() # import PyPDF2 # with open('test.pdf', 'rb') as pdffile: # reader = PyPDF2.PdfFileReader(pdffile) # print(reader.numPages) # page = reader.getPage(0) # page.rotateClockwise(90) # writer = PyPDF2.PdfFileWriter() # writer.addPage(page) # with open("rotated.pdf", "wb") as output: # writer.write(output) # import PyPDF2 # merger = PyPDF2.PdfFileMerger() # file_names = ["first.pdf", "second.pdf"] # for file_name in file_names: # merger.append(file_name) # merger.write('combined.pdf') # import openpyxl # # wb = openpyxl.Workbook() # wb = openpyxl.load_workbook("configuration.xlsx") # print(wb.sheetnames) # sheet = wb["Sheet1"] # # wb.create_chartsheet("Sheet2", 0) # cell = sheet['a1'] # cell_value = cell.value # print(cell_value) # print(cell.coordinate) # sheet.cell # import openpyxl # wb = openpyxl.load_workbook('configuration.xlsx') # sheet = wb['Sheet1'] # sheet.cell(row=1, column=1) # print(sheet.max_column) # wb = openpyxl.load_workbook('configuration.xlsx') # sheet = wb['Sheet1'] # sheet.cell(row=1, column=1) # for row in range(1, sheet.max_row + 1): # print(sheet.cell(row, 1).value) # sheeta = sheet['a'] # sheetac = sheet['a:c'] # print(sheeta) # print(sheetac) # sheet.append([1, 2, 3, 4]) # sheet.insert_rows(16, 3) # wb.save('configurations2.xlsx') # import numpy as np # array = np.array([[1, 2, 3], [4, 5, 6]]) # print(array) # print(type(array)) # print(array.shape) # zeros = np.zeros((3, 3), dtype=int) # print(zeros) # print(zeros[0, 2]) # print(zeros == 0) # print(zeros[zeros == 0]) # print(np.sum(zeros)) # print(np.floor(zeros)) # dimensions_inch = np.array([1, 2, 3]) # dimensions_cm = dimensions_inch * 2.54 # print(dimensions_cm)
5fa252ec038b246bff6615dcdfb99104de65a85e
Maxarre/CodingBat
/Python/Logic_1/alarm_clock.py
721
4.09375
4
# Given a day of the week encoded as 0=Sun, 1=Mon, 2=Tue, ...6=Sat, # and a boolean indicating if we are on vacation, # return a string of the form "7:00" indicating when the alarm # clock should ring. Weekdays, the alarm should be "7:00" and on # the weekend it should be "10:00". # Unless we are on vacation -- then on weekdays it should be # "10:00" and weekends it should be "off". # alarm_clock(1, False) → '7:00' # alarm_clock(5, False) → '7:00' # alarm_clock(0, False) → '10:00' def alarm_clock(day, vacation): if 1<=day<=5: if vacation==True: return "10:00" else: return "7:00" elif day==0 or day==6: if vacation==True: return "off" else: return "10:00"-
253a681c677b34020eb48b07ad14426fdfe99ce1
rohitrs3/Python
/Sum of Natural Numbers.py
332
4.0625
4
#Program for Sum N natural numbers N=int(input("Enter the numbers : ")) Sum= N*(N+1)/2 print(Sum) ## n=eval(input("enter the number to add for natural number : ")) if(not instance(n,int)): print("Wrong Input") if(n>0): sum=(n*(n+1))/2 print("sum of natural numbers is ", sum) else: print("Error!!")
0e986cc7d5235e68d9a7f48c54422046e535dd60
Vampirskiy/helloworld
/venv/Scripts/Урок2/in_ex.py
383
3.734375
4
hero='superman' if hero.find('man') != -1: # Ищем слово мен 1 способ print('Есть!') if 'man' in hero: # Ищем слово мен 2 способ print('Есть!') goals = ['стать гуру языка питон', 'здоровье', 'накормить курицу'] if 'здоровье' in goals: print('все заебись!')
ed555bedb87042a81c11f1be06739a0b29eeb7d9
epenelope/python-playground
/heart.py
583
3.796875
4
import turtle turtle.bgcolor('black') turtle.pensize(2) def curve(): for i in range(200): turtle.right(1) turtle.forward(1) turtle.speed(2) turtle.color("red", "pink") turtle.begin_fill() turtle.left(140) turtle.forward(111.65) curve() turtle.left(120) curve() turtle.forward(111.65) turtle.end_fill() turtle.penup() turtle.setpos(0,100) turtle.write('you\'re my person', move='True', align='center', font='veranda, 14') turtle.setpos(0,60) turtle.write('love, Liz', move='True', align='center', font='veranda, 14') turtle.hideturtle() turtle.exitonclick()
ee2b9e2d2be2754988911626649326f1a3389430
langtodu/learn
/study/class.py
1,182
3.953125
4
# -*- coding: utf-8 -*- ##类的构建方法介绍 #**************** 实例方法 ************** ## classmethod 修饰符对应的函数不需要实例化,不需要 self 参数,但第一个参数需要是表示自身类的 cls 参数,可以来调用类的属性,类的方法,实例化对象等。 ## classmethod和staticmethod都不能调用实例属性 class Test(object): def __init__(self, str="Hello istancemethod!"): self.init_str = str def add1(self, val1, val2): #类方法添加self才能使用类属性 print self.init_str print "this is istancemethod" print val1+val2 @classmethod def add2(cls, val1, val2): # 类方法需要添加cls才能使用属性 print cls.__name__ print "this is classmethod" print val1 + val2 @staticmethod def add3(val1, val2): # 类方法不需要添加任何必要的参数就可以使用类属性 # print StaticMethod.init_str print Test.__name__ print "this is staticmethod" print val1 + val2 if __name__ == "__main__": stance1 = Test() stance1.add1(1, 2) Test.add2(2, 3) Test.add3(3, 4)
c32b6844d21f7686bdbbe493159b1a447ef684ee
cvargas-xbrein/aws-glue-monorepo-style
/glue/shared/glue_shared_lib/src/glue_shared/str2obj.py
614
3.515625
4
import datetime import logging from typing import Tuple import dateutil.parser LOGGER = logging.getLogger(__name__) def str2bool(value): return value.lower() == "true" def comma_str_time_2_time_obj(comma_str: str) -> Tuple[datetime.datetime, ...]: """ Convert comma separated time strings into a list of datetime objects. Parameters ---------- comma_str Comma separated times: 2020-04-20 16:00:00, 2020-04-20 15:00:00 Returns ------- A list of datetime objects. """ return tuple(dateutil.parser.parse(time_str) for time_str in comma_str.split(","))
7840462070b262c589723764b9314780f03b4a9a
nkrishnappa/100DaysOfCode
/Python/Day-#27/PythonArguments.py
872
4.4375
4
# Default Arguments def my_fn(a, b, c=5): pass my_fn(c=3, b=2, a=1) # Unlimited Arguments ''' # Problem def add(a, b): print(a + b) add(3,4) # 7 add(3, 4, 5) # TypeError: add() takes 2 positional arguments but 3 were given ''' # Solution def add(*args): """the add module will add any number of numbers Args: *args : numbers """ print(type(args)) # <class 'tuple'> sum = 0 for element in args: sum += element print(sum) add(3,4) # 7 add(3, 4, 5) # 12 add(3, 4, 5, 6, 7) # 25 # kwargs def calculate(n, **kwargs): print(type(kwargs)) # <class 'dict'> # for key, value in kwargs.items(): # print(key,value) # add 3 # multiply 5 # print(kwargs["add"]) # 3 # add additional argument n n += kwargs["add"] n *= kwargs["multiply"] print(n) # 40 calculate(5, add=3, multiply=5)
d82514659192f06b879e4ac5557ed766027da44a
Peggyliu613/mile_to_km_converter
/main.py
668
3.734375
4
from tkinter import * window = Tk() window.title("Mile to Kilogram Converter") window.minsize(200, 100) window.config(padx=20, pady=20) mile_inputted = Entry(width=5) mile_inputted.grid(column=1, row=0) mile_label = Label(text="Miles") mile_label.grid(column=2, row=0) convert_to = Label(text=0) convert_to.grid(column=1, row=1) km_label = Label(text="Km") km_label.grid(column=2, row=1) is_equal_label = Label(text="is equal to") is_equal_label.grid(column=0, row=1) def calculate(): convert_to["text"] = int(mile_inputted.get()) * 1.609 submit_button = Button(text="calculate", command=calculate) submit_button.grid(column=1, row=2) window.mainloop()
0fd6a34b52d092c238cfd65a8296c4bededd81b0
3desinc/YantraBot
/example_programs/simple_light_sensor.py
2,333
4.5625
5
#!/usr/bin/env python3 ## simple_light_sensor.py ## This is an example program designed for 3DES programs ## Writen by Martin Dickie ## this example program will just read a light sensor connected to pin 2 and print either 0 or 1, based on how bright the light is. import RPi.GPIO as GPIO # brings in the packages for GPIO, GPIO is the way to use pins which are connected to the raspberry pi. GPIO.setmode(GPIO.BCM) # tells the board to use BCM format which is the numbering on the board that we have # there are other ways to have the pin numbers mapped, but they are usually more confusing GPIO.setup(2,GPIO.IN) # here GPIO is setting pin 2 to be an input which means we can read values from it. Notice how there's a coma, that coma indicates # that there is a second option in the perameters. so it's (PIN# , INPUT/OUTPUT) ################################### ##### ##### ##### basic program ##### ##### ##### ################################### print(GPIO.input(2)) # this will print whatever the sensor pin is reading. In this case since the Raspberry pi is only using "digital" pins the value can either be 0 or 1. Some other devices can have "analog" pins which are more sensitive and range from 0 to 1023 ## That first area is just to print the input. Next let's try printing the input every second forever ################################### ##### ##### ##### infinite program ##### ##### ##### ################################### try: # when planning to do an infinite loop it's good to tell it to try something and then if there's an exception it will know to stop. while True: # while will continue until it is given false, so in this case it will continue forever print(GPIO.input(2)) # prints the value of pin 2. Same deal as before, so 1 or 0 sleep(1) # sleep takes any number of seconds and tells the program to wait that long before continuing. except KeyboardInterrupt: # this exception will happen on a keyboard interrupt. Normally this is pressing Ctrl + C at the same time while in command prompt. GPIO.cleanup() # cleanup will reset all of the values to the correct values
148c6d9d37a9fd79e06e4371a30c65a5e36066b2
jtquisenberry/PythonExamples
/Jobs/multiply_large_numbers.py
2,748
4.25
4
import unittest def multiply(num1, num2): len1 = len(num1) len2 = len(num2) # Simulate Multiplication Like this # 1234 # 121 # ---- # 1234 # 2468 # 1234 # # Notice that the product is moved one space to the left each time a digit # of the top number is multiplied by the next digit from the right in the # bottom number. This is due to place value. # Create an array to hold the product of each digit of `num1` and each # digit of `num2`. Allocate enough space to move the product over one more # space to the left for each digit after the ones place in `num2`. products = [0] * (len1 + len2 - 1) # The index will be filled in from the right. For the ones place of `num` # that is the only adjustment to the index. products_index = len(products) - 1 products_index_offset = 0 # Get the digits of the first number from right to left. for i in range(len1 -1, -1, -1): factor1 = int(num1[i]) # Get the digits of the second number from right to left. for j in range(len2 - 1, -1, -1): factor2 = int(num2[j]) # Find the product current_product = factor1 * factor2 # Write the product to the correct position in the products array. products[products_index + products_index_offset] += current_product products_index -= 1 # Reset the index to the end of the array. products_index = len(products) -1; # Move the starting point one space to the left. products_index_offset -= 1; for i in range(len(products) - 1, -1, -1): # Get the ones digit keep = products[i] % 10 # Get everything higher than the ones digit carry = products[i] // 10 products[i] = keep # If index 0 is reached, there is no place to store a carried value. # Instead retain it at the current index. if i > 0: products[i-1] += carry else: products[i] += (10 * carry) # Convert the list of ints to a string. #print(products) output = ''.join(map(str,products)) return output class Test(unittest.TestCase): def setUp(self): pass def test_small_product(self): expected = "1078095" actual = multiply("8765", "123") self.assertEqual(expected, actual) def test_large_product(self): expected = "41549622603955309777243716069997997007620439937711509062916" actual = multiply("654154154151454545415415454", "63516561563156316545145146514654") self.assertEqual(expected, actual) def tearDown(self): pass if __name__ == '__main__': unittest.main()
0a4de4cf1a193012cc678daa7efa786d713bd22e
aetooc/Practice-Questions-Python
/Test1_part1.py
178
4.03125
4
# My Answer for Question 1 number= int(input('Enter a number:')) Range= int(input('Enter the Range:')) for j in range(1, Range+1): k=number*j print(number,'x',j,'=',k)
494c89ea33244ab5db3066ab7e0662edd34c27b9
IanCBrown/practice_questions
/two_stones.py
224
3.734375
4
def two_stones(state): if state % 2 == 0: return "Bob" else: return "Alice" def main(): start_state = int(input()) print(two_stones(start_state)) if __name__ == "__main__": main()
4fa9c01e77d27a0f21cfd8fc63d7ed31fdc1b56f
hoelzl/L3
/l3/core/dice.py
5,899
3.875
4
import random import re from abc import ABC, abstractmethod from typing import Sequence, Callable, Tuple, List class Die(ABC): @abstractmethod def roll(self) -> None: """" Roll the die and store the value. The rolled value can be accessed by the value property. """ pass @property @abstractmethod def value(self) -> int: """Return the last value rolled with this die.""" pass @property @abstractmethod def num_sides(self) -> int: """Return the number of sides this die has.""" pass class ConstantDie(Die): """ A die that returns a constant value. Mostly useful as an offset for rpg dice, but can also be used to simulate a cheating player using loaded dice. """ def __init__(self, value): self._value = value def roll(self) -> None: pass @property def value(self) -> int: return self._value @property def num_sides(self) -> int: return self._value class RegularDie(Die): """ A single roll of a fair n-sided die. """ def __init__(self, num_sides: int = 6): """ Initialize a Die. :param num_sides: The number of sides of the die. """ if num_sides < 2: raise ValueError(f"Cannot create a die with less than 2 sides") self._num_sides = num_sides self._value = 0 # Roll the die once to ensure we have a valid value. self.roll() def roll(self) -> None: self._value = random.randint(1, self.num_sides) @property def value(self) -> int: return self._value @value.setter def value(self, value: int) -> None: if 1 <= value <= self.num_sides: self._value = value else: raise ValueError(f"{self.num_sides}-sided die cannot have value " f"{value}.") @property def num_sides(self) -> int: return self._num_sides class PairOfDice: """ A single roll with a pair of 6-sided dice. """ def __init__(self): self._dice = (RegularDie(6), RegularDie(6)) def roll(self) -> None: consume(map(lambda d: d.roll(), self._dice)) @property def values(self) -> (int, int): return tuple(map(lambda d: d.value, self._dice)) @values.setter def values(self, values): d1, d2 = self._dice v1, v2 = values d1.value = v1 d2.value = v2 @property def value(self) -> int: return sum(self.values) @property def is_double(self) -> bool: return self._dice[0].value == self._dice[1].value class RpgDice: """" A single roll with a given configuration of dice. Dice configurations are specified in the usual RPG notation: - d6, D6, 1d6 or 1D6 represent a single roll of a 6-sided die, i.e., an uniformly distributed value between 1 and 6. - 2d6 or 2D6 represents a single roll of two 6-sided dice, i.e., a value between 2 and 12 distributed so that 2 and 12 have probability 1/36 and 7 has probability 1/6. - In general ndk or nDk with positive integers n and k represents a single roll of n k-sided dice. - Rolls can be added, e.g., 1d4 + 2d6 represents a single roll of one 4-sided and two 6-sided dice. - A single number represents a fixed value. For example, d6 + 4 represents a single roll of a six-sided die to which 4 is added, i.e., a random number uniformly distributed between 6 and 10. """ def __init__(self, configuration): self.dice = self.parse_configuration(configuration) DICE_REGEX = re.compile(r'^\s*(\d*)\s*([Dd]?)\s*(\d+)\s*$') @classmethod def parse_single_die_configuration(cls, configuration: str) \ -> Tuple[int, Callable, int]: """ Parse a single die configuration string into a die spec. A die spec is a triple with the elements - Number of dice this triple represents - Function to construct a single die of this type - Value/Number of Sides of the dice """ match = cls.DICE_REGEX.match(configuration) num_dice = int(match.group(1) or '1') dice_kind = RegularDie if match.group(2) else ConstantDie num_sides = int(match.group(3)) return num_dice, dice_kind, num_sides @staticmethod def parse_configuration(configuration: str) \ -> Sequence[Tuple[int, Callable, int]]: """ Parse a configuration string and return a sequence of dice specs. Dice specs are triples with the elements - Number of dice this triple represents - Function to construct a single die of this type - Value/Number of Sides of the dice :param configuration: A string in the form '2d6 + 4' :return: A sequence of Dice specs """ single_configs = configuration.split('+') return list(map(RpgDice.parse_single_die_configuration, single_configs)) @staticmethod def dice_from_single_spec(spec: Tuple[int, Callable, int]) -> List[Die]: """ Create a list of Die instances, given a single die spec. :param spec: A die spec in the form returned by parse_configuration :return: A list of dice """ num_dice, constructor, num_sides = spec return [constructor(num_sides)] * num_dice @staticmethod def dice_from_specs(specs: Sequence[Tuple[int, Callable, int]]) \ -> List[Die]: """ Create a list of Die instances given a sequence of die specs. :param specs: A list of die specs as returned by parse_configuration :return: A list of dice """ ds = map(RpgDice.dice_from_single_spec, specs) return [die for dice_list in ds for die in dice_list]
b99d2d725d0da10ea4d0d02367e7322d743cf28a
Aasthaengg/IBMdataset
/Python_codes/p02909/s116131344.py
134
3.953125
4
s = input() if s == 'Sunny': result = 'Cloudy' elif s == 'Cloudy': result = 'Rainy' else: result = 'Sunny' print(result)
a09384307150c62f613150e3943eeac09388d61a
vighnesh153/ds-algo
/src/arrays/first-and-last-position-of-element-in-sorted-array.py
937
3.75
4
def find_left(arr: [int], target: int): position = float('inf') low = 0 high = len(arr) - 1 while low <= high: mid = (low + high) // 2 if target <= arr[mid]: if arr[mid] == target: position = min(position, mid) high = mid - 1 else: low = mid + 1 return -1 if position == float('inf') else position def find_right(arr: [int], target: int): position = -float('inf') low = 0 high = len(arr) - 1 while low <= high: mid = (low + high) // 2 if target >= arr[mid]: if arr[mid] == target: position = max(position, mid) low = mid + 1 else: high = mid - 1 return -1 if position == -float('inf') else position def solve(arr, target): return [find_left(arr, target), find_right(arr, target)] A = [5, 7, 7, 8, 8, 10] B = 8 print(solve(A, B))
58a2afa51ccad18da54428f0247cf07778debb1f
clturner/algorithms_linked-lists_data-structures
/0x0A-nqueens/0-nqueens.py
2,027
3.5
4
#!/usr/bin/python3 import sys global N board = [] queens = [] first_column = [] sys.setrecursionlimit(18500) if len(sys.argv) is 1: print("Usage: nqueens N") sys.exit(1) N = sys.argv[1] try: int(N) except: print("N must be a number") sys.exit(1) if int(N) < 4: print("N must be at least 4") sys.exit(1) def safe(board, row, column): for i in range(len(queens)): coords = queens[i] r = coords[0] c = coords[1] if row == r: return(False) elif column == c: return(False) elif (r-c) == (row-column): return(False) elif (r+c) == (row+column): return(False) return(True) def place(board, row, column): if column >= int(N): return(True) if safe(board, row, column) is True: board[row][column] = 1 if column == 0: idx = [] idx.append(row) idx.append(column) first_column.append(idx) idx = [] idx = [] idx.append(row) idx.append(column) queens.append(idx) idx = [] if column >= int(N)-1: print(queens) return(True) column += 1 row = 0 place(board, row, column) else: row += 1 if row == int(N): l = queens[-1] row = l[0] column = l[1] board[row][column] = 0 row += 1 del queens[-1] if row >= int(N): if len(first_column) == int(N): sys.exit() l = queens[-1] row = l[0] column = l[1] board[row][column] = 0 row += 1 del queens[-1] place(board, row, column) def nQueens_board(N): count = 0 for i in range(0, int(N)): board_row = [] for j in range(0, int(N)): count += 1 board_row.append(0) board.append(board_row) nQueens_board(int(N)) place(board, 0, 0)
31a6d64dea403d6a7343eb9652577a665f7fd8ca
masyuk/LearnPython
/11_dictionary_1.py
299
3.6875
4
# (----Item----) # (key) (value) enemy = { 'loc_x': 70, 'loc_y': 50, 'color': 'green', 'health': 100, 'name': 'Mudilo' } print(enemy) print(enemy['name']) enemy['rank'] = 'Noob' print(enemy) del enemy['rank'] print(enemy) print('--------------') enemy['loc_x'] += 40
972362f6ecdfacdfc1559075ee82a2f3ed8500ee
JulieZhang0102/MIS3640
/session15/exercise2.py
1,853
4.15625
4
import math class Point: ''' a point with x, y attributes ''' class Circle: ''' Circle with attributes center and radius ''' center = Point() circle = Circle() circle.center.x = 150 circle.center.y = 100 circle.radius = 75 class Rectangle: """Represents a rectangle. attributes: width, height, corner. """ def distance_between_points(p1, p2): """Computes the distance between two Point objects. p1: Point p2: Point returns: float """ distance_x = p1.x - p2.x distance_y = p1.y - p2.y distance = math.sqrt(distance_x**2 + distance_y**2) return distance def point_in_circle(Circle, Point): circle_center = Circle.center if distance_between_points(circle_center, Point) <= Circle.radius: return True else: return False def rect_in_circle(Circle, Rectangle): aCorner=Rectangle.corner bCorner=Rectangle.corner cCorner=Rectangle.corner dCorner=Rectangle.corner bCorner.x=aCorner.x+Rectangle.width dCorner.y=bCorner.y-Rectangle.height cCorner.x=dCorner.x-Rectangle.width #Checking All Corners of Rec if point_in_circle(Circle,aCorner): if point_in_circle(Circle,bCorner): if point_in_circle(Circle,cCorner): if point_in_circle(Circle,dCorner): return True def rect_circle_overlap(Circle,Rectangle): a2Corner=Rectangle.corner b2Corner=Rectangle.corner c2Corner=Rectangle.corner d2Corner=Rectangle.corner b2Corner.x=a2Corner.x+Rectangle.width d2Corner.y=b2Corner.y-Rectangle.height c2Corner.x=d2Corner.x-Rectangle.width if point_in_circle(Circle,a2Corner): return True elif point_in_circle(Circle,b2Corner): return True elif point_in_circle(Circle,c2Corner): return True elif point_in_circle(Circle,d2Corner): return True
670a9bb45e6ce666b8296df4da30c2b14e883641
pflun/learningAlgorithms
/isSubtree.py
1,357
3.9375
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 isSubtree(self, s, t): res = [] queue = [s] while queue: curr = queue.pop(0) if self.helper(curr, t): res.append(True) if curr.left: queue.append(curr.left) if curr.right: queue.append(curr.right) return any(res) def helper(self, s, t): if not s and not t: return True elif s and not t: return True elif t and not s: return False elif t and s: if s.val == t.val: return self.helper(s.left, t.left) and self.helper(s.right, t.right) else: return False head_node = TreeNode(0) n1 = TreeNode(1) n2 = TreeNode(0) n3 = TreeNode(5) n4 = TreeNode(4) n5 = TreeNode(5) n6 = TreeNode(5) n7 = TreeNode(5) head_node.left = n1 head_node.right = n2 n1.left = n3 n1.right = n4 n3.left = n6 n6.left = n5 n6.right = n7 head_node2 = TreeNode(5) m1 = TreeNode(5) m2 = TreeNode(5) head_node2.left = m1 head_node2.right = m2 test = Solution() print test.isSubtree(head_node, head_node2) # 0 # 1 0 # 5 4 # 5 #5 5
cfb728e4c1ed16e2dc94c3c3544878021e3b6193
arifanf/Python-AllSubjects
/PDP 5/pdp5_7.py
208
3.59375
4
def main(): sumData=0 n=int(input("input bil : ")) while n!= 9999: print(n) sumData+=n n=int(input("Input bil : ")) print("Jumlahan : {}".format(sumData)) if __name__ == '__main__': main()
a2635d0abdf94fa30448166a77a857a520724023
RakeshSuvvari/Joy-of-computing-using-Python
/PointsDistributionMethod.py
2,013
3.609375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed May 19 20:22:33 2021 @author: rakesh """ import networkx as nx import random import matplotlib.pyplot as plt def add_edges(): nodes=list(G.nodes()) for s in nodes: for t in nodes: if s!=t: r=random.random() if r<= 0.5: G.add_edge(s,t) return G def assign_points(G): nodes=list(G.nodes()) p=[] for each in nodes: p.append(100) return p def distribute_points(G,points): nodes = list(G.nodes()) new_points=[] for i in range(len(nodes)): new_points.append(0) for n in nodes: out=list(G.out_edges(n))#list of tuples if len(out)==0: #if no outgoing edges for a node new_points[n]=new_points[n]+points[n] else: share=points[n]/len(out) for (src,tgt) in out: new_points[tgt]=new_points[tgt]+share return new_points def keep_distributing(points,G): while(1): new_points=distribute_points(G,points) print(new_points) print(' ') '''stop=input("Press q to stop or any other key to continue: ") if stop == 'q': break''' if points == new_points: break points=new_points return new_points def rank_by_points(points): d={} for i in range(len(points)): d[i]=points[i] print(sorted(d.items(),key=lambda f:f[1])) #Create a directed graph G=nx.DiGraph() G.add_nodes_from([i for i in range(10)]) G=add_edges() #Visualise the Graph print(G.edges()) nx.draw(G,with_labels=True) plt.show() #points distribution procedure #assign initial points points=assign_points(G) #keep distributing final_points=keep_distributing(points,G) #rank by points rank_by_points(final_points) #default networkx function result=nx.pagerank(G) print(' ') print("Compare with default pagerank") print(sorted(result.items(),key=lambda f:f[1]))
779e84f66b5b7952863a324ad23de399f27231fa
yanliangchen/ware_house
/技术收藏/learingnote/基础代码/Python练习题 010:分解质因数.py
1,877
3.765625
4
''' 将一个正整数分解质因数。例如:输入90,打印出90=2*3*3*5。 一开始我简单地以为,只要将输入的整数拿个数字列表挨个除一遍,能整除的就可以收为质因数。 但事实上是行不通的,因为这样会连同 4、6、9 这样的数字也收进去,而当质因数有重复时(比如12=2*2*3),就会被遗漏掉。 基于以上的考虑,转换思路:还是将输入的整数(n)拿个数字列表挨个除,但要多除几遍,而且每遍除的时候,一旦出现质因数, 立即把这个数字收了,把输入的数字除以这个质因数并重新赋值给n,然后停止这个循环,进入下一个循环。如此便能解决上述的问题。 最后还有一点需要注意的:如果这个数字已被任意质因数整除过,那么走完所有循环之后,最后的 n 也必然是其中的一个质因数,应该把它一并收进列表里。 ''' n = num = int(input('请输入一个数字:')) # 用num保留初始值 f = [] # 存放质因数的列表 for j in range(int(num / 2) + 1): # 判断次数仅需该数字的一半多1次 for i in range(2, n): t = n % i # i不能是n本身 if t == 0: # 若能整除 f.append(i) # 则表示i是质因数 n = n // i # 除以质因数后的n重新进入判断,注意应用两个除号,使n保持整数 break # 找到1个质因数后马上break,防止非质数却可以整除的数字进入质因数列表 if len(f) == 0: # 若一个质因数也没有 print('该数字没有任何质因数。') else: # 若至少有一个质因数 f.append(n) # 此时n已被某个质因数整除过,最后一个n也是其中一个质因数 f.sort() # 排下序 print('%d=%d' % (num, f[0]), end='') for i in range(1, len(f)): print('*%d' % f[i], end='')
94c900cc7ad12ddf238a58e591f0057d975f8df2
twonds/healthmonger
/healthmonger/memory.py
2,480
3.546875
4
"""In memory data store module """ from collections import defaultdict import config class Store: """Simple in-memory data store. """ def __init__(self): self.data_loaded = False self.time_loaded = None self.data = defaultdict(dict) for table, schema in config.TABLE_SCHEMA.iteritems(): self.data[table] = self.new_store() def new_store(self): """ Create and return an new storage type. """ return defaultdict(set) def update_store(self, table, store, timestamp): """Update a table with new data. This overwrites the old data. @param table: Table name @type table: C{string} @param store: The new table data that will replace the old @param store: C{dict} @param timestamp: The timestamp to mark the time this data was loaded @type timestamp: C{int} """ self.data[table] = store self.time_loaded = timestamp self.data_loaded = True def connect(self): """ This connects to nothing since this is in memory. Used to do some initialization. """ def insert(self, table_name, key, value, obj): """Insert a row of data into the table keyed by a key and value. This is used for quick lookups when hits from a search index are a key and value in the row. @param table_name: The name of the table @type table_name: C{string} @param key: The key indicating where the data is located. @type key: any @param value: The value stored in that key. The key and value are used to create a lookup key for the entire row @type value: any @parm obj: The row of data we want to store @type obj: any """ i = unicode(key)+u':'+unicode(value) self.data[table_name][i] = obj def fetch(self, table_name, key, value): """Fetch a row or object based on a key and value in that row. @param table_name: The name of the table @type table_name: C{string} @param key: The key indicating where the data is located. @type key: any @param value: The value stored in that key. The key and value are used to create a lookup key for the entire row @type value: any """ i = unicode(key)+u':'+unicode(value) return self.data[table_name][i]
ff6252ff0903b8bdfe57d8ebbe27f58cd1877a4f
mshasan/Python-Computing
/Random number generations/generate normal by Box-muller.py
1,902
3.546875
4
import random import math import numpy as np import pylab as P #============================================================================================================ # 2(d) ------------------------------------------------------------------------------------------------------ # generating Normal(10,25) random sample of size 1000 by Box-Muller algorithm n = 1000 mu = 10 # mean of normal sigma = 5 # standard deviation of normal norm = [] normal_sum = 0 # a variable to store the sum of normal random values normal_sq_sum = 0 # another variable to store sum of squares for i in range(n): # initialization of the for loop over n numbers u1 = random.uniform(0, 1) # generating a uniform random value u2 = random.uniform(0, 1) # generating another uniform random value z1 = math.sqrt(-2*math.log(u1))*math.cos(2*math.pi*u2) # using appropriate transformation to get z1 and z2 z2 = math.sqrt(-2*math.log(u1))*math.sin(2*math.pi*u2) # two standard normal values normal = mu + z1*sigma # transformation from standard normal to normal norm.append(normal) # print(normal) # print normal random variates normal_sum = normal_sum + normal # sum of normal random values normal_sq_sum = normal_sq_sum + normal**2 # sum of squares of normal mean = normal_sum/n # mean of the normal sample var = (normal_sq_sum - n*mean**2)/(n-1) # sample variance print "Normal sample mean of the sample is:" print mean print "Normal sample variance of the sample is:" print var #sample mean and variance are close to expected mean 10 and variance 25 # creating a normal histogram P.figure() P.hist(norm) P.show()
f76b180064b451c4075bc87eee7caf3d66786d9e
thenu97/codewars
/string-split.py
325
3.703125
4
# split string in pair and if odd, pair it with '_' def soluton(s): if len(s) % 2 == 0: l = [s[i:i+2] for i in range(0, len(s), 2)] if len(s) % 2 == 1: l = [s[i:i+2] for i in range(0, len(s) - 1, 2)] l2 = s[-1] + "_" print(l2) #l3 = str(l2) l.append(l2) return l
2cea947273ac03e10181188665955e52521a5d5c
shan-mathi/InterviewBit
/largest_number_formed.py
331
3.5
4
def arrange(A): li = list(map(str,A)) li.sort() l = len(A) for i in range(l): for j in range(i,l): first = li[i]+li[j] second = li[j]+li[i] if second>first: li[j],li[i]= li[i], li[j] ans = "".join(li) return int(ans) print(arrange([0,0,0,0,0]))
ec28302363c51db69fadc004239e2d1ac9bf5704
popcorncolonel/Sim
/actuators.py
5,759
3.609375
4
""" TODO: left, right, up, down actuators. """ import sim_tools import random import time class Actuator: """ Only actuates on all organisms. "targets" can be False. """ def __init__(self, sim, org): from sim import Simulation from organism import Organism assert isinstance(sim, Simulation) assert isinstance(org, Organism) self.sim = sim self.org = org self.parents = set() def add_parent(self, parent): self.parents.add(parent) def actuate(self, target): """ Actuates on an organism. Perhaps eventually an erroneous assumption, but works for now (there is nothing other than organisms) """ assert False # this must be overwritten by the actuator def default(self): """ What gets called if target == None """ return def activate(self, target, signal, parent=None): if signal == False: return if target is not None: self.actuate(target) else: self.default() class MoveActuator(Actuator): """ Performs an action when it recieves a signal. """ def __init__(self, sim, org, delta_x=0, delta_y=0): super().__init__(sim, org) self.delta_x = delta_x self.delta_y = delta_y def actuate(self, target) -> None: self.sim[self.org.x][self.org.y].remove(self.org) self.org.x += self.delta_x self.org.y += self.delta_y self.org.x = self.org.x % self.sim.width self.org.y = self.org.y % self.sim.height self.sim[self.org.x][self.org.y].append(self.org) class TowardsActuator(MoveActuator): def default(self): # If target is None, move in a random direction self.delta_x = random.choice([-1, 0, 1]) self.delta_y = random.choice([-1, 0, 1]) super().actuate(None) def actuate(self, target): assert target is not None import math if target.x == self.org.x: self.delta_x = 0 else: self.delta_x = math.copysign(1, target.x - self.org.x) # if i am at (5,0) and target is at (7,0), we want to return 1. if target.y == self.org.y: self.delta_y = 0 else: self.delta_y = math.copysign(1, target.y - self.org.y) # if i am at (0,8) and target is at (0,10), we want to return 1. self.delta_x = int(self.delta_x) self.delta_y = int(self.delta_y) super().actuate(target) class AwayActuator(MoveActuator): def default(self): # If target is None, move in a random direction self.delta_x = random.choice([-1, 0, 1]) self.delta_y = random.choice([-1, 0, 1]) super().actuate(None) def actuate(self, target): assert target is not None import math if target.x == self.org.x: self.delta_x = random.choice([-1, 1]) else: self.delta_x = math.copysign(1, -(target.x - self.org.x)) # if i am at (5,0) and target is at (7,0), we want to return -1. if target.y == self.org.y: self.delta_y = random.choice([-1, 1]) else: self.delta_y = math.copysign(1, -(target.y - self.org.y)) # if i am at (0,8) and target is at (0,10), we want to return -1. self.delta_x = int(self.delta_x) self.delta_y = int(self.delta_y) super().actuate(target) class AttackActuator(Actuator): """ Can battle another organism if they're one unit away from you """ def actuate(self, target): """ Only attack if Check if the target(s) is(are) 1 unit away """ if not sim_tools.is_n_units_away((self.org.x, self.org.y), (target.x, target.y), 1): return # if they try to attack something that's more than one unit away self.org.power += 1 # reward for being aggressive prob_victory = self.org.power / (self.org.power + target.power) won_battle = sim_tools.bernoulli(prob_victory) if won_battle: winner = self.org loser = target else: winner = target loser = self.org self.sim.remove(loser) winner.kills += 1 winner.hunger = 0 winner.power += 1 # reward for winning winner.start_time += (time.time() - winner.start_time) / 2 class MateActuator(Actuator): """ Can mate with another organism if they're one unit away from you """ def actuate(self, target): """ Returns the baby of self.organism and target, to-be-placed where they are """ if not sim_tools.is_n_units_away((self.org.x, self.org.y), (target.x, target.y), 1): return # if they try to mate with something that's more than 1 unit away if self.org.representing_char != target.representing_char: # TODO: maybe allow orgs of different species to mate? just with unfavorable outcomes # (i.e. choose the min of the powers, not the avg) return if not self.org.able_to_mate() or not target.able_to_mate(): return power_avg = (target.power + self.org.power) / 2 parent_coords = (self.org.x, self.org.y) my_char = sim_tools.bernoulli(0.5) if my_char: char = self.org.representing_char else: char = target.representing_char baby = self.sim.spawn_new_life(coords=parent_coords, representing_char=char, power=power_avg, parents=(self.org, target)) self.org.mate_timeout = target.mate_timeout = time.time() + 30 self.org.start_time += (time.time() - self.org.start_time) / 2 return baby
26cd1ffcb81295cfb5e1ce3884bd37161ba57195
abhay-jindal/Coding-Problems
/Array/Find K Closest Elements.py
1,933
4.15625
4
""" Find K Closest Elements https://leetcode.com/problems/find-k-closest-elements/ Given a sorted integer array arr, two integers k and x, return the k closest integers to x in the array. The result should also be sorted in ascending order. An integer a is closer to x than an integer b if: |a - x| < |b - x|, or |a - x| == |b - x| and a < b Time complexity is O(nk) as we have to iterate over elements once and for finding max time complexity is length of dict i.e. k """ def closestNumbers(array, number, k): n = len(array) # if range of numbers to return i.e. k is greater than the length of array itself then return array # as we already have required number of elements or less. if n < k: return array # further verions of python 3.6+ already have dicts in order i.e. as in the order the keys have been inserted in dictionary. # Using OrderedDict so that output array can be easily return in the order itself. from collections import OrderedDict # OrderedDict comprehension where key is array index and value as difference to given number. data = OrderedDict((i, abs(array[i] - number)) for i in range(k)) maximum = max(data.values()) for i in range(k, n): # iterating over remaining elements of array diff = abs(array[i] - number) if diff < maximum: data.pop(max(data, key=data.get)) # get key of maximum value data[i] = diff maximum = max(data.values()) return [array[i] for i in data.keys()] if __name__ =="__main__": number = int(input("Enter the number to find closest numbers of: ")) k = int(input("Enter the number of closest numbers to return: ")) n = int(input('Number of elements in an array: ')) array = list(map(int,input("\nEnter space separated elements: ").strip().split()))[:n] # array = [22,15,13,11,9,8,4,2,1] print(closestNumbers(array, number, k))
aa3197fbbbe85ab50cbd541ea43f68ca296a6474
ValentynTroian/Python-Homework
/word_guessing_game.py
4,320
4.21875
4
''' Word guessing game. The game is over if user successfully guessed the word. User can exit the game, reload the word and give up. ''' from sys import exit from random import choice from os import path # Path to file which contains words FILE_PATH = path.join('C:', 'Users', 'Valentyn_Troian', 'Desktop', 'dict.txt') def read_file_and_choose_random_word(): '''This function read file and choose random word''' # File opening and choosing random line(=word for current file) from txt try: with open(FILE_PATH, 'r') as f: word = choice(f.readlines()) # Creating list from string and removing newline (last) symbol from the word letter_list = list(word[:-1]) except FileNotFoundError: print('Could not open file by location: ', FILE_PATH) exit(-1) return letter_list def create_alphabets(): '''This function creates alphabets''' # Creating alphabet list to check user's input alphabet = [] # Creating alphabet list to check if user have already chosen this letter remaining_alphabet = [] # Alphabets letters filling using the ASCII table, only English uppercase letters are using for letter in range(65, 91): alphabet.append(chr(letter)) remaining_alphabet.append(chr(letter)) return alphabet, remaining_alphabet def guess_process(letter_list, alphabet, remaining_alphabet): '''This function ...''' # Word guessed progress word_guessed = list('_' * len(letter_list)) # Initialization a variable of user's attempts. attempts_cnt = 1 print('Welcome to word guessing game! Please use only uppercase letter\n' 'Enter [RESTART] if you want to choose new word\n' 'Enter [EXIT] if you want to end the game\n' 'Enter [GIVE UP] if you want to stop the game and learn the guessed word\n') print(''.join(word_guessed)) # Game process while letter_list != word_guessed: # User's input user_input = input('Your choice:').upper() # Option to exit the game if user_input == 'EXIT': print('Bye!') exit(1) # Option to reload the word. All progress is resetting if user_input == 'RESTART': guess_process(letter_list, alphabet, remaining_alphabet) # Option to stop the game and learn the guessed word if user_input == 'GIVE UP': print('Better luck next time! You didn\'t guess the word:', ''.join(letter_list)) exit(2) # Check if user's input is valid if user_input in alphabet: # Check if user have already chosen this letter if user_input in remaining_alphabet: # Removing the used letter remaining_alphabet.remove(user_input) # Check if the word contains user's letter if user_input in letter_list: # Finding the position of guessed letters matches = [i for i, x in enumerate(letter_list) if x == user_input] # 'Opening' guessed letters for i in matches: word_guessed[i] = user_input # Printing the current word guessing progress print(''.join(word_guessed)) else: attempts_cnt += 1 print(''.join(word_guessed)) print(f'No luck, the letter {user_input} is not in this word.\ Please try again') else: print('You have already entered this letter. Please try another') else: print('Incorrect input. Please use only english symbols') else: print('Congratulations! The guessed word:', ''.join(letter_list), '\n' 'Count of your attempts:', attempts_cnt) return 0 def main(): '''This function starts main control flow''' letter_list = read_file_and_choose_random_word() alphabet, remaining_alphabet = create_alphabets() guess_process(letter_list, alphabet, remaining_alphabet) if __name__ == '__main__': main()
16a77feedf908077f3f74c74a00aa95765f46124
tombstoneghost/Python_Advance
/RandomNumbers.py
1,440
4.25
4
# Working with random numbers import random import secrets import numpy as np # Getting a Random Number a = random.random() print(a) # Specifying a Range a = random.uniform(1, 10) print(a) # Getting a Random Integer a = random.randint(1, 10) # This includes the upperbound where randrange() does not include the upperbound print(a) # Working with List my_list = list('ABCDEFGH') a = random.choice(my_list) # Used to pick a random choice from the list print(a) a = random.sample(my_list, 3) # Will pick 3 random elements print(a) random.shuffle(my_list) # Randomly Shuffle the list print(my_list) # To initialize a random number generator random.seed(10) print(random.random()) print(random.randint(1, 100)) # To work with passwords we need to use the secrets module a = secrets.randbelow(10) # This will produce a random integer between 0 and upperbound (upperbound not included) print(a) a = secrets.randbits(4) # This will return a random number with k random bits print(a) a = secrets.choice(my_list) # This will return a random choice which is not reproducible print(a) # Working with Arrays a = np.random.rand(3) # Returns an Array with 3 random elements print(a) a = np.random.randint(0, 10, (3, 4)) # A 3 X 4 Array with random integers in range (3, 4) print(a) ''' You can also shuffle the array using np.random.shuffle(arr). The Numpy's Random Number generator is not similar to the one in random module '''
b3f9556e68beb5f48135ca2ebb211ccdb7e4d280
sSeongJae91/python
/list.py
320
3.84375
4
x = [4,2,3,1] y = ["hello", "world!"] z = ["hello", 1, 2, 3] # print(x + y) # print(x[0]) #len num_elements = len(x) # print(num_elements) #sorted sort = sorted(x) # print(sort) #sum z = sum(x) # print(z) #list + loop # for n in x: # print(n) #list -> index print(y.index("hello")) #find print("hello" in y)
1347c374d065223dfd59abe3cf7b325172acd055
inauski/SistGestEmp
/Tareas/Act08-Listas/ejer06/ejer06.py
327
3.796875
4
from ejer02 import ListaMinusMayus lista = ["Beñat", "Xabi", "Xabi", "María", "Alexander", "Carlos", "Juan", "Imanol", "Pedro", "Uxue", "Javier", "Iker", "Carlos", "Xabi", "Alejandra", "Carolina", "Iñaki", "Asier", "Maria"] l = ListaMinusMayus(lista) l.modificaciones(input("Nombre a buscar: ")) print(lista)
8750601391095dc42ba27efea9569bb27ec993f8
lovehhf/LeetCode
/415_字符串相加.py
1,125
3.75
4
# -*- coding:utf-8 -*- __author__ = 'huanghf' """ 给定两个字符串形式的非负整数 num1 和num2 ,计算它们的和。 注意: num1 和num2 的长度都小于 5100. num1 和num2 都只包含数字 0-9. num1 和num2 都不包含任何前导零。 你不能使用任何內建 BigInteger 库, 也不能直接将输入的字符串转换为整数形式。 """ class Solution(object): def addStrings(self, num1, num2): """ 和第二题类似, 取长度大的用于循环能省很多麻烦 :type num1: str :type num2: str :rtype: str """ num1, num2 = num1[::-1], num2[::-1] m, n = len(num1), len(num2) res = '' carry = 0 for i in range(max(m, n)): n1 = ord(num1[i]) - ord('0') if i < m else 0 n2 = ord(num2[i]) - ord('0') if i < n else 0 s = n1 + n2 + carry carry, r = s // 10, s % 10 res = str(r) + res if carry: res = str(carry) + res return res num1 = "9999999" num2 = "99889" s = Solution() print(s.addStrings(num1, num2))
4bcb118d7678c090212c7771cbe810edba896317
yzl232/code_training
/mianJing111111/geeksforgeeks/bit/Count number of bits to be flipped to convert A to B.py
684
4.125
4
# encoding=utf-8 ''' Count number of bits to be flipped to convert A to B ''' class Solution: def cntBits(self, n): cnt = 0 while n: cnt+=n&1 n>>=1 return cnt def countFlip(self, a, b): return self.cntBits(a^b) ''' # Turn off the rightmost set bit class Solution: def cntBits(self, n): cnt=0 while n: n&=n-1 cnt+=1 return cnt def countFlip(self, a, b): return self.cntBits(a^b) Solution: 1. Calculate XOR of A and B. a_xor_b = A ^ B 2. Count the set bits in the above calculated XOR result. countSetBits(a_xor_b) '''
08ebc24ff841a21244ff4970f7fc7be9d3f042a6
KiselevAleksey/algorithmic_problems
/Square_of_2_rectangles.py
1,027
4.0625
4
""" Площадь прямоугольников. Вам даны координаты противоположных углов двух прямоугольников со сторонами, параллельными осям координат. Необходимо определить площадь пересечения этих прямоугольников. Формат вывода Выведите одно целое число, равное площади пересечения двух прямоугольников. Пример 1 Ввод 1 1 2 2 1 1 3 3 Вывод 1 """ def find_square (A:list, B:list): x11 = max(min(A[0],A[2]),min(B[0],B[2])) x12 = min(max(A[0],A[2]),max(B[0],B[2])) y11 = max(min(A[1],A[3]),min(B[1],B[3])) y12 = min(max(A[1],A[3]),max(B[1],B[3])) if (x12 - x11 > 0) and (y12 - y11 > 0): sq = (x12 - x11) * (y12 - y11) else: sq = 0 return sq print(find_square([int(i) for i in input().split()],[int(i) for i in input().split()]))
aec9b7c2357e6e98db30481d19e6a9a453406695
sakateka/atb
/src/course1/week4_divide_and_conquer/_4_number_of_inversions/inversions.py
674
3.59375
4
# Uses python3 import sys def merge(left, right, inv=0): ret = [] while left and right: if left[0] > right[0]: inv += len(left) ret.append(right.pop(0)) else: ret.append(left.pop(0)) ret.extend(left) ret.extend(right) return ret, inv def inversions(array): arr_len = len(array) if arr_len == 1: return array, 0 l1, inv1 = inversions(array[:arr_len//2]) l2, inv2 = inversions(array[arr_len//2:]) return merge(l1, l2, inv1+inv2) if __name__ == '__main__': input = sys.stdin.read() n, *a = list(map(int, input.split())) _, b = inversions(a) print(b)
af8ddae5bea25e450d3f41f7ac99cdd4b9221ff0
nkukarl/lintcode
/Q110 Minimum Path Sum.py
1,113
3.625
4
''' Thoughts: Dynamic programming Initialise dp to be a two-dimensional array whose size is the same as that of grid, let dp[0][0] = grid[0][0] For the first row and first column of dp, let dp[i][0] = dp[i - 1][0] + grid[i][0] and dp[0][j] = dp[0][j - 1] + grid[0][j] For i ranging from 1 to m and for j ranging from 1 to n, let dp[i][j] = min(dp[i - 1][j], dp[i][j - 1]) + grid[i][j] Return dp[-1][-1] ''' class Solution: def minPathSum(self, grid): # write your code here if not grid: return 0 m, n = len(grid), len(grid[0]) dp = [[0] * n for _ in range(m)] dp[0][0] = grid[0][0] for i in range(1, m): dp[i][0] = dp[i - 1][0] + grid[i][0] for j in range(1, n): dp[0][j] = dp[0][j - 1] + grid[0][j] for i in range(1, m): for j in range(1, n): dp[i][j] = min(dp[i - 1][j], dp[i][j - 1]) + grid[i][j] return dp[-1][-1] grid = [[1, 1, 2], [4, 7, 1], [3, 2, 5], [3, 6, 1]] inst = Solution() print(inst.minPathSum(grid))
dbde982f6a9f252795810681b11e1317257846af
KobrinIsTheBestCityInTheWorld/Python_labs
/task7.py
1,028
3.921875
4
import math import sys import argparse def leonardo(n): """Вычесляет число Леонардо Args: n -- номер числа, которое нужно вычеслить Return: n-ое число Леонардо """ if not isinstance(n, int): raise NameError('n must be int') if n < 0: raise ValueError('n must be positive') if n == 0 or n == 1: return 1 b = (1 + math.sqrt(5))/2 number = 2*(b**(n+1) - (1-b)**(n+1))/(b - (1-b)) - 1 return int(number) def main (): parser = argparse.ArgumentParser() parser.add_argument("-n", type=int) args = parser.parse_args() if args.n is not None: try: print(leonardo(args.n)) except: print("Error") print("One more time?") if input() in ["No","NO","no","nO","Нет","нет"]: sys.exit() while True: n = input("Enter the number: ") try: print(leonardo(int(n))) except: print("Error") print("One more time?") if input() in ["No","NO","no","nO","Нет","нет"]: break if __name__ == '__main__': main()
72077975d6aa0c73548df339c47d941a015400d1
silas-inegbe/AirBnB_clone-1
/tests/test_models/test_city.py
659
3.546875
4
#!/usr/bin/python3 """Test suite for the City class of the models.city module""" import unittest from models.base_model import BaseModel from models.city import City class TestCity(unittest.TestCase): """Test cases for the City class""" def setUp(self): self.city = City() self.attr_list = ["state_id", "name"] def test_city_is_a_subclass_of_basemodel(self): self.assertTrue(issubclass(type(self.city), BaseModel)) def test_attrs_are_class_attrs(self): for attr in self.attr_list: self.assertIs(type(getattr(self.city, attr)), str) self.assertFalse(bool(getattr(self.city, attr)))
b84ac97473ab23460f75b388553849095b4aad4d
nuSapb/basic-python
/Day2/error_handling/error_handling.py
210
3.671875
4
import datetime import random day = random.choice(['Eleventh', 11]) try: date = 'September ' + day except TypeError: date = datetime.date(2018, 9, day) else: day += '2018' finally: print(date)
58d01ac9c8c9e03448dd6b14acda49a9f00e1070
AdamRajoBenson/beginnerSET9
/divmod.py
98
3.515625
4
z,q,y=input().split() x=int(z) w=str(q) e=int(y) if(q=='/'): print(w//e) else: print(w%e)
8fc8ded2f598c11fb225012c563408a52ed71040
edu-athensoft/stem1401python_student
/py210110d_python3a/day09_210307/homework/stem1403a_hw_8_0228_zeyueli.py
614
4.1875
4
""" [Homework] 2021-02-28 Show and Hide a label in a window Due date: By the end of next Sat. """ from tkinter import * root = Tk() root.title("Python GUI - Homework") root.geometry("640x480+0+0") label1 = Label(root, text='Label 1', font=('Times', 25), bg="orange", fg='blue') label2 = Label(root, text='Label 2', font=('Times', 25), bg="orange", fg="red") label3 = Label(root, text='Label 3', font=('Times', 25), bg="orange", fg='yellow') label1.pack(side=LEFT) label2.pack(side=LEFT) label3.pack(side=LEFT) label1.after(2000, Pack.forget(label1)) label1.after(2000, label1.pack(side=LEFT)) root.mainloop()
e1af949fb26d93bebc0d0206c709a1e77c1248ab
elinanovo/chewbacca
/exam/task3.py
502
3.734375
4
print("Введите слово") a=input() while a!='': with open("Ozhegov2.txt", encoding="utf-8") as f: for line in f: slovo=line.split('|') if a== slovo[0]: print(slovo[0],'—',slovo[3],'—',slovo[1]) break a=input() #if a!==slovo[0]: #print("Ожегов такого слова не знает") #break print("Упс, вы ничего не ввели")