blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
f874b6d02c210eeaaf7e7e57c235fa119b6971c3
grodrigues3/InterviewPrep
/Leetcode/houseRobber.py
1,000
3.765625
4
""" You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security system connected and it will automatically contact the police if two adjacent houses were broken into on the same night. Given a list of non-negative integers representing the amount of money of each house, determine the maximum amount of money you can rob tonight without alerting the police. See Also: Weighted Independent Set """ __author__ = 'grodrigues' class Solution: # @param num, a list of integer # @return an integer def rob(self, num): #weighted independent set problem n = len(num) if n == 0: return 0 A = {0:0, 1: num[0] } if n == 1: return A[1] for j in range(2, n+1): A[j] = max( num[j-1]+A[j-2], A[j-1]) return A[n]
8b781cc39cc18239fa2a71e72d51549f220c536d
gatorjuice/exercism
/python/atbash-cipher/atbash_cipher.py
303
3.71875
4
import string import re alphabet = string.lowercase[0:26] def decode(): pass def encode(message): return ''.join([transform(re.match('[a-zA-Z]', char).string) for char in message if re.match('[a-zA-Z]', char)]) def transform(letter): return alphabet[25-alphabet.index(letter.lower())]
58133c2fc33b2a6aed2d23e1973997d4dc1c6c6d
loggerscode/Practicepython.org
/problem3.py
334
4
4
#Problem Nr.3 #http://www.practicepython.org print("Problem 3") a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] b = [] print(a) number = int(input("Type in a number..\nthe program will display you all numbers that are less than\nyour typed-in number in the list ")) print(a) for i in a: if i < number: b.append(i) print(b)
b8650d57780c6b83cb0f3359c0eb88009abf44f2
ruchirbhai/SortingAlgos
/GroupNumbersIK.py
1,921
4.21875
4
# Group the numbers # You are given an integer array arr of size n. Group and rearrange them (in-place) # into evens and odds in such a way that group of all even integers appears on the # left side and group of all odd integers appears on the right side. # Example # Input: [1, 2, 3, 4] # Output: [4, 2, 1, 3] # Order does not matter. Other valid solutions are: # [2, 4, 1, 3] # [2, 4, 3, 1] # [4, 2, 3, 1] import time arr = { "data1" : [5,4,1,3,2], # happy path easy to vizualize "data2" : [5,4,1999,3,2,8,7,6,10,100], #larger range of values "data3" : [5,4,1,3,2,2], # repeated values "data4" : [1,1,1,1,1,1], # every element is the same "data5" : [0,22,100,1,2,3,4,5,6,7,7,8,89,9,0,-1], #negative + zero "data6" : [5,4,3,2,1], #reverse sorted array "data7" : [1], # data with only 1 value "data8" : [], # data with NULL value "data9" : [1,1] #failed on IK for some reason } def solve(arr): length = len(arr) if length <=1: return arr left_ptr, right_ptr = 0, length - 1 curr_ptr = 0 while left_ptr <= right_ptr: if (arr[curr_ptr]%2) == 0: arr[curr_ptr],arr[left_ptr] = arr[left_ptr],arr[curr_ptr] left_ptr += 1 curr_ptr +=1 else: # value is odd arr[curr_ptr], arr[right_ptr] = arr[right_ptr],arr[curr_ptr] right_ptr -= 1 # Remeber to NOT increment the curr_ptr when swapping on the right side!! # As the right side values are not yet tested for odd/even cases # curr_ptr +=1 return arr if __name__ == "__main__": # Call the dataset to test Bubble sort for i in range(len(arr)): start_time = time.time() aux = solve(arr["data"+str(i+1)]) print(aux) print("Merge time for data" + str(i+1) + " = "+ str(time.time() - start_time))
217d0eefc32064f1a8b4fba1357a750f116d67ec
parky83/python0209
/st01.Python기초/0301수업/py07선택문/py07_05_연속if.py
928
3.875
4
# py04_02_ifelse # 하나의 점수를 입력 받고, 입력 받은 점수에 해당하는 학점을 출력하는 프로그램을 작성하시오. # 입력 받는 정수는 0~100까지이고 # 90점 이상이면 A, # 80점 이상이면 B, # 70점 이상이면 C, # 60점 이상이면 D, # 나머지는 F grade = input("점수 입력") grade = int( grade) # 정수 변환 # 비교 연산자와 논리 연산자 결합한 방법 if 90<= grade and grade <=100 : print("A") elif 80<= grade and grade <90 : print("B") elif 70<= grade and grade <80 : print("C") elif 60<= grade and grade <70 : print("D") else : #elif 0<= grade and grade <60 : print("F") # 비교 연산자만 사용한 방법 if 90<= grade : print("A") elif 80<= grade : print("B") elif 70<= grade : print("C") elif 60<= grade : print("D") else : print("F")
db4804d4e866c9e7a668afbb06144155eeb04b27
bryangj23/juego_carros
/mijuego.py
2,307
3.640625
4
""" ● Configurar Juego: Crear juego con jugadores, el juego debe tener los limites de kilómetros por cada pista (un jugador puede ser un conductor y un conductor debe tener un carro asociado y un carro debe estar asociado a un carril que a su vez debe estar en una pista) """ from jugadores import Jugador from carros import Carro from random import randint import csv pistas={1:{'kilometros':1,'cariles':3},2:{'kilometros':3,'cariles':3},3:{'kilometros':30,'cariles':3}} juego=[] opcion=0 pista=[] jugadores=[] i=1 print("*********************************** Carros ************************************\n") print("Nuevo juego...") print('\n*Para iniciar el juego elija la pista (numero) en la que desea jugar:') print('Para iniciar el juego, elija la pista (numero) en la que desea jugar:\nPistas:') # Mostrando pistas for g in pistas: print(f" {g}: Kilometros: {pistas.get(g)['kilometros']}, numeros de cariles: {pistas.get(g)['cariles']} ") opcion=int(input('Ingrese el (numero) de la pista: ')) pista=[pistas[opcion]['kilometros'],pistas[opcion]['cariles']] print("\n*************** Para iniciar el juego debe crear los 3 jugadores *************") while i <= pista[1]: nombre=input(f"\nIngrese el nombre del jugador{i}:") jugadores.append(Jugador(nombre)) i+=1 for c in range(pista[1]): juego.append(Carro(jugadores[c])) termino=-True while termino: print('\n**** AVANCE *****') for i in juego: i.set_pos(i.get_pos()+randint(1,6)*100) print(i.getKm()) if (i.getKm()) >= pista[0]: termino=False break #Ordenando segun llegada podio= sorted(juego, key=lambda objeto: objeto.posicion, reverse=True) #Mostrando ganadores print(f"\nEn el primer lugar: {podio[0].jugador.getNombre()}, {podio[0].get_pos()}m, {podio[0].getKm()}km") print(f"En el segundo lugar: {podio[1].jugador.getNombre()}, {podio[1].get_pos()}m, {podio[1].getKm()}km") print(f"En el tercer lugar: {podio[2].jugador.getNombre()}, {podio[2].get_pos()}m, {podio[2].getKm()}km") guardar=(f"\nEn la pista {opcion}; 1; {podio[0].jugador.getNombre()}; {podio[0].get_pos()}m; 2; {podio[1].jugador.getNombre()}, {podio[1].get_pos()}m; 3; {podio[2].jugador.getNombre()}; {podio[2].get_pos()}m") with open('juega.csv','a') as fd: fd.write(guardar)
a957a4e8899784432fe2798f494c163fb1862ddb
xueshen3/inf1340_2015_asst3
/exercise1.py
3,000
4.21875
4
#!/usr/bin/env python3 """ Assignment 3, Exercise 2, INF1340, Fall, 2015. DBMS This module performs table operations on database tables implemented as lists of lists. """ __author__ = 'Bertha Chan & Philips Xue' def filter_employees(row): """ Check if employee represented by row is AT LEAST 30 years old and makes MORE THAN 3500. :param row: A List in the format: [{Surname}, {FirstName}, {Age}, {Salary}] :return: True if the row satisfies the condition. """ return row[-2] >= 30 and row[-1] > 3500 ##################### # HELPER FUNCTIONS ## ##################### def remove_duplicates(l): """ Removes duplicates from l, where l is a List of Lists. :param l: a List """ d = {} result = [] for row in l: if tuple(row) not in d: result.append(row) d[tuple(row)] = True return result class UnknownAttributeException(Exception): """ Raised when attempting set operations on a table that does not contain the named attribute """ pass def selection(t, f): # New list created as a result result = [] # Enter the for loop to append the element in the table for t_list in t: # If rows are in the t_list after being run through the function, append to result if f(t_list): result.append(t_list) # If the result is none or the header only, return None if len(result) == 1 or len(result) == 0: return None # Otherwise, return the result after removing any duplicates else: return remove_duplicates(result) def projection(t, r): # Check if t or r are empty list if not t or not r: return None result = [] matching_attributes_index = [] # Enter the for loop to test if the attribute is in table 1 for attribute in r: if attribute not in t[0]: raise UnknownAttributeException("Not in table1 attribute list") # Enter the for loop to append the attribute for attribute in t[0]: if attribute in r : matching_attributes_index.append(t[0].index(attribute)) # Enter the for loop to append the attribute into the new row for row in t: filtered_row = [] for index_to_append in matching_attributes_index: filtered_row.append(row[index_to_append]) result.append(filtered_row) return result def cross_product(t1, t2): # Create a empty result to store combined table result = [] t1_counter = 0 result.append(t1[0]+t2[0]) # Enter the for loop to combine two table into and store them in result for t1_row in t1: t2_counter = 0 # Enter the for loop to append the new element for t2_row in t2: if t2_counter > 0: if t1_counter > 0: result.append(t1_row + t2_row) t2_counter += 1 t1_counter += 1 if len(result) == 1: return None else: return result
0b3d008838795bd4740b93211c9b469b44e983bc
samilarinc/CSLabs
/CS115 Lab03/lab-03-2.py
548
4.46875
4
def square_digits(number): """ This function takes positive integers as input and returns an integer in which every digit of the input is squared int he same order. """ numStr = str(number) newStr = '' for i in numStr: j = int(i) j **= 2 newStr += str(j) return int(newStr) num = int(input("Enter an int : ")) while num != -1: num = square_digits(num) print("number with squared digits is " + str(num)) num = int(input("Enter an int : ")) print("bye")
ba74d89a1ef1c4c129352305d9d9fd77060d610f
prasadkhajone99/prime
/for_even_no.py
68
3.765625
4
for x in range(0,20) : if (x%2)==0 : print(x,end=' ') print(' ')
86b4c7fe9ddc3fde85656997591d7dacf7ece8e0
weichuntsai0217/work-note
/programming-interviews/epi-in-python/ch04/05_7_COMPUTE_X_TO_THE_POWER_OF_Y.py
861
3.8125
4
from __future__ import print_function def power(x, y): """ Time complexity is O(n) where n is the integer width (ex: 64-bit) """ if y == 0: return 1 if y < 0: y = -y x = 1.0 / x res = 1. mask = 1 cache = x while mask <= y: if (mask & y) != 0: res *= cache cache *= cache mask <<= 1 return res def get_input(big=False, negative=False): if big: if negative: return 5, -12, 1. / 244140625, 1e-9 return 5, 12, 244140625, 0 else: if negative: return 3, -5, 1. / 243, 1e-6 return 3, 5, 243, 0 def main(): for arg1, arg2 in [(False, False), (False, True), (True, False), (True, True)]: x, y, ans, delta = get_input(arg1, arg2) res = power(x, y) print(res) print('Test success' if abs(res - ans) <= delta else 'Test failure') if __name__ == '__main__': main()
afd653a99e0bfca5b68e393a91b099f9fa31bf3e
sajnanshetty/NLP
/task3/advance_python.py
4,916
4.03125
4
import functools import operator import string import random import math from functools import partial import urllib.request as urllib2 def check_fibonacci(num: int): """ case1: Write a function using only list filter lambda that can tell whether a number is a Fibonacci number or not. You can use a pre-calculated list/dict to store fab numbers till """ is_perfect_square = lambda x: True if math.pow(int(math.sqrt(x)), 2) == x else False is_fib = lambda x: True if is_perfect_square(5 * x * x + 4) or is_perfect_square(5 * x * x - 4) else False return is_fib(num) def add_iterables(l1: list, l2: list): """ case 2.1: Using list comprehension (and zip/lambda/etc if required) write an expression that: add 2 iterables a and b such that a is even and b is odd """ return sum([a + b for a, b in zip(l1, l2) if a % 2 == 0 and b % 2 != 0]) def skip_vowels(word: str): """ case 2.2: Using list comprehension (and zip/lambda/etc if required) write an expression that: strips every vowel from a string provided (tsai>>t s)""" format_word = [ch for ch in word if ch.lower() not in ['a', 'e', 'i', 'o' 'u']] return ' '.join(format_word) def customize_relu(l: list): """ case 2.3: Using list comprehension (and zip/lambda/etc if required) write an expression that: acts like a ReLU function for a 1D array""" return [item for item in l if bool(item) and item > 0] def customize_sigmoid(l: list): """ case 2.4: Using list comprehension (and zip/lambda/etc if required) write an expression that: acts like a sigmoid function for a 1D array""" return [1 / (1 + math.exp(-i)) for i in l] def ascii_to_char(x: str): """ handles small alpha chracter shifting by 5 """ if x + 5 > 122: return chr(96 + ((x + 5) - 122)) else: return chr(x + 5) def shift_char(s: str): """ case 2.5: Using list comprehension (and zip/lambda/etc if required) write an expression that: acts like a sigmoid function for a 1D array takes a small character string and shifts all characters by 5 (handle boundary conditions) tsai>>yxfn""" return ''.join(list(map(ascii_to_char, [ord(ch) for ch in s]))) def find_swear_words(paragraph: str): """ case 3: A list comprehension expression that takes a ~200 word paragraph, and checks whether it has any of the swear words mentioned in https://github.com/RobertJGabriel/Google-profanity-words/blob/master/list.txt """ swear_word_url = "https://raw.githubusercontent.com/RobertJGabriel/Google-profanity-words/master/list.txt" swear_word_container = list( map(lambda word: word.decode('utf-8').rstrip('\n'), urllib2.urlopen(swear_word_url).readlines())) return [word for word in paragraph.split() if word in swear_word_container] def add_even_numbers(l: list): """ case 4.1: using reduce function: add only even numbers in a list """ return functools.reduce(operator.add, filter(lambda x: x % 2 == 0, l)) def find_biggest_character(s: str): """ case 4.2: using reduce function: find the biggest character in a string (printable ascii characters) """ return functools.reduce(lambda a, b: a if ord(a) > ord(b) else b, s) def add_3rd_element(l: list): """ case 4.3: using reduce function: adds every 3rd number in a list """ return functools.reduce(operator.add, l[::3]) def generate_vehicle_num(state: str = "KA"): """ case 5: Using randint, random.choice and list comprehensions, write an expression that generates 15 random KADDAADDDD number plates, : where KA is fixed, : D stands for a digit, : A stands for Capital alphabets. 10<<DD<<99 : & 1000<<DDDD<<9999 """ return [ f"{state}{random.randint(10, 100)}{''.join(random.choices(string.ascii_uppercase, k=2))}{random.randint(1000, 10000)}" for i in range(15)] def generate_vehicle_num_using_partial(): """ case 6: Write the above again from scratch where KA can be changed to DL, and 1000/9999 ranges can be provided. Now use a partial function such that 1000/9999 are hardcoded, but KA can be provided """ partial_fuc = partial(generate_vehicle_num, "DL") return partial_fuc() if __name__ == "__main__": # print(add_even_numbers([1, 2, 3, 4, 10])) # print(add_3rd_element([0, 1, 2, 3, 4, 10])) # print(find_biggest_character("sajna")) # print(add_iterables([1, 2, 3, 4], [3, 1, 5, 7])) # print(skip_vowels('sajna')) # print(customize_relu([1, 2, -1, 0, None])) # print(shift_char("sajna")) # print(generate_vehicle_num()) # print(customize_sigmoid([5,6,1,0,3, -5])) # print(generate_vehicle_num_using_partial()) # print(check_fibonacci(13)) # print(find_swear_words("ballsack bi+ch sajna")) pass
fc598236eeb80287189936f8d30e8a8b20ef0749
zhangtyps/Python
/queue_study.py
1,607
3.5625
4
#!/usr/bin/env python # -*- encoding: utf-8 -*- ''' @File : queue_study.py @Time : 2019/03/08 15:16:08 @Author : zhangtyps @GitHub : https://github.com/zhangtyps @Version : 1.0 @Desc : 如何理解threading和queue的配合使用 ''' # here put the import lib import threading, queue, random, time class MyThread(threading.Thread): def __init__(self, i, queue): #类初始化时,带入需要的参数和刚才创建的队列 threading.Thread.__init__(self) self.queue = queue self.i = i def run(self): #当类的实例调用start()时运行的代码 time.sleep(random.randint(1, 3)) print('thread %s is over' % self.i) #当运行完,调用get()从对列表里找到该任务,task_down通知该线程任务已完成 self.queue.get() self.queue.task_done() def main(): #创建一个队列,长度最大为3 q = queue.Queue(3) #往队列里丢15个任务,虽然超过了队列长度,但是任务执行还是一次只能执行3个 for i in range(15): #把任务添加到队列中,如果添加超过队列长度,将会等待 #这里put添加的值其实没有任何意义,只是一个在队列里的占位符而已,全部put(1)也不会有任何报错 q.put(i) #实例化类,并运行 t = MyThread(i, q) t.start() #这里的q.join()实际上在等待最后队列中的任务,因为put本身就会因为队列长度不够而等待,最好加上这个函数 q.join() print('over') if __name__ == '__main__': main()
94a50c0865f4fd3da92100257d3bc84eab2f79a7
DURODOLA-ABDULKABIR/Practice
/practice2.py
3,537
3.8125
4
# while True: # line = input('> ') # if line[0] == '#' : # continue # if line == 'done' : # break # print(line) # print('Done!') # largest_so_far = -1 # print('Before', largest_so_far) # for the_num in [9, 41, 12, 3, 74, 15] : # if the_num > largest_so_far : # largest_so_far = the_num # print(largest_so_far, the_num) # print('After', largest_so_far) # count = 0 # sum = 0 # print('Before', count, sum) # for value in [9, 41, 12, 3, 74, 15] : # count = count + 1 # sum = sum + value # print(count, sum, value) # print('After', count, sum, sum / count) # count = 0 # sum = 0 # print('Before', count, sum) # for value in [9, 41, 12, 3, 74, 15] : # count = count + 1 # sum = sum + value # print(count, sum, value) # average = sum/count # print('After', count, sum, average) # def thing(): # print('Hello') # print('Fun') # thing() # x = 5 # print('Hello') # x = 5 # def print_lyrics(): # print("I'm a lumberjack, and I'm okay.") # print('I sleep all night and I work all day.') # print('Yo') # x = x + 2 # print(x) # print_lyrics() # def addtwo(a, b): # added = a + b # return added # x = addtwo(3, 5) # print(x) # x = int(input ('enter a number; ')) # y = int(input ('enter a number; ')) # z = int(input ('enter a number; ')) # number = 0 # for largest_number in ( x, y, z): # if (largest_number > number): # number = largest_number # print (largest_number) # smallest_number = None # for value in [9, 12, 41, 3, 31, 90]: # if smallest_number is None: # smallsest_number = value # elif value < smallest_number: # smallest_number = value # print (smallest_number, value) # smallest = None # print('Before') # for value in [9, 41, 12, 3, 74, 15] : # if smallest is None : # smallest = value # elif value < smallest : # smallest = value # print(smallest, value) # print('After', smallest) # x = int (input('enter a number here> ')) # y = int (input ('enter a numter here> ')) # z = int (input ('enter a number here> ')) # largest = None # for num in [x, y, z]: # if largest is None: # largest = num # elif num > largest: # largest = num # print ('largest number is', largest) # def lyrics (): # print('I am in love with you ' + # 'from the first day that I met you') # print ('you are the best thing that has ever happened to me') # lyrics() # ARITHMETIC PROGRESSION # a = input ('enter the first term; ') # try: # a = int(a) # except: # print ('pls enter an integer value ') # exit () # d = input ('enter the common diff; ') # try: # d = int(d) # except: # print ('pls enter an integer value ') # exit() # n = input ('enter number of terms; ') # try: # n = int(n) # except: # print ('pls enter an integer value ') # exit() # x = -1 # y = 0 # z = 1 # while (n > 0): # term = a + ((x+z) * d) # y = y + 1 # z = z + 1 # print (term) # if (y == n) : # break # print ('done!') # SUM OF GP a = input ('enter the 1st term; ') try: a = int(a) except: print ('please enter an integer value; ') exit() b = input ('enter the 2nd term; ') try: b = int (b) except: print ('please enter an integer value') exit() n = input ('enter number of terms; ') try: n = int(n) except: print ('please enter an integer value') exit() r = a/b if r > 1: s = a(r**n-1)/(r-1) else: s = a(1-r**n)/(1-r) print (s)
5b4680430c5c2dd7a1148d9e4e3af50710104597
rafasando/bc_clases
/Persona.py
980
3.78125
4
# En el archivo Persona.py crear una clase Persona con atributo nombre. # Despues, instanciar un objeto de tipo Persona # Agregarle un atributo edad y un metodo cumple_anhos # y un metodo get_edad. # Inicializar un objeto de tipo Persona y hacerle cumplir anhos class Persona: nombre = None edad = None def __init__(self, arg_nombre, arg_edad): self.set_Nombre(arg_nombre) self.set_Edad(arg_edad) def get_Nombre(self): return self.nombre def set_Nombre(self, arg_nombre): self.nombre = arg_nombre def get_Edad(self): return self.edad def set_Edad(self, arg_edad): self.edad = arg_edad def cumple_anhos(self): self.set_Edad(self.get_Edad() + 1) from time import sleep p = Persona("Ror", 10) print("Te llamas", p.nombre, "y tenes", p.edad, "anhos") for i in range(5): print("Ahora quiero que cumplas un anho mas!!!") p.cumple_anhos() print("Edad:", p.edad) sleep(2)
bfd3af903ae8511991868d7803cd9ab80bafc6d6
bmay2/cs
/stack/hanoi.py
266
3.546875
4
A = [6,5,4,3,2,1] B = [] C = [] def move(n, current, target, aux): if n == 1: target.append(current.pop()) return move(n-1, current, aux, target) move(1, current, target, aux) move(n-1, aux, target, current) move(len(A), A, C, B) print(A) print(B) print(C)
182f528909c0ae7542312859ba105ff2173bd84e
CHIH-YI-LU/ycsh_python_course
/test/prime_list.py
510
3.921875
4
n = int(input()) m = int(input()) def is_prime(n): if n >1 : for i in range(2, n): if n % i == 0: # 整除,i 是 n 的因數,所以 n 不是質數。 return False return True # 都沒有人能整除,所以 n 是質數。 else : return False for i in range(n, m + 1): # 產生 2 到 n 的數字。 i_is_prime = is_prime(i) # 判斷 i 是否為質數。 if i_is_prime: # 如果是,印出來。 print(i)
99e581bcdeb1d99a126e734cdd4aac826dac5350
eokeeffe/Python
/misc1.py
1,666
3.546875
4
def msplit(string, delimiters): ''' Behaves str.split but supports multiple delimiters ''' delimiters = tuple(delimiters) stack = [string,] for delimiter in delimiters: for i, substring in enumerate(stack): substack = substring.split(delimiter) stack.pop(i) for j, _substring in enumerate(substack): stack.insert(i+j, _substring) return stack def mreplace(string, delimiters,replacements): ''' Behaves str.replace but supports multiple delimiters ''' if len(delimiters) != len(replacements): return [] delimiters = tuple(delimiters) stack = [string,] for index in range(0,len(delimiters)): for i, substring in enumerate(stack): substack = substring.replace(delimiters[index],replacements[index]) stack.pop(i) for j, _substring in enumerate(substack): stack.insert(i+j, _substring) return stack def getGreatestdifference(list): ''' Return the first and last index that have the greatest difference between terms ''' print "Hello World" f = 0 l = 0 max = 0 for index in list: for index2 in list: if index2-index > max: max = index2-index l = index2 f = index return f,l,max #list = [10,20,40,50,500] #a,b,c = getGreatestdifference(list) #print a,b,c u = ['"',',','.','-','_','[',']','(',')','+','=','<','>'] v = [' " ',' , ',' . ',' - ',' _ ',' [ ',' ] ',' ( ',' ) ',' + ',' = ',' < ',' > '] html = open("test1.htm","r").read() file = open('t.txt','w') #list = msplit(html,['"',',','.','-','_','[',']','(',')','+','=','<','>']) for index in range(0,len(u)): html = html.replace(u[index],v[index]) list = [] for tok in html: list.append(tok) for l in list: file.write(l) file.close()
b19f6653bb2412ec7691fce3057f224e0a2276bd
tabletenniser/leetcode
/5741_max_building_height.py
2,229
3.984375
4
''' You want to build n new buildings in a city. The new buildings will be built in a line and are labeled from 1 to n. However, there are city restrictions on the heights of the new buildings: The height of each building must be a non-negative integer. The height of the first building must be 0. The height difference between any two adjacent buildings cannot exceed 1. Additionally, there are city restrictions on the maximum height of specific buildings. These restrictions are given as a 2D integer array restrictions where restrictions[i] = [idi, maxHeighti] indicates that building idi must have a height less than or equal to maxHeighti. It is guaranteed that each building will appear at most once in restrictions, and building 1 will not be in restrictions. Return the maximum possible height of the tallest building. Example 1: Input: n = 5, restrictions = [[2,1],[4,1]] Output: 2 Explanation: The green area in the image indicates the maximum allowed height for each building. We can build the buildings with heights [0,1,2,1,2], and the tallest building has a height of 2. Example 2: Input: n = 6, restrictions = [] Output: 5 Explanation: The green area in the image indicates the maximum allowed height for each building. We can build the buildings with heights [0,1,2,3,4,5], and the tallest building has a height of 5. Example 3: Input: n = 10, restrictions = [[5,3],[2,5],[7,4],[10,3]] Output: 5 Explanation: The green area in the image indicates the maximum allowed height for each building. We can build the buildings with heights [0,1,2,3,3,4,4,5,4,3], and the tallest building has a height of 5. Constraints: 2 <= n <= 109 0 <= restrictions.length <= min(n - 1, 105) 2 <= idi <= n idi is unique. 0 <= maxHeighti <= 109 ''' class Solution: def canMake(self, n, rest, target): lower = 0 upper = n - 1 for r in rest: def maxBuilding(self, n: int, rest) -> int: a, b = 0, 1000000001 while a < b: mid = (a+b) // 2 if self.canMake(n, rest, mid): a = mid + 1 else: b = mid return mid s = Solution() n = 10 restrictions = [[5,3],[2,5],[7,4],[10,3]] print(s.maxBuilding(n, restrictions))
3eee648f9bf326f979f20f36db275bc2e2d8965d
t-ah/adventofcode-2020
/day17_2.py
1,269
3.53125
4
from collections import defaultdict def read_input(): with open(__file__[:5]+".txt", "r") as f: return f.read().split("\n") def neighbours(x,y,z,w): d = (-1,0,1) for dx in d: for dy in d: for dz in d: for dw in d: yield (x+dx,y+dy,z+dz,w+dw) def count_active_neighbours(xyz, blocks): count = -1 if blocks[xyz] else 0 for other_xyz in neighbours(*xyz): if blocks[other_xyz]: count += 1 return count def cycle(blocks): new_blocks = defaultdict(bool) for xyz in list(blocks): for block in neighbours(*xyz): if block in new_blocks: continue active_neighbours = count_active_neighbours(block, blocks) if (blocks[block] and active_neighbours in (2,3)) or (not blocks[block] and active_neighbours == 3): new_blocks[block] = True return new_blocks def main(): lines = read_input() blocks = defaultdict(bool) for y in range(len(lines)): line = lines[y] for x in range(len(line)): if line[x] == "#": blocks[x,y,0,0] = True for _ in range(6): blocks = cycle(blocks) print(len(blocks)) if __name__ == "__main__": main()
2458aea50a22b076aa68909d37c3de2ff5c3ab8a
gabriellaec/desoft-analise-exercicios
/backup/user_143/ch31_2020_03_23_14_14_13_863688.py
158
3.578125
4
def eh_primo (perg): perg=Int(input('qual o numero?')) if perg=1 or perg=0: return False elif perg>1 and perg%2 ==0 or :
9a632daf841aebff633d93545f6b97919e3cc54a
guangyi/Algorithm
/uniqueBST2.py
879
3.53125
4
class Solution: # @return a list of tree node def generateTrees(self, n): temp = [] for i in range(1, n + 1): temp.append(i) return self.trees(temp) def trees(self, arr): if arr == []: return [None] if len(arr) == 1: return [TreeNode(arr[0])] result = [] for i in range(0, len(arr)): leftArr = arr[0:i] rightArr = arr[i + 1:] rootLeft = self.trees(leftArr) rootRight = self.trees(rightArr) for left in range(0, len(rootLeft)): for right in range(0, len(rootRight)): # !!!! create new root node!!!!! root = TreeNode(arr[i]) root.left = rootLeft[left] root.right = rootRight[right] result.append(root) return result
9f967003f7ddcc1ce92b8557909aa8d566775526
jpbass96/Project-Rock-Paper-Scisors
/ProjectTest2.py
1,874
4.03125
4
import time import random lives = [1,2,3,4,5] score = [] ready = False alive = True print ("Welcome to Bass RPS. This is a basic Rock, Paper, Scissors game played against a lone computer opponent.") print ("You will have 5 lives and each time you lose a round, you will lose one life. Good Luck!") print ("") time.sleep(.5) print ("Type ready when you are ready to begin.") while not ready: start = input("User Input: ") if start == ("ready"): ready = True while alive: print ("You currently have " + str(len(lives)) + " lives remaining") time.sleep(1) print ("Enter 1 for Rock") print ("Enter 2 for Scissors") print("Enter 3 for Paper") play = input("User Input: ") bot = random.randrange(1,3+1) print ("Rock...") time.sleep(.5) print ("Paper...") time.sleep(.5) print ("Scissors...") time.sleep(.5) print ("Shoot!") time.sleep(.5) print ("BOT: " + str(bot) + "PLAYER: " + str(play)) if bot / int(play) == 1: print ("Draw") print ("Score: " + str(len(score))) if bot == 1 and int(play) == 2: print ("You Win!") score.append (len(score) + 1) print ("Score: " + str(len(score))) if bot == 1 and int(play) == 3: print ("You Lose!") del lives [len(lives) - 1:] print ("Score: " + str(len(score))) if bot == 2 and int(play) == 1: print ("You Lose!") del lives [len(lives) - 1:] print ("Score: " + str(len(score))) if bot == 2 and int(play) == 3: print ("You Win!") score.append (len(score) + 1) print ("Score: " + str(len(score))) if bot == 3 and int(play) == 1: print ("You Win!") score.append (len(score) + 1) print ("Score: " + str(len(score))) if bot == 3 and int(play) == 2: print ("You Lose!") del lives [len(lives) - 1:] print ("Score: " + str(len(score))) if len(lives) == 0: print ("Game Over!") print(len(score)) alive = False print ("Thanks for playing!")
ac835b23cfe6a20d686280f7977b2874cc0c3027
Shokran/stepik_Programming_on_Python
/1/1.12.2.py
66
3.578125
4
a = int(input()) print((-15) < a <= 12 or 14 < a < 17 or 19 <= a)
34987ca6d6b799d568e9cbe25d722ebd0b43a595
coderdojoka/Materialien
/_includes/code/python/ka/tuerenspiel.py
716
3.78125
4
from random import randint anzahl_tueren = 2 weitermachen = "j" zaehler = 1 while weitermachen == "j": tuer_richtig = "Ja" while tuer_richtig == "Ja": tuer = randint(1, anzahl_tueren) eingabe = input("Raten Sie welche von " + str(anzahl_tueren) + " Türen die richtige ist.") eingabe = int(eingabe) if tuer == eingabe: print("Richtig!!!") else: print("Leider falsch!!!") tuer_richtig = "Nein" zaehler = 0 if zaehler == 3: tuer_richtig = "Nein" print("Super Sie haben es geschaft!!!") zaehler = zaehler + 1 weitermachen = input("Weitermachen?(j/n): ")
86e265a6d752b4f4134113cdd6b9ce21fe176597
mrmarten/avegapythonclass
/pythoncourse-part2/16. Functions Exercise - Integers.py
2,419
4.03125
4
''' Exercise : Does a String Represent an Integer? In this exercise you will write a function named isInteger that determines whether or not the characters in a string represent a valid integer. When determining if a string represents an integer you should ignore any leading or trailing white space. Once this white space is ignored, a string represents an integer if its length is at least one and it only contains digits, or if its first character is either + or - and the first character is followed by one or more characters, all of which are digits. Write a main program that reads a string from the user and reports whether or not it represents an integer. Ensure that the main program will not run if the file containing your solution is imported into another program. Start coding below this line''' ''' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' # Solution to Exercise : Does a String Represent an Integer? ## # Determine whether or not a string entered by the user is an integer. # # Determine if a string contains a valid representation of an integer # @param s the string to check # @return True if s represents an integer. False otherwise. # def isInteger(s): # Remove whitespace from the beginning and end of the string s = s.strip() # The isdigit method returns True if and # only if the string is at least one character in # length and all of the characters in the string # are digits. # Determine if the remaining characters form a valid integer if (s[0] == "+" or s[0] == "-") and s[1:].isdigit(): return True if s.isdigit(): return True return False # Demonstrate the isInteger function def main(): s = input("Enter a string: ") if isInteger(s): print("That string represents an integer.") else: print("That string does not represent an integer.") # Only call the main function when this file has not been imported if __name__ == "__main__": main() # The __name__ variable is automatically assigned a value by Python when the program # starts running. It contains "__main__" when the file is executed directly by Python. It # contains the name of the module when the file is imported into another program. '''
1d35f809b5821217924250ef0ab9801a98c44608
sandeepkumar8713/pythonapps
/24_fourthFolder/49_shortest_path_break_wall.py
3,571
3.90625
4
# https://leetcode.com/discuss/interview-question/353827 # Similar : https://leetcode.com/problems/shortest-path-in-a-grid-with-obstacles-elimination/ # Question : Given a 2D grid of size r * c. 0 is walkable, and 1 is a wall. You can move up, down, left or right at # a time. Now you are allowed to break at most 1 wall, what is the minimum steps to walk from the upper left corner # (0, 0) to the lower right corner (r-1, c-1)? Follow-up: # What if you can break k walls? # # Example : Input: k = 2 # [[0, 1, 0, 0, 0], # [0, 0, 0, 1, 0], # [0, 1, 1, 1, 1], # [0, 1, 1, 1, 1], # [1, 1, 1, 1, 0]] # Output: 10 # Explanation: Change (2, 4) and (3, 4) to `0`. # Route (0, 0) -> (1, 0) -> (1, 1) -> (1, 2) -> (0, 2) -> (0, 3) -> (0, 4) -> (1, 4) -> (2, 4) -> (3, 4) -> (4, 4) # # Question Type : Generic, SimilarAdded # Used : Do normal bfs, whenever we hit a wall, break it. Keep the count to walls broken and push it along with distance # in queue. Skip the nodes, where wall broken count is more than limit. If we reach target return length. # Logic: def shortestPathBreakWalls(inpMat, K): # m, n = len(inpMat), len(inpMat[0]) # offsets = [(1, 0), (-1, 0), (0, 1), (0, -1)] # pq = [(0, 0, (0, 0))] # seen = {(0, (0, 0))} # while pq: # length, wallBroke, (r, c) = heappop(pq) # for dr, dc in offsets: # nextR, nextC = r + dr, c + dc # if not (0 <= nextR < m and 0 <= nextC < n): continue # if (nextR, nextC) == (m - 1, n - 1): return length + 1 # nextWallBroke = wallBroke + inpMat[nextR][nextC] # if nextWallBroke > K or (nextWallBroke, (nextR, nextC)) in seen: # continue # seen.add((nextWallBroke, (nextR, nextC))) # heappush(pq, (length + 1, nextWallBroke, (nextR, nextC))) # return -1 # Complexity : O(n*m) from heapq import heappush, heappop def shortestPathBreakWalls(inpMat, K): m, n = len(inpMat), len(inpMat[0]) offsets = [(1, 0), (-1, 0), (0, 1), (0, -1)] # elements in form of: (path length, wall breaks, (row, column)) pq = [(0, 0, (0, 0))] # store visited states: (wall breaks, (row, column)) seen = {(0, (0, 0))} while pq: # pick the current shortest path # pick one with fewest wall breaks, if there is a tie length, wallBroke, (r, c) = heappop(pq) for dr, dc in offsets: nextR, nextC = r + dr, c + dc # skip if out of bound if not (0 <= nextR < m and 0 <= nextC < n): continue # reach target if (nextR, nextC) == (m - 1, n - 1): return length + 1 nextWallBroke = wallBroke + inpMat[nextR][nextC] # skip if exceed wall break limit or state has been visited if nextWallBroke > K or (nextWallBroke, (nextR, nextC)) in seen: continue seen.add((nextWallBroke, (nextR, nextC))) heappush(pq, (length + 1, nextWallBroke, (nextR, nextC))) return -1 if __name__ == "__main__": A = [[0, 1, 0, 0, 0], [0, 0, 0, 1, 0], [1, 1, 0, 1, 0], [1, 1, 1, 1, 0]] K = 1 print(shortestPathBreakWalls(A, K), 7) A = [[0, 1, 1], [1, 1, 0], [1, 1, 0]] K = 1 print(shortestPathBreakWalls(A, K), -1) A = [[0, 1, 0, 0, 0], [0, 0, 0, 1, 0], [0, 1, 1, 1, 1], [0, 1, 1, 1, 1], [1, 1, 1, 1, 0]] K = 2 print(shortestPathBreakWalls(A, K), 10)
79f86dbf9100317530766e48a5374cec2ef06c37
yuheunk/practice_codes
/sort_안테나.py
439
3.5
4
# 일직선상에 여러 채의 집이 위치함. # 이 중 하나에 안테나를 설치하는데 모든 집까지의 거리가 최소가 되도록 설치한다. # output: 설치할 집의 위치(여러 개면 가장 작은 값) n = int(input('number of houses')) houses = list(map(int, input('Location of houses').split())) houses.sort() if len(houses)%2==0: print(houses[len(houses)//2-1]) else: print(houses[len(houses)//2])
3ef0afc3cf92d3298704014d3a4fee03bea1b569
iamkumar0512/Escaping-the-Caves
/RSA/rsa_break.py
3,370
3.59375
4
import binascii # Constants Provided N = 84364443735725034864402554533826279174703893439763343343863260342756678609216895093779263028809246505955647572176682669445270008816481771701417554768871285020442403001649254405058303439906229201909599348669565697534331652019516409514800265887388539283381053937433496994442146419682027649079704982600857517093 C = 58851190819355714547275899558441715663746139847246075619270745338657007055698378740637742775361768899700888858087050662614318305443064448898026503556757610342938490741361643696285051867260278567896991927351964557374977619644763633229896668511752432222528159214013173319855645351619393871433455550581741643299 e = 5 from math import * def int2bytes(i): hex_string = '%x' % i n = len(hex_string) return binascii.unhexlify(hex_string.zfill(n + (n & 1))) def multiply(p1,p2): ''' Multiply two given polynomials p1 and p2 Please ensure that the given degree should be the length of the array being used 4x^2 + 2x + 1 = [4,2,1] ''' deg1 = len(p1) deg2 = len(p2) deg = deg1 + deg2 - 1 poly = [0]*deg for i in range(deg1): for j in range(deg2): poly[i+j] += p1[i]*p2[j] return poly def scale(p1,alpha): ''' Scales polynomial p(x) by p(alpha x) This will be used while scaling the coefficients ''' deg1 = len(p1) - 1 return [p1[i]*(alpha**(deg1-i)) for i in range(len(p1))] def eval_poly(p,x): deg1 = len(p) - 1 return sum([x**(deg1-i)*p[i] for i in range(len(p))]) def search_roots(p,hi = 2**80, lo = 0): max_iter=0 while max_iter < 200: mid = (lo + hi)//2 val = eval_poly(p,mid) if val == 0: return mid # Now check signs val1 = eval_poly(p,hi) val2 = eval_poly(p,lo) if val1==0: return hi elif val2==0: return lo elif eval_poly(p,hi)*val > 0: hi = mid else: lo = mid max_iter += 1 return None degree = e #Same as the exponent scale_factor = int(N**0.1) #Any large value < 0.2 should do # print(scale_factor) base = "This door has RSA encryption with exponent 5 and the password is ".encode('UTF-8') base = int(binascii.hexlify(base),16)<<72 poly = [1%N,(5*(base))%N,(10*(base**2))%N,(10*base**3)%N,(5*base**4)%N,((base**5)-C)%N] #The polynomial under investigation basis_poly = [] # Make lattice of 10 polynomials for i in range(2): for j in range(5): p1 = [0]*5 p1[-j-1] = scale_factor**j p2 = [0]*6 p2[-1] = N**(2-i) p_temp = multiply(p1,p2) if i > 0: p_dash = scale(poly,scale_factor) p_temp = multiply(p_temp[-5:],p_dash) basis_poly.append(p_temp) # print(basis_poly) basis_matrix = Matrix(ZZ, 10) # Init a 10x10 matrix # Changing format for i in range(10): for j in range(10): basis_matrix[i,j] = basis_poly[i][9-j] # print(basis_matrix[0]) # fpylll implementation of LLL # opylll fails because of high coefficients basis_matrix = basis_matrix.LLL() # The smallest LLL factor is in 1st row shortest_lattice = basis_matrix[0] # print(shortest_lattice) root = search_roots([shortest_lattice[9 - i]/scale_factor**(9 - i) for i in range(10)]) print('Password = ',int2bytes(root).decode('UTF-8'))
9c7610e1065f8a4c33c6549b50cd0f928111fbc7
Sahil4UI/Python_REG_Feb_Afternoon
/webcrawl.py
838
3.84375
4
import bs4 '''it is used to fetch the page's html code''' import urllib.request as url ''' it is used to send the request and get the response''' path = 'https://www.amazon.in/dp/B07DJD1RTM?pf_rd_r=5AEEXNXMJNKYYBX0BT3N&pf_rd_p=fa25496c-7d42-4f20-a958-cce32020b23e' httpresponse = url.urlopen(path) pagedata = bs4.BeautifulSoup(httpresponse,'lxml') '''lxml -library xml- parser library''' itemName = pagedata.find('span',id='productTitle') itemName = itemName.text itemName = itemName.strip(' \n') '''itemName = itemName.replace('\n','') itemName = itemName.replace(' ','') ''' print('item name',itemName) div = pagedata.find('div',id='feature-bullets') spanlist = div.findAll('span', class_ = 'a-list-item') c = 1 for i in spanlist: i = i.text i = i.strip(' \n\t ') print(c,'. ',i) c+=1
a64f6185a78ad3c1f04e6bdd6e31c1f69088879f
WilliamVJacob/Python-Code
/02.oddeven.py
184
4.1875
4
#progeam to print all the even numbers till 20 #var1=int(input("Enter a no:")); for num in range(1,21): # print (num); if(num%2==0): print(num,"is even"); # else: # print("odd");
6b8e11343d471def989a03f31b13d1979fc9bb2e
Kr08ti/Python
/Modules and Functions/Recursive().py
473
3.75
4
def factorial(x): if x == 0: return 1 else: return x * factorial(x-1) print factorial(6) def fibo(n): a = 0 b = 1 c = [] while b < n: c.append(b) temp = a a = b b = temp+a print c fibo(9) def fib(n): x = 0 y = 1 while y < n: temp = x x = y y = temp + x return n print(fibo(50)) def interger(num): n = 0 add = n + num print add interger(10)
b4aa21a4addac79ae14b9952a00bfd1f352aecb2
mingweihe/leetcode
/_0381_Insert_Delete_GetRandom_O_1_Duplicates_allowed.py
1,448
4.03125
4
from collections import defaultdict class RandomizedCollection(object): def __init__(self): """ Initialize your data structure here. """ self.vals = [] self.idxs = defaultdict(set) def insert(self, val): """ Inserts a value to the collection. Returns true if the collection did not already contain the specified element. :type val: int :rtype: bool """ res = not self.idxs[val] self.vals += val, self.idxs[val].add(len(self.vals)-1) return res def remove(self, val): """ Removes a value from the collection. Returns true if the collection contained the specified element. :type val: int :rtype: bool """ if self.idxs[val]: out_idx = self.idxs[val].pop() in_val = self.vals[-1] self.vals[out_idx] = self.vals[-1] self.vals.pop() self.idxs[in_val].add(out_idx) self.idxs[in_val].discard(len(self.vals)) return True return False def getRandom(self): """ Get a random element from the collection. :rtype: int """ return random.choice(self.vals) # Your RandomizedCollection object will be instantiated and called as such: # obj = RandomizedCollection() # param_1 = obj.insert(val) # param_2 = obj.remove(val) # param_3 = obj.getRandom()
0be30b35b7878d041971739b94d1d0f73fd4b77a
shivaniyads25/python-programs
/evenodd.py
108
4.15625
4
a=int(input("enter your number")) if(a%2==0): print("the number is even") else: print("the number is odd")
07728cb8697c21230cfaf605a1e79c250253f76a
13715483309/Test13
/test/类属性.py
310
3.875
4
# 类属性和类方法可以由类对象或者实例对象访问,但是实例属性和实例方法只能有实例对象访问 class Dog(): __tooth = 10 @classmethod def oo(self): print('one') obj = Dog() print(obj._Dog__tooth)#命名重装,可以访问私用方法 obj.oo() Dog.oo()
ba7b35d2d0c947e34afff9441889394806ac23bd
andrewdaoust/project-euler
/problem002.py
599
3.9375
4
""" Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms. """ def run(): fib_1 = 1 fib_2 = 2 result = 0 while fib_2 < 4e6: if fib_2 % 2 == 0: result += fib_2 tmp = fib_2 fib_2 += fib_1 fib_1 = tmp return result if __name__ == '__main__': sol = run() print(sol)
6541301d45346595e592656d64c419bab8677f9e
fralychen/Python_study
/py.py
139
3.890625
4
#!/usr/bin/python row = int(input("Enter the number of rows: ")) while row >= 0: x = "*" * row y = " " * (row - 1) print(x+y) row -= 1
50e83c86c7358dbc2d826dd9d70c773955756377
EdsonRodrigues1994/Mundo-2-Python
/desafio039.py
653
4.0625
4
#Faça um programa que leia o ano de nascimento de um jovem e informe, de acordo com sua idade: #Se ele ainda vai se alistar ao serviço militar #Se é a hora de se alistar #Se ja passou do tempo de se alistar #Seu programa também deverá mostrar o tempo que falta ou que passou do prazo from datetime import date nascimento = int(input("Digite o ano do seu nascimento: ")) anos = date.today().year - nascimento if anos < 18: print("Faltam {} ano(s) para o seu alistamento militar.".format(18 - anos)) elif anos == 18: print("É hora de se alistar") else: print("Já se passaram {} ano(s) do seu alistamento militar.".format(anos - 18))
782089238bedfcd981037066298a43e72efa87f5
chrycon/amfs
/setup.py
3,944
3.53125
4
# The whole fountain consisting of its 77 jets. U0=range(0,77) # The outer circle of 36 jets U1=range(0,36) # The even and odd jets on the outer circle U1_EVEN=[jet for jet in U1 if jet%2==0] U1_ODD=[jet for jet in U1 if jet%2!=0] # The two halves of the outer circle U1_HALF1=U1[:18] U1_HALF2=U1[18:] # The two triplet groups of the outer circle U1_TRIPLETS1=[0,1,2,6,7,8,12,13,14,18,19,20,24,25,26,30,31,32] U1_TRIPLETS2=[3,4,5,9,10,11,15,16,17,21,22,23,27,28,29,33,34,35] # The middle circle of 36 jets U2=range(36,72) # The even and odd jets on the middle circle U2_EVEN=[jet for jet in U2 if jet%2==0] U2_ODD=[jet for jet in U2 if jet%2!=0] # The two halves of the middle circle U2_HALF1=U2[:18] U2_HALF2=U2[18:] # The two triplet groups of the middle circle U2_TRIPLETS1=[jet+36 for jet in U1_TRIPLETS1] U2_TRIPLETS2=[jet+36 for jet in U1_TRIPLETS2] # The inner circle of 4 jets U3=range(72,76) # The two (opposite) halves of the inner circle U3_HALF1=[72,74] U3_HALF2=[73,75] # The middle jet U4=[76] # Maximum and minimum velocities of the four units, given that that they are on # i.e. their velocity is not 0m/s. MAX_VELOCITIES={"U1":11.0,"U2":14.0,"U3":15.0,"U4":17.0} MIN_VELOCITIES={"U1":6.0,"U2":8.0,"U3":10.0,"U4":12.0} # Maximum and minimum light intensities of the four units MAX_INTENSITIES={"U0":7.0,"U1":7.0,"U2":7.0,"U3":7.0,"U4":7.0} MIN_INTENSITIES={"U0":4.0,"U1":4.0,"U2":4.0,"U3":4.0,"U4":4.0} # The probability transition matrix of the scenarios. TRANSITIONS=[ # Intro [0,0,0,0.4,0.3,0.3], # Outro [0,0,0,0,0,0], # Chorus [0,0,0,0.5,0,0.5], # scVerse_1 [0,0,0,0,0.5,0.5], # scVerse_2 [0,0,0,0.5,0,0.5], # scVerse_3 [0,0,0,0.5,0.5,0]] # Calculate the cumulative transition matrix CUM_TRANSITIONS=[list(row) for row in TRANSITIONS] for i in range(0,len(TRANSITIONS)): for j in range(0,len(TRANSITIONS[i])): CUM_TRANSITIONS[i][j]=sum(TRANSITIONS[i][:j+1]) # The colors names used are found from "https://en.wikipedia.org/wiki/List_of_colors:_A-F" # Our color groups are divided in 8 equal-sized sectors around the centre .They are # defined by the respective boundary conditions. # NB: (5,5) is center COLOR_GROUPS=[ # Top-right # Aureolin rgb(0.99,0.93,0), Cadmium Orange rgb(0.93,0.53,0.18) {"bounds":(lambda x,y: y>=x and x>=5),"color1":{"r":0.99,"g":0.93,"b":0.0,"a":1.0},"color2":{"r":0.93,"g":0.53,"b":0.18,"a":1.0}}, # Azure rgb(0,0.5,1), Aureolin rgb(0.99,0.93,0) {"bounds":(lambda x,y: y<=x and y>=5),"color1":{"r":0.0,"g":0.5,"b":1.0,"a":1.0},"color2":{"r":0.99,"g":0.93,"b":0.0,"a":1.0}}, # Bottom-right # Bright Green rgb(0.4,1,0),Azure rgb(0,0.5,1) {"bounds":(lambda x,y: y>=-x+10 and y<=5),"color1":{"r":0.0,"g":0.5,"b":1.0,"a":1.0},"color2":{"r":0.4,"g":1.0,"b":0.0,"a":1.0}}, # Cadmium Green rgb(0,0.42,0.24), Caribbean Green (0,0.8,0.6) {"bounds":(lambda x,y: y<=-x+10 and x>=5),"color1":{"r":0.0,"g":0.42,"b":0.24,"a":1.0},"color2":{"r":0.0,"g":0.8,"b":0.6,"a":1.0}}, # Bottom-left # Dark Orchid rgb(0.6,0.2,0.8), Deep Mauve rgb(0.83,0.45,0.83) {"bounds":(lambda x,y: y<=x and x<5),"color1":{"r":0.6,"g":0.2,"b":0.8,"a":1.0},"color2":{"r":0.83,"g":0.45,"b":0.83,"a":1.0}}, # Fresh Air rgb(0.65,0.91,1), Cyan Cobalt Blue rgb(0.16,0.35,0.61) {"bounds":(lambda x,y: y>=x and y<5),"color1":{"r":0.65,"g":0.91,"b":1.0,"a":1.0},"color2":{"r":0.16,"g":0.35,"b":0.61,"a":1.0}}, # Top-left # Crimson Red rgb(0.6,0,0), Awesome (shade of red) rgb(1,0.13,0.32) {"bounds":(lambda x,y: y<=-x+10 and y>5),"color1":{"r":0.6,"g":0.0,"b":0.0,"a":1.0},"color2":{"r":1.0,"g":0.13,"b":0.32,"a":1.0}}, # Candy Apple Red rgb(1,0.03,0), Chrome Yellow rgb(1,0.65,0) {"bounds":(lambda x,y: y>=-x+10 and x<5),"color1":{"r":1.0,"g":0.03,"b":0.0,"a":1.0},"color2":{"r":1.0,"g":0.65,"b":0.0,"a":1.0}} ]
f20bcc923525120efd7b38d6614a2e418afa4c10
AhmetFurkanDEMIR/Python-Workouts
/OOP - Python/OOP - Proje/Class.py
2,076
3.765625
4
class Ogrenci(): def __init__(self, ad_soyad, tc_no, okul_no, ders_sayisi, bolum, dersler): self.ad_soyad = ad_soyad self.tc_no = tc_no self.okul_no = okul_no self.ders_sayisi = ders_sayisi self.bolum = bolum self.dersler = dersler def ogrenci_bilgi(self): print(""" İsim Soyisim : {} T.C No : {} Okul No : {} Okuduğu Bölüm : {} Aldığı Ders Sayısı : {} """.format(self.ad_soyad, self.tc_no, self.okul_no, self.bolum, self.ders_sayisi)) def __str__(): self.strr = """\n Üniversite Otomasyonu, Öğrenci Bölümü. Ogrenci bilgileri : Ad-Soyad, T.C No, Okul No, Bolum, Aldığı Ders sayisi, """ return def __len__(self): return self.ders_sayisi def __del__(self): print("\n Öğrenci silinmiştir.") class Dersler(): def __init__(self,ders_adi, ders_kodu, vize_orani,final_orani, final, vize): self.ders_adi = ders_adi self.ders_kodu = ders_kodu self.final_orani = final_orani self.vize_orani = vize_orani self.vize = vize self.final = final def vize_guncelle(self,vize): self.vize = vize def final_guncele(self,final): self.final = final def __len__(self): return (self.final * float(self.final_orani)) + (self.vize * float(self.vize_orani)) def __str__(self): self.a = self.final self.b = self.vize self.sonuc = float(self.final) * float(self.final_orani) + float(self.vize) * float(self.vize_orani) if int(self.final) == -1: self.a = "Vize Notu Girilmemiştir" if int(self.vize) == -1: self.b = "Final Notu Girilmemiştir" if (int(self.vize) == -1) | (int(self.final) == -1): self.sonuc = "Ders Sonuçlandırılmadı" self.verii = """ Ders adi : {} Ders kodu : {} Ders Final : {} Ders Vize : {} Ders Final oran : {} Ders Vize oran : {} Ders Ortalaması : {} """.format(self.ders_adi, self.ders_kodu, self.a, self.b, self.final_orani, self.vize_orani, self.sonuc) return self.verii
fdbb1ff89602f6bb04e4b37ead7ae9fdfffb073e
L1nwatch/Mac-Python-3.X
/Python项目开发实战/第6章 Python在更大项目中的应用/6.4 调试Python代码/except_class.py
1,282
4
4
#!/bin/env python3 # -*- coding: utf-8 -*- # version: Python3.X ''' 创建和使用自定义异常 在Python解释器中运行该脚本,使用-i标签来执行: python -i except_class.py 当使用-i标签启动Python解释器时,可以传入一个Python文件.而这会导入你传入的文件,而不必显示地在解释器中导入. ''' __author__ = '__L1n__w@tch' class TestClass(object): def __init__(self, name, number): self.name = name self.number = number def return_values(self): try: if type(self.number) is int: return "The values are: ", type(self.name), type(self.number) else: raise NotANumber(self.number) except NotANumber as e: print("The value for number must be an int you passed: ", e.value) class NotANumber(Exception): # 重写了__init__函数,使用value而不是args捕捉了异常中抛出的值 def __init__(self, value): self.value = value # 调用repr()方法输出了self.value属性,对于引发异常的值,repr()方法给出该值的正确的表示形式(也就是指打印出来的异常错误消息) def __str__(self): return repr(self.value) def main(): pass if __name__ == "__main__": main()
d0d554ebc114f8db772489a033265456abc65834
daniel-reich/ubiquitous-fiesta
/f6X7pa38iQyoytJgr_23.py
234
3.890625
4
def num(word): values = [ord(x) for x in word if x.isalpha()] return sum(values) def increasing_word_weights(sentence): words = sentence.split(" ") values = [num(word) for word in words] return values == sorted(values)
ae7449a71f1d23ae4d4e176e521698539bf7ffc4
yh97yhyh/ProblemSolving
/programmers/level1/level1_13.py
433
3.921875
4
''' < 소수 찾기 > 효율성 실패 ''' n1, n2 = 10, 5 def isprime(n): if n == 2: return True for i in range(3, n): if n % i == 0: return False return True def solution(n): cnt = 0 if n >= 2: cnt += 1 for i in range(3, n+1, 2): if i == 1: continue if isprime(i): cnt += 1 return cnt print(solution(n1)) print(solution(n2))
0d3a853377255935babe7b69847a80cb80cc1662
rer3/Coursera_RiceUni
/PoC/PoC_Assignments/PoC2_Project3_TTTMinimax.py
26,052
4.0625
4
""" Rice University / Coursera: Principles of Computing (Part 2) Week 3: Project 3 Tic-Tac-Toe - Minimax """ #================================================================= # All code for this assignment is shown below with only essential imports. # Code provided by Rice University has been modified whenever applicable. # All sections/questions enclosed in functions precede a call to their function. # Code for this project was run in CodeSkulptor (http://www.codeskulptor.org). #================================================================= # All import statements needed. import codeskulptor import simplegui codeskulptor.set_timeout(60) # Below is the link to the description of this assignment. COURSE = "https://class.coursera.org/principlescomputing1-004/" DESCRIPTION = COURSE + "wiki/view?page=tictactoemm" #----------------------------------------------------------------- ## Provided TicTacGUI class, constants, and run_gui function (poc_ttt_gui). GUI_WIDTH = 400 GUI_HEIGHT = GUI_WIDTH BAR_WIDTH = 5 class TicTacGUI: """ GUI for Tic Tac Toe game. """ def __init__(self, size, aiplayer, aifunction, ntrials, reverse=False): # Game board self._size = size self._bar_spacing = GUI_WIDTH // self._size self._turn = PLAYERX self._reverse = reverse # AI setup self._humanplayer = switch_player(aiplayer) self._aiplayer = aiplayer self._aifunction = aifunction self._ntrials = ntrials # Set up data structures self.setup_frame() # Start new game self.newgame() def setup_frame(self): """ Create GUI frame and add handlers. """ self._frame = simplegui.create_frame("Tic-Tac-Toe", GUI_WIDTH, GUI_HEIGHT) self._frame.set_canvas_background('White') # Set handlers self._frame.set_draw_handler(self.draw) self._frame.set_mouseclick_handler(self.click) self._frame.add_button("New Game", self.newgame) self._label = self._frame.add_label("") def start(self): """ Start the GUI. """ self._frame.start() def newgame(self): """ Start new game. """ self._board = TTTBoard(self._size, self._reverse) self._inprogress = True self._wait = False self._turn = PLAYERX self._label.set_text("") def drawx(self, canvas, pos): """ Draw an X on the given canvas at the given position. """ halfsize = .4 * self._bar_spacing canvas.draw_line((pos[0]-halfsize, pos[1]-halfsize), (pos[0]+halfsize, pos[1]+halfsize), BAR_WIDTH, 'Black') canvas.draw_line((pos[0]+halfsize, pos[1]-halfsize), (pos[0]-halfsize, pos[1]+halfsize), BAR_WIDTH, 'Black') def drawo(self, canvas, pos): """ Draw an O on the given canvas at the given position. """ halfsize = .4 * self._bar_spacing canvas.draw_circle(pos, halfsize, BAR_WIDTH, 'Black') def draw(self, canvas): """ Updates the tic-tac-toe GUI. """ # Draw the '#' symbol for bar_start in range(self._bar_spacing, GUI_WIDTH - 1, self._bar_spacing): canvas.draw_line((bar_start, 0), (bar_start, GUI_HEIGHT), BAR_WIDTH, 'Black') canvas.draw_line((0, bar_start), (GUI_WIDTH, bar_start), BAR_WIDTH, 'Black') # Draw the current players' moves for row in range(self._size): for col in range(self._size): symbol = self._board.square(row, col) coords = self.get_coords_from_grid(row, col) if symbol == PLAYERX: self.drawx(canvas, coords) elif symbol == PLAYERO: self.drawo(canvas, coords) # Run AI, if necessary if not self._wait: self.aimove() else: self._wait = False def click(self, position): """ Make human move. """ if self._inprogress and (self._turn == self._humanplayer): row, col = self.get_grid_from_coords(position) if self._board.square(row, col) == EMPTY: self._board.move(row, col, self._humanplayer) self._turn = self._aiplayer winner = self._board.check_win() if winner is not None: self.game_over(winner) self._wait = True def aimove(self): """ Make AI move. """ if self._inprogress and (self._turn == self._aiplayer): row, col = self._aifunction(self._board, self._aiplayer, self._ntrials) if self._board.square(row, col) == EMPTY: self._board.move(row, col, self._aiplayer) self._turn = self._humanplayer winner = self._board.check_win() if winner is not None: self.game_over(winner) def game_over(self, winner): """ Game over """ # Display winner if winner == DRAW: self._label.set_text("It's a tie!") elif winner == PLAYERX: self._label.set_text("X Wins!") elif winner == PLAYERO: self._label.set_text("O Wins!") # Game is no longer in progress self._inprogress = False def get_coords_from_grid(self, row, col): """ Given a grid position in the form (row, col), returns the coordinates on the canvas of the center of the grid. """ # X coordinate = (bar spacing) * (col + 1/2) # Y coordinate = height - (bar spacing) * (row + 1/2) return (self._bar_spacing * (col + 1.0/2.0), # x self._bar_spacing * (row + 1.0/2.0)) # y def get_grid_from_coords(self, position): """ Given coordinates on a canvas, gets the indices of the grid. """ posx, posy = position return (posy // self._bar_spacing, # row posx // self._bar_spacing) # col def run_gui(board_size, ai_player, ai_function, ntrials, reverse=False): """ Instantiate and run the GUI """ gui = TicTacGUI(board_size, ai_player, ai_function, ntrials, reverse) gui.start() #----------------------------------------------------------------- ## Provided TTTBoard class, constants, and switch_player and play_game functions ## (poc_ttt_provided). # Constants EMPTY = 1 PLAYERX = 2 PLAYERO = 3 DRAW = 4 # Map player constants to letters for printing STRMAP = {EMPTY: " ", PLAYERX: "X", PLAYERO: "O"} class TTTBoard: """ Class to represent a Tic-Tac-Toe board. """ def __init__(self, dim, reverse = False, board = None): """ Initialize the TTTBoard object with the given dimension and whether or not the game should be reversed. """ self._dim = dim self._reverse = reverse if board == None: # Create empty board self._board = [[EMPTY for dummycol in range(dim)] for dummyrow in range(dim)] else: # Copy board grid self._board = [[board[row][col] for col in range(dim)] for row in range(dim)] def __str__(self): """ Human readable representation of the board. """ rep = "" for row in range(self._dim): for col in range(self._dim): rep += STRMAP[self._board[row][col]] if col == self._dim - 1: rep += "\n" else: rep += " | " if row != self._dim - 1: rep += "-" * (4 * self._dim - 3) rep += "\n" return rep def get_dim(self): """ Return the dimension of the board. """ return self._dim def square(self, row, col): """ Returns one of the three constants EMPTY, PLAYERX, or PLAYERO that correspond to the contents of the board at position (row, col). """ return self._board[row][col] def get_empty_squares(self): """ Return a list of (row, col) tuples for all empty squares """ empty = [] for row in range(self._dim): for col in range(self._dim): if self._board[row][col] == EMPTY: empty.append((row, col)) return empty def move(self, row, col, player): """ Place player on the board at position (row, col). player should be either the constant PLAYERX or PLAYERO. Does nothing if board square is not empty. """ if self._board[row][col] == EMPTY: self._board[row][col] = player def check_win(self): """ Returns a constant associated with the state of the game If PLAYERX wins, returns PLAYERX. If PLAYERO wins, returns PLAYERO. If game is drawn, returns DRAW. If game is in progress, returns None. """ board = self._board dim = self._dim dimrng = range(dim) lines = [] # rows lines.extend(board) # cols cols = [[board[rowidx][colidx] for rowidx in dimrng] for colidx in dimrng] lines.extend(cols) # diags diag1 = [board[idx][idx] for idx in dimrng] diag2 = [board[idx][dim - idx -1] for idx in dimrng] lines.append(diag1) lines.append(diag2) # check all lines for line in lines: if len(set(line)) == 1 and line[0] != EMPTY: if self._reverse: return switch_player(line[0]) else: return line[0] # no winner, check for draw if len(self.get_empty_squares()) == 0: return DRAW # game is still in progress return None def clone(self): """ Return a copy of the board. """ return TTTBoard(self._dim, self._reverse, self._board) def switch_player(player): """ Convenience function to switch players. Returns other player. """ if player == PLAYERX: return PLAYERO else: return PLAYERX def play_game(mc_move_function, ntrials, reverse = False): """ Function to play a game with two MC players. """ # Setup game board = TTTBoard(3, reverse) curplayer = PLAYERX winner = None # Run game while winner == None: # Move row, col = mc_move_function(board, curplayer, ntrials) board.move(row, col, curplayer) # Update state winner = board.check_win() curplayer = switch_player(curplayer) # Display board print board print # Print winner if winner == PLAYERX: print "X wins!" elif winner == PLAYERO: print "O wins!" elif winner == DRAW: print "Tie!" else: print "Error: unknown winner" ##================================================================= DIRECTIONS = ''' Overview ---------- We have previously seen Tic-Tac-Toe in part 1 of this class. In this assignment, we are going to revisit the game and develop an alternative strategy to play the game. For this assignment, your task is to implement a machine player for Tic-Tac-Toe that uses a Minimax strategy to decide its next move. You will be able to use the same console-based interface and graphical user interface to play the game as you did before. Although the game is played on a 3×3 grid, your version should be able to handle any square grid (however, the time it will take to search the tree for larger grid sizes will be prohibitively slow). We will continue to use the same grid conventions that we have used previously. This project does not require you to write a lot of code. It does, however, bring together a lot of concepts that we have previously seen in the class. We would like you to think about how these concepts are coming together to enable you to build a relatively complex machine player with very little code. Further, you should think about the situations in which Minimax or Monte Carlo might produce better/worse machine players for games other than Tic-Tac-Toe. Provided Code ---------- We have provided a TTTBoard class for you to use. This class keeps track of the current state of the game board. You should familiarize yourself with the interface to the TTTBoard class in the poc_ttt_provided module. The provided module also has a switch_player(player) function that returns the other player (PLAYERX or PLAYERO). The provided module defines the constants EMPTY, PLAYERX, PLAYERO, and DRAW for you to use in your code. The provided TTTBoard class and GUI use these same constants, so you will need to use them in your code, as well. At the bottom of the provided template, there are example calls to the GUI and console game player. You may uncomment and modify these during the development of your machine player to actually use it in the game. Note that these are the same calls we used previously for your Monte Carlo strategy, so they take an ntrials parameter. You can pass anything you want as ntrials, since you will not be using it for Minimax. In order to allow us to use the same infrastructure, we have also provided a move_wrapper function in the template that you can pass to play_game and run_gui. This wrapper simply translates between the inputs and outputs of your function and those that were expected if you were implementing a Monte Carlo player. Testing your mini-project ---------- As you implement your machine player, we suggest that you build your own collection of tests using the poc_simpletest module that we have provided. Please review this page for an overview of the capabilities of this module. These tests can be organized into a separate test suite that you can import and run in your program as we demonstrated for Solitaire Mancala. To facilitate testing on the first few mini- projects, we will create a thread in the forums where students may share and refine their test suites for each mini-project. IMPORTANT: In this project, you will use Minimax to search the entire game tree. If you start with an empty Tic-Tac-Toe board, it will take a long time for your strategy to search the tree. Therefore, we strongly suggest that you write tests that start with a partially full board. This will allow your code to run much faster and will lead to a more pleasant development and debugging experience. Finally, submit your code (with the calls to play_game and run_gui commented out) to this Owltest page. This page will automatically test your mini-project. It will run faster if you comment out the calls to play_game and run_gui before submitting. Note that trying to debug your mini-project using the tests in OwlTest can be very tedious since they are slow and give limited feedback. Instead, we strongly suggest that you first test your program using your own test suite and the provided GUI. Programs that pass these tests are much more likely to pass the OwlTest tests. Remember that OwlTest uses Pylint to check that you have followed the coding style guidelines for this class. Deviations from these style guidelines will result in deductions from your final score. Please read the feedback from Pylint closely. If you have questions, feel free to consult this page and the class forums. When you are ready to submit your code to be graded formally, submit your code to the CourseraTest page for this mini-project that is linked on the main assignment page. Machine Player Strategy ---------- Your machine player should use a Minimax strategy to choose the next move from a given Tic-Tac-Toe position. As the objective of this assignment is to help you bring together what you have learned, we ask that you do not search for pseudo- code to implement Minimax. At this point in the class, we hope that you can use the examples in the lectures and an English language description and be able to implement Minimax. The general idea on Minimax is to search the entire game tree alternating between minimizing and maximizing the score at each level. For this to work, you need to start at the bottom of the tree and work back towards the root. However, instead of actually building the game tree to do this, you should use recursion to search the tree in a depth-first manner. Your recursive function should call itself on each child of the current board position and then pick the move that maximizes (or minimizes, as appropriate) the score. If you do this, your recursive function will naturally explore all the way down to the bottom of the tree along each path in turn, leading to a depth first search that will implement Minimax. The following page describes the process in more detail. As you recursively call your minimax function, you should create a copy of the board to pass to the next level. When the function returns, you no longer need that copy of the board. In this manner, you are dynamically constructing the part of the game tree that you are actively looking at, but you do not need to keep it around. For this mini-project, you need only implement one function: * mm_move(board, player): This function takes a current board and which player should move next. The function should use Minimax to return a tuple which is a score for the current board and the best move for the player in the form of a (row, column) tuple. In situations in which the game is over, you should return a valid score and the move (-1, -1). As (-1, -1) is an illegal move, it should only be returned in cases where there is no move that can be made. You should start from this code that imports the Tic-Tac-Toe class and a wrapper function to enable you to play the game. You may add extra helper functions if so desired. Hints ---------- You do not need to write a lot of code to implement Minimax, but it can be difficult to get everything working correctly. Here are some hints that may help you out: * Do not forget the base case in your recursive function. Think carefully about when you can return with an answer immediately. * Remember to make a copy of the board before you recursively call your function. If you do not, you will modify the current board and you will not be searching the correct tree. * The SCORES dictionary is useful. You should use it to score a completed board. For example, the score of a board in which X has won should be SCORES[provided.PLAYERX]. If the game is a draw, you should score the board as 0. * In Minimax, you need to alternate between maximizing and minimizing. Given the SCORES that we have provided you with, player X is always the maximizing player and play O is always the minimizing player. You can use an if-else statement to decide when to maximize and when to minimize. But, you can also be more clever by noticing that if you multiply the score by SCORES[player] then you can always maximize. Why? Because this has the effect of negating player O's scores allowing you to maximize instead of minimize for player O. * Minimax can be slow when there are a lot of moves to explore. The way we have set up the scoring, you do not always need to search everything. If you find a move that yields a winning score (+1 for X or -1 for O), you know that you cannot do any better by continuing to search the other possible moves from the current board. So, you can just return immediately with the score and move at that point. This will significantly speed up the search. ''' ##================================================================= # Write a function mm_move(board, player) that computes "minimax" # scores for TTT boards. PLAYERX pursues maximum scores and PLAYERO # pursues minimum scores. Use recursion to perform a depth first search # on each board configuration, terminating when there is a winner or draw. # The mm_move implementation takes advantage of a dictionary called # MEMORY to store computed scores for board configurations to improve # running time. The recursive function has a base case equal to a finished # game with a winner (PLAYERX, PLAYERO, DRAW) and no more moves. # If no moves, a square (-1, -1) is returned, which is an illegal move. # Start with the base case where there is a winner and no move can be made. # This check can be done with a call to board.check_win(). If there is no winner, # proceed with the recursive call. First initialize best_score with a placeholder # that is the extreme opposite of the player score (so if player == X, the score # must be init'd to -INF since we are looking for the largest score for X). Then # for each empty square in the board: clone the board, move the player to the # empty square, check the "memory" for the board config score (or make a recursive # call to mm_move with the new board and update the memory), and then check # against certain conditions. # For player X, if the computed score of the board config is greater than the # best score (starting out at -INF), best_score must be updated along with the # associated best_square. The opposite is true for player O, where best_score is # updated with the config score if it is less than best_score. If the config score is # equal to the player score, that signifies a win and the function can return the # move as it is arbitrary whether other moves exist that can lead to a win. # This repeats for every empty move in the board, and then the best score and # the associated best square are returned. # There must be a trick to combining a best_score/best_square update that affects # player X and O equally so that two separately conditionals need not be used. # Instinctually, I want to write two statements (if player == PLAYERX, if player == # PLAYER O), but it is hinted at that this can be done in one single statement. # I have to identify how a config score can be compared to best score the same # way for both players. It's obvious that X = 1 and O = -1 is a good start. Since # for X, score > best score means updating best score, and for O score < best # score means updating best score, I could integrate the player score into that # computation in a way that makes a generic "score > best score" work. By # multiplying player score by both sides, player X's check is unchanged as player # X's score is +1, but player O, with a score of -1, would see a change such that # its largest value between score and best score would be swapped. If the starting # best_score is INF, and it's looking for a smaller number, it wants score < INF. # If score = 0, and both sides are multiplied by -1, that changes the expression # to 0 > -INF, or score * player score > best score * player score. # SCORING VALUES - DO NOT MODIFY SCORES = {PLAYERX: 1, DRAW: 0, PLAYERO: -1} # Initialize a "memory" variable to store scores for board configurations. MEMORY = {} def mm_move(board, player): """ Make a move on the board. Returns a tuple with two elements. The first element is the score of the given board and the second element is the desired move as a tuple, (row, col). """ # Check for the base case. winner = board.check_win() if winner != None: return SCORES[winner], (-1, -1) else: if player == PLAYERX: best_score = float("-inf") elif player == PLAYERO: best_score = float("inf") best_square = (-1, -1) # Iterate over each potential move. Reference MEMORY or # execute recursive call with updated board and other player. for square in board.get_empty_squares(): test_board = board.clone() test_board.move(square[0], square[1], player) if str(test_board) in MEMORY: score = MEMORY[str(test_board)] else: score, dummy_square = mm_move(test_board, switch_player(player)) MEMORY[str(test_board)] = score # Return if winning move, otherwise update score accordingly. if score == SCORES[player]: return score, square if score * SCORES[player] > best_score * SCORES[player]: best_score = score best_square = square return best_score, best_square def move_wrapper(board, player, trials): """ Wrapper to allow the use of the same infrastructure that was used for Monte Carlo Tic-Tac-Toe. """ move = mm_move(board, player) assert move[1] != (-1, -1), "returned illegal move (-1, -1)" return move[1] # Test game with the console or the GUI. # Uncomment whichever you prefer. Uncomment when submitting to OwlTest. #play_game(move_wrapper, 1, False) #run_gui(3, PLAYERO, move_wrapper, 1, False) ##================================================================= ##=================================================================
de034b96d8812565cea64d7556b83127c9dbea19
sandyjernigan/Graphs
/projects/word/word_ladder1.py
3,122
3.9375
4
# Given two words (begin_word and end_word), and a dictionary's word list, # return the shortest transformation sequence from begin_word to end_word, such that: # Only one letter can be changed at a time. # Each transformed word must exist in the word list. Note that begin_word is not a transformed word. # Note: # Return None if there is no such transformation sequence. # All words contain only lowercase alphabetic characters. # You may assume no duplicates in the word list. # You may assume begin_word and end_word are non-empty and are not the same. # Sample: # begin_word = "hit" # end_word = "cog" # return: ['hit', 'hot', 'cot', 'cog'] # begin_word = "sail" # end_word = "boat" # ['sail', 'bail', 'boil', 'boll', 'bolt', 'boat'] # beginWord = "hungry" # endWord = "happy" # None class Queue(): def __init__(self): self.queue = [] def enqueue(self, value): self.queue.append(value) def dequeue(self): if self.size() > 0: return self.queue.pop(0) else: return None def size(self): return len(self.queue) f = open('words.txt', 'r') words = f.read().split("\n") f.close() # create a set of words, for easy lookup words_set = set() for word in words: words_set.add(word) alphabet = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'] def get_neighbors(word): neighbors = [] # for each letter in word list_of_chars = list(word) for i in range(len(list_of_chars)): # change that letter with every letter of alphabet for letter in alphabet: new_word = list(list_of_chars) new_word[i] = letter # check if the new word exists in our word_set new_word_string = "".join(new_word) if (new_word_string != word and new_word_string in words_set): # if yes, add the word as a neighbor neighbors.append(new_word_string) # return a list of neighbors return neighbors def find_path(begin_word, end_word): visted = set() words_to_visit = Queue() words_to_visit.enqueue([begin_word]) while words_to_visit.size() > 0: # remove the current vertex and path from queue path = words_to_visit.dequeue() current_word = path[-1] # make sure we havent visited this word if current_word not in visted: # add to visited visted.add(current_word) # check if this current_word is our target if current_word == end_word: return path # otherwise, find all neighbors and create new paths for neighbor in get_neighbors(current_word): path_copy = list(path) path_copy.append(neighbor) words_to_visit.enqueue(path_copy) begin_word = "hit" end_word = "cog" print(find_path(begin_word, end_word)) # return: ['hit', 'hot', 'cot', 'cog'] begin_word = "sail" end_word = "boat" print(find_path(begin_word, end_word)) # ['sail', 'bail', 'boil', 'boll', 'bolt', 'boat']
0b81b4d99fb7bf4c671227494892bf6a4e151a78
milenatteixeira/cc1612-exercicios
/exercicios/lab 11/ex1.py
496
3.609375
4
from tkinter import * from datetime import datetime janela = Tk() janela.geometry("300x200") janela.title("Exercício 1") hora = Label(janela) hora.place(relx=0.5, rely=0.3, anchor=CENTER) data = Label(janela) data.place(relx=0.5, rely=0.5, anchor=CENTER) def att(): x = datetime.now() time = x.strftime("%H:%M:%S") date = x.strftime("%d/%m/%Y") hora['text'] = time data['text'] = date janela.after(1000, att) att() janela.mainloop()
aebbb6b5242560ae599be5864aa34dc032492efc
eric-bickerton/hackerrank
/breaking-records
844
3.671875
4
#!/bin/python3 import math import os import random import re import sys # # Complete the 'breakingRecords' function below. # # The function is expected to return an INTEGER_ARRAY. # The function accepts INTEGER_ARRAY scores as parameter. # def breakingRecords(scores): # Write your code here most, least = scores[0],scores[0] countmin,countmax = 0,0 for x in scores: if x>most: most = x countmax+=1 if x<least: least = x countmin+=1 return [countmax,countmin] if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') n = int(input().strip()) scores = list(map(int, input().rstrip().split())) result = breakingRecords(scores) fptr.write(' '.join(map(str, result))) fptr.write('\n') fptr.close()
74951b2a5cc04157582430aecbdb466f3d4eea72
slayer96/codewars_tasks
/replace_with_alphabet_position.py
1,000
4.21875
4
""" In this kata you are required to, given a string, replace every letter with its position in the alphabet. If anything in the text isn't a letter, ignore it and don't return it. "a" = 1, "b" = 2, etc. Example alphabet_position("The sunset sets at twelve o' clock.") Should return "20 8 5 19 21 14 19 5 20 19 5 20 19 1 20 20 23 5 12 22 5 15 3 12 15 3 11" (as a string) """ from random import randint def alphabet_position(text): res = [] for char in text: if char.isalpha(): res.append(str(ord(char.lower())-96)) return ' '.join(res) assert alphabet_position("The sunset sets at twelve o' clock.") ==\ "20 8 5 19 21 14 19 5 20 19 5 20 19 1 20 20 23 5 12 22 5 15 3 12 15 3 11" assert alphabet_position("The narwhal bacons at midnight.") ==\ "20 8 5 14 1 18 23 8 1 12 2 1 3 15 14 19 1 20 13 9 4 14 9 7 8 20" number_test = "" for item in range(10): number_test += str(randint(1, 9)) assert alphabet_position(number_test) == "" print('done')
47a275a95150db285b53395f8a323f6d2b25ded0
voyagelll/python
/data_structure/_哈希/hash.py
3,450
3.890625
4
# coding=gbk """ ϣ - ǽһȵ룬ͨɢ㷨任ɹ̶ȵ ϣ - ݼֵʵݽṹ ͨѼֵӳһλʼ¼Լӿٶȣӳ亯ɢкż¼ݣɢб - ʱ O(1) - ͻ * Ѱַ H = (hash(k) + di) MOD m, i=1,2,3...k(k<=m-1) [hash(k):ɢкdi] 1. ̽ɢУ di = 1,2,3...m-1 2. ƽ̽ɢУ di = 1^2, -1^2, ...+-(k)^2 (k<=m/2) 3. ̽ɢУ di = α * ɢз * ַ * ժҪ㷨 - MD5 - SHA - Ӧ * ļУ * ǰ """ class hashtable1(object): def __init__(self): self.items = [] def put(self, k, v): self.items.append((k, v)) def get(self, k): for key, value in self.items: if (k==key): return value class hashtable2(object): # ֱӶַ˷ѿռ) def __init__(self): self.items = [None] * 100 def hash(self, a): return a*1+1 def put(self, k, v): self.items[self.hash(k)] = v def get(self, k): hashcode = self.hash(k) return self.items[hashcode] class hashtable3(object): # ŵַ̽⣩ def __init__(self): self.capacity = 10 self.hash_table = [[None, None] for i in range(self.capacity)] self.num = 0 self.load_factor = 0.75 def hash(self, k, i): h_value = (k+i) % self.capacity if self.hash_table[h_value][0] == k: return h_value if self.hash_table[h_value][0] != None: i += 1 h_value = self.hash(k, i) return h_value def resize(self): self.capacity = self.num * 2 temp = self.hash_table[:] self.hash_table = [[None, None] for i in range(self.capacity)] for i in temp: if (i[0] != None): hash_v = self.hash(i[0], 0) self.hash_table[hash_v][0] = i[0] self.hash_table[hash_v][1] = i[1] def put(self, k, v): hash_v = self.hash(k, 0) self.hash_table[hash_v][0] = k self.hash_table[hash_v][1] = v self.num = self.num + 1 if (self.num / len(self.hash_table) > self.load_factor): self.resize() def get(self, k): hash_v = self.hash(k, 0) return self.hash_table[hash_v] table = hashtable3() for i in range(1,13): table.put(i, i) print(table.get(3)) print(table.hash_table) """ ж - ̳ - ɸѡ 1nȫŽ飬Ϊ϶״̬ 2±żȫΪ״̬ 3һα鳤ȵƽ 4ǰִڱ϶״̬䱳״̬Ϊ """ def find_prime(num): # ̳1 if num > 1: for i in range(2, num): if num % i == 0: print(num, 'is not prime num') print(i, '*', num//i, '=', num) break else: print(num, 'is prime num') else: print(num, 'is not prime num') # find_prime(7) import math def prime_filter(num): # ɸѡ primes_bool = [False, False] + [True]*(num-1) for i in range(3, len(primes_bool)): if i%2 == 0: primes_bool[i] = False for i in range(3, int(math.sqrt(num))+1): if primes_bool[i] is True: for j in range(i+i, num+1, i): primes_bool[j] = False primes = [] for i, v in enumerate(primes_bool): if v is True: primes.append(i) return primes print(prime_filter(100))
b152eccc8b5a6636c7fed7cf4ce112ce6d17a068
liangqiding/python-milestone
/05函数式编程/1高阶函数.py
1,099
3.96875
4
# 以Python内置的求绝对值的函数abs()为例,调用该函数用以下代码: from functools import reduce print('请绝对值:', abs(-10)) # 传入函数 def add(x, y, f): return f(x) + f(y) print('传入函数:', add(-5, 6, abs)) # Python内建了map()和reduce()函数。 def f(x): return x * x r = map(f, [1, 2, 3, 4, 5, 6, 7, 8, 9]) print('map:', list(r)) # 转str r = list(map(str, [1, 2, 3, 4, 5, 6, 7, 8, 9])) print('转str:', r) # 再看reduce的用法。reduce把一个函数作用在一个序列[x1, x2, x3, ...]上,这个函数必须接收两个参数,reduce把结果继续和序列的下一个元素做累积计算,其效果就是: def add(x, y): return x + y r = reduce(add, [1, 3, 5, 7, 9]) print('求和:', r) # filter def is_odd(n): return n % 2 == 1 r = list(filter(is_odd, [1, 2, 4, 5, 6, 9, 10, 15])) print('过滤:', r) def not_empty(s): return s and s.strip() print(not_empty('s')) # Python内置的sorted()函数就可以对list进行排序: r = sorted([36, 5, -12, 9, -21], key=abs) print('排序:', r)
0c35d9ca069fb5c5aa45a1614f92b9e0e627f929
JRobertEdwards/RedditFlairCLI
/RedditFlairCLI/redditCLI.py
2,078
3.59375
4
import argparse from reddit import reddit def check_for_flairs(args): sub = str(args.sub[0]).strip('[]\' ') flair_count = 0 if(args.flair): # Characters must be stripped due to the way that ArgParse handles user inputs. flair_entered = str(args.flair[0]).strip('[]\' ') sub = str(args.sub[0]) print(type(sub)) this_sub = reddit.subreddit(sub) for flair in this_sub.flair(limit=None): if flair['flair_text'] == flair_entered: print('Match') flair_count += 1 if(args.css): cs = str(args.css[0]).strip('[]\' ') # Characters must be stripped due to the way that ArgParse handles user inputs. this_sub = reddit.subreddit(sub) for flair in this_sub.flair(limit=None): if flair['flair_css_class'] == cs: print('Match') flair_count += 1 return print('Flair Count: ', flair_count) # This is the CLI you can use to determine the functions of this program. This was initially only designed to be used for selecting a subreddit to point at. parser = argparse.ArgumentParser(description='Can count how many flairs or flair_css_class instances you have on your subreddit.', add_help='This is a test.') parser.add_argument('sub', nargs=1, type=str, help='This is the subreddit you want to use. You don\'t need to type \'sub\' for this,' 'it will just pick up the first string you enter. \n\n An Example of this would be to type something like: ' 'python3 redditCLI.py soccer -f :Arsenal:') parser.add_argument('-v', '--version', action='version', version='Flair Counter-CLI 1.0') parser.add_argument('-flair', '-f', nargs=1, type=str, help='This is the flair you want to check. By Default this will ' 'perform a count on all possible flairs.', action='append') parser.add_argument('-css', nargs=1, type=str, help='The flair_css_class text you want to look for.') args = parser.parse_args() parser.set_defaults(func=check_for_flairs(args))
200a4f45ab2f2e5767096d3c81d04f169ba76746
cirusthenter/python
/src/sort/counting_sort.py
1,409
3.859375
4
from typing import List, MutableSequence import time import random def counting_sort(a: List[int]) -> None: counts = [0] * (max(a) + 1) for i in a: counts[i] += 1 i = 0 for elem, count in enumerate(counts): for _ in range(count): a[i] = elem i += 1 def fsort(a: MutableSequence, max: int) -> None: """度数ソート(配列要素の値は0以上max以下)""" n = len(a) f = [0] * (max + 1) # 累積度数 b = [0] * n # 作業用目的配列 for i in range(n): f[a[i]] += 1 # [Step 1] for i in range(1, max + 1): f[i] += f[i - 1] # [Step 2] for i in range(n - 1, -1, -1): f[a[i]] -= 1; b[f[a[i]]] = a[i] # [Step 3] for i in range(n): a[i] = b[i] # [Step 4] def counting_sort_text(a: MutableSequence) -> None: """度数ソート""" fsort(a, max(a)) num = int(input("input an integer: ")) x1 = [random.randint(0, num) for _ in range(num)] x2 = x1.copy() x3 = x2.copy() start1 = time.time() counting_sort(x1) end1 = time.time() start2 = time.time() counting_sort_text(x2) end2 = time.time() start3 = time.time() x3.sort() end3 = time.time() print("result:", "success" if x1 == x2 == x3 else "failed") print("my counting_sort:", end1 - start1) print("text:", end2 - start2) print("STL:", end3 - start3)
a89d9b2939dda806beaccbd1f5540e306ccb48d3
Gkar-Narn/biblia_xml
/lib_funcoes.py
1,844
3.84375
4
def zeros_esq(valor, tamanho=3): '''Função que acrescenta zeros a esquerda de acordo com a quantidade definida.\n Retorna Texto. Padrão '000'\n valor = valor que deseja acrescentar zeros a esquerda\n tamanho = tamanho da string completa ''' texto = str(valor) return (tamanho - len(texto)) * '0' + str(texto) def distrib_pacote(num, base): ''' Distribui uniformemente uma quantidade informada em pacotes de acordo com a base máxima definida.\nEx: Distribuir 13 unidades em pacotes com conteúdo máximo de 5 por pacote.\n Retorno: [5, 4, 4] ''' # Definindo qte pacotes qte_pacotes = num // base if (num % base) != 0: # sobrou resto? então é mais um pacote qte_pacotes+=1 # Definindo conteúdo conteudo = num // qte_pacotes resto = num % qte_pacotes # Preenchendo o conteudo para cada pacote pacotes = [] # se o resto == 0 o conteudo por pacote é a mesma para todos os pacotes for i in range(qte_pacotes): if resto == 0: pacotes.append(conteudo) else: resto-=1 # retirando 1 do resto pacotes.append(conteudo + 1) return pacotes def acentos(texto): '''Retira os acentos de um texto''' a = ['á','â','ã'] e = ['é','ê'] i = ['í','î'] o = ['ó','ô','õ'] u = ['ú','û'] c = ['ç'] saida = texto for v in a: saida = saida.replace(v, 'a') for v in e: saida = saida.replace(v, 'e') for v in i: saida = saida.replace(v, 'i') for v in o: saida = saida.replace(v, 'o') for v in u: saida = saida.replace(v, 'u') for v in c: saida = saida.replace(v, 'c') # Espaço dentro saida = saida.replace(' ','') return saida
7677773c0a4e1710d63788501e16ed5b79a84894
LMFrank/Algorithm
/course/01_single_link_list.py
2,818
3.828125
4
class Node(object): def __init__(self, elem, next_=None): self.elem = elem self.next = next_ class SingleLinkList(object): """单链表""" def __init__(self, node=None): self._head = node def is_empty(self): """链表是否为空""" return self._head is None def length(self): """链表长度""" cur = self._head # cur游标,用来遍历节点 count = 0 # 记录数量 while cur is not None: count += 1 cur = cur.next return count def travel(self): """遍历整个链表""" cur = self._head while cur is not None: print(cur.elem, end=' ') cur = cur.next print('') def add(self, item): """链表头部添加元素""" node = Node(item) node.next = self._head self._head = node def append(self, item): """链表尾部添加元素""" node = Node(item) if self.is_empty(): self._head = node else: cur = self._head while cur.next is not None: cur = cur.next cur.next = node def insert(self, pos, item): """指定位置添加元素""" if pos < 0: self.add(item) elif pos >=(self.length() - 1): self.append(item) else: pre = self._head count = 0 while count < (pos-1): count += 1 pre = pre.next node = Node(item) node.next = pre.next pre.next = node def remove(self, item): """删除节点""" cur = self._head pre = None while cur is not None: if cur.elem == item: # 先判断此节点是否是头结点 if cur == self._head: self._head = cur.next else: pre.next = cur.next break else: pre = cur cur = cur.next def search(self, item): """查找节点""" cur = self._head while cur is not None: if cur.elem == item: return True else: cur = cur.next return False if __name__ == '__main__': li = SingleLinkList() print(li.is_empty()) print(li.length()) li.append(1) print(li.is_empty()) print(li.length()) li.append(2) li.add(6) for i in range(4, 8): li.append(i) li.travel() li.insert(-1, 9) li.travel() li.insert(2, 100) li.travel() li.insert(20, 200) li.travel() li.remove(9) li.travel() li.remove(200) li.travel() print(li.search(7))
05ded89c2cb4388c48c95445d888ee6169093545
CurtCalledBurt/MessingAround
/LeetCode_Challenges/find_duplicates.py
1,664
4.34375
4
# Given an array of integers, find if the array contains any duplicates. # Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct. def find_duplicates(array): # function that scans an array for duplicates that returns True if it contains duplicates and False if it does not. Also returns a dictionary with the duplicate elements of the array as keys and the total count of those duplicates in the original array as values. Duplicate-Count pairs. # we don't know the addresses of any of these elements, so to search for a duplicate of any of them would be an O(n) operation, doing that for every element in the array would then be an O(n**2) operation. We are going to convert this array to a set, an O(n) operation, in order to achieve an O(1) look up time, giving a total O(n) operation time. ht = set() duplicates = {} # store every element in the hashtable for elem in array: # add elem to duplicates if it already exists in ht if elem in ht: if elem not in duplicates: # when counting duplicates, we start at 2, because any duplicate occurs twice! duplicates[elem] = 2 else: duplicates[elem] += 1 ht.add(elem) return (len(duplicates) > 0), duplicates # Testing find_duplicates array = [1,2,3,4,5,6,7,8,9,1,1,1,1,1] print(find_duplicates(array)) array = [1,2,3,4,5] print(find_duplicates(array)) array = [1,2,3,4,5,6,7,8,9,1] print(find_duplicates(array)) array = [1,2,3,4,5,6,7,8,9,1,2,3,4,5,6,7,8,9,9,2,3,4,10] print(find_duplicates(array))
364fa06fafab06851c251014ce47a452eb8288ec
MinSu-Kim/python_tutorial
/mysql_tutorial/query/delete_query.py
952
3.59375
4
import pandas as pd from mysql.connector import Error from mysql_tutorial.coffee_sale.connection_pool import DatabaseConnectionPool from mysql_tutorial.query.fetch_query import query_with_fetchall2 def delete_product(sql, code): try: conn = DatabaseConnectionPool.get_instance().get_connection() cursor = conn.cursor() cursor.execute(sql, (code,)) conn.commit() except Error as error: print(error) finally: cursor.close() conn.close() if __name__ == "__main__": res = query_with_fetchall2("select code, name from product where code like 'C___'") columns_list = ['code', 'name'] df = pd.DataFrame(res, columns=columns_list) print(df) delete_sql = "delete from product where code = %s" delete_product(delete_sql, 'C004') for code, name in (query_with_fetchall2("select code, name from product where code like 'C___'")): print(code , " ", name)
a7784b5b8fc2ae6a4e56e8c45ee5b334c597c2df
mahmoud791/CPU-scheduler
/os_assignment/priority_queue.py
2,127
4.21875
4
from process import* # A simple implementation of Priority Queue # using Queue. class TimeQueue(object): def __init__(self): self.queue = [] # for checking if the queue is empty def isEmpty(self): return len(self.queue) == 0 # for inserting an element in the queue def put(self, data): self.queue.append(data) # for popping an element based on Priority def get(self): try: min = 0 for i in range(len(self.queue)): if self.queue[i].time_remaining < self.queue[min].time_remaining: min = i item = self.queue[min] del self.queue[min] return item except IndexError: print('index out of boundries ya 3ashry') exit() class SimpleQueue(object): def __init__(self): self.queue = [] # for checking if the queue is empty def isEmpty(self): return len(self.queue) == 0 # for inserting an element in the queue def put(self, data): self.queue.append(data) # for popping an element def get(self): if self.isEmpty(): print('queue is empty') else: item = self.queue[0] del self.queue[0] return item class PriorityQueue(object): def __init__(self): self.queue = [] # for checking if the queue is empty def isEmpty(self): return len(self.queue) == 0 # for inserting an element in the queue def put(self, data): self.queue.append(data) # for popping an element based on Priority def get(self): try: min = 0 for i in range(len(self.queue)): if self.queue[i].priority < self.queue[min].priority: min = i item = self.queue[min] del self.queue[min] return item except IndexError: print('index out of boundries ya 3ashry') exit()
9d2f0f9e0b65924f0f5d4b1d06c854702db942e9
edwinkuruvila/Calculator
/calcer.py
5,630
3.53125
4
from tkinter import * import operator root = Tk() root.title('Calculator') # Creates dict for operators and list for identifying operators ops = {'•': operator.mul, '/': operator.truediv, '+': operator.add, '_': operator.sub} expressions = ['/', '•', '_', '+'] # Creates entry box object e = Entry(root, width=30, borderwidth=5) def MD(type, rawS): entered = rawS # Checks for operator type in str while type in entered: for i in range(len(entered)): # Ignores i if str range out of bounds try: if entered[i] == type: expressionsL = [0] expressionsR = [] # Looks for other operators on the left and right of found operator for exp in expressions: if entered.rfind(exp, 0, i) != -1: expressionsL.append(entered.rfind(exp, 0, i)) if entered.find(exp, i+1) != -1: expressionsR.append(entered.find(exp, i+1)) closeL = max(expressionsL) entered = entered.replace('~', '-') # If there are no operators on the left of selected operator if closeL == 0: if expressionsR: closeR = (min(expressionsR)) middle = str( '%.2f' % (ops[type](float(entered[closeL:i]), float(entered[i+1:closeR])))) entered = (middle+entered[closeR:]) else: middle = str( '%.2f' % (ops[type](float(entered[closeL:i]), float(entered[i+1:])))) entered = (middle) # If there are operators on the left and right of selected operator elif expressionsR: closeR = (min(expressionsR)) middle = str( '%.2f' % (ops[type](float(entered[closeL+1:i]), float(entered[i+1:closeR])))) entered = (entered[:closeL+1]+middle+entered[closeR:]) # If there are no operators on the right of selected operator else: middle = str( '%.2f' % (ops[type](float(entered[closeL+1:i]), float(entered[i+1:])))) entered = (entered[:closeL+1]+middle) entered = entered.replace('~', '-') except: pass entered = entered.replace('-', '~') return entered def button_click(number): current = e.get() e.delete(0, END) e.insert(0, str(current) + str(number)) def button_clear(): e.delete(0, END) def button_equal(): # Changes minus to diff identifier for subtraction to allow negative operations final = e.get().replace('-', '_') # Cycles through for every operator for exp in expressions: final = (MD(exp, final)) e.delete(0, END) e.insert(0, final) # Define Buttons button_1 = Button(root, text='1', padx=40, pady=20, command=lambda: button_click(1)) button_2 = Button(root, text='2', padx=40, pady=20, command=lambda: button_click(2)) button_3 = Button(root, text='3', padx=40, pady=20, command=lambda: button_click(3)) button_4 = Button(root, text='4', padx=40, pady=20, command=lambda: button_click(4)) button_5 = Button(root, text='5', padx=40, pady=20, command=lambda: button_click(5)) button_6 = Button(root, text='6', padx=40, pady=20, command=lambda: button_click(6)) button_7 = Button(root, text='7', padx=40, pady=20, command=lambda: button_click(7)) button_8 = Button(root, text='8', padx=40, pady=20, command=lambda: button_click(8)) button_9 = Button(root, text='9', padx=40, pady=20, command=lambda: button_click(9)) button_0 = Button(root, text='0', padx=40, pady=20, command=lambda: button_click(0)) button_add = Button(root, text='+', padx=40, pady=20, command=lambda: button_click('+')) button_subtract = Button(root, text='-', padx=41, pady=20, command=lambda: button_click('-')) button_divide = Button(root, text='/', padx=41, pady=20, command=lambda: button_click('/')) button_mult = Button(root, text='*', padx=41, pady=20, command=lambda: button_click('•')) button_neg = Button(root, text='~', padx=40, pady=20, command=lambda: button_click('~')) button_clear = Button(root, text='Clear', padx=27.4, pady=20, command=button_clear) button_equal = Button(root, text='=', padx=91, pady=20, command=button_equal) # Put objects on the screen e.grid(row=0, column=0, columnspan=3, padx=10, pady=10) button_1.grid(row=3, column=0) button_2.grid(row=3, column=1) button_3.grid(row=3, column=2) button_4.grid(row=2, column=0) button_5.grid(row=2, column=1) button_6.grid(row=2, column=2) button_7.grid(row=1, column=0) button_8.grid(row=1, column=1) button_9.grid(row=1, column=2) button_0.grid(row=4, column=1) button_add.grid(row=4, column=2) button_clear.grid(row=4, column=0) button_mult.grid(row=5, column=0) button_divide.grid(row=5, column=1) button_subtract.grid(row=5, column=2) button_equal.grid(row=6, column=0, columnspan=2) button_neg.grid(row=6, column=2) root.mainloop()
957173c4e89667bab8d9b38798738af79fe0e627
jiaozhennan/python_demo
/cnur/sort_list.py
567
3.921875
4
# coding = utf-8 def sort_list(the_list): """ 取出列表内的最大值和最小值 列表 比较最大值 [4,2,7,1,9] [2,4,7,1,9] [2,4,7,1,9] [2,4,1,7,9] [2,4,1,7,9] """ for i in range(0, len(the_list)): for j in range(i+1, len(the_list)): #print(the_list) if the_list[i] > the_list[j]: #print(the_list) the_list[i], the_list[j] = the_list[j], the_list[i] return the_list if __name__ == '__main__': news = sort_list([2, 4, 7, 1, 9]) print(news)
573e522d033bc0decccd58b9972216f5fcd09faf
alittlefish128/workStar
/SecondDay/second.py
6,882
3.59375
4
# lst1=[1,'abc',[True,'hello'],3] # # print(lst1) # lst1.append('world') # print(lst1) # print('#################################') # u=lst1.pop(1) # print(u) # print(lst1) # print('#################################') # 最基础的操作 # print('abc') # print(100) # print(True) # print('abc',100) # print('-------------------------') # print(int('100')+100) # print('abc','def','hij',end='--',sep=',') # print('hello world') # i=100 # j=None # if j==None: # print('i不为空') #python是存粹的面向对象语言,比java还要存粹 # print(int('100')+200) # myint=int # print(myint('100')+200) # int=str # print(int('100')+'200') # True=1 # False=0 # b=None # 数据类型 # print(1e3) # int float str bool # 结构类型 # list tuple set map # 常用函数 # 工厂方法 # print(str(100)+'abc') # from datetime import * # print(datetime.now()) # 数学函数 # + - * / // % ** pow # print(2**3) # print(pow(2,3)) # 位运算 # & | ^ << >> # print(10>>2) #逻辑运算 # and or not # if not age>19 and ssex='男': # print('true') # else: # print('false') # 系统的内置函数 # i=100 # print(type(True)) # <class 'int'> # <class 'bool'> # print(isinstance(bool(1),bool)) # i=0 # i+=1 # i-=3 # i*=4 i=i*4 # i//=5 i=i//5 i/=3 i|=3 # i=j=k=10 i,j=10,20 # def getInfo(): # return 'hello','world','abc' # a,b,c=getInfo() # print(a) # print(b) # print(c) # i,j=5,6 # i,j=j,i # a,b,c=1,1,2 # a,b,c=b,c,b+c # 控制语句 # mk=int(input('请输入均分')) # if mk>90: # i='优秀' # elif mk>80: # i='良好' # else: # i='差' # 循环 # while循环和for循环 # s,i=0,0 # while i<=100: # s,i=s+i,i+1 # print(s) # break和continue # i=0 # while i<100: # i+=1 # if i%2==0: # continue # print(i) # for i in range(1,100,2): # print(i) # for i in 'hel lo': # print(i) # 可迭代器:序列sequence # print(range(1,100)) # for i,j in zip([0,2,4,8],'abcde'): # print(i,j) def abc(): print("This is abc") # lst=[1,True,abc,'hello',5] # print(lst) # print('----------------------------') # for unit in lst: # print(unit) # lst1=list('abc') # print(lst1) #切片 # i=list('abcdefhijk') # print(i[2]) # print(i[2:5]) # print(i[2:]) # print(i[:5]) # print(i[:]) # print(i[2::2]) # print(i[-3:]) # print(i[-1]) # print(i[-1:-3]) # print(i[2:7:2]) # print(i[7:2:-1]) # print(i[::-1]) # ['a','b','c','d','h','i','j','k'] # 深拷贝和浅拷贝 # 关于引用 # i=100 # j=50 # print(id(i)) # print(id(j)) # s='abc' # print(id(s)) # s+='d' # print(id(s)) # 任何操作系统中,任何语言中,连续字符串具备"不变性" # s='' # for i in range(10000): # s+=str(i) # String类,StringBuffer类和StringBuilder类有什么区别? # i=100 # print(id(i)) # i+=1 # print(id(i)) # lst1=[1,2,3] # print(id(lst1)) # lst1.append(4) # print(id(lst1)) # del lst1[0] # print(id(lst1)) # print('hello'[1:4]) # lst1=[10,True,'hello'] # lst2=lst1 # lst1[0]=200 # print(lst2) # python解释器在运行时需要加载基础类和基础库 # 那么python有那么多的类库,以及互联网中不断提交的新的功能类和库 # python不能在解释器开始运行前将所有的类库都实现加载 # 那样会导致解释器臃肿和占用海量内存,效率变得非常低下 # 所以python和java一样,默认仅仅加载最常用的基础类 # 而其他的类库,则是什么时候用到,什么时候请编码者自己用import语句将其 # 导入内存 # import copy # lst1=[10,'abc',True] # lst2=copy.deepcopy(lst1) # lst1[0]=20 # print(lst1) # print(lst2) # import copy # lsta=[1,2,3] # lstx=['hello',lsta] # lsty=copy.deepcopy(lstx) # lstx[1][1]=20 # print(lstx) # print(lsty) # print(lstx[0][0]) # 切片不仅仅操作列表,可以操作任意可迭代元素 # lst1=[1,2,3] # # lst2=['a'] # lst3=lst1+['a'] # print(lst3) # print(lst3*3) # lst1=[1,'ab',True] # i=False # print(i not in lst1) # in和not in同样不仅仅针对列表,可以对任意可迭代元素进行操作 # print('e' in 'hallo') # print(150 in range(1,120)) # 列表的内置函数: # print(cmp([10,20,30],[6,22,33])) # 字符串本身是可迭代查询元素 # 所有可迭代元素都可以通过[]进行查找和切片 # print(len('abc')) # print(len([1,2,3,[4,10],5,60])) # lst1=[1,20,33,2,4] # lst2=list(reversed(lst1)) # print(lst2) # lst1=['中国','上海','北京'] # lst3=sorted(lst1,reverse=True) # print(lst3) # lst4=sorted(lst1,reverse=False) # print(lst4) # print(max(lst1),min(lst1),sum(lst1)) # print(max(lst1)) # 汉语拼音的顺序排列的字母编码 # 列表生成式,现在学习的第二个表达式,第一个是三元表达式 # lst=[] # for i in range(0,101): # if i%2==1: # lst.append(i) # print(lst) # lst=[i**2 for i in range(0,11) if i%2==1] # print(lst) # names=['张三','李四','王五','马六'] # fruits=['梨子','苹果','樱桃'] # 请快速的生成一个列表,列表中的元素为'张三喜欢吃梨子','李四喜欢吃苹果'.. # 最后打印这个列表 # lst=[names[i]+'喜欢吃'+fruits[i] for i in range(0,3)] # print(lst) # lst=[name+'喜欢吃'+fruit for name,fruit in zip(names,fruits)] # print(lst) # lst=[name+'喜欢吃'+fruit for name in names for fruit in fruits] # print(lst) # lst=[str(j)+'*'+str(i)+'='+str(i*j) for i in range(1,10) for j in range(1,i+1)] # print(lst) # for i in range(1,10): # print([str(j)+'*'+str(i)+'='+str(i*j) for j in range(1,i+1)]) # for i in range(1,10): # print('\t'.join([str(j)+'*'+str(i)+'='+str(i*j) for j in range(1,i+1)])) # [print('\t'.join([str(j)+'*'+str(i)+'='+str(i*j) for j in range(1,i+1)])) for i in range(1,10)] # 字符串具有不变性 # i='abc' # j='ab' # j=j+'c' # k='ab'+'c' # print(id(i),id(j),id(k)) # i==k != j # 这里的结果和java完全保持一致 # 静态缓冲池 # 先编译再执行 # 而编译在做什么? # 1:语法检查 # 2:常量对象的构建 # 3:将文字翻译成二进制 # String s1="hello"; # String s2="world"; # String s3="hello"+"world"; # String s4=s1+st2; # String s5="helloworld"; # print(s3==s4) # print(s5==s4) # print(s3==s5) # i=100 # print(i.bit_length()) # i=100000 # print(i.bit_length()) # 所有的对象都可以通过.来进行寻址 # i=100 # python一切皆是对象 # print('hello world'.count('o')) # s='hello world' # print(s.upper()) # 3&4 1==1 and 2>1 # 位运算和逻辑运算不要弄混淆 # ip1='192.168.11.33' # mask1='255.255.254.0' # def getNetId(ip,mask): # return '.'.join([str(int(a)&int(b)) for a,b in zip(ip.split('.'),mask.split('.'))]) # def getNetId(ip,mask): # lst=[] # for a,b in zip(ip.split('.'),mask.split('.')): # lst.append(str(int(a)&int(b))) # return '.'.join(lst) # print(getNetId(ip1,mask1)) # python基础解释器,没有互联网中各个工程师后期编写的库函数 # pip install numpy lst=[1,2,3,4,5] print(sum(lst))
0f193de9689e96b67cd9a5dbec7a6b3c1d59fb32
melodist/CodingPractice
/src/HackerRank/Components in a graph.py
1,091
3.75
4
""" https://www.hackerrank.com/challenges/components-in-graph/problem """ def componentsInGraph(queries): def find_set(root: int, array: list) -> int: if array[root] == root: return root else: return find_set(array[root], array) n = len(queries) nodes_count = 2*n+1 root = [0] * nodes_count count = [0] * nodes_count for i in range(1, nodes_count): root[i] = i count[i] = 1 for query in queries: a, b = query # find root of a & b a_root = find_set(a, root); b_root = find_set(b, root) if a_root == b_root: continue # union without ranking root[b_root] = a_root count[a_root] += count[b_root] count[b_root] = 0 # find min and max smallest, biggest = nodes_count, -1 for i in range(1, nodes_count): if count[i] > biggest: biggest = count[i] if count[i] > 1 and count[i] < smallest: smallest = count[i] return [smallest, biggest]
4f6311088a485a1bc76c4ea42d61bc71b259f47d
amanagrawal5510/Computer-Vision-Projects
/Computer Vision With Open CV_/04-Object-Detection/Contor_detection.py
1,961
3.515625
4
# Contour Detection # External vs Internal Contours import cv2 import numpy as np import matplotlib.pyplot as plt img = cv2.imread('../DATA/internal_external.png',0) img.shape plt.imshow(img,cmap='gray') # ============================================================================= # findContours # # function will return back contours in an image, and based on the RETR method called, you can get back external, internal, or both: # # 1. cv2.RETR_EXTERNAL:Only extracts external contours # 2. cv2.RETR_CCOMP: Extracts both internal and external contours organized in a two-level hierarchy # 3. cv2.RETR_TREE: Extracts both internal and external contours organized in a tree graph # 4. cv2.RETR_LIST: Extracts all contours without any internal/external relationship # ============================================================================= contours, hierarchy = cv2.findContours(img, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_SIMPLE) type(contours) len(contours) type(hierarchy) hierarchy.shape hierarchy # Draw External Contours # Set up empty array external_contours = np.zeros((652, 1080)) # For every entry in contours for i in range(len(contours)): # last column in the array is -1 if an external contour (no contours inside of it) if hierarchy[0][i][3] == -1: # We can now draw the external contours from the list of contours cv2.drawContours(external_contours, contours, i, 255, -1) plt.imshow(external_contours,cmap='gray') # Create empty array to hold internal contours image_internal = np.zeros((652, 1080)) # Iterate through list of contour arrays for i in range(len(contours)): # If third column value is NOT equal to -1 than its internal if hierarchy[0][i][3] != -1: # Draw the Contour cv2.drawContours(image_internal, contours, i, 255, -1) plt.imshow(image_internal,cmap='gray')
11d3036be6fe68b2008b0cd8fd0c6e568104cd3b
lanxingjian/Learn-Python-the-Hard-Way
/ex35-2.py
750
3.875
4
def cthulhu_room(): print "Here you see the great evil Cthulhu." print "He, it, whatever stares at you and you go insane." print "Do you flee for your life or eat your head?" next == raw_input("> ") if "flee" in next: start() elif "head" in next: dead("Well that was tasty!") else: cthulhu_room() def dead(why): print why, "Good job!" exit(0) def start(): print "You are in a dark room." print "There is a door to your right and left." print "Which one do you take?" next = raw_input("> ") if next == "left": bear_room() elif next == "right": cthulhu_room() else: dead("You stumble around the room until you starve.") start()
bddd4a59fb51c8163d9a8be8e80aba2327308f6d
vikas-t/practice-problems
/functional-problems/spiralTreePrint.py
1,265
4.59375
5
#!/usr/bin/python3 # https://practice.geeksforgeeks.org/problems/level-order-traversal-in-spiral-form/1 # Again the simplest solution is to do a level order traversal and for every # height keep changing the direction of printing the list def printSpiralLevelOrder(root): """ Fetch the height and for every height print the left and right leaf nodes This is also the way to do the level order traversal without aux space Worst case complexity of this recursive approach: Worst case time complexity of the above method is O(n^2). Worst case occurs in case of skewed trees. """ reverse = True height = getHeight(root) for h in range(1, height+1): printLevel(root, h, reverse) reverse = not(reverse) def printLevel(root, level, reverse): if root==None: return if level == 1: print(root.data, end=" ") elif level > 1: if reverse: printLevel(root.right, level-1, reverse) printLevel(root.left, level-1, reverse) else: printLevel(root.left,level-1, reverse) printLevel(root.right, level-1, reverse) def getHeight(root): if not root: return 0 return 1 + max(getHeight(root.left), getHeight(root.right))
01d3de6bc6f67869dcd817942e2df998d91ee37b
lorryzhai/test7
/oh-my-python-master/oh-my-python-master/target_offer/010-斐波那契数列/变态青蛙跳.py
1,178
3.640625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2017/12/30 22:00 # @Author : WIX # @File : 变态青蛙跳.py """ 一只青蛙一次可以跳上1级台阶,也可以跳上2级……它也可以跳上n级。求该青蛙跳上一个n级的台阶总共有多少种跳法。 f(0) = 1 f(1) = 1 f(2) = f(2-1) + f(2-2) f(3) = f(3-1) + f(3-2) + f(3-3) ... f(n) = f(n-1) + f(n-2) + ... + f(n-(n-1)) + f(n-n) 简单的解释一下:例如f(3-1)表示3阶跳了1阶后,剩下的跳阶方法数,f(3-2)表示3阶跳了两阶后剩下的跳阶方法数,以此类推,直到一次跳n阶后,剩下的跳阶方法数。 现在问题明了了很多,但是还不够,我们可以继续对其进行分解: 因为 : f(n) = f(n-1) + f(n-2) + ... + f(n-(n-1)) + f(n-n) = f(0) + f(1) + f(2) + ... + f(n-2) + f(n-1) 所以 : f(n-1) = f(0) + f(1) + ... + f((n-1)-1) = f(0) + f(1) + f(2) + ... + f(n-2) 则: f(n) = f(n-1) + f(n-1) = 2*f(n-1) """ class Solution(object): def biantai(self, n): result = 1 if n >= 2: for i in range(n - 1): result = 2 * result return result s = Solution() print(s.biantai(5))
c18a930dbc97e3b19749780d1edc88c3207d5d4c
rafaelperazzo/programacao-web
/moodledata/vpl_data/303/usersdata/294/78072/submittedfiles/testes.py
143
3.875
4
# -*- coding: utf-8 -*- #COMECE AQUI ABAIXO a= int(input('Digite a: ')) b= int(input('Digite b: ')) soma= a+b if soma>10: print(soma)
edea834718e3e1ac8c0317cb9fffce4d47d9e676
YauheSh/bh_5_tasks-master
/medium/common_numb.py
485
4.25
4
""" Написать функцию common_numbers, которая принимает 2 списка, которые содержат целые числа. Функция должна вернуть список общих чисел, который отсортирован по убыванию """ def common_numbers(first: list, second: list) -> list: common_list = first + second return sorted(common_list, reverse=True) print(common_numbers([4, 2, 3], [1, 2, 3]))
f58e3ecee002aad173d6bfeda939c377f5dca843
SpooderManEXE/Hacktoberfest2020-Expert
/Python Programs/MinimumAndMaximum
242
3.578125
4
my_dict = {'x':500, 'y':5874, 'z': 560} key_max = max(my_dict.keys(), key=(lambda k: my_dict[k])) key_min = min(my_dict.keys(), key=(lambda k: my_dict[k])) print('Maximum Value: ',my_dict[key_max]) print('Minimum Value: ',my_dict[key_min])
c9bef3aac3de00c55c76cef0c10df4b3d703196f
WIT-Casino/MainProject
/Games/Roulette_sim.py
1,628
3.765625
4
import random def Roulette(): """Roullette game""" bet = [5,10,15,20,25,30,35,40,45,50,55,60,65,70,75,80,85,90,95,100,1000] i =1 red =[1,3,5,7,9,12,14,16,18,21,23,25,27,30,32,34,36] black = [2,4,6,8,10,11,13,15,17,19,20,22,24,26,28,29,31,33,35] green = 0 even = [2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36] odd = [1,3,5,7,9,11,13,15,17,19,21,23,25,27,29,31,33,35] player= 0 #print('____________________________________________________________') #print('Red=1, Black=2, Green=3, Odd=4, Even=5') player = random.randint(1,5) # print('____________________________________________________________') #print('you bet:',player) #print('____________________________________________________________') spin = random.randint(0,36) #print('Landed on: ',spin) #print('____________________________________________________________') ranBet= random.choice(bet) winnings = ranBet*2 # winningsG = ranBet*35 betR = ranBet if player==1: if spin in red: return 1 else: return 0 elif player==2: if spin in black: return 1 else: return 0 elif player==3: if spin == green: return 1 else: return 0 elif player==4: if spin in odd: return 1 else: return 0 elif player==5: if spin in even: return 1 else : return 0 #print('__________________________________________________________')
f389a2374f9ea8df3e05508e2457e49c5770ef1c
brogan-avery/MyPortfolio-AndExamples
/Data Structures/Queues/PriorityQueues/priorityQueueDriver.py
1,610
4.03125
4
""" *************************************************************** * Title: Priority Queues * Author: Brogan Avery * Created : 2021-03-05 * Course: CIS 152 - Data Structure * Version: 1.0 * OS: macOS Catalina * IDE: PyCharm * Copyright : This is my own original work based on specifications issued by the course instructor * Description : An app that demos list based priority queues * Academic Honesty: I attest that this is my original work. * I have not used unauthorized source code, either modified or * unmodified. I have not given other fellow student(s) access * to my program. *************************************************************** """ from priorityQueue import PriorityQueue # MAIN-------------------------------------------------------------------- if __name__ == '__main__': # node data jobNum1 = 1111 jobNum2 = 1112 jobNum3 = 1113 jobNum4 = 1114 jobNum5= 1115 jobNum6 = 1116 jobNum7 = 1117 jobNum8 = 1118 jobNum9 = 1119 # priority levels p1 = 'A' p2 = 'B' p3 = 'C' p4 = 'D' jobList = PriorityQueue() # add jobs to list jobList.enqueue(jobNum1, p2) jobList.enqueue(jobNum2, p2) jobList.enqueue(jobNum3, p2) jobList.enqueue(jobNum4, p4) jobList.enqueue(jobNum5, p4) jobList.enqueue(jobNum6, p4) jobList.enqueue(jobNum7, p4) jobList.enqueue(jobNum8, p1) jobList.enqueue(jobNum9, p1) jobList.print_queue() jobList.dequeue() print("\nAfter dequeue:") jobList.print_queue() jobList.dequeue() print("\nAfter dequeue again:") jobList.print_queue()
4b84cd0018446d4558151a89d1b19ea4e58bb953
Leiasa/Bioinformatics
/1PatternCounter.py
558
3.609375
4
#problem 1 #Pattern Matching #Finds all of the occurences of a pattern in a string Genome = '' Pattern = '' lenGenome = len(Genome) lenPattern = len(Pattern) output = '' currentPat ='' x = 0 for i in range (0, (lenGenome - lenPattern +1)): currentPat = Genome[i] x = i + 1 for y in range (0,lenPattern-1): currentPat = currentPat + Genome[x] if str(currentPat) == Pattern: index = i output = output + str(index) + ' ' x = x + 1 y = y + 1 currentPat = '' i = i + 1 print output
88b4240de55c18c494d79d2b46e8bce0a027c82a
ppanero/coding-challenges
/hackerrank/greedy_algorithms/get_minimum_cost.py
749
3.921875
4
#!/bin/python3 """ Given a list of prices of the flowers and a number of buyers, calculate the minimum cost possible taking into account the cost of each flower is: (#flowers already bought + 1) * cost of the flower """ def get_minimum_cost(k, c): c.sort(reverse=True) cost = sum(c[:k]) bought_counter = 0 for idx, flower_cost in enumerate(c[k:], start=k): curr_counter = idx // k if bought_counter < curr_counter: bought_counter = curr_counter cost += (bought_counter + 1) * flower_cost return cost if __name__ == '__main__': nk = input().split() n = int(nk[0]) k = int(nk[1]) c = list(map(int, input().rstrip().split())) print(get_minimum_cost(k, c))
87078f877823cc0a342c5601ce26526de4deda16
tafiaalifianty/Digital-Signature
/src/RSA.py
2,034
3.515625
4
from utils import * def generate_key(size): #pembangkitan kunci publik dan privat seukuran size bits #input: ukuran kunci #output: pasangan (d, e, n) kunci p = get_new_prime(size) q = get_new_prime(size) n = p*q totient = (p-1) * (q-1) e = random.randint(1, totient) while(gcd(e, totient) != 1): e = random.randint(1, totient) for k in range(1, totient): if((e * k) % totient == 1): break d = k key = (int(d), e, n) return(key) def encrypt(key, message): #enkripsi pesan dengan algoritma RSA #input: key adalah kunci pasangan nilai, pesan adalah plain #output: cipher berupa hex string publicKey, n = key result = [] plain = [] for i in message: ascii_code = '' for j in range(len(str(ord(i))), 3): ascii_code = '0' + ascii_code ascii_code += str(ord(i)) plain.append(ascii_code) plain = list(chunkstring("".join(plain), len(str(n))-1)) for x in plain: cipher = pow(int(x), publicKey, n) cipher_code = '' for i in range(len(format(cipher, 'x')), 4): cipher_code = '0' + cipher_code cipher_code += format(cipher, "x") result.append(cipher_code) return("".join(result)) def decrypt(key, message): #dekripsi pesan dengan algoritma RSA #input: key adalah kunci pasangan nilai, pesan adalah cipher (hex string) #output: plain string private, n = key cipher = list(chunkstring(message, 4)) message = [] for x in cipher: ascii_code = int(x, 16) plain = pow(ascii_code, private, n) plain_code = '' for i in range(len(str(plain)), len(str(n))-1): plain_code = '0' + plain_code plain_code += str(plain) message.append(plain_code) message = "".join(message) message = list(chunkstring(message, 3)) result = '' for k in message: result += chr(int(k)) return(result)
450cc6ae38c5c6a003a5cde2fbc3bccb2729ca50
jsutch/Python-Algos
/tictactoe.py
5,630
4.09375
4
# -*- coding: utf-8 -*- import os, random import pdb def draw(board): """ Draw a board from a board array """ os.system('clear') print(' | |') print((' ' + board[7] + ' | ' + board[8] + ' | ' + board[9])) print(' | |') print('-----------') print(' | |') print((' ' + board[4] + ' | ' + board[5] + ' | ' + board[6])) print(' | |') print('-----------') print(' | |') print((' ' + board[1] + ' | ' + board[2] + ' | ' + board[3])) print(' | |') def newboard(): """ return a new board as a list """ return [' ' for x in range(10)] def setmark(): """ Who takes X or O? """ print('Do you want to be X or O?') print('default is X') letter = input("Type X, O or press enter: ").upper() if letter == 'O': return ['O', 'X'] return ['X', 'O'] def firstmove(name='Nimrod'): """ Randomize who goes first """ if random.randint(0,1) == 0: # if random.randint(0,10) < 9: # computer probably goes first return 'computer' return 'player' def replay(): """ restart game """ # print('Inplay is set to: ',inplay) # debugger if input('Great game! Want to play again? (y/n q)').lower().startswith('y'): newgamevars() return def winner(b, l): """ winning moves: top row, middle row bottom row left column, middle column, right column top diagonal, bottom diagonal """ return ((b[7] == b[8] == b[9] == l) or #horz (b[4] == b[5] == b[6] == l) or #horz (b[1] == b[2] == b[3] == l) or #horz (b[1] == b[5] == b[9] == l) or #diag (b[7] == b[5] == b[3] == l) or #diag (b[7] == b[4] == b[1] == l) or #vert (b[8] == b[5] == b[2] == l) or #vert (b[9] == b[6] == b[3] == l)) #vert def boardcopy(board): """ utility for testing array overwrites """ return board.copy() def spacefree(board, move): """ Check for free space on board """ if isinstance(move, int): return board[move] == ' ' else: return "Space is taken. Need a number between 1-9" def randommove(board, moveslist): """ random move for computer """ possiblemove = [] for i in moveslist: if spacefree(board, i): possiblemove.append(i) def boardfull(board): """ returns True or False if there are no spaces on board """ return False if ' ' in board[1:] else True def movesleft(board): """ returns an array of move numbers """ moves = [] for i in range(1, 10): if ' ' in board[i]: moves.append(i) return moves def getcomputermove(board): """ returns a random choice as integer """ if not boardfull(board): return random.choice(movesleft(board)) def computermove(board): """ make the computer's move """ makemove(board, getcomputermove(board), computertoken) def getplayermove(board): """ get the player's move - integer 1-9 """ intarr=[1,2,3,4,5,6,7,8,9] rawmove = input("What's your next move? 1-9, q: ") if rawmove.isdigit() and int(rawmove) in intarr: move = int(rawmove) if move and spacefree(mainboard, move): return move elif move == 'q': print('Quitting') os._exit(0) else: print('Need a digit for an unused space between 1-9 or q') return getplayermove(mainboard) else: print('Need a digit for an unused space between 1-9 or q') return getplayermove(mainboard) def makemove(board, move, token): """ Helper to make moves """ if inplay == False or isinstance(move, int) == False: print('MainMove: Something went wrong. Move was:', move, type(move)) os._exit(666) elif isinstance(move, int) and spacefree(board, move): board[move] = token return draw(board) return draw(board) def otherguy(): """ Helper to change players during turns """ if turn == 'player': return 'computer' return 'player' def outcome(board, player): """ a dict called belligerants has to be created to map the player to the token belligerants = {'player': 'X','computer':'O'}. this will take belligerants[turn] to for the winner/tie/scoring phase """ global turn global inplay if winner(board, belligerants[player]): draw(board) print(f"{player} has won the game") inplay = False replay() elif boardfull(board): draw(board) print("game is a tie!") inplay = False replay() else: turn = otherguy() def newgamevars(): global playertoken, computertoken, belligerants, turn, mainboard, inplay playertoken, computertoken = setmark() belligerants = {'player': playertoken,'computer':computertoken} turn = firstmove() mainboard = newboard() inplay = True def main(): global turn global mainboard global inplay while inplay: if turn == 'player': draw(mainboard) move = getplayermove(mainboard) makemove(mainboard, move, playertoken) outcome(mainboard, turn) elif turn == 'computer': computermove(mainboard) outcome(mainboard, turn) if __name__ == "__main__": print("Ok - let's play a new game") newgamevars() while True: if inplay == True: main() else: print('Game Over') break
13ffd72945430e9bd9194465441c14234c9c9446
Felhaba/K-means_clustering_Coursera
/worldbank_&_banknotes.py
6,696
3.671875
4
#!/usr/bin/env python # coding: utf-8 # In[2]: import pandas as pd data = pd.read_csv('worldbank_data') #function to upload the data (in brackets use tab button) #data # just printing the name results in a cool table data.sort_values('avg_income', inplace=True) #I want my DataFrame to change as a result of sorting it whereas, otherwise, it will just return the sorted version. #I'm going to pass this argument here ‘inplace’ and set it to True. #So, that means the data itself is going to be affected and we're not just going to get a copy of it. # In[3]: import numpy as np richest = data[data['avg_income'] > 15000] #all the countries with the income > 15000 richest.iloc[0] # to pull out a row rich_mean = np.mean(richest['avg_income']) all_mean = np.mean(data['avg_income']) plt.scatter(richest['avg_income'], richest['happyScore']) for k, row in richest.iterrows(): plt.text(row['avg_income'], row['happyScore'], row['country']) # In[4]: happy = data['happyScore'] # data.happyScore income = data['avg_income'] print(happy, income) # In[8]: import matplotlib.pyplot as plt plt.xlabel('income, USD') plt.ylabel('happy') plt.scatter(income, happy, s = 50, alpha = 0.25) # In[30]: # K-means analysis from sklearn.cluster import KMeans import numpy as np # to work with the data income_happy = np.column_stack((income, happy)) #as in k-means library there is no way to insert 2 separate datasets # to determine the clusters, so one need to join them using _slack #print(income_happy[:5]) kmeans = KMeans(n_clusters=3).fit(income_happy) # to fit the data in 3 clusters kmeans.cluster_centers_ # to determine the coordintes of the centres y_kmeans = kmeans.predict(income_happy) # predict the group for each pair income-happy plt.xlabel('average income, USD') plt.ylabel('happiness') plt.scatter(income_happy[:, 0], income_happy[:, 1],c = y_kmeans, s = 100, alpha = 0.25) # In[100]: import pandas as pd data = pd.read_csv('worldbank_data') #function to upload the data (in brackets use tab button) data import numpy as np data_draw = data[['GDP', 'adjusted_satisfaction', 'country']].sort_values('GDP') last = data_draw.iloc[-1] #max GDP first = data_draw.iloc[0] #min GDP plt.scatter(data_draw['GDP'], data_draw['adjusted_satisfaction'], alpha = 0.5) #initial plot with the satis = f(GDP) plt.xlabel('GDP, bln USD') plt.ylabel('Satisfaction') # it appeared that level of satisfaction as expected proportional to the level of GDP plt.text(last[0], last[1], last[2], c= 'green') # max plt.text(first[0], first[1], first[2], c = 'red') # min plt.show() # 1) the choice of the columns was arbitrary (I thought, that the wealther country sholud have higher satisfaction) # 2) the data was sorted by GDP, so from min to max # 3) then the lowest and the highest GDP countries were marked with text => there is a clear pattern as expected, # however, the poorest country is not the most unsatisfied # In[102]: gdp = data['GDP'] satis = data['adjusted_satisfaction'] from sklearn.cluster import KMeans import numpy as np # to work with the data satis_gdp = np.column_stack((gdp, satis)) #as in k-means library there is no way to insert 2 separate datasets # to determine the clusters, so one need to join them using _slack #print(income_happy[:5]) kmeans = KMeans(n_clusters=3).fit(satis_gdp) # to fit the data in 3 clusters kmeans.cluster_centers_ # to determine the coordintes of the centres y_kmeans = kmeans.predict(satis_gdp) # predict the group for each pair income-happy plt.xlabel('GDP, bln USD') plt.ylabel('Satisfaction') plt.scatter(satis_gdp[:, 0], satis_gdp[:, 1],c = y_kmeans, s = 100, alpha = 0.25) plt.text(last[0], last[1], last[2], c= 'green') # max plt.text(first[0], first[1], first[2], c = 'red') # min plt.show() # # Banknotes project # In[ ]: import numpy as np #for data import pandas as pd # for statistics import matplotlib.pyplot as plt # for the chart import matplotlib.patches as patches # to lay over another chart (like oval of the std in this case) data = pd.read_csv('Banknote-authentication-dataset-.csv') data # V1 - variance of the transformed image (deviation from the mean) # V2 - skewness of the transformed image (how far and where is the peak shifted) len(data) #1372 observations ## statistical features ## # mean multidim_mean = np.mean(data, 0) #0 for column mean and 1 for the each row mean # std multidim_std = np.std(data, 0) print(round(multidim_mean, 3), round(multidim_std, 3)) ## ellipse ellipse_1 = patches.Ellipse([multidim_mean[0], multidim_mean[1]], multidim_std[0]*2, multidim_std[1]*2, alpha = 0.4, color = 'red') ellipse_2 = patches.Ellipse([multidim_mean[0], multidim_mean[1]], multidim_std[0]*4, multidim_std[1]*4, alpha = 0.4, color = 'purple') fig, graph = plt.subplots() ## plot the V1 = f(V2) ## plt.xlabel('V1') plt.ylabel('V2') plt.scatter(data['V1'], data['V2'], alpha = 0.25) #only by plotting this chart one may distinguish like 3 clusters # if counted horizontally (like layers) #add std_dev oval plt.scatter(multidim_mean[0], multidim_mean[1]) # centre of the oval #graph.add_patch(ellipse_1) #graph.add_patch(ellipse_2) #### df = pd.DataFrame({'V1': data['V1'], 'V2': data['V2']}) df[(df.V1 > 2*multidim_std[0]) & (df.V2 > 2*multidim_std[1])].count() df[df.V1 > 2*multidim_std[0]].count() df[df.V2 > 2*multidim_std[1]].count() # In[ ]: ## k-means clustering ## from sklearn.cluster import KMeans import numpy as np # to work with the data #v1_v2 = np.column_stack(data['V1'], data['V2']) #as in k-means library there is no way to insert 2 separate datasets # to determine the clusters, so one need to join them using _slack kmeans = KMeans(n_clusters=2, n_init = 2, max_iter = 20).fit(data) # to fit the data in 3 clusters clusters = kmeans.cluster_centers_ # to determine the coordintes of the centres n_iterations = kmeans.n_iter_ labels = kmeans.labels_ #with 2 clusters lable 0 or 1 is assigned y_kmeans = kmeans.predict(data) # predict the group for each pair income-happy plt.xlabel('V1, standard deviation') plt.ylabel('V2, skewness') plt.scatter(data['V1'], data['V2'], c = y_kmeans, s = 50, alpha = 0.2) plt.scatter(clusters[:, 0], clusters[:, 1], c = 'blue', s = 70, alpha = 0.8) plt.show() n_iterations # number of iterations before assigning to the cluster clusters # In[ ]: from sklearn.metrics import accuracy_score data_full = pd.read_csv('full_banknotes.csv') labels2 = labels + 1 # as in the data 'Class' has either 1 or 2 lables #final = np.column_stack((data_full['Class'], labels2)) score = accuracy_score(data_full['Class'], labels2) print(round(score, 3))
486e13b72435f750074a1659aff22bf166c5efe0
ClaudioCarvalhoo/you-can-accomplish-anything-with-just-enough-determination-and-a-little-bit-of-luck
/problems/AE113.py
468
3.796875
4
# Quick Sort # O(n*log(n)) average case # n = len(array) def quickSort(array): helper(array, 0, len(array)-1) return array def helper(array, start, end): if start == end or start > end: return pivot = end i = start for j in range(start, pivot): if array[j] < array[pivot]: swap(array, i, j) i += 1 swap(array, i, pivot) helper(array, start, i-1) helper(array, i+1, end) def swap(array, i, j): array[i], array[j] = array[j], array[i]
49290e1530bbeaa0432db3ba48a7c15a9ba24138
FriendlyUser/Python
/Basic Math/DistBewteenPoints.py
852
4.28125
4
# David Li # August 18, 2015 # This program will find the distance bewteen two points import math class point(object): def __init__(self, x,y): #define x and y variables self.X= x self.Y = y def __str__(self): return ("Point(%s,%s)"%(self.X, self.Y)) print("This program will calculate the distance bewteen given points. ") while True: try: p1= point(float(input("Enter the x1: ")),float(input("Enter y1: "))) p2 = point(float(input("Enter the x2: ")),float(input("Enter the y2: "))) break except ValueError: print("Mistake") continue except TypeError: print("Enter x,y coordinate: ") continue d = math.sqrt((p2.X-p1.X)**2 +(p2.Y-p1.Y)**2) print("The distance bewteen Point1" + str(p1) + "and Point2 " + str(p2) + " is %.2f" % d)
1a89dce3de231b16fc07e876d000a7c8edbc0d46
CorSar5/Python-Exercises-115-World3
/exercícios 72-115/ex093.py
706
3.6875
4
print(' ==ANÁLISE DE JOGADORES==') print('='*40) jogador = dict() partidas = list() jogador['Nome'] = str(input('Nome do Jogador: ')) f = int(input(f'Quantas partidas {jogador["Nome"]} jogou? ')) for c in range(0, f): partidas.append(int(input(f' Quantos golos marcou na {c+1}ª partida? '))) jogador['Golos'] = partidas[:] jogador['total'] = sum(partidas) print('='*40) print(jogador) print('='*40) for k, v in jogador.items(): print(f'O campo {k} tem o valor {v}') print('='*40) print(f'O jogador {jogador["Nome"]} jogou {f} partidas.') for i, v in enumerate(jogador['Golos']): print(f' => Na partida {i}, fez {v} golos.') print(f'Foi um total de {jogador["total"]} golos.')
138d4d2caacb8e67a9fa3edd32aef13c655cbfa3
JorgeTowersmx/python2020
/variables.py
389
4
4
#Data types #String #cuando queremos sacar un elemento de un string podemos usar subscript ""Hello"[0] print("Hello"[0]) print("Hello"[1]) print("Hello"[2]) print("Hello"[3]) print("Hello"[4]) print("Hello") print("123"+"456") #Integer print(123 + 456) 1_000_000 1000000 print(1_000_000 + 1_000_000) print(1000000 + 1000000) #Float 3.141516 #Boolean True False
19c8da06331b9f7f4be85fb51e71c265bdaa7a8f
alabugevaaa/hw22
/main.py
2,692
4.09375
4
# -*- coding: utf-8 -*- class Animal: hunger = 'hungry' voice = '' def __init__(self, name, weight): self.name = name self.weight = weight def feed(self): self.hunger = 'full' print(f'{self.name}: покормили!') def voices(self): print(self.voice) def __gt__(self, other): return self.weight > other.weight def __add__(self, other): return Animal('',self.weight + other.weight) def __radd__(self, other): if other == 0: return self else: return self.__add__(other) class Milk: def get_milk(self): print(f'{self.name}: подоили!') class Egg: def get_eggs(self): print(f'{self.name}: собрали яйца!') class Wool: def get_wool(self): print(f'{self.name}: постригли!') class Goose(Animal, Egg): def __init__(self, name, weight): super().__init__(name, weight) self.voice = 'Га!' class Cow(Animal, Milk): def __init__(self, name, weight): super().__init__(name, weight) self.voice = 'Муу!' class Sheep(Animal, Wool): def __init__(self, name, weight): super().__init__(name, weight) self.voice = 'Бее!' class Chiken(Animal, Egg): def __init__(self, name, weight): super().__init__(name, weight) self.voice = 'Ко!' class Goat(Animal, Milk): def __init__(self, name, weight): super().__init__(name, weight) self.voice = 'Бее!' class Duck(Animal, Egg): def __init__(self, name, weight): super().__init__(name, weight) self.voice = 'Кря!' animals = [] goose1 = Goose('Серый', 3000) animals.append(goose1) goose2 = Goose('Белый', 2500) animals.append(goose2) cow1 = Cow('Манька', 400000) animals.append(cow1) sheep1 = Sheep('Барашек', 100000) animals.append(sheep1) sheep2 = Sheep('Кудрявый', 90000) animals.append(sheep2) chiken1 = Chiken('Ко-Ко', 1000) animals.append(chiken1) chiken2 = Chiken('Кукареку', 800) animals.append(chiken2) goat1 = Goat('Рога', 60000) animals.append(goat1) goat2 = Goat('Копыта', 65000) animals.append(goat2) duck1 = Duck('Кряква', 1600) animals.append(duck1) goose1.feed() goose2.feed() cow1.feed() sheep1.feed() sheep2.feed() chiken1.feed() chiken2.feed() goat1.feed() goat2.feed() duck1.feed() cow1.get_milk() sheep1.get_wool() chiken1.get_eggs() total_weight = sum(animals) print(f'Общий вес животных: {total_weight.weight} грамм') max_animal = max(animals) print(f'Наибольший вес имеет: {max_animal.name}')
9cd6a204db5ef15a8d354b83340ef521b3207252
Practice-Problems/wk2-SamanGaziani188
/Encryption.py
638
3.75
4
#!/bin/python3 import math import os import random import re import sys # Complete the encryption function below. def encryption(s): if (math.sqrt(len(s))).is_integer() == True: rows = columns = int(math.sqrt(len(s))) else: rows = int(math.sqrt(len(s))) columns = rows + 1 if rows*columns < len(s): rows = rows+1 String = '' ## print(rows,columns) for i in range(columns): k = i while k < len(s): String = String + s[k] k += columns String = String + ' ' return String print(encryption('chillout'))
6189e83d1dc355fcd5a1eca8fb7783fdd123e9fc
Darshan1917/Data_analysis
/demo.py
310
3.796875
4
# -*- coding: utf-8 -*- class Vector: def __init__(self,x,y): self.x = x self.y = y def __add__(self,other): return Vector(self.x + other.x, self.y + other.y) def __str__(self): return "Vector : " + str(self.x)+ " "+ str(self.y) p1 = Vector(10,20) p2 = Vector(2,3) p3 = p1 + p2 print(p3)
89718330af20f9adcbaf566aef8e460be4501dbe
rajuprade/Python_Code
/Pandas_program/4.py
334
3.671875
4
import pandas as pd import numpy as np #Create a Dictionary of series d = {'Name':pd.Series(['Tom','James','Ricky','Vin','Steve','Smith','Jack']), 'Age':pd.Series([25,26,25,23,30,29,23]), 'Rating':pd.Series([4.23,3.24,3.98,2.56,3.20,4.6,3.8])} #Create a DataFrame df = pd.DataFrame(d) print ("Our data series is:") print (df)
4b2aaa7b226ce0e597d3f229a92a8483c2d8ff4f
henriqueconte/Challenges
/LeetCode/733.py
1,693
3.625
4
class Solution: visitedImage = [[]] def floodFill(self, image, sr, sc, color): self.visitedImage = [[0 for i in range(len(image))] for j in range(len(image[0]))] self.floodPath(image, sr, sc, color) image[sr][sc] = color return image def floodPath(self, image, sr, sc, color): self.visitedImage[sr][sc] = 1 # Going up if sr > 0 : if image[sr - 1][sc] == image[sr][sc] and self.visitedImage[sr - 1][sc] == 0: self.floodPath(image, sr - 1, sc, color) image[sr - 1][sc] = color # Going left if sc > 0: if image[sr][sc - 1] == image[sr][sc] and self.visitedImage[sr][sc - 1] == 0: self.floodPath(image, sr, sc - 1, color) image[sr][sc - 1] = color # Going right if sc < len(image[0]) - 1: if image[sr][sc + 1] == image[sr][sc] and self.visitedImage[sr][sc + 1] == 0: self.floodPath(image, sr, sc + 1, color) image[sr][sc + 1] = color # Going down if sr < len(image) - 1: if image[sr + 1][sc] == image[sr][sc] and self.visitedImage[sr + 1][sc] == 0: self.floodPath(image, sr + 1, sc, color) image[sr + 1][sc] = color return image # Create auxiliary table filled with 0s # Given a point, we will verify on the auxiliary table if we checked each of the 4 sides # If we have already checked, move to the next side # If we didn't check, replace the color if it's the same number solution = Solution() print(solution.floodFill([[1,1,1],[1,1,0],[1,0,1]], 1, 1, 2))
6e7f06f8b746598a57872a4e54ea34f1a2552210
rafaelperazzo/programacao-web
/moodledata/vpl_data/59/usersdata/158/47478/submittedfiles/testes.py
128
3.53125
4
# -*- coding: utf-8 -*- #COMECE AQUI ABAIXO h=int(input('Digite sua altura:')) p=(72.7*h)-58 print('Seu peso ideal é: %d' %p)
a1ea8800649110e3c8facf08031bda916ccbcc9f
omadios/eda_information_gain
/information_gain.py
4,465
3.5
4
import numpy as np import matplotlib.pyplot as plt import pandas as pd import matplotlib.gridspec as gridspec def gini_calc(data,y): """Given input variable (data, pd series/np array) and target(y, pd series/np array), calculate the maximum information gain for a binary split. Code is not written to be computationally efficient, but to show clearly how to calculate the Gini Inpurity. Brute force computation of all possible thresholds for continous data. Supports multiple targets (i.e. three classes 0,1,2) but only binary splits. """ assert len(y)==len(data),'Target vector and feature vector dimension mismatch' y=np.array(y) data=np.array(data) label_unique=np.sort(np.unique(y)) data_unique=np.sort(np.unique(data)) len_data=len(data) data_interval=(data_unique[:-1]+data_unique[1:])/2 igs=np.zeros([len(data_interval),2]) for num,interval in enumerate(data_interval): #GINI INDEX LEFT NODE ln_data=y[data<interval] ln_tot = len(ln_data) #†otal in left node ln = 1 for label in label_unique: ln_x=np.count_nonzero(ln_data == label) ln -= (ln_x/ln_tot)**2 #GINI INDEX RIGHT NODE rn_data=y[data>interval] rn_tot = len(rn_data) #†otal in left node rn = 1 for label in label_unique: rn_x=np.count_nonzero(rn_data == label) rn -= (rn_x/rn_tot)**2 #GINI INDEX BEFORE SPLIT gn = 1 for label in label_unique: gn_x=np.count_nonzero(y == label) gn -= (gn_x/len_data)**2 tot=ln_tot+rn_tot wgn = ln * (ln_tot/tot) + rn * (rn_tot/tot) #weight right and left node by #observations #INFORMATION GAIN: substract from gini before split the weighted gini for split ig = gn - wgn igs[num,0]=interval igs[num,1]=ig max_gain=igs[igs[:,1]==igs[:,1].max()] threshold=max_gain[0,0] ig=max_gain[0,1] #print('treshold >= %.3f, information gain = %.10f' % (max_gain[0,0],max_gain[0,1])) return threshold,ig def plot_gini_hist(data,y,threshold,ig,target_name='Target',feature_name='Feature',target_label={'0':'No', '1':'Yes'}): """Given input variable (data) and target(y), split threshold and information gain plot histograms with data before and after the split. Only supports binary targets (i.e. 0/1) """ def lab_gen(a,b,pre_data): """Labelling helper function """ count_lab0=('='+str(len(a))+'/'+str(len(pre_data))) count_lab1=('='+str(len(b))+'/'+str(len(pre_data))) label=[target_label.get('0')+count_lab0,target_label.get('1')+count_lab1] return label gs = gridspec.GridSpec(2, 4) gs.update(wspace=0.5) label=[target_label.get('0'),target_label.get('1')] fig = plt.figure(figsize=(8,8)) fig.suptitle('Treshold split <= %.3f, information gain = %.3f' % (threshold,ig),fontsize=16) #----- ax1 = plt.subplot(gs[0, 1:3]) hist, bin_edges = np.histogram(data, bins='rice') a = data[y==0] b = data[y==1] label=lab_gen(a,b,data) plt.hist([a, b ], bin_edges, label=label) plt.legend(loc='best',title=target_name) plt.xlabel(feature_name) plt.ylabel('Count') scale_arrow_w=0.25*np.diff(bin_edges)[0] scale_arrow_l=0.10*np.max(hist) plt.arrow(threshold, scale_arrow_l, 0, -scale_arrow_l, length_includes_head=True, head_length=0.5*scale_arrow_l, width=scale_arrow_w, facecolor='black') limx=ax1.get_xlim() limy=ax1.get_ylim() #----- ax2 = plt.subplot(gs[1, :2]) ln_data=data[data<threshold] ln_y=y[data<threshold] a = ln_data[ln_y==0] b = ln_data[ln_y==1] label=lab_gen(a,b,ln_data) plt.hist([a, b ], bin_edges, label=label) plt.xlabel(feature_name) plt.ylabel('Count') plt.legend(loc='best',title=target_name) ax2.set_xlim(limx),ax2.set_ylim(limy) #----- ax3 = plt.subplot(gs[1, 2:]) rn_data=data[data>threshold] rn_y=y[data>threshold] a = rn_data[rn_y==0] b = rn_data[rn_y==1] label=lab_gen(a,b,rn_data) plt.hist([a, b ], bin_edges, label=label) plt.xlabel(feature_name) plt.ylabel('Count') plt.legend(loc='best',title=target_name) ax3.set_xlim(limx),ax3.set_ylim(limy) plt.show()
d4c0f1966c41b7e2f5cd72de3a048a47be22f35b
whikwon/python-patterns
/structural/facade.py
694
3.953125
4
""" Provides convenient access to a particular part of the subsystem's functionality. """ class WeddingHall(object): def book(self): print("Booked a wedding hall.") class FlowerShop(object): def buy(self): print("Bought some wedding flowers.") class Singer(object): def book(self): print("Booked a singer to sing Wedding anthem.") class WeddingPlanner(object): def prepare(self): hall = WeddingHall() flower_shop = FlowerShop() singer = Singer() hall.book() flower_shop.buy() singer.book() def main(): planner = WeddingPlanner() planner.prepare() if __name__ == "__main__": main()
13d28c35f5c99eba408c9245534a6e51354b087b
Sai-Chandar/Machine_Learning_practice
/K_Nearest_neighbour/K_nearest_neighbors_without_sklearn.py
886
3.65625
4
import numpy as np from collections import Counter import matplotlib.pyplot as plt dataset = { 'r': [[1,3.5],[1,4],[1,5]], 'y': [[3.5,1],[4,1],[5,1]] } def k_nearest_neighbors(dataset, predict, k=3): distance = [] for group in dataset: for features in dataset[group]: euclidean_distance = np.sqrt(np.sum((np.array(features)-np.array(predict))**2)) ## print(euclidean_distance, group) distance.append([euclidean_distance, group]) distance.sort() votes = [i[1] for i in distance[:k]] vote_result = Counter(votes).most_common(1)[0][0] return vote_result predict = [2,5] sol = k_nearest_neighbors(dataset, predict) print(sol) for i in dataset: for j in dataset[i]: plt.scatter(j[0], j[1], color = i) plt.scatter(predict[0], predict[1], color = sol, s = 20) plt.show()
5319421377cc69ddc26de82e53a9234ba3062073
max1y0/AyP
/examenes/ciro.py
324
4.03125
4
nota = 0 rta = "si" while (rta== "si"): print("ingrese la nota") nota = input() if (nota < 7): print("aprendizajes pendientes") elif (nota >= 7 and nota < 10): print ("aprendizajes logrados") elif (nota == 10): print ("aprendizajes ampliamente logrados") print("quiere probar otra nota?") rta = raw_input()
5783a8881f2e8e62948c54d77116853593a0a7ec
IonutPopovici1992/Python
/Python/loops.py
345
3.984375
4
numbers = [1, 2, 3, 4, 5] for number in numbers: if number == 3: print('Found!') continue print(number) print() for number in numbers: for letter in 'abc': print(number, letter) print() for i in range(1, 11): print(i) print() x = 0 while True: if x == 5: break print(x) x += 1
c00acefd32d9c807c341a7980803bda3c339ae25
takin6/algorithm-practice
/codility/12/chocolates_by_numbers.py
172
3.53125
4
def solution(N, M): res = 1 X = 0 while (X+M)%N != 0: X = (X+M)%N res += 1 return res # print(solution(10,4)) print(solution(4,4))
507f0f0642a34264f530661096458a0ed615cd10
ds-ga-1007/assignment7
/ym910/Interval.py
4,180
3.828125
4
class MergeError(Exception): def __str__(self): return 'Cannot merge intervals: gap between two intervals.' class Interval(): def __init__ (self, user_input): # user_input=user_input.replace(' ','') ''' check the validity of the user input string, take input strings and transform to bounds and numbers.''' self.user_input=user_input.strip() lbd_sign =['(','['] rbd_sign =[')',']'] if self.user_input[0] in lbd_sign and self.user_input[-1] in rbd_sign: self.lbd=user_input[0] #left bound symbol self.rbd=user_input[-1] #right bound symbol self.num_range=list(map(int,self.user_input[1:-1].split(','))) #the number range in list format self.lnum=self.num_range[0] #lower bound number self.unum=self.num_range[-1] #upper bound number if len(self.num_range)!=2: raise ValueError("Please input valid bounds.") '''check validity mathematically.''' if (self.lbd=='[' and self.rbd ==']' and self.lnum<=self.unum) or (self.lbd=='(' and self.rbd ==']' and self.lnum <self.unum) or (self.lbd=='[' and self.rbd ==')' and self.lnum <self.unum) or (self.lbd=='(' and self.rbd ==')' and self.lnum <self.unum -1): '''list of numbers the interval represents.''' self.bg_num=self.lnum #beginning number self.ed_num=self.unum #ending number if self.lbd=='(': self.bg_num=self.lnum+1 if self.rbd==')': self.ed_num=self.unum-1 self.lowerpt=(self.user_input[0],self.lnum) self.upperpt=(self.user_input[-1],self.unum) else: raise ValueError('Invalid number input.') else: raise ValueError('Invalid interval input.') def __repr__(self): return '%s%d,%d%s' % (self.lbd, self.lnum,self.unum,self.rbd) '''The function is to check the validity of the input string in format. ''' '''def isValidInput(user_input): user_input=user_input.replace(' ','') if (user_input[0] in ['(','[']) and (user_input[-1] in [')',']']) and (',' in user_input): return True else: return False ''' '''Merge functions.''' '''First check if two intervals are mergeable or not: we take the number list of two intervals, if one's smallest number is small than the other's biggest number, and its biggest number is bigger than the other's smallest, then they are mergeable. ''' def IsMergeable (int1, int2): if (int1.bg_num< int2.bg_num and int1.ed_num+1<int2.bg_num) or (int2.bg_num<int1.bg_num and int2.ed_num+1<int1.bg_num): return False return True '''If two intervals can be merged, we then merge them accordingly.''' def mergeIntervals(int1, int2): result="" if IsMergeable (int1, int2) == False: raise MergeError if int1.bg_num>=int2.bg_num: new_lbd=int1.lowerpt else: new_lbd=int2.lowerpt if int1.ed_num>=int2.ed_num: new_rbd=int1.upperpt else: new_rbd=int1.upperpt newint=str(new_lbd[0])+str(new_lbd[1])+","+str(new_rbd[1])+str(new_rbd[0]) return Interval(newint) '''We first sort the interval list by their lower bound number, then choose the first one as base and merge others with the former iteratedly if applicable.''' def mergeOverlapping(intervals): if intervals ==0: return [] intervals = sorted(intervals, key=lambda user_input: user_input.bg_num) result=[intervals[0]] for i in range (1, len(intervals)): if IsMergeable(intervals[i],result[-1]): result[-1]=mergeIntervals(intervals[i],result[-1]) else: result.append(intervals[i]) return result '''the insert function is just to add one more interval to the list and redo the overlap function.''' def insert (intervals, newint): intervals.append(newint) return mergeOverlapping(intervals)
8c204ae2dac7c9b781bd989cacab3c5d2e7c0599
jrcolas/Learning-Python
/100DaysBootcamp/Day17/quiz_brain.py
1,242
3.859375
4
#Quiz Brain class QuizBrain: def __init__(self, q_list): self.question_number = 0 self.question_list = q_list self.score = 0 # TODO: Asking the questions def next_question(self): current_question = self.question_list[self.question_number] self.question_number += 1 response = input(f"Q.{self.question_number}: {current_question.text} (True/False): ").lower() self.check_answer(response, current_question.answer) # TODO: Checking if we're at the end of the quiz def still_has_questions(self): total_questions = len(self.question_list) return self.question_number < total_questions # TODO: Checking if the answer was correct def check_answer(self, user_answer, answer): if user_answer == answer.lower(): self.score += 1 print("You got it right!") else: print("Sorry, that is incorrect.") print(f"The correct answer was: {answer}") print(f"Your current score is: {self.score}/{self.question_number}.") print("\n") def quiz_completed(self): print("You've completed the quiz.") print(f"Your final score was: {self.score}/{self.question_number}.")
642d9bc31aed6395de77a9451e0c92b18f47323e
zangaisishi/zangai
/py02/main.py
270
3.84375
4
def BinSearch(array, key, low, high): mid = int((low+high)/2) if key == array[mid]: return array[mid] if low > high: return False if key < array[mid]: return BinSearch(array, key, low, mid-1) if key > array[mid]: return BinSearch(array, key, mid+1, high)
e86e40de12555c84d3f9d21118b131ca6615d876
Gaju27/Assignment_17_B
/list_of_n_divisible_another_num.py
198
3.828125
4
# Find list of number are divisible by another given number def divisible_number(n,list_input): return list(filter(lambda x: (x % n == 0), list_input)) print(divisible_number(4,[1,3,4,16]))
6327d3df76ae29c9b19e606e41fa903b6694c7ce
yellowmonkeyman/pythonstuff
/ifelse5.py
104
3.828125
4
num1 = 5 num2 = 6 if((num1 + num2) % 2 == 0): print("SUCCESS!") else: print("EPIC FAIL!")
eb85a2d655e53157ae39d4bebaf983a29ed77ba8
anirudhrathore/HactoberFest2020-1
/Python/prime_composite.py
148
4.25
4
num = int(input("Enter the Number : ")) if (num%2 & num%3 == 0): print(num " is a Composite number") else : print(num " is a Prime Number")
f23b562a74f10abbe63d1eaa1c9aa3cdacde2112
entick/training_it_cloud
/tasks1/task2.py
532
4
4
def trimmed_text(text,limit): if len(text)<=limit: return text i=0 pr=0 while i<limit: if (text[i]==" "): pr=i i+=1 if (pr+3>limit): pr-=1 while (text[pr]!=" " and pr>0): pr-=1 if (pr==0): return text[:limit-3]+"..." if (pr+3)<=limit: return text[:pr]+"..." def main(): print(trimmed_text('Python is simple to use, but it is a real programming language.',7)) if __name__ == '__main__': main()
58494e7f98f673172db5b44ce111dbf7bcdd8a2c
lia07/practicaFunciones
/PrintingP10.py
218
3.890625
4
def pattern(n): k = 2*n-2 for i in range(0,n): for j in range(0, k): print(end="") k=k-2 for j in range(0,i+1): print("*", end="") print("\r") pattern(5)
2256b5ded34edaa796328bc589f103b4d18f22ee
Kingz2020/AoC2020
/2/main.py
606
3.59375
4
sled_valid = 0 toboggan_valid = 0 with open("input.txt") as f: for line in f.readlines(): limits, letter, password = line.split() letter = letter[0] lower, upper = [int(x)-1 for x in limits.split('-')] if lower + 1 <= password.count(letter) <= upper + 1: sled_valid += 1 if (password[lower] == letter and password[upper] != letter) or \ (password[upper] == letter and password[lower] != letter): toboggan_valid += 1 print(f"Valid Sled Co Passwords:: {sled_valid}") print(f"Valid Toboggan Co Passwords: {toboggan_valid}")
af0ab0de51ba9f4d15c7358b602d0ae6e2b7309b
mxb360/AlientInvasion
/bullet.py
1,037
3.640625
4
import pygame from pygame.sprite import Sprite class Bullet(Sprite): """ 一个对飞船发射的子弹进行管理的类 """ def __init__(self, ai_settings, screen, ship): """ 在飞船所在处的位置创建一个子弹对象 """ super().__init__() self.screen = screen image = pygame.image.load(ai_settings.bullet_ship_img).convert_alpha() self.image = pygame.transform.scale(image, (ai_settings.bullet_ship_width, ai_settings.bullet_ship_height)) self.rect = self.image.get_rect() self.rect.centerx = ship.rect.centerx self.rect.top = ship.rect.top self.speed_factor = ai_settings.bullet_ship_speed_factor def update(self): """ 向上移动子弹 """ self.rect.y -= self.speed_factor def draw_bullet(self): """ 在屏幕上绘制子弹 """ self.screen.blit(self.image, self.rect) def __str__(self): return 'Bullet(%d, %d)' % (self.rect.centerx, self.rect.centery)