blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
d840cb2ca2cc12e6a4f065e40085098efc5f4f45
ausaafnabi/30DaysOfAlgorithms
/GreedyAlgorithm/Day_3/GraphColouring.py
1,188
3.6875
4
class Graph: def __init__(self,edges,N): self.adj = [[] for _ in range(N)] # add edges to undirected graph for (src,dest) in edges: self.adj[src].append(dest) self.adj[dest].append(src) def colorGraph(graph,colors,N): # stores color assigned to each V result = {} # assign color to V one by one for u in range(N): # set to store color of adj vertices of u # check color of adj of u and store in set assigned = set([result.get(i) for i in graph.adj[u] if i in result]) # check for the first free color color = 1 for c in assigned: if color != c: break color = color + 1 #assigns vertex u the first available color result[u] = color for v in range(N): print("Color assigned to vertex",v,"is",colors[result[v]]) def main(): colors = ["","BLUE","GREEN","BLACK","RED","WHITE","YELLOW","VIOLET","PINK","PURPLE","ORANGE"] edges = [(0,1),(0,4),(0,5),(4,5),(1,4),(1,3),(2,3),(2,4)] N = 6 graph = Graph(edges,N) colorGraph(graph,colors,N) if __name__ == "__main__": main()
839891e58fdceb5afeac05012de0e001e86c1cb0
adc-code/Math_Various
/LinearRegression/LinearRegression_SciKitLearn.py
1,283
3.765625
4
# # LinearRegression_SciKitLearn.py # # Calculates simple linear regression; slope and intercept of line of best with along with R^2 # # Usage: > python LinearRegression_SciKitLearn.py <InputFile> # from sklearn import linear_model from sklearn.metrics import mean_squared_error, r2_score import numpy as np import sys if len (sys.argv) == 2: fileName = sys.argv [1] f = open (fileName, 'r') xValues = [] yValues = [] for line in f: tokens = line.split (',') xValues.append (float (tokens[0])) yValues.append (float (tokens[1])) f.close () xValues = np.array (xValues).reshape(-1, 1) yValues = np.array (yValues).reshape(-1, 1) # Create linear regression object linReg = linear_model.LinearRegression () # 'Train' the model using the training sets linReg.fit (xValues, yValues) # Predicted y-values yPred = linReg.predict (xValues) # The coefficients print ('Slope: ', linReg.coef_, ' Intercept: ', linReg.intercept_, 'RSquared: ', linReg.score (xValues, yValues)) # The mean squared error print('Mean squared error: ', mean_squared_error(yValues, yPred)) # The coefficient of determination print('Coefficient of determination: ', r2_score(yValues, yPred))
508a2a4d467b6314b54a50fac957df3c9a2c0742
Aman-gusain1998/UML-university-management-system-
/core_utils/ums_utils/teacher.py
1,126
3.625
4
class Teacher: def __init__(self,cursor): self.cursor=cursor def get_teacher_name(self,roll_no): self.cursor.execute("select teacher_name from teacher where student_roll_no="+roll_no) teachername=self.cursor.fetchall() return teachername def get_teacher_department(self,roll_no): self.cursor.execute("select teacher_department from teacher where student_roll_no="+roll_no) teacherdepartment=self.cursor.fetchall() return teacherdepartment def get_t_u_id(self,roll_no): self.cursor.execute("Select t_u_id from teacher where student_roll_no=" + roll_no) teacher_university_id = self.cursor.fetchall() return teacher_university_id def get_t_c_id(self,roll_no): self.cursor.execute("Select t_c_id from teacher where student_roll_no="+roll_no) teacher_college_id =self.cursor.fetchall() return teacher_college_id def get_teacher_details(self,teacher_id): name = self.get_teacher_name(teacher_id) department = self.get_teacher_department(teacher_id) return name, department
9eeabc5f5c5d92f49b3598733434087ba4cc502a
jtlai0921/euler.
/scratch/closure_fun.py
2,195
3.65625
4
#!/usr/bin/env python from itertools import tee, takewhile, count, ifilterfalse #, ifilter from math import sqrt def isprime(number): if number<=1 or number%2==0: return False check=3 maxneeded=number while check<maxneeded+1: maxneeded=number/check if number%check==0: return False check+=2 return True def ifilter(predicate, iterable): # ifilter(lambda x: x%2, range(10)) --> 1 3 5 7 9 if predicate is None: predicate = bool #import pdb; pdb.set_trace() for x in iterable: print x, if predicate(x): yield x def ifilterfalse(predicate, iterable): # filterfalse(lambda x: x%2, range(10)) --> 0 2 4 6 8 if predicate is None: predicate = bool for x in iterable: print x, if not predicate(x): yield x def filter_t(t): def modulo(m): print 'making a thing',m def func(a): return a % m != 0 return func return modulo(t) def filter_primes(top): from pprint import pprint i = 0 t = 3 #skip 2, add it at the end p = xrange(t, top, 2) primes = [] #toproot = sqrt(top) #try: while t < top: print '****',t,'****' primes.append(t) mo = modulo(t) p = ifilter(filter_t, p) #takewhile(lambda x: x < t, p) t = p.next() #p, p_c = tee(p) #print len([x for x in p_c]) print primes i += 1 #except (StopIteration,IndexError) as s: # print s # print i primes.insert(0,2) return primes def iter_primes(): # an iterator of all numbers between 2 and +infinity numbers = itertools.count(2) # generate primes forever while True: # get the first number from the iterator (always a prime) prime = numbers.next() yield prime # this code iteratively builds up a chain of # filters...slightly tricky, but ponder it a bit numbers = itertools.ifilter(prime.__rmod__, numbers) #for p in iter_primes(): # if p > 1000: # break # print p if __name__ == "__main__": print 'hi'
c08617a8cce802138e31c87022295217d354a781
amr-ayoub/lin_alg
/Lin_Alg/src/vector/vect.py
2,359
3.515625
4
import math class Vector(object): def __init__(self, coordinates): try: if not coordinates: raise ValueError self.coordinates = tuple(coordinates) self.dimension = len(coordinates) except ValueError: raise ValueError('The coordinates must be nonempty') except TypeError: raise TypeError('The coordinates must be an iterable') def plus(self,x): new_coordinates= [] n = len(self.coordinates) for i in range(n): new_coordinates.append(self.coordinates[i] + x.coordinates[i]) return Vector(new_coordinates) def minus(self,x): new_coordinates = [] n=len(self.coordinates) for i in range(n): new_coordinates.append(self.coordinates[i] - x.coordinates[i]) return Vector(new_coordinates) def scalar(self,x): new_coordinates = [] n=len(self.coordinates) for i in range(n): new_coordinates.append(self.coordinates[i] * x) return Vector(new_coordinates) def magnitude(self): n=len(self.coordinates) res = 0 for i in range(n): res = res + math.pow(self.coordinates[i], 2) res = math.sqrt(res) return res def normalize(self): magnitude = self.magnitude() magnitude = 1 /magnitude return (self.scalar(magnitude)) def dot_product(self,x): n=len(self.coordinates) res = 0 for i in range(n): res = res + (self.coordinates[i] * x.coordinates[i]) return res def angle_rad(self,x): res = self.dot_product(x) res = res / (self.magnitude() * x.magnitude()) angle = math.acos(res) return angle def angle_deg(self,x): return math.degrees(self.angle_rad(x)) def __str__(self): return 'Vector: {}'.format(self.coordinates) def __eq__(self, v): return self.coordinates == v.coordinates
7ddd3037499aa907eb976ee304d40d8380a88f4a
marvincosmo/Python-Curso-em-Video
/ex069 - Análise de dados do grupo.py
947
3.953125
4
""" 69 - Crie um programa que leia a idade e o sexo de várias pessoas. A cada pessoa cadastrada, o programa deverá perguntar se o usuário quer ou não continuar. No final, mostre: A) quantas pessoas tem mais de 18 anos. B) quantos homens foram cadastrados. C) quantas mulheres tem menos de 20 anos. """ m18 = h = mm20 = 0 while True: print('-'*30) print('CADASTRE UMA PESSOA'.center(30)) print('-'*30) i = int(input('Idade: ')) s = ' ' while s not in 'MF': s = str(input('Sexo [M/F]: ')).strip().upper()[0] print('-'*30) if i > 18: m18 += 1 if s == 'M': h += 1 if s == 'F' and i < 20: mm20 += 1 r = ' ' while r not in 'SN': r = str(input('Quer continuar [S/N]? ')).strip().upper()[0] if r == 'N': break print(f'''Total de pessoas com mais de 18 anos: {m18}. Ao todo, há {h} homens cadastrados. E há {mm20} mulheres com menos de 20 anos.''')
f56e20d7a5bf92d0ee777b212bc80435cac4246a
Avani18/Hackerrank-Python
/12. Python Functionals/Map_And_Lambda_Function.py
270
4.09375
4
cube = lambda x: x**3 def fibonacci(n): # return a list of fibonacci numbers l = [0,1] for i in range(2,n): l.append(l[i-2] + l[i-1]) return(l[0:n]) if __name__ == '__main__': n = int(input()) print(list(map(cube, fibonacci(n))))
d0b87f8441341b246176762bac801890eee6053b
FranzDiebold/project-euler-solutions
/src/p026_reciprocal_cycles.py
2,579
3.875
4
""" Problem 26: Reciprocal cycles https://projecteuler.net/problem=26 A unit fraction contains 1 in the numerator. The decimal representation of the unit fractions with denominators 2 to 10 are given: 1/2 = 0.5 1/3 = 0.(3) 1/4 = 0.25 1/5 = 0.2 1/6 = 0.1(6) 1/7 = 0.(142857) 1/8 = 0.125 1/9 = 0.(1) 1/10 = 0.1 Where 0.1(6) means 0.166666..., and has a 1-digit recurring cycle. It can be seen that 1/7 has a 6-digit recurring cycle. Find the value of d < 1000 for which 1/d contains the longest recurring cycle in its decimal fraction part. """ # pylint: disable=invalid-name from typing import Tuple def _calculate_division( dividend: int, divisor: int, max_decimal_places: int = int(1e6) ) -> Tuple[str, str, str]: """For given integer `dividend` and `divisor`, calculate the division `dividend / divisor`. The decimal fraction part is made up of a fixed starting sequence and a recurring cycle. Example: 1/6 (dividend=1, divisor=6) -> ('0', '1', '6') meaning 0.166666... """ integer_part = str(dividend // divisor) remainder = dividend % divisor idx = max_decimal_places decimal_fraction_parts = [] while remainder != 0 and len(decimal_fraction_parts) < max_decimal_places: remainder *= 10 decimal_place = str(remainder // divisor) remainder %= divisor try: idx = decimal_fraction_parts.index((decimal_place, remainder)) break except ValueError: decimal_fraction_parts.append((decimal_place, remainder)) decimal_fraction = ''.join(str(decimal_place) for decimal_place, _ in decimal_fraction_parts) decimal_fraction_start = decimal_fraction[:idx] decimal_fraction_recurring_cycle = decimal_fraction[idx:] return integer_part, decimal_fraction_start, decimal_fraction_recurring_cycle def main() -> None: """Main function.""" threshold_d = 1000 max_d = None _calculate_division(1, 8) max_d_recurring_cycle_length = -1 for d in range(2, threshold_d): _, _, recurring_cycle = _calculate_division(1, d) if len(recurring_cycle) > max_d_recurring_cycle_length: max_d = d max_d_recurring_cycle_length = len(recurring_cycle) print(f'The unit fraction `1/{max_d:,}` has the longest recurring cycle in its ' \ f'decimal fraction part of all unit fractions `1/d` for d from 2 to {threshold_d}. ' \ f'It has a length of {max_d_recurring_cycle_length:,}.') if __name__ == '__main__': main()
25bb2fc7c26d921ee4aacff98c7ca4fa86441b3b
mukundkri/testing
/testcase.py
2,718
3.90625
4
def reverse(lst): return lst[::-1] def test_reverse1(): input = [1, 2, 3, 4] output = [4, 3, 2, 1] ev = reverse(input) if output == ev: return True, None else: return False, "Four Element Case failed" def test_reverse2(): input = [1, 2, 3, 4, 5] output = [5, 4, 3, 2, 1] ev = reverse(input) if output == ev: return True, None else: return False, "Five Element Test Case failed" def test_reverse(): status, message = test_reverse1() if status == False: return status, message status, message = test_reverse2() if status == False: return status, message return True, None def merge(left, right): result = [] i ,j = 0, 0 while i < len(left) and j < len(right): if left[i] <= right[j]: result.append(left[i]) i += 1 else: result.append(right[j]) j += 1 # Unncomment the 2 lines below # result += left[i:] # result += right[j:] return result def mergesort(list): if len(list) < 2: return list else: middle = len(list) / 2 left = mergesort(list[:middle]) right = mergesort(list[middle:]) return merge(left, right) def test_mergesort(): input = [1, 7, 3, 8, 4] output = [1, 3, 4, 7, 8] ev = mergesort(input) if output == ev: return True, None else: return False, "When I pass %s to your mergesort function I get %s" % (input, ev) def test_bsearch1(): input = [1, 2, 3, 4] key = 2 output = 1 ev = bsearch(input, key) if output == ev: return True, None else: return False, "Key Error" def test_bsearch2(): input = [1, 2, 3, 4] key = 5 output = -1 ev = bsearch(input, key) if output == ev: return True, None else: return False, "Second Key Error" def test_bsearch(): status, message = test_bsearch1() if status == False: return status, message status, message = test_bsearch2() if status == False: return status, message return True, None def test(method_name): state = False if method_name == "reverse": state, message = test_reverse() if not state: return "FAIL", message if method_name == "bsearch": state, message = test_bsearch() if not state: return "FAIL", message if method_name == "mergesort": state, message = test_mergesort() if not state: return "FAIL", message if state: return "SUCCESS" else: return "FAIL" print test('mergesort')
076e692318b4c368c0cb43d33a0bc5dea670ffdf
julie98/Python-Crash-Course
/chapter_9/dice.py
406
3.53125
4
from random import randint class Die(): def __init__(self,sides = 6): self.sides = sides def roll_die(self): return randint(1, self.sides) results = [] die_one = Die(10) for roll_number in range(10): result = die_one.roll_die() results.append(result) print(results) results = [] die_two = Die(20) for roll_number in range(20): result = die_two.roll_die() results.append(result) print(results)
d0269081fa81fbf2e95500754dc5d370ec5d5b89
ZhiyuSun/leetcode-practice
/practice/practice.py
1,206
3.53125
4
#!/usr/bin/python # -*- coding: utf-8 -*- class Solution(object): def find_next_node(self, current_position, step): master = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20, 21,22,23,24,25,31,32,33,1] branch = [26,27,28,29,30] if current_position == 19 and step > 0: return branch[step-1] if current_position == 25 and step < 0: return branch[step+5] if 26 <= current_position <= 30: if 0 <= branch.index(current_position)+step <= 4: return branch[branch.index(current_position)+step] else: return master[19+branch.index(current_position)+step] return master[(master.index(current_position) + step) % 28] solution = Solution() print solution.find_next_node(1,4) print solution.find_next_node(5, -4) # 1 print solution.find_next_node(17, 5) # 22 print solution.find_next_node(19, 2) # 27 print solution.find_next_node(27, -3) # 18 print solution.find_next_node(30, 3) # 32 print solution.find_next_node(32, -4) # 23 print solution.find_next_node(25, -2) # 29 print solution.find_next_node(33, 3) # 3 print solution.find_next_node(1, -2) # 32
55a943281093be07a7a6224f702b4ec0cc734ea5
methane/gdd11
/hitori/hitori.py
1,186
3.796875
4
#!/usr/bin/env python # coding: utf-8 # ただの深さ優先探索. # 無限ループしないように、 /2 操作で変化がない場合を切る. def read_input(): problem = [] with open('input.txt', 'r') as f: N = int(f.readline().strip()) i = 0 while True: l = f.readline().strip() if not l: if i != N: raise Exception("Can't read N problems.") return problem k = int(l) l = f.readline().strip() p = map(int, l.split()) assert k == len(p) problem.append(p) i += 1 def op_x(n): return [i//2 for i in n] def op_y(n): return [i for i in n if i%5!=0] def solve(numbers): if not numbers: return 0 x = op_x(numbers) if x == numbers: # They're all 0 return 1 xstep = solve(x) y = op_y(numbers) if not y: return 1 if y == numbers: return xstep+1 ystep = solve(y) return min(xstep, ystep) + 1 def main(): problems = read_input() for p in problems: print solve(p) if __name__ == '__main__': main()
3a2d54737ae39ab4ab6f1b086895865dab6b625c
ny1103/USTC
/leetcode-plugin/cn/[4]寻找两个有序数组的中位数.py
2,062
3.734375
4
# -*- coding: utf-8 -*- # 给定两个大小为 m 和 n 的有序数组 nums1 和 nums2。 # # 请你找出这两个有序数组的中位数,并且要求算法的时间复杂度为 O(log(m + n))。 # # 你可以假设 nums1 和 nums2 不会同时为空。 # # 示例 1: # # nums1 = [1, 3] # nums2 = [2] # # 则中位数是 2.0 # # # 示例 2: # # nums1 = [1, 2] # nums2 = [3, 4] # # 则中位数是 (2 + 3)/2 = 2.5 # for循环遍历两个列表失败—— ValueError: too many values to unpack # nums1, = [3, 4, 6, 7, 8, 11] # nums2, = [2, 5, 9, 12, 17, 20] # https://blog.csdn.net/hehedadaq/article/details/81836025 """ 在pyhon3中/是真除法。 3/2=1.5 如果想在python3使用地板除,是// 3//2=1 7 // 2=3 %表示求余数 5%2=1 " / " 就表示 浮点数除法,返回浮点结果; " // " 表示整数除法。 """ class Solution: def findMedianSortedArrays(self, nums1, nums2): """ :type nums1: List[int] :type nums2: List[int] :rtype: float """ def findKth(A, B, k): if len(A) == 0: return B[k - 1] if len(B) == 0: return A[k - 1] if k == 1: return min(A[0], B[0]) a = A[k // 2 - 1] if len(A) >= k // 2 else None b = B[k // 2 - 1] if len(B) >= k // 2 else None if b is None or (a is not None and a < b): return findKth(A[k // 2:], B, k - k // 2) return findKth(A, B[k // 2:], k - k // 2) # 这里要注意:因为 k/2 不一定 等于 (k - k/2) n = len(nums1) + len(nums2) if n % 2 == 1: return findKth(nums1, nums2, n // 2 + 1) else: smaller = findKth(nums1, nums2, n // 2) bigger = findKth(nums1, nums2, n // 2 + 1) return (smaller + bigger) / 2.0 nums1 = [3, 4, 6, 7, 8, 11, 13] nums2 = [2, 5, 9, 12, 17, 20, 22] solution = Solution() print(solution.findMedianSortedArrays(nums1, nums2))
e462fa37aacc83108b2489e4cf116542abff5c1a
hmnathel/nyc-mhtn-ds-071519-lectures
/week-1/Calculator.py
1,584
3.5625
4
# -*- coding: utf-8 -*- """ Spyder Editor This is a temporary script file. """ import math class Calculator: def __init__(self, data): assert all(isinstance(x, (int, float)) for x in data), "list can only be numbers" self.data = data self.__update() def __update(self): self.length = len(self.data) self.mean = self.__calc_mean() self.median = self.__calc_median() self.variance = self.__calc_var() self.standev = self.__std_dev() def __calc_mean(self): mean = sum(self.data)/len(self.data) return mean def __calc_median(self): srt_data = sorted(self.data) length = len(srt_data) half_length = int(len(srt_data)/2) med_int = int((half_length)+0.5) if length%2 == 0: median = (srt_data[half_length]+srt_data[half_length-1])/2 else: median = srt_data[med_int] return median def __calc_var(self): diff_square = [] for x in self.data: diff_square.append((x - self.mean)**2) return sum(diff_square)/(len(self.data) - 1) def __std_dev(self): return math.sqrt(self.variance) def add_data(self, new_data): if type(new_data) == list: self.data.extend(new_data) else: self.data.append(new_data) self.__update() def remove_data(self, to_be_removed): return self.data.remove(to_be_removed) self.__update()
9261365e4726614ac27f96caa7fb15f39e3ffa37
Giantcatasaurus/All-my-projects
/Quiz.py
838
3.9375
4
a = 0 print("Hi! I am Quiz-Bot. Initializing quiz...") print("If there are any word answers, capitalize it.") answer1 = input("What is 1 + 1? ") if answer1 == "2": print("Correct!") a = a + 1 else: print("Wrong!") answer2 = input("What is 1 + 4? ") if answer2 == "5": print("Correct!") a = a + 1 else: print("Wrong!") answer3 = input("What is my name? ") if answer3 == "Quiz-Bot": print("Correct!") a = a + 1 else: print("Wrong!") answer4 = input("What lanquage is this? ") if answer4 == "Python": print("Correct!") a = a + 1 else: print("Wrong!") answer5 = input("Is this a cool program? ") if answer5 == "Yes": print("Correct!") a = a + 1 else: print("Wrong!") print ("You got", a, "/5") if a == 5: print("Perfect!") if a == 0: print("You're not great at this...")
44708e742eccc8312fb712a9005d0bd8676b4202
MarcosLazarin/Curso-de-Python
/ex049b.py
256
3.96875
4
#Refazer o ex009, mostrando a tabuada de um número que o usuário escolher, só que agora utilizando o laço FOR. n = int(input('Digite um número que você queira saber a tabuada: ')) for a in range(1, 11): print('{} x {} = {}'.format(n, a, n * a))
fa64141ea139a1e457bbf94956ea9957651b2967
e1four15f/python-intro
/lesson2/ExC.py
132
4
4
n = int(input()) def factorial(n): curr = 1; for i in range(1, n+1): curr *= i return curr print(factorial(n))
963418ba1d8f9a76a80b01c765c38ab363891e36
NHlaing/Programming_Basic_With_Python
/Chapter2/Area.py
231
4.28125
4
#READ height of rectangle #READ width of rectangle #COMPUTE area as height times width height = input("Enter Height Of Rectangle: ") width = input("Enter Width Rectangle: ") area = int(height) * int(width) print("Area is ", area)
9b0d7d8a9ba5fde81ca5b2bb4a24927404d8043d
zoomie/algorithms_practise
/python/stack.py
469
3.8125
4
class Stack: def __init__(self, first_element): self.data = [] self.current_min = first_element def add(self, item: int): if item < self.current_min: self.current_min = item self.data.append(item) def pop(self) -> int: return self.data.pop() def min_(self) -> int: return self.current_min stack = Stack(0) stack.add(1) stack.add(2) print(stack.min_()) # -> 0 print(stack.pop()) # -> 2
4e7f7bdf3ee0e028460b65a204cddc20492b40c5
tanyinqing/Python_20170902
/h11/h11_shape.py
751
3.84375
4
class Shape(object): def area(self): print('in shape:area...') pass def perimeter(self): print('in Shape:perimeter...') pass class Circle(Shape): def area(self): print('in Circle:area...') # 继承父类 class Square(Shape): def print_info(self): print('a new def in Square...') class Triangle(Shape): def area(self): print('in Triangle:area...') class Rectangle(Shape): def area(self): print('in Rectangle:area...') def perimeter(self): print('in Rectangle:perimeter..') a_triangle=Triangle() a_triangle.area() a_circle=Circle(); a_square=Square(); a_circle.area() a_circle.perimeter() a_square.area() a_square.perimeter() a_square.print_info()
dcc136f8079cefa4581e841cffba3ca6a115e94e
bhavaniravi/caching-in-python
/lru_caching_example/lru_caching.py
902
3.75
4
from functools import lru_cache # 1. A simple example @lru_cache(maxsize=32) def add(a, b): return a + b numbers = [(1, 2), (2, 3), (3, 4), (1, 2), (1, 2)] [add(a, b)for a, b in numbers] print (add.cache_info()) # 2. Cache invalidation example a = [10, 11, 12, 13, 14, 15, 16] @lru_cache(maxsize=32) def get_item(i): global a return a[i] for index, i in enumerate([1, 1, 1, 3, 4, 1, 1]): if index == 5: a[i] = 99 get_item.cache_clear() print (index, i, get_item(i)) print (get_item.cache_info()) # 3. Caching on non-deterministic inputs from datetime import datetime a = [10, 10, 10, 10, 10, 10, 1000] @lru_cache(maxsize=32) def get_item(i): global a dt = datetime.now() if dt.microsecond/2 == 0: return a[6] return a[i] for index, i in enumerate(a): print (index, i, get_item(index)) print (get_item.cache_info())
10d65e3a11418067f820ac524984cff643066205
havu73/discoverHomomorphisms
/word.py
9,647
3.734375
4
import letter import root_list import copy class Word: def create_root_list(): a=letter.Letter("a",1) b=letter.Letter("b",1) c=letter.Letter("c",1) d=letter.Letter("d",1) A=letter.Letter("a",-1) B=letter.Letter("b",-1) C=letter.Letter("c",-1) D=letter.Letter("d",-1) root=root_list.RootList([],0) root.add_last(a) root.add_last(b) root.add_last(A) root.add_last(B) root.add_last(c) root.add_last(d) root.add_last(C) root.add_last(D) root_inv=root_list.RootList([],0) root_inv.add_last(d) root_inv.add_last(c) root_inv.add_last(D) root_inv.add_last(C) root_inv.add_last(b) root_inv.add_last(a) root_inv.add_last(B) root_inv.add_last(A) return [root,root_inv] root_list=create_root_list() ROOT=root_list[0] ROOT_INV=root_list[1] def __init__(self,l): self.list=l def append_letter(self,l): if l.is_trivial(): pass if len(self.list)==0: self.list.append(l) else: if self.list[len(self.list)-1].compare_letter(l): to_add=self.list[len(self.list)-1].sum(l) if not (to_add.is_trivial()): self.list[len(self.list)-1]=to_add else: self.list=self.list[:-len(self.list)] else: self.list.append(l) def append_word(self,w): if len(self.list)==0: self.list=copy.deepcopy(w.list) elif len(w.list)==0: pass else: cont=True while(len(w.list)!=0 and len(self.list)!=0 and cont): if self.list[len(self.list)-1].compare_letter(w.list[0]): new_letter=self.list[len(self.list)-1].sum(w.list[0]) if not new_letter.is_trivial(): self.list[len(self.list)-1]=new_letter del w.list[0] else: del w.list[0] del self.list[len(self.list)-1] else: cont=False if len(w.list)!=0: self.list.extend(w.list) del w def append_letter_return_new(self,let): result=Word([]) result.append_word(copy.deepcopy(self)) result.append_letter(let) return result def append_word_return_new(self,w): result=Word([]) result.append_word(copy.deepcopy(self)) result.append_word(w) return result def clear(self): del self.list[:] def append_reduced_word(self,temp,current_root,start_index): new_temp=self.find_dehn_inverse(temp, current_root, start_index) self.append_word(new_temp) def dehn_inverse_assist(self,current_root,start_index,length): result=Word([]) i=0 while i<length: index=(start_index+8-i-1)%8 new =current_root.get(index).find_inverse() result.append_letter(new) i+=1 return result def find_dehn_inverse(self,temp, current_root, start_index): result=Word([]) if len(temp.list)<4: return temp elif len(temp.list)>4: length=8-len(temp.list) result=self.dehn_inverse_assist(current_root,start_index,length) return result else: if current_root.equals(Word.ROOT_INV): result=self.dehn_inverse_assist(current_root,start_index,4) return result else: return temp def __str__(self): result="" for let in self.list: result+= let.__str__()+" " return result def is_identity(self): test=self.reduce() del self return len(test.list)==0 def compare_to_reduced(self,other): new_this=self.reduce() new_other=other.reduce() if len(new_this.list)!=len(other.list): return False elif (new_this.is_identity() and new_other.is_identity()): return True else: result=True for i in range (len(new_this.list)): if not (new_this.list[i].compare_to(new_other.list[i])): result=False break return result def reduce(self): if (len(self.list)==0):return self else: current_root=None temp=Word([]) result=Word([]) start_index=None for i in range(len(self.list)): let=self.list[i] if i==0: temp.append_letter(let) continue if (let.is_single()): if(current_root!=None): if(let.compare_to(current_root.next())): temp.append_letter(let) if(i==len(self.list)-1): result.append_reduced_word(temp, current_root,start_index) else: continue else: result.append_reduced_word(temp,current_root,start_index) temp.clear() if i==len(self.list): result.append_letter(let) else: temp.append_letter(let) current_root=None start_index=None continue else: Word.ROOT.update_pointer(temp.list[0]) Word.ROOT_INV.update_pointer(temp.list[0]) if (let.compare_to(Word.ROOT.next())): current_root=Word.ROOT temp.append_letter(let) start_index=Word.ROOT.get_current_index()-1 if (i==len(self.list)-1): result.append_word(temp) temp.clear else: continue elif (let.compare_to(Word.ROOT_INV.next())): current_root=Word.ROOT_INV temp.append_letter(let) start_index=Word.ROOT_INV.get_current_index()-1 if (i==len(self.list)-1): result.append_word(temp) temp.clear else: continue else: if(i==len(self.list)-1): result.append_word(temp) result.append_letter(let) temp.clear() else: result.append_word(temp) temp.clear() temp.append_letter(let) current_root=None start_index=None continue else: head=let.find_head_tail() middle=let.find_middle() tail=let.find_head_tail() if(current_root!=None): if(head.compare_to(current_root.next())): temp.append_letter(head) result.append_reduced_word(temp,current_root,start_index) result.append_letter(middle) temp.clear() current_root=None start_index=None temp.append_letter(tail) else: result.append_reduced_word(temp, current_root,start_index) result.append_letter(head) result.append_letter(middle) temp.clear() current_root=None start_index=None temp.append_letter(tail) if(i==len(self.list)-1): result.append_word(temp) else: continue else: result.append_word(temp) temp.clear() result.append_letter(head) result.append_letter(middle) temp.append_letter(tail) if(i==len(self.list)-1): result.append_letter(tail) temp.clear() else: continue return result def find_inverse(self): result=Word([]) for i in range (len(self.list)): let=self.list[len(self.list)-1-i] result.append_letter(let.find_inverse()) return result def sum_exp(self): result=0 for let in self.list: result+=abs(let.exp) return result
cb3b153fea4f0e6d0a92c235e4c14e6dd4846724
Laurasoto98/TicTacToe
/tic_tac_toe_random.py
5,189
4.0625
4
""" Course: Python for Scientist (Part-I) """ #%% def author(): return 'Laura Soto' #%% import random import copy # %% def DrawBoard(Board): rows=len(Board) columns=len(Board[0]) if rows!=3 or columns!=3: print('No valid') print(' --+--+--') for i in range(0,rows): for j in range(0,columns): print('|',Board[i][j], end='') print('|''\n --+--+--') #%% def IsSpaceFree(Board, i ,j): try: if Board[i][j] == ' ': return True else: return False except: return False #%% def GetNumberOfChessPieces(Board): num=0 for i in range(len(Board)): for j in range(len(Board)): if Board[i][j]=='X' or Board[i][j]=='O': num+=1 return num #%% def IsBoardFull(Board): num = GetNumberOfChessPieces(Board) if num == 9: return True else: return False #%% def IsBoardEmpy(Board): num = GetNumberOfChessPieces(Board) if num == 0: return True else: return False #%% def UpdateBoard(Board, Tag, Choice): i=Choice[0] j=Choice[1] Board[i][j]=Tag #%% def HumanPlayer(Tag, Board): print('Please enter the row and column:') choice=[0,0] while True: row=int(input('Row: ')) column=int(input('Colum:')) if type(row)==int and type(column)==int: if row > 3 or column > 3 or row < 0 or column < 0: print('This position is invalid, please choose another spot:') elif IsSpaceFree(Board, row, column)==False: print('This position is occupied, please choose another spot:') else: choice[0]=row choice[1]=column break else: print("Error. Please input a valid number") return choice #%% def ComputerPlayerRandom(Tag, Board): choice=[0,0] while True: randRow=random.randint(0,2) randCol=random.randint(0,2) if IsSpaceFree(Board,randRow,randCol): choice[0]=randRow choice[1]=randCol break return choice #%% def Judge(Board): if Board[0]==['X', 'X','X'] or Board[1]==['X', 'X','X'] or Board[2]==['X', 'X','X'] or [Board[0][0],Board[1][0],Board[2][0]]==['X', 'X','X'] or [Board[0][1],Board[1][1],Board[2][1]]==['X', 'X','X'] or [Board[0][2],Board[1][2],Board[2][2]]==['X', 'X','X'] or [Board[0][0],Board[1][1],Board[2][2]]==['X', 'X','X'] or [Board[0][2],Board[1][1],Board[2][0]]==['X', 'X','X']: return 1 elif Board[0]==['O', 'O','O'] or Board[1]==['O', 'O','O'] or Board[2]==['O', 'O','O'] or [Board[0][0],Board[1][0],Board[2][0]]==['O', 'O','O'] or [Board[0][1],Board[1][1],Board[2][1]]==['O', 'O','O'] or [Board[0][2],Board[1][2],Board[2][2]]==['O', 'O','O'] or [Board[0][0],Board[1][1],Board[2][2]]==['O', 'O','O'] or [Board[0][2],Board[1][1],Board[2][0]]==['O', 'O','O']: return 2 elif IsBoardFull(Board): print("Full board") return 3 else: return 0 #%% def ShowOutcome(Outcome, NameX, NameO): print("Outcome:", Outcome) if Outcome==0: print('The game is still in progress') elif Outcome==1: print('The winner is ', NameX, '!') elif Outcome==2: print('The winner is ', NameO, '!') elif Outcome==3: print('Its a tie') #%% read but do not modify this function def Which_Player_goes_first(): if random.randint(0, 1) == 0: print("Computer player goes first") PlayerX = ComputerPlayerRandom PlayerO = HumanPlayer else: print("Human player goes first") PlayerO = ComputerPlayerRandom PlayerX = HumanPlayer return PlayerX, PlayerO #%% the game def TicTacToeGame(): #--------------------------------------------------- print("Wellcome to Tic Tac Toe Game") Board = [[' ', ' ', ' '], [' ', ' ', ' '], [' ', ' ', ' ']] DrawBoard(Board) # determine the order PlayerX, PlayerO = Which_Player_goes_first() # get the name of each function object NameX = PlayerX.__name__ NameO = PlayerO.__name__ while True: ChoiceX=PlayerX('X',Board) UpdateBoard(Board, 'X', ChoiceX) DrawBoard(Board) Outcome=Judge(Board) ShowOutcome(Outcome, NameX, NameO) if Outcome!=0: break else: ChoiceO=PlayerO('O',Board) UpdateBoard(Board, 'O', ChoiceO) DrawBoard(Board) Outcome=Judge(Board) ShowOutcome(Outcome, NameX, NameO) if Outcome!=0: break #%% play the game many rounds until the user wants to quit # read but do not modify this function def PlayGame(): while True: TicTacToeGame() print('Do you want to play again? (yes or no)') if not input().lower().startswith('y'): break print("GameOver") #%% do not modify anything below if __name__ == '__main__': PlayGame()
9af4a1c052bd492b2a268032cc794681ec423062
matiasmasca/python
/ucp_intro/031_strings.py
2,144
4.4375
4
frase = "Curso de Python" print(frase) # Es posible realizar operaciones con cadenas. Por ejemplo, podemos "sumar" cadenas añadiendo una a otra. Esta operación no se llama suma, sino concatenación y se representa con el signo +. # Concatenación print(frase + " esta muy bueno") print("muy " + "pero " + "muy " + "bueno!") # Repetición # podemos repetir una misma cadena un ciertno numero de veces con el signo * print("Esto es una prueba. " * 3) # funciones/métodos para cadenas # Los métodos son funciones adjuntas a un valor. Por ejemplo, todos los valores de cadena tienen el método lower(), el cuál devuelve una copia de la cadena en minúsculas. print(frase.lower()) # convertir a minusculas print(frase.upper()) # convertir a MAYUSCULAS print(frase.isupper()) # esta todo en mayusculas? print(frase.upper().isupper()) # podemos convinar funciones print(len(frase)) # cantidad de caracteres de la cadena print(frase[0]) # caracter por indice en la cadena print(frase[0] + frase[6] + frase[9]) # iniciales por indice en la cadena print(frase.index("C")) print(frase.replace("Python", "Ruby")) # remplazar una cadena dentro de otra # Caracteres # Cuando se comparan cadenas, Python va a usar la tabla ASCII para definir quien esta primero. # con la funcion ORD nos devuelve el nro. de orden de ese caracter en la tabla print(ord('a')) # 97 print(chr(64)) # @ print(chr(241)) # ñ print("abajo" < "arriba") """ La tabla ASCII presenta un problema cuando queremos ordenar palabras: las letras mayúscu- las tienen un valor numérico inferior a las letras minúsculas (por lo que ’Zapata’ precede a ’ajo’) y las letras acentuadas son siempre ((mayores)) que sus equivalentes sin acentuar (’aba- nico’ es menor que ’ábaco’). Hay formas de solucionar eso, pero ya es otra historia. """ # Cadenas Multi-Línea """ Hasta ahora todas las cadenas han sido de una sola línea y tenían un carácter de comillas al principio y al final. Sin embargo, si utiliza comillas triples al comienzo y al final entonces la cadena puede ir a lo largo de varias líneas """ print(""" una cadena de varias lineas""")
9caa89350a0bf56232a9936a28813aa06752caac
ravinaNG/python
/Function/check_element.py
632
4.09375
4
def check_numbers(number1, number2): print " << Of integer >> " if(number1 % 2 == 0 and number2 % 2 == 0): print "Both numbers are even." else: print "Both numbers are not even." print "--------------------------------------" check_numbers(12, 13) def check_numbers_list(list1, list2): length = len(list1) a = 0 print "<< Element of list >> " while (a < length): if(list1[a] % 2 == 0 and list2[a] % 2 == 0): print "Both numbers are even." else: print "Both numbers are not even." print "---------------------------------------" a = a + 1 check_numbers_list([2, 6, 18, 10, 3, 75], [6, 19, 24, 12, 3, 87])
fe654a74c36bf234ee0d07b1084df37c0f6fd48b
DanielleRenee/python_practices
/danielle-oo.py
3,091
4.25
4
class Book(object): """A Book Object.""" def __init__(self, title, author, pub_yr='Unknown'): self.title = title self.author = author self.pub_yr = pub_yr def __repr__(self): return '<Book. Title: %s.>' % (self.title) class Library(object): """A collection of book objects.""" def __init__(self): self.books = [] def __repr__(self): print '<Library containing %s book(s).>' % (len(self.books)) #Read up a bit more on dunder repr, notes for self: #A __repr__ method takes exactly one parameter, self, and must return a string. #This string is intended to be a representation of the object, #suitable for display to the programmer, #for instance when working in the interactive interpreter. __repr__ #will be called anytime the builtin repr function is applied to an object; #this function is also called when the backquote operator is used. def list_books(self): """List all the books in the library.""" if len(self.books) == 0: print "Library is empty." return for book in self.books: print book.title print ' Author:', book.author print ' Published:', book.pub_yr print def add_book(self, book): """Add a book to the library.""" if not isinstance(book, Book): raise Exception('Please enter a Book Object to add to the library') self.books.append(book) print 'Added: {} by {}.'.format(book.title, book.author) def empty_library(self): """Remove all books from the library.""" #if a library calls the empty_library method, clear all items from the library #tried clear method from python book, but found out clear wasn't added until 3.3 #self.books.clear() #per stack overflow, searched for error message, used del instead #https://stackoverflow.com/questions/32055768/python3-attributeerror-list-object-has-no-attribute-clear del self.books[:] print "Library deleted!" ########### WRITE YOUR SCRIPT HERE # Details on what the script should include are in the skills assessment # instructions. the_bell_jar = Book("The Bell Jar", "Sylvia", 1963) # the_bell_jar.title = "The Bell Jar" # the_bell_jar.author = "Sylvia Plath" # the_bell_jar.pub_yr = 1963 anna_karenina = Book("Anna Karenina", "Leo Tolstoy") # anna_karenina.title = "Anna Karenina" # anna_karenina.author = "Leo Tolstoy" # anna_karenina.pub_yr = "Unknown" #sunday = Library() #sunday.list_books = bound method Library.list_books of <Library containing 0 book(s)> #sunday.add_book(the_bell_jar) #= Added: The Bell Jar #sunday.add_book(anna_karenina) #= Added: Anna Karenina #sunday.list_books() = # The Bell Jar # Author: Sylvia # Published: 1963 # Anna Karenina # Author: Leo Tolstoy # Published: Unknown #sunday.empty_library() = Library deleted! #sunday.list_books() = Library is empty. #update the method add book. #sunday.add_book(the_bell_jar) = Added: The Bell Jar by Sylvia.
9421a1937eca823adf0f2384d9f8e9304189a00a
kevinktom/Advent-of-Code-2020
/Day 16/ticket_translation.py
5,737
3.578125
4
def create_input_array(): filepath = 'input.txt' input_numbers = [] with open(filepath) as fp: lines = fp.readlines() cnt = 0 group = [] for line in lines: if line == "\n" and group: input_numbers.append(group) group = [] continue item = line.strip() group.append(item.split()) # group += item.split() input_numbers.append(group) return input_numbers input_numbers = create_input_array() # print(input_numbers[2]) import collections # def reformat_input_array(input_numbers): # input_object = collections.defaultdict(list) # # Fields # for i in range(len(input_numbers[0])): # field = input_numbers[0][i] # first_interval = field[-3].split('-') # first_interval[0] = int(first_interval[0]) # first_interval[1] = int(first_interval[1]) # second_interval = field[-1].split('-') # second_interval[0] = int(second_interval[0]) # second_interval[1] = int(second_interval[1]) # input_object['fields'].append(first_interval) # input_object['fields'].append(second_interval) # input_object['fields'] = sorted(input_object['fields'], key = lambda x: (x[0], x[1])) # input_object['fields'] = merge_intervals(input_object['fields']) # # your_ticket # your_ticket_numbers = input_numbers[1][1][0].split(',') # your_ticket_numbers = list_elements_to_int(your_ticket_numbers) # input_object['your_ticket'] = your_ticket_numbers # # nearby_tickets # nearby_tickets = [] # for i in range(1, len(input_numbers[2])): # arr = input_numbers[2][i][0].split(',') # arr = list_elements_to_int(arr) # nearby_tickets += arr # input_object['nearby_tickets'] = nearby_tickets # return input_object # Part Two reformat def reformat_input_array(input_numbers): input_object = collections.defaultdict(list) # Fields for i in range(len(input_numbers[0])): field = input_numbers[0][i] first_interval = field[-3].split('-') first_interval[0] = int(first_interval[0]) first_interval[1] = int(first_interval[1]) second_interval = field[-1].split('-') second_interval[0] = int(second_interval[0]) second_interval[1] = int(second_interval[1]) both_intervals = sorted([first_interval, second_interval], key = lambda x: (x[0], x[1])) both_intervals = merge_intervals(both_intervals) input_object['fields'].append(both_intervals) # your_ticket your_ticket_numbers = input_numbers[1][1][0].split(',') your_ticket_numbers = list_elements_to_int(your_ticket_numbers) input_object['your_ticket'] = your_ticket_numbers # nearby_tickets nearby_tickets = [] for i in range(1, len(input_numbers[2])): arr = input_numbers[2][i][0].split(',') arr = list_elements_to_int(arr) nearby_tickets.append(arr) input_object['nearby_tickets'] = nearby_tickets # print(input_object['nearby_tickets']) return input_object def list_elements_to_int(arr): for i in range(len(arr)): arr[i] = int(arr[i]) return arr def merge_intervals(intervals): merged = [] for interval in intervals: if not merged: merged.append(interval) else: prev = merged[-1] if interval[0] > prev[1]: merged.append(interval) else: merged[-1][1] = max(interval[1], prev[1]) return merged # print(reformat_input_array(input_numbers)) # print(reformat_input_array(input_numbers)['fields']) # test = (reformat_input_array(input_numbers)) # print(merge_intervals(test['fields'])) def within_interval(intervals, num): for interval in intervals: left = interval[0] right = interval[1] if left <= num <= right: return True return False def find_ticket_scanning_error_rate(input_numbers): input_object = reformat_input_array(input_numbers) # input_object = {'fields': [[[0, 1], [4,19]], [[0,5], [8,19]], [[0,13], [16,19]]], # 'nearby_tickets': [[3,9,18], [15,1,5], [5,14,9]] # } field_idx_to_ticket_idx = {} all_intervals = input_object['fields'] all_tickets = input_object['nearby_tickets'] # your_ticket = input_object['your_ticket'] # print(your_ticket) for i in range(len(all_intervals)): intervals = all_intervals[i] for col in range(len(all_tickets[0])): not_in_this_col = False for row in range(len(all_tickets)): # print(row, col) # if all_tickets[row][col] == 9: # print(all_tickets[row][col], all_intervals[i]) if not within_interval(all_intervals[i], all_tickets[row][col]): # print(all_intervals[i], all_tickets[row][col]) # print(within_interval(all_intervals[i], all_tickets[row][col])) not_in_this_col = True break if not_in_this_col: continue else: field_idx_to_ticket_idx[i] = col break return field_idx_to_ticket_idx # intervals = input_object['fields'] # nearby_tickets = input_object['nearby_tickets'] # ticket_scanning_error_rate = 0 # for ticket_num in nearby_tickets: # in_interval = within_interval(intervals, ticket_num) # if not in_interval: # ticket_scanning_error_rate += ticket_num # return ticket_scanning_error_rate print(find_ticket_scanning_error_rate(input_numbers))
0d5c3fc94c5e462609b24bff0cf25137c20b03b6
Janepoor/Python-Practice-
/sample2.py
1,590
3.609375
4
'''input IBM cognitive computing|IBM "cognitive" computing is a revolution|IBM cognitive computing| 'IBM Cognitive Computing' is a Revolution? "Computer Science Department"|Computer-Science-Department"|the "computer science department" ''' import string input1=' IBM cognitive computing |IBM "cognitive" computing is a revolution|IBM cognitive computing| \'IBM Cognitive Computing\' is a Revolution?' input2='"Computer Science Department"|Computer-Science-Department"|the "computer science department"' onearray=input2.split('|') secondarray=[] for i in onearray: i = i.lower() # all in the lower case i = i.lstrip() #delete the whitespace i = i.rstrip() #delete the whitespace i = ' '.join(i.split()) # delete extra space i= ''.join([k for k in i if k.isalpha()or k==' ']) # remove non-alphanumeric if i not in secondarray: secondarray.append(i) else: i=i+str(1) secondarray.append(i) print secondarray dictionary=dict(zip(secondarray,onearray)) ######################################################### for m in secondarray: for n in secondarray: if (n.rstrip('1') in m.rstrip('1')): if n.rstrip('1')== m.rstrip('1'): if len(dictionary[n])> len(dictionary[m]): secondarray.remove(n) elif secondarray.index(m)<secondarray.index(n): secondarray.remove(n) else: ##not equal secondarray.remove(n) print secondarray output = '|'.join([dictionary[k] for k in secondarray ]) print output
9da82081778ca244fe0bf755838a6e1259aceeb2
Constantine19/cs265-fall-2017
/assn4/accounts
5,597
3.765625
4
#!/usr/bin/python ''' CS 265 Assignment 4 Author: Konstantin Zelmanovich Date: 12/11/2017 Description: This is a command-line utility that lists bank account information and transactions such as deposits and withdrawals Platform: Python 2.7.12 on tux4.cs.drexel.edu ''' import os import sys from datetime import date # Defining classes class Transaction: def __init__(self, operation, date, amount): self.operation = operation self.date = date self.amount = amount return class Account: def __init__(self, account_id, name): self.account_id = account_id self.name = name self.balance = 0 self.transactions = [] return # function to def add_transaction(self, transaction): self.transactions.append(transaction) if transaction.operation == "W" or "w": self.balance = self.balance - transaction.amount else: self.balance = self.balance + transaction.amount return def __repr__(self): return repr((self.name, self.balance, self.account_id)) def output_for_file(self): output = '' for transaction in self.transactions: output = output + self.account_id + ":" + self.name + ":" + transaction.date + ":" + transaction.operation + ":" + str(transaction.amount) + "\n" return output # Defining methods def account_sort(): sorted_account_ids = sorted(accounts, key= lambda account_id:accounts[account_id].name) return sorted_account_ids def account_print(): sorted_account_ids = account_sort() count = 0 for i in sorted_account_ids: count += 1 print str(count) + ')' + accounts[i].name + " " + accounts[i].account_id print 'q)uit\n' return sorted_account_ids def account_select(): current_account = raw_input('Enter choice => ' ).strip() if current_account == 'q': exit(0) return int(current_account) - 1 def account_select_for_inset(): current_account = raw_input('Enter choice or type "n" to create a new account => ').strip() if current_account == 'n': account_create() return int(len(accounts.keys())) - 1 else: if current_account == 'q': exit(0) return int(current_account) - 1 def account_create(): account_id = raw_input('Enter account ID:' ).strip() if account_id in accounts.keys(): print "This account ID cannot be used twice" exit(1) name = raw_input('Enter account name:').strip() accounts[account_id] = Account(account_id, name) sorted_account_ids.append(account_id) return def date_form(): t = date.today().timetuple() year = str(t[0])[2:] month = '' if len(str(t[1])) == 1: month = '0' + str(t[1]) else: month = str(t[1]) day = '' if len(str(t[2])) == 1: day = '0' + str(t[2]) else: day = str(t[2]) return year + "." + month + "." + day def insert_operation(): operation = raw_input("Enter the Operation (w - withdrawal ; d - deposit): ").strip() amount = float(raw_input("Enter the amount: ")) accounts[sorted_account_ids[current_account]].add_transaction(Transaction(operation.capitalize(), date_form(), amount)) def account_details(): print '\n\t account #: ' + accounts[sorted_account_ids[current_account]].account_id print '\t name: ' + accounts[sorted_account_ids[current_account]].name print '\t balance: ' + str(accounts[sorted_account_ids[current_account]].balance) + '\n' raw_input("Press Enter to go back") return def account_history(): for transaction in accounts[sorted_account_ids[current_account]].transactions: if transaction.operation == "W": print transaction.date + " withdrawal in the amount of " + str(transaction.amount) else: print transaction.date + " deposit in the amount of " + str(transaction.amount) return def usage(): print "-i Account info" print "-h History" print "-t Insert transaction" print "-? Show usage msg and quit" def save_to_file(): data = '' for account in accounts: data = data + accounts[account].output_for_file() with open('tmp','w') as f: f.write(data) os.rename('tmp',path) return # Defining global variables accounts = {} sorted_account_ids = [] current_account = None insert_new_account = False path = os.environ.get('ACCT_LIST') if path == None: path = "sample.log" with open("test.txt", 'r') as f1: for line in f1: form_line = line.strip(); line_info = form_line.split(':') transaction = Transaction(line_info[3], line_info[2], float(line_info[4])) if line_info[0] not in accounts.keys(): accounts[line_info[0]] = Account(line_info[0], line_info[1]) accounts[line_info[0]].add_transaction(transaction) # checking the validity of arguments if(len(sys.argv) > 1): if sys.argv[1].strip() == "-?": usage(); exit(0) while 1: if sys.argv[1].strip() == "-i": sorted_account_ids = account_print() current_account = account_select() account_details() if sys.argv[1].strip() == "-h": sorted_account_ids = account_print() current_account = account_select() account_history() if sys.argv[1].strip() == "-t": sorted_account_ids = account_print() current_account = account_select_for_inset() insert_operation() save_to_file() else: usage()
541c4d146cd22c9b19e0a6fe03379a7a6d6d78de
IamJenver/mytasksPython
/follow_rules.py
590
3.796875
4
# На вход программе подается натуральное число n. Напишите программу, # которая выводит числа от 1 до n включительно за исключением: # чисел от 5 до 9 включительно; # чисел от 17 до 37 включительно; # чисел от 78 до 87 включительно. n = int(input()) for i in range(1, n + 1): if 5 <= i <= 9 or 17 <= i <= 37 or 78 <= i <= 87: continue # переходим на следующую итерацию print(i)
76ce336f19035f376335c517f261f64d9eff0fdd
imgomez0127/daily-programming
/algorithm-implementations/segmented_sieve.py
820
3.53125
4
import math def sieve(a, b): is_prime = [not (i in (0, 1)) for i in range(int(b**0.5)+1)] high_primes = [True for _ in range(b-a+1)] for i in range(int(b**0.25)+1): if is_prime[i]: for j in range(i**2,int(b**0.5)+1,i): is_prime[j] = False low_primes = [i for i,primality in enumerate(is_prime) if primality] for p in low_primes: i = math.ceil(a/p)*p-a if a <= p: i = i + p for j in range(i,len(high_primes),p): high_primes[j] = False for i,prime in enumerate(high_primes): if prime and (i + a) != 1: print(i+a) print() if __name__ == "__main__": a=input() for i in range(int(a)): case=input() primes=case.split(" ") sieve(int(primes[0]),int(primes[1]))
0cb919e9153abeab0434615666cda2dd0b78f107
magik2art/DZ_9_Pavel_Mamaev
/task3.py
722
3.65625
4
class Worker: def __init__(self, name, surname, position, wage, bonus): self.position_name = name self.position_surname = surname self._position = position self.position_income = {"wage": wage, "bonus": bonus} class Position(Worker): def __init__(self, name, surname, position, wage, bonus): super().__init__(name, surname, position, wage, bonus) def get_full_name(self): return self.position_name + ' ' + self.position_surname def get_total_income(self): return self.position_income["wage"] + self.position_income["bonus"] start = Position('Pavel', 'Mamaev', 'Director', 30000, 250000) print(start.get_full_name(), start.get_total_income())
7f260fcd89a3b08050e50365c25cab1f0177ed9e
TahiraFatima98/day-27
/multiplication table.py
125
3.8125
4
a=int(input('Enter any no: ')) print('Multiplication table of:', a) for i in range(1, 11): print(a, 'x', i, '=', a*i)
42caeb2c399184e4ba45f0b128dc88e9d47c373f
Connor-Knabe/Coding-Challenges
/Python/Warmup-1/missing_char.py
135
3.671875
4
str = "kitten" n = 1 front = str[:n] # up to but not including n back = str[n+1:] # n+1 through end of string print front + back
01fd2f62f2c35add5844241134c610ddf3b6fa94
Hidenver2016/Leetcode
/Python3.6/61-Py3-M-Rotate List.py
2,315
4.125
4
# -*- coding: utf-8 -*- """ Created on Thu May 16 18:00:07 2019 @author: hjiang """ """ Given a linked list, rotate the list to the right by k places, where k is non-negative. Example 1: Input: 1->2->3->4->5->NULL, k = 2 Output: 4->5->1->2->3->NULL Explanation: rotate 1 steps to the right: 5->1->2->3->4->NULL rotate 2 steps to the right: 4->5->1->2->3->NULL Example 2: Input: 0->1->2->NULL, k = 4 Output: 2->0->1->NULL Explanation: rotate 1 steps to the right: 2->0->1->NULL rotate 2 steps to the right: 1->2->0->NULL rotate 3 steps to the right: 0->1->2->NULL rotate 4 steps to the right: 2->0->1->NULL 知道了移动几次,本质上就是把链表的后面k个节点移动到开头去。注意是平移,顺序不变的。所以要找到后面的k个节点, 那么需要用到19. Remove Nth Node From End of List类似的方法,用两个距离为k的指针进行平移操作,当前面的到达了末尾,那么后面的正好是倒数第k个。 找到倒数第k个之后,那么把这个节点和之前的节点断开,把后面的这段移到前面去即可 --------------------- 原文:https://blog.csdn.net/fuxuemingzhu/article/details/80788107 """ class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution: def rotateRight(self, head, k): """ :type head: ListNode :type k: int :rtype: ListNode """ if not head or not head.next: return head _len = 0 root = head while head: _len += 1 head = head.next k %= _len if k == 0: return root fast, slow = root, root while k - 1: fast = fast.next k -= 1 pre = slow while fast.next:#当fast到底之后,slow正好是倒数第k个 pre = slow slow = slow.next fast = fast.next pre.next = None fast.next = root return slow if __name__ == "__main__": head = ListNode(1) head.next = ListNode(2) head.next.next = ListNode(3) head.next.next.next = ListNode(4) head.next.next.next.next = ListNode(5) print (Solution().rotateRight(head, 2).val)
d6b5a9d0dd1edc2ea26f80af580334114d81d175
dr-dos-ok/Code_Jam_Webscraper
/solutions_python/Problem_74/387.py
1,080
3.640625
4
#!/usr/bin/env python import sys import re Pos = { 'O' : 0, 'B' : 0} def getNext(L, color, event): for i in range(event*2,len(L),2): if L[i] == color: return (i/2, int(L[i+1])) def stepRobot(L, color, goal, event, dis): global Pos if goal == None: return 0 # print "stepRobot", color, goal, event, Pos if Pos[color] > goal[1]: Pos[color]-=1 elif Pos[color] < goal[1]: Pos[color]+=1 else: if goal[0] == event and not dis: return 1 return 0 def main(): T = raw_input() for t in range(int(T)): L = raw_input().split() S = int(L[0]) L = L[1:] if(t < 0): continue Pos['O'] = 0 Pos['B'] = 0 EVENT = 0 ONext = getNext(L, 'O', EVENT) BNext = getNext(L, 'B', EVENT) # print L STEP = 0 while EVENT < S: STEP+=1 dis = False if stepRobot(L, 'O', ONext, EVENT, dis) == 1: EVENT +=1; ONext = getNext(L, 'O', EVENT) dis = True if stepRobot(L, 'B', BNext, EVENT, dis) == 1: EVENT +=1; BNext = getNext(L, 'B', EVENT) print "Case #"+str(t+1)+": " + str(STEP-1) if __name__ == "__main__": main()
da39bd7c7b010217c456ad05a1ca984afa1ddb67
stephsorandom/PythonJourney
/Functions and Methods/Functions.py
3,035
4.3125
4
def Keyword: stands for the definition of the function def name_of_function(): ''' Docstring explains the function with 3 Quotes. Everything inside the function is indented ''' - Python uses snake casing in functions..all lowercase with underscores_between_words EX: def name_of_function(name): ''' print("Hello" + name) ) ''' name_of_function("Jose") ---> Hello Jose • Return keyword - Typically 'return' is used to send back the results of the function instead of just printing it out. - 'Return' allows us to assign the ouput of the function to a new variable. EX: def add_function(num1 + num2) return num1 + num2 ##Return allows to save the result to a variable! result = add_function(1,2) ## 1 + 2 ===> 3 print(result) ====>>> 3 EX2: def say_hello(name): print(f'Hello {name}') say_hello(Jose) ======>> Hello Jose def say_hello(name='Default'): print(f'Hello {name}') say_hello() =====>> Hello Default • The difference between print and result PRINT def print_result(a,b): print(a+b) result = print_result(10,20) ====> 30 ## print_result is not actually saving any part of the function. ## it is just executing the function and then closing it right after. ## If you call result again later...it will return nothing. becaues it is a instant command type(result) ====> NoneType RESULT def return_result(a,b): return a+b result = return_result(10,20) ##call the function later in your code result ====>>> 30 Functions with Logic: def even_check(number): number % 2 == 0 return result even_check(20) ==> True even_check(21) ==> False ## True or False if any even number in List def check_even_list(num_list): #num_list gets passed into function to be executed for number in num_list: ##loops through all numbers in list if number % 2 == 0: ##if any number is Modulos to 2...or even, return True ##return true else: ## else skip that number and continue looping pass return False ## if there are no even numbers in the whole Loop...then return false ## Now return all even numbers in a list, if no even numbers..return empty list def check_even(num_list): even_numbers = [] ##placeholder for number in num_list: ##loops through the list in the function argument if number % 2 == 0: ## if the number is even even_numbers.append(number) ## append =>> add to even_number list else: pass return even_numbers ##return the even_number list
0074dcaf526f3a85e4deaddf55287306f6d199f6
Carter-Co/she_codes_python
/lists/Q3.py
502
4.34375
4
#Ask user for three names, add them to a list and print name_1 = input("Enter a name") name_2 = input("Enter a second name") name_3 = input("Enter a third and final name") print(name_1 + name_2 + name_3) #num1 = input("Enter a number") #num2 = input("Enter another number") #additiontotal_value = int(num1) + int(num2) #print(f"{additiontotal_value} additiontotal_value") #day = "Saturday" #print(type(day)) #month = "July" #message = f"Today is {day} and the month is {month}!" #print(message)
6d40c96832f88ffb8ea9c6291144537f21dc36ee
miolfo/file-line-calculator
/line-calculator.py
1,747
3.609375
4
import os import argparse def calculate_lines(path, extension): dirs = os.listdir(path) linecount = 0 for dir in dirs: if os.path.isfile(os.path.join(path, dir)): linecount += get_lines_in_file(path, dir) return linecount def calculate_lines_recursive(path, extension): linecount = 0 for root, _, files in os.walk(path): for file in files: if not extension: linecount += get_lines_in_file(root, file) else: _, file_extension = os.path.splitext(file) if file_extension == extension: linecount += get_lines_in_file(root, file) return linecount def get_lines_in_file(path, file_name): with open(os.path.join(path, file_name)) as file: try: lines = file.readlines() return len(lines) except UnicodeDecodeError: return 0 if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument("-p", "--path", dest="path", help="Path from which to start line calculation") parser.add_argument("-r", "--recursive", dest="recursive", help="Recurse through all folders in specified folder", action="store_true") parser.add_argument("-e", "--file-ending", dest="file_ending", help="Only calculate files of this extension") args = parser.parse_args() path = os.getcwd() if(args.path): path = args.path if args.recursive: count = calculate_lines_recursive(path, args.file_ending) print("Line count (recursively) in {0} is {1}".format(path, str(count))) else: count = calculate_lines(path, args.file_ending) print("Line count in {0} is {1}".format(path, str(count)))
1fa4ee63bfa6d099be2e87dc3775a1ece9d8b8dc
scouvreur/hackerrank
/30-days-of-code/python/day_8.py
432
3.796875
4
# Enter your code here. Read input from STDIN. Print output to STDOUT num_entries = int(input()) phone_book = {} for i in range(num_entries): line = str(input()).split() phone_book.update({line[0]: int(line[1])}) while True: try: key = str(input()) try: print("{}={}".format(key, phone_book[key])) except KeyError: print("Not found") except EOFError: break
a6ba83934b3388a7cbd7dbb3505f44454bf9cb21
MichellCazares/pythonLA2
/Ejercicio1.py
217
3.65625
4
# def main(): st = float(input("Ingrese su sueldo: ")) if(st<1000): st = st*1.15 elif(st>=1000): st = st*1.12 print("Su sueldo nuevo es: ",st) if __name__ == "__main__": main()
43126234e08b7b6274f7e221bbcdc022a5791e46
habit456/Python3_Projects_msc
/connected.py
1,162
3.625
4
# my goal is to create a matrix that randomly generates 1s and 0s # for each value. And then to find the longest connection in that matrix import numpy as np class Matrix: def __init__(self, rows, columns): self.matrix = np.array([[0 for column in range(columns)] for row in range(rows)]) self.rows = rows self.columns = columns self.shape = (rows, columns) def display(self): for row in self.matrix: print(row) def randomize(self): for r in self.matrix: for i, n in enumerate(r): r[i] += np.random.randint(0, 2) def flattened(self): flat_mat = [] for r in self.matrix: flat_mat.extend(r) return flat_mat """def find_path(matrix, row_num, col_num, memory=[]): paths = memory.copy() if col_num + 1 < matrix.columns: if matrix[row_num][col_num + 1] == 1: count = 0 for i in paths: if path[0]""" np.random.seed(456) my_matrix = Matrix(20, 10) my_matrix.randomize() # find_path(my_matrix, 0, 0) print(dir(my_matrix))
891c57f43bbd0c9e5260ed93f34b655756009ebe
ferfabricio/MITx-6.00.1x
/L4P5.py
637
3.59375
4
import unittest def clip(lo, x, hi): ''' Takes in three numbers and returns a value based on the value of x. Returns: - lo, when x < lo - hi, when x > hi - x, otherwise ''' return min(x, lo) == x and lo or (max(x, hi) == x and hi or x) class TestClip(unittest.TestCase): def test_with_first_negative(self): self.assertEqual(clip(-4.01, 2.25, 9.29), 2.25) def test_with_small_values(self): self.assertEqual(clip(-0.29, 0.84, 0.18), 0.18) def test_with_five(self): self.assertEqual(clip(-5.62, 5.14, 5.23), 5.14) if __name__ == '__main__': unittest.main()
f26ec94b66ec965b425e2539960880d76a08a836
fako/python_introduction
/play.py
1,957
3.84375
4
""" A script to play around with Python a bite To setup run: conda create --name pi pip install -r requirements.txt """ from pprint import pprint import pandas as pd # data analysis library from tamagotchi import KillerRabbit if __name__ == "__main__": # Creating some rabbits! snuggles = KillerRabbit("Snuggles") winky = KillerRabbit("Winky", hunger=100) problem_child = snuggles + winky # In ipython: # See what a KillerRabbit is with KillerRabbit? # And what a KillerRabbit can do with KillerRabbit. # We're making some dinner :P food = ["a knight", "a priest", "a charlatan"] snuggles_dinner, winky_lunch, child_dessert = food # tuple unpacking # Go ahead and feed a KillerRabbit. Check out KillerRabbit.feed. in ipython # Managing our population rabbits = [ snuggles, winky, problem_child, snuggles, winky # oops some duplicates! ] # correcting the duplicates with list slicing rabbits = rabbits[1:-1] # list comprehensions in action to get only happy rabbits happy_rabbits = [ rabbit for rabbit in rabbits if rabbit.happiness > 30 ] happy_rabbits.sort( key=lambda rabbit: rabbit.happiness, # lambda's are simple anonymous functions reverse=True ) happy_rabbit_names = [str(rabbit) for rabbit in happy_rabbits] happy_rabbits_hall_of_fame = ", ".join(happy_rabbit_names) # Keep track of the population with data! rabbit_records = [rabbit.to_record() for rabbit in rabbits] # pprint this! population = pd.DataFrame.from_records(rabbit_records) # A DataFrame is a matrix containing data # You can make our population very happy with # 1) population["happiness"] *= 2 # 2) population["hunger"] /= 2 # Or try some real science: # population["satisfaction_coefficient"] = \ # population["happiness"] / population["hunger"] # When in doubt what to do # import this
31933bade91519911f544a1e5255d5222f7ab31e
ekoz/python-study
/3.8/cv2/chapter02/01_img_add.py
996
3.5
4
# -*- coding: utf-8 -*- # @author : eko.zhan # @time : 2021/8/23 23:05 import cv2 import numpy as np # Load two images img1 = cv2.imread("../data/messi8.jpg") img2 = cv2.imread("../data/opencv-logo.png") img2 = cv2.resize(img2, (80, 80)) # cv2.imshow("1", cv2.resize(img2, (80, 80))) # cv2.waitKey() # I want to put logo on top-left corner, So I create a ROI rows, cols, channels = img2.shape roi = img1[0:rows, 0:cols] # Now create a mask of logo and create its inverse mask also img2gray = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY) ret, mask = cv2.threshold(img2gray, 10, 255, cv2.THRESH_BINARY) mask_inv = cv2.bitwise_not(mask) # Now black-out the area of logo in ROI img1_bg = cv2.bitwise_and(roi, roi, mask=mask_inv) # Take only region of logo from logo image. img2_fg = cv2.bitwise_and(img2, img2, mask=mask) # Put logo in ROI and modify the main image dst = cv2.add(img1_bg, img2_fg) img1[0:rows, 0:cols] = dst cv2.imshow("res", img1) cv2.waitKey(0) cv2.destroyAllWindows()
39c0da5844a822d6d3cd3dc8f5d5eb4d33e08e15
hemantkumbhar10/Practice_codes_python
/University_admission_class.py
1,780
3.5625
4
class Student: def __init__(self): self.__student_id = None self.__age = None self.__marks = None self.__course_id = None self.__fees = None def set_student_id(self, student_id): self.__student_id = student_id def set_age(self, age): self.__age = age def set_marks(self, marks): self.__marks = marks def get_student_id(self): return self.__student_id def get_age(self): return self.__age def get_marks(self): return self.__marks def get_course_id(self): return self.__course_id def get_fees(self): return self.__fees def validate_marks(self): return self.__marks >= 0 and self.__marks <= 100 def validate_age(self): return self.__age > 20 def check_qualification(self): return self.validate_marks() and self.validate_age() and self.__marks >= 65 def choose_course(self, course_id): if self.check_qualification() and (course_id == 1001 or course_id == 1002): self.__course_id == course_id if self.__course_id == 1001: self.__fees == 25575 elif self.__course_id == 1002: self.__fees = 15500 if self.__marks > 85: self.__fees = self.__fees/(self.__fees*25/100) return True else: return False maddy=Student() maddy.set_student_id(1004) maddy.set_age(21) maddy.set_marks(65) if(maddy.check_qualification()): print("Student has qualified") if(maddy.choose_course(1002)): print("Course allocated") else: print("Invalid course id") else: print("Student has not qualified")
9845a6cef9c3ac685768547a1567c0d5e94613d0
rnsdoodi/Programming-CookBook
/Back-End/Databases/SQLite/Python-APIs/simple_csv.py
1,822
3.65625
4
import sqlite3 import csv conn = sqlite3.connect('library.db') c = conn.cursor() c.execute('DROP TABLE IF EXISTS book_s') c.execute('''CREATE TABLE "book_s"( "title" TEXT, "price" TEXT, "rating" TEXT, "in_stock" INTEGER) ''') fname = 'filename.csv' with open(fname, 'r+') as csv_file: csv_reader = csv.reader(csv_file, delimiter=',') for row in csv_reader: print(row) title = row[0] price = row[1] rating = row[2] in_stock = int(row[3]) c. execute('''INSERT INTO book_s(title, price, rating, in_stock) VALUES (?,?,?,?)''', (title, price, rating, in_stock)) conn.commit() ######################################################### ######################################################### import sqlite3 import csv conn = sqlite3.connect('library.db') c = conn.cursor() c.execute('DROP TABLE IF EXISTS book_s') c.execute('''CREATE TABLE "book_s"( "title" TEXT, "price" TEXT, "rating" TEXT, "in_stock" INTEGER ) ''') fname = 'book_scrape_new.csv' new_csv = [] with open(fname) as csv_file: csv_reader = csv.reader(csv_file, delimiter=',') next(csv_reader) for row in csv_reader: title = row[0] price = row[1] rating = row[2] in_stock = row[3] c.execute('''INSERT INTO book_s(title, price, rating, in_stock) VALUES (?,?,?,?)''', (title, price, rating, in_stock)) conn.commit() conn.close() def delete_one(id): conn = sqlite3.connect('database.db') c = conn.cursor() c.execute('DELETE from database_file_name WHERE rowid = (?)', id) conn.commit() conn.close() def lookup(thing): conn = _sqlite3.connect('database.db') c = conn.cursor() c.execute('SELECT * from database_file_name WHERE thing=(?)', (thing,)) item = c.fetchall() conn.commit() conn.close() return item[0][1]
2ae775ba2801a78f83f2e900e87af01bca626c94
renansald/Python
/cursos_em_video/Desafio85.py
302
3.984375
4
numero = [[], []]; for x in range(0, 7): num = int(input("Informe um número: ")); if(num%2 == 0): numero[0].append(num); else: numero[1].append(num); numero[0].sort(); numero[1].sort(); print(f"Os números pares foram {numero[0]}\nOs números inmpáres foram {numero[1]}")
23d37f9ee8fd8f75da492ac9dca8b74699fd629e
mtknguyen03/MaiTranKhoiNguyen-c4t6
/mini_hack/cang_vl_7.py
77
3.65625
4
n = input("Number? ") m = int(n) for i in range(m, -1, -1): print(i)
be7235d5a6c583383bc3183a53cb2a6e97fcc449
yblanco/design-pattern
/src/libs/ObjectPool.py
773
3.640625
4
import time class PoolReusable: def __init__(self, size=5): self._max = max; self.size = 1; self._reusables = [Reusable(_) for _ in range(size)] def acquire(self): if len(self._reusables) == 0: raise Exception("Pool empty") return self._reusables.pop() def release(self, reusable): self._reusables.append(reusable) return self.available(); def use(self): reusable = self.acquire(); print("Available after internal acquire " + str(self.available())) available = self.release(reusable); print("Available after internal release " + str(self.available())) return available def available(self): return len(self._reusables); class Reusable: def __init__(self, id): print("Created " + str(id)) pass
b572501005a33a2802d3d2166168f47ddbd6c83f
AAKA999/Tic_Tac_Toe
/2player_tic_tac_toe.py
3,843
3.90625
4
import random def display_board(current_board): print(current_board[1]+'|'+current_board[2]+'|'+current_board[3]) print(current_board[4]+'|'+current_board[5]+'|'+current_board[6]) print(current_board[7]+'|'+current_board[8]+'|'+current_board[9]) def player_input(): selection=input('Player 1 choose your marker, X or O: ') if (selection.upper()=='X'): return ('X','O') elif (selection.upper()=='O'): return ('O','X') def place_marker(the_board,position,marker): if position in range (1,10): the_board[position] = marker def choose_first(): switch=random.randint(0,1) if (switch==1): return 'Player 1' else: return 'Player 2' def win_check(the_board,turn): if (the_board[1]==the_board[2]==the_board[3] or the_board[4]==the_board[5]==the_board[6] or the_board[7]==the_board[8]==the_board[9] or the_board[1]==the_board[4]==the_board[7] or the_board[2]==the_board[5]==the_board[8] or the_board[3]==the_board[6]==the_board[9] or the_board[1]==the_board[5]==the_board[9] or the_board[3]==the_board[5]==the_board[7] ): return True def board_full_check(the_board): board_full = True for i in range(1,10): if the_board[i].isdigit(): board_full = False return board_full def replay(): choice=input('Play again? Yes or No:').upper() return choice=='YES' while(True): print('WELCOME TO TIC TAC TOE !!!') the_board=['#','1','2','3','4','5','6','7','8','9'] display_board(the_board) p1,p2=player_input() print(f'Player 1 marker is {p1}\nPlayer 2 marker is {p2}') turn=choose_first() print(turn+ ' will go first') game_status= True while(game_status): if turn=='Player 1': #display_board(the_board) position= int(input(f'{turn}, select a position to make your move: ')) if position in range(1,10): if the_board[position]!='X' and the_board[position]!='O': place_marker(the_board,position,p1) display_board(the_board) else: print('Choose correct position!') continue else: print('Choose correct position!') if win_check(the_board,turn): display_board(the_board) print('Player 1 won!!') game_status=False else: if board_full_check(the_board): display_board(the_board) print('TIE Game!!') game_status=False break else: turn='Player 2' else: #display_board(the_board) position= int(input(f'{turn}, select a position to make your move: ')) if position in range(1,10): if the_board[position]!='X' and the_board[position]!='O': place_marker(the_board,position,p2) display_board(the_board) else: print('Choose correct position!') continue else: print('Choose correct position!') if win_check(the_board,turn): display_board(the_board) print('Player 2 won!!') game_status=False else: if board_full_check(the_board): display_board(the_board) print('TIE Game!!') game_status=False break else: turn='Player 1' if not replay(): break
a72c94036650fc9543fb54724b46d938379e710f
b166erbot/300_ideias_para_programar
/tipo_de_pessoa3.3.1.py
277
4.03125
4
def main(): pessoa = input('digite um tipo de pessoa F/J: ').upper() if pessoa == 'F': print('pessoa física') elif pessoa == 'J': print('pessoa jurídica') else: print('tipo de pessoa inválido') if __name__ == '__main__': main()
551566e534ecdf178f37e3f4c224d8df0beee4db
samirelanduk/inferi
/inferi/datasets.py
4,442
3.75
4
"""Contains the Dataset class.""" from .variables import Variable class Dataset: """A collection of :py:class:`.Variable` objects which describe the same experimental units. :param \*variables: The Variables that make up the Dataset. :raises TypeError: if non-Variables are given.""" def __init__(self, *variables): for variable in variables: if not isinstance(variable, Variable): raise TypeError("{} is not a Variable".format(variable)) if variable.length != variables[0].length: raise ValueError( "Can't make Dataset with different-length Variables" ) self._variables = list(variables) def __repr__(self): return "<Dataset ({} Variables)>".format(len(self._variables)) @property def variables(self): """Returns the :py:class:`.Variable` objects in the Dataset. :rtype: ``tuple``""" return tuple(self._variables) def add_variable(self, variable): """Adds a :py:class:`.Variable` column to the Dataset. :param Variable variable: The Variable to add. :raises TypeError: if a non-Variable is given. :raises ValueError: if the Variable's length doesn't match.""" if not isinstance(variable, Variable): raise TypeError("{} is not a Variable".format(variable)) if self._variables and variable.length != self._variables[0].length: raise ValueError("Can't have Dataset of different-length Variables") self._variables.append(variable) def insert_variable(self, index, variable): """Inserts a :py:class:`.Variable` column to the Dataset at the index given.. :param int index: The location to insert at. :param Variable variable: The Variable to add. :raises TypeError: if a non-Variable is given. :raises ValueError: if the Variable's length doesn't match.""" if not isinstance(variable, Variable): raise TypeError("{} is not a Variable".format(variable)) if self._variables and variable.length != self._variables[0].length: raise ValueError( "Can't have Dataset with different-length Variables" ) self._variables.insert(index, variable) def remove_variable(self, variable): """Removes a :py:class:`.Variable` column from the Dataset. :param Variable variable: the Variable to remove.""" self._variables.remove(variable) def pop_variable(self, index=-1): """Removes and returns the variable at a given index - by default the last one. :param int index: The index to remove at (default is ``-1``). :returns: the specified Variable.""" return self._variables.pop(index) @property def rows(self): """Returns the rows of the Dataset. :rtype: ``tuple``""" columns = [var._values for var in self._variables] return tuple([values for values in zip(*columns)]) def add_row(self, row): """Adds a row to the Dataset, updating all the Variables in the process. :param list row: A list of values to add. :raises ValueError: if the length of the row does not equal the number\ of Variables in the Dataset.""" if len(row) != len(self._variables): raise ValueError("Row {} is not the correct length".format(row)) for value, variable in zip(row, self._variables): variable.add(value) def sort(self, column=None): """Sorts all the Variables in the Dataset by a single column, by default the first one. :param Variable column: the Variable to sort by. :raises TypeError: if a non-Variable is given. :raises ValueError: if the Variable given isn't in the Dataset.""" var = self._variables[0] if column: if not isinstance(column, Variable): raise TypeError("Can't sort by non-Variable {}".format(column)) if column not in self._variables: raise ValueError("{} isn't a Variable in {}".format(column, self)) var = column indeces = list(range(len(var._values))) indeces.sort(key=var._values.__getitem__) for variable in self._variables: variable._values = list(map(variable._values.__getitem__, indeces))
a1061d4dec85b69f9751ea39a3f7140afc3cb370
maheshmasale/pythonCoding
/AlgoHW3/Ema's Supercomputer.py
2,824
3.9375
4
#https://www.hackerrank.com/challenges/two-pluses?h_r=next-challenge&h_v=zen #!/bin/python3 def get_item(grid, position): return grid[position[0]][position[1]] def get_positions(grid, position, offset_amt=1): positions = [] positions.append(get_position(grid, position, 'up', offset_amt)) positions.append(get_position(grid, position, 'down', offset_amt)) positions.append(get_position(grid, position, 'left', offset_amt)) positions.append(get_position(grid, position, 'right', offset_amt)) return positions def get_position(grid, position, offset, offset_amt=1): posr, posc = position if offset == 'up': posr -= offset_amt elif offset == 'left': posc -= offset_amt elif offset == 'down': posr += offset_amt elif offset == 'right': posc += offset_amt if ((posr < 0 or posr > len(grid)-1) or (posc < 0 or posc > len(grid[0])-1)): return None return (posr, posc) def compare_positions(positions_1, positions_2): for position in positions_1: if position in positions_2: return True return False # retrieve input and populate grid n, m = [int(x) for x in input().strip().split(' ')] grid = [] for row in range(n): grid.append(list(input().strip())) # search grid for all valid pluses valid_pluses = [] for row in range(1,n-1): for column in range(1,m-1): current_position = (row, column) if get_item(grid, current_position) == 'B': continue offset_amt = 1 positions_queue = [] while True: positions = get_positions(grid, current_position, offset_amt) if None in positions: break items = [get_item(grid, position) for position in positions] if 'B' in items: break positions_queue.extend(positions) valid_pluses.append(((offset_amt * 4) + 1, positions_queue + [current_position])) offset_amt += 1 # process the valid pluses for the max product if not valid_pluses: # there were no valid pluses. still check if there are any Gs count_g = 0 for row in grid: count_g += row.count('G') print(1) if count_g >= 2 else print(0) elif len(valid_pluses) == 1: print(valid_pluses[0][0]) else: # need to find max products without re-using positions. valid_pluses = list(reversed(sorted(valid_pluses))) products = [] for i in range(len(valid_pluses)): current_plus = valid_pluses[i] comparison_pluses = valid_pluses[i+1:] for comparison_plus in comparison_pluses: if compare_positions(current_plus[1], comparison_plus[1]) != True: products.append(current_plus[0] * comparison_plus[0]) break else: products.append(current_plus[0] * 1) print(max(products))
d66b312ec236404a78d2deadbffc687fac7f4d57
Michabele/pdsnd_github
/bikeshare.py
9,502
4.3125
4
import time import pandas as pd import numpy as np CITY_DATA = { 'chicago': 'chicago.csv', 'new york city': 'new_york_city.csv', 'washington': 'washington.csv' } def get_filters(): """ Asks user to specify a city, month, and day to analyze. Returns: (str) city - name of the city to analyze (str) month - name of the month to filter by, or "all" to apply no month filter (str) day - name of the day of week to filter by, or "all" to apply no day filter """ print('Hello! Let\'s explore some US bikeshare data!') # get user input for city (chicago, new york city, washington). HINT: Use a while loop to handle invalid inputs i=0 while i < 1: city = input("You are interested in some bike data? Which city would you like? chicago, new york city or washington: ").lower() i=0 if city in ["chicago", 'new york city', "washington"]: i=1 print('-'*40) print("You have choosen:", city) else: print("sorry. That was not a correct City. Try again!") print('-'*40) i=0 # get user input for month (all, january, february, ... , june) i=0 j=0 while j < 1: by_month = input("Do you want to filter by month? yes / no: ").lower() if by_month in ["yes"]: while i<1: month = input("Which month do you want to analyze? january, february, march, april, may, june: ").lower() if month in ["january", "february", "march", "april", "may", "june"]: i=1 j=1 print('-'*40) print("You have choosen:", month) else: print("Sorry. That was not a correct month. Try again!") print('-'*40) i=0 elif by_month in ["no"]: month="all" print('-'*40) print("You have choosen:", month) j=1 else: print("Sorry. That was not a correct option. Try again!") print('-'*40) j=0 # get user input for day of week (all, monday, tuesday, ... sunday) i=0 j=0 while j < 1: by_day = input("Do you want to filter by day? yes / no: ") if by_day in ["yes"]: while i<1: day = input("Which month do you want to analyze? monday, tuesday, wednesday, thursday, friday, saturday, sunday: ").lower() if day in ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"]: i=1 j=1 print('-'*40) print("You have choosen:", day) else: print("Sorry. That was not a correct day. Try again!") print('-'*40) i=0 elif by_day in ["no"]: day="all" print('-'*40) print("You have choosen:", day) j=1 else: print("Sorry. That was not a correct option. Try again!") print('-'*40) j=0 print('-'*40) return city, month, day def load_data(city, month, day): """ Loads data for the specified city and filters by month and day if applicable. Args: (str) city - name of the city to analyze (str) month - name of the month to filter by, or "all" to apply no month filter (str) day - name of the day of week to filter by, or "all" to apply no day filter Returns: df - Pandas DataFrame containing city data filtered by month and day """ # load data file into a dataframe df = pd.read_csv(CITY_DATA[city]) # convert the Start Time column to datetime df['Start Time'] = pd.to_datetime(df['Start Time']) # extract month and day of week from Start Time to create new columns df['month'] = df['Start Time'].dt.month df['day_of_week'] = df['Start Time'].dt.weekday_name # filter by month if applicable if month != 'all': # use the index of the months list to get the corresponding int months = ['january', 'february', 'march', 'april', 'may', 'june'] month = months.index(month) + 1 # filter by month to create the new dataframe df = df[df['month'] == month] # filter by day of week if applicable if day != 'all': # filter by day of week to create the new dataframe df = df[df['day_of_week'] == day.title()] return df def time_stats(df): """Displays statistics on the most frequent times of travel.""" print('\nCalculating The Most Frequent Times of Travel...\n') start_time = time.time() # display the most common month most_month = df["month"].value_counts().idxmax() month_list=["January", "February", "March", "April", "May", "June", "July", "August"] print("The most common month is: ", month_list[most_month]) # display the most common day of week most_day = df["day_of_week"].value_counts().idxmax() print("The most common day is: ", most_day) # display the most common start hour df["hour_of_timestamp"] = df["Start Time"].dt.hour most_hour = df["hour_of_timestamp"].value_counts().idxmax() print("The most common starting hour is: ", most_hour, "'o clock") print("\nThis took %s seconds." % (time.time() - start_time)) print('-'*40) def station_stats(df): """Displays statistics on the most popular stations and trip.""" print('\nCalculating The Most Popular Stations and Trip...\n') start_time = time.time() # display most commonly used start station most_start_st = df["Start Station"].value_counts().idxmax() print("The most common start station is: ", most_start_st) # display most commonly used end station most_end_st = df["End Station"].value_counts().idxmax() print("The most common end station is: ", most_end_st) # display most frequent combination of start station and end station trip df['Start - End Station'] = df[['Start Station', 'End Station']].agg(' - '.join, axis=1) most_start_end=df["Start - End Station"].value_counts().idxmax() print("\nThe most frequent combination of start station and end station trip is:\n", most_start_end) print("\nThis took %s seconds." % (time.time() - start_time)) print('-'*40) def trip_duration_stats(df): """Displays statistics on the total and average trip duration.""" print('\nCalculating Trip Duration...\n') start_time = time.time() # display total travel time total_time= df["Trip Duration"].sum() print("The total travel time was:", total_time, "sec's") # display mean travel time mean_time= df["Trip Duration"].mean() print("The mean travel time was: ", mean_time, "sec's") print("\nThis took %s seconds." % (time.time() - start_time)) print('-'*40) def user_stats(df): """Displays statistics on bikeshare users. Like gender, age or the type of the user (private, commercial) """ print('\nCalculating User Stats...\n') start_time = time.time() # Display counts of user types count_user_typ = df["User Type"].value_counts() print("\nThe counts of the User Types are: ") print(count_user_typ) # Display counts of gender count_gender = df["Gender"].value_counts() print("\nThe counts of the Genders are: ") print(count_gender) # Display earliest, most recent, and most common year of birth earliest=df["Birth Year"].min() print("\nThe earliest year of birth is: ", earliest) most_recent=df["Birth Year"].max() print("The most recent year of birth is: ", most_recent) most_common=df["Birth Year"].value_counts().idxmax() print("The most common year of birth is: ", most_common) print("\nThis took %s seconds." % (time.time() - start_time)) print('-'*40) def show_raw_data(df): """Displays 5 rows of the Raw Data (DataFrame) as long the User wants to""" # Ask the user if he wants to see raw data j=0 n=0 m=5 while j<1: raw_ans=input("Do you want to see 5 lines of the raw data? Yes/No: ").lower() i=0 if raw_ans in ["yes"]: while i<1: print(df[n:m]) n=n+5 m=m+5 more_raw=input("Do you want to see 5 more lines?: Yes/No: ").lower() if more_raw in ["yes"]: i=0 elif more_raw in ["no"]: i=1 j=1 else: i=1 raw_ans="wrong" print("Sorry. That was not a correct answer. Try again!") elif raw_ans in ["no"]: j=1 else: print("Sorry. That was not a correct answer. Try again!") print("Fine. Let's start with data analysis\n") print("-"*40) def main(): while True: city, month, day = get_filters() df = load_data(city, month, day) show_raw_data(df) time_stats(df) station_stats(df) trip_duration_stats(df) user_stats(df) restart = input('\nWould you like to restart? Enter yes or no.\n').lower() if restart.lower() != 'yes': break if __name__ == "__main__": main()
9d50c5d6c6c40e6d8d46bc9ded80c13774bc985a
latata666/newcoder
/leecode/lec_322_coinChange.py
1,114
3.640625
4
# -*- coding: utf-8 -*- # @Time : 2020/6/15 10:56 # @Author : Mamamooo # @Site : # @File : lec_322_coinChange.py # @Software: PyCharm """ 给定不同面额的硬币 coins 和一个总金额 amount。编写一个函数来计算可以凑成总金额所需的最少的硬币个数。 如果没有任何一种硬币组合能组成总金额,返回 -1 输入: coins = [1, 2, 5], amount = 11 输出: 3 解释: 11 = 5 + 5 + 1 """ import functools class Solution: def coinChange(self,coins,amount): print(coins,amount) @functools.lru_cache(amount) def dp(rem): if rem < 0: return -1 if rem == 0: return 0 mini = int(1e9) for coin in self.coins: res = dp(rem -coin) if res >= 0 and res < mini: mini = res + 1 return mini if mini < int(1e9) else -1 self.coins = coins if amount < 1 : return 0 return dp(amount) s = Solution() coins = [1, 2, 5] amount = 11 result = s.coinChange(coins,amount) print(result)
1984a9f1a651382543ffe067e6fecc101f746c22
tyagian/Algorithms-and-Data-Structure
/practice/system/logs_2/read_file_enumerate_count_freq.py
1,601
4.03125
4
#https://stackabuse.com/read-a-file-line-by-line-in-python/#readafilelinebylinewithaforloopmostpythonicapproach """ To read line by line without loading file in memory with open('Iliad.txt') as f: for index, line in enumerate(f): print("Line {}: {}".format(index, line.strip())) with open("sample.txt") as a_file: for line in a_file: print(line) """ """ You can write a from-scratch solution to count the frequency of certain words, without using any external libraries. Let's write a simple script that loads in a file, reads it line-by-line and counts the frequency of words, printing the 10 most frequent words and the number of their occurrences """ import sys, os def order_bag_of_words(bag_of_words, desc=False): words = [(word, cnt) for word, cnt in bag_of_words.items()] return sorted(words, key=lambda x: x[1], reverse=desc) def record_word_cnt(words, bag_of_words): for word in words: if word != '': if word.lower() in bag_of_words: bag_of_words[word.lower()] += 1 else: bag_of_words[word.lower()] = 1 def main(): filepath = sys.argv[1] if not os.path.isfile(filepath): print ("File path {} doesn't exit. Exiting....".format(filepath)) sys.exit() bag_of_words = {} with open(filepath) as fp: for line in fp: record_word_cnt(line.strip().split(' '), bag_of_words) sorted_words = order_bag_of_words(bag_of_words, desc= True) print("Most frequent 10 words {}".format(sorted_words[:10])) if __name__ == '__main__': main()
a6340770379a5d2d8aa0d2321176fa8b6dd2be7c
thraddash/python_tut
/22_advance_concept/uppercase_name.py
929
4.4375
4
#!/usr/bin/env python a=""" def person_name(name): return name upper_name = person_name("John Wick") print(upper_name) """ def person_name(name): return name upper_name = person_name("John Wick") print(a) print(upper_name) b=""" ################################################## covert output to uppercase change person_name during runtime using decorator def uppercase(function): def decorated(*args): result = function(*args) result_upper = result.upper() return result_upper return decorated @uppercase def person_name(name): return name upper_name = person_name("John Wick") print(upper_name) """ def uppercase(function): def decorated(*args): result = function(*args) result_upper = result.upper() return result_upper return decorated @uppercase def person_name(name): return name upper_name = person_name("John Wick") print(b) print(upper_name)
e00dcb6ea88b8f6e518dafaa82596937527d8ce6
zuosong/python
/cgi-bin/friends2.py
1,345
3.640625
4
#!/usr/bin/env python import cgi header = 'Content-Type:text/html\n\n' formhtml='''<HTML><HEAD><TITLE> Friends CGI Deom</TITLE></HEAD> <BODY><H3>Friends list for: <I>NEW USER</I></H3> <FORM ACTION="/cgi-bin/friends2.py"> <B>Enter your Name:</B> <INPUT TYPE=hidden NAME=action VALUE=edit> <INPUT TYPE=text NAME=person VALUE="NEW USER" SIZE=15> <P><B>How many friends do you have?</B> %s <P><INPUT TYPE=submit></FORM></BODY></HTML>''' fradio = '<INPUT TYPE=radio NAME=howmany VALUE="%s" %s> %s\n' def showForm(): friends = '' for i in [0,10,15,50,100]: checked='' if i ==0: checked='CHECKED' friends = friends+fradio%(str(i),checked,str(i)) print header + formhtml %(friends) reshtml = '''<HTML><HEAD><TITLE> Friends CGI Demo</TITLE></HEAD> <BODY><H3>Friends list for:<I>%s</I> </H3> Your name is:<B>%s</B><P> You have <B>%s</B> friends. </BODY></HTML>''' def doResults(who,howmany): print header + reshtml %(who,who,howmany) def process(): form = cgi.FieldStorage() if form.has_key('person'): who = form['person'].value else: who = 'NEW USER' if form.has_key('howmany'): howmany=form['howmany'].value else: howmany = 0 if form.has_key('action'): doResults(who,howmany) else: showForm() if __name__ == '__main__': process()
40bd014df322f0433dc868b3b7a42cf600fd2d07
satyam-seth-learnings/ds_algo_learning
/Applied Course/4.Problem Solving/1.Problems on Array/28.Game of Life.py
2,102
3.828125
4
# https://leetcode.com/problems/game-of-life/ # Logic-1 class Solution: def gameOfLife(self, board: List[List[int]]) -> None: """ Do not return anything, modify board in-place instead. """ rows=len(board) cols=len(board[0]) neighbors=[(1,0),(1,-1),(0,-1),(-1,-1),(-1,0),(-1,1),(0,1),(1,1)] copy_board=[[board[row][col] for col in range(cols)] for row in range(rows)] for row in range(rows): for col in range(cols): live_neighbors=0 for neighbor in neighbors: r=row+neighbor[0] c=col+neighbor[1] if (r<rows and r>=0) and (c<cols and c>=0) and copy_board[r][c]==1: live_neighbors+=1 if copy_board[row][col]==1 and (live_neighbors<2 or live_neighbors>3): board[row][col]=0 if copy_board[row][col]==0 and live_neighbors==3: board[row][col]=1 # Logic-2 class Solution: def gameOfLife(self, board: List[List[int]]) -> None: """ Do not return anything, modify board in-place instead. """ rows=len(board) cols=len(board[0]) neighbors=[(1,0),(1,-1),(0,-1),(-1,-1),(-1,0),(-1,1),(0,1),(1,1)] for row in range(rows): for col in range(cols): live_neighbors=0 for neighbor in neighbors: r=row+neighbor[0] c=col+neighbor[1] if (r<rows and r>=0) and (c<cols and c>=0) and abs(board[r][c])==1: live_neighbors+=1 if (board[row][col]==1) and (live_neighbors<2 or live_neighbors>3): board[row][col]=-1 if (board[row][col]==0) and (live_neighbors==3): board[row][col]=2 for row in range(rows): for col in range(cols): if board[row][col]>0: board[row][col]=1 else: board[row][col]=0
4f795f244105b6b2cfba6ffc76af923ad3a2ed1a
mbalakiran/Python
/Bala Kiran LAB 3/wordlistfilewriter.py
1,296
4.21875
4
def main(): #Asking for the number of words user wants to enter numberofwords = int(input("Enter the number of words to be written to a file: ")) #Creating an file with the write funtion w wordfile = open("Written file.txt", "w") #Enetering the number of the words informed by the user word = input("Enter the number of words requested: ") #Spliting the words through quatations as it understands the space and next word which has been entered by the user #will be taken as an new word words = word.split(" ") #Creating an while loop for checking the number of words is matching with the user count or not while numberofwords >= len(words): wordfile.write(str(word) + " ") break #Ending the functon through break else: #If the number of words entered more than of requested print("The number of letters are more") # Number it would be printing this error message main() def printfile(): wordfile = open("written file.txt", "r") #Opeing the file and reading the file wordcontent = wordfile.read() print("The words which have been entered to the file are: \n",wordcontent) printfile()
7946ae5e32580592c37fc737dbf0820d89676e5d
Caio-Margutti-Alves/Programming_Challenges
/Code in Game/speed.py
275
3.5
4
#!/usr/bin/python3 import datetime s = input() while s != "0 0 0": d, s1, s2 = (int(x) for x in s.split()) #print (d,s1,s2) h = 3600 a1 = d*h/s1 a2 = d*h/s2 ans = abs(a1-a2) #print (ans) ans = str(datetime.timedelta(seconds=ans)) print (ans) s = input()
835e382f52de53093caef02c4acd25ede727eb20
gnikolaropoulos/AdventOfCode2020
/day24/main.py
2,080
3.546875
4
from collections import defaultdict, Counter def get_puzzle_input(): instructions = defaultdict(list) j = 0 with open("input.txt") as input_txt: for line in input_txt: i = 0 while i < len(line.strip()): if line[i] == "e" or line[i] == "w": instructions[j].append(line[i]) i += 1 else: instructions[j].append(line[i] + line[i + 1]) i += 2 j += 1 return instructions def solve_part_1(instructions): black = set() for line in instructions: x, y = 0, 0 for instruction in instructions[line]: if instruction == "e": x += 1 if instruction == "w": x -= 1 if instruction == "se": y += 1 if instruction == "sw": x -= 1 y += 1 if instruction == "ne": x += 1 y -= 1 if instruction == "nw": y -= 1 if (x, y) in black: black.remove((x, y)) else: black.add((x, y)) return black, len(black) COORDS = { 'e': (1, 0), 'se': (0, 1), 'sw': (-1, 1), 'w': (-1, 0), 'ne': (1, -1), 'nw': (0, -1) } def solve_part_2(black): for _ in range(100): adjacent = Counter() # Track adjacent 'live' counts, also serves as a bounds-checking mechanic next_black = set() # Next state for x, y in black: for dx, dy in COORDS.values(): adjacent[x + dx, y + dy] += 1 for coords, count in adjacent.items(): if count == 2 or (coords in black and count == 1): next_black.add(coords) black = next_black return len(black) if __name__ == "__main__": puzzle_input = get_puzzle_input() black, answer_1 = solve_part_1(puzzle_input) print(f"Part 1: {answer_1}") answer_2 = solve_part_2(black) print(f"Part 2: {answer_2}")
a11d8b3d392dcaa3e99483edc2cbf81fb9ca358d
drajan21/Object-Oriented-Programming
/libPrjPython/Book.py
1,118
3.5625
4
from Media import Media class Book(Media): def __init__(self, callno, title, subject, author, description, publisher, city, year, series, notes): super(Book, self).__init__(callno, title, subject, notes) self.author = author self.description = description self.publisher = publisher self.city = city self.year = year self.series = series def display(self): print "---------------Book Details-------------------------------------------------------------------------" super(Book, self).display() print "Author : ", self.author print "Description : ", self.description print "Publisher : ", self.publisher print "City : ", self.city print "Year : ", self.year print "Series : ", self.series print "Notes : ", self.notes print "\n" def compare_other(self,srch_other): return srch_other in self.description or srch_other in self.notes or srch_other in self.year
83aecdfcecceb7c13a0e88fe46926c05f520639f
kkk12538/python-visualization
/可视化编程小项目/数据处理/气温折线图.py
576
3.5625
4
import csv import matplotlib.pyplot as plt with open('weather.csv') as file: reader=csv.reader(file) # header_row=next(reader) # print(header_row) # for index,column_header in enumerate(header_row): # print(index,column_header) a=[] for row in reader: for i in row: a.append(int(i)) print(a) plt.plot(a,c='red') plt.xlabel('days',fontsize=16) plt.ylabel('temperatures',fontsize=16) plt.title('temperature of weather',fontsize=24) plt.tick_params(axis='both',which='major',labelsize=16) plt.show()
41badc6c42b6630dfb7d3208bb11238e7e766482
harishk-97/python
/hacker rank/program3.py
146
3.671875
4
a=int(input()) p=a for i in range(a): b='' for i in range(a): if(i<p-1): b+=' ' else: b+='#' p=p-1 print(b)
ab379fadd5d5fcae01d856f606b93a13349d8b7c
Lucas-Severo/python-exercicios
/mundo03/ex088.py
930
4.15625
4
''' Faça um programa que ajude um jogador da MEGA SENA a criar palpites. O programa vai perguntar quantos jogos serão gerados e vai sortear 6 números entre 1 e 60 para cada jogo, cadastrando tudo em uma lista composta. ''' from random import randint from time import sleep jogos = [] numeros = [] print('-'*30) print(f'{"JOGA NA MEGA SENA":^30}') print('-'*30) quantidadeJogos = int(input('Quantos jogos você quer que eu sorteie? ')) print(f'-=-=-= SORTEANDO {quantidadeJogos} JOGOS -=-=-=') for jogo in range(0, quantidadeJogos): for sorteio in range(0, 6): while True: numero = randint(1, 60) if numero not in numeros: break numeros.append(numero) numeros.sort() jogos.append(numeros[:]) numeros.clear() for indice, jogo in enumerate(jogos): sleep(0.5) print(f'Jogo {indice+1}: {jogo}') print('-=-=-=-=-= < BOA SORTE! > -=-=-=-=-=')
17f95176c391ac0b30cde3c4371652cd1a6d32e6
toniall/webscraping
/tweet_scraper.py
1,596
3.640625
4
#!/usr/bin/python # -*- coding: utf-8 -*- # =========== Código para scrapear tweets empleando GetOldTweets3 ============== # # Objetivo: con este código se scrapea tweets, más o menos recientes de @nperedo. # # Notas: idealmente quisiéramos scrapear tweets recientes de todos los usuarios; # \sin embargo, para ello se requiere una cuenta de developper en Tweepy. Por lo # \para el presente ejercicio se realiza el scrapeo con GetOldTweets3. # # Output: el output de este script es un documento .csv # ============================================================================== # ===================== Importando paquetería empleanda ======================== import GetOldTweets3 as got import pandas as pd username = 'nperedo' # set username of interest since_date = '2019-01-20' # set daterange until_date = '2020-05-02' # set daterange count = 1000 # setcount max of tweets tweetCriteria = got.manager.TweetCriteria().setUsername(username).setSince(since_date).setUntil(until_date)# Creation of list that contains all tweets tweets = got.manager.TweetManager.getTweets(tweetCriteria) # Creating list of chosen tweet data user_tweets = [[tweet.date, tweet.text] for tweet in tweets] df = pd.DataFrame(data=user_tweets, columns=['date_time', "tweet"]) df['date'] = df['date_time'].dt.date df['time'] = df['date_time'].dt.time file_name="tweet_search" # define name of file df.to_csv(file_name, sep='\t') # save output in .csv file
72dc44e6be256b1d0c7fb04e8a782c088e10e85f
mazerlodge/MrRobot
/DarleneDecode.py
3,553
3.703125
4
#!/usr/local/opt/python/bin/python3.7 # Version: 20170707-1815 # Opens data file and outputs first two letters of every sixth word. import sys from ArgTools import ArgParser # Hard coded constants DATA_FILE__MAC = "./darlene_code.txt" DATA_FILE__WIN = ".\\darlene_code.txt" # Setup variables osType = "NOT_SET" dataPath = "NOT_SET" bDataFileSet = False wordIndex = -1 charCount = -1 skipChar = "!" def showUsage(): print("Usage: python DarleneDecode.py [-os {mac | win} | -file datafile.txt] " + "-wordindex n -charcount c [-skipchar g]\n" + "\t -os {mac | win} - Operating system selection (used to set dictionary path).\n" + "\t -file filename.txt - (optional) data file to process.\n" + "\t -wordindex n - process every n words (e.g. n=5, process every fifth word).\n" + "\t -charcount c - retrieve c chars from each word processed.\n" + "\t -skipchar g - (optional) if a target word starts with g, skip that letter when processing.\n") exit() def parseArgs(): # Parse the arguments looking for required parameters. # Return false if any tests fail. global osType, dataPath, bDataFileSet, wordIndex, charCount, skipChar subtestResults = [] rval = True # Instantiate the ArgParser ap = ArgParser(sys.argv) # Check for wordIndex rv = False if (ap.isInArgs("-wordindex", True)): wordIndex = int(ap.getArgValue("-wordindex")) rv = True subtestResults.append(rv) # Check for characterCount rv = False if (ap.isInArgs("-charcount", True)): charCount = int(ap.getArgValue("-charcount")) rv = True subtestResults.append(rv) # Check for data file being specified. if (ap.isInArgs("-file", True)): dataPath = ap.getArgValue("-file") bDataFileSet = True rv = True subtestResults.append(rv) if (not bDataFileSet): # if no data file specified, check for OS type rv = False if (ap.isArgWithValue("-os", "mac") or ap.isArgWithValue("-os", "win")): osType = ap.getArgValue("-os") rv = True subtestResults.append(rv) # Check for optional skipChar if (ap.isInArgs("-skipchar", True)): skipChar = ap.getArgValue("-skipchar") # Determine if all subtests passed for idx in range(len(subtestResults)): rval = rval and subtestResults[idx] return(rval) def getDarleneData(): global dataPath if (not bDataFileSet): # set data path based on OS if (osType == "mac"): dataPath = DATA_FILE__MAC else: dataPath = DATA_FILE__WIN # Read the data file = open(dataPath, "r") lines = file.readlines() file.close() return(lines) def doDarleneDecode(): # Determine if a skip char was specified. bSkipEnabled = False if (skipChar != "!"): bSkipEnabled = True # Load the data into a lines string lines = getDarleneData() words = [] print (len(lines)) # split words, handling multi-line input and stripping excess whitespace for line in lines: if (line[0] != "#"): rawWords = line.split(' ') for aword in rawWords: if (len(aword.strip(' \n\r\t')) > 0): words.append(aword) print(words) # zero based array, so reduce first wordIndex by 1. targetwordindex = wordIndex-1 while (targetwordindex < len(words)): if (bSkipEnabled and (words[targetwordindex][0] == skipChar)): # skip the first char in the word print(words[targetwordindex][1:charCount+1], end="") else: print(words[targetwordindex][0:charCount], end="") targetwordindex += wordIndex print() #### EXECUTION Starts Here #### # Validate startup parameters if (not parseArgs()): showUsage() exit() doDarleneDecode()
39290d24d9e11d27c619d77bbff3c742e54f3a0e
syurskyi/Python_Topics
/070_oop/001_classes/examples/Python_3_Deep_Dive_Part_4/Section 8 Descriptors/103. Properties and Descriptors - Coding.py
7,208
4
4
# %% ''' ### Properties and Descriptors ''' # %% ''' Let's start by creating a property using the decorator syntax: ''' # %% from numbers import Integral class Person: @property def age(self): return getattr(self, '_age', None) @age.setter def age(self, value): if not isinstance(value, Integral): raise ValueError('age: must be an integer.') if value < 0: raise ValueError('age: must be a non-negative integer.') self._age = value # %% p = Person() # %% try: p.age = -10 except ValueError as ex: print(ex) # %% ''' And notice how the instance dictionary does not contain `age`, even though we have that instance `age` attribute: ''' # %% p.age = 10 # %% p.age, p.__dict__ # %% ''' Next, let's rewrite this using a `property` class instead of the decorators: ''' # %% class Person: def get_age(self): return getattr(self, '_age', None) def set_age(self, value): if not isinstance(value, Integral): raise ValueError('age: must be an integer.') if value < 0: raise ValueError('age: must be a non-negative integer.') self._age = value age = property(fget=get_age, fset=set_age) # %% ''' And this works the exact same way as before: ''' # %% p = Person() # %% try: p.age = -10 except ValueError as ex: print(ex) # %% p.age = 10 # %% p.age, p.__dict__ # %% ''' Now, in both cases the property object instance can be accessed by using the class: ''' # %% prop = Person.age # %% prop # %% ''' And this property, is actually a data descriptor! ''' # %% hasattr(prop, '__set__') # %% hasattr(prop, '__get__') # %% ''' In this case, our property has both the `__get__` and `__set__` methods so we ended up with a data descriptor. ''' # %% ''' Even if we only defined a read-only property, we would still end up with a data descriptor: ''' # %% from datetime import datetime class TimeUTC: @property def current_time(self): return datetime.utcnow().isoformat() # %% t = TimeUTC() t.current_time # %% prop = TimeUTC.current_time # %% hasattr(prop, '__get__') # %% hasattr(prop, '__set__') # %% ''' But the internal implemetation of the `__set__` method would refuse to set a value: ''' # %% try: t.current_time = datetime.utcnow().isoformat() except AttributeError as ex: print(ex) # %% ''' So, if properties are implemented using data descriptors - this means that instance attributes with the same name will not shadow the descriptor: ''' # %% t.__dict__ # %% t.__dict__['current_time'] = 'not a time' # %% t.__dict__ # %% t.current_time # %% ''' OK, so given what we know about data descriptors all this should make sense. ''' # %% ''' Now let's try to implement our own version of the property type, decorators and all! ''' # %% class MakeProperty: def __init__(self, fget=None, fset=None): self.fget = fget self.fset = fset def __set_name__(self, owner_class, prop_name): self.prop_name = prop_name def __get__(self, instance, owner_class): print('__get__ called...') if instance is None: return self if self.fget is None: raise AttributeError(f'{self.prop_name} is not readable.') return self.fget(instance) def __set__(self, instance, value): print('__set__ called...') if self.fset is None: raise AttributeError(f'{self.prop_name} is not writable.') self.fset(instance, value) # %% ''' This is now sufficient to start creating properties using this data descriptor: ''' # %% class Person: def get_name(self): return self._name def set_name(self, value): self._name = value name = MakeProperty(fget=get_name, fset=set_name) # %% p = Person() # %% p.__dict__ # %% p.name = 'Guido' # %% p.name # %% ''' And even if we try to shadow the property name in the instance, things will work just fine: ''' # %% p.__dict__['name'] = 'Alex' # %% p.__dict__ # %% p.name # %% ''' Next we would like to have a decorator approach as well. To do that we're going to mimic the way the property decorators work (you may want to go back to those lectures and refresh your memory if needed). ''' # %% ''' So how should the `@MakeProperty` decorator work? It should take a function and return a descriptor object. In turn, that descriptor object should have a `setter` method that we can call to *add* the setter method to the descriptor, that also returns the descriptor object - just like we have with `property` types: ''' # %% class MakeProperty: def __init__(self, fget=None, fset=None): self.fget = fget self.fset = fset def __set_name__(self, owner_class, prop_name): self.prop_name = prop_name def __get__(self, instance, owner_class): print('__get__ called...') if instance is None: return self if self.fget is None: raise AttributeError(f'{self.prop_name} is not readable.') return self.fget(instance) def __set__(self, instance, value): print('__set__ called...') if self.fset is None: raise AttributeError(f'{self.prop_name} is not writable.') self.fset(instance, value) def setter(self, fset): self.fset = fset return self # %% ''' So both the `__init__` and the `setter` methods can be used like decorators, and we can now use our `MakeProperty` class with decorator syntax: ''' # %% ''' We can do it the "long" way first: ''' # %% class Person: def get_first_name(self): return getattr(self, '_first_name', None) def set_first_name(self, value): self._first_name = value def get_last_name(self): return getattr(self, '_last_name', None) def set_last_name(self, value): self._last_name = value first_name = MakeProperty(fget=get_first_name, fset=set_first_name) last_name = MakeProperty(fget=get_last_name, fset=set_last_name) # %% ''' Or, we can use the "shorthand" decorator syntax: ''' # %% class Person: @MakeProperty def first_name(self): return getattr(self, '_first_name', None) @first_name.setter def first_name(self, value): self._first_name = value @MakeProperty def last_name(self): return getattr(self, '_last_name', None) @last_name.setter def last_name(self, value): self._last_name = value # %% p1 = Person() # %% p1.first_name = 'Raymond' # %% p1.last_name = 'Hettinger' # %% p1.first_name # %% p1.last_name # %% ''' And of course this will work with multiple instances of the `Person` class since we are using the instances themselves for the underlying storage: ''' # %% p2 = Person() p2.first_name, p2.last_name = 'Alex', 'Martelli' # %% p1.first_name, p1.last_name, p2.first_name, p2.last_name # %% ''' Of course our implementation is quite simplistic, but it should help solidy our understanding of properties, descriptors, and decorators too! ''' # %%
673e3bade2f90528ce2fac21e928d5db6cf683a7
MarianoAIglesias1994/Data_Analytics
/Exercise_1/Coding_1.py
2,527
3.59375
4
# ------------------------------------------------------------------------------ # Original code # ------------------------------------------------------------------------------ #import random # def weighted_random(values, weights): # total_weight = sum(weights) # In this line and in the following one, a normalization of the weights is carried out. # acum_weights = [w / total_weight for w in weights[:]] # I consider it a good idea, since weights might not be given in a normalized format # as in the example. But the name might be confusing, as the variable is reused in the next lines. # for i in range(len(weights)): # Here it seems that it attempts to obtain the cumulative distribution function # (i.e., the accumulated weights). # acum_weights[i] += acum_weights[i] # But instead, it calculates the double of each element. For instance, in the example # it gets acum_weights = [1.0, 0.6, 0.4]. # rand = random.random() # It generates a random float uniformly distributed in the semi-open range [0.0, 1.0). # This would be the basis to compare against the accumulated weights. # for value, weight in zip(values, acum_weights): # For each pair value - accumulated weight, it will map the cumulative distribution function # to the uniformly distributed random variable. # if weight > rand: # It checks if the random float is below the accumulated weigth. # return value # In that case, the value paired to the accumulated weight should be retrieved. # ------------------------------------------------------------------------------ # Fixed code # ------------------------------------------------------------------------------ import random def weighted_random(values, weights): total_weight = sum(weights) acum_weights = [w / total_weight for w in weights[:]] # The normalization procedure is kept, and the variable name stays the same, in order to change the least in the code. for i in range(1, len(weights)): # This is modified in order to obtain the cumulative distribution function, # the accumulated weights up to the actual weight. # The first accumulated weight will always be the first weight. # The next ones will be obtained as the previous accumulation plus the actual weight. acum_weights[i] += acum_weights[i-1] rand = random.random() # Now, this weighted random sampling has the correct cumulative distribution function, therefore it works accordingly. for value, weight in zip(values, acum_weights): if weight > rand: return value
aeea46377810ce62cccd29f0f33a0e01f132e724
annusingh100995/Data_Analysis
/PARAMETER EVALUATION AND HYPER_PARAMETER_TUNING/data_preprocessing.py
6,773
3.515625
4
import pandas as pd from io import StringIO # Making a sample incomplete data csv_data = \ '''A,B,C,D 1.0,2.0,3.0,4.0 5.0,6.0,,8.0 10.0,11.0,12.0,''' # converting the file into a dataframe for data manipulation df = pd.read_csv(StringIO(csv_data)) #sum: return the number of missing values per column df.isnull().sum() #Elimiating the samples, , drops the row(axis =1) column(axis = 0) where the data is missing df.dropna(axis=0) df.dropna(axis=1) #or drop all , drops all rows and columns where there are missing values df.dropna(how='all') # drops where Nan appers in specific rows, here C df.dropna(subset=['C']) """ # IMPUTING MISSING VALUES from sklearn.impute import SimpleImputer imr = Imputer(missing_values='NaN', strategy='mean',axis=0) imr = imr.fit(df.values) imputed_data = imr.transform(df.values) imputed_data # some library issues """ # Nominal and Ordinal(a comparing order can be defined) Features import pandas as pd df = pd.DataFrame([ ['green','M',10.1,'class1'], ['red','L',13.5,'classs2'], ['blue','XL',15.4,'class1']]) df.columns = ['color','size','price','classlabel'] #MApping ordinal features # Defining a size mapping ruel for nominal reature size, a mapping size dictionary size_mapping ={'XL':3,'L':2, 'M':1} df['size'] = df['size'].map(size_mapping) df # Reversing the mapping back to the original feature # Defining the inverse of the mapping size dictionary inv_size_mapping = {v: k for k , v in size_mapping.items()} df['size'].map(inv_size_mapping) # Encoding class label, useful when there is no need for the label to be in any order, just # distinguished integral labels are good # Creating a mapping dictionary import numpy as np class_mapping = {label:idx for idx ,label in enumerate(np.unique(df['classlabel']))} # using the dictionary to transform the label into integars\\ # The classlabel column of df is mapped to the intergars using the clas mapping dictionary df['classlabel'] =df['classlabel'].map(class_mapping) # reversing the key-values inv_class_mapping = {v:k for k , v in class_mapping.items()} df['classlabel'] = df['classlabel'].map(inv_class_mapping) # Lable Encoder form the sklearn from sklearn.preprocessing import LabelEncoder class_le = LabelEncoder() y = class_le.fit_transform(df['classlabel'].values) y class_le.inverse_transform(y) """ One Hot Encoding the idea here is to create a dummy feature to encode the original feature This is done to ensure that there is no unnecessary comparison happening after feature conversion """ X = df[['color','size','price']].values color_le = LabelEncoder() X[:,0] =color_le.fit_transform(X[:,0]) X from sklearn.preprocessing import OneHotEncoder ohe = OneHotEncoder(categorical_features=[0]) #ohe.fit_transform(X).toarray() # some errror # more convient method to create the dummy features pd.get_dummies(df[['price','color','size']]) # importing the wine data df = pd.read_csv('https://archive.ics.uci.edu/ml/machine-learning-databases/wine/wine.data',header=None) df.columns = ['Class label','Alcohol','Malic acid','Ash','Alcalinity of ash','Magnesium', 'Total phenols', 'Flavanoids','Nonflavanoid phenols','Proanthocyanins','Color intensity','Hue','OD280/OD315 of diluted wines', 'Proline'] # Partioning the data and creating the traning and the test data from sklearn.model_selection import train_test_split X,y = df.iloc[:,1:].values, df.iloc[:,0].values X_train, X_test, y_train, y_test = train_test_split(X,y,test_size=0.3,random_state=0,stratify=y) # stratify ensures that both training and test data set have same class proportion # Scaling the features, min max methods from sklearn.preprocessing import MinMaxScaler mms = MinMaxScaler() X_train_norm = mms.fit_transform(X_train) X_test_norm = mms.transform(X_test) # Scaling via standardisation from sklearn.preprocessing import StandardScaler stdsc = StandardScaler() X_train_std = stdsc.fit_transform(X_train) X_test_std = stdsc.fit_transform(X_test) # Tacking ovefitting by regularisation , using L1 regularisation from sklearn.linear_model import LogisticRegression LogisticRegression(penalty='l1') # lambda is the regularisation parameter, lr = LogisticRegression(penalty='l1',C=1.0) lr.fit(X_train_std, y_train) print('Training accuracy:' , lr.score(X_train_std, y_train)) print('Test accuracy:' , lr.score(X_test_std, y_test)) # to find the intercept lr.intercept_ # Plotting a curve, varying the regularisation strength and plot the regularisaion path # The weight coefficient for different features for differnt regularisation strength import matplotlib.pyplot as plt fig = plt.figure() ax = plt.subplot(111) colors = ['blue','green', 'red','cyan','magenta','yellow','black','pink','lightgreen','lightblue','gray','indigo','orange'] weights , param = [], [] for c in np.arange(-4. , 6.): lr = LogisticRegression(penalty='l1', C= 10.**c, random_state=0) lr.fit(X_train_std, y_train) weights.append(lr.coef_[1]) param.append(10**c) weights = np.array(weights) for column,color in zip(range(weights.shape[1]), colors): plt.plot(param, weights[:,column], label=df.columns[column+1], color=color) plt.axhline(0,color='black',linestyle='--',linewidth=3) plt.xlim([10**(-5), 10**5]) plt.ylabel('weight coefficeient') plt.xlabel('C') plt.xscale('log') plt.legend(loc='lower left') ax.legend(loc='upper center',bbox_to_anchor=(1.38,1.03),ncol=1,fancybox=True) plt.show() """ Assessing the important feature with RANDOM FOREST """ from sklearn.ensemble import RandomForestClassifier feat_labels = df.columns[1:] forest = RandomForestClassifier(n_estimators=500,random_state=1) forest.fit(X_train, y_train) # This is to get hte inportance of each feature of the data, values between 0 and 1 importances = forest.feature_importances_ # Sorting the indices of the features indices = np.argsort(importances)[::-1] for f in range(X_train.shape[1]): print("%2d) %-*s %f" %(f+1, 30, feat_labels[indices[f]], importances[indices[f]])) plt.title('FEATURE IMPORTANCE') plt.bar(range(X_train.shape[1]), importances[indices], align='center') plt.xticks(range(X_train.shape[1]), feat_labels, rotation=90) plt.xlim([-1, X_train.shape[1]]) plt.tight_layout() plt.show() """ Selecting the most important feature""" from sklearn.feature_selection import SelectFromModel sfm = SelectFromModel(forest, threshold=0.1, prefit=True) X_selected = sfm.transform(X_train) print('Number of asmples that meet this criterion:', X_selected.shape[0]) for f in range(X_selected[1]): print("%2d) %-*s %f" %(f+1, 30, feat_labels[indices[f]], importances[indices[f]])) for f in range(X_selected.shape[1]): print(" %2d) -*s %f" %(f+1, 30, feat_labels[indices[f]], importances[indices[f]]))
f9f1a14179463a3fee894e183674aaab442deca2
ZhengLiangliang1996/Leetcode_ML_Daily
/BinarySearch/287_FindTheDuplicateNumber.py
1,259
3.765625
4
#! /usr/bin/env python3 # -*- coding: utf-8 -*- # vim:fenc=utf-8 # # Copyright © 2021 liangliang <liangliang@Liangliangs-Air> # # Distributed under terms of the MIT license. class Solution(object): def findDuplicate(self, nums): """ :type nums: List[int] :rtype: int """ ''' n+1 number, all number in [1, n], definitely one duplicate Requirement: 1. don't change the original list (no sorting, on extra space) 2. lower than O(n^2), can not use brute force Solution: Binary Search Search in [1, n], count midian, iterate the list and count all numbers that is lower or equal to mid, then it means the duplicate appear in [mid+1, n], otherwise it will be in [1, mid) Bound: l -> 1 staring number r -> len(nums) e.g. [3,1,3,4,2] -> 5 search space [l, r) -> [1, 4] ''' l = 1 r = len(nums) while l < r: mid = l + ((r - l) >> 1) cnt = 0 for num in nums: if num <= mid: cnt += 1 if mid >= cnt: l = mid + 1 else: r = mid return l
06391af0fe3b295fe5d777afb23307ae4cece87b
SageBinder/MAT276-Final-Project
/ThrownBallEulerStudentWithDrag.py
14,551
3.546875
4
# Written by Chris McCarthy July 2019 SIMIODE DEMARC # Drag = 0 Student Version #=========================================== for online compilers import matplotlib as mpl #=========================================== usual packages import numpy as np from matplotlib import pyplot as plt import math plt.rcParams.update({'font.size': 12}) class Ball: def __init__(self, x, y, vx, vy, t, m, c): self.x = x self.y = y self.vx = vx self.vy = vy self.t = t self.m = m self.c = c def update_ball(self, delta_t, g, drag=True): self.x = self.x + delta_t * self.vx self.y = self.y + delta_t * self.vy if drag: v = np.sqrt(self.vx ** 2 + self.vy ** 2) Fd = -self.c * (v * v) cos_theta = self.vx / v sin_theta = self.vy / v Fd_x = Fd * cos_theta Fd_y = Fd * sin_theta else: Fd_x = 0 Fd_y = 0 Fg = -g * self.m self.vx = self.vx + delta_t * (Fd_x / self.m) self.vy = self.vy + delta_t * ((Fg + Fd_y) / self.m) self.t = self.t + delta_t def trajectory(ball, g, dt): xvalues = [] yvalues = [] while 0 <= ball.y: ball.update_ball(dt, g, drag=drag) xvalues.append(ball.x) yvalues.append(ball.y) return (xvalues, yvalues) def plot_trajectory(ball, g, dt, drag=True, label=None, style='-', color=None): xvalues = [] yvalues = [] while 0 <= ball.y: ball.update_ball(dt, g, drag=drag) xvalues.append(ball.x) yvalues.append(ball.y) plt.plot(xvalues, yvalues, style, label=label, color=color) def plot_best_ball(x0, y0, speed, dt, get_ball, g, label=None, drag=True): plot_trajectory(find_best_ball(x0, y0, speed, dt, get_ball, drag), g, dt, label, drag) def find_best_ball(x0, y0, speed, dt, get_ball, drag=True): #============================================ Delta t xDistance = [] # store the horizontal distance ball travelled Theta = [] # store the angle the ball is thrown at #============================================ run Euler for theta in [0, 90] for theta in range(0, 90): theta_rads = np.radians(theta) ball = get_ball(x0, y0, t0, speed, theta_rads) # initialize ball object while 0 <= ball.y: # Euler Method applied to that ball ball.update_ball(dt, g, drag=drag) xDistance.append(ball.x) # collect x value when ball hits ground Theta.append(theta_rads) # collect theta #============================================ find max x distance over theta, print it maxpos = xDistance.index(max(xDistance)) #============================================= run Euler (again) for best theta best_theta = Theta[maxpos] best_vx0 = speed*np.cos(best_theta) # initial vx best_vy0 = speed*np.sin(best_theta) # initial vy best_ball = get_ball(x0, y0, t0, speed, best_theta) # initialize ball object return best_ball def find_best_ball_and_theta(x0, y0, speed, dt, get_ball, drag=True): #============================================ Delta t xDistance = [] # store the horizontal distance ball travelled Theta = [] # store the angle the ball is thrown at #============================================ run Euler for theta in [0, 90] for theta in range(0, 90): theta_rads = np.radians(theta) ball = get_ball(x0, y0, t0, speed, theta_rads) # initialize ball object while 0 <= ball.y: # Euler Method applied to that ball ball.update_ball(dt, g, drag=drag) xDistance.append(ball.x) # collect x value when ball hits ground Theta.append(theta_rads) # collect theta #============================================ find max x distance over theta, print it maxpos = xDistance.index(max(xDistance)) #============================================= run Euler (again) for best theta best_theta = Theta[maxpos] best_vx0 = speed*np.cos(best_theta) # initial vx best_vy0 = speed*np.sin(best_theta) # initial vy best_ball = get_ball(x0, y0, t0, speed, best_theta) # initialize ball object return (best_ball, best_theta) d = 1.21 # density of air def create_golf_ball(x0, y0, t0, speed, theta): # Golf ball constants m = 0.046 # mass of ball r = 0.0213 # radius of ball C_d = 0.5 # coefficient of drag c = (C_d * d * np.pi * r * r) / 2 return Ball(x0, y0, speed * np.cos(theta), speed * np.sin(theta), t0, m, c) def create_tennis_ball(x0, y0, t0, speed, theta): # Tennis ball constants m = 0.059 # mass of ball r = 0.0327 # radius of ball C_d = 0.6 # coefficient of drag c = (C_d * d * np.pi * r * r) / 2 return Ball(x0, y0, speed * np.cos(theta), speed * np.sin(theta), t0, m, c) def create_soccer_ball(x0, y0, t0, speed, theta): # Soccer ball constants m = 0.454 # mass of ball r = 0.11 # radius of ball C_d = 0.5 # coefficient of drag c = (C_d * d * np.pi * r * r) / 2 return Ball(x0, y0, speed * np.cos(theta), speed * np.sin(theta), t0, m, c) def create_racquetball(x0, y0, t0, speed, theta): # Racquetball constants m = 0.04 # mass of ball r = 0.026 # radius of ball C_d = 0.5 # coefficient of drag c = (C_d * d * np.pi * r * r) / 2 return Ball(x0, y0, speed * np.cos(theta), speed * np.sin(theta), t0, m, c) def create_ping_pong_ball(x0, y0, t0, speed, theta): # Ping pong ball constants m = 0.0027 # mass of ball r = 0.02 # radius of ball C_d = 0.5 # coefficient of drag c = (C_d * d * np.pi * r * r) / 2 return Ball(x0, y0, speed * np.cos(theta), speed * np.sin(theta), t0, m, c) def create_wiffle_ball(x0, y0, t0, speed, theta): # Wiffle ball constants m = 0.02 # mass of ball r = 0.04 # radius of ball C_d = 1 # coefficient of drag c = (C_d * d * np.pi * r * r) / 2 return Ball(x0, y0, speed * np.cos(theta), speed * np.sin(theta), t0, m, c) def create_shuttlecock(x0, y0, t0, speed, theta): # Shuttlecock constants m = 0.0055 # mass of ball r = 0.068 # radius of ball C_d = 0.6 # coefficient of drag c = (C_d * d * np.pi * r * r) / 2 return Ball(x0, y0, speed * np.cos(theta), speed * np.sin(theta), t0, m, c) g = 9.8 # gravitational acceleration x0 = 0 # initial x position in meters y0 = 2 # initial y position in meters t0 = 0 # initial time in seconds speed = 12 # initial speed of the ball in meters/sec dt = .001 # Delta t dpi = 110 xpixels = 1800 ypixels = 900 def make_fig(): fig = plt.figure(figsize=(xpixels/dpi, ypixels/dpi), dpi=dpi) plt.xlabel("Distance [m]") plt.ylabel("Height [m]") return fig def grid(): plt.grid(linewidth='3', color='black') plt.gca().set_aspect('equal', adjustable='box') def plot_all_balls_at_45(show_fig=True): fig = make_fig() plot_trajectory(create_tennis_ball(x0, y0, t0, 12, np.pi / 4), g, dt, label="Tennis ball") plot_trajectory(create_ping_pong_ball(x0, y0, t0, 12, np.pi / 4), g, dt, label="Ping pong ball") plot_trajectory(create_golf_ball(x0, y0, t0, 12, np.pi / 4), g, dt, label="Golf ball") plot_trajectory(create_soccer_ball(x0, y0, t0, 12, np.pi / 4), g, dt, label="Soccer ball") grid() plt.legend(loc='upper right') plt.title("Different balls thrown at 45 degrees, initial speed of 12 m/s") if show_fig: plt.show() return fig def plot_all_balls_at_ideal(show_fig=True): fig = make_fig() plot_trajectory(find_best_ball(x0, y0, speed, dt, lambda x0, y0, t0, speed, theta: create_tennis_ball(x0, y0, t0, speed, theta)), g, dt, label="Tennis ball") plot_trajectory(find_best_ball(x0, y0, speed, dt, lambda x0, y0, t0, speed, theta: create_ping_pong_ball(x0, y0, t0, speed, theta)), g, dt, label="Ping pong ball") plot_trajectory(find_best_ball(x0, y0, speed, dt, lambda x0, y0, t0, speed, theta: create_golf_ball(x0, y0, t0, speed, theta)), g, dt, label="Golf ball") plot_trajectory(find_best_ball(x0, y0, speed, dt, lambda x0, y0, t0, speed, theta: create_soccer_ball(x0, y0, t0, speed, theta)), g, dt, label="Soccer ball") grid() plt.legend(loc='upper right') plt.title("Different balls thrown at ideal angles, initial speed of 12 m/s") if show_fig: plt.show() return fig def plot_no_drag_ball(color): best_ball, best_theta = find_best_ball_and_theta(x0, y0, speed, dt, lambda x0, y0, t0, speed, theta: create_golf_ball(x0, y0, t0, speed, theta), drag=False) plot_trajectory(best_ball, g, dt, label=f"Without drag, ideal angle ({round(np.degrees(best_theta))} degrees)", color=color, drag=False) plot_trajectory(create_golf_ball(x0, y0, t0, speed, np.pi/4), g, dt, label="Without drag, 45 degrees", color=color, style='--', drag=False) def plot_golf_ball(color): best_ball, best_theta = find_best_ball_and_theta(x0, y0, speed, dt, lambda x0, y0, t0, speed, theta: create_golf_ball(x0, y0, t0, speed, theta), drag=True) plot_trajectory(best_ball, g, dt, label=f"Golf ball with drag, ideal angle ({round(np.degrees(best_theta))} degrees)", color=color, drag=True) plot_trajectory(create_golf_ball(x0, y0, t0, speed, np.pi/4), g, dt, label="Golf ball with drag, 45 degrees", color=color, style='--', drag=True) def plot_racquetball(color): best_ball, best_theta = find_best_ball_and_theta(x0, y0, speed, dt, lambda x0, y0, t0, speed, theta: create_racquetball(x0, y0, t0, speed, theta), drag=True) plot_trajectory(best_ball, g, dt, label=f"Racquetball with drag, ideal angle ({round(np.degrees(best_theta))} degrees)", color=color, drag=True) plot_trajectory(create_racquetball(x0, y0, t0, speed, np.pi/4), g, dt, label="Racquetball with drag, 45 degrees", color=color, style='--', drag=True) def plot_tennis_ball(color): best_ball, best_theta = find_best_ball_and_theta(x0, y0, speed, dt, lambda x0, y0, t0, speed, theta: create_tennis_ball(x0, y0, t0, speed, theta), drag=True) plot_trajectory(best_ball, g, dt, label=f"Tennis ball with drag, ideal angle ({round(np.degrees(best_theta))} degrees)", color=color, drag=True) plot_trajectory(create_tennis_ball(x0, y0, t0, speed, np.pi/4), g, dt, label="Tennis ball with drag, 45 degrees", color=color, style='--', drag=True) def plot_soccer_ball(color): best_ball, best_theta = find_best_ball_and_theta(x0, y0, speed, dt, lambda x0, y0, t0, speed, theta: create_soccer_ball(x0, y0, t0, speed, theta), drag=True) plot_trajectory(best_ball, g, dt, label=f"Soccer ball with drag, ideal angle ({round(np.degrees(best_theta))} degrees)", color=color, drag=True) plot_trajectory(create_soccer_ball(x0, y0, t0, speed, np.pi/4), g, dt, label="Soccer ball with drag, 45 degrees", color=color, style='--', drag=True) def plot_ping_pong_ball(color): best_ball, best_theta = find_best_ball_and_theta(x0, y0, speed, dt, lambda x0, y0, t0, speed, theta: create_ping_pong_ball(x0, y0, t0, speed, theta), drag=True) plot_trajectory(best_ball, g, dt, label=f"Ping pong ball with drag, ideal angle ({round(np.degrees(best_theta))} degrees)", color=color, drag=True) plot_trajectory(create_ping_pong_ball(x0, y0, t0, speed, np.pi/4), g, dt, label="Ping pong ball with drag, 45 degrees", color=color, style='--', drag=True) def plot_wiffle_ball(color): best_ball, best_theta = find_best_ball_and_theta(x0, y0, speed, dt, lambda x0, y0, t0, speed, theta: create_wiffle_ball(x0, y0, t0, speed, theta), drag=True) plot_trajectory(best_ball, g, dt, label=f"Wiffle ball with drag, ideal angle ({round(np.degrees(best_theta))} degrees)", color=color, drag=True) plot_trajectory(create_wiffle_ball(x0, y0, t0, speed, np.pi/4), g, dt, label="Wiffle ball with drag, 45 degrees", color=color, style='--', drag=True) def plot_shuttlecock(color): best_ball, best_theta = find_best_ball_and_theta(x0, y0, speed, dt, lambda x0, y0, t0, speed, theta: create_shuttlecock(x0, y0, t0, speed, theta), drag=True) plot_trajectory(best_ball, g, dt, label=f"Shuttlecock with drag, ideal angle ({round(np.degrees(best_theta))} degrees)", color=color, drag=True) plot_trajectory(create_shuttlecock(x0, y0, t0, speed, np.pi/4), g, dt, label="Shuttlecock with drag, 45 degrees", color=color, style='--', drag=True) def drag_comparison(show_fig=True): fig = make_fig() plot_no_drag_ball('blue') plot_golf_ball('orange') plot_racquetball('brown') plot_tennis_ball('green') plot_soccer_ball('yellow') plot_ping_pong_ball('red') plot_wiffle_ball('pink') plot_shuttlecock('purple') grid() plt.legend(loc='upper right', prop={'size': 7}) plt.title(f"Comparing each ball with drag to ideal no-drag trajectory, initial speed of {speed} m/s") if show_fig: plt.show() return fig def tennis_ball_at_multiple_angles(show_fig=True): plot_trajectory(create_tennis_ball(x0, y0, t0, speed, 0), g, dt, label="0 degrees", style='--', drag=True) plot_trajectory(create_tennis_ball(x0, y0, t0, speed, np.pi/8), g, dt, label="22.25 degrees", style='--', drag=True) plot_trajectory(create_tennis_ball(x0, y0, t0, speed, np.pi/4), g, dt, label="45 degrees", style='--', drag=True) best_ball, theta = find_best_ball_and_theta(x0, y0, speed, dt, lambda x0, y0, t0, speed, theta: create_tennis_ball(x0, y0, t0, speed, theta), drag=True) plot_trajectory(best_ball, g, dt, label=f"Ideal angle ({np.degrees(theta)} degrees)", drag=True) # fig = plot_all_balls_at_45(show_fig=True) # fig.savefig("All balls at 45 degrees.pdf", dpi=dpi) # fig = plot_all_balls_at_ideal(show_fig=True) # fig.savefig("All balls at ideal angle.pdf", dpi=dpi) # fig = drag_comparison() # fig.savefig("Drag comparison.pdf") # SHUTTLECOCK VS GOLF BALL VS NO DRAG make_fig() plot_no_drag_ball('blue') plot_golf_ball('orange') plot_shuttlecock('purple') grid() plt.legend(loc='upper right', prop={'size': 8}) plt.title(f"Shuttlecock vs. Golf Ball vs. No Drag, initial speed of {speed} m/s") plt.savefig("Shuttlecock vs. Golf Ball vs. No Drag.pdf") plt.show() # TENNIS BALL AT MULTIPLE ANGLES, AND AT IDEAL ANGLE # make_fig() # tennis_ball_at_multiple_angles() # grid() # plt.legend(loc='upper right', prop={'size': 8}) # plt.title(f"Tennis ball with drag, multiple angles, initial speed of {speed} m/s") # plt.savefig("Tennis ball at multiple angles.pdf") # plt.show()
1f5cb91d3f23b41b6a9fcbbaa331e9b3bf216360
cxyang/myexercise
/part1.py
330
3.703125
4
# coding=utf-8 class Solution(object): def isAnagram(self, s, t): if len(s) != len(t): return False return sorted(s) == sorted(t) def main(): s = "hello world" t = "world hello" solution = Solution() print(Solution().isAnagram(s, t)) if __name__ == "__main__": main()
9c166bfc1e2f6b9864f3e9975111cb7dfdb25aa8
abhishekkr/tutorials_as_code
/talks-articles/languages-n-runtimes/python/Googles.Python.Class--Day1-and-Day2/day02_eg04.py
547
3.65625
4
#!/usr/bin/env python -tt # List Comprehension def ls_a(): import os import re fylz = os.listdir('/tmp') hidden = [ f for f in fylz if re.search(r'^\.', f)] print sorted(hidden)[0] def main(): lst = ['aaaa', 'b', 'cccccc', 'dd', 'eee'] print lst lst2 = [ len(s) for s in lst ] print "lst2 = [ len(s) for s in a ]", "\n gives\n", lst2 lst3 = [ len(s) for s in lst if len(s) > 2 ] print "lst3 = [ len(s) for s in lst if len(s) > 2 ]", "\n gives\n", lst3 ls_a() if __name__ == '__main__': main()
eb138b8d9396dbb1ab1f35d0d69b6a7f0bb3e63f
hermann-roemer/py_learn
/tktest01.py
1,443
3.84375
4
from tkinter import * import datetime dtm=datetime.datetime.now().strftime("==%A, %d.%m.%Y, %H:%M ==") global ln ln=0 print(ln) def okbtn_pressed(xxx): ln=3 if xxx.num == 1: txt = "LB" elif xxx.num == 2: txt = "MB" elif xxx.num ==3: txt = "RB" else: txt = "Hääää??" txt = txt +": "+ minp01.get() print ( txt) # idx=str(ln)+'.2' idx=END # printing one line (at the END) to the Text ...) mtxt01.insert(idx, txt+"\n") print("::"+etxt.get()) # deleting content of the Entry minp01.delete('0',END) def qbtn_pressed(event): if event.num == 1 or event.num == 3 : print("Quitting...") import sys quit() myapp=Tk() etxt=StringVar() myapp.title("Hermanns TK Window") myapp.geometry("500x300+1000+500") #frm01=Frame(myapp) #frm01.pack tlabel01=Label(myapp,text = "Hello World : ") tlabel01.place(x=0,y=40) # tlabel01.pack() mlb02=Label(myapp,text=dtm) mlb02.place(x=120,y=10) minp01=Entry(myapp, width=60) minp01.place(x=100,y=40) mtxt01=Text(myapp,height= 10, width=40 ) mtxt01.place( x=40, y=80 ) mtxt01.insert(INSERT, 'Hallo...\nAlle\n') ln=0 okbtn=Button(myapp, text="OK") okbtn.place(x=10,y=260) okbtn.bind('<Button>',okbtn_pressed) qbtn=Button(myapp, text="Quit") qbtn.place(x=460,y=260) qbtn.bind('<Button-1>',qbtn_pressed) #qbtn.pack( ) myapp.mainloop() print("BYE...")
99b9f4959c047aa1ad02866b2e8bc086e935d2e1
eugeniodias5/Snake
/snake/snake.py
10,018
3.765625
4
import pygame, sys, random import math WHITE = (255, 255, 255) RED = (255, 0, 0) GREEN = (0, 255, 0) size = width, height = 600, 600 pygame.init() screen = pygame.display.set_mode(size) pygame.display.set_caption('Snake') GREENBLOCKSIDE = 15 SPEEDINCREASE = 0.05 #Speed increased when the snake eats the apple class GreenBlock(): def __init__(self, positionX, positionY, speed, direction): self.COLOR = GREEN self.SIDE = GREENBLOCKSIDE self.position = {"x": positionX, "y": positionY} self.speedXY = {"speedX": speed["speedX"], "speedY": speed["speedY"]} self.direction = direction self.directionChange = [] # Store the direction changes self.directionChangeCounter = [] # Counter that determines when to change direction def setDirection(self, direction, speed): if direction == "UP": if self.direction != "DOWN": # It wont be possible to move the snake down while it's been moving up self.direction = direction self.speedXY["speedX"], self.speedXY["speedY"] = 0, -speed elif direction == "DOWN": if self.direction != "UP": self.direction = direction self.speedXY["speedX"], self.speedXY["speedY"] = 0, speed elif direction == "RIGHT": if self.direction != "LEFT": self.direction = direction self.speedXY["speedX"], self.speedXY["speedY"] = speed, 0 elif direction == "LEFT": if self.direction != "RIGHT": self.direction = direction self.speedXY["speedX"], self.speedXY["speedY"] = -speed, 0 else: raise Exception("Invalid direction!") if direction == self.direction: # direction changed if len(self.directionChangeCounter) == 0: self.directionChangeCounter.append(0) self.directionChange.append(direction) self.directionChangeCounter.append(0) def increaseSpeed(self, speed): if self.direction == "UP": self.speedXY['speedY'] -= speed elif self.direction == "DOWN": self.speedXY['speedY'] += speed elif self.direction == "LEFT": self.speedXY['speedX'] -= speed else: self.speedXY['speedX'] += speed def draw(self): pygame.draw.rect(screen, self.COLOR, (self.position["x"], self.position["y"], self.SIDE, self.SIDE)) class Snake(): def __init__(self): self.size = 1 self.speed = 0.2 self.position = {"x": 50, "y": 50} # Snake is created by default moving to down and speed = 0.5 self.blockList = [GreenBlock(self.position["x"], self.position["y"], {"speedX": 0, "speedY": self.speed}, "DOWN")] def addBlock(self): lastBlock = self.blockList[-1] #Cleaning direction changes from the last block lastBlock.directionChange = [] lastBlock.directionChangeCounter = [] newBlock = GreenBlock(lastBlock.position["x"], lastBlock.position["y"], lastBlock.speedXY, lastBlock.direction) # newBlock.setDirection(lastBlock.direction, self.speed) if lastBlock.direction == "UP": newBlock.position["y"] += newBlock.SIDE elif lastBlock.direction == "DOWN": newBlock.position["y"] -= newBlock.SIDE elif lastBlock.direction == "LEFT": newBlock.position["x"] += newBlock.SIDE else: newBlock.position["x"] -= newBlock.SIDE self.blockList.append(newBlock) def setDirection(self, direction): self.blockList[0].setDirection(direction, self.speed) # Setting the first block of the snake will set the snake's direction def move(self): for i in range(0, len(self.blockList)): if i == 0: pass else: lastBlock = self.blockList[i - 1] lastBlockChanges = len(lastBlock.directionChange) # print("Bloco " + str(i) + " " + str(lastBlock.directionChangeCounter)) if lastBlockChanges > 0: lastBlock.directionChangeCounter[0] += 1 try: lastBlock.directionChangeCounter[lastBlockChanges] += 1 except: pass if lastBlock.directionChangeCounter[0] >= lastBlock.SIDE / self.speed: self.blockList[i].setDirection(lastBlock.directionChange[0], self.speed) lastBlock.directionChangeCounter.pop(0) lastBlock.directionChange.pop(0) if len(lastBlock.directionChangeCounter) > 0 and lastBlock.directionChangeCounter[0] >= 0: lastBlock.directionChangeCounter[0] = (lastBlock.SIDE / self.speed) - \ lastBlock.directionChangeCounter[0] if lastBlock.directionChangeCounter[0] <= 0: lastBlock.directionChangeCounter.pop(0) else: if lastBlock.direction == "UP" or lastBlock.direction == "DOWN": self.blockList[i].position["x"] = lastBlock.position["x"] else: self.blockList[i].position["y"] = lastBlock.position["y"] self.blockList[i].position["x"] += self.blockList[i].speedXY["speedX"] self.blockList[i].position["y"] += self.blockList[i].speedXY["speedY"] self.blockList[i].position["x"] = round(self.blockList[i].position["x"], 2) self.blockList[i].position["y"] = round(self.blockList[i].position["y"], 2) def increaseSpeed(self): self.speed += SPEEDINCREASE # Updating speed of blocks for block in self.blockList: block.increaseSpeed(SPEEDINCREASE) def draw(self): self.move() for block in self.blockList: block.draw() class Apple(): def __init__(self): self.color = RED self.active = True self.size = 50 self.position = {"x": random.randint(0, width - self.size), "y": random.randint(0, height - self.size)} apple_image = pygame.image.load('../image/apple.png') apple_image = pygame.transform.scale(apple_image, (self.size, self.size)) apple_rect = apple_image.get_rect() apple_rect.center = (self.position["x"], self.position["y"]) screen.blit(apple_image, apple_rect) self.appleRect = pygame.Rect(self.position["x"], self.position["y"], self.size, self.size) def draw(self): apple_image = pygame.image.load('../image/apple.png') apple_image = pygame.transform.scale(apple_image, (self.size, self.size)) apple_rect = apple_image.get_rect() apple_rect.center = (self.position["x"] + self.size / 2, self.position["y"] + self.size / 2) screen.blit(apple_image, apple_rect) def checkAppleCollision(apple, snake): appleRect = pygame.Rect(apple.position['x'], apple.position['y'], apple.size, apple.size) snakeHead = pygame.Rect(snake.blockList[0].position['x'], snake.blockList[0].position['y'], snake.blockList[0].SIDE, snake.blockList[0].SIDE) return pygame.Rect.colliderect(appleRect, snakeHead) def checkSnakeCollision(snake): head = pygame.Rect(snake.blockList[0].position['x'], snake.blockList[0].position['y'], snake.blockList[0].SIDE / 2, snake.blockList[0].SIDE / 2) for i in range(1, len(snake.blockList)): blockRect = pygame.Rect(snake.blockList[i].position['x'], snake.blockList[i].position['y'], snake.blockList[i].SIDE / 2, snake.blockList[i].SIDE / 2) if i == 1: pass elif pygame.Rect.colliderect(head, blockRect): return pygame.Rect.colliderect(head, blockRect) return False def checkWallCollision(snake): head = snake.blockList[0] headX, headY = head.position['x'], head.position['y'] if headX < 0 or headY < 0: return True if (headX + head.SIDE) > width or (headY + head.SIDE) > height: return True return False def checkGameOver(snake): return checkSnakeCollision(snake) or checkWallCollision(snake) def gameOver(snake): # print GAME OVER pygame.font.init() myfont = pygame.font.SysFont('Comic Sans MS', 30) textsurface = myfont.render('GAME OVER', False, (255, 0, 0)) # Centering the text screen.blit(textsurface, ((width / 2 - 3 * 30), (height / 2 - 3 * 30))) for block in snake.blockList: block.COLOR = RED snake.draw() snake = Snake() apple = Apple() while 1: screen.fill(WHITE) snake.draw() apple.draw() for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() if event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: sys.exit() if event.key == pygame.K_UP: snake.setDirection("UP") if event.key == pygame.K_DOWN: snake.setDirection("DOWN") if event.key == pygame.K_LEFT: snake.setDirection("LEFT") if event.key == pygame.K_RIGHT: snake.setDirection("RIGHT") if not apple.active: apple = Apple() # Checking if the snake has eaten the apple appleCollision = checkAppleCollision(apple, snake) if appleCollision: apple.active = False snake.increaseSpeed() snake.addBlock() # Checking gameOver if checkGameOver(snake): gameOver(snake) pygame.display.update() while 1: for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() if event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: sys.exit() pygame.display.update()
9a31dd2868530de24759b1a9298fef245f291060
eessm01/100-days-of-code
/e_bahit_data_science/working_strings_replace.py
1,208
3.75
4
"""CIENCIA DE DATOS CON PYTHON by Eugenia Bahit. 2 edition. pages 11-12""" # dar formato a una cadena, sustituyendo texto dinámicamente cadena = 'bienvenido a mi aplicación {0}' print(cadena.format('en Python')) cadena = 'Importe bruto: ${0} + IVA: ${1} = IMPORTE NETO: {2}' print(cadena.format(100,21,121)) cadena = 'Importe bruto: ${bruto} + IVA: ${iva} = Importe neto: {neto}' print(cadena.format(bruto=100, iva=21, neto=121)) print(cadena.format(bruto=100, iva=100 * 21 / 100, neto=100 * 21/ 100 + 100)) # remplazar texto en una cadena buscar = 'nombre apellido' remplazar_por = 'Juan Pérez' cadena = 'Estimado Sr. nombre apellido:'.replace(buscar, remplazar_por) print(cadena) # eliminar caracteres a la izquierda y derecha de una cadena cadena = ' www.eugeniahabit.com ' print(cadena.strip()) cadena = '****www.eugeniahabit.com***' print(cadena.strip('*')) # eliminar caracteres a la izquierda de una cadena cadena = 'www.eugeniahabit.com' print(cadena.lstrip('w.')) cadena = ' www.eugeniahabit.com' print(cadena.lstrip()) # eliminar caracteres a la derecha de una cadena cadena = 'www.eugeniahabit.com' print(cadena.rstrip('.com')) cadena = 'www.eugeniahabit.com ' print(cadena.rstrip())
006640d6b872a7cc369cf7296f3ad3c06028a0a0
Pavan9676/Python-Codes
/BasicProgramOfArrays/AdditionOfSubArray.py
387
3.703125
4
from array import * arr = array('i', []) arr1 = array('i', []) n = int(input("Enter size of array: ")) for i in range(n): x = int(input("Enter next value: ")) arr.append(x) print(arr) a = int(input("Enter starting value: ")) b = int(input("Enter ending value: ")) for i in range(a-1, b): y = arr[i] arr1.append(y) print(arr1) sum = 0 for i in arr1: sum +=i print(sum)
9f53c7e06c61a1ce3d38474d892c726376285cbc
DJV23/DarthVeder
/Programming/ClassesandGraphics.py
2,686
4.0625
4
""" ClassesandGraphics.py Ved Ballary Last edit: 17 November 2017 Version 1 This program randomly moves randomly generated ellipses and rectangles. Sample Python/Pygame Programs Simpson College Computer Science http://programarcadegames.com/ http://simpson.edu/computer-science/ Explanation video: http://youtu.be/vRB_983kUMc """ import pygame import random # Define some colors BLACK = (0, 0, 0) WHITE = (255, 255, 255) GREEN = (0, 255, 0) RED = (255, 0, 0) class Rectangle(object): def __init__(self): self.xmove = random.randrange(1, 700) self.ymove = random.randrange(1,500) self.x = random.randrange(1,700) self.y = random.randrange(1, 500) self.height = random.randrange(20,70) self.width = random.randrange(20,70) self.xvel = random.randrange(-3, 3) self.yvel = random.randrange(-3, 3) self.colour = (random.randrange(0, 255), random.randrange(0, 255), random.randrange(0, 255)) def draw(self,screen): pygame.draw.rect(screen, self.colour, [self.x, self.y, self.height, self.width], 0) def move(self): self.x += self.xvel self.y += self.yvel class Ellipse(Rectangle): def draw(self, screen): pygame.draw.ellipse(screen, self.colour,[self.x, self.y, self.height, self.width], 0 ) def move(self): self.x += self.xvel self.y += self.yvel pygame.init() # Set the width and height of the screen [width, height] size = (700, 500) screen = pygame.display.set_mode(size) pygame.display.set_caption("My Game") # Loop until the user clicks the close button. done = False # Used to manage how fast the screen updates clock = pygame.time.Clock() my_object = Rectangle() or Ellipse() my_list = [] i = 0 for i in range(1000): my_list.append(Rectangle()) my_list.append(Ellipse()) # -------- Main Program Loop ----------- while not done: # --- Main event loop screen.fill(BLACK) for event in pygame.event.get(): if event.type == pygame.QUIT: done = True for my_object in my_list: # --- Game logic should go here # --- Screen-clearing code goes here # Here, we clear the screen to white. Don't put other drawing commands # above this, or they will be erased with this command. # If you want a background image, replace this clear with blit'ing the # background image. # --- Drawing code should go here my_object.draw(screen) my_object.move() # --- Go ahead and update the screen with what we've drawn. pygame.display.flip() # --- Limit to 60 frames per second clock.tick(120) # Close the window and quit. pygame.quit()
bf1d75e197ef97eb8e3e8ab298963c2d16762142
naveenraj93/HackerRank_Interview_Preparation
/Warm-up Challenges/03 Jumping on the Clouds.py
564
3.59375
4
# Enter your code here. Read input from STDIN. Print output to STDOUT noOfClouds = int(input()) cloudArr = input().split() noOfJump = 0 currentCloud = 0 i = 1 twoPlaceFlag= 1 while i < noOfClouds: twoPlaceFlag += 1 if currentCloud == i: pass elif cloudArr[i] == '0': if twoPlaceFlag == 2: noOfJump += 1 twoPlaceFlag = 0 currentCloud += 1 else: noOfJump += 1 currentCloud += 2 twoPlaceFlag = 0 #print(cloudArr[i],i,noOfJump,currentCloud) i+= 1 print(noOfJump)
1f7527eaff36eb0b7599ed6503c9cee825421541
leuduc2002/minhduc
/cai.hinh.canh.hinh.phi.tieu.py
226
3.84375
4
from turtle import * speed(0) for i in range(4): if i % 2 == 0: pencolor("blue") else: pencolor("red") side = i + 3 for _ in range(side): forward(100) left(360 / side) mainloop()
932c40eb454e40ce1e2ffb86d9ef50f8b1489ac7
bramil20/GradueteJavaProject
/Dictionary/Dictionary.py
191
3.875
4
classmates={'Marco':'cool but smells', 'Luca': 'not a good guy', 'Peter':'well known lair'} #print(classmates) #print(classmates['Peter']) for j,k in classmates.items(): print(k+"-"+j)
fc5d705a47143bd8a463b3013da221b729ecba8f
ronys79/DI_Bootcamp
/Week6/hackathon2/calculator.py
3,238
4.15625
4
from tkinter import * root=Tk() root.title("Simple Calculator") e= Entry(root, width=35, borderwidth=5) e.grid(row=0, column=0, columnspan=3) e.insert(0, ' ') def button_click(number): # e.delete(0, END) current = e.get() e.delete(0, END) e.insert(0, str(current) + str(number)) def button_clears(): e.delete(0, END) def b_add(): first_number = e.get() global f_num global math math = "addition" f_num = int(first_number) e.delete(0, END) def b_equal(): second_number = e.get() e.delete(0,END) if math == "multiply": e.insert(0, f_num * int(second_number)) elif math == "subtract": e.insert(0, f_num * int(second_number)) elif math == "divide": e.insert(0, f_num * int(second_number)) elif math == "addition": e.insert(0, f_num + int(second_number)) def b_multiply(): first_number = e.get() global f_num global math math = "multiply" f_num = int(first_number) e.delete(0, END) def b_subtract(): first_number = e.get() global f_num global math math = "subtract" f_num = int(first_number) e.delete(0, END) def b_divide(): first_number = e.get() global f_num global math math = "divide" f_num = int(first_number) e.delete(0, END) # Define buttons button_1 = Button(root, text='1', padx=40, pady=20, command = lambda:button_click(1)) button_2 = Button(root, text='2', padx=40, pady=20, command = lambda:button_click(2)) button_3 = Button(root, text='3', padx=40, pady=20, command = lambda:button_click(3)) button_4 = Button(root, text='4', padx=40, pady=20, command = lambda:button_click(4)) button_5 = Button(root, text='5', padx=40, pady=20, command = lambda:button_click(5)) button_6 = Button(root, text='6', padx=40, pady=20, command = lambda:button_click(6)) button_7 = Button(root, text='7', padx=40, pady=20, command = lambda:button_click(7)) button_8 = Button(root, text='8', padx=40, pady=20, command = lambda:button_click(8)) button_9 = Button(root, text='9', padx=40, pady=20, command = lambda:button_click(9)) button_0 = Button(root, text='0', padx=40, pady=20, command = lambda:button_click(0)) button_sum= Button(root, text='+', padx=39, pady=20, command = b_add) button_sub= Button(root, text='-', padx=41, pady=20, command = b_subtract) button_mul= Button(root, text='x', padx=40, pady=20, command = b_multiply) button_divide= Button(root, text='/', padx=41, pady=20, command = b_divide) button_equal = Button(root, text='=', padx=91, pady=18, command = b_equal) button_clear = Button(root, text='CLEAR', padx=79, pady=17, command = button_clears) # Place buttons in grid button_9.grid(row=1, column=2) button_8.grid(row=1, column=1) button_7.grid(row=1, column=0) button_6.grid(row=2, column=2) button_5.grid(row=2, column=1) button_4.grid(row=2, column=0) button_3.grid(row=3, column=2) button_2.grid(row=3, column=1) button_1.grid(row=3, column=0) button_0.grid(row=4, column=0) button_clear.grid(row=4, column=1, columnspan=2) button_sum.grid(row=5, column=0 ) button_equal.grid(row=5, column=1, columnspan=2) button_sub.grid(row=6, column=0 ) button_mul.grid(row=6, column=1 ) button_divide.grid(row=6, column=2 ) root.mainloop()
8ddc10ac21f3cc069ebd5d5eb3c4aa3fcaddbfa3
tristanbatchler/MATH3302-Scripts
/transmit.py
20,528
3.75
4
from typing import * from math import inf from random import random from itertools import combinations class AmbiguityError(BaseException): """Raised when ambiguity arises and there is no suitable return value""" pass def legal(word: str) -> bool: allowed = '01' for b in word: if b not in allowed: return False return True def uniform_length(*words: str) -> bool: for i in range(len(words) - 1): if len(words[i]) != len(words[i + 1]): return False return True def weight(word: str) -> int: if not legal(word): raise ValueError(f"word '{word}' must consist of bits ('0' or '1')") w = 0 for b in word: if b == '1': w += 1 return w def bitsum2(b1: chr, b2: chr) -> chr: if not legal(b1 + b2): raise ValueError("arguments to add must be bits ('0' or '1')") if b1 + b2 in ('00', '11'): return '0' return '1' def bitdot2(b1: chr, b2: chr) -> chr: if not legal(b1 + b2): raise ValueError("arguments to dot must be bits ('0' or '1')") if b1 + b2 == '11': return '1' return '0' def wordsum2(w1: str, w2: str) -> str: if len(w1) != len(w2): raise ValueError(f"words to add {w1} and {w2} must be of the same length") result = '' for c1, c2 in zip(w1, w2): result += bitsum2(c1, c2) return result def worddot2(w1: str, w2: str) -> str: if len(w1) != len(w2): raise ValueError(f"words to dot {w1} and {w2} must be of the same length") result = '' for b1, b2 in zip(w1, w2): result += bitdot2(b1, b2) return result def bitsumn(bits: str) -> chr: n: int = len(bits) if n == 1: return bits[0] if n == 2: return bitsum2(bits[0], bits[1]) if weight(bits) % 2 == 0: return '0' return '1' def bitdotn(bits: str) -> chr: n: int = len(bits) if n == 1: return bits[0] if n == 2: return bitdot2(bits[0], bits[1]) if ''.join(bits) == '1' * n: return '1' return '0' def wordsumn(*words: str) -> str: if not uniform_length(*words): raise ValueError(f"words to sum {words} must have the same length") n = len(words) if n == 1: return words[0] if n == 2: return wordsum2(words[0], words[1]) wordscpy = [w for w in words] for i in range(n - 1): wordscpy[i + 1] = wordsum2(wordscpy[i], wordscpy[i + 1]) return wordscpy[n - 1] def worddotn(*words: str) -> str: if not uniform_length(*words): raise ValueError(f"words to dot {words} must have the same length") n = len(words) if n == 1: return words[0] if n == 2: return worddot2(words[0], words[1]) wordscpy = [w for w in words] for i in range(n - 1): wordscpy[i + 1] = worddot2(wordscpy[i], wordscpy[i + 1]) return wordscpy[n - 1] def distance2(w1: str, w2: str) -> int: return weight(wordsum2(w1, w2)) def distancen(*codewords: str) -> int: min_dist = inf for w1, w2 in combinations(codewords, 2): d = distance2(w1, w2) if d < min_dist: min_dist = d return min_dist def nearest(*word, others: str) -> str: bestWord = None bestDist = inf for other in others: d = distance2(word, other) if d < bestDist: bestDist = d bestWord = other elif d == bestDist: raise AmbiguityError("multiple nearest words found") return bestWord def g(code: str) -> str: return code + bitsumn(code) def get_codewords(f, inputSize) -> Set[str]: result = set() for i in range(2 ** inputSize): inbits = str(bin(i))[2:] inbits = '0' * (inputSize - len(inbits)) + inbits result.add(f(inbits)) return result def applyError(word: str): erroneous = '' for b in word: if random() < 0.1: b = bitsum2(b, '1') erroneous += b return erroneous def threefold(w): return 3 * w def int2word(n: int, size: int): b = str(bin(n))[2:] padding = '0' * (size - len(b)) return padding + b def bitproduct2(b1: chr, b2: chr): if not legal(b1 + b2): raise ValueError("arguments to add must be bits ('0' or '1')") if b1 + b2 == '11': return '1' return '0' def encode(inputword: str, matrix: Tuple[str]) -> str: if len(matrix) != len(inputword): raise ValueError(f"""incompatible dimensions for multiplication of word {inputword} with matrix {matrix}""") inputsize: int = len(inputword) resultsize: int = len(matrix[0]) for mtxwrd in matrix: if len(mtxwrd) != resultsize: raise ValueError(f"matrix {matrix} has invalid row lengths") result: str = '' # indices of zeros in the input word should be discarded significant_indices = set(i for i in range(inputsize) if inputword[i] == '1') # if the input word is zero, return zero if len(significant_indices) == 0: return '0' * resultsize significant_rows = tuple(row for row in matrix if matrix.index(row) in significant_indices) # return the sum of the leftover rows return wordsumn(*significant_rows) def lindep2(w1: str, w2: str): if not legal(w1 + w2): raise ValueError(f"words '{w1}' and '{w2}' must consist of bits ('0' or '1')") if len(w1) != len(w2): raise ValueError(f"words '{w1}' and '{w2}' must be of the same length") return w1 == w2 def lindepn(*words: str): if not uniform_length(*words): raise ValueError(f"words to check linear dependancy {words} must have the same length") n = len(words) zero = '0' * len(words[0]) if n == 1: w: str = words[0] return w == zero if n == 2: return lindep2(words[0], words[1]) for r in range(2, n + 1): for combination in combinations(words, r): if wordsumn(combination) == zero: return True return False def subspace(*words: str) -> bool: if not uniform_length(*words): raise ValueError(f"words to check subspace {words} must have the same length") n = len(words) l = len(words[0]) zero = '0' * l if zero not in words: return False for r in range(2, n + 1): for combination in combinations(words, r): if wordsumn(combination) not in words: return False return True def span(*words: str) -> List[str]: if not uniform_length(*words): raise ValueError(f"words {words} must have the same length") if lindepn(*words): raise ValueError(f"words {words} must be linearly independant to calculate the span") n = len(words) l = len(words[0]) result = [] for i in range(2**n): newword = '0' * l for j in range(n): if int2word(i, n)[j] == '1': newword = wordsum2(newword, words[j]) result.append(newword) return result def orthog_comp(*codewords: str): if not uniform_length(*codewords): raise ValueError(f"codewords {codewords} must have the same length") G: Iterable[str] = generating_mtx(*codewords) k = len(G) n = len(G[0]) Gp = normalise(*G) # print('\n'.join(Gp)) X = [row[k:] for row in Gp] Hp = X for row in identity(n - k): Hp.append(row) return Hp def identity(n: int): result = [] for i in range(n - 1, -1, -1): result.append(int2word(2**i, n)) return result def transpose(*rows: str): if not uniform_length(*rows): raise ValueError(f"rows {rows} must have the same length") rowcount = len(rows) colcount = len(rows[0]) trows = [] for x in range(colcount): trows.append(''.join([rows[y][x] for y in range(rowcount)])) return trows def normalise(*rows: str) -> Tuple[List[str], Tuple[int]]: """ Returns a tuple containing the normalised matrix as the first element and the permutation steps which occurred on the columns as the second element. E.g. normalise(['100011', '110001', '101001']) returns (['100101', '010101', '001101'], (5, 1)) """ if not uniform_length(*rows): raise ValueError(f"rows {rows} must have the same length") rowcount = len(rows) colcount = len(rows[0]) # List the identity columns which we want to find, # e.g. 1000, 0100, 0010, 0001 id_cols_to_find = identity(rowcount) # Get the indices of the columns which belong to the identity id_col_indices = [] x = 0 # print(f"first col to find: {id_cols_to_find[0]}") while x < colcount: # print(f"start: x={x}") if len(id_cols_to_find) <= 0: break column = ''.join([rows[y][x] for y in range(rowcount)]) if column == id_cols_to_find[0]: id_col_indices.append(x) # print(f"found {id_cols_to_find[0]} at column {x}") # print(f"column {x} ({column}) must go to column {rowcount - len(id_cols_to_find)}") id_cols_to_find.pop(0) x = 0 continue x += 1 # print(f"x+=1") # Get the indices of the remaining columns which don't belong to the identity rest = [] for x in range(colcount): if x not in id_col_indices: rest.append(x) # print(f"column {x} must go to column {rowcount + len(rest) - 1}") # It's easier to work with transposes. We will just transpose the result at the end. t_original_mtx = transpose(*rows) # Stuff the identity columns at the beginning of the new matrix t_normal_mtx = [t_original_mtx[y] for y in id_col_indices] # Stuff the rest of the columns at the end of the new matrix for idx in rest: t_normal_mtx.append(t_original_mtx[idx]) return transpose(*t_normal_mtx) def outer(w1: str, w2: str) -> Tuple[str]: result = [] for i in range(len(w1)): row = "" for j in range(len(w2)): row += bitdot2(w1[i], w2[j]) result.append(row) return tuple(result) def rref(*rows: str) -> Tuple[str]: if not uniform_length(*rows): raise ValueError(f"rows {rows} must have the same length") result = [row for row in rows] rowcount, colcount = len(result), len(result[0]) row = 0 col = 0 while row < rowcount and col < colcount: # find index of largest element in remainder of column j k = -1 for y in range(row, rowcount): val = result[y][col] if val == '1': k = y break if k != -1: column = ''.join([result[y][col] for y in range(rowcount)]) # swap rows if k != row: result[k], result[row] = result[row], result[k] # save the right hand side of the pivot row aijn = ''.join(result[row][col:]) # column we're looking at thiscol = ''.join([result[y][col] for y in range(rowcount)]) # avoid adding pivot row with itself thiscol = thiscol[:row] + '0' + thiscol[row + 1:] flip = outer(thiscol, aijn) for y in range(rowcount): if '1' in flip[y]: lhs = result[y][col:] replacement = wordsum2(result[y][col:], flip[y]) result[y] = result[y][:col] + replacement + result[y][col + len(flip[y]):] # Check if we're done if is_rref(*result): return result row += 1 col += 1 return result def strictly_increasing(numbers: Iterable[int]): for i in range(len(numbers) - 1): if numbers[i] >= numbers[i + 1]: return False return True def is_ref(*rows: str) -> bool: if not uniform_length(*rows): raise ValueError(f"rows {rows} must have the same length") rowcount: int = len(rows) colcount: int = len(rows[0]) zero: str = '0' * colcount # Find the first zero row and make sure all rows below it are also zero for y in range(rowcount - 1): if rows[y] == zero: for below in range(y + 1, rowcount): if rows[below] != zero: return False # Make sure the indices of leading '1's in each non-zero row is strictly increasing leading_indices = [] for y in range(rowcount): if rows[y] != zero: leading_indices.append(''.join(rows[y]).find('1')) return strictly_increasing(leading_indices) def is_rref(*rows: str) -> bool: if not uniform_length(*rows): raise ValueError(f"rows {rows} must have the same length") if not is_ref(rows): return False rowcount: int = len(rows) colcount: int = len(rows[0]) zero: str = '0' * colcount # Make sure the columns containing a leading '1' have '0' everywhere else in the column leading_indices = [] for y in range(rowcount): if rows[y] != zero: leading_indices.append(''.join(rows[y]).find('1')) for x in leading_indices: column = [rows[y][x] for y in range(rowcount)] if column.count('1') > 1: return False return True def generating_mtx(*codewords: str): if not uniform_length(*codewords): raise ValueError(f"codewords {codewords} must have the same length") n = len(codewords[0]) zero = '0' * n mtx = [c for c in codewords] mtx = rref(*mtx) # Remove zero rows mtx = [row for row in mtx if row != zero] return mtx def basis(*codewords: str) -> Set[str]: return set(generating_mtx(*codewords)) def dim(*codewords: str) -> int: return len(basis(*codewords)) def rate(*codewords: str) -> float: if not uniform_length(*codewords): raise ValueError(f"codewords {codewords} must have the same length") n = len(codewords[0]) k = dim(*codewords) return k / n def printmtx(*rows: str) -> None: print('\n'.join(rows)) print() def construct_linear_code(n: int, k: int, d: int) -> List[str]: # Create the parity check: n=16, k=11, d=3 => H is 16x(16-11) = 16x5 cols = n - k zero = '0' * cols H = identity(cols) forbidden = set() forbidden.add(zero) for r in range(1, d - 1): for combination in combinations(H, r): word = wordsumn(*combination) forbidden.add(word) while len(H) < n: # Check if we're trying to kid ourselves... if len(forbidden) >= 2**n: raise ValueError(f"no linear ({n}, {k}, {d})-code exists") # Try adding the sum of of d or more rows of H if it's not forbidden wordToAdd = None for r in range(d - 1, len(H)): for combination in combinations(H, r): word = wordsumn(*combination) if word not in forbidden: wordToAdd = word break if wordToAdd is not None: H.append(wordToAdd) break else: raise ValueError(f"no linear ({n}, {k}, {d})-code exists") # Update the forbidden set for r in range(1, d - 1): for combination in combinations(H, r): word = wordsumn(*combination) forbidden.add(word) # Obtain G from H using standard algorithm X = [H[i] for i in range(cols, len(H))] Hp = X + identity(cols) GpT = identity(k) + transpose(*X) Gp = transpose(*GpT) GT = [GpT[i] for i in range(k, len(GpT))] + identity(k) G = transpose(*GT) return span(*G) def syndrome(w: str, H: Tuple[str]): n = len(w) if len(H) != n: raise ValueError(f"length of word ({len(w)}) must equal rows in parity check matrix ({len(H)})") s = '' # Iterate over the columns of H for i in range(len(H[0])): col = ''.join([row[i] for row in H]) _sum = '0' for i in range(n): prod = bitproduct2(w[i], col[i]) _sum = bitsum2(_sum, prod) s += _sum return s def ext_golay_decode(w: str, logging=False) -> str: if len(w) != 24: raise ValueError(f"{w} must be of length 24") B = [] for i in range(11): b_i = '11011100010' b_i = b_i[i:] + b_i[: i] B.append(b_i) B.append('1' * 11 + '0') for i in range(11): B[i] += '1' B = tuple(B) H = identity(12) + list(B) s = syndrome(w, H) if logging: print(f"Calculated s = wH = {pretty(s)}") if weight(s) <= 3: e = s + '0' * 12 if logging: print(f"||s|| = ||{pretty(s)}|| = {weight(s)} <= 3 so e = (s | 0_12) = {pretty(e)}") print(f"Thus c is w + e = {pretty(w)} + {pretty(e)} = {pretty(wordsum2(w, e))}") print(f"Message is first 12 bits, {pretty(wordsum2(w, e)[:12])}") return wordsum2(w, e)[:12] if logging: print(f"||s|| = ||{pretty(s)}|| = {weight(s)} > 3 so moving on to next check") for j in range(12): if weight(wordsum2(s, B[j])) <= 2: e = wordsum2(s, B[j]) + '0'* j + '1' + '0' * (12 - j - 1) if logging: print(f"||s + bj|| = ||{pretty(s)} + {pretty(B[j])}|| = ||{pretty(wordsum2(s, B[j]))}|| = {weight(wordsum2(s, B[j]))} <= 2 for j = {j + 1}") print(f"So e = (s + bj | theta_j) = {pretty(e)}") print(f"Thus c is w + e = {pretty(w)} + {pretty(e)} = {pretty(wordsum2(w, e))}") print(f"Message is first 12 bits, {pretty(wordsum2(w, e)[:12])}") return wordsum2(w, e)[:12] if logging: for j in range(12): print(f"||s + bj|| = ||{pretty(s)} + {pretty(B[j])}|| = ||{pretty(wordsum2(s, B[j]))}|| = {weight(wordsum2(s, B[j]))} > 2 for j = {j + 1}") print("no luck with s, trying for s'...") sp = syndrome(s, B) if logging: print(f"Calculated s' = sB = {pretty(sp)}") if weight(sp) <= 3: e = '0' * 12 + sp if logging: print(f"||s'|| = ||{pretty(sp)}|| = {weight(sp)} <= 3 so e = (0_12 | s') = {pretty(e)}") print(f"Thus c is w + e = {pretty(w)} + {pretty(e)} = {pretty(wordsum2(w, e))}") print(f"Message is first 12 bits, {pretty(wordsum2(w, e)[:12])}") return wordsum2(w, e)[:12] if logging: print(f"||s'|| = ||{pretty(sp)}|| = {weight(sp)} > 3 so moving on to next check") for j in range(12): if weight(wordsum2(sp, B[j])) <= 2: e = '0'* j + '1' + '0' * (12 - j - 1) + wordsum2(sp, B[j]) if logging: print(f"||s' + bj|| = ||{pretty(sp)} + {pretty(B[j])}|| = ||{pretty(wordsum2(sp, B[j]))}|| = {weight(wordsum2(sp, B[j]))} <= 2 for j = {j + 1}") print(f"So e = (theta_j | s' + bj) = {pretty(e)}") print(f"Thus c is w + e = {pretty(w)} + {pretty(e)} = {pretty(wordsum2(w, e))}") print(f"Message is first 12 bits, {pretty(wordsum2(w, e)[:12])}") return wordsum2(w, e)[:12] if logging: for j in range(12): print(f"||s' + bj|| = ||{pretty(sp)} + {pretty(B[j])}|| = ||{pretty(wordsum2(sp, B[j]))}|| = {weight(wordsum2(sp, B[j]))} > 2 for j = {j + 1}") print("no luck with s', out of options. request retransmission.") raise AmbiguityError(f"More than 3 errors ocurred, can't find suitable decoding") def pretty(w: str) -> None: prettyword = '' for i in range(len(w)): prettyword += w[i] + ' ' * (((i + 1) % 3 == 0) and i != 0 and i != len(w) - 1) return prettyword def golay_decode(w: str, logging=False): if len(w) != 23: raise ValueError(f"{w} must be of length 23") w_star = w + '0' if weight(w) % 2 == 0: w_star = w + '1' if logging: print(f"word {pretty(w)} has even weight, appending a '1' to get w* {pretty(w_star)} (weight {weight(w_star)})") else: if logging: print(f"word {pretty(w)} already has odd weight, appending a '0' to get w* {pretty(w_star)} (weight {weight(w_star)})") if logging: print(f"running extended golay decode on w* = {pretty(w_star)}...") c_star = ext_golay_decode(w_star, logging=logging) return c_star[: -1] w = '110 010 000 000 010 000 001 11'.replace(' ', '') print(pretty(golay_decode(w, logging=True)))
cd3430e18c7fc1b3395c5124712549f73feaadee
wduncan21/Mooc
/EdX/edx_intro_to_data_science/final/f6.py
917
3.75
4
# -*- coding: utf-8 -*- """ Created on Sun May 7 15:29:52 2017 @author: lwang138 """ def find_combination(choices, total): """ choices: a non-empty list of ints total: a positive int Returns result, a numpy.array of length len(choices) such that * each element of result is 0 or 1 * sum(result*choices) == total * sum(result) is as small as possible In case of ties, returns any result that works. If there is no result that gives the exact total, pick the one that gives sum(result*choices) closest to total without going over. """ import itertools import numpy as np bins = np.array(list(itertools.product([0, 1], repeat=len(choices)))) combo=[bin for bin in bins if sum(bin*choices)==total] if combo: return (min(combo,key=sum)) else: return max([bin for bin in bins if sum(bin*choices)<total],key=sum)
81e6dd38cb38a7fee61b4b1e3eac35823d55ba0a
youjin9209/2016_embeded_raspberry-pi
/pythonBasic/grade_elif.py
187
3.71875
4
score = int(input("total")) if score >= 90: print("su") elif 80 <= score < 90: print("wu") elif 70 <= score < 80: print("mi") elif 60 <= score < 70: print("yang") else: print("ga")
b117663558840538a3260aeb97f8d63a832e605c
mcedster/FirstProject
/src/Enemy.py
3,352
3.671875
4
import random class enemy: def __init__(self, name): if name == "imp": self.max_health = 10 self.health = self.max_health self.attack = 0 self.armor = 0 self.magic_resist = 0 self.item = 0 self.speed = 1 self.level = 0 self.exp = 3 self.gold = 5 if name == "slime": self.max_health = 18 self.health = self.max_health self.attack = 0 # cahnge self.armor = 3 self.magic_resist = 1 self.item = 0 self.speed = 2 self.level = 1 self.exp = 5 self.gold = 8 if name == "skeleton": self.max_health = 25 self.health = self.max_health self.attack = 0 self.armor = 3 self.magic_resist = 2 self.item = 0 #after u know how many items u gonna have, put the random int thing here self.speed = 3 self.level = 3 self.exp = 8 self.gold = 12 if name == "vampire-bat": self.max_health = 30 self.health = self.max_health self.attack = 0 self.armor = 3 self.magic_resist = 2 self.item = 0 # after u know how many items u gonna have, put the random int thing here self.speed = 3 self.level = 3 self.exp = 10 self.gold = 14 if name == "basilisk": self.max_health = 40 self.health = self.max_health self.attack = 0 self.armor = 5 self.magic_resist = 5 self.item = 0 # after u know how many items u gonna have, put the random int thing here self.speed = 5 self.level = 5 self.exp = 18 self.gold = 20 if name == "lizard-man": self.max_health = 50 self.health = self.max_health self.attack = 0 self.armor = 6 self.magic_resist = 5 self.item = 0 # after u know how many items u gonna have, put the random int thing here self.speed = 5 self.level = 6 self.exp = 24 self.gold = 28 if name == "minotaur": self.max_health = 70 self.health = self.max_health self.attack = 0 self.armor = 7 self.magic_resist = 5 self.item = 0 # after u know how many items u gonna have, put the random int thing here self.speed = 6 self.level = 7 self.exp = 29 self.gold = 40 if name == "Fusion": self.max_health = 100 self.health = self.max_health self.attack = 0 self.armor = 10 self.magic_resist = 10 self.item = 0 # after u know how many items u gonna have, put the random int thing here self.speed = 10 self.level = 10 self.exp = 50 self.gold = 100 if name == "Jeremy": self.gold = -50 if name == "Mighty-Grey": # boss self.status = 0 #0 is normal, 1 is burned, 2 is paralyzed (might be hard to code), 3 is poisoned,
234dab557674f37573904a83b7f427d116871a0a
Surenu1248/Python_Assignment_Set_2
/21.py
1,047
4.21875
4
#a) Round of the given floating point number. Example: n=0.543 then round it next # decimal number, i.e n=1.0 Use round() function import math,random x = 6.574 print("Round value of {} is: ".format(x), round(x)) # b) Find out the square root of a given number. (Use sqrt(x) function) y = 9 print("Square root of {} is".format(y),math.sqrt(y)) #c) Generate random number between 0, and 1 ( use random() function) print("random value: -->",random.randint(0,1)) # d) Generate random number between 10 and 500. (Use uniform() function) print("uniform value: -->",random.uniform(10,500)) #e) Explore all Math and Random module functions on a given number/ List. a = 2.73 print("ceil value: -->",math.ceil(a)) print ("floor value: -->",math.floor(a)) print ("absolute value: -->",math.fabs(a)) print ("factorial value: -->",math.factorial(int(a))) print ("copysign value: -->",math.copysign(5.5, -10)) print("random value: -->",random.randrange(0, 101, 2)) print("random choie: -->",random.choice(['win', 'lose', 'draw']))
9a84aa60add7d1c70bf405fb9d50719e6faaa686
emmanuelluur/scratch_api
/scratch_api.py
528
3.578125
4
#!/usr/bin/env python # coding: utf-8 import requests # Use scratch api # in request api search user and projects user res = requests.get("https://api.scratch.mit.edu/users/masg92") resP = requests.get(f"https://api.scratch.mit.edu/users/masg92/projects") # store responses on variable as json type user = res.json()['username'] project = resP.json() print(f'Projects on SCRATCH from {user}') # print each project with it's id for item in project: print(f"ID {item['id']} Project Name {item['title']}")
6a7c57027a019ca543eaf27371a639261e050dbc
rakshit6432/HackerRank-Solutions
/Python/06 - Itertools/01 - itertools.product().py
415
3.890625
4
# ======================== # Information # ======================== # Direct Link: https://www.hackerrank.com/challenges/itertools-product/problem # Difficulty: Easy # Max Score: 10 # Language: Python # ======================== # Solution # ======================== from itertools import product A = list(map(int, input().split())) B = list(map(int, input().split())) print(*list(product(A, B)))
cd9f9b3cd7c00e13adfe86c795f452bf73991ebe
srush-shah/Python-Programiz
/Functions/Ex12.py
298
4.25
4
# Python program to find the sum of natural numbers using recursive function def recur_sum(n): if n <= 1: return n else: return n + recur_sum(n-1) # change this value for a different result num = 16 if num < 0: print('Enter a positive number') else: print('The sum is',recur_sum(num))
147a379004cbe2cea6410f9a43f29cc7feb49113
Okeoma/Codility_python
/common_prime_divisors.py
1,037
3.734375
4
def gcd(x, y): # Compute the greatest common divisor if x%y == 0: return y else: return gcd(y, x%y) def hasSamePrimeDivisors(x, y): gcd_value = gcd(x, y) # The gcd contains all # the common prime divisors while x != 1: x_gcd = gcd(x, gcd_value) if x_gcd == 1: # x does not contain any more # common prime divisors break x /= x_gcd if x != 1: # If x and y have exactly the same common # prime divisors, x must be composed by # the prime divisors in gcd_value. So # after previous loop, x must be one. return False while y != 1: y_gcd = gcd(y, gcd_value) if y_gcd == 1: # y does not contain any more # common prime divisors break y /= y_gcd return y == 1 def solution(A, B): count = 0 for x,y in zip(A,B): if hasSamePrimeDivisors(x,y): count += 1 return count
e0829b10c48f89503e0b989d406902a3b5939539
djun02/par-ou-impar
/main.py
760
3.71875
4
from tkinter import * class App: def __init__(self, master = None): self.a = master self.label = Label(self.a) self.label["text"] = "Digite um número" self.label.grid(columnspan=2) self.entry = Entry(self.a) self.entry.grid(row=1, column=1) self.button = Button(self.a) self.button["text"] = "Btn" self.button["command"] = lambda: self.mudaLabel() self.button.grid(row=3,column=1) self.label2 = Label(self.a) self.label["text"] def mudaLabel(self): n = int(self.entry.get()) if n%2 == 0: self.label["text"] ="par" elif n%2 == 1: self.label["text"] = "impar" root = Tk() App(root) root.mainloop()
1c3a4144838f40c30ad9fa490de7350be0a01d12
niranjan-nagaraju/Development
/python/leetcode/reverse_linked_list_ii/reverse_linked_list_ii.py
2,560
4.1875
4
#+encoding: utf-8 ''' https://leetcode.com/problems/reverse-linked-list-ii/ 92. Reverse Linked List II Reverse a linked list from position m to n. Do it in one-pass. Note: 1 ≤ m ≤ n ≤ length of list. Example: Input: 1->2->3->4->5->NULL, m = 2, n = 4 Output: 1->4->3->2->5->NULL ''' # Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None def __str__(self): return str(self.val) class Solution: def reverseBetween(self, head, m, n): """ :type head: ListNode :type m: int :type n: int :rtype: ListNode """ # Nothing to do, start position = end position if m == n: return head i = 1 # positions start at 1 tmp = head prev = None while i < m: prev = tmp tmp = tmp.next i += 1 #print prev return self.reverseNodes(head, prev, n-m) # Start at beforeStart.next and reverse num_nodes (start+num_nodes => end) # readjust links before and after start,end. def reverseNodes(self, head, beforeStart, num_nodes): start = beforeStart.next if beforeStart else head a = start b = a.next i = 0 while i < num_nodes: c = b.next # Make b->a link b.next = a a,b = b,c i += 1 # end is now at a, end's (earlier) next node is at c (also == b) # Adjust beforeStart to point to end, # and start to point to end's next node in the original list start.next = c if beforeStart: # Reversed a fragment of the list not starting at head # head remains unaffected # Establish node before starting position to node after ending position beforeStart.next = a else: # reverse started at head node # changing head node to node num_nodes away in the original list head = a return head # A few helper functions to make testcases easier def printList(head): tmp = head while tmp: print tmp, " -> ", tmp = tmp.next print def fromList(lst): head = ListNode(lst[0]) tail = head for x in lst[1:]: tail.next = ListNode(x) tail = tail.next return head def toList(head): tmp = head lst = [] while tmp: lst.append(tmp.val) tmp = tmp.next return lst if __name__ == '__main__': s = Solution() head = fromList([1,2,3,4,5]) assert(toList(head) == [1,2,3,4,5]) #printList(head) head = s.reverseBetween(head, 1, 4) #printList(head) assert(toList(head) == [4,3,2,1,5]) head = fromList([1,2,3,4,5]) head = s.reverseBetween(head, 2, 4) assert(toList(head) == [1,4,3,2,5]) head = fromList([1,2,3,4,5]) head = s.reverseBetween(head, 1, 5) assert(toList(head) == [5,4,3,2,1])
bc276bf28c174f57cdea272c92e29d04d4b7a940
du-phan/Rosalind
/Enumerating k-mers Lexicographically/solution.py
791
3.515625
4
def enumerate(link): file = open(link,'rU') input = file.readlines() symbol = input[0].split() symbol = ''.join(symbol) n = int(input[-1]) ''' symbol_list = {} counter = 0 for x in symbol: symbol_list[counter] = x counter += 1 ''' result = [[None]*n for i in range(len(symbol)**2)] #*(len(symbol)**2) repeat = 1 counter = 1 for b in range(n-1,-1,-1): x = 1 j = 0 for a in range(len(result)): result[a][b] = symbol[j] #print 'result', result[a][b] x += 1 if x > repeat: x = 1 j = (j+1)%len(symbol) #print result repeat = len(symbol)*counter counter += 1 for i in range(len(result)): output = [] for j in range(n): output.append(result[i][j]) output = ''.join(output) print output enumerate('rosalind_lexf.txt')
b9c23add3801523535e717c66eb6edea19cd9361
zhangyuanqiao93/pyTest
/py1/test.py
3,276
4.03125
4
# print('100+300') # 以#开头的语句是注释,注释是给人看的,可以是任意内容,解释器会忽略掉注释。 # 其他每一行都是一个语句,当语句以冒号:结尾时,缩进的语句视为代码块。 a = 100 if a > 0: print(a) else: print(-a) # //十六进制的123 b = 0x123 # 字符串内部既包含'又包含"怎么办?可以用转义字符\来标识 print('I\'m \"OK\"!') # Python允许用'''...'''的格式表示多行内容 # Python还允许用r''表示''内部的字符串默认不转义 print('''line1 line2 line3''') print(10 // 3) # 地板除//,即两个整数相除还是整数 print(10 % 3) print(True and False) c = 19 if c > 18: print('adult') else: print('child') # Python提供了ord()函数获取字符的整数表示,chr()函数把编码转换为对应的字符 print(ord('我')) print(ord('想')) print(ord('你')) print(chr(25105)) print(chr(24819)) print(chr(20320)) # 如果知道字符的整数编码,还可以用十六进制这么写str: print('\u4e2d\u6587') # 两种写法完全是等价的 # 由于Python的字符串类型是str,在内存中以Unicode表示,一个字符对应若干个字节。 # 如果要在网络上传输,或者保存到磁盘上,就需要把str变为以字节为单位的bytes。 # 区分'ABC'和b'ABC',前者是str ,后者是一个字节一个字节的 x = b'ABC' # python 对bytes类型的数据用带有b前缀的单引号或者双引号标识 # Unicode表示的str通过encode()方法可以编码为指定的bytes print('ABC'.encode('ascii')) # 纯英文的str可以用ASCII编码为bytes,内容是一样的,含有中文的str可以用UTF-8编码为bytes。 # 含有中文的str无法用ASCII编码,因为中文编码的范围超过了ASCII编码的范围,Python会报错。 # 在bytes中,无法显示为ASCII字符的字节,用\x##显示 # 如果我们从网络或磁盘上读取了字节流,那么读到的数据就是bytes。要把bytes变为str,就需要用decode()方法 print(b'ABC'.decode('ascii')) print(len('abc')) print(len('中文')) # 在utf-8 编码下,一个中文字符占3个字节,而1个英文字符只占用1个字节 print(len('中文'.encode('utf-8'))) # 为了告诉Linux/OS X系统,这是一个Python可执行程序,Windows系统会忽略这个注释; # /usr/bin/env/python3 # 指定编码格式为utf-8,按照UTF-8编码读取源代码 # -*- coding: utf-8 -*- # Python格式化 # 常见的问题是如何输出格式化的字符串。 # 我们经常会输出类似'亲爱的xxx你好!你xx月的话费是xx,余额是xx'之类的字符串, # 而xxx的内容都是根据变量变化的,所以,需要一种简便的格式化字符串的方式 # 用%解决 print('Hello, %s' % ("World"),'今天吃%s'%('冒菜')) print('尊敬的%s'% ("VIP"),'用户','您当月%s'%('话费'),'剩余量不足,请及时充值') print('Hi, %s, you have $%d.' % ('Michael', 1000000)) print('Hi,%s,Nice Shoes,$%d.' % ('Curry',10000)) # 格式化整数和浮点数还可以指定是否补0和整数与小数的位数: # 如果你不太确定应该用什么,%s永远起作用,它会把任何数据类型转换为字符串: print('%2d-%02d'% (3,1)) print('%.2f'%(3.14159))
3c5c9ec4b039d8ec37b361f3aac01f7b700e9827
ApexTone/Learn-Python
/sort.py
812
4.0625
4
def merge(array1, array2): answer = list() while len(array1) > 0 and len(array2) > 0: buffer1 = array1[0] buffer2 = array2[0] if buffer1 <= buffer2: answer.append(buffer1) array1.pop(0) else: answer.append(buffer2) array2.pop(0) while len(array1) > 0: answer.append(array1.pop(0)) while len(array2) > 0: answer.append(array2.pop(0)) return answer def merge_sort(array): n = len(array) if n <= 1: return array middle = n//2 b_array = merge_sort(array[:middle]) c_array = merge_sort(array[middle:]) array_sorted = merge(b_array, c_array) return array_sorted if __name__ == "__main__": array = list(map(int, input().split())) print(merge_sort(array))
e068f81b486aed65e3809d9a36baa0735244f39c
gkotas/ProjectEuler
/problems/pe019.py
1,015
4.09375
4
""" Counting Sundays Problem 19 You are given the following information, but you may prefer to do some research for yourself. 1 Jan 1900 was a Monday. Thirty days has September, April, June and November. All the rest have thirty-one, Saving February alone, Which has twenty-eight, rain or shine. And on leap years, twenty-nine. A leap year occurs on any year evenly divisible by 4, but not on a century unless it is divisible by 400. How many Sundays fell on the first of the month during the twentieth century (1 Jan 1901 to 31 Dec 2000)? """ def answer(): total = 0 # Starting days in the year 1899 # Saturday = 0, Friday = 6 months = [1, 4, 4, 0, 2, 5, 0, 3, 6, 1, 4, 6] # Start in the year 1901 for year in xrange(1, 100): for month in xrange(12): # (Day + Day in 1899 + Year + Leap Years) % 7 = Day of Week if (1 + months[month] + year + year/4) % 7 == 1: total += 1 return total if __name__ == '__main__': print answer()