blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
3510fc6dbf6866155e891b8ea84cf7eb481458dc
youngdukk/python_stack
/python_activities/forLoop_basic2.py
3,590
4.8125
5
Biggie Size - Given an array, write a function that changes all positive numbers in the array to "big". Example: makeItBig([-1, 3, 5, -5]) returns that same array, changed to [-1, "big", "big", -5]. def makeItBig(arr): for i in range(0, len(arr)): if arr[i] > 0: arr[i] = "big" return ar...
c910dcd52762954ca55c4322848805e481a2d68c
YusufLiu/LevenshteinDistance
/LevenshteinDistance.py
1,226
3.609375
4
from __future__ import print_function import argparse import math import random class Levenshtein: def minimun(i1, i2 ,i3): return min(min(i1,i2),i3) def distance(s1, s2): if s1 == s2: return 0 # Prepare a matrix s1len, s2len = len(s1), len(s2) dist = [[0 for ...
7cf4328271a9250915b5329c3be1a6aba9825816
bernardli/leetcode
/JZoffer/59_2.py
845
3.953125
4
class MaxQueue: def __init__(self): self.maxValues = [] self.queue = [] def max_value(self) -> int: if len(self.queue) == 0: return -1 return self.maxValues[0] def push_back(self, value: int) -> None: self.queue.append(value) while len(self.maxV...
4643b147ba1fe912c9ce804c33804f4ddcd4cf19
LaplaceKorea/DC-CC2
/divide.py
3,883
3.71875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon May 1 11:59:34 2017 Divide a graph into connected subgraphs @author: laci """ import math import collections import graph as g from typing import List, Tuple def _next_group(remained, chunksize, bg:g.Graph) -> List[int]: """Calculate a group of...
ade93d86b508a1944ccf7ce0b268fe255e4250fc
twitu/projecteuler
/euler56.py
617
3.640625
4
'''A googol (10100) is a massive number: one followed by one-hundred zeros; 100100 is almost unimaginably large: one followed by two-hundred zeros. Despite their size, the sum of the digits in each number is only 1. Considering natural numbers of the form, ab, where a, b < 100, what is the maximum digital sum?''' ...
45c0ba07461ea0de318e9220a372864fa7f75aee
acarter881/Python-Workout-50-Exercises
/45.py
2,090
3.75
4
#! python3 class Animal(): def __init__(self, color, number_of_legs): self.species = self.__class__.__name__ self.color = color self.number_of_legs = number_of_legs def __repr__(self): return f'{self.color} {str(self.species).lower()}, {self.number_of_legs} legs' class Sheep(A...
f0bc2a6428da5bcc92df54444a373d07b2e1ee90
luozhiping/leetcode
/2018tencent50/easy/reverse_integer.py
597
3.71875
4
# 反转整数 # https://leetcode-cn.com/problems/reverse-integer/ class Solution: def reverse(self, x): """ :type x: int :rtype: int """ result = 0 negative = x < 0 if negative: x = -x while x > 0: result = result * 10 + x % 10 ...
29b89e602382b540e94a5087766f9f74a7f246e2
shishir-kr92/HackerRank
/Algorithm/problem_solving/Between_Two_Sets.py
1,043
3.75
4
def get_GCD(x, y): res = 0 while x != 0: res = y%x y = x x = res return y def get_LCM(x, y): return int((x*y)/get_GCD(x, y)) def getTotalX(a, b): count = 0 resultant_LCM = 0 resultant_GCD = 0 for i in range(len(a)): if i == 0: resultant_LCM...
73eaaf9ef4d09c3f56269b59d9a60f606d9ac3f2
royan2024/Algorithm_Practice
/Sorting/BinarySort.py
300
3.8125
4
from Sorting.BinarySearch import binary_search def binary_sort(l: list) -> list: sorted_list = [] for v in l: idx = binary_search(sorted_list, v) sorted_list.insert(idx, v) return sorted_list if __name__ == "__main__": l = [4, 5, 8, 9, 1] print(binary_sort(l))
86155359e5b7b40a4b9c5e44c059a62ed2a98383
RiyazShaikAuxo/datascience_store
/PyhonProgramming/numsorting.py
295
3.890625
4
numbers=[1,4,5,7,8,1,2,19,9,0,12,3] sort1=sorted(numbers) print(sort1) #descending sort2=sorted(numbers,reverse=True) print(sort2) letters=['A','C','T','Y','L','Z','E'] sort3=sorted(letters) print(sort3) letters1=['A','C','T','Y','L','Z','E'] sort4=sorted(letters1,reverse=True) print(sort4)
fda225e8130cb9d33006ecf3136becacb2093634
sv85jt/PythonExample
/loops/whileEx.py
341
3.65625
4
def start(): print ("----- START -----") def end(): print ("----- END -----") start() animals = ['dog','cat','horse','cow'] count = 0 animals.append('goat') #animals.clear() while count < len(animals): print ('Current animals is {}'.format(animals[count].upper())) count += 1 end () print ("-------...
0970c6a49b3822f8c899604f9291b53bf85ede55
eloghin/Python-courses
/HackerRank/Athlete-sort-nested-list.py
850
3.90625
4
import math import os import random import re import sys if __name__ == '__main__': nm = input().split() n = int(nm[0]) m = int(nm[1]) arr = [] for _ in range(n): arr.append(list(map(int, input().rstrip().split()))) k = int(input()) arr.sort(key=lambda x: x[k]) ...
fdb7628d54510e86d311f6cba5e020063034be4b
rafhaeldeandrade/learning-python
/2 - Variáveis e tipos de dados em Python/Exercicios/ex32.py
325
3.84375
4
""" 32. Leia um número inteiro e imprima a soma do sucessor de seu triplo com o antecessor de seu dobro. """ numero_inteiro = int(input('Digite um número inteiro: ')) resultado = ((numero_inteiro * 3) + 1) + ((numero_inteiro * 2) - 1) print(f'A soma do sucessor de seu triplo com o antecessor de seu dobro é {resultado}'...
85b11603a23f7df1dc98f34a2d35e15fb2da11e8
afzal-xyz/GTEdx_6040
/Midterm 1/problem1.py
10,884
3.921875
4
# coding: utf-8 # # Problem 1: Who's the fastest of 'em all!? # # This problem will test your mastery of basic Python data structures. It consists of five (5) exercises, numbered 0 through 4, worth a total of ten (10) points. # For this problem, you will be dealing with Formula1 race results of a particular year. T...
13896ecb4ce975e3f49891857cdcf8203460603a
asmallbit/python
/chapter07_user_imput_and_while_loops/pizza.py
227
4.0625
4
prompt="What do you need to add in your pizza" prompt+="\nInput 'quit' to end the program\n" message="" while message != 'quit': message=input(prompt) if message != "quit": print("We will add "+message+" in your pizza.\n")
c4fad664fdc1b59b01aff6357464676428ccbca0
pharnb/Python-PyBank-PyPoll
/pypoll/main.py
2,615
4.125
4
#* In this challenge, you are tasked with helping a small, rural town modernize its vote counting process. #* You will be give a set of poll data called [election_data.csv](PyPoll/Resources/election_data.csv). # The dataset is composed of three columns: `Voter ID`, `County`, and `Candidate`. Your task is to create #...
fdd88ac43cd14c21c4ee0c78a8625aea38e6d274
jianyu-m/plato
/plato/algorithms/base.py
836
3.9375
4
""" Base class for algorithms. """ from abc import ABC, abstractmethod from plato.trainers.base import Trainer class Algorithm(ABC): """Base class for all the algorithms.""" def __init__(self, trainer: Trainer, client_id=None): """Initializing the algorithm with the provided model and trainer. ...
286396e606464f35516d7cdc96207e109f069bbe
Immaannn2222/holbertonschool-higher_level_programming
/0x07-python-test_driven_development/0-add_integer.py
348
4.21875
4
#!/usr/bin/python3 """ the add module""" def add_integer(a, b=98): """ adds two integers a and b""" if not (isinstance(a, int) or isinstance(a, float)): raise TypeError("a must be an integer") if not (isinstance(b, int) or isinstance(b, float)): raise TypeError("b must be an integer") ...
725acc81315e8fb43ec4ebf5b569b044f7e4bf4d
Programwithurwashi/calculator
/calculator.py
886
4.1875
4
def addition(first,second): return first+second def Substraction(first,second): return first-second def Multiplication(first,second): return first*second def division(first,second): return first/second print('''Enter the operation to be performed: 1> Addition 2> Subtraction ...
7c0f1c70d56aef28cd8e5f22fe1b8e5587e028d6
paceko/intro_hackbright
/conditionals.py
1,078
4.375
4
#my_name = "Jessica" #partners_name = "Kelsey" #if (my_name > partners_name): # print "My name is greater!" #elif (partners_name > my_name): # print "Their name is greater." #else: # print "Our names are equal!" #todays_date = float(raw_input("What is the day of the month?")) #if (todays_date >= 15.0): # print "Oh, we...
1967b60dc30a3b3c7c604efae66a4a437bd48bb6
veekaybee/dailyprogrammer
/atbash.py
531
4.03125
4
''' Reddit Daily Programming Challenge 254 Atbash Cypher http://bit.ly/1PIHXb0 ''' alphabet = 'abcdefghijklmnopqrstuvwxyz' atbash = alphabet[::-1] mydict = dict(zip(alphabet, atbash)) def atbash_gen(mydict, word): reverse = [] for i in word: if i not in alphabet: reverse.append(i) else: for key, va...
85f7b6d834171538c8b5eb91a474180e1ee933ad
Jonathan-aguilar/DAS_Sistemas
/Ago-Dic-2018/Claudia Seca/Práctica 2/Login_attempts.py
946
3.75
4
class User(): def __init__(self, first_name, last_name, email, birthday, mascota_favorita, login_attempts=0): self.first_name = first_name self.last_name = last_name self.email = email self.birthday = birthday self.mascota_favorita = mascota_favorita self.login_attempts =login_attempts def increment...
beb4de42e97ffeff4ac58e066aa16d638ff9ae1d
michdol/Data-driven-testing
/Basics/sumAll.py
476
3.5625
4
file_name = 'sumAllExample.txt' def sumAll(file): f = open(file, 'r') lines = f.read() print(lines) x = '' my_list = [] for i in lines: if i.isnumeric() == True: x += i elif i.isspace() == True or i == '\n': if x == '': pass e...
90148054e0c975415d85870fcfc36e4b47728ed4
spiky1224/Python_Practice
/count_char.py
220
3.6875
4
def count_char(s): cnt_dict = {} s = s.lower() for c in s: if c in cnt_dict: cnt_dict[c] += 1 else: cnt_dict[c] = 1 return cnt_dict result = count_char("MyNameIsNobuyukiTsuboi") print(result)
29d9dd8146e1fd5215e38106d80f7d694cae9712
okorach/excel-tools
/bourso_cb.py
1,608
3.53125
4
#!python3 import sys months = {"janvier": 1, "février": 2, "mars": 3, "avril": 4, "mai": 5, "juin": 6, "juillet": 7, "août": 8, "septembre": 9, "octobre": 10, "novembre": 11, "décembre": 12} jour = r"(0?\d|[12]\d|3[01])" year = r"202\d" no_cb, nom_cb = "CB Débit différé Elodie", "CB Débit différé Elodie" step...
8a5466325a64fa45b6041d6385f26fc89ceb19ca
kanhaiya38/ppl_assignment
/1.Python/7.py
430
3.828125
4
""" 7. Find Armstrong Numbers in the given range. """ import math def is_armstrong(val): num = val n = int(math.log10(num)) + 1 sum = 0 for _ in range(n): digit = num % 10 sum += digit ** n num //= 10 if val == sum: return True else: return Fals...
128f1ac2fd93c76a5ea1707ec97546d69f26bee5
devam6316015/all-assignments
/assign 14 file handling.py
1,924
4.1875
4
print("1. write a program to read last n lines of a file") f=open("test.txt","r",encoding="utf8") content = f.readlines() f.close() n=int(input("enter")) print("last lines are :") while n > 0: print(content[-n]) n-=1 print("Q.2- Write a Python program to count the frequency of words in a file") f=open("tes...
7eb44052b4deed5dcd505076b4c0ced8d99b9d2a
fernandochimi/Intro_Python
/Exercícios/027_Distancia_Km.py
264
3.734375
4
distancia = float(input("Digite a distância em KM a ser percorrida: ")) base = distancia valor_pagar = 0 if base <= 200: valor_pagar = base * 0.50 else: valor_pagar = base * 0.45 print("Você percorreu %5.2f. Você irá pagar R$ %5.2f." % (base, valor_pagar))
be543aaf74bbfea56b02ca3e3e9d0184e299f1cd
kit023/hello-python
/geometry.py
528
4.0625
4
# Geometry import math import geometry # def area_circle (radius): # return math.pi * radius **2 # if __name__ == "__geometry__": # print("This is from geometry.py") # data = input("Enter the radius of "+ # "a circle:") # radius = float(data) # print("Area of the circle: {:.4f}" # .form...
e057a47dd74e4912ba5a2a8a8ccf63fc9be9b734
gdh756462786/Leetcode_by_python
/math/Multiply Strings.py
1,125
4.1875
4
# coding: utf-8 ''' Given two numbers represented as strings, return multiplication of the numbers as a string. Note: The numbers can be arbitrarily large and are non-negative. Converting the input string to integer is NOT allowed. You should NOT use internal library such as BigInteger. ''' class Solution(object): ...
501140c334de11e0ece8ebfc24075362827bc0a2
jzhang1223/CBA
/Calculations/ConvertDate.py
635
3.625
4
from Calculations import CalculationAPI import datetime # Converts datetime.date to and string date, and vice versa. Throws error if None or a different data type is given. class ConvertDate(CalculationAPI.CalculationAPI): def __call__(self, date): if type(date) == datetime.date: return "{}-{}...
30bdb2b30757dde3c47825516cfb2faff913d611
yulunli/COMP432
/src/h0/unbalanced_experiments.py
2,133
3.984375
4
#!/usr/bin/python -O # # A small program to simulate results from an experiment with an exponential distribution. # # - Make sure you understand the code below # - Complete the evaluation_metric method so that it returns the mean # - What do you expect the results to be? # ----- I expect the result to be somewhere betw...
84516ef4fdabbb199f70209b0474968fa637ea2a
chongliw/algorithm_py
/algorithms/tree/representation.py
1,804
3.84375
4
__author__ = 'cwang' class BinaryTree(object): def __init__(self, val): self.val = val self.left, self.right = None, None def insertLeft(self, newNode): if self.left is None: self.left = newNode else: raise RuntimeError('Cannot insert when left node exis...
1966ba17d7be155db454a382b17263a7cea7b80e
martinber/guia-sphinx
/ejemplos_sphinx/manual/pynprcalc/pynprcalc/comandos.py
1,855
3.921875
4
""" Interfaz entre los comandos de la calculadora y las funciones matemáticas. Por ejemplo, la función ``X SIN`` se corresponde a ``math.trig.sen(x)``. """ import inspect from .funciones import math from .funciones import misc comandos = { "+": math.basico.suma, "-": math.basico.resta, "*"...
3f8b28de5084c60ab97c4ad841dca6612671f3b4
standrewscollege2018/2020-year-12-python-code-sli4144
/bookstore task.py
3,187
4.21875
4
#list store all the book detail books= [["In to the wild", "Jon Krakauer", 20.3], ["Castle", "Franz Kafka", 16.5],["The three body problem", "Liu Cixin", 50.25]] # function # a loop go through the list and print out each item def show_books(): for book in range(0, len(books)): print (book+...
77ef4994fdbf4d719d031ee4029f9556b67bc605
zoomjuice/CodeCademy_Learn_Python_3
/Unit 10 - Classes/10_01_07-MethodArguments.py
959
4.21875
4
""" Methods can also take more arguments than just self: class DistanceConverter: kms_in_a_mile = 1.609 def how_many_kms(self, miles): return miles * self.kms_in_a_mile converter = DistanceConverter() kms_in_5_miles = converter.how_many_kms(5) print(kms_in_5_miles) # prints "8.045" Above we defined a Distanc...
f1982af07f07bde317db520f015110d669a49cbf
EricHuang950313/Python
/Folders/Learning/Python01/c.py
164
3.578125
4
student_name = "Eric Huang" subject, score = input("Please key in your subject and score.(e.x.Chinese, 100:):").split(", ") score = int(score) print(subject, score)
15f3593a8764e672ed6d6fb47653515685c761df
shiwanibiradar/10days_python
/day7/overlaprect.py
958
4.03125
4
#An axis-aligned rectangle is represented as a list [x1, y1, x2, y2], where (x1, y1) is the coordinate of its bottom-left corner, and (x2, y2) is the coordinate of its top-right corner. Its top and bottom edges are parallel to the X-axis, and its left and right edges are parallel to the Y-axis. #Two rectangles overlap...
36b3d6f131ccb7d1a05be3ef2c6dbf8bf88e5be2
jawang35/project-euler
/python/lib/problem21.py
1,268
3.84375
4
# coding=utf-8 ''' Problem 21 - Amicable Numbers Let d(n) be defined as the sum of proper divisors of n (numbers less than n which divide evenly into n). If d(a) = b and d(b) = a, where a ≠ b, then a and b are an amicable pair and each of a and b are called amicable numbers. For example, the proper divisors of 220 ar...
dd162cdfc074bf5dd21bfe32309d65c789f9c9d2
Marian4/Praticando-python
/Exercício funções/Questão1.py
147
3.734375
4
def imprimeAt(n): for i in range(n+1): print() for j in range(i): print (i,end=' ') n = eval(input("digite um nmero:")) imprimeAt(n)
a5f601e3eb256cc727e3f61b98d4b32a7c00d4b6
Maor2871/CodeDup
/Project/Code/Executor/exe3/MyThread.py
776
4.0625
4
import threading from abc import abstractmethod class MyThread(threading.Thread): """ This class creates threads. """ def __init__(self, thread_id, name): """ Constructor- assign each value to its corresponding attribute. """ # Call the super constructor with ...
0ef8244b5740e777ad200c2f18bb38c127f55d01
PaulieRizzo/Forced-Harmonic-Oscillator
/Solve Newtonian Numerically.py
2,896
3.78125
4
"""The three different initial conditions is the c value, changing from -0.5 -> 0.0 -> 0.5 giving us a graph of three functions. Being a damped, neutral, and driven harmonic oscillator.""" import numpy as np from scipy.integrate import odeint from matplotlib import pyplot as plt mass = 1.0 # mass constant in...
ddf4af3da4176a9929b5aee6f68c9d9dbc9e3b34
rayxiehui/OMOOC2py
/_src/om2py2w/2wex0/main2.py
459
3.671875
4
# -*- coding: UTF-8 -*- from Tkinter import * root = Tk() li = ['c','python','php','html','sql','java'] movie = ['css','jquery','bootstrap'] listb = Listbox(root) listb2 = Listbox(root) for item in li : listb.insert(0,item) for item in movie : listb2.insert(0,item) def callback(): print "click!" button ...
601a373c774fc66bf3e1ef5f322171fc72d4ef74
miky-roze/Python-exercises
/exercise_11.py
386
3.734375
4
# Function compresses the number according to this formula: (number, how_many_in_a_row) # Example: 111155003 ----> [(1, 4), (5, 2), (0, 2), (3, 1)] from itertools import groupby def compress(number): compressedNumber = list() for k, g in groupby(str(number)): compressedNumber.append((k, list(g).cou...
7591f444dcccd6c8a2fcbf565ae1c8e6a9561133
ValorWind1/passwords
/password_gen.py
694
4.03125
4
""" printable(): string of characters which are considered printable. """ import string # .printable() import random import pickle def genPass(n): password = " " for i in range(n): int = random.randint(10,34) password += string.printable[int] return password # print (genPass(6)) # pr...
1b748249130664b041d49371156cdd350f19bc6c
gregor-gh/python-for-everybody
/LoopsAndIteration.py
1,597
3.96875
4
# while loop n = 5 while n > 0: print(n) n -= 1 print("done") # break while True: break print("broken out") # continue runs from start of loop n = 0 while True: if n < 5: n += 1 continue break print(n) # for loop for i in [5, 4, 3, 2, 1]: print(i) print("done") # a for exampl...
246d04125a0dc203f4f4edb893ddf3dcc5bfcb27
danvb112/Projeto_parte_2
/Aluno.py
2,315
3.734375
4
import sqlite3 class Aluno: def __init__(self): self.nome = "" self.cpf = "" def get_nome(self): return self.nome def set_nome(self, novo_nome): self.nome = novo_nome def get_cpf(self): return self.cpf def set_cpf(self, novo_cpf): ...
59bf4b3d3c817a145f43efecb5ced6123043dc38
wesleywesley97/FATEC---Mecatr-nica---0791921003---Wesley-Baptista
/LTP1-2020-2/Prática05/exercício01.py
705
4.3125
4
#Exercício 1 - Aula 05 #Lê 3 valores, encontra o maior, menor e a média deles valor1 = int(input('informe um valor:')) valor2 = int(input('informe outro valor:')) valor3 = int(input('informe o terceiro valor:')) #Encontrar o maior valor if valor1 >= valor2 and valor1 >= valor3: maior = valor1 elif valor2 >= valor1...
689af2020cd5a5400e05c24c9322b5e9f1539dc4
vikil94/mar26_reinforcement
/excercise.py
627
4.03125
4
class Location: def __init__(self, name): self.name = name def __str__(self): return f"{self.name}" class Trip: destinations = [] def add_location(self, destination): self.destinations.append(destination) def trip_show(self): print("Begin Trip") for i in...
985a080508bd7ce1579877ed31b009d46c948585
itsolutionscorp/AutoStyle-Clustering
/all_data/exercism_data/python/grade-school/27c607960b224df5b5c60f151db3e3b2.py
766
3.796875
4
class School(): def __init__(self, school): self.school = school self.db = {} def add(self, student_name, grade): if grade in self.db: self.db.update({grade : [self.db[grade], student_name]}) else: self.db[grade] = [student_name] def grade(self, grade): return self.db.get(grade) ...
406010b6e0ad460b9dfeb82aa9209c86e06d6051
Aravin008/my_pet_dog
/basic_person_class.py
2,845
4.15625
4
""" basic_person_class to interact with dog. there are limited actions that can be considered for a person like feed, play, bath dog owned by him. This class also keep track of person object affinity with that dog object. This can be improved by playing and other actions. """ from my_pet_dog import Dog...
1f9a4daf43ca4e7d6117b37c56e3a68c18a0b3bf
wlgud0402/dev
/자료구조/Queue.py
449
3.53125
4
#deque 라이브러리를 통해 Queue 구현 from collections import deque queue = deque() #Queue는 선입선출을 지키는 '공평한' 자료구조 #=>먼저 들어온게 먼저 나간다. queue.append(5) queue.append(4) queue.append(6) queue.append(0) queue.popleft() #위치와 상관없이 먼저 들어온 자료가 먼저 나간다. queue.append(7) queue.append(1) queue.append(8) queue.popleft() queue.append(3) p...
c9b3ba164e5e405beb11ff64f3398cc537e56064
fyit-37/DS
/practical6.py
664
3.671875
4
#bubble sort arr=[3,6,8,4,29] n=len(arr) for i in range(n): swappe = False for j in range(0, n-i-1): if arr[j] > arr[j+1] : arr[j], arr[j+1] = arr[j+1], arr[j] swappe = True else: swappe = False break #insertion sort n=[5,2,8,4,51] for i in ran...
9737527361feac5fafc0b079d8c222343fcabaf1
limiracle/python_example
/com/py/multi_test/threading_example1.py
1,672
3.578125
4
#coding=utf-8 #多线程和多进程最大的不同在于,多进程中,同一个变量,各自有一份拷贝存在于每个进程中,互不影响, # 而多线程中,所有变量都由所有线程共享,所以,任何一个变量都可以被任何一个线程修改,因此,线程之间共享数据最大的危险在于多个线程同时改一个变量,把内容给改乱了。 import time,threading #假设这是你的银行存款 balance=0 lock = threading.Lock() def change_it(n): global balance balance=balance+n balance=balance-n def run_thread(n): ...
9e0d104c71023a391eea3f2b5ea7375d54f527dd
nosrac77/code-katas
/src/sort_cards.py
591
3.96875
4
"""Kata: Sort a Deck of Cards - my task was the sort a given list of unicode characters based upon their card value. After seeing the solution, I'm not proud of my answer. #1 Best Practices Solution by zebulan, Unnamed, acaccia, j_codez, Mr.Child, iamchingel (plus 7 more warriors) def sort_cards(cards): return so...
2ff7976defbe53686db9c9f471a6e7152e9c2e04
umbs/practice
/IK/sorting/Quicksort.py
2,334
4
4
from random import randint def swap(arr, i, j): arr[i], arr[j] = arr[j], arr[i] def get_pivot_index(start, end): ''' start and end indices, are both inclusive ''' return randint(start, end) def partition(arr, start, end, p_idx): ''' Use Lumoto's algorithm. When paritioning is done, swap...
5a8369e14fbef6242cfc9378bee7f006f370f98b
yonwu/thinkpython
/CaseStudy_Interface_Design/4.3.py
177
3.78125
4
import turtle def polygon(t, length, n): for i in range(n): t.fd(length) t.lt(360 / n) turtle.mainloop() bob = turtle.Turtle() polygon(bob, 100, 6)
a5bafeb23de80a18683f2ce636446baaef7523b2
JLodha/PythonTutorial
/TryExcept.py
401
3.671875
4
try: infinity = 10/0 except ZeroDivisionError as err: print(err) except ValueError as err: print(err) except: print("Undefined Error!") try: ex = int(input("Enter a number: ")) #For checking the exceptions provide a string instead of a number here except ZeroDivisionError as err: print(err...
eb99aac3792d6a57c1670a4b190dd5180a958002
hemantcaf/RSA
/Decrypt.py
749
3.71875
4
def decrypt(cipher, d, mod): plain = 1 d = '{0:b}'.format(d) for i in range(len(d)): plain = (plain * plain) % mod if d[i] == '1': plain = (plain * cipher) % mod return plain if __name__ == '__main__': length = int(input('Enter the number of strings:\n')) D = int(i...
06b93d97124f2bc956b630d70528de6adb8011a0
basicskywards/data_structures_algorithms
/Heaps/heap_k_largest_elements.py
1,017
3.546875
4
import heapq # naive, time O(klogn) # good, time O(klogk) # logk: insert/extract from max_heap def k_largest_in_binary_heap(A, k): if k <= 0: return [] candidate_max_heap = [] candidate_max_heap.append((-A[0], 0)) result = [] #print(candidate_max_heap) for _ in range(k): candidate_idx = candidate_max_heap...
74f3e96304e1463e9f38f2acf03a5afa8cd83f75
Deaddy0430/python_learning
/01_basic_python_1/06_for_for.py
165
4.15625
4
height=int(input("please enter the square height: ")) for x in range(1,height+1): for y in range(x, x+height): print("%2d" % y,end=' ') print()
8b49aefdec8d6987801f38890e6959be3ed05a82
eyasyasir/COMP208
/Assignment 2/encryption.py
5,175
4.15625
4
# Author: [Eyas Hassan] # Assignment 1, Question 3 import random # Given a dictionary d and value v, # find and return the key associated with that value. # (From the slides.) def reverse_lookup(d, v): for key in d: if d[key] == v: return key return None LETTERS = 'abcdefghijklmnopqrstuvw...
060dd549a5d2a60a27ae47ccede9f6699b9dea9a
samantabueno/python
/CursoEmVideo/CursoEmVideo_ex048.py
274
4.1875
4
# Exercise for training repetition structure # Program to know the sum of the odd and multiple by three numbers # Between 0 and 500 (five hundred) sum = 0 for c in range(1, 500+1, 2): if c % 3 == 0: sum = sum + c print(c, 'is divisible by 3') print(sum)
0b5b5e9e8808688bb994f5afb9644d076fd75a65
linhnt31/Python
/Fundamentals/Data StructuresAndAlgorithms/Stack/simple_balanced_parentheses.py
472
3.765625
4
from Stack import Stack def checkBalanced(symbolString): s = Stack() for sub_str in symbolString: if sub_str == '(': s.push(sub_str) if sub_str == ')': if s.isEmpty(): return 'Unbalanced' s.pop() if s.isEmpty(): return 'Balanced' ...
77039f854268e428368262a963c8a26de3f6ab3e
GustavoLeao2018/trabalho-aula
/exercicios/aulas-auler-master/aula_4/exercicio_2.py
999
4.09375
4
''' Faça um programa que receba a temperatura média de cada mês do ano e armazene-as em uma lista. Em seguida, calcule a média anual das temperaturas e mostre a média calculada juntamente com todas as temperaturas acima da média anual, e em que mês elas ocorreram (mostrar o mês por extenso: 1 – Janeiro, 2 – Fevereiro, ...
01eccf58720746499b87b83c8ed184e95f6ec6d7
milena-marcinik/LeetCode
/Easy/1572 matrix diagonal sum.py
985
4.375
4
""" Given a square matrix mat, return the sum of the matrix diagonals. Only include the sum of all the elements on the primary diagonal and all the elements on the secondary diagonal that are not part of the primary diagonal. Example 1: Input: mat = [[1,2,3], [4,5,6], [7,8,9]] Output: 25 ...
8e19870711de26ce9c3e37597eb8978e4fd5c411
vernikagupta/Opencv-code
/Masking.py
1,493
3.796875
4
# -*- coding: utf-8 -*- """ Created on Wed Nov 4 08:49:53 2020 @author: vernika """ '''Masking helps in focusing on area of interest in an image and mask the rest of the image.''' import numpy as np import cv2 import argparse def show_img(img): cv2.imshow("canvas",img) cv2.waitKey(0) ...
57ee0ecc497226247dc49edd2cff1028710357d2
HocoHelper/Python-solve-Practice
/13-SepidroodRasht.py
207
3.59375
4
lst = [] for i in range(0, 30): ele = int(input()) lst.append(ele) count_0=lst.count(0) count_1=lst.count(1) count_3=lst.count(3) total=count_3*3+count_1 print(total, count_3)
b7157b0d23d11e75e947d6b3b7a23d00b431ec3f
shirilsukhadeve/Daily_Problems
/DCP_6/1.py
598
3.75
4
class Node: def __init__(self, data): self.data = data self.both = None class LL: def __init__(self): self.head = None def add (self, data): newNode = Node(data) if self.head == None: self.head = newNode else: a = ne...
6b91194aeed881cfb4c6154064d759c4d811a175
Carter-Co/she_codes_python
/oop/book.py
1,290
4
4
#class Book: #def __init__(self): # self.title = "Great Expectations" # self.author = "Charles Dickens" class Book: #First def gives class attributes def __init__(self, title, author, num_page, current_page): self.title = title self.author = author self.num_page = nu...
bfab870e749a5024f35434046d72105558e2af1c
alkatrazua/python_best_program_ever
/pisode 21.py
2,011
4.09375
4
# Create a double linked list class, i.e., a list where each element #has an attribute previous and an attribute next, and of course previous #and next are also instances of the same class. class Node: def __init__(self, data, to_head = None, to_tail = None): self.data = data se...
e4e20740200dca8c2862bd92fcc1ae2e59564474
bio-tarik/PythonUnitTesting
/pytest/Proj01/TestUM.py
2,186
4.09375
4
""" Learning unit testing on Python using py.test. Tutorial: http://pythontesting.net/framework/pytest/pytest-introduction/ """ from unnecessary_math import multiply def setup_module(module): """ Module setup method """ print("setup_module module:%s" % module.__name__) def teardown_module(m...
3260729209b5d10659322a039a5c21df5d8aa4a7
efrainclg95/Sion
/Ejercicios_Web/Diccionarios/ejercicio6.py
794
4.125
4
# Escribir un programa que cree un diccionario vacío y lo vaya llenando con información sobre una persona # (por ejemplo nombre, edad, sexo, teléfono, correo electrónico, etc.) # que se le pida al usuario. Cada vez que se añada un nuevo dato debe imprimirse el contenido del diccionario. dic = {} v_dato = str(input("Q...
6847d3336656caa9ecb85b551f29d46d10121084
sjNT/checkio
/Elementary/Best Stock.py
999
4.03125
4
""" Вам даны текущие цены на акции. Вам необходимо выяснить за какие акции дают большую цену. Input: Словарь (dict), в котором ключи - это рыночный код, а значение - это цена за акцию(float) Output: Строка, рыночный код """ def best_stock(data): for i in data.keys(): if data[i] == max(data.values()): ...
ce002b934a400ad23506e9a2937ebcdf2fad081c
Pedro-H-Castoldi/descobrindo_Python
/pphppe/sessao13/xiii_sistema_de_arquivos_manipulacao.py
5,365
3.625
4
""" Manipulação de Arquivos import os # Identificar se o arquivo existe print(os.path.exists('aula_de_arquivos.txt')) # True # Identificar se o diretório existe # Path Relativos print(os.path.exists('pacote')) # True print(os.path.exists('arquivos')) # False print(os.path.exists('pacote\\sub_pacote')) print(os.path....
f7f6fef26faf5372de08e4ea4d4fa4f7d47a99d9
parikshittyagi/OpenCV-python
/EdgeDetection.py
752
3.59375
4
import cv2 import numpy as np img = cv2.imread('/home/iot/Downloads/img1.jpeg') #In laplacian or sobel method we loose edges i.e it is more proficient method for removing noise in the images laplacian = cv2.Laplacian(img, cv2.CV_64F) #Sobel(image name,cv2.CV_64F,x-axis,y-axis, kernel size) sobelx = cv2.Sobel(img, cv...
b6b69c722385e1db3dd4fa1c7d6a089448e18bd2
driellevvieira/ProgISD20202
/JoaoVitor/Atividade Contextualizada 6/Atividade6.py
11,914
3.734375
4
####################### ################Etapa 1 print('Inicio do procedimento de cirurgia esterotaxica.') dic_anestesia = {'1': 'Ketamina e Xilazina', '2': 'Halotano (solucao gasosa)'} sw_anestesia = input('\nDigite 1 para Ketamina e Xilazina, e 2 para Halotano (solucao gasosa): ') if (sw_anestesia == '1'): print...
0fd3d004ace8c1b465538854f33a3421b56ecd4e
bb554C/ECE163L-ACTIVITIES
/LT1/LT1_C/05_if-acl.py
279
4.21875
4
firstNumber = int(input("Enter an Integer: ")) if firstNumber >= 1 and firstNumber <= 99: print("The integer is within 1 to 99") elif firstNumber >=100 and firstNumber <= 199: print("The integer is within 100 to 199") else: print("The integer is not within 1 to 199")
706b8c14c80a1188c5e8b1eb88e88394dc93d81e
SimeonTsvetanov/Coding-Lessons
/SoftUni Lessons/Python Development/Python Basics April 2019/Lessons and Problems/11 - For Loop Exercise/07. Salary .py
368
3.765625
4
tabs = int(input()) wage = int(input()) for i in range(0, tabs): website = input() if website == "Facebook": wage -= 150 elif website == "Instagram": wage -= 100 elif website == "Reddit": wage -= 50 if wage <= 0: print("You have lost your salary.") ...
d952cdc1760095255ed26d9c274ce5b1a354f4a0
grayjac/Filters
/filters.py
759
4.09375
4
#!/usr/bin/env python3 # ME499-S20 Python Lab 2 Problem 4 # Programmer: Jacob Gray # Last Edit: 4/21/2020 from statistics import mean def mean_filter(data, filter_width=3): """ This function replaces each sensor reading with the mean of itself and the readings on either side of itself. :param data: Da...
67b1a46b4b103b8e31814352fe43ba0cb3a3d20c
K10shah/Linear-regression-on-LeToR
/regressionEssentials.py
4,859
3.59375
4
import numpy as np import pandas as pd import scipy.stats as stats import sklearn.cluster as cl from sklearn.metrics import mean_squared_error from math import sqrt import matplotlib.pyplot as plt # Cluster the data into K clusters using KMeans clustering. def calculateM(data, k): # Calculates the number of basis fun...
47ec4ff7313c19af80476ef24892efaa3c11f496
AdamZhouSE/pythonHomework
/Code/CodeRecords/2129/60657/248772.py
626
3.6875
4
import math n=int(input()) cons=0 def Judge(a): while a > 1: a = a / 2 if a == 1: return True else: return False while(n>1): if(n%2==0): n=n//2 cons+=1 if(Judge(n)): cons+=math.log(n,2) break elif(n==3): cons+=2 ...
b15d194dc7a42a3183315d0b5dbbce26960efcd8
developer20161104/python_practice
/py_object/chapter8/regular_expression.py
1,295
3.65625
4
import re import sys def match_str(patterns, search_string): # patterns = sys.argv[1] # search_string = sys.argv[2] match = re.match(patterns, search_string) # 内部变量还能这么用?? if match: template = "'{}' matches pattern '{}'" else: template = "'{}' does not matches pattern '{}'" ...
fb3e0a63302028d8398677fd0ec6b224a75c8624
AlexBlackson/Algorithms
/Three Partition/ThreePartition.py
1,659
3.6875
4
""" Created on Tue May 15 19:52:47 2018 Written by Alex Blackson ENSEA: FAME Algorithms Course Last Updated: May 17, 2018 """ # Memoization function given in class to prevent repeat function calls def memoize(f): mem={} def f_memoized(*args): if args not in mem: mem[args] = f(*a...
8c0b2e0b94ebbf3665a68fab862b91c4eb960104
vikramlance/Python-Programming
/Leetcode/problems/problem0020_valid_Parentheses.py
545
3.859375
4
from collections import deque class solution: def is_valid(self, input_str): stack = [] # Can use stack = deque() paran_dict = {')': '(', '}': '{', ']': '['} for i in input_str: if i in paran_dict: if not stack or stack.pop() != paran_dict[i]: ...
eebcda9993eee08a48ab37066acb5b51067e3048
atanx/atanx.github.io
/assets/code/pyds/pyds/Queue.py
688
3.859375
4
#!/usr/bin/env python # coding=utf-8 # # Copyright 2019, Bin Jiang # # 实现队列数据结构 from .error import EmptyError from collections import deque class Queue(object): def __init__(self): self._data = [] def enqueue(self, e): """ 入栈一个元素 """ self._data.append(e) def dequeue(self): """ 出栈一个元素 "...
e13b9c6f502f618e3c2009f646bc3ac4973b1409
mikaelbeat/Robot_Framework_Recap
/Robot_Framework_Recap/Python_Basics/Input_from_the_user.py
85
3.8125
4
# input from the user i = input("Enter something --> ") print("You entered " + i)
7f1e750146da391955c2a673a18b2e3f052d0eb5
abhay772/LeetCodeSolutions
/python-solutions/43.py
564
3.84375
4
# Runtime: 32 ms, faster than 85.56% of Python3 online submissions for Multiply Strings. # Memory Usage: 14.3 MB, less than 26.58% of Python3 online submissions for Multiply Strings. class Solution: def multiply(self, num1: str, num2: str) -> str: temp=0 for i in range(len(num1)): ...
b84dca8069e9bd7ecf7e8e3edb214594dd5a4696
xiangzz159/Python-Study
/leetcode/easy/Intimate_String.py
1,061
3.625
4
#!/usr/bin/env python # _*_ coding:utf-8 _*_ ''' @author: yerik @contact: xiangzz159@qq.com @time: 2018/6/25 14:23 @desc: https://leetcode-cn.com/contest/weekly-contest-90/problems/buddy-strings/ ''' class Solution: def buddyStrings(self, A, B): """ :type A: str :type B: str :...
7e0a8d783adb81e68ba82f845edc17aac845c79c
Kai-Bailey/machinelearnlib
/machinelearnlib/models/linearRegression.py
2,924
4.03125
4
import numpy as np from .. import loadModel def cost(features, labels, weights, reg=0): """ Computes the squared error between the labels and predicted output with regularization for each weight. :param features: Numpy matrix of input data used to make prediction. Each row is a training example and each f...
0be1e78e20cf77da594a616641f79ca92e562e69
sangm1n/problem-solving
/CodingTest/6-4.py
443
3.671875
4
""" author : Lee Sang Min github : https://github.com/sangm1n e-mail : dltkd96als@naver.com title : Quick Sort2 """ array = [5, 7, 9, 0, 3, 1, 6, 2, 4, 8] def quick_sort(array): if len(array) <= 1: return array pivot = array[0] tail = array[1:] left_side = [x for x in tail if x <= pivot] ...
7d749a061225e406f166fcf61737ac418bda4774
NabinAdhikari674/Files
/Pytho/Sum of 'n' numbers.py
141
4.125
4
def sum(): n=int(input("Enter The Value For n :\t")) s=0 i=0 while i<=n : s=s+i i=i+1 print("The Sum Of n numbers is : ",s)
9429189509533ce2a1bc91c5d303ba74b9011ced
kwangsooshin/MoviePlace
/utils/rectagle.py
2,087
3.828125
4
class Rectangle: x = 0 y = 0 w = 0 h = 0 def __init__(self, x=0, y=0, w=0, h=0): self.x = x self.y = y self.w = w self.h = h def top(self): return self.y def bottom(self): return self.y + self.h def left(self): return self.x def right(sel...
e978aef37bff857247d436e186822169403ac6bf
lakshmirnair/problem-solving-in-python
/Math with python/trajectory_2dbody.py
827
3.5625
4
# x=ucosθ t #y=usinθ t-1/2(g t^2) #Drwawing the trajectory of 2d motion #comparing the trajectory with different initial values from matplotlib import pyplot as plt import math def graph(x,y): plt.plot(x,y) plt.xlabel('x coordinate') plt.ylabel('y cordinate') plt.title('projectile motion of a ball') de...
e2d7badd929c76feabf82d1c91ea310b43ab10cf
schaeferrodrigo/highways
/plot_teste_function/main.py
887
3.53125
4
# -*- coding: utf-8 -*- #=============================================================================== import matplotlib.pyplot as plt from function_to_be_bounded import * from parametros import * #=============================================================================== def main(): print("mu= ",mu) pri...
82c34caed152d5ac18bf27d69c921a55a7a91814
ALEGOVE03/Tarea1GomezPorras
/tarea1.py
1,997
3.96875
4
# ----------------------------------------------------------------------- # -------------- Método para operaciones básicas ------------------------ # ----------------------------------------------------------------------- def basic_ops(op1, op2, sel): # Error cuando no se usa un entero if not(isinstance(...
49f8fba9195b83665a86acb5cd1200671e1b1697
makirsch/Python
/6-Complex Exception Loops and Dict Exercise.py
3,405
4.21875
4
""" Writing File and Making Dictionary Program: Exercise in Exceptions By Michael Kirsch For Dr. Weimen He This Program is made up of two programs that work independently and also together. The first program main1, opens a file and prompts the user for two space separated integers. A comprehension is used to defin...
2546e406aaa5d8502df37ff092da0a7972887792
ilbarlow/DiseaseModelling
/gene_selection/Old_code/sgDesignInput.py
1,269
3.515625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Dec 6 16:17:50 2018 @author: ibarlow """ """ function to convert WormMine output to a csv with columns Gene name, chromosome, start, and end of targeted region from left to right""" import pandas as pd import sys def sgDesignInput(input_file, outpu...
9e722ff443e1cf8513d52e9cb11e72ca459ec99f
Gaiokane/CrazyPython
/Chapter_6/6-5/6-5_1.py
552
3.578125
4
import sys #sys.stdin代表系统的标准输入(键盘),它是一个类文件的对象 #遍历文件(把sys.stdin当成文件来看)的语法 #for line in sys.stdin: # print(line) #默认情况下,sys.stdin是从键盘读取 #如果使用管道输入之后,sys.stdin将改为从前一个程序的输出来读取 #程序要使用python将javac命令的输出中有关'module'的行,都打印出来 for line in sys.stdin: #如果读到这一行包含了'module',输出该行内容 if 'module' in line: print(line)
25095d8a2ee0bc428ca43d226c40e7c53d2da4de
dvaibhavim/solutions_codechef
/probs.py
350
3.5625
4
# -*- coding: utf-8 -*- """ Created on Wed Jun 10 10:28:59 2020 @author: lenovo """ #t = int(input()) #for tc in range(t): # digit = input() # sum_digit = (int(i) for i in digit ) # print(sum(sum_digit)) import math as m T = int(input()) for tc in range(T): (a,b) = map(int,input().split(' ')) ...