blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
3.06M
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
3.06M
67c56866ae607159c5d91fa33153b58dee44440b
wcphkust/sling
/python/tree_traversal_inorder.py
894
3.6875
4
import random import pprint class node: def __init__(self, key = 0, left = None, right = None): self.key = key self.left = left self.right = right def inorder(x, n): if x is None: return n else: n1 = inorder(x.left, n) x.key = n1 n2 = n1 + 1 n3 = inroder(x.right, n2) return n3 def create_tree(size): root = None for i in range(0, size): new_node = node(random.randint(0, 10), None, None) root = insert(root, new_node) return root def insert(root, node): if root is None: return node else: t = random.randint(-5, 5) if t > 0: root.left = insert(root.left, node) else: root.right = insert(root.right, node) return root def main(): root = create_tree(5) inorder(root, 0) inorder(None, 0) if __name__=="__main__": main()
77ba68fad7d5e790611d61f47a570b6fa98fb2c2
wcphkust/sling
/python/sorted_insert_iter.py
978
3.65625
4
import random import pprint def ret_heap(m): for c in m: ret_cell(c) def ret_cell(c): while c is not None: print hex(id(c)) + ' ' + pprint.pformat(vars(c)) c = c.next class node: def __init__(self, key = None, next = None): self.key = key self.next = next def insert_iter(x, k): if x is None: x = node(k) return x else: if k <= x.key: newNode = node(k,x) return newNode else: prv = x nxt = x.next while(nxt is not None and k > nxt.key ): prv = nxt nxt = nxt.next newNode = node(k,nxt) prv.next = newNode return x def show(x): while x: print x.key, x = x.next print '\n' def create_list(size): head = None for key in sorted(random.sample(range(0, 10), size),reverse = True): newNode = node( key ) newNode.next = head head = newNode return head def main(): x1 = create_list(3) show(x1) res = insert_iter(x1, 5) show(res) if __name__=="__main__": main()
530075ed989fcf34df154720d0477c4044e034a0
wcphkust/sling
/python/circular_insert_back.py
997
3.59375
4
import random import pprint def ret_heap(m): for c in m: ret_cell(c) def ret_cell(c): while c is not None: print hex(id(c)) + ' ' + pprint.pformat(vars(c)) c = c.next class node: def __init__(self, key = 0, next = None): self.key = key self.next = next def create_list(size): head = node( random.randint(0,10), None ) head.next = head for i in range(size - 1): new_node = node( random.randint(0,10) ) new_node.next = head.next head.next = new_node head = new_node return head def show(x): head = x.next while x != head: print x.key, x = x.next def lseg_insert_back(hd, tl): new_node = node() new_node.next = hd tl.next = new_node return new_node def insert_back(x): next = x.next if(next == x): tl = node() tl.next = x x.next = tl return tl else: tl = lseg_insert_back(next, x) x.next = tl return tl def main(): root = create_list(5) res = insert_back(root) #show(res) if __name__=="__main__": main()
070231f820697975cab6adee16b75ca72f87d500
shandamonke/Project-Euler-Solutions
/problem9.py
320
3.671875
4
import math for a in range(1,1001): for b in range(1, 1001): if a + b + math.sqrt(a ** 2 + b ** 2) == 1000: print('a = ' + str(a) + 'b = ' + str(b)) c = math.sqrt(a ** 2 + b ** 2) print(math.sqrt(a ** 2 + b ** 2)) print('answer = ' + str(a * b * c))
8e880e707ce62c8f0a8c1d90f2b3dc2c67730565
lukasrieger-dev/CADCostCalculator
/calculator/dxfutils.py
7,329
3.671875
4
import math import ezdxf import logging __author__ = 'lukas' # dxf constants DXF_TYPE_LWPOLYLINE = 'LWPOLYLINE' DXF_TYPE_CIRCLE = 'CIRCLE' DXF_TYPE_TEXT = 'TEXT' DXF_TYPE_MTEXT = 'MTEXT' DXF_TYPE_LINE = 'LINE' DXF_TYPE_ARC = 'ARC' DXF_TYPE_INSERT = 'INSERT' def distance_2d(p1, p2): x1, y1 = p1 x2, y2 = p2 distance = math.sqrt((x2 - x1)**2 + (y2 - y1)**2) return distance def get_arc_length_simple(radius, angle): arc_length = 2*math.pi*radius * angle/360 return arc_length def get_arc_length(p1, p2): """ Helper function to compute the arc length between two points. """ x1, y1, start1, end1, bulge1 = p1 x2, y2, start2, end2, bulge2 = p2 reverse = False bulge = abs(bulge1) # If bulge is greater 1.0, the angle is greater 180 degrees. # We consider the case 360 - angle and reverse in the end. if bulge > 1.0: bulge = bulge - int(bulge) # only take digits after float point reverse = True # l is half the base side of the triangle l = 0.5 * distance_2d((x1, y1), (x2, y2)) # s is the sagita: the distance between the base side of the triangle # and the circle. The bulge value can be negative, denoting the side # of the curve. Not important for its length. s = l * bulge # compute the circle's radius r = ((s*s) + (l*l)) / (2*s) # height of the triangle h = r - s if h == 0.0: # edge case: half circle leads to h = 0 alpha = math.pi else: # angle in the triangle in the middle of the circle alpha = 2 * math.atan(l/h) # arc length as part of the entire circumference of the circle arc_length = alpha * r if reverse: arc_length = 2*r*math.pi - arc_length return arc_length def get_polyline_length(polyline): """ Computes the total length of a given polyline. A polyline consists of points in the 2D space and a bulge value which indicates curves. """ length = 0 with polyline.points('xyseb') as points: if not (points[-1][4] == 0.0000): # bulge from last point to first length += get_arc_length(points[-1], points[0]) for i in (range(len(points) - 1)): p1 = points[i] p2 = points[i + 1] x1, y1, start1, end1, bulge1 = p1 x2, y2, start2, end2, bulge2 = p2 if bulge1 == 0.0000: length += distance_2d((x1, y1), (x2, y2)) else: length += get_arc_length(p1, p2) return length def get_edge_sum(msp): """ Iterate over all elements in the modelspace and sum up the edge lengths. """ total_length = 0 for e in msp: dxftype = e.dxftype() if dxftype == DXF_TYPE_LWPOLYLINE: total_length += get_polyline_length(e) elif dxftype == DXF_TYPE_CIRCLE: circumference = 2 * e.dxf.radius * math.pi total_length += circumference elif dxftype == DXF_TYPE_ARC: angle = e.dxf.end_angle - e.dxf.start_angle total_length += get_arc_length_simple(e.dxf.radius, angle) elif dxftype == DXF_TYPE_LINE: x1, y1, _ = e.dxf.start x2, y2, _ = e.dxf.end total_length += distance_2d((x1, y1), (x2, y2)) elif dxftype in {DXF_TYPE_TEXT, DXF_TYPE_INSERT, DXF_TYPE_MTEXT}: continue else: logging.error(f'Fehler -> {dxftype} is unknown.') raise ValueError(f'Fehler: Unbekanntes CAD Element: {dxftype}') return round(total_length, 3) def get_min_square(msp, offset=5): """ Return the size of the minimal square around this drawing. """ if offset < 0: print('Negativer Offset ist nicht erlaubt! Setze Offset = 0') offset = 0 all_points = [] for e in msp: dxftype = e.dxftype() if dxftype == DXF_TYPE_LWPOLYLINE: with e.points('xyseb') as points: for point in points: x, y, *_ = point all_points.append((x, y)) elif dxftype == DXF_TYPE_CIRCLE: radius = e.dxf.radius center = e.dxf.center all_points.append((center[0] - radius, center[1] - radius)) all_points.append((center[0] + radius, center[1] + radius)) elif dxftype == DXF_TYPE_LINE: x1, y1, _ = e.dxf.start x2, y2, _ = e.dxf.end all_points.append((x1, y1)) all_points.append((x2, y2)) elif dxftype == DXF_TYPE_ARC: x1, y1, _ = e.start_point x2, y2, _ = e.end_point radius = e.dxf.radius center = e.dxf.center all_points.append((x1, y1)) all_points.append((x2, y2)) #all_points.append((center[0] - radius, center[1] - radius)) #all_points.append((center[0] + radius, center[1] + radius)) arc_points = compute_arc_points(e) all_points.extend(arc_points) elif dxftype in {DXF_TYPE_TEXT, DXF_TYPE_INSERT, DXF_TYPE_MTEXT}: continue else: logging.error(f'Fehler -> {dxftype} is unknown.') raise ValueError(f'Fehler: Unbekanntes CAD Element: {dxftype}') if not all_points: raise ValueError('Die/eine angegebene Zeichnung ist leer/fehlerhaft.') min_x = min(all_points, key=lambda p: p[0])[0] min_y = min(all_points, key=lambda p: p[1])[1] max_x = max(all_points, key=lambda p: p[0])[0] max_y = max(all_points, key=lambda p: p[1])[1] a = distance_2d((min_x, 0), (max_x, 0)) + 2*offset b = distance_2d((0, min_y), (0, max_y)) + 2*offset return a, b, round(a * b, 3) def compute_arc_points(e): """ 3 points on the arc - This is a very rough approximation of the arc """ points = [] center_x, center_y, *_ = e.dxf.center start_angle = e.dxf.start_angle end_angle = e.dxf.end_angle radius = e.dxf.radius rotation_angle = (end_angle - start_angle)/2 x = center_x + radius * math.cos(rotation_angle) y = center_y + radius * math.sin(rotation_angle) points.append((x, y)) # TODO: Diese Winkel passen nicht?! x = center_x + radius * math.cos(rotation_angle/4) y = center_y + radius * math.sin(rotation_angle/4) #points.append((x, y)) x = center_x + radius * math.cos(3*rotation_angle/4) y = center_y + radius * math.sin(3*rotation_angle/4) #points.append((x, y)) return points def get_dxf_model_space(path): """ Return the DXF file's model space. """ document = ezdxf.readfile(path) return document.modelspace() def process_dxf_file(path, offset): """ Compute total edge length and minimal square of a given drawing. """ model_space = get_dxf_model_space(path) total_edge_length = get_edge_sum(model_space) logging.debug(f'Kantenlänge = {round(total_edge_length / 10, 2)}cm') # min_square is a tuple! (length a, length b, area) min_square = get_min_square(model_space, offset) logging.debug(f'Kleinstes Rechteck: a = {round(min_square[0] / 10, 2)}cm, b = {round(min_square[1] / 10, 2)}cm, Fläche = {round(min_square[2] / 100, 2)}cm2') area_mm2 = min_square[2] return total_edge_length, area_mm2
6784d650612574c41665f81d47fff4598bf3b7aa
Revel109/Uri-Problems-Solution-10-20-
/prob-15.py
202
3.609375
4
import math a=input().split(" ") b=input().split(" ") x1,y1=a x2,y2=b z=math.sqrt(((float(x2) - float(x1))*(float(x2) - float(x1))) + ((float(y2)-float(y1)) *(float(y2)-float(y1)))) print('%.4lf'%z)
d14cfcde4dadc3e4e509fa8a57ec6d2822eb4fb4
ashutoshkrjha/Daily_Code_Challenge
/Karumanchi_Algos/Ch2/bitnstrings.py
465
3.953125
4
def bitstring(num_bits, global_arr): if (num_bits == 0): print(global_arr) else: global_arr[num_bits - 1] = 0 bitstring(num_bits - 1, global_arr) global_arr[num_bits - 1] = 1 bitstring(num_bits - 1, global_arr) def main(): num_bits = input("Give me the number of bits:") num_bits = int(num_bits) global_arr = [None] * num_bits bitstring(num_bits, global_arr) if __name__ == '__main__': main()
a17e198eeaac4a06b472845f6dffdd2bcf1f74c3
damsonli/mitx6.00.1x
/Mid_Term/problem7.py
2,190
4.4375
4
''' Write a function called score that meets the specifications below. def score(word, f): """ word, a string of length > 1 of alphabetical characters (upper and lowercase) f, a function that takes in two int arguments and returns an int Returns the score of word as defined by the method: 1) Score for each letter is its location in the alphabet (a=1 ... z=26) times its distance from start of word. Ex. the scores for the letters in 'adD' are 1*0, 4*1, and 4*2. 2) The score for a word is the result of applying f to the scores of the word's two highest scoring letters. The first parameter to f is the highest letter score, and the second parameter is the second highest letter score. Ex. If f returns the sum of its arguments, then the score for 'adD' is 12 """ #YOUR CODE HERE Paste your entire function, including the definition, in the box below. Do not leave any print statements. ''' def score(word, f): """ word, a string of length > 1 of alphabetical characters (upper and lowercase) f, a function that takes in two int arguments and returns an int Returns the score of word as defined by the method: 1) Score for each letter is its location in the alphabet (a=1 ... z=26) times its distance from start of word. Ex. the scores for the letters in 'adD' are 1*0, 4*1, and 4*2. 2) The score for a word is the result of applying f to the scores of the word's two highest scoring letters. The first parameter to f is the highest letter score, and the second parameter is the second highest letter score. Ex. If f returns the sum of its arguments, then the score for 'adD' is 12 """ #YOUR CODE HERE i = 0 scores = [] word = word.lower() for letter in word: score = (ord(letter) - ord('a') + 1) * i scores.append(score) i += 1 scores = sorted(scores, reverse=True) return f(scores[0], scores[1]) def f(num1, num2): print(num1) print(num2) return num1 + num2 print(score('adDe', f))
622b10cab635fa09528ffdeab353bfd42e69bdc7
damsonli/mitx6.00.1x
/Final Exam/problem7.py
2,105
4.46875
4
""" Implement the class myDict with the methods below, which will represent a dictionary without using a dictionary object. The methods you implement below should have the same behavior as a dict object, including raising appropriate exceptions. Your code does not have to be efficient. Any code that uses a Python dictionary object will receive 0. For example: With a dict: | With a myDict: ------------------------------------------------------------------------------- d = {} md = myDict() # initialize a new object using your choice of implementation d[1] = 2 md.assign(1,2) # use assign method to add a key,value pair print(d[1]) print(md.getval(1)) # use getval method to get value stored for key 1 del(d[1]) md.delete(1) # use delete method to remove key,value pair associated with key 1 """ class myDict(object): """ Implements a dictionary without using a dictionary """ def __init__(self): """ initialization of your representation """ self.keys = [] self.values = [] def assign(self, k, v): """ k (the key) and v (the value), immutable objects """ if k not in self.keys: self.keys.append(k) self.values.append(v) else: index = self.keys.index(k) self.values[index] = v def getval(self, k): """ k, immutable object """ if k not in self.keys: raise KeyError(k) else: index = self.keys.index(k) return self.values[index] def delete(self, k): """ k, immutable object """ if k not in self.keys: raise KeyError(k) else: index = self.keys.index(k) self.keys.pop(index) self.values.pop(index) md = myDict() print(md.keys) print(md.values) md.assign(1,2) print(md.keys) print(md.values) md.assign('a', 'c') print(md.keys) print(md.values) md.assign(1,3) print(md.keys) print(md.values) print(md.getval(1)) #print(md.getval('d')) md.delete(1) print(md.keys) print(md.values) md.delete('d')
de17bb8bd8f94f087845cd59e2ad83f7b43f8ebd
Nicolanz/holbertonschool-web_back_end
/0x00-python_variable_annotations/3-to_str.py
269
4.21875
4
#!/usr/bin/env python3 """Module to return str repr of floats""" def to_str(n: float) -> str: """Function to get the string representation of floats Args: n (float): [float number] Returns: str: [str repr of n] """ return str(n)
180368ef6cef54de3e94387eddd54ff39a41e4c4
Nicolanz/holbertonschool-web_back_end
/0x04-pagination/0-simple_helper_function.py
460
3.890625
4
#!/usr/bin/env python3 """Module containing index_range function""" from typing import Tuple def index_range(page: int, page_size: int) -> Tuple[int, int]: """Index range function Args: page (int): [Number of page] page_size (int): [Number of page size] Returns: Tuple[int, int]: [Tuple with two values] """ my_page = page_size * (page - 1) my_page_size = page * page_size return my_page, my_page_size
a124cd5fc15e3058c03414c35fb9a9df61ff98f6
Nicolanz/holbertonschool-web_back_end
/0x01-python_async_function/2-measure_runtime.py
559
3.640625
4
#!/usr/bin/env python3 """Module to create a measure_time function with integers n and max_delay""" import time import asyncio wait_n = __import__('1-concurrent_coroutines').wait_n def measure_time(n: int, max_delay: int) -> float: """Function o measure time Args: n (int): [number of items] max_delay (int): [max delay of the range] Returns: float: [total time] """ start_time = time.time() new_list = asyncio.run(wait_n(n, max_delay)) total_time = time.time() - start_time return total_time / n
94c63cf09da1e944b67ca243ee40f67ad3550cf5
Nicolanz/holbertonschool-web_back_end
/0x00-python_variable_annotations/9-element_length.py
435
4.28125
4
#!/usr/bin/env python3 """Module with correct annotation""" from typing import Iterable, Sequence, List, Tuple def element_length(lst: Iterable[Sequence]) -> List[Tuple[Sequence, int]]: """Calculates the length of the tuples inside a list Args: lst (Sequence[Iterable]): [List] Returns: List[Tuple[Sequence, int]]: [New list with the length of the tupes] """ return [(i, len(i)) for i in lst]
522c24738fc362ea620859d392eab2a3bd63dcc3
Feldron21/Flappy-Bird-Bot
/learning.py
4,299
3.5
4
import json from json import JSONDecodeError import random class Learning: def __init__(self): # Initialize the agent self.previous_state = "0_0_0_0" self.previous_action = 0 self.discount_factor = 0.9 self.learning_rate = 0.8 self.reward = {0: -1, 1: -100} self.epsilon = 0.1 # for epsilon greedy algorithm self.moves = [] self.scores = [] self.max_score = 0 self.episode = 0 self.qvalues = {} self.load_qvalues() def load_qvalues(self): try: with open("data\game_history.json", "r") as file: self.qvalues = json.load(file) except IOError: self.initialize_qvalues(self.previous_state) except JSONDecodeError: self.initialize_qvalues(self.previous_state) def initialize_qvalues(self, state): if self.qvalues.get(state) is None: self.qvalues[state] = [0, 0, 0] def act(self, x, y, vel): state = self.get_state(x, y, vel) self.moves.append((self.previous_state, self.previous_action, state)) self.previous_state = state if random.random() <= self.epsilon: self.previous_action = random.choice([0, 1]) return self.previous_action # Chose the best action : default is 0 (don't do anything) or 1 (flap) self.previous_action = 0 if self.qvalues[state][0] >= self.qvalues[state][1] else 1 return self.previous_action # Update Q values using history def update_qvalues(self, score): self.episode += 1 self.scores.append(score) self.max_score = max(score, self.max_score) history = list(reversed(self.moves)) print('/n/n') print(history) dead = True if int(history[0][2].split("_")[1]) > 120 else False t, last_flap = 0, True for move in history: t += 1 state, action, new_state = move self.qvalues[state][2] += 1 reward = self.reward[0] if t <= 2: reward = self.reward[1] if action: last_flap = False elif (last_flap or dead) and action: reward = self.reward[1] last_flap = False dead = False self.qvalues[state][action] = (self.qvalues[state][action] + self.learning_rate * ( reward + self.discount_factor * max(self.qvalues[state][0:2]))) if self.learning_rate < 0.1: self.learning_rate = 0.9 if self.epsilon > 0: self.epsilon = 0 self.moves = [] def get_state(self, x, y, vel): if x < 140: x = int(x) - (int(x) % 10) else: x = int(x) - (int(x) % 70) if y < 180: y = int(y) - (int(y) % 10) else: y = int(y) - (int(y) % 60) state = str(int(x)) + "_" + str(int(y)) + "_" + str(vel) self.initialize_qvalues(state) return state def end_episode(self, score): self.episode += 1 self.scores.append(score) self.max_score = max(score, self.max_score) history = list(reversed(self.moves)) for move in history: state, action, new_state = move self.qvalues[state][action] = (1 - self.learning_rate) * (self.qvalues[state][action] + self.learning_rate * ( self.reward[0] + self.discount_factor * max(self.qvalues[state][0:2]))) self.moves = [] def qvalues_to_json(self): print(f"Saving Q Table with {len(self.qvalues.keys())} states ...") with open("data\game_history.json", "w") as file: json.dump(self.qvalues, file)
aedfe44fe94a31da053f830a56ad5842c77b4610
jesseklein406/data-structures
/simple_graph.py
2,747
4.28125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- """A data structure for a simple graph using the model from Martin BroadHurst http://www.martinbroadhurst.com/graph-data-structures.html """ class Node(object): """A Node class for use in a simple graph""" def __init__(self, name, value): """Make a new node object""" self.name = name self.value = value class G(tuple): """A data structure for a simple graph""" def __init__(self): """Make a new simple graph object""" self.nodes_ = set() self.edges_ = set() def __repr__(self): return (self.nodes_, self.edges_) def nodes(self): """return a list of all nodes in the graph""" return list(self.nodes_) def edges(self): """return a list of all edges in the graph""" return list(self.edges_) def add_node(self, n): """adds a new node 'n' to the graph""" self.nodes_.add(n) def add_edge(self, n1, n2): """adds a new edge to the graph connecting 'n1' and 'n2', if either n1 or n2 are not already present in the graph, they should be added. """ if n1 not in self.nodes_: self.nodes_.add(n1) if n2 not in self.nodes_: self.nodes_.add(n2) self.edges_.add((n1, n2)) def del_node(self, n): """deletes the node 'n' from the graph, raises an error if no such node exists """ self.nodes_.remove(n) for edge in self.edges_.copy(): if n in edge: self.edges_.remove(edge) def del_edge(self, n1, n2): """deletes the edge connecting 'n1' and 'n2' from the graph, raises an error if no such edge exists """ self.edges_.remove((n1, n2)) def has_node(self, n): """True if node 'n' is contained in the graph, False if not. """ return n in self.nodes_ def neighbors(self, n): """returns the list of all nodes connected to 'n' by edges, raises an error if n is not in g """ if n not in self.nodes_: raise ValueError("Node not in graph") neighbors = set() for edge in self.edges_: if edge[0] is n: neighbors.add(edge[1]) return list(neighbors) def adjacent(self, n1, n2): """returns True if there is an edge connecting n1 and n2, False if not, raises an error if either of the supplied nodes are not in g """ if n1 not in self.nodes_ or n2 not in self.nodes_: raise ValueError("Both nodes not in graph") for edge in self.edges_: if n1 in edge and n2 in edge: return True return False
b90c20842ac3410291253377a8f2026c1330e9f2
jesseklein406/data-structures
/merge.py
4,506
4.28125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import unicode_literals def merge_sort(lst): """ Sort a list of values using merge sort. Return the sorted version of the list """ if len(lst) <= 1: return lst middle = len(lst) // 2 left = lst[:middle] right = lst[middle:] sort_left = merge_sort(left) sort_right = merge_sort(right) return merge(sort_left, sort_right) def merge(left, right): """ Helper function for merge sort. Merges two pre-sorted lists of values """ sort = [] l_index = 0 r_index = 0 while l_index < len(left) and r_index < len(right): if left[l_index] <= right[r_index]: sort.append(left[l_index]) l_index += 1 else: sort.append(right[r_index]) r_index += 1 if l_index < len(left): sort.extend(left[l_index:]) else: sort.extend(right[r_index:]) return sort if __name__ == '__main__': from timeit import Timer def best_case(n): return range(n) def worst_case(n): return range(n, 0, -1) print print "Time for best case of list of first 10 integers" print Timer( 'merge_sort(best_case(10))', 'from __main__ import merge_sort, best_case' ).timeit(10) / 10 print print "Time for worst case of list of first 10 integers" print Timer( 'merge_sort(worst_case(10))', 'from __main__ import merge_sort, worst_case' ).timeit(10) / 10 print print "Time for best case of list of first 100 integers" print Timer( 'merge_sort(best_case(100))', 'from __main__ import merge_sort, best_case' ).timeit(10) / 10 print print "Time for worst case of list of first 100 integers" print Timer( 'merge_sort(worst_case(100))', 'from __main__ import merge_sort, worst_case' ).timeit(10) / 10 print print "Time for best case of list of first 1000 integers" print Timer( 'merge_sort(best_case(1000))', 'from __main__ import merge_sort, best_case' ).timeit(10) / 10 print print "Time for worst case of list of first 1000 integers" print Timer( 'merge_sort(worst_case(1000))', 'from __main__ import merge_sort, worst_case' ).timeit(10) / 10 print print "Time for best case of list of first 2000 integers" print Timer( 'merge_sort(best_case(2000))', 'from __main__ import merge_sort, best_case' ).timeit(10) / 10 print print "Time for worst case of list of first 2000 integers" print Timer( 'merge_sort(worst_case(2000))', 'from __main__ import merge_sort, worst_case' ).timeit(10) / 10 print print "Time for best case of list of first 3000 integers" print Timer( 'merge_sort(best_case(3000))', 'from __main__ import merge_sort, best_case' ).timeit(10) / 10 print print "Time for worst case of list of first 3000 integers" print Timer( 'merge_sort(worst_case(3000))', 'from __main__ import merge_sort, worst_case' ).timeit(10) / 10 print print "Time for best case of list of first 4000 integers" print Timer( 'merge_sort(best_case(4000))', 'from __main__ import merge_sort, best_case' ).timeit(10) / 10 print print "Time for worst case of list of first 4000 integers" print Timer( 'merge_sort(worst_case(4000))', 'from __main__ import merge_sort, worst_case' ).timeit(10) / 10 print print "Time for best case of list of first 5000 integers" print Timer( 'merge_sort(best_case(5000))', 'from __main__ import merge_sort, best_case' ).timeit(10) / 10 print print "Time for worst case of list of first 5000 integers" print Timer( 'merge_sort(worst_case(5000))', 'from __main__ import merge_sort, worst_case' ).timeit(10) / 10 print "These tests approximately model O(n log(n)) behavior for all cases" print "so the merge sort is unbiased of how well sorted any inputs are prior" print "to a merge sort. The merge sort is ideal for large, poorly sorted data" print "sets, as compared to insertion sort which is O(n2) in worst cases." print "However merge sorts are more expensive with space as compared to" print "other algorithms, according to Wikipedia" print "https://en.wikipedia.org/wiki/Merge_sort"
ca00f0b24983a61a3691a80acf8017e63290dc1b
lsommerer/number-guessing-game
/main.py
1,315
4.09375
4
import time import random def main(): """ A simple number guessing game framework. """ lowerLimit = 1 upperLimit = 20 correctGuess = random.randint(lowerLimit, upperLimit) currentGuess = 'wrong-number' maxTries = 5 currentTry = 0 pauseTime = 1 print('I am thinking of a number between',lowerLimit,'and',upperLimit) print('You have',maxTries,'attempts to guess my number.') # # While we are not out of guesses and the correct number # hasn't been guessed, keep looping. # while (currentTry < maxTries) and (currentGuess != correctGuess): currentGuess = input('Guess my number: ') # # Make sure the user guesses a number. # while currentGuess.isdigit() == False: currentGuess = input('You have to guess a number: ') currentTry = currentTry + 1 currentGuess = int(currentGuess) time.sleep(pauseTime) if currentGuess < correctGuess: print('My number is higher.') if currentGuess > correctGuess: print('My number is lower.') if currentGuess == correctGuess: print('Nice work! You guessed my number in ',currentTry,'tries.') else: print('You ran out of tires. My number was',correctGuess) main()
71c4de24e31e2f6dddf916debd083071d6ec9a0f
upsmancsr/Algorithms
/making_change/making_change.py
1,518
4.03125
4
#!/usr/bin/python import sys def making_change(amount, denominations): # --- method 1 start --- # if amount == 0: # return 1 # if amount < 0: # return 0 # if len(denominations) == 0: # return 0 # return making_change(amount - denominations[-1], denominations) + making_change(amount, denominations[-1]) # --- method 1 end --- ways = [0] * (amount + 1) ways[0] = 1 # ways will be an array, each element is number of ways to get to 0 cents, 1 cent, 2 cents, 3 cents, ... , amount of cents for coin in denominations: # Loop through each coin denomination 1, 5, 10, 25, 50 for higher_amount in range(coin, amount + 1): # Loop through each integer from current coin (denomination) to (amount + 1) remainder = higher_amount - coin ways[higher_amount] += ways[remainder] # shorthand for ways[higher_amount] = ways[higher_amount] + ways[remainder] # print(f'{coin} {ways}') # number of ways to get to 0 cents, 1 cent, 2 cents, 3 cents, ... , amount of cents return ways[amount] if __name__ == "__main__": # Test our your implementation from the command line # with `python making_change.py [amount]` with different amounts if len(sys.argv) > 1: denominations = [1, 5, 10, 25, 50] amount = int(sys.argv[1]) print("There are {ways} ways to make {amount} cents.".format(ways=making_change(amount, denominations), amount=amount)) else: print("Usage: making_change.py [amount]")
d15f0e09c36d24cb1685e9e14ca94de6eeee5826
7ty/Programming1Repository
/HYShapes- Edited by TH/Pyramid.py
525
3.671875
4
class Pyramid: def __init__(self,pyramidL,pyramidW,pyramidH): self.pyramidL = int(pyramidL) self.pyramidW = int(pyramidW) self.pyramidH = int(pyramidH) def calcVol(self,pyramidL,pyramidW,pyramidH): print("The volume is: " + str((pyramidL*pyramidW*pyramidH)/3)) def calcSA(self,pyramidL,pyramidW,pyramidH): print("The surface area is: " + str((pyramidL*pyramidW)+(pyramidL*(((pyramidW/2)**2)+pyramidH**2)**0.5)+(pyramidW*(((pyramidL/2)**2)+pyramidH**2)**0.5)))
34aa3059b0bd6a2b100280fd3e6580b551fe71c9
FathimaRz/python-assignment1-2-day4
/ASSIGNMENT1DAY4RAZ.py
324
3.90625
4
#!/usr/bin/env python # coding: utf-8 # In[2]: str1= "what we think we become; we are python programmers" str1.count ("we") # In[3]: str1.count ("we",0,15) # In[4]: str1[0:15].count("we") # In[5]: str1.find("we") # In[6]: str1[5] # In[7]: str1.rfind("we") # In[8]: str1.index("we") # In[ ]:
56ca126bba997578083504a366e2afaeeaf9d046
prabhakarjoshi/face-recognition-based-attendance-system
/GUI/Get_The_Password_UI.py
954
3.71875
4
from DB.Get_Password_db import Get_Password_db_fun from tkinter import * import tkinter.messagebox def Get_The_Password_fun(): def Get_Password_db_fun_helper(): str=Get_Password_db_fun(entry_1.get(),entry_2.get()) root3.destroy() tkinter.messagebox.showinfo("Password","Your Password is '"+str+"'") # root3.destroy() root3=Tk() root3.geometry('400x300') root3.title("Forget Password") root3.resizable(0,0) label_1 = Label(root3, text="Name :",width=20, font=("bold", 10)) label_1.place(x=40,y=40) entry_1 = Entry(root3) entry_1.place(x=200,y=40) label_2 = Label(root3, text="Code No. :",width=20,font=("bold", 10)) label_2.place(x=40,y=80) entry_2 = Entry(root3) entry_2.place(x=200,y=80) but_Get=Button(root3, text='Get Password',width=12,bg='brown',fg='white',command=Get_Password_db_fun_helper) but_Get.place(x=150,y=180) root3.mainloop()
f6a3c26889b4837b0e6a80cbcea3b6f9b4ae75eb
ryansdowning/aoc-2020
/aoc_2020/day22.py
1,329
3.515625
4
def game_score(deck): return sum(i * card for i, card in enumerate(deck[::-1], 1)) def solve1(deck_a, deck_b): while deck_a and deck_b: a, b = deck_a.pop(0), deck_b.pop(0) if a > b: deck_a += [a, b] else: deck_b += [b, a] return game_score(deck_a if deck_a else deck_b) def solve2(deck_a, deck_b): def play(deck_a, deck_b): mem = set() while deck_a and deck_b: if (game := (tuple(deck_a), tuple(deck_b))) in mem: return 1, deck_a mem.add(game) a, b = deck_a.pop(0), deck_b.pop(0) if len(deck_a) >= a and len(deck_b) >= b: winner, _ = play(deck_a[:a], deck_b[:b]) else: winner = int(b > a) + 1 if winner == 1: deck_a += [a, b] else: deck_b += [b, a] return (1, deck_a) if deck_a else (2, deck_b) return game_score(play(deck_a, deck_b)[1]) if __name__ == "__main__": with open('../data/day22.txt', 'r') as f: _, player_a, player_b = f.read().split('Player') player_a = list(map(int, player_a[3:].split())) player_b = list(map(int, player_b[3:].split())) print(solve1(player_a[::], player_b[::])) print(solve2(player_a[::], player_b[::]))
4bc7aa00dc066c938517d221940333af32335ec9
memiles47/PythonWithMosh
/HelloWorld/app.py
138
3.625
4
birthYear = input('Birth Year: ') # print(type(birthYear)) age = 2019 - int(birthYear) print(type(birthYear)) print(type(age)) print(age)
70b72d5cae0908be4f08976911f0e5eb3082c800
CaioHenriqueMachado/Algoritmo-A-estrela
/AEstrela.py
4,905
3.640625
4
class Aresta: def __init__(self, alvo,custo): self.custo=custo self.alvo=alvo def getCusto(self): return self.custo def getAlvo(self): return self.alvo class No: def __init__(self, nome, funcaoH): self.nome=nome self.funcaoH=funcaoH self.funcaoF=0 self.adjacente=None def getNome(self): return self.nome def getFuncaoH(self): return self.funcaoH def setFuncaoF(self, funcaoF): self.funcaoF = funcaoF def getFuncaoF(self): return self.funcaoF def setFuncaoG(self, funcaoG): self.funcaoG=funcaoG def getFuncaoG(self): return self.funcaoG def setAdjacente(self, adjacente): self.adjacente=adjacente def getAdjacente(self): return self.adjacente def setAdjacentes(self, adjacentes): self.adjacentes=adjacentes def getAdjacentes(self): return self.adjacentes def encontrarMenor(lista): menor = 0 for indice in range(0,len(lista)): if(lista[menor].getFuncaoF()>lista[indice].getFuncaoF()): menor = indice return lista.pop(menor) def percorrerCaminho(alvo): caminho = "]" while(not(alvo is None)): caminho=", "+alvo.getNome()+caminho alvo=alvo.getAdjacente() caminho = "["+caminho return caminho def aEstrela(origem,fim): # 1. Criar fila explorados e fila de prioridades = {Ø} fila=[] explorados=[] # 2. Se origem == destino -> finaliza if(origem.getNome() != fim.getNome()): # 3. Função g do nó origem = 0 origem.setFuncaoG(0) # 4. filaPrioridades adiciona origem fila.append(origem) # 5. Enquanto filaPrioridades não vazia e destino não encontrado encontrado=False while(len(fila)>0 and not(encontrado)): # 5_1. Nó atual = Nó com menor função f atual = encontrarMenor(fila) # 5_2. Fila explorados adiciona nó atual explorados.append(atual) # 5_3. Se nó atual == destino -> parar if(atual.getNome()==fim.getNome()): encontrado=True # 5_4. Se não... else: # 5_4_1. Para cada aresta adjacente do no atual for aresta in atual.getAdjacentes(): # 5_4_2. Nó filho = aresta.alvo filho = aresta.getAlvo() # 5_4_3. funcaoGTemp= noAtual.FuncaoG() + aresta.custo funcaoGTemp = atual.getFuncaoG() + aresta.getCusto() # 5_4_4. funcaoFTemp= funcaoGTemp+ noFilho.FuncaoH() funcaoFTemp= funcaoGTemp+filho.getFuncaoH() # 5_4_5. Se caso o nó filho já tenha sido explorado e seu valor de função f é maior que a função f do pai, então ele é desconsiderado if((filho in explorados) and (funcaoFTemp>=filho.getFuncaoF())): continue # 5_4_6. senão se o nó filho não está na filaPrioridadesou sua função f é maior que a funcaoFTemp elif((filho not in fila)or (funcaoFTemp < filho.getFuncaoF())): # 5_4_6_1. filho.Adjacente= atual filho.setAdjacente(atual) # 5_4_6_2.filho.funcaoG= funcaoGTemp filho.setFuncaoG(funcaoGTemp) # 5_4_6_3. filho.funcaoF= funcaoFTemp filho.setFuncaoF(funcaoFTemp) # 5_4_6_4. Se filaPrioridadescontem filho # 5_4_6_5. fila.removefilho if(filho not in fila): # 5_4_6_5. Fila adiciona filho fila.append(filho) # --------------------------------------------------------------------------- arad = No("Arad",366) bucharest=No("Bucharest",0) craiova = No("Craiova",160) eforie=No("Eforie",161) fagaras= No("Fagaras",178) giurgiu = No("Giurgiu", 77) zerind = No("Zerind", 374) oradea = No("Oradea", 380) sibiu = No("Sibiu", 253) rimnicu = No("Rimnicu Vilcea", 193) pitesti = No("Pitesti", 98) timisoara = No("Timisoara", 329) lugoj = No("Lugoj", 244) mehadia = No("Mehadia", 241) drobeta = No("Drobeta", 242) arad.setAdjacentes([Aresta(zerind,75),Aresta(sibiu,140),Aresta(timisoara,118)]) zerind.setAdjacentes([Aresta(arad,75),Aresta(oradea,71)]) oradea.setAdjacentes([Aresta(zerind,71),Aresta(sibiu,151)]) sibiu.setAdjacentes([Aresta(arad,140),Aresta(fagaras,99),Aresta(oradea,151),Aresta(rimnicu,80)]) fagaras.setAdjacentes([Aresta(sibiu,99),Aresta(bucharest,211)]) rimnicu.setAdjacentes([Aresta(sibiu,80),Aresta(pitesti,97),Aresta(craiova,146)]) pitesti.setAdjacentes([Aresta(rimnicu,97),Aresta(bucharest,101),Aresta(craiova,138)]) timisoara.setAdjacentes([Aresta(arad,118),Aresta(lugoj,111)]) lugoj.setAdjacentes([Aresta(timisoara,111),Aresta(mehadia,70)]) mehadia.setAdjacentes([Aresta(lugoj,70),Aresta(drobeta,75)]) drobeta.setAdjacentes([Aresta(mehadia,75),Aresta(craiova,120)]) craiova.setAdjacentes([Aresta(drobeta,120),Aresta(rimnicu,146),Aresta(pitesti,138)]) bucharest.setAdjacentes([Aresta(pitesti,101),Aresta(giurgiu,90),Aresta(fagaras,211)]) giurgiu.setAdjacentes([Aresta(bucharest,90)]) aEstrela(arad,bucharest) print(percorrerCaminho(bucharest))
3ba8d38d218d435affea8e4a9bfa6644568fd4f4
Vlad-Shcherbina/PegJumping
/render.py
6,444
3.5
4
from __future__ import division from math import sqrt, erf, log, exp import io import collections class Distribution(object): def __init__(self): self.n = 0 self.sum = 0 self.sum2 = 0 self.max = float('-inf') self.min = float('+inf') def add_value(self, x): self.n += 1 self.sum += x self.sum2 += x*x self.max = max(self.max, x) self.min = min(self.min, x) def mean(self): if self.n == 0: return 0 return self.sum / self.n def sigma(self): if self.n < 2: return 0 mean = self.mean() sigma2 = (self.sum2 - 2*mean*self.sum + mean*mean*self.n) / (self.n - 1) if sigma2 < 0: # numerical errors sigma2 = 0 return sqrt(sigma2) def to_html(self): if self.n == 0: return '--' if self.sigma() < 1e-10: return str(self.mean()) return ( '<span title="{}..{}, {} items">' '{:.3f} &plusmn; <i>{:.3f}</i>' '</span>'.format( self.min, self.max, self.n, self.mean(), self.sigma())) def prob_mean_larger(self, other): """ Probability that actual mean of this dist is larger than of another. """ if self.n == 0 or other.n == 0: return 0.5 diff_mean = self.mean() - other.mean() sigma1 = self.sigma() sigma2 = other.sigma() # If we have no data about variance of one of the distributions, # we take it from another distribution. if other.n == 1: sigma2 = sigma1 if self.n == 1: sigma1 = sigma2 diff_sigma = sqrt(sigma1**2 + sigma2**2) if diff_sigma == 0: if diff_mean > 0: return 1 elif diff_mean < 0: return 0 else: return 0.5 p = 0.5 * (1 + erf(diff_mean / (sqrt(2) * diff_sigma))) return p def aggregate_stats(results): stats = collections.defaultdict(Distribution) for result in results: # for dp in result['data_points']: # for k, v in dp.items(): # if k != 'type': # stats[k].add_value(v) stats['log_score'].add_value( log(result['score']) if result['score'] else -100) stats.setdefault('seeds', []).append(result['seed']) for k, v in result.items(): if k in ('score', 'seed', 'time', 'longest_path_stats'): continue stats[k].add_value(v) return stats def color_prob(p): if p < 0.5: red = 1 - 2 * p; return '#{:x}00'.format(int(15 * red)) else: green = 2 * p - 1 return '#0{:x}0'.format(int(15 * green)) def render_cell(results, baseline_results): fout = io.StringIO() stats = aggregate_stats(results) baseline_stats = aggregate_stats(baseline_results) color = color_prob(stats['log_score'].prob_mean_larger(baseline_stats['log_score'])) print(color) fout.write( '<span style="font-size:125%; font-weight:bold; color:{color}">' 'log_score = {log_score}</span>' '<br>score = {score}' .format( color=color, score=exp(stats['log_score'].mean()), log_score=stats['log_score'].to_html())) for k, v in sorted(stats.items()): if k != 'log_score': if isinstance(v, Distribution): color = color_prob(v.prob_mean_larger(baseline_stats[k])) fout.write('<br>{} = <span style="color:{}">{}</span>'.format( k, color, v.to_html())) else: v = str(v) if len(v) > 43: v = v[:40] + '...' fout.write('<br>{} = {}'.format(k, v)) return fout.getvalue() class DummyGrouper(object): def __init__(self): pass def get_bucket(self, result): return None def get_all_buckets(self, all_results): return [None] def belongs_to_bucket(self, result, bucket): return True def is_bucket_special(self, bucket): return False class FunctionGrouper(object): def __init__(self, function): self.function = function def get_bucket(self, result): return self.function(result) def get_all_buckets(self, all_results): return [None] + sorted(set(map(self.get_bucket, all_results))) def belongs_to_bucket(self, result, bucket): return bucket is None or self.get_bucket(result) == bucket def is_bucket_special(self, bucket): return bucket is None def render_table(results, baseline_results): fout = io.StringIO() fout.write('<table>') fout.write('<tr> <th></th>') column_grouper = FunctionGrouper(lambda result: int((result['density'] - 0.1) * 6) / 3) row_grouper = FunctionGrouper(lambda result: (result['n'] - 20) // 7 * 7 + 20) for column_bucket in column_grouper.get_all_buckets(results + baseline_results): fout.write('<th>{}</th>'.format(column_bucket)) fout.write('</tr>') for row_bucket in row_grouper.get_all_buckets(results + baseline_results): fout.write('<tr>') fout.write('<th>{}</th>'.format(row_bucket)) for column_bucket in column_grouper.get_all_buckets(results + baseline_results): filtered_results = [] for result in results: if (row_grouper.belongs_to_bucket(result, row_bucket) and column_grouper.belongs_to_bucket(result, column_bucket)): filtered_results.append(result) filtered_baseline_results = [] for result in baseline_results: if (row_grouper.belongs_to_bucket(result, row_bucket) and column_grouper.belongs_to_bucket(result, column_bucket)): filtered_baseline_results.append(result) if (row_grouper.is_bucket_special(row_bucket) or column_grouper.is_bucket_special(column_bucket)): fout.write('<td align="right" bgcolor=#eee>') else: fout.write('<td align="right">') fout.write(render_cell(filtered_results, filtered_baseline_results)) fout.write('</td>') fout.write('</tr>') fout.write('</table>') return fout.getvalue()
51428801feafb425b87e8ece7f93416e7e64c69b
yuvaltimen/LanguageModel
/language_model.py
16,346
3.625
4
import sys from math import log10 import numpy as np import matplotlib.pyplot as plt from random import choice as rand_choice """ Yuval Timen N-Gram statistical language model generalized for all n-gram orders >= 1 Main method will train a unigram and bigram model, will generate 50 sentences from each of these models, will create histograms from the probabilities of each test set, and will calculate the perplexity of the first 10 sentences of the test set. """ class LanguageModel: UNK = "<UNK>" SENT_BEGIN = "<s>" SENT_END = "</s>" MIN_FREQUENCY = 2 # Threshold for <UNK> def __init__(self, n_gram, is_laplace_smoothing, verbose=False): """Initializes an untrained LanguageModel Parameters: n_gram (int): the n-gram order of the language model to create is_laplace_smoothing (bool): whether or not to use Laplace smoothing backoff (str): optional argument with default value None of whether or not to use a backoff stragety. Options: ["katz"] """ # The order of the n-grams used for this model if (n_gram < 1) or (type(n_gram) != int): raise Exception("N-gram order must be an integer >= 1") self.ngram_order = n_gram # The set of words encountered by the model self.vocabulary = set() # The size of the vocabulary - used in some calculations self.vocab_size = 0 # Counts for the n-grams self.n_gram_counts = dict() # List of n-grams for sentence generation self.n_gram_list = list() # Whether to use laplace smoothing self.use_laplace_smoothing = is_laplace_smoothing # Whether to print verbose output self.verbose = verbose # The log to print out at the end self.log = "" def load_tokens(self, training_file_path): """Reads the training data from the given path and produces a list of tokens. Parameters: training_file_path (str) the location of the training data to read Returns: list: the list of tokenized sentences """ output_list = [] with open(training_file_path) as f: for line in f.readlines(): output_list.extend(line.split()) if self.verbose: self.log += f"Loaded in {training_file_path}\n Found {len(output_list)} tokens\n" return output_list def create_ngrams(self, tokens, n): """Creates a list of n-grams from the provided list of tokens Parameters: tokens (list) the list of tokenized words n (int) the order of the n-grams to produce Returns: list: the list of tuples representing each n-gram """ output_list = [] for idx in range(len(tokens) - n + 1): output_list.append(tuple(tokens[idx:idx + n])) if self.verbose: self.log += f"Splicing: {tokens[:4]} \nFound {len(output_list)} n-grams\n" return output_list def replace_by_unk(self, tokens): """Replaces any token not encountered by the model with <UNK> Parameters: tokens (list) the list of tokenized words Returns: list: the list of tokens, with any unknown words replaced with <UNK> """ for idx in range(len(tokens)): if tokens[idx] not in self.vocabulary: tokens[idx] = self.UNK return tokens def train(self, training_file_path): """Trains the language model on the given data. Assumes that the given data has tokens that are white-space separated, has one sentence per line, and that the sentences begin with <s> and end with </s> Parameters: training_file_path (str): the location of the training data to read Returns: None """ # Refresh the counting dict and n-gram list in case we re-train an existing model self.n_gram_counts = dict() self.n_gram_list = list() tokens = self.load_tokens(training_file_path) # First pass - replace any word below the MIN_FREQUENCY with <UNK> initial_counts = dict() for token in tokens: if token in initial_counts.keys(): initial_counts[token] += 1 else: initial_counts[token] = 1 for idx in range(len(tokens)): if initial_counts[tokens[idx]] < self.MIN_FREQUENCY: tokens[idx] = self.UNK # Save our vocab size for future computations self.vocabulary = set(tokens) self.vocab_size = len(self.vocabulary) # Second pass - create n-grams and update counts in stored dict n_grams = self.create_ngrams(tokens, self.ngram_order) for ngram in n_grams: # Put this n-gram in our list - we will sample from it later during sentence generation self.n_gram_list.append(ngram) # Update the count associated with each n-gram in our dictionary if ngram in self.n_gram_counts.keys(): self.n_gram_counts[ngram] += 1 else: self.n_gram_counts[ngram] = 1 if self.verbose: self.log += f"Training {self.ngram_order}-gram model...\n" self.log += f"|V| = {self.vocab_size}\n" self.log += f"Range: [{min(self.n_gram_counts.values())},{max(self.n_gram_counts.values())}]\n" def score(self, sentence): """Calculates the probability score for a given string representing a single sentence. Parameters: sentence (str): a sentence with tokens separated by whitespace to calculate the score of Returns: float: the probability value of the given string for this model """ if self.verbose: self.log += "Scoring...\n" # If the string is empty then we have a problem if not sentence: raise Exception("Cannot score an empty string") # Given an example sentence of '<s> w1 w2 w3 w4 w5 </s>' # We want to compute bigram probability of this sentence # So for bigrams, we calculate: # MLE = P(w1 | <s>) * P(w2 | w1) * P(w3 | w2) * P(w4 | w3) * P(w5 | w4) * P(</s> | w5) sentence_tokens = sentence.split() sentence_tokens = self.replace_by_unk(sentence_tokens) sentence_ngrams = self.create_ngrams(sentence_tokens, self.ngram_order) # Now sentence_ngrams = [(<s>, w1), (w1, w2), (w2, w3), (w3, w4), (w4, w5), (w5, </s>)] # For a unigram model, P(w) = C(w) / sum_w(C(w)) # For a bigram model, P(w2 | w1) = C((w1, w2)) / C(w1) # For an n-gram model, P(wN | w1, w2, ... w_N-1) = C(w1...wN) / C(w1 ... w_N-1) log_probability = 0 for sentence_ngram in sentence_ngrams: # How many times does this n-gram occur? if sentence_ngram in self.n_gram_counts.keys(): numerator = self.n_gram_counts[sentence_ngram] elif self.use_laplace_smoothing: numerator = 0 else: if self.verbose: self.log += f"P(\"{sentence}\") = 0\n" return 0 # How many times do all n-grams with words w1...w_N-1 occur? # Sum up the counts for all keys that share the first N-1 tokens of our n-gram if self.ngram_order == 1: # Save on computation time - if we're using a unigram model, then # the denominator is just the total count of unigrams denominator = sum(self.n_gram_counts.values()) else: # Find all matching tuples up to N-1 denominator = 0 for key in self.n_gram_counts.keys(): if key[:-1] == sentence_ngram[:-1]: denominator += self.n_gram_counts[key] if self.verbose: if self.use_laplace_smoothing: self.log += f"(({numerator} + 1)/({denominator} + {self.vocab_size})) * \n" else: self.log += f"(({numerator})/({denominator})) * \n" # Add to the running log-probability total if self.use_laplace_smoothing: log_probability += log10((numerator + 1) / (denominator + self.vocab_size)) else: log_probability += log10(numerator / denominator) # Return the result as a probability -> 2^log_prob ans = pow(10, log_probability) if self.verbose: self.log += f"P(\"{sentence}\") = {ans}\n" return ans def perplexity(self, test_sequence): """Measures the perplexity for the given test sequence with this trained model. As described in the text, you may assume that this sequence may consist of many sentences "glued together". Parameters: test_sequence (string): a sequence of space-separated tokens to measure the perplexity of Returns: float: the perplexity of the given sequence """ # Measure the probability of the sequence using our language model sequence_probability = self.score(test_sequence) # PP(W) = [P(w1 w2.... wN)]^(-1/N) perplexity = pow(sequence_probability, -1/self.vocab_size) if self.verbose: self.log += f"PP(\"{test_sequence}\") = {perplexity}\n" return perplexity def print_log(self): """Prints out the log to the console Parameters: None Returns: None """ print(self.log) def sew_together(self, tupls): """Takes in a list of tuples of order n and 'sews' them together to form a string. Parameters: tupls (list) The list of tuples to be combined Returns: str: The sewn together n-grams """ output = [] # Iterate through the list for idx in range(len(tupls)): # If it's the last tuple, take all the entries if idx == len(tupls) - 1: output.extend(tupls[idx]) # Otherwise, take just the first entry else: output.append(tupls[idx][0]) return " ".join(output) def generate_sentence(self): """Generates a single sentence from a trained language model using the Shannon technique. Returns: str: the generated sentence """ output = [] # Define the initial filter function - the first N-1 terms of the tuple must be <s> init_filt = lambda tup: tup[:-1] == tuple(self.SENT_BEGIN for _ in range(self.ngram_order - 1)) # Filter out all n-grams that don't satisfy this init_candidates = list(filter(init_filt, self.n_gram_list)) # Choose randomly from list - each n-gram is duplicated according to its frequency already output.append(rand_choice(init_candidates)) # While we have not yet found the end token while output[-1][-1] != self.SENT_END: # Filter out all n-grams that don't succeed the last one current_candidates = list(filter(lambda tup: tup[:-1] == output[-1][1:], self.n_gram_list)) current_candidates = list(filter(lambda tup: tup != (self.SENT_BEGIN,), current_candidates)) output.append(rand_choice(current_candidates)) # Tack on any remaining </s> tokens add_to_end = [self.SENT_END for _ in range(self.ngram_order - 2)] output[-1] = tuple(list(output[-1]) + add_to_end) if output[0] != (self.SENT_BEGIN,) and self.ngram_order == 1: output.insert(0, (self.SENT_BEGIN,)) return self.sew_together(output) def generate(self, n): """Generates n sentences from a trained language model using the Shannon technique. Parameters: n (int): the number of sentences to generate Returns: list: a list containing strings, one per generated sentence """ output = [] self.log += f"Generating {n} sentences for {self.ngram_order}-gram model:\n" for _ in range(n): sent = self.generate_sentence() output.append(sent) self.log += f"{sent}\n" return output def load_sentences(testing_file_path): """Reads the testing data line by line and returns a list of lines. Parameters: testing_file_path (str) the location of the data to be read Returns: list: the list of sentences to test """ output = [] with open(testing_file_path, 'r') as f_read: for line in f_read.readlines(): line = line.strip() if line: output.append(line) return output def create_histogram(values, f_path_1, f_path_2, file_save_name=None): """Plot a histogram showing the relative frequency of the probabilities. Returns: None """ f = plt.figure() all_vals = values[0] + values[1] overall_min = min(all_vals) min_exponent = np.floor(np.log10(np.abs(overall_min))) plt.hist(values, bins=np.logspace(np.log10(10 ** min_exponent), np.log10(1.0)), label=["label1", "label2"], stacked=True) plt.xlabel("Probability of test sentence") plt.ylabel("Frequency of score") plt.xscale('log') plt.legend([f_path_1, f_path_2]) plt.title("Test Score vs. Frequency of Score") plt.show() if file_save_name is None: print("Figure not saved") else: f.savefig(file_save_name) def main(): # Create the models unigram_model = LanguageModel(1, True) bigram_model = LanguageModel(2, True) # Load in the testing data testing_data_1 = load_sentences(sys.argv[2]) testing_data_2 = load_sentences(sys.argv[3]) # Train, generate sentences unigram_model.train(sys.argv[1]) print("-----SENTENCES FROM UNIGRAMS-----") for sent in unigram_model.generate(50): print(sent) unigram_scores_tests_1 = [] unigram_scores_tests_2 = [] for sent in testing_data_1: unigram_scores_tests_1.append(unigram_model.score(sent)) for sent in testing_data_2: unigram_scores_tests_2.append(unigram_model.score(sent)) # Train, generate sentences bigram_model.train(sys.argv[1]) print("-----SENTENCES FROM BIGRAMS-----") for sent in bigram_model.generate(50): print(sent) bigram_scores_tests_1 = [] bigram_scores_tests_2 = [] for sent in testing_data_1: bigram_scores_tests_1.append(bigram_model.score(sent)) for sent in testing_data_2: bigram_scores_tests_2.append(bigram_model.score(sent)) # Create histograms and save as file savename_1 = "hw2-unigram-histogram.pdf" savename_2 = "hw2-bigram-histogram.pdf" create_histogram([unigram_scores_tests_1, unigram_scores_tests_2], sys.argv[2], sys.argv[3], savename_1) create_histogram([bigram_scores_tests_1, bigram_scores_tests_2], sys.argv[2], sys.argv[3], savename_2) # Calculate perplexity for each file and model print("\nPerplexity for 1-grams:") perplexity_1_1 = unigram_model.perplexity(" ".join(testing_data_1[:10])) perplexity_1_2 = unigram_model.perplexity(" ".join(testing_data_2[:10])) print(f"hw2-test.txt: {perplexity_1_1}") print(f"hw2-my-test.txt: {perplexity_1_2}") print("\nPerplexity for 2-grams:") perplexity_2_1 = bigram_model.perplexity(" ".join(testing_data_1[:10])) perplexity_2_2 = bigram_model.perplexity(" ".join(testing_data_2[:10])) print(f"hw2-test.txt: {perplexity_2_1}") print(f"hw2-my-test.txt: {perplexity_2_2}") if __name__ == '__main__': if len(sys.argv) != 4: print("Usage:", "python hw2_lm.py training_file.txt textingfile1.txt textingfile2.txt") sys.exit(1) main()
630ca37331b91d15e5c808cb77e658ea38a591bf
pooja-pichad/list
/substract ilist.py
509
3.5625
4
l1 = [10, 20, 30, 40, 50, 60] l2 = [60, 50, 40, 30, 20, 10] a= [] # i=0 for i in range(len(l1)): if l1[i] > l2[i]: a.append(l1[i] - l2[i]) else: a.append(l1[i]) print("Original list are :") print(l1) print(l2) print("\nOutput list is") print(a) # while i<len(l1): # if l1[i]>l2[i]: # a.append(l1[i]-l2[i]) # else: # a.append(l1[-i]) # i=i+1 # print("original list is:") # print(l1) # print(l2) # print("output of given list:") # print(a)
eb8b61a458f25d4b4c2e047aac42eb619688abcc
pooja-pichad/list
/code sum.py
208
4
4
# Write a program to find the sum of all elements of a list. # a=[1,2,3,4,5,6,7,8,9] # i=0 # sum=0 # while i<len(a): # b=a[i] # sum=sum+b # i=i+1 # print(sum) # # i=i+1 a=[1,2,3,4,5,6,7]
db9f20c4fe4300a16f19f7c582d0d4c2986b17da
pooja-pichad/list
/largest smallest.py
164
3.921875
4
# Find largest and smallest elements of a list. a=[1,3,4,7,8,9,11,12] i=0 large=a[i] while i<len(a): if a[i]>large: large=a[i] i=i+1 print(large)
45c2833deed1c43476f35496cce681a2fba7d17e
pooja-pichad/list
/1 se 10 lis.py
225
3.546875
4
# output=[1,1,1,1,1,1,1,1,1] a=[1,2,3,4,5,6,7,8,9,10] # i=0 # b=[] # while i<len(a): # t=a[i] # b.append(t*5) # i=i+1 # print(b) i=1 b=[] while i<len(a): t=a[0] b.append(t*1) i=i+1 print(b)
b33d4b18f0e3dedb594d79c68a5512b29ec21ab9
amanchauhan98/shoes-bill
/shoes_program.py
2,394
3.9375
4
import time pair = 0 cost = 0 print("|---------------------|") print(" AMAN SHOES STORE ") print("|---------------------|") name = str(input("Enter your name here\n")) phone = (input("Enter your mobile number here\n")) adress = str(input("Enter your address\n")) time.sleep(0.5) print("THANK YOU!") print("for entering information here!") i = 1 print("we have many types of varities available for our shoes. like:\n") print("[1]. Sports [2]. Sneakers [3].Formal [4].Informal [5].Dancing and many more") type = str(input("Enter the type of shoes do you want?\n")) if type == "sports" : print("How Much pair do you want?") pair = int(input()) price = int(500) cost = pair*price print("The price of your",type,"shoes is",cost) # f = open("shoes.txt","a") # f.write(type) # f.close() elif type == "sneakers" : print("How Much pair do you want?") pair = int(input()) price = int(600) cost = pair*price print("The price of your",type,"shoes is",cost) elif type == "formal" : print("How Much pair do you want?") pair = int(input()) price = int(800) cost = pair*price print("The price of your",type,"shoes is",cost) elif type == "informal" : print("How Much pair do you want?") pair = int(input()) price = int(1000) cost = pair*price print("The price of your",type,"shoes is",cost) elif type == "dancing" : print("How Much pair do you want?") pair = int(input()) price = int(1200) cost = pair*price print("The price of your",type,"shoes is",cost) time.sleep(2) def print_bill() : print("|---------------------|") print(" AMAN SHOES STORE ") print("|---------------------|") print("|Name :-",name) print("|Phone :-",phone) print("|Address :-",adress) print("|Shoes :-",type) print("|Pair :-",pair) print("|Cost :-",cost) print_bill() f = open("shoes.txt","a") f.write(name) f.write("\n") f.write(phone) f.write("\n") f.write(adress) f.write("\n") f.write(type) f.write("\n") f.write(str(pair)) f.write("\n") f.write(str(cost)) f.write("\n") f.close()
d496e4a15bff3c8f728128e5e16b82dcd4f12f21
zadair005/Introduction-to-Data-Science
/Functions.py
3,048
3.75
4
Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 27 2018, 04:06:47) [MSC v.1914 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> #Below is the function >>> def hello(): print ("hello") return 1234 #And here is the function being used print hello() SyntaxError: invalid syntax >>> print(hello()) Traceback (most recent call last): File "<pyshell#6>", line 1, in <module> print(hello()) NameError: name 'hello' is not defined >>> ef hello(): print ("hello") return 1234 #And here is the function being used print (hello()) SyntaxError: invalid syntax >>> def hello(): print ("hello") return 1234 #And here is the function being used print(hello()) SyntaxError: invalid syntax >>> hello Traceback (most recent call last): File "<pyshell#9>", line 1, in <module> hello NameError: name 'hello' is not defined >>> #How parameters work >>> def funnyfunction(first_word,second_word,third_word): print("The word created is: " + first_word + second_word + third_word) return first_word + second_word + third_word >>> #Calculator program >>> #NO CODE IS REALLY RUN HERE, IT IS ONLY TELLING US WHAT WE WILL DO LATER >>> #Here we will define our functions >>> #this prints the main menu, and prompts for a choice >>> def menu(): #print what options you have print("Welcome to calculatory.py") print("your options are:") print(" ") print("1) Addition") print("2) Subtraction") print("3) Multiplication") print("4) Division") print("5) Quit calculator.py") print(" ") return input ("Choose your option: ") #this adds two numbers given def add(a,b): SyntaxError: invalid syntax >>> def add(a,b): print a, "+", b, "=", a + b SyntaxError: Missing parentheses in call to 'print'. Did you mean print(a, "+", b, "=", a + b)? >>> def add(a,b): print(a, "+", b, "=", a + b) >>> #this subtracts two numbers given >>> def sub(a,b) SyntaxError: invalid syntax >>> def sub(a,b): print(b, "-", a, "=", b - a) >>> #this multiplies two numbers given >>> def mul(a,b): print(a, "*", b, "=", a * b) >>> #this divides two numbers given >>> def div(a,b): print(a, "/", b, "=", a / b) >>> #NOW THE PROGRAM REALLY STARTS, AS CODE IS RUN >>> loop = 1 >>> choice = 0 >>> while loop == 1: choice = menu() if choice == 1: add(input("Add this: "),input("to this: ")) elif choice == 2: sub(input("Subtract this: "),input("from this: ")) elif choice == 3: mul(input("Multiply this: "),input("from this: ")) elif choice == 4: div(input("Divide this: "),input("from this: ")) elif choice == 5: loop = 0 print("Thank you for using calculator.py") SyntaxError: invalid syntax >>> add(2,30) 2 + 30 = 32 >>> sub(2,30) 30 - 2 = 28 >>> num1 = 45 >>> num2 = 8 >>> add(num1,num2) 45 + 8 = 53 >>> div(num1,num8) Traceback (most recent call last): File "<pyshell#72>", line 1, in <module> div(num1,num8) NameError: name 'num8' is not defined >>> div(num1,num2) 45 / 8 = 5.625 >>>
a7413dc1858d6a48a49692f302cd88be66a6925d
Sanria2309/caramel-ice-cream
/Hangman Game.py
6,785
3.703125
4
import time import random def intro() : print("It is adviced to play with uppercase characters.") time.sleep(2) print("Just remember, if you are ever stuck and need help, hit the 'h'(not 'H') button.\n") print("Best of luck for the game !!") time.sleep(2) pr("Let's begin the game...") print("\n") time.sleep(3) def lev() : lev=input("Enter the level, you want to play (Easy/Medium/Hard) : ") print("You want to play {} level.".format(lev)) time.sleep(2) easy_words=["JUICY", "FUNNY", "FILM", "QUIZ", "LUCKY"] easy_hint=["We all love to eat _ _ _ _ _ apples.", "It struck her _ _ _ _ _ and she giggled.", "He made his _ _ _ _ debut in 1992.", "The sports trivia _ _ _ _ isn't all that bad.", "She got _ _ _ _ _, and won jackpot."] medium_words=["PUZZLE", "ZOMBIE", "YUMMY", "YIPPEE"] medium_hint=["The pieces of the _ _ _ _ _ simply didn't fit together", "a corpse said to be revived by witchcraft, especially in certain African and Caribbean religions.", "These gummy bears are so _ _ _ _ _.", "Expressing wild excitement or delight."] hard_words=["KNOWLEDGE", "MICROWAVE", "UNKNOWN", "BOOKWORM", "WITCHCRAFT", "TRANSPLANT"] hard_hint=["I acquired more _ _ _ _ _ _ _ _ _ on the subject.", "These are immense artificial excavations of _ _ _ _ _ _ _ date.", "A _ _ _ _ _ _ _ _ is a person who enjoys reading.", "Witch A person, normally a woman who practices _ _ _ _ _ _ _ _ _ _.","Cornea _ _ _ _ _ _ _ _ _ _ was carried out in March 2001."] if lev.lower()=="easy" : intro() game(easy_hint, easy_words,6) elif lev.lower()=="medium" : intro() game(medium_hint, medium_words, 7) elif lev.lower()=="hard" : intro() game(hard_hint, hard_words, 9) else : print("You entered an invalid input !") br() again() def again() : ask=input("Do you want to play again (y/n) ?") time.sleep(1) if ask.lower()=="y" or ask.lower()=="yes" : br() lev() else : print("Have a good day !") br() def br() : print("_"*25, "\n") def pr(str1="") : print(" "*10, "*"*8, str1, "*"*8) time.sleep(2) def game(hint_list, word_list, c=8) : words_list=["JUICY", "WAVE", "QUIZ", "LUCKY", "JUMBO"] index=random.randint(0,len(words_list)-1) chance=c print("You can try {} times.".format(chance)) word=(word_list[index]) guesses="" wrong=[] l=len(word) #print(word) while chance>0 : cnt=0 for char in word : if char in guesses : print(char) else : print("_") cnt+=1 time.sleep(2) if cnt==0 : print("You won, smartie !!") print("The word is : ", word) br() time.sleep(3) break if c==9 : if chance==8 : print(" \n" " \n" " \n" " \n" " \n" " \n" " | \n" "_|_\n") if c==9 : if chance==7 : print(" \n" " \n" " \n" " \n" " \n" " | \n" " | \n" "_|_\n") if c==7 : if chance==6 : print(" \n" " \n" " \n" " \n" " | \n" " | \n" " | \n" "_|_\n") if chance==5 : print(" \n" " \n" " | \n" " | \n" " | \n" " | \n" " | \n" "_|_\n") if chance==4 : print(" \n" " | \n" " | \n" " | \n" " | \n" " | \n" " | \n" "_|_\n") if chance==3 : print(" ___\n" " | \n" " | \n" " | \n" " | \n" " | \n" " | \n" "_|_\n") if chance==2 : print(" ___\n" " | | \n" " | |\n" " | \n" " | \n" " | \n" " | \n" "_|_\n") if chance==1 : print(" ___\n" " | | \n" " | | \n" " | |\n" " | o\n" " | \n" " | \n" "_|_\n") guess=input("\nGuess the character :") if len(guess)==1 : guesses+=guess.upper() + " " if guess.upper() not in word : if guess=="h": ask_h=input("Do you need help ?(y/n)") if ask_h.lower()=="y" or ask_h.lower()=="yes": print("This is your hint...") time.sleep(2) print(hint_list[index]) chance+=1 else : print("Use Uppercase, 'H'") time.sleep(2) else : chance-=1 print("Wrong guess.") time.sleep(2) br() print("You have {} more guesses.".format(chance)) time.sleep(2) if chance==0 : print(" ___\n" " | | \n" " | | \n" " | | \n" " | o \n" " | /|\ \n" " | / \ \n" "_|_ \n") print("You lose !") print("Already guessed characters : ", guesses.replace("H","")) else : print("One character at a time !!") time.sleep(2) again() pr("WELCOME TO HANGMAN GAME") name=input("Enter your name: ") print("Hello {} !!".format(name)) time.sleep(1) lev()
097a3e342b6f3d947ea81924e8b89a1563b425bc
ElAouane/Python-Basics
/104_List.py
1,195
4.5625
5
#LIST #Defining a list #The syntax of a list is [] crazy_landlords = [] #print(type(crazy_landlords)) # We can dynamically define a list crazy_landlords = ['My. Richards', 'Raj', 'Mr. Shirik', 'Ms Zem'] #Access a item in a list. #List are organized based on the index crazy_landlords = ['My. Richards', 'Raj', 'Mr. Shirik', 'Ms Zem'] print(crazy_landlords) print(crazy_landlords[1]) #We can also redefine at a specific index #Change Raj to Rajesh crazy_landlords[1] = 'Rajesh' print(crazy_landlords) #Adding a record to the list crazy_landlords.append('Raj') crazy_landlords.insert(0, 'Hamza') print(crazy_landlords) #Remove an item from a list crazy_landlords.remove('Raj') print(crazy_landlords) #Remove using the index using POP crazy_landlords.pop() #<= Remove the highest index in the list crazy_landlords.pop(0) #<= Remove the specific index in the list print(crazy_landlords) #We can have mixed data list hybrid_list = ['JSON', 'Jason', 13, 53, [1, 2]] print(hybrid_list) #Tuples #immutable lists my_tuple = (2, 'Hello', 22, 'more values') print(my_tuple) #Range Slicing crazy_landlords[0 : 1] #<= from 0 to 1 not inclusive crazy_landlords[1 : 2] #<= from 1 to 2 not inclusive
985677d77e2d0dcda0eca81d4924075e1c8b2e77
ElAouane/Python-Basics
/110_Python_WhileLoops.py
359
3.953125
4
#Syntax #While <condition>: # block of code num = 0 # while 10 > num: # print(num) # num += 1 #2nd Syntax and pattern for while loops #While True: # block of code # control flow # if <condition> # #break for val in 'String': print(val) if val == 'i': print('going out of the loop') break print('Out of loop')
7e0db0417467e7948835dcde1c67985b76a2dce6
skdmajee/Coding
/unscramble.py
1,815
3.6875
4
from collections import defaultdict scramble = 'ehllotehotwolrd' wordset = {'the','hello','world','to'} def calchash(s, kv, ll): hk = 0 for c in s: hk += ord(c) hk *= (kv+ll) return hk def builddict(wordset): # #Creates a dictionary of words. Each entry has the string and the unique value #that is used to create the key # wdict=defaultdict(list) kv = 1 for word in wordset: hk = calchash(word, kv, len(word)) wdict[hk].append(word) wdict[hk].append(kv) kv += 1 return wdict def unscramble(scramble, wdict): # # Look for each keys in the scrambled string. Find the position and # insert into a list # wlist=[] #Loop to srch all dict words in strint for k in wdict.keys(): kv = wdict[k][-1] word = wdict[k][0] i = 0 #Key aka word srch loop while ( i < len(scramble)): end = i + len(word) win = scramble[i:end] # cacl hash hk = calchash(win, kv, len(word)) # check to see if it exists if hk not in wdict: # Shift to right and continue srching i += 1 if (i+len(word) <= len(scramble)): continue else: # Found a match s = wdict[hk][0] tp = (i,s) wlist.append(tp) print ('found %s at %d'% (s,i)) break; return(wlist) def getkey(k): return k[0] def main(): wd = builddict(wordset) print wd wl = unscramble(scramble, wd) # Sort the list according to position number print wl a = sorted(wl, key=lambda wl:wl[0]) #a = sorted(wl, key=getkey) print a if __name__ == "__main__": main()
dfc818c931c516d40f82d5d2b16c18bd2b2ff20d
vibhor3081/GL_OD_Tracker
/lib.py
2,986
4.1875
4
import pandas as pd def queryTable(conn, tablename, colname, value, *colnames): """ This function queries a table using `colname = value` as a filter. All columns in colnames are returned. If no colnames are specified, `select *` is performed :param conn: the connection with the database to be used to execute/fetch the query :param tablename: the tablename to query :param colname: the column to filter by :param value: the value to filter by :param colnames: the columns to fetch in the result """ if not colnames: colnames = "*" else: colnames = ', '.join(colnames) df = pd.read_sql(f"SELECT {colnames} FROM {tablename} WHERE {colname}='{value}'", conn) return df def queryTableNew(conn, tablename, colname1, value1, colname2, value2, *colnames): """ This function queries a table using `colname = value` as a filter. All columns in colnames are returned. If no colnames are specified, `select *` is performed :param conn: the connection with the database to be used to execute/fetch the query :param tablename: the tablename to query :param colname: the column to filter by :param value: the value to filter by :param colnames: the columns to fetch in the result """ if not colnames: colnames = "*" else: colnames = ', '.join(colnames) df = pd.read_sql(f"SELECT {colnames} FROM {tablename} WHERE {colname1}='{value1}' AND {colname2}= '{value2}'", conn) return df def currencyFormatter(n): """ Format a number as it if were currency. Force two decimal places of precision :param n: a number to format """ s = format(round(n, 2), ',') # formatted with ','s as the 100s separator if '.' not in s: s += '.' tail = len(s.rsplit('.',1)[-1]) s += '0'*(2-tail) # rpad decimal precision to 2 places return s def cumsumByGroup(df): """ Given a dataframe, group the dateaframe by AccounNumber. Sort each group by date, multiply the Amount by -1 for CR/DR and perform a cumsum :param df: a pandas dataframe containing transaction information across multiple accounts for one customer """ df.sort_values(by=['AccountNumber', 'Date'], inplace=True, ignore_index=True) # we can sort by date here, just the one time, rather than having to sort each group individually # get a signed amount by CR/DR df['NetAmount'] = df.Amount df.loc[df.CRDR=='DR', 'NetAmount'] = df[df.CRDR=='DR']['NetAmount']*-1 df['AvailableBalance'] = None # new column for the cumsum for accountNum in df.AccountNumber.unique(): # cumsum for each account number df.loc[df.AccountNumber==accountNum, 'AvailableBalance'] = df[df.AccountNumber==accountNum].NetAmount.cumsum() df.sort_values(by=['Date'], inplace=True, ignore_index=True) # sort again by date, so that all transactions are stratified by date df.fillna(value='', inplace=True) # so that None's don't show up in the st.write(df) return df
80ef822d5d085af5e216fb57c6b15c2067836f46
yasmineElnadi/python-introductory-course
/Assignment 3/3.1.py
164
3.65625
4
#3.1 def getPentagonalNumber(n): pentagonalnumber=int((n*(3*n - 1))/2) return pentagonalnumber for i in range(1, 101): print(getPentagonalNumber(i))
e617e0788ff6129a6717d7cc26bb2a9fe2e7f12b
yasmineElnadi/python-introductory-course
/Assignment 2/2.9.py
330
4.1875
4
#wind speed ta=float(input("Enter the Temperature in Fahrenheit between -58 and 41:")) v=eval(input("Enter wind speed in miles per hour:")) if v < 2: print("wind speed should be above or equal 2 mph") else: print("the wind chill index is ", format(35.74 + (0.6215*ta) - (35.75* v**0.16) + (0.4275 * ta * v**0.16), ".5f"))
1b6d2d0843efad0980c4fa09aa7388c3b1eb609c
birkirkarl/assignment5
/Forritun/Æfingardæmi/Hlutapróf 1/practice2.py
241
4.28125
4
#. Create a program that takes two integers as input and prints their sum. inte1= int(input('Input the first integer:')) inte2= int(input('Input the second integer:')) summan= int(inte1+inte2) print('The sum of two integers is:',+summan)
3729b7247c1d1aa07ebe9b59c8b642b6740e3c6c
birkirkarl/assignment5
/Forritun/Heimadæmi/TileTraveller/filetraveller.py
290
3.609375
4
out1=False out2=False while out1==False: bref=input('Enter number of shares: ') brefin(bref) while out2==False: price=input('Enter price (dollars, numerator, denominator): ') theprice(price) while out3==False: afram=input("Continue: ") if afram=='y': else:
557aeb343b71809953779d58c5f357ab5ad6a074
birkirkarl/assignment5
/Forritun/Heimadæmi/Cards/Cards.py
5,120
4.15625
4
import random class Card(object): """ A card with rank and suit """ def __set_rank(self,rank): ''' Sets the rank of the card. The rank parameter can either be a character or an integer corresponding to the rank. Internally, the rank is an integer. ''' # rank is int: 1=Ace, 2-10 face value, 11=Jack, 12=Queen, 13=King self.__rank = 0 # Create a 0 rank as default if type(rank) == str: if rank in 'Jj': self.__rank = 11 # Jack elif rank in 'Qq': self.__rank = 12 # Queen elif rank in 'Kk': self.__rank = 13 # King elif rank in 'aA': self.__rank = 1 # Ace elif type(rank) == int: if 1 <= rank <= 14: self.__rank = rank def __set_suit(self, suit): ''' Sets the suit of the card. Suit is a character S=Space, H=Heart, D=Diamond, C=Club) ''' self.__suit = '' # create blank suit by default if type(suit) == str and suit: if suit in 'Cc': self.__suit = 'C' elif suit in 'Hh': self.__suit = 'H' elif suit in 'Dd': self.__suit = 'D' elif suit in 'Ss': self.__suit = 'S' def is_blank(self): return self.__rank == 0 or self.__suit == '' def __init__(self, rank = 0, suit = ''): if not (rank == 0 and suit == ''): self.__set_rank(rank) self.__set_suit(suit) else: self.__rank = 0 self.__suit = '' def __str__(self): """ String representation of card for printing: rank + suit, e.g. 7S or JD, 'blk' for 'no card' """ name_string = "blk A 2 3 4 5 6 7 8 9 10 J Q K" # 'blk' for blank, i.e. no card name_list = name_string.split() # create a list of names so we can index into it using rank return ("{:>3s}".format(name_list[self.__rank]+self.__suit)) class Deck(object): """ A deck to play cards with """ NUMBER_CARDS_LINE = 13 def __init__(self): """ Initialize deck as a list of all 52 cards: 13 cards in each of 4 suits """ self.__deck = [Card(i, j) for i in range(1,14) for j in "SHDC" ] # list comprehension def __str__(self): """ Represent the whole deck as a string for printing """ s = "" for index, card in enumerate(self.__deck): if index % Deck.NUMBER_CARDS_LINE == 0 and index != 0: # insert newline: print 13 cards per line s += "\n" s += str(card) + " " return s def shuffle(self): """ Shuffle the deck """ random.shuffle(self.__deck) # random.shuffle() randomly rearranges a sequence def deal(self): """ Deal a single card by returning the card that is removed off the top of the deck """ if len(self.__deck) == 0: # deck is empty return None else: return self.__deck.pop(0) # remove card (pop it) and then return it class PlayingHand(object): NUMBER_CARDS = 13 def __init__(self): """ Initializes an empty playing hand """ self.__cards = [ Card() for i in range(PlayingHand.NUMBER_CARDS)] def __str__(self): """ Represent the whole hand as a string for printing """ s = "" for card in self.__cards: s += str(card) + " " return s def add_card(self, a_card): ''' Adds the given card to the hand ''' # Find the empty slot the card empty_idx = -1 for idx, card in enumerate(self.__cards): if (card.is_blank()): empty_idx = idx break # Add the card if an empty slot is founds if empty_idx >= 0: self.__cards[empty_idx] = a_card def test_cards(): card1 = Card() print(card1) card2 = Card(5,'s') print(card2) card3 = Card('Q','D') print(card3) card4 = Card('x', 7) print(card4) def print_4_hands(hand1, hand2, hand3, hand4): ''' Prints the 4 hands ''' print(hand1) print(hand2) print(hand3) print(hand4) def deal_4_hands(deck, hand1, hand2, hand3, hand4): ''' Deals cards for 4 hands ''' for i in range(PlayingHand.NUMBER_CARDS): hand1.add_card(deck.deal()) hand2.add_card(deck.deal()) hand3.add_card(deck.deal()) hand4.add_card(deck.deal()) def test_hands(deck): hand1 = PlayingHand() hand2 = PlayingHand() hand3 = PlayingHand() hand4 = PlayingHand() print("The 4 hands:") print_4_hands(hand1, hand2, hand3, hand4) deal_4_hands(deck, hand1, hand2, hand3, hand4) print("The 4 hands after dealing:") print_4_hands(hand1, hand2, hand3, hand4) # The main program starts here random.seed(10) test_cards() deck = Deck() deck.shuffle() print("The deck:") print(deck) test_hands(deck) print("The deck after dealing:") print(deck)
3c5a435952dd3ad37df854caa705ce4c77c048d8
birkirkarl/assignment5
/Forritun/Midterm2/Analyze.list.py
1,542
3.859375
4
def is_prime(n): '''Returns True if the given positive number is prime and False otherwise''' if n == 1: return False if n == 2: return True for i in range(2,n): if n%i == 0: return False else: return True def get_numbers(get): nytt_inntak=[] nytt=get.split(',') try: for i in range(len(nytt)): tala=nytt[i] tala=int(tala) nytt_inntak.append(tala) print("Input list:",nytt_inntak) return nytt_inntak except: return print('Incorrect input!') def makeaverages(sumslist,totalint): averages_list = [] for value_int in sumslist: averages_list.append(value_int/total_int) return averages_list def sortari(nytt_inntak): sortad=sorted(nytt_inntak,key=int) print('Sorted list: ',sortad) return sortad def minmax(sortad): summa=0 counter=0 minval=sortad[0] maxval=sortad[-1] for i in sortad: summa+=int(i) counter+=1 ave=float(summa/counter) print("Min:"'%d'', Max:'"%d"', Average:',"%.2f" %minval,%maxval,%ave) return maxval,minval,ave def allarprim(nytt_inntak): prime_tolur=[] for i in nytt_inntak: if is_prime(int(i)): prime_tolur.append(int(i)) print('Prime list: ',sorted(list(set(prime_tolur)))) # The main program starts here get=input("Enter integers separated with commas: ") nytt_inntak=get_numbers(get) sortad=sortari(nytt_inntak) allarprim(nytt_inntak) minmax(sortad)
b1841b923e2e6878e14b4846d4c59328a6e351f2
birkirkarl/assignment5
/Forritun/Assignment 15 - Sets/CommonLetters.py
1,018
3.984375
4
def get_input(): a_list=input('Input a list of integers separated with a comma: ').split(',') b_list=input('Input a list of integers separated with a comma: ').split(',') a_list=[int(i) for i in a_list] b_list=[int(i) for i in b_list] return a_list, b_list def set_lists(a_list,b_list): a_set=set(a_list) b_set=set(b_list) return a_set,b_set def print_sets(a_set,b_set): print(a_set) print(b_set) def set_operation(a_set,b_set): operation=1 while operation != 4: print('1. Intersection') print('2. Union') print('3. Difference') print('4. Quit') operation=int(input('Set operation: ')) if operation == 1: print(a_set & b_set) elif operation == 2: print(a_set | b_set) elif operation ==3: print(a_set-b_set) def main(): a_list,b_list=get_input() a_set,b_set=set_lists(a_list,b_list) print_sets(a_set,b_set) set_operation(a_set,b_set) main()
bda620609ee67d3c75d75fd92ec42d7a005bddc5
birkirkarl/assignment5
/Forritun/Heimadæmi/english scramble/test.py
4,442
4.0625
4
def nyrleikur(): current_tile = 1.1 s = 'You can travel: ' coin = 0 while current_tile != 3.1: if current_tile == 1.1: print(s + '(N)orth.') direction = '' while direction != 'N': direction = str(input("Direction: ")).upper() if direction == 'N': current_tile = 1.2 else: print('Not a valid direction!') if current_tile == 1.2: k = input('Pull a lever (y/n): ') if k =='y': coin += 1 print('You received 1 coins, your total is now ' + str(coin) + '.') print(s + '(N)orth or (E)ast or (S)outh.') direction = 'W' while direction != 'N' and direction != 'S' and direction != 'E': direction = str(input("Direction: ")).upper() if direction == 'N': current_tile = 1.3 elif direction == 'E': current_tile = 2.2 elif direction == 'S': current_tile = 1.1 else: print('Not a valid direction!') if current_tile == 1.3: print(s + '(E)ast or (S)outh.') direction = '' while direction != 'E' and direction != 'S': direction = str(input("Direction: ")).upper() if direction == 'E': current_tile = 2.3 elif direction == 'S': current_tile = 1.2 else: print('Not a valid direction!') if current_tile == 2.1: print(s + '(N)orth.') direction = '' while direction != 'N': direction = str(input("Direction: ")).upper() if direction == 'N': current_tile = 2.2 else: print('Not a valid direction!') if current_tile == 2.2: k = input('Pull a lever (y/n): ') if k =='y': coin += 1 print(' You received 1 coins, your total is now '+str(coin)+'.') print(s + '(S)outh or (W)est.') direction = '' while direction != 'W' and direction != 'S': direction = str(input("Direction: ")).upper() if direction == 'S': current_tile = 2.1 elif direction == 'W': current_tile = 1.2 else: print('Not a valid direction!') if current_tile == 2.3: k = input('Pull a lever (y/n): ') if k =='y': coin += 1 print('You received 1 coins, your total is now '+str(coin)+'.') print(s + '(E)ast or (W)est.') direction = '' while direction != 'E' and direction != 'W': direction = str(input("Direction: ")).upper() if direction == 'E': current_tile = 3.3 elif direction == 'W': current_tile = 1.3 else: print('Not a valid direction!') if current_tile == 3.2: k = input('Pull a lever (y/n): ') if k =='y': coin += 1 print('You received 1 coins, your total is now '+str(coin)+'.') print(s + '(N)orth or (S)outh.') direction = '' while direction != 'N' and direction != 'S': direction = str(input("Direction: ")).upper() if direction == 'N': current_tile = 3.3 elif direction == 'S': current_tile = 3.1 print('Victory!') else: print('Not a valid direction!') if current_tile == 3.3: print(s + '(S)outh or (W)est.') direction = '' while direction != 'S' and direction != 'W': direction = str(input("Direction: ")).upper() if direction == 'S': current_tile = 3.2 elif direction == 'W': current_tile = 2.3 else: print('Not a valid direction!') g = 'y' while g == 'y': nyrleikur() g = input('Play again (y/n): ')
c326ce32719b4f47e4c5257e54d1b2c093c3e7cd
birkirkarl/assignment5
/Forritun/Assignment 7 - Functions /Fibonacci.py
323
3.90625
4
def fibo(x): array=[1,1] if x!=1: for i in range(2,x): tala=(array[i-2])+(array[i-1]) array.append(tala) for n in range(0, len(array)): print(array[n], end=' ') else: print(x) n = int(input("Input the length of Fibonacci sequence (n>=1): ")) fibo(n)
18ad8bcf6e920438f101c955b30c4e4d11f72e4b
birkirkarl/assignment5
/Forritun/Assignment 10 - lists/PascalTriangle.py
422
4.15625
4
def make_new_row(row): new_row = [] for i in range(0,len(row)+1): if i == 0 or i == len(row): new_row.append(1) else: new_row.append(row[i]+row[i-1]) return new_row # Main program starts here - DO NOT CHANGE height = int(input("Height of Pascal's triangle (n>=1): ")) new_row = [] for i in range(height): new_row = make_new_row(new_row) print(new_row)
8ea021e0d21620c3bdd2a4f48fccc60d0465efe8
birkirkarl/assignment5
/Forritun/Frá Brynjari/Fs%3a_Python/sk.py
1,495
3.921875
4
import re from fractions import Fraction def skalli(u, s): if u.isdigit() or ('/') in u: if '/' in u and ' ' in u: u = u.split(' ') a = Fraction(u[0]) + Fraction(u[1]) a *= Fraction(s) b = Fraction(a) if int(b) != 0: rest = b - int(b) e = str(int(b)) + ' ' + str(Fraction(rest)) elif '/' in u: b = Fraction(u) * Fraction(s) c = Fraction(b) if int(c) != 0: rest = c - int(c) e = str(int(c)) + ' ' + str(Fraction(rest)) elif '/' in u: b = Fraction(u) * Fraction(s) e = Fraction(b) if int(e) != 0: if int(e) != e: rest = e - int(e) e = str(int(e)) + ' ' + str(Fraction(rest)) else: b = Fraction(u) * Fraction(s) c = Fraction(b) if int(c) != 0: if int(c) != c: rest = c - int(c) e = str(int(c)) + ' ' + str(Fraction(rest)) return print(scale('''Ingredients 4 skinless, boneless chicken thighs 1/2 cup soy sauce 1/2 cup ketchup 1 1/3 cup honey 3 cloves garlic, minced 1 teaspoon dried basil''', '1/2')) '''Ingredients 2 skinless, boneless chicken thighs 1/4 cup soy sauce 1/4 cup ketchup 1/6 cup honey 1 1/2 cloves garlic, minced 1/2 teaspoon dried basil''' print(skalli('4', '1/2'))
ec624856087f5952ad3b3e440dd7879478b291ef
birkirkarl/assignment5
/Forritun/Æfingardæmi/Heimadæmi gerð aftur/klassarúrfyrraprofi.py
1,709
3.796875
4
class OrderLine(object): def __init__(self, name, price, number, discount): self.name=name self.price = price self.number = number self.discount = discount def __str__(self): return "{0:<10}{1:<9}{2:<11}{3:<12}{4:<5}".format(self.name, self.price, self.number, self.discount, self.price * self.number) class Order(object): def __init__(self): self.lines = [] def __str__(self): result = 'Product Price Quantity Discount Total \n' result += '==============================================\n' for line in self.lines: result += '{0}\n'.format(str(line)) result += '==============================================\n' total, totalExcludingDiscount, discount = self.getTotals() result += 'Total excluding discount : {0:>21.0f}\n'.format(totalExcludingDiscount) result += 'Total discount: {0:>31.0f}\n'.format(discount) result += 'Total: {0:>40.0f}\n'.format(total) return result def addLine(self, name, price, number, discount): self.lines.append(OrderLine(name, price, number,discount)) def getTotals(self): total_ex = 0 total_disc = 0 for line in self.lines: total_ex += line.price * line.number total_disc += line.price * line.number * (line.discount / 100) return total_ex - total_disc, total_ex, total_disc def main(): order = Order() order.addLine("eggs", 60, 12, 0) order.addLine("bread", 200, 1, 10) order.addLine("milk", 120, 2, 5) total, _, _ = order.getTotals() print("The total price is: {0:0f}".format(total)) print(order) main()
f8d320c1892c3458552bc3eb5d66a9f092a00ebc
birkirkarl/assignment5
/Forritun/Heimadæmi/PriceOfStock/priceOfStock.py
1,331
3.59375
4
#hef int i öllu til að checka hvort þetta séu tölur def brefin(): global out1 global bref while out1==False: bref=input('Enter number of shares: ') try: bref = int(bref) out1=True return except ValueError or SyntaxError or NameError: print("Invalid number!") def theprice(): global out2 global bref while out2==False: try: price=input('Enter price (dollars, numerator, denominator): ') x,y,z=price.split(" ")# splitta þessu í sitthvorar tölurnar frá því að vera í string num= int(x) num1= int(y) num2= int(z) verd="{0:.2f}".format(bref*(num+num1/num2)) out2=True return print('%d shares with market price %d %d/%d have value $%s' %(bref,num,num1,num2,verd)) except ValueError or SyntaxError or TypeError or NameError:# gerði alla þessa errors bara til að vera viss um að fara í exception en ekki að fá villu. print("Invalid price!") out1=False out2=False afram='y' while afram == 'y': # aðal loopan sem lætur allt keyrast brefin() theprice() afram=input("Continue: ") if afram=='y': out1=False # endurstilli gildin svo function keyrist aftur out2=False
6d1d4e00410eba10b7396a5f41ec2775c634d424
birkirkarl/assignment5
/Forritun/Æfingardæmi/Heimadæmi gerð aftur/midterm2.py
1,963
4
4
# def filereader(x): # try: # file_name=open(x,'r') # return file_name # except: # return False # def word_tool(the_file): # file_list=[] # longest=0 # for i in the_file: # file_list.append(i.strip()) # for i in range(len(file_list)): # if len(file_list[i])>longest: # longest=len(file_list[i]) # the_word=file_list[i] # print('Longest word is \'{}\' of length {}'.format(the_word,longest)) # def main(): # x=input('Enter name of file: ') # the_file=filereader(x) # if the_file == False: # print('File {} not found!'.format(x)) # else: # word_tool(the_file) # #main() # def is_prime(n): # '''Returns True if the given positive number is prime and False otherwise''' # if n == 1: # return False # if n == 2: # return True # for i in range(2,n): # if n%i == 0: # return False # else: # return True # def get_numbers(get): # basic_list=[] # prime_list=[] # try: # for i in get: # basic_list.append(int(i)) # if is_prime(int(i)): # prime_list.append(int(i)) # return basic_list, prime_list # except: # print('Incorrect input!') # def basic_stuff(basic_list,prime_list): # print('Input list: {}'.format(basic_list)) # print('Sorted list: {}'.format(sorted(basic_list))) # prime_stuff(prime_list) # Average=(sum(basic_list)/len(basic_list)) # minimum=min(basic_list) # maximum=max(basic_list) # print('Min: {}, Max: {}, Average: {:.2f}'.format(maximum,minimum,Average)) # def prime_stuff(prime_list): # correct_prime=list(set(prime_list)) # print('Prime list: {}'.format(sorted(correct_prime))) # get=input("Enter integers separated with commas: ").split(',') # basic_list,prime_list=get_numbers(get) # basic_stuff(basic_list,prime_list)
77627ea28d92565289b6cd6c76778f0c98bf8c18
birkirkarl/assignment5
/BKS Önn/age.py
225
4.03125
4
age_float=float(input("Enter your age: ")) if 0 <= age_float < 34: print("Young") elif 35 <= age_float < 50: print("Mature") elif 51 <= age_float < 69: print("Middle-aged") elif 70 <= age_float: print("Old")
b09764f40c136fe3c93a97976e545f8ba67db081
phil-nye/MontyHallSimulation
/MontyHall.py
4,120
4
4
import random as rnd class GameShow: win_count = 0 lose_count = 0 total = 0 def __init__(self): self.doors = ['reward', 'nothing a', 'nothing b'] self.reward = 0 self.wrong = 0 self.host = '' self.player = '' self.set_door() def set_door(self): rnd.shuffle(self.doors) print(self.doors) self.reward = self.doors.index('reward') self.host = 'reward' # only enable if you want user input def player_choice(self): decision = input('Enter (1, 2, or 3): ') # loop if invalid input while decision != '3' and decision != '2' and decision != '1': decision = input('Enter (1, 2, or 3): ') self.player = self.doors[int(decision) - 1] def set_wrong(self): # this method is suboptimal # pick a wrong door that has not been chosen, yet while self.host == 'reward' or self.host == self.player: self.host = rnd.choice(self.doors) self.wrong = self.doors.index(self.host) + 1 def get_wrong(self): return self.wrong def check_win(self): if self.player == 'reward': self.win_count += 1 else: self.lose_count += 1 self.total += 1 def rand_change(self): change = rnd.randint(0, 1) if change == 1: self.always_change() def always_change(self): new_choice = rnd.choice(self.doors) while new_choice is self.player or new_choice is self.host: new_choice = rnd.choice(self.doors) self.player = new_choice def play(self): again = 'y' while again.lower() == 'y': again = '' print("There are three doors. Only one of these doors has a reward behind it. Choose wisely...") self.set_door() self.player_choice() self.set_wrong() print("\nHere is a clue. There is no reward behind Door", self.get_wrong(), '\b.') change = input("\nDo you want to change? (Y/N) ") # loop if invalid input while change.lower() != 'y' and change.lower() != 'n': change = input("Do you want to change? (Y/N) ") # Uncomment below to cheat # print("\nHost: ", self.wrong + 1, '(', self.host, ')', "\tPlayer: ", self.player) if change == 'y': self.player_choice() print("\nReward:", self.reward + 1, ", Choice:", self.doors.index(self.player) + 1, self.player) self.check_win() # loop if invalid input while again.lower() != 'y' and again.lower() != 'n': again = input("\nPlay again? (Y/N) ") print('\n\n') print("Wins:", self.win_count, "/", self.total) print("Losses:", self.lose_count, "/", self.total) def autoplay(self, method=0, trials=100): for x in range(trials): self.set_door() # reset door placement self.player = rnd.choice(self.doors) self.set_wrong() self.get_wrong() if method == 2: print('Change Randomly') self.rand_change() elif method == 1: print('Always Change') self.always_change() else: print('No Change (by default)') # print(x, "\b:", self.get_door(), ",", self.get_choice()) self.check_win() print("Wins:", self.win_count, "/", self.total) print("Losses:", self.lose_count, "/", self.total) @staticmethod def auto(method=0, trials=100): g = GameShow() g.autoplay(method, trials) @staticmethod def game(): g = GameShow() g.play() # print("No Change") # g = GameShow() # g.autoplay(0, 1000000) # print("Always Change") # g = GameShow() # g.autoplay(1, 1000000) # print("Randomly Change") # g = GameShow() # g.autoplay(2, 1000000) # g = GameShow() # g.play()
5cac525605095e2923c91749bed70eace20e5912
Seal-Li/statistics-learning-method
/knn.py
2,026
3.6875
4
# -*- coding: utf-8 -*- import numpy as np import matplotlib.pyplot as plt import sys sys.path.append(r"C:\Users\dell\Desktop\code\knn") import get_data def EuclideanDistances(x): """ Parameters ---------- x : ndarray matrix of instances. norm : float, optional p-normal for distances. The default is 2. Returns ------- distances : ndarray matrix of distances between instances. """ n, p = x.shape xy = x @ x.T xsq = np.sum(np.square(x), axis=1).reshape(n,1) distances = np.sqrt(xsq + xsq.T - 2*xy + np.eye(n)*np.exp(10)) return distances def Knn(x, y, k=5): """ Parameters ---------- x : ndarray matrix of instances. y : array labels of instances. k : int, optional the number of neighbours used to assign instances' label. The default is 10. Returns ------- pre : array predict labels. """ n, p = x.shape pre = np.zeros((n,1)) distances = EuclideanDistances(x) kth_value = np.sort(distances,axis=1)[:,k] for i in range(n): position = np.where(distances[i,:]<=kth_value[i])[0] labels = y[position].astype("int32") pre[i] = np.argmax(np.bincount(labels)) return pre def Score(y, pre): """ Parameters ---------- y : array real labels. pre : array predict labels. Returns ------- score : float model score. """ n = y.shape[0] pre = pre.reshape(n,) score = np.sum(y==pre)/n return score n = 10000 pos = np.array([0.1, 0.2, 0.3, 0.4]) data = get_data.FourCluster(n, pos) x = data[:,:2] y = data[:,-1] pre = Knn(x, y, k=5) score = Score(y, pre) plt.figure() plt.scatter(data[:,0], data[:,1], c=y) plt.show() plt.figure() plt.scatter(data[:,0], data[:,1], c=pre) plt.show()
c3b2939dd88a1e38aad72ef09982eda2d1390511
LucianoUACH/IP2021-2
/PYTHON/ClasePractica11/funcion_angulo_triangulo.py
488
3.9375
4
import math def calcular_angulo_triangulo(a,b): if a <= 0 or b <= 0: print("Error, los valores deben ser positivos") return 0 else: c = math.sqrt(a**2+b**2) angulo = math.asin(a/c) return angulo if __name__ == "__main__": print("Ingrese el valor de a: ") a = float(input()) print("Ingrese el valor de b: ") b = float(input()) angulo = calcular_angulo_triangulo(a,b) print("El angulo buscado es: " + str(angulo))
5ac52919724b8b658c1a2586b4a6b4a7e371af0d
LucianoUACH/IP2021-2
/PYTHON/X_1/x_1.py
103
3.875
4
print("Ingrese un número") x = int(input()) x_1 = 1 / x print("El resultado es: ", end="") print(x_1)
35b5bcedc003939f44bef58326dd49e725717da4
LucianoUACH/IP2021-2
/PYTHON/Funcion1/funcion1.py
219
4.25
4
print("Ingrese el valor de X:") x = float(input()) #f = ((x+1)*(x+1)) + ((2*x)*(2*x)) f = (x+1)**2 + (2*x)**2 # el operador ** la potencia print("El resultado es: " + str(f)) # str() tranforma un número a una palabra
ac10acfb84da478b5b3cc4b192510ade116ac675
LucianoUACH/IP2021-2
/PYTHON/Clase9/clase_9.py
1,433
4.03125
4
#Ejercicio 1 def mayor(a, b): if a > b: print(str(a) + " es mayor!!!") return a elif a < b: print(str(b) + " es mayor!!!") return b else: print(str(a) + " y " + str(b) + " Son iguales") return a #Ejercicio 2 def menor(a, b): if a < b: print(str(a) + " es menor!!!") return a elif a > b: print(str(b) + " es menor!!!") return b else: print(str(a) + " y " + str(b) + " Son iguales") return a #ejercicio 3 def potencia(a, b): p = 1 es_neg = False # booleano:{False, True|} if b < 0: b = -b es_neg = True #range(b) = [0,1,...,b-1] for i in range(b): p *= a if es_neg: p = float(1/p) return p if __name__ == "__main__": #Con una variable se almacena el retorno de la funcion valor_mayor = mayor(4,4) print("EL valor mayor es: " + str(valor_mayor)) #Se muestra el valor, pero no se almacena print("El mayor valor es: " + str(mayor(3,5))) #Con una variable se almacena el retorno de la funcion valor_menor = menor(8,4) print("EL valor menor es: " + str(valor_menor)) #Se muestra el valor, pero no se almacena print("El menor valor es: " + str(menor(3,5))) #Potencia #valor_potencia = potencia(2,9) valor_potencia = potencia(2,-2) print("El valor de la potencia es: " + str(valor_potencia))
af2dcfa2dc824abad123b6c829c134e6a3d515b9
abulka/Pythonista
/Examples/Plotting/Motion Plot.py
957
3.71875
4
'''This script records your device's orientation (accelerometer data) for 5 seconds, and then renders a simple plot of the gravity vector, using matplotlib.''' import motion import matplotlib.pyplot as plt from time import sleep import console def main(): console.alert('Motion Plot', 'When you tap Continue, accelerometer (motion) data will be recorded for 5 seconds.', 'Continue') motion.start_updates() sleep(0.2) print 'Capturing motion data...' num_samples = 100 data = [] for i in xrange(num_samples): sleep(0.05) g = motion.get_gravity() data.append(g) motion.stop_updates() print 'Capture finished, plotting...' x_values = [x*0.05 for x in xrange(num_samples)] for i, color, label in zip(range(3), 'rgb', 'XYZ'): plt.plot(x_values, [g[i] for g in data], color, label=label, lw=2) plt.grid(True) plt.xlabel('t') plt.ylabel('G') plt.gca().set_ylim([-1.0, 1.0]) plt.legend() plt.show() if __name__ == '__main__': main()
68645766659dbcf46d206fdde71462ede7adbaed
chengxxi/SWEA
/D4/1486.py
1,542
3.53125
4
# 1486. 장훈이의 높은 선반 def dfs(s, h): # staff / height of tower if h >= shelf: towers.append(h) if s == staff: # len(heights) if h >= shelf: towers.append(h) return dfs(s+1, h + heights[s]) dfs(s+1, h) for test_case in range(1, int(input())+1): staff, shelf = map(int, input().split()) # number of staffs & height of shelf heights = list(map(int, input().split())) # each staff's height towers = [] dfs(0, 0) tower = min(set(towers)) - shelf print('#{} {}'.format(test_case, tower)) ''' 장훈이는 서점을 운영하고 있다. 서점에는 높이가 B인 선반이 하나 있는데 장훈이는 키가 매우 크기 때문에, 선반 위의 물건을 자유롭게 사용할 수 있다. 어느 날 장훈이는 자리를 비웠고, 이 서점에 있는 N명의 점원들이 장훈이가 선반 위에 올려놓은 물건을 사용해야 하는 일이 생겼다. 각 점원의 키는 Hi로 나타나는데, 점원들은 탑을 쌓아서 선반 위의 물건을 사용하기로 하였다. 점원들이 쌓는 탑은 점원 1명 이상으로 이루어져 있다. 탑의 높이는 점원이 1명일 경우 그 점원의 키와 같고, 2명 이상일 경우 탑을 만든 모든 점원의 키의 합과 같다. 탑의 높이가 B 이상인 경우 선반 위의 물건을 사용할 수 있는데 탑의 높이가 높을수록 더 위험하므로 높이가 B 이상인 탑 중에서 높이가 가장 낮은 탑을 알아내려고 한다. '''
e0708591fa989e92ab07f8f9370b206551f49f1a
ViktorKarpilov/Study_reposytory_with_structure
/Small-stydy-things_and-tasks-from-amis/seven_task.py
372
3.78125
4
def translation(): input_minutes = int(input("Enter pleas minutes: ")) hours = input_minutes//60 result_hours = hours - (hours//24)*24 result_minutes = input_minutes - hours*60 result = str(result_hours) +"Hours and "+str(result_minutes) +"Minutes" print(result) try: translation() except: print("Something wrong") translation()
128f9d2c0776b35758e20d750e577d8ac7227ef3
eunchanity/davids_repo
/scripts/list_function_solution.py
379
4.09375
4
def find_first_names(students_input): """ input: list of a class roster return: sorted list of first names in roster """ first_name = [] for name in students_input: first_name.append(name.split()[0].capitalize()) return sorted(first_name) print( find_first_names([ 'nicholas Jones', 'Ashley Rowland', 'Stephanie Jackson', 'Donald Hicks', 'evan Johnson' ]))
c5927a700a348468464f200631e9e2dbdf872322
dhurataK/python
/insertionSort.py
506
3.921875
4
import random, datetime def insertionSort(array): for i in range(1, len(array)): key = array[i] j = i-1 while j>=0 and array[j] > key: array[j+1] = array[j] j = j-1 array[j+1] = key return array arr = [] for i in range(0 , 100): rand_num = random.randint(0,10000) arr.append(rand_num) print arr time = datetime.datetime.now() print time print insertionSort(arr) time2 = datetime.datetime.now() print time2
b74ac298e5cba51c032cee6114decf658a67f494
dhurataK/python
/score_and_grades.py
804
4.1875
4
def getGrade(): print "Scores and Grades" for i in range(0,9): ip = input() if(ip < 60): print "You failed the exam. Your score is: "+str(ip)+" Good luck next time!" elif (ip >= 60 and ip <= 69): print "Score: "+str(ip)+"; Your grade is D" elif (ip >= 70 and ip <= 79): print "Score: "+str(ip)+"; Your grade is C" elif (ip >= 80 and ip <= 89): print "Score: "+str(ip)+"; Your grade is B" elif (ip >= 90 and ip <= 100): print "Score: "+str(ip)+"; Your grade is A" elif (ip > 100): print "Invalid score! "+str(ip) print "End of the program. Bye! " getGrade() # Looks great, but what happens if I supply a grade below 60 or over 100? Just something to think about.
739202147eac8f44a40e213cbd6bafdcc26dcea1
17leungkaim/programming-portfolio
/grading.py
426
4.1875
4
# program to figure out grades score = int(raw_input("Enter your test score")) if score >= 93: print "A" elif score >= 90: print "-A" elif score >= 87: print "B+" elif score >=83: print "B" elif score >=80: print "-B" elif score >=77: print "+C" elif score >=73: print "C" elif score >=70: print "-C" elif score >=67: print "+D" elif score >=63: print "D" elif score >=60: print "-D" elif score >=50: print "F"
495dffd2bb07f45cc5bb355a1a00d113c2cd6288
cadyherron/mitcourse
/ps1/ps1a.py
981
4.46875
4
# Problem #1, "Paying the Minimum" calculator balance = float(raw_input("Enter the outstanding balance on your credit card:")) interest_rate = float(raw_input("Enter the annual credit card interest rate as a decimal:")) min_payment_rate = float(raw_input("Enter the minimum monthly payment rate as a decimal:")) monthly_interest_rate = interest_rate / 12 number_of_months = 1 total_amount_paid = 0 while number_of_months <= 12: min_payment = round(min_payment_rate * balance, 2) total_amount_paid += min_payment interest_paid = round(interest_rate / 12 * balance, 2) principle_paid = min_payment - interest_paid balance -= principle_paid print "Month: ", number_of_months print "Minimum monthly payment: ", min_payment print "Principle paid: ", principle_paid print "Remaining balance: ", balance number_of_months += 1 print "RESULT" print "Total amount paid: ", total_amount_paid print "Remaining balance: ", balance
49f3df82601d5ec49d18f2e76971080100b6927a
cadyherron/mitcourse
/ps3/filter.py
732
3.9375
4
""" filter input: list input: function that returns a boolean if True keep element in list if False remove element returns: a new list with only the elements that meet a certain condition """ list = [5, 6, 7] def function(x): if x == 6: return True else: return False def filter_function(list, function): def go(list, accum): if not list: return accum else: # function returns a boolean # if you get True, append to your list if function(list[0]): return go(list[1:], accum + [list[0]]) else: return go(list[1:], accum) return go(list, []) print filter_function(list, function)
f3fb695d70656cd48495be8fc89af09dd3cee40a
learning-triad/hackerrank-challenges
/gary/python/2_if_else/if_else.py
838
4.40625
4
#!/bin/python3 # # https://www.hackerrank.com/challenges/py-if-else/problem # Given a positive integer n where 1 <= n <= 100 # If n is even and in the inclusive range of 6 to 20, print "Weird" # If n is even and greater than 20, print "Not Weird" def check_weirdness(n): """ if n is less than 1 or greater than 100, return "Not Applicable" if n is odd, return "Weird" if n is even and in the inclusive range of 6 to 20, return "Weird" if n is even and in the inclusive range of 2 to 5, return "Not Weird" if n is even and greater than 20, return "Not Weird" """ if n < 1 or n > 100: return "Not Applicable" return "Not Weird" if n % 2 == 0 and (2 <= n <= 5 or n > 20) else "Weird" if __name__ == '__main__': n = int(input().strip()) result = check_weirdness(n) print(result)
3f43cee2f9a74cf64526522defccd2f1af8d6d9e
korynewton/Algorithms
/eating_cookies/eating_cookies.py
1,337
4
4
#!/usr/bin/python import sys # The cache parameter is here for if you want to implement # a solution that is more efficient than the naive # recursive solution def eating_cookies(n, cache=None): if n < 0: return 0 elif n == 0: return 1 else: return eating_cookies(n-1) + eating_cookies(n-2) + eating_cookies(n-3) print(eating_cookies(1)) print(eating_cookies(3)) cookie_cache = {} def eating_cookies_cached(n, cookie_cache): if n in cookie_cache: return cookie_cache[n] if n < 0: return 0 elif n == 0: return 1 else: number_cookies = eating_cookies_cached( n-1, cookie_cache) + eating_cookies_cached(n-2, cookie_cache) + eating_cookies_cached(n-3, cookie_cache) cookie_cache[n] = number_cookies return number_cookies print(eating_cookies_cached(1, cookie_cache)) print(eating_cookies_cached(3, cookie_cache)) print(eating_cookies_cached(10, cookie_cache)) print(eating_cookies_cached(50, cookie_cache)) # if __name__ == "__main__": # if len(sys.argv) > 1: # num_cookies = int(sys.argv[1]) # print("There are {ways} ways for Cookie Monster to eat {n} cookies.".format( # ways=eating_cookies(num_cookies), n=num_cookies)) # else: # print('Usage: eating_cookies.py [num_cookies]')
b80f01747733f676db5bce5dd0a16c278f505e33
JohnAsare/TicTacToe
/tictactoe.py
4,380
4.1875
4
# John Asare # Jun 25 2020 14:07 """Tic Tac Toe Milestone Project game! """ import random # Prints 100 spaces to behave like a clear screen def clear_screen(): print('\n' * 100) # A function to print out the Tic Tac Toe board def display_board(board): # print('\n'*100) print(board[7] + '|' + board[8] + '|' + board[9]) print('-----') print(board[4] + '|' + board[5] + '|' + board[6]) print('-----') print(board[1] + '|' + board[2] + '|' + board[3]) # Ask users for what marker do they want. def player_input(): check = '' while check != 'X' and check != 'O': check = input('What maker do you want to be? (X or O): ').upper() if check == 'X': print(f'Okay, you are {check} and your opponent is O') return 'X', 'O' else: print(f'Okay, you are {check} and your opponent is X') return 'O', 'X' # Place the player's marker at the position they will choose def place_marker(board, marker, position): board[position] = marker display_board(board) # Check to see if there is a win def win_check(board, mark): won = [mark, mark, mark] return (board[1:4] == won or board[4:7] == won or board[7:10] == won or board[1:8:3] == won or board[2:9:3] == won or board[3:10:3] == won or board[1:10:4] == won or board[3:8:2] == won) # Randomly pick which player is going first def choose_first(): coin_toast = random.randint(0, 6) if coin_toast % 2 == 0: return 'Player 1' else: return 'Player 2' # Check if there is a space on the board def space_check(board, position): return board[position] == ' ' # Check if all board is full def full_board_check(board): for i in range(1, 10): if space_check(board, i) == ' ': return False return True # Ask the player for their move def player_choice(board): move = 0 while move not in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] or not space_check(board, move): move = int(input('What is your move?(1-9): ')) return move # Ask user if they want to play again def replay(): play_again = '' while play_again != 'Y' or play_again != 'N': play_again = input('Do you want to play again? (Y or N): ').upper() return play_again == 'Y' print('Welcome to Aj Tic Tac Toe') while True: # Set up the board the_board = [' '] * 10 # Assign the maker player1_maker, player2_maker = player_input() # Randomly pick who goes first goes_first = choose_first() print(f'{goes_first} aka {player1_maker} will go first') # Ask if they are ready to play # play_game = ' ' # while play_game != 'y' or play_game != 'n': play_game = input('Ready to play? (Y or N): ').lower() if play_game == 'y': game_on = True else: game_on = False # if they say Y, then let player start playing while game_on: if goes_first == 'Player 1': # Display the board display_board(the_board) # Ask for their move pos = player_choice(the_board) # Place their maker on the board place_marker(the_board, player1_maker, pos) # check if they won if win_check(the_board, player1_maker): display_board(the_board) print('You won!') game_on = False # Check if it is a tie elif full_board_check(the_board): display_board(the_board) print('Its a tie') game_on = False else: goes_first = 'Player 2' elif goes_first == 'Player 2': # Display the board display_board(the_board) # Ask for their move pos = player_choice(the_board) # Place their maker on the board place_marker(the_board, player2_maker, pos) # check if they won if win_check(the_board, player2_maker): display_board(the_board) print('You won!') game_on = False # Check if it is a tie elif full_board_check(the_board): display_board(the_board) print('Its a tie') game_on = False else: goes_first = 'Player 1' if not replay(): break
09a3ab3cde4354f311071092cc20d004e9a3f572
TahaKaawan/AOC
/dcf.py
1,297
3.671875
4
# import numpy as np #import pandas as pd #import matplotlib.pyplot as plt def growth_value(FCF_t0,g,r,n): r = r/100 g = g/100 value=0 t=0 for k in range(n): tk = ((FCF_t0*((1+g)**(k))))/((1+r)**(k)) t += tk value =t global terminal_FCF,g1,r1,n1 terminal_FCF = tk r1 = r n1 = n return t def perpetuity_value(tg, tr, g): g = g/100 #move this to EV function, maybe wrap it into a function of its own so that its clear whats happening (are we just dividing by a 100 or anaylsing a 100 companies) tg = tg/100 tr = tr/100 FCF_n = terminal_FCF terminal_value = (FCF_n * (1+g))/((tr-tg)) discounted_TV = terminal_value / (1+r1)**n1 return discounted_TV def enterprise_value(FCF_t0, g,r,n,tg,tr): # if we just call growth_value(FCF_t0,g,r,n) then we are calling the function itself rather than its output. return growth_value(FCF_t0,g,r,n) + perpetuity_value(tg, tr, g) def share_value(enterprise_value,cash,debt,sharecount): # enterprise_value1 = enterprise_value --> not neccessary in this case,quite confusing too. We are just reassigning variables. Usually you'd do it for copy like reasons return ((enterprise_value+cash-debt)/(sharecount))
9554fcb0cf04be3c94f11d58e329a3bfcf4f74b1
imaadfakier/cheap-flight-club
/flight_data.py
2,046
3.515625
4
# This class is responsible for structuring the flight data. class FlightData: """Responsible for structuring the flight data.""" # class attributes # ... def __init__(self): self.all_flight_data_per_destination_city = [] self.specific_flight_data_per_destination_city = [] def structure_file_data(self): for destination_airport, flight_info in self.all_flight_data_per_destination_city: try: city_from = flight_info[0]['cityFrom'] city_to = flight_info[0]['cityTo'] fly_from = flight_info[0]['flyFrom'] fly_to = flight_info[0]['flyTo'] flight_price = flight_info[0]['price'] flight_departure_date = flight_info[0]['route'][0]['local_departure'].split('T').pop(0) if len(flight_info[0]['route']) == 3: flight_arrival_date = flight_info[0]['route'][2]['local_arrival'].split('T').pop(0) stop_over_city = flight_info[0]['route'][1]['city_from'].split('T').pop(0) else: flight_arrival_date = flight_info[0]['route'][1]['local_arrival'].split('T').pop(0) stop_over_city = None self.specific_flight_data_per_destination_city.append( ( city_from, city_to, fly_from, fly_to, flight_price, flight_departure_date, flight_arrival_date, stop_over_city, ) ) except IndexError as e: print(e) # print('No cheap flight available for CPT -> {departure_airport}'.format( # departure_airport=departure_airport # ) # ) print(f'No cheap flight available for LON -> {destination_airport}') continue
838bfbfabfb5e341aa341bc9042d49107c5234ce
Madhav-Somanath/LeetCode-AugustChallenge
/PancakeSorting-August29.py
992
4
4
""" Given an array of integers A, We need to sort the array performing a series of pancake flips. In one pancake flip we do the following steps: Choose an integer k where 0 <= k < A.length. Reverse the sub-array A[0...k]. For example, if A = [3,2,1,4] and we performed a pancake flip choosing k = 2, we reverse the sub-array [3,2,1], so A = [1,2,3,4] after the pancake flip at k = 2. Return an array of the k-values of the pancake flips that should be performed in order to sort A. Any valid answer that sorts the array within 10 * A.length flips will be judged as correct. """ class Solution: def pancakeSort(self, A: List[int]) -> List[int]: n = len(A) res = [] for i in range(n): cur_max = max(A[0:n-i]) j = 0 while A[j] != cur_max: j += 1 A[:j+1] = reversed(A[:j+1]) res.append(j+1) A[:n-i] = reversed(A[:n-i]) res.append(n-i) return res
d74a203fb83246ada7d0777b94667dc6d243cbef
Madhav-Somanath/LeetCode-AugustChallenge
/AddandSearchWord-August5.py
1,245
3.9375
4
""" Design a data structure that supports the following two operations: void addWord(word) bool search(word) search(word) can search a literal word or a regular expression string containing only letters a-z or . A . means it can represent any one letter. """] from collections import defaultdict class WordDictionary: def __init__(self): Trie = lambda: defaultdict(Trie) self.root = Trie() def addWord(self, word: str) -> None: node = self.root for letter in word: node = node[letter] node['$'] = True def search(self, word: str) -> bool: def helper(word, i, node): if i == len(word): return '$' in node elif word[i] == '.': return any( helper(word, i+1, node[letter]) for letter in node if letter != '$' ) elif word[i] in node: return helper(word, i+1, node[word[i]]) else: return False return helper(word, 0, self.root) # Your WordDictionary object will be instantiated and called as such: # obj = WordDictionary() # obj.addWord(word) # param_2 = obj.search(word)
fc1816b5c55421855a87b4fab9fef655bf70fb1b
Madhav-Somanath/LeetCode-AugustChallenge
/IteratorforCombinations-August13.py
1,795
3.890625
4
""" Design an Iterator class, which has: A constructor that takes a string characters of sorted distinct lowercase English letters and a number combinationLength as arguments. A function next() that returns the next combination of length combinationLength in lexicographical order. A function hasNext() that returns True if and only if there exists a next combination. """ from itertools import combinations class CombinationIterator: def __init__(self, characters, combinationLength): self.it = combinations(characters, combinationLength) self.buffer = next(self.it, None) def next(self): res = ''.join(self.buffer) self.buffer = next(self.it, None) return res def hasNext(self): return self.buffer is not None # Your CombinationIterator object will be instantiated and called as such: # obj = CombinationIterator(characters, combinationLength) # param_1 = obj.next() # param_2 = obj.hasNext() ''' def __init__(self, characters, length): self.generator = self.gen(characters, length) self.buffer = next(self.generator) def gen(self, characters, length): if length == 0: yield "" elif len(characters) == length: yield characters elif len(characters) > length: for tail in self.gen(characters[1:], length - 1): yield characters[0] + tail for tail in self.gen(characters[1:], length): yield tail def next(self): res = self.buffer try: self.buffer = next(self.generator) except StopIteration: self.buffer = None return res def hasNext(self): return self.buffer is not None '''
704471e605b3ea2f00faf7f79477698681fc7eec
MaloMn/SudokuSolver
/f_solcan.py
468
3.703125
4
# -*- coding: utf-8 -*- """ Sole candidate technique. If there is only one possibility in a cell, because of the constraints of the other numbers, then it can only be this number. """ from copy import deepcopy def sole_candidate(s, poss): sudoku = deepcopy(s) for i in range(9): for j in range(9): a = poss[i][j] if type(a) is list: if len(a) == 1: sudoku[i][j] = a[0] return sudoku
ff93536c0021d334658ef14d60eb3bf30f328f84
chillinc/angel
/lib/devops/settings_helpers.py
1,374
3.65625
4
import sys def key_value_string_to_dict(data_string, key_value_separator='='): ''' Given a string like: key=value\nkey2=value2 Return a dict with data[key] = values. - Ignores all lines that start with # or are empty. - Returns None on any parse errors. - Strips leading and trailing white-space on a line ''' if not isinstance(data_string, str): print >>sys.stderr, "Warning: key_value_string_to_dict called with a non-string value of data_string: %s" % data_string return None try: data_lines = map(lambda x: x.lstrip(), data_string.strip().split('\n')) data_lines_wo_comments = filter(lambda x: not (len(x) == 0 or x[0] == '#'), data_lines) invalid_lines = filter(lambda x: x.find(key_value_separator) < 0 and len(x.strip()), data_lines_wo_comments) if len(invalid_lines): print >>sys.stderr, "Invalid lines found while parsing string:\n%s" % '\n'.join(invalid_lines) return None return dict([ [y.strip() for y in x.split(key_value_separator,1)] for x in filter(lambda x: x.find(key_value_separator) > 0, data_lines_wo_comments)]) except Exception as e: print >>sys.stderr, "Parse error in key_value_string_to_dict: %s" % e import traceback traceback.format_exc(sys.exc_info()[2]) return None
1bfa2d483b59b2cdadc6498bb3ec5d85bd9fa658
gaoyang836/python_text
/learning_test/循环.py
740
3.625
4
''' names = ['gaoyang', 'xinxin', 'guanglin'] for ceshi in names: print(ceshi)''' '''sum = 0 for x in [1,2,3,4,5,6,7,8,9,10]: sum = sum + x print(sum)''' '''sum = 0 for x in range(101): sum = sum + x print(sum)''' '''sum = 0 n = 99 while n>0: sum=sum+n n=n-2 print(sum)''' '''sum = 0 n = 1 while n<100: sum=sum+n n=n+2 print(sum)''' # l = ['Bart', 'Lisa', 'Adam'] # n = 0 # while n<3: # n=n+1 # print('hello,',l(n)) # name = ['Bart', 'Lisa', 'Adam'] # for x in name : # print('hello,',x) # n=1 # while n<= 100: # if n > 10 : # break # print(n) # n=n+1 # print('end') n = 0 while n<10: n=n+1 if n % 2 == 0: continue print(n)
3f9b52057465aa6657f677e2ebf65ea5e3e9ede9
gaoyang836/python_text
/test_tool/my_sort.py
311
3.90625
4
def mysort(inList,dir): newList=[] while len(inList)>0: if dir: minData = max(inList) else: minData =min(inList) newList.append(minData) inList.remove(minData) return newList alist=[0,8,5,1,2] print(mysort(alist)) print(mysort(alist),True)
38ab9b100cd65fa8f507932ce3824bcfde62099e
gaoyang836/python_text
/test_tool/Decorator_certification.py
1,664
3.859375
4
# -*-coding:utf-8 -*- # author:gaoyang time:2020-03-04 #用装饰器加认证功能(token) #token:令牌,是服务端生成的一串字符串,作为客户端进行请求的一个标识, # 当用户第一次登录后,服务器生成一个token并将token返回给客户端, # 以后客户端登录会判断token,有token不用登录,没有token需要登陆 #按理说此处应该连接数据库表,此处用字典代替 user_dict={ #用户名密码 'user1':'123', 'user2':'123' } token="" #定义一个装饰器 def auth(func): def inner(*args,**kwargs): global token #声明全局变量 if token: #有效token func() else: name=input("请输入用户名").strip() passwd= input("请输入密码").strip() if name in user_dict and user_dict[name]==passwd: token=name func(*args,**kwargs) else: print('用户名和密码错误') return inner def my_log(): print('this is my_log') def my_name(name): print('欢迎登录',name) def my_shopping(): print('商城购物') while True: choose_num=input("\n\n1、查看信息\n2、我的信息\n3、我的商城" "\n请输入操作选项") if choose_num=='q' or choose_num=='Q': break elif choose_num == '1': my_log() elif choose_num == '2': my_name('张三') elif choose_num == '3': my_shopping() else: print('输入不合法') #随机字符串 # import uuid # # print(uuid.uuid4()) # # for i in range(10): # a+=chr(random.radint(65,95))
3e9f5cb439f461d32d83823f63379b7b72a8c259
ahmadzaidan99/Codewars
/Write_Number_In_Expanded_Form.py
274
3.75
4
def expanded_form(num): result = [] divider = 10 while divider < num: temp = num%divider if temp != 0: result.insert(0, str(temp)) num -= temp divider *= 10 result.insert(0, str(num)) return ' + '.join(result)
835fc048225330f1334708fc2a0ede731d1be94b
demptdmf/python_lesson_3
/homework_3.py
7,393
4.09375
4
f = open('text.txt') text = f.read() print('1) Методами строк очистить текст от знаков препинания:') text = text.replace(',', '') text = text.replace('.', '') text = text.replace('?', '') text = text.replace('!', '') text = text.replace('«', '') text = text.replace('»', '') text = text.replace(':', '') text = text.replace(';', '') text = text.replace('—', '') print(text) print(type(text)) print() # ---- ВОПРОС ---- # 1. Хотел сделать в единой строке через or/and/& — но все условия не выполнялись. Сделал вручную, можно как-то сразу всё? ''' ОТВЕТ: symbols = [",", ".", ":", ";", "!", "?", "—", "»","«","(",")"] for symbol in symbols: text = text.replace(symbol,"") ''' print('2) Сформировать list со словами (split):') text_list = text.split() print(type(text_list)) print() print('3) Привести все слова к нижнему регистру (map);') new_list = list(map(lambda letters: letters.lower(), text_list)) print(new_list) print(type(new_list)) print() print('4) получить из list пункта 3 dict, ключами которого являются слова, а значениями их количество появлений в тексте;') dict_text = {} for word in new_list: # В ЦИКЛЕ БЕРЕТСЯ ПЕРВОЕ СЛОВО, ОБХОДИТСЯ ПО СПИСКУ, dict_text[word] = new_list.count(word) # СЧИТАЕТ КОЛВО ПОВТОРЕНИЙ, ЗАПИСЫВАЕТСЯ В СЛОВАРЬ ПОД КЛЮЧЕМ С СООТВЕТСВУЮЩИМ ИМЕНЕМ, # И ПЕРЕХОДИТ К СЛЕДУЩЕМУ ЭЛЕМЕНТУ print(dict_text) # Это сложная часть задания, но решаемая не сложно, просто в голове нужно определить порядок действий: # 1. Вы уже должны были получисть какойто список слов из текста допустим list_ # 2. Теперь можно например задать какой то пустой словарь: # dict_text = {} # 3. Потом пройтись циклом по списку слов: # for word in list_: # 4. И для каждого слова в списке, добавлять в пустой словарь, к соответсвующему ключу значение, которое получить можно с помощью метода списков "count". # Этот метод вызываем для какого то списка, и указываем слово, чье количество повторений нам интересно # сперва цикл возьмет первое слово в списке, запишет его ключом в словарь, а потом присоединит к нему значение кол-ва повторений, и так по следущему и следующему слову до конца списка # ->dict_text[word] = list_.count(word) # допустим, взгляните на решение выше # В ЦИКЛЕ БЕРЕТСЯ ПЕРВОЕ СЛОВО, # ОБХОДИТСЯ ПО СПИСКУ, # СЧИТАЕТ КОЛВО ПОВТОРЕНИЙ, # ЗАПИСЫВАЕТСЯ В СЛОВАРЬ ПОД КЛЮЧЕМ С СООТВЕТСВУЮЩИМ ИМЕНЕМ, # И ПЕРЕХОДИТ К СЛЕДУЩЕМУ ЭЛЕМЕНТУ # ТОП-ВАРИАНТ # from collections import defaultdict # word_count = defaultdict(int) # for word in text_list: # print(word, word_count[word]) # word_count[word] += 1 # # ---- ВОПРОС К ВАРИАНТУ 3 ---- # 2. Самый топ варинат, как мне показалось, но опять же — как читается, что из себя представляет и так далее print() print('5.1) Вывести 5 наиболее часто встречающихся слов (sort)') # чтобы отсортировать — нужно привести к списку # но тогда не получится выбрать парно топ 5 значений и ключей # следовательно нужно выбрать 5 топ ключей и как-то потом сопоставить со значениями # val_top = list(dict_text.values()) # val_top.sort() # val_top.reverse() # print(val_top[:5]) # # word_top = list(dict_text.keys()) # word_top.sort() # word_top.reverse() # print(word_top[:5]) dict_list = list(dict_text.items()) # Используем парные значения через items, присваивая список для каждой пары "ключ/значение" dict_list.sort(key=lambda i: i[1]) # сортируем по первому элементу списка (по цифре), с индексом 1. Здесь у списка индекс 0 = слово, индекс 1 = цифра dict_list.reverse() print(dict_list[:5]) print() # ---- ВОПРОС ---- # 3. Мы вроде лямдбу не проходили, покопался\посмотрел\нашел\дописал, есть ли решение на нашем уровне for-in-while-if?) # 4. А как вывести более красиво? чтобы построчно было "слово А встречается 5 раз" print('5.2) Вывести количество разных слов в тексте (set).') # Считаем количество одинаковых слов (попытка 1): # Считаем в словаре все значения с "1" в словаре (value = 1) count = 0 for value in dict_text.values(): if value == 1: count += 1 print(count, 'Одинаковые') simillar = count # Считаем количество одинаковых слов (попытка 2): count = 0 for i in dict_text: if i == i: # тут выводится вообще всего количество слов 398, а не повторений, а как сделать проверку? count += 1 print(count, 'Все слова') # в итоге случайно посчиталось так. allwords = count different_words = allwords - simillar print(different_words, 'Разные') # Попытка посчитать одинаковые слова (попытка 3) count = 0 for keys in dict_text.keys(): if keys == keys: # тут тоже вывелись все слова. count += 1 print(count) # ------ ВОПРОС ----- # 5. Как правильно посчитать общее количество слов в словаре? привести к листу и len(dict_list) ?)) # 6. Как правильно посчитать количество одинаковых/разных слов в словаре? # Затем вычесть из общего количества элементов повторящиеся элементы. # Или нужно сделать 2 множества, и из одного вычестть все значения с "1". # Значит для начала нужно привести текущий лист к множеству
d13d318c78f4f902ef6b1a1474a832c70db6b9f2
demptdmf/python_lesson_3
/range.py
2,788
4.21875
4
# Когда использовать RANGE # позволяет создать последовательность целых чисел numbers = range(10) print(numbers) print(type(numbers), '— это диапазон') print(list(range(1, 20, 2))) # Напечатать список от 1 до 20 с шагом "2" — 1+2, 3+2, 5+2 и так далее for number in range(1, 20, 2): # Просто напечатать эти же самые цифры, но без списка print(number, '-', type(number)) print() winners = ['Max', 'Leo', 'Kate'] for i in range(1, len(winners)): # Для элемента в диапазоне длины списка winners print(i, winners[i]) # выводить номер элемента (+1, иначе начало будет с 0, т.к. это список) и его значение print() print('Вывод простых чисел') for n in range(2, 10): # для числа от 2 до 9 for x in range(2, n): # для множителя (х) от 2 до числа N if n % x == 0: # если остаток деления N на X = 0 (если число N делится на Х без остатка) print(n, 'равно:', x, '*', n//x) # то печатать это число N с условием: оно берется из "множитель" * "число/множитель" break else: # цикл потерпел неудачу, не найдя множитель print(n, '— это простое число') print() print('Вывод через CONTINUE \n' 'Оператор continue продолжает выполнение со следующей итерации цикла') for num in range(2, 10): if num % 2 == 0: print(num, '— четное число') continue # идет сразу к след строчке кода, и потом повторяется if. print(num, '— нечетное число') print() for num in range(2, 10): if num % 2 == 0: print(num, '— четное число') else: print(num, '— нечетное число') # В первом случае мы идем подряд по коду, и условием является "после найденного четного числа к следующему числу пишем "нечетное". # Во втором примере мы перебираем цифры, и если число делится на 2 — пишем "четное", если нет — "нечетное"
7fb1cb548a817550635159efe45fb90df7441f18
Kederly84/pythonProject
/Unit 3.py
1,486
3.921875
4
# ИГРА "УГАДАЙ ЧИСЛО" # №1 Программа загадывает число import random number = random.randint(1, 100) # №2 и №3 ввод числа пользователя и реализация цикла проверки чисел user_answer = None counter = 0 levels = {1: 10, 2: 5, 3: 3} level = int(input('Выберите уровень сложности от 1 до 3')) max_count = levels[level] user_count = int(input('Введите кол-во пользователей: ')) users = [] is_winner = False winner_name = '' for i in range(user_count): user_name = input(f'Введите имя пользователя {i}') users.append(user_name) while not is_winner: counter += 1 if counter > max_count: print('Все игроки проиграли') break print(f'Попытка №: {counter}') for user in users: print(f'Ход пользователя {user}') user_answer = int(input('Введи загаданное число: ')) if user_answer == number: is_winner = True winner_name = user break elif user_answer > number: print('Вы загадали слишком большое число') else: print('Вы загадали слишком маленькое число') else: print('Поздравляем вы победили. Загаданное число: ', number)
e5730e25a2d2a5272616443ba26f8fa912278127
Kederly84/pythonProject
/Lesson 7.py
1,616
3.75
4
# cities = ['Las Vegas', 'Paris', 'Moscow', 'Paris', 'Moscow'] # print(cities) # print(type(cities)) # # cities = set(cities) # # print(cities) # print(type(cities)) # # cities ={'Las Vegas', 'Paris', 'Moscow'} # cities.add('Birma') # добавление элемента в множество # cities.add('Moscow') # повторяющийся элемент не добавиться # print(cities) # # cities.remove('Moscow') # удаление элемента # print(cities) # print(len(cities)) # длина множества # # print('Paris' in cities) # проверка наличия элемента в множестве True/False # # for city in cities: # перебор элементов множества. Тип получемого элемента всегда str # print(city) # print(type(city)) max_things = {'Телефон', 'Бритва', 'Рубашка', 'Шорты'} kate_things = {'Телефон', 'Шорты', 'Зонт', 'Помада'} # Объединение множеств. При объединении совпадающие элементы удаляются,остаются только уникальные. print(max_things | kate_things) # Определение повторяющихся элементов print(max_things & kate_things) # Определение уникальных элементов множества, относительно другого множества # Первым идет множество уникальные элементы которого ммы определяем print(max_things - kate_things)
d2cfcecd211e2b6ff7047c4d3239311c430d6f8f
kushal200/python
/Basic/Function/OddEvenFunction.py
206
4.09375
4
def oddeven(a): if a%2==0: print( a,"is Even Number") else: print(a,"is Odd Number") def main(): num=int(input("Enter any number:")) oddeven(num) main()
16356775ed7d047aa0146ced654ac2bf8a45d112
kushal200/python
/Basic/Function/MultiplicationFunctino.py
189
4
4
def multiplication_table(a): for i in range(1,11): print("%d * %d = %d" %(a,i,a*i)) def main(): num=int(input("Enter the number")) multiplication_table(num) main()
24de5abad8325fa762558ccd6ba5e733691c4f3e
kushal200/python
/Basic/ClassAndObject/areaOfCircle.py
398
3.703125
4
# class dog: # def __init__(self, name, age): # self.name=name # self.age=age # print(name,age) # buddy=dog("buddy", 9) # miles=dog("miles", 4) # print(buddy.name) # # print(buddy.name) # # print(buddy.age) class circle: def __init__(self, radious): self.radious=radious def area(self): self.radious=input("Enter the radius of circle:")
cb04fdd6c7777b683649f3bb1b889092280146b4
kushal200/python
/Basic/Function/examQues.py
2,876
3.609375
4
def check(m_u, income): if m_u == 'Y': if annual <= 450000: a = annual * 0.01 total = a tax = 1 elif 450000 < annual <= 550000: a = 450000 * 0.01 b = (annual - 450000) * 0.1 tax = (1 + 10) total = a + b elif 550000 < annual <= 650000: a = 450000 * 0.01 b = (550000 - 450000) * 0.1 c = (annual - 550000) * 0.2 tax = (1 + 10 + 20) total = a + b + c elif 650000 < annual <= 1250000: a = 450000 * 0.01 b = (550000 - 450000) * 0.1 c = (650000 - 550000) * 0.2 d = (annual - 650000) * 0.3 tax = (1 + 10 + 20 + 30) total = a + b + c + d elif 2000000 <= annual: a = 450000 * 0.01 b = (550000 - 450000) * 0.1 c = (650000 - 550000) * 0.2 d = (1250000 - 650000) * 0.3 e = (annual - 1250000) * 0.36 tax = (1 + 10 + 20 + 30 + 36) total = a + b + c + d + e elif m_u == 'N': if annual <= 400000: a = annual * 0.01 total = a tax = 1 elif 400000 < annual <= 500000: a = 400000 * 0.01 b = (annual - 400000) * 0.1 tax = (1 + 10) total = a + b elif 500000 < annual <= 600000: a = 400000 * 0.01 b = (500000 - 400000) * 0.1 c = (annual - 500000) * 0.2 tax = (1 + 10 + 20) total = a + b + c elif 600000 < annual <= 1300000: a = 400000 * 0.01 b = (500000 - 400000) * 0.1 c = (600000 - 500000) * 0.2 d = (annual - 600000) * 0.3 tax = (1 + 10 + 20 + 30) total = a + b + c + d elif 2000000 <= annual: a = 400000 * 0.01 b = (500000 - 400000) * 0.1 c = (600000 - 500000) * 0.2 d = (1300000 - 600000) * 0.3 e = (annual - 1300000) * 0.36 tax = (1 + 10 + 20 + 30 + 36) total = a + b + c + d + e return tax, total print("Inland Revenue Department") print("Welcome to Integrated Tax System") name = input("\nEnter your name: ") address = input("Address: ") status = input("Enter 'Y' for Married and 'N' for Unmarried: ").upper() pan = int(input("Enter your PAN No.: ")) income = int(input("Enter your per month income[Rs.]: ")) annual = income * 12 tax = check(status) total = check(income) print("Inland Revenue Department") print("Lazimpat, Kathmandu") print("Welcome to") print("Integrated Tax System(ITS)\n") print(f"Tax Payee: {name}\t\t\t\tAddress: {address}") print(f"PAN No. {pan}\t\tFY: 2020/21\t\t\tMarried Status = {status}") print(f"{name} (PAN {pan}) to pay tax to government is [Rs.]= {total}")
748885bd08afb97b4a16c100814f6a99d26923e4
kushal200/python
/Basic/ListOfpython/vowel.py
392
3.953125
4
userinput=input("Enter the Sentence:") print(userinput) vowel=0 for i in userinput: if(i=='a' or i=='e' or i=='i' or i=='o' or i=='u' or i=='A' or i=='E' or i=='I' or i=='O' or i=='U'): vowel+= 1 print(vowel) if vowel%i==0: print("The given number is a prime number.") else: print("The number is not a prime number.") print("%d * %d = %d"%(vowel,i,vowel*i))
acdbae328d4470d480c2369c62c05a4c12514331
kushal200/python
/Basic/ListOfpython/greatestNumber.py
268
4.03125
4
a=int(input("Enter the First Number:")) b=int(input("Enter the Second Number:")) c=int(input("Enter the Third Number:")) if a>b>c: print("%d is a Greatest Number" %a) elif b>a>c: print("%d is a Greatest Number" %b) else: print("%d is a Greatest Number" %c)
3469b3d2e746ed029a42d652fea839ede1def1fd
VivekKumar4387/tathastu_week_of_code
/day1/prog4.py
252
3.90625
4
CP = float(input("enter cost price of product:")) SP = float(input("enter selling price of product:")) profit = SP-CP newsp = 1.05*profit + CP print("profit from product=",profit) print("to increase profit 5% more new selling price should be =",newsp)
98b8612d26bf010ae68ea139a0811c3627846881
cegodwin/BIOL5153HW
/parseGFF_2.py
1,391
3.796875
4
#! /usr/bin/env python3 #import modules import csv import argparse #create and argument parse object parser = argparse.ArgumentParser(description = 'This script will take a .gff file, pull out the gene names from the list, and store them in a alphabatized list. Then it will take that list and use it to pull out the gene sequences from a fasta file and calculate the GC content.') #add positional arguments for the gff and fasta files to be used parser.add_argument('gff', help= 'The name of the .gff file you wish to use', type=str) parser.add_argument('fasta', help= "The name of the fasta file you wish to use", type=str) #parse the arguments args = parser.parse_args() #open fasta file fasta = open(args.fasta, 'r') #open and parse the gff file, and define the list with open(args.gff, 'r') as gff: genes = [] reader = csv.reader(gff, delimiter= '\t') for line in reader: if not line: continue else: #separate out the repeated or similar to genes if (line[2] != 'misc_feature' and line[2] != 'repeat_region'): #pull out gene name and add it to the list parse = line[8].split(' ') genes.append(parse[1] + " " + line[3] + " " + line[4]) #print the gene games in alphabetical order for gene in sorted(genes): print(gene) #close both files gff.close() fasta.close()
b1baeef01b90b0ecae1b840759d619a71a8e1a29
Hovhanes/Webs
/Basic/script.py
1,428
3.703125
4
#name = "hovlo" #age = 25.555 #print(f"hello,{name},qo tariqna {age}") #print('%d is ok' % (age)) #print ('%s is %d years old' % ('Joe', 42)) #str_lower = 'abcdefjhy' #str_uper = 'ABCDEFJS' #print(str_lower.upper()) #print(str_uper.lower()) #string = "geeks for geeks geeks geeks geeks" # Prints the string by replacing geeks by Geeks #print(string.replace("geeks", "Geeks")) # Prints the string by replacing only 3 occurrence of Geeks #print(string.replace("geeks", "GeeksforGeeks", 2)) # for integers #print(float(10),'for integers') # for floats #print(float(11.22),'for floats') # for string floats #print(float("-13.33"),'for string floats') # for string floats with whitespaces #print(float(" -24.45\n"),'for string floats with whitespaces') # string float error #print(float("abc"),'string float error') #class Parent(): # arg = 5 # def __init__(self): # print('decorator class') # def __call__(self, cls): # print('call parent call function') #class Child(Parent): # def __init__(self): # print('child class') # def new_method(self, value): # return value * 3 #x = Child() #print(x.arg) def tester(start): state = start def nerqin_funkcia(): #nonlocal state state += 1 return state return nerqin_funkcia() print(tester(5))
d5e440eed002560547bf69c31a88bd5584a2bb53
snlucas/Poke_Trader
/test_trade_calculator.py
3,380
3.5
4
from pokemon import Pokemon from player import Player from trade_calculator import TradeCalculator import unittest class TestTradeCalculator(unittest.TestCase): def test_player_total_base_experience_passing_wrong_type(self): """Teste passando argumento diferente de Player >>> _total_base_experience(Player(...)) sum(Player(Pokemon.base_experience, ...)) >>> _total_base_experience(wrong_type) Error """ p1 = Player([Pokemon("Pichu", 42), Pokemon("Pikachu", 145)]) p2 = Player([Pokemon("Dito", 30), Pokemon("Charizard", 260)]) tc = TradeCalculator(p1, p2) self.assertRaises(TypeError, lambda: tc._total_base_experience(42)) def test_is_trade_valid_returns_True(self): """Teste para trade valido >>> tc = TradeCalculator(Player(...), Player(...)) >>> tc.is_trade_valid() True """ p1 = Player([Pokemon("Pichu", 42), Pokemon("Pikachu", 145)]) p2 = Player([Pokemon("Dito", 30), Pokemon("Charizard", 155)]) tc = TradeCalculator(p1, p2) self.assertTrue(tc.is_trade_valid(), "Funcao nao esta retornando o valor correto.") def test_is_trade_valid_returns_False(self): """Teste para trade invalido >>> tc = TradeCalculator(Player(...), Player(...)) >>> tc.is_trade_valid() False """ p1 = Player([Pokemon("Pichu", 42), Pokemon("Pikachu", 145)]) p2 = Player([Pokemon("Dito", 30), Pokemon("Charizard", 260)]) tc = TradeCalculator(p1, p2) self.assertRaises(TypeError, lambda: tc.is_trade_valid(42)) def test_is_base_experience_approximated_passing_wrong_type(self): """Teste passando argumentos diferentes de inteiro >>> _is_base_experience_approximated(42, 42) bool >>> _is_base_experience_approximated([...]) Error """ p1 = Player([Pokemon("Pichu", 42), Pokemon("Pikachu", 145)]) p2 = Player([Pokemon("Dito", 30), Pokemon("Charizard", 260)]) tc = TradeCalculator(p1, p2) self.assertRaises(TypeError, lambda: tc._is_base_experience_approximated({'n1': 42}, {'n2': 13})) def test_is_base_experience_approximated_passing_negative_value(self): """Teste passando um argumento negativo >>> _is_base_experience_approximated(42, 42) bool >>> _is_base_experience_approximated(-10, 4) Error """ p1 = Player([Pokemon("Pichu", 42), Pokemon("Pikachu", 145)]) p2 = Player([Pokemon("Dito", 30), Pokemon("Charizard", 260)]) tc = TradeCalculator(p1, p2) self.assertRaises(ValueError, lambda: tc._is_base_experience_approximated(-42, 10)) def test_is_base_experience_approximated_passing_zero_value(self): """Teste passando um argumento nulo >>> _is_base_experience_approximated(42, 42) bool >>> _is_base_experience_approximated(0, 4) Error """ p1 = Player([Pokemon("Pichu", 42), Pokemon("Pikachu", 145)]) p2 = Player([Pokemon("Dito", 30), Pokemon("Charizard", 260)]) tc = TradeCalculator(p1, p2) self.assertRaises(ValueError, lambda: tc._is_base_experience_approximated(0, 10)) if __name__ == "__main__": unittest.main()
3eb3915dfca95ace11f03d4eb2ae162c0428e4cf
ConnorWood/Prac03
/namePrint.py
94
3.859375
4
name = str(input("What is your name? ")) for i in range(0, len(name), 2): print(name[i])
4f5d0feece8584349ad40d9da35afc37ec8cadce
st084331/InaccurateInput
/main.py
1,683
3.765625
4
def Z_func_with_discrepancy(str): I = 0 r = 0 j = 0 Z = [0] * (len(str)) Z[0] = len(str) for i in range(1, len(str)): j = i discrepancy = 0 if i <= r: Z[i] = min(r - i + 1, Z[i - I]) while j + Z[i] < len(str) and (str[Z[i]] == str[j + Z[i]] or (i > str.index("#") and discrepancy == 0)) and str[j + Z[i]] != "#": if (str[Z[i]] != str[j + Z[i]]): discrepancy = 1 if (str[Z[i] + 1] == str[j + Z[i]]): j -= 1 elif(j + Z[i] + 1 < len(str)): if (str[Z[i]] == str[j + Z[i] + 1]): j += 1 Z[i] += 1 if (discrepancy == 1 and Z[i] == 1): Z[i] = 0 if i + Z[i] - 1 > r: I = i r = i + Z[i] - 1 return Z substr = input() text = "BCG is one of the leading international management consulting companies. The main task of the company is to help answer the most pressing questions on business management and development: development of new strategies, increase in operational efficiency, purchase and sale of other companies, mastering new technologies and concepts, and many others. Our company is focused on the highest welfare of its employees. We have the highest salaries among our competitors. Up to 31% of employees are promoted annually. 80% of the students stayed with the company after completing the internship. Equal number of men and women in the state." str = substr + "#" + text Z = Z_func_with_discrepancy(str) for i in range(len(substr)+1, len(str)): if(Z[i] == len(substr)): print("Index of substring is", i)
7e02ef06abb2d2ab0566c999decf610d54c232ee
florenciano/estudos-Python
/_first.py
599
3.921875
4
# -*- coding: utf-8 -*- # comentário de várias linhas """ Lorem ipsum dolor sit amet, consectetur adipisicing elit. Perferendis, labore, autem nihil ratione ipsum itaque sapiente, et eveniet error obcaecati a provident veniam nam consequuntur quod enim natus. Tempore aliquid maxime laboriosam sunt. Vero repellat animi alias mollitia sed eligendi eveniet sint eaque quo accusantium. """ print("primeira linha") #teste #print("segunda linha") print(3+4) print(9*9) #indentacao if True: print(8*2) print(3.1/2.56) #variáveis r = 23 r = "A rua do Rodrigo" print( r ) b = 12 print( b ) type (r) type (b)
612e27abc6ddf0c70b01aecc4b98b05f9d146857
florenciano/estudos-Python
/livro-introducao-a-programacao-em-python/cap9/arquivo_exercicio1.py
393
3.5
4
# -*- coding: utf-8 -*- # abrindo os arquivos pares.txt e impares.txt pares = open("pares.txt", "r") impares = open("impares.txt", "r") lista = [] # lendo os arquivos pares.txt e impares.txt for x in pares.readlines(): lista.append(int(x)) pares.close() for x in impares.readlines(): lista.append(int(x)) impares.close() # imprimindo o conteúdo deles print(lista.sort(reverse=True))
c6f81be710ff83f95f7b3ed87711cdcc40251903
florenciano/estudos-Python
/livro-introducao-a-programacao-em-python/cap10/classe-objeto-all.py
2,004
4.125
4
# -*- coding: utf-8 -*- #abrindo conta no banco Tatú class Cliente(object): def __init__(self, nome, telefone): self.nome = nome self.telefone = telefone #movimentando a conta """ Uma conta para representar uma conta do banco com seus clientes e seu saldo """ class Conta(object): def __init__(self, clientes, numero, saldo = 0): super(Conta, self).__init__() self.clientes = clientes self.numero = numero self.saldo = saldo self.operacoes =[] self.deposito(saldo) def resumo(self): print("CC Número: %s Saldo: %10.2f" % (self.numero, self.saldo)) def saque(self, valor): if self.saldo >= valor: self.saldo -= valor self.operacoes.append(["SAQUE", valor]) def deposito(self, valor): self.saldo += valor self.operacoes.append(["DEPOSITO", valor]) def extrato(self): print("Extrato CC Nº %s\n" % self.numero) for x in self.operacoes: print("%10s %10.2f" % (x[0], x[1])) print("\n Saldo: %10.2f\n" % self.saldo) #cadastrando os primeiros clientes joao = Cliente("João da Silva", "777-1234") maria = Cliente("Maria da Silva", "555-1234") #criando a conta do joao (nome, nº conta, valor inicial) conta_corrente_joao = Conta(joao, 8759, 0) #movimentando a conta do joao conta_corrente_joao.resumo() conta_corrente_joao.deposito(1000) conta_corrente_joao.resumo() conta_corrente_joao.saque(50) conta_corrente_joao.resumo() conta_corrente_joao.deposito(190) conta_corrente_joao.resumo() conta_corrente_joao.saque(360) conta_corrente_joao.resumo() conta_corrente_joao.saque(97.15) conta_corrente_joao.resumo() conta_corrente_joao.saque(250) conta_corrente_joao.resumo() conta_corrente_joao.extrato() #classe para armazenar todas as contas do banco Tatu class Banco(object): def __init__(self, nome): self.nome = nome self.clientes = [] self.contas = [] def abre_contas(self, conta): self.contas.append(conta) def lista_contas(self): for c in self.contas: print(c) tatu = Banco("Tatú") tatu.abre_contas([conta_corrente_joao]) tatu.lista_contas()