blob_id
stringlengths
40
40
repo_name
stringlengths
5
119
path
stringlengths
2
424
length_bytes
int64
36
888k
score
float64
3.5
5.22
int_score
int64
4
5
text
stringlengths
27
888k
d9b1d267f1901f7b976d076692328db0ec0eeb51
rootid23/fft-py
/ckbk/valid-anagram.py
1,350
4.28125
4
#!/usr/bin/env python #Given two strings s and t, write a function to determine if t is an anagram of s. #For example, #s = "anagram", t = "nagaram", return true. #s = "rat", t = "car", return false. #Note: #You may assume the string contains only lowercase alphabets. #Follow up: #What if the inputs contain unicode characters? How would you adapt your solution to such case? # W/ clean dict def isAnagram1(self, s, t): dic1, dic2 = {}, {} for item in s: dic1[item] = dic1.get(item, 0) + 1 for item in t: dic2[item] = dic2.get(item, 0) + 1 return dic1 == dic2 #W/ Array def isAnagram2(self, s, t): dic1, dic2 = [0] * 26, [0] * 26 for item in s: dic1[ord(item) - ord('a')] += 1 for item in t: dic2[ord(item) - ord('a')] += 1 return dic1 == dic2 #W/ sorting def isAnagram3(self, s, t): return sorted(s) == sorted(t) # W/ dict class Solution(object): def isAnagram(self, s, t): if (len(s) == len(t)): tmap = {} for i in range(len(s)): if (s[i] in tmap): tmap[s[i]] += 1 else: tmap[s[i]] = 1 if (t[i] in tmap): tmap[t[i]] -= 1 else: tmap[t[i]] = -1 for _, v in tmap.iteritems(): if (v != 0): return False return True return False # vim: ai ts=2 sts=2 et sw=2 tw=100 fdm=indent fdl=1
30bb0104ac96f16325936530c70c62f1b77c316c
CUGshadow/Solution_to_Daniel_Liang_python_exercises
/chapter11/11.5.py
1,438
4.21875
4
'''Program to add two 2D matrix''' def printMatrix(m): for row in range(len(m)): for column in range(len(m[row])): print(m[row][column], end = " ") print() def addMatrices(m1, m2): if(len(m1) == len(m2)): m3 = [] for i in range(len(m1)): m3.append([]) for j in range(len(m1)): m3[i].append(m1[i][j] + m2[i][j]) printMatrix(m3) else: print("Matrices of different length cannot be added") def main(): matrix1 = [] # Create an empty list matrix2 = [] numberOfRows = 3 #eval(input("Enter the number of rows: ")) numberOfColumns = 3 #eval(input("Enter the number of columns: ")) numbers = input("Enter the matrix1: ") value = numbers.split(" ") count = 0 for row in range(numberOfRows): matrix1.append([]) # Add an empty new row for column in range(numberOfColumns): matrix1[row].append(int(value[count])) count += 1 numbers2 = input("Enter the matrix2: ") value2 = numbers2.split(" ") count = 0 for row in range(numberOfRows): matrix2.append([]) # Add an empty new row for column in range(numberOfColumns): matrix2[row].append(int(value2[count])) count += 1 print("The sum of matrix 1 and 2 is:") addMatrices(matrix1,matrix2) main()
6c235e49decaeb1ab99d0ee9ecb841dca5818c00
Rabbi50/PythonPracticeFromBook
/add.py
141
3.875
4
number1=10 number2=20 addResult=number1+number2 subResult=number2-number1 print("Add Result is:",addResult) print("Add Result is:",subResult)
d5dd5022b211a1d4569067353574e39561e6e041
eldadpuzach/MyPythonProjects
/100days/01.py
323
3.75
4
# find all numbers divisible by 7 but NOT a multiple of 5 between 2000 and 3200 # solution should be comma separated on a single line empty_list = [] # iterate through the range of numbers for i in range(1, 100): if (i%7 == 0) and (i%5!=0): empty_list.append(str(i)) print(','.join(empty_list))
da22fbc7e688262770e0d7b70c61e19e2ca5753f
ICRA-2021/ProbRobScene
/src/probRobScene/core/lazy_eval.py
5,621
3.578125
4
"""Support for lazy evaluation of expressions and specifiers.""" import abc import itertools from inspect import signature from typing import Mapping, Any, Sequence, Callable from multimethod import multimethod class LazilyEvaluable(abc.ABC): """Values which may require evaluation in the context of an object being constructed. If a LazilyEvaluable specifies any properties it depends on, then it cannot be evaluated to a normal value except during the construction of an object which already has values for those properties. """ @abc.abstractmethod def required_properties(self) -> set: pass class DelayedArgument(LazilyEvaluable): """Specifier arguments requiring other properties to be evaluated first. The value of a DelayedArgument is given by a function mapping the context (object under construction) to a value. """ def required_properties(self) -> set: return self.rps def __init__(self, required_props, valuation_func: Callable): self.value_func : Callable = valuation_func self.rps = required_props def __getattr__(self, name): return DelayedArgument(self.rps, lambda context: getattr(evaluate_in(self, context), name)) def __call__(self, *args, **kwargs): dargs = [toDelayedArgument(arg) for arg in args] kwdargs = {name: toDelayedArgument(arg) for name, arg in kwargs.items()} subprops = (darg.required_properties() for darg in itertools.chain(dargs, kwdargs.values())) props = self.required_properties().union(*subprops) def value(context): subvalues = (evaluate_in(darg, context) for darg in dargs) kwsvs = {name: darg.evaluate_in(context) for name, darg in kwdargs.items()} return evaluate_in(self, context)(*subvalues, **kwsvs) return DelayedArgument(props, value) @multimethod def evaluate_inner(x: LazilyEvaluable, context: Mapping[Any, Any]) -> Any: cls = x.__class__ init_params = list(signature(cls.__init__).parameters.keys())[1:] current_vals = [x.__getattribute__(p) for p in init_params] context_vals = [value_in_context(cv, context) for cv in current_vals] return cls(*context_vals) @multimethod def evaluate_inner(x: DelayedArgument, context: Any) -> Any: return x.value_func(context) def evaluate_in(x: LazilyEvaluable, context: Any) -> Any: """Evaluate this value in the context of an object being constructed. The object must define all of the properties on which this value depends. """ assert all(hasattr(context, prop) for prop in x.required_properties()) value = evaluate_inner(x, context) if needs_lazy_evaluation(value): print(needs_lazy_evaluation(value)) print(evaluate_inner(x, context)) assert not needs_lazy_evaluation(value), f"value {value} should not require further evaluation" return value # Operators which can be applied to DelayedArguments allowedOperators = [ '__neg__', '__pos__', '__abs__', '__lt__', '__le__', '__eq__', '__ne__', '__gt__', '__ge__', '__add__', '__radd__', '__sub__', '__rsub__', '__mul__', '__rmul__', '__truediv__', '__rtruediv__', '__floordiv__', '__rfloordiv__', '__mod__', '__rmod__', '__divmod__', '__rdivmod__', '__pow__', '__rpow__', '__round__', '__len__', '__getitem__' ] def make_delayed_operator_handler(op): def handler(self, *args): dargs = [toDelayedArgument(arg) for arg in args] props = self.required_properties().union(*(darg._requiredProperties for darg in dargs)) def value(context): subvalues = (evaluate_in(darg, context) for darg in dargs) return getattr(self.evaluate_in(context), op)(*subvalues) return DelayedArgument(props, value) return handler for op in allowedOperators: setattr(DelayedArgument, op, make_delayed_operator_handler(op)) def makeDelayedFunctionCall(func, args, kwargs): """Utility function for creating a lazily-evaluated function call.""" dargs = [toDelayedArgument(arg) for arg in args] kwdargs = {name: toDelayedArgument(arg) for name, arg in kwargs.items()} props = set().union(*(darg.required_properties() for darg in itertools.chain(dargs, kwdargs.values()))) def value(context): subvalues = (evaluate_in(darg, context) for darg in dargs) kwsubvals = {name: darg.evaluate_in(context) for name, darg in kwdargs.items()} return func(*subvalues, **kwsubvals) return DelayedArgument(props, value) @multimethod def value_in_context(l: Sequence, context: Mapping) -> Sequence: return [value_in_context(x, context) for x in l] @multimethod def value_in_context(d: Mapping, context: Mapping) -> Mapping: return {k: value_in_context(v, context) for k, v in d.items()} @multimethod def value_in_context(value: Any, context: Mapping) -> Any: """Evaluate something in the context of an object being constructed.""" try: return value.evaluate_in(context) except AttributeError: return value def toDelayedArgument(thing): if isinstance(thing, DelayedArgument): return thing return DelayedArgument(set(), lambda context: thing) def requiredProperties(thing): if isinstance(thing, LazilyEvaluable): return thing.required_properties() return set() def needs_lazy_evaluation(thing) -> bool: del_arg = isinstance(thing, DelayedArgument) req_p = requiredProperties(thing) return del_arg or req_p
59b69de104c376f5b9fa427bf19ad4158c196de5
KIDJourney/algorithm
/leetcode/algorithm/implement Queue using stacks.py
457
3.8125
4
class Queue: # initialize your data structure here. def __init__(self): self.stack = [] # @param x, an integer # @return nothing def push(self, x): self.stack.append(x) # @return nothing def pop(self): self.stack.pop(0) # @return an integer def peek(self): return self.stack[0] # @return an boolean def empty(self): return len(self.stack) == 0
51327d8a8188924f9eac9a04bdeea47b00fdc2ea
tashareva/cs1024
/homework01/caesar.py
2,219
4.4375
4
import typing as tp def encrypt_caesar(plaintext: str, shift: int = 3) -> str: """ Encrypts plaintext using a Caesar cipher. >>> encrypt_caesar("PYTHON") 'SBWKRQ' >>> encrypt_caesar("python") 'sbwkrq' >>> encrypt_caesar("Python3.6") 'Sbwkrq3.6' >>> encrypt_caesar("") '' """ ciphertext = "" ciphertext = "" for i in plaintext: if i.isupper(): code = (ord(i) - ord("A") + shift) % 26 + ord("A") sym = chr(code) ciphertext += sym elif i.islower(): code = (ord(i) - ord("a") + shift) % 26 + ord("a") sym = chr(code) ciphertext += sym else: ciphertext += i return ciphertext return ciphertext def decrypt_caesar(ciphertext: str, shift: int = 3) -> str: """ Decrypts a ciphertext using a Caesar cipher. >>> decrypt_caesar("SBWKRQ") 'PYTHON' >>> decrypt_caesar("sbwkrq") 'python' >>> decrypt_caesar("Sbwkrq3.6") 'Python3.6' >>> decrypt_caesar("") '' """ plaintext = "" for i in ciphertext: if i.isupper(): if ord(i) - ord("A") < shift: code = 25 - ((shift - 1) - (ord(i) - ord("A"))) + ord("A") else: code = ord(i) - ord("A") - shift + ord("A") sym = chr(code) plaintext += sym elif i.islower(): if ord(i) - ord("a") < shift: code = 25 - ((shift - 1) - (ord(i) - ord("a"))) + ord("a") else: code = ord(i) - ord("a") - shift + ord("a") sym = chr(code) plaintext += sym else: plaintext += i return plaintext def caesar_breaker(ciphertext: str, dictionary: tp.Set[str]) -> int: """ >>> d = {"python", "java", "ruby"} >>> caesar_breaker("python", d) 0 >>> caesar_breaker("sbwkrq", d) 3 """ best_shift = 0 for i in dictionary: if ciphertext == i: return 0 for shift in range(25): word = decrypt_caesar(ciphertext, shift) if word == i: return shift best_shift += shift return best_shift
18aad0681177d51dd9ae047664c1588a1e8e26e5
maheshnayak616/Hackerrank
/Hackerrank/leetcode/adjacent_duplicates.py
478
3.703125
4
class Solution(object): def removeDuplicates(self, S): """ :type S: str :rtype: str """ stack = [] for x in S: if not stack: stack.append(x) else: y = stack.pop() if x != y: stack.append(y) stack.append(x) print "".join(stack) if __name__ == '__main__': s = Solution() s.removeDuplicates("abbaca")
2731efaeac25cc04c9ca0e847a35c9bc9a585800
withinfinitedegreesoffreedom/datastructures-algorithms
/sorting-searching/search_in_rotated_array.py
3,392
3.84375
4
import unittest def search_in_rotated_array(array,x): if not array: return None low = 0 high = len(array)-1 while low <= high: mid = (low+high)//2 if array[mid] == x: return mid elif array[mid+1] <= array[high]: if x >= array[mid+1] and x <= array[high]: low = mid+1 else: high = mid-1 elif array[low] <= array[mid-1]: if x >= array[low] and x <= array[mid-1]: high = mid-1 else: low = mid+1 return -1 def search_in_rotated_sorted_array_leetcode(array, x): if array is None: return -1 if len(array)==1: if array[0]==x: return 0 else: return -1 low=0 high=len(array)-1 while low<=high: mid=(low+high)//2 if array[mid]==x: return mid elif array[mid]<array[high]: if x>array[mid] and x<=array[high]: low=mid+1 else: high=mid-1 else: if x>=array[low] and x<array[mid]: high=mid-1 else: low=mid+1 return -1 def search_in_rotated_array_recursive(array, low, high, x): mid = (low+high)//2 if array[mid] == x: return mid if low > high: return -1 if array[low] <= array[mid-1]: if x >= array[low] and x <= array[mid-1]: return search_in_rotated_array_recursive(array, low, mid-1, x) else: return search_in_rotated_array_recursive(array, mid+1, high, x) elif array[mid+1] <= array[high]: if x >= array[mid+1] and x<=array[high]: return search_in_rotated_array_recursive(array, mid+1, high, x) else: return search_in_rotated_array_recursive(array, low, mid-1, x) elif array[mid] == array[low]: # left is just repeats if array[mid] != array[high]: return search_in_rotated_array_recursive(array, mid+1, high, x) else: result = search_in_rotated_array_recursive(array, low, mid-1, x) if result == -1: return search_in_rotated_array_recursive(array, mid+1, high, x) else: return result class Test(unittest.TestCase): def setUp(self): self.array = [11,12,13,14,15,1,4,5,7,10] self.array1 = [15,16,19,20,25,1,3,4,5,7,10,14] def test(self): self.assertEqual(search_in_rotated_array(self.array, 8),-1) self.assertEqual(search_in_rotated_array(self.array, 1),5) self.assertEqual(search_in_rotated_array(self.array, 10),9) self.assertEqual(search_in_rotated_array(self.array1, 5),8) self.assertEqual(search_in_rotated_array_recursive(self.array, 0, len(self.array)-1, 8),-1) self.assertEqual(search_in_rotated_array_recursive(self.array, 0, len(self.array)-1, 1),5) self.assertEqual(search_in_rotated_array_recursive(self.array, 0, len(self.array)-1, 10),9) self.assertEqual(search_in_rotated_array_recursive(self.array1, 0, len(self.array)-1, 5),8) self.assertEqual(search_in_rotated_array_recursive([3,4,5,6,1,2],0, 5, 2),5) # leetcode self.assertEqual(search_in_rotated_array([4,5,6,7,0,1,2], 0),4) #leetcode if __name__=="__main__": unittest.main()
e5879555fe67375c579b1027b083bce20d559bae
endiliey/pysql
/Python/mitx_600/02_simple-programs/pset2-1.py
854
3.71875
4
# -*- coding: utf-8 -*- """ Created on Fri Feb 3 01:38:35 2017 @author: User """ """ For testing purpose def minpayment(balance, annualInterestRate, monthlyPaymentRate): monthlyInterestRate = annualInterestRate / 12.0 for month in range(12): minimumMonthlyPayment = monthlyPaymentRate * balance monthlyUnpaidBalance = balance - minimumMonthlyPayment balance = monthlyUnpaidBalance + (monthlyInterestRate * monthlyUnpaidBalance) print('Remaining balance:', round(balance, 2)) minpayment(42, 0.2, 0.04) """ monthlyInterestRate = annualInterestRate / 12.0 for month in range(12): minimumMonthlyPayment = monthlyPaymentRate * balance monthlyUnpaidBalance = balance - minimumMonthlyPayment balance = monthlyUnpaidBalance + (monthlyInterestRate * monthlyUnpaidBalance) print('Remaining balance:', round(balance, 2))
c66696bd91339c3cc64cd37caa8f242910cd766c
JeffreyAsuncion/CSPT15_DataStructuresAndAlgorithms1
/Module04_SearchingAndRecursion/csSearchRotatedSortedArray.py
1,640
4.09375
4
""" Given an integer array nums sorted in ascending order, and an integer target. Suppose that nums is rotated at some pivot unknown to you beforehand (i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]). You should search for target in nums and if found return its index, otherwise return -1. Example 1: Input: nums = [6,7,0,1,2,3,4,5], target = 0 Output: 2 Example 2: Input: nums = [6,7,0,1,2,3,4,5], target = 3 Output: 5 Example 3: Input: nums = [1], target = 0 Output: -1 Note: 1 <= nums.length < 100 1 <= nums[i] <= 100 All values of nums are unique. [execution time limit] 4 seconds (py3) [input] array.integer nums [input] integer target [output] integer """ """Brute force""" # def csSearchRotatedSortedArray(nums, target): # return nums.index(target) def csSearchRotatedSortedArray(nums, target): if not nums: return -1 low, high = 0, len(nums)-1 while low <= high: mid = (low + high)//2 if target == nums[mid]: return mid if nums[low] <= nums[mid]: if nums[low] <= target <= nums[high]: high = mid - 1 else: low = mid + 1 else: if nums[mid] <= target <= nums[high]: low = mid + 1 else: high = mid - 1 return -1 #Example 1: nums = [6,7,0,1,2,3,4,5] target = 0 print(csSearchRotatedSortedArray(nums, target)) #Output: 2 #Example 2: nums = [6,7,0,1,2,3,4,5] target = 3 print(csSearchRotatedSortedArray(nums, target)) #Output: 5 #Example 3: nums = [1] target = 0 print(csSearchRotatedSortedArray(nums, target)) #Output: -1
e1094307432738f1d2f501010b1d559e3238de4a
AyelenDemaria/frro-soporte-2019-23
/practico_01/ejercicio-02.py
284
3.6875
4
# Implementar la función mayor, que reciba tres números y devuelva el mayor de ellos. def mayor(a, b, c): if a >= b and a >= c: return a elif b >= a and b >= c: return b return c assert mayor(10,9,3) == 10 assert mayor(2,9,3) == 9 assert mayor(2,5,8) == 8
7c5db1d532f33c61ee6e49bdb1fc53ca6f4c3d13
pmop/mfcp-GRASP
/cgrasp-solution.py
7,390
3.671875
4
from random import randint, sample from math import sqrt import math from copy import deepcopy import pygame """ TODO: Linear Search TODO: Adapting to the problem """ Ternary = [[0, 1], [0, -1], [1, 0], [1, 1], [1, -1], [-1, 0], [-1, 1], [-1, -1]] def cartesian_distance_point_to_point(A, B): x, y = A[0], A[1] sx, sy = B[0], B[1] return sqrt((sx - x) ** 2 + (sy - y) ** 2) # Input: vector min [x,y], vector max [maxX,maxY] # Output: sorted list with respect to X of random points from min to max def generate_random_points(min, max, p): points = [] minX, minY = min[0], min[1] maxX, maxY = max[0], max[1] for _ in range(p): x = randint(minX, maxX) y = randint(minY, maxY) points.append([x, y]) points.sort(key=lambda k: k[0] + k[1]) return points def solution_fully_covers(demand_points, facility_points, radius): covered = 0 for point in demand_points: for facility in facility_points: if cartesian_distance_point_to_point(point, facility) <= radius: covered = covered + 1 break return covered == len(demand_points) # Input: the set of tuples of demand points and one tuple facility # Output: the set of indexes of demand points covered by facility def points_facility_covers(demand_points, facility, radius): output = [] for i in range(len(demand_points)): point = demand_points[i] if cartesian_distance_point_to_point(point, facility) <= radius: output.append(i) return output # Input: the set of demand points # Output: Vectors lower bound (minX,minY) upper bound (maxX,maxY) def min_max_demands(demand_points): first = demand_points[0] minX, minY, maxX, maxY = first[0], first[1], 0, 0 for demand in demand_points: x, y = demand[0], demand[1] if x > maxX: maxX = x if x < minX: minX = x if y > maxY: maxY = y if y < minY: minY = y return [minX, maxX], [minY, maxY] # i represents the ith coordinate of x def line_search(x, f, h, i, n, l, u, demand_points): xstar = deepcopy(x) z = xstar[i] o = f([x], demand_points) d = 0 while vleq(u,xstar) and vgeq(l,xstar): xstar[i] = xstar[i] + d def randomly_select_element(rcl): return sample(rcl, 1) def min(*args): m = args[0] for arg in args: if arg < m: m = arg return m # vector b >= a def vgeq(a, b): x0, y0 = a[0], a[1] x1, y1 = b[0], b[1] if x1 >= x0 and y1 >= y0: return True else: return False # vector b <= a def vleq(a, b): x0, y0 = a[0], a[1] x1, y1 = b[0], b[1] if x1 <= x0 and y1 <= y0: return True else: return False # l is lower bound, u is upper bound def local_improvement(x, f, n, h, l, u, max_dir_to_try): improved = True # c = 3**n - 1 xstar = deepcopy(x) fstar = f(x) D = [] c = len(Ternary) # num_dir_to_try = min(c, max_dir_to_try) num_dir_to_try = c while improved: improved = False while len(D) <= num_dir_to_try and not improved: r = randint(1, c) while r in D: r = randint(1, c) D.append(r) d = Ternary[r] x[0], x[1] = xstar[0] + h * d[0], xstar[1] + h * d[1] if vgeq(l, x) and vleq(u, x): if f(x) < fstar: xstar = x fstar = f(x) D.clear() improved = True return xstar # n is always 2 because we're dealing with plane # x is a solution # f is the objective function # h is the search parameter # l and u are the max and min vectors # alpha is the selection parameter def construct_greedy_randomized(x, f, n, h, l, u, alpha, demand_points): S = [i for i in range(n)] z_set = dict(int) g_set = dict(int) while len(S) > 0: mn = math.inf mx = -math.inf for i in range(n): if i in S: z_set[i] = line_search(x, h, i, n, l, u, demand_points) g_set[i] = f(z_set[i], demand_points) if mn > g_set[i]: mn = g_set[i] if mx < g_set[i]: mx = g_set[i] RCL = [] for i in range(n): if i in S and g_set[i] <= (1 - alpha) * mn + alpha * mx: RCL.append(i) j = randomly_select_element(RCL) x[j] = z_set[j] S.remove(j) return x # returns an uniformly randomized integer vector def unif_rand(u, l): minX, minY = u[0], u[1] maxX, maxY = l[0], l[1] x = randint(minX, maxX) y = randint(minY, maxY) return [x, y] # Objective function def objective_function(x, demand_points): score = len(x) uncovered = deepcopy(demand_points) for t in x: index_covered = points_facility_covers(uncovered, t, 30) for i in index_covered: uncovered.remove(demand_points[i]) score = score - len(index_covered) return score def cgrasp(demand_points, radius, max_iters, max_num_iter_no_improv, num_times_to_run, max_dir_to_try, alpha=1): fstar = math.inf l, u = min_max_demands(demand_points) xstar = None for _ in range(num_times_to_run): x = unif_rand(l, u) h = 1 num_iter_no_improv = 0 for _ in range(max_iters): x = construct_greedy_randomized(x, objective_function,2, h, l, u, alpha) x = local_improvement(x, objective_function, 2, h, l, u, max_dir_to_try) # there are some adaptations to do here. we have to acknowledge for uncovered points and # also, the solution is a set if objective_function(x, demand_points) < fstar: xstar = x fstar = objective_function(x, demand_points) num_iter_no_improv = 0 else: num_iter_no_improv = num_iter_no_improv + 1 if num_iter_no_improv >= max_num_iter_no_improv: h = h / 2 num_iter_no_improv = 0 return xstar def solution(width, height, demand_points, radius): p = len(demand_points) solution_found = False sol = None while not solution_found: sol = generate_random_points(width, height, randint(p, p + 5)) solution_found = solution_fully_covers(demand_points, sol, radius) return sol def show_sol(dpoints, floc, fradius): pygame.init() screen = pygame.display.set_mode((640, 480)) surface = pygame.Surface(screen.get_size()) running = True while running: surface.fill((0, 0, 0)) screen.blit(surface, (0, 0)) event = pygame.event.wait() if event.type == pygame.QUIT: running = False for point in dpoints: pygame.draw.circle(screen, (255, 255, 255), (point[0], point[1]), 2, 0) for facility in floc: pygame.draw.circle(screen, (0, 0, 255), (facility[0], facility[1]), fradius, 1) pygame.time.wait(500) pygame.display.flip() pygame.quit() def simul(): radius = 30 demand_points = generate_random_points(620, 460, 50) print("Waiting for solution.") sol = grasp(demand_points, radius, 50) show_sol(demand_points, sol, radius) simul()
b00b6ab777c05e21ce674a232413dc762233b2fe
Samcfuchs/TicTacToe
/interface.py
3,959
3.875
4
class Game: """Deals with updating board and game arbitration""" # Note that player1 will always go first and will # always be X. Player2 will be O and go second. def __init__(self): self.result = False self.turn = 0 self.board = [[' ',' ',' '],[' ',' ',' '],[' ',' ',' ']] def playerpick(self): print 'PLAYERPICK EXECUTED' player1 = raw_input('Player 1: ').lower() player2 = raw_input('Player 2: ').lower() # Add ends to this list as they are created if player1 == 'human': from human import Human self.player1 = Human(1, self) elif player1 == 'roteai': raise RuntimeError elif player1 == 'learnai': #player1 = learnAI() pass else: from human import Human self.player1 = Human(1, self) if player2 == 'human': from human import Human self.player2 = Human(2, self) elif player2 == 'roteai': raise RuntimeError elif player2 == 'learnai': #player2 = learnAI() pass else: from human import Human player2 = Human(2, self) print def is_over(self): if (self.board[0][0] == 'X' and self.board[0][1] == 'X' and self.board[0][2] == 'X') or\ (self.board[0][0] == 'O' and self.board[0][1] == 'O' and self.board[0][2] == 'O'): return True #mid horiz elif (self.board[1][0] == 'X' and self.board[1][1] == 'X' and self.board[1][2] == 'X') or\ (self.board[1][0] == 'O' and self.board[1][1] == 'O' and self.board[1][2] == 'O'): return True #low horiz elif (self.board[2][0] == 'X' and self.board[2][1] == 'X' and self.board[2][2] == 'X') or\ (self.board[2][0] == 'O' and self.board[2][1] == 'O' and self.board[2][2] == 'O'): return True #left vert elif (self.board[0][0] == 'X' and self.board[1][0] == 'X' and self.board[2][0] == 'X') or\ (self.board[0][0] == 'O' and self.board[1][0] == 'O' and self.board[2][0] == 'O'): return True #mid vert elif (self.board[0][1] == 'X' and self.board[1][1] == 'X' and self.board[2][1] == 'X') or\ (self.board[0][1] == 'O' and self.board[1][1] == 'O' and self.board[2][1] == 'O'): return True #right vert elif (self.board[0][2] == 'X' and self.board[1][2] == 'X'and self.board[2][2] == 'X') or\ (self.board[0][2] == 'O' and self.board[1][2] == 'O' and self.board[2][2] == 'O'): return True #left-right diag elif (self.board[0][0] == 'X' and self.board[1][1] == 'X' and self.board[2][2] == 'X') or\ (self.board[0][0] == 'O' and self.board[1][1] == 'O' and self.board[2][2] == 'O'): return True #right-left diag elif (self.board[0][2] == 'X' and self.board[1][1] == 'X' and self.board[2][0] == 'X') or\ (self.board[0][2] == 'O' and self.board[1][1] == 'O' and self.board[2][0] == 'O'): return True else: return False def print_board(self): print ''' %s | %s | %s ----------- %s | %s | %s ----------- %s | %s | %s ''' % (self.board[0][0],self.board[0][1],self.board[0][2],\ self.board[1][0],self.board[1][1],self.board[1][2],\ self.board[2][0],self.board[2][1],self.board[2][2]) def play(self): # TODO turn = 0 # print # print self # print while self.is_over() == False: if turn % 2 == 0: one = self.player1 self.player1.turn() elif turn % 2 == 1: two = self.player2 self.player2.turn() turn += 1
970fba5372232d978ea63034431888c46b028c79
junlovecat/adofai-gg-bot
/identifier.py
184
3.75
4
#여기서 의미하는 value란 getvalue()를 의미 def returnthing(value,num): thing=[] for x in range(len(value)): thing.append(value[x][num]) return thing
0f6ad685ccc10d47449194a1f69910d6521d61f6
kastrul/school
/Keeleaine/hw1/assignment01_template.py
2,545
3.59375
4
import pynini as pn import sys # Helper function to return all outputs of the fiven fst in sorted order def sorted_outputs(fst): return sorted([p[1] for p in fst.paths()]) # Create an acceptor for digits 1..9 a_1_to_9 = pn.u(*"123456789").optimize() # Create an acceptor for digits 0..9 a_0_to_9 = (a_1_to_9 | pn.a("0")).optimize() # First, let's define the factorizer. # Factorizer converts numbers to their factorized form, using ^ characters # to denote powers of ten: # # 0 -> 0 # 1 -> 1 # 10 -> 1^ # 23 -> 2^ 3 # 203 -> 2^^ 3 # TODO: currently only works for 0..99 factorizer = (((a_1_to_9 + pn.t("", "^ ")) | "") + a_0_to_9).optimize() # You can debug the factorizer by generating random paths through it # print(list(pn.randgen(factorizer, 5).paths())) # Now, let's define number-to-string mappings map_1_to_9 = {"1": "one", "2": "two", "3": "three", "4": "four", "5": "five", "6": "six", "7": "seven", "8": "eight", "9": "nine"} t_1_to_9 = pn.string_map(map_1_to_9).optimize() # TODO: define the similar mappings for teens (10..19) and tens (20, 30, 40, etc) # map_10_to_19 # map_20_to_90 # Now, define a FST that uses the mapper FSTs to transform factorized form to # verbalized form: # 0 -> zero # 1^ -> ten # 1^ 1 -> eleven # 9^ 1 -> ninety one # 1^^ 9^ 1 -> ['one hundred ninety one', 'hundred ninety one'] # TODO: currently only works for single digits (and doesn't work for zero) factorized_to_words = t_1_to_9 numbers_to_words = factorizer * factorized_to_words # Test, for your convinience # If you have completed the above FSTs, the following asserts should not fail # Feel free to comment them out while developing the program assert (sorted_outputs("1" * numbers_to_words) == ["one"]) assert (sorted_outputs("0" * numbers_to_words) == ["zero"]) assert (sorted_outputs("10" * numbers_to_words) == ["ten"]) assert (sorted_outputs("11" * numbers_to_words) == ["eleven"]) assert (sorted_outputs("21" * numbers_to_words) == ["twenty one"]) assert (sorted_outputs("121" * numbers_to_words) == ["hundred twenty one", "one hundred twenty one"]) assert (sorted_outputs("12.23" * numbers_to_words) == ["twelwe point two three"]) # Now, the interactive program while True: try: number = raw_input("Please enter a number (Ctrl-D to exit): ") print("Result in factorized form") print((number * factorizer).stringify()) print("Result in words") print(sorted_outputs(number * numbers_to_words)) except EOFError: print("") break
f4cf94b088daf11177670223641613334347f322
varerysan/python_start_lessons
/some_ideas/water_v2.py
209
3.71875
4
# author: Valery Mosyagin temp = float(input("Введите температуру:")) if temp < 0: print("Лёд") else: if temp > 100: print("Пар") else: print("Вода")
492bf549dd5b12b93f05da40b2f9f52aa7459619
farshadasadpour/Rock_Paper_Scissors
/computer_choice.py
250
3.84375
4
from random import randint def computer_choice(content): ''' function that generates a random number based on the available options. returns random int ''' computer_chose = randint(0, len(content) - 1) return computer_chose
d9794cd620f0626831abcbd6d14aead2af426dcc
Grae-Drake/Python_Euler
/Problem_41.py
1,028
4.03125
4
# Problem 41: Pandigital Primes """ We shall say that an n-digit number is pandigital if it makes use of all the digits 1 to n exactly once. For example, 2143 is a 4-digit pandigital and is also prime. What is the largest n-digit pandigital prime that exists? """ # Note: answer must be 7 digits or less, as all 8 and 9 digit pandigitals # are divisible by 3. import time t1 = time.clock() f = open("1-7_pandigitals.txt") bigstring = f.read() f.close() biglist = bigstring.split() biglist = [int(x) for x in biglist] biglist = reversed(biglist) def isPrime(n): if n%2 == 0: return False if n%3 == 0: return False r = int(n**0.5) f = 5 while f <= r: if n%f == 0: return False if n%(f+2) == 0: return False f +=6 return True found = False answer = [] while found == False: for item in biglist: if isPrime(item) == True: answer.append(item) found = True print(answer)
3387ae1b1d0a34336e4ea23eb4760242a75c0806
sergioc6/python-course
/basics/ejercicio1.py
241
3.9375
4
#Ejercicio 1 a = float(input("Ingrese el valor de a: ")) b = float(input("Ingrese el valor de b: ")) c = float(input("Ingrese el valor de c: ")) result = (pow(a, 3) * (pow(b, 2) - (2 * a * c))) / (2*b) print(f"El resultado es: {result}")
2385623e406a594d6d23b531279104d2a6800bca
Dcz4hp5d/CP2015
/p01/q3_miles_to_kilometre.py
146
4.28125
4
miles = float(input("Enter your distance (in miles): ")) kilometre = miles * 1.60934 print (miles, "miles is", "{0:.2f}".format(kilometre), "km")
16a4285a5ffdf79ca81cae3185b7937adc521777
suhasbhairav/PythonProjects
/practise9.py
801
4.15625
4
import numpy as np # Array joining arr1 = np.array([1, 2, 3]) arr2 = np.array([4, 4, 6]) arr = np.concatenate((arr1, arr2)) print(arr) arr3 = np.array([1, 2, 3, 4]) arr4 = np.array([2, 3, 4]) arr = np.concatenate((arr3, arr4)) print(arr) # 2-D arrays along axis 1 arr1 = np.array([[1, 2], [3, 4]]) arr2 = np.array([[1, 3], [4, 5]]) arr = np.concatenate((arr1, arr2), axis=0) print(arr) # Stacking is same as concatenation, the only difference is that stacking is done along a new axis. - W3SCHOOLS arr1 = np.array([1, 2, 3]) arr2 = np.array([4, 5, 6]) arr = np.stack((arr1, arr2), axis=1) print(arr) # To stack along rows arr = np.hstack((arr1, arr2)) print(arr) # To stack along columns arr = np.vstack((arr1, arr2)) print(arr) # To stack along height arr = np.dstack((arr1, arr2)) print(arr)
976cd58e89e6aaf5019c3cbb64eab438f91ddff8
pitikdmitry/leetcode
/recursion/partition_to_k_equal_subsets.py
1,744
3.71875
4
''' Given an array of integers nums and a positive integer k, find whether it's possible to divide this array into k non-empty subsets whose sums are all equal. Example 1: Input: nums = [4, 3, 2, 3, 5, 2, 1], k = 4 Output: True Explanation: It's possible to divide it into 4 subsets (5), (1, 4), (2,3), (2,3) with equal sums. ''' from typing import List # recursive backtracking solution class Solution: def helper(self, nums: List[int], used: List[int], used_amount: int, target: int, cur_s: int, k: int) -> bool: if cur_s == target: # found answer if k == 1 and used_amount == len(nums): return True # found answer, but not all elements are used elif k == 1: return False # found not all subsets else: return self.helper(nums, used, used_amount, target, 0, k - 1) elif cur_s > target: return False i = 0 # try to take every unused number while i < len(nums): if used[i] is True: i += 1 continue used[i] = True res = self.helper(nums, used, used_amount + 1, target, cur_s + nums[i], k) used[i] = False if res is True: return True i += 1 return False def canPartitionKSubsets(self, nums: List[int], k: int) -> bool: if sum(nums) % k != 0: return False target = sum(nums) // k used = [False for _ in range(len(nums))] return self.helper(nums, used, 0, target, 0, k) solution = Solution() nums = [4, 3, 2, 3, 5, 2, 1] k = 4 print(solution.canPartitionKSubsets(nums, k))
71cd74fe819ae3d65c656f8148da2a0358c5efe9
ahmedazab1235/learningPython
/CheckingUsernames.py
288
4
4
current_users = ['ahmed', 'essam', 'azab', 'omer', 'eslam'] new_users = ['ahmed', 'essam','mohamed', 'cotineo'] for newuser in new_users: if newuser.lower() in current_users: print('that the person will need to enter a new username') else: print('that the username is available')
5fd9cfb4a62daa5ff1fc5daff90b8b40d3b703c8
gentle-potato/Python
/13_built-in-function/ftn_extra.py
2,252
3.890625
4
# 재귀함수 # def selfCall() : # print('ha', end='') # selfCall() # # selfCall() # Error def selfCall(num) : if num == 0 : return else : print('ha', end='') selfCall(num-1) selfCall(10) # 팩토리얼 계산 def fact(num) : if num == 1 : return 1 else : return num * fact(num-1) print(fact(5)) # 실습문제. 자연수를 입력받으면 해당하는 자연수까지 출력 # 49 입력하면 49 ~ 1로 출력 def count(num) : if num == 1 : print(num) return else : print(num, end = ' ') count(num-1) count(49) # 내부함수 : 함수 내에서 정의된 함수 def outFunc(x, y) : def inFunc(a, b) : return a + b return inFunc(x, y) print(outFunc(10, 20)) # print(inFunc(10, 20)) # Error! # lambda 함수(표현식) # 방법1. # (lambda 매개변수들 : 식)(인수들) # 객체명 = lambda 매개변수들 : 식 # 방법2. # 객체명(인수들) (lambda x, y : x + y)(10, 50) print((lambda x, y : x + y)(10, 50)) # 또는 hap2 = lambda x, y : x + y print(hap2(5, 10)) def hap(x=10, y=20) : return x + y print(hap()) print(hap(30, 100)) hap3 = lambda x=10, y=20 : x+y print(hap3()) print(hap3(9, 10)) # 람다함수 안에서 변수를 생성할 수는 없음 # print((lambda x : y=10, x+y)(10)) # Error y=10 print((lambda x : x+y)(10)) # 람다함수 list 사용 # 리스트의 값에 각각 10을 더하는 람다함수를 작성 # 10을 더하는 함수 def addTen(x) : return x + 10 myL = [1, 3, 4] print(list(map(addTen, [1, 3, 4]))) print(list(map(addTen, myL))) print(list(map(lambda x : x+10, [1, 3, 4]))) # 실습문제. 두 개의 리스트의 같은 요소의 값들을 더해서 하나의 리스트로 반환 # 1) def 함수 정의 # 2) lambda 표현식 정의 list1 = [1, 2, 3, 4] list2 = [10, 20, 30, 40] # 1) def addList(x, y) : addList = [] for i in range(len(x)) : z = x[i] + y[i] addList.append(z) return addList print(addList(list1, list2)) # comprehension을 사용하여 간단하게 작성하면, def hap(a, b): return [x + y for x, y in zip(a, b)] print(hap(list1, list2)) # 2) print(list(map((lambda x, y : x + y), list1, list2)))
0ccdb2f484bb214d97499b4b5ae1e64e8b42364a
AnsonTing/Programming-Challenges
/the_trip.py
2,523
3.953125
4
# A group of students are planning a trip. # The group agrees in advance to share expenses equally, but it is not practical to share every expense as it occurs. # Thus individuals in the group pay for particular things, such as meals, hotels, and plane tickets. # After the trip, each student's expenses are tallied and money is exchanged so that the net cost to each is the same, to within one cent. # The program outputs the minimum amount of money that must change hands in order to equalize (within one cent) all the students' costs. # Sample input contain information for several trips. # Each trip consists of a line containing a positive integer n denoting the number of students on the trip. # This is followed by n lines input, each containing the amount spent by a student in dollars and cents # A single line containing 0 follows the information for the last trip # Constraints: n < 1000, cost by one student < $10,000.00 # Sample Input # 3 # 10.00 # 20.00 # 30.00 # 4 # 15.00 # 15.01 # 3.00 # 3.01 # 0 # Sample Output # $10.00 # $11.99 from math import floor # define a function to get all the amount spent by each student and return a 2-dimenional array storing the information. def getInput(): l = [] no_of_students = None print "Enter Here:" while no_of_students != 0: costs = [] no_of_students = int(input()) for _ in range(no_of_students): costs.append(float(input())) if costs: l.append(costs) print '\n' return l # define a function to calculate the minimum amount of money that must change hands for a trip def MinMoneyToChangeHands(costs): s = round(sum(costs), 2) average = s / len(costs); average = floor(average * 100) / 100. lst = [average] * len(costs) index = 0 # Handle the extra cents that cannot be evenly distributed while round(sum(lst), 2) != s: lst[index] += 0.01 index += 1 if index == len(lst): index = 0 # calculate the sum of all differences between costs[i] and lst[i], where 0 <= i <= len(costs) - 1 # then divide it by two diff = 0 costs.sort(reverse=True) for i in range(len(costs)): diff += abs(costs[i] - lst[i]) diff /= 2. return round(diff, 2) #finally, define a function that calculates the output of several trips and output them def MinMoneyToChangeHands_SeveralTrips(): trips = getInput() for costs in trips: print '$' + str(MinMoneyToChangeHands(costs)) MinMoneyToChangeHands_SeveralTrips()
5b6c9ed53b3789006609898cb926456f7292ddc6
anirudhaps/Python_Programs
/basics/functions/func1.py
165
4.0625
4
#building functions def printlist(lst): for i in lst: print i list1 = [23,12,45,36,76,89,48] print 'the list is as follows:' printlist(list1)
d7543a52b31f9aeeabf50d61e1620633b6b55f7c
LiyaKyo/Python_hometasks
/task1_3.py
533
4.1875
4
# Реализовать склонение слова «процент» во фразе «N процентов». Вывести эту фразу на экран отдельной строкой для # каждого из чисел в интервале от 1 до 100: for N in range(1, 101): if (N % 10 == 1) and (N // 10 != 1): print(f"{N} процент") elif (N % 10 > 1) and (N % 10 < 5) and (N // 10 != 1): print(f"{N} процента") else: print(f"{N} процентов")
153723ce4fbd8f4f7a4e35a924988ba503367058
green-fox-academy/wenjing-liu
/week-02/day-01/class-as-field/blog.py
1,966
3.75
4
from blog_post import BlogPost class Blog: def __init__(self): self.blog_list = [] def add(self, blog_post): self.blog_list.append(blog_post) def delete(self, index): if self.blog_list[index]: self.blog_list.pop(index) def update(self, index, blog_post): if self.blog_list[index]: self.blog_list[index] = blog_post def __str__(self): result = '' for index in range(len(self.blog_list)): result += str(index + 1) + ' blog post: ' + self.blog_list[index].__str__() + '\n' return result post_1 = { 'author_name': 'John Doe', 'title': 'Lorem Ipsum', 'text': 'Lorem ipsum dolor sit amet.', 'publication_date': '2000.05.04.' } post_2 = { 'author_name': 'Tim Urban', 'title': 'Wait but why', 'text': 'A popular long-form, stick-figure-illustrated blog about almost everything.', 'publication_date': '2010.10.10.' } post_3 = { 'author_name': 'William Turton', 'title': 'One Engineer Is Trying to Get IBM to Reckon With Trump', 'text': 'Daniel Hanley, a cybersecurity engineer at IBM, doesn’t want to be the center of attention. When I asked to take his picture outside one of IBM’s New York City offices, he told me that he wasn’t really into the whole organizer profile thing.', 'publication_date': '2017.03.28.' } posts = [post_1, post_2, post_3] blog_posts = [] for post in posts: blog_posts.append(BlogPost(post['author_name'], post['title'], post['text'], post['publication_date'])) blog = Blog() blog.add(blog_posts[0]) blog.add(blog_posts[1]) print('After add:') print(blog) blog.update(1, blog_posts[2]) print('After update') print(blog) blog.delete(1) print('After detele') print(blog) """ # Blog - Reuse your `BlogPost` class - Create a `Blog` class which can - store a list of BlogPosts - add BlogPosts to the list - delete(int) one item at given index - update(int, BlogPost) one item at the given index and update it with another BlogPost """
be95f83a8889483170c5f012db42f87e240267ce
CoriAriasGibert/ta-te-ti
/tateti.py
3,261
4.1875
4
#----------Global Variables--------------- #------Game board--------- board = [ "_", "_", "_", "_", "_", "_", "_", "_", "_", ] # \\\\\If game stil going////// game_still_going = True #++++++ who won or NO_hay_mas_movimientos_posibles?+++++ winner = None #***** What turn its? ********* current_player = "x" def display_board(): print(board[0] + "|", board[1] + "|", board[2]) print(board[3] + "|", board[4] + "|", board[5]) print(board[6] + "|", board[7] + "|", board[8]) def play_game(): #start game with empty boar display_board() while game_still_going: handle_turn(current_player) check_if_game_over() flip_player() #------The game has ennded------- if winner == "x" or winner == "o": print(winner + " GanadorX de un cafecito! ☕️.") elif winner == None: print("Empate!") def handle_turn(player): position = input("Elige una posicion entre 1 y 9 por favor: ") valid=False while not valid: while position not in ["1","2","3","4","5","6","7","8","9"]: position=input("Posicion invalida, selecciona un numero del 1 al 9: ") position = int(position) - 1 if board[position] == "_": valid=True else: print("Ese lugar ya esta ocupado, por favor, mueve tu pieza hacia otro lado") board[position]=player display_board() def check_if_game_over(): check_for_winer() check_if_NO_hay_mas_movimientos_posibles() def check_for_winer(): #set up to globals Variables--------------- global winner #check rows row_winner = check_rows() #check columns columns_winner = check_columns() #check diagonals diagonals_winner = check_diagonals() if row_winner: winner = row_winner elif columns_winner: winner = columns_winner elif diagonals_winner: winner = diagonals_winner else: winner = None return def check_rows(): global game_still_going row1 = board[0] == board[1] == board[2] != "_" row2 = board[3] == board[4] == board[5] != "_" row3 = board[6] == board[7] == board[8] != "_" if row1 or row2 or row3: game_still_going = False if row1: return board[0] elif row2: return board[3] elif row3: return board[6] return def check_columns(): global game_still_going column1 = board[0] == board[3] == board[6] != "_" column2 = board[1] == board[4] == board[7] != "_" column3 = board[2] == board[5] == board[8] != "_" if column1 or column2 or column3: game_still_going = False if column1: return board[0] elif column2: return board[1] elif column3: return board[2] return def check_diagonals(): global game_still_going diagonal1 = board[0] == board[4] == board[8] != "_" diagonal2 = board[2] == board[4] == board[6] != "_" if diagonal1 or diagonal2: game_still_going = False if diagonal1: return board[0] elif diagonal2: return board[2] return def check_if_NO_hay_mas_movimientos_posibles(): global game_still_going if "_" not in board: game_still_going=False return def flip_player(): global current_player if current_player == "x": current_player = "o" elif current_player == "o": current_player = "x" return play_game() #board #display board #play game #handle turn #check win #check columns #check diagonals #check rowms #check tie #flip player
e26b3cc62b0ffa63868dfaa4aee29f2cf3c0eede
Stefanh18/gagnaskipan
/time_complexity/multiplication_ints.py
276
3.75
4
from time import time # Time complex = O(n) def multiplication(integer, integer2): end_value = 0 for _ in range(integer2): end_value += integer return end_value start_time = time() print(multiplication(4,2)) end_time = time() print(end_time - start_time)
4a1dcbfd5aa43f81e47dfd83beece7703086e145
obukhalov/edX
/Introduction to Computer Science and Programming Using Python/Week2/gcdIter.py
332
4.03125
4
# -*- coding: utf-8 -*- def gcdIter(a, b): ''' a, b: positive integers returns: a positive integer, the greatest common divisor of a & b. ''' if a < b: gcd = a else: gcd = b while bool(a % gcd) or bool(b % gcd): if gcd == 1: break gcd -= 1 return gcd
507e355168f72472d5b189bb95e9783c6539e554
1877762890/python_all-liuyingyign
/day05任务及课上代码/代码/day05/demo/demo1.py
1,153
4.28125
4
''' python: 56,23,25:整型(int) 56.31:浮点数据(float,double) "hello world" "刘嘉伟":字符串(str) True,False:布尔(boolean) 元组:(1,4,5,6,6,8,2,10) 不可能在改变 列表:[1,2,3,4,5,6,65,5,47] 数据可以随时改变 字典:{ "010":"南京", "020":"上海", } (键值对应关系。特点:不能存储重复数据。) 集合:(1,5,7,8,9,9):不能存储重复的数据 ''', ''' a = 56 b = "张家玮" c = True d = 6.32 print(type(a)) print(type(b)) print(type(c)) print(type(d)) ''' ''' 列表:[] 常用的api: len() 求长度 ''' '''print(a[0]) print(a[1]) print(a[2]) print("列表的长度:",len(a)) ''' a = [-9,-5,-4,-2,-3,-7,-8,-9] max = a[0] index = -1 for i in range(0,len(a)): if a[i] >= max: max = a[i] index = i print("a里的最大值为:",max,",所对应角标为:",index) # 求所有数的和
22063a89bd8365f45ebe46e87ba38dbcb69c9202
jamil-said/code-samples
/Python/Python_code_challenges/gameBoardLights.py
1,887
3.953125
4
""" gameBoardLights You are programming the behavior of a series of eight lights arranged in a straight line on the board of an electronic game. The lights can be either on or off. At every second that elapses, the lights will change (or not) their state according to the following pattern: if both neighbor lights are on or off, the light turns (or remains) off; otherwise, the light turns (or remains) on. For the edge lights that have only one neighbor, you may consider that the other (non-existing) neighbor light is always off. Write a program that returns the state of the lights after a certain amount of seconds. You will be provided with an array that represents the initial status of the lights (with 0 and 1 values, 0 being "off" and 1 being "on") and an integer that represents the amount of seconds to be elapsed. Return an array with the state of the lights after the given seconds elapse. Note that even after updating the light state, its previous state is considered for updating the state of the other lights. The light states should be all updated at the same time. For example: boardLights([1, 0, 0, 1, 0, 0, 0, 0], 1) should return: [0, 1, 1, 0, 1, 0, 0, 0] """ def boardLights(states, s): newStates = [0] * len(states) while s > 0: for i in range(1, len(states)-1): if states[i-1] == 0 and states[i+1] == 0 or states[i-1] == 1 \ and states[i+1] == 1: newStates[i] = 0 else: newStates[i] = 1 if states[1] == 1: newStates[0] = 1 else: newStates[0] = 0 if states[-2] == 1: newStates[-1] = 1 else: newStates[-1] = 0 states = newStates[:] s -= 1 return states print(boardLights([1, 0, 0, 1, 0, 0, 0, 0], 1))# [0, 1, 1, 0, 1, 0, 0, 0] print(boardLights([1, 1, 0, 0, 1, 1, 1, 1], 2))# [1, 0, 0, 0, 1, 1, 1, 0]
ac984fc5634778dd9bb7fb800fee934d28c490c5
tomyagel/tybmicalc
/calc_sub_file.py
2,890
3.75
4
import tkinter.messagebox as msb class Validator: @classmethod def validate_name(cls, name): # Validates the name entry str_name = str(name) if str_name == '': msb.showerror("No Name Entered", "Please enter a name to proceed") return False if not str_name.isalpha(): msb.showerror("Invalid Name Entered", "Your name entry must be entirely alphabetic") return False @classmethod def validate_metric_weight(cls, kg_weight): # Validates the weight entry str_kg_weight = str(kg_weight) if str_kg_weight == '': msb.showerror("No Weight Entered", "Please enter valid weight value(s) to proceed") return False if not (str_kg_weight.replace('.', '', 1)).replace('e+', '', 1).isdigit(): msb.showerror("Invalid Weight Value(s) Entered", "Weight values must be entirely numeric") return False if float(kg_weight) < 2 or float(kg_weight) > 700: msb.showerror("Weight Value Out of Range", "Weight values must be between 2-700 kg / 4.5 lbs-110 st. 3.3lbs") return False @classmethod def validate_metric_height(cls, cm_height): # Validates the height entry str_cm_height = str(cm_height) if str_cm_height == '': msb.showerror("No Height Entered", "Please enter valid height value(s) to proceed") return False if not (str_cm_height.replace('.', '', 1)).replace('e+', '', 1).isdigit(): msb.showerror("Invalid Height Value(s) Entered", "Height values must be entirely numeric") return False if (float(cm_height) != 0.0 and float(cm_height) < 50) or float(cm_height) > 300: msb.showerror("Height Value Out of Range", "Height values must be between 50-300 cm / 19.7 in-9 ft 11 in") return False class Metric: def __init__(self): self.user_name = "" self.kg_weight = 0 self.cm_height = 0 def calculate_metric_bmi(self): kg_weight = self.kg_weight cm_height = self.cm_height bmi = 0 bmi += kg_weight / ((cm_height / 100) * (cm_height / 100)) bmi = round(bmi, 1) return bmi def categorize_bmi(self): kg_weight = self.kg_weight cm_height = self.cm_height bmi = 0 bmi += kg_weight / ((cm_height/100) * (cm_height/100)) bmi = round (bmi, 1) bmi_category = "" if bmi < 18.5: bmi_category += "Underweight" elif 18.5 <= bmi < 25: bmi_category += "Normal (Healthy Weight)" elif 25 <= bmi < 30: bmi_category += "Overweight" else: bmi_category += "Obese" return bmi_category
e79bca0618719305dab5e6807799150d4a20375a
kersky98/stud
/coursera/pythonHse/sixth/13.py
1,181
3.640625
4
# В олимпиаде участвовало N человек. Каждый получил определенное количество # баллов, при этом оказалось, что у всех участников разное число баллов. # Упорядочите список участников олимпиады в порядке убывания набранных баллов. # Формат ввода # Программа получает на вход число участников олимпиады N. Далее идет N строк, # в каждой строке записана фамилия участника, затем, через пробел, набранное # им количество баллов. # Формат вывода # Выведите список участников (только фамилии) в порядке убывания набранных # баллов. # from audioop import reverse n = int(input()) lst = [] for i in range(n): lst.append(tuple(input().split())) # print(lst) lst.sort(key=lambda x: int(x[1]), reverse=True) for item in lst: print(item[0])
9794c9c04ebcd5c7d761be2e80ed12ba29e3bb66
0ndrey/Homework-GeekBrains
/Homework #1 (6).py
336
3.859375
4
a = float(input("Результат в 1 день:")) b = float(input("Желаемый результат:")) n = 1 while a < b: a = a + 0.1 * a n += 1 if a >= b: print(f"на {n} день спортсмен достиг нужного результата") break else: continue
34c1dfd0142cc1a2e66a251ecd57cb1015074079
pizzadancer/pythontuts
/stringsbegin.py
342
4.25
4
first_name = "jim" last_name = "bob" #output = "Hello, {1}, {0}".format(first_name, last_name) output = f"Hello, {first_name} {last_name}" print(output) name = input("Who the hell are ya? \n") #asks user for first/last name output = f"Hello {name}" print(output) fav_car = input("What's your favorite car? ") print(f"{fav_car} very nice")
14702a6c79e48f8a277dfb812a78692f1e4966f3
rhnvrm/mini-projects
/vignere.py
525
3.609375
4
ciphertext = raw_input() key = raw_input() ciphertext = ciphertext.lower() key = key.lower() def itoc(x): return chr(x + ord('a')) def ctoi(x): return (ord(x) - ord('a')) % 26 #print ctoi('a'), ctoi('z') #print itoc(0), itoc(25) while(len(key) < len(ciphertext)): key = key + key print "+ve: " for i in xrange(0, len(ciphertext)): print itoc((ctoi(ciphertext[i]) + ctoi(key[i]))%26) , print "" print "-ve: " for i in xrange(0, len(ciphertext)): print itoc((ctoi(ciphertext[i]) - ctoi(key[i]))%26) , print ""
dd7611d8f847b1c80742459ed3099e038007d0f5
sanchitmonga22/Python-Programming
/Derp interpreter implementation using nodes/Derp interpreter.py
5,735
3.921875
4
""" 141 Tree Lab - Derp the Interpreter Derp is a simple interpreter that parses and evaluates prefix expressions containing basic arithmetic operators (*,//,-,+). It performs arithmetic with integer only operands that are either literals or variables (read from a symbol table). It dumps the symbol table, produces the expression infix with parentheses to denote order of operation, and evaluates/produces the result of the expression. Author: Scott C Johnson (scj@cs.rit.edu) Author: Sanchit Monga """ from dataclasses import dataclass from typing import Union @dataclass class LiteralNode: """Represents an operand node""" val: int @dataclass class VariableNode: """Represents a variable node""" name: str @dataclass class MathNode: """Represents a mathematical operation""" left: Union['MathNode', LiteralNode, VariableNode] op: str right: Union['MathNode', LiteralNode, VariableNode] ############################################################################## # parse ############################################################################## def parse(tokens): """parse: list(String) -> Node From a prefix stream of tokens, construct and return the tree, as a collection of Nodes, that represent the expression. """ a=tokens.pop(0)#npopping the first element if a in ['+','-','//','*']:# checking whether the element is a mathmatical operator or not return MathNode(parse(tokens), a, parse(tokens)) elif a.isidentifier():# chekcing whether the element is a character return VariableNode(a) elif a.isdigit():# checking whether the element is a digit return LiteralNode(a) else:# checking whether the user input is other than the required raise ValueError(a,"invalid") ############################################################################## # infix ############################################################################## def infix(node): """infix: Node -> String | TypeError Perform an inorder traversal of the node and return a string that represents the infix expression.""" if node is None:# base case return '' else: if isinstance(node,MathNode)==True:# checking wherhter the element is a math node or not return '('+infix(node.left)+str(node.op)+infix(node.right)+')' elif isinstance(node,VariableNode)==True:# checking wherhter the element is a variable node or not return infix(None)+str(node.name)+infix(None) elif isinstance(node,LiteralNode)==True:# checking wherhter the element is a literal node or not return infix(None)+str(node.val)+infix(None) ############################################################################## # evaluate ############################################################################# def evaluate(node, symTbl): """evaluate: Node * dict(key=Sring, value=int) -> int | TypeError Given the expression at the node, return the integer result of evaluating the node. Precondition: all variable names must exist in symTbl""" if node is None:# base case for recursion return '' else: if isinstance(node,MathNode)==True:# if the value is a mathnode or not if(str(node.op)=='+'):# checking whether the node.op ois ewual to different operators and perfomring the operations according to that return evaluate(node.left, symTbl)+evaluate(node.right, symTbl) elif(str(node.op)=='-'): return evaluate(node.left, symTbl)-evaluate(node.right, symTbl) elif(str(node.op)=='*'): return evaluate(node.left, symTbl)*evaluate(node.right, symTbl) elif (str(node.op) == '//'): return evaluate(node.left, symTbl)//evaluate(node.right, symTbl) elif isinstance(node,VariableNode)==True:# checking wherhter the element is a variable node or not return int(symTbl[str(node.name)]) elif isinstance(node,LiteralNode)==True:# checking whether the elements belong to a literal node return int(node.val) ############################################################################## # main ############################################################################## def main(): """main: None -> None The main program prompts for the symbol table file, and a prefix expression. It produces the infix expression, and the integer result of evaluating the expression""" print("Hello Herp, welcome to Derp v1.0 :)") inFile = input("Herp, enter symbol table file: ") a={}# creating a new dictionary for line in open(inFile):# for every line in the file a1=line.strip() b=a1.split() #storing the elements of each line in a list a[b[0]]=b[1]# entering all the elements in the dictionary along with the key print("Herp, enter prefix expressions, e.g.: + 10 20 (ENTER to quit)...") # input loop prompts for prefix expressions and produces infix version # along with its evaluation while True: prefixExp = input("derp> ") if prefixExp == "": break l=prefixExp.split()# splitting all the elements in the prefix and storing it in a list s=parse(l)# invoking the parse function by passing a list inside it inf=infix(s)# storing the infix value by passing the node value in the parse function print("Derping the infix expression:"+inf)# printing the infix expression eval=evaluate(s,a)# invoking the evaluate function and storing its value print("Derping the evaluation:", eval)# printing the value after evaluation print("Goodbye Herp :(") if __name__ == "__main__": main()
d6dbb39ae9b27e416af63b22a2b8440e4b3d2dbf
coco-in-bluemoon/baekjoon-online-judge
/CLASS 1/2741: N 찍기/solution.py
275
3.78125
4
def solution(n): numbers = [str(number) for number in range(1, n+1)] return '\n'.join(numbers) if __name__ == "__main__": n = 5 answer = '1\n2\n3\n4\n5' assert solution(n) == answer n = int(input()) my_answer = solution(n) print(my_answer)
3c92534e849f1f12831f7b4f35fc6022f66fdfe2
ShaunakSen/algorithms-in-python
/snippets/derek_twelfth.py
599
3.890625
4
# ASSIGN VAR TO A FUNCTION def multiplyBy2(num): return num * 2 times2 = multiplyBy2 print "4*2 =", times2(4) # PASS FUNCTION AS ARGUMENT def do_math(func, num): return func(num) print "8*2 =", do_math(multiplyBy2, 8) # DYNAMICALLY CREATE A FUNCTION INSIDE A FUNCTION def get_func_mult_by_num(num): def mult_by(value): return num * value return mult_by generated_function = get_func_mult_by_num(5) print "5 * 10 =", generated_function(10) # EMBED FUNCTION INTO A DATA STRUCTURE listOfFuncs = [times2, generated_function] print "5 * 9 =", listOfFuncs[1](9)
2e4e70cfde859e81cae30d9e8dfc34e482199b43
rushirg/LeetCode-Problems
/solutions/sign-of-the-product-of-an-array.py
736
3.890625
4
""" 1822. Sign of the Product of an Array - https://leetcode.com/problems/sign-of-the-product-of-an-array/ - https://leetcode.com/contest/weekly-contest-236/problems/sign-of-the-product-of-an-array/ """ # Method 1 class Solution: def arraySign(self, nums: List[int]) -> int: product = 1 for x in nums: product *= x if product == 0: return product elif product > 0: return 1 return -1 # slight variation in Method 1 class Solution: def arraySign(self, nums: List[int]) -> int: product = 1 for x in nums: if x == 0: return x elif x < 0: product = -product return product
65a4622504829cb665a411a95dde691cecc101fc
btemovska/Functions
/star_example.py
373
3.65625
4
numbers = (0, 1, 2, 3, 4, 5) print(numbers) #(0, 1, 2, 3, 4, 5) print(*numbers) #0 1 2 3 4 5 print(numbers, sep=";") #(0, 1, 2, 3, 4, 5) print(*numbers, sep=";") #0;1;2;3;4;5 print() def test_star(*args): print(args) #(0, 1, 2, 3, 4, 5) for x in args: print(x) #puts them in each row test_star(0, 1, 2, 3, 4, 5) print() test_star() #() empty tuple
1c84bf7378fad2c37edec81a26b4d27704f54440
G-Vicky/hackerrank-challenges
/string formatting.py
545
3.90625
4
def print_formatted(number): for i in range(1, number + 1): # o = oct(i) # o = o[o.find('o') + 1:] # h = hex(i) # h = list(c.upper() for c in h) # h = "".join(h) # h = h[h.find('X') + 1:] # b = bin(i) # b = b[b.find('b') + 1:] # print("{:d} {:s}".format(i, o)) width = len("{0:b}".format(number)) print("{0:{width}d} {0:{width}o} {0:{width}X} {0:{width}b}".format(i, width=width)) if __name__ == '__main__': n = int(input()) print_formatted(n)
4e6cf3a1ba3649f3ad0d73b4e4ad1766a6d27745
dundunmao/lint_leet
/mycode/leetcode_old/1 array(12)/88. merge sorted array.py
429
4.34375
4
# -*- encoding: utf-8 -*- # 1级 # 内容:Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array. # 主要方法: def merge(nums1, m, nums2, n): nums3 = nums1[:m]+nums2[:n] nums3.sort() nums1[:m+n] = nums3 #因为需要 in place return nums1 if __name__ =="__main__": nums1 = [0,1,1,3] nums2 = [0.5,4,5,5,5,1] m = 2 n = 3 print merge(nums1, m, nums2, n)
adef8bea0c2b324f2031096132787ff1f6e6bab6
CodyMorley/cs-module-project-algorithms
/product_of_all_other_numbers/product_of_all_other_numbers.py
1,016
4.125
4
''' Input: a List of integers Returns: a List of integers ''' def get_product(arr): product = 1 for x in range(0, len(arr) - 1): factor = arr[x] product *= factor return product def product_of_all_other_numbers(arr): ret_list = list() if len(arr) < 2: return -1 elif len(arr) == 2: replacement = arr[1] del arr[1] arr.insert(0, replacement) return arr for i in range(0, len(arr) - 1): lhs = arr[ : i] rhs = arr[i+1 : ] product_to_append = get_product(lhs) * get_product(rhs) ret_list.append(product_to_append) return ret_list if __name__ == '__main__': # Use the main function to test your implementation # arr = [1, 2, 3, 4, 5] arr = [2, 6, 9, 8, 2, 2, 9, 10, 7, 4, 7, 1, 9, 5, 9, 1, 8, 1, 8, 6, 2, 6, 4, 8, 9, 5, 4, 9, 10, 3, 9, 1, 9, 2, 6, 8, 5, 5, 4, 7, 7, 5, 8, 1, 6, 5, 1, 7, 7, 8] print(f"Output of product_of_all_other_numbers: {product_of_all_other_numbers(arr)}")
dd6a18a87b5e6f5260dbfc8a3f992dd7233826c4
terryproctor/python_stuff
/pets.py
570
3.609375
4
pets = [] pet = { 'type': 'dog', 'name': 'rover', 'legs': 4, 'tail': 'yes', 'food': 'dogfood', } pets.append(pet) pet = { 'type': 'snake', 'name': 'sid', 'legs': 'none', 'tail': 'yes', 'food': 'mice', } pets.append(pet) pet = { 'type': 'cat', 'name': 'henry', 'legs': 4, 'tail': 'yes', 'food': 'catfood', } pets.append(pet) for animal in pets: print(f"{animal['name'].title()}") for attributes, value in animal.items(): print(f"\t{attributes}: {value}") print('\n')
05886b1d2445b612eb3316b656276e91e65c4c52
kdaivam/data-structures
/linkedlists/linkedlists_mergeSort.py
2,615
3.984375
4
#!/bin/python3 import math import sys import os class LinkedListNode: def __init__(self, node_value): self.val = node_value self.next = None def _insert_node_into_singlylinkedlist(head, tail, val): if head == None: head = LinkedListNode(val) tail = head else: node = LinkedListNode(val) tail.next = node tail = tail.next return tail def mergeSortList(pList): if pList == None or pList.next == None: return pList pList_left, pList_right = divide_list(pList) left = mergeSortList(pList_left) right = mergeSortList(pList_right) return mergelist(left, right) def mergelist(pList_left, pList_right): merged_list = LinkedListNode(None) curr = merged_list while pList_left and pList_right: if pList_left.val < pList_right.val: curr.next = pList_left pList_left = pList_left.next else: curr.next = pList_right pList_right = pList_right.next curr = curr.next if pList_left == None: curr.next = pList_right if pList_right == None: curr.next = pList_left return merged_list.next def divide_list(pList): if pList == None or pList.next == None: pList_left = pList pList_right = None return pList_left, pList_right else: mid_ptr = pList front_runner_ptr = pList.next while front_runner_ptr != None: front_runner_ptr = front_runner_ptr.next if front_runner_ptr != None: front_runner_ptr = front_runner_ptr.next mid_ptr = mid_ptr.next pList_left = pList pList_right = mid_ptr.next mid_ptr.next = None return pList_left, pList_right # Complete the function below. #For your reference: #LinkedListNode { # int val # LinkedListNode next #} #def mergeSortList(pList): #f = open(os.environ['OUTPUT_PATH'], 'w') _pList = None _pList_tail = None _pList_size = 0 _pList_size = int(input()) _pList_i=0 while _pList_i < _pList_size: _pList_item = int(input()); if _pList_i == 0: _pList = _insert_node_into_singlylinkedlist(_pList, _pList_tail, _pList_item) _pList_tail = _pList else: _pList_tail = _insert_node_into_singlylinkedlist(_pList, _pList_tail, _pList_item) _pList_i += 1 res = mergeSortList(_pList); #while (res != None): # f.write(str(res.val) + "\n") # res = res.next; #f.close() while(res != None): print(str(res.val)) res = res.next
63637449f0e387519f1bf00b0ecafdd29babd646
v0lta/pyTrace
/src/math/Color.py
834
3.53125
4
''' Created on Feb 23, 2016 @author: moritz ''' import numpy as np class Color(object): ''' Contains a numpy array with color definitions for red, green and blue raning from 1 to 255. ''' def __init__(self, red=None,green=None,blue=None,npArray=None): ''' Sets up the color. ''' if npArray != None: self.npArray = npArray else: if (red < 0) or (red > 255): raise ValueError, "Red value out of bounds" if (green < 0) or (green > 255): raise ValueError, "green value out of bounds" if (blue < 0) or (blue > 255): raise ValueError, "blue value out of bounds" self.npArray = np.array([red,green,blue]) def getColor(self): return self.npArray
a41dddca24701083d235657d783ffde09b82c2a1
Sankti/Collabo_Tests
/Circle_area_calc.py
387
4.1875
4
def circle_area(x): pi = 3.141592 area = pi * (float(x)*float(x)) print("The area of a wheel with a radius of " + x + "cm is " + (str(round(float(area),4)) + "cm2.\n")) while True: r = input("""Enter radius value in cm or enter Q to quit: \n""").lower() if r == "q": break elif r.isalpha(): print("Sorry, incorrect input, try again.\n") continue circle_area(r)
53081ebeef1144b49dfeda1bdb78c6c02dfe0102
JuliaClaireLee/old-python-course-work
/untitled folder 2/lab6.py
246
3.953125
4
mountains = {} mountains["Mount Everest"] = "29,029 feet" mountains["k2"] = "28,251 feet" mountains["Kangchenjunga"] = "28,169 feet" for moutain, height in mountains.items(): print("\nmountain: %s" % moutain) print("height: %s" % height)
12904649614e1ca3157dc430697b4316f7fca915
green-fox-academy/IBS_guthixx23
/week-02/day-02/draw_pyramid.py
186
4.0625
4
num = int(input("Give me a number!")) stars = 1 spaces = num - 1 while num != 0: print((" " * spaces) + ("*" * stars) + (" " * spaces)) stars += 2 spaces -= 1 num -= 1
33b2c7abbddef8847dc945d9d51b6a94e5a1cb01
vicchu/Leetcode-Python
/medium/product-of-array-except-self.py
559
3.609375
4
from typing import List class Solution: def productExceptSelf(self, nums: List[int]) -> List[int]: answer = [1, nums[0]] backward = [nums[-1]] for i, num in enumerate(nums[1:-1]): answer.append(num*answer[i+1]) for i, num in enumerate(nums[-2::-1]): backward.append(num*backward[i]) answer[-2-i] = backward[i] * answer[-2-i] return answer print(Solution().productExceptSelf([1, 2, 3, 4])) print(Solution().productExceptSelf([-1, 1, 0, -3, 3]))
7501a0e797e52a9748b36df26b02b930b9934447
NatanLisboa/python
/exercicios-cursoemvideo/Mundo2/ex067.py
1,482
4.375
4
# Aula 14 - Estrutura de repetição while (Estrutura de repetição com teste lógico) # Desafio 067 - Faça um programa que mostre a tabuada de vários números, um de cada vez, para cada valor digitado pelo # usuário. O programa será interrompido quando o número solicitado for negativo. print('-' * 30) print('Desafio 067 - Tabuada v3.0') print('-' * 30) while True: num = str(input('Digite um número para ver a sua tabuada (Digite um número negativo para encerrar o programa): ')) numeroValido = False if num.isnumeric(): numeroValido = True elif num[0] == '-' and num[1:num.find('.')].isnumeric() and num[num.find('.') + 1:].isnumeric(): numeroValido = True elif num[0] == '-' and num[1:num.find('.')].isnumeric(): numeroValido = True elif num[0] == '-' and num[1:].isnumeric(): numeroValido = True elif num[:num.find('.')].isnumeric() and len(num) == num.find('.') + 1: numeroValido = True elif num[:num.find('.')].isnumeric() and num[num.find('.') + 1:].isnumeric(): numeroValido = True if not numeroValido: print('\n\033[4;31mVOCÊ NÃO DIGITOU UM NÚMERO VÁLIDO! TENTE NOVAMENTE.\033[m\n') else: num = float(num) if num < 0.0: break else: print('-' * 30) for i in range(0, 11): print(f'{num} x {i:>2} = {num * i}') print('-' * 30) print('\nObrigado por utilizar o programa :)')
cc0a130ba62fdf2c86964790852454e3c236f635
ChaoMneg/Offer-python3
/数组/Array_multiply.py
827
3.96875
4
# -*- coding: utf-8 -*- # @Time : 2020/1/31/031 16:40 # @Author : mengchao # @Site : # @File : Array_multiply.py # @Software: PyCharm """ 题目:乘积数组 给定一个数组A[0,1,...,n-1],请构建一个数组B[0,1,...,n-1], 其中B中的元素B[i]=A[0]*A[1]*...*A[i-1]*A[i+1]*...*A[n-1]。 不能使用除法。 """ class Solution: def multiply(self, A): if not A: return False n = len(A) B = [None] * n B[0] = 1 # 前半部分,从上往下计算 for i in range(1, n): B[i] = B[i-1] * A[i-1] # 后半部分,从下往上计算 tmp = 1 for j in range(n-2, -1, -1): tmp = tmp * A[j+1] B[j] = B[j] * tmp return B S = Solution() A = [2,3,4,5,6] B = S.multiply(A) print(B)
5d9fa02f3c9c81636a79bc98e411550dd4b1b71f
sudhir512kj/just-test
/spiral_matrix.py
862
3.59375
4
def spiralOrder(matrix): ans = [] if (len(matrix) == 0): return ans R = len(matrix) C = len(matrix[0]) rowBeg = 0 colBeg = 0 rowEnd = R-1 colEnd = C-1 while rowBeg <= rowEnd and colBeg <= colEnd: for i in range(colBeg, colEnd+1): ans.append(matrix[rowBeg][i]) rowBeg += 1 for i in range(rowBeg, rowEnd+1): ans.append(matrix[i][rowEnd]) colEnd -= 1 if rowBeg <= rowEnd: for i in range(colEnd, colBeg-1, -1): ans.append(matrix[rowEnd][i]) rowEnd -= 1 if colBeg <= colEnd: for i in range(rowEnd, rowBeg-1, -1): ans.append(matrix[i][colBeg]) colBeg += 1 return ans # Driver code a = [[1,2,3,4],[5,6,7,8],[9,10,11,12]] print(spiralOrder(a))
6f028f0accaab92611e15fc1ed374a44714e4a26
yinguangyao/py
/oop/slot.py
211
3.53125
4
# slots可以限制当前类的实例只能设置哪些属性 # 但是对继承的子类无效 class Student(object): __slots__ = ["name", "age"] s1 = Student() s1.name = "111" s1.age = 20 s1.sex = "female"
bf42e3163ecbcef0746a23cc30472b1c479e6242
Shivansh-007/Python-Beginner-Projects
/Get User Name Prompt.py
326
3.984375
4
#get the username from a prompt username = input("Login: >> ") #list of allowed users user1 = "Shivansh" user2 = "Shivansh The Great" #control that the user belongs to the list of allowed users if username == user1: print("Access granted") elif username == user2: print("Welcome to the system") else: print("Access denied")
5088d0c02bade7ff9b40500ed7e4a75fc849abed
raygolden/leetcode-python
/src/stringInterleaving.py
895
4.125
4
#!/usr/bin/env python """ Given s1, s2, s3, find whether s3 is formed by the interleaving of s1 and s2. For example, Given: s1 = "aabcc", s2 = "dbbca", When s3 = "aadbbcbcac", return true. When s3 = "aadbbbaccc", return false. """ def isInterleaving(s1, s2, s3): k = 0 q = [(k, [(0, 0)])] # examing s3 k position, (0, 0) is examing s1 and s3 position l3 = len(s3) while q: k, out = q.pop() i, j = out[-1] if k == l3 and i + j == l3: return True if i < len(s1) and s3[k] == s1[i] and k < l3: q.append((k + 1, out + [(i + 1, j)])) if j < len(s2) and s3[k] == s2[j] and k < l3 : q.append((k + 1, out + [(i, j + 1)])) return False if __name__ == '__main__': print isInterleaving("aabcc", "dbbca", "aadbbcbcac") print isInterleaving("aabcc", "dbbca", "aadbbbaccc")
da89c9a443f3fdd0abbfc008cf3b80bfd3f30e9b
pranshu798/Python-programs
/Functions/Partial Functions/p1.py
235
3.53125
4
from functools import partial # A normal function def f(a, b, c, x): return 1000 * a + 100 * b + 10 * c + x # A partial function that calls f with # a as 3, b as 1 and c as 4. g = partial(f, 3, 1, 4) # Calling g() print(g(5))
c7ac5aafb578c49d364f1be0c5145fc7a2a42448
Changyoon-Lee/TIL
/Algorithm/programmers/두 개 뽑아서 더하기.py
195
3.609375
4
from itertools import combinations def solution(numbers): res = [sum(i) for i in combinations(numbers,2)] res = list(set(res)) res.sort() return res print(solution([2,1,3,4,1]))
f64429b25b659e4a3ed5f2dd52058b74203349a4
kaleeswarinataraja/hhh.py
/vowel.py
141
3.609375
4
m=['a','e','i','o','u'] n=input() if(l.count(n)!=0): print("Vowel") elif(n.isalpha()): print("Consonant") else: print("invalid")
8892331f6b017386f6dc0ac3feb6042aa20a4920
maomao905/algo
/longest-word-in-dictionary.py
1,292
3.765625
4
""" O(NLlogNL) """ from typing import List class Solution: def longestWord(self, words: List[str]) -> str: seen = set() for w in sorted(words, key=len): if len(w) == 1: seen.add(w) elif w[:-1] in seen: seen.add(w) ans = '' for w in seen: if len(ans) < len(w) or (len(ans) == len(w) and w < ans): ans = w return ans """ trie O(NL) """ class Solution: def longestWord(self, words: List[str]) -> str: trie = {} for w in words: node = trie for c in w: if c not in node: node[c] = {} node = node[c] node['*'] = w ans = '' def dfs(node): for ch in node: if '*' in node[ch]: nonlocal ans w = node[ch]['*'] if len(ans) < len(w) or (len(ans) == len(w) and w < ans): ans = w dfs(node[ch]) dfs(trie) return ans s = Solution() print(s.longestWord(['w','wo','wor','worl','world'])) print(s.longestWord(["a", "banana", "app", "appl", "ap", "apply", "apple"]))
8877573c95f5d15d4e2327ac629d22b0e449ff40
EnigmaticEntity/MI250Lab2
/gamble.py
510
3.65625
4
import random def flipCoin(): random.randrange(0,2) if random.randrange(0,2) == 0: print("Heads") else: print("Tails") def casino(dollars): stats = [] flips = 0 heads = 0 profit = 0 while dollars >= 1 | flips < 300: dollars = dollars - 1 random.randrange(0,2) if random.randrange(0,2) == 0: dollars = dollars + 1.2 print("You won this flip, total is $" + str(dollars)) else: print("Lost this flip")
becb9c3bbe4afc2d3087251ff18ba2c60bed668b
Sravaniram/pythonprogramming
/prime and reminder is 3 sum.py
93
3.609375
4
n=int(input()) s=0 for x in range(1,n+1): if(x%2!=0 and x%10==3): s=s+x print(s)
c5d87acb608e52b3f23efe69c103d21c7c14edc6
noahsark769/top-frequency
/frequency.py
4,103
4.21875
4
from collections import defaultdict def most_frequent_words(corpus, n): """Given a large string representing a text document, return a list of the n most frequent words in the string. Note: here we define a word to be any sequence of characters in the corpus delimited by spaces. If we wanted to exclude certain sequences(for example "--", ",", etc), it would be simple to apply a basic filter. However, we do let words be delimited by any number of spaces. Args: corpus - a string n - an integer representing the number of most frequent words to return, in order of frequency, with ties broken arbitrarily. Returns: a list of the n most frequent words Raises: ValueError if either of the arguments are improperly formatted Running time: We iterate over the corpus exactly once, then iterate through a range that is bounded by the maximum frequency, which is at most the number of words in the corpus (which is bounded by the number of characters in the corpus). Thus our asymptotic running time is in O(n), where n is the number of characters in the corpus. """ # handle a few edge cases: if n == 0 or len(corpus) == 0: raise ValueError("Incorrectly formatted arguments to most_frequent_words.") word_to_frequency = defaultdict(lambda: 0) # a dict mapping words to their frequencies frequency_to_words = defaultdict(set) # a dict mapping a frequency to a set of words with that frequency non_empty_frequencies = set() # a set of all the frequencies for which there are words with that frequency max_frequency = 0 # the maximum frequency of any word words = [word for word in corpus.strip().split(" ") if len(word)] # iterate through all the words in the corpus. # for each word, increment its frequency. remove the word # from the old frequency entry, and add it to the new one. # update the max if needed. for word in words: # the current frequency of the word that we've noted so far: curr_word_frequency = word_to_frequency[word] # say a word currently has frequency 4, but we've seen it again, so # we want to increment it to 5. we have to remove the word from the frequency 4 # set and add it to the frequency 5 set. additionally, if frequency 4 no longer # has any words, we'll remove it from the set of non empty frequencies. if curr_word_frequency > 0: frequency_to_words[curr_word_frequency].remove(word) if len(frequency_to_words[curr_word_frequency]) == 0: non_empty_frequencies.remove(curr_word_frequency) # now, actually increment the frequency word_to_frequency[word] += 1 new_frequency = word_to_frequency[word] # update the maximum frequency we've seen so far if new_frequency > max_frequency: max_frequency = new_frequency # if frequency 5 is still believed to be empty, then we say it's not anymore if new_frequency not in non_empty_frequencies: non_empty_frequencies.add(new_frequency) # and add the current word to the set of words with frequency 5 frequency_to_words[new_frequency].add(word) # now, start with the maximum frequency, and take words in # decreasing order of frequency and print them. result = [] frequency = max_frequency num_printed = 0 while frequency != 0 and num_printed < n: if frequency in non_empty_frequencies: words_with_this_frequency = frequency_to_words[frequency] while len(words_with_this_frequency) != 0 and num_printed < n: popped = words_with_this_frequency.pop() result.append(popped) num_printed += 1 frequency -= 1 return result def print_most_frequent_words(corpus, n): """Given a large text document as a string, print the n most frequent words.""" for word in most_frequent_words(corpus, n): print word
0b2d4d953f26fdfa0edf41e8ad47adfb4ccb7b06
DaniNem/N2T_Zilber_Neimark
/projects/06/Assembler/AInstruction.py
1,074
3.875
4
class AInstruction: """ an a instruction converting class """ AT = "@" # a instruction sign def __init__(self): """ default constructor """ pass def run(self, lines, symbols): """ go over the lines and convert them to binary form :param lines: file lines :param symbols: symbols dictionary """ for i in range(len(lines)): # go over the lines and and replace # the appropriate lines to binary form if lines[i].startswith(self.AT): # check if a instruction jump = lines[i].strip(self.AT) self.__convert_to_bin(lines, jump, i) def __convert_to_bin(self, lines, name, line_num): """ :param lines: file lines :param name: name of register :param line_num: appropriate line number """ if name.isdigit(): # check that line is int reg = str(bin(int(name)))[2:] # convert to binary form lines[line_num] = "0" + "0" * (15 - len(reg)) + reg
2d56876471b1205d47403f1222538e553394d3b1
arungajora/Atom_Projects
/Exercises/Beginner_Projects/Pythagorean_Triples_checker_including_triangle_checking.py
479
4.375
4
print("Please input side a, b, and c, where c is the longest.") print("Please input side a.") a=float(input()) print("Please input side b.") b=float(input()) print("Please input side c (aka longest side).") c=float(input()) print("Please input side a, b, and c, where c is the longest.") if (c**2) == (a**2 + b**2): print("This is a Pythagorean triangle.") elif a<b+c and b<a+c and c<a+c: print("This is a triangle.") else: print("This is NOT even a triangle.")
ade24cf547690fbea1c8322e1367849849ffe320
LouisYLWang/leetcode_python
/647.palindromic-substrings.py
597
3.53125
4
# # @lc app=leetcode id=647 lang=python # # [647] Palindromic Substrings # class Solution(object): count = 0 def extendPalindrome(self, s, l, r): while l >= 0 and r < len(s) and s[l] == s[r]: self.count += 1 l -= 1 r += 1 def countSubstrings(self, s): """ :type s: str :rtype: int """ if not s: return 0 for i in range(len(s)): self.extendPalindrome(s, i, i) self.extendPalindrome(s, i, i + 1) return self.count
6eac5991c86da08fffc565a43f1dfea33dbf2595
ondreali/Module4
/validation_with_try.py
1,285
4.125
4
""" Program: Coupon Calculation.py Author: Ondrea Li Date: 6/10/20 The purpose of this program is to input validation to make user_input positive """ NUMBER_TEST = 1 def average(): # Get input for scores # declare variables, use score1, score2, score3 in calculation return average_scores score1 = int(input("What is score1?")) score2 = int(input("What is score2?")) score3 = int(input("What is score3?")) def average(score1, score2, score3): NUMBER_TESTS = 3 try: if 0<score1<= 100: print ("score is within range") else: print("score needs to be a positive integer") raise ValueError if 0<score2<= 100: print("score is within range") else: print("score needs to be a positive integer") raise ValueError if 0<score3<= 100: print("score is within range") else: print("score needs to be a positive integer") raise ValueError except: print("score not convert") raise ValueError return float((score1 + score2 + score3)/NUMBER_TESTS) average_score = average(score1, score2, score3) print(average_score) if __name__ == '__main__': pass
54be544ba212e2b37b1a2f2d7f88feb20e7697c4
abdesamad11/TestOdoo
/Test1.py
570
4.125
4
#Test 1: Any language (3/20) # Write a program that outputs sequentially the integers from 1 to 99, but on some conditions prints a string instead: # when the integer is a multiple of 3 print “Open” instead of the number, # when it is a multiple of 7 print “Source” instead of the number, # when it is a multiple of both 3 and 7 print “OpenSource” instead of the number. for i in range(1,100): if i % 21 == 0: print('openSource') elif i % 3 == 0: print('open') elif i % 7 == 0: print('source') else: print(i)
ac887ef047d009845d22b8433c3522ad89c369b4
robertcristensen/pscript
/sphere.py
768
3.9375
4
import math class Sphere: def __init__(self,r=1,x=0,y=0,z=0): self.r = r self.x = x self.y = y self.z = z def get_volume(self): volume = (4.0/3.0)*math.pi*self.r**3 return volume def get_square(self): s = 4*math.pi*self.r**2 return s def get_radius(self): return self.r def get_center(self): return (self.x,self.y,self.z) def set_radius(self,r): self.r=r def set_center(self,x,y,z): self.x = x self.y = y self.z = z def is_point_inside(self,x,y,z): if math.sqrt((x-self.x)**2+(y-self.y)**2+(z-self.z)**2) < self.r: return True else: return False
832ae5746fec2192da41e729ee59886c6640c855
metalauren/codingground
/New Project/main.py
858
3.90625
4
# Hello World program in Python tweetfile = open("tweets.txt", "r") #open file alltweets = tweetfile.read() #read the file tweets = alltweets.splitlines() #a list where each element is an tweet runningmedians = [] wordsintweet = [] def median(x): x.sort() mid = len(x) // 2 if len(x) % 2: return x[mid] else: return (x[mid - 1] + x[mid]) / 2.0 for i in range(0,(len(tweets))): tweets[i] = tweets[i].split() #splits each tweet into a list of words for j in range(0,(len(tweets[i]))): if tweets[i][j][-1] in [".",",","?","!",":",";"]: tweets[i][j] = tweets[i][j][0:-1] #cuts off basic punctuation from the end of a word wordsintweet.append(len(tweets[i])) runningmedians.append(median(wordsintweet)) print tweets print wordsintweet print runningmedians print tweets[0][7][0:7]
4709b191c0c4701f432b319f1388a0bebcbaaddc
Animeshjainq/Python-books-and-exercises
/Data-Structures/singly_linked_list/singly_linked_list.py
2,173
3.953125
4
class Node: def __init__(self, value = None, next_node = None): self.value = value self.next_node = next_node def get_value(self): return self.value def get_next_node(self): return self.next_node def set_next_node(self, new_next): self.next_node = new_next class LinkedList: def __init__(self): self.head = None self.tail = None def add_to_head(self,value): new_node = Node(value) if self.head is None: self.head = new_node self.tail = new_node else: #set next_node of my new node to the head new_node.set_next_node(self.head) #update head self.head = new_node def add_to_tail(self,value): new_node = Node(value) if self.head is None: self.head = new_node self.tail = new_node else: self.tail.set_next_node(new_node) self.tail = new_node def remove_head(self): #empty list if self.head is None: return None else: return_val = self.head.get_value() #one thing if self.head == self.tail: self.head = None self.tail = None #nonempty - return a VALUE of the old head else: self.head = self.head.get_next_node() return return_val def remove_tail(self): if self.head is None: return None elif (self.head == self.tail): val = self.tail.get_value() self.tail = None self.head = None else: val = self.tail.get_value() temp = self.head while temp.get_next_node() is not self.tail: temp = temp.get_next_node() temp.set_next_node(None) self.tail = temp return val def contains(self,value): cur_node = self.head while cur_node is not None: if cur_node.get_value() == value: return True return False def get_max(self): pass
75328570a3a9d8b4bb56cc09b2edb3e44fbf729d
dunmatt/house-of-enlightenment
/python/stateMachine/neighbor_filter.py
583
3.859375
4
#!/usr/bin/env python """ """ class NeighborFilter(object): """NeighborFilter is in charge of knowing whether two stations are neighbors, and if so which side they're on. """ def __init__(self, station): super(NeighborFilter, self).__init__() self.id = station.id def IsLeftNeighbor(self, other): return other.id == self.id - 1 or other.id == 5 and self.id == 0 def IsRightNeighbor(self, other): return other.id == self.id + 1 or other.id == 0 and self.id == 5 if __name__ == '__main__': # TODO(dunmatt): put some sort of test/example code here pass
05ef6412918334a4176f2a90447bcd0e4f83a4de
cnzxcxt1/Mastering-scikitlearn
/chapter-07.py
3,039
3.90625
4
# chapter 07: Dimensionality Reduction with PCA ### Performing Principal Component Analysis import numpy as np X = [[2, 0, -1.4], [2.2, 0.2, -1.5], [2.4, 0.1, -1], [1.9, 0, -1.2]] print(np.cov(np.array(X).T)) import numpy as np w, v = np.linalg.eig(np.array([[1, -2], [2, -3]])) w v # Dimensionality reduction with Principal Component Analysis # Using PCA to visualize high-dimensional data import matplotlib.pyplot as plt from sklearn.decomposition import PCA from sklearn.datasets import load_iris data = load_iris() y = data.target X = data.data pca = PCA(n_components=2) reduced_X = pca.fit_transform(X) red_x, red_y = [], [] blue_x, blue_y = [], [] green_x, green_y = [], [] for i in range(len(reduced_X)): if y[i] == 0: red_x.append(reduced_X[i][0]) red_y.append(reduced_X[i][1]) elif y[i] == 1: blue_x.append(reduced_X[i][0]) blue_y.append(reduced_X[i][1]) else: green_x.append(reduced_X[i][0]) green_y.append(reduced_X[i][1]) plt.scatter(red_x, red_y, c='r', marker='x') plt.scatter(blue_x, blue_y, c='b', marker='D') plt.scatter(green_x, green_y, c='g', marker='.') plt.show() ################# Sample 1 ################# import numpy as np print(np.linalg.eig(np.array([[3, 2], [1, 2]]))[0]) W, V = np.linalg.eig(np.array([[3, 2], [1, 2]])) ################# Figure 1################# import matplotlib .pyplot as plt import numpy as np A = np.array([[2, 1], [1, 2]]) plt.scatter(A[:, 0], A[:, 1], marker='.', s=200) plt.plot(A[0], A[1]) plt.show() ################# Sample: Face recognition with PCA ################# from os import walk, path import numpy as np import mahotas as mh from sklearn.cross_validation import train_test_split from sklearn.cross_validation import cross_val_score from sklearn.preprocessing import scale from sklearn.decomposition import PCA from sklearn.linear_model import LogisticRegression from sklearn.metrics import classification_report X = [] y = [] for dir_path, dir_names, file_names in walk('D://Dropbox//Scikit-Learn//Mastering Machine Learning with scikit-learn//Chapter7//data//att-faces/orl_faces'): for fn in file_names: if fn[-3:] == 'pgm': image_filename = path.join(dir_path, fn) X.append(scale(mh.imread(image_filename, as_grey=True).reshape(10304).astype('float32'))) y.append(dir_path) X = np.array(X) X_train, X_test, y_train, y_test = train_test_split(X, y) pca = PCA(n_components=150) X_train_reduced = pca.fit_transform(X_train) X_test_reduced = pca.transform(X_test) print('The original dimensions of the training data were', X_train.shape) print('The reduced dimensions of the training data are', X_train_reduced.shape) classifier = LogisticRegression() accuracies = cross_val_score(classifier, X_train_reduced, y_train) print('Cross validation accuracy:', np.mean(accuracies), accuracies) classifier.fit(X_train_reduced, y_train) predictions = classifier.predict(X_test_reduced) print(classification_report(y_test, predictions))
4906915fb42eccdba24c3234e3feececc9199da4
Somebodyzm/IsValid
/isValid.py
796
3.515625
4
class Solution(object): def isValid(self, s): """ :type s: str :rtype: bool """ stack =[] #初始化栈stack dic ={')':'(','}':'{',']':'['} #建立字典dict,key为右括号,value为左括号 for char in s : #遍历输入字符串s的每个字符char if char in dic : #如果char在dict里(即为右括号) top = stack.pop() if stack else '#' #弹出栈顶字符top if top != dic[char] : #如果栈顶字符不是对应符号的左括号,返回无效 return False else : # 如果char不在dict里(即为左括号),将char压入栈中 stack.append(char) return not stack #最后栈中还有字符,返回无效
3b8941bc0e52ba754411ec103dee3be4282078c3
chlos/exercises_in_futility
/misc/nebius/04_algo_aa_2.py
2,525
3.90625
4
""" Реализовать функцию fuzzysearch как в редакторе sublime text 3 . Для незнакомых с редактором и/или термином fuzzysearch (нечёткий поиск), можно упомянуть более формальное название — approximate string matching (нахождение приблизительного соответствия строк). По факту требуется проверить, является ли первая строка подпоследовательностью второй. fuzzysearch('car', 'cartwheel'); // true fuzzysearch('cwhl', 'cartwheel'); // true fuzzysearch('cwhee', 'cartwheel'); // true fuzzysearch('cartwheel', 'cartwheel'); // true fuzzysearch('cwheeel', 'cartwheel'); // false fuzzysearch('lw', 'cartwheel'); // false """ #('cl', 'cel') # ^ ^ def is_substring(pattern, text): if not pattern: return True p_idx = 0 t_idx = 0 while t_idx < len(text): if pattern[p_idx] == text[t_idx]: p_idx += 1 t_idx += 1 else: t_idx += 1 if p_idx == len(pattern): return True return False """ Дан текст T и строка P. Требуется найти подстроку P' в T такую, что она совпадает с P с точностью до перестановки букв. В качестве ответа стоит вернуть индекс первого вхождения, или -1, если такая подстрока P' не нашлась. P T 'abc', 'bca' >> 0 'abc', 'qqbcarabc' >> 2 'abc', 'qqbarab' >> -1 'abc', 'qcqbarab' >> -1 """ import collections import copy def get_first_substring_idx(pattern, text): if not pattern: return 0 if not text: return -1 pattern_counter_init = collections.Counter(pattern) pattern_count = copy.copy(pattern_counter_init) t_start_idx, t_end_idx = 0, 0 while t_end_idx < len(text): curr_ch = text[t_end_idx] if curr_ch in pattern_count: pattern_count[curr_ch] -= 1 if pattern_count[curr_ch] == 0: del pattern_count[curr_ch] t_end_idx += 1 else: pattern_count = copy.copy(pattern_counter_init) t_start_idx, t_end_idx = t_end_idx + 1, t_end_idx + 1 if not pattern_count: return t_start_idx return -1
b481369f0502223872ae2dacaf8ccade5d87489a
shubhamfursule/Square-Magic
/Square Magic.py
1,471
3.71875
4
sq_magic=[[8,11,14,1] ,[13,2,7,12] ,[3,16,9,6] ,[10,5,4,15]] def square_magic(sq_matrix): add_up_row=sum(sq_matrix[0]) #Here first check the sum for rows flag= False for i in range(1,len(sq_matrix)): if add_up_row==sum(sq_matrix[i]): add_up_row=sum(sq_matrix[i]) flag=True else: flag=False break #checking column and diagonal if flag==True: list_diagonal=0 for i in range(0,len(sq_matrix)): list_colm=[] for j in range(0,len(sq_matrix[i])): list_colm.append(sq_matrix[j][i]) if i==j: #calculating for diagonal item list_diagonal += sq_matrix[i][j] #checking the sum of columns if add_up_row==sum(list_colm): #comparing same value and sum of columns add_up_row=sum(list_colm) flag=True else: flag=False break #Calculating second diagonal list_diagonal2=0 z=0 for k in range(len(sq_matrix[z])-1,-1,-1): list_diagonal2+=sq_matrix[z][k] z+=1 if flag==True and list_diagonal==add_up_row and list_diagonal2==add_up_row: return True,add_up_row else: return False print(f"Square magic is :{square_magic(sq_magic)} with same value")
6200cd975bebcfcf35af7fe6425d3cd1c7a69357
ciszakdamian/cdv_interface_api
/09-11-2019/1/5.py
232
3.65625
4
file = open("file.txt", "w") text = '' while True: line = input("Podaj linie tekstu: ") if not line.strip(): break text += str(line+'\n') file.write(text) file.close() print('Plik file.txt został utworzony.')
de63983d2a77ec1c67cc840bce69e6f316ffa5a0
Adlerchuayc/Worksheet-1-2017
/2017 Worksheet 1/Question 14/Significant_Figure_Calculator.py
5,512
4.0625
4
number = input("Please type in an integer or a float: ") sig_fig = input("How many significant figures would you like? ") # 0 is taken to be positive def positive_integer(): final_answer = "" a = number if len(a) == int(sig_fig): final_answer = number else: if len(a) < int(sig_fig): a = a + "." while len(a) - 1 != int(sig_fig): a = a + "0" final_answer = a else: b = 1 while len(a) > int(sig_fig): if int(a[len(a) - 1]) < 5: a = a[:len(a) - 1] final_answer = a else: while int(a[len(a) - b]) > 4: b += 1 else: c = str(int(a[len(a) - b]) + 1) a = a[:len(a) - b] + c final_answer = a while len(a) < len(number): a = a + "0" final_answer = a print_value = "The value " + number + " rounded to " + sig_fig + " significant figures is: " + final_answer print(print_value) def negative_integer(): final_answer = "" a = str(abs(int(number))) if len(a) == int(sig_fig): final_answer = number else: if len(a) < int(sig_fig): a = a + "." while len(a) - 1 != int(sig_fig): a = a + "0" final_answer = a else: b = 1 while len(a) > int(sig_fig): if int(a[len(a) - 1]) < 5: a = a[:len(a) - 1] final_answer = a else: while int(a[len(a) - b]) > 4: b += 1 else: c = str(int(a[len(a) - b]) + 1) a = a[:len(a) - b] + c final_answer = a while len(a) < len(number) - 1: a = a + "0" final_answer = a print_value = "The value " + number + " rounded to " + sig_fig + " significant figures is: " + "-" + final_answer print(print_value) def positive_float(): final_answer = "" a = number if len(a) - 1 == int(sig_fig): final_answer = number else: if len(a) - 1 < int(sig_fig): while len(a) - 1 != int(sig_fig): a = a + "0" final_answer = a else: a = a.replace(".", "") b = 1 + 1 while len(a) > int(sig_fig): if int(a[len(a) - 1]) < 5: a = a[:len(a) - 1] final_answer = a else: while int(a[len(a) - b]) > 4: b += 1 else: c = str(int(a[len(a) - b]) + 1) a = a[:len(a) - b] + c final_answer = a while len(a) < len(number) - 1: a = a + "0" final_answer = a final_answer = str(float(final_answer) / (10 ** float(sig_fig))) print_value = "The value " + number + " rounded to " + sig_fig + " significant figures is: " + final_answer print(print_value) def negative_float(): final_answer = "" a = str(abs(float(number))) if len(a) - 1 == int(sig_fig): final_answer = number else: if len(a) - 1 < int(sig_fig): while len(a) - 1 != int(sig_fig): a = a + "0" final_answer = a else: a = a.replace(".", "") b = 1 + 1 while len(a) > int(sig_fig): if int(a[len(a) - 1]) < 5: a = a[:len(a) - 1] final_answer = a else: while int(a[len(a) - b]) > 4: b += 1 else: c = str(int(a[len(a) - b]) + 1) a = a[:len(a) - b] + c final_answer = a while len(a) < len(number) - 1: a = a + "0" final_answer = a final_answer = str(float(final_answer) / (10 ** float(sig_fig))) print_value = "The value " + number + " rounded to " + sig_fig + " significant figures is: " + "-" + final_answer print(print_value) ##floats are messed up #Function call if "." not in number: if "-" not in number: positive_integer() else: negative_integer() else: if "-" not in number: positive_float() else: negative_float() ## ## ###positive integers ##if "." not in number: ## ## sig_fig = input("How many significant figures would you like? ") ## ## ## if (len(number) == int(sig_fig)): ## final_answer = number ## ## elif (len(number) < int(sig_fig)): ## final_answer = number + str(".") ## if (len(number) == int(sig_fig)): ## done = False ## while True: ## final_answer = final_answer + str(0) ## print(final_answer) ## ## else: ## a = number ## b = [] ## for i in range(int(sig_fig)): ## b.append(a[i]) ## final_answer = str(b) ## ## print_value = "The value " + number + " rounded to " + sig_fig + " significant figures is: " + final_answer ## ## print(print_value) ## ## rounding up and down? fix the print and the float ones too
9c203b51877842e0b82ab6466cf6a41fe82d5bde
daniel-reich/ubiquitous-fiesta
/XYvyirQMkmPHGLaZi_16.py
283
3.546875
4
def boom_intensity(n): res = "B" + "o" * n + "m" if n < 2: return "boom" elif n % 5 == 0 and n % 2 == 0: return res.upper() + "!" elif n % 5 == 0: return res.upper() elif n % 2 == 0: return res + "!" else: return res
bde569a5851c7d1802ac30d10057d0eec4768c98
Metallicode/designpatterns
/dp_03_builder.py
2,704
3.546875
4
##Robot Parts class Legs: def __init__(self): self.size = None def __repr__(self): return f"LEGS size: {self.size}" class Arms: def __init__(self): self.length = None def __repr__(self): return f"ARMS length: {self.length}" class Body: def __init__(self): self.power = None def __repr__(self): return f"BODY power: {self.power}" class Head: def __init__(self): self.color = None def __repr__(self): return f"HEAD color: {self.color}" ##Builder Interface class Builder: def getLegs(self): pass def getArms(self): pass def getBody(self): pass def getHead(self): pass ##Concrete Builder 01 class DefenceRobotBuilder(Builder): def getLegs(self): legs = Legs() legs.size = "big" return legs def getArms(self): arms = Arms() arms.length = "full" return arms def getBody(self): body = Body() body.power = "max" return body def getHead(self): head = Head() head.color = "gray" return head ##Concrete Builder 02 class HomeRobotBuilder(Builder): def getLegs(self): legs = Legs() legs.size = "small" return legs def getArms(self): arms = Arms() arms.length = "half" return arms def getBody(self): body = Body() body.power = "economy" return body def getHead(self): head = Head() head.color = "pink" return head #full item class Robot: def __init__(self): self.__legs = None self.__arms = None self.__body = None self.__head = None def setLegs(self, legs): self.__legs = legs def setArms(self, arms): self.__arms = arms def setBody(self, body): self.__body = body def setHead(self, head): self.__head = head def __repr__(self): return f"ROBOT id{id(self)} \n{self.__legs}\n{self.__arms}\n{self.__body}\n{self.__head}" #Director class Director: __builder = None def SetBuilder(self, builder): self.__builder = builder def GetRobot(self): bot = Robot() bot.setLegs(self.__builder.getLegs()) bot.setArms(self.__builder.getArms()) bot.setBody(self.__builder.getBody()) bot.setHead(self.__builder.getHead()) return bot if __name__ == "__main__": director = Director() director.SetBuilder(DefenceRobotBuilder()) test_robot = director.GetRobot() print(test_robot)
8914aea06c49b838f88d66eb66ecb23c24a7c275
elva02347/python-2020-8
/untitled4.py
279
3.953125
4
import random number = random.randint(1,10) while True: guess = int(input('fill in your number from one to ten:')) if number == guess: print('you are right!!') print(number) break else: print('you are wrong~~, keep trying.')
003044465cb3caeeb0cfc6b4707a9404ab7d39cf
smrodrigues/programacao2
/calculadora.py
295
4
4
print ("sinta-se a vontade") print ("calculadora")print ("SEJA BEM VINDO!!") x = int (input ("digite um número:")) y = int (input ("digite um número:")) opcao = str (input ("a para adição" "\n s para subtração" "\n d para divisão" "\n m para multiplicação \n escolha:")) print (x, y)
252f80277e1a4c9016d13bc071776fb6ba46ed06
Tatiana-Yatna/numbers
/src/exercises/current-age.py
148
3.859375
4
import datetime born = int(input('What year were you born?')) def age(born): return datetime.datetime.now().year - born print(age(born))
93c30117c2868c47440ca9c31f28a38180bf6291
Unst1k/GeekBrains-PythonCourse
/DZ3/DZ3-2.py
1,683
4.0625
4
# Реализовать функцию, принимающую несколько параметров, описывающих данные # пользователя: имя, фамилия, год рождения, город проживания, email, телефон. # Функция должна принимать параметры как именованные аргументы. # Реализовать вывод данных о пользователе одной строкой. def user_data(user_name, user_surname, user_birth_year, user_city, user_email, user_tel): print(f'{user_name} {user_surname}, {user_birth_year} года рождения. Проживает в городе {user_city}.' f' Email пользователя: {user_email}. Телефон пользователя: {user_tel}.') print('Введите данные и получите краткую информацию о себе!') while True: try: name, surname = input('Введите Имя и Фамилию через пробел: ').split(' ') birth_year = int(input('Введите год рождения: ')) city = input('Введите город проживания: ') email = input('Введите ваш email: ') tel = int(input('Введите номер телефона(без пробелов и спец. символов): ')) user_data(user_name=name, user_surname=surname, user_birth_year=birth_year, user_city=city, user_email=email, user_tel=tel) break except ValueError: print('Введено некорректное значение!')
f1c5ac257a404573aa44509e7d7e955a24abbc6d
szcheng0702/cs229-finalproject
/PCA.py
766
3.5
4
import numpy as np import matplotlib.pyplot as plt ##features includes all n article ## features=np.array(([1,9,0],[0,2,1]))#test value, modified later ## def PCA(features,k): #k:number of principal components numfeat=features.shape[1] numarticle=features.shape[0] Cov=np.cov(features.T) ##take the covariance matrix for the features eval,evec=np.linalg.eig(Cov) ##find the first k principal components, where eval[k] is closest enough to zero #plt.plot(eval) #plt.show() evec_k=evec[0:k,:] mu=np.mean(features,axis=0) feat_new=np.zeros([numarticle,k]) for i in range(numarticle): feat_new[i,:]=np.dot(evec_k,(feat_new[i,:]-mu)) #the new features matrix is called feat_new return feat_new
19ab36b81957c26983d73fcd534c7de5b764bd71
monybun/TestDome_Exercise
/TrainComposition(H20).py
2,475
3.828125
4
''' A TrainComposition is built by attaching and detaching wagons from the left and the right sides, efficiently with respect to time used. For example, if we start by attaching wagon 7 from the left followed by attaching wagon 13, again from the left, we get a composition of two wagons (13 and 7 from left to right). Now the first wagon that can be detached from the right is 7 and the first that can be detached from the left is 13. Implement a TrainComposition that models this problem. ''' ''' ##colloction-->deque : list-like container with fast appends and pops on either end import collections class TrainComposition: def __init__(self): self.train = collections.deque() def attach_wagon_from_left(self, wagonId): self.train.appendleft(wagonId) def attach_wagon_from_right(self, wagonId): self.train.append(wagonId) def detach_wagon_from_left(self): return self.train.popleft() if self.train else None def detach_wagon_from_right(self): return self.train.pop() if self.train else None if __name__ == "__main__": train = TrainComposition() train.attach_wagon_from_left(7) train.attach_wagon_from_left(13) print(train.detach_wagon_from_right()) # should print 7 print(train.detach_wagon_from_left()) # should print 13 ''' ## METHOD TWO : using dictionary class TrainComposition: def __init__(self): self.train = dict() self.left = 1 self.right = 0 def attach_wagon_from_left(self, wagonId): self.left -= 1 self.train[self.left] = wagonId def attach_wagon_from_right(self, wagonId): self.right += 1 self.train[self.right] = wagonId def detach_wagon_from_left(self): if self.left > self.right: return None wagonId = self.train[self.left] del self.train[self.left] self.left += 1 return wagonId def detach_wagon_from_right(self): if self.left>self.right: return None wagonId = self.train[self.right] del self.train[self.right] self.right -= 1 return wagonId if __name__ == "__main__": train = TrainComposition() train.attach_wagon_from_left(7) train.attach_wagon_from_left(13) print(train.detach_wagon_from_right()) # should print 7 print(train.detach_wagon_from_left()) # should print 13
caf2eb8a007daf1b9a50326980ea2daa7b6b57c8
JosephLevinthal/Research-projects
/5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/226/users/4131/codes/1593_1803.py
187
3.5
4
from math import* n= int(input(" digite um n ")) x1= n//1000 x2= n//100 - (n//1000)*10 x3= n//10 - (n//100)*10 x4= n//1 - (n//10)*10 final= (x1* 5)+(x2* 4)+(x3* 3)+(x4*2) print(final %11)
84eddd3c6e12a62d37a6d682fb2a5320303f963a
ushodayak/ushodaya
/5.temp.py
115
3.921875
4
celsius = input('Enter degree Celsius: ') fahrenheit = (celsius * 1.8) + 32 print('fahrenheit temp is'+fahrenheit)
10a62ad8faadf5537691adc009099208e7c34e52
JeffUsername/python-stuff
/python/test/Ch6/table_printer.py
803
3.75
4
def printTable(tab): #sets ip recursion h = len(tab) w = len(tab[0]) lLen =0 printT_Helper(tab, h, w, lLen) def printT_Helper(tab, h, w, lLen): #recursive helper if w>0: t = str(tab[0][w-1] + ' '+ tab[1][w-1] + ' ' + tab[2][w-1]) s = len(t) if s > lLen: lLen = s z = printT_Helper(tab, h, w-1, lLen) #rec call #print(z) t = t.rjust(((z-lLen)+ lLen), '-') print(t) if lLen < z: lLen = z return z else: #print(lLen) return lLen if __name__ == "__main__": tableData = [['apples', 'oranges', 'cherries', 'banana'], ['Alice', 'Bob', 'Carol', 'David'], ['dogs', 'cats', 'moose', 'goose']] printTable(tableData)
36302fc8eae05f82a1972655b4df6fbf004c1c21
nadiavp/NeuralNetwork
/train_single_layer.py
3,603
3.578125
4
def train_single_layer(net, desired_out, inputs): #this does forward and backward propagation for a one layer network for a set of #generators and a demand #inputs: #net - instance of class NueralNetwork #desired_out - desired network output when using forward funnction in the form of a vertical vector, #inputs - matrix of inputs of size inputlength x number of outputs #outputs: #net - trained neural network #sqrerror - square error for each training example #train_error - vector of mean square error at each iteration #initialize [sqrerror, dedw, dedb] = finderror(net, inputs, desired_out) tolerance = 0.0001 iterations = 0 laststep = np.zeros(np.shape(dedw)) lastbstep = np.zeros(np.shape(dedb)) a = 1 momentum = 0.25 #train until you meet the threshold or the number of iterations while np.count_nonzeros(abs(sqrerror)>tolerance)>0: #find error and relation to weights and biases [sqrerror, dedw, dedb] = finderror(net, inputs, desired_out) step = dedw*a/100 + laststep*momentum/100 bstep = dedb*a/100 + lastbstep*momentum/100 net.wlayer1 = net.wlayer1 - step net.blayer1 = net.blayer1 - bstep #check error with new weight and bias [sqrerrornew, _, _] = finderror(net, inputs, desired_out) #if it gets worse, try a different step size if sum(sum(abs(sqrerrornew)))>= sum(sum(abs(sqrerror))) or np.count_nonzeros(sqrerrornew==float('inf')): if abs(a) < 1e-12: a = 1 else: a = a/10 #undo the last change net.wlayer1 = net.wlayer1+step net.blayer1 = net.blayer1+bstep laststep = np.zeros(np.shape(laststep)) lastbstep = np.zeros(np.shape(lastbstep)) #if it gets better, keep the change and keep going else: laststep = step lastbstep = bstep sqrerror = sqrerrornew #if you are below tolerance, stop if np.count_nonzeros(abs(sqrerrornew)>tolerance) == 0: print('below tolerance') break #if you have hit your max iterations, stop if iterations>1e4: print('not converging after 10^4 iterations, exiting training loop') sqrerror = sqrerrornew break iterations = iterations+1 return net, sqrerror def finderror(net, inputs, desired_out): #this is a sub function of train_single_layer which calcualtes the error in the #network output and also finds the necessary change in wieghts and biases #inputs: #net - instance of class NueralNetwork in the process of being trained #inputs - training examples in matrix #desired_out - training example desired outputs in matrix #outputs: #derrordw - derivative of weight with respect to error #derrordb - derivative of bias with respect to error #cost - 1/2 square error for each training example net_out = net.forward(inputs) error = desired_out-net_out cost = error**2 *0.5 if net.classify: #if it has a sigmoid function derrordw = -2*np.transpose(inputs)*error*(net_out*(1-net_out))*net.nodeconst/len(desired_out[:,0]) derrordb = -2*sum(error*net_out*(1-net_out)*net.nodeconst)/len(desired_out[:,0]) else: #if no activation function derrordw = np.transpose(-error*inputs) derrordb = -1/len(error[0,:]) * sum(error,axis=2) return cost, derrordw, derrordb
1230686531a2c2b2cf61e232f6ff40494bdef7cb
cmanders/languageDetection
/languageDetector.py
13,009
3.703125
4
#!/usr/bin/env python3 import sys import csv import numpy as np from random import randrange csv.field_size_limit(sys.maxsize) # # Language Detection System for Text # April 26th, 2020 # # Corey Manders #----------------- utility functions ------------------- # getWordFreq takes as input a single word as # a character string. The output is the frquency # of the word from the oneLang list of words for a # single language. # # input: word (character string) # oneLang (dim 2 and 3 from the frequency model) # # output: frequency of word from the oneLang frequency table # if it is in the table, 0 if it is not found def getWordFreq(word, oneLang): justWord = [row[0] for row in oneLang] if word in justWord: return float(oneLang[justWord.index(word)][1]) else: return 0 # convertToFrqCounts returns a list of word frequencies # corresponding to a list of words given as input. # # input: wordList - a list of words to find frequencies for # languageRef - the 3D language frequency model generated # by buildLanguageCounts # languageIndex - the index to be used (first dim of languageRef) # # output: a list of frquencies corresponding to wordList def convertToFreqCounts(wordList, languageRef, languageIndex): freqs=[] numOccurances = 0 # print("->",wordList) for word in wordList: # print("checking!!",word) freq= getWordFreq(word,languageRef[languageIndex]) if freq > 0: numOccurances+=1 freqs.append(freq) return freqs, numOccurances # seperateToWords takes a character string as input, # and returns a list of words from the character string # # input: character string # output: a list of strings, where every string is one word def seperateToWords(input): # initialization of string to "" new = "" output = [] # traverse in the string for x in input: if x.isspace(): output.append(new) new="" else: new += x return output, len(output) # buildLanguageCounts uses the openSubtitles frequency dataset # to build ordered lists for the frquencies of the sizeOfDict # most common words that at least minWordSize characters in length # # input: a list of languages to construct ordered frquency lists # for, the language should be in their two-letter abbreviations # for example, en for English, fr for French. # # important to note, the function expects the text files of various # languages word frequencies to be in the relative directory # 2018/(two-letter language abbreviation)/(two-letter language abbreviation)_50k.txt # # output: a three dimensional list # dim 1: the index of the language from the list passed in # dim 2: the sizeOfDict most frequent words which are minWordSize # or larger, in order of frquency # dim 3: the frequency of the word from dim2, unnormalized def buildLanguageCounts(languages, dictSize, minWSize): languageWordCounts=[[[0] * 2]*dictSize]*len(languages) currLang = 0 for lang in languages: print("building frquency for language: ",lang) path = "2018/"+lang+"/"+lang+"_50k.txt" line_count = 0 mostFreqCount = 0; with open(path) as lang_file: unsortedList = [[-1] * 2]*sizeOfDict csv_reader = csv.reader(lang_file, delimiter=' ') for row in csv_reader: if line_count < dictSize and len(row[0])>=minWSize: unsortedList[line_count] = row line_count+=1 languageWordCounts[currLang] =unsortedList currLang+=1 return languageWordCounts # grabRandomSentence will extract one sentence randomly from # a character string dataSet. The function assumes that sentences # end with "." and have spaces seperating words. # # input: dataSet is a character string comprised of several sentences # output: a list of words makimng one sentence (return value 1), and # the number of words in the sentence def grabRandomSentence(dataSet): foundSentence = False while not foundSentence: foundStart = False start=randrange(len(dataSet)) while start < len(dataSet) and not foundStart: if dataSet[start]=='.': start+=1 while(start<len(dataSet) and dataSet[start].isspace() ): start+=1 foundStart=True else: start+=1 foundEnd = False end = start while (end< len(dataSet) and not foundEnd): if dataSet[end] == '.': foundEnd = True else: end+=1 sentence, sentLen = seperateToWords(dataSet[start:end]) if (sentLen> minTestSentenceLength): return sentence, sentLen #print(dataSet[start:end]) return NoneType # # read data reads the data file (.csv) containing the two-letter # language code as the first item in the csv field, the text # sample of the language in the second field, and the number of # words in the third field # # input: path to a csv file (for example formatted_data.csv) # output: a 2d list, where the first dimension indexes the language sample # the second dimension is the index for (0), the two-letter # language abbreviation, (1), the language sample, (2) the count # of words in the language sample # def readData(inputPath): data=[] languages = [] with open(inputPath) as csv_file: csv_reader = csv.reader(csv_file, delimiter=';') line_count = 0 for row in csv_reader: if line_count == 0: print(f'Column names are {", ".join(row)}') line_count += 1 else: line_count += 1 data.append(row) for line in data: languages.append(line[0]) return data, languages #------------------------------------------- # testing code # -code to drive the testing of the detection stragetgy # # Detection strategy: # The language detection system leverages the data found in # https://github.com/hermitdave/FrequencyWords # this repository uses the opensubtitle database, in which subtitles # exist for many languages. For example, each language has a file # with the top 50,000 words from the language, in decending order of frequency # # The strategy evolved slightly during initial testing. The initial # thought was to first normalize the frquency counter from the FrequencyWords # list. Then,for any list of words, get the normalized frequency for # each word, for each language being tested. Then add all of the frequencies, # and use the highest summed value to predict the language. # However, though this did work oftern, there were cases where it would # not. For example, if the list of words is short, and one of the words # exists in two languages. If the frequency normalization resulted in # large number for one of the languages, even if it matched more words # in a competing prediction, the language with the single frequency # count may win the prediction, and result in a wrong prediction. # # Given this issue, a second method was selected. This was to take the # list of words, count the number of matches in the top N most frequent # words in the language, and then choose the language which had the # higest count. # # This strategy overall works exceedingly well. There are likely ways # to further improve the result, as well as making the prediction # more computationally light, however, this method seems to be # a good "base" starting point. # # The code for testing this strategy/algorithm implements two methods # of testing and generating accuracy values. Note that as the "training" # data is the frequency lists for each language, and in this implementation # none of the data from "formatted_data.csv" was actually used for # training, the complete content from this file is used for testing. # # The first method of testing is to pick M words from the testing set # from one language. Then use the algortith to predict the language # given all of the languages available in "formatted_data.csv" as # potential candidates. The code below uses M={5,15,30}, however, # this could be any number. The value 5 was chosen as a starting point, # as certainly with the cross-over of identical words from different # languages, one sample may easily be too few to make a prediction. # Five seems to be a reasonable amount as a minimum number, however. # this could be reduced if required. # # There is a trade-off in the minimum size to of words used to # predict the language, and, the number of top N most frequent # words to use in the the frequency table. As the minimum size # of words increases, the higher probability that words will be # in the top frequencies, therefore improving the probability # of an accurate prediction. This would also allow reducing N, # thereby reducing the time needed to make predictions. # # Each language was tested in this manner, and, the results are # presented in the accompanying report. # # The second method of testing was to sample random sentences # from "formatted_data.csv". Again, samples were taken from # each language sample, and predictions were made. Since the # number of words that make up a sentence in any language is # highly variable, this is also considered. The minimum length # of sentence tested in this case was 5, and the output of the testing # also included the length of sentence being tested. # As one would expect, errors generally only occur when the # length of the sentence is very short. # # Both manners of testing are in the accompanying report. inFilename = 'formatted_data.csv' outFilename = 'report_char_seq2.csv' #variables to be used for exploration and reporting randWordSeqLength = (5, 15, 30) numRandomSentenceTrial = 3 numRandomSeqLengthTrial = 3 sizeOfDict = 40000 minWordSize = 4 # when building the word frequency tables, this is # the minimum size word to consider minTestSentenceLength = 5 data,languages = readData(inFilename) reportFile = open(outFilename,"w+") langCounts = buildLanguageCounts(languages,sizeOfDict, minWordSize) #for i in range(len(languages)): #start testing samples for each language for i in range(0,len(languages)): #for i in range(0,2): trialResultsSeq=[] print("---------------------") test,numWordData = seperateToWords(data[i][1]) sentence,sentLen = grabRandomSentence(data[i][1]) #sentenceInWords,numWords = seperateToWords(sentence) print("testing :",languages[i]) if (numRandomSeqLengthTrial > 0): reportFile.write("testing :"+str(languages[i])+ " random sequence lengths "+str(randWordSeqLength)+"\n") print("random word sequences of lengths: ",randWordSeqLength) prediction = -1 randSeqResults=[] ##### testing sequences of words from a random starting point counts = np.zeros((len(languages),len(randWordSeqLength))) for trialNum in range(numRandomSeqLengthTrial): print("running",languages[i],"trial:",trialNum+1,"of",numRandomSeqLengthTrial) for index,lang in enumerate(languages): randStart = randrange(numWordData) for seqLengthInd in range(len(randWordSeqLength)): currLength = int(randWordSeqLength[seqLengthInd]) f, ret= convertToFreqCounts(test[randStart:randStart+currLength], langCounts,index) counts[index][seqLengthInd]=ret results = np.argmax(counts,axis = 0) resultsArgMax = np.equal(results, i) trialResultsSeq.append(resultsArgMax) #print(trialResultsSeq) if (numRandomSeqLengthTrial > 0): reportFile.write('\n'.join([','.join(['{:4}'.format(item) for item in row]) for row in trialResultsSeq])) reportFile.write("\n") ##### testing random sentences from the input files print("starting sentence testing") if (numRandomSentenceTrial > 0): reportFile.write("testing: "+str(languages[i])+ " random sentences from data ""\n") trialResultsSentence = [] counts = np.zeros(len(languages)) for trialNum in range (numRandomSentenceTrial): print("trialnum ",trialNum) sentence2,sentLen = grabRandomSentence(data[i][1]) for index,lang in enumerate(languages): freqs, counts[index] =convertToFreqCounts(sentence2, langCounts,index) print(counts) results = np.argmax(counts) resultsArgMax = np.equal(results, i) trialResultsSentence.append([resultsArgMax, sentLen]) reportFile.write('\n'.join([','.join(['{:4}'.format(item) for item in row]) for row in trialResultsSentence])) reportFile.write("\n") reportFile.close()
d0ad3afe3e2dd32c6e643d00fb3a984286f13cb4
fjmkfjmk/hangman
/hangman.py
1,010
3.90625
4
Python 3.9.2 (tags/v3.9.2:1a79785, Feb 19 2021, 13:44:55) [MSC v.1928 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license()" for more information. >>> #第十章HANGMAN >>> def hangman (word): wrong=0 stages=["", "_______ ", "| ", "| | ", "| 0 ", "| /|| ", "| /| ", "|____________" ] rletters=list(word) board=["_"]*len(word) win=False print("ハングマンへようこそ!") while wrong<len(stages)-1: print("\n") msg="一文字目を予想してね" char=input(msg) if char in rletters: cind=rletters.index(char) board[cind]=char rletters[cind]="$" else: wrong+=1 print(" ".join(board)) e=wrong+1 print("\n".join(stages[0:e])) if "_" not in board: print("あなたの勝ち") print(" ".join(board)) win=True break if not win: print("\n".join(stages[0:wrong+1])) print("あなたの負け!正解は{}.".format(word))
b3a20337964bc5a3454b4d91c3b66ad3d0807b74
jorgesmu/algorithm_exercises
/mathematical/intervals_intersection.py
619
3.9375
4
# Given two intervals in a unidimensional space. Find the # intersection interval between them. Each interval is # represented by a start and end # updated and simplified based on: https://www.youtube.com/watch?v=zGv3hOORxh0&t=30s def intersection(s1, e1, s2, e2): start = max(s1, s2) end = min(e1, e2) if end - start <= 0: return None, None return start, end def execute(s1, e1, s2, e2): print('intersection of s1: ', s1, ' e1: ', e1, ' s2: ', s2, ' e2:', e2) print('is: ', intersection(s1, e1, s2, e2)) execute(2, 5, 3, 7) execute(2, 5, 3, 70) execute(3, 7, 3, 7) execute(3, 5, 5, 7) execute(3, 5, 4, 7)
9e3111c2b29af32f03ff49f1f6ba4fa7a32a4490
slack333/Python
/Super2.py
1,620
3.71875
4
import os os.system ('clear') menu = """Superheroes V.0.0.1 1. Crea un nuevo Superhéroe 2. Muestra Superhéroes 3. Modificar Superhéroes 4. Eliminar Superhéroe X. Salir """ print (menu) while True: opcion = int(input("Selecciona una opción: ")) heroe = [] if opcion == 1: h = {'Nombre':'','Clase':'','Poder':'','Raza':''} h['Nombre'] = input("Ingresa el nombre del Superhéroe: ") h['Clase'] = input("Ingresa el tipo de Superhéroe: ") h['Poder'] = input("Ingresa el poder del Superhéroe: ") h['Raza'] = input("Ingresa la raza del Superhéroe: ") heroe.append(h) print (heroe) elif opcion == 2: print (h['Nombre'], h['Clase'], h['Poder'], h['Raza']) elif opcion == 3: #nombre = input("Ingresa el Nombre del Superhéroe:") print ("¿Qué quieres modificar de?") print (""" 1. Nombre 2. Clase 3. Poder 4. Raza """) opcion2 = int(input("Selecciona una opción: ")) if opcion2 == 1: h['Nombre'] = input("Ingresa un nuevo nombre para este Superhéroe: ") elif opcion2 == 2: h['Clase'] = input("Ingresa una nueva clase para este Superhéroe: ") elif opcion2 == 3: h['Poder'] = input("Ingresa un nuevo poder para este Superhéroe: ") elif opcion2 == 4: h['Raza'] = input("Ingresa una nueva raza para este Superhéroe: ") else: print ("Error, ", opcion2) #elif (opcion == "X" or opcion =="x"): # salir = input(("¿Estás seguro que quieres salir? S/n: ")
f1593ed27ffcdb290ed81ff8beb705163794d6b0
ims010/py
/OOP.py
3,518
4.46875
4
# Python Objct Oriented Programming # Creating classes and instances # Inheritance # Class and instance variables # Static method and classs method # Creating classes and instances - # Class - logically group data and functions in a way to reuse and also easy to build upon # Data - Attributes # Functions - Methods(a function that is associated with a class) class Employee: pass emp_1 = Employee() emp_2 = Employee() print(emp_1) print(emp_2) # Class and a instance of a class: A class is basically a blueprint for creating instances # Instance Variables cantain data that is unique to each instance, we can manually create instance variable for each employee like emp_1.first = 'Nick' emp_1.last = 'Jones' emp_1.email = 'Nick.Jones@company.com' emp_1.pay = 50000 emp_2.first = 'Sarah' emp_2.last = 'Jones' emp_2.email = 'Sarah.Jones@company.com' emp_2.pay = 45000 print(emp_1.email) print(emp_2.email) # Instead of manually adding all these values, we can use a __init__ method class Employee: raise_amount = 1.04 def __init__(self, first, last, pay): self.first = first self.last = last self.pay = pay self.email = first + '.' + last + '@company.com' # When we create methods within a class, they recieve the instance as the first argument automatically. By convension, self is used but anything can be used. # After self we can specify what all the argument we want to accept # self.first = first is same as emp_1.first = 'Nick' # When we create an object outside the __init__ method, instance is passed automatically, so we can leave off the self # __init__ method will be called automatically and instead of self the instance is called def fullname(self): return '{} {}'.format(self.first, self.last) def apply_raise(self): # self.pay = int(self.pay * 1.04) # self.pay = int(self.pay * raise_amount) -> will thrown an error when the instance tries to access this variable. so we can call it as Employee.raise_amount or self.raise_amount self.pay = int(self.pay * self.raise_amount) emp_1 = Employee('Nick', 'Mat', 60000) emp_2 = Employee('Adia', 'Zora', 700000) print(emp_1) print(emp_2) print(emp_1.email) print(emp_2.email) # Methods in class # To print full name without using method print('{} {}'.format(emp_1.first, emp_1.last)) # Else we can define a method within our class print(emp_1.fullname()) print(emp_2.fullname()) # If self is not included in the method def, we gwt TypeError: <Method_Name> takes 0 positional arguments but 1 was given # Running methods using class name iteself print(Employee.fullname(emp_1)) print(Employee.fullname(emp_2)) # While calling a method from class name, we need to provide the instance but if call using the just the method, we don't need instance as the self is called as first instance of the method by default. # Class variable and Instance variables # Class variable are the variables that are shared among all instances of the class # Instance variable can be unique to each instance(first, last, email). # Class varaible should be the same for each instance(apply_raise) print(emp_1.pay) emp_1.apply_raise() print(emp_1.pay) # Regular, Class and Static methods # Regular methods and class automatically take instance as the first argument, by convension, its self. # Class methods called using decorators - @<decorator_name>
046f587ff29e4ca1949564647089a40d0d17f1e7
zhanglae/pycookbook
/ch9/Unwrapping-decorator.py
1,422
3.671875
4
'9.4 Unwrapping a Decorator' ' 去裝飾化' import time from functools import wraps def timethis(func): ''' Decorator that reports the execution time. ''' @wraps(func) def wrapper(*args, **kwargs): start = time.time() result = func(*args, **kwargs) end = time.time() print(func.__name__, end-start) return result return wrapper @timethis def printmoreandmore(i): while i > 0: print(i, end=' ') i -= 1 if i < 1: print() printmoreandmore(5) orig_printmore = printmoreandmore.__wrapped__ orig_printmore(5) 'multiple decorators 儘量不要用此方式' '不知道去掉哪個 decorator...' 'Python3.3 是要去掉所有的' '現在我們在3.4中試試會怎樣' from functools import wraps def decorator1(func): @wraps(func) def wrapper(*args, **kwargs): print('Decorator 1') return func(*args, **kwargs) return wrapper def decorator2(func): @wraps(func) def wrapper(*args, **kwargs): print('Decorator 2') return func(*args, **kwargs) return wrapper @decorator1 @decorator2 def add(x,y): return x + y add(1, 2) # 關於多裝飾器問題, 未來會有變化 也不一定. # However, this behavior has been reported as a bug (see http://bugs.python.org/issue17482) and may be changed to explose the proper decorator chain in a future release.