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
29eb9e047670b7cca01bd1dffae767824332952e
DrOuissem/useful_programs
/code_zoom5/main3.py
3,069
3.78125
4
class Person: def __init__(self,name,age,gender,ssn): self.__name=name self.__age=age self.__gender=gender self.__ssn=ssn #acessor, getter def get_name(self): return self.__name #mutator (setter) def set_name(self,name): self.__name=name def get...
10ff506b1a8fbadabaf181a94ea3f12e9341ebef
DrOuissem/useful_programs
/zoom5/main2.py
1,051
3.890625
4
class Person: def __init__(self,name,age,gender,ssn): self.name=name self.age=age self.gender=gender self.ssn=ssn class Student(Person): def __init__(self,name,age,gender,ssn,id,gpa): super().__init__(name,age,gender,ssn) self.id=id self.gpa=gpa def ente...
f643f39546ae35916bf1147df22e1bdfddfd4972
sheriaravind/Python-ICP4
/Source/Code/Num-Py -CP4.py
359
4.28125
4
import numpy as np no=np.random.randint(0,1000,(10,10)) # Creating the array of 10*10 size with random number using random.randint method print(no) min,max = no.min(axis=1),no.max(axis=1) # Finding the minimum and maximum in each row using min and max methods print("Minimum elements of 10 size Array is",min) print("Max...
2c0861c01668af6b00dfadec1ff30864e8fa0131
adelliamaharanip/Python-X2-AdelliaMaharaniPutri
/PROGRAM 1.py
175
3.9375
4
kilometers = float(input('input valid kilometer : ')) conv_fac = 0.621317 miles = kilometers * conv_fac print('%0.2f kilometers is equal to %0.2f' %(kilometers, miles))
4c5195ceece85c4dfcef214d3dd3c874cbae4d16
adelliamaharanip/Python-X2-AdelliaMaharaniPutri
/T2. Program 6.py
182
3.8125
4
kata = 'nama saya adellia maharani putri' jum = 0 for letter in kata: if letter == 'a': jum += 1 #continue print('huruf sekarang : ', letter) print('jumlah : ', jum)
12ca65ea1eacbb1693ef68721793b32fe1fe7c2a
adelliamaharanip/Python-X2-AdelliaMaharaniPutri
/Program 3 Fungsi Rekursi.py
339
3.84375
4
#mencari nilai penjumlahan dari nilai asli suatu bilangan def penjumlah(n): if n <= 1: return n else: return n + penjumlah(n-1) bil = int(input('input bilangan : ')) if bil < 0: print ('Masukkan bilangan positif') else: print ('Penjumlahan dari nilai asli', bil,'adalah...
50a06a1fb275e923b5744c523130edf79cbb8fe7
rshock262/SimpleTCP-server-py
/TCP-Simple-Server.py
1,445
3.5625
4
#import socket module import socket serverSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #Prepare server socket #####Fill in start#### ip = socket.gethostbyname(socket.gethostname()) port = 8080 addr = (ip, port) serverSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) serverSocket.bind(addr) ...
4f61ba1b120ee25893c1f0986bcc006cf8ab4cf6
romerocesar/fidi
/tree.py
2,385
3.53125
4
class TreeNode: def __init__(self, x, left=None, right=None): self.val = x self.left = left self.right = right def __str__(self): return '({} {} {})'.format(self.left, self.val, self.right) def from_array(A, l=0, u=None): 'from sorted array A' if u is None: u...
ef6d1366196155e89f4f157e3839dbe115bd786a
Bhupinder1995/Practical-10
/Practical_10.py
3,518
3.546875
4
from tkinter import * from tkinter import ttk import mysql.connector def sql_execution(sql): conn = mysql.connector.connect(user='root', password='root', host='127.0.0.1', database='dbone', auth_plugin='mysql_native_p...
32fb2e8e958adff324259a40e06d4ccea8d08740
crockeo/finalproject
/src/IfElse.py
2,343
3.796875
4
# IfElse.py import Interpreter import Utils # Performing an operation def _do_op(n1, o1, n2): if o1 == "==": return n1 == n2 elif o1 == "!=": return n1 != n2 elif o1 == "&&": return Utils.to_boolean(n1) and Utils.to_boolean(n2) elif o1 == "||": return Utils.to_boolean(n1) or Utils.to_boolean(n2) # Ch...
ca6aee7b598e8a8a184b6a803fc5993b33dc8a41
Jimoh1993/Udemy-Data-Analysis-Visualization-Bootcamp-by-Python-Data-Analytics-Data-Science
/Series.py
1,064
4.03125
4
import pandas as pd from pandas import Series import numpy as np object = Series([5, 10, 15, 20]) #print object #print object.value #print object.index #use numpy_arrays to series data_array = np.array(['a', 'b', 'c']) s = Series(data_array) # print s # custom index s = Series(data_array, index=[100, ...
fb69eeb68ced2d2d1abb4c6754d6e3c75244240a
Jimoh1993/Udemy-Data-Analysis-Visualization-Bootcamp-by-Python-Data-Analytics-Data-Science
/Decision Trees on Iris Dataset.py
2,011
3.75
4
import pandas as pd import numpy as np import seaborn as sns import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split from sklearn.tree import DecisionTreeClassifier df = pd.read_csv('Iris.csv') #Check null value df.isnull().any() #Check Datatype of the flowers features df....
3fb3edce524850dfdc618bc407b47c3f57d89978
TENorbert/Python_Learning
/learn_python.py
637
4.125
4
#!/usr/bin/python """ python """ ''' first_name = input("Enter a ur first name: ") last_name = input("Enter your last name: ") initial = input("Enter your initial: ") person = initial + " " + first_name + " " + last_name print("Ur name is %s" %person) print("Ur name is %s%s%s" %initial %first_name %last_name) ...
af84729e748148c904be605b77df0ac80e4e0ff5
dParikesit/TubesDaspro
/exit.py
845
3.78125
4
from save import save def exit(user, gadget, gadget_borrow, gadget_return, consumable, consumable_history, header_user, header_gadget, header_gadget_borrow, header_gadget_return, header_consumable, header_consumable_history) : Pilihan = str(input("Apakah Anda mau melakukan penyimpanan file yang sudah di ubah? (Y/N...
c3d9fdd1ac4796dfe3d6d5181b7b422ff946cd3c
Engcompaulo/compiladores2018_2
/Compiler/lex.py
2,548
3.546875
4
import re # (1) -> La funcion realiza lo que debe de manera natural. # (0) -> La funcion realiza lo que debe pero no de manera natual. #Realiza la busqueda del simbolo correspondiente (1) def simbols(code_section): if code_section == '(': return 'openParentesis' if code_section == ')': return 'closeParentesis' ...
c614652958acc10679d3259839aef781dc15e4dd
ozmaws/Chapter-6
/CH6P1.py
403
4.03125
4
def newton(number): tolerance = 0.000001 estimate = 1.0 while True: estimate = (estimate + number / estimate) / 2 difference = abs(number - estimate ** 2) if difference <= tolerance: break print(estimate) def main(): num = input("Enter number: ") while num != "": newton(flo...
9cde09b7f3922f3c691f9d87af272dfa40ab8b53
HaeunJeong/Project4Me
/brute_force.py
836
3.828125
4
# 제곱근 사용을 위한 sqrt 함수 from math import sqrt # 두 매장의 직선 거리를 계산해 주는 함수 def distance(store1, store2): return sqrt((store1[0] - store2[0]) ** 2 + (store1[1] - store2[1]) ** 2) # 가장 가까운 두 매장을 찾아주는 함수 def closest_pair(coordinates): result = [coordinates[0], coordinates[1]] for t1 in range(len(coordinates)-1): ...
c2067416b858f387b409b551f764f685ec2f56c9
markdunning/MOST
/modules/log_writer.py
6,597
4.34375
4
import logging def setup_logger(info_file = "stdout.log", error_file = "stderr.log", logger_name = 'stdout_stderr_logger' ): """ A function to set up a logger for writing out log files Parameters ---------- info_file : String Path to info level log file (default: stdout.log) error_file...
6eee0560b38eadf477b174afaa485f92aa7f4024
akhlaghiandrew/Data_and_MiddleEast
/World_Bank_intro
1,139
3.734375
4
#!/usr/bin/env python3 #you can enter these commands directly into the command line or into IDLE import pandas as pd #importing brings in new libraries of commands import matplotlib.pyplot as plt #import the library that makes graphs import numpy as np df_1=pd.read_csv(WOLRD_BANK_DATA.CSV) #the file name will dep...
f3656e752fc296eb8f1c569b63a14ba412457054
diegoasanch/Fundamentos-de-Progra-2019
/TP2 Estructura secuencial/TP2.6 Promedio de 3 enteros.py
374
4.09375
4
#Ingresar tres números enteros, calcular su promedio y mostrarlo por pantalla. print('Calculador del promedio de 3 numeros enteros') print() a=int(input('Ingrese el primer valor a promediar: ')) b=int(input('Ingrese el segundo valor: ')) c=int(input('Ingrese el ultimo valor: ')) promedio=(a+b+c)/3 print() prin...
993ee5480a7ae87e4b03604799d08036f8290615
diegoasanch/Fundamentos-de-Progra-2019
/TP6/TP6.10 Ingresa dos listas y genera 3 distintas.py
1,611
3.859375
4
# Cargar dos listas de números A y B. Se solicita construir e imprimir tres nuevas # listas C, D y E que contengan: # · La concatenación de los valores pares de A con los impares de B.* # · La concatenación de los valores pares de A con el reverso de los valores # pares de B. ("valores pares" o "valores impares" se ref...
877dd957c6e7d6b3524a81eaeb20171455d799d8
diegoasanch/Fundamentos-de-Progra-2019
/TP6/TP6.1 Ingreso de valores en una lista.py
844
3.84375
4
# Escribir una función para ingresar desde el teclado una serie de números entre 1 y 20 y guardarlos en una lista. # En caso de ingresar un valor fuera de rango el programa mostrará un mensaje de error y solicitará un nuevo número. # Para finalizar la carga se deberá ingresar -1. La función no recibe ningún parámetro, ...
b9edd40bd75062b9d73e7fe76855e560e29bf6f8
diegoasanch/Fundamentos-de-Progra-2019
/TP3 Estructura alternativa/TP3.3 Ingrese un numero N y duplicarlo o triplicarlo.py
538
3.921875
4
#Leer un número entero N y determinar si es un número natural (positivo y distinto de 0). # Si lo es, imprimirlo junto con su doble. En caso contrario, imprimirlo junto con su triple. print('Leer un numero entero N. Si N es natural, duplicarlo. De lo contrario, triplicarlo') print() N=int(input('Ingrese el valor d...
8ae77f7cea8c63611b790b97b0c65d03826a4e4f
diegoasanch/Fundamentos-de-Progra-2019
/TP5 Funciones/TP5.9 Valor ingresado positivo, negativo o nulo.py
559
4.0625
4
# Desarrollar la función signo(n), que reciba un número entero y devuelva un 1, -1 # o 0 según el valor recibido sea positivo, negativo o nulo. def signo(n): if n>0: v=1 valor='positivo' elif n<0: v=-1 valor='negativo' else: v=0 valor='nulo' return v,valor...
0b0f72365845e394e4886962c4c51d0a4a1f2c2e
diegoasanch/Fundamentos-de-Progra-2019
/TP4 Estructura iterativa/TP4.8 Imprime todos los naturales entre 1 y 300.py
299
3.953125
4
#Desarrollar un programa que imprima los números naturales comprendidos entre #1 y 300. print('Ve en pantalla todos los numeros naturales entre 1 y 300') print() n=input('Presiona enter para comenzar: ') x=1 while x<=300: print(x) x=x+1 print('Esos son todos los enteros entre 1 y 300 :)')
e9dd0b17773024f0cb66df618302fecc807a4c2c
diegoasanch/Fundamentos-de-Progra-2019
/TP4 Estructura iterativa/TP4.21 Naturales pares menores que n.py
447
4
4
#Leer un número natural N. Calcular e imprimir los números naturales pares menores que N. print('Imprime los naturales pares menores que un numero natural cualquiera') print() n=int(input('Ingrese un numero natural: ')) if n>0: inicial=n n=n-1 while n>=0: if n%2==0: print(n) n=n-...
2f9463f54a81dc7d2752becc1aca6352331e62fc
diegoasanch/Fundamentos-de-Progra-2019
/TP2 Estructura secuencial/TP2.9 Cajero automatico.py
2,245
3.859375
4
#Un banco necesita para sus cajeros automáticos un programa que lea #una cantidad de dinero e imprima a cuántos billetes equivale, considerando #que existen billetes de $100, $50, $10, $5 y $1. Desarrollar dicho programa #de tal forma que se minimice la cantidad de billetes entregados por el cajero. print('Cajero Autom...
2c23e549b3f04c9d776a698348039ef1e8eba4a3
diegoasanch/Fundamentos-de-Progra-2019
/TP3 Estructura alternativa/TP3.10 Clasificador de triangulos.py
1,441
4.28125
4
#Desarrollar un programa para leer las longitudes de los tres lados de un triángulo # L1, L2, L3 y determinar qué tipo de triángulo es según la siguiente clasificación: # · Si A >= B + C no se trata de un triángulo. # · Si A² = B² + C² se trata de un triángulo rectángulo. # · Si A² > B² + C² se trata de un triángulo ob...
00e6d264e72e105fe3c5953ffa1f1f558974c8a0
diegoasanch/Fundamentos-de-Progra-2019
/TP4 Estructura iterativa/Repaso parcial 1/ej 8 modif 2 (cuenta en pasos predefinidos).py
546
3.921875
4
print('Ver en pantalla los numeros contando en pasos ingresados comprendidos entre dos numeros') print() a=int(input('Ingrese uno de los limites: ')) b=int(input('Ingrese el otro limite: ')) sep=int(input('Ingrese la cant de separacion entre cada num a imprimir: ')) print() if a==b: print('No ingreso 2 numeros natu...
2bc83bf2c084a7baba788f047d97427d57d7eb3c
diegoasanch/Fundamentos-de-Progra-2019
/TP5 Funciones/TP5.12 Extraer un digito de un entero.py
1,705
4.15625
4
# Extraer un dígito de un número entero. La función recibe como parámetros dos # números enteros, uno será del que se extraiga el dígito y el otro indica qué cifra # se desea obtener. La cifra de la derecha se considera la número 0. Retornar el # valor -1 si no existe el dígito solicitado. Ejemplo: extraerdigito(12345,...
34565aa00c3f57d068b105f6b5dd1c4f4bcfec91
diegoasanch/Fundamentos-de-Progra-2019
/TP5 Funciones/TP5.4 Numero par o impar.py
355
3.8125
4
# Verificar si un número es par o impar, devolviendo True o False respectivamente. def paroimpar(numero): if numero%2==0: paridad=True else: paridad=False return paridad #Programa principal print('Verificar si un numero es par o impar') n=int(input('Ingrese un numero: ')) par= paroimpar(n) ...
88f48cfe8704c479ef00c4d259fb6e6a851e40f3
diegoasanch/Fundamentos-de-Progra-2019
/TP6/TP6.3 Lista capicua v2.py
1,037
3.796875
4
# Determinar si una lista es capicúa. #funcion ingreso de valores def ingresodenum(): lista = [] n=int(input('Ingrese un numero: ')) while n!=-1: if n>=1 and n<=20: lista.append(n) else: print('Error, debe ingresar un numero entre 1 y 20') n=int(input('Ingres...
9c6c3f00151e299ed1ec9ddc58e25f0b5766e317
diegoasanch/Fundamentos-de-Progra-2019
/TP5 Funciones/TP5.7 Factorial de un numero.py
389
4
4
# Dado un número entero, calcular su factorial. Ejemplo: fact(4) = 4*3*2*1 = 24. #funcion factorial def fact(n): if n==1: factorial = 1 else: factorial = n * fact(n-1) return factorial # programa principal print('Calculador del factorial de un numero') print() A=int(input('Ingrese un numero...
4d2e57dbc334cb1ba9f22efbdbac4fd5f38d95a8
diegoasanch/Fundamentos-de-Progra-2019
/TP4 Estructura iterativa/TP4.2 Imprimir primer y ultimo valor.py
504
4.15625
4
#Realizar un programa para ingresar desde el teclado un conjunto de números. Al #finalizar mostrar por pantalla el primer y último elemento ingresado. Finalizar la #lectura con el valor -1. print('Ingrese numeros, para finalizar ingrese -1') print() n=int(input('Ingrese un valor: ')) if n!=-1: primero=n while n...
ef583f58372944db47f089c771190a4d00feddbd
riyadh-ouz/Graphs
/graph.py
8,386
3.8125
4
#from collections import deque from queue import LifoQueue from queue import Queue from queue import PriorityQueue # the Graph class (represented with adjacency list) class Graph: def __init__(self, n_vertices, n_edges, weighted, directed, input_stream = input): self.__n_vertices = n_vertices ...
7a1f5765a5df51b3e0d1a0a67dea67f43266b555
Rjlmota/Memoria
/main3.py
388
3.71875
4
import ram3 op = "R" while op in ("RWLrwl"): op = input("Digite W para escrever, R para ler, L para listar toda a memoria e qualquer tecla para parar. \n") if op == "R" or op == "r": ram3.read() if op == "W" or op =="w": ram3.write() if op == "L" or op == "l": f...
48ccadf4b544006414dab3c9b2698156713d84e3
MifARION/Mif_project
/homework_four_mif.py
983
3.6875
4
try: alphabet = "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz" \ "ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZ" \ "12345678901234567890 " encrypt = input("Enter somethings: ") key = int(input("Enter a key (number from 1-25): ")) result = "" if key <= 0:...
b236ae0bd0d54b7d7cb82fafb396cd8ce4c1be25
MifARION/Mif_project
/prize_by_mif.py
1,179
3.78125
4
try: alphabet = "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz" \ "ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZ" \ "12345678901234567890 " encrypt = input("Enter somethings: ") key = int(input("Enter a key (number from 1-25): ")) def caesar(encrypt, key): ...
219fad66c338b33cd48a90bcdb9fc31725f8d270
MifARION/Mif_project
/homework_six_mif.py
1,240
3.65625
4
import re import calendar from itertools import accumulate from operator import mul import fileinput #Задание 1 if __name__ == '__main__': with open('ragnar.txt', 'r') as my_file: data = ''.join(i for i in my_file.read()) result = re.findall(r'\d\d\-\d\d\-\d{4}', data) print(result) #Зада...
25b1a46a621054c7d04da0e02ce0acc6181c46eb
keithrpotempa/python-book1
/sets/cars.py
1,539
4.21875
4
# Create an empty set named showroom. showroom = set() # Add four of your favorite car model names to the set. showroom.update(["Car1", "Car2", "Car3", "Car4"]) # Print the length of your set. print("Showroom length", len(showroom)) # Pick one of the items in your show room and add it to the set again. showroom.upda...
6f18b9418ab67ae1ff78c1410d2ca96dc77e619f
JuanDavidDava2/holbertonschool-interview
/0x19-making_change/0-making_change.py
601
3.796875
4
#!/usr/bin/python3 """ Given a pile of coins of different values """ def makeChange(coins, total): """ determine the fewest number of coins needed to meet a given amount total """ if total <= 0: return 0 tmp = total + 1 tmp_list = {0: 0} for i in range(1, total + 1): ...
d4a524ea19b19afd811e32a9f0c58916b4cabb8f
BrutalCoding/INFDEV01-1_0912652
/DEV_01_1___Assignment_4___Exercise_1.b/DEV_01_1___Assignment_4___Exercise_1.b/DEV_01_1___Assignment_4___Exercise_1.b.py
227
4.25
4
celcius = -273.15 #This is the default value to trigger the while loop here below while celcius <= -273.15: celcius = input("Enter Celcius to convert it to Kelvin:\n") print "Celcius:", celcius, "Kelvin = ", celcius+273.15
c4d3b5655e0ae700de07ee01b1c94cdf4bbc952a
d-milisits/ATM_JSON
/classATM/view.py
1,003
3.8125
4
#controller imports model and view and calls all the functions #model is the logic #view is the print statements/user interface stuff def PIN_prompt(): return input("Please enter your 4 digit PIN number now: ") def acc_num_prompt(): return input("Please enter your account number.") def pin_error(): prin...
ede22ce40be586fe2db259caed01c3cb73747d07
pratyusa98/Open_cv_Crashcourse
/opencvbasic/13. blending.py
895
3.71875
4
#Blending means addition of two images #if you want to blend two images then both have same size #Here We use two important functions cv2.add(), cv2.addWeighted() import cv2 img1 = cv2.imread("resources/roi_opr.jpg") img1 = cv2.resize(img1,(500,700)) img2 = cv2.imread("resources/bro_thor.jpg") img2 = cv2.res...
e18be0e755b19dad2c1170e8dd4d91f181985909
pratyusa98/Open_cv_Crashcourse
/opencvbasic/20. Morphological Transformation p2.py
1,710
3.890625
4
#Two more basic Morphological Transformations are #1) - Opening and 2) - Closing #-------------Morphological Transformations----------------------- #Morphological transformations are some simple operations based on the image shape. #It is normally performed on binary images(gray scale image). # It needs two in...
7b8a733511cf5addbcd795bfdf1b2358273104cc
s00hyun/Today-I-Learned
/Coding-test-practice/Baekjoon/그래프와BFS/ABCDE.py
1,596
3.515625
4
#-*- coding: utf-8 -*- def answer(): # n: 사람의 수 (정점의 수) # m: 친구 관계의 수 (간선의 수) n, m = map(int, input().split()) # 인접행렬 A = [] # 인접리스트 (딕셔너리와 셋을 이용) A_list = {} # 간선리스트 E_list = [] for i in range(n): A.append([0] * n) A_list[i] = set() # 인접행렬, 인접리스트, 간선리스트 업...
ee8c6026516672b5038dbc2b3cff6d0eb921c348
s00hyun/Today-I-Learned
/Coding-test-practice/Baekjoon/줄서기_17178.py
1,604
3.6875
4
import sys from collections import deque # t1 < t2 => return 1 # t1 > t2 => return 0 def smaller(t1, t2): t1_a, t1_n = t1 t2_a, t2_n = t2 if t1_a < t2_a: return 1 elif t1_a > t2_a: return 0 else: # t1_a == t2_a if t1_n < t2_n: return 1 else: ...
f97463227c7e32507e636f8bb43a3ba9e0d14dbb
1605125/newthing11
/inheritance_concept.py
1,392
3.5625
4
class Profile: # def __init__(self, name, email, address): def setProfile(self, name, email, address): self.name = name self.email = email self.address = address def displayProfile(self): return "Name : {0} \nEmail : {1} \nAddress : {2} ".format(self.name, self.email, self.a...
36e3711ee1b1dbf5aff92da40740562431a7ccb9
1605125/newthing11
/ex_1.py
210
3.59375
4
a='10' print(isinstance(a,int)) print(type(a)) b=input("please enter value 1\n") c=input('please enter value 2\n') print(int(b)+int(c)) count=0 print(id(count)) while(count<5): count=count+1 print(id(count))
d2fc20a6dc255ced3819f5527ffafaef06150be0
1605125/newthing11
/fns2.py
485
4.0625
4
def addition(name,email): return "Name: {0}\nEmail:{1}".format(name,email) temp = addition(email='rajemail.com',name='Raj') print(temp) print("------------------------------------------------------") # single * and double ** arguments and keywords def sub(*args): print(args) sub(1,2,3,4) print("----------------...
114ebbef6396c6f03848873e56acf214cf41b9ae
tensory/Code501
/Homework 4/directed_graph.py
827
3.640625
4
class DirectedGraph(): def __init__(self, vertices): self.adjacents = {} self.V = vertices def insert(self, key, value): if key in self.adjacents: if self.adjacents[key] and value is not None: self.adjacents[key].append(value) return if value is None: self.adjacents[key] = [] else: self.a...
1090c62ec1860c737307c2fe1fc354ec7098bd53
AlexanderTallqvist/AAP1-PYTHON
/Prov/mara.py
716
3.640625
4
# Uppg. 1 def sum_ints(m, n): counter = n - m ret_value = 0 while counter >= 0: temp_value = m + counter ret_value = temp_value + ret_value counter = counter - 1 return ret_value print sum_ints(11,20) # Uppg. 2 def file_to_list(file_name): return_list = [] tr...
1c822e39d85b66e8aa38f9be901fb690c9188316
AlexanderTallqvist/AAP1-PYTHON
/Prov/blanda.py
411
3.515625
4
import random def myshuffle(cards): for i in range(1,52): temp = random.randint(0,i) # randint inkluderar ju båda gränserna cards[i],cards[temp] = cards[temp],cards[i] def cardshuffle(): cards = [] for i in range(0,52): # korten lagras i listan i positionerna 0..51 cards.append(i...
1de957364c93cd3f8f9a3e6968e985178848c261
AlexanderTallqvist/AAP1-PYTHON
/Övning 10/search.py
1,902
4.09375
4
''' search.py Collection of search functions ''' def linear_search_for(mylist, x): '''Using linear search, returns some i such that mylist[i] == x. If x is not in mylist, then -1 is returned. ''' # number of elements in mylist, i.e. last index + 1 numelem = len(mylist) # create a list of a...
b3f3433d00f2e111949ff1b2c3ba3fbcb745de54
karthiksastha/Data-visualization-assignment
/Matplotlib assignment-9.py
4,869
4.125
4
#Q1)Scipy: #We have the min and max temperatures in a city In India for each months of the year. We would like to find a function to describe this and show it graphically, the dataset given below. #Task: #fitting it to the periodic function #plot the fit #Importing necessary libraries import numpy as np ...
1d719efdb3c5a7e26285d2121f130aadf9cfa701
Dolantinlist/DolantinLeetcode
/101-150/101A_symmetric_tree.py
544
3.78125
4
from Tree import * class Solution: def isSymmetric(self, root): if not root: return True return self.checkSymmetric(root.left, root.right) def checkSymmetric(self, left, right): if not left and not right: return True if not left or not right: ...
370ac6d650af08c2a0de8f58faedbfcac841f3fe
Dolantinlist/DolantinLeetcode
/51-100/73_search_2d_matrix.py
1,074
3.59375
4
# class Solution(object): # def searchMatrix(self, matrix, target): # m = len(matrix) # if m == 0: # return False # else: # n = len(matrix[0]) # if n == 0: # return False # l, r = 0, m * n - 1 # while l <= r: # ...
973a1d8dab6aea1e8b0d5ac759e12e93ad1013e2
Dolantinlist/DolantinLeetcode
/suanfa/merge_sort.py
538
3.875
4
def merge_sort(nums): if len(nums) <= 1: return nums mid = len(nums) // 2 left = merge_sort(nums[:mid]) right = merge_sort(nums[mid:]) return merge(left, right) def merge(a, b): rlt = [] i = j = 0 while i < len(a) and j < len(b): if a[i] <= b[j]: rlt.append(a...
fae78138c27b039741b2d9d14bfa90eccb942359
Dolantinlist/DolantinLeetcode
/jianzhi/max_in_window.py
292
3.59375
4
class Solution: def maxInWindows(self, num, size): if not size: return [] l = len(num) rlt = [] for i in range(l - size + 1): rlt.append(max(num[i:i + size])) return rlt print(Solution().maxInWindows([2,3,4,2,6,2,5,1], 3))
53de9cf5dc962d5f6c89e672d34755bed8c4f473
Dolantinlist/DolantinLeetcode
/51-100/79_word_search.py
1,010
3.765625
4
class Solution(object): def exist(self, board, word): if len(board) == 0 or len(board[0]) == 0: return False for i in range(len(board)): for j in range(len(board[0])): if self.helper(board, i, j, word): return True return False ...
315a714cc31e4c11b6a3216af1294e71ae601b41
Dolantinlist/DolantinLeetcode
/1-50/37_sudoku_solver.py
1,525
3.671875
4
class Solution(object): def solveSudoku(self,board): self.board = board self.solve() def solve(self): row, col = self.find_empty() if row == -1 & col == -1: return True else: for num in ['1', '2', '3', '4', '5', '6', '7', '8', '9']: ...
a964bc87005b3ff39fa5a4e9fadfc973639f594b
Dolantinlist/DolantinLeetcode
/201-250/204_count_primes.py
310
3.609375
4
class Solution: def countPrimes(self, n): rlt = [True] * n rlt[0], rlt[1] = False, False for i in range(2, n): if rlt[i]: for j in range(2, (n - 1)//i + 1): rlt[i * j] = False return sum(rlt) print(Solution().countPrimes(10))
c3e4ea650c31bab644390bdfd3c72c1ada9379c9
Dolantinlist/DolantinLeetcode
/101-150/116_BT_next_right_pointer.py
405
3.625
4
from Tree import * class Solution: def connect(self, root): if not root: return while root.left: cur = root.left prev = None while root: if prev: prev.next = root.left root.left.next = root.right ...
b0985c06edbb8bc0ff8d86e3f7b5772d204954a3
olivepeace/ASSIGNMENT-TO-DETERMINE-DAYOF-BIRTH
/ASSIGNMENT TO DETERMINE DAY OF BIRTH.py
1,960
4.375
4
""" NAME: NABUUMA OLIVIA PEACE COURSE:BSC BIOMEDICAL ENGINEERING REG NO: 16/U/8238/PS """ import calendar print("This Program is intended to determine the exact day of the week you were born") print(".....................................................") day = month = year = None #Next code ensures that o...
e67689a5670811838dfe6741d5bc43051ba5497b
up1/course-basic-python
/demo/loop_while.py
109
3.765625
4
counter = 0 while counter<5: print(counter) counter += 1 else: print("%d more than 4" % counter)
a8a75ce7999ded00d78dcef11a033a2807d0076a
up1/course-basic-python
/workshop/day1/loop.py
134
3.703125
4
datas = range(1, 9, 2) # For-each for data in datas: print(data) # Loop by index for i in range(len(datas)): print(datas[i])
d194611d50815d285c6bed78a8f1b9ebc07b6754
up1/course-basic-python
/demo/more_operator.py
170
4.03125
4
name = input("Enter your name: ") names = ["some", "one", "somkiat", "pui"] if name in names: print("Found %s in database" % name) else: print("Name not found")
19ea88fe0b47dc7d203e80d1fc385ccddb3f72ea
katuhito/workspace9
/tensorflow/mnist-mip.py
1,771
3.5625
4
# MLPでMNISTの分類問題に挑戦 import keras from keras.models import Sequential from keras.layers import Dense, Dropout from keras.optimizers import RMSprop from keras.datasets import mnist import matplotlib.pyplot as plt # 入力と出力を設定 in_size = 28 * 28 out_size = 10 # MNISTのデータを読み込み (X_train, y_train), (X_test, y_test) = mnist.lo...
859dd2292bc3fd590264c0f7319e6fce86551b7d
CTingy/CheckiO
/home/01_HousePassword.py
1,547
3.625
4
import re def checkio(data): a = False b = False c = False d = False if len(data) >= 10: a = True for s in data: if s.isupper(): b = True if s.islower(): c = True if s.isdigit(): d = True return a and b and c ...
b5811324659ae106c9b5e007b2a942343ab7d00e
CTingy/CheckiO
/home/06_Pawns.py
1,245
3.890625
4
def safe_pawns(pawns: set) -> int: safe_pawns = set() while pawns: pawn = max(pawns, key=lambda x: x[1]) next_pawn = {chr(ord(pawn[0])+1) + str(int(pawn[1])-1), chr(ord(pawn[0])-1) + str(int(pawn[1])-1)} if next_pawn & pawns: safe_pawns.add(pawn) pawns.remove(pawn) ...
c90f3b0c9c714665e6ae1991a9a3e3f35a44d794
NDjust/python_data_structure
/dummy_LikedList/popMethod_nathan.py
626
3.625
4
''' 1. 맨앞의 리스트를 pop 할경우 2. 리스트가 한개일 경우 3. 맨뒤의 리스트를 pop할 경우 * dummy node 고려해서 코드 짜기. ''' def popAfter(self, prev): if prev.next is None: return None curr = prev.next if self.nodeCount != 1 and curr.next is None: self.tail = prev prev.next = curr.next self.nodeCount -= 1 retu...
c08a6b31684f0d20fd1c7ef9b64e8db0168e7ff5
NDjust/python_data_structure
/sort_search/search.py
1,413
4.21875
4
from random import randint import time def linear_search(L, x): ''' using linear search algorithms time complexity -> O(n) parmas: L: list x: target num ''' for i in range(len(L)): if x == L[i]: return i return -1 def binary_search(L, x): ''' usin...
bcf8ae10f23b2177ad6af1c476e5fb707dc591f4
rousgidraph/est_algorithm
/solution.py
10,585
3.59375
4
import math #this is not an external library import random from queue import PriorityQueue from typing import OrderedDict """constants""" #env file filename = "001.env" #obstacle array BOUNDS =[]# X_low,X_high,y_low,y_high the limit of the word area obstacle_count = 0 obstacles = [] tree = [] #an empty list tha...
c4171f9cf0e4c1dbb3ec2f91819c7d5a06e20270
CMRD2/Trishita-Gharai
/ttt.py
1,069
3.890625
4
# tic tac toe a=['1','2','3','4','5','6','7','8','9'] def board(): print('-------------') print('|',a[0],'|',a[1],'|',a[2],'|') print('-------------') print('|',a[3],'|',a[4],'|',a[5],'|') print('-------------') print('|',a[6],'|',a[7],'|',a[8],'|') print('-------------') p1 = True while True: board() c=inp...
49749bd442af3b5dfa759b48b5a5fd7b8318dcd8
CMRD2/Trishita-Gharai
/positivenegative.py
152
4.15625
4
x=int(input("enter the no.")) #checking whether the no. is positive or not if(x>0): print("the no. is positive") else: print("the no. is negative")
25130b5ceeddf52c7bdd47d9fd371928190d01cb
alloik/python_basic_07_09_2020
/Task6.py
1,763
3.53125
4
""" Спортсмен занимается ежедневными пробежками. В первый день его результат составил a километров. Каждый день спортсмен увеличивал результат на 10 % относительно предыдущего. Требуется определить номер дня, на который общий результат спортсмена составить не менее b километров. Программа должна принимать значения пара...
0a5e0016caf745d3e00ae48b523e94b9e11bdcaf
pavanboyapati/ds
/queue.py
549
3.875
4
class EmptyQueueException(Exception): def __str__(self): return "Queue is empty" class Queue(object): def __init__(self): self.__list = [] def __str__(self): return str(self.__list) # .__str__() def enqueue(self, item): self.__list.append(item) def dequeue(self...
600be6c101d2ca51130abe1a4e01fb755c401869
shubajitsaha/reverse
/reverse/reverse.py
1,156
3.734375
4
class ReverseFile: def __init__(self,filename, sep=' ',encoding='utf-8'): self.filename = filename self.encoding = encoding if len(sep) != 1: raise ValueError('separator should be a single character') self.separator = sep def _read_file(self): with op...
682361a204e5dde8c1f6ac1ee4061863ac71be21
JawadArman96/ContactManagement
/ContactManagementApp/venv/LoginAccessValidation.py
1,740
3.75
4
import UserInfo class LoginAccessValidation: """A class interface for validation of Login Access """ def __init__(self,name): """Constructor for LoginAccessValidation""" self.name=name self.token=1200 self.activeUserList=[] self.activeTokenList=[] def accessValidation...
c09774baba526c5554ec80c63ee9c214ac356596
Montana/travis-ibmz-day
/regex_count.py
576
3.921875
4
# For IBM Z Day 2021 & Travis CI by Montana Mendy import re string = "Montana Mendy !, 010" uppercase_characters = re.findall(r"[A-Z]", string) lowercase_characters = re.findall(r"[a-z]", string) numerical_characters = re.findall(r"[0-9]", string) special_characters = re.findall(r"[, .!?]", string) print("The...
c79e9b0e4e98f6502ec0cf1ff112b8de879bf7cf
mikamyrseth/hydro-product-mix
/data_insight/product_intersections.py
1,614
3.5625
4
import pandas as pd from pandas import DataFrame from data.raw import Column def analyse_products_by(column: Column, data: DataFrame) -> None: """ Find properties of products when viewed in relation to supplied column. The results will be written into various files. :param column: The column to ana...
47fb97ace5801a814e223576783122ad074b31bd
alrus2797/EDA
/Lab2 - Cubeta/main.py
1,380
3.78125
4
def getLenNumber(number): res=0 number=abs(number) while number > 0: number=number//10 res+=1 return res def getSubNumber(number,position): #tam=getLenNumber(number) if position < 0: return -2 modulo=10**(position) return int((number//(modulo))%10) def sho...
3abf9ffbad8cc8a2da068ab8245dc54c577b0dcd
danielknight/bob-ross
/Transcript Scraper/wordCloudGen.py
1,369
3.5
4
"""Make a wordcloud from the Bob Ross Corpus """ from os import path from os import walk from wordcloud import WordCloud import matplotlib.pyplot as plt transcripts = [] for root, dirs, files in walk(r".\Transcripts\The Joy of Painting - Season 1"): for file in files: if file.endswith(").txt"): ...
95e8cca1f3a7737d571d52c82f93d7fd1b0b245e
wmcu/my_leetcode
/longest-palindromic-substring.py
930
3.578125
4
class Solution: # @return a string def longestPalindrome(self, s): LL = len(s) if LL < 3: return s maxL, maxB = 1, 0 # init as one char # odd length: 3, 5, ... for i in range(1, LL - 1): # select center point n = min(i, LL - i - 1) # upper bound of...
70cb2be0a8263fc1216a82df1f5b0c98b9e7e994
30-something-programmer/Python-Noob
/try catch.py
125
3.5625
4
x = input("Please type an integer: ") try: x = int(x) print(x) except ValueError: print("Please type an integer")
fbe32e05c55748ebfdb31bdd95f4abd3adb4dd99
afzals2000/python_resource
/src/thread_and_process/run_2_process.py
739
3.90625
4
import time import multiprocessing # Processes speed up Python operations that are CPU intensive because they benefit from multiple cores # Processes can have multiple threads and can execute code simultaneously in the same python program def cal_square(numbers): for n in numbers: time.sleep(0.2) p...
22bdb25a652babeab48e8a4d981fa732bfe815b2
afzals2000/python_resource
/src/data_structures/list_example.py
2,142
3.75
4
from data_structures.user import User def shallowCopy(): l1 = [[1,2],3,[4,5]] l2 = l1[:] print(l1) print(l2) if (l1 is l2): print("l1 and l2 same object {0} <=> {1}".format(id(l1),id(l2))) else: print("l1 and l2 not same object {0} <=> {1}".format(id(l1),id(l2))) if (l1[0...
6083c488cfbb2a69c96e54ade6df87e83a1a9644
dreamingfish2011/leetcode
/com/self/linkedList/_2AddTwoNumbers.py
1,128
3.921875
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 """ curr = dum...
95160e565a65430821217add33e4967b502f33e7
dreamingfish2011/leetcode
/com/self/linkedList/_25ReverseNodesinkGroup.py
1,151
3.75
4
# Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def reverseKGroup(self, head: ListNode, k: int) -> ListNode: dummy = jump = ListNode(0) dummy.next = l = r = head while True: count = 0 ...
7d6d608de73a0151fc21423c29fd0a82dc80f8eb
dreamingfish2011/leetcode
/com/self/array/_35_SearchInsertPosition.py
954
3.921875
4
class Solution: # Runtime: 28 ms, faster than 99.70% of Python3 online submissions for Search Insert Position. # Memory Usage: 13.7 MB, less than 33.67% of Python3 online submissions for Search Insert Position. def searchInsert(self, nums, target: int) -> int: lo = 0 hi = len(nums) - 1 ...
35095d81a6b1eaa6666aa45ed8f83370a50fa04d
dreamingfish2011/leetcode
/com/self/linkedList/_21MergeTwoSortedLists.py
1,068
3.96875
4
# Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: start = ListNode(0) head = start while l1 and l2: if l1.val <= l2.val: ...
46adb9d2ace4da7256c3aae77ac9ccfa440da733
dreamingfish2011/leetcode
/com/self/matrix/_498_DiagonalTraverse.py
937
3.671875
4
class Solution: def findDiagonalOrder(self, matrix ) : rel = [] M = len(matrix) if M ==0: return rel N = len(matrix[0]) if M ==0: return rel i = 0 j = 0 for X in range(0,M*N) : rel.append(matrix[j][i]) i...
d64661ef679fc6314f75f22364f2d3dd787ab8bc
RaazeshP96/Python_assignment1
/dataTypes03.py
675
4.03125
4
''' Write a Python program to get a string made of the first 2 and the last 2 chars from a given a string. If the string length is less than 2, return instead of the empty string. Sample String : 'Python' Expected Result : 'Pyon' Sample String : 'Py' Expected Result : 'PyPy' Sample String : ' w' Expected Result : Empty...
95b2dae71598ad8aafb49dcff0715554c05c473e
RaazeshP96/Python_assignment1
/dataTypes44.py
149
4.15625
4
''' Write a Python program to slice a tuple. ''' # let tuple1 tuple1 = (1, 2, 3, 4, 5) tuple1 = tuple1[:-2] # remove last 2 element print(tuple1)
730b8f7a6d5176e8a8f9bc6754d682c86bda7103
RaazeshP96/Python_assignment1
/dataTypes34.py
226
3.53125
4
''' Write a Python script to merge two Python dictionaries. ''' def mergeDict(dic1, dic2): dic1.update(dic2) return dic1 # sample values dic1 = {1: 10, 2: 20} dic2 = {3: 30, 4: 40} print(mergeDict(dic1, dic2))
a528812054cf782c2340bc8b52f7f5319457f08b
RaazeshP96/Python_assignment1
/function08.py
308
3.984375
4
''' Write a Python function that takes a list and returns a new list with unique elements of the first list. Sample List : [1,2,3,3,3,3,4,5] Unique List : [1, 2, 3, 4, 5] ''' def uniqueList(lis): tempSet = set(lis) return list(tempSet) lis = [1, 2, 3, 3, 3, 3, 4, 5] print(uniqueList(lis))
afad2695aa4dff1ce100cfaf65cbdcca9b6c37d4
RaazeshP96/Python_assignment1
/function12.py
305
4.3125
4
''' Write a Python program to create a function that takes one argument, and that argument will be multiplied with an unknown given number. ''' def multi(n): a = int(input("Enter the number:")) return f"The required result is { n * a }" n = int(input("Enter the integer:")) print(multi(n))
8c225b5b0ac4648cfa8e555b9aaf74312d89484f
RaazeshP96/Python_assignment1
/function16.py
237
4.25
4
''' Write a Python program to square and cube every number in a given list of integers using Lambda. ''' sq=lambda x:x*x cub=lambda x:x*x*x n=int(input("Enter the integer:")) print(f"Square -> {sq(n)}") print(f"Cube -> {cub(n)}")
df3c874927ade80ffcba44c2ba712f47bcca0cb3
RaazeshP96/Python_assignment1
/function14.py
200
4.21875
4
''' Write a Python program to sort a list of dictionaries using Lambda. ''' res=lambda dic: sorted(dic) # sample value dic = {'v': 30, 'd': 60, 'm': 10, 'n': 40, 'f': 50, 'e': 40} print(res(dic))
7acc61ce28fe8a608aa5bf13406aa9fc83a89181
tomassabol/python-SEN5
/priemer.py
411
3.734375
4
#uloha #4 pocetZnamok = int(input("vložte počet známok a stlačte ENTER")) sucetZnamok=0 for i in range(pocetZnamok): sucetZnamok += float(int(input("vložte známky z testov a zakaždým stlačte ENTER "))) def priemerTestov(): priemer=sucetZnamok/pocetZnamok return priemer print("priemer tvojich známok je"...