blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
bb3fadcb3d1bceeaedd473ef4d69fa99a79246a4
rosita-hormann/programacion-basica-python
/MATRICES/mouse_maze/solucion.py
8,186
3.6875
4
""" SOLUCIÓN PROPUESTA PARA PROBLEMA DEL LABERINTO DEL RATÓN Autor: Rosita Hormann Lobos. Contacto: rosita.hormannlobos@gmail.com """ import numpy as np def separacion(): print("- - - - - - - - - - - - - - - - - - - - - - - - -") ###################################################### # LECTURA DEL ARCHIVO experimentos.txt experimentosTxt = open("experimentos.txt","r") # Archivo que tiene lista de experimentos listaExperimentos = [] exp = experimentosTxt.readline().strip() cantExps = 0 # Cantidad de experimentos while exp != "": listaExperimentos.append(exp) exp = experimentosTxt.readline().strip() cantExps +=1 def imprimirOpciones(listaOpciones): pos = 0 for elem in listaOpciones: print(pos, ") ", elem) pos += 1 ###################################################### # A partir de aquí se pregunta al usuario qué experimentos quiere consultar # y se realizan los requerimientos principales del problema: seguir = True # Seguir preguntando while seguir: ###################################################### # Escogiendo experimento a procesar imprimirOpciones(listaExperimentos) opcionValida = False # Todavía no se ingresan opciones while not opcionValida: pos = int(input("Que experimento quiere consultar?:" )) # "pos" representa la posicion dentro de la listaExperimentos if pos >= cantExps or pos < 0: print("Posicion inválida. Por favor escriba un numero entre 0 y ", (cantExps - 1)) else: opcionValida = True expTxt = open(listaExperimentos[pos],"r") # Se abre el archivo del experimento seleccionado. ###################################################### # Se procede a procesar el archivo del laberinto nombreLaberinto = expTxt.readline().strip() # Primera linea del archivo debe ser el nombre del archivo del laberinto mazeTxt = open(nombreLaberinto,"r") # Se abre el archivo del laberinto. linea = mazeTxt.readline().strip() # Se lee la primera linea, que tiene dos numeros en formato n,m partes = linea.split(",") n = int(partes[0]) # Filas de la matriz del laberinto m = int(partes[1]) # Columnas de la matriz del laberinto laberinto = np.zeros([n, m]) laberintoBueno = True cantidadQuesos = 0 cantidadSalidas = 0 archivoBueno = True # Asumimos que el archivo no tiene errores for i in range(n): linea = mazeTxt.readline().strip() partes = linea.split(",") # Ahora "partes" es un arreglo de "m" strings. for j in range(m): if partes[j] == "P": # Pared laberinto[i][j] = 1 elif partes[j] == "Q": # Queso laberinto[i][j] = 8 cantidadQuesos += 1 elif partes[j] == " ": # Espacio libre laberinto[i][j] = 0 elif partes[j] == "S": # Salida laberinto[i][j] = 5 cantidadSalidas += 1 else: archivoBueno = False if not archivoBueno: print("El archivo tiene un error!") elif cantidadSalidas <= 0: print("Experimento no válido (laberinto no tiene salidas)") print(laberinto) print(cantidadSalidas) else: ###################################################### # Ahora se posiciona al ratón en el laberinto. #posicionInicial = expTxt.readline().strip().split(",") # La siguiente línea a leer es la posicion inicial del ratón posicionInicial = expTxt.readline().strip() print(posicionInicial) posicionInicial = posicionInicial.split(",") filaActual = int(posicionInicial[0]) # fila en la que se encuentra el ratón. columnaActual = int(posicionInicial[1]) # columna en la que se encuentra el ratón. print("POSICION INICIAL: ", posicionInicial) laberinto[filaActual][columnaActual] = 6 # Se marca posicion del ratón separacion() print(laberinto) # Se imprime el laberinto tal cual está ahora. separacion() ###################################################### ###################################################### # Ahora comenzaremos a mover el ratón a través del laberinto. movimiento = expTxt.readline().strip() ratonSalio = False quesosCapturados = 0 while movimiento != "" and not ratonSalio: x = input("Presione enter para continuar") # Esta línea de código nos permitirá que la lectura de los movimientos del ratón no se realicen todas de una, sino que el programa espere a que el usuario presione "enter" para pasar al siguiente movimiento. separacion() movFilas = 0 movColumnas = 0 if movimiento == "U": #up (arriba) movFilas = -1 # Hay que disminuir la fila. elif movimiento == "D": #down (abajo) movFilas = 1 # Hay que aumentar la fila. elif movimiento == "L": # left (izquierda) movColumnas = -1 # Hay que disminuir la columna. elif movimiento == "R": # right (derecha) movColumnas = 1 # Hay que aumentar la columna. nuevaFila = filaActual + movFilas nuevaColumna = columnaActual + movColumnas ###################################################### # Ahora analizaremos si el movimiento era válido o no. if nuevaFila < 0 or nuevaFila >= n or nuevaColumna < 0 or nuevaColumna >= m: # Aquí corroboramos que no nos estamos saliendo de la matriz "laberinto" print("Movimiento inválido!") elif laberinto[nuevaFila][nuevaColumna] == 1: # PARED. Movimiento inválido. print("Movimiento inválido! (había una pared)") else: ###################################################### # Ahora analizamos los casos de movimientos válidos if laberinto[nuevaFila][nuevaColumna] == 8: # QUESO. Captura el queso. print("Queso capturado!") quesosCapturados+=1 elif laberinto[nuevaFila][nuevaColumna] == 5: # SALIDA. ratonSalio = True # Una vez el ratón sale no hay que seguir leyendo el archivo. ###################################################### # Se procede a marcar el movimiento en el laberinto laberinto[filaActual][columnaActual] = 2 #Dejar huellas filaActual = nuevaFila # Actualizar fila columnaActual = nuevaColumna # Actualizar columna laberinto[filaActual][columnaActual] = 6 # Actualizamos posicion del ratón en el laberinto. print(laberinto) # Finalmente imprimimos el laberinto separacion() movimiento = expTxt.readline().strip() # Leemos siguiente movimiento separacion() print("FIN DEL EXPERIMENTO") separacion() ###################################################### # Ahora que terminamos de mover al ratón, hay que informar quesos capturados y si el ratón salió del laberinto o no. print("El ratón capturó ", quesosCapturados, " de ", cantidadQuesos, " totales.") if ratonSalio: print("El ratón logró salir del laberinto!") else: print("El ratón no logró salir del laberinto...") separacion() ###################################################### # Finalmente hay que preguntar al usuario si desea seguir consultando por experimentos respuesta = -1 while respuesta != 0 and respuesta != 1: respuesta = int(input("Desea consultar otro experimento? [0] NO, [1] Si")) if respuesta != 1 and respuesta != 0: print("Opción inválida!") if respuesta == 0: seguir = False print("Adiós!") ###################################################### ######################################################
4acf284913c1e526aa53b8158bfcb70030cb69a8
KnightSlayerTsorig/Zoo
/menu_functions.py
1,340
3.78125
4
def split(animals): # function that split user input return animals.replace(' ', '').lower().split(',') def add_animals(a_list, a_to_add_list, corrals): # function that allows user add animals to existing corrals for el in corrals: if corrals[el].kind == 'herbivore': herb = corrals[el] if corrals[el].kind == 'predator': pred = corrals[el] try: for i in a_list: for j in a_to_add_list: if j + "'s" == i.species.lower(): if i.kind == herb.kind: herb.add_animal(i.kind, j, i.area, 1) if i.kind == pred.kind: pred.add_animal(i.kind, j, i.area, 1) else: pass except UnboundLocalError: print( 'Before adding animals to the zoo, you need to create at least two corrals one for herbivores and one for ' 'predators' ) def info(): # function that displays on the screen actions that user can perform print( 'Enter the number of the action you want to perform:\n' '1. Create a new corral at the zoo\n' '2. Add animal(s) to the existing corral\n' '3. Get overall zoo info\n' '4. Get overall corrals info\n' '5. Exit\n' )
374b4d99b6bfd005d9843a5fb500b4886c8058ac
DKNY1201/cracking-the-coding-interview
/LinkedList/2_4_Partition.py
2,804
4.21875
4
""" Partition: Write code to partition a linked list around a value x, such that all nodes less than x come before all nodes greater than or equal to x. If x is contained within the list, the values of x only need to be after the elements less than x (see below). The partition element x can appear anywhere in the "right partition"; it does not need to appear between the left and right partitions. EXAMPLE Input: 3 -> 5 -> 8 -> 5 - > 10 -> 2 -> 1 [partition = 5) Output: 3 -> 1 -> 2 -> 10 -> 5 -> 5 -> 8 """ import unittest from LinkedList import LinkedList def partition(ll, x): if not ll or not ll.head: return ll.head less = dummy_less = greater = dummy_greater = None head = ll.head while head: if head.val < x: if not less: less = head dummy_less = head else: less.next = head less = head else: if not greater: greater = head dummy_greater = head else: greater.next = head greater = head head = head.next if less: less.next = dummy_greater if greater: greater.next = None ll.head = dummy_less if dummy_less else dummy_greater class Test(unittest.TestCase): def test_partition(self): ll = LinkedList() vals = [7, 3, 4, 5, 6, 7, 10, 100, 4, 7] ll.add_nodes_to_tail(vals) expect = [3, 4, 5, 6, 4, 7, 7, 10, 100, 7] partition(ll, 7) self.assertEqual(expect, ll.to_list(), "Should partition linkedlist nodes around given x") ll = LinkedList() vals = [7, 3, 4, 5, 6, 7, 10, 100, 4, 7] ll.add_nodes_to_tail(vals) expect = [7, 3, 4, 5, 6, 7, 4, 7, 10, 100] partition(ll, 8) self.assertEqual(expect, ll.to_list(), "Should partition linkedlist nodes around given x") ll = LinkedList() vals = [-7, -3, -4, 5, 6, 7, 10, 100, -4, 7] ll.add_nodes_to_tail(vals) expect = [-7, -3, -4, -4, 5, 6, 7, 10, 100, 7] partition(ll, 0) self.assertEqual(expect, ll.to_list(), "Should partition linkedlist nodes around given x") ll = LinkedList() vals = [7, 3, 4, 5, 6, 7, 10, 100, 4, 7] ll.add_nodes_to_tail(vals) expect = [7, 3, 4, 5, 6, 7, 10, 100, 4, 7] partition(ll, 2) self.assertEqual(expect, ll.to_list(), "Should partition linkedlist nodes around given x") ll = LinkedList() vals = [7, 3, 4, 5, 6, 7, 10, 100, 4, 7, 100] ll.add_nodes_to_tail(vals) expect = [7, 3, 4, 5, 6, 7, 10, 4, 7, 100, 100] partition(ll, 100) self.assertEqual(expect, ll.to_list(), "Should partition linkedlist nodes around given x")
b792d8a0f9697236576721acd7a85d326feef613
daniel-reich/ubiquitous-fiesta
/pSrCZFim6Y8HcS9Yc_20.py
205
3.8125
4
def convert(deg): if deg[-1] == "F": C = (int(deg[:-2])-32)*5/9 return "{:.0f}*C".format(C) if deg[-1] == "C": F = int(deg[:-2])*9/5 + 32 return "{:.0f}*F".format(F) return 'Error'
afebde0bb976635cfae3f9e7dece7e6093adf6e9
Lindisfarne-RB/GUI-L3-tutorial
/Lesson62_REFREACTOR.py
5,393
4.28125
4
'''14.4 Using the account names in the GUI code We have a list called account_list which contains our 3 account objects. We want to use this list like account_names on lines 93‑100 for the Combobox. However, the account_list is actually a list of objects, so if we plug that list straight in we will have some issues. CREATE Let's see what happens if we do that. Find line 93 where account_names is set, and replace ["Savings", "Phone", "Holiday"] with account_list. Click RUN to see what happens to the account combobox. Using a list of objects is not going to work for this, so instead we will write a function that will loop through the list of objects and make a new list of just their names as strings. Under the relevant comment in the Functions and Setup section, define a new function called create_name_list() which takes no parameters. Add in pass for now and we will complete this function in the next task.''' #################### IMPORTS ####################### from tkinter import * from tkinter import ttk ################## CLASS CODE ###################### # Create the Account class class Account: """The Account class stores the details of each account and has methods to deposit, withdraw and calculate progress towards the savings goal""" def __init__(self, name, balance, goal): self.name = name self.balance = balance self.goal = goal account_list.append(self) # Deposit method adds money to balance def deposit(self, amount): if amount > 0: self.balance += amount return True else: return False # Withdraw method subtracts money from balance def withdraw(self, amount): if amount > 0 and amount <= self.balance: self.balance -= amount return True else: return False # Get progress method calculates goal progress def get_progress(self): progress = (self.balance / self.goal) * 100 return progress ############## FUNCTIONS AND SETUP ############### # Create a function to get account names list def create_name_list(): pass # Create a function that will update the balance. def update_balance(): pass # Set up Lists account_list = [] # Create instances of the class savings = Account("Savings", 0, 1000) phone = Account("Phone", 0, 800) holiday = Account("Holiday", 0, 7000) ################## GUI CODE ###################### root = Tk() root.title("Goal Tracker") # Create the top frame top_frame = ttk.LabelFrame(root, text="Account Details") top_frame.grid(row=0, column=0, padx=10, pady=10, sticky="NSEW") # Create and set the message text variable message_text = StringVar() message_text.set("Welcome! You can deposit or withdraw money and see your progress towards your goals.") # Create and pack the message label message_label = ttk.Label(top_frame, textvariable=message_text, wraplength=250) message_label.grid(row=0, column=0, columnspan=2, padx=10, pady=10) # Create the PhotoImage and label to hold it neutral_image = PhotoImage(file="smiley.png") image_label = ttk.Label(top_frame, image=neutral_image) image_label.grid(row=1, column=0, columnspan=2, padx=10, pady=10) # Create and set the account details variable account_details = StringVar() account_details.set("Savings: $0 \nPhone: $0\nHoliday: $0\nTotal balance: $0") # Create the details label and pack it into the GUI details_label = ttk.Label(top_frame, textvariable=account_details) details_label.grid(row=2, column=0, columnspan=2, padx=10, pady=10) # Create the bottom frame bottom_frame = ttk.LabelFrame(root) bottom_frame.grid(row=1, column=0, padx=10, pady=10, sticky="NSEW") # Create a label for the account combobox account_label = ttk.Label(bottom_frame, text="Account: ") account_label.grid(row=3, column=0, padx=10, pady=3) # Set up a variable and option list for the account Combobox account_names = account_list chosen_account = StringVar() chosen_account.set(account_names[0]) # Create a Combobox to select the account account_box = ttk.Combobox(bottom_frame, textvariable=chosen_account, state="readonly") account_box['values'] = account_names account_box.grid(row=3, column=1, padx=10, pady=3, sticky="WE") # Create a label for the action Combobox action_label = ttk.Label(bottom_frame, text="Action:") action_label.grid(row=4, column=0) # Set up a variable and option list for the action Combobox action_list = ["Deposit", "Withdraw"] chosen_action = StringVar() chosen_action.set(action_list[0]) # Create the Combobox to select the action action_box = ttk.Combobox(bottom_frame, textvariable=chosen_action, state="readonly") action_box['values'] = action_list action_box.grid(row=4, column=1, padx=10, pady=3, sticky="WE") # Create a label for the amount field and pack it into the GUI amount_label = ttk.Label(bottom_frame, text="Amount:") amount_label.grid(row=5, column=0, padx=10, pady=3) # Create a variable to store the amount amount = DoubleVar() amount.set("") # Create an entry to type in amount amount_entry = ttk.Entry(bottom_frame, textvariable=amount) amount_entry.grid(row=5, column=1, padx=10, pady=3, sticky="WE") # Create a submit button submit_button = ttk.Button(bottom_frame, text="Submit", command=update_balance) submit_button.grid(row=6, column=0, columnspan=2, padx=10, pady=10) # Run the mainloop root.mainloop()
36ca1ce8a5e4727a90ac76ead6922ed5be5dc8ef
lixiang2017/leetcode
/lintcode/009010_·_Closest_Binary_Search_Tree_Value_II.py
772
3.515625
4
''' 86 mstime cost 8.74 MBmemory cost Your submission beats78.80 %Submissions ''' """ Definition of TreeNode: class TreeNode: def __init__(self, val): self.val = val self.left, self.right = None, None """ import heapq class Solution: """ @param root: the given BST @param target: the given target @param k: the given k @return: k values in the BST that are closest to the target """ def closestKValues(self, root, target, k): # write your code here nums = [] def dfs(node): if not node: return dfs(node.left) nums.append(node.val) dfs(node.right) dfs(root) return heapq.nsmallest(k, nums, lambda x: abs(x - target))
433ad7d74007d201b8a44717839f05d75f9f4916
ProdigyX6217/interview_prep
/word_count.py
728
4.25
4
str_1 = "Anyway, like I was sayin', shrimp is the fruit of the sea. You can barbecue it, boil it, broil it, bake it, \ saute it. Dey's uh, shrimp-kabobs, shrimp creole, shrimp gumbo. Pan fried, deep fried, stir-fried. There's pineapple \ shrimp, lemon shrimp, coconut shrimp, pepper shrimp, shrimp soup, shrimp stew, shrimp salad, shrimp and potatoes, \ shrimp burger, shrimp sandwich. That- that's about it." spaces_and_letters = "" # this for loop reduces the string to letters, numbers, and spaces for char in str_1: if char.isalnum() or char.isspace() or char == "-": spaces_and_letters += char words = spaces_and_letters.split() number_of_words = len(words) print(words) print("") print(number_of_words)
bfe4574c88dcc7d6cd57a3c634e85fb2dc44c2d3
rahulsrma26/manim
/from_rahul/assignments/11_isosceles_triangle.py
796
4.28125
4
''' ## Printing Isosceles Triangle using asterisk This is a star isosceles triangle with base as 4. ```text * * * * * * * * * * ``` You are given a number *n*. We want to print the triangle with base *n*. Hint: You may need to use nested loop. Inner loop will be printing stars in a single row. # Input Format: You will be given an integer *n*. # Constraints: 1 <= *n* <= 20 # Output Format: Star triangle with base *n*. ''' import random def solve(n): output = [] for x in range(1, n + 1): output.append(' ' * (n - x) + '* ' * x) return '\n'.join(output) def main(): inputs = [4] + list(filter(lambda x: x != 4, range(1, 21))) return [(x, solve(x)) for x in inputs] if __name__ == "__main__": print(main())
a95bfe8b40612444ec696801176912073bb3ab07
MELCHIOR-1/myleetcode
/No33_Search in Rotated Array.py
1,274
3.65625
4
# -*- coding: utf-8 -*- """ Created on Thu Mar 19 21:32:48 2017 @author: shawpan """ # Suppose an array sorted in ascending order is rotated at some # # pivot unknown to you beforehand. # # (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2). # # You are given a target value to search. If found in the array # # return its index, otherwise return -1. # # You may assume no duplicate exists in the array. class Solution(object): def search(self, nums, target): """ :type nums: List[int] :type target: int :rtype: int """ n = len(nums) lo,hi = 0,n-1 while(lo<hi): mid = (lo+hi)/2 if nums[mid]>nums[hi]: # 注意这步比较的项 lo = mid + 1 else: hi = mid rot = lo # print rot,mid lo, hi = 0,n-1 while(lo<=hi): mid = (lo+hi)/2 realMid = (mid + rot) % n # print mid,realMid if nums[realMid] == target: return realMid elif nums[realMid] < target: lo = mid + 1 else: hi = mid - 1 return -1 if __name__ == "__main__": print Solution().search([3,1],1) print Solution().search([1,3], 1)
ca2b504b0c6701cde8b219b4cd688f04778c59e5
asnewton/Data-Structure-and-Algorithm
/arrays/spiralTraversal.py
852
3.6875
4
arr = [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ] def spiralTraversal(arr): n = len(arr) m = len(arr[0]) T = 0 B = n-1 L = 0 R = m-1 direction = 1 while( T <= B and L <= R): if(direction == 1): for i in range(L, R): print(arr[T][i]) T += 1 direction = 2 elif( direction == 2): for i in range(T, B): print(arr[i][R]) R -= 1 direction = 3 elif(direction == 3): for i in range(R, L, -1): print(arr[B][i]) L -= 1 direction = 4 elif(direction == 4): for i in range(B, T, -1): print(arr[i][L]) L += 1 direction = 1 direction = (direction + 1) % 5 spiralTraversal(arr)
722bf5c8157b0ccf99bc3f3d2a03c45d169abcba
srikanthpragada/PYTHON_12_JULY_2021
/demo/assignments/common_factors.py
154
3.609375
4
num1 = 450 num2 = 250 small = num1 if num1 < num2 else num2 for i in range(2, small // 2 + 1): if num1 % i == 0 and num2 % i == 0: print(i)
406d0f3423ecc279606cf31f7e6b169114552250
Abhi1o/python_learning-
/4_day/3_list.py
434
4.03125
4
#list is a organized set of data in python. #List enclosed with in [] and seperated by ,comma. State_in_India=["Jammu&kashmir", "punjab", "Haryana", "Himachal_Pradesh", "Uttar_Pardesh"] print(State_in_India[1]) print(State_in_India[1:]) print(State_in_India[:3]) print(State_in_India[1:4]) print(State_in_India[0:6]) print(State_in_India[-2:-1]) #to edit any value State_in_India[1]="bihar" print(State_in_India)
9670b699d421375a8f78c218dc6f698762c140c2
olegbrz/coding_every_day
/CodeWars/018_291120_man_boy_sort.py
1,244
4.1875
4
"""Scenario Now that the competition gets tough it will Sort out the men from the boys . Men are the Even numbers and Boys are the odd!alt!alt Task Given an array/list [] of n integers , Separate The even numbers from the odds, or Separate the men from the boys!alt!alt Notes Return an array/list where Even numbers come first then odds Since , Men are stronger than Boys , Then Even numbers in ascending order While odds in descending . Array/list size is at least *4*** . Array/list numbers could be a mixture of positives , negatives . Have no fear , It is guaranteed that no Zeroes will exists .!alt Repetition of numbers in the array/list could occur , So (duplications are not included when separating). Input >> Output Examples: menFromBoys ({7, 3 , 14 , 17}) ==> return ({14, 17, 7, 3}) Explanation: Since , { 14 } is the even number here , So it came first , then the odds in descending order {17 , 7 , 3} . menFromBoys ({-94, -99 , -100 , -99 , -96 , -99 }) ==> return ({-100 , -96 , -94 , -99}) """ def men_from_boys(arr): odd, even = set(), set() for i in arr: if i % 2: odd.update([i]) else: even.update([i]) return sorted(even) + sorted(odd, reverse=True)
04f0177ed40f107486c7831b340736acc5e88e34
ababa831/atcoder_beginners
/progcon_book/alds1_1_a_3rd.py
774
4.1875
4
# Accepted # Ref: http://interactivepython.org/courselib/static/pythonds/SortSearch/TheInsertionSort.html def insertation_sort(a, n): for i in range(1, n): # Temporary memorize the current value # because the value vanishes if shiftings (a[i] = a[i-1]) are executed. current_val = a[i] # Search the destination of the value position = i while position > 0 and a[position - 1] > current_val: a[position] = a[position - 1] position -= 1 # Insert the current value to the destination a[position] = current_val print(' '.join(a)) def main(): # Input n = int(input()) a = input().split() # Sort insertation_sort(a, n) if __name__ == '__main__': main()
e912f0b29416d0bfab57d21267f115abbc841c53
cmgn/problems
/kattis/whatdoesthefoxsay/whatdoesthefoxsay.py
350
4.0625
4
#!/usr/bin/env python3 number_of_tests = int(input()) for _ in range(number_of_tests): sounds_made = input().split() other_animals = set() s = input() while s != "what does the fox say?": other_animals.add(s.split()[-1]) s = input() print(" ".join(sound for sound in sounds_made if sound not in other_animals))
02cdd366f889483176ddaadf122e5056d6a9eb0b
rtribiolli/520
/aula4/func4.py
406
3.78125
4
#!/usr/bin/python3 #testar com diciionario convidados = [] def adicionar(nome, idade): """ funcao para adicionar convidados na lista """ global convidados convidados.append(nome, idade) return True while True: nome = input("nome ou sair: ") if nome.strip().lower() == 'sair': break idade = int(input('Digite a idade: ')) adicionar(nome, idade) print (convidados)
ef4177ab546ef296a9d1e8e93c92730a22ef685e
pmstangmailcom/2020_1_homework_4
/Tasks/Like.py
1,059
4.3125
4
''' Мне нравится 👍 Создайте функцию, которая, принимая массив имён, возвращает строку описывающая количество лайков (как в Facebook). def likes(*arr: str) -> str: pass Примеры: likes() -> "no one likes this" likes("Peter") -> "Peter likes this" likes("Jacob", "Alex") -> "Jacob and Alex like this" likes("Max", "John", "Mark") -> "Max, John and Mark like this" likes("Alex", "Jacob", "Mark", "Max") -> "Alex, Jacob and 2 others like this" Бонусные очки Функция работает на нескольких языках и кодировках - язык ответа определяется по языку входного массива. ''' class MyClass: def likes(self, var: str) -> str: result = '' return result if __name__ == '__main__': # Here we can make console input and check how function works var = input('Input names: ') result = MyClass().likes(var) print(result)
f9bf6bbebdedc3b38f40fdea2dafe7c18e0469ce
hernandez26/Projects
/4.10-4.12 try exercises.py
1,258
4.40625
4
# 4.10 Practice using slices numeros =["uno","dos","tres","cuatro", "cinco","sies","siete","ocho","nueve","diez","once","doce"] print(f"Here are the first 4 items of my list {numeros[0:4]}") print(f'Here are the 4 items of my list found in the middle {numeros[4:8]}') print(f"Here are the final four items found on my list {numeros[8:]}") #4.11 Practice copying a list print("\n") my_sports= ["basketball","baseball","football","UFC"] friends_sports= my_sports[:] print(f"My favorite sports to watch are {my_sports}") print(f"My friends favorite sports to watch are {friends_sports}") my_sports.append("Boxing") friends_sports.append("E-Sports") print("\n") print("The Following is an updated list of sport I like to watch...") for x in my_sports: print(x) print("\n") print("the following is an updated list of the sports my friend watches...") for x in friends_sports: print(x) # 4.12 More Practice with For loops print("\n") pies = ["apple","cherry","pecan","blueberry"] for x in pies: print(x.title()) for x in pies: print(x.upper()) print("\n") shoebrands= ["nike","reebok","addidas","new balance", "puma"] for x in shoebrands: print(x.title()) for x in shoebrands: print(x.upper())
0a7e93b2838cf0f789ef8639306b6c08f6f9edd7
MurilloGodoi/Cota-o
/cotacao_moedas.py
961
3.65625
4
import requests import json class ListValors(): def __init__(self, currency): self._currency = currency def request_api(self): response = requests.get( f'https://economia.awesomeapi.com.br/json/{self._currency}') if response.status_code == 200: return response.json() else: print("Currency not found") return response.status_code def list_informations(self): datas_api = self.request_api() print("\n") print("Code: " , datas_api[0]['code']) print("Name: ",datas_api[0]['name']) print("Highest value in the day: ",datas_api[0]['high']) print("Lowest value in the day: ",datas_api[0]['low']) print("Variation in the day: ",datas_api[0]['varBid']) print("\n") currency = input("Enter the name of the currency: ") currency = ListValors(currency) currency.list_informations()
16193746bcca70345ead8cfefd55a5923a26b9b5
Makhosandile/abantu
/api/utils.py
918
3.546875
4
import pandas as pd import numpy as np population_df = pd.read_csv('data/population.csv') population_df = population_df.fillna(0) population_df['Population'] = population_df['Population'].astype(int) def male_population(): df = population_df.query('Series == "Population, male"') df = df.drop('Series', axis=1) return df def population(): df = population_df.query('Series == "Population, total"') df = df.drop('Series', axis=1) return df def female_population(): df['Female Population'] = population()['Population'] - male_population()['Population'] df = df.drop(['Series', 'Population'], axis=1) return df def male_perc(): df['Male Percentage'] = male_population()['Population'] / population()['Population'] * 100 return df def female_perc(): df['Female Percentage'] = female_population()['Female Population'] / population()['Population'] * 100 return df
78166046acedeececdf45d76734f355b84a2407c
wpsymans/PythonCourse
/Section 4 - Loops/Section 4 - For Loops.py
539
4.0625
4
groceries = ["ham","spam","milk","bread"] #this block removes spam from the grocery list using continue for item in groceries: if item == "spam": continue print(item) print("a second list with break") for item in groceries: if item == "spam": break print(item) item_to_find = input("What item") found_at = None for index in range(len(groceries)): if groceries[index] == item_to_find: found_at = index print("{0} found at position {1}".format(item_to_find,found_at)) break
36644164ffd88c6c29e4c5c3ef05be587a9d9823
brunadelmourosilva/cursoemvideo-python
/mundo2/ex049_tabuada.py
263
4
4
# Refaça o DESAFIO 009, mostrando a tabuada de um número que o usuário escolher, # só que agora utilizando um laço for. n = int(input('digite um número para ver sua tabuada: ')) for cont in range(1,10+1): print('{} X {} = {}'.format(cont, n, cont * n))
5cc2285365636bf9538185fc13bb921874486b18
suvimanikandan/PYTHON_CODES
/python codes/keyword variables args.py
166
3.546875
4
def person(name,**data): print(name) for i,j in data.items(): print(i,j) person('swetha',age=24,city='Chidambaram',mob=8903098719)
8d3fbbdcf23d555db18199aab42622a379bbad8f
AdityaNarayan001/Basic_Library_App-GUI-
/main_code.py
5,999
3.59375
4
# GUI for Library from tkinter import * from tkinter import messagebox from tkinter.filedialog import askopenfile root = Tk() root.title('LIBRARY GUI') root.geometry("1250x640") root.configure(bg='black') bn = [] bid = [] bc = [] newbooklist = [] name = " " cost = 0 id = 0 def reversecontents(): bn.reverse() messagebox.showinfo('RESULT',bn) def add(): main_name = name.get() bn.append(main_name) main_ids = ids.get() bid.append(main_ids) int_cost = int(cost.get()) #important string to int conversion bc.append(int_cost) #def addbooks(): #print("You need to add the books to the library first") #n = int(input("enter the number of books you wanna add")) # for i in range(0, int(n)): #name = input("Enter the name of the book :") # bn.append(name) #ids = input("Enter the id of the book :") # bid.append(ids) #cost = int(input("Enter the cost of the book :")) # bc.append(int(cost)) #print(addbooks()) def addmorebooks(): print("Okay!!,You wanna add more") w = int(input("enter the number of books you wanna add")) for i in range(0, w): name = input("Enter the name of the book :") bn.append(name) ids = input("Enter the id of the book :") bid.append(ids) cost = input("Enter the cost of the book :") bc.append(cost) def arrangebooks(): # bubble sort works for i in range(0, len(bn) - 1): for j in range(i): if bn[j + 1] < bn[j]: c = bn[j] bn[j] = bn[j + 1] bn[j + 1] = c #print(bn) messagebox.showinfo('RESULT',bn) #listbox = Listbox(root) #listbox.insert(0,bn) #listbox.pack() def countbooks(): # works count = 0 for cost in bc: if (cost > 500): count += 1 messagebox.showinfo('RESULT',f"The number of books whose cost is more than 500 = {count}") def copybooks(): new = [] for i in bn: if i not in new: new.append(i) messagebox.showinfo('RESULT',f"The updated list without duplicates using a temporary array is = {new}") def deleteduplicate(): for cost in bc: if cost < 500: newbooklist.append(name) messagebox.showinfo('RESULT',f"The updated list of books are = {newbooklist}") def full_reset(): name.delete(0, END) ids.delete(0, END) cost.delete(0, END) #def menu(): # Menu print # print("Choose the operation you want to perform") # print("1: Add more books to the Library") #Add new button added # print("2: Display books in ascending order on the basis of cost") #msgbox # print("3:Delete duplicate entries using a temporary array") #msgbox # print("4:Count the number of books which cost more than 500") #msgbox # print("5:Copy books in a new list which have cost less than 500") #msgbox # print("6:Reverse contents of the library books") #msgbox # print("Thanks for the mess!") # choice = int(input("Enter your choice!")) # while choice != 0: # if choice == 1: # addmorebooks() # break # elif choice == 2: # arrangebooks() # break # elif choice == 3: # deleteduplicate() # break # elif choice == 4: # countbooks() # break # elif choice == 5: # copybooks() # break # elif choice == 6: # reversecontents() # break # else: # break # GUI code -------------------------------------------------------- #main() #Labels------------------------------ mylabel1 = Label(root, text='GUI for Library App', font=("Arial Bold", 20, 'underline') , fg='cyan', bg='black') mylabel1.pack() #mylabel2 = Label(root, text='Enter the Number of Books you want to Add :', font=('Arial', 15), bg='black', fg='white') #mylabel2.place(x=135, y=55) mylabel3 = Label(root, text='Enter the Name of the Book :', font=('Arial', 15), bg='black', fg='white') mylabel3.place(x=135, y=90) mylabel4 = Label(root, text='Enter ID of the Book :', font=('Arial', 15), bg='black', fg='white') mylabel4.place(x=135, y=125) mylabel5 = Label(root, text='Enter Cost of the Book :', font=('Arial', 15), bg='black', fg='white') mylabel5.place(x=135, y=160) #Buttons------------------------------ Add_book = Button(root, text='ADD BOOK', fg='white', bg='red', width=20,height=6, font='sans 10 bold', command=add).place(x=600, y=85) Arrange_books = Button(root, text='ARRANGE BOOK IN ASCENDING ORDER ON COST', fg='white', bg='red', width=55,height=2, font='sans 10 bold', command=arrangebooks).place(x=135, y=345) Delete = Button(root, text='DELETE DUPLICATE ENTRIES', fg='white', bg='red', width=55,height=2, font='sans 10 bold', command=deleteduplicate).place(x=135, y=255) Count = Button(root, text='NUMBER OF BOOKS EXPENSIVE THAN 500', fg='white', bg='red', width=55,height=2, font='sans 10 bold', command=countbooks).place(x=135, y=300) Copy = Button(root, text='COPY BOOKS IN A NEW LIST WHICH HAS COST LESS THAN 500', fg='white', bg='red', width=55,height=2, font='sans 10 bold', command=copybooks).place(x=135, y=435) Reverse = Button(root, text='REVERSE CONTENT OF THE LIBRARY BOOKS', fg='white', bg='red', width=55,height=2, font='sans 10 bold', command=reversecontents).place(x=135, y=390) Add_new_book = Button(root, text='ADD NEW BOOK', fg='white', bg='red', width=55,height=2, font='sans 10 bold', command=full_reset).place(x=135, y=210) #Entry-------------------------------- #n = Entry(root, bg='misty rose', fg='black') #n.place(x=540, y=55, width=50, height=27) name = Entry(root, bg='misty rose', fg='black') name.place(x=400, y=90, width=190, height=27) ids = Entry(root, bg='misty rose', fg='black') ids.place(x=400, y=125, width=190, height=27) cost = Entry(root, bg='misty rose', fg='black') cost.place(x=400, y=160, width=190, height=27) root.mainloop()
3b4a8144a99e07a45f2bd43f6e2c110844cf2e81
kunalsxngh/qa_python_excercises
/excercises/classes.py
274
3.515625
4
class students: def __init__(self, name, age, className = "student"): self.name = name self.age = age self.className = className def average_test_scores(self, test1, test2, test3): return round(((test1 + test2 + test3) / 3), 2)
4e0ca1fbe89cf1e7359f3cd5faaa4efe94050e89
RaelViana/Python_3
/ex025.py
1,575
3.703125
4
""" Manipulando Texto """ # Fatiamento frase = 'Curso em Video Python ' print(frase[9]) # Apresenta a letra no indice 9 print(frase[3:5]) # Apresenta somente o valor fatiado do indice 3 ao 5 print(frase[:14]) # Apresente valor fatiado do inicio até o indice 14 print(frase[9:]) # Apresente valor fatiado do ince 9 até o final print(frase[0:14:2]) # Aprsenta valor fatiado do inicio até o indice 14, pulando de 2 em 2 dividido = frase.split() # cria uma lista e aloca cada palavra da frase dentro print(dividido[2]) # apresenta a palavra no indice 2 # Analise print(frase.count('o')) # Apresenta a recorrência da letra o dentro da frase print(frase.upper()) # transforma toda a frase um letras maiúsculas print(frase.lower()) # transforma toda a frase um letras minúsculas print(len(frase)) # percorre toda a extensão da frase e apresenta a quantidade de caracteres print(frase.strip()) # remove os espaços antes e depois da frase print(frase.replace('Python', 'Android')) # Substitui a palavra da frase, pela palavra referenciada print('Curso' in frase) # Verifica se existe a palavra referenciada dentro da frase print(frase.find('Video')) # Retorna o indice de onde a palavra está alocada print(frase.capitalize()) # Torna a primeira letra da frase Maiúscula e o restante Minúscula print(frase.title()) # Torna todas as palavras iniciando com letras Maiúsculas print('-'.join(frase)) # insere um caracter especifico entre os espaçõs de cada letra #--------------------------------------------------------------------------------------------------------
8b4700056666483d2d61556dfe7010648b4a92b6
gscho/Ackermann
/src/python/iterative.py
609
3.921875
4
import time; def Ackermann(m,n): stack = [m] i = 0 while (len(stack)): x = stack.pop() if(x == 0): n = n + 1 elif(n == 0): n = 1 stack.append(x-1) else: n = n - 1 stack.append(x-1) stack.append(x) return n print "****Iterative Ackermann in Python****" print "Enter m and n: " m = int(raw_input()) n = int(raw_input()) start = time.time() ack = Ackermann(m,n) finish = time.time() print "Result = %d" % (ack) timing = finish-start print "Elapsed Time in milliseconds: %f" % (timing*100.0)
4e28b258bb49fce1bb9def195375fc41f7404f48
zephyr123/blibli
/book/p8/8_4.py
179
3.578125
4
def make_shirt(size,type='I love Python'): print("This shirt's size:" + size,"字样是: " + type) make_shirt('big') make_shirt('middle') make_shirt('small','life is short')
f13c3225c24bd5d9bdf5ddd7ceef12b5128b3a7e
mattjax16/DFS_data_analysis
/draftkings_files/draftkings_scrapper.py
3,319
3.515625
4
""" draftkings_scrapper.py this file is to scrape draft kings mlb data """ import psycopg2 import pandas as pd import sys from configparser import ConfigParser from requests_html import HTMLSession import bs4 class DkScrapper(): ''' This is a class to scrape date from draft kings ''' def __init__(self): self.mlb_cat_urls = {'50/50':'https://www.draftkings.com/lobby#/MLB/0/IsFiftyfifty'} self.session = HTMLSession() self.con = self.config() def config(self,filename='draftkings_scrapper.ini', section='login'): ''' This is a function to read the ini file and use the info to login into draftkings :param filename: :param section: :return: ''' # create a parser parser = ConfigParser() # read config file parser.read(filename) # get section, con = {} if parser.has_section(section): params = parser.items(section) for param in params: con[param[0]] = param[1] else: raise Exception('Section {0} not found in the {1} file'.format(section, filename)) return con def login(self): ''' This function is to login the person to draft kings trying to use the scrapper The login info comes from draftkings_scrapper.ini :return: ''' login_form_url = 'https://api.draftkings.com/users/v3/providers/draftkings/logins?format=json' login_form = { "login": self.con['email'], "password": self.con['password'], "host": "api.draftkings.com", } response = self.session.post(login_form_url,data=login_form) print(f'Login Response: {response.status_code}') if response.status_code == 200: print(f'Successfully Logged In!') else: print(f'Login Failed!') return def get_response(self,url): ''' :param url (string): a url of a webpage :return: ''' response = self.session.get(url) print(f'Response: {response.status_code}') return response def get_div_html(self,response,div): ''' :param response (response object): :param tag (string): tag to find: :return: ''' div_html = response.html.find(f'div.{div}') return div_html def get_draft_csv(self, csv_link ='https://www.draftkings.com/lineup/getavailableplayerscsv?contestTypeId=28&draftGroupId=55478'): ''' This is a function to request the csv file from the link :param csv_link: :return: ''' return ''' The main function used to test functions from this python script ''' def main(): scrapper = DkScrapper() t_login = scrapper.login() test_url = scrapper.mlb_cat_urls['50/50'] r = scrapper.get_response('https://www.draftkings.com/lineup/getavailableplayerscsv?contestTypeId=28&draftGroupId=55478') r.html.render(sleep=1,keep_page=True,scrolldown=1) grid_canvas_tag = 'dk-grid slickgrid_521465 ui-widget' grid_canvas_html = scrapper.get_div_html(r,grid_canvas_tag) print('Done Maine()') if __name__ == '__main__': main()
8c8eee3fd67c1b50cc49e0acbae8643de1b6b59a
tanmaybhoir09/SSW567-HW02
/TestTriangle.py
1,961
4.03125
4
""" Updated Feb 22, 2019 The primary goal of this file is to demonstrate a simple unittest implementation @author: jrr @author: rk @auther: Tanmay Bhoir """ import unittest from Triangle import classifyTriangle # This code implements the unit test functionality # https://docs.python.org/3/library/unittest.html has a nice description of the framework class TestTriangles(unittest.TestCase): # define multiple sets of tests as functions with names that begin def testRightTriangleA(self): self.assertEqual(classifyTriangle(3,4,5),'Right') def testRightTriangleB(self): self.assertEqual(classifyTriangle(5,3,4),'Right') def testEquilateralTrianglesA(self): self.assertEqual(classifyTriangle(1,1,1),'Equilateral') def testEquilateralTrianglesB(self): self.assertEqual(classifyTriangle(100,100,100),'Equilateral') def testIsocelesTrianglesA(self): self.assertEqual(classifyTriangle(5,5,3),'Isoceles') def testIsocelesTrianglesB(self): self.assertEqual(classifyTriangle(36,28,36),'Isoceles') def testScaleneTrianglesA(self): self.assertEqual(classifyTriangle(13,9,14),'Scalene') def testScaleneTrianglesB(self): self.assertEqual(classifyTriangle(7,15,12),'Scalene') def testNotATriangleA(self): self.assertEqual(classifyTriangle(1,2,10),'NotATriangle') def testNotATriangleB(self): self.assertEqual(classifyTriangle(150,1,1),'NotATriangle') def testNotATriangleC(self): self.assertEqual(classifyTriangle(300,2,2),'NotATriangle') def testInvalidInputA(self): self.assertEqual(classifyTriangle(10,False,10),'InvalidInput') def testInvalidInputC(self): self.assertEqual(classifyTriangle(-1,-1,-1),'InvalidInput') if __name__ == '__main__': print('Running unit tests') unittest.main(exit=False, verbosity=2)
12830ea78130f0dc74e139a03517c8f6727ae661
HazelIP/Programming-21
/week4/lab 4.1.2 grade.py
366
4
4
# This program print a student's corresponding grade based on the student's % marks # author: Ka Ling IP grade = int(input("Enter the percentage:")) if grade < 40: print("fail") elif grade>=40 and grade<49: print ("pass") elif grade>=50 and grade <59: print ("Merit 2") elif grade>=60 and grade<69: print ("Merit 1") else: print ("Distinction")
0b4b60ca311565ccc3eab5e47b580f2e10725193
delvinlow/coding-practices
/RomanToInteger/Solution.py
1,003
3.5625
4
class Solution: mapping = { "I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000 } def romanToInt(self, s: str) -> int: numerals = [] str_reversed = [char for char in s] while len(str_reversed) != 0: char = str_reversed.pop() offset = 0 if (len(str_reversed) > 0): if ((char == "V" or char == "X") and str_reversed[-1] == "I"): str_reversed.pop() offset = -1 elif ((char == "L" or char == "C") and str_reversed[-1] == "X"): str_reversed.pop() offset = -10 elif ((char == "D" or char == "M") and str_reversed[-1] == "C"): str_reversed.pop() offset = -100 else: pass numerals.append(self.mapping.get(char, 0) + offset) return sum(numerals)
d257939403666c82af753e8f998c0e57102e1b01
Ashi-s/coding_problems
/DevPost/fb_sorted_square.py
511
3.796875
4
''' Input: a sorted array Output: Squared sorted array O(n) complexity e.g = [-6,-4,1,2,3,5] output: [1,4,9,16,25,36] ''' def sorted_square(s): if s == []: return "Invalis" n = len(s) low = 0 high = n-1 out = [0]*n while n > 0 : if abs(s[low]) > abs(s[high]): out[n-1] = s[low] * s[low] low += 1 else: out[n-1] = s[high] * s[high] high -= 1 n -= 1 return out print(sorted_square([-6,-4,1,2,3,5]))
1b8f4ea067ebc66d450ba92d32d9cb862596a3b5
jketo/arcusysdevday2015
/team2/python/rasacalculator.py
909
3.609375
4
#!/usr/bin/env python import argparse def calculate_file_rasa(file_path): row_count = 0 multiplier = 1 rasa = 0 for line in open(file_path): row_count += 1 for char in line: if char == '{': multiplier += 1 if char == ';': rasa += multiplier if char == '}': multiplier -= 1 return (row_count, rasa) def main(args): total_rows = 0 total_rasa = 0 for file_path in args.argument: row_count, rasa = calculate_file_rasa(file_path) total_rows += row_count total_rasa += rasa print '%s: lines %d, RaSa: %d' % (file_path, row_count, rasa) print 'total: lines %d, RaSa: %d' % (total_rows, total_rasa) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('argument', nargs='*') main(parser.parse_args())
95f2e1d452678a302fb1b3052730ac55864b31bf
hacktoolkit/code_challenges
/project_euler/python/056.py
684
3.671875
4
"""http://projecteuler.net/problem=056 Powerful digit sum A googol (10^100) is a massive number: one followed by one-hundred zeros; 100^100 is almost unimaginably large: one followed by two-hundred zeros. Despite their size, the sum of the digits in each number is only 1. Considering natural numbers of the form, a^b, where a, b < 100, what is the maximum digital sum? Solution by jontsai <hello@jontsai.com> """ from utils import * EXPECTED_ANSWER = 972 max_so_far = 0 for a in xrange(1, 100): for b in xrange(1, 100): value = a ** b max_so_far = max(sum_digits(value), max_so_far) answer = max_so_far print 'Expected: %s, Answer: %s' % (EXPECTED_ANSWER, answer)
531b202e0b2ba20e2321c824c4b4330c794b6114
sdamashek/gb500
/stack.py
377
3.71875
4
pointer = -1 stack = [] def push(value): global pointer """ Push to top of stack """ stack.append(value) pointer += 1 def pop(index=hex(pointer)): # Pop the passed index of the stack, or pop the top value return stack[hextopointer(index)] def hextopointer(value): """ Convert hex pointer for stack to array index """ return int(value, 16)
56a0f0e3f45bebd27a3c6c71f5fb43a25bb6628b
YCJGG/Leet-Code
/JGG/twoSum_2.py
1,080
3.828125
4
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def addTwoNumbers(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ re = ListNode(0) carry = 0 l3 = re while(l1 or l2): x = l1.val if l1 else 0 y = l2.val if l2 else 0 s = x + y + carry carry = s // 10 l3.next = ListNode(s%10) l3 = l3.next if(l1!=None): l1 = l1.next if(l2!=None): l2 = l2.next if carry > 0 : l3.next = ListNode(1) return re.next # 链表法 # 套路: (1) 先定义一个空链表re作为返回值 # (2) re 链表 next 指向最后的结果 # (3) 链表循环 --> while # (4) 循环里每一次都需要定义l3.next = ListNode(s%10) l3 = l3.next # (5) 边界判定 最后carry>0时, 最后增加一位
6bee0f8b6331a842fc49b92c8cc3b39eaf684e6b
0xJinbe/Exercicios-py
/Ex 002.py
755
3.578125
4
"""Faça um Programa que pergunte quanto você ganha por hora e o número de horas trabalhadas no mês. Calcule e mostre o total do seu salário no referido mês, sabendo-se que são descontados 11% para o Imposto de Renda, 8% para o INSS e 5% para o sindicato, faça um programa que nos dê: salário bruto. quanto pagou ao INSS. quanto pagou ao sindicato. o salário líquido.""" ganho_hr = float(input('Quanto se ganha por hora? ')) qt_hrs = float(input('Quantas horas sao trabalhadas por mẽs? ')) bruto = ganho_hr*qt_hrs print(bruto) ir = (bruto*0.11) inss = (bruto*0.08) sindicato = (bruto*0.05) liquido = bruto-ir-inss-sindicato print('Seu sal bruto é: ', bruto, 'Descontos: IR-INSS-sindicato:', ir,inss,sindicato, 'Sal liquido é: ', liquido )
f17701647e9f6a0d93746f30b5c9c6f0d5d4a36d
XuYiwen/Machine-Learning
/hw4/NN.py
9,723
4.0625
4
''' A 3 layer neural network (input layer, hidden layer, output layer) for MNIST dataset ''' import random import numpy as np import NN_functions as nf from numpy import argmax """ Initializes and returns an instance of the NN class. Parameters: -domain: one of ['mnist', 'circles'] -batch_size: the number of examples to consider for each batch update -learning rate: the gradient descent learning rate -activation function: one of ['tanh', 'relu'] -hidden_layer_width: the number of nodes to include in the hidden layer """ def create_NN(domain, batch_size, learning_rate, activation_function, hidden_layer_width): if domain == 'mnist': input_size = 784 elif domain == 'circles': input_size = 2 else: raise Exception('Domain must be one of [mnist, circles]') layer_sizes = [input_size, hidden_layer_width, 2] #input, hidden, output layer sizes iterations = 100 if activation_function == 'tanh': input_activation_func = nf.tanh output_func = nf.tanh activation_func_derivative = nf.tanh_derivative output_func_derivative = nf.tanh_derivative elif activation_function == 'relu': input_activation_func = nf.relu output_func = nf.relu activation_func_derivative = nf.relu_derivative output_func_derivative = nf.relu_derivative else: raise Exception('Activation function not recognized: %s' % activation_function) return NN(batch_size, iterations, learning_rate, layer_sizes, activation_func=input_activation_func, output_func=output_func, activation_func_derivative=activation_func_derivative, output_func_derivative=output_func_derivative) class NN (): def __init__ (self, batch_size, iterations, learning_rate, sizes = [], activation_func = None, output_func = None, activation_func_derivative = None, output_func_derivative = None, loss_func_derivative = None): self.layers = len(sizes) self.sizes = sizes self.batch_size = batch_size self.iterations = iterations self.learning_rate = learning_rate if activation_func is None: self.activation_func = nf.sigmoid else: self.activation_func = activation_func if output_func is None: self.output_func = nf.sigmoid else: self.output_func = output_func if activation_func_derivative is None: self.activation_func_derivative = nf.sigmoid_derivative else: self.activation_func_derivative = activation_func_derivative if output_func_derivative is None: self.output_func_derivative = nf.sigmoid_derivative else: self.output_func_derivative = output_func_derivative if loss_func_derivative is None: self.loss_func_derivative = nf.squared_loss_gradient else: self.loss_func_derivative = loss_func_derivative #### Initialization of Parameters ##### ''' List of bias arrays per layer (starts from the first hidden layer) ''' self.biases = [0.01*np.ones((y, 1)) for y in sizes[1:]] ''' List of weight matrices per layer (starts from the (input - first hidden layer) combo) Each row of the matrix corresponds to input weights for 1 target hidden unit ''' self.weights = [np.sqrt(2/x)*np.random.randn(y, x) for x, y in zip(sizes[:-1], sizes[1:])] #endDef def transform_data(self, data, is_train): new_training_data = [] for x,y in data: new_x = x.reshape((len(x),1)) if is_train: new_y = np.zeros((2,1)) new_y[y] = 1 else: new_y = y new_training_data.append((new_x, new_y)) return new_training_data def train (self, training_data): num_train = len(training_data) training_data = self.transform_data(training_data, True) print "Training NN:" for j in xrange(self.iterations): if (j%30 == 0): print "\tTraining step %d"%j #random shuffling of the training dataset at the start of the iteration random.shuffle(training_data) mini_batches = [training_data[k : k + self.batch_size] for k in xrange(0, num_train, self.batch_size)] for mini_batch in mini_batches: self.update_mini_batch(mini_batch, self.learning_rate) #endFor ###Done making 1 pass over the entire dataset### #endFor transformed_training_data = [] for (x,y) in training_data: true_label = argmax(y) transformed_training_data.append((x, true_label)) return self.evaluate(transformed_training_data) #endDef def train_with_learning_curve(self, training_data): num_train = len(training_data) test_training_data = training_data training_data = self.transform_data(training_data, True) learning_curve_data = [] for j in xrange(self.iterations): if j%10 == 0: print "Training step %d"%j #random shuffling of the training dataset at the start of the iteration random.shuffle(training_data) mini_batches = [training_data[k : k + self.batch_size] for k in xrange(0, num_train, self.batch_size)] for mini_batch in mini_batches: self.update_mini_batch(mini_batch, self.learning_rate) #endFor ###Done making 1 pass over the entire dataset### learning_curve_data.append((j+1, self.evaluate(test_training_data))) print learning_curve_data[-1] #endFor transformed_training_data = [] return learning_curve_data def update_mini_batch (self, mini_batch, l_rate): grad_b_accumulated = [np.zeros(b.shape) for b in self.biases] grad_w_accumulated = [np.zeros(w.shape) for w in self.weights] #Accumulate the gradients over the mini batches for x, y in mini_batch: #use backpropagation to calculate the gradients grad_b, grad_w = self.backprop(x, y) grad_b_accumulated = [nb + dnb for nb, dnb in zip(grad_b_accumulated, grad_b)] grad_w_accumulated = [nw + dnw for nw, dnw in zip(grad_w_accumulated, grad_w)] #endFor #Update the parameters self.weights = [w - (l_rate/len(mini_batch)) * grad_w for w, grad_w in zip(self.weights, grad_w_accumulated)] self.biases = [b - (l_rate/len(mini_batch)) * grad_b for b, grad_b in zip(self.biases, grad_b_accumulated)] #endDef def feedforward (self, x): a = x for b, w in zip(self.biases[: -1], self.weights[: -1]): a = self.activation_func(np.dot(w, a) + b) #endFor b_last = self.biases[-1] w_last = self.weights[-1] y = self.output_func(np.dot(w_last, a) + b_last) return y #endDef def backprop (self, x, y): grad_b = [np.zeros(b.shape) for b in self.biases] grad_w = [np.zeros(w.shape) for w in self.weights] ####### Forward Pass ####### a = x As = [a] # list to store all the activations, layer by layer Zs = [] # list to store all the z vectors, layer by layer for b, w in zip(self.biases[:-1], self.weights[:-1]): z = np.dot(w, a) + b Zs.append(z) a = self.activation_func(z) As.append(a) #endfor b_last = self.biases[-1] w_last = self.weights[-1] z = np.dot(w_last, a) + b_last Zs.append(z) a = self.output_func(z) As.append(a) ####### Backward Pass ####### #Last layer delta = self.loss_func_derivative(As[-1], y) * self.output_func_derivative(Zs[-1]) grad_b[-1] = delta grad_w[-1] = np.dot(delta, As[-2].transpose()) #Back Passes -- Remember, 1st layer is the input layer for l in xrange(2, self.layers): z = Zs[-l] sp = self.activation_func_derivative(z) delta = np.dot(self.weights[-l+1].transpose(), delta) * sp grad_b[-l] = delta grad_w[-l] = np.dot(delta, As[-l-1].transpose()) #endFor return (grad_b, grad_w) #endDef def evaluate (self, test_data): n_test = len(test_data) test_data = self.transform_data(test_data, False) #O-1 error with the argmax value test_results = [(np.argmax(self.feedforward(x)), y) for (x, y) in test_data] correct = sum(int(x == y) for (x, y) in test_results) return correct*100/float(n_test) #endDef #endClass
4df8752e45e5a7a7495e6f354484ec306f96b396
RaymondDashWu/tweet-generator
/histogram.py
5,299
3.5
4
import re import sys import random def read_sterilize_source(source_text): """Filters out all punctuation and white space (line breaks + spaces) using regex and substitutes with a space " ". Then splits into array Updated for edge cases '. Now keeps words that use ' as part of word (I've, haven't, etc.)""" #temporarily uncommented for nth order markov with open(source_text) as file: source = file.read() filtered = re.sub(r'\W*[^\'\w+\']', " ", source).split() return filtered # TODO: REFACTOR TO ACCOUNT FOR SENTENCES. IMPORTANT FOR MARKOV CHAINS def unique_words(filtered): """Finds unique words. Intended to take in the words from read_sterilize_source results""" # Updated to account for uppercase letters by lowering all of them unique = [] for word in filtered: if word not in unique: unique.append(word) return unique def frequency(unique, filtered): """Finds out how often each unique word is used and putting them all in a dictionary""" words_dict = {} for unique in filtered: if unique in words_dict: words_dict[unique] += 1 else: words_dict[unique] = 1 return words_dict def frequency_list_of_list(unique, filtered): """UNUSED. Only for class assignment. Finds out how often each unique word is used and putting them all in a list""" listoflists = [] for entry in unique: counter = 0 for index in filtered: if entry == index: counter += 1 listoflists.append([entry, counter]) return listoflists def frequency_list_of_tuples(unique, filtered): """UNUSED. Only for class assignment. Finds out how often each unique word is used and putting them all in a tuple""" listoftuples = [] for entry in unique: counter = 0 for index in filtered: if entry == index: counter += 1 listoftuples.append((entry, counter)) return listoftuples def pick_random_word(words_list): rand_index = random.randint(0, len(words_list) - 1) return words_list[rand_index] def random_word_tester(words_list): total_random_picked = 0 tmp_dict = {} while total_random_picked < 10000: rand_word = pick_random_word(words_list) if rand_word in tmp_dict: tmp_dict[rand_word] += 1 else: tmp_dict[rand_word] = 1 total_random_picked += 1 return tmp_dict def stochastic_sampling(words_dict): """Calculates total values of all words in dictionary, and then calculates percentages to total 100%. Ex: {'one': 1, 'fish': 4, 'two': 1, 'red': 1, 'Blue': 1, 'l': 1} one: 1/9 fish: (1+4)/9 two: (1+4+1)/9 ... Afterwards chooses a random # using random.random() and picks which # is in the range of generated #""" dict_value_totals = 0 total_percentage = 0 tmp_dict = {} for value in words_dict: dict_value_totals += words_dict[value] for value in words_dict: new_value = words_dict[value]/dict_value_totals total_percentage += new_value tmp_dict[value] = total_percentage random_picker = random.random() for value in tmp_dict: if tmp_dict[value] >= random_picker: return value def multiple_stochastic_sampling(words_dict): """Same as stochastic sampling except tested for randomness 10000x""" total_random_picked = 0 dict_value_totals = 0 total_percentage = 0 tmp_percent_dict = {} tmp_dict = {} while total_random_picked < 10000: word = stochastic_sampling(words_dict) if word not in tmp_dict: tmp_dict[word] = 1 else: tmp_dict[word] += 1 total_random_picked += 1 return tmp_dict if __name__ == "__main__": #uncomment to test file # with open("fish.txt", "r") as file: # source = file.read() # removes symbols, punctuation, etc. from source text and puts in array sterilized_source = read_sterilize_source(source) # retrieves uniques from above sterilized source sterilized_source_uniques = unique_words(sterilized_source) # counts the instances of uniques in sterilized source text sterilized_source_frequency = frequency(sterilized_source_uniques, sterilized_source) # corpus_length = sum(filtered.values()) # destination = random.randint(0, corpus_length) # for word in histogram: # destination = destination - histogram[word] # if destination < 0: # return word # return filtered[random.randint(0,len(filtered) - 1)] """ # one fish two fish blue fish red fish clean_txt_list = read_sterilize_source("text-corpus.txt") print(clean_txt_list) unique_words_list = unique_words(clean_txt_list) print(unique_words_list) # print(frequency(unique_words("text-corpus.txt"),read_sterilize_source("text-corpus.txt"))) freq = frequency(unique_words_list, clean_txt_list) print(freq) # print(multiple_stochastic_sampling(freq)) # print(random_word_tester(sterilized_source)) # print(stochastic_sampling(freq)) print(multiple_stochastic_sampling(freq)) # toki-pona-the-egg.txt # print(frequency(unique_words("toki-pona-the-egg.txt"),read_sterilize_source("toki-pona-the-egg.txt"))) """
4615b36c7005248fc1566367325dc8e73daaff8d
Tuchev/Python-Fundamentals---january---2021
/08.Text_Processing/02.Text_Processing_-_Exercise/05. Emoticon Finder.py
126
3.828125
4
text = input() for index in range(len(text)): if text[index] == ":": print(f"{text[index]}{text[index + 1]}")
35644a547148decd7e8545dd8c93e88a5b6ef5c8
TahaKhan8899/Coding-Practice
/LeetCode/assignEmployeesToEmails.py
1,545
3.546875
4
def solution(S, C): emailList = [] personInfo = [] emailDict = {} finalStr = "" #parse string S: s = S.split('; ') print(s) prefix = "" #read fname, mid(if possible) and last into an array for name in s: fullName = name.split() #mid name if len(fullName) > 2: c1 = fullName[0][0].lower() c2 = fullName[1][0].lower() c3 = fullName[2].lower() if "-" in c3: c3 = c3.replace("-", "") prefix = c1 + "_" + c2 + "_" + c3 #no midname else: c1 = fullName[0][0].lower() c2 = fullName[1].lower() prefix = c1 + "_" + c2 #create email and add count to dictionary email = prefix + "@" + C.lower() + ".com" #check for duplicate emails if email in emailDict: num = emailDict[email] + 1 emailDict[email] += 1 email = prefix + str(num) + "@" + C.lower() + ".com" else: emailDict[email] = 1 emailList.append(email) for i in range(0, len(emailList)): if i == len(emailList) - 1: thing = s[i].lower() + " <" + emailList[i] + ">" finalStr = finalStr + thing else: thing = s[i].lower() + " <" + emailList[i] + ">; " finalStr = finalStr + thing return(finalStr) print(solution("John Doe; Peter Parker; Mary Jane Watson-Parker; James Doe; John Elvis Doe; Jane Doe; Penny Parker", "Example"))
8281791c98b8adb1191e97a3473dbcb561e1ca87
Ngiong/Indonesian_Parser
/python/src/parsetree/WordToken.py
361
3.53125
4
class WordToken(object): def __init__(self, word, tag): self.WORD = word self.TAG = tag def __str__(self): return self.WORD + "#" + self.TAG def __eq__(self, other): return self.WORD == other.WORD and self.TAG == other.TAG def __hash__(self): return hash((self.WORD, self.TAG)) __repr__ = __str__
0151374f9d500bb496cdb6f6a29b9a790eba9955
SimasRug/Learning_Python
/Chapter3/D1.py
1,867
4.1875
4
def weight(): print('For converting pounds to grams enter 1') selection = int(input('For converting grams to punds enter 2: \n')) if selection == 1: pounds = float(input('Input pounds: ')) total = pounds * 453.59 print(pounds,' pounds are ',total, 'grams') else: grams = float(input('Input grams: ')) total = format(grams / 453.59, '.4f') print(grams,' grams are ',total, 'pounds') def distance(): print('Do you want to convert short or long distances?') choice = input('S for short L for long: ') if choice == 'S': print('For converting inches to centimeters enter 1') selection = int(input('For converting centimeters to inches enter 2: \n')) if selection == 1: inches = float(input('Input inches: ')) total = inches * 2.54 print(inches,' inches are ',total, 'centimeters') elif selection == 2: cm = float(input('Input centimeters: ')) total = format(cm / 2.54, '.4f') print(cm,' centimeters are ',total, 'inches') elif choice == 'L': print('For converting kilometers to miles enter 1') selection = int(input('For converting miles to kilometers enter 2: \n')) if selection == 1: km = float(input('Input kilometers: ')) total = km / 1.6 print(km,' kilometers are ',total, 'miles') elif selection == 2: miles = float(input('Input miles: ')) total = miles * 1.6 print(miles,' miles are ',total, 'kilometers') print('What do you want ot convet?') choice = input('For weight enter W for distance enter D: ') while choice not in ('W', 'D'): choice = input('For weight enter W for distance enter D: ') if choice == 'W': weight() elif choice == 'D': distance()
2098d8b056fca130d1c25ac89b695d5a83fb022b
Scott-Larsen/LeetCode
/383-RansomNote.py
594
3.59375
4
# Given an arbitrary ransom note string and another string containing letters # from all the magazines, write a function that will return true if the ransom # note can be constructed from the magazines ; otherwise, it will return false. # # Each letter in the magazine string can only be used once in your ransom note. class Solution: def canConstruct(self, ransomNote: str, magazine: str) -> bool: magazine = list(magazine) for char in ransomNote: try: magazine.remove(char) except: return False return True
00420cdc2c6f7b2af868d701540ed396b7947862
etkinpinar/ScriptProgramming
/Script_B.py
556
4.0625
4
################## METADATA ################## # NAME: Etkin Pınar # USERNAME: a18etkpi # COURSE: Scriptprogramming IT384G - Spring 2019 # ASSIGNMENT: Assignment 1 - Python # DATE OF LAST CHANGE: 2019-04-09 ############################################## number = input("Enter a number: ") while number: if int(number) > 42: print("Your number is greater than 42.") elif int(number) < 42: print("Your number is less than 42.") else: print("Your number is exactly 42.") number = input("Enter a number: ")
abeee2b124cb5c0a6bf881b5ab8a0c2cd864ad40
alekseyzelepukin/python_algorithms_and_data_structures
/lesson_03/scripts/exercise_06.py
907
3.625
4
# 6. В одномерном массиве найти сумму элементов, находящихся между минимальным и максимальным элементами. # Сами минимальный и максимальный элементы в сумму не включать. from random import randint from typing import List if __name__ == '__main__': n: int = 4 arr: List = [randint(0, 9) for _ in range(n)] min_idx: int = 0 max_idx: int = 0 for i in range(1, n): if arr[i] < arr[min_idx]: min_idx = i elif arr[i] > arr[max_idx]: max_idx = i if min_idx > max_idx: min_idx, max_idx = max_idx, min_idx amount: int = 0 for i in range(min_idx+1, max_idx): amount += arr[i] print(f'Массив элементов: {arr}') print(f'Сумма элементов: {amount}')
330850e867dc75950fe84d9784e354dd6694bbc9
Amansingh1811/Programing-Interview-Questions-
/Main.py
491
3.921875
4
import majority_number as m import array_length as a import convertToIntArray as c promptStr = "Please enter your value: " userstring = input(promptStr) arrLen: int = a.lengthofarray(userstring) print("your array length is ", arrLen) m.findMajority(userstring) arrtype = userstring.split(",") intArr = c.convertToIntArray(arrtype) print("Int Array: ", intArr); nthNumber = int(input("enter your nth number: ")) nn = m.printmNnumber(intArr, nthNumber) print("your nth number is ", nn)
ab969509e22cb710602874ce99b48fa722854989
QuentinDuval/PythonExperiments
/linked/Node.py
870
3.515625
4
class Node: def __init__(self, val): self.val = val self.next = None @classmethod def from_list(cls, xs): if not xs: return None h = Node(xs[0]) t = h for x in xs[1:]: curr = Node(x) t.next = curr t = curr return h ''' class Iterator: def __init__(self, node): self.node = node def __next__(self): if self.node is None: raise StopIteration val = self.node.val self.node = self.node.next return val def __iter__(self): return self.Iterator(self) ''' def __iter__(self): curr = self while curr is not None: yield curr.val curr = curr.next def to_list(self): return list(self)
0c9ed9bcf7b678025daf8192a4cba3a31dec737c
leezzx/Baekjun-Study-Python
/입출력과사칙연산.py
1,611
3.515625
4
# 2557 Hello World print('Hello World!') # 10718 We love kriii print('강한친구 대한육군\n강한친구 대한육군') # \n으로 엔터역할 # 10171 고양이 print('''\\ /\\''') print(''' ) ( ')''') print('''( / )''') print(''' \\(__)|''') # 10172 개 print('''|\_/|''') print('''|q p| /}''') print('''( 0 )\"\"\"\\''') print('''|\"^\"` |''') print('''||_/=\\\\__|''') # 1000 A+B A, B = input().split() # 입력되는 문자를 input()함수로 입력받고, split()함수로 나누어 A, B에 저장 print(int(A) + int(B)) # int()함수로 A, B를 정수로 변환 뒤 합을 출력 # 1001 A-B A, B = input().split() print(int(A) - int(B)) # 10998 A×B A, B = map(int, input().split()) # map함수를 통해 int변환을 먼저함 print(A * B) # 1008 A/B A, B = map(int, input().split()) print(A / B) # 10869 사칙연산 A, B = map(int,input().split()) print(A + B) print(A - B) print(A * B) print(int(A / B)) # 나누어떨어지지 않을 때 float형으로 출력됨, 고로 int 처리 print(A % B) # 10430 나머지 A, B, C = map(int, input().split()) print((A + B) % C) print(((A % C) + (B % C)) % C) print((A * B) % C) print(((A % C) * (B % C)) % C) # 2588 곱셈 a = int(input()) b = input() axb2 = a * int(b[2]) # []를 통해 원하는 자리의 문자 가져오기 axb1 = a * int(b[1]) axb0 = a * int(b[0]) axb = a * int(b) print(axb2, axb1, axb0, axb, sep='\n') # sep : 여러가지 출력할 때 값 사이사이에 들어갈 문자 지정
2dbe6427ba14b9247ffd799adae18885fff427aa
cavad2187/Neon
/math.py
651
3.90625
4
import math print("Neon K Proqramına Xoş Gəlmisiniz") a=int(input("a Əmsalını Qeyd Edin: ")) b = int(input("b Əmsalını Qeyd Edin: ")) c = int(input("Sərbəst Həddi Qeyd Edin: ")) d = (b*b)-(4*a*c) if (d>0): x1 = math.floor((-b - math.sqrt(d))/(2*a)) x2 = math.floor((-b + math.sqrt(d))/(2*a)) print("Diskliminat 0-dan Böyük Olduğuna Görə Tənliyin 2 Kökü Var.") print("Tənliyin Kökləri: ",x1,x2) elif (d==0): xb = math.floor((-b)/(2*a)) print("Diskliminat 0-a Bərabər Olduğuna Görə x1=x2") print("Tənliyin Kökü: ",xb) else: print("T'nliyin Kökü Yoxdur :(")
9eb03f9f587f6eba3c98de04236474e610058229
guyao/leetcode
/number-of-islands.py
2,272
3.515625
4
#Union Find class Solution(object): def numIslands(self, grid): """ :type grid: List[List[str]] :rtype: int """ if not any(grid): return 0 ht = len(grid) wd = len(grid[0]) uf = [i for i in range(ht*wd)] def find(x): p = uf[x] while p != uf[p]: p = uf[p] top = p t = -1 p = x while p != uf[p]: t = uf[p] uf[p] = top p = t return top def union(x, y): p_x, p_y = find(x), find(y) if p_x != p_y: uf[p_x] = p_y def index(x, y): return x*wd + y def search(x, y): for i, j in [(x+1, y), (x-1, y), (x, y+1), (x, y-1)]: if 0 <= i < ht and 0 <= j < wd: if grid[i][j] == "1": union(index(i, j), index(x, y)) for i in range(ht): for j in range(wd): if grid[i][j] == "1": search(i, j) for i in range(ht): for j in range(wd): if grid[i][j] == "1": find(i*wd+j) result = set() for i in range(ht): for j in range(wd): if grid[i][j] == "1": result.add(uf[index(i,j)]) return len(result) class Solution(object): def numIslands(self, grid): """ :type grid: List[List[str]] :rtype: int """ if not any(grid): return 0 ht = len(grid) wd = len(grid[0]) count = 0 m = [list(l) for l in grid] def dfs(i, j): if 0 <= i < ht and 0 <= j < wd and m[i][j] == "1": m[i][j] = "0" for ii, jj in [(i+1, j), (i-1, j), (i, j+1), (i, j-1)]: dfs(ii, jj) else: return for i in range(ht): for j in range(wd): if m[i][j] == "1": dfs(i, j) count += 1 return count t = ["11110","11010","11000","00000"] t = ["11000", "11000", "00100", "00011"] r = Solution().numIslands(t)
a58609aba69dcb376f6e9eb5cd64af054d57d3a5
Uthsavikp/Python_Data_Structures
/Dictionary_Programs/convert_list_to_nested_dictionary.py
680
4.15625
4
''' @Author: Uthsavi KP @Date: 2021-01-08 23:27:24 @Last Modified by: Uthsavi KP @Last Modified time: 2021-01-08 23:27:24 @Title: To convert a list into a nested dictionary of keys ''' class NestedDictionary: def get_nested_dictionary(self): """ converting list to nested dictionary using list comprehension """ list1 = ["abc", 'to', 'xyz'] list2 = ['good', 'better', 'best'] list3 = [2, 4, 6] nested_dictionary = [{a: {b: c}} for (a, b, c) in zip(list1, list2, list3)] print("Nested dictionary :",nested_dictionary) if __name__ == "__main__": nested_dict = NestedDictionary() nested_dict.get_nested_dictionary()
c6b5a909f074c4547040155ca17f876848adfb6c
jamiedotpro/etc
/tf/tf21_rnn2_1to100.py
2,219
3.75
4
# 1 ~ 100 까지의 숫자를 이용해서 6개씩 잘라서 rnn 구성 # train, test 분리할 것 # 1,2,3,4,5,6 : 7 # 2,3,4,5,6,7 : 8 # 3,4,5,6,7,8 : 9 # ... # 94,95,96,97,98,99 : 100 # predict: 101 ~ 110까지 예측하시오. # 지표 RMSE import numpy as np def split_n(seq, size): aaa = [] for i in range(len(seq) - size + 1): subset = seq[i:(i+size)] aaa.append([item for item in subset]) print(type(aaa)) return np.array(aaa) data = np.array([i for i in range(1, 101)]) dataset = split_n(data, 7) x = dataset[:, :6] y = dataset[:, 6:] # ...Scaler 사용해서 정규화 from sklearn.preprocessing import StandardScaler, MinMaxScaler scaler = StandardScaler() # scaler = MinMaxScaler() scaler.fit(x) x = scaler.transform(x) from sklearn.model_selection import train_test_split x_train, x_test, y_train, y_test = train_test_split(x, y, random_state=66, test_size=0.2) x_train = x_train.reshape(-1, 6, 1) x_test = x_test.reshape(-1, 6, 1) from keras.models import Sequential from keras.layers import Dense, LSTM model = Sequential() model.add(LSTM(32, input_shape=(6, 1), return_sequences=True)) model.add(LSTM(4)) model.add(Dense(64, activation='relu')) model.add(Dense(32, activation='relu')) model.add(Dense(8, activation='relu')) model.add(Dense(1, activation='relu')) model.summary() model.compile(loss='mse', optimizer='adam', metrics=['mse']) from keras.callbacks import EarlyStopping early_stopping = EarlyStopping(monitor='loss', patience=15, mode='auto') model.fit(x_train, y_train, epochs=500, batch_size=1, verbose=1, callbacks=[early_stopping]) # 4. 평가 loss, acc = model.evaluate(x_test, y_test) y_predict = model.predict(x_test) print('loss: ', loss) # print('acc: ', acc) # RMSE 구하기 from sklearn.metrics import mean_squared_error def RMSE(ytest, y_predict): return np.sqrt(mean_squared_error(y_test, y_predict)) print('RMSE : ', RMSE(y_test, y_predict)) # 낮을수록 좋음 test_data = np.array([i for i in range(101, 111)]) test_dataset = split_n(test_data, 6) # print(test_dataset) test_dataset = scaler.transform(test_dataset) test_dataset = test_dataset.reshape(-1, 6, 1) y_predict = model.predict(test_dataset) print(y_predict)
4e2f1535de3b2ff70375800a05b837368ae2066f
mhaut/pythonExamples
/ASR_audioExample/ASR.py
3,699
3.515625
4
import pyaudio import wave import audioop from collections import deque import os import urllib2 import urllib import time import json def listen_for_speech(): """ Does speech recognition using Google's speech recognition service. Records sound from microphone until silence is found and save it as WAV and then converts it to FLAC. Finally, the file is sent to Google and the result is returned. """ #config chunk = 1024 FORMAT = pyaudio.paInt16 CHANNELS = 1 RATE = 16000 THRESHOLD = 180 #The threshold intensity that defines silence signal (lower than). SILENCE_LIMIT = 2 #Silence limit in seconds. The max ammount of seconds where only silence is recorded. When this time passes the recording finishes and the file is delivered. #open stream p = pyaudio.PyAudio() stream = p.open(format = FORMAT, channels = CHANNELS, rate = RATE, input = True, frames_per_buffer = chunk) print "* listening. CTRL+C to finish." all_m = [] data = '' SILENCE_LIMIT = 2 rel = RATE/chunk slid_win = deque(maxlen=SILENCE_LIMIT*rel) started = False while (True): data = stream.read(chunk) slid_win.append (abs(audioop.avg(data, 2))) if(True in [ x>THRESHOLD for x in slid_win]): if(not started): print "starting record" started = True all_m.append(data) elif (started==True): print "finished" #the limit was reached, finish capture and deliver filename = save_speech(all_m,p) stt_google_wav(filename) #reset all started = False slid_win = deque(maxlen=SILENCE_LIMIT*rel) all_m= [] print "listening ..." print "* done recording" stream.close() p.terminate() def save_speech(data, p): filename = 'output_'+str(int(time.time())) # write data to WAVE file data = ''.join(data) wf = wave.open(filename+'.wav', 'wb') wf.setnchannels(1) wf.setsampwidth(p.get_sample_size(pyaudio.paInt16)) wf.setframerate(16000) wf.writeframes(data) wf.close() return filename def stt_google_wav(filename): #Convert to flac os.system(FLAC_CONV+ filename+'.wav') f = open(filename+'.flac','rb') flac_cont = f.read() f.close() key = "" #YOUR API KEY HERE googl_speech_url = 'https://www.google.com/speech-api/v2/recognize?&lang=en-US&key=%s' % key hrs = {"User-Agent": "Mozilla/5.0 (X11; Linux i686) AppleWebKit/535.7 (KHTML, like Gecko) Chrome/16.0.912.63 Safari/535.7",'Content-type': 'audio/x-flac; rate=16000'} req = urllib2.Request(googl_speech_url, data=flac_cont, headers=hrs) p = urllib2.urlopen(req) temp = p.read() s = temp.split("\n") if len(s) > 1: try: res = json.loads(s[1]) if "result" in res: if len(res['result']) > 0: if 'alternative' in res['result'][0]: if len(res['result'][0]['alternative']) > 0: if 'transcript' in res['result'][0]['alternative'][0]: transcription = res['result'][0]['alternative'][0]['transcript'] else: transcription = "" else: transcription = "" else: transcription = "" else: transcription = "" else: transcription = "" print "Transcription: %s" % transcription map(os.remove, (filename+'.flac', filename+'.wav')) except ValueError: print "No JSON to be parsed. No result" else: print "No result" FLAC_CONV = 'flac -f ' # We need a WAV to FLAC converter. if(__name__ == '__main__'): listen_for_speech()
206bd6db2d53bba97dd58e293bdd5556286587c3
LeoTod/learning_python
/learn_python_freecodecamp/mad_libs_game.py
347
3.734375
4
adjective1 = input("Enter an adjective: ") adjective2 = input("Enter another adjective: ") type_of_bird = input("Enter a type of bird: ") room = input("Enter a room: ") print("It was a " + adjective1 + ", cold November day. ") print("I woke up to the " + adjective2 + " smell of " + type_of_bird) print("roasting in the " + room + " downstairs.")
6abb80247985baec5f013fb024551aeaf7fc948a
PythonicNinja/elliot-test
/utils/reverse.py
460
3.90625
4
from math import log10 def how_many_digits(number): return int(log10(number)) def reverse_num(value): if not isinstance(value, int): raise ValueError( 'Unexpected value for reverse_num which requires integers. ' 'Passed type = %s', type(value)) if -10 < value < 10: return value last_digit = value % 10 rest = value // 10 return last_digit * 10 ** how_many_digits(value) + reverse_num(rest)
86c4bde551158d82ab181405efd726176774ed17
WagnerSF10/curso_intensivo_python
/python_work/chapter7/rollercoaster.py
169
4
4
height = input("Qual a sua altura, em metros? ") height = float(height) if height >= 1.70: print("\nVoce tem altura ideal!") else: print("Altura insuficiente!")
3703ef62dff7a995d12405b589dc362ed8dd90bd
nnur/Cracking-the-Coding-Interview-in-Python
/linkedLists/2-5.py
1,174
4.03125
4
from LinkedList import LinkedList def add_linked_lists(list1, list2): list3 = LinkedList() p1 = list1.head p2 = list2.head numbers_to_add = [] position = 0 while True: if p2 and p1: numbers_to_add.append(p1.data*10**position + p2.data*10**position) p2 = p2.next_node p1 = p1.next_node elif p1: # if p2 is the shorter number numbers_to_add.append(p1.data*10**position) p1 = p1.next_node elif p2: numbers_to_add.append(p2.data*10**position) p2 = p2.next_node else: break position += 1 return create_sum_list(numbers_to_add) def create_sum_list(numbers_to_add): sum_ = 0 for number in numbers_to_add: sum_ += number str_sum = str(sum_) backward_number_list = [int(i) for i in str_sum[::-1]] result_list = LinkedList() for number in backward_number_list: result_list.append_to_tail(number) return result_list #testing list1 = LinkedList() list2 = LinkedList() # filling the linked list data2 = [7, 1] data1 = [5, 9, 8] for value in data2: list2.append_to_tail(value) for value in data1: list1.append_to_tail(value) print(add_linked_lists(list1, list2))
8555fd529d1cd8fb0329fc0f88c3cc0f499c7a2c
shinysu/test
/Q2.py
363
3.828125
4
def is_multiples(l): return [(((num % 3) == 0) or ((num % 5) == 0)) for num in l] def is_multiple(n): if ((n % 3) == 0) and ((n % 5) == 0): return "GraphQL" elif (n % 3) == 0: return "Graph" elif (n % 5) == 0: return "QL" print(is_multiples([1,2,3,4])) print(is_multiple(3)) print(is_multiple(5)) print(is_multiple(15))
92e466ce9fbf44153b824dc46c9439d5849d7466
Sandhie177/CS5690-Python-deep-learning
/ICP3/codon.py
948
3.875
4
import csv #imoprting library i=1 while i%3 !=0: string=input('Give the sequence of DNA:') i=len(string) if i%3 !=0: print ('Sequence is invalid. Give the Sequence Again') #if there is a sequence #with 1 or 2 characters it can't process list1=[] #creating empty list dict1={} for x in range(i): if x%3==0: list1.append(string[x:x+3]) #spliting the string by 3 elements and keeping them in list1 for x in range(len(list1)): with open('codon.tsv') as tsvfile: reader = csv.reader(tsvfile, delimiter='\t') for row in reader: if list1[x] in row: if row[1] in dict1: dict1[row[1]] +=1 #counts the number of each codon sequense else: dict1[row[1]] =1 print (dict1) #list1=[i for i in string] #print (list(list1))
a3d023460b9a6dd915ee9129a128325fef966a7a
devmanner/security
/bin/anonymize_hashfile.py
1,416
3.8125
4
#!/usr/bin/python import sys import re from coolname import generate_slug if len(sys.argv) != 7: print("Script to anonymize a list of usernames and hashes. Good step to do when auditing passwords.") print("Usage: anonymize_hashfile.py file_with_hashes_and_names user_field hash_field delimiter user_output_file hash_output_file") print(" file_with_hashes_and_names: Input file. Typically the output of ushadow.") print(" user_field: 0-counted field number in file_with_hashes_and_names that contains username") print(" hash_field: 0-counted field number in file_with_hashes_and_names that contains password hash") print(" delimiter: Character used to split the fields in file_with_hashes_and_names. Same char is used as separator in output") print(" user_output_file: Output file that will contain user[delimiter]random_name") print(" hash_output_file: Output file that will contain random_name[delimiter]hash") exit(-1) fname_in = sys.argv[1]; usrf = sys.argv[2]; hashf = sys.argv[3]; delim = sys.argv[4]; fname_users = sys.argv[5]; fname_hashes = sys.argv[6]; fh_in = open(fname_in, "r") fh_users = open(fname_users, "w"); fh_hashes = open(fname_hashes, "w"); for line in fh_in: l = re.split(delim, line); rnd_name = generate_slug(4) fh_users.write(l[int(usrf)] + delim + rnd_name +"\n") fh_hashes.write(rnd_name + delim + l[int(hashf)]) fh_in.close() fh_users.close() fh_hashes.close()
df74aa1a255a124f1a7cd6486e38c30c266e8f57
isabellahenriques/Python_Estudos
/ex068.1.py
1,205
4.0625
4
''' Faça um programa que jogue par ou ímpar com o computador. O jogo só será interrompido quando o jogador perder, mostrando o total de vitórias consecutivas que ele conquistou no final do jogo.''' from random import randint print("=+" * 20) print("Vamos jogar Par ou Impar") print("=+" * 20) while True: numeroJogador = int(input("Digite um valor entre 0 e 10: ")) jogador = str(input("Par ou Ímpar? [P/I]: ")).upper().strip()[0] computador = randint(0,10) jogada = numeroJogador + computador print(f"O computador escolheu: {computador}") print(f"O jogador escolheu: {numeroJogador}") print(f"A soma é {numeroJogador} + {computador} = {jogada}") if (jogada % 2 == 0) and jogador == "P": print("Deu PAR - Você ganhou!") elif (jogada % 2 == 0 ) and jogador == "I": print("DEU PAR - Você perdeu!") elif (jogada % 2 != 0) and jogador == "I": print("DEU ÍMPAR - Você Ganhou!") else: print("DEU ÍMPAR - Você perdeu!") continuar = " " while continuar not in "SN": continuar = str(input("Quer continuar: [S/N] ")).upper()[0].strip() if continuar == "N": break print("Volte Sempre!")
8f6a348e6c9f6b9bee57d0c27ebbfae82adbdd3b
iluy420/Qwiz
/Python/pr_2_2.py
1,941
3.640625
4
import sqlite3 import string def in_base (cursor): list_staff=[(1,'Костиков','1977-02-05','Специалист'),(2,'Рой','1977-11-15','Специалист'),(3,'Пестов','1975-11-11','Председатель ПЦК'),(4,'Ожигова','1976-07-24','Специалист')] cursor.executemany("INSERT INTO staff VALUES (?,?,?,?)", list_staff) database.commit() def create_tab_staff(cursor): # cursor.execute('''CREATE TABLE staff (tab_n INT, f_name TEXT, l_name TEXT, p_name TEXT, position TEXT, key_dep INT)''') cursor.execute('''CREATE TABLE staff (tab_n INT, f_name TEXT, date_on TEXT, position TEXT)''') def del_row(cursor,n1): cursor.execute("DELETE FROM staff WHERE n= ?", (n1)) database.commit() def print_base(cursor): cursor.execute("SELECT * FROM staff ORDER BY f_name") results=cursor.fetchall() for row in results: print(row) def in_row(cursor): new_name=input("Введите фамилию: ") new_DoB=input("Введите дату рождения в формате YYYY-MM-DD: ") new_spec=input("Введите должность: ") cursor.execute("SELECT Count(*) FROM staff") count = cursor.fetchone() new_n = count[0]+1 cursor.execute("INSERT INTO staff VALUES (new_n,new_name,new_DoB,new_spec)") def up_base(cursor): old_name=input("Введите старую фамилию: ") new_name=input("Введите новую фамилию: ") cursor.execute("UPDATE staff SET f_name= :new_name1 WHERE f_name= :old_name1 ",{"new_name1": new_name,"old_name1":old_name}) database.commit() database=sqlite3.connect('file.db') sql_request=database.cursor() #create_tab_staff(sql_request) #in_base(sql_request) print_base(sql_request) #del_row(sql_request,'1') #up_base(sql_request) in_row(sql_request) print_base(sql_request) database.close()
a45426b4300e2edbe4571fbe238fe838415c9cff
udani95/Python-Exercises
/Printing_Input.py
172
4.1875
4
# How to get a input from the user and print it val = input("Please Enter your Name: ") val2=input("Enter your Age: ") print("Your name is",val) print("Your age is",val2)
a4c0f733388143433a58ba82141eaa9615e3b47e
spoliv/Algorithms_Python_10.09.2019
/DZ/Lesson_3/test_2.py
743
4.09375
4
# 2. Во втором массиве сохранить индексы четных элементов первого массива. Например, если дан # массив со значениями 8, 3, 15, 6, 4, 2, второй массив надо заполнить значениями 0, 3, 4, 5, # (индексация начинается с нуля), т.к. именно в этих позициях первого массива стоят четные числа. import random SIZE = 10 MIN_ITEM = 0 MAX_ITEM = 100 array_1 = [random.randint(MIN_ITEM, MAX_ITEM) for _ in range(SIZE)] print(array_1) array_2 = [] for i, elem in enumerate(array_1): if elem % 2 == 0: array_2.append(i) print(array_2)
f1932696124d8bb8e11fd121edb010fbb91488ca
rawitscherr/python_speaks
/speak.py
1,183
3.5
4
import os import record import transcribe import keyboard import stt import time SAVE_FILE = "output.wav" simple_rules = { "declare":["variable","list","class","function"], "control":["if", "for", "while"] } declared = [] time.sleep(2) while True: print "recording" # stt.listen_for_speech(SAVE_FILE) record.record_and_save(SAVE_FILE) print "transcribing" trans = transcribe.audio_to_text(SAVE_FILE) if trans == None: print "No text found" continue print "saving" print "text understood:" + trans + '\n' os.remove(SAVE_FILE) words = trans.split(' ') text = '' if words[0] == "declare": if words[1] in simple_rules["declare"]: if words[1] == "variable": text += (words[2].lower() + ' = ' + '"' + words[4]) + '"' # elif words[0] == "control": # elif words[0] == "print": text = "print " for r in words[1:]: text += r elif words[0] == "hello": keyboard.new_line() else: print "Didn't get that please try again" continue keyboard.write_text(text)
28ea92b2caefae8a39d276fd85a06440991dda1b
Americacastaneda/SIP-2018-starter
/U2-Applications/U2.1-Data/data_vis_project_starter.py
2,616
3.703125
4
''' In this project, you will visualize the feelings and language used in a set of Tweets. This starter code loads the appropriate libraries and the Twitter data you'll need! ''' #is meant for the tweets text import json from textblob import TextBlob import matplotlib.pyplot as plt #is meant for the graph import numpy as np #for the frequency of the word from wordcloud import WordCloud #Get the JSON data tweetFile = open("TwitterData/tweets_small.json", "r") tweetData = json.load(tweetFile) tweetFile.close() # Continue your program below! tweettext = [] tweetstring = "" for tweet in tweetData: tweetstring += tweet['text'] print(tweetstring) tweetBlob = TextBlob(tweetstring) print(tweetBlob.translate(to='es')) blob_polarity = [] for text in tweettext: b = TextBlob(text) blob_polarity.append(b.polarity) blob_subjectivity = [] for text in tweettext: b = TextBlob(text) blob_subjectivity.append(b.subjectivity) word_dict = {} for word in tweetBlob.words: word_dict[word.lower()] = tweetBlob.word_counts[word.lower()] print(word_dict) #tweettext.append(tweet['text']) # blob_polarity = [] # for text in tweettext: # b = TextBlob(text) # blob_polarity.append(b.polarity) # print("polarity average: ",sum(blob_polarity)/len(blob_polarity)) # #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # blob_subjectivity = [] # for text in tweettext: # b = TextBlob(text) # blob_subjectivity.append(b.subjectivity) # print("subjectivity average: ",sum(blob_subjectivity)/len(blob_subjectivity)) # #~~~~~~~~~~~~~~~~graph~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # plt.hist(blob_polarity, bins=[-1, -0.8, -0.5, 0, 0.5, 0.8, 1]) # plt.xlabel("polarity") # plt.ylabel("tweets") # plt.title("Histogram of polarity") # plt.axis([-1.1, 1.1, 0, 100]) # plt.grid(True) # plt.show() # #~~~~~~~~~~~~~~~graph 2~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # plt.hist(blob_subjectivity, bins=[-1, -0.8, -0.5, 0, 0.5, 0.8, 1]) # plt.xlabel("subjectivity") # plt.ylabel("tweets") # plt.title("Histogram of subjectivity") # plt.axis([-1.1, 1.1, 0, 100]) # plt.grid(True) # plt.show() # #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # # s = tweettext # # ''.join(s) # # print(s) # # first = tweettext[10] # # print (first) # #print(tweet.keys()) # # Textblob sample: # tb = TextBlob("You are a brilliant computer scientist.") # print(tb.sentiment) # # # words = tb.words # # # print(tb.polarity) # # # print(TextBlob("bad").sentiment) # # # for word in words: # # # print(TextBlob(word).sentiment)
7ffb29e3d870630c6ddab8cc07ec71426f829374
jailukanna/Python-Projects-Dojo
/16.Functional Programming with Python - SW/02.Python - Functional Parts/lambda.py
308
3.953125
4
numbers_list = range(10) # simple lambda # add = lambda x, y : x+y # print(add) doubled_numbers = list(map(lambda x: x*2, numbers_list)) print(doubled_numbers) # using lambda for multiplier def multiplier(multipler_num): return lambda x: x * multipler_num doubled = multiplier(2) print(doubled(4))
697ef44f7c35d4a9440d1f09d0cfb71df5de3084
rainman0709/algorithm_python
/Tree/Tree.py
1,946
4.125
4
from collections import deque class Node: def __init__(self, data=-1, lchild=None, rchild=None): self.data = data self.lchild = lchild self.rchild = rchild class Create_Tree: def __init__(self): self.root = Node() self.myQueue = deque() def add(self,elem): node = Node(elem) #根节点 if self.root.data == -1: self.root.data = node self.myQueue.append(self.root) else: treeNode = self.myQueue[0] if treeNode.lchild is None: treeNode.lchild = node self.myQueue.append(treeNode.lchild) else: treeNode.rchild = node self.myQueue.append(treeNode.rchild) self.myQueue.popleft() def traversal_create(self,root): data = input() if data is '#': return None else: root.data=data root.lchild=self.traversal_create(root.lchild) root.rchild=self.traversal_create(root.rchild) return root def travelsal_tree(self,root): if root is None: return print(root.data) self.travelsal_tree(root.lchild) self.travelsal_tree(root.rchild) def stack_traversal(self,root): if root is None: return mystack = [] node=root while node or mystack: while node: print(node.data) mystack.append(node) node=node.lchild node=mystack.pop() node=node.rchild def queue_traversal(self,root): if root is None: return q = deque() q.append(root) while q: node=q.pop() print(node.data) if node.lchild is not None: q.append(node.lchild) else: q.append(node.rchild)
c7dc29329893195431fbe36cb1650de15dc78764
runzedong/Leetcode_record
/Python/wiggle_sort.py
671
3.875
4
def wiggleSort(nums): """ :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead. """ if len(nums)%2==0: max=len(nums)-1 else: max=len(nums)-2 i=1 while i<=max: if nums[i-1]>nums[i]: temp=nums[i] nums[i]=nums[i-1] nums[i-1]=temp if i+1<=len(nums)-1 and nums[i]<nums[i+1]: temp=nums[i+1] nums[i+1]=nums[i] nums[i]=temp i+=2 def main(): nums=[3,5,2,1,6,4] print(nums) wiggleSort(nums) print(nums) main()
60a4a5cbc1f3a5a9be121a556cfbd3ba3597dcb2
giuliom95/python-tree-silhouettes
/src/renderer.py
3,179
3.65625
4
import numpy as np import examples FILM_DIMENSIONS = (800, 800) def bounding_box(polygon): """ Calculates bounding box of a convex polygon. :param polygon: List of vertices of the polygon. :return: The lower left point, the width and the height. """ vtx = polygon.T lower_left = np.array([np.min(vtx[0]), np.min(vtx[1])]) upper_right = np.array([np.max(vtx[0]), np.max(vtx[1])]) width, height = upper_right - lower_left return lower_left, width, height def inside_polygon(point, polygon): """ Check if point is inside a convex polygon. Uses the ray casting algorithm. Points must be in homogeneous coordinates. :param point: Point to check :param polygon: List of vertices of the polygon :return: Boolean """ vertex_couples = [(polygon[i-1], polygon[i]) for i in range(len(polygon))] for vertex in polygon: ray = [point, vertex] i = 0 for couple in vertex_couples: if between_points(ray, couple): i += 1 if i == 2: return False return True def fill_polygon(polygon, film): """ Fills the film with the points occupied by the polygon. :param polygon: The polygon :param film: The matrix of pixels """ polygon = np.array(polygon) (llx, lly), width, height = bounding_box(polygon) points = np.array([(x, y, 1) for y in range(lly, lly+height+1) for x in range(llx, llx+width+1)]) for p in points: if inside_polygon(p, polygon): x, y, _ = p try: film[x][y] = 1 except IndexError: print 'WARNING: Out of film' def render(polygons, filename): """ Renders the scene and saves it to filename :param polygons: List of convex polygons. :param filename: Output file name """ film_w, film_h = FILM_DIMENSIONS film = np.array([[0]*film_w]*film_h) l = len(polygons) i = 0 polygons = np.array(polygons) polygons = (polygons*film_w/2 + film_w/2).astype(int) for poly in polygons: fill_polygon(poly, film) i += 1 print i, '/', l with open(filename, 'w') as f: f.write('P5\n{0} {1}\n255\n'.format(*FILM_DIMENSIONS)) for row in film: for elem in row: f.write(chr(elem*255)) def between_points(ray, points): """ Check if the ray defined by two points of it passes through the two given points. Points must be in homogeneous coordinates. :param ray: Two points that defines the ray. :param points: Two points. :return: Boolean """ v1 = (points[0][0]-ray[0][0])*(ray[0][1]-ray[1][1]) - \ (points[0][1]-ray[0][1])*(ray[0][0]-ray[1][0]) v2 = (points[1][0]-ray[0][0])*(ray[0][1]-ray[1][1]) - \ (points[1][1]-ray[0][1])*(ray[0][0]-ray[1][0]) return v1*v2 <= 0 if __name__=='__main__': branches = examples.side_tree() polys = [] for branch in branches: polys += branch render(polys, "out.pgm")
1266e83edea885939664796ba5018c9e31733a4b
xinshengqin/DistributedComputing
/src/client_app/computing.py
922
3.609375
4
from numpy import * #from math import * ##we can use numpy or math def solve_simple_problem(p1,p2,p3,p4,p5): return p1+p2+p3+p4+p5 def solve_problem(p1,p2,p3,p4,p5): '''solve the function with Newton's method ''' def f(x): return p1*sin(p2*x)-p3-p4*exp(int(p5)*x) def df(x): return p1*p2*cos(p2*x)-p4*p5*exp((p5*x)) tolerance=.0000001 x=2*pi while x>=0: x1 = x - f(x)/df(x) t = abs(x1 - x) if t < tolerance: break x = x1 if x==0 or x<0: print('can not find the approx. answer') return None else: return x ###############################test #7.12530535898?1.7841188001?-0.676578247777?0.625368322208?1.17482593761 #1.57335759382 # p1=7.12530535898 # p2=1.784118800 # p3=-0.676578247777 # p4=0.625368322208 # p5=1.17482593761 # # # a=solve_problem(p1,p2,p3,p4,p5) # print(a)
497acea529793d30a5f7237e81443b59024db3f7
MeriDm7/statistic
/the_end_result.py
2,489
3.546875
4
# In this file, I import a list of dictionaries that contain mortality information. #I calculate the percentage of deaths in total and for various reasons (Heart Disease and Cancer) # relative to the total population each year in a particular area and record that percentage # instead of the previous one. And I calculate the average mortality rate in each area and add # it to the dictionaries from RESULT import lst_with_res from convert_to_float import convert lst_with_keys = [] for i in lst_with_res: for j in i.keys(): lst_with_keys.append(j) for i in range(len(lst_with_res)): dict_by_year = lst_with_res[i][lst_with_keys[i]] lst_with_years = [] for j in dict_by_year.keys(): lst_with_years.append(j) dict_2005 = dict_by_year[lst_with_years[0]] lst_with_num = [] for l in dict_2005.keys(): lst_with_num.append(l) for i in range(len(lst_with_res)): my_dict = lst_with_res[i][lst_with_keys[i]] all_percent_of_dead = [] all_cancer = [] all_heart = [] for j in lst_with_years: dead = my_dict[j][lst_with_num[0]] cancer = my_dict[j][lst_with_num[1]] heart = my_dict[j][lst_with_num[2]] total = convert(my_dict[j][lst_with_num[3]]) * 1000 percent_dead = (dead * 100) / total percent_cancer = (cancer * 100) / total percent_heart = (heart * 100) / total lst_with_res[i][lst_with_keys[i]][j][lst_with_num[0]] = round(percent_dead, 2) lst_with_res[i][lst_with_keys[i]][j][lst_with_num[1]] = round(percent_cancer, 2) lst_with_res[i][lst_with_keys[i]][j][lst_with_num[2]] = round(percent_heart, 2) lst_with_res[i][lst_with_keys[i]][j][lst_with_num[3]] = total all_percent_of_dead.append(round(percent_dead, 2)) all_cancer.append(round(percent_cancer, 2)) all_heart.append(round(percent_heart, 2)) mid_dead = round(sum(all_percent_of_dead) / len(all_percent_of_dead), 2) mid_cancer = round(sum(all_cancer) / len(all_cancer), 2) mid_heart = round(sum(all_heart) / len(all_heart), 2) mid_dict = {} mid_dict["Dead"] = mid_dead mid_dict["Cancer"] = mid_cancer mid_dict["Heart"] = mid_heart lst_with_res[i][lst_with_keys[i]]["All"] = mid_dict
c8687d26b8a0e24d706e33627461eb3be9f0392a
natnaelabay/comptetive-programming
/CP/D6/Intersection of Two arrays.py
376
3.640625
4
# Natnael Abay # se.natnael.abay@gmail.com class Solution: def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]: ans = [] for i in nums1: boolean = True for j in nums2: if i == j: boolean = False if not boolean: ans.append(i) return list(set(ans))
2120c581c6e43b612a668b5e04081198705cbc25
addisonVota/addisonVota.github.io
/odds or even.py
968
4.15625
4
import random Question = raw_input("Please choose either odd or even: ") if Question == "odd" or Question == "even" : Question_number=int(input("Pick a number between 0 and 5")) else: raw_input("Please choose either odd or even: ") bool_number = False if Question >= 0 or Question <= 5: bool_number = True else: print("Please type in odd or even next time.") quit() bot_number = random.randint(0,5) if bool_number == True: print("My number is %s.") % bot_number else: quit() Answer = Question_number + bot_number print "Your number was %s. My number was %s. The sum these is %s." % (Question_number,bot_number,Answer) if (Answer % 2) == 0 and "even" in Question: print "The sum is even. You win!" elif (Answer % 2) == 0 and "odd" in Question: print "The sum is even. You lose." elif (Answer % 2) == 1 and "odd" in Question: print "The sum is odd. You win!" elif (Answer % 2) == 1 and "even" in Question: print "The sum is odd. You lose."
58de9f033f9366a08cb2b47142ed105981e03784
J-0-K-E-R/Python-Programs
/07. Dictionary.py
1,103
4.40625
4
# Dictionay consists of keys and value. Every key is unique and every key is used to access the value associated with it. dic = {'I': 'am Joker', 'Goku': 'is the strongest', 'Naruto': 'is a Ninja', 'Python': 'is a snake. :P'} print(dic) print(dic['Python']) for key,value in dic.items(): print(key, value) ''' Some methods of Dictionary are as follows clear() Removes all the elements from the dictionary copy() Returns a copy of the dictionary fromkeys() Returns a dictionary with the specified keys and values get() Returns the value of the specified key items() Returns a list containing a tuple for each key value pair keys() Returns a list containing the dictionary's keys pop() Removes the element with the specified key popitem() Removes the last inserted key-value pair setdefault() Returns the value of the specified key. If the key does not exist: insert the key, with the specified value update() Updates the dictionary with the specified key-value pairs values() Returns a list of all the values in the dictionary '''
f9998d21e1eb1c0eae5764a9eda556eb3b4f58a2
gabriellaec/desoft-analise-exercicios
/backup/user_253/ch16_2020_04_26_16_09_11_140823.py
106
3.71875
4
a=int(input("Qual o valor da conta? ")) b=a+a*10/100 print ("Valor da conta com 10%: R${:.2f}" .format(b))
08efd7b2924983c57e436f50c7702a9f12c50de2
ParshvaTimbadia/Aglorithms
/Hard/Longest Subarray with Ones after Replacement.py
1,237
4.03125
4
''' Problem Statement # Given an array containing 0s and 1s, if you are allowed to replace no more than ‘k’ 0s with 1s, find the length of the longest contiguous subarray having all 1s. Example 1: Input: Array=[0, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1], k=2 Output: 6 Explanation: Replace the '0' at index 5 and 8 to have the longest contiguous subarray of 1s having length 6. Example 2: Input: Array=[0, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1], k=3 Output: 9 Explanation: Replace the '0' at index 6, 9, and 10 to have the longest contiguous subarray of 1s having length 9. ''' def length_of_longest_substring(arr, k): window_start, max_length, max_ones_count = 0, 0, 0 # Try to extend the range [window_start, window_end] for window_end in range(len(arr)): if arr[window_end] == 1: max_ones_count += 1 if (window_end - window_start + 1 - max_ones_count) > k: if arr[window_start] == 1: max_ones_count -= 1 window_start += 1 max_length = max(max_length, window_end - window_start + 1) return max_length def main(): print(length_of_longest_substring([0, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1], 2)) print(length_of_longest_substring( [0, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1], 3)) main()
24aa223acd5c6845bb3dc01cc8dae6e558180ae4
MalsR/python-learning
/puzzles/random/parity_outlier.py
437
3.734375
4
class ParityOutlier: def find(self, number): odd_numbers = [] even_numbers = [] for number_to_check in number: if number_to_check % 2 != 0: odd_numbers.append(number_to_check) else: even_numbers.append(number_to_check) if len(odd_numbers) > len(even_numbers): return even_numbers[0] else: return odd_numbers[0]
5bc04936a2aa550b52f50f1056309ee24efa00cf
jfgilman/Lab
/Snake.py
3,630
3.921875
4
"""Trying to start learning python for reals.""" import pygame import random pygame.init() white = (255, 255, 255) black = (0, 0, 0) red = (255, 0, 0) green = (0, 175, 0) display_width = 800 display_height = 600 block_size = 10 gameDisplay = pygame.display.set_mode((display_width, display_height)) pygame.display.set_caption('Slither') clock = pygame.time.Clock() font = pygame.font.SysFont(None, 25) def snake(snake_list): """Draw the snake.""" for XnY in snake_list: pygame.draw.rect(gameDisplay, green, [XnY[0], XnY[1], block_size, block_size]) def text_objects(text, color): """Set up text.""" textSurface = font.render(text, True, color) return textSurface, textSurface.get_rect() def message_to_screen(msg, color): """Send text to the screen.""" textSurf, textRect = text_objects(msg, color) textRect.center = (display_width / 2), (display_height / 2) gameDisplay.blit(textSurf, textRect) def gameLoop(): """Loop through the game.""" gameExit = False gameOver = False lead_x = display_width / 2 lead_y = display_height / 2 lead_x_change = 0 lead_y_change = 0 snake_list = [] snake_length = 1 randAppleX = round(random.randrange(0, display_width - block_size)/10)*10 randAppleY = round(random.randrange(0, display_height - block_size)/10)*10 while not gameExit: while gameOver: gameDisplay.fill(white) message_to_screen("Gameover, C to play again, Q to Quit", red) pygame.display.update() for event in pygame.event.get(): if event.type == pygame.KEYDOWN: if event.key == pygame.K_q: gameExit = True gameOver = False if event.key == pygame.K_c: gameLoop() for event in pygame.event.get(): if event.type == pygame.QUIT: gameExit = True if event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT: lead_x_change = -block_size lead_y_change = 0 elif event.key == pygame.K_RIGHT: lead_x_change = block_size lead_y_change = 0 elif event.key == pygame.K_DOWN: lead_y_change = block_size lead_x_change = 0 elif event.key == pygame.K_UP: lead_y_change = -block_size lead_x_change = 0 if (lead_x >= display_width or lead_x < 0 or lead_y >= display_height or lead_y < 0): gameOver = True lead_x += lead_x_change lead_y += lead_y_change gameDisplay.fill(white) pygame.draw.rect(gameDisplay, red, [randAppleX, randAppleY, block_size, block_size]) snake_head = [] snake_head.append(lead_x) snake_head.append(lead_y) snake_list.append(snake_head) if len(snake_list) > snake_length: del snake_list[0] for eachSeg in snake_list[:-1]: if eachSeg == snake_head: gameOver = True snake(snake_list) pygame.display.update() if lead_x == randAppleX and lead_y == randAppleY: snake_length += 1 randAppleX = round(random.randrange(0, display_width - block_size)/10)*10 randAppleY = round(random.randrange(0, display_height - block_size)/10)*10 clock.tick(10) pygame.quit() quit() gameLoop()
ee807af5d135c806dabbce769377dd3959cc9542
nbrahman/HackerRank
/01 Algorithms/02 Implementation/Equalizing-the-Array.py
1,484
3.90625
4
''' Karl has an array of n integers defined as A=a<0>,a<1>,...,a<n-1>. In one operation, he can delete any element from the array. Karl wants all the elements of the array to be equal to one another. To do this, he must delete zero or more elements from the array. Find and print the minimum number of deletion operations Karl must perform so that all the array's elements are equal. Input Format The first line contains an integer, n, denoting the number of elements in array A. The next line contains n space-separated integers where element i corresponds to array element a<i>(0<=i<n). Constraints 1<=n,a<i><=100 Output Format Print a single integer denoting the minimum number of elements Karl must delete for all elements in the array to be equal. Sample Input 5 3 3 2 1 3 Sample Output 2 Explanation Array A={3,3,2,1,3}. If we delete a<2>=2 and a<3>=1, all of the elements in the resulting array, A'={3,3,3}, will be equal. Deleting these 2 elements is minimal because our only other options would be to delete 4 elements to get an array of either [1] or [2]. Thus, we print 2 on a new line, as that is the minimum number of deletions resulting in an array where all elements are equal. ''' #!/bin/python3 import sys def Solution (a): d={} for i in a: d[i]=d.get(i,0)+1 print(len(a)-sorted(d.items(), key=lambda x: (-x[1], x[0]))[0][1]) n = int(input().strip()) a = [int(arr_temp) for arr_temp in input().strip().split(' ')] Solution(a)
45814113c2b74b0d001e170b8789c19ae0b50364
joseangel-sc/CodeFights
/Arcade/MirrorLake/IsSubstitutionCipher.py
1,613
4.0625
4
'''A ciphertext alphabet is obtained from the plaintext alphabet by means of rearranging some characters. For example "bacdef...xyz" will be a simple ciphertext alphabet where a and b are rearranged. A substitution cipher is a method of encoding where each letter of the plaintext alphabet is replaced with the corresponding (i.e. having the same index) letter of some ciphertext alphabet. Given two strings, check whether it is possible to obtain them from each other using some (possibly, different) substitution ciphers. Example For string1 = "aacb" and string2 = "aabc", the output should be isSubstitutionCipher(string1, string2) = true. Any ciphertext alphabet that starts with acb... would make this transformation possible. For string1 = "aa" and string2 = "bc", the output should be isSubstitutionCipher(string1, string2) = false. Input/Output [time limit] 4000ms (py) [input] string string1 A string consisting of lowercase characters. Constraints: 1 ≤ string1.length ≤ 10. [input] string string2 A string consisting of lowercase characters of the same length as string1. Constraints: string2.length = strin1.length. [output] boolean''' def isSubstitutionCipher(string1, string2): string1count = [] string2count = [] for i in range(0,len(string1)): string1count.append(string1.count(string1[i])) for i in range(0,len(string2)): string2count.append(string2.count(string2[i])) for i in range(0,len(string1count)): if string1count.count(string1count[i])!=string2count.count(string1count[i]): return False return True
1b5561ba409b750a4bfd5ec9815c1cce8795bffa
azure1016/MyLeetcodePython
/JavaImpl/EPI/parallel_computation/syschronization_interleaving_threads.py
1,212
3.671875
4
import threading class OddEvenMonitor(threading.Condition): ODD_TURN = True EVEN_TURN = False def __init__(self): super().__init__() # would always start with an odd number self.turn = self.ODD_TURN def wait_turn(self, waited_turn): with self: while self.turn != waited_turn: self.wait() def toggle_turn(self): with self: self.turn ^= True self.notify() class OddThread(threading.Thread): def __init__(self, monitor): super().__init__() # so the monitor is shared? self.monitor = monitor def run(self): for i in range(1, 101, 2): self.monitor.wait_turn(OddEvenMonitor.ODD_TURN) print(i) self.monitor.toggle_turn() class EvenThread(threading.Thread): def __init__(self, monitor): super().__init__() self.monitor = monitor def run(self): for i in range(2, 101, 2): self.monitor.wait_turn(OddEvenMonitor.EVEN_TURN) print(i) self.monitor.toggle_turn() monitor = OddEvenMonitor() t1 = EvenThread(monitor) t2 = OddThread(monitor) t1.start() t2.start()
4da8146bfe89e7d110b4b4c55b136590cfdd6f9c
AdamZhouSE/pythonHomework
/Code/CodeRecords/2704/59140/319056.py
717
3.59375
4
def find(x): if x == parent[x]: return x else: return find(parent[x]) def union(x, y): xroot = find(x) yroot = find(y) if xroot != yroot: if rank[xroot] > rank[yroot]: parent[yroot] = xroot else: parent[xroot] = yroot rank[yroot] += 1 def union_find(): for line in edges: if find(line[0]) == find(line[1]): return line else: union(line[0], line[1]) temp=input()[2:-2].split("], [") edges=[] for i in temp: edges.append([int(x) for x in i.split(",")]) N = max([max(i) for i in edges]) parent = [-1] + [i for i in range(1, N + 1)] rank = [1 for i in parent] print(union_find())
0f00a7652d46e33be20039b4d48e598fd0eff23d
Yoozek27/PyPodstawy
/fizzbuzz.py
317
3.65625
4
import sys inputs = sys.argv inputs.pop(0) for i, item in enumerate(inputs, start=1): check = int(item) if check % 3 == 0 and check % 5 == 0: print("fizzbuzz") elif check % 3 == 0: print("fizz") elif check % 5 == 0: print("buzz") else: print(item)
acba64d22329e0e9a43bd54d9f4b7c1dcdcb04a3
pedroceciliocn/programa-o-1
/strings/exe_2_print_nome_escala_string.py
102
3.859375
4
nome = input("Dê o seu nome: ") escala = "" for letra in nome: escala += letra print(escala)
d72cf386f3d9d458f577ec70a2c69c2e80877837
timole/experiment-analysis
/data_helper.py
516
3.546875
4
import sys, re import pandas as pd def import_and_clean_data(file_name): print "Parse CSV: " + file_name df = pd.read_csv(file_name, parse_dates=['datetime'], sep='|') print "Done." print "There are {:.0f} rows in the data.".format(len(df)) idx = df.target_email.str.contains('solita.fi$|stt.fi$|stt-lehtikuva.fi$|example.com$', flags=re.IGNORECASE, regex=True, na=False) df = df[~idx] print "After cleaning, there are {:.0f} rows in the data".format(len(df)) print return df
4a41fe40adac36a319c1995525ae514b59a9c4ff
mwhittemore2/vocab_manager
/devops/aws/configurations/lib/config_loader.py
511
3.8125
4
from abc import ABC class ConfigLoader(ABC): """ Generates a config file from a template. """ def write(params, destination): """ Writes a config file according to the template specified by the class that instantiates this method. Parameters ---------- params : dict A dictionary of parameters for the config template. destination : str The location to write the config file to. """ pass
f8071e8965db0da6e61345e3ad479d2f8b0bc855
Amaayezing/ECS-10
/ConnectN/connectn.py
19,530
4.15625
4
#Maayez Imam 11/10/17 #Connect N program import time import random matrix_height = int(input("Enter the number of rows: ")) matrix_width = int(input("Enter the number of columns: ")) connect_n = int(input("Enter the number of pieces in a row to win: ")) def el(): # Empty line - Makes spacing nicer print(' ') def make_board(): # (Re)creates board/grid/matrix global board board = [] for x in range(matrix_height): # Makes [matrix_height] lists each containing [matrix_width + 1] columns. board.append(["* "] * (matrix_width + 1)) # +1 for the extra line after the final column def print_board(): for row in board: print(" ".join(row)) # Joins list elements to form a string, " " means they have a space in between # no comma after means that rows are printed one after another (as rows are list items) def character_select(player): while True: # Repeats until a (length 1) character is chosen. el() c = input("Player " + str(player) + ", choose your character! ").upper() # Uppercase looks nicer. if c == "NO" or c == "NOPE" or c == "NO THANKS": el() stubborn = ["You're very stubborn, aren't you?", "Fine, have it your way"] print(random.choice(stubborn)) time.sleep(0.6) c = "L" print("I'll choose your character for you, since you find it so difficult. ") time.sleep(1.1) print("It's 'L' by the way. You know, L for Loser.") time.sleep(1.2) if player == 2: if character_1 == "L": c = "A" print("Come to think of it, I'll choose 'A', for A**hole. Much more relevant.") time.sleep(1.4) if c == "MAKE ME": el() make_me = ["Okay then.", "Sure thing.", "With pleasure."] print(random.choice(make_me)) time.sleep(0.5) elif len(c) != 1: # Includes returning nothing awa strings longer than 1 el() if c == "OK" or c == "OKAY" or c == "SURE": print("Very funny.") time.sleep(0.4) if c == "HELLO" or c == "HI" or c == "HELLO WORLD" or c == "SUP": print("Hello to you too!") time.sleep(0.6) not_char = ["Your character must be a character.", "That\'s not a character!", "Try again.", "Character. Literally.", "I'm not going to let you do that. Nothing personal."] print(random.choice(not_char)) # Randomly chooses one of above sentences. time.sleep(0.6) # Player sees message before being told to choose column again. if c == "TOM" or c == "TOM QUINCEY" or c == "TRQ": print("Shame - you had such a great choice!") time.sleep(0.5) elif c == "." or c == "," or c == "`" or c == "'": el() print("You should choose a more visible character.") time.sleep(0.5) else: return c def show_columns(): # Prints row of numbers, showing player which column is which for i in range(matrix_width): if i + 1 <= 10: print(' ' + str(i + 1),) # Makes spacing right for numbers <=10 else: print(str(i + 1),) # Makes spacing right for numbers >10 el() def choose_column(): try: c = int(input("Choose Column " + '(1-' + str(matrix_width) + '): ')) - 1 except ValueError: # Input of strings to choose_column() would break game el() no_number = ["That's not even a number!", "Pressing a number key really isn't that difficult.", "You somehow managed to miss the board, well done.", "Impressive! Try again."] print(random.choice(no_number)) time.sleep(0.5) c = choose_column() while c not in range(matrix_width): # Must be while, not if el() off_board = ["You missed the board, good job!", "Helpful hint: the board isn't that big.", "Is this how you normally play?", "Is it really that hard?", "Have another go. Aren't I kind?"] print(random.choice(off_board)) time.sleep(0.5) c = choose_column() return c def stack_height(cc): # Finds out how high the stack is, returns height of lowest empty "hole". h = matrix_height - 1 # Top row has height 0, row no. increases down the grid. h is now the bottom row. while True: if h == -1: # If top row is full (on column), then h = 0-1 = -1 el() too_high = ["The board doesn't go that high. Obviously.", "Try again, genius.", "Do you normally play like this?", "I should make you lose instantly for that."] print(random.choice(too_high)) # Player placed counter above matrix time.sleep(0.5) return -1 elif board[h][cc] != "| ": # If there is a character in this hole, look at hole above. h -= 1 else: return h # h is (now) lowest empty hole def pattern(): # pwetty pattern el() print ('\*/*' * 8) + '\ ' print ('/*\*' * 2) + '/ ' + ' YOU WIN! ' + ('/*\*' * 2) + '/ ' print ('\*/*' * 8) + '\ ' def play(char): el() print(str(char) + '\'s ' "turn: ") show_columns() print_board() el() cc = choose_column() sh = stack_height(cc) while sh == -1: # Player places counter again after attempting to place in a full stack. cc = choose_column() sh = stack_height(cc) board[sh][cc] = "|" + str(char) # Left half works because 'board' has lists within it's own list. [row][column] if find_4(sh, cc): # If n are connected in a row, stack, or diagonal pattern() el() return True def play_again(): time.sleep(1.0) while True: el() replay = input("Do you want to play again? ") if replay == 'y' or replay == 'yes' or replay == 'yeah' or replay == 'okay' \ or replay == 'ok' or replay == 'sure' or replay == '01111001': return True elif replay == 'n' or replay == 'no' or replay == 'nope' or replay == 'rather not' or replay == 'seriously?': return False else: el() other = ["What?", "Pardon?", "I don't understand!", "I haven't been programmed to answer that."] print(random.choice(other)) time.sleep(0.5) def board_full(): # Finds out if board is full. (Easiest to test with n = 3) count = 0 for x in range(matrix_width): if board[0][x] != '| ': # If the top row is full, therefore the whole board is full. count += 1 if count == matrix_width: return True # --------------------------- FIND SURROUNDING COUNTERS ----------------------------- def left(sh, cc): if board[sh][cc] == board[sh][cc - 1]: # Counter to the left is the same as counter just dropped return True def right(sh, cc): if board[sh][cc] == board[sh][cc + 1]: # Counter to the right is the same as counter just dropped return True def up_left(sh, cc): if board[sh][cc] == board[sh - 1][cc - 1]: return True def up_right(sh, cc): if board[sh][cc] == board[sh - 1][cc + 1]: return True def down(sh, cc): if sh < matrix_height - 1: # See stack_height() description. if board[sh][cc] == board[sh + 1][cc]: # Two 'ifs' are identical to 'and' (I think this way looks nicer) return True def down_left(sh, cc): if sh < matrix_height - 1: # See stack_height() description. if board[sh][cc] == board[sh + 1][cc - 1]: return True def down_right(sh, cc): if sh < matrix_height - 1: # See stack_height() description. if board[sh][cc] == board[sh + 1][cc + 1]: return True def find_horizontal_4(sh, cc): horiz_count = 1 tracker_count = 0 while True: if left(sh, cc - tracker_count): # If counter to left is same, increase horiz_count by 1 horiz_count += 1 tracker_count += 1 else: break tracker_count = 0 # Resets tracker_count after first while loop. while True: if right(sh, cc + tracker_count): horiz_count += 1 tracker_count += 1 else: break if horiz_count >= connect_n: # n counters are connected horizontally return True def find_vertical_4(sh, cc): vert_count = 1 tracker_count = 0 # This is slightly redundant as there is only one while loop for find_vertical_4() while True: if down(sh + tracker_count, cc): vert_count += 1 tracker_count += 1 else: break if vert_count >= connect_n: # n counters are connected vertically return True def find_down_left_4(sh, cc): down_left_count = 1 tracker_count = 0 while True: if down_left(sh + tracker_count, cc - tracker_count): down_left_count += 1 tracker_count += 1 else: break tracker_count = 0 # Resets tracker_count after first while loop. while True: if up_right(sh - tracker_count, cc + tracker_count): down_left_count += 1 tracker_count += 1 else: break if down_left_count >= connect_n: # n counters are connected diagonally (down/left) return True def find_down_right_4(sh, cc): down_right_count = 1 tracker_count = 0 while True: if down_right(sh + tracker_count, cc + tracker_count): down_right_count += 1 tracker_count += 1 else: break tracker_count = 0 # Resets tracker_count after first while loop. while True: if up_left(sh - tracker_count, cc - tracker_count): down_right_count += 1 tracker_count += 1 else: break if down_right_count >= connect_n: # n counters are connected diagonally (down/right) return True def find_4(sh, cc): if find_horizontal_4(sh, cc) or find_vertical_4(sh, cc) or find_down_right_4(sh, cc) or find_down_left_4(sh, cc): return True # ---------------------------------- GAME ----------------------------------------- # Intro make_board() print("Let's play Connect " + str(connect_n) + "!") time.sleep(0.2) if connect_n >= 7: print("Good luck! You'll need it.") time.sleep(0.4) if connect_n <= 2: small_n = ["This is going to be an odyssey of a game, I can tell.", "Spoiler: Player 1 wins. Bet you didn't see that one coming."] print(random.choice(small_n)) time.sleep(1.0) character_1 = character_select(1) character_2 = character_select(2) while character_2 == character_1: el() same_char = ["You cannot have the same character as Player 1.", "*sigh*", "Have another go. I feel sorry for you.", "That might make the game a *little* confusing.", "That's not a very good idea, is it?"] print(random.choice(same_char)) time.sleep(0.5) character_2 = character_select(2) # Main Game while True: if play(character_1): # Still runs play() (which returns True when find_4() == True) print_board() # All this code only runs when [n] counters have been connected. el() if play_again(): make_board() else: break if play(character_2): print_board() el() if play_again(): make_board() else: break if board_full(): el() print_board() el() time.sleep(0.8) for a in range(3): print(".",) time.sleep(0.5) print("Somehow you both managed to lose.",) time.sleep(1.0) print("Congratulations.",) time.sleep(1.0) el() if play_again(): make_board() else: break # def makeMove(board, numRows, numCols, col, piece): # i = int() # # for i in range(numRows - 1): # if board[i][col] == '*': # board[i][col] = piece # break # # # printBoard(board, numRows, numCols) # # # def declareWinner(board, numRows, numCols, turn, numToWin): # # if tied(board, numRows, numCols, numToWin): # print("Tie game!\n") # elif turn == 0: # print("Player 2 Won!\n") # else: # print("Player 1 Won!\n") # # # def playGame(board, turn, numRows, numCols, numToWin): # col = int() # pieces = '\XO' # # while not checkGameOver(board, numRows, numCols, numToWin): # col = getValidMove(board, numCols) # makeMove(board, numRows, numCols, col, pieces[turn]) # turn = (turn + 1) % 2 # # declareWinner(board, numRows, numCols, turn, numToWin) # # def main(argc, argv): # numRows = int() # numCols = int() # numToWin = int() # turn = int() # board = chr # # if(argc != 4): # if (argc < 4): # print("Not enough arguments entered\n") # print("Usage connectn.out num_rows num_columns number_of_pieces_in_a_row_needed_to_win\n") # exit(0) # # elif (argc > 4): # print("Too many arguments entered\n") # print("Usage connectn.out num_rows num_columns number_of_pieces_in_a_row_needed_to_win\n") # exit(0) # else: # input(argv[1], "%d" %numRows) # input(argv[2], "%d" %numCols) # input(argv[3], "%d" %numToWin) # # setUp(board, turn, numRows, numCols) # printBoard(board, numRows, numCols) # playGame(board, turn, numRows, numCols, numToWin) # cleanUpBoard(board, numRows) # # # return 0 # # # def getValidMove(board, numCols): # col = int() # numArgsRead = int() # # while not isValidMove(numArgsRead, 1, board, col, numCols): # print("Enter a column between 0 and %d to play in: ", numCols-1) # numArgsRead = input("%d" %col) # # return col # # #bool # def isValidMove(numArgsRead, numArgsNeeded, board, col, numCols): # # if not isValidFormatting(numArgsRead, numArgsNeeded): # return False # # elif not inBounds(col, numCols): # return False # # elif board[0][col] != '*': # return False # # else: # return True # # #bool # def isValidFormatting(numArgsRead, numArgsNeeded): # newLine = '\n' # isValid = True # # if numArgsRead != numArgsNeeded: # isValid = False # # while newLine != '\n': # input("%c" %newLine) # if not newLine.isspace(): # isValid = False # # return isValid # # #bool # def inBounds(col, numCols): # return col >= 0 and col < numCols # # def setUp(board, turn, numRows, numCols): # board = makeBoard(numRows, numCols) # turn = 0 # # #char** # def makeBoard(numRows, numCols) # # board = (char**)malloc(numRows * sizeof(char*)) # i = int() # j = int() # # for i in range(numRows): # board[i] = (char*)malloc(numCols*sizeof(char)) # for j in range(numCols): # board[i][j] = '*' # # return board # # def printBoard(board, numRows, numCols): # i = int() # j = int() # # for i in range(numRows): # print("%d ", numRows - i -1) # for j in range(numCols): # print("%c ", board[i][j]) # print("\n") # # print(" ") # # for j in range(numCols): # print("%d ", j) # print("\n") # # # def cleanUpBoard(board, numRows): # i = int() # for i in range(numRows): # free(board[i]) # free(board) # # #bool # def checkGameOver(board, numRows, numCols, numToWin): # return won(board, numToWin, numCols, numRows) or tied(board, numRows, numCols, numToWin) # # #bool # def won(board, numToWin, numCols, numRows): # return horizWin(board, numToWin, numCols, numRows) or vertWin(board, numToWin, numCols, numRows) or diagWin(board, numToWin, numCols, numRows) # # #bool # def horizWin(board, numToWin, numCols, numRows): # i = int() # j = int() # k = int() # winner = bool # firstPiece = chr # # for i in range(numRows): # for j in range(numCols - numToWin + 1): # winner = True # firstPiece = board[i][j] # if firstPiece == '*': # continue # # for k in range(numToWin): # if firstPiece != board[i][j+k]: # winner = False # break # # if winner: # return True # # return False # # # #bool # def vertWin(board, numToWin, numCols, numRows): # i = int() # j = int() # k = int() # winner = bool # firstPiece = chr # # for i in range(numCols): # for j in range(numRows - numToWin + 1): # winner = True # firstPiece = board[j][i] # if firstPiece == '*': # continue # # for k in range(numToWin): # if firstPiece != board[j+k][i] : # winner = False # break # # if winner: # return True # # return False # # #bool # def diagWin(board, numToWin, numCols, numRows): # return leftDiagWin(board, numToWin, numCols, numRows) or rightDiagWin(board, numToWin, numCols, numRows) # # # #bool # def leftDiagWin(board, numToWin, numCols, numRows): # i = int() # j = int() # k = int() # winner = bool # firstPiece = chr # # for i in range(numRows - numToWin + 1): # for j in range(numCols - numToWin + 1): # winner = True # firstPiece = board[i][j] # if firstPiece == '*': # continue # # for k in range(numToWin): # if firstPiece != board[i+k][j+k]: # winner = False # break # # if winner: # return True # # return False # # #bool # def rightDiagWin(board, numToWin, numCols, numRows): # i = int() # j = int() # k = int() # winner = bool # firstPiece = chr # # for i in range(numRows - numToWin + 1)#(i = numRows - 1; i >= numRows - numToWin + 1; --i) { # for j in range(numCols - numToWin + 1): # winner = True # firstPiece = board[i][j] # if firstPiece == '*': # continue # # for k in range(numToWin): # if firstPiece != board[i-k][j+k]: # winner = False # break # # if winner: # return True # # return False # # # def tied(board, numRows, numCols, numToWin): # return checkBoardFull(board, numRows, numCols) and not won(board, numToWin, numCols, numRows) # # # def checkBoardFull(board, numRows, numCols): # i = int() # j = int() # # for i in range(numRows): # for j in range(numCols): # if board[i][j] == '*': # return False # # return True
91ff0e33e112780b7c680379261f24ebf4dad519
wasabidina/pie
/mad.py
4,300
4.0625
4
#print('hello Madina') #print('Hello Arkhat') # x = 5 # y = 7 # print(x) # print(x,y) # print(x+y) # name = "Madina" # #print(name) # surname = "Imangaliyeva" # print(name,surname) # if 6==6: # print(x,y,'matematika') # a = "string Madina" # b = 77 #integer # c = 5.12 #float # list1 = [1,2,'ASdsd'] # dictionary = { # "a" : "asd", # "b" : 123 # } # boolean = True #False # a = '1' # # a = float(a) # b = 2.912 # # b = float(b) # c = 3 # # c = float(c) # # print(float(a) + float(b) + float(c)) # # print(str(a) + str(b) + str(c)) # print(int(a) + int(round(b)) + int(c)) # print("hello world") # c = 98.98 # 98 # d = 100 #'100' # c = int(c) # d = int(d) # # print(type(d)) # name = "Madina" # a = "menya zovut " # d = " mne " # c = 24.5 # # a = str(a) # # name = str(name) # # d = str(d) # c = str(c) # # print(a+name+d+c) # intro = f" menya zovut {name} mne {c}" # print(intro) # a = 6 # b = 4 # c = 1996 # # print(a + b + c) # a = '0' + str(6) + "." # b = "0" + str(4) + "." # c = str(1996) # print(a+b+c) # a = 123 # if a > 200: # print("False") # elif a == 123: # print("True") # else: # print("True") # if a > 10: # print("больше 10ти") # elif a == 10: # print("ровно 10") # else: # print("меньше 10ти") # elif a == 10: # print("ровно 10") # else: # print("меньше 10ти") # a = "qShaskl" # b = 8 # # print(b) # if b > 5 and not b < 8: # print("больше 5ти или 8") # elif b == 5: # print("равно с 5") # elif b == 7: # print('7777') # else: # print("ничего из вышеперечисоенного") # a = input('введите а\n') # b = input('введите b\n') # o = input('введите что сделать\n') # a = int(a) # b = int(b) # print(a) # print(b) # if o =='*': # print(a * b) # elif o =='/': # print(int(a / b)) # elif o =='-': # print(int(a-b)) # elif o =='+' or 'plus' == o: # print(int(a+b)) # else: # print('выберите правильный оператор') # a = input('введите пол\n') # b = input('введите возраст\n') # a = str(a) # b = int(b) # print(a) # print(b) # if (a =='ж' and b >= 18) or (a =='м' and b >= 21): # print('Добро пожаловать') # elif (a =='ж' and b < 18) or (a =='м' and b < 21): # print('Запрещено') # a = input('выберите продукт\n') # b = input('сколько кг\n') # a = str(a) # b = int(b) # if a == "яблоко": # summa = b * 100 # print(summa) # elif a == "груша": # summa = b * 200 # print(summa) # a = input("ваш возраст") # a = int(a) # b = input("зарплата") # if a > 21 and a < 30 and int(b) > 1000000: # print("звони 777568991") # else: # print("thank you, next") # a = ["vinograd", 23, 96, 74, 'lozhka'] # print(a[-3]) # d = { # 'soz' : 'vinograd', # 'cifra' : 23, # "chislo" : 96, # "vozrast" : 74, # 'vesh' : 'lozhka' # } # print(d['vesh']) # massiv = [1,2,3,1,2,3,2,17,45,7,45,8,'low',2,3,1,3] # x = 13 # while x < len(massiv): # if massiv[x] == 'low': # print('индекс: ' , x) # break # x = x + 1 # for x in range (0,10): # print('я прграмист') # for x in range (1,100): # print(x) # summa = [1, 100] # x = 0 # while x < summa: # print('индекс: ' , x) # # bre?"ak # def say_hello(name,age): # print('hello ' + name) # # print(name, age) # # say_hello('Arkhat', 23) # import datetime # n = datetime.datetime.now() # print(n) # # def plus(a, b): # # c = a * b # # return c # jauabi = plus(2, 3) # print(jauabi) # # x = 1 # # summa = 0 # # while x <= 5: # # print(x) # # # summa = summa + x # # x = x + 1 # a =['asdz', 'asdas', 'Aza', 'Madina', 'Iza'] import requests import json # croco = requests.post('http://example.com/', data={'key': 'value'}) # print(croco.text) # url = "https://api-football-v1.p.rapidapi.com/v2/predictions/157462" # headers = { # 'x-rapidapi-key': "SIGN-UP-FOR-KEY", # 'x-rapidapi-host': "api-football-v1.p.rapidapi.com" # } # response = requests.request("GET", url, headers=headers) # print(response.text) ploads = {'things':2,'total':25} r = requests.get('https://httpbin.org/get',params=ploads) res = r.text res = json.loads(res) print(res['args']['total']) print(res["headers"]['Host'])
bfe4f38860012acb11c7045563159f759408c168
abhaysinh/Data-Camp
/Cleaning Data with PySpark/Cleaning Data with PySpark/04- Complex processing and data pipelines/01-Quick pipeline.py
1,181
3.53125
4
''' Quick pipeline Before you parse some more complex data, your manager would like to see a simple pipeline example including the basic steps. For this example, you'll want to ingest a data file, filter a few rows, add an ID column to it, then write it out as JSON data. The spark context is defined, along with the pyspark.sql.functions library being aliased as F as is customary. Instructions 100 XP Import the file 2015-departures.csv.gz to a DataFrame. Note the header is already defined. Filter the DataFrame to contain only flights with a duration over 0 minutes. Use the index of the column, not the column name (remember to use .printSchema() to see the column names / order). Add an ID column. Write the file out as a JSON document named output.json. ''' # Import the data to a DataFrame departures_df = spark.read.csv('2015-departures.csv.gz', header=True) # Remove any duration of 0 departures_df = departures_df.filter(departures_df[3] > 0) # Add an ID column departures_df = departures_df.withColumn('id', F.monotonically_increasing_id()) # Write the file out to JSON format departures_df.write.json('output.json', mode='overwrite')
d47fae19d75a6324efa9361831a9f7a8793b98bc
caroline-mccain/aiddata-technical-test
/question1.py
2,945
4.125
4
# https://docs.python.org/3/library/math.html import math # https://docs.python.org/3/library/os.html import os # create arrays to hold the points a_points = [] b_points = [] # hard-coded file paths # file_path_a = "C:\\Users\\carol\\Desktop\\Sophomore Year\\TechnicalTest\\TechnicalTest\\Question1\\a.csv" # file_path_b = "C:\\Users\\carol\\Desktop\\Sophomore Year\\TechnicalTest\\TechnicalTest\\Question1\\b.csv" # relative file paths cur_wd = os.getcwd() file_path_a = os.path.join(cur_wd, "Question1\\a.csv") file_path_b = os.path.join(cur_wd, "Question1\\b.csv") # helper function that reads points from file def points_from_file(file, array): # open the specified file with open (file, 'r') as file_r: # skip over the header line of the file file_r.readline() # read in each line in the file for line in file_r.readlines(): # split the line at the commas point = line.split(',') # the x coordinate is in the first cell x = float(point[0]); # the y coordinate is in the second cell y = float(point[1]); # create a point array point_array = [x, y] # append this point to the specified points array array.append(point_array) # read in point set a and point set b and populate their respective arrays points_from_file(file_path_a, a_points) points_from_file(file_path_b, b_points) # helper function that calculates the distance between a and b def distance_calc(a, b): return math.sqrt(math.pow((a[0] - b[0]), 2) + math.pow((a[1] - b[1]),2)) # holds the current minimun distance min_dist = float('inf') # holds the points that give the current minimun distance min_dist_points = ["a","b"] # holds the current maximum distance max_dist = 0.0 # holds the points that give the current maximum distance max_dist_points = ["a","b"] # traverse through all of the a points for p_a in a_points: # traverse through all of the b points for p_b in b_points: # calculate the distance between the current pair of points dist = distance_calc(p_a, p_b) # compare the calculated distance to the current minimum if (dist < min_dist): # if this pair yields a smaller distance, store that distance and these points min_dist = dist min_dist_points[0] = p_a min_dist_points[1] = p_b # compare the calculated distance to the current maximum if (dist > max_dist): # if this pair yields a greater distance, store that distance and these points max_dist = dist max_dist_points[0] = p_a max_dist_points[1] = p_b # print results print("Minimun Distance (Closest Together): " + str(min_dist_points)) print("Maximum Distance (Farthest Apart): " + str(max_dist_points))
2aae111f0c9efcbe4f6ac66ae578893d2c89e100
981377660LMT/algorithm-study
/7_graph/带权图最短路和最小生成树/floyd多源/2642. 设计可以求最短路径的图类-更新边的floyd.py
2,270
3.921875
4
# https://leetcode.cn/problems/design-graph-with-shortest-path-calculator/solution/geng-da-shu-ju-fan-wei-diao-yong-shortes-ibmj/ # 请你实现一个 Graph 类: # !Graph(int n, int[][] edges) 初始化图有 n 个节点,并输入初始边。 # !addEdge(int[] edge) 向边集中添加一条边,其中 edge = [from, to, edgeCost] 。 # 数据保证添加这条边之前对应的两个节点之间没有有向边。 # !int shortestPath(int node1, int node2) 返回从节点 node1 到 node2 的路径 最小 代价。 # 如果路径不存在,返回 -1 。一条路径的代价是路径中所有边代价之和。 # 1 <= n <= 100 # 0 <= edges.length <= n * (n - 1) # !调用 shortestPath 1e5 次 from typing import List, Tuple INF = int(1e18) class Graph: __slots__ = "_dist" def __init__(self, n: int, edges: List[Tuple[int, int, int]]): dist = [[INF] * n for _ in range(n)] for i in range(n): dist[i][i] = 0 for u, v, w in edges: dist[u][v] = w for k in range(n): for i in range(n): for j in range(n): cand = dist[i][k] + dist[k][j] if dist[i][j] > cand: dist[i][j] = cand self._dist = dist def addEdge(self, edge: Tuple[int, int, int]) -> None: """ 向边集中添加一条边,保证添加这条边之前对应的两个节点之间没有有向边. 加边时,枚举每个点对,根据是否经过edge来更新最短路. """ u, v, w = edge n = len(self._dist) for i in range(n): for j in range(n): cand = self._dist[i][u] + w + self._dist[v][j] if self._dist[i][j] > cand: self._dist[i][j] = cand def shortestPath(self, start: int, target: int) -> int: """返回从节点 node1 到 node2 的最短路.如果路径不存在,返回 -1.""" return self._dist[start][target] if self._dist[start][target] < INF else -1 # Your Graph object will be instantiated and called as such: # obj = Graph(n, edges) # obj.addEdge(edge) # param_2 = obj.shortestPath(node1,node2)
3888bb19bf99926d1de3977ead6ffff9b4cd0bf0
Mattia-Tomasoni/Esercizi-Python
/es14pag189.py
1,095
3.578125
4
''' ESERCIZIO 14 PAG 189 Organizza in una struttura di dati i valori degli occupati negli ultimi dieci anni. Utilizza un dizionario, assegnand il ruolo di chiave all'anno. Inserisci i dati da tastiera e memorizzabili nel contenitore. Calcola poi il valore medio dei dieci anni e visualizzane il risultato. ''' from statistics import mean#Dalla libreria statistics importa la funzione mean dati_occupati = {} lista_occupati = [] c = 1 while True: occupati = input("Quanti sono gli occupati il "+ str(c) + "° anno(* = fine)? ") if occupati == "*": break#Interrompe il ciclo else: occupati = int(occupati)#Trasforma occupati da str a int dati_occupati[str(c) + "° anno"] = occupati#Aggiunge al dizionario una chiave e le assoce il suo valore lista_occupati.append(occupati)#Aggiunge occupati a lista_occupati c += 1 print() print() print("Questa è la lista di occupati per anno: ") for e in dati_occupati: print(e, ":", dati_occupati[e]) print() print("Questa è la media di lavoratori annui: ", mean(lista_occupati))
3f92984f231196b6aaf729b847561d40c0e87bc0
zabdulre/Algorithms-
/codeforces/71A-LongWords.py
198
3.859375
4
numberOfWords = input() for i in range(int(numberOfWords)): word = input() if len(word) > 10: abbreviation = word[0] + str((len(word) - 2)) + word[-1] print(abbreviation) else: print(word)
a2b82ac3665372c112fb10ef8f4250d255155acf
usunday/python_examples
/left.py
223
3.875
4
def left_join(phrases): """ Join strings and replace "right" to "left" """ string = ','.join(phrases).replace('right', 'left') return string s=left_join(("left", "right", "left", "stop")) print(s)
af8f970440e7c54e77090d026603a63392c18c0f
chinnuz99/luminarpython
/regular expression/rules1.py
438
4.03125
4
import re n="hello" x='\w*' #"\w" word including special character, "a*" count including zero number of a match=re.fullmatch(x,n) if match is not None: print("valid") else: print("invalid") # # import re # n = "hello*-+" # x = '\w*' # "\w" word including special character, "a*" count including zero number of a # match = re.fullmatch(x, n) # if match is not None: # print("valid") # else: # print("invalid")
940679b03d9576fb44b099ea32556d4a7d10d2ef
Eric-Wonbin-Sang/CS110Manager
/2020F_hw6_submissions/bunissamuel/homework 6 p 2.py
489
4.28125
4
def main(): date = input("Enter the date: ") mm,dd,yy = date.split('/') mm = int(mm) dd = int(dd) yy = int(yy) if(mm == 1 or mm == 3 or mm == 5 or mm == 7 or mm == 8 or mm == 10 or mm == 12): day = 31 elif(mm == 4 or mm ==6 or mm == 9 or mm == 11): day = 30 if(mm < 1 or mm > 12): print("The date is invalid") elif(dd < 1 or dd > day): print("The date is invalid") else: print("The date is valid") main()
14d631e1c269eb1b5777ade6db55db3af845bcf9
ywpark/Python3
/STEP8/ExRegular.py
5,966
3.828125
4
# Regular Expressions import re # pattern = r'spam' # raw string # # if re.match(pattern, 'spamspamspam'): # re.match 는 string beggining 이다 # print('Match') # else: # print('No match') # # if re.match(pattern, 'eggspamsausagespam'): # print('Match') # else: # print('No match') # # if re.search(pattern, 'eggspamsausagespam'): # re.search 는 pattern anywhere in the string # print('search Match') # else: # print('search No match') # # print('find all = ', re.findall(pattern, 'eggspamsausagespam')) # re.findall 는 return a list of all substrings that match a pattern # pattern = r'pam' # # match = re.search(pattern, 'eggspamsausage') # if match: # print(match.group()) # returns the string matched # print(match.start()) # print(match.end()) # print(match.span()) # returns the start and end positions of the first match as a tuple # str = 'My name is David. Hi David.' # pattern = r'David' # newstr = re.sub(pattern, 'Amy', str, 1) # print(newstr) # Metacharacters # pattern = r'gr.y' # dot match any character # # if re.match(pattern, 'grey'): # print('Match 1') # # if re.match(pattern, 'gray'): # print('Match 2') # # if re.match(pattern, 'blue'): # print('Match 3') # pattern = r'^gr.y$' # ^ : start , $ : end # # if re.match(pattern, 'grey'): # print('Match') # # if re.match(pattern, 'gray'): # print('Match') # # if re.search(pattern, 'stingray'): # print('Match') # Character Classes # pattern = r'[aeiou]' # only one of a specific set of characters. # # if re.search(pattern, 'grey'): # print('Match 1') # # if re.search(pattern, 'qwertyiop'): # print('Match 2') # # if re.search(pattern, 'rhythm myths'): # print('Match 3') # pattern = r'[A-Z][A-Z][0-9]' # match ranges of characters. # # if re.search(pattern, 'LS8'): # print('Match 1') # # if re.search(pattern, 'E3'): # print('Match 2') # # if re.search(pattern, '1ab'): # print('Match 3') # pattern = r'[^A-Z]' # ^ 반대의 의미 ( invert ) # # if re.search(pattern, 'this is all quiet.'): # print('Match 1') # # if re.search(pattern, 'AbCdEfG123'): # print('Match 2') # # if re.search(pattern, 'THISISALLSHOUTING'): # print('Match 3') # Metacharacters # # pattern = r'egg(spam)*' # * zero or more repetitions of the previous thing # # () * 에서 말한 previous thing can be a single character, a class, or a group of characters in parentheses # # if re.match(pattern, 'egg'): # print('Match 1') # # if re.match(pattern, 'eggspamspamegg'): # print('Match 2') # # if re.match(pattern, 'spam'): # print('Match 3') # pattern = r'g+' # + one or more repetitions # # if re.match(pattern, 'g'): # print('Match 1') # # if re.match(pattern, 'ggggggggggggggg'): # print('Match 2') # # if re.match(pattern, 'gabc'): # print('Match 3') # pattern = r'ice(-)?cream' # ? means zero or one repetitions # # if re.match(pattern, 'ice-cream'): # print('Match 1') # # if re.match(pattern, 'icecream'): # print('Match 2') # # if re.match(pattern, 'sausages'): # print('Match 3') # # if re.match(pattern, 'ice--ice'): # print('Match 4') # pattern = r'9{1,3}$' # {x,y} between x and y repetitions of something # # if re.match(pattern, '9'): # print('Match 1') # # if re.match(pattern, '999'): # print('Match 2') # # if re.match(pattern, '9999'): # print('Match 3') # Groups # pattern = r'egg(spam)*' # # if re.match(pattern, 'egg'): # print('Match 1') # # if re.match(pattern, 'eggspamspamspamegg'): # print('Match 2') # # if re.match(pattern, 'spam'): # print('Match 3') # # groups in a match can be accessed pattern = r'a(bc)d' #pattern = r'[a-z]@([a-z].[a-z])' match = re.match(pattern, 'abcdefghijklmnop') #match = re.match(pattern, 'a@b.d') if match: print(match.group()) # whole match print(match.group(0)) # whole match print(match.group(1)) # nth group from the left #print(match.group(2)) print(match.groups()) # all groups # # group naming 형식 -> (?P<name>...) name 으로 접근가능하다 # # Non-capturing groups -> (?:...) 형식은 group 메소드로 접근이 불가능하다 # pattern = r'(?P<first>abc)(?:def)(ghi)' # # match = re.match(pattern, 'abcdefghi') # # if match: # print(match.group('first')) # print(match.groups()) # pattern = r'gr(a|e)y' # | -> or 의 의미 red|blue 'red' or 'blue' # # match = re.match(pattern, 'gray') # # if match: # print('Match 1') # # match = re.match(pattern, 'grey') # # if match: # print('Match 2') # # match = re.match(pattern, 'graey') # # if match: # print('Match 3') # Special Sequences # pattern = r'(.+) \0' # \1 means a repetition of what was found in group number 1 # # match = re.match(pattern, 'word word') # if match: # print('Match 1') # # match = re.match(pattern, '?! ?!') # if match: # print('Match 2') # # match = re.match(pattern, 'abc cde') # if match: # print('Match 3') # pattern = r'(\D+\d)' # 대문자는 소문자의 반대 의미 # # \d : digits, \s : whitespace , \w : word characters # # match = re.match(pattern, 'Hi 999!') # if match: # print('Match 1') # # match = re.match(pattern, '1, 23, 456!') # if match: # print('Match 2') # # match = re.match(pattern, '!$?233') # if match: # print('Match 3') # pattern = r'\b(cat)\b' # \A , \Z : match the beginning and end of a string # # \b : 일반적인 character 가 아닌 것들 # # match = re.search(pattern, 'The cat sat!') # if match: # print('Match 1') # # match = re.search(pattern, 'We s>cat<tered?') # if match: # print('Match 2') # # match = re.search(pattern, 'We @cat#tered.') # if match: # print('Match 3') # Email Extraction # pattern = r'([\w\.-]+)@([\w\.-]+)(\.[\w\.]+)' # str = 'Please contact in123234-.fo@solo-lean.com for assistance' # # match = re.search(pattern, str) # if match: # print(match.group())