blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
3.06M
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
3.06M
febcd0ffccaaae5d6ca072db5433f7d3ff8fc96f
TheElementalOfDestruction/creatorUtils
/creatorUtils/forma.py
4,802
3.65625
4
""" Formatting package of creatorUtils. """ import os import hashlib import math import sys import time from creatorUtils.compat.types import * #Constants LITTLE = True # Marker for little endian BIG = False # Marker for big endian ##-------------------STRING-------------------## def divide(string, length): """ Divides a string into multiple substrings of equal length. If there is not enough for the last substring to be equal, it will simply use the rest of the string. Can also be used for things like lists and tuples. :param string: string to be divided. :param length: length of each division. :returns: list containing the divided strings. Example: >>>> a = divide('Hello World!', 2) >>>> print(a) ['He', 'll', 'o ', 'Wo', 'rl', 'd!'] """ return [string[length*x:length*(x+1)] for x in range(int(math.ceil(len(string)/length)))] def hexToStr(inp): """ Converts a hexadecimal stream into a string. Example: >>>> hexToStr('00002031') '\\x00\\x00 1' """ a = '' if math.floor(len(inp)/2.0) != len(inp)/2.0: inp = '0' + inp for x in range(len(inp)/2): a += chr(int(inp[x * 2:(x * 2) + 2], 16)) return a def numToChars(inp, end = BIG): a = hexToStr(numToHex(inp)) if end: a = a[::-1] return a def pad(inp, num, padding = '0'): if not isinstance(padding, stringType): raise TypeError('Padding must be a single character string') elif len(padding) != 1: raise ValueError('Padding must be a single character string') if isinstance(inp, str): inp = str(inp) if (num-len(inp)) <= 0: return inp return padding * (num - len(inp)) + inp ##-------------------NUMBER-------------------## if sys.version_info[0] < 3: def readNum(string, val, end = BIG): if len(string) != val: raise ValueError('String input must be {} bytes. Got {}'.format(val, len(string))) if end: a = bytearray(string[::-1]) else: a = bytearray(string) b = 0 for x in range(val): b = (b << 8) ^ a[x] return b else: def readNum(string, val, end = BIG): if not isinstance(string, bytes): raise TypeError('`string` MUST be an instance of bytes') if len(string) != val: raise ValueError('String input must be {} bytes. Got {}'.format(val, len(string))) if end: a = string[::-1] else: a = string b = 0 for x in range(val): b = (b << 8) ^ a[x] return b def readInt(string, end): a = '<' if end else '>' struct.unpack('{}I'.format(a), string) def readLong(string, end): a = '<' if end else '>' struct.unpack('{}Q'.format(a), string) def readShort(string, end): a = '<' if end else '>' struct.unpack('{}H'.format(a), string) ##-------------------HEXADECIMAL-------------------## def strToHex(s, encoding = None): if encoding: s = s.encode(encoding) return ''.join('{:02x}'.format(ord(c)) for c in s) def numToHex(inp): out = '{:x}'.format(inp) if len(out) % 2 != 0: out = '0' + out return out def toHex(inp, encoding = None): """ Converts many data types into a hexadecimal value. Value is not prepended with "0x", but it is prepended with a single "0" if the length is not a multiple of two. If encoding is specified, it will only be used if needed Input type matters as it determines what function will be used to convert it. The table bellow shows how the function is determined. + String: \tforma.strToHex + Unicode: \tforma.strToHex + Long: \tforma.numToHex + int: \tforma.numToHex """ if isinstance(inp, stringType): return strToHex(inp) if isinstance(inp, intlong): return numToHex(inp) raise TypeError('Input must be an integer, long, string, or unicode.') def msgEpoch(inp): ep = 116444736000000000 inp = ''.join(inp.split(' ')) inp2 = '' for x in range(len(inp)/2): inp2 = inp[2 * x: (2 * x) + 2] + inp2 print(inp2) inp = int(inp2, 16) return (inp - ep)/10000 ##-------------------HASHES-------------------## ## NOTE: These hash functions are provided as shorthands for getting ## the hex digest of a string. def md5(inp): return hashlib.md5(inp).hexdigest() def sha256(inp): return hashlib.sha256(inp).hexdigest() def sha1(inp): return hashlib.sha1(inp).hexdigest() def sha512(inp): return hashlib.sha512(inp).hexdigest() ##-------------------ENDIENNESS-------------------## def changeBitEndianness(inp): """ Switches the bit endienness of a single character. """ a = bin(ord(inp)) a = pad(a[2:], 8)[::-1] return chr(int(a, 2)) def changeByteEndianness(inp): """ Takes the input string and returns the reverse, effectively switching the endienness. """ return inp[::-1] changeBitEndian = changeBitEndianness changeByteEndian = changeByteEndianness
620350ad0044b57481be8073fba61c60acb8ebdd
Rhosid/PythonWars
/Projects/sumList.py
964
3.828125
4
""" Name: sumList.py Description: sums all the digits in the list Version: 1.0.0 Python: 3.3.5 """ __author__ = "Spencer Dockham" __date__ = "10/29/2014" # DEF def checkString(string): for ch in string: if ch not in numbet: return False return True def addString(string): total = 0 stringList = string.split(" ") for ct in range(0,len(stringList)): total = total + int(stringList[ct]) return total # LISTS numbet = ['0','1','2','3','4','5', '6','7','8','9',' '] # MAIN # sum list print("4sumList.py") string = input("Please Enter a string of numbers separated by spaces: ") while checkString(string) == False: print("Error.. found none number.") string = input("Please Enter a string of numbers separated by spaces: ") total = addString(string) print("Total of string: "+str(total)) # program concluded print("Done") # pause keeps the command window open pause = input("Press any key to end: ")
0be3b5597b8245be7571c59259a1aaec5bcafba6
fob413/TicTacToeApi
/app/main/utils/validation.py
869
3.9375
4
def board_is_present(board): """validate board exists""" if board: return True else: return False def validate_length(board): """validate length of the board""" if len(board) is 9: return True else: return False def validate_characters(board): """validate player and server characters""" allowed_characters = set('xo ') if set(board).issubset(allowed_characters): return True else: return False def validate_turn(board): """validate who's turn is next""" server_play = board.count('o') user_play = board.count('x') difference = user_play - server_play if difference is 0 or difference is 1: return True else: return False def board_is_valid(board): """validate board""" if (board_is_present(board) and validate_length(board) and validate_characters(board) and validate_turn(board)): return True else: return False
0f7c3ae3ca9f584cdeb424c04b1f6b2a9a8317d5
gitStudyToY/PythonStudy
/ name_cases.py
736
4.21875
4
message = "Eric" print("Hello " + message + ", would you like to learn some Python today?" ) print(message.title()) print(message.upper()) print(message.lower()) message = "Albert Einstein once said, 'A person who never made a mistake never tried anything new.'" print(message) famous_person = "Albert Einstein" famous_person_said = " once said, 'A person who never made a mistake never tried anything new.'" message = famous_person + famous_person_said print(message) message = " Eric " print(message.lstrip()) print(message.rstrip()) print(message.strip()) famous_person = "\t\nAlbert Einstein" famous_person_said = " once said, 'A person who never made a mistake never tried anything new.'" message = famous_person + famous_person_said print(message)
2d002aa39b0ef845d7044f52ecfec05ac0497429
dxab/SOWP
/ex2_11.py
342
3.84375
4
#Male and Female Percentages males = float(input('How many men are in your class?')) females = float(input('How many women are in your class?')) totalclass = males + females percentm = males / totalclass percentf = 1-percentm print(format(percentm, '.1%'), "of students are male in your class, and", format(percentf, '.1%'), "are female.")
aaf077c666e7c6d687e953d9b3e7d35596e7f430
dxab/SOWP
/ex2_9.py
427
4.5
4
#Write a program that converts Celsius temperatures to Fahrenheit temp. #The formula is as follows: f = 9 / 5 * C + 32 #This program should ask the user to enter a temp in Celsius and then #display the temp converted to Fahrenheit celsius = float(input('Please enter todays temperature (in celsius): ')) fahr = 9 / 5 * celsius + 32 print("Today's temperature in degrees fahrenheit is", format(fahr, '.0f'), 'degrees.')
c6e8a77fe5d0c2d061bcf1c7af24913ee304935f
davsingh/SI206
/madlibhw3.py
1,879
3.671875
4
# Using text2 from the nltk book corpa, create your own version of the # MadLib program. # Requirements: # 1) Only use the first 150 tokens # 2) Pick 5 parts of speech to prompt for, including nouns # 3) Replace nouns 15% of the time, everything else 10% # Deliverables: # 1) Print the orginal text (150 tokens) # 1) Print the new text print("START*******") import nltk # requires some downloading/installing dependencies to use all its features; numpy is especially tricky to install import random # import nltk nltk.download('book') from nltk.book import * from nltk import word_tokenize,sent_tokenize debug = False #True # get file from user to make mad lib out of if debug: print ("Getting information from file madlib_test.txt...\n") fname = "madlibtest2.txt" # need a file with this name in directory tok_lst = text2[:151] print (type(tok_lst)) tagmap = {"NN":"a noun","NNS":"a plural noun","VB":"a verb","JJ":"an adjective", "AV":"a adverb"} substitution_probabilities = {"NN":.15,"NNS":.1,"VB":.1,"JJ":.1, "AV": .10} def spaced(word): if word in [",", ".", "?", "!", ":"]: return word else: return " " + word print ("".join([spaced(word) for word in tok_lst])) final_words = [] tagged_tokens = nltk.pos_tag(tok_lst) for (word, tag) in tagged_tokens: if tag not in substitution_probabilities or random.random() > substitution_probabilities[tag]: final_words.append(spaced(word)) else: new_word = input("Please enter %s:\n" % (tagmap[tag])) final_words.append(spaced(new_word)) print ("".join(final_words)) print("\n\nEND*******") #print new #goal is to learn NLTK, learn about looping and Github ''' Questions: Where do I get text2? How do I call/incorporate it? What is a token? Are parts of speech built into NLTK? How do I do 15 percent of the time? (choose random number thru 100 and if it is 1-15 then yes?) Replace with what? '''
af0f2e3a6375ce20afcb04e0df1b971d679685f4
jocoder22/PythonDataScience
/OOP/try_except.py
1,348
3.765625
4
#!/usr/bin/env python from printdescribe import print2 class SalaryError(ValueError): pass class HourError(ValueError): _message = "Hours out of range!" def __init__(self): ValueError.__init__(self) def __str__(self): print(HourError._message) return HourError._message class Worker: _MAX_HOUR = 60 _MAX_SALARY = 150000 def __init__(self, name, wage = 15.53, hour = 8, bonus=1): self.name = name self.wage = wage if hour > Worker._MAX_HOUR: raise HourError() self.hour = hour self.bonus = bonus self._salary = 0 def salary_cal(self): _amount_sal = self.wage * self.hour * self.bonus if _amount_sal > Worker._MAX_SALARY: raise SalaryError("Salary out of range!") return _amount_sal @property def salary(self): self._salary = Worker.salary_cal(self) return self._salary def __repr__(self): return f"Worker('{self.name}', {self.wage}, {self.hour}, {self.bonus})" def __str__(self): strr = f""" Worker: Name: {self.name} Hourly wages: ${self.wage} Hours worked: {self.hour} Bonus earned: {self.bonus} Total salary: ${self.salary} """ return strr john = Worker("John Smith", 43.50, 50) jane = Worker("Jane Pretty", 196.00, 40) print2(jane, repr(jane))
5e24782f10d7f439c435626f5ff82b722a09101c
jocoder22/PythonDataScience
/NewPackages/mypackage/util.py
2,721
3.5625
4
from collections import Counter import matplotlib.pyplot as plt from sklearn.feature_extraction.text import CountVectorizer from nltk import word_tokenize from nltk.corpus import stopwords from nltk.stem.wordnet import WordNetLemmatizer import string def print2(*args): """ Function that print descriptive summary Input: DataFrame """ sp = {"sep":"\n\n", "end":"\n\n"} for memb in args: print(memb.head(), memb.info(), memb.describe(), **sp) def tokenize(text): """ This is a function to form tokens of text passages: Input: Text Output: List of words """ excludePunt = set(string.punctuation) excludePunt.update(('"', "'")) stopword = set(stopwords.words("english")) stopword.update(("said", "to", "th", "e", "cc", "subject", "http", "from", "new", "time", "times", "york", "sent", "ect", "u", "fwd", "w", "n", "s", "www", "com", "de", "one", "may", "home", "u", "la", "advertisement", "information", "service", "—", "year", "would")) wordlemm = WordNetLemmatizer() # form word tokens text2 = word_tokenize(text) # Retain alphabetic words: alpha_only alpha_only = [t.lower() for t in text2 if t.isalpha()] # Remove all punctuation words: wordtokens = [t for t in alpha_only if t not in stopword and t not in excludePunt] # Lemmatize all tokens into a new list: lemmatized lemmat = [wordlemm.lemmatize(t) for t in wordtokens] # return list of words return lemmat def countwordtokens(counters): """ Function to count number of words in a list Input: List of words Output: tuple of words and number of occurane """ # sum the counts return sum(counters, Counter()) def plotcount(countObject, n_common=6): """ Function to compute most common words Input: 1. countObject: tuple of words and number of occurance 2. n_common: int Output: Histogram """ # Get the most common n words topx = countObject.most_common(n_common) # Plot top n words plot_most_common(topx) return topx def plot_most_common(tops): """" Function to plot histogram of the most common words Input: words Output: Histogram """ # form dict from list of tuple top_items_dict = dict(tops) # create x range values xx = range(len(top_items_dict)) # create y values and y labels yvalues = list(top_items_dict.values()) ylab = list(top_items_dict.keys()) # plot bar chart plt.figure() plt.bar(xx, yvalues, align='center') plt.xticks(xx, ylab, rotation='vertical') plt.tight_layout() plt.show()
bb2c7002901bab1dbf1280e4572663fb0a07ec3e
jocoder22/PythonDataScience
/OOP/operators.py
1,089
3.515625
4
#!/usr/bin/env python from printdescribe import print2 class Patients: def __init__(self, name, id, gender): self.name = name self.id = id self.gender = gender def __eq__(self, other): return self.name == other.name and self.id == other.id\ and type(self) == type(other) # return self.name == other.name and self.id == other.id\ # and isinstance(other, Patients) class Staff: def __init__(self, name, id, gender): self.name = name self.id = id self.gender = gender def __eq__(self, other): return self.name == other.name and self.id == other.id\ and isinstance(other, Staff) patient1 = Patients("Charles", 459234, "Male") patient2 = Patients("Charles", 876323, "Male") patient3 = Patients("Marylene", 459234, "Female") patient4 = Patients("Charles", 459234, "Male") patient5 = Staff("Charles", 459234, "Male") print2(patient1 == patient2, patient3 == patient1, patient1 == patient4) print2("$"*20) print2(patient1 == patient5, patient5 == patient1)
b09564d1645c3fd85fe53ca794e2d20a31a253bf
jocoder22/PythonDataScience
/importingData/localData/jsonfile.py
562
3.671875
4
#!/usr/bin/env python import json def print2(*args): for arg in args: print(arg, end='\n\n') params = {"sep":"\n\n", "end":"\n\n"} with open('myfile.json', 'r') as json_file: jsonData = json.load(json_file) type(jsonData) ## dict for key, value in jsonData.items(): print(f'{key} : {value}', **params) # Load JSON: json_data with open("a_movie.json") as json_file: json_data = json.load(json_file) # Print each key-value pair in json_data for k in json_data.keys(): print(k + ': ', json_data[k], **params)
f5e52e4e521318372d7cc14698bf3e07fa10d440
jocoder22/PythonDataScience
/functions.py/decorator3.py
1,036
4.03125
4
#!/usr/bin/env python import os from functools import wraps def print2(*args): for arg in args: print(arg, end='\n\n') sp = {"sep": "\n\n", "end": "\n\n"} def mycounter(func): """ """ @wraps(func) def mywrapper(*args, **kwargs): result = func(*args, **kwargs) mywrapper.count += 1 print(f'The square of {(args, kwargs)} is {result}') return result mywrapper.count = 0 return mywrapper @mycounter def square(n=1): """This return the square of a number Args: int The number to find the square Returns: int """ print(f'Called {square.__name__} function with {n} argument!') return n ** 2 # square(5) # square(4) print(f'Called {square.__name__} function {square.count} times') print(square.__doc__, square.__defaults__, square.__wrapped__, sep=sp, end=sp) # Accessing the original undecorated function using originalfunction.__wrapped__ print(square.__wrapped__(6), end=sp) print(square.__wrapped__.__doc__, end=sp)
72930c1545845fb65cdbccf0c0d5dd75b4bada43
jocoder22/PythonDataScience
/computational_finance/cva.py
6,541
3.734375
4
#!/usr/bin/env python import os import sys import numpy as np import pandas as pd import matplotlib.pyplot as plt import random import progressbar, tqdm from scipy.stats import norm def print2(*args): for arg in args: print(arg, sep="\n\n", end="\n\n") # 1. Write a function which takes a risk-free rate, the initial share price, the share volatility, # and term as inputs, and determines the terminal value of a share price, # assuming geometric Brownian Motion. Note, you should vectorize this function where possible. def terminalValue(present_price, risk_free, sigma, Z, T): """ terminalValue function gives the terminal value of a share price, assuming geometric Brownian Motion and vectorization where possible. Inputs: present_price(float/int): initial share price riskfree(float/int): risk free rate sigma: share volatility Z: normal random variables T(float/int): term of share price Output: terminal value of a share price """ return present_price*np.exp((risk_free - sigma**2/2)*T + sigma*np.sqrt(T)*Z) def callpayoff(terminalval, strikeprice): """The callpayoff function Args: terminalval (float/int): initial share price strikeprice (float/int): : strike price Returns: payoff (float/int) """ return np.maximum(terminalval - strikeprice, 0) def discounted_call_payoff(S_T, K, risk_free_rate, L, T): '''The discounted_call_payoff calculate discounted payoff Args: S_T (float/int): intial stock price K (float/int): strike price risk_free_rate (float): risk free rate L (float/int) : up-and-out barrier T (int) : term Returns: P (float/int):discount option prices ''' if (S_T > L): return 0 return np.maximum(S_T-K, 0) def black_schole_callprice(S, K, T, rf, sigma): """The black_schole_callprice function calculates the call option price under Black Schole Merton model Args: S: current stock price K: strike price T: maturity date in years rf: risk-free rate (continusouly compounded) sigma: volatiity of underlying security Returns: callprice: call price """ current_time = 0 d1_numerator = np.log(S/K) + (r + sigma**2/2) * (T - current_time) d1_denominator = sigma * np.sqrt(T - current_time) d1 = d1_numerator / d1_denominator d2 = d1 - d1_denominator callprice = S*norm.cdf(d1) - (norm.cdf(d2)*K*np.exp(-r * (T - current_time))) return callprice np.random.seed(0) # market information r= 0.1 # Risk-free rate # share specific information s0= 100 # Today's stock price sigma= 0.3 # Annualized volatility # call option specific information K= 110 # Strike/Exercise price T= 1 # Maturity (in years) # firm specific information v0 = 200 # firm current value sigma_firm = 0.25 # firm volatility debt = 180 # firm debt recovery_rate = 0.2 # recovery rate corr_t = np.linspace(-1 ,1,21) cva_est = np.zeros(len(corr_t)) cva_std = np.zeros(len(corr_t)) callval_est = np.zeros(len(corr_t)) callval_std = np.zeros(len(corr_t)) callcva_est = np.zeros(len(corr_t)) # callcva_std = np.zeros(len(corr_t)) center2 = 0 bar = progressbar.ProgressBar(maxval=200, widgets=[progressbar.Bar("=", "[", "]"), " ", progressbar.Percentage()]) bar.start() # for i in range(1,200): # center2+=1 # bar.update(center2) # bar.finish() numb = 50000 for i in range(len(corr_t)): correlation = corr_t[i] if (correlation == 1 or correlation == -1 ): norm_vec_0 = norm.rvs(size = numb) norm_vec_1 = correlation * norm_vec_0 corr_norm_matrix = np.array([norm_vec_0, norm_vec_1]) else: corr_matrix = np.array([[1, correlation], [correlation, 1]]) norm_matrix = norm.rvs(size = np.array([2, numb])) corr_norm_matrix = np.matmul(np.linalg.cholesky(corr_matrix), norm_matrix) tem_stock_value = terminalValue(s0, r, sigma, corr_norm_matrix[0,], T) call_val = callpayoff(tem_stock_value, K) callval_est[i] = np.mean(call_val) callval_std[i] = np.std(call_val)/np.sqrt(numb) # firm evolution term_firm_value = terminalValue(v0, r, sigma_firm, corr_norm_matrix[1,],T) amount_lost = np.exp(-r*T)*(1 - recovery_rate)*(term_firm_value < debt)*call_val # cva estimation cva_est[i] = np.mean(amount_lost) cva_std[i] = np.std(amount_lost)/np.sqrt(numb) # calculate option value with cva callcva_est[i] = callval_est[i] - cva_est[i] # callcva_std[i] = np.sqrt(callval_est[i]**2 + cva_est[i]**2 - 2*np.matmul(corr_norm_matrix,callval_est[i],cva_std[i])) center2+=1 bar.update(center2) bar.finish() # calculate firm default probability d1_numerator = np.log(v0/debt) + (r + sigma_firm**2/2) * T d1_denominator = sigma_firm * np.sqrt(T) d1 = d1_numerator / d1_denominator d2 = d1 - d1_denominator firm_default_prob = norm.cdf(-d2) # calculate analytic vanilla European call option price analytic_callprice = black_schole_callprice(s0,K,T, r, sigma) # calculate uncorrelated credit valuation adjustment (cva) uncor_cva = (1 - recovery_rate)*firm_default_prob*analytic_callprice # plot monte carlo cva estimates for different correlations plt.plot(corr_t,[uncor_cva]*21) plt.plot(corr_t, cva_est, ".") plt.plot(corr_t, cva_est+3*np.array(cva_std), "black") plt.plot(corr_t, cva_est-3*np.array(cva_std), "g") plt.title("Monte carlo Credit Valuation Adjustments estimates for different correlations") plt.xlabel("Correlation") plt.ylabel("CVA") plt.show() corr_t plt.figure(figsize=[12,8]) plt.plot(corr_t,callval_est, '.') plt.plot(corr_t, callcva_est,'-') plt.plot(corr_t,callval_est+3*np.array(callval_std),'black') plt.plot(corr_t,callval_est-3*np.array(callval_std),'g') # plt.plot(corr_t,callval_est+3*np.array(callcva_std),'black') # plt.plot(corr_t,callval_est-3*np.array(callcva_std),'g') plt.xlabel("Months") plt.ylabel("Price") plt.title("Monte Carlo Estimates of risk-adjusted call option price") plt.legend(('Risk-neutral price', 'Risk-adjusted price', 'Risk-neutral price UB', 'Risk-neutral price LB')) plt.show() print2(cva_est, cva_std, firm_default_prob) url = "https://view98n6mw6nlkh.udacity-student-workspaces.com/edit/data/portfolio.json" portfolio = pd.read_json(url, orient='records', lines=True)
d23baf8c78e7feb95ea7c95b2e919f8c1959e339
jocoder22/PythonDataScience
/importingData/relationalDB/sqlalchemy/connecting.py
981
3.546875
4
#!/usr/bin/env python # Import necessary module import os from sqlalchemy import create_engine, MetaData, Table, select print(engine.table_names()) # ['Person', 'Site', 'Survey', 'Visited'] """ survey = Table('Survey', metadata, autoload=True, autoload_with=engine) ssmt = select([survey]) print(ssmt) results = connection.execute(ssmt).fetchall() print(results) print(results[0]) print(results[0].keys()) # Get the first row of the results by using an index: first_row first_row = results[0] # Print the first row of the results print(first_row) # Print the first column of the first row by using an index print(first_row[0]) # Print the 'family' column of the first row by using its name print(first_row['quant']) # Add a where clause to filter the results to only those for lake ssmt = ssmt.where(survey.columns.person == 'lake') # Execute the query to retrieve all the data returned: results results = connection.execute(ssmt).fetchall() print(results) """
50282feebd1d39828b1c619b6db0839103161941
jocoder22/PythonDataScience
/pandas/datamgt/stringManipulation.py
723
3.53125
4
from pandas import DataFrame import re, string from datetime import datetime eassy = """This is the begining of time. But with all good and noble intention comes failure, only work hard as you and others can and expect the best. Be careful while going slowly on a journey of life.""" print(eassy.upper()) print(eassy.lower()) eassy_split = eassy.lower().split(" ") eassy_split[:10] "_".join(eassy[:10]) "_".join(eassy_split[:10]) string.punctuation all_join = "".join(c for c in eassy.lower() if c not in string.punctuation) all_join all_join.strip() eassy_split.strip() # Replace all double spaaces Nospace = re.sub('\s+', ' ', all_join) Nospace22 = Nospace.split() Nospace22[:10]
55198f51c0659fa110caa69f069dace6c8f41ffb
jocoder22/PythonDataScience
/DataFrameManipulation/indexing.py
974
3.96875
4
# Import pandas import matplotlib.pyplot as plt import pandas as pd # Reindex weather1 using the list year: weather2 weather2 = weather1.reindex(year) # Print weather2 print(weather2) # Reindex weather1 using the list year with forward-fill: weather3 weather3 = weather1.reindex(year).ffill() # Print weather3 print(weather3) # Reindex names_1981 with index of names_1881: common_names common_names = names_1981.reindex(names_1881.index) # Print shape of common_names print(common_names.shape) # Drop rows with null counts: common_names common_names = common_names.dropna() # Print shape of new common_names print(common_names.shape) # Import pandas # Reindex names_1981 with index of names_1881: common_names common_names = names_1981.reindex(names_1881.index) # Print shape of common_names print(common_names.shape) # Drop rows with null counts: common_names common_names = common_names.dropna() # Print shape of new common_names print(common_names.shape)
6ce847483d6be92cf458476bf21cb51c7542483d
jocoder22/PythonDataScience
/importingData/relationalDB/sqlalchemyQuery.py
25,650
3.578125
4
# #####################creating database from sklearn import preprocessing import pandas as pd from PIL import Image import seaborn as sns import matplotlib.pyplot as plt import matplotlib from sqlalchemy import Table, Column, String, Integer, Float, Boolean import os path = 'D:\PythonDataScience\importingData\webData' os.chdir(path) # Create engine: engine engine = create_engine('sqlite:///survey.db') connection = engine.connect() metadata = MetaData() # Define a new table with a name, count, amount, and valid column: data data = Table('data', metadata, Column('name', String(255)), Column('count', Integer()), Column('amount', Float()), Column('valid', Boolean()) ) # Use the metadata to create the table metadata.create_all(engine) # Print table details print(repr(data)) # Define a new table with a name, count, amount, and valid column: data data = Table('data', metadata, Column('name', String(255), unique=True), Column('count', Integer(), default=1), Column('amount', Float()), Column('valid', Boolean(), default=False) ) # Use the metadata to create the table metadata.create_all(engine) # Print the table details print(repr(metadata.tables['data'])) ############### inserting dataset # Import insert and select from sqlalchemy from sqlalchemy import select, insert # Build an insert statement to insert a record into the data table: stmt stmt=insert(data).values(name='Anna', count=1, amount=1000.00, valid=True) # Execute the statement via the connection: results results=connection.execute(stmt) # Print result rowcount print(results.rowcount) # Build a select statement to validate the insert stmt=select([data]).where(data.columns.name == 'Anna') # Print the result of executing the query. print(connection.execute(stmt).first()) # Build a list of dictionaries: values_list values_list = [ {'name': 'Anna', 'count': 1, 'amount': 1000.00, 'valid': True}, {'name': 'Taylor', 'count': 1, 'amount': 750.00, 'valid': False} ] # Build an insert statement for the data table: stmt stmt = insert(data) # Execute stmt with the values_list: results results = connection.execute(stmt, values_list) # Print rowcount print(results.rowcount) # Create an empty list and zeroed row count: values_list, total_rowcount values_list = [] total_rowcount = 0 # Enumerate the rows of csv_reader for idx, row in enumerate(csv_reader): #create data and append to values_list data = {'state': row[0], 'sex': row[1], 'age': row[2], 'pop2000': row[3], 'pop2008': row[4]} values_list.append(data) # Check to see if divisible by 51 if idx % 51 == 0: results = connection.execute(stmt, values_list) total_rowcount += results.rowcount values_list = [] # Print total rowcount print(total_rowcount) # Build a select statement: select_stmt select_stmt = select([state_fact]).where(state_fact.columns.name == 'New York') # Print the results of executing the select_stmt print(connection.execute(select_stmt).fetchall()) # Build a statement to update the fips_state to 36: stmt stmt = update(state_fact).values(fips_state = 36) # Append a where clause to limit it to records for New York state stmt = stmt.where(state_fact.columns.name == 'New York') # Execute the statement: results results = connection.execute(stmt) # Print rowcount print(results.rowcount) # Execute the select_stmt again to view the changes print(connection.execute(select_stmt).fetchall()) # Build a statement to update the notes to 'The Wild West': stmt stmt=update(state_fact).values(notes='The Wild West') # Append a where clause to match the West census region records stmt=stmt.where(state_fact.columns.census_region_name == 'West') # Execute the statement: results results=connection.execute(stmt) # Print rowcount print(results.rowcount) # Build a statement to select name from state_fact: stmt fips_stmt = select([state_fact.columns.name]) # Append a where clause to Match the fips_state to flat_census fips_code fips_stmt = fips_stmt.where( state_fact.columns.fips_state == flat_census.columns.fips_code) # Build an update statement to set the name to fips_stmt: update_stmt update_stmt = update(flat_census).values(state_name=fips_stmt) # Execute update_stmt: results results = connection.execute(update_stmt) # Print rowcount print(results.rowcount) ########################## Deletig a table # Import delete, select from sqlalchemy import select, delete # Build a statement to empty the census table: stmt stmt = delete(census) # Execute the statement: results results = connection.execute(stmt) # Print affected rowcount print(results.rowcount) # Build a statement to select all records from the census table stmt = select([census]) # Print the results of executing the statement to verify there are no rows print(connection.execute(stmt).fetchall()) # Build a statement to count records using the sex column for Men ('M') age 36: stmt stmt = select([func.count(census.columns.sex)]).where( and_(census.columns.sex == 'M', census.columns.age == 36) ) # Execute the select statement and use the scalar() fetch method to save the record count to_delete = connection.execute(stmt).scalar() # Build a statement to delete records from the census table: stmt_del stmt_del = delete(census) # Append a where clause to target Men ('M') age 36 stmt_del = stmt_del.where( and_(census.columns.sex == 'M', census.columns.age == 36) ) # Execute the statement: results results = connection.execute(stmt_del) # Drop the state_fact tables state_fact.drop(engine) # Check to see if state_fact exists print(state_fact.exists(engine)) # Drop all tables metadata.drop_all(engine) # Check to see if census exists print(census.exists(engine)) # final project # Import create_engine, MetaData from sqlalchemy import create_engine, MetaData # Define an engine to connect to chapter5.sqlite: engine engine = create_engine('sqlite:///chapter5.sqlite') # Initialize MetaData: metadata metadata = MetaData() from sqlalchemy import Table, Column, String, Integer # Build a census table: census census = Table('census', metadata, Column('state', String(30)), Column('sex', String(1)), Column('age', Integer()), Column('pop2000', Integer()), Column('pop2008', Integer())) # Create the table in the database metadata.create_all(engine) values_list = [] import csv csv_reader = csv.reader(csvfile) # Iterate over the rows for row in csv_reader: # Create a dictionary with the values data = {'state': row[0], 'sex': row[1], 'age':row[2], 'pop2000': row[3], 'pop2008': row[4]} # Append the dictionary to the values list values_list.append(data) from sqlalchemy import insert # Build insert statement: stmt stmt = insert(census) # Use values_list to insert data: results results = connection.execute(stmt, values_list) # Print rowcount print(results.rowcount) from sqlalchemy import select # Calculate weighted average age: stmt stmt = select([census.columns.sex, (func.sum(census.columns.pop2008 * census.columns.age) / func.sum(census.columns.pop2008)).label('average_age') ]) # Group by sex stmt = stmt.group_by(census.columns.sex) # Execute the query and store the results: results results = connection.execute(stmt).fetchall() # Print the average age by sex for result in results: print(result.sex, result.average_age) # import case, cast and Float from sqlalchemy from sqlalchemy import case, cast, Float # Build a query to calculate the percentage of females in 2000: stmt stmt = select([census.columns.state, (func.sum( case([ (census.columns.sex == 'F', census.columns.pop2000) ], else_=0)) / cast(func.sum(census.columns.pop2000), Float) * 100).label('percent_female') ]) # Group By state stmt = stmt.group_by(census.columns.state) # Execute the query and store the results: results results = connection.execute(stmt).fetchall() # Print the percentage for result in results: print(result.state, result.percent_female) # Build query to return state name and population difference from 2008 to 2000 stmt = select([census.columns.state, (census.columns.pop2008 - census.columns.pop2000).label('pop_change') ]) # Group by State stmt = stmt.group_by(census.columns.state) # Order by Population Change stmt = stmt.order_by(desc('pop_change')) # Limit to top 10 stmt = stmt.limit(10) # Use connection to execute the statement and fetch all results results = connection.execute(stmt).fetchall() # Print the state and population change for each record for result in results: print('{}:{}'.format(result.state, result.pop_change)) #################### ploting # Import matplotlib.pyplot # Set the style to 'ggplot' plt.style.use('ggplot') # Create a figure with 2x2 subplot layout plt.subplot(2, 2, 1) # Plot the enrollment % of women in the Physical Sciences plt.plot(year, physical_sciences, color='blue') plt.title('Physical Sciences') # Plot the enrollment % of women in Computer Science plt.subplot(2, 2, 2) plt.plot(year, computer_science, color='red') plt.title('Computer Science') # Add annotation cs_max = computer_science.max() yr_max = year[computer_science.argmax()] plt.annotate('Maximum', xy=(yr_max, cs_max), xytext=( yr_max-1, cs_max-10), arrowprops=dict(facecolor='black')) # Plot the enrollmment % of women in Health professions plt.subplot(2, 2, 3) plt.plot(year, health, color='green') plt.title('Health Professions') # Plot the enrollment % of women in Education plt.subplot(2, 2, 4) plt.plot(year, education, color='yellow') plt.title('Education') # Improve spacing between subplots and display them plt.tight_layout() plt.show() plt.plot(year, computer_science, color='red', label='Computer Science') plt.plot(year, physical_sciences, color='blue', label='Physical Sciences') plt.legend(loc='lower right') # Compute the maximum enrollment of women in Computer Science: cs_max cs_max = computer_science.max() # Calculate the year in which there was maximum enrollment of women in Computer Science: yr_max yr_max = year[computer_science.argmax()] # Add a black arrow annotation plt.annotate('Maximum', xy=(yr_max, cs_max), xytext=( yr_max+5, cs_max+5), arrowprops=dict(facecolor='black')) # Add axis labels and title plt.xlabel('Year') plt.ylabel('Enrollment (%)') plt.title('Undergraduate enrollment of women') plt.show() plt.pcolor(A, cmap='Blues') plt.colorbar() plt.show() # Generate a 2-D histogram plt.hist2d(hp, mpg, bins=(20, 20), range=((40, 235), (8, 48))) # Add a color bar to the histogram plt.colorbar() # Add labels, title, and display the plot plt.xlabel('Horse power [hp]') plt.ylabel('Miles per gallon [mpg]') plt.title('hist2d() plot') plt.show() plt.hexbin(hp, mpg, gridsize=(15, 12), extent=(40, 235, 8, 48)) # Add a color bar to the histogram plt.colorbar() # Add labels, title, and display the plot plt.xlabel('Horse power [hp]') plt.ylabel('Miles per gallon [mpg]') plt.title('hexbin() plot') plt.show() # Load the image into an array: img img = plt.imread('480px-Astronaut-EVA.jpg') # Print the shape of the image print(img.shape) # Compute the sum of the red, green and blue channels: intensity intensity = img.sum(axis=2) # Print the shape of the intensity print(intensity.shape) # Display the intensity with a colormap of 'gray' plt.imshow(intensity, cmap='gray') # Add a colorbar plt.colorbar() # Hide the axes and show the figure plt.axis('off') plt.show() # Load the image into an array: img img = plt.imread('480px-Astronaut-EVA.jpg') # Specify the extent and aspect ratio of the top left subplot plt.subplot(2, 2, 1) plt.title('extent=(-1,1,-1,1),\naspect=0.5') plt.xticks([-1, 0, 1]) plt.yticks([-1, 0, 1]) plt.imshow(img, extent=(-1, 1, -1, 1), aspect=0.5) # Specify the extent and aspect ratio of the top right subplot plt.subplot(2, 2, 2) plt.title('extent=(-1,1,-1,1),\naspect=1') plt.xticks([-1, 0, 1]) plt.yticks([-1, 0, 1]) plt.imshow(img, extent=(-1, 1, -1, 1), aspect=1) # Specify the extent and aspect ratio of the bottom left subplot plt.subplot(2, 2, 3) plt.title('extent=(-1,1,-1,1),\naspect=2') plt.xticks([-1, 0, 1]) plt.yticks([-1, 0, 1]) plt.imshow(img, extent=(-1, 1, -1, 1), aspect=2) # Specify the extent and aspect ratio of the bottom right subplot plt.subplot(2, 2, 4) plt.title('extent=(-2,2,-1,1),\naspect=2') plt.xticks([-2, -1, 0, 1, 2]) plt.yticks([-1, 0, 1]) plt.imshow(img, extent=(-2, 2, -1, 1), aspect=2) # Improve spacing and display the figure plt.tight_layout() plt.show() # Load the image into an array: image image = plt.imread('640px-Unequalized_Hawkes_Bay_NZ.jpg') # Extract minimum and maximum values from the image: pmin, pmax pmin, pmax = image.min(), image.max() print("The smallest & largest pixel intensities are %d & %d." % (pmin, pmax)) # Rescale the pixels: rescaled_image rescaled_image = 256*(image-pmin) / (pmax-pmin) print("The rescaled smallest & largest pixel intensities are %.1f & %.1f." % (rescaled_image.min(), rescaled_image.max())) # Display the original image in the top subplot plt.subplot(2, 1, 1) plt.title('original image') plt.axis('off') plt.imshow(image) # Display the rescaled image in the bottom subplot plt.subplot(2, 1, 2) plt.title('rescaled image') plt.axis('off') plt.imshow(rescaled_image) plt.show() # Import plotting modules # Plot a linear regression between 'weight' and 'hp' sns.lmplot(x='weight', y='hp', data=auto) # Display the plot plt.show() # Generate a green residual plot of the regression between 'hp' and 'mpg' sns.residplot(x='hp', y='mpg', data=auto, color='green') # Display the plot plt.show() # Generate a scatter plot of 'weight' and 'mpg' using red circles plt.scatter(auto['weight'], auto['mpg'], label='data', color='red', marker='o') # Plot in blue a linear regression of order 1 between 'weight' and 'mpg' sns.regplot(x='weight', y='mpg', data=auto, scatter=None, color='blue', label='order 1') # Plot in green a linear regression of order 2 between 'weight' and 'mpg' sns.regplot(x='weight', y='mpg', data=auto, scatter=None, order=2, color='green', label='order 2') # Add a legend and display the plot plt.legend(loc='upper right') plt.show() # Plot a linear regression between 'weight' and 'hp', with a hue of 'origin' and palette of 'Set1' sns.lmplot(x='weight', y='mpg', data=auto, palette='Set1', hue='origin') # Display the plot plt.show() # Plot a linear regression between 'weight' and 'hp', with a hue of 'origin' and palette of 'Set1' sns.lmplot(x='weight', y='hp', data=auto, palette='Set1', hue='origin') # Display the plot plt.show() # Plot linear regressions between 'weight' and 'hp' grouped row-wise by 'origin' sns.lmplot(x='weight', y='hp', data=auto, palette='Set1', row='origin') # Display the plot plt.show() # Make a strip plot of 'hp' grouped by 'cyl' plt.subplot(2, 1, 1) sns.stripplot(x='cyl', y='hp', data=auto) # Make a strip plot of 'hp' grouped by 'cyl' plt.subplot(2, 1, 1) sns.stripplot(x='cyl', y='hp', data=auto) # Make the strip plot again using jitter and a smaller point size plt.subplot(2, 1, 2) sns.stripplot(x='cyl', y='hp', data=auto, size=3, jitter=True) # Display the plot plt.show() # Generate a swarm plot of 'hp' grouped horizontally by 'cyl' plt.subplot(2, 1, 1) sns.swarmplot(x='cyl', y='hp', data=auto) # Generate a swarm plot of 'hp' grouped vertically by 'cyl' with a hue of 'origin' plt.subplot(2, 1, 2) sns.swarmplot(x='hp', y='cyl', data=auto, hue='origin', orient='h') # Display the plot plt.show() # Generate a violin plot of 'hp' grouped horizontally by 'cyl' plt.subplot(2, 1,1) sns.violinplot(x='cyl', y='hp', data=auto) # Generate the same violin plot again with a color of 'lightgray' and without inner annotations plt.subplot(2, 1, 2) sns.violinplot(x='cyl', y='hp', data=auto, color='lightgray', inner=None) # Overlay a strip plot on the violin plot sns.stripplot(x='cyl', y='hp', data=auto, size=1.5, jitter=True) # Display the plot plt.show() # Generate a joint plot of 'hp' and 'mpg' sns.jointplot(x='hp', y='mpg', data=auto) # Display the plot plt.show() # Generate a joint plot of 'hp' and 'mpg' using a hexbin plot sns.jointplot(x='hp', y='mpg', data=auto, kind='hex') # kind = 'scatter' uses a scatter plot of the data points # kind = 'reg' uses a regression plot(default order 1) # kind = 'resid' uses a residual plot # kind = 'kde' uses a kernel density estimate of the joint distribution # kind = 'hex' uses a hexbin plot of the joint distribution # Display the plot plt.show() # Print the first 5 rows of the DataFrame print(auto.head()) # Plot the pairwise joint distributions from the DataFrame sns.pairplot(auto) # Display the plot plt.show() # Print the first 5 rows of the DataFrame print(auto.head()) # Plot the pairwise joint distributions grouped by 'origin' along with regression lines sns.pairplot(auto, kind='reg', hue='origin') # Display the plot plt.show() # Print the covariance matrix print(cov_matrix) # Visualize the covariance matrix using a heatmap sns.heatmap(cov_matrix) # Display the heatmap plt.show() ################### Time Series # Import matplotlib.pyplot # Plot the aapl time series in blue plt.plot(aapl, color='blue', label='AAPL') # Plot the ibm time series in green plt.plot(ibm, color='green', label='IBM') # Plot the csco time series in red plt.plot(csco, color='red', label='CSCO') # Plot the msft time series in magenta plt.plot(msft, color='magenta', label='MSFT') # Add a legend in the top left corner of the plot plt.legend(loc='upper left') # Specify the orientation of the xticks plt.xticks(rotation=60) # Display the plot plt.show() # Plot the series in the top subplot in blue plt.subplot(2, 1, 1) plt.xticks(rotation=45) plt.title('AAPL: 2001 to 2011') plt.plot(aapl, color='blue') # Slice aapl from '2007' to '2008' inclusive: view view = aapl['2007':'2008'] # Plot the sliced data in the bottom subplot in black plt.subplot(2, 1, 2) plt.xticks(rotation=45) plt.title('AAPL: 2007 to 2008') plt.plot(view, color='black') plt.tight_layout() plt.show() # Slice aapl from Nov. 2007 to Apr. 2008 inclusive: view view = aapl['2007-11':'2008-04'] # Plot the sliced series in the top subplot in red plt.subplot(2, 1, 1) plt.xticks(rotation=45) plt.title('AAPL: Nov. 2007 to Apr. 2008') plt.plot(view, color='red', label='AAPL') # Reassign the series by slicing the month January 2008 view = aapl['2008-01'] # Plot the sliced series in the bottom subplot in green plt.subplot(2, 1, 2) plt.xticks(rotation=45) plt.title('AAPL: Jan. 2008') plt.plot(view, color='green', label='AAPL') # Improve spacing and display the plot plt.tight_layout() plt.show() ############### Plotting an inset view # Slice aapl from Nov. 2007 to Apr. 2008 inclusive: view view = aapl['2007-11':'2008-04'] # Plot the entire series # plt.subplot(2,1,1) plt.xticks(rotation=45) plt.title('AAPL: 2001-2011') plt.plot(aapl) # Specify the axes # plt.subplot(2,1,2) plt.axes([0.25, 0.5, 0.35, 0.35]) # Plot the sliced series in red using the current axes plt.plot(view, color='red') plt.xticks(rotation=45) plt.title('2007/11-2008/04') plt.show() # Plot the 30-day moving average in the top left subplot in green plt.subplot(2, 2,1) plt.plot(mean_30, 'green') plt.plot(aapl, 'k-.') plt.xticks(rotation=60) plt.title('30d averages') # Plot the 75-day moving average in the top right subplot in red plt.subplot(2, 2, 2) plt.plot(mean_75, 'red') plt.plot(aapl, 'k-.') plt.xticks(rotation=60) plt.title('75d averages') # Plot the 125-day moving average in the bottom left subplot in magenta plt.subplot(2, 2, 3) plt.plot(mean_125, 'magenta') plt.plot(aapl, 'k-.') plt.xticks(rotation=60) plt.title('125d averages') # Plot the 250-day moving average in the bottom right subplot in cyan plt.subplot(2, 2, 4) plt.plot(mean_250, 'cyan') plt.plot(aapl, 'k-.') plt.xticks(rotation=60) plt.title('250d averages') ###################### histogram equalization of images # Load the image into an array: image image = plt.imread('640px-Unequalized_Hawkes_Bay_NZ.jpg') # Display image in top subplot using color map 'gray' plt.subplot(2, 1, 1) plt.title('Original image') plt.axis('off') plt.imshow(image, cmap='gray') # Flatten the image into 1 dimension: pixels pixels = image.flatten() # Display a histogram of the pixels in the bottom subplot plt.subplot(2, 1, 2) plt.xlim((0, 255)) plt.title('Normalized histogram') plt.hist(pixels, bins=64, color='red', alpha=0.4, range=(0, 256), normed=True) # Display the plot plt.show() # Load the image into an array: image image = plt.imread('640px-Unequalized_Hawkes_Bay_NZ.jpg') # Display image in top subplot using color map 'gray' plt.subplot(2, 1, 1) plt.imshow(image, cmap='gray') plt.title('Original image') plt.axis('off') # Flatten the image into 1 dimension: pixels pixels = image.flatten() # Display a histogram of the pixels in the bottom subplot plt.subplot(2, 1, 2) pdf = plt.hist(pixels, bins=64, range=(0, 256), normed=False, color='red', alpha=0.4) plt.grid('off') # Use plt.twinx() to overlay the CDF in the bottom subplot plt.twinx() # Display a cumulative histogram of the pixels cdf = plt.hist(pixels, bins=64, range=(0, 256), cumulative=True, normed=True, color='blue', alpha=0.4) # Specify x-axis range, hide axes, add title and display plot plt.xlim((0, 256)) plt.grid('off') plt.title('PDF & CDF (original image)') plt.show() ############################################################## ############################################################## ################################################################ ############################################################## # Load the image into an array: image image = plt.imread('640px-Unequalized_Hawkes_Bay_NZ.jpg') file = os.listdir()[0] image = plt.imread(file) # Flatten the image into 1 dimension: pixels pixels = image.flatten() # Generate a cumulative histogram cdf, bins, patches = plt.hist(pixels, bins=256, range=( 0, 256), density=True, cumulative=True) new_pixels = np.interp(pixels, bins[:-1], cdf*255) # df_norm = (new_pixels - new_pixels.min()) / \ # (new_pixels.max() - new_pixels.min()) # Reshape new_pixels as a 2-D array: new_image # scaler = preprocessing.MinMaxScaler() new_image = new_pixels.reshape(image.shape).astype(int) # # new_pixels = scaler.fit_transform(new_pixels) # new_image = df_norm.reshape(image.shape) matplotlib.image.imsave('new_{}.png'.format(file[:-4]), new_image) # Display the new image with 'gray' color map # plt.subplot(2, 1, 1) plt.title('Equalized image') plt.axis('off') plt.imshow(new_image) plt.show() # matplotlib.image.imsave('newImage.png', new_image) # from PIL import Image # im = Image.fromarray(new_image) # im.save("New_{}.jpg".format(file[:-4])) ########################################################################### ######################################################################## # Generate a histogram of the new pixels plt.subplot(2, 1, 2) pdf = plt.hist(new_pixels, bins=64, range=(0, 256), normed=False, color='red', alpha=0.4) plt.grid('off') # Use plt.twinx() to overlay the CDF in the bottom subplot plt.twinx() plt.xlim((0, 256)) plt.grid('off') # Add title plt.title('PDF & CDF (equalized image)') # Generate a cumulative histogram of the new pixels cdf = plt.hist(new_pixels, bins=64, range=(0, 256), cumulative=True, density=True, color='blue', alpha=0.4) plt.show() # Load the image into an array: image image = plt.imread('hs-2004-32-b-small_web.jpg') # Display image in top subplot plt.subplot(2, 1, 1) plt.title('Original image') plt.axis('off') plt.imshow(image) # Extract 2-D arrays of the RGB channels: red, blue, green red, green, blue = image[:, :, 0], image[:, :, 1], image[:, :, 2] # Flatten the 2-D arrays of the RGB channels into 1-D red_pixels = red.flatten() blue_pixels = blue.flatten() green_pixels = green.flatten() # Overlay histograms of the pixels of each color in the bottom subplot plt.subplot(2, 1, 2) plt.title('Histograms from color image') plt.xlim((0, 256)) plt.hist(red_pixels, bins=64, normed=True, color='red', alpha=0.2) plt.hist(blue_pixels, bins=64, normed=True, color='blue', alpha=0.2) plt.hist(green_pixels, bins=64, normed=True, color='green', alpha=0.2) # Display the plot plt.show() # Load the image into an array: image image = plt.imread('hs-2004-32-b-small_web.jpg') # Extract RGB channels and flatten into 1-D array red, blue, green = image[:,:,0], image[:,:,1], image[:,:,2] red_pixels = red.flatten() blue_pixels = blue.flatten() green_pixels = green.flatten() # Generate a 2-D histogram of the red and green pixels plt.subplot(2,2,1) plt.grid('off') plt.xticks(rotation=60) plt.xlabel('red') plt.ylabel('green') plt.hist2d(x=red_pixels, y=green_pixels, bins=(32,32)) # Generate a 2-D histogram of the green and blue pixels plt.subplot(2,2,2) plt.grid('off') plt.xticks(rotation=60) plt.xlabel('green') plt.ylabel('blue') plt.hist2d(x=green_pixels, y=blue_pixels, bins=(32,32)) # Generate a 2-D histogram of the blue and red pixels plt.subplot(2,2,3) plt.grid('off') plt.xticks(rotation=60) plt.xlabel('blue') plt.ylabel('red') plt.hist2d(x=blue_pixels, y=red_pixels, bins=(32,32)) # Display the plot plt.show()
2bd5e2556a3706a7f186ff01dd0d641005a7a508
snehaa2632000/Scientific-Computing
/Newton_Raphson.py
1,001
3.8125
4
import numpy as np from sympy import * x = symbols('x') #inp = input('Enter the exp :') expr = 2 * x**3 - 2 * x - 5 print("Given expression : {}".format(expr)) expr_diff = expr.diff(x) print("Derivative of expression with respect to x : {}".format(expr_diff.doit())) f = lambdify(x,expr,'numpy') f_diff = lambdify(x,expr_diff,'numpy') def func(x): return f(x) def derivative(x): return f_diff(x) def newtonRaphson(x): itr = 1 h = func(x) / derivative(x) while abs(h) >= 0.000001: h = func(x)/derivative(x) # x(i+1) = x(i) - f(x) / f'(x) x = x - h print('Iteration-%d => x = %0.6f'%(itr,x)) itr = itr + 1 print("The value of the root is : ", "%.4f"% x) #Initial value for i in range(10): m = func(i) i = i+1 n = func(i) if m <= 0 and n>=0: a = i - 1 b = i break x_0 = (a+b)/2 print(x_0) newtonRaphson(x_0)
729f34288c56863ac66284f3a1b1ae7e9edc56ce
SoumyadeepDey2002/MachineLearning_and_DeepLearning
/Python basics for ML 1/18_birthday.py
106
4.03125
4
birthday = input('What\'s your birthday?') age = 2021 - int(birthday) -1 print(f'your age is {age}')
3626abcfc689afecdd6d74aca9ed4ebdbc157ed2
SoumyadeepDey2002/MachineLearning_and_DeepLearning
/Python basics for ML 1/07_bin_complex.py
198
3.96875
4
complex #data type to store complex numbers print(bin(7)) print(bin(5)) # decimal to binary # 0b represents that it's binary print(int('0b101',2)) #convert base 2 to 10 which is decimal
fe0ed51cf0cdab74d7d87b9f8317e18776d0c27d
ostanleigh/csvSwissArmyTools
/dynamicDictionariesFromCSV.py
2,363
4.25
4
import csv import json from os import path print("This script is designed to create a list of dictionaries from a CSV File.") print("This script assumes you can meet the following requirements to run:") print(" 1) The file you are working with has clearly defined headers.") print(" 2) You can review the headers ('.head') ") print(" 3) You wish to leverage the headers as keys, create a dict per row, and use the row values as Dict vals.") while True: userFileVal = input("\n Dynamic Dictionaries from CSV file," "\n \n What is the name of the csv file you would like to work with? (Don't enter the file extension.): ") try: filename = path.exists(userFileVal+'.csv') except FileNotFoundError: print("Wrong file or file path") else: break #filename = input("What is the name of the csv file you would like to work with? (Don't enter the file extension.) ? ") userEvalIn = input("Do you want to remove any columns or characters from the left of the header? Y or N?: ") userEval = str.lower(userEvalIn) if userEval == 'y': startIndex = int(input("How many fields should be trimmed from left margin? Enter an integer: ")) # If file corruption introduces characters, or redundant file based index is in place # Can add lines to support further indexing / slicing as needed else: startIndex = 0 outFileName = input("What do you want to name your output file? Please enter a valid csv file name: ") with open (userFileVal+'.csv', 'r') as csvInputFile: filereader = csv.reader(csvInputFile) headerRaw = next(filereader) header = headerRaw header = headerRaw[startIndex:] print(f"header is: {header}") with open (outFileName+'.json','w',newline='') as jsonOutputFile: filereader = csv.reader(csvInputFile) outDicts = [ ] for line in filereader: keyValsRaw = next(filereader) keyVals = keyValsRaw[ startIndex: ] # If file corruption introduces characters, or redundant index is in place # keyVals = keyValsRaw[1:] # use further indexing / slicing as needed headerKeys = dict.fromkeys(header) zipObj = zip(headerKeys, keyVals) dictObj = dict(zipObj) outDicts.append(dictObj) filewriter = json.dump(outDicts,jsonOutputFile) print("Close")
0635e54f09efc07afe7d10dd199422e4923ff5cf
Lee7goal/lee7_2019
/python高级/lee7_创建property属性的方式装饰器.py
927
3.5625
4
# coding = utf-8 # Version:Python3.7.3 # Tools:Pycharm 2017.3.2 __date__ = '2019/4/21 0021 21:21' __author__ = 'Lee7' class Goods: def __init__(self): # 原价 self.original_price = 100 # 折扣 self.discount = 0.8 @property def price(self): # 实际价格 = 原价 * 折扣 new_price = self.original_price * self.discount return new_price @price.setter def price(self, value): self.original_price = value @price.deleter def price(self): del self.original_price # ########## 调用 ########## obj = Goods() print(obj.price) # 自动执行@property修饰的price方法,并获取方法的返回值 obj.price = 200 # 自动执行@price.setter修饰的price方法,并将123赋值给方法的参数 print(obj.price) del obj.price # 自动执行@price.deleter修饰的price方法
860e71a0d01ad592ff68ba81394f3fafcaac97a8
Lee7goal/lee7_2019
/Machine_learning/05_07_02demo.py
427
3.765625
4
# coding=utf-8 # Version:3.6.3 # Tools:Pycharm __date__ = ' 2019/5/7 12:37' __author__ = 'lee7goal' # strings = ['a', 'as', 'bat', 'car', 'dove', 'python'] # print([x.upper() for x in strings if len(x) > 2]) some_tuples = [(1, 2, 3), (4, 5, 6), (7, 8, 9)] flattened = [x.__float__() for tup in some_tuples for x in tup] print(flattened) flattened2 = [[x for x in tup] for tup in some_tuples] print(tuple(flattened2))
7726ff58eed732d19877462105b37b8b1e24b538
StefanTobler/HeavyFailure
/hack.py
2,045
3.84375
4
# Hacking Maintenance closet to get tool box import paths import parts import maze import random import os import time clear = lambda: os.system("cls") # Simple algebra problem, I wish I could make it more interactive def hacking(): # Creates 2 numbers num2 can be anywhere between 1 and 5 times larger than num1 num1 = random.randint(1, 100) num2 = random.randint(1, 5) * num1 sum = num1 + num2 multiple = num2 // num1 maze.rprint("It seems that the door got stuck when Heavy crashed. " "You’re going to have to hack it to get through.\n") maze.enter("Press enter to initiate hacking.") clear() for i in range(5): time.sleep(.25) maze.rprint("Hacking initiating. . .") clear() attempts = 3 # Actual hacking while attempts > 0: clear() print("Attempts:", attempts, "\n") maze.rprint("The sum of two numbers is ", "") maze.rprint(str(sum), " ") maze.rprint("and the second number is", " ") maze.rprint(str(multiple), " ") maze.rprint("times larger than the first number") maze.rprint("\nWhat is the value of the first number?") val1 = input() maze.rprint("\nWhat is the value of the second number?") val2 = input() if val1 == str(num1) and val2 == str(num2): maze.rprint("Success!") maze.enter() attempts = -1 else: if attempts != 1: maze.rprint("Error try again.") maze.enter() attempts -= 1 # Checks if hacking failed if attempts == 0: maze.rprint("Hacking failed. To try again enter \"again\" or \"exit\" to leave.") val = input().lower() try: if val == "again": hacking() except UnboundLocalError: pass if attempts == -1: clear() maze.rprint("You got the door open and found the tool box!") parts.toolBox = True maze.enter() paths.menu()
418886582c9050a100c75b3105b181d53cf3ad1b
SakaiMasato/pythonTest
/task/demo/renameDates.py
948
3.53125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- ' file traverse then rename the date from MM-DD-YYYY to MM-DD-YYYY ' __author__ = 'Bob' import os, re path = os.path.join(os.path.abspath('.'), 'renameDatesDatas') filePaths = os.listdir(path) def findAmericanDate(str): regex = r''' ((0\d)|(1[012])) #MM - #separator ((0\d)|([12]\d)|(3[01])) #DD - #separator (\d{1,}) #YYYY ''' matcher = re.compile(regex, re.VERBOSE) return matcher.search(str) if __name__ == '__main__': for filePath in filePaths: filePath = os.path.join(path, filePath) file = open(filePath) str = file.read() mo = findAmericanDate(str) if(mo is not None): MM = mo.group(1) DD = mo.group(4) YYYY = mo.group(8) print(DD,'-',MM,'-',YYYY)
b17242db6b0538bc876043e7bdde6e9c7b5f5a37
SakaiMasato/pythonTest
/task/chapter6_task_displayInentory.py
709
3.859375
4
#!/usr/bin/env python # -*- coding: utf-8 -*- ' display inventory ' __author__ = 'Bob Bao' def displayInventory(dic): print('Inventory:') totalNum = 0 for k, v in dic.items(): print(k,' ',v) totalNum += v print('Total number of items: ', totalNum) def addToInventory(inventory, addedItems): for k1, v1 in addedItems.items(): inventory.setdefault(k1, 0) inventory[k1] += v1 return; if __name__ == '__main__': dic = {'rope':1, 'torch':6, 'gold coin':42, 'dagger':1, 'arrow':12} displayInventory(dic) print('kill a dragon') dragonLoot = {'gold coin':5, 'dagger':1, 'ruby':1} addToInventory(dic, dragonLoot) displayInventory(dic)
338448b8a3a314d1a45bcdef05ebefb03b7d3123
on-merrit/ON-MERRIT
/WP3/Task3.3/src/utils/file_utils.py
1,882
3.78125
4
"""Utilities for working with files (e.g. creation of dated folders) """ import os from datetime import datetime class FileUtils(object): @staticmethod def ensure_dir(dir_path: str) -> None: """Create directory (including parent directories) if it does not exist. :param dir_path: directory to create :type dir_path: str :return: None :rtype: None """ if not os.path.exists(dir_path): os.makedirs(dir_path) @staticmethod def create_dated_directory(parent_directory: str) -> str: """Create a new directory inside parent_directory which uses today's date its name. Date format: %Y%m%d :param parent_directory: where to create the directory :type parent_directory: str :return: path to the created directory :rtype: str """ today = datetime.today() dir_path = os.path.join(parent_directory, today.strftime('%Y%m%d')) FileUtils.ensure_dir(dir_path) return dir_path @staticmethod def create_timed_directory( parent_directory: str, suffix: str = None ) -> str: """Create a new directory inside parent_directory which uses date & time as its name. Date format: %Y%m%d%H%m :param parent_directory: where to create the directory :type parent_directory: str :param suffix: optional suffix for the name, default: None :type suffix: str, optional :return: path to the created directory :rtype: str """ today = datetime.now() dir_name = ( f"{today.strftime('%Y%m%d%H%M')}_{suffix}" if suffix else today.strftime('%Y%m%d%H%M') ) dir_path = os.path.join(parent_directory, dir_name) FileUtils.ensure_dir(dir_path) return dir_path
32ed93f11b342e7ff62bc9eaa83d7e3f5ed41e2c
zhogan85/zth_new_coder
/dataviz/graph.py
2,814
3.65625
4
import csv import matplotlib.pyplot as plt import numpy as np from collections import Counter MY_FILE = "sample_sfpd_incident_all.csv" def parse(raw_file, delimiter): """Parses a raw CSV file to a JSON-like object.""" #open csv file opened_file = open(raw_file) #read csv file csv_data = csv.reader(opened_file,delimiter=delimiter) #build parsed data parsed_data = [] #define headers fields = csv_data.next() #Iterate over each row of the csv file, zip together field->value pairs for row in csv_data: parsed_data.append(dict(zip(fields, row))) #close csv file opened_file.close() return parsed_data def visualize_days(): """Visualize data by day of week.""" #grab our parsed data that we parsed earlier data_file = parse(MY_FILE, ",") #make a new variable, counter, from iterating through each line of #data in the parsed data, and count how many incidents happen on each #day of the week counter = Counter(item["DayOfWeek"] for item in data_file) #separate the x-axis data (days of the week) from the counter variable #from the y-axis (number of incidents each day) data_list = [ counter["Monday"], counter["Tuesday"], counter["Wednesday"], counter["Thursday"], counter["Friday"], counter["Saturday"], counter["Sunday"] ] day_tuple = tuple(["Mon", "Tues", "Wed", "Thurs", "Fri", "Sat", "Sun"]) #with y-axis data, assign it to a matplotlib plot instance plt.plot(data_list) #create amount of ticks need for x and y axes and assign labels plt.xticks(range(len(day_tuple)), day_tuple) #save the plot plt.savefig("Days.png") #close plot file plt.clf() def visualize_type(): """Visualize data by category in a bar graph""" #grab our parsed data data_file = parse(MY_FILE, ",") #make a new variable, counter, from iterating through each line of #data in parsed data, and count how many incidents happen by category counter = Counter(item["Category"] for item in data_file) #set the labels which are based on the keys of our counter #since order doesn't matter, we can just use counter.keys() labels = tuple(counter.keys()) #set exactly where the labels should hit the x-axis xlocations = np.arange(len(labels)) + 0.5 #width of each bar that will be plotted width = 0.5 #assign data to a bar plot plt.bar(xlocations, counter.values(), width=width) #assign labels and tick location to x-axis plt.xticks(xlocations + width /2, labels, rotation=90) #give more room to the x-axis so the labels aren't cut off plt.subplots_adjust(bottom=0.4) #make the overall graph/figure larger plt.rcParams['figure.figsize'] = 12, 8 #save the graph plt.savefig("type.png") #close the plot figure plt.clf() def main(): visualize_days() visualize_type() if __name__ == "__main__": main()
9d9418791dd153f6df877edbb8d35f64c56360bd
Rubyroobinibu/pythonpractice
/python 15.09.19/inheritance.py
969
3.75
4
class A: def m1(self): print("method 1") def m2(self): print("method 2") class B(A): #B class acquires properties of A #single inh def m1(self): #mtd overriding print("called from B") def m3(self): print("method 3") def m4(self): return "method 4" class C(B): #B class acquires properties of A #multilevel inh def __init__(self,a,b): print("dfsdf") def m5(self): print("method 5") class D: def m6(self): print("mtd 6") class E(A,D): #multiple inh def m7(self): print("mtd 7") a=A() a.m1() print(a.m2()) #print(a.m3()) throws error b=B() print(b.m3()) print(b.m4()) print(b.m1()) c=C(5,10) c.m5() c.m1() c.m3() e=E() e.m1() e.m6() print(issubclass(B,A)) print(isinstance(b,B)) print(issubclass(C,A)) print(issubclass(B, object)) #all user def classes are subclasses of object clas by default
77aeacb8eec0dac1b258e9cba1b78c8f32a2577b
pauldubois98/PrimesGame
/primes.py
907
3.609375
4
from random import choice def primeRange(mini, maxi): ###fonding primes #init l=[True for i in range(maxi)] #case 0 & 1 l[0], l[1]=False, False #extraction of the primes numbers for a in range (2,int(maxi/2)+1): if l[a]: for i in range (a*a,maxi,a): if l[i]==1: l[i]=False ###put all primes in a list final=[] for i in range (mini,maxi): if l[i]: final.append(i) return final def makeRandNb(nbPrimes, mini, maxi): li=[] primes=primeRange(mini, maxi) nb=1 for i in range(nbPrimes): new=choice(primes) li.append(new) nb*=new return (nb, li) if __name__=='__main__': #test of the module print(primeRange(0, 10)) print(primeRange(10, 50)) print() for i in range(5): print(makeRandNb(10,0,100))
c21fae89fda3395df34e09a78cfefa990836159a
Aafreen29/digit_recognition_opencv
/model_build.py
2,232
3.59375
4
# -*- coding: utf-8 -*- """ Created on Sun Nov 4 09:08:41 2018 @author: Aafreen Dabhoiwala """ # importing keras libraries from keras.models import Sequential from keras.layers import Conv2D from keras.layers import MaxPooling2D from keras.layers import Flatten from keras.layers import Dense from keras.utils.np_utils import to_categorical from keras.datasets import mnist import numpy as np import pandas as pd import matplotlib.pyplot as plt %matplotlib inline #separting data into train and test from mnnist dataset (train_images, train_labels), (test_images, test_labels) = mnist.load_data() #converting labels into hot encoding train_labels = to_categorical(train_labels) test_labels = to_categorical(test_labels) #train_images = train_images.astype('float32') #test_images = test_images.astype('float32') #reshaping train_images =np.array(train_images).reshape(-1,28,28,1) test_images =np.array(test_images).reshape(-1,28,28,1) #normalizing train_images = train_images/255.0 test_images= test_images/255.0 # Initialising the CNN classifier = Sequential() # Step 1 - Convolution classifier.add(Conv2D(32, (3, 3), padding = 'Same', activation="relu", input_shape=(28, 28, 1))) # Step 2 - Pooling classifier.add(MaxPooling2D(pool_size = (2, 2))) #adding another convulationary layer classifier.add(Conv2D(32, (3, 3), activation="relu")) classifier.add(Conv2D(64, (3, 3), activation="relu")) classifier.add(MaxPooling2D(pool_size = (2, 2))) # Step 3 - Flattening classifier.add(Flatten()) # Step 4 - Full connection classifier.add(Dense(output_dim = 256, activation = 'relu')) #output layer classifier.add(Dense(output_dim = 10, activation = 'softmax')) classifier.compile(optimizer = 'adam', loss = 'categorical_crossentropy', metrics = ['accuracy']) epochs=30 batch_size=90 classifier.fit(train_images, train_labels, batch_size=batch_size, epochs=epochs) score = classifier.evaluate(test_images, test_labels, verbose=0) print('Test loss:', score[0]) print('Test accuracy:', score[1]) # serialize model to JSON model_json = classifier.to_json() with open("model.json", "w") as json_file: json_file.write(model_json) # serialize weights to HDF5 classifier.save_weights("model.h5") print("Saved model to disk")
355e2f783c7d3928436eef46e0c94d31125fe899
ravi501/dataanalyst-udacity
/p2-investigatingadataset/final-project/titanic-data-analysis-pandas.py
4,008
3.859375
4
import unicodecsv import pandas as pd import matplotlib.pyplot as plt """ Load Data from CSVs The first step in the process would be to load the data from the CSV file into our data dictionary. """ def read_csv_file(filename): with open(filename, 'rb') as f: reader = unicodecsv.DictReader(f) return list(reader) titanic_data_pandas = pd.read_csv('titanic-data.csv') print('Using describe method to print the description of the data') print titanic_data_pandas.describe() print('Printing the actual data') print titanic_data_pandas """ Data Wrangling Phase Once the CSV data is imported into the lists, the data needs to be fixed and the data needs to be converted into their respective data types. """ # Takes string with values 0 or 1, # and returns a boolean True or False def parse_int_to_boolean(i): if i == 1: return True elif i == 0: return False # Takes the name of the passenger, and returns the first name and last name # as a list. This function also removes the Mr., Mrs., Miss, Master titles given to the person, # and it also crops out everything provided in brackets def parse_first_and_last_names(name): #Splits the name by a comma first_last_names = name.split(",") #Splits the first name by ". " first_last_names[1] = first_last_names[1].split(". ")[1] #If the name contains anything in brackets, they are ignored if '(' in first_last_names[1]: first_last_names[1] = first_last_names[1].split(" (")[0] return first_last_names[0], first_last_names[1] # Takes the sex as male or femal, and returns a single character 'M' or 'F' def parse_sex(sex): if 'male' == sex: return 'M' else: return 'F' def get_last_names(name): return name[0] titanic_data_pandas['Name'] = titanic_data_pandas['Name'].map(parse_first_and_last_names) titanic_data_pandas['Sex'] = titanic_data_pandas['Sex'].map(parse_sex) titanic_data_pandas['Survived'] = titanic_data_pandas['Survived'].map(parse_int_to_boolean) titanic_data_pandas['Last Name'] = titanic_data_pandas['Name'].map(get_last_names) print('Printing the titanic data after performing cleaning operations') print titanic_data_pandas """ Exploration, Conclusions and Communication Phase """ ## 1. The ratio of male to female survivors def male_female_survivors_ratio(): male_female_survivors = titanic_data_pandas.groupby('Sex')['Survived'].count() labels = 'Male', 'Female' colors = ['yellow', 'blue'] plt.title('Ratio of male to female survivors') plt.pie(male_female_survivors, labels=labels, colors=colors, autopct='%1.1f%%', shadow=True) plt.show() male_female_survivors_ratio() ## 2. The ratio of first, second and third class survivors def class_wise_survivors(): first_second_third_class_survivors = titanic_data_pandas.groupby('Pclass')['Survived'].count() labels = 'First class', 'Second class', 'Third class' colors = ['yellow', 'blue', 'Green'] plt.title('Ratio of first, second and third class survivors') plt.pie(first_second_third_class_survivors, labels=labels, colors=colors, autopct='%1.1f%%', shadow=True) plt.show() class_wise_survivors() ## 3. The ratio of passengers who survived vs those who didn't in first, second and third classes def survivors_vs_non_survivors(): each_class_survivors = titanic_data_pandas.groupby(['Survived', 'Pclass']).size().unstack('Survived').fillna(False) each_class_survivors[[0, 1]].plot(kind='bar') plt.title('Survivors by class') plt.xlabel('Class numbers') plt.ylabel('Survived vs not survived count') plt.show() survivors_vs_non_survivors() ## 4. Survived passengers grouped by last name def survivors_grouped_by_last_name(): survivors_by_last_name = titanic_data_pandas.groupby('Last Name')['Survived'].count() labels1 = titanic_data_pandas['Last Name'].unique() plt.pie(survivors_by_last_name, labels=labels1, shadow=True) print plt.show() survivors_grouped_by_last_name()
1cc2d81fb38544d7e6d8f195f47bdc1c5aa5d6fe
duckietown-udem/udem-fall19-public
/notebooks/code/exercise_03_control/controller.py
2,319
3.53125
4
import numpy as np class Controller(): def __init__(self): self.gain = 2.0 pass def angle_control_commands(self, dist, angle): # Return the angular velocity in order to control the Duckiebot so that it follows the lane. # Parameters: # dist: distance from the center of the lane. Left is negative, right is positive. # angle: angle from the lane direction, in rad. Left is negative, right is positive. # Outputs: # omega: angular velocity, in rad/sec. Right is negative, left is positive. omega = 0. ####### # # MODIFY ANGULAR VELOCITY # # YOUR CODE HERE # ####### return omega def pure_pursuit(self, env, pos, angle, follow_dist=0.25): # Return the angular velocity in order to control the Duckiebot using a pure pursuit algorithm. # Parameters: # env: Duckietown simulator # pos: global position of the Duckiebot # angle: global angle of the Duckiebot # Outputs: # v: linear veloicy in m/s. # omega: angular velocity, in rad/sec. Right is negative, left is positive. closest_curve_point = env.unwrapped.closest_curve_point # Find the curve point closest to the agent, and the tangent at that point closest_point, closest_tangent = closest_curve_point(pos, angle) iterations = 0 lookup_distance = follow_dist multiplier = 0.5 curve_point = None while iterations < 10: ######## # #TODO 1: Modify follow_point so that it is a function of closest_point, closest_tangent, and lookup_distance # ######## follow_point = closest_point curve_point, _ = closest_curve_point(follow_point, angle) # If we have a valid point on the curve, stop if curve_point is not None: break iterations += 1 lookup_distance *= multiplier ######## # #TODO 2: Modify omega # ######## omega = 0. v = 0.5 return v, omega
89ec0897f99163edb014c185425b3054332f6dbe
RamyaRaj14/assignment5
/max1.py
258
4.25
4
#function to find max of 2 numbers def maximum(num1, num2): if num1 >= num2: return num1 else: return num2 n1 = int(input("Enter the number:")) n2 = int(input("Enter the number:")) print(maximum(n1,n2))
cbb74e2a3e69c3c27ecda584ac2f632c0820db49
jaynarayan94/API-Applications-Projects
/Stock News/main.py
2,988
3.515625
4
import requests from twilio.rest import Client STOCK_NAME = "TSLA" COMPANY_NAME = "Tesla Inc" STOCK_ENDPOINT = "https://www.alphavantage.co/query" NEWS_ENDPOINT = "https://newsapi.org/v2/everything" STOCK_API_KEY = "STOCK_API_KEY" NEWS_API_KEY = "NEWS_API_KEY" account_sid = "account_sid" auth_token = "auth_token" ## STEP 1: Use https://www.alphavantage.co/documentation/#daily # When stock price increase/decreases by 5% between yesterday and the day before yesterday. # Get yesterday's closing stock price. # Hint: We can perform list comprehensions on Python dictionaries. e.g. [new_value for (key, value) in dictionary.items()] stock_params = { "function": "TIME_SERIES_DAILY", "symbol": STOCK_NAME, "apikey": STOCK_API_KEY } response = requests.get(STOCK_ENDPOINT, params= stock_params) data = response.json()["Time Series (Daily)"] print(response.json()) data_list = [value for (key,value) in data.items()] yesterday_data = data_list[0] yesterday_closing_price = float(yesterday_data["4. close"]) print(yesterday_closing_price) # print(data_list) # print(data) # Get the day before yesterday's closing stock price day_before_yesterday_data = data_list[1] day_before_yesterday_closing_price = float(day_before_yesterday_data["4. close"]) print(day_before_yesterday_closing_price) # Find the positive difference between 1 and 2. e.g. 20 - 40 = -20, but the positive difference is 20. difference = round(yesterday_closing_price- day_before_yesterday_closing_price, 2) up_down = None if difference > 0: up_down = "🔺" else: up_down = "🔻" # Work out the percentage difference in price between closing price yesterday and closing price the day before yesterday. diff_percent = round((difference/ yesterday_closing_price)*100, 2) print(diff_percent) # STEP 2: https://newsapi.org/ # If percentage is greater than 5 then print("Get News"). # Get the first 3 news pieces for the COMPANY_NAME. if abs(diff_percent) > 0.5: news_params = { "apiKey": NEWS_API_KEY, "qInTitle": COMPANY_NAME, } news_response = requests.get(url=NEWS_ENDPOINT, params = news_params) articles = news_response.json()["articles"] three_articles = articles[:3] # print(articles) # print(three_articles) # STEP 3: Use twilio.com/docs/sms/quickstart/python to send a separate message with each article's title and description to your phone number. # Create a new list of the first 3 article's headline and description using list comprehension. # Send each article as a separate message via Twilio. formatted_articles = [f"{STOCK_NAME}: {up_down}{diff_percent}%\nHeadline: {article['title']}. \nBrief: {article['content']}" for article in three_articles] client = Client(account_sid, auth_token) for article in formatted_articles: message = client.messages.create( body= article, from_='Twilio Number', to='Receivers number') # print(message.status)
0dee971d88bf1e2b93e1f006407c4c987dfe3a69
manon2012/python
/work/leetcode/testunknown.py
838
3.65625
4
def findRestaurant( list1, list2): for item in list1: if item in list2: return item r=findRestaurant(["Shogun","Tapioca Express","Burger King","KFC"],["Piatti","The Grill at Torrey Pines","Hungry Hunter Steakhouse","Shogun"]) print (r) # filter=["av","japan","xiaodao"] # content=input("please input:") # for i in filter: # if i in content: # content=content.replace(i,"***") # print (content) # c=content.split(" ") # for i in c: # if i in filter: # c[c.index(i)]="***" # print ("".join(c)) def sebsequence(a,b): sum=0 j=0 for i in range(len(b)-1): if b[i] == a[j]: sum += 1 if j<len(a)-1: j+=1 if j==len(a)-1: break return sum==len(a) r=sebsequence("abc","aaabbbccc") print (r)
483709ef78d4f9b384100aace775e562ee79ab32
manon2012/python
/work/leetcode/square.py
308
3.71875
4
def isPerfectSquare(num): """ :type num: int :rtype: bool """ if num == 1: return True for i in range(num): if i * i == num: return True return False r1=isPerfectSquare(16) r2=isPerfectSquare(1) r3=isPerfectSquare(15) print (r1) print (r2) print (r3)
606bcf541577b92fa7b328d4ab8b502e77850d3e
manon2012/python
/work/Do/testsort3.py
1,318
3.71875
4
<<<<<<< HEAD ======= >>>>>>> fa18662c7df3c24470bfae36b878e5cf1d7121a0 def bubble_sort(n): for i in range(len(n)-1): for j in range(len(n)-i-1): if n[j]>n[j+1]: n[j],n[j+1]=n[j+1],n[j] <<<<<<< HEAD return n print (bubble_sort([3,2,1,100])) ======= return n print (bubble_sort([3,2,1])) >>>>>>> fa18662c7df3c24470bfae36b878e5cf1d7121a0 def select_sort(n): for i in range(len(n)-1): min_index=i <<<<<<< HEAD for j in range(i, len(n)): if n[j]<n[min_index]: min_index=j n[i],n[min_index]=n[min_index],n[i] return n print (select_sort([3,2,1,9,0])) def insert_sort(n): for i in range(len(n)-1): ======= for j in range(i+1,len(n)): if n[j]<n[min_index]: min_index=j n[i],n[min_index]=n[min_index],n[i] return n print (select_sort([3,2,1,100])) def insert_sort(n): for i in range(1,len(n)): >>>>>>> fa18662c7df3c24470bfae36b878e5cf1d7121a0 key=n[i] j=i-1 while j>=0 and n[j]>key: n[j+1]=n[j] j-=1 <<<<<<< HEAD n[j+1]=key return n print (insert_sort([3,2,1,0,100])) ======= n[j+1]=key return n print(insert_sort([3,2,1])) >>>>>>> fa18662c7df3c24470bfae36b878e5cf1d7121a0
1769bc8b3639e3683fc8b12bcda8e0266cae127d
manon2012/python
/test/test1.py
651
3.53125
4
import unittest class TestCount: def __init__(self,a,b): self.a=a self.b=b def doadd(self): return self.a + self.b class TestUt(unittest.TestCase): def setUp(self): print ("before...") def testdoadd(self): i=TestCount(1,2) print (i) self.assertEqual(i.doadd(),3,"not equal") def teststr(self): self.assertTrue(0) def tearDown(self): print ("after...") if __name__ == '__main__': #unittest.main() suite=unittest.TestSuite() suite.addTest(TestUt("testdoadd")) print (suite) runner=unittest.TextTestRunner runner.run(suite)
e7b628c275951b76de5644dbb20ffa055ce3403d
manon2012/python
/work/Do/testUT.py
752
3.671875
4
import unittest class cal(): def __init__(self, a, b): self.a = int(a) self.b = int(b) def caladd(self): return self.a + self.b def caldiv(self): return (self.a)/(self.b) class test_unit(unittest.TestCase): def setUp(self): print("before everyrun") def tearDown(self): print ("after everyrun") @classmethod def setUpClass(cls): print ("one class run once") c1 = cal(10, 10) # why not work? def test_01(self): #c1=cal(10,10) self.assertEqual(c1.caladd(),20,"not equal") @unittest.skip def test_02(self): c2 = cal(10, 1) self.assertEqual(c2.caldiv(),10) if __name__ == '__main__': unittest.main()
860396ad50c09af0162141639cce177da0db17dc
manon2012/python
/work/leetcode/restr.py
2,314
3.796875
4
def restr(str): r=str.split(" ") rr=[i[::-1] for i in r] return ' '.join(rr) r=restr("hi hello world") print (r) def all(str): return str[::-1] r=all("hi hello world") print (r) """Input : str = "geeks quiz practice code" Output : str = "code practice quiz geeks""" def a1(str): a=str.split(" ") b=a[::-1] return " ".join(b) r=a1("geeks quiz practice code") print (r) """Input : geeksforgeeks Output : efgkos""" def a2(str): # a=[] # for i in str: # a.append(i) # b=list(set(a)) # return "".join(b) return "".join(set(str)) r=a2("geeksforgeeks") print (r) """Input : list = [1, 2, 3] Output : [[], [1], [1, 2], [1, 2, 3], [2], [2, 3], [3]]""" a = [1, 2, 3] r=[] for i in range(len(a)): for j in range(i+1,len(a)): r.append(a[i:j]) print (r) """Input : list = [10, 20, 30, 40, 50] index = 2 Output : [10, 20, 40, 50] """ def test(a,index): a.remove(a[2]) return a r=test([10, 20, 30, 40, 50] ,2) print (r) def check(a,x): for i in a: if i>x: return True return False print (check([2,3,4,1],1)) """ Input : [10, 20, 30, 40, 50, 60, 70, 80, 90] Output : 30 60 90 40 80 50 20 70 10 """ def removee3(n): index=0 pos=3-1 a=len(n) while a>0: index=(index+pos)%a print (n.pop(index)) a-=1 removee3([10, 20, 30, 40, 50, 60, 70, 80, 90,100]) # a=[10, 20, 30, 40, 50, 60, 70, 80, 90] # while len(a)>0: # a.pop() # len(a)-=1 can't assign to function call print ("$$$$$") a=[10, 20, 30, 40, 50, 60, 70, 80, 90] n=len(a) while n>0: print (a.pop()) n-=1 #can't assign to function call print (a) def sum1(n): a=[] # for i in n: # a.append(sum(i)) # return max(a) for i in n: x = 0 for y in i: x+=y a.append(x) return max(a) r=sum1([[1, 2, 3], [4, 5, 6], [10, 11, 12], [7, 8, 9]] ) print (r) d1={"a":1,"b":2,"c":3} d2=dict([("a",1),("b",2),("c",3)]) d3=dict(a=1,b=2,c=3) # print (d1) # print (d2) # print (d3) a=['a','b','b','c','c','c'] b={}.fromkeys(a,[]) c={}.fromkeys(a,"vm") print (b) print (c) print (c.get('a')) #print (c.get(d)) aa={'a': 'vm', 'b': 'vm', 'c': 'vm'} print (aa.get("a")) print (aa.setdefault("d","VM")) print (aa)
5969ccbe82c1dc36934636e7a9e2a2beda7b2cb2
VieuxChameau/pythonCoursera
/assignment.4.6.py
200
3.875
4
def computepay(h, r): if h <= 40: return h * r else: return (40 * r) + ((h - 40) * r * 1.5) hrs = float(input("Enter Hours:")) rate = float(input("Enter Rate:")) print(computepay(hrs, rate))
7a78c1adc57f43aeed0f304f39199656e69d8c03
hahastudio/Algorithms
/primality.py
1,024
3.90625
4
import math import random def primality1(n): """give a positive integer n, testing primality. It proclaim n a prime as soon as it have rejected all candidate up to sqrt(n). """ for i in xrange(2, int(math.sqrt(n)) + 1): if n % i == 0: return False return True def primality2(n): """give a positive integer n, testing primality. With the power of Fermat's little theorem, we can use a probabilistic tests that it makes the probability of failure at most 2^(-100). """ if n <= 102: for a in xrange(2, n): if pow(a, n - 1, n) != 1: return False return True else: for i in xrange(100): a = random.randint(2, n - 1) if pow(a, n - 1, n) != 1: return False return True def generate_prime(n): """Return a n-bit prime.""" while 1: p = random.randint(pow(2, n-2), pow(2, n-1)-1) p = 2 * p + 1 if primality2(p): return p
5755031ab15c2429980d5f7def1f26cd1a59a8d5
hahastudio/Algorithms
/bfs.py
832
3.9375
4
""" 约定:图的存储方法 这里的图采用邻接表的方法存储。有两种可行的方式: 1. 边无权重: 采用集合存储该点可到达的点集 2. 边有权重: 采用字典(点:边的权重)存储该点可到达的点集 例: V = a, b, c, d, e, f, g, h = range(8) E = [ set([b, c, f]), set([e]), set([d]), set([a, h]), set([f, g, h]), set([b, g]), set(), set([g]) ] G = (V, E) """ from collections import deque inf = float("inf") def bfs(G, s): """Input: Graph G = (V, E), directed or undirected; vertex s in V Output: For all vertices u reachable from s, dist[u] is set to the distance from s to u """ V, E = G dist = [inf for u in V] dist[s] = 0 Q = deque([s]) while Q: u = Q.popleft() for v in E[u]: if dist[v] == inf: Q.append(v) dist[v] = dist[u] + 1 return dist
7d0b02264a79f998560f83e92d4377719e763351
qiusiyuan/adventofcode
/2019/day6/day6.py
1,076
3.515625
4
with open("input.txt", "r") as fd: inputlines = fd.read().splitlines() def splitr(route): jj = route.split(")") main = jj[0] ob = jj[1] return main, ob all_dict = {} for route in inputlines: main, ob = splitr(route) if ob not in all_dict: all_dict[ob] = main dp = {} def count(ob): if ob in dp: return dp[ob] main = all_dict[ob] if main not in all_dict: return 1 if main in dp: return dp[main] + 1 counts = count(main) + 1 dp[ob] = counts return counts c = 0 for ob in all_dict: c += count(ob) print(c) #2 def count_route(obj): orbting = {} main = all_dict[obj] s = 0 while main in all_dict: orbting[main] = s main = all_dict[main] s += 1 orbting[main] = s return orbting def minimum_route(o1, o2): minimum = float('inf') for key in o1.keys(): if key in o2: minimum = min(o1[key] + o2[key], minimum) return minimum o1 = count_route("YOU") o2 = count_route("SAN") print(minimum_route(o1,o2))
3eeb5bd250346b47af7ceb28ca46b9a5bb5f8514
ncdunker/python-challenge
/good_movies.py
1,245
3.78125
4
#!/usr/bin/env python # coding: utf-8 # In[1]: # Dependencie import pandas as pd # In[2]: # Load in file movie_file = "Resources/movie_scores.csv" # In[3]: # Read and display the CSV with Pandas movie_file_pd = pd.read_csv(movie_file) movie_file_pd.head() # In[4]: # List all the columns in the table movie_file_pd.columns # In[5]: # We only want IMDb data, so create a new table that takes the Film and all the columns relating to IMDB imdb_table = movie_file_pd[["FILM", "IMDB", "IMDB_norm", "IMDB_norm_round", "IMDB_user_vote_count"]] imdb_table.head() # In[6]: # We only like good movies, so find those that scored over 7, and ignore the norm rating good_movies = movie_file_pd.loc[movie_file_pd["IMDB"] > 7, [ "FILM", "IMDB", "IMDB_user_vote_count"]] good_movies.head() # In[7]: # Find less popular movies--i.e., those with fewer than 20K votes unknown_movies = good_movies.loc[good_movies["IMDB_user_vote_count"] < 20000, [ "FILM", "IMDB", "IMDB_user_vote_count"]] unknown_movies.head() # In[8]: # Finally, export this file to a spread so we can keep track of out new future watch list without the index unknown_movies.to_excel("output/movieWatchlist.xlsx", index=False)
163c1b4beb8cd62c23abacd9ed1fb1cdf51929dd
EYandura/Artificial-Intelligence-Group-T3
/PEX2-MultiAgent/multiAgents.py
15,987
3.71875
4
# ############################## # # Reece Clingenpeel, Eric Yandura # # DOCUMENTATION: # ~ The Python Doc was used throughout this file in order to explore the built in Python structures and functionality. # ~ The class text and Notes were used throughout the assignment. # I followed along with a similar problem online to better understand how to do number 1 (Eric Yandura) ' # Did not just copy, once I already had my solution, it was used to help find errors # https://github.com/advaypakhale/Berkeley-AI-Pacman-Projects/blob/master/multiagent/multiAgents.py # # ############################### # multiAgents.py # -------------- # Licensing Information: You are free to use or extend these projects for # educational purposes provided that (1) you do not distribute or publish # solutions, (2) you retain this notice, and (3) you provide clear # attribution to UC Berkeley, including a link to http://ai.berkeley.edu. # # Attribution Information: The Pacman AI projects were developed at UC Berkeley. # The core projects and autograders were primarily created by John DeNero # (denero@cs.berkeley.edu) and Dan Klein (klein@cs.berkeley.edu). # Student side autograding was added by Brad Miller, Nick Hay, and # Pieter Abbeel (pabbeel@cs.berkeley.edu). from util import manhattanDistance from game import Directions import random, util from game import Agent class ReflexAgent(Agent): """ A reflex agent chooses an action at each choice point by examining its alternatives via a state evaluation function. The code below is provided as a guide. You are welcome to change it in any way you see fit, so long as you don't touch our method headers. """ def getAction(self, gameState): """ You do not need to change this method, but you're welcome to. getAction chooses among the best options according to the evaluation function. Just like in the previous project, getAction takes a GameState and returns some Directions.X for some X in the set {North, South, West, East, Stop} """ # Collect legal moves and successor states legalMoves = gameState.getLegalActions() # Choose one of the best actions scores = [self.evaluationFunction(gameState, action) for action in legalMoves] bestScore = max(scores) bestIndices = [index for index in range(len(scores)) if scores[index] == bestScore] chosenIndex = random.choice(bestIndices) # Pick randomly among the best "Add more of your code here if you want to" return legalMoves[chosenIndex] def evaluationFunction(self, currentGameState, action): """ Design a better evaluation function here. The evaluation function takes in the current and proposed successor GameStates (pacman.py) and returns a number, where higher numbers are better. The code below extracts some useful information from the state, like the remaining food (newFood) and Pacman position after moving (newPos). newScaredTimes holds the number of moves that each ghost will remain scared because of Pacman having eaten a power pellet. Print out these variables to see what you're getting, then combine them to create a masterful evaluation function. """ # Useful information you can extract from a GameState (pacman.py) successorGameState = currentGameState.generatePacmanSuccessor(action) newPos = successorGameState.getPacmanPosition() newFood = successorGameState.getFood() newGhostStates = successorGameState.getGhostStates() newScaredTimes = [ghostState.scaredTimer for ghostState in newGhostStates] "*** YOUR CODE HERE Question 1***" # get the minimum distance to the closest ghost ghostDistance = min([manhattanDistance(newPos, each.getPosition()) for each in newGhostStates]) if ghostDistance: ghost_dist = -10 / ghostDistance else: ghost_dist = -1000000 list_of_food = newFood.asList() # get the distance to the closest food if list_of_food: closeFood = min([manhattanDistance(newPos, food) for food in list_of_food]) # there is no food else: closeFood = 0 # return the weighted score return (-1 * closeFood) + ghost_dist - (100 * len(list_of_food)) def scoreEvaluationFunction(currentGameState): """ This default evaluation function just returns the score of the state. The score is the same one displayed in the Pacman GUI. This evaluation function is meant for use with adversarial search agents (not reflex agents). """ return currentGameState.getScore() class MultiAgentSearchAgent(Agent): """ This class provides some common elements to all of your multi-agent searchers. Any methods defined here will be available to the MinimaxPacmanAgent, AlphaBetaPacmanAgent & ExpectimaxPacmanAgent. You *do not* need to make any changes here, but you can if you want to add functionality to all your adversarial search agents. Please do not remove anything, however. Note: this is an abstract class: one that should not be instantiated. It's only partially specified, and designed to be extended. Agent (game.py) is another abstract class. """ def __init__(self, evalFn = 'scoreEvaluationFunction', depth = '2'): self.index = 0 # Pacman is always agent index 0 self.evaluationFunction = util.lookup(evalFn, globals()) self.depth = int(depth) class MinimaxAgent(MultiAgentSearchAgent): """ Your minimax agent (Question 2) Perform a post order traversal of the game tree assuming that the opponent behaves optimally. """ def getAction(self, gameState): """ Returns the minimax action from the current gameState using self.depth and self.evaluationFunction. Here are some method calls that might be useful when implementing minimax. gameState.getLegalActions(agentIndex): Returns a list of legal actions for an agent agentIndex=0 means Pacman, ghosts are >= 1 gameState.generateSuccessor(agentIndex, action): Returns the successor game state after an agent takes an action gameState.getNumAgents(): Returns the total number of agents in the game """ "*** YOUR CODE HERE ***" # TODO count to keep track of iteration and agent (each agent needs x iterations) agentIndex = self.index depth = self.depth return self.value(gameState, agentIndex, depth)[1] def value(self, gameState, agentIndex, depth): """ If the gameState is a terminal state, return it. Otherwise, find the min/max and return the minimax value. :param gameState: The current state of the game. :return: The minimax value at the state gameState. """ # If the current depth is 0, we have traversed the tree; return the value of the evaluation function. if depth == 0: return (self.evaluationFunction(gameState), '') # If gameState is a terminal state (win or loss), return the value of the evaluation function. if gameState.isWin() or gameState.isLose(): return (self.evaluationFunction(gameState), '') # If the agent is Pacman (agentIndex == 0) find the max. if agentIndex == 0: return self.maxValue(gameState, agentIndex, depth) # Otherwise, the agent is a Ghost (agentIndex >= 1); find the min. elif agentIndex >= 1: return self.minValue(gameState, agentIndex, depth) def maxValue(self, gameState, agentIndex, depth): """ Return the max value of the successors of gameState. :param gameState: The current state of the game. :return: The max value of gameState's successors. """ # Initialize v to a min value. v = -99999 # The number of agents in the game. numAgents = gameState.getNumAgents() # The nextAgentIndex will be agentIndex + 1 (mod numAgents) as we want to iterate each agent # once for each level of depth. nextAgentIndex = (agentIndex + 1) % numAgents # If we are looking at the last agent in the game, decrement the depth by 1. if agentIndex == numAgents - 1: nextDepth = depth - 1 # Otherwise, the depth remains the same. else: nextDepth = depth # Return a list of all the legal actions of the agent. actions = gameState.getLegalActions(agentIndex) # Loop the legal actions and find the max. for a in actions: successor = gameState.generateSuccessor(agentIndex, a) actionVal = self.value(successor, nextAgentIndex, nextDepth) if actionVal[0] > v: v = actionVal[0] currentBestAction = a return (v, currentBestAction) def minValue(self, gameState, agentIndex, depth): """ Return the min value of the successors of gameState. :param gameState: The current state of the game. :return: The min value of gameState's successors. """ # Initialize v to a max value. v = 99999 # The number of agents in the game. numAgents = gameState.getNumAgents() # The nextAgentIndex will be agentIndex + 1 (mod numAgents) as we want to iterate each agent # once for each level of depth. nextAgentIndex = (agentIndex + 1) % numAgents # If we are looking at the last agent in the game, decrement the depth by 1. if agentIndex == numAgents - 1: nextDepth = depth - 1 # Otherwise, the depth remains the same. else: nextDepth = depth # Return a list of all the legal actions of the agent. actions = gameState.getLegalActions(agentIndex) # Loop the legal actions and find the min. for a in actions: successor = gameState.generateSuccessor(agentIndex, a) actionVal = self.value(successor, nextAgentIndex, nextDepth) if actionVal[0] < v: v = actionVal[0] currentBestAction = a return (v, currentBestAction) class AlphaBetaAgent(MultiAgentSearchAgent): """ Your minimax agent with alpha-beta pruning (question 4 - optional) """ def getAction(self, gameState): """ Returns the minimax action using self.depth and self.evaluationFunction """ "*** YOUR CODE HERE ***" util.raiseNotDefined() class ExpectimaxAgent(MultiAgentSearchAgent): """ Your expectimax agent (Question 3) """ def getAction(self, gameState): """ Returns the expectimax action from the current gameState using self.depth and self.evaluationFunction. Here are some method calls that might be useful when implementing minimax. gameState.getLegalActions(agentIndex): Returns a list of legal actions for an agent agentIndex=0 means Pacman, ghosts are >= 1 gameState.generateSuccessor(agentIndex, action): Returns the successor game state after an agent takes an action gameState.getNumAgents(): Returns the total number of agents in the game """ agentIndex = self.index depth = self.depth return self.value(gameState, agentIndex, depth)[1] def value(self, gameState, agentIndex, depth): """ If the gameState is a terminal state, return it. Otherwise, find the min/max and return the minimax value. :param gameState: The current state of the game. :return: The minimax value at the state gameState. """ # If the current depth is 0, we have traversed the tree; return the value of the evaluation function. if depth == 0: return (self.evaluationFunction(gameState), '') # If gameState is a terminal state (win or loss), return the value of the evaluation function. if gameState.isWin() or gameState.isLose(): return (self.evaluationFunction(gameState), '') # If the agent is Pacman (agentIndex == 0) find the max. if agentIndex == 0: return self.maxValue(gameState, agentIndex, depth) # Otherwise, the agent is a Ghost (agentIndex >= 1); find the expected. elif agentIndex >= 1: return self.expValue(gameState, agentIndex, depth) def maxValue(self, gameState, agentIndex, depth): """ Return the max value of the successors of gameState. :param gameState: The current state of the game. :return: The max value of gameState's successors. """ # Initialize v to a min value. v = -99999 # The number of agents in the game. numAgents = gameState.getNumAgents() # The nextAgentIndex will be agentIndex + 1 (mod numAgents) as we want to iterate each agent # once for each level of depth. nextAgentIndex = (agentIndex + 1) % numAgents # If we are looking at the last agent in the game, decrement the depth by 1. if agentIndex == numAgents - 1: nextDepth = depth - 1 # Otherwise, the depth remains the same. else: nextDepth = depth # Return a list of all the legal actions of the agent. actions = gameState.getLegalActions(agentIndex) # Loop the legal actions and find the max. for a in actions: successor = gameState.generateSuccessor(agentIndex, a) actionVal = self.value(successor, nextAgentIndex, nextDepth) if actionVal[0] > v: v = actionVal[0] currentBestAction = a return (v, currentBestAction) def expValue(self, gameState, agentIndex, depth): """ Return the probable value of the successors of gameState. :param gameState: The current state of the game. :return: The min value of gameState's successors. """ # Initialize v to a max value. v = 0 # The number of agents in the game. numAgents = gameState.getNumAgents() # The nextAgentIndex will be agentIndex + 1 (mod numAgents) as we want to iterate each agent # once for each level of depth. nextAgentIndex = (agentIndex + 1) % numAgents # If we are looking at the last agent in the game, decrement the depth by 1. if agentIndex == numAgents - 1: nextDepth = depth - 1 # Otherwise, the depth remains the same. else: nextDepth = depth # Return a list of all the legal actions of the agent. actions = gameState.getLegalActions(agentIndex) currentProbability = 0 # Loop the legal actions and find the min. for a in actions: successor = gameState.generateSuccessor(agentIndex, a) actionVal = self.value(successor, nextAgentIndex, nextDepth) # The probability of the move is 1/(# of legal actions for the agent). p = 1.0 / len(gameState.getLegalActions(agentIndex)) v += p * actionVal[0] if v > currentProbability: currentProbability = v currentBestAction = a return (currentProbability, currentBestAction) def betterEvaluationFunction(currentGameState): """ Your extreme ghost-hunting, pellet-nabbing, food-gobbling, unstoppable evaluation function (question 5 - optional). DESCRIPTION: <write something here so we know what you did> """ "*** YOUR CODE HERE ***" "*** YOUR CODE HERE ***" util.raiseNotDefined() # Abbreviation better = betterEvaluationFunction
1715d9a7c8af4c221ec1027ca51ef13a8d269058
Arcadonauts/BES-2018
/email_myself.py
1,683
3.515625
4
"""Send an email message from the user's account. """ #!/usr/bin/python2.7 from email.mime.text import MIMEText import httplib2 import base64 from apiclient import discovery import credentials def SendMessage(service, user_id, message): """Send an email message. Args: service: Authorized Gmail API service instance. user_id: User's email address. The special value "me" can be used to indicate the authenticated user. message: Message to be sent. Returns: Sent Message. """ message = (service.users().messages().send(userId=user_id, body=message) .execute()) print('Message Id: %s' % message['id']) return message def CreateMessage(sender, to, subject, message_text): """Create a message for an email. Args: sender: Email address of the sender. to: Email address of the receiver. subject: The subject of the email message. message_text: The text of the email message. Returns: An object containing a base64url encoded email object. """ message = MIMEText(message_text) message['to'] = to message['from'] = sender message['subject'] = subject string = message.as_string() bts = string.encode('ascii') raw = base64.urlsafe_b64encode(bts) return {'raw': raw.decode()} def send(subject, message): print('Email: %s'%subject) creds = credentials.fegleyapi http = creds.authorize(httplib2.Http()) service = discovery.build('gmail', 'v1', http=http) user_id = 'me' msg = CreateMessage('fegleyapi@gmail.edu', 'fegleynick@gmail.com', subject, message) SendMessage(service, user_id, msg) if __name__ == '__main__': pass #send('Test4', "It's still working!")
4735d3a958dab66d6b2f0710a92a4300619ff3df
Horlando-Leao/geradorRelatorioInteligente
/src/Util.py
2,629
3.609375
4
import re class Util(): def __init__(self): pass def detectarDataExpressaoRegular(texto): date_pattern = re.compile(''' ([12][0-9]|3[0-1]|0?[1-9]) # to detect days from 1 to 31 ([./-]) # to detect different separations (1[0-2]|0?[1-9]) # to detect number of months ([./-]) # to detect different seperations (2?1?[0-9][0-9][0-9]) # to detect number of years from 1000-2999 years ''', re.VERBOSE) days = [] months = [] years = [] dates = [] for date in date_pattern.findall(texto): days.append(int(date[0])) months.append(int(date[2])) years.append(int(date[4])) for num in range(len(days)): # appending dates in a list that dont need any filtering to detect wrong dates if months[num] not in (2, 4, 6, 9, 11): dates.append([days[num], months[num], years[num]]) # detecting those dates with months that have only 30 days elif days[num] < 31 and months[num] in (4, 6, 9, 11): dates.append([days[num], months[num], years[num]]) # filtering leap years with Feb months that have 29 days elif months[num] == 2 and days[num] == 29: if years[num] % 4 == 0: if years[num] % 100 == 0: if years[num] % 400 == 0: dates.append([days[num], months[num], years[num]]) else: dates.append([days[num], months[num], years[num]]) # appending Feb dates that have less than 29 days elif months[num] == 2 and days[num] < 29: dates.append([days[num], months[num], years[num]]) if len(dates) > 0: listDates = [] for date in dates: listDates.append( str(date[2]) +"-"+ str(date[1]) +"-"+ str(date[0]) ) return listDates def procurarStrings(self, boleano = False, string="", matchess = []): a_string = string matches = [] for x in matchess: if x in a_string and x not in matches: matches.append(x) if(boleano == True and matches): return True elif(boleano == True and matches == []): return False else: return matches #utilidade = Util().procurarStrings(string="Relátorio de vendas por ano", matchess=["por ano"], boleano=True) #print(utilidade)
c3eb6412b70b6627a0bbf0ff50b86e64cdd22fe0
Horlando-Leao/geradorRelatorioInteligente
/src/test/detectarData2.py
1,552
4
4
import re def date_is_valid(day: int, month: int, year: int) -> bool: return (month not in (2, 4, 6, 9, 11) # 31 days in month (Jan, Mar, May, Jul, Aug, Oct, Dec). or day < 31 and month in (4, 6, 9, 11) # 30 days in month (Feb, Apr, Jun, Sep, Nov). or month == 2 and day == 29 and year % 4 == 0 and (year % 100 != 0 or year % 400 == 0) # February, 29th in a Gregorian leap year. or month == 2 and day < 29) # February, 1st-28th. def date_detector(text: str): date_pattern = re.compile(''' (?P<day>[12][0-9]|3[0-1]|0?[1-9]) # to detect days from 1 to 31 (?P<sep>[./-]) # to detect different separations (?P<month>1[0-2]|0?[1-9]) # to detect number of months (?P=sep) # to detect different seperations (?P<year>2?1?[0-9][0-9][0-9]) # to detect number of years from 1000-2999 years ''', re.VERBOSE) dates = [] for match in date_pattern.finditer(text): date = match.groupdict() # convert Match object to dictionary. del date['sep'] # we don't need the separator any more. date = {key: int(val) for key, val in date.items()} # apply int() to all items. if date_is_valid(date['day'], date['month'], date['year']): dates.append(date) if len(dates) > 0: for date in dates: print(date) data = '30-06-2012, 31-12.2012' date_detector(data)
f8ec2566b82d611fe6e8ae0ecff036978de9a002
ayaabdraboh/python
/lap1/shapearea.py
454
4.125
4
def calculate(a,c,b=0): if c=='t': area=0.5*a*b elif c=='c': area=3.14*a*a elif c=='s': area=a*a elif c=='r': area=a*b return area if __name__ == '__main__': print("if you want to calculate area of shape input char from below") c = input("enter char between t,s,c,r : ") a=int(input("enter num1")) b=int(input("enter num2")) print(calculate(a,c,b))
f0ff04904913946057b156dbde69511b11015a63
GeoGateway/BuriedSAFSlip2010
/daynum2k.py
2,023
3.796875
4
# Date to day past y2k def daynum2k(date): """ Function daynum2k: date: string in format dd-Mmm-yyyy ie 13-Nov-2009 return day past y2k start (01-Jan-2000 => 1) Note: good for years 2000-2023 (easily generalized) """ yearc = [366,365,365,365,366,365,365,365,366,365,365,365, 366,365,365,365,366,365,365,365,366,365,365,365] monthc = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] day,month,year = date.split('-') if int(year)%4==0: monthc[1]=29 monthld = 12*[None] monthfd = 12*[None] monthld[0] = monthc[0] monthfd[0] = 1 for i in range(1,12): monthld[i] = monthld[i-1] + monthc[i] monthfd[i] = monthld[i]-monthc[i]+1 mnames = ["Jan","Feb","Mar","Apr","May","Jun", "Jul","Aug","Sep","Oct","Nov","Dec"] firstday = dict(zip(mnames,monthfd)) # firstday should return first day of named month: firstday["Feb"] => 32 daynum = firstday[month]+int(day) - 1 yearld = 24*[None] yearfd = 24*[None] yearld[0] = yearc[0] yearfd[0] = 1 for i in range(1,24): yearld[i] = yearld[i-1]+yearc[i] yearfd[i] = yearld[i]-yearc[i]+1 ynames=["2000","2001","2002","2003","2004","2005", "2006","2007","2008","2009","2010","2011", "2012","2013","2014","2015","2016","2017", "2018","2019","2020","2021","2022","2023"] firstyday = dict(zip(ynames,yearfd)) daynum2k = firstyday[year]+daynum-1 return daynum2k def test(): a=daynum2k("04-Jul-2009") b=daynum2k("04-Jun-2009") c=daynum2k("31-Dec-2009") d=daynum2k("01-Jan-2009") e=daynum2k("01-Jan-2010") diff=a-b yd1=daynum2k("01-Apr-2010")-daynum2k("01-Apr-2009") yd2=daynum2k("01-Apr-2008")-daynum2k("01-Apr-2007") print "04-Jul-2009", a print "04-Jun-2009", b print "diff = ",diff print "31-Dec-2009", c print "01-Jan-2009", d print "01-Jan-2010", e print "2010-2009",yd1 print "2008-2007 (leap)",yd2 if __name__ == '__main__': test()
9151027c3ddbb445db1602733a81712e1396a7af
retzstyleee/chapter-08-protek
/Praktikum8.1.py
235
3.8125
4
try: jumlah = int(input("Jumlah : ")) data = [] for i in range(jumlah): data.append(int(input("Data ke {} : ".format(i+1)))) data.sort(reverse=True) print(data) except: print("Input tidak Valid")
0d40a49c5c13f3d2dfb56fd63fa8a7ea708a8da8
retzstyleee/chapter-08-protek
/Praktikum8.3.py
292
3.703125
4
try: jumlah = int(input("Jumlah : ")) data = [] for i in range(jumlah): data.append(input("Data ke {} : ".format(i+1))) data.sort() for i in data: print("[{}] {} ({} karakter)".format(data.index(i),i,len(i))) except: print("Input tidak Valid")
87696c2adf3314acbc96db79addb184b010915fb
natallia-zzz/labs_python
/n7_lab_2_6.py
2,882
3.578125
4
def extract_file(file_name): txtfile = file_name + 'txt' f = open(txtfile, "r") return from_json(str_gen(f)) def str_gen(s): for ch in s: yield ch def from_json(obj): ch = next(obj) if ch.isdigit() or ch == "-": return json_num(ch, obj) elif ch.isalpha(): val = json_val(ch, obj) if val == "null": return None elif val == "true": return True elif val == "false": return False else: raise ValueError elif ch == '"': return json_str(obj) elif ch == "[": return json_list(obj) elif ch == "{": return json_dict(obj) else: raise ValueError def json_num(first_ch, obj): num_str = first_ch is_int = True while True: ch = next(obj) if ch.isspace(): if is_int: return int(num_str) else: return float(num_str) elif ch.isdigit(): num_str += ch elif ch == ".": is_int = False num_str += ch else: raise ValueError def json_val(first_ch, obj): val = first_ch while True: ch = next(obj) if ch.isspace() or ch == ',': return val elif ch.isdigit() or ch.isalpha(): val += ch else: raise ValueError def json_str(obj): string = '' while True: ch = next(obj) if ch == '"': return string else: string += ch def json_list(obj): res = [] while True: ch = next(obj) if ch.isspace(): continue if ch == "]": return res if ch == '{': res.append(json_dict(obj)) elif ch == '[': res.append(json_list(obj)) elif ch == '"': res.append(json_str(obj)) elif ch.isdigit() or ch == '-': res.append(json_num(ch, obj)) elif ch.isalpha(): value = json_val(ch, obj) if value == "true": res.append(True) elif value == "false": res.append(False) elif value == "null": res.append(None) else: raise ValueError def json_dict(obj): dict = {} while True: ch = next(obj) if ch.isspace() or ch == ',': continue elif ch == '}': return dict elif ch == '"': k = json_str(obj) while True: ch = next(obj) if ch.isspace(): continue elif ch == ':': break else: raise ValueError v = from_json(obj) dict[k] = v else: raise ValueError
832cf97e515ef6358319cbb03ee6cfed43486558
aanwar5/Data_Analytics_Python_Test
/Tables Calculator.py
279
4.0625
4
#!/usr/bin/env python # coding: utf-8 # In[5]: #Making a multiplication table on Python j=1 while (j<=10): i = 1 print("Printing the following table of ", j) while(i<=10): print( j, "times", i, j*i) i=i+1 j =j+1 # In[ ]:
83190ab93ab688c07c57e3e17889c9b671d0589b
madisonmay/SoftwareDesign
/ai_v_ai.py
673
3.53125
4
import tictactoe, ankur import sys def unpack(b): l = [1,2,3,4,5,6,7,8,9] for elem in b['x']: l.remove(elem) for elem in b['o']: l.remove(elem) return {' ':l,'x':b['x'],'o':b['o']} def printboard(board): nboard = unpack(board) for j in range(3): for i in range(1+3*j,4+3*j): if i in nboard[' ']: sys.stdout.write('- ') if i in nboard['x']: sys.stdout.write('x ') if i in nboard['o']: sys.stdout.write('o ') print() print() if __name__ == "__main__": board = {'X': [], 'O': []} for i in range(4): board = tictactoe.play(board, 'x') board = ankur.play(board, 'o')
d9141766341e0f20c31c53bbe4f2aa7fd29b7254
ss666/leetcode-practice
/ReorderList.py
1,262
4.0625
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def reorderList(self, head: ListNode) -> None: """ Do not return anything, modify head in-place instead. """ def middleNode(head): slow, fast = head, head while fast is not None and fast.next is not None: slow = slow.next fast = fast.next.next return slow def reverseList(head): if head is None or head.next is None: return head reversed_head = reverseList(head.next) head.next.next = head#.next head.next = None return reversed_head mid = middleNode(head) mid_next = mid.next mid.next = None # 断开链表 l1 = head l2 = reverseList(mid_next) while l2 is not None: #or l2.next is not None: l1_nxt = l1.next l1.next = l2 l2_nxt = l2.next l2.next = l1_nxt l1 = l1_nxt l2 = l2_nxt
7e4503ab4bfd9f18557b6d0b4b3e3d5a4f5d4820
virginiayung/UW
/amath583_scientific_computing/homework3/intersections.py
1,538
4.03125
4
""" solving g1(x)=g2(x) or equivalently solving for zeros of the function f(x)=g1(x)-g2(x) by using newton.solve """ import numpy as np from pylab import * interactive(True) from newton2 import solve #Graph to find intersections to use as x0 x = np.linspace(-10,10, 1000) ylim(-3,3,0.01) g1 = x*np.cos(np.pi*x) g2= 1-0.6*x**2 plot(x,g1,'b-') plot(x,g2,'r-') title("Plot 2 Functions") show() def fvals_g1g2(x): """ Return f(x) and f'(x) for applying Newton to find a square root. """ f = x*np.cos(np.pi*x)-1. + 0.6*x**2. fp = np.cos(np.pi*x)- np.pi*x*np.sin(np.pi*x) + 1.2*x return f, fp def test_intersections(debug_solve=False): """ Test Newton iteration for the square root with different initial conditions." """ for x0 in [-2., -1.6, -0.8, 1.4]: print " " # blank line x, iters = solve(fvals_g1g2, x0, debug=debug_solve) print "With initial guess x0 = %22.15e ," %(x0) print "solve returns x = %22.15e after %i iterations " % (x,iters) fx, fpx = fvals_g1g2 (x) print "the value of f(x) is %22.15e" % fx xt=x y= xt*np.cos(np.pi*xt) x = np.linspace(-5,5, 1000) ylim(-3,3,0.01) g1 = x*np.cos(np.pi*x) g2= 1-0.6*x**2 p1, = plot(x,g1,'b-',label= 'g1(x)') p2, = plot(x,g2,'r-',label= 'g2(x)') plot(xt,y, 'ko') legend([p1,p2],["g1","g2"]) title("Plot 2 Functions with intersections") show() plt.savefig('intersections.png')
eb07e42211c4d4576e43c3614de7385b0d63e4c8
Sparrow612/PythonCodePrac
/DFS/exist_word.py
986
3.8125
4
from typing import List def exist(board: List[List[str]], word: str) -> bool: if not board or not board[0]: return False directions = [(0, 1), (1, 0), (0, -1), (-1, 0)] def check(i, j, k): if word[k] != board[i][j]: return False if k == len(word) - 1: return True visited.add((i, j)) result = False for di, dj in directions: newi = i + di newj = j + dj if 0 <= newi < len(board) and 0 <= newj < len(board[0]): if check(newi, newj, k + 1) and (newi, newj) not in visited: result = True break visited.remove((i, j)) return result visited = set() for i in range(len(board)): for j in range(len(board[0])): if check(i, j, 0): return True return False if __name__ == '__main__': board = [['A', 'B', 'C', 'E'], ['S', 'F', 'C', 'S'], ['A', 'D', 'E', 'E']] print(exist(board, "ABCCED"))
f93efab3989b4e17054543a315e62b71bfa105e9
Sparrow612/PythonCodePrac
/Competition/parking_system.py
603
3.828125
4
# class Car: # def __init__(self, t): # self.carType = t class ParkingSystem: def __init__(self, big: int, medium: int, small: int): self.spaces = [big, medium, small] def addCar(self, carType: int) -> bool: if self.spaces[carType - 1]: self.spaces[carType - 1] -= 1 return True return False if __name__ == '__main__': p = ParkingSystem(1, 1, 0) print(p.addCar(1), p.addCar(3)) # Your ParkingSystem object will be instantiated and called as such: # obj = ParkingSystem(big, medium, small) # param_1 = obj.addCar(carType)
cecf0a359662e808478965729e6563be79b0e312
Sparrow612/PythonCodePrac
/Tree/BST_2_GRT.py
1,594
3.828125
4
class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None """ 本题中要求我们将每个节点的值修改为原来的节点值加上所有大于它的节点值之和。这样我们只需要反序中序遍历该二叉搜索树,记录过程中的节点值之和,并不断更新当前遍历到的节点的节点值,即可得到题目要求的累加树。 关键词:反序中序遍历 中序遍历是从小到大,那么从大到小反过来即可 PS:这题是看答案看来的 """ sum_of_val = 0 # 遍历和 def convertBST(root: TreeNode) -> TreeNode: global sum_of_val if root: convertBST(root.right) sum_of_val += root.val root.val = sum_of_val convertBST(root.left) return root def another_convert_bst(root): """ :param root: TreeNode :return: root 这段代码思路和上面一样,只不过换了一种实现方式 """ def dfs(root: TreeNode): nonlocal total if root: dfs(root.right) total += root.val root.val = total dfs(root.left) total = 0 dfs(root) return root if __name__ == '__main__': root = TreeNode(2) left = TreeNode(1) right = TreeNode(3) # ll = TreeNode(-4) # lr = TreeNode(1) # left.left = ll # left.right = lr root.left = left root.right = right root = convertBST(root) print(root.val) print(root.left.val) print(root.right.val) # print(root.left.left.val) # print(root.left.right.val)
142250fa8db529bee7c8f758baa797ccd3c26d06
Perfectly-Purple/CSES-python
/Permutations.py
176
3.890625
4
x=int(input()) if(x==1): print("1") elif(x>1 and x<4): print("NO SOLUTION") else: for i in range(2,x+1,2): print(i, end=" ") for i in range(1,x+1,2): print(i, end=" ")
7963ad9983277a0306758115fa5c01f63ec08cc1
Sahbetdin/ACMP
/rucode/oper.py
238
3.75
4
#кол-во операций def f(n): if n == 0: return 1 else: index = n - 1 sum = 1 while (index >= 0): sum = sum + f(index) print("index = " , sum) index = index - 1 #print("~~~~~~~") return sum print(f(30))
b5d6e17221eb7f62196a18fdbe0f92839c253a8b
symbolr/python
/demo/6.py
101
3.5
4
def fact(n): if n==1: return 1 return n*fact(n-1) print(fact(1)) print(fact(5)) print(fact(100))
538b835102d5dec7ff140c72725be5adb7efa851
symbolr/python
/demo/debug.py
628
3.859375
4
# 第一种打print # def foo(s): # n = int(s) # print('>>>n = %d' %n) # return 10/n # def main(): # foo('0') # main() # 第二种断言 # def foo(s): # n = int(s) # assert n!= 0 ,'n is zero' # return 10/n # def main(): # foo('0') # main() # 第三种 logging # # logging.basicConfig(level=logging.INFO) # def foo(s): # n = int(s) # logging.info('>>>n = %d' %n) # return 10/n # def main(): # foo('0') # main() # 第四种 pdb # def foo(s): # n = int(s) # return 10/n # def main(): # foo('0') # main() import pdb def foo(s): n = int(s) pdb.set_trace() return 10/n def main(): foo('0') main()
419ab4ff6ec8b2241d2a242cd3d3cdb448cfa4c3
bekahbooGH/oo-desserts
/desserts.py
2,053
3.796875
4
class Cupcake: """A cupcake.""" # Class attribute cache = {} # INSTANCE METHOD:: def __init__(self, name, flavor, price): self.name = name self.flavor = flavor self.price = price self.qty = 0 self.cache[name] = self def add_stock(self, amount): self.qty = ( self.qty + amount ) # NOTE: self.amount? Nope, it's just amount since we didn't create an instance for it in the __init__ # return self.qty def sell(self, amount): if self.qty == 0 and amount > self.qty: print("Sorry, these cupcakes are sold out") elif self.qty < amount: self.qty = 0 else: self.qty = self.qty - amount # return self.qty #Checks that it works # STATIC METHOD: @staticmethod def scale_recipe(ingredients, amount): # ingredients = [(ingredient_name , ingredient_qty), ()] final_list = [] for ingr in ingredients: multiplied_amount = amount * ingr[1] final_list.append((ingr[0], multiplied_amount)) # print(final_list) return final_list # Function call: # Cupcake.scale_recipe([('flour', 1), ('sugar', 3)], 10) # output --> [('flour', 10), ('sugar', 30)] # CLASS METHODS: @classmethod def get(cls, name): if name not in cls.cache: print("Sorry, that cupcake doesn't exist") else: return cls.cache[name] def __repr__(self): """Human-readable printout for debugging.""" # test_cupcake.name = "testing 123" # test_cupcake.qty = 0 # test_cupcake.flavor = "vanilla" # test_price = 1.00 return f'<Cupcake name="{self.name}" qty={self.qty}>' if __name__ == "__main__": import doctest result = doctest.testfile( "doctests.py", report=False, optionflags=(doctest.REPORT_ONLY_FIRST_FAILURE) ) doctest.master.summarize(1) if result.failed == 0: print("ALL TESTS PASSED")
2d15daa653ac971c8c916848d2ffdc507572a528
cloudmesh/cloudmesh-pi
/cloudmesh/pi/grove_speaker.py
2,303
3.53125
4
import grovepi import time import sys class GroveSpeaker: def __init__(self, pin = 3): """ use digital pin as output pin for speaker pin 3 by default connect to port D3 of grove pi hat """ self.speaker = 3 self.high = 0 self.low = 0 grovepi.pinMode(self.speaker,"OUTPUT") grovepi.digitalWrite(self.speaker, self.low) def setFreq(self, freq = 0 , seconds = 0): """ Generate a wave with the frequency freq (Hz) for specified number of seconds approximately by default 0 Hz for 0 seconds for freq time for each wavelength = 1/freq time for half a wave = wait_time = 1/(2*freq) number of wavelengths in specified seconds = loop loop = seconds * freq """ wait_time = 1/(2*float(freq)) loop = int(seconds*freq) for i in range(loop): grovepi.digitalWrite(self.speaker, self.high) time.sleep(wait_time) grovepi.digitalWrite(self.speaker, self.low) time.sleep(wait_time) def setVolumeHigh(self): """ When high = 1, low = 0 , more voltage to the speaker, therefore more volume """ self.high = 1 def setVolumeLow(self): """ when high = 0 and low = 0, very little voltage goes to the speaker and therefore low volume """ self.high = 0 def speakerOff(self): """ to avoid some noise voltage to speaker leadning to some noise in the speaker set voltage to -1 """ grovepi.digitalWrite(self.speaker, -1) def speakerOn(self): """ to activate the speaker or allow some noise set voltage to 0 """ grovepi.digitalWrite(self.speaker, 0) if __name__ == "__main__": speaker = GroveSpeaker() print "set speaker off to avoid noise" speaker.speakerOff() time.sleep(1) print "set speaker volume high" speaker.setVolumeHigh() print "play a certain tune 10 times" print "play a tone with frequency 200 for 0.05 seconds" print "play a tone with frequency 500 for 0.05 seconds" print "play a tone with frequency 1000 for 0.05 seconds" print "repeat" for i in range(10): speaker.setFreq(200, 0.03) speaker.setFreq(500, 0.03) speaker.setFreq(1000, 0.03) print "set speaker volume low" speaker.setVolumeLow() print "play the same tune for 10 times" for i in range(10): speaker.setFreq(200, 0.03) speaker.setFreq(500, 0.03) speaker.setFreq(1000, 0.03) print "turn speaker off" speaker.speakerOff()
ad75fca23576922d2cb4e36658a86bce443e2fc7
cloudmesh/cloudmesh-pi
/cloudmesh/pi/led.py
1,635
3.640625
4
"""Usage: led.py [-h] pin=PIN Demonstarte a blining LED on given PIN Arguments: PIN The PIN number [default: 3]. Options: -h --help """ from docopt import docopt import time import grovepi import sys class LED(object): def __init__(self, pin=3): """ Connect the LED to a digital port. 3 is default. :param pin: Integer """ self.pin = pin grovepi.pinMode(self.pin, "OUTPUT") def on(self): """ turns LED on. :return: None """ grovepi.digitalWrite(self.pin, 1) # Send HIGH to switch on LED def off(self): """ turns LED off. :return: None """ grovepi.digitalWrite(self.pin, 0) # Send LOW to switch off LED def blink(self, n, t=0.2): """ blinks LED n times with t time delay. Default t is .2 seconds. :param n: Integer :param t: Number :return: None """ for i in range(0, n): try: # LED on self.on() time.sleep(t) # duration on # LED off self.off() time.sleep(t) #duration off except KeyboardInterrupt: # Turn LED off before stopping grovepi.digitalWrite(self.pin, 0) sys.exit() break except IOError: # Print "Error" if communication error encountered print ("Error") if __name__ == "__main__": # arguments = docopt(__doc__) # pin = arguments['PIN'] # led = LED(pin=pin) led = LED(pin=3) led.blink(5)
4601288128d4c43f69a2bb9b0ef6c8a28d67ee55
cloudmesh/cloudmesh-pi
/cloudmesh/pi/led_bar.py
903
3.765625
4
import time import grovepi class LedBar: def __init__(self, pin=3, color = 0): """ color = 0 starts counting led 1 from the Red LED end color = 0 starts counting led 1 from the green LED end """ self.ledbar = pin grovepi.ledBar_init(self.ledbar,color) def setLevel(self,level = 0): """ level = 1-10 level - 5 turns on LEDs 1 to 5 """ grovepi.ledBar_setLevel(self.ledbar,level) def setLED(self, led=1, status=0): """ led= number of led to set: 1- 10 status 1= on, 0 = off """ grovepi.ledBar_setLed(self.ledbar,led,status) def toggleLED(self, led=0): """ Inverts the status of the led """ grovepi.ledBar_toggleLed(self.ledbar,led) if __name__ == '__main__': ledbar = LedBar() ledbar.setLevel(5) time.sleep(0.2) ledbar.setLED(9,1) while True: ledbar.toggleLED(2) time.sleep(0.2)
28295bc71fba86b113b197459dbf24cbb4ffaf41
prasad2012/longtime
/src/squares.py
245
4.09375
4
def my_square(x): """takes a value and returns the square of it by using ** """ return(x ** 2) def my_square2(y): """takes a value and returns the square of it by using ** """ return(y ** 2) print(my_square(5)) print(my_square2(6))
20a3f9fa7dfe64042baf3ba500d6f2a583b4c324
alex7071/AOC
/Day2P1.py
788
3.78125
4
import numpy as np def read_strings(): filepath = "Day2P1.txt" stringList = [] with open(filepath) as fp: for line in fp: stringList.append(line) return stringList def frequency_count(text): #elem is an array of the unique elements in a string #and count is its corresponding frequency elem, count = np.unique(tuple(text), return_counts=True) print(count) return count def main(): textStringList = read_strings() twoFreq=0 threeFreq=0 for txt in textStringList: freqCountList = frequency_count(txt) if 2 in freqCountList: twoFreq += 1 if 3 in freqCountList: threeFreq += 1 checksum = twoFreq * threeFreq print(checksum) if __name__ == '__main__': main()
eabf59ece386cef321e8a639ee6fb75af265df83
dotXem/pcLSTM
/postprocessing/rescaling.py
415
3.6875
4
def rescaling(results, mean, std): """ Scale back the results that have previously been standardized. :param results: results of shape (None, 2) :param mean: vector of mean values (one per initial feature) :param std: vector of std values (one per initial feature) :return: rescaled results """ min_y, max_y = mean[-1], std[-1] return results * max_y + min_y
ef3f6373867dbacee7aae3af141d9fcd1edbd311
PabloG6/COMSCI00
/Lab4/get_next_date_extra_credit.py
884
4.28125
4
from datetime import datetime from datetime import timedelta '''the formatting on the lab is off GetNextDate(day, month, year, num_days_forward) would not return 9/17/2016 if GetNextDate(2, 28, 2004) is passed because 28 is not a month. ''' def GetNextDate(day, month, year, num_days_forward): num_days_forward = int(num_days_forward) if (type(num_days_forward) == str) else num_days_forward day = str(day).zfill(2) month = str(month).zfill(2) year = str(year).zfill(2) date = '{0}/{1}/{2}'.format(day, month, year) new_date = datetime.strptime(date, '%d/%m/%Y') new_date += timedelta(days=num_days_forward) new_date = new_date.strftime('%m/%d/%Y') return new_date print(GetNextDate(input("Please enter the day: "), input("Please enter the month: "), input("Please enter the year: "), input("Enter number of days forward: ")))
e5b776388e4d7ae5bab7891ed36d53ae14dfdc4d
PabloG6/COMSCI00
/Lab2/kind_of_a_big_deal.py
209
3.9375
4
minutes = float(input("Minutes: ")) num_hours = minutes//60 num_minutes = minutes%60 num_seconds = 60*(num_minutes%1) print(int(num_hours), "hours", int(num_minutes), "minutes", int(num_seconds), "seconds")
af817ff14fbc1b00968c49da3f427ddb3d75622d
PabloG6/COMSCI00
/Lab2/moon_earths_moon.py
279
4.125
4
first_name = input("What is your first name?") last_name = input("What is your last name?") weight = int(input("What is your weight?")) moon_gravity= 0.17 moon_weight = weight*moon_gravity print("My name is", first_name, last_name+".", "And I weigh", moon_weight, "on the moon")
81d8c252747fb1a2f801e779a5c378f1f79b3dd3
irfanki/HackerRanker
/machine_learning/compute_Karl_Pearson’s_coefficient.py
492
3.53125
4
from math import * x = [15, 12, 8, 8, 7, 7, 7, 6, 5, 3] y = [10, 25, 17, 11, 13, 17, 20, 13, 9, 15] # Calculating the mean x_mean = sum(x)/len(x) y_mean = sum(y)/len(y) diff_x_mean = [(i - x_mean) for i in x] diff_y_mean = [(i - y_mean) for i in y] xx = sum([(i - x_mean)**2 for i in x]) yy = sum([(i - y_mean)**2 for i in y]) sum_diff = [] for i in range(len(x)): sum_diff.append(diff_x_mean[i] * diff_y_mean[i]) r = sum(sum_diff)/sqrt(xx * yy) result = round(r, 3) print(result)
683ce144348dbb8d1f15f38ada690d70e9b1a22f
joeschweitzer/board-game-buddy
/src/python/bgb/move/move.py
827
4.3125
4
class Move: """A single move in a game Attributes: player -- Player making the move piece -- Piece being moved space -- Space to which piece is being moved """ def __init__(self, player, piece, space): self.player = player self.piece = piece self.space = space class MoveHistory: """Records a move that was made Attributes: move -- Move that was made time -- Time move was made """ def __init__(self, move, time): self.move = move self.time = time class InvalidMoveError(Exception): """Error thrown for invalid move Attributes: value -- Error string """ def __init__(self, value): self.value = value def __str__(self): return repr(self.value)
5d04f60a21a7c031213744c2ae2e779a223e2ca2
2020668/api_automation_course
/util/base/list_demo.py
280
3.53125
4
# -*- coding: utf-8 -*- """ ================================= Author: keen Created on: 2020/8/7 E-mail:keen2020@outlook.com ================================= """ # 索引取值 从前到后 从0开始 反向从-1开始 b = [1, 2, 3, 4] print(b[0]) print(b[1]) print(b[-1])
e88ec5b3aa79dfa449dad5726912937eddbdeb96
2020668/api_automation_course
/util/thread_demo.py
1,631
3.5625
4
# -*- coding: utf-8 -*- """ ================================= Author: keen Created on: 2020/7/27 E-mail:keen2020@outlook.com ================================= """ import time import threading def demo1(): for i in range(2): print("正在加载中...") # 获取当前执行的线程 print("当前活跃的线程有:{}".format(threading.current_thread())) time.sleep(1) def demo2(): for i in range(3): print("正在登录...") # 获取当前执行的线程 print("当前活跃的线程有:{}".format(threading.current_thread())) time.sleep(1) # 创建一个子线程执行demo1 并为线程设置name t1 = threading.Thread(target=demo1, name="thread1") # 创建一个子线程执行demo2 并为线程设置name t2 = threading.Thread(target=demo2, name="thread2") start_time = time.time() # 执行子线程1 t1.start() # 执行子线程2 t2.start() # 获取线程的名称 print(t1.name) print(t2.name) # 获取当前执行的线程 print("当前活跃的线程有:{}".format(threading.current_thread())) # 获取正在运行的所有线程 print("正在运行的所有线程:{}".format(threading.enumerate())) # 获取正在运行的线程数量 print("正在运行的线程数量:{}".format(threading.active_count())) # 等待子线程2执行完毕 再继续执行主线程 可传参数 等待子线程执行几秒后再执行主线程 这个时间不能大于子线程执行完毕所需的时间 # 可等待多个线程 耗时累计 一般不会设置时间 t2.join() end_time = time.time() print("程序运行耗时:{}".format(end_time - start_time))
38e2624ef1a24be287c62b638819a8338ec6fbb3
junyi1997/python-class
/20190321/20190321.py
267
3.6875
4
# -*- coding: utf-8 -*- import turtle #from turtle import* t=turtle.Turtle() s=turtle.Screen() ''' t=Turtle() s=Screen() ''' def my_rect(): t.begin_fill() for i in range(4): t.forward(100) t.left(90) t.end_fill() my_rect() s.mainloop()
d34b71724d35e5e90fe9181bcaa23d4be637d072
h4x0rlol/PythonLabs
/lab_3_4_5/2.py
117
3.5
4
n = int(input('n: ')) sum = 0 # 1 while (n > 0): sum += n n -= 1 # 2 for i in range(0, n+1): sum += i
2b0293a0bd0452e9e94a7c6aea0d13a803cc9dbd
Demesaikiran/MyCaptainAI
/Fibonacci.py
480
4.21875
4
def fibonacci(r, a, b): if r == 0: return else: print("{0} {1}".format(a, b), end = ' ') r -= 1 fibonacci(r, a+b, a+ 2*b) return if __name__ == "__main__": num = int(input("Enter the number of fibonacci series you want: ")) if num == 0 or num < 0: print("Incorrect choice") elif num == 1: print("0") else: fibonacci(num//2, 0, 1)
856baf6c40ff468515c09acab0971498025ad832
zhongyusheng/store
/旅游导航.py
6,298
3.5
4
def goshoping() : money = input("请输入您的支付宝余额:") money = int(money) laoganma = 1 lenovo = 1 shop = [ ["劳力士手表", 200000], ["Ipone 12X plus", 12000], ["lenovo PC", 6000], ["HUA WEI WATCH", 1200], ["Mac PC", 15000], ["辣条", 2.5], ["老干妈", 13] ] choose1 = input("您是否需要抽取1张优惠券,如果输入‘是’将会随机抽取一张购物优惠券,如果输入‘否’将会正常购物 请输入:") if choose1 == "是": import random card = random.randint(0, 29) if 0 <= card and card <= 9: laoganma = 0.7 print("\033[31m恭喜您获得老干妈7折优惠券一张\033[0m") print("\033[32m欢迎您进入购物界面:\033[0m") new1 = laoganma * shop[6][1] shop[6] = ["老干妈 折后价为:", new1] else: lenovo = 0.1 print("\033[31m恭喜您获得联想电脑1折优惠券一张\033[0m") print("\033[32m欢迎您进入购物界面:\033[0m") new2 = lenovo * shop[2][1] shop[2] = ["lenovo PC 折后价为:", new2] elif choose1=="是": shop = [ ["劳力士手表", 200000], ["Ipone 12X plus", 12000], ["lenovo PC", 6000], ["HUA WEI WATCH", 1200], ["Mac PC", 15000], ["辣条", 2.5], ["老干妈", 13] ] else: print("别瞎弄!请输入正确字符!您的折扣券飞了!!") mycard = [] i = 0 while i < 20: for key, value in enumerate(shop): print(key, value) choose2 = input("请输入您要选择的商品编号:") if choose2.isdigit(): choose2 = int(choose2) if choose2 > 6: print("\033[31m您输入的商品不存在,别瞎弄!\033[0m") else: if money >= shop[choose2][1]: money = money - shop[choose2][1] print("\033[32m恭喜您购买商品成功!\033[0m") print("您现在的余额为:", money) mycard.append(shop[choose2]) else: print("您的余额不足,请进行充值!") elif choose2 == "q" or choose2 == "Q": print("\033[32m欢迎下次光临\033[0m") break else: print("\033[31m输入有误,请重新输入!\033[0m") i = i + 1 choose3 = input("是否需要打印购物清单?") if choose3 == "是": print("您的购物清单如下:") for key, value in enumerate(mycard): print(key, value) print("您的余额为:", money) print("欢迎您下次光临!") else: print("欢迎您下次光临!") return def shopping() : choose4=input("是否购买土特产?") if choose4=="是": goshoping() elif choose4=="否": print("好嘞!拜拜!") else: print("别瞎弄!重输!") data={ "北京":{ "昌平":{ "十三陵":["十三陵水库","沙河水库"], "高校":["北京邮电大学","中央戏剧学院","北京师范大学","华北电力大学"], "天通苑":["海底捞","呷哺呷哺"] }, "海淀":{ "公主坟":["军事博物馆","中华世纪园"], "科普场馆":["中国科技馆","北京天文馆"], "高校":["北京大学","清华大学"], "景区":["北京植物园","香山公园","玉渊潭公园"] }, "朝阳":{ "龙城":["鸟化石国家地质公园","朝阳南北塔"], "双塔":["朝阳凌河公园","朝阳凤凰山"] }, "延庆":{ "龙庆峡":["龙庆峡景区"] } }, "四川":{ "成都":{ "高升桥":["锦里古街","成都武侯祠"], "成华区":["成都大熊猫繁育研究基地","升仙湖","多宝寺公园"], "都江堰市":["都江堰景区","青城山景区","青城后山"], "青龙":["成都动物园","昭觉寺"], "东大街":["春熙路"], "人民中路":["天府广场","成都博物馆"], "天府新区":["黄龙溪","成都海昌极地海洋公园","南湖公园"], "龙泉驿区":["洛带古镇","龙泉山风景区","蔚然花海","龙泉山城市森林公园"] } } } def print_place(choice): for i in choice: print(i) for i in data: print(i) city1=input("请输入您要去的地区:") while True: if city1 in data: print_place(data[city1]) city2=input("请输入二级地区:") if city2 in data[city1]: choose5=input("您是选择进入商场?还是浏览下级地区景点?进入商城请输入1,浏览下级地区请输入2:") choose5 = int(choose5) if choose5==1: shopping() break elif choose5==2: print_place(data[city1][city2]) city3=input("请输入三级地区:") if city3 in data[city1][city2]: print_place(data[city1][city2][city3]) shopping() elif city3 == "q" or city3 == "Q": print("欢迎下次使用本系统!") break else: print("当前三级地区未录入,别瞎搞!请输入其他地区!") else: print("别瞎弄!重输!") elif city2 == "q" or city2 == "Q": print("欢迎下次使用本系统!") break else: print("当前二级地区未录入,别瞎搞!请输入其他地区!") elif city1=="q" or city1=="Q": print("欢迎下次使用本系统!") break else: print("当前地区未录入,别瞎搞!请输入其他地区!") break
95b08d13183f9aebc8a6ac5fa10284a33bc6a517
hauckc21/python-challenge
/PyPoll/main.py
2,176
3.890625
4
import os import csv #Define variables total_votes = 0 candidates = {} #Store csv file path csvpath = os.path.join('Resources', '02-Homework_03-Python_Instructions_PyPoll_Resources_election_data.csv') #Open csv in read mode with open (csvpath) as csvfile: csv_reader = csv.reader(csvfile, delimiter=",") #Read the header row csv_header = next(csvfile) #Read through each row of data after the header for row in csv_reader: #Count total votes total_votes = total_votes + 1 #search for name in dataset name = row[2] if name not in candidates: #add the candidate to candidates dictionary candidates[name] = 1 #Move and and find next candidates name else: candidates[name] = candidates[name] + 1 #Print results to terminal print("Election Results") print("-----------------------") print(f"Total Votes: {total_votes}") print("-----------------------") for candidate_name, vote_count in candidates.items(): percentage = round((vote_count / total_votes * 100), 3) print(f"{candidate_name}: {percentage}% ({vote_count})") print("-----------------------") winner = sorted(candidates.items(), reverse=False) print("Winner:" + str(winner[1][0])) print("-----------------------") #Export text file with results election_analysis = os.path.join("Analysis", "election_analysis.txt") with open(election_analysis, "w") as outfile: outfile.write("Election Results\n") outfile.write("-----------------------\n") outfile.write(f"Total Votes: {total_votes}\n") outfile.write("-----------------------\n") for candidate_name, vote_count in candidates.items(): percentage = round((vote_count / total_votes * 100), 3) outfile.write(f"{candidate_name}: {percentage}% ({vote_count})\n") outfile.write("-----------------------\n") winner = sorted(candidates.items(), reverse=False) outfile.write("Winner:" + str(winner[1][0])) outfile.write(" \n") outfile.write("-----------------------\n")
f8488e9528758acba0a6aa5833eea6c6ba13b98c
wakashijp/study-python
/Learning-Python3/Chapter10/Section10-1/dice_game2.py
603
3.78125
4
from random import randint # サイコロを定義する def dice(): num = randint(1, 6) return num # 2個のサイコロを振るゲーム def dicegame(): dice1 = dice() # 1個目のサイコロを振る dice2 = dice() # 2個目のサイコロを振る sum_number = dice1 + dice2 # 2個のサイコロの目の合計 if sum_number % 2 == 0: print(f"{dice1}と{dice2}で合計{sum_number}、偶数") else: print(f"{dice1}と{dice2}で合計{sum_number}、奇数") # dicegame()を5回行う for i in range(5): dicegame() print("ゲーム終了")
f914ab7f5a515256e17c49a1878fd7d889d1e8ba
wakashijp/study-python
/Learning-Python3/Chapter05/Section5-1/if_or.py
554
4
4
# randomモジュールのrandint関数を読み込む from random import randint size = randint(5, 20) # 5〜20の乱数を生成する。 weight = randint(20, 40) # 20〜40の乱数を生成する。 # 判定(どちらか片方でもTrueならば合格) if (size >= 10) or (weight >= 25): # orで連結しているので、2つの条件のどちらか一方でもTrueならば式はTrueになります。 result = "合格" else: result = "不合格" # 結果の出力 text = f"サイズ{size}、重量{weight}:{result}" print(text)
9f66c93bebd85232ea3646b96a3c6a5ff877ba2c
wakashijp/study-python
/Learning-Python3/Chapter05/Section5-2/while_else.py
663
3.9375
4
# randomモジュールからrandint関数を読み込む from random import randint numbers = [] # 空のリスト # numbersの値が10個になるまで繰り返す while len(numbers) < 10: n = randint(-10, 90) # -10〜90の乱数を生成する if n < 0: # nがマイナスならばブレイクする print("中断されました") break # elseブロックを実行せずに終了します if n in numbers: # nがnumbersに含まれていたらスキップする continue # numbersにnを追加する numbers.append(n) else: print(numbers) # 繰り返しが終わったら実行します
760684cec3d5bb0b3f4d81e136a9bd83301e43d0
wakashijp/study-python
/Learning-Python3/Chapter02/Section2-3/if.py
112
3.734375
4
a = 10 if a >= 0: print('0以上の値です') else: print('負の値です') print('判定終わり')
edd965cb5e4cd40f651a2ed14f0b422a708e4635
wakashijp/study-python
/Learning-Python3/Chapter05/Section5-3/for_else_break.py
439
3.953125
4
numlist = [3, 4.2, 10, "x", 1, 9] # 文字列が含まれている sum_value = 0 for num in numlist: # numが数値でない時は処理をブレイクする if not isinstance(num, (int, float)): print(num, "数値ではない値が含まれていました。") break # ブレイクする sum_value += num else: # breakされなかった時は合計した値を出力する print("合計", sum_value)
8aa75c2d3c2bde564d5a5baa30666d8f9d002985
Picolino66/resmat-1-2
/Resmat1/Natan/trampo.py
5,773
3.734375
4
from math import* #importa funções matemáticas import math #Função para pegar os valores do arquivo def criar_arq(): #funcao para ler os dados dos arquivos print ("Digite o nome do arquivo: ") arq=input() arqentrada = arq + '.dat' #junção de string para ler o nome do arquivo f = open(arqentrada, 'r') #abrir arquivo para leitura #ler as entradas do arquivo NC = int(f.readline()) a = [] NCV = 0 #caso for um em baixo do outro for i in range(NC): aaux = int(f.readline()) a.append(aaux) NCV = aaux + NCV px=[] py=[] for i in range(NCV): x, y = map(float, f.readline().split()) px.append(x) py.append(y) unidade = f.readline() return NC,NCV,a,px,py,arq, unidade def principal(): figuras,NCV,arestas,x,y,arqsaida, unidade = criar_arq() arqsaida = arqsaida + '.out' arquivo = open(arqsaida,'w')#abrir para escrever no arquivo arquivo.write("**** PROPRIEDADES GEOMÉTRICAS DAS FIGURAS PLANAS ****") arquivo.write ("\n") tam=NCV+1 i=0 j=0 k=0 aux=0 #aux identifica quando a figura estiver na ultimo ponto para poder fechar com o primeiro ponto prox=0 #prox armazena a posição inicial da figura ###AREA E PERIMETRO#### area=[] tarea=0.0 perimetro=[] tperimetro=0.0 area.append(0.0) perimetro.append(0.0) somap=0 somaa=0 #laço para fazer as equações for i in range(figuras): for j in range(arestas[i]): if(aux==(arestas[i]-1)): somap+=sqrt(((x[prox]-x[k])**2)+((y[prox]-y[k])**2)) somaa+=x[k]*y[prox]-x[prox]*y[k] else: somap+=sqrt(((x[k+1]-x[k])**2)+((y[k+1]-y[k])**2)) somaa+=x[k]*y[k+1]-x[k+1]*y[k] k+=1 aux+=1 perimetro.append(somap) area.append(somaa) aux=0 prox=arestas[i]+prox somaa=0 somap=0 for i in range(len(area)):#somar area,somar perimetro tarea+=area[i] tperimetro+=perimetro[i] tarea*=0.5 arquivo.write("A area da sua figura e: ") arquivo.write("{:.6f}".format(tarea)) arquivo.write(unidade+'²') arquivo.write('\n') arquivo.write("O perimetro de sua figura e: ") arquivo.write("{:.6f}".format(tperimetro)) arquivo.write(unidade) arquivo.write('\n') ##cacluco centro de gravidade x,y cgx=[] tcgx=0.0 cgy=[] tcgy=0.0 k=0 aux=0 prox=0 cgx.append(0.0) cgy.append(0.0) somax=0 somay=0 for i in range(figuras): for j in range(arestas[i]): if(aux==(arestas[i]-1)): somax+=((x[k]+x[prox])*(x[k]*y[prox]-x[prox]*y[k])) somay+=((y[k]+y[prox])*(x[k]*y[prox]-x[prox]*y[k])) else: somax+=((x[k]+x[k+1])*(x[k]*y[k+1]-x[k+1]*y[k])) somay+=((y[k]+y[k+1])*(x[k]*y[k+1]-x[k+1]*y[k])) k+=1 aux+=1 cgx.append(somax) cgy.append(somay) aux=0 prox+=arestas[i] somax=0 somay=0 for i in range(len(cgx)): tcgx+=cgx[i] tcgy+=cgy[i] tcgx/=(6*tarea) tcgy/=(6*tarea) arquivo.write("Coordenada do CG no eixo x: ") arquivo.write("{:.6f}".format(tcgx)) arquivo.write(unidade) arquivo.write('\n') arquivo.write("Coordenada do CG no eixo y: ") arquivo.write("{:.6f}".format(tcgy)) arquivo.write(unidade) arquivo.write('\n') ##momento inercia for i in range(NCV): x[i] = x[i] - tcgx y[i] = y[i] - tcgy Ix=[] tIx=0.0 Iy=[] tIy=0.0 Ixy=[] tIxy=0.0 a=[] k=0 aux=0 prox=0 Ix.append(0.0) Iy.append(0.0) Ixy.append(0.0) somaix=0 somaiy=0 somaixy=0 ax=0 for i in range(figuras): for j in range(arestas[i]): if(aux==(arestas[i]-1)): ax=((x[k]*y[prox])-(x[prox]*y[k])) a.append(ax) somaix+=a[k]*(pow(y[k],2)+y[k]*y[prox]+pow(y[prox],2)) somaiy+=a[k]*(pow(x[k],2)+x[k]*x[prox]+pow(x[prox],2)) somaixy+=a[k]*(x[prox]*y[prox]+2*x[k]*y[k]+2*x[prox]*y[prox]+x[k]*y[k]) else: ax=((x[k]*y[k+1])-(x[k+1]*y[k])) a.append(ax) somaix+=a[k]*(pow(y[k],2)+y[k]*y[k+1]+pow(y[k+1],2)) somaiy+=a[k]*(pow(x[k],2)+x[k]*x[k+1]+pow(x[k+1],2)) somaixy+=a[k]*(x[k+1]*y[k+1]+2*x[k]*y[k]+2*x[k+1]*y[k+1]+x[k]*y[k]) k+=1 aux+=1 aux=0 prox=arestas[i]+prox Ix.append(somaix) Iy.append(somaiy) Ixy.append(somaixy) somaix=0 somaiy=0 somaixy=0 for i in range(len(Ix)): tIx+=Ix[i] tIy+=Iy[i] tIxy+=Ixy[i] tIx = tIx/12 tIy = tIy/12 tIxy = tIxy/24 arquivo.write("Momento de inercia em x: ") arquivo.write("{:.6f}".format(tIx)) arquivo.write(unidade+'4') arquivo.write('\n') arquivo.write("Momento de inercia em y: ") arquivo.write("{:.6f}".format(tIy)) arquivo.write(unidade+'4') arquivo.write('\n') arquivo.write("Produto de inercia em xy: ") arquivo.write("{:.6f}".format(tIxy)) arquivo.write(unidade+'4') arquivo.write('\n') arquivo.write("Momento polar de Inercia: ") arquivo.write("{:.6f}".format(tIx+tIy)) arquivo.write(unidade+'4') arquivo.write('\n') ##MOMENTO DE INERCIA MAXIMO E MINIMO Imax = (tIx+tIy)/2 + sqrt(((tIx-tIy)/2)**2+(tIxy**2)) Imin = (tIx+tIy)/2 - sqrt(((tIx-tIy)/2)**2+tIxy**2) arquivo.write("O Imin de sua figura é: ") arquivo.write("{:.6f}".format(Imin)) arquivo.write(unidade+'4') arquivo.write('\n') arquivo.write("O Imax de sua figura é: ") arquivo.write("{:.6f}".format(Imax)) arquivo.write(unidade+'4') arquivo.write('\n') ##ANGULO PRINCIPAL TETA 1 E TETA 2 tetap1 = (math.atan(-tIxy/((tIx-tIy)/2)))/2 tetap1 = tetap1*180/math.pi tetap2 = tetap1 + 90 arquivo.write("O Tetap1 de sua figura é: ") arquivo.write(str(tetap1)) arquivo.write("º") arquivo.write('\n') arquivo.write("O Tetap2 de sua figura é: ") arquivo.write(str(tetap2)) arquivo.write("º") arquivo.write('\n') #RAIO DE GIRAÇÃO Kx = sqrt(Imax/tarea) Ky = sqrt(Imin/tarea) arquivo.write("O Rmin de sua figura: ") arquivo.write("{:.6f}".format(Ky)) arquivo.write(unidade) arquivo.write('\n') arquivo.write("O Rmax de sua figura: ") arquivo.write("{:.6f}".format(Kx)) arquivo.write(unidade) arquivo.write('\n') arquivo.close() print ("Arquivo salvo.") principal()
3c342d2651d4a45ceb042119999f3532221493ad
Rekkuj/pygame
/game.py
2,641
3.84375
4
# player_name = 'Rekku' # player_attack = 10 # player_heal = 16 # health = 100 # List: # player = ['Rekku', 10, 16, 100] # you can change the values in list: # player[1] = 11 # print(player['attack']) game_running = True while game_running == True: new_round = True # Dictionaries (key: value -pairs): player = {'name': 'Rekku', 'attack': 10, 'heal': 16, 'health': 100} monster = {'name': 'Max', 'attack': 12, 'health': 100} print('---' * 5) print('Enter Player name') player['name'] = input() print('---' * 5) # String concatenation can only concatenate string, not int, so we need to convert health into a string print(player['name'] + ' has ' + str(player['health']) + ' health') print(monster['name'] + ' has ' + str(monster['health']) + ' health') while new_round == True: player_won = False monster_won = False print('---' * 5) print('Please select action') print('1) Attack') print('2) Heal') print('3) Exit') player_choice = input() if player_choice == 1: monster['health'] = monster['health'] - player['attack'] if monster['health'] <= 0: # pass (pass is kind of a placeholder to tell python, that it can continue executing and to the author that the code is missing player_won = True else: player['health'] = player['health'] - monster['attack'] if player['health'] <= 0: monster_won = True elif player_choice == 2: print('Healing player...') player['health'] = player['health'] + player['heal'] player['health'] = player['health'] - monster['attack'] if player['health'] <= 0: monster_won = True elif player_choice == 3: new_round = False game_running = False print('Game Over') else: print('Invalid choice') if player_won == False and monster_won == False: print(player['name'] + ' has ' + str(player['health']) + ' left') print(monster['name'] + ' has ' + str(monster['health']) + ' left') elif player_won: print('Round Over. ' + player['name'] + ' won. Starting a new round..') new_round = False elif monster_won: print('Round Over. The Monster won. Starting a new round..') new_round = False if player_won == True or monster_won == True: new_round = False print('Round Over. Starting a new round..')
066eb39f5220714b49df4cf8a52267f1e59b52db
holtsho1/CS1301xIII
/CourseInfo.py
298
3.640625
4
def course_info(tup_list): course_dict={} course_dict["students"]=[] average=0 for tup in tup_list: course_dict["students"].append(tup[0]) average=average+tup[1] average=average/len(tup_list) course_dict["avg_age"]=average return course_dict
f19dab35f971baf9a8a62a0c92c36d775ab73365
kgolezardi/simulation-project
/pqueue.py
893
3.671875
4
import heapq import itertools class PriorityQueue: def __init__(self): self.heap = [] self.counter = itertools.count() self.entry_finder = {} self._size = 0 def size(self): return self._size def push(self, priority, x): count = next(self.counter) entry = [priority, count, x] self.entry_finder[x] = entry heapq.heappush(self.heap, entry) self._size += 1 def empty(self): return self._size == 0 def pop(self): while len(self.heap) > 0: priority, count, x = heapq.heappop(self.heap) if x is not None: del self.entry_finder[x] self._size -= 1 return priority, x raise KeyError def remove(self, x): entry = self.entry_finder.pop(x) self._size -= 1 entry[-1] = None
bb50b8feabc4e027222ed347042d5cefdf0e64da
abtripathi/data_structures_and_algorithms
/problems_and_solutions/arrays/Duplicate-Number_solution.py
1,449
4.15625
4
# Solution ''' Notice carefully that 1. All the elements of the array are always non-negative 2. If array length = n, then elements would start from 0 to (n-2), i.e. Natural numbers 0,1,2,3,4,5...(n-2) 3. There is only SINGLE element which is present twice. Therefore let's find the sum of all elements (current_sum) of the original array, and find the sum of first (n-2) Natural numbers (expected_sum). Trick: The second occurance of a particular number (say `x`) is actually occupying the space that would have been utilized by the number (n-1). This leads to: current_sum = 0 + 1 + 2 + 3 + .... + (n-2) + x expected_sum = 0 + 1 + 2 + 3 + .... + (n-2) current_sum - expected_sum = x Tada!!! :) ''' def duplicate_number(arr): current_sum = 0 expected_sum = 0 # Traverse the original array in the forward direction for num in arr: current_sum += num # Traverse from 0 to (length of array-1) to get the expected_sum # Alternatively, you can use the formula for sum of an Arithmetic Progression to get the expected_sum # The argument of range() functions are: # starting index [OPTIONAL], ending index (non exclusive), and the increment/decrement size [OPTIONAL] # It means that if the array length = n, loop will run form 0 to (n-2) for i in range(len(arr) - 1): expected_sum += i # The difference between the return current_sum - expected_sum
daddf0cf3602340d5b377400e31df7a681d110ea
CHB94git/Retos-Python-Ciclo1
/Reto1/CalcSquare.py
303
3.71875
4
def CalculadoraRectangulo(ancho:float, largo:float)->str: perimetro = (ancho*2) + (largo*2) area = ancho*largo print("El cuadrado tiene un perímetro de: " +str(perimetro) +" y un área de: " +str(area)) #Ingresar los parámetros con un solo decimal CalculadoraRectangulo(3.0, 2.5)
26d6e211c524aae3668176e7f54638f589b9226c
nicholasrokosz/python-crash-course
/Ch. 15/random_walk.py
945
4.25
4
from random import choice class RandomWalk: """Generates random walks.""" def __init__(self, num_points=5000): """Initializes walk attributes.""" self.num_points = num_points # Walks start at (0, 0). self.x_values = [0] self.y_values = [0] def fill_walk(self): """Calculate all the points in a walk.""" # Keep calculating random steps until number of steps is reached. while len(self.x_values) < self.num_points: # Randomly decide which direction and how far to step. x_direction = choice([1, -1]) x_distance = choice([0, 1, 2, 3, 4]) x_step = x_direction * x_distance y_direction = choice([1, -1]) y_distance = choice([0, 1, 2, 3, 4]) y_step = y_direction * y_distance # Reject non-steps. if x_step == 0 and y_step == 0: continue # Calculate the new position. x = self.x_values[-1] + x_step y = self.y_values[-1] + y_step self.x_values.append(x) self.y_values.append(y)
6405fb18f932d4ef96807f2dc65b04401f32e5be
nicholasrokosz/python-crash-course
/Ch. 10/favorite_number.py
467
4.125
4
import json def get_fav_num(): """Asks a user for their favorite number and stores the value in a .json file.""" fav_num = input("What is your favorite number? ") filename = 'fav_num.json' with open(filename, 'w') as f: json.dump(fav_num, f) def print_fav_num(): """Retrieves user's favoite number and prints it.""" filename = 'fav_num.json' with open(filename) as f: fav_num = json.load(f) print(f"I know your favorite number! It's {fav_num}.")
fe05cab40de57a35592c9273d23dd67e9f06a4ba
nicholasrokosz/python-crash-course
/Ch. 5/hello_admin.py
221
3.9375
4
users = ['admin', 'Nick', 'Nicole', 'Al', 'Pete', 'Michaela'] for user in users: if user == 'admin': print("Hello admin, would you like to see a status report?") else: print(f"Hello {user}, thanks for logging in.")
423045af400951a00f9e952f0e92757c77c2ff29
nicholasrokosz/python-crash-course
/Ch. 10/programming_poll.py
265
3.5625
4
prompt = "Why do you like programming? (enter 'q' to exit)\n\t" keep_going = True while keep_going: reason = input(prompt) if reason != 'q': with open('programming_poll.txt', 'a') as file_object: file_object.write(f"{reason}\n") else: keep_going = False