blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
3.06M
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
3.06M
59e910d6b0fd95ddd3da22bcff86fec7fe92f076
luhralive/python
/ailurus1991/0004/main.py
343
3.796875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- __author__ = 'jinyang' def calcWords(path): file = open(path, 'r') inputStr = file.read() wordsNum = 0 for i in inputStr: if i == ' ' or i == '\n': wordsNum += 1 file.close() print wordsNum + 1 if __name__ == '__main__': calcWords('input.txt')
59d383fce09fddcab3808941b2f1061bf3e596ab
luhralive/python
/BrambleXu/play1/play1.py
558
3.59375
4
# -*- coding:utf-8 -*- #**第 0001 题:**做为 Apple Store App 独立开发者,你要搞限时促销,为你的应用**生成激活码**(或者优惠券),使用 Python 如何生成 200 个激活码(或者优惠券)? import random, string def random_str(num, length = 7): f = open("Running_result.txt", 'wb') for i in range(num): chars = string.letters + string.digits s = [random.choice(chars) for i in range(length)] f.write(''.join(s) + '\n') f.close() if __name__ == '__main__': random_str(200)
33e9b3d3209477a2e24421803b26c9697b374d44
star10919/Keras_
/02_keras2/keras66_gradient1.py
312
3.71875
4
import numpy as np import matplotlib.pyplot as plt f = lambda x: x**2 - 4*x + 6 x = np.linspace(-1, 6, 100) # -1부터 6까지 100개의 데이터 # print(x) y = f(x) # 그리자!! plt.plot(x, y, 'k-') plt.plot(2, 2, 'sk') # 최솟점에 점 찍힘 plt.grid() plt.xlabel('x') plt.ylabel('y') plt.show()
d6a908a27dd70295ba986d4aed8dde9c20dfc03b
bryangreener/School
/Spring 2018/Python/Assignments/Assignment#6/hw#6PartI_BryanGreener.py
597
3.5
4
# Name: Bryan Greener # Date: 2018-04-11 # Homework : #6 Part 1 import csv def csvopen(file): with open(file, "r") as entries: for entry in csv.reader(entries): yield entry rownum = 0 #iterator for row number for i in csvopen('people.csv'): if rownum != 0: # If 0, skip header row first, last, age = i[0], i[1], int(i[2]) if(age%2): print('{0}: {1}, {2}'.format(rownum, last, first)) else: #Have to use last[1] since there is a space in the CSV print('{0}{1} is number {2}'.format(first[0], last[1], rownum)) rownum += 1
f454e3872e516ac64bb105063071ab7a23f119a6
bryangreener/School
/Spring 2018/Python/Assignments/Assignment#4/hw#4Greener.py
7,932
4.09375
4
#Name: Bryan Greener #Date: 2018-02-23 #Homework: 4 class Customer: def __init__(self): self.first_name = "" self.last_name = "" self.phone = 0 self.email = "" self.date = "" self.history = [] def __str__(self): output = "" output = (("\n%s, %s - Phone Number: %s - Email Address(es): %s - Date: %s - Purchase history: {") % (self.last_name, self.first_name, self.phone, self.email, self.date)) for i in customers_db: #get to searched customer then print history if(i.first_name == self.first_name and i.last_name == self.last_name): for j in i.history: output += str(j) + ", " output += "}\n" return output def add_contact(self): self.first_name = input("Enter customer's first name:\n") self.last_name = input("Enter customer's last name:\n") self.phone = input("Enter customer's phone no.:\n") self.email = input("Enter customer's email address(es):\n") self.date = input("Enter today date:\n") def look_contact(self, last_name): return class ItemToPurchase: def __init__(self): self.item_name = input("Enter the item name:\n") self.item_description = input("Enter the item description:\n") self.item_price = float(input("Enter the item price:\n")) self.item_quantity = int(input("Enter the item quantity:\n")) def __str__(self): return ("%s: %s") % (self.item_name, self.item_description) def print_item_cost(self): try: if(self.item_price <= 0): raise ValueError('Price cannot be <= 0.') #manually output error else: print(("%s %d @ $%f = $%f") % (self.item_name, self.item_quantity, self.item_price, (self.item_price * self.item_quantity))) except ValueError as e: print(e) class ShoppingCart: def __init__(self, customer_name="", current_date="", cart_items=[]): self.customer_name = customer_name self.current_date = current_date self.cart_items = cart_items def add_item(self, ItemToPurchase): self.cart_items.append(ItemToPurchase) def remove_item(self, ItemToRemove): try: for i in self.cart_items: #check for item in cart then remove if(i.item_name == ItemToRemove): self.cart_items.remove(i) return raise ValueError except ValueError: print("Item not found in cart. Nothing removed.") def modify_item(self, ItemToPurchase): try: for i in self.cart_items: if(i.item_name == ItemToPurchase): #check for item in cart then update quantity i.item_quantity = int(input("Enter the new quantity:\n")) return raise ValueError except ValueError: print("Item not found in cart. Nothing modified.") def return_item(self, Cust, ItemToRemove): try: for i in customers_db: if(i.first_name == Cust): for j in i.history: #check for item in history and remove it if(j.item_name == ItemToRemove): i.history.remove(j) print("The item is found and returned successfully") return raise ValueError except ValueError: print("The item is not found") def get_num_items_in_cart(self): total_items = 0 for i in self.cart_items: total_items += i.item_quantity return total_items def get_cost_of_cart(self): total_cost = 0.0 for i in self.cart_items: #accumulate cart item prices total_cost += (i.item_price * i.item_quantity) return total_cost def print_total(self): try: print("Total: $", ShoppingCart.get_cost_of_cart(self)) except ValueError: print("SHOPPING CART IS EMPTY.") def print_descriptions(self): for i in self.cart_items: print(i) #should use __str__ from ItemToPurchase def print_menu(): options = ['a','r','c','u','i','o','q'] #Used to easily validate input while(1): print( "\nMENU\n" "a - Add item to cart\n" "r - Remove item from cart\n" "c - Change item quantity\n" "u - Return items\n" "i - Output item descriptions\n" "o - Output shopping cart\n" "q - Quit\n") choice = input("\nChoose an option:\n") if(choice in options): return choice else: print("INVALID MENU OPTION") #Lists used to store customer and cart objects customers_db = [] shopping_cart = [] #Get number of users input try: num_customers = int(input("Enter the number of customers:\n")) except ValueError as e: print(e) for i in range(0, num_customers): #Get customer info for each customer customers_db.append(Customer()) print("Enter customer info. #%d" % (i + 1)) customers_db[i].add_contact() print(customers_db[i]) for i in range(0, num_customers): #Loop through menu for each customer print(("Customer name: %s %s") % (customers_db[i].first_name, customers_db[i].last_name)) print("Today's date:", customers_db[i].date) shopping_cart.append(ShoppingCart(customers_db[i].first_name, customers_db[i].date)) shopping_cart[i].cart_items = [] menu_choice = 'z' while(menu_choice != 'q'): #Keep looping through menu until user says to quit menu_choice = print_menu() if(menu_choice == 'a'): print("\nADD ITEM TO CART") ShoppingCart.add_item(shopping_cart[i], ItemToPurchase()) ShoppingCart.print_descriptions(shopping_cart[i]) elif(menu_choice == 'r'): print("\nREMOVE ITEM FROM CART") ShoppingCart.remove_item(shopping_cart[i], input("Enter name of item to remove:\n")) elif(menu_choice == 'c'): print("\nCHANGE ITEM QUANTITY") ShoppingCart.modify_item(shopping_cart[i], input("Enter the item name:\n")) elif(menu_choice == 'u'): print("\nRETURN ITEM") cnametoreturn = input("Enter the customer name:\n") for j in customers_db: #for each customer, check if at entered customer if(j.first_name == cnametoreturn): print(j) ShoppingCart.return_item(shopping_cart[i], cnametoreturn, input("Enter name of item to return:\n")) print(j) elif(menu_choice == 'i'): print(("\nOUTPUT ITEM'S DESCRIPTIONS" "%s %s's Shopping Cart - %s\n" "Item Descriptions\n") % (customers_db[i].first_name, customers_db[i].last_name, customers_db[i].date)) ShoppingCart.print_descriptions(shopping_cart[i]) elif(menu_choice == 'o'): print(("\nOUTPUT SHOPPING CART" "%s's Shopping Cart - %s\n" "Number of Items: %d\n") % (customers_db[i].first_name, shopping_cart[i].current_date, ShoppingCart.get_num_items_in_cart(shopping_cart[i]))) for j in shopping_cart[i].cart_items: #for each cart item, print item ItemToPurchase.print_item_cost(j) print("\n") ShoppingCart.print_total(shopping_cart[i]) elif(menu_choice == 'q'): for j in shopping_cart[i].cart_items: #add cart items to current user history customers_db[i].history.append(j)
231490f1ba7aa8be510830ec4a16568b5e4b2adb
THUEishin/Exercies-from-Hard-Way-Python
/exercise15/ex15.py
503
4.21875
4
''' This exercise is to read from .txt file Pay attention to the operations to a file Namely, close, read, readline, truncate, write(" "), seek(0) ''' from sys import argv script, filename = argv txt = open(filename) print(f"Here is your file {filename}") #readline() is to read a line from the file #strip(*) is to delete the character * at the beginning or end of the string line = txt.readline().strip(' ').strip('\n') while line: print(line) line = txt.readline().strip(' ').strip('\n')
d7bb8090a4e4af1cc2443a2cf81bbb22885b6c95
Hugo-Oh/study_DataStructure
/9012, 실버4, 괄호, DFS/AAA.py
326
3.53125
4
import sys sys.stdin=open("input.txt", "rt") N = int(input()) for _ in range(N): a = input() stack = [] #stack for i in a: if stack and stack[-1] == "(" and i == ")": stack.pop() else: stack.append(i) if stack: print("NO") else: print("YES")
b429ecbee6d9567020821e24134937bdb17100d9
Hugo-Oh/study_DataStructure
/캐치 파이썬스터디/배달, sUMMER/WINTER.py
912
3.546875
4
from collections import deque road = [[1,2,1],[2,3,3],[5,2,2],[1,4,2],[5,3,1],[5,4,2]] N = 5 K = 3 # 양방향 que = deque() dis = [21470000 for _ in range(N)] graph = [[0 for _ in range(N)] for _ in range(N)] que.append(0) #1번부터 시작 dis[0] = 0 for y, x, cost in road: if graph[y-1][x-1] == 0: graph[y-1][x-1] = cost graph[x-1][y-1] = cost else: graph[y-1][x-1] = min(graph[y-1][x-1], cost) graph[x-1][y-1] = min(graph[x-1][y-1], cost) for _ in graph: print(_) x def BFS(): while que: now = que.popleft() for next in range(N): #해당노드 if graph[now][next] != 0: #갈 길이 있다면 if dis[next] > dis[now] + graph[now][next]: dis[next] = dis[now] + graph[now][next] que.append(next) BFS() print(len([x for x in dis if x <= K])) # def BFS(): # while que:
16e30b0ff9c0b0dee4ddd0c9d075491b9de9f44b
Hugo-Oh/study_DataStructure
/1260, DFS_BFS, S2, BFS_DFS/AA.py
14,096
3.71875
4
"""price = [13, 15, 20, 100] cost = [13, 15, 15, 0] def solution(price, cost): price_maxx = 0 sales_maxx = 0 for price in prices: sales = sum([price-y for x, y in zip(prices, costs) if (x >= price) and (price > y)]) if sales_maxx < sales: sales_maxx = sales price_maxx = price return price_maxx if price_maxx > 0 else 0 print(solution(prices = price, costs = cost))""" X = 0 Y = 0 walkTime = 12 sneakTime = 25 min_time = 21470000 def dja(time, y, x): global X, Y, min_time if x == X and y == Y: if time < min_time: min_time = time return if sneakTime > 2 * walkTime: time = X * walkTime + Y * walkTime if time < min_time: min_time = time elif sneakTime < walkTime: pass elif sneakTime <= 2 * walkTime: time = min(X, Y) * sneakTime + abs(Y-X) * walkTime if time < min_time: min_time = time dja(0, 0, 0) print(min_time) """ 문제 3 문제 설명 엘보니아의 왕은 int width미터 * int length미터 넓이의 궁전에서 살고 있다. 그는 신하들을 진흙 위에 살고 있게 하였기 때문에 인기 있는 왕은 아니었다. 그는 방문자들이 그를 접견하기 위해 오래 걷게 만들고 싶어서 궁전을 나누고 싶어했다. 왕의 보안 고문은 나선형으로 나누자고 제안했다. 방문자는 남서쪽 모서리에서 입궁하여 동쪽으로 걷는다. 방문자 앞에 벽이 나타나면 왼쪽으로 방향을 바꾼다. 나선형 복도의 너비는 1미터이다. 아래 다이어그램은 나선형 길의 한 예제이다: 방문객은 a (남서쪽 모서리)에서 출발하여 알파벳 순서대로 x (왕좌)까지 이동한다. nmlkji oxwvuh pqrstg abcdef 왕은 궁전의 길을 새로 만들기 전에 그의 왕좌를 먼저 정확한 위치로 옮기고 싶어하기 때문에 나선형의 길이 어디서 끝날지 알아야 한다. 왕좌의 좌표를 두개의 정수로 리턴하시오. 남서쪽 모서리는 (0, 0)이고 남동쪽 모서리는 (width - 1, 0), 그리고 북동쪽 모서리는 (width - 1, length - 1)이다. 참고 / 제약 사항 width와 length는 둘 다 최소값 1, 최대값 5000의 범위를 가진다. 테스트 케이스 int width = 6 int length = 4리턴(정답): [1,2] 문제 내용에 언급된 예제이다. int width = 6 int length = 5리턴(정답): [3,2] int width = 1 int length = 11리턴(정답): [0,10] int width = 12 int length = 50리턴(정답): [5,6] int width = 50 int length = 50리턴(정답): [24,25]""" """ 문제 2 문제 설명 당신은 학교에서 집까지 도시를 거쳐 걸어가고 있다. 도시는 무한히 크며 모든 X값에는 수직 도로가 놓여있고 모든 Y에는 수평 도로가 놓여있다. 당신은 현재 (0, 0)에 있으며 (X, Y)에 있는 집에 가려고 한다. 집까지 가는 방법에는 두가지가 있다: 수평 혹은 수직으로 인접한 교차로를 거쳐 ( walkTime 초가 걸린다) 도로를 따라 걷는 것과 몰래 대각선으로 건너 ( sneakTime 초가 걸린다) 반대쪽 모서리로 가는 방법이 있다. 이미지에 나와있는 것처럼 걷거나 대각선을 가로지르는 8가지 방향 어느쪽으로도 가는 것이 가능하다 (예제 2번 참고). 집에 도착할 수 있는 최단 시간을 반환하여라. 명확한 이해를 위해 예제를 참고하여라. 참고 / 제약 사항 X는 0 이상, 1,000,000,000 이하이다. Y는 0 이상, 1,000,000,000 이하이다. walkTime은 1 이상, 10000 이하이다. sneakTime은 1 이상, 10000 이하이다. 테스트 케이스 X = 4 Y = 2 walkTime = 3 sneakTime = 10리턴(정답): 18 전혀 가로질러가지 않는 것이 가장 빠른 길이다. X = 4 Y = 2 walkTime = 3 sneakTime = 5리턴(정답): 16 가장 빨리 가는 방법은 두번 가로질러서 가는 길로서 경로는 다음과 같다: (0,0)->(1,0)->(2,1)->(3,1)->(4,2). 도합 가로지르는데 10초가 걸리고 걷는데 6초가 걸린다. X = 2 Y = 0 walkTime = 12 sneakTime = 10리턴(정답): 20 다음과 같은 경로를 택할 수 있다: (0,0)->(1,1)->(2,0). X = 1000000 Y = 1000000 walkTime = 1000 sneakTime = 1000리턴(정답): 1000000000 X = 0 Y = 0 walkTime = 12 sneakTime = 25리턴(정답): 0""" """문제1 설명 당신은 새 물건을 판매하기에 앞서 어떻게 하면 매출을 극대화할 수 있는지 알고 싶다. 물건의 최적의 가격을 정하는 것도 여러 전략 중 하나이다. 당신은 잠재적 고객들이 지출할 수 있는 제일 높은 가격을 적은 고객 목록을 만들었다. 당신은 또한 각 고객들에게 물건을 배송하기 위해 얼마의 비용이 필요한지 알고 있다. 배송 비용은 당신이 모두 부담해야되기 때문에 배송 비용이 너무 비싸다면 그 고객에게는 물건을 팔지 않을 수도 있다. 주어진 정수배열 price과 cost에는 각각 고객 i가 지출할 수 있는 제일 높은 가격과 배송 비용이 담겨 있다. 매출을 극대화할 수 있는 물건의 가격을 반환하여라. 최적의 가격이 2가지 이상 존재한다면 더 작은 가격을 리턴하시오. 이윤을 남길 수 없다면 0을 리턴하시오. 참고 / 제약 사항 price는 1개 이상, 50개 이하의 요소를 가지고 있다. price의 각 요소는 1 이상, 10^6 이하이다. cost는 price와 동일한 개수의 요소를 가지고 있다. cost의 각 요소는 0 이상, 10^6 이하이다. 테스트 케이스 price = [13,22,35] cost = [0,0,0]리턴(정답): 22 13원에 물건을 팔면 3명 모두 구입할 것이다: 매출: 3*13=39 22원에 물건을 팔면 2명만 구입할 것이다: 매출: 2*22=44 35원에 물건을 팔면 1명만 구입할 것이다: 매출: 1*35=35 그러므로 22가 최적의 가격이다. price = [13,22,35] cost = [5,15,30]리턴(정답): 13 13원에 물건을 팔면 3명 모두 구입하겠지만, 배송비를 고려하여 첫번째 고객에게만 물건을 팔 것이다: 매출: 13-5=8 22원에 물건을 팔면 2명이 구입하겠지만 배송비를 고려하여 두번째 고객에게만 물건을 팔 것이다: 매출: 22-15=7 35원에 물건을 팔면 1명만이 물건을 구입할 것이다: 매출: 35-30=5 그러므로 13이 최적의 가격이다. price = [13,22,35] cost = [15,30,40]리턴(정답): 0 배송비가 너무 비싸 누구에게도 팔 수 없으므로 0을 반환한다. price = [10,10,20,20,5] cost = [1,5,11,15,0]리턴(정답): 10 10원에 물건을 팔면 첫번째, 두번째 고객에게 물건을 팔고 14의 총 매출을 거둘 수 잇다. 20원에 물건을 팔면 세번째, 네번째 고객에세 물건을 팔고 14의 총 매출을 거둘 수 있다. 5원에 물건을 팔면 다섯번째 고객에게 물건을 팔고 5의 총 매출을 거둘 수 있다. 10과 20이 최적의 가격이므로 이 중에서 더 작은 10을 반환한다. price = [13,17,14,30,19,17,55,16] cost = [12,1,5,10,3,2,40,19]리턴(정답): 17""" """ 4/5 가방 퀴즈 시간 제한 : 2초메모리 제한 : 256MB 문제 설명 1부터 n까지 번호가 붙여진 n개의 가방이 있다. 각 가방은 다른 가방에 넣을 수 있으며, 다른 가방에 들어간 가방 역시 다른 가방을 넣고 있을 수 있다. 문제의 명확성을 위해 가방 i가 가방 j의 안에 있다는 것은 가방 i가 가방 j에 직접적으로 들어있음을 의미한다. 예를 들어서, 가방 2가 가방 1 안에 있고, 가방 3이 가방 2 안에 있으면, 가방 3은 가방 2 안에 있지만 가방 1 안에 있지는 않다. 모든 가방은 처음에 다 빈 채로 바닥에 놓여 있다. 우리는 다음에 나열되는 것들 중 하나의 행동을 각각 단계적으로 취할 것이다. PUT i INSIDE j - 가방 i를 가방 j안에 넣는다. 이 행동을 취하기 위해서는 가방 i와 j는 반드시 바닥에 놓여있어야 한다. SET i LOOSE - 가방 i안에 있는 모든 가방을 다시 꺼내서 바닥에 놓는다. 이 행동을 취하기 위해서는 가방 i는 반드시 바닥에 놓여 있어야 한다. SWAP i WITH j - 가방 i와 가방 j의 내용물을 서로 바꾼다 (다시 말하면, 가방 i의 모든 내용물을 꺼내서 가방 j에 넣고, 가방 j의 모든 내용물을 꺼내서 가방 i에 넣는다). 이 행동을 취하기 위해서는 가방 i와 j는 반드시 바닥에 놓여 있어야 한다. 가방들이 놓여진 마지막 상태에서 어떤 가방도 자기보다 더 작은 번호의 가방 안에 들어가 있지 않을 때, 이 상태를 적절하다고 말한다. 주어진 가방의 개수 int n과 취할 행동의 단계 vector<string> actions를 이용하여 마지막 상태가 적절한지 판단하여라. 만약 적절하다면 마지막 상태에 바닥에 놓인 가방의 개수를 반환하여라. 적절하지 않거나 어느 단계의 행동이 유효하지 않다면 -1을 반환하여라. 참고 / 제약 사항 n은 1 이상, 50 이하이다. actions는 0개 이상, 50개 이하의 요소를 가진다. actions의 각 요소는 "PUT i INSIDE j" (이 때, i와 j는 1부터 n사이의 서로 다른 두 정수이며 leading zero는 없다), 혹은 "SET i LOOSE" (이 때, i는 1부터 n사이의 정수이며 leading zero는 없다), 혹은 "SWAP i WITH j" (이 때, i와 j는 1부터 n사이의 서로 다른 두 정수이며 leading zero는 없다)와 같은 형태로 이루어지며 따옴표는 문자열에 포함되지 않는다. 테스트 케이스 int n = 2 vector<string> actions = ["PUT 1 INSIDE 2"]리턴(정답): 1 가방 1이 가방 2 안에 들어가 있으므로 적절한 상태이고 오직 하나의 가방만이 바닥에 놓여있다. int n = 2 vector<string> actions = ["PUT 1 INSIDE 2","SET 2 LOOSE"]리턴(정답): 2 처음 상태와 마지막 상태가 동일하게 된다. int n = 2 vector<string> actions = ["PUT 2 INSIDE 1"]리턴(정답): -1 가방 2가 가방 1 안에 들어가 있으므로, 더 적은 숫자의 가방 안에 들어가 있게 된다. 따라서 이 경우는 부적절한 상태이다. int n = 4 vector<string> actions = ["PUT 3 INSIDE 2","SWAP 4 WITH 2","PUT 2 INSIDE 4","SET 1 LOOSE"]리턴(정답): 2 int n = 3 vector<string> actions = ["PUT 1 INSIDE 2","PUT 3 INSIDE 1"]리턴(정답): -1 마지막 행동은 가방 1이 바닥에 놓여 있지 않으므로 유효하지 않다.""" """ 5/5 도로 건설 시간 제한 : 2초메모리 제한 : 256MB 문제 설명 오늘 시의회 회의에서 전문가들이 도시 내에 늘어나는 교통량에 대해 경고했다. 아마도 타조 협회에서 타조들의 대규모 이동 때문에 도시로 접근하는 도로를 차단한 것이 원인인 것 같았다. 불행히도 이 때문에 많은 차들이 고속도로에서 빠져나오지를 못하고 있다. 공사 인부들이 비상 대피로를 만들어 차들이 빠져나갈 수 있도록 하고 있지만 차가 빠져나가는 규칙이 없다면 혼란에 빠질 것이다. 편안히 운전할 수 있도록 돕기 위해서 다음과 같은 규칙을 실시하기로 했다: 같은 도로 상에서 앞에 차가 있다면 빠져나갈 수 없다. 낮은 차선에서 차가 빠져나가려고 하는 경우 빠져나갈 수 없다. 차가 가장 앞에 도착했을 때 높은 차선에 있는 차에게 (가능하다면) 정확히 한번 양보해야 한다. 이는 (만약 더 높은 차선에 차가 있다면) 더 높은 차선에 있는 차가 먼저 빠져나가도록 하는 것을 의미한다. 위의 조건을 모두 충족시켰다면, 차는 고속도로에서 빠져나갈 수 있다. 그 후에 같은 도로에 있는 뒤차가 (현재 차가 마지막 차가 아니라면) 도로의 가장 앞으로 나온다. 예를 들어서, 도로에 아래와 같이 다섯 개의 차량이 있다고 가정하자 (왼쪽이 차선의 가장 앞이다): 0 A B 1 C D 2 E A 차는 아직 양보하지 않았으며 먼저 양보해야 한다. C 차 역시 마찬가지이다. 더 높은 차선이 없는 E 차는 양보할 수 없으므로 먼저 빠져나간다. A 차는 한번 양보했으므로 빠져나갈 수 있다. B 차가 앞쪽으로 이동하지만 아직 양보하지 않았기 때문에 먼저 C 차에게 양보해야 한다. C 차가 빠져나가고 나서 B 차가 빠져나간다. 마지막으로 D 차가 빠져나간다. 문제에서는 vector<string> currentLanes가 주어진다. vector<string> currentLanes의 i번째 요소는 i차선에 있는 차들을 의미한다. 0번째 요소는 차선 가장 앞 쪽에 있는 차를 의미한다. vector<string> currentLanes에 있는 어떠한 차도 아직 다른 차에게 양보하지 않았다. 'D'로 표시된 차를 멀리서 온 다른 나라의 외교관이다. 외교관이 도착하기 전까지 얼마만큼의 시간이 남았는지 알기 위해서 외교관이 빠져나오기 위해서 몇 대의 차량이 먼저 빠져나가야 하는지 알고 싶다. 이 숫자를 반환하여라. 참고 / 제약 사항 currentLanes는 최소 1개, 최대 50개의 요소를 가지고 있다. currentLanes의 각 요소는 최소 1개, 최대 50개의 문자를 가지고 있다. currentlanes의 각 문자는 대문자이다 ('A'-'Z'). currentLanes에는 오직 한 개의 'D'가 있다. 테스트 케이스 vector<string> currentLanes = ["AB","CD","E"]리턴(정답): 4 문제 내용에 나온 예제이다. vector<string> currentLanes = ["AH","D","BCG","E","F"]리턴(정답): 2 F 차가 먼저 빠져나가고 나서 A 차가 빠져나간다. 그리고 나면 D 차가 빠져나갈 수 있다. vector<string> currentLanes = ["ABC","DEF"]리턴(정답): 0 하나의 알파벳으로 여러 개의 차량이 표현될 수 있다. 하지만 D는 오직 하나 뿐이다. vector<string> currentLanes = ["ABEDSCSMAN"]리턴(정답): 3 vector<string> currentLanes = ["AAA","A","AAA","A","AAD","A","AAB"]리턴(정답): 13 """ dja(0, 0, 0) print(min_time) def solution(X, Y, walkTime, sneakTime): return 0
50bfbf2caca5ce37fc342346e801519f1e4fa6e6
traffaillac/traf-kattis
/kafkaesque.py
124
3.515625
4
last = 0 rounds = 1 for _ in range(int(input())): clerk = int(input()) rounds += clerk < last last = clerk print(rounds)
350090f3b735d4c317e9160eef06298a7ebece31
traffaillac/traf-kattis
/flagquiz.py
312
3.59375
4
input() ans = [input().split(", ") for _ in range(int(input()))] def dist(a:list, b:list): return sum(i != j for i, j in zip(a, b)) def incongruousity(a:list): return max(dist(a, b) for b in ans if b != a) i = min(incongruousity(a) for a in ans) for a in ans: if incongruousity(a) == i: print(", ".join(a))
3a3218a2c96e4d4d9c959b912f5bdcfa61d70995
traffaillac/traf-kattis
/windows.py
2,974
3.5625
4
class Window: def __init__(self, x, y, X, Y): self.x = x self.y = y self.X = X self.Y = Y def __repr__(self): return f'{self.x} {self.y} {self.X-self.x} {self.Y-self.y}' def intersects(self, x, y, X, Y): return self.x<X and self.X>x and self.y<Y and self.Y>y xmax, ymax = (int(i) for i in input().split()) windows = [] # x1,y1,x2,y2 for i in range(1, 257): try: cmd, *args = input().split() except: break x, y = int(args[0]), int(args[1]) w = None if cmd == 'CLOSE' or cmd == 'RESIZE' or cmd == 'MOVE': try: w = next(w for w in windows if w.x<=x<w.X and w.y<=y<w.Y) x, y = w.x, w.y except: print(f'Command {i}: {cmd} - no window at given position') continue if cmd == 'OPEN' or cmd == 'RESIZE': X, Y = x+int(args[2]), y+int(args[3]) if X>xmax or Y>ymax or any(v!=w and v.intersects(x, y, X, Y) for v in windows): print(f'Command {i}: {cmd} - window does not fit') continue if cmd == 'OPEN': windows.append(Window(x, y, X, Y)) elif cmd == 'CLOSE': windows.remove(w) elif cmd == 'RESIZE': w.X, w.Y = X, Y elif cmd == 'MOVE': dx, dy = int(args[2]), int(args[3]) moving = {w} while dx > 0: move, bump = dx, None for w in windows: if w in moving: continue for m in moving: if 0<=w.x-m.X<move and w.Y>m.y and m.Y>w.y: move, bump = w.x-m.X, w X = max(m.X for m in moving) if X+move > xmax: print(f'Command {i}: {cmd} - moved {int(args[2])-(X+dx-xmax)} instead of {args[2]}') move = dx = xmax-X for m in moving: m.x += move m.X += move moving.add(bump) dx -= move while dx < 0: move, bump = dx, None for w in windows: if w in moving: continue for m in moving: if move<w.X-m.x<=0 and w.Y>m.y and m.Y>w.y: move, bump = w.X-m.x, w X = min(m.x for m in moving) if X+move < 0: print(f'Command {i}: {cmd} - moved {-int(args[2])+X+dx} instead of {-int(args[2])}') move = dx = -X for m in moving: m.x += move m.X += move moving.add(bump) dx -= move while dy > 0: move, bump = dy, None for w in windows: if w in moving: continue for m in moving: if 0<=w.y-m.Y<move and w.X>m.x and m.X>w.x: move, bump = w.y-m.Y, w Y = max(m.Y for m in moving) if Y+move > ymax: print(f'Command {i}: {cmd} - moved {int(args[3])-(Y+dy-ymax)} instead of {args[3]}') move = dy = ymax-Y for m in moving: m.y += move m.Y += move moving.add(bump) dy -= move while dy < 0: move, bump = dy, None for w in windows: if w in moving: continue for m in moving: if move<w.Y-m.y<=0 and w.X>m.x and m.X>w.x: move, bump = w.Y-m.y, w Y = min(m.y for m in moving) if Y+move < 0: print(f'Command {i}: {cmd} - moved {-int(args[3])+Y+dy} instead of {-int(args[3])}') move = dy = -Y for m in moving: m.y += move m.Y += move moving.add(bump) dy -= move print(f'{len(windows)} window(s):') for w in windows: print(w)
e26fc6f5f156320565aeae808b77a7a4dc187a81
traffaillac/traf-kattis
/greedilyincreasing.py
189
3.546875
4
N = int(input()) A = [int(i) for i in input().split()] gis = [A[0]] largest = A[0] for a in A: if a > largest: gis.append(a) largest = a print(len(gis)) print(' '.join(map(str, gis)))
d7163d8f0103969ae0bde1b5a78eec2de69ae2b9
traffaillac/traf-kattis
/fractalarea.py
181
3.640625
4
from math import pi for _ in range(int(input())): r, n = map(int, input().split()) area = pi * r * r inc = area for _ in range(1, n): area += inc inc *= 3 / 4 print(area)
2528414bb4d275a06a005c6916a34fb14d1044a8
traffaillac/traf-kattis
/estimatingtheareaofacircle.py
145
3.65625
4
from math import pi while True: r, m, c = input().split() if r==m==c=='0': break print(pi*float(r)**2, (float(r)*2)**2*int(c)/int(m))
6f6ee1e51869b660295e04630614abfc191d5ce3
traffaillac/traf-kattis
/stararrangements.py
132
3.71875
4
S = int(input()) print(f"{S}:") for l in range(S-1, 1, -1): q, r = divmod(S, l) if r==0 or r==(l+1)//2: print(f"{q+(r>0)},{q}")
7609faa9ce11e3c51897a1bf3f6af1d4555df6a6
traffaillac/traf-kattis
/hidden.py
228
3.625
4
password, string = input().split() pos = 0 for i, c in enumerate(string): idx = password.find(c, pos) if idx == pos: pos += 1 elif idx > pos: print("FAIL") break else: print("PASS" if pos == len(password) else "FAIL")
51e46ec32799eaabb5f3d4c38b7e42e8c25700a1
traffaillac/traf-kattis
/calculatingdartscores.py
502
3.515625
4
def valid(d): return 0<d<21 or d%2==0 and 0<d<41 or d%3==0 and 0<d<61 def output(*args): for d in args: if d%3 == 0: print("triple", d//3) elif d%2 == 0: print("double", d//2) else: print("single", d) exit() n = int(input()) for d in range(1, min(n+1, 61)): if not valid(d): continue if d == n: output(d) for e in range(1, min(n-d+1, 61)): if not valid(e): continue if d+e == n: output(d, e) f = n-d-e if valid(f): output(d, e, f) else: print("impossible")
f7e2f32b81397a04b68ba2f99421eb69e695198b
traffaillac/traf-kattis
/justaminute.py
152
3.53125
4
N = int(input()) m,s = 0,0 for _ in range(N): M,S = (int(i) for i in input().split()) m += M s += S print(s/m/60 if s/m>60 else "measurement error")
bfaff6249a671404ff2d7e6b70805617128a3ff2
traffaillac/traf-kattis
/warehouse.py
338
3.578125
4
from operator import itemgetter for t in range(int(input())): toys = {} for n in range(int(input())): name, num = input().split() toys[name] = toys.setdefault(name, 0) + int(num) items = sorted(toys.items(), key=lambda t: t[0]) items.sort(key=lambda t: t[1], reverse=True) print(len(items)) for i in items: print(i[0], i[1])
b1a178f88369e1944b141b40708c4c674ca81a4c
lakshman-battini/Examples-from-Spark-The-Definitive-Guide
/code/Ch6-Working_with_Different_Types_of_Data-I.py
8,588
3.65625
4
# Databricks notebook source # This notebook covers building expressions, which are the bread and butter of Spark’s structured operations. # We also review working with a variety of different kinds of data, including the following: # Booleans # Numbers # Strings # Dates and timestamps # Handling null # Complex types # User-defined functions # COMMAND ---------- # To begin, let’s read in the DataFrame from the retail-dateset that we’ll be using for this analysis: df = spark.read.format("csv")\ .option("header", "true")\ .option("inferSchema", "true")\ .load("dbfs:/data/retail-data/by-day/2010-12-01.csv") df.printSchema() df.createOrReplaceTempView("dfTable") # COMMAND ---------- # Converting to Spark Types # The 'lit' function, converts a type in another language to its correspnding Spark representation. from pyspark.sql.functions import lit df.select(lit(5), lit("five"), lit(5.0)).printSchema() # COMMAND ---------- # Booleans are essential when it comes to data analysis because they are the foundation for all filtering. # Boolean statements consist of four elements: and, or, true, and false. # These statements are often used as conditional requirements for when a row of data must either pass the test (evaluate to true) or else it will be filtered out. from pyspark.sql.functions import col df.where(col("InvoiceNo") != 536365)\ .select("InvoiceNo", "Description")\ .show(5) # Scala has some particular semantics regarding the use of == and ===. In Spark, if you want to filter by equality you should use === (equal) or =!= (not equal). You can also use the not function and the equalTo method. # COMMAND ---------- # Another option is to specify the predicate as an expression in a string. This is valid for Python or Scala. df.where("InvoiceNo = 536365").show(3, False) # df.where("InvoiceNo <> 536365").show(5, False) # COMMAND ---------- # Complex Boolean Statements from pyspark.sql.functions import instr # Defining the Price Filter based on Unit Price. priceFilter = col("UnitPrice") > 600 # instr locates the position of the Given String in the column. descripFilter = instr(df.Description, "POSTAGE") >= 1 # isin - A boolean expression that is evaluated to true if the value of this expression is contained by the evaluated values of the arguments. df.where(df.StockCode.isin("DOT")).where(priceFilter | descripFilter).show(3) # Corresponding SQL Statement: # SELECT * FROM dfTable WHERE StockCode in ("DOT") AND(UnitPrice > 600 OR instr(Description, "POSTAGE") >= 1) # COMMAND ---------- # One “gotcha” that can come up is if you’re working with null data when creating Boolean expressions. # If there is a null in your data, you’ll need to treat things a bit differently. Here’s how you can ensure that you perform a null-safe equivalence test: df.where(col("Description").eqNullSafe("hello")) # COMMAND ---------- # Working with numerical data types. # Let’s imagine that we found out that we mis-recorded the quantity in our retail dataset and the true quantity is equal to (the current quantity * the unit price)2 + 5 # We use pow function that raises a column to the expressed power: from pyspark.sql.functions import expr, pow # Expressing the equation using pow function. fabricatedQuantity = pow(col("Quantity") * col("UnitPrice"), 2) + 5 df.select("CustomerId", fabricatedQuantity.alias("realQuantity")).show(2) # COMMAND ---------- # The same expression can be expressed as SQL query. df.selectExpr( "CustomerId", "(POWER((Quantity * UnitPrice), 2.0) + 5) as realQuantity").show(2) # COMMAND ---------- # Rounding to the whole number. # By default, the round function rounds up if you’re exactly in between two numbers. You can round down by using the bround: from pyspark.sql.functions import lit, round, bround df.select(round(lit("2.5")), bround(lit("2.5"))).show(2) # COMMAND ---------- # Calculating the Correlation of two columns. from pyspark.sql.functions import corr # We can find correlation using df.stat (DataFrameStatFunctions). df.stat.corr("Quantity", "UnitPrice") # We can also find using corr function available in DataFrame. df.select(corr("Quantity", "UnitPrice")).show() # COMMAND ---------- # Compute summary statistics for a column or set of columns. We can use the describe method to achieve exactly this. # This will take all numeric columns and calculate the count, mean, standard deviation, min, and max. df.describe().show() # COMMAND ---------- # We can also find these statistics by computing them invidually. from pyspark.sql.functions import count, mean, stddev_pop, min, max # COMMAND ---------- # You also can use this to see a cross-tabulation or frequent item pairs (be careful, this output will be large and is omitted for this reason): df.stat.crosstab("StockCode", "Quantity").show() df.stat.freqItems(["StockCode", "Quantity"]).show() # COMMAND ---------- # we can also add a unique ID to each row by using the function monotonically_increasing_id. This function generates a unique value for each row, starting with 0: from pyspark.sql.functions import monotonically_increasing_id df.select(monotonically_increasing_id()).show(2) # COMMAND ---------- # Note: # There are also a number of more advanced tasks like bloom filtering and sketching algorithms available in the stat package. # Be sure to search the API documentation for more information and functions. # COMMAND ---------- # String manipulation shows up in nearly every data flow. # COMMAND ---------- # The initcap function will capitalize every word in a given string when that word is separated from another by a space. from pyspark.sql.functions import initcap df.select(initcap(col("Description"))).show(5) # COMMAND ---------- # You can cast strings in uppercase and lowercase, as well: from pyspark.sql.functions import lower, upper df.select(col("Description"), lower(col("Description")), upper(lower(col("Description")))).show(2) # COMMAND ---------- # Regular Expressions # Regular expressions give the user an ability to specify a set of rules to use to either extract values from a string or replace them with some other values. # Spark takes advantage of the complete power of Java regular expressions. # COMMAND ---------- # regexp_replace function to replace substitute color names in our description column: from pyspark.sql.functions import regexp_replace regex_string = "BLACK|WHITE|RED|GREEN|BLUE" df.select(col("Description"), regexp_replace(col("Description"), regex_string, "COLOR").alias("color_clean")).show(2, False) # COMMAND ---------- # Another task might be to replace given characters with other characters. Spark provides the translate function to replace these values. from pyspark.sql.functions import translate df.select(col("Description"), translate(col("Description"), "LEET", "1337")).show(2) # COMMAND ---------- # Using regex_extract we can pull the matching Strings from the column values. from pyspark.sql.functions import regexp_extract extract_str = "(BLACK|WHITE|RED|GREEN|BLUE)" df.select( regexp_extract(col("Description"), extract_str, 1).alias("color_clean"), col("Description")).show(2, False) # COMMAND ---------- # Contains function is to just simply check for the existence of the String in column value. from pyspark.sql.functions import instr containsBlack = instr(col("Description"), "BLACK") >= 1 containsWhite = instr(col("Description"), "WHITE") >= 1 df.withColumn("hasSimpleColor", containsBlack | containsWhite)\ .where("hasSimpleColor")\ .select("Description").show(3, False) # COMMAND ---------- # The above is just with 2 arguements, let's walk through some rigorous example. from pyspark.sql.functions import expr, locate # colors to be identified. simpleColors = ["black", "white", "red", "green", "blue"] # function to locate the color in column, if exists returns "is_color" value def color_locator(column, color_string): return locate(color_string.upper(), column)\ .cast("boolean")\ .alias("is_" + c) selectedColumns = [color_locator(df.Description, c) for c in simpleColors] selectedColumns.append(expr("*")) # has to a be Column type df.select(*selectedColumns).where(expr("is_white OR is_red"))\ .select("Description").show(3, False) # COMMAND ---------- # COMMAND ---------- # COMMAND ---------- # COMMAND ---------- # COMMAND ---------- # COMMAND ---------- # COMMAND ---------- # COMMAND ---------- # COMMAND ---------- # COMMAND ---------- # COMMAND ---------- # COMMAND ----------
1fbae5b6f69ff34a7849e3d0d1a227a5ffac2a81
ekim0188/theGrind2
/cleanDBaccess3.py
1,237
3.515625
4
#!/usr/bin/env python3 """ Created on Sun Oct 14 22:57:31 2018 @author: Mike Blake Script to interact with the database itself """ # import pymysql def readDB(msg = []): print(msg) ##READ INFO FROM A DATABASE### db = pymysql.connect('localhost', 'root', '[removed for security]', 'thegrind') cursor = db.cursor() #prepare sql query to retrieve a record from the db sql = "SELECT * FROM userinfo" try: # execute the sql command cursor.execute(sql) # fetch all rows in a list of lists results = cursor.fetchall() print(results) for row in results: idnum = row[0] username = row[1] email = row[2] password = row[3] achiev = row[4] if (msg[0] == username) and (msg[1] == password): del idnum, username, email, password print('SUCCESS: msg[0] is : ', msg[0], '\n', 'msg[1] is: ', msg[1]) return True else: print('FAIL: msg[0] is : ', msg[0], '\n', 'msg[1] is: ', msg[1]) continue except: pass # print("Error: Unable to fetch data, sorry.") #disconnect from server db.close()
6a4f8c8732b5e384c0da3a6f8c36f90d57a982fc
ElManous/PythonStuff
/PythonStuff/MinaTawfik_omis30_project_s2019/scraping2.py
5,171
3.515625
4
from lxml import html import requests import re import json # Call the link I want to scrape club_page = requests.get('https://www.premierleague.com/clubs') tree = html.fromstring(club_page.content) linkLocation = tree.cssselect('.indexItem') #Create an empty list for us to send each team's link to teamLinks = [] #For each link... for i in range(0,20): #...Find the page the link is going to... temp = linkLocation[i].attrib['href'] #...Add the link to the website domain... temp = "http://www.premierleague.com/" + temp #...Change the link text so that it points to the squad list, not the page overview... temp = temp.replace("overview", "squad") #...Add the finished link to our teamLinks list... teamLinks.append(temp) # create lists to differentiate the type of links playerLink1 = [] playerLink2 = [] # Download liverpool's team page squadPage = requests.get(teamLinks[9]) squadTree = html.fromstring(squadPage.content) # Extract the player links playerLocation = squadTree.cssselect('.playerOverviewCard') # For each player link within the team page.. for i in range(len(playerLocation)): # save the link, complete with domain.. playerLink1.append("http://www.premierleague.com/" + playerLocation[i].attrib['href']) # For the second link, change the page from player overview to stats playerLink2.append(playerLink1[i].replace("overview", "stats")) # create lists for each stat I want to scrape Name = [] Position = [] Apps = [] Goals = [] Assists = [] Passes = [] BCC = [] CleanSheets = [] GKSaves = [] Tackles = [] Ints = [] j=0 # use for loop to loop thru the stats page to attain the stats I want for i in range(len(playerLink2)): playerPage2 = requests.get(playerLink2[i]) playerTree2 = html.fromstring(playerPage2.content) # Player name tempName = str(playerTree2.cssselect('div.name')[0].text_content()) # assign the player position if(j<29): if (j<3): spot = "GK" elif (j<11 ): spot = "D" elif(j<21): spot = "M" else: spot = "F" j+=1 #print(j) Position.append(spot) # Appearances try: tempApps = playerTree2.cssselect('.statappearances')[0].text_content() tempApps = int(re.search(r'\d+', tempApps).group()) except IndexError: tempApps = 0 # Goals try: tempGoals = playerTree2.cssselect('.statgoals')[0].text_content() tempGoals= int(re.search(r'\d+', tempGoals).group()) except IndexError: tempGoals = 0 # Assists try: tempAssists = playerTree2.cssselect('.statgoal_assist')[0].text_content() tempAssists = int(re.search(r'\d+', tempAssists).group()) except IndexError: tempAssists = 0 # Passes try: tempPasses = playerTree2.cssselect('.stattotal_pass')[0].text_content() tempPasses = int(re.search(r'\d+', tempPasses).group()) except IndexError: tempPasses = 0 # Big chances created try: tempBCC = playerTree2.cssselect('.statbig_chance_created')[0].text_content() tempBCC = int(re.search(r'\d+', tempBCC).group()) except IndexError: tempBCC = 0 # Clean sheets try: tempCleanSheets = playerTree2.cssselect('.statclean_sheet')[0].text_content() tempCleanSheets = int(re.search(r'\d+', tempCleanSheets).group()) except IndexError: tempCleanSheets = 0 # GK Saves try: tempGksaves = playerTree2.cssselect('.statsaves')[0].text_content() tempGksaves = int(re.search(r'\d+', tempGksaves).group()) except IndexError: tempGksaves = 0 # Tackles try: tempTackles = playerTree2.cssselect('.stattotal_tackle')[0].text_content() tempTackles = int(re.search(r'\d+', tempTackles).group()) except IndexError: tempTackles = 0 # Interceptions try: tempInts = playerTree2.cssselect('.statinterception')[0].text_content() tempInts = int(re.search(r'\d+', tempInts).group()) except IndexError: tempInts = 0 # Append each player's stats to the lists I created earlier Name.append(tempName) Apps.append(tempApps) Goals.append(tempGoals) Assists.append(tempAssists) Passes.append(tempPasses) BCC.append(tempBCC) GKSaves.append(tempGksaves) CleanSheets.append(tempCleanSheets) Tackles.append(tempTackles) Ints.append(tempInts) data={} #create a dictionary for storing player info data['players']=[] #loop through players info and add their data to a specific entry in data for i in range(0,29): data['players'].append({ 'name':Name[i], 'position':Position[i], 'apps':Apps[i], 'goals':Goals[i], 'assists':Assists[i], 'passes':Passes[i], 'big chances created':BCC[i], 'cleansheets':CleanSheets[i], 'gksaves':GKSaves[i], 'tackles':Tackles[i], 'ints':Ints[i] }) #open file with JSON and dump data into output file with open('playerData.txt','w') as outfile: json.dump(data,outfile)
5cfafd423c1d2d315dadc17c6796ec3cc860dad4
aav789/pengyifan-leetcode
/src/main/python/pyleetcode/keyboard_row.py
1,302
4.4375
4
""" Given a List of words, return the words that can be typed using letters of alphabet on only one row's of American keyboard like the image below. Example 1: Input: ["Hello", "Alaska", "Dad", "Peace"] Output: ["Alaska", "Dad"] Note: - You may use one character in the keyboard more than once. - You may assume the input string will only contain letters of alphabet. """ def find_words(words): """ :type words: List[str] :rtype: List[str] """ keyboards = ['qwertyuiop', 'asdfghjkl', 'zxcvbnm',] out = [] for word in words: for row in keyboards: in_row = False not_in_row = False for c in word.lower(): if c in row: in_row = True else: not_in_row = True if in_row and not not_in_row: out.append(word) break return out def test_find_words(): input = ["Hello","Alaska","Dad","Peace"] expected = ["Alaska","Dad"] assert find_words(input) == expected input = ["asdfghjkl","qwertyuiop","zxcvbnm"] expected = ["asdfghjkl","qwertyuiop","zxcvbnm"] assert find_words(input) == expected if __name__ == '__main__': test_find_words()
98ca0cf6d09b777507091ea494f28f756f6ca1e1
aav789/pengyifan-leetcode
/src/main/python/pyleetcode/Reverse_Words_in_a_String_III.py
682
4.40625
4
""" Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order. Example 1: Input: "Let's take LeetCode contest" Output: "s'teL ekat edoCteeL tsetnoc" Note: In the string, each word is separated by single space and there will not be any extra space in the string. """ def reverseWords(s): """ :type s: str :rtype: str """ if not s: return s return ' '.join([w[::-1] for w in s.split(' ')]) def test_reverseWords(): assert reverseWords("Let's take LeetCode contest") == "s'teL ekat edoCteeL tsetnoc" if __name__ == '__main__': test_reverseWords()
ec00fc0c7a2c9628d55ca08364653a356ce4bfe4
aav789/pengyifan-leetcode
/src/main/python/pyleetcode/string-to-interger-atoi.py
3,195
4.34375
4
""" Implement atoi which converts a string to an integer. The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value. The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function. If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed. If no valid conversion could be performed, a zero value is returned. Note: Only the space character ' ' is considered as whitespace character. Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. If the numerical value is out of the range of representable values, INT_MAX (231 − 1) or INT_MIN (−231) is returned. Example 1: Input: "42" Output: 42 Example 2: Input: " -42" Output: -42 Explanation: The first non-whitespace character is '-', which is the minus sign. Then take as many numerical digits as possible, which gets 42. Example 3: Input: "4193 with words" Output: 4193 Explanation: Conversion stops at digit '3' as the next character is not a numerical digit. Example 4: Input: "words and 987" Output: 0 Explanation: The first non-whitespace character is 'w', which is not a numerical digit or a +/- sign. Therefore no valid conversion could be performed. Example 5: Input: "-91283472332" Output: -2147483648 Explanation: The number "-91283472332" is out of the range of a 32-bit signed integer. Thefore INT_MIN (−231) is returned. """ class Solution: def myAtoi(self, str: str) -> int: n = 0 neg = False state = 0 for c in str: if state == 0: if c == ' ': pass elif '0' <= c <= '9': n = 10*n + int(c) state = 1 elif c == '-': neg = True state = 1 elif c == '+': state = 1 else: break elif state == 1: if '0' <= c <= '9': n = 10*n + int(c) else: break if n != 0 and neg: n = -n n = max(n, -(2**31)) n = min(n, 2**31-1) print(n) return n def test_myAtoi(self): assert self.myAtoi('42') == 42 assert self.myAtoi(' -42') == -42 assert self.myAtoi('4193 with words') == 4193 assert self.myAtoi('words and 987') == 0 assert self.myAtoi('-91283472332') == -2147483648 assert self.myAtoi('+1') == 1 if __name__ == "__main__": s = Solution() s.test_myAtoi()
91e826ad0ea139bf3abe1a4889c86338f833edfa
Sandy134/FourthSem_Material
/Python_Lab/Termwork1b.py
1,068
4.1875
4
#11/5/2021 MAX = 3 def add(q, item): if len(q) == MAX: print("\nQueue Overflow") else: q.append(item) def delete(q): if len(q) == 0: return '#' else: return q.pop(0) def disp(q): if len(q) == 0: print("\nQueue is empty") return else: print("\nQueue Contents are :",q) def main(): queue = [] while True: print("\n1.add 2.Remove 3.Display 4.Exit") opt = int(input("Enter your option : ")) if opt == 1: item = input("Enter the item to be added to the queue : ") add(queue, item) elif opt == 2: item = delete(queue) if item == '#': print("\nQueue Underflow") else: print("\nItem Deleted") elif opt == 3: disp(queue) elif opt == 4: break else: print("\nPlease enter a valid option ") if __name__=='__main__': main()
7efd406c8661629efec66a1d88ccc1bb565941be
naijopkr/tic-tac-toe
/functions.py
1,795
3.78125
4
from sys import exit, platform from os import system def clear(): if platform == 'win32': system('cls') else: system('clear') def choose_name(player): return input(f'Hello, enter the name for player {player}: ') def enter_position(player, board_size): while True: try: position_str = input(f'{player}, enter a number from 1 to {board_size**2}: ') if position_str == 'q': exit(0) position = int(position_str) if position in range(1, board_size**2 + 1): break except ValueError: pass print('Invalid position, try again.') return position def enter_board_size(): while True: try: board_size = int(input('Enter the board size (min. 3): ')) if (board_size >= 3): break except: pass print('Invalid size, try another.') return board_size def check_win(positions_taken, row_taken, col_taken): last_index = len(positions_taken) - 1 row_win = len(set(positions_taken[row_taken])) == 1 col_win = len(set(row[col_taken] for row in positions_taken)) == 1 diagonal_win = False anti_diagonal_win = False if row_taken + col_taken == last_index or row_taken == col_taken: diagonal = set() anti_diagonal = set() for index in range(len(positions_taken)): row = positions_taken[index] diagonal.add(row[index]) anti_diagonal.add(row[last_index - index]) diagonal_win = len(diagonal) == 1 and min(diagonal) != 0 anti_diagonal_win = len(anti_diagonal) == 1 and min(anti_diagonal) != 0 return row_win or col_win or diagonal_win or anti_diagonal_win
2f839536c9011ef074e49ddd72e96d420e7b2099
Bl41r/code-katas
/forbes.py
1,542
3.921875
4
"""Forbes top 40. This savory chunk of code takes a provided json file, namely forbes_billionaires.json, and returns the oldest dude on the list under the age of 80, and the youngest member of the list. There are a few 'errors' in the json file, so only valid ages are considered. """ import json def oldrich_and_youngest(filename): """Return info for oldest under 80 and youngest billionaires.""" with open(filename) as json_data: data = json.load(json_data) init_dict_o = {'name': 'init', 'net_worth (USD)': 0, 'age': 0} init_dict_y = {'name': 'init', 'net_worth (USD)': 0, 'age': 80} return_dict = {'oldest': init_dict_o, 'youngest': init_dict_y} for entry in data: try: if entry['age'] < 1 or entry['age'] > 79: continue if entry['age'] > return_dict['oldest']['age']: return_dict['oldest'] = entry if entry['age'] < return_dict['youngest']['age']: return_dict['youngest'] = entry except KeyError: raise KeyError('There was a problem the data.') print(return_dict) return ((return_dict['oldest']['name'], return_dict['oldest']['net_worth (USD)'], return_dict['oldest']['source']), (return_dict['youngest']['name'], return_dict['youngest']['net_worth (USD)'], return_dict['youngest']['source'])) if __name__ == '__main__': # pragma: no cover print(oldrich_and_youngest('forbes_billionaires_2016.json'))
4ccf01874b1265abcb901ee7a0d6d23dfb64ed3f
Bl41r/code-katas
/credit-card-issuer-checking.py
573
3.640625
4
"""Code Wars Kata. https://www.codewars.com/kata/credit-card-issuer-checking """ def get_issuer(number): cc = str(number) if cc[0] == '4' and (len(cc) == 13 or len(cc) == 16) : return 'VISA' elif cc[0:4] == '6011' and len(cc) == 16: return 'Discover' elif (cc[0:2] == '34' or cc[0:2] == '37') and len(cc) == 15: return 'AMEX' elif (cc[0:2] == '51' or cc[0:2] == '52' or cc[0:2] == '53' or cc[0:2] == '54' or cc[0:2] == '55') and (len(cc) == 13 or len(cc) == 16): return 'Mastercard' else: return 'Unknown'
cbc03484b8f7179e775dff6c594d4aa28a177522
Bl41r/code-katas
/get-all-possible-anagrams-from-a-hash.py
619
3.9375
4
"""Code Wars Kata. https://www.codewars.com/kata/get-all-possible-anagrams-from-a-hash """ def anagrams(word): if len(word) < 2: yield word else: for i, letter in enumerate(word): if letter not in word[:i]: for j in anagrams(word[:i] + word[i + 1:]): yield j + letter def get_words(hash_of_letters): x = [] # put all letters in amounts to be used in a list that becomes joined for key in hash_of_letters: for letter in hash_of_letters[key]: x.append(letter * key) return sorted(list(anagrams(''.join(x))))
699e447a4545dd42bf8d7ac835608dd7aa978e57
erziebart/pykiddou
/src/value.py
1,350
4.0625
4
from abc import ABC, abstractmethod from dataclasses import dataclass class Value(ABC): """A value in the kiddou language.""" @abstractmethod def type_name(self) -> str: return self.__class__.__name__ @abstractmethod def stringify(self) -> str: return str(self) class Undef(Value): """A value representing undefined.""" def type_name(self) -> str: return super().type_name() def stringify(self) -> str: return "undef" @dataclass class Bool(Value): """A value representing a boolean.""" val: bool def type_name(self) -> str: return super().type_name() def stringify(self) -> str: return "true" if self.val else "false" @dataclass class Int(Value): """A value representing an integer.""" val: int def type_name(self) -> str: return super().type_name() def stringify(self) -> str: return str(self.val) @dataclass class Float(Value): """A value representing a floating-point number.""" val: float def type_name(self) -> str: return super().type_name() def stringify(self) -> str: return str(self.val) @dataclass class String(Value): """A value representing a string.""" val: str def type_name(self) -> str: return super().type_name() def stringify(self) -> str: return self.val
78e972f58f05adb457b4348172c000b7e46d7462
AI-Inspire/Code-for-Workshops-Spring-2018-PL
/Stastistics.py
519
3.96875
4
#STATISTICS number_of_laptops = [30, 40, 50, 60, 311, 23, 13] num_points = len(number_of_laptops) #number of data points, length largest_value = max(number_of_laptops) #largest value #sorting values sorted_values = sorted(number_of_laptops) smallest_value = sorted_values[0] second_smallest_value = sorted_values[1] third_largest_value = sorted_values[-3] print(sorted_values,"\n") print(smallest_value,"\n") print(second_smallest_value,"\n") print(third_largest_value,"\n") print(largest_value,"\n")
6520ca71378dbafd74eece20d613404d647d2d6a
moredhel/project_dolly
/src/server/user.py
439
3.828125
4
import database class User: db = database def __init__(self, name, email): self.name = name self.email = email self.computers = get_computers def user_creation(self, db): """user creation returns error string if unsuccessful""" if ((db.query("select '%s' from db") % (self.name)) != self.name): db.update("insert '%s") % (self.name) return null else: return "Name already exists!! Please input another name:"
1af36f5047e5ed15218cdc84f3b2bc9ea77bc57c
faridmaamri/PythonLearning
/PCAP_Lab Palindromes_method2.py
1,052
4.34375
4
""" EDUB_PCAP path: LAB 5.1.11.7 Plaindromes Do you know what a palindrome is? It's a word which look the same when read forward and backward. For example, "kayak" is a palindrome, while "loyal" is not. Your task is to write a program which: asks the user for some text; checks whether the entered text is a palindrome, and prints result. Note: - assume that an empty string isn't a palindrome; - treat upper- and lower-case letters as equal; - spaces are not taken into account during the check - treat them as non-existent; there are more than a few correct solutions - try to find more than one. """ ### Ask the user to enter the text or sentence text=input('Please enter the text to check : ') ##remove spaces and convert all caracters to lower case string=text.replace(' ','') string=string.lower() for i in range (len(string)): if string[-i-1]!=string[i]: print(i,(-i-1)) print('it\'s not a palindrome') break if i == (len(string)-1): print('it\'s a palindrome')
23658a3a61c3d99202f05925b331cb5e3e62cffc
fmsilver89/IN_5400
/Project1/dnn/main.py
23,095
3.578125
4
#:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::# # # # Part of mandatory assignment 1 in # # IN5400 - Machine Learning for Image analysis # # University of Oslo # # # # # # Ole-Johan Skrede olejohas at ifi dot uio dot no # # 2019.02.12 # # # #:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::# """ Main routine capable of training a dense neural network, and also running inference. This program builds an L-layer dense neural network. The number of nodes in each layer is set in the configuration. By default, every node has a ReLu activation, except the final layer, which has a softmax output. We use a cross-entropy loss for the cost function, and we use a stochastic gradient descent optimization routine to minimize the cost function. Custom configuration for experimentation is possible. """ import os import numpy as np import import_data import run import model import matplotlib.pyplot as plt plt.style.use('ggplot') def config(): """Return a dict of configuration settings used in the program""" conf = {} # Determine what dataset to run on. 'mnist', 'cifar10' and 'svhn' are currently supported. conf['dataset'] = 'mnist' # Relevant datasets will be put in the location data_root_dir/dataset. conf['data_root_dir'] = "/tmp/data" # Number of input nodes. This is determined by the dataset in runtime. conf['input_dimension'] = None # Number of hidden layers, with the number of nodes in each layer. conf['hidden_dimensions'] = [128, 32] # Number of classes. This is determined by the dataset in runtime. conf['output_dimension'] = None # This will be determined in runtime when input_dimension and output_dimension is set. conf['layer_dimensions'] = [784, 128, 32, 10] # Size of development partition of the training set conf['devel_size'] = 5000 # What activation function to use in the nodes in the hidden layers. conf['activation_function'] = 'relu' # The number of steps to run before termination of training. One step is one forward->backward # pass of a mini-batch conf['max_steps'] = 2000 # The batch size used in training. conf['batch_size'] = 128 # The step size used by the optimization routine. conf['learning_rate'] = 1.0e-2 # Whether or not to write certain things to stdout. conf['verbose'] = False # How often (in steps) to log the training progress. Prints to stdout if verbose = True. conf['train_progress'] = 10 # How often (in steps) to evaluate the method on the development partition. Prints to stdout # if verbose = True. conf['devel_progress'] = 100 return conf def plot_progress(train_progress, devel_progress, out_filename=None): """Plot a chart of the training progress""" fig, ax1 = plt.subplots(figsize=(8, 6), dpi=100) ax1.plot(train_progress['steps'], train_progress['ccr'], 'b', label='Training set ccr') ax1.plot(devel_progress['steps'], devel_progress['ccr'], 'r', label='Development set ccr') ax1.set_xlabel('Steps') ax1.set_ylabel('Correct classification rate') ax1.legend(loc='lower left', bbox_to_anchor=(0.6, 0.52), framealpha=1.0) ax2 = ax1.twinx() ax2.plot(train_progress['steps'], train_progress['cost'], 'g', label='Training set cost') ax2.set_ylabel('Cross entropy cost') gl2 = ax2.get_ygridlines() for gl in gl2: gl.set_linestyle(':') gl.set_color('k') ax2.legend(loc='lower left', bbox_to_anchor=(0.6, 0.45), framealpha=1.0) plt.title('Training progress') fig.tight_layout() if out_filename is not None: plt.savefig(out_filename) plt.show() def get_data(conf): """Return data to be used in this session. Args: conf: Configuration dictionary Returns: X_train: numpy array of floats with shape [input_dimension, num train examples] in [0, 1]. Y_train: numpy array of integers with shape [output_dimension, num train examples]. X_devel: numpy array of floats with shape [input_dimension, num devel examples] in [0, 1]. Y_devel: numpy array of integers with shape [output_dimension, num devel examples]. X_test: numpy array of floats with shape [input_dimension, num test examples] in [0, 1]. Y_test: numpy array of integers with shape [output_dimension, num test examples]. """ data_dir = os.path.join(conf['data_root_dir'], conf['dataset']) if conf['dataset'] == 'cifar10': conf['input_dimension'] = 32*32*3 conf['output_dimension'] = 10 X_train, Y_train, X_devel, Y_devel, X_test, Y_test = import_data.load_cifar10( data_dir, conf['devel_size']) elif conf['dataset'] == 'mnist': conf['input_dimension'] = 28*28*1 conf['output_dimension'] = 10 X_train, Y_train, X_devel, Y_devel, X_test, Y_test = import_data.load_mnist( data_dir, conf['devel_size']) elif conf['dataset'] == 'svhn': conf['input_dimension'] = 32*32*3 conf['output_dimension'] = 10 X_train, Y_train, X_devel, Y_devel, X_test, Y_test = import_data.load_svhn( data_dir, conf['devel_size']) conf['layer_dimensions'] = ([conf['input_dimension']] + conf['hidden_dimensions'] + [conf['output_dimension']]) if conf['verbose']: print("Train dataset:") print(" shape = {}, data type = {}, min val = {}, max val = {}".format(X_train.shape, X_train.dtype, np.min(X_train), np.max(X_train))) print("Development dataset:") print(" shape = {}, data type = {}, min val = {}, max val = {}".format(X_devel.shape, X_devel.dtype, np.min(X_devel), np.max(X_devel))) print("Test dataset:") print(" shape = {}, data type = {}, min val = {}, max val = {}".format(X_test.shape, X_test.dtype, np.min(X_test), np.max(X_test))) return X_train, Y_train, X_devel, Y_devel, X_test, Y_test def get_batch_indices(indices, start_index, end_index): """Return the indices of the examples that are to form a batch. This is done so that if end_index > len(example_indices), we will include the remainding indices, in addition to the first indices in the example_indices list. Args: indices: 1D numpy array of integers start_index: integer > 0 and smaller than len(example_indices) end_index: integer > start_index Returns: 1D numpy array of integers """ n = len(indices) return np.hstack((indices[start_index:min(n, end_index)], indices[0:max(end_index-n, 0)])) def evaluate(conf, params, X_data, Y_data): """Evaluate a trained model on X_data. Args: conf: Configuration dictionary params: Dictionary with parameters X_data: numpy array of floats with shape [input dimension, number of examples] Y_data: numpy array of integers with shape [output dimension, number of examples] Returns: num_correct_total: Integer num_examples_evaluated: Integer """ num_examples = X_data.shape[1] num_examples_evaluated = 0 num_correct_total = 0 start_ind = 0 end_ind = conf['batch_size'] while True: X_batch = X_data[:, start_ind: end_ind] Y_batch = model.one_hot(Y_data[start_ind: end_ind], conf['output_dimension']) Y_proposal, _ = model.forward(conf, X_batch, params, is_training=False) _, num_correct = model.cross_entropy_cost(Y_proposal, Y_batch) num_correct_total += num_correct num_examples_evaluated += end_ind - start_ind start_ind += conf['batch_size'] end_ind += conf['batch_size'] if end_ind >= num_examples: end_ind = num_examples if start_ind >= num_examples: break return num_correct_total, num_examples_evaluated def main_test(): print("----------START OF TESTS-----------") # Get configuration conf = config() ################################### Task 1.1: Parameter initialization from model import initialization params = initialization(conf) ################################### Task 1.2: Forward propagation # Import Activation functions [1.2a & 1.2b] from model import activation from model import softmax # Test Activation functions from tests import task_2a from tests import task_2b input_Z, expected_A = task_2a() A = activation(input_Z, 'relu') print('Activation valid?:',np.array_equal(expected_A, A)) input_Z, expected_S = task_2b() S = softmax(input_Z) print('Softmax valid?:',np.array_equal(np.round(expected_S,decimals=3), np.round(S,decimals=3))) # Import Forward propagation [1.2c] from model import forward from tests import task_2c ### Test Forward propagation conf, X_batch, params, expected_Z_1, expected_A_1, expected_Z_2, expected_Y_proposed = task_2c() Y_proposed, features = forward(conf, X_batch, params, is_training=True) print('feature Z_1 valid?:',np.array_equal(expected_Z_1, np.round(features['Z_1'],decimals=8))) print('feature A_1 valid?:',np.array_equal(expected_A_1, np.round(features['A_1'],decimals=8))) print('feature Z_2 valid?:',np.array_equal(expected_Z_2, np.round(features['Z_2'],decimals=8))) print('proposed Y valid?:',np.array_equal(expected_Y_proposed, np.round(Y_proposed,decimals=8))) ################################### Task 1.3: Cross Entropy cost function # Import Cost function from model import cross_entropy_cost from tests import task_3 ### Test Cost function Y_proposed, Y_batch, expected_cost_value, expected_num_correct = task_3() cost_value, num_correct = cross_entropy_cost(Y_proposed, Y_batch) print('Cost value valid?:',np.array_equal(np.round(expected_cost_value,decimals=4), np.round(cost_value,decimals=4))) print('Number of succesess valid?:',np.array_equal(expected_num_correct, np.round(num_correct,decimals=4))) ################################### Task 1.4: Backward propagation # Import Derivative of the activation function [1.4a] from model import activation_derivative from tests import task_4a # Test Derivative of activation input_Z, expected_dg_dz = task_4a() dg_dz = activation_derivative(input_Z, "relu") print('Derivative function valid?:',np.array_equal(expected_dg_dz, np.round(dg_dz,decimals=4))) # Import Backward propagation [1.4b] from model import backward from tests import task_4b # Test Backward propagation (conf, Y_proposed, Y_batch, params, features, expected_grad_W_1, expected_grad_b_1, expected_grad_W_2, expected_grad_b_2) = task_4b() grad_params = backward(conf, Y_proposed, Y_batch, params, features) print('Grad_W_1 valid?:',np.array_equal(np.round(expected_grad_W_1,decimals=4), np.round(grad_params["grad_W_1"],decimals=4))) print('Grad_b_1 valid?:',np.array_equal(np.round(expected_grad_b_1,decimals=4), np.round(grad_params["grad_b_1"][:, np.newaxis],decimals=4))) print('Grad_W_2 valid?:',np.array_equal(np.round(expected_grad_W_2,decimals=4), np.round(grad_params["grad_W_2"],decimals=4))) print('Grad_b_2 valid?:',np.array_equal(np.round(expected_grad_b_2,decimals=4), np.round(grad_params["grad_b_2"][:, np.newaxis],decimals=4))) ################################### Task 1.5: Update parameters # Import Update from model import gradient_descent_update from tests import task_5 # Test Update (conf, params, grad_params, expected_updated_W_1, expected_updated_b_1, expected_updated_W_2, expected_updated_b_2) = task_5() updated_params = gradient_descent_update(conf, params, grad_params) print('update of W_1 valid?:',np.array_equal(np.round(expected_updated_W_1,decimals=4), np.round(updated_params["W_1"],decimals=4))) print('update of b_1 valid?:',np.array_equal(np.round(expected_updated_b_1,decimals=4), np.round(updated_params["b_1"],decimals=4))) print('update of W_2 valid?:',np.array_equal(np.round(expected_updated_W_2,decimals=4), np.round(updated_params["W_2"],decimals=4))) print('update of b_2 valid?:',np.array_equal(np.round(expected_updated_b_2,decimals=4), np.round(updated_params["b_2"],decimals=4))) print("----------END OF TESTS-----------") def main_exceed(): """Run the program according to specified configurations.""" ################################### Task 1.6b: Exceed results conf = config() conf['dataset'] = 'mnist' # Dataset conf['max_steps'] = 5000 # Training steps conf['learning_rate'] = 1.0e-2*0.5 # Learning rate conf['hidden_dimensions'] = [128, 64, 32] # Hidden layers & Nodes conf['batch_size'] = 64 # Batch size conf['activation_function'] = 'sigmoid' # Hidden activation function print("----------START DNN ON: ",conf['dataset']) X_train, Y_train, X_devel, Y_devel, X_test, Y_test = get_data(conf) params, train_progress, devel_progress = run.train(conf, X_train, Y_train, X_devel, Y_devel) plot_progress(train_progress, devel_progress) print("Evaluating train set") num_correct, num_evaluated = run.evaluate(conf, params, X_train, Y_train) print("CCR = {0:>5} / {1:>5} = {2:>6.4f}".format(num_correct, num_evaluated, num_correct/num_evaluated)) print("Evaluating development set") num_correct, num_evaluated = run.evaluate(conf, params, X_devel, Y_devel) print("CCR = {0:>5} / {1:>5} = {2:>6.4f}".format(num_correct, num_evaluated, num_correct/num_evaluated)) print("Evaluating test set") num_correct, num_evaluated = run.evaluate(conf, params, X_test, Y_test) print("CCR = {0:>5} / {1:>5} = {2:>6.4f}".format(num_correct, num_evaluated, num_correct/num_evaluated)) print("----------END DNN ON: ",conf['dataset']) ################################### Task 1.6a: Reproduce results cifar10 conf = config() conf['dataset'] = 'cifar10' # Dataset conf['max_steps'] = 12000 # Training steps conf['learning_rate'] = 1.0e-2*4 # Learning rate conf['hidden_dimensions'] = [256, 128, 64, 32] # Hidden layers & Nodes conf['batch_size'] = 32 # Batch size conf['activation_function'] = 'tanh' # Hidden activation function print("----------START DNN ON: ",conf['dataset']) X_train, Y_train, X_devel, Y_devel, X_test, Y_test = get_data(conf) params, train_progress, devel_progress = run.train(conf, X_train, Y_train, X_devel, Y_devel) plot_progress(train_progress, devel_progress) print("Evaluating train set") num_correct, num_evaluated = run.evaluate(conf, params, X_train, Y_train) print("CCR = {0:>5} / {1:>5} = {2:>6.4f}".format(num_correct, num_evaluated, num_correct/num_evaluated)) print("Evaluating development set") num_correct, num_evaluated = run.evaluate(conf, params, X_devel, Y_devel) print("CCR = {0:>5} / {1:>5} = {2:>6.4f}".format(num_correct, num_evaluated, num_correct/num_evaluated)) print("Evaluating test set") num_correct, num_evaluated = run.evaluate(conf, params, X_test, Y_test) print("CCR = {0:>5} / {1:>5} = {2:>6.4f}".format(num_correct, num_evaluated, num_correct/num_evaluated)) print("----------END DNN ON: ",conf['dataset']) ################################### Task 1.6a: Reproduce results svhn conf = config() conf['dataset'] = 'svhn' # Dataset conf['max_steps'] = 12000 # Training steps conf['learning_rate'] = 1.0e-2*0.5 # Learning rate conf['hidden_dimensions'] = [256, 64, 32] # Hidden layers & Nodes conf['batch_size'] = 64 # Batch size conf['activation_function'] = 'sigmoid' # Hidden activation function print("----------START DNN ON: ",conf['dataset']) X_train, Y_train, X_devel, Y_devel, X_test, Y_test = get_data(conf) params, train_progress, devel_progress = run.train(conf, X_train, Y_train, X_devel, Y_devel) plot_progress(train_progress, devel_progress) print("Evaluating train set") num_correct, num_evaluated = run.evaluate(conf, params, X_train, Y_train) print("CCR = {0:>5} / {1:>5} = {2:>6.4f}".format(num_correct, num_evaluated, num_correct/num_evaluated)) print("Evaluating development set") num_correct, num_evaluated = run.evaluate(conf, params, X_devel, Y_devel) print("CCR = {0:>5} / {1:>5} = {2:>6.4f}".format(num_correct, num_evaluated, num_correct/num_evaluated)) print("Evaluating test set") num_correct, num_evaluated = run.evaluate(conf, params, X_test, Y_test) print("CCR = {0:>5} / {1:>5} = {2:>6.4f}".format(num_correct, num_evaluated, num_correct/num_evaluated)) print("----------END DNN ON: ",conf['dataset']) def main(): """Run the program according to specified configurations.""" ################################### Task 1.6a: Reproduce results mnist conf = config() conf['dataset'] = 'mnist' print("----------START DNN ON: ",conf['dataset']) X_train, Y_train, X_devel, Y_devel, X_test, Y_test = get_data(conf) params, train_progress, devel_progress = run.train(conf, X_train, Y_train, X_devel, Y_devel) plot_progress(train_progress, devel_progress) print("Evaluating train set") num_correct, num_evaluated = run.evaluate(conf, params, X_train, Y_train) print("CCR = {0:>5} / {1:>5} = {2:>6.4f}".format(num_correct, num_evaluated, num_correct/num_evaluated)) print("Evaluating development set") num_correct, num_evaluated = run.evaluate(conf, params, X_devel, Y_devel) print("CCR = {0:>5} / {1:>5} = {2:>6.4f}".format(num_correct, num_evaluated, num_correct/num_evaluated)) print("Evaluating test set") num_correct, num_evaluated = run.evaluate(conf, params, X_test, Y_test) print("CCR = {0:>5} / {1:>5} = {2:>6.4f}".format(num_correct, num_evaluated, num_correct/num_evaluated)) print("----------END DNN ON: ",conf['dataset']) ################################### Task 1.6a: Reproduce results cifar10 conf = config() conf['dataset'] = 'cifar10' conf['max_steps'] = 10000 print("----------START DNN ON: ",conf['dataset']) X_train, Y_train, X_devel, Y_devel, X_test, Y_test = get_data(conf) params, train_progress, devel_progress = run.train(conf, X_train, Y_train, X_devel, Y_devel) plot_progress(train_progress, devel_progress) print("Evaluating train set") num_correct, num_evaluated = run.evaluate(conf, params, X_train, Y_train) print("CCR = {0:>5} / {1:>5} = {2:>6.4f}".format(num_correct, num_evaluated, num_correct/num_evaluated)) print("Evaluating development set") num_correct, num_evaluated = run.evaluate(conf, params, X_devel, Y_devel) print("CCR = {0:>5} / {1:>5} = {2:>6.4f}".format(num_correct, num_evaluated, num_correct/num_evaluated)) print("Evaluating test set") num_correct, num_evaluated = run.evaluate(conf, params, X_test, Y_test) print("CCR = {0:>5} / {1:>5} = {2:>6.4f}".format(num_correct, num_evaluated, num_correct/num_evaluated)) print("----------END DNN ON: ",conf['dataset']) ################################### Task 1.6a: Reproduce results svhn conf = config() conf['dataset'] = 'svhn' conf['max_steps'] = 10000 print("----------START DNN ON: ",conf['dataset']) X_train, Y_train, X_devel, Y_devel, X_test, Y_test = get_data(conf) params, train_progress, devel_progress = run.train(conf, X_train, Y_train, X_devel, Y_devel) plot_progress(train_progress, devel_progress) print("Evaluating train set") num_correct, num_evaluated = run.evaluate(conf, params, X_train, Y_train) print("CCR = {0:>5} / {1:>5} = {2:>6.4f}".format(num_correct, num_evaluated, num_correct/num_evaluated)) print("Evaluating development set") num_correct, num_evaluated = run.evaluate(conf, params, X_devel, Y_devel) print("CCR = {0:>5} / {1:>5} = {2:>6.4f}".format(num_correct, num_evaluated, num_correct/num_evaluated)) print("Evaluating test set") num_correct, num_evaluated = run.evaluate(conf, params, X_test, Y_test) print("CCR = {0:>5} / {1:>5} = {2:>6.4f}".format(num_correct, num_evaluated, num_correct/num_evaluated)) print("----------END DNN ON: ",conf['dataset']) if __name__ == "__main__": main_test() # Task [1.1 -> 1.5] Benchmark against tests main() # Task 1.6a Run datasets for reproduction main_exceed() # Task 1.6b Run datasets for improvement
3bfc4eee9efa7d88b031271d9f474e3dc4c5d5f4
b64-vishal/python-lab
/aphabets_count.py
353
3.96875
4
ch=input("enter the string") alphabet=digit=special=space=0 for i in range(len(ch)): if(ch[i].isalpha()): alphabet+=1 elif(ch[i].isdigit()): digit+=1 else: special+=1 print("total number of aphabet :" ,alphabet) print("totsl number of digit :", digit) print("total number of special character :",special)
99b26d6675d16b87d6eb0295ffb1ac8b1507b958
mikeleppane/Advent_of_Code
/2018/Day_5/solution_part1.py
1,182
3.8125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import sys from collections import deque INPUT_FILE = "input.txt" def scan_polymer(polymer: str): while True: indices_to_be_removed = set() found = False for index in range(len(polymer) - 1): if (polymer[index].isupper() and polymer[index + 1].islower()) or ( polymer[index].islower() and polymer[index + 1].isupper() ): if polymer[index].lower() == polymer[index + 1].lower(): found = True indices_to_be_removed.add(index) indices_to_be_removed.add(index + 1) polymer = polymer.replace(polymer[index] + polymer[index + 1], "") break if not found: break print("".join(polymer)) print(len(polymer)) def read_polymer() -> str: polymer = "" with open(INPUT_FILE, "r") as f_handle: for line in f_handle: if line: polymer += line.rstrip() return polymer def main(): polymer = read_polymer() scan_polymer(polymer) if __name__ == "__main__": sys.exit(main())
0723dc096c41ef7f503e45b99c848d7293abad5e
mikeleppane/Advent_of_Code
/2018/Day_15/solution_part1.py
9,326
3.609375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from dataclasses import dataclass from enum import IntEnum, Enum import sys from collections import Counter from itertools import product from typing import NamedTuple, Dict, Tuple, Union from copy import deepcopy from pprint import PrettyPrinter INPUT_FILE = "input.txt" ELF, GOBLIN, WALL, OPEN_CAVERN = ("elf", "goblin", "#", ".") pp = PrettyPrinter(indent=4) class AreaType(Enum): WALL = "#" OPEN_CAVERN = "." class Coordinate(NamedTuple): x: int y: int class Area(NamedTuple): type: str = "" @dataclass class Elf: name: str = ELF is_attacking: bool = False attack_power: int = 3 hit_points: int = 200 @dataclass class Goblin: name: str = GOBLIN is_attacking: bool = False attack_power: int = 3 hit_points: int = 200 visited_points = set() travel_distances = {} # Counter() directions = [(0, -1), (1, 0), (0, 1), (-1, 0)] def start_combat( area: Dict[Coordinate, Area], units: Dict[Coordinate, Union[Elf, Goblin]] ): round = 0 while True: for starting_coordinate, unit in sorted( units.items(), key=lambda item: (item[0][1], item[0][0]) ): print(round) new_places = {} if isinstance(unit, Goblin): targets = { coordinate: unit2 for coordinate, unit2 in units.items() if isinstance(unit2, Elf) and unit2.hit_points > 0 } else: targets = { coordinate: unit2 for coordinate, unit2 in units.items() if isinstance(unit2, Goblin) and unit2.hit_points > 0 } if not targets: print(round) for key, value in units.items(): if unit.name == value.name: print(value.hit_points) return in_range_enemies = [] for end_coordinate, target in targets.items(): in_range_points = [] for direction in directions: next_point = tuple(sum(x) for x in zip(end_coordinate, direction)) if next_point in area: in_range_points.append(next_point) if in_range_points and starting_coordinate in in_range_points: in_range_enemies.append((end_coordinate, target)) if in_range_enemies: unit.is_attacking = True else: unit.is_attacking = False travel_distances.clear() rr = None if not unit.is_attacking: for end_coordinate, elf in targets.items(): in_range_poins = [] for direction in directions: next_point = tuple( sum(x) for x in zip(end_coordinate, direction) ) if next_point in area and area[next_point].type == OPEN_CAVERN: in_range_poins.append(next_point) if in_range_poins and starting_coordinate not in in_range_poins: for in_range_point in in_range_poins: for direction in directions: visited_points.clear() seen.clear() next_dir = tuple( sum(x) for x in zip(starting_coordinate, direction) ) if ( next_dir in area and area[next_dir].type == OPEN_CAVERN ): visited_points.add(starting_coordinate) visited_points.add(next_dir) #print(starting_coordinate, next_dir, in_range_point, area[in_range_point]) found = walk(next_dir, in_range_point, area) if found: travel_distances[ (next_dir, in_range_point) ] = len(visited_points) - 1 if travel_distances: min_distance = min(travel_distances.values()) possible_distances = { coordinates: distance for coordinates, distance in travel_distances.items() if distance == min_distance } new_point = sorted( possible_distances.items(), key=lambda item: (item[0][0][1], item[0][0][0]), )[0][0][0] if (new_point, starting_coordinate) not in new_places: if min_distance == 1: unit.frozen = True new_places[(new_point, starting_coordinate)] = unit for places, unit in new_places.items(): rr = places[0] units[places[0]] = unit del units[starting_coordinate] area[places[0]] = Area(type=unit.name) if area[starting_coordinate].type != unit.name: area[starting_coordinate] = Area(type=OPEN_CAVERN) if isinstance(unit, Goblin): targets = { coordinate: unit2 for coordinate, unit2 in units.items() if isinstance(unit2, Elf) and unit2.hit_points > 0 } else: targets = { coordinate: unit2 for coordinate, unit2 in units.items() if isinstance(unit2, Goblin) and unit2.hit_points > 0 } in_range_enemies = [] ee = starting_coordinate if rr: ee = rr for end_coordinate, target in targets.items(): in_range_points = [] for direction in directions: next_point = tuple(sum(x) for x in zip(end_coordinate, direction)) if next_point in area: in_range_points.append(next_point) if in_range_points and ee in in_range_points: in_range_enemies.append((end_coordinate, target)) if in_range_enemies: lowest_hit_point = min(e.hit_points for c, e in in_range_enemies) in_range_enemies = [ (c, e) for c, e in in_range_enemies if e.hit_points == lowest_hit_point ] target_coordinate, enemy = sorted( in_range_enemies, key=lambda x: (x[0][1], x[0][0]) )[0] enemy.hit_points -= 3 if enemy.hit_points < 0: enemy.hit_points = 0 area[target_coordinate] = Area(type=OPEN_CAVERN) units = { starting_coordinate: unit for starting_coordinate, unit in units.items() if unit.hit_points > 0 } #if round == 2: # print() # pp.pprint(units) # return round += 1 def manhattan(p1, p2): return abs(p1[0] - p2[0]) + abs(p1[1] - p2[1]) seen = set() def walk(start: Coordinate, end: Coordinate, area: Dict[Coordinate, Area]): if start == end: return True new_dirs = {} for direction in directions: next_dir = tuple(sum(x) for x in zip(start, direction)) if ( next_dir in area and area[next_dir].type != WALL and next_dir not in visited_points and next_dir not in seen ): new_dirs[next_dir] = manhattan(next_dir, end) if not new_dirs: seen.add(start) #visited_points.remove(start) return False new_dirs = dict(sorted(new_dirs.items(), key=lambda item: item[1])) for next_dir in new_dirs.keys(): visited_points.add(next_dir) found = walk(next_dir, end, area) if found: return True else: seen.add(next_dir) #visited_points.remove(next_dir) return False def scan_area() -> Tuple: area = {} units = {} with open(INPUT_FILE, "r") as f_handle: for y, line in enumerate(f_handle): line = line.rstrip("\n") if line: for x, area_type in enumerate(line): if area_type in ("G", "E"): if area_type == "G": units[Coordinate(x=x, y=y)] = Goblin() else: units[Coordinate(x=x, y=y)] = Elf() area[Coordinate(x=x, y=y)] = Area(type=area_type) return area, units def main(): area, units = scan_area() #walk(start=(11,11),end=(27,18),area=area) start_combat(area, units) if __name__ == "__main__": sys.exit(main())
f0290af4261bdb25a9c093e1041d550d09a4664c
mikeleppane/Advent_of_Code
/2021/Solutions/Day-12/solution_p2.py
2,513
3.8125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from collections import Counter import sys from pprint import PrettyPrinter from typing import List, Set, Tuple custom_printer = PrettyPrinter( indent=4, width=100, depth=2, compact=True, sort_dicts=False, underscore_numbers=True, ) INPUT_FILE = "test_input_3.txt" def read_map() -> List[List[str]]: caves: List[List[str]] = [] with open(INPUT_FILE, "r", encoding="utf-8") as f_handle: for line in f_handle: line = line.rstrip() if line: caves.append(line.split("-")) return caves def contain_twice_visited_small_cave(path: List[str]) -> bool: return Counter([char for char in path if char.islower()]).most_common(1)[0][1] > 1 def should_append_next_cave(next_cave: str, path: List[str]) -> bool: if next_cave != path[-1]: if next_cave.islower(): if path.count(next_cave) == 0: return True if path.count(next_cave) == 1 and not contain_twice_visited_small_cave( path ): return True if next_cave.isupper(): return True return False def find_distinct_paths( name, caves: List[List[str]], path: List[str], paths: Set[Tuple[str, ...]] ): for cave in caves: if name in cave: next_cave = get_next_cave(name, cave) if next_cave == "end": new_path: Tuple[str, ...] = (*path, "end") if new_path not in paths: paths.add(new_path) elif should_append_next_cave(next_cave, path): path.append(next_cave) find_distinct_paths(next_cave, caves, path, paths) if len(path) > 2: path.pop() def get_next_cave(name, cave: List[str]) -> str: next_index = 1 if cave.index(name) == 0 else 0 return cave[next_index] def solve() -> int: caves = read_map() start_caves = [cave for cave in caves if "start" in cave] other_caves = [cave for cave in caves if "start" not in cave] paths: Set[Tuple[str, ...]] = set() for start_cave in start_caves: path: List[str] = ["start"] next_cave = get_next_cave("start", start_cave) path.append(next_cave) find_distinct_paths(next_cave, other_caves, path, paths) return len(paths) def main(): number_of_paths = solve() print(f"Result: {number_of_paths}") if __name__ == "__main__": sys.exit(main())
373762827d80124fd528f21e1e67261addaff6ab
mikeleppane/Advent_of_Code
/2019/Day_1/solution_part1.py
481
3.71875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import sys import math INPUT_FILE = "input.txt" inputs = [] def read_inputs(): with open(INPUT_FILE, "r") as f_handle: for line in f_handle: inputs.append(int(line.strip())) def calculate_total_fuel_consumption(): return sum(math.floor(mass / 3.0) - 2 for mass in inputs) def main(): read_inputs() print(calculate_total_fuel_consumption()) if __name__ == "__main__": sys.exit(main())
7b08e1891542f11851fb78919915c7ed7e80d4ea
mikeleppane/Advent_of_Code
/2019/Day_1/solution_part2.py
803
3.6875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import sys import math INPUT_FILE = "input.txt" inputs = [] def read_inputs(): with open(INPUT_FILE, "r") as f_handle: for line in f_handle: inputs.append(int(line.strip())) def calculate_total_fuel_required_for_module(module_mass): total_fuel = 0 while True: module_mass = math.floor(module_mass / 3.0) if module_mass == 0 or (module_mass - 2) <= 0: break module_mass -= 2 total_fuel += module_mass return total_fuel def calculate_total_fuel_consumption(): return sum(calculate_total_fuel_required_for_module(mass) for mass in inputs) def main(): read_inputs() print(calculate_total_fuel_consumption()) if __name__ == "__main__": sys.exit(main())
46c7dc2ae604d10cd4849834b6b1f087f54b7978
mikeleppane/Advent_of_Code
/2020/Day_12/solution_part1.py
6,940
3.765625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from dataclasses import dataclass from enum import Enum from itertools import cycle import re import sys from typing import List INPUT_FILE = "input.txt" class Direction(Enum): NORTH = "N" SOUTH = "S" EAST = "E" WEST = "W" LEFT = "L" RIGHT = "R" FORWARD = "F" @dataclass(eq=True) class CurrentPosition: previous_direction: Direction = Direction.EAST direction: Direction = Direction.EAST NS: Direction = Direction.NORTH NS_value: int = 0 EW: Direction = Direction.EAST EW_value: int = 0 @dataclass(frozen=True, eq=True) class NavInstruction: action: Direction value: int def get_new_direction( current_direction: Direction, nav_instruction: NavInstruction ) -> Direction: directions = { 0: Direction.NORTH, 1: Direction.EAST, 2: Direction.SOUTH, 3: Direction.WEST, } current_direction_value = 0 for key, value in directions.items(): if value == current_direction: current_direction_value = key break if nav_instruction.value == 90 and nav_instruction.action == Direction.RIGHT: new_value = current_direction_value + 1 if new_value > 3: new_value = 0 return directions[new_value] if nav_instruction.value == 90 and nav_instruction.action == Direction.LEFT: new_value = current_direction_value - 1 if new_value < 0: new_value = 3 return directions[new_value] if nav_instruction.value == 180 and nav_instruction.action in ( Direction.RIGHT, Direction.LEFT, ): if current_direction == Direction.EAST: return directions[3] new_value = abs(current_direction_value - 2) return directions[new_value] if nav_instruction.value == 270 and nav_instruction.action == Direction.RIGHT: if current_direction == Direction.NORTH: return directions[3] if current_direction == Direction.EAST: return directions[0] if current_direction == Direction.SOUTH: return directions[1] if current_direction == Direction.WEST: return directions[2] if nav_instruction.value == 270 and nav_instruction.action == Direction.LEFT: if current_direction == Direction.NORTH: return directions[1] if current_direction == Direction.EAST: return directions[2] if current_direction == Direction.SOUTH: return directions[3] if current_direction == Direction.WEST: return directions[0] def handle_navigation_instruction( current_position: CurrentPosition, nav_instruction: NavInstruction ): if nav_instruction.action == Direction.NORTH: if current_position.NS == Direction.SOUTH: value = current_position.NS_value - nav_instruction.value if value < 0: current_position.NS = Direction.NORTH current_position.NS_value = abs(value) else: current_position.NS_value += nav_instruction.value elif nav_instruction.action == Direction.SOUTH: if current_position.NS == Direction.NORTH: value = current_position.NS_value - nav_instruction.value if value < 0: current_position.NS = Direction.SOUTH current_position.NS_value = abs(value) else: current_position.NS_value += nav_instruction.value elif nav_instruction.action == Direction.EAST: if current_position.EW == Direction.WEST: value = current_position.EW_value - nav_instruction.value if value < 0: current_position.EW = Direction.EAST current_position.EW_value = abs(value) else: current_position.EW_value += nav_instruction.value elif nav_instruction.action == Direction.WEST: if current_position.EW == Direction.EAST: value = current_position.EW_value - nav_instruction.value if value < 0: current_position.EW = Direction.WEST current_position.EW_value = abs(value) else: current_position.EW_value += nav_instruction.value elif nav_instruction.action == Direction.FORWARD: if current_position.direction in (Direction.NORTH, Direction.SOUTH): if current_position.direction != current_position.NS: value = current_position.NS_value - nav_instruction.value if value < 0: if current_position.NS == Direction.NORTH: current_position.NS = Direction.SOUTH elif current_position.NS == Direction.SOUTH: current_position.NS = Direction.NORTH current_position.NS_value = abs(value) else: current_position.NS_value += nav_instruction.value if current_position.direction in (Direction.EAST, Direction.WEST): if current_position.direction != current_position.EW: value = current_position.EW_value - nav_instruction.value if value <= 0: if current_position.EW == Direction.WEST: current_position.EW = Direction.EAST elif current_position.EW == Direction.EAST: current_position.EW = Direction.WEST current_position.EW_value = abs(value) else: current_position.EW_value += nav_instruction.value elif nav_instruction.action in (Direction.RIGHT, Direction.LEFT): current_position.previous_direction = current_position.direction current_position.direction = get_new_direction( current_position.direction, nav_instruction ) print(current_position) def start_navigation(navigation_instructions: List[NavInstruction]): current_position = CurrentPosition() for nav_instruction in navigation_instructions: handle_navigation_instruction(current_position, nav_instruction) print( f"Manhattan distance: {current_position.NS_value + current_position.EW_value}" ) def read_navigation_instructions() -> List[NavInstruction]: nav_instructions = list() nav_instruction_regex = re.compile(r"(\w)(\d{1,3})") with open(INPUT_FILE, "r") as f_handle: for line in f_handle: if line: if match := nav_instruction_regex.match(line.rstrip()): action, value = match.groups() nav_instructions.append( NavInstruction(action=Direction(action), value=int(value)) ) return nav_instructions def main(): nav_instructions = read_navigation_instructions() start_navigation(nav_instructions) if __name__ == "__main__": sys.exit(main())
bf28365b1f0dd24a1801e9c35c19febeef8bd8f1
mikeleppane/Advent_of_Code
/2020/Day_5/solution_part2.py
2,499
3.625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from dataclasses import dataclass import math import sys from typing import List, Set, Optional INPUT_FILE = "input.txt" UPPER_ROW_HALF, LOWER_ROW_HALF = ("B", "F") UPPER_COLUMN_HALF, LOWER_COLUMN_HALF = ("R", "L") @dataclass(frozen=True, eq=True) class BoardingPass: seat_id: str def find_row_index(seat_id: str) -> int: row_range = range(1, 127) return find_index(row_range, seat_id) def find_column_index(seat_id: str) -> int: row_range = range(0, 8) return find_index(row_range, seat_id) def find_index(array: range, ids: str) -> int: mid_point = 0 for half in ids: try: mid_point = range_mid_point(array, half) if half in (UPPER_ROW_HALF, UPPER_COLUMN_HALF): array = array[mid_point:] if half in (LOWER_ROW_HALF, LOWER_COLUMN_HALF): array = array[: mid_point + 1] except IndexError as e: print(e) if len(array) == 1: return array[0] return array[mid_point] def range_mid_point(array: range, part: str) -> int: try: if part in (LOWER_ROW_HALF, LOWER_COLUMN_HALF): return math.floor((array[-1] - array[0]) / 2) if part in (UPPER_ROW_HALF, UPPER_COLUMN_HALF): return math.ceil((array[-1] - array[0]) / 2) except IndexError as e: print(e) raise IndexError from e return -1 def read_boarding_passes() -> Set[BoardingPass]: boarding_passes = set() with open(INPUT_FILE, "r") as f_handle: for line in f_handle: if line: boarding_passes.add(BoardingPass(seat_id=line.rstrip())) return boarding_passes def get_seat_ids(boarding_passes: Set[BoardingPass]) -> Set[int]: ids = set() for boarding_pass in boarding_passes: row_id = boarding_pass.seat_id[:-3] column_id = boarding_pass.seat_id[-3:] row_number = find_row_index(row_id) column_number = find_column_index(column_id) ids.add(row_number * 8 + column_number) return ids def find_user_id(ids: Set[int]) -> int: ids_ordered: List[int] = sorted(ids) for id_low, id_high in zip(ids_ordered[:-1], ids_ordered[1:]): if id_high - id_low > 1: return id_low + 1 return -1 def main(): boarding_passes = read_boarding_passes() ids = get_seat_ids(boarding_passes) print(find_user_id(ids)) if __name__ == "__main__": sys.exit(main())
bc99f279e82adaead3c0900f07dc16607da095ba
mikeleppane/Advent_of_Code
/2019/Day_6/solution_part2.py
4,094
3.875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import sys from collections import deque from typing import Deque, List, NamedTuple INPUT_FILE = "input.txt" class OrbitObject: def __init__(self, name, orbits_around): self.name = name self.orbits_around = orbits_around def __str__(self): return f"{self.orbits_around} orbits directly around {self.name}" def __eq__(self, other): return self.name == other.name and self.orbits_around == other.orbits_around def __hash__(self): return hash(str(self)) class TravelObject(NamedTuple): name: str orbit_object: OrbitObject class OrbitMap: COM, YOU, SAN = ("COM", "YOU", "SAN") def __init__(self): self.map: List[OrbitObject] = list() def read_orbit_map(self): with open(INPUT_FILE, "r") as f_handle: for line in f_handle: if line: data = line.rstrip().split(")") self.map.append(OrbitObject(name=data[0], orbits_around=data[1])) def get_starting_point_from_map(self): for orbit in self.map: if self.is_starting_point(orbit.orbits_around): return orbit def is_center_of_mass(self, name): return name == self.COM def is_starting_point(self, name): return name == self.YOU def is_santa(self, name): return name == self.SAN class Traveller: def __init__(self): self.orbit_map = OrbitMap() self.travelled_path: Deque[TravelObject] = deque() self.minimum_distance = float("inf") self.non_valid_routes = set() def calculate_minimum_orbital_trasfer(self): self.orbit_map.read_orbit_map() starting_object = self.orbit_map.get_starting_point_from_map() self.travelled_path.append(TravelObject(starting_object.name, starting_object)) self._find_minimum_distance() def _find_minimum_distance(self): while True: latest_visited_item = self._get_last_travelled_item() if not latest_visited_item: break found_path = False for orbit in self.orbit_map.map: if orbit != latest_visited_item.orbit_object and not self.orbit_map.is_starting_point(orbit.name): if orbit.orbits_around == latest_visited_item.name: if self.orbit_map.is_center_of_mass(orbit.name): continue if (orbit.name, orbit) not in self.non_valid_routes: if self.orbit_map.is_santa(orbit.name): self._set_minimum_distance() self.travelled_path.append(TravelObject(orbit.name, orbit)) found_path = True break if orbit.name == latest_visited_item.name: if (orbit.orbits_around, orbit) not in self.non_valid_routes: if self.orbit_map.is_santa(orbit.orbits_around): self._set_minimum_distance() self.travelled_path.append(TravelObject(orbit.orbits_around, orbit)) found_path = True break if not found_path: self._handle_if_not_found_path() def _set_minimum_distance(self): self.minimum_distance = min(self.minimum_distance, len(self.travelled_path) - 1) def _handle_if_not_found_path(self): if self.travelled_path[-1] not in self.non_valid_routes: self.non_valid_routes.add(self.travelled_path[-1]) self.travelled_path.pop() def _get_last_travelled_item(self): if self.travelled_path: return self.travelled_path[-1] return () def main(): traveller = Traveller() traveller.calculate_minimum_orbital_trasfer() print(f"Minimum orbital path from YOU to SAN is: {traveller.minimum_distance}") if __name__ == "__main__": sys.exit(main())
534f0bcba402ade07b132cc23e8974748438593d
AGCapdeville/Data-Mining-Labs
/Lab3.py
3,842
4.34375
4
''' Lab 3 ''' print ("Lab 3") ##########Part 1 ########### ''' 1) Write a python function to find the frequency of the charchters in a sentence Hint : Use a dictionary e.g.: "hello" {"h":1, "e":1, "l":2, "o":1} ''' # YOUR CODE GOES HERE import pandas as pd ######### Part 2 ########### ''' 1) using pandas.read_csv load and print out the iris-data.csv ''' # YOUR CODE GOES HERE with open("./data/iris-data-color.csv" ) as csvfile: data = pd.read_csv(csvfile, delimiter=',') print(data) ''' 2) after loading the data, print out index, columns, and values information and their types (in a comment line expalin what are they) print out the length of the data set print out the last 50 data points print out the labels print out the labels and petal_length slide notes: print(type(data)) print(data.index) print(data.columns) print(data.values) print(data.values[100]) print(data.values[1:6]) ''' # YOUR CODE GOES HERE print("\nINDEX: \n", data.index) print("\nCOLUMNS: \n", data.columns) print("\nDATA: \n", data.values) print("\nLENGTH: ", len(data)) print() print("last 50 data points:", data[-50:]) print("\nLABELS:") print(data["species"]) print("\nLABELS + petal_length:") print(data[["species","petal_length"]]) ''' 3) print out the mean and std of each feature print out the mean of petal_length for first 100 samples print out the maximum and minimum values for each feature ''' # YOUR CODE GOES HERE import statistics as stat print("\nsepal length mean:",stat.mean(data["sepal_length"])) print(" stdev:",stat.stdev(data["sepal_length"])) print("\nsepal width mean:",stat.mean(data["sepal_width"])) print(" stdev:",stat.stdev(data["sepal_width"])) print("\npetal length mean:",stat.mean(data["petal_length"])) print(" stdev:",stat.stdev(data["petal_length"])) print("\npetal width mean:",stat.mean(data["petal_width"])) print(" stdev:",stat.stdev(data["petal_width"])) print("\nmean of first 100 samples of petal length:",stat.mean(data["petal_length"].head(100))) print("\nsepal length min:",min(data["sepal_length"])) print(" max:",max(data["sepal_length"])) print("\nsepal width min:",min(data["sepal_width"])) print(" max:",max(data["sepal_width"])) print("\npetal length min:",min(data["petal_length"])) print(" max:",max(data["petal_length"])) print("\npetal width min:",min(data["petal_width"])) print(" max:",max(data["petal_width"])) ''' 4) print out the frequency count of each label Hint: use pandas’ function value_counts ''' # YOUR CODE GOES HERE print("\nFreq. count of Sepal Lengths:\n",pd.value_counts(data["sepal_length"])) print("\nFreq. count of Sepal Widths:\n",pd.value_counts(data["sepal_width"])) print("\nFreq. count of Petal Lengths:\n",pd.value_counts(data["petal_length"])) print("\nFreq. count of Petal Widths:\n",pd.value_counts(data["petal_width"])) ######### Part 3 ########### ''' 1) using pandas.DataFrame.drop_duplicates drop duplications in "petal_length" feature (keep the last instance) and print out the resulted data print out the length of the data set print out the mean of each feature print out the frequency count of each label ''' # YOUR CODE GOES HERE dup = data["petal_length"].drop_duplicates(keep='last') print("\nPetal lengths w/out duplicates keeping the last:") print(dup) print("\n length:",len(dup)) print("\n mean:",stat.mean(dup)) print("\n freq:") print(pd.value_counts(dup)) ''' 2) plot the data in a single graph Hint: pandas.DataFrame.plot ''' # YOUR CODE GOES HERE print("\nGraph of the data:") data.plot()
6f8df55732c84ebe46f917494b0b4aba0c6b33b9
AGCapdeville/Data-Mining-Labs
/lab1.py
4,415
4.53125
5
''' Lab 1 ''' print ("Lab 1") ##########Part 0 ########### ''' 1) Create a variable, x, and set its value to 5 Create a variable, y, and set its value to 3 more than x's value Exponentiate x by half of y, and store the result in x (hint: **=) ''' # YOUR CODE GOES HERE print() print("= = = = = = = = = = = = Part 0.1 = = = = = = = = = = = = ") x = 5 y = x+3 print("X:",x) print("Y:",y) x = x ** (y/2) print("( After X**Y/2 ):") print("X:",x) ''' 2) A rectangle has the width and height defined below. Store its area in a new variable. Print out your result and check your answer. Change the values of width and height and ensure the result is still correct. ''' print() print("= = = = = = = = = = = = Part 0.2 = = = = = = = = = = = = ") width = 3 height = 4 # YOUR CODE GOES HERE area = width * height print("width:",width,"height:",height,"area:",area) print("new values: width:5 height:5") width = 5 height = 5 area = width * height print("new area:",area) ######### Part 1 ########### print() print("= = = = = = = = = = = = Part 1.1 = = = = = = = = = = = = ") x = 4 y = -7 z = 10 print(x==4) print(x>4) print(x<=y) print(x>=z-11) print(x!=z-8%11) print((2*z+1)%11>3*x-1) ######### Part 2 ########### ''' 1) Use an if-else sequence to print whether x is even or odd. HINT: use the modulus operator % ''' x = 12 # YOUR CODE GOES HERE print() print("= = = = = = = = = = = = Part 2.1 = = = = = = = = = = = = ") if x%2 == 0: print("+ even") else: print("- odd") ''' 2) Write a program which: - stores their two inputs in variables as floats (e.g. num1 and num2) - stores an arithmetic operation ( + - * / %) as a string (op = '+') - stores the result of the specfied operation with the specified numbers - if the user's input operation isn't one of those listed above, instead print a message telling them so - if the inputs are invalid for the operation (i.e. dividing by 0) print a message informing the user - if the inputs were valid, prints out the resulting equation ''' # num1 = 2.1 # num2 = 3 # op = '*' # YOUR CODE GOES HERE print() print("= = = = = = = = = = = = Part 2.2 = = = = = = = = = = = = ") def getNum(s): while True: print(" Number",s) number = input("Enter number :") try: number = float(number) if isinstance(number, float) or isinstance(number, int): return number except: print(" INVALID NUMBER") def getOp(): while True: op = input("Enter an operator ( + - * / % ) :") if op=="+" or op=="-" or op=="*" or op=="/" or op=="%": return op print(" INVALID OP") def tryOp(n1, n2, op): if op=="+": print(n1 + n2) return True if op=="-": print(n1 + n2) return True if op=="*": print(n1 * n2) return True if op=="/": if n2==0: return False else: print(n1 / n2) return True if op=="%": print(n1 % n2) return True while True: n1 = getNum(1) n2 = getNum(2) op = getOp() if tryOp(n1, n2, op): cont = input("Test another input? ( Enter yes / no ): ") if cont=="no": break else: print("ERROR, INVALID OPERATION") ######### Part 3 ########### ''' 1) Use a while loop to print all integers from 0 to 10, including 0 and 10. ''' # YOUR CODE GOES HERE print() print("= = = = = = = = = = = = Part 3.1 = = = = = = = = = = = = ") i=0 while i < 11: print(i) i+=1 ''' 2) Use a while loop to print all even numbers from 2 up to and including 12 ''' # YOUR CODE GOES HERE print() print("= = = = = = = = = = = = Part 3.2 = = = = = = = = = = = = ") i=2 while i <= 12: if i%2 == 0: print(i) i+=1 ######### Part 4 ########### ''' 1) Use a For loop to calculate -1000-999-...+-1+0+1+2+3+4+......+1000 ''' # YOUR CODE GOES HERE print() print("= = = = = = = = = = = = Part 4.1 = = = = = = = = = = = = ") ans = 0 for i in (-1000, 1000): ans += i print(ans) ''' 2) Use a For loop to print all positive odd numbers less than 8, except 5. ''' # YOUR CODE GOES HERE print() print("= = = = = = = = = = = = Part 4.2 = = = = = = = = = = = = ") for x in range(8): if x%2 == 0: DoNothing=0 elif x != 5: print(x)
a99405e7e2fddce640e8925494eb32a53a94b4d5
mallius/CppPrimer
/CorePythonProg/ch06/0609ex.py
128
3.53125
4
#!/usr/bin/env python str = raw_input('Enter a string like 03:30 >') hm = str.split(":", 1) print int(hm[0])*60 + int(hm[1])
ecfbcab263b54fed0c927844370a752a6efa1363
mallius/CppPrimer
/CorePythonProg/ch07/0703ex.py
109
3.78125
4
#!/usr/bin/env python d = {'a':1, 'c':2, 'b':3, 'd':4} s = sorted(d.items()) for x in s: print x[0], x[1]
1b7c1dc4a3cfe1aa34b2972bca53e80ea1201244
mallius/CppPrimer
/CorePythonProg/ch11/1113ex.py
154
3.578125
4
#!/usr/bin/env python def mult(x, y): return x*y ret = reduce(mult, range(1,4,1)) print ret ret = reduce((lambda x,y: x*y), range(1, 4, 1)) print ret
f50848bcf18dcb9ab437b73f7ca595b7bdb12106
mallius/CppPrimer
/CorePythonProg/ch06/0602ex.py
573
3.65625
4
#!usr/bin/env python import string import keyword alphas = list(string.letters + '_') nums = list(string.digits) key = keyword.kwlist kw = alphas + nums + key print 'Welcome to the Identifier Checker v1.1' print 'Testees must be at least 1 chars long' myInput = (raw_input('Identifier to test: ')).split() print myInput if len(myInput) > 0: if myInput[0] not in kw: print '''invalid: first symbol must be alphabetic''' else: for otherChar in myInput[0:]: if otherChar in kw: print '''ok as an identifier''' else: print "okay not an identifier"
f930faad4a19494e55d7666cf6f4db2bd1df0e41
mallius/CppPrimer
/CorePythonProg/ch13/p376_1305anylter.py
384
3.515625
4
#!/usr/bin/env python class AnyIter(object): def __init__(self, data, safe=False): self.safe = safe self.iter = iter(data) def __iter__(self): return self def next(self, howmany=1): retval = [] for eachIter in range(howmany): try: retval.append(self.iter.next()) except StopIteration: if self.safe: break else: raise return retval
b4944285e06ae6c8f26feeb861afe4754fc97af5
mallius/CppPrimer
/CorePythonProg/ch13/p374_1303time60.py
683
4.09375
4
#!/usr/bin/env python class Time60(object): 'Time60 - track hours and minutes' def __init__(self, hr, min): 'Time60 constructor - takes hours and minutes' self.hr = hr self.min = min def __str__(self): 'Time60 - string representation' return '%d:%d' % (self.hr, self.min) __repr__ = __str__ def __add__(self, other): 'Time60 - overloading the addition operator' return self.__class__(self.hr + other.hr, self.min + other.min) def __iadd__(self, other): 'Time60 - overloading in-place addition' self.hr += other.hr self.min += other.min return self wed = Time60(12, 5) print wed thu = Time60(10, 30) fri = Time60(8, 45) print thu + fri
c7cf28ba610285a09fa49d7e01760d9700e41310
mallius/CppPrimer
/CorePythonProg/ch11/p289.py
175
3.5625
4
#!/usr/bin/env python from random import randint def odd(n): return n % 2 allNums = [] for eachNum in range(9): allNums.append(randint(1,99)) print filter(odd, allNums)
d1c21863de80c80b30f6afe24696fc4dc18ebe31
binary-com/gce-manager
/lib/terminaltables.py
11,513
4.15625
4
"""Generate simple tables in terminals from a nested list of strings. Example: >>> from terminaltables import AsciiTable >>> table = AsciiTable([['Name', 'Type'], ['Apple', 'fruit'], ['Carrot', 'vegetable']]) >>> print table.table +--------+-----------+ | Name | Type | +--------+-----------+ | Apple | fruit | | Carrot | vegetable | +--------+-----------+ Use UnixTable instead of AsciiTable for box-drawing characters instead. https://github.com/Robpol86/terminaltables https://pypi.python.org/pypi/terminaltables """ import fcntl import re import struct import sys import termios __author__ = '@Robpol86' __license__ = 'MIT' __version__ = '1.0.2' DEFAULT_TERMINAL_HEIGHT = None DEFAULT_TERMINAL_WIDTH = None def _align_and_pad(input_, align, width, height, lpad, rpad): """Aligns a string with center/rjust/ljust and adds additional padding. Positional arguments: input_ -- input string to operate on. align -- 'left', 'right', or 'center'. width -- align to this column width. height -- pad newlines and spaces to set cell to this height. lpad -- number of spaces to pad on the left. rpad -- number of spaces to pad on the right. Returns: Modified string. """ # Handle trailing newlines or empty strings, str.splitlines() does not satisfy. lines = input_.splitlines() or [''] if input_.endswith('\n'): lines.append('') # Align. if align == 'center': aligned = '\n'.join(l.center(width) for l in lines) elif align == 'right': aligned = '\n'.join(l.rjust(width) for l in lines) else: aligned = '\n'.join(l.ljust(width) for l in lines) # Pad. padded = '\n'.join((' ' * lpad) + l + (' ' * rpad) for l in aligned.splitlines() or ['']) # Increase height. additional_padding = height - 1 - padded.count('\n') if additional_padding > 0: padded += ('\n{0}'.format(' ' * (width + lpad + rpad))) * additional_padding return padded def _convert_row(row, left, middle, right): """Converts a row (list of strings) into a joined string with left and right borders. Supports multi-lines. Positional arguments: row -- list of strings representing one row. left -- left border. middle -- column separator. right -- right border. Returns: String representation of a row. """ if not row: return left + right if not any('\n' in c for c in row): return left + middle.join(row) + right # Split cells in the row by newlines. This creates new rows. split_cells = [(c.splitlines() or ['']) + ([''] if c.endswith('\n') else []) for c in row] height = len(split_cells[0]) # Merge rows into strings. converted_rows = list() for row_number in range(height): converted_rows.append(left + middle.join([c[row_number] for c in split_cells]) + right) return '\n'.join(converted_rows) def set_terminal_title(title): """Sets the terminal title. Positional arguments: title -- the title to set. """ sys.stdout.write('\033]0;{0}\007'.format(title)) def terminal_height(): """Returns the terminal's height (number of lines).""" try: return struct.unpack('hhhh', fcntl.ioctl(0, termios.TIOCGWINSZ, '\000' * 8))[0] except IOError: if DEFAULT_TERMINAL_HEIGHT is None: raise return int(DEFAULT_TERMINAL_HEIGHT) def terminal_width(): """Returns the terminal's width (number of character columns).""" try: return struct.unpack('hhhh', fcntl.ioctl(0, termios.TIOCGWINSZ, '\000' * 8))[1] except IOError: if DEFAULT_TERMINAL_WIDTH is None: raise return int(DEFAULT_TERMINAL_WIDTH) class AsciiTable(object): """Draw a table using regular ASCII characters, such as `+`, `|`, and `-`.""" CHAR_CORNER_LOWER_LEFT = '+' CHAR_CORNER_LOWER_RIGHT = '+' CHAR_CORNER_UPPER_LEFT = '+' CHAR_CORNER_UPPER_RIGHT = '+' CHAR_HORIZONTAL = '-' CHAR_INTERSECT_BOTTOM = '+' CHAR_INTERSECT_CENTER = '+' CHAR_INTERSECT_LEFT = '+' CHAR_INTERSECT_RIGHT = '+' CHAR_INTERSECT_TOP = '+' CHAR_VERTICAL = '|' def __init__(self, table_data, title=None): self.table_data = table_data self.title = title self.inner_column_border = True self.inner_heading_row_border = True self.inner_row_border = False self.justify_columns = dict() # {0: 'right', 1: 'left', 2: 'center'} self.outer_border = True self.padding_left = 1 self.padding_right = 1 def column_max_width(self, column_number): """Returns the maximum width of a column based on the current terminal width. Positional arguments: column_number -- the column number to query. Returns: The max width of the column (integer). """ column_widths = self.column_widths borders_padding = (len(column_widths) * self.padding_left) + (len(column_widths) * self.padding_right) if self.outer_border: borders_padding += 2 if self.inner_column_border and column_widths: borders_padding += len(column_widths) - 1 other_column_widths = sum(column_widths) - column_widths[column_number] return terminal_width() - other_column_widths - borders_padding @property def column_widths(self): """Returns a list of integers representing the widths of each table column without padding.""" if not self.table_data: return list() number_of_columns = max(len(r) for r in self.table_data) widths = [0] * number_of_columns for row in self.table_data: for i in range(len(row)): if not row[i]: continue widths[i] = max(widths[i], len(max(row[i].splitlines(), key=len))) return widths @property def ok(self): """Returns True if the table fits within the terminal width, False if the table breaks.""" return self.table_width <= terminal_width() @property def padded_table_data(self): """Returns a list of lists of strings. It's self.table_data but with the cells padded with spaces and newlines. Most of the work in this class is done here. """ if not self.table_data: return list() # Set all rows to the same number of columns. max_columns = max(len(r) for r in self.table_data) new_table_data = [r + [''] * (max_columns - len(r)) for r in self.table_data] # Pad strings in each cell, and apply text-align/justification. column_widths = self.column_widths for row in new_table_data: height = max([c.count('\n') for c in row] or [0]) + 1 for i in range(len(row)): align = self.justify_columns.get(i, 'left') cell = _align_and_pad(row[i], align, column_widths[i], height, self.padding_left, self.padding_right) row[i] = cell return new_table_data @property def table(self): """Returns a large string of the entire table ready to be printed to the terminal.""" padded_table_data = self.padded_table_data column_widths = [c + self.padding_left + self.padding_right for c in self.column_widths] final_table_data = list() # Append top border. max_title = sum(column_widths) + ((len(column_widths) - 1) if self.inner_column_border else 0) if self.outer_border and self.title and len(self.title) <= max_title: pseudo_row = _convert_row(['h' * w for w in column_widths], 'l', 't' if self.inner_column_border else '', 'r') pseudo_row_key = dict(h=self.CHAR_HORIZONTAL, l=self.CHAR_CORNER_UPPER_LEFT, t=self.CHAR_INTERSECT_TOP, r=self.CHAR_CORNER_UPPER_RIGHT) pseudo_row_re = re.compile('({0})'.format('|'.join(pseudo_row_key.keys()))) substitute = lambda s: pseudo_row_re.sub(lambda x: pseudo_row_key[x.string[x.start():x.end()]], s) row = substitute(pseudo_row[:1]) + self.title + substitute(pseudo_row[1 + len(self.title):]) final_table_data.append(row) elif self.outer_border: row = _convert_row([self.CHAR_HORIZONTAL * w for w in column_widths], self.CHAR_CORNER_UPPER_LEFT, self.CHAR_INTERSECT_TOP if self.inner_column_border else '', self.CHAR_CORNER_UPPER_RIGHT) final_table_data.append(row) # Build table body. indexes = range(len(padded_table_data)) for i in indexes: row = _convert_row(padded_table_data[i], self.CHAR_VERTICAL if self.outer_border else '', self.CHAR_VERTICAL if self.inner_column_border else '', self.CHAR_VERTICAL if self.outer_border else '') final_table_data.append(row) # Insert row separator. if i == indexes[-1]: continue if self.inner_row_border or (self.inner_heading_row_border and i == 0): row = _convert_row([self.CHAR_HORIZONTAL * w for w in column_widths], self.CHAR_INTERSECT_LEFT if self.outer_border else '', self.CHAR_INTERSECT_CENTER if self.inner_column_border else '', self.CHAR_INTERSECT_RIGHT if self.outer_border else '') final_table_data.append(row) # Append bottom border. if self.outer_border: row = _convert_row([self.CHAR_HORIZONTAL * w for w in column_widths], self.CHAR_CORNER_LOWER_LEFT, self.CHAR_INTERSECT_BOTTOM if self.inner_column_border else '', self.CHAR_CORNER_LOWER_RIGHT) final_table_data.append(row) return '\n'.join(final_table_data) @property def table_width(self): """Returns the width of the table including padding and borders.""" column_widths = self.column_widths borders_padding = (len(column_widths) * self.padding_left) + (len(column_widths) * self.padding_right) if self.outer_border: borders_padding += 2 if self.inner_column_border and column_widths: borders_padding += len(column_widths) - 1 return sum(column_widths) + borders_padding class UnixTable(AsciiTable): """Draw a table using box-drawing characters on Unix platforms. Table borders won't have any gaps between lines. Similar to the tables shown on PC BIOS boot messages, but not double-lined. """ CHAR_CORNER_LOWER_LEFT = '\033(0\x6d\033(B' CHAR_CORNER_LOWER_RIGHT = '\033(0\x6a\033(B' CHAR_CORNER_UPPER_LEFT = '\033(0\x6c\033(B' CHAR_CORNER_UPPER_RIGHT = '\033(0\x6b\033(B' CHAR_HORIZONTAL = '\033(0\x71\033(B' CHAR_INTERSECT_BOTTOM = '\033(0\x76\033(B' CHAR_INTERSECT_CENTER = '\033(0\x6e\033(B' CHAR_INTERSECT_LEFT = '\033(0\x74\033(B' CHAR_INTERSECT_RIGHT = '\033(0\x75\033(B' CHAR_INTERSECT_TOP = '\033(0\x77\033(B' CHAR_VERTICAL = '\033(0\x78\033(B' @property def table(self): ascii_table = super(UnixTable, self).table optimized = ascii_table.replace('\033(B\033(0', '') return optimized
a00233fcb03e5dd33ff8d39575f520a5bf5f8bf0
webpagedemo/python101-my
/skrypty/trzyLiczby.py
238
3.515625
4
op = "t" while op == "t": a, b, c = input("Podaj trzy liczby oddzielone spacjami: ").split(" ") liczby = [a, b, c] print("Wprowadzono liczby:", a, b, c) print("\nNajmnijsza: ") liczby.sort() print(liczby[0])
d9395f8dd710f4555f66febe8bb575799b52e181
hannahTao/2021-Coding-Club-Biweekly-Challenges
/challenge3.py
4,052
4.21875
4
import math def calculator_functions(userInput): if userInput in ["add", "multiply", "divide"]: numOfNumbers = int(input("How many numbers do you want to " + userInput + "? ")) for i in range(numOfNumbers): if i == 0: value = float(input("Input a number: ")) else: if userInput == "add": value += float(input("Input a number: ")) if userInput == "multiply": value *= float(input("Input a number: ")) if userInput == "divide": value /= float(input("Input a number: ")) return value elif userInput == "angles": conversion = input('Type "radians" to convert degrees to radians and "degrees" to convert radians to degrees: ') angleMeasure = float(input("Angle measure: ")) if conversion == "degrees": return math.degrees(angleMeasure) if conversion == "radians": return math.radians(angleMeasure) elif userInput == "trig": trigFunction = input('Type "sin", "cos", "tan", "asin", "acos", or "acot": ') if trigFunction in ["sin", "cos", "tan"]: angleMeasure = float(input("Angle measure: ")) if trigFunction == "sin": return math.sin(angleMeasure) if trigFunction == "cos": return math.cos(angleMeasure) if trigFunction == "tan": return math.tan(angleMeasure) elif trigFunction in ["asin", "acos", "acot"]: x = float(input("x: ")) if trigFunction == "asin": return math.asin(x) if trigFunction == "acos": return math.acos(x) if trigFunction == "atan": return math.atan(x) elif userInput == "log": base = float(input("Base: ")) x = float(input("x: ")) return math.log(x, base) elif userInput == "Ln": x = float(input("x: ")) return math.log(x) elif userInput == "x^y": x = float(input("x: ")) y = float(input("y: ")) return math.pow(x,y) elif userInput == "e^x": x = float(input("x: ")) return math.exp(x) elif userInput == "sqrt": x = float(input("x: ")) return math.sqrt(x) elif userInput == "remainder": x = float(input("x: ")) y = float(input("y: ")) return math.fmod(x,y) elif userInput == "factorial": x = int(input("x: ")) return math.factorial(x) elif userInput == "gcd": x = int(input("x: ")) y = int(input("y: ")) return math.gcd(x,y) elif userInput == "hypotenuse": x = float(input("x: ")) y = float(input("y: ")) return math.hypot(x,y) elif userInput == 'more': output = 'You can type: \n"angles" to convert angle measures in degrees/radians\n"trig" for trig functions (mode radian)\n"log" to find logarithm of x to a base\n"Ln" to find natural logarithm of x\n"x^y" to raise x to the y power\n"e^x" to raise e to the x power\n"sqrt" to find square root of x\n"remainder" to find remainder when x/y, where x and y can be decimals\n"factorial" to find x factorial\n"gcd" to find gcd of integers x and y\n"hypotenuse" to find hypotenuse of a right triangle with legs of length x and y\n\nChoose one! ' return output print('Welcome to the calculator with many options!!') print('Instructions: when prompted for input, type "add" "multiply" or "divide" (input negative numbers in "add" to subtract). Or, type "more" to see more options, or "done" when you are done with the calculator!\n') userInput = input('What do YOU want to do with this calculator? ').strip() possibleInputs = ['add', 'multiply', 'divide', 'angles', 'trig', 'log', 'Ln', 'x^y', 'e^x', 'sqrt', 'remainder', 'factorial', 'gcd', 'hypotenuse', 'more', 'done'] calcRunning = True if userInput == 'done': print('Thank you for using my calculator!') calcRunning = False while calcRunning: while userInput not in possibleInputs: userInput = input('Please type a valid input: ').strip() if userInput != 'done': print(calculator_functions(userInput)) userInput = input('\nInput: ').strip() # prompt for new input else: print('Thank you for using my calculator!') calcRunning = False
fabf3690168c58868a8de655cbb3b522dab2e0fc
martika810/superbeginner
/test.py
468
3.84375
4
class Palindrome: def __init__(self, phrase): self.phrase = phrase.replace(' ','').lower() def is_position_palindrome(self, index): return self.phrase[index] == self.phrase[-index-1] def is_palindrome(self): for index in range(int(len(self.phrase)/2)): if not self.is_position_palindrome(index): return False return True palindrome = Palindrome('Nurses run') print(palindrome.is_palindrome())
fa578313a53ff90e3a1733cba0dd6248ca4f5771
katsuragawaa/japanese-flash-card
/Flash Card.py
2,952
3.609375
4
from tkinter import * import pandas from random import randint from csv import writer, reader data = pandas.read_csv("data/japanese.csv") # ----------------- FONT = "Bahnschrift" BACKGROUND_COLOR = "#B1DDC6" class Card: def front(self): card.itemconfig(card_image, image=image_front) card.itemconfig(language, text="Japanese", fill="black") card.itemconfig(word, text=self.new_kana, fill="black") card.itemconfig(expression, text=self.new_expression, fill="black") def back(self): card.itemconfig(card_image, image=image_back) card.itemconfig(language, text="English", fill="white") card.itemconfig(word, text=self.new_meaning, fill="white") card.itemconfig(expression, text="") def new_card(self): self.i = randint(0, 6000) self.new_kana = data.kana[self.i] self.new_expression = data.expression[self.i] self.new_meaning = data.meaning[self.i] self.learned_words = [ str(self.i), self.new_expression, self.new_kana, self.new_meaning, ] with open("data/learned.csv", encoding="utf-8") as f: dt = reader(f) learned_list = list(dt) print(learned_list) print(f"\n\n{self.learned_words}") if self.learned_words in learned_list: self.new_card() print("deu certo") else: self.front() def save_csv(self): with open("data/learned.csv", "a+", newline="", encoding="utf-8") as write_obj: csv_writer = writer(write_obj) csv_writer.writerow(self.learned_words) self.new_card() window = Tk() window.config(padx=100, pady=100, bg=BACKGROUND_COLOR) window.title("Japanese Flash Cards") image_front = PhotoImage(file="images/card_front.png") image_back = PhotoImage(file="images/card_back.png") wrong_image = PhotoImage(file="images/wrong.png") right_image = PhotoImage(file="images/right.png") card = Canvas(width=800, height=526, highlightthickness=0, bg=BACKGROUND_COLOR) card_image = card.create_image(400, 263) language = card.create_text(400, 50, font=(FONT, 30)) word = card.create_text(400, 250, font=(FONT, 60, "bold"), width=700) expression = card.create_text(400, 430, font=(FONT, 40, "bold")) new = Card() new.new_card() card.grid(column=1, row=1, columnspan=3) flip_button = Button() flip_button.config(text="Flip Card", width=20, command=new.back) flip_button.grid(column=2, row=2) right_button = Button() right_button.config( image=right_image, width=100, height=100, highlightthickness=0, command=new.save_csv, ) right_button.grid(column=3, row=2) wrong_button = Button() wrong_button.config( image=wrong_image, width=100, height=100, highlightthickness=0, command=new.new_card, ) wrong_button.grid(column=1, row=2) window.mainloop()
7a7e4c2393928ca31e584f184f4a6c51689a42c5
DominiqueGregoire/cp1404practicals
/prac_04/quick_picks.py
1,351
4.4375
4
"""asks the user how many "quick picks" they wish to generate. The program then generates that many lines of output. Each line consists of 6 random numbers between 1 and 45. pseudocode get number of quick picks create a list to hold each quick pick line generate a random no x 6 to make the line print the line repeat this x number of quick picks""" from random import randint NUMBERS_PER_LINE = 6 MAXIMUM = 45 MINIMUM = 1 def main(): amount = int(input("How many quick picks? ")) while amount < 0: # check for invalid amount of quick picks print("Invalid amount") amount = int(input("How many quick picks? ")) for i in range(amount): quick_pick_lines = [] for number in range(NUMBERS_PER_LINE): # create a list of 6 random numbers between 1 and 45 number = randint(MINIMUM, MAXIMUM) if number in quick_pick_lines: number = randint(MINIMUM, MAXIMUM) quick_pick_lines.append(number) # print(quick_pick_lines) quick_pick_lines.sort() # print(quick_pick_lines) # quick_pick_lines = [str(number) for number in quick_pick_lines] # print(quick_pick_lines) # print(' '.join(quick_pick_lines)) print(' '.join('{:2}'.format(number) for number in quick_pick_lines)) main()
8ce539f39c64ec427b153f83dd925b6f06dae087
DominiqueGregoire/cp1404practicals
/prac_02/capitalist_conrad.py
3,853
4.28125
4
""" CP1404/CP5632 - Practical Capitalist Conrad wants a stock price simulator for a volatile stock. The price starts off at $10.00, and, at the end of every day there is a 50% chance it increases by 0 to 10%, and a 50% chance that it decreases by 0 to 5%. If the price rises above $1000, or falls below $0.01, the program should end. The price should be displayed to the nearest cent (e.g. $33.59, not $33.5918232901) """ import random MAX_INCREASE = 0.1 # 10% MAX_DECREASE = 0.05 # 5% MIN_PRICE = 0.01 MAX_PRICE = 1000.0 INITIAL_PRICE = 10.0 OUTPUT_FILE = "stock_price_simulator.txt" # name of output file price = INITIAL_PRICE print("${:,.2f}".format(price)) while MIN_PRICE <= price <= MAX_PRICE: price_change = 0 # generate a random integer of 1 or 2 # if it's 1, the price increases, otherwise it decreases if random.randint(1, 2) == 1: # generate a random floating-point number # between 0 and MAX_INCREASE price_change = random.uniform(0, MAX_INCREASE) else: # generate a random floating-point number # between negative MAX_DECREASE and 0 price_change = random.uniform(-MAX_DECREASE, 0) price *= (1 + price_change) print("${:,.2f}".format(price)) print() # things to do no 1. add a day counter and format the output # initialise a loop count as 0 # loop count will count each instance and will help the user see the price on a particular instance loop_count = 0 price = INITIAL_PRICE print("Starting price: ${:,.2f}".format(price)) while MIN_PRICE <= price <= MAX_PRICE: price_change = 0 loop_count += 1 # generate a random integer of 1 or 2 # if it's 1, the price increases, otherwise it decreases if random.randint(1, 2) == 1: # generate a random floating-point number # between 0 and MAX_INCREASE price_change = random.uniform(0, MAX_INCREASE) else: # generate a random floating-point number # between negative MAX_DECREASE and 0 price_change = random.uniform(-MAX_DECREASE, 0) price *= (1 + price_change) print("On day {} price is: ${:,.2f}".format(loop_count, price)) print() # things to do no 2. changing the constants MAX_INCREASE = 0.175 # 17.5% MIN_PRICE = 1 MAX_PRICE = 100.0 loop_count = 0 price = INITIAL_PRICE print("Starting price: ${:,.2f}".format(price)) while MIN_PRICE <= price <= MAX_PRICE: price_change = 0 loop_count += 1 # generate a random integer of 1 or 2 # if it's 1, the price increases, otherwise it decreases if random.randint(1, 2) == 1: # generate a random floating-point number # between 0 and MAX_INCREASE price_change = random.uniform(0, MAX_INCREASE) else: # generate a random floating-point number # between negative MAX_DECREASE and 0 price_change = random.uniform(-MAX_DECREASE, 0) price *= (1 + price_change) print("On day {} price is: ${:,.2f}".format(loop_count, price)) print() # things to do no 3 ... print the program output to file out_file = open(OUTPUT_FILE, 'w') loop_count = 0 price = INITIAL_PRICE print("Starting price: ${:,.2f}".format(price), file=out_file) while MIN_PRICE <= price <= MAX_PRICE: price_change = 0 loop_count += 1 # generate a random integer of 1 or 2 # if it's 1, the price increases, otherwise it decreases if random.randint(1, 2) == 1: # generate a random floating-point number # between 0 and MAX_INCREASE price_change = random.uniform(0, MAX_INCREASE) else: # generate a random floating-point number # between negative MAX_DECREASE and 0 price_change = random.uniform(-MAX_DECREASE, 0) price *= (1 + price_change) print("On day {} price is: ${:,.2f}".format(loop_count, price), file=out_file) print() out_file.close()
5675306e73bfd33b8371343e45af5c8ec1c50499
SherwinRF/olympics-data-analysis
/code.py
3,260
3.5625
4
# -------------- #Importing header files import pandas as pd import numpy as np import matplotlib.pyplot as plt #Path of the file is stored in the variable path #Code starts here # Data Loading data = pd.read_csv(path) data.rename( columns = {'Total':'Total_Medals'}, inplace = True ) data.head(10) # Summer or Winter c1 = data['Total_Summer'] == data['Total_Winter'] c2 = data['Total_Summer'] > data['Total_Winter'] data['Better_Event'] = np.where( c1, 'Both', (np.where(c2, 'Summer', 'Winter')) ) better_event = data['Better_Event'][data['Better_Event'].value_counts().max()] print(better_event) # Top 10 def top_ten(df, col): country_list = [] a = df.nlargest(10, col) country_list = list(a['Country_Name']) return country_list top_countries = pd.DataFrame( data, columns = ['Country_Name','Total_Summer', 'Total_Winter','Total_Medals'] )[:-1] top_10_summer = top_ten(top_countries, 'Total_Summer') top_10_winter = top_ten(top_countries, 'Total_Winter') top_10 = top_ten(top_countries, 'Total_Medals') common = list(set(top_10_summer) & set(top_10_winter) & set(top_10)) print( top_10_summer, "\n", top_10_winter, "\n", top_10, "\n", common ) # Plotting top 10 summer_df = data[data['Country_Name'].isin(top_10_summer)] winter_df = data[data['Country_Name'].isin(top_10_winter)] top_df = data[data['Country_Name'].isin(top_10)] p1 = plt.figure().add_axes([0,0,1,1]) p1.bar(summer_df['Country_Name'], summer_df['Total_Summer']) plt.xlabel('Country') plt.ylabel('Total Medals') plt.xticks(rotation=90) plt.title('Top 10 Countries for Summer Olympics') p2 = plt.figure().add_axes([0,0,1,1]) p2.bar(winter_df['Country_Name'], winter_df['Total_Winter']) plt.xlabel('Country') plt.ylabel('Total Medals') plt.xticks(rotation=90) plt.title('Top 10 Countries for Winter Olympics') p3 = plt.figure().add_axes([0,0,1,1]) p3.bar(top_df['Country_Name'], top_df['Total_Medals']) plt.xlabel('Country') plt.ylabel('Total Medals') plt.xticks(rotation=90) plt.title('Top 10 Countries for Olympics Overall') # Top Performing Countries summer_df['Golden_Ratio'] = summer_df['Gold_Summer'] % summer_df['Total_Summer'] summer_max_ratio = summer_df['Golden_Ratio'].max() summer_country_gold = list(summer_df['Country_Name'][summer_df['Golden_Ratio']==summer_max_ratio])[0] winter_df['Golden_Ratio'] = winter_df['Gold_Winter'] % winter_df['Total_Winter'] winter_max_ratio = winter_df['Golden_Ratio'].max() winter_country_gold = list(winter_df['Country_Name'][winter_df['Golden_Ratio']==winter_max_ratio])[0] top_df['Golden_Ratio'] = top_df['Gold_Total'] / top_df['Total_Medals'] top_max_ratio = top_df['Golden_Ratio'].max() top_country_gold = list(top_df['Country_Name'][top_df['Golden_Ratio']==top_max_ratio])[0] # Best in the world data_1 = data[:-1] data_1['Total_Points'] = data_1['Gold_Total']*3 + data_1['Silver_Total']*2 + data_1['Bronze_Total']*1 most_points = data_1['Total_Points'].max() best_country = list(data_1['Country_Name'][data_1['Total_Points']==most_points])[0] # Plotting the best best = data[ data['Country_Name'] == best_country ] best = pd.DataFrame( best, columns = ['Gold_Total','Silver_Total','Bronze_Total'] ) best.plot.bar( stacked=True ) plt.xlabel('United States') plt.ylabel('Medals Tally') plt.xticks(rotation=45)
032b23fefe460e8a624bf0885d4b85c6d2166837
nickcorin/nbx
/users/errors.py
927
3.5
4
class UsersError(Exception): """Base class for exceptions in this module.""" pass class DuplicateEmail(UsersError): """Returned when registering a user with an email that already exists.""" def __init__(self): self.status_code = 400 def __str__(self): return "email already exists" class UserNotFound(UsersError): """Returned when querying for a user that does not exist.""" def __init__(self): self.status_code = 404 def __str__(self): return "user does not exist" class InvalidEmail(UsersError): """Returned when providing an invalid email address.""" def __init__(self): self.status_code = 400 def __str__(self): return "invalid email provided" def status_code(e: UsersError) -> int: """ Returns an HTTP status code for some Error.""" if isinstance(e, UsersError): return e.status_code return 500
966fdbc0aef9bb5ea720d4234f2bcb7d68b3eec1
nickcorin/nbx
/users/db/util.py
221
3.984375
4
import re def valid_email(email: str) -> bool: """Validates an email format using regex.""" regex = '^(\w|\.|\_|\-)+[@](\w|\_|\-|\.)+[.]\w{2,3}$' return True if re.search(regex, email) is not None else False
76ad563b5afe7a6657cf7c62d4c450cfd022da37
gperaza/ISLR-Python-Exercises
/Chapter11/02-discrete-distributions/discrete-dist.py
685
3.640625
4
from random import random import matplotlib.pyplot as plt from collections import Counter def plot_prob_mass_funct(sample): """ Plots a probability mass function from a sample of discrete random variables. """ bars = sorted(Counter(sample).items()) heights = [x[1]/len(sample) for x in bars] ticks = [x[0] for x in bars] plt.bar(range(len(heights)), heights, align='center') plt.xticks(range(len(ticks)), ticks) plt.show() def random_discrete(a_list, p_list, n): sample = [] # Complete this function return sample a_list = [1, 3, 4] p_list = [3/5, 1/5, 1/5] sample = random_discrete(a_list, p_list, 10000) plot_prob_mass_funct(sample)
d96ac503bf0327c03984ad0e0bb26247d335926f
vbnguyen165/Ted-Talks-Database
/command-line_utility.py
2,661
3.859375
4
# importing the requests library import requests import csv URL = 'http://127.0.0.1:5000/' def get(object): request = input('Do you want to see all records (Yes/No) ') while request.lower() != 'yes' and request.lower() != 'no': print('Please enter Yes or No.') request = input('Do you want to see all records (Yes/No) ') if request.lower() == 'no': id = input('Please enter the id of what you are looking for: ') get_url = URL + '{}/{}'.format(object, id) else: get_url = URL + '{}'.format(object) response = requests.get(get_url) return response def add_speech_with_csv(): add_url = URL + "speeches" file_input = str(input("Please enter the name of the csv file: ")) if ".csv" not in file_input: file_input += ".csv" with open(file_input, encoding='utf-8') as f: reader = csv.DictReader(f) responses = [] for row in reader: response = requests.post(add_url, row) responses.append(response) f.close() return responses if __name__ == '__main__': purpose = input( 'Do you want to add or retrieve information? ' '(add/retrieve).Enter "quit" to exit the program ') while purpose.lower() != 'quit': if purpose.lower() == 'retrieve': user_input = input( 'What do you want to know about? (speeches/speakers/topics) ') while user_input.lower() != 'speeches' \ and user_input.lower() != 'speakers' \ and user_input.lower() != 'topics': print('Please enter either "speeches", "speakers", or "topics"') user_input = input( 'What do you want to know about? ' '(speeches/speakers/topics) ') response = get(user_input) output = response.json() if type(output) is list: for record in output: for field in record: print(field, ":", record[field]) print('---------------------------') else: for field in output: print(field, ":", output[field]) purpose = input( 'Do you want to add or retrieve information? (add/retrieve). ' 'Enter "quit" to exit the program ') elif purpose.lower() == 'add': responses = add_speech_with_csv() if 'error' not in responses[0].json(): print('The following speeches have been added to the database:') for response in responses: output = response.json() for field in output: print(field, ":", output[field]) print('---------------------------') print('\n') purpose = input( 'Do you want to add or retrieve information? (add/retrieve). ' 'Enter "quit" to exit the program ') else: purpose = input('Please enter either "add", "retrieve", or "quit"')
13e9c29eed2b024c271fa1984cc5e90c86b23683
jasmintey/pythonLab6
/labsheet/lab7/Lab7 practice.py
1,640
3.734375
4
#Q2 # f = open("demofile.txt", "r") # print(f.read()) # f.close() #Q3 # print(f.read(5)) # f.close() #Q4 # print(f.readline()) #Q5 # print(f.readline()) # print(f.readline()) #Q6 # for x in f: # print(x) #Q7 # f = open("demofile.txt", "a") # f.write("Now the file has more content!") # f.close() # # f = open("demofile.txt", "r") # print(f.read()) # f.close() #Q8 # f = open("demofile3.txt", "w") # f.write("Woops! I have deleted the content!") # f.close() # f = open("demofile3.txt", "r") # print(f.read()) #Q9 # f = open("myfile.txt", "x") # f = open("myfile1.txt", "w") #Q10 # import os # os.remove("demofile.txt") # # import os # if os.path.exists("demofile.txt"): # os.remove("demofile.txt") # else: # print("The file does not exist") #Q11 # f = open("test.txt", "r") # print(f.read()) #Q12 # readFile = open("test.txt", "r") #Q13 names = [] marks = [] readFile = open("test.txt", "r") for line in readFile: name,mark = line.split() names.append(name) marks.append(float(mark)) readFile.close() print(names, marks) #Q14 totalMark = 0 studentCount = 0 for i in marks: totalMark += i studentCount += 1 print(totalMark) #Q15 # newName = input("Please enter new student name: ") # while True: # try: # newMark = float(input("Please enter his mark in number: ")) # break # except ValueError: # print("Oh, you have entered the mark wrongly! Please enter the mark in number!") # continue #Q16 class MarkStudent: def calAverage(totalMark, count): average = totalMark / count print(average) MarkStudent.calAverage(totalMark,studentCount)
b78ec391ca8bbc6943de24f6b4862c8793e3cc14
cat-holic/Python-Bigdata
/03_Data Science/2.Analysis/3.Database/2.db_insert_rows.py
1,218
4.375
4
# 목적 : 테이블에 새 레코드셋 삽입하기 import csv import sqlite3 # Path to and name of a CSV input file input_file = "csv_files/supplier_data.csv" con = sqlite3.connect('Suppliers.db') c = con.cursor() create_table = """CREATE TABLE IF NOT EXISTS Suppliers( Supplier_Name VARCHAR(20), Invoice_Number VARCHAR(20), Part_Number VARCHAR(20), Cost FLOAT, Purchase_Date);""" c.execute(create_table) # Read the CSV file # Insert the data into the Suppliers table file_reader = csv.reader(open(input_file, 'r'), delimiter=',') header = next(file_reader, None) # Header 건너뛰고 data만 접근 하기 위함 for row in file_reader: data = [] for column_index in range(len(header)): data.append(row[column_index]) print(data) c.execute("INSERT INTO Suppliers VALUES (?,?,?,?,?);", data) con.commit() print("데이터 베이스 삽입 완료 \n\n") # Query the Suppliers table output = c.execute("SELECT * FROM Suppliers") rows = output.fetchall() for row in rows: output = [] for column_index in range(len(row)): output.append(row[column_index]) print(output)
1e8d40ea899ea7a2913c0fd03325bb4d2f14c2e9
cat-holic/Python-Bigdata
/01_jumptopy/Jump_to_Python/chap04/20180509(수)/sandwich.py
751
3.515625
4
def make_sandwich(order_list): print("샌드위치를 만들겠습니다.") for i in order_list: print("%s 추가합니다"%i) print("\n여기 주문하신 샌드위치 만들었습니다. 맛있게 드세요.") def input_ingredient(message): if message == 1: order_list = [] while True: order = input("안녕하세요. 원하시는 재료를 입력하세요: ") if order == "종료": print() break else: order_list.append(order) make_sandwich(order_list) wait_message = int(input("안녕하세요. 저희 가게에 방문해 주세서 감사합니다.\n1. 주문\n2. 종료\n입력 : ")) input_ingredient(wait_message)
44d5f96ed08732ddc8b79b07f05846dc91ff51af
cat-holic/Python-Bigdata
/01_jumptopy/Jump_to_Python/chap03/Rhombus-v3.py
1,305
3.75
4
#coding: cp949 print(" α׷ v3") while True: floor = int(input("ִ غ ũ⸦ Էϼ.(, Ȧ Է. 0 Է½ ) : ")) if floor == 0:break maxFloorline = int((floor+1)/2) maxBorderline = floor+4 i=0 print(" ",end="") while i!=maxBorderline-3: print("-",end="") i+=1 print() i=0 while i!=maxFloorline: print("| ",end="") blank = maxFloorline - i - 1 star = 0 while blank != 0: print(" ", end="") blank-=1 while star != (2*i+1): print("*",end="") star+=1 while blank !=maxFloorline-i-1: print(" ",end="") blank+=1 print(" |") i+=1 i=maxFloorline-1 while i != 0: print("| ",end="") blank = maxFloorline-i star = 2*i-1 while blank !=0: print(" ",end="") blank-=1 while star != 0: print("*",end="") star-=1 while blank != maxFloorline - i: print(" ",end="") blank += 1 print(" |") i-=1 i=0 print(" ",end="") while i!=maxBorderline-3: print("-",end="") i+=1 print()
bea0678a341e3fc8bc10aeaa0f3f3ff5cce2eb43
akash3927/python-
/list.py
1,454
4.375
4
#lists companies=["mahindra","swarajya","rucha","papl"] #1 print(companies) #2 print(companies[0]) #3 print(companies[1]) #4 print(companies[1].title()) #replacing companies[0]="force" print(companies) #adding or appending companies.append("mahindra") print(companies) #removing del companies[0] print(companies) #sort companies.sort() print(companies) ###### print("Here is the original list:") print(companies) print("\nHere is the sorted list:") print(sorted(companies)) print("\ nHere is the original list again:") print(companies) #reverse function companies.reverse() print(companies) #length print(len(companies)) ####working with the lists industries=["mahindra","swarajya","rucha","papl"] for industry in industries: print(industry) print(industry.title()+",is good company for learning") print("it s giving chance to freshers to built thier carrier") ##########or loop for numbers for value in range(1,5): print(value) ####### numbers=list(range(1,6)) print(numbers) #even numbers evennos=list(range(2,40,2)) print(evennos) ####oddnos oddnos=list(range(1,30,2)) print(oddnos) #### nos=[1,2,3,4,5,6,7,8,9] print(min(nos)) print(max(nos)) print(sum(nos)) #### squares=[square**2 for square in range(10,16)] print(squares) ##### family=["mother","father","brother","sister","me"] print(family[1:4]) print(family[:4]) myfamily=family[:] print(myfamily)
e90cd19052685e2143da03934d17bcfc3daa2140
OmkarShidore/FacialRecognitionAttendance
/Facial Recognition (GUI and Server)/tktest.py
1,473
3.828125
4
from tkinter import * #main window= Tk() # def click(): entered_text=textentry.get()#this will collect the text from textentry box if (len(entered_text))==0: pass else: output.delete(0.0,END) try: defination=my_compdictionary[entered_text] except: defination="sorry no word found" output.insert(END,defination) def close_window(): window.destroy() exit() #title window.title("Upasthiti") #background #Label(window,bg="black").grid(row=0,column=0,sticky=W) #create a text entry box Label(window,text="Enter the word you wold like to defination for", bg="black",fg="white",font="none 12 bold").grid(row=1,column=0,sticky=W) #textbox textentry=Entry(window,width=20,bg="white") textentry.grid(row=2,column=0,sticky=W) #submit button Button(window,text="Submit",width=6,command=click).grid(row=3,column=0,sticky=W) #create label Label(window,text="Defination",bg="black",fg="white",font="none 12 bold").grid(row=4,column=0,sticky=W) #output in window output=Text(window,width=75,height=6,wrap=WORD,background="white") output.grid(row=5,columnspan=2,sticky=W) #dictionary my_compdictionary={ 'algorithm':'Step by 1','bug':'piece of code' } #exit label Label (window,text="click to exit",bg="black",fg="white",font="none 12 bold").grid(row=6,column=0,sticky=W) #exit button Button(window,text="Exit", width=14,command=close_window).grid(row=7,column=0,sticky=W) window.mainloop()
43757f10da1a76545a1fe22bdecc6fbfcaf80cfa
apriantoa917/Python-Latihan-DTS-2019
/LIST/list - find number.py
263
3.875
4
# 3.1.6.8 Lists - more details myList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] toFind = 5 found = False for i in range(len(myList)): found = myList[i] == toFind if found: break if found: print("Element found at index", i) else: print("absent")
ac26196e5daed22f4972565f957dff6f6c087525
apriantoa917/Python-Latihan-DTS-2019
/OOP/OOP - import class object/class - stack.py
476
3.828125
4
# 6.1.2.4 A short journey from procedural to object approach class Stack: # defining the Stack class def __init__(self): # defining the constructor function, constructor diawali dengan __init__() print("Hi!") stackObject = Stack() # instantiating the object # 6.1.2.5 A short journey from procedural to object approach class Stack1: def __init__(self): self.stackList = ['1','2'] stackObject1 = Stack1() print(len(stackObject1.stackList))
edcc3cce2a1f416279ee73c73b15f596d7e850a7
apriantoa917/Python-Latihan-DTS-2019
/EXCEPTIONS/try except - example 4.py
1,305
3.8125
4
# 5.1.5.2 The anatomy of exceptions # source image : https://edube.org/uploads/media/default/0001/01/0ee75473d85349d36925771423976c94c08ddbf1.png # ZeroDivisionError berada di dalam ArithmethicError, jika exceptions menggunkan class yang lebih general maka cakupan lebih banyak # lihat hasil di bawah print('percobaan 1 : ZeroDivisionError') try: y = 1/0 except ZeroDivisionError: print('ooooppps') print() print('percobaan 2 : ArithmeticError') try: y = 1/0 except ArithmeticError: print('ooooppps') # keduanya (percobaan 1&2) bisa menjalankan kode yang ada di dalam exceptions karena kelas ZeroDivisionError berada dalam ArithmeticError try: y = 1 / 0 except ZeroDivisionError: print("Zero Division!") except ArithmeticError: print("Arithmetic problem!") print("THE END.") # kode dibawah eror karena order / urutan aritmetic merupakan class general dari zerodivision (terdeteksi kelas aritmetik lebih luas harus diletakkan setelah klass spesifik (dibawah except zero division)) # try: # y = 1 / 0 # except ArithmeticError: # print("Arithmetic problem!") # except ZeroDivisionError: # print("Zero Division!") # print("THE END.") # ketika kedua kondisi memenuhi untuk masuk ke except, urutan menentukan. program akan menjalankan kode exception terdekat
13712aa9ee6581cdc87c817cb630001117e159b7
apriantoa917/Python-Latihan-DTS-2019
/LOOPS/loops - for examples.py
415
4.15625
4
#3.1.2.5 Loops in Python | for # for range 1 parameter -> jumlah perulangan for i in range(10) : print("perulangan ke",i) print() # for range 2 parameter -> angka awal perulangan, angka akhir perulangan a = 1 for i in range(3,10) : print(i," = perulangan ke",a) a+=1 print() # for range 3 parameter -> angka awal, angka akhir, pertambahan / iterasi for i in range(3,20,4) : print(i) print()
2de1d64d9050ce148da40aec103d0eac7dabfe20
apriantoa917/Python-Latihan-DTS-2019
/OOP/OOP - Methods/examples 2.py
849
3.84375
4
# 6.1.4.3 OOP: Methods class Classy: def __init__(self, value): self.var = value obj1 = Classy("object") print(obj1.var) # constructor : #tidak dapat mengembalikan nilai, karena ini dirancang untuk mengembalikan objek yang baru dibuat dan tidak ada yang lain; # # tidak dapat dipanggil secara langsung baik dari objek atau dari dalam kelas (Anda dapat memanggil konstruktor dari superclasses objek mana pun, class Classy2: def __init__(self, value = None): self.var = value obj1 = Classy2("Ini sebuah value") obj2 = Classy2() print(obj1.var) print(obj2.var) class Classy3: def visible(self): print("visible") def __hidden(self): print("hidden") obj = Classy3() obj.visible() try: obj.__hidden() except: print("failed") obj._Classy3__hidden() # untuk mengakses method private
e84ee8da19f091260bef637a5d7104b383f981a5
apriantoa917/Python-Latihan-DTS-2019
/LOOPS/loops - pyramid block.py
366
4.28125
4
# 3.1.2.14 LAB: Essentials of the while loop blocks = int(input("Enter the number of blocks: ")) height = 0 layer = 1 while layer <= blocks: blocks = blocks - layer #jumlah blok yang disusun pada setiap layer , 1,2,3... height += 1 #bertambah sesuai pertambahan layer layer += 1 print("The height of the pyramid:", height)
a0eb44d5616b3d273426c5a7397c773a4a558c46
apriantoa917/Python-Latihan-DTS-2019
/TUPLES/tuples - example.py
691
4.21875
4
# 4.1.6.1 Tuples and dictionaries # tuple memiliki konsep sama dengan list, perbedaan mendasar tuple dengan list adalah : # Tuples # - tuple menggunakan (), list menggunakan [] # - isi dari tuple tidak dapat dimodifikasi setelah di inisialisasi, tidak dapat ditambah (append) atau hapus (delete) # - yang dapat dilakukan tuple : # - len() # - + (tambah), menambah elemen baru di dalam tuple (konsep append di list) # - * (multiple), menggandakan isi tuple sejumlah n dengan isi yang sama # - in, not in. sama dengan list myTuple = (1, 10, 100) t1 = myTuple + (1000, 10000) t2 = myTuple * 3 print(len(t2)) print(t1) print(t2) print(10 in myTuple) print(-10 not in myTuple)
d78e0d79180c505e8d77b77aef43b5fbf14b8c64
apriantoa917/Python-Latihan-DTS-2019
/LIST/list - hat list.py
241
3.890625
4
# 3.1.4.6 LAB: The basics of lists hatList = [1, 2, 3, 4, 5] # This is an existing list of numbers hidden in the hat. indices = int(input("enter a new number : ")) hatList[2] = indices del hatList[4] print(len(hatList)) print(hatList)
0568e98654b7e85c3856519194c5f9b50f376f21
apriantoa917/Python-Latihan-DTS-2019
/nature of string/string sequence.py
291
4.03125
4
# 5.1.8.6 The nature of strings in Python # indexing : memerankan string sebagai elemen index yang dapat diakses str1 = 'sebuah kata' for i in range(len(str1)): print(str1[i],end=' ') print() #iterating : memanggil string berdasarkan urutannya for str2 in str1: print(str2,end=' ')
02fc00ec75f78c552b47cf4376c8d655b1012cc6
apriantoa917/Python-Latihan-DTS-2019
/LOOPS/loops - the ugly vowel eater.py
282
4.21875
4
# 3.1.2.10 LAB: The continue statement - the Ugly Vowel Eater userWord = input("Enter the word : ") userWord = userWord.upper() for letter in userWord : if (letter == "A" or letter == "I" or letter == "U" or letter == "E" or letter == "O"): continue print(letter)
b4816f6cf26d87c58b12a15fc379748e0c167db9
hyunsooryu/Algorithm
/GCD_3_WAYS_BRUTEFORCE_RECURSIVE_ITERATIVE_in_python.py
402
3.609375
4
def GCD_R(A, B): if not(B): return A return GCD_R(int(B), int(A % B)) def GCD_BRUTE_FORCE(A, B): g_c_d = 1 for i in range(2, min(A, B) + 1): if A % i == 0 and B % i == 0: g_c_d = i return g_c_d def GCD_I(A, B): while B > 0: tmp = A A = B B = int(tmp % A) return A print("HI") print(GCD_R(14,26)); print(GCD_BRUTE_FORCE(128,256)) print(GCD_I(128,256))
a177c5db9ef4c8144c44298ca08aaf365169577c
hyunsooryu/Algorithm
/2_HowToSolveArrayProblem_TwoNumsNegative.py
322
3.6875
4
def maxTwoDiff(nums): MAX = nums[0] MIN = nums[0] for i in nums: if i > MAX: MAX = i if i < MIN: MIN = i return MAX - MIN def main(): print(maxTwoDiff([2, 8, 19, 37, 4, 5, 12, 50, 1, 34, 23])) # should return 49 if __name__ == "__main__": main()
7eede1c69baa25dc60fa9127efa24817b627ddac
SharmaManav/CMPS101
/hw2.py
5,388
3.75
4
# -*- coding: utf-8 -*- # Manav Sharma msharma7 # Jeffrey Chan jchan40 """ Spyder Editor This is a temporary script file. """ import numpy as np import timeit import matplotlib.pyplot as plt import scipy def selectionsort(A): for i in range (len(A)): minIndex = i #set the minimum index i for j in range (i, len(A)): #iterate through unsorted part of array if A[j] < A[minIndex]: minIndex = j #find the smallest element and set it to j if minIndex != i: A[i], A[minIndex] = A[minIndex], A[i] #swap the element into its sorted place return(A) def insertionsort(A): for i in range(len(A)): j = i-1 #for looping through all items to i's left while A[j] > A[j+1] and j>=0: A[j], A[j+1] = A[j+1], A[j] #swap the elements if the one to the right is larger j = j-1 return(A) def mergesort(A): n = len(A) #initialize n as the length of A if (n <= 1): return A middle = n//2 left = A[:middle] #declare left for all elements to the left of middle right = A[middle:] #declare right for all elements to the right of middle l = mergesort(left) r = mergesort(right) #recursive call to mergesort return merge(l, r) def merge(B, C): B = np.append(B,float('inf')) C = np.append(C,float('inf')) #adding infinity to the end of B,C D = [] i = j = 0 while B[i] < (float('inf')) or C[j] < (float('inf')): if B[i] < C[j]: #if the element of B is less than the element of C D.append(B[i]) #Add the element of B to the end of D i = i+1 else: D.append(C[j]) #Add the element of C to the end D j = j + 1 return D ''' np.random.seed(0) array = np.random.permutation(1000000) intime = timeit.timeit(lambda: insertionsort(array),number=1) mergetime = timeit.timeit(lambda: mergesort(array),number=1) seltime = timeit.timeit(lambda: selectionsort(array),number=1) print("insertion time: ", intime) print("merge time: ", mergetime) print("selection time: ", seltime) x = np.arange(100,10100,100) #fully sorted y = np.arange(10100,100,-100) #inverted result2 = [] result = [] meresult = [] meresult2 = [] selresult = [] selresult2 = [] for i in range(len(x)): #fully sorted t = timeit.timeit(lambda: insertionsort(np.arange(1,x[i])),number = 1) ts = timeit.timeit(lambda: selectionsort(np.arange(1,x[i])),number = 1) tm = timeit.timeit(lambda: mergesort(np.arange(1,x[i])),number = 1) result.append(t) meresult.append(tm) selresult.append(ts) i = i +1 print(i) for i in range(len(y)): #inverted t = timeit.timeit(lambda: insertionsort(np.arange(y[i],1,-1)),number = 1) ts = timeit.timeit(lambda: selectionsort(np.arange(y[i],1,-1)),number = 1) tm = timeit.timeit(lambda: mergesort(np.arange(y[i],1,-1)),number = 1) result2.append(t), meresult2.append(tm) selresult2.append(ts) i = i + 1 print(i) x = np.arange(10,1000,10) number 4 plot i=100 j=0 inlist = [] merlist = [] selist = [] avg = 0 merAvg = 0 selAvg = 0 while (i <= 5000): print(i) while (j <= 100): np.random.seed(j) array= np.random.permutation(i) #print (array) avg += timeit.timeit(lambda: insertionsort(array),number = 1) merAvg += timeit.timeit(lambda: mergesort(array),number = 1) selAvg += timeit.timeit(lambda: selectionsort(array),number = 1) j += 1 avg = avg / 100 merAvg = merAvg / 100 selAvg = selAvg / 100 merlist.append(merAvg) selist.append(selAvg) inlist.append(avg) avg = 0 i = i + 100 j = 0 x = np.arange(100,5100,100) plt.plot(x,inlist,'g-',label = "insertion-sort") plt.plot(x,merlist,'b-',label = "mergesort") plt.plot(x,selist, 'y-',label= "selectionsort") plt.xlabel('Input Size') plt.ylabel('Average Time') plt.title("Average Sorting Times on Random Arrays") plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.) plt.show() plot 4-5 plt.plot(x,result,'g-',label = "insertion-sort") plt.plot(x,meresult,'b-',label="mergesort") plt.plot(x,selresult,'y-',label="selectionsort") plt.xlabel('numElements') plt.ylabel('times') plt.title("Fully Sorted") plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.) plt.show() plt.plot(y,result2,'g-',label = "insertion-sort") plt.plot(y,meresult2,'b-',label="mergesort") plt.plot(y,selresult2,'y-',label="selectionsort") plt.xlabel('numElements') plt.ylabel('times') plt.title("Reverse Sorted") plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.) plt.show() plot 1-3 plt.plot(x,result,'g-',label = "sorted") plt.plot(y,result2,'b-',label = "reverse") plt.xlabel('numElements') plt.ylabel('insertiontimes') plt.title("InsertionSort") plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.) plt.show() plt.plot(x,meresult,'g-',label = "sorted") plt.plot(y,meresult2,'b-',label = "reverse") plt.xlabel('numElements') plt.ylabel('Mergetimes') plt.title("MergeSort") plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.) plt.show() plt.plot(x,selresult,'g-',label = "sorted") plt.plot(y,selresult2,'b-',label= "reverse") plt.xlabel('numElements') plt.ylabel('Selecttimes') plt.title("SelectionSort") plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.) plt.show() '''
70320362f2dcf8277c59efd3a1b104fca0c0b784
100ballovby/6V_Lesson
/IV_term/05_lesson_2505/01_star_functions.py
1,387
4.3125
4
''' Чтобы передать функции неограниченное количество элементов, необходимо использовать звездочки. *args - список аргументов **kwargs - список именованных аргументов На примере задачи. Дан список чисел, длина списка неизвестна, сложите все числа в списке между собой. Верните сумму. ''' from random import randint n = [] for number in range(randint(1, 70)): n.append(randint(-100, 100)) print(n) def sum_list(*numbers): '''Функция получает любое количество аргументов''' print(type(numbers)) s = 0 for i in numbers: s += i return s print(sum_list(4, 6, 7, 2)) # можно указывать любое количество чисел print(sum_list(*n)) # распаковка списка (достать из него только числа и убрать скобки) def smth(**kwargs): '''Именованные аргументы в неограниченном количстве''' print(type(kwargs)) print(kwargs) for key, value in kwargs.items(): print(f'Key: {key}\nValue: {value}') smth(name='Jagor', Age=26, Hobby='Programming', Pet='Cat')
3091db7ad4567ec16d070bb42bece1340cec2cf3
100ballovby/6V_Lesson
/lesson_0902/03_list_sorting.py
532
4.0625
4
''' Сортировка списка. Метод .sort() располагает элементы списка от меньшего к большему. ''' cars = ['toyota', 'skoda', 'mercedes', 'seat', 'audi'] print('Список ДО сортировки', cars) cars.sort() # обычная сортировка print('Список ПОСЛЕ сортировки', cars) cars.sort(reverse=True) # сортировка в обратном порядке print('Сортировка в обратном порядке', cars)
2225f0786213292a5106ca625af0a65885d2ebbb
100ballovby/6V_Lesson
/IV_term/02_lesson_2704/00_hw_solution.py
512
3.859375
4
# simple message1 = input('Input smth: ') num1 = [] for letter in message1: if letter.isnumeric(): num1.append(letter) print(num1) # middle message2 = input('Input smth: ') num2 = [] for letter in message2: try: num2.append(int(letter)) except: pass print(num1) # hard import string numbers = string.digits # 0123456789 message3 = input('Input smth: ') num3 = [] for i in range(len(message3)): if message3[i] in numbers: num3.append(message3[i]) print(num3)
c73e20200d1fe03e2746432dc925cc63361fd5a4
100ballovby/6V_Lesson
/lesson_2601/task0.py
753
4.3125
4
''' Task 0. Систему работы с багажом для аэропорта. Багаж можно поместить в самолет если: Его ширина < 90 см; Его высота < 80 см; Его глубина < 40 см; ИЛИ Ширина + высота + глубина < 160. ''' w = float(input('Введите ширину багажа: ')) h = float(input('Введите высоту багажа: ')) d = float(input('Введите глубину багажа: ')) if (w > 0 and h > 0 and d > 0) and ((w <= 90 and h <= 80 and d <= 40) or (w + h + d <= 160)): print('Багаж можно поместить в самолет!') else: print('Багаж нельзя поместить в самолет!')
2d01844b3781a61af499ab1f1be75892f03cdfcf
100ballovby/6V_Lesson
/lesson_0203/02_bigger_and_smaller.py
782
4
4
'''Самый большой и самый маленький''' n = [123, 12, 56, 34, 87, 9, 10, 413] max = n[0] # здесь храню максимум min = n[0] # здесь храню минимум for number in n: # перебираю числа в списке if max < number: # если число из списка больше максимума max = number # переназначить максимум if min > number: # если число из списка меньше минимума min = number # переназначить минимум # повторять, пока числа не закончатся print('Самый большой элемент: ', max) print('Самый маленький элемент: ', min)
a57cba9867327db26740cb194168c8c33de8e329
100ballovby/6V_Lesson
/lesson_2601/bool_condition.py
204
3.609375
4
''' a = True # 1 b = False # 0 print(a > b) # True ''' ex1 = True ex2 = True ex3 = True ex4 = True mid = 4.5 if (ex1 and ex2 and ex3 and ex4) and (mid > 4): print('OK') else: print('Ne ok')
fd09482d05ff8e7a0eebed43f3159153792a5834
100ballovby/6V_Lesson
/IV_term/03_lesson_0405/shapes.py
1,192
4.34375
4
''' Параметры: 1. Черепашка 2. Длина стороны 3. координата х 4. координата у 5. Цвет ''' def square(t, length, x, y, color='black'): """Функция рисования квадрата""" t.goto(x, y) # переместить черепашку в x, y t.down() # опустить перо (начать рисовать) t.color(color) # задать черепашке цвет через параметр (по умолчанию - черный) for i in range(4): t.fd(length) t.rt(90) t.up() # поднять перо (перестать рисовать) def triangle(t, length, x, y, thickness, color='black'): t.goto(x, y) t.pensize(thickness) t.down() t.color(color) for i in range(3): t.fd(length) t.lt(120) t.up() t.pensize(1) def rectangle(t, l1, l2, x, y, color='black'): t.goto(x, y) t.color(color) t.down() for i in range(2): # рисую длинную сторону t.fd(l1) t.rt(90) # рисую короткую сторону t.fd(l2) t.rt(90) t.up()
0cf3ed5712c6fddad0759d449d56f434cc1ff3aa
hibruna/Sistemas01
/Exercício c.py
500
3.796875
4
#Desejo que minha função receba 2 valores e retorne sucesso caso seja possível fazer a divisão Objetivo do teste: #Verificar se a divisão entre 2 valores numéricos retorna sucesso #d. Caso from unittest import TestCase def divisao(valor1, valor2): return valor1 / valor2 class validadivisao(TestCase): def testedivisao(self): self.assertTrue(divisao(10, 2)) def divisao(valor1, valor2): try: valor1 / valor2 return True except: return False
3822fece34f2135dfc9392c03b14a44bf93b374c
thepr0blem/spaceAI
/game_classes.py
11,949
3.78125
4
""" Game classes: - SpaceShip - Obstacle - Population - collection of Spaceships - Pilot - "brain" of SpaceShip, decides on what movement should be done by SpaceShip when in non-human player mode """ import random as rd import arcade import numpy as np from settings import * from ext_functions import softmax, relu, cross_over, mutate, add_score # ------------------------------------------------------------------------------------------------------------------- # class Population: """ Collection of SpaceShip objects, which together with their pilots will be evolving as playing Methods: - populate - generates collection of POPULATION_SIZE ships - erase_history - restars population by cleaning ships_list and performing fresh initialization - evolve - performs evolution algorithm steps: selection, crossover and mutation and reassigns Pilots genotypes - ressurect_ships - resurrects all ships in population and reposition them to the middle of the screen - check_if_all_dead - returns TRUE if all ships are dead - evolve - performs population evolution - selection - sorts pilots by their fitness """ def __init__(self): # Population parameters self.generation_id = 0 self.all_dead = False self.living_ships = POPULATION_SIZE # Population ship lists self.ships_list = [] self.prev_gen_ships_list = [] self.top_ships = [] def populate(self): """Generate population with ships and randomly intialized brains/pilots. """ self.living_ships = POPULATION_SIZE for i in range(POPULATION_SIZE): self.ships_list.append(SpaceShip(320, 50, 0, 15)) def erase_history(self): """Restart population by cleaning ships_list and performing fresh initialization. """ self.ships_list = [] self.prev_gen_ships_list = [] self.top_ships = [] self.generation_id = 0 self.populate() def ressurect_ships(self): """Resurrects all ships in population and reposition them to the middle of the screen. """ for ship in self.ships_list: ship.alive = True ship.position_x = int(SCREEN_WIDTH / 2) self.all_dead = False def check_if_all_dead(self): """Checks if all ships are dead. """ alive_ships_num = 0 self.all_dead = True for ship in self.ships_list: if ship.alive: self.all_dead = False alive_ships_num += 1 self.living_ships = alive_ships_num return self.all_dead def evolve(self): """Performs evolution algorithm steps: selection, crossover and mutation and reassigns Pilots' genotypes. """ # --- Selection --- self.selection() # --- Evolution --- # Top ships are survivors, they go to next generation for i in range(int(SELECTION_RATE * POPULATION_SIZE)): self.ships_list[i] = self.top_ships[i] # Generate "children" for the next generation by crossing over randomly chosen parents from top_ships for i in range(int(SELECTION_RATE * POPULATION_SIZE), POPULATION_SIZE): new_gen_a, new_gen_b, new_bias_a, new_bias_b = cross_over(rd.choice(self.top_ships).pilot, rd.choice(self.top_ships).pilot) new_gen_a, new_gen_b, new_bias_a, new_bias_b = mutate(new_gen_a, new_gen_b, new_bias_a, new_bias_b) self.ships_list[i].pilot.genotype_a = new_gen_a self.ships_list[i].pilot.genotype_b = new_gen_b self.ships_list[i].pilot.bias_a = new_bias_a self.ships_list[i].pilot.bias_b = new_bias_b def selection(self): """Sorts pilots by their fitness and assigns the best units to top_ships variable""" # --- Selection --- # Sort ships by their performance (measured by pilot's score) self.prev_gen_ships_list = [] self.prev_gen_ships_list = self.ships_list[:] self.prev_gen_ships_list.sort(key=lambda c: c.pilot.fitness, reverse=True) # Assign best scorers to top_ships self.top_ships = [] self.top_ships = self.prev_gen_ships_list[:int(SELECTION_RATE * POPULATION_SIZE)] # ------------------------------------------------------------------------------------------------------------------- # class Pilot: """Pilot (or brain) for SpaceShip class. Its genes store information on weights for nerual network that make a decision on next movement of the ship. """ def __init__(self): # Random initialization of weights for neural network using two arrays: # Layer 1 self.genotype_a = np.random.randn(NEURONS, 3) self.bias_a = np.random.randn(NEURONS, 1) * 0.5 # Layer 2 self.genotype_b = np.random.randn(3, NEURONS) self.bias_b = np.random.randn(3, 1) * 0.5 # Pilot attributes self.pilot_score = 0 self.fitness = 0 self.stay_decs_count = 0 self.move_decs_count = 0 def decide(self, x_ship, gap_x1, gap_x2): """ Making decision on which direction ship moves using neural network. Properties of neural network: Input: x coordinates of the ship and closest obstacle (x_ship, gap_x1, gap_x2) Structure of NN: - 3 input values - 1 hidden layer with n neurons (n -> see NEURONS var in settings) - 3 output values Output: 0 - STAY, 1 - LEFT, 2 - RIGHT """ input_lay = np.array((x_ship, gap_x1, gap_x2)).reshape(3, 1) / SCREEN_WIDTH hid_lay = relu(np.dot(self.genotype_a, input_lay) + self.bias_a) output = softmax(relu(np.dot(self.genotype_b, hid_lay) + self.bias_b)) decision = np.argmax(output) if decision == 0: self.stay_decs_count += 1 elif decision == 1: self.move_decs_count += 1 elif decision == 2: self.move_decs_count += 1 return decision def calc_fitness(self): """ - Calculates pilot's fitness based on his current score and proportion of 'stay' decisions to total decisions. - The latter is the tweak implemented to eliminate ships which perform well, but do many neccessary movements. Additional points are granted when ships have scored > 3 points. """ # Relative part of stay decisions if self.pilot_score > 3: moves_distr_score = self.stay_decs_count / (self.move_decs_count + self.stay_decs_count) else: moves_distr_score = 0 self.fitness = self.pilot_score + add_score(moves_distr_score, STAY_FRAC) # ------------------------------------------------------------------------------------------------------------------- # class SpaceShip: """ Spaceship game class. Methods: - draw - draws the spaceship - update - updates current state of spaceship e.g. position """ def __init__(self, position_x, position_y, change_x, h_width): # Geometrical params self.position_x = position_x self.position_y = position_y self.change_x = change_x self.half_width = h_width self.center_y = self.position_y + 20 # In-game params self.alive = True self.pilot = Pilot() def draw(self): """Draws the spaceship. """ if self.alive: arcade.draw_point(self.position_x, self.position_y + 20, arcade.color.BLACK, 5) texture = arcade.load_texture("images/spaceShips_008.png") scale = .5 arcade.draw_texture_rectangle(self.position_x, self.position_y + 20, scale * texture.width, scale * texture.height, texture, 0) def update(self, ai_state, gap_x1, gap_x2): """Updates current status of spaceship. """ # --- MOVEMENT --- # If non-human player decides on next movement # Rules applied: 0 - STAY, 1 - LEFT, 2 - RIGHT if ai_state: if self.pilot.decide(self.position_x, gap_x1, gap_x2) == 0: self.position_x += 0 elif self.pilot.decide(self.position_x, gap_x1, gap_x2) == 1: self.position_x += - MOVEMENT_SPEED else: self.position_x += MOVEMENT_SPEED # When human player decides on next movement else: # Move left or right self.position_x += self.change_x # --- COLLISIONS WITH SCREEN EDGES --- if self.position_x < self.half_width: self.position_x = self.half_width if self.position_x > SCREEN_WIDTH - self.half_width: self.position_x = SCREEN_WIDTH - self.half_width # ------------------------------------------------------------------------------------------------------------------- # class Obstacle: """Obstacle game class. Methods: - draw - draws space obstacle - respawn - respawn obstacle "above" the visibile screen area after passing by the spaceship y position - update - updates current state of obstacle (moves obstacle down the screen) - level_up - increase obstacle vertical movement every x points """ def __init__(self, position_y): # --- GAP generation --- # left edge x_position random generation: self.gap_x1 = rd.randrange(0, 440, 1) # right edge x_position random generation to be between 100 to 200 pixels from left x_position self.gap_x2 = rd.randrange(self.gap_x1 + 100, self.gap_x1 + 200, 1) self.position_y = position_y self.thickness = 20 self.color = arcade.color.ANTI_FLASH_WHITE self.is_active = True self.is_textured = True self.speed = OBSTACLE_SPEED def draw(self): """Draw space obstacle. """ # --- TEXTURED RECTANGLE --- if self.is_textured: obstacle_texture = arcade.load_texture("images/spaceBuilding_016.png") arcade.draw_texture_rectangle(0.5 * self.gap_x1, self.position_y, self.gap_x1, self.thickness, obstacle_texture) arcade.draw_texture_rectangle(0.5 * (SCREEN_WIDTH + self.gap_x2), self.position_y, SCREEN_WIDTH - self.gap_x2, self.thickness, obstacle_texture) # --- WHITE RECTANGLE --- else: arcade.draw_rectangle_filled(0.5 * self.gap_x1, self.position_y, self.gap_x1, self.thickness, self.color) arcade.draw_rectangle_filled(0.5 * (SCREEN_WIDTH + self.gap_x2), self.position_y, SCREEN_WIDTH - self.gap_x2, self.thickness, self.color) def update(self, delta_time): """Move obstacle downwards. """ # Move the obstacle if self.is_active: self.position_y -= self.speed * delta_time # If obstacle "below" the screen, respawn if self.position_y < 0: self.respawn() def respawn(self): """Respawn obstacle after going out of the screen. """ self.gap_x1 = rd.randrange(0, 440, 1) self.gap_x2 = rd.randrange(self.gap_x1 + 100, self.gap_x1 + 200, 1) self.position_y = SCREEN_HEIGHT + OBSTACLE_FREQ def level_up(self, score): """Accelerate every 100 points""" if score % 50 == 0: self.speed += 50 # ------------------------------------------------------------------------------------------------------------------- #
44238507b6d8b885054912b93cbdd799ddf73b46
burtr/reu-cfs
/reu-cfs-2018/svn/cipher/crack-shift.py
1,721
3.59375
4
import string import sys import os import argparse import numpy as np # # crack-shift.py # # author: # date: # last update: # args_g = 0 # args are global def frequencycount(s): """ input: string of lowercase letters return: an integer array of length 26, where index i has the count of occurances of the i-th letter (where a is the 0th letter and z is the 25th letter) """ count = np.zeros(26, dtype=int) # code return count def dotproduct_twist(s,t,twist): """ input: s, t array of integer twist, and integer return: the dot product between s and t when t is "rolled forward" by the amount twist """ # code return 0 def crack_shift(ct,rt): """ input: ct: the cipher text, lower case letters rt: the reference test, lower case letters (for frequency count) return: the shift key that was used to encode the cipher text """ # code return "a" def get_statistics(filename): f = open(filename,"r") p = "" ; for line in f: for c in line : if c.isalpha() : p = p + c.lower() ; f.close() ; return frequencycount(p) ; def parse_args(): parser = argparse.ArgumentParser(description="Cracks a shift cipher by freqency analysis.") parser.add_argument("reference_text", help="a text file sampling the letter frequence statistics") parser.add_argument("-v", "--verbose", action="store_true", help="verbose") return parser.parse_args() def main(argv): global args_g args_g = parse_args() fc = get_statistics(args_g.reference_text) if args_g.verbose: print (fc) ## gather plain text and format t_in = "" for line in sys.stdin: for c in line: if c.isalpha(): t_in += c x = crack_shift(fc,frequencycount(t_in)) print (x) main(sys.argv)
8735cfbd69ed580c6740fe9fc608c7328782f896
ealmuina/fuzzy-logic-evaluator
/fuzzy/defuzzifiers.py
1,609
4.03125
4
def centroid(func, step=0.1): """ Determine the center of gravity (centroid) of a function's curve :param func: Function object :param step: Distance between domain's values :return: Numeric value representing the domain's value which approximately corresponds to the centroid """ points = func.points(step) num, den = 0, 0 for x, y in points: num += x * y den += y return num / den def bisecter(func, step=0.1): """ Determine the center of area (splits the curve in two pices with the same area) (bisecter) of a function :param func: Function object :param step: Distance between domain's values :return: Numeric value representing the domain's value which approximately corresponds to the bisecter """ points = list(func.points(step)) area = sum(map(lambda p: p[1], points)) current = 0. for x, y in points: current += y if current >= area / 2: return x def mean_max(func, step=0.1): """ Determine the point which corresponds with the mean of the function's maximums :param func: Function object :param step: Distance between domain's values :return: Numeric value representing the domain's value which approximately corresponds to the mean of maximums """ points = func.points(step) maximums = [] k = 0 for x, y in points: if abs(y - k) < 1e-6: # y == k maximums.append(x) elif y > k: k = y maximums.clear() maximums.append(x) return sum(maximums) / len(maximums)
9227bf5285617689daf3ed5dd9507780c63bcc84
christoforuswidodo/Hacker-Rank
/NumberTheory/SherlockDivisor/SherlockDivisor.py
213
3.828125
4
def count_divisor_div_2(n): if (n <= 1): return 0; else: i = 2; while (i <= n): if (n % i == 0): return 1 + t = int(input()) for case in range(t): n = int(input()) print(count_divisor_div_2(n))
6612f0794f4af6fc91a783f7a90ff5ba60bf57f6
christoforuswidodo/Hacker-Rank
/Warmup/TaumBday/TaumBday.py
931
3.609375
4
def minPrice(black, white, b_price, w_price, shift_price): if b_price == w_price: return black*b_price + white*w_price else: min_price = min(b_price, w_price) if (min_price == b_price): sp_or_wp = min(b_price + shift_price, w_price) if sp_or_wp == (b_price + shift_price): init_price = black*b_price + white*(b_price+shift_price) else: init_price = black*b_price + white*w_price else: sp_or_wp = min(w_price + shift_price, b_price) if sp_or_wp == (w_price + shift_price): init_price = black*(w_price+shift_price) + white*w_price else: init_price = black*b_price + white*w_price return init_price t = int(input()) for case in range(t): candies = input().split() black = int(candies[0]) white = int(candies[1]) prices = input().split() b_price = int(prices[0]) w_price = int(prices[1]) shift_price = int(prices[2]) print(minPrice(black, white, b_price, w_price, shift_price))
cdbb2662d61edbf9a01005cebf4b926b4df003b5
deividasskiparis/calculator-1
/nershcalculator/nershcalculator.py
3,480
4.46875
4
class Calculator: """Calculator class object whose methods do addition, subtraction, multiplication, division, takes n root of a number and resets the stored memory to the initial value. """ def __init__(self, number=0): """Accepts a number as initial value and if none is specified, default is 0. Checks if the number is int or float type and if not raises and error. Also converts it into a float type. """ if type(number) in (int, float): self.starting_number = float(number) self.result = float(number) else: raise ValueError('Value has to be a real number') def reset(self): """Resets the calculator memory to the initial value.""" self.result = self.starting_number return self.result def add(self, number_to_add): """Checks if the given value is a real number. Adds it to the current number in calculator memory. """ if type(number_to_add) in (int, float): self.result = self.result + number_to_add return self.result else: raise ValueError('Value has to be a real number') def subtract(self, number_to_subtract): """Checks if the given value is a real number. Subtracts it from the current number in calculator memory """ if type(number_to_subtract) in (int, float): self.result = self.result - number_to_subtract return self.result else: raise ValueError('Value has to be a real number') def multiply(self, number_to_multiply): """Checks if the given value is a real number. Multiplies the current number in calculator memory by that number. """ if type(number_to_multiply) in (int, float): self.result = self.result * number_to_multiply return self.result else: raise ValueError('Value has to be a real number') def divide(self, number_to_divide_by): """Checks if the given value is a real number, after that checks if the value is 0, because division by zero is undifined. Current number in calculator memory is divided by that number. """ if type(number_to_divide_by) in (int, float): try: self.result = self.result / number_to_divide_by return self.result except ZeroDivisionError: raise ZeroDivisionError('Error. Can not divide by 0.') else: raise ValueError('Value has to be a real number') def root(self, n_root_of_a_number): """Checks if the current number in memory is <0 and if the n root number is even. If that is the case raises an error. Also checks if the n root number isn't a 0 because division by zero is undefined. Takes n root of a current number in calculator memory. """ if type(n_root_of_a_number) in (int, float): if self.result<0 and n_root_of_a_number%2==0: raise ValueError('Can not take even root out of negative numbers.') elif n_root_of_a_number==0: raise ZeroDivisionError('Error. Can not divide by 0.') else: self.result = self.result ** (1/n_root_of_a_number) return self.result else: raise ValueError('Value has to be a real number')
267c852b0d5c87ea91bdfabb2c29485717f0dd7d
rahulsangwn/DS-Algo-CTCI
/python/removeAdjacentDuplicates.py
633
3.65625
4
def remove(str): string = list(str) flag = 1 while flag == 1: i = 0 j = 1 flag = 0 flag2 = 0 while j < len(string): while j < len(string) and string[i] == string[j]: flag = 1 flag2 = 1 temp = string.pop(j) if flag2 == 1: string.pop(i) flag2 = 0 i = i + 1 j = j + 1 for i in range(len(string)): print(string[i], end="") def main(): testCases = int(input()) for i in range(testCases): remove(input()) print() main()