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
de8fe1ad386f946fe1fec6f73160d14ee5d09018
dieduk89/project_euler
/python/exercise 15/code1.py
145
3.671875
4
print "\nCALCULUS\n" def factorial(n): if n<2: return 1 else: return n*factorial(n-1) print factorial(40)/factorial(20)**2 print "\n"
f4f3d75990936230434cb06a2f1cccb9541c064a
dieduk89/project_euler
/python/exercise 7/code1.py
429
3.859375
4
print "\nSECUENCIAL SEARCH\n" def is_prime(primes,n): index = 2 result = True while primes[index]<= int(n**0.5) and result: result = n%primes[index] != 0 index = index+1 return result primes = [2,3,5,7] index = 2 num = 6*index-1 while len(primes)<10001: if is_prime(primes,num): primes.append(num) if is_p...
73a995f700310633a78b2a2244f46e15d1504ee5
MGijon/Learning-Python
/Graphics/Pyplot/ScatterPlot3D.py
763
3.625
4
from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt import numpy as np def randrange(n, vmin, vmax): '''just generate the random numbers in an appropiate way''' return(vmax-vmin) * np.random.rand(n) + vmin fig = plt.figure() ax = fig.add_subplot(111, projection = '3d') n = 100 for c, m, ...
e2c3f931eeb53079296a907480d4239e7bee5fb2
MGijon/Learning-Python
/Clases en Python/namedtuple_rename.py
577
4.09375
4
''' Usaremos RENAME = TRUE para que los identificadores vñalidos se renombres automáticamente (también eliminará los repetidos), sustituyéndolos por identificadores posicionales. Muy útil para generar namedtuple's a partir de BASES DE DATOS -> MACHINE LEARNING for instance. ''' from collections import namedtuple ...
0b8b5dde9938c9547df86946fa1159df37d816e9
MGijon/Learning-Python
/PyGame/SpaceInvaders.py
1,476
3.734375
4
import pygame from Ship import Ship from Enemy import Enemy pygame.init() BLACK = ( 0, 0, 0) WHITE = ( 255, 255, 255) GREEN = ( 0, 255, 0) RED = ( 255, 0, 0) SCREENWIDTH=400 SCREENHEIGHT=500 size = (SCREENWIDTH, SCREENHEIGHT) screen = pygame.display.set_mode(size) pygame.display.set_caption("Spaca Invaders") carry...
9c4e4dc4cd7e4b1b64653cbaa10d51d2ffc1138c
MGijon/Learning-Python
/SciPy/Distances.py
572
3.734375
4
import numpy as np import scipy # ahora jugaremos con algunas de las distancias, primero construiremos dos vectores X = np.array([x for x in range(0, 11)], dtype = float) Y = np.array([x for x in range(10, 21)], dtype = float) #print(X) #print(Y) #print(X*Y) # observemos como detalle (no es el objeto de esto) que mul...
48672d94d19b9f833a11f38045c864699caa3e7a
hoinv10/SocketPython
/LearningPython/Class1.py
618
3.640625
4
class hcn: dai = 0; rong = 0; # constructor def __init__(self, dai =0 , rong= 0): self.dai = dai self.rong = rong def dientich(self): return self.dai*self.rong def chuvi(self): return (self.dai + self.rong)*2 #ke thua class hinhhop(hcn): cao = 0; # chồng...
392f00d069b009ef00bc8a230279ad0edc1be834
veyron-davids/Myshop
/test.py
222
3.671875
4
def duplicate_encode(word): new = word for wd in word: for nw in new: if wd == nw: return print(")") else: return print("(") duplicate_encode("bun")
af6b9e72ba37710ded9b826c5a4101e4baa5027f
YukiT1990/Greedy-Algorithms
/TaskScheduler.py
1,108
3.640625
4
class Solution: def leastInterval(self, tasks: List[str], n: int) -> int: taskLength = len(tasks) if n == 0: return taskLength # create dictionary which key is the kind of task, the value is number of the tasks taskCounts = defaultdict(int) for task in tasks: ...
64b90615aa4a991fbe66e9ece61a1d4b01db930b
WalterSimoncini/GeneticWordGenerator
/word_generator.py
3,067
3.984375
4
import sys import time import random from population import * from fitness import compute_population_fitness # Utility function that checks if an individual matches the chosen word # If that happens the index of the individual is returned, if not -1 is # returned def check_for_matching_word(population, word_to_match)...
8e1361cc6d13f0e4b44a7737f00dc0303689f326
michalbal/Cluedo-solver-using-Planning-and-Bayesian-Networks
/board.py
2,305
3.765625
4
import numpy as np from util import * class Board: """ A simplified board for Clue game """ def __init__(self, players): self._locations = {player: OPEN_LOC[player.get_character()] for player in players} self._players = players def print_board(self): """ ...
9a660f9ca9da3ccd6c4622dc54ef1905a4dd483b
aishwaryagm1999/Basic-Python-Programming
/Strings - Palindrome.py
471
4.09375
4
#!/usr/bin/env python # coding: utf-8 # In[ ]: def palin(str1): #method 1 str2 = str1[::-1] if str2 == str1: return "palindrome" else: return "not palindrome" def palin2(str1): #method 2 str2 = "" for i in range(len(str1)-1,-1,-1): str2=str2+str1[i] if str2 ...
ec74319cbc0c872b1bdda76070ee73c94d270eb3
aishwaryagm1999/Basic-Python-Programming
/Strings - Subsequence or not (Given two strings S1 and S2, find if S1 is a subsequence of S2).py
262
3.84375
4
#!/usr/bin/env python # coding: utf-8 # In[ ]: str1 = "bxc" str2 = "bdbpycx" str3 = "" for i in range(len(str2)): if str2[i] in str1: if str2[i] not in str3: str3 = str3+str2[i] if str1 == str3: print("yes") else: print("no")
80534cc1df949c80c6083934783f6e55c9c045fd
aishwaryagm1999/Basic-Python-Programming
/Arrays - Count of numbers which divide all numbers in the given range L-R. (Given N numbers and Q queries, each query consists of L and R).py
2,065
3.734375
4
#!/usr/bin/env python # coding: utf-8 # In[ ]: print("Enter array elements: ") a = list(map(int,input().split(' '))) #reading input as list of integers using map n = len(a) #length of input list q = int(input("Enter number of queries: ")) #number o...
251a77b3255ec0e7e01978ef27020c92a0c0e191
nckathleen/approximate-square-root
/square_root.py
560
4
4
user_inpt = input("Enter a positive number: ") b = int(user_inpt) def validate_input(): if b <= 0: print("This is not a positive number") else: fun_with_newton() def fun_with_newton(): epsilon = 1 x = b / 2 new_x = 0 count = 1 while epsilon >= float(0.01): new_x =...
c4de61f23f52db03a3eec395cbe1f8fabe871208
hamzazaman/cs170proj
/maker.py
7,335
3.59375
4
def generate_output_lsts(bus_num, cap): """ inputs: bus_num: integer number of buses cap: inclusive integer capactiy of bus return: names inside buses """ max_possible = bus_num * cap num_letters = math.ceil(math.log(max_possible, 26)) + 2 return [[string_maker(num_...
2384c7c82af5eccdb070c7522a11895f2c3f4aa6
ldocao/utelly-s2ds15
/clustering/utils.py
674
4.25
4
###PURPOSE : some general purposes function import pdb def becomes_list(a): """Return the input as a list if it is not yet""" if isinstance(a,list): return a else: return [a] def add_to_list(list1, new_element): """Concatenate new_element to a list Parameters: ---------- ...
9135d41ce68357c0c3cf5d4eaf14dde16340b8c1
NatalieCoding/Learning-Basics
/simple_function.py
72
3.53125
4
def addtwo(a,b): added=a+b return added x=addtwo(3,5) print(x)
867f3816a1a681dab6edc672b7bb7b87c28abba2
DreGorski2/udacity-data-structures-project-2
/problem 6/union_and_intersection_linked_lists.py
3,342
3.859375
4
class Node: def __init__(self, value): self.value = value self.next = None def __repr__(self): return str(self.value) class LinkedList: def __init__(self): self.head = None def __str__(self): cur_head = self.head out_string = "" while cur_head:...
54017ea671a4d3358a64a3d3d20ba2d65a846c50
RickYuankangShong-Quantitative-Finance/Quant-python
/faco.py
195
3.765625
4
def factorial(n): result=1 while n>1: result *=n n-=1 return result print(factorial(100)) s=str(factorial(100)) sum=0 for c in s: sum+=int(c) print(sum)
d9a115166af284f7698189ed597d746c90643267
AlexanderMoore2409/1310Codesumu
/Programas Python/fibonacci con recursividad.py
447
3.921875
4
#------------------------------------------------------------------------------- # Name: module2 # Purpose: # # Author: Usuario # # Created: 08/09/2021 # Copyright: (c) Usuario 2021 # Licence: <your licence> #------------------------------------------------------------------------------- ...
929aed42b9deb2eb1f865a8427b465846a0e8356
IanAtkin/python
/tests/target2.py
2,099
4.03125
4
# write a function with the following input: an array of integers and a number 'target' # find all the pairs that sum equals to the input number 'target' # output is a list of pairs (number_a, number_b) # e.g input: [1,3,9,-5,-2,0,100,-25], -2 # e.g output [(3,-5), (-2,0)] # assume the input array has no duplicates #...
21a6bb48340cd5e64ecc70a474e79eedbfdce1c2
wuping5719/PythonTest
/src/test/test18.py
563
3.609375
4
# -*- coding: utf-8 -*- ''' Created on 2017 年 9 月 12 日 @author: Nick ''' ''' 题目:有一分数序列:2/1,3/2,5/3,8/5,13/8,21/13...求出这个数列的前20项之和。 程序分析:请抓住分子与分母的变化规律。 ''' # 方法一 a = 2 b = 1 lst = [] for i in range(20): lst.append(str(a) + '/' + str(b)) a,b = a+b, a print('{0} = {1}'.format(eval('+'.join(...
1437470727f850a0e25a140e9e25587a15e45866
wuping5719/PythonTest
/src/test/test17.py
630
3.765625
4
# -*- coding: utf-8 -*- ''' Created on 2017 年 9 月 11 日 @author: Nick ''' ''' 打印出如下图案(菱形): * *** ***** ******* ***** *** * 程序分析:先把图形分成两部分来看待,前四行一个规律,后三行一个规律, 利用双重for循环,第一层控制行,第二层控制列。 ''' def pic(lines): middle, lines = int(lines / 2), int(lines / 2) * 2 + 1 for i in...
ec18defec6010dd268a51d7d43c3e7216bbd4b31
wuping5719/PythonTest
/src/test/test31.py
393
3.9375
4
# -*- coding: utf-8 -*- ''' Created on 2017 年 9 月 15 日 @author: Nick ''' ''' 题目:求一个3*3矩阵对角线元素之和。 程序分析:利用双重for循环控制输入二维数组,再将a[i][i]累加后输出。 ''' """ 1 2 3 4 5 6 7 8 9 """ matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] sum_ = 0 for i in range(0, 3): sum_ += matrix[i][i] print (sum_)
2f3763046105d528b0c63daca593c8a71b51f521
wuping5719/PythonTest
/src/test/test57.py
327
3.84375
4
# -*- coding: utf-8 -*- ''' Created on 2017 年 10 月 9 日 @author: Nick ''' ''' 题目:写一个函数,求一个字符串的长度,在main函数中输入字符串,并输出其长度。 ''' if __name__ == '__main__': s = input('please input a string:\n') print ('the string has %d characters.' % len(s))
53c493542b4ef798828d8eced747d0c56dfb9958
wuping5719/PythonTest
/src/test/test9.py
978
3.859375
4
# -*- coding: utf-8 -*- ''' Created on 2017 年 9 月 9 日 @author: Nick ''' ''' 题目:将一个正整数分解质因数。例如:输入90,打印出90=2*3*3*5。 程序分析:对n进行分解质因数,应先找到一个最小的质数k,然后按下述步骤完成: (1)如果这个质数恰等于n,则说明分解质因数的过程已经结束,打印出即可。 (2)如果n<>k,但n能被k整除,则应打印出k的值,并用n除以k的商,作为新的正整数你n,重复执行第一步。 (3)如果n不能被k整除,则用k+1作为k的值,重复执行第一步。 ''' def prime(n): l = [] whil...
46db4fa4fc2dc3072ff78767fea443d21c0311e1
wuping5719/PythonTest
/src/test/test3.py
350
3.5625
4
# -*- coding: utf-8 -*- ''' Created on 2017 年 9 月 4 日 @author: Nick ''' ''' 题目:有一分数序列:2/1,3/2,5/3,8/5,13/8,21/13...求出这个数列的前20项之和。 程序分析:请抓住分子与分母的变化规律。 ''' sum1 = 0 a, b = 1, 2 for i in range(1, 21): sum1 += b / a a, b = b, a + b print(sum1)
2392b697889511a3efbb1242df2aa0d76f9f17c4
wuping5719/PythonTest
/src/test/test16.py
592
3.5625
4
# -*- coding: utf-8 -*- ''' Created on 2017 年 9 月 11 日 @author: Nick ''' ''' 题目:两个乒乓球队进行比赛,各出三人。甲队为a,b,c三人,乙队为x,y,z三人。已抽签决定比赛名单。 有人向队员打听比赛的名单。a说他不和x比,c说他不和x,z比,请编程序找出三队赛手的名单。 ''' n=['a','b','c'] m=['x','y','z'] L=[] for i in range(0,3): for j in range(0,3): L.append(n[i]+'-'+m[j])...
423e1b7c6a92f463ab132d5c19bccf2e1932f8aa
tyrelhooker/learningPython
/part2_exercises/indexingAndSlicing.py
498
3.953125
4
""" Define a list named L that contains 4 strings or numbers. Then experiment with the boundary cases. a. What happens when you try to index out of bounds, L[4]? - receive an error b. what about slicing out of bounds? - The slice will capture the whole list items. c. How does Py handle it if you try to extract a sequen...
4624191fdd1a722c20dde6761c1854dfb4cb684c
littlehippo147/Advanced-Statistical-Programming
/HW/과제8.py
3,085
3.984375
4
# inside class Point : class Point(object): def __str__(self): return '(%g, %g)' % (self.x, self.y) def __add__(self, other): add = Point() if type(other) == tuple: add.x = self.x + other[0] add.y = self.y + other[1] return add el...
20590597f207137c780609993a35ec0e52b8c9db
littlehippo147/Advanced-Statistical-Programming
/Code/15장 클래스와 객체.py
1,552
4.03125
4
## user-defined types class Point(object): """Represents a point in 2-D space.""" print(Point) blank = Point() print(blank) ## attributes blank.x = 3.0 blank.y = 4.0 print(blank.x) print(blank.y) print('(%g, %g)' % (blank.x, blank.y)) distance = math.sqrt(blank.x**2 + blank.y**2) print(distance...
e484388cc92e1042dfb4d8271e5535b991e4245b
dikshakewat3776/Data-Structures-Python
/1_Recursion/4_SumOfDigits.py
234
3.59375
4
def SumOfDigits(n): assert n >= 0, "Number 'n' should be positive." if n == 0: return 0 else: return int(n % 10) + SumOfDigits(n / 10) if __name__ == "__main__": res = SumOfDigits(54) print(res)
a04d6b37acbff24dd3a265ac6a453358056886e7
dikshakewat3776/Data-Structures-Python
/1_Recursion/1_PowerOfTwo.py
185
3.5625
4
def PowerOfTwo(n): if n == 0: return 1 else: power = PowerOfTwo(n-1) return power*2 if __name__ == "__main__": res = PowerOfTwo(4) print(res)
ef5de42d1c34be441c9b7aa0ab339ffc5631d873
dikshakewat3776/Data-Structures-Python
/3_SinglyLinkedLists/5_SLLDeletion.py
5,137
3.890625
4
""" ALGORITHM: DELETION IN SINGLY LINKED LIST 1. Get node location. 2. Check if head is none, terminate else check first location. (no nodes case) 3. If location is first, (if only one node) HEAD = NULL , TAIL = NULL, (if many nodes) HEAD = FIRST.NEXT and terminate ...
a3d90fc11ec40efd2f075b1f5e1ee1f03f66d465
qiao-zhi/pythonCraw
/HelloPython/function1.py
1,638
4.25
4
# python函数练习 # 1.python自带的一些常见函数的练习 print(abs(-95)) print(hash(-95)) print("sssssssssssssssss"+str(95)) # 2.自定义函数 def my_abs(a): if a >= 0: return a else: return -a # 3.定义不带参数与返回值的函数(无返回值的函数类似于return None,可以简写为return) def print_star(): print("***********") print_star() x=print_star() #...
73e6f5603007f690859b8859a3ef129f95bc5d55
qiao-zhi/pythonCraw
/HelloPython/list.py
857
4
4
import sys list1 = ['zhangsan', 'lisi', 'wangyu'] # 直接打印集合 print(list1) # c从0开始,类似于java print(list1[1]) # 负号代表倒着数 print(list1[-1]) # 打印集合长度 print(len(list1)) # 追加元素 list1.append("john") print(list1) print(list1[-1]) # 插入到指定位置 list1.insert(1, 'john1') print(list1) # 删除元素 # 删除最后一个元素 list1.pop() print(list1) ...
e6217fa5b4b1625d14e353ff47d4bf1b75d38ee9
qiao-zhi/pythonCraw
/HelloPython/if.py
338
3.875
4
# if语句用法(缩进相同的成为一个代码块) score=90 if score>=60: print("合格") print("OK") print("END") # if-else用法 if score>=60: print("合格") else: print("不合格") # if-else if -else....语句 if score>=90: print("优秀") elif score>=60: print("合格") else: print("不及格")
8fc6d4ce95f4d2b2191e54a3acdee763e15c171e
VitaliiFesh/QApython
/hw_3/hw_3_task_4_1and2.py
950
3.640625
4
# QApython Vitalii Feshchenko # Homework #3 Task 4_1 and 4_2 # У вас есть список чисел. print('First task:', end='\n\n') ls = [i for i in range(10)] print(f'Original list: {ls}') # 1. Напишите цикл, который выводит на экран и удаляет с начала элементы списка, пока он не # останется пустым count = 0 while len(ls) > ...
81719e8bc0000baed9aefec649c7d401c67dbde6
VitaliiFesh/QApython
/hw_2/homework2_task3.py
871
3.890625
4
# QApython Vitalii Feshchenko # Homework #2 Task 3 ls = ['The', 'world', 'is', 'clothing', 'in'] # Выведите 3-е с конца слово из списка print(ls[-3]) # Выведите 1-ю букву второго слова из списка print(ls[1][0]) # Выведите последнюю букву последнего слова из списка print(ls[-1][-1]) # Добавьте в конец списка еще од...
d7884ac62fdd0c5aa7c3ce0ce33822856e37bd9e
mecomontes/Python
/Bases de Datos/SQlite2.py
2,531
3.890625
4
""" Inserción dinámica en una base de datos con SQLite Implementar dichos métodos en un programa En este tutorial, vamos a ir cubriendo cómo insertar dinámicamente en la tabla de una base de datos, usando variables. 1º Vamos a importar algunas nuevo módulos: import time i...
aa6e218cb40d24dab91624067a024c2f90e1f543
mecomontes/Python
/Fundamentos Python/ecuacion_gauss_4.py
422
3.96875
4
# !/usr/bin/env python # -*- coding: utf-8 -*- # Sumatoria de los n primeros números # Ciclo repetitivo: for Numero = int(input("Ingrese el último Número a incluir en la sumatoria: ")) Sumatoria = 0 for Contador in range(1, (Numero+1)): Sumatoria += Contador # Es equivalente a decir: Sumatoria = Suma...
851e06d13fdf2c81f56368bc4bc869035c3c1334
mecomontes/Python
/Conversión tasa/Amortizacion.py
6,299
3.609375
4
import xlsxwriter """from datetime import date from datetime import datetime from datetime import time Today=date.today() Date = str(Today.day) + '/' + str(Today.month) + '/' + str(Today.year) print(Date)""" def CambioTasa(nomi,peri,VoAi,tasa,nomf,perf,VoAf): D={"A":12,"S":6,"T":3,"B":2,"M":1,"Q":1/2,"D":1/30...
878466e6aa53b3737b48673c0a295bc2430725e9
mecomontes/Python
/Fundamentos Python/recta.py
228
3.84375
4
def punto_recta(x,y,recta): if y==recta[0]*x+recta[1]: print('el punto está en la recta') else: print('el punto no está en la recta') recta=(3,4) x,y=(2,10) punto_recta(x,y,recta)
fa9d26f16e326f88614ec786aca1db240c7efdc2
mecomontes/Python
/Analisis de Datos/Accidentes en UK/pandas_accidents.py
15,240
3.75
4
import pandas as pd # Read the file data = pd.read_csv("Accidents7904.csv", low_memory=False) # Output the number of rows print("Total rows: {0}".format(len(data))) # See which headers are available print(list(data)) # Accidents which happened on a Sunday accidents_sunday = data[data.Day_of_Week == 1] print("Accident...
bba08a00b748e448207912c5ba6438fd702acfc8
mecomontes/Python
/Desde0/Random.py
4,239
4.21875
4
#funcionamiento de este módulo al generar 10 números escogidos aleatoriamente entre el 0 y el 100. import random for x in range(10): print (random.randint(1,101)) #Funciones aleatorias y Ejemplos de números aleatorio en Python #El módulo Random contiene algunas funciones que resultan ser muy útiles: # Ran...
d03fadbed828fec3b51e1c482cf29db5993a654e
mecomontes/Python
/Analisis de Datos/Manejo Basico de archivos/Archivos_Datos_W4.py
533
3.765625
4
# Archivo de datos # Escribir datos al final de un archivo existente: el modo 'a' (append) # Manejar la Excepcion: NO ES NECESARIA # En este caso, modo: a append; como en el caso del modo: w (write), el manejo de la excepcion no es valido por: # Si el archivo no existe, lo crea # Si el archivo existe, adicio...
03be2c4df4c404636dd5599ca939e5692cba538d
mecomontes/Python
/Desde0/listConprehension.py
2,545
4.40625
4
"""Qué son las list comprehensions Básicamente son una forma de crear listas de una manera elegante simplificando el código al máximo. Como lo oyes, Python define una estructura que permite crear listas de un modo un tanto especial. Te lo mostraré con un ejemplo:""" numeros = [1, 2, 34, 86, 4, 5, 99, 890, 45] pare...
74a7c442c3e12a0304a6e6f055941c04e6b3d89d
mecomontes/Python
/Vision Artificial/CirculosHough.py
1,549
3.984375
4
""" La transformada de círculo de Hough Objetivo del 28º tutorial de Curso de Procesamiento de Imágenes y Visión Artificial Aprender a usar Transformada de Hough para encontrar círculos en una imagen. Entender la función cv2.HoughCircles() Teoría Un círculo...
5b1d73fe53c06e6973112db0962a48fa454a40a1
mecomontes/Python
/Fundamentos Python/Fun_Seleccion1.py
1,638
4.21875
4
#!/usr/bin/env python #-*- coding: utf-8 -*- def Fun_Crea_Lista(): import random # Crea una lista a partir de numeros aleatorios # Generar un numero aleatorio(7-10) # Generar una lista de números aleatorios de acuerdo al número generado en el punto anterior # Mostrar: # El nume...
bcc9c451220a71b4b3c9121c025bb0ce442c4449
mecomontes/Python
/Fundamentos Python/bisiesto.py
377
3.78125
4
def comprobar(año): if año%400==0: print('el año ', año, ' es bisiesto') mes=400 elif año%4==0 and año%100!=0: print(f'el año {año} es bisiesto') mes=4 else: print(f'el año {año} NO es bisiesto') mes=0 return año, mes x=int(i...
6293c5200d2c5d6792c357d758e7f2a46171683a
mecomontes/Python
/Redes Neuronales/Primera.py
2,052
3.578125
4
import numpy as np def nonlin(x,deriv=False):### """función de perdida como una derivación de la función Sigmoide""" if deriv==True: return x*(1-x) return 1/(1+np.exp(-x)) X=np.array([[0,0,1],[0,1,1],[1,0,1],[1,1,1]]) ## """Dataset para entrenar la red""" Y=np.array([[0],[1],[1],[0]]) np.random.seed(...
4b2dbef27d25141172dbfcb91038c17c4b182f87
mecomontes/Python
/Desde0/Variables.py
4,157
3.984375
4
### DATOS CADENA cadena1 = ('comillas simples') print (cadena1) cadena2 = ("comillas dobles") print (cadena2) n = "Aprender" a = "Python" n_a = n + " " + a print (n_a) ### DATOS BOOLEANOS: Este es el tipo de variable que solo puede tener Verdadero o Falso. #Son valores muy usados en condiciones y bucles. Ejemplo de ...
399bb9e4963cc5ad148d52261fcc6c04b3727d57
AP-MI-2021/lab-1-catarotaru231
/main.py
2,539
4.03125
4
''' Returneaza true daca n este prim si false daca nu. ''' def is_prime(n): if (n > 1): for i in range(2, int(n / 2) + 1): if (n % i == 0): print("Numarul", n, "nu este prim") break else: print("Numarul", n, "este prim") else: print("Numarul", n, "nu este prim") ...
696f1528cdafc145a9ad041af3eb3a6155a2ac21
aanastasiou/pyjunix
/pyjunix/pyjuniq.py
4,321
3.8125
4
""" PyJUniq returns unique items from a list of items. :authors: Athanasios Anastasiou :date: November 2019 """ import sys import json from .core import BasePyJUnixFunction, PyJUnixException, PyJCommandLineArgumentParser import deepdiff import collections import pdb class PyJUniq(BasePyJUnixFunction): """ ...
d7016a1d176a65d07c72817bd86eca6d3c1fc0ad
sofiazenzola/Python-INFO1-CE9990
/forloop.py
630
4
4
""" forloop.py Input a string and will output how many spaces, vowels, consonants, and other characters there are in the string. Ys are not counted as a vowel """ string=input("type in your sentence: ") spacecount=0 vowelcount=0 consonantscount=0 othercount=0 for x in string: if x.lower() == " ": spaceco...
b4a9bc20bf2db2d016583b257a707dd9f49d7ede
sofiazenzola/Python-INFO1-CE9990
/graphpaper.py
1,301
4.09375
4
""" graphpaper.py Let the user input four numbers to design a sheet of graph paper. Output the graph paper """ import sys rows= input("How many rows of boxes?") try: rows=int(rows) except ValueError: print("That is not a valid input.It must be a whole number. Default is 3") rows = 3 columns= in...
55905e7492d2307eae9f8932eaf5bd0f396ee949
anatolytsi/db-pyqt-gb
/lesson1/task_3.py
1,545
3.90625
4
""" Написать функцию host_range_ping_tab(), возможности которой основаны на функции из примера 2. Но в данном случае результат должен быть итоговым по всем ip-адресам, представленным в табличном формате (использовать модуль tabulate). Таблица должна состоять из двух колонок """ from tabulate import tabulate from lesso...
e6c996b6c6ee9948280981b7d622426d798a884c
Lavekernis/Symulacja
/symulacja.py
6,051
3.640625
4
# -*- coding: utf-8 -*- """Program do symulacji rozprzestrzeniania choroby w populacji Kod do wykorzystania na zajęciach 01.04.2020 """ import math import random def d(p1,p2): return math.sqrt((p1.x - p2.x)**2 + (p1.y - p2.y)**2) def dv_rand(v_max): dvx = random.uniform(-v_max, v_max) dvy_max = ma...
5a710f498946ff72afff52add5d17e3b20a2d434
dlicari/replit-test
/1.4. Input/print_ Previous and next/submissions/DDD LLL/main.py
189
3.921875
4
# Read an integer: a = int(input()) # Print a value: print("The next number for the number %s is %s" % (a, int(a)+2) ) print("The previous number for the number %s is %s" % (a, int(a)-1) )
02cfe4a936477537807301af43ad17e63ea34797
grant0417/project_euler_solutions
/p009.py
342
3.734375
4
import math def find_triplet(n): for a in range(500): for b in range(500): if math.sqrt(a * a + b * b).is_integer(): if a + b + math.sqrt(a * a + b * b) == 1000: return a, b, math.sqrt(a * a + b * b) triplet = find_triplet(1000) print(int(triplet[0] * trip...
17313e8a68b1f71f00be35be9afb4b4ca20f66b5
Crescent617/code-practice
/py/misc/sudoku.py
838
3.625
4
class Sudoku: def is_valid_digit(self, d, i, j): g = self.grid bi, bj = i // 3, j // 3 return not (d in g[i] or d in {g[r][j] for r in range(9)} or d in {g[bi*3+k][3*bj+n] for k in range(3) for n in range(3)}) def _so...
8cb5ce1c79632343a5e09e5c0e3ca73a46163b24
Crescent617/code-practice
/py/my_collections/stack.py
1,103
3.828125
4
class StackNode: def __init__(self, value, nxt): self.value = value self.next = nxt def __repr__(self): nval = self.next and self.next.value or None return f'[{self.value}:{repr(nval)}]' class Stack: def __init__(self): self.top = None def push(self, ...
2cbe368100af5aabeb7db5dd1e6ef1f6b4cf5fa1
nmendozavd/math_dojo
/mathdojo.py
1,341
3.890625
4
""" class MathDojo(object): def __init__(self): self.result = 0 def add(self, *args): for i in args: if type(i) == list or type(i) == tuple: for k in i: self.result += k else: self.result += i return self """ #P...
138d601c02f64bd4509a907bac0f49308c71a0da
AnishSherchan/Binary-addition
/BinaryAddition/binConvo.py
647
3.671875
4
def binConvo(Deci): #Function for changing Decimal to binary DuplicateBin=[] ActualBin=[] flag = True while flag == True: #While loop for chaing Decimal to Binary for i in range(0,8): Remi = Deci % 2 DuplicateBin.append(Remi) Ques = Deci // 2 ...
c5a62e7f4c042bc7e109c8f4a222ca9f6b5a18b3
mukherjee96/coding-challenges
/rangoli.py
956
3.65625
4
import string def print_rangoli(size): width = 4*size - 3 counter = int(0) letters = list(reversed(string.ascii_lowercase[:size])) pattern = [] for i in range(1, (2*size)): if(int(i) <= size): counter = counter + 1 pattern = list("".join(letter + '-' for ...
f5e43e782e31f8a7b452e07a191eb439dc664e1e
CelsoUliana/Introduction-to-Algorithms
/4/4.2/4.2-2.py
3,947
3.515625
4
# Celso Uliana -- Feb (yay) 2021 # Strassen algorithm square matrix multiplication with size n power of 2 # Should result in [[4, 4], [10, 8]] #A = [[1, 2], [3, 4]] #B = [[2, 0], [1, 2]] # Should result in [[2, 4], [7, 10]] #A = [[2, 0], [1, 2]] #B = [[1, 2], [3, 4]] # Should result in [[96, 68, 69, 69], # ...
063aa034eab01119d65578dcf1d284aad1163466
CelsoUliana/Introduction-to-Algorithms
/4/4.2/squareMatrixMultiply.py
1,301
3.609375
4
# Celso Uliana -- Feb (yay) 2021 # Naive square matrix multiply O(n³) # Should result in [[4, 4], [10, 8]] #A = [[1, 2], [3, 4]] #B = [[2, 0], [1, 2]] # Should result in [[2, 4], [7, 10]] #A = [[2, 0], [1, 2]] #B = [[1, 2], [3, 4]] # Should result in [[96, 68, 69, 69], # [24, 56, 18, 52], # ...
1f4bcc946417c66df872652f56d0eff4bade247d
dhhruv/BrainyBeam-Summer-Internship-Tasks
/Task-4/task4b.py
87
3.6875
4
import numpy as np a = np.array([[1, 2, 3], [4, 5, 6]]) a = a.reshape(-1, 1) print(a)
0788fde47e1c8be6a257c9d0bf9835609cadc096
nurxx/npuzzle
/npuzzle.py
4,541
4.03125
4
from math import sqrt global N class Node: ''' Class Node holding the state of the puzzle, possible movement/direction, parent node, g(n) - the depth and f(n) the total estimated cost of the state ''' def __init__(self, state, direction, parent, g_n, f_n): self.state = state self.direction = direction sel...
ca7f65e50aa637dd87b450dd52fe323b5d7e38fb
calfdog/Robs_automation_tools
/misc_utils/covert_string_to_dict.py
777
3.96875
4
""" Developed by: Rob Marchetti July 2021 Lazy man's script that lets you take a string that you want as a dict and converts it to a dictionary Example: INPUT: s = "Lang1 Python Lang2 Ruby Lang3 Java Lang4 Perl" OUTPUT: {'Lang1': 'Python', 'Lang2': 'Ruby', 'Lang3': 'Java', 'Lang4': 'Perl'} ...
edf676b2dcc73b51d0ddd716f7e472f49fe9f401
Medmly20208/guessNumber
/guessNumberProject/geussnumber.py
5,369
3.96875
4
import random con = True while con: x = random.randint(0,1000) print(x) print("guess number") print("you have 3 tries .") n = int(input('>')) tries = 3 if x==n: print("good job you guessed the number ") ch = input("do you wanna continue playing ? type Y...
d3e0b773920477b663223d169228c86511c86b43
alects/Diablos-Cold-Call-System
/src/Flash.py
4,929
3.828125
4
from tkinter import * import sqlite3 import os import random class Flash(Frame): """ This window will be used to quiz the instructor on students names via their photos. """ def __init__(self, name=None, master=None): ''' Constructor ''' Frame.__init__(self, master) self.name = name self.master = m...
f3bfa33eb7735c01cf830f07a81a65a597e069b5
Melania227/University-SemesterVI-WordProcessor
/procesador.py
3,166
3.703125
4
from collections import Counter import re import unicodedata #Funcion que abre y lee y retorna el texto de un archivo def readFile(path): try: with open(path, encoding='utf-8') as file: content=file.read() file.close() except: with open(path,"r") as file: ...
8a1e63fc959a79e138bba3f566f513f60faa148d
shail8989/pythontest
/buyLotsOfFruit.py
275
3.84375
4
def buyLotsOfFruit(orderList): """ orderList: List of (fruit, numPounds) tuples Returns cost of order """ totalCost = 0.0 for f, q in orderList: totalCost += fruitPrices[f] * q "* YOUR CODE HERE *" return totalCost
e88deed3ed0b301760156936d009f511f89f6c8d
sunnyyants/crackingPython
/Linked_List/P2_1.py
847
3.90625
4
__author__ = 'SunnyYan' # Write code to remove duplicates from an unsorted linked list # Follow up # How would you solve this problem if a temporary buffer is not allowed from Linked_List.SingleLinkedList import SLinkedList def findDuplicates(List): currentNode = List.head while(currentNode != None): ...
e68f7daf7a588470c36b131e13606b458298906d
sunnyyants/crackingPython
/Recursion_and_DP/P9_5.py
1,169
4.21875
4
__author__ = 'SunnyYan' # Write a method to compute all the permutation of a string def permutation(string): if string == None: return None permutations = [] if(len(string) == 0): permutations.append("") return permutations firstcharacter = string[0] remainder = string[1:...
70269b4f1997e6509e7323da0d8a7592355e0ef5
sunnyyants/crackingPython
/Trees_and_Graph/P4_4.py
850
4.1875
4
__author__ = 'SunnyYan' # Given a binary tree, design an algorithm which creates a linked list # of all the nodes at each depth(e.g., if you have a tree with depth D, # you'll have D linked lists from Tree import BinarySearchTree from P4_3 import miniHeightBST def createLevelLinkedList(root, lists, level): if...
2db3135898b0a57ef68bc4005a12874954b4809f
sunnyyants/crackingPython
/strings_and_array/P1_7.py
893
4.40625
4
__author__ = 'SunnyYan' # # Write an algorithm such that if an element in an M*N matrix is 0, # set the entire row and column to 0 # def setMatrixtoZero(matrix): rowlen = len(matrix) columnlen = len(matrix[0]) row = [0]*rowlen column = [0]*columnlen for i in range(0, rowlen): for j in range...
2f368df1a73c05f6b2f911d588344a1abac148e6
sunnyyants/crackingPython
/Sorting_and_Searching/Counting_Sort.py
516
3.828125
4
__author__ = 'SunnyYan' # Implement of counting sort def countingSort(array): c = [0] * (max(array) + 1) b = [0] * len(array) for i in range(0,len(array)): c[array[i]] += 1 total = 0 for i in range(0,len(c)): count = c[i] c[i] = total total += count for i in ...
bb947745901d55db7cd3d4f7d54f875b17ab6bf5
loluwot/ProgrammingLabs
/Lab1/hello3.py
161
3.921875
4
name1 = 'Andy' name2 = 'Richard' print(f"Hello, {name1} and {name2}. Your names are {name2} and {name1}. Hi there. Your names are still {name1} and {name2}.")
19ef12007dcad4f61ae31f0419c0daca1869ba66
loluwot/ProgrammingLabs
/Lab6/ttt2_opt2.py
3,320
3.625
4
''' X | O | X ---+---+--- O | O | X ---+---+--- | X | ''' import random #globals # primes = [2, 3, 5, 7, 11, 13, 17, 19, 23] # pre_compute_rows = [2*3*5, 7*11*13, 17*19*23] # pre_compute_columns = [2*7*17, 3*11*19, 5*13*23] # pre_compute_diagonals = [2*11*23, 5*11*17] # net_compute = pre_compute_rows + pre_...
b90743a0b575f657bb38d2838ef47d0d30e16e2f
kevchan7/Linked_lists
/Linked_lists/main.py
671
3.765625
4
from linked_list import * def test_linkedlist(): testlist = singly_linked_list testlist.head = node(1) testlist.listprint(testlist) testlist.append(testlist,2) testlist.listprint(testlist) testlist.append(testlist,3) testlist.append(testlist,5) testlist.insert(testlist,4,3) testlis...
0e272ef96a1bc171e10a1b1cb4eb9d2f4105960b
xuqi62/ml
/logist_reg/logistc_regression-base.py
3,935
3.65625
4
# coding: utf-8 # ## Logistic Regression # 来源于《机器学习实战》第五章逻辑回归,使用逻辑回归解决二分类问题。 # # In[3]: # %load lr.py #!/usr/bin/env python3 import numpy as np import matplotlib.pyplot as plt import pandas as pd class LogisticRegression: def __init__(self): print("init 11111") self.__learning_rate = 0.00...
92be7aa5fcabb26a88a71033a344595c1d7bc874
ausaki/data_structures_and_algorithms
/leetcode/find-winner-on-a-tic-tac-toe-game/393687489.py
849
3.5
4
# title: find-winner-on-a-tic-tac-toe-game # detail: https://leetcode.com/submissions/detail/393687489/ # datetime: Thu Sep 10 17:45:24 2020 # runtime: 32 ms # memory: 13.8 MB class Solution: def tictactoe(self, moves: List[List[int]]) -> str: rows = [0] * 3 cols = [0] * 3 dia = [0, 0] ...
4719c2cbd0bbeb02074cea54b50c8d3424e0c99c
ausaki/data_structures_and_algorithms
/leetcode/day-of-the-week/396099168.py
852
3.75
4
# title: day-of-the-week # detail: https://leetcode.com/submissions/detail/396099168/ # datetime: Tue Sep 15 21:48:43 2020 # runtime: 28 ms # memory: 14 MB import datetime class Solution: def dayOfTheWeek(self, day: int, month: int, year: int) -> str: Y, M, D, W = 1971, 1, 1, 4 WEEK = ["Monday", "T...
2b7056eba125cf0d8234314fcc59a7d3ed1263bb
ausaki/data_structures_and_algorithms
/leetcode/pseudo-palindromic-paths-in-a-binary-tree/381734078.py
1,023
3.53125
4
# title: pseudo-palindromic-paths-in-a-binary-tree # detail: https://leetcode.com/submissions/detail/381734078/ # datetime: Sun Aug 16 22:05:01 2020 # runtime: 384 ms # memory: 49.6 MB # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = va...
1ac312ae6fb2ce3ef7886ac05d6a70e0bc669090
ausaki/data_structures_and_algorithms
/leetcode/insert-interval/145383773.py
1,307
3.5
4
# title: insert-interval # detail: https://leetcode.com/submissions/detail/145383773/ # datetime: Fri Mar 16 14:05:32 2018 # runtime: 76 ms # memory: N/A # Definition for an interval. # class Interval(object): # def __init__(self, s=0, e=0): # self.start = s # self.end = e class Solution(object): ...
5851fc04415bc1deefbb79417a0056bd3d05459e
ausaki/data_structures_and_algorithms
/leetcode/rotate-image/190428930.py
1,709
3.53125
4
# title: rotate-image # detail: https://leetcode.com/submissions/detail/190428930/ # datetime: Mon Nov 19 11:59:37 2018 # runtime: 28 ms # memory: N/A class Solution(object): def rotate(self, matrix): """ :type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-pl...
eb1c5ca15d57c35d3ba97c37fbda68a730300d1b
ausaki/data_structures_and_algorithms
/jump_stairs.py
351
3.6875
4
def jump_rec(n, result): if n < 0: return if n == 0: print(result) return result.append(1) jump_rec(n - 1, result) result.pop() result.append(2) jump_rec(n - 2, result) result.pop() def jump_stairs(n): result = [] jump_rec(n, result) if __name__ == ...
ac2fe4a4ec9bc8d8edbf77e476c754d9f721aa47
ausaki/data_structures_and_algorithms
/leetcode/walking-robot-simulation/406567675.py
864
3.5625
4
# title: walking-robot-simulation # detail: https://leetcode.com/submissions/detail/406567675/ # datetime: Fri Oct 9 22:02:31 2020 # runtime: 420 ms # memory: 19.8 MB class Solution: def robotSim(self, commands: List[int], obstacles: List[List[int]]) -> int: x, y = 0, 0 d = 1 result = 0 ...
2150f56352303b76659c70f5bda06979d674d615
ausaki/data_structures_and_algorithms
/leetcode/coloring-a-border/400186394.py
1,175
3.640625
4
# title: coloring-a-border # detail: https://leetcode.com/submissions/detail/400186394/ # datetime: Fri Sep 25 00:42:48 2020 # runtime: 144 ms # memory: 14.1 MB class Solution: def colorBorder(self, grid: List[List[int]], r0: int, c0: int, color: int) -> List[List[int]]: C = grid[r0][c0] if color =...
d62fb046f83e5c7cefbc97c13df13e882004e0d7
ausaki/data_structures_and_algorithms
/quick_select.py
1,179
3.59375
4
def quick_select(data, k): if k <= 0 or k > len(data): return -1 l, r = 0, len(data) - 1 while True: mid = (l + r) // 2 if data[l] > data[mid]: data[l], data[mid] = data[mid], data[l] if data[mid] > data[r]: data[mid], data[r] = data[r], data[mid] ...
3e213f5f4c7786f287f728f85342900ae771e81b
ausaki/data_structures_and_algorithms
/leetcode/distance-between-bus-stops/396089901.py
401
3.625
4
# title: distance-between-bus-stops # detail: https://leetcode.com/submissions/detail/396089901/ # datetime: Tue Sep 15 21:20:07 2020 # runtime: 52 ms # memory: 14.8 MB class Solution: def distanceBetweenBusStops(self, distance: List[int], start: int, destination: int) -> int: s1 = sum(distance[min(start, ...
08328167d6d53e86585f15552614da85251218af
ausaki/data_structures_and_algorithms
/leetcode/minesweeper/287092257.py
1,204
3.53125
4
# title: minesweeper # detail: https://leetcode.com/submissions/detail/287092257/ # datetime: Thu Dec 19 18:24:16 2019 # runtime: 204 ms # memory: 15.3 MB class Solution: def updateBoard(self, board: List[List[str]], click: List[int]) -> List[List[str]]: def update(i, j): if board[i][j] == 'M':...
b6701826fc5079a87dfcd04e7f616e5cfed28bd9
ausaki/data_structures_and_algorithms
/leetcode/shortest-path-with-alternating-colors/397032271.py
932
3.59375
4
# title: shortest-path-with-alternating-colors # detail: https://leetcode.com/submissions/detail/397032271/ # datetime: Thu Sep 17 21:35:16 2020 # runtime: 96 ms # memory: 14 MB class Solution: def shortestAlternatingPaths(self, n: int, red_edges: List[List[int]], blue_edges: List[List[int]]) -> List[int]: ...
8dac732bf531576a63a273a57bc1453d5e03cbe3
ausaki/data_structures_and_algorithms
/leetcode/count-all-possible-routes/398355248.py
1,173
3.5625
4
# title: count-all-possible-routes # detail: https://leetcode.com/submissions/detail/398355248/ # datetime: Sun Sep 20 23:59:32 2020 # runtime: 1680 ms # memory: 20.4 MB class Solution: def countRoutes(self, locations: List[int], start: int, finish: int, fuel: int) -> int: MOD = 10 ** 9 + 7 start, ...
19f323ee3cbcea0d323779cf8d411b28c967acd4
ausaki/data_structures_and_algorithms
/leetcode/maximum-product-of-splitted-binary-tree/390469579.py
1,122
3.609375
4
# title: maximum-product-of-splitted-binary-tree # detail: https://leetcode.com/submissions/detail/390469579/ # datetime: Thu Sep 3 21:40:37 2020 # runtime: 392 ms # memory: 80.1 MB # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val ...
da621a5a8e6d0d5c3d32f9974a61dfe3ca3d3dbd
ausaki/data_structures_and_algorithms
/leetcode/paint-house-iii/381224890.py
1,176
3.546875
4
# title: paint-house-iii # detail: https://leetcode.com/submissions/detail/381224890/ # datetime: Sat Aug 15 21:50:41 2020 # runtime: 1852 ms # memory: 44.6 MB from functools import lru_cache import math class Solution: def minCost(self, houses: List[int], cost: List[List[int]], m: int, n: int, target: int) -> in...
7a37c4adc7575525b27417dd3e67d78097fdce08
ausaki/data_structures_and_algorithms
/leetcode/mini-parser/282915805.py
3,612
3.625
4
# title: mini-parser # detail: https://leetcode.com/submissions/detail/282915805/ # datetime: Sun Dec 1 17:40:16 2019 # runtime: 76 ms # memory: 16.2 MB # """ # This is the interface that allows for creating nested lists. # You should not implement it, or speculate about its implementation # """ #class NestedInteger:...