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
11159e9e46469e2c9f9a8a362fe590f55d292997
UnderDogLearning/python
/NumberGuessingGame.py
880
4.09375
4
# Number Guessing Game: import random guessesTaken = 0 print("Welcome to Gussing Game ") print("Hello! What is your name? ") myName = input() print('Well, ' + myName + ', I am thinking of a number between 1 and 20.') number = random.randint(1, 20) while guessesTaken < 6: print('Take a guess.') guess = int(input()) guessesTaken = guessesTaken + 1 if guess < number: print("The Guessed number is low than the actual number") elif guess > number: print("The Guessed Number is higher than the actual Number") else: break if guess == number: print(f"Your Number matches with the Actual Number and you have gussed in {guessesTaken} Guesses!") if guess != number: print(f"You have not able to guess the actual number in {guessesTaken} Guesses!")
9e0a3cf48f109d1764db5939e030cfcee7d692e2
UnderDogLearning/python
/complex_json.py
2,039
3.78125
4
# Handing the Json nested file: #work with complex Json and extract data from it #Iterate through Json data which has list, json string, nested Json. Here I will explain how to work with complex Json and extract data from it import json def checkList(ele, prefix): for i in range(len(ele)): if (isinstance(ele[i], list)): checkList(ele[i], prefix+"["+str(i)+"]") elif (isinstance(ele[i], str)): printField(ele[i], prefix+"["+str(i)+"]") else: checkDict(ele[i], prefix+"["+str(i)+"]") def checkDict(jsonObject, prefix): for ele in jsonObject: if (isinstance(jsonObject[ele], dict)): checkDict(jsonObject[ele], prefix+"."+ele) elif (isinstance(jsonObject[ele], list)): checkList(jsonObject[ele], prefix+"."+ele) elif (isinstance(jsonObject[ele], str)): printField(jsonObject[ele], prefix+"."+ele) def printField(ele, prefix): print (prefix, ":" , ele) data = {'field1': 'hello1', 'field2': 'hello2', 'NestedJson': {'Field': 'helloNested1', 'List': [{'f01': 'v01', 'f02': 'v02'}, {'f11': 'v11'}], 'NestedNestedJson': {'Field1': 'value1', 'Field2': 'value2'} }, 'List': [{'a1': 'b1'}, {'a1': 'b1'}], 'ElementList': ['ele1', 'ele2', 'ele3'] } # if data is in the file then: """with open('data1.txt') as outfile1: data = json.load(outfile1)""" #Iterating all the fields of the JSON for element in data: #If Json Field value is a Nested Json if (isinstance(data[element], dict)): checkDict(data[element], element) #If Json Field value is a list elif (isinstance(data[element], list)): checkList(data[element], element) #If Json Field value is a string elif (isinstance(data[element], str)): printField(data[element], element)
f74e3aaff1778023fc4d7180c9c3e7a96cd871ee
MatthewGerges/CS50-Programming-Projects
/MatthewGerges-cs50-problems-2021-x-sentimental-readability/readability.py
2,780
4.125
4
from cs50 import get_string # import the get_string function from cs50's library def main(): # prompt the user to enter a piece of text (a paragraph/ excerpt) paragraph1 = get_string("Text: ") letters = count_letters(paragraph1) # the return value of count_letters (how many letters there are in a paragraph) is assigned to the variable letters words = count_words(paragraph1) # the variable words is assigned the return value of the count_words function (tells you how many words are in a paragraph) sentences = count_sentences(paragraph1) # the variable sentences is assigned the return value of the count_sentences function(tells you how many sentences are in a paragraph) # letters100 is automatically converted to a double in python letters100 = (letters * 100) / words # calculate the average number of letters and sentences per 100 words in the text sentences100 = (sentences * 100) / words formula = (0.0588 * letters100) - (0.296 * sentences100) - 15.8 # The above is Coleman-Liau formula, whose rounded value tells you the grade-reading level of a particular text grade = round(formula) # if formula gives you a number between 1 and 16, print that number as the grade reading level if (grade >= 1 and grade < 16): print(f"Grade {grade}") # if the formula gives you a number that it is not in that range, specify if it is too low or too high of a reading level elif (grade < 1): print("Before Grade 1") elif (grade >= 16): print("Grade 16+") # count the letters in the paragraph by checking the if the letters are alphabetical def count_letters(paragraph): letters = 0 for char in paragraph: if char.isalpha(): # char.isalpha() returns true if a character is a letter and false otherwise letters += 1 return letters # count the words in the paragraph by adding 1 to the number of spaces def count_words(paragraph): words = 1 for i in range(len(paragraph)): if (" " == paragraph[i]): words += 1 return words # count the number of sentences by counting the number of punctuation marks in the paragraph (compare strings and add to a counting variable) def count_sentences(paragraph): sentences = 0 for i in range(len(paragraph)): # check for periods, exclamations, and question marks if (paragraph[i] == "." or paragraph[i] == "!" or paragraph[i] == "?"): sentences += 1 return sentences main() ''' # This is how to iterate through each character in a string and check if it is a letter s = 'a123b' for char in s: print(char, char.isalpha()) '''
5c5f1801b51078fdbaf5274ba0100cd2071eb38c
MatthewGerges/CS50-Programming-Projects
/MatthewGerges-cs50-labs-2021-x-birthdays/application.py
2,439
3.78125
4
import os from cs50 import SQL from flask import Flask, flash, jsonify, redirect, render_template, request, session # Configure application app = Flask(__name__) # Ensure templates are auto-reloaded app.config["TEMPLATES_AUTO_RELOAD"] = True # Configure CS50 Library to use SQLite database db = SQL("sqlite:///birthdays.db") # Here we are creating a database equal to the SQL birthday database @app.route("/", methods=["GET", "POST"]) # / is the default route - the index homepage # 2 methods are allowed on the homepage - get which displays the content of the URL and post which allows users to submit the form def index(): # If the user submits the form (using POST), store their name, month and day entered as variables if request.method == "POST": #These variables are created by accessing the names of the inputs in the index.html file name = request.form.get("name") month = request.form.get("birthmonth") day = request.form.get("birthday") id = request.form.get("id") act = request.form.get("act") #allow a user to register or deregister based on what they typed in the act field if act.lower() == "deregister": # Forget the person and their data (birthday) db.execute("DELETE FROM birthdays WHERE id = ?", id) # if not name or not birthday: # TODO: Add the user's entry into the database # enter the name, month and day variables of the user into the sql database else: # only if you give a new unique id (number), you can register if id: db.execute("INSERT INTO birthdays (name, month, day, id) VALUES(?, ?, ?, ?)", name, month, day, id) # This line confirms their birthday entry/form submission; it reloads the page return redirect("/") else: # TODO: Display the entries in the database on index.html (via GET! before a user submits) # Bdays is a list; a vraible that is set equal to the table from the SQL database Bdays = db.execute("SELECT * FROM birthdays") # select * = select all rows # direct the user to the index.html page; the index page will use a Bdays variable somewhere in there # we are passing this variable based on our query and work in this application.py file return render_template("index.html", Bdays = Bdays)
da488efb041e58f2e67718c7ee4fd4293b36e223
kvamsi7/Python_L2_Assignments
/prgm3.py
211
3.5
4
''' handling exception''' c = 0 def f2(x): try: c+= 1 b = x + c print(c) return b except Exception as err: print(err) print(f2(1)) print(c)
a0b908959d6c6bbd6d902b061b41258fce2bcae7
LandscapeGeoinformatics/GRQA_src
/preprocessing/GLORICH/glorich_preprocessing.py
14,072
3.546875
4
# Import the libraries import datetime import os import geopandas as gpd import pandas as pd import numpy as np import hashlib # Function for stripping whitespace from string columns def strip_whitespace(df): for col in df.columns: if df[col].dtype == object: df[col] = df[col].str.strip() return df # Function for replacing semicolons and line breaks def replace_chars(df): for col in df.columns: if df[col].dtype == object: df[col] = df[col].str.replace(';', ',') df[col] = df[col].str.replace('\n', '') df[col] = df[col].str.replace('\r', ' ') return df # Function to check if the date is valid def check_date(row, date_col): correct_date = False date_strings = str(row[date_col]).split('-') if len(date_strings) >= 3: year, month, day = int(date_strings[0]), int(date_strings[1]), int(date_strings[2]) datetime.datetime(year, month, day) correct_date = True else: print(f'Date error at row {row.name}') print(row) print('\n') return correct_date # Function for creating dictionary containing file information def get_file_info(file_path, row_count, file_desc, sheet_name=None): info_dict = {} info_dict['File name'] = os.path.basename(file_path) info_dict['Size (MB)'] = round(int(os.path.getsize(file_path)) / (1024 * 1024), 1) info_dict['Rows'] = row_count info_dict['Description'] = file_desc if sheet_name: info_dict['Sheet name'] = sheet_name return info_dict # Function for creating DF of missing values def get_missing_values(df, file_name, sheet_name=None): mv_df = df.isnull().sum(axis=0).reset_index() mv_df.columns = ['Column name', 'Missing values'] mv_df['File name'] = os.path.basename(file_name) mv_df = mv_df[['File name', 'Column name', 'Missing values']] if sheet_name: mv_df['Sheet name'] = sheet_name mv_df = mv_df[['File name', 'Sheet name', 'Column name', 'Missing values']] return mv_df # Function for getting statistics of water quality parameter time series def get_param_stats(value_col, date_col): stats_dict = {} stats_dict['count'] = value_col.count() stats_dict['min'] = value_col.min() stats_dict['max'] = value_col.max() stats_dict['mean'] = value_col.mean() stats_dict['median'] = value_col.median() stats_dict['std'] = value_col.std() year_col = date_col.str.split('-').str[0] year_col = year_col.astype(int) stats_dict['min_year'] = year_col.min() stats_dict['max_year'] = year_col.max() stats_dict['ts_length'] = stats_dict['max_year'] - stats_dict['min_year'] return pd.Series( stats_dict, index=['count', 'min', 'max', 'mean', 'median', 'std', 'min_year', 'max_year', 'ts_length'] ) # Function for getting a DF with parameter statistics def get_stats_df(df, groupby_cols, value_col, date_col): stats_df = df.groupby(groupby_cols)\ .apply(lambda group: get_param_stats(group[value_col], group[date_col]))\ .reset_index() for col in ['count', 'min_year', 'max_year', 'ts_length']: stats_df[col] = stats_df[col].astype(np.int32) return stats_df # Name of the dataset ds_name = 'GLORICH' # Directory paths # proj_dir = '/gpfs/space/home/holgerv/gis_holgerv/river_quality' # raw_dir = os.path.join(proj_dir, 'data', ds_name, 'raw') # proc_dir = os.path.join(proj_dir, 'data', ds_name, 'processed') # Directory paths proj_dir = '/gpfs/terra/export/samba/gis/holgerv' raw_dir = os.path.join(proj_dir, 'river_quality', 'data', ds_name, 'raw') proc_dir = os.path.join(proj_dir, 'GRQA_v1.3', 'GRQA_source_data', ds_name, 'processed') # Download directory dl_dir = os.path.join(raw_dir, 'download_2020-11-16') # Import the code map # cmap_file = os.path.join(raw_dir, 'meta', ds_name + '_code_map.csv') cmap_file = os.path.join(proj_dir, 'GRQA_v1.3', 'GRQA_source_data', ds_name, 'raw', 'meta', ds_name + '_code_map.csv') cmap_df = pd.read_csv(cmap_file, sep=';') param_codes = cmap_df['source_param_code'].to_list() # Import site point data site_file = os.path.join(dl_dir, 'Shapefiles_GloRiCh/Shapes_GloRiCh/Sampling_Locations_v1.shp') site_df = gpd.read_file(site_file) site_df = strip_whitespace(site_df) site_df = replace_chars(site_df) site_df.drop_duplicates(inplace=True) # Get site file information and append to list info_dicts = [] info_dicts.append(get_file_info(site_file, len(site_df), 'Site point data')) # Get missing values and append to list mv_dfs = [] mv_dfs.append(get_missing_values(site_df, site_file)) # Add latitude and longitude column site_df['lat_wgs84'] = site_df['geometry'].y site_df['lon_wgs84'] = site_df['geometry'].x # Drop sites with missing or implausible location information site_df.drop(site_df[(site_df['STAT_ID'].isnull())].index, inplace=True, errors='ignore') site_df.drop( site_df[(site_df['lat_wgs84'].isnull()) & (site_df['lon_wgs84'].isnull())].index, inplace=True, errors='ignore' ) site_df.drop( site_df[(site_df['lat_wgs84'] < -90) & (site_df['lat_wgs84'] > 90)].index, inplace=True, errors='ignore' ) site_df.drop( site_df[(site_df['lon_wgs84'] < -180) & (site_df['lon_wgs84'] > 180)].index, inplace=True, errors='ignore' ) # Get duplicate sites and export to CSV dup_sites = site_df[site_df.duplicated(['STAT_ID'])]['STAT_ID'].to_list() dup_df = site_df.loc[site_df['STAT_ID'].isin(dup_sites)].sort_values('STAT_ID') dup_df.to_csv(os.path.join(proc_dir, 'meta', ds_name + '_dup_sites.csv'), sep=';', index=False, encoding='utf-8') # Keep first instance of duplicate site ID site_df.drop_duplicates(subset='STAT_ID', keep='first', inplace=True) # Import site name data sname_file = os.path.join(dl_dir, 'sampling_locations.csv') sname_dtypes = { 'STAT_ID': np.int64, 'STATION_NAME': object, 'Country': object, 'Latitude': np.float64, 'Longitude': np.float64 } sname_df = pd.read_csv( sname_file, sep=',', usecols=sname_dtypes.keys(), dtype=sname_dtypes, skipinitialspace=True, quotechar='"', encoding='latin-1' ) sname_df = strip_whitespace(sname_df) sname_df = replace_chars(sname_df) sname_df.drop_duplicates(inplace=True) info_dicts.append(get_file_info(sname_file, len(sname_df), 'Site name data')) mv_dfs.append(get_missing_values(sname_df, sname_file)) # Import catchment data catchment_file = os.path.join(dl_dir, 'catchment_properties.csv') catchment_dtypes = { 'STAT_ID': np.int64, 'Shape_Area': np.float64 } catchment_df = pd.read_csv(catchment_file, sep=',', usecols=catchment_dtypes.keys(), dtype=catchment_dtypes, skipinitialspace=True, quotechar='"') catchment_df = strip_whitespace(catchment_df) catchment_df = replace_chars(catchment_df) catchment_df.drop_duplicates(inplace=True) info_dicts.append(get_file_info(catchment_file, len(catchment_df), 'Catchment data')) mv_dfs.append(get_missing_values(catchment_df, catchment_file)) # Import remark data remark_file = os.path.join(raw_dir, 'meta', ds_name + '_remark_codes.csv') remark_df = pd.read_csv(remark_file, sep=';') # Import observation data obs_file = os.path.join(dl_dir, 'hydrochemistry.csv') obs_dtypes = { 'STAT_ID': np.int64, 'RESULT_DATETIME': object } value_cols = param_codes remark_cols = [code + '_vrc' for code in param_codes] for value_col, remark_col in zip(value_cols, remark_cols): obs_dtypes[value_col] = np.float64 obs_dtypes[remark_col] = object obs_reader = pd.read_csv(obs_file, sep=',', usecols=obs_dtypes.keys(), dtype=obs_dtypes, chunksize=100000, skipinitialspace=True, quotechar='"') # Process observation data in chunks obs_row_count = 0 obs_chunks = [] for obs_chunk in obs_reader: obs_row_count += len(obs_chunk) obs_chunk = strip_whitespace(obs_chunk) obs_chunk = replace_chars(obs_chunk) obs_chunk.drop_duplicates(inplace=True) value_chunk = pd.melt( obs_chunk, id_vars='STAT_ID', value_vars=value_cols, var_name='source_param_code', value_name='source_obs_value' ) remark_chunk = pd.melt( obs_chunk, id_vars='RESULT_DATETIME', value_vars=remark_cols, var_name='remark_code', value_name='remark' ) obs_chunk = pd.concat([value_chunk, remark_chunk], axis=1) # Drop missing or negative values obs_chunk.drop( obs_chunk[(obs_chunk['source_obs_value'].isnull()) | (obs_chunk['source_obs_value'] <= 0)].index, inplace=True, errors='ignore' ) obs_chunks.append(obs_chunk) # DF of observations obs_df = pd.concat(obs_chunks) obs_df.drop_duplicates(inplace=True) obs_df.reset_index(drop=True, inplace=True) info_dicts.append(get_file_info(obs_file, obs_row_count, 'Water chemistry observations')) mv_dfs.append(get_missing_values(obs_df, obs_file)) # Create observation identifier column by hashing df_string = obs_df.to_string(header=False, index=False, index_names=False).split('\n') obs_strings = ['\t'.join(string.split()) for string in df_string] hash_ids = [hashlib.sha256(string.encode()).hexdigest() for string in obs_strings] obs_df['obs_id'] = hash_ids # Convert date to correct format and add time column obs_df['obs_date'] = pd.to_datetime(obs_df['RESULT_DATETIME'], format='%d/%m/%Y %H:%M:%S').dt.strftime('%Y-%m-%d') obs_df['obs_time'] = pd.to_datetime(obs_df['RESULT_DATETIME'], format='%d/%m/%Y %H:%M:%S').dt.strftime('%H:%M:%S') obs_df.drop(obs_df[(obs_df['obs_date'].isnull())].index, inplace=True, errors='ignore') # Check the validity of the dates and drop invalid dates obs_df['valid_date'] = obs_df.apply(check_date, date_col='obs_date', axis=1) obs_df = obs_df[obs_df['valid_date']] # Export file information to CSV info_df = pd.DataFrame(info_dicts) info_df.to_csv(os.path.join(proc_dir, 'meta', ds_name + '_file_info.csv'), sep=';', index=False, encoding='utf-8') # Export missing values to CSV mv_df = pd.concat(mv_dfs) mv_df.to_csv( os.path.join(proc_dir, 'meta', ds_name + '_missing_values.csv'), sep=';', index=False, encoding='utf-8' ) # Flag values that are marked as below and above detection limit in source data obs_df.loc[obs_df['remark'] == '<', 'detection_limit_flag'] = '<' obs_df.loc[obs_df['remark'] == '>', 'detection_limit_flag'] = '>' # Merge the DFs merged_df = site_df\ .merge(sname_df, how='left', on='STAT_ID')\ .merge(catchment_df, how='left', on='STAT_ID')\ .merge(obs_df, how='left', on='STAT_ID')\ .merge(cmap_df, how='left', on='source_param_code')\ .merge(remark_df, how='left', left_on='remark', right_on='Value remark code') merged_df.drop_duplicates(inplace=True) merged_df.reset_index(drop=True, inplace=True) merged_df.drop(merged_df[(merged_df['param_code'].isnull())].index, inplace=True, errors='ignore') merged_df.drop(merged_df[(merged_df['obs_date'].isnull())].index, inplace=True, errors='ignore') # Convert observation values merged_df['obs_value'] = merged_df['source_obs_value'] * merged_df['conversion_constant'] # Add filtration column merged_df.loc[merged_df['remark'] == 'U', 'filtration'] = 'unfiltered' # Get statistics about raw and processed observation values and export to CSV value_dict = {'raw': 'source_obs_value', 'processed': 'obs_value'} for value_type, value_col in value_dict.items(): stats_df = get_stats_df( merged_df, ['source_param_code', 'param_code', 'param_name', 'source_param_form', 'param_form', 'source_unit', 'unit'], value_col, 'obs_date' ) agg_stats_df = get_stats_df(merged_df, ['STAT_ID', 'source_param_code'], value_col, 'obs_date') agg_stats_df = agg_stats_df.groupby(['source_param_code'])\ .agg( site_count=('count', 'count'), mean_obs_count_per_site=('count', 'mean'), mean_ts_length_per_site=('ts_length', 'mean') ).reset_index() stats_df = stats_df.merge(agg_stats_df, on='source_param_code') fname = '_'.join([ds_name, value_type, 'stats.csv']) stats_df.to_csv(os.path.join(proc_dir, 'meta', fname), sep=';', index=False, encoding='utf-8') # Export processed data to CSV meta_cols = ['Value remark code', 'Meaning'] output_codes = merged_df['param_code'].unique() for code in output_codes: code_df = merged_df[merged_df['param_code'] == code] # Dictionary with output columns code_dict = { 'obs_id': code_df['obs_id'], 'lat_wgs84': code_df['lat_wgs84'], 'lon_wgs84': code_df['lon_wgs84'], 'obs_date': code_df['obs_date'], 'obs_time': code_df['obs_time'], 'obs_time_zone': np.nan, 'site_id': code_df['STAT_ID'], 'site_name': code_df['STATION_NAME'], 'site_country': code_df['Country'], 'upstream_basin_area': code_df['Shape_Area'], 'upstream_basin_area_unit': np.nan, 'drainage_region_name': np.nan, 'param_code': code_df['param_code'], 'source_param_code': code_df['source_param_code'], 'param_name': code_df['param_name'], 'source_param_name': code_df['source_param_name'], 'detection_limit_flag': code_df['detection_limit_flag'], 'obs_value': code_df['obs_value'], 'source_obs_value': code_df['source_obs_value'], 'param_form': code_df['param_form'], 'source_param_form': code_df['source_param_form'], 'unit': code_df['unit'], 'source_unit': code_df['source_unit'], 'filtration': code_df['filtration'], 'source': ds_name } # Add metadata columns to the dictionary for col in meta_cols: col_name = '_'.join([ds_name, 'meta', col]) col_name = col_name.replace(' ', '_') code_dict[col_name] = code_df[col] output_df = pd.DataFrame(code_dict) output_df.to_csv(os.path.join(proc_dir, code + '_' + ds_name + '.csv'), sep=';', index=False, encoding='utf-8')
0ccffb80d50c39d3ebcfaf6cc45db853762833b9
Augmented-Reality-Comps/backend
/walkAround/datasource.py
1,233
3.5
4
import psycopg2 class DataSource: def __init__(self): pass def getData(self, query): ''' this is the actual query to the database. every function that wants information from the database MUST call this function ''' # Login to the database connection = self.login() # Query the database try: cursor = connection.cursor() cursor.execute(query) return cursor.fetchall() except Exception, e: print 'Cursor error', e connection.close() exit() connection.close() def sendQueries(self, queries): ''' Execute a list of queries ''' connection = self.login() # Query the database try: cursor = connection.cursor() for query in queries: cursor.execute(query) except Exception, e: print 'Cursor error', e connection.close() exit() connection.commit() connection.close() def login(self): # Login to the database database = 'comps' user = 'comps' password='jeffcomps#1' try: connection = psycopg2.connect(database=database, user=user, password=password) except Exception, e: print 'Connection error: ', e exit() return connection
f3779d8bd7d12e4ca6f2fdb3d7710f9b14d91bf6
seabre/citybuilder
/cb-scripts/point-convert.py
448
3.640625
4
#!/usr/bin/python from sys import stdin def convert_point(lon_str, lat_str): lon = round(float(lon_str), 3) lat = round(float(lat_str), 3) return (lon, lat) def main(): lines = stdin.readlines() print "[" for l in lines: (lon_str, lat_str, _) = l.split(',') (lon, lat) = convert_point(lon_str, lat_str) print "\t[%.3f, %.3f]," %(lat, lon) print "]" if __name__ == '__main__': main()
602ea8ecddf9d0747115b17773236b33780a8507
TTUSDC/practical-python-sdc
/Week 1/notes/testing.py
1,407
4.1875
4
print("Hello World") pizza = 3 print(pizza) pizza = 3.3 print(pizza) pizza = "i like pizza" print(pizza) pizza = 333333333333 print(pizza) # + - / ** * // % x = 3 y = 5 print(x - y) print(x + y) print(x // y) print(x * y) print(x ** y) print(30 % 11) # True, False # and, or, is, not print(True is True) print(True is False) print(False is False) print(True is not False) print(False is not True) print(True or False) # True print(True and False) # False # <=, ==, >=, != greeting1 = 'Hello' greeting2 = 'Helloo' print("The id of the first Hello is", id(greeting1)) print("The id of the second Hello is", id(greeting2)) print(1 < 2 > 3) print(1 != 1) if 1 == 2: print("Hello") elif 1 != 1 or 1 > 0: print("What's up") for x in range(5): x = x + 1 print(x) i = 0 while i <= 5: print("Hi") i += 1 # Same: i = i + 1 # f(x, y) = x + y def f(x, y): def z(x, y): print("Inside function z:", x, y) print("Inside function f:", x, y) x -= 1 y -= 1 z(x, y) return x, y x, y = f(1, 2) print("Outside function f:", x, y) my_list = [1, 2, "string", 4, False] print("Before loop:", my_list) for x in range(len(my_list)): my_list[x] = my_list[x] * 5 print("After loop:", my_list) my_dict = {"key1":[1, 2, 3, 4], "key2": 2 ,"key3": 3, "key4": 4, "key5": 5 } """ dict list int str float """ for x in my_dict.items(): print(x)
a4bad5bf1285ea89be936906ed69f16c05f9d355
FrostyTheLonely/Python
/test.py
1,390
3.703125
4
from tkinter import * def donothing(var=''): pass class interface(Tk): def __init__(self, name='Interface', size=None): super(interface, self).__init__() if size: self.geometry(size) self.title(name) self.frame=Frame(self) self.frame.pack() def gui_print(self, text='This is some text', command=donothing): self.frame.destroy() self.frame=Frame(self) self.frame.pack() Label(self.frame, text=text).pack() Button(self.frame, text='Ok', command=command).pack() def gui_input(self, text='Enter something', command=donothing): self.frame.destroy() self.frame=Frame(self) self.frame.pack() Label(self.frame, text=text).pack() entry=StringVar(self) Entry(self.frame, textvariable=entry).pack() Button(self.frame, text='Ok', command=lambda: command(entry.get())).pack() def end(self): self.destroy() def start(self): mainloop() if __name__=='__main__': def foo2(value): global main main.gui_print('Your name is '+value+'.', main.end) def foo1(): global main main.gui_input('What is your name?', foo2) main=interface('Window') foo1() main.start()
2fb626bd6631b8ede2be9c9fe60a44e955f4666b
aNLPer/AlgorithmNotes
/Leetcode/test.py
821
3.546875
4
import random class Solution(object): def __init__(self, nums): """ :type nums: List[int] """ self.array = nums self.original = nums def reset(self): """ Resets the array to its original configuration and return it. :rtype: List[int] """ self.array = self.original return self.array def shuffle(self): """ Returns a random shuffling of the array. :rtype: List[int] """ self.array = self.original for i in range(len(self.array)): j = random.randint(0,len(self.original)-1) temp = self.array[i] self.array[i] = self.array[j] self.array[j] = temp return self.array a = [1,2,3,4,5,6] c = a[::-1] print(id(a), id(c))
b3fc8fb5b02cebc3effd18f5b10af66aa645242a
aNLPer/AlgorithmNotes
/Algorithm/DynamicProgramming/LongestIncreasingSequence.py
1,110
3.859375
4
""" 300. Longest Increasing Subsequence Given an unsorted array of integers, find the length of longest increasing subsequence. Example: Input: [10,9,2,5,3,7,101,18] Output: 4 Explanation: The longest increasing subsequence is [2,3,7,101], therefore the length is 4. Note: There may be more than one LIS combination, it is only necessary for you to return the length. Your Algorithm should run in O(n2) complexity. Follow up: Could you improve it to O(n log n) time complexity? 总结: 动态规划就像填dp数组的游戏,要明确以下几点: 1、dp数组的含义(状态) 2、明确dp数组的初始状态(base case) 3、递推dp数组的规则(状态转移方程) """ def lengthOfLIS(nums): dp = [0]*len(nums) dp[0] = 1 for i in range(1, len(nums)): length = float("-inf") for j in range(i): if nums[i] > nums[j]: length = max(length, dp[j]+1) dp[i] = length return max(dp) nums=[1,4,2,7,8,3] dp, ans = lengthOfLIS(nums)
5263292467eef236f7185fe14816b067ead978e3
aNLPer/AlgorithmNotes
/Algorithm/BinaryTree/Traverse.py
3,678
3.875
4
""" 介绍二叉树的遍历(前序、中序、后序遍历) """ # 二叉树的遍历 from collections import deque class Solution(object): def __init__(self): self.ans = [] def preorderTraversal_recur(self, root): """ :type root: TreeNode :rtype: List[int] """ if root == None: return [] self.ans.append(root.val) self.inorderTraversal(root.left) self.inorderTraversal(root.right) return self.ans def inorderTraversal_recur(self, root): """ :type root: TreeNode :rtype: List[int] """ if root == None: return [] self.inorderTraversal(root.left) self.ans.append(root.val) self.inorderTraversal(root.right) return self.ans def postorderTravelsal_recur(self, root): """ :type root: TreeNode :rtype: List[int] """ if root is None: return [] self.postorderTravelsal_recur(root.left) self.postorderTravelsal_recur(root.right) self.ans.append(root.val) return self.ans def preorderTravelsal_iter(self, root): """ :type root: TreeNode :rtype: List[int] """ result = [] stack = [] if root is not None: stack.append(root) while len(stack) > 0: curr = stack.pop() result.append(curr.val) if curr.right: stack.append(curr.right) if curr.left: stack.append(curr.left) return result def inorderTraversal_iter(self, root): """ :type root: TreeNode :rtype: List[int] """ result = [] stack = [] curr = root while curr and len(stack) > 0: while curr: stack.append(curr) curr = curr.left curr = stack.pop() result.append(curr.val) curr = curr.right return result def postorderTravelsal_iter(self, root): """ :type root: TreeNode :rtype: List[int] """ result = [] stack = [] curr = root prev = None while len(stack) > 0 or curr: while curr: stack.append(curr) curr = curr.left curr = stack.pop() # 如果右节点不存在或者右节点已经被访问 if curr.right and prev == curr.right: result.append(curr.val) prev = curr curr = None else: stack.append(curr) curr = curr.right return result # 锯齿形层序遍历二叉树 def zigzagLevelOrder(self, root): """ :type root: TreeNode :rtype: List[List[int]] """ result = [] dq = deque() count = 0 if root is not None: dq.append(root) count = 1 while len(dq) > 0: temp = 0 container = [] for _ in range(count): curr = dq.popleft() container.append(curr.val) if curr.left: dq.append(curr.left) temp += 1 if curr.right: dq.append(curr.right) temp += 1 result.append(container) count = temp for i in range(len(result)): if (i % 2) == 1: result[i].reverse() return result # 从中序与后序遍历序列构造二叉树
3c75198d39ef5a519610aecd5bc9b162385fb2d4
YKato521/ironpython-stubs
/release/stubs.min/System/Diagnostics/__init___parts/Stopwatch.py
2,471
3.53125
4
class Stopwatch(object): """ Provides a set of methods and properties that you can use to accurately measure elapsed time. Stopwatch() """ @staticmethod def GetTimestamp(): """ GetTimestamp() -> Int64 Gets the current number of ticks in the timer mechanism. Returns: A long integer representing the tick counter value of the underlying timer mechanism. """ pass def Reset(self): """ Reset(self: Stopwatch) Stops time interval measurement and resets the elapsed time to zero. """ pass def Restart(self): """ Restart(self: Stopwatch) Stops time interval measurement,resets the elapsed time to zero,and starts measuring elapsed time. """ pass def Start(self): """ Start(self: Stopwatch) Starts,or resumes,measuring elapsed time for an interval. """ pass @staticmethod def StartNew(): """ StartNew() -> Stopwatch Initializes a new System.Diagnostics.Stopwatch instance,sets the elapsed time property to zero, and starts measuring elapsed time. Returns: A System.Diagnostics.Stopwatch that has just begun measuring elapsed time. """ pass def Stop(self): """ Stop(self: Stopwatch) Stops measuring elapsed time for an interval. """ pass Elapsed = property(lambda self: object(), lambda self, v: None, lambda self: None) """Gets the total elapsed time measured by the current instance. Get: Elapsed(self: Stopwatch) -> TimeSpan """ ElapsedMilliseconds = property( lambda self: object(), lambda self, v: None, lambda self: None ) """Gets the total elapsed time measured by the current instance,in milliseconds. Get: ElapsedMilliseconds(self: Stopwatch) -> Int64 """ ElapsedTicks = property( lambda self: object(), lambda self, v: None, lambda self: None ) """Gets the total elapsed time measured by the current instance,in timer ticks. Get: ElapsedTicks(self: Stopwatch) -> Int64 """ IsRunning = property(lambda self: object(), lambda self, v: None, lambda self: None) """Gets a value indicating whether the System.Diagnostics.Stopwatch timer is running. Get: IsRunning(self: Stopwatch) -> bool """ Frequency = None IsHighResolution = True
34740944fe71365f4c9a9a6242bdea68e5789e62
rnhibatullah/invention_idea_generator
/raw_object.py
992
3.71875
4
class RawObject: def __init__(self, name, cost,novelty, size, skill, viable ): self.name = name if cost <15 and cost > 0 : self.cost = cost else : print("cost of {} {} not in range of 1 - 10 ".format(self.name,self.cost)) return if novelty <10 and cost >0 : self.novelty = novelty else : print("novelty of {} {} not in range of 1 - 10 ".format(self.name,self.novelty)) return if size <5 and size > 0: self.size = size else: print("size of {} {} not in range of 1 - 5 " .format(self.name,self.size)) return if skill<30 and skill > 0 : self.skill = skill else : print("skill {} {} not in range of 1 - 30 ".format(self.name,self.skill)) return if viable <40 and viable > 0 : self.viable = viable else : print("viability {} {} not in range of 1 - 30 ".format(self.name,self.viable)) return def calculate_total(raw_obj): return raw_obj.cost + raw_obj.novelty + raw_obj.size + raw_obj.skill + raw_obj.viable
c46a860bd99dc8e6df086be204822b9b11b312b6
Daria-T/py-for-begginers
/src/main/lesson4/task3.py
296
3.71875
4
# Используюя numpy вычислить среднее арифметическое для 100 случайных числе. import numpy as np from numpy import array from numpy.random import seed from numpy.random import rand seed(3) values = array(rand(100)) print(np.mean(values))
fa4348c886de9e98fee1878c424aab1ebe8e448e
marina-h/lab-helpers
/primer_helper.py
813
4.15625
4
#!/usr/bin/env python # -*- coding: utf8 -*- import readline reverse_comp_dict = {'A':'T', 'T':'A','G':'C', 'C':'G'} def melting_temp(p): Tm = 0 for n in p: if n == 'A' or n == 'T': Tm += 2 if n == 'G' or n == 'C': Tm += 4 return Tm def reverse_comp(p): reverse = "" for n in p[::-1]: reverse += reverse_comp_dict[n] return reverse while True: print "--------------------START--------------------" primer = raw_input("\nWhat is your primer sequence? \ \n(Press CTRL-C to terminate program.) \ \n> ").upper() print "\nYour primer sequence is:\n5' %s (%s bp)\n" % (primer, len(primer)) print "Its reverse complement is:\n5'", reverse_comp(primer), "(%s bp)\n" % len(primer) print "The Tm of this primer (A,T=2°C, G,C=4°C) is:\n", melting_temp(primer), "°C" print "\n"
26ddeb9c91066e4bfd2ae820d434aa686c4ffdcd
ronie2/war
/war/base_shop.py
1,634
3.890625
4
class Shop(object): """Shop class providing methods to manipulate player's palnes""" def __init__(self, equipment): """ Args: equipment (dict): DB of the game palnes in the following format: 'planes': { <plane_id:int>: { 'price': {<game_currency:str>: <amount:int>, ...}, '__compatible_guns': {<gun_id:int>, ...} }, ... }, 'guns': { <gun_id:int>: { 'price': {<game_currency:str>: <amount:int>, ...} }, ... } """ self.db = equipment def buy_plane(self, player, plane_id): """Buy plane with ID `plane_id` for player `player` and update player's data as necessary. Args: player(dict): player's data in the following format: 'id': <player_id:int>, 'resources': {<game_currency:str>: <amount:int>, ...}, 'planes': { <plane_id:int>: {'gun': <gun_id:int>}, ... } plane_id(int): Id of plane to buy Returns: None """ def buy_gun(self, player, plane_id, gun_id): """Buy gun with ID `gun_id` for player `player` and update player's data as necessary. Args: player(dict): Player's data plane_id(int): Id of plane to buy gun for gun_id(int): Id of gun to buy Returns: None """
f883e815f7b4ea4bd03a04ded5265ffb473dc607
capatch/finalProject
/test_1.py
541
3.53125
4
from tkinter import * import tkinter.font from gpiozero import LED import RPi.GPIO RPi.GPIO.setmode(RPi.GPIO.BCM) led=LED(14) win=Tk() win.title('LED Toggler') myFont=tkinter.font.Font(family='Helvetica', size = 12, weight = 'bold') def ledToggle(): if led.is_lit: led.off() ledButton['text']='Turn LED on' else: led.on() ledButton['text']='Turn LED off' ledButton=Button(win, text = 'Turn LED on', font=myFont, command=ledToggle, bg='bisque2', height=1, width=24) ledButton.grid(row=0,column=1)
ae6a511723cc0f54dc39d56b2c9ed70ed3bb9305
lnbe10/Math-Thinking-for-Comp-Sci
/combinatory_analysis/dice-game.py
2,755
4.1875
4
# dice game: # a shady person has various dices in a table # the dices can have arbitrary values in their # sides, like: # [1,1,3,3,6,6] # [1,2,3,4,5,6] # [9,9,9,9,9,1] # The shady person lets you see the dices # and tell if you want to choose yor dice before # or after him # after both of you choose, # them roll your dices, and see # who wins (the one with bigger number showing up) # to maximize the chances of winning, you have to # do some tasks: # 1- check if there's a dice better than all others # 1.1 - if it exists, you choose first and select it # 1.2 - if it doesn't exist, you let the shady person # choose a dice and you choose one wich is better # than his one .-. def count_wins(dice1, dice2): assert len(dice1) == 6 and len(dice2) == 6 dice1_wins, dice2_wins = 0, 0 for i in dice1: for j in dice2: if i>j: dice1_wins+=1; if j>i: dice2_wins+=1; return (dice1_wins, dice2_wins) dice1 = [1, 2, 3, 4, 5, 6]; dice2 = [1, 2, 3, 4, 5, 6]; count_wins(dice1,dice2); dice3 = [1, 1, 6, 6, 8, 8]; dice4 = [2, 2, 4, 4, 9, 9]; count_wins(dice3,dice4); def find_the_best_dice(dices): assert all(len(dice) == 6 for dice in dices) wins = [0 for i in range(len(dices))]; for i in range(len(dices)): for j in range(i+1, len(dices)): versus = count_wins(dices[i], dices[j]); if versus[0]>versus[1]: wins[i]+=1; if versus[1]>versus[0]: wins[j]+=1; if max(wins) == len(dices)-1: #print('best dice is', wins.index(max(wins))); return wins.index(max(wins)); #print('no best dice'); return -1 find_the_best_dice([[1, 1, 6, 6, 8, 8], [2, 2, 4, 4, 9, 9], [3, 3, 5, 5, 7, 7]]); find_the_best_dice([[3, 3, 3, 3, 3, 3], [6, 6, 2, 2, 2, 2], [4, 4, 4, 4, 0, 0], [5, 5, 5, 1, 1, 1]]); find_the_best_dice([[1, 1, 2, 4, 5, 7], [1, 2, 2, 3, 4, 7], [1, 2, 3, 4, 5, 6]]); def compute_strategy(dices): assert all(len(dice) == 6 for dice in dices) strategy = dict() strategy["choose_first"] = True strategy["first_dice"] = 0 for i in range(len(dices)): strategy[i] = (i + 1) % len(dices) if find_the_best_dice(dices) != -1: strategy["choose_first"] = True; strategy["first_dice"] = find_the_best_dice(dices); else: strategy["choose_first"] = False; for i in range(len(dices)): for j in range(i+1, len(dices)): versus = count_wins(dices[i], dices[j]); if versus[0]>versus[1]: strategy[j]=i; if versus[1]>versus[0]: strategy[i]=j; print(strategy); return strategy; dices = [[4, 4, 4, 4, 0, 0], [7, 7, 3, 3, 3, 3], [6, 6, 2, 2, 2, 2], [5, 5, 5, 1, 1, 1]]; compute_strategy(dices); dices2 = [[1, 1, 4, 6, 7, 8], [2, 2, 2, 6, 7, 7], [3, 3, 3, 5, 5, 8]]; #compute_strategy(dices2);
dfbb1d0a6d09d617ce6a3d30579a40a6793b3f71
AndyDaly90/FYP_PythonScraping
/FYPSprint3/car_crawler.py
2,922
3.515625
4
# -*- coding: utf-8 -*- from __future__ import print_function import mechanize from bs4 import BeautifulSoup import re import urllib2 def clean_url(data): """ In order to make requests across the network I need a clean URL (example : http://www.desiquintans.com/articles/). This is done by using a regular expression along with some string splitting & string replacing. :rtype : String URL """ url = re.findall('[a-z]+[:.].*?(?=\s)', data) formatted_url = url[0].replace('%3D', '=').replace('%3F', '?').replace('%2520', '+').replace('%26', '&')#Document+++ cleaned_url = re.split('&amp|amp', formatted_url)#Document++++ return cleaned_url[0] def perform_google_search(_make, _model, _site, _area): browser = mechanize.Browser() browser.set_handle_robots(False) browser.addheaders = [('User-Agent', 'Mozilla/5.0')] google_request = "http://www.google.ie/search?q=used+%s+%s+%s+%s" % (_make, _model, _site, _area) try: result = browser.open(google_request).read() except mechanize.HTTPError, error: print("HTTP Error Found: ", error.args) raise return result def get_url(search_result): """ This method takes a google search result (HTML). The method uses Beautiful soup to extract the top URL from the search result, contained in 'r'. 'r' is the location that google stores its resulting links from a search query. :rtype : str (URL) """ soup = BeautifulSoup(search_result, 'html.parser') search_div = soup.find_all('h3', attrs={'class': 'r'}) top_search_result = str(search_div[0]) url_soup = BeautifulSoup(top_search_result, 'html.parser') url = url_soup.find_all('a') dirty_url = str(url) return dirty_url def get_web_page(url): try: urllib2.urlopen(url) except urllib2.URLError, error: print(error.args) html_file = urllib2.urlopen(url) html_text = html_file.read() html_page = BeautifulSoup(html_text, 'html.parser') return html_page def get_car_info(_page): car_info = {'class': re.compile("desc|grid-card|details|info")} info_list = [] all_info = _page.findAll(attrs=car_info) for info in all_info: print(info.text.encode('utf-8', errors='replace')) info_list.append(info.text) return info_list def get_car_year(_page): car_year = { 'class': re.compile("time-listed") } years_list = [] year_data = _page.findAll(attrs=car_year) for data in year_data: years_list.append(data.text) return years_list def get_car_prices(web_page): car_prices = [] pattern = '(euro;\d+,\d+|\€\d{1,2},\d{3}|\d{1,2},\d{3}|\£\d{1,2},\d{3})' regex = re.compile(pattern) prices = re.findall(regex, str(web_page)) for p in prices: if ',' in p: p = p.replace(',', '.') car_prices.append(p) return car_prices
40d29a3a935db6151ee3e06f4d4bd7dbc1e6c815
idane19-meet/meet2017y1lab5
/add_numbers.py
262
3.765625
4
def add_numbers(start, end): c = 0 for number in range(start, end + 1): print(number) c = c + number return(c) test1 = add_numbers(1,2) print(test1) test2=add_numbers(1,100) print(test2) test3 = add_numbers(1000,5000) print(test3)
2e79930ea3e3a80484e3f2d2fe4279970c6c3ec9
johnksterling/falconcodingclub
/madlib/madlibs_dynamic.py
519
4.0625
4
import random keep_playing = True madlibs = [] madlibs.append("I would like to {verb} at the {place}") madlibs.append("When I was a child a was afraid to {verb} at the {place}") madlibs.append("Is the {place} where you like to {verb}") while keep_playing: madlib = random.choice(madlibs) verb = input('enter a verb: ') place = input('enter a place: ') print(madlib.format(verb=verb, place=place)) answer = input('Would you like to play again?') if answer == 'no': keep_playing = False
7750ffc47e269a9b87001c4299d19e969af1f30f
johnksterling/falconcodingclub
/analytics/names/summarize_name.py
370
3.8125
4
import csv name = input('What name would you like to search? ') NAME_INDEX = 1 YEAR_INDEX = 2 COUNT_INDEX = 4 with open('input.csv', 'r') as csvfile: reader = csv.reader(csvfile) next(reader, None) for row in reader: year = row[YEAR_INDEX] count = row[COUNT_INDEX] if row[NAME_INDEX] == name: print(year + ': ' + count)
f07a7a11cca03a01d509100b4cc60bb99825829e
TanmayPriyadarshi/Coding_Blocks
/pattern_mountain.py
666
3.796875
4
def Main(): try: N = int(input("\nEnter the number")) if N > 10: raise Exception for i in range(1, N + 1): j = 1 while j <= N: if j <= i: print(j, end=' ') else: print(' ', end=' ') j += 1 j = N - 1 while j >= 1: if j > i: print(' ', end=' ') else: print(j, end=' ') j -= 1 print("\n") except Exception: print("\nSomething is not right") if __name__ == '__main__': Main()
6a86ef0e9ed02f1deea5979e760cbcbecbc51857
shanereid19/Final-Project
/FirstDraft.py
2,907
3.953125
4
import pygame import time # For my project I plan to create a game simialr to pong but modified to be more like a soccer game. # The game is called "Soccer Pong". # Therefore, as a reulst I have imported "pygame" and "time" to use in the interface of the game. # I will use pygame to design the game and time is an important variable in games and soccer alike. pygame.init() # This was done to iniatlise the game. """ Watched tutorials of functions and how to make screens from the pygame website https://pythonprogramming.net/pygame-python-3-part-1-intro/ """ display_width = 800 #This is the display width of the window that the game will be played in. display_height = 600 ##This is the display height of the window that the game will be played in. black = (0,0,0) white = (255,255,255) #These are the colors that the game will use. gameDISPLAY = pygame.display.set_mode((display_width, display_height)) # This is the display window in which the game will be played. pygame.display.set_caption("Soccer Pong") # This is the title of the display window. clock = pygame.time.Clock() # This will be the clock that helps to set the game time for each match. crashed = False while not crashed: for event in pygame.event.get(): if event.type == pygame.QUIT: crashed = True print(event) pygame.display.update() clock.tick(30) pygame.quit() quit() def game_intro(): #This will be the introductary screen to the game. intro = True while intro: for event in pygame.event.get(): print(event) if event.type == pygame.QUIT: pygame.quit() quit() gameDISPLAY.fill(white) largeText = pygame.font.Font("freesansbold.ttf",100) TextSurf, TextRect = text_objects("Soccer Pong", largeText) TextRect.center = ((display_width/2), (display_height/2)) gameDisplay.blit(TextSurf, TextRect) pygame.display.update() clock.tick(30) def game_loop(): #This function is the function that allows theuser to exit the game. #When the user hits the "x" to close the window, the window will be closed. x = (display_width * 0.45) y = (display_height * 0.8) x_change = 0 gameExit = False while not gameExit: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() quit() if event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT: x_change = -5 if event.key == pygame.K_RIGHT: x_change = 5 if event.type == pygame.KEYUP: if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT: x_change = 0 x += x_change pygame.display.update() clock.tick(60) game_intro() game_loop()
433fde58590d64d945c2ee79560d40f8e8dfb43f
choijaehoon1/programmers_level
/src/test60.py
515
3.546875
4
def trans(num): answer = '' while num > 0: answer = str(num%2) + answer num //= 2 return answer def solution(s): zero_cnt = 0 time = 0 if s == "1": return [0,0] else: while s != "1": new_s = s.replace('0','') length = len(new_s) zero_cnt += (len(s) - length) time += 1 result = trans(length) # print(result) s = result return [time, zero_cnt]
a1e461eb0d83cbf08167139b198cc63e83d459b1
choijaehoon1/programmers_level
/src/test28.py
447
3.546875
4
def solution(phone_book): # 범위가 커서 터지므로 유사한 번호가 오게 정렬 후 다음값과 비교 phone_book.sort() # O(N Log N) for i in range(len(phone_book)-1): if phone_book[i] in phone_book[i+1]: # 안에 들어가 있는 형태 if phone_book[i+1].index(phone_book[i]) == 0: # i+1번째에서 i번째 인덱스를 찾는데 접두어인지 check return False return True
0c90a32f4293acf4d1cd06cb6a738ea39608600c
choijaehoon1/programmers_level
/src/test77.py
705
3.515625
4
def score(cnt): if cnt >= 6: return 1 elif cnt >= 5: return 2 elif cnt >= 4: return 3 elif cnt >= 3: return 4 elif cnt >= 2: return 5 return 6 def solution(lottos, win_nums): mask = lottos.count(0) # print(mask) if mask == 0: cnt = 0 for i in lottos: if i in win_nums: cnt += 1 num = score(cnt) return [num,num] else: tmp = 0 for i in lottos: if i != 0 and i in win_nums: tmp += 1 max_num = score(tmp+mask) min_num = score(tmp) return [max_num,min_num]
5566ab29cd5b0bea8f9ec3e99110fa94d955cb7a
choijaehoon1/programmers_level
/src/test90.py
1,469
3.578125
4
def binary(x): tmp = '' while x > 0: n = x % 2 x //= 2 tmp = str(n) + tmp return tmp def solution(n, arr1, arr2): answer = [] tmp_list = [['#']*n for _ in range(n)] new_arr1 = [] new_arr2 = [] for i in arr1: num = binary(i) if len(num) != n: cnt = n - len(num) for j in range(cnt): num = '0' + num new_arr1.append(list(num)) for i in arr2: num = binary(i) if len(num) != n: cnt = n - len(num) for j in range(cnt): num = '0' + num new_arr2.append(list(num)) for i in range(n): for j in range(n): if new_arr1[i][j] == '0': new_arr1[i][j] = '' elif new_arr1[i][j] == '1': new_arr1[i][j] = '#' for i in range(n): for j in range(n): if new_arr2[i][j] == '0': new_arr2[i][j] = '' elif new_arr2[i][j] == '1': new_arr2[i][j] = '#' for i in range(n): for j in range(n): if new_arr1[i][j] == '' and new_arr2[i][j] == '': tmp_list[i][j] = '' for i in tmp_list: tmp = '' for j in i: if j == '': tmp += ' ' else: tmp += j answer.append(tmp) return answer
7b49830e3e184c294c303018d1a8dd94ecc6e9cf
choijaehoon1/programmers_level
/src/test33.py
648
3.6875
4
answer = 0 def dfs(numbers,target,i): global answer if i == len(numbers): # 끝까지 수행했을 때만 확인(i가 인덱스 범위 벗어날때가 끝까지 수행한 것임) if sum(numbers) == target: # 종료 조건 answer += 1 return else: dfs(numbers,target,i+1) # 재귀먼저 수행(맨 처음 주어진 numbers가 target과 같을수도 있으므로) numbers[i] *= -1 # 값을 바꿔주고 (원복도 수행 됨) dfs(numbers,target,i+1) # 바뀐 numbers로 재귀 수행 def solution(numbers, target): global answer dfs(numbers,target,0) return answer
763e59a4dd2ca848e41297c3002c8a9297f41979
PiGuy23/ThereminPi
/Testing/FunctionTest.py
672
3.8125
4
#An example of a running avg done with a function from time import sleep vals = [1] * 13 vals2 = [3] * 4 d = 1 d2 = 4 def f_avg (arr): k = len(arr) -1 i = 0 while i < k: arr[i] = arr[i+1] i = i+1 global d global d2 x = int(input()) if (k == 12) : if x == 1.0: arr[k] = d else: arr[k] = x d = x else: if x == 1.0: arr[k] = d2 else: arr[k] = x d2 = x j = 0 for y in arr: j = j + y avg = j/(k+1) return avg while True: print(f_avg(vals2)) print(f_avg(vals))
193945b7cdebfd846f466c69e25be71937df24da
PiGuy23/ThereminPi
/Testing/RunAvgTest.py
657
3.53125
4
#Works really well. Thi bigger the better from time import sleep vals = [0] * 4 b = 0 def average(arr, next, hol): k = len(arr) -1 i = 0 while i < k: arr[i] = arr[i+1] i = i+1 if next == 1.0: arr[k] = hol[0] else: arr[k] = next hol[0] = next j = 0 for y in arr: j = j + y avg = j/(k+1) return avg d = [0] while True: x = int(input()) print("Average: ") print(average(vals, x, d)) print("\n") print("D: ") print(d[0]) print("\n") for n in vals: print(n) print("\n")
eb077fce1e2eb66846fefd42afd9871c3d7e1129
karolxxx/Regex-project
/phone.py
489
3.671875
4
import re import time print('Welcome, you have won 1 million dollars! Please verify your phone number!') time.sleep(2) #sleep content = input('Please enter your number:') # content = "111-111-1111" numberRegex = re.compile(r'\d\d\d-\d\d\d-\d\d\d\d') result = numberRegex.search(content) if result is not None: time.sleep(3) #sleep if result.group() == content: print('thank you') if result.group() != content: print('try again') else: print('try again')
a60df60f1bd19896da30e8d46be5fee3a020413c
battyone/Practical-Computational-Thinking-with-Python
/ch4_orOperator.py
220
4.125
4
A = True B = False C = A and B D = A or B if C == True: print("A and B is True.") else: print("A and B is False.") if D == True: print("A or B is True.") else: print("A or B is False.")
72de8c1646257560a280b2a139bea22f86515258
tx621615/pythonlearning
/025inherit1.py
2,713
3.71875
4
# 类变量和成员变量的继承规则 """ 1,对于类变量x,最开始Children1和Children2都没有赋值x,所以都等于1。当Children1赋值2之后值就变了,但Children2还是之前的1,当父类修改为3后,由于Children2一直没有赋值,所以等于修改后的父类的x值3,直到Children2自己赋值才是4。 2,对于实例变量y,最开始child1和child2都没有对y赋值,所以都等于1。当child1变成2之后就变成2,但child2还是之前的1,即使父类实例par改变y的值为3,child2还是为1。直到child2自己赋值为4才改变。 1,对于类变量x,最开始Children和GrandChildren都没有赋值x,所以都等于1。当Children赋值2之后值就变了,GrandChildren也跟着变,当父类修改后,由于Children2在之前赋值为2,所以即使修改了父类的x,但也不会访问到他。GrandChildren自己赋值为3就会变成4,不影响Parent和GrandChildren。 2,对于实例变量y,最开始child和grand都没有对y赋值,所以都等于1。当child变成2之后就变成2,但grand还是最开始的初值1,即使父类实例par改变y的值为3,grand还是1。直到grand自己赋值为4才改变。 总结:对于类变量来说,当子类没有赋值类变量,那么就会随父类的类变量的值改变而改变,一旦子类自身赋值过后则与父类类变量没有关系了。 对于成员变量,除了最开始的继承值外,则无任何关系。 """ class Parent(object): x = 1 # 类变量 def __init__(self): self.y = 1 # 实例变量 class Children1(Parent): pass class Children2(Parent): pass par = Parent() # 具体的类实例对象 child1 = Children1() # 具体的类实例对象 child2 = Children2() # 具体的类实例对象 print('-------------------------------------') print('Parent.x=', Parent.x, ',Children1.x=', Children1.x, ',Children2.x=', Children2.x) print('par.y=', par.y, ',child1.y=', child1.y, ',child2.y=', child2.y) print('-------------------------------------') Children1.x = 2 child1.y = 2 print('Parent.x=', Parent.x, ',Children1.x=', Children1.x, ',Children2.x=', Children2.x) print('par.y=', par.y, ',child1.y=', child1.y, ',child2.y=', child2.y) print('-------------------------------------') Parent.x = 3 par.y = 3 print('Parent=', Parent.x, ',Children1=', Children1.x, ',Children2=', Children2.x) print('par.y=', par.y, ',child1.y=', child1.y, ',child2.y=', child2.y) print('-------------------------------------') Children2.x = 4 child2.y = 4 print('Parent=', Parent.x, ',Children1=', Children1.x, ',Children2=', Children2.x) print('par.y=', par.y, ',child1.y=', child1.y, ',child2.y=', child2.y)
1c9483e36d864bd7a8f5722f60801cda7e6c521f
tx621615/pythonlearning
/02tab.py
223
4.15625
4
# 测试缩进,python中没有大括号,通过相同的缩进表示同一个代码块 if True: print("Answer") print("True") else: print("Answer") print("False") # 缩进不同则不在同一个块中
b33f2ed903c56bda63a02dac1bfe99882f0bfaed
JDRanpariya/question_paper_scraper
/qPull.py
871
3.5
4
from selenium import webdriver from bs4 import BeautifulSoup # set the chromedriver to interact with chrome.exe to scrape webpage driver = webdriver.Chrome(""" enter your chromedriver path """) driver.get("https://engineering.jainuniversity.ac.in/") question_paper = open("Question_Paper.txt", "a") while(True): # manual buffer for scrape input("\nEnter to continue...") # loading Selenium & Beautiful Soup for web page scraping and lxml parsing content = driver.page_source soup = BeautifulSoup(content, features="lxml") # extract question-containing-element from webpage raw_qs = soup.findAll("table", id="ContentPlaceHolder1_dlquestions") # strip newlines and clean formatting for the scraped question qs = raw_qs[0].text.replace("\n\n\n", "") qs = qs.replace("\n\n", "\n") # write pulled question to .txt file question_paper.write(qs + "\n")
255c09b29bc9cd76e730a64a0722d24b003297c8
ugneokmanaite/api_json
/json_exchange_rates.py
1,068
4.3125
4
import json # create a class Exchange Rates class ExchangeRates: # with required attributes def __init__(self): pass # method to return the exchange rates def fetch_ExchangeRates(self): with open("exchange_rates.json", "r") as jsonfile: dataset = json.load(jsonfile) # For loop to get all exchange rates for e in dataset: if e == "rates": print(dataset(["rates"])) currency = input("What currency would you like the exchange rate of, please see list.\n") # display exchange rates with specific currencies print(dataset["rates"][currency]) e = ExchangeRates e.__init__(ExchangeRates) # fetch the data from exchange_rates.json # method to return the exchange rates # creating an object of class # rate_display = ExchangeRates ("exchange_rates.json") # print(rate_display.rates) # display the data # display the type of data # method to return the exchange rates # display exchange rates with specific currencies
9f4bffa47c541d34029428166d2af6b9138d9b2c
MathewsPeter/PythonProjects
/inheritence.py
529
3.703125
4
class A: def __init__(self, a): self.a = a def disp(self): print(self.a) class B(A): def __init__(self,a,b): A.__init__(self, a) self.b = b def disp(self): print(self.a,self.b) class C(B): def __init__(self,a,b,c): B.__init__(self, a,b) self.c = c def disp(self): print(self.a,self.b,self.c) #Aobj = A(1) #Bobj = B(1,2) Cobj = C(1,2,3) #Aobj.disp() #Bobj.disp() Cobj.disp()
9445b358d4c35b1caec4c3bc2620b47ef514d331
MathewsPeter/PythonProjects
/biodata_validater.py
1,124
4.5625
5
'''Example: What is your name? If the user enters * you prompt them that the input is wrong, and ask them to enter a valid name. At the end you print a summary that looks like this: - Name: John Doe - Date of birth: Jan 1, 1954 - Address: 24 fifth Ave, NY - Personal goals: To be the best programmer there ever was. ''' while(1): name = input("Enter name: ") if name.replace(" ", "").isalpha(): break print("Name shall have only alphabets and space. Please try again.\n") while(1): dob = input("Enter DOB as DDMMYYY: ") dd = (int)(dob[0:2]) mm = (int)(dob[2:4]) yyyy = (int)(dob[4:8]) if(dd>0 and dd<=31): if(mm>0 and mm<=12): if(yyyy>1900 and yyyy<=2021): break; else: print("Year should be between 1900 and 2021. Please try again.\n") else: print("Month should be between 1 and 12. Please try again.\n") else: print("Date should be between 1 and 31. Please try again.\n") print("Name is ", name) print("DOB is ", dd,"-",mm,"-",yyyy)
f105606ceb0d3a72e2d35e88a78952fed10f38a7
MathewsPeter/PythonProjects
/bitCountPosnSet.py
408
4.15625
4
''' input a 8bit Number count the number of 1s in it's binary representation consider that as a number, swap the bit at that position ''' n = (int)(input("enter a number between [0,127] both inclusive")) if n<0 or n>127: print("enter properly") else: n_1= n c = 0 while n: if n&0b1: c+=1 n = n>>1 print(c) n_2 = n_1 ^ (1<<c) print(n_2)
207a64f73bfea0453920889718fe099ed8f611ae
Ahmed-Zoher/Python_Based_Projects
/XML_Parser_Lab/bonus_sort.py
582
4.0625
4
""" CONTENTS: 1)Bubble Sort Algorithm 2)Selection Sort Algorithm """ def my_bubble_sort(b): for n in range(0,len(b)-1): for a in range (1,len(b)-n): if b[a-1]>b[a]: temp = b[a] b[a]=b[a-1] b[a-1]=temp def my_selection_sort(b): for n in range(1,len(b)): for a in range (n,0,-1): if b[a-1]>b[a]: temp = b[a] b[a]=b[a-1] b[a-1]=temp def main(): a=[9,1,0,2,1,4,-5] my_bubble_sort(a); print(a); b=['z','c','b','o','t','w','y'] my_selection_sort(b); print(b); if __name__ == "__main__": main()
52b5aa090d6eefd26c773af730bbd2eb1ec54d03
Zob-code/Inceptial-Assignment
/Ex43.py
5,820
3.703125
4
from sys import exit from random import randint from textwrap import dedent class Scene(object): def enter(self): print("This scene is not yet configured") print("Subscribe it and implement enter()") exit(1) class Engine(object): def __init__(self, scene_map): self.scene_map = scene_map def play(self): current_scene = self.scene_map.opening_scene() last_scene = self.scene_map.next_scene("Finished") while current_scene != last_scene: next_scene_name = current_scene.enter() current_scene = self.scene_map.next_scene(next_scene_name) current_scene.enter() class Death(Scene): quips = [ "You died. You kinds suck at this.", "Your Mom would be proud .. if she were smarter.", "Such a luser." ] def enter(self): print(Death.quips[randint(0, len(self.quips)-1)]) exit(1) class CentralCorridor(Scene): def enter(self): print(dedent(""" The Gothons of planet Percel #25 have invaded your ship and destroyed your entire crew. You aret he last surviving member and your last mission is to geet the neutron destruct bomb from the weapon armory. Your are runnign down the centrla corridor to the weapons armory when a gothon jumps out red skin , dark griemy teeth, and evil clown costume flowing around his hate fille body""")) action = input("> ") if action == "shoot": print(dedent(""" Quick onth edraw you yank out your blaster and fire it at the gothon. His clown is flowing and moving around his body, which throws off your aim. Your laser hits his contume but missed him entirely. This completely ruins his brand new costume his mother bought him, which makes him fly into an insane rage. Then he eats you. """)) return 'death' elif action == "dodge": print(dedent(""" Like a world class boxer you dodge, weave slip and slider right as the gothon's blaster cranks a laser past your head. In the middle of your artful dodge your slips and you bang you head on the metal wall and pass out.hten the gothon eats you.""")) return 'death' else: print("DOES NOT COMPUTE!") return 'central_corridor' class LaserWeaponArmory(Scene): def enter(self): print(dedent(""" You do a dive roll into the weapons armory, crouch and scan the room for more Gothons that might be hiding. its dead quiet too quiet. You stand up and run to the far side of the room and find the neutron bomb in its container. The deactivaiton code in 3 digits.""")) code = f"{randint(1,9)}{randint(1,9)}{randint(1,9)}" guess = input("[keypad]> ") guesses = 0 while guess != code and guesses < 10: print("BZZZEDDD") guesses += 1 guess = input("[keypad]> ") if guess == code: print(dedent(""" The container clicks and return the seal breaks letterring gasout you grab the neutro bomb ans run as fast as you can """)) return 'excape_pod' else: print(dedent(""" The lock buzzers one last time andd then you hear a sickeing melting sound as the mechanism is fused together. You decide to sit there and finally the gothons blow up the ship form thier ship and you die. """)) return 'death' class EscapePod(Scene): def enter(self): print(dedent(""" Yourush through the ship desparately trying to make it to the escape pod before the shole ships explodes. It seems like hardly any Gothoms are onthe ship, so your run is clear of inteference. tere are 5 pods which do you takae? """)) good_pod = randint(1,5) guess = input("[pod #]> ") if int(guess) != good_pod: print(dedent(""" You jump into pod {guess} and hit the eject button. Then implodes as the hull rupture, crushing you body into jamjelly. """)) return 'death' else: print(dedent(""" You jump into pod {guess} and hit the eject button The pod easily slides into space. You won!!""")) class Finished(Scene): def enter(self): print("You won the game") return 'finished' class Map(object): scenes = { 'central_corridor' : CentralCorridor(), 'laser_weapon_armory' : LaserWeaponArmory(), 'escape_pod' : EscapePod(), 'death' : Death(), 'finished' : Finished() } def __init__(self, start_scene): self.start_scene = start_scene def next_scene(self, scene_name): val = Map.scenes.get(scene_name) return val def opening_scene(self): return self.next_scene(self.start_scene) a_map = Map('central_corridor') a_game = Engine(a_map) a_game.play()
d1dac2b0984c21855a5b6b42185aaea62355a157
heman-oliver/Puligitham-II
/screen.py
903
3.609375
4
# IMPORTS import pygame from color import Color # /////////////////////////| # SCREEN CLASS FOR THE GAME| # /////////////////////////| class Screen(object): # CONTAINS THE ATTRIBUTES: WIDTH, HEIGHT, FONT, CLOCK def __init__(self): self.screen_width = 1000 self.screen_height = 1000 self.screen = pygame.display.set_mode((self.screen_width, self.screen_height)) self.font = pygame.font.Font('freesansbold.ttf', 64) self.line_thickness = 5 self.clock = pygame.time.Clock() self.set_title() # FILLS THE BACKGROUND def fill_background(self, color=Color.BLACK): self.screen.fill(color) # SETTING THE TITLE IN THE SCREEN @staticmethod def set_title(title="Puligitham"): pygame.display.set_caption(title) # UPDATES THE SCREEN @staticmethod def update(): pygame.display.flip()
306385c68e724e165af399e5ef06ca719f56f6f0
huwenbo920529/pythonBuiltIn
/collections_test.py
3,024
3.578125
4
# coding:utf-8 from collections import namedtuple, deque, Counter, OrderedDict, defaultdict # namedtuple() # namedtuple主要用来产生可以使用名称来访问元素的数据对象,通常用来增强代码的可读性, 在访问一些tuple类型的数据时尤其好用。 websites = [ ('Sohu', 'http://www.google.com/', u'张朝阳'), ('Sina', 'http://www.sina.com.cn/', u'王志东'), ('163', 'http://www.163.com/', u'丁磊') ] Website = namedtuple('Website', ['name', 'url', 'founder']) for website in websites: website = Website._make(website) print website print website.name # deque # deque其实是 double-ended queue 的缩写,翻译过来就是双端队列, # 它最大的好处就是实现了从队列 头部快速增加和取出对象: .popleft(), .appendleft() fancy_loading = deque('>--------------') n = 1 while n < 16: print '{}'.format(''.join(fancy_loading)) fancy_loading.rotate(1) n = n + 1 d1 = deque() d1.appendleft('first') d1.appendleft('second') d1.appendleft('third') d1.append('four') print d1 d1.pop() print d1 d1.popleft() print d1 d = deque(xrange(10)) print 'Normal:', d d = deque(xrange(10)) d.rotate(2) print 'Right roration:', d d = deque(xrange(10)) d.rotate(-2) print 'Left roration:', d # Counter计数器是一个非常常用的功能需求 s = '''A Counter is a dict subclass for counting hashable objects. It is an unordered collection where elements are stored as dictionary keys and their counts are stored as dictionary values. Counts are allowed to be any integer value including zero or negative counts. The Counter class is similar to bags or multisets in other languages.'''.lower() c = Counter(s) print c print c.most_common(5) # 获取出现频率最高的5个字符 # OrderedDict # 在Python中,dict这个数据结构由于hash的特性,是无序的,这在有的时候会给我们带来一些麻烦, # 幸运的是,collections模块为我们提供了OrderedDict items = ( ('A', 1), ('B', 2), ('C', 3) ) regular_dict = dict(items) ordered_dict = OrderedDict(items) print 'Regular dict:' for k, v in regular_dict.items(): print k, v print 'Ordered dict:' for k, v in ordered_dict.items(): print k, v # defaultdict # 我们都知道,在使用Python原生的数据结构dict的时候,如果用 d[key] 这样的方式访问, # 当指定的key不存在时,是会抛出KeyError异常的。 # 但是,如果使用defaultdict,只要你传入一个默认的工厂方法,那么请求一个不存在的key时, # 便会调用这个工厂方法使用其结果来作为这个key的默认值。 members = [ # gender, name ['male', 'John'], ['male', 'Jack'], ['female', 'Lily'], ['male', 'Pony'], ['female', 'Lucy'], ] result = defaultdict(list) for gender, name in members: result[gender].append(name) print result for k, v in result.items(): print k, v # collections中ChainMap的使用 # ChainMap可以合并多个dict,而且效率很高
cfb8789ffbdd2e4e09c43ddb6d326a32b8dc7fdd
huwenbo920529/pythonBuiltIn
/python_built_in_test.py
18,274
3.765625
4
# coding:utf-8 # 1.abs() 函数返回数字的绝对值。 import math print abs(-3.9) # 等价于,math.fabs(-3.9) print math.fabs(-3.9) # 2.dict() 函数用于创建一个字典。 # 语法: # class dict(**kwarg) # class dict(mapping, **kwarg) # class dict(iterable, **kwarg) print dict(a=1, b=2, c=3) # 传入关键字 print dict(zip(['a', 'b', 'c'], [1, 2, 3])) # 映射方式构造字典 print dict([('a', 1), ('b', 1), ('c', 1)]) # 可迭代方式构造字典 # 3.help() 函数用于查看函数或模块用途的详细说明。 # print help('math') a = [1, 2, 3] # print help(a) print help(a.append) # 4.min() 方法返回给定参数的最小值,参数可以为序列。 print min(2+1, 3, 6+1) # 5.setattr 函数对应函数 getatt(),用于设置属性值,该属性必须存在。 class A(object): bar = 1 a = A() setattr(a, 'bar', 5) print a.bar # 6.getattr() 函数用于返回一个对象属性值。 print getattr(a, 'bar') print getattr(a, 'bar2', 999) # 对象a中不存在属性bar2时返回999 # 7.all() 函数用于判断给定的可迭代参数 iterable 中的所有元素是否都为 TRUE,如果是返回 True,否则返回 False。 # 元素除了是 0、空、FALSE 外都算 TRUE。 s = [1, 2, 0, 3] print all(s) # 8.dir() 函数不带参数时,返回当前范围内的变量、方法和定义的类型列表;带参数时,返回参数的属性、方法列表。 # 如果参数包含方法__dir__(),该方法将被调用。如果参数不包含__dir__(),该方法将最大限度地收集参数信息。 print dir(a) # 9.hex() 函数用于将10进制整数转换成16进制,以字符串形式表示。 print hex(35) # 10.next() 返回迭代器的下一个项目。next(iterator[, default]) # default -- 可选,用于设置在没有下一个元素时返回该默认值,如果不设置,又没有下一个元素则会触发 StopIteration 异常。 it = iter(s) print next(it) # 11.slice() 函数实现切片对象,主要用在切片操作函数里的参数传递。 # class slice(stop) # class slice(start, stop[, step]) myslice = slice(5) print myslice arr = range(10) if len(arr) > 5: print arr[myslice] # 12.any() 函数用于判断给定的可迭代参数 iterable 是否全部为 False,则返回 False,如果有一个为 True,则返回 True。 # 元素除了是 0、空、FALSE 外都算 TRUE。 print any(s) # 13.python divmod() 函数把除数和余数运算结果结合起来,返回一个包含商和余数的元组(a // b, a % b), 对于浮点数,返回的是(math.floor(a/b), a%b) print divmod(5.2, 3) # 14.id() 函数用于获取对象的内存地址。 print id(s) # 15.sorted() 函数对所有可迭代的对象进行排序操作。 # sort 与 sorted 区别: # sort 是应用在 list 上的方法,sorted 可以对所有可迭代的对象进行排序操作。 # list 的sort方法返回的是对已经存在的列表进行操作,而内建函数 sorted 方法返回的是一个新的 list,而不是在原来的基础上进行的操作。 print sorted(it) # 16.ascii() 函数类似 repr() 函数, 返回一个表示对象的字符串, 但是对于字符串中的非 ASCII 字符则返回通过 repr() 函数使用 \x, \u 或 \U 编码的字符。 生成字符串类似 Python2 版本中 repr() 函数的返回值。 # print ascii('hello') python3的内置函数 # 17.enumerate() 函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标,一般用在 for 循环当中。 season = ['Spring', 'Summer', 'Fall', 'Winter'] print list(enumerate(season)) # 18.Python3.x 中 input() 函数接受一个标准输入数据,返回为 string 类型。 # Python2.x 中 input() 相等于 eval(raw_input(prompt)) ,用来获取控制台的输入。 # raw_input() 将所有输入作为字符串看待,返回字符串类型。而 input() 在对待纯数字输入时具有自己的特性,它返回所输入的数字的类型( int, float ) # 注意:input() 和 raw_input() 这两个函数均能接收 字符串 ,但 raw_input() 直接读取控制台的输入(任何类型的输入它都可以接收)。而对于 input() ,它希望能够读取一个合法的 python 表达式,即你输入字符串的时候必须使用引号将它括起来,否则它会引发一个 SyntaxError 。 # 除非对 input() 有特别需要,否则一般情况下我们都是推荐使用 raw_input() 来与用户交互。 # 注意:python3 里 input() 默认接收到的是 str 类型。 # input() 需要输入 python 表达式 # a = input("input a:") # print type(a) # b = input("input b:") # 需要输入正确的python表达式, 比如:"hello"而不是hello # print type(b) # # raw_input() 将所有输入作为字符串看待 # a = raw_input("input a:") # print type(a) # b = raw_input("input b:") # print type(b) # 19.oct() 函数将一个整数转换成8进制字符串。 print oct(21) # 20.python staticmethod 返回函数的静态方法。该方法不强制要求传递参数. class C(object): @staticmethod def f(): print 'hello' C.f() # 静态方法无需实例化 c_object = C() c_object.f() # 也可以实例化后调用 # 21.bin() 返回一个整数 int 或者长整数 long int 的二进制表示。 print bin(6) # 22.eval() 函数用来执行一个字符串表达式,并返回表达式的值。 x = 7 print eval('3*x') # 23.int() 函数用于将一个字符串或数字转换为整型。 # class int(x, base=10) x -- 字符串或数字; base -- 进制数,默认十进制。 print int('0xa', 16) # 24.python open() 函数用于打开一个文件,创建一个 file 对象,相关的方法才可以调用它进行读写。 # 25.str() 函数将对象转化为适于人阅读的形式。 # 26.bool() 函数用于将给定参数转换为布尔类型,如果没有参数,返回 False。 # 27.exec 执行储存在字符串或文件中的 Python 语句,相比于 eval,exec可以执行更复杂的 Python 代码, exec 返回值永远为 None。 exec("""for i in range(5): print i""") # 28.isinstance() 函数来判断一个对象是否是一个已知的类型,类似 type() print isinstance(c_object, C) print isinstance(c_object, (int, str, list)) # 是元组中的一个返回 True # 29.ord() 函数是 chr() 函数(对于8位的ASCII字符串)或 unichr() 函数(对于Unicode对象)的配对函数,它以一个字符(长度为1的字符串)作为参数, # 返回对应的 ASCII 数值,或者 Unicode 数值,如果所给的 Unicode 字符超出了你的 Python 定义范围,则会引发一个 TypeError 的异常。 print ord('a') # 30.sum() 方法对系列进行求和计算。sum(iterable[, start]) start -- 指定相加的参数,如果没有设置这个值,默认为0。 li = [1, 2, 3, 4] print sum(li) print sum(li, 2) # 列表计算总和后再加 2 # 31.bytearray() 方法返回一个新字节数组。这个数组里的元素是可变的,并且每个元素的值范围: 0 <= x < 256 print bytearray([1, 2, 3])[0] print bytearray('runoob', 'utf-8')[0] # 31.filter() 函数用于过滤序列,过滤掉不符合条件的元素,返回由符合条件元素组成的新列表。filter(function, iterable) # function -- 判断函数。 iterable -- 可迭代对象。 def is_odd(n): return n % 2 == 1 newlist = filter(is_odd, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) print(newlist) # 32.issubclass() 方法用于判断参数 class 是否是类型参数 classinfo 的子类。issubclass(class, classinfo) class A(object): pass class B(A): pass print(issubclass(B, A)) # 33.pow() 方法返回 xy(x的y次方)的值 pow(x, y[, z]) print pow(2, 3) # math 模块 pow() # 函数是计算x的y次方,如果z在存在,则再对结果进行取模,其结果等效于pow(x,y) %z,注意:x,y,z必须为整数 # 注意:pow() 通过内置的方法直接调用,内置方法会把参数作为整型,而 math 模块pow只含两个参数,且会把参数转换为 float print pow(2, 3, 3) print math.pow(2.1, 3.1) # 34.super() 函数是用于调用父类(超类)的一个方法。 # super 是用来解决多重继承问题的,直接用类名调用父类方法在使用单继承的时候没问题,但是如果使用多继承,会涉及到查找顺序(MRO)、重复调用(钻石继承)等种种问题。 # MRO 就是类的方法解析顺序表, 其实也就是继承父类方法时的顺序表 class FooParent(object): def __init__(self): self.parent = "I'am the parent" print "Parent" def bar(self, message): print "{} from Parent".format(message) class FooChild(FooParent): def __init__(self): super(FooChild, self).__init__() # super(FooChild,self) 首先找到 FooChild 的父类(就是类 FooParent),然后把类B的对象 FooChild 转换为类 FooParent 的对象 print 'child' def bar(self, message): super(FooChild, self).bar(message) print 'Child bar function' print self.parent fooChild = FooChild() fooChild.bar('helloWorld!') # 35.bytes 函数返回一个新的 bytes 对象,该对象是一个 0 <= x < 256 区间内的整数不可变序列。它是 bytearray 的不可变版本。 # 36.float() 函数用于将整数和字符串转换成浮点数。 # 37.iter() 函数用来生成迭代器。iter(object[, sentinel]) # object -- 支持迭代的集合对象。 # sentinel -- 如果传递了第二个参数,则参数 object 必须是一个可调用的对象(如,函数), # 此时,iter 创建了一个迭代器对象,每次调用这个迭代器对象的__next__()方法时,都会调用 object。 lst = [1, 2, 3] for i in iter(lst): print(i) # 38.print() 方法用于打印输出,最常见的一个函数。 # 39.tuple 函数将列表转换为元组。。 # 40.callable() 函数用于检查一个对象是否是可调用的。如果返回True,object仍然可能调用失败;但如果返回False,调用对象ojbect绝对不会成功 # 对于函数, 方法, lambda 函式, 类, 以及实现了 __call__ 方法的类实例, 它都返回 True。 class A(object): def method(self): pass print callable(A) # 类返回true a = A() print callable(a) # 没有实现 __call__,返回false # format --Python2.6 开始,新增了一种格式化字符串的函数 str.format(),它增强了字符串格式化的功能。 # 基本语法是通过 {} 和 : 来代替以前的 % class AssignValue(object): def __init__(self, value): self.value = value my_value = AssignValue(6) print 'value为:{0.value}'.format(my_value) print("{:.2f}".format(3.1415926)) # 数字 格式 输出 描述 # 3.1415926 {:.2f} 3.14 保留小数点后两位 # 3.1415926 {:+.2f} +3.14 带符号保留小数点后两位 # -1 {:+.2f} -1.00 带符号保留小数点后两位 # 2.71828 {:.0f} 3 不带小数 # 5 {:0>2d} 05 数字补零 (填充左边, 宽度为2) # 5 {:x<4d} 5xxx 数字补x (填充右边, 宽度为4) # 10 {:x<4d} 10xx 数字补x (填充右边, 宽度为4) # 1000000 {:,} 1,000,000 以逗号分隔的数字格式 # 0.25 {:.2%} 25.00% 百分比格式 # 1000000000{:.2e} 1.00e+09 指数记法 # 13 {:10d} 13 右对齐 (默认, 宽度为10) # 13 {:<10d} 13 左对齐 (宽度为10) # 13 {:^10d} 13 中间对齐 (宽度为10) # 11 '{:b}'.format(11) 1011 进制 # '{:d}'.format(11) 11 # '{:o}'.format(11) 13 # '{:x}'.format(11) b # '{:#x}'.format(11) 0xb # '{:#X}'.format(11) 0XB # ^, <, > 分别是居中、左对齐、右对齐,后面带宽度, : 号后面带填充的字符,只能是一个字符,不指定则默认是用空格填充。 # + 表示在正数前显示 +,负数前显示 -; (空格)表示在正数前加空格 # b、d、o、x 分别是二进制、十进制、八进制、十六进制。 # 此外我们可以使用大括号 {} 来转义大括号,如下实例: print ("{} 对应的位置是 {{0}}".format("runoob")) # 41.len()方法返回对象(字符、列表、元组等)长度或项目个数。 # 42.property() 函数的作用是在新式类中返回属性值。 class property([fget[, fset[, fdel[, doc]]]]) # fget -- 获取属性值的函数 # fset -- 设置属性值的函数 # fdel -- 删除属性值函数 # doc -- 属性描述信息 class C(object): def __init__(self): self._x = None def getx(self): return self._x def setx(self, value): self._x = value print self._x def delx(self): del self._x print 'del self._x' x = property(getx, setx, delx, "I'am the 'x' property") c = C() print c.x # 触发 getx c.x = 1 # 触发 setx del c.x # 触发 delx # 43.type() 函数如果你只有第一个参数则返回对象的类型,三个参数返回新的类型对象。 # isinstance() 与 type() 区别: # type() 不会认为子类是一种父类类型,不考虑继承关系。 # isinstance() 会认为子类是一种父类类型,考虑继承关系。 # 44.chr() 用一个范围在 range(256)内的(就是0~255)整数作参数,返回值是当前整数对应的ascii字符。 print chr(97) # 45.frozenset() 返回一个冻结的集合,冻结后集合不能再添加或删除任何元素。class frozenset([iterable]) print frozenset(range(10)) # 46.list() 方法用于将元组转换为列表。 # 47.Python3 range() 函数返回的是一个可迭代对象(类型是对象),而不是列表类型, 所以打印的时候不会打印列表。 # Python3 list() 函数是对象迭代器,可以把range()返回的可迭代对象转为一个列表,返回的变量类型为列表。 # Python2 range() 函数返回的是列表。 # 47.vars() 函数返回对象object的属性和属性值的字典对象 class A(object): a = 1 print vars(A) a = A() print vars(a) # {} # 48.classmethod 修饰符对应的函数不需要实例化,不需要 self 参数,但第一个参数需要是表示自身类的 cls 参数,可以来调用类的属性,类的方法,实例化对象等。 class A(object): bar = 1 def func1(self): print 'foo' @classmethod def func2(cls): print 'func2' print cls.bar cls().func1() # 注意调用类的方法和获得类的属性的不同之处 A.func2() # 49.locals() 函数会以字典类型返回当前位置的全部局部变量。 # 对于函数, 方法, lambda 函式, 类, 以及实现了 __call__ 方法的类实例, 它都返回 True。 def hel(arg): z = 1 print locals() hel(2) # 50.repr() 函数将对象转化为供解释器读取的形式。 dic = {'runoob': 'runoob.com', 'google': 'google.com'} print repr(dic) # 51.zip() 函数用于将可迭代的对象作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的对象,这样做的好处是节约了不少的内存。 # 如果各个迭代器的元素个数不一致,则返回列表长度与最短的对象相同.利用 * 号操作符,可以将元组解压为列表。 a = [1, 2, 3] b = [4, 5, 6] c = [7, 8, 9, 10] print list(zip(a, b)) # [(1, 4), (2, 5), (3, 6)] print list(zip(a, c)) # [(1, 7), (2, 8), (3, 9)] print zip(*zip(a, c)) # 与 zip 相反,*zip 可理解为解压,返回二维矩阵式 [(1, 2, 3), (7, 8, 9)] # 52.compile() 函数将一个字符串编译为字节代码。 # compile(source, filename, mode[, flags[, dont_inherit]]) # source -- 字符串或者AST(Abstract Syntax Trees)对象。。 # filename -- 代码文件名称,如果不是从文件读取代码则传递一些可辨认的值。 # mode -- 指定编译代码的种类。可以指定为 exec, eval, single。 # flags -- 变量作用域,局部命名空间,如果被提供,可以是任何映射对象。。 # flags和dont_inherit是用来控制编译源码时的标志 st = "for i in range(0,10): print(i)" c = compile(st, '', 'exec') # 编译为字节代码对象 exec(c) # 53.globals() 函数会以字典类型返回当前位置的全部全局变量。 print globals() # 54.map() 会根据提供的函数对指定序列做映射。 # 第一个参数 function 以参数序列中的每一个元素调用 function 函数,返回包含每次 function 函数返回值的新列表.Python 3.x 返回迭代器。 print map(lambda x: x ** 2, [1, 2, 3, 4]) print map(lambda x, y: x+y, [1, 3, 5, 7], [2, 4, 6, 8]) # 55.reversed 函数返回一个反转的迭代器。 print list(reversed([1, 3, 5])) # 56.__import__() 函数用于动态加载类和函数。如果一个模块经常变化就可以使用 __import__() 来动态载入。 # 57.complex() 函数用于创建一个值为 real + imag * j 的复数或者转化一个字符串或数为复数。如果第一个参数为字符串,则不需要指定第二个参数。 # 58.hasattr() 函数用于判断对象是否包含对应的属性。 # 59.max() 方法返回给定参数的最大值,参数可以为序列。 print max([1, 9, 0, 2, 7]) # 60.round() 方法返回浮点数x的四舍五入值。round( x [, n]) print round(1.2242, 3) # 61.delattr 函数用于删除属性。delattr(x, 'foobar') 相等于 del x.foobar。 # 62.hash() 用于获取取一个对象(字符串或者数值等)的哈希值。 # hash() 函数可以应用于数字、字符串和对象,不能直接应用于 list、set、dictionary。 # 在 hash() 对对象使用时,所得的结果不仅和对象的内容有关,还和对象的 id(),也就是内存地址有关。 class Test: def __init__(self, i): self.i = i for i in range(2): t = Test(1) print(hash(t), id(t)) # 63.memoryview() 函数返回给定参数的内存查看对象(Momory view)。 # 所谓内存查看对象,是指对支持缓冲区协议的数据进行包装,在不需要复制对象基础上允许Python代码访问 v = memoryview('abcefg') print v[1] # 64.set() 函数创建一个无序不重复元素集,可进行关系测试,删除重复数据,还可以计算交集、差集、并集等。 x = set('runoob') y = set('google') print x, y print x & y # 交集 print x | y # 并集 print x - y # 差集
e988f63eb96e701e6c40e8c48b3083603e36746a
nbandodk/Misc
/permutationOfPalindrome.py
440
3.578125
4
import string def isPermutationOfPalindrome(str): d = dict.fromkeys(string.ascii_lowercase, False) count = 0 for char in str: if(ord(char) > 96 and ord(char) < 123): d[char] = not d[char] for key in d: if d[key] == True: count += 1 if count > 1: return False return True print isPermutationOfPalindrome("aabbcceee")
590026f07d4beb574733ce77b498c448653dd013
Prakhyath07/INEURON_ASSIGNMENTS
/ASSIGNMENT-3/3.1.1__myreduce.py
344
3.515625
4
def myreduce(func,iterable,initializer=None): l=len(iterable)-1 if initializer==None: a=iterable[0] for i in range(l): b=iterable[i+1] a=func(a,b) else: a=initializer for i in range(l): b=iterable[i] a=func(a,b) return a
b71c86c8d2f1bdb62981bf87d39f7b64785c26fa
Prakhyath07/INEURON_ASSIGNMENTS
/ASSIGNMENT-4/4.1.2__FILETERWRONGWORDS.PY
263
3.578125
4
def filter_long_words(words,n): long=[] if type(words) is list: for word in words: if len(word)>n: long.append(word) return long else: return "Plese enter words inside a list"
3966d55212271c1a681156beaee25f6820a076fc
zsamantha/coding_challenge
/calc.py
1,217
4.125
4
import math print("Welcome to the Calculator App") print("The following operations are available: + - / *") print("Please separate entries with a space. Ex: Use 1 + 2 instead of 1+2") print("Type \"Q\" to quit the program.") result = None op = None while(True): calc = input().strip().split() if calc[0].lower() == "q": break for item in calc: if item.isnumeric(): if result is None: result = int(item) else: num = int(item) if op == "+": result += num elif op == "-": result -= num elif op == "*": result *= num elif op == "/": result /= num else: print("Bad Input.") result = None break elif item.isalpha(): print("Bad Input") result = None break else: op = item if result is not None: if result % 1 == 0: print("= ", math.trunc(result)) else: print("= {0:.2f}".format(result)) print("Goodbye :)")
f23c780e6f960278ee0462ed83a828b475c58f1b
flipbug/2048_ai
/heuristicai.py
6,139
3.90625
4
import random import game import sys from util import get_possible_merges, UP, DOWN, LEFT, RIGHT # Author: chrn (original by nneonneo) # Date: 11.11.2016 # Description: The logic of the AI to beat the game. THRESHOLD = 8 MIN_THRESHOLD = 2 OPTIMAL_POSITION_WEIGHT = 2 BEST_MERGE_WEIGHT = 2 FUTURE_MERGE_WEIGHT = 2 DIRECTION_WEIGHT = [1, 1, 1, 1] def find_best_move(board): bestmove = -1 # Build a heuristic agent on your own that is much better than the random agent. # Your own agent don't have to beat the game. bestmove = find_best_move_rule_agent(board, THRESHOLD) if bestmove == -1: # Fallback to random agent if no optimal move has been found # print('random') bestmove = find_best_move_random_agent() return bestmove def find_best_move_random_agent(): return random.choice([UP, DOWN, LEFT, RIGHT]) def find_best_move_rule_agent(board, threshold=0): possible_moves = [] # 1. Rule move, value = find_move_by_highest_merge(board, threshold) possible_moves.append((move, value)) # 2. Rule move, value = find_move_by_future_outcome(board, threshold) possible_moves.append((move, value)) # 3. Rule (disabled) move, value = find_move_by_optimal_position(board) possible_moves.append((-1, value)) # 4. Rule move, value = find_move_by_number_of_merges(board) possible_moves.append((move, value)) # select move with highest value move = select_best_possible_move(possible_moves, board) if move == -1: if threshold > MIN_THRESHOLD: # try again with lower threshold move = find_best_move_rule_agent(board, threshold/2) else: # 3. Rule as fallback move, value = find_move_by_optimal_position(board) # print('Rule 3 fallback') return move def find_move_by_highest_merge(board, threshold=8): """ Search for possible merges and use the move with the biggest number and larger than the threshold. """ move = -1 value = -1 possible_merges = get_possible_merges(board, direction_weight=DIRECTION_WEIGHT) if possible_merges and possible_merges[0]['number'] > threshold: move = possible_merges[0]['move'] value = possible_merges[0]['number'] # weight adjustment value = value * BEST_MERGE_WEIGHT return move, value def find_move_by_future_outcome(board, threshold=8): """ Move tiles to get a good merge (larger than the threshold) in the next round """ move = -1 value = -1 next_moves = {UP: 0, DOWN: 0, LEFT: 0, RIGHT: 0} for m in next_moves.keys(): new_board = execute_move(m, board) new_possible_moves = get_possible_merges(new_board, direction_weight=DIRECTION_WEIGHT) next_moves[m] = new_possible_moves[0]['number'] if new_possible_moves else -1 possible_move, value = find_best_move_in_dict(next_moves) if value > threshold: move = possible_move # weight adjustment value = value * FUTURE_MERGE_WEIGHT return move, value def find_move_by_number_of_merges(board): """ Use direction with the most merges """ move = -1 value = -1 possible_merges = get_possible_merges(board, direction_weight=DIRECTION_WEIGHT) amount_of_merges = {UP: 0, DOWN: 0, LEFT: 0, RIGHT: 0} for merge in possible_merges: amount_of_merges[merge['move']] += 1 # search direction with th most merges possible_move, value = find_best_move_in_dict(amount_of_merges) if value > 2: move = possible_move # weight adjustment value = value^2 return move, value def find_move_by_optimal_position(board): """ Maximize the top and left column to keep higher tiles together and out of the middle """ move = -1 value = -1 moves = [(),()] # first check top column top_sum = sum(board[0]) for row in board: row_sum = sum(row) if top_sum < row_sum: moves[0] = (UP, row_sum) # second check left column left_sum = sum([row[0] for row in board]) for index,_ in enumerate(board): col_sum = sum([row[index] for row in board]) if left_sum < col_sum: moves[1] = (LEFT, col_sum) # check if a move is possible for m in moves: if len(m) == 2 and not board_equals(board, execute_move(m[0], board)): move = m[0] value = m[1] # small cheat value = OPTIMAL_POSITION_WEIGHT return move, value def select_best_possible_move(moves, board): """ Select the best possible move by value. Additionaly check if the board gets stuck and choose another move to prevent this. """ move = -1 max_value = 0 index = 0 for idx, item in enumerate(moves): # set a weight for directions # value = item[1] * DIRECTION_WEIGHT[item[0]] value = item[1] if value > max_value and item[0] >= 0: max_value = value move = item[0] index = idx #print(moves) # check if the move is possible, otherwise discard it and try again if move > -1 and board_equals(board, execute_move(move, board)): del moves[index] move = select_best_possible_move(moves, board) #print('Used Rule: {}'.format(index + 1)) return move def find_best_move_in_dict(move_dict): move = -1 max_value = 0 for key, value in move_dict.items(): if value > max_value: max_value = value move = key return move, max_value def execute_move(move, board): """ move and return the grid without a new random tile It won't affect the state of the game in the browser. """ if move == UP: return game.merge_up(board) elif move == DOWN: return game.merge_down(board) elif move == LEFT: return game.merge_left(board) elif move == RIGHT: return game.merge_right(board) else: sys.exit("No valid move") def board_equals(board, newboard): """ Check if two boards are equal """ return (newboard == board).all()
31d0b19e04fce106e14c19aec9d7d6f463f0d852
panchaly75/MyCaptain_AI
/AI_MyCaptainApp_03(1).py
863
4.3125
4
#Write a Python Program for Fibonacci numbers. def fibo(input_number): fibonacci_ls=[] for count_term in range(input_number): if count_term==0: fibonacci_ls.append(0) elif count_term==1: fibonacci_ls.append(1) else: fibonacci_ls.append(fibonacci_ls[count_term-2]+fibonacci_ls[count_term-1]) return fibonacci_ls number = int(input("Enter how much terms you want?\t:\t")) ls = fibo(number) print(ls) ''' #if you want to print without list type, so in place of print(ls), you can use below lines of code for item in ls: print(item, end=' ') #in place of define fuction you may also use only for loop https://github.com/panchaly75/MyCaptainPythonProjects/blob/main/project03.py in this above github link has same code with for loop ''' #https://colab.research.google.com/drive/1gK-J2dPT7Cn5HP0EFNJrf0S-6x0pyWki?usp=sharing
e5ad375c76600d598f605ed7434046c40d7b356b
flaviocardoso/myCodelearnpythonTHW
/ex15.py
388
3.828125
4
from sys import argv #import of system argv script, filename = argv #argument of scropt and file name (insert) txt = open(filename) # open file print ("Here's your file %r" % filename) # print a string describer the file name print (txt.read()) # print from read file print ("Type the filename again:") file_again = input("> ") txt_again = open(file_again) print (txt_again.read())
5d8aad14ee2fc3f7dec59334444cfcbfd6359f52
SSDD11/Some-Small-Projects--Monty-Hall-
/ackermann.py
656
3.8125
4
''' Created on Apr 6, 2016 @author: Administrator ''' import math def ack(x, y): if x == 0: return y + 1 elif y == 0: return ack(x - 1, 1) else: return ack(x - 1, ack(x, y-1)) print "0, 0:", ack(0, 0) print "0, 2:", ack(0, 2) print "3, 0:", ack(3, 0) print "2, 2:", ack(2, 2) print "3, 3:", ack(3, 3) print "2, 3:", ack(2, 3) print "3, 2:", ack(3, 2) print "2, 1:", ack(2, 1) print "1, 2:", ack(1, 2) print "3, 1:", ack(3, 1) print "1, 3:", ack(1, 3) print "4, 0:", ack(4, 0) print "0, 4:", ack(0, 4) print "3, 4:", ack(3, 4) print "Ackermann 4,3, max recursion" print "end"
5e3c27923416fe3aa7921fef222d9b3c09182c28
jcberntsson/networks
/utils/loading.py
2,365
3.546875
4
# (c) 2019 Joakim Berntsson # Loading of data. import csv import pandas as pd import tensorflow as tf import numpy as np class Loader: """Data loading class with support for: * loading csv files using pandas * data curation * column selection * creating train/test split with normalization. Note that this class only supports continuous values. """ def __init__(self, filepath): self._data = pd.read_csv(filepath, header=0) def get_data(self): """Get the underlying pandas dataframe.""" return self._data def apply(self, column_name, func): """Apply a function to a specific column to curate data.""" self._data = self._data.dropna(subset=[column_name]) self._data[column_name] = self._data[column_name].apply(func) def set_features(self, features: list): """Limit the loader to certain columns.""" self._data = self._data[features] def get_data_split(self, train_fraction: float, target_name: str = 'target'): """Split the underlying dataframe into train/test sets. Note that the returned objects are TensorSliceDatasets.""" features = self._data.columns.difference([target_name]) # Divide into train and test train = self._data.sample(frac=train_fraction, random_state=200) test = self._data.drop(train.index) train_data = train[features].values.astype(float) train_labels = np.expand_dims(train[target_name].values, axis=1) test_data = test[features].values.astype(float) test_labels = np.expand_dims(test[target_name].values, axis=1) # Normalize train_mean = train_data.mean(axis=0) train_std = train_data.std(axis=0) train_data = (train_data - train_mean) / train_std test_data = (test_data - train_mean) / train_std # Construct tensorflow datasets train_dataset = tf.data.Dataset.from_tensor_slices(( tf.cast(train_data, tf.float32), tf.cast(train_labels, tf.float32))) test_dataset = tf.data.Dataset.from_tensor_slices(( tf.cast(test_data, tf.float32), tf.cast(test_labels, tf.float32))) return train_dataset, test_dataset def get_features(self): """Get the features for the data.""" return self._data.columns
1b96269e657f2792c7a35b4f2f4ade76f1cc2bd7
premlogan/Early-Warning-System-to-Predict-Students-at-Risk-of-Not-Graduating-High-School
/utils.py
5,787
3.5625
4
# Import libraries import pandas as pd import numpy as np import matplotlib.pyplot as plt # Function desc: load_data function reads SQL query to extract data from Postgres db and loads into dataframe # Input: .txt file SQL ETL query and engine with database connection information # Returns: Dataframe with data extracted from database def load_data(file, engine): query = open(file, "r").read() dataset = pd.read_sql(query, engine) return dataset # Function desc: df_to_db function loads the training and test dataset to database for easier retrival. # Input: Name of the database table to store test and train data, name of schema where table should be created, # train and test dataframe and database engine with database connection information # Returns: None def df_to_db(table_name, schema, train_df, test_df, engine): train_df['split'] = 'train' test_df['split'] = 'test' train_df.to_sql(name = table_name, schema = schema, con = engine, if_exists = 'append', index = False) test_df.to_sql(name = table_name, schema = schema, con = engine, if_exists = 'append', index = False) # Function desc: db_to_df function extracts the test and train data from database for a cohort and creates dataframe for processing # Input: Name of the table with train and test data, name of the scheme, engine with database connection information # Returns: Dataframe with train data and dataframe with test data for a given cohort def db_to_df(table_name, schema, engine): train_query = '''SELECT * FROM {} WHERE split = 'train' '''.format(schema + '."' + table_name + '"') test_query = '''SELECT * FROM {} WHERE split = 'test' '''.format(schema + '."' + table_name + '"') train_df = pd.read_sql(train_query, engine).drop('split', axis = 1) test_df = pd.read_sql(test_query, engine).drop('split', axis = 1) return train_df, test_df # Function desc: top_idx function identifies the students with highest risk score based on the predicted probability of not grduating # Input: Predicted probability scores for each student and 0.1 as default for getting top 10% of the students at risk of not graduating # Returns: Index of top 10% of students at risk of not graduating def top_idx(pred_proba, topP=0.1): topK = int(topP * len(pred_proba)) riskiest_idx = np.argsort(pred_proba) # smallest to largest, want largest to smallest riskiest_idx = np.flip(riskiest_idx)[:topK] return riskiest_idx # Function desc: top_precision determines the proportion of correctly identified at risk students at some top precision level # Input: labels of ground truth graduation status, prediction probabilities for each student, percentile for cutoff # Returns: Precision score def top_precision(label_test, pred_proba, topP = 0.1): topK = int(topP * len(pred_proba)) riskiest_idx = top_idx(pred_proba, topP=topP) riskiest_label = label_test[riskiest_idx] return np.sum(riskiest_label) / topK # Function desc: top_accuracy determines the ratio between the number of students in some top percentile that will not graduate # and the number of all positive labels in the test set # Input: labels of ground truth graduation status, prediction probabilities for each student, percentile for cutoff # Returns: Accuracy scores def top_accuracy(label_test, pred_proba, topP = 0.1): riskiest_idx = top_idx(pred_proba, topP=topP) riskiest_label = label_test[riskiest_idx] return np.sum(riskiest_label) / np.sum(label_test) # Function desc:bias_metrics function calculates the recall disparity and false discovery rate for gender and disadvantagement # Input: 1. ,2. ,3. list of features with gender and disadvantagement as values # Returns: def bias_metrics(df_pred, df_processed, feature): df = df_pred.merge(df_processed, on = 'student_lookup') df = df.sort_values(by = 'probability', ascending = False) topP = 0.1 topK = int(topP * len(df)) df = df.head(topK) if feature == 'gender': protect_group_true = df_processed[df_processed.gender_M == 1].not_graduated.sum() protect_group_pred = df[df.gender_M == 1].not_graduated.sum() reference_group_true = df_processed[df_processed.gender_F == 1].not_graduated.sum() reference_group_pred = df[df.gender_F == 1].not_graduated.sum() protect_pred = len(df[df.gender_M == 1]) protect_true = df[df.gender_M == 1].not_graduated.sum() protect_wrong = protect_pred - protect_true reference_pred = len(df[df.gender_F == 1]) reference_true = df[df.gender_F == 1].not_graduated.sum() reference_wrong = reference_pred - reference_true elif feature == 'disadvantagement': protect_group_true = df_processed[df_processed.disadvantagement_economic == 1].not_graduated.sum() protect_group_pred = df[df.disadvantagement_economic == 1].not_graduated.sum() reference_group_true = df_processed[df_processed.disadvantagement_no_disadvantagement == 1].not_graduated.sum() reference_group_pred = df[df.disadvantagement_no_disadvantagement == 1].not_graduated.sum() protect_pred = len(df[df.disadvantagement_economic == 1]) protect_true = df[df.disadvantagement_economic == 1].not_graduated.sum() protect_wrong = abs(protect_pred - protect_true) reference_pred = len(df[df.disadvantagement_no_disadvantagement == 1]) reference_true = df[df.disadvantagement_no_disadvantagement == 1].not_graduated.sum() reference_wrong = abs(reference_pred - reference_true) recall_disparity = (protect_group_pred/protect_group_true)/(reference_group_pred/reference_group_true) fdr = (protect_wrong/protect_pred)/(reference_wrong/reference_pred) return recall_disparity, fdr
88edd09cd4cb32f70797774e6e41686dac33f515
bughunt88/python_study_2020
/python_basic/test.py
214
3.671875
4
def solution(arr, divisor): answer = [] list = [] for i in arr: if i%divisor == 0: list.append(i) list.sort() return list print(sum(range(1,3)))
bf3b1c591e8834c6f9448d48bdb55285244925c8
bughunt88/python_study_2020
/python_basic/python_for.py
2,007
3.734375
4
# 파이썬 반복문 # FOR 실습 # 코딩의 핵심 # for in <collection> # <Loop body> for v1 in range(10): # 0~9 print(v1) print() for v2 in range(1,11): # 1~10 print(v2) print() # 2의 배수 for v3 in range(1,11,2): print(v3) # 1 ~ 1000 합 sum1 = 0 for v in range(1,1001): sum1 += v print('1 ~ 1000 Sum : ', sum1) print('1 ~ 1000 sum : ', sum(range(1,1001))) # Iterables 자료형 반복 # 문자열, 리스트, 튜플, 집합, 사전(딕셔너리) # iterable 리턴 함수 : range, reversed, enumerate, filter, map, zip # 예제1 names = ['kim', 'park', 'cho', 'um' ] for n in names: print(n) # 예제2 lotto_numbers = [11, 19, 21, 28, 36, 37] for n in lotto_numbers: print(n) word = "beautiful" # 예제3 for s in word: print(s) # 예제4 my_info = { "name": 'lee', "age": 33 } for key in my_info: print(my_info[key]) for v in my_info.values(): print(v) # 예제5 name = 'FineAppLE' for n in name: if n.isupper(): # 대문자 확인 코드 print(n) else: print(n.upper()) # break numbers = [14,3,4,7,10,24,17,2,33,15,30,34,36,38] for num in numbers: if num == 34: print("find") break else: print("num") # continue : for 진행 중 넘겨버리는 코드 it = ["1",2,5,True, 4.3, complex(4)] for v in it: if type(v) is bool: continue print(type(v)) # for - else # for가 다 돌고 이상이 없으면 else 구문이 나오도록 한다 (break가 없으면 실행된다) numbers = [14,3,4,7,10,24,17,2,33,15,34,36,38] for num in numbers: if num == 24: print("found 24") break else: print('not found : 24') # 구구단 출력 for n in range(2,10): for n1 in range(1,10): print('{:4d}'.format(n*n1), end='') print() # 변환 예제 name2 = 'aceman' print(reversed(name2)) print(list(reversed(name2))) print(tuple(reversed(name2))) print(set(reversed(name2))) # 집합 - 순서x
ebb169123be03b88cdd6dcfab33657bd4a60f573
Devlin1834/Games
/collatz.py
1,792
4.15625
4
## Collatz Sequence ## Idea from Al Sweigart's 'Automate the Boring Stuff' def collatz(): global over over = False print("Lets Explore the Collatz Sequence") print("Often called the simplest impossible math problem,") print("the premise is simple, but the results are confusing!") print("Lets start and see if you can catch on...") c = '' while c == '': try: c = int(input("Type in any integer: ")) except ValueError: print("Thats very funny but its NOT an integer") while c != 1: if c % 2 == 0: c = c // 2 print(c) elif c % 2 == 1: c = (3 * c) + 1 print(c) if c == 1: print("Do you get it?") print("For ANY real integer, you can reduce it down to 1 using the Collatz Sequence") print("If the number is even, take n/2") print("If the number is odd, take 3n+1") print("Follow that sequence with your answers until you reach 1") print() print("Lets keep going") print("Type 0 at any point to return to the Games screen") while over == False: newc = '' while newc != 0: try: print("-" * 65) newc = int(input("Type in any number: ")) except ValueError: print("Thats very funny but its NOT a number") if newc == 0: over = True break while newc != 1: if newc % 2 == 0: newc = newc // 2 print(newc) elif newc % 2 == 1: newc = (3 * newc) + 1 print(newc)
6d670cc158afe0b3c3e6206c0c351a49237ca6b8
ssxday/Python35
/functions.py
5,298
3.9375
4
# -*- coding: utf-8 -*- # 列表作为参数传递 def jisuan(args=[]): x, y = args # 在函数内部解包,但参数数量必须等于列表长度 return x + y print(jisuan([1, 2])) # 参数需要传列表,而不能只传值 # 传递可变参数!!! def changing(*args): # 用*表示引用元组 print(args) changing(1, 2, 3, 6) def search(*t, **d): # 用**表示引用字典 keys = d.keys() values = d.values() print(keys, values) for i in t: for k in keys: if i == k: print('find:', d[k]) # *务必要写在**前面!! search(1, 'two', 'one', two='twooooooo') # 实参不能加引号 # 函数返回多个值 # 思路:打包进元组,调用时解包 def fanhuiduogezhi(x, y, z): l = [x, y, z] l.reverse() numbers = tuple(l) return numbers # fanhuiduogezhi()最终返回的实际是一个元组,调用时拆包 x, y, z = fanhuiduogezhi(7, 8, 9) print(z) def fanhuiduo(*t): l = list(t) l.reverse() a, b, c = tuple(l) return a, b, c x, y, z = fanhuiduo(6, 9, 15) # 如果在函数内部解包了,也要在外面分别对应上 print(x) # lambda匿名函数 # 1、变量可以作为函数使用 lmd = lambda x, y: x ** y print(lmd(2, 3)) # 2、lambda直接做函数 print((lambda x: -x)(-19)) # 求相反数 # 注意:lambda中只能用表达式,不能用判断、循环这类多重语句 # generator函数,在循环中,一次只返回一个值 def gnrt(n): for i in range(n): yield i ** 2 print("gnrt:", gnrt(6)) r = gnrt(6) print(r.__next__()) # exercise5 s = lambda x, y: x + y print('exercise5:\n', s('aa', 'bb')) print('*' * 30) # 函数中引用的全局变量,只是那个模块中的全局变量。 from gl import foo_fun name = 'Current module' def bar(): print('当前模块中函数bar:') print('变量name:', name) def call_foo_fun(fun): fun() if __name__ == '__main__': bar() print() foo_fun() print() call_foo_fun(foo_fun) # 闭包:打包函数和函数的执行环境,比如函数所需的全局变量,都在一个大的闭包对象里 print('\n闭包:') s = '模块级全局变量' def bibao(): s = '嵌入函数的执行环境' def show(s): print(s) show(s) bibao() # 可见是里面的s被执行了 # 延迟执行 print('延迟执行 及 泛型函数:') def delay_func(a,b): def eryuanyicifangcheng(x): print(a * x + b) return eryuanyicifangcheng eyyc = delay_func(3,4) print(eyyc) eyyc(8) print('上下文管理器:') class FileMgr: """ 定义一个文件资源打开、关闭的管理器 """ def __init__(self,pathname): self.pathname = pathname self.f = None # 此时还不用open文件资源 def __enter__(self): self.f = open(self.pathname, 'r', encoding='utf-8') return self.f # __enter__()一定要把资源return出来,as语句将与之绑定!! def __exit__(self, exc_type, exc_val, exc_tb): # 各种exc参数用来跟踪错误 # 退出with语句时执行 if self.f: self.f.close() print('file closed.') # 使用上下文管理器(ContextManager) with FileMgr('./chaoxie.txt') as f: l1 = f.readline() f.readline() l2 = f.readline() print(l1, l2) # with结束之时,资源也就关闭了,不用再手动关一次 # 使用装饰器装饰生成器,使其变成一个上下文管理器,那么yield后的表达式即为as后的变量 import contextlib # help(contextlib.ContextDecorator) @contextlib.contextmanager def my_gnr(n): print('yield之前') yield n print('yield结束') m5 = my_gnr(5) # 使用上下文管理器 with m5 as val: print(val) print(val) print(val) print(val) print(val) print(hasattr(m5,"__enter__")) class DemoClass: class_val = 'leishuxing' def __init__(self): self.x = 'shilix' print(self.class_val) # 用字符串操作对象属性 print('用字符串操作对象属性'.center(30,'*')) dc = DemoClass() # print(dc.class_val) # print(DemoClass.class_val) setattr(DemoClass,'fuck','zhangsan') print('newly created attibute fuck:',DemoClass.fuck) # 用字典构造分支结构 print('用字典构造分支结构'.center(30,'*')) def branch_a(): print('分支a') def branch_b(): print('fuckb') def branch_c(): print('c') # 构造函数字典,跟switch...case...差不多 func_dict = { 'a': branch_a, # 不加括号 'b': branch_b(), # 一旦加括号,就会直接执行里面的print了 'c': branch_c } # 调用 func_dict['c']() # 加括号调用 # 鸭子类型 duck typing print('鸭子类型 duck typing'.center(30,'*')) class Duck: def jiaosheng(self): print('gagaga') class Cat: def jiaosheng(self): print('miaomiaomiao') class Tree(): pass # 以上是三种类,下面实例化 duck = Duck() cat = Cat() tree = Tree() # 定义一个函数,可以调用任何带有jiaosheng方法的对象 def jiaoqilai(obj): obj.jiaosheng() # 调用jiaoqilai jiaoqilai(cat) # 让猫叫起来 jiaoqilai(duck) # 让鸭子叫起来 # jiaoqilai(tree) # 让树叫起来 会出错,因为Class Tree里面没有定义jiaosheng方法
20c8b0d87a129a10d668cee8b57209fae5c79ce5
ssxday/Python35
/gothrough.py
667
3.59375
4
# -*- coding:utf-8 -*- # 遍历目录文件及子文件夹 def gothr(path = './overall'): import os l = os.listdir(path) decration = '' for ford in l: decration = '-' if os.path.isdir(path + os.sep + ford): print(decration,ford) gothr(path + '/' + ford) elif os.path.isfile(path + os.sep + ford): print(decration,ford) # return l # gothr() def goover(pth = './overall'): import os l = os.walk(pth) for root, dirname, filename in l: print('\nroot:',root) print('dir:', dirname) print('file:',filename) # print(l) # goover()
70dcf217c9557716d42a3bda038e51ab1d5e39e7
ssxday/Python35
/stack&queue.py
272
3.671875
4
lst = ['apple', 'banana', 'cherry', 'durian', 'elva', 'fig', 'grape'] # 堆栈 #进栈 lst.append('honey') print(lst) #出栈 lst.pop() print(lst) # 队列 # 入队 lst.append('housewife') print(lst) # 出队 lst.pop(0) #队列出队用pop(0) print(lst)
06c762e9658bf1b06a403ba8a53181c67272cfb6
ssxday/Python35
/xiancheng.py
3,718
3.765625
4
# -*- coding:utf-8 -*- def isPrime(n=3): if n <= 1: return False for i in range(2, n // 2 + 1): if n % i == 0: return False else: continue return True def forthrd(start=2, step=100, mark=''): fltr = filter(isPrime, range(start, start + step)) i = 0 for r in fltr: print(r, mark) i += 1 return i print(' 主程序开始了 '.center(50, '=')) print('没有使用线程的情况:') start = 10000000 step = 130 # forthrd(start, step, 'a') # print() # forthrd(start, step, 'b') import threading print('创建并使用线程:') # help(threading.Thread.daemon) # 创建线程,交替执行子线程 ta = threading.Thread(target=forthrd, args=(start, step, 'A')) tb = threading.Thread(target=forthrd, args=(start, step, 'B')) # print('线程a:',ta) # <Thread(Thread-1, initial)> # print('线程b:',tb) # <Thread(Thread-2, initial)> # Daemon 和 isDaemon() print('%s会守护主进程吗:%s' % (ta.name, ta.isDaemon())) print('%s会守护主进程吗:%s' % (tb.name, tb.isDaemon())) # ta.daemon = True # tb.daemon = True print('%s会守护主进程吗:%s' % (ta.name, ta.isDaemon())) print('%s会守护主进程吗:%s' % (tb.name, tb.isDaemon())) # 开启执行 print('使用线程后的执行情况:') # tb.start() # ta.start() # isAlive()方法 与 name属性 print('线程%s在运行吗:' % ta.name, ta.is_alive()) # 同isAlive() print('线程%s在运行吗:' % tb.name, tb.isAlive()) # 在主线程调用子线程的join()方法,主程序会等ta,tb完成后才继续!!! # 实现效果:大部队原地待命等着ta,tb if ta.is_alive(): ta.join() # 主线程会等ta完成再继续 if tb.is_alive(): tb.join() # 主线程会等tb完成再继续 # 线程同步 print('\n线程同步问题(开启flag为True时会锁定GG标记)') # 锁住变量threading.Lock & threading.RLock # 用第二种办法:继承Thread类来创建线程 print('通过继承Thread类创建线程:') # 定义一个全局变量 GG = 'imGlobal' # 继承threading.Thread类 class Mythread(threading.Thread): def __init__(self, mark='', dolock=False): super(Mythread, self).__init__() # 必须首先调用父类构造方法 self._mark = mark self.dolock = dolock # 重载run()方法 def run(self): if self.dolock: self._dolock() # 封装了同步锁 fltr = filter(self._isPrime, range(10000000, 10000000 + 130)) for r in fltr: print(r, self._mark, GG) def _isPrime(self, n=3): if n <= 1: return False for i in range(2, n // 2 + 1): if n % i == 0: return False else: continue return True def _dolock(self): # 创建锁对象 rlock = threading.RLock() print('创建锁对象:', rlock) # 哪个线程调用了rlock的acquire()方法,中间操作的数据就会被它锁住 rlock.acquire() global GG GG = '我被%s锁住了' % self.name # 把全局变量锁住了 rlock.release() # 实例化自定义线程类 mya = Mythread('classA') myb = Mythread('classB', True) # print('自定义线程mya:',mya) # print('自定义线程myb:',myb) # 执行操作: # myb.start() # mya.start() # mya在这里就开始了!! try: mya.join() # 主程序等着mya myb.join() except RuntimeError: pass # Event对象(类) print('线程间的通信:Event对象') # 实例化Event对象 evt = threading.Event() help(threading.Event.is_set) print('内部flag标记:',evt.is_set()) # end print(' 主线程在此结束 '.center(50, '='))
0f3aee647a23837b86c52f2f185f2b06d35fb6de
ssxday/Python35
/group-rename.py
512
3.953125
4
# 批量修改文件后缀程序 def mrename(src = 'haha',dst = 'txt',srcdir = '.'): src = '.' + src dst = '.' + dst warning = input('警告!你确定要把后缀为'''+ src +'的文件修改为' + dst + '的后缀吗?(Y/N):') if warning not in ['y','Y']: exit('还好你放弃了') import os files = os.listdir(srcdir) for filename in files: if filename.endswith(src): newname = filename.replace(src,dst) os.rename(filename,newname)
aa401bd02b779ddfbe5302e616e12a9f3876aba2
ssxday/Python35
/input.py
166
3.875
4
x = input('x=') #input的都是字符串,要输入数字需要再后面转换类型 x = int(x) x = x+1 print('x=',x) y = int(input('y=')) if x<y: print(x+y)
fda4e26f03bd1c99534e50d042a0102d3a80f01a
ssxday/Python35
/whatday.py
525
3.90625
4
# 写一个根据日期计算星期几的模块 def whatday(s = '19860831'): #s是传进来的日期字符串 s = str(s) # 强制转换类型,传进来的是数字还是字符串都无所谓了 import time,datetime time_s = list(time.strptime(s,'%Y%m%d')) # print(time_s) days = { 0:'星期一', 1:'星期二', 2:'星期三', 3:'星期四', 4:'星期五', 5:'星期六', 6:'星期天' } return days[time_s[6]] # 索引6代表星期
81ca064bad2a277ab5adf7e01c1dc6b11ff78910
cpe202fall2018/lab0-AlekTheGreat
/planets.py
437
3.734375
4
#Alek Ramirez #013927364 #9-24-18 # #Lab 0 #Section 13 #Purpose: Solving for the weight on different planets #Comments: def weight_on_planets(): weight = float(input('What do you weigh on earth? ')) WoM = weight * 0.38 WoJ = weight * 2.34 print('\nOn Mars you would weigh {:0.2f} pounds.\n' 'On Jupiter you would weigh {:0.2f} pounds.'.format(WoM, WoJ)) if __name__ == '__main__': weight_on_planets()
f56b7728d9dd9677b8bb498a9c679e1961da4bdc
Adomkay/sql-intro-to-join-statements-lab-nyc-career-ds-062518
/sql_queries.py
933
3.515625
4
# Write your SQL queries inside the strings below. If you choose to write your queries on multiple lines, make sure to wrap your query inside """triple quotes""". Use "single quotes" if your query fits on one line. def select_hero_names_and_squad_names_of_heroes_belonging_to_a_team(): return "SELECT superheroes.name, squads.name FROM superheroes JOIN squads ON superheroes.squad_id = squads.id;" def reformatted_query(): return "SELECT superheroes.name, squads.name AS team FROM superheroes JOIN squads ON superheroes.squad_id = squads.id ORDER BY team" def all_superheroes(): return "SELECT superheroes.name, superheroes.superpower, squads.name AS team FROM superheroes LEFT JOIN squads ON superheroes.squad_id = squads.id ORDER BY team;" def all_squads(): return "SELECT squads.name AS team, COUNT(superheroes.id) FROM squads LEFT JOIN superheroes ON superheroes.squad_id = squads.id GROUP BY squads.name;"
0082bcd072d04e3ee7ea6f0301ae72d4a05dd97e
chriszhang3/checkers
/main.py
1,593
3.9375
4
from tkinter import Tk, Label from Board import Board from UI import UI from Computer import Computer def main(): option = input("Press h to play against a human player. \nPress c to play against a computer player. \n") while option != "c" and option != "h": option = input("Invalid input. Try again: ") root = Tk() board_size = UI.window_size cell_size = int(board_size/8) window_size = board_size+cell_size letters = ["A","B","C","D","E","F","G","H"] root.geometry(str(window_size)+'x'+str(window_size)) board = Board() computer = Computer(board,1) ui = UI.make_ui(board) canvas =ui.get_canvas() canvas.pack() canvas.place(x=0,y=0) if option == "h": canvas.bind('<Button-1>', lambda event, b=board, u = ui: UI.onclick_human(event,b,u)) # After the human turn, you need to click for the computer's turn to start. elif option == "c": computer = Computer(board,1) canvas.bind('<Button-1>', lambda event, b=board, c= computer, u = ui: UI.onclick_computer(event,b,c,u)) for i in range(8): label = Label(root, text=letters[i], font = "Helvetica %d"%int(cell_size/2)) label.pack() label.place(x = cell_size*i+22, y = board_size+15) for number in range(8): label = Label(root, text=str(number+1), font = "Helvetica %d"%int(cell_size/2)) label.pack() label.place(x = board_size+27, y = 14+number*cell_size) root.mainloop() if __name__ == "__main__": main()
26a77eaf507d1b0107e311ee09706bc352e70ced
ScottG489/Task-Organizer
/src/task/task.py
2,528
4.125
4
"""Create task objects Public classes: Task TaskCreator Provides ways to instantiate a Task instance. """ from textwrap import dedent # TODO: Should this be private if TaskCreator is to be the only # correct way to make a Task instance? class Task(): """Instantiate a Task object. Provides attributes for tasks and methods to compare Task instances. """ def __init__(self, **kwargs): try: self.key = kwargs['key'] except KeyError: self.key = None try: self.title = kwargs['title'] except KeyError: self.title = None try: self.notes = kwargs['notes'] except KeyError: self.notes = None # self.priority = priority # self.tags = tags def __str__(self): return dedent('''\ ID: %(key)s Title: %(title)s Notes: %(notes)s''') % { 'key': self.key, 'title': self.title, 'notes': self.notes } def __eq__(self, other): if not isinstance(other, Task): return False if self.key == other.key\ and self.title == other.title\ and self.notes == other.notes: return True return False def __ne__(self, other): if not isinstance(other, Task): return True if self.key != other.key\ or self.title != other.title\ or self.notes != other.notes: return True return False class TaskCreator(): """Create a Task instance automatically. Public methods: build(arg_dict) Create a Task instance in a automatic and safer manner.""" def __init__(self): pass @staticmethod def build(arg_dict): """Creates a Task instance given a dictionary. Args: arg_dict (dict): dictionary formatted to create a Task The given dictionary must have a correct naming scheme. However, it can be missing any field. """ task_item = Task() try: task_item.key = arg_dict['key'] except KeyError: task_item.key = None try: task_item.title = arg_dict['title'] except KeyError: task_item.title = None try: task_item.notes = arg_dict['notes'] except KeyError: task_item.notes = None return task_item
6f3619f2726fba6e2f6a01eff7d633e7b0acdaea
ohmaj/rockspock
/game.py
1,443
3.765625
4
import random class game: def __init__(self,name,player1,player2): self.name=name self.player1=player1 self.player2=player2 def getHumanChoice(self): playerChoice= input('enter # for choice 1:rock 2:paper 3:scissors 4:Spock 5:lizard: ') if int(playerChoice) in range(1,6): return (playerChoice) else: print('not a valid selection please choose again') return(self.getHumanChoice()) def getComputerChoice(self): playerChoice=str(random.randint(1,5)) return (playerChoice) def calcResult(self,player1Choice,player2Choice): print(self.player1.name+' chose: '+str(self.player1.choice)) print(self.player2.name+' chose: '+str(self.player2.choice)) if player1Choice == player2Choice: return('Draw! ') elif ((player1Choice - player2Choice)%5) in [1,3]: return('Player 1 Wins! ') else: return('Player 2 Wins! ') def getrResult(self): players=(self.player1,self.player2) for player in players: if player.isHuman == True: player.choice=self.getHumanChoice() elif player.isHuman == False: player.choice=self.getComputerChoice() print(self.calcResult((int(self.player1.choice)),(int(self.player2.choice))))
4c34d295e42684443f40bef31e8a1a8d646761c3
robJolley/PythonVision
/BilateralFilter_Sobel_Canny.py
4,620
3.59375
4
""" ======================================================= Simple image blur by convolution with a Gaussian kernel ======================================================= Blur an an image (:download:`../../../../data/elephant.png`) using a Gaussian kernel. Convolution is easy to perform with FFT: convolving two signals boils down to multiplying their FFTs (and performing an inverse FFT). """ import numpy as np import statistics import math import cv2 from scipy import fftpack from numpy import zeros import matplotlib.pyplot as plt ##################################################################### # The original image ##################################################################### # read image img = plt.imread('resize.bmp') #img =cv2.resize(img,(200,200)) #bilateral_filtered_image = cv2.bilateralFilter(img, 5, 175, 175) img = img/255 thold = 15 plt.figure() plt.title('Raw') plt.imshow(img) #bilateral_filtered_image = bilateral_filtered_image/255 #plt.figure() #plt.title('Bilateral CV2') #plt.imshow(bilateral_filtered_image) width, height, channels = img.shape imga = zeros([width,height,3]) imgDir = zeros([width,height]) imgSobl = imga t = imga[1,1] sobelX =[[-1.0,0.0,1.0],[-2.0,0.0,2.0],[-1.0,0.0,1.0]] sobelY =[-1.0,-2.0,-1.0],[0.0,0.0,0.0],[1.0,2.0,1.0] imgSob = 0.0 tS =0.0 tSx = tS tSy = tS tr = t mat = 5 mp =1+(int)(mat/2) ta = zeros([mat,mat,3]) #plt.figure() #plt.imshow(imga) ##################################################################### # Prepare an Gaussian convolution kernel ##################################################################### # First a 1-D Gaussian t = np.linspace(-mat, mat, mat) # esecentialy for loop starting at -10 ending at 10 with 30 steps bump = np.exp(-0.1*t**2) # Used to generate line that erodes in an expodential patern -10 to + 10 building a bell curve bump /= np.trapz(bump) # normalize the integral to 1 #print ('bump',bump) # make a 2-D kernel out of it kernel = bump[:, np.newaxis] * bump[np.newaxis, :] #print ('kernel',kernel) for xk in range (0,(mat-1), 1): # nested loop to parce through raw image for yk in range (0,(mat-1), 1): ta[xk,yk,0] = kernel[xk,yk] ta[xk,yk,1] = kernel[xk,yk] ta[xk,yk,2] = kernel[xk,yk] for h in range (0,(height-1), 1): # nested loop to parce through raw image for w in range (0,(width-1), 1): img[h,w] = (img[h,w,0] + img[h,w,1] + img[h,w,2])/3 # print(img[h,w]) if img[h,w,0] < 0.02: img[h,w] = [0,0,0] for h in range (mp,(height-mp), 1): # nested loop to parce through raw image for w in range (mp,(width-mp), 1): tr = img[h,w] # trAvg = (tr[0]+tr[1]+tr[2])/3 if tr[0] > 0.0: for xk in range (0,(mat-1), 1): # nested loop to parce through raw image for yk in range (0,(mat-1), 1): intPixel = ((img[(h+(xk-mp)),(w+(yk-mp)),0])+(img[(h+(xk-mp)),(w+(yk-mp)),1])+(img[(h+(xk-mp)),(w+(yk-mp)),2]))/3 # if (intPixel -(thold/255)) <= trAvg <= (intPixel + (thold/255)): t[0] += img[(h+(xk-mp)),(w+(yk-mp)),0]*ta[xk,yk,0] t[1] += img[(h+(xk-mp)),(w+(yk-mp)),1]*ta[xk,yk,1] t[2] += img[(h+(xk-mp)),(w+(yk-mp)),2]*ta[xk,yk,2] # else: # t[0] += tr[0]*ta[xk,yk,0] # t[1] += tr[1]*ta[xk,yk,1] # t[2] += tr[2]*ta[xk,yk,2] else: t[0] = 0 t[1] = 0 t[2] = 0 # print(intPixel) imga[h,w,0] = t[0] imga[h,w,1] = t[1] imga[h,w,2] = t[2] t[0] = 0 t[1] = 0 t[2] = 0 plt.figure() plt.imshow(imga) plt.title('Bilateral filter') imga1 = np.uint8(imga*255) cv2.imshow('Filtered Image ', imga1) #cv2.waitKey(0) for h in range (1,(height-2), 1): # nested loop to parce through raw image for w in range (1,(width-2), 1): if imga[h,w,0] > 0.0: # tS = imga1[h,w,0] for xk in range (0,3,1): # nested loop to parce through raw image for yk in range (0,3,1): tSx+=((sobelX[xk][yk])*imga1[((h-1)+xk),((w-1)+yk),0]) tSy+=((sobelY[xk][yk])*imga1[((h-1)+xk),((w-1)+yk),0]) tS =math.sqrt(tSx*tSx + tSy*tSy) # print('tS :',tS) if tS >76: imgSobl[h,w] =[tS,tS,tS] if tSx > 0.0: dirE = (tSy/tSx) imgDir[h,w] = dirE else: imgSobl[h,w] = [0,0,0] tS = 0.0 tSx = 0.0 tSy = 0.0 #bilateral_filtered_image8 = np.uint8(bilateral_filtered_image*255) #edge_detected_image1 = cv2.Canny((bilateral_filtered_image8), 75, 200) #edge_detected_image1 = edge_detected_image1/255 #imgFP = img #imgSobl = imgSobl/(imgSobl.max()/255.0) cv2.imshow('Edge Sobel',imgSobl/255) #cv2.waitKey(0) #imgSobl = imgSobl/255 plt.figure() plt.imshow(imgSobl/255) plt.title('Sobel Filter') plt.figure() plt.imshow(imgDir/255) plt.title('direction') plt.show()
4f2f17050ed4c4c8db4d722fe642284d1359127b
GH-Zhou/interview-prep
/Session 2/02-Sort-Sorted-Lists.py
5,707
4.3125
4
import unittest import heapq # ---- Definition of ListNode Class # A ListNode is a node in the linked list with its value and next property pointing to the next node class ListNode: def __init__(self, val): self.val = val self.next = None # Comparator for heapq def __lt__(self, other): return self.val < other.val # ---- Test Cases # 1) Input: None, None Output: None # 2) Input: 1 -> 2, None Output: 1 -> 2 # 3) Input: None, 2 -> 3 Output: 2 -> 3 # 4) Input: 1, 2 Output: 1 -> 2 # 5) Input: 1 -> 3, 2 -> 4 Output: 1 -> 2 -> 3 -> 4 # 6) Input: 3 -> 4, 1 -> 2 Output: 1 -> 2 -> 3 -> 4 # 7) Input: 1 -> 5, 2 -> 3 -> 4 Output: 1 -> 2 -> 3 -> 4 -> 5 # 8) Input: 2 -> 3 -> 5, 1 -> 4 -> 6 Output: 1 -> 2 -> 3 -> 4 -> 5 -> 6 # ---- Approach # Idea: Use two pointers to iterate two lists, add the smaller one to the merged list # # Implementation: def sort_two_sorted_lists(l1, l2): if l1 is None: return l2 if l2 is None: return l1 dummy = ListNode(0) cur = dummy while l1 and l2: if l1.val < l2.val: cur.next = l1 l1 = l1.next else: cur.next = l2 l2 = l2.next cur = cur.next if l1 is None: cur.next = l2 else: cur.next = l1 return dummy.next # - Complexity # Time: O(m + n), spent on iterating two lists # Space: O(1), only the references of nodes changed # ==================================== # ---- FOLLOW UP - Sort K Sorted Lists # ---- Test Case # Input: 1 -> 4 -> 7, 2 -> 5 -> 8, 3 -> 6 -> 9 Output: 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> 9 # ---- Approach # Idea: Use a heap to keep track of the currently smallest number among the headers of each list # # Implementation: def sort_k_sorted_lists(lists): if lists is None or len(lists) == 0: return None h = [] for l in lists: if l: heapq.heappush(h, l) dummy = ListNode(0) cur = dummy while len(h) > 0: lst = heapq.heappop(h) print(lst.val) cur.next = lst lst = lst.next if lst: heapq.heappush(h, lst) cur = cur.next return dummy.next # - Complexity # Time: O(nk(log k)), where n is the average length of k lists # Space: O(k), spent on the heap for k headers of the lists class TestSortSortedLists(unittest.TestCase): l11 = None; l12 = None; l1 = None l21 = ListNode(1); l21.next = ListNode(2); l22 = None l2 = ListNode(1); l2.next = ListNode(2) l31 = None; l32 = ListNode(2); l32.next = ListNode(3) l3 = ListNode(2); l3.next = ListNode(3) l41 = ListNode(1); l42 = ListNode(2) l4 = ListNode(1); l4.next = ListNode(2) l51 = ListNode(1); l51.next = ListNode(3); l52 = ListNode(2); l52.next = ListNode(4) l5 = ListNode(1); l5.next = ListNode(2); l5.next.next = ListNode(3); l5.next.next.next = ListNode(4) l61 = ListNode(3); l61.next = ListNode(4); l62 = ListNode(1); l62.next = ListNode(2) l6 = ListNode(1); l6.next = ListNode(2); l6.next.next = ListNode(3); l6.next.next.next = ListNode(4) l71 = ListNode(1); l71.next = ListNode(5); l72 = ListNode(2); l72.next = ListNode(3); l72.next.next = ListNode(4) l7 = ListNode(1); l7.next = ListNode(2); l7.next.next = ListNode(3); l7.next.next.next = ListNode(4) l7.next.next.next.next = ListNode(5) l81 = ListNode(2); l81.next = ListNode(3); l81.next.next = ListNode(5) l82 = ListNode(1); l82.next = ListNode(4); l82.next.next = ListNode(6) l8 = ListNode(1); l8.next = ListNode(2); l8.next.next = ListNode(3); l8.next.next.next = ListNode(4) l8.next.next.next.next = ListNode(5); l8.next.next.next.next.next = ListNode(6) def test_sort_two_sorted_lists(self): self.assertTrue(self.check_list_equal(sort_two_sorted_lists(self.l11, self.l12), self.l1)) self.assertTrue(self.check_list_equal(sort_two_sorted_lists(self.l21, self.l22), self.l2)) self.assertTrue(self.check_list_equal(sort_two_sorted_lists(self.l31, self.l32), self.l3)) self.assertTrue(self.check_list_equal(sort_two_sorted_lists(self.l41, self.l42), self.l4)) self.assertTrue(self.check_list_equal(sort_two_sorted_lists(self.l51, self.l52), self.l5)) self.assertTrue(self.check_list_equal(sort_two_sorted_lists(self.l61, self.l62), self.l6)) self.assertTrue(self.check_list_equal(sort_two_sorted_lists(self.l71, self.l72), self.l7)) self.assertTrue(self.check_list_equal(sort_two_sorted_lists(self.l81, self.l82), self.l8)) list1 = ListNode(1); list1.next = ListNode(4); list1.next.next = ListNode(7) list2 = ListNode(2); list2.next = ListNode(5); list2.next.next = ListNode(8) list3 = ListNode(3); list3.next = ListNode(6); list3.next.next = ListNode(9) list = ListNode(1); list.next = ListNode(2); list.next.next = ListNode(3) list.next.next.next = ListNode(4); list.next.next.next.next = ListNode(5) list.next.next.next.next.next = ListNode(6) list.next.next.next.next.next.next = ListNode(7) list.next.next.next.next.next.next.next = ListNode(8) list.next.next.next.next.next.next.next.next = ListNode(9) def test_sort_k_sorted_lists(self): self.assertTrue(self.check_list_equal(sort_k_sorted_lists([self.list1, self.list2, self.list3]), self.list)) def check_list_equal(self, l1, l2): p1, p2 = l1, l2 while p1 and p2: if p1.val != p2.val: return False p1 = p1.next; p2 = p2.next return p1 is None and p2 is None if __name__ == '__main__': unittest.main()
86af8c55ca5cbfa8dedebd3dede4b048c74fa8a9
GH-Zhou/interview-prep
/Session 3/05-Decode-Ways.py
2,858
3.796875
4
import unittest # ---- Test Cases # 1) Input: "" Output: 0 # 2) Input: "0" Output: 0 # 3) Input: "1" Output: 1 # 4) Input: "10" Output: 1 # 5) Input: "12" Output: 2 # 6) Input: "226" Output: 3 # ---- Approach 1 # Idea: Use dynamic programming to count the ways of decode # # Implementation: def decode_ways(str): if str is None or len(str) == 0 or str[0] == "0": return 0 dp = [0] * len(str) dp[0] = 1 for i in range(1, len(str)): if str[i] == "0": if str[i - 1] == "1" or str[i - 1] == "2": dp[i] = dp[i - 2] if i > 1 else 1 else: dp[i] = 0 else: if "10" <= str[(i - 1):(i + 1)] <= "26": dp[i] = dp[i - 1] + dp[i - 2] if i > 1 else 2 else: dp[i] = dp[i - 1] return dp[len(str) - 1] # - Complexity # Time: O(n), spent on iterating the array # Space: O(n), spent on dp caching array # ---- Approach 2 (Optimization on Space) # Idea: Use a rolling array to minimize the use of caching memory # # Implementation: def decode_ways_with_constant_space(str): n = len(str) if str is None or n == 0 or str[0] == "0": return 0 dp = [1, 0] for i in range(1, n): if str[i] == "0": if str[i - 1] == "1" or str[i - 1] == "2": dp[i % 2] = dp[(i - 2) % 2] if i > 1 else 1 else: dp[i % 2] = 0 else: if "10" <= str[(i - 1):(i + 1)] <= "26": dp[i % 2] = dp[(i - 1) % 2] + dp[(i - 2) % 2] if i > 1 else 2 else: dp[i % 2] = dp[(i - 1) % 2] return dp[(n - 1) % 2] # - Complexity # Time: O(n), spent on iterating the array # Space: O(1) class TestDecodeWays(unittest.TestCase): str1 = "" str2 = "0" str3 = "1" str4 = "10" str5 = "12" str6 = "226" def test_decode_ways(self): self.assertEqual(decode_ways(self.str1), 0) self.assertEqual(decode_ways(self.str2), 0) self.assertEqual(decode_ways(self.str3), 1) self.assertEqual(decode_ways(self.str4), 1) self.assertEqual(decode_ways(self.str5), 2) self.assertEqual(decode_ways(self.str6), 3) def test_decode_ways_with_constant_space(self): self.assertEqual(decode_ways_with_constant_space(self.str1), 0) self.assertEqual(decode_ways_with_constant_space(self.str2), 0) self.assertEqual(decode_ways_with_constant_space(self.str3), 1) self.assertEqual(decode_ways_with_constant_space(self.str4), 1) self.assertEqual(decode_ways_with_constant_space(self.str5), 2) self.assertEqual(decode_ways_with_constant_space(self.str6), 3)
96b15dbc03157c924f356d11062a67800fd3d175
simenheg/euler
/057/problem57.py
998
3.90625
4
# It is possible to show that the square root of two can be expressed as an # infinite continued fraction. # √ 2 = 1 + 1/(2 + 1/(2 + 1/(2 + ... ))) = 1.414213... # By expanding this for the first four iterations, we get: # 1 + 1/2 = 3/2 = 1.5 # 1 + 1/(2 + 1/2) = 7/5 = 1.4 # 1 + 1/(2 + 1/(2 + 1/2)) = 17/12 = 1.41666... # 1 + 1/(2 + 1/(2 + 1/(2 + 1/2))) = 41/29 = 1.41379... # The next three expansions are 99/70, 239/169, and 577/408, but the eighth # expansion, 1393/985, is the first example where the number of digits in # the numerator exceeds the number of digits in the denominator. # In the first one-thousand expansions, how many fractions contain a # numerator with more digits than denominator? def num_dig(n): dig = 0; while n > 0: dig += 1; n /= 10; return dig; num = 3; den = 2; sum = 0; for i in range (0, 1000): old_den = den; den += num; num = old_den + den; if num_dig(num) > num_dig(den): sum += 1 print sum # => 153
a43cfd28ceeff948ab356981f708cac198643ed8
wzy414033395/DiscreteMathProgrammingProjects-1
/ProgrammingProject2/quicksort.py
853
3.84375
4
#Discrete Mathematics #CSIS Programming Project 2 #Gordon Portzline #Zhengyu Wu #Brad Rohbock #QuickSort pulled from online repository # """https://gist.github.com/anirudhjayaraman/897ca0d97a249180a48b50d62c87f239""" def quicksort(lista,start,end): i = start j = end pivote = lista[(start + end)//2] swap_count = 0 while i <= j: while lista[i] < pivote: i += 1 while pivote < lista[j]: j -= 1 if i <= j: aux = lista[i] lista[i] = lista[j] lista[j] = aux swap_count += 1 i += 1 j -= 1 if start < j: swap_count += quicksort(lista, start, j) if i < end: swap_count += quicksort(lista, i, end) return swap_count alist = [54,26,93,17,77,31,44,55,20] print(alist) count = quicksort(alist, 0, len(alist)-1) print("Swaps: ", count) print(alist)
2904498a6402126bae0c6577b098541a00e395ec
IvanIlin22/myWork
/level00/ft_print_numbers/ft_print_numbers.py
71
3.609375
4
i = '0' while i <= '9': print(i, end = "") i = ord(i) + 1 i = chr(i)
4b95b8dbae3dc31930e33139ae9f3677469cb71c
thejacobhardman/Powerball
/Powerball.py
10,096
3.984375
4
# Jacob Hardman # Intro To Programming # Professor Marcus Longwell # 3/6/19 # Python Version 3.7.2 # Importing pkgs import os import random import decimal # Clears the screen def cls(): os.system('cls' if os.name=='nt' else 'clear') ########################################################## GLOBAL VARIABLES ############################################################## # Tracks if the program is still running Is_Running = True # Tracks the user's input User_Input = "" # Tracks if the user has made a decision User_Confirm = False # Checks if the user has guessed a valid number Valid_Guess = False # Stores the user's ticket guess User_Ticket = [] # Stores the user's guess for the powerball User_Powerball = 0 # Stores a random number Random_Number = 0 # Stores the winning ticket numbers Winning_Ticket = [] # Stores the winning powerball value Winning_Powerball = 1 # Stores the number of correct numbers Correct_Numbers = 0 # Tracks if the user guessed the powerball correctly Correct_PowerBall = False # Displays the user's winnings as text Winnings = ["$0.00", "$1.00", "$2.00", "$10.00", "$20.00", "$100.00", "$1,000.00"] # Tracks the Player's balance Player_Balance = decimal.Decimal('5.00') ########################################################### PROGRAM LOGIC ################################################################ ### Generates the winning ticket and PowerBall def Draw_Ticket(): # Importing global variables global Valid_Guess global Random_Number global Winning_Ticket global Winning_Powerball global Player_Balance # Subtracts $1 from the player's balance once they start the game Player_Balance = Player_Balance - decimal.Decimal('1.00') i = 0 while i < 3: Random_Number = random.randint(1,9) if Random_Number not in Winning_Ticket: Winning_Ticket.append(Random_Number) i += 1 else: continue while Valid_Guess == False: Random_Number = random.randint(1,9) if Random_Number not in Winning_Ticket: Winning_Powerball = Random_Number break else: continue ### The player wants to guess their numbers manually def Manual_Guess(): # Importing global variables global User_Input global User_Ticket global User_Powerball # Clearing the screen to improve readability cls() print("You have chosen to guess your numbers manually.") print("Your guess must be between 1-9 and you cannot guess any number more than once with the exception of the powerball.\n") # Validating the user's first guess while Valid_Guess == False: User_Input = input("Please enter your first guess: ") if int(User_Input) >= 1 and int(User_Input) <= 9: User_Ticket.append(int(User_Input)) break else: print("Please enter a valid guess.\n") # Validating the user's second guess while Valid_Guess == False: User_Input = input("Please enter your second guess: ") if User_Input not in User_Ticket and int(User_Input) >= 1 and int(User_Input) <= 9: User_Ticket.append(int(User_Input)) break else: print("Please enter a valid guess.\n") # Validating the user's third guess while Valid_Guess == False: User_Input = input("Please enter your third guess: ") if User_Input not in User_Ticket and int(User_Input) >= 1 and int(User_Input) <= 9: User_Ticket.append(int(User_Input)) break else: print("Please enter a valid guess.\n") # Validating the user's guess for the powerball while Valid_Guess == False: User_Input = input("Please enter your guess for the PowerBall: ") if int(User_Input) >= 1 and int(User_Input) <= 9: User_Powerball = int(User_Input) break else: print("Your PowerBall guess must be between 1 and 9.") ### The player wants to guess their numbers randomly def Random_Guess(): # Importing global variables global User_Input global User_Ticket global User_Powerball # Clearing the screen to improve readability cls() i = 0 while i < 3: Random_Number = random.randint(1,9) if Random_Number not in User_Ticket: User_Ticket.append(Random_Number) i += 1 else: continue while Valid_Guess == False: Random_Number = random.randint(1,9) if Random_Number not in User_Ticket: User_Powerball = Random_Number break else: continue ### Checks the player's guess (either manual or random) against the winning ticket def Display_Result(): # Importing global variables global User_Ticket global User_Powerball global Winning_Ticket global Winning_Powerball print("\nYour Ticket: ", end="") for Number in User_Ticket: print(Number, end=" ") print("| " + str(User_Powerball)) print("The Drawing: ", end="") for Number in Winning_Ticket: print(Number, end=" ") print("| " + str(Winning_Powerball)) input("Press 'enter' to continue.") ### Calculates how much the user won based on the number of correct numbers def Calculate_Winnings(): # Importing global variables global User_Ticket global User_Powerball global Winning_Ticket global User_Powerball global Correct_Numbers global Correct_PowerBall global Winnings global Player_Balance for Number in User_Ticket: if Number in Winning_Ticket: Correct_Numbers += 1 else: continue if User_Powerball == Winning_Powerball: Correct_PowerBall = True else: Correct_PowerBall = False if Correct_Numbers == 1 and Correct_PowerBall == False: print("\nCongratulations!") print("You matched 1 number but not the PowerBall.") print("You won: " + Winnings[1]) Player_Balance = Player_Balance + decimal.Decimal('1.00') elif Correct_Numbers == 1 and Correct_PowerBall == True: print("\nCongratulations!") print("You matched 1 number and the PowerBall.") print("You won: " + Winnings[2]) Player_Balance = Player_Balance + decimal.Decimal('2.00') elif Correct_Numbers == 2 and Correct_PowerBall == False: print("\nCongratulations!") print("You matched 2 numbers but not the PowerBall.") print("You won: " + Winnings[3]) Player_Balance = Player_Balance + decimal.Decimal('10.00') elif Correct_Numbers == 2 and Correct_PowerBall == True: print("\nCongratulations!") print("You matched 2 number and the PowerBall.") print("You won: " + Winnings[4]) Player_Balance = Player_Balance + decimal.Decimal('20.00') elif Correct_Numbers == 3 and Correct_PowerBall == False: print("\nCongratulations!") print("You matched 3 number but not the PowerBall.") print("You won: " + Winnings[5]) Player_Balance = Player_Balance + decimal.Decimal('100.00') elif Correct_Numbers == 3 and Correct_PowerBall == True: print("\nCongratulations!") print("You matched 3 numbers and the PowerBall.") print("You won: " + Winnings[6]) Player_Balance = Player_Balance + decimal.Decimal('1000.00') else: print("\nBetter luck next time!") print("You didn't match any ticket numbers.") print("You won: " + Winnings[0]) ### Asking the player if they want to play again and reseting the game def Reset_Game(): # Importing global variables global Is_Running global User_Confirm global User_Ticket global User_Powerball global Winning_Ticket global Winning_Powerball global Correct_Numbers global Correct_PowerBall User_Ticket = [] User_Powerball = 0 Winning_Ticket = [] Winning_Powerball = 1 Correct_Numbers = 0 Correct_PowerBall = False while User_Confirm == False: User_Input = input("\nWould you like to play again? (y/n): ") if User_Input.upper() == "Y": break elif User_Input.upper() == "N": Is_Running = False break else: print("\nPlease enter a valid selection.") input("Press 'enter' to continue.") ########################################################### PROGRAM FLOW ################################################################# while Is_Running == True: # Clearing the screen for replayability cls() print("Welcome to PowerBall!!!".center(100, " ")) print("Your balance is: $", end="") print(Player_Balance) print("It costs $1 to play the game.") print("\nPlease enter '1' to select your numbers manually.") print("Please enter '2' to guess random numbers.") User_Input = input("\nPlease make a selection: ") if Player_Balance > 1.00: if User_Input == "1": Draw_Ticket() # Generates the winning ticket and PowerBall Manual_Guess() # The player makes their guesses Display_Result() # Checks the player's guess against the winning ticket Calculate_Winnings() # Calculates the amount that the player won Reset_Game() # Resets the game for another playthrough elif User_Input == "2": Draw_Ticket() # Generates the winning ticket and PowerBall Random_Guess() # The computer generates the player's random guess Display_Result() # Checks the player's guess against the winning ticket Calculate_Winnings() # Calculates the amount that the player won Reset_Game() # Resets the game for another playthrough else: print("\nPlease enter a valid selection.") input("\nPress 'enter' to continue.") else: cls() print("You do not have enough money to play the game.") input("Press 'enter' to close the game.") Is_Running = False break
db11b8cd747205d5bcb9dd5b96f50fd826ad4392
ZedRover/stats-algo
/老婆的代码/Sep 9_week1.py
3,070
4.65625
5
""" 统计软件与算法 2020年9月9日 """ """ PYTHON INTRODUCTION """ # Addition, subtraction print(5 + 5) print(5 - 5) # Multiplication, division, modulo, and exponentiation print(3 * 5) print(10 / 2) print(18 % 7) print(4 ** 2) # How much is your $100 worth after 7 years with 10% return each year? print(100*1.1**7) """ Variables and Data Types """ #int,float,str,bool height = 1.78 weight = 65 bmi = weight /height**2 print(bmi) type(height) x = 'height ' y = 'weight' type(x) z = True type(z) #string add/multiplication x+y x*2 #covert type using int(), float(),str(),bool() # Definition of pi_string pi_string = "3.1415926" # Convert pi_string into float: pi_float pi_float = float(pi_string) # Definition of savings and result savings = 100 result = 100 * 1.10 ** 7 # Fix the printout str(savings) str(result) print("I started with $" + str(savings) + " and now have $" + str(result) + ".") "halo行" """ LIST """ h1 = [1.70,1.65,1.82,1.80,1.60] h2 = ['a',1.70,'b',1.65,'c',1.82,'d',1.80,'e',1.60] #list of list h3 = [['a',170],['b',1.65],['c',1.82],['d',1.80],['e',1.60]] #subsetting list h2[0] h2[9] h2[-1] h2[2:4] h2[2:] h2[:2] h3[-1][1] #list manupulation #chaning list elements h2[1] = 1.72 print(h2) h2[0:2] = ['g',1.75] print(h2) #adding and removing elements h2_new = h2+['f',1.62] print(h2_new) #append extend del function h2_new.append() h2_new.extend(['h',1.88]) print(h2_new) del(h2[2:4]) print(h2) #copy of list h1_copy = list(h1) h1_copy = h1[:] """ DICTIONARY """ pop = [30.55,2.77,39.21] countries = ['a','b','c'] world = {'a':30.55,'b':2.77,'c':39.21} world['a'] world['d'] = 2.78 'd' in world del(world['d']) print(world) """ FUNCTION and PACKAGES """ #build-in function max(h1) min(h1) round(h1[1]) round(h1[1],1) sorted(h1,reverse = True) #list method h1.index(1.82) #call method index on h1 h1.count(1.82) print(h1.index(1.82)/len(h1)) #string method sister = 'liz' sister.capitalize() sister.upper() sister.replace('z','sa') """ NUMPY """ import numpy as np height = [1.73,1.68,1.71,1.89,1.79] weight = [65.4,59.2,63.6,88.4,68.7] weight/height**2 #get error np_height = np.array(height) np_weight = np.array(weight) np_height np_weight bmi = np_weight/np_height**2 bmi #remark: numpy array only contains one type np_height+np_weight #different type differnt behavior #numpy array subsetting bmi[1] bmi>23 bmi[bmi>23] #2D numpy array np_2d = np.array([[1.73,1.68,1.71,1.89,1.79], [65.4,59.2,63.6,88.4,68.7]]) np_2d np_2d.shape #2d numpy array subsetting np_2d[0] np_2d[0][2] np_2d[0,2] np_2d[:,1:3] np_2d[1,:] #numpy basic statistics np.mean(np_2d[0]) np.median(np_2d[1]) np.corrcoef(np_2d[0,:],np_2d[1,:]) np.std(np_2d[0,:]) #generate data help(np.random.normal) h_r = np.random.normal(1.75,0.2,5000) w_r = np.random.normal(60,15,5000)
04f03ef2d9a649d4b9f65ef6783e169a14ee05e1
ZedRover/stats-algo
/老婆的代码/统计软件_Sep 16_week2.py
4,155
3.984375
4
""" 统计软件与算法 2020年9月16日 """ """ Remark(array subsetting) """ import numpy as np #2D numpy array np_2d = np.array([[1.73,1.68,1.71,1.89,1.79], [65.4,59.2,63.6,88.4,68.7]]) #2d numpy array subsetting np_2d[0] #first row np_2d[0,:] #first row np_2d[0:1,1:3] np_2d[0][2] np_2d[0,2] np_2d[[0,1,1], [0,3,1]] #创建数组 x = np.empty((3,2), dtype = int) y = np.zeros(5) z = np.ones((2,4)) x = np.arange(5) x = np.arange(10,20,2) x = np.linspace(10,20,5) """ 数组变换 """ # 创建一个行向量 vector = np.array([1, 2, 3, 4, 5, 6]) # 创建一个二维数组表示一个矩阵 matrix3 = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]) # 查看行数和列数 print(matrix3.shape) # 查看元素数量 print(matrix3.size) # 查看维数 print(matrix3.ndim) # 调整大小 matrix3.shape = (4,3) #直接改变了matrix3 print(matrix3) a = matrix3.reshape(4,3) # reshape如果提供一个整数,那么reshape会返回一个长度为该整数值的一维数组 print(matrix3.reshape(12)) c = matrix3.reshape(2,2,3) print(c) #矩阵转置 vector = np.array([1, 2, 3, 4, 5, 6]) matrix_vector = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) # 转置matrix_vector矩阵 print(matrix_vector.T) # 向量是不能被转置的 print(vector.T) vector.T.shape # 转置向量通常指二维数组表示形式下将行向量转换为列向量或者反向转换 print(np.array([[1, 2, 3, 4, 5, 6]]).T) # 矩阵展开 print(matrix_vector.flatten()) #数组链接 a = np.array([[1,2],[3,4]]) b = np.array([[5,6],[7,8]]) print(np.concatenate((a,b))) print(np.concatenate((a,b),axis = 1)) print(np.hstack((a,b))) print(np.vstack((a,b))) a = np.array([[1,2,3],[4,5,6]]) #向a里加元素 print(np.append(a, [7,8,9])) print(np.append(a, [[7,8,9]],axis = 0)) print(np.append(a, [[5,5,5],[7,8,9]],axis = 1)) #删除第二列 print(np.delete(a,1,axis = 0)) """ 数组计算 """ # 返回最大的元素 print(np.max(matrix3)) # 返回最小元素 print(np.min(matrix3)) # 找到每一列的最大元素 print(np.max(matrix3, axis=0)) # 找到每一行最大的元素 print(np.max(matrix3, axis=1)) # 返回平均值 print(np.mean(matrix3)) # 返回方差 print(np.var(matrix3)) # 返回标准差 print(np.std(matrix3)) # 求每一列的平均值 print(np.mean(matrix3, axis=0)) # 求每一行的方差 print(np.var(matrix3, axis=1)) # 点积 vector_a = np.array([1, 2, 3]) vector_b = np.array([4, 5, 6]) print(np.dot(vector_a, vector_b)) # Python 3.5+ 版本可以这样求 print(vector_a @ vector_b) #矩阵加,减,乘,逆 matrix_c = np.array([[1, 1], [1, 2]]) matrix_d = np.array([[1, 3], [1, 2]]) print(np.add(matrix_c, matrix_d)) print(np.subtract(matrix_c, matrix_d)) print(matrix_c + matrix_d) print(matrix_c - matrix_d) # 两矩阵相乘 print(np.dot(matrix_c, matrix_d)) print(matrix_c @ matrix_d) #矩阵对应元素相乘,而非矩阵乘法 print(matrix_c * matrix_d) matrix_e = np.array([[1, 4], [2, 5]]) # 计算矩阵的逆 print(np.linalg.inv(matrix_e)) # 验证一个矩阵和它的逆矩阵相乘等于I(单位矩阵) print(matrix_e @ np.linalg.inv(matrix_e)) """ 逻辑运算符 """ #数值比较 2<3 2==3 3<=3 #布尔运算 and or not x = 12 x>5 and x<15 y=5 y<7 or y>13 #numpy逻辑运算 a = np.array([21.5,15.8,25,18.2,17]) a>20 a>18 and a<22 #error np.logical_and(a>18,a<22) a[np.logical_and(a>18,a<22)] #条件语句 if else elif z = 4 if z%2 ==0: #True print('z is even') z = 5 if z%2 ==0: #false print('z is even') else: print('z is odd') z = 3 if z%2 ==0: #false print('z is even') elif z%3 ==0: print('z is divisible by 3') else: print('z is neither divisible by 2 nor by 3') """ 循环语句 """ #while loop error = 50 while error >1: error = error/4 print(error)
46271c71606f4a0c5d8bea5244401d1db8419b67
cl199406/python-data-structure-code
/treeOrder.py
677
4
4
#遍历树 #前序遍历 def preorder(tree): if tree: print(tree.getRootVal) preorder(tree.getLeftChild()) preorder(tree.getRightChild()) else: return None #后序遍历 def postorder(tree): if tree: preorder(tree.getLeftChild()) preorder(tree.getRightChild()) print(tree.getRootVal()) else: return None #中序遍历 def inorder(tree): if tree: inorder(tree.getLeftChild()) print(tree.getRootVal()) inorder(tree.getRightChild()) else: return None def printexp(tree): val='' if tree: val=val+'('+printexp(tree.getLeftChild()) val=val+str(tree.getRootVal()) val=val+printexp(tree.getRightChild())+')' else: val=None return val
cabd755951f46f0e6454a9342e4e7198113ff33c
cl199406/python-data-structure-code
/selectSort.py
347
3.78125
4
#selectSort 选择排序 def selectSort(alist): for fillslot in range(len(alist)-1,0,-1): positionMax=0 for location in range(1,fillslot+1): if alist[location]>alist[positionMax]: positionMax=location alist[fillslot],alist[positionMax]=alist[positionMax],alist[location] return alist print(selectSort([54,26,93,17,77,31,44,55,20]))
3ac26042891246dead71c85f0fd59f5f7316a516
akhilpgvr/HackerRank
/iterative_factorial.py
408
4.25
4
''' Write a iterative Python function to print the factorial of a number n (ie, returns n!). ''' usersnumber = int(input("Enter the number: ")) def fact(number): result = 1 for i in range(1,usersnumber+1): result *= i return result if usersnumber == 0: print('1') elif usersnumber < 0: print('Sorry factorial exists only for positive integers') else: print(fact(usersnumber))
d289be40f557068715fd14f141c3c24c7f516324
akhilpgvr/HackerRank
/nested.py
640
3.515625
4
namelist = list() gradelist = list() numbers = list() newlist = list() counter = int(input()) for i in range(counter): name = namelist.append(input().strip()) grade = gradelist.append(input().strip()) studentlist = [list(l) for l in zip(namelist,gradelist)] for list in studentlist: for element in list: if element.isdigit(): numbers.append(int(element)) for i in numbers: if i not in newlist: newlist.append(i) newlist.sort() newlist.remove(max(newlist)) minimum = newlist.pop() for list in studentlist: for element in list: if minimum in list: print(list)
a412e958ac2c18dd757f6b5a3e91fd897eda6658
akhilpgvr/HackerRank
/fuzzbuzz.py
435
4.1875
4
''' Write a Python program to print numbers from 1 to 100 except for multiples of 3 for which you should print "fuzz" instead, for multiples of 5 you should print 'buzz' instead and for multiples of both 3 and 5, you should print 'fuzzbuzz' instead. ''' for i in xrange(1,101): if i % 15 == 0: print 'fuzzbuzz' elif i % 3 == 0: print 'fuzz' elif i % 5 == 0: print 'buzz' else: print i
f44d2629a566d9a7e9ce2336d442fde4dd87ba20
jzferreira/datastructures
/python/linked_list/linked_list.py
6,609
4.28125
4
#!/bin/python3 class Node: '''Classe que representa um item do Linked List''' def __init__(self, data = None): self.data = data self.next = None class LinkedList: '''Classe que representa a estrutura de classe LinkedList''' def __init__(self, head = None): self.head = head self.__size = 0 def is_empty(self): return (self.head is None) def insert_tail(self, value=None): if (value is None): return #cria um novo Nó com o valor passado new_node = Node(data=value) #incrementa o tamanho da linked list self.__size += 1 #se a lista estiver vazia, adicione o nome nó como o Head if (self.is_empty()): self.head = new_node else: #senão, vamos até o final da Linked List para podermos adicionar last = self.head while (last.next is not None): last = last.next last.next = new_node def insert_head(self, value=None): if (value is None): return #cria um novo Nó com o valor passado new_node = Node(data=value) #incrementa o tamanho da linked list self.__size += 1 if (self.is_empty()): self.head = new_node else: #recuperamos o proximo do head current = self.head self.head = new_node self.head.next = current def find_node(self, value=None): if (value is None): return if (self.is_empty()): print('Linked Lista Vazia\n') return None else: current = self.head pos = 0 while (current is not None): if (current.data == value): print(f'{value} foi encontrado na posicao {pos}\n') break else: current = current.next pos += 1 if (current is None): print(f'{value} nao esta na lista\n') pos = -1 return current, pos def update_value(self, value=None, new_value=None): if (value is None or new_value is None): return if (self.is_empty()): print('Linked Lista Vazia\n') else: current = self.head while (current is not None): if (current.data == value): current.data = new_value break else: current = current.next def update_value_at_position(self, value=None, pos=-1): if (value is None): return if (pos < 0): return if(self.is_empty()): print('Linked Lista Vazia\n') else: current = self.head index = 0 while (current is not None): if (index == pos): current.data = value else: current = current.next index += 1 def delete(self, value): if (value is None): return if (self.is_empty()): print('Linked Lista Vazia\n') return None else: current = self.head prev = None #1 caso: o head é o Nó a ser removido if (current is not None and current.data == value): self.head = current.next print(f'{value} foi removido e era o head, o novo head e {self.head.data}\n') #incrementa o tamanho da linked list self.__size -= 1 return #2 caso: o valor a ser deletado está no meio da lista # Vamos procurar o valor e salvar o nó anterior visitado while (current is not None and current.data != value): prev = current current = current.next # se o current Node for diferente de None, então precisamos definir o prev.next # com o proximo do current. Assim, removemos o nó if (current is not None): prev.next = current.next self.__size -= 1 print(f'{value} foi removido\n') else: # porém, se o current Node for None, porque nao achou print(f'{value} nao foi encontrado\n') def delete_at_position(self, pos=-1): if (pos < 0): return if (self.is_empty()): return if (pos + 1) >= self.size(): print('Posicao nao encontrada2\n') else: current = self.head prev = None # 1 caso: Seja o head a ser removido if (pos == 0 and current is not None): #remove o HEAD self.head = current.next self.__size -= 1 return #2 caso: seja o caso do index ser maior que zero e menor que o tamanho index = 0 while (current is not None): if (index == pos): prev.next = current.next self.__size -= 1 break else: prev = current current = current.next index += 1 #caso 3: nao achou. Essa parte nao e necessaria pois comparamos antes de entrar no else if (current is None): print('Posicao não encontrado\n') def size(self): return self.__size def print_list(self): if (self.is_empty()): print('Linked List esta vazia\n') else: current = self.head while (current is not None): print(current.data, end=' -> ') current = current.next LinkedList = LinkedList() for i in range(1,11): LinkedList.insert_tail(i) LinkedList.print_list() print() LinkedList.find_node(11) LinkedList.delete(10) print(f'Tamanho da Lista: {LinkedList.size()}\n') LinkedList.print_list() LinkedList.delete(1) LinkedList.print_list() print(f'Tamanho da Lista: {LinkedList.size()}\n') LinkedList.insert_head(1) LinkedList.delete_at_position(1) LinkedList.print_list() LinkedList.update_value(1,20) LinkedList.update_value(50, 30) print() LinkedList.print_list() print() LinkedList.update_value_at_position(3, 50) LinkedList.update_value_at_position(30, 50) print() LinkedList.print_list()
3f8ea5f051b82e120e22782a1551c664a6fb8ea7
maciexu/pandas-Foundations
/Case_study.py
12,233
4.25
4
# what if there's no header???->header=None # Import pandas import pandas as pd # Read in the data file: df df = pd.read_csv(data_file) # Print the output of df.head() print(df.head()) # Read in the data file with header=None: df_headers df_headers = pd.read_csv(data_file, header=None) # Print the output of df_headers.head() print(df_headers.head()) # Re-assigning column names # Split on the comma to create a list: column_labels_list column_labels_list = column_labels.split(',') # Assign the new column labels to the DataFrame: df.columns df.columns = column_labels_list # Remove the appropriate columns: df_dropped df_dropped = df.drop(list_to_drop, axis='columns') # Print the output of df_dropped.head() print(df_dropped.head()) """ Cleaning and tidying datetime data In order to use the full power of pandas time series, you must construct a DatetimeIndex. To do so, it is necessary to clean and transform the date and time columns. The DataFrame df_dropped you created in the last exercise is provided for you and pandas has been imported as pd. Your job is to clean up the date and Time columns and combine them into a datetime collection to be used as the Index. """ # Convert the date column to string: df_dropped['date'] df_dropped['date'] = df_dropped['date'].astype(str) # Pad leading zeros to the Time column: df_dropped['Time'] df_dropped['Time'] = df_dropped['Time'].apply(lambda x:'{:0>4}'.format(x)) # Concatenate the new date and Time columns: date_string date_string = df_dropped['date'] + df_dropped['Time'] # Convert the date_string Series to datetime: date_times date_times = pd.to_datetime(date_string, format='%Y%m%d%H%M') # Set the index to be the new date_times container: df_clean df_clean = df_dropped.set_index(date_times) # Print the output of df_clean.head() print(df_clean.head()) """ Cleaning the numeric columns The numeric columns contain missing values labeled as 'M'. In this exercise, your job is to transform these columns such that they contain only numeric values and interpret missing data as NaN. The pandas function pd.to_numeric() is ideal for this purpose: It converts a Series of values to floating-point values. Furthermore, by specifying the keyword argument errors='coerce', you can force strings like 'M' to be interpreted as NaN. """ # Print the dry_bulb_faren temperature between 8 AM and 9 AM on June 20, 2011 print(df_clean.loc['2011-06-20 08:00:00':'2011-06-20 09:00:00', 'dry_bulb_faren']) # Convert the dry_bulb_faren column to numeric values: df_clean['dry_bulb_faren'] df_clean['dry_bulb_faren'] = pd.to_numeric(df_clean['dry_bulb_faren'], errors='coerce') # Print the transformed dry_bulb_faren temperature between 8 AM and 9 AM on June 20, 2011 print(df_clean.loc['2011-06-20 08:00:00':'2011-06-20 09:00:00', 'dry_bulb_faren']) # Convert the wind_speed and dew_point_faren columns to numeric values df_clean['wind_speed'] = pd.to_numeric(df_clean['wind_speed'] , errors='coerce') df_clean['dew_point_faren'] = pd.to_numeric(df_clean['dew_point_faren'], errors='coerce') # EDA # Print the median of the dry_bulb_faren column print(df_clean['dry_bulb_faren'].median()) # Print the median of the dry_bulb_faren column for the time range '2011-Apr':'2011-Jun' print(df_clean.loc['2011-Apr':'2011-Jun', 'dry_bulb_faren'].median()) # Print the median of the dry_bulb_faren column for the month of January print(df_clean.loc['2011-Jan', 'dry_bulb_faren'].median()) """ Signal variance You're now ready to compare the 2011 weather data with the 30-year normals reported in 2010. You can ask questions such as, on average, how much hotter was every day in 2011 than expected from the 30-year average? The DataFrames df_clean and df_climate from previous exercises are available in the workspace. Your job is to first resample df_clean and df_climate by day and aggregate the mean temperatures. You will then extract the temperature related columns from each - 'dry_bulb_faren' in df_clean, and 'Temperature' in df_climate - as NumPy arrays and compute the difference. Notice that the indexes of df_clean and df_climate are not aligned - df_clean has dates in 2011, while df_climate has dates in 2010. This is why you extract the temperature columns as NumPy arrays. An alternative approach is to use the pandas .reset_index() method to make sure the Series align properly. You will practice this approach as well. """ # Downsample df_clean by day and aggregate by mean: daily_mean_2011 daily_mean_2011 = df_clean.resample('D').mean() # Extract the dry_bulb_faren column from daily_mean_2011 using .values: daily_temp_2011 # Extract the 'dry_bulb_faren' column from daily_mean_2011 as a NumPy array using .values. # Store the result as daily_temp_2011. Note: .values is an attribute, not a method, so you don't have to use (). daily_temp_2011 = daily_mean_2011['dry_bulb_faren'].values # Downsample df_climate by day and aggregate by mean: daily_climate daily_climate = df_climate.resample('D').mean() # Extract the Temperature column from daily_climate using .reset_index(): daily_temp_climate # Be sure you call reset_index() on daily_climate and then access the 'Temperature' column using bracket indexing. daily_temp_climate = daily_climate.reset_index()['Temperature'] # Compute the difference between the two arrays and print the mean difference difference = daily_temp_2011 - daily_temp_climate print(difference.mean()) """ Sunny or cloudy On average, how much hotter is it when the sun is shining? In this exercise, you will compare temperatures on sunny days against temperatures on overcast days. Your job is to use Boolean selection to filter for sunny and overcast days, and then compute the difference of the mean daily maximum temperatures between each type of day. The DataFrame df_clean from previous exercises has been provided for you. The column 'sky_condition' provides information about whether the day was sunny ('CLR') or overcast ('OVC'). """ # Using df_clean, when is sky_condition 'CLR'? is_sky_clear = df_clean['sky_condition']=='CLR' # Filter df_clean using is_sky_clear sunny = df_clean.loc[is_sky_clear] # Resample sunny by day then calculate the max sunny_daily_max = sunny.resample('D').max() # See the result sunny_daily_max.head() # Using df_clean, when does sky_condition contain 'OVC'? is_sky_overcast = df_clean['sky_condition'].str.contains('OVC') # Filter df_clean using is_sky_overcast overcast = df_clean.loc[is_sky_overcast] # Resample overcast by day then calculate the max overcast_daily_max = overcast.resample('D').max() # See the result overcast_daily_max.head() # From previous steps is_sky_clear = df_clean['sky_condition']=='CLR' sunny = df_clean.loc[is_sky_clear] sunny_daily_max = sunny.resample('D').max() is_sky_overcast = df_clean['sky_condition'].str.contains('OVC') overcast = df_clean.loc[is_sky_overcast] overcast_daily_max = overcast.resample('D').max() # Calculate the mean of sunny_daily_max sunny_daily_max_mean = sunny_daily_max.mean() # Calculate the mean of overcast_daily_max overcast_daily_max_mean = overcast_daily_max.mean() # Print the difference (sunny minus overcast) print(sunny_daily_max_mean-overcast_daily_max_mean) """ Weekly average temperature and visibility Is there a correlation between temperature and visibility? Let's find out. In this exercise, your job is to plot the weekly average temperature and visibility as subplots. To do this, you need to first select the appropriate columns and then resample by week, aggregating the mean. In addition to creating the subplots, you will compute the Pearson correlation coefficient using .corr(). The Pearson correlation coefficient, known also as Pearson's r, ranges from -1 (indicating total negative linear correlation) to 1 (indicating total positive linear correlation). A value close to 1 here would indicate that there is a strong correlation between temperature and visibility. """ # Import matplotlib.pyplot as plt import matplotlib.pyplot as plt # Select the visibility and dry_bulb_faren columns and resample them: weekly_mean # Remember that to select multiple columns with the indexing operator, you need to pass a list (e.g. df_clean[['item 1', 'item 2']] weekly_mean = df_clean[['visibility','dry_bulb_faren']].resample('W').mean() # Print the output of weekly_mean.corr() print(weekly_mean.corr()) # Plot weekly_mean with subplots=True weekly_mean.plot(subplots=True) plt.show() # Daily hours of clear sky # Using df_clean, when is sky_condition 'CLR'? is_sky_clear = df_clean['sky_condition']=='CLR' # Resample is_sky_clear by day resampled = is_sky_clear.resample('D').sum() # See the result print(resampled) # From previous step is_sky_clear = df_clean['sky_condition'] == 'CLR' resampled = is_sky_clear.resample('D') # Calculate the number of sunny hours per day sunny_hours = resampled.sum() # Calculate the number of measured hours per day total_hours = resampled.count() # Calculate the fraction of hours per day that were sunny sunny_fraction = sunny_hours / total_hours # From previous steps is_sky_clear = df_clean['sky_condition'] == 'CLR' resampled = is_sky_clear.resample('D') sunny_hours = resampled.sum() total_hours = resampled.count() sunny_fraction = sunny_hours / total_hours # Make a box plot of sunny_fraction sunny_fraction.plot(kind='box') plt.show() """ Heat or humidity Dew point is a measure of relative humidity based on pressure and temperature. A dew point above 65 is considered uncomfortable while a temperature above 90 is also considered uncomfortable. In this exercise, you will explore the maximum temperature and dew point of each month. The columns of interest are 'dew_point_faren' and 'dry_bulb_faren'. After resampling them appropriately to get the maximum temperature and dew point in each month, generate a histogram of these values as subplots. """ # Resample dew_point_faren and dry_bulb_faren by Month, aggregating the maximum values: monthly_max monthly_max = df_clean[['dew_point_faren', 'dry_bulb_faren']].resample('M').max() # Generate a histogram with bins=8, alpha=0.5, subplots=True monthly_max.plot(kind='hist', bins=8, alpha=0.5, subplots=True) # Show the plot plt.show() """ Probability of high temperatures We already know that 2011 was hotter than the climate normals for the previous thirty years. In this final exercise, you will compare the maximum temperature in August 2011 against that of the August 2010 climate normals. More specifically, you will use a CDF plot to determine the probability of the 2011 daily maximum temperature in August being above the 2010 climate normal value. T o do this, you will leverage the data manipulation, filtering, resampling, and visualization skills you have acquired throughout this course. The two DataFrames df_clean and df_climate are available in the workspace. Your job is to select the maximum temperature in August in df_climate, and then maximum daily temperatures in August 2011. You will then filter to keep only the days in August 2011 that were above the August 2010 maximum, and use this to construct a CDF plot. Once you've generated the CDF, notice how it shows that there was a 50% probability of the 2011 daily maximum temperature in August being 5 degrees above the 2010 climate normal value! """ # Extract the maximum temperature in August 2010 from df_climate: august_max # You can select the rows corresponding to August 2010 in multiple ways. For example, df_climate.loc['2011-Feb'] selects all rows corresponding to February 2011, while df_climate.loc['2009-09', 'Pressure'] selects the rows corresponding to September 2009 from the 'Pressure' column. august_max = df_climate.loc['2010-Aug','Temperature'].max() print(august_max) # Resample August 2011 temps in df_clean by day & aggregate the max value: august_2011 august_2011 = df_clean.loc['2011-Aug','dry_bulb_faren'].resample('D').max() # Filter for days in august_2011 where the value exceeds august_max: august_2011_high august_2011_high = august_2011.loc[august_2011 > august_max] # Construct a CDF of august_2011_high august_2011_high.plot(kind='hist', normed=True, cumulative=True, bins=25) # Display the plot plt.show()
a8942c180a6a472c9481a8f581047e37844ff2e3
sidv1905/Python-programs
/Prac/revnumber.py
211
3.59375
4
#reverse of an number N=int(input('enter')) mylist=[] for i in range(0,N): n=input() mylist.append(temp) for reverse in mylist: rev=0 while(n>0): dig=n%10 rev=rev*10+dig n=n/10 print(rev)
4cfe8c7b648fea193a18ecbe38fe47686d62d411
sidv1905/Python-programs
/Codechef/turbosort.py
130
3.65625
4
t=int(input()) arr=[] for i in range(t): temp=int(input()) arr.append(temp) arr.sort() for sorti in arr: print(sorti)
d5e9f2961664be8cdb4248b657290c4f3d57a6fd
sidv1905/Python-programs
/Snackdown/combinations.py
652
3.625
4
def makeNumber(number, digits, path = []): if digits == 1: if number not in path: path += [number] path.sort() if number < 10 and path not in combinations: combinations.append(path) else: nums = list(range(1, min(number - digits + 2, 10))) nums = list(set(nums).difference(path)) for i in nums: makeNumber(number - i, digits - 1, path + [i]) import itertools as it def makeNumber2(number, digits): return list(filter(lambda x: sum(x) == number, it.combinations(range(1,10), digits))) combinations = [] makeNumber(15,3) print(combinations)
99618bf4dc37025a2a5ba52e1b71c8b22d205bef
sidv1905/Python-programs
/Prac/reversestring.py
76
3.75
4
s=input("enter a string") s=s.split() sx=s[::-1] sx=" ".join(sx) print(sx)
cea57889ff008ab9227ae48c07a56cbed8a5f78e
sidv1905/Python-programs
/Codechef/fitsquare.py
154
3.53125
4
T=int(input()) while T>0: B=int(input()) ans=0 while B>=2: B=B-2 base=B//2 ans=ans+base print(int(ans)) T=T-1
ec5f230755901f9a0c5dc17a03da7831ddbc0326
neighborpil/PY_WebCrawlingStudy
/Week1/Day2_8_EscapeCharacter.py
348
3.84375
4
""" # Escape character - 사용하다 보면 특수한 regular expression의 실제 문자를 사용하고 싶을 때에는 - 앞에다가 '\'를 붙여주면 된다 - special character가 아니라 그냥 문자가 된다 """ import re x = 'We just received $10.00 for cookies.' y = re.findall('\$[0-9.]+', x) # \$ : real dollar sign print(y)
7620e6d03efeb674fad8fb5d3b2565c78ddeaf2f
neighborpil/PY_WebCrawlingStudy
/Week2/Day6_Question3.py
825
3.5625
4
""" [질문 3] http://python-data.dr-chuck.net/comments_42.xml 해당 URL의 xml을 load한 후, comments의 총 갯수와 comments에 있는 각 count들을 모두 더해서 출력하는 파이썬 프로그램을 작성해주세요. (urllib, xml.etree.ElementTree 등을 import 하여 사용하시면 됩니다.) * """ import xml.etree.ElementTree as ET import urllib.request, urllib.parse, urllib.error import re raw = urllib.request.urlopen('http://python-data.dr-chuck.net/comments_42.xml').read() lines = raw.decode() stuff = ET.fromstring(lines) lst = stuff.findall('comments/comment') sum = 0; for item in lst: word = item.find('count').text word = word.strip() check = re.findall("[0-9]+", word) if len(check) == 1: sum += int(check[0]) print('totalcount: ', len(lst)) print('sum: ', sum)
0cacf9f1b270d2814847c7d4091de5592bc47bad
SherriChuah/google-code-sample
/python/src/playlists.py
1,501
4.1875
4
"""A playlists class.""" """Keeps the individual video playlist""" from .video_playlist import VideoPlaylist class Playlists: """A class used to represent a Playlists containing video playlists""" def __init__(self): self._playlist = {} def number_of_playlists(self): return len(self._playlist) def get_all_playlists(self): """Returns all available playlist information from the playlist library.""" return list(self._playlist.values()) def get_playlist(self, playlist_name): """Returns the videoplaylist object (name, content) from the playlists. Args: playlist_name: Name of playlist Returns: The VideoPlaylist object for the requested playlist_name. None if the playlist does not exist. """ for i in self._playlist: if i.lower() == playlist_name.lower(): return self._playlist[i] def add_playlist(self, playlist: VideoPlaylist): """Adds a playlist into the dic of playlists Args: playlist: VideoPlaylist object """ lower = [i.lower() for i in self._playlist.keys()] if playlist.name.lower() in lower: return False else: self._playlist[playlist.name] = playlist return True def remove_playlist(self, name): """Remove a playlist from the dic of playlists Args: name: name of playlist """ lower = [i.lower() for i in self._playlist.keys()] if name.lower() in lower: self._playlist.pop(self.get_playlist(name).name) return True else: return False
f8cfd25b751825375fc4a164104a149a5220fd22
Manish-Kumar317/Python-Assgn.
/Program 1.py
174
4
4
a=30 b=10 print("additon of two numbers is",(a+b)) print("additon of two numbers is",(a-b)) print("additon of two numbers is",(a*b)) print("additon of two numbers is",(a/b))
c55506a58a3547970149ed7b11225fcfeee5f193
tryhear/info
/bak/zanbu.py
6,020
3.671875
4
import random from icecream import ic import sqlite3 import stackprinter # 0为阴,1为阳 # —为阴 ——为阳 X为老阴 O为老阳 def 抽签(): 签 = "" 备选字符 = [0, 1] 三枚铜钱 = [] 爻序 = 1 爻列表 = [] 变爻序号 = [] 变爻次数 = 0 变卦 = "" for i in range(6): for j in range(3): 摇卦 = random.choice(备选字符) 三枚铜钱.append(摇卦) if 三枚铜钱.count(0) == 3: 爻列表.append("X") 变爻序号.append(i + 1) 变爻次数 += 1 爻 = 0 变卦 += "1" elif 三枚铜钱.count(1) == 3: 爻列表.append("O") 变爻序号.append(i + 1) 变爻次数 += 1 爻 = 1 变卦 += "0" elif 三枚铜钱.count(1) == 2: 爻列表.append("—") 爻 = 1 变卦 += str(爻) elif 三枚铜钱.count(0) == 2: 爻列表.append("--") 爻 = 0 变卦 += str(爻) else: stackprinter.show() 爻序 += 1 签 += str(爻) 三枚铜钱.clear() if 变爻次数 == 0: 变卦 = "静卦" # 爻列表.reverse() ic(爻列表) ic(变爻次数) ic(变爻序号) ic(变卦) return 签, 变卦, 变爻次数, 变爻序号 def 解签(待解的签, 变卦="", 变爻次数="0", 变爻序号=[]): 待解的签 = 待解的签 变卦 = 变卦 变爻次数 = 变爻次数 变爻序号 = 变爻序号 原始爻 = {1: "初", 2: "二", 3: "三", 4: "四", 5: "五", 6: "上"} 解签用变爻序号 = "" connect = sqlite3.connect("zanbu.db") cursor = connect.cursor() # 测试变爻次数 # 根据变爻次数按顺序取解签序号,这里会根据变爻次数确定取值及顺序 # 六爻不变为静卦,用本卦卦辞解卦 # 变爻次数=1,就用这个变爻的爻辞解卦 # 变爻次数=2,就用这两个变爻的爻辞解卦,以上爻为主(上爻在前) # 变爻次数=3,用本卦卦辞结合变卦卦辞作综合考虑 # 变爻次数=4,用另外两个静爻的爻辞解卦,并以下爻爻辞为主(原始爻和变爻序号的差集,余二,下爻在前) # 变爻次数=5,用变卦的静爻爻辞解卦 # 变爻次数=6,乾、坤用用九,用六爻辞解卦,其它卦则用变卦的卦辞解卦 if 变爻次数 == 1: for i in 变爻序号: 解签用变爻序号 += 原始爻[i] sql = "SELECT " + 解签用变爻序号 + " FROM zanbu WHERE 符号=" + '"' + 待解的签 + '"' ic(sql) cursor.execute(sql) ic(cursor.fetchall()) elif 变爻次数 == 2: for i in 变爻序号: 解签用变爻序号 += 原始爻[i] 解签用变爻序号 += "," # 去掉最后的逗号 解签用变爻序号 = 解签用变爻序号[:-1] # 倒序 解签用变爻序号 = 解签用变爻序号[::-1] sql = "SELECT " + 解签用变爻序号 + " FROM zanbu WHERE 符号=" + '"' + 待解的签 + '"' ic(sql) cursor.execute(sql) ic(cursor.fetchall()) elif 变爻次数 == 3: sql = "SELECT 初,二,三,四,五,上 FROM zanbu WHERE 符号=" + '"' + 待解的签 + '"' sql_bg = "SELECT 初,二,三,四,五,上 FROM zanbu WHERE 符号=" + '"' + 变卦 + '"' ic(sql, sql_bg) cursor.execute(sql) ic(cursor.fetchall()) cursor.execute(sql_bg) ic(cursor.fetchall()) elif 变爻次数 == 4: # 求差集得到两个静爻 解签用变爻序号1 = "" b = {1: "初", 2: "二", 3: "三", 4: "四", 5: "五", 6: "上"} for i in 变爻序号: # ic(i) b.pop(i) #ic(b) for i in b: 解签用变爻序号1 += b[i] 解签用变爻序号1 += "," #ic(解签用变爻序号1) # 去掉最后的逗号 解签用变爻序号1 = 解签用变爻序号1[:-1] sql = "SELECT " + 解签用变爻序号1 + " FROM zanbu WHERE 符号=" + '"' + 待解的签 + '"' ic(sql) try: cursor.execute(sql) ic(cursor.fetchall()) except: stackprinter.show() elif 变爻次数 == 5: # 求差集得到一个静爻 解签用变爻序号1 = "" b = {1: "初", 2: "二", 3: "三", 4: "四", 5: "五", 6: "上"} for i in 变爻序号: # ic(i) b.pop(i) #ic(b) for i in b: 解签用变爻序号1 += b[i] 解签用变爻序号1 += "," ic(解签用变爻序号1) # 去掉最后的逗号 解签用变爻序号1 = 解签用变爻序号1[:-1] sql = "SELECT " + 解签用变爻序号1 + " FROM zanbu WHERE 符号=" + '"' + 变卦 + '"' ic(sql) try: cursor.execute(sql) ic(cursor.fetchall()) except: stackprinter.show() elif 变爻次数 == 6: if 待解的签 == "111111" or 待解的签 == "000000": sql = "SELECT 用九 FROM zanbu WHERE 符号=" + '"' + 待解的签 + '"' cursor.execute(sql) ic(cursor.fetchall()) else: sql = "SELECT 初,二,三,四,五,上 FROM zanbu WHERE 符号=" + '"' + 变卦 + '"' cursor.execute(sql) ic(cursor.fetchall()) else: # 为0的情况 sql = "SELECT 初,二,三,四,五,上 FROM zanbu WHERE 符号=" + '"' + 待解的签 + '"' cursor.execute(sql) ic(cursor.fetchall()) cursor.close() # connect.commit() if __name__ == "__main__": stackprinter.set_excepthook(style="color") 所抽的签, 变卦, 变爻次数, 变爻序号 = 抽签() ic(所抽的签) 解签(所抽的签, 变卦, 变爻次数, 变爻序号)
861ada8af86a6060dfc173d19e0364e2132a447e
DataActivator/Python3tutorials
/Decisioncontrol-Loop/whileloop.py
944
4.21875
4
''' A while loop implements the repeated execution of code based on a given Boolean condition. while [a condition is True]: [do something] As opposed to for loops that execute a certain number of times, while loops are conditionally based so you don’t need to know how many times to repeat the code going in. ''' # Q1:- run the program until user don't give correct captain name captain = '' while captain != 'Virat': captain = input('Who is the captain of indian Team :- ') print('Yes, The captain of india is ' + captain) print('Yes, the captain of india is {} ' .format(captain)) print(f'Yes, The captain of India is {captain.upper()}') # break & continue example in while loop i = 0 while i<5: print(i) if i == 3: break i += 1 # else block in for & while loop i = 0 while i<5: print(i) # if i == 3: # break i += 1 else : print('After while loop ') print('Data Activator')
23011b3f23f690d63031dfb0691b58b8b883ba0d
AineKiraboMbabazi/analysis-api
/statisticsapi/models/government.py
412
3.625
4
class Government(): """Government class defining the Government model""" def __init__(self, name, photo, status, created_by, creation_date, updated_by, updated_at): self.photo = photo self.name = name self.updated_by = updated_by self.status = status self.created_by = created_by self.creation_date = creation_date self.updated_at = updated_at