blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
545k
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
545k
0436dee19634438870f2c0b4584a8fde330ff2f0
ApurvaW18/python
/Day 10/Q1 to Q15.py
2,644
4.0625
4
import numpy as np ''' 1.Write a NumPy program to get the numpy version and show numpy build configuration. print(np.__version__) 2.Write a NumPy program to test element-wise for complex number, real number of a given array. Also test whether a given number is a scalar type or not. c=2+5.25j print(np....
3a81a4436ed70fba3f71886abe7c7b8fd0b3f9a6
ApurvaW18/python
/Day1/Q2.py
586
4.0625
4
''' Que2:With a given integral number n, write a program to generate a dictionary that contains (i, i*i) such that is an integral number between 1 and n(both included). and then the program should print the dictionary. Suppose the following input is supplied to the program: 8 Then, the output should be: {1: 1, 2...
3f82de6f9240b9a40c4553657503eede29a82bdc
ApurvaW18/python
/Day 3/Q4.py
307
3.921875
4
''' 4.Accept data in two 3*3 matrix and calculate the sum of the matrices. ''' a=[[10,20,30],[40,50,60],[70,80,90]] b=[[90,80,70],[60,50,40],[30,20,10]] t=[[0,0,0],[0,0,0],[0,0,0]] for i in range(len(a)): for j in range(len(a[0])): t[i][j]=a[i][j]+b[i][j] for k in t: print(k)
efea91f3919f1f3bc91cafa9dc56cc38dcc34dc8
JulietaCaro/Programacion-I
/Trabajo Practico 3/Ejercicio 1.py
5,584
4.1875
4
# 1. Desarrollar cada una de las siguientes funciones: # a. Cargar números enteros en una matriz de N x N, ingresando los datos desde teclado. # b. Ordenar en forma ascendente cada una de las filas de la matriz. # c. Intercambiar dos filas, cuyos números se reciben como parámetro. # d. Intercambiar dos columnas dad...
15ebe42761bea8ab1fb3de226499d85ae102ddf6
JulietaCaro/Programacion-I
/Trabajo Practico 4/Ejercicio 12.py
853
4.0625
4
# 12.Desarrollar una función para reemplazar todas las apariciones de una palabra por otra en una cadena de caracteres # y devolver la cadena obtenida y un entero con la cantidad de reemplazos realizados. # Escribir también un programa para verificar el comportamiento de la función. # FUNCIONES def reemplazarApar...
aa1ada7e81e64075c99197bddac25b0bffdf3a39
JulietaCaro/Programacion-I
/Trabajo Practico 8/Tuplas/Ejercicio 5.py
1,001
3.953125
4
# Escribir una función que reciba dos vectores en forma de tuplas y devuelva un valor de verdad indicando si son ortogonales o # no. Desarrollar también un programa que permita verificar el comportamiento de la función. # A = (2,3) y B = (-3,2) => 2 * (-3) + 3 * 2 = -6 + 6 = 0 => Son ortogonales def verificarOrto...
89761125d4fc792edc01fd368dc3d071545af202
JulietaCaro/Programacion-I
/Trabajo Practico 2/Ejercicio 3.py
444
3.875
4
#3. Crear una lista con los cuadrados de los números entre 1 y N (ambos incluidos), #donde N se ingresa desde el teclado. Luego se solicita imprimir los últimos 10 valores de la lista. from funciones import pedirYValidarNum #FUNCIONES def main(): 'Programa principal' numN = pedirYValidarNum() listaCu...
b048aeb9eded722f81e2b1b084da6549938457fa
JulietaCaro/Programacion-I
/Trabajo Practico 4/Explicacion PPT/Ejer pais.py
218
3.96875
4
# Pedir el pais y decir si es arg o no pais = input("Ingrese el pais donde nacio: ") minPais = pais.capitalize() if minPais == "Argentina": print("Usted es argentino") else: print("Usted no es argentino")
2e54bd35ce68792dc83c1f9bcccb13670e378a46
JulietaCaro/Programacion-I
/Trabajo Practico 1/Ejercicio 2.py
1,048
3.96875
4
#FUNCIONES def positivo (valor): while valor < 0: valor = int(input("Ingrese un numero positivo: ")) return valor def fechaValida(dia, mes, año): fecha = True bisiesto = False if ((año%4 == 0 and año%100 != 0) or año%400 == 0): bisiesto = True if mes <...
09e8a1f3816fcdbeba2632c33b93a7dbfc46d46d
JulietaCaro/Programacion-I
/Trabajo Practico 2/Ejercicio 11.py
830
4.40625
4
#11. Intercalar los elementos de una lista entre los elementos de otra. La intercalación #deberá realizarse exclusivamente mediante la técnica de rebanadas y no se creará #una lista nueva sino que se modificará la primera. Por ejemplo, si lista1 = [8, 1, 3] #y lista2 = [5, 9, 7], lista1 deberá quedar como [8, 5, 1, ...
aa38ec0ca5623804f8d5ca71268e0ce7b6187496
JulietaCaro/Programacion-I
/Trabajo Practico 5/Explicacion PPT/while true.py
175
4
4
#Ingresar numeros hasta -1 suma = 0 while True: num = int(input("Ingrese un numero: ")) if num == -1: break suma = suma+num print("Suma: ",suma)
e944521a3543388d97642e45fcb3f413b555a557
JulietaCaro/Programacion-I
/Trabajo Practico 2/Ejercicio 4.py
632
3.90625
4
#4. Definir una función superposición() que reciba como parámetros dos listas de cualquier tipo #y devuelva True si tienen al menos un elemento en común, o False encaso contrario. #Desarrollar un programa para verificar su comportamiento. #FUNCIONES def superposicion(listaA,listaB): 'Devuelve true si tienen ...
23d611bc30083346d20f96ed7cefc84dc1fb6a8f
JulietaCaro/Programacion-I
/Trabajo Practico 1/Ejercicio 4.py
1,011
3.71875
4
#FUNCIONES def totalGastado(tarifa, viajes): if viajes > 1 and viajes <= 20: total = viajes * tarifa if viajes > 20 and viajes <= 30: tarifaFinal = tarifa - (20*tarifa)//100 total = viajes * tarifaFinal if viajes > 30 and viajes <= 40: tarifaFinal = tarifa - (30*tarif...
3cb2c6ecffde5c7deb96444d2e04dc24adf8dcc5
JulietaCaro/Programacion-I
/Trabajo Practico 8/Conjuntos/Ejercicio 7.py
607
4.0625
4
# Ingresar una frase desde el teclado y eliminar las palabras repetidas, dejando un solo ejemplar de cada una. Finalmente mostrar # las palabras ordenadas según su longitud. La eliminación de las palabras duplicadas debe realizarse a través de un conjunto. def eliminarRepetidas(frase): frase = frase.lower() ...
ac24d46e891f6add58f2dd5b750134923466596d
JulietaCaro/Programacion-I
/Trabajo Practico 8/Diccionarios/Ejercicio 10.py
535
4
4
# 10.Escribir una función que reciba un número entero N y devuelva un diccionario con la tabla de multiplicar de N del 1 al 12. # Escribir también un programa para probar la función def tablaMultiplicar(n): dic = {} for i in range(1,13): dic[i] = n*i return dic def imprimirDiccionario(dic...
2b957856684056fdad48fc84aa6edafa70598df9
JulietaCaro/Programacion-I
/Trabajo Practico 4/Ejercicio 13.py
1,539
4.1875
4
# 13.Escribir un programa que cuente cuántas veces se encuentra una subcadena dentro de otra cadena, sin diferenciar # mayúsculas y minúsculas. Tener en cuenta que los caracteres de la subcadena no necesariamente deben estar en forma # consecutiva dentro de la cadena, pero sí respetando el orden de los mismos. # F...
134311f98bd545be035b029ab54cbd8915fb2362
JulietaCaro/Programacion-I
/Trabajo Practico 6/Ejercicio 1.py
1,411
3.875
4
# 1.Desarrollar un programa para eliminar todos los comentarios de un programa escrito en lenguaje Python. Tener en cuenta # que los comentarios comienzan con el signo # (siempre que éste no se encuentre encerrado entre comillas simples o dobles) y # que también se considera comentario a las cadenas de documentación...
1617d0cd0c801f66c436d74b09b4b367ea6a100c
JulietaCaro/Programacion-I
/Trabajo Practico 5/Ejercicio 3.py
831
4.03125
4
# 3.Desarrollar una función que devuelva una cadena de caracteres con el nombre del mes cuyo número se recibe como parámetro. # Los nombres de los meses deberán obtenerse de una lista de cadenas de caracteres inicializada dentro de la función. # Devolver una cadena vacía si el número de mes es inválido. La detección ...
a876dcf61ad791d5841ff0fdf5d2926774763f16
JulietaCaro/Programacion-I
/Trabajo Practico 7/Explicacion PPT/suma recursiva.py
192
3.796875
4
# Calcular la suma de los N primeros números naturales. def sumaRecursiva(n): if n == 0: return 0 else: return n + sumaRecursiva(n-1) print(sumaRecursiva(3))
4d6b88ed81bd61f28bde8bf629f9257c8ce647ec
sirelkhatim/Project-2---Datastructures-Algorithms
/lru_cache.py
2,024
3.9375
4
### data structure to store key, value, times used from collections import deque class LRU_Cache(object): def __init__(self, capacity): # Initialize class variables self.cache = {} self.lru = deque() self.capacity = capacity def set_lru_capacity(self): if len(self.lru)...
1e22265cdf325110c4dab2cf1cb20b2d05dcd5ab
JastrzebskiB/PyTraining_Snake
/game.py
11,816
4.03125
4
""" Tried to keep true to the PEP-8 good code practices. The comments are pretty verbose, but I try to explain my reasoning fully in them. All questions are welcome either through Facebook event page, on Facebook direct message or at jastrzebskib (at) gmail (dot) com. Things that could be modified if you want to play ...
5033050ff01955dc2bbdbf0b7d5a1834a588fd8c
I-ll-Go-Rythm/2021_winter_study
/junhee/divide_conquer/별찍기_깨달음.py
700
3.78125
4
def draw(H): if H == 3: return [['*','*','*'],['*',' ','*'],['*','*','*']] temp=[] starlist=[] for i in range(H): temp.append(0) for i in range(H): starlist.append(temp)#temp를 바꾸면 starlist도 바뀜 h = H//3 last_star = draw(h) for i in range(3): for j in range(...
3cb8bdbc35c2f35ce1f15185c156bb7dd53f70ed
I-ll-Go-Rythm/2021_winter_study
/junhee/brute_force/분해합_2231.py
485
3.65625
4
in_num = input() in_num = int(in_num) digit = 0 def digit_sum(a): global digit Sum = 0 while a != 0: Sum += a%10 digit += 1 a = int(a/10) return Sum digit_sum(in_num) i = 9*digit if digit == 1 and in_num % 2 == 0: print(int(in_num/2))s else: while i!...
2736524f8b8f2c4a2fa6d0732e5c996af96e9bb9
vipnormalhy/learn
/python/coroutine.py
551
3.828125
4
#!/usr/bin/env python # -*- coding:utf-8 -*- def consumer(): print "Init a consumer" n = 0 while True: n = yield if n <= 0: print 'Wait for next product' continue n -= 1 print 'consume a product, now product = %d' % n def producer(consumer): print 'Init a producer' while True: print 'produced a...
4f48dc3ba410b24cf152a385a850d67048ecdaaf
oski89/udemy
/complete-python-3-bootcamp/my-files/advanced_sets.py
914
4
4
# advanced sets s = set() s.add(1) s.add(2) print(s) s.add(2) # won't add 2 since it is already in set print(s) sc = s.copy() # makes a copy of set s s.add(4) # adds 4 to set s print(s) print(s.difference(sc)) # prints elements in s1 not found in s2 s1 = {1, 2, 3} s2 = {1, 4, 5} print("s1:", s1) print("s2:", s...
8104aae810a1d0987d16c10ef9410ea73583317e
oski89/udemy
/complete-python-3-bootcamp/my-files/legb.py
552
4.03125
4
# LEGB - Ther order of assignment # L = Local (inside function) # E = Enclosing function locals (inside function of function) # G = Global # B = Built-in # It is often better to take in local arguments and return them rather than make variables global x = 'GLOBAL' def func(): x = 'ENCLOSING' def hello(): ...
fe7b67785e6c74b8afb9eb66931a0396028b38c1
oski89/udemy
/complete-python-3-bootcamp/my-files/try_except_finally.py
621
3.953125
4
# Error handling try: f = open('testfile2', 'r') f.write("Write a test line") except TypeError: print("Hey, there was a TypeError") except OSError: print("Hey, you have an OSError") except: print("All other exceptions!") finally: print("I always run!") def ask_for_int(): while True: ...
9fef6a6753a7fc3f577a737d811d5179fe0d1435
oski89/udemy
/complete-python-3-bootcamp/my-files/advanced_lists.py
398
4.25
4
l = [1, 2, 3, 3, 4] l.append([5, 6]) # appends the list as an item print(l) l = [1, 4, 3, 3, 2] l.extend([5, 6]) # extends the list print(l) print(l.index(3)) # returns the index of the first occurance of the item l.insert(2, 'inserted') # insertes at index print(l) l.remove(3) # removes the first occurance pr...
30b1917bb2c16b8ab4726e6de58c8079eaaa5236
matthdll/Python
/login.py
221
3.609375
4
login = (input('Digite seu Login: ')) senha = (input('Digite sua Senha: ')) while senha == login: print ('Your password must to be different of your user please try again: ') senha = input('Senha: ')
205f2040f57618b0988360eb73e25b7491ce2fb5
NickRuiz/moses-mt-server
/code/xliff/xml2txt.py
926
3.578125
4
#!/usr/bin/python import sys import xml.etree.ElementTree as ET import re ''' extract all text from xml files ''' def peel(s): # remove one layer of tags re_tag = re.compile(r"^<[^>]+>(?P<inner>.*)<[^>]+>$", re.DOTALL) m = re_tag.match(s.strip()) if m: return m.groupdict()['inner'].strip() ...
310f242008eac048fc61257eebd8643d1517b6c4
3leno4ka/python_basic_course
/l4_iteration/l4_iteration.py
679
4.03125
4
low_digit_limit = 1 upper_digit_limit = 100 my_new_list = [] while True: favorite_num = input("Enter your favorite number: ") try: favorite_num = int(favorite_num) my_new_list.append(favorite_num) if favorite_num < low_digit_limit: print(f'Your input value is less than {low_...
b1c8a9a6d4757f3917c849e7db8851e76a3345e1
3leno4ka/python_basic_course
/l5_function/my_first_package/my_functions.py
242
3.75
4
def my_func(name, surname, age): if age < 25: print(f'Hello, {name} {surname}. You are young enough.') if age >= 25: print(f'Hello, {name} {surname}. You are old.') def year_of_birth(age): print(f'{2018 - age}')
009d16dcf7ecf2487db2b46a912147eb5ba5668e
jimmyren23/minimax-fair
/src/paired_regression_classifier.py
2,243
3.78125
4
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 from sklearn.linear_model import LinearRegression class PairedRegressionClassifier: """ A custom machine learning algorithm for fair classification. Trains two regression models for predicting posi...
3489689bd1808494a1e6f20f4751b4011e6ae384
hyfzur/pythonSelenium
/sample-test/6_how_to_work_with_a_checkbox.py
911
3.546875
4
import time from selenium import webdriver from selenium.webdriver import DesiredCapabilities hubUrl = "http://localhost:4444/wd/hub" capsChrome = DesiredCapabilities.CHROME driver = webdriver.Remote(command_executor=hubUrl, desired_capabilities=capsChrome) driver.get('http://the-internet....
7ee567aacc01208ec256af3ac0b971221c8e52eb
sdwebster/learn-python-the-hard-way-solutions
/19/ex19.py
496
3.640625
4
def cheese_and_crackers(cheese_count, boxes_of_crackers): print "You have %d cheeses!\nYou have %d boxes of crackers!" % (cheese_count, boxes_of_crackers) print "Man that's enough for a party!\nGet a blanket.\n" print "We can just give the function numbers directly!" cheese_and_crackers(20, 30) cheese_count = 100...
5131bd93005dd1108f74fcff4d2dbffb4217d711
syedhammad618/Bioinformatics
/test3.py
774
3.671875
4
seq = open('test1.txt', 'r') import itertools chains=[] [chains.append(line[:-1]) for line in seq] # motif_name=input('Enter Motif name: ') s='ABCDEFGHIJKLMNOPQRSTUVWXYZ' t=list(itertools.combinations(s,2)) list1=[] list2=[] list3=[] for i in t: w=''.join(i) word1="S{0}K".format(w) list1.append(word1) fo...
24168b26d13c024cc52d9e98a4adb735bcd20c10
diwakar1998/Maze-Solver
/mazeSolver.py
6,508
4.09375
4
""" Modify the maze to see if it works maze represented using "#"-for wall " "-for path "o"-for starting point """ maze=[] maze.append(['#','#','#',' ','#']) maze.append(['#',' ','o',' ','#']) maze.append([' ',' ','#',' ','#']) maze.append(['#',' ','#','#',' ']) mazeCord={} #max values of (row,columns...
9271324b87d2c13a5cf3fd3d113c9c3bce9516f1
golfnut1400/Python101
/WhileLoop_using len.py
319
3.65625
4
#Loops through 'apple' fruit = "apple" position = 0 while position < len(fruit): print(fruit[position]) #print position position = position + 1 # # prints: # a # p # p # l # e print print s = "python rocks" idx = 1 while idx < len(s): #print(s[idx]) idx = idx + 2 print((idx),":",(s[idx]))
63cc1af0f9b8fc26c4c93df10e637e69c6356d46
golfnut1400/Python101
/List_using randon choice.py
364
3.6875
4
# use of random, not in import random all_data = random.sample(range(1000),15) #creates 15 random numbers up to 1000 #all_data = [1,2,2,3,4,5,6,7,8,8,9,10,11,11,12,13,14,15,15] #hard coded list choices = [] while len(choices) < 4: selection = random.choice(all_data) if selection not in choices: ...
8a7a7e8b02b3ca96c8e4e8f3389c890961b5c22e
golfnut1400/Python101
/Strings_in and not in.py
298
3.9375
4
# use of 'in' print('p' in 'apple') # True print('i' in 'apple') # True print('ap' in 'apple') # True print('pa' in 'apple') # False print('a' in 'a')# True print('apple' in 'apple')# True print('' in 'a')# True print('' in 'apple')# True # use of 'not in' print('x' not in 'apple')
800319d01235504239ac6011970662a0b9dc7a76
Tduncan14/PythonCode
/pythonGuessGame.py
834
4.21875
4
#Guess my number ## #The computer picks a random number between 1 and 100 #The player tries to guess it and the computer lets #The player on guessing the numner is too high, too low # or right on the money import random print("\tWelcome to 'Guess My Number'!") print("\n I'm thinking of a number between 1 and 100.") ...
0b915741fbf604a2f8152d291185a362296f8b7f
eugenezakh/balhard_4_tasks
/tasks/list_tasks/del_last.py
674
3.921875
4
""" ЗАДАНИЕ -------------------------------------------------------------------------------- Электронная очередь. Имеется список посетителей. Чтобы подозвать человека к окошку - нужно удалить последнего посетителя из списка и вернуть его номерок """ client_list = [123, 321, 213] def del_last(collection: list) -> int...
28b0b9941f4af49aa340902b4e278f817913b0f0
eugenezakh/balhard_4_tasks
/tasks/list_tasks/first_3_last_3.py
1,126
3.890625
4
""" ЗАДАНИЕ -------------------------------------------------------------------------------- На сайте необходимо вывести количество страниц для перехода по ним. Так как список страниц очень большой, то необходимо вывести первые три и последние 3, а промежуточные заменить "..." Написать функцию, которая принимает списо...
c34077c79fd7914ec5d89fa782475481db3ec6e4
eugenezakh/balhard_4_tasks
/tasks/list_tasks/first_last.py
806
4.03125
4
""" ЗАДАНИЕ -------------------------------------------------------------------------------- Есть список работников, отсортированный по из производительности. Отредактировать функцию get_first_last таким образом, чтобы можно было узнать кто лучший, а кто худший работник """ workers = [ "Зебест Иван Суперович", ...
9aaf6a7074faa31598b20f9354a4b19f4e567a08
eugenezakh/balhard_4_tasks
/tasks/list_tasks/count_element.py
960
3.671875
4
""" ЗАДАНИЕ -------------------------------------------------------------------------------- На сервере хранится лог запросов к серверу. Администратору необходимо знать, сколько ошибок произошло за день. Отредактировать функцию count_elements таким образом, чтобы с ее помощью можно было посчитать количество элементов ...
78aa63ab11d675859c5f683cb02bbb1541bfbd18
Arlisha2019/Calculator-EvenOdd-FizzBuzz
/EvenOdd.py
215
4.28125
4
user_number = int(input("Enter a number: ")) def even_or_odd(): if(user_number % 2 == 0): print("You entered an even number!") else: print("You have entered an odd number!") even_or_odd()
b469d953a0e6b939afc18731e6481d429a2395f7
rishi-koul/Cracking-the-Coding-Interview
/01 - Array And String/06-string_compression.py
1,324
4
4
def string_compression(string): compressed_string = "" prev_letter = "" # Iterate over the string for i in range(0, len(string)): # Add the first element of the string in compressed string if compressed_string == "": compressed_string += string[i] counter = 1 # If it is last letter and...
4741931113c64c098b5d06449bceafc4949bab1f
seen2/Python
/workshop2019/secondSession/function.py
415
4.1875
4
# without parameter def func(): a, b = 10, 20 c = a+b print(c) # func() def funcP(a, b): ''' takes two integer and print its sum ''' c = a+b print(c) # default argument comes last in parameter sequence. def funcDefaultP(a, b=1, c=1): ''' takes three integer and print its su...
e90d7ae10791ac7dd407d940ed3e444770d087c1
seen2/Python
/bitwiseOperators/bitwiseLogicalOperators.py
406
4.125
4
def main(): a=2 # 2=ob00000010 b=3 # 3=ob00000011 # logical operations print(f"{a} AND {b}={a&b}") print(f"{a} OR {b}={a|b}") # takes binary of a and flips its bits and add 1 to it. # whilch is 2 's complement of a print(f"2's complement of {a} ={~a}") # exclusive OR (...
f2741e5e6a3920af24602eb2ba1cb5415065b764
seen2/Python
/workshop2019/tikTakToe/takeIpAndDisplay.py
350
3.640625
4
from printBoard import printBoard def takeIpAndDisplay(theBoard): turn = 'X' for i in range(9): printBoard(theBoard) if turn == 'X': ip = input("X move:") theBoard[ip] = 'x' turn = '0' else: ip = input("0 move:") theBoard[ip]...
b55cfbcecf1a7704df5110e1492c6b4207c7ae6d
seen2/Python
/StringHandling/Practice/uniqueChar.py
216
3.5625
4
def main(): s = input("Enter String:") i = 0 for c in s: i += 1 if c in s[i:]: print(f"{c} occurs so it'sn't unique") break if __name__ == "__main__": main()
711529f915e2fafa1c018d401b4446fa6f727b1d
seen2/Python
/DataStructure/StackAndQueues/stack/arrayStack.py
935
3.90625
4
class Stack: def __init__(self, capacity): self.__data = [0]*capacity self.__capacity = capacity self.__top = 0 def push(self, val): if self.__capacity >= self.__top+1: self.__data[self.__top] = val self.__top += 1 return True else: ...
a00a59aaa630012ebfa400364bc634fda3057a1e
ashish-monal/open-CV
/How to sharpen the image/How to sharpen the image.py
849
3.734375
4
#!/usr/bin/env python # coding: utf-8 # # image sharpening depend on the 2 factors # 1. Resolution # 2.Acutance # What are the needs of Sharpening the image # 1. to overcome Blurring in the images # 2. to Highlight certain areas of the image # 3. to increase the legibilty # In[1]: # import the ...
05da09928b22ae0cfb74b7b22a568c2a35d2a9da
ashish-monal/open-CV
/How to rotate image horizonatally vertically , or at any Angle/How to Rotate a image alonge center , horizontal and vertically.py
1,089
3.703125
4
#!/usr/bin/env python # coding: utf-8 # In[5]: #import requiredd Library for the process import cv2 import numpy as np #store the image in any variable input_image = cv2.imread('Ashish.jpg') cv2.imshow('original Image',input_image) # here we try to know the height and weidth of the image for the rotation heigh...
8f4f7e07bc0eccac62d1a2de900cb9af3adf372d
S1LV3RJ1NX/saarthi
/Python/password.py
580
3.78125
4
import re def password_validate(password): # Check password based on required conditions if not re.search("[a-z]", password): return False if not re.search("[A-Z]", password): return False if not re.search("[0-9]", password): return False if not re.search("[!\"#$%&'()*+,./:;<=>?@[\\]^_`{|}~-]",password)...
ddaa1a4545fb4a2cadbf69ad6addfbfc4a469cea
Doraemon-star/Word-Wrangler
/Word-Wrangler.py
3,628
4
4
""" Student code for Word Wrangler game """ import urllib2 import codeskulptor import poc_wrangler_provided as provided WORDFILE = "assets_scrabble_words3.txt" # Functions to manipulate ordered word lists def remove_duplicates(list1): """ Eliminate duplicates in a sorted list. Returns a new sorted lis...
c4c1594d7151ff8af3f9979ed76b7ef8adbf9344
DimiG/myWINscripts
/Python/Say/say.py
1,877
3.59375
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # ''' @author: Copyright 2014 Dmitri G. <dimi615@pisem.net> ''' # Copyright 2014 Dmitri G. <dimi615@pisem.net> # To bring the speech capability for your Windows computer # Install SAPI5Speech (XP and Windows 7 probably have it already) # Program tested by Windows 7 PC compu...
94ce91d54cdf5374a04215909517b6fce71a3608
Zainab-Kalief/OOP_call_center
/call.py
585
3.671875
4
count = 1 class Call(object): def __init__(self, name, phoneNumber, callTime, reasonForCall): global count self.name = name self.phoneNumber = phoneNumber self.callTime = callTime self.reasonForCall = reasonForCall self.num = count #we create a unique ID by giving eac...
4343fe0acd26d71e4ee7dc92ef0cdf988890aa64
pietro-andreoli/DnDRegex
/main.py
1,650
3.671875
4
from regex import * def print_class_intro(): with open("ClassIntro.txt", 'r') as intro: print(intro.read()) def get_classes(): num_of_classes = 0 class_list = [] with open("Classes.txt", 'r') as class_file: for dnd_class in class_file.readlines(): num_of_classes += 1 ...
40e20f723be03a87c760251c27861a7ed7f95336
oliverboamah/data-structures-and-algos
/leetcode/arrays/duplicate_zeros.py
442
3.625
4
# solution class class Solution: def duplicateZeros(self, arr) -> None: star = 0 i = 0 while i < len(arr): if arr[i] == star: for j in range(len(arr)-1, i, -1): arr[j] = arr[j-1] i += 1 i += 1 ...
a2c6cdca18da7c2f7df637a9074b9c61d24542ae
oliverboamah/data-structures-and-algos
/leetcode/arrays/two_sum.py
760
3.71875
4
'''' Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. You may assume that each input would have exactly one solution, and you may not use the same element twice. You can return the answer in any order. ''' # solution class class Solution: de...
68fba99ac99ffc4e5922f66254df5bc2aa365d3a
FilipMohyla/Cycles-in-Python
/math_operations.py
884
4.03125
4
### Task: Get input (n) from user and count factorial n, figure out if n is prime number # and make fibbonacci sequence up to number n ### from math import factorial numb = int(input("Zadej číslo: ")) fact_numb = factorial(numb) rest = [] fibbo_seq = [1, 1] for sequence in range(2, numb): rest.appe...
6868c968ecb69a243c19ae78dcfb7c18d8c2f198
Kwsswart/utilities-python
/roman.py
1,125
3.65625
4
class roman(): def int_to_roman(self, n): """ Function to convert integers to roman integers """ values = [ 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1] sym =[ "M", "CM", "D", "CD", "C", "XC", "L", "XL"...
8f3b1377e6f85736763845dcfe97aa57537be955
benhg/phylo-text-mining
/data_processing/random_chunk/random_chunking.py
1,386
3.59375
4
import sys import random """ Random Chunking approach. In this methodology, we chunk each gene sequence into random-length "words" For now, we're using "text-document like" files, which means that we're putting everything into plain text files with space-separated chunks """ # minimum and maximum chunk sizes CHUNK_M...
a4d81bb8f016eae398660ae67916e4c1e207a2c1
PubliHero/Web_Academy_python_SE_2
/lesson 2/HW_5.py
1,180
4.0625
4
group = input('Введите номер группы:') name = input('Введите имя:') s_name = input('Введите фамилию:') f_name = input('Введите отчество:') t_len = len(name) + len(s_name) + len(f_name) l_name_lw = len('Лабораторная работа № 1') r_group = len('Выполнил(а): ст. гр.') + len(group) if t_len >= l_name_lw >= r_group: pri...
5a8ee7e070043a037c40cdbd1d0bf7cc55316cdf
StanislavVolodarskiy/trie
/trie.py
897
3.609375
4
def make_trie(iterable): root = {} for s in iterable: node = root for c in s: node = node.setdefault(c, {}) node[''] = None return root def contains(text, trie): if '' in trie: return True nodes = [] for c in text: nodes.append(trie) ...
e285b987e5a31f074bd7816d5c07800ab68e9c80
lambertv/Project_Euler
/PE4.py
870
3.9375
4
#PE4.py #Program by Valerie Lambert #reverse function adapted from projecteuler.net """ Project Euler Problem 4- - - - A palindromic number reads the same both ways. The largest plaindrome made from the product of two 2-digit numbers is 9009 = 91 x 99. Find the largest palindrome made from the product of two 3-digit n...
f567776a6d6fb2a5e4b057527400777090268db2
lvfe/lintcode
/LeetcodePy/codes/Leetcode15.py
1,104
3.625
4
def threeSum(nums, target): """ :param nums: :return: """ res = [] nums.sort() for idx in range(len(nums)-1): start,end = idx+1, len(nums)-1 while start<end: if nums[idx]+nums[start]+nums[end]==0: res.append((nums[idx],nums[start],nums[end])) ...
78c62c8944c81c10e80cc64673aab404ff0f4bd5
GeorgeMohammad/Time2ToLoseWeightCalculator
/WeightLossCalculator.py
1,081
4.3125
4
####outputs the amount of time required to lose the inputted amount of weight. #computes and returns the amount of weight you should lose in a week. def WeeklylbLoss(currentWeight): return (currentWeight / 100) #Performs error checking on a float. def NumTypeTest(testFloat): errorFlag = True while(err...
ff05aa7d85f2d7a414accb8daaebe64663c4606a
clementin-bonneau-riera/mathsPythonLycee
/pythagore/pythagoreCheck.py
677
4.15625
4
print("Vérifier la réciproque de Pythagore.") print("Ne marche qu'avec des nombres entiers.") a = input("longueur du côté A: ") b = input("Longueur du côté B: ") hyp = input("Longueur du côté C (hypoténuse): ") a_b_lenght_square = pow(int(a), 2) + pow(int(b), 2) # additionne les carrés des côtés A et B if a_b_lenght...
5df2cfa42ecd09762f2fa56ab4ae28d86bdf0e03
ansari3492/Data-types
/mohammed_burhan_cc4.py
184
3.828125
4
# -*- coding: utf-8 -*- """ Created on Thu May 17 16:11:06 2018 @author: Lenovo """ str3=input("enter string: ").strip() x=str3.find(" ") print (str3[x:].strip(),str3[0:x].strip())
8229e4b76dc7d31e6dca7fa677e89229f47b70dd
JsyPhil/streamlit_demo
/streamlit_demo.py
1,739
3.921875
4
import streamlit as st import numpy as np import pandas as pd import time # Using st.title st.title("My Streamlit App") st.write("Here is my first attempt at using data to creat a table in Streamlit") st.write(pd.DataFrame({ 'first column': [1, 2, 3, 4], 'second column': [10, 20, 30, 40] })) # Using magic ""...
09a6ecb85c30c615b5aada3f20883a86974cc5e1
R-Trubechkov/PythonSample
/Pizza.py
2,442
3.921875
4
menu={'pizza':{'peperony': 13},'drinks':{'pepsi': 2},'adds':{'nuggets': 8}} def exeptions(): print('Fuck off you leatherman!!!') raise ProcessLookupError def isAdmin(login,password): if login and password == 'admin': return True else: return False def writeMenu(): with open("men...
176f3d41f425c78a59ad404933c839bcd869578c
Elitnexu/strunk
/strunk/file_parser/file_parser.py
1,303
3.703125
4
from builtins import object #File Parser handles text file importing. class file_parser(object): def __init__(self, filepath): #Instance variables self.file = None self.filepath = filepath self.SENTENCE_PATH = "temp.strunk" self.ruleset = None self.DELIMITERS = { ...
ed90eb383919253d335d3bf2bea2b4bffd673415
ngtrunghuan/50.021-ArtificialIntelligence
/inclass/grdescent(l04).py
26,396
3.6875
4
import pdb import numpy as np import matplotlib.pyplot as plt import math ###################################################################### # # Learning algorithms and helpers # ###################################################################### # Ordinary least squares regression # X is an n x d matrix # Y i...
24115f34af7e2162c885ffc7f22ec1f76550fc56
Goku0858756/rzzzwilson
/talks/recursion_1/code/fibonacci.py
1,228
4.21875
4
#!/usr/bin/env python """ Recursive solution for the Fibonacci function. With and without memoisation. Usage: fibonacci <integer> """ import time def fibonacci(n): """Return the 'n'th Fibonacci number.""" if n == 0: return 0 if n == 1: return 1 return fibonacci(n-1) + fibonacci(n-...
de97d0426ab25ac5d7ff658ba6903b8770ab4382
Goku0858756/rzzzwilson
/talks/recursion_1/code/hanoi.py
1,132
4.21875
4
#!/usr/bin/env python """ Recursive solution to the "Tower of Hanoi" puzzle. [http://en.wikipedia.org/wiki/Tower_of_Hanoi] Usage: hanoi <number_of_disks> """ def hanoi_original(n, src, dst, tmp): """Move 'n' disks from 'src' to 'dst' using temporary 'tmp'.""" if n == 1: print('move %s to %s' % (src...
ed31d74b3d4f3ace7626b39eec77ebdf282dc0aa
Goku0858756/rzzzwilson
/code_jam/big_city/skyline.py
2,665
3.734375
4
#!/usr/bin/env python """ A program to solve the Google Big City Skyline puzzle. Usage: test.py <datafile> """ def read_width_height(fd): """Read building width&height from a file. Read a character at a time to minimise memory usage. """ def read_int(fd): """Read one integer from file."""...
152b51623e9eb88f243dc4a479e3926d60231f54
asdiuh/AutomateUsingPython
/AutomateUsingPython/Chapter3.py
930
3.9375
4
#a function is like a mini program within a program def hello(): print('howdy') print('Howdy!!!') print('Hello there.') hello() def hello(name): print('Hello {}'.format(name)) hello('Red') #in functions you can return a value if necessary #in pythone None is the same as Null #in a function with no...
442a9109c08a1b083cdd8e65e445940715183e66
24Jay/MachineLearning
/karpathy/Unit.py
637
3.9375
4
class Unit: count = 0 def __init__(self, v, d): self.value = v self.derivative = d Unit.count = Unit.count + 1 self.printll() def printll(self): print("value=", self.value, "derivative=", self.derivative, "count=", Unit.count) class AddUnit(Unit): def __init__...
81677ba881b752800cfcff19977a6cd3f735ddfc
24Jay/MachineLearning
/karpathy/Deriatives.py
909
3.5625
4
def forwardMultiplyGate(a, b): return a * b def forwardAddGate(a, b): return a + b def forwardCircuit(x, y, z): return forwardMultiplyGate(forwardAddGate(x, y), z) if '__main__' == __name__: x, y, z = -2, 5, -4 q = forwardAddGate(x, y) derivative_q_wrt_x = 1 derivative_q_wrt_y = 1 ...
b7df58e4d45c16fc5fe35e2ba028378c9cf227d8
rcreagh/network_software_modelling
/vertex.py
606
4.125
4
#! usr/bin/python """This script creates an object of class vertex.""" class Vertex(object): def __init__(self, name, parent, depth): """Initialize vertex. Args: name: Arbitrary name of the node parent: Parent vertex of the vertex in a tree. depth: Number of edges between the vertex itself ...
f91febfb13a3ec1e627473ec9400a3b168c7f939
SaiChandraCh/IB
/src/week_7/day_29_trees_III/h_w/3_symmetric_binary_tree.py
1,130
3.875
4
class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: # @param A : root node of tree # @return an integer def isSymmetric(self, A): return Solution.isMirror(Solution,A.left,A.right) def isMirror(self, root1, root2): if not root1 and not...
476d2575b98f722a087c9168e06bfc027382af1a
SaiChandraCh/IB
/src/week_7/day_30_BST/h_w/4_root_leaf_Path_Sum.py
1,119
3.6875
4
class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: # @param A : root node of tree # @param B : integer # @return a list of list of integers def pathSum(self, A, B): result = [] Solution.util(self, A, B,[],result) return result ...
faad3d756ad344c4ebc15d30a1d55ca92b531c47
SaiChandraCh/IB
/src/week_7/day_35_tries/assignment/2_maximum_XOR.py
963
3.59375
4
class TrieNode: def __init__(self): self.child = {} self.isTerminal = None class Solution: # @param A : list of integers # @return an integer def __init__(self): Solution.root = TrieNode() Solution.result = 0 Solution.insert_status = 0 def insert(self, binar...
bc231bc7fd0591c07a872cc809e1abdb314cffd1
SaiChandraCh/IB
/src/week_5/day_24_linkedlist/h_w/3_middle_element_linkedlist.py
402
3.5
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: # @param A : head node of linked list # @return an integer def solve(self, A): snail, hare = A, A while hare != None and hare.next != None: ...
41bd1e0e4ab464b96409bbccb206c8d96aa05521
SaiChandraCh/IB
/src/others/path_sum.py
1,804
3.765625
4
class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: found = False def hasPathSum(self, root: TreeNode, sum: int): if root is None: return (sum == 0) else: ans = False # Otherwise...
748ae850fa63d06e63a8931bc568c349d029e92c
SaiChandraCh/IB
/src/week_3/day_14_backtracking/assignment/2_n_quees.py
1,833
3.5625
4
import copy class Solution: # @param A : integer # @return a list of list of strings res = [] def __init__(self): Solution.res = [] def solveNQueens(self, A): board = ["."*A]*A Solution.util(Solution, A, board, 0,0) print(Solution.res) def util(self, A, board, r...
bebddf4a63575f010f67ca926b46f22507f1d4b7
LetoMurakai/fundamentosPython
/aula04.py
527
3.84375
4
# Coleções(Listas) ''' preco_1 = 20 preco_2 = 50 preco_3 = 200 ''' #Listas precos = [20,50,200]#indices [0,1,2,...] print(precos[1])#(precos.index(50)) diversidade = [18,'Leto',True] print(diversidade[0]) print(diversidade[1]) print(diversidade[2]) # Laços em iteráveis for preco in precos: print(preco) # Some os v...
9fcdc2eb6647cbb676774e64e1d6a8c716acbbba
mwsfr/AppMobile_py
/SpaceShip.py
1,010
3.625
4
class SpaceShip: # public ArrayList <Person> crew = new ArrayList<Person>() def __init__(self,name='unknown',fuel=0,hull=0,power=0,robots=0,missiles=0,battleMode=False,enemy=None,room=[],crew=[]): self.name = name self.fuel=fuel self.hull=hull self.power=power self.robots=robots self.missiles=mi...
b722454a775c2345a4ee44f318e38341872cb479
gittangxh/python_learning
/ds_seq.py
330
4.21875
4
shoplist=['apple', 'mango','carrot','banana'] name = 'swaroop' print('item -1 is', shoplist[-1]) print('character 0 is', name[0]) print('item 0 to 2 are:', shoplist[0:2]) print('item 1 to -1 are:', shoplist[1:-1]) print('reverse all items:', shoplist[-1::-1]) print('reverse the string:', name[-1::-1]) print(shopli...
8c2e4e8110aa53f0b5ecffce8b2b80ba2bbeb1aa
gittangxh/python_learning
/io_input.py
364
4.3125
4
def reverse(text): return text[::-1] def is_palindrome(text): newtext='' for ch in text: if ch.isalpha() and ch.isnumeric(): newtext+=ch.lower() return newtext == reverse(newtext) something = input('Enter text:') if is_palindrome(something): print('yes, it is palindrome') el...
032083abede80dbe6bb0ad327dfe57258ab046c1
OfficialPouya/SmartClock
/import json.py
179
3.671875
4
import json # read file with open('city.list.json', 'r') as myfile: data=myfile.read() # parse file obj = json.loads(data) # show values print("Name: " + str(obj['name']))
1b007725c0e1cac2b49b5f0b913ddf5c6a3fe977
Krishntikmani/Deep_Learning_Algo
/Perceptron.py
1,296
3.5
4
import numpy as np import matplotlib.pyplot as plt from sklearn.metrics import accuracy_score class Perceptron: def __init__(self): self.w = None self.b = None def model(self,x): return (np.dot(self.w,x)+self.b>=0) def predict(self,X): Y_pred = [] for x in X: ...
60f48cb49d59bdcf68e697eb364234a0326c4ed8
langsky/mooc_china
/Python语言程序设计/第四周_Python编程之控制结构/quadratic.py
3,925
4.34375
4
# coding=utf-8 # /usr/bin/env python3 import math # 没有决策条件,可能导致抱错 def main1(): print("This program finds the real solutions to the quadratic\n") a, b, c = eval(input("Please enter the coefficients (a, b, c): ")) delta = b * b - 4 * a * c delta = math.sqrt(delta) root1 = (-b + delta) / (2 * a) ...
895fea2cad12d4bc321f186ffc3ee78716088c0b
hyejun18/daily-rosalind
/prepare/template_scripts/bioinformatics-textbook-track/BA3D.py
588
3.640625
4
################################################## # Construct the De Bruijn Graph of a String # # http://rosalind.info/problems/BA3D/ # # Given: An integer k and a string Text. # # Return:DeBruijnk(Text), in the form of an adjacency # list. # # AUTHOR : dohlee ################################################## # Y...
d1fc10eafc50fc19e2eca6243557c5b455e8841c
hyejun18/daily-rosalind
/prepare/template_scripts/bioinformatics-stronghold/OAP.py
917
3.515625
4
################################################## # Overlap Alignment # # http://rosalind.info/problems/OAP/ # # Given: Two DNA strings s and t in FASTA format, # each having length at most 10 kbp. # # Return: The score of an optimal overlap alignment # of s and t, followed by an alignment of a suffix # s' of s a...
1e0c4bbb46333effecfc61c0b2e09bea3a584251
hyejun18/daily-rosalind
/prepare/template_scripts/bioinformatics-textbook-track/BA9Q.py
687
3.71875
4
################################################## # Construct the Partial Suffix Array of a String # # http://rosalind.info/problems/BA9Q/ # # Given: A string Text and a positive integer K. # # Return: SuffixArrayK(Text), in the form of a list # of ordered pairs (i, SuffixArray(i)) for all # nonempty entries in th...
08a0e523524ea7de0506e4f70e8ebc77715aa38d
hyejun18/daily-rosalind
/scripts/bioinformatics-stronghold/OSYM.py
830
3.515625
4
################################################## # Isolating Symbols in Alignments # # http://rosalind.info/problems/OSYM/ # # Given: Two DNA strings s and t in FASTA format, # each having length at most 1000 bp. # # Return: The maximum alignment score of a global # alignment of s and t, followed by the sum of # ...
24e6fb5a2b0a9dadeb6d85f9486e5d34dc84bf5e
hyejun18/daily-rosalind
/prepare/template_scripts/bioinformatics-textbook-track/BA9D.py
653
3.65625
4
################################################## # Find the Longest Repeat in a String # # http://rosalind.info/problems/BA9D/ # # Given: A string Text. # # Return: A longest substring of Text that appears # in Text more than once. (Multiple solutions may # exist, in which case you may return any one.) # # AUTHOR...