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
749178beb8f2ee98702d6b2256290f8d83f21bdd
OriEylon/automation_test
/try.py
3,074
3.75
4
import sqlite3 from sqlite3 import Error def create_connection(db_file): connection = None try: connection = sqlite3.connect(db_file) except Error as e: print(e) return connection def select_all_from(conn,from_where): cur = conn.cursor() cur.execute("SELECT * FROM {}".format...
62c3e6e9a96588d4f80fff39552b42a8eb5ba813
onelharrison/python-practice
/words_rotation_point/words_rotation_point.py
1,142
3.75
4
def rotation_point(words): start_point = 0 end_point = len(words) - 1 mid_point = end_point // 2 while start_point <= end_point: if words[mid_point] < words[mid_point - 1]: return mid_point elif words[mid_point] < words[start_point]: end_point = mid_point - 1 ...
1a80f6b7ee6adff4881db3a0fbb99636e0fe81b6
AtalantaAlter/machinelearn
/learn_numpy/calc.py
776
3.953125
4
import numpy as np p=np.array([[-1,4], [-2,8] ]); p1=np.array([[4,6], [3,1] ]); #矩阵乘法是将各个位置的值相乘 p3=p*p1; print(p3); print(np.multiply(p,p1)) #等价于上面 #点乘法 是将行和列相乘 ''' 第一行的任意数字和第一列的任意数字累加 -1*4+-4*3=8 最后在第一行 第一行的任意数字和第二列的任意数字累加 -1*6+4*1=-2 在第一行 接下来第二行和第一列和第二列点乘 放在第二列 ''' ...
d42002714295c0119e6825291cdc1f8378bbc8f2
Ghassen-Faidi/Learning-projects_py
/Python/Exersices/First Last/First last.py
108
3.734375
4
a = [2, 8, 5, 42, 12, 7] items = [] def add(i): items.append(a[i]) add(0) add(-1) print(items)
53350afdb7bf3398636756205073726db35152be
Ghassen-Faidi/Learning-projects_py
/Python/HG converter/func.py
752
3.84375
4
# Functions # Gregorian to Hijri def GreToHij(): Greg = int(input("Enter a Gregorin(Miladi) year: \n>>>")) # Calculation Hij = (Greg-622)/0.97 # Get rid of the fraction frac = Hij - int(Hij) if frac > 0.5: Hij = int(Hij)+1 else: Hij= int(Hij) # final result print("The gregorin(Mil...
615e9a0302286d516d963277affe9aa7ded6a257
MikeACG/surfOpt
/genetics.py
2,777
3.546875
4
import random as rd import numpy as np import matplotlib.pyplot as plt from matplotlib import cm # implements a differential evolution GA class diffEvolver: def __init__(self, ps, F, cp, nfe, rng = 123): self.ps = ps # population size self.F = F # scaling factor self.cp = cp # crossover pro...
9571e3ea20f160b28ae49cf6a0348dd49c614d58
IvanildoCandido/learning-python
/units_numbers.py
522
3.984375
4
""" Faça um programa que leia um número de 0 a 9999 e mostre na teça cada um dos digitos separados: Ex: 1834 unidades: 4 dezenas: 3 centenas: 8 milhar: 1 """ number = int(input("Informe um número: ")) unit = number // 1 % 10 ten = number // 10 % 10 hundred = number // 100 % 10 thousand = number // 1000 ...
5e23c58aae57333c223cdc4dd0c27bfd9c5e4544
JRLV14/Pensamiento_Computacional
/funciones_y_abstracciones.py
1,108
3.78125
4
def busqueda_binaria(): epsilon = 0.01 bajo = 0.0 alto = max(1.0, objetivo) respuesta = (alto + bajo) / 2 while abs(respuesta**2 - objetivo) >= epsilon: print(f"bajo={bajo}, alto={alto}, respuesta={respuesta}") if respuesta**2 < objetivo : bajo = respuesta else: ...
51966fbad81a7355cb31857cbf663a13a7482706
Shreejichandra/October-Leetcode
/1007_minimum_domino_rotations_for_equal_row.py
1,869
4.03125
4
''' In a row of dominoes, A[i] and B[i] represent the top and bottom halves of the ith domino. (A domino is a tile with two numbers from 1 to 6 - one on each half of the tile.) We may rotate the ith domino, so that A[i] and B[i] swap values. Return the minimum number of rotations so that all the values in A are the ...
331d5354417420a43c8c6fbcdd8c9a640e61fa10
mario-alop/ejemplos_python
/diccionario_notas.py
845
3.96875
4
estudiantes = {} id = 1 aprobados = 5 suspensos = 4 suma = 0 media = 0 print() cantidad = int(input('Introduce la cantidad de alumnos que vamos a guradar: ')) print() while id <= cantidad: nombre = input('Nombre del alumno: ') nota = float(input('Dame una nota del alumno: ')) suma += nota print() es...
10378f358b3c66ef446ebd9449daa7c4df097750
mario-alop/ejemplos_python
/fun_adivina.py
629
3.9375
4
from random import randint, uniform, random print() print('Introduzca un número del 1 al 10') aleatorio = randint(0, 10) #print(aleatorio) def adivina(): try: numero = int(input('Número: ')) if aleatorio == numero: print('Has acertado el número!!!!') elif aleatorio > numero: ...
9943c849e468966d8c520e0626408c0cbef9eb0a
mario-alop/ejemplos_python
/diccionario.py
348
3.65625
4
lista = [12, 23, 5, 12, 92, 5,12, 5, 29, 92, 64, 23] diccionario = {} for i in lista: if i not in diccionario: diccionario[i] = 1 else: diccionario[i] = diccionario[i] + 1 print() print('Lista:') print() print(lista) print() print('Número de veces que aparece cada número en la lista:') print() ...
ec6d3c49239b2b2092f22c2e99863283482285bd
qzylinux/Python
/if-else.py
732
3.984375
4
a='start' while a!='end': a=input('please input your weight:') #判断输入的是数字还是其他 if a.isdigit(): #将input的输入str类型转换为int(需要的类型) weight=int(a) #输出转换后的数字 print('you input a float is %d.'%weight) #判断体重类型 if weight<18.5: print('you are underweight.') #continue elif weight<=25: print('your weight is norm...
833b170674ce129a25e3efbea133eae6c903cb1b
qzylinux/Python
/generator.py
216
4.15625
4
#generator 返回当前值,并计算下一个值 def mygenerator(max): a,b,n=0,1,0 while n<max: yield b a,b=b,a+b n=n+1 return 'done' f=mygenerator(10) print('mygenerator(10):',f) for x in f: print(x)
40eefed408a874f7dc517a20c16238ddced6b516
JiniousChoi/tree
/tree.py
833
3.703125
4
#!/usr/bin/python3 from enum import Enum class Deco(Enum): MID = '├── ' END = '└── ' CONT = '│   ' EMPTY = ' ' class Tree: def __init__(self, traverser, print_node, deco=Deco): self.deco = deco self.traverser = traverser self.print_node = print_node def print(self)...
5034bd1032c880a1754a442d0fd519da6779e113
adityakamble49/ml-algorithms
/supervised/regression/linearregression/linear_regression.py
2,199
4.09375
4
# # Linear Regression using Gradient Descent # ## Import Packages import numpy as np import pandas as pd import matplotlib.pyplot as plt # ## Import Data set train_data = pd.read_csv('apartment_data_train.csv') train_data.head() train_data.info() train_data.describe() test_data = pd.read_csv('apartment_data_test...
9e2db45663075ac0ca4158318d93a039416a331d
gsg62/Basic-Python-Programs
/careerPathGamebook.py
1,449
3.90625
4
# Greg Geary # Career Path Gamebook print("Career Path Gamebook") choice1 = input("Do you want to go to college after highschool? (yes/no)") if choice1 == "yes": choice2 = input("What major do you want? (computer science or buisness)") if choice2 == "computer science": choice3 = input("Do you w...
8e3b79279217250bbf35acacc51e8df73ae7e93e
IsaacStong/Leet_Code_Solutions
/Add_Two_Numbers.py
881
3.5625
4
"""Created by Isaac Stong on 6/17/20 Given two singly linked list sum the reverse of those linked lists Store result in same manner. Ex. (2 -> 4 -> 3) + (5 -> 6 -> 4) = 7 -> 0 -> 8 Explanation 342 + 465 = 807""" class ListNode: def __init__(self, val=0, next_node=None): self.val = val ...
ac5fb09501c10e94d3f0c3149967aa2dc28d46ab
pranjal2203/Python_Programs
/recursive fibonacci.py
518
4.5
4
#program to print fibonacci series using recursion #recursive function for generating fibonacci series def FibRecursion(n): if n <= 1: return n else: return(FibRecursion(n-1) + FibRecursion(n-2)) #input from the users no = int(input("Enter the terms: ")) #checking if the...
7a0bc20e388ef8d5856a9513938852b890efcc71
pranjal2203/Python_Programs
/goats_n_ducks.py
454
4.03125
4
#count and display no of goats n ducks by counting by their headds n feets #inputing value of no of heads and legs head=int(input("enter the number of heads : ")) legs=int(input("enter the number of legs : ")) #for loop for calculating no of goats and ducks for duck in range(1,head): goat=head-duck ...
61082c9e36d5c2f72e741985fcad901aaf77811c
Mushrif/Final_Project
/Final_Project_Python_BY_Musharraf_ALRUWAILL
19,658
3.578125
4
#!/usr/bin/env python3 import os import sqlite3 import pprint import random filename = 'C:\sqlite\Mush_db.db' conn = sqlite3.connect(filename) class functions: # to control all functions functionlaity def _init_(self): pass def delete_Fun(self): num_of_...
25cb724c79dabac67e6a7cb66b459708a46b6c6a
cgDeepLearn/DSA_python
/6-trees/PriorityQueue_list.py
1,516
3.859375
4
# -*- coding: utf-8 -*- """ 优先队列的list实现(), O(n)插入,O(1)访问 若采用链表实现,头插入和弹出,O(1)插入,O(n)检查和弹出 date:2017/10/11 """ class PrioQueueError(ValueError): pass class PrioQueue(): """ 优先队列 """ def __init__(self, elist=None): """ Args: elist:初始化数据,默认为None """ if el...
ce05dd1910832fe0b4c8e964e659d0576fa609d8
cgDeepLearn/DSA_python
/8-dict_and_set/dict_list.py
2,865
4.03125
4
# -*- coding: utf-8 -*- """ 基于list的字典实现 """ class Assoc(): """ 字典的基本关联类 """ def __init__(self, key, value): self.key = key self.value = value def __lt__(self, other): return self.key < other.key def __le__(self, other): return self.key < other.key or self.key...
6490128a5a204c3d6a117c326d5e5c398f3195f5
blockheads/ConquerorGame
/Console.py
4,314
3.609375
4
# this is our font size we use for our console import pygame from pygame import font from parsing.parse import Parser from Canvas import WHITE, BLACK CONSOLE_FONT_SIZE = 16 # how long the console should be CONSOLE_LENGTH = 5 CONSOLE_LINE_WIDTH = 3 class Console: def __init__(self,size): # length of the...
d9f819d9f4be1751951d24cf14164923ee246924
stroke-one/ProjectEuler_Python
/Euler_007.py
437
3.59375
4
import time t = time.time() class prime(): def __init__(self): self.primes = [2] def test(self, number): for n in self.primes: if number % n == 0: return self.primes.append(number) num = 2 p = prime() while 1: num += 1 p.test(num) if le...
58c6c0e2929a494e250ae4c7936c8aebe00fb9e4
stroke-one/ProjectEuler_Python
/Euler_012.py
539
3.578125
4
import time t = time.time() def facts(triangle): factorials = [] for n in range(1, int(triangle**.5)): if triangle % n == 0: factorials.append(n) factorials.append(triangle//n) return(len(factorials)) current_triangle = 1 current_step = 1 number_of_factorials = 0 while n...
ac8b06c7597bede605741007b994f3e3c8e56975
nilidan/Training
/MachineLearning/Starting Template for Trainging and Splitting/data_preprocessing_template.py
650
3.515625
4
# Data Preprocessing Template # Importing the libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd # Importing the dataset dataset = pd.read_csv('Data.csv') X = dataset.iloc[:, :-1].values y = dataset.iloc[:, -1].values print(X) print(y) from sklearn.impute import SimpleImputer imputer = ...
2049e82aa7a5a24f4f9bdf39393b2aba2b1faa6a
kipland-m/PythonPathway
/FactorialRecursion.py
764
4.21875
4
# This program is a part of my program series that I will be using to nail Python as a whole. # Assuming given parameter is greater than or equal to 1 | Or just 0. def Factorial(n): if (n >= 1): return n * Factorial(n-1) else: return 1 # Function Fibonacci will take "n" as parameter, in whic...
5495c20c68683ee40fcfccd91ecdde5f2c5e1a6e
Beard12/PythonWork
/Pylot/loginapp/models/Welcome.py
3,777
3.765625
4
""" Sample Model File A Model should be in charge of communicating with the Database. Define specific model method that query the database for information. Then call upon these model method in your controller. Create a model using this template. """ from system.core.model import Model import re ...
ff2eb76db8619b619e9e18a4c1a36cc2d2fd1afd
Beard12/PythonWork
/pythonbasic/drawstars.py
295
3.515625
4
def draw_stars(arr): for x in range(0, len(arr)): count = arr[x] if type(count) is str: print count[0].lower() * len(count), print ("\n") else: for i in range(0, count): print "*", print("\n") x=[4,6,1,3,5,7,25] b=[4, "Tom", 1, "Micheal", 5, 7, "Jimmy Smith"] draw_stars(b)
a4d239d34499301270a10040016fca94af868b91
asen-krasimirov/Python-Advanced-Course
/Exam-Exercises/Python Advanced Exam Preparation- 17 February 2020/Problem 3- Advent Calendar.py
366
3.84375
4
def fix_calendar(array): swaps = -1 while True: if swaps == 0: break swaps = 0 for i in range(len(array)-1): if array[i] > array[i+1]: array[i], array[i+1] = array[i+1], array[i] swaps += 1 return array numbers = [3, 2, ...
1d85c44a1e6eaa0d02100d03914fecae90d886ff
asen-krasimirov/Python-Advanced-Course
/Exam- Python Advanced - September 2020/Problem 2- Chechmate.py
1,137
4
4
def valid_index(number): if -1 < number < 8: return True return False def is_queen_attaching(matrix, directions, *cur_position): for direction in directions: local_row, local_column = cur_position row_delta, column_delta = direction for _ in range(8): local_r...
7bfd25ac37b7057b5c5df020ca86ce7c92425a23
asen-krasimirov/Python-Advanced-Course
/2. Tuples and Sets/2.2 Exercises/Problem 1- Unique Usernames.py
171
3.640625
4
number_of_usernames = int(input()) usernames = set() for _ in range(number_of_usernames): name = input() usernames.add(name) print('\n'.join(usernames))
85ffedeeaebc6040cfa3985cbf3622494e634669
asen-krasimirov/Python-Advanced-Course
/6. File Handling/6.2 Exercises/Problem 3- File Manipulation.py
1,638
3.921875
4
import os while True: data = input().split("-") command = data[0] # Saves the command if command == "End": # If the command is "End" the program stops break file_name = data[1] # Saves the name, all commands use it if command == "Create": """ Creates a new file. ...
25a1c557ef87b2d713b294d0ea94271f80fd1f2a
asen-krasimirov/Python-Advanced-Course
/3. Multidimensional Lists/3.1 Lab/Problem 4- Symbol in Matrix.py
611
3.984375
4
# def get_input_as_list_in_int(separator=" "): # return list(map(int, input().split(separator))) def find_symbol_in_matrix(matrix_, size_, symbol_): for row in range(size_): for column in range(size_): element = matrix_[row][column] if element == symbol_: ...
0445b2d1dc7c3fcdfb2a5eedb9826adf1a34b412
asen-krasimirov/Python-Advanced-Course
/2. Tuples and Sets/2.1 Lab/Problem 5- SoftUni Party.py
431
3.671875
4
number_of_guests = int(input()) invited_guests = set() for _ in range(number_of_guests): name = input() invited_guests.add(name) guests_that_came = set() while True: name = input() if name == "END": break guests_that_came.add(name) guests_that_did_not_came = invited_guests...
02fc6e716ebaccf5a932ff18884a79451e7eb1c8
asen-krasimirov/Python-Advanced-Course
/1. Lists as Stacks and Queues/1.1. Exercises/Problem 6- Balanced Parentheses 2.py
602
3.671875
4
from collections import deque sequence = deque(list(input())) fail_flag = False if len(sequence) % 2 != 0: fail_flag = True while sequence and not fail_flag: current_bracket = sequence.popleft() next_bracket = sequence.pop() if current_bracket == '(' and next_bracket == ')': ...
2d771ad4c572f4b08b9ef60d5d7c901df24e82d5
asen-krasimirov/Python-Advanced-Course
/1. Lists as Stacks and Queues/1.1. Exercises/Problem- Taxi Express.py
710
3.859375
4
from collections import deque customers = deque(list(map(int, input().split(", ")))) drive = input().split(", ") drivers = deque(list(map(int, drive[::-1]))) total_time = 0 while customers and drivers: customer = customers.popleft() driver = drivers.popleft() if driver >= customer: ...
89b99e4eb04aa879244d934f43af01c8caa2db46
asen-krasimirov/Python-Advanced-Course
/Exam-Exercises/Python Advanced Exam - 27 June 2020/Problem 2- Snake.py
2,385
3.546875
4
class GameLogic: __possible_moves = { "up": (-1, 0), "down": (1, 0), "left": (0, -1), "right": (0, 1), } def __init__(self, territory): self.territory = territory self.territory_size = len(territory) self.snake_position = self.find_element("S") ...
c629410961abac7f096b2022d9e6725356a91fc2
jantonisito/Daniel-Arbuckles-Mastering-Python
/Chapter01/example_1_2_2_with_main.py
263
3.71875
4
import math def main(): print(example_function('Alice',7)) print(example_function('Bob', 5)) def example_function(name, radius): area = math.pi * radius ** 2 return "The area of {} is {}".format(name, area) if __name__ == '__main__': main()
7dc680094d33f5f071e6325038e5185d67792a5f
emimuniz/URIONLINEJUGDLE
/1018 - Cédulas.py
1,172
3.78125
4
#Leia um valor inteiro. A seguir, calcule o menor número de notas possíveis (cédulas) no qual o valor pode ser decomposto. #As notas consideradas são de 100, 50, 20, 10, 5, 2 e 1. A seguir mostre o valor lido e a relação de notas necessárias. valor = int(input('')) val = valor cem = cinquenta = vinte = dez = cinco = do...
b12a456322a8fa9063ac2d2bda209c2b579ceb0b
emimuniz/URIONLINEJUGDLE
/1051 - Imposto de Renda.py
526
3.765625
4
salario = float(input('')) if salario <= 2000.00: print('Isento') elif 2000.01 < salario <= 3000: t = (salario - 2000) tx = (t * 8) / 100 print("R$ %.2f" % tx) elif 3000.01 < salario <= 4500: t = (salario - 2000) t1 = t - 1000 tx1 = (1000 * 8) / 100 tx2 = (t1 * 18) / 100 print("R$ %....
6e0da55d79941b5c5346e974de8dbf1a964951d9
cihangiroksuz/python
/Koşullu Durumlar/mükemmelsayıbulma_2.py
386
3.71875
4
x=int(input("Lütfen sayı giriniz:")) b=1 c=int() toplam=int() while 1: b=b+1 if b<=x: if x%b==0: c=x/b print(c) toplam=toplam+c else: break print("Toplam:{}" .format(toplam)) if toplam==x: print("Girilen sayı MÜKEMMEL SAYI'dır.") else...
e39b60eb97dcccc582853714ff3370ad4cac1fdc
cihangiroksuz/python
/fonksiyonlar/ekok,.py
900
3.828125
4
def ekok(x, y): ekok1 = 1 ekok2 = 1 ekok3 = 1 i = 2 while 1: if x % i == 0 and y % i != 0: x = x / i ekok1 = ekok1 * i elif y % i == 0 and x % i != 0: y = y / i ekok2 = ekok2 * i elif x % i == 0 and y % i == 0: ...
1569b35a0e54cd3a8c65961822601ad613536628
cihangiroksuz/python
/Koşullu Durumlar/kullanıcı_girisi.py
338
3.671875
4
print("Lütfen kullanıcı adı ve şifrenizi giriniz\n") kullaniciadi=str(input("Kullanıcı Adı:")) parola=str(input("Parola:")) if kullaniciadi == 'boztepeghetto' and parola == 'ghettokemal61': print("Giriş onaylandı.") else: print("Kullanıcı adı ya da parolayı yanlış giridniz. Lütfen tekrar deneyiniz.") ...
5f72be073a858b4421bbc997bc021b0d97aeeb72
sreeramvasu/Coursera_Python
/Pong.py
4,948
3.984375
4
# Implementation of classic arcade game Pong # Author: SV # Mailto: sreeram.vasudevan@gmail.com import simplegui import random # initialize globals - pos and vel encode vertical info for paddles WIDTH = 600 HEIGHT = 400 BALL_RADIUS = 20 PAD_WIDTH = 8 PAD_HEIGHT = 80 LEFT = False RIGHT = True # initialize ball...
e32e692b073d079bb59aa2ed83460f8f3ff8802d
mukeshmithrakumar/PythonUtils
/PythonMasterclass/Exercise2.py
1,362
4.5625
5
""" Create a program that takes an IP address entered at the keyboard and prints out the number of segments it contains, and the length of each segment. An IP address consists of 4 numbers, separated from each other with a full stop. But your program should just count however many are entered Examples of the input you...
7016534bdc605ab2cea27bfb6916c440c52ad441
leahabiol/conditionals
/conditionals.py
1,653
4.09375
4
# if "Sammie" > "Leah": # print "My name is greater!" # elif "Leah" > "Sammie": # print "Their name is greater." # else: # print "Our names are equal!" # date = 19 # if date > 15: # print "Oh, we're halfway there!" # else: # print "The month is still young." # today = "Thursday" # if today == "Mon...
4dae827b1f8b2e14be39ceff7a8dc3926051de17
jpz/puzzles
/listener-4425/foursquares.py
2,062
3.96875
4
#!/usr/bin/env python3 ################################## # PUBLIC INTERFACE ################################## # This file implements a dictionary of the sum of square solutions for n, where # n = a^2 + b^2 + c^2 + d^2, and a to d are rangebound from [0..25], and a >= b >= c >= d # A solution is determined accordin...
913657a4a9e4cd57ed5d46802060bb3661732448
tsigemit/Python_Script
/week2/practice.py
523
3.8125
4
whole_deck = "abcdefg" my_card = "h" print('Looking for card', my_card,'among', whole_deck) top = len(whole_deck) bottom = 0 while bottom < top: print('bottom =', bottom, 'top =', top, '- remaining cards', whole_deck[bottom:top]) middle = (top+bottom)//2 if whole_deck[middle] == my_card: ...
b01c601a91f9d5f9489e2633cd2faa2d1a5bc2ab
risg99/Data-Science
/Corona/visualisation.py
6,215
3.8125
4
#!/usr/bin/env python # coding: utf-8 # We are just going to visualize the dataset given in this python notebook using Choropleth Maps. # # # A choropleth map is a type of thematic map where areas or regions are shaded in proportion to a given data variable. # Static choropleth maps are most useful when you want to...
a05db85fa702bd7b4c723c111aad94243a0c1b1e
Ares-debugger/Frontend-01-Template
/week02/三种递归二叉树遍历.py
1,081
3.515625
4
class Solution(object): def preorderTraversal(self, root): """ :type root: TreeNode :rtype: List[int] """ res = [] def helper(root): if root: res.append(root.val) helper(root.left) helper(root.right) ...
0512db35031316c393b4571c8dca11b0a411b22a
kramin343/test_2
/first.py
428
4.28125
4
largest = None smallest = None while True: num1 = input("Enter a number: ") try: num = float(num1) except: print('Invalid input') continue if num == "done" : break if largest == none: largest = num smallest = num if largest < num: largest ...
ebdd809c06fe5aa9bef2639eba594c976357c5b8
JeffACate/LearnPythonProject
/Code/AverageConfidence.py
400
3.53125
4
tot = 0 count = 0 fname = input("Enter file name: ") fh = open(fname) for line in fh: if not line.startswith("X-DSPAM-Confidence:") : continue else: line = line.strip() start = line.find('0') end = len(line) section = line[start:end] num = float(section) tot = num...
5bee6ade1e7340c4fc502c4cc2cad724c40342be
maharshmellow/patelib
/patelib/adt/boundedQueue.py
1,637
3.796875
4
class BoundedQueue: """Queue with a capacity""" def __init__(self, capacity): self.__items = [] self.__capacity = capacity try: if (int(capacity) >= 0): pass else: raise except: raise def enqueue(self, item)...
56ba1be71e3cc80e4844ed48172d8b54ad112808
maharshmellow/patelib
/patelib/adt/queue.py
786
3.5
4
class Queue: """ADT - First in First Out""" def __init__(self): self.__items = [] def queue(self, item): self.__items.append(item) def dequeue(self): if len(self.__items) > 0: removedItem = self.__items[0] self.__items.remove(removedItem) ret...
0ca502687d92d2e25228cf70a6cc1fe8499ae045
victormaiam/python_studies
/conditions.py
1,111
4.15625
4
is_hot = False is_cold = False if is_hot: print("It`s a hot day.") print ("Drink plenty of water.") elif is_cold: print("It`s a cold day.") print("Wear warm clothes.") else: print("It`s a lovely day.") print("Enjoy your day.") tem_credito = False preco = 1000000 preco1 = preco * 0.10 preco2 ...
3e7950446a092a65ef871c98e64e9820a6e637a5
victormaiam/python_studies
/exercise1_4.py
399
4.3125
4
'''' Write a function that returns the sum of multiples of 3 and 5 between 0 and limit (parameter). For example, if limit is 20, it should return the sum of 3, 5, 6, 9, 10, 12, 15, 18, 20. ''' def calcula_soma(limite): soma = 0 for i in range(0, limite + 1): if i%3 == 0 or i%5 == 0: soma =...
b6e5336a9730937696b15554609ee1334bdc6203
junglefire/introduction_to_ml_with_python
/chap04/dummy_variables.py
1,573
3.671875
4
import pandas as pd from sklearn.linear_model import LogisticRegression from sklearn.model_selection import train_test_split # 导入mglearn模块 import sys sys.path.append("../") import mglearn # The file has no headers naming the columns, so we pass header=None # and provide the column names explicitly in "names" data ...
2b7f8be7b350e53a298987a6f562b76fd04e9216
hoo00nn/Algorithm
/Programmers_Lv2/Hash-위장(Level2).py
377
3.5625
4
def solution(clothes): answer = 1 test = {} for i in dict(clothes).values(): if i in test.keys(): test[i] += 1 else: test[i] = 1 for i in test.keys(): test[i] += 1 answer *= test[i] return answer-1 solution([["yellow_hat", "headgear"], ["blue...
6e815f5e411a15b3ad1ea382adbedae06072ffd5
hoo00nn/Algorithm
/Programmers_Lv2/Sort-K번째 수(Level1).py
353
3.515625
4
def solution(array, commands): answer = [] for i in range(0, len(commands)): start = commands[i][0] - 1 end = commands[i][1] num = commands[i][2] - 1 isSorted = sorted(array[start:end]) answer.append(isSorted[num]) return answer solution([1, 5, 2, 6, 3, 7, 4], [...
10b58c2923c3a3a2508bd44ae011a64301c61e92
hoo00nn/Algorithm
/Programmers_Lv2/Level2-폰켓몬.py
792
3.59375
4
# 첫 번째 시도 정확성 30.0 나머지 시간초과.. from itertools import combinations def solution(nums): answer = list(map(lambda x: len(set(x)), combinations(nums, len(nums) // 2))) return max(answer) # 두 번째 시도 정확성 80.0 나머지 시간초과.. from itertools import combinations def solution(nums): if len(nums) // 2 >= len(set(nums...
57d3c5593f11f34bebb752bad652fa60ac9b5aee
hoo00nn/Algorithm
/Programmers_Lv1/Level1-시저 암호.py
519
3.703125
4
# 문자를 ASCII 코드로 변환하는 함수 ord() 함수 # ASCII 코드를 문자로 변환하는 함수 chr() 함수 def solution(s, n): answer = '' ALPHA = 26 ALPHA_LOWER = 97 ALPHA_UPPER = 65 for i in s: if i == ' ': answer += ' ' else: if i.isupper(): answer += chr(ALPHA_UPPER + (ord(i) +...
ae2d1018c63e42d3cf8ebc036f6777fbbc588f1e
hoo00nn/Algorithm
/알고리즘 구현/DFS와 BFS/깊이 우선 탐색.py
414
3.53125
4
def dfs(graph, root): visited = [] stack = [root] while stack: n = stack.pop() if n not in visited: visited.append(n) stack += set(graph[n]) - set(visited) print(n) return visited graph_list = {1: [2, 3, 4], 2: [1, 4], 3:...
68bd2c0f2ef93783095770f31b5b47ac42dacd8a
ASh1ne/myownrepo
/exercise6.py
436
3.984375
4
dayCount = 0 print("Введите начальную дистанцию") defaultDistance = int(input()) print("Введите необходимый результат") upgradeDistance = int(input()) while defaultDistance <= upgradeDistance: defaultDistance = defaultDistance + (defaultDistance*0.1) dayCount += 1 print(f"Спортсмен достиг результата {defaultD...
83ca590d681b8cc8b76146d7a4fdd539c880b4e1
pythonRepo4/SEC-Scrape
/SQL/SQLMethods.py
1,882
3.5
4
from SQL import sqlite as sql """----------------------------------------------------------------------------------- Returns earnings data from EarningsData.db -----------------------------------------------------------------------------------""" def getDebtData(tickerName, year): try: tableName = ticke...
f8585415e04f4b7d84726d0888d82bdcf009de67
LimbOfTree/LegisQuest
/BookHomework/Vehicles.py
406
3.78125
4
class vehicle: def __init__(self): raise NotImplementedError('Don\'t just make a vehicle, make a specific type of vehicle.') def __str__(self): return "{}".format(self.name) class motorcycle(vehicle): def __init__(self): self.name = 'Motorcycle' self.wheels = 4 class c...
0e2fa11b94b12602692645663ecdcd57317e79a4
leomatheuss/aulapy
/LISTA3/tuplas.py
316
3.78125
4
""" Tuplas são bastante parecidas com listas Existem duas diferenças básicas: Sua representação é por parenteses () Tuplas são IMUTÁVEIS. Toda operação em uma tupla, gera uma nova tupla """ # É possível gerar uma tupla dinamicamente com range(inicio, fim, passo) tupla = tuple(range(1,6,2))
f7d81f1ed243a05e02f725f081cfa3dd37605d70
leomatheuss/aulapy
/LISTA2/lista2sec5e3.py
264
3.765625
4
#notas válidas nota1 = float(input()) nota2 = float(input()) if ((0.0 < nota1 < 10.0) and (0.0 < nota2 < 10.0)) == True: media = (nota1 + nota2 )/ 2 print(f'A média das duas notas é {media}') else: print("Uma, ou as duas notas estão inválidas")
d7d60620c5192189c1dbfb89a006a7f607945617
leomatheuss/aulapy
/LISTA 1/atividade3.py
152
3.78125
4
idade = int(input()) ano_atual = int(input('Entre com o ano atual')) ano_nasc = ano_atual - idade print(f"O ano de nascimento da pessoa é: {ano_nasc}")
6bb25ae3b0ce05f16ecd3f34cfdcd997ab1c1805
leomatheuss/aulapy
/URI_atividades/1168.py
176
3.828125
4
leds = (6,2,5,5,4,5,6,4,7,6) n = int(input()) for i in range(n): num = input() soma = 0 for j in num: soma = soma + leds[int(j)] print(soma, "leds")
2c7b33bf5b87afc2ebe5379d3705b7b30576831b
leomatheuss/aulapy
/URI_atividades/1120.py
269
3.609375
4
while True: x, y = map(int,input().split()) if x == 0 and y == 0: break else: x = str(x) y = str(y) b = y.replace(x, '') if b == '': print(0) else: y = int(b) print(y)
963c397a588e8db33c06323cd90e225051eb77b8
leomatheuss/aulapy
/URI_atividades/mdcteste.py
171
3.609375
4
def mdc(x,y): mdc1 = x while x % mdc1 != 0 or y % mdc1 != 0: mdc1 = mdc1 - 1 return print(mdc1) f1 = int(input()) f2 = int(input()) mdc(f1, f2)
3c057937f265a653fde61863d1d4ed3088a3e73d
leomatheuss/aulapy
/URI_atividades/1065.py
183
3.640625
4
nums = [] for i in range(1,6): nums.append(int(input())) cont = 0 for j in nums: if j % 2 == 0: cont = cont + 1 else: pass print(cont,"valores pares")
9508618304d962e676556eb7b1a78a818bdd3dae
leomatheuss/aulapy
/URI_atividades/1132_func.py
315
4.0625
4
def verifica(x, y): ''' Função que vai verificar se o número é divisível por 13 ''' teste = 0 for i in range(x, y+1): if i % 13 != 0: teste = teste + i print(teste) a = int(input()) b = int(input()) if a < b: verifica(a, b) elif a > b: verifica(b, a)
9a95ff5dd167c9ecae9fc8392620899db10719f5
MysticAhuacatl/PHY494
/assignments-2019-MysticAhuacatl/assignment_04/Submission/problem1.py
708
3.5625
4
# Problem 4. s = """'But I don't want to go among mad people,' Alice remarked. 'Oh, you can't help that,' said the Cat, 'we're all mad here. I'm mad. You're mad.' 'How do you know I'm mad?' said Alice. 'You must be,' said the Cat, 'or you wouldn't have come here.'""" counts = [0,0,0,0,0,0] def count_vowels(words): ...
9f8362f2099487f776356be66e3d34aecfedc32b
MysticAhuacatl/PHY494
/assignments-2019-MysticAhuacatl/assignment_02/Solution/addtemperatures.py
223
3.78125
4
# HW02 2.2 T_K = float(input("Temperature in Kelvin --> ")) theta_F = float(input("Temperature difference in Fahrenheit --> ")) delta_T_K = 5/9 * theta_F T_total = T_K + delta_T_K print("Total T " + str(T_total) + " K")
1e81046ef18617b2f1d1a7f5f105fe619dafb6c7
oneelay/Intro_Biocomp_ND_318_Tutorial5
/Exercise5_new.py
1,374
3.765625
4
#Exercise 5 Om and Joshua import os import numpy import pandas #Set working directory and read in wages file os.chdir('C:\\Users\\joshu\\OneDrive\\github\\BioComp\\Intro_Biocomp_ND_318_Tutorial5\\') wages=pandas.read_csv("wages.csv") #START OF CHALLENGE 1 #isolate 2 columns: Gender and YearsExperience first2column...
56cf27d686c64d1fba048058e0e211acf7a4a638
IlyaShushlebin/lab7
/testSwitchNewTab.py
1,422
3.5625
4
import time import math # webdriver это и есть набор команд для управления браузером from selenium import webdriver # инициализируем драйвер браузера. После этой команды вы должны увидеть новое открытое окно браузера driver = webdriver.Chrome("C:/chromedriver/chromedriver.exe") # Метод get сообщает браузеру, что нуж...
36ee5944630dd54e5fa5c80b26a02085c03d6706
Faraz-Nasir/Jumble-Words-tkinter
/sqlite.py
16,011
3.625
4
import sqlite3 import pandas as pd #connect to database conn=sqlite3.connect('Jumbled_Words.db') c=conn.cursor() ''' c.execute(""" CREATE TABLE words( ID INTEGER PRIMARY KEY AUTOINCREMENT, Word TEXT ) """)''' def add(word_list,number_of_words_in_the_list): ...
e2d162869509023697e5231bdf2d5b214ced5f26
rmesseguer/number_game
/number_game.py
1,430
4.09375
4
import random robot_score = 0 player_score = 0 while True: num = random.randint(1,10) good_guess = False while not good_guess: try: guess = int(input('Guess a number between 1 and 10: ')) if guess < 1 or guess > 10: ra...
28d5915b71c0f0ce0266c6169d724582b0d3963c
ranju117/cegtask
/7.py
286
4.21875
4
#tuple tuple1 = ('python', 'ruby','c','java') list1 = ['python','ruby','c','java'] print tuple1 print list1 # Let's include windows in the list and it works! list1[1] = "windows" list1[2]="Python" print list1 # Windows does not work here! tuple1[1] = "windows" print tuple1
897aeeae7843d653f2c422df5c0bcd5367076eb2
admk/nabp
/pynabp/conf/validator/constraints.py
4,691
3.53125
4
from base import Validator, ValidateError # use a dummy lambda to get the function type func = type(lambda _: 0) # constraint functions natural = lambda val: val >= 0 positive = lambda val: val > 0 negative = lambda val: val < 0 odd = lambda val: val % 2 == 1 even = lambda val: val % 2 == 0 def boundaries( ...
2293c26f5ae1fdf5417ce4033829cc36c80cff00
furkanaygur/Codewars-Examples
/RemoveTheParantheses.py
754
4.4375
4
''' Remove the parentheses In this kata you are given a string for example: "example(unwanted thing)example" Your task is to remove everything inside the parentheses as well as the parentheses themselves. The example above would return: "exampleexample" Notes Other than parentheses only letters and spaces...
d7eb20ba3f3a7b3b858265fb5dc87aea3939d909
furkanaygur/Codewars-Examples
/MatrixAddition.py
1,056
4.15625
4
''' Write a function that accepts two square matrices (N x N two dimensional arrays), and return the sum of the two. Both matrices being passed into the function will be of size N x N (square), containing only integers. How to sum two matrices: Take each cell [n][m] from the first matrix, and add it with the sam...
68ef323d3c407c857ff33a26bc91847a4af5356f
furkanaygur/Codewars-Examples
/ParseStringReloaded.py
1,991
3.953125
4
''' Description: Input Range is 0-999 There may be duplicates The array may be empty Example Input: 1, 2, 3, 4 Equivalent names: "one", "two", "three", "four" Sorted by name: "four", "one", "three", "two" Output: 4, 1, 3, 2 Notes Don't pack words together: e.g. 99 may be "ninety nine" or "ninety-ni...
a8477323029366675ff8de5169e40fbc701ffe0a
furkanaygur/Codewars-Examples
/SplitStrings.py
844
4.28125
4
''' Complete the solution so that it splits the string into pairs of two characters. If the string contains an odd number of characters then it should replace the missing second character of the final pair with an underscore ('_'). Examples: solution('abc') # should return ['ab', 'c_'] solution('abcdef') # shou...
8093fd80925a5c7fd809bdb195ab6f8ac552fbd6
furkanaygur/Codewars-Examples
/DecipherThis.py
945
4.03125
4
''' You are given a secret message you need to decipher. Here are the things you need to know to decipher it: For each word: the second and the last letter is switched (e.g. Hello becomes Holle) the first letter is replaced by its character code (e.g. H becomes 72) Note: there are no special characters used, o...
ad213ac20a71fb84dfa39d4ad5375110c6f6281b
furkanaygur/Codewars-Examples
/Snail.py
2,004
4.3125
4
''' Snail Sort Given an n x n array, return the array elements arranged from outermost elements to the middle element, traveling clockwise. array = [[1,2,3], [4,5,6], [7,8,9]] snail(array) #=> [1,2,3,6,9,8,7,4,5] For better understanding, please follow the numbers of the next array consecutiv...
6879db3b8aabbae7dcc46f3c4d3be47bafa9c3e0
shivangi-ml/projects
/Recurrent_Neural_Networks/google_stock_price.py
2,787
3.515625
4
# -*- coding: utf-8 -*- """ Created on Sat Nov 23 20:29:56 2019 @author: spriyadarshini """ # import libs import pandas as pd import numpy as np import matplotlib.pyplot as plt #import dataset dataset_train = pd.read_csv('Google_Stock_Price_Train.csv') training_set = dataset_train.iloc[:,[1]].values # scaling is a m...
1c528e653a6fb181308c0eda02a65b1f518fa03d
901david/algorithms
/python/merge-sorted-arrays.py
681
3.90625
4
arr1 = [1, 2, 5, 8, 9] arr2 = [5, 8, 9, 23] def iterative_array_merger(arr1, arr2): merged = [] while len(arr1) and len(arr2): if arr1[0] < arr2[0]: merged.append(arr1.pop(0)) else: merged.append(arr2.pop(0)) return [*merged, *arr1, *arr2] #print(iterative_array_...
e33e9e635201dc2ba729ef957ec92c0f7480e5d7
ndhansen/programming-challenges
/02_BMI_calculator/calculator.py
159
4
4
weight = float(input("What is your weight (kg)? ")) height = float(input("What is your height (m)? ")) print("Your BMI is", round(weight / (height ** 2), 1))
285f86a89e23cecb1a4b0d062d87735624040b4b
scipianne/OLS
/calculations.py
5,107
3.578125
4
# coding: utf-8 import math class Matrix(list): """ Список, который считает себя квадратной матрицей с шириной int(sqrt(len - 1)) + 1 """ def __len__(self): # переопределяем функцию len как ширину матрицы length = super(Matrix, self).__len__() if length: width = int(m...
fbed9de940cb5f58be578eae698ad6d85bdeff42
jmockbee/strings
/example1.py
229
3.890625
4
def double_word(word): word = word * 2 return word + str(len(word)) print(double_word("hello")) # Should return hellohello10 print(double_word("abc")) # Should return abcabc6 print(double_word("")) # Should return 0
b24d011cf6257002c11e2f76a0a54961151641e7
AlamgirHassan5002/Word-Split-Python
/index.py
1,615
3.609375
4
def WordSplit(strArr): size=len(strArr) word=strArr[0] pattern=strArr[1] words1=[] words2=[] patternlist=pattern.split(",") length=0 for i in range(0,len(word)-1): for j in range(0,len(patternlist)): pattern1=patternlist[j] length=0 ...
63cf1c0ac7e3880b7217de8c4fe78bc6e2a9f6dd
ustczhhao/Simulation-of-Gibson-et-al-Paper
/2.1. Gibson First Reaction Method_OOP.py
8,588
3.90625
4
import numpy as np from numpy import random import matplotlib.pyplot as plt %matplotlib inline class ChemicalSpecies(object): '''define the class of chemical species''' def __init__(self, name, count): self.name=name self.count=count class Reaction(object...
41965f24584a736144f5fa0bdd7814a21a44cc61
Melwyna/LaboratorioColecciones
/custom_functions/temperature_methods.py
4,137
3.6875
4
#Promedio de cada depatamento def suma(a): sum=0 for item in a: sum=sum+item prome=sum/len(a) return prome #Promedio nacional y temperatura promedio de los meses más calientes de los 3 departamentos def suma2(a): sum=0 for item in a: sum=sum+item return sum def promedion2(a,b,c): ter2=(a+b+c)/36 return...
4e5453723e9224120e84b3f6713af9aa84c647a6
FA0AE/Mision-03
/Boletos.py
1,510
4.15625
4
# Autor: Francisco Ariel Arenas Enciso # Actividad : Cálculo del total a pagar de boletos dependiendo de su clase ''' Función que recibe los datos de entrada de la función main (número de boletos) como parametros, los alamcena en variables y realiza las operaciones artimeticas necesarias para devolver datos de sa...
0d644ab18e56d13805766663cc0fb4bf7fd20840
reeha-parkar/python
/dunder_magic_methods.py
1,006
4.15625
4
import inspect '''x = [1, 2, 3] y = [4, 5] print(type(x)) # Output: <class 'list'> # Whatever we make it print, it follows a certain pattern # Which means that there is some class related method that works uunder the hood to give a certain output ''' # Let's make our own data type: class Person: def __init__(self...
bdee03756772c0848b3a27bf3c309e3523205975
reeha-parkar/python
/classmethod_and_staticmethod.py
1,109
4.1875
4
# class methods and static method: # class method is a method in the class whcih takes te class name as a parameter, requires class instances # static method is a method which can be directly called without creating an instance of the class class Dog: dogs = [] def __init__(self, name): self.name = nam...