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
039916b7ca6174a0c119d08ee6e8848337a12c26
abigail-hyde/flood-agh54-bjw68
/floodsystem/geo.py
5,853
3.71875
4
# Copyright (C) 2018 Garth N. Wells # # SPDX-License-Identifier: MIT """This module contains a collection of functions related to geographical data. """ from .utils import sorted_by_key # noqa import plotly.express as px import geopandas import pandas as pd from haversine import haversine, Unit from .analysis import flow_range_colours def rivers_with_station(stations): """Created a sorted list of Rivers with stations on them""" # Initialise rivers list rivers = [] # Add river to list from station, if river is not present for station in stations: if station.river in rivers: pass else: rivers.append(station.river) # Sort list rivers.sort() return rivers def stations_by_river(stations): """Create a dictionary of all Rivers with a corresponding station list""" # Initialise river dictionary rivers_dict = {} # Create list of valid rivers rivers = rivers_with_station(stations) # Create a station list for each river for river in rivers: river_list = [] # If the river value of a station matches the current river, add it to the list checked_stations = [] for station in stations: if station.name not in checked_stations: if station.river == river: river_list.append(station.name) checked_stations.append(station.name) river_list.sort() rivers_dict[river] = river_list return rivers_dict def rivers_by_station_number(stations, N): """Create a list of stations and corresponding number of monitoring stations""" # Initialise station list and container for all rivers river_stations = stations_by_river(stations) river_number = [] # Find number for all rivers for river in river_stations: # Sum number of stations on each river total = 0 for station in river_stations[river]: total += 1 # Create a container for the river and its value river_value = (river, total) river_number.append(river_value) # Sort total list by number in reverse order river_num_sorted = sorted(river_number, key=lambda x: x[1], reverse=True) # Iterate through list of rivers count = 0 top_N_rivers = [] # Break when desired value is reached while count < N and count < len(river_num_sorted): # Add top river if count == 0: top_N_rivers.append(river_num_sorted[0]) count += 1 # Add river and to the count provided the entry is smaller than the last elif (river_num_sorted[count][1]) < (river_num_sorted[count-1][1]): top_N_rivers.append(river_num_sorted[count]) count += 1 # Add river when it has the same as the previous number, but add to N as well to preserve distance else: top_N_rivers.append(river_num_sorted[count]) count += 1 N += 1 # Return list return top_N_rivers def map_station(stations): """Function to plot the locations of the pumping stations""" #Create coordiante lists coordx = [] coordy = [] name = [] # Stores coordinate data per station for station in stations: coordx.append(station.coord[0]) coordy.append(station.coord[1]) name.append(station.name) #Get the respective colours for our station list colour = flow_range_colours(stations) # Creates a dataframe of names, coordinates and colours df = pd.DataFrame( {'City': name, 'Colour': colour, 'Latitude': coordx, 'Longitude': coordy}) # Convert to geo-dataframe storage type for access gdf = geopandas.GeoDataFrame(df, geometry=geopandas.points_from_xy(df.Longitude, df.Latitude)) # Output dataframe return gdf def position_plotter(geodf): # Creates a map image with points plotted at coordiantes, labelled with their name fig = px.scatter_geo(geodf, lat=geodf.geometry.y, lon=geodf.geometry.x, #Set the label as station name, and colour as the assigned station colour hover_name="City", color='Colour', color_discrete_sequence=["goldenrod", "blue", "red", "green"] ) # Fits the view around the input data fig.update_geos(fitbounds="locations") # Modifies plot window and margins fig.update_layout(height=300, margin={"r":0,"t":0,"l":0,"b":0}) # Plots the result fig.show() def stations_by_distance(stations, p): """Create a list of stations ordered by distance from a specified location""" # Create list distances = [] # Calculate the distance from the point to each station use the haversine library function and add to list for station in stations: distance = haversine(station.coord,p) data = (station.name, distance) if data in distances: pass else: distances.append((station.name,distance)) # Sort by distance and return this list distances_sorted = sorted_by_key(distances,1) return distances_sorted def stations_within_radius(stations, centre, r): """Create a list of stations within a certain radius of a specified location""" # Create list close_stations = [] # Adds valid stations to the list for station in stations: if station.name in close_stations: pass else: # works out distance of station from centre distance = haversine(station.coord,centre) if distance < r: close_stations.append(station.name) else: pass # Sort by distance and return this list stations_sorted = sorted(close_stations) return stations_sorted
10434d3fba05ecfd9cda0e34a4629511f6c9e657
superman-wrdh/python-application
/product_and_consume/demo_4.py
1,811
3.90625
4
""" 4、信号量模型 """ import sys, time import random from threading import Thread, Semaphore product = [] mutex = Semaphore(1) full = Semaphore(0) empty = Semaphore(5) class Producer(Thread): def __init__(self, speed): Thread.__init__(self); self.speed = speed; def run(self): while True: for i in range(self.speed): ProductThing = ''; empty.acquire() mutex.acquire() num = random.random() ProductThing += str(num) + ' ' product.append(str(num)) print('%s: count=%d' % ("producer" + str(self.speed), len(product))) print(' product things:' + ProductThing) mutex.release() full.release() time.sleep(1) class Consumer(Thread): def __init__(self): Thread.__init__(self); def run(self): count = 0 time_start = time.clock() while True: speed = random.randint(1, 5) for i in range(speed): consumeThing = "" full.acquire() mutex.acquire() consumeThing += str(product[0]) + ' ' del product[0] print('%s: count=%d' % ("consumer", len(product))) print(' consume things:' + consumeThing) count = count + 1 if (count == 20): time_end = time.clock() print("消费 " + str(count) + "个商品所用时间: %f s" % (time_end - time_start)) mutex.release() empty.release() time.sleep(1) if __name__ == '__main__': Producer(1).start() Producer(2).start() Consumer().start()
541b931a10c54f951a05271d70425d085634da56
superman-wrdh/python-application
/python_thread/ConsumerProduct.py
1,053
3.75
4
# -*- encoding: utf-8 -*- import threading import queue import random import time class Producter(threading.Thread): """生产者线程""" def __init__(self, t_name, queue): self.queue = queue threading.Thread.__init__(self, name=t_name) def run(self): for i in range(100): #random_num = random.randint(1, 99) self.queue.put(i) print('put num in Queue %s' % i) time.sleep(1) print('put queue done') class ConsumeEven(threading.Thread): """消费线程""" def __init__(self, t_name, queue): self.queue = queue threading.Thread.__init__(self, name=t_name) def run(self): while True: v = self.queue.get() print(self.name + " " + str(v)) if __name__ == '__main__': q = queue.Queue() pt = Producter('producter', q) ce = ConsumeEven('consumeeven-1', q) ce2 = ConsumeEven('consumeeven-2', q) ce.start() ce2.start() pt.start() pt.join() ce.join() ce2.join()
554629c99caf7f3c1fab124b412a16fd865b8f4b
Colaplusice/hello_fluent_python
/chapter 1/1.2.py
830
4.0625
4
#encoding=utf-8 from math import hypot #设计一个向量类 #hypot 返回欧氏距离 class Vector: def __init__(self,x,y): self.x=x self.y=y pass #求欧式距离 def __abs__(self): return hypot(self.x,self.y) pass ##打印对象 def __repr__(self): return "Vector({},{})".format(self.x,self.y) pass # 如果模是0,返回false def __bool__(self): return bool(abs(self)) #两个向量相加 def __add__(self, other): x=self.x+other.x y=self.y+other.y return Vector(x,y) #两个向量相乘 def __mul__(self, other): x=self.x*other.x y=self.y*other.y return Vector(x,y) vector=Vector(2,5) vector2=Vector(3,4) print vector v3=vector+vector2 print(v3) print abs(vector)
7e0665c20c10efb75b64bc249ebd832c615de897
Colaplusice/hello_fluent_python
/chapter7_decorator/program_time.py
657
3.59375
4
import time def clock(func): def clocked(*args): t_1 = time.perf_counter() # 运行实体函数 result = func(*args) t_2 = time.perf_counter() name = func.__name__ arg_str = ",".join(repr(arg) for arg in args) print("spend time is {},arg is{}".format(t_2 - t_1, arg_str)) return result return clocked @clock def generate_100(): a_list = [] for i in range(10): a = [2] * 10 a_list.append(a) return a_list @clock def factorial(n): return 1 if n < 2 else n * factorial(n - 1) if __name__ == "__main__": factorial(130) # print(generate_100())
e919859a9e00b0da6f488fa5160e4b699a550e2a
Insight-book/data-science-from-scratch
/scratch/probability.py
4,737
3.703125
4
def uniform_cdf(x: float) -> float: """Returns the probability that a uniform random variable is <= x""" if x < 0: return 0 # uniform random is never less than 0 elif x < 1: return x # e.g. P(X <= 0.4) = 0.4 else: return 1 # uniform random is always less than 1 import math SQRT_TWO_PI = math.sqrt(2 * math.pi) def normal_pdf(x: float, mu: float = 0, sigma: float = 1) -> float: return (math.exp(-(x-mu) ** 2 / 2 / sigma ** 2) / (SQRT_TWO_PI * sigma)) import matplotlib.pyplot as plt xs = [x / 10.0 for x in range(-50, 50)] plt.plot(xs,[normal_pdf(x,sigma=1) for x in xs],'-',label='mu=0,sigma=1') plt.plot(xs,[normal_pdf(x,sigma=2) for x in xs],'--',label='mu=0,sigma=2') plt.plot(xs,[normal_pdf(x,sigma=0.5) for x in xs],':',label='mu=0,sigma=0.5') plt.plot(xs,[normal_pdf(x,mu=-1) for x in xs],'-.',label='mu=-1,sigma=1') plt.legend() plt.title("Various Normal pdfs") # plt.show() # plt.savefig('im/various_normal_pdfs.png') plt.gca().clear() plt.close() plt.clf() def normal_cdf(x: float, mu: float = 0, sigma: float = 1) -> float: return (1 + math.erf((x - mu) / math.sqrt(2) / sigma)) / 2 xs = [x / 10.0 for x in range(-50, 50)] plt.plot(xs,[normal_cdf(x,sigma=1) for x in xs],'-',label='mu=0,sigma=1') plt.plot(xs,[normal_cdf(x,sigma=2) for x in xs],'--',label='mu=0,sigma=2') plt.plot(xs,[normal_cdf(x,sigma=0.5) for x in xs],':',label='mu=0,sigma=0.5') plt.plot(xs,[normal_cdf(x,mu=-1) for x in xs],'-.',label='mu=-1,sigma=1') plt.legend(loc=4) # bottom right plt.title("Various Normal cdfs") # plt.show() plt.close() plt.gca().clear() plt.clf() def inverse_normal_cdf(p: float, mu: float = 0, sigma: float = 1, tolerance: float = 0.00001) -> float: """Find approximate inverse using binary search""" # if not standard, compute standard and rescale if mu != 0 or sigma != 1: return mu + sigma * inverse_normal_cdf(p, tolerance=tolerance) low_z = -10.0 # normal_cdf(-10) is (very close to) 0 hi_z = 10.0 # normal_cdf(10) is (very close to) 1 while hi_z - low_z > tolerance: mid_z = (low_z + hi_z) / 2 # Consider the midpoint mid_p = normal_cdf(mid_z) # and the cdf's value there if mid_p < p: low_z = mid_z # Midpoint too low, search above it else: hi_z = mid_z # Midpoint too high, search below it return mid_z import random def bernoulli_trial(p: float) -> int: """Returns 1 with probability p and 0 with probability 1-p""" return 1 if random.random() < p else 0 def binomial(n: int, p: float) -> int: """Returns the sum of n bernoulli(p) trials""" return sum(bernoulli_trial(p) for _ in range(n)) from collections import Counter def binomial_histogram(p: float, n: int, num_points: int) -> None: """Picks points from a Binomial(n, p) and plots their histogram""" data = [binomial(n, p) for _ in range(num_points)] # use a bar chart to show the actual binomial samples histogram = Counter(data) plt.bar([x - 0.4 for x in histogram.keys()], [v / num_points for v in histogram.values()], 0.8, color='0.75') mu = p * n sigma = math.sqrt(n * p * (1 - p)) # use a line chart to show the normal approximation xs = range(min(data), max(data) + 1) ys = [normal_cdf(i + 0.5, mu, sigma) - normal_cdf(i - 0.5, mu, sigma) for i in xs] plt.plot(xs,ys) plt.title("Binomial Distribution vs. Normal Approximation") # plt.show() def main(): import enum, random # An Enum is a typed set of enumerated values. We can use them # to make our code more descriptive and readable. class Kid(enum.Enum): BOY = 0 GIRL = 1 def random_kid() -> Kid: return random.choice([Kid.BOY, Kid.GIRL]) both_girls = 0 older_girl = 0 either_girl = 0 random.seed(0) for _ in range(10000): younger = random_kid() older = random_kid() if older == Kid.GIRL: older_girl += 1 if older == Kid.GIRL and younger == Kid.GIRL: both_girls += 1 if older == Kid.GIRL or younger == Kid.GIRL: either_girl += 1 print("P(both | older):", both_girls / older_girl) # 0.514 ~ 1/2 print("P(both | either): ", both_girls / either_girl) # 0.342 ~ 1/3 assert 0.48 < both_girls / older_girl < 0.52 assert 0.30 < both_girls / either_girl < 0.35 def uniform_pdf(x: float) -> float: return 1 if 0 <= x < 1 else 0 if __name__ == "__main__": main()
777f8bcef8f9630c473f891529f57ad1c824c1a9
Insight-book/data-science-from-scratch
/scratch/databases.py
12,901
3.59375
4
users = [[0, "Hero", 0], [1, "Dunn", 2], [2, "Sue", 3], [3, "Chi", 3]] from typing import Tuple, Sequence, List, Any, Callable, Dict, Iterator from collections import defaultdict # A few type aliases we'll use later Row = Dict[str, Any] # A database row WhereClause = Callable[[Row], bool] # Predicate for a single row HavingClause = Callable[[List[Row]], bool] # Predicate over multiple rows class Table: def __init__(self, columns: List[str], types: List[type]) -> None: assert len(columns) == len(types), "# of columns must == # of types" self.columns = columns # Names of columns self.types = types # Data types of columns self.rows: List[Row] = [] # (no data yet) def col2type(self, col: str) -> type: idx = self.columns.index(col) # Find the index of the column, return self.types[idx] # and return its type. def insert(self, values: list) -> None: # Check for right # of values if len(values) != len(self.types): raise ValueError(f"You need to provide {len(self.types)} values") # Check for right types of values for value, typ3 in zip(values, self.types): if not isinstance(value, typ3) and value is not None: raise TypeError(f"Expected type {typ3} but got {value}") # Add the corresponding dict as a "row" self.rows.append(dict(zip(self.columns, values))) def __getitem__(self, idx: int) -> Row: return self.rows[idx] def __iter__(self) -> Iterator[Row]: return iter(self.rows) def __len__(self) -> int: return len(self.rows) def __repr__(self): """Pretty representation of the table: columns then rows""" rows = "\n".join(str(row) for row in self.rows) return f"{self.columns}\n{rows}" def update(self, updates: Dict[str, Any], predicate: WhereClause = lambda row: True): # First make sure the updates have valid names and types for column, new_value in updates.items(): if column not in self.columns: raise ValueError(f"invalid column: {column}") typ3 = self.col2type(column) if not isinstance(new_value, typ3) and new_value is not None: raise TypeError(f"expected type {typ3}, but got {new_value}") # Now update for row in self.rows: if predicate(row): for column, new_value in updates.items(): row[column] = new_value def delete(self, predicate: WhereClause = lambda row: True) -> None: """Delete all rows matching predicate""" self.rows = [row for row in self.rows if not predicate(row)] def select(self, keep_columns: List[str] = None, additional_columns: Dict[str, Callable] = None) -> 'Table': if keep_columns is None: # If no columns specified, keep_columns = self.columns # return all columns if additional_columns is None: additional_columns = {} # New column names and types new_columns = keep_columns + list(additional_columns.keys()) keep_types = [self.col2type(col) for col in keep_columns] # This is how to get the return type from a type annotation. # It will crash if `calculation` doesn't have a return type. add_types = [calculation.__annotations__['return'] for calculation in additional_columns.values()] # Create a new table for results new_table = Table(new_columns, keep_types + add_types) for row in self.rows: new_row = [row[column] for column in keep_columns] for column_name, calculation in additional_columns.items(): new_row.append(calculation(row)) new_table.insert(new_row) return new_table def where(self, predicate: WhereClause = lambda row: True) -> 'Table': """Return only the rows that satisfy the supplied predicate""" where_table = Table(self.columns, self.types) for row in self.rows: if predicate(row): values = [row[column] for column in self.columns] where_table.insert(values) return where_table def limit(self, num_rows: int) -> 'Table': """Return only the first `num_rows` rows""" limit_table = Table(self.columns, self.types) for i, row in enumerate(self.rows): if i >= num_rows: break values = [row[column] for column in self.columns] limit_table.insert(values) return limit_table def group_by(self, group_by_columns: List[str], aggregates: Dict[str, Callable], having: HavingClause = lambda group: True) -> 'Table': grouped_rows = defaultdict(list) # Populate groups for row in self.rows: key = tuple(row[column] for column in group_by_columns) grouped_rows[key].append(row) # Result table consists of group_by columns and aggregates new_columns = group_by_columns + list(aggregates.keys()) group_by_types = [self.col2type(col) for col in group_by_columns] aggregate_types = [agg.__annotations__['return'] for agg in aggregates.values()] result_table = Table(new_columns, group_by_types + aggregate_types) for key, rows in grouped_rows.items(): if having(rows): new_row = list(key) for aggregate_name, aggregate_fn in aggregates.items(): new_row.append(aggregate_fn(rows)) result_table.insert(new_row) return result_table def order_by(self, order: Callable[[Row], Any]) -> 'Table': new_table = self.select() # make a copy new_table.rows.sort(key=order) return new_table def join(self, other_table: 'Table', left_join: bool = False) -> 'Table': join_on_columns = [c for c in self.columns # columns in if c in other_table.columns] # both tables additional_columns = [c for c in other_table.columns # columns only if c not in join_on_columns] # in right table # all columns from left table + additional_columns from right table new_columns = self.columns + additional_columns new_types = self.types + [other_table.col2type(col) for col in additional_columns] join_table = Table(new_columns, new_types) for row in self.rows: def is_join(other_row): return all(other_row[c] == row[c] for c in join_on_columns) other_rows = other_table.where(is_join).rows # Each other row that matches this one produces a result row. for other_row in other_rows: join_table.insert([row[c] for c in self.columns] + [other_row[c] for c in additional_columns]) # If no rows match and it's a left join, output with Nones. if left_join and not other_rows: join_table.insert([row[c] for c in self.columns] + [None for c in additional_columns]) return join_table def main(): # Constructor requires column names and types users = Table(['user_id', 'name', 'num_friends'], [int, str, int]) users.insert([0, "Hero", 0]) users.insert([1, "Dunn", 2]) users.insert([2, "Sue", 3]) users.insert([3, "Chi", 3]) users.insert([4, "Thor", 3]) users.insert([5, "Clive", 2]) users.insert([6, "Hicks", 3]) users.insert([7, "Devin", 2]) users.insert([8, "Kate", 2]) users.insert([9, "Klein", 3]) users.insert([10, "Jen", 1]) assert len(users) == 11 assert users[1]['name'] == 'Dunn' assert users[1]['num_friends'] == 2 # Original value users.update({'num_friends' : 3}, # Set num_friends = 3 lambda row: row['user_id'] == 1) # in rows where user_id == 1 assert users[1]['num_friends'] == 3 # Updated value # SELECT * FROM users; all_users = users.select() assert len(all_users) == 11 # SELECT * FROM users LIMIT 2; two_users = users.limit(2) assert len(two_users) == 2 # SELECT user_id FROM users; just_ids = users.select(keep_columns=["user_id"]) assert just_ids.columns == ['user_id'] # SELECT user_id FROM users WHERE name = 'Dunn'; dunn_ids = ( users .where(lambda row: row["name"] == "Dunn") .select(keep_columns=["user_id"]) ) assert len(dunn_ids) == 1 assert dunn_ids[0] == {"user_id": 1} # SELECT LENGTH(name) AS name_length FROM users; def name_length(row) -> int: return len(row["name"]) name_lengths = users.select(keep_columns=[], additional_columns = {"name_length": name_length}) assert name_lengths[0]['name_length'] == len("Hero") def min_user_id(rows) -> int: return min(row["user_id"] for row in rows) def length(rows) -> int: return len(rows) stats_by_length = ( users .select(additional_columns={"name_length" : name_length}) .group_by(group_by_columns=["name_length"], aggregates={"min_user_id" : min_user_id, "num_users" : length}) ) assert len(stats_by_length) == 3 assert stats_by_length.columns == ["name_length", "min_user_id", "num_users"] def first_letter_of_name(row: Row) -> str: return row["name"][0] if row["name"] else "" def average_num_friends(rows: List[Row]) -> float: return sum(row["num_friends"] for row in rows) / len(rows) def enough_friends(rows: List[Row]) -> bool: return average_num_friends(rows) > 1 avg_friends_by_letter = ( users .select(additional_columns={'first_letter' : first_letter_of_name}) .group_by(group_by_columns=['first_letter'], aggregates={"avg_num_friends" : average_num_friends}, having=enough_friends) ) assert len(avg_friends_by_letter) == 6 assert {row['first_letter'] for row in avg_friends_by_letter} == \ {"H", "D", "S", "C", "T", "K"} def sum_user_ids(rows: List[Row]) -> int: return sum(row["user_id"] for row in rows) user_id_sum = ( users .where(lambda row: row["user_id"] > 1) .group_by(group_by_columns=[], aggregates={ "user_id_sum" : sum_user_ids }) ) assert len(user_id_sum) == 1 assert user_id_sum[0]["user_id_sum"] == 54 friendliest_letters = ( avg_friends_by_letter .order_by(lambda row: -row["avg_num_friends"]) .limit(4) ) assert len(friendliest_letters) == 4 assert friendliest_letters[0]['first_letter'] in ['S', 'T'] user_interests = Table(['user_id', 'interest'], [int, str]) user_interests.insert([0, "SQL"]) user_interests.insert([0, "NoSQL"]) user_interests.insert([2, "SQL"]) user_interests.insert([2, "MySQL"]) sql_users = ( users .join(user_interests) .where(lambda row: row["interest"] == "SQL") .select(keep_columns=["name"]) ) assert len(sql_users) == 2 sql_user_names = {row["name"] for row in sql_users} assert sql_user_names == {"Hero", "Sue"} def count_interests(rows: List[Row]) -> int: """counts how many rows have non-None interests""" return len([row for row in rows if row["interest"] is not None]) user_interest_counts = ( users .join(user_interests, left_join=True) .group_by(group_by_columns=["user_id"], aggregates={"num_interests" : count_interests }) ) likes_sql_user_ids = ( user_interests .where(lambda row: row["interest"] == "SQL") .select(keep_columns=['user_id']) ) likes_sql_user_ids.group_by(group_by_columns=[], aggregates={ "min_user_id" : min_user_id }) assert len(likes_sql_user_ids) == 2 ( user_interests .where(lambda row: row["interest"] == "SQL") .join(users) .select(["name"]) ) ( user_interests .join(users) .where(lambda row: row["interest"] == "SQL") .select(["name"]) ) if __name__ == "__main__": main()
5200b01aac613d06740c4654226c7a74aa960aea
Insight-book/data-science-from-scratch
/scratch/simple_linear_regression.py
3,316
3.84375
4
def predict(alpha: float, beta: float, x_i: float) -> float: return beta * x_i + alpha def error(alpha: float, beta: float, x_i: float, y_i: float) -> float: """ The error from predicting beta * x_i + alpha when the actual value is y_i """ return predict(alpha, beta, x_i) - y_i from scratch.linear_algebra import Vector def sum_of_sqerrors(alpha: float, beta: float, x: Vector, y: Vector) -> float: return sum(error(alpha, beta, x_i, y_i) ** 2 for x_i, y_i in zip(x, y)) from typing import Tuple from scratch.linear_algebra import Vector from scratch.statistics import correlation, standard_deviation, mean def least_squares_fit(x: Vector, y: Vector) -> Tuple[float, float]: """ Given two vectors x and y, find the least-squares values of alpha and beta """ beta = correlation(x, y) * standard_deviation(y) / standard_deviation(x) alpha = mean(y) - beta * mean(x) return alpha, beta x = [i for i in range(-100, 110, 10)] y = [3 * i - 5 for i in x] # Should find that y = 3x - 5 assert least_squares_fit(x, y) == (-5, 3) from scratch.statistics import num_friends_good, daily_minutes_good alpha, beta = least_squares_fit(num_friends_good, daily_minutes_good) assert 22.9 < alpha < 23.0 assert 0.9 < beta < 0.905 from scratch.statistics import de_mean def total_sum_of_squares(y: Vector) -> float: """the total squared variation of y_i's from their mean""" return sum(v ** 2 for v in de_mean(y)) def r_squared(alpha: float, beta: float, x: Vector, y: Vector) -> float: """ the fraction of variation in y captured by the model, which equals 1 - the fraction of variation in y not captured by the model """ return 1.0 - (sum_of_sqerrors(alpha, beta, x, y) / total_sum_of_squares(y)) rsq = r_squared(alpha, beta, num_friends_good, daily_minutes_good) assert 0.328 < rsq < 0.330 def main(): import random import tqdm from scratch.gradient_descent import gradient_step num_epochs = 10000 random.seed(0) guess = [random.random(), random.random()] # choose random value to start learning_rate = 0.00001 with tqdm.trange(num_epochs) as t: for _ in t: alpha, beta = guess # Partial derivative of loss with respect to alpha grad_a = sum(2 * error(alpha, beta, x_i, y_i) for x_i, y_i in zip(num_friends_good, daily_minutes_good)) # Partial derivative of loss with respect to beta grad_b = sum(2 * error(alpha, beta, x_i, y_i) * x_i for x_i, y_i in zip(num_friends_good, daily_minutes_good)) # Compute loss to stick in the tqdm description loss = sum_of_sqerrors(alpha, beta, num_friends_good, daily_minutes_good) t.set_description(f"loss: {loss:.3f}") # Finally, update the guess guess = gradient_step(guess, [grad_a, grad_b], -learning_rate) # We should get pretty much the same results: alpha, beta = guess assert 22.9 < alpha < 23.0 assert 0.9 < beta < 0.905 if __name__ == "__main__": main()
52932753322af66b2837825e7012181a39bf56fe
LearnDreamCode/Python
/for_while_loop.py
1,013
3.984375
4
# -*- coding: utf-8 -*- """ Created on Tue Jul 27 06:10:26 2021 @author: kalai """ #for loop is iretation based # range(<start>,<stop>,<step>) # start and step are optionnal and the default values are 0 and 1 respectively # num_list = [0,10,200,3000,40000] # for num in num_list: # num *= num # print(num) # for num in range(len(num_list)): # print(f'square of index {num} is {num_list[num]*num_list[num]}') # #Iteration on range function # for i in range(0,20,5): # n = i*i # print (f'square of {i} is {n}') #while loop # x=1 # while x<10: # if x%2: # print (f'{x} is an odd number') # else: # print(f'{x} is a even number'); # x += 1 # else: # print('All elements/numbers were verified') x=-3 while x<10: if x<0: x+=1 continue if x==8: break if x%2: print (f'{x} is an odd number') else: print(f'{x} is a even number'); x += 1 else: print('All elements/numbers were verified')
e6bbe92ecd3a9ac0966e3f9aecd907178a6b5c63
LearnDreamCode/Python
/Find_index_a.py
390
3.65625
4
# -*- coding: utf-8 -*- """ Created on Mon Aug 2 06:16:27 2021 @author: kalai """ magic_word = 'abracadabra' search_str = 'a' start_pos=0 iteration_count=len(magic_word)-len(magic_word.replace('a', '') ) for i in range(iteration_count): start_pos=magic_word.index(search_str,start_pos) print('a is present at the position ',start_pos) start_pos+=1 print('sreach completed')
778ddbbe8fb9c307c2d59218d7ff01f318d79636
LearnDreamCode/Python
/repeated_charcters.py
793
3.90625
4
# -*- coding: utf-8 -*- """ Created on Mon Aug 2 06:44:20 2021 @author: kalai """ # Q3: # o4 e3 u2 h2 r2 t2 # print the repeated characters in a string. # Sample string: 'the quick brown fox jumps over the lazy dog' # Expected output : o4 e3 u2 h2 r2 t2 input_string= 'the quick brown fox jumps over the lazy dog' s_string = set(input_string) #print(s_string) opt_string='' opt_string_sort='' for i in s_string: char_count = input_string.count(i) if i != ' ' and char_count>1: #len(input_string)-len(input_string.replace(i, '')) > 1: opt_string+=str(char_count)+i+' ' list_opt_string=opt_string.split() list_opt_string.sort(reverse=True) # print(list_opt_string) for i in list_opt_string: opt_string_sort+=' '+i[::-1] print(opt_string_sort.lstrip())
612d6ac158e726eafc396a65c515f048d053aa25
LearnDreamCode/Python
/ex1_q3_2characters.py
557
3.828125
4
# -*- coding: utf-8 -*- """ Created on Mon Aug 2 15:03:24 2021 @author: kalai """ # Q3: Write a Python program to get a string made of the first 2 and the # last 2 chars from a given a string. If the string length is less than 2, # return an empty string, for example, if: # sample_string = "abcdefghij", the expected_output = "abij" # sample_string = "ab", the expected_output = "abab" # sample_string = "a", the expected_output = "" i_string = input('Enter a string: ') if len(i_string)>=2: print(i_string[:2]+i_string[-2:]) else: print('')
7fa64bd1facdd7be31696a26f8239536e43a93d6
LearnDreamCode/Python
/generate_pwd.py
2,266
3.6875
4
# -*- coding: utf-8 -*- """ Created on Wed Jul 28 06:22:48 2021 @author: kalai """ # Q: Generate a password of 8 characters long # - one of them should be upper case # - one of them should be numeric # - one of them should be a special character import random # numList = [random.randint(0, 10)] # print('int',numList) # numList = [random.randrange(0, 10, 3)] # print('range',numList) low_case = ''.join([chr(int(random.randint(97,122))) for i in range(0,3)]) num = chr(random.randint(48,57)) up_case = chr(random.randint(65,90)) special_char = chr(random.randint(33,47)) low_case2 = ''.join([chr(int(random.randint(97,122))) for i in range(2)]) temporary_pwd = low_case+num+up_case+special_char+low_case2 print(f'Your temporary password is {temporary_pwd}') import random # numList = [random.randint(0, 10)] # print('int',numList) # numList = [random.randrange(0, 10, 3)] # print('range',numList) #lower case pwd = [chr(random.randint(97,122)) for i in range(3)] #number pwd.append(chr(random.randint(48,57))) #uppper case pwd.append(chr(random.randint(65,90))) #Special Character pwd.append(chr(random.randint(33,47))) temporary_pwd = ''.join(pwd+[chr(random.randint(97,122)) for i in range(2)]) print(f'Your temporary password is {temporary_pwd}') import random #lower case pwd = ''.join([chr(random.randint(97,122)) for i in range(3)]) #number pwd+=(chr(random.randint(48,57))) #uppper case pwd+=(chr(random.randint(65,90))) #Special Character pwd+=(chr(random.randint(33,47))) temporary_pwd = pwd+''.join([chr(random.randint(97,122)) for i in range(2)]) print(temporary_pwd) import random #lower case pwd='' for i in range(5): # not sure whether I could replace this with map pwd+= chr(random.randint(97,122)) #number pwd+=(chr(random.randint(48,57))) #uppper case pwd+=(chr(random.randint(65,90))) #Special Character pwd+=(chr(random.randint(33,47))) print(pwd) import random #lower case pwd='' for i in range(8): if i==2: #number pwd+=(chr(random.randint(48,57))) continue if i==4: #uppper case pwd+=(chr(random.randint(65,90))) continue if i==6: #Special Character pwd+=(chr(random.randint(33,47))) continue pwd+= chr(random.randint(97,122)) print(pwd)
c4a153490c7f2e6b1d87dc01b9feace934b33d3e
deep-scribe/handwriting-recognition
/src/rc.py
2,814
3.6875
4
""" The code to generate the risk-coverage curve given the model and the test data. It is assumed that the model is implemented using pytorch Usage: $ python >>> import rc >>> rc.draw_curve(model, input_data) # png file saved to the current directory """ import numpy as np import matplotlib.pyplot as plt def draw_curve(confidence, prediction, label, output_dir='.'): ''' generate the risk coverage curve and save png file to output_dir @param: confidence (Tensor): confidence.shape = (n,) @param: prediction (Tensor): prediction.shape = (n,) @param: label (Tensor): label.shape = (n,) @return: None ''' confidence, prediction, label = confidence.numpy(), prediction.numpy(), label.numpy() correctness = (prediction - label) == 0 zipped = zip(confidence, prediction, label, correctness) sorted_res = sorted(zipped, key=lambda x: x[0], reverse=True) risk = [] coverage = [] mistake_count = 0 curr_count = 0 total_count = len(label) for conf, pred, lab, correct in sorted_res[:1000]: curr_count += 1 if correct == False: mistake_count += 1 risk.append(mistake_count * 1.0 / curr_count) coverage.append(curr_count * 1.0 / total_count) fig, ax = plt.subplots() line1, = ax.plot(coverage, risk, label="risk-coverage curve") ax.fill_between(coverage, risk, alpha=0.5) ax.legend() plt.show() def example(): ''' In terminal, run {python rc.py path_to_model path_to_testdata} ''' # if len(sys.argv) != 2: # print('Usage: python data_flatten.py <subject_path>') # quit() # subject_path = sys.argv[1] # import rnn_bilstm import rnn_bilstm import torch import data_loader import pandas as pd from sklearn.metrics import confusion_matrix import string trainx, devx, testx, trainy, devy, testy = data_loader.load_all_classic_random_split( resampled=True, flatten=False) print(testy.shape) BATCH_SIZE = 1050 testloader = rnn_bilstm.get_dataloader(testx, testy, BATCH_SIZE) net = rnn_bilstm.get_net( "../saved_model/rnn_bilstm/rnn_bilstm_random_resampled_0.pth") print(rnn_bilstm.acc(net, testloader)) input, label = next(iter(testloader)) logit = rnn_bilstm.get_prob(net, input) confidence, prediction = torch.max(logit.data, 1) draw_curve(confidence + 1, prediction, label) # print(logit) # _, predicted = torch.max(logit.data, 1) # print(torch.sum((predicted - label) == 0).item()/len(label)) # print(predicted) # cm = confusion_matrix(label, predicted) # index = list(string.ascii_uppercase) # df = pd.DataFrame(data=cm, index=index, columns=index) # print(df) if __name__ == "__main__": example()
01ce27d5d65b55566cccded488d1c99d2fd848b0
dablackwood/my_scripts_project_euler
/specific_solutions/project_euler_019.py
1,079
4.1875
4
""" You are given the following information, but you may prefer to do some research for yourself. * 1 Jan 1900 was a Monday. * Thirty days has September, April, June and November. All the rest have thirty-one, Saving February alone, Which has twenty-eight, rain or shine. And on leap years, twenty-nine. * A leap year occurs on any year evenly divisible by 4, but not on a century unless it is divisible by 400. How many Sundays fell on the first of the month during the twentieth century (1 Jan 1901 to 31 Dec 2000)? """ day = 2 tally = 0 months_common = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] months_leap = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] for year in xrange(1901, 2001): #print print year, if year % 4 == 0: months_current = months_leap else: months_current = months_common for month in xrange(0, 12): #print day, day % 7, if day % 7 == 0: tally = tally + 1 day = day + months_current[month] print tally print "*", tally
f8b7c76ef696215141cce020ad7a7d89f702aacc
dablackwood/my_scripts_project_euler
/specific_solutions/project_euler_046.py
1,716
3.921875
4
""" It was proposed by Christian Goldbach that every odd composite number can be written as the sum of a prime and twice a square. 9 = 7 + 2x1^(2) 15 = 7 + 2x2^(2) 21 = 3 + 2x3^(2) 25 = 7 + 2x3^(2) 27 = 19 + 2x2^(2) 33 = 31 + 2x1^(2) It turns out that the conjecture was false. What is the smallest odd composite that cannot be written as the sum of a prime and twice a square? """ import time def prime_list(set_limit): #factors = [-1, -1] + [0] * (set_limit - 1) for index in xrange(2, set_limit): # skip 0, 1 & last number if factors[index] == 0: # if index is prime multiple = 2 * index while multiple <= set_limit: factors[multiple] += 1 # for each multiple of the prime multiple += index #print factors #primes = [] #for index2 in xrange(len(factors)): # if factors[index2] == 0: # primes.append(index2) #return primes def goldbach_check(n): # True if odd composite = some prime + 2n^2 max_k = int((n / 2) ** 0.5) for k in xrange(1, max_k + 1): if factors[n - 2*k**2] == 0: #print n, "=", n - 2*k**2, "+ 2* " + str(k) + "^2" return True return False set_limit = input("What is the limit of primes to be generated: ") t1 = time.time() factors = [-1, -1] + [0] * (set_limit - 1) prime_list(set_limit) #print goldbach_check(9), goldbach_check(25), goldbach_check(33) index = 9 # the 1st odd composite while True: if factors[index] > 0 and goldbach_check(index) is False: # if composite print "answer", index break index += 2 # next odd no. - only odd composites need to be checked print time.time() - t1
159b7422dc21ca5c01cec91b1c27ee3a88b08ca1
dablackwood/my_scripts_project_euler
/specific_solutions/project_euler_029a.py
759
4.15625
4
""" Consider all integer combinations of a^(b) for 2<=a<=5 and 2<=b<=5: 2^(2)=4, 2^(3)=8, 2^(4)=16, 2^(5)=32 3^(2)=9, 3^(3)=27, 3^(4)=81, 3^(5)=243 4^(2)=16, 4^(3)=64, 4^(4)=256, 4^(5)=1024 5^(2)=25, 5^(3)=125, 5^(4)=625, 5^(5)=3125 If they are then placed in numerical order, with any repeats removed, we get the following sequence of 15 distinct terms: 4, 8, 9, 16, 25, 27, 32, 64, 81, 125, 243, 256, 625, 1024, 3125 How many distinct terms are in the sequence generated by a^(b) for 2<=a<=100 and 2<=b<=100? """ max_a_b = input("Max for 'a' and 'b': ") big_list = [] for a in xrange(2, max_a_b + 1): for b in xrange(2, max_a_b + 1): if big_list.count(a ** b) == 0: big_list.append(a ** b) print len(big_list)
c82c4d48f19a55298f5dce09cca394ea676114e8
dablackwood/my_scripts_project_euler
/specific_solutions/project_euler_027.py
2,122
3.703125
4
""" Find the product of the coefficients, a and b, for the quadratic expression that produces the maximum number of primes for consecutive values of n, starting with n = 0. n^2 + an + b, abs(a) < 1000, abs(b) < 1000 """ def is_prime(n): if n in prime_list: return True elif n < 0: return False check = 2 if n % check == 0 and n != 2: return False check = 3 stop = int(n ** .5) while check <= stop: if n % check == 0: return False check = check + 2 return True def add_from_wheel(limit): n = 7 while n <= limit: prime_list.append(n) n = n + 4 prime_list.append(n) n = n + 2 def sieve(list): # set the limit for numbers to test with max_tester = list[len(list) - 1] ** 0.5 # start with 5, since all multiples of 2 & 3 were not included by the wheel tester_index = 2 tested_index = 3 while list[tester_index] <= max_tester: # test all members of list to see if divisible by list[tester_index] # start with the item following tester_index tested_index = tester_index + 1 while tested_index <= len(list) - 1: if list[tested_index] % list[tester_index] == 0: del list[tested_index] else: tested_index = tested_index + 1 tester_index = tester_index + 1 def trim_end(limit, list): while limit < list[len(list) - 1]: del list[len(list) - 1] # !!! get set_limit from the program that calls this one. def evaluate(a, b, n): return (n ** 2) + (a * n) + b def num_consecutive(a, b): n = 1 while is_prime(evaluate(a, b, n)): #print a, b, n, evaluate(a, b, n), is_prime(evaluate(a, b, n)) n += 1 return n prime_list = [2,3,5] set_limit = 1000 add_from_wheel(set_limit) trim_end(set_limit, prime_list) sieve(prime_list) b_list = prime_list[:] best = (0, 0, 0) for b in b_list: for a in xrange(-999, 1000): consecutive = num_consecutive(a, b) if consecutive > best[2]: best = (a, b, consecutive) print best
4f9bf7956310ee9dd9ea90c99ce45a3534a0e2ff
dablackwood/my_scripts_project_euler
/specific_solutions/project_euler_037a.py
2,320
4
4
""" The number 3797 has an interesting property. Being prime itself, it is possible to continuously remove digits from left to right, and remain prime at each stage: 3797, 797, 97, and 7. Similarly we can work from right to left: 3797, 379, 37, and 3. Find the sum of the only eleven primes that are both truncatable from left to right and right to left. NOTE: 2, 3, 5, and 7 are not considered to be truncatable primes. """ import time def add_from_wheel(limit): for n in xrange(6, limit, 6): prime_list.append(n - 1) prime_list.append(n + 1) if prime_list[-1] > limit: del prime_list[-1] def sieve(prime_list): # set the limit for numbers to test with max_tester = prime_list[-1] ** 0.5 # start with 5, since all multiples of 2 & 3 were not included by the wheel tester_index = 2 tested_index = 3 while prime_list[tester_index] <= max_tester: # test all members of list to see if divisible by list[tester_index] # start with the item following tester_index tested_index = tester_index + 1 while tested_index <= len(prime_list) - 1: if prime_list[tested_index] % prime_list[tester_index] == 0: del prime_list[tested_index] else: tested_index = tested_index + 1 tester_index = tester_index + 1 def check_truncations(n): if len(str(n)) > 2: if str(n)[0] != '2' and \ str(n)[0] != '3' and \ str(n)[0] != '5' and \ str(n)[0] != '7': return False elif str(n)[-1] != '3' and \ str(n)[-1] != '7': return False scratch = n length = len(str(n)) while scratch > 9: scratch /= 10 if scratch not in prime_list: return False while n > 9: n = int(str(n)[1:]) if n not in prime_list: return False return True #set_limit = input("What is the limit of primes to be generated: ") t1 = time.time() good2go = [] set_limit = 1000000 prime_list = [2, 3] add_from_wheel(set_limit) sieve(prime_list) print "sieved", len(prime_list), time.time() - t1 roll = prime_list[4:] for check in roll: if check_truncations(check): good2go.append(check) print good2go, len(good2go) print time.time() - t1
0858af55a19ec262d3dc7bd9d8c6b72ff28153c3
dablackwood/my_scripts_project_euler
/specific_solutions/project_euler_028.py
456
3.5625
4
""" Starting with the number 1 and moving to the right in a clockwise direction a 5 by 5 spiral is formed as follows: 21 22 23 24 25 20 7 8 9 10 19 6 1 2 11 18 5 4 3 12 17 16 15 14 13 It can be verified that the sum of both diagonals is 101. What is the sum of both diagonals in a 1001 by 1001 spiral formed in the same way? """ tally = 0 for n in xrange(1, 1002): tally = tally + (n * n) tally = 2 * tally - 1 + 500 - 500500 print tally
099c512c463ddfa211338eea98842567cbb5b43a
dablackwood/my_scripts_project_euler
/specific_solutions/project_euler_056.py
472
3.890625
4
""" Considering natural numbers of the form, a^b, where a and b < 100, what is the maximum digital sum? """ import time t1 = time.time() def digit_sum(n): tally = 0 for digit in str(n): tally += int(digit) return tally max_sum = 0 for a in xrange(1, 100): if a % 10 != 0: for b in xrange(1, 100): tally = digit_sum(a**b) if tally > max_sum: max_sum = tally print max_sum print time.time() - t1
c141565f89ce702eaa419f11c5627325475147a2
claudiugroza/msa
/a-02/a_05.py
456
3.921875
4
#!/usr/bin/python # Write a new script that takes three arguments as input. # The program should execute sequences of LED pulses using the previous given configuration: # the first argument is the number of pulses contained by one sequence, # the second argument is the interval (in seconds) between two pulses in a sequence # and the third argument is the pause period (in seconds) between two consecutive sequences. import sys import RPi.GPIO as GPIO
26e8ab97f958a339586216bd10d7488a5791b2e0
NinahMo/lock-in
/user.py
897
3.78125
4
class User: user_list = [] def __init__(self,full_name,login_name,email,password_value): ''' Here we call ana array which has the login information and what is needed for the login. ''' self.full_name = full_name self.login_name = login_name self.email = email self.password_value = password_value def save_user(self): ''' this allows you to save your login information ''' User.user_list.append(self) @classmethod def user_authenticate(cls,loginname,passcode): ''' this allows authentication of the the users information before allowing access. ''' for user in cls.user_list: if user.login_name == loginname and user.password_value == passcode: return True return False #pass
0368c583e2098cfdff1da61e00c0f7e997a42120
shaziya21/PYTHON
/static_methods.py
386
3.65625
4
class student: school = "telusko" def __init__(self,m1,m2,m3): self.m1 = m1 self.m2 = m2 self.m3 = m3 def avg(self): return(self.m1 + self.m2 + self.m3)/3 @staticmethod def info(): print('this is a student class.. in abc mmodule') s1 = student(12,43,76) s2 = student(32,54,15) print(s1.avg()) student.info()
627e26b857e77b466da042acef1737e3d0816d1e
shaziya21/PYTHON
/zip.py
349
4.25
4
# if we want to join two list or tuple or set or dict we'll use zip names = ('shaz','naaz','chiku') comps = ('apple','hp','asus') zipped = list(zip(names,comps)) print(zipped) # or we can use loop to iterate like names = ('shaz','naaz','chiku') comps = ('apple','hp','asus') zipped = list(zip(names,comps)) for (a,b) in zipped: print(a,b)
56645c2bf5af3de091280d873c5ccf0a45a19201
shaziya21/PYTHON
/instance_method.py
604
3.8125
4
class student: school = "telusko" def __init__(self,m1,m2,m3): self.m1 = m1 self.m2 = m2 self.m3 = m3 def avg(self): return(self.m1 + self.m2 + self.m3)/3 def get_m1(self): #getter return self.m1,self.m2,self.m3 def set_m1(self,a,b,c): self.m1 =a self.m2=b self.m3 =c return self.m1+self.m2+self.m3 #setter s1 = student(12,43,76) # s1 = student(m1,m2,m3) s2 = student(32,54,15) s3 = student(322,544,115) s1.set_m1(12,1,2) s1.set_m1(12,12,12) # two types of instance method : accessors and mutators
5ce1f734f8785fd51730ec0f34e62e59c4a45a2c
shaziya21/PYTHON
/pali.py
907
3.96875
4
def count(lst): even = 0 odd = 0 for i in lst: if i%2==0: even+=1 else: odd+=1 return even,odd lst=[20,25,14,19,16,24,28,47,26] even,odd = count(lst) print(even) print(odd) print(type(even)) ###################################### def count(lst): even = 0 odd = 0 for i in lst: if i%2==0: even+=1 else: odd+=1 return even,odd lst=[20,25,14,19,16,24,28,47,26] even,odd = count(lst) print('even : {} and odd : {}' .format(even,odd)) # format() method formats the specified #value(s) and insert them inside the string's placeholder. # QUES : Take 10 names from the user and then count and display the no of users who has len more thn 5 letters names= int(input('enter the names of users')) count+=1 for i in names: if length>=5 print(names) else: print('not found')
68a88b204fc3ee4e82f5d493be81f5de27f61fb9
shaziya21/PYTHON
/linear_search.py
865
3.6875
4
pos = -1 def search(list,n): i = 0 while i < len(list): if list[i] == n: globals()['pos'] = i return True i = i + 1 return False list = [2,3,4,5,6,7,9] n = 2 if search(list,n): print('found at', pos) else: print('not found') # ------------------------------------------------------- # using for loop list=[4,3,12,34,56,77,89] n=int(input('enter a number')) for i in range(len(list)): if list[i]==n: print('found at pos',i+1) break else: print('not found') # --------------------------------------------------------- # Using for loop code: pos = -1 def search(list, n): for i in range(len(list)): if list[i]==n: globals()['pos'] = i return True return False list = [5,8,4,6,9,2] n = 9 if search(list, n): print("Found at ",pos+1) else: print("Not Found")
73980da3c813213a81f11db877458ff72c0a47b7
shaziya21/PYTHON
/constructor_in_inheritance.py
732
4.1875
4
class A: # Parent class / Super class def __init__(self): # Constructor of parent class A print("in A init") def feature1(self): print("feature1 is working") def feature2(self): print("feature2 is working") class B(A): def __init__(self): super().__init__() # jump up to super class A executes it thn jump back to B and thn execute it. print("in B init") def feature3(self): print("feature3 is working") def feature4(self): print("feature4 is working") a1 = B() # when you create object of sub class it will call init of sub class first. # if you have ccall super then it will first call init of super class thn call init of sub class.
6ffafcc1da316699df44275889ffab8ba957265f
shaziya21/PYTHON
/MRO.py
1,004
4.4375
4
class A: # Parent class / Super class def __init__(self): # Constructor of parent class A print("in A init") def feature1(self): print("feature 1-A is working") def feature2(self): print("feature2 is working") class B: def __init__(self): # Constructor of class B print("in B init") def feature1(self): print("feature 1-B is working") def feature4(self): print("feature4 is working") class C(A,B): # C is inheriting both from A & B def __init__(self): super().__init__() # Constructor of parent class A print("in C init") def feature5(self): print("feature5 is working") def feat(self): super().feature2() # super method is used to call other method as well not just init a1 = C() # it will give output for C & A only coz in multiple inheritance a1.feature1() # it starts from left to right a1.feat() # to represent super class we use super method.
1e870f6429ff8f0b0cde4f40b7d0f3e148242257
JoshiDivya/PythonExam
/Pelindrome.py
354
4.3125
4
def is_pelindrome(word): word=word.lower() word1=word new_str='' while len(word1)>0: new_str=new_str+ word1[-1] word1=word1[:-1] print(new_str) if (new_str== word): return True else: return False if is_pelindrome(input("Enter String >>>")): print("yes,this is pelindrome") else: print("Sorry,this is not pelindrome")
dde0ef91117d5b96b9822b4be184133f84ccb59b
abalasky/algorithms
/dp/knapsack.py
1,990
3.875
4
""" Dynamic programming solution to 0/1 knapsack """ import numpy as np def knapsack(items, weight): """ Maximizes value of items given a weight limit """ #Init DP Table x: 0->items y: 0 ->weight opt = np.zeros((len(items)+1, weight+1), dtype = int) #Fill out base cases i.e. first row/first column for w in range(weight+1): opt[0][w] = 0 for i in range(1,len(items)+1): for w in range(weight+1): if items[i-1][1] > w: opt[i][w] = opt[i-1][w] else: opt[i][w] = max( opt[i-1][w], items[i-1][2] + opt[i-1][w-items[i-1][1]] ) print(opt) #Find optimal solution knapsackItems = [] currWeight = weight currItem = len(items) for i in range(len(items)): if opt[currItem][w] == opt[currItem-1][currWeight]: currItem -= 1 continue weightNew = currWeight - items[currItem][1] if opt[currItem][w] - items[currItem][1] == opt[currItem-1][weightNew]: knapsackItems.append(items[0][0]) currItem -= 1 currWeight -= items[currItem][1] print(knapsackItems) return opt[len(items)][weight] def main(): #List of tuples itemName-weight-value items = [ ("map", 9, 150), ("compass", 13, 35), ("water", 153, 200), ("sandwich", 50, 160), ("glucose", 15, 60), ("tin", 68, 45), ("banana", 27, 60), ("apple", 39, 40), ("cheese", 23, 30), ("beer", 52, 10), ("suntan cream", 11, 70), ("camera", 32, 30), ("t-shirt", 24, 15), ("trousers", 48, 10), ("umbrella", 73, 40), ("waterproof trousers", 42, 70), ("waterproof overclothes", 43, 75), ("note-case", 22, 80), ("sunglasses", 7, 20), ("towel", 18, 12), ("socks", 4, 50), ("book", 30, 10), ] value = knapsack(items,400) print('Knapsack returned:', value) if __name__ == '__main__': main()
6c96de768cdd8d50ee6a8e2fc2f9f1a92afb40ba
S8A/voting-simulator
/voting-simulator/result.py
2,243
3.65625
4
# coding=utf-8 """Each election result records the voting system used, counts, winners, etc.""" from .utils import sort_dict_desc, make_table class ElectionResult: def __init__(self, voting_system, counts, winners, count_type='Votes', percent_column=True, details=[]): """Creates an election result with the given information. Args: voting_system: Name of the voting system used. counts: Dictionary mapping candidates to final counts. winners: List of winning candidates. count_type: Type of count data: Votes, Score, Points, Wins, etc. percent_column: Indicates if the results table should have a percent column. details: List of text strings with details about the election. """ self.voting_system = voting_system self.counts = counts self.winners = winners self.count_type = count_type self.percent_column = percent_column self.details = details def __repr__(self): """Returns a string representation of the election result.""" return f'Election Result ({self.voting_system})' def summary(self): """Returns a summary of the election result.""" summary = [f'Election Result :: {self.voting_system} :.\n'] summary.extend(self.details) summary.append('\nFinal counts:') summary.extend(self.counts_table()) summary.append('\nWinner(s):') for winner in self.winners: summary.append(str(winner)) return '\n'.join(summary) def counts_table(self): """Sorts counts and converts them into a text table.""" widths = [20, 20] header = ['Candidate', self.count_type] total = sum(list(self.counts.values())) sorted_counts = sort_dict_desc(self.counts) body = [[candidate, count] for candidate, count in sorted_counts] if self.percent_column: widths.append(10) header.append('Percent') for row in body: percent = 100.0 * row[1] / total row.append(f'{percent :.2f}%') return make_table(widths, header, body)
08f0a1f3b617dc4ec04d2c46f0690fb75a9f9711
RugeljGG/AdventOfCode
/2019/day1.py
663
3.5625
4
# -*- coding: utf-8 -*- """ Created on Sun Dec 1 09:54:54 2019 @author: gape """ def task1(): with open('day1.txt') as file: total = 0 for row in file: w = int(row) total += (w / 3) // 1 - 2 print('Task 1 result: ', total) def task2(): with open('day1.txt') as file: total = 0 for row in file: w = int(row) f = w while True: f1 = (f / 3) // 1 - 2 if f1 >= 0: f = f1 total += f1 else: break print('Task 2 result: ', total)
2dd93300d7ede7b2fd78a925eeea3d912ae55c51
dhaffner/pycon-africa
/example1.py
408
4.53125
5
# Example #1: Currying with inner functions # Given a function, f(x, y)... def f(x, y): return x ** 2 + y ** 2 # ...currying constructs a new function, h(x), that takes an argument # from X and returns a function that maps Y to Z. # # f(x, y) = h(x)(y) # def h(x): def curried(y): return f(x, y) return curried fix10 = h(10) for y in range(10): print(f'fix10({y}) = {fix10(y)}')
6fe75095725512cb6f19b389882d0cd32558ca4d
Joaoflavo/codigos-de-treino
/aula3 operadores logicos.py
639
4.09375
4
#programa de treino feito para aprender a usar operadores lógicos #programa desenvolvido por: João Flavo J°@°2@2@ 14-10-2020 03:14 AM print ('Escolha uma opção e descubra o que acontece') print('Menu:\n1 = Escolha Guilherme: \n2 = Escolha João:\n3 = Escolha Maria:') opcao = input('Escolha uma opção do menu:') if opcao == '1': print('Guilherme é um anjo brother!') elif opcao == '2': print('João vc é muito louco brother!') elif opcao == '3': print('Maria vc e ruim vai é pro inferno') else: print('Vc não quer saber sobre ninguem, esta opção é invalida , Por favor, reinicie o programa!')
76e613510e58653a02ff08a4821f357b8dfd1d22
diptijadhav1999/Pattern
/number.py
134
3.5
4
#1111 #2222 #3333 #4444 n=int(input()) for i in range(1,n+1): for j in range(1,n+1): print(i,end="") print()
7447eb932ce829288aa0ce3491b07e049733d552
liweisunny/InterviewQuestions
/4.单列模式.py
391
3.640625
4
#__author:liwei #date:2017/2/23 # 使用 __new__()方法实现 class Singleton(object): def __new__(cls, *args, **kw): if not hasattr(cls, '_instance'): orig = super(Singleton, cls) cls._instance = orig.__new__(cls, *args, **kw) return cls._instance class MyClass(Singleton): a=1 cls=MyClass() cls2=MyClass() print(id(cls)) print(id(cls2))
8a70aebde7d72dfaca31b9223863e3ba14415acf
cpe202fall2018/lab0-loogyboy
/planets.py
655
4
4
# #Name: Peter Moe-Lange #Student ID: 014335967 #Date (Last Modified): September 23th # #Lab 0 #Section 13 #Purpose of Lab: intro/warm up to python and github #additional comments: in this program I prompt the user for an input which then format. after this I take the input and multiply it by the constant and the print it in a formatted string. def weight_on_planets(): e_weight = float(input("What do you weigh on earth? ")) m_weight = e_weight * 0.38 j_weight = e_weight * 2.34 print("\nOn Mars you would weigh %.2f pounds.\nOn Jupiter you would weigh %.2f pounds." % (m_weight, j_weight)) if __name__ == '__main__': weight_on_planets()
dafb3e2d94649cf1f7a26a0a5930f640529ae88a
vbelousPy/py_base
/Lesson_04/fourth/main.py
215
3.90625
4
myList = list() while True: try: n = input("Input number: ") if len(n) == 0: break myList.append(float(n)) except ValueError: print("Invalid value") print(myList)
96a3983fba2043c726e287e809ed03614f7ae037
vbelousPy/py_base
/Lesson_02/1.py
342
3.984375
4
import math a = int(input("Enter a: ")) b = int(input("Enter b: ")) c = int(input("Enter c: ")) d = b ** 2 - 4 * a * c if d < 0: print("The result is a complex value") else: if d == 0: print("x =", (-b / 2 * a)) else: print("x1 =", (-b - math.sqrt(d)) / 2 * a) print("x2 =", (-b + math.sqrt(d)) / 2 * a)
383a51887fc50cf85359feb303af2e5a8a268245
vbelousPy/py_base
/Lesson_03/5.py
792
3.6875
4
length = int(input("Enter length: ")) t = int(input("Select type (1-4): ")) result = str() if t == 1: i = 0 while i < length: temp = "".ljust(length - i, "*") temp = temp.ljust(length, " ") result += temp + "\n" i += 1 elif t == 2: i = length - 1 while i >= 0: temp = "".ljust(length - i, "*") temp = temp.ljust(length, " ") result += temp + "\n" i -= 1 elif t == 3: i = 1 while i <= length: temp = "".ljust(length - i, " ") temp = temp.ljust(length, "*") result += temp + "\n" i += 1 elif t == 4: i = length while i >= 0: temp = "".ljust(length - i, " ") temp = temp.ljust(length, "*") result += temp + "\n" i -= 1 print(result)
aa5cd6b20b24b8c70cb89851eb573c18ae3fed90
vbelousPy/py_base
/Lesson_05/3.py
277
3.90625
4
def foo(n): if n == 0: return 0 elif n == 1: return 1 else: return foo(n - 1) + foo(n - 2) try: print("result =", foo(int(input("Enter a number greater than zero: ")))) except (RecursionError, ValueError): print("Incorrect value")
d50179cb3e7e9f91a92a310ceaa1ce4b035dadb3
vbelousPy/py_base
/Lesson_03/3.py
161
3.9375
4
cortege = tuple() while True: text = input("Input text: ") if len(text) == 0: break else: cortege = cortege + (text,) print(cortege)
f05722b55357f9116b536e2e110e1b4b35769fa4
korymath/talk-generator
/talkgenerator/util/random_util.py
509
3.78125
4
import random # From https://stackoverflow.com/questions/14992521/python-weighted-random def weighted_random(pairs): if len(pairs) == 0: return None total = sum(pair[0] for pair in pairs) r = random.uniform(0, total) for (weight, value) in pairs: r -= weight if r <= 0: return value def choice_optional(lst): """" Returns random.choice if there are elements, None otherwise """ if len(lst) > 0: return random.choice(lst) return None
22b54ee1f842906a09ce8408a788d1c8819f25a8
javier-ls/PracticasTeoriadelaComputacion
/expresiones regulares/101.py
201
3.6875
4
import re expresion = r'(1)(0)(1)' resultado = re.compile(expresion) prueba = raw_input("entrada: ") busqueda = re.search(resultado,prueba) if busqueda: print busqueda.group() else: print "qr"
bc596e74392c23e4fb099068b6d0929ba02aa830
Yaambs18/python-bootcamp
/Dockerfiles/Second_image/perfect_num.py
281
3.703125
4
def perfect_num(num): sum = 0 for i in range(1,num): if num%i==0: sum+=i if sum==num: return f"The {num} is perfect number." return f"The {num} is not a perfect number." n = int(input("Enter a number :")) print(perfect_num(n))
b86300067afe20ac6d3661a4d8a6b85446b57512
Yaambs18/python-bootcamp
/Day3/Ineheritance.py
1,251
4.15625
4
#Multilevel Inheritance class Base(): def __init__(self, name): self.name = name def getName(self): return self.name class Child(Base): def __init__(self, name, age): Base.__init__(self, name) self.age = age def getAge(self): return self.age class GrandChild(Child): def __init__(self, name, age, address): Child.__init__(self, name, age) self.address = address def getAddress(self): return self.address m = GrandChild("Yansh", 1, "Aligarh") print(m.getName(), m.getAge(), m.getAddress()) #Mutiple inheritance class Addition(): def __init__(self): print("addition") def Addition(self,a,b): return a+b; def func(self): print("this method is of addition class") class Mulultiplication(): def __init__(self): print("multiplication") def Multiplication(self,a,b): return a*b def m1(self): print("this method is of multipication class") class Division(Addition, Mulultiplication): def __init__(self): print("divide") def Divide(self,a,b): return a/b; divide_ = Division() print(divide_.Addition(10,20)) print(divide_.Multiplication(10,20)) print(divide_.Divide(10,20)) divide_.m1()
da75875b647a9673efb113e14ebd237cd4e4d1fa
Yaambs18/python-bootcamp
/Day4/line_class_test.py
560
3.546875
4
import unittest import line_class class Test_Dist_slope(unittest.TestCase): def test_distance(self): coordinate1 = (3,2) coordinate2 = (8,10) obj = line_class.Line(coordinate1,coordinate2) result = obj.distance() self.assertEqual(result, 9.433981132056603) def test_slope(self): coordinate1 = (3,2) coordinate2 = (8,10) obj = line_class.Line(coordinate1,coordinate2) result = obj.slope() self.assertEqual(result, 1.6) if __name__ == '__main__': unittest.main()
84239ec9ebda1d612b73379e7cb439fb8f4f857c
kgarrison343/Randomizer
/Main.py
814
3.75
4
from RandomChoice import choose_randomly from os import listdir def list_files(files: list): print("What file would you like to choose from?") for i, file in enumerate(files): print(str(i + 1) + ". " + file) def main(): files = listdir("./Choices") list_files(files) choice = int(input()) choice_file = '' if 0 < choice < len(files) + 1: choice_file = "./Choices/" + files[choice - 1] else: print("That is not a valid number, try again") with open(choice_file) as f: choices = [x.strip('\n') for x in f.readlines()] print(choose_randomly(choices)) choice = input("q to exit, any other to choose again\n") return choice == 'q' or choice == 'Q' if __name__ == "__main__": done = False while not done: done = main()
a93f8e9ac02ba81adbd2b0ead5aa0a2af11d6011
egill12/pythongrogramming
/P3_question4.py
842
4.625
5
''' Write a program that asks the user for a long string containing multiple words. Echo back to the user the same string, except with the words in backwards order. For example, say we type the string: My name is Michele Then we would expect to see the string: Michele is name My ''' def reverse_str(string): ''' Write a program that asks the user for a long string containing multiple words. Echo back to the user the same string, except with the words in backwards order. :param string: :return: ''' broken_string = string.split() reversed_string = [] for element in reversed(broken_string): reversed_string.append(element) return reversed_string string = str(input("please give str:")) reversed_string = reverse_str(string) for element in reversed_string: print(element, end = " " )
30ef3384627cae5a2c54746091e041319a9907a9
richardcostarocha/atividades_blue
/exerciciosEntrega.py
8,049
4.5
4
#01 - Utilizando estruturas condicionais faça um programa que pergunte ao usuário dois números e mostre: # A soma deles; # A multiplicação entre eles; # A divisão inteira deles; # Mostre na tela qual é o maior; # Verifique se o resultado da soma é par ou impar e mostre na tela; # Se a multiplicação entre eles for maior que 40, divida pelo resultado da divisão inteira e mostre o # resultado na tela. Se não, mostre que a multiplicação não foi maior que 40. from os import system """ n1 = int(input('digite um valor: ')) n2 = int(input('digite outro valor: ')) print(f'a soma é: {n1+n2}') print(f'a divisão entre {n1} com {n2} é: {n1/n2}') if n1>n2: print(f'{n1} é maior que {n2}') else: print(f'{n2} é maior que {n1}') if (n1+n2)%2 == 0: print(f'a soma de {n1} com {n2} é par') else: print(f'a soma de {n1} com {n2} é impar') if (n1*n2)>40: if n1>n2: print(f'resultado: {(n1*n2)/(n1//n2)}') else: print(f'resultado: {(n1*n2)/(n2//n1)}') else: print(f'a muliplicação entre {n1} com {n2} não é maior que 40') system('cls') """ #02 - Utilizando estruturas de repetição com variável de controle, faça um programa que receba uma string com # uma frase informada pelo usuário e conte quantas vezes aparece as vogais a,e,i,o,u e mostre na tela, # depois mostre na tela essa mesma frase sem nenhuma vogal. """ frase = str(input('digite uma frase: ')).lower() cont = 0 for i in frase: if i in 'aeiou': cont +=1 print(f'na frase tem {cont} vogais') for i in 'aeiou': frase = frase.replace(i,' ') print(f'a frase sem as vogas fica: {frase}') """ #03 - Utilizando estruturas de repetição com teste lógico, faça um programa que peça uma senha para iniciar # seu processamento, só deixe o usuário continuar se a senha estiver correta, # após entrar dê boas vindas a seu usuário e apresente a ele o jogo da advinhação, # onde o computador vai “pensar” em um número entre 0 e 10. # O jogador vai tentar adivinhar qual número foi escolhido até acertar, # a cada palpite do usuário diga a ele se o número escolhido pelo computador é maior ou menor ao que ele palpitou, # no final mostre quantos palpites foram necessários para vencer. """ from random import randint senha = 'richard gostosão' comp = randint(0,10) erro = 0 senhateste = '' senhateste = str(input('digite a senha: ')) while senhateste != senha: system('cls') senhateste = str(input('senha invalida!\ndica: "criador gostosão"\ndigite a senha: ')) print('\33[33;41m') print('============') print('|Bem Vindo!|') print('============') print('\33[m') print('\33[7m ') usuario = int(input('tente adivinhar qual foi o numero que o pc escolheu(dica: foi um numero de 0 a 10): ')) while usuario != comp: erro += 1 if usuario > comp: print('seu numero foi maior!') else: print('seu numero foi menor!') usuario = int(input('vc errou, tente novamente: ')) print(f'vc precisou de {erro} vezes para acertar o numero {comp}') """ #04 - Utilizando funções e listas faça um programa que receba uma data no formato DD/MM/AAAA e devolva uma string # no formato DD de mesPorExtenso de AAAA. Opcional: valide a data e retorne 'data inválida' caso a data seja # inválida. """ data = str(input('data(dd/mm/aaaa): ')) def dataAjustada(data): dia,mes,ano = data.split('/') mesPorExtenso = ('Janeiro','Fevereiro','Março','Abril','Maio','Junho','Julho','Agosto','Setembro','Outubro','Novenbro','Dezembro') if mes == '01': mes = mesPorExtenso[0] elif mes == '02': mes = mesPorExtenso[1] elif mes == '03': mes = mesPorExtenso[2] elif mes == '04': mes = mesPorExtenso[3] elif mes == '05': mes = mesPorExtenso[4] elif mes == '06': mes = mesPorExtenso[5] elif mes == '07': mes = mesPorExtenso[6] elif mes == '08': mes = mesPorExtenso[7] elif mes == '09': mes = mesPorExtenso[8] elif mes == '10': mes = mesPorExtenso[9] elif mes == '11': mes = mesPorExtenso[10] elif mes == '12': mes = mesPorExtenso[11] return (dia,mes,ano) dia,mes,ano = dataAjustada(data) print(f'a data digitada é: {dia}/{mes}/{ano}') """ #05 - Refatore o exercício 2, para que uma função receba a frase, faça todo o tratamento necessário e retorne o # resultado. Depois mostre na tela o resultado e a quantidade de letras foram retiradas da frase original. """ frase = str(input('digite uma frase: ')).lower() contA = contE = contI = contO = contU = cont = 0 for i in frase: if i in 'aeiou': cont += 1 if i == 'a': contA += 1 elif i == 'e': contE += 1 elif i == 'i': contI += 1 elif i == 'o': contO += 1 elif i == 'u': contU += 1 print(f'na frase tem {cont} vogais') for i in 'aeiou': frase = frase.replace(i,' ') print(f'a frase sem as vogas fica: {frase}') print(f'foram retiradas {contA} vogais A da frase') print(f'foram retiradas {contE} vogais E da frase') print(f'foram retiradas {contI} vogais I da frase') print(f'foram retiradas {contO} vogais O da frase') print(f'foram retiradas {contU} vogais U da frase') """ #06 - Utilizando listas faça um programa que faça 5 perguntas para uma pessoa sobre um crime. As perguntas são: # "Telefonou para a vítima?" # "Esteve no local do crime?" # "Mora perto da vítima?" # "Devia para a vítima?" # "Já trabalhou com a vítima?" # O programa deve no final emitir uma classificação sobre a participação da pessoa no crime. # Se a pessoa responder positivamente a 2 questões ela deve ser classificada como "Suspeita", # Entre 3 e 4 como "Cúmplice" e 5 como "Assassino". # Caso contrário, ele será classificado como "Inocente". """ resporta = list() resporta.append(input('Telefonou para a vítima? ').lower().strip()[0]) resporta.append(input('Esteve no local do crime? ').lower().strip()[0]) resporta.append(input('Mora perto da vítima? ').lower().strip()[0]) resporta.append(input('Devia para a vítima? ').lower().strip()[0]) resporta.append(input('Já trabalhou com a vítima? ').lower().strip()[0]) if resporta.count('s') == 2: print('Suspeita') elif resporta.count('s') == 3 or resporta.count('s') == 4: print('Cúmplice') elif resporta.count('s') == 5: print('Assassino') else: print('Inocente') """ #07 - Crie um programa onde o usuário possa digitar sete valores numéricos e cadastre-os em uma lista única que # mantenha separados os valores pares e ímpares. No final, mostre os valores pares e ímpares em ordem crescente. """ valor = [list(),list()] for i in range(7): alx = 0 alx =int(input('digite um valor: ')) if alx % 2 == 0: valor[0].append(alx) else: valor[1].append(alx) valor[0].sort() valor[1].sort() print(f'os numers pares em ordem crescente é: {valor[0]}') print(f'os numers inpares em ordem crescente é: {valor[1]}') """ #08 - Crie um programa que leia nome, ano de nascimento e carteira de trabalho e cadastre-os (com idade) # em um dicionário. Se por acaso a CTPS for diferente de 0, o dicionário receberá também o ano de contratação # e o salário. Calcule e acrescente , além da idade, com quantos anos a pessoa vai se aposentar. # Considere que o trabalhador deve contribuir por 35 anos para se aposentar. """ from datetime import date anoAtual = date.today().year funcionario = dict() funcionario['nome'] = str(input('nome: ')) nascimento = int(input('ano de nascimento: ')) idade = anoAtual - nascimento funcionario['idade'] = idade funcionario['CTPS'] = int(input('carteira de trabalho: ')) if funcionario['CTPS'] != 0: contratação = int(input('ano de contratação: ')) anoDeContratação = anoAtual - contratação funcionario['anoDeContratação'] = anoDeContratação funcionario['salario'] = float(input('salario: ')) aposentadoria = 35 - funcionario.get('anoDeContratação') aposentado = idade + aposentadoria funcionario['aposentadoria'] = aposentado print(funcionario) """
c0d14de9fc61072d34558eec22c277fa45e321ea
BjornChrisnach/Basics_of_Computing_and_Programming
/count_for_loop.py
127
4.0625
4
print("Please enter a positive integer: ") input_num = int(input()) for counter in range(1, input_num + 1): print(counter)
97c210b42a229ca7690b464160e088b3480ae193
BjornChrisnach/Basics_of_Computing_and_Programming
/convert_Fahr_to_Celsius.py
398
4.03125
4
def main(): print("Please enter the temperature in Fahrenheit: ") temp_fahr = float(input()) temp_celsius = fahrenheit_to_celsius(temp_fahr) print(temp_fahr, "Fahrenheit is", temp_celsius, "Celcius") def fahrenheit_to_celsius(F): temp_celc = (F - 32) * (5/9) temp_celc = round(temp_celc, 3) return temp_celc # print(F, "Fahrenheit is", temp_celc, "Celcius") main()
c9fb1db790544b2d33dafa3e7e4c3f65558c695c
BjornChrisnach/Basics_of_Computing_and_Programming
/evennumbers.py
139
3.984375
4
print("Please enter a positive integer: ") number_of_numbers = int(input()) for i in range(2, (number_of_numbers*2) + 1, 2): print(i)
fc044bef4295e8e85313366be4a89689938756c2
BjornChrisnach/Basics_of_Computing_and_Programming
/days_traveled.py
233
4.125
4
print("Please enter the number of days you traveled") days_traveled = int(input()) full_weeks = days_traveled // 7 remaining_days = days_traveled % 7 print(days_traveled, "days are", full_weeks, "weeks and",\ remaining_days,"days")
f5740230d40654e8af5c0c75b2cc77eaeb470a89
BjornChrisnach/Basics_of_Computing_and_Programming
/str_count_number_words_ex3.py
267
4.09375
4
print("Please input several words, so a line of text, seperated with spaces: ") line = input() spaces_count = 0 for curr_char in line: if(curr_char == " "): spaces_count += 1 number_of_words = spaces_count + 1 print("You typed", number_of_words, "words")
5b8a04e1bd700a830a788b62704c6a8526dc32ba
BjornChrisnach/Basics_of_Computing_and_Programming
/print_triangle.py
118
4
4
print("Please enter a positive integer: ") n = int(input()) for i in range(1,n + 1): line = i*'*' print(line)
20676d87b7477c1403c8077ba0d012065903113c
jlroland/retirement-success
/randomize.py
7,313
3.5625
4
import numpy as np import pandas as pd import random from statistics import mean from plotly.subplots import make_subplots import plotly.graph_objects as go run calculations.py #import clean data & function to calculate interest #display distribution of historical returns for S&P 500 fig = go.Figure(data=[go.Histogram(x=refined_data['Return on S&P Composite'])]) fig.update_layout( title_text='Frequency of S&P Returns', xaxis_title_text='Percent Return', yaxis_title_text='Count' ) fig.show() #fig.write_image('images/annual_returns_frequency.png') #want to create a simulation of "historical" data based on randomized returns #distribution of historical returns will be used to approximate boundaries for randomization def get_random_data(): ''' Generates two arrays--one for random market returns and one for share prices resulting from the random returns. ''' rand_returns = [] for i in range(142): rand_returns.append(random.choice([random.triangular(-0.5, 0.075, 0.025),random.triangular(0.075, 0.5, 0.125)])) rand_price = [82.03] #share price for S&P 500 in 1871 for i in range(len(rand_returns)-1): rand_price.append(rand_price[i]*(1+rand_returns[i])) rand_returns = np.around(np.array(rand_returns),4) rand_price = np.array(rand_price) return rand_price,rand_returns def calculate_rand_portfolio(num_years, start_year, wr, pct_equity=0.5): ''' Calculates ending portfolio balance over a given timeframe when starting with a balance of $100,000. The calculation is made using the specified annual withdrawal rate and specified asset allocation (default 50/50 equities/fixed income). The equity share price values are randomized instead of historical values. Parameters: num_years (int): length of retirement period start_year (int): historical calendar year in which retirement period starts wr (float): initial withdrawal rate pct_equity (float): percent of portfolio invested in equities, default=0.5 Returns: portfolio (float): ending portfolio balance in dollars ''' init_portfolio = 100000 withdrawal_amount = init_portfolio*wr year1_balance = init_portfolio-withdrawal_amount equity_portion = pct_equity*year1_balance bond_portion = (1-pct_equity)*year1_balance rand_data = get_random_data() for i in range(start_year, start_year+num_years-1): num_shares = equity_portion/rand_data[0][i] portfolio = (equity_portion*(1+rand_data[1][i]) + num_shares*refined_data['RealD S&P Dividend'][i]) + calculate_interest(bond_portion, refined_data['Long Government Bond Yield'][i]) withdrawal_amount += withdrawal_amount*refined_data['Annual Inflation'][i] portfolio -= withdrawal_amount equity_portion = pct_equity*portfolio #rebalance asset allocation each year bond_portion = (1-pct_equity)*portfolio return portfolio def prob_rand_success(num_years, wr): ''' Calculates the probability of portfolio success based on historical data for a specified retirement length and initial withdrawal rate; portfolio success is defined as an ending portfolio balance greater than zero. The equity share prices in the historical data have been replaced with randomized data. Parameters: num_years (int): length of retirement period wr (float): initial withdrawal rate Returns: probability of success (float): probability of ending portfolio balance >0, based on past observations ''' success = 0 for i in range(0,142-num_years): result = calculate_rand_portfolio(num_years, i, wr) if result > 0: success += 1 return success/(142-num_years) #running 100 iterations of randomization to plot distribution for 4% withdrawal rate, comparing 30-yr and 60-yr retirements prob_rand_30 = [] prob_rand_60 = [] for i in range(100): prob_rand_30.append(prob_rand_success(30, 0.04)) prob_rand_60.append(prob_rand_success(60, 0.04)) fig = go.Figure() fig.add_trace(go.Scatter(x=np.arange(100), y=prob_rand_30, mode='markers', name='30-yr random')) fig.add_trace(go.Scatter(x=np.arange(100), y=prob_rand_60, mode='markers', name='60-yr random')) fig.add_shape( go.layout.Shape(type="line", x0=0, y0=mean(prob_rand_30), x1=100, y1=mean(prob_rand_30), line=dict( color="RoyalBlue", width=3 ))) fig.add_shape( go.layout.Shape(type="line", x0=0, y0=mean(prob_rand_60), x1=100, y1=mean(prob_rand_60), line=dict( color="Red", width=3))) fig.update_layout( showlegend=False, annotations=[ go.layout.Annotation( x=100, y=mean(prob_rand_30), xref="x", yref="y", text=round(mean(prob_rand_30),2), showarrow=True, arrowhead=7, ax=0, ay=-40 ), go.layout.Annotation( x=100, y=mean(prob_rand_60), xref="x", yref="y", text=round(mean(prob_rand_60),2), showarrow=True, arrowhead=7, ax=0, ay=-40 ) ] ) fig.update_layout(title='Probability of Success Based on Random Returns at 4% Withdrawal', xaxis_title='Sample Iteration', yaxis_title='Probability of Portfolio Success') fig.show() #fig.write_image('portfolio_success_random_4pct.png') #running 100 iterations of randomization to plot distribution for 3% withdrawal rate, comparing 30-yr and 60-yr retirements prob_rand_30_3 = [] prob_rand_60_3 = [] for i in range(100): prob_rand_30_3.append(prob_rand_success(30, 0.03)) prob_rand_60_3.append(prob_rand_success(60, 0.03)) fig = go.Figure() fig.add_trace(go.Scatter(x=np.arange(100), y=prob_rand_30_3, mode='markers', name='30-yr random')) fig.add_trace(go.Scatter(x=np.arange(100), y=prob_rand_60_3, mode='markers', name='60-yr random')) fig.add_shape( go.layout.Shape(type="line", x0=0, y0=mean(prob_rand_30_3), x1=100, y1=mean(prob_rand_30_3), line=dict( color="RoyalBlue", width=3 ))) fig.add_shape( go.layout.Shape(type="line", x0=0, y0=mean(prob_rand_60_3), x1=100, y1=mean(prob_rand_60_3), line=dict( color="Red", width=3 ))) fig.update_layout( showlegend=False, annotations=[ go.layout.Annotation( x=100, y=mean(prob_rand_30_3), xref="x", yref="y", text=round(mean(prob_rand_30_3),2), showarrow=True, arrowhead=7, ax=0, ay=-40 ), go.layout.Annotation( x=100, y=mean(prob_rand_60_3), xref="x", yref="y", text=round(mean(prob_rand_60_3),2), showarrow=True, arrowhead=7, ax=0, ay=-40 ) ] ) fig.update_layout(title='Probability of Success Based on Random Returns at 3% Withdrawal', xaxis_title='Sample Iteration', yaxis_title='Probability of Portfolio Success') fig.show() #fig.write_image('portfolio_success_random_3pct.png')
bd9cbc8368a63b0652102e1490ba049386c32b20
thusyasin/python-programming
/leapy.py
88
3.890625
4
a=int(input()) if a%4==0: print a,"is a leap year." else: print a,"is not a leap year."
386917245b7e7130aa3a96abccf9ca35842e1904
getachew67/UW-Python-AI-Coursework-Projects
/Advanced Data Programming/hw2/hw2_pandas.py
2,159
4.1875
4
""" Khoa Tran CSE 163 AB This program performs analysis on a given Pokemon data file, giving various information like average attack levels for a particular type or number of species and much more. This program immplements the panda library in order to compute the statistics. """ def species_count(data): """ Returns the number of unique species in the given file """ result = data['name'].unique() return len(result) def max_level(data): """ Returns a tuple with the name and level of the Pokemon that has the highest level """ index = data['level'].idxmax() result = (data.loc[index, 'name'], data.loc[index, 'level']) return result def filter_range(data, low, high): """ Returns a list of Pokemon names having a level that is larger or equal to the lower given range and less than the higher given range """ temp = data[(data['level'] >= low) & (data['level'] < high)] return list(temp['name']) def mean_attack_for_type(data, type): """ Returns the average attack for all Pokemon in dataset with the given type Special Case: If the dataset does not contain the given type, returns 'None' """ temp = data.groupby('type')['atk'].mean() if type not in temp.index: return None else: return temp[type] def count_types(data): """ Returns a dictionary of Pokemon with the types as the keys and the values as the corresponding number of times that the type appears in the dataset """ temp = data.groupby('type')['type'].count() return dict(temp) def highest_stage_per_type(data): """ Returns a dictionary with the key as the type of Pokemon and the value as the highest stage reached for the corresponding type in the dataset """ temp = data.groupby('type')['stage'].max() return dict(temp) def mean_attack_per_type(data): """ Returns a dictionary with the key as the type of Pokemon and the value as the average attack for the corresponding Pokemon type in the dataset """ temp = data.groupby('type')['atk'].mean() return dict(temp)
2a0042d38b10f6c4639988b12112e8ee795b480e
getachew67/UW-Python-AI-Coursework-Projects
/Advanced Data Programming/hw1/hw1.py
4,316
3.921875
4
""" Khoa Tran CSE 163 AB Program that implements the solution code for various problems presented """ def total(n): """ Returns the sum of the numbers from 0 to n (inclusive). If n is negative, returns None. """ if n < 0: return None else: result = 0 for i in range(n + 1): result += i return result def count_divisible_digits(n, m): """ Returns the number of digits in the given number that are divisible by the other given number """ result = 0 if m == 0: return 0 n = abs(n) while n != 0: temp = n % 10 if temp % m == 0: result += 1 n = n // 10 return result def is_relatively_prime(n, m): """ Returns whether two numbers are prime relative to one another, meaning if the only common factor is "1" between the two numbers, function returns True """ result = True larger = n if m > n: larger = m for i in range(1, larger + 1): if n % i == 0 and m % i == 0: if i == 1: result = True else: result = False return result def travel(direction, x, y): """ Returns a final coordinate of x and y based on given instructions of cardinal directions from the given string """ x_new = x y_new = y for i in range(len(direction)): test = direction[i].lower() if test == 'n': y_new += 1 elif test == 's': y_new -= 1 elif test == 'e': x_new += 1 elif test == 'w': x_new -= 1 return (x_new, y_new) def compress(word): """ Returns a string in which each letter is followed by count of the same characters adjacent to it from the passed string """ temp = [] for i in range(len(word)): if word[i] in temp and word[i] == word[i - 1]: if temp[len(temp) - 2] == word[i]: last = int(temp[len(temp) - 1]) + 1 temp[len(temp) - 1] = str(last) else: num = temp.index(word[i]) + 1 val = int(temp[num]) + 1 temp[num] = str(val) else: temp.append(word[i]) temp.append(str(1)) return ''.join(temp) def longest_line_length(file_name): """ Returns the length of the longest line in given file. Returns None if the file is empty """ result = 0 with open(file_name) as file: lines = file.readlines() for line in lines: if len(line) > result: result = len(line) if result <= 1: return None else: return result def longest_word(file_name): """ Returns the longest word in a file and along with its line number. Returns None if the file is empty """ longest = 0 linenum = 0 finalnum = 0 result = '' with open(file_name) as file: lines = file.readlines() for line in lines: linenum += 1 words = line.split() for word in words: if len(word) > longest: longest = len(word) result = word finalnum = linenum if longest == 0: return None return str(finalnum) + ': ' + result def get_average_in_range(list, low, high): """ Returns the average of the digits in the given list that is in the range between the given low (inclusive) and the high (exclusive) integers """ track = 0 val = 0 for num in list: if num >= low and num < high: val += num track += 1 if track == 0: return 0 return val / track def mode_digit(n): """ Returns the digit that most commonly occur in given integer """ temp = dict() result = 0 most = 0 n = abs(n) while n != 0: val = n % 10 if val in temp: temp[val] += 1 else: temp[val] = 1 n = n // 10 for k, v in temp.items(): if v >= most: if v == most: if k > result: result = k else: most = v result = k return result
f72d0033f0c5504ad87e558f6a6b097b54c14c6b
veryspecialdog/pythonpractice
/创建函数.py
525
3.671875
4
x=1 while x<=9: y=1 while y<=x: print("{}*{}={}\t".format(x,y,x*y),end='') y +=1 print() x +=1 print() names = ['anne','beth','george','damon'] ages = [12,45,32,102] for i in range(len(names)): print(names[i],'is',ages[i],'years old') print(list(zip(names,ages))) from math import sqrt for n in range(99,0,-1): root = sqrt(n) if root == int(root): print(n) break
62963b58ed75d45c53c5ccbc3dcb01ed292307d4
Baloolaoo/python-test
/02 - Matplotlib/candlestick.py
928
3.8125
4
# imports import pandas_datareader as data import pandas as pd import mplfinance as mpf import trading_functions as tf ''' This scripts purpose is to plot a candlestick chart out of a pandas dataframe. Next To-Do: - Add functions for - Inside days - Outside days - Plot Inside/Outside days in chart ''' # set print options for console output pd.set_option('max_rows', 1000) pd.set_option('max_columns', 1000) pd.set_option('display.width', 1000) # First day start_date = '2021-01-01' # Last day end_date = '2021-02-28' # Call the function DataReader from the class data dataset = data.DataReader('GC=F', 'yahoo', start_date, end_date) # Transform with trading_functions.py dataset = tf.updays(dataset) dataset = tf.tradingrange(dataset) apd = mpf.make_addplot(dataset['Upday_Signal'], type='scatter',markersize=100,marker='^', color='r') print(dataset) mpf.plot(dataset,type='candle',addplot=apd)
c3626ea1efb1c930337e261be165d048d842d15a
Razorro/Leetcode
/72. Edit Distance.py
3,999
3.515625
4
""" Given two words word1 and word2, find the minimum number of operations required to convert word1 to word2. You have the following 3 operations permitted on a word: Insert a character Delete a character Replace a character Example 1: Input: word1 = "horse", word2 = "ros" Output: 3 Explanation: horse -> rorse (replace 'h' with 'r') rorse -> rose (remove 'r') rose -> ros (remove 'e') Example 2: Input: word1 = "intention", word2 = "execution" Output: 5 Explanation: intention -> inention (remove 't') inention -> enention (replace 'i' with 'e') enention -> exention (replace 'n' with 'x') exention -> exection (replace 'n' with 'c') exection -> execution (insert 'u') A good question! I thought it was similiar with the dynamic programming example in CLRS, it turns out the skeleton may has a little similiarity, but the core idea can't be extracted with the situation of this question. It was called Levenshtein distance. Mathematically, the Levenshtein distance between two strings {\displaystyle a,b} a,b (of length {\displaystyle |a|} |a| and {\displaystyle |b|} |b| respectively) is given by {\displaystyle \operatorname {lev} _{a,b}(|a|,|b|)} \operatorname{lev}_{a,b}(|a|,|b|) where | --- max(i, j) if min(i, j) = 0 lev(i, j) = | min --- lev(i-1, j) + 1 | --- lev(i, j-1) + 1 | --- lev(i-1, j-1) + 1 Computing the Levenshtein distance is based on the observation that if we reserve a matrix to hold the Levenshtein distances between all prefixes of the first string and all prefixes of the second, then we can compute the values in the matrix in a dynamic programming fashion, and thus find the distance between the two full strings as the last value computed. This algorithm, an example of bottom-up dynamic programming, is discussed, with variants, in the 1974 article The String-to-string correction problem by Robert A. Wagner and Michael J. Fischer.[4] """ class Solution: def minDistance(self, word1: 'str', word2: 'str') -> 'int': points = self.findBiggestCommon(word1, word2) def findBiggestCommon(self, source, target): path = [0] * len(source) directions = [] for i in range(len(target)): current = [0] * len(source) d = [] for j in range(len(source)): if target[i] == source[j]: current[j] = path[j-1] + 1 if j-1 >= 0 else 1 d.append('=') else: left = current[j-1] if j-1 >= 0 else 0 if left > path[j]: d.append('l') else: d.append('u') current[j] = max(left, path[j]) path = current directions.append(d) x_y = [] row, col = len(target)-1, len(source)-1 while row >= 0 and col >=0: if directions[row][col] == '=': x_y.append((row, col)) row -= 1 col -= 1 elif directions[row][col] == 'u': row -= 1 else: col -= 1 return x_y def standardAnswer(self, word1, word2): m = len(word1) + 1 n = len(word2) + 1 det = [[0 for _ in range(n)] for _ in range(m)] for i in range(m): det[i][0] = i for i in range(n): det[0][i] = i for i in range(1, m): for j in range(1, n): det[i][j] = min(det[i][j - 1] + 1, det[i - 1][j] + 1, det[i - 1][j - 1] + 0 if word1[i - 1] == word2[j - 1] else 1) return det[m - 1][n - 1] if __name__ == '__main__': s = Solution() distance = s.findBiggestCommon('horse', 'ros') distance = sorted(distance, key=lambda e: e[1]) c = 0 trans = 0 for left, right in distance: trans += abs(right - left) + left-c c = left + 1 print(s.findBiggestCommon('horse', 'ros'))
5d01d82bfd16634be636cce2cf2e1d31ea7208b1
Razorro/Leetcode
/88. Merge Sorted Array.py
1,353
4.28125
4
""" Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array. Note: The number of elements initialized in nums1 and nums2 are m and n respectively. You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2. Example: Input: nums1 = [1,2,3,0,0,0], m = 3 nums2 = [2,5,6], n = 3 Output: [1,2,2,3,5,6] No other tricks, just observation. 执行用时: 68 ms, 在Merge Sorted Array的Python3提交中击败了8.11% 的用户 内存消耗: 13.1 MB, 在Merge Sorted Array的Python3提交中击败了0.51% 的用户 Although the result is not so well, but I think there is no big difference with other solutions. """ class Solution: def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None: """ Do not return anything, modify nums1 in-place instead. """ idx1, idx2 = m - 1, n - 1 fillIdx = len(nums1) - 1 while idx1 >= 0 and idx2 >= 0: if nums1[idx1] > nums2[idx2]: nums1[fillIdx] = nums1[idx1] idx1 -= 1 else: nums1[fillIdx] = nums2[idx2] idx2 -= 1 fillIdx -= 1 while idx2 >= 0: nums1[fillIdx] = nums2[idx2] idx2 -= 1 fillIdx -= 1
86323e12a03901c476e861a37956ec4b04406ea7
Razorro/Leetcode
/32. Longest Valid Parentheses.py
2,151
3.890625
4
""" Description 32: Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring. Example 1: Input: "(()" Output: 2 Explanation: The longest valid parentheses substring is "()" Example 2: Input: "((()()))" Output: 4 Explanation: The longest valid parentheses substring is "()()" "()(()" "(()" I made it! When I occur the hard level problem, always think that it surpass my ability to solve it. It turns out, as you carefully clear the path of the problem, the left is only the implementation. Runtime: 52 ms, faster than 68.84% of Python3 online submissions for Longest Valid Parentheses. """ def test(s): remain = [] for i in range(len(s)): if s[i] == '(': remain.append(i) elif len(remain): remain.pop() else: return remain return remain class Solution: def longestValidParentheses(self, s): """ :type s: str :rtype: int """ return self._checkMaxLen(s, 0, len(s)-1) def _checkMaxLen(self, s, start, end): if start >= len(s): return 0 if end - start <= 1: return 2 if s[start] == '(' and s[end] == ')' else 0 remains = [] invalidIdx = None for i in range(start, end+1): if s[i] == '(': remains.append(i) elif len(remains) > 0: remains.pop() else: invalidIdx = i break if len(remains): left = remains[0] - start middle = 0 for k in range(len(remains)-1): middle = max(middle, (remains[k+1]-remains[k]-1)) maxLen = max(left, middle, self._checkMaxLen(s, remains[-1]+1, end)) elif invalidIdx is not None: left = invalidIdx - start maxLen = max(left, self._checkMaxLen(s, invalidIdx+1, end)) else: maxLen = end - start + 1 return maxLen if __name__ == '__main__': s = Solution() print(s.longestValidParentheses(")(((((()())()()))()(()))("))
2cd13056f72eaf8f16e342bacde6c9b17bd43d3b
Razorro/Leetcode
/49. Group Anagrams.py
863
4.125
4
""" Description: Given an array of strings, group anagrams together. Example: Input: ["eat", "tea", "tan", "ate", "nat", "bat"], Output: [ ["ate","eat","tea"], ["nat","tan"], ["bat"] ] Note: All inputs will be in lowercase. The order of your output does not matter. Runtime: 152 ms, faster than 39.32% of Python3 online submissions for Group Anagrams. Memory Usage: 15.5 MB, less than 100.00% of Python3 online submissions for Group Anagrams. Not very fast, but I guess all the answer comply the rule: Make unique hash value of those same anagrams. """ class Solution: def groupAnagrams(self, strs: 'List[str]') -> 'List[List[str]]': import collections h = collections.defaultdict(list) for s in strs: h[''.join(sorted(s))].append(s) return list(h.values()) return list(collectorDict.values())
fad684b0de4618f7f7b2986dffc215705a382862
Razorro/Leetcode
/77. Combinations.py
1,177
3.6875
4
""" Given two integers n and k, return all possible combinations of k numbers out of 1 ... n. Example: Input: n = 4, k = 2 Output: [ [2,4], [3,4], [2,3], [1,2], [1,3], [1,4], ] 执行用时: 160 ms, 在Combinations的Python3提交中击败了85.61% 的用户 内存消耗: 9.1 MB, 在Combinations的Python3提交中击败了56.38% 的用户 Not bad, just use recursive method to create the situation that fit this question. """ class Solution: def combine(self, n: 'int', k: 'int') -> 'List[List[int]]': def combine(self, n: 'int', k: 'int') -> 'List[List[int]]': if n <= 0 or k <= 0: return [[]] result = [] current = [] k = min(n, k) self.solve(n, k, 1, result, current) return result def solve(self, n, k, i, result, current): if k == 0: result.append(list(current)) return k -= 1 if n - i < k: return for j in range(i, n + 1): current.append(j) self.solve(n, k, j + 1, result, current) current.pop()
d2d6f21556955a4b8ec8893b8bf03e7478032b68
Razorro/Leetcode
/7. Reverse Integer.py
817
4.15625
4
""" Description: Given a 32-bit signed integer, reverse digits of an integer. Note: Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−2^31, 2^31 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows. """ """ Analysis: Easy... Nope... forget to deal with overflow """ class Solution: def reverse(self, x): """ :type x: int :rtype: int """ flag = x < 0 constant = 2**31 x = abs(x) x = str(x) x = x[::-1] x = int(x) if flag: x = -x if x <= constant else 0 else: x = x if x <= constant-1 else 0 return x if __name__ == '__main__': testCase = [ ]
c0de2ccf5660c74c913334edfee8f488603b9643
Razorro/Leetcode
/24. Swap Nodes in Pairs.py
1,194
3.984375
4
""" Description 24 Given a linked list, swap every two adjacent nodes and return its head. Example: Given 1->2->3->4, you should return the list as 2->1->4->3. Note: Your algorithm should use only constant extra space. You may not modify the values in the list's nodes, only nodes itself may be changed. Runtime: 48 ms, faster than 30.72% of Python3 online submissions for Swap Nodes in Pairs. Emm... Not so fast as I think, but I reckoned the solution is pretty clear. """ # Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def swapPairs(self, head): """ :type head: ListNode :rtype: ListNode """ cur = head tail = None while cur and cur.next: if cur is head: head = cur.next third = cur.next.next nextHead = cur.next cur.next.next = cur cur.next = third if tail: tail.next = nextHead tail = cur cur = cur.next return head if __name__ == '__main__': s = Solution() print(s.swapPairs())
1e806c64ffe1956225f22f369b5f355a053876c4
fangmingc/ChuannBlog
/Python/Beginning_of_Python/3Function/作业3/Simulate_SQL.py
13,814
3.75
4
# 实现员工信息表 # 文件存储格式如下: # id,name,age,phone,job # 1,Alex,22,13651054608,IT # 2,Egon,23,13304320533,Tearcher # 3,nezha,25,1333235322,IT # # 现在需要对这个员工信息文件进行增删改查。 # 基础必做: # a.可以进行查询,支持三种语法: # select 列名1,列名2,… where 列名条件 # 支持:大于小于等于,还要支持模糊查找。 # 示例: # select name,age where age>22 # select * where job=IT # select * where phone like 133 # # 进阶选做: # b.可创建新员工记录,id要顺序增加 # c.可删除指定员工记录,直接输入员工id即可 # d.修改员工信息 # 语法:set 列名=“新的值” where 条件 # #先用where查找对应人的信息,再使用set来修改列名对应的值为“新的值” # # 注意:要想操作员工信息表,必须先登录,登陆认证需要用装饰器完成 # 其他需求尽量用函数实现 import os import functools inspect = { 'status': False, 'permission': 10, } # 打印列表 def show(data): if not data: pass else: for i in range(len(data)): for j in range(len(data[i])): print(data[i][j], end=', ') print() # 判断从读取文件的一行字符串是否为空或者注释 def judge_line(line): """Function to judge the blank line or comment. Receive a string from a line of file and judge whether this line is blank line or comment. :param line: Receive a string. :return: """ if len(line) < 4: return True elif line[0] == '#': return True else: return False # 从指定文件名加载数据 def load_data(filename): """Function to load data. :return: Return a list which element is single information. """ data = [] with open(filename, 'r') as rf: for line in rf: if judge_line(line): continue # 文件一行有四个逗号,为员工信息文件 elif line.count(',') == 4: temp = line.strip('\n').split(',') data.append([int(temp[0]), temp[1], int(temp[2]), temp[3], temp[4]]) # 文件一行有三个逗号,为用户信息文件 elif line.count(',') == 2: temp = line.strip('\n').split(',') data.append([temp[0], temp[1], int(temp[2])]) return data # 登录函数,成功返回True,失败返回False def sign_in(): """Function to sign in. :return: True for signing in successfully, False for failure. """ data = load_data('Account') while True: username = input("'quit' or 'q' to quit\nPlease input \033[1;34musername\033[0m:").strip() if username in ('quit', 'q'): return False elif username: for i in range(len(data)): if username == data[i][0]: while True: password = input("'quit' or 'q' to quit\nPlease input \033[1;34mpassword\033[0m:") if not password: print('Password can not be empty!') elif password == data[i][1]: inspect['permission'] = data[i][2] print('Login successful!') return True elif password in ('quit', 'q'): return False else: print('Password is incorrect!') else: print('Username is incorrect!') # Decorator to judge the permission to execute the function. def permission(func): @functools.wraps(func) def inner(*args, **kwargs): if inspect['permission'] <= 2: ret = func(*args, **kwargs) return ret else: print('You do not have permission to use this feature.') return inner # Decorator to check the login status of user. def auth(func): @functools.wraps(func) def inner(*args, **kwargs): if inspect['status']: ret = func(*args, **kwargs) return ret else: print("Continue after login!") if sign_in(): inspect['status'] = True ret = func(*args, **kwargs) return ret return inner # 根据给定的条件从员工信息文件筛选,返回结果 def search(column_index, i, logic, cmd): """""" be_data = load_data('Employee_info_table') af_data = [] for j in range(len(be_data)): if logic == '>=' and int(be_data[j][i]) >= int(cmd): af_data.append(be_data[j]) elif logic == '<=' and int(be_data[j][i]) <= int(cmd): af_data.append(be_data[j]) elif logic == '!='and be_data[j][i] != cmd: af_data.append(be_data[j]) elif logic == '<>' and be_data[j][i] != cmd: af_data.append(be_data[j]) elif logic == '>' and int(be_data[j][i]) > int(cmd): af_data.append(be_data[j]) elif logic == '<' and int(be_data[j][i]) < int(cmd): af_data.append(be_data[j]) elif logic == '=' and str(be_data[j][i]) == str(cmd): af_data.append(be_data[j]) elif logic == 'like' and str(be_data[j][i]).count(cmd) > 0: af_data.append(be_data[j]) if len(column_index) == 5: data = af_data else: data = [] for k in range(len(af_data)): temp = list(af_data[k][column_index[n]] for n in range(len(column_index))) data.append(temp) return data # 将select语句的范围和条件进一步拆分 @auth def command_select(c_n1, cmd): """""" column_name = ['id', 'name', 'age', 'phone', 'job'] logics = ['>=', '<=', '!=', '<>', '>', '<', '=', 'like'] # 把列名对应的索引储存进c_n2 if c_n1.count('*') > 0: c_n2 = range(len(column_name)) else: c_n2 = tuple(i1 for i1 in range(len(column_name)) if c_n1.count(column_name[i1]) > 0) if not c_n2: print('Please specify the effective range!') return for i2 in range(len(logics)): if cmd.count(logics[i2]) > 0: logic = tuple(cmd.split(logics[i2])[j].strip() for j in range(len(cmd.split(logics[i2])))) if logic[0] in column_name: return search(c_n2, column_name.index(logic[0]), logics[i2], logic[1]) else: print('Please specify the effective logic!') # 将add语句的的添加信息进行鉴别,写入文件 @auth def command_add(info, filename='Employee_info_table'): """""" if len(info) != 4: print('Please input valid information!\nlike:\nadd jack,18,1234568911,student') return False data = load_data(filename) name = (data[i][1] for i in range(len(data))) job = ('Teacher', 'IT', 'Student', 'Employee') job_lower = tuple(job[i].lower() for i in range(len(job))) item = list(info[i].strip() for i in range(len(info))) # 如果信息为空则初始化信息 for j in range(4): if j == 0 and not item[j]: print('name can not be empty!') return False elif j == 1 and not item[j]: item[j] = str(16) elif j == 2 and not item[j]: item[j] = '***********' elif j == 3 and not item[j]: item[j] = 'Employee' # 给信息添加id,追加进文件 if item[0].isalpha(): if item[0] not in name: if int(item[1]) in range(16, 100): if len(item[2]) in (6, 11): if item[3].lower() in job_lower: with open(filename, 'a', encoding='utf-8')as wf: ind = job_lower.index(item[3].lower()) wf.write(','.join((str(data[-1][0]+1), *item[:-1], job[ind]))+'\n') print('Add successfully!') return True else: print('This job can not be added!\nYou can add these:\n{}'.format(job)) else: print('Invalid phone number!(6/11 phone number is valid)') else: print('Invalid age!(16-99 is valid)') else: print('This name has existed.') else: print('Name is invalid!') return False # 从delete语句给定的id或者name确定唯一员工,从文件删除 @auth @permission def command_delete(obj, filename='Employee_info_table'): """ sadadssadfdsag """ if obj.isdigit() or obj.isalpha(): with open(filename, encoding='utf-8') as rf, \ open(filename + '_swap', 'w', encoding='utf-8') as wf: for line in rf: if judge_line(line): wf.write(line) elif obj == line.split(',')[0] or obj == line.split(',')[1]: print('Delete successfully!') continue else: wf.write(line) os.remove(filename) os.rename(filename + '_swap', filename) return True else: print('Please input valid command!') return False # 将set语句的范围和条件给select函数得到筛选好的结果,对结果进行修改 @auth @permission def command_set(change, condition): """""" column_name = ('name', 'age', 'phone', 'job') cha = tuple(change.split('=')[i].strip().strip('"') for i in range(len(change.split('=')))) if len(cha) == 2 and cha[0] in column_name: select_data = command_select('*', condition) data = load_data('Employee_info_table') if select_data: for i in range(len(select_data)): select_data[i][column_name.index(cha[0])] = cha[1] for j in range(len(data)): if select_data[i][0] == data[j][0]: data[j] = select_data[i] with open('Employee_info_table', 'r', encoding='utf-8') as rf, \ open('Employee_info_table_swap2', 'w', encoding='utf-8') as wf: for line in rf: if judge_line(line): wf.write(line) else: for k in range(len(data)): item = (str(data[k][0]), data[k][1], str(data[k][2])) wf.write(','.join((*item, *data[k][3:]))+'\n') else: break os.remove('Employee_info_table') os.rename('Employee_info_table_swap2', 'Employee_info_table') print('Successfully modified!') return True else: print('Please input valid command!') return False # 主页面 @auth def index(): """""" print("Welcome to \033[1;33mEmployee Information Management System\033[0m!\n\ 'help' or 'help <command>'to check command") flag = True while flag: cmd = input('@EIMS $ ').strip() # select语句,去掉select,以where分割开列名和条件传入select函数,打印返回值 if cmd.startswith('select') and 'where' in cmd: temp = cmd.lstrip('select').split('where') show(command_select(temp[0].strip(), temp[1].strip())) # set语句,去掉set,以where分隔开修改内容和条件,传入set函数 elif cmd.startswith('set') and 'where' in cmd: temp = cmd.lstrip('set').split('where') command_set(temp[0].strip(), temp[1].strip()) # add语句,去掉add,传入增加信息 elif cmd.startswith('add'): command_add(cmd.lstrip('add').split(',')) # delete语句,去掉delete,传入修改目标 elif cmd.startswith('delete'): command_delete(cmd.lstrip('delete').strip()) # help语句,去掉help,传入help目标 elif cmd.startswith('help'): command_help(cmd.lstrip('help').strip()) elif cmd in ('quit', 'q'): return else: print('Command is incorrect!') # 帮助函数 def command_help(cmd): """""" select = ''' \ 1.select <范围> where <条件> <范围> 支持列名: 'id', 'name', 'age', 'phone', 'job', '*' <条件> 支持逻辑(按优先级排列): '>=', '<=', '!=', '<>', >', '<', '=', 'like' 指令示范: select name,age where id>=3 \ ''' add = '''\ 2.add <信息> <信息> 支持信息格式: 姓名,年龄,电话,职位 指令示范: add jack,22,13340578393,student\ ''' delete = '''\ 3.delete <id>/<name> <id>/<name> 支持格式: id号码或者员工姓名 指令示范: delete 4 \ ''' _set = '''\ 4.set <列名>=<修改值> where <条件> <列名>=<修改值> 支持格式: 列名:'id', 'name', 'age', 'phone', 'job' 修改值:不限 <条件> 支持逻辑: '>=', '<=', '!=', '<>', >', '<', '=', 'like' 指令示范: set name=alex where name=Alex\ ''' # _help = '''\ # 查看指定命令: # help <指令> # ''' if not cmd: print('{}\n{}\n{}\n{}'.format(select, add, delete, _set)) elif cmd == 'select': print(select) elif cmd == 'add': print(add) elif cmd == 'delete': print(delete) elif cmd == 'set': print(set) return True index() # print(command_delete.__doc__)
c0c1620a94c64f7b13fe354fbbbe3032533a88c6
jrahman1988/PythonSandbox
/myPandas_DataFrame_FromList.py
733
4.0625
4
''' A Data frame is a two-dimensional data structure, i.e., data is aligned in a tabular fashion in rows and columns. Features of DataFrame: Potentially columns are of different types Size – Mutable Labeled axes (rows and columns) Can Perform Arithmetic operations on rows and columns ''' import pandas as pd #Create DataFrame from a single list with only one column data = [100,200,300,400,500] df1 = pd.DataFrame(data) print("\nCreated DataFrame = {} ".format(df1)) #Create DataFrame from a list of list with multiple columns data = [['Alex',10],['Bob',12],['Clarke',13]] df2 = pd.DataFrame(data, columns=['Name','Age'], dtype=float) print ("\nThe DataFrame created from a 'list of list' is : \n{}".format(df2))
92b2ac96f202ac222ccd4b9572595602abf0a459
jrahman1988/PythonSandbox
/myDataStruct_CreateDictionaryByFilteringOutKeys.py
677
4.34375
4
''' A dictionary is like an address-book where we can find the address or contact details of a person by knowing only his/her name i.e. we associate keys (name) with values Dictionary is represented by dict class. Pair of keys and values are specified in dictionary using the notation d = {key1 : value1, key2 : value2 } When we need to create a dictionary from a dictionary by filtering specific keys ''' # Single dictionary, from here will create another dictionary by filtering out keys 'a' and 'c': d1 = {"c": 3, "a": 1, "b": 2, "d": 4} filter_list = ["a", "c"] d11 = dict((i, d1[i]) for i in filter_list if i in d1) print("Type of d11: ", type(d11)) print(d11)
1a4d781b35cfbb98acbc1b8b9fad8aa9a78c51ac
jrahman1988/PythonSandbox
/myPandas_DescriptiveStatistics.py
1,754
4.40625
4
''' A large number of methods collectively compute descriptive statistics and other related operations on DataFrame. Most of these are aggregations like sum(), mean(), but some of them, like sumsum(), produce an object of the same size. Generally speaking, these methods take an axis argument, just like ndarray.{sum, std, ...}, but the axis can be specified by name or integer ''' import pandas as pd desired_width=320 pd.set_option('display.width', desired_width) pd.set_option('display.max_columns',100) #Read the pokemon_data.csv from the file system and transform into a DataFrame using read_csv() method df = pd.read_csv("~/Desktop/Learning/Sandbox/PythonSandbox/Data/pokemon_data.csv") #Output statistics of all data in the file using describe() method print("\nOutput all basic statistics using describe(): \n", df.describe()) #Sort output using sort_values() method (default is ascending order) print("\nOutput sorted data based on the column named 'Name': \n", df.sort_values('Name')) #Sorting based on a single column in a file and output using sort_values() method (descending order - ascending=false) print("\nOutput sorted data based on the column named 'Name' in descending order: \n", df.sort_values('Name', ascending=False)) #Sorting based on a multiple columns in a file and output using sort_values() method ('Name' column in ascending order and 'HP' column in descending order) print("\nOutput sorted data based multiple columns 'Name' and 'HP' one in ascending and other in descending order: \n", df.sort_values(['Name', 'HP'], ascending=[1,0])) #Summing the values in the columns of a DF using sum(axis) where axis = 0 is vertical and 1= horizontal print("\nSum of the values in column with index 1 of the DF :\n", df.sum(1))
ebb36c2e43bbe17c911516f90c0874f406463b51
jrahman1988/PythonSandbox
/myWebScrapping_fmNYTimes_VaccineProgress02.py
867
3.875
4
''' Webscraping to GET the html response, then PARSE and fetch the content, FIND the tables, CONSTRUCT a DF We'll use here the pandas.read_html(), which returns a list of data frames. According to the PANDAS doc: "This function searches for <table> elements and only for <tr> and <th> rows and <td> elements within each <tr> or <th> element in the table. <td> stands for “table data”. Document URL: https://www.nytimes.com/interactive/2021/world/covid-vaccinations-tracker.html ''' import pandas as pd import requests from bs4 import BeautifulSoup # vaccineDF = pd.read_html('https://www.nytimes.com/interactive/2021/world/covid-vaccinations-tracker.html')[0] vaccineDF = vaccineDF.reset_index(drop=True) print(vaccineDF.head(100)) print(vaccineDF.tail(100)) vaccineDF.to_csv("~/Desktop/Learning/Sandbox/PythonSandbox/Data/VaccineDataFromNYT_02.csv", index=True)
e10c97db1dd0330fdc54271714ae7dbd607d3005
jrahman1988/PythonSandbox
/myMatplotlib_CoronaVirusGraphs_v1.py
4,580
3.875
4
''' Using Matplotlib module of Python, draw a different graphs, data read from (corona_virus.csv) Note that, here we do the followings to fine tune the dataframe: 1. Read the data file corona_virus.csv from file system and create a dataframe 2. Delete the last row so that 'Total' is not considered in any calculations using: cv = cv.iloc[:-1] 3. Drop the 'Diamond Princess' row as a country usincv = cv[cv.Country != 'Diamond Princess']g: ''' from matplotlib import pyplot as plt import numpy as np import pandas as pd import datetime #This is for how many data will be read dataSize = 9 desired_width=360 pd.set_option('display.width', desired_width) pd.set_option('display.max_columns',120) dt = datetime.datetime.now() today = dt.strftime("%A, %d %B %Y, %H:%M:%S") #Read the coronoa_virus.csv from the file system and transform into a DataFrame using read_csv() method cv = pd.read_csv("~/Desktop/Learning/Sandbox/PythonSandbox/Data/corona_virus.csv") cv = cv.iloc[:-1] #<-- Here we drop the last row of the dataframe (last row holds the total of all rows) cv = cv[cv.Country != 'Diamond Princess'] #<-Here we drop a row where the 'Country' column contains a value 'Diamond Princess' #Sorting the data based on a single column in a file and output using sort_values() method (descending order - ascending=False) cv_TotalCases = cv.sort_values('Total cases', ascending=False) cv_TotalRecovered = cv.sort_values('Total recovered', ascending=False) cv_TotalCasesPerMillion = cv.sort_values('Total cases per 1M pop.', ascending=False) cv_TotalDeaths = cv.sort_values('Total deaths', ascending=False) cv_NewCases = cv.sort_values('New cases', ascending=False) cv_NewDeaths = cv.sort_values('New deaths', ascending=False) print("\nOutput sorted data based on the column named 'Total cases' in descending order: \n", cv_TotalCases.head(10)) print("\nOutput sorted data based on the column named 'Total recovered' in descending order: \n", cv_TotalRecovered.head(10)) print("\nOutput sorted data based on the column named 'Total cases per 1M pop.' in descending order: \n", cv_TotalCasesPerMillion.head(10)) print("\nOutput sorted data based on the column named 'Total deaths' in descending order: \n", cv_TotalDeaths.head(10)) print("\nOutput sorted data based on the column named 'New cases' in descending order: \n", cv_NewCases.head(10)) print("\nOutput sorted data based on the column named 'New deaths' in descending order: \n", cv_NewDeaths.head(10)) #Graph of top 10 'Total cases' x = cv_TotalCases.head(10) x1 = x["Country"] y1 = x["Total cases"] print(x1) print(y1) plt.figure(1,figsize=(12,5)) plt.title('Top 10 countries based on Total cases - [Total countries effected as of today = {}]'.format(cv.shape[0])) plt.suptitle(today) plt.xlabel("Countries") plt.ylabel("Total cases") plt.bar(x1,y1, color="Red") plt.grid(True) plt.show() #Graph of top 10 'Total recovered' x = cv_TotalRecovered.head(10) x1 = x["Country"] y1 = x["Total recovered"] print(x1) print(y1) plt.figure(2,figsize=(12,5)) plt.title("Top 10 countries based on Total recovered") plt.suptitle(today) plt.xlabel("Countries") plt.ylabel("Total recovered") plt.bar(x1,y1, color="limegreen") plt.grid(True) plt.show() #Graph of top 10 'Total cases per 1M pop.' x = cv_TotalCasesPerMillion.head(10) x1 = x["Country"] y1 = (x["Total cases per 1M pop."]) print(x1) print(y1) plt.figure(3,figsize=(12,5)) plt.title("Top 10 countries based on Total cases per million pop.") plt.suptitle(today) plt.xlabel("Countries") plt.ylabel("Total cases per million pop.") plt.bar(x1,y1, color="cornflowerblue") plt.grid(True) plt.show() #Graph of top 10 'Total deaths' x = cv_TotalDeaths.head(10) x1 = x["Country"] y1 = (x["Total deaths"]) print(x1) print(y1) plt.figure(4,figsize=(12,5)) plt.title("Top 10 countries based on Total deaths") plt.suptitle(today) plt.xlabel("Countries") plt.ylabel("Total deaths") plt.bar(x1,y1, color="dimgray") plt.grid(True) plt.show() #Graph of top 10 'New cases' x = cv_NewCases.head(10) x1 = x["Country"] y1 = (x["New cases"]) print(x1) print(y1) plt.figure(5,figsize=(12,5)) plt.title("Top 10 countries based on New cases") plt.suptitle(today) plt.xlabel("Countries") plt.ylabel("New cases") plt.bar(x1,y1, color="lightcoral") plt.grid(True) plt.show() #Graph of top 10 'New deaths' x = cv_NewDeaths.head(10) x1 = x["Country"] y1 = (x["New deaths"]) print(x1) print(y1) plt.figure(6,figsize=(12,5)) plt.title("Top 10 countries based on New deaths") plt.suptitle(today) plt.xlabel("Countries") plt.ylabel("New deaths") plt.bar(x1,y1, color="dimgrey") plt.grid(True) plt.show()
f45471a04eef4398d02bbe12151a6b031b394452
jrahman1988/PythonSandbox
/myFunction_printMultipleTimes.py
427
4.3125
4
''' Functions are reusable pieces of programs. They allow us to give a name to a block of statements, allowing us to run that block using the specified name anywhere in your program and any number of times. This is known as calling the function. ''' def printMultipleTimes(message:str, time:int): print(message * time) #Call the functions by passing parameters printMultipleTimes("Hello ",2) printMultipleTimes("Hello ",5)
b2965c970bce71eee39841548b95ab6edf37d99b
jrahman1988/PythonSandbox
/myLambdaFunction.py
1,212
4.125
4
''' A lambda function is a small anonymous function. A lambda function can take any number of arguments, but can only have one expression. Syntax lambda arguments : expression ''' #define the lambda function sentence = "I bought a bike, from a bike store, she bought a bike from amazon, they bought a bike from bike stores" myLambdaFunction = lambda argument: argument.count("bike") #here we are calling the lambda function: passing the 'sentence' as parameter and lamda function is taking it as an 'argument' print("Total number of 'bike' word appeared = ", myLambdaFunction(sentence)) # filePath = "~/Desktop/Learning/Sandbox/PythonSandbox/Data/README.md" # readFile=open('~/Desktop/Learning/Sandbox/PythonSandbox/Data/README.md', 'r') with open('/home/jamil/Desktop/Learning/Sandbox/PythonSandbox/Data/README.md') as f: readFile = f.readlines() print (readFile) print(readFile.count("Spark")) sparkAppeared = lambda s: s.count("Spark") apacheAppeared = lambda s: s.count("Apache") hadoopAppeared = lambda s: s.count("Hadoop") print("Spark word appeared = ", sparkAppeared(readFile)) print("Apache word appeared = ", apacheAppeared(readFile)) print("Hadoop word appeared = ", hadoopAppeared(readFile))
a1a0da1d51bcc8c4f129c11550512d1221c9de92
jrahman1988/PythonSandbox
/myPandas_WriteToCSV.py
3,426
4.125
4
''' The Series and DataFrame class of Pandas has an instance method called to_csv() which allows to write the DF to a file either in .xlsx, .txt or .csv format ''' import pandas as pd desired_width=320 pd.set_option('display.width', desired_width) pd.set_option('display.max_columns',100) #Read the pokemon_data.csv from the file system and transform into a DataFrame using read_csv() method df = pd.read_csv("~/Desktop/Learning/Sandbox/PythonSandbox/Data/pokemon_data.csv") print("\nOutput the header index of the DF: \n", df.columns) #Now add a column named 'Total by adding all the columns value containg numeric values df['Total'] = df['HP'] + df['Attack'] + df['Defense'] + df['Sp. Atk'] + df['Sp. Def'] + df['Speed'] print("\nOutput the tail of the file with newly added column: \n",df.tail()) #Now write the new DF into a csv file with the added column + the index on first column df = df.to_csv("~/Desktop/Learning/Sandbox/PythonSandbox/Data/modified_withIndex.csv") ###------------------------------------------------------------------------------------### #Read the pokemon_data.csv from the file system and transform into a DataFrame using read_csv() method df1 = pd.read_csv("~/Desktop/Learning/Sandbox/PythonSandbox/Data/pokemon_data.csv") print("\nOutput the header index of the DF: \n", df1.columns) #Now add a column named 'Total by adding all the columns value containg numeric values df1['Total'] = df1['HP'] + df1['Attack'] + df1['Defense'] + df1['Sp. Atk'] + df1['Sp. Def'] + df1['Speed'] print("\nOutput the tail of the file with newly added column: \n",df1.tail()) #Now write the new DF into a csv file with the added column with no index on first column df1 = df1.to_csv("~/Desktop/Learning/Sandbox/PythonSandbox/Data/modified_withoutIndex.csv", index=False) ###------------------------------------------------------------------------------------### #Read the pokemon_data.csv from the file system and transform into a DataFrame using read_csv() method df2 = pd.read_csv("~/Desktop/Learning/Sandbox/PythonSandbox/Data/pokemon_data.csv") print("\nOutput the header index of the DF: \n", df2.columns) #Now add a column named 'Total by adding all the columns value containg numeric values df2['Total'] = df2['HP'] + df2['Attack'] + df2['Defense'] + df2['Sp. Atk'] + df2['Sp. Def'] + df2['Speed'] print("\nOutput the tail of the file with newly added column: \n",df2.tail()) #Now write the new DF into a xlsx file with the added column with no index on first column df2 = df2.to_excel("~/Desktop/Learning/Sandbox/PythonSandbox/Data/modified_withoutIndex.xlsx", index=False) ###------------------------------------------------------------------------------------### #Read the pokemon_data.csv from the file system and transform into a DataFrame using read_csv() method df3 = pd.read_csv("~/Desktop/Learning/Sandbox/PythonSandbox/Data/pokemon_data.csv") print("\nOutput the header index of the DF: \n", df3.columns) #Now add a column named 'Total by adding all the columns value containg numeric values df3['Total'] = df3['HP'] + df3['Attack'] + df3['Defense'] + df3['Sp. Atk'] + df3['Sp. Def'] + df3['Speed'] print("\nOutput the tail of the file with newly added column: \n",df3.tail()) #Now write the new DF into a xlsx file with the added column with no index on first column df3 = df3.to_csv("~/Desktop/Learning/Sandbox/PythonSandbox/Data/modified_withoutIndex.txt", index=False, sep='\t')
ecc2b9c95284d27fc838148c5c3c0bd4f6d90358
jrahman1988/PythonSandbox
/myPandas_FindValuesFromCSV.py
642
4.03125
4
''' Find and output all rows contain a specific value in a specific column using df.loc() ''' import pandas as pd desired_width=320 pd.set_option('display.width', desired_width) pd.set_option('display.max_columns',100) #Read the pokemon_data.csv from the file system and transform into a DataFrame using read_csv() method df = pd.read_csv("~/Desktop/Learning/Sandbox/PythonSandbox/Data/pokemon_data.csv") #Locate and output all rows contain a specific value in a specific column print(df.loc[df['Type 1'] == "Fire"]) #Locate and output all rows contain a specific value in a specific column print("\n",df.loc[df['Name'] == "Charmander"])
56056f96ce0b1faa68b0937b60bbbf8294e1f3d8
jrahman1988/PythonSandbox
/myWebScrapping3.py
870
3.578125
4
''' Webscraping to GET the html response, then PARSE and fetch the content, FIND the tables, CONSTRUCT a DF ''' import pandas as pd import requests from bs4 import BeautifulSoup from tabulate import tabulate from pandas import DataFrame # GET the response from the web page using requests library # url = 'https://www.trackcorona.live' # res = requests.get("https://www.trackcorona.live") # res = requests.get("https://worldpopulationreview.com/countries/saarc-countries/") # res = requests.get("https://ourworldindata.org/coronavirus") res = requests.get("https://www.worldometers.info/coronavirus/") # PARSE and fetch content using BeutifulSoup method of bs4 library soup = BeautifulSoup(res.content,'lxml') table = soup.find_all('table') df = pd.read_html(str(table))[0] print(tabulate(df[0], headers='keys', tablefmt='psql')) df = df[0] print(df) print(df.info())
76e7dc6bfa340596459f1a535e4e2e191ea483bc
jrahman1988/PythonSandbox
/myOOPclass3.py
2,017
4.46875
4
''' There is way of organizing a software program which is to combine data and functionality and wrap it inside something called an object. This is called the object oriented programming paradigm. In this program we'll explore Class, behaviour and attributes of a class ''' #Declaring a class named Mail and its methods (behaviours). All methods of a class must have a default parameter 'self' class Mail(): #Class variable to count 'how many' types of Mail instances created numberOfObjectsCreated = 0 #Init method to create an instance (object) by passing an object name def __init__(self, name): """Initilializes the data""" self.name = name print("Initializing an {}".format(self.name)) Mail.numberOfObjectsCreated +=1 def destinationOfMail(self, type: str): self.type = type def costOfMail(self, cost: int): self.cost = cost def sizeOfmail(self, size: int): self.size = size def getDescription(self): print("The type of the mail is ", self.type) print("The cost of the mail is ", self.cost) print("The size of the mail is ", self.size) @classmethod def countOfMail(count): """Prints number of Mail objects""" print("Created objects of Mail class are = {}".format(count.numberOfObjectsCreated)) #Create an object of the class Mail named domesticMail dMail = Mail("domesticMail") dMail.destinationOfMail("Domestic") dMail.costOfMail(10) dMail.sizeOfmail("Large") dMail.getDescription() #Create an object of the class Mail named internationalMail iMail = Mail("internationalMail") iMail.destinationOfMail("International") iMail.costOfMail(99) iMail.sizeOfmail("Small") iMail.getDescription() #How many Mail objects were created (here we are using class variable 'numberOfObjectsCreated' print("Total Mail objects created = {} ".format(Mail.numberOfObjectsCreated)) #How many Mail objects were created (here we are using class method 'countOfMail()' Mail.countOfMail()
dafcc8c5cf58608ca4bba1a27dda168aa2980533
jrahman1988/PythonSandbox
/myWebScrapping_fmAPIsample.py
1,171
4.09375
4
''' Webscraping to GET the html response, then PARSE and fetch the content, FIND the tables, CONSTRUCT a DF We'll use here the pandas.read_html(), which returns a list of data frames. According to the PANDAS doc: "This function searches for <table> elements and only for <tr> and <th> rows and <td> elements within each <tr> or <th> element in the table. <td> stands for “table data”. Document URL: https://pandas.pydata.org/pandas-docs/version/0.23.4/generated/pandas.read_html.html ''' import pandas as pd import requests # GET the response from the web page using requests library, response = a list of dfs req = "http://api.coronatracker.com/v3/stats/worldometer/country" df = pd.read_json(req) print(df) df.to_csv("~/Desktop/Learning/Sandbox/PythonSandbox/Data/dataFrom_myWebScrapping_fmAPI.csv", index=False) ''' # This webpage has multiple tables, we will use the index [1] to fetch the table of our interest, the respose is a list of dfs df = pd.read_html(req.content)[0] print(type(df)) print(df.head(10)) print(df.tail(10)) print(df.info()) df.to_csv("~/Desktop/Learning/Sandbox/PythonSandbox/Data/dataFrom_myWebScrapping_fmAPI.csv", index=False) '''
cf3158ef73377ac7fe644d4637c21ae1501d804b
jrahman1988/PythonSandbox
/myStringFormatPrint.py
551
4.25
4
#Ways to format and print age: int = 20 name: str = "Shelley" #Style 1 where format uses indexed parameters print('{0} was graduated from Wayne State University in Michigan USA when she was {1}'.format(name,age)) #Style 2 where 'f' is used as f-string print(f'{name} was graduated from Wayne State University in Michigan USA when she was {age}') #Style 3 where format's parameters can mbe changed as local variable print('{someOne} was graduated from Wayne State University in Michigan USA when she was {someAge}'.format(someOne=name,someAge=age))
75d2d53e7ca3ab189536b69d71a45abaa9c16435
moyales/Data-Visualization
/Exercises/Ch15/15_1_cubes.py
617
4.09375
4
import matplotlib.pyplot as plt # 15.1: Plot the first 5 cubic numbers; # Then plot the first 5000 cubic numbers. # Simple list of first 5 cube numbers # x = [1, 2, 3, 4, 5] # y = [1, 8, 27, 64, 125] # plt.plot(x, y, linewidth=3) # First 5000 cubes x_val = list(range(1, 5001)) y_val = [x**3 for x in x_val] plt.scatter(x_val, y_val, c=y_val, cmap=plt.cm.Reds, edgecolor='none', s=20) # Set chart title and label axes. plt.title("Cube Numbers", fontsize=24) plt.xlabel("Value", fontsize=14) plt.ylabel("Cube of Value", fontsize=14) # Set sie of tick labels plt.tick_params(axis='both', labelsize=14) plt.show()
892e851f82ea063d2c0dfff954ca742a16e6108a
YuZih/MystanCodeProJects
/stanCode_projects/Breakout Game/breakout.py
2,734
3.984375
4
""" stanCode Breakout Project Adapted from Eric Roberts's Breakout by Sonja Johnson-Yu, Kylie Jue, Nick Bowman, and Jerry Liao. Here is the basic version of breakout game. """ from campy.gui.events.timer import pause from breakoutgraphics import BreakoutGraphics FRAME_RATE = 1000 / 120 # 120 frames per second NUM_LIVES = 3 # Number of attempts def main(): # initial window graphics = BreakoutGraphics() # other settings lives = NUM_LIVES vy = graphics.get_ball_dy() vx = graphics.get_ball_dx() # animation while True: pause(FRAME_RATE) if lives > 0 and graphics.num_bricks > 0: # first-click to start game if graphics.to_start is True: graphics.ball.move(vx, vy) # rebound when ball bumps into bricks or the paddle if graphics.detect_bump() is True: # when near bricks if graphics.ball.y < graphics.bricks_bottom: vy = - vy # change the vertical direction of ball # when near paddle and the distance from top of paddle to bottom of ball is less than dy # let ball not run along the paddle elif graphics.ball.y + graphics.ball.height - graphics.paddle.y < graphics.get_ball_dy(): vy = - vy # change the vertical direction of ball # when ball touches the left and right side of wall if graphics.ball.x <= 0 or (graphics.ball.x + graphics.ball.width) > graphics.window.width: vx = - vx # change the horizontal direction of ball # when ball touches the upper side of wall if graphics.ball.y <= 0: vy = - vy # change the vertical direction of ball # when ball falls down out of window elif graphics.ball.y >= graphics.window.height: lives -= 1 if lives > 0: pause(FRAME_RATE * 100) graphics.lives_label.text = str(lives) + ' lives left!' graphics.show_lives_left() pause(FRAME_RATE * 100) graphics.window.remove(graphics.lives_label) pause(FRAME_RATE * 100) graphics.reset_ball() pause(FRAME_RATE * 100) else: break # when win if graphics.num_bricks == 0: pause(FRAME_RATE * 50) graphics.game_win() # when lose elif lives == 0: pause(FRAME_RATE * 50) graphics.game_over() if __name__ == '__main__': main()
0ca475cbfde5171ee06d55f0a4bb3e7209e33794
aastrand/aoc2015
/14/solve.py
1,427
3.5
4
#!/usr/bin/env python3 import re import sys from collections import defaultdict def run_reindeer(speed, time, resting_time, run_time): total = time + resting_time laps = run_time // total rest = run_time - (laps * total) return laps * time * speed + (speed * (rest if rest < time else time)) def race(reindeer, run_time): max_distance = 0 animal = None for r in reindeer: distance = run_reindeer(r[1], r[2], r[3], run_time) if distance > max_distance: max_distance = distance animal = r[0] return animal, max_distance # Vixen can fly 8 km/s for 8 seconds, but then must rest for 53 seconds. RACE_RE = re.compile('^([A-Za-z]+) can fly (\d+) km/s for (\d+) seconds, but then must rest for (\d+) seconds.$') def parse(f): reindeer = [] for l in open(f, 'r'): m = RACE_RE.match(l.strip()) if m: reindeer.append((m.group(1), int(m.group(2)), int(m.group(3)), int(m.group(4)))) return reindeer def test(): assert 1120 == run_reindeer(14, 10, 127, 1000) assert 1056 == run_reindeer(16, 11, 162, 1000) def main(f): test() reindeer = parse(f) print(race(reindeer, 2503)) score_map = defaultdict(int) for s in range(2504): animal, distance = race(reindeer, s) score_map[animal] += 1 print(score_map) if __name__ == '__main__': sys.exit(main(sys.argv[1]))
dc3af3cadad3ebf5b5afc2f35a84716f47fb50dc
DAFFA4EVER/Jeruk-Nipis
/1.0/data_user.py
1,384
3.75
4
user_list = [] id = 0 class user: def __init__(self, uid, name, age, film, food, address): self.uid = uid self.name = name self.age = age self.film = film self.food = food self.address = address def save_list(): global user_list data_list = open(r'1.0\user_data_list', 'w') for i in user_list: data = { "uid": f'{i.uid}', "name": f'{i.name}', "age": f'{i.age}', "film": f'{i.film}', "food": f'{i.food}', "address": f'{i.address}' } data_list.write(str(data)) data_list.close() def create(): global user_list, id uid = "" name = input("Please insert your name : ") age = int(input("Please insert your age : ")) flag = input("Do you have favorite movies/film? ") film = "" food = "" address = "" if flag == "yes" or flag == "y": film = input("Please insert your favorite film : ") flag = input("Do you have favorite food? ") if flag == "yes" or flag == "y": food = input("Please insert your favorite food : ") uid = f'{id + 1}' user_list.append(user(uid, name, age, film, food, address)) save_list() return user_list def see_user(): global user_list n=0 for i in user_list: print(f"{n+1} : {i.name}") n = n + 1
2f8eb7b30968c7c80f498a119cb82663c0eed891
RomanYes/RomanYevchackProject
/HW_2_3.py
95
3.90625
4
a=int(input("Your number a:")) b=int(input("Your number b:")) a,b=b,a print("Your answer:",a,b)
5bde28c19b34d4d55a137b2ef673df2bcfe58f71
yuanhsin8311/Spark-Projects
/Tutorial/Airline Delay Analysis/airline.py
2,023
3.6875
4
sc # Set up the file paths for data # If it's on the local system append file:// to the beginning of the path # If it's on hdfs append hdfs:// airlinePath = "hdfs:///user/yuanhsin/flightDelaysData/airlines.csv" airportPath = "hdfs:///user/yuanhsin/flightDelaysData/airports.csv" flightPath = "hdfs:///user/yuanhsin/flightDelaysData/flights.csv" # Use SparkContext initialized by pyspark to load the data # sc: SparkContext variable ie. the connection to spark # textFile: tell sparkContext to load data from a text file into memory airlines=sc.textFile(airlinesPath) # Airlines is an RDD print airlines # View the full dataset airlines.collect() # Get the first line airlines.first() # Get the first 10 lines airlines.take(10) # Count airlines.count() ## Transformation and Actions: filter-> transformation -> (1)filter the header (2)split by comma (3)convert alrline code to integer take -> action # Filter the header "Description" out # Filter function takes a boolean function # The filter returns another RDD airlinesWoHeader = airlines.filter(lambda x:"Description" not in x) print airlinesWoHeader airlinesWoHeader.take(10) # RDD knows their lineage; RDD holds the metadata # Data is processed only when the users request a result(take actions) # lazy evaluation ->fast computation # spark will keep a record of the series of transformations requested by the user -> efficiently group the transformation and execute airlinesParsed=airlinesWoHeader.map(lambda x:x.split(",")).take(10) print airlinesParsed # map(function) airlines.map(len).take(10) def notHeader(row): return "Description" not in row airlines.filter(notHeader).take(10) # Chain transformations together airlines.filter(notHeader).map(lambda x: x.split(',')).take(10) # Use Python libraries import csv from StringIO import StringIO def split(line): reader = csv.reader(StringIO(line)) return reader.next() airlines.filter(notHeader).map(split).take(10)
2b1a371545c766dc0cab3e981c587382d4d4aead
mimipeshy/pramp-solutions
/code/arr_i_and_element_equality.py
1,749
3.75
4
""" Array Index & Element Equality Given a sorted array arr of distinct integers, write a function indexEqualsValueSearch that returns the lowest index i for which arr[i] == i. Return -1 if there is no such index. Analyze the time and space complexities of your solution and explain its correctness. input: arr = [-8,0,2,5] output: 2 # since arr[2] == 2 input: arr = [-1,0,3,6] output: -1 # since no index in arr satisfies arr[i] == i. """ # O(logn) time # O(1) space def index_equals_value_search(arr): low = 0 high = len(arr) - 1 while low <= high: mid = low + (high - low) // 2 if arr[mid] == mid: # check if the previous index also equals its element while mid > 0 and arr[mid - 1] == mid - 1: mid -= 1 return mid elif arr[mid] < mid: low = mid + 1 else: high = mid - 1 return -1 def index_equals_value_search(arr): low = 0 high = len(arr) - 1 while low <= high: mid = low + (high - low) // 2 if arr[mid] == mid and (mid == 0 or arr[mid - 1] != mid - 1): return mid elif arr[mid] < mid: low = mid + 1 else: # includes case where arr[mid] > mid # or arr[mid - 1] == mid - 1 high = mid - 1 return -1 def binary_search(arr): low = 0 high = len(arr) - 1 while low <= high: mid = low + (high - low) // 2 if arr[mid] == mid: return mid elif arr[mid] < mid: low = mid + 1 else: high = mid - 1 return -1 def index_equals_value_search(arr): low = 0 high = len(arr) - 1 ans = binary_search(arr) # check if the previous index also equals its element while ans > 0 and arr[ans - 1] == ans - 1: ans -= 1 return ans
2b2895c74d089f7685f264b6e70a7ab8b090dc6e
mimipeshy/pramp-solutions
/code/award_budget_cuts.py
1,967
3.671875
4
""" Award Budget Cuts The awards committee of your alma mater (i.e. your college/university) asked for your assistance with a budget allocation problem they’re facing. Originally, the committee planned to give N research grants this year. However, due to spending cutbacks, the budget was reduced to newBudget dollars and now they need to reallocate the grants. The committee made a decision that they’d like to impact as few grant recipients as possible by applying a maximum cap on all grants. Every grant initially planned to be higher than cap will now be exactly cap dollars. Grants less or equal to cap, obviously, won’t be impacted. Given an array grantsArray of the original grants and the reduced budget newBudget, write a function findGrantsCap that finds in the most efficient manner a cap such that the least number of recipients is impacted and that the new budget constraint is met (i.e. sum of the N reallocated grants equals to newBudget). input: grantsArray = [2, 100, 50, 120, 1000], newBudget = 190 output: 47 # and given this cap the new grants array would be # [2, 47, 47, 47, 47]. Notice that the sum of the # new grants is indeed 190 """ # O(nlogn) time # O(1) space def find_grants_cap(grantsArray, newBudget): n = len(grantsArray) grantsArray.sort() # Initiate variables to track how much of the budget is left # and how many grants left to cover amount_budget_left = float(newBudget) count_grants_left = n for i in range(n): money_req = grantsArray[i] * count_grants_left if money_req >= amount_budget_left: # Case 1: we'd need more money than we have left # meaning we need to set the cap at this point cap = amount_budget_left / count_grants_left return cap # Case 2: we have more money left to allocate # so we don't set the cap yet amount_budget_left -= grantsArray[i] count_grants_left -= 1 return newBudget
8788d7516ed9bd589cd392a1af5c37f453a8796c
mimipeshy/pramp-solutions
/code/array_quadruplet.py
1,798
3.859375
4
""" Array Quadruplet (meaning 4Sum) Given an unsorted array of integers arr and a number s, write a function findArrayQuadruplet that finds four numbers (quadruplet) in arr that sum up to s. Your function should return an array of these numbers in an ascending order. If such a quadruplet doesn’t exist, return an empty array. Note that there may be more than one quadruplet in arr whose sum is s. You’re asked to return the first one you encounter (considering the results are sorted). Explain and code the most efficient solution possible, and analyze its time and space complexities. input: arr = [2, 7, 4, 0, 9, 5, 1, 3], s = 20 output: [0, 4, 7, 9] # The ordered quadruplet of (7, 4, 0, 9) # whose sum is 20. Notice that there # are two other quadruplets whose sum is 20: # (7, 9, 1, 3) and (2, 4, 9, 5), but again you’re # asked to return the just one quadruplet (in an # ascending order) """ # O(n^3) time # O(1) space def find_array_quadruplet(nums, target): n = len(nums) if n < 4: return [] nums.sort() for i in range(n - 3): if i != 0 and nums[i] == nums[i - 1]: continue for j in range(i + 1, n - 2): if j != 1 and nums[j] == nums[j - 1]: continue curr_sum = nums[i] + nums[j] target_complement = target - curr_sum low = j + 1 high = n - 1 while low < high: curr_complement = nums[low] + nums[high] if curr_complement > target_complement: high -= 1 elif curr_complement < target_complement: low += 1 else: return [nums[i], nums[j], nums[low], nums[high]] return []
34653fdfffaacb579ad87ee2d590c6ae37c5bb71
mimipeshy/pramp-solutions
/code/drone_flight_planner.py
1,903
4.34375
4
""" Drone Flight Planner You’re an engineer at a disruptive drone delivery startup and your CTO asks you to come up with an efficient algorithm that calculates the minimum amount of energy required for the company’s drone to complete its flight. You know that the drone burns 1 kWh (kilowatt-hour is an energy unit) for every mile it ascends, and it gains 1 kWh for every mile it descends. Flying sideways neither burns nor adds any energy. Given an array route of 3D points, implement a function calcDroneMinEnergy that computes and returns the minimal amount of energy the drone would need to complete its route. Assume that the drone starts its flight at the first point in route. That is, no energy was expended to place the drone at the starting point. For simplicity, every 3D point will be represented as an integer array whose length is 3. Also, the values at indexes 0, 1, and 2 represent the x, y and z coordinates in a 3D point, respectively. input: route = [ [0, 2, 10], [3, 5, 0], [9, 20, 6], [10, 12, 15], [10, 10, 8] ] output: 5 # less than 5 kWh and the drone would crash before the finish # line. More than `5` kWh and it’d end up with excess e """ # O(n) time # O(1) space def calc_drone_min_energy(route): energy_balance = 0 energy_deficit = 0 prev_altitude = route[0][2] for i in range(1, len(route)): curr_altitude = route[i][2] energy_balance += prev_altitude - curr_altitude if energy_balance < 0: energy_deficit += abs(energy_balance) energy_balance = 0 prev_altitude = curr_altitude return energy_deficit def calc_drone_min_energy(route): max_altitude = route[0][2] for i in range(1, len(route)): if route[i][2] > max_altitude: max_altitude = route[i][2] return max_altitude - route[0][2]
c7f8cc285310a8dac2a2b4e62cf76f476323c2a8
kwitte2232/CS121
/pp6/permutationencryption.py
1,703
3.96875
4
import sys # Skeleton code for problem https://uchicago.kattis.com/problems/permutationencryption # # Make sure you read the problem before editing this code. # # You should focus only on implementing the solve() function. # Do not modify any other code. def encrypt(string, perm): ''' Takes a string and a list with the keys for the permutation Returns the permutation Inputs: string: a string perm: a list Returns: A string with the permuted message ''' n = len(perm) end = len(string) -1 substrings = [] ss = '' for i, letter in enumerate(string): ss = ss + letter if len(ss) == n: substrings.append(ss) ss = '' if i == end: while len(ss)%n != 0: ss = ss + ' ' substrings.append(ss) print(substrings) swapped = [] for sub in substrings: swap_string = [0]*n swap_indices = {} for i, letter in enumerate(sub): new_dex = perm[i] - 1 swap_indices[new_dex] = letter for dex in swap_indices: swap_string[dex] = swap_indices[dex] new_string = ''.join(swap_string) swapped.append(new_string) perm_string = ''.join(swapped) return perm_string if __name__ == "__main__": tokens = sys.stdin.readline().split() while int(tokens[0]) != 0: n = int(tokens[0]) permutations = [int(x) for x in tokens[1:]] assert(len(permutations) == n) message = sys.stdin.readline().strip() print("'{}'".format(encrypt(message, permutations))) tokens = sys.stdin.readline().split()
22070230157e2d2621270485f3820923f3949923
kwitte2232/CS121
/pa3/cps.py
14,879
3.578125
4
# CS121 A'15: Current Population Survey (CPS) # # Functions for mining CPS data # # Kristen Witte from pa3_helpers import read_csv, plot_histogram import statistics # Constants HID = "h_id" AGE = "age" GENDER = "gender" RACE = "race" ETHNIC = "ethnicity" STATUS = "employment_status" HRWKE = "hours_worked_per_week" EARNWKE = "earnings_per_week" FULLTIME_MIN_WORKHRS = 35 COLUMN_WIDTH = 18 COLUMN_SEP = "|" MEAN_INDEX = 0 MEDIAN_INDEX = 1 MIN_INDEX = 2 MAX_INDEX = 3 def make_input_dict(filename): ''' Builds an input dictionary that contains the input Morg data and the code files Inputs: filename: csv file the morg_data file name An example of input_dict is shown below: {'morg':'data/morg_d14_mini.csv', 'gender_codes':'data/gender_code.csv', 'race_codes':'data/race_code.csv', 'ethnic_codes':'data/ethnic_code.csv', 'employment_codes':'data/employment_status_code.csv'} Returns: morg_input_dict ''' morg_input_dict = {'morg': ' ', 'gender_codes':'data/gender_code.csv', 'race_codes':'data/race_code.csv', 'ethnic_codes':'data/ethnic_code.csv', 'employment_codes':'data/employment_status_code.csv'} morg_input_dict['morg'] = filename return morg_input_dict def build_morg_dict(input_dict): ''' Build a dictionary that holds a set of CPS data Inputs: input_dict: dict An example of input_dict is shown below: {'morg':'data/morg_d14_mini.csv', 'gender_codes':'data/gender_code.csv', 'race_codes':'data/race_code.csv', 'ethnic_codes':'data/ethnic_code.csv', 'employment_codes':'data/employment_status_code.csv'} Returns: ID_dict: dictionary with HIDs as keys and values as a dictionary of their information, with keys as general terms and values as the individuals information ''' HID = "h_id" AGE = "age" GENDER = "gender" RACE = "race" ETHNIC = "ethnicity" STATUS = "employment_status" HRWKE = "hours_worked_per_week" EARNWKE = "earnings_per_week" sub_dict = make_subdict[input_dict] inds = sub_dict['data'] categories = [HID, AGE, GENDER, RACE, ETHNIC, STATUS, HRWKE, EARNWKE] l = len(categories) ID_dict = {} for i in inds: hid = i[0] info = {} for c in range(1,l): info[categories[c]] = i[c] descriptions = list(info.keys()) for desc in descriptions: code = info[desc] if desc == STATUS or desc == ETHNIC or desc == RACE or desc == GENDER: curr_search = sub_dict[desc] if code == '': code = '0' for elem in curr_search: cd = elem[0] if code == cd: str_code = elem[1] info[desc] = str_code elif desc == AGE or desc == HRWKE: if code != '': str_to_int = int(code) info[desc] = str_to_int elif desc == EARNWKE: if code != '': earn = float(code) info[desc] = earn else: info[desc] = code ID_dict[hid] = info return ID_dict def create_histogram(morg_dict, var_of_interest, num_buckets, min_val, max_val): ''' Create a histogram using a list Inputs: morg_dict: a MORG dictionary var_of_interest: string (e.g., HRWKE or EARNWKE) num_buckets: number of buckets in the histogram min_val: the minimal value (lower bound) of the histogram max_val: the maximal value (upper bound) of the histogram Returns: freq: list that represents a histogram ''' freq = [0]*num_buckets if num_buckets == 0: return freq else: diff = max_val - min_val step_size = diff/num_buckets step_dict = {} step_list = [] top = min_val for s in range(num_buckets): r = [] bottom = top top = top + step_size r.append(bottom) r.append(top) step_list.append(r) l = len(step_list) for i, step in enumerate(step_list): bot_r = step[0] top_r = step[1] for hid in morg_dict: info = morg_dict[hid] work = info[STATUS] if work == "Working": ft = info[HRWKE] if ft >= 35: value = info[var_of_interest] if i < l-1: if value >= bot_r and value < top_r: freq[i] = freq[i] + 1 elif i == l-1: if value >= top_r: freq[i] = freq[i] + 1 return freq def make_subdict(input_dict): ''' Builds a dictionary that contains the input Morg data and the code files as values with keys of the provided Constants for each attribute (GENDER, RACE, etc) Inputs: input_dict: dict An example of input_dict is shown below: {'morg':'data/morg_d14_mini.csv', 'gender_codes':'data/gender_code.csv', 'race_codes':'data/race_code.csv', 'ethnic_codes':'data/ethnic_code.csv', 'employment_codes':'data/employment_status_code.csv'} Returns: sub_dict: dict ''' data_csv = input_dict['morg'] gen_csv = input_dict['gender_codes'] rc_csv = input_dict['race_codes'] ec_csv = input_dict['ethnic_codes'] emc_csv = input_dict['employment_codes'] csvs = [data_csv, gen_csv, rc_csv, ec_csv, emc_csv] names = ['data', GENDER, RACE, ETHNIC, STATUS] n = len(csvs) sub_dict = {} for n in range(n): f = csvs[n] read = read_csv(f, False) sub_dict[names[n]] = read return sub_dict def calculate_unemployment_rates(filename_list, age_range, var_of_interest): ''' Output a nicely formatted table for the unemployment rates for the specified age_rage, further broken down by different categories in var_of_interest for the data specified in each file in filename_list Inputs: filename_list: a list of MORG dataset file names age_rage: a tuple consisted of two integers var_of_interest: string (e.g., AGE, RACE or ETHNIC) Returns: list ''' year_brkdn = make_year_brkdn(filename_list, age_range, var_of_interest) chart_l = make_chart_list(year_brkdn) chart = make_chart(chart_l) return chart def make_year_brkdn(filename_list, age_range, var_of_interest): ''' Builds a dictionary with the years for each file in filename_list as keys and values as a list of unemployment rates for each sub group that satsifies age_range and var_of_interest. The values in the list correspond to an alphabetized list of each sub group. Ex: value = [0.0, 0.4] corresponds to the unemployment rates for "Female" and "Male" if the var_of_interest is GENDER Inputs: filename_list: a list of MORG dataset file names age_rage: a tuple consisted of two integers var_of_interest: string (e.g., AGE, RACE or ETHNIC) Returns: year_brkdn: dict ''' ages = list(age_range) low_bound = ages[0] up_bound = ages[1] data = {} input_dict = {} for f in filename_list: input_dict = make_input_dict('data/' + f) morg_dict = build_morg_dict(input_dict) year = f[6:8] data[year] = morg_dict sub_dict = make_subdict(input_dict) years = list(data.keys()) hids_for_year = {} num_persons = 0 for year in data: hids_of_int = [] all_info = data[year] for hid in all_info: info = all_info[hid] status = info[STATUS] curr_age = info[AGE] if (status == "Working" or status == "Looking" or status == "Layoff"): if curr_age >= low_bound and curr_age <= up_bound: hids_of_int.append(hid) num_persons += 1 for yr in years: if yr == year: hids_for_year[yr] = hids_of_int codes = sub_dict[var_of_interest] total_variants = [] for code in codes: description = code[1] total_variants.append(description) year_brkdn = {} for year in data: breakdown = {} curr_hids = hids_for_year[year] all_info = data[year] counts = {} for hid in curr_hids: info = all_info[hid] status = info[STATUS] if status == "Looking" or status == "Layoff": voi = info[var_of_interest] if voi not in counts: counts[voi] = 1 else: counts[voi] = counts[voi] + 1 for voi in counts: breakdown[voi] = (counts[voi])/num_persons curr_variants = list(breakdown.keys()) diffs = [] for var in total_variants: if var not in curr_variants: diffs.append(var) if len(diffs) > 0: for d in diffs: breakdown[d] = 0.0 year_brkdn[year] = breakdown return year_brkdn def make_chart_list(year_brkdn): ''' Builds a list of lists with each element in the list corresponding to what will be a row in the final chart. No processing of the chart specifications (see make_chart) Inputs: year_brkdn: a dictionary containing the unemployment rates for each sub_group for each year_brkdn Returns: chart_l: list ''' yrs_l = list(year_brkdn.keys()) yrs_l.sort() sorted_data = {} all_stats = {} all_cats = [] for year in year_brkdn: data = [] data_pairs = [] all_stats = year_brkdn[year] all_cats = list(all_stats.keys()) all_cats.sort() cats_values = list(all_stats.items()) all_cats_values = [list(pair) for pair in cats_values] for cat in all_cats: for pair in all_cats_values: if cat == pair[0]: data.append(pair[1]) data_pairs.append(pair) sorted_data[year] = data num_cats = len(all_cats) chart_l = [] for i in range(num_cats): yr_cat_org = [all_cats[i]] for year in yrs_l: curr_data = sorted_data[year] data_point = curr_data[i] yr_cat_org.append(data_point) chart_l.append(yr_cat_org) yrs_l.insert(0, "Year") chart_l.insert(0, yrs_l) return chart_l def make_chart(chart_l, COLUMN_SEP, COLUMN_WIDTH): ''' Builds a list of lists with each element in the list corresponding to what will be a row in the final chart. Processes the strings to format the chart Inputs: chart_l: list of lists COLUMN_SEP: "|" COLUMN_WIDTH: 18 Returns: chart: list of lists ''' COLUMN_WIDTH = 18 COLUMN_SEP = "|" chart = [] for i, row in enumerate(chart_l): sub_chart = [COLUMN_SEP] insert = [] for inputs in row: print(inputs) inp = inputs t = type(inp) if t == float: inp = str(inp) curr_chars = len(inp) space = [''] diff = COLUMN_WIDTH - curr_chars) if diff < 0: num_chars = abs(diff) inp = inputs[:diff] else: while len(space) <= diff: space.append(' ') spaces = ''.join(space) insert.append(inp) insert.append(spaces) insert.append(COLUMN_SEP) insert.append('\n') insert_string = ''.join(insert) sub_chart.append(insert_string) row_insert = ''.join(sub_chart) chart.append(row_insert) for row in chart: print(row) return chart def calculate_weekly_earnings_stats_for_fulltime_workers(morg_dict, gender, race, ethnicity): ''' Returns a 4-element list of earnings statics (mean, median, min, and max) for all fulltime workers who satisfy the given query criteria Inputs: morg_dict: dict gender: query criteria for gender race: query criteria for race ethnicity: query criteria for ethnicity Returns: A 4-element list ''' MEAN_INDEX = 0 MEDIAN_INDEX = 1 MIN_INDEX = 2 MAX_INDEX = 3 data_list = [0.0]*4 given_stats = [gender, race, ethnicity] dex_of_all = [0]*3 for i, s in enumerate(given_stats): if s == "All" or s == "ALL": dex_of_all[i] = True else: dex_of_all[i] = False tot_persons = len(morg_dict) hids_of_int = [] for hid in (morg_dict): add = [0]*3 info = morg_dict[hid] work = info[STATUS] hours = info[HRWKE] print(work) if work == "Working" and hours >= 35: gen = info[GENDER] rc = info[RACE] en = info[ETHNIC] stats = [gen, rc, en] for i in range(3): if dex_of_all[i] == True: add[i] = 1 elif stats[i] == given_stats[i]: add[i] = 1 elif given_stats[i] == "Other": if (stats[i] != "WhiteOnly" and stats[i] != "BlackOnly" and stats[i] != "AmericanIndian/AlaskanNativeOnly" and stats[i] != "AsianOnly" and stats[i] != "Hawaiian/PacificIslanderOnly"): add[i] = 1 else: add[i] = 0 total = sum(add) if total == 3: hids_of_int.append(hid) if len(hids_of_int) == 0: return data_list else: earnings = [] for hid in hids_of_int: info = morg_dict[hid] earned = info[EARNWKE] earnings.append(earned) num_persons = len(hids_of_int) mean = float(sum(earnings)/num_persons) med = float(statistics.median(earnings)) min_earned = float(min(earnings)) max_earned = float(max(earnings)) data_list[MEAN_INDEX] = mean data_list[MEDIAN_INDEX] = med data_list[MIN_INDEX] = min_earned data_list[MAX_INDEX] = max_earned return data_list
fa778ff469feb683a8373a688ef68ef6a31626c1
kwitte2232/CS121
/pa6/model.py
16,266
4.0625
4
# CS121 Linear regression # # Kristen Witte, kwitte import numpy as np from asserts import assert_Xy, assert_Xbeta ############################# # # # Our code: DO NOT MODIFY # # # ############################# def prepend_ones_column(A): ''' Add a ones column to the left side of an array Inputs: A: a numpy array Output: a numpy array ''' ones_col = np.ones((A.shape[0], 1)) return np.hstack([ones_col, A]) def linear_regression(X, y): ''' Compute linear regression. Finds model, beta, that minimizes X*beta - Y in a least squared sense. Accepts inputs with type array Returns beta, which is used only by apply_beta Examples -------- >>> X = np.array([[5, 2], [3, 2], [6, 2.1], [7, 3]]) # predictors >>> y = np.array([5, 2, 6, 6]) # dependent >>> beta = linear_regression(X, y) # compute the coefficients >>> beta array([ 1.20104895, 1.41083916, -1.6958042 ]) >>> apply_beta(beta, X) # apply the function defined by beta array([ 4.86363636, 2.04195804, 6.1048951 , 5.98951049]) ''' assert_Xy(X, y, fname='linear_regression') X_with_ones = prepend_ones_column(X) # Do actual computation beta = np.linalg.lstsq(X_with_ones, y)[0] return beta def apply_beta(beta, X): ''' Apply beta, the function generated by linear_regression, to the specified values Inputs: model: beta as returned by linear_regression Xs: 2D array of floats Returns: result of applying beta to the data, as an array. Given: beta = array([B0, B1, B2,...BK]) Xs = array([[x11, x12, ..., x0K], [x21, x22, ..., x1K], ... [xN1, xN2, ..., xNK]]) result will be: array([B0+B1*x11+B2*x12+...+BK*x1K, B0+B1*x21+B2*x22+...+BK*x2K, ... B0+B1*xN1+B2*xN2+...+BK*xNK]) ''' assert_Xbeta(X, beta, fname='apply_beta') # Add a column of ones X_incl_ones = prepend_ones_column(X) # Calculate X*beta yhat = np.dot(X_incl_ones, beta) return yhat def read_file(filename): ''' Read data from the specified file. Split the lines and convert float strings into floats. Assumes the first row contains labels for the columns. Inputs: filename: name of the file to be read Returns: (list of strings, 2D array) ''' with open(filename) as f: labels = f.readline().strip().split(',') data = np.loadtxt(f, delimiter=',', dtype=np.float64) return labels, data ############### # # # Your code # # # ############### def calculate_R2(curr_yhats, y_test, y_mean): ''' Compute the R2 value for given data Inputs: curr_yhats = numpy array derived from apply_beta y_test: numpy array for the dependent variable. Either from training.csv or testing.csv depending on find_R2 y_mean: average of y* derived from either training.csv or testing.csv depending on find_R2 Returns: r2: R^2 value as a float ''' numerator = [] denominator = [] for i, yn in enumerate(y_test): yhat = curr_yhats[i] top = (yn - yhat)**2 bottom = (yn - y_mean)**2 numerator.append(top) denominator.append(bottom) sum_numerator = sum(numerator) sum_denominator = sum(denominator) r2 = 1 - (sum_numerator/sum_denominator) return r2 def find_R2(x_train, y_train, y_mean, x_test = None, y_test = None): ''' Find the R2 value for given data using linear_regression and apply_beta Inputs: x_train: independent variable data from training.csv y_train: dependent variab data from training.csv y_mean: average of y* (default from training.csv or if x_test is not None, testing.csv) Optional Inputs: x_test: independent variable data from testing.csv y_test: dependent variab data from testing.csv Returns: r2: R^2 value as a float ''' if x_test is not None: beta = linear_regression(x_train, y_train) yhats = apply_beta(beta, x_test) r2 = calculate_R2(yhats, y_test, y_mean) else: beta = linear_regression(x_train, y_train) yhats = apply_beta(beta, x_train) r2 = calculate_R2(yhats, y_train, y_mean) return r2 def build_K_arrays(dex, cat, temp_arrays, r2s, base_category, remaining, base_num_rows, y_train, y_mean, temp_train_data = None, y_test = None): ''' Builds numpy arrays of K categories. Used in a for loop in get_R2 "Arbitrary" Inputs: dex: current index cat: current category temp_arrays: empty dictionary to store numpy arrays for K categories r2s: empty dicitonary to store R2s for K categories base_category: numpy array for K = 1 remaing: numpy array for the reamining data after removing base_category data base_num_rows: numer of rows in base_category y_train: numpy array for the y data from training.csv y_mean: average of the y values for either the training.csv or the testing.csv (if y_test is not None) Optional inputs: temp_train_data: dictionary storing the training numpy array for K categories y_test: numpy array for the y data from testing.csv Returns: r2s: filled dictionary of R2s for K categories temp_arrays: filled dictionary of numpy arrays for K categories If y_test is None: temp_data: numpy array for K categories (solely for training data) ''' temp_data = np.empty([base_num_rows, 0]) temp_data = np.append(temp_data, base_category, axis = 1) additional_category = remaining[:,[dex]] temp_data = np.append(temp_data, additional_category, axis = 1) temp_arrays[cat] = temp_data if y_test is None: r2 = find_R2(temp_data, y_train, y_mean) else: r2 = find_R2(temp_train_data, y_train, y_mean, temp_data, y_test) r2s[cat] = r2 if y_test is None: return r2s, temp_arrays, temp_data else: return r2s, temp_arrays def ratio_less_than_threshold(all_variables, compiled_data, threshold): ''' Determines if the increase in K R^2 from K-1 R^2 is greater than threshold Inputs: all_variables: a list of all the current column categories compiled_data: dictionary of the categories and their R^2 values threshold: float Returns: Boolean If Boolean is True, also returns the K-1 category ''' assert len(list(compiled_data.keys())) >= 2 assert threshold is not None k_categories = ','.join(all_variables) k_1_variables = all_variables[:-1] k_subtract_1_categories = ','.join(k_1_variables) k_r2 = compiled_data[k_categories] k_subtract_1_r2 = compiled_data[k_subtract_1_categories] percent_increase = (k_r2/k_subtract_1_r2) - 1 if percent_increase < threshold: return True, k_subtract_1_categories else: return False, None def get_R2(col_names, data_train, num_vars, data_test = None, threshold = None): ''' Returns the R2 squared value(s) using linear regression Inputs: col_names: a list of the column names from the read in data_test data_train: a numpy array of the data from training.csv num_vars: string indicating amount of data to include in the linear regression Options:"Single": R^2 value for each column "Multi": R^2 value for all columns "BiVar": R^2 value for pairs of columns "Arbitrary": R^2 value for K columns Optional Inputs: *Only used when num_vars is "Arbitrary"* data_test: a numpy array of the data from testing.csv threshold: minimum percent that R^2 must increase by with increasing K Returns: Options:"Single": a list of the R^2 values "Multi": a list of the R^2 value (single element) "BiVar": two single element lists. One of the Category pair with the highest R^2. One of the R^2 value for that pair. "Arbitrary": a dictionary of 1 <= K <= N categories and the corresponding R^2 value for K. If threshold is not None: a second dictionary with the K-1 categories and the corresponding R^2 value such that the percent increase of K R^2 to K-1 R^2 is less than threshold. ''' total_cols = len(col_names) y_train = data_train[:, (total_cols - 1)] all_training = data_train[: , 0:total_cols - 1] y_mean = (y_train.sum()/len(y_train)) if data_test is not None: y_test = data_test[:, (total_cols - 1)] all_test = data_test[: , 0:total_cols - 1] y_mean = (y_test.sum()/len(y_test)) num_categories = total_cols - 1 r2_values = [] if num_vars == "Single": for i in range(num_categories): curr_train_category = all_training[:,[i]] if data_test is not None: curr_test_category = all_test[:,[i]] r2 = find_R2(curr_train_category, y_train, y_mean, curr_test_category, y_test) else: r2 = find_R2(curr_train_category, y_train, y_mean) r2_values.append(r2) return r2_values elif num_vars == "Multi": r2 = find_R2(all_training, y_train, y_mean) r2_values.append(r2) return r2_values elif num_vars == "BiVar": paired_r2 = {} for i in range(num_categories): base_category = all_training[:,[i]] for j in range(i+1, num_categories): paired_category = all_training[:,[j]] bivar_data = np.concatenate((base_category, paired_category), axis = 1) r2 = find_R2(bivar_data, y_train, y_mean) pair = col_names[i] + ":" + col_names[j] paired_r2[pair] = r2 highest_r2 = 0 for pair in paired_r2: r2 = paired_r2[pair] if r2 >= highest_r2: highest_r2 = r2 highest_pair = [pair] r2_values.append(highest_r2) return highest_pair, r2_values elif num_vars == "Arbitrary": compiled_data = {} if data_test is not None: single_test_r2s = get_R2(col_names, data_train, "Single", data_test) single_r2s = get_R2(col_names, data_train, "Single") highest_r2 = 0 for i, r2 in enumerate(single_r2s): if r2 >= highest_r2: highest_r2 = r2 highest_category = col_names[i] index_highest_category = i all_variables = [highest_category] category_names = highest_category if data_test is not None: compiled_data[category_names] = single_test_r2s[index_highest_category] else: compiled_data[category_names] = single_r2s[index_highest_category] base_train_category = all_training[:,[index_highest_category]] base_train_rows = len(base_train_category) if data_test is not None: base_test_category = all_test[:,[index_highest_category]] base_test_rows = len(base_test_category) remaining_training = np.delete(all_training, [index_highest_category], axis = 1) if data_test is not None: remaining_test = np.delete(all_test, [index_highest_category], axis = 1) remaining_cols = [x for x in col_names if x != highest_category] remaining_cols.pop() #remove the totals column num_remaining = len(remaining_cols) best = {} #for thresholding for i in range(num_remaining): temp_train_arrays = {} #temp arrays temp_test_arrays = {} train_r2s = {} #r2s test_r2s = {} for j, category in enumerate(remaining_cols): if category not in all_variables: train_r2s, temp_train_arrays, temp_train_data = build_K_arrays(j, category, temp_train_arrays, train_r2s, base_train_category, remaining_training, base_train_rows, y_train, y_mean) if data_test is not None: test_r2s, temp_test_arrays = build_K_arrays(j, category, temp_test_arrays, test_r2s, base_test_category, remaining_test, base_test_rows, y_train, y_mean, temp_train_data, y_test) highest_r2 = 0 for category in train_r2s: current_r2 = train_r2s[category] if current_r2 >= highest_r2: highest_r2 = current_r2 highest_category = category #From the train data base_train_category = temp_train_arrays[highest_category] if data_test is not None: base_test_category = temp_test_arrays[highest_category] all_variables.append(highest_category) category_names = ','.join(all_variables) if data_test is not None: compiled_data[category_names] = test_r2s[highest_category] else: compiled_data[category_names] = train_r2s[highest_category] if threshold != None: x, final_key = ratio_less_than_threshold(all_variables, compiled_data, threshold) if not best: if x: best[final_key] = compiled_data[final_key] if threshold != None: return compiled_data, best return compiled_data def print_dict_data(d): ''' Prints out the info from a dictionary in an easy to read format Inputs: d: dictionary Returns: prints out data from dictionary. ''' for key in d: print(key + " : " + str(d[key])) def make_table(r2_values, names): ''' Makes a table for the provided r2_values and the k_categories Inputs: r2_values: list of R2 values names: list of names **indices of names and r2_values must match Returns: prints out a nicely formatted table. ''' COLUMN_WIDTH = 18 COLUMN_SEP = "|" names.insert(0, "Category") r2_values.insert(0, "R2") table = [] for i, name in enumerate(names): insert = [] insert = make_column(name, insert, COLUMN_WIDTH, COLUMN_SEP) insert = make_column(r2_values[i], insert, COLUMN_WIDTH, COLUMN_SEP) insert.append('\n') table.append(insert) for row in table: line = ''.join(row) print(line) def make_column(current_input, insert, COLUMN_WIDTH, COLUMN_SEP): ''' Makes a column insert for table Inputs: current_input: a the category name or r2 values insert: an empty list COLUMN_WIDTH: integer COLUMN_SEP: string Returns: insert: a single element list. Element is the string for that column ''' inp = current_input t = type(inp) if t == np.float64 or t == int: inp = str(inp) curr_characters = len(inp) space = [' '] diff = COLUMN_WIDTH - curr_characters if diff < 0: num_characters = abs(diff+1) inp = inp[:diff] else: while len(space) < diff: space.append(' ') spaces = ''.join(space) insert.append(inp) insert.append(spaces) insert.append(COLUMN_SEP) return insert
dd9c666ab17a5afeb3e6c0fa1bdd1b27bb7f78ce
CSC1-1101-TTh9-S21/lab-week3
/perimeter.py
594
4.3125
4
# Starter code for week 3 lab, parts 1 and 2 # perimeter.py # Prof. Prud'hommeaux # Get some input from the user. a=int(input("Enter the length of one side of the rectangle: ")) b=int(input("Enter the length of the other side of the rectangle: ")) # Print out the perimeter of the rectangle c = a + a + b + b print("The perimeter of your rectangle is: ", c) # Part 1: Rewrite this code so that it gets the sides from # command line arguments (i.e., Run... Customized) # Part 2: Rewrite this code so that there are two functions: # a function that calculates the perimeter # a main function
daf9244c272a6fcf552cf3fc20c6a65566fa2d43
HarshalBhoir/hackerrank-solutions
/python_practice/print_function.py
343
3.59375
4
if __name__ == '__main__': n = int(input()) i = 1 numbers = [] while i <= n: numbers.append(str(i)) i+=1 start = 0 count = len(numbers) total = "" total =str(total) for number in numbers: total+=numbers[start] if start <= count: start+=1 print(total)