blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
16fc19a79917a581f4ef3571485471a159f1d3e4
TudroVilin/PYTHON
/numeromayor.py
300
3.828125
4
print("Introduzca el primer número:") n1=int(input()) print("Introduzca el segundo valor:") n2=int(input()) if(n1>n2): print(str(n1)+" es mayor que "+str(n2)) elif(n1==n2): print(str(n1)+" y "+str(n2)+" son iguales") else: print(str(n2)+" es mayor que "+str(n1)) print("Fin de programa")
b307cae1c33261177b08212dd16864603cf0122a
Matt711/anime_reference
/anime_reference/anime_objects/utils.py
2,284
3.53125
4
from re import search, findall from bs4 import BeautifulSoup from typing import List def clean_str_list(list_str: List[str], search_str: str = '"(.*)"') -> List[str]: """ Description: "Cleans" a list of strings using regex based on on a search string. Parameters: ----------- list_str (List[str]): list of strings search_str (str): regex search string Returns: -------- List[str]: the "cleaned" str """ clean_list = [] for string in list_str: result = search(search_str, string) try: clean_list.append(result.group(1).strip()) except AttributeError: clean_list.append(string) return clean_list def format_episode_links(prefix_url: str, links: List[str]) -> List[str]: """ Description: Formats the episode links from Ex: "/wiki/Plot_of_Naruto" to "https://naruto.fandom.com/wiki/Plot_of_Naruto" Parameters: ----------- prefix_url (str): prefix string url links (List[str]): unformatted list of string links Returns: -------- List[str]: list of formatted string links """ return [prefix_url+search('a href="(.*)" ', string).group(1) for string in links] def clean_text(text: str) -> str: """ Description: Cleans the test information of links and other unecessary html tags and characters Parameters: ----------- text (str): a string Returns: -------- str: a "cleaned" string """ text = findall("<p>(.*)\n</p>", text) text = str(text) text = text.replace("<p>", "") text = text.replace("</p>", "") text = text.replace(" ", " ") text = text.replace(".,", ".") text = text.replace("['", "") text = text.replace("']", "") text = text.replace(".',", ".") text = text.replace('<p class="mw-empty-elt">', "") # text = text.replace(', ', "") text = text.replace("\\", "") text = text.replace(" '", " ") soup = BeautifulSoup(text, "html.parser") tags = list(map(str, soup.find_all("a"))) for tag in tags: try: result = search('title="(.*)"', tag) text = text.replace(tag, result.group(1)) except AttributeError: continue return text
c996ec67271d7686e47eabff7dc9633b261596ff
ushadevipatturaj/HyperSkillPythonCodesScenarios
/venv/Data/Coffee_Machine.py
749
4.3125
4
# Write your code here print("Write how many ml of water the coffee machine has:") water = int(input()) print("Write how many ml of milk the coffee machine has:") milk = int(input()) print("Write how many grams of coffee beans the coffee machine has:") coffee = int(input()) print("Write how many cups of coffee you will need:") cups_of_coffee = int(input()) coffee_available = min(water // 200, coffee // 15, milk // 50) if cups_of_coffee == coffee_available: print("Yes, I can make that amount of coffee") elif cups_of_coffee < coffee_available: print("Yes, I can make that amount of coffee (and even ", (coffee_available - cups_of_coffee) ," more than that)") else: print("No, I can make only ",coffee_available ," cups of coffee")
576f2d139cab34f1d5c01f3e8921d2f43d66d26b
ak795/acm
/spoj/SCAVHUNT/1.py
382
3.59375
4
for i in range(int(input())): print('Scenario #{0}:'.format(i + 1)) nonroot = set() d = {} for j in range(int(input()) - 1): s = input().split() d[s[0]] = s[1] nonroot.add(s[1]) for root in d: if root not in nonroot: break; while root in d: print(root) root = d[root] print(root) print()
4fedfa4819f2529b8b84a92a8e20cc1d1b9a1b73
michalkalinowski-/StdProblems
/optimal_decision.py
5,453
4.125
4
# F O X E S A N D H E N S # Example of defining an optimal strategy when playing a game based on a random event # ----------------------------------------------------------------------------------- # This code is derived from one of the homeworks I completed for Peter Norvig's # *Design of Computer Programs* class on Udacity.com # Some utility functions provided by Peter Norvig # # Problem description: # -------------------- # You play a game of Foxes and Hens. Threre is a deck consisting of cards of two different # kinds: foxes and hens. They're shuffled randomly, but you know how many foxes and hens there # are. If you draw a Hen you add it to the "yard"(score pending). If you draw a Fox it eats all # the Hens from the yard (resets pending score). You can decide to collect the hens from the yard # at any point (you add pending score to your score) but you discard the next card from the deck. # The goal is to score as many hens as possible. # # Solution: # --------- # This is a classic *decision under uncertainity* problem so game theory approach is used. # State consists of number of points, points pending and a collection of cards remaining. # Function of the Utility of the state is defined recursivly in terms of Quality of actions # [wait, gather] you can take to advance to the next state. Goal is to arrive to the state # with max score based on the probability of drawing a Fox. # Imports from functools import update_wrapper import random # Simple Cashing def decorator(d): "Make function d a decorator: d wraps a function fn." def _d(fn): return update_wrapper(d(fn), fn) update_wrapper(_d, d) return _d @decorator def memo(f): """Decorator that caches the return value for each call to f(args). Then when called again with same args, we can just look it up.""" cache = {} def _f(*args): try: return cache[args] except KeyError: cache[args] = result = f(*args) return result except TypeError: # some element of args refuses to be a dict key return f(args) _f.cache = cache return _f # Utilities def pop_card(cards): """ draw a card and remove it from the deck possible choices for kind are random, H, F """ card = random.choice(cards) cards = cards.replace(card, "", 1) return card, cards # defines n_foxes = 7 n_hens = 45 def foxes_and_hens(strategy, foxes=n_foxes, hens=n_hens): """Play the game of foxes and hens.""" # A state is a tuple of (score-so-far, number-of-hens-in-yard, deck-of-cards) state = (score, yard, cards) = (0, 0, 'F'*foxes + 'H'*hens) while cards: action = strategy(state) state = (score, yard, cards) = do(action, state) return score + yard def do(action, state): "Apply action to state, returning a new state." score, yard, cards = state card, cards = pop_card(cards) if action == 'wait': return (score, yard+1, cards) if card == 'H' else (score, 0, cards) elif action == 'gather': return (score + yard, 0, cards) else: raise ValueError('Wrong action') # Evaluation of the strategy def average_score(strategy, N=1000): return sum(foxes_and_hens(strategy) for _ in range(N)) / float(N) # Optimal Solution: # ---------------- def strategy(state): """ My ultimate-optimal strategy function """ # define Expected Utility as quality of performing an action on a state def EU(action): return Q(state, action) return max(['wait', 'gather'], key=EU) @memo def U(state): """ Returns utility of the state """ score, yard, cards = state if not len(cards): return score + yard else: return max(Q(state, action, U) for action in hens_actions(state)) def Q(state, action, fU=U): """ Returns quality for a given action """ (score, yard, cards) = state Pfx = p_fox(state) if action == 'gather': return Pfx * fU((score + yard, 0, cards[1:])) + \ (1-Pfx) * fU((score + yard, 0, cards[:-1])) elif action == 'wait': return Pfx * fU((score, 0, cards[1:])) + \ (1-Pfx) * fU((score, yard +1, cards[:-1])) else: raise ValueError def p_fox(state): """ Compute probability of drawing a fox given a deck of cards""" _, _, cards = state return cards.count('F')/float(cards.count('H')+cards.count('F')) if cards.count('H') else 1 # make sure no division by 0 will take place def hens_actions(state): """ return a touple of actions possible to execute. When there are no hens it's useless to gather""" _, yard, _ = state return ['wait', 'gather'] if yard else ['wait'] # Testing results def tests(): error = 0.001 assert (p_fox((0, 0, 'FFHH')) - 0.5) <= error assert (p_fox((0, 0, 'FFFHH')) - 0.75) <= error assert set(hens_actions((0, 0,'FFHH'))) == set(('wait')) assert set(hens_actions((0, 1,'FFHH'))) == set(('wait', 'gather')) # tests below by Peter Norvig, thanks! gather = do('gather', (4, 5, 'F'*4 + 'H'*10)) assert (gather == (9, 0, 'F'*3 + 'H'*10) or gather == (9, 0, 'F'*4 + 'H'*9)) wait = do('wait', (10, 3, 'FFHH')) assert (wait == (10, 4, 'FFH') or wait == (10, 0, 'FHH')) # Print some stuff: print "Gathered", average_score(strategy), "/", n_hens, "Hens on average" print "Game played thousand times" print "Yay!"
0016e4334d67696ac139e3cdb1e4226b33a3c178
Shimpa11/PythonTutorial
/session44.py
3,114
4.4375
4
""" Unsupervised Learning We have data but no labels !! Classification will be numerically done by the model and we later name those classes Output is not known for observations in the dataset k-means clustering k here denotes number of classes we expect from model after classification ---------- X Y P ---------- 1 1 A 1 0 B 0 2 C 2 4 D 3 5 E ---------- we have above dataset as an example to work on 5 observations each observation has 2 data points But we don't know what class it belongs to """ """ # we need to put data points mathematically step1: Assumption of data points or centroids no of data paoints is number of classes K-represnts number of classes after classification k-2, 2 datapoints Assume any 2 datapoints randomly from the given dataset as CENTROIDS egA(1,1) and C(0,2) Step2: calculate distance of each point from centroids Eucilidean Distance formula sqrt[square (x2-x1)+square(y2-y1)] X Y P C1(1,1) C2(0,2) -------------------- 1 1 A 0 1.4 1 0 B 1 2.2 0 2 C 1.4 0 2 4 D 3.2 2.8 3 5 E 4.5 4.2 Step3: Arrange points as per distance from centroids P nearest to -------------------- A C1 B C1 C C2 D C2 E C2 looking the data above A and B nearest to C! should be in One cluster and C D and E who are nearest to C2 should be in other cluster Even now we dont know if above assumption is correct or not we need to be sure about our assumption Step 4: so recheck again with new centroids and these new centroids shall be mean of previous cluster cluster 1 mean= mean of A nd B cluster 2 mean= mean of C D and E data points C1 Mean=(1+1)/2, (1+0)/2=(1,0.5) C2 Mean=(0+2+3)/3,(2+4+5)/3=(1.7,3.7) X Y P C1 Mean C2 Mean distance(1,0.5) distance(1.7,3.7) -------------------- 1 1 A 0.5 2.7 1 0 B 0.5 3.7 0 2 C 1.8 2.4 2 4 D 3.6 0.5 3 5 E 4.9 1.9 P nearest to -------------------- A C1 B C1 C C1 D C2 E C2 one data point has been shifted from C2 to C1 still for surity , to hold it true if we get the same result twice, we stop the futher computation go on computing till we get the same result twice NC1=(1+1+0)/3,(1+0+2)/3=(0.7,1) NC2=(2+3)/2,(4+5)/2=(2.5,4.5) X Y P NC1 Mean NC2 Mean distance(0.7,1) distance(2.5,4.5) -------------------- 1 1 A 0.3 3.8 1 0 B 1.04 4.7 0 2 C 1.2 3.5 2 4 D 3.2 0 3 5 E 4.6 0.70 X Y P nearest to -------------------- 1 1 A C1 1 0 B C1 0 2 C C1 2 4 D C2 3 5 E C2 got the same result (0.7,1) class1 (2.5,4.5) class2 """ import matplotlib.pyplot as plt X=[1,1,0,2,3] Y=[1,0,2,4,5] plt.scatter(X,Y) plt.xlabel("X-Axis") plt.ylabel("Y-Axis") plt.legend() plt.title("K-means Clustering") plt.show() class KMeans: def __init__(self,clusters=2): self.clusters=clusters print("KMeans Model Created") def fit(self,X,Y): pass def predict(self,X,Y): pass
16f0c1c00d457e412636c393f9e050d8929f9c7a
gusatb/split-py
/game.py
19,603
4
4
"""Game logic for Split. Rules: Game starts with a square of neutral colored lines. (Pie rule for first move?) Players take turns drawing line segments of their color with each endpoint touching preexisting lines and not crossing any lines. Endpoints of lines cannot be placed on intersections. If both endpoints are on lines of the players color, one of the areas is filled with their color (opponents choice). A line may not be played if one of the resulting areas is less than the min area limit. Player with more area colored wins when no more legal moves remain. """ import math import struct EPSILON = 1e-5 # Not used in this file class GamePlayer: """Represents a player. A human playing locally making moves through the UI should use this class as is. Extend these functions for AI, remote play, or alternate UI. Attributes: local_human: Whether to wait for a move through the UI or call get_move. """ def __init__(self, local_human=True): self.local_human = local_human def choose_color(self, state): """Returns whether to choose to play as Red. Args: state: GameState. """ pass def get_move(self, state): """Returns a GameMove for the current color. Args: state: GameState to move in. """ pass def update_color_choice(self, choose_red): """Makes update to internal state given other players move. Args: choose_red: Whether the other player chose red. """ pass def update_move(self, move): """Makes update to internal state given other players move. Args: move: Move made by other player. """ pass class GamePoint: """Represents a point in space. Attributes: x: X coordinate. y: Y coordinate. lines: List of GameLine which have an endpoint at this point. """ def __init__(self, x, y): self.x = x self.y = y self.lines = [] def is_at_xy(self, x, y): return self.x == x and self.y == y def is_at(self, point): """Returns whether or not the given point is at the same location as this.""" return self.is_at_xy(point.x, point.y) def pair(self): """Returns tuple containing x and y coordinates.""" return self.x, self.y def distance(self, point): """Returns distance between given point and this.""" return math.sqrt((self.y - point.y)**2 + (self.x - point.x)**2) class GameLine: """Represents a line segment. Attributes: endpoints: List of two GamePoints. color: Color/Owner of line. A: Helper for calculating intersections. B: Helper for calculating intersections. C: Helper for calculating intersections. """ def __init__(self, p1, p2, color=None, add_self_to_points=False): """Creates a GameLine. Args: p1: GamePoint which is an endpoint of this line. p2: GamePoint which is an endpoint of this line. color: Color/Owner of line. add_self_to_points: Whether to add this line to lines attribute of GamePoints p1, p2. """ self.endpoints = [p1, p2] self.color = color # Helpers for calculating intersections self.A = (p1.y - p2.y) self.B = (p2.x - p1.x) self.C = -1 * (p1.x*p2.y - p2.x*p1.y) if add_self_to_points: for ep in self.endpoints: assert self not in ep.lines ep.lines.append(self) def intersection(self, line): """Returns tuple of coordinates of the intersection of given line and this, or None if no intersection. Args: line: Line to calculate intersection with. """ D = self.A * line.B - self.B * line.A Dx = self.C * line.B - self.B * line.C Dy = self.A * line.C - self.C * line.A if D != 0: x = Dx / D y = Dy / D intersect_point = GamePoint(x, y) if self.contains(intersect_point) and line.contains(intersect_point): return intersect_point return None def slope(self): """Returns slope of this line.""" return (self.endpoints[0].y - self.endpoints[1].y) / (self.endpoints[0].x - self.endpoints[1].x + EPSILON) def midpoint(self): """Returns GamePoint which is the midpoint of this line.""" return GamePoint((self.endpoints[0].x + self.endpoints[1].x)/2, (self.endpoints[0].y + self.endpoints[1].y)/2) def length(self): """Returns length of this line.""" return self.endpoints[0].distance(self.endpoints[1]) def closest_point(self, point): """Returns GamePoint on this line which is closes to given point. Args: point: Point to find closest point on this line to. """ line_slope = (self.endpoints[0].y - self.endpoints[1].y)/(self.endpoints[0].x - self.endpoints[1].x + EPSILON) perp_slope = -1 / (line_slope + EPSILON) on_line_x = (perp_slope * point.x - point.y - line_slope * self.endpoints[0].x + self.endpoints[0].y)/(perp_slope - line_slope) on_line_y = perp_slope * (on_line_x - point.x) + point.y on_line = GamePoint(on_line_x, on_line_y) on_line_dists = [ep.distance(on_line) for ep in self.endpoints] line_length = self.length() if max(on_line_dists) > line_length: # Endpoint is closest point_dists = [ep.distance(point) for ep in self.endpoints] closest_point = self.endpoints[min(enumerate(point_dists), key=lambda x: x[1])[0]] return closest_point else: return on_line def contains(self, point): """Returns whether given point is (approximately) on this line.""" dists = [x.distance(point) for x in self.endpoints] return abs(sum(dists) - self.length()) <= 0.01 def atan2(p1, p2): """Returns angle between horizontal and the line between the given points. Args: p1: GamePoint representing one endpoint of line to find angle of. p2: GamePoint representing one endpoint of line to find angle of. """ theta = math.atan((p1.y - p2.y)/(p1.x - p2.x + EPSILON)) if abs(p2.x - p1.x) < EPSILON or p2.x < p1.x: theta += math.pi return theta class GameArea: """Represents an area (will always be a convex polygon). Attributes: points: List of points in clockwise or counterclockwise order. state: GameState this area exists in. color: Color for area score: Geometric area of this GameArea. """ def __init__(self, points, state, color=None): self.points = points self.state = state self.color = color self.score = self.calculate_score() def calculate_score(self): """Returns geometric area of this GameArea.""" points = self.points n = len(points) term1 = sum([self.points[i].x * self.points[(i+1)%n].y for i in range(n)]) term2 = sum([self.points[i].y * self.points[(i+1)%n].x for i in range(n)]) return 0.5 * (term1 - term2) def contains(self, point, ignore_lines=[]): """Returns whether or not point is within the bounds of this GameArea. This function calculates if each bordering point has a clear path to the given point. Therefore ignore_lines should include all lines in the area, since they may obstruct a clear path to a bordering point. Args: point: Point to determine. ignore_lines: List of lines to ignore. """ for p in self.points: if not self.state.clear_path(p, point, ignore_lines): return False return True class GameMove: """Represents a move in the game. Attributes: line_move: Whether or not this move is a new line being placed. p1: Endpoint 1 of new line. p1_line: Line that will be split by p1 once move is played. p2: Endpoint 2 of new line. p2_line: Line that will be split by p2 once move is played. area: List of points """ def __init__(self, p1=None, p1_line=True, p2=None, p2_line=True, area=None): self.line_move = area is None self.p1 = p1 self.p1_line = p1_line self.p2 = p2 self.p2_line = p2_line self.area = area def serialize(self): """Returns byte array representing GameMove object. First byte is 0 if line_move else 1. If line move: four floats are packed representing p1 x,y and p2 x,y. Else: int is packed (num of points) followed by 2 floats per point. """ pack_types = '=' pack_objs = [] # Move type pack_types += 'i' pack_objs.append(0 if self.line_move else 1) if self.line_move: pack_types += 'ffff' pack_objs.extend([self.p1.x, self.p1.y, self.p2.x, self.p2.y]) else: pack_types += 'i' pack_objs.append(len(self.area.points)) pack_types += 'ff' * len(self.area.points) for p in self.area.points: pack_objs.extend([p.x, p.y]) return struct.pack(pack_types, *pack_objs) @classmethod def deserialize(cls, byte_array, state): """Returns GameMove represented by byte_array. Args: byte_array: Array of bytes representing GameMove. state: GameState object. """ line_move = struct.unpack_from('=i', byte_array, offset=0)[0] == 0 if line_move: all_coordinates = struct.unpack_from('=ffff', byte_array, offset=4) p1 = GamePoint(*all_coordinates[:2]) p2 = GamePoint(*all_coordinates[2:]) # Find lines p1_line, p2_line = None, None for line in state.lines: if not p1_line and line.contains(p1): p1_line = line elif not p2_line and line.contains(p2): p2_line = line if p1_line and p2_line: break return GameMove(p1=p1, p1_line=p1_line, p2=p2, p2_line=p2_line) else: n_points = struct.unpack_from('=i', byte_array, offset=4)[0] all_coordinates = struct.unpack_from('=' + 'ff'*n_points, byte_array, offset=8) points = [state.get_point_at_location(*all_coordinates[i*2:i*2+2]) for i in range(n_points)] color = 3 - state.next_player area = GameArea(points, state, color) return GameMove(area=area) class GameState: """Represents the state of the game. Attributes: width: Width/Height of the game area. min_score: Minimum amount a move can score / Largest unscored area. area: List of GameAreas which have already been filled. lines: List of all GameLines played in game (including the initial lines). next_player: Player to draw a line or choose an area. area_split_line: If not None, next move should choose an area on either side of this GameLine. scores: Current score for each player. """ def __init__(self): self.width = 10 self.min_score = 5 self.areas = [] # Scored and filled areas. self.lines = [] self.next_player = 1 self.area_split_line = None # If not None, then next turn is area selection self.scores = [0, 0] self.new_game() def new_game(self): """Reset game.""" p1 = GamePoint(0, 0) p2 = GamePoint(0, self.width) p3 = GamePoint(self.width, self.width) p4 = GamePoint(self.width, 0) self.game_area = GameArea([p1, p2, p3, p4], self) self.lines = [ GameLine(p1, p2, -1, add_self_to_points=True), GameLine(p2, p3, -1, add_self_to_points=True), GameLine(p3, p4, -1, add_self_to_points=True), GameLine(p4, p1, -1, add_self_to_points=True), ] self.scores = [0, 0] def get_point_at_location(self, x, y): temp_p = GamePoint(x, y) dists = {} for l in self.lines: for p in l.endpoints: if p not in dists: dists[p] = p.distance(temp_p) p_dists = list(dists.items()) return min(p_dists, key=lambda x: x[1])[0] def get_game_area(self): """Returns GameArea containing the entire playable area.""" return self.game_area def is_legal_move(self, move): """Returns whether given move is legal to make. Args: move: GameMove to determine legality of. """ if not move.line_move: # TODO(gusatb): Add test to ensure points are legal area. if not move.area: print('Illegal move: GameArea must be chosen.') return move.area else: if self.area_split_line is not None: print('Illegal move: Line move is set and area split is supplied.') return False if not move.p1 or not move.p2: print('Illegal move: Line move must have two points.') return False # A move is legal if the created line does not cross any other lines, # and each point is on a unique line. temp_line = GameLine(move.p1, move.p2) for line in self.lines: # Check if either point already exists for ep in line.endpoints: if move.p1.is_at(ep) or move.p2.is_at(ep): print('Illegal move: Cannot move on an existing endpoint.') return False # Check if points are shared by a line if (move.p1_line == line or move.p2_line == line) and temp_line.slope() == line.slope(): print('Illegal move: Both points are on the same line.') return False # Check for intersection if temp_line.intersection(line) and move.p1_line != line and move.p2_line != line: print('Illegal move: Crosses an existing line.') return False # Check the area the line crosses midpoint = temp_line.midpoint() for area in self.areas: if area.contains(midpoint): print('Illegal move: Cannot move in scored area.') return False return True def clear_path(self, p1, p2, ignore_lines=[]): """Returns whether or not there is a clear path from p1 to p2. Every line in this state is checked for an intersection with the line between p1 and p2 except line in ignore_lines. Args: p1: One of the GamePoints to check a clear path between. p2: One of the GamePoints to check a clear path between. ignore_lines: List of GameLines to ignore. """ temp_line = GameLine(p1, p2) for line in self.lines: if line in ignore_lines: continue if temp_line.intersection(line) and line not in p1.lines and line not in p2.lines: return False return True def get_surrounding_area(self, pos): """Returns GameArea surrounding point. Args: pos: GamePoint to get GameArea surrounding. """ # Get all points points = set() for line in self.lines: points.add(line.endpoints[0]) points.add(line.endpoints[1]) # Filter to visible points middle = pos points = list(filter(lambda x: self.clear_path(middle, x), points)) # Order points thetas = [] for p in points: theta = math.atan((p.y - middle.y)/(p.x - middle.x + EPSILON)) if abs(middle.x - p.x) < EPSILON or middle.x < p.x: theta += math.pi thetas.append(theta) point_thetas = list(zip(points, thetas)) point_thetas.sort(key=lambda x: x[1]) points, thetas = list(zip(*point_thetas)) if len(points) < 3: return None return GameArea(points, self) def get_areas(self, split_line, color): """Returns two GameAreas on either side of split_line. Args: split_line: New line splitting the area into 2. color: Color of new area. """ # Get all points points = set() for line in self.lines: points.add(line.endpoints[0]) points.add(line.endpoints[1]) # Filter to visible points middle = split_line.midpoint() points = list(filter(lambda x: self.clear_path(middle, x, ignore_lines=[split_line]), points)) # Order points thetas = [] for p in points: theta = math.atan((p.y - middle.y)/(p.x - middle.x + EPSILON)) if abs(middle.x - p.x) < EPSILON or middle.x < p.x: theta += math.pi thetas.append(theta) point_thetas = list(zip(points, thetas)) point_thetas.sort(key=lambda x: x[1]) if len(points) != len(thetas): return None points, thetas = list(zip(*point_thetas)) # Split the areas split_point_indexes = [points.index(ep) for ep in split_line.endpoints] i1 = min(split_point_indexes) i2 = max(split_point_indexes) area_1 = points[i1:i2+1] area_2 = points[0:i1+1] + points[i2:] if len(area_1) < 3 or len(area_2) < 3: return None return GameArea(area_1, self, color), GameArea(area_2, self, color) def split_line(self, old_line, new_point): """Split line into two lines. Note: Does not update areas. Args: old_line: GameLine to split. new_point: GamePoint on old_line to split. """ self.lines.remove(old_line) new_lines = [] for ep in old_line.endpoints: new_line = GameLine(ep, new_point, color=old_line.color, add_self_to_points=True) ep.lines.remove(old_line) self.lines.append(new_line) def make_move(self, move): """Make a move and update the state. Args: move: GameMove object. """ assert self.is_legal_move(move) if self.area_split_line is not None: # TODO(gusatb): Check legality of area. self.areas.append(move.area) self.scores[move.area.color - 1] += move.area.score self.area_split_line = None else: self.split_line(move.p1_line, move.p1) self.split_line(move.p2_line, move.p2) new_line = GameLine(move.p1, move.p2, color=self.next_player, add_self_to_points=True) self.lines.append(new_line) # Check for endgame fill areas = self.get_areas(new_line, self.next_player) total_score = areas[0].score + areas[1].score if total_score <= self.min_score: self.areas.extend(areas) self.scores[self.next_player-1] += total_score elif move.p1_line.color == self.next_player and move.p2_line.color == self.next_player: self.area_split_line = new_line self.next_player = 3 - self.next_player
736cec9862a48f3789776e9a631ed5ce9ad11050
Thearakim/int_to_bin
/int_to_bin.py
606
4.4375
4
def int_to_binary(a, b): #function take two paramaters sum = a + b #sum two number take from print temBi = "" #declare string "" for adding the code below while sum != 0: #using loop to make sure a and b is greater than 0 because equal 0 error temBi = str(sum % 2) + temBi #first it calculated sum % 2 take remainder to temBi sum //= 2 #divided sum by 2 example 4 divided by 2 = 2 so loop again and temp add again return temBi #return binary value to our function int_to_binary print(int_to_binary(12, 3)) #put number a =12 and b =3 and print binary value
44ea22d11697fe7b59f85775d99a8c7fb519812e
lschock/python
/collection_challenges.py
1,137
4.15625
4
# Challenge Task 1 of 2 # Create a function named square. It should define a single parameter named number. # In the body of the function return the square of the value passed in. # (A square is the value multiplied by itself. eg: The square of 5 is 25. 25 = 5 x 5) def square(number): value = number * number return(value) print(square(3)) #<-------------------------------------------------------------------------------># # I need you to finish writing a function for me. The function disemvowel takes a single word as a parameter and then returns that word at the end. # I need you to make it so, inside of the function, all of the vowels ("a", "e", "i", "o", and "u") are removed from the word. Solve this however you want, it's totally up to you! # Oh, be sure to look for both uppercase and lowercase vowels! # IDEA: break word up into a list, remove letters, bring word back together as one def disemvowel(word): vowels = ['a', 'e', 'i', 'o', 'u'] for letter in word: if letter.lower() in vowels: word = word.replace(letter, "") return word print(disemvowel("This is a test"))
e3e69d274c08baaaf05e776a451af261374eedb9
warleyken42/estrutura-de-dados
/lista_03/exercicio08.py
804
3.671875
4
class Macaco: def __init__(self, nome): self.nome = nome self.bucho = [] def comer(self, objeto): self.bucho.append(objeto) def verBucho(self): print("Coisas no Bucho: ") for i in self.bucho: print(i) print("...") def digerir(self): print("Digerindo...") print("\n") self.verBucho() self.bucho = [] def imprimir(self): print("Nome: {}".format(self.nome)) m1 = Macaco("João") m1.imprimir() m1.comer("Banana") m1.verBucho() m1.digerir() m2 = Macaco("Jardel") m2.imprimir() m2.comer("Maca") m2.verBucho() m2.digerir() m1 = Macaco("João") m1.imprimir() m1.comer("Manga") m1.verBucho() m1.digerir() m2 = Macaco("Jardel") m2.imprimir() m2.comer("Melão") m2.verBucho() m2.digerir()
767c0ccdded4a985ae8679c00ef5b4159ea9b41d
mehmetatesgit/pythonkurs
/class.py
1,065
4.3125
4
''' #class class Person: # class attributes address = 'no information' #constructor (yapıcı metod) def __init__(self, name, year): #object attribute self.name = name self.year = year # methods def intro (self): print('Hello There I am '+ self.name) def calculateAge(self): return 2020 - self.year # object, instance p1 = Person('Ali', 1997) p2 = Person('ahmet',1987) p1.intro() p2.intro() print(f"adım: {p1.name} yaşım: {p1.calculateAge()} ") print(f"adım: {p2.name} yaşım: {p2.calculateAge()} ") ''' class Circle: pi = 3.14 def __init__(self, yaricap = 1): self.yaricap = yaricap def cevreHesapla(self): return 2 * self.pi * self.yaricap def alanHesapla(self): return self.pi * (self.yaricap**2) c1 = Circle() c2 = Circle(5) print(f"c1: alan = {c1.alanHesapla()} çevre: {c1.cevreHesapla()} ") print(f"c2: alan = {c2.alanHesapla()} çevre: {c2.cevreHesapla()} ")
e1b23f89ca96196315eb7e92762a3982a69b38b5
generocha/ITC110
/week7/weekly_wage.py
1,267
4.21875
4
''' Peer Assignment 6 Calculate weekly wage with functions 1. Get hours worked 2. Get hourly wage 3. Calculate regular pay 4. Calculate overtime pay 5. Calculate weekly pay 6. Print result Gene Rocha 11/5/2019 ''' REGHOURS = 40 # get the hours worked def getHours(): hours = int(input("Enter the hours worked for the week:")) return hours # get the houlry wage def getWage(): wage = float(input("Enter the hourly wage:")) return wage # calculate the reg pay def calculateRegularPay(hours, wage): regularPay = 0 if hours > REGHOURS: regPay = REGHOURS * wage else: regPay = hours * wage return regPay # calculate overtime def calculateOvertime(hours,wage): otPay = 0 if hours > REGHOURS: otPay = wage * (hours - REGHOURS) * 1.5 return otPay # calculate weekly pay def calculateWeeklyWage(): h = getHours() w = getWage() reg = calculateRegularPay(h,w) ot = calculateOvertime(h,w) total = reg + ot printWages(reg,ot,total) # print the result def printWages(reg,ot,total): print("Your regular pay is ${0:0.2f}".format(reg)) print("Your overtime pay is ${0:0.2f}".format(ot)) print("Your weekly pay is ${0:0.2f}".format(total)) def main(): calculateWeeklyWage() main()
13cbbf688ca760d5b6f98c3970ac5f7ee8843789
wangyendt/LeetCode
/Contests/201-300/week 297/2303. Calculate Amount Paid in Taxes/Calculate Amount Paid in Taxes.py
752
3.546875
4
#!/usr/bin/env python # -*- coding:utf-8 _*- """ @author: wangye(Wayne) @license: Apache Licence @file: Calculate Amount Paid in Taxes.py @time: 2022/06/12 @contact: wang121ye@hotmail.com @site: @software: PyCharm # code is far away from bugs. """ from typing import * class Solution: def calculateTax(self, brackets: List[List[int]], income: int) -> float: ret = 0 last = 0 for i, (b_upper, b_tax) in enumerate(brackets): ret += min(b_upper - last, income - last) * b_tax / 100 # print(b_upper, b_tax, ret) if income <= b_upper: break last = b_upper return ret so = Solution() print(so.calculateTax(brackets=[[3, 50], [7, 10], [12, 25]], income=10))
fe58fa2e31a454fd8f152a703ee71e38276e3121
kpberry/minimum-vertex-cover-algorithms
/hill_climbing.py
6,532
3.8125
4
# File containing our implementation of a variation on randomized hill climbing. # Uses two neighbor functions: get_close_neighbor, which tries to remove a # random vertex from a VC if doing so will keep the VC a solution, and # get_neighbors, which removes 0 to 3 random vertices from a graph if it is a # solution or add 1 to 3 vertices to a graph if it is not a solution. from datetime import datetime, timedelta from random import random, seed, choice from approx import edge_deletion from graph_utils import read_graph from vc import is_solution, eval_fitness def get_close_neighbor(vc, graph, iterations=5000): # Try 5000 times to find a close neighbor for i in range(iterations): v = int(random() * len(vc)) if v in graph and vc[v] == 1: # If removing the vertex would leave an edge uncovered, then the # candidate vertex does not yield a close neighbor for u in graph[v]: if vc[u] == 0: break else: # If there are no vertices which would break the vertex cover, # then we have a close neighbor. copy = [u for u in vc] copy[v] = 0 return copy return None def get_neighbors(vc, graph_is_solution, iterations=10): # If the vc is a solution to the graph, yield a potential neighbor with # a vertex potentially removed; examining one neighbor at a time is better # than actually producing the neighbors eagerly since a good neighbor may # be found in the middle or beginning of the set of candidates if graph_is_solution: for i in range(iterations): copy = [v for v in vc] # Choose up to 3 random vertices to remove (may already be removed) for i in range(int(random() * 3) + 1): copy[int(random() * len(vc))] = 0 yield copy # If the graph is not a solution, definitely add a vertex. Again, yields in # case early stopping is possible. else: # Get all of the vertices which could be added zeroes = [i for i in range(len(vc)) if vc[i] == 0] for i in range(iterations): copy = [v for v in vc] # Add 1 to 3 vertices for i in range(int(random() * 3) + 1): copy[choice(zeroes)] = 1 yield copy def randomized_hill_climb(problem, gen_model, filename, cutoff_time, random_seed): seed(random_seed) # Basic setup; construct the initial solution and evaluate its fitness most_fit = model = gen_model(problem) best_so_far = fitness = eval_fitness(problem, model) model_is_solution = is_solution(problem, model) # IO stuff base = filename.split('/')[-1].split('.')[0] \ + '_LS1_' + str(cutoff_time) + '_' \ + str(random_seed) with open(base + '.trace', 'w') as trace: start_time = cur_time = datetime.now() # Loop until time runs out while (cur_time - start_time) < timedelta(seconds=cutoff_time): neighbor = get_close_neighbor(model, problem) # If a close neighbor is found, automatically make it the candidate # model since it will definitely be a solution if neighbor is not None and model_is_solution: model = neighbor # Update the actual fitness calculation every so often; the # close neighbors don't use the fitness value for selection, # using only the actual VC size instead, so updates don't # matter much when VC size changes quickly. Will be # approximately up to date (or only slightly off) when regular # neighbors need the fitness to determine if they are better # than the best model. All this saves computation time. if random() > 0.99: fitness = eval_fitness(problem, neighbor) best_so_far = max(best_so_far, fitness) # Update the model if it's better than the best so far. if sum(neighbor) < sum(most_fit): most_fit = model # log results trace.write('{:0.2f}'.format( (cur_time - start_time).total_seconds() )) trace.write(',' + str(sum(most_fit)) + '\n') else: # get the model's neighbors in a random order neighbors = get_neighbors(model, model_is_solution) # update the current model if it has a neighbor with a better or # slightly worse fitness for n in neighbors: fitness = eval_fitness(problem, n) if fitness > best_so_far * random(): model = n # If the current model is better than the current # solution, update the solution accordingly model_is_solution = is_solution(problem, model) if fitness > best_so_far and model_is_solution: best_so_far = fitness if most_fit is None or sum(model) < sum(most_fit): most_fit = model # log results trace.write('{:0.2f}'.format( (cur_time - start_time).total_seconds() )) trace.write(',' + str(sum(most_fit)) + '\n') # Stop examining neighbors when a good one is found break print(sum(most_fit), sum(model), fitness, best_so_far, model_is_solution) cur_time = datetime.now() # More IO stuff with open(base + '.sol', 'w') as sol: sol.write(str(sum(most_fit)) + '\n') sol.write(','.join([str(i + 1) for i in range(len(most_fit)) if most_fit[i] == 1])) return most_fit # Run the algorithm on an input graph with a specified time and random seed def run(filename, cutoff_time, random_seed): seed(random_seed) graph = read_graph(filename) randomized_hill_climb(graph, # Generate the initial candidate as all vertices edge_deletion, filename, cutoff_time, random_seed)
6e0893aba1a4d8ff9341538a505f8ef2d47c16bd
vijay0423/project1
/python program implemented by using comments to easily understand.py
1,991
4.28125
4
x=100#Global Variables y=200 class X:#Super class(X) """sample class to test basic concepts of python programs"""#Documentational string it is a optional statement a=300#Static Variables b=400 def __init__(self):#Constructor To initialize the nonstatic variables print("in constructor of X")#When ever we create object constructor method will be executed automatically self.p=500 self.q=600#Non static variables def m1(self):#Normal method i=700 j=800#Local variables print(i) print(j) print("in m1 of X") def m2(self):#Methods print("in m2 of X") print(x) print(y) def __del__(self):#Destructor method whenever we delete the object this method will be executed print("in destructor of X") class Y(X):#Sub class(Y) c=900#Static variables d=1000 def __init__(self):#Magic or Constructor or Initiator Methods self.r=1100#Nonstatic variables self.s=1200 super().__init__()#We call superclass properties into subclass we use this statement explicetely purpose of nonstatic variables calling purpose def m2(self):#Methods print("in m2 of Y") def m3(self):#Methods print("in m3 of Y") def modify(self):#Methods Y.c=Y.c+100 self.r=self.r+100 def display(self):#Methods print(Y.c) print(Y.d) print(self.r) print(self.s) self.m2() self.m3() print(Y.a) print(Y.b) print(self.p) print(self.q) self.m1() super().m2()#We call super class methods with in the subclass we use this statement by method overwrite concept r1=Y() print(r1) r1.display() r1.modify() r1.display() r2=Y() print(r2) r2.display() del r1#When ever we delete object destructor method will be executed
511a742b7f27dc0379d65090f25ec91375f0b2d9
VisionAILab/Training
/Anudit Bhatt/Python_OOPs/Ex4.py
745
3.953125
4
class Computer: def __init__(self): self.name = "Anudit" self.age = 21 def update(self): self.age = 26 def compare(self,other):#compare(who is calling, whom is calling) if self.age == other.age: return True else: return False c1 = Computer() c2 = Computer() #c1.name = "Rashi" c1.age = 12 #c1.update()# here self works as a pointer to c1 object if c1.compare(c2): print("They are same") else: print("They are not same") #print(id(c1))#this gives the address of the object(c1) in heap memory. There will be different memory address each time you run the code print(c1.name) print(c1.age) print(c2.name)
b70dcfe75ba4585c3a840afa58d5992377acf27e
walstra/phd_nikhef
/slides/bubblesort_dbg.py
407
4.0625
4
import random def display_list(l): for value in l: print("**" * value) input("") def bubblesort(l): for left in range(len(l)-1,0,-1): for i in range(left): if l[i] < l[i+1]: l[i], l[i+1] = l[i+1], l[i] display_list(l) return l l = [random.randrange(1,50) for i in range(1,20)] print(l) import pdb; pdb.set_trace() bubblesort(l) print(l)
93f056e361928986f3c011df6f2c2873ba8a3402
LucasLeone/tp2-algoritmos
/ciclo_while/cw1.py
155
3.609375
4
''' Leer una serie de cincuenta números enteros. ''' import random i = 0 while i < 50: i = i + 1 num = random.randint(0, 100) print(num)
e4a5f9a05ddf95e329abb9d80dea1b3b83e2a782
henmanzur/Python
/Exercises/Exercise3_Strings_and_ConsoleOutput.py
2,031
3.859375
4
############ # # מחרוזת ############ ''' מחרוזות(STRINGS) הן משתנה המתאר רצף של תווים (אותיות, מספרים וערכים שונים של ביטויים כמו רווח,סימן קריאה וכו') ההכרזה על משתנה מסוג מחרוזת נעשית באמצעות מרכאות או גרשיים hen = 'hen manzur' hen2 = "hen manzur" ''' #hen3 = ''' # hen manzur # ''' #hen4= """ # hen manzur # """ ''' מחרוזות ניתן לחבר כמו מספרים print(hen + hen2 + hen3 + hen4) fullname = hen + "love or " age = 27.2 #מחרוזות לא ניתן לחבר עם מספרים כדי להמיר מספר למחרוזת נרשום כך: str(age) וכך נוכל לחבר בין integer לstring ''' # ניתן להטמין פרמטרים במחרוזת: #print("p1={},p2={},p3={},p4={red}".format(1,1.0,"hen",red="BBFD")) #בדיקה עם מחרוזת קיימת בתוך מחרוזת: True or False #print("hen" in "hen manzur") #a = "hen manzur" #print("hen manzur" in a) #ניתן לייצג או להדפיס תווים ספציפים: ### A=0 B=1 C=2 D=3 E=4 F=5 ### A=-6 B=-5 C=-4 D=-3 E=-2 F=-1 - בספירה לאחור s1="ABCDEF" print(s1[0]) # ידפיס רק את התו הראשון A print(s1[-1]) # ידפיס רק את התו האחרון F (הספירה הפוכה) #print(s1[]) # לא ניתן להדפיס ללא הכנסת ערך לסוגריים מרובעים print(s1[1:-1]) # ידפיס טווח מהתו השני B עד התו לפני אחרון E ,עד הערך לאחר ה: ולא כולל הערך לאחר הנקודותיים print(s1[1:]) # ידפיס טווח מהתו השני B עד התו האחרון F ,על מנת להדפיס הכל לא נרשום כלום לאחר הנקודותיים print(s1[:]) # ידפיס הכל מהתחלה עד הסוף print(s1[1::2]) # פעמיים נקודותיים - [2::1] ידפיס מהתו השני בקפיצות של 2 print(s1[::-1]) # פעמיים נקודותיים - [1-::] ידפיס הכל בסדר הפוך
bbefa9841031f810cb756d5f76c0396ca0141ce0
saequus/learn-python-favorites
/Tasks/GetDigitPart.py
1,499
3.921875
4
# Return part with digit(s) if the string starts with one. def get_digit_part(string) -> int: """ Returns part with digit(s) if the string starts with one. :param string: :return int: """ negative = False punctuation_set = { '~', ':', "'", '+', '[', '\\', '@', '^', '{', '%', '(', '-', '"', '*', '|', ',', '&', '<', '`', '}', '.', '_', '=', ']', '!', '>', ';', '?', '#', '$', ')', '/'} stack = str() if string == '' or string.isspace(): return 0 s = string.split()[0] if s.startswith('-'): negative = True s = list(s) s.pop(0) elif s.startswith('+'): negative = False s = list(s) s.pop(0) for i in range(len(list(s))): element = str(s[i]) if element.isdigit(): stack += element elif element in punctuation_set or element.isalpha(): if stack == '': return 0 else: break if stack == '': return 0 else: number = int(stack) if number > 2147483648: return -2147483648 if negative else 2147483647 elif number == 2147483648: return -2147483648 if negative else 2147483647 else: return number * -1 if negative else number # Driver Code print(get_digit_part(''), 0) print(get_digit_part('04356'), 4356) print(get_digit_part('2345af324masdl3e'), 2345) print(get_digit_part('asf2345af324masdl3e'), 0)
284b69789595832fd82ab28133a6855848df00ca
ashiqks/Data-Structures-Algorithms
/Linked_Lists/Singly_Linked_List.py
15,301
4.03125
4
#!/usr/bin/env python # coding: utf-8 # In[235]: # Class to create a node for singly-linked list class Node: def __init__(self, data): # Variable to hold the data point self.data = data # Reference for the next node self.next = None # In[252]: class SinglyLinkedList: # singly-linked list def __init__(self): # Create an empty list with the tail and head nodes as None self.tail = None self.head = None # Counter to keep the number of values in the list self.count = 0 # Function to add a data point to the list def append(self, data): # create an object of the node node = Node(data) # If linked list already contains values then make the head pointing to the currently being added node if self.head: self.head.next = node self.head = node # If the list is empyt initially then make it point to the tail point else: self.tail = node self.head = node self.count += 1 # Function to delete a value from list def delete_by_data(self, data): current = self.tail prev = self.tail while current: if current.data == data: # Checking if the value to be deleted is the first node if current == self.tail: self.tail = current.next # Checking if the value to be deleted is the last node elif current == self.head: self.head = prev prev.next = None # Values to deleted between the first and last nodes else: prev.next = current.next self.count -= 1 return prev = current current = current.next # Function to delete a data point using the index of it def delete_by_index(self, index): if index > (self.count-1): raise Exception('Index out of range') current = self.tail prev = self.tail for i in range(self.count): if i == index: # If the node is at the 0th index if i == 0: self.tail = current.next # If the node is at the last index elif i == (self.count-1): self.head = prev prev.next = None else: prev.next = current.next self.count -= 1 return prev = current current = current.next # Function to iterate over the nodes in the list def iteration(self): # Make the current variable equal the first node current = self.tail # Iterate using the while loop till next attribute of the current node is none while current: val = current.data current = current.next yield val # Function to search if a particular data is in the list or not def search(self, data): # Making use of the iteration function to chech if the data point is included for d in self.iteration(): if d == data: return True return False # Using the __getitem__ magic function to return a data node using the index def __getitem__(self, index): if index > (self.count-1): raise Exception("Index out of range") current = self.tail for i in range(index): current = current.next return current.data # Using the __setitem__ magic function to set a data at a particular index def __setitem__(self, index, data): if index > (self.count-1): raise Exception('Index out of range') current = self.tail for i in range(index): current = current.next current.data = data # Function to reverse the values in the list def reverse(self): current = self.tail # Initialise a stack to hold the data points inorder to hold the values stack = Stack() # Push the values from the beginning to end of the list to stack for i in range(self.count): stack.push(current.data) current = current.next current = self.tail # Pop the values in the stack onto the list from the beginning to the end so as to reverse the list for i in range(self.count): current.data = stack.pop() current = current.next # In[254]: # Class for stack class Stack: def __init__(self): self.top = None self.size = 0 # Function to store the data in the stack def push(self, data): node = Node(data) # Checking if the stack is empty or not if self.top: # If not empty make the current top node pointing to the newly added node node.next = self.top # Make the newly added node as top self.top = node else: # If stack is already empty make the node top self.top = node self.size += 1 # Function to remove data from the stack def pop(self): # Checking if there is any node present in the stack if self.top: data = self.top.data self.size -= 1 # If the current top node contains the next attribute then make the next node as top if self.top.next: self.top = self.top.next # If not then top is none else: self.top = None return data else: return None # Function to see the value without removing the data def peek(self): if self.top: return self.top.data # In[11]: # Node class for doubly-linked list class Node: def __init__(self, data=None): self.data = data self.next = None self.prev = None # In[225]: # Class for doubly-linked list class Doubly_Linked_List: def __init__(self): self.head = None self.tail = None self.count = 0 # Fucntion to append a data to the list def append(self, data): node = Node(data) # Checking and adding the data if the list is empty if self.head is None: self.head = node self.tail = self.head else: # If the list is not empty then add the data nodes at the end of the list node.prev = self.tail self.tail.next = node self.tail = node self.count += 1 # Function to iterate over the nodes in the list to print the values def iteration(self): current = self.head while current: val = current.data current = current.next yield val # To check if a particular data is found in the list with the help of iteration function def search(self, data): for d in self.iteration(): if d == data: return True return False # Use of the magic functions to get a particular value using the index point def __getitem__(self, index): if index > (self.count-1): raise Exception("Index out of range") current = self.head for i in range(index): current = current.next return current.data # Function to set the value of a particular node using the index def __setitem__(self, index, data): if index > (self.count-1): raise Exception('Index out of range') current = self.head for i in range(index): current = current.next current.data = data # Funciton to delete a node in the list using the index def delete_by_data(self, data): current = self.head node_deleted = False # If the item is not in the list if current is None: node_deleted = False # If the node to be deleted is at the beginning of the list elif current.data == data: self.head = current.next self.head.prev = None node_deleted = True # If the node to be deleted is at the end of the list elif self.tail.data == data: self.tail = self.tail.prev self.tail.next = None node_deleted = True # Search item to be deleted, and delete that node else: while current: if current.data == data: # Make the next attribute of the current's previous node point to next attribute of the current node current.prev.next = current.next # Make the previous attribute of the current's previous node point to the previous attribute of the current node current.next.prev = current.prev node_deleted = True current = current.next if node_deleted: self.count -= 1 # Function to delete a node using the index def delete_by_index(self, index): current = self.head node_deleted = False if current is None: node_deleted = False # If the node is at the beginning of the list elif index == 0: self.head = current.next self.head.prev = None node_deleted = True # If the node is at the end of the list elif index == (self.count-1): self.tail = self.tail.prev self.tail.next = None node_deleted = True else: for i in range(self.count-1): if i == index: # Make the next attribute of the current's previous node point to next attribute of the current node current.prev.next = current.next # Make the previous attribute of the current's previous node point to the previous attribute of the current node current.next.prev = current.prev node_deleted = True current = current.next if node_deleted: self.count -=1 # Function to reverse the list def reverse(self): current = self.head end = self.tail # Iterate over till the half index of the list and exchange the data between nodes in the list so as to reverse the list for i in range(self.count//2): current.data, end.data = end.data, current.data current = current.next end = end.prev # In[229]: # Class for the circular doubly-linked list class Circular_Doubly_Linked_List: def __init__(self): self.head = None self.tail = None self.count = 0 # Function to add a node to the list def append(self, data): node = Node(data) if self.head is None: self.head = node self.tail = self.head else: node.prev = self.tail self.tail.next = node self.tail = node self.tail.next = self.head self.head.prev = self.tail self.count += 1 # Iterate over the list to return the values one by one def iteration(self): current = self.head for i in range(self.count): val = current.data current = current.next yield val # Search if a particular value is found at the list def search(self, data): for d in self.iteration(): if d == data: return True return False # Use of the magic functions to get a particular value using the index point def __getitem__(self, index): if index > (self.count-1): raise Exception("Index out of range") current = self.head for i in range(index): current = current.next return current.data # Using the __setitem__ magic function to set a data at a particular index def __setitem__(self, index, data): if index > (self.count-1): raise Exception('Index out of range') current = self.head for i in range(index): current = current.next current.data = data def delete_by_data(self, data): current = self.head node_deleted = False if current is None: node_deleted = False # If the node to be deleted is at the beginning elif current.data == data: self.head = current.next self.head.prev = self.tail self.tail.next = self.head node_deleted = True # If the node to be deleted is at the last elif self.tail.data == data: self.tail = self.tail.prev self.tail.next = self.head self.head.prev = self.tail node_deleted = True else: # If the node to be deleted is in between the first and last nodes of the list for i in range(1, self.count-1): if current.data == data: current.prev.next = current.next current.next.prev = current.prev node_deleted = True current = current.next if node_deleted: self.count -= 1 # Function to delete a data point using the index def delete_by_index(self, index): current = self.head node_deleted = False if current is None: node_deleted = False # If the node is at the beginning of the list elif index == 0: self.head = current.next self.head.prev = self.tail self.tail.next = self.head node_deleted = True # If the node is at the end of the list elif index == (self.count-1): self.tail = self.tail.prev self.tail.next = self.head self.head.prev = self.tail node_deleted = True else: for i in range(1, self.count-1): if i == index: # Make the next attribute of the current's previous node point to next attribute of the current node current.prev.next = current.next # Make the previous attribute of the current's previous node point to the previous attribute of the current node current.next.prev = current.prev node_deleted = True current = current.next if node_deleted: self.count -=1 # Function to reverse the list def reverse(self): current = self.head end = self.tail # Iterate over till the half index of the list and exchange the data between nodes in the list so as to reverse the list for i in range(self.count//2): current.data, end.data = end.data, current.data current = current.next end = end.prev
f8063f6f47184d1d0a4039524861605ad8dd6c11
alv2017/Python---YahooFinanceDataLoader
/YahooFinanceDataLoader/utils/set_time_point.py
562
3.90625
4
import datetime def set_time_point(dt): """ The function takes date as an input and returs a timestamp in seconds Input: date, format "yyyy-mm-dd" Return: date timestamp in seconds since 1970-01-01 """ year, month, day = dt.split("-") # input date is valid try: input_time = datetime.datetime(int(year), int(month), int(day), tzinfo=datetime.timezone.utc) except ValueError as err: raise err return int(input_time.timestamp())
fcbf1da11a4716ef13b1cc556e508d55b7b11797
MercybirungiS/PYTHON-CLASSES
/PyQuiz/python_test.py
1,619
3.796875
4
# Number 1 from typing import AsyncGenerator x = [100,110,120,130,140,150] y=[] a=1 for a in x: a=a*5 y.append(a) print (y) # number 2 def divisible_by_three (n): x=range(n) for i in x: if i %3==0: print(i) divisible_by_three(15) # number 3 def flatten(): x = [[1,2],[3,4],[5,6]] flatlist=[] for sublist in x: for element in sublist: flatlist.append(element) print(flatlist) flatten() # number 4 def smallest (): n=[2,7,8,9,12,9,9,0] return min(n) print(smallest()) # number 5 def duplicate (): x = ['a','b','a','e','d','b','c','e','f','g','h'] y=set(x) print(y) duplicate() # number 6 def divisible_by_seven(): y=range(100,200) for i in y: if i %7==0: print(i) else : print("not divisible by 7") divisible_by_seven() # number 7 def greeting(student_list): for item in student_list: birth_year=2021-item["age"] name=item["name"] print(f"Hello {name} you were born in the year {birth_year}") greeting([{"age": 19, "name": "Eunice"}, {"age": 21, "name": "Agnes"}, {"age": 18, "name": "Teresa"}, {"age": 22, "name": "Asha"}]) # 8 class Rectangle: def __init__(self,width,length): self.width=width self.length=length def rect_area(self): area=self.width*self.length return area def rect_perimeter(self): perimeter=2*(self.length+self.width) return perimeter rectangle=Rectangle(8,6) print(rectangle.area()) print(rectangle.perimeter())
f9bac027b8ada7e760d6d4edf2bc7f480ea4726b
arogers1/VBPR
/utils.py
628
3.796875
4
def bsearch(a, x, reverse_sorted=False): left, right = 0, len(a) - 1 while left <= right: mid = left + (right - left) // 2 if a[mid] == x: return mid if reverse_sorted: if a[mid] >= x: # go right left = mid + 1 else: right = mid - 1 else: if a[mid] >= x: # go left right = mid - 1 else: left = mid + 1 return -1 def in_array(a, idx, reverse_sorted=False): i = bsearch(a, idx, reverse_sorted) if i >= 0: return True return False def insert_sorted(a, x): i = 0 while i < len(a) and x >= a[i]: while i < len(a) - 1 and a[i] == a[i+1]: i += 1 i += 1 a.insert(i, x)
8035a412e96e819592f572bf50cd019bfe6e4195
alirezataleshi/project
/bmi standard.py
689
4.0625
4
unit= input("aya metric estefade mikonid?:") if unit=="y": weight = float(input("weight in metric?:")) height= float(input("height in metric?:")) bmi = weight / (height * height) print(bmi) if bmi > 30: print("obesity") if bmi < 18.5: print("underweight") if 18.5 < bmi < 25: print("normal") if 25 < bmi < 30: print("overwight") elif unit=="n": weight = float(input("weight in imp?:")) height = float(input("height in imp?:")) bmi = (weight*703) / (height * height) print(bmi) if bmi > 30: print("obesity") if bmi < 18.5: print("underweight") if 18.5 < bmi < 25: print("normal") if 25 < bmi < 30: print("overwight")
e75559fa1d15a4e8093d16b417bbfb6ef701cc5d
mekcherie/CS1.1OOP
/instructor.py
1,402
3.640625
4
from School import School from manager import Manager from students import Students class Instructor(School): def __init__(self, name, year, address, id, title, class_names, salary=3000): super().__init__(name, year, address, id) self._title = title # protected bc we only want it to be accessed from a subclass self.class_names = class_names self.__salary = salary # private self.assistant_names = [] # extend is putting it all together in a list while in append it prints out one by one def assistant(self, assistant_names): self.assistant_names.extend(assistant_names) AB = self.class_names print(f" I'm a {AB}") def satsfiy_level(self, response): if response.lower() == "yes": print(f"{self.name} is very satsfied about the payment") else: print(f"{self.name} is sad about the payment") jacob = Instructor("jacob", 2, "Assistant", "555 post st", 5425626, "business instructor") jacob.assistant(["luke" "abiy"]) jacob.satsfiy_level("yes") businessschool = School("busines school", 2, "444 post st", 45646 ) jacob = Instructor("jacob", 2, "Assistant", "555 post st", 5425626, "business instructor", "Python") jacob = Students("jacob", 20, "male", ["CS", "FEW", "BEW"]) businessschool.get_id() businessschool.information() jacob.identity() jacob.courses()
13f7693d11c6a081ce4124c253f74f3caf788637
Leo7890/Tarea-04
/Áreas de rectángulos.py
2,122
3.921875
4
#encode: UTF-8 #Autor: Leonardo Castillejos Vite #Descripción: programa que lee los lados de 2 rectángulos y entrega el perimetro y el área. import turtle def main(): largo1 = int(input("Teclea el largo del rectángulo 1: ")) ancho1 = int(input("Teclea el ancho del rectángulo 1: ")) perimetro1 = calcularPerimetro(largo1, ancho1) area1 = calcularArea (largo1, ancho1) print("El perimetro del rectángulo 1 es %d cm" % (perimetro1)) print("El área del rectángulo 1 es %d cm**2" % (area1)) largo2 = int(input("Teclea el largo del rectángulo 2: ")) ancho2 = int(input("Teclea el ancho del rectángulo 2: ")) perimetro2 = calcularPerimetro(largo2, ancho2) area2 = calcularArea(largo2, ancho2) print("El perimetro del rectángulo 2 es %d cm"% (perimetro2)) print("El área del rectángulo 2 es %d cm**2"% (area2)) mayor = compararArea(area1, area2) print(mayor) dibujarRectangulos(largo1, ancho1, largo2, ancho2) # Calcula el perimetro de un rectángulo def calcularPerimetro(largo, ancho): perimetro = (largo * 2)+(ancho * 2) return perimetro # Calcula el área de un rectángulo def calcularArea(largo, ancho): area = largo * ancho return area # Compara el área de 2 rectángulos def compararArea (area1, area2): if area1 > area2: return "El área del rectángulo 1 es mayor" elif area1 == area2: return "Los rectángulos tienen la misma área " else: return "El área del rectángulo 2 es mayor" # Dibuja dos rectángulos de 2 colores diferentes def dibujarRectangulos(largo1, ancho1, largo2, ancho2): turtle.pencolor("blue") turtle.forward(largo1) turtle.left(90) turtle.forward(ancho1) turtle.left(90) turtle.forward(largo1) turtle.left(90) turtle.forward(ancho1) turtle.pencolor("red") turtle.left(90) turtle.forward(largo2) turtle.left(90) turtle.forward(ancho2) turtle.left(90) turtle.forward(largo2) turtle.left(90) turtle.forward(ancho2) turtle.exitonclick() main()
48253bc7e52d88290f101573c26132a59ae6e5ec
changrif/CIS4930_PPA1
/console/console.py
2,893
4.09375
4
from main import bmi, shortestDistance, email, tab, db def run(): choice = -1 while(choice != "5"): choice = raw_input( "**********************" "\nFunction Menu: " "\n (1) Body Mass Index" "\n (2) Shortest Distance" "\n (3) Email Verifier" "\n (4) Split the Tab" "\n (5) Quit" "\n**********************" "\n Choose a Function: "); if choice == "1": bmi_console(); elif choice == "2": shortestDistance_console(); elif choice == "3": email_console(); elif choice == "4": tab_console(); elif choice != "5": print("\n Not a valid choice. Please enter an integer choice 1-5.\n") # ********************** # *** BMI METHOD *** # ********************** def bmi_console(): db.printAllBMI() feet = raw_input(" Height (ft): ") inches = raw_input(" Height (in): ") weight = raw_input(" Weight (lb): ") try: category, bmiNum = bmi.calculate(feet, inches, weight) print("\n Your BMI of : " + str(bmiNum) + " is considered " + category + "\n") db.saveBMI(feet, inches, weight, category, bmiNum) except Exception as e: print("\n Try again: " + type(e).__name__ + "\n") # ********************** # *** DISTANCE METHOD ** # ********************** def shortestDistance_console(): x1 = raw_input(" x1: ") y1 = raw_input(" y1: ") x2 = raw_input(" x2: ") y2 = raw_input(" y2: ") try: shortestDistanceNum = shortestDistance.calculate(x1, y1, x2, y2) print("\n The shortest distance between (" + x1 + ", " + y1 + ") and (" + x2 + ", " + y2 + ") is " + str(shortestDistanceNum) + "\n") except Exception as e: print("\n Try again: " + type(e).__name__ + "\n") # ********************** # *** EMAIL METHOD *** # ********************** def email_console(): db.printAllEmails(); address = raw_input(" Email: ") try: verified = email.verify(address) if verified: print("\n \"" + address + "\" is a valid email address.\n") else: print("\n \"" + address + "\" is not a valid email address.\n") db.saveEmail(address, verified) except Exception as e: print("\n Try again: " + type(e).__name__ + "\n") # ********************** # *** TAB METHOD *** # ********************** def tab_console(): total = raw_input(" Total: ") guests = raw_input(" Guests: ") try: totalCheck, splitAmount = tab.calculate(total, guests) print("\n Total: " + str(totalCheck) + "\n Split Between " + guests + " Guests:" + str(splitAmount) + "\n") except Exception as e: print("\n Try again: " + type(e).__name__ + "\n")
4232c9a680a5c0afd57c73207354b33a62bf4c67
Chaguin/PruebasPython
/PRUEBAS2/PRUEBAS PYTHON 2/str_punto.py
247
3.609375
4
# -*- coding: utf-8 -*- class punto: def __init__(self, x,y): self.x=x self.y=y def __str__(self): return "("+str(self.x)+", "+str(self.y)+")" punto1=punto(10, 3) punto2=punto(3, 4) print (punto1) print (punto2)
84a0f57e19b16703a89249f20f15ecae04865fc3
AntoniyaV/SoftUni-Exercises
/Fundamentals/04-Functions/03-character-in-range.py
261
3.859375
4
def characters_in_range(char1, char2): chars_str = '' for i in range(ord(char1) + 1, ord(char2)): chars_str += chr(i) + " " return chars_str character_1 = input() character_2 = input() print(characters_in_range(character_1, character_2))
fc85059fa8de5888bfe5ccac1950cf157a3e0693
rakshit6432/HackerRank-Solutions
/30 Days of Code/Python/27 - Day 26 - Nested Logic.py
668
3.609375
4
# ======================== # Information # ======================== # Direct Link: https://www.hackerrank.com/challenges/30-nested-logic/problem # Difficulty: Easy # Max Score: 30 # Language: Python # ======================== # Solution # ======================== DAY_1, MONTH_1, YEAR_1 = map(int, input().split()) DAY_2, MONTH_2, YEAR_2 = map(int, input().split()) def date(): if YEAR_1 > YEAR_2: return 10000 if YEAR_1 == YEAR_2: if MONTH_1 > MONTH_2: return (MONTH_1-MONTH_2) * 500 if MONTH_1 == MONTH_2 and DAY_1 > DAY_2: return (DAY_1-DAY_2)*15 return 0 RESULT = date() print(RESULT)
7d30a9d566872924a17b4c61c4e7b0ec29f4c7ec
GSimas/PyThings
/Coursera/Python for Everybody/2-Data Structures/assignment7_2.py
470
4.125
4
## Python for Everybody Coursera ## Assignment 6_5 ## Gustavo Simas da Silva - 2017 ## Python Data Structures, String Manipulation, File handling # Use mbox-short.txt as the file name fname = input("Enter file name: ") fh = open(fname) result = 0 n = 0 for line in fh: line = line.rstrip() if 'X-DSPAM-Confidence:' in line: index = line.find(':') result = result + float(line[index+1:]) n = n + 1 value = result/n print("Average spam confidence:",value)
f75edc2a86e9a9456ea654f80de3ab3da6e1fb44
Erickmarquez7/python
/funciones/adivina.py
915
4.1875
4
import random """ El usuario adivina el numero al azar producido por la computadora La computadora genera un numero al azar en un rango determinado por el usuario, el objetivo es adivinar dicho numero Para ejecutarlo solo es necesario utilizar el interpretador de python python3 adivina.py """ def adivina(x): """Función principal que genera un numero al azar para que el usario adivine dicho numero""" azar = random.randint(1, x) usuario = 0 #Así en la primera vuelta nunca va a salir, pues 0 != (1,x) while azar != usuario: usuario = int(input(f'Adivina el numero entre 0 y {x}: ')) if usuario > azar: print('Número alto, intenta otra vez: ') elif usuario < azar: print('Número bajo, intenta otra vez: ') print('Felicidades, acertaste el número') n = int(input('Ingresa un rango para adivinar un número: ')) adivina(n)
2337b326b1cb213ea75b1ef833441540bafa1b41
Rahul0506/Python
/Worksheet1/18.py
955
3.921875
4
cent10In = int(input("Enter number of 10-cent coins inserted: ")) cent20In = int(input("Enter number of 20-cent coins inserted: ")) cent50In = int(input("Enter number of 50-cent coins inserted: ")) cent100In = int(input("Enter number of 1-dollar coins inserted: ")) drinkPrice = float(input("Enter price of drink (0.8 or 1.2): ")) money = (0.1 * cent10In) + (0.2 * cent20In) + (0.5 * cent50In) + (1 * cent100In) money -= drinkPrice money *= 100 money = int(money) cent100Out = cent10Out = cent20Out = cent50Out = 0 print("Change to be returned = $", money/100) while money >= 100: cent100Out += 1 money -= 100 while money >= 50: cent50Out += 1 money -= 50 while money >= 20: cent20Out += 1 money -= 20 while money >= 10: cent10Out += 1 money -= 10 print(cent100Out, " x 1-dollar coin(s)") print(cent50Out, " x 50-cent coin(s)") print(cent20Out, " x 20-cent coin(s)") print(cent10Out, " x 10-cent coin(s)")
641b862473d72835d6b905234969e7a3d35872e0
MrHamdulay/csc3-capstone
/examples/data/Assignment_4/lkxant002/boxes.py
807
3.953125
4
def print_square(): print(5*"*",sep="") print("*"," ","*") print("*"," ","*") print("*"," ","*") print(5*"*",sep="") def print_rectangle(w,h): print(w*"*",sep="") for i in range(1,h-1): print("*",(w-2)*" ","*",sep="") print(w*"*",sep="") def get_rectangle(w,h): recta=w*"*" rectc=w*"*" if h>1: out2="{0}\n{1}\n{2}" out1="{0}\n{1}" if h>2: rectb="*"+(w-2)*" "+"*" for i in range(h-3): rectb=out1.format(rectb,"*"+(w-2)*" "+"*") rect=out2.format(recta,rectb,rectc) return(rect) else: rect=out1.format(recta,rectc) return(rect) else: return(recta)
a84a4e53eb14695644d1f97e10771d8086833da6
saifsafsf/Semester-1-Assignments
/Lab 05/task 5.py
632
3.84375
4
num = int(input('Enter number of rows: ')) # Taking Input if num > 0: for i in range(1, num+1): for j in range(num-i): # Displaying Spaces print(end=' ') for k in range(i): # Displaying Asterisks print('*', end=' ') print() # ESEs Prep. for i in range(1, num+1): print(end = ' \t'*(num-i)) for j in range(1, i+1): print(end = str(j)) if j < i: print(end = '\t') continue print() # ESEs Prep. else: print('Invalid Input... (Natural numbers only)')
a1385ce75f4fd37a083e44cd9ac0b620f6ffbd18
pathankhansalman/LeetCode
/simplify-path.py
1,137
3.53125
4
# -*- coding: utf-8 -*- """ Created on Thu Mar 10 23:20:14 2022 @author: patha """ class Solution(object): def simplifyPath(self, path): """ :type path: str :rtype: str """ if len(path) == 1: return path mystr = path prev_len = len(mystr) while 1: mystr = mystr.replace('//', '/') curr_len = len(mystr) if curr_len == prev_len: break prev_len = len(mystr) if len(mystr) == 1: return mystr if mystr[0] == '/': mystr = mystr[1:] if mystr[-1] == '/': mystr = mystr[:-1] comps = mystr.split('/') new_path = ['/'] for comp in comps: if comp == '.': continue if comp == '..': if new_path == ['/']: continue new_path[:] = new_path[:-1] else: new_path.append(comp + '/') new_path = ''.join(new_path) if len(new_path) == 1: return new_path return new_path[:-1]
2b62c3766c2235eea7d1cc72dbbc535fd04ac0e3
bdnguye2/Python_scripts
/frags_cnt.py
865
3.9375
4
#!/usr/bin/python3 # # This script reads in csv file (user input) and # computes the total charge of fragments from # Mulliken population analysis of the supermolecules. # The csv file must be formatted with the following # columns: Supermolecule, and Monomer A. # In addition, the supermolecule coordinates must # have atoms organized starting with Monomer A # then Monomer B. # # # import csv import sys filename = sys.args[1] with open(filename,'r') as csv_file: mylist = [] mylist2= [] for i in csv.reader(csv_file, delimiter=','): mylist.append(i[0]) mylist2.append(i[1]) mylist2 = list(filter(None, mylist2)) tmp=0 for i in mylist[1:len(mylist2)]: tmp += float(i) tmp2=0 for i in mylist[len(mylist2):]: tmp2 += float(i) print('Total charge of monomer 1: ',tmp) print('Total charge of monomer 2: ',tmp2)
d62ec7de1990969711771bcdbb9e01b8cad67ed4
peinbill/leetcode_learning_card
/array/SolutionOffer29.py
1,331
3.609375
4
from typing import List class Solution: def spiralOrder(self, matrix: List[List[int]]) -> List[int]: if matrix==None or len(matrix)==0: return [] if len(matrix)==1: return matrix[0] row_num = len(matrix) col_num = len(matrix[0]) num_count = row_num*col_num start = 1 top,bottom = 0,row_num-1 left,right = 0,col_num-1 result = [] while start<=num_count: # top for i in range(left,right+1): result.append(matrix[top][i]) start+=1 # right for i in range(top+1,bottom+1): result.append(matrix[i][right]) start+=1 if top!=bottom: # bottom for i in range(right-1,left-1,-1): result.append(matrix[bottom][i]) start += 1 if left!=right: # left for i in range(bottom-1,top,-1): result.append(matrix[i][left]) start += 1 left+=1 right-=1 top+=1 bottom-=1 return result if __name__=="__main__": solution = Solution() print(solution.spiralOrder([[1,2,3,4],[5,6,7,8],[9,10,11,12]]))
459c4290559f1146196be19590e2b86e93a79ede
semensorokin/educational-nlp-projects
/ClientServerArchitecture/Day2_part_1_solutions/unit_test_examples.py
232
3.734375
4
# return multiplication of two digits def multiply(a, b): return a*b # return true if a point is in circle # with radius 1 and center in (0, 0) # including borders def is_in_circle(x, y): return x**2 + y**2 <= 1.0
24bb27e2f7279ab0648d61ec17d1bc7185d578d4
riturajkush/Geeks-for-geeks-DSA-in-python
/Tree/Check if subtree.py
4,120
4.09375
4
#User function Template for python3 ''' class Node: def _init_(self, val): self.right = None self.data = val self.left = None ''' # your task is to complete this function # function should print the left view of the binary tree # Note: You aren't required to print a new line after every test case def isSubTree(T, S): # Base Case if S is None: return True if T is None: return False # Check the tree with root as current node if (areIdentical(T, S)): return True # IF the tree with root as current node doesn't match # then try left and right subtreee one by one return isSubTree(T.left, S) or isSubTree(T.right, S) def areIdentical(root1, root2): # Base Case if root1 is None and root2 is None: return True if root1 is None or root2 is None: return False # Check fi the data of both roots is same and data of # left and right subtrees are also same return (root1.data == root2.data and areIdentical(root1.left , root2.left)and areIdentical(root1.right, root2.right) ) #Wrong Outputs To be Reviewed '''def ino2(T1, T2, f): if (T1==None) and (T2!=None): f = 0 return if (T1!=None) and (T2==None): f = 0 return if (T1==None) and (T2==None): return ino2(T1.left, T2.left, f) if (T1.data!=T2.data): f = 0 return ino2(T1.right, T2.right, f) def ino1(T1, T2, f): if (T1==None): return if (T1.data==T2.data): ff=1 ino2(T1, T2, ff) if (ff==1): f = 1 ino1(T1.left, T2, f) ino1(T1.right, T2, f) def isSubTree(T1, T2): f = 0 ino1(T1, T2, f) if (f==1): return True else: return False''' #{ # Driver Code Starts #Initial Template for Python 3 #Initial Template for Python 3 #Contributed by Sudarshan Sharma from collections import deque # Tree Node class Node: def __init__(self, val): self.right = None self.data = val self.left = None # Function to Build Tree def buildTree(s): #Corner Case if(len(s)==0 or s[0]=="N"): return None # Creating list of strings from input # string after spliting by space ip=list(map(str,s.split())) # Create the root of the tree root=Node(int(ip[0])) size=0 q=deque() # Push the root to the queue q.append(root) size=size+1 # Starting from the second element i=1 while(size>0 and i<len(ip)): # Get and remove the front of the queue currNode=q[0] q.popleft() size=size-1 # Get the current node's value from the string currVal=ip[i] # If the left child is not null if(currVal!="N"): # Create the left child for the current node currNode.left=Node(int(currVal)) # Push it to the queue q.append(currNode.left) size=size+1 # For the right child i=i+1 if(i>=len(ip)): break currVal=ip[i] # If the right child is not null if(currVal!="N"): # Create the right child for the current node currNode.right=Node(int(currVal)) # Push it to the queue q.append(currNode.right) size=size+1 i=i+1 return root if __name__=="__main__": t=int(input()) for _ in range(0,t): rootT=buildTree(input()) rootS=buildTree(input()) if isSubTree(rootT, rootS) is True: print("1") else: print("0") # } Driver Code Ends
3442e72a8d7131d66a85d35254978f64204b389b
Magssch/TDT4113-computer-science-programming-project
/project 2/ManyGames.py
2,358
3.625
4
from matplotlib import pyplot as plot from Game import * from Random import * from Sequential import * from MostFrequent import * from Historian import * class ManyGames: # Setup game def __init__(self): self.p1 = self.setupPlayer(True) self.p2 = self.setupPlayer(False) self.num_games = int(input("Velg hvor mange spill som skal spilles: ")) self.p1_wins = 0 self.p2_wins = 0 # Runs a single game, saving the score of p1 and p2 def run_game(self): game = Game(self.p1, self.p2) game.play_game() if game.winner == self.p1: self.p1_wins+=1 elif game.winner == self.p2: self.p2_wins += 1 else: self.p1_wins += 0.5 self.p2_wins += 0.5 return str(game) # Starts a tournament, runs an amount of games, and then plots the result. def tournament(self): win_percentage = [] round = 0 while round < self.num_games: print(self.run_game()) win_percentage.append(self.p1_wins / (self.p1_wins + self.p2_wins)) round += 1 plot.ylabel('Gevinst') plot.xlabel('Antall spill') plot.ylim(0,1) plot.plot(win_percentage) plot.show() # Initializes a player def setupPlayer(self, isPlayer1): if(isPlayer1): name = input("Hva heter spiller 1? ") else: name = input("Hva heter spiller 2? ") while True: ptype = int(input("Velg spillertype: (Skriv 1 for Tilfeldig, 2 for Sekvensiell, 3 for Mest vanlig og 4 for Historiker) ")) if ptype == 1: player = Random(name) break elif ptype == 2: player = Sequential(name) break elif ptype == 3: player = MostFrequent(name) break elif ptype == 4: memory = int(input("Velg antall ledd i minnet til Historian: ")) player = Historian(name, memory) break else: print("Den spillertypen finnes ikke. (velg fra 1-4)") return player # Runs the class if the script is executed and not imported. if __name__ == '__main__': game = ManyGames() game.tournament()
1fe034fc8c1f9dced00f457ca3565a12163aadba
WuTang94/Cryptography-programs
/HW 7 Miller Rabin.py
3,134
4.03125
4
# -*- coding: utf-8 -*- """ Created on Sat Nov 18 09:36:05 2017 @author: Justin Tang unless otherwise stated; methods that I borrowed online and modified are denoted """ import random #import math """ I borrowed this method of Miller Rabin from a website, but I replaced the pow() function with the Square and Multiply method. Also, I made it so that there is only one security parameter and thus only one random instance of a """ #Original source: https://www.snip2code.com/Snippet/4311/Python-implementation-of-the-Miller-Rabi #partly modifications done by me def MRPTest(p,k): #p is the prime candidate, k is the security parameter if p%2 == 0:# weeding out the even numbers return False r, s = 1, p - 1 while s % 2 == 0: r += 1 s //= 2 for i in range(1,k): a = random.randrange(2, p - 1) #x = pow(a, s, p) x = SquareNMult2(p,a,s) if x == 1 or x == p - 1: continue for j in range(r - 1): #x = pow(x, 2, p) x = SquareNMult2(p,a,s) if x == p - 1: break else: return False return True print (MRPTest(123003,1)) # """ another square and multiply function that I found. Only the second method was particularly useful in my case """ """ def SquareNMult(x,n): return SquareNMult2(1, x, n) """ def SquareNMult2(y,x,n): if n < 0: return SquareNMult2(y,1/x,n) elif n == 0: return y elif n == 1: return x*y elif n % 2 == 0: return SquareNMult2(y, x * x, n/2) elif n % 2 == 1: return SquareNMult2(x * y, x * x, (n - 1)/2) """ print(SquareNMult(2,5)) print(pow(3,2,10)) print(2**5) """ #and here's a primality method that I borrowed that I'll test against Miller-Rabin def is_prime(n): """#pre-condition: n is a nonnegative integer #post-condition: return True if n is prime and False otherwise.""" if n < 2: return False; if n % 2 == 0: #weeding out the even numbers return n == 2 # return False k = 3 #this should work for all other odd numbers while k*k <= n: if n % k == 0: return False k += 2 return True print(is_prime(13)) #This is the method I wrote to run Miller Rabin for a certain range #it shows the different errors and calculates total error def testrange(a,b): errorCount = 0;#creating a place to count all errors totalErr = 0; total = 0 #prime = False for i in range(a,b): errorCount = 0 if i % 2 == 1:#odd numbers total += 1 reg = is_prime(i) MR1 = MRPTest(i,1) for j in range(0,100): #repeating this 10 times if reg == MR1: errorCount += 1 print(i, "Error Probability: ", float(errorCount/1000)) totalErr += float(errorCount/1000) ErrProbability = totalErr/total print("Total Error: ", ErrProbability, "% for ", total, "tries") #return errors print(testrange(115000,125000))
189b5c54f70c5c7b774ac099e85421e7520c1424
deepakkt/codility-training-python
/007-stacks-and-queues/codility-stacks-and-queues-4-manhattan.py
1,220
3.875
4
# you can write to stdout for debugging purposes, e.g. # print("this is a debug message") def solution(H): # write your code in Python 3.6 # start with the first height cuboid_stack = [H[0]] blocks = 1 cuboid_sum = H[0] # scroll through the 2nd onwards for (idx, n) in enumerate(H[1:]): # same as last height, nothing to do if n == cuboid_sum: continue # so we have a height lower than existing sum of blocks if n < cuboid_sum: # keep removing blocks until existing sum becomes lower while n < cuboid_sum: cuboid_sum -= cuboid_stack.pop() # remember, existing some could be equal, so we don't act in that case if n > cuboid_sum: cuboid_stack.append(n - cuboid_sum) blocks += 1 cuboid_sum = n continue # if a new height higher than existing sum is present # add the differential alone if n > cuboid_sum: cuboid_stack.append(n - cuboid_sum) cuboid_sum = n blocks += 1 continue return blocks inp = [8, 8, 5, 7, 9, 8, 7, 4, 8] print(solution(inp))
6140f5159480d8ad6e5522e851b27ad2fb473175
pareshsalunke/sortingcodes
/insertion_sort.py
356
4.1875
4
def insertion_sort(list): for index in range(1,len(list)): value = list[index] i = index-1 while(i>=0): if (value < list[i]): list[i+1]=list[i] list[i] = value i = i - 1 print list def main(): list = [8,4,3,6,1,2] insertion_sort(list) if __name__ == '__main__': main()
bbb64d37fa95e3c918c51558af3422f1fb6d77d1
mrigankasaikia91119993/String-Functions
/find_string_elements.py
527
4.28125
4
###The function find_alphanum(a, b) find if a given string's elements occured in n another string, takes two arguments , a is the string where elements are to be find and b is the string who's elements are to be find. This function is not case sensitive.### def find_alphanum(A, B): A.upper() B.upper() c = False for i in B: ses = A.find(i) if ses > 0: c = True if int(c) == 1: print("Yes the elements of string B are found in string A") else: print("No the elements of string B aren't found in string A")
2bdae8cf4c3a6891c6f675ec5254fa5f75b5d845
SUKESH127/bitsherpa
/[3] CodingBat Easy Exercises /solutions/string1 - alternate.py
662
3.75
4
def hello_name(name): return 'Hello ' + name + '!' def make_abba(a, b): return a + b + b + a def make_tags(tag, word): return '<' + tag + '>' + word + '</' + tag + '>' def make_out_word(out, word): mid = int(len(out) / 2) # note that the 0 is optional # So this would also work: # return out[:mid] + word + out[mid:] return out[0:mid] + word + out[mid:] def extra_end(str): return str[-2:] + str[-2:] + str[-2:] def first_two(str): if len(str) == 0: return "" elif len(str) < 2: return str else: return str[0:2] def first_half(str): mid = int(len(str)/2) return str[:mid] def without_end(str): return str[1:-1]
d47de4eaaa9169ef7c6dd6e4ffd5e9121456e258
AnjiSingh738/Task-1
/TASK 1.py
2,168
3.875
4
#!/usr/bin/env python # coding: utf-8 # # # GRIP: The Sparks Foundation # # Data Science and Business Analytics Intern # # Author: Anjali Singh # # Task 1: Prediction Using Supervised ML # In this task we have to predict the percentage score of a student based on the number of hours studied. The task has twovariables where the feature is the no. of hours studied and the target value is the percentage score. This can be solved using simple Linear Regression. # # In[ ]: #Importing required libraries import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns # # Reading data from remote url # In[3]: url="http://bit.ly/w-data" data = pd.read_csv(url) # # Exploring Data # In[5]: print(data.shape) data.head() # In[6]: data.describe() # In[7]: data.info() # In[8]: data.plot(kind="scatter",x="Hours",y="Scores") plt.show() # In[12]: data.corr(method='pearson') # In[13]: data.corr(method='spearman') # In[14]: hours=data['Hours'] scores=data['Scores'] # In[15]: sns.distplot(hours) # In[16]: sns.distplot(scores) # # Linear Regression # In[25]: x = data.iloc[:, :-1].values y = data.iloc[:, 1].values # In[26]: from sklearn.model_selection import train_test_split x_train, x_test, y_train, y_test = train_test_split(x,y,test_size = 0.2, random_state = 50) # In[28]: from sklearn.linear_model import LinearRegression reg = LinearRegression() reg.fit(x_train, y_train) # In[30]: m = reg.coef_ c = reg.intercept_ line = m*x + c plt.scatter(x,y) plt.plot(x,line) plt.show() # In[31]: y_pred=reg.predict(x_test) # In[35]: actual_predicted=pd.DataFrame({'Target':y_test,'Predicted':y_pred}) actual_predicted # In[37]: sns.set_style('whitegrid') sns.distplot(np.array(y_test-y_pred)) plt.show() # In[38]: h = 9.25 s = reg.predict([[h]]) print("If a student for {} hours per day he/she will score {} % in exam.".format(h,s)) # # Model Evaluation # In[40]: from sklearn import metrics from sklearn.metrics import r2_score print('Mean Absolute Error:',metrics.mean_absolute_error(y_test, y_pred)) print('R2 Score:',r2_score(y_test, y_pred)) # In[ ]:
74e324b9e75effb439daf996e64c99372f4016d0
mvargasmoran/interview-stuff
/python/friendlyElapsedExecutionTime.py
1,977
3.53125
4
# Requested by project waste not inc. # # Problem 1 (Python) # # Provide some Python code that can be used to measure how long a function takes to run in a friendly # format. The amount of time can range from less than a second to several hours and should be easy # for a human to read (for example “00:00:00:00012” is not a good output). import time start = time.time() i = 0 while i < 150000: i = i + 1 end = time.time() def formatElapsedTime(seconds): timeUnits = [ 365*24*60*60, 7*24*60*60, 24*60*60, 60*60, 60, 1, ] results = [] for timeUnit in timeUnits: result = seconds / timeUnit if seconds < 1: results.append(float(seconds)) break if float(result) >= 1 : if(int(seconds) > 60): results.append(int(result)) else: results.append(float(result)) seconds = seconds - (timeUnit*int(result)) elif len(results) > 0 : results.append(int(result)) friendlyTimeMeasuresBase = [ "Years", "Weeks", "Days", "Hours", "Minutes", "Seconds", #"miliseconds", ] sliceStart = len(friendlyTimeMeasuresBase)-len(results) sliceStart = sliceStart friendlyTimeMeasures = friendlyTimeMeasuresBase[sliceStart:len(friendlyTimeMeasuresBase)] formatted = "This took: " for index in range(0, len(results)): newline = '\n {0} {1} '.format(results[index], friendlyTimeMeasures[index]) formatted = formatted + newline return formatted; testInput = 694861.9404271125793457 testInput = 60.9404271125793457 testInput = 90061.1404271125793457 # print(testInput % 1) testOutput = formatElapsedTime(testInput) print(testOutput) # testInput2 = 70.1404271125793457 # testInput3 = 3722.1404271125793457 # testInput4 = 86800.1404271125793457 # testInput5 = 607800.1404271125793457
aa4e7199245b6784f40cfd7d22344f3640afba37
Soumya1910/Competetive_Programs
/waveArray.py
924
4.03125
4
""" Problem Statement : Given an array of integers, sort the array into a wave like array and return it, In other words, arrange the elements into a sequence such that a1 >= a2 <= a3 >= a4 <= a5..... """ class Solution: # @param A : list of integers # @return a list of integers def swap(self, a,b): a = a+b b = a -b a = a - b return a,b def wave(self, A): A.sort() for i in range(len(A)-1): if i%2 == 0: if A[i] < A[i+1]: A[i], A[i+1] = self.swap(A[i], A[i+1]) else: if A[i] > A[i+1]: A[i], A[i + 1] = self.swap(A[i], A[i + 1]) return A def main(): s = Solution() l = [5, 1, 3, 2, 4 ] # l = [3, 30, 34, 5, 9] # l = [0,0,0,0,0] print(s.wave(l)) if __name__ == "__main__": main()
a85d14f8eef7b8564179616cdf221da2368a6eb8
savannahjune/wbpractice
/trees/binarysearchtree.py
2,690
4.125
4
class Node(object): def __init__(self, value): self.left = None self.right = None self.value = value class BinarySearchTree(object): def __init__(self): self.root = None def append_node(self, value): new_node = Node(value) if not self.root: # if there's no root (e.g. this is first node), set root to new node self.root = new_node else: # start search at root # "node" is a marker for where we currently are node = self.root while new_node.value != node.value: # as long as node hasn't already been added if new_node.value < node.value and node.left: # if node exists to the left, move left --> new root node = node.left elif new_node.value < node.value: # set node.left to new_node (add to tree) node.left = new_node elif new_node.value > node.value and node.right: # checks if node to right exists, move right --> new root node = node.right elif new_node.value > node.value: # set node.right to new_node (add to tree) node.right = new_node def lookup(self, value, node=None): # @param self is the instance of the tree # @param value is the value i'm searching for # node is where to start but must assign value later if node == None: # start looking at the top of the tree node = self.root if value > node.value: if node.left is None: return None return node.right.lookup(value, node = node.right) elif value > node.value: if node.right is None: return None return node.left.lookup(value, node = node.left) else: return True def depth_first_traversal(self, node): if node: #if you printed first it would be "pre ordered" self.depth_first_traversal(node.left) # print here because you have no more left values so it will be "in order" print node.value self.depth_first_traversal(node.right) # if you print here it would be "post order" return t = BinarySearchTree() node_options = [9, 5, 13, 1, 6] for i in node_options: t.append_node(i) t.depth_first_traversal(t.root) # depth first traversal # go to my left node go to my right node and return # go down as far as you can and then cover all options # use this if you want to check out all the nodes # when you have nothing to the left you can begin printing, then the nodes will # be in order
4bfcf6cdacddbe31557305496ef4dde765617527
AtharvaJoshi21/PythonPOC
/Lecture 22/Lecture22HWAssignment1.py
641
3.515625
4
# WAP to accept a command to be executed as a cmd line arg. Execute the command provided and print output of the same. import optparse import subprocess def ExecCmd(inputCommand): execCmdOutput = subprocess.check_output(inputCommand, shell = True) return execCmdOutput def main(): parser = optparse.OptionParser() parser.add_option("-c", help = "Input Command to be executed", dest = "inputCommand") (options, args) = parser.parse_args() execCommandOutput = ExecCmd(options.inputCommand) print("**** Output of the command execution is : ****") print(execCommandOutput) if __name__ == "__main__": main()
70498113dff682b485e812bb5b509ce9e3411100
benjaminner/python-scripts
/bentrainsim.py
888
3.875
4
import time cc = 0 dc = 0 now = time.time() trntme = now + 30 stations = {'srrvyce':1,'tuomo':2,'leeo':3,'polutica':4,'orvochino':5,'loino':6,'ilumitcio':7} po = raw_input("look at your current station. what is it's name? ") if po in stations : cc = stations[po] else : print("sorry, that is not a station") quit() pp = raw_input("look at your destination station. what is it's name? ") if pp in stations : dc = stations[pp] else : print("sorry, that is not a station") quit() x = raw_input("type how many ways, or 'day pass'. ") dist = abs(cc - dc) if x == 'day pass': fareD = dist * 2 else : faree = dist * int(x) fare = faree / 1.35 fareD = fare / (1+(int(x)-1)/10) print ("your fare is $"), print("{:.2f}".format(fareD)) if time.time() < trntme: print(":D you caught your train!") else : print(":( you missed your train.")
94c5bbbddff6732954fb54cb31ff13876926f78d
LZZimmerman/GamesProgramming
/Class 7/classwork1.py
759
3.5
4
import pygame from pygame.locals import * #initialisation, on all pygames pygame.init() pygame.display.set_caption("My first PyGame program") screen = pygame.display.set_mode((640,480)) xpos = 100 ypos = 200 clock = pygame.time.Clock() while 1: pressed_key = pygame.key.get_pressed() screen.fill((255,69,0)) pygame.draw.circle(screen, (255, 255, 255), (xpos, ypos), 10, 2) if pressed_key[K_RIGHT] and xpos <= 640: xpos += 1 if pressed_key[K_LEFT]and xpos >= 0: xpos -= 1 if pressed_key[K_UP] and ypos >= 0: ypos -= 1 if pressed_key[K_DOWN] and ypos <= 640: ypos += 1 for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() pygame.display.update()
6c4ba1ede4d61ab2e47a9b7eb11f48867eb5c5e2
dim272/coursera_python
/solution2.py
455
3.8125
4
import sys value = int(sys.argv[1]) initial_value = value result = [] while value > 0: number_of_spaces = value - 1 number_of_octohorpe = initial_value - number_of_spaces while number_of_spaces > 0: result.append(' ') number_of_spaces -=1 while number_of_octohorpe >= 1: result.append('#') number_of_octohorpe -= 1 print(''.join(result)) result.clear() value -= 1 number_of_octohorpe += 1
f87485148b631551b008761bcef2d5d3b68a9ef1
asmikush111/projecttkinter
/validation.py
1,982
4.0625
4
import tkinter # imports Tkinter module root = tkinter.Tk() # creates a root window to place an entry with validation there ''' # valid percent substitutions (from the Tk entry man page) # note: you only have to register the ones you need; this # example registers them all for illustrative purposes # # %d = Type of action (1=insert, 0=delete, -1 for others) # %i = index of char string to be inserted/deleted, or -1 # %P = value of the entry if the edit is allowed # %s = value of entry prior to editing # %S = the text string being inserted or deleted, if any # %v = the type of validation that is currently set # %V = the type of validation that triggered the callback # (key, focusin, focusout, forced) # %W = the tk name of the widget ''' def only_numeric_input(P): # checks if entry's value is an integer or empty and returns an appropriate boolean if P.isdigit() or P == "": # if a digit was entered or nothing was entered return True return False def only_char_input(P): # checks if entry's value is an integer or empty and returns an appropriate boolean if P.isalpha() or P == "": # if a digit was entered or nothing was entered return True return False my_entry = tkinter.Entry(root) # creates an entry my_entry.grid(row=0, column=0) # shows it in the root window using grid geometry manager my_entry1 = tkinter.Entry(root) # creates an entry my_entry1.grid(row=1, column=0) # shows it in the root window using grid geometry manager callback = root.register(only_char_input) # registers a Tcl to Python callback callback1 = root.register(only_numeric_input) # registers a Tcl to Python callback my_entry.configure(validate="key", validatecommand=(callback, "%P")) # enables validation my_entry1.configure(validate="key", validatecommand=(callback1, "%P")) root.mainloop() # enters to Tkinter main event loop
92a85814291d1750b6aba269c09cb2b99fa299f9
MariusArhaug/FinalStateMachine
/rule.py
972
3.703125
4
""" RULES """ class Rule: """ Class for rules to be used for states, signals and actions """ def __init__(self, state1, state2, signal, action): self.state1 = state1 self.state2 = state2 self.signal = signal self.action = action def match(self, fsm_state, signal): """ if signal_is_digit(signal): return self.state1 == fsm_state and self.signal == int(signal) return self.state1 == fsm_state and self.signal == signal """ return self.state1 == fsm_state and self.__check_signal(signal) def __check_signal(self, signal): """ checks signal type """ if self.signal == "all_signals": return True elif self.signal == "all_digits": return signal_is_digit(signal) return self.signal == signal def signal_is_digit(signal): """ if signal is digit """ return 48 <= ord(signal) <= 57
c6614a440e29b5c29b1e2931131d2c8208d52636
william1lai/SPOJ
/ONP.py
1,288
3.671875
4
# let + = 0, - = 1, * = 2, / = 3, ^ = 4 def isOp(ch): return ch == '+' or ch == '-' or ch == '*' or ch == '/' or ch == '^' def opPrec(ch): if ch == '+': return 0 elif ch == '-': return 1 elif ch == '*': return 2 elif ch == '/': return 3 elif ch == '^': return 4 else: return -1 ncases = input() for i in range(ncases): line = raw_input() ans = "" operators = [] for j in range(len(line)): if line[j] == '(': operators.append('(') elif line[j] == ')': top = operators.pop() while top != '(': ans = ans + top top = operators.pop() elif isOp(line[j]): if operators == []: operators.append(line[j]) else: top = operators.pop() while operators != [] and top != '(' and opPrec(line[j]) <= opPrec(top): ans = ans + top top = operators.pop() if opPrec(line[j]) <= opPrec(top): ans = ans + top else: operators.append(top) operators.append(line[j]) else: ans = ans + line[j] print ans
baff21b67a80eeac4b67891268476a3f5d69cd65
maneeshd/algo-ds
/algorithms/prime_factors.py
1,611
4.0625
4
from typing import List def prime_factors(num: int) -> List[int]: if num < 2: return [] if num < 6: return [num] p_factors = [] while num % 2 == 0: p_factors.append(2) num = num // 2 for i in range(3, int(num ** 0.5) + 1, 2): while num % i == 0: p_factors.append(i) num = num // i if num > 2: p_factors.append(num) return p_factors def unique_prime_factors(num: int) -> List[int]: if num < 2: return [] if num < 6: return [num] p_factors = [] while num % 2 == 0: if 2 not in p_factors: p_factors.append(2) num = num // 2 for i in range(3, int(num ** 0.5) + 1, 2): while num % i == 0: if i not in p_factors: p_factors.append(i) num = num // i if num > 2: p_factors.append(num) return p_factors if __name__ == "__main__": print(f"Prime Factors of 420 : {prime_factors(420)}") print(f"Prime Factors of 317 : {prime_factors(317)}") print(f"Prime Factors of 10 : {prime_factors(10)}") print(f"Prime Factors of 0 : {prime_factors(0)}") print(f"Prime Factors of 1 : {prime_factors(1)}") print(f"Prime Factors of 2 : {prime_factors(2)}") print(f"Prime Factors of 5 : {prime_factors(5)}") print(f"Prime Factors of 14782 : {prime_factors(14782)}") print("") print(f"Unique Prime Factors of 420 : {unique_prime_factors(420)}") print(f"Unique Prime Factors of 2147483648 : {unique_prime_factors(2147483648)}")
ca857be2fab83eac17878a3d5ff51a33b7ac4702
JackChen207/COMP0034-coursework-1
/matplotlib_line_graph.py
654
3.828125
4
import pandas as pd import matplotlib.pyplot as plt import matplotlib.dates as mdates %matplotlib inline # Read the data for the population and crime into a data frame skipping the second heading row data = pd.read_csv('parliamentary-constituency-profiles-data.csv', usecols=["Crime Rate", "F010"], skiprows=[1]) # Create a new DataFrame with the required Date column population = data.loc[:,['F010']] crime = data.loc[:,['Crime Rate']] fig, axes = plt.subplots(figsize=(12, 6)) plt.plot(population, crime, 'o') axes.set_xlabel('Population Density') axes.set_ylabel('Crime Rate') axes.set_title('The graph of Population Density against Crime Rate')
a65f41d6d1886f2711538a2bd04e30322f3022a9
taymosier/Python-Practice
/big_diff.py
718
4.09375
4
''' Given an array length 1 or more of ints, return the difference between the largest and smallest values in the array. Note: the built-in min(v1, v2) and max(v1, v2) functions return the smaller or larger of two values. ''' def big_diff(nums): minimum = nums[0] maximum = nums[0] for i in range(len(nums)): if minimum > min(minimum,nums[i]): minimum = nums[i] print('new minimum is ' + str(minimum)) if maximum < max(maximum,nums[i]): maximum = nums[i] print('new maximum is ' + str(maximum)) return maximum - minimum print(big_diff([10, 3, 5, 6])) print(big_diff([7, 2, 10, 9])) print(big_diff([2, 10, 7, 2]))
17312a4c3898c15643b58cec0819caac8d628981
rab20/Udemy-Blockchain-using-python
/files.py
497
3.984375
4
# Write into a file. Creates the file if non existant f = open('demo.txt', mode='w') f.write('Hello from Python!\n') f.close() # Append data in the file f = open('demo.txt', mode='a') f.write('Hello again!\n') f.write('-' * 30) f.close() # Reads the contents of the file r = open('demo.txt', mode='r') file_content = r.read() print(file_content) r.close() # Getting file contents as a list s = open('demo.txt', mode='r') file_list = s.readlines() print(file_list) s.close()
5ec16a05f554964707b2cfe62474ea55312774b8
RLeary/projects
/Python/100 challenges/day 8 -26-30/c27 - int to str.py
312
4.34375
4
# Define a function that can convert a integer into a string and print it in # console. # # Hints: # Use str() to convert a number to string. def int_to_string(intteger): return str(intteger) number = 123 string_from_number = int_to_string(number) print(string_from_number) print(string_from_number[2])
2ff00e49bdb1c26ae355ee6d2ed30f03023ac8b9
Niteshrana0007/python
/python_to_JSON.py
145
3.5
4
import json data = { "name":"Nitesh", "marks":[1,2,3,4], "age":21 } print(json.dumps(data)) # output is string
d78f2a5d6b58c8271f42628a89ec13a1ddd1bed0
Aasthaengg/IBMdataset
/Python_codes/p03680/s839052949.py
425
3.703125
4
def readinput(): n=int(input()) a=[0] for _ in range(n): a.append(int(input())) return n,a def main(n,a): button=[0]*(n+1) button[1]=1 i=1 count=0 while(True): i=a[i] count+=1 if i==2: return count if button[i]>0: return -1 button[i]+=1 if __name__=='__main__': n,a=readinput() ans=main(n,a) print(ans)
cdd88f92784c70358044c2a4d2f1e9a762f1110d
florentinolim/pythonestudos
/pythonCursoEmVideo/Exercicios/desafio004.py
756
4.25
4
# Faça um programa que leia algo pelo teclado e mostre na tela o seu tipo primitivo e todas as informações possíves sobre ela n = input('Digite algo:') print('O tipo primitivo é ', type(n)) print('O que você digitou só tem espaços? ', n.isspace()) print('O que você digitou é numerico ? ', n.isnumeric()) print('O que você digitou é apenas letras ?', n.isalpha()) print('O que você digitou é alfa numérico? ', n.isalnum()) print('O que você digitou esta em letras maiusculas ? ', n.isupper()) print('O que você digitou esta em letras minusculas ? ', n.islower()) print('O que você digitou esta capitalizada?', n.istitle()) print('Transformando em letras Maiusculas! ', n.upper()) print('Transformando em letras Minusculas! ', n.lower())
32336f9d5a18fea0199d3cc4fcef1e516b7202c9
JonathWesley/travelingSalesman
/main.py
8,466
3.734375
4
import numpy as np, random, operator, pandas as pd, matplotlib.pyplot as plt from City import City from Fitness import Fitness # criacao de uma rota def createRoute(cityList): # embaralha uma lista com todas as cidades route = random.sample(cityList, len(cityList)) return route # cria a populacao inicial def initialPopulation(popSize, cityList): population = [] for i in range(0, popSize): population.append(createRoute(cityList)) return population # ordena as rotas por maior Fitness def rankRoutes(population): fitnessResults = {} # calcula o valor de Fitness de cada rota for i in range(0,len(population)): fitnessResults[i] = Fitness(population[i]).routeFitness() # retorna esses valores ordenados, com index e valor return sorted(fitnessResults.items(), key = operator.itemgetter(1), reverse = True) # seleciona os individuos que vao ser utilizados para gerar a nova geracao def selection(popRanked, eliteSize): selectionResults = [] # cria um data frame de chave e valor df = pd.DataFrame(np.array(popRanked), columns=["Index","Fitness"]) # soma todos os valores de fitness df['cum_sum'] = df.Fitness.cumsum() # fitness relativa, faz a porcentagem -> 100 * soma dos valores / quantidade de valores df['cum_perc'] = 100*df.cum_sum/df.Fitness.sum() # inclui a elite (numero indicado pelo usuario) for i in range(0, eliteSize): selectionResults.append(popRanked[i][0]) # percorre o restante do vetor de rank for i in range(0, len(popRanked) - eliteSize): # selecao por proporcao de Fitness utilizando o metodo da roleta # faz com que os individuos com maior Fitness relativa tenham maior probabilidade de serem escolhidos pick = 100*random.random() for i in range(0, len(popRanked)): if pick <= df.iat[i,3]: selectionResults.append(popRanked[i][0]) break return selectionResults # pega as rotas que serao usadas para reproduzir def matingPool(population, selectionResults): matingpool = [] for i in range(0, len(selectionResults)): index = selectionResults[i] matingpool.append(population[index]) return matingpool # cruza dois cromossomos para gerar um novo def breed(parent1, parent2): child = [] childP1 = [] childP2 = [] geneA = int(random.random() * len(parent1)) geneB = int(random.random() * len(parent1)) startGene = min(geneA, geneB) endGene = max(geneA, geneB) # pega uma quatidade aleatoria de genes do pai1 for i in range(startGene, endGene): childP1.append(parent1[i]) # pega o restante dos genes do pai2 childP2 = [item for item in parent2 if item not in childP1] # junta os genes dos dois pais child = childP1 + childP2 return child # cruza a matingPool para gerar uma nova populacao def breedPopulation(matingpool, eliteSize): children = [] length = len(matingpool) - eliteSize pool = random.sample(matingpool, len(matingpool)) # adiciona as melhores rotas para a nova geracao for i in range(0,eliteSize): children.append(matingpool[i]) # gera novas rotas a partir de antigas para preencher o restante da populacao for i in range(0, length): # cruza os pais child = breed(pool[i], pool[len(matingpool)-i-1]) children.append(child) return children # faz a mutacao de um individuo def mutate(individual, mutationRate): # utiliza a taxa de mutacao como uma probabilidade de trocar 2 cidades em uma rota for swapped in range(len(individual)): if(random.random() < mutationRate): swapWith = int(random.random() * len(individual)) city1 = individual[swapped] city2 = individual[swapWith] individual[swapped] = city2 individual[swapWith] = city1 return individual # faz a mutacao da populacao def mutatePopulation(population, mutationRate): mutatedPop = [] # percorre toda a populacao mutando ela a partir da taxa de mutacao for ind in range(0, len(population)): mutatedInd = mutate(population[ind], mutationRate) mutatedPop.append(mutatedInd) return mutatedPop # gera a proxima geracao def nextGeneration(currentGen, eliteSize, mutationRate): # ordena as rotas pelo Fitness popRanked = rankRoutes(currentGen) # seleciona o index das rotas para cruzar selectionResults = selection(popRanked, eliteSize) # pega as rotas pela selecao de index matingpool = matingPool(currentGen, selectionResults) # cruza as rotas e gera uma populacao nova children = breedPopulation(matingpool, eliteSize) # faz a mutacao da populacao nova nextGeneration = mutatePopulation(children, mutationRate) # retorna a populacao nova mutada return nextGeneration # executa o algoritmo genetico def geneticAlgorithm(problemName, population, popSize, eliteSize, mutationRate, generations): print("\n\nProblema " + problemName) pop = initialPopulation(popSize, population) print("Distancia inicial: " + str(1 / rankRoutes(pop)[0][1])) bestRouteIndex = rankRoutes(pop)[0][0] bestRoute = pop[bestRouteIndex] print("Melhor rota inicial: ", end='') for x in bestRoute: print(str(x.name) + ' ', end='') for i in range(0, generations): pop = nextGeneration(pop, eliteSize, mutationRate) print("\nDistancia final: " + str(1 / rankRoutes(pop)[0][1])) bestRouteIndex = rankRoutes(pop)[0][0] bestRoute = pop[bestRouteIndex] print("Melhor rota final: ", end='') for x in bestRoute: print(str(x.name) + ' ', end='') # executa o algoritmo genetico plotando o grafico de desenvolvimento def geneticAlgorithmPlot(problemName, population, popSize, eliteSize, mutationRate, generations): print("\n\nProblema " + problemName) pop = initialPopulation(popSize, population) print("Distancia inicial: " + str(1 / rankRoutes(pop)[0][1])) bestRouteIndex = rankRoutes(pop)[0][0] bestRoute = pop[bestRouteIndex] print("Melhor rota inicial: ", end='') for x in bestRoute: print(str(x.name) + ' ', end='') progress = [] progress.append(1 / rankRoutes(pop)[0][1]) for i in range(0, generations): pop = nextGeneration(pop, eliteSize, mutationRate) progress.append(1 / rankRoutes(pop)[0][1]) print("\nDistancia final: " + str(1 / rankRoutes(pop)[0][1])) bestRouteIndex = rankRoutes(pop)[0][0] bestRoute = pop[bestRouteIndex] print("Melhor rota final: ", end='') for x in bestRoute: print(str(x.name) + ' ', end='') plt.figure('Problema ' + problemName,figsize=(10,8)) plt.plot(progress) plt.title('Problema ' + problemName) plt.ylabel('Distancia') plt.xlabel('Geracao') plt.savefig('Problema' + problemName + '.png', format='png') plt.show() if __name__ == "__main__": problemList = [] problemTam = [] input_file = open("input20.txt") for line in input_file.readlines(): cityNumber = 0 cityList = [] data = line.split(';') cityNumber = int(data[0]) iterator = 0 index = 1 for i in range(cityNumber-1): city = City(iterator) for k in range(0, len(cityList)): city.connectedTo[k] = cityList[k].connectedTo[city.name] for j in range(i+1, cityNumber): city.connectedTo[j] = int(data[index]) index += 1 cityList.append(city) iterator += 1 city = City(iterator) for i in range(len(cityList)): city.connectedTo[i] = cityList[i].connectedTo[cityNumber-1] cityList.append(city) problemList.append(cityList) problemTam.append(cityNumber) i = 0 for x in problemList: if problemTam[i] <= 5: geneticAlgorithmPlot(problemName=str(i), population=x, popSize=10, eliteSize=2, mutationRate=0.01, generations=50) elif problemTam[i] > 5 and problemTam[i] <= 10: geneticAlgorithmPlot(problemName=str(i), population=x, popSize=50, eliteSize=10, mutationRate=0.01, generations=100) else: geneticAlgorithmPlot(problemName=str(i), population=x, popSize=100, eliteSize=20, mutationRate=0.01, generations=200) i += 1
2528512205922c026f1831c6a9aa0e080d38a258
einik1/pythongames
/list1.py
811
3.609375
4
# -*- coding: utf-8 -*- def avg_diff(list1, list2): return float(sum([(list1[i]-list2[i]) for i in range(0, len(list1))]))/len(list1) f = lambda x: x+2 g = lambda x: abs(x) def doubleS(str): return "".join(map(lambda x: x+x, str)) def Sinon(x): return filter(lambda y: y % 3 == 0, range(1, x)) def Safrut(x): return reduce(lambda z, y: z + y, [int(str(x)[i]) for i in range(0, len(str(x)))]) def main(): #print avg_diff([1, 2, 3, 4], [1, 1, 1, 1]) #print f(-2) #list1 = [2, -8, 5, -6, -1, 3] #list1.sort(key=g) #print(list1) #string = 'kobi is the king' #print doubleS(string) #print Sinon(100) print [int(str(123)[i]) for i in range(0, len(str(123)))] print Safrut(123456789) if __name__ == '__main__': main()
efbcba9821722760f57917780a85cbeb45236870
glifed/Flashbacks_1-5_sem
/4 sem/вычислительные алгоритмы/lab_2.py
2,011
3.578125
4
#Янова Даниэлла ИУ7-43 #Многомерная интерполяция import numpy as np import matplotlib.pyplot as plt from math import sin, cos def z_f(x, y): return x**2 + y**2 def y_k(xi, xj, yi, yj): y = (yi - yj)/(xi - xj) return y def interpolation(x, y, n, xx): y_n=[] for i in range (n - 1): f_ij = y_k(x[i], x[i+1],y[i],y[i+1]) y_n.append(f_ij) nn = n - 1 F = y[0] + (xx-x[0])*y_n[0] yy = (xx-x[0]) while (nn>0): for i in range (nn-1): y_n[i] = y_k(x[i], x[i+1], y_n[i], y_n[i+1]) yy *= (xx-x[n-nn]) F += yy*y_n[0] nn -= 1 return F x=[] y=[] for i in range (10): x.append(i+1) y.append(i+1) z=[0]*10 for i in range(10): z[i]=[0]*10 print("Table") print(" X\Y |", end='') for i in range(10): print('{:5.1f}'.format(y[i]),end=' |') print() print('------------------------------------------------------------------------------') for i in range (10): print('{:5.1f}'.format(x[i]),end=' |') for j in range(10): z[i][j]=z_f(x[i],y[j]) print('{:5.1f}'.format(z[i][j]),end=' |') print() print() xx=float(input('Введите х, в котором хотите узнать значение функции z: ')) yy=float(input('Введите y, в котором хотите узнать значение функции z: ')) n=int(input('Введите степень точности(натуральное число): ')) cx = xx // 1; cy = yy // 1 sx = n // 2; sy = n // 2 kx = cx-sx; ky = cy-sy x=[]; y=[] n += 1 for i in range(n): x.append(kx) kx += 1 for i in range(n): y.append(ky) ky += 1 Z=[0]*(n) zzx=[0]*(n) for i in range (n): for j in range (n): zzx[j] = z_f(x[j],y[i]) Z[i] = interpolation(x, zzx, n, xx) Result = interpolation(y, Z, n, yy) f = z_f(xx, yy) print("Результат интерполяции: ",'{:.3e}'.format(Result)) print("Значение z: ", '{:.3f}'.format(f))
f4767670ed3ff7a394c4095011c192f8409a06b0
simonpaix/Snake-Python-Turtle
/scoreboard.py
684
4.0625
4
import turtle from turtle import Turtle class ScoreBoard(Turtle): def __init__(self): # class Pen extends Turtle, to make sure it has all the attributes of Turtle we need to initialize Turtle here by calling super.init # this is necessary because we overrided turtle init method here to write pen init method super().__init__() self.speed(0) self.shape("square") self.color("black") self.penup() self.hideturtle() self.goto(0, 260) # score and top score self.score = 0 self.top_score = 0 self.write("Score: 0 top score: {}".format(self.top_score), align="center", font=("Courier", 24, "normal"))
a2f99cae189643848065da47cf7609e5bf766951
CubeSugar/HeadFirstPython
/Day03/print_list_v1.3.py
478
3.859375
4
""" this is a function, the function : *print each item of the list *print every level indent *print to specify output v1.3.0 """ import sys def print_list(the_list, indent = False, level = 0, output = sys.stdout): for each_item in the_list: if isinstance(each_item, list): print_list(each_item, indent, level + 1, file = output) else: if indent: for tab_stop in range(level): print("\t", end = '', file = output) print(each_item, file = output)
9fe87f65ac4b5f7e5a0483e42850dd52f53cff58
Wendyssh/Wendy-s-python
/D12/D12_liao_breakloop.py
86
3.515625
4
n=1 while n<=100: if n>10: break print(n) n=n+1 print('end')
772e9d4ecaea1d441a33afd4e3d5490d48d21fdf
MotazBellah/Code-Challenge
/Algorithms/word_split.py
1,345
4.09375
4
# Create a function called word_split() which takes in a string phrase and a set list_of_words. # The function will then determine if it is possible to split the string in a way in which # words can be made from the list of words. # You can assume the phrase will only contain words found in the dictionary if it is completely splittable. # Use recursive def word_split(phrase,list_of_words, output = None): if output is None: output = [] for word in list_of_words: if phrase.startswith(word): output.append(word) return word_split(phrase[len(word):],list_of_words,output) return output # Use recursive def word_split2(phrase, words, output=[]): if not phrase: return output for word in words: x = phrase.split(word) y = ''.join(x) if len(x) > 1: output.append(word) return word_split(y, words[1:], output) # Without recursive def word_split3(phrase,list_of_words): word_list = [] for word in list_of_words: if word in phrase: word_list.append(word) phrase.replace(word, '') return word_list print(word_split('themanran',['the','ran','man'])) print(word_split('ilovedogsJohn',['am','i','a','dogs','lover','love','John'])) print(word_split('themanran',['clown','ran','man']))
3267b4a72603479c9d271441d7aabc5ddd9c2ef5
shantanu609/Hashing-2
/Problem3.py
791
3.828125
4
# Time Complexity : O(n) # Space Complexity : O(52 characters) = O(1) # Did this code successfully run on Leetcode : # Any problem you faced while coding this : Yes # Your code here along with comments explaining your approach class Solution: def longestPallindrom(self,string): if not string or len(string) == 0 : return 0 count = 0 set1 = set() for i in range(len(string)): if string[i] not in set1 : set1.add(string[i]) else: count += 2 set1.remove(string[i]) if set1: count += 1 return count if __name__ == "__main__": s = Solution() string = "abccccdd" res = s.longestPallindrom(string) print(res)
b9b881b7987a1d5990ca0aaa2d7e8714504a04f3
glasnak/aoc2017
/day2.py
1,266
3.6875
4
#!/usr/bin/env python3 """ --- Day 2: Corruption Checksum --- """ input_file = 'input_day2.txt' def get_input(): with open(input_file, 'r') as f: return f.readlines() def parse_input(lines): """ parse the string into a matrix """ matrix = [] for line in lines: line_nums = [int(x) for x in line.split('\t')] matrix.append(line_nums) return matrix def compute_checksum(sheet): """ main algorithm to do stuff """ result = 0 for line in sheet: result += max(line) - min(line) return result def compute_divisible_checksum(sheet): result = 0 for line in sheet: # PM me a non-ugly way to return both [divisible, by_what] bignum = next((i for i in line if any(i != j and i % j == 0 for j in line)), None) assert bignum line.remove(bignum) for x in line: if bignum % x == 0: result += bignum // x continue return result def main(): sheet = parse_input(get_input()) result = compute_checksum(sheet) print("Checksum 1: {}".format(result)) result2 = compute_divisible_checksum(sheet) print("Checksum 2: {}".format(result2)) return if __name__ == '__main__': main()
a4854f0100d96b880c655b3e148d9ce7d6869c5a
amydeng2000/InterviewPrep
/BFS/BASICS.py
2,089
3.8125
4
""" - 3 things for graphs: BFS/DFS, Topological Sort, Dikjstra - Topological sort: directed acyclic graph (DAG) only. In an edge uv, u comes before v in the traversal ordering """ from collections import deque # Iterative Implementation of BFS # FIRST create the graph (with adjList = [[] for _ in nodes] or using a dictionary) visited = [False for _ in nodes] # or an empty array to add to def bfs(i): q = deque() visited[i] = True q.append((i)) # OR append((level, i)) -> usually slow and takes up a lot of memory! while q: x = q.popleft() # this pops one node at a time for node in x.neighbors: if valid and not visited[node]: visited[node] = True q.append(node) # OR passes += 1 """ if we want to deal with one level at a time... count = 0 while q: nextQ = deque() for node in q: for dep in dependencies: if valid and not visited[dep]: visit[dep] = True nextQ.append(dep) count += 1 q = nextQ """ def topologicalSort(graph): visited = [False]*numNodes # or a set() and add to it resultStack = [] for n in nodes: if not visited[n] topologicalSortRecur(n) def topologicalSortRecur(node): visited[node] = True for n in child: if not visited[n]: topologicalSortRecur(child) resultStack.insert(0, node) # Iterative way to do topological sort by tracking indegree def topoInterative(graph) resultStack = [] adjList = [[] for n in nodes] indegree = [0]*numNodes for i, j in edges: adjList[i].append(j) indegree[j] += 1 q = deque() for i in range(indegree): if indegree[i] == 0: q.apend(i) while q: i = q.popleft() resultStack.apoend(i) # keep track of the result order of topo for j in adjList[i]: indegree[j] -= 1 if indegree[j] == 0: q.append(j)
ae83aafe048239d8fafae5befa779dee0ec61daf
JakeSeib/Python-Practice
/Isolated problems/array_left_rotation.py
1,004
4.5
4
# A left rotation operation on an array shifts each of the array's elements 1 unit to the left. For example, if 2 left # rotations are performed on array [1,2,3,4,5], then the array would become [3,4,5,1,2]. # # Given an array a of n integers and a number, d, perform d left rotations on the array. Return the updated array to be # printed as a single line of space-separated integers. # # Function Description # # Complete the function rotLeft in the editor below. It should return the resulting array of integers. # # rotLeft has the following parameter(s): # # - An array of integers a. # - An integer d, the number of rotations. # Complete the rotLeft function below. import math def rotLeft(a, d): # calculate the overall shift of the array # full rotations can be ignored net_shift = d - math.floor(d/len(a))*len(a) # slice off an appropriately-sized section from the beginning and add it to the end return a[net_shift:len(a)] + a[0:net_shift] print(rotLeft([1,2,3,4,5], 8))
9ffe1a5702c5f0df19016ad4796321d73e4a789e
pavi-ninjaac/python
/basic-interaction/dunderMethods_labTest1.py
1,952
3.9375
4
import math class Lead: def __init__(self , name , staff_size , estimated_revenue , effort_factor): self.name = name self.staff_size = staff_size self.estimated_revenue = estimated_revenue self.effort_factor = effort_factor def __get_digit(self , op): return len(str(math.floor(op))) def lead_score(self): return (1/ (self.staff_size / self.estimated_revenue * ( 10 ** ( self.__get_digit(self.estimated_revenue) - self.__get_digit(self.staff_size) ) ) * self.effort_factor)) def __eq__(self , other): return self.lead_score() == other.lead_score() def __ne__(self,other): return self.lead_score() != other.lead_score() def __lt__(self,other): return self.lead_score() < other.lead_score() def __le__(self,other): return self.lead_score() <= other.lead_score() def __gt__(self,other): return self.lead_score() > other.lead_score() def __ge__(self,other): return self.lead_score() >= other.lead_score() def __str__(self): return f"you estimated factore {str(self.effort_factor)} and youe staff size are {self.staff_size}" l1 = Lead('pavi' , 12 , 1000 , 10.0) l2 = Lead('pavi' , 12 , 1000 , 10.0) print(l1.lead_score()) print(l1==l2) print(str(l1)) """ example of using thes function $ python -i vars.py >>> user1 = User("KeVin", "kbacon@EXAMPLE.com") >>> user2 = User("kevIN", "KBACON@example.com") >>> user3 = User("Keith", "keith@example.com") >>> user1 == user2 True >>> user1 != user2 False >>> user1 == user3 False >>> user1 != user3 True >>> user1 > user3 Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: '>' not supported between instances of 'User' and 'User' """
bb15d5911a95f41a19206e1cc24707e0916b53f3
sadiqQT/Learn-Python
/Lesson3/3DateTime.py
518
3.671875
4
# to import any library in Python # one needs to write like # from *** import *** # for example # from datetime import datetime from datetime import datetime # print Date and Time print(datetime.now()) #Make it more readable print(f"What is the Date and Time now ? = {datetime.now()} " ) # Print individual info. print(f"Today's Day ? = {datetime.now().day} " ) print(f"Today's Month ? = {datetime.now().month} " ) # Can you print current year ? print(f"Today's Year ? = {datetime.now().year} " )
058c3ef633960dc41728afa2f010602c89e90bde
qperotti/Cracking-The-Coding-Interview-Python
/Chapter 4 - Trees and Graphs/ex3.py
959
3.90625
4
''' Exercise 4.3 - List of Depths: Given a binary tree, design an algorithm which creates a linked list of all the nodes at each depth. ''' from collections import deque # Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None def listofDepths(root): if not root: return [] lvlList = [] lvl = 0 queue = deque() queue.append((root,lvl)) while queue: node, lvl = queue.popleft() if len(lvlList) == lvl: lvlList.append([]) lvlList[lvl].append(node.val) lvl +=1 if node.left: queue.append((node.left,lvl)) if node.right: queue.append((node.right,lvl)) return lvlList def testTree(): def addNode(x,lvl): if lvl > 4: return None root = TreeNode(x) root.left = addNode(x*2,lvl+1) root.right = addNode(x*2+1,lvl+1) return root return addNode(1,1) if __name__ == '__main__': root = testTree() print(listofDepths(root))
c4addf0baad06323e59f0674689c1b7c5b8715b3
Aasthaengg/IBMdataset
/Python_codes/p02422/s033171556.py
429
3.65625
4
string = input() for i in range(int(input())): lst = list(map(str, input().split())) if lst[0] == "replace": string = string[:int(lst[1])] + lst[3] + string[int(lst[2])+1:] if lst[0] == "reverse": rev_str = str(string[int(lst[1]):int(lst[2])+1]) string = string[:int(lst[1])] + rev_str[::-1] + string[int(lst[2])+1:] if lst[0] == "print": print(string[int(lst[1]):int(lst[2])+1])
21543df6921c2046b7924b60af1db37ba58c50cf
paknorton/Bandit
/Bandit/colortest.py
4,250
3.78125
4
#!/usr/bin/python # Set ANSI Terminal Color and Attributes. # Original code obtained from: http://code.activestate.com/recipes/574451/ # from __future__ import (absolute_import, division, print_function) from sys import stdout esc = '%s[' % chr(27) reset = '%s0m' % esc format_code = '1;%dm' fgoffset, bgoffset = 30, 40 for k, v in dict(attrs='none bold faint italic underline blink fast reverse concealed', colors='grey red green yellow blue magenta cyan white').items(): globals()[k] = dict((s, i) for i, s in enumerate(v.split())) def term(arg=None, sep=' ', end='\n'): """ "arg" is a string or None if "arg" is None : the terminal is reset to its default values. if "arg" is a string it must contain "sep" separated values. if args are found in globals "attrs" or "colors", or start with "@" they are interpreted as ANSI commands else they are output as text. colors, if any, must be first (foreground first then background) you can not specify a background color alone ; \ if you specify only one color, it will be the foreground one. @* commands handle the screen and the cursor : @x;y : go to xy @ : go to 1;1 @@ : clear screen and go to 1;1 examples: term('red') : set red as the foreground color term('red blue') : red on blue term('red blink') : blinking red term() : restore terminal default values term('reverse') : swap default colors term('cyan blue reverse') : blue on cyan <=> term('blue cyan) term('red reverse') : a way to set up the background only term('red reverse blink') : you can specify any combination of \ attributes in any order with or without colors term('blink Python') : output a blinking 'Python' term('@@ hello') : clear the screen and print 'hello' at 1;1 """ cmd, txt = [reset], [] if arg: arglist = arg.split(sep) for offset in (fgoffset, bgoffset): if arglist and arglist[0] in colors: cmd.append(format_code % (colors[arglist.pop(0)] + offset)) for a in arglist: c = format_code % attrs[a] if a in attrs else None if c and c not in cmd: cmd.append(c) else: if a.startswith('@'): a = a[1:] if a == '@': cmd.append('2J') cmd.append('H') else: cmd.append('%sH' % a) else: txt.append(a) if txt and end: txt[-1] += end stdout.write(esc.join(cmd) + sep.join(txt)) if __name__ == '__main__': from time import sleep, strftime, gmtime print('') term('@@ reverse blink') print('reverse blink default colors at 1;1 on a cleared screen') term('red') print('red') term('red blue') print('red blue') term('yellow blink') print('yellow blink') term('default') term('cyan blue cyan blue') term('cyan blue reverse cyan blue reverse') term('blue cyan blue cyan') term('red reverse red reverse') term('yellow red yellow on red 1') term('yellow,red,yellow on red 2', sep=',') print('yellow on red 3') print('') for bg in colors: term(bg.title().center(8), sep='.', end='') for fg in colors: att = [fg, bg] if fg == bg: att.append('blink') att.append(fg.center(8)) term(','.join(att), sep=',', end='') print('') print('') for att in attrs: term('%s,%s' % (att, att.title().center(10)), sep=',', end='') print('') colist = 'grey blue cyan white cyan blue'.split() while True: try: for cc in colist: sleep(.1) term('%s @28;33 hit ctrl-c to quit' % cc) term('yellow @6;66 %s' % strftime('%H:%M:%S', gmtime())) except KeyboardInterrupt: break except: raise term('@30;1') print('')
d5835268f5d3de9ceaf8af76e62afe9694d19d23
shadowsmain/200907
/200912_homework2.py
404
3.765625
4
my_list = ['v', 'l', 'a', 'd', 'l', 'e', 'n'] my_dict = {'v': 1, 'l': 2, 'a': 3, 'd': 4, 'e': 5, 'n': 6} print (my_list) print (my_dict) print (len(my_list)) print (len(my_dict)) print (len('vl a')) my_list = ['v', 'l', 'a', 'd', 'l', 'e' 'n'] print('a' in my_list) # True print('q' in my_list) # False print('a' not in my_list) # False print('q' not in my_list) # True
a8b79074a0f7f281769e7436a1ad06c255b980cf
Will-So/dsp
/python/q5_datetime.py
768
4.15625
4
# Hint: use Google to find python function import arrow def day_difference(d1, d2, style='MM-DD-YYYY'): """Calculates the differences between dates d1 and d2 assuming American date system. params --- d1: string of format style d2: string of format style style: string dictating how """ d1 = arrow.get(d1, style) d2 = arrow.get(d2, style) return abs((d1- d2).days) ####a) date_start = '01-02-2013' date_stop = '07-28-2015' day_difference(date_start, date_stop, 'MM-DD-YYYY') ####b) date_start = '12312013' date_stop = '05282015' day_difference(date_start, date_stop, 'MMDDYYYY') ####c) date_start = '15-Jan-1994' date_stop = '14-Jul-2015' day_difference(date_start, date_stop, style='DD-MMM-YYYY')
ff867de67d691780273c629c770b0c8bb6562cab
Rynxiao/python3-learn
/basic/list.py
679
4.125
4
#!/usr/bin/env python3 # list classmates = ['Michael', 'Bob', 'Tracy'] print(classmates) # list len len(classmates) # 访问 print(classmates[0]) # 反向索引 print(classmates[-1]) # append classmates.append('Adam') print(classmates) # 删除末尾 last = classmates.pop() print(classmates) # 删除指定位置的元素 spcial = classmates.pop(1) print(classmates) # 列表里面的不同元素 L = ['Apple', 123, True] print(L) # 嵌套LIST l = ['python', 'java', ['asp', 'php'], 'scheme'] print(l) print(len(l)) p = ['asp', 'php'] ll = ['python', 'java', p, 'scheme'] print(ll[2][1]) # 空列表 L1 = [] print(len(L1)) # 拼接 L2 = [1] L3 = [2] print(L2 + L3)
5a92d5463f25712bea0c79a43c296cb615ccc12e
upadhyay-arun98/PythonForME
/Turtle Programs/random_walker.py
416
3.609375
4
import turtle from random import randint screen = turtle.Screen() distance = 50 ttl = turtle.Turtle() ttl.speed(100) for i in range(500): op = ["right", "left", "forward"] move = op[randint(0,2)] if move == "forward": ttl.forward(randint(9, 12)) elif move == "right": ttl.right(randint(0,90)) elif move == "left": ttl.left(randint(0,90)) turtle.done()
0ecdf4698785ad6148514a08b1eca46a8923c2f5
CorSar5/Python-World2
/exercícios 36-71/ex057.py
218
3.890625
4
s = str(input('Escreva o seu sexo [M/F]: ')).strip()[0] while s not in 'MmFf': s = str(input('Dados inválidos. Por favor, informe o seu sexo ')).upper().strip()[0] print('Sexo {} registrado com sucesso'.format(s))
f060a7b08f27e21a82200382811cf4115c477add
leandroaa7/selenium
/sdet-selenium-with-python/class_7/explicitwait.py
3,399
3.609375
4
# -*- coding: utf-8 -*- # 7/45 Selenium with Python Tutorial 7-WebDriver Explicit wait ''' Agenda Waits -Explicit Wait Material de apoio -https://medium.com/@lflucasferreira/entendendo-os-tipos-de-espera-no-selenium-webdriver-2b7adda4db59 -https://medium.com/dev-cave/webdriverwait-fazendo-o-selenium-esperar-a093abeb747b -http://www.macoratti.net/vb_xpath.htm -https://www.w3schools.com/xml/xml_xpath.asp -https://www.guru99.com/xpath-selenium.html#1 Espera Explícita a espera explícita diz ao WebDriver para esperar por uma condição para poder continuar os testes ''' from selenium import webdriver import time #modulo para utilizar estratégias de localizador (por id, xpath, name etc) from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.support.ui import WebDriverWait driver = webdriver.Firefox() #espera implicita de 5 segundos driver.implicitly_wait(5) #maximiza a janela do navegador driver.maximize_window() driver.get('https://www.expedia.com/') #buscar botão de voos #driver.find_element_by_id('tab-flight-tab-hp').click() #outra forma de buscar o botão de voos driver.find_element(By.ID,"tab-flight-tab-hp").click() #Flights button #função de espera do python ''' usar o time.sleep() do python ou Thread.Sleep() do Java não é uma boa prática, pois depende do navegador e da máquina por isso, use o WebDriverWait ''' time.sleep(2) #localizar o elemento de origem do passageiro e digitar o nome #driver.find_element_by_id('flight-origin-hp-flight').send_keys("SFO") driver.find_element(By.ID,'flight-origin-hp-flight').send_keys("SFO") time.sleep(2) #localizar o elemento de destino do passageiro e digitar o nome #driver.find_element_by_id('flight-origin-hp-flight').send_keys("NYC") driver.find_element(By.ID,'flight-destination-hp-flight').send_keys("NYC") #limpa o campo driver.find_element(By.ID,"flight-departing-hp-flight").clear() #localizar elemento de data de partida e digitar o valor da data de partida driver.find_element(By.ID,"flight-departing-hp-flight").send_keys("12/10/2020") #limpa o campo driver.find_element(By.ID,'flight-returning-hp-flight').clear() #localizar elemento de data de retorno e digitar o valor da data de retorno driver.find_element(By.ID,'flight-returning-hp-flight').send_keys("15/10/2020") #localizar elemento do botão submit pelo XPATH ''' XPATH é uma sintaxe para definir partes de um arquivo XML com ele é possível localizar qualquer elemento pelo DOM ''' button_xpath = "/html/body/meso-native-marquee/section/div/div/div[1]/section/div/div[2]/div[2]/section[1]/form/div[7]/label/button" driver.find_element(By.XPATH, button_xpath).click() #search ''' TENTATIVA DO VÍDEO #explicit wait, o valor 10 é o máximo de tempo suportado wait = WebDriverWait(driver,10) input_xpath = "//*[@id='stopFilter_stops-0']" #espera o elemento até que ele seja clicável element = wait.until(EC.element_to_be_clickable((By.XPATH,input_xpath))) #no video funcionou sem o timer.sleep() time.sleep(3) element.click() #driver.quit() ''' ''' TENTATIVA MAIS ELABORADA try: input_xpath = "//*[@id='stopFilter_stops-0']" wait = WebDriverWait(driver,10).until(EC.element_to_be_clickable((By.XPATH,input_xpath))) #nao sei porque mas com dois click funciona! wait.click() wait.click() finally: driver.quit() #pass '''
53ac712d497650e91cdd1f2adcb36284dfb23744
PauliKarl/algorithm-track
/movingCount.py
916
3.53125
4
''' 地上有一个m行n列的方格,从坐标 [0,0] 到坐标 [m-1,n-1] 。 一个机器人从坐标 [0, 0] 的格子开始移动,它每次可以向左、右、上、下移动一格(不能移动到方格外), 也不能进入行坐标和列坐标的数位之和大于k的格子。例如,当k为18时,机器人能够进入方格 [35, 37] ,因为3+5+3+7=18。 但它不能进入方格 [35, 38],因为3+5+3+8=19。请问该机器人能够到达多少个格子? ''' def digitsum(n): ans = 0 while n: ans += n % 10 n //= 10 return ans class Solution: def movingCount(self, m: int, n: int, k: int) -> int: vis = set([(0, 0)]) for i in range(m): for j in range(n): if ((i - 1, j) in vis or (i, j - 1) in vis) and digitsum(i) + digitsum(j) <= k: vis.add((i, j)) return len(vis)
6b2ceb1c6851551209211d9736e93697ea79e0f2
ChuseFronden/PythonTasks
/CalculatorwithIf.py
899
4.125
4
print("Calculator") firstNumber = input("Give the first number:") firstNumber= int(firstNumber) secondNumber = input("Give the second number:") secondNumber = int(secondNumber) plus = firstNumber + secondNumber plus = int(plus) minus = firstNumber - secondNumber minus = int(minus) multiplication = firstNumber * secondNumber multiplication = int(multiplication) division = firstNumber / secondNumber division = float(division) print("(1) +") print("(2) -") print("(3) *") print("(4) /") calculatorNumber = input("Please select something (1-4): ") calculatorNumber = int(calculatorNumber) if calculatorNumber == 1: print("The result is:",plus) elif calculatorNumber == 2: print("The result is:", minus) elif calculatorNumber == 3: print("The result is:", multiplication) elif calculatorNumber == 4: print("The result is:", division) else: print("Selection was not correct.")
55b44185a6e2e0891a94d07218ced4188206470d
satanlia/blue-tardis
/prac3_ex4-2.py
229
4.03125
4
#Изменить код так, чтобы в конце каждой буквы добавлялась точка. s = ['yesterday', 'today', 'tomorrow'] for i in s: print() for j in i: print(j, end=".")
bcf250d0c3cda08faa084caebb05a992f2ad9cfe
wildenali/openCV-Basic-with-Python
/43_DetectCorner/43_b_ShiTomasiCorner.py
1,647
3.65625
4
import cv2 import numpy as np from matplotlib import pyplot as plt # https://www.geeksforgeeks.org/circle-detection-using-opencv-python/ ''' Shi-Tomasi Corner Detection was published by J.Shi and C.Tomasi in their paper ‘Good Features to Track‘. Here the basic intuition is that corners can be detected by looking for significant change in all direction. Syntax : cv2.goodFeaturesToTrack(gray_img, maxc, Q, minD) Parameters : gray_img – Grayscale image with integral values maxc – Maximum number of corners we want(give negative value to get all the corners) Q – Quality level parameter(preferred value=0.01) maxD – Maximum distance(preferred value=10) ''' # Reading image from folder where it is stored # img = cv2.imread('/home/dewatic/Documents/openCV-Basic-with-Python/image_resources/corner1.png') img = cv2.imread('/home/dewatic/Documents/openCV-Basic-with-Python/image_resources/corner4.png') # convert image to grayscale gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # Shi-Tomasi corner detection function # We are detecting only 100 best corners here # You can change the number to get desired result. corners = cv2.goodFeaturesToTrack(gray_img, 100, 0.01, 10) # convert corners values to integer # So that we will be able to draw circles on them corners = np.int0(corners) # draw red color circles on all corners for i in corners: x, y = i.ravel() cv2.circle(img, (x, y), 3, (255, 0, 0), -1) # resulting image plt.imshow(img) plt.show() # De-allocate any associated memory usage # if cv2.waitKey(0) & 0xff == 27: # cv2.destroyAllWindows() # cv2.waitKey(0) # cv2.destroyAllWindows()
109182ac4f732b755c67e7ac49a32008850396fe
jinnovation/JJinProjectEuler
/pe42.py
1,596
3.90625
4
####PROMPT#### # The nth term of the sequence of triangle numbers is given by, tn = ½n(n+1); so # the first ten triangle numbers are: # 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ... # By converting each letter in a word to a number corresponding to its # alphabetical position and adding these values we form a word value. # For example, the word value for SKY is 19 + 11 + 25 = 55 = t10. If the word # value is a triangle number then we shall call the word a triangle word. # Using words.txt (right click and 'Save Link/Target As...'), a 16K text file # containing nearly two-thousand common English words, how many are triangle # words? import time time_start = time.time() ################################################################################ #### Methods #### def wordToNum(word): sum = 0 for letter in word: sum += ord(letter) - ord('A') + 1 return sum def isTri(word): wordNum = wordToNum(word) for num in tris: if (wordNum == num): return True return False ################################################################################ #### Items #### words = [word.strip('"\n').upper() for word in open("words.txt",'r').read().split(',')] tris = [] n = 1 while 0.5*n*(n+1) < max([wordToNum(word) for word in words]): tris.append(int(0.5*n*(n+1))) n+=1 ################################################################################ #### Procession #### quant = 0 for word in words: if (isTri(word)): quant+=1 print quant print "Runtime:",time.time()-time_start,"seconds"
62449f66361d4c5c57d01bb6975603be19347ade
tangml961025/learn_python
/args_kwargs.py
438
4.25
4
""" args:list kwargs:dict 经常在装饰器中使用 """ def test_args_kwargs(arg1, arg2, arg3): print("arg1:", arg1) print("arg2:", arg2) print("arg3:", arg3) # 首先使用 *args args = ("two", 3, 5) test_args_kwargs(*args) # 现在使用 **kwargs: kwargs = {"arg3": 3, "arg2": "two", "arg1": 5} test_args_kwargs(**kwargs) # 标准参数与*args、**kwargs在使用时的顺序 # some_func(fargs, *args, **kwargs)
dc7d915b87aeed1779e5a0095074238868701201
avisek-3524/Python-
/gcd.py
245
3.96875
4
''' write a program to print the gcd of the two numbers''' a = int(input('enter the first number ')) b = int(input('enter the second number ')) i = 1 while(a >= i and b >= i): if(a%i==0 and b%i==0): gcd = i i = i+1 print( gcd )
248f8f6597cff90a3e61f7691400f12d3812f4d4
15963064649/-Fluent-Python-NOTE
/第二章/2.1.2计算笛卡尔积.py
621
4.125
4
#此处笛卡尔积的计算实现过程如下: #加入你需要一个列表,表里是3种不同尺寸的T恤衫,每个尺寸有两个颜色,列表推导写法为: colors = ['black', 'white'] sizes = ['S', 'M', 'L'] Tshitr = [(color,size) for color in colors for size in sizes] #这里得到的是先以颜色排列,再以尺码排列顺序 print(Tshitr) #迭代写法为: for color in colors: for size in sizes: print((color,size)) ''' 则第一章中的纸牌可以写为: class Card: def __init__(self): self._cards = [Card(rank,suit)for rank in ranks for suit in suits] '''
f7493df7dd69ca1c08eb5259406270ac30934a8c
vedatonal38/pulling-a-table-from-the-website
/attract_html_table.py
7,107
3.671875
4
import requests as req import argparse import pandas as pd from bs4 import BeautifulSoup as bs from urllib.parse import urljoin, urlparse # English : Convert and save HTML tables to CSV or EXCEL Files in Python # Türkçe : Python'da HTML tablolarını CSV veya EXCEL Dosyalarına Dönüştürüp kaydetme # kurulum : pip install requests # pip install bs4 # pip install pandas class HTML_Tables: def __init__(self,url): self.USER_AGENT = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36" # US english self.LANGUAGE = "en-US,en;q=0.5" self.url = url def is_valid(self): """ English: Checks whether `url` is a valid URL. Türkçe: "Url" nin geçerli bir URL olup olmadığını kontrol eder. """ temp = urlparse(self.url) # temp.netloc -> example.com # temp.scheme -> https return bool(temp.netloc) and bool(temp.scheme) def get_soup(self): """ English: Constructs and returns a soup using the HTML content of `url` passed Türkçe: Geçilen" url "nin HTML içeriğini kullanarak bir soup oluşturur ve döndürür """ # initialize a session / bir oturumu başlat session = req.Session() session.headers["User-Agent"] = self.USER_AGENT session.headers['Accept-Language'] = self.LANGUAGE session.headers['Content-Language'] = self.LANGUAGE # request / istek html = session.get(self.url) return bs(html.content, "html.parser") def get_all_tables(self, soup): """ English: Extracts and returns all tables in a soup object Türkçe: Bir soup nesnesindeki tüm tablolari cikarir ve dondurur """ return soup.find_all("table") def get_table_headers(self, table): """ English: Given a table soup, returns all the headers. If the number of header cells and the number of data cells are not equal, the number of header cells increases. Türkçe: Tablo soup verildiğinde tüm başlıkları döndürür. Eğer başlık hücrelerin sayısı ile veri hücrelerin sayısı birbirine eşit değilse başlık hücrelerin sayısını artırıyor. """ len_headers = len(table.find_all("tr")[0].find_all("th")) len_datas = len(table.find_all("tr")[1].find_all("th")) + len(table.find_all("tr")[1].find_all("td")) headers = [] if len_headers == len_datas: for th_tag in table.find("tr").find_all("th"): # <tr> tag satir <th> tag sutun headers.append(th_tag.text.strip()) else: for th_tag in table.find("tr").find_all("th"): # <tr> tag satir <th> tag sutun headers.append(th_tag.text.strip()) length = abs(len_datas - len_headers) for i in range(length): headers.append(" ") return headers def get_table_rows(self,table): """ English: Given a table, returns all its rows. Türkçe: Bir tablo verildiğinde, tüm satırlarını döndürürür. """ rows = [] for tr_tag in table.find_all("tr")[1:]: cells = [] td_tags = tr_tag.find_all("td") if len(td_tags) == 0: th_tags = tr_tag.find_all("th") for th_tag in th_tags: cells.append(th_tag.text.strip()) else: th_tags = tr_tag.find_all("th") if len(th_tags) != 0: for th_tag in th_tags: cells.append(th_tag.text.strip()) for td_tag in td_tags: cells.append(td_tag.text.strip()) rows.append(cells) return rows def print_(self, table_name, headers, rows): """ English: Print the table to the screen Türkçe: Tabloyu ekrana yazdırma """ dataframe = pd.DataFrame(rows, columns=headers) dataframe.index +=1 print(dataframe) def save_as_csv(self, table_name, headers, rows): """ English: Saving the table in csv format Türkçe: Tabloyu csv formatta ile kaydetme """ pd.DataFrame(rows, columns=headers).to_csv(f"{table_name}.csv") def save_as_excel(self,table_name, headers, rows): """ English: Saving the table in excel format Türkçe: Tabloyu excel formatta ile kaydetme """ pd.DataFrame(rows, columns=headers).to_excel(f"{table_name}.xlsx") def main(self, _format): print(f"Web site: {self.url}") # get the soup / soup nesnesi al soup = self.get_soup() # extract all the tables from the web page / web sayfasından tüm tabloları çıkar tables = self.get_all_tables(soup) print(f"[+] Found a total of {len(tables)} tables.") # iterate over all tables / tüm tabloları yineleyin for i, table in enumerate(tables, start=1): # get the table headers / tablo başlıklarını al headers = self.get_table_headers(table) # get all the rows of the table / tablonun tüm satırlarını al rows = self.get_table_rows(table) table_name = f"table-{i}" print(f"[+] Saving {table_name}") # save table as csv or excel file / tabloyu csv veya excel dosyası olarak kaydet if _format.lower() == "csv" or _format.lower() == "c": self.save_as_csv(table_name, headers, rows) if _format.lower() == "excel" or _format.lower() == "e": self.save_as_excel(table_name, headers, rows) if _format.lower() == "print" or _format.lower() == "p": self.print_(table_name, headers, rows) if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("--url","-u",help="To enter a URL") parser.add_argument("--file","-f",help="Save from what file type (csv or excel)") parser.add_argument("-p", help="Print on screen") data = parser.parse_args() if data.url: table = HTML_Tables(data.url) if table.is_valid(): if data.file: table.main(data.file) elif data.p: table.main(data.p) else: print("[!]Please enter a valid URL") # Lütfen geçerli bir adres girin print("[!]Example: https://example.com") # Örnek: https://example.com else: print("[!] You need to enter a URL.")
88f677d6bb3856999426b07f1aa413e9bfd5797b
sameertulshyan/python-projects
/daily_weather_update/Send_Html_file.py
1,321
3.609375
4
''' Created on 10 Jan 2018 @author: Sameer Tulshyan ''' import smtplib from email.mime.text import MIMEText from datetime import datetime def send_gmail(msg_file): with open(msg_file, mode='rb') as message: # Open report html file for reading msg = MIMEText(message.read(), 'html', 'html') # Create html message msg['Subject'] = 'Daily Weather {}'.format(datetime.now().strftime("%Y-%m-%d")) msg['From'] = '<enter your email address here>' msg['To'] = '<recipient 1 email address>, <recipient 2 email address>' server = smtplib.SMTP('smtp.gmail.com', port=587) server.ehlo() server.starttls() #place the SMTP connection in TLS (Transport Layer Security) mode. server.ehlo() server.login('<enter your email address here>', '<enter your email password here>') server.send_message(msg) server.close() #--------------------------------------------------------------- if __name__ == '__main__': from Get_Weather_Data import get_weather_data from Create_Html_file import create_html_report weather_dict, icon = get_weather_data() email_file = "Email_File.html" create_html_report(weather_dict, icon, email_file) send_gmail(email_file)
c7320d9ba3f13cb032609a4394f9313831112509
PandyaDeval/Scooby
/keyphraseid.py
544
3.5
4
import speech_recognition as sr import speech, time def nlp_file(): import nlp r=sr.Recognizer() keyword='Scooby' with sr.Microphone() as source: print('Start talking') while True: audio=r.listen(source) try: text=r.recognize_google(audio) if keyword.lower() in text.lower(): print("\'Scooby\' Detected in speech") nlp_file() except Exception as e: print('speak again') time.sleep(1) continue
42e18952a35efae6de88e606d3cd7a95b359b744
OpenImaging/miqa
/samples/convert_miqa_import_csv_format.py
1,845
3.515625
4
import sys from pathlib import Path import pandas for file_name in sys.argv[1:]: if not Path(file_name).exists(): raise Exception(f"{file_name} does not exist.") if not file_name.endswith(".csv"): raise Exception(f"{file_name} is not a CSV file.") df = pandas.read_csv(file_name) expected_columns = [ "xnat_experiment_id", "nifti_folder", "scan_id", "scan_type", "experiment_note", "decision", "scan_note", ] if len(df.columns) != len(expected_columns) or any(df.columns != expected_columns): raise Exception( f"{file_name} is not congruent with the old" f" MIQA import format. Expected columns {str(expected_columns)} but recieved {str(df.columns)}." ) project_name = str(input("Enter a project name for these scans:\n")) print() new_rows = [] for index, row in df.iterrows(): new_rows.append( [ project_name, row["xnat_experiment_id"], f"{row['xnat_experiment_id']}_{row['scan_type']}", row["scan_type"], row["scan_id"], str( Path( row["nifti_folder"], f"{row['scan_id']}_{row['scan_type']}", "image.nii.gz", ) ), ] ) new_df = pandas.DataFrame( new_rows, columns=[ "project_name", "experiment_name", "scan_name", "scan_type", "frame_number", "file_location", ], ) new_filename = f"new_{file_name.replace('old_', '')}" new_df.to_csv(new_filename, index=False) print(f"Wrote converted CSV to {new_filename}.")