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
ff9f7ec04facfd5b436431e18a1c4c6d46a3976c
as-iF-30/My-Python
/floodfill.py
684
3.578125
4
#leetcode def floodFill(image, sr, sc, newColor): color = image[sr][sc] def fun(image,sr,sc,newColor,color): if(image[sr][sc]==color and image[sr][sc]!=newColor): image[sr][sc] = newColor if(sr>=1): fun(image,sr-1,sc,newColor,color) if(sr+1<len(image)): fun(image,sr+1,sc,newColor,color) if(sc+1<len(image[0])): fun(image,sr,sc+1,newColor,color) if(sc>=1): fun(image,sr,sc-1,newColor,color) return image else: return image return(fun(image,sr,sc,newColor,color)) print(floodFill([[0,0,0],[0,1,1]],1,1,1))
50a88c887869ec5162d483e6b05727da552aa1d3
as-iF-30/My-Python
/stack.py
781
3.984375
4
class Stack: def __init__(self,size): self.size = size self.stack = [] def push(self,element): if self.size == 0: print('stack full') else: self.stack.append(element) self.size -= 1 def pop(self): if(self.stack == [] ): print('stack is empty') else: self.stack.pop() self.size += 1 def isEmpty(self): if self.stack == []: print('True') else: print('False') def peek(self): if self.size = []: print('stack is empty') else: print(self.stack[-1]) def sprint(self): print(self.stack) obj = Stack(10) # obj.push(5) # obj.sprint() obj.pop()
c944fa7fc1c05795d46f39ef4956636ba44f977a
as-iF-30/My-Python
/basic2.py
632
3.5
4
#max count element test = [1, 2, 3, 4, 2, 2, 3, 1, 4, 4, 4] print(max(set(test), key = test.count)) def x( ): return 1, 2, 3, 4 a, b, c, d = x() print(a, b, c, d) class MyName: Skill, Santa, Upskill = range(3) print(MyName.Skill) print(MyName.Upskill) print(MyName.Santa) #store n = 10 result = 1 < n < 20 print(result) result = 1 > n <= 9 print(result) #reverse l = [1,2,3,4,5] print(l[::-1]) #array rotation g = [] g.extend(l[2:]) g.extend(l[:2]) print(g) # counting 1 in bits in number def countBits(num): r = [0] for i in range(1, num +1): r.append(r[i>>1] + int(i&1)) return r print(countBits(5))
6d487cac6f5e42a683913e8c18899d5ff08f15f5
as-iF-30/My-Python
/basicfun.py
145
3.5
4
import itertools l = [1,3,2,6,1,2] c = 0 t = list(itertools.combinations(l,2)) print(t) l = [1,2,3] t = list(itertools.permutations(l)) print(t)
200aab6d017d69934a5698201cfdf12e48a78884
NecroReindeer/comp110-coding-task-1
/Client-Server Database/updatename.py
1,521
3.515625
4
#!/usr/bin/python """Update the name of a given player. The code in this file updates the name of a given player stored in the table of players in the highscores database. """ import cgi import cgitb import json import pymysql import processing def change_player_name(username, player_id): """Change the name of a given player. This function changes the name of the player corresponding to the given player id to the given name. """ connection, cursor = processing.connect_to_database() # Change the appropriate username cursor.execute("UPDATE players SET player_name=%s" "WHERE player_id=%s", (username, player_id)) connection.commit() if __name__ == '__main__': # Turn on debug mode cgitb.enable() # Print necessary headers print("Content-Type: text/html; charset=utf-8\n\n") form = cgi.FieldStorage() current_name = processing.get_player_name(form) new_name = processing.get_new_name(form) if current_name is not None and new_name is not None: player_id = processing.get_player_id(current_name) if player_id is not None and processing.username_is_unique(new_name): change_player_name(new_name, player_id) print(json.dumps(new_name)) else: # If player doesn't exist in database or new name isn't unique print(json.dumps(None)) else: # If original name/new name not provided or new name already taken print(json.dumps(None))
ef91a958487b036791414114005c6f37c2b5db04
karim-hb/practice-python-2
/convertToSecond.py
234
4.0625
4
def convert(time): hour = int(time[0:2]) minutes = int(time[3:5]) seconds = int(time[6:8]) print(hour*3600 + minutes*60 + seconds) time = input("please enter a full hour like 01:00:20 : ") convert(time)
4a96ee6aa058b1e4a82d47dfbc7ac154d37ad726
gourav071295/PythonCodes
/game.py
317
3.515625
4
print "\t\t\tWelcome to the game of numbers" name = raw_input("\tEnter your name :") print "\nYou entered " + name print "\nGreat ! Now Enter your password :" password = raw_input("\t Type your password here :") if password == "secret" : print "Access Granted" raw_input("\n Press Enter to exit")
54e250c7c93908773fd293b84468594d9706eb5d
incesubaris/Numerical
/secant.py
1,330
4.1875
4
import matplotlib.pyplot as plt import numpy as np ## Defining Function def f(x): return x**3 - 5*x - 8 ##Secant Method Algorithm def secant(x0, x1, error, xson, yson): x2 = x0 - (x0-x1) * f(x0) / (f(x0)-f(x1)) print('\n--- SECANT METHOD ---\n') iteration = 1 while abs(f(x2)) > error: if f(x0) == f(x1): print('ERROR : Divide by zero!') break x2 = x0 - (x1 - x0) * f(x0) / (f(x1) - f(x0)) xson.append(x2) yson.append(f(x2)) print('Iteration-%d, x2 = %0.8f and f(x2) = %0.6f' % (iteration, x2, abs(f(x2)))) x0 = x1 x1 = x2 iteration = iteration + 1 print('\nReach the Root Iteration-%d the root is: %0.8f' % (iteration, x2)) ## Input print("\nEnter the Initial Values and Tolerable Error\n") x0 = float(input('Enter Initial Value (x0): ')) x1 = float(input('Enter Initial Value (x1): ')) error = float(input('Tolerable Error: ')) ## Graph Elemnt Lists xson = [] yson = [] ## Implementing Secant Method secant(x0, x1, error, xson, yson) ##Graph of Bisection Method for Visualizing x = np.arange(x0, x1, 0.001) y = (f(x)) plt.title("Secant Method on f(x)") plt.plot(x, y, label="f(x)") plt.plot(xson, yson , '-o', label="Secant Iterations") plt.xlabel('x') plt.ylabel('y') plt.grid() plt.legend() plt.show()
2287864288827205f98be7e301deb75c78c8fa1f
bwbeckwi/Python
/dirtest.py
443
4
4
def replace_single_slash(slash): return slash.replace("\\","\\\\") current_dir = input("Enter current directory to copy from: ") target_dir = input("Enter target directory to copy to: ") if "\\\\" not in current_dir: current_dir = replace_single_slash(current_dir) if "\\\\" not in target_dir: target_dir = replace_single_slash(target_dir) print("Current directory: " + current_dir) print("Target directory: " + target_dir)
dfec1eedaca2e273de067d33b0331359e4c1c3da
bbearce/coding_tests
/Amazon/lot_problem.py
825
3.65625
4
lot = [[1,1,1,1,1,1,1], [1,1,0,1,1,1,1], [0,1,1,0,0,0,1], [0,0,1,1,1,1,9],] def bfs(grid, start): # queue=[start] width = len(lot[0]) height = len(lot) queue = [[start]] seen = set([start]) loop_limit = 3000 count=0 while queue and count < loop_limit: path = queue.pop(0) x, y = path[-1] if lot[y][x] == 9: return (path,len(path)) for x2, y2 in ((x+1,y),(x-1,y),(x,y+1),(x,y-1)): if 0 <= x2 < width and 0 <= y2 < height and lot[y][x] != 0 and (x2,y2) not in seen: queue.append(path + [(x2,y2)]) seen.add((x2,y2)) count=count+1 #print(count) #print(path) return ["we didn't get to finish",path] shortest_path = bfs(lot, (0,0)) print(shortest_path)
c35064703f7ed412ac6d8536c5356eaea1a66046
bbearce/coding_tests
/hacker_rank/python/easy/decorator_tutorial.py
4,309
3.96875
4
# [1] functions def foo(): return 1; # [2] scope a_string = 'this is a string' def foo(): print(locals()) foo() # {} print(globals()) # {..., 'a_string': 'this is a string'} # [3] varible resolution rules ### blah...it just says that local variables with the same name as global ones don't modify the global one. # [4] variable lifetime def foo(): x = 1; foo() # NameError: name 'x' is not defined # [5] function arguments and parameters def foo(x): print(locals()) foo(1) # {'x': 1} def foo(x, y=0): # remember if no default it's mandatory return x - y foo() # Traceback (most recent call last): # File "<stdin>", line 1, in <module> # TypeError: foo() missing 1 required positional argument: 'x' # [6] Nested Functions def outer(): x = 1 def inner(): print(x) inner() outer() # 1 # [7] Functions are first class objectsin python # all objects in Python inherit from a common baseclass issubclass(int, object) # True def foo(): pass foo.__class__ # <type 'function'> issubclass(foo.__class__, object) # True #..so what? def add(x,y): return x + y def sub(x,y): return x - y def apply(func, x, y): return func(x, y) apply(add, 2, 1) # 3 apply(sub, 2, 1) # 1 #.. closure lead in def outer(): def inner(): print('this is inner') return inner # the function not what it returns foo = outer() foo # <function outer.<locals>.inner at 0x10be011e0> foo() # 'this is inner' # [8] Closures def outer(): x = 1 def inner(): print(x) return inner # the function not what it returns foo = outer() foo.__closure__ # (<cell at 0x10bf00b88: int object at 0x10bc5bc00>,) # aside: cell objects are used to store the free variables of a closure # without closures x would have not existed as after the call to outer x is gone based on variable life time. # inner functions defined in non-global scope remember what their enclosing namespaces looked like at definition time. foo() # 1 # let's tweak it def outer(x): def inner(): print(x) return inner print1 = outer(1) print2 = outer(2) print1() # 1 print2() # 2 # [9] Decorators def outer(some_func): def inner(): print('before some_func') ret = some_func() # 1 return ret + 1 return inner def foo(): return 1 decorated = outer(foo) decorated() # we've added functionality to foo()! # what if we did this foo = outer(foo) foo() # before some_func # 2 # Let's write a more useful decorator class Coordinate(object): def __init__(self, x, y): self.x = x self.y = y def __repr__(self): return "Coord: " + str(self.__dict__) def add(a, b): return Coordinate(a.x + b.x, a.y + b.y) def sub(a, b): return Coordinate(a.x - b.x, a.y - b.y) one = Coordinate(100, 200) two = Coordinate(300, 200) add(one, two) # Coord: {'y': 400, 'x': 400} # add this instance three = Coordinate(-100, -100) def wrapper(func): def checker(a, b): # 1 if a.x < 0 or a.y < 0: a = Coordinate(a.x if a.x > 0 else 0, a.y if a.y > 0 else 0) if b.x < 0 or b.y < 0: b = Coordinate(b.x if b.x > 0 else 0, b.y if b.y > 0 else 0) ret = func(a, b) if ret.x < 0 or ret.y < 0: ret = Coordinate(ret.x if ret.x > 0 else 0, ret.y if ret.y > 0 else 0) return ret return checker add = wrapper(add) sub = wrapper(sub) sub(one, two) add(one, three) # [10] the @ symbol # so instead of wrapper(add)\wrapper(sub), use @wrapper @wrapper def add(a, b): return Coordinate(a.x + b.x, a.y + b.y) @wrapper def sub(a, b): return Coordinate(a.x - b.x, a.y - b.y) # [11] *args and **kwargs def one(*args): print(args) one() # () one(1,2,3) # (1, 2, 3) def two(x, y, *args): print(x, y, args) two('a','b','c') # Reminder # l = (1,2,3) # one(l[0], l[1], l[2]) # (1, 2, 3) # one(*l) # (1, 2, 3) def foo(**kwargs): print(kwargs) foo() foo(x=1, y=2) # [12] More generic decorators def logger(func): def inner(*args, **kwargs): print('Arguments were: {}, {}'.format(args,kwargs)) return func(*args, **kwargs) return inner @logger def foo1(x,y=1): return x * y @logger def foo2(): return 2 foo1(5,4) # Arguments were: (5, 4), {} # 20 foo2() # Arguments were: (), {} # 2
b874620b4a29bd65d3577370525adada91391cfa
ppicavez/PythonMLBootcampD00
/ex07/cost.py
1,210
4.03125
4
import numpy as np def cost_elem_(y, y_hat): """ Description: Calculates all the elements (1/2*M)*(y_pred - y)^2 of the cost function. Args: y: has to be an numpy.ndarray, a vector. y_hat: has to be an numpy.ndarray, a vector. Returns: J_elem: numpy.ndarray, a vector of dimension (number of the training examples,1). None if there is a dimension matching problem between X, Y or theta. Raises: This function should not raise any Exception. """ if y.shape != y_hat.shape: return None elems = np.zeros(y.shape) for i in range(y.shape[0]): elems[i] = (y_hat[i] - y[i]) ** 2 / (y.shape[0] * 2) return elems def cost_(y, y_hat): """ Description: Calculates the value of cost function. Args: y: has to be an numpy.ndarray, a vector. y_hat: has to be an numpy.ndarray, a vector. Returns: J_value : has to be a float. None if there is a dimension matching problem between X, Y or theta. Raises: This function should not raise any Exception. """ my_sum = 0 cost_elem = cost_elem_(y, y_hat) for j in cost_elem: my_sum = my_sum + j return float(my_sum)
4cfefb42c88250aa58e56356cd9489a9eca915f6
ppicavez/PythonMLBootcampD00
/ex09/plot.py
1,399
4.15625
4
import matplotlib.pyplot as plt import numpy as np def cost_(y, y_hat): """Computes the mean squared error of two non-empty numpy.ndarray, without any for loop. The two arrays must have the same dimensions. Args: y: has to be an numpy.ndarray, a vector. y_hat: has to be an numpy.ndarray, a vector. Returns: The mean squared error of the two vectors as a float. None if y or y_hat are empty numpy.ndarray. None if y and y_hat does not share the same dimensions. Raises: This function should not raise any Exceptions. """ if y.shape != y_hat.shape: return None return np.sum(np.power(y_hat - y, 2) / (2 * y.shape[0])) def plot_with_cost(x, y, theta): """Plot the data and prediction line from three non-empty numpy.ndarray. Args: x: has to be an numpy.ndarray, a vector of dimension m * 1. y: has to be an numpy.ndarray, a vector of dimension m * 1. theta: has to be an numpy.ndarray, a vector of dimension 2 * 1. Returns: Nothing. Raises: This function should not raise any Exception. """ y_hat = np.dot(np.c_[np.ones((len(x), 1)), x], theta) cost = cost_(y, y_hat) * 2 plt.plot(x, y, 'o') plt.plot(x, y_hat) i = 0 while i < len(x): plt.plot([x[i], x[i]], [y[i], y_hat[i]], 'r--') i = i + 1 plt.title("Cost : {}".format(cost)) plt.show()
7a278079bd6b7ebd4dbb79011fc0f3bb1a77dfe5
vinagrace-sadia/python-mini-projects
/Hangman/hangman.py
1,330
4.125
4
import time import random def main(): player = input('What\'s your name? ') print('Hello,', player + '.', 'Time to play Hangman!') time.sleep(1) print('Start guessing . . .') time.sleep(0.5) # Lists of possible words to guess words = [ 'bacon', 'grass', 'flowers', 'chair', 'fruit', 'morning', 'games', 'queen', 'secret', 'funny' ] word = words[random.randint(0, len(words) - 1)] turns = 10 guesses = '' while turns > 0: # The number of letters or characters to find char_to_find = 0 for char in word: if char in guesses: print(char) else: char_to_find += 1 print('_') # When all the characters of the word are found if char_to_find == 0: print('Congratulations! You won!') print('The word we\'re looking for is: ', word + '.') break guess = input('Guess the letter: ') guesses += guess if guess not in word: turns -= 1 print('Wrong!') if turns == 0: print('Game Over. You Loose.') else: print('You have', turns, 'turn(s) left. More guesses.') main()
9f994b26f9b4bbb2eb91b2f705bcb132438e0257
fredkeemhaus/zero_base_algorithm
/python_basic/section10.py
4,355
3.609375
4
# Section10 # 파이썬 예외처리의 이해 # 예외 종류 # 문법적으로 에러가 없지만, 코드 실행(런타임) 프로세스에서 발생하는 예외 처리도 중요하다 # linter : 코드 스타일, 문법 체크 # ① SyntaxError (문법 에러) : 잘못된 문법 # print('Test) # SyntaxError: unterminated string literal (detected at line 10) # if True >>> SyntaxError: expected ':' # pass # x => y # ② NameError : 참조 변수가 없을 때 생기는 에러 import time a = 10 b = 15 # print(c) # NameError: name 'c' is not defined # ③ ZeroDivisionError : 0 나누기 에러 # print(10 / 0) # ZeroDivisionError: division by zero # ④ IndexError : 인덱스 범위가 오버(넘쳤을)됐을 때 x = [10, 20, 30] print(x[0]) # print(x[3]) >>> IndexError: list index out of range # ⑤ KeyError (Dictionaries에 Key가 없을 때) dic = {'name': 'Kim', 'Age': 33, 'city': 'Seoul'} # print(dic['hobby']) >>> KeyError: 'hobby' print(dic.get('hobby')) # >>> None # ⑥ AttributeError : 모듈, 클래스에 있는 잘못된 속성 사용시에 예외 # import time print(time.time()) # print(time.month()) >>> AttributeError: module 'time' has no attribute 'month' # ⑦ valueError : 참조 값이 없을 때 발생 x = [1, 5, 9] # x.remove(10) >>> ValueError: list.remove(x): x not in list # x.index(10) # ⓼ FileNotFoundError 경로를 찾을 수 없을 때 # f = open('test.txt', 'r') >>> FileNotFoundError: [Errno 2] No such file or directory: 'test.txt' # ⑨ TypeError x = [1, 2] y = (3, 4, 5) z = 'test' # print(x + y) >>> TypeError: can only concatenate list (not "tuple") to list # print(x + z) # 따라서 형 변환이 필요하다 print(x + list(y)) # 항상 예외가 발새앟지 않을 것으로 가정하고 먼저 코딩을 해야 한다! # 그 후 런타임 예외 발생시 예외 처리 코딩하는 단계를 권장한다(EAFP 코딩 스타일) # 예외 처리 기본 # try : 에러가 발생할 가능성이 있는 코드 실행 # except : 에러명 1 # except : 에러명 2 # else : 에러가 발생하지 않았을 경우 실행 # finally : 항상 실행 # 예제 1 # name = ['kim', 'lee', 'park'] # try: # z = 'kim' # # z = 'shin' # x = name.index(z) # print('{} Found it! in name {}'.format(z, x + 1)) # except ValueError: # print('Not Found it! - Occured valueError! ') # else: # print('Ok! else!') # print() # 예제 2 # name = ['kim', 'lee', 'park'] # try: # z = 'kim' # # z = 'shin' # x = name.index(z) # print('{} Found it! in name'.format(z, x+1)) # except: # Error 의 종류를 적지 않으면 모든 Error가 해당 except로 들어온다 # print('Not Found it! - Occured valueError! ') # else: # print('Ok! else!') # 예제3 # name = ['kim', 'lee', 'park'] # try: # z = 'kim' # # z = 'shin' # x = name.index(z) # print('{} Found it! in name'.format(z, x+1)) # except: # Error 의 종류를 적지 않으면 모든 Error가 해당 except로 들어온다 # print('Not Found it! - Occured valueError! ') # else: # print('Ok! else!') # finally: # print('무조건 실행!') # 예제 4 # 예외처리는 하지 않지만, 무조건 수행되는 코딩 패턴 try: print('Try') finally: print('OK Finally') # 예제 5 # 에러를 계층적으로 잡기 # 가장 방대한 에러를 다루는 기본 except는 가장 마지막에 적어주는 것이 좋다 name = ['kim', 'lee', 'park'] try: z = 'kim' # z = 'shin' x = name.index(z) print('{} Found it! in name'.format(z, x+1)) except ValueError as v: print('Not Found it! - Occured value Error! ') print(v) except IndexError: print('Not Found it! - Occured index Error! ') except Exception: print('Not Found it! - Occured Error! ') else: print('Ok! else!') finally: print('무조건 실행!') print() # 예제 6 # 예외를 직접 방생 : raise: 일으키다 # raise 키워드로 예외 직접 발생 # try: # # a = 'Lee' # a = 'Kim' # if a == 'Kim': # print('Ok 허가') # else: # '김'이 아닌 경우네는 ValueError를 발생시키도록 프로그램을 구현해놓음 # raise ValueError # except ValueError: # print('문제 발생!') # except Exception as f: # print(f) # else: # 다 통과될 경우 # print('done')
790dd69517a00a4b80ec18d32211d78403e79c02
fredkeemhaus/zero_base_algorithm
/data_structure/14-7.py
4,517
3.546875
4
# 추가 예제 코드 # search_from_head # search_from_tail # insert_before class Node: def __init__(self, data, prev=None, next=None): self.prev = prev self.data = data self.next = next class NodeManageMent: def __init__(self, data): # 인스턴스 초기화시에는 아직 연결된 노드들이 없으므로, head 와 tail 모두 인스턴스 본인을 가리키도록 만든다 self.head = Node(data) self.tail = self.head # 맨 뒤 노드에 더블 링크드 리스트 추가 def insert(self, data): if self.head == None: self.head = Node(data) self.tail = self.head else: # 기존 head를 node 변수에 할당한다 node = self.head # 링크드 리스트의 맨끝까지 도달하기 위함 while node.next: node = node.next # 새로 추가할 data 객체를 new라는 변수에 할당 new = Node(data) # 기존 링크드 리스트의 맨 마지막에 new를 링크 1(바인딩) node.next = new # 새로 추가할 data 객체의 앞에도 기존의 마지막 노드를 링크 2(바인딩) new.prev = node # 기존 링크드 리스트의 꼬리를 새로 추가할 data 객체로 바인딩 self.tail = new def desc(self): # 어디서부터 내려올 지 기준을 잡는다 # 기준은 head node = self.head while node.next: print('node.data:', node.data) node = node.next def search_from_head(self, data): if self.head == None: return False # node 변수를 통해 방향 명시 node = self.head while node: if node.data == data: return node.data else: node = node.next return False def search_from_tail(self, data): if self.tail == None: return False # node 변수를 통해 방향 명시 node = self.tail while node: if node.data == data: return node.data else: node = node.prev return False # data >> 삽입할 데이터 # existing_data >>> 기존의 데이터 # existing_data 앞에 data를 삽입할 것이다 def insert_before(self, data, existing_data): # head가 없을 경우, 노드 객체를 생성한다 if self.head == None: self.head = Node(data) return True # head가 있을 때 else: # 맨 뒤에서부터 데이터를 검색한다 (앞 뒤 순서는 상관이 없다) node = self.tail while node.data != existing_data: # existing_data가 우리가 입력한 값과 맞을 때까지 앞으로 이동 node = node.prev # 계속 앞으로 이동했을 때 결과가 None이라면 >>> data가 없는 것 if node == None: return False # while node.data == before_data: 일 경우, (data를 정상적으로 찾은 경우) # new라는 변수에 우리가 인수로 넣은 data를 객체화하여 할당 # 양방향 링크드 리스트이므로 새로 추가할 변수를 기준으로 prev / / next 둘다 연결해줘야 함 # 1 과 2 사이에 1.5를 넣고 싶은 경우 new = Node(data) # 1.5 before_new = node.prev # before_new = 1 before_new.next = new # before_new(1).next = new(1.5) 기존에는 2 였겠죠? # new.prev는 기존의 new (node.prev)를 가리켜야 한다 # new(1.5).prev = before_new(1) 새로 만든 데이터 객체 앞에도 1을 추가해줘야 겠죠? new.prev = before_new # new(1.5).next = node(2, 뒤에서 부터 찾아왔으니 기준이 되는 데이터겠죠?) new.next = node # node(2).prev = new (기준이 되는 데이터의 앞에도 1.5를 넣어줘야 겠죠?) node.prev = new return True node1 = NodeManageMent(1) print('node1.__dict__:', node1.__dict__) print() print() for elem in range(2, 11): node1.insert(elem) node1.desc() print() print() print(node1.search_from_head(2)) print() print() # data가 2 인 노드 앞에 1.5를 가지는 노드를 삽입할꺼야 node1.insert_before(1.5, 2) node1.desc()
03f4a8ffa7da986f30e69cd0f737a306eaf53e9a
fredkeemhaus/zero_base_algorithm
/python_basic/section12-3.py
1,594
3.53125
4
# Section12-3 # 파이썬 데이터베이스 연동(SQLite) # 테이블 데이터 수정 및 삭제 # DB 사용을 위한 패키지 import import sqlite3 # DB 생성(파일) conn = sqlite3.connect( '/Users/leejunhee/FastCampus/python_basic/resource/database.db') # 해당 경로애 있는 db 파일 DB Brwoser for SQLite로 열기 # Cursor 연결 c = conn.cursor() # 데이터 수정 1 (기본적인 형태로 수정하기 SQL 문법) # c.execute("UPDATE users SET username = ? WHERE id = ?", ('niceman', 2)) # 데이터 수정 2 (딕셔너리 형태로 수정하기) # c.execute("UPDATE users SET username = :name WHERE id = :id", # {"name": 'goodman', "id": 3}) # # 데이터 수정 3 # c.execute("UPDATE users SET username = '%s' WHERE id = '%s'" % ('badboy', 4)) # 중간 데이터 확인 1 for user in c.execute("SELECT * FROM users"): print('user1:', user) # 데이터 삭제 1 c.execute("DELETE FROM users WHERE id = ?", (2,)) # 데이터 삭제 2 (딕셔너리 형태로 삭제하기) c.execute("DELETE FROM users WHERE id = :id", {"id": 3}) # 데이터 삭제 3 c.execute("DELETE FROM users WHERE id = '%s'" % (4)) # c.execute("DELETE FROM users WHERE id = '%s'" % 4) >>> 튜플이 하나일 경우에는 소괄호를 적지 않아도 된다 print() # 중간 데이터 확인 2 for user in c.execute("SELECT * FROM users"): print('user2:', user) # 테이블 전체 데이터 삭제 print("user db deleted :", conn.execute("DELETE FROM users").rowcount, " rows") # 커밋 : DB(SQLite)에 반영하기 conn.commit() # 접속 해제 conn.close()
6d7bdda5d1552860a15bc5a252c395c6ed017bc9
fredkeemhaus/zero_base_algorithm
/python_basic/quiz2_2.py
1,169
3.859375
4
class Median: def __init__(self): self.item = [] def get_item(self, item): self.item.append(item) def clear(self): self.item = [] def show_result(self): self.item.sort() if len(self.item) % 2 == 1: idx = 0 idx = int(len(self.item)/2) print(self.item[idx]) else: print((self.item[0] + self.item[-1])/2) median = Median() for x in range(10): # 0 - 9 까지 median.get_item(x) # 차례대로 x 의 값을 저장하는 메서드 median.show_result() # 중앙값을 출력하는 메서드. 입력받은 값이 짝수개이면, 중앙값 2개의 평균을 출력 median.clear() for x in [0.5, 6.2, -0.4, 9.6, 0.4]: median.get_item(x) median.show_result() # def sort_result(arr: list): # arr.sort() # print(arr) # def show_result(arr: list): # if len(arr) % 2 == 1: # idx = 0 # idx = int(len(arr)/2) # print('홀수') # print(arr[idx]) # else: # print('짝수') # print((arr[0] + arr[-1])/2) # show_result([1, 2, 3, 4, 5, 6, 7]) # sort_result([3, 2, 4, 1, 5, 6, 8, -1, -6])
bcc1ad6c291450e157344c7ef26558eb9a7fb5bd
fredkeemhaus/zero_base_algorithm
/algo/bubble_sort.py
583
4.03125
4
data = [5, 1, 3, 10, 9, -1] # 1,3,5,9,-1,10 # 1,3,5,-1,9,10 # 1,3,-1,5,9,10 # 1,-1,3,5,9,10 # -1,1,3,5,9,10 # swap이라는 true false를 반환하는 boolean 값을 어디에 놓을지 아는 것이 중요 def bubble_sort(data): for index in range(len(data) - 1): swap = False for index2 in range(len(data) - index - 1): if data[index2] > data[index2+1]: data[index2], data[index2+1] = data[index2+1], data[index2] swap = True if swap == False: break return data print(bubble_sort(data))
922e9b6ffdd514134b75b935e7b0a0e7564ed982
fredkeemhaus/zero_base_algorithm
/algo/HappyNumber.py
549
3.515625
4
# def solution(n): # if n == 1: # return True # if n >= 10: # pass # return n // 10, n % 10, n # Test code # print(solution(1)) # True # print(solution(19)) # True # print(solution(61)) # False # print(solution(201)) # False def solution(n): r = s = 0 while(n > 0): r = n % 10 s += r**2 n //= 10 return s n = int(input()) res = n while(res != 1 and res != 4): res = solution(res) if(res == 1): print("happy number") elif(res == 4): print("not a happy number")
2d81cff070d030949787d422246f96bfb826e76a
jhnguyen521/SpeedCrafter
/scripts/parse_recipes.py
4,365
3.625
4
import os import json from collections import namedtuple class RecipeParser: """ Parse individual recipe JSON files into a single JSON file so they can be easily retrieved by other scripts. For simplicity, only the first choice gets added for recipes that accept different items (e.g. substituting coal with charcoal or using different types of wood) TODOS: * Add smelting recipes if possible (uses 1.13+ ID format, so would need converting) ** Can alternatively just hardcode them in * Remove non-1.11 recipes if necessary """ def __init__(self, recipe_dir): self.recipe_dir = recipe_dir self.data_dict = dict() self.output_filename = 'recipes.json' def add_crafting_shaped(self, input_dict: dict): temp_dict = {} result_dict = input_dict['result'] output_dict = { 'count': 1, 'ingredients': {} } output_item = self.strip_prefix(result_dict['item']) for key, key_data in input_dict['key'].items(): if isinstance(key_data, dict): item = self.strip_prefix(key_data['item']) elif isinstance(key_data, list): item = self.strip_prefix(key_data[0]['item']) temp_dict[key] = { 'item': item, 'count': 0 } if 'data' in key_data: temp_dict[key]['data'] = key_data['data'] for row in input_dict['pattern']: for char in row: if char != ' ': temp_dict[char]['count'] += 1 if 'data' in result_dict: output_dict['data'] = result_dict['data'] if 'count' in result_dict: output_dict['count'] = result_dict['count'] for key_data in temp_dict.values(): output_dict['ingredients'][key_data['item']] = { 'count': key_data['count'] } if 'data' in key_data: output_dict['ingredients'][key_data['item']]['data'] = key_data['data'] self.data_dict[output_item] = output_dict def add_crafting_shapeless(self, input_dict: dict): result_dict = input_dict['result'] output_dict = { 'count': 1, 'ingredients': {} } output_item = self.strip_prefix(result_dict['item']) if 'data' in result_dict: output_dict['data'] = result_dict['data'] if 'count' in result_dict: output_dict['count'] = result_dict['count'] for ingredient_dict in input_dict['ingredients']: if isinstance(ingredient_dict, dict): item = self.strip_prefix(ingredient_dict['item']) elif isinstance(ingredient_dict, list): item = self.strip_prefix(ingredient_dict[0]['item']) if item in output_dict['ingredients']: output_dict['ingredients'][item]['count'] += 1 else: output_dict['ingredients'][item] = { 'count': 1 } if 'data' in ingredient_dict: output_dict['ingredients'][item]['data'] = ingredient_dict['data'] self.data_dict[output_item] = output_dict def parse_dir(self): for file in os.scandir(self.recipe_dir): if not file.name.endswith('.json'): continue with open(file) as openfile: file_data = json.load(openfile) if file_data['type'] == 'crafting_shaped': self.add_crafting_shaped(file_data) elif file_data['type'] == 'crafting_shapeless': self.add_crafting_shapeless(file_data) def create_output(self): """Output self.data_dict into Python file for retrieval""" with open(self.output_filename, 'w') as openfile: json.dump(self.data_dict, openfile, indent=2) @staticmethod def strip_prefix(input_str): """Strip minecraft: prefix from item names""" return input_str.split(':')[1] def main(): parser = RecipeParser('recipes/') parser.parse_dir() parser.create_output() if __name__ == '__main__': main()
e5eb3ba3404d6f56fead0ab54db6ddf3da04f154
ethanbar11/python_advanced_course1
/lecture_3/examples_2.py
314
3.6875
4
import sys print('woho') sys.stdout.write('Woho #2\n') raise Exception() x = sys.stdin.readline() sys.stderr.write(x) # Printing the string, and then accepting input from the user # and returns it. def my_input(string_to_print): pass # same as print, with enter in the end. def my_print(to_print): pass
88608003a64a994b7d78d09c29cf1174c35b34bf
DavideMaspero/python-alfabetizzazione-docenti
/esercizi/binomiale.py
322
3.671875
4
def fattoriale(numero): i = numero prodotto = 1 while i > 1: prodotto = prodotto * i i = i - 1 return prodotto print "inserire i valori n e k" n = input("n ") k = input("k ") binomiale = fattoriale(n) / (fattoriale(k) * fattoriale(n-k)) print "il coefficiente binomiale è ", binomiale
4eb7b896756ccdf0fa4b579606b8cb3834c868c8
DavideMaspero/python-alfabetizzazione-docenti
/esercizi/percorso2.py
689
3.703125
4
def radice(numero): radice = 1.0 while (radice * radice) <= numero: radice = radice + 1.0 for i in range(0, 10): radice = 0.5 * (radice + numero / radice) return radice haltFlag = 1 lunghezza = 0.0 print "inserire le coordinate delle citta':" print "un valore negativo termina l'inserimento" xOld = input("ascissa ") yOld = input("ordinata ") while (haltFlag > 0): x = input("ascissa ") y = input("ordinata ") if(x < 0.0 or y < 0.0): haltFlag = 0 else: deltaX = x - xOld deltaY = y - yOld lunghezza += (deltaX**2 + deltaY**2) lunghezza = radice(lunghezza) print "la lunghezza del percorso e' ", lunghezza
1537aee9542dbdba07a414fda91e7962fe6c94b9
DavideMaspero/python-alfabetizzazione-docenti
/esercizi/maxSemplice.py
129
3.703125
4
a = input('inserire a ') b = input('inserire b ') if (a > b): print 'a maggiore di b' if (b > a): print 'b maggiore a'
4c09b471e8659d835613639abe1c786ca9d48564
DavideMaspero/python-alfabetizzazione-docenti
/esercizi/functionsArgsKind.py
1,853
3.953125
4
# default argument values # definition: it is possible to assaign a default value to some parameters # (AFTER THE POSITIONALS ONES) def ask_ok(prompt, retries=4, complaint='Yes or no, please!'): while True: ok = raw_input(prompt) if ok in ('y', 'ye', 'yes'): return True if ok in ('n', 'no', 'nop', 'nope'): return False retries = retries - 1 if retries < 0: raise IOError('refusenik user') print complaint # default argument values # call: the values are still passed positionally, but the parameters with a # default can be omitted ask_ok('Do you really want to quit?') ask_ok('OK to overwrite the file?', 2) ask_ok('OK to overwrite the file?', 2, 'Come on, only yes or no!') # keyword arguments # definition: same as the default parameters def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'): print "-- This parrot wouldn't", action, print "if you put", voltage, "volts through it." print "-- Lovely plumage, the", type print "-- It's", state, "!" # keyword arguments # call: only positional parameters are mandatory, the keyword ones, that # must follow, can be called in any order or omitted parrot(1000) # 1 positional argument parrot(voltage=1000) # 1 keyword argument parrot(voltage=1000000, action='VOOOOOM') # 2 keyword arguments parrot(action='VOOOOOM', voltage=1000000) # 2 keyword arguments parrot('a million', 'bereft of life', 'jump') # 3 positional arguments parrot('a thousand', state='pushing up the daisies') # 1 positional, 1 keyword # wrong call methods: # parrot() # required argument missing # parrot(voltage=5.0, 'dead') # non-keyword argument after a keyword argument # parrot(110, voltage=220) # duplicate value for the same argument # parrot(actor='John Cleese') # unknown keyword argument
af90d3755b1021b142b67ad95e730b8f52ba38aa
DavideMaspero/python-alfabetizzazione-docenti
/esercizi/if.py
106
3.5625
4
a = input("Inserire un numero intero a:\n") if a < 0: a = -a print "Il valore assoluto di a e' ", a
ba7f1a767538ad2dfa7a758930a83c80c7085e85
DavideMaspero/python-alfabetizzazione-docenti
/esercizi/primalita.py
689
4.09375
4
numero = input("inserire un numero intero positivo: ") primo = False contatore = 1 divisore = contatore * 2 + 1 while divisore <= numero: print "contatore ", contatore print "divisore ", divisore print "resto ", numero%divisore print "divisione", numero/divisore print numero%divisore == 0 print "numero == divisore", numero == divisore print "numero mod divisore ", numero%divisore == 0 print "check ", numero - (numero/divisore)*divisore, "\n" if numero == divisore: primo = True contatore = contatore + 1 divisore = contatore * 2 + 1 if primo: print numero, "e' un numero primo" else: print numero, "non e' un numero primo"
2c602e7c8e6f9862eda00e14c9959c2cb9d59336
FelipeDreissig/Prog-em-Py---CursoEmVideo
/Mundo 1/Ex006 - operacoes.py
216
4.125
4
num = int(input('Digite um número inteiro: ')) dobro = num*2 triplo = num*3 raiz = num**(1/2) print('O dobro do número é {}, o triplo do número é {} e a raiz do número é {:.2f};'.format(dobro, triplo, raiz))
b67a6cf01324b2aadb667274281476d1d8144d85
FelipeDreissig/Prog-em-Py---CursoEmVideo
/Mundo 3/06 - Funções - p2/Ex102 - Fatorial.py
489
3.890625
4
def fatorial(n, show=False): """ Calcula o fatorial de um número. :param n: O número que será feito o fatorial. :param show: Apresenta o cálculo ou não :return:o valor do fatorial. """ c = 1 for l in range(n, 0, -1): c = c*l if show: if l == 1: print(f' {l}', end='') print(' = ', end='') else: print(f' {l} x', end='') return c print(fatorial(5, show=True))
6ace00e157783862c0e9c60984da537efa86cb7b
FelipeDreissig/Prog-em-Py---CursoEmVideo
/Mundo 1/Ex008.py
371
3.859375
4
### convertendo valores met = float(input('Quantos metros você quer converter?')) km = met*(1/1000) hec = met*(1/100) deca = met*(1/10) met = met dec = met*10 cent = met*100 mili = met*1000 print('Os {} metros são {} milímetros, {} centímetros,' '\n {} decímetros, {} decâmetros, {} hetômetros e {} kilometros '.format(met, mili, cent, dec, deca, hec, km))
a11e59a765703bff36652a66a332071d0ba9df35
FelipeDreissig/Prog-em-Py---CursoEmVideo
/Mundo 3/05 - Funções - p1/Ex098 - Contando.py
1,055
3.6875
4
from time import sleep def contador(i, f, r): if i < f: if r > 0: for k in range(i, f+1, r): sleep(0.25) print(k, end=' ') else: for k in range(i, f+1, -r): sleep(0.25) print(k, end=' ') if f < i: if r > 0: for k in range(i, f-1, -r): sleep(0.25) print(k, end=' ') else: for k in range(i, f-1, r): sleep(0.25) print(k, end=' ') print('\033[7;31;40mContado de 1 até 10 com razao 1.\033[m') contador(1, 10, 1) print('\nFim.') print('\033[7;33;40mContando de 2 até 0 com razão 2.\033[m') contador(10, 0, 2) print('\nFim.') print('\033[7;34;40mContagem personalizada.\033[m') ini = int(input('Digite o início:')) fim = int(input('Digite o fim:')) raza = int(input('Qual a razão:')) if raza == 0: print('Você quer uma razão inválida, dessa forma, a razão será o valor 1.') raza = 1 contador(ini, fim, raza) print('\nFim.')
1957807513aa138bec412a1545ff2d1f4b4ba4d8
FelipeDreissig/Prog-em-Py---CursoEmVideo
/Mundo 1/Ex013 - new wage.py
289
3.5625
4
# novo salário salario = float(input('A empresa está aumentando o salário dos funcionários, \n' 'em 15%, dessa forma, precisamos saber seu salário atual.\n')) salario_novo = salario*1.15 print('O seu novo salário será de {:.2f} reais.'.format(salario_novo))
c7eefb1f08a05a85e320466bcf62fce07522f2e1
FelipeDreissig/Prog-em-Py---CursoEmVideo
/Mundo 3/01 - Tuplas/Ex077 - Vogais.py
530
3.703125
4
#vogais em aplavras print('Digite palavras sem acento ou pontuação.') pala1 = str(input('Digite uma palavra aleatória:')).strip().lower() pala2 = str(input('Digite uma palavra aleatória:')).strip().lower() pala3 = str(input('Digite uma palavra aleatória:')).strip().lower() tupla = (pala1, pala2, pala3) vogais = ('a', 'e', 'i', 'o', 'u') for p in tupla: print(f'\nPara a palavra {p}, temos:') for i in range(1,len(p)): if p[i] in vogais: print(f'\033[7;31;40m{p[i]}, na {i+1}ª posição.\033[m')
3199745c9d39422425a740007f83d6e891f80031
FelipeDreissig/Prog-em-Py---CursoEmVideo
/Mundo 1/Ex018 - trigonometria.py
356
3.953125
4
#### lendo um angulo qualquer import math angu = float(input('Digite um angulo qualquer, em graus: \n')) ang = math.radians(angu) print('Os graus digitados correspondem a {:.2f} radianos'.format(ang)) sen = math.sin(ang) cos = math.cos(ang) tg = math.tan(ang) print('Os graus digitados são em seno {}, cosseno {} e tangente {}.'.format(sen, cos, tg))
080cadb27e20a0ed9463581c0db1ef4724d3d454
FelipeDreissig/Prog-em-Py---CursoEmVideo
/Mundo 2/Ex057 - Corretamente.py
186
4
4
### leitura correta sexo = str(input('Qual o seu sexo?[M/F]\n')).strip().lower() while sexo!='f' and sexo!='m': sexo = str(input('Qual o seu sexo?[M/F]\n')) print('Está correto!')
9e641d338cf72647db394ed29d950f99a4badaa1
FelipeDreissig/Prog-em-Py---CursoEmVideo
/Mundo 3/04 - Dicionários/Ex094 - people.py
1,515
3.703125
4
q = 0 pessoa = dict() people = list() somaidade = 0 mulheres = list() pessoaacima = list() while True: pessoa.clear() q = q + 1 pessoa['name'] = str(input(f'Digite o nome da {q}ª pessoa:')).strip().lower().capitalize() while True: pessoa['years old'] = int(input(f'Digite a idade da {q}ª pessoa:')) if type(pessoa['years old']) == int or float: break print('Por favor, apenas valores numérios.') while True: pessoa['gender'] = str(input(f'Digite o sexo da {q}ª pessoa:\n' f'F - Feminino\n' f'M - masculino\n')).strip().lower()[0] if pessoa['gender'] in 'fm': break print('Por favor, digite apenas M ou F') people.append(pessoa.copy()) while True: exit = str(input('Deseja continuar? [S/N]')).strip().lower()[0] if exit in 'sn': break print('Por favor, apenas S ou N.') if exit == 'n': break for k in people: somaidade = somaidade + k['years old'] if k['gender'] == 'f': mulheres.append(k.copy()) mediaidade = somaidade/q for y in people: if y['years old']>=mediaidade: pessoaacima.append(y.copy()) print(f'Foram cadastradas {q} pessoas.') print(f'os cadastrados foram:\n{people}') print(f'A média de idade é {mediaidade} anos.') print(f'As mulheres cadastradas foram:\n{mulheres}') print(f'As pessoas com idade igual ou maior da média são:\n{pessoaacima}')
8a40c2f37e572042d27f6dff7b663306ab579885
FelipeDreissig/Prog-em-Py---CursoEmVideo
/Mundo 2/Ex045 - JO KEN PO.py
1,718
3.734375
4
#### jo KEN PO import random from time import sleep aceite = int(input('Olá, eu sou seu computador. Gostaria de jogar jokenpô?\n1 - Sim\n2 - Não\n')) escolhapc = random.choice([1, 2, 3]) if aceite == 1: escolhahumano = int(input("""Escolha uma das opções: 1 - Pedra 2 - Papel 3 - Tesoura \n""")) if escolhahumano == 1 or escolhahumano == 2 or escolhahumano == 3: print('JO') sleep(1) print('ken') sleep(1) print('PO') sleep(1) if escolhapc == escolhahumano: print('Vocês empataram') elif escolhapc == 1: if escolhahumano == 2: print('O humano venceu. o PC escolheu {} e o humano escolheu {}.'.format('pedra', 'papel')) elif escolhahumano == 3: print('O PC venceu. O pc escolheu {} e o humano escolheu {}.'.format('pedra','tesoura')) elif escolhapc == 2: if escolhahumano == 1: print('O PC venceu. O PC escolheu {} e o humano escolheu {}.'.format('papel', 'pedra')) elif escolhahumano == 3: print('O humano venceu. O PC escolheu {} e o humano escolheu {}'.format('papel', 'tesoura')) elif escolhapc == 3: if escolhahumano == 1: print('O homem venceu. O PC escolheu {} e o homem escolheu {}.'.format('tesoura', 'pedra')) elif escolhahumano == 2: print('O PC venceu. O pc escolheu {} e o homem escolheu {}.'.format('tesoura', 'papel')) else: print('\33[30;41mOpção inválida, tente novamente.\33[m') elif aceite == 2: print('Fica para a próxima.') else: print('\33[30;41mOpção inválida, tente novamente.\33[m')
72279874ee3d72540d8b5be30d39ccc47e579227
FelipeDreissig/Prog-em-Py---CursoEmVideo
/Mundo 3/01 - Tuplas/Ex073 - brasileirão.py
618
3.515625
4
# tabela do brasileirão - inventarei uma tabela obs:brasileiro nao começou tupla = ('grêmio', 'flamengo', 'vasco', 'internacional', 'chapecoense', 'fluminense', 'avai', 'athletico', 'atletico', 'palmeiras', 'são paulo', 'corinthians', 'santos', 'botafogo', 'bahia', 'ceara', 'ponte preta', 'juventude','guarani', 'cruzeiro') order = sorted(tupla) posichape = tupla.index('chapecoense') print(f'Os 5 primeiros colocados são, {tupla[:5]}.\n') print(f'Os últimos 4 colocados são, {tupla[16:]}.\n') print(f'A tabela, em ordem alfabética é, {order}.\n') print(f'A chapecoense está na {posichape+1}ª posição.')
46376015c5a7c9d3b2b2da4b686e809db1591a3a
FelipeDreissig/Prog-em-Py---CursoEmVideo
/Mundo 1/Ex012 - new price.py
221
3.578125
4
# Calculadora de desconto preco = float(input('Qual o preço do produto?\n')) novo_preco = preco*0.95 print('Levando-se em consideração 5% de desconto\n' 'o novo preõ será de {:.2f} reais.'.format(novo_preco))
469ad8416a32b02a7cd806a95a2c2738bd0ba6be
FelipeDreissig/Prog-em-Py---CursoEmVideo
/Mundo 3/02 - Listas - p1/Ex078 - v2.py
357
3.515625
4
c = 0 l = [] for c in range(0, 5): n = int(input(f'Digite o {c + 1}º valor, sem repetir:')) while n in l: n = int(input(f'Digite o {c+1}º valor, sem repetir:')) l.append(n) n = ' ' print(f'O maior valor foi o {max(l)} na {l.index(max(l))+1}ª posição.\n' f'O menor valor foi o {min(l)} na {l.index(min(l))+1}ª posição.')
ec8aeb14483945f77dca0dd7b7133c2c16cff418
Karran8458/Values-Greater-Than-Second
/Values Greater Than Second.py
188
3.96875
4
def values_greater_than_second(arr): arr2 = [ ] if len(arr) < 3: return false for x in range(0,len(arr),1): if arr[x] > arr[1]: arr2.append(arr[x]) print(len(arr2)) return arr2
c00f2b8f1e2b7d5db631c18fe0005e35f5cb1b91
camera510PC7/codeiq_answer
/no_progress.py
338
3.578125
4
# -*- coding: utf-8 -*- value=input() if value%2==0: print"invalid" elif value==1: print "n" else: n='n' d='.' nf=0 for i in range(value): if i<1 or i>=value-1: nf=0 else: nf=1 print 'n'+d*(i-1)+n*nf+d*(value-i-2)+'n' print "\n"
13a5ee46b9ea315b1aea6400754c17391a6561aa
CodecoolMSC2016/python-game-statistics-3rd-si-oONinaOo
/part2/reports.py
4,413
3.71875
4
# What is the title of the most played game? def get_most_played(file_name): games_list = [] with open(file_name, "r") as my_file: for lines in my_file: games_list.append(lines.strip().split("\t")) # list of all by title and popularity most_played = [] for i in range(len(games_list)): appending = games_list[i][0], games_list[i][1] most_played.append(appending) top = max(float(game[1]) for game in most_played) # get the top number for game in most_played: if top == game[1]: result = game[1] return str(list(filter(lambda game: float(game[1]) == top, most_played))[0][0]) # pair the number with title # How many copies have been sold total? def sum_sold(file_name): games_list = [] with open(file_name, "r") as my_file: for lines in my_file: games_list.append(lines.strip().split("\t")) # summing total = 0.0 for game in range(len(games_list)): total += float(games_list[game][1]) return total # What is the average selling? def get_selling_avg(file_name): games_list = [] with open(file_name, "r") as my_file: for lines in my_file: games_list.append(lines.strip().split("\t")) # summ all sold total = 0.0 for game in range(len(games_list)): total += float(games_list[game][1]) # count games in list counter = 0 for i in games_list: counter += 1 return(total / counter) # AVG = total / piece # How many characters long is the longest title? def count_longest_title(file_name): games_list = [] with open(file_name, "r") as my_file: for lines in my_file: games_list.append(lines.strip().split("\t")) # see all titles and get the longest longest = 0 for game in range(len(games_list)): if len(games_list[game][0]) > len(games_list[longest][0]): longest = game return len(games_list[longest][0]) # What is the average of the release dates? def get_date_avg(file_name): games_list = [] with open(file_name, "r") as my_file: for lines in my_file: games_list.append(lines.strip().split("\t")) # summing the years total = 0.0 for game in range(len(games_list)): total += int(games_list[game][2]) # count games in list counter = 0 for i in games_list: counter += 1 return round((total / counter)) # AVG = total / piece -> rounded to int # What properties has a game? def get_game(file_name, title): games_list = [] with open(file_name, "r") as my_file: for lines in my_file: games_list.append(lines.strip().split("\t")) # getting everyting to a different list from the title properties = [] for game in range(len(games_list)): if title == games_list[game][0]: properties.append(games_list[game][0]) properties.append(float(games_list[game][1])) properties.append(int(games_list[game][2])) properties.append(games_list[game][3]) properties.append(games_list[game][4]) return properties raise ValueError # How many games are there grouped by genre? def count_grouped_by_genre(file_name): games_list = [] with open(file_name, "r") as my_file: for lines in my_file: games_list.append(lines.strip().split("\t")) # making the dictionary and fill it with genres and the amount of genres grouped = {} for game in range(len(games_list)): if games_list[game][3] not in grouped: grouped.update( {games_list[game][3]: grouped.get(games_list[game][3], 0) + 1}) else: grouped.update( {games_list[game][3]: grouped.get(games_list[game][3]) + 1}) return grouped # What is the date ordered list of the games? def get_date_ordered(file_name): games_list = [] with open(file_name, "r") as my_file: for lines in my_file: games_list.append(lines.strip().split("\t")) # sorting the list out games_list = sorted(games_list, key=lambda x: x[0], reverse=False) games_list = sorted(games_list, key=lambda x: int(x[2]), reverse=True) # addig just titles after sorting to a different list titles = [] for i in range(len(games_list)): titles.append(games_list[i][0]) return titles
a76e9c4a69e9993ed9b5e290ca9aa1b6077448cf
crhmhealey/2018_ClassDemos
/c block demos/factorial.py
1,200
3.953125
4
def factorial(n): if n is 0 or n is 1: return 1 return factorial(n-1)*n print(factorial(5)) print(factorial(4)) print(factorial(3)) print(factorial(2)) print(factorial(1)) print(factorial(0)) # evil fib but interesting for recursion def fib(n): if n is 0 or n is 1: return n return fib(n-1)+fib(n-2) print(fib(0)) print(fib(1)) print(fib(2)) print(fib(3)) print(fib(4)) print(fib(5)) print(fib(6)) print(fib(7)) print(fib(8)) # class exercises def countx(word): if len(word) < 1: return 0 if word[0] is "x": return 1+countx(word[1:]) return countx(word[1:]) print(countx("xx53xx")) print(countx("abcdefgzxjefjnsdzxmijderbgrnjkldms")) def crazy_eights(n): if n is 0: return 0 if n%10 == 8: if n%100 == 88: return 2 + crazy_eights(n//10) return 1 + crazy_eights(n//10) return crazy_eights(n//10) print(crazy_eights(8918228)) print(crazy_eights(88918)) print(crazy_eights(1234)) print(crazy_eights(89288438)) print(crazy_eights(888988980)) # from: https://introcs.cs.princeton.edu/python/23recursion/euclid.py.html def gcd(p, q): if q == 0: return p return gcd(q, p % q) print(gcd(4, 8)) print(gcd(3, 27)) print(gcd(100,250)) print(gcd(77, 1258))
9cce81610a18cf89b0469db1cf756e3447977f7f
crhmhealey/2018_ClassDemos
/Deck of Cards/card.py
684
3.9375
4
# card class represents a single card in a deck class Card: # card class keeps track of rank and suit for a single card def __init__(self, rank, suit): self.rank = rank self.suit = suit # print out the rank and suit in a nice way for the card # rank is stored as a number, but will display as a word here def __str__(self): rank = self.rank if self.rank == 11: rank = "Jack" elif self.rank == 12: rank = "Queen" elif self.rank == 13: rank = "King" elif self.rank == 1: rank = "Ace" return str(rank)+" of "+self.suit __repr__ = __str__ # remove these when card class is imported; for error checking only # card1 = Card(4, "Hearts") # print(card1)
80aee09b4007aeffde77cd8094eed571a2088ed7
crhmhealey/2018_ClassDemos
/g block demos/demo_game.py
1,103
4.03125
4
def lake(): choice = input('You are sitting on the lake, enjoying your picnic, when the water starts stirring and bubbling. Do you run [r] to the mountains for safety, or stand [s] your ground and prepare to fight? ') if check(choice,'r','s') == 'r': print('You decide to flee to the mountain for safety. ') mountain() else: stand() def stand(): print('That was stupid. How are you going to fend off a sea monster with some apple juice and a baguette? You die. ') again() def mountain(): print('You sit on top of the mountaintop and enjoy the sunshine and your delicious juice and baguette. What a lovely picnic! ') again() def start(): choice = input('You are going on a picnic. Do you want to picnic at a lake [l] or on a mountaintop [m]? ') if check(choice,'l','m') == 'l': lake() else: mountain() def again(): choice = input('Would you like to play again? [y] or [n] ') if check(choice,'y','n') == 'y': start() else: print('Goodbye.') def check(choice,a,b): while choice!=a and choice!=b: choice = input('Please choose '+a+' or '+b+': ') return choice start()
ec951fa06ca117a254e2dc83eba1483801ab4958
crhmhealey/2018_ClassDemos
/c block demos/lists_revisited.py
263
3.875
4
apples = [] for orange in range(5): apples.append(orange) i = [x for x in range(5)] i = [[1,2,3],[4,5,6],[7,8,9]] i[1][0] i = [0 for x in range(12)] print(i) j = [0]*12 print(j) i = [[0]*10 for x in range(10)] print(i) for x in range(len(i)): print(*i[x])
de007536891581b70c55725f97b33bc8df2d1ce6
crhmhealey/2018_ClassDemos
/g block demos/Bank.py
973
3.546875
4
import random class Account: def __init__(self, amount, pin): self.balance = amount self.pin = pin self.account = random.randint(10000000,99999999) self.isOpen = True def close(self, pin): if self.pin == pin: isOpen = False money = self.balance self.balance = 0 return money else: return pinerror() def deposit(self, amount, pin): if self.pin == pin: self.balance += amount else: return pinerror() def widthdrawal(self, amount, pin): if self.pin == pin: if self.balance > amount: self.balance -= amount return "success" else: return "insufficient funds" else: return pinerror() def pinerror(self): return "wrong pin. This is a short error, but it could be more complex, making sense to have it in a method." ba = Account(500, 1111) print(ba.withdrawal(200, 1123)) print(ba.withdrawal(200, 1111)) print(ba.withdrawal(500, 1111)) print(ba.deposit(500, 5432)) print(ba.deposit(500, 1111)) ba.close()
5a699fabe189e8453a4ba1b7a3db892255042771
crhmhealey/2018_ClassDemos
/c block demos/dog_class_demo.py
1,084
3.9375
4
class Dog: # constructor def __init__(self, energy, name): self.energy = energy self.hunger = 5 self.weight = 30 self.happiness = 5 self.name = name #------------------------------ # methods - functions #------------------------------ # allows the dog to eat some food def eat(self): status = "" if self.hunger > 0: self.weight += 1 self.hunger -= 1 self.energy += 1 self.happiness += 1 status = self.name+" just ate." if self.weight>40: self.happiness -= 3 status += "\nFYI, this dog is unhappy because it's getting fat." else: status = "Nope, not eating. Not hungry." return status # returns a string that conveys the general stats of the dog def stats(self): return "Name:"+self.name+"\nHunger:"+str(self.hunger)+"\nEnergy:"+str(self.energy)+"\nHappiness:"+str(self.happiness)+"\nWeight:"+str(self.weight) myDog = Dog(3, "Tim") mySecondDog = Dog(8, "Annabelle") print(myDog.stats()) print(myDog.eat()) print(myDog.eat()) print(myDog.eat()) print(myDog.eat()) print(myDog.eat()) print(myDog.eat()) print(myDog.stats())
bd1eee9df1c0a3dba011e36ed0c293e7a2225e1f
09Susinthan08/guvi
/digitcount.py
89
3.640625
4
num=int(input()) count=0 while num>0: num=int(num/10) count=count+1 print(count)
3fe5251b4cd5884f4adaba9a5cb954c92baeed0b
09Susinthan08/guvi
/extract_num.py
127
3.859375
4
s=input() li=[] for i in s: if(i.isnumeric()): li.append(i) else: continue for i in range(len(li)): print(li[i],end="")
675dec9cd96b305c2647a43b2143010340e7ec85
09Susinthan08/guvi
/sumarr.py
72
3.515625
4
num=int(raw_input()) su=0 for i in range(0,num+1): su = su+f print(su)
6cc5d5847c780a73f3b4e4c6534cd1036a3427b5
09Susinthan08/guvi
/word_split.py
248
3.546875
4
s=input() li=[] li1=[] for i in range(len(s)): if(i%2==0): li.append(s[i]) else: li1.append(s[i]) for i in range(len(li)): if(i==len(li)-1): print(li[i],end=" ") else: print(li[i],end="") for i in range(len(li1)): print(li1[i],end="")
57a9ed5a42dfc9c95e8abc9250bee77a20f7e274
protossw512/Deep-learning-projects
/MLP_Skeleton_d_minibatch.py
9,655
3.59375
4
""" Xinyao Wang """ from __future__ import division from __future__ import print_function import sys import cPickle import numpy as np # np.random.seed(321) # This is a class for a LinearTransform layer which takes an input class LinearTransform(object): def __init__(self, W): # DEFINE __init function self.W = W def forward(self, x): # DEFINE forward function self.linear_forward = np.dot(x, self.W) # This is a class for a ReLU layer max(x,0) class ReLU(object): def forward(self, x): # DEFINE forward function self.x = x vmax = np.vectorize(max) self.relu_forward = vmax(self.x, 0.0) self.relu_forward = np.c_[np.ones(x.shape[0]), self.relu_forward] def backward(self): def _grad_calculator(x): if x > 0: return 1 elif x == 0: return 0.5 else: return 0 vgrad = np.vectorize(_grad_calculator) return vgrad(self.x) # DEFINE backward function # ADD other operations in ReLU if needed # This is a class for a sigmoid layer followed by a cross entropy layer, the reason # this is put into a single layer is because it has a simple gradient form class SigmoidCrossEntropy(object): def forward(self, x, y): # DEFINE forward function self.sigmoid_forward = 1 / (1 + np.exp(-x)) self.cross_entropy = - (y * np.log(self.sigmoid_forward) + (1 - y) * np.log(1 - self.sigmoid_forward)) # This is a class for the Multilayer perceptron class MLP(object): def __init__(self, input_dims, hidden_units): # INSERT CODE for initializing the network self.input_dims = input_dims self.hidden_unites = hidden_units self.W1 = np.random.randn(self.input_dims + 1, hidden_units) * 0.1 self.W2 = np.random.randn(self.hidden_unites + 1, 1) * 0.1 self.W1Dt0 = 0 self.W2Dt0 = 0 def train( self, x_batch, y_batch, learning_rate, momentum, l2_penalty, ): def _gradients(): # Initialize delta_W2 = np.zeros(self.hidden_unites + 1) # Add 1 dimension for bias term delta_W1 = np.zeros((self.input_dims + 1, self.hidden_unites)) # Add 1 dimension for bias term W2minus = np.delete(self.W2, 0, 0) # For each sample, calculate gradient matrix of W1 and W2, and sum them together # We calculated gradient for each linear trasnformation layer and activation function for each node for i in range(len(y_batch)): dEdL2 = (S2.sigmoid_forward[i] - y_batch[i]) dL2dW2 = S1.relu_forward[i] dEdW2 = dEdL2 * dL2dW2 delta_W2 += dEdW2 # delta_W2 is the summation of gradient matrix for W2 dL2dS1 = W2minus dS1dL1 = ReLU_grad[i].reshape(self.hidden_unites, 1) # delta W1 is the summation of gradient matrix for W1 # Here we reused the result from dEdL2 delta_W1 += np.dot((dEdL2 * dL2dS1 * dS1dL1).reshape(self.hidden_unites, 1), x_batch[i].reshape(1, self.input_dims + 1)).T return delta_W1, delta_W2 # Go through forward function to get out put of this set of mini-batch samples L1 = LinearTransform(self.W1) L1.forward(x_batch) S1 = ReLU() S1.forward(L1.linear_forward) ReLU_grad = S1.backward() L2 = LinearTransform(self.W2) L2.forward(S1.relu_forward) S2 = SigmoidCrossEntropy() S2.forward(L2.linear_forward, y_batch) delta_W1, delta_W2 = _gradients() # Update W1 and W2 by applying momentum and l2 regularization W1Dt1 = momentum * self.W1Dt0 - learning_rate * (delta_W1 + l2_penalty * self.W1) self.W1 += W1Dt1 self.W1Dt0 = W1Dt1 W2Dt1 = momentum * self.W2Dt0 - learning_rate * (delta_W2.reshape(self.hidden_unites + 1,1) + l2_penalty * self.W2) self.W2 += W2Dt1 self.W2Dt0 = W2Dt1 # INSERT CODE for training the network def evaluate(self, x, y): L1 = LinearTransform(self.W1) L1.forward(x) S1 = ReLU() S1.forward(L1.linear_forward) L2 = LinearTransform(self.W2) L2.forward(S1.relu_forward) S2 = SigmoidCrossEntropy() S2.forward(L2.linear_forward, y) self.evaluate_loss = np.sum(S2.cross_entropy) def epoch_evaluate(self, train_x, train_y, test_x, test_y): def _binary(x): return 1 if x >= 0.5 else 0 def _accuracy(x, y): return 1 if x == y else 0 # Create functions that apply _binary() and _accuracy() function to numpy array vbinary = np.vectorize(_binary) vaccuracy = np.vectorize(_accuracy) # Calculate training loss and training accuracy L1 = LinearTransform(self.W1) L1.forward(train_x) S1 = ReLU() S1.forward(L1.linear_forward) L2 = LinearTransform(self.W2) L2.forward(S1.relu_forward) S2 = SigmoidCrossEntropy() S2.forward(L2.linear_forward, train_y) self.train_loss = np.sum(S2.cross_entropy) train_predict = vbinary(S2.sigmoid_forward) self.train_acc = sum(vaccuracy(train_predict, train_y)) / len(train_x) # Calculate testing loss and testing accuracy L1bar = LinearTransform(self.W1) L1bar.forward(test_x) S1bar = ReLU() S1bar.forward(L1bar.linear_forward) L2bar = LinearTransform(self.W2) L2bar.forward(S1bar.relu_forward) S2bar = SigmoidCrossEntropy() S2bar.forward(L2bar.linear_forward, test_y) self.test_loss = np.sum(S2bar.cross_entropy) test_predict = vbinary(S2bar.sigmoid_forward) self.test_acc = sum(vaccuracy(test_predict, test_y)) / len(test_x) # INSERT CODE for testing the network # ADD other operations and data entries in MLP if needed if __name__ == '__main__': data = cPickle.load(open('cifar_2class_py2.p', 'rb')) train_x = data['train_data'] train_y = data['train_labels'] test_x = data['test_data'] test_y = data['test_labels'] num_examples, input_dims = train_x.shape # INSERT YOUR CODE HERE num_testings, _ = test_x.shape # YOU CAN CHANGE num_epochs AND num_batches TO YOUR DESIRED VALUES train_x_mean = np.array(np.mean(train_x, axis = 0)) train_x_std = np.array(np.std(train_x, axis = 0)) norm_x_train = (train_x - train_x_mean) / train_x_std norm_x_test = (test_x - train_x_mean) / train_x_std train_x = np.c_[np.ones(num_examples), norm_x_train] test_x = np.c_[np.ones(num_testings), norm_x_test] num_epochs = 50 num_batches = 200 hidden_units = 40 batch_size = 64 learning_rate = 0.0001 momentum = 0.8 l2_penalty = 0.4 mlp = MLP(input_dims, hidden_units) train_loss_output = [] train_acc_output = [] test_loss_output = [] test_acc_output = [] for epoch in xrange(num_epochs): # Combine data and label together, then random shuffle the order combine = np.concatenate((train_y, train_x), axis = 1) np.random.shuffle(combine) train_y, train_x = np.hsplit(combine, [1]) loopindex = 0 total_loss = 0 for b in xrange(num_batches): # Devide shuffled data into small batches, each loop takes one batch if loopindex + batch_size >= num_examples - 1: loopindex = 0 x_batch = train_x[loopindex : loopindex + batch_size] y_batch = train_y[loopindex : loopindex + batch_size] loopindex += batch_size batch_index = np.random.randint(0, high = num_examples, size = batch_size) mlp.train(x_batch, y_batch, learning_rate, momentum, l2_penalty ) mlp.evaluate(x_batch, y_batch) # I talked to Dr. Li he said here we only need to calculate loss for batch. total_loss += mlp.evaluate_loss # MAKE SURE TO UPDATE total_loss print( '\r[Epoch {}, mb {}] Avg.Loss = {:.3f}'.format( epoch + 1, b + 1, (total_loss / b) / batch_size, ), end='', ) sys.stdout.flush() # INSERT YOUR CODE AFTER ALL MINI_BATCHES HERE # MAKE SURE TO COMPUTE train_loss, train_accuracy, test_loss, test_accuracy mlp.epoch_evaluate(train_x, train_y, test_x, test_y) train_loss = mlp.train_loss train_accuracy = mlp.train_acc[0] test_loss = mlp.test_loss test_accuracy = mlp.test_acc[0] print() print(' Train Loss: {:.3f} Train Acc.: {:.2f}%'.format( train_loss / num_examples, 100. * train_accuracy, )) print(' Test Loss: {:.3f} Test Acc.: {:.2f}%'.format( test_loss / num_testings, 100. * test_accuracy, )) train_loss_output.append(train_loss) train_acc_output.append(train_accuracy) test_loss_output.append(test_loss) test_acc_output.append(test_accuracy) # Write test accuracy to txt file so that I can use it to build figures report = open('test_acc.txt', 'w') for item in test_acc_output: report.write('%s \n' % item) report.close()
5d87a628b94927bab71349d685783154e819e912
praveengadiyaram369/LearningPython
/Basic_Python_Programming/Sequences_Tuples_Sets_Basics.py
686
4
4
####### Tuples ####### tuple_1 = ('A', 'AB', 'ABCD', 'EUIHVEAO') print(tuple_1) tuple_2 = tuple_1 print(tuple_2) ####### Empty Tuple ######### empty_tuple = tuple() empty_tuple = () #tuple_1[0] = 'WUI' #print(tuple_1) #tuple_2[0] = 'WUI' #print(tuple_2) ######### Set ###### subject_set = {'Maths', 'Physics', 'Chemistry', 'Biology', 'Sanskrit', 'Telugu', 'Maths'} course_set = {'IT', 'Data Science', 'Big Data', 'Maths'} print(subject_set) print(course_set) print(subject_set.intersection(course_set)) print(subject_set.union(course_set)) print(subject_set.difference(course_set)) print(course_set.difference(subject_set)) ###### Empty Set ##### empty_Set={} empty_Set=set()
83bcc918ad14403337b92d9a96fb5f9f846033f9
mdudapinho/Seguranca-de-Redes
/Trabalho 5/hash.py
640
3.53125
4
import hashlib hash_file = "hash_file.txt" this_file = "server.py" CREATENEWHASH = False USEHASH = False def md5Hash(text): result = hashlib.md5(text.encode("utf-8")).hexdigest() return result[:16] def checkApplicationIntegrity(): if(USEHASH): fh = open(hash_file).read() th = open(this_file).read() hash_ = md5Hash(th) print("fh: ", fh) print("th: ", hash_) if(fh == hash_): return True return False return True def createHashFile(): fh = open(this_file).read() hash_ = md5Hash(fh) f = open(hash_file,'w+') f.write(hash_) f.close()
6bfce60110b0b09bf5ba10f77b491e1d194c15a9
harishpichukala/tesseract-based-text-to-braille
/convert_num.py
563
3.75
4
def convert(text): temp=text out=[] for i in temp: if '1'==i: j="@a" out.append(j) elif '2'==i: j="@b" out.append(j) elif '3'==i: j="@c" out.append(j) elif '4'==i: j="@d" out.append(j) elif '5'==i: j="@e" out.append(j) elif '6'==i: j="@f" out.append(j) elif '7'==i: j="@g" out.append(j) elif '8'==i: j="@h" out.append(j) elif '9'==i: j="@i" out.append(j) elif '0'==i: j="@j" out.append(j) else: j=i out.append(j) #print i #print out out=''.join(out) return out
fa55764c1e7a96b334fde53f5ae89200a8160793
Planet-Nine/cs207project
/timeseries/timeseries.py
11,476
3.953125
4
import numpy as np from pytest import raises import pype import numbers def f(a): return a class LazyOperation(): """ An class that takes a function and an arbitrary number of positional arguments or keyword arguments as input Parameters ---------- function : an arbitrary function args : arbitrary positional arguments kwargs : arbitrary keyword arguments Returns ------- eval(LazyOperation): value a value representing the result of evaluating function with arguments args and kwargs __str__ / __repr__: when printing LazyOperation, the class name is printed followed by the function name, the positional arguments and the keyword arguments Examples -------- >>> a = TimeSeries([0,5,10], [1,2,3]) >>> b = TimeSeries([1,2,3], [5,8,9]) >>> thunk = check_length(a,b) >>> thunk.eval() True >>> assert isinstance( lazy_add(1,2), LazyOperation ) == True >>> thunk = lazy_mul( lazy_add(1,2), 4) >>> thunk.eval() 12 >>> print(thunk) LazyOperation( lazy_mul, args = (3, 4), kwargs = {} ) """ def __init__(self,function,*args,**kwargs): self.function = function self.args = args self.kwargs = kwargs def __str__(self): class_name = type(self).__name__ function_name = self.function.__name__ str_return = "{}( {}, args = {}, kwargs = {} )".format(class_name, function_name, self.args, self.kwargs) return str_return def eval(self): l = [] for arg in self.args: if isinstance(arg,LazyOperation): l += [arg.eval()] else: l += [arg] self.args = tuple(l) for kwarg in self.kwargs: if isinstance(self.kwargs[kwarg],LazyOperation): self.kwargs[kwarg] = self.kwargs[kwarg].eval() return self.function(*self.args,**self.kwargs) class TimeSeries(): """ An class that takes a sequence of integers or floats as input Parameters ---------- data : any finite numeric sequence time : any finite, monotonically increasing numeric sequence Returns ------- len(TimeSeries): int an integer representing the length of the time series Timeseries[position:int]: number returns the value of the TimeSeries at position Timeseries[position:int] = value:int/float set value of TimeSeries at position to be value __str__ / __repr__: when printing TimeSeries, if the total length of the Timeseries is greater than 10 the result shows the first ten elements and its total length, else it prints the whole Timeseries Examples -------- >>> a = TimeSeries([0,5,10], [1,2,3]) >>> threes = TimeSeries(range(100),range(100)) >>> len(a) 3 >>> a[10] 3 >>> a[10]=10 >>> a[10] 10 >>> print(a) [(0, 1), (5, 2), (10, 10)] >>> print(threes) [(0, 0), (1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6), (7, 7), (8, 8), (9, 9), ...], length=100 >>> [v for v in TimeSeries([0,1,2],[1,3,5])] [1, 3, 5] >>> a = TimeSeries([0,5,10], [1,2,3]) >>> b = TimeSeries([2.5,7.5], [100, -100]) >>> c = TimeSeries([0,5,10], [1,2,3]) >>> a == c True >>> a == b False >>> print(a.interpolate([1])) [(1, 1.2)] >>> print(a.interpolate(b.times())) [(2.5, 1.5), (7.5, 2.5)] >>> print(a.interpolate([-100,100])) [(-100, 1.0), (100, 3.0)] >>> b.mean() 0.0 >>> a.mean() 2.0 >>> a = TimeSeries([],[]) >>> a.mean() Traceback (most recent call last): ... ValueError: Cannot perform operation on empty list >>> a = TimeSeries([1,2],[1,'a']) >>> a.mean() Traceback (most recent call last): ... TypeError: cannot perform reduce with flexible type >>> a = TimeSeries([0,5,10], [1,2,3]) >>> lazy_series = a.lazy >>> assert isinstance(lazy_series.eval(),TimeSeries)==True >>> a = TimeSeries([0,5], [1,2,3]) Traceback (most recent call last): ... ValueError: Not the same length >>> a = TimeSeries([0,5,10], [1,2,3]) >>> a[1] Traceback (most recent call last): ... IndexError: Time does not exist >>> a[1] = 5 Traceback (most recent call last): ... IndexError: Time does not exist >>> assert (0 in a) == True >>> a [(0, 1), (5, 2), (10, 3)] >>> a = TimeSeries(range(11),range(1,12)) >>> a [(0, 1), (1, 2), (2, 3), (3, 4), (4, 5), (5, 6), (6, 7), (7, 8), (8, 9), (9, 10), ...], length=11 >>> a.values() [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] >>> a.items() [(0, 1), (1, 2), (2, 3), (3, 4), (4, 5), (5, 6), (6, 7), (7, 8), (8, 9), (9, 10), (10, 11)] >>> a.std() 3.1622776601683795 >>> b = TimeSeries([1,2],[3,4]) >>> a._check_times_helper(b) Traceback (most recent call last): ... ValueError: [(0, 1), (1, 2), (2, 3), (3, 4), (4, 5), (5, 6), (6, 7), (7, 8), (8, 9), (9, 10), ...], length=11 and [(1, 3), (2, 4)] must have the same times >>> a == b False >>> a == 'hi' False >>> 2+b [(1, 5), (2, 6)] >>> TimeSeries([1,2],[5,6])+b [(1, 8), (2, 10)] >>> 2*b [(1, 6), (2, 8)] >>> TimeSeries([1,2],[5,6])*b [(1, 15), (2, 24)] >>> 2-b [(1, -1), (2, -2)] >>> TimeSeries([1,2],[5,6])-b [(1, 2), (2, 2)] Notes ----- PRE: `data` is numeric """ def __init__(self,time,data): if len(time)!=len(data): raise ValueError("Not the same length") self.time=np.array(time) self.data=np.array(data) self.index=0 self.len=len(time) @pype.component def __len__(self): return len(self.data) def __getitem__(self, time): if time in self.time: return int(self.data[np.where(self.time==time)]) raise IndexError("Time does not exist") def __setitem__(self,time,value): if time not in self.time: raise IndexError("Time does not exist") self.data[np.where(self.time==time)]=value def __contains__(self, time): return time in self.time def __next__(self): try: word = self.data[self.index] except IndexError: raise StopIteration() self.index += 1 return word def __iter__(self): return self def itertimes(self): return iter(self.time) def itervalues(self): return iter(self.data) def iteritems(self): return iter(list(zip(self.time,self.data))) def __str__(self): if self.len>10: return '[{}, ...], length={}'.format(str(list(zip(self.time,self.data))[0:10])[1:-1], self.len) return '{}'.format(list(zip(self.time,self.data))) def __repr__(self): if self.len>10: return '[{}, ...], length={}'.format(str(list(zip(self.time,self.data))[0:10])[1:-1], self.len) return '{}'.format(list(zip(self.time,self.data))) def values(self): return list(self.data) def times(self): return list(self.time) def items(self): return list(zip(self.time,self.data)) def interpolate(self,newtime): newvalue=np.interp(newtime,self.time,self.data) return TimeSeries(newtime,newvalue) def to_json(self): # json_dict={} # json_dict['time']=self.time.tolist() # json_dict['data']=self.data.tolist() json_dict=(self.time.tolist(),self.data.tolist()) return json_dict @property def lazy(self): lazy_fun = LazyOperation(f,self) return lazy_fun @pype.component def mean(self): if self.len == 0: raise ValueError("Cannot perform operation on empty list") return np.mean(self.data) @pype.component def std(self): if self.len == 0: raise ValueError("Cannot perform operation on empty list") return np.std(self.data) def median(self): if self.len == 0: raise ValueError("Cannot perform operation on empty list") return np.median(self.data) @pype.component def _check_times_helper(self,rhs): if not self.times() == rhs.times(): raise ValueError(str(self)+' and '+str(rhs)+' must have the same times') def __eq__(self, other): if isinstance(other, TimeSeries): return ((len(self) == len(other)) and all(self.time==other.time) and all(self.data==other.data )) else: return NotImplemented @pype.component def __add__(self, rhs): try: if isinstance(rhs, numbers.Real): return TimeSeries(self.time,self.data+rhs) else: self._check_times_helper(rhs) pairs = zip(self, rhs) return TimeSeries(self.time,self.data+rhs.data) except TypeError: raise NotImplemented def __radd__(self, other): # other + self delegates to __add__ return self + other @pype.component def __mul__(self, rhs): try: if isinstance(rhs, numbers.Real): return TimeSeries(self.time,self.data*rhs) else: # self._check_times_helper(rhs) pairs = zip(self, rhs) return TimeSeries(self.time,self.data*rhs.data) except TypeError: raise NotImplemented @pype.component def __rmul__(self, other): # other + self delegates to __mul__ return self*other @pype.component def __truediv__(self, rhs): try: if isinstance(rhs, numbers.Real): return TimeSeries(self.time,self.data/rhs) else: # self._check_times_helper(rhs) pairs = zip(self, rhs) return TimeSeries(self.time,self.data/rhs.data) except TypeError: raise NotImplemented @pype.component def __sub__(self, rhs): try: if isinstance(rhs, numbers.Real): return TimeSeries(self.time,self.data-rhs) else: # self._check_times_helper(rhs) pairs = zip(self, rhs) return TimeSeries(self.time,self.data-rhs.data) except TypeError: raise NotImplemented @pype.component def __rsub__(self, other): # other + self delegates to __sub__ return -self + other @pype.component def __pos__(self): if self.len!=0: return TimeSeries(self.time,self.data) else: raise ValueError @pype.component def __neg__(self): if self.len!=0: return TimeSeries(self.time, -1*self.data) else: raise ValueError def __abs__(self): if self.len!=0: return np.sqrt(np.sum(self.data*self.data)) else: raise ValueError def __bool__(self): if self.len!=0: return bool(abs(self)) else: raise ValueError def lazy(f): def inner(*args,**kwargs): inner.__name__ = f.__name__ lazy_fun = LazyOperation(f,*args,**kwargs) return lazy_fun return inner @lazy def check_length(a,b): return len(a)==len(b) @lazy def lazy_add(a,b): return a+b @lazy def lazy_mul(a,b): return a*b
6b550237b3a3516a689a79adf7b34825314dd2d6
mattthewong/cs_5_green
/lengthToATG.py
619
3.578125
4
import random def lengthToATG(): counter = 0 newcontainer = "" while counter <=3 or newcontainer[counter-4:counter-1] != "ATG": newcontainer += random.choice(['A','T','C','G']) counter = counter + 1 return counter def meanToATG(trials): newcounter = 0 newcontainer = "" while newcounter <= 3 or newcontainer[newcounter-4:newcounter-1] !='AAA': newcontainer += random.choice(['A','T','C','G']) newcounter = newcounter +1 return newcounter def meanToAAA(trials): newcounter = 0 for x in range(trials): newcounter = lengthToAAA() + newcounter
7af649c957548e185780ad58824ea7ab16eb198b
mattthewong/cs_5_green
/count.py
171
3.890625
4
def count(letter, string): counter = 0 for symbol in string: if letter == symbol: counter = counter+1 return counter
fe74281880b4219344591d6f7e8b1dc974969565
mattthewong/cs_5_green
/hw10/Ant.py
2,671
4.6875
5
from Vector import * import random import turtle class Ant: def __init__(self, position): '''This is the "constructor" for the class. The user specifies a position of the ant which is a Vector. The ant keeps that vector as its position. In addition, the ant chooses a random color for its footstep. A color is a tuple with three numbers between 0 and 1, representing the amount of red, green, and blue in the color mixture. For example, the tuple (0.5, 0.8, 0.1) is a combination of some red, quite a bit of green, and just a touch of blue. You can get a random number between 0 and 1 using the random package using random.uniform(0, 1).''' self.position = position self.color = (random.uniform(0,1), random.uniform(0,1), random.uniform(0,1)) def __repr__(self): '''This function returns a string which represents the ant. This string can simply display the ant's x- and y- coordinates.''' return str(self.position) def moveTowards(self, otherAnt): '''This function takes as input a reference to another ant. Then, our ant "moves" towards the other ant by a step of length 1. That is, we first compute a vector from ourself (self) to the other ant, normalize it to have length 1, and then update our ant's position by adding this vector to its current position. This method doesn't display anything, it simply updates the ant's own position vector!''' distancetomove = otherAnt.position - self.position distancetomove.normalize() self.position = self.position + distancetomove def footstep(self): '''This function draws a dot in the ant's chosen color (remember, we established that color in the constructor when the ant was first "manufactured") at the ant's current location. To do this, you'll need to pickup the turtle (using turtle.penup()), move the turtle to the ant's current location (using turtle.setpos(x, y) where x and y are the desired x- and y- coordinates - which you'll need to extract from the vector that stores the ant's position), put the pen down so that the turtle can draw (using turtle.pendown()), set the turtle's drawing color (using turtle.color(c) where c represents the 3-tuple that contain's this ant's chosen drawing color), and draw a dot for the footstep (using turtle.dot()).''' turtle.penup() turtle.setpos(self.position.x,self.position.y) turtle.pendown() turtle.color(self.color) turtle.dot()
88a542ae63daee452e566099abf61e367326d0ea
mattthewong/cs_5_green
/hw1bonus.py
296
3.90625
4
def palindrome(input): if input == input[::-1]: return True else: return False def fancyPal(string): lowerstring = string.lower() for value in lowerstring: if value == ',' or value == ' ' or value == '.':
0f6ba572e53dc34067241b53aa7d65c72f4e1462
Mauricio1xtra/python
/basic_revisions2.py
2,903
4.125
4
""" Formatando valores com modificadores - AUlA 5 :s - Texto (strings) :d - Inteiro (int) :f - Números de ponto flutuante (float) :.(NÚMERO)f - Quantidade de casas decimais (float) :CARACTERE) (> ou < ou ^) (QUANTIDADE) (TIPO - s, d ou f) > - Esquerda < - Direita ^ - Centro """ """ num_1 = 1 print(f"{num_1:0>10}") num_2 = 2 print(f"{num_2:0^10}") print(f"{num_2:0>10.2f}") nome = "Mauricio" sobrenome = "Ferreira" print(f'{nome:#^50}') #Add cerquinha print((50-len(nome)) / 2) #subtrai 50 - qtde de caracteres da função nome e divide por 2 #Na primeira situação estamos passando o indice do sobrenome(1) nome_formatado = "{1:+^50}".format(nome, sobrenome) #{:*^50}".format(nome) ou "{n:0>20}".format(n=nome) print(nome_formatado) """ #MINIPULANDO STRINGS - AULA 6 """ *String indices *Fatiamento de strings [inicio:fim:passo] *Funções Built-in len, abs, type, print, etc... Essas funções podem ser usadas diretamente em cada tipo. """ #Positivos [012345678] texto = "Python s2" #Negativos -[987654321] nova_string = texto[2:6] #[0::2] pega o caractere do inicio ao fim, pulando 2 casas print(nova_string) """ While em Python = AULA 7 Utilizando para realizar ações enquanto uma condição for verdadeira requisitos: Entender condições e operadores """ """ x = 0 while x < 10: if x == 3: x = x + 1 continue #ou break para o loop quando a condição é verdadeira print(x) x = x + 1 print("Acabou!") """ """ x = 0 while x < 10: y = 0 print(f"({x}, { while y < 5: print(f"({x},{y})") y += 1 x += 1 # x = x + 1 print("Acabou!") """ #Calculadora while True: print() num_1 = input("Digite um número: ") num_2 = input("Digite outro número: ") operador = input("Digite um operador: ") sair = input("Deseja sair? [s]im ou [n]ão: ") if sair == "s": break if not num_1.isnumeric() or not num_2.isnumeric(): print("Você precisa digitar um número.") continue num_1 = int(num_1) num_2 = int(num_2) # + - / * if operador == "+": print(num_1 + num_2) elif operador == "-": print(num_1 - num_2) elif operador == "/": print(num_1 / num_2) elif operador == "*": print(num_1 * num_2) else: print("Operador invalido!") """WHILE / ELSE - AULA 8 Contadores Acumuladores """ #!CONTADOR contador = 0 #pode começar a partir de qualquer número, ex: contador = 50 # while contador <= 100: # print(contador) # contador += 1 #!ACUMULADOR contador_1 = 1 acumulador = 1 while contador_1 <= 10: print(contador_1, acumulador) if contador_1 > 5: break #TODO: quando colocamos o BREAK o ELSE não será executado, ele sai do bloco de código acumulador = acumulador + contador_1 contador_1 += 1 else: print("Cheguei no else.") print("Isso será executado!")
08f92f268f365273ba0eeecfa7ea637599cd126e
FigNewtons/hackerrank
/warmup/CountingValleys.py
447
3.875
4
def counting_valleys(s: str) -> int: valley_count = 0 level = 0 in_valley = False for ch in s: if ch == 'D': if level == 0: in_valley = True level -= 1 else: level += 1 if level == 0 and in_valley: in_valley = False valley_count += 1 return valley_count if __name__ == '__main__': print(counting_valleys('UDDDUDUU'))
f74423128c8fcacbf42426d5a6d8061ad747d706
lyubomirShoylev/pythonBook
/Chapter04/ex08_herosInventory2.py
1,292
4.1875
4
# Hero's Inventory 2.0 # Demonstrates tuples # create a tuple with some items and display with a for loop inventory = ("sword", "armor", "shield", "healing potion") print("\nYour items:") for item in inventory: print(item) input("\nPress the enter key to exit.") # get the length of a tuple print(f"You have {len(inventory)} items in your possesion.") input("\nPress the enter key to exit.") # test for membership with in if "healing potion" in inventory: print("You will live another day.") input("\nPress the enter key to exit.") # display one item through an index index = int(input("\nEnter the index number for an item in inventory: ")) print(f"At index {index} is {inventory[index]}") # display a slice start = int(input("\nEnter the index number to begin a slice: ")) finish = int(input("\nEnter the index number to end a slice: ")) print(f"inventory[{start}:{finish}] is", end=" ") print(inventory[start:finish]) input("\nPress the enter key to exit.") # concatenate two tuples chest = ("gold", "gems") print("You find a chest. It contains: ") print(chest) print("You add the contents of the chest to your inventory.") inventory += chest print("Your inventory is now:") print(inventory) input("\nPress the enter key to exit.")
9eaf4fbd375f2f10554b93b64cddd7f6f0e8d334
lyubomirShoylev/pythonBook
/Chapter06/ch02_guessMyNumberModified.py
1,848
4.21875
4
# Guess My Number # **MODIFIED** # # The computer picks a random number between 1 and 100 # The player tries to guess it and the computer lets # the player know if the guess is too high, too low # or right on the money. In this version of the game # the player has limited amount of turns. # # MODIFICATION: # Reusing the function askNumber from Chapter06 in order to exercise # function usage and reusability import random # ask the user for a number in a certain range def askNumber(question, low, high, step = 1): """ askNumber(question, low, high[, step])\n Ask for a number within a range. Optional step is available, and the default value is 1. """ counter = 0 response = None while response not in range(low, high, step): counter += 1 response = int(input(question)) if response > theNumber: print("Lower...") elif response < theNumber: print("Higher...") return response, counter # main print("\tWelcome to 'Guess My Number'!") print("\nI'm thinking of a number between 1 and 100.") print("Try to guess it in under fifteen attempts if possible.\n") # set the inital values theNumber = random.randint(1,100) # guess = int(input("Take a guess: ")) guess = None tries = 0 # guessing loop while guess != theNumber and tries < 15: # if guess > theNumber: # print("Lower...") # else: # print("Higher...") guess, counter = askNumber("Take a guess: ", 1, 101) # guess = int(input("Take a guess: ")) tries += counter if guess == theNumber: print(f"\nYou guessed it! The number was {theNumber}") print(f"And it only took you {tries} tries!\n") else: print(f"\nYou failed! You know there is an actual strategy?") print("Anyway, better luck next time!") input("\n\nPress the enter key to exit.")
cd8e55a1d45d6c3375e5747fb57f4d83ff92f103
lyubomirShoylev/pythonBook
/Chapter09/ch02_war/war.py
4,906
3.609375
4
# War Game # # A one-card version of the game war, based on modules 'cards' and 'games' as in # example code from the book. import games, cards class WarCard(cards.Card): """A War Card.""" ACE_VALUE = 14 @property def value(self): if self.isFaceUp: v = self.RANKS.index(self.rank) if v == 0: v = self.ACE_VALUE else: v = None return v class WarDeck(cards.Deck): """A War Deck.""" def populate(self): for suit in WarCard.SUITS: for rank in WarCard.RANKS: self.cards.append(WarCard(rank, suit)) class WarStack(cards.Hand): """A War Player's Hand.""" def __init__(self, name): super(WarStack, self).__init__() self.name = name def __str__(self): rep = self.name + ": " + str(len(self.cards)) + " cards in stack" return rep # same as pop, but removes the first card def pipCard(self): c = self.cards[0] self.cards.remove(self.cards[0]) print(c) return c def addWinner(self, cardsWon): for card in cardsWon: self.add(card) class WarPlayer(WarStack): """A War Player.""" def isPlaying(self): return self.cards def lose(self): print(self.name, "loses.") def win(self): print(self.name, "wins.") # to add: # game condition - when a player has three or les cards in hand, to be able # to choose either card in play. it may be a little difficult to implement class WarGame(object): """A War Game.""" def __init__(self, names): self.players = [] for name in names: player = WarPlayer(name) self.players.append(player) self.deck = WarDeck() self.deck.populate() self.deck.shuffle() @property def stillPlaying(self): sp = [] for player in self.players: if player.isPlaying(): sp.append(player) return (len(sp) == 1) def noWinnerRound(self, topCards): # if more than one player has a winning card, return all cards to their origin for i in range(len(self.players)): self.players[i].add(topCards[i]) def clearPlayers(self): # at the end of a round, remove players from the game who have no cards left in their hand for player in self.players: if not player.isPlaying(): print(f"{player.name} has no cards left! Removing them from the current game.") self.players.remove(player) def endGame(self): print(f"{self.players[0]} has won this game of War. Congratulations!\ You are the champion of the people!") def play(self): # deal the players some cards self.deck.deal(self.players, perHand=54//len(self.players)) for player in self.players: print(player) print("Let the game begin!") # game round counter self.round = 0 while self.stillPlaying: self.round += 1 print(f"Round {self.round}:") self.topCards = [] for player in self.players: print(player.cards[0]) self.topCards.append(player.pipCard()) self.topCardNum = 0 self.topCardWinner = True for cardNum in range(len(self.topCards[1:])): if self.topCards[self.topCardNum].value < self.topCards[cardNum+1].value: self.topCardNum = cardNum + 1 self.topCardWinner = True elif self.topCards[self.topCardNum].value == self.topCards[cardNum+1].value: self.topCardWinner = False if not self.topCardWinner: print("No winner this round! Everyone recieves back their cards.") self.noWinnerRound(self.topCards) else: print(f"{self.players[self.topCardNum].name} wins this round.") self.players[self.topCardNum].addWinner(self.topCards) self.clearPlayers() if len(self.players) == 1: self.endGame() break input("Press enter for next round...\n") def main(): print("\t\tWelcome to War, the simple one-card many-player game!\n") names = [] number = games.askNumber("How many players? (1 - 7):", low=1, high=8) for i in range(number): name = input("Enter player name: ").capitalize() names.append(name) print() game = WarGame(names) again = None while again != "n": game.play() again = games.askYesNo("\nDo you want to play again?: ") main() input("\n\nPress the enter key to exit.")
e550fd073b917dafc66ff71ee3455053617cd920
lyubomirShoylev/pythonBook
/Chapter04/ex05_noVowels.py
445
4.53125
5
# No Vowels # Demonstrates creating new strings with a for loop message = input("Enter a message: ") newMessage = "" VOWELS = "aeiou" print() for letter in message: # letter.lower() assures it could be from VOWELS if letter.lower() not in VOWELS: newMessage += letter print("A new string has been created:", newMessage) print("\n Your message without vowels is:", newMessage) input("\n\nPress the enter key to exit.")
5f7c7c5018f3db3c93c1cb1dcc4fe731c06cee2d
ARM-software/ML-examples
/yeah-world/randomsound.py
1,727
3.5625
4
#!/usr/bin/python # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Provides RandomSound, a simple way to play a random sound file from a directory using pygame. """ from builtins import object from os.path import join from glob import glob from random import choice from time import sleep from pygame import mixer class RandomSound(object): """ A simple way to play random sound files """ def __init__(self): mixer.init() self.playing = None def play_from(self, path): """ Play a random .wav file from path if none is currently playing """ if mixer.music.get_busy() and self.playing == path: return filename = choice(glob(join(path, '*.wav'))) mixer.music.load(filename) mixer.music.play() self.playing = path def wait(self): """ Wait for the current sound to finish """ while mixer.music.get_busy(): sleep(0.1) def stop(self): """ Stop any playing sound """ mixer.music.stop() def main(): """ Play a single sound and wait for it to finish """ from sys import argv rs = RandomSound() rs.play_from(argv[1]) rs.wait() if __name__ == '__main__': main()
85a40eed93bd27097008e98354632806036e426e
veteransgroup/leetcode
/leetcode/3Sum.py
1,849
3.9375
4
from collections import Counter def speedup(numbers): """ list 里任意三个数相加为0 Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero. Args: numbers (list): 一个全部元素为整数的list Returns: list: 返回list的里面包含所有情况:任意三个元素相加等于0的子list """ result = [[0, 0, 0]] if numbers.count(0) > 2 else [] ocur_numbers = Counter(numbers) twice_numbers = [x for x, y in ocur_numbers.items() if y > 1] ordered_numbers = sorted(ocur_numbers.keys()) ordered_dict = dict() for index, val in enumerate(ordered_numbers): ordered_dict[val] = index ordered_count = len(ordered_numbers) running_times = 0 for outer in range(ordered_count - 1): used_number = set() for inter in range(outer + 1, ordered_count): need = - (ordered_numbers[outer] + ordered_numbers[inter]) running_times += 1 if need in ordered_dict: index = ordered_dict[need] if index > outer and index != inter: if inter in used_number or index in used_number: break else: used_number.add(inter) used_number.add(index) result.append( [ordered_numbers[outer], ordered_numbers[inter], need]) for match_twice in twice_numbers: need = -2 * match_twice running_times += 1 if need in ordered_numbers and need != 0: result.append([need, match_twice, match_twice]) print("running Times", running_times) return result
98af62cdddb028c83bfbf05f2f53c56dd7a7171b
matheusdelimasilva/ChronicKidneyDisorderDiagnostic
/NN_KNN_functions.py
7,345
3.921875
4
# Machine Learning Project - Functions for Step 2 and 3 # ***************************************** # COLLABORATION STATEMENT: # https://www.w3schools.com/ # https://numpy.org/ # https://www.askpython.com/python/array/python-add-elements-to-an-array # ***************************************** #Import statements import numpy as np import matplotlib.pyplot as plt import random from scipy import stats # ******************************************************************* # FUNCTIONS # ******************************************************************* def openckdfile(): glucose, hemoglobin, classification = np.loadtxt('ckd.csv', delimiter=',', skiprows=1, unpack=True) return glucose, hemoglobin, classification ''' PURPOSE: normalize a NumPy array (glucose and hemoglobin both will need to be normalized) PARAMETERS: NumPy array to be normalized RETURNS: the normalized array, the minimum value of the old array, and the maximum value of the old array. ''' def normalizeData(array): #Find min min = np.amin(array) #Fin max max = np.amax(array) #Claculate the scaled values scaled = (array - min)/(max - min) #Return them return scaled, min, max ''' PURPOSE: create a scatter plot of the glucose (Y) and hemoglobin (X) with the points graphed colored based on the classification PARAMETERS: array of glucose, array of hemoglobins, and its classification RETURNS: nothing, only makes the graph ''' def graphData(glucose, hemoglobin, classification): length = len(classification) # zeroGlucose and zeroHemoglobin arrays will values # for patients with no CKD zeroGlucose = [] zeroHemoglobin = [] # oneGlucose and oneHemoglobin arrays will hold the values # for patients with CKD oneGlucose = [] oneHemoglobin = [] for i in range(length): if (classification[i] == 0): zeroGlucose.append(glucose[i]) zeroHemoglobin.append(hemoglobin[i]) else: oneGlucose.append(glucose[i]) oneHemoglobin.append(hemoglobin[i]) plt.scatter(oneGlucose, oneHemoglobin, label="Patients with CKD") plt.scatter(zeroGlucose, zeroHemoglobin, label="Patients without CKD") plt.xlabel("Glucose levels") plt.ylabel("Hemoglobin levels") plt.legend() plt.title("Patients' glucose and hemoglobin levels") plt.show() ''' PURPOSE:creates a random test case that falls within the minimum and maximum values of the training hemoglobin and glucose data PARAMETERS: glucose's min and max value, hemoglobin's min and max value RETURNS: normalized and not-normalized test case ''' def createTestCase(minH, maxH, minG, maxG): print(" -Generating a random test case- ") #generate random test cases for hemoglobin and glucose testCaseH = random.randint(int(minH), int(maxH)+1) testCaseG = random.randint(int(minG), int(maxG)+1) print("Hemoglobin level:", testCaseH) print("Glucose level:", testCaseG) #normalize random test cases newHemoglobin = (testCaseH - minH)/(maxH - minH) newGlucose = (testCaseG - minG)/(maxG - minG) return newHemoglobin, newGlucose, testCaseH, testCaseG ''' PURPOSE:Calculates the distance from the test case to each point PARAMETERS: test case's glucose and hemoglobin levels, the array with glucose and hemoglobin levels from the patients RETURNS: an array containing all the distances calculated ''' def calculateDistanceArray(newGlucose, newHemoglobin, glucose, hemoglobin): distanceG = (newGlucose - glucose)**2 distanceH = (newHemoglobin - hemoglobin)**2 distanceArray = (distanceG + distanceH)*0.5 return distanceArray ''' PURPOSE: Use the Nearest Neighbor Classifier to classify the test case PARAMETERS: glucose and hemoglobins data, and their classifications, test case's glucose and hemoglobin levels (newGlucose, newHemoglobin) RETURNS: prints test case's classification ''' def nearestNeighborClassifier(newGlucose, newHemoglobin, glucose, hemoglobin, classification): print("\nNearest Neighbor Classifier:") #Get the distance array distanceArray = calculateDistanceArray(newGlucose, newHemoglobin, glucose, hemoglobin) #Find the point that is closest to the test case closest = min(distanceArray) #Find the index of the closest point closestIdx = np.where(distanceArray == closest) print("Closest index:", closestIdx) #Get the closest point's classification if (classification[closestIdx]): print("RESULT: Test case probably has CKD (class = 1)") else: print("RESULT: Test case probably does not have CKD (class = 0)") print("\n") ''' PURPOSE: Graph the patients' and the test case's glucose and hemoglobin levels PARAMETERS: glucose and hemoglobins data and their classifications, test case's glucose and hemoglobin levels (newGlucose, newHemoglobin) RETURNS: plots a graph ''' def graphTestCase (newGlucose, newHemoglobin, glucose, hemoglobin, classification): length = len(classification) # zeroGlucose and zeroHemoglobin arrays will hold values # for patients with no CKD zeroGlucose = [] zeroHemoglobin = [] # oneGlucose and oneHemoglobin arrays will hold the values # for patients with CKD oneGlucose = [] oneHemoglobin = [] for i in range(length): if (classification[i] == 0): zeroGlucose.append(glucose[i]) zeroHemoglobin.append(hemoglobin[i]) else: oneGlucose.append(glucose[i]) oneHemoglobin.append(hemoglobin[i]) plt.scatter(oneGlucose, oneHemoglobin, label="Patients with CKD") plt.scatter(zeroGlucose, zeroHemoglobin, label="Patients without CKD") plt.scatter(newGlucose, newHemoglobin, label="Test case", edgecolors = "r", color = "r") plt.xlabel("Glucose levels") plt.ylabel("Hemoglobin levels") plt.legend() plt.title("Patients' glucose and hemoglobin levels") plt.show() ''' PURPOSE: Use the K-Nearest Neighbor Classifier to classify the test case PARAMETERS: glucose and hemoglobins data, and their classifications, test case's glucose and hemoglobin levels (newGlucose, newHemoglobin) RETURNS: prints test case's classification ''' def kNearestNeighborClassifier(k, newGlucose, newHemoglobin, glucose, hemoglobin, classification): print("K-Nearest Neighbor Classifier:") #Get the distance array distanceArray = calculateDistanceArray(newGlucose, newHemoglobin, glucose, hemoglobin) #Get all the indices in closest order (closest to furthest) allClosestIndexes = np.argsort(distanceArray) #Get the k-closest points kClosestIndexes = allClosestIndexes[0:k] print("K-closest indexes:", kClosestIndexes) #Get the classification of the closest points kClosestClass = classification[kClosestIndexes] #Find the mode of the k closest points mode = stats.mode(kClosestClass) print("K-closest classifications:", kClosestClass) #Get the test's classification if (mode): print("RESULT: Test case probably has CKD (class = 1)") else: print("RESULT: Test case probably does not have CKD (class = 0)")
300702830b8f8c6e092c6068a667fa61bd69d84c
iiibsceprana/pranavsai
/functions/funtest2.py
153
3.6875
4
def reassign(list): list = [0,1,9,8,7] print(list) def append(list): list.append(-5) print(list) list=[4] reassign(list) append(list)
14d3fd4767b746e8fe459695f66ec523201bd95a
iiibsceprana/pranavsai
/pranav/iterators.py
248
3.703125
4
#Geneartor def squares(start, stop): for i in range(start, stop): print(i*i,end=" ") Iterator = squares(1, 10) #print(Iterator) Iterator1=squares(11,20) i=range(10) print(i) for l in i: print(l) for l in i: print(l)
bcb1b9acfea3e0eb1714788eee2c42d9ddb9d694
LeeroyC710/pj
/Desktop/py/YuyoITGradingSystem2.py
2,203
4.1875
4
def grading(num): #Grades the grades if num >=99: return "U. No way you could have gotten that without cheating. (A****)" elif num >=94: return "S-Class Hero ranking. All might would be proud." elif num >= 87: return "A**. Either a prodigy or a cheater." elif num >= 79: return "A*. Hard work pays off!" elif num >= 70: return "A. First class grade." elif num >= 58: return "B. You payed enough attention in class. Well done!" elif num >= 42: return "C. You have passed and can still apply to the same jobs as everyone else smarter than you!" elif num >= 28: return "D." elif num >= 17: return "E." elif num >= 11: return "F. At least you can still put it on your CV." else: return "U, which is a fail. How on Earth did you manage to do that? It's only 11% to pass!" def gradecalc(test1, test2, test3, maxgrade1, maxgrade2, maxgrade3): valid = True while valid: try: Home_Grade = float(input(test1)) Assess_Grade = float(input(test2)) Exam_Grade = float(input(test3)) if Home_Grade > maxgrade1 or Assess_Grade > maxgrade2 or Exam_Grade > maxgrade3: print("One (or more) of your grades is higher than the maximum mark") elif Home_Grade < 0 or Assess_Grade < 0 or Exam_Grade < 0: print("You can't have negative marks") else: valid = False except ValueError: print("That is not a (valid) number.") #return [Home_Grade, Assess_Grade, Exam_Grade] return { "home": Home_Grade, "assess": Assess_Grade, "exam": Exam_Grade } def thecode(): print ("Virtual report card.") first = input("First Name:") last = input("Last Name:") grades = gradecalc("Homework grade out of 25: ","Assessment grade out of 50: ","Final exam grade out of 100: ",25,50,100) score = round((grades["home"]*4*0.25 + grades["assess"]*2*0.35 + grades["exam"]*0.45), 2) grade = grading(score) print(first, last, "got a score of: " + str(score) + ", This is a grade of: " + grade) thecode()
b3c8b2390a7d72e0976953785881c3b3471294ed
geosun61/CS50Projects
/geosun61-web50-projects-2020-x-1/sql/list.py
959
3.671875
4
import os from sqlalchemy import create_engine from sqlalchemy.orm import scoped_session, sessionmaker engine = create_engine(os.getenv("DATABASE_URL")) # database engine object from SQLAlchemy that manages connections to the database # DATABASE_URL is an environment variable that indicates where the database lives db = scoped_session(sessionmaker(bind=engine)) # create a 'scoped session' that ensures different users' interactions with the # database are kept separate def main(): books = db.execute("SELECT isbn, title, author, year FROM books").fetchall() # execute this SQL command and return all of the results for book in books: print(f"Book ISBN: {book.isbn}, Title: {book.title}, Author: {book.author}, Year Published: {book.year}") # for every flight, print out the flight info if __name__ == "__main__": main()
d7a3cb208bba848829312fec5f9542f4f8952ee8
geosun61/CS50Projects
/geosun61-web50-projects-2020-x-1/sql/import.py
1,266
3.609375
4
import os import csv from sqlalchemy import create_engine from sqlalchemy.orm import scoped_session, sessionmaker engine = create_engine(os.getenv("DATABASE_URL")) # database engine object from SQLAlchemy that manages connections to the database # DATABASE_URL is an environment variable that indicates where the database lives db = scoped_session(sessionmaker(bind=engine)) # create a 'scoped session' that ensures different users' interactions with the # database are kept separate def main(): f = open("..\\books.csv") #open books reader = csv.reader(f) for isbn, title, author, year in reader: # loop gives each column a name db.execute("INSERT INTO books (isbn, title, author, year) VALUES (:isbn, :title, :author, :year)", {"isbn": isbn, "title": title, "author": author, "year": year}) # substitute values from CSV line into SQL command, as per this dict print(f"Added book isbn number {isbn}, title is {title}, author name is {author}, Year Published {year} ----- to books table") db.commit() # transactions are assumed, so close the transaction finished if __name__ == "__main__": main()
deb4768dc86b14721ab971c668cd1108e10e68fc
dmoini/python
/tile_cover_cost.py
306
4.03125
4
def ask(): width = int(input("What is the width of each tile? ")) length = int(input("What is the length of each tile? ")) cost = int(input("What is the cost of each tile? ")) return width, length, cost def cost(): width, length, cost = ask() print(width * length * cost) cost()
f5d40426005cb11f4d9170a0d9ccd2ae0ecb1c16
PetrJanousek/Neurogenetic_algorithm
/mutation_funcs.py
1,343
3.890625
4
# Mutation helper functions: import random import numpy as np def swap_weights(array): """ Given the matrix of weights of the neural network, it mutates it. Chooses randomly how how many columns and which ones will be swapped. Then it swaps the positions of the weights columns. array : np.ndarray Returns : np.ndarray """ number_of_swaps = (np.random.randint(0, array.shape[0] * 2, 1) // 2)[0] if number_of_swaps == 0: return array indexes = np.random.choice(array.shape[0], number_of_swaps, replace=False) swap_pairs = [(indexes[i], indexes[i+1]) for i in range(0, number_of_swaps, 2) \ if i+1 != number_of_swaps] for pair in swap_pairs: tmp = array[pair[0]] array[pair[0]] = array[pair[1]] array[pair[1]] = tmp return array def replace_weights(array): """ Given the matrix of weights of the neural network, it mutates it. Randomly chooses the columns to be completely replaced by randomly generated new columns. array : np.ndarray Returns : np.ndarray """ number_of_replaces = np.random.randint(2, array.shape[0], 1)[0] indexes = np.random.choice(array.shape[0], number_of_replaces, replace=False) for index in indexes: array[index] = np.random.uniform(-1,1) return array
dd61435d53cd3d5c36a69148d79a7efd06aa726f
meixingdg/course-prereq
/misc/datastoreBuilder/tsvBuilder.py
2,453
3.703125
4
import json import urllib # We keep global variables to store the YACS API's urls. yacs_url = "http://yacs.me/api/4/" yacs_deps_url = yacs_url + "departments/" yacs_courses_url = yacs_url + "courses/" def get_deps(): """Get a json of departments from YACS.""" response = urllib.urlopen(yacs_deps_url) data = json.loads(response.read()) return data["result"] def get_courses(depId = None): """Function to get a json of courses from YACS. If a department id is passed in, we get only the courses from that department. """ if depId == None: response = urllib.urlopen(yacs_courses_url) else: response = urllib.urlopen(yacs_courses_url + "?department_id=" + str(depId)) data = json.loads(response.read()) return data["result"] def make_deps_tsv(outFileName): """Function to create a tsv file. The tsv will have the department code, name. """ depsData = get_deps() outFileObj = open(outFileName, 'w') for dep in depsData: outFileObj.write(dep["code"] + "\t" + dep["name"] + "\n") def create_departments_dict(): """Function to create a dictionary in which the YACS department ID is the key and the department name and code is the value. """ departmentsJsonResult = get_deps() departmentsDict = dict() for row in departmentsJsonResult: departmentsDict[row["id"]] = (row["name"], row["code"]) return departmentsDict def make_courses_tsv(semester, year, outFileName): """Function to create a tsv file of course info.""" departmentsDict = create_departments_dict() coursesData = get_courses() outFile = open(outFileName, 'w') for row in coursesData: outFile.write(semester + "\t" + year + "\t" + row["name"].encode('utf8') + "\t" + str(row["number"]) + "\t" + row["description"].encode('utf8') + "\t" + str(row["is_comm_intense"]) + "\t" + str(row["min_credits"]) + "\t" + row["grade_type"].encode('utf8') + "\t" + str(row["max_credits"]) + "\t" + row["prereqs"].encode('utf8') + "\t" + departmentsDict[row["department_id"]][0].encode('utf8') + "\t" + departmentsDict[row["department_id"]][1].encode('utf8') + "\n") outFile.close() make_deps_tsv("tdeps.tsv") make_courses_tsv("Fall", "2015", "tcourses.tsv")
1c2e851481cd1b777079e28833c71e84dbe81368
Maor2871/DogsBeach
/Server/threads/Client communicator/User.py
1,692
3.625
4
# -*- coding: utf-8 -*- import threading import random class User(): """ The class represent a user that has connected to the program and use it right now. """ random_id_numbers = [] def __init__(self, general, socket): """Constructor. The function receives general, socket and client_com_thread in order to create an instance which will represent a user in the program. The function does not return parameters.""" self.id = None self.get_random_id_number() self.general = general # The socket of the client. With this socket the system can communicate with the client self.socket = socket self.user_name = "unknown" # Start the communicator of the client. self.update_con_users = threading.Thread(target=self.update_connected_users) self.update_con_users.start() def update_connected_users(self): """The function wait till the client will connect to the program as a user, than it update this to general. The function does not receive or return parameters.""" while self.user_name == "unknown": pass self.general.connected_users[self.user_name] = self def get_random_id_number(self): """The function does not receive or return parameters. The function update a random id number that will sign the user to self.id.""" self.id = random.randint(0, 60000) #blocking until we get a number that not sign another client. while self.id in User.random_id_numbers: self.id = random.randint(0, 60000) User.random_id_numbers.append(self.id)
6373c1db4bfd90b91593bc90c957c0d98feda180
haiyaoxliu/old
/stuyvesant intro class/brooks and pclassic/raw input.py
250
3.765625
4
def get(): while True: c = raw_input('input name? (Y/N)') if c == 'Y' or c == 'y': n = raw_input('name:') elif c == 'N' or c == 'n': break else: print('Error') break
2d3665446a721820d23752ce7ca92e6f44bed8fe
haiyaoxliu/old
/stuyvesant intro class/brooks and pclassic/test56.py
628
3.953125
4
# Problem 5: def replaceAll(astring,lookfor,replaceWith): rstring = "" while astring.find(lookfor) != -1: rstring = rstring + astring[:astring.find(lookfor)] + replaceWith astring = astring[astring.find(lookfor) + len(lookfor):] rstring = rstring + astring return rstring # Test results: print(replaceAll('whatever, what','what','where')) # returns 'whereever, where' print(replaceAll('he said, she said','he','she')) # returns 'she said, sshe said' print(replaceAll('he said whatever else','whatever',' ')) # returns 'he said else" # Problem 6: def countWords(s): return len(s.split())
5e4a0022d4dbe3ce97ae4e8345f031106b7fdb1f
IvanCaballero1204/Actividad_3
/main.py
668
4.03125
4
#!/usr/bin/env python3 from math import pi import areas def main(): print("Hola mundo") nombre = input("¿Cual es tu nombre? ") print("Hola {}".format(nombre)) edad = int(input("¿Cuántos años tienes? ")) print("{} tienes {} años y en un año tendrás {} años".format(nombre, edad, edad + 1)) area_triangulo = areas.triangulo() print("El area de tu triangulo es igual a: {}".format(area_triangulo)) area_circulo = areas.circulo() print("El area de tu circulo es igual a: {}".format(area_circulo)) area_dona = areas.dona() print("El area de tu dona es igual a: {}".format(area_dona)) #print("Bienvenido a main") main()
d9dbb2999d18d9d3eed3a6d5391a99ea17554842
panipinaka/FML
/Linear_regression.py
1,247
3.8125
4
# -*- coding: utf-8 -*- """ Created on Sat Oct 5 09:01:27 2019 @author: Pinaka Pani """ #import libraries import numpy as np import pandas as pd import matplotlib.pyplot as plt #importing the dataset dataset = pd.read_csv("Salary_Data.csv") X = dataset.iloc[:,:-1].values y = dataset.iloc[:,1].values ##spliting the dataset into training and test set from sklearn.model_selection import train_test_split X_train,X_test,y_train, y_test = train_test_split(X,y,test_size=1/3.0,random_state=0) #fitting simple linear regression to training data from sklearn.linear_model import LinearRegression regressor = LinearRegression() regressor.fit(X_train,y_train) #preadicting the test set results y_pred = regressor.predict(X_test) #visulization the training set results plt.scatter(X_train,y_train,color='red') plt.plot(X_train,regressor.predict(X_train),color = 'blue') plt.title("Salary vs Experience(Training set)") plt.xlabel('years of experience') plt.ylabel('Salary') plt.legend() plt.show() #visulization the training set results plt.scatter(X_test,y_test,color='red') plt.plot(X_train,regressor.predict(X_train),color = 'blue') plt.title("Salary vs Experience(Test set)") plt.xlabel('years of experience') plt.ylabel('Salary') plt.show()
ad882f87d72023e54a7e3b8997a170d15032e48f
meghasn/study_grp_practice
/leaf_similar_tree.py
994
3.875
4
# // Time Complexity :O(n) # // Space Complexity :O(h) # // Did this code successfully run on Leetcode :yes # // Any problem you faced while coding this :no # // Your code here along with comments explaining your approach # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def __init__(self): self.li1=[] self.li2=[] def leafSimilar(self, root1: Optional[TreeNode], root2: Optional[TreeNode]) -> bool: self.dfs(root1,self.li1) self.dfs(root2,self.li2) return self.li1==self.li2 def dfs(self,root,li): #base if root.left is None and root.right is None: li.append(root.val) return #logic if root.left: self.dfs(root.left,li) if root.right: self.dfs(root.right,li)
fb2b2ae876479abe029ef5db6f0e854442511b4c
windmill312/compilers
/python-compiler/src/main/java/com/windmill312/samples/listInversion.py
160
3.515625
4
list = [1,2,3,4,5] nnCnt = 2 for i in range(0, nnCnt): temp = list[len(list) - 1 - i] list[len(list) - 1 - i] = list[i] list[i] = temp print(list)
e74ab7f678eb535ee17cbe4cae7e22a835038407
imranasq/DataStructPy
/brickPyramid.py
336
3.96875
4
blocks = int(input("Enter the number of blocks: ")) height = 0 sum = 0 if blocks == 0: print("The height of the pyramid:", height) else: for i in range(1, blocks): sum = sum + i if sum <= blocks: height = height+1 else: break print("The height of the pyramid:", height)
96816dff40bd38767a7fb5ed41c40171bb84304e
imranasq/DataStructPy
/Array/matrix.py
338
3.890625
4
from numpy import * matrix1 = matrix('3, 24, 5; 24, 6, 2 ; 4, 5, 76') matrix2 = matrix('4, 3, 4 ; 24, 5, 1; 6, 67, 2') matrix3 = matrix1 + matrix2 matrix4 = matrix1 * matrix2 #for multiplication it should be 1st matrix row = 2nd matrix column. print("Sum of the matrices: ", matrix3) print("Multiplication of the matrices: ", matrix4)
70f8f903d61d69a2664cd978a1fad2abd2d0c94f
MeSrinathReddy/nltk-examples
/src/book/ch06.py
9,819
3.65625
4
#!/usr/bin/python # Text classification from __future__ import division import nltk from nltk.classify import apply_features import random import math def _gender_features(word): features = {} # started with 1 feature features["last_letter"] = word[-1].lower() # added some more features["first_letter"] = word[0].lower() for letter in "abcdefghijklmnopqrstuvwxyz": features["count(%s)" % letter] = word.lower().count(letter) features["has(%s)" % letter] = (letter in word.lower()) # result of error analysis: # names ending in -yn are mostly female, and names ending # in -ch ar mostly male, so add 2 more features features["suffix2"] = word[-2:] return features def naive_bayes_gender_classifier(): from nltk.corpus import names names = ([(name, "male") for name in names.words("male.txt")] + [(name, "female") for name in names.words("female.txt")]) random.shuffle(names) # featuresets = [(_gender_features(n), g) for (n,g) in names] # train_set, test_set = featuresets[500:], featuresets[:500] # advisable to stream the sets in for large data set. train_set = apply_features(_gender_features, names[500:]) test_set = apply_features(_gender_features, names[:500]) classifier = nltk.NaiveBayesClassifier.train(train_set) print "Neo is ", classifier.classify(_gender_features("Neo")) print "Trinity is", classifier.classify(_gender_features("Trinity")) # calculate the accuracy of the classifier print nltk.classify.accuracy(classifier, test_set) classifier.show_most_informative_features(5) def error_analysis(): from nltk.corpus import names names = ([(name, "male") for name in names.words("male.txt")] + [(name, "female") for name in names.words("female.txt")]) random.shuffle(names) test_names, devtest_names, train_names = \ names[:500], names[500:1500], names[1500:] train_set = [(_gender_features(n), g) for (n,g) in train_names] devtest_set = [(_gender_features(n), g) for (n,g) in devtest_names] test_set = [(_gender_features(n), g) for (n,g) in test_names] classifier = nltk.NaiveBayesClassifier.train(train_set) print nltk.classify.accuracy(classifier, devtest_set) errors = [] for (name, tag) in devtest_names: guess = classifier.classify(_gender_features(name)) if guess != tag: errors.append((tag, guess, name)) for (tag, guess, name) in sorted(errors): print "correct=%s, guess=%s, name=%s" % (tag, guess, name) def _document_features(document, word_features): document_words = set(document) features = {} for word in word_features: features['contains(%s)' % word] = (word in document_words) return features def document_classification_movie_reviews(): from nltk.corpus import movie_reviews documents = [(list(movie_reviews.words(fileid)), category) for category in movie_reviews.categories() for fileid in movie_reviews.fileids(category)] random.shuffle(documents) # use the most frequest 2000 words as features all_words = nltk.FreqDist(w.lower() for w in movie_reviews.words()) word_features = all_words.keys()[:2000] featuresets = [(_document_features(d, word_features), category) for (d,category) in documents] train_set, test_set = featuresets[100:], featuresets[:100] classifier = nltk.NaiveBayesClassifier.train(train_set) print nltk.classify.accuracy(classifier, test_set) classifier.show_most_informative_features(30) def _pos_features(word, common_suffixes): features = {} for suffix in common_suffixes: features["endswith(%s)" % suffix] = word.lower().endswith(suffix) return features def pos_tagging_classification(): # find most common suffixes of words from nltk.corpus import brown suffix_fdist = nltk.FreqDist() for word in brown.words(): word = word.lower() suffix_fdist.inc(word[-1:]) suffix_fdist.inc(word[-2:]) suffix_fdist.inc(word[-3:]) common_suffixes = suffix_fdist.keys()[:100] tagged_words = brown.tagged_words(categories="news") featuresets = [(_pos_features(w, common_suffixes), pos) for (w, pos) in tagged_words] size = int(len(featuresets) * 0.1) train_set, test_set = featuresets[size:], featuresets[:size] classifier = nltk.DecisionTreeClassifier.train(train_set) print nltk.classify.accuracy(classifier, test_set) print classifier.pseudocode(depth=4) def _pos_features2(sentence, i): features = { "suffix(1)" : sentence[i][-1:], "suffix(2)" : sentence[i][-2:], "suffix(3)" : sentence[i][-3:]} if i == 0: features["prev-word"] = "<START>" else: features["prev-word"] = sentence[i - 1] return features def pos_tagging_classification_with_sentence_context(): from nltk.corpus import brown tagged_sents = brown.tagged_sents(categories="news") featuresets = [] for tagged_sent in tagged_sents: untagged_sent = nltk.tag.untag(tagged_sent) for i, (word, tag) in enumerate(tagged_sent): featuresets.append((_pos_features2(untagged_sent, i), tag)) size = int(len(featuresets) * 0.1) train_set, test_set = featuresets[size:], featuresets[:size] classifier = nltk.NaiveBayesClassifier.train(train_set) print nltk.classify.accuracy(classifier, test_set) def _pos_features3(sentence, i, history): features = { "suffix(1)" : sentence[i][-1:], "suffix(2)" : sentence[i][-2:], "suffix(3)" : sentence[i][-3:]} if i == 0: features["prev-word"] = "<START>" features["prev-tag"] = "<START>" else: features["prev-word"] = sentence[i-1] features["prev-tag"] = history[i-1] return features class ConsecutivePosTagger(nltk.TaggerI): def __init__(self, train_sents): train_set = [] for tagged_sent in train_sents: untagged_sent = nltk.tag.untag(tagged_sent) history = [] for i, (word, tag) in enumerate(tagged_sent): featureset = _pos_features3(untagged_sent, i, history) train_set.append((featureset, tag)) history.append(tag) self.classifier = nltk.NaiveBayesClassifier.train(train_set) def tag(self, sentence): history = [] for i, word in enumerate(sentence): featureset = _pos_features3(sentence, i, history) tag = self.classifier.classify(featureset) history.append(tag) return zip(sentence, history) def sequence_classification_using_prev_pos(): from nltk.corpus import brown tagged_sents = brown.tagged_sents(categories="news") size = int(len(tagged_sents) * 0.1) train_sents, test_sents = tagged_sents[size:], tagged_sents[:size] tagger = ConsecutivePosTagger(train_sents) print tagger.evaluate(test_sents) def _punct_features(tokens, i): return { "next-word-capitalized" : tokens[i+1][0].isupper(), "prevword" : tokens[i-1].lower(), "punct" : tokens[i], "prev-word-is-one-char" : len(tokens[i-1]) == 1} def sentence_segmentation_as_classification_for_punctuation(): from nltk.corpus import treebank_raw sents = treebank_raw.sents() tokens = [] boundaries = set() offset = 0 for sent in sents: # each sent is a list of words, added flat into sents tokens.extend(sent) offset += len(sent) boundaries.add(offset - 1) # all sentence boundary tokens featuresets = [(_punct_features(tokens, i), (i in boundaries)) for i in range(1, len(tokens) - 1) if tokens[i] in ".?!"] size = int(len(featuresets) * 0.1) train_set, test_set = featuresets[size:], featuresets[:size] classifier = nltk.NaiveBayesClassifier.train(train_set) print nltk.classify.accuracy(classifier, test_set) def _dialog_act_features(post): features = {} for word in nltk.word_tokenize(post): features["contains(%s)" % word.lower()] = True return features def identify_dialog_act_types(): posts = nltk.corpus.nps_chat.xml_posts()[:10000] featuresets = [(_dialog_act_features(post.text), post.get("class")) for post in posts] size = int(len(featuresets) * 0.1) train_set, test_set = featuresets[size:], featuresets[:size] classifier = nltk.NaiveBayesClassifier.train(train_set) print nltk.classify.accuracy(classifier, test_set) def _rte_features(rtepair): # builds a bag of words for both text and hypothesis # after throwing away some stopwords extractor = nltk.RTEFeatureExtractor(rtepair) return { "word_overlap" : len(extractor.overlap("word")), "word_hyp_extra" : len(extractor.hyp_extra("word")), "ne_overlap" : len(extractor.overlap("ne")), "ne_hyp_overlap" : len(extractor.hyp_extra("ne"))} def recognize_text_entailment(): rtepair = nltk.corpus.rte.pairs(["rte3_dev.xml"])[33] extractor = nltk.RTEFeatureExtractor(rtepair) # all important words in hypothesis is contained in text => entailment print "text-words=", extractor.text_words print "hyp-words=", extractor.hyp_words print "overlap(word)=", extractor.overlap("word") print "overlap(ne)=", extractor.overlap("ne") print "hyp_extra(word)=", extractor.hyp_extra("word") print "hyp_extra(ne)=", extractor.hyp_extra("ne") def entropy(labels): freqdist = nltk.FreqDist(labels) probs = [freqdist.freq(label) for label in labels] return -sum([p * math.log(p, 2) for p in probs]) def calc_entropy(): print entropy(["male", "male", "male", "female"]) print entropy(["male", "male", "male", "male"]) print entropy(["female", "female", "female", "female"]) def main(): # naive_bayes_gender_classifier() # error_analysis() document_classification_movie_reviews() # pos_tagging_classification() # pos_tagging_classification_with_sentence_context() # sequence_classification_using_prev_pos() # sentence_segmentation_as_classification_for_punctuation() # identify_dialog_act_types() # recognize_text_entailment() # calc_entropy() print "end" if __name__ == "__main__": main()
124cee9a7367047f0fed2037b3997df4cfaf9399
Kamil-Ru/Functions_and_Methods_Homework
/Homework_7.py
1,384
4.46875
4
# Hard: # Write a Python function to check whether a string is pangram or not. (Assume the string passed in does not have any punctuation) # Note : Pangrams are words or sentences containing every letter of the alphabet at least once. # For example : "The quick brown fox jumps over the lazy dog" # Hint: You may want to use .replace() method to get rid of spaces. # Hint: Look at the string module # Hint: In case you want to use set comparisons ##### My Notes ''' import string alphabet=string.ascii_lowercase str1 = "The quick brown fox jumps over the lazy" str2 = str1.replace(' ','') str2 = str2.lower() str2 = set(str2) alphabet=set(string.ascii_lowercase) if alphabet.issubset(str2): print('OK') else: print('nop') ''' import string def ispangram(str1, alphabet=set(string.ascii_lowercase)): # remove any space from string, lowercase, convert too set and grab all uniques letters str2 = set(str1.replace(' ','').lower()) if alphabet.issubset(str2): print('"{}" is a pangram.'.format(str1)) else: print('"{}" is not a pangram.'.format(str1)) ## TEST ispangram("The quick brown fox jumps over the lazy dog") ispangram("The quick brown fox jumps over the lazy DOG") ispangram("The quick brown fox jumps over the lazy") ispangram("Jackdaws love my big sphinx of quartz") ispangram("Pack my box with five dozen liquor jugs")
f4e2b611a1ee76f58dbe1a4bc56d96b9491d7a95
emg110/LearningGameStructure
/MCTS/snake_player.py
906
3.609375
4
import game from snake_action import * class SnakePlayer(game.HumanPlayer): """ Human player that plays Snake. """ def choose_action(self, board): next_dir = self.source() # returns 0,1,2,3,4, representing the direction the person wants to go color = board.turn curr_dir = board.get_snake(color)[0] # current direction the snake is going # if human isn't holidng the joystick in any direction if next_dir == 0: action = SnakeAction(board.turn, curr_dir) elif (next_dir == 1 and curr_dir == 3) or (next_dir == 3 and curr_dir == 1): action = SnakeAction(board.turn, curr_dir) elif (next_dir == 2 and curr_dir == 4) or (next_dir == 4 and curr_dir == 2): action = SnakeAction(board.turn, curr_dir) else: action = SnakeAction(board.turn, next_dir) return action
00e9cd084d8b464fda0560b1e24e93290af4099c
ptkang/python-advanced
/chapter06/s04_set_frozenset.py
801
4.03125
4
# set集合, frozenset(不可变集合) 无需,不重复 # set实际顺序和我们添加的顺序不一样 # set接收一个iterable对象 # set性能很高,时间复杂度为O(1) s = set('abcdee') print(s) s = set(['a', 'b', 'c', 'd', 'e']) print(s) s = {'a', 'b', 'c', 'd', 'e'} print(s) s.add('f') print(s) # frozenset不可变集合使得其可以作为dict的key s = frozenset('abcdee') print(s) # update,将两个集合合并 s = set('abcdee') another_set = set('defg') s.update(another_set) print(s) # difference 求集合的差集: s - another_set = diff_set diff_set = s.difference(another_set) print(diff_set) minus_set = s - another_set print(minus_set) # 集合里面三种运算: 联合 | , 交集 &, 差集 - if 'c' in s: print(True) print(diff_set.issubset(s))
fc05708df40a3f5a691e39484a629d50863e27d0
ptkang/python-advanced
/chapter04/class_var_4_4.py
573
4.0625
4
# 类变量和实例变量 class A: # 类变量 aa = 1 def __init__(self, x, y): # self是类的实例 # x, y 前面加self,即为实例变量 self.x = x self.y = y a = A(2, 3) # a.aa能访问是因为a先查找自身实例变量aa,若没找到,则向上在所在类里面查找类变量aa print(a.x, a.y, a.aa, A.aa) # 类变量必须通过类名.变量名来修改 A.aa = 11 # a.aa = 255 实质为动态的给实例a增加了实例变量aa a.aa = 255 print(a.x, a.y, a.aa, A.aa) b = A(4, 5) print(b.x, b.y, b.aa, A.aa)
eec1b219bf01cb69e8d813cd2cc0ede7a1d43cb2
schana/random-hacking
/mod_pow.py
1,041
4.09375
4
''' This computes the result of (base ^ exponent) % modulus for large numbers with both an iterative and recursive solution. Time complexity is O(logN) where N is the exponent. ''' def power_mod(base, exponent, modulus): result = 1 base = base % modulus while exponent > 0: if exponent % 2 == 1: result = (result * base) % modulus base = (base ** 2) % modulus exponent = exponent // 2 return result def power_mod_recursive(base, exponent, modulus): if exponent == 0: return 1 base = base % modulus result = power_mod_recursive((base ** 2) % modulus, exponent // 2, modulus) if exponent % 2 == 1: result = (result * base) % modulus return result if __name__ == '__main__': examples = [ (1223, 4124, 1), (1223, 0, 13), (2, 3, 5), (1231214, 12592198, 12577), (2467092835, 1035991785, 149855123) ] for example in examples: print(f'{power_mod(*example)} == {power_mod_recursive(*example)}')
a44b05ffd053712ead4334cfdcb03527bae47098
CKubinec/NHLAnalytics
/main.py
4,593
3.515625
4
import requests import json from Forward import Forward from Goalie import Goalie def write_to_file(player_array, name_of_role): """Writes all data to 3 separate files, 1 for Forwards (`forwards.txt`), 1 for Defencemen (`defenceman.txt`), and 1 for Goalies (`goalies.txt`)""" # Sorts the arrays by points before printing to files player_array.sort(key=lambda x: x.projected_points, reverse=True) f = open(f"{name_of_role}.txt", "w") for player in player_array: f.write(f"{player.name}\t{player.projected_points}\n") f.close() def get_teams_players(): """Uses the NHL API to get data for processing. Stores all data into global array: `player_array`""" print("Getting all teams players...") # loops and get all NHL teams roster team_dict = {} player_array = [] for i in range(1, 70): response = requests.get(f"https://statsapi.web.nhl.com/api/v1/teams/{i}?expand=team.roster") team_dict[i] = json.loads(json.dumps(response.json())) for i in range(1, 50): try: for x in range(0, 50): player = (team_dict[i]["teams"][0]["roster"]["roster"][x]["person"]["fullName"], team_dict[i]["teams"][0]["roster"]["roster"][x]["person"]["link"], team_dict[i]["teams"][0]["roster"]["roster"][x]["position"]["type"]) player_array.append(player) except (KeyError, IndexError): continue return player_array def create_players(player_array): """Brings in player data and calculates the points for each player. Sends the players out to get written in a file for easy reading""" forward_array = [] defence_array = [] goalie_array = [] # loops for player data for player in player_array: response = requests.get(f"https://statsapi.web.nhl.com{player[1]}/stats?stats=statsSingleSeason" f"&season=20202021") temp = json.loads(json.dumps(response.json())) # Calculates forward and defencemen points if player[2] != "Goalie": try: skater = Forward(player[0], player[2], temp["stats"][0]["splits"][0]["stat"]["goals"], temp["stats"][0]["splits"][0]["stat"]["assists"], temp["stats"][0]["splits"][0]["stat"]["plusMinus"], temp["stats"][0]["splits"][0]["stat"]["powerPlayPoints"], temp["stats"][0]["splits"][0]["stat"]["shortHandedPoints"], temp["stats"][0]["splits"][0]["stat"]["gameWinningGoals"], temp["stats"][0]["splits"][0]["stat"]["shots"], temp["stats"][0]["splits"][0]["stat"]["hits"], temp["stats"][0]["splits"][0]["stat"]["blocked"], temp["stats"][0]["splits"][0]["stat"]["games"]) print("Player " + skater.name + " created") if player[2] == "Defenseman": defence_array.append(skater) else: forward_array.append(skater) except IndexError: print("Player " + player[0] + " has no relevant data.. SKIPPING") continue # Calculates goalie points else: try: skater = Goalie(player[0], player[2], temp["stats"][0]["splits"][0]["stat"]["wins"], temp["stats"][0]["splits"][0]["stat"]["goalsAgainst"], temp["stats"][0]["splits"][0]["stat"]["saves"], temp["stats"][0]["splits"][0]["stat"]["shutouts"], temp["stats"][0]["splits"][0]["stat"]["games"]) print("Player " + skater.name + " created") goalie_array.append(skater) except IndexError: print("Player " + player[0] + " has no relevant data.. SKIPPING") continue # Writes all arrays into the files write_to_file(forward_array, "forwards") write_to_file(defence_array, "defenseman") write_to_file(goalie_array, "goalies") def main(): """Program to find the average points per game an NHL Player would get using the current point structure in the league I'm currently in. Point structure can be changed in the Goalie and Forward Classes.""" create_players(get_teams_players()) if __name__ == '__main__': main()
3d6307db27e1682c31ed948cae246e6075a7c6da
dstanfield/adventcode2020
/day1/day1.py
565
3.8125
4
import csv valuesString = [] with open('input.csv', 'r') as fd: reader = csv.reader(fd) for row in reader: valuesString.append(row[0]) values = [int(numeric_string) for numeric_string in valuesString] print (values) for year in values: for secondyear in values: for thirdyear in values: if year + secondyear + thirdyear == 2020: answer = year*secondyear*thirdyear print(str(year) + ' and ' + str(secondyear) + ' and ' + str(thirdyear) + ' add up to 2020 and multiply to ' + str(answer) )
7242e72be2fc01a2d79bc2fbd565801072750e65
muhammed94munshid/codekatta-hunter-
/h03.py
190
3.515625
4
n=int(input()) l=[] for i in range (1,n+1): a=int(input()) l.append(a) print (l) m=[] for idx,val in enumerate(l): b=idx,val m.append(b) print(m) for x in m:
df1de6d59515d454f05524238460a4f76e77b99b
MatiwsxD/ayed-2019-1
/Labinfo_7/D -Left Rotation.py
317
3.625
4
from sys import stdin def rotation(lista,y): if y == 0: return lista else: x =lista[0] lista = lista[1:] z = lista+[x] return rotation(z,y-1) def main(): x = [int(x) for x in stdin.readline().strip(" ").split()] y = int(input()) print(rotation(x,y)) main()
6058618fbbf2007c45b019d103bb2ba2a34609d6
MatiwsxD/ayed-2019-1
/Labinfo_4/punto_2.py
468
3.546875
4
from sys import stdin def parejas(x): lista = [] for i in x: for j in range(len(x)): if i[0] == x[j][0] or i[0] == x[j][1] or x[1] == x[j][0] or x[1] == x[j][1] and i != x[j]: lista += x[j] return lista def main(): lista_1 = [] x = int(input()) for i in range(x): y = [int(x) for x in stdin.readline().strip(" ").split()] lista_1.append(y) print(parejas(lista_1)) main()