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
48d2fe2df2355969ac7e2545d4a634aa36b34250
erik-t-irgens/algorithmic-toolbox-assignments
/lcm.py
451
3.859375
4
# Uses python3 import sys def lcm_naive(a, b): for l in range(1, a*b + 1): if l % a == 0 and l % b == 0: return l return a*b def compute_gcd(x, y): while(y): x, y = y, x % y return x # This function computes LCM def compute_lcm(x, y): lcm = (x*y)//compute_gcd(x,y) re...
fecf0c1cffc0eb53850f947ea9647e17da7c5e93
yusufferdemm/PythonApps
/[9]AtmProgram.py
908
3.984375
4
print(""" **************************** Welcome to ATM Program! Operation; 1.Balance inquiry 2.Pay Into 3.Withdraw Money Press 'q' to exit the program. **************************** """) balance=1000 while True: operation = input("Select Action:") if operation == "q": print("We hope you come again."...
f3e804a8e5b5889d2e7ab322d9a7203b8c9f936f
lbmello/router-config
/routerconfig/queue/queue.py
1,763
3.9375
4
"""Modulo Queue.""" from .node import Node class Queue: """Gerencia a fila.""" def __init__(self): self.first_element = None self.last_element = None self.size = 0 def push(self, element): """ ADICIONA ELEMENTOS NA FILA. """ node = Node(element) ...
c99442ed74dca0dde9268e1c513f144b53498e9f
mutasimm/Bookleted
/Bookletify.py
3,232
3.71875
4
# Reorders the pages of a pdf file and makes a 1 x 2 pdf in booklet format. The pages are arranged in sets 32 pages (8 sheets of paper). # Permutation of the pages of a set of 32 pages, divided among 8 sheets of paper. This could also be done with the seq4KGen function by setting k = 8, but the permutation is shown he...
08753b84546689ef314d17e24122ed5be0f9c0e3
mukunddubey10000/DubeyCoin
/dubeycoin_node_5001.py
7,450
3.875
4
"@author : Mukund" "Cryptocurrency" "Uses Flask and Postman" import datetime "To get exact date the blockchain was created" import hashlib "To use Hash functions to hash blocks" import json "To encode the blocks before hashing them" from flask import Flask, jsonify, request #request->connect nodes import requests from ...
69b93afa6c9792b6f336e928eb500133674eceff
ponickkhan/unix
/assignment4.py
1,308
3.609375
4
# Name : Md.Rafiuzzaman Khan # ID : 011161017 # Students Result Data student_info = { "Md. Hasan": 92, "Mehrub Hossain": 20, "Md.Rafiuzzaman Khan": 81, "Samiul Ahmed": 67, "Pranto Shikdar": 56, "Nusrat Jahan": 38, "Hasibul Haque": 75, "Abir Hasan": 66, "Tamanna Afroz": 30, "Mo...
84c109154914f003b7e45be2c2723a4a4e21c952
OrlovaNV/learn-homework-2
/2_files.py
1,185
3.9375
4
""" Домашнее задание №2 Работа с файлами 1. Скачайте файл по ссылке https://www.dropbox.com/s/sipsmqpw1gwzd37/referat.txt?dl=0 2. Прочитайте содержимое файла в перменную, подсчитайте длинну получившейся строки 3. Подсчитайте количество слов в тексте 4. Замените точки в тексте на восклицательные знаки 5. Сохраните ре...
8ccf9ed5fa5853951c3aae5a44d3286d8fd83076
gachikuku/simple_programming_python
/elementary/elementary9.py
898
4.1875
4
#!/usr/bin/env python3 """ Write a guessing game where the user has to guess a secret number. After every guess the program tells the user whether their number was too large or too small. At the end the number of tries needed should be printed. It counts only as one try if they input the same number multipletim...
e3c80f54458d9a5a4d3834d20ac75ce87f5e049c
MaZdan6/workspacePython-InzynieriaOprogramowania
/Python_lab/lab_09/zad1_T1.py
1,052
3.890625
4
from Python_lab.lab_09.zad1 import Bibltioteka '''' #input numberOfBooks=5; listOfBooks=[]; tuple0=("Chatka Puchatka" , "Alan A . Milne" , 2014 , (2014 , 4, 10)); tuple1=("Quo Vadis" , "Henryk Sienkiewicz" , 2010 , (2014 , 1 , 15)); tuple2=("Chatka Puchatka" , "Alan A . Milne" , 1998 , (2013 , 12 , 31)); tuple3=("Pan...
4fc021edcc67f6c2f9e019c925cde36e77c0f067
BugChef/yandex_alghoritms
/sprint5/binary_search_tree.py
479
3.6875
4
class Node: def __init__(self, value, left=None, right=None): self.value = value self.right = right self.left = left def solution(root: Node) -> bool: stack = [] prev = None while root or stack: while root: stack.append(root) root = root.left ...
64e29c11d950e9f9f6907e35c67a596a0e64c090
tcheung99/ML_Projects
/a3_mod.py
4,787
3.765625
4
import autograd.numpy as np from autograd import value_and_grad def forward_pass(W1, W2, W3, b1, b2, b3, x): """ forward-pass for an fully connected neural network with 2 hidden layers of M neurons Inputs: W1 : (M, 784) weights of first (hidden) layer W2 : (M, M) weights of second (hidden)...
9bc55c95ba9cf0d9bae78c97428cfd59245ec553
AnzhelikaD/PythonLabs
/Davidenko_5_14.py
652
4.0625
4
"""Дано действительное x . Вычислить приближенное значение бесконечной суммы""" def infSum(x, exp): elem = x step = 1 sumElems = elem if abs(elem) > exp else 0 while abs(elem) > exp: step += 2 elem = x**step / step sumElems += elem return sumElems x = float(input("Введите...
3eb195847354ecf515cab8db61df7145945cfa1e
KJabbusch/Codecademy-Practice
/sparse_search.py
1,641
4.0625
4
def sparse_search(data, search_val): # Printing out the data set print("Data: " + str(data)) # Printing out what we are looking for print("Search Value: " + str(search_val)) # Create two variables. first being the start index and last being end index. first = 0 last = len(data) - 1 # Continuous loop...
b48bfad4893acf4259175f369c6dce3dced850b4
Stefanh18/python_projects
/mimir/assingnment_10/q3.py
546
4.1875
4
# Your functions should appear here def triple_list(a_list): outcome = a_list * 3 return outcome def populate_list(a_list): new = True while new == True: user_input = input("Enter value to be added to list: ") if user_input.lower() == "exit": new = False else: ...
2b1240ad035e5d8fbd80da15afc6fd6d967a02fa
nwyche9/my_converters
/Converters.py
4,769
4.3125
4
#Main screen #Currency converter def currency(): user_choice = input("Dollars to Euros? choose D. \nDollars to Pounds? choose P. \nDollars to Chinese Yuan? choose C. \nDollars to Japanese Yen? choose J. \nExit? choose E. ") while user_choice != "E".lower(): if user_choice == "D".lower(): ...
4ed2d9c6fc8f1bf2aa37fc735e97879f767f49cc
MasatakeShirai/Python
/chap8/8-1.py
1,078
4.40625
4
#条件分岐 #if-then-else a=1 if a>0: print(True) else: print(False) #else-ifパート # 複数条件を評価する場合は,elifを使う n=5 if n<0: print('n<0') elif n==0: print('n==0') elif n==5: print('n==5') elif n<10: print('n<10') else: print('else') #条件式 #無や負に相当するものはfalse,1や実体の存在するものはtrueになる print(bool('')) print(bool('p...
faa145a8d07f0e3e0b84b31503ef3a931b85f52e
afeefebrahim/anand-python
/chap2/ex5.py
221
4.1875
4
#a function name 'reverse' to reverse a list def reverse (num): rev = [] i=0 while i < len(num): rev.insert(i,num.pop()) i=i+1 return rev print reverse([1,2,3,4,5]) print reverse(reverse([1,2,3,4,5]))
0cb7915d02a35fc6a2e3df7267ac7fc8d21de198
Divya9j/testyp
/MultiDimLists/sum2D.py
232
3.546875
4
def sum2D(dlist): tot = 0 for i in range(0,len(dlist)): for j in range(0,len(dlist[i])): #print(dlist[i][j]) tot = tot + dlist[i][j]; return tot print(sum2D([[1, 2, 3, 4], [1, 2, 3, 4]]))
c7c8ab89a7b793934c71a36536cb5c349050004c
OwnNightmare/CookBook
/resultant.py
1,993
3.515625
4
class File: new_str_sign = '\n' def __init__(self, name, path='sort_in_file/'): self.content = '' self.length = 0 self.name = name self.path = path def reading(self, mode='r', buffering=1, encoding='utf8'): with open(self.path + self.name, mode, buffering, encoding)...
8820a11caf563da68ef1c587730123a2f4d6c357
lwoiceshyn/leetcode
/longest-common-subsequence.py
1,775
4.15625
4
''' https://www.hackerrank.com/challenges/dynamic-programming-classics-the-longest-common-subsequence/problem ''' ''' The recursive formula for this problem is as follows. Define the two inputs as sequence a of length n, and sequence b of length m. There are three potential cases when examining these two sequences. ...
316bb890e07a121f1f52cded921bd348252bd526
kokje/insight_challenge
/src/median.py
1,426
3.9375
4
import sys uniquewordcounts = [0] * 140 def readTweets(inputfile, outputfile): """ Read tweets and use a hashmap with entries as count of unique words to determine median """ try: f = open(inputfile, 'r') o = open(outputfile, 'w') count = 0 for tweet in f: #Read tweets and use a set to get count of uniqu...
2c57d04757f3e042dd12eb733f710fca4d4674a9
shen-huang/selfteaching-python-camp
/exercises/1901020006/d07/mymodule/stats_word.py
2,336
3.890625
4
# 封装统计英文单词词频的函数 def stats_text_en(text): elements = text.split() words = [] symbols = ',.*-!' for element in elements: for symbol in symbols: element = element.replace(symbol,'') # master # 用 str 类型的 isascii 方法判断是否是英文单词 if len(element) and element.isascii: #======= ...
75698837e7212a6a5ad86da3db319d291fc2647e
Robert0202/Atividades
/Algoritmo_Logica/Lista_For/q10.py
346
4.125
4
media = 0 for x in range (1, 31): n = int(input(" informe a nota final: ")) media += n if x == 0 : maior = menor = n else: if maior <n: maior = n elif menor > n: menor = n media = media / 30 print(" media da turma ", media) print(" maior nota ", maior) pri...
39086fa0bc9b7fcc75c46ad7e263ac523a18680a
16044037/secu2002_-16044037-
/lab04/strings.py
1,399
4.15625
4
#Task 1 #Example 1 of the string mysep.join(mylist) #Define my list with a list of colours mylist = ['blue', 'pink', 'purple', 'red', 'green'] #Define a separator as a space mysep = ' ' print 'should return: blue pink purple red green' print 'is returning', mysep.join(mylist) print '-------------' #Example 2 of the s...
9cc5867beb9e1182b0e8ad2d8c318246a6dc2881
rnaster/python-study
/closure.py
876
3.53125
4
""" closure the following class and two functions are same. """ class Average1: def __init__(self): self.series = [] def __call__(self, new_value): self.series.append(new_value) return sum(self.series) / len(self.series) def average2(): series = [] def average(new_value):...
ddc3d8778a07f2223a25b8adfa49867f5f947cc6
VanceJarwell/pythonActivities
/CH0708/Exercise1.py
164
4.1875
4
def backwards(word): index = len(word) - 1 while index >= 0: print(word[index]) index -= 1 word = input("Enter a word: ") backwards(word)
56ec7f9f799fe13f505baca20636fd205e261039
lima-BEAN/python-workbook
/programming-exercises/ch2/stock-transaction.py
2,110
3.65625
4
## Last month Joe purchased some stock in Acme Software Inc. Here are the ## details of the purchase: ## - The number of shares that Joe purchased was 2,000 ## - When Joe purchased the stock, he paid $40.00 per share. ## - Joe paid his stockbroker a commission that amounted to 3 percent of the ## amount he paid for t...
c4dbde0f8ef90f7a6adbf42804f2c0ea13726541
miaojia527/python
/cipher.py
426
3.625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- def translationCipher(msg,key): result = [""]*key for i in range(key):#把每一列元素按照顺序相加组成新的字符序列 pointer = i while i<len(msg): result[pointer]+=msg[i] i+=key return ''.join(result) def main(): print translationCipher("hello,world",4)#以4个字母为一行进行...
b444bb4e43efc2e4f97b34272788f825827cbc4b
DanyHe/test
/条件判断.py
1,790
3.640625
4
#if-elif-else #С1.7580.5kgBMIʽسߵƽСBMIָBMIָ #18.5 #318.5-25 #25-28 #28-32 #32ط height = 1.75 weight =83 BMI =weight/(height*height) if BMI > 32: print('ط') elif BMI > 28: print('') elif BMI > 25: print('') elif BMI >18.5: print('') else: print('') #ѭ names = ['jack','jones','lily'] for name in...
de7c96a7f9acd86619dc8f3c2a0b07103ad9e410
ghwlchlaks/old_otter
/appFolder/wordcount_search1.py
785
3.515625
4
from pyspark import SparkContext import argparse #spark context sc = SparkContext() #make & receved outer argument parser = argparse.ArgumentParser() parser.add_argument("--file", help=": file name") parser.add_argument("--user", help=": user name") parser.add_argument("--word", help=": search word name")...
8dca8295b70ee195f727e222699ef9a3fcd76831
prasant73/python
/programs/dictionaries.py
716
3.96875
4
from inputs import list_input def add_list_to_dict(l1,l2): d = {} # for i in range(len(l2)): # d[l1[i]] = l2[i] # print(i) # for i in range(i+1, len(l1)): # d[l1[i]] = 0 # return d for i in range(len(l1)): if i < len(l2): d[l1[i]] = l2[i] else: ...
40c280d22825da95cc72e7d18dfb239c7552109b
apurbahasan1994/Algo
/coin_change.py
836
3.625
4
coin=[1,2,5] sum=5 n=3 # def coin_chnage(sum,n): # if n==0 and sum==0: # return 1 # if n == 0: # return 0 # if sum == 0: # return 1 # # if coin[n-1]<=sum: # return coin_change(sum,n-1)+coin_chnage(sum-coin[n-1],n) # else: # return coin_chnage(sum,n-1) # # pri...
ab3d04960496ed1abe06ade6914bc72af749bd9f
rishcodelib/PythonPro-Bootcamp2021
/Day1/main.py
249
4.3125
4
# Band Name Generator # Project 1 ("String Concatenation in Python") print("Welcome to the Band name Generator") city = input("Enter city name?") petname = input("enter your petname ") print(" Your Band Name Could be: " + city + " " + petname)
e1f7604c2af82efc8b01127deb2cf4e454a25fa0
scikit-learn-contrib/imbalanced-learn
/examples/over-sampling/plot_shrinkage_effect.py
3,929
4
4
""" ====================================================== Effect of the shrinkage factor in random over-sampling ====================================================== This example shows the effect of the shrinkage factor used to generate the smoothed bootstrap using the :class:`~imblearn.over_sampling.RandomOverSamp...
67dc20d09ea74741a12722ce73db8ea4f11d9935
seanloe/PythonHome
/Python_Execercises/mytest.py
2,360
3.828125
4
#! /usr/bin/env python # -*- coding: utf-8 -*- import numpy as np import threading,time, copy from queue import Queue class Myclass: species = 'human' def __init__(self, name, gender,age): self.name = name self.gender = gender self.age = age def run(self): print(self.name,...
b22dd2f585507c90d469cfbb6fcdc71bca015f1b
LourdesOshiroIgarashi/algorithms-and-programming-1-ufms
/Lists/Lista 1/Lourdes/10.py
254
3.546875
4
lista = [] n = int(input()) for i in range(n): lista.append(int(input())) print(lista) if n % 2 == 0: elemento1 = n//2 - 1 elemento2 = n//2 print(lista[elemento1], lista[elemento2]) else: elemento = n//2 print(lista[elemento])
349e660ba3bd9db92efeb584f57e7027e8e5fe6a
pathakamaresh86/python_class_prgms
/oop_complex.py
2,546
3.6875
4
#!/usr/bin/python class complex: #constructor def __init__(self,real=0,img=0): self.real=real #object attribute self.img=img #object attribute #destructor def __del__(self): #print "Destructing self", self print def add2ComplexNo(self,c1): c3=complex() if type(c1)==int:#if isinst...
f4a9a5e7352b60dc4ad3cf4f52606730fb13e006
platform6/ga_python
/class_notes/W4/day-01/2.py
1,007
3.90625
4
# -*- coding: utf-8 -*- """ Created on Tue Oct 6 18:03:08 2020 @author: platf """ class HR: def __init__(self): self.__name = None self.__age = None self.__address = None def __set_name(self, name): self.__name = name def __get_name(self): return self.__name ...
f83bb455bee33575ec2da2479fd28893e9954345
xiaogy0318/coding-exercises
/python/copy_array.py
526
3.84375
4
#"Write a function with the following specification: Input: a list. Output: a copy of the list with duplicates removed." #from array import array array1 = [] array2 = [] count_string = raw_input("Number of strings please (default is 3): ") count = 3 try: count = int(count_string) except ValueError: count = 3 for i in...
2823e46f466450230dfb1f70ebc292d2f4b940b6
Salor69/CS01-Salor
/CS01-Max Min.py
197
3.90625
4
Num = int(input('Enter Your Loop: ')) Numtotal = [] for i in range(Num): num = int(input('Enter Your Number:')) Numtotal += [num] print(Numtotal) print(min(Numtotal)) print(max(Numtotal))
e1beaa798985f64ed3adf77bcbea76edf45295b0
consbio/trefoil
/trefoil/utilities/format.py
1,253
3.5625
4
import numpy MAX_PRECISION = 6 class PrecisionFormatter(object): """ Utility class to provide cleaner handling of decimal precision for string outputs """ def __init__(self, values, max_precision=6): """ Extract the maximum precision required to represent the precision of v...
8acf366a767976cdfd3a3fb5ea7d04eafaaf1705
Shubham8037/Project-Euler-Challenge
/Problem 1 - Multiples of 3 and 5/Problem_1.py
1,090
4.4375
4
#!/bin/python3 """ If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below the provided parameter value number """ def solLogic(multipleOf, actualRange): # Range is updated since problem ...
349712a5d78871e464ccbe83605a59995e081a3d
KingGenius5/Tech-Int-Prac-Prob
/coding-syntax/find_duplicates.py
238
3.890625
4
def find_duplicates(list): rep = {} for item in list: if item in rep: return item else: rep[item] = 1 if __name__ == "__main__": list = [0,2,2,3,4,5,7] print(find_duplicates(list))
f983071afdc326e07f7ca4b84b626ada972ddb36
harshv47/Artemis-arrow
/songs/youtube.py
527
3.578125
4
import playlist as pl import songs as sg def single(service,playlist_id,song): """ A single song is added to the playlist represented by the playlist id if it is not already present """ song_id = sg.video_id(service,song) playlist_songs_id = pl.playlist_list(service,playlist_id) ...
283e668c8583c7240947d907f49fad5a612ef355
TinkerGen/bit_maker_lite_covid_prevention
/bitmaker_covid.py
3,580
3.625
4
from microbit import * import time import speech class Servo: """ A simple class for controlling hobby servos. Args: pin (pin0 .. pin3): The pin where servo is connected. freq (int): The frequency of the signal, in hertz. min_us (int): The minimum signal length supported by the ser...
3cf09e2f06f9b101b721eed53268aff53b56fdb8
kameronlightheart14/projects
/DataCollection/WebTechnologies/web_technologies.py
10,212
3.625
4
# web_technologies.py """ Kameron Lightheart 9/7/19 MATH 403 """ import json import socket from matplotlib import pyplot as plt import numpy as np # Problem 1 def prob1(filename="nyc_traffic.json"): """Load the data from the specified JSON file. Look at the first few entries of the dataset and decide how to g...
0408aa6362540532e93737b5e1d8306aa725825f
rafaelpederiva/Resposta_Python_Brasil
/Exercícios de Estrutura de Repetição/Exercício 46 - Salto em Distância.py
2,023
3.765625
4
#Exercício 46 '''Em uma competição de salto em distância cada atleta tem direito a cinco saltos. No final da série de saltos de cada atleta, o melhor e o pior resultados são eliminados. O seu resultado fica sendo a média dos três valores restantes. Você deve fazer um programa que receba o nome e as cinco distâncias a...
daa51f7e7fcbc9b6f8bb8d46a00f043168b9b59d
Karenahv/holbertonschool-machine_learning
/math/0x00-linear_algebra/7-gettin_cozy.py
480
3.75
4
#!/usr/bin/env python3 """concatenates two matrix""" def cat_matrices2D(mat1, mat2, axis=0): """concatenates two matrix""" if (len(mat1[0]) == len(mat2[0]) and axis == 0): result = [] result += [elem.copy() for elem in mat1] result += [elem.copy() for elem in mat2] return resul...
d04a9d22a8c828a0df7b77b12c042fec9d2bd0f3
fxy1018/Leetcode
/41_First_Missing_Positive.py
265
3.640625
4
""" Given an unsorted integer array, find the first missing positive integer. For example, Given [1,2,0] return 3, and [3,4,-1,1] return 2. Your algorithm should run in O(n) time and uses constant space. """ ''' Created on Feb 20, 2017 @author: fanxueyi '''
53246242559337f536ea020acca15f9f7640aabb
BrechtVandevoort/AdventOfCode
/2020/day_08/day_08.py
1,187
3.65625
4
def simulate_code(instructions): acc = 0 visited = [] current_instr = 0 while current_instr not in visited and 0 <= current_instr < len(instructions): visited.append(current_instr) instr, value = instructions[current_instr].split() value = int(value) if instr == "acc": ...
f78ce98b80b05d278c214f68b8853d20937e4be0
vivekyadav6838/Data-Structures-and-Algorithms-for-Interviews
/Python/Recursion/Fiboanacci.py
159
4.0625
4
def fibonacci(n): if (n == 1 or n == 2): return 1 return fibonacci(n - 1) + fibonacci(n - 2) if __name__ == '__main__': n = 10 print(fibonacci(n))
19cc19da3564256299b2f0b4930e7aa7676ba0e1
sagynangare/I2IT
/class_ex1.py
236
3.59375
4
class Demo: def __init__(self, a, b): print('Demo is initialized.......') self.a = a self.b = b def display(self): print('A: ', self.a, '\n', 'B: ', self.b) obj= Demo(5, 8) obj.display()
9e244c6bcf51a91993e863be9b0375bec35fc13d
lunar-r/sword-to-offer-python
/leetcode/62. Unique Paths.py
1,838
3.640625
4
# -*- coding: utf-8 -*- """ File Name: 62. Unique Paths Description : Author : simon date: 19-3-26 """ class Solution(object): def uniquePaths(self, m, n): """ :type m: int :type n: int :rtype: int """ self.cnt = 0 # 如果是list 可以不用加sel...
485b9057d1fe88d2d8d8551d83134fcfd50767c0
KishoreMayank/CodingChallenges
/Interview Cake/Linked Lists/ReverseLinkedList.py
392
4.375
4
''' Reverse Linked List: Write a function to reverse a linked list ''' def reverse(head): curr = head prev = None next_node = None while curr: # iterate till the end next_node = curr.next # copy pointer to next node curr.next = prev # Reverse the 'next' pointer prev = curr...
0ecca80ef97f6c3b22629b79e5178b66a186487b
DaHuO/Supergraph
/codes/CodeJamCrawler/16_0_2/sebadzia/pancakes_revenge.py
1,075
3.5
4
def counter(function): def wrapper(*args): wrapper.called += 1 return function(*args) wrapper.called = 0 wrapper.__name__ = function.__name__ return wrapper @counter def flip(stack, index): left, right = stack[:index+1], stack[index+1:] return invert(left[::-1]) + right def inv...
409968b36f37b761d4a6c7a9d573f412aba008c2
viharivnv/DSA
/Hw_1_2/quickunion.py
2,209
3.625
4
#The code was run on PYCHARM IDE on WINDOWS python version 3.x ''' Steps to recreate: 1)Open PYCHARM 2)Create a new project 3) Add a new python file and paste the code 4) Run the code ''' import time file=input("enter the file name excluding '.txt' extension for example 8pair:\n") file=file+".txt" # referred "https://s...
c26a02e9ea461702f30d13cafcda0601aad3f4bc
cccccccccccccc/Myleetcode
/203/removelinkedlistitems.py
707
3.78125
4
# Definition for singly-linked list. class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def removeElements(self, head: ListNode, val: int) -> ListNode: if head is None: return head newhead = ListNode(0) cur = ...
6f287809f27bc8b180415811a0ff34cfdf60a758
Code-Institute-Solutions/proposed_myfirstserver
/4a-http_server_echo_styled_challenge.py
4,015
4.25
4
#!/usr/bin/env python3 """A very very basic http server""" # The socket library which lets us create network connections: import socket # The ip address to listen on: # 127.0.0.1 (aka localhost) only listens to requests from the local computer # while 0.0.0.0 accepts requests from entire network, and is needed in C9 I...
658582b1a3e69b45326b6e9ffd79f97da72f29b3
sirjoe29/basic-python-joe
/list.py
128
3.5625
4
mylist = [] mylist.append(10) mylist.append(12) mylist.append(20) print(mylist) print(len(mylist)) mylist[1] = 15 print(mylist)
b01dd2ccf1cb832b11cad275c9762bb62bdd9a93
snanoh/Python-Algorithm-Study
/graph/combine.py
536
3.890625
4
"""전체 수 n을 입력받아 k개의 조합을 리턴한다.""" from typing import List n,k = 5,3 def combine(n: int , k: int) -> List[List[int]]: results = [] def dfs(elements, start: int, k: int): if k == 0: results.append(elements[:]) # 자신 이전의 모든 값을 고정하여 재귀 호출 for i in range(start, n + 1): ...
f6c5aac53ec637cb564a9baf419e4fa4748c8f18
AIA2105/A_Practical_Introduction_to_Python_Programming_Heinold
/Python sheets/GUI6.py
533
3.921875
4
from tkinter import * def welcome(): outpt.configure(text='Welcome '+inpt1.get()+' !') root=Tk() label1=Label(text='Enter your name: ',font=(8)) label1.grid(row=0,column=0, padx=(20,0),pady=(20,0)) inpt1=Entry(width = 20,font=(8)) inpt1.grid(row=0,column=1, padx=(10,20),pady=(20,10)) btn=Button(comm...
30938ac4128e71d0477191619d851085327cdf53
Tester1313/Python
/Exercicio 4.py
1,159
3.78125
4
#Thiago Henrique dos Santos i = 9 candidato1 = 0 candidato2 = 0 candidato3 = 0 candidato4 = 0 nulo = 0 branco = 0 total = 0 print('Para o candidato A vote 1') print('Para o candidato B vote 2') print('Para o candidato C vote 3') print('Para o candidato D vote 4') print('Nulo vote 5') print('Branco vote 6') while i ...
3c32d6c8c436d9cf7734851e3d0d86a7e70f66b7
stungkit/Leetcode-Data-Structures-Algorithms
/06 Heap/719. Find K-th Smallest Pair Distance.py
1,108
3.984375
4
# Given an integer array, return the k-th smallest distance among all the pairs. The distance of a pair (A, B) is defined as the absolute difference between A and B. # Example 1: # Input: # nums = [1,3,1] # k = 1 # Output: 0 # Explanation: # Here are all the pairs: # (1,3) -> 2 # (1,1) -> 0 # (3,1) -> 2 ...
152abc8cc738659443907693895e27a33a4dfd70
SeungHune/Programming-Basic
/과제 2/실습 2-2.py
258
3.984375
4
def smaller(x,y): pass # fill your code here if (x>y): return(y) elif (x<y): return(x) else: return(x) print(smaller(3,5)) # returns 3 print(smaller(5,3)) # returns 3 print(smaller(3,3)) # returns 3
f0cec5bbb77f3601fba561251ee2be7fce5835d0
kundan8474/python-specialisation
/py4e/exercises/functions/pseudorandom.py
328
4.125
4
import random as r # range function iterates from 0 to argument in range # random generate a random number between 0.0 and 1.0 but excluding them for i in range(5): print(r.random(),'\n') # randint(min, max) will generate a random integer between min and max, including both for i in range(5): print(r.randint...
e92760e11557f20d81de486c4af048247d479d64
thirstfortruth/diving-in-python
/w2/generator_3.py
396
3.671875
4
def accumulator(): total = 0 while True: value = yield total print('Got: {}'.format(value)) if not value: break total += value generator = accumulator() next(generator) print('Accumulated: {}'.format(generator.send(1))) print('Accumulated: {}'.format(generator.send(2))) next(ge...
251f347edf6915a3256dd615dce646a6c4997dca
wkswilliam/challenges
/CSES/Sorting and Searching/ferris_wheel.py
641
3.90625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Aug 11 16:18:54 2020 @author: william """ def ferris_wheel(n, x, weight): weight.sort(reverse=True) # x maximum wei head = 0 tail = n -1 count = 0 while head <= tail: if weight[head] + weight[tail]<=x: count+=...
a3936122c2f25fa0f3b4883f7a8f595d7dcf5bbf
stevenhorsman/advent-of-code-2015
/day-24/hangs_in_the_balance.py
1,533
3.65625
4
import itertools, operator from functools import reduce input_file = 'day-24/input.txt' def does_remainder_split(weights, split_groups): target_weight = sum(weights) // split_groups for group_size in range(1, len(weights)): for group in [comb for comb in itertools.combinations(weights, group_size) if sum(comb...
4fe2f4c4652f1b178ebb1b185d610e763bdfb29c
Oussema3/Python-Programming
/equation.py
181
3.640625
4
def solve_eq(equation): x, add, num1, equal, num2 =equation.split() num1, num2 = int(num1), int(num2) return "x= " + str(num2 - num1) print(solve_eq("x + 23 = 196"))
f0b92e65e48bef75e52297cdf5af0525080d7986
hsindorf/madlib-cli
/madlibs/file_io.py
1,132
4.375
4
"""Functions for reading/writing files""" def read_file(filename): """ Reads file and returns output input: string, a filename to be opened output: string, the file contents """ if type(filename) is not str: raise TypeError('filename must be a string') try: with open(fil...
ffaf00899f4ddd2eb3ed9c87b6a1441ffffeb324
gabriellaec/desoft-analise-exercicios
/backup/user_286/ch162_2020_06_09_20_34_40_106192.py
311
3.53125
4
def verifica_lista(lista): if lista == []: return 'misturado' i = 0 p = 0 for num in lista: if num % 2 == 0: p += 1 else: i += 1 if p == 0: return 'ímpar' elif i == 0: return 'par' else: return 'misturado'
b69433fc6c318c8beb48090f9d0aa103b2a1984b
I82Much/TI-Tech-Tree-Helper
/scripts/topo.py
7,803
3.796875
4
from xml.sax.saxutils import escape from collections import defaultdict # Original topological sort code written by Ofer Faigon (www.bitformation.com) and used with permission def topological_sort(items, partial_order): """Perform topological sort. items is a list of items to be sorted. partial_order...
b1a83bcc944e46f8827f5390f5687c01467c636c
srinjoychakravarty/formula1_probability_distribution
/sports_analytics.py
10,489
3.6875
4
from bs4 import BeautifulSoup from urllib.request import urlopen class ProbDist(dict): """A Probability Distribution; an {outcome: probability} mapping.""" def __init__(self, mapping=(), **kwargs): self.update(mapping, **kwargs) # Make probabilities sum to 1.0; assert no negative probabilities ...
3e986e12dd1a19e7794c9b3def06b833b19d0695
littleyellowbicycle/pythonPrac
/printPrac.py
297
3.90625
4
# -*- coding: utf-8 -*- test="%r %r %r %r" print test %( "this", "is", "a", "test" ) print """ we can say "this is a test" lol ????? """ print "%r" %"\t" print "this is" print "a test" raw_input_A = raw_input("raw_input: ") input_A = input("input: ") print raw_input_A print input_A
3f0e34d8d383ed052cd70f78a70a85d98c428114
alchemyfordummies/march_madness_simulator
/marchmadness_2017.py
7,742
3.765625
4
import random import time #64-team tournament ~.75 seconds class Team: def __init__(self, n, s): self.__name = n; self.__seed = s; self.__games_won = 0; self.__upsets = 0; self.__teams_upset = []; def get_name(self): return self.__name def ...
b1fdc2281954caca8f46f450bd5eaae8de7189c2
TrangHo/cs838-code
/src/lib/features/feature09.py
777
3.515625
4
import re from lib.constants import prefixKeywords # Whether it has the keywords prefix: "receive", "degree", "M.B.A.", "master" # - Whether it has the prefix: "received a/an (M.B.A.)/(... degree) (in ...) from" # - and received a law degree from the <pos>University of Pennsylvania</pos> # - He graduated cu...
029b2ce6ee636e94d07b15904a527b8c0688a40a
Sirachenko12/Homework
/zadanie 4.py
110
3.625
4
n = int(input("Podaj liczbę całkowitą: ")) i = 1 while i <= n: print(i * i , end=' ') i += 1 print()
76ef203b71aab063c274874112bf94a78d8c1e8f
s3rvac/talks
/2018-03-05-Introduction-to-Python/examples/13-type-hints.py
440
3.671875
4
# The presence of type hints has no effect on runtime whatsoever. It is used by # source analyzers (e.g. http://mypy-lang.org/). # # Requires Python >= 3.5. def hello(name: str) -> str: return 'Hello ' + name hello('Joe') # Hello Joe hello(5) # Hello 5 # The type hints can be accessed via __annotations__: pri...
20b5a8c2bf021f2593103ae78594c3dbab8b90e5
HaydenInEdinburgh/LintCode
/829_word_pattern_II.py
1,265
3.8125
4
class Solution: """ @param pattern: a string,denote pattern string @param str: a string, denote matching string @return: a boolean """ def wordPatternMatch(self, pattern, str): # write your code here if not pattern or not str: return False p_to_word = {} ...
cc9c02f97a3876f94db67e57b6a15acedadb088e
evidawei/Hacktoberfest2021-2
/Python/sum_array.py
108
3.65625
4
def sum(arr): sum=0 for i in arr: sum+=i return sum arr=[] arr=[1,2,3] print(sum(arr))
c8062f2b17ec267f6aecab992882f9c64ddcf753
LEE2020/leetcode
/coding_reversion/687_samevaluepath.py
1,367
4.15625
4
''' 给定一个二叉树,找到最长的路径,这个路径中的每个节点具有相同值。 这条路径可以经过也可以不经过根节点。 注意:两个节点之间的路径长度由它们之间的边数表示。 示例 1: 输入: 5 / \ 4 5 / \ \ 1 1 5 输出: 2 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/longest-univalue-path 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 ''' # Definition ...
9086fd4f5f9a4843ddfc6a398fe544df1a626d79
wtrnash/LeetCode
/python/040组合总和II/040组合总和II.py
1,539
3.609375
4
""" 给定一个数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。 candidates 中的每个数字在每个组合中只能使用一次。 说明: 所有数字(包括目标数)都是正整数。 解集不能包含重复的组合。 示例 1: 输入: candidates = [10,1,2,7,6,1,5], target = 8, 所求解集为: [ [1, 7], [1, 2, 5], [2, 6], [1, 1, 6] ] 示例 2: 输入: candidates = [2,5,2,1,2], target = 5, 所求解集为: [ [1,2,2...
adf83a155f22d1d03ad3554378bdacd20b334c54
grockcharger/LXFpython
/slice.py
486
3.875
4
#!/usr/bin/env python in Linux/OS X # -*- coding: utf-8 -*- # 切片 # 1 L = ['Michael','Sarah','Tracy','Bob','Jack'] print L,"\n" print [L[0],L[1],L[2]],"\n" # 2 r = [] n = 3 for i in range(n): r.append(L[i]) print r,"\n" print L[0:3],"\t",L[:3] print L[-2:],"\t",L[-2:-1],"\n" L = range(100) print L,"\n" print...
0a9788e3aca817a8e3c9bfdd55cc60dddfa710ba
6igsm0ke/Introduction-to-Programming-Using-Python-Liang-1st-edtion
/CH05/EX5.43.py
341
4.125
4
# 5.43 (Math: combinations) Write a program that displays all possible combinations for # picking two numbers from integers 1 to 7. Also display the total number of combinations. count = 0 for i in range(1, 8): for j in range(i+1, 8): print(i, " ", j) count += 1 print("The total number of all comb...
04ff4e8bb6e48e265c329b8719f3152a4921adc2
DongGunYoon/Algo_DS
/mar_26th/circularLinkedList.py
967
4.09375
4
class Node: def __init__(self, value, next): self.value = value self.next = next class CircularLinkedList: def __init__(self): self.head = None def append(self, value): if self.head is None: node = Node(value, None) self.head = node node....
571824bb765ae0d6c692c10ca8971438d00c9390
amar-jain123/PythonLoop
/loop/p4.py
508
3.703125
4
''' 1 2 1 4 2 1 8 4 2 1 16 8 4 2 1 32 16 8 4 2 1 ''' # first input the number of rows rows = int(input()) # outer loop for i in range(1, rows+1): # Inner loop start, stop and step for j in range(-1+i, -1, -1): print(2**j, end=' ') # for new lines print('') # list comprehension a...
3df49a86d9156ac566050c989a68abaf175cc96e
harshsinha03/naruto-cv
/imgproc/filter.py
3,969
3.59375
4
""" Filtering functions. """ import numpy as np def filter_col(img, f, mode='same', **kwargs): """ Filter an image with a single column filter. Args: - img: input image (2D numpy array) - f: input filter (1D numpy array) - mode: indicates size of output image ('full', 'same', or 'val...
45b6d74202126ea218fb94db98dc0a00db8c5ea6
Fhernd/PythonEjercicios
/Parte002/ex1078_hackerrank_combinaciones_caracteres_itertools.py
687
3.84375
4
# Ejercicio 1078: HackerRank Imprimir en orden lexicográfico las combinaciones de varios caracteres. # Task # You are given a string . # Your task is to print all possible combinations, up to size , of the string in lexicographic sorted order. from itertools import combinations if __name__ == '__main__': s, k =...
4948e685666ba5633a7d723dd468f98e49afec94
yashrajkakkad/Automate-The-Boring-Stuff-Solutions
/chapter-7/regex_strip.py
845
4.03125
4
''' regex_strip.py Author: Yashraj Kakkad Chapter 7, Automate the Boring Stuff with Python ''' import re def regex_strip(string, chars=""): stripRegex = None if chars == "": stripRegex = re.compile(r'\S+.*\S+') stripMatch = stripRegex.search(string) new_string = stripMatch.group(0) ...
593c80c763a6a7264ba6217ba93d5612f58ad253
nzevgolisda/tavli.py
/Square.py
246
3.53125
4
from Piece import Piece class Square: def __init__(self, pos): self.pos = pos self.pieces = [] def __str__(self): s = '' for piece in self.pieces: s += str(piece) return s s = Square(0)
863337d82338ca79957742c7bcacfab4791bf41b
alexaquino/HackerEarth
/Problems - Very Easy/ToggleString.py
239
3.703125
4
# Toggle String # https://www.hackerearth.com/practice/basic-programming/input-output/basics-of-input-output/practice-problems/algorithm/modify-the-string/ #input first_line = input() #output output = first_line.swapcase() print(output)
a5c99de7d3243a509f861f29effdf34af513226f
JOLLA99/Algorithm-Study
/04_이남준/week_01/2588.py
201
3.640625
4
num1 = int(input()) num2 = input() num2_1s = int(num2[2]) num2_10s = int(num2[1]) num2_100s = int(num2[0]) print(num1 * num2_1s) print(num1 * num2_10s) print(num1 * num2_100s) print(num1 * int(num2))
8339a54dd030ea3e86f16f6364953c59c502ca9e
milenatteixeira/cc1612-exercicios
/exercicios/lab 9.2/modulo.py
2,019
3.859375
4
def funcao(x): #criaçao de dicionários centena = {1: 'cento',2: 'duzentos',3: 'trezentos',4: 'quatrocentos',5: 'quinhentos',6: 'seicentos',7: 'setecentos',8: 'oitocentos',9: 'novecentos'} dezena = {1:'dez',2:'vinte',3:'trinta',4:'quarenta',5:'cinquenta',6:'sessenta',7:'setenta',8:'oitenta',9:'noventa'} ...
31f955395602ff711f17a057b229cbb2409fb84e
AustinMitchell/ProjectEuler_Python
/Solutions/p003.py
364
3.59375
4
from __future__ import division def isPrime(n): for i in range(2, n//2): if n%i == 0: return False return True largest = 0 n = 600851475143 current = 2 while (n != 1): if (n%current == 0): n = n//current if current > largest: largest = current current = 2 else: current += 1 while (not isPrim...
82dce60a2441db9d2d557a2883cdeda230a645dd
ValerieBrave/ITechArt-courses
/tribonacchi.py
827
3.71875
4
class RangeIterator: def __init__(self, size): self.c = 0 self.first = 0 self.second = 0 self.third = 1 self.size = size def __next__(self): self.c += 1 if self.c > self.size: raise StopIteration if self.c == 1: return self...
c7949cc49a0269af2663b193fc90fcfd0a9d178b
AntimonyAidan/Intro-To-OPP
/PP3.py
4,149
3.828125
4
''' Name: Aidan Latham Email: aidan.latham@slu.edu Current Date: Feb 15th Course Information: CSCI 1300-01 Instructor: Judy Etchison Description: Source code for "Mastermind" code game. Includes user defined functions and loop structures. ''' ''' Import packages ''' # Import cs1graphics package to use fo...
ebafc0930b9e2e2a21ae34d107f30aa16bda81df
sachinpkale/ContactsApp
/src/contacts.py
915
4.03125
4
"""ContactsApp supports two functions: 1. add_contact 2. search_contact Assumptions: 1. Only prefix based search is supported. 2. As data is being stored in in-memory data structure, it will not be available in subsequent runs of the application. """ from src.contacts_app import ContactsApp if __name__ == "__main__":...
5d707c6c862bf839d6d820c72b650a49ca1239a3
loggar/py
/py-core/dictionary/dictionary.invert.py
748
4.40625
4
# Use to invert dictionaries that have unique values from collections import defaultdict my_inverted_dict = dict(map(reversed, my_dict.items())) # Use to invert dictionaries that have unique values my_inverted_dict = {value: key for key, value in my_dict.items()} # Use to invert dictionaries that have non-uniq...
ebb851f8606e6d71362d13f8c627e7649b54a92a
sqq113/Code
/first work/Action1.py
173
3.71875
4
# -*- coding: utf-8 -*- """ Created on Sun Jan 31 18:12:21 2021 @author: songqianqian """ sum=0 for number in range(2,102,2): sum=sum+number print(sum)
62d3560028d1a9b76743eba009d07627508474c7
a-bereg/my_learning
/ex_03/04_student.py
1,317
4
4
# -*- coding: utf-8 -*- # (цикл while) # Ежемесячная стипендия студента составляет educational_grant руб., а расходы на проживание превышают стипендию # и составляют expenses руб. в месяц. Рост цен ежемесячно увеличивает расходы на 3%, кроме первого месяца # Составьте программу расчета суммы денег, которую необходимо...