blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
d3646897390d6ad0266783a7124731478d834ff6
zhangler1/leetcodepractice
/链表/剑指 Offer 25. 合并两个排序的链表.py
601
3.734375
4
class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: p=ListNode() head=p p1=l1 p2=l2 while(p1!=None and p2!=None): if p1.val>=p2.val: p.next=p2 p2=p2.next p=p.next else: p.next=p1 p1=p1.next p=p.next if p1==None: p.next=p2 else: p.next=p1 return head.next
2b578291c9c7dc15177d5d6edaa4bbc7ff2ea975
RyLaney/userpass
/userpass/tests/test_module.py
1,834
3.515625
4
"""Test cases for module """ from unittest import TestCase import userpass.generate class TestModule(TestCase): """Test Case class for module """ def test_alphanumeric_is_string(self): """generate.alphanumeric should return a string """ item = userpass.generate.alphanumeric(64) self.assertIsInstance(item, str) def test_alphanumeric_string_length_is_12(self): """generate.alphanumeric(12) should be 12 chars long """ item = userpass.generate.alphanumeric(12) self.assertEqual(len(item), 12) def test_alphanumeric_string_length_is_64(self): """generate.alphanumeric(64) should be 64 chars long """ item = userpass.generate.alphanumeric(64) self.assertEqual(len(item), 64) def test_passphrase_is_string(self): """generate.passphrase should return a string """ item = userpass.generate.passphrase(4) self.assertIsInstance(item, str) def test_passphrase_number_of_words_is_4(self): """generate.passphrase(4) should have 4 words """ item = userpass.generate.passphrase(4) self.assertEqual(len(item.split()), 4) def test_passphrase_number_of_words_is_8(self): """generate.passphrase(8) should have 8 words """ item = userpass.generate.passphrase(8) self.assertEqual(len(item.split()), 8) def test_urlsafe_is_string_with_arg(self): """generate.token_urlsafe should return a string """ item = userpass.generate.token_urlsafe(64) self.assertIsInstance(item, str) def test_urlsafe_works_without_arg(self): """generate.token_urlsafe should return a string """ item = userpass.generate.token_urlsafe() self.assertIsInstance(item, str)
2d40827f1d3307b9966772ace3f48d98b8124eda
arakann/python-basics
/practice_2/vladimir_assertions.py
1,579
3.546875
4
''' Created on 12.03.2014 @author: vladimirbessmertnyj ''' def assert_equal(a, b): if a == b: return True else: raise Exception def assert_not_equal(a, b): if a != b: return True else: raise Exception def assert_true(x): if x: return True else: raise Exception def assert_false(x): if not x: return True else: raise Exception def assert_is(a, b): if a is b: return True else: raise Exception def assert_is_not(a, b): if a is not b: return True else: raise Exception def assert_is_none(x): if x is None: return True else: raise Exception def assert_is_not_none(x): if x is not None: return True else: raise Exception def assert_in(a, b): if a in b: return True else: raise Exception def assert_not_in(a, b): if a not in b: return True else: raise Exception #tests print assert_equal(1, 1) print assert_equal(1, 2) print assert_not_equal(1, 1) print assert_not_equal(1, 2) print assert_true(True) print assert_true(False) print assert_false(False) print assert_false(True) a = "abc" print assert_is(a, a) print assert_is(a, "abc") print assert_is_not(a, a) print assert_is_not(a, "abc") print assert_is_none(a) print assert_is_none(None) print assert_is_not_none(a) print assert_is_not_none(None) b = ["abc", 1, 42] print assert_in(a, b) print assert_in(a, b[1:]) print assert_not_in(a, b) print assert_not_in(a, b[1:])
ab3d832b14744e03f55203484a4d4000c0d5e93b
CamiloCastiblanco/AYED-AYPR
/AYED/Programas/mid.py
456
3.734375
4
import sys def main(): x=int(input()) y=int(input()) z=int(input()) if x>y and x>z: if y>z: print ("Case 1:",y) else: print ("Case 1:",z) if y>x and y>z: if x>z: print ("Case 1:",x) else: print ("Case 1:",z) if z>y and z>x: if y>x: print ("Case 1:",y) else: print ("Case 1:",x) main()
6469ec80a5bbdc439a2b4d61a78e03fc3ae98478
changbokLee/Python-in-Practice
/section07-03.py
1,815
3.921875
4
#파이썬 클래스 상세이해 # 상속 , 다중상속 # 예제1 # 상속기본 # 슈퍼클래스(부모) 및 서브클래스(자식) -> 모든속성 ,메소드 사용가능 # 라면 -> 속성(종류 , 회사 , 맛 , 면 종류, 이름 ): 부모클래스 # 코드의 재사용 가능 class Car: """Parent Class""" def __init__(self, tp , color): self.type = tp self.color = color def show(self): return 'Car Clas "Show Method!"' class BmwCar(Car): """sub class""" def __init__(self,car_name ,tp , color): super().__init__(tp,color) self.car_name = car_name def show_model(self) -> None: return "Your Car Name: %s " % self.car_name class BenzCar(Car): """sub class""" def __init__(self,car_name ,tp , color): super().__init__(tp,color) self.car_name = car_name def show_model(self) -> None: return "Your Car Name: %s " % self.car_name def show(self): return 'Car Info: %s %s %s' % (self.car_name, self.type, self.color) # 일반사용 model1 = BmwCar('520d', 'sedan', 'red') print(model1.color) # super print(model1.type) # super print(model1.car_name) # sub print(model1.show()) # super print(model1.show_model) # sub print(model1.__dict__) # Method Overiding(오버라이딩) model2 =BenzCar("220d", "suv", "black") print(model2.show) # Parent Method Call model3 = BenzCar("350s", "sedan", "sliver") print(model3.show()) # Inheriatance Info(상속정보) print(BmwCar.mro()) print(BenzCar.mro()) #예제2 # 다중상속 class X(object): pass class Y(): pass class Z(): pass class A(X,Y): pass class B(Y,Z): pass class M(B, A, Z): pass print(M.mro) print(A.mro()) ws = wb.active ws['A1'] = 42 ws.apppend([1,2,3]) import datetime
ec8af6720f602475dfe4f8cece908545371b2d30
kongfany/python100
/if_for/shuixianhua.py
865
3.546875
4
""" ---------------------------------------- File Name: shuixianhua Author: Kong Date: 2021/7/8 Description: 寻找所有水仙花数 水仙花:三位数,个位的3次方之和为本省 关键得出数字的三位 个位:num % 10 十位:num // 10 % 10 百位:num // 100 153 370 371 407 ---------------------------------------- for num in range(100,1000): low = num % 10 mid = num // 10 % 10 high = num // 100 if num == low ** 3 +mid **3 +high ** 3: print(num,end=" ") """ """ 找出所有水仙花数 """ for num in range(100, 1000): low = num % 10 # 个位(取余) mid = num // 10 % 10 # 十位,先去掉个位(整除),然后取余 high = num // 100 # 百位,直接去掉后两位(整除) if num == low ** 3 + mid ** 3 + high ** 3: print(num)
c3742cdf2d9fb26c62d1cc81f0938a726b410385
ed100miles/StructuresAndAlgorithms
/SearchTrees/bst_simple.py
1,590
4.125
4
class Node: def __init__(self, data=None): self.data = data self.left = None self.right = None class BST: """Simple implementation of a binary search tree""" def __init__(self): self.root = None def insert(self,data): if self.root is None: self.root = Node(data) else: self._insert(data, self.root) def _insert(self, data, current_node): if data < current_node.data: if current_node.left is None: current_node.left = Node(data) else: self._insert(data, current_node.left) elif data > current_node.data: if current_node.right is None: current_node.right = Node(data) else: self._insert(data, current_node.right) else: raise ValueError(f'Value alread present: {repr(data)}') def find(self, data): if self.root: is_found = self._find(data, self.root) if is_found: return True return False else: return None def _find(self, data, current_node): if data > current_node.data and current_node.right: return self._find(data, current_node.right) if data < current_node.data and current_node.left: return self. _find(data, current_node.left) if data == current_node.data: return True # bst = BST() # for x in range(10): # bst.insert(x) # print(bst.find(4)) # print(bst.find(5)) # print(bst.find(11))
184745da9d5f0ba618b3ea3e96ab18a098e7eef7
singultek/ModelAndLanguagesForBioInformatics
/Python/List/31.lendecoding.py
945
3.90625
4
def repeat_value(repetition,value)-> list: i=0 _shallow = [] while i < repetition: _shallow.append(value) i+=1 return _shallow def flatten(nested_list: list) -> list: """ Flatten an input list which could have a hierarchical multi nested list :param nested_list: The source list :return: The flatten list """ if len(nested_list) == 0: return [] if type(nested_list[0]) is list: return flatten(nested_list[0]) + flatten((nested_list[1:])) return [nested_list[0]] + flatten(nested_list[1:]) def len_decoding(i_list)-> list: """ Given a run-length code list generated construct its uncompressed version. :param list: :return: """ return flatten(list(map(lambda sublist: repeat_value(sublist[0],sublist[1]),i_list))) if __name__ == "__main__": print(len_decoding([[3, 1], [3, 2], [1, 4], [3, 3]]))
cbd8645102c0622bcf874cf619045a901480e2a2
kubbo/python-lang
/ListDemo.py
202
3.75
4
__author__ = 'zhu' str="hello are you" list=str.split() print(list) print(len(list)) while len(list)!=0: print(list.pop()) list=["hello","world"] print(" ".join(list)) print("#".join(list[0:2]))
58a7af593921bf5e1634f8f6bf64dff98d755e33
geraldzm/Othello-ASM
/putPice.py
1,341
3.53125
4
mtz = [] # 0 = - , 1 = B, 2 = N def putPice(fil, col, color): global mtz for i in range(-1, 2): for j in range(-1, 2): if((i,j) == (0,0)): continue if(mtz[fil+i][col+j] != color): if(path(fil, col, j, i, color) == color): mtz[fil][col] = color def path(fil, col, vx, vy, color): global mtz fil += vy col += vx if(mtz[fil][col] == '-'): return 2 if(mtz[fil][col] == color): return color if(path(fil, col, vx, vy, color) == color): mtz[fil][col] = color return color return '-' def printMatrix(mtz): print(end=" ") for i in range(8): print(i, end=" ") print("") i =0 for row in mtz: print(i, end=" ") i += 1 for column in row: print(column, end=" ") print("") for row in range(8): mtz.append(['-','-','-','-','-','-','-','-']) mtz[3][3] = 'B' mtz[4][4] = 'B' mtz[4][3] = 'N' mtz[3][4] = 'N' col = 0 col1 = 'B' col2 = 'N' color = 'N' while (col != 9): printMatrix(mtz) print("turno de ", color) fil = int(input("Digite el fila ")) col = int(input("Digite el columna ")) putPice(fil, col, color) if(color == col1): color = col2 else: color = col1
08e76bcbb4d4407c3f414e368f0ad1f688d54f59
edithturn/Data-Structures-Algorithms
/valid_parentesis/valid_parentesis_01.py
1,250
4.4375
4
# A string of brackets is considered correctly matched if every opening bracket in the string can be paired up with a later closing bracket, and vice versa. For instance, “(())()” is correctly matched, whereas “)(“ and “((” aren’t. For instance, “((” could become correctly matched by adding two closing brackets at the end, so you’d return 2. # Given a string that consists of brackets, write a function bracketMatch that takes a bracket string as an input and returns the minimum number of brackets you’d need to add to the input in order to make it correctly matched. # Explain the correctness of your code, and analyze its time and space complexities. # Examples: # input: text = “(()” # output: 1 # input: text = “(())” # output: 0 # input: text = “())(” # output: 2 from pythonds.basic import Stack def checkBalanced(expresion): index = 0 balanced = True s = Stack() while index < len(expresion) and balanced: simbol = expresion[index] if simbol == '(': s.push(simbol) else: if s.isEmpty(): balanced == False else: s.pop() index = index + 1 if balanced and s.isEmpty(): return True else: return False print (checkBalanced('((()))()')) print (checkBalanced('(()'))
97e7fac458c215ed312bb59f8bc05ec850368125
sunnyyeti/Leetcode-solutions
/34 Find First and Last Position of Elements in Sorted Array.py
1,330
3.78125
4
# Given an array of integers nums sorted in ascending order, find the starting and ending position of a given target value. # If target is not found in the array, return [-1, -1]. # You must write an algorithm with O(log n) runtime complexity. # Example 1: # Input: nums = [5,7,7,8,8,10], target = 8 # Output: [3,4] # Example 2: # Input: nums = [5,7,7,8,8,10], target = 6 # Output: [-1,-1] # Example 3: # Input: nums = [], target = 0 # Output: [-1,-1] # Constraints: # 0 <= nums.length <= 105 # -109 <= nums[i] <= 109 # nums is a non-decreasing array. # -109 <= target <= 109 class Solution: def searchRange(self, nums: List[int], target: int) -> List[int]: def bleft(nums,target): l,r = 0,len(nums)-1 while l<=r: m = (l+r)//2 if nums[m]>=target: r = m -1 else: l = m + 1 return l def bright(nums,target): l,r = 0,len(nums)-1 while l<=r: m = (l+r)//2 if nums[m]<=target: l = m + 1 else: r = m - 1 return r l,r = bleft(nums,target),bright(nums,target) return [l,r] if 0<=l<len(nums) and 0<=r<len(nums) and nums[l]==target else [-1,-1]
2b6d52fec15f0c05e7730b4756212a10fb813bc9
ekomai/Forecast_AI
/2_owm_sql_csv.py
993
3.5
4
# api to json from pprint import pprint import urllib import urllib.request import json import sqlite3 import sqlite3 as sql import os import csv from sqlite3 import Error try: conn = sqlite3.connect('sqlite/forecast.db') cur = conn.cursor() cur.execute('''SELECT * FROM Forecast''') rows = cur.fetchall() for row in rows: print(row) # conn.commit() # Export data into CSV file # print("Exporting data into CSV............") cursor = conn.cursor() cursor.execute("select * from Forecast") with open("csv/forecast.csv", "w") as csv_file: csv_writer = csv.writer(csv_file, delimiter=",") csv_writer.writerow([i[0] for i in cursor.description]) csv_writer.writerows(cursor) dirpath = os.getcwd() + "csv/forecast.csv" print("Data exported Successfully into {}".format(dirpath)) except Error as e: print(e) # Close database connection finally: conn.close()
96fde298fd9ef94a7ddd925d790f4b799f757763
petro-ew/test1
/solutions/1.py
993
4
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import sys import cmath import math __author__ = 'petro-ew' #zadacha number 1 """ #список квадратов чисел от 1 до 10 n=int(input()) print("n=",n) l1=[] x=0 while x < n: x=x+1 l1.append(x) l2 = [x ** 2 for x in l1] print(l2) """ """ #список квадратов чисел от 1 до 10 n=int(input()) print("n=",n) l1=[] for x in range(1,n+1): l1.append(x) l2 = [x ** 2 for x in l1] print(l2) """ """ #список квадратов чисел от 1 до 10 n=int(input()) print("n=",n) l1 = range(1,n+1) l1 = list(l1) print(l1) l2 = [x ** 2 for x in l1] print(l2) """ """ #список квадратов чисел от 1 до 10 n=int(input()) print("n=",n) print([x ** 2 for x in list(range(1,n+1))]) """ #список квадратов чисел от 1 до 10 n = int(input()) print("n=", n) l2 = [x ** 2 for x in range(1, n + 1)] print(l2)
1bcf5e6314ee9cc3f82bd93b8ca8af892d18860c
Santigonzaq/Exercisespython
/Ejercicio.py
3,825
3.578125
4
from datetime import datetime as dt from datetime import timedelta as td from dateutil.relativedelta import relativedelta as rd import locale locale.setlocale(locale.LC_ALL,"Spanish_Spain.1252") formato="%d/%m/%y - %I:%m:%p" alterno = "%Y-%m-%d" print("----------------CLINICA LA ESPERANZA------------------") print("Hoy es: "+str(dt.today().strftime(formato))) print("----------------------------------------------------------------------") nombre=str(input("Ingrese el nombre de la mascota: \n")) tipo="" while(True): seleccion=str(input("Ingrese el tipo de mascota (p/g): \n")) seleccion=seleccion.lower() if seleccion!="p" and seleccion !="g": print("Entrada no valida, por favor ingrese p ó g") else: if seleccion=="p": tipo="Perro" else: tipo="Gato" break print("Bienvenido/a "+nombre+", "+tipo) print("----------------------------------------------------------------------") def volverFecha(aux=1): #strp es para volver una entrada por teclado, una fecha #si aux=1, requiero fecha de nacimiento #Sino, estoy hablando de última desparacitación if aux==1: nacimiento=input("Ingrese fecha de nacimiento de la mascota (yyyy-mm-dd): \n") nacimiento=dt.strptime(nacimiento,alterno) return nacimiento else: ultima = input("Ingrese fecha especifica de última desparasitación de la mascota (yyyy-mm-dd): \n") ultima = dt.strptime(ultima, alterno) return ultima ultima=volverFecha(0) print("La ultima fecha de desparasitación de "+nombre+" es: "+str(dt.strftime(ultima,alterno))) print("----------------------------------------------------------------------") fechatope=ultima+td(days=1461) print("La programación de desparacitación de "+nombre+" durante los proximos cuatro años es: ") def queDiaEs(fecha): formatoaux="%A" dia=dt.strftime(fecha,formatoaux) if str(dia)=="viernes" or str(dia)=="sábado" or str(dia)=="domingo": if str(dia)=="viernes": fecha+=td(days=3) elif str(dia)=="sábado": fecha+=td(days=2) else: fecha += td(days=1) return fecha while ultima<=fechatope: formatomostrar="%A, %B %d de %Y" ultima+=td(days=90) ultima=queDiaEs(ultima) print("Desparasitación el dia: "+str(dt.strftime(ultima,formatomostrar))) print("----------------------------------------------------------------------") nacimiento=volverFecha() print("La fecha de nacimiento de "+nombre+" es: "+str(dt.strftime(nacimiento,alterno))) print("----------------------------------------------------------------------") fechahoy=dt.today() #Para hacer los calculos de días meses y años vividos, voy a hacer uso del formato de la fecha, extrayendo a su vez los datos requeridos añosvividos=rd(fechahoy,nacimiento).years diasvividos=rd(fechahoy,nacimiento).days mesesvividos=rd(fechahoy,nacimiento).months print(nombre+" ha vivido por "+str(añosvividos)+" años, "+str(mesesvividos)+" meses y "+str(diasvividos)+" dias.") esperanzaperro=14*365 esperanzagato=6*365 diasvividospormascota=fechahoy-nacimiento if tipo=="Perro": print("El potencial de vida para "+nombre+" es de: "+str(esperanzaperro)+", días es decir, 14 años aproximadamente") if int(diasvividospormascota.days)>esperanzaperro: print("Ha superado la expectativa de vida") else: print("El potencial de vida para " + nombre + " es de: " + str(esperanzagato) + " días, es decir, 6 años aproximadamente") if int(diasvividospormascota.days)>esperanzagato: print("Ha superado la expectativa de vida")
df0cce5e478f0fae6633b42c936601da00ff7451
yanshengjia/algorithm
/leetcode/Breadth First Search/513. Find Bottom Left Tree Value.py
1,027
3.9375
4
""" Given a binary tree, find the leftmost value in the last row of the tree. Example 1: Input: 2 / \ 1 3 Output: 1 Example 2: Input: 1 / \ 2 3 / / \ 4 5 6 / 7 Output: 7 Solution: 1. DFS + Stack 2. BFS + Queue """ # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None # BFS # Time: O(n), n is tree size # Space: O(n), worst case class Solution: def findBottomLeftValue(self, root: TreeNode) -> int: if root == None: return [] level = [root] while level: cache = [] for node in level: if node.left: cache.append(node.left) if node.right: cache.append(node.right) if cache: level = cache else: break return level[0].val
285bf181a4ded51deea18aa6a71129503f2981de
arbitre125/ChessTournament-1
/Controllers/utils.py
2,583
3.828125
4
import datetime class Util: @staticmethod def input_format(string_input): """ Format the asked input of the user Replace caracters with accents Delete white spaces """ if type(string_input) == str: string_input = string_input.lower() for caracter in ["à", "â", "ä"]: string_input.replace(caracter, "a") for caracter in ["é", "è", "ê", "ë"]: string_input.replace(caracter, "e") for caracter in ["î", "ï"]: string_input.replace(caracter, "i") for caracter in ["ô", "ö"]: string_input.replace(caracter, "o") for caracter in ["ù", "û", "ü"]: string_input.replace(caracter, "u") split_input = string_input.split(" ") string_input = "".join(split_input) return string_input @staticmethod def call_options(options, response, *args): """ Method to call the function in the value of a dictonnary Calls dict[key]() or dict[key][]() if the value is a list The next element of the list is the parameters of the function *args corresponds to the paramaters in all the function of this dictionnary """ if isinstance(options[response], list): new_args = args params = options[response][1:] for param in reversed(params): new_args = (param,) + new_args result = options[response][0](*new_args) else: result = options[response](*args) return result @staticmethod def check_date(date): """ Check the asked date """ try: date = datetime.date.fromisoformat(date) except ValueError: print("Date invalide") return False else: return date.isoformat() @staticmethod def check_response(len_options, response): """ Check the response for the selection of the action to do next """ if response not in [f"{i + 1}" for i in range(len_options)]: print("Réponse invalide") return False return response @staticmethod def check_player(all_players, input_player): """ Check the asked player input """ if input_player not in [f"{i + 1}" for i in range(len(all_players))]: print("Joueur invalide") return False return input_player
0166d1a226e16647bd2c9e281f953e163e23dd8a
Arxtage/leetcode
/zigzag-iterator/zigzag-iterator.py
797
3.640625
4
class ZigzagIterator: # Create a list beforehand def __init__(self, v1: List[int], v2: List[int]): L, R = 0, 0 self.res = [] while L < len(v1) and R < len(v2): self.res.append(v1[L]) L += 1 self.res.append(v2[R]) R += 1 while L < len(v1): self.res.append(v1[L]) L += 1 while R < len(v2): self.res.append(v2[R]) R += 1 def next(self) -> int: val = self.res.pop(0) return val def hasNext(self) -> bool: if self.res: return True return False # Your ZigzagIterator object will be instantiated and called as such: # i, v = ZigzagIterator(v1, v2), [] # while i.hasNext(): v.append(i.next())
9e8a391c8911ffa73757421a939218e8202b5087
nawaka7/Booking_System
/main.py
31,763
3.53125
4
# Booking System (Concert Ticket) import pymysql.cursors def connect_sql(): connection = pymysql.connect( host = 'YOUR_HOST', port = 8888, user = 'USER_NAME', password = 'PASSWORD', db = 'DATABASE', charset = 'utf8', cursorclass = pymysql.cursors.DictCursor, autocommit = True) return connection connection = connect_sql() # no.1 Create Tables try: # Q: how to clear tables? error - Unknown table with connection.cursor() as cursor: sql_comm = "drop table if exists Book cascade" cursor.execute(sql_comm) sql_comm = "drop table if exists Audience cascade;" cursor.execute(sql_comm) sql_comm = "drop table if exists Building cascade;" cursor.execute(sql_comm) sql_comm = "drop table if exists Performances cascade;" cursor.execute(sql_comm) sql_comm = "drop table if exists Buildings cascade;" cursor.execute(sql_comm) connection = connect_sql() with connection.cursor() as cursor: sql_comm = "create table Audience (" \ "aud_id varchar(10) AUTO_INCREMENT primary key," \ "aud_name varchar(200)," \ "gender varchar(1) check(gender = 'M' or gender = 'F')," \ "age int, check( 0 <= age <= 999))" cursor.execute(sql_comm) sql_comm = "create table Buildings (" \ "building_id varchar(5) AUTO_INCREMENT primary key," \ "building_name varchar(200)," \ "building_cap int default 0," \ "building_loc varchar(200)," \ "building_asgn int default 0 check(building_asgn =1 or building_asgn =0))" cursor.execute(sql_comm) sql_comm = "create table Building (" \ "building_id varchar(5)," \ "seat_number int," \ "constraint building_pk primary key(building_id, seat_number)," \ "constraint fk_buildings foreign key(building_id) references Buildings(building_id) " \ "on delete cascade on update cascade)" cursor.execute(sql_comm) sql_comm = "create table Performances (" \ "perf_id varchar(10) AUTO_INCREMENT primary key," \ "perf_name varchar(200)," \ "perf_type varchar(10)," \ "price int, check(0 <= price <= 1000000)," \ "booked int default 0," \ "building_id varchar(5) default null," \ "constraint fk_perf foreign key(building_id) references Buildings(building_id)" \ "on delete cascade on update cascade)" cursor.execute(sql_comm) sql_comm = "create table Book (" \ "booking_id varchar(10) primary key," \ "aud_id varchar(10) not null AUTO_INCREMENT," \ "perf_id varchar(10) not null," \ "building_id varchar(5) not null," \ "seat_number varchar(4) not null," \ "constraint fk_book_aud foreign key(aud_id) references Audience(aud_id) " \ "on delete cascade on update cascade," \ "constraint fk_book_per foreign key(perf_id) references Performances(perf_id) " \ "on delete cascade on update cascade," \ "constraint fk_book_bui foreign key(building_id, seat_number) references Building(building_id, seat_number)" \ "on delete cascade on update cascade)" cursor.execute(sql_comm) connection = connect_sql() with connection.cursor() as cursor: cursor.execute("show tables") print(cursor.fetchall(), "\nTables Are Successfully Created") except: print("ERROR: Tables Failed to Be Created") finally: pass # no.2 Insert Data connection = connect_sql() with connection.cursor() as cursor: #Audience sql_comm = "insert into Audience(aud_name, gender, age) " \ "values ('Yoon Jaeyeun', 'M', 30);" cursor.execute(sql_comm) sql_comm = "insert into Audience(aud_name, gender, age) " \ "values ('Kim Taeuk', 'M', 27);" cursor.execute(sql_comm) sql_comm = "insert into Audience(aud_name, gender, age) " \ "values ('Ahn Chaemin', 'F', 25);" cursor.execute(sql_comm) #Buildings sql_comm = "insert into Buildings(building_name, building_loc) " \ "values ('Seoul Arts Center', 'Seoul');" cursor.execute(sql_comm) sql_comm = "insert into Buildings(building_name, building_loc) " \ "values ('Grand Peace Palace', 'Seoul');" cursor.execute(sql_comm) #Building (seat_numbers) sql_comm = "insert into Building(building_id, seat_number)" \ "values ('1', 'A001');" cursor.execute(sql_comm) sql_comm = "insert into Building(building_id, seat_number)" \ "values ('1', 'A002');" cursor.execute(sql_comm) sql_comm = "insert into Building(building_id, seat_number)" \ "values ('1', 'A003');" cursor.execute(sql_comm) sql_comm = "insert into Building(building_id, seat_number)" \ "values ('1', 'B001');" cursor.execute(sql_comm) sql_comm = "insert into Building(building_id, seat_number)" \ "values ('1', 'B002');" cursor.execute(sql_comm) sql_comm = "insert into Building(building_id, seat_number)" \ "values ('1', 'B003');" cursor.execute(sql_comm) sql_comm = "insert into Building(building_id, seat_number)" \ "values ('2', 'A001');" cursor.execute(sql_comm) sql_comm = "insert into Building(building_id, seat_number)" \ "values ('2', 'A002');" cursor.execute(sql_comm) sql_comm = "insert into Building(building_id, seat_number)" \ "values ('2', 'A003');" cursor.execute(sql_comm) sql_comm = "insert into Building(building_id, seat_number)" \ "values ('2', 'B001');" cursor.execute(sql_comm) sql_comm = "insert into Building(building_id, seat_number)" \ "values ('2', 'B002');" cursor.execute(sql_comm) sql_comm = "insert into Building(building_id, seat_number)" \ "values ('2', 'B003');" cursor.execute(sql_comm) #Performances sql_comm = "insert into Performances(perf_name, perf_type, price, building_id)" \ "values ('Coldplay Concert', 'Concert', 100000, '1');" cursor.execute(sql_comm) sql_comm = "insert into Performances(perf_name, perf_type, price, building_id)" \ "values ('Jekyll & Hyde', 'Musical', 70000, '2');" cursor.execute(sql_comm) #Book sql_comm = "insert into Book(aud_id, perf_id, building_id, seat_number)" \ "values ('1', '1', '1', 'A001');" cursor.execute(sql_comm) sql_comm = "insert into Book(aud_id, perf_id, building_id, seat_number)" \ "values ('1', '1', '2', 'A002');" cursor.execute(sql_comm) # count building capacity, assigned performance, and performance bookings # 1) building_cap def count_cap(): connection = connect_sql() with connection.cursor() as cursor: cursor.execute("select distinct building_id from Building") result = cursor.fetchall() building_ids = [] for i in range(len(result)): building_ids += list(result[i].values()) for i in range(len(building_ids)): sql_comm = "update Buildings " \ "set building_cap = (select count(seat_number) " \ "from Building where building_id = \'%s\') " \ "where building_id = \'%s\'" %(building_ids[i], building_ids[i]) cursor.execute(sql_comm) # 2) building_asgn def count_asgn(building_id): connection = connect_sql() with connection.cursor() as cursor: cursor.execute("select count(building_id) from Performances where building_id = \'%s\';"%building_id) # 3) Performances booked def count_booked(): connection = connect_sql() with connection.cursor() as cursor: cursor.execute("select perf_id, count(booking_id) from Book group by perf_id") result = cursor.fetchall() for i in range(len(result)): sql_comm = "update Performances " \ "set booked = %d "\ "where perf_id = \'%s\'" %(result[i]['count(booking_id)'], result[i]['perf_id']) cursor.execute(sql_comm) print("Data are Successfully Inserted") # no.3 Application Classes Definitions #id_generator # import random # def id_gen(num): # id = '' # for i in range(num): # id += str(random.randrange(10)) # return id #id_autoincrement class Insert(object): def __init__(self): self.sql_comm_insert = "insert into " def into_buildings(self, building_name, building_cap, building_loc): while True: connection = connect_sql() # with connection.cursor() as cursor: # sql_comm = "select building_id from Buildings" # cursor.execute(sql_comm) # result = cursor.fetchall() # building_ids= [] # for i in range(len(result)): # building_ids += result[i]['building_id'] # while True: # building_id = id_gen(5) # if building_id not in building_ids: # break if not (type(building_name) == str and len(building_name) <= 200): print("building_name must be shorter than or equal to 200 letters") break elif not (type(building_loc) == str and len(building_loc) <= 200): print("building_loc must be shorter than or equal to 200 letters") break else: connection = connect_sql() with connection.cursor() as cursor: sql_comm = self.sql_comm_insert + "Buildings(building_name, building_cap, building_loc) values(" \ "\'%s\', \'%s\', \'%s\')" %(building_name, building_cap, building_loc) cursor.execute(sql_comm) break return building_id def into_performances(self, perf_name, perf_type, price): while True: connection = connect_sql() with connection.cursor() as cursor: sql_comm = "select perf_id from Performances" cursor.execute(sql_comm) result = cursor.fetchall() perf_ids= [] for i in range(len(result)): perf_ids += result[i]['perf_id'] while True: perf_id = id_gen(10) if perf_id not in perf_ids: break if not (type(perf_id) == str and len(perf_id) == 10 and perf_id.isdigit()): print("perf_id must be a 10 digit-long string") break elif not(type(perf_name) == str and len(perf_name) <= 200): print("perf_name must be shorter than or equal to 200 letters") break elif not (type(perf_type) == str and len(perf_type) <= 200): print("perf_type must be shorter than or equal to 200 letters") break elif not (type(price) == int and 0 <= price <= 1000000): print("price must be between 0 ~ 1,000,000") break else: connection = connect_sql() with connection.cursor() as cursor: sql_comm = self.sql_comm_insert + \ "Performances(perf_id, perf_name, perf_type, price) values(" \ "\'%s\', \'%s\', \'%s\', \'%d\')" %(perf_id, perf_name, perf_type, price) cursor.execute(sql_comm) break return perf_id def into_audience(self, aud_name, gender, age): while True: connection = connect_sql() with connection.cursor() as cursor: sql_comm = "select aud_id from Audience" cursor.execute(sql_comm) result = cursor.fetchall() aud_ids= [] for i in range(len(result)): aud_ids += result[i]['aud_id'] while True: aud_id = id_gen(10) if aud_id not in aud_ids: break if not (type(aud_id) == str and len(aud_id) == 10 and aud_id.isdigit()): print("aud_id must be a 10 digit-long string") break elif not (type(aud_name) == str and len(aud_name) <= 200): print("aud_name must be shorter than or equal to 200 letters") break elif not (gender == 'M' or gender == 'F'): print("gender must be either 'M' or 'F'") break elif not (type(age) == int and 0 <= age <= 999): print("age must be between 0 ~ 999") break else: connection = connect_sql() with connection.cursor() as cursor: sql_comm = self.sql_comm_insert + "Audience(aud_id, aud_name, gender, age) values(" \ "\'%s\', \'%s\', \'%s\', \'%d\')" %(aud_id, aud_name, gender, age) cursor.execute(sql_comm) break return aud_id def into_building(self, building_id, seat_number): while True: if not (type(building_id) == str and len(building_id) == 5 and building_id.isdigit()): print("building_id must be a 5 digit-long string") break elif not (type(seat_number) == str and len(seat_number) <= 4): print("seat_number must be shorter or equal to 4 letters") break else: connection = connect_sql() with connection.cursor() as cursor: sql_comm = self.sql_comm_insert + "Building(building_id, seat_number) values(" \ "\'%s\', \'%s\')" % (building_id, seat_number) cursor.execute(sql_comm) count_cap() break def into_book(self, aud_id, perf_id, seat_number, building_id): connection = connect_sql() with connection.cursor() as cursor: sql_comm = "select booking_id from Book" cursor.execute(sql_comm) result = cursor.fetchall() booking_ids= [] for i in range(len(result)): booking_ids += result[i]['booking_id'] while True: booking_id = id_gen(10) if booking_id not in booking_ids: break connection = connect_sql() with connection.cursor() as cursor: sql_comm = self.sql_comm_insert + "Book(booking_id, aud_id, perf_id, seat_number, building_id) values(" \ "\'%s\', \'%s\', \'%s\', \'%s\', \'%s\')" % (booking_id, aud_id, perf_id, seat_number, building_id) cursor.execute(sql_comm) count_booked() return booking_id class Delete(object): def __init__(self): self.sql_comm_del = "delete from " def from_buildings(self, building_id): while True: if not (type(building_id) == str and len(building_id) == 5): print("building_id must be a 5-digit-long string") break else: connection = connect_sql() with connection.cursor() as cursor: sql_comm = self.sql_comm_del + "Buildings where building_id = %s" %building_id cursor.execute(sql_comm) count_asgn(building_id) break def from_performances(self, perf_id): while True: if not (type(perf_id) == str and len(perf_id) == 10): print("perf_id must be a 10-digit-long string") break else: connection = connect_sql() with connection.cursor() as cursor: result = Select('building_id', 'Performances', 'where = perf_id').execute() sql_comm = self.sql_comm_del + "Performances where perf_id = %s" cursor.execute(sql_comm, perf_id) count_asgn(result[0]['building_id']) break def from_audience(self, aud_id): while True: if not (type(aud_id) == str and len(aud_id) == 10): print("aud_id must be a 10-digit-long string") break else: connection = connect_sql() with connection.cursor() as cursor: sql_comm = self.sql_comm_del + "Audience where aud_id = %s" cursor.execute(sql_comm, aud_id) break def from_book(self, booking_id): while True: if not (type(booking_id) == str and len(booking_id) == 10): print("booking_id must be a 10-digit-long string") break else: connection = connect_sql() with connection.cursor() as cursor: sql_comm = self.sql_comm_del + "Book where booking_id = %s" cursor.execute(sql_comm, booking_id) count_booked() break class Select(object): def __init__(self, column_name, Table_name, where = None): self.sql_comm = "select %s from %s %s" %(column_name, Table_name,where) def execute(self): connection = connect_sql() with connection.cursor() as cursor: cursor.execute(self.sql_comm) return cursor.fetchall() print("Classes and Functions Were Successfully Defined") # no.4 Application Execution if input("Please, press Enter to proceed: ", ): pass line_len_1 = 60 while True: connection = connect_sql() print("="*line_len_1 + "\n"\ "1. print all buildings \n"\ "2. print all performances \n"\ "3. print all audiences \n"\ "4. insert a new building \n"\ "5. remove a building \n"\ "6. insert a new performance \n"\ "7. remove a performance \n"\ "8. insert a new audience \n"\ "9. remove an audience \n"\ "10. assign a performance to a building \n"\ "11. book a performance \n"\ "12. print all performances assigned to a building \n"\ "13. print all audiences who booked for a performance \n"\ "14. print ticket booking status of a performance \n"\ "15. exit\n"+ "="*line_len_1) while True: num_choice = input("Select your action: ", ) if 1 <= int(num_choice) <= 15: print("you chose < %s >." %num_choice) break else: print("the number you chose, < %s >, is out of range (not 1~15).\n" %num_choice) line_len_2 = 70 if num_choice == '1': connection = connect_sql() result = Select('*', 'Buildings').execute() print("-" * line_len_2 +'\nid'.ljust(8), 'name'.ljust(30), 'location'.ljust(10), 'capacity'.ljust(10), 'assigned\n' +"-" * line_len_2) for i in range(len(result)): print(result[i]['building_id'].ljust(7), result[i]['building_name'].ljust(30), result[i]['building_loc'].ljust(10), str(result[i]['building_cap']).ljust(10), str(result[i]['building_asgn']).ljust(10)) print("-" * line_len_2) elif num_choice == '2': connection = connect_sql() result = Select('*', 'Performances').execute() print("-" * line_len_2 +'\nid'.ljust(13), 'name'.ljust(27), 'type'.ljust(10), 'price'.ljust(10), 'booked\n' +"-" * line_len_2) for i in range(len(result)): print(result[i]['perf_id'].ljust(12), result[i]['perf_name'].ljust(27), result[i]['perf_type'].ljust(10), str(result[i]['price']).ljust(10), str(result[i]['booked']).ljust(10)) print("-" * line_len_2) elif num_choice == '3': connection = connect_sql() result = Select('*', 'Audience').execute() print("-" * line_len_2 +'\nid'.ljust(13), 'name'.ljust(30), 'gender'.ljust(10), 'age'.ljust(10), '\n' + "-" * line_len_2) for i in range(len(result)): print(result[i]['aud_id'].ljust(12), result[i]['aud_name'].ljust(30), result[i]['gender'].ljust(10), str(result[i]['age']).ljust(10)) print("-" * line_len_2) elif num_choice == '4': connection = connect_sql() while True: building_name = input("building name: ",) if len(building_name) <= 200: break print("building name must be under 200 letters") while True: building_loc = input("building location: ", ) if len(building_name) <= 200: break print("building location must be under 200 letters") print("building id is automatically created \n", "building capacity is automatically calculated when you insert seats data into the building table") building_id = Insert().into_buildings(building_name, building_loc) seats = [] while True: seat = input("seat numbers of the building: ", ) if len(seat) > 4: print("building location must be under or equal to 4 digit- or letter- long string, e.g., 'A001', 'B123") else: seats.append(seat) print(seat, 'added to', building_id) answer = input('continue inserting (press Enter)? if not, type \'exit\'', ) if answer == 'exit': break for i in range(len(seats)): Insert().into_building(building_id, seats[i]) count_cap() print("A building is successfully inserted:") elif num_choice == '5': connection = connect_sql() temp = Select('building_id', 'Buildings').execute() building_ids = list(map(lambda x: temp[x]['building_id'], range(len(temp)))) while True: building_id = input('building id: ',) if building_id in building_ids: Delete().from_buildings(building_id) break else: print("The building id is not defined. Check the table") elif num_choice == '6': connection = connect_sql() while True: perf_name = input("performance name: ",) if len(perf_name) <= 200: break print("performance name must be under 200 letters") while True: perf_type = input("performance type: ", ) if len(perf_type) <= 10: break print("performance type must be under 200 letters") while True: price = int(input("performance price: ",)) if 0 <= price <= 1000000: break print("price must be between 0 and 1,000,000") print("performance id is automatically created \n", "the number of bookings is automatically calculated whenever a booking is made.\n" "building_id allocation is optional: default is None.") perf_id = Insert().into_performances(perf_name, perf_type, price) print("A performance is successfully created: ", perf_id) elif num_choice == '7': connection = connect_sql() temp = Select('perf_id', 'Performances').execute() perf_ids = list(map(lambda x: temp[x]['perf_id'], range(len(temp)))) while True: perf_id = input('performance id: ', ) if perf_id in perf_ids: Delete().from_performances(perf_id) break else: print("The performance id is not defined. Check the table") elif num_choice == '8': connection = connect_sql() while True: aud_name = input("audience name: ",) if len(aud_name) <= 200: break print("audience name must be under 200 letters") while True: gender = input("audience gender (M, F): ", ) if gender == 'M' or gender == 'F': break print("audience gender must be either M or F") while True: age = int(input("audience age: ",)) if 0 <= age <= 999: break print("age must be between 0 and 999") print("audience id is automatically created.") aud_id = Insert().into_audience(aud_name, gender, age) print("An audience is successfully created: ", aud_id) elif num_choice == '9': connection = connect_sql() temp = Select('aud_id', 'Audience').execute() aud_ids = list(map(lambda x: temp[x]['aud_id'], range(len(temp)))) while True: aud_id = input('audience id: ', ) if aud_id in aud_ids: Delete().from_audience(aud_id) break else: print("The audience id is not defined. Check the table") elif num_choice == '10': connection = connect_sql() temp = Select('building_id', 'Buildings').execute() building_ids = list(map(lambda x: temp[x]['building_id'], range(len(temp)))) while True: building_id = input('building id: ',) if building_id in building_ids: break print("The building id is not defined. Check the table") temp = Select('perf_id', 'Performances', 'where building_id is null ').execute() perf_ids = list(map(lambda x: temp[x]['perf_id'], range(len(temp)))) while True: perf_id = input("performance id: ",) if perf_id in perf_ids: break print("The performance id is either not defined or already assigned. Check the table") with connection.cursor() as cursor: sql_comm = "update Performances set building_id = \'%s\' where perf_id = \'%s\'"%(building_id, perf_id) cursor.execute(sql_comm) count_asgn(building_id) print("Successfully assigned a performance to a building") elif num_choice == '11': connection = connect_sql() temp = Select('perf_id', 'Performances').execute() perf_ids = list(map(lambda x: temp[x]['perf_id'], range(len(temp)))) while True: perf_id = input("performance id: ") if perf_id in perf_ids: break print("The performance is not defined. Check the table") temp = Select('aud_id', 'Audience').execute() aud_ids = list(map(lambda x: temp[x]['aud_id'], range(len(temp)))) while True: aud_id = input("audience id: ") if aud_id in aud_ids: break print("The audience is not defined. Check the table") temp = Select('building_id', 'Performances', 'where perf_id = \'%s\''%perf_id).execute() building_id = temp[0]['building_id'] temp = Select('seat_number', 'Building', 'where building_id = \'%s\'' % building_id).execute() seat_numbers = list(map(lambda x: temp[x]['seat_number'], range(len(temp)))) temp = Select('seat_number', 'Book', 'where perf_id = \'%s\''%perf_id).execute() booked_seat_number = list(map(lambda x: temp[x]['seat_number'], range(len(temp)))) temp = Select('seat_number', 'Building', 'where building_id = \'%s\' and seat_number not in (' 'select seat_number from Book where perf_id = \'%s\')'%(building_id,perf_id)).execute() unbooked_seat_number = list(map(lambda x: temp[x]['seat_number'], range(len(temp)))) print("Choose a seat from down below. \n", unbooked_seat_number) looper = True while looper: seat_number = input("seat number: \n#for multiple seats, separate them with a comma") seat_number_lst = seat_number.split(',') for i in seat_number_lst: if i.strip() in seat_numbers: if i.strip() not in booked_seat_number: pass else: print("The seat, \'%s\', is already booked."%i) seat_number_lst.remove(i) else: print("The seat number, \'%s\', is not defined. Check the table."%i) seat_number_lst.remove(i) looper = False if len(seat_number_lst) > 0: for i in seat_number_lst: booking_id = Insert().into_book(aud_id, perf_id, i.strip(), building_id) print("Successfully booked a performance: ", booking_id) elif num_choice == '12': connection = connect_sql() temp = Select('building_id', 'Buildings').execute() building_ids = list(map(lambda x: temp[x]['building_id'], range(len(temp)))) while True: building_id = input('building id: ', ) if building_id in building_ids: break print("The building id is not defined. Check the table") result = Select('*', 'Performances', 'where building_id = \'%s\''%building_id).execute() print("-" * line_len_2 + '\nid'.ljust(13), 'name'.ljust(27), 'type'.ljust(10), 'price'.ljust(10), 'booked\n' + "-" * line_len_2) for i in range(len(result)): print(result[i]['perf_id'].ljust(12), result[i]['perf_name'].ljust(27), result[i]['perf_type'].ljust(10), str(result[i]['price']).ljust(10), str(result[i]['booked']).ljust(10)) print("-" * line_len_2) elif num_choice == '13': connection = connect_sql() result = Select('*', 'Audience', 'where aud_id in (select aud_id from Book)').execute() print("-" * line_len_2 + '\nid'.ljust(13), 'name'.ljust(30), 'gender'.ljust(10), 'age'.ljust(10), '\n' + "-" * line_len_2) for i in range(len(result)): print(result[i]['aud_id'].ljust(12), result[i]['aud_name'].ljust(30), result[i]['gender'].ljust(10), str(result[i]['age']).ljust(10)) print("-" * line_len_2) elif num_choice == '14': connection = connect_sql() temp = Select('perf_id', 'Performances').execute() perf_ids = list(map(lambda x: temp[x]['perf_id'], range(len(temp)))) while True: perf_id = input("performance id: ") if perf_id in perf_ids: break print("The performance is not defined. Check the table") with connection.cursor() as cursor: sql_comm = "select bd.seat_number, bk.aud_id "\ "from Building bd left join Book bk on(bd.seat_number = bk.seat_number) "\ "where bd.building_id = (select building_id from Performances where perf_id = \'%s\')"%perf_id cursor.execute(sql_comm) result = cursor.fetchall() print("-" * line_len_2 + '\nseat number'.ljust(30), 'audience id'.ljust(30),'\n' + "-" * line_len_2) for i in range(len(result)): print(result[i]['seat_number'].ljust(30), result[i]['aud_id']) print("-" * line_len_2) elif num_choice == '15': print("Bye!") break connection.close()
542301d4bd2e43831f702fbee5eca43f29b284cf
bhuvankaruturi/Python-Programs
/least_cost_path.py
1,120
3.8125
4
#Path with the least cost inputString = input() blocks = [] row = [] cost = '' for value in inputString: if value == '#': row.append(int(cost)) blocks.append(row) row = [] cost = '' else: if value == '@': row.append(int(cost)) cost = '' else: cost = cost + value if cost != '': row.append(int(cost)) blocks.append(row) print(blocks) def least_cost_path(blocks): for i in range(len(blocks)): for j in range(len(blocks[i])): cost = blocks[i][j] costs = [] if i == 0 and j == 0: costs.append(cost) if i > 0 and j > 0: costs.append(cost + blocks[i-1][j-1]) if i > 0: costs.append(cost + blocks[i-1][j]) if i > 0 and j < (len(blocks[i]) - 1): costs.append(cost + blocks[i-1][j+1]) if j > 0: costs.append(cost + blocks[i][j-1]) blocks[i][j] = min(costs) return blocks print("**********************") print(least_cost_path(blocks))
0de36cab21e7a08bd840fe93ea481ea93b6fbaa5
dawidstefaniak/Python30DaysChallange
/22BST.py
997
3.765625
4
class Node: def __init__(self,data): self.right=self.left=None self.data = data class Solution: def insert(self,root,data): if root==None: return Node(data) else: if data<=root.data: cur=self.insert(root.left,data) root.left=cur else: cur=self.insert(root.right,data) root.right=cur return root def getHeight(self,root): leftcounter = 0 rightcounter = 0 if root.left is not None: leftcounter = 1 + self.getHeight(root.left) if root.right is not None: rightcounter = 1 + self.getHeight(root.right) if leftcounter >= rightcounter: return leftcounter else: return rightcounter T = int(input()) myTree = Solution() root=None for i in range(T): data = int(input()) root = myTree.insert(root, data) height = myTree.getHeight(root) print(height)
f8e24836094201741c4c57330b7e108ae0d78dd6
Arvind-Bhakuni/Projects
/rock_paper_scissor/rps.py
3,896
3.796875
4
# importing necessary libraries import random import tkinter as tk # creating objects root = tk.Tk() # set geometry root.geometry('400x400') root.resizable(0,0) root.title('Rock Paper Scissor') # defining global variable user_score = 0 com_score = 0 user_choice = '' com_choice = '' # define a function to convert user choice to number def choice_to_number(ch): rps = {'Rock' :0, 'Paper' :1, 'Scissor' :2} return rps[ch] def number_to_choice(n): rps = {0: 'Rock', 1: 'Paper', 2: 'Scissor'} return rps[n] # create a function to get the computer choice def comp_choice(): return random.choice(['Rock', 'Paper', 'Scissor']) def play(human, com): global user_score global com_score user = choice_to_number(human) com = choice_to_number(com) if user == com: lb4.config(text="It's a Tie!") lb5.config(text="Your Choice: {}\nComputer's choice: {}".format(human, number_to_choice(com))) lb6.config(text='Computer Score: {}\nYour Score: {}'.format(com_score, user_score)) # lb5.Text() elif (user-com)%3==1: lb4.config(text='You Win!') user_score += 1 lb5.config(text="Your Choice: {}\nComputer's choice: {}".format(human, number_to_choice(com))) lb6.config(text='Computer Score: {}\nYour Score: {}'.format(com_score, user_score)) else: lb4.config(text='Computer Win!') com_score += 1 lb5.config(text="Your Choice: {}\nComputer's choice: {}".format(human, number_to_choice(com))) lb6.config(text='Computer Score: {}\nYour Score: {}'.format(com_score, user_score)) disable_buttons() # define 3 functions rock, paper and scissor def rock(): global user_choice, com_choice user_choice = 'Rock' com_choice = comp_choice() play(user_choice, com_choice) def paper(): global user_choice, com_choice user_choice = 'Paper' com_choice = comp_choice() play(user_choice, com_choice) def scissor(): global user_choice, com_choice user_choice = 'Scissor' com_choice = comp_choice() play(user_choice, com_choice) # function to reset the play def reset_play(): b1['state'] = 'active' b2['state'] = 'active' b3['state'] = 'active' lb1.config(text='Player') lb2.config(text='vs') lb3.config(text="Computer") lb4.config(text='') # function to disable the buttons def disable_buttons(): b1['state'] = 'disable' b2['state'] = 'disable' b3['state'] = 'disable' # adding labels tk.Label(root, text='Rock Paper Scissor', font='normal 22 bold', fg='green').pack(pady=10) frame1 = tk.Frame(root) frame1.pack() lb1 = tk.Label(frame1, text='Player', font=14) lb1.pack(side=tk.LEFT) lb2 = tk.Label(frame1, text='vs', font='normal 14 bold') lb2.pack(side=tk.LEFT) lb3 = tk.Label(frame1, text='Computer', font=14) lb3.pack() lb4 = tk.Label(root, text="", font='normal 22 bold', bg='#E0E3D9', width=15, borderwidth=2, relief='solid') lb4.pack(pady=15) frame2 = tk.Frame(root) frame2.pack() b1 = tk.Button(frame2, text='Rock', font=14, width=10, command=rock, bg='#E3D9E0') b1.pack(side=tk.LEFT, pady=8) b2 = tk.Button(frame2, text='Paper', font=14, width=10, command=paper, bg='#E3D9E0') b2.pack(side=tk.LEFT, pady=8) b3 = tk.Button(frame2, text='Scissor', font=14, width=10, command=scissor, bg='#E3D9E0') b3.pack(side=tk.LEFT, pady=8) lb5 = tk.Label(root, text="", font=5, bg='#E0E3D9', width=30, height=2, borderwidth=1, relief='solid') lb5.pack() lb6 = tk.Label(root, text="", font=5, bg='#E0E3D9', width=30, height=2, borderwidth=1, relief='solid') lb6.pack() # reset button tk.Button(root, text='Reset Game', width=17, font=10, fg='orange', bg='#272951', command=reset_play).pack(side=tk.LEFT, pady=5) # exit button tk.Button(root, text="Exit Game", command=root.destroy, width=17, font=10, fg='orange', bg='#272951').pack(side=tk.RIGHT, pady=5) root.mainloop()
58318a02e0f738cdef8f1a61ea23faa176e7f9e3
vijay-vj/python
/Date_Formattin.py
580
4.03125
4
from datetime import datetime def main(): x = 0 print (x) now = datetime.now(); print (now.strftime("%Y")) # %a/ %A -- weeday # d/ D -- Day # b/ B -- Month # y/ Y -- Year # c -- Local date and time # x -- Local date # X -- Local time # print (now.strftime("%A, %d, %B, %Y")) print (now.strftime("%c, %x, %X")) # I/ H -- 12/ 24, M - Minutes, S - Seconds, p -- AM/ PM print (now.strftime("%I:%M:%S %p")) print (now.strftime("%H:%M")) if __name__ == "__main__": main()
36c38bdde076f2acffc62e1074bfce8f68737f68
Vern01/comp_v2
/maths.py
252
3.640625
4
def solve(equation): print("Needs to solve equation.") class Math: def __init__(self, memory): self.memory = memory def calc(self, string, ignore=""): values = self.memory.set_values(string, ignore) return string
b6297410ce3040058c477ae931b0e3857015f4a4
anyone21/Project-Euler
/gallery/Dynamic-programming/Problem-82/Problem-82.py
1,988
3.65625
4
# -*- coding: utf-8 -*- """ Created on Sun Apr 17 18:09:44 2016 @author: Xiaotao Wang """ """ Problem 82: The minimal path sum in the 5 by 5 matrix below, by starting in any cell in the left column and finishing in any cell in the right column, and only moving up, down, and right, is indicated in red and bold; the sum is equal to 994. Find the minimal path sum, in matrix.txt, a 31K text file containing a 80 by 80 matrix, from the left column to the right column. """ # Given a n*n matirx, the complexity of this algorithm is O(n^3) import copy import numpy as np def readdata(filename): data = [list(map(int, line.rstrip().split(','))) for line in open(filename)] return data def dynamic(data): paths = copy.deepcopy(data) mintotal = np.r_[data] for i in range(1, len(data)): paths[i][0] = (i, 0) for stage in range(1, len(data[0])): tmpsum = [] for i in range(len(data)): orisum = mintotal[i, stage-1] + mintotal[i, stage] p = (i, stage-1) for j in range(0, i): cursum = mintotal[j, stage-1] + mintotal[j:i+1, stage].sum() if cursum < orisum: orisum = cursum p = (i-1, stage) for j in range(i+1, len(data)): cursum = mintotal[j, stage-1] + mintotal[i:j+1, stage].sum() if cursum < orisum: orisum = cursum p = (i+1, stage) tmpsum.append(orisum) paths[i][stage] = p mintotal[:,stage] = tmpsum minidx = mintotal[:,-1].argmin() minimum = mintotal[minidx, -1] pos = paths[minidx][-1] path = [pos] while pos[1] != 0: pos = paths[pos[0]][pos[1]] path = [pos] + path return minimum, path if __name__ == '__main__': data = readdata('p082_matrix.txt') res = dynamic(data) # ~1.26s
4eef352068ed9bd22a8eda7c6ca688613c1abb4a
ArvindAROO/AckermannFunctionHyperOptimization
/ackermannOriginal.py
534
3.9375
4
def ackermann(m,n): #the legacy code for the actual ackermann function if m==0: ans = n+1 elif n==0: ans = ackermann(m-1,1) else: ans = ackermann(m-1,ackermann(m,n-1)) return ans if __name__ == "__main__": print("Be careful with the values, the function grows beyond exponentially,") print("This function might not find the value in any reasonable amount of time") m = int(input("Enter the value of m: ")) n = int(input("Enter the value of n: ")) print(ackermann(m,n))
b47b74dee2093752a94167d0e51705c430d9b544
YLyeliang/now_leet_code_practice
/tree/depth_binary_tree.py
2,068
4.09375
4
# 输入一棵二叉树的根节点,求该树的深度。 # 从根节点到叶节点依次经过的节点(含根、叶节点)形成树的一条路径,最长路径的长度为树的深度。 # 树的遍历方式总分为两类:深度优先搜索(DFS)、广度优先搜素(BFS) # 常见DFS:前序、中序、后序遍历 # 常见BFS:层序遍历 # 一、 DFS # 后序遍历/DFS一般采用递归或栈来实现。 # 采用递归的方式进行。 树的深度由左右子树决定,其深度等于左右子树中最深的+1. # 则可得到递归公式max(left,right)+1 # time: O(N) space:O(N) # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def maxDepth(self, root) -> int: if not root: return 0 return max(self.maxDepth(root.left),self.maxDepth(root.right))+1 # 二、 BFS # 树的层序遍历 / 广度优先搜索往往利用 队列 实现。 # 关键点: 每遍历一层,则计数器 +1 ,直到遍历完成,则可得到树的深度。 # 步骤: # 特例处理: 当 root​ 为空,直接返回 深度 0。 # 初始化: 队列 queue (加入根节点 root ),计数器 res = 0。 # 循环遍历: 当 queue 为空时跳出。 # 初始化一个空列表 tmp ,用于临时存储下一层节点; # 遍历队列: 遍历 queue 中的各节点 node ,并将其左子节点和右子节点加入 tmp; # 更新队列: 执行 queue = tmp ,将下一层节点赋值给 queue; # 统计层数: 执行 res += 1 ,代表层数加 11; # 返回值: 返回 res 即可。 class Solution: def maxDepth(self, root) -> int: if not root: return 0 queue=[root] res=0 while queue: tmp=[] for node in queue: if node.left: tmp.append(node.left) if node.right: tmp.append(node.right) res+=1 queue=tmp return res
0d9fa9a2e977babc33005ffe51eeab630811cfd9
981377660LMT/algorithm-study
/20_杂题/骑士距离.py
910
3.921875
4
# 骑士距离 # 棋盘上马从(0,0)到目标点的最短路径 def knight_distance(tx: int, ty: int) -> int: """https://maspypy.github.io/library/other/knight_distance.hpp""" max = lambda x, y: x if x > y else y tx = abs(tx) ty = abs(ty) if tx + ty == 0: return 0 if tx + ty == 1: return 3 if tx == 2 and ty == 2: return 4 step = (max(tx, ty) + 1) // 2 step = max(step, (tx + ty + 2) // 3) step += (step ^ tx ^ ty) & 1 return step print(knight_distance(11, 9)) print(knight_distance(100, 100)) def superKnight(n: int) -> int: """超级马经过n步后能抵达的格子数 https://yukicoder.me/problems/no/1500 二次多项式? => 待定系数法 """ if n <= 2: return [1, 12, 65][n] return (17 * n * n + 6 * n + 1) % 1000000007 print(superKnight(int(input())))
c7b0231ee433241fcc447c86157cbfeaea1d0dbe
SelinaBains/SEL
/Python/unique_chars.py
2,053
4.46875
4
def is_char_unique(x=None, case_sensitivity=True): """ Checks if the string has unique characters. Example: is_char_unique(x="abcABC") is_char_unique(x=abcABC, case_sensitivity=False) :param str x: **REQUIRED** Input string. :param bool case_sensitivity: *OPTIONAL* Pass True if you want to treat "A" and "a" equally and so on. :return: Returns True or False :rtype: bool """ if x is None: raise Exception("String Cannot by NULL") bit_array = [0] * 256 for character in list(x): if bit_array[ord(character)] == 1: return False bit_array[ord(character)] = 1 if case_sensitivity is False: if ord(character) >= 65 and ord(character)<=90: bit_array[ord(character)+32] = 1 elif ord(character) >= 97 and ord(character)<=122: bit_array[ord(character)-32] = 1 return True #This function is using bitwise opertaions where no exra space is used (except 1 int) #Assuming input character, range from 'a' to 'z' def is_char_unique_bitwise(x=None): """ Checks if the string has unique characters. Example: is_char_unique_bitwise(x="abca") :param str x: **REQUIRED** Input string. :return: Returns True or False :rtype: bool """ if x is None: raise Exception("String Cannot by NULL") flag = 0 for character in list(x): value = ord(character) - ord('a') if flag & (1<<value) != 0: return False flag = flag | (1<<value) return True if __name__ == '__main__': #This will return True print(is_char_unique(x="abcABC")) #This will return False, will treat "a" and "A" equally. print(is_char_unique(x="abcABC", case_sensitivity=False)) #This will return True print(is_char_unique_bitwise(x="abcd")) #This will return False print(is_char_unique_bitwise(x="abca"))
1ec5f0daf6b560fc9d57293f9029e42fea7c907c
tfcampbell/startech
/testPyMongo.py
338
3.515625
4
import pymongo 'make db connection' myclient = pymongo.MongoClient("mongodb://localhost:27017/") mydb = myclient["testDatabase"] 'a document in MongoDB same as record in SQl' 'insert a column into testDatabase' mycol = mydb["customers"] 'add data' mydict ={"name" : "John", "Address" : "23 London Road"} x = mycol.insert_one(mydict)
34708977bcc962e922c5923225e2ac5e9b65f594
jshaw63/codeinprogress
/program4.py
1,104
4.375
4
# program prime physics 104 # j. shaw 3/10/17 # # prime test and factoring program # # input a number: # print ' prime number test and factoring program:' print ' tests for primality and factors x if not prime' x=float(input("enter x: ")) # # echo back to screen # print 'You entered:' print 'x = ',x # if x%2==0: print 'x = ',x,' is even' if x%2==1: print 'x = ',x,' is odd' # generates list of primes # nmax=10000 primes=[2,3] for p in range(5,nmax): isprime='true' nxmax=int(p**0.5)+1 for q in range(2,nxmax): remainder = p%q if remainder==0: isprime='false' if isprime=='true': primes.append(p) # # end primes list generation # # begin to test if x is prime and # generate list of factors if it is not prime # isprime='true' factors=('') for p in primes: remainder = x%p if remainder==0: isprime='false' reduced=x/p factors=factors+str(p)+'*' while reduced%p==0: factors=factors+str(p)+'*' reduced=reduced/p if x==p: isprime='true' print 'x = prime is ',isprime print 'factors= ',factors+'1' # # end of factoring algorithm # #
165572e40474e8dc1d38fcd949b39b6fa97407fd
SJTU-yys/Leetcode
/isPalindrome.py
277
3.8125
4
# -*- coding: utf-8 -*- """ Created on Mon Sep 28 23:57:08 2015 @author: yys """ def isPalindrome(self, x): """ :type x: int :rtype: bool """ # Get the length of the digit if x >= 0: return x == int(str(x)[::-1]) else: return False
957f1daef5c4d81b2bf644068c6186016737bc47
ElizaLo/Practice-Python
/DataCamp/Writing Efficient Python Code/Foundations for efficiencies/enumerate.py
454
3.65625
4
# Rewrite the for loop to use enumerate indexed_names = [] for i, name in enumerate(names): index_name = (i,name) indexed_names.append(index_name) print(indexed_names) # Rewrite the above for loop using list comprehension indexed_names_comp = [(i,name) for i,name in enumerate(names)] print(indexed_names_comp) # Unpack an enumerate object with a starting index of one indexed_names_unpack = [*enumerate(names, 1)] print(indexed_names_unpack)
71f93fa4629e3d1926e1a7d9897e9e4d1a481c29
chulsea/TIL
/algorithm/Python/algorithm/problems/steal_pole.py
458
3.671875
4
def solution(arr): answer = 0 n = len(arr) stack = [] for i in range(n): if arr[i] == "(": stack.append(arr[i]) else: prev = arr[i-1] stack.pop() if prev == "(": answer += len(stack) elif prev == ")": answer += 1 return answer def main(): arr = list(input()) print(solution(arr)) if __name__ == '__main__': main()
8ec72a745bd6d9001f74bfd0dd8c7054e33dd762
LRYnew/note
/015 python/code/nine/f1.py
783
3.734375
4
# -*- coding:utf-8 -*- # 类的定义 class Student(): sum = 0 name = '' age = 20 __score = 100 # 构造函数 def __init__(self, name='YJob', age=18): self.name = name self.age = age self.__score = 0 # print(name) # name为传入的参数,而不是类变量 # print(age) self.__class__.add_sum() # self.add_sum() # 实例方法必须强制传入self参数 def __print_files(self): print('name:' + self.name) print('age:' + str(self.age)) # 类方法 @classmethod def add_sum(cls): cls.sum += 1 # print('班级人数:' + str(cls.sum)) print(cls.__score) # 实例化 student1 = Student('WJob', 28) print(student1.__dict__)
97f55ce4ba4c31b5576820d167e57251027b1e69
bakunobu/exercise
/1400_basic_tasks/chap_7/main_funcs.py
1,159
4.46875
4
from typing import Union def get_input(message:str, is_float:bool=True) -> Union[int, float]: """ Gets a number as an imput and returns it. If input is incorrect, i.e. float instead of int or a string that can't be converted to number prints warning and asks for another input Works while the correct input is being typed in Args: ===== message: str A message that is shown each time is_float: bool if is_float=True expects the input is float, otherwise int (True is a default value) Return: ======= a: Union[int, float] The return is float if is_float (default value) otherwise int. """ if is_float: while True: try: a = float(input(message)) return(a) except ValueError: print('Используйте только числа (разделитель - \'.\')') else: while True: try: a = int(input(message)) return(a) except ValueError: print('Используйте только целые числа')
727efdb2d34b7077afc10120a65ecefd5f4e810c
perticascatalin/1.1-Understanding-an-Image
/code/colorScales.py
1,442
3.625
4
# Run: python colorScales.py # Creates image examples for 1.1 Understanding an image # Obtained images saved under: 'blackwhite.jpg', 'grayscale.jpg', 'blue.jpg', 'green.jpg', 'red.jpg' import cv2 import numpy as np import sys rows = int(sys.argv[1]) cols = 256 blackwhite = np.zeros((rows, cols), np.uint8) for col in range(cols/2, cols): for row in range(rows): blackwhite[row, col] = 255 grayscale = np.zeros((rows, cols), np.uint8) for col in range(cols): for row in range(rows): grayscale[row, col] = col blue = np.zeros((rows, cols, 3), np.uint8) for col in range(cols): for row in range(rows): blue[row, col] = (col,0,0) green = np.zeros((rows, cols, 3), np.uint8) for col in range(cols): for row in range(rows): green[row, col] = (0,col,0) red = np.zeros((rows, cols, 3), np.uint8) for col in range(cols): for row in range(rows): red[row, col] = (0,0,col) blackwhite = cv2.copyMakeBorder(blackwhite, 2,2,2,2, cv2.BORDER_CONSTANT,value = 0) grayscale = cv2.copyMakeBorder(grayscale, 2,2,2,2, cv2.BORDER_CONSTANT,value = 0) blue = cv2.copyMakeBorder(blue, 2,2,2,2, cv2.BORDER_CONSTANT,value = 0) green = cv2.copyMakeBorder(green, 2,2,2,2, cv2.BORDER_CONSTANT,value = 0) red = cv2.copyMakeBorder(red, 2,2,2,2, cv2.BORDER_CONSTANT,value = 0) cv2.imwrite('blackwhite.jpg', blackwhite) cv2.imwrite('grayscale.jpg', grayscale) cv2.imwrite('blue.jpg', blue) cv2.imwrite('green.jpg', green) cv2.imwrite('red.jpg', red)
0a71f498965749dfed415b8969a2256470399eed
agarwalmohak6/Python-codes
/primecheck.py
172
3.78125
4
n=int(input()) i=2 c=0 while(i<n): if(n%i==0): c+=1 break else: i+=1 if(c!=0): print("Not prime") else: print("Prime")
d00165f352151ba859d37e321323acd8251f4ba0
jaehyunan11/leetcode_Practice
/robotBoundedInCircle.py
3,479
3.984375
4
# class Solution: # def # if after the set of operations, the robot is still at the position (0,0) then it is bounded # if the robot doesn't point North after the set of instuctions, it will # return to the point (0,0) after 4 sets of instructions, pointing North, and repeat # Therefore, if the robot doesn't point North after the set of operations, it is bounded. # IN all other cases, the robot is unbounded class Solution: def isRobotBounded(self, instructions): # initial direction direc = [0, 0] # set pos to 0 pos = 0 for c in instructions: if c == "L": direc = (direc + 1) % 4 elif c == "R": direc = (direc - 1) % 4 elif c == "G": # 0 as North if direc == 0: pos[1] += 1 # 1 as West elif direc == 1: pos[0] -= 1 # 2 as South elif direc == 2: pos[1] -= 1 # 3 as East else: pos[0] += 1 # bounded condition should be either [0,0] or direc is not north. return pos == [0, 0] or direc != 0 # class Solution: # def isRobotBounded(self, instructions): # # robot is bounded if end position is 0,0 # # OR # # end direction is not north # n = {'l': 'w', 'r': 'e'} # s = {'l': 'e', 'r': 'w'} # e = {'l': 'n', 'r': 's'} # w = {'l': 's', 'r': 'n'} # state = 'n' # pos = (0, 0) # for i in range(len(instructions)): # if instructions[i] == 'G': # if state == 'n': # pos = pos[0], pos[1] + 1 # elif state == 's': # pos = pos[0], pos[1] - 1 # elif state == 'w': # pos = pos[0] + 1, pos[1] # else: # pos = pos[0] - 1, pos[1] # elif instructions[i] == 'L': # if state == 'n': # state = n['l'] # elif state == 's': # state = s['l'] # elif state == 'w': # state = w['l'] # else: # state = e['l'] # else: # if state == 'n': # state = n['r'] # elif state == 's': # state = s['r'] # elif state == 'w': # state = w['r'] # else: # state = e['r'] # # print(pos, state) # # if state is facing to north is is unbounded. # if pos == (0, 0) or state != 'n': # return True # return False class Solution: def isRobotBounded(self, instructions): direc, pos = 0, [0, 0] for c in instructions: if c == "L": direc = (direc + 1) % 4 elif c == "R": direc = (direc - 1) % 4 elif c == "G": if direc == 0: pos[1] += 1 elif direc == 1: pos[0] -= 1 elif direc == 2: pos[1] -= 1 else: pos[0] += 1 return pos == [0, 0] or direc != 0 s = Solution() instructions = "GGLLGG" print(s.isRobotBounded(instructions))
e09f7bbdaa45b9d65ab904f2a8da5d979f4d1901
6igsm0ke/Introduction-to-Programming-Using-Python-Liang-1st-edtion
/CH12/EX12.14.py
3,770
4.3125
4
# 12.14 (Tkinter: Mandelbrot fractal) The Mandelbrot fractal is a well-known image # created from a Mandelbrot set (see Figure 12.26a). A Mandelbrot set is defined # using the following iteration: # Z(n+1) = Z(n)^2 + c # c is a complex number, and the starting point of the iteration is Z(0) = 0(For # information on complex numbers, see Exercise 8.21.) For a given c, the iteration # will produce a sequence of complex numbers: [Z(0), Z(1), ... , Z(n), ... ].It can be # shown that the sequence either tends to infinity or stays bounded, depending on # the value of c. For example, if c is 0, the sequence is which is # bounded. If c is i, the sequence is [0, 0, c], which # is bounded. If c is the sequence is [0, i, -1 + i, -i, -1 + i, i, ...], which is # unbounded. It is known that if the absolute value of a complex value in the # sequence is greater than 2, then the sequence is unbounded. The Mandelbrot set # consists of the c value such that the sequence is bounded. For example, 0 and i # are in the Mandelbrot set. # The count(c) function (lines 23–28) computes Z1,Z2,...,Z60 If none of their # absolute values exceeds 2, we assume c is in the Mandelbrot set. Of course, # there could always be an error, but 60 (COUNT_LIMIT) iterations usually are # enough. Once we find that the sequence is unbounded, the method returns the # iteration count (line 28). The method returns COUNT_LIMIT if the sequence is # bounded (line 30). # The loop in lines 6–20 examines each point (x, y) for -2 < x < 2 and -2 < y < 2 # with interval 0.01 to see if its corresponding complex number c = x + yi # is in the Mandelbrot set (line 9). If so, paint the point red (line 11). # If not, set a color that is dependent on its iteration count (line 14). Note that the # point is painted in a square with width 5 and height 5. All the points are scaled # and mapped to a grid of 400x400 pixels (lines 17–18). from tkinter import * # Import tkinter # Convert a decimal to a hex as a string def toHex(decimalValue): hex = "" while decimalValue != 0: hexValue = decimalValue % 16 hex = toHexChar(hexValue) + hex decimalValue = decimalValue // 16 if len(hex) < 2: hex = "0" + hex return hex # Convert an integer to a single hex digit in a character def toHexChar(hexValue): if hexValue <= 9 and hexValue >= 0: return chr(hexValue + ord('0')) else: # hexValue <= 15 && hexValue >= 10 return chr(hexValue - 10 + ord('A')) COUNT_LIMIT = 60 # Paint a Mandelbrot image in the canvas def paint(): x = -2.0 while x < 2.0: y = -2.0 while y < 2.0: c = count(complex(x, y)) if c == COUNT_LIMIT: color = "red" # c is in a Mandelbrot set else: color = "#" + toHex(c * 37 % 256) + toHex( c * 58 % 256) + toHex(c * 159 % 256) # print(color) # Fill a tiny rectangle with the specified color canvas.create_rectangle(x * 100 + 200, y * 100 + 200, x * 100 + 200 + 5, y * 100 + 200 + 5, fill=color) y += 0.05 x += 0.05 # Returns the iteration count def count(c): z = complex(0, 0) # z0 for i in range(COUNT_LIMIT): z = z * z + c # Get z1, z2, ... if abs(z) > 2: return i # The sequence is unbounded return COUNT_LIMIT # Indicate a bounded sequence window = Tk() # Create a window window.title("Mandelbrot fractal") # Set a title width = 400 # Width of the canvas height = 400 # Height of the canvas canvas = Canvas(window, width=width, height=height) canvas.pack() Button(window, text="Display", command=paint).pack() window.mainloop() # Create an event loop
31fd84e2258879af1e3ccc2eba05a9ec196908bb
terrifyzhao/leetcode
/daily/1071_gcdOfStrings.py
391
3.546875
4
class Solution(object): def gcdOfStrings(self, str1, str2): """ :type str1: str :type str2: str :rtype: str """ if str1 + str2 != str2 + str1: return '' def gcd(a, b): return a if b == 0 else gcd(b, a % b) return str1[0:gcd(len(str1), len(str2))] print(Solution().gcdOfStrings("ABCABC", "ABC"))
f5eac7228672449e7a1e014a8cb16df6f6229f84
atulpatel991928/bitcoin-maxnum
/add.py
227
3.8125
4
"""var1= "45 " var2= 4 var3= " 60" print(int(var1) + int(var3)) print(10* "hwllo word\n") """ print("Enter firsrt number:") n1 = input() print("Enter second number:") n2 = input() print("sum of the number:", int(n1) + int(n2))
635e8f44f46576687f27585d7e7b296d6b5e8017
dexterka/coursera_files
/1_Python_for_everybody/week6_functions/functions_testing.py
373
3.78125
4
# Conditions within functions # Calling the function with parameters and returning the values def greet(lang): if lang == 'es': return 'Hola' elif lang == 'fr': return 'Bonjour' else: return 'Hello' print(greet('en'), 'Sally!') print(greet('es'), 'Maria!') print(greet('hr'), 'Zlatan!') print(greet('fr'), 'Susanna!')
2f1025ffd9e87284d4447b9e1120c46baaaca6d6
ArthurConmy/EPQ
/A General Solution.py
25,324
3.703125
4
from itertools import count from math import factorial as f from random import randint white='\033[1;37m' black='\033[1;30m' reset='\033[0m' def print_game(horizontals, verticals, rs, cs): ##if you're in repl.it, turn this into print_game and delete the function below for index in range(0, rs+1): for index_2 in range(index*cs, (index+1)*cs): if horizontals[index_2]==1: print('{} --'.format(white), end='') else: print('{} --{}'.format(black, reset), end='') ## colour ?! print() if index!=rs: for index_3 in range(index*(cs+1), (index+1)*(cs+1)): if verticals[index_3]==1: print('{}| {}'.format(white, reset), end='') else: print('{}| {}'.format(black, reset), end='') print() def is_critical(hs, vs, rs, cs): ## try to find a non critical ## assuming we can't ALREADY TAKE a square for horizontal in range(0, (rs+1)*cs): if hs[horizontal] == 0: newh = hs[:] newh[horizontal] = 1 if is_winnable_square(newh, vs, rs, cs) == False: return 'h'+str(horizontal) for vertical in range(0, (cs+1)*rs): if vs[vertical] == 0: newv = vs[:] newv[vertical] = 1 if is_winnable_square(hs, newv, rs, cs) == False: return 'v'+str(vertical) return True def is_winnable_square(hs, vs, rs, cs): for horizontal in range(0, rs*cs): no_filled = 0 if hs[horizontal] == 1: no_filled+=1 else: move = 'h'+str(horizontal) if hs[horizontal + cs] == 1: no_filled+=1 else: move = 'h'+str(horizontal + cs) if vs[horizontal + horizontal//cs] == 1: no_filled+=1 else: move = 'v'+str(horizontal + horizontal//cs) if vs[horizontal + horizontal//cs + 1] == 1: no_filled+=1 else: move = 'v'+str(horizontal + horizontal//cs + 1) if no_filled == 3: return move else: return False def no_winnable_squares(hs, vs, rs, cs): no=0 for horizontal in range(0, rs*cs): no_filled = 0 if hs[horizontal] == 1: no_filled+=1 else: move = 'h'+str(horizontal) if hs[horizontal + cs] == 1: no_filled+=1 else: move = 'h'+str(horizontal + cs) if vs[horizontal + horizontal//cs] == 1: no_filled+=1 else: move = 'v'+str(horizontal + horizontal//cs) if vs[horizontal + horizontal//cs + 1] == 1: no_filled+=1 else: move = 'v'+str(horizontal + horizontal//cs + 1) if no_filled == 3: no+=1 return no def is_neutral_square(hs, vs, rs, cs): ## is there a neutral move that can be made ? no_winnable = no_winnable_squares(hs, vs, rs, cs) for h in range(0, (rs+1)*cs): if hs[h] == 1: continue copyh=hs[:] copyh[h]=1 if no_winnable_squares(copyh, vs, rs, cs) == no_winnable: return True ## ie theres a move that doesn't change the number of winnable squares for v in range(0, rs*(cs+1)): if vs[v] == 1: continue copyv=vs[:] copyv[v]=1 if no_winnable_squares(hs, copyv, rs, cs) == no_winnable: return True return False def no_neutrals(hs, vs, rs, cs): ## how many (naively) neutral moves from this point? number=0 copyh=hs[:] copyv=vs[:] while is_critical(copyh, copyv, rs, cs)!=True: number+=1 move=is_critical(copyh, copyv, rs, cs) if move[0]=='h': copyh[int(move[1:])]=1 else: copyv[int(move[1:])]=1 return number def completed_squares(hs, vs, rs, cs): ## Returns the number of completed squares (all players) the_completed_squares=0 ##=[] for upper in range(0, rs*cs): ## dependent on board_size !!! if hs[upper]==1 and hs[upper+cs]==1 and vs[upper + upper//cs]==1 and vs[upper + upper//cs + 1]==1: the_completed_squares+=1 ##.append(upper) return the_completed_squares ## used to be len def no_consecutive_takeable_squares(hs, vs, rs, cs): ## take as many squares as possible! copyh = hs[:] copyv = vs[:] number = 0 while is_winnable_square(copyh, copyv, rs, cs) != False: number+=1 move_made = is_winnable_square(copyh, copyv, rs, cs) #print(move_made) if move_made[0] == 'h': copyh[int(move_made[1:])] = 1 #print('changed') if move_made[0] == 'v': copyv[int(move_made[1:])] = 1 #print('changed too') return number def parity_long_chains(hs, vs, rs, cs): ch=hs[:] cv=vs[:] chain_sizes=[] while ch.count(0)+cv.count(0)>0: ## make dumb move for h in range(0, (rs+1)*cs): if ch[h]==0: ch[h]=1 break else: for v in range(0, (cs+1)*rs): if cv[v]==0: cv[v]=1 break while is_winnable_square(ch, cv, rs, cs)!=False: move=is_winnable_square(ch, cv, rs, cs) if move[0]=='h': ch[int(move[1:])]=1 else: cv[int(move[1:])]=1 chain_sizes.append(completed_squares(ch, cv, rs, cs)-completed_squares(hs, vs, rs, cs)-sum(chain_sizes)) long_chains=0 ##return chain_sizes for x in chain_sizes: if x>2: long_chains+=1 return long_chains%2 def isin(big, small): for thing in big: if thing[1:]==small[1:]: return big.index(thing) return -1 print('Welcome to the general solution Dots-and-Boxes opponent!') print() print('First, you will have to enter the number of rows, columns and the maximum ply for the minimax search. Do so now:') print() rows = int(input('Enter number of rows >')) columns = int(input('Enter number of columns >')) max_ply = int(input('Enter maximum ply for the minimax search. 8 will be slow, 6 medium, 4 fast >')) print() print('To enter a horizontal move, enter \'hN\' (without the quotation marks) in order to enter the Nth horizontal move, which is counted from 0. Thus \'h0\' is the first horizontal move, and likewise \'v0\' is the first vertical move.') print() print('It may be best to play a couple of practise games with this program before a \'serious\' game, to become accustomed to this method of entering moves') print() print('We\'re about to begin: a blank grid shall be printed, which shall have white lines drawn onto after moves have been made. Good luck!') print() hs=[0 for i in range(0, columns*(rows+1))] vs=[0 for i in range(0, rows*(columns+1))] no_players=2 our_completed_squares=[0 for i in range(0, no_players)] players_turn=0 critical_yet = False for turn in count(): ##print(hs) ##print(vs) print() print_game(hs, vs, rows, columns) if hs.count(0)+vs.count(0)==0: break ## game over move_made = False if players_turn == 0: ## players turn move_made = input('It\'s your move, player! >') else: ## AI turn if is_winnable_square(hs, vs, rows, columns)!=False: ## if neutral squares left ## then take square if no_neutrals(hs, vs, rows, columns)>1: move_made = is_winnable_square(hs, vs, rows, columns) print('Making move thats taking a square because neutral squareS exist') ## else if squares in long chain ## then take all but last two ## okay several functions to be defined here ## one function that takes as many squares as it can, so we know how many squares are winnable ## another that lists all moves that are part of else: ## NO neutral squares if no_consecutive_takeable_squares(hs, vs, rows, columns)>2: ## multiple takeable squares move_made = is_winnable_square(hs, vs, rows, columns) print('More than 2 winnable squares so getting the winnable square') else: ## no_consecutive_takeable_squares is EQUAL to 2. ##try and make move that doesn't cause completed squares to increase is_move_made = False for horizontal in range(0, (rows+1)*columns): if hs[horizontal]==1: continue copyh=hs[:] copyv=vs[:] copyh[horizontal]=1 if completed_squares(hs, vs, rows, columns)==completed_squares(copyh, copyv, rows, columns) and no_consecutive_takeable_squares(copyh, copyv, rows, columns)==2: ## ie theres a 'neutral' move is_move_made=True move_made='h'+str(horizontal) break for vertical in range(0, (columns+1)*rows): if vs[vertical]==1: continue copyh=hs[:] copyv=vs[:] copyv[vertical]=1 if completed_squares(hs, vs, rows, columns)==completed_squares(copyh, copyv, rows, columns) and no_consecutive_takeable_squares(copyh, copyv, rows, columns)==2: ## ie theres a 'neutral' move is_move_made=True move_made='v'+str(vertical) break if is_move_made==False: move_made=is_winnable_square(hs, vs, rows, columns) print('Can\'t make \'neutral\' move') else: print('There\'s a neutral move') ## bit peak but we'll just have to make sacrifices next turn ### THINGS: #else: # ## okay ... simulate until we can no longer take squares or something? # chain_size = 0 # if chain_size > 2: # ## take all but last two # pass # else: ## the square is not part of a long chain # ## hmm ... we should try and not take it! # move_made = is_winnable_square(vs, hs, rows, columns) ### else take square #pass else: ## no winnable squares ## if can play neutral move ## then minimax to try to reach right parity of chains ## (if f(rows*columns + rows + columns) // f(rows*columns) < 10**8: ## is this a good bound ?!) ## else sacrifice the least valuable chain. AND ACTUALLY SACRIFICE IT, NOT JUST LET THEM RETURN THE FAVOR if no_neutrals(hs, vs, rows, columns)>0: if no_neutrals(hs, vs, rows, columns) <= max_ply: print('Beginning minimax') print('Please wait ...') ## begin minimax breadth=[[[[False], hs, vs, 0, 'NA']]] ## initialise BFS. player 0 to move ## breadth[depth][index][0] is the list of the parents ## breadth[depth][index][1] are horizontals ## breadth[depth][index][2] are verticals ## breadth[depth][index][3] is player who has JUST made a move before this happened; the LAST move ## breadth[depth][index][4] is the parity of chains while len(breadth[-1]) > 0: ##print(len(breadth)) ##print_game(breadth[-1][0][1], breadth[-1][0][2], rows, columns) ##print(breadth[-1][0][1]) ##print(breadth[-1][0][2]) ##print(breadth[-1][0]) new_layer=[] for index in range(0, len(breadth[-1])): ##leaf in breadth[-1]: leaf=breadth[-1][index] for h in range(0, (rows+1)*columns): if leaf[1][h]==1: continue copyh=leaf[1][:] copyh[h]=1 if is_winnable_square(copyh, leaf[2][:], rows, columns)==False: potential=[[index], copyh, leaf[2][:], (leaf[3]+1)%2, 'NA'] if isin(new_layer, potential)!=-1: new_layer[isin(new_layer, potential)][0].append(index) else: new_layer.append(potential) for v in range(0, (columns+1)*rows): if leaf[2][v]==1: continue copyv=leaf[2][:] copyv[v]=1 if is_winnable_square(leaf[1][:], copyv, rows, columns)==False: potential=[[index], leaf[1][:], copyv, (leaf[3]+1)%2, 'NA'] if isin(new_layer, potential)!=-1: new_layer[isin(new_layer, potential)][0].append(index) else: new_layer.append(potential) breadth.append(new_layer) print('BFS complete') print('Just wait for a countdown from the number of plies') for i in range(len(breadth)-2, 0, -1): print(i) print() for leafi in range(0, len(breadth[i])): ##leafi is 'leaf index' leaf=breadth[i][leafi] if is_critical(leaf[1], leaf[2], rows, columns)!=False and leaf[-1]=='NA': breadth[i][leafi][-1]=parity_long_chains(leaf[1], leaf[2], rows, columns) ## if leaf[-1]==False: continue ##is_critical(leaf[1], leaf[2], rows, columns)!=True: continue par = breadth[i][leafi][-1] ##parity_long_chains(leaf[1], leaf[2], rows, columns) if rows%2==0 and columns%2==0: target=(leaf[3]+1)%2 else: target=leaf[3] ## target here is the parity that we want to have ##print('Leaf is', leaf, 'target is', target) if par==target: ## the target is right for ind in leaf[0]: breadth[i-1][ind][4]=target continue if par=='NA' or par==-1: for ind in leaf[0]: if breadth[i-1][ind][4]!=target: breadth[i-1][ind][4]=-1 ## this is basically 'NA' continue else: for ind in leaf[0]: if breadth[i-1][ind][4]=='NA': breadth[i-1][ind][4]=(target+1)%2 # for board in breadth[-2]: # hs=board[1] # vs=board[2] # print_game(hs, vs, 4, 4) # print(parity_long_chains(hs, vs, 4, 4)) if rows%2==0 and columns%2==0: true_target = 0 else: true_target = 1 for thing in breadth[1]: if thing[4]==true_target: ## find odd one out between hs+vs and thing[1]+thing[2]. for h in range(0, (rows+1)*columns): if thing[1][h]==1 and hs[h]==0: move_made='h'+str(h) for v in range(0, (columns+1)*rows): if thing[2][v]==1 and vs[v]==0: move_made = 'v'+str(v) if move_made!=False: print('Found move with minimax!') ## end minimax if move_made==False: ## neutral square to be taken candidate_moves=[] ##print('We\'re making neutral moves') for horizontal in range(0, (rows+1)*columns): if hs[horizontal]==1: continue copyh=hs[:] copyv=vs[:] copyh[horizontal]=1 if is_winnable_square(copyh, copyv, rows, columns)==False: candidate_moves.append('h'+str(horizontal)) for vertical in range(0, (columns+1)*rows): if vs[vertical]==1: continue copyh=hs[:] copyv=vs[:] copyv[vertical]=1 if is_winnable_square(copyh, copyv, rows, columns)==False: candidate_moves.append('v'+str(vertical)) move_made = candidate_moves[randint(0, len(candidate_moves)-1)] print('random neutral move') else: ## sacrifice least number of squares sacrifice_size = rows*columns ## max possible for horizontal in range(0, (rows+1)*columns): if hs[horizontal] == 1: continue copyh=hs[:] copyv=vs[:] copyh[horizontal]=1 if no_consecutive_takeable_squares(copyh, copyv, rows, columns) <= sacrifice_size: sacrifice_size=no_consecutive_takeable_squares(copyh, copyv, rows, columns) move_made = 'h'+str(horizontal) for vertical in range(0, (columns+1)*rows): if vs[vertical] == 1: continue copyh=hs[:] copyv=vs[:] copyv[vertical]=1 if no_consecutive_takeable_squares(copyh, copyv, rows, columns) <= sacrifice_size: sacrifice_size=no_consecutive_takeable_squares(copyh, copyv, rows, columns) move_made = 'v'+str(vertical) print('sacrifices have to be made') completed = completed_squares(hs, vs, rows, columns) ## prior completed squares if move_made[0] == 'h': hs[int(move_made[1:])] = 1 if move_made[0] == 'v': vs[int(move_made[1:])] = 1 if completed_squares(hs, vs, rows, columns) > completed: ## rotate turn our_completed_squares[players_turn] += completed_squares(hs, vs, rows, columns)-completed else: ## rotate turn players_turn+=1 players_turn=players_turn%2 print('You took', our_completed_squares[0], 'squares') print('The computer took', our_completed_squares[1], 'squares') if our_completed_squares[0]>our_completed_squares[1]: print('You win!') if our_completed_squares[1]>our_completed_squares[0]: print('You lose!') if our_completed_squares[0]==our_completed_squares[1]: print('It\'s a draw!')
f6b6db6125364f64f347e9cd435aa26839a7166e
gnenov89/BashScripting
/re_json.py
1,773
3.5625
4
#!/usr/bin/python # Create class that takes a file as an argument class Open_File(): def __init__(self, filename, mode): self.filename= filename self.mode = mode def __enter__(self): self.file = open(self.filename, self.mode) return self.file def __exit__(self, exc_type, exec_value, traceback): self.file.close() import re import json #Creating 2 instanced of the Open_File() obejct rf(to read from) and wf(to write to) with Open_File('new.txt', 'r') as rf: with Open_File('output.json', 'w') as wf: lines = rf.read().strip('\n') pattern = re.compile(r'(?:^NAME)(?:\n\s+)(.*?)(?:\n+)(?:^DESCRIPTION)(.*?)(?:^SYNOPSIS)(.*?)(?:^OPTIONS)(.*?)(?:EXAMPLES)(.*?)(?:OUTPUT)(.*?)(?:\n{3})', re.DOTALL | re.MULTILINE) # console.log(pattern) matches=re.findall(pattern,lines) for match in matches: # print(match) my_dict = { match[0]:[ {"name": match[0]}, {"description": match[1]}, {"synopsis": match[2]}, {"options": match[3]}, {"examples": match[4]}, {"output": match[5]} ] } # print(my_dict.keys()) json_file=json.dumps(my_dict, indent=2, separators=(',', ': ')) # print(type(json_file)) wf.write(str(json_file)) with Open_File('output.json', 'r') as file: with Open_File('final.json', 'w') as out_file: filedata=file.read() filedata=filedata.replace('\n}{',',') print(type(filedata)) json_final=json.dumps(filedata, indent=2, separators=(',', ': ')) out_file.write(filedata)
867bfd831baf5ffaa5697a299979f0a32bb07177
xiaotiankeyi/PythonBase
/exercise/base_exercise.py
1,549
4.46875
4
"""x 的 y 次方(xy) 以下表达式""" v = 3 ** 2 print(v) """3*1**3表达式输出结果""" b = 3 * 1 ** 3 # 正确的是 3,** 拥有更高的优先级, print(b) """9//2表达式输出为,取整除,返回商的整数部分""" s = 9 // 2 print(s) """如果表达式的操作符有相同的优先级,则运算规则是?____从左到右""" g = (3 + 1) * (5 + 5) print(g) """以下代码输出为""" x = True y = False z = False if x or y and z: # 这里先运算and,y等于0,返回y的值False,在运算or,x不是0,返回x的值True print("yes") else: print("no") """在bool值中代表False的有(0),([]),({}),(None),(()) """ v = () print(bool(v)) """以下代码输出为""" x = False y = True z = True if x or y and z: # 这里先运算and,y不等于0,返回z的值True,在运算or,x等于0返回y的值True print("yes") else: print("no") """逻辑运算符的优先级顺序为(not, and, or)""" x = True y = False z = False print(not x or y) # x不为零,先返回True,在反转为False if not x or y: print(not x or y) elif not x or not y and z: print(2) elif not x or y or not y and x: print(3) else: print(4) """or逻辑运算符例题""" a = 0 c = 10 print((a or c)) """""" i = sum = 0 while i <= 4: sum += i i = i + 1 # print(sum) """函数递归""" def Foo(x): print(x) if (x == 1): return 1 else: return x + Foo(x - 1) # print(Foo(4)) a = [2, 5, -1,56,3, 2, -4, -23] b = [i for i in a if int(i) >=1 ] print('大于1的数有{}个'.format(len(b)))
3c6b3e0e225fb71a6c0d1832a68f57f825bf5085
OlehPalka/Second_semester_labs
/labwork8/test_validator.py
5,537
3.71875
4
"""" This is testing module. """ import unittest from validator import Validator class TestValidator(unittest.TestCase): """ Class which tests function from module disc """ def test_validator(self): """ This method cheks if the functtion works correctly. """ valid = Validator() self.assertEqual(valid.validate_name_surname("Elvis Presley"), True) self.assertEqual(valid.validate_name_surname("ElvisPresley"), False) self.assertEqual(valid.validate_name_surname( "Elvis Presley forever"), False) self.assertEqual(valid.validate_name_surname("elvis Presley"), False) self.assertEqual(valid.validate_name_surname("Elvis presley"), False) self.assertEqual(valid.validate_name_surname("Elvis PResley"), False) self.assertEqual(valid.validate_name_surname( "Elvis Presleyqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq"), False) self.assertEqual(valid.validate_name_surname("Elvis P"), False) self.assertEqual(valid.validate_name_surname("Elvis P,resley"), False) self.assertEqual(valid.validate_name_surname("El1vis Presley"), False) self.assertEqual(valid.validate_age("20"), True) self.assertEqual(valid.validate_age("7"), False) self.assertEqual(valid.validate_age("100"), False) self.assertEqual(valid.validate_age("20."), False) self.assertEqual(valid.validate_age("20a"), False) self.assertEqual(valid.validate_age("12"), False) self.assertEqual(valid.validate_country("Ukraine"), True) self.assertEqual(valid.validate_country("U"), False) self.assertEqual(valid.validate_country( "UUUUUUUUUUUUUUUUUUUUUUU"), False) self.assertEqual(valid.validate_country("Ukraine1"), False) self.assertEqual(valid.validate_country("ukraine"), False) self.assertEqual(valid.validate_country("USA"), True) self.assertEqual(valid.validate_region("Lviv"), True) self.assertEqual(valid.validate_region("Lviv1"), True) self.assertEqual(valid.validate_region("L"), False) self.assertEqual(valid.validate_region("lviv"), False) self.assertEqual(valid.validate_living_place( "Koselnytska st. 2a"), True) self.assertEqual(valid.validate_living_place( "koselnytska st. 2a"), False) self.assertEqual(valid.validate_living_place( "Koselnytska provulok 2a"), False) self.assertEqual(valid.validate_living_place( "Koselnytska st. 2"), False) self.assertEqual(valid.validate_living_place( "Koselnytska st. a2"), False) self.assertEqual(valid.validate_living_place( "Koselnytska st. 22"), True) def test_phone_mail(self): """ This method cheks if the functtion works correctly. """ valid = Validator() self.assertEqual(valid.validate_index("79000"), True) self.assertEqual(valid.validate_index("7900"), False) self.assertEqual(valid.validate_index("790000"), False) self.assertEqual(valid.validate_index("7900q"), False) self.assertEqual(valid.validate_index("790 00"), False) self.assertEqual(valid.validate_phone("+380951234567"), True) self.assertEqual(valid.validate_phone("+38 (095) 123-45-67"), True) self.assertEqual(valid.validate_phone("38 (095) 123-45-67"), False) self.assertEqual(valid.validate_phone("380951234567"), False) self.assertEqual(valid.validate_phone("-380951234567"), False) self.assertEqual(valid.validate_phone("+3810951234567"), False) self.assertEqual(valid.validate_phone("+20951234567"), True) self.assertEqual(valid.validate_email("username@domain.com"), True) self.assertEqual(valid.validate_email( "username+usersurname@domain.com"), True) self.assertEqual(valid.validate_email("username@ucu.edu.ua"), True) self.assertEqual(valid.validate_email("usernamedomain.com"), False) self.assertEqual(valid.validate_email("usernam..edomain.com"), False) self.assertEqual(valid.validate_email("username@domaincom"), False) self.assertEqual(valid.validate_email("username@domain.aaa"), False) self.assertEqual(valid.validate_email("username@aaa"), False) self.assertEqual(valid.validate_email("@domain.com"), False) self.assertEqual(valid.validate_id("123450"), True) self.assertEqual(valid.validate_id("011111"), True) self.assertEqual(valid.validate_id("123456"), False) self.assertEqual(valid.validate_id("123006"), False) self.assertEqual(valid.validate_id("1230916"), False) self.assertEqual(valid.validate_id("12306"), False) self.assertEqual(valid.validate( "Elvis Presley,20,Ukraine,Lviv,Koselnytska st. 2a,79000,\ +380951234567,username@domain.com,123450"), True) self.assertEqual(valid.validate( "Elvis Presley;20;Ukraine;Lviv;Koselnytska st. 2a;79000;\ +380951234567;username@domain.com;123450"), True) self.assertEqual(valid.validate( "Elvis Presley; 20; Ukraine; Lviv; Koselnytska st. 2a; 79000;\ +380951234567; username@domain.com; 123450"), True) self.assertEqual(valid.validate( "Elvis Presley, 20, Ukraine, Lviv, Koselnytska st. 2a, 79000,\ +380951234567, username@domain.com, 123450"), True) self.assertEqual(valid.validate( "ElvisPresley, 20, Ukraine, Lviv, Koselnytska st. 2a, 79000, \ +380951234567, username@domain.com, 123450"), False) if __name__ == "__main__": unittest.main()
f781becc20b89fa939854ad2bc1f984af7115450
Minions1128/sorting_algorithm
/sort/select_sort.py
253
3.921875
4
def select_sort(array): for i in range(len(array)): _min = i for j in range(i, len(array)): if array[j] < array[_min]: _min = j array[_min], array[i] = array[i], array[_min] return array
000a81cb903328f4ae595eae436b1693e7b4bf06
eat-toast/Algorithm
/Baek_jun/1924.py
528
3.5625
4
day = {6: 'SUN', 0: 'MON', 1: 'TUE', 2: 'WED', 3: 'THU', 4: 'FRI', 5: 'SAT'} mon = {1 : 31, 2: 28, 3:31, 4: 30, 5: 31, 6: 30, 7: 31, 8: 31, 9: 30, 10: 31, 11: 30, 12: 31} # 1월 1일이 Mon 이다 # 시작일로 부터 현재까지 지난일 수를 더하고 7로 나누면 현재 요일이 나온다. x, y = map(int, input().split(' ')) after_mon = 0 for M in range(1, x, 1): after_mon += mon[M] after_day = after_mon + y idx = after_day % 7 if idx == 0: print(day[6]) else: print(day[idx-1])
bec2cb22a536528db70d1a39dd056ae6aeda0c29
kevhunte/hackerrank_leetcode_solutions
/leetcode/python/max_depth_binary_tree.py
1,265
3.65625
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: # DFS / Recursive def maxDepth(self, root: TreeNode) -> int: # recurse in a helper, return the num of calls at the leaf # take the max of all runs def depthHelper(node,count): if node is None: return count left = depthHelper(node.left,count+1) right = depthHelper(node.right,count+1) return max(left,right) #ans = depthHelper(root,0) return depthHelper(root,0) #ans # BFS / Iterative def maxDepth(self, root: TreeNode) -> int: # BFS, inc for each level level = [root] if root else [] count = 0 while level: count += 1 queue = [] for node in level: if node.left: queue.append(node.left) if node.right: queue.append(node.right) level = queue return count
97f705029cc049e46803d87020d73c2842a46c8a
kirtivr/leetcode
/Leetcode/2385.py
7,534
3.953125
4
from typing import List, Optional, Tuple import math import ast import pdb import time # Definition for a binary tree node. class TreeNode: def __init__(self, val, left=None, right=None): self.val = val self.left = left self.right = right class BST: head: Optional[TreeNode] def PrintTree(root: Optional[TreeNode]): if root == None: print("", end = "") return print(f'({root.val}', end = " ") PrintTree(root.left) PrintTree(root.right) print(f')', end = " ") def BSTTraverseLeft(popped: Optional[TreeNode], pq, tq): curr = popped # Minimum element is curr or curr.left. while curr.left != None: curr = curr.left # Add to print queue. pq.append(curr) #print(f'update after adding curr = {curr.idx} pq = {pq} tq = {tq}') def BSTTraverseInOrder(bst: BST, traversal, chunk): #pdb.set_trace() #PrintTree(bst.head) index = 0 # Iterative In Order Traversal. # Traverse left until no more elements. tq = [bst.head] pq = [] while (len(tq) > 0 or len(pq) > 0): popped = None if len(tq) > 0: popped = tq.pop() if popped == None: return pq.append(popped) if popped.left != None: BSTTraverseLeft(popped, pq, tq) elif len(pq) > 0: popped = pq.pop() # Add to traversal. traversal[index] = popped.idx index += 1 # Add the right element to tq. if popped.right: tq.append(popped.right) return def BSTInsert(bst: BST, priority: int, index: int): to_insert = TreeNode(priority, index, None, None) if bst.head == None: bst.head = to_insert return def TraverseTreeAndAdd(curr: Optional[TreeNode], to_insert: Optional[TreeNode]): # Curr cannot be None. if curr == None: print('Invariant broken') return if curr.val < to_insert.val: if curr.right == None: curr.right = to_insert return TraverseTreeAndAdd(curr.right, to_insert) return else: if curr.left == None: curr.left = to_insert return TraverseTreeAndAdd(curr.left, to_insert) return TraverseTreeAndAdd(bst.head, to_insert) def MakeBSTFromSortedList(input: List[int]): # Making the BST from a sorted list lets it be more balanced compared to a # random list. if not input: return None def recurseAndCreateTreeFromList(input: List[int], left, right): if left > right: return mid = left + (right - left)//2 root = TreeNode(input[mid], None, None) root.left = recurseAndCreateTreeFromList(input, left, mid - 1) root.right = recurseAndCreateTreeFromList(input, mid + 1, right) return root return recurseAndCreateTreeFromList(input, 0, len(input) - 1) def MakeBinaryTreeFromList(input: List[int]): if not input: return None root = None current = None # If element at "i" is root, element at "i + 1" is left # and element at "i + 2" is right. i = 0 queue = [TreeNode(input[0], None, None)] while queue: parent = queue.pop(0) if parent.val == None: continue if root == None: root = parent if i * 2 + 1 < len(input) and input[i * 2 + 1] is not None: new_node = TreeNode(input[i * 2 + 1], None, None) queue.append(new_node) parent.left = new_node if i * 2 + 2 < len(input) and input[i * 2 + 2] is not None: new_node = TreeNode(input[i * 2 + 2], None, None) queue.append(new_node) parent.right = new_node i += 1 return root def MakeBSTFromList(input: List[int]): pass def BSTTraverseInOrder(bst: BST, traversal): index = 0 def do_traverse(curr: Optional[TreeNode], traversal): global index if curr == None: return do_traverse(curr.left) do_traverse(curr.right) traversal[index] = curr.val index += 1 return def BSTInsert(bst: BST, el: int): to_insert = TreeNode(el, None, None) if bst.head == None: bst.head = to_insert return def TraverseTreeAndAdd(curr: Optional[TreeNode], to_insert: Optional[TreeNode]): # Curr cannot be None. if curr == None: print('Invariant broken') return if curr.val < to_insert.val: if curr.right == None: curr.right = to_insert return TraverseTreeAndAdd(curr.right, to_insert) return else: if curr.left == None: curr.left = to_insert return TraverseTreeAndAdd(curr.left, to_insert) return TraverseTreeAndAdd(bst.head, to_insert) def Height(head: Optional[TreeNode]): if head == None: return 0 return max(1 + Height(head.left), 1 + Height(head.right)) def CountNodes(head: Optional[TreeNode]): if head == None: return 0 return 1 + CountNodes(head.left) + CountNodes(head.right) class Solution: def __init__(self) -> None: self.maxTime = 0 def traverse(self, root: Optional[TreeNode], start: int): if root == None: return (False, -1) if root.val == start: # Root is infected. # Return the amount of time it takes to reach the leaf node. lh = self.traverse(root.left, start)[1] rh = self.traverse(root.right, start)[1] self.maxTime = max(self.maxTime, 1 + max(lh, rh)) #print(f'\n{root.val} found!, lh = {lh} rh = {rh} max = {self.maxTime} out = {(True, 1 + max(lh, rh) if lh > 0 or rh > 0 else 0)}') return (True, 0) (lf, lh) = self.traverse(root.left, start) (rf, rh) = self.traverse(root.right, start) if lf and rh >= 0: # It takes one minute to percolate up and then one minute to get to the right node. self.maxTime = max(self.maxTime, max(1, 1 + lh, 2 + lh + rh)) elif rf and lh >= 0: self.maxTime = max(self.maxTime, max(1, 1 + lh, 2 + lh + rh)) elif lf or rf: self.maxTime = max(self.maxTime, max(1, 1 + lh, 1 + rh)) outh = 0 if lf: outh = 1 + lh elif rf: outh = 1 + rh else: outh = 1 + max(lh, rh) out = (lf or rf, outh) #print(f'\ncurrent node = {root.val} lf = {lf} rf = {rf} lh = {lh} rh = {rh} max = {self.maxTime} out = {out}') return out def amountOfTime(self, input: List[int], start: int) -> int: root = self.CreateTree(input) self.traverse(root, start) return self.maxTime def CreateTree(self, input: List[int]) -> TreeNode: root = MakeBinaryTreeFromList(input) #PrintTree(root) return root if __name__ == '__main__': x = Solution() start = time.time() with open('2385_tc.text', 'r') as f: n = ast.literal_eval(f.readline()) start = ast.literal_eval(f.readline()) #print(edges) print(x.amountOfTime(n, start)) end = time.time() elapsed = end - start print(f'time elapsed: {elapsed}')
64d995ba53cee507db1b0ea02993a50e7bc3a2be
Tr4shL0rd/mathScripts
/blandedeTal/blandede_tal_Brøker_minus.py
1,318
3.71875
4
from fractions import Fraction try: def fracToMixed(num,dem): a = num // dem b = num % dem #print(a) print("{} {}/{}".format(a, b, dem)) print() main() def gcd(a, b): if (a == 0): return b; return gcd(b % a, a); def lowest(den3, num3): common_factor = gcd(num3, den3); den3 = int(den3 / common_factor); num3 = int(num3 / common_factor); #print(num3, "/", den3); fracToMixed(num3,den3) def addFraction(num1, den1, num2, den2): den3 = gcd(den1, den2); den3 = (den1 * den2) / den3; num3 = ((num1) * (den3 / den1) - (num2) * (den3 / den2)); lowest(den3, num3); def main(): loop = True while loop == True: heltal1 = int(input("heltal1 = "))#2 tæller1 = int(input("tæller1 = "))#2 nævner1 = int(input("nævner1 = "))#3 heltal2 = int(input("heltal2 = "))#3 tæller2 = int(input("tæller2 = "))#1 nævner2 = int(input("nævner2 = "))#2 brøkTop1 = heltal1 * nævner1 + tæller1 brøkBot1 = nævner1 brøkTop2 = heltal2 * nævner2 + tæller2 brøkBot2 = nævner2 #print(f"{brøkTop1} / {brøkBot1}") #print(f"{brøkTop2} / {brøkBot2}\n") addFraction(brøkTop1, brøkBot1, brøkTop2, brøkBot2) #loop = False main() except KeyboardInterrupt: print("goodbye")
b0f9eaea8c87bdb418ba016a02e982d217b7a4b4
emersonsemidio/python
/Desafio61.py
242
3.71875
4
import time a = int(input('Digite o primeiro termo: ')) b = int(input('Digite a razão: ')) cont = 0 termo = a while cont <10: print('{}'.format(termo),end=' > ') termo = termo + b cont = cont +1 time.sleep(2) print('FIM')
4e87d6cb56ce9ac5f28b7c46bb646d774f2f2649
nanapereira/python-introducao
/desafios/desafio_retangulo_circulo.py
557
3.5
4
from math import pi class Retangulo: def __init__(self, lado_x, lado_y): self.lado_x = lado_x self.lado_y = lado_y def calcular_area_retangulo(self): return self.lado_x * self.lado_y def calcular_perimetro_retangulo(self): return (self.lado_x * 2) + (self.lado_y * 2) class Circulo: def __init__(self, raio): self.raio = raio def calcular_area_circulo(self): return (self.raio ** 2) * math.pi def calcular_perimetro_circulo(self): return 2 * math.pi * self.raio
0aea0a41da8bdb87b05d1f1e75c63d12e2851fd7
azureleaf/utilities
/anagram/main.py
1,608
3.6875
4
import romkan import itertools src_hiragana = "あさって" # Container of the anagrams generated anagrams = [] # Note that only the vowels "a", "u", "o" can connect to # these double consonants in MOFA's Hepburn Romaji double_consonants = ["ky", "sh", "ch", "ny", "hy", "my", "ry", "gy", "by", "py"] def grow_stem(pool, stem=[]): '''(Unused function) Get a single char from the pool, append it to the stem''' global anagrams if len(pool) == 0: anagrams.append(stem) else: for i, char in enumerate(pool): new_stem = stem.copy() new_pool = pool.copy() new_stem.append(char) new_pool.pop(i) grow_stem(new_pool, new_stem) def get_anagrams(src_str): '''Get iterator of anagrams for the list of chars given''' return itertools.permutations(src_str, len(src_str)) def decompose_hiraganas(hiraganas): '''Decompose the hiragana str into consonants & vowels''' alphabets = [] # Convert hiragans into Romaji, # then divide string (e.g. "abc") into list (e.g. ["a", "b", "c"]) alphabets[:0] = romkan.to_roma(hiraganas) vowels = [] for i, alphabet in enumerate(alphabets): if alphabet in ["a", "e", "i", "o", "u"]: vowels.append(alphabets.pop(i)) return {"consonants": alphabets, "vowels": vowels} def group_consonants(consonants): collections = [] return collections anagrams = get_anagrams(["ch", "b", "y", "k"]) for v in anagrams: print(v) # alphabets = decompose_hiraganas(src_hiragana) # print(alphabets)
8542098909a2582c49c5818ff63ef8198dc0b681
czchen1/cs164-projects
/proj2/tests/error2/D5.py
110
3.5
4
class A: x = 3 def __init__(self): pass def f(self): if self.x > 0: return x
294b15673cbb073a1c6618c3513817626ee0bfef
sat5297/AlgoExperts.io
/Easy/NthFibonacci.py
897
3.8125
4
#Approach 1: Recursive def getNthFibRec(n): if n==2: return 1 elif n==1: return 0 else: return getNthFib(n-1) + getNthFib(n-2) # Time Complexity = O(2^n) # Space Complexity = O(n) ############################# #Approach 2: Memoization def getNthFibMem(n, memoize={1:0, 2:1}): if n in memoize: return memoize[n] else: memoize[n] = getNthFibMem(n-1, memoize) + getNthFibMem(n-2, memoize) return memoize[n] # Time Complexity = O(n) # Space Complexity = O(n) ############################# #Approach 3: Iterative def getNthFibIter(n): lastTwo = [0,1] counter = 3 while counter<=n: nextFib = lastTwo[0] + lastTwo[1] lastTwo[0] = lastTwo[1] lastTwo[1] = nextFib counter+=1 return lastTwo[1] if n>1 else lastTwo[0] # Time Complexity = O(n) # Space Complexity = O(1)
c3e834eef13cf670f8c4f4a2dd1ea7ae8a1fa1bf
BommakantiHarshitha-1/O11_Cp-Python
/Module-13/CP-ELECTIVE-02-wordwrap-Python/02-wordwrap-Python/wordwrap.py
1,078
4.40625
4
# Write the function wordWrap(text, width) that takes a string of text (containing only lowercase letters # or spaces) and a positive integer width, and returns a possibly-multiline string that matches the # original string, only with line wrapping at the given width. So wordWrap("abc", 3) just returns "abc", # but wordWrap("abc",2) returns a 2-line string, with "ab" on the first line and "c" on the second line. # After you complete word wrapping in this way, only then: All spaces at the start and end of each # resulting line should be removed, and then all remaining spaces should be converted to dashes ("-"), # so they can be easily seen in the resulting string. Here are some test cases for you: # assert(wordWrap(" abcdefghij", 4) == """\ # abcd # efgh # ij""") # assert(wordWrap(" a b c de fgh ", 4) == """\ # a-b- # c-de # -fgh""") import textwrap def fun_wordwrap(s, n): s1=[] s=("-".join(s.split())) for i in range(0,len(s),n): s1.append(s[i:i+n]) return ("\n".join(map(str,s1)))
630936f5057afb03f5b057cbb458a695c90080dc
ArtemKonnov/python_stepik
/2.6.3.py
906
3.90625
4
# Напишите программу, которая считывает список чисел lstlst из первой строки и число xx из второй строки, которая выводит все позиции, на которых встречается число xx в переданном списке lstlst. # Позиции нумеруются с нуля, если число xx не встречается в списке, вывести строку "Отсутствует" (без кавычек, с большой буквы). # Позиции должны быть выведены в одну строку, по возрастанию абсолютного значения. a = [int(i) for i in input().split()] b = int(input()) if b in a: for i in range(len(a)): if a[i] == b: print(i, end=" ") else: print("Отсутствует")
99f22b207bebc9b65baba6da5acee2e1c24987b3
gurupunskill/Competitive-Programming
/archive/deprecated/week-1/program-1.py
559
3.703125
4
#!/bin/python3 # Question: https://www.hackerrank.com/challenges/breaking-best-and-worst-records/problem # O(n) import sys # Attempt 1: def getRecord(s): highest = s[0] lowest = s[0] high_count = 0 low_count = 0 for i in s: if i > highest: high_count += 1 highest = i if i < lowest: low_count += 1 lowest = i return high_count, low_count n = int(input().strip()) s = list(map(int, input().strip().split(' '))) result = getRecord(s) print (" ".join(map(str, result)))
cab162bd2b0ae715227e5400c9f93b2a69b0d650
giurgiumatei/Graph-Algorithms
/Lab3/UI.py
1,898
3.546875
4
from Domain import * from copy import deepcopy class UI: def __init__(self,graph):#the UI is initialised with the graph self.graph=graph def print_menu(self): # prints the menu print("11.Represent the graph using the set of inbound edges: ") print("12.Represent the graph using the set of outbound edges: ") print("13.Find out the lowest cost path from node A to node B: ") def start(self): # UI starts here while True: self.print_menu() while True: try: op=int(input()) assert op>=11 and op<=13 or op==0 break except:print("Give a valid option! ") # op stores the option chosen by the user and using the following if statements # will help execute the afferent method if op == 0: break elif op==11: self.option11() elif op==12: self.option12() elif op==13: self.option13() def option11(self): print(self.graph.inbound) def option12(self): print(self.graph.outbound) def option13(self): vertices=self.graph.get_vertices() source_point=input("Give the starting node: ") destination_point=input("Give the destination node: ") if source_point not in vertices or destination_point not in vertices: print("Invalid input! ") else: result=self.graph.Dijkstra(destination_point,source_point) #backwards search if result!=None: print(result[0]) print("Cost is "+str(result[1])) else: print("There is no path! ")
579e8d59d0c96951e955d5d40e3f3939296879f1
takafuji23/Python
/1-2-1.py
230
4.0625
4
def is_anagram(_str1, _str2 ): if "".join(sorted(_str1)) == "".join(sorted(_str2)): return True else: return False k = False while k == False: _str1, _str2 = map(str, raw_input().split(" ")) k = is_anagram(_str1, _str2)
a251cd44e5068f33509dd4902fe07f6bd298fa21
Marcos-Valencia/practicePython
/ex8rps.py
1,275
4.09375
4
print("WELCOME TO RPS") user1 = str(input("who will be player 1?")) user2 = str(input("who will be player 2?")) game_status = str("ongoing") user1_trn = str(user1) + ", Paper Rock or Scissors?" user2_trn = str(user2) + ", Paper Rock or Scissors?" print("This is RPS(Rock Paper Scissors)\n " "To quite Type out as soon as you get a winner\n" "Rock = 1\n" "Paper = 2\n" "Scissors = 3") while game_status !=str("out"): user1_move = int(input(user1_trn)) user2_move = int(input(user2_trn)) if user1_move == user2_move: print("draw") elif user1_move ==1 and user2_move == 3: print(user1, " is the winner Congrats") elif user2_move ==1 and user1_move == 3: print(user2, " is the winner Congrats") elif user1_move ==3 and user2_move ==2: print(user1, " is the winner Congrats") elif user2_move ==3 and user1_move ==2: print(user2, " is the winner Congrats") elif user1_move ==2 and user2_move ==1: print(user1, " is the winner Congrats") elif user2_move == 2 and user1_move == 1: print(user2, " is the winner Congrats") game_status = str(input("Do you want to quite? Type 'out' if so else type any other character/s \n "))
69ae4f5791b0739975a8793bd19ce100524b6b9f
rsgmon/api_retrieval
/api_retrieval/setup_api_parameters.py
1,238
3.890625
4
import argparse import json from .config import APIConfig import sys def parse_args(args=None): if not args: return None parser = argparse.ArgumentParser(description='Path to the config file.') parser.add_argument('path', help='Specify the absolute path of the config file.') return parser.parse_args(args) def read_config_file(file_path): if not file_path: return None with open(file_path.path, 'r') as config_file: config_object = json.loads(config_file.read()) if type(config_object) != type([]): config_object = [config_object] return config_object def create_config_collection(config_collection): return [APIConfig(x) for x in config_collection] def config_operation(): parsed = parse_args(sys.argv[1:]) return create_config_collection(read_config_file(parsed)) #So I read a json object from the json file which can contain many config objects. I then return a collection of config objects. Now what I could do is say "hey I want to run this with a parameter one time and get data, or I want this to run everytime it checks a folder and that folder has changed, or if I input a variable I get a menu that allows me to run via inputing a config file location.
a20f18fcee5574fa3b4179bfb44f56455f247da5
robertoItSchool/homework
/ex3.py
836
4.3125
4
# 3. Exercises with lists list1 = [1, 3, 45, -7, 89, 3, 1, 12, 3, 3, 1, 3] list2 = ["a", "cd", "b", "b", "f", "oj", "Zz"] list3 = [1, 2, "a", 34, "bgh", "#"] # a. eliminate all elements from list3 # list3.clear() # b. eliminate all 3s from list1 print(list1) while 3 in list1: list1.remove(3) print(list1) # c. sort list1 from the biggest number to the lowest list1.sort(reverse=True) print(list1) # d. sort list2 without "Zz" print(list2) list2.pop() list2.sort() print(list2) # e. make list3 in the reverse order print(list3) list3.reverse() print(list3) # f. eliminate last 3 elements from list 2, last element from list3 and last 2 elements from list1 i = 3 print(list2) # while i > 0: # list2.pop() # i -= 1 # print(list2) list2 = list2[:-2] print(list2) # g. how many "b" values are in list2 print(list2.count('b'))
b500fd177e68ab68c723c885b50dc05dbe3cf044
evanSpendlove/CompetitiveProgramming
/Kattis/qaly.py
594
3.859375
4
# Kattis - Quality of Life Problem - Code: qaly # Written by Evan Spendlove def qaly(): numPeriods = int(input()) sumQaly = 0 period = numPeriods while(period > 0): # For each period in the given number [quality, numYears] = input().split(" ") # Gets the quality of life for the given period quality = float(quality) numYears = float(numYears) sumQaly += (quality * numYears) # Add the quality x number of years to the running total period = period-1 print(round(sumQaly, 3)) # Output the total Qaly def main(): qaly() main()
ab746bd82b53f855c4f107143b3e2cf3ce2da6a0
artificial-cassiano/yapCAD
/examples/example7.py
3,722
3.578125
4
## yapCAD poly() intersecton and drawing examples print("example7.py -- yapCAD computational geometry and DXF drawing example") print(""" In this demo we create open and closed polyline figures and calculate intersections with lines and arcs. We draw the elememnts so we can visibly confirm the correctness of the intersection calculations.""") from yapcad.ezdxf_drawable import * from yapcad.geom import * #set up DXF rendering dd=ezdxfDraw() filename="example7-out" print("Output file name is {}.dxf".format(filename)) dd.filename = filename dd.layer = 'DOCUMENTATION' dd.draw_text("yapCAD", point(-12,13),\ attr={'style': 'OpenSans-Bold', 'height': 1.5}) dd.draw_text("example7.py", point(-12,10)) dd.draw_text("polygons, polylines, arcs,", point(-12,8)) dd.draw_text("and intersections", point(-12,6.5)) dd.layer = False # make some points centerd at the origin to be used as vertices for # our polys a = point(0,-5) b = point(5,0) c = point(0,5) d = point(-5,0) ## these are offsets that we will for the above points to create two separate ## offset polyline figures offset1 = point(-4,-4) offset2 = point(4,4) ## make an open polyline figure in the XY plane from the points we ## defined above, offset by offset1 ## Note, I like lambda expressions and map, but there are lots ## of other ways to accomplish this offset. pol1 = poly(list(map(lambda x: add(x,offset1),[a,b,c,d]))) ## make a closed polyline figure in the XY plane from the points we ## defined above, offset by offset2 pol2 = poly(list(map(lambda x: add(x,offset2),[a,b,c,d,a]))) line1 = line(offset1,add(offset1,point(4,4))) line2 = line(add(offset1,point(0,-6)),add(offset1,point(0,6))) arc1 = arc(offset1,4.0,270,90) arc2 = arc(offset1,4.5,0,360) line3 = line(offset2,add(offset2,point(4,4))) line4 = line(add(offset2,point(0,-6)),add(offset2,point(0,6))) arc3 = arc(offset2,4.0,270,90) arc4 = arc(offset2,4.5,0,360) dd.polystyle='lines' dd.draw(pol1) dd.draw(pol2) dd.layer = 'PATHS' dd.linecolor = 1 dd.draw(line1) dd.draw(line2) dd.draw(line3) dd.draw(line4) dd.linecolor = 4 dd.draw(arc1) dd.draw(arc2) dd.draw(arc3) dd.draw(arc4) dd.linecolor = False ## Do some intersection calculation int0 = intersectXY(line1,pol1,True) int1 = intersectXY(line2,pol1,True) int2 = intersectXY(arc1,pol1,True) int2u =intersectXY(arc1,pol1,params=True) int3 = intersectXY(arc2,pol1,True) int3u = intersectXY(arc2,pol1,params=True) int10 = intersectXY(line3,pol2,True) int11 = intersectXY(line4,pol2,True) int12 = intersectXY(arc3,pol2,True) int12u =intersectXY(arc3,pol2,params=True) int13 = intersectXY(arc4,pol2,True) int13u = intersectXY(arc4,pol2,params=True) ## draw intersection points on documentation layer dd.layer = 'DOCUMENTATION' dd.polystyle = 'points' dd.draw(int0 + int1 + int10 + int11) dd.pointstyle='o' i = 6 for p in int2 + int12: dd.draw(p) # dd.draw(arc(p,0.1*i)) i = i+1 dd.pointstyle='x' i = 6 for u in int2u[1]: p = samplepoly(pol1,u) #print("sample point: ",vstr(p)) dd.draw(p) #dd.draw(arc(p,0.1*i)) i = i+1 i = 6 for u in int12u[1]: p = samplepoly(pol2,u) dd.draw(p) #dd.draw(arc(p,0.1*i)) i = i+1 dd.pointstyle='o' i = 6 for p in int3 + int13: dd.draw(p) #dd.draw(arc(p,0.1*i)) i = i+1 dd.pointstyle='x' i = 6 for u in int3u[1]: p = samplepoly(pol1,u) #print("sample point: ",vstr(p)) dd.draw(p) #dd.draw(arc(p,0.1*i)) i = i+1 i = 6 for u in int13u[1]: p = samplepoly(pol2,u) dd.layer = 'DOCUMENTATION' dd.draw(p) dd.layer = 'DRILLS' dd.draw(arc(p,0.1*i)) i = i+1 dd.display()
7067f7dd24150f640409c644cc1856fe4a741e3b
ykushla/TES-P
/yk/data/frame.py
598
4.03125
4
class Frame: # Frame class provides a structure for abstract datasets storage and representation def __init__(self, names, items): self.names = names self.items = items def print_to_console(self): # prints the data to console for name in self.names: print(str(name) + "\t", end="") print() for item in self.items: for name in self.names: value = item[name] if value == "": value = "-" print(str(value) + "\t", end="") print()
f86ada03d5ca1220de7162504a4fca811fdb2cf8
esvarmajor/AICamp
/EsvarabalaK/MyPet.py
577
3.625
4
class MyPet: def __init__(self, name): self.name = name self.trust=0 def pet(self): print("Your pet " + self.name + " seemed happy that you pet them.") def make_noise(self): print("Noise noise noise.") def spend_time(self,minutes_spent): self.trust=minutes_spent orange_cat = MyPet("Miles") small_dog = MyPet("Fido") print(orange_cat.name) small_dog.pet() class MyDog(MyPet): def bark(self): print("Woof woof woof") my_dog = MyDog("Spike") my_dog.pet() my_dog.bark()
426c00aa93e86cc3d8241c37528ccc8eca70b73b
couchjanus/python-fundamental
/index.str.test.py
1,789
4.03125
4
# -*- coding: utf-8 -*- # index.str.test.py word = 'Help' + 'A' print(word[4]) char = "C" print(char[0]) print(word[0:2]) print(word[2:4]) print(word[:2]) # Первые два символа print(word[2:]) # Всё, исключая первые два символа # В отличие от строк в C, строки Python не могут быть изменены. # Присваивание по позиции индекса строки вызывает ошибку: # print(word[0] = 'x') print('x' + word[1:]) print('Splat' + word[4]) print(word[:2] + word[2:]) print(word[:3] + word[3:]) #чересчур большой индекс заменяется на размер строки, print(word[1:100]) # а верхняя граница меньшая нижней возвращает пустую строку. print(word[10:]) print(word[2:1]) # Индексы могут быть отрицательными числами, # обозначая при этом отсчет справа налево: print(word[-1]) # Последний символ print(word[-2]) # Предпоследний символ print(word[-2:]) # Последние два символа print(word[:-2]) # Всё, кроме последних двух символов # Но обратите внимание, что -0 действительно # эквивалентен 0 - это не отсчет справа. print(word[-0]) # (поскольку -0 равен 0) # Отрицательные индексы вне диапазона обрезаются, # но не советуем делать это с одно-элементными индексами (не-срезами): word[-100:] # word[-10] # ошибка
d53f82ebdc1ec386356052c14f35c72a84b8bd77
amadabhu/funtime
/Vowel_remover.py
359
3.59375
4
class vowel_remover: def removeVowels(self, S: str) -> str: vowels = list('aeiou') s_ls = list(S) seperator = "" new_ls = [] for letter in s_ls: if letter not in vowels: new_ls.append(letter) else: continue S = seperator.join(new_ls) return S
e00dff8735ecbcfc952e3111e7baa13d1d254c1a
Markboerrigter/webapp
/python_files/tagging_from_xml_Mark.py
6,796
3.59375
4
#import the needed packages #a common package to work with data in Python import pandas as pd #used to do stuff with regex (for recognizing the product id) import re #used to read data from sql database from pymongo import MongoClient import importlib def retrieve_links(csv_path,col_names,split_name): """ Gets a dataframe with links from a database table links_db: name of the database which contains links links_table: the name of the table in the database which contains the needed links col_names: a list with all the column names you want in the dataframe (except urls) split_name: string with from where on to cut the url links: a dataframe which contains the links of the folder (urls) """ #import the csv by pandas links=pd.read_csv(csv_path,encoding='utf-8') #have to change this if you change column name in database #change column name, just for ease of rest of proces links.columns=['urls'] #THIS MIGHT HAVE TO BE CHANGED, DEPENDING ON THE FORMAT OF THE URLS WE GET #only get the first part of the link links.urls=[i[:int(i.find(split_name))] if split_name and i.find(split_name)!=-1 else i for i in links.urls] #initialize all the columns for i in col_names: links[i]=None return links def retrieve_vars(db,ret): """ Retrieve the retailer specific information from the database and return a dictionary with this information ret: the name of the retailer retail_var: a dictionary with the information from the retailer """ #select all information collection = db.variables_retailers retail_var=dict(collection.find_one({"retailer":ret})) print("retail_vars loaded") return retail_var def split_cat(delimiter,links,main_category,all_categories): #split the name into categories from main to sub-bers for idx,cat in enumerate(links[main_category]): if links.loc[idx,main_category]: category_split=cat.split(delimiter) attr=category_split+[None]*(len(all_categories)-len(category_split)) links.loc[idx,all_categories]=attr return links def fill_tags(xml_db,retail_var,links,col_names): """ Loop through the links and check if there is an entry in the xml file that contains this link. If so, get the values of the given categories of that product and write them to the dataframe. xml_db: name of database containing the xml table_name: the name of the table containing the xml retail_var: dictionary with retailer specific information links (in): dataframe with the links in the folder links (out): dataframe with the links in the folder and the found tags that belong to each links """ all_categories=['category','category2','category3','category4','category5','category6'] collect_name='xml_'+retail_var['retailer'] try: collection = xml_db[collect_name] except Exception as e: print(e) print("you should first initialize a xml database") print('collection initialized') #loop over all urls for idx,start in enumerate(links.urls): #select the information from the row of the xml database where the link is like the link from the folder query={} query["link"]={'$regex':".*"+start+".*"} hit=collection.find_one(query) #if there is a link like the one from the folder if hit: hit={your_key: hit[your_key] for your_key in hit.keys() if your_key not in ['link','_id']} #set those values in the dataframe #links.loc[idx,col_names]=vals[0] for k in hit.keys(): links.loc[idx,k]=hit[k] if links.loc[idx,'category'] and retail_var['delimiter']: if type(links.loc[idx,'category']) ==list: links.loc[idx,'category']=''.join(links.loc[idx,'category']) category_split=links.loc[idx,'category'].split(retail_var['delimiter']) links.loc[idx,all_categories]=category_split+[None]*(len(all_categories)-len(category_split)) #if there is no current price but there is an old price, set the old price as current price #this because some retailers have a price and a sale price. if not links.price.loc[idx] and 'price_old' in col_names: links.price.loc[idx]=links.price_old.loc[idx] #if a price is found #HAVE TO TEST IF THIS ALWAYS WORKS for k in ['price','price_old']: if links.loc[idx,k]: #remove all none currency related characters links.loc[idx,k]=re.sub('[^0-9.,-]','',links.loc[idx,k]) #make it in a general format links.loc[idx,k]=links.loc[idx,k].replace('-','00').replace(',','.') #calculate the discount p=links.price.loc[idx] o=links.price_old.loc[idx] if p!=None and o!=None and p!=o: links.discount.loc[idx]=str(int(round((1-float(p)/float(o))*100)))+'%' #price_old is only for computing purposes so can be deleted del links['price_old'] print('tags filled') return links def save_to_csv(links,csv_out): """ save the dataframe with links and tags to a database links (in):dataframe with links and tags table_out: the name of the table the tags should be saved in links (out): the dataframe with links and tags """ #write the results to a csv links.to_csv(csv_out,index=False,encoding='utf-8') #not fully necessary but might come in handy return links def tags_from_xml(ret, week,csv_name): client = MongoClient('ds119533.mlab.com', 19533) db = client['tagging'] db.authenticate('hahamark','hahamark') csv_out='tags_'+ret+'_'+week+'.csv' #table=ret+'_week'+week xml_table='xml_'+ret col_names=['title','brand','price','price_old','discount','category','category2','category3','category4','category5','category6','category7','persuasion'] retail_var=retrieve_vars(db,ret) links=retrieve_links(csv_name,col_names,retail_var['split_name']) #get the tags from the xml if retail_var['xml']: links=fill_tags(db,retail_var,links,col_names) if 'price_old' in links.columns: del links['price_old'] links=save_to_csv(links,'csv_output/beforescrape'+ csv_out) if retail_var['scrape']==True: module_name='webscraping_'+ret module = importlib.import_module('python_files.webscraping.' + module_name) links=module.scrape(links) download_path = 'csv_output/'+ csv_out links=save_to_csv(links,'csv_output/'+ csv_out) print('links saved to csv') return links, download_path
1cddb3b74519620edbfe27461dc42d1b8997c182
opwtryl/leetcode
/746. 使用最小花费爬楼梯.py
1,371
3.796875
4
''' 数组的每个索引做为一个阶梯,第 i个阶梯对应着一个非负数的体力花费值 cost[i](索引从0开始)。 每当你爬上一个阶梯你都要花费对应的体力花费值,然后你可以选择继续爬一个阶梯或者爬两个阶梯。 您需要找到达到楼层顶部的最低花费。在开始时,你可以选择从索引为 0 或 1 的元素作为初始阶梯。 示例 1: 输入: cost = [10, 15, 20] 输出: 15 解释: 最低花费是从cost[1]开始,然后走两步即可到阶梯顶,一共花费15。 示例 2: 输入: cost = [1, 100, 1, 1, 1, 100, 1, 1, 100, 1] 输出: 6 解释: 最低花费方式是从cost[0]开始,逐个经过那些1,跳过cost[3],一共花费6。 注意: cost 的长度将会在 [2, 1000]。 每一个 cost[i] 将会是一个Integer类型,范围为 [0, 999]。 ''' # 时间复杂度:O(n) # 空间复杂度:O(1) class Solution: def minCostClimbingStairs(self, cost): """ :type cost: List[int] :rtype: int """ ''' 状态转移方程:F(i)=min(F(i-1),F(i-2))+cost[i] 边界:F(1)=cost[1],F(2)=cost[2] ''' first=cost[0] second=cost[1] for i in range(2,len(cost)): third=min(first,second)+cost[i] first=second second=third return min(first,second)
e9d109e49e4a2bb1c9c6b4251b647a510cdc0247
rodrigosantosti01/LingProg
/Exercicio5/atv03.py
4,919
3.828125
4
# 3 Jogo de Blackjack: Faça um joguinho simples em Python. # Aqui estão os requisitos: # - Você precisa criar um jogo de BlackJack (21) baseado em texto simples # - O jogo precisa ter um jogador contra um croupier automatzado. # - O jogador pode desistr ou bater. # - O jogador deve ser capaz de escolher o seu valor de aposta. # - Você precisa acompanhar o dinheiro total do jogador. # - Você precisa alertar o jogador de vitórias, derrotas ou estouros, etc ... # E o mais importante: # Você deve usar OOP e classes em alguma parte do seu jogo. Você não pode # simplesmente usar funções no seu jogo. Use classes para ajudá-lo a definir o deck e a # mão do jogador. Há muitas maneiras certas de fazer isso, então explore bem! import random, os, sys cartas = { 1: 'Ás', 2: 'Dois', 3: 'Três', 4: 'Quatro', 5: 'Cinco', 6: 'Seis', 7: 'Sete', 8: 'Oito', 9: 'Nove', 10: 'Dez', 11: 'Valete', 12: 'Rainha', 13: 'Rei' } naipes = { 'p': 'Paus', 'c': 'Copas', 'e': 'Espadas', 'o': 'Ouro' } valorAposta = float(input("Digite um valor a ser apostado:")) valorCroupier = valorAposta valorJogador = valorAposta class Cartas: def __init__(self, rank, suit): self.rank = rank self.suit = suit def __str__(self): return(cartas[self.rank]+" de "+ naipes[self.suit]) def rank(self): return(self.rank) def naipe(self): return(self.suit) def arredonda(self): if self.rank > 9: return(10) else: return(self.rank) def mostraMao(hand): for Cartas in hand: print(Cartas) def mostraContagem(hand): print("Contagem das Cartas: "+str(cartasContagem(hand))) def cartasContagem(hand): cartasContagem=0 for Cartas in hand: cartasContagem += Cartas.arredonda() return(cartasContagem) def fim(score,money): print("Blackjack! *Placar final* croupier: "+str(score['croupier'])+" Você: "+str(score['jogador'])) print("Saldo Final: croupier: "+str(money['croupier'])+" Você: "+str(money['jogador'])) sys.exit(0) deck = [] suits = [ 'p','c','e','o' ] score = { 'croupier': 0, 'jogador': 0 } money = {'croupier':valorCroupier, 'jogador': valorJogador} hand = { 'croupier': [],'jogador': [] } for suit in suits: for rank in range(1,14): deck.append(Cartas(rank,suit)) continuarJogando = True while continuarJogando: random.shuffle(deck) random.shuffle(deck) random.shuffle(deck) hand['jogador'].append(deck.pop(0)) hand['croupier'].append(deck.pop(0)) hand['jogador'].append(deck.pop(0)) hand['croupier'].append(deck.pop(0)) playjogador = True bustedjogador = False while playjogador: os.system('clear') print("Blackjack! croupier: "+str(score['croupier'])+" Você: "+str(score['jogador'])) print("Saldo jogadores:"+str(money['croupier'])+" Você: "+str(money['jogador'])) print() print('Sua Mão:') mostraMao(hand['jogador']) mostraContagem(hand['jogador']) print() inputCycle = True userInput = '' while inputCycle: userInput = input("(C)Continuar , (P)Parar, ou (S)Sair: ").upper() if userInput == 'C' or 'P' or 'S': inputCycle = False if userInput == 'C': hand['jogador'].append(deck.pop(0)) if cartasContagem(hand['jogador']) > 21: playjogador = False bustedjogador = True elif userInput == 'P': playjogador = False else: fim(score,money) playcroupier = True bustedcroupier = False while not bustedjogador and playcroupier: print(cartasContagem(hand['croupier'])) if cartasContagem(hand['croupier'])<17: hand['croupier'].append(deck.pop(0)) else: playcroupier = False if cartasContagem(hand['croupier'])>21: playcroupier = False bustedcroupier = True if bustedjogador: print('Você perdeu!') money['croupier'] += valorAposta money['jogador'] -= valorAposta score['croupier'] += 1 elif bustedcroupier: print('croupier perdeu') money['croupier'] -= valorAposta money['jogador'] += valorAposta score['jogador'] += 1 elif cartasContagem(hand['jogador']) > cartasContagem(hand['croupier']): print('Você Ganhou!') money['croupier'] -= valorAposta money['jogador'] += valorAposta score['jogador'] += 1 elif cartasContagem(hand['jogador']) == cartasContagem(hand['croupier']): print('Empate!') else: print('croupier Ganhou!') money['croupier'] += valorAposta money['jogador'] -= valorAposta score['croupier'] += 1 print() print('Mão da Máquina:') mostraMao(hand['croupier']) mostraContagem(hand['croupier']) print() print('Sua mão:') mostraMao(hand['jogador']) mostraContagem(hand['jogador']) print() if input("Precione (S) para sair ou enter para jogar a próxima rodada").upper() == 'S': fim(score,money) # if (money['croupier']) <= 0.0 or (money['jogador']<=0.0): # print("Jogador nao tem saldo") # fim(score,money) valorAposta = float(input("Digite um novo valor a ser apostado:")) deck.extend(hand['croupier']) deck.extend(hand['jogador']) del hand['croupier'][:] del hand['jogador'][:]
31323f96134549f8c54de472a9670d4e592e55da
yanbinkang/problem-bank
/epi/arrays/even_odd.py
466
4.1875
4
def even_odd(A): """ Your input is an array of integers, and you have to reorder its entries so that even entries appear first """ next_even, next_odd = 0, len(A) - 1 while next_even < next_odd: if A[next_even] % 2 == 0: next_even += 1 else: A[next_even], A[next_odd] = A[next_odd], A[next_even] next_odd -= 1 if __name__ == '__main__': print(even_odd([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]))
ee6a52d8877a8ea0848657e5a0e9ad7c13c2be52
alicelieutier/AoC2020
/day1/day1.py
759
3.671875
4
import sys def get_lines_as_number(filename): f = open(filename) return [int(line.strip()) for line in f.readlines()] def find_pair(numbers, target): seen = set() for number in numbers: missing_pair = target - number if missing_pair in seen: return(number, missing_pair) seen.add(number) def find_triplet(numbers, target): seen = set() for a in numbers: for b in numbers: missing_c = target - (a + b) if missing_c in seen: return a, b, missing_c seen.add(b) file = './day1/input' numbers = get_lines_as_number(file) # part 1 a, b = find_pair(numbers, 2020) print(a * b) # part 2 a, b, c = find_triplet(numbers, 2020) print(a * b * c)
a5a36e6d3732b14be51a11a92493c4bb4951e0d3
ehdrn3020/Python_Ref
/sum_multiples.py
220
3.828125
4
n=int(input("input the number ")) k=0 Sum=0 if n<1 and n>100: print("input only 1 to 100 number") elif n>=1 and n<=100: while k<100: k=k+n Sum=Sum+k print(k) print(Sum) else: print("wrong number")
1762ee81fb7446d066ba07da7e6dee163ee496b9
AnhellO/DAS_Sistemas
/Ene-Jun-2022/jesus-raul-alvarado-torres/práctica-2/capítulo-9/Three_Restaurants.py
826
4.5
4
"""9-2. Three Restaurants: Start with your class from Exercise 9-1 . Create three different instances from the class, and call describe_restaurant() for each instance .""" class Restaurant(): def __init__(self, name, cuisine_type): self.name = name.title() self.cuisine_type = cuisine_type def describe_restaurant(self): msg = f"{self.name} tiene los mejores {self.cuisine_type} del condado." print(f"\n{msg}") def open_restaurant(self): msg = f"{self.name} ya abrio sus puertas al publico!" print(f"\n{msg}") KFC = Restaurant('KFC', 'nuggets de pollo') KFC.describe_restaurant() Tobi = Restaurant("Burritos Tobi", 'burritos') Tobi.describe_restaurant() Applebees = Restaurant('Applebees', 'boneless') Applebees.describe_restaurant()
1674c5eb6caa015a1262d727a2be31663c2785be
Bondarev2020/infa_2019_Bondarev2020
/kontr3-4.py
615
3.640625
4
money = int(input()) A = input().split(' ') coins = [0] * len(A) for i in range(len(A)): coins[i] = int(A[i]) def make_exchange(money, coins): for i in range(1, len(A[1]), 2): C.append(int(A[1][i])) ways_of_doing_n_cents = [0] * (money + 1) ways_of_doing_n_cents[0] = 1 for coin in coins: for higher_amount in range(coin, money + 1): higher_amount_remainder = higher_amount - coin ways_of_doing_n_cents[higher_amount] += ways_of_doing_n_cents[higher_amount_remainder] print (ways_of_doing_n_cents[money]) make_exchange(money, coins)
8ee6e4e4ed30ce7e0d5bbdf050c646e33bed09d1
YiyingW/Leetcode
/20-Valid-Parentheses/solution.py
677
3.71875
4
class Solution(object): def isValid(self, s): """ :type s: str :rtype: bool """ match = {"(":")", "[":"]","{":"}"} stack = [] for sambol in s: if sambol == '(' or sambol == '[' or sambol == '{': stack.append(sambol) else: if len(stack)==0: return False toppest = stack.pop() if toppest not in match.keys(): return False if match[toppest] != sambol: return False if len(stack) != 0: return False return True
7e394af4c075b84798292a95a6834a652345b1ae
tuhiniris/Python-ShortCodes-Applications
/patterns1/alphabet pattern_5.py
294
4.0625
4
""" Example Enter the number of rows: 5 E E E E E D D D D C C C B B A """ print('Alphabet Pattern: ') number_rows=int(input('Enter number of rows: ')) for row in range(1,number_rows+1): for column in range(1,number_rows+2-row): print(chr(65+(number_rows-row)),end=' ') print()
ed8b212293c95e135579f659c6fee3333bf10949
henrikforb/TDT4113-ProgrammingProject
/Keypad/Keypad.py
2,209
3.5
4
""" Docstring """ import time import RPi.GPIO as GPIO class Keypad: """ Docstring """ def __init__(self): """ Docstring """ self.keypad = [['1', '2', '3'], ['4', '5', '6'], ['7', '8', '9'], ['*', '0', '#']] self.rows = [19, 13, 6, 5] # list of pin numbers for row self.cols = [27, 17, 4] # list of pin numbers of col self.setup() def setup(self): """ Docstring """ # Set the proper mode via: GPIO.setmode(GPIO.BCM). Also, use GPIO functions to # set the row pins as outputs and the column pins as inputs. GPIO.setmode(GPIO.BCM) for row in self.rows: GPIO.setup(row, GPIO.OUT) for col in self.cols: GPIO.setup(col, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) # - Use nested loops (discussed above) to determine the key currently being pressed def do_polling(self): """ Docstring """ self.reset_all_pins() for i in range(len(self.rows)): GPIO.output(self.rows[i], GPIO.HIGH) for j in range(len(self.cols)): if GPIO.input(self.cols[j]) == GPIO.HIGH: # debouncing time.sleep(0.01) if GPIO.input(self.cols[j]) == GPIO.HIGH: # debouncing while GPIO.input(self.cols[j]) == GPIO.HIGH: pass return str(self.keypad[i][j]) GPIO.output(self.rows[i], GPIO.LOW) return None # This is the main interface between the agent and the Keypad. It should def get_next_signal(self): """ Docstring """ # initiate repeated calls to do polling until a key press is detected. signal = self.do_polling() while signal is None: signal = self.do_polling() return signal def reset_all_pins(self): """ Docstring """ for row in self.rows: GPIO.output(row, GPIO.LOW) if __name__ == "__main__": KEYPAD = Keypad() print(KEYPAD.get_next_signal())
62755a204003a11a153c0c35d263ceeaa11c3ee5
Omar-Castillo/Advanced-Data-Storage-and-Retrieval-HW
/Instructions/oc_climateapp.py
4,910
3.59375
4
### #Flask Routes for Surf's Up Homework ### import numpy as np import sqlalchemy from sqlalchemy.ext.automap import automap_base from sqlalchemy.orm import Session from sqlalchemy import create_engine, func, inspect # import pandas and datetime import pandas as pd import datetime as dt #import flask from flask import Flask, jsonify #create engine for database engine = create_engine("sqlite:///Resources/hawaii.sqlite", connect_args={'check_same_thread': False}) #reflect an existing database into a new model Base = automap_base() #reflect the tables Base.prepare(engine, reflect=True) #Save references to each table Measurement = Base.classes.measurement Station = Base.classes.station #Create our session(link) from Python to the DB session = Session(engine) #Create an app, being sure to pass __name__ app = Flask(__name__) #Define API Home Page @app.route("/") def home(): return( """Welcome to the Home page for Omar Castillo's Surf's Up API!<br/> The routes that are API routes that will be available are the following:<br/> /api/precipitation<br/> /api/stations<br/> /api/temperature<br/> /api/'start' and /api/'start'/'end'""" ) @app.route("/api/precipitation") def precipitation(): '''Return a list of precipitation data including date, precipitation''' # Design a query to retrieve the last 12 months of precipitation data and plot the results. Using in dates from 8/23/2016 #filter out none values #sorted by measurement date year_ago_date = dt.datetime(2016, 8, 22) results = session.query(Measurement.date,Measurement.prcp)\ .filter(Measurement.date > year_ago_date,Measurement.prcp != "None").order_by(Measurement.date).all() #Create a dictionary from raw precipitation data precipitation_data = [] for date, prcp in results: precipitation_dict = {} precipitation_dict["date"] = date precipitation_dict["prcp"] = prcp precipitation_data.append(precipitation_dict) return jsonify(precipitation_data) @app.route("/api/stations") def stations(): '''Return a list of stations in our data''' #Use Pandas `read_sql_query` to load a query statement directly into the DataFrame stmt = session.query(Measurement).statement measurement_df = pd.read_sql_query(stmt, session.bind) list_stations = measurement_df['station'].unique() #Need to convert the tuple to a list in order to run jsonify call properly final_stations = list(np.ravel(list_stations)) return jsonify(final_stations) @app.route("/api/temperature") def temperature(): '''Query for the dates and temperature observations from a year from the last data point''' #use date from pandas notebook. A year from last point would be 8-23-16, so we use anything after 8-22-16 as our reference point year_ago_date = dt.datetime(2016, 8, 22) temp_results = session.query(Measurement.date, Measurement.tobs).filter(Measurement.date > year_ago_date).order_by(Measurement.date).all() # #create an empty list to be filled with info from for loop last_year_temp = [] for date, temp in temp_results: temp_dict = {} temp_dict["date"] = date temp_dict["temp"] = temp last_year_temp.append(temp_dict) return jsonify(last_year_temp) @app.route("/api/<start>") # This function called `calc_temps` will accept start date in the format '%Y-%m-%d' # and return the minimum, average, and maximum temperatures for that range of dates def start_temps(start): """TMIN, TAVG, and TMAX for a list of dates. Args: start (string): A date string in the format %Y-%m-%d, example 2016-01-31 end_date (string): A date string in the format %Y-%m-%d Returns: TMIN, TAVE, and TMAX """ summary_data = session.query(func.min(Measurement.tobs), func.avg(Measurement.tobs), func.max(Measurement.tobs))\ .filter(Measurement.date >= start).all() final_data = list(np.ravel(summary_data)) return jsonify(final_data) @app.route("/api/<start>/<end>") # This function called `calc_temps` will accept start date and end date in the format '%Y-%m-%d' # and return the minimum, average, and maximum temperatures for that range of dates def between_temps(start,end): """TMIN, TAVG, and TMAX for a list of dates. Args: start (string): A date string in the format %Y-%m-%d, 2016-01-31 end (string): A date string in the format %Y-%m-%d Returns: TMIN, TAVE, and TMAX """ between_data = session.query(func.min(Measurement.tobs), func.avg(Measurement.tobs), func.max(Measurement.tobs))\ .filter(Measurement.date >= start).filter(Measurement.date<=end).all() between_final = list(np.ravel(between_data)) return jsonify(between_final) if __name__ == "__main__": app.run(debug=True)
2e97f7502cd586551e4ec18b93a56689dad7b245
jabbalaci/AdventOfCode2019
/day04/python/part2.py
1,299
3.59375
4
#!/usr/bin/env python3 from typing import Dict, List def explode(n: int) -> List[int]: digits = [] while n > 0: digits.append(n % 10) n = n // 10 # return digits[::-1] def is_password(digits: List[int]) -> bool: ascending = True for i in range(len(digits)-1): a = digits[i] b = digits[i+1] if a > b: ascending = False # if not ascending: return False # d: Dict[int, int] = {} for digit in digits: d[digit] = d.get(digit, 0) + 1 has_double = 2 in d.values() # if not has_double: return False # return True def process(lo: int, hi: int) -> int: cnt = 0 for n in range(lo, hi+1): digits = explode(n) if is_password(digits): cnt += 1 # # return cnt def main() -> None: # line = "112233-112233" # test 1 # line = "123444-123444" # test 2 # line = "111122-111122" # test 3 line = "136760-595730" # input parts = line.split("-") lo = int(parts[0]) hi = int(parts[1]) # print(lo) # print(hi) result = process(lo, hi) print(result) ############################################################################## if __name__ == "__main__": main()
047293fa58bd1d960637d62d67627a77598a97d4
Sheenazz/pythonlessons
/return-largest-numbers-in-arrays/lessons.py
490
4.15625
4
numbers = [[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]] arrayOfLargestNumber = [] def findingLargestNumberInArrays(arrayOfArraysOfNumbers): for arrayOfNumbers in arrayOfArraysOfNumbers: max = arrayOfNumbers[0] for number in arrayOfNumbers: if number > max: max = number arrayOfLargestNumber.append(max) findingLargestNumberInArrays(numbers) print("Largest found:") for number in arrayOfLargestNumber: print(number)
f6699e6f81a69b99d027dedf402950955da4d9f4
pjt3591oo/exchange-crawler
/test.py
642
3.515625
4
''' https://datascienceschool.net/view-notebook/c645d51f308b4047aa78e8b343a2e181/ ''' from statsmodels.tsa.statespace.kalman_filter import KalmanFilter import numpy as np import matplotlib.pyplot as plt model1 = KalmanFilter(k_endog=1, k_states=1, transition=[[1]], selection=[[1]], state_cov=[[10]], design=[[1]], obs_cov=[[100]]) np.random.seed(0) y1, x1 = model1.simulate(100) print(x1) print(y1) plt.plot(y1, 'r:', label="관측값") plt.plot(x1, 'g-', label="상태값") plt.legend() plt.title("로컬레벨 모형의 시뮬레이션 ($\sigma_w^2 = 10$, $\sigma_v^2 = 100$)") plt.show()
6af3a6abbd058e36731b8ba1fcae987af1cf1bb7
ShahradX/Term4
/Insert to mysql TKINTER.py
2,017
3.625
4
import tkinter from tkinter import * import mysql.connector as sql def connection(): cnx = sql.connect( user = 'root', password = 'shahrad.f.99', host = 'localhost', database = 'legends' ) cursor = cnx.cursor() return cnx, cursor def insert(first_name, last_name, code_meli, age=None): cnx , cursor = connection() if age is None: query = f"INSERT INTO persons(first_name, last_name ,code_meli)VALUES('{first_name}','{last_name}','{code_meli}')" else: query =f"INSERT INTO persons(first_name, last_name, code_meli, age)VALUES('{first_name}','{last_name}','{code_meli}', {age})" cursor.execute(query) cnx.commit() print('One person registered') cnx.close() #Tk root root = Tk() root.geometry("500x500") #Title root.title('Registration form') #Label label_0 =Label(root,text="Registration form", width=20,font=("Commons",20)) label_0.place(x=90,y=40) #First Name First_name_Label =Label(root,text="First Name : ", width=20,font=("Alex Brush",20)) First_name_Label.place(x=8,y=120) First_name_entry=Entry(root) First_name_entry.place(x=240,y=130) #Last Name Last_name_Label =Label(root,text="Last Name : ", width=20,font=("Alex Brush",20)) Last_name_Label.place(x=8,y=170) Last_name_entry=Entry(root) Last_name_entry.place(x=240,y=180) #Code Meli code_meli_Label =Label(root,text="Meli Code : ", width=20,font=("Alex Brush",20)) code_meli_Label.place(x=8,y=220) code_meli_entry=Entry(root) code_meli_entry.place(x=240,y=230) #Age Age_Label =Label(root,text="Age : ", width=20,font=("Alex Brush",20)) Age_Label.place(x=8,y=270) Age_entry=Entry(root) Age_entry.place(x=240,y=280) #Submit Button def submitFunction() : insert(first_name=First_name_entry.get(), last_name=Last_name_entry.get(), code_meli=code_meli_entry.get(), age=Age_entry.get()) button_submit = tkinter.Button(root, text ="Submit", font="Constantia",width=15, bg="black",fg='white', command=submitFunction) button_submit.place(x=180,y=380) root.mainloop()
811f4a91e75ab9d4cda3fa24c15f2c0b24e9f6cb
renarfreitas/Coursera
/imprime_retangulo_cheio.py
170
4.0625
4
l = int(input("digite a largura: ")) a = int(input("digite a altura: ")) while a > 0: for i in range(l): print('#', end = '') print() a -= 1
e23134c82d6c05e649d4f96af8036647d028bb21
code-tamer/Library
/Business/KARIYER/PYTHON/Python_Temelleri/strings-demo.py
1,292
3.953125
4
website = "http://www.sadikturan.com" course = "Python Kursu: Baştan Sona Python Programlama Rehberiniz (40 Saat)" # 1- "course" karakter dizisinde kaç karakter bulunmaktadır ? result = len(course) lenght = len(website) # 2- "website" içinde www karakterlerini alın. #result = website[7:10] # 3- "website" içinde com karakterlerini alın. result = website[lenght-3:lenght] # 4- "course" içinden ilk 15 ve son 15 karakterlerini alın. result = course[0:15] result = course[-15:] # 5- "course" ifadesindeki arakterleri tersten yazdırın. result = course[::-1] s = "12345" print(s[::5]) name, surname, age, job = "Bora", "Yılmaz", 32, "mühendis" # 6- Yukarıda verilen değişkenler ile ekrana aşağıdaki ifadeyi yazdırın; # "Benim adım Bora Yılmaz, Yaşım 32 ve mesleğim mühendis" result = "Benim adım" + " " + name + " " +surname + ", Yaşım" + " " + str(age) + " ve mesleğim" + " " + job result = "Benim adım {} {} , Yaşım {} ve mesleğim {}.".format(name,surname, age,job) result = f"Benim adım {name} {surname}, Yaşım {age} ve mesleğim {job}." # 7- "Hello world" ifadesindeki w yi W ile değiştirin. s = "Hello world" s = s[0:6] + "W" + s[-4:] print(s) # 8- "abc" ifadesini yanyana 3 defa yazdırın. result = "abc" * 3 print(result)
7c9a0879f6895a9c289a88e3710be09ad1c4a2bd
mxmoca/python
/rank_choice_lab.py
7,273
3.84375
4
from matplotlib import pyplot as plt from pprint import pprint # This will read in the necessary data # make sure avengers.csv is in the same directory # as this python file. # You can get the file here: https://raw.githubusercontent.com/mks22-dw/python/main/avengers.csv # avengers.csv represents the results of ranked choice voting # on who should be the leader of the Avengers. # Each line in the file represents a single ballot. # The names in each line represent the ranked choices # separated by commas. # The first name listed is the top choice, second name, second # choice, etc. text = open('avengers.csv').read().strip() print(text) #================================================== print(('=' * 10) + "Problem 0" + ('=' * 10)) # See above for a description of that data that should be # in text. # Write a function that will take a string of csv data and # return a list of lists. # Each sublist should represent a single line, with the # values separated by commas. # For example, the first two elements in this list given # the avengers data should be: # [['Captain America', 'Falcon', 'Black Widow', 'Iron Man', 'Thor'], # ['Black Widow', 'Thor', 'Falcon', 'Captain America', 'Iron Man'], def make_lists(s): data = [] return data choices = make_lists(text) # only printing out the first 5 to keep from overloading # the Thonny shell with data. pprint(choices[:5]) #================================================== print(('=' * 10) + "Problem 1" + ('=' * 10)) # In order to do ranked choice voting, we # need to count votes for candidates, focusing on # the specific rank in a given ballot. # This function should take a list of lists, like # what make_lists returns as input. # It should create and return a dictionary where the # keys are the names on the ballots, and the values # are the number of people that voted for that name # in the given rank. # Assume that rank 0 means top choice, rank 1 means second, etc def isolate_choice(data, rank): single_choice = {} return single_choice choice0 = isolate_choice(choices, 0) # This should print: # {'Black Widow': 35, # 'Captain America': 14, # 'Falcon': 25, # 'Iron Man': 9, # 'Thor': 17} pprint(choice0) # find and print the choices for the last rank choice4 = {} pprint(choice4) #================================================== print(('=' * 10) + "Problem 2" + ('=' * 10)) # We can create bar graphs to look at the voting data. # This function should take a dictionary like the one returned # in problem 1, and generate a bar graph where the x axis constains # the names of the candidates, and the y axis is their vote count. # Use the second parameter as the title for the graph def choice_bar(choice_data, title): plt.show() choice_bar(choice0, "top choices") choice_bar(choice4, "bottom choices") #================================================== print(('=' * 10) + "Problem 3" + ('=' * 10)) # In ranked choice voting, percentages are important. # We can make pie charts to visualize this. # This function should take a dictionary like the one returned # in problem 1, and generate a pie chart where each wedge # represents a specific candidate. The wedges should contain # the vote percentage. # For information on pie charts, go here: https://matplotlib.org/stable/gallery/pie_and_polar_charts/pie_features.html def choice_pie(choice_data, title): plt.show() choice_pie(choice0, "top choices") #================================================== print(('=' * 10) + "Problem 4" + ('=' * 10)) # Charts are helpful, but to automate ranked choice voting # we need to calculate the percentages ourselves. # This function should take a dictionary like the one returned # in problem 1 and modify it so the values are no longer vote counts, # but percentages of the total vote def add_pcts(choice_data): values = [] total = 0 add_pcts(choice0) # This should print: # {'Black Widow': 35.0, # 'Captain America': 14.000000000000002, # 'Falcon': 25.0, # 'Iron Man': 9.0, # 'Thor': 17.0} pprint(choice0) #================================================== print(('=' * 10) + "Problem 5" + ('=' * 10)) # When voting, we need to know who got the most votes. # This function should take a dictionary like one that # has been modified by add_pcts, and return a dictionary # with keys 'name', and 'pct', containing the name and # perect vote of the top candidate. def get_top_choice(choice_data): top = {'name':'', 'pct': 0} return top top_choice = get_top_choice(choice0) # should print: # winner: {'name': 'Black Widow', 'pct': 35.0} print("winner:", top_choice) # For ranked choice voting, it is also important to find # the candidate with the fewest votes. # This function should take a dictionary like one that # has been modified by add_pcts, and return a dictionary # with keys 'name', and 'pct', containing the name and # perect vote of the bottom candidate. def get_bottom_choice(choice_data): bottom = {'name':'', 'pct': 100} return bottom bottom_choice = get_bottom_choice(choice0) # should print: # last place: {'name': 'Iron Man', 'pct': 9.0} print('last place:', bottom_choice) #================================================== print(('=' * 10) + "Problem 6" + ('=' * 10)) # In ranked choice voting, we need to be able to # remove all votes for the last place candidate. # This function should create a new list that is # almost identical to the one generated by make_lists # (problem 0), except it will not contain any values # equal to the option parameter. # For example, if Iron Man were given as option, then # this function would create a new ballot list of # lists, without any votes for Iron Man, but leaving # everything else, and not changing the order. def remove_option(data, option): new_data = [] return new_data choices = remove_option(choices, bottom_choice['name']) # The printed list should not contain Iron Man pprint(choices[:5]) #================================================== print(('=' * 10) + "Problem 7" + ('=' * 10)) # In problem 6, we removed Iron Man, let's see # how things changes. # First, recalcualte the the top choice votes. pprint(choice0) # Now display a bar and pie graphs of the new results. # Calculate precentages for the new results pprint(choice0) #================================================== print(('=' * 10) + "Problem 8" + ('=' * 10)) # First off, lets reset the data since it has been # modified for prior tests. text = open('avengers.csv').read().strip() choices = make_lists(text) # Now, let's automate the ranked choice voting # process. # This function should: # get the choices for rank 0 # display a bar graph of them: include the number of removed candidates in the title # display a pie chart of them: include the number of removed candidates in the title # calculate the percentages # find the top choice # find the bottom choice # print out the bottom choice # remove the bottom choice # repeat all these steps until the top choice has over 50% of the vote # At the end, return the top choice winner def ranked_choice_voting(data): top_choice = {'name': '', 'pct':0} return top_choice winner = ranked_choice_voting(choices) pprint(winner)
84068b82291e6980a980258d0afec505eee065a1
lduran2/dev.array-problems.in-python
/p01A-missing-number
2,684
4.28125
4
#!/usr/bin/env python3 r''' ./p01A-missing-number This program finds the missing number in a list of integers. * by: Leomar Duran <https://github.com/lduran2> * date: 2019-06-28T19:00ZQ * for: https://dev.to/javinpaul/50-data-structure-and-algorithms-\ problems-from-coding-interviews-4lh2 ''' import random # for picking the missing number import logging # for logging import sys # for command line arguments def main( min = 1, # The minimum value in the array to generate max = 100, # The maximum value in the array to generate print = print # The printing function ): r''' Tests the find_missing function on a shuffled array from 1 to 100. ''' # generate the list of numbers NUMBERS = generate_missing_number_list(min, max) # find the missing number MISSING = find_missing(NUMBERS, min, max) # The output: print(r'The array:') print(NUMBERS) print() print(r'The missing number is ', MISSING, r'.', sep=r'') def find_missing(numbers, min, max): r''' Finds the number missing in the array of integers @numbers whose elements are in the interval [min, max]. {1} Calculates the trapezoidal number from $k to $l. {2} Subtracts each number in the array from the trapezoidal number. {3} The resulting number is the missing number ''' sum = trapezoidal_number(min, max) #{1} for x in numbers: #{2} sum -= x RESULT = sum #{3} return RESULT def trapezoidal_number(k, l): r''' Calculates the trapezoidal number with rows from $k to $l. ''' return (triangular_number(l) - triangular_number(k)) def triangular_number(k): r''' Calculates the triangular number with $k rows. ''' return ((k*(k + 1)) >> 1) def generate_missing_number_list(min, max): r''' Generates a list of shuffled numbers in the interval [min, max] with one number missing. {1} Chooses a random number in the interval [min, max[ to replace. {2} Creates an list in the interval [min, max[. {3} Replaces the random number [1] in the list with $max. {4} Shuffles the list. params: min -- the minimum value in the list max -- the maximum value in the list ''' MISSING = random.randrange(min, max) #{1} logging.debug(r'Missing number chosen: %d', MISSING) numbers = list(range(min, max)) #{2} numbers[MISSING - min] = max #{3} random.shuffle(numbers) #{4} return numbers if (r'__main__' == __name__): # if '--debug' flag was given in command line arguments, # place the logger in debug mode if (r'--debug' in sys.argv): logging.basicConfig(level=logging.DEBUG) main()
28d24a5a847d7b83235c52dda88308bca87641c9
scottrob/palindrome
/palindrome.py
1,023
4.1875
4
import re import os def is_palindrome(sentence): sentence = re.sub(r'[^A-Za-z]','',sentence).lower() if len(sentence) != 0 and sentence[0] == sentence[-1]: return is_palindrome(sentence[1:-1]) elif len(sentence) == 0: return True else: return False def its_is_palindrome(sentence): while sentence != " ": sentence = re.sub(r'[^A-Za-z]','',sentence).lower() if len(sentence) >= 1 and sentence[0] == sentence[-1]: sentence = sentence[1:-1] continue elif len(sentence) == 0: return True else: return False def main(): sentence = input("Test letters for palindrome -ness, SPACE to exit: ") if is_palindrome(sentence) and its_is_palindrome(sentence): os.system('cls' if os.name == 'nt' else 'clear') print("This is a palindrome") else: os.system('cls' if os.name == 'nt' else 'clear') print("This is NOT a palindrome") if __name__ == '__main__': main()
5e53d20e66562ffef6d7db2317a890289b9d50e3
kukuhyudhistiro/algpython
/readingItemList.py
797
3.5625
4
# -*- coding: utf-8 -*- """ Created on Mon Jun 21 15:33:34 2021 @author: x220 """ #1. Mencetak seluruh item List menggunakan Loop namakota = ['A','B','C','D','E'] #a. While print(" Menggunakan WHILE ------------------------------") i = 0; while i < len(namakota): print(namakota[i]) i = i + 1; #b. For print(" Menggunakan FOR ------------------------------") for i in range(len(namakota)): print(namakota[i]) #2. mencetak nomor indeks dari item yang terpilih pilihan = input(">> Masukkan Pilihan = ") i = 0; while i<len(namakota): #cek apakah namakota pada index yg AKTIF == pilihan if namakota[i] == pilihan: #jika COCOK, print index numbernya print(">>> Index Number dari item terpilih = " + str(i)) i+=1
c6d9de92457a3e6df52f43b679d6c088d5f33128
ProximaDas/HW07
/HW07_ex10_02.py
1,000
4.1875
4
# I want to be able to call capitalize_nested from main w/ various lists # and get returned a new nested list with all strings capitalized. # Ex. ['apple', ['bear'], 'cat'] # Verify you've tested w/ various nestings. # In your final submission: # - Do not print anything extraneous! # - Do not put anything but pass in main() # Imports import types # Global elements # elements = [] def capitalize_nested(list_): # global elements for idx in range(len(list_)): if type(list_[idx]) is types.ListType: capitalize_nested(list_[idx]) elif type(list_[idx]) is types.StringType: list_[idx] = list_[idx].upper() return list_ def main(): pass # print capitalize_nested(["apple",["bear","orange"],["name",["bob","harry"]]]) # print capitalize_nested(["apple",["bear","orange"],["name",["bob","harry",["banana","pear"]]]]) # print capitalize_nested(["apple",["bear","orange"],["name",["bob","harry",["banana","pear"],["imo","etc",["any","more"]]]]]) if __name__ == '__main__': main()
cdce163717590f63a104d181f4aa2d1ab1205225
aatul/Python-Workspace
/068_SearchFile.py
501
4.03125
4
""" Serach File in Current Folder: WAP to search '.txt' files in current folder. We can change file type/name and path according to the requirements. """ import os # Get the directory that the program is currently running in dir_path = os.path.dirname(os.path.realpath(__file__)) for root, dirs, files in os.walk(dir_path): for file in files: # Change the extension from '.txt' to the one of your choice if file.endswith('.txt'): print(root + "/" + str(file))
377cbc5f1e647ab3882c1758dcdfe276151cbfc3
lobsterkatie/CodeFights
/Arcade/AtTheCrossroads/metro_card.py
2,279
4.75
5
""" AT THE CROSSROADS / METRO CARD You just bought a public transit card that allows you to ride the Metro for a certain number of days. Here is how it works: upon first receiving the card, the system allocates you a 31-day pass, which equals the number of days in January. The second time you pay for the card, your pass is extended by 28 days, i.e. the number of days in February (note that leap years are not considered), and so on. The 13th time you extend the pass, you get 31 days again. You just ran out of days on the card, and unfortunately you've forgotten how many times your pass has been extended so far. However, you do remember the number of days you were able to ride the Metro during this most recent month. Figure out the number of days by which your pass will now be extended, and return all the options as an array sorted in increasing order. Example For lastNumberOfDays = 30, the output should be metroCard(lastNumberOfDays) = [31]. There are 30 days in April, June, September and November, so the next months to consider are May, July, October or December. All of them have exactly 31 days, which means that you will definitely get a 31-days pass the next time you extend your card. Input/Output [input] integer lastNumberOfDays A positive integer, the number of days for which the card was extended the last time. This number can be equal to 28, 30 or 31. [output] array.integer An array of positive integers, the possible number of days for which you will extend your pass. The elements of the array can only be equal to 28, 30 or 31 and must be sorted in increasing order. """ def metroCard(lastNumberOfDays): #December, being the 12th month, can also be thought of as the #0th month, so start there for modding purposes days = [31, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30] options = set() for month_num in range(12): #figure out the month num for the next month next_month_num = (month_num + 1) % 12 #if this month could have been the current one if days[month_num] == lastNumberOfDays: #then next month is an option options.add(days[next_month_num]) return sorted(list(options))
0a6ff307ce961e107ff805f4a973527e9c0615fe
NishantSinghChandra/test-python
/test-home.py
176
3.515625
4
def last2(str): count = 0 for i in xrange(len(str)-2): print str[i:i+2], str[-2:] if str[i:i+2] ==str[-2:]: count+=1 return count print last2('xaxxaxaxx')
2fc12dd6d7f7b2701b2e1decbea25887057d1485
silversurfer-gr/Python
/BlinkLED.py
1,073
3.875
4
import RPi.GPIO as GPIO import time ledPin = 5 # RPI Board pin17 dauer = 5 def setup(): print("setup ist entert") GPIO.setmode(GPIO.BOARD) GPIO.setup(ledPin, GPIO.OUT) GPIO.output(ledPin, GPIO.LOW) # Set ledPin low to off led print ('using pin%d'%ledPin) # Numbers GPIOs by physical location # Set ledPin's mode is output def loop(): print("loop is entert") while True: print("is looping LED-Pin: "+str(ledPin)) GPIO.output(ledPin, GPIO.HIGH) # led on print ('...led on') print("LED on") time.sleep(dauer) GPIO.output(ledPin, GPIO.LOW) # led off print ('led off...') print("LED off") time.sleep(dauer) def destroy(): print("destroy is entert") GPIO.output(ledPin, GPIO.LOW) # led off GPIO.cleanup() # Release resource if __name__ == '__main__': # Program start from here setup() try: loop() except KeyboardInterrupt: # When 'Ctrl+C' is pressed, the child program destroy() will be executed. destroy()
35ca57cac32bb10115cbf44f4b1827327f4456a4
Eric-programming/PythonTutorial
/PyBasics/0_list.py
1,286
4.125
4
# List items are ordered, changeable, and allow duplicate values. # Define List my_list = [1, 2, "3"] my_list = list(["i1", "i2", "i3"]) my_list = [1, 2] * 10 # Access / mutate item my_list = ["i1", "i2", "i3"] second_item = my_list[1] # access second item last_item = my_list[-1] # access last item second_last_item = my_list[-2] # access second last item my_list[0] = "item1" # Insert Items my_list.append("i4") # O(1) my_list.insert(0, "i0") # O(n) # Remove item in list my_list.remove("i0") my_list.pop() # Check item exists my_list = ["i1", "i2", "i3"] is_exists = "i1" in my_list # other operations my_list.reverse() my_list.sort() # Combine lists my_list += ["item2"] # Sublist or slice my_list = ["i1", "i2", "i3", "i4"] my_list = my_list[2:] # from index 2 to end my_list = ["i1", "i2", "i3", "i4"] my_list = my_list[1:3] # from 1 to 3 but not include index 3 my_list = my_list[:1] # from beginning to index 1 # Iterate list my_list = ["i1", "i2", "i3", "i4"] result = "" for item in my_list: result += item + "," # Shallow copy and Deep copy my_list_2 = [1, 2, 3, 4] my_list = my_list_2 is_equal = my_list is my_list_2 my_list = list(my_list_2) # or my_list_2.copy() is_equal = my_list is my_list_2 is_equal = my_list == my_list_2 print(is_equal)
62014e241e885fb3d336ca16b97cb74af7e320fd
Strd79/Class_Work
/week_01/day_04/start_code/modules/output.py
778
3.59375
4
def print_task(task): print(f'Description: { task["description"] }') print(f'Status: { "Completed" if task["completed"] else "Incomplete"}') print(f'Time Taken: {task["time_taken"]} mins') def print_list(list): for task in list: print_task(task) def mark_task_complete(task): task["completed"] = True # add a task to the list def add_to_list(list, task): list.append(task) # create a menu def print_menu(): print("Options:") print("1: Display All Tasks") print("2: Get Uncompleted Tasks") print("3: Get Completed Tasks") print("4: Mark Task as Complete") print("5: Get Tasks Which Take Longer Than a Given Time") print("6: Find Task by Description") print("7: Add a new Task to list") print("Q or q: Quit")