blob_id
stringlengths
40
40
repo_name
stringlengths
5
119
path
stringlengths
2
424
length_bytes
int64
36
888k
score
float64
3.5
5.22
int_score
int64
4
5
text
stringlengths
27
888k
abe74cce327ffb477c7a83cd10a67e062d616e23
almogboaron/IntroToCsCourseExtended
/ID.py
1,518
4.125
4
def is_valid_ID(): # prompts for input from user ID = input("pls type all 9 digits (left to right) of your ID: ") assert len(ID) == 9 if control_digit(ID[:-1]) == ID[-1]: print("Valid ID number") else: print("ID number is incorrect") def control_digit1(ID): """ compu...
5e012d74fb693f6808498d7d80edd46fb4385e44
kichu2020/age
/main.py
217
4.375
4
age = int(input("What is your child's age? ")) if age < 0: print("not born") elif 0 < age <= 3: print("toddler") elif 3 < age <= 12: print("child") elif 12 < age <= 18: print("teenager") else: print("adult")
feb52586c9a5e550d83b3103a545846d0152e9a3
ruigodoy/PythonBrasilListas
/EstruturaSequencial/7_exercicio.py
241
3.65625
4
# Faça um Programa que calcule a área de um quadrado, # em seguida mostre o dobro desta área para o usuário. def area_quadrado(lado): return lado * lado area_dobrada = area_quadrado(8) * 2 print(f'Área dobrada: {area_dobrada}')
73d042d895d6b52049cc1ab10cfb084f126ae838
karinaaltheaabad/Computer-Networks
/Labs/lab4/server.py
3,467
3.84375
4
######################################################################################################################## # Class: Computer Networks # Date: 02/03/2020 # Lab3: TCP Server Socket # Goal: Learning Networking in Python with TCP sockets # Student Name: Karina Abad # Student ID: 918533530 # Student Github Use...
a807cf4f160ef240d265d7f11f52b591359c328f
LitianZhou/Intro_Python
/ass10.py
1,538
3.578125
4
# ass 10 import pickle class Employee(): def __init__(self, name, id): self.name = name self.id = id self.department = "N.A." self.job_title = "N.A." def set_department(self, dep): self.department = dep def set_job_title(self, job_title): self.job_title = job_title def get_name(self): return self...
320c1f7f2b55f8c4ed2951df99ae6b9b6a97e55e
dvjr22/IST_736_TextMining
/HW/007/002_svn_edit.py
16,954
3.875
4
#!/usr/bin/env python # coding: utf-8 # # Tutorial - build LinearSVC model with sklearn # This tutorial demonstrates how to use the Sci-kit Learn (sklearn) package to build linearSVC model, rank features, and use the model for prediction. We will be using the Kaggle sentiment data again. # # Note that sklearn actual...
8aba8880f20ee138c5aa2a0068e093364b0a01c3
AlPus108/Python_lessons
/Proect_Eylera.py
2,300
3.640625
4
# ПРОЭКТ ЭЙЛЕРА # Задача по программированию # https://euler.jakumo.org/problems/view/1.html # ----------------------------------- Задача 1 ------------------------------------ # Числа, кратные 3 или 5 # Если выписать все натуральные числа меньше 10, кратные 3 или 5, то получим 3, 5, 6 и 9. Сумма этих чисел равна 23. ...
28fbee8499057c61329fbc6eeff9560a24cf17ba
thedrkpenguin/CPT1110
/Week 3/ContinueTest2.py
175
3.921875
4
var = 10 while var > 0: var -= 1 if var == 5: continue #break print('Current variable value :', var) print("Good bye!")
d27fe5feb96962ee09202284d16b43427e592cad
dekasthiti/pythonic
/learn_varargs_kwargs.py
792
3.796875
4
def foo(p, q, *args, **kwargs): print("p = {0}, q = {1}".format(p, q)) for i in range(len(args)): print("args[{0}] = {1}".format(str(i), str(args[i]))) for keyword, value in kwargs.items(): print("keyword, value " + str((keyword, value))) args = (2.71, [6, 28]) kwargs = {'name': 'cfg'...
62ce1db588f9976c85754dc589204ad1a7414214
andreisavu/python-mvfs
/mvfs/utils.py
387
3.578125
4
import os import errno def mkdir_p(path): """ Create a hierarchy of directories. Same functionality as the shell command mkdir -p Credits: http://stackoverflow.com/questions/600268/mkdir-p-functionality-in-python """ try: os.makedirs(path) except OSError, exc: if exc.errrno ...
dd3bea85cd7e88124e5a7e5fdb77a2427e04cb66
tydlitele/Kniha-Keya
/print_layout.py
807
3.5625
4
#Toto jsem napsal po nekolika nocich, kdy jsem skoro nespal #Uprimne, takhle hnusny kod jsem dlouho nenapsal #Pozor, muze zpusobovat paleni oci, nevolnosti #Pouzil jsem velmi enefektivne seznam, kde bych moh mit cislo... #K certu s blbou knihou keya #si to sazejte sami #pocet stranek pages = 56 if(pages%4): raise...
4f4cd7f2d04c64b59d13c6112db2486d015039d2
sapamja/Algorithms
/Dictionary_sorted_array.py
2,676
3.9375
4
# Fundamental operations: # Search # Insert # Delete # Succesor # Predecessor # Minimum key # Maximum key # Could be implemented with: # Sorted array # Unsorted array # Linked list # Binary search trees p. 77 # Hash tables p. 89 # Other p. 367 # ------------------------------ # Some links # http://lyle.smu.edu/~tyler...
b285f3fe4428dd5a325577d9dfaccd694a162123
mhn998/-data-structures-and-algorithms
/python/code_challenges/ll_zip/ll_zip.py
1,139
4
4
from Data_Structures.linked_list.linked_list import Linked_list def zipLists(ll1,ll2): i , j = 0, 0 current1 = ll1.head current2 = ll2.head while current1: i += 1 current1 = current1.next if current1 == None: break while current2: j += 1 current2...
bdaaebf068cb3910bad5728334ddc74a64aa88a2
IgnacioPascale/careers-optimizer
/api/plotting.py
6,427
3.5625
4
# Data Libraries import pandas as pd import numpy as np # Visualization import matplotlib.pyplot as plt # Math from math import pi from helpers import * from io import StringIO import io import base64 def create_stats(player_stats, print_plot=True): """ For an individual dataframe of player stats, cr...
60c2b283bc64e84ec886b0683a0c49aedd239e08
ETCBC/sbl_berlin17_textfabric
/codes/present.py
9,704
3.734375
4
# A set of functions for displaying pretty text output in our presentation from __main__ import HTML, display, time, clear_output, F, T, L import copy def present(string, size=60, font='Baskerville'): """ Return pretty output for presentation. Requires a string. Optional arguments: size for font size,...
b4ecc31569d6605d25042c668b547d90afbd2b74
Radbull123/My_Framework
/sorts&search/bubble_sort.py
331
3.828125
4
def bubble_sort(any_list): count = 1 while count < len(any_list): for n in range(len(any_list)-1): if any_list[n] > any_list[n+1]: any_list[n+1], any_list[n] = any_list[n], any_list[n+1] count += 1 return any_list a = [44, 20, 13, 5, 13, 8, 13, 1, 0, 0, 1, 2, 7...
7232c528501b6c6c4afce36367e767f68b7df91c
DanilWH/Python
/python_learning/chapter_03/5 cars.py
3,019
4.34375
4
cars = ["bmw", "audi", "toyota", "subaru"] print("Исходный список.") print(cars) cars.reverse() print("\nПревёрнутый список.") print(cars) # Чтобы переставить элементы списка в обратном порядке, нужно использовать метод reverse(). # Этот метод просто переходит ка обратному порядку списка, а не сортирует элемен...
d51c7604ab5e0f79e81073a1685461b48528019d
gama79530/DesignPattern
/AbstractFactoryPattern/python/PizzaStore/Pizza.py
1,525
3.59375
4
from enum import Enum import abc from .Ingredient import * class PizzaType(Enum): CHEESE_PIZZA = 0 class Pizza(metaclass=abc.ABCMeta): def __init__(self, ingredients:list[Ingredient]) -> None: self.ingredients = ingredients @abc.abstractmethod def getName(self) -> str: return NotImpl...
4be2a451ea23cbd15d26852553875655afb56484
dalibor-meszaros/Summarizer
/tools/mystring.py
290
3.765625
4
import string def remove_punctuation(text, punctuation=None): if punctuation is None: punctuation = string.punctuation + u'„“–ʾ†-/' # common symbols in documents for p in punctuation: text = text.replace(p, ' ') return ' '.join(text.split()).strip()
3fe9b0c225fc5ad42891692f2f5e0461f99bc01e
mdjglover/hotmail-eml-to-text-converter
/hotmail_eml_to_txt_converter/parser/Email.py
782
3.875
4
class Email(): # Simple object to hold email data def __init__(self): self.sender_name = "" self.sender_email = "" self.receiver_name = "" self.receiver_email = "" self.date = "" self.time = "" self.datetime_hotmail_format = "" self.subject = "...
5eeea80b482464cf68cdb9454b1feb54983a360b
GauravR31/Solutions
/Files/Zip_creator.py
492
3.921875
4
import os import zipfile directory = raw_input("Enter the directory path to zip ") dir_zip = zipfile.ZipFile('zip_directory.zip', 'w') if os.path.isdir(directory): for folder, subfolders, files in os.walk(directory): for file in files: dir_zip.write(os.path.join(folder, file), os.path.relpath(os.path.join(fold...
0d02cd50d63f2defec8b2b3729cfcd1e93db3985
TrevorMorrisey/Project-Euler
/Python/pe049.py
1,278
3.59375
4
# -*- coding: utf-8 -*- """ Created on Sat Nov 9 11:43:11 2019 @author: TrevorMorrisey """ import peUtilities def primePermutations(): # primes = [] # for i in peUtilities.yieldPrime(): # if i >= 1000: # if i < 10000: # primes.append(i) # else: # brea...
a6e02cc186b7120299240326164b2759c659dece
Sathyasree-Sundaravel/sathya
/Find_the_lexicographical_order_for_a_given_string.py
107
4
4
#Find the lexicographical order for a given string a=str(input()) s=sorted(a) for i in s: print(i,end="")
31435c3bdfbbc0c57fdb1566ae7902fbb4b18b8e
spacecase123/py-sandbox
/main.py
1,026
3.96875
4
# This is a sample Python script. # Press Shift+F10 to execute it or replace it with your code. # Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings. thisIsaVariable = "Hello! I am a value stored in a Variable!" def print_hi(name): # Use a breakpoint in the code line...
0504465475ca5afa4525c61bc557a20b81a635e6
sun1day/leetcode
/lt_2022_5_26/main.py
1,311
4.0625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2022/5/26 14:42 # @Author : Jax # @File : main.py # @Software: PyCharm """ ## 905. 按奇偶排序数组 ### 相关标签 1. 数组 2. 双指针 3. 排序 给你一个整数数组 nums,将 nums 中的的所有偶数元素移动到数组的前面,后跟所有奇数元素。 返回满足此条件的 任意一个数组 作为答案。   示例 1: 输入:nums = [3,1,2,4] 输出:[2,4,3,1] 解释:[4,2,3,1]、[2,4,1...
2e8a4c2d7939580f620d62c169870f1cb20193ae
brandohardesty/Showcase
/primeFact.py
1,476
4.03125
4
__author__ = "Brandon Hardesty" def sieve(n = int(1e7)): """ builds a list of primes less than n :param n: limit on our primes :return: reverse ordered list of primes less than n """ multiples = set() primes = [2] for i in range(3,n+1,2): if i not in multiples: prime...
2a5483b7e5af1f423035284f27c4cf245d6ddc57
FullStackToro/Funciones_Intermedias_Python
/main.py
599
3.765625
4
import random def randInt (min=0,max=100): if min>max: return 'Error: Verificar valor mínimo y máximo.' elif max<0: return 'Error: El valor máximo no puede ser menor a cero (0).' else: num=random.random()*(max-min)+min num=round(num) return num # Press t...
2fe02a93f7a2881e1264fa00eab6b6f16a7d9df5
leclm/CeV-Python
/PythonDesafios/desafio62b.py
702
4.125
4
''' Melhore o desafio 61, perguntando para o usuário se ele quer mostrar mais alguns termos. O programa encerra quando ele disser que quer mostrar 0 termos. ''' primeiro = int(input('Digite o primeiro termo da PA: ')) razao = int(input('Digite a razão da PA: ')) termo = primeiro cont = 1 print('\033[1;35m-=\033[m...
c59cf2569aeec39d24595f017bdc6f7115213573
matchallenges/Portfolio
/2021/PythonScripts/leet_code_4.py
1,670
3.546875
4
class Solution: def romanToInt(self, s: str) -> int: ret = 0 trail = '' target = '' lead = '' string_with_suffix = s + '~' for i in string_with_suffix: #initalize variables trail = target target = lead...
2ac5f934c54e50806407cfd74ad7da5bb316da7d
Trevortds/lingbot
/lingbot/features/elections.py
2,449
3.578125
4
import Hashids import datetime import hashlib # TODO implement hashes-add-to-total thing # Types of votes, each has a hash, this is how you confirm that your vote was counted. class vote: # vote abstract class. implements hashing method for all votes. Contains informatin about the # user and the date, but n...
d18f6e1bd145e6a7422e1174cba881f2b2f3152b
chati757/python-learning-space
/tkinter/dialog_box.py
655
4.125
4
import tkinter as tk # Create the main window root = tk.Tk() #win.withdraw() # Create the dialog window dialog = tk.Toplevel(root) dialog.title("test title") dialog.focus_set() # Add a label and a button to the dialog window label = tk.Label(dialog, text="This is a focused dialog window1") button = tk.Button(dialog, ...
a56962204734a33d9e69259f860aa878bf603cd3
bphillab/Five_Thirty_Eight_Riddler
/Joker_22_04_01/Joker_Classic_22_04_01.py
467
3.65625
4
def pred_next(x): temp = {2 * x} if x % 2 == 0 and x % 3 == 1: temp.add((x - 1) / 3) return temp def step(curr, prev): nxt = set() for i in curr: nxt = nxt.union(pred_next(i)) nxt = nxt.difference(prev) return nxt if __name__ == '__main__': curr = {1} prev = {1} ...
93282350ee718deb38c810cc752143f4b7d3017e
zaino1234/Python
/CursoemVídeo/ex001.py
359
3.96875
4
from random import randint n = randint(1, 10) while True: escolha = int(input('Escolha um número ente 0 a 10: ')) if n == escolha: print(f'Parabéns!!!' f'Sua resposta foi correta...' f' eu tinha escolhido {n}') break if n > escolha: print(f'Maior') if ...
d78c01a80cf41fd7be5fcea9b8f79e7604e92930
sabin262/AI-fun
/suduku.py
1,797
3.921875
4
class Suduku: SIZE = 9 def __init__(self, inputs): self.board =[[0 for x in range(self.SIZE)] for y in range(self.SIZE)] i = 0 j = 0 for index, data in enumerate(inputs): i = index // 9 j = index % 9 self.board[i][j] = data def printBoard(self): i = 0 while i < self.SIZE: row = "" j = 0 ...
8107e666e74550753f4fc5b22f62016a6e91fc45
weilyuwang/python-algorithms-data-structures
/data_structures_playground/min_stack.py
1,150
4.0625
4
""" Design a stack that supports push, pop, top, and retrieving the minimum element in constant time. push(x) -- Push element x onto stack. pop() -- Removes the element on top of the stack. top() -- Get the top element. getMin() -- Retrieve the minimum element in the stack. """ # Using two stacks # one for usual stac...
cd127724533425846101a39c7ae68773176ea305
matheusvictor/estudos_python
/curso_em_video/mundo_01/ex002.py
162
3.921875
4
nome = input('Qual é o seu nome?\nResp: ') # print('Prazer em te conhecer,', nome) --> resolução mais simples print('Prazer em te conhecer, {}!'.format(nome))
e0516fb0a184aa04ccb07dd115243d29febdc6fa
ytmimi/Yahoo-Finance-Scraper
/yahoo_finance/utc_converter.py
2,013
3.53125
4
import datetime as dt from pytz import UTC time_codes = ['%m/%d/%Y', '%m/%d/%y', '%m-%d-%Y','%b %d, %Y',] def date_str_from_timestamp(timestamp, fmt_str='%m/%d/%Y'): date = dt.datetime.utcfromtimestamp(timestamp) return date.strftime(fmt_str) def utc(date, fmt_str=None): '''converts either a date or a string to ...
c8152a4b9cfdd254fb22fbb7c474cb09ca4f67b5
namani-karthik/Python
/operator_overloading.py
280
3.75
4
class test(): def __init__(self,x): self.value=x def __add__(self,val): c=self.value + val.value return c def __sub__(self,val): c=self.value - val.value return c a=test(10) b=test(20) c=a+b # => a.add(b) print(c)
639b484d7ed735d17edebffba89a82fa0bc01c86
liuguoquan727/python-study
/tutorial/elementary/type_number.py
791
3.5
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ * * Description: 数字数据类型 * * Created by liuguoquan on 2017/7/28 10:35 * """ import sys # python3 默认编码 print(sys.getdefaultencoding()) # int型 可以存储到任意大小的整型 number = 9 print(type(number)) # int # 查看内存地址 print(id(number)) number = int(9) print(type(number)) # 负数 numb...
994151af308e4923859a73299f659850ccafb2ec
spisheh/DeepLearningPractices
/numpy/tools.py
1,454
4.3125
4
def softmax(x): """Calculates the softmax for each row of the input x. Workd for a row vector and also for matrices of shape (n, m). Argument: x -- A numpy matrix of shape (n,m) Returns: s -- A numpy matrix equal to the softmax of x, of shape (n,m) """ x_exp = np.exp(x) x_sum = np.s...
2b3667b14c47e0efdbaeeb3539bdd275769453fd
devincmartin/calculatorapp
/calculator.py
733
4.25
4
print("Please insert your first number") first_number_string = input(">> ") first_number = int(first_number_string) print("Please insert your second number") second_number_string = input(">> ") second_number = int(second_number_string) print("Your numbers are", first_number, "and", second_number) print("Select you...
fdb4c3ff0d722a8469d7e3acc189de12a850e430
JIANGWQ2017/Algorithm
/JianZhiOffer/18.py
898
3.640625
4
class Solution: def HasSubtree(self, pRoot1, pRoot2): # write code here if not pRoot1 or not pRoot2: return False return self.helper(pRoot1, pRoot2) def helper(self,root1,root2): if root1.val == root2.val: if self.isSameStructure(root1,root2): ...
e090bb43325ab44e816454046c74a076865d7ceb
ChaosNyaruko/leetcode_cn
/324.摆动排序-ii.py
4,480
3.90625
4
from typing import List # @lc app=leetcode.cn id=324 lang=python3 # # [324] 摆动排序 II # # https://leetcode-cn.com/problems/wiggle-sort-ii/description/ # # algorithms # Medium (36.68%) # Likes: 226 # Dislikes: 0 # Total Accepted: 17.8K # Total Submissions: 48.4K # Testcase Example: '[1,5,1,1,6,4]' # # 给你一个整数数组 nums...
7d8972a08172bc81dc3408a659f394f61fa1cd60
Sandy4321/NN
/deep/NN.py
9,103
3.734375
4
''' The net class defines the overall topology of a neural networks, be it directed or undirected. This is a very flexible setup which should give the user a high degree of manipulative ability over the various aspects of neural net training. ''' import numpy as np import cPickle import gzip import theano import thea...
9d2d6fb6c682ada9bf67db23b672678e24af200f
elenaborisova/Python-Fundamentals
/05. Lists Basics - Lab/01_courses.py
124
3.734375
4
n = int(input()) courses = [] for _ in range(n): course_name = input() courses.append(course_name) print(courses)
233ffa5443e276acfa322ad1408bfc36039e9ec6
AnkitM18-tech/Python-Introductory-Problems
/4.Function/Hypotenuse.py
368
3.921875
4
# -*- coding: utf-8 -*- """ Created on Wed Jul 8 02:03:02 2020 @author: OCAC """ def pythogorian(b,p): from math import sqrt h=sqrt(p**2+b**2) return h def main(): b=float(input("Enter The Base length:")) p=float(input("Enter The Perpendicular length:")) result=pythogorian(b,p) print("Th...
203dc2a50e9898e67e52da3fee7fc0e99b8d3bc7
foodhype/practice
/careercup/5749537700315136/main.py
1,503
4
4
class Step(object): def __init__(self, start, finish): self.start = start self.finish = finish def __str__(self): return "Step(%s, %s)" % (self.start, self.finish) class Node(object): def __init__(self, value, next_node): self.value = value self.next_node = next_no...
781b8b93ebe4d109dcbfcf04d76dc7366be6a7a0
adityaramteke/python-pune
/pyramid.py
169
3.90625
4
# Program for Pyramid n = int(input("Enter the step size: ")) # Read the input for i in range(1, n+1): for j in range(1, i+1): print(i,end=' ') print()
459199e767e81ce39ddde461a6bc776efa852669
hsyy673150343/PythonLearning
/函数/function_2.py
1,768
3.5
4
#!/usr/bin/env python # -*- coding:utf8 -*- # @TIME : 16:35 # @Author : 洪松 # @File : function_2.py ''' 函数的参数 ''' ''' 必需的参数:必需参数须以正确的顺序传入函数。 调用时的数量必须和声明时的一样。 ''' def print_info(name,age,sex='male'):#sex就是默认参数(注意:(定长参数)默认参数要跟在非默认参数后面,否则会报错) print('Name: %s' %name) print('Age: %d' %age) print('Sex...
88af11b4db2db9ea1cc0c335e8af5a79c05d1dd2
gmangini/hash_map
/main.py
1,261
3.828125
4
""" main.py Gino Mangini CS 2420 """ from hashmap import HashMap def clean_line(raw_line): '''removes all punctuation from input string and returns a list of all words which have a length greater than one ''' if not isinstance(raw_line, str): raise ValueError("Input must be a str...
14a7fbf77f1fe0b13594d584771eb9dca17abbd9
miroso/pis_code
/starter_bundle/ch11-cnns/convolutions.py
4,655
4.34375
4
# -*- coding: utf-8 -*- """Understand convolutions. This code is suppose to teach you / give you insights how kernels and convolutions are implemented. This source code will not only help you understand how to apply convolutions to images, but also enable you to understand what’s going on under the hood when training ...
4f2e0e69157513b73bccfbdd0ef805bccf5c3fef
JackieMaw/Calculator
/myCalculator_Part2.py
853
3.890625
4
def calculateLine(line): lineParts = line.split() function = lineParts[0] operation = lineParts[1] int1 = int(lineParts[2]) int2 = int(lineParts[3]) return calculate(operation, int1, int2) def calculate(operation, int1, int2): if operation == "+": return int1 + int2 elif operati...
dc02f89362b1f9e1e1022e9814d9c73cb298267f
DanielP-coder/Teste
/par-impar.py
168
4.09375
4
numero = int (input("Digite um número: ")) if (numero % 2 == 0): print ("O número {} é par ".format(numero)) else: print ("O número {} é ímpar ".format(numero))
efec912aa3bd7b2e11bee0a8e812cc926e39c8a3
adrianlopa/D002-2019
/Q1L5.py
96
3.578125
4
def quad(x): y=x**2+2*x+1 return y for z in range(1,11): print (quad(z))
f18e49df29222e779831cff0ce0a6ff1234329ae
IrfaanDomun/Dataquest
/python-programming-beginner/Challenge_ Files, Loops, and Conditional Logic-157.py
726
3.671875
4
## 3. Read the file into string ## file = open("dq_unisex_names.csv",'r') data = file.read() ## 4. Convert the string to a list ## f = open('dq_unisex_names.csv', 'r') data = f.read() data_list = data.split("\n") first_five = data_list[:5] ## 5. Convert the list of strings to a list of lists ## f = open('dq_un...
303e5c3755e9abb531860aedb20a14fe412e7257
pri7/testlearn
/calc.py
227
3.734375
4
def add(x,y): """Adding Function""" return x+y def subtract(x,y): """Subtraction Function""" return x-y def multiply(x,y): """Multiplication Function""" return x*y def divide(x,y): """Division Function""" return x/y
a06b8bd3f3f99ea787a3564c8ba886ea93292b38
dr-dos-ok/Code_Jam_Webscraper
/solutions_python/Problem_89/30.py
1,295
3.578125
4
import math import fractions def int_input(): return int(raw_input()) def list_int_input(): return map(int, raw_input().split()) def list_char_input(): return list(raw_input()) def table_int_input(h): return [list_int_input() for i in range(h)] def table_char_input(h): return [list_char_input()...
9ed2200d2e9663c22b088d036aea67e206a86590
thetechnocrat-dev/algorithm-practice
/Algorithm-Design/ch4-sorting-and-searching/4-10_has_k_pair_sum.py
991
3.890625
4
def has_sum_pair_sorted(array, sum): num_dict = {} for num in array: if num in num_dict: num_dict[num] += 1 else: num_dict[num] = 1 for num in array: target = sum - num if target in num_dict: # to not count the same num twice ...
5d2a07fb3544a42d650edebc3dd7451bcca736c9
vladbortnik/HackerRank
/Python/string-formatting.py
371
3.640625
4
def print_formatted(number): bin_length = len(bin(number)[2:]) for i in range(1, number + 1): print(f'{i: >{bin_length}}', end='') print(f'{oct(i)[2:]: >{bin_length + 1}}', end='') print(f'{hex(i)[2:]: >{bin_length + 1}}'.upper(), end='') print(f'{bin(i)[2:]: >{bin_length + 1}}',...
27ff95f0e0d26d5a1ea923e725af8ff516671daf
rupali23-singh/function
/fun.py
281
3.953125
4
def add(*b): result=0 for i in b: result=result+i return(result) print(add(1,2,3,4,5)) '''def even_numbers(num1,num2): i=0 c=0 while i<len(num1): c=num1[i]+num2[i] c+=1 i=i+1 print(even_numbers([1, 2, 3, 4, 5,],[6, 7, 8, 9]))
33cb8376ad1a9975d8a0bf4a8361ac826c71102c
tristanbatchler/MATH3302-Exam-Study
/cryptography.py
3,494
3.625
4
from typing import * import algorithms import random from collections import Counter from Crypto.Util.number import getPrime SHOW_WORKING = True def affine_encrypt(a: int, b: int, *xs: int) -> Tuple[int]: """Encrypts a message of one or more plaintext x's in Z_{26} using the given affine key (a, b) both i...
0d82d8c3b89eda245fff2169c2e84c0f7c789723
queuedq/ps
/competitions/Facebook Hacker Cup/2018/round-1/2_ethan-traverses-a-tree.py
1,643
3.515625
4
class DisjointSet: def __init__(self, totalSize): self.parent = list(range(totalSize)) self.size = [1] * totalSize def find(self, x): while x != self.parent[x]: x = self.parent[x] self.parent[x] = self.parent[self.parent[x]] return x def union(self, x, y): xRoot = self.find(x) ...
7ece8c4a2b6d782ddc77b3200f874b29e29c4206
JohnpFitzgerald/Python
/sr00156081-Assess1.py
16,080
3.703125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*-"""Second assessment Programming for Data Analytic """ # Please write your name and student ID: #John Fitzgerald import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns def cleanFile(): #read the file and remove empty ...
81b29a7ec1448f5f8eb5df58f7cd30ab08693036
Lucilvanio/Hello-Word
/Exercício 23 - Separano digitos.py
682
3.640625
4
n = int(input('Digite um número entre 0 e 9999: ')) m = n // 1000 % 100 c = n // 100 % 10 d = n // 10 % 10 u = n // 1 % 10 if m == 1: print(f'Você tem {m} milhar\n{c} centena\n{d} dezenas\n{u} unidades') else: print(f'Você tem {m} milhares\n{c} centenas\n{d} dezenas\n{u} unidades') if m and c == 1:...
4a2d5b85a1e0a314b8a063a5224e3335e1eca92d
gaurav-singh-au16/Online-Judges
/Leet_Code_problems/1108.defining_ip_address.py
720
4.15625
4
""" 1108. Defanging an IP Address Easy 542 1019 Add to List Share Given a valid (IPv4) IP address, return a defanged version of that IP address. A defanged IP address replaces every period "." with "[.]". Example 1: Input: address = "1.1.1.1" Output: "1[.]1[.]1[.]1" Example 2: Input: address = "255.100.50.0"...
ea9376c8ab589ad95bfe697b0f88a3a877a80947
emersonrs01/faculdade.Python
/17_04/exercicio04.py
176
3.71875
4
y=int(input("digite o valor de y: ")) cont=0 for i in range (1,y+1): if(y%i==0): cont=cont+1 if(cont==2): print(y,"e primo") else: print(y,"nao e primo")
51056ed25e869e90e2dbb71314947dae1d2c2a67
luiz158/basics-of-python
/wall_painting.py
1,451
4.4375
4
#calculate the number of cans required to paint the area of wall #user should enter the height and width of the wall in meters #calculate the area and then calculate the number of cans required #formula for calculating the number of cans = 1 can = 5 meters square area of wall # height = 2 width = 4 -> no of cans = (2X4...
5df40a384fe2cf48390acb9d516dfd6f9c8e4c9c
BraeWebb/mit6.00.2
/quiz/p4.py
1,253
3.90625
4
def greedySum(L, s): """ input: s, positive integer, what the sum should add up to L, list of unique positive integers sorted in descending order Use the greedy approach where you find the largest multiplier for the largest value in L then for the second largest, and so on to ...
8e905538dad87b0f4a64203305faa4b6c7535d27
FT3006-OOP/OOP-TI3C
/A2.1900196/#09 - Encapsulasi/main.py
1,458
3.765625
4
@@ -0,0 +1,32 @@ class Hero: def __init__(self, name, health, attackPower): self.__name = name self.__health = health self.__attPower = attackPower # getter def getName(self): return self.__name def getHealth(self): return self.__health # setter def d...
2beca4cc4b58c059be14fe0762f4b3463aaa6084
romeroRigger/Mimic
/mimic/scripts/robotmath/transforms.py
4,036
4.0625
4
#!usr/bin/env python """ Basic transforms for vectors, quaternions, and euler angles. """ import math def quaternion_conjugate(q): """ Computes quaternion conjugate :param q: Quaternion :return: """ return [q[0], -q[1], -q[2], -q[3]] def quaternion_multiply(q, r): """ Computes quate...
9f0aecf1cbffa8e3e3187cf41654b2126691a0a3
MoniqueMoreira/FolhaPagamento-Refactoring
/Registro.py
1,601
3.75
4
from NullEmpregado import NullEmpregado import pickle class Registro(): #lista para armazena emp_cadastrados = pickle.load(open( "emp_cadastrados.pickls", "rb" )) agenda_disp = pickle.load(open( "agendas_disp.pickls", "rb" )) #Funções internas def atul_lista(): Registro.emp_ca...
e2ef592449c4d6e2e018bff18cbc69857fa7801a
muamala/fundamental-python
/fundamental3-tipe-data-dict.py
978
3.546875
4
""" Tipe data dictionary sekedar menghubungkan antara KEY dan Value KVP = Key Value Pair Dictionary = kamus """ kamus_ind_eng = {'anak': 'child', 'istri': 'wife', 'ayah': 'father', 'ibu': 'mother'} print(kamus_ind_eng) print(kamus_ind_eng['ayah']) print(kamus_ind_eng['ibu']) print('Data ini dikirimkan oleh server Go...
638697de79bb1ef9f9394b9aef69845cd05017fb
HopeCheung/leetcode
/leetcode-first_time/leetcode417(Pacific Atlantic Water Flow)_DFS.py
3,359
3.671875
4
class Solution(object): def pacificAtlantic(self, matrix): """ :type matrix: List[List[int]] :rtype: List[List[int]] """ if len(matrix) == 0 or len(matrix[0]) == 0: return [] visited = [[True for j in range(len(matrix[0]))] for i in range(len(matrix))] ...
3438529ed3d81ba685194564ead305335120a56a
surajgholap/python-Misc
/Amazing_no.py
1,133
4.375
4
"""Define amazing number as: its value is less than or equal to its index. Given a circular array, find the starting position, such that the total number of amazing numbers in the array is maximized. Example 1: 0, 1, 2, 3 Ouptut: 0. When starting point at position 0, all the elements in the array are equal to its inde...
1f1374bce39cade7b3939c980fa37c5e67a3ac23
aindrila2412/DSA-1
/Booking.com/two_out_of_three.py
1,235
4.375
4
""" You have three Arrays. A = {2, 5, 3, 2, 8,1} B = {7, 9, 5, 2, 4, 10, 10} C = {6, 7, 5, 5, 3, 7} make an array from this three arrays which elements is present in at least two array. Return the sorted list of numbers that are present in at least 2 out of the 3 arrays. This question was followed by instead of thre...
6975451557bf3a92750936da4b0c0d6c1403253b
kate-melnykova/LeetCode-solutions
/LC1619-Mean-of-Array-After-Removing-Some-Elements.py
2,980
3.765625
4
""" Given an integer array arr, return the mean of the remaining integers after removing the smallest 5% and the largest 5% of the elements. Answers within 10^(-5) of the actual answer will be considered accepted. Example 1: Input: arr = [1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,3] Output: 2.00000 Explanation: After era...
753ae9a3295948693755e41676baf661ad771d91
orphefs/muselearn
/src/utils/parsers.py
2,200
3.703125
4
from pathlib import Path from muselearn.src.helpers.errors import FileExistsError2 def input_file_path(directory: str, file_name: str) -> Path: """Given the string paths to the result directory, and the input file return the path to the file. 1. check if the input_file is an absolute path, and if so, ...
d1425a4ef747ba5257c74b380576e8cfa1b5fb2d
Degdevs/Python3-code
/TicTacToe/game.py
5,906
3.9375
4
import random #Definiendo funciones def dibujarTablero(tablero): # tablero es una lista de 10 cadenas representadas en la pizarra print(' ' + tablero[7] + ' | ' + tablero[8] + ' | ' + tablero[9]) print('-----------') print(' ' + tablero[4] + ' | ' + tablero[5] + ' | ' + tablero[6]) print(...
f00e33561ecfa4ffc12c7e30110a44777fccfae5
jlhg/rosalind-solution
/dna/dna.py
790
4
4
#!/usr/bin/env python # # dna.py # # Copyright (C) 2013, Jian-Long Huang # Author: Jian-Long Huang (jianlong@ntu.edu.tw) # Version: 0.2 # # http://rosalind.info/problems/dna/ # # Usage: dna.py <input> def main(finput): """Counting DNA nucleotides finput: input file that contains a DNA string """ nucl...
841ed287781c229c9c5e8c4fcee2579ed60aa381
AroopN/LeetCode-Solutions
/Python/146_LRUCache.py
2,136
3.53125
4
class Node: def __init__(self, key, val): self.key = key self.val = val self.prev = None self.next = None class LRUCache: def __init__(self, capacity: int): self.front = None self.rear = None self.ref = dict() self.n = 0 self.capacity = c...
7afad8a66be9eb61e7b083fc7dc7886ecc93d89a
Vlad-Harutyunyan/Python450-advance
/week0/Nairi/homework0/problem7.py
727
4.125
4
import re def word_count(stri): #remove with regular expression # stri = re.sub(r'[^\w\s]','',stri) #or we can wihout using additional lib punctuations = '''!()-[]{};:'"\,<>./?@#$%^&*_~''' removed = "" for char in stri: if char not in punctuations: removed = removed + char ...
b75a4981d3eac1baef0b743fc580a455353f6550
jd6th/LearnPythonTheHardWay3
/ex18.py
488
3.609375
4
#this one is like your scripts def print_two(*args): arg1, arg2 = args print(f"arg1: {arg1}, arg2: {arg2}") #ok, the *args are actually pointless, we can do just this def print_two_again(arg1, arg2): print(f"arg1: {arg1}, arg2: {arg2}") #this just takes one argument def print_one(arg1): print(f"arg1: {arg1...
a88d661216d3b1eaf26db62318dfe6be44e926e7
KadirTaban/OOP
/oop_2.py
1,005
3.578125
4
class calisan: zam_oranı = 1.05 per_say = 0#class içindeki tüm objeleri etkileyen parametreler def __init__(self,ad,soyad,maas): self.ad = ad self.soyad = soyad self.maas = maas self.eposta = self.ad+self.soyad+"@sirket.com" calisan.per_say+=1 def t...
1393f91bb675e3ffde60da0ee07ca83b2870b9fa
qmnguyenw/python_py4e
/geeksforgeeks/python/python_all/51_9.py
3,041
4
4
Python – Extract Maximum Keys’ value dictionaries Given a dictionary, extract all the dictionary which contains a any key which has maximum values among other keys in dictionary list. > **Input** : [{“Gfg” : 3, “is” : 7, “Best” : 8}, {“Gfg” : 9, “is” : 2, > “Best” : 9}, {“Gfg” : 5, “is” : 4, “Best” : 10}, ...
7c6183e3eac7a7e30959efc49f5603ddd83283b1
Tiger-Dong/Learn_Python2
/program1/myy1.py
507
3.890625
4
# 1 # print("Hollow wold") # # 2 # print(" ^") # print(" /|") # print(" / |") # print(" / |") # print("/___|") # # 3 # character_name = "Tom" # #character_age = "45" # character_age2 = 45 # print("Once there was a man name " + character_name + ",") # print("He is " + str(character_age2) + " years old.") # print(...
89f23c871219555df37b01a4337a4153e8ed097d
WilliamPerezBeltran/studying_python
/clases-daniel_python/pequenos_proyectos/gestor_de_clientes/gestor/menu.py
982
3.6875
4
import helpers import manager def loop(): while True: helpers.clear() print("=================") print("BIENVENIDO AL GESTOR") print("=================") print("[1] Listar clientes") # listeme todos los clientes print("[2] Mostrar clientes") print("[3] Añadir clientes") print("[4] Modi...
de011484876f475187ae8318211c7c52b1de92a6
Cartmanfku/Hackerrank
/python/sortings/quicksort_inplace.py
685
3.71875
4
def partition(c,left,right,pivotidx): pivot = c[pivotidx] storeidx = left for i in range(left,right): if c[i] > pivot: continue else: c[i],c[storeidx] = c[storeidx],c[i] storeidx = storeidx + 1 else: c[storeidx],c[pivotidx] = c[pivotidx],c[sto...
1279ddab726153ae3c2384b950bb9ca47084e7e2
Rohini-Vaishnav/list
/logical ques1.py
115
3.515625
4
list=[4,9,8,7,6] i=0 while i<len(list): if list[i]==8: print(list[i]) elif list[i]==7: print(list[i]) i=i+1
2e8cf278dd6e65b41c8bf47f24b3b45ad072c345
alda07/hackerrank
/03.Python/15.Concatenate.py
629
3.53125
4
#import numpy # array_1 = numpy.array([1, 2, 3]) # array_2 = numpy.array([4, 5, 6]) # array_3 = numpy.array([7, 8, 9]) # print(numpy.concatenate((array_1, array_2, array_3))) # import numpy # array_1 = numpy.array([[1,2,3], [0,0,0]]) # array_2 = numpy.array([[0,0,0], [7,8,9]]) # print (numpy.concatenate((array_1,...
a18e136916c47312f783792eae0187e262749e8f
y33-j3T/FEEG1001-Python-for-Computational-Science-and-Engineering
/L02/L2Q6.py
212
3.96875
4
def seconds2days(n): ''' Given parameter n, convert the number n of seconds into the corresponding number of days ''' return n/60/60/24 print(seconds2days(43200))
21ea991fb76fd69cd5927dae0b6b4f6350d7731a
thumphries/python
/codeforces/watermelon.py
1,660
3.984375
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # http://codeforces.com/problemset/problem/4/A # A. Watermelon # time limit per test1 second # memory limit per test64 megabytes # inputstandard input # outputstandard output # # One hot summer day Pete and his friend Billy decided to buy a # watermelon. They chose the bi...
1eed8e4956fff6c1e99a44e316dda4e51a8b000c
junebash/Sprint-Challenge--Data-Structures-Python
/names/singly_linked_list.py
2,108
3.9375
4
class ListNode: def __init__(self, value=None, next_node=None): self.value = value self.next_node: ListNode = next_node class LinkedList: def __init__(self, head=None): self.head = head self.tail = head self.length = 0 if head is None else 1 def __len__(self): ...
598a89a766fbe4f6d4fd7b310ca681dcd14fd291
ishaansharma/ProblemSolving_Python
/1. Min Amplitude.py
1,006
4.09375
4
"""Question 1: Given an Array A, find the minimum amplitude you can get after changing up to 3 elements. Amplitude is the range of the array (basically difference between largest and smallest element). Example 1: Input: [-1, 3, -1, 8, 5 4] Output: 2 Explanation: we can change -1, -1, 8 to 3, 4 or 5 Example 2: Input...
8e24874b4be0a34f220f49e99ddba96c04bd24d9
alexzwir/python-studing
/control-flow/functions.py
626
3.5
4
# def add(a,b): # return a + b # x = add(a=1000000,b=2) # print(x) # m = ['Alex', 29, 'São Paulo - SP', 'Brasil', 'Av. Paulista'] # print(m) # x = input('Escreva algo que iremos colocar na lista a seguir: ') # def append_zero(lst=None): # if lst == None: # lst=[] # lst.append(x) # return lst # m_new = [] ...
e5615fe658731b659339cc00c468ba44dc90e7cc
mhoare/GraphTraversal
/Graph.py
2,163
4.03125
4
import collections import math from Dijkstra import * class Graph: def __init__(self): self.vertices = set() self.edges = collections.defaultdict(list) self.weights = {} def add_vertex(self, value): self.vertices.add(value) def add_edge(self, from_vertex, to_vertex, weigh...
33b9f957af0ee0131d5ac07899595c9fa21d6198
Redster11/NGCP_UGV_2019-2020
/ReferenceCode/Jeff/test1/controllers/e-puck_collision_avoidance/e-puck_collision_avoidance.py
3,328
3.578125
4
from controller import Robot, Motor, DistanceSensor, Camera, Keyboard, GPS, Compass import math # create the Robot instance. robot = Robot() # get the time step of the current world. timestep = 64 maxSpeed = 6.28 leftSpeed = 0 rightSpeed = 0 heading = 0 leftMotor = robot.getMotor('left wheel motor') rightMotor =...
84d695da5e0f0fb0d80c600e745f1726d9b39ed2
sxwd4ever/UQSTEPS_modelica
/src/python/ex/random-search-example.py
5,452
3.796875
4
from random import Random, random, randrange # function to optimize: takes in a list of decision variables, returns an objective value # this is the Rosenbrock function: http://en.wikipedia.org/wiki/Rosenbrock_function # the global minimum is located at x = (1,1) where f(x) = 0 def my_function(x): return (1-x[0])...
e22988c498e7da56ae76a13980e0cc4cdd4d4b40
Ali007baloch/hacktoberfest-2020
/python/Dijkstra.py
2,699
4.125
4
class graph: def __init__(self,n): #self.vertices=int(input("Enter number of Vertices: ")) self.vertices=n self.adj=[] for i in range(self.vertices): temp=[-1 for j in range(self.vertices)] self.adj.append(temp) print("The Nodes are Numbered as 0,1,2,3...
b5e45f6638a1e0a8cbdff539fc05fc7e18fa4b64
aka-luana/AulaEntra21_Luana
/Outros/Udemy/06.py
327
3.875
4
import random #----- Para dar o mesmo resultado sempre é usado o .seed() #numero2 = random.seed(1) #----- Para sortar um numero aleatorio entre o 0 e o 10 #numero = random.randint(0, 10) #print(numero) #----- Sorteia/escolhe um numero dentro de uma lista lista = [1, 20, 5, -60] numero = random.choice(lista) print(nu...
da77b617be93830ce209b0a304b3313b4f1eac6e
daniel-reich/turbo-robot
/87YxyfFJ4cw4DsrvB_13.py
1,054
4.0625
4
""" Create a function that takes in parameter `n` and generates an `n x n` (where `n` is odd) **concentric rug**. The center of a concentric rug is `0`, and the rug "fans-out", as show in the examples below. ### Examples generate_rug(1) ➞ [ [0] ] generate_rug(3) ➞ [ [1, 1, 1], [...