blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
545k
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
545k
3c55e208d740d938a13acd27fab92876a53c5ab4
MadmanSilver/holbertonschool-higher_level_programming
/0x01-python-if_else_loops_functions/100-print_tebahpla.py
148
3.53125
4
#!/usr/bin/python3 i = 25 while i > -1: if i % 2: m = 97 else: m = 65 print("{}".format(chr(i + m)), end="") i -= 1
53abf3765bba1a488d830c47c04160059cc0b41b
neilwithdata/pythonmorsels
/add/add.py
521
3.53125
4
def add(*matrices): rows, cols = len(matrices[0]), len(matrices[0][0]) # Check all matrices have the same number of rows if not all(len(matrix) == rows for matrix in matrices): raise ValueError("Given matrices are not the same size.") # Check all rows have the same number of columns if not all(len(row) == cols for matrix in matrices for row in matrix): raise ValueError("Given matrices are not the same size.") return [[sum(x) for x in zip(*pair)] for pair in zip(*matrices)]
6f8f84b3ab5f996453a0b5a9dba6a6e858c91f72
SamueldaCostaAraujoNunes/ColorWindowsLed
/color.py
3,710
3.5625
4
from typing import Tuple class Color: def __init__(self, color, standard): self.standard = self.verify_standard(standard) self.color = self.verify_color(color) self.functions_color = {('RGB', 'HEX'): self.rgb_to_hex, ('HEX', 'RGB'): self.hex_to_rgb} def verify_standard(self, standard): padrao = standard.upper() if padrao in {"HEX", "RGB", "HSV"}: return padrao else: raise Exception("Invalid standard") def verify_color(self, color): if self.standard == "HEX": return self.is_hex(color) elif self.standard == "RGB": return self.is_rgb(color) def is_rgb(self, color): if isinstance(color, (list ,tuple)): if len(color) == 3: for espectre in color: if isinstance(espectre, int): if not (espectre >= 0 and espectre <= 255): raise Exception(f"A cor: {color} não corresponde ao padrão RGB, pois o item: {espectre} da lista, está fora do intervalo entre 0 e 255") else: return color else: raise Exception(f"A cor: {color} não corresponde ao padrão RGB, pois o item: {espectre} da lista não é um inteiro") return else: raise Exception(f"A cor: {color} não corresponde ao padrão HEX, pois a quantidade de itens na lista não correspondem ao esperado") else: raise Exception(f"A cor: {color} não corresponde ao padrão RGB, pois não é uma lista ou tupla") def is_hex(self, color): if isinstance(color, str): color = color.lstrip('#') if color.startswith("#") else color if self.__is_hex(color): return '#'+color.upper() else: raise Exception(f"A cor: {color} não corresponde ao padrão HEX, pois não respeita a formatação de um hexadecimal") else: raise Exception(f"A cor: {color} não corresponde ao padrão HEX, pois não é uma string") def __is_hex(self, s): try: int(s, 16) except ValueError: return False return len(s) % 2 == 0 def set_color(self, color, standard): self.standard = self.verify_standard(standard) self.color = self.verify_color(color) def rgb_to_hex(self, color) -> str: r, g, b = color hex_color = f"#{r:02x}{g:02x}{b:02x}" return hex_color.upper() def hex_to_rgb(self, color) -> Tuple[int, int, int]: value = color.lstrip('#') return tuple(int(value[i:i + 2], 16) for i in range(0, 6, 2)) def to_max(self, color, standard) -> Tuple[int, int, int]: if standard == 'RGB': cores = color else: cores = self.functions_color.get((standard, 'RGB'))(color) max_color: int = max(cores) n_cor = tuple(int((cor/max_color)*255) for cor in cores) return n_cor if standard == 'RGB' else self.functions_color.get(('RGB', standard))(n_cor) def get_color(self, standard=None, max=False): if standard is None or self.standard == standard.upper(): return self.to_max(self.color, standard) if max else self.color else: standard = self.verify_standard(standard) n_color = self.functions_color.get((self.standard, standard))(self.color) return self.to_max(n_color, standard) if max else n_color if __name__ == "__main__": color = Color([230,67,0], standard="rgb") print(color.get_color(standard="hex", max=False))
bdcb3a4e53c7632cfa3fd3b3f8f63ed92b749d80
fatecoder/Python-practices
/list_comp.py
206
3.765625
4
#!/bin/python #even_squares = [x%2==0 for x in range(1, 11)] even_squares = [x**2 for x in range(2, 11, 2)] print even_squares even_squares2 = [x**2 for x in range(1, 11) if x%2==0] print even_squares2
f31a63242dae74dcb863f4ff1b4d3b923fe3d22f
fatecoder/Python-practices
/exe7.py
855
4.0625
4
#!/bin/python import math from random import randrange numero = randrange(-100,100) #print dir(math) #print dir(randrange) print "################################################" print "Numero: %i" %numero if numero < 0 : numero = abs(numero) print "La raiz es: %f" %math.sqrt(numero) print "Potencia al cuadrado: %s" %math.pow(numero,2) print "Raiz %s" %type(math.sqrt(numero)) print "Numero %s" %type(numero) def rec() : palabra = raw_input("Ingresa una palabra: ") if palabra.isalpha() : print "Palabra %s" %type(palabra) print "Max: %s" %max(palabra) print "Min: %s" %min(palabra) print "steps %s" %palabra[::2] print min(palabra) + palabra[1:len(palabra)-1] + max(palabra) return True else : print "Tienes que ingresar una palabra valida" return False print rec()
3970e5e6d2fedd9f1eaa243d982d95d8a05322bb
fatecoder/Python-practices
/cadena.py
635
3.84375
4
#!/bin/python str1 = raw_input("Ingresa el primer string: ") str2 = raw_input("Ingresa el segundo string: ") ini = 0 fin = len(str2) acum = 0 def contar_veces (ini, fin, str1, str2, acum): if len(str1) >= fin : #print str1[ini:fin] if str1[ini:fin] == str2 : acum = acum + 1 ini = ini + 1 fin = fin + 1 contar_veces(ini, fin, str1, str2, acum) elif len(str1) < len(str2): print "Error, la primera cadena debe ser la mas grande" else : print "La segunda cadena aparece %i veces dentro de la primera cadena" %acum contar_veces(ini, fin, str1, str2, acum)
aef54f093c26995c87c9e5dadc69fb2a1f453495
chetanbala-thunga/python
/calculator.py
1,519
4.09375
4
calc_on = 1 def addition(): print("Adding two values") first = float(raw_input('What is your first number?')) second = float(raw_input('What is your second number?')) print(first + second) def subtraction(): print("Substracting two values") first = float(raw_input('What is your first number?')) second = float(raw_input('What is your second number?')) print(first - second) def multiplication(): print("Multiplying two values") first = float(raw_input('What is your first number?')) second = float(raw_input('What is your second number?')) print(first * second) def division(): print("Division of two values") first = float(raw_input('What is your first number?')) second = float(raw_input('What is your second number?')) print(first / second) def modulo(): print("Remainder of two values after division") first = float(raw_input('What is your first number?')) second = float(raw_input('What is your second number?')) print(first % second) def count_to_ten(): for number in range (1,11): print(number) def quit(): global calc_on calc_on = 0 def calc_run(): op = raw_input('add, subtract, multiply, divide, modulo, or ten? ') if op == 'add': addition() elif op == 'subtract': subtraction() elif op == 'multiply': multiplication() elif op == 'divide': division() elif op == 'modulo': modulo() elif op == 'ten': count_to_ten() else: quit() while calc_on == 1: calc_run()
1f44db5874020fcf3e221e01bce62b793379be06
W0uterdeBoer/Exercises
/Divisorfinder.py
2,130
3.640625
4
from graphics import * import math max_i = 100 Graph_sides = int(math.sqrt(max_i)) print("Graphsides= ", Graph_sides) win = GraphWin("My bar", Graph_sides * 10, Graph_sides * 10) def main2(): all_divisors = finddivisors(max_i)[0] primes = finddivisors(max_i)[1] i = 0 while i < max_i: assigncolor(i, all_divisors, primes) i += 1 win.getMouse() # pause for click in window win.close() def finddivisors(max_i): primes = [2] divisors = [] i = 0 while i < max_i: i_divisors = [] for k in primes: if div(i, k): i_divisors.append(k) if len(i_divisors) == 0: if i != 1: primes.append(i) divisors.append(i_divisors) i += 1 return divisors, primes def div(i, j): return i % j == 0 def assigncolor(i, all_divisors, primes): primecolors = colorscheme(primes) if len(all_divisors[i]) > 2: draw(i, color_rgb(165, 0, 165)) print(i, (165, 0, 165)) elif i in primes: red = primecolors[primes.index(i)][0] green = primecolors[primes.index(i)][1] blue = primecolors[primes.index(i)][2] draw(i, color_rgb(red, green, blue)) else: k = 0 for j in primes: if j in all_divisors[i]: k += 1 if i != 1 and i != 0: red = primecolors[primes.index(all_divisors[i][0])][0] green = min(255, 50 * k) blue = primecolors[primes.index(all_divisors[i][0])][2] draw(i, color_rgb(red, green, blue)) def draw(i, colour): c = Rectangle(Point((i % Graph_sides) * 10, (i // Graph_sides) * 10), Point(((i % Graph_sides) + 1) * 10, ((i // Graph_sides) + 1) * 10)) c.setFill(colour) c.draw(win) def colorscheme(primes): primecolors = [] k = 0 while k <= len(primes): primecolors.append([255 - int(k * 255 // len(primes)), 0, int(k * 255 // len(primes))]) k += 1 return primecolors main2()
393c711aceaa405d0055b59891fb6e9c5a154b41
TheCDC/cbu_csse_euler
/euler_024/Christopher D Chen/euler_024.py
731
3.65625
4
digits = set(range(10)) def generate_pandigitals(current=None, unused=None): if not current: current = [] if not unused: unused = set(digits) if len(unused) == 1: # yield a single item list # this allows for results to be concatenated yield current + [next(iter(unused))] else: for d in sorted(unused): yield from generate_pandigitals( current + [d], unused.difference({d})) def list_to_num(l, b): n = 0 for i in l: n = n * b + i return n def main(): g = generate_pandigitals() for _ in range(10**6): item = next(g) print(list_to_num(item, 10)) if __name__ == '__main__': main()
f4bb7f1961f46b94961fd5649b09d001e19afed4
TheCDC/cbu_csse_euler
/euler_018/Christopher D Chen/euler_018.py
2,958
3.828125
4
#!/usr/bin/env python3 """ Problem 18: Maximum path sum I By starting at the top of the triangle below and moving to adjacent numbers on the row below, the maximum total from top to bottom is 23. 3 7 4 2 4 6 8 5 9 3 That is, 3 + 7 + 4 + 9 = 23. Find the maximum total from top to bottom of the triangle below: 75 95 64 17 47 82 18 35 87 10 20 04 82 47 65 19 01 23 75 03 34 88 02 77 73 07 63 67 99 65 04 28 06 16 70 92 41 41 26 56 83 40 80 70 33 41 48 72 33 47 32 37 16 94 29 53 71 44 65 25 43 91 52 97 51 14 70 11 33 28 77 73 17 78 39 68 17 57 91 71 52 38 17 14 91 43 58 50 27 29 48 63 66 04 68 89 53 67 30 73 16 69 87 40 31 04 62 98 27 23 09 70 98 73 93 38 53 60 04 23 NOTE: As there are only 16384 routes, it is possible to solve this problem by trying every route. However, Problem 67, is the same challenge with a triangle containing one-hundred rows; it cannot be solved by brute force, and requires a clever method! ;o) """ """ Perhaps begin by collapsing the entire triangle into the second (length-2) row. This would create a score. Choose the options with the highest score. Repeat by collapsing all remaining options into the next row and so on. """ triangle = """ 75 95 64 17 47 82 18 35 87 10 20 04 82 47 65 19 01 23 75 03 34 88 02 77 73 07 63 67 99 65 04 28 06 16 70 92 41 41 26 56 83 40 80 70 33 41 48 72 33 47 32 37 16 94 29 53 71 44 65 25 43 91 52 97 51 14 70 11 33 28 77 73 17 78 39 68 17 57 91 71 52 38 17 14 91 43 58 50 27 29 48 63 66 04 68 89 53 67 30 73 16 69 87 40 31 04 62 98 27 23 09 70 98 73 93 38 53 60 04 23""" triangle = [[int(j) for j in i.strip().split()] for i in triangle.split('\n')] st = sum([sum(i) for i in triangle]) def pairwise(f, it): for i in range(len(it) - 1): yield f(it[i], it[i + 1]) def max_path(tri): t = tri[:] cur = t.pop() while len(t) > 0: cur = pairwise(max, cur) cur = list(map(sum, zip(cur, t.pop()))) return cur # print(cur[0]) def main(): # print(pairwise(max, [8, 5, 3, 9])) print(max_path(triangle)[0]) if __name__ == '__main__': main()
8e0f7f62bebfa5f4aa6c81d91e2b5bdaa09c9ba2
TheCDC/cbu_csse_euler
/euler_027/Chris Nugent/PE27.py
2,070
3.75
4
import functools import multiprocessing import os @functools.lru_cache(maxsize=None) def is_prime(num): if num == 2: return True if num % 2 == 0 or num < 0: return False check = 3 while check * check <= num: if num % check == 0: return False check += 2 return True def f(targs): """Solution is setup in this slightly ugly way since it was modified on a whim to support multiprocessing""" # Even values for b always produce a score of 0, so # we only check odds. a, bmax = targs best_b = None best = -1 for b in range(1, bmax, 2): n = 0 test = b while is_prime(test): n += 1 test = (n * n) + (a * n) + b if n > best: best = n best_b = b return a, best_b, best def g(targs): """Faster version of f, which works by only testing primes. Since f(0) = b, b must be prime for non-zero chains.""" a, bmax = targs bs = primes_up_to(bmax) best_b = None best = -1 for b in bs: n = 0 test = b while is_prime(test): n += 1 test = (n * n) + (a * n) + b if n > best: best = n best_b = b return a, best_b, best @functools.lru_cache(maxsize=None) def primes_up_to(pmax): print('Thread generating primes lower than {}...'.format(pmax)) t = tuple([2] + [n for n in range(1, pmax, 2) if is_prime(n)]) print('Thread found {} primes.'.format(len(t))) return t def main(xmin, xmax, ymax): xs = range(xmin, xmax) ymaxes = [ymax] * (xmax - xmin) threads = os.cpu_count() pool = multiprocessing.Pool(threads) print('Running with up to {} threads...'.format(threads)) m = pool.map(g, zip(xs, ymaxes)) print('Mapping done! Finding maximum...') vals = max(m, key=lambda x: x[2]) print('n^2 + {}n + {} produced {} consecutive primes.'.format(*vals)) if __name__ == '__main__': amin, amax, bmax = -999, 1000, 1001 main(amin, amax, bmax)
da373b579653e76fdfa78659109586dcbdb2ac6c
TheCDC/cbu_csse_euler
/euler_021/Chris Nugent/euler_021.py
502
3.5625
4
from functools import lru_cache from math import ceil def divisors(n): divs = {1} for i in range(2, ceil(n**(1 / 2))): if n % i == 0: divs.update([i, n // i]) return divs @lru_cache(maxsize=None) def d(n): return sum(divisors(n)) def main(n): known = set() for a in range(1, n): b = d(a) db = d(b) if db == a and a != b: known.update([a, b]) return sum(known) if __name__ == "__main__": print(main(10000))
b3c406b38a2a87ec02607ae0c0ea27117bc83c0c
TheCDC/cbu_csse_euler
/euler_005/Christopher D Chen/euler_005.py
1,268
3.84375
4
#!/usr/bin/env python3 def isPrime(n): for i in range(2, int(n**(1 / 2)) + 1): if n % i == 0: return False return True def pfactors(n): res = [] if isPrime(n) or n == 4: return [n] while not isPrime(n): for i in range(2, int(n**(1 / 2)) + 1): if isPrime(i) and n % i == 0: res.append(i) n = n // i res.append(n) return res def numprod(l, default=1): try: p = l[0] for i in l[1:]: p *= i except IndexError: return default return p def main(): # create list of numbers and their prime factors facts = [(i, pfactors(i)) for i in range(1, 21)] """Goal: Keep only the single largest exponent for a given prime factor base. i.e. if we have 12 and 6 which have p. factors [2,2,3] and [2,3], respectively, we want [2,2,3] """ counts = dict() for i in facts: for j in set(i[1]): if isPrime(j): counts.update({j: max(i[1].count(j), counts.get(j, 0))}) out = 1 for i in counts.items(): out *= i[0]**i[1] assert out == 232792560, "incorrect" # found answer on paper print(out) if __name__ == '__main__': main()
4f02459b200b9c61fdc96b717cc339ba9b4271c5
Kimonili/data-structures-and-algorithms-python
/stack_reverse_string.py
696
4.0625
4
from collections import deque class Stack: def __init__(self): self.container = deque() def push(self,val): self.container.append(val) def pop(self): return self.container.pop() def peek(self): return self.container[-1] def is_empty(self): return len(self.container)==0 def size(self): return len(self.container) def reverse_string(self, string): for ch in string: self.push(ch) rev = '' while self.size()!=0: rev += self.pop() return rev if __name__ == '__main__': stack = Stack() print(stack.reverse_string("We will conquere COVID-19")) print(stack.reverse_string("91-DIVOC ereuqnoc lliw eW")) # should return "91-DIVOC ereuqnoc lliw eW"
b53773fbc6ed0d4de74b35df96ee85bb6fc0ceb2
Amagash/machine_learning_ud120
/datasets_questions/explore_enron_data.py
2,015
3.515625
4
#!/usr/bin/python """ Starter code for exploring the Enron dataset (emails + finances); loads up the dataset (pickled dict of dicts). The dataset has the form: enron_data["LASTNAME FIRSTNAME MIDDLEINITIAL"] = { features_dict } {features_dict} is a dictionary of features associated with that person. You should explore features_dict as part of the mini-project, but here's an example to get you started: enron_data["SKILLING JEFFREY K"]["bonus"] = 5600000 """ import pickle import pprint import re enron_data = pickle.load(open("../final_project/final_project_dataset.pkl", "r")) # pprint.pprint (enron_data) print (len(enron_data)) # pprint.pprint (enron_data['GLISAN JR BEN F']) # print (type(enron_data['GLISAN JR BEN F']['salary'])) # print (type(enron_data['GLISAN JR BEN F']['salary']) == int) # print (enron_data['PRENTICE JAMES']['total_stock_value']) # print (enron_data['COLWELL WESLEY']['from_this_person_to_poi']) # pprint.pprint (enron_data['SKILLING JEFFREY K']['total_payments']) # pprint.pprint (enron_data['FASTOW ANDREW S']['total_payments']) # pprint.pprint (enron_data['LAY KENNETH L']['total_payments']) # no_of_features = len(enron_data[enron_data.keys()[0]]) # print (no_of_features) count_salary = 0 count_email = 0 # emails = re.findall(r'[\w\.-]+@[\w\.-]+', str) for element in enron_data: print (enron_data[element]['email_address']) # if enron_data[element]['email_address'] is emails: # print enron_data[element]['email_address'] # if (type(enron_data[element]['salary']) == int): # count_salary += 1 if (enron_data[element]['email_address']) != 'NaN': count_email += 1 # print ("count salary = ", count_salary) print ("count email = ", count_email) # if type(enron_data[element]['salary']) == True: def isValidEmail(email): if len(email) > 7: if re.match("^.+@([?)[a-zA-Z0-9-.]+.([a-zA-Z]{2,3}|[0-9]{1,3})(]?)$", email) != None: return True return False isValidEmail("asffafs")
ea104f260c04d3f7bbf7367f42aa08c55a958f1c
sanjeevs/AlgoByTimPart1
/assignment3/test/test_qsort.py
781
3.609375
4
from qsort.qsort import * import unittest from random import randint class MyTest(unittest.TestCase): def test_qsort1(self): a = [3, 8, 2, 5, 1, 4, 7, 6] num_cmps = 0 qsort(a, 0, len(a) -1, num_cmps) self.assertEqual([1,2,3,4,5,6,7,8], a) def test_rand1(self): randints = [] for _ in range(1000): randints.append(randint(1,9999)) a = randints.copy() num_cmps = 0 qsort(a, 0, len(a) -1, num_cmps) randints.sort() self.assertEqual(a, randints) def test_txt(self): a = [] with open('QuickSort.txt') as file: a = [int(x) for x in file] exp_arr = a.copy() exp_arr.sort() num_cmps = 0 qsort(a, 0, len(a) -1, num_cmps) self.assertEqual(a, exp_arr) if __name__ == "__main__": unittest.main()
b141ddc29c11db608d165e4c1a9062f27671bee6
sanjeevs/AlgoByTimPart1
/assignment3/qsort/qsort.py
2,243
4.1875
4
from math import floor def qsort(a, lhs, rhs, num_cmps): """ Sort the array and record the number of comparisons. >>> a = [2,1] >>> num_cmps = 0 >>> qsort(a, 0, 1, num_cmps) 1 >>> print(a) [1, 2] """ if((rhs - lhs) >= 1): num_cmps += (rhs - lhs) pivot = partition(a, lhs, rhs) num_cmps = qsort(a, lhs, pivot -1, num_cmps) num_cmps = qsort(a, pivot + 1, rhs, num_cmps) return num_cmps def partition(a, lhs, rhs): """ Return the correct position of the pivot element. >>> a = [1] >>> partition(a, 0, 0) 0 >>> a = [2,1] >>> partition(a, 0, 1) 1 >>> print(a) [1, 2] >>> a = [100,101,3,8,2,200,201] >>> partition(a, 2, 4) 3 >>> print(a) [100, 101, 2, 3, 8, 200, 201] """ if(len(a) == 1): return 0 else: #swap(a, lhs, rhs) idx = choose_median_pivot(a, lhs, rhs) swap(a, lhs, idx) pivot = a[lhs] i = lhs + 1 for j in range(lhs+1, rhs+1): if(a[j] < pivot): swap(a, i, j) i += 1 swap(a, lhs, i -1) return i -1 def swap(a, i, j): """ Swap the elements of the arr. >>> a = [1,2,3] >>> swap(a, 1, 2) >>> print(a) [1, 3, 2] """ a[i], a[j] = a[j], a[i] def mid(a, lhs, rhs): """ Return the middle element of arr >>> a = [8,2,4,5,7,1] >>> mid(a, 0, 5) 2 >>> a = [8,2,4,5,7,1] >>> mid(a, 1, 5) 3 """ mid = floor((lhs + rhs)/2) return mid def median_of_3(a): """ Return the median of 3 elements. >>> median_of_3([1, 4, 8]) 4 >>> median_of_3([8, 1, 4]) 4 """ tmp = a.copy() tmp.sort() return tmp[1] def choose_median_pivot(a, lhs, rhs): """ Choose the median of the value. Consider the first, last and middle value of array. Find the median an use that as the pivot. >>> choose_median_pivot([8,2,4,5,7,1], 0, 5) 2 >>> choose_median_pivot(list(range(10)), 1, 5) 3 >>> choose_median_pivot([2,1,4], 0, 2) 0 >>> choose_median_pivot([2,1,4,5], 0, 3) 0 """ mid_idx = mid(a, lhs, rhs) choices = [a[lhs], a[mid_idx], a[rhs]] mid_value = median_of_3(choices) if(mid_value == a[lhs]): return lhs elif(mid_value == a[rhs]): return rhs else: return mid_idx if __name__ == "__main__": import doctest doctest.testmod()
2ed279c417d060bb07233d96fc30feeee8607419
Donicia/Homework3
/PyPoll/main.py
2,051
3.765625
4
import os import csv election_data = r'C:\Users\donic\Desktop\CLASS\RICEHOU201906DATA1\HW\03-Python\Instructions\PyPoll\Resources\election_data.csv' votes = 0 Candidate =[] Candidates = {"Khan":0,"Correy":0,"Li":0,"O'Tooley":0} Candidates_Per = {"Khan":0,"Correy":0,"Li":0,"O'Tooley":0} List = {"Khan", "Correy","Li","O'Tooley"} with open(election_data, newline="") as File: csv_reader = csv.reader(File) next(csv_reader) for row in csv_reader: votes = votes + 1 #The total number of votes each candidate won Candidates[row[2]]+= 1 #The percentage of votes each candidate won for Candidate in Candidates: Candidates_Per[Candidate] = '{:.3%}'.format(Candidates[Candidate]/votes) Winner = max(Candidates, key=lambda i:Candidates[i]) print("Election Results") print("-------------------------") print(f"Total Votes: {votes}") print("-------------------------") print(f"{Candidates}") print(f"{Candidates_Per}") print("-------------------------") print(f"Winner: {Winner}") print("-------------------------") PyPoll = r'C:\Users\donic\Desktop\Homework\Homework 3\Python Homework\PyPoll\election_data.txt' Line_1 = ("Election Results") Line_12 =("-------------------------") Line_2 = (f"Total Votes: {votes}") Line_22 = ("-------------------------") Line_3 = (f"{Candidates}") Line_4 = (f"{Candidates_Per}") Line_5 = ("-------------------------") Line_6 = (f"Winner:{Winner}") LIne_7 = ("-------------------------") with open("PyPoll.txt", "w") as output: output.write(str(Line_1)) output.write('\n') output.write(str(Line_12)) output.write('\n') output.write(str(Line_2)) output.write('\n') output.write(str(Line_22)) output.write('\n') output.write(str(Line_3)) output.write('\n') output.write(str(Line_4)) output.write('\n') output.write(str(Line_5)) output.write('\n') output.write(str(Line_6)) output.write('\n') output.write(str(LIne_7))
d4576d365d88c995dea71cad2dbd05ebe63988e1
abdulahi1000/python-project
/project4-1.py
1,032
3.96875
4
# try exception handling # 1. FileNotFoundError # raised when a file or directory is requested but doesn’t exist. # Example try: file_name = 'myfile.txt' with open(file_name) as f: print(f) except: print("File Not Found") # 2. Exception FileExistsError # Raised when trying to create a file or directory which already exists. # Example: import os try: file_name = 'myfile.txt' os.mkdir('./myfile.txt') except FileExistsError: print("File Exists Error") choose = input('Rewrite y/n') # 3. PermissionError # Raised when trying to run an operation without the adequate access rights # Example import os try: os.mkdir('admin_data', 000) with open('admin_data') as f: print(f) except PermissionError: print("Access denied") # Describe how you might deal with each error if you were writing a large production program. # To deal with error when writting a large program, i will make sure to test the project to ses # the kind of error it's bringing out then write a try-exception block for it.
22e283d052f9b9931bf09c823dfb93dba87b33ed
Aijaz12550/python
/list/main.py
953
4.375
4
######################### ##### remove method ##### ######################### list1 = [ 1, 2, True, "aijaz", "test"] """ list.remove(arg) it will take one item of list as a argument to remove from list """ list1.remove(1) # it will remove 1 from list1 #list1.remove(99) # it will throw error because 99 is not exist print("list1",list1) ######################### ##### sorting list ##### ######################### sorting_list = [1,2 ,33, -44, 108, 9876, -44545, 444] sorting_list.sort() # it will sort the original list print(" sorting_list =",sorting_list) sorted_list = sorted(sorting_list) # it will return the sorted list without changing the original. print("sorted_list = ",sorted_list) ######################### ##### slicing list ##### ######################### s_l1 = [0, 1, 2, 3] s_c = s_l1[:] print("s_c",s_c) list2 = [1] * 3 # [1, 1, 1] list3 = [2,3] list4 = list2 + list3 # [ 1, 1, 1, 2, 3 ] print("list4",list4)
89cfbb12e1226acb21867932f6a1a76557b04214
gainfoe/NguyenQuangAnh_c4t3_S3
/dem_chu_theo_bang_chu_cai.py
282
4.03125
4
str_nhap = sorted(input("Nhap tu: ").lower()) alphabet = "qwertyuiopasdfghjklzxcvbnm" letters = {} for letter in str_nhap: if letter in alphabet and letter not in letters: letters[letter] = [] print("So chu cai la:") for letter in letters: print(letter + ":", str_nhap.count(letter))
88e4b65456f59fc1ef6ba41e469a9c6cddfe2ac7
pdhummel/practice
/leetcode/first-missing-positive.py
1,719
3.75
4
#!/usr/bin/python import sys import time class Solution(object): def firstMissingPositive(self, nums): """ :type nums: List[int] :rtype: int """ found_num = set() missing_num_set = set() missing_num_set.add(1) missing_num = 1 for num in nums: if num > 0: found_num.add(num) if num in missing_num_set: missing_num_set.remove(num) missing_num_list = list(missing_num_set) missing_num_list.sort() if len(missing_num_list) > 0: missing_num = missing_num_list[0] else: missing_num = None if num+1 not in found_num: missing_num_set.add(num+1) if missing_num is None or num+1 < missing_num: missing_num = num+1 return missing_num def main(args): if len(args) > 1: pass start = time.clock() solution = Solution() nums = [1,2,0] nums = [3,4,-1,1] nums = [] nums = [1] nums = [-1,4,2,1,9,10] nums = [44,48,31,53,24,56,6,18,33,20,-5,-2,-2,-2,53,-9,11,13,35,34,22,-6,28,11,44,52,43,42,-9,4,14,45,12,56,41,-4,5,7,42,49,55,47,7,13,55,4,14,9,27,-8,54,-8,13,42,31,17,37] missing_num = solution.firstMissingPositive(nums) print missing_num end = time.clock() elapsed_time = end - start print "The program took " + str(elapsed_time) + " seconds to execute." if __name__ == "__main__": main(sys.argv)
956f4a8497ea4d1dcca292eb4d98009aff89af9d
pdhummel/practice
/reverse_string.py
510
3.75
4
#!/usr/bin/python import sys import ctypes def main(args): if len(args) > 1: reverse_string(args[1]) def reverse_string(str2rev): mutable = ctypes.create_string_buffer(str2rev) for i in range(len(str2rev)): j = len(str2rev) - i - 1 if i >= j: break left = mutable[i] right = mutable[j] mutable[i] = right mutable[j] = left print mutable.value if __name__ == "__main__": main(sys.argv)
4923f19a1086cd3a12203af926840edba8193d3c
RajashriN/CreaTe-Python
/Chapter3_Challenges_HeleenKok.py
6,158
4.5625
5
__author__ = 'heleenkok' #Student Number: S1183435 #Python_Programming Chapter 3 #The end assignment from chapter 3 # Challenges: # 1. Write a program that simulates a fortune cookie. The program should display one of five unique fortunes, at random, each time it’s run. # 2. Write a program that flips a coin 100 times and then tells you the number of heads and tails. # 3. Modify the Guess My Number game so that the player has a limited number of guesses. If the player fails to guess in time, the program should display an appropriately chastising message. # 4. Here’s a bigger challenge. Write the pseudocode for a program where the player and the computer trade places in the number guessing game. That is, the player picks a random number between 1 and 100 that the computer has to guess. Before you start, think about how you guess.If all goes well, try coding the game. # 1. Fortune cookie program # Welcome the user # Pick a random number between 1 and 5 # Pick a fortune, out of five fortunes relating the random number # Print the fortune import random fortune_1="Your shoes will make you happy today." fortune_2="A dream you have will come true." fortune_3="The greatest risk is not taking one." fortune_4="Now is the time to try something new." fortune_5="You are very talented in many ways." print("\tWelcome to the Fortune Cookie program!") print("\nYour fortune cookie says: \n") fort_numb=random.randint(1,5) if fort_numb==1: print(fortune_1) elif fort_numb==2: print(fortune_2) elif fort_numb==3: print(fortune_3) elif fort_numb==4: print(fortune_4) else: print(fortune_5) # 2. Flip a coin program # Explain the game # Set the count number to 1 # Set the heads_value to 0 # Set the tails_value to 0 # while count<=100 # Randomly choose 1 or 2 # If 1 the coin value is heads, add 1 to the heads_value # Elif 2 the coin value is tails, add 1 to the tails_value # Else the coin has a secret value print congratulations your coins is invalid # Add 1 to count. # When count is 100 print: After flipping the coin 100 times we counted (print value heads_value) times heads and (print value tails_value) times tails. print("\n\n\tWelcome to the Flip a Coin Program\n") print("The program will flip a coin 100 time") print("It will count the times it landed on heads and on tails") print("Then it will tell you the exact amounts.\n") count_number=1 heads_value=0 tails_value=0 while count_number<=100: coin_value=random.randint(1,2) count_number+=1 if coin_value==1: heads_value+=1 elif coin_value==2: tails_value+=1 else: print("The coin was so special that it had no head and no tail.") print("After flipping 100 times we counted",heads_value,"times heads and",tails_value,"times tails.\n\n") # 3. Modification to Guess My Number, by giving the user the user 10 times to guess the number # welcome the player to the game and explain it # pick a random number between 1 and 100 # ask the player for a guess # set the number of guesses to 1 # while the number of guesses is smaller then 10 # while the player’s guess does not equal the number # if the guess is greater than the number: tell the player to guess lower # otherwise tell the player to guess higher # get a new guess from the player # increase the number of guesses by 1 # congratulate the player on guessing the number # let the player know how many guesses it took print("\tWelcome to the modified 'Guess My Number'!") print("\nI'm thinking of a number between 1 and 100.") print("Try to guess it in less then 10 attempts.\n") # set the initial values the_number = random.randint(1, 100) # print(the_number) # I used this line to check if it worked guess = int(input("Take a guess: ")) tries = 1 # guessing loop while guess != the_number: tries+=1 if tries>10: # When the user has guessed more then 10 times, print Game Over and break the while loop print("Game Over! It took you more then 10 attempts.\n") break elif guess > the_number: #if the guessed number is bigger, print Lower... print("Lower...") else: #if the guessed number is lower, print higher print("Higher...") guess = int(input("Take a guess: ")) #let the user guess again if guess == the_number: #if the guessed number is correct print the following lines: print("You guessed it! The number was", the_number) print("And it only took you", tries, "tries!\n") print("End of the Guess My Number game, I hope you enjoyed it!\n\n") #4 PC Guess my number # Welcome the player and explain # Let the player give the input for the user_number # Let the PC pick a random_number between 1 and 100 # Set the number of guesses to 1 # While the random_number is not equal to the user_number # Increase the number of guesses by 1 # Set the random_number to a new random number between 1 and 100 # Congratulate the player and let the player know how many guesses it took # Quit the game print("\tWelcome to the NEW 'Guess My Number'!") print("\nThis time we will switch seats! You may pick a number between 1 and 10.") print("And the PC will try to guess it in less then 10 attempts.\n") # Set the initial values user_number = int(input("Pick a number between 1 and 10: ")) times = 1 pc_guess = random.randint(1, 10) # The while loop is used to compare the user_number to the pc_guess while pc_guess != user_number: # when the numbers are not the same run the while loop times+=1 # add 1 to the attempts of the PC if times>10: # When the PC has guessed more then 10 times, congratulate the user and break the while loop print("You win!! It took the PC more then 10 attempts to guess your number!!\n") break pc_guess = random.randint(1, 10) # give a new value to pc_guess print("Is it", pc_guess,"?") print("No.") if pc_guess == user_number: #if the guessed number is correct print the following lines: print("The PC guessed it! The number was", user_number) print("It took", times, "tries!\n") print("End of the NEW Guess My Number game, I hope you enjoyed it!\n\n") #exit statement input("\n\nPress the enter key to exit.")
bfdcdd33e0984845295981c206272ca9f11355b8
DragonKoc/ITEA
/0402/04_function_hard.py
643
3.90625
4
def f(x): return 2*x double = f print(double(2)) ################## print('######') def execute (f,x): return f(x) print(execute(double,5)) ################## print('######') def f(): def g(x): return 3*x return g print(double(2)) print(f()(2)) ################## print('######map') map(double, [1,2,3,4]) print(list(map(double, [1,2,3,4]))) ################## print('######') def odd(x): return x%2 print(odd(2)) print(odd(3)) print(list(filter(odd,[1,2,3,4]))) ################## print('######') import functools def add(x,y): return x + y res1 = functools.reduce(add,[1,2,3,4]) print(res1)
ddf3fbd69841bd21c7108c93b99a9f413b2b589c
DragonKoc/ITEA
/2801/task3_while.py
373
3.71875
4
i = 0 # while i<5: # print(i) # i +=1 # while True: # pass try: while i <= 10: print(1+i) i +=1 if i == 5: print('continue') continue print('after contiue') elif i == 7: print('breack') break except: print('ogo') else: print('nichego ne srabotalo')
4618b3ed36dabcafed233d3e85a1e2c1251b271b
DragonKoc/ITEA
/2002/20_3.py
1,142
3.75
4
class ReprMixin: # только методы без состояний def __repr__(self): return "{}({})".format( self.__class__.__name__, ','.join(f"{name}={value}" for name , value in vars(self).items()) ) class EqMixin: def __eq__(self, other): #vars - все поля и все значения return vars(self) ==vars(other) class Person(ReprMixin, EqMixin): def __init__(self,name,age): # состояние!!!! self.name = name self.age = age # def __repr__(self): #object see # return f"Person({self.name=},{self.age=})" def __str__(self): #first return f"<{self.name}, {self.age}>" # def __eq__(self, other): # if hasattr(other, 'name') and hasattr(other,'age'): # return self.name == other.name and self.age == other.age # if isinstance(other, str): # return self.name == other # return NotImplemented def __lt__(self, other): return self.name < other.name p = Person('Bill',32) print(p) p1 = Person('John',23) p2 = Person('John',23) print(p1==p2)
8e535eee69266f51080a2577c504dbb33bd463d3
DragonKoc/ITEA
/2801/tes1.py
1,134
3.5
4
i = 1000 # while i>100: # print(i, end=' ') # i /=2 for j in 'hello world': if j=='h': continue print(j * 2, end ='') else: print('end with break') a=5 lis = [1,22,333] print(lis) lis.append(56) print(lis) lis.extend([45,34]) print(lis) a = [a + b for a in 'kostya' if a!='s' for b in 'grebenyuk' if b!= 'u'] print(a) print(a.count('yy')) print(a.index('yy')) print(a) try: print(a.index(2)) except ValueError: print('oshubochka') l = [] for i in '12345': l.extend(i) print(l) ii=0 while ii < 5: print(l[ii]) ii+=1 tup = (1,2,3,[4,5]) print(tup) tup[3][0] = 'a' print(tup) d = {'name' : 'koc', 'surname' : 'grebenyuk'} dd = dict(d) print(d) dd['name'] = 5 print(dd) ddd = {a : a ** 2 for a in range(7)} print(ddd) person = {'name' : {'surname' : 'Grebenyuk', 'name': 'Koc'}, 'adress' : ['Kiev', 'Antonovicha', '11'], 'phone' : {'home_phone': '55-55-55', 'work_phone':'33-33-33'}} print(person['name']['name']) print(person['adress'][2]) print(person.values()) print(person.keys()) def func (ak): return ak*2 print(func(2)) a,b,c = input().split (",") print(a,b,c)
43224d710674f33eafd7a5d1b0feb25bfec35141
FlyingEwok/Linear-BinarySearch
/binarysearch.py
1,116
4.21875
4
def binarySearch (list, l, listLength, value): # Set up mid point variable if listLength >= l: midPoint = l + (listLength - l) // 2 if list[midPoint] == value: # return the midpoint if the value is midpoint return midPoint elif list[midPoint] > value: # Do a search to the left of midpoint for value then return that return binarySearch(list, l, midPoint-1, value) else: # Do a search to the right of midpoint for value then return that return binarySearch(list, midPoint + 1, listLength, value) else: # if value not in list then return -1 return -1 searchList = [1, 2, 3, 4, 5, 6, 7, 8, 99] # Ask user for a number try: value = int(input("Enter a number: ")) # perform the binary search on the search list result = binarySearch(searchList, 0, len(searchList)-1, value) # Print the results in a statement if result != -1: print ("Element is at index", result) else: print ("Element is not in list") except ValueError: print("That's no number! Try again.")
499581bb47a86a0632b19edbb323ee8237da9dd6
jmfuch02/advent2018
/advent2-1.py
754
3.8125
4
def compute_checksum(input: list): two_times: int = 0 three_times: int = 0 for item in input: counter = {} for letter in item: if letter not in counter: counter[letter] = 1 else: counter[letter] += 1 if 2 in counter.values(): two_times += 1 if 3 in counter.values(): three_times += 1 checksum: int = two_times * three_times return checksum checklist = [ 'abcdef', 'bababc', 'abbcde', 'abcccd', 'aabcdd', 'abcdee', 'ababab', ] assert compute_checksum(checklist) == 12 boxes = [] with open('input2.txt') as f: for line in f: boxes.append(line) print(compute_checksum(boxes))
a525a1d61778c525286ec01c6cff5ab887a9d90e
Wsky51/ML-DL_MyselfCodes
/各种权重初始化方法.py
5,056
3.53125
4
#对比几种初始化方法 import numpy as np import matplotlib.pyplot as plt #1,初始化为0 def initialize_parameters_zeros(layers_dims): """ Arguments: layer_dims -- python array (list) containing the size of each layer. Returns: parameters -- python dictionary containing your parameters "W1", "b1", ..., "WL", "bL": W1 -- weight matrix of shape (layers_dims[1], layers_dims[0]) b1 -- bias vector of shape (layers_dims[1], 1) ... WL -- weight matrix of shape (layers_dims[L], layers_dims[L-1]) bL -- bias vector of shape (layers_dims[L], 1) """ parameters = {} L = len(layers_dims) # number of layers in the network for l in range(1, L): parameters['W' + str(l)] = np.zeros((layers_dims[l], layers_dims[l - 1])) parameters['b' + str(l)] = np.zeros((layers_dims[l], 1)) return parameters #2,随机初始化 def initialize_parameters_random(layers_dims): """ Arguments: layer_dims -- python array (list) containing the size of each layer. Returns: parameters -- python dictionary containing your parameters "W1", "b1", ..., "WL", "bL": W1 -- weight matrix of shape (layers_dims[1], layers_dims[0]) b1 -- bias vector of shape (layers_dims[1], 1) ... WL -- weight matrix of shape (layers_dims[L], layers_dims[L-1]) bL -- bias vector of shape (layers_dims[L], 1) """ np.random.seed(3) # This seed makes sure your "random" numbers will be the as ours parameters = {} L = len(layers_dims) # integer representing the number of layers for l in range(1, L): parameters['W' + str(l)] = np.random.randn(layers_dims[l], layers_dims[l - 1])*0.01 parameters['b' + str(l)] = np.zeros((layers_dims[l], 1)) return parameters #3,xavier initialization def initialize_parameters_xavier(layers_dims): """ Arguments: layer_dims -- python array (list) containing the size of each layer. Returns: parameters -- python dictionary containing your parameters "W1", "b1", ..., "WL", "bL": W1 -- weight matrix of shape (layers_dims[1], layers_dims[0]) b1 -- bias vector of shape (layers_dims[1], 1) ... WL -- weight matrix of shape (layers_dims[L], layers_dims[L-1]) bL -- bias vector of shape (layers_dims[L], 1) """ np.random.seed(3) parameters = {} L = len(layers_dims) # integer representing the number of layers for l in range(1, L): parameters['W' + str(l)] = np.random.randn(layers_dims[l], layers_dims[l - 1]) * np.sqrt(1 / layers_dims[l - 1]) parameters['b' + str(l)] = np.zeros((layers_dims[l], 1)) return parameters #4,He initialization def initialize_parameters_he(layers_dims): """ Arguments: layer_dims -- python array (list) containing the size of each layer. Returns: parameters -- python dictionary containing your parameters "W1", "b1", ..., "WL", "bL": W1 -- weight matrix of shape (layers_dims[1], layers_dims[0]) b1 -- bias vector of shape (layers_dims[1], 1) ... WL -- weight matrix of shape (layers_dims[L], layers_dims[L-1]) bL -- bias vector of shape (layers_dims[L], 1) """ np.random.seed(3) parameters = {} L = len(layers_dims) # integer representing the number of layers for l in range(1, L): parameters['W' + str(l)] = np.random.randn(layers_dims[l], layers_dims[l - 1]) * np.sqrt(2 / layers_dims[l - 1]) parameters['b' + str(l)] = np.zeros((layers_dims[l], 1)) return parameters def relu(Z): """ :param Z: Output of the linear layer :return: A: output of activation """ A = np.maximum(0,Z) return A def initialize_parameters(layer_dims): """ :param layer_dims: list,每一层单元的个数(维度) :return:dictionary,存储参数w1,w2,...,wL,b1,...,bL """ np.random.seed(3) L = len(layer_dims)#the number of layers in the network parameters = {} for l in range(1,L): parameters["W" + str(l)] = np.random.randn(layer_dims[l],layer_dims[l-1])*np.sqrt(2 / layer_dims[l - 1]) parameters["b" + str(l)] = np.zeros((layer_dims[l],1)) return parameters def forward_propagation(initialization="he"): data = np.random.randn(1000, 100000) # 数据 layers_dims = [1000,800,500,300,200,100,10] # 每层节点个数 num_layers = len(layers_dims) # 总共7层数据 # Initialize parameters dictionary. if initialization == "zeros": parameters = initialize_parameters_zeros(layers_dims) elif initialization == "random": parameters = initialize_parameters_random(layers_dims) elif initialization == "xavier": parameters = initialize_parameters_xavier(layers_dims) elif initialization == "he": parameters = initialize_parameters_he(layers_dims) A = data for l in range(1,num_layers): A_pre = A W = parameters["W" + str(l)] # 从参数字典中获取权重 b = parameters["b" + str(l)] # 从参数字典中获取偏值 z = np.dot(W,A_pre) + b # 计算z = wx + b # A = np.tanh(z) #relu activation function A = relu(z) # 激活 plt.subplot(2,3,l) # 两行三列 plt.hist(A.flatten(),facecolor='g') plt.xlim([-1,1]) plt.yticks([]) plt.show() if __name__ == '__main__': forward_propagation("he")
e840a4beac5dc3f15f45923bcfd33f3509df09f2
archanrr/Python-Programs
/Convert_sentence_to_morse.py
856
3.734375
4
import json import sys def main(): print("Welcome to Morse command prompt") input_string = input("Enter the sentence: ") # Getting input from user print("\nMorse code for {} is".format(input_string)) input_string = input_string.lower() # open json file as object with open('moorse-code', 'r') as f: data = json.load(f) # Morse coe for sentence morse_list = [] for character in input_string: if character != ' ': morse_list.append(data[character]) else: morse_list.append(data["space"]) print(''.join(morse_list)) if __name__ == "__main__": while 1: try: main() except KeyboardInterrupt: print("\nQuitting the command") sys.exit() except KeyError: print("Error: Unused charcter")
0c98cf632b5e8638d1eb2e1f576b0bf667c10fe1
YunusEmreAlps/Python-Basics
/3. Advanced/Inheritence.py
2,315
4.25
4
# Inheritence (Kalıtım) # Inheritance belirttiğimiz başka classlardaki method ve attribute'lara erişmemizi sağlar. # Diyelim ki farklı tipte çalışanlar yaratmak istiyorum IT ve HR olsun. class Employee: raise_percent = 0.5 num_emp = 0 def __init__(self, name, last, age, pay): self.name = name self.last = last self.age = age self.pay = pay Employee.num_emp += 1 def apply_raise(self): self.pay += (self.pay * Employee.raise_percent) # self.raise_percent @classmethod def set_raise(cls, amount): cls.raise_percent = amount @classmethod def from_string(cls, userstr): name, last, age, pay = userstr.split('-') return cls(name, last, int(age), float(pay)) @staticmethod def holiday_print(day): if(day == "weekend"): print("This is an off day") else: print("This is not an off day") emp_1 = Employee("Yunus Emre", "Alpu", 22, 5000) emp_2 = Employee("Yusuf Emre", "Alpu", 28, 4000) # Hangi class'tan inherit etmek istediğimizi parantezin içine yazıyoruz. # Inherit ettiğimiz class'a super/parent class, inherit edene de child/subclass deniyor. class IT(Employee): raise_percent = 1.2 def __init__(self, name, last, age, pay, lang): super().__init__(name, last, age, pay) self.lang = lang pass # Employee raise_percent attribute'unu kullanmak yerine içine belirtiğimizi kullanıyor. Kendi içerisinde bulabilirse kullanıyor. Bulamazsa inherit ettiği yere bakıyor. # IT'nin içine hiç bir şey yazmasak da, Employee'nin özelliklerine erişimi var. # IT içerisinde bulamazsa aradığını, inherit ettiği yere gidip bakacak. IT'nin içerisinde __init__ methodu yok.O yüzden Employee classının içine bakacak. it_1 = IT("Yunus", "Alp", 22, 10000, "Python") print(it_1.__dict__) class IK(Employee): raise_percent = 1.5 def __init__(self, name, last, age, pay, experience): super().__init__(name, last, age, pay) self.experience = experience def print_exp(self): print(f"This employee has {self.experience} years of experience") pass ik_1 = IK("Yun", "Alp", 22, 10000, 10) print(ik_1.__dict__)
62237ae4ae5033ecf30d2f578aae1a909e34d42b
YunusEmreAlps/Python-Basics
/2. Basic/Non-scalar Veri Tiplerinde For.py
1,761
3.859375
4
# Non-Scalar For # --------- List --------- grades = [90, 72, 81, 77] for i in grades: print(i) # 90 # 72 # 81 # 77 total = 0 for i in grades: total += i average = (total / (len(grades))) print("Average: "+str(average)) for i in range(len(grades)): print("Iteration :"+str(i)) print(grades) # [90, 72, 81, 77] for i in range(len(grades)): grades[i] += 5 print(grades) # [95, 77, 86, 82] # (Continue) grades = [90, 72, 81, 77] print(grades) # [90, 72, 81, 77] for i in range(len(grades)): print(grades[i]) if(i == 1): continue grades[i] += 5 print(grades) # [95, 72, 86, 82] # (Break) user = int(input("Number: ")) nums = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] for i in range(len(nums)): print(nums[i]) if(nums[i] == user): print("Found it!") break print(nums) # [95, 72, 86, 82] # --------- Tuple --------- tList = (1, 2, 3, 4) for i in tList: print(i) # 1 # 2 # 3 # 4 total = 0 for i in tList: total += i print(total) # 10 total = 0 for i in range(len(tList)): total += tList[i] print(total) # 10 # --------- Dictionary --------- students = { "student_1": [90,89], "student_2": [80,83], "student_3": [72,71] } for i in students: print(i) # student_1 # student_2 # student_3 for i in students: print(students[i]) # [90, 89] # [80, 83] # [72, 71] for i in students.values(): print(i) # [90, 89] # [80, 83] # [72, 71] students = { "student_1": 90, "student_2": 80, "student_3": 72 } for i in students: if(students[i] > 85): print(i) for k, v in students.items(): print("Key: "+str(k)+", Value: "+str(v))
c0b54db814c2b03264b46d1ee6868d09aae6e11d
YunusEmreAlps/Python-Basics
/2. Basic/Patika.py
1,022
4.03125
4
# PROJECT flat_list = [] # Q1: Bir listeyi düzleştiren (flatten) fonksiyon yazın. # Elemanları birden çok katmanlı listelerden ([[3],2] gibi) oluşabileceği gibi, non-scalar verilerden de oluşabilir. # input: [[1,'a',['cat'],2],[[[3]],'dog'],4,5] # output: [1,'a','cat',2,3,'dog',4,5] def solution1(arr): # iterating over the data for i in arr: # checking for list if(type(i) == list): solution1(i) else: flat_list.append(i) pass # Q2 # input : [[1, 2], [3, 4], [5, 6, 7]] # output : [[7, 6, 5], [4, 3], [2, 1]] def solution2(arr): reverse_list = list() for i in range(len(arr)-1, -1, -1): temp = list() for j in range(len(arr[i])-1, -1, -1): temp.append(arr[i][j]) reverse_list.append(temp) return reverse_list pass arr1 = [[1, 'a', ['cat'], 2], [[[3]], 'dog'], 4, 5] arr2 = [[1, 2], [3, 4], [5, 6, 7]] solution1(arr1) print(flat_list) print(solution2(arr2))
15bf570be794b9919f43b5786f61a8a97eb81d31
YunusEmreAlps/Python-Basics
/2. Basic/Output.py
1,846
4.34375
4
# -------------------- # Example 1 (Output) # This is comment """ This is multi-line comments """ # if you want to show something on console # you need to use a "print" instruction # syntax: # print('Message') -> single quotes # print("Message") -> double quotes print(' - Hello World!') print(" - I love Python programming language.") # ---------- # print('I'm Yunus Emre') syntax error print(" - I'm Yunus Emre") print(" - I'm student of computer engineer.") # ---------- # print("George always says "I love you"") syntax error print(' - George always says "I love you"') print(' - “Be the change that you wish to see in the world.” Mahatma Gandhi') # ---------- # Escape sequence syntax : # \n -> new line # \t -> tab # \r -> return # \\ -> backslash # ---------- print(" - first line \n") print("\n - second line") # first line # (new line) # (new line) # second line # ---------- print(" - A \t B \t C \n") # ---------- # This is important # _-_Avatar (return) # _-_James # Output : Jamesr print(" - Avatar \r - James") print("\t\t Escape Sequence\r - Python") # ---------- # print("\") syntax error print(" - \\") # ---------- # if you want to read a paragraph you need to use: print(''' - If you choose to use your status and influence to raise your voice on behalf of those who have no voice; if you choose to identify not only with the powerful, but with the powerless; if you retain the ability to imagine yourself into the lives of those who do not have your advantages, then it will not only be your proud families who celebrate your existence, but thousands and millions of people whose reality you have helped change. We do not need magic to change the world, we carry all the power we need inside ourselves already: we have the power to imagine better. ''') # ---------- print("+"*10) # Output:++++++++++
19be701b4dee8fff590fdb72f6ce6ced9c7eae2a
veeneel/GridSolver
/CppDemo/GridTest.py
1,928
3.5
4
import csv import bisect # grid size = 4 (min), 100 (max) squares = [x*x for x in range(2,11)] #print(squares) # nextHighest = lambda seq,x: min([(i-x,i) for i in seq if x<=i] or [(0,None)])[1] # nextLowest = lambda seq,x: min([(x-i,i) for i in seq if x>=i] or [(0,None)])[1] def validate(fname): print('Input File {} :'.format(fname)) print('---------------------') # Open the input file with open(fname, "r") as gridData: #Set up CSV reader and process the header csvReader = csv.reader(gridData) # Make an empty list coordList = [] # Loop through the lines in the file and get each coordinate for row in csvReader: x = row[0] y = row[1] coordList.append([x,y]) #print(x) length = len(coordList) # print(length) if length not in squares: print('Incorrect Size: {} points in file.'.format(length)) index = bisect.bisect(squares, length) # print('Smaller than target: {}'.format(squares[index-1])) # print('Greater than target: {}'.format(squares[index])) diff1 = length - squares[index-1] diff2 = squares[index] -length if (diff2 < diff1): print('Too few points in file') else: print('Too many points in file') else: size = squares.index(length)+2 print('Grid Size: {0}x{0}'.format(size)) # print('Greater than target: {}'.format(nextHighest(squares,length))) # print('Smaller than target: {}'.format(nextLowest(squares,length))) # Print the coordinate list #print (coordList[0]) print('---------------------\n') def main(): validate('Data4x4.txt') validate('Data4x4b.txt') validate('Data4x4c.txt') validate('Data4x4d.txt') if __name__ == '__main__': main()
f5f54b5db00added0abbf07df9fa2c38bb2e2fbc
compsciprep-acsl-2020/2019-2020-ACSL-Python-Akshay
/class10-05/calculator.py
844
4.21875
4
#get the first number #get the second number #make an individual function to add, subtract, multiply and divide #return from each function #template for add function def add(num1, num2): return (num1+num2) def sub(num1, num2): return (num1-num2) def multiply(num1, num2): return (num1*num2) def division(num1, num2): return (num1/num2) num1 = int(input("Enter the First Number")) num2 = int(input("Enter the Second Number")) option = int(input("Enter 1 for Addition \n Enter 2 for Subtration \n Enter 3 for Multiplication \n Enter 4 for Division")) if (option == 1): print("The sum is: ", add(num1,num2)) elif (option == 2): print("The difference is: ", sub(num1,num2)) elif (option == 3): print("The product is: ", multiply(num1,num2)) elif (option == 4): print("the quotient is: ", division(num1,num2))
d938608a76e72261a3fe71c38a6d75c434315800
StevenSadler/AIND-Isolation
/stub_board.py
6,570
4.25
4
""" This file contains the `Board` class, which implements the rules for the game Isolation as described in lecture, modified so that the players move like knights in chess rather than queens. You MAY use and modify this class, however ALL function signatures must remain compatible with the defaults provided, and none of your changes will be available to project reviewers. """ import random import timeit from copy import copy TIME_LIMIT_MILLIS = 150 class Board(object): """Implement a model for the game Isolation assuming each player moves like a knight in chess. Parameters ---------- player_1 : object An object with a get_move() function. This is the only function directly called by the Board class for each player. player_2 : object An object with a get_move() function. This is the only function directly called by the Board class for each player. width : int (optional) The number of columns that the board should have. height : int (optional) The number of rows that the board should have. """ BLANK = 0 NOT_MOVED = None def __init__(self, player_1, player_2, width=7, height=7): self.width = width self.height = height self.move_count = 0 self._player_1 = player_1 self._player_2 = player_2 self._active_player = player_1 self._inactive_player = player_2 # The last 3 entries of the board state includes initiative (0 for # player 1, 1 for player 2) player 2 last move, and player 1 last move self._board_state = [Board.BLANK] * (width * height + 3) self._board_state[-1] = Board.NOT_MOVED self._board_state[-2] = Board.NOT_MOVED def hash(self): return str(self._board_state).__hash__() @property def active_player(self): """The object registered as the player holding initiative in the current game state. """ return self._active_player @property def inactive_player(self): """The object registered as the player in waiting for the current game state. """ return self._inactive_player def get_opponent(self, player): """Return the opponent of the supplied player. Parameters ---------- player : object An object registered as a player in the current game. Raises an error if the supplied object is not registered as a player in this game. Returns ------- object The opponent of the input player object. """ if player == self._active_player: return self._inactive_player elif player == self._inactive_player: return self._active_player raise RuntimeError("`player` must be an object registered as a player in the current game.") def copy(self): """ Return a deep copy of the current board. """ new_board = Board(self._player_1, self._player_2, width=self.width, height=self.height) new_board.move_count = self.move_count new_board._active_player = self._active_player new_board._inactive_player = self._inactive_player new_board._board_state = copy(self._board_state) return new_board def forecast_move(self, move): """Return a deep copy of the current game with an input move applied to advance the game one ply. Parameters ---------- move : (int, int) A coordinate pair (row, column) indicating the next position for the active player on the board. Returns ------- isolation.Board A deep copy of the board with the input move applied. """ new_board = self.copy() return new_board def get_player_location(self, player): """Find the current location of the specified player on the board. Parameters ---------- player : object An object registered as a player in the current game. Returns ------- (int, int) or None The coordinate pair (row, column) of the input player, or None if the player has not moved. """ if player == self._player_1: if self._board_state[-1] == Board.NOT_MOVED: return Board.NOT_MOVED idx = self._board_state[-1] elif player == self._player_2: if self._board_state[-2] == Board.NOT_MOVED: return Board.NOT_MOVED idx = self._board_state[-2] else: raise RuntimeError( "Invalid player in get_player_location: {}".format(player)) w = idx // self.height h = idx % self.height return (h, w) def get_legal_moves(self, player=None): """Return the list of all legal moves for the specified player. Parameters ---------- player : object (optional) An object registered as a player in the current game. If None, return the legal moves for the active player on the board. Returns ------- list<(int, int)> The list of coordinate pairs (row, column) of all legal moves for the player constrained by the current game state. """ return [self.get_player_location(self.active_player), self.get_player_location(self.inactive_player)] def to_string(self, symbols=['1', '2']): """Generate a string representation of the current game state, marking the location of each player and indicating which cells have been blocked, and which remain open. """ p1_loc = self._board_state[-1] p2_loc = self._board_state[-2] col_margin = len(str(self.height - 1)) + 1 prefix = "{:<" + "{}".format(col_margin) + "}" offset = " " * (col_margin + 3) out = offset + ' '.join(map(str, range(self.width))) + '\n\r' for i in range(self.height): out += prefix.format(i) + ' | ' for j in range(self.width): idx = i + j * self.height if not self._board_state[idx]: out += ' ' elif p1_loc == idx: out += symbols[0] elif p2_loc == idx: out += symbols[1] else: out += '-' out += ' | ' out += '\n\r' return out
04f69fb9ea8ff0ad3cb052883d5d75632daeade7
ivmtorres/OpenCV-1
/31.Detect_Corners_using_Harris_Corner_Detector/Detect_Corners_using_Harris_Corner_Detector.py
1,168
3.53125
4
# Harris Corner Detector # Corners are regions with large variation in the intensity in all the directions. # It contains three main steps : # 1. Determine which windows produce very large variations in intensity when moved in both X and Y directions. # 2. With each such window found a score R is computed. # 3. After applying a threshold to this score, important corners are selected & marked. # There are different conditions of R which determine - Flat region, Edge, and Corner. import numpy as np import cv2 as cv img = cv.imread('chessboard.png') cv.imshow('img', img) gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY) gray = np.float32(gray) # CornerHarris method read image in float format therefore convertion is taken place. dst = cv.cornerHarris(gray, 2, 3, 0.04) # image, blockSize - It is the size of neighbourhood considered for corner detection, ksize - Aperture parameter of sobel derivative, k - harris detector free parameter. dst = cv.dilate(dst, None) # for better result img[dst > 0.01 * dst.max()] = [0, 0, 255] # threshold and coloration cv.imshow('dst', img) if cv.waitKey(0) & 0xff == 27 : cv.destroyAllWindows()
f854478c9d2851fda210df04d7c8c36d6e1008e3
ivmtorres/OpenCV-1
/10.Bind_Trackbar/Change_color_using_trackbar_switch.py
963
3.765625
4
# change colors using trackbar using switch. import numpy as np import cv2 as cv def nothing(x): print(x) img = np.zeros((300,512,3),np.uint8) cv.namedWindow('image') # Create a window with name 'image' cv.createTrackbar('B', 'image', 0, 255, nothing) # Trackbar_Name, Window_Name, initial_value, Final_value, call_back_function cv.createTrackbar('G', 'image', 0, 255, nothing) cv.createTrackbar('R', 'image', 0, 255, nothing) switch = '0 : OFF\n 1 : ON' # Name of switch as a trackbar cv.createTrackbar(switch, 'image', 0, 1, nothing) while(1): cv.imshow('image',img) if cv.waitKey(1) == 27: break b = cv.getTrackbarPos('B','image') # trackbar, window g = cv.getTrackbarPos('G','image') r = cv.getTrackbarPos('R','image') s = cv.getTrackbarPos(switch,'image') if s ==0: img[:] = 0 else: img[:] = [b, g, r] # set this color to img cv.destroyAllWindows()
681ac7bfeac29a22b7689221ff55dd10ca7db676
ChrisLR/BFLib
/bflib/characters/abilityscores/base.py
754
3.5
4
import abc class AbilityScore(object): __metaclass__ = abc.ABCMeta __slots__ = ["value"] _modifier_table = { 3: -3, 4: -2, 5: -2, 6: -1, 7: -1, 8: -1, 9: 0, 10: 0, 11: 0, 12: 0, 13: 1, 14: 1, 15: 1, 16: 2, 17: 2, 18: 3, } def __init__(self, value): self.value = value def modifier(self): return self._modifier_table[self.value] class Strength(AbilityScore): pass class Dexterity(AbilityScore): pass class Constitution(AbilityScore): pass class Intelligence(AbilityScore): pass class Wisdom(AbilityScore): pass class Charisma(AbilityScore): pass
211e5843e73e12ed17babd1a823a44bfadbffd17
wangtao10494/api
/alien_invasion/matplotlib/random_die.py
463
3.609375
4
from random import choice from random import randint class Random_die(): def __init__(self,num_points=2,num_sides=6): self.num_points = num_points self.num_sides = num_sides """开始时没有坐标""" self.x_values=[] self.y_values=[] def roll(self): return randint(1,self.num_sides) def fill_walk(self): for value in range(self.num_points): x_step = self.roll() self.x_values.append(x_step) self.y_values.append(x_step)
67a35cec9980373961eba321fa878983130369e9
vassmate/Learn_Python_THW
/mystuff/ex15.py
212
3.984375
4
# http://learnpythonthehardway.org/book/ex15.html print "Please enter the file name here: " filename = raw_input("> ") txt = open(filename) print "Here's your file %r:" % filename print txt.read() txt.close()
8d438c71959d3fd16bffc44490bdfea783fcf61d
vassmate/Learn_Python_THW
/mystuff/ex3.py
1,312
4.8125
5
# http://learnpythonthehardway.org/book/ex3.html # This will print out: "I will count my chickens:". print "I will count my chikens:" # This will print out how much Hens we have. print "Hens", 25.0 + 30.0 / 6.0 # This will print out how much roosters we have. print "Roosters", 100.0 - 25.0 * 3.0 % 4.0 # This will print out: "Now I will count the eggs:". print"Now I will count the eggs:" # This will print out the result of the given math opertions. print 3.0 + 2.0 + 1.0 - 5.0 + 4.0 % 2.0 - 1.0 / 4.0 + 6.0 # This will print out: "Is it true that 3 + 2 < - 7?" print "Is it true that 3 + 2 < 5 - 7?" # This will print out the result of the given math operations. print 3.0 + 2.0 < 5.0 - 7.0 # This will print out the answer for the printed question: "What is 3 + 2?". print "What is 3.0 + 2.0?", 3.0 + 2.0 # This will print out the answer for the printed question: "What is 5 - 7?". print "What is 5.0 - 7.0?", 5.0 - 7.0 # This will print out : "Oh, that's why it's False.". print "Oh, that's why it's False." # THis will print out : "How about some more.". print "How about some more." # These will print out the answers for the printed questions. print "Is 5.0 > -2.0 greater?", 5.0 > -2.0 print "Is 5.0 >= -2.0 greater or equal?", 5.0 >= -2.0 print "Is 5.0 <= -2.0 less or equal?", 5.0 <= -2.0
1bd1431550433e411757182599741bfc865f7e39
GithubWangXiaoXi/Time_Series_Analysis
/src/model/GM.py
1,406
3.578125
4
import numpy as np import matplotlib.pyplot as plt class GM: def paramSetter(self): # 使用GM(1,1)模型,无参数设置 pass def fit(self): # GM模型无需训练 print("GM fit") def predict(self, X, K): print("GM predict") """ Return the predictions through GM(1, 1). Parameters ---------- X_0 : np.ndarray Raw data, a one-dimensional array. K : int number of predictions. display : bool Whether to display the results. Returns ------- X_0_pred[N:] : np.ndarray predictions, a one-dimensional array. """ X_0 = X N = X_0.shape[0] X_1 = np.cumsum(X_0) B = np.ones((N - 1, 2)) B[:, 0] = [-(X_1[i] + X_1[i + 1]) / 2 for i in range(N - 1)] y = X_0[1:] assert np.linalg.det(np.matmul(B.transpose(), B)) != 0 a, u = np.matmul( np.matmul(np.linalg.inv(np.matmul(B.transpose(), B)), B.transpose()), y ) pred_range = np.arange(N + K) X_1_pred = (X_1[0] - u / a) * np.exp(-a * pred_range) + u / a X_0_pred = np.insert(np.diff(X_1_pred), 0, X_0[0]) # print(X_1_pred) # print(X_0_pred) return X_0_pred[N:]
741c4b7001847616f27cd35228d6369dab972d29
IronManZheng/GraphicCaculate_cloud
/people_class.py
921
3.703125
4
class People(): #定义人员的类 def __init__(self,name,next,edge): self.name = name self.next = [] self.edge = () def put_next(self,people_class): #给下一跳next赋值 self.next.append(people_class) def put_edge(self,edge_name,width): #给两跳之间的连线也就是边赋值 self.edge[edge_name] = width #边的名字被命名为字典的键,边的权重被命名为字典的值 return def get_node_atr(self): #获得节点的名称 return(self.name) def get_neighbors_iter(self): #获得节点的所有下一跳 return(self.next) def get_neighbor_edge(self): #获得节点的所有相邻边 return(self.edge) def remove_neighbors_iter(self,i): #删除节点的下一跳 del self.next[i] def remove_neighbors_edge(self,end): del self.edge[end]
7e23563c827b797bcb11bf669533fff78fc759ff
ksnt/Euler
/problem42.py
1,159
3.765625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # ksnt def main(): f = open("words.txt","r") data = f.read() data_split = data.split(',') str_data = [] f.close() for i in data_split: str_data.append(i.strip("\"")) # '"'を取り除く result = [] for i in str_data: result.append(sum(map(transfer_word_into_wordvalue, i))) # wordごとのword valueを足して数列をつくる tri_num = triange_number(30) # max(result)=192なのでこれくらいの大きさをつくっておけばok final_result = [] for i in tri_num: final_result.append(result.count(i)) # result中にtriange_numberがいくつあるか数える print sum(final_result) # triangle numberの個数の和をとって、結果を表示 return sum(final_result) def transfer_word_into_wordvalue(str): """ wordをword valueに変換する関数 A=>1, B=>2, ...""" return ord(str)-64 def triange_number(n): """ n個のtriangle numberの数列を作り出す関数""" result = [] for i in range(1,n): result.append(i*(i+1)/2) return result if __name__ == '__main__': main()
05ea77a096dac9ea5c5f9b711d2a088ef70b1be1
rpatillo/Python-Matrice
/Pokemon/04_poke_types/pokeball.py
821
3.703125
4
import sys from pokemon import Pokemon class Pokeball: pokemon = None def __init__(self, pokemon=None): if pokemon != None: self.store(pokemon) def __str__(self): if self.pokemon == None: return("An empty pokeball") else: return(str(self.pokemon)) def store(self, pokemon): if self.pokemon != None: print("Two pokemons in the same pokeball is barbary!") else: self.pokemon = pokemon def release(self): if self.pokemon != None: temp = self.pokemon self.pokemon = None return(temp) else: print("No pokemons to release!", file=sys.stderr) # Check also : sys.stderr.write("No pokemons to release!\n") return(None)
52480fd2a516e8b889ea9f8f86c102f62c9f7383
XiyunLiu/STLeetcode
/281. Zigzag Iterator.py
1,621
3.78125
4
__author__ = 'liuxiyun' class ListNode(object): def __init__(self,val): self.val = val self.next = None class ZigzagIterator(object): def __init__(self, v1, v2): """ Initialize your data structure here. :type v1: List[int] :type v2: List[int] """ v1Pre = ListNode(0) pre1 = v1Pre for node in v1: pre1.next = ListNode(node) pre1 = pre1.next v2Pre = ListNode(0) pre2 = v2Pre for node in v2: pre2.next = ListNode(node) pre2 = pre2.next self.v1 = v1Pre.next self.v2 = v2Pre.next self.cur = self.v1 def next(self): """ :rtype: int """ if self.v1 == None: tmp = self.v2.val self.v2 = self.v2.next return tmp if self.v2 == None: tmp = self.v1.val self.v1 = self.v1.next return tmp if self.cur == self.v1: tmp = self.v1.val self.v1 = self.v1.next self.cur = self.v2 return tmp if self.cur == self.v2: tmp = self.v2.val self.v2 = self.v2.next self.cur = self.v1 return tmp def hasNext(self): """ :rtype: bool """ if self.v1 == None and self.v2 == None: return False return True v1 = [1,2] v2 = [3,4,5,6] # Your ZigzagIterator object will be instantiated and called as such: i, v = ZigzagIterator(v1, v2), [] while i.hasNext(): v.append(i.next()) print v
034373050d319b47889520057ac923efbd9cc2e2
XiyunLiu/STLeetcode
/288. Unique Word Abbreviation.py
974
3.609375
4
__author__ = 'liuxiyun' class ValidWordAbbr(object): def __init__(self, dictionary): """ initialize your data structure here. :type dictionary: List[str] """ self.word_dic = {} for word in dictionary: key = self.getKey(word) if key in self.word_dic and self.word_dic[key]!=word: self.word_dic[key] = "" else: self.word_dic[key] = word def isUnique(self, word): """ check if a word is unique. :type word: str :rtype: bool """ key = self.getKey(word) if key in self.word_dic: return self.word_dic[key] == word return True def getKey(self,word): return word if len(word)<2 else word[0]+str(len(word)-2)+word[-1] # Your ValidWordAbbr object will be instantiated and called as such: vwa = ValidWordAbbr(["d"]) print vwa.isUnique("dog") print vwa.isUnique("dig")
52c689ba66d7c8a442195e93a23474d89c5da6cf
aaron-xyz/CS50
/pset6/vigenere.py
1,854
3.828125
4
""" Pset6: Vigenere From pset1 - vigenere imported from C to Python $ python vigenere.py ABC plaintext: HELLO ciphertext: HFNLP $ python vigenere.py bacon plaintext: Meet me at the park at eleven am ciphertext: Negh zf av huf pcfx bt gzrwep oz """ import sys def main(): # check correct number or inputs if len(sys.argv) != 2: print("You must enter the key: python vigenere.py KEY") exit(1) # every char must be alphabetical key = sys.argv[1] if (not key.isalpha()): print("k must be alpha: python vigenere.py k") exit(2) # input p = input("plaintext: ") c = "" j = 0 lkey = len(key) # cipher the plaintext for char in p: # char is uppercase letter if char.isalpha() and char.isupper(): # char of key is uppercase if key[j].isupper(): shift = ( (ord(char)-ord('A')) + (ord(key[j])-ord('A')) )%26 + ord('A') c = c + chr(shift) else: shift = ( (ord(char)-ord('A')) + (ord(key[j])-ord('a')) )%26 c = c + chr(shift + ord('A')) # next index for k j = (j+1) % lkey # char is lowercase letter elif char.isalpha() and char.islower(): # char of key is lower if key[j].islower(): shift = ( (ord(char)-ord('a')) + (ord(key[j])-ord('a')) )%26 c = c + chr(shift + ord('a')) else: shift = ( (ord(char)-ord('a')) + (ord(key[j])-ord('A')) )%26 c = c + chr(shift + ord('a')) # next index for k j = (j+1) % lkey # do not shift if char is not a letter else: c = c + char # print ciphered text print("ciphertext: {}".format(c)) if __name__ == "__main__": main()
a7accddf475b97f65173dd098bb0c703b5de5aca
codeAligned/CS156
/hw4/problem7.py
6,441
3.5625
4
import random import math import numpy as np import numpy.linalg as linalg import matplotlib.pyplot as plt def dot(list1, list2): assert(len(list1) == len(list2)) result = 0 for i in range(len(list1)): result += (list1[i] * list2[i]) return result def generatePoint(): x = random.uniform(-1,1) y = random.uniform(-1,1) return (x,y) def sign(value): if (value >= 0.0): return 1.0 else: return -1.0 def sine(): (x1,y1) = generatePoint() y1 = math.sin(math.pi * x1) (x2,y2) = generatePoint() y2 = math.sin(math.pi * x2) # Calculate the best a a = ((x1 * y1) + (x2 * y2)) / ((x1*x1) + (x2 * x2)) print a return a def sineA(): (x1,y1) = generatePoint() y1 = math.sin(math.pi * x1) (x2,y2) = generatePoint() y2 = math.sin(math.pi * x2) # calculate the best b for h(x) = b # this will just be the average of y1 and y2 to minimize error b = (y1 + y2) / 2 return b def sineB(): (x1,y1) = generatePoint() y1 = math.sin(math.pi * x1) (x2,y2) = generatePoint() y2 = math.sin(math.pi * x2) # calculate the best a for h(x) = ax # minimize (a * x1 - y1)^2 + (a * x2 - y2)^2 # Calculate the best a a = ((x1 * y1) + (x2 * y2)) / ((x1*x1) + (x2 * x2)) return a def sineC(): (x1,y1) = generatePoint() y1 = math.sin(math.pi * x1) (x2,y2) = generatePoint() y2 = math.sin(math.pi * x2) # calculate the best a, b for h(x) = ax + b # or in other words, just calculate the line between the 2 points... :) rise = y2 - y1 run = x2 - x1 slope = rise / run # find the y intercept # y1 = mx1 + b # b = y1 - mx1 b = (y1 - slope * x1) return (slope, b) def sineD(): (x1,y1) = generatePoint() y1 = math.sin(math.pi * x1) (x2,y2) = generatePoint() y2 = math.sin(math.pi * x2) # calculate the best a for h(x) = ax^2 # minimize (ax1^2 - y1) ^2 + (ax2^2 - y2) ^2 # differentiate: # 0 = 2(ax1^2 - y1) * x1^2 + 2(ax2^2 - y2) * x2^2 # ax1^4 - x1^2*y1 + ax2^4 - x2^2 * y2 = 0 # a(x1^4 + x2^4) = x1^2 * y1 + x2^2 * y2 # a = (x1^2 * y1 + x2^2 * y2) / (x1 ^ 4 + x2^4) num = (x1 * x1 * y1) + (x2 * x2 * y2) den = (x1 * x1 * x1 * x1) + (x2 * x2 * x2 * x2) a = num/den return a def sineE(): (x1,y1) = generatePoint() y1 = math.sin(math.pi * x1) (x2,y2) = generatePoint() y2 = math.sin(math.pi * x2) # find ax^2 + b == y # ax1^2 + b = y1 => b = y1 - ax1^2 # ax2^2 + b = y2 # ax2^2 + y1 - ax1^2 = y2 # a(x2^2 - x1^2) = y2 - y1 # a = (y2-y1) / (x2^2 - x1^2) a = (y2 - y1) + (x2 * x2 - x1 * x1) b = y1 - (a * x1 * x1) return (a,b) aCounter = 0 aVariance = 0 for i in range(1000): b = sineA() aCounter += b x = random.uniform(-1,1) sq = (b - 0) * (b - 0) aVariance += sq print "A: AVG B: ", aCounter / 1000 print "A: AVG VAR: ", aVariance / 1000 aError = 0 for i in range(1000): (x1, y1) = generatePoint() # True f(x1) = y1 y1 = math.sin(math.pi * x1) g1 = 0 * x1 # g(x) estimate aError += ((g1 - y1) * (g1 - y1)) print "A: AVG BIAS: ", aError / 1000 # CHOICE B bCounter = 0 bVariance = 0 for i in range(1000): a = sineB() bCounter += a for j in range(1000): x = random.uniform(-1,1) sq = (a * x - 1.426 * x) * (a * x - 1.426 * x) bVariance += sq print "B: AVG A: ", bCounter / 1000 print "B: AVG VAR: ", bVariance / 1000000 bError = 0 for i in range(1000): (x1, y1) = generatePoint() # True f(x1) = y1 y1 = math.sin(math.pi * x1) g1 = 1.426 * x1 # g(x) estimate bError += ((g1 - y1) * (g1 - y1)) print "B: AVG BIAS: ", bError / 1000 # CHOICE C cCounterSlope = 0 cCounterIntercept = 0 cVariance = 0 for i in range(1000): (slope, b) = sineC() # g(x) cCounterSlope += slope cCounterIntercept += b #for j in range(1000): # x = random.uniform(-1,1) # sq = (a * x - 1.426 * x) * (a * x - 1.426 * x) # cVariance += sq print "C: AVG SLOPE: ", cCounterSlope / 1000 print "C: AVG INTERCEPT: ", cCounterIntercept / 1000 aAvg = cCounterSlope/1000 bAvg = cCounterIntercept / 1000 for i in range(1000): (slope, b) = sineC() for j in range(1000): x = random.uniform(-1,1) sq = (slope * x + b - (aAvg * x + bAvg)) * (slope * x + b - (aAvg * x + bAvg)) cVariance += sq print "C: AVG VAR: ", cVariance / 1000000 cError = 0 for i in range(1000): (x1, y1) = generatePoint() # True f(x1) = y1 y1 = math.sin(math.pi * x1) #g1 = 1.426 * x1 # g(x) estimate g1 = aAvg * x1 + b cError += ((g1 - y1) * (g1 - y1)) print "C: AVG BIAS: ", cError / 1000 # CHOICE D dCounterSlope = 0 dVariance = 0 for i in range(10000): slope = sineD() dCounterSlope += slope print "D: AVG SLOPE: ", dCounterSlope / 10000 dAvg = dCounterSlope / 10000 for i in range(1000): slope = sineD() for j in range(1000): x = random.uniform(-1,1) sq = (slope * x * x - (dAvg * x * x)) * (slope * x * x - (dAvg * x * x)) dVariance += sq print "D: AVG VAR: ", dVariance / 1000000 dError = 0 for i in range(1000): (x1, y1) = generatePoint() # True f(x1) = y1 y1 = math.sin(math.pi * x1) g1 = dAvg * x1 * x1 # g(x) estimate dError += ((g1 - y1) * (g1 - y1)) print "D: AVG BIAS: ", dError / 1000 # CHOICE E eCounterSlope = 0 eCounterIntercept = 0 eVariance = 0 for i in range(1000): (a,b) = sineE() eCounterSlope += a eCounterIntercept += b print "E: AVG SLOPE: ", eCounterSlope / 1000 print "E: AVG INTERCEPT: ", eCounterIntercept / 1000 eAvg = eCounterSlope / 1000 eAvgInt = eCounterIntercept/1000 for i in range(1000): (a, b) = sineE() for j in range(1000): x = random.uniform(-1,1) sq = (a * x * x + b - (eAvg * x * x + eAvgInt)) * (a * x * x + b - (eAvg * x * x + eAvgInt)) eVariance += sq print "E: AVG VAR: ", eVariance / 1000000 eError = 0 for i in range(1000): (x1, y1) = generatePoint() # True f(x1) = y1 y1 = math.sin(math.pi * x1) g1 = eAvg * x1 * x1 + eAvgInt # g(x) estimate eError += ((g1 - y1) * (g1 - y1)) print "E: AVG BIAS: ", eError / 1000 """ aCounter = 0 aVar = 0 sqTotal = 0 for i in range(100000): (a, aMiss) = sine() aCounter += a aVar += aMiss for i in range(1000): x = random.uniform(-1,1) sq = (a*x - 1.426 * x) * (a*x - 1.426 * x) sqTotal += sq print "AVG A:", aCounter / 100000 print "Var: ", aVar/100000 print "SQtotal: ", sqTotal / 100000000 # now, generate 1000 random points to determine the average squared error # between g(x) = 1.426x and f(x) aError = 0 for i in range(100000): (x1, y1) = generatePoint() # True f(x1) = y1 y1 = math.sin(math.pi * x1) g1 = 1.426 * x1 # g(x) estimate aError += ((g1 - y1) * (g1 - y1)) print "AVG BIAS: ", aError / 100000 """
fdacb2906e0822d1234549419b8695bd467ec4e4
GlaucioSales/paradigmas-2019
/perso/Personalizada2.py
5,147
3.609375
4
#Crie uma função isVowel :: Char -> Bool que verifique se um caracter é uma vogal ou não. def isVowel(c): if c == 'a' or c == 'e' or c == 'i' or c == 'o' or c == 'u': return True else: return False #Escreva uma função addComma, que adicione uma vírgula no final de cada string contida numa lista. def addComma (x): newList = [] for n in x: newList.append (n + ',') return newList #Crie uma função htmlListItems :: [String] -> [String], que receba uma lista de strings e retorne outra lista contendo as strings formatadas como itens de lista em HTML. Resolva este exercício COM e SEM funções anônimas (lambda). Exemplo de uso da função: def htmlListItems(x): newList = [] for n in x: newList.append ('<LI>' + n + '</LI>') return newList #Defina uma função que receba uma string e produza outra retirando as vogais, conforme os exemplos abaixo. Resolva este exercício COM e SEM funções anônimas (lambda). def semVogais(x): newList = [] for n in x: if n != 'a' and n != 'e' and n != 'i' and n != 'o' and n != 'u': newList.append(n) newList = ''.join(newList) return newList #Defina uma função que receba uma string, possivelmente contendo espaços, e que retorne outra string substituindo os demais caracteres por '-', mas mantendo os espaços. Resolva este exercício COM e SEM funções anônimas (lambda). Exemplos: def codifica (x): newList = [] for n in x: if n == ' ': newList.append(' ') else: newList.append('-') newList = ''.join(newList) return newList #Escreva uma função firstName :: String -> String que, dado o nome completo de uma pessoa, obtenha seu primeiro nome. Suponha que cada parte do nome seja separada por um espaço e que não existam espaços no início ou fim do nome. Dica: estude funções pré-definidas em Haskell (List operations -> Sublists) em http://hackage.haskell.org/package/base-4.10.1.0/docs/Prelude.html#g:18. Exemplos de uso da função: def firstName (x): newList = [] for n in x: if n != ' ': newList.append(n) else: newList = ''.join(newList) return newList #Escreva uma função isInt :: String -> Bool que verifique se uma dada string só contém dígitos de 0 a 9. Exemplos: def isInt (x): newList = [] for n in x: if n != '0' and n != '1' and n != '2' and n != '3' and n != '4' and n != '5' and n != '6' and n != '7' and n != '8' and n != '9': return False return True #Escreva uma função lastName :: String -> String que, dado o nome completo de uma pessoa, obtenha seu último sobrenome. Suponha que cada parte do nome seja separada por um espaço e que não existam espaços no início ou fim do nome. Exemplos de uso da função: def lastName(x): newList = [] x = x[::-1] x = firstName(x) x = x[::-1] return x #Escreva uma função userName :: String -> String que, dado o nome completo de uma pessoa, crie um nome de usuário (login) da pessoa, formado por: primeira letra do nome seguida do sobrenome, tudo em minúsculas. Dica: estude as funções pré-definidas no módulo Data.Char, para manipulação de maiúsculas e minúsculas. Você precisará carregar este módulo usando import Data.Char no interpretador ou no início do arquivo do programa. def userName (x): newList = [] x = x.lower() newList.append(x[0]) newList.append(lastName(x)) newList = ''.join(newList) return newList #Escreva uma função encodeName :: String -> String que substitua vogais em uma string, conforme o esquema a seguir: a = 4, e = 3, i = 2, o = 1, u = 0. def encodeName (x): newList = [] for n in x: if n == 'a': newList.append('4') elif n == 'e': newList.append('3') elif n == 'i': newList.append('2') elif n == 'o': newList.append('1') elif n == 'u': newList.append('0') else: newList.append(n) newList = ''.join(newList) return newList #Dada uma lista de strings, produzir outra lista com strings de 10 caracteres, usando o seguinte esquema: strings de entrada com mais de 10 caracteres são truncadas, strings com até 10 caracteres são completadas com '.' até ficarem com 10 caracteres. Exemplo: def func (x): newList = [] for n in x: if len(n) >= 10: newList.append(n[:10]) else: n = n + '...............' newList.append(n[:10]) return newList print(isVowel('a')) print(addComma(["Glaucio", "Sales", "Santos"])) print(htmlListItems(["Glaucio", "Sales", "Santos"])) print(semVogais("Glaucio")) print(codifica("Glaucio Sales Santos")) print(firstName("Glaucio Sales Santos")) print(isInt("9595559a")) print (lastName ("Glaucio Sales Santos")) print( userName("Glaucio Sales Santos")) print (encodeName("Glaucio Sales Santos")) print (func (["glauciosalessantos","g"]))
b087f330b72cfcde0342e2d835d9adb684a12123
akashpakkan/Reinforcement-Learning-based-Tic-Tac-Toe
/Reinforcement Learning based Tic Tac Toe/ML task.py
8,042
3.734375
4
#!/usr/bin/env python # coding: utf-8 # # ML Task - 01 (The Robotics Forum) # ### Mentor Shripad Kulkarni # #### Preeti Oswal, Aryan Gupta, Avinash Vijayvargiya # # ## Importing all required lib # In[1]: import numpy as np import pickle # ### Developing board and funcation to game play # In[2]: class Game: def __init__(self, p1, p2): self.board = np.zeros((3, 3)) self.p1 = p1 self.p2 = p2 self.isEnd = False self.boardHash = None self.playerSymbol = 1 def getHash(self): self.boardHash = str(self.board.reshape(9)) return self.boardHash ## DECLARING CONDITION TO WIN THE GAME def winner(self): ## CONDITION FOR ROWS for i in range(3): if sum(self.board[i, :]) == 3: self.isEnd = True return 1 if sum(self.board[i, :]) == -3: self.isEnd = True return -1 ## CONDITION FOR COLUMNS for i in range(3): if sum(self.board[:, i]) == 3: self.isEnd = True return 1 if sum(self.board[:, i]) == -3: self.isEnd = True return -1 ## CONDITION FOR DIAGONALS sum1_diag = sum([self.board[i, i] for i in range(3)]) sum2_diag = sum([self.board[i, 3-i-1] for i in range(3)]) if sum1_diag == 3 or sum2_diag == 3: self.isEnd = True return 1 if sum1_diag == -3 or sum2_diag == -3: self.isEnd = True return -1 if len(self.remainingPositions()) == 0: self.isEnd = True return 0 self.isEnd = False return None ## FUNCTION TO DETERMINE VACANT POSITIONS def remainingPositions(self): positions = [] for i in range(3): for j in range(3): if self.board[i, j] == 0: positions.append((i, j)) return positions ## FUNCTION TO UPDATE BOARD VALUES def update(self, position): self.board[position] = self.playerSymbol self.playerSymbol = -1 if self.playerSymbol == 1 else 1 ## FUNCTION TO REWARD MACHINE def giveReward(self): result = self.winner() if result == 1: self.p1.feedReward(1) self.p2.feedReward(0) elif result == -1: self.p1.feedReward(0) self.p2.feedReward(1) else: self.p1.feedReward(0.1) self.p2.feedReward(0.5) ## FUNCTION TO RESET THE BOARD FOR THE GAME def reset(self): self.board = np.zeros((3,3)) self.boardHash = None self.isEnd = False self.playerSymbol = 1 ## FUNCTION FOR PLAYER 1 AND PLAYER 2 def play(self, rounds=100): for i in range(rounds): while not self.isEnd: positions = self.remainingPositions() p1_action = self.p1.NextMove(positions, self.board, self.playerSymbol) self.update(p1_action) board_hash = self.getHash() self.p1.addState(board_hash) win = self.winner() if win is not None: self.giveReward() self.p1.reset() self.p2.reset() self.reset() break else: positions = self.remainingPositions() p2_action = self.p2.NextMove(positions, self.board, self.playerSymbol) self.update(p2_action) board_hash = self.getHash() self.p2.addState(board_hash) win = self.winner() if win is not None: self.giveReward() self.p1.reset() self.p2.reset() self.reset() break def play2(self): while not self.isEnd: positions = self.remainingPositions() p1_action = self.p1.NextMove(positions, self.board, self.playerSymbol) self.update(p1_action) self.Display() win = self.winner() if win is not None: if win == 1: print(self.p1.name, "Wins! , Better Luck next time") else: print("Tie!") self.reset() break else: positions = self.remainingPositions() p2_action = self.p2.NextMove(positions) self.update(p2_action) self.Display() win = self.winner() if win is not None: if win == -1: print(self.p2.name, "Win!") else: print("Tie!") self.reset() break def Display(self): for i in range(0, 3): print('-------------') out = '| ' for j in range(0, 3): if self.board[i, j] == 1: token = 'X' if self.board[i, j] == -1: token = 'O' if self.board[i, j] == 0: token = ' ' out += token + ' | ' print(out) print('-------------') # ### Creating self-learning machine model # In[3]: class Model: def __init__(self, name, random=0.3): self.name = name self.states = [] self.random = random self.lr = 0.2 self.states_value = {} def getHash(self, board): boardHash = str(board.reshape(9)) return boardHash def NextMove(self, positions, current_board, symbol): if np.random.uniform(0, 1) <= self.random: idx = np.random.choice(len(positions)) action = positions[idx] else: value_max = -999 for p in positions: next_board = current_board.copy() next_board[p] = symbol next_boardHash = self.getHash(next_board) value = 0 if self.states_value.get(next_boardHash) is None else self.states_value.get(next_boardHash) if value >= value_max: value_max = value action = p return action def addState(self, state): self.states.append(state) def feedReward(self, reward): for st in reversed(self.states): if self.states_value.get(st) is None: self.states_value[st] = 0 self.states_value[st] += self.lr*(0.9*reward - self.states_value[st]) reward = self.states_value[st] def reset(self): self.states = [] def saveDict(self): fw = open('policy_' + str(self.name), 'wb') pickle.dump(self.states_value, fw) fw.close() def loadDict(self, file): fr = open(file,'rb') self.states_value = pickle.load(fr) fr.close() # ### When Human is player # In[4]: class Human: def __init__(self, name): self.name = name def NextMove(self, positions): while True: row = int(input("Input your action row:")) col = int(input("Input your action col:")) action = (row, col) if action in positions: return action def addState(self, state): pass def feedReward(self, reward): pass def reset(self): pass # ### Training the model # In[5]: p1 = Model("p1") p2 = Model("p2") st = Game(p1, p2) print("training...") st.play(50000) # In[6]: p1.saveDict() p2.saveDict() # In[7]: p1.loadDict("policy_p1") # In[8]: p1 = Model("computer" , 0) p1.loadDict("policy_p1") p2 = Human("You") st = Game(p1, p2) st.play2()
bb69b0aa43fa4249d3a392f643e07d6c699d22de
celeste16/gwc-2017
/triangle.py
466
4.09375
4
from turtle import * import math # Name your Turtle. t = Turtle() # Set Up your screen and starting position. t.penup() setup(500,300) x_pos = -0 y_pos = -0 t.setposition(x_pos, y_pos) ### Write your code below: t.pendown() t.pencolor("black") t.fillcolor("hot pink") t.begin_fill() t.forward(100) t.right(120) t.forward(100) t.right(120) t.forward (100) t.right(120) t.forward(100) t.end_fill() # Close window on click. exitonclick()
2fa79815188096b82806ce536187c9555c1d682b
Zuck84/Money-Convertor
/For Linux & Mac OS/ConvertingMoney.py
11,050
4.0625
4
from decimal import Decimal import os os.system("clear") # EVENTS OF THE PROGRAM def Dollar(): final_currency_dollar = input ("\n New Currency ---> ") final_currency_dollar = float(final_currency_dollar) if final_currency_dollar == 2: initial = input("\n $") initial = float(initial) final = initial * 0.92 print("\n €", final) elif final_currency_dollar == 3: initial = input("\n $") initial = float(initial) final = initial * 108.2 print("\n JAP¥", final) elif final_currency_dollar == 4: initial = input("\n $") initial = float(initial) final = initial * 7.1 print("\n CHN¥", final) elif final_currency_dollar == 5: initial = input("\n $") initial = float(initial) final = initial * 23.39 print("\n MXN$", final) elif final_currency_dollar == 6: initial = input("\n $") initial = float(initial) final = initial * 0.8 print("\n £", final) elif final_currency_dollar == 7: initial = input("\n $") initial = float(initial) final = initial * 0.00016 print("\n ฿", final) else: print("You didn't choose an available currency, try again!") quit = input("Do you want to quit the program ? (y/n)") if quit == "y": print("End of the Program...") else: Dollar() def Euro(): final_currency_euro = input ("\n New Currency ---> ") final_currency_euro = float(final_currency_euro) if final_currency_euro == 1: initial = input("\n €") initial = float(initial) final = initial * 1.12 print("\n $", final) elif final_currency_euro == 3: initial = input("\n €") initial = float(initial) final = initial * 120.52 print("\n JAP¥", final) elif final_currency_euro == 4: initial = input("\n €") initial = float(initial) final = initial * 7.93 print("\n CHN¥", final) elif final_currency_euro == 5: initial = input("\n €") initial = float(initial) final = initial * 26.12 print("\n MXN$", final) elif final_currency_euro == 6: initial = input("\n €") initial = float(initial) final = initial * 0.9 print("\n £", final) elif final_currency_euro == 7: initial = input("\n €") initial = float(initial) final = initial * 0.00018 print("\n ฿", final) else: print("You didn't choose an available currency, try again!") quit = input("Do you want to quit the program ? (y/n)") if quit == "y": print("End of the Program...") else: Euro() def Yen(): final_currency_yen = input ("\n New Currency ---> ") final_currency_yen = float(final_currency_yen) if final_currency_yen == 1: initial = input("\n JAP¥") initial = float(initial) final = initial * 0.0093 print("\n $", final) elif final_currency_yen == 2: initial = input("\n JAP¥") initial = float(initial) final = initial * 0.0083 print("\n €", final) elif final_currency_yen == 4: initial = input("\n JAP¥") initial = float(initial) final = initial * 0.066 print("\n CHN¥", final) elif final_currency_yen == 5: initial = input("\n JAP¥") initial = float(initial) final = initial * 0.22 print("\n MXN$", final) elif final_currency_yen == 6: initial = input("\n JAP¥") initial = float(initial) final = initial * 0.0074 print("\n £", final) elif final_currency_yen == 7: initial = input("\n JAP¥") initial = float(initial) final = initial * 0.0000015 print("\n ฿", final) else: print("You didn't choose an available currency, try again!") quit = input("Do you want to quit the program ? (y/n)") if quit == "y": print("End of the Program...") else: Yen() def Yuan(): final_currency_yuan = input ("\n New Currency ---> ") final_currency_yuan = float(final_currency_yuan) if final_currency_yuan == 1: initial = input("\n CHN¥") initial = float(initial) final = initial * 0.14 print("\n $", final) elif final_currency_yuan == 2: initial = input("\n CHN¥") initial = float(initial) final = initial * 0.13 print("\n €", final) elif final_currency_yuan == 3: initial = input("\n CHN¥") initial = float(initial) final = initial * 15.21 print("\n JAP¥", final) elif final_currency_yuan == 5: initial = input("\n CHN¥") initial = float(initial) final = initial * 3.3 print("\n MXN$", final) elif final_currency_yuan == 6: initial = input("\n CHN¥") initial = float(initial) final = initial * 0.11 print("\n £", final) elif final_currency_yuan == 7: initial = input("\n CHN¥") initial = float(initial) final = initial * 0.000023 print("\n ฿", final) else: print("You didn't choose an available currency, try again!") quit = input("Do you want to quit the program ? (y/n)") if quit == "y": print("End of the Program...") else: Yuan() def Pesos(): final_currency_pesos = input ("\n New Currency ---> ") final_currency_pesos = float(final_currency_pesos) if final_currency_pesos == 1: initial = input("\n MXN$") initial = float(initial) final = initial * 0.043 print("\n $", final) elif final_currency_pesos == 2: initial = input("\n MXN$") initial = float(initial) final = initial * 0.038 print("\n €", final) elif final_currency_pesos == 3: initial = input("\n MXN$") initial = float(initial) final = initial * 4.61 print("\n JAP¥", final) elif final_currency_pesos == 4: initial = input("\n MXN$") initial = float(initial) final = initial * 0.3 print("\n CHN¥", final) elif final_currency_pesos == 6: initial = input("\n MXN$") initial = float(initial) final = initial * 0.034 print("\n £", final) elif final_currency_pesos == 7: initial = input("\n MXN$") initial = float(initial) final = initial * 0.0000069 print("\n ฿", final) else: print("You didn't choose an available currency, try again!") quit = input("Do you want to quit the program ? (y/n)") if quit == "y": print("End of the Program...") else: Pesos() def Pound(): final_currency_pound = input ("\n New Currency ---> ") final_currency_pound = float(final_currency_pound) if final_currency_pound == 1: initial = input("\n £") initial = float(initial) final = initial * 1.25 print("\n $", final) elif final_currency_pound == 2: initial = input("\n £") initial = float(initial) final = initial * 1.12 print("\n €", final) elif final_currency_pound == 3: initial = input("\n £") initial = float(initial) final = initial * 134.21 print("\n JAP¥", final) elif final_currency_pound == 4: initial = input("\n £") initial = float(initial) final = initial * 8.84 print("\n CHN¥", final) elif final_currency_pound == 5: initial = input("\n £") initial = float(initial) final = initial * 29.13 print("\n MXN$", final) elif final_currency_pound == 7: initial = input("\n £") initial = float(initial) final = initial * 0.00020 print("\n ฿", final) else: print("You didn't choose an available currency, try again!") quit = input("Do you want to quit the program ? (y/n)") if quit == "y": print("End of the Program...") else: Pound() def Bitcoin(): final_currency_bitcoin = input ("\n New Currency ---> ") final_currency_bitcoin = float(final_currency_bitcoin) if final_currency_bitcoin == 1: initial = input("\n ฿") initial = float(initial) final = initial * 6205.59 print("\n $", final) elif final_currency_bitcoin == 2: initial = input("\n ฿") initial = float(initial) final = initial * 5556.33 print("\n €", final) elif final_currency_bitcoin == 3: initial = input("\n ฿") initial = float(initial) final = initial * 669676.24 print("\n JAP¥", final) elif final_currency_bitcoin == 4: initial = input("\n ฿") initial = float(initial) final = initial * 44037.35 print("\n CHN¥", final) elif final_currency_bitcoin == 5: initial = input("\n ฿") initial = float(initial) final = initial * 143622.14 print("\n MXN$", final) elif final_currency_bitcoin == 6: initial = input("\n ฿") initial = float(initial) final = initial * 4929.8 print("\n £", final) else: print("You didn't choose an available currency, try again!") quit = input("Do you want to quit the program ? (y/n)") if quit == "y": print("End of the Program...") else: Bitcoin() # PROGRAM ORGANIZATION initial_currency = input ("\n Initial Currency (type a number): \n 1- dollar ($) \n 2- euro (€) \n 3- japanese yen (JAP¥) \n 4- chinese yuan (CHN¥) \n 5- pesos (MXN$) \n 6- pounds (£) \n 7- bitcoins (฿) \n ---> ") initial_currency = float(initial_currency) if initial_currency == 1: Dollar() elif initial_currency == 2: Euro() elif initial_currency == 3: Yen() elif initial_currency == 4: Yuan() elif initial_currency == 5: Pesos() elif initial_currency == 6: Pound() elif initial_currency == 7: Bitcoin() else: print("\n You didn't choose an available currency, try again!") os.system("python3 ConvertingMoney.py")
2fd7d2546a5bc41e1e9daee2c1c17060afede28d
thenickforero/holbertonschool-machine_learning
/supervised_learning/0x00-binary_classification/6-neuron.py
7,567
4.34375
4
#!/usr/bin/env python3 """Module that contains a basic implementation of a Neuron that performs binary classification. """ import numpy as np class Neuron(): """Class that defines a single neuron performing binary classification. """ def __init__(self, nx): """Initialize a Neuron instance according to a number of input features. Arguments: nx (Int): Is the number of input features to the neuron. Raises: TypeError: If nx is not an integer. ValueError: If nx is less than 1. """ # Check if the number of input features have the right format if not isinstance(nx, int): raise TypeError("nx must be an integer") if nx < 1: raise ValueError("nx must be a positive integer") # Initialize the weights, the bias and the activated output # of the neuron. self.__W = np.random.normal(size=(1, nx)) self.__b = 0 self.__A = 0 @property def W(self): """Getter for the weights vector of the neuron. Returns: numpy.ndarray: The weights vector for the neuron. """ return self.__W @property def b(self): """Getter for the bias of the neuron. Returns: float: The bias for the neuron. """ return self.__b @property def A(self): """Getter for the prediction of the neuron. Returns: float: The activated output of the neuron. """ return self.__A def forward_prop(self, X): """Calculates the forward propagation of the neuron. Take in account that the neuron will use the sigmoid activation function. Arguments: X (numpy.ndarray): an array with shape (nx, m) that contains the input data, where: - nx: number of input features to the neuron. - m: number of examples. Returns: float: The activated output of the neuron(prediction). """ input_shape = X.shape weights_shape = self.W.shape # Check if the Input features have the right dimensions. if input_shape[0] != weights_shape[1]: print("Dimension error") else: y = (self.W @ X) + self.b # Applies the sigmoid function as activation function. activated = 1 / (1 + np.exp(-y)) self.__A = activated return self.A def cost(self, Y, A): """Calculates the cost of the model using logistic regression. Take in account that to avoid division by zero errors, 1.0000001 - A will be used instead of 1 - A. m = the number of labels in Y. Arguments: Y (numpy.ndarray): an array with shape (1, m) that contains the correct labels for the input data. A (numpy.ndarray): an array with shape (1, m) containing the activated output of the neuron for each example. Returns: float: the cost of the model. """ number_of_labels = Y.shape[1] cost = np.sum(Y * np.log(A) + (1 - Y) * np.log(1.0000001 - A)) return (-1 / number_of_labels) * cost def evaluate(self, X, Y): """Evaluates the neuron’s predictions. Take in account that: The prediction has a of shape (1, m) containing the predicted labels for each example. The label values are 1 if the output of the network is >= 0.5 and 0 otherwise. Arguments: X (numpy.ndarray): an array with shape (nx, m) that contains the input data, where: - nx: number of input features to the neuron - m: number of examples. Y (numpy.ndarray): an array with shape (1, m) that contains the correct labels for the input data. Returns: tuple(numpy.ndarray, float): the neuron’s prediction and the cost of the network, respectively """ A = self.forward_prop(X) cost = self.cost(Y, A) prediction = np.where(A >= 0.5, 1, 0) return (prediction, cost) def gradient_descent(self, X, Y, A, alpha=0.05): """Calculates one pass of gradient descent on the neuron. Arguments: X (numpy.ndarray): an array with shape (nx, m) that contains the input data, where: - nx: number of input features to the neuron - m: number of examples. Y (numpy.ndarray): an array with shape (1, m) that contains the correct labels for the input data. A (numpy.ndarray): an array with shape (1, m) containing the activated output of the neuron for each example. Keyword Arguments: alpha (float): is the learning rate (default: {0.05}). """ number_of_labels = Y.shape[1] differential_in_z = A - Y differential_in_w = (X @ differential_in_z.T) / number_of_labels differential_in_b = differential_in_z.sum() / number_of_labels self.__W = self.W - (alpha * differential_in_w.T) self.__b = self.b - (alpha * differential_in_b) def train(self, X, Y, iterations=5000, alpha=0.05): """Trains the neuron with a specific number of iterations. Arguments: X (numpy.ndarray): an array with shape (nx, m) that contains the input data, where: - nx: number of input features to the neuron - m: number of examples. Y (numpy.ndarray): an array with shape (1, m) that contains the correct labels for the input data. Keyword Arguments: iterations (int): the number of iterations to train over (default: {5000}). alpha (float): the learning rate (default: {0.05}). Raises: TypeError: if iterations isn't an integer. ValueError: if iterations isn't a positive integer. TypeError: if alpha isn't a float. ValueError: if alpha isn't positive. Returns: tuple(numpy.ndarray, float): the evaluation of the training data after iterations of training have occurred. """ # Check iterations and learning rate if not isinstance(iterations, int): raise TypeError('iterations must be an integer') if iterations < 0: raise ValueError('iterations must be a positive integer') if not isinstance(alpha, float): raise TypeError('alpha must be a float') if alpha < 0: raise ValueError('alpha must be positive') # Start Training for i in range(iterations): A = self.forward_prop(X) self.gradient_descent(X, Y, A, alpha) evaluation = self.evaluate(X, Y) return evaluation
1abd8eea6ff68cbb119651fc9e978bef80dfa1a8
thenickforero/holbertonschool-machine_learning
/math/0x00-linear_algebra/2-size_me_please.py
577
4.4375
4
#!/usr/bin/env python3 """Module to compute the shape of a matrix""" def matrix_shape(matrix): """Calculates the shape of a matrix. Arguments: matrix (list): the matrix that will be processed Returns: tuple: a tuple that contains the shape of every dimmension in the matrix. """ shape = [] dimension = matrix[:] while isinstance(dimension, list): size = len(dimension) shape.append(size) if size > 0: dimension = dimension[0] else: break return shape
79969b00b7683284a24114fa72d3b613caf1d3d2
thenickforero/holbertonschool-machine_learning
/math/0x00-linear_algebra/14-saddle_up.py
598
4.15625
4
#!/usr/bin/env python3 """Module to compute matrix multiplications. """ import numpy as np def np_matmul(mat1, mat2): """Calculate the multiplication of two NumPy Arrays. Arguments: mat1 (numpy.ndarray): a NumPy array that normally represents a square matrix. mat2 (numpy.ndarray): a NumPy array that normally represents a square matrix. Returns: numpy.ndarray: a NumPy array which is the multiplication of @mat1 and @mat2. """ return np.matmul(mat1, mat2)
78c1d41234eac73a6a458bc23d73b63ada9d9d84
M-Mazzoleni96/Landmark-Based-Navigation---Tesi-laurea-2020
/Progetto/Dijkstra.py
1,871
3.78125
4
def dijsktra(graph, initial, end): global total_weight global pesi # shortest paths is a dict of nodes # whose value is a tuple of (previous node, weight) shortest_paths = {initial: (None, 0)} current_node = initial visited = set() total_weight = 0 pesiParz = [] pesi = [] while current_node != end: visited.add(current_node) destinations = graph.edges[current_node] weight_to_current_node = shortest_paths[current_node][1] for next_node in destinations: weight = graph.weights[(current_node, next_node)] + weight_to_current_node if next_node not in shortest_paths: shortest_paths[next_node] = (current_node, weight) else: current_shortest_weight = shortest_paths[next_node][1] if current_shortest_weight > weight: shortest_paths[next_node] = (current_node, weight) next_destinations = {node: shortest_paths[node] for node in shortest_paths if node not in visited} if not next_destinations: return "inesistente" # next node is the destination with the lowest weight current_node = min(next_destinations, key=lambda k: next_destinations[k][1]) # Work back through destinations in shortest path path = [] total_weight = shortest_paths[current_node][1] while current_node is not None: path.append(current_node) pesiParz.append(shortest_paths[current_node][1]) next_node = shortest_paths[current_node][0] current_node = next_node # Reverse path path = path[::-1] pesiParz = pesiParz[::-1] i = 0 pesilen = len(pesiParz) while (pesilen > i + 1): pesi.append(pesiParz[i + 1] - pesiParz[i]) i += 1 return path
0e6bbe6bb462b23c7588eebb661a01880653de4a
tanvirarafin/l2race
/src/car_command.py
1,226
3.703125
4
# structure to hold driver control input class car_command: """ Car control commands from software agent or human driver """ def __init__(self): self.steering=0 # value bounded by -1:1, this is the desired steering angle relative to maximum value and it is only the desired steering angle; actual steering angle is controlled by hidden dynamics of steering actuation and its limits self.throttle=0 # bounded to 0-1 from 0 to maximum possible, acts on car longitudinal acceleration according to hidden car and its motor dynamics self.brake=0 # bounded from 0-1 self.reverse=False # boolean reverse gear self.reset_car=False # in debugging mode, restarts car at starting line self.restart_client=False # abort current run (server went down?) and restart from scratch self.quit=False # quit input from controller, mapped to ESC for keyboard and menu button for xbox controller self.auto = False # activate or deactivate the autonomous driving, mapped to A key or Y Xbox controller button def __str__(self): return 'steering={:.2f}, throttle={:.2f}, brake={:.2f} reverse={}'.format(self.steering, self.throttle, self.brake,self.reverse)
8b86c897a10bb9910e27ec82354136fc9a3c1e38
ErikPerez312/CS-3-Core-Data-Structures
/source/palindromes.py
3,529
4.40625
4
#!python import string import re # Hint: Use these string constants to ignore capitalization and/or punctuation # string.ascii_lowercase is 'abcdefghijklmnopqrstuvwxyz' # string.ascii_uppercase is 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' # string.ascii_letters is ascii_lowercase + ascii_uppercase LETTERS = string.ascii_letters def is_palindrome(text): """A string of characters is a palindrome if it reads the same forwards and backwards, ignoring punctuation, whitespace, and letter casing.""" # implement is_palindrome_iterative and is_palindrome_recursive below, then # change this to call your implementation to verify it passes all tests assert isinstance(text, str), 'input is not a string: {}'.format(text) return is_palindrome_iterative(text) # return is_palindrome_recursive(text) def is_palindrome_iterative(text): # TODO: implement the is_palindrome function iteratively here ##Method 1: lowercase_text = text.lower() left = 0 right = len(lowercase_text) - 1 print(LETTERS) while left < right: ##TODO: Fails two test # current_left_character = lowercase_text[left] # current_right_character = lowercase_text[right] if lowercase_text[left] not in LETTERS: left += 1 continue if lowercase_text[right] not in LETTERS: right -= 1 continue if lowercase_text[left] is not lowercase_text[right]: return False left += 1 right -= 1 return True ##Method 2: # S/O Stack Overflow for Regex. Link: https://stackoverflow.com/questions/1276764/stripping-everything-but-alphanumeric-chars-from-a-string-in-python # text = re.sub(r'\W+', '', text).lower() # left = 0 # right = len(text) - 1 # while left < right: # if text[left] is not text[right]: # return False # left += 1 # right -= 1 # return True # once implemented, change is_palindrome to call is_palindrome_iterative # to verify that your iterative implementation passes all tests def is_palindrome_recursive(text, left=None, right=None): # TODO: implement the is_palindrome function recursively here lowercase_text = text.lower() if left == None and right == None: left = 0 right = len(text) - 1 if left <= right: if lowercase_text[left] not in LETTERS: left_index = left + 1 return is_palindrome_recursive(text, left_index, right) if lowercase_text[right] not in LETTERS: right_index = right - 1 return is_palindrome_recursive(text, left, right_index) if lowercase_text[left] is not lowercase_text[right]: return False return is_palindrome_recursive(text, left + 1, right - 1) return True # once implemented, change is_palindrome to call is_palindrome_recursive # to verify that your iterative implementation passes all tests def main(): import sys args = sys.argv[1:] # Ignore script file name if len(args) > 0: for arg in args: is_pal = is_palindrome(arg) result = 'PASS' if is_pal else 'FAIL' is_str = 'is' if is_pal else 'is not' print('{}: {} {} a palindrome'.format(result, repr(arg), is_str)) else: print('Usage: {} string1 string2 ... stringN'.format(sys.argv[0])) print(' checks if each argument given is a palindrome') if __name__ == '__main__': main()
9590f0ee2cd0330f7acddc3856923b5356db6698
hirosige/python-guys
/008 module/teacher.py
561
3.515625
4
# -*- coding: utf-8 -*- """ Created on Wed Sep 13 13:24:21 2017 @author: mysurface """ class Teacher: def __init__(self, name): self.students = [] self.average = 0 self.name = name def set_name(self, name): self.name = name def get_name(self): return self.name def add_student(self, student): self.students.append(student) def calc_average(self): total = 0 for student in self.students: total += student.get_score() return total / len(self.students)
a403e25b42db8d2b9033c06b5aac45074300d4b3
dkrusch/python
/lists/planets.py
1,109
4.40625
4
planet_list = ["Mercury", "Mars"] planet_list.append("Jupiter") planet_list.append("Saturn") planet_list.extend(["Uranus", "Neptune"]) planet_list.insert(1, "Earth") planet_list.insert(1, "Venus") planet_list.append("Pluto") slice_rock = slice(0, 4) rocky_planets = planet_list[slice_rock] del[planet_list[8]] # Use append() to add Jupiter and Saturn at the end of the list. # Use the extend() method to add another list of the last two planets in our solar system to the end of the list. # Use insert() to add Earth, and Venus in the correct order. # Use append() again to add Pluto to the end of the list. # Now that all the planets are in the list, slice the list in order to get the rocky planets into a new list called rocky_planets. # Being good amateur astronomers, we know that Pluto is now a dwarf planet, so use the del operation to remove it from the end of planet_list. # Example spacecraft list spacecraft = [ ("Cassini", "Saturn"), ("Viking", "Mars"), ] for planet in planet_list: print(planet) for craft in spacecraft: if (craft[1] == planet): print(craft[0])
5cb1287e6fa4f8bd84535bbda3ebe49acc265189
dkrusch/python
/lightning/garrys-garage/garage.py
2,479
3.75
4
class Car: def __init__(self, manufacturer="", model="", horsepower=0, wheel_count=0): self.manufacturer = manufacturer self.model = model self.horsepower = horsepower self.wheel_count = wheel_count class GasPowered(Car): def __init__(self, capacity): super().init(manufacturer="", model="", horsepower=0, wheel_count=0) def drive(self, lowerby): self.gas_level -= lowerby print(f"You used 4 gallons, you have {self.gas_level} gallons left.") def refuel(self): self.gas_level = self.fuel_capacity print(f"The car's gas level is now {self.gas_level}") class ElectricPowered(Car): def __init__(self, manufacturer="", model="", fuel_capacity=0, gas_level=0, horsepower=0, wheel_count=0): self.manufacturer = manufacturer self.model = model self.fuel_capacity = fuel_capacity self.gas_level = gas_level self.horsepower = horsepower self.wheel_count = wheel_count def drive(self, lowerby): self.gas_level -= lowerby print(f"You used 4 gallons, you have {self.gas_level} gallons left.") def refuel(self): self.gas_level = self.fuel_capacity print(f"The car's gas level is now {self.gas_level}") class Mustang(Car): def __init__(self): super().__init__("Mustang", "Ford", 20, 460, 4) def drive(self): super().drive(4) def refuel(self): super().refuel() class Ram(Car): def __init__(self): super().__init__("Ram", "Dodge", 26, 395, 4) def drive(self): super().drive(5) def refuel(self): super().refuel() class Leaf(Car): def __init__(self, battery_level=10, battery_capacity=20): super().__init__("Leaf", "Nissan", 0, 200, 4) self.battery_level = battery_level def drive(self): self.battery_level -= 2 print(f"The battery level has been lowered to {self.battery_level}.") def recharge(self): battery_level = battery_capacity print(f"Battery level is now {battery_capacity}") # 1. Create a Nissan Leaf class # * `manufacturer` attribute # * `model` attribute # * `battery_capacity` attribute # * `battery_level` attribute # * `horsepower` attribute # * `wheel_count` attribute # * `drive()` method lowers `battery_level` by 2 each time it is invoked # * `recharge()` method sets `battery_level` to `battery_capacity` value
174008d5ff445a72a43b6f626b6186d1af637208
heigre/Prime
/primechecker.py
513
3.59375
4
n = [] checker = [] x = 213 for y in range (2, x+1): z = x/(float(y)) checker.append(z) #print checker print z for k in range (0, x-1): p = checker[k] if p.is_integer() == True: n.append(1) else: s=0 if sum(n) > 1: print "" print "" print "" print n print x print "Sadly, it is not a prime" break if sum(n) == 1: print "" print "" print "" print n print x print "It is a prime!"
d5229e9967b6cd88ce6ecb2913a59248c6994e09
ballipongala/sqlworkshops
/PythonForDataProfessionals/Python for Data Professionals/code/02_ProgrammingBasics.py
1,798
4.0625
4
# 02_ProgrammingBasics.py # Purpose: General Programming exercises for Python # Author: Buck Woody # Credits and Sources: Inline # Last Updated: 27 June 2018 # 2.1 Getting Help help() help(str) # <TODO> - Write code to find help on help # 2.2 Code Syntax and Structure # <TODO> - Python uses spaces to indicate code blocks. Fix the code below: x=10 y=5 if x > y: print(str(x) + " is greater than " + str(y)) # <TODO> - Arguments on first line are forbidden when not using vertical alignment. Fix this code: foo = long_function_name(var_one, var_two, var_three, var_four) # <TODO> operators sit far away from their operands. Fix this code: income = (gross_wages + taxable_interest + (dividends - qualified_dividends) - ira_deduction - student_loan_interest) # <TODO> - The import statement should use separate lines for each effort. You can fix the code below # using separate lines or by using the "from" statement: import sys, os # <TODO> - The following code has extra spaces in the wrong places. Fix this code: i=i+1 submitted +=1 x = x * 2 - 1 hypot2 = x * x + y * y c = (a + b) * (a - b) # 2.3 Variables # <TODO> - Add a line below x=3 that changes the variable x from int to a string x=3 type(x) # <TODO> - Write code that prints the string "This class is awesome" using variables: x="is awesome" y="This Class" # 2.4 Operations and Functions # <TODO> - Use some basic operators to write the following code: # Assign two variables # Add them # Subtract 20 from each, add those values together, save that to a new variable # Create a new string variable with the text "The result of my operations are: " # Print out a single string on the screen with the result of the variables # showing that result. # EOF: 02_ProgrammingBasics.py
fdcd57fd81cc62bc189b9a23f762dc3991d3922f
andystjean1/nba-totals-analysis
/data_cleaner.py
7,558
3.65625
4
#clean up and reshape the data from the excel file import datetime import pandas as pd import sys DATA_FILE = "nba_odds_2019-20.xlsx" TEAM_ABV_DICT = {"GoldenState":"GSW", "Boston":"BOS", "NewOrleans":"NOP", "Toronto":"TOR", "LALakers":"LAL", "LAClippers":"LAC", "Detroit":"DET", "Indiana":"IND", "Cleveland":"CLE", "Orlanda":"ORL", "Chicago":"CHI", "Charlotte":"CHA", "Philadelphia":"PHI", "Memphis":"MEM", "Miami":"MIA", "Minnesota":"MIN", "Brooklyn":"BRK", "NewYork":"NYK", "SanAntonio":"SAS", "Washington":"WAS", "Dallas":"DAL", "OklahomaCity":"OKC", "Utah":"UTA", "Sacramento":"SAC", "Phoneix":"PHO", "Denver":"DEN", "Portland":"POR", "Atlanta":"ATL", "Milwaukee":"MIL", "Houston":"HOU", "GoldenState":"GSW" } # get the clean data set # reads in the excel file -- does some cleaning and then returns a dataframe def get_clean_data(): #read the file into a dataframe df = pd.read_excel(DATA_FILE) df = df.drop(columns = ["Rot", "2H", "Open"]) num_rows = int(df.size/(len(df.columns))) #build the clean data frame clean_df = pd.DataFrame() for i in range(0, num_rows, 2): # reformat and build the new rows #print("grabing ", i, i+1) #convert the two row gmae block into single row for each team row_0_dict = convert_row(df.loc[i:i+1], i) row_1_dict = convert_row(df.loc[i:i+1], i+1) #add the new rows to the dataframe if(clean_df.empty): #if the frame is empty initialize it first clean_df = pd.DataFrame(row_0_dict, index=[0]) clean_df = clean_df.append(row_1_dict, ignore_index=True) else: #add both rows to the dictionary clean_df = clean_df.append(row_0_dict, ignore_index=True) clean_df = clean_df.append(row_1_dict, ignore_index=True) #doing some more cleaning #add these to account for overtime clean_df["OT_PTS"] = clean_df.apply(lambda row: calculate_ot_points(row), axis=1) clean_df["OPP_OT_PTS"] = clean_df.apply(lambda row: calculate_opp_ot_points(row), axis=1) clean_df["OT"] = clean_df.apply(lambda row: set_ot_flag(row), axis=1) #clean up the location clean_df["location"] = clean_df.apply(lambda row: clean_location(row), axis=1) #clean up the date and convert it to datetime clean_df["date"] = clean_df.apply(lambda row: format_date(row), axis=1) #map the team names to their abbreviations clean_df["team"] = clean_df["team"].map(TEAM_ABV_DICT) clean_df["opp_team"] = clean_df["opp_team"].map(TEAM_ABV_DICT) #send the frame over return clean_df # take in two rows that represent a game # row number indicates whether to convert the first or the second row # newly formatted row for the given team def convert_row(game, row_number): if(row_number % 2 == 0): #if the row number is even then the opponent is a row above them opp_row_num = row_number + 1 else: # if the row number is odd then the opponent is a row below them opp_row_num = row_number - 1 #print(row_number, opp_row_num) #grab all the values date = game.loc[row_number].Date location = game.loc[row_number].VH team = game.loc[row_number].Team first_qtr_pts = game.loc[row_number, "1st"] second_qtr_pts = game.loc[row_number, "2nd"] third_qtr_pts = game.loc[row_number, "3rd"] fourth_qtr_pts = game.loc[row_number, "4th"] final_score = game.loc[row_number].Final moneyline = game.loc[row_number].ML #grab the values for the opponent opp_team = game.loc[opp_row_num].Team opp_first_qtr_pts = game.loc[opp_row_num, "1st"] opp_second_qtr_pts = game.loc[opp_row_num, "2nd"] opp_third_qtr_pts = game.loc[opp_row_num, "3rd"] opp_fourth_qtr_pts = game.loc[opp_row_num, "4th"] opp_final_score = game.loc[opp_row_num].Final opp_moneyline = game.loc[opp_row_num].ML # grab the total the spread for the game # the number for the spread and the total arent always the same # in this data assuming the the total will be biger than the spread row_0_num = game.loc[row_number].Close row_1_num = game.loc[opp_row_num].Close #figure out which is the total and which is the spread and put it in a dictionary lines = convert_lines(row_0_num, row_1_num) #throw everything into a dictionary to add to the dataframe return { "date": date, "location": location, "team": team, "opp_team": opp_team, "1Q_PTS": first_qtr_pts, "2Q_PTS": second_qtr_pts, "3Q_PTS": third_qtr_pts, "4Q_PTS": fourth_qtr_pts, "final_score": final_score, "opp_1Q_PTS": opp_first_qtr_pts, "opp_2Q_PTS": opp_second_qtr_pts, "opp_3Q_PTS": opp_third_qtr_pts, "opp_4Q_PTS": opp_fourth_qtr_pts, "opp_final_score": opp_final_score, "moneyline": moneyline, "opp_moneyline": opp_moneyline, "total": lines["total"], "spread": lines["spread"], } #format the date to a datetime object # takes in the number from the dataset # returns a datetime object def format_date(row): #####set the year for season being handled -- THIS WILL NEED TO BE CHANGED TO HANDLE DATA FROM DIFF SEASONS##### start_season = 2019 end_season = 2020 #grab the month and the day from the number #print(row) date = row["date"] month = int(date/100) day = int(date % 100) if(month >= 10): #10 is the cutoff because thats when the first game of the season was year = 2019 else: year = 2020 return datetime.date(year, month, day) def convert_lines(row_0_num, row_1_num): PICK_EM_SPREAD = 0.5 if(type(row_0_num) == str): total = row_1_num spread = PICK_EM_SPREAD elif(type(row_1_num) == str): total = row_0_num spread = PICK_EM_SPREAD else: if(row_0_num > row_1_num): total = row_0_num spread = row_1_num else: total = row_1_num spread = row_0_num return {"total": total, "spread": spread} # calculate the points scored in overtime # if there was no overtime it returns 0 def calculate_ot_points(row): total_points = sum(row[["1Q_PTS", "2Q_PTS", "3Q_PTS", "4Q_PTS"]]) return row.final_score - total_points # calculate the points the opponent scored in overtime # if there was no overtime it returns 0 def calculate_opp_ot_points(row): total_points = sum(row[["opp_1Q_PTS", "opp_2Q_PTS", "opp_3Q_PTS", "opp_4Q_PTS"]]) return row.opp_final_score - total_points #sets the flag for the overtime column def set_ot_flag(row): team_pts = sum(row[["1Q_PTS", "2Q_PTS", "3Q_PTS", "4Q_PTS"]]) opp_team_pts = sum(row[["opp_1Q_PTS", "opp_2Q_PTS", "opp_3Q_PTS", "opp_4Q_PTS"]]) if(team_pts == opp_team_pts): return 1 return 0 #clean up the location column def clean_location(row): location = row.location if(location == 'V'): location = 'A' return location
94d4dae91040dd8a74cce61e0977cc3931760ac0
mali44/PythonPracticing
/Palindrome1.py
645
4.28125
4
#Ask the user for a string and print out whether this string is a palindrome or not. #(A palindrome is a string that reads the same forwards and backwards.) mystr1= input("Give a String") fromLeft=0 fromRight=1 pointer=0 while True: if fromLeft > int(len(mystr1)): break if fromRight > int(len(mystr1)): break checker=mystr1[fromLeft] fromLeft+=1 revChecker=mystr1[-fromRight] fromRight+=1 if (checker != revChecker): flag=0 else: flag=1 if pointer==1: print(mystr1+"is a Palindrome") else: print(mystr1+"not a Palindrome")
8b20bc0ca433632db5d3e5f3e6a3284fb504c3e5
MinChul-Son/study_Phython
/day1/day1.py
8,744
3.640625
4
from copy import copy # copy라이브러리 import print("hello") # 이건 주석이에요 a = "hobby" # 원하는값 count함수 print(a.count("b")) # 원하는 값 find 함수(첫번째로 찾은 값의 인덱스 return), 비슷함 함수로 index함수도 있는데 이건 찾는 값있으면 index리턴 없으면 에러 print(a.find("b")) # 원하는 문자열 삽입 a = "," print(a.join('abcd')) # ==>결과:a,b,c,d # 공백지우기 a = " hi " print(a.strip()) # 파이썬에는 문자열 리스트도 있음 # 리스트에 요소추가 a = ["손민철", "유현욱", "이경우"] a.append("강승훈") print(a) # 리스트 vs 튜플==> 리스트는 append, pop, extend등의 함수를 통해 삽입,삭제 등이 가능하지만 튜플은 불가능, 자물쇠로 잠겨있다고 생각, final과 같이 변경 불가 # 튜플 끼리 더하여 새로운 튜플을 출력하는건 가능 # ex) t1 = (1, 2, 'a', 'b') t2 = (3, 4) print(t1+t2) # 튜플에 *3을하면 3번 반복되어 출력 # dictionary == JSON == OBJECT 비슷한 개념 ==> Key를 통해 Value를 얻는다는 것이 핵심개념 # ex) dictionary key값과 value추가 dic = {1: 'a'} dic['name'] = "손민철" print(dic) # ex) 키값 삭제 del dic[1] print(dic) # ex) key 값만 추출, value 값만 추출 dic = {1: "a", 2: "b", 3: "c"} print(dic.keys()) print(dic.values()) print(dic.items()) # 반복문에서 각각의 key값, value값만 추출할때 많이사용 # ex)모두 지우기 dic.clear() print(dic) # ex)키 값으로 직접추출 vs get메소드 활용 vs in dic = {1: "a", 2: "b", 3: "c"} # print(dic[4]) ==>키값이 없으면 에러 print(dic.get(4)) # ==> 없으면 none이라고 나옴 none이 default값이고 따로 메세지 줄수 있음 print(dic.get(4, "없어요")) print(4 in dic) # ==>bool형으로 있으면 true 없으면 false # 집합 자료형: 중복허용 x , 순서 x(unordered) 데이터 다룰때 사용할 일이 많다. s1 = set([1, 2, 3]) # s1 ={1,2,3} 둘다 똑같이 집합을 정의 print(s1) # ex) 중복된 값이 있는 리스트가 있을때 이를 집합으로 바꾸어 중복 제거후 리스트로 다시 변경해 # 중복 값을 제거할 수 있음. s2 = [1, 2, 2, 3, 3] s3 = list(set(s2)) print(s3) # 집합에 문자열을 넣으면 한글자 씩 쪼개짐, 순서가 없으므로 순서가 뒤죽박죽, 중복제거 # 교집합 s1 = set([1, 2, 3, 4, 5, 6]) s2 = set([4, 5, 6, 7, 8, 9]) print(s1 & s2) print(s1.intersection(s2)) # 합집합 print(s1 | s2) print(s1.union(s2)) # 차집합 print(s1 - s2) print(s1.difference(s2)) # 집합에 요소 추가:add ,여러개 요소 추가: update s1.add(7) print(s1) s1.update([8, 9, 10]) print(s1) # 요소 제거:remove s1.remove(1) print(s1) # bool ==> True or False a = True if a: print(s1) # 리스트, 문자열, 튜플, 딕셔너리 값이 있으면 True, 비어있으면 False a = "안녕" if a: print(a) a = "" if a: print(a) # 메모리와 주소 a = [1, 2, 3] b = a a[1] = 4 print(a) print(b) # ==>값을 복사한 것이 아니라 메모리의 같은 주소를 가지고 있으므로 a의 값을 바꾸면 b도 바뀐다 # ex)b의 값을 변하지 않게 하고싶을때 a = [1, 2, 3] b = a[:] # 슬라이싱해서 넣어주면 가능 a[1] = 4 print(a) print(b) a = [1, 2, 3] b = copy(a) a[1] = 4 print(a) print(b) # 변수 할당 방법 a, b = ('python', 'life') print(a) print(b) (a, b) = 'python', 'life' print(a) print(b) a, b = ['python', 'life'] print(a) print(b) [a, b] = 'python', 'life' print(a) print(b) a = b = 'hello' print(a) print(b) # 두 값을 바꾸기 c에서의 SWAP함수 a = 3 b = 5 print(a, b) a, b = b, a print(a, b) # 조건문 if money = True if money: print("택시를 타고 가라") print("adsf") else: print("걸어가라") # 들여쓰기들 맞춰야함 tab키로 제어 중괄호 안에 묶듯이 같은 if문안의 실행문은 들여쓰기로 맞춰줘야함 # in 과 not in number = [1, 2, 3] if 1 in number: print("존재합니다") else: print("존재하지 않습니다") if 1 not in number: print("존재합니다") else: print("존재하지 않습니다") # 조건문에서 아무 것도 실행하지 않게하려면 :pass if 1 in number: pass else: print("존재하지 않습니다") # 다중 조건 판단 elif ==> else if 랑 같은 개념 # 조건부 표현식 score = 70 if score >= 60: message = "success" else: message = "failure" print(message) # 이를 조건부 표현식으로 표현하면 message = "success" if score >= 60 else "failure" print(message) # while문 treeHit = 0 while treeHit < 10: treeHit = treeHit+1 # treeHit++ 사용불가 print("나무를 %d번 찍었습니다." % treeHit) if treeHit == 10: print("나무가 넘어갑니다.") # break: 내가 알던 break문이랑 기능 동일, continue ==> 이 구문을 만나면 while의 맨 위로 올라감. # continue example a = 0 while a < 10: a += 1 if a % 2 == 0: continue # continue구문때문에 짝수는 출력되지 않음. print(a) # for 문 # 기본 구조 for i in 리스트,튜플: # ex) test_list = ['one', 'two', 'three'] for i in test_list: print(i) a = [(1, 2), (3, 4), (5, 6)] for (first, last) in a: print(first+last) for (first, last) in a: print(first) print(last) # for문에서도 break나 continue 사용 가능 # range함수 # for i in range(1,11) ==> 1이상 11미만의 범위 지정 i를 자바나 c에서 for문에 i값의 범위지정하는거랑 마찬가지 # print메소드의 option값중에 end메소드는 출력문 뒤에 값을 정해줄 수 있음 print(2, end=" ") # 연속되는 문자 사이에 공백이나 특정값 넣어줄 수 있음, 단위나 뒤에 특정값 붙일때 사용 print(3) # 리스트 내포(List comprehension) a = [1, 2, 3, 4] result = [num*3 for num in a] print(result) #같은 의미 result = [] for num in a: result.append(num*3) print(result) result = [num*3 for num in a if num % 2 == 0] print(result) #같은 의미 result = [] for num in a: if num % 2 ==0: result.append(num*3) print(result) result = [] result = [x*y for x in range(2, 10) for y in range(1, 10)] print(result) #같은 의미 result = [] for x in range(2,10): for y in range(1, 10): result.append(x*y) print(result) #함수:funcion==> def def sum(a,b): result = a + b return result print(sum(3,4)) def hi(): print("hi") hi() #여러개의 인자를 받고싶을 때 ==>*args , dictionary를 인자로 ==> **kwargs def sum_many(*args): sum = 0 for i in args: sum = sum + i return sum print(sum_many(1,2,3,4,5)) #return 값은 하나이다. 튜플형태로 묶여서 하나로 출력 def sum_and_mul(a,b): return a+b, a*b, a-b print(sum_and_mul(1,2)) #그중 하나만 뽑아서 쓰고싶다면? print(sum_and_mul(1,2)[0]) #나온 튜플 값중 첫번째 index의 값을 추출 #함수 default 값지정 def myself(name, old, man=True): print("나의 이름은 %s 입니다." %name) print("나이는 %d살입니다." %old) if man: print("남자입니다.") else: print("여자입니다.") myself("손민철",24) #함수 선언시 값을 미리 지정해놓으면 default값으로 지정되어 함수호출 때 비워도 dafault값으로 지정 #lambda 함수 def add(a,b): return a+b add = lambda a,b: a+b #두개다 같은 의미 람다함수를 쓰면 축약해서 사용가능하므로 리스트 안에 함수를 넣을수 있음 #ex myList = [lambda a,b: a+b, lambda a,b: a*b] print(myList[0](1,2)) #myList의 0번째 인덱스에 있는 더하는 함수를 가져와서 매개변수로 1과2를 넣은 문장 print(myList[1](1,2)) #input ==> scanf #print print("life" "is" "too short") #문자열 합쳐줌 알아서 print("life","is","too short") #문자열 합쳐주고 콤마를 기준으로 공백 생성 #파일 읽고 쓰기 #write mode f = open("새파일.txt", 'w') for i in range(1, 11): date = "This is %dLine\n" % i f.write(date) f.close() #read mode f = open("새파일.txt", 'r') while True: line = f.readline() #readline() ==> 한 줄씩 읽어온다. if not line: break print(line) f.close() #readlines ==>리스트형태로 가져옴. #read ==> 통채로 가져옴. #readline ==> 한 줄씩 가져옴 #add mode(추가) f = open("새파일.txt", 'a') f.write("This is new line") f.close #with 함수 with open("foo.txt", 'w') as f: f.write("Life is too short, you need python") #foo.txt란 파일을 write모드로 생성하고 f라는 변수에 저장한다.라는 뜻이다. #들여쓰기가 되어 있으므로 개별 함수로 생각, 따라서 close()해줄 필요가 없다.
118535cb3faadb606b2b4803ead697867a76ba1f
osatooh/CIDM6303code
/assignment-python-chapter-1/app.py
593
3.5
4
print("syntax error means there is a problem in the grammar of the expression") print("." * 5) print("An IDE is a code editor with features for autocompletion and debugging.") print("." * 10) print("File extensions for a python app is .py") print("." * 15) print("A linter is to check for syntax errors.") print("." * 20) print("PEP8 is a style guide for best practices in python") print("." * 30) print("machine code is specific to a type of operating system/CPU") print("." * 30) print ("order of execution: Python language, cpython, bytecode, virtual machine, machine code") print("." * 30)
620709285099d86166721d8d860aeb940269982a
sourcedexter/IBM-NLU
/text_analyser.py
9,734
3.640625
4
""" Script to analyse text and gain insights into unstructured data such as Sentiment and Emotion. The complete tutorial can be found at: https://sourcedexter.com/product-review-sentiment-analysis-with-ibm-nlu Author: Akshay Pai Twitter: @sourcedexter Website: https://sourcedexter.com Email: akshay@sourcedexter.com """ from watson_developer_cloud import NaturalLanguageUnderstandingV1 from watson_developer_cloud.natural_language_understanding_v1 import Features, EmotionOptions, SentimentOptions import pandas as pd import matplotlib.pyplot as plt import numpy as np import operator def read_csv_file(file_path): """ method to read a csv file and return an iterable object :param file_path: path to the dataset file :return: iterable object """ # read the file and store it as a dataframe csv_iterator = pd.read_csv(file_path) # print the number of rows found in the file: num_rows, num_cols = csv_iterator.shape print(f"the number of rows found in file: {num_rows}") # print all the column headings print("column headings from raw dataset: ", list(csv_iterator.columns.values)) return csv_iterator def get_distribution(dataframe, target_column): """ method to find the distribution of a certain column in a given dataframe. Shows the generated visualization to the user. :param dataframe: :param target_column: column upon which the distribution needs to be applied :return: dictionary of unique values from target column and its count in the dataset. """ # get the count of unique products in the dataset df_clean = dataframe[target_column].value_counts() print("number of unique products found: ", len(df_clean.values)) # building a scatter plot to show the distribution of products x = df_clean.values # the x axis shows the count of reviews per product y = np.random.rand(len(df_clean.values)) # y axis does not have any significance here. so setting random values z = df_clean.values # the size of each bubble in the scatter plot corresponds to the count of reviews. # use the scatter function to create a plot and show it. plt.scatter(x, y, s=z * 5, alpha=0.5) plt.show() # return the aggregation as a dictionary return df_clean.to_dict() def preprocess_data(dataset_file_path, features_included): """ :param dataset_file_path: path to the dataset :param features_included: list of column names to keep. For example : ["name", "review.txt", "date"] :return: python dict with product name as key and dataframe with reviews in date sorted order. """ # read the dataset file csv_dataframe = read_csv_file(dataset_file_path) # keep only those columns which we need cleaned_frame = csv_dataframe[features_included] # check to see if the column names are what we wanted print("column headings from cleaned frame: ", list(cleaned_frame.columns.values)) # get the count of reviews for each product distribution_result = get_distribution(cleaned_frame, "name") # get the names of products who have more than 300 reviews products_to_use = [] for name, count in distribution_result.items(): if count < 300: products_to_use.append(name) # get only those rows which have the products that we want to use for our analysis cleaned_frame = cleaned_frame.loc[cleaned_frame['name'].isin(products_to_use)] # data structure to store the individual product details dataframe product_data_store = {} for product in products_to_use: # get all rows for the product temp_df = cleaned_frame.loc[cleaned_frame["name"] == product] # the date column is in string format, convert it to datetime temp_df["date"] = pd.to_datetime(temp_df["reviews.date"]) # sort the reviews in reverse chronological order temp_df.sort_values(by='date') # store the dataframe to the product store product_data_store[product] = temp_df.copy() return product_data_store def perform_text_analysis(text): """ method that accepts a piece of text and returns the results for sentiment analysis and emotion recognition. :param text: string that needs to be analyzed :return: dictionary with sentiment analysis result and emotion recognition result """ # initialize IBM NLU client natural_language_understanding = NaturalLanguageUnderstandingV1( version='2018-11-16', iam_apikey='your_api_key_here', url='https://gateway-lon.watsonplatform.net/natural-language-understanding/api' ) # send text to IBM Cloud to fetch analysis result response = natural_language_understanding.analyze(text=text, features=Features( emotion=EmotionOptions(), sentiment=SentimentOptions())).get_result() return response def aggregate_analysis_result(product_dataframe): """ method to analyse and aggregate analysis results for a given product. :param product_dataframe: preprocessed dataframe for one product :return: """ # data structure to aggregated result product_analysis_data = {} count = 0 print("shape of dataframe", product_dataframe.shape) # iterate through the reviews in the dataframe row-wise for row_index, row in product_dataframe.iterrows(): print(count + 1) count += 1 review_text = row["reviews.text"] date = row["reviews.date"] # get the sentiment result. analysis = perform_text_analysis(review_text) sentiment_value = analysis["sentiment"]["document"]["score"] # emotion of the text is the emotion that has the maximum value in the response. # Example dict: {"joy":0.567, "anger":0.34, "sadness":0.8,"disgust":0.4}. # in the dict above, the emotion is "Sadness" because it has the max value of 0.8 emotion_dict = analysis["emotion"]["document"]["emotion"] # get emotion which has max value within the dict emotion = max(emotion_dict.items(), key=operator.itemgetter(1))[0] # check if review on date exists. if yes: update values, if no: create new entry in dict if date in product_analysis_data: product_analysis_data[date]["sentiment"].append(sentiment_value) product_analysis_data[date]["emotion"].append(emotion) else: product_analysis_data[date] = {} product_analysis_data[date]["sentiment"] = [sentiment_value] product_analysis_data[date]["emotion"] = [emotion] # find the average sentiment for each date and update the dict. for date in product_analysis_data.keys(): sentiment_avg = sum(product_analysis_data[date]["sentiment"]) / len( product_analysis_data[date]["sentiment"]) product_analysis_data[date]["sentiment"] = sentiment_avg return product_analysis_data def visualize_sentiment_data(prod_sentiment_data): """ takes in the sentiment data and produces a time series visualization. :param prod_sentiment_data: :return: None. visualization is showed """ # to visualize, we will build a data frame and then plot the data. # initialize empty dataframe with columns needed df = pd.DataFrame(columns=["date", "value"]) # add data to the data frame dates_present = prod_sentiment_data.keys() for count, date in enumerate(dates_present): df.loc[count] = [date, prod_sentiment_data[date]["sentiment"]] # set the date column as a datetime field df["date"] = pd.to_datetime(df['date']) # convert dataframe to time series by setting datetime field as index df.set_index("date", inplace=True) # convert dataframe to series and plat it. df_series = pd.Series(df["value"], index=df.index) df_series.plot() plt.show() def visualize_emotion_data(prod_emotion_data): """ method that takes in emotion data and generates a pei chart that represnts the count of each emotion. IBM provides data for 5 types of emotions: Joy, Anger, Disgust, Sadness, and fear :param prod_emotion_data: :return: """ # data structure to hold emotions data prod_emotions = {} for key in prod_emotion_data.keys(): emotions = prod_emotion_data[key]["emotion"] # update emotion count in the emotions data store for each_emotion in emotions: if each_emotion in prod_emotions: prod_emotions[each_emotion] += 1 else: prod_emotions[each_emotion] = 1 # define chart properties labels = tuple(prod_emotions.keys()) sizes = list(prod_emotions.values()) # initialize the chart plt.pie(sizes, labels=labels, autopct='%1.1f%%', shadow=True, startangle=90) plt.axis('equal') # Equal aspect ratio ensures that pie is drawn as a circle. plt.show() # starting point of script execution if "__main__" == __name__: # pass the location of the dataset file and the list of columns to keep to the pre-processing method dataframe_clean = preprocess_data("./Datafiniti_Amazon_Consumer_Reviews_of_Amazon_Products.csv", ["id", "name", "reviews.date", "reviews.text"]) # get the list of product names prod_names = list(dataframe_clean.keys()) for each_prod in prod_names: # get the dataframe prod_dataframe = dataframe_clean[each_prod] # start analysis of all the reviews for the product result_analysis = aggregate_analysis_result(each_prod) print("product analysis complete") # visualize both sentiment and emotion results visualize_sentiment_data(result_analysis) visualize_emotion_data(result_analysis)
71dad1096b5699d19ad30d431d025aa12b8165f4
E-Cell-VSSUT/coders
/python/IBAN.py
2,276
4.125
4
# IBAN ( International Bank Account Number ) Validator ''' An IBAN-compliant account number consists of: -->a two-letter country code taken from the ISO 3166-1 standard (e.g., FR for France, GB for Great Britain, DE for Germany, and so on) -->two check digits used to perform the validity checks - fast and simple, but not fully reliable, tests, showing whether a number is invalid (distorted by a typo) or seems to be good; -->the actual account number (up to 30 alphanumeric characters - the length of that part depends on the country) The standard says that validation requires the following steps (according to Wikipedia): (step 1) Check that the total IBAN length is correct as per the country. (step 2) Move the four initial characters to the end of the string (i.e., the country code and the check digits) (step 3) Replace each letter in the string with two digits, thereby expanding the string, where A = 10, B = 11 ... Z = 35; (step 4) Interpret the string as a decimal integer and compute the remainder of that number on division by 97; If the remainder is 1, the check digit test is passed and the IBAN might be valid. ''' def country_length(name): if name == 'INDIA': return 'IN' elif name == 'USA' or name == 'UNITED STATES': return 'US' elif name == 'UK' or name == 'GREAT BRITAIN': return 'GB' elif name == 'GERMANY': return 'DE' iban = input("Enter IBAN, please: ") iban = iban.replace(' ', '') country = input('Enter your country: ').upper() iban_len = country_length(country) if not iban.isalnum(): # checking for special characters in IBAN print('Invalid characters entered') elif len(iban) < 15: # checking if the length is less than 15 print('IBAN enetered is too short') elif len(iban) > 31: # checking if the length is greater than 15 print('IBAN enetered is too long') else: # checking the iban after adding the first four characters to the end of iban iban = (iban[4:] + iban[0:4]).upper() iban2 = '' for ch in iban: if ch.isdigit(): iban2 += ch else: iban2 += str(10 + ord(ch) - ord('A')) iban = int(iban2) if iban % 97 == 1: print("IBAN entered is valid.") else: print("IBAN entered is invalid.")
68e650fa51502dcc2a1e15bb7b956cb0c8630c58
E-Cell-VSSUT/coders
/python/Fibonacci.py
750
4.3125
4
# -- Case-1 -->> Using Function # This is a program to find fibonacci series using simple function def fib(n): if n < 1: # Fibonacci is not defined for negative numbers return None if n < 3: # The first two elements of fibonacci are 1 return 1 elem1 = elem2 = 1 sum = 0 for i in range(3, n+1): sum = elem1+elem2 elem1, elem2 = elem2, sum # First element becomes becomes second element # Second element becomes the sum of previous two elements return sum #--Main--# for i in range(1, 10): print(i, " -->> ", fib(i)) # -- Case-2 -->> Using Recursive Function def fib_rec(n): if n < 0: return None if n < 3: return 1 return fib(n-1)+fib(n-2)
0a95d362e7e9afd2c4c95d3937dfd9c7914ea2d7
Ispaniolochka/lab_python
/3_3_math_sin.py
393
4.3125
4
'''Написать программу, вычисляющую значение функции (на вход подается вещественное число):''' import math def value(x): if 0.2<= x <= 0.9: print('результат:', math.sin(x)) else: print('результат:',1) element=input('Введите число:') result=value(float(element))
0b9a4aa03fa604c841688a7847118df804b2c5ed
Ispaniolochka/lab_python
/homework3_2.py
383
3.703125
4
import random num = random.randint(1,4) user_num = int(input('Введите число от 1 до 4:')) if user_num == num: print('Победа') elif user_num > num: print('Не угадали. Ваше число больше!') elif user_num < num: print('Не угадали. Ваше число меньше!') else: print('Повторите еще раз!')
7469de4e15f499d391230cd8f11527e36f9de942
Ispaniolochka/lab_python
/homework1.py
345
4.0625
4
element=input("Введите номер элемента:") if len(element)>0: number=int(element) if number==3: print(number,'Li') elif number==17: print(number,'Cl') elif number==25: print(number,'Mn') elif number==80: print(number,'Hg') else: print('Вы не ввели число!')
e98d98a90049e360c7f398921cd5c545f0d865f8
Ispaniolochka/lab_python
/homework3_3.py
207
3.953125
4
import math def value(x): if 0.2<= x <= 0.9: return math.sin(x) else: 1 element=input('Введите число:') result=value(float(element)) print('результат:',result)
6448f6f3a3c44296e2bb0166000a6cb7d91898d9
smitamitra2016/Python-test
/TestPython/com/Conditional.py
357
3.734375
4
''' Created on 26 Jan 2017 @author: Nomad Digital ''' a,b = 4,1 if (a+b)<2: print('Summation {} is less than 2'.format((a+b))) else: print('Summation {} is greater than 2'.format((a+b))) print("abc" if (a+b)<2 else "def") choices = dict( one = 1, two = 2, three = 3 ) #print(choices['four']) print(choices.get('four'))
5eec04b7937ecc36999127b68edf991e68db7cf7
Remor53/lesson2
/strings.py
1,256
4.375
4
def str_check(str1, str2): """Проверяет объекты на пренадлежность типу string. Если оба объекта строки, то проверяет одинаковые ли они, если разные, то определяет какая длиннее и проверяет, является ли вторая строка словом 'learn' Ключевые аргументы: str1 -- первый объект str2 -- второй объект Возвращает: различные целые числовые значения (int), либо кортеж из двух чисел (tuple) """ type1 = str(type(str1)) type2 = str(type(str2)) if type1 != '<class \'str\'>' or type2 != '<class \'str\'>': return 0 elif len(str1) == len(str2): return 1 elif len(str1) > len(str2): if str2 == 'learn': return 2, 3 else: return 2 elif str2 == 'learn': return 3 if __name__ == '__main__': print(str_check(1, 3)) print(str_check('hello', 'hello')) print(str_check('good morning', 'hello')) print(str_check('learning', 'learn')) print(str_check('read', 'learn'))
8fbc68d5d56c5f11b8f827b60febdb9674c9f1d7
sahay1996/Project1
/Project1.py
749
3.90625
4
import random def game(comp, b): if comp==b: return None elif comp =='s': if b=='w': return False elif b=='g': return True elif comp=='w': if b=='w': return False elif b=='g': return True print("Computer Turn: Snake(s) Water(w) or Gun(g)? \n") randno=random.randint(1,3) if randno==1: com = 's' elif randno==2: com ='w' elif randno==3: com = 'g' b=input("Your Turn: Snake(s) Water(w) or Gun(g)? \n") print("Computer chose:", com) print("You chose: ", b) WinorLose=game(com, b) if WinorLose== None: print("It's a Tie") elif WinorLose: print("You Win!") else: print("You Lose!")
b1e76d86c4ab0af7af6b5c86308e8797abb0479b
akashsrikanth2310/expertiza-topic-bidding
/app/matching_model.py
9,694
3.59375
4
import math import random import json class Topic: """ Base class for Assignment Topics ATTRIBUTES: ---------- model : MatchingModel The parent matching model according to whose rules the matching will be done. id : String The topic ID corresponding to the topic. preferences : list {String, String, ....} List of student IDs in the linear order of the topic's preference. current_proposals : list {String, String, ....} The list of student_ids to which the topic has proposed in the current step. Initially empty. accepted_proposals : list {String, String, ....} The list of student_ids who have accepted the topic's proposal so far. Initially empty. last_proposed : Integer The position of the student_id in the topic's preference list to which the topic has last proposed. Initialized to -1. num_remaining_slots : Integer Number of students the topic can still be assigned to. Or equivalently, number of students the topic can still propose to. Initially model.p_ceil. """ current_proposals = [] accepted_proposals = [] last_proposed = -1 def __init__(self,model,id,preferences): self.id = id self.preferences = preferences self.model = model self.num_remaining_slots = self.model.p_ceil def propose(self,num): """ Proposes to accept 'num' number of Students it has not yet proposed to, or proposes to accept all the Students it has not yet proposed to if they are less in number than 'num'. """ if(self.last_proposed+num <= len(self.preferences)-1): self.current_proposals = self.preferences[self.last_proposed + 1 :self.last_proposed+num+1] self.last_proposed = self.last_proposed + num else: self.current_proposals = self.preferences[self.last_proposed + 1 :len(self.preferences)] self.last_proposed = len(self.preferences)-1 for student_id in self.current_proposals: self.model.get_student_by_id(student_id).receive_proposal(self.id) def acknowledge_acceptance(self,student_id): """ Acknowledges acceptance of proposal by a student. """ self.accepted_proposals.append(student_id) self.num_remaining_slots -= 1 def done_proposing(self): ''' Returns a boolean indicating whether the topic has proposed to all the students in its preference list. ''' return (self.last_proposed >= len(self.preferences)-1) def slots_left(self): ''' Returns a boolean indicating whether the topic has any slots left in its quota of students. ''' return self.num_remaining_slots > 0 class Student: """ Base class for Review Participants ie., Students. ATTRIBUTES: ---------- model : MatchingModel The parent matching model according to whose rules the matching will be done. id : String The Student ID corresponding to the student. preferences : list {String, String, ....} List of topic IDs in the linear order of the student's preference. current_proposals : list {String, String, ....} The list of topic_ids who have proposed to the student in the current step. Initially empty. accepted_proposals : list {String, String, ....} The list of topic_ids whose proposals the student has accepted so far. Initially empty. num_remaining_slots : Integer The number of topics the student can be still assigned. Initially model.q_S. """ current_proposals = [] accepted_proposals = [] def __init__(self,model,id,preferences): self.model = model self.id = id self.preferences = preferences self.num_remaining_slots = self.model.q_S def receive_proposal(self,topic_id): """ Receives Proposal from a topic. """ self.current_proposals.append(topic_id) def accept_proposals(self): """ Accepts no more than k = num_remaining_slots proposals according to their preferences, rejecting the rest. """ self.current_proposals = list(set(self.current_proposals)) self.current_proposals.sort(key=lambda x: self.preferences.index(x)) self.accepted_proposals = self.accepted_proposals + \ self.current_proposals[:min(len(self.current_proposals), max(self.num_remaining_slots,0))] self.current_proposals = [] for topic_id in self.accepted_proposals: self.model.get_topic_by_id(topic_id).acknowledge_acceptance(self.id) self.num_remaining_slots -= len(self.accepted_proposals) class MatchingModel: """ Base Class for the Many-to-Many Matching Problem/Model ATTRIBUTES: ---------- student_ids : list {String, String, ....} A list containing all the Student IDs. topic_ids : list {String, String, ....} A list containing all the Topic IDs. students : list {Student, Student, ....} A list containing objects of the 'Student' class, corresponding to the student IDs in student_ids. topics : list {Topic, Topic, ....} A list containing objects of the 'Topic' class, corresponding to the topic IDs in topic_ids. q_S : Integer Number of topics a student must be assigned. num_students : Integer Total number of students. num_topics : Integer Total number of topics in the assignment. p_floor : Integer Floor of average number of students assigned each topic. p_ceil : Integer Ceil of average number of students assigned each topic. """ def __init__(self,student_ids,topic_ids,student_preferences_map, topic_preferences_map,q_S): self.student_ids = student_ids self.topic_ids = topic_ids self.q_S = q_S self.num_students = len(self.student_ids) self.num_topics = len(self.topic_ids) if(self.num_topics==0): self.num_topics=1 self.p_floor = math.floor(self.num_students * q_S/self.num_topics) self.p_ceil = math.ceil(self.num_students * q_S/self.num_topics) self.students = list(map(lambda student_id: Student(self,student_id, student_preferences_map[student_id]), student_ids)) self.topics = list(map(lambda topic_id: Topic(self,topic_id, topic_preferences_map[topic_id]), topic_ids)) def get_student_by_id(self,student_id): """ Returns Student object corresponding to the given student_id. """ student_id_index = self.student_ids.index(student_id) return self.students[student_id_index] def get_topic_by_id(self,topic_id): """ Returns Topic object corresponding to the given topic_id. """ topic_id_index = self.topic_ids.index(topic_id) return self.topics[topic_id_index] def stop_condition(self): """ Returns a boolean indicating whether the stop condition to the algorithm has been met. """ flag = True for topic in self.topics: if (topic.slots_left()): if not topic.done_proposing(): flag = False break return flag def get_matching(self): """ Runs the Many-to-Many matching algorithm on the students and students according to the specified quotas and returns a stable matching. RETURNS: ------- matching : dict {String : list of Strings, String : list of Strings, ....} key: Student ID value: List of topic IDs corresponding to the topics assigned to the student. """ # Highly Recommended: Read the algorithm in the wiki page to better # understand the following code. # Wiki Link: http://wiki.expertiza.ncsu.edu/index.php/CSC/ECE_517_Fall_2019_-_E1986._Allow_reviewers_to_bid_on_what_to_review # Step 1: Each topic proposes to accept the first p_ceil students in # its preference list. # Each student accepts no more than q_S proposals according to their # preferences, rejecting the rest. for topic in self.topics: topic.propose(self.p_ceil) for student in self.students: student.accept_proposals() # Step k: Each course that has z < p_ceil students proposes to accept # p_ceil - z students it has not yet proposed to. # Each student accepts no more than qS proposals according to their # preferences, rejecting the others. # The algorithm stops when every topic that has not reached the # maximum quota p_ceil has proposed acceptance to every student. while(self.stop_condition() == False): for topic in self.topics: topic.propose(num = topic.num_remaining_slots) for student in self.students: student.accept_proposals() # Return a dictionary that represents the resultant stable matching. matching = dict() for student in self.students: matching[student.id] = student.accepted_proposals return matching
7cda694f8abc221af457b68cfc6de3169515931d
wu4f/cyberpdx-crypto
/www/users.py
4,542
3.6875
4
""" +------------+------------------+ | Username | PassHash | +============+==================+ | John Doe | 1234 | +------------+------------------+ This can be created with the following SQL (see bottom of this file): create table users (username text, passhash text); """ import sqlite3, csv from passlib.hash import pbkdf2_sha256 import shlex, subprocess import settings DB_FILE = 'users.db' # file for our Database class Users(): def __init__(self): # Make sure our database exists self.connection = sqlite3.connect(DB_FILE) cursor = self.connection.cursor() try: cursor.execute("select count(rowid) from users") except sqlite3.OperationalError: self.initializeUsers() def initializeUsers(self): cursor = self.connection.cursor() cursor.execute("create table users (username text, passhash text)") self.addUser('admin', settings.admin_pass) for i in range(10): self.addUser(f'demo{i}','malware') def addUser(self, username, password): """ Checks to see user does not exist, then adds user Each row contains: name, email, date, message :param username: String :param password: String :return: True if successful, False if user exists already """ cursor = self.connection.cursor() params = {'username':username} cursor.execute("SELECT username FROM users WHERE username=(:username)", params) res = cursor.fetchall() if len(res) == 0: passhash = pbkdf2_sha256.hash(password) params = {'username':username, 'passhash':passhash} print(f'Adding {username} with password {password} and hash {passhash}') cursor.execute("insert into users (username, passhash) VALUES (:username, :passhash)", params) self.connection.commit() subprocess.Popen(shlex.split(f'/bin/mkdir -p static/obj/{username}/solved')) return True else: return False def checkUser(self, username, password): """ Checks credentials :param username: String :param password: String :return: True if successful, False if user exists already :raises: Database errors on connection and insertion """ params = {'username':username} cursor = self.connection.cursor() cursor.execute("select passhash from users WHERE username=(:username)", params) res = cursor.fetchall() if len(res) != 0: hash = res.pop()[0] if (pbkdf2_sha256.verify(password, hash)): return True return False def changeUser(self, username, password): """ Checks credentials :param username: String :param password: String :return: True if successful, False if user exists already :raises: Database errors on connection and insertion """ passhash = pbkdf2_sha256.hash(password) params = {'username':username, 'passhash':passhash} cursor = self.connection.cursor() cursor.execute("update users SET passhash = (:passhash) WHERE username=(:username)", params) self.connection.commit() print(f'Changing {username} with {password} and hash {passhash}') return True def importUsers(self, filename): """ :param filename: String """ f = open(filename, 'r') reader = csv.DictReader(f, fieldnames = ('username','password')) imported = [] notimported = [] cnt = 0; for row in reader: if self.addUser(row['username'],row['password']): imported.append((row['username'],row['password'])) cnt = cnt + 1 else: notimported.append((row['username'],row['password'])) return imported, notimported def dumpUsers(self): """ Gets all users from the database :return: List of users """ cursor = self.connection.cursor() cursor.execute("SELECT username FROM users") res = cursor.fetchall() return [ i[0] for i in res ] def resetCTF(self): """ Reset the CTF """ cursor = self.connection.cursor() cursor.execute("drop table users") subprocess.Popen(shlex.split(f'/bin/rm -rf static/obj')) self.initializeUsers() return True
0eb2e3d2ba757ffdae11e4b78ec73ac6e035ce24
OmarAnwar19/Voice-Prescription-Maker
/SET Hackathon/First Course - 1.py
3,087
4.03125
4
from random import randint game_run = True game_record = [] def calc_monster_attack(attack_min, attack_max): return randint(attack_min, attack_max) def game_over(victor_name): print(F"{victor_name} Won!") while game_run == True: round_counter = 0 new_round = True player = {"name": "", "attack": 13, "heal": 16, "health": 100} monster = {"name": "", "attack_min": 10, "attack_max": 20, "health": 100} print("---" * 7) print("Enter Player Name") player["name"] = input() print("") print("Enter Monster Name") monster["name"] = input() print("") print("Hello, ", player["name"], "!") print(player["name"], " Health = ", player["health"]) print(monster["name"], " Health = ", monster["health"]) while new_round == True: round_counter = round_counter + 1 player_win = False monster_win = False print("---" * 7) print("Please select action", "\n") print("1) Attack") print("2) Heal") print("3) Exit Game") print("4) Show Previous Results") action_choice = input() print ("") if action_choice == "1": monster["health"] = monster["health"] - player["attack"] if monster["health"] <= 0: player_win = True else: player["health"] = player["health"] - calc_monster_attack(monster["attack_min"], monster["attack_max"]) if player["health"] <= 0: monster_win = True print(player["name"], " Attacks!") print(monster["name"], " Attacks!", "\n") elif action_choice == "2": player["health"] = player["health"] + player["heal"] player["health"] = player["health"] - calc_monster_attack(monster["attack_min"], monster["attack_max"]) if player["health"] <= 0: monster_win = True print(player["name"] + " Heals") elif action_choice == "3": game_run = False new_round = False elif action_choice == "4": for i in game_record: print(i) print("") else: print ("Invalid Input") if player_win == False and monster_win == False: print(monster["name"], "Health = ", monster["health"], "\n" ) print(player["name"], "Health = ", player["health"], "\n") elif player_win: game_over(player["name"]) round_data = {"winner_name": player["name"], "health": monster["health"], "rounds": round_counter} game_record.append(round_data) new_round = False elif monster_win: game_over(monster["name"]) round_data = {"winner_name": monster["name"], "health": monster["health"], "rounds": round_counter} game_record.append(round_data) new_round = False
df1f60c45a33ca268610f2428289efc27342e12f
fbscott/BYU-I
/CS241 (Survey Obj Ort Prog Data Struct)/_starter_files/assign04/main.py
1,562
3.75
4
""" File: main.py Author: Br. Burton This file tests the customer, order, and product classes for assignment 04. You should not need to change this file. """ from customer import Customer from order import Order from product import Product def main(): print("### Testing Products ###") p1 = Product("1238223", "Sword", 1899.99, 10) print("Id: {}".format(p1.id)) print("Name: {}".format(p1.name)) print("Price: {}".format(p1.price)) print("Quantity: {}".format(p1.quantity)) p1.display() print() p2 = Product("838ab883", "Shield", 989.75, 6) print("Id: {}".format(p2.id)) print("Name: {}".format(p2.name)) print("Price: {}".format(p2.price)) print("Quantity: {}".format(p2.quantity)) p2.display() print("\n### Testing Orders ###") # Now test Orders order1 = Order() order1.id = "1138" order1.add_product(p1) order1.add_product(p2) order1.display_receipt() print("\n### Testing Customers ###") # Now test customers c = Customer() c.id = "aa32" c.name = "Gandalf" c.add_order(order1) c.display_summary() print() c.display_receipts() # Add another product and order and display again p3 = Product("2387127", "The Ring", 1000000, 1) p4 = Product("1828191", "Wizard Staff", 199.99, 3) order2 = Order() order2.id = "1277182" order2.add_product(p3) order2.add_product(p4) c.add_order(order2) print() c.display_summary() print() c.display_receipts() if __name__ == "__main__": main()
79deed779d787d6b116860d08fedbff0a9e216db
fbscott/BYU-I
/CS241 (Survey Obj Ort Prog Data Struct)/checkpoints/check08b.py
1,915
3.65625
4
############################################################################### # Assignment: # Checkpoint 08b # curtis mellor, cs241 ############################################################################### class GPA: def __init__(self, gpa = 0.0): self.__gpa = float(gpa) def __get_gpa(self): return self.__gpa def __set_gpa(self, gpa): if gpa < 0: self.__gpa = 0 elif gpa > 4: self.__gpa = 4.0 else: self.__gpa = gpa def __get_letter(self): if self.__gpa <= 0.99: return 'F' elif self.__gpa <= 1.99: return 'D' elif self.__gpa <= 2.99: return 'C' elif self.__gpa <= 3.99: return 'B' else: return 'A' def __set_letter(self, letter): if letter == 'F': self.__set_gpa(0.0) elif letter == 'D': self.__set_gpa(1.0) elif letter == 'C': self.__set_gpa(2.0) elif letter == 'B': self.__set_gpa(3.0) else: self.__set_gpa(4.0) gpa = property(__get_gpa, __set_gpa) @property def letter(self): return self.__get_letter() @letter.setter def letter(self, letter): self.__set_letter(letter) def main(): student = GPA() print("Initial values:") print("GPA: {:.2f}".format(student.gpa)) print("Letter: {}".format(student.letter)) value = float(input("Enter a new GPA: ")) student.gpa = value print("After setting value:") print("GPA: {:.2f}".format(student.gpa)) print("Letter: {}".format(student.letter)) letter = input("Enter a new letter: ") student.letter = letter print("After setting letter:") print("GPA: {:.2f}".format(student.gpa)) print("Letter: {}".format(student.letter)) if __name__ == "__main__": main()
ac59fae1f1f0495af9a0ecbcb56aed8723da4391
fbscott/BYU-I
/CS241 (Survey Obj Ort Prog Data Struct)/homework/hw_09_hash_table.py
1,119
3.921875
4
import csv # dictionary to hold the education level and counts education_counts = {} def get_education_counts(file): """hash function""" with open(file) as csv_file: rows = csv.reader(csv_file) for row in rows: # get the education level from the 4th column (index 3) of each row education_level = row[3] # if the education level is in the dictionary if education_level in education_counts: # add 1 to the existing value education_counts[education_level] += 1 # if the education level is NOT in the dictionary else: # add it with a count of 1 education_counts[education_level] = 1 # loop through each key in the dictionary and print out its associated value for key in education_counts.keys(): print(f"{education_counts[key]} -- {key}") csv_file.close() def main(): get_education_counts("c:\\git_repos\\BYU-I\\CS241 (Survey Obj Ort Prog Data Struct)\\_data\\census.csv") if __name__ == "__main__": main()
faf830c550d3166f125c4b846f95de6b1047d5c7
fbscott/BYU-I
/CS241 (Survey Obj Ort Prog Data Struct)/checkpoints/check02b.py
682
4.21875
4
user_provide_file = input("Enter file: ") num_lines = 0 num_words = 0 # method for opening file and assigning its contents to a var # resource: https://runestone.academy/runestone/books/published/thinkcspy/Files/Iteratingoverlinesinafile.html # file = open(user_provide_file, "r") # best practice is to use "with" to ensure the file is properly closed # resource: https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files with open(user_provide_file, "r") as file: for lines in file: words = lines.split() num_lines += 1 num_words += len(words) print(f"The file contains {num_lines} lines and {num_words} words.") file.close()
a4c93b8eb9a24d5e896c869ce1cc6fee77666e60
fbscott/BYU-I
/CS241 (Survey Obj Ort Prog Data Struct)/skeet/flying_object.py
1,213
3.671875
4
import arcade from point import Point from velocity import Velocity class FlyingObject: """ Base (parent) class for all objects (other than the rifle) that move on the screen. """ def __init__(self): """constructor""" self.center = Point() self.velocity = Velocity() self.radius = 0.0 self.color = '' self.alive = True def draw(self): """ Draw the object (bullet, target, etc.) on the screen. Assumes the object is a circle. Can be overridden in the child class. """ arcade.draw_circle_filled( self.center.x, self.center.y, self.radius, self.color) def advance(self): """Moves the object. Adds velocity (dx,dy) to its (x,y) coordinates.""" self.center.x += self.velocity.dx self.center.y += self.velocity.dy def is_off_screen(self, screen_width, screen_height): """Determines if the object is outside the viewable screen area.""" if self.center.x > screen_width or self.center.y > screen_height or self.center.x < 0 or self.center.y < 0: return True else: return False
87f85202f1713c2ac5e6064593f525db40be111c
fbscott/BYU-I
/CS241 (Survey Obj Ort Prog Data Struct)/asteroids/main.py
8,203
3.875
4
""" File: asteroids.py Original Author: Br. Burton Designed to be completed by others This program implements the asteroids game. """ import arcade import os from rock_large import Rock_large from rock_medium import Rock_medium # from rock_small import Rock_small from ship import Ship from bullet import Bullet # These are Global constants to use throughout the game SCREEN_WIDTH = 800 SCREEN_HEIGHT = 600 BULLET_RADIUS = 30 BULLET_SPEED = 10 BULLET_LIFE = 60 SHIP_TURN_AMOUNT = 3 SHIP_THRUST_AMOUNT = 0.25 SHIP_RADIUS = 30 INITIAL_ROCK_COUNT = 5 BIG_ROCK_SPIN = 1 BIG_ROCK_SPEED = 0.5 BIG_ROCK_RADIUS = 15 MEDIUM_ROCK_SPIN = -2 MEDIUM_ROCK_RADIUS = 5 SMALL_ROCK_SPIN = 5 SMALL_ROCK_RADIUS = 2 class Game(arcade.Window): """ This class handles all the game callbacks and interaction This class will then call the appropriate functions of each of the above classes. You are welcome to modify anything in this class. """ def __init__(self, width, height): """ Sets up the initial conditions of the game :param width: Screen width :param height: Screen height """ super().__init__(width, height) # arcade.set_background_color(arcade.color.SMOKY_BLACK) self.held_keys = set() # TODO: declare anything here you need the game class to track self.background = None self.asteroids = [] self.bullets = [] self.ship = Ship( SHIP_RADIUS, SCREEN_WIDTH, SCREEN_HEIGHT, SHIP_THRUST_AMOUNT, SHIP_TURN_AMOUNT ) for i in range(INITIAL_ROCK_COUNT): rock_large = Rock_large( BIG_ROCK_RADIUS, SCREEN_WIDTH, SCREEN_HEIGHT, BIG_ROCK_SPIN, BIG_ROCK_SPEED ) self.asteroids.append(rock_large) def setupBgImage(self): """ Add background image to game. source: https://api.arcade.academy/en/latest/examples/sprite_collect_coins_background.html """ absolutepath = os.path.abspath(__file__) rootDirectory = os.path.dirname(absolutepath) bgImgPath = os.path.join(rootDirectory, 'img') self.background = arcade.load_texture(bgImgPath + "\\space.png") def on_draw(self): """ Called automatically by the arcade framework. Handles the responsibility of drawing all elements. """ # clear the screen to begin drawing arcade.start_render() # TODO: draw each object # Draw the background texture arcade.draw_lrwh_rectangle_textured( 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, self.background ) for asteroid in self.asteroids: asteroid.draw() for bullet in self.bullets: bullet.draw() if self.ship.alive: self.ship.draw() else: arcade.draw_text( "GAME OVER", SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2, arcade.color.RED, 60, width = 400, align = "center", anchor_x = "center", anchor_y = "center" ) if len(self.asteroids) == 0: arcade.draw_text( "YOU WIN!", SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2, arcade.color.GREEN, 60, width = 400, align = "center", anchor_x = "center", anchor_y = "center" ) def update(self, delta_time): """ Update each object in the game. :param delta_time: tells us how much time has actually elapsed """ self.check_keys() # TODO: Tell everything to advance or move forward one step in time self.ship.advance() self.ship.wrap() for asteroid in self.asteroids: asteroid.advance() asteroid.wrap() asteroid.rotate() if (not asteroid.alive): self.asteroids.remove(asteroid) for bullet in self.bullets: bullet.advance() bullet.wrap() bullet.is_alive() if (not bullet.alive): self.bullets.remove(bullet) if not self.ship.alive: self.ship.alive = False # TODO: Check for collisions self.check_collisions() def check_collisions(self): for bullet in self.bullets: for asteroid in self.asteroids: if bullet.alive and asteroid.alive: hit = bullet.radius + asteroid.radius if ( abs(bullet.center.x - asteroid.center.x) < hit and abs(bullet.center.y - asteroid.center.y) < hit ): bullet.alive = False asteroid.hit( self.asteroids, MEDIUM_ROCK_RADIUS, MEDIUM_ROCK_SPIN ) for asteroid in self.asteroids: if self.ship.alive and asteroid.alive: hit = self.ship.radius + asteroid.radius if ( abs(self.ship.center.x - asteroid.center.x) < hit and abs(self.ship.center.y - asteroid.center.y) < hit ): self.ship.alive = False asteroid.hit( self.asteroids, MEDIUM_ROCK_RADIUS, MEDIUM_ROCK_SPIN ) def check_keys(self): """ This function checks for keys that are being held down. You will need to put your own method calls in here. """ if arcade.key.LEFT in self.held_keys: self.ship.rotate_left() if arcade.key.RIGHT in self.held_keys: self.ship.rotate_right() if arcade.key.UP in self.held_keys: self.ship.forward() self.ship.img_on_key_press() if arcade.key.DOWN in self.held_keys: self.ship.reverse() # Machine gun mode... # Hold "F" for rapid fire if arcade.key.F in self.held_keys: rapid_fire_bullet = Bullet( BULLET_RADIUS, SCREEN_WIDTH, SCREEN_HEIGHT, self.ship.center.x, self.ship.center.y, self.ship.velocity.dx, self.ship.velocity.dy, self.ship.rotation, BULLET_SPEED, BULLET_LIFE ) self.bullets.append(rapid_fire_bullet) rapid_fire_bullet.rapid_fire() def on_key_press(self, key: int, modifiers: int): """ Puts the current key in the set of keys that are being held. You will need to add things here to handle firing the bullet. """ if self.ship.alive: self.held_keys.add(key) if key == arcade.key.SPACE: # TODO: Fire the bullet here! bullet = Bullet( BULLET_RADIUS, SCREEN_WIDTH, SCREEN_HEIGHT, self.ship.center.x, self.ship.center.y, self.ship.velocity.dx, self.ship.velocity.dy, self.ship.rotation, BULLET_SPEED, BULLET_LIFE ) self.bullets.append(bullet) bullet.fire() def on_key_release(self, key: int, modifiers: int): """ Removes the current key from the set of held keys. """ if key in self.held_keys: self.ship.img_on_key_release() self.held_keys.remove(key) # Creates the game and starts it going window = Game(SCREEN_WIDTH, SCREEN_HEIGHT) window.setupBgImage() arcade.run()
2ce6dc58476374b5ef0f10ac94eee3b47b598800
fbscott/BYU-I
/CS241 (Survey Obj Ort Prog Data Struct)/team_assignments/ta03.py
668
3.875
4
class RationalNumber(): def __init__(self): self.numerator = 0 self.denominator = 1 def display(self): print(f"{self.numerator}/{self.denominator}") def prompt(self): self.numerator = input("Enter the numerator: ") self.denominator = input("Enter the denominator: ") def display_decimal(self): decimal = float(self.numerator) / float(self.denominator) print(decimal) def main(): rationalNumber = RationalNumber() rationalNumber.display() rationalNumber.prompt() rationalNumber.display() rationalNumber.display_decimal() if __name__ == "__main__": main()
41b67a637f805c11cc6cc1fd1dc73b2e94f22cbe
fbscott/BYU-I
/CS241 (Survey Obj Ort Prog Data Struct)/skeet/bullet.py
723
3.75
4
import math from flying_object import FlyingObject class Bullet(FlyingObject): """Projectile. Fires from rifle. Destroys targets. Origin: (0,0)""" def __init__(self, radius, speed, color): """constructor""" super().__init__() # bullets start at (0,0) so there's no need to override the "center" # value as it's already set in the Point class by default self.radius = radius self.velocity.dy = speed self.velocity.dx = speed self.color = color def fire(self, angle): """Fire bullets""" self.velocity.dx = math.cos(math.radians(angle)) * self.velocity.dx self.velocity.dy = math.sin(math.radians(angle)) * self.velocity.dy
8ac515605efd5ab84dedb6ec93a78120d04264a2
alexnix/ngnt_matching
/notebooks/levSubstring.py
782
3.578125
4
import Levenshtein as lev import re def isLevSubstring(substring, string, precision): substring = substring.lower().strip() string = string.lower().strip() i = 0 j = len(substring) if j > len(string): j = len(string) while j <= len(string): if lev.distance(string[i:j], substring) <= len(substring)/precision: pattern = '([^a-zA-Z]|^)' + string[i:j] + '([^a-zA-Z]|$)' substringRegex = re.compile(pattern) if len(substringRegex.findall(string)) > 0: return True i += 1 j += 1 return False def isWordSubstring(substring, string): splitString = re.split(' |,|\.|-|\/', string.lower()) if substring.lower() in splitString: return True return False
05f7c6a29397b5c5f3412c99d2648db8822e2862
xinmingzh/CS1010X
/Mission 5/Mission 5/mission05-template-XINMING-PC.py
2,419
3.546875
4
# # CS1010S --- Programming Methodology # # Mission 5 # # Note that written answers are commented out to allow us to run your # code easily while grading your problem set. # Functions List: # connect_rigidly(curve1, curve2) # connect_ends(curve1, curve2) # gosperize(curve) # gosper_curve(level) # show_connected_gosper(level) # show_points_gosper(level, num_points, initial_curve) # gosperize_with_angle(theta)(curve) - returns one level of transformation given angle and curve (using complicated geometry) # gosper_curve_with_angle(level, angle_at_level) - repeats transpormation with different angle for each level of transformation # put_in_standard_position(curve) - forced start point at 0,0 and end point at 1,0 # your_gosperize_with_angle(theta) - improved version of gosperize_with_angle from hi_graph import * ########## # Task 1 # ########## def connect_rigidly(curve1, curve2): def connected_curve(t): if(t < 0.5): return curve1(2 * t) else: return curve2(2 * t - 1) return connected_curve #draw_connected_scaled(200, arc) #draw_connected_scaled(200, connect_rigidly(arc, unit_line)) def connect_ends(curve1, curve2): return connect_rigidly(curve1, translate(x_of(curve1(1)) - x_of(curve2(0)), y_of(curve1(1)) - y_of(curve2(0)))(curve2)) #draw_connected_scaled(200, connect_ends(arc, unit_line)) ########## # Task 2 # ########## def show_points_gosper(level, num_points, initial_curve): "your solution here!" squeezed_curve = squeeze_curve_to_rect(-0.5, -0.5, 1.5, 1.5)(repeated(gosperize, level)(initial_curve)) draw_points(num_points, squeezed_curve) # Test # show_points_gosper(7, 1000, arc) # show_points_gosper(5, 500, arc) ########## # Task 3 # ########## def your_gosper_curve_with_angle(level, angle_at_level): if level == 0: return unit_line else: return your_gosperize_with_angle(angle_at_level(level))(your_gosper_curve_with_angle(level-1, angle_at_level)) def your_gosperize_with_angle(theta): def inner_gosperize(curve_fn): return put_in_standard_position(connect_ends(rotate(theta)(curve_fn), rotate(-theta)(curve_fn))) return inner_gosperize # testing # draw_connected(200, your_gosper_curve_with_angle(10, lambda lvl: pi/(2+lvl))) # draw_connected(200, your_gosper_curve_with_angle(5 , lambda lvl: (pi/(2+lvl))/(pow(1.3, lvl))))
ecea0819ddc4eed242bf0705f35edacec7d5a90c
xinmingzh/CS1010X
/Mission 2/Side Quest 2.4/sidequest02.4-template.py
998
3.671875
4
# # CS1010X --- Programming Methodology # # Mission 2 - Side Quest 2 # # Note that written answers are commented out to allow us to run your # code easily while grading your problem set. import math ########## # Task 1 # ########## # Simplifed Order notations: # 4^n * n^2 # Ans: 4^n # n * 3^n # Ans: 3^n # 1000000000n^2 # Ans: n^2 # 2^n/1000000000 # Ans: 2^n # n^n + n^2 + 1 # Ans: n^n # 4^n + 2^n # Ans: 4^n # 1^n # Ans: 1 # n^2 # Ans: n^2 # Faster order of growth in each group: # i. 4^n # ii. 2^n # iii. n^n # iv. n^2 ########## # Task 2 # ########## # Time complexity: n # Space complexity: n ########## # Task 3 # ########## # Time complexity of bar: n # Time complexity of foo: n^2 # Space complexity of bar: n # Space complexity of foo: n^2 def improved_foo(n): # Fill in code here result = 0 for i in range(1, n+1): result += ((i + 1) * i)/2 print(result) return result # Improved time complexity: n # Improved space complexity: 3
185bc6d17e0c61c6cb112816d318e9aba34b7fd1
bkytchak/AutomateTheBoring
/Section 5/GuessTheNumber.py
486
4.09375
4
#This is a guess the number game. import random print("What is your name?") name = input() secretNum = random.randint(1, 5) print("I am thinking of a number 1 through 5") #Ask the player to guess 6 times for guessesTaken in range (1,5): print("Take a guess") guess = int(input()) if guess < secretNum: print ("Too Low") elif guess > secretNum: print ("Too High") else: print("Correct") print("You took " + str(guessesTaken) + " guesses. ")
4b29b5de3c75cc757f11cacad097747d02790a86
ndraper2/data-structures
/binheap.py
1,741
3.84375
4
# -*- coding: utf-8 -*- from __future__ import unicode_literals class BinHeap(object): def __init__(self, iterable=None): """Create a new binary min-heap. Insert values from an optional iterable. """ self.list = [] if iterable: for item in iterable: self.push(item) def push(self, value): """Push a new value onto the heap, maintaining the heap property.""" self.list.append(value) self._bubble_up() def _bubble_up(self): i = len(self.list) - 1 while (i - 1) // 2 >= 0: if self.list[i] < self.list[(i - 1) // 2]: self.list[i], self.list[(i - 1) // 2] = ( self.list[(i - 1) // 2], self.list[i]) i = (i - 1) // 2 def pop(self): """Pop the top value off the heap, maintaining the heap property.""" if len(self.list) == 1: return self.list.pop() try: return_val = self.list[0] except IndexError: raise IndexError('Heap is empty!') self.list[0] = self.list.pop() self._bubble_down() return return_val def _bubble_down(self): i = 0 while i * 2 + 1 <= len(self.list) - 1: child = self._min_child(i) if self.list[i] > self.list[child]: self.list[i], self.list[child] = ( self.list[child], self.list[i]) i = child def _min_child(self, index): if index * 2 + 2 > len(self.list) - 1: return index * 2 + 1 if self.list[2 * index + 1] > self.list[2 * index + 2]: return 2 * index + 2 else: return 2 * index + 1
f2dcd6ec19dfb7de95df56c80e7189f02fbf5e4c
Leeheejin1/python-test
/n10.py
189
3.578125
4
b=input('단어를 입력하세요') c=0 for i in range(0,len(b)): if b[i] == 'f': print(i,end=" ") c= 1 else: if i==len(b)-1 and c==0: print(-1)
7c1897412e54a953bde229a65a976e05e192923e
RichInCode/projectEulerProblems
/SpecialPythagoreanTriplet.py
1,142
3.75
4
import math def SpecialPythagoreanTriplet(): x = [i**2 for i in xrange(1,1001)] #print x for i in xrange(0,len(x)-2): a = x[i] #print 'a = '+str(a) for j in xrange(i+1,len(x)-1): b = x[j] # print 'b = '+str(b) aAndb = a + b for k in xrange(j+1,len(x)): c = x[k] # print 'c = '+str(c) # print ' ' if aAndb == c: # means we have a pythagorean triplet aAndbAndc = a + b + c #print str(a)+' '+str(b)+' = '+str(c) #print 'sum = '+str( math.sqrt(a)+math.sqrt(b)+math.sqrt(c)) if int(math.sqrt(a)+math.sqrt(b)+math.sqrt(c)) == 1000: # we found the special! print math.sqrt(a)*math.sqrt(b)*math.sqrt(c) return print 'cannot not find it...jerk' def main(): SpecialPythagoreanTriplet() # Standard boilerplate to call the main() function. if __name__ == '__main__': main()