blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
73fb819191c49ef12da49f614a9b440cda98994a
antoninabondarchuk/algorithms_and_data_structures
/linked lists/unique_list.py
813
3.84375
4
# Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None def __str__(self): result = '' s = self while s: result += str(s.val) + '->' s = s.next return result[:-2] def deleteDuplicates(hea...
c8a17782c8edb78df898634fdd1b13853512427b
peterlew/euler-python
/p15.py
261
3.703125
4
results = {} def numRoutes(w, h): if (w, h) in results: return results[(w, h)] if w == 0 or h == 0: results[(w, h)] = 1 return( 1 ) result = numRoutes(w - 1, h) + numRoutes(w, h - 1) results[(w, h)] = result return result print(numRoutes(20, 20))
0096a8c7c5d8f0fa860574ba9d65aa24d05463b5
pdhhiep/Computation_using_Python
/subset/josephus.py
3,716
4
4
#!/usr/bin/env python # def josephus ( n, m, k ): #*****************************************************************************80 # ## JOSEPHUS returns the position X of the K-th man to be executed. # # Discussion: # # The classic Josephus problem concerns a circle of 41 men. # Every third man is killed and re...
4fbeed9fdfaf52f8250a944b693aaf025cc663a9
ron1506/DrawAndGuess
/server.py
9,342
3.796875
4
############################################################################ # Basic Server that supports threads ############################################################################ import socket import threading from users import Users import random import time class Server(object): def __init__(self, i...
6329a25299c02a75a29b46855ac959d24cd5def2
almartin1911/ETC-playground
/matplotlibbook/ch3_1markerslinestyles.py
343
3.5
4
# %% Specifying colors import matplotlib.pyplot as plt import numpy as np y = np.arange(1, 3) # plt.plot(y, color=(1, 0, 1, 1)) plt.plot(y, 'y') plt.plot(y+1, 'm') plt.plot(y+2, 'c') plt.show() # %% plt.plot(y, 'y', y+1, 'm', y+2, 'c') plt.show() # %% Line styles plt.plot(y, '--', y+1, '-.', y+2, ':') plt.show() # %% ...
81f1cbdc9cff19fac37a5d4635808ccaa2a69d02
grrtvnlw/python-functions
/only_evens.py
237
3.96875
4
def is_even(num): if num % 2 == 0: return True else: return False def only_evens(lst): new_lst = [] for n in lst: if is_even(n): new_lst.append(n) return new_lst print(only_evens([11, 20, 42, 97, 23, 10]))
25e224ffa8422c567915c0f73425c657694b5f1c
daisykha/pythonSimpleProgram
/sum.py
355
3.796875
4
def sumNumbers(line): sum = 0 k = line.split(" ") for i in k: sum += int(i) return sum def sumFromFile(filename): sum = 0 with open(filename,"r") as input_file: for line in input_file: sum += sumNumbers(line) return sum filename=input("Enter a file nam...
3be52f18eca16ffa0304681cc6649ced8bdb44f8
jason3298/IS340_Problems
/Q3-hw10.py
394
3.640625
4
from questions import ChoiceQuestion def main(): first = ChoiceQuestion() first.setText('In what ye?') first.addChoice('1991',True) first.addChoice('123',False) first.addChoice('123',False) first.addChoice('123',False) presentQuestion(first) def presentQuestion(q): q.display() ...
516a1271bd7e3311150a0eac3568bc3acb9133c1
SammyRobensParadise/pendulum-spring-model
/twographattempt.py
467
3.65625
4
import matplotlib.pyplot as plt import numpy as np # setting the x coordinates x = np.arange(0, 6*(np.pi), 0.01) # setting the y1 coordinates y1 = (np.sin(4*(np.pi)*x))*(np.cos(x)) # plot the points plt.plot(x, y1, label = "pendulum 1") # setting the y1 coordinates y2 = (np.sin(4*(np.pi)*x))*(n...
958e0d32a56f8a63ecc83cf241121506cc14482f
hyunsooDii/TIL_Source
/python/chapter8/ex08_01.py
822
3.515625
4
# 첨자(인덱스) - 문자열[정수] : 0부터 인덱싱, 문자열[-정수] : 끝에서부터 인덱싱 # 문자열의 떨어져있는 간격 : offset # len() : 문자열의 길이 # 대표적인 Sequence : 문자열, 리스트, 튜플 # s = "python" # for c in range(len(s)): # print(c, end = ",") # s = "0123456789" # print(s[2:5]) # print(s[3:]) # print(s[:4]) # print("2+3 = ", 2+3) # ,와 +의 차이 : ,는 매개변수를 두개 받는 다는 뜻이고 +...
be9a294f0848d5fa05ffa437fcabc2891cae1a4a
nayemalam/python_exercises
/charcterinput.py
1,155
4.28125
4
from datetime import datetime #name = input("What is your name? ") #get users input #age = int(input("How old are you? ")) curYear = datetime.now().year; curMonth = datetime.now().month; # curMonth = int(input("Enter your month: ")) #convert input to an integer! if curMonth == 12: #if statements end with : not { ...
eb0954fab498fd3f2d551edffd7413734c3787c6
hafizmuhammadhamza/LearningPython
/Assignment2/printPoem2.py
3,054
4.25
4
# to print poem in seprate line , using one print function myPoem_1 = "Twinkle Twinkle little, star,"; myPoem_2 = " How i wonder what you are up above the world so high"; myPoem_3 = "Twinkle Twinkle little, star,"; myPoem_4 = " How i wonder what you are up above the world so high"; print(myPoem_1 + ...
4d439d90e8d1de14c3c1b02a45aec11948efefa3
44858/functions
/storing students names.py
794
4.40625
4
#Lewis Travers #09/12/2014 #storing and editing students names def getting_eight_names(): first_name = input("Please enter the name of the first student: ") second_name = input("Please enter the name of the second student: ") third_name = input("Please enter the name of the third student: ") fo...
044bca938380e92f9de20b91eb94984d3749ae57
LuisAlbertoZepedaHernandez/Mision_02
/misDatos.py
578
3.625
4
# Autor: Luis Alberto Zepeda Hernandez, A01328616 # Descripcion: Elabora un algoritmo y escribe un programa que muestre: Nombre completo, matricula, carrera, escuela de procedencia, y una breve descipcion presonal. # Escribe tu programa después de esta línea. print("Nombre:") print("Luis Alberto Zepeda Hernandez") p...
2ce7a55d153d226092468636e6b48a96611b9251
CapSOSkw/My_leetcode
/leetcode/118. Pascal's Triangle.py
1,200
4.09375
4
''' Given a non-negative integer numRows, generate the first numRows of Pascal's triangle. https://upload.wikimedia.org/wikipedia/commons/0/0d/PascalTriangleAnimated2.gif In Pascal's triangle, each number is the sum of the two numbers directly above it. Example: Input: 5 Output:ytr [ [1], #0 [1,1]...
e54d55d2f473f04a57d91cd2032d25ed29c08ca9
sailymarudwar/Leetcode
/190_reverse_bits.py
857
4.125
4
'''Reverse bits of a given 32 bits unsigned integer. Example 1: Input: 00000010100101000001111010011100 Output: 00111001011110000010100101000000 Explanation: The input binary string 00000010100101000001111010011100 represents the unsigned integer 43261596, so return 964176192 which its binary representation is 001110...
0949c782373d9043d8f3d7094b4679c037675a32
atul-bharti/Python
/Anagram.py
349
3.875
4
def is_anagram(str1,str2): if len(str1) != len(str2): return False else: count = 1 strlen = len(str1) tmpstr = str1 for s in range(strlen): tmpstr = tmpstr[count:]+tmpstr[0] if tmpstr == str2: return True return False pri...
a3e7520036e1fbb4ce56e96ecbb8e745494c5f69
coopie/teaching_material
/shopping_list_solutions.py
6,030
4.1875
4
def split_line_into_item_and_mark(line): return split_string(line, ' ') def mark_to_bool(mark): return mark == '/' def filter_out_ticked_items(items, marks): # Delete the line below and and write your code to the solution return [item for item, mark in zip(items, marks) if not mark_to_bool(mark)] ...
bca8cfe719b0790c255728ae99edfd7bd0359cc3
neizod/problems
/acm/uva/462-bridge-hand-evaluator.py
1,854
3.515625
4
#!/usr/bin/env python3 def by_suits(cards): suits = {s: [] for s in 'SHDC'} for n, s in cards: suits[s] += [n] return suits def is_stopped(suit): if 'A' in suit: return True if 'K' in suit and 2 <= len(suit): return True if 'Q' in suit and 3 <= len(suit): retu...
1f02b5689b752e17e1cb9106e83d8d18a67a5ad2
AndyReckt/python_class_1
/learning/04_comparaison_operators.py
175
3.828125
4
print(3 < 1) print(3 > 1) print(3 <= 1) print(3 >= 1) print(3 == '3') print(3 != '3') print(not 3 > 2) student = "sacha likes hollister" print('hollister' in student)
dd17d027c84848e753943f9af17b571f38aa9ba8
wangyuteng1997/python_algorithm
/Palindrome.py
691
4.03125
4
def isPalindrome_num(Num): if Num < 0: return False else: cur = 0 num = Num while(num != 0): cur =cur*10 + num%10 num = num // 10 return cur == Num def isPalindrome_str(str): return str == str[::-1] # 这里前两个:代表切片的范围,最后一个代表切片的距离,-1就是翻转 def _is_...
63163b9c9634bf5427381f0fb44a165edb3fbd82
Paletimeena/Prac_data
/Meena (copy)/python/ns academy/programs/14-12/multi.py
468
3.71875
4
class A(object): def __init__(self,kind,name): self.kind=kind self.name=name def printName(self): print "name: ",self.name,"kind: ",self.kind class B(A): def __init__(self,kind,name): super(B,self).__init__(kind,name) class C(B): def __init__(self,kind,nam...
41657d998547074b69d5263e152d96a2687230fe
jiyeonseo/hackerrank_python
/set/py-introduction-to-sets.py
326
3.578125
4
#!/usr/bin/python # https://www.hackerrank.com/challenges/py-introduction-to-sets # Enter your code here. Read input from STDIN. Print output to STDOUT inputVal=int(input().strip()); inputArr=input().strip().split(" "); tmpSet=set() for n in range(inputVal): tmpSet.add(int(inputArr[n])) print(sum(tmpSet)/len(tm...
08ed3dad41113a582fea66eb6c35afc8963aaeef
ruhangon/cursos-online-python
/parte 2/jogos/forca.py
1,602
3.625
4
import random def jogar(): print("JOGO DA FORCA") palavra_secreta=carrega_palavra_secreta() letras_acertadas = inicializa_letras_acertadas(palavra_secreta) enforcou = False acertou=False tentativas=0 print(letras_acertadas) while(not acertou and not enforcou): ...
773a02106caa81104c360e3f6734640cb631847b
NehaKherde/Data-Mining
/Assignment 2/Code/JS.py
2,221
3.640625
4
def JaccardSimilarity(a,b): """ intersection_set=set() for items in a: for values in b: if values==items: intersection_set.add(values) break #intersection_count=len(intersection_set) union_set=set() for items in a: for values in b: if values not in union_set: union_set.add(values) ...
e0fb55e414a3169122fb4045606a3c743414ec33
beccathomson/lyrics_mining
/preprocess.py
1,341
3.578125
4
from sys import exit import nltk import pandas as pd from nltk.corpus import stopwords from nltk.corpus import words from nltk.tokenize import word_tokenize stop_words = set(w.lower() for w in stopwords.words('english')) english_vocab = set(w.lower() for w in words.words()) def stem_lyrics(song): return [ps.ste...
0f596007dca63abef416aa8f1dd9469334ca2d37
jeshc/claseGitCarlos
/mayor.py
176
3.953125
4
edad = int(input("Cual es tu edad?:")) print(f"Tu edad es:{ edad }") if edad > 18 : print("Eres mayor de edad") else: print("No eres mayor de edad, Sal de mi bar!!!")
cb21b69048c6237c2433a1d031f5bcecda68da5c
bharat0071/Python_Assignments
/reverseword.py
204
4.15625
4
# -*- coding: utf-8 -*- """ Created on Sat May 30 22:56:07 2020 @author: MOHANA D """ word = input("Input a word to reverse: ") for x in range(len(word) - 1, -1, -1): print(word[x], end="")
c9236060f39d751a3480a1ee579bcb0b77556107
aviral36/HackerRank-Solutions
/Practice/Python/itertools-permutations().py
279
3.546875
4
# Enter your code here. Read input from STDIN. Print output to STDOUT from itertools import permutations s=raw_input().split() le=len(s[0]) l=list() k=int(s[1]) for i in s[0]: l.append(i) f=list(permutations(l,k)) f.sort() for i in f: temp="".join(i) print temp
8d1225145a9036577c031e2de2d707a11c4e731c
ByoungSooPark/python1
/test24.py
862
3.890625
4
#myList = ['중국','한국','미국','대만','호주','Japan'] myList = [1,8,3,4,2,7] print('현재 리스트 : %s' % myList) myList.append(80) print("append(80) 후의 리스트 : %s" % myList) print("pop()으로 추출한 값 : %s" % myList.pop(1)) print("pop()후의 리스트 : %s" % myList) myList.sort() print("sort()후의 리스트 : %s" % myList) print("2값의 위치 : %d" % myList....
3223336eeea5a1eb9a2f785f819e7582c3b402a9
sambasivaraokambala/Intro-to-Programming-with-Python
/strftime-weddinginvite.py
380
3.859375
4
################################################# # Dispalying a wedding invite # Shiva K ################################################# #importing datetime class import datetime # Stores today’s date in a variable currentDate = datetime.date.today() # prints the invite print(currentDate.strftime("...
e2c78a19a27c97eb43bd87a5102999c10705ef1f
zxzerster/algorithms
/SingleLinkedList.py
9,445
3.78125
4
class SingleLinkedList(object): class Node(object): def __init__(self, val): self._val = val self._next = None def __init__(self): self._head = SingleLinkedList.Node(None) def insert(self, node): node._next = self._head._next self._head._next = n...
8f6c7a128228f4314789ee2af41de28cb45796a4
kentfrazier/euler
/Python/p051.py
1,864
3.9375
4
# By replacing the 1st digit of *3, it turns out that six of the # nine possible values: 13, 23, 43, 53, 73, and 83, are all prime. # # By replacing the 3rd and 4th digits of 56**3 with the same # digit, this 5-digit number is the first example having seven primes # among the ten generated numbers, yielding the fam...
e83a6c62d8c5a138f82e10a8e0fdaee90c26defe
PaulSedra/Poker
/poker_tests/validators/test_three_of_a_kind_validator.py
1,725
3.765625
4
import unittest from poker.card import Card from poker.validators import ThreeOfAKindValidator class ThreeOfAKindValidatorTest(unittest.TestCase): def setUp(self): self.king_of_clubs = Card(rank='King', suit='Clubs') self.king_of_diamonds = Card(rank='King', suit='Diamonds') self.king_of_h...
1b1df03a3680957ba001d3174f574d5e503b2b94
CVforty2/python_cellular_automata
/gui.py
799
3.546875
4
import grid import pygame class Gui: RED = (255, 0, 0) WHITE = (255, 255, 255) BLACK = (0, 0, 0) def __init__(self, row, height, color, margin): self.grid_obj = grid.Grid(row, height) self.color = color self.margin = margin self.draw_grid() def draw_grid(self): ...
215dfd05e6434d48f0bead92c208464f701b0def
yuseungwoo/baekjoon
/5622.py
285
3.671875
4
# coding: utf-8 def find(l, c): for i in range(len(l)): if c in l[i]: return i dial = ['ABC', 'DEF', 'GHI', 'JKL', 'MNO', 'PQRS', 'TUV', 'WXZY'] string = input() result = 0 for i in range(len(string)): result += find(dial, string[i]) + 3 print(result)
ebf8efd0013aeab3b61c27fd8dacdf80d45683f3
vnguyen96/PythonCrashCourse
/1Input.py
1,027
4.4375
4
name = input("Please enter your name: ") print(f"\nHello, {name}!") #Sometimes you'll want to write a prompt that's longer than one line. prompt = "If you tell us who you are, we can personalize the messages you see." prompt += "\nWhat is your first name?" # operator += takes the strong that was assigned to 'prompt' ...
0b8cc8124d14b07b834cfa89f8b8b14c0def3ad2
tataurova/lessons-gb-python
/lesson_7/try_except_else_finally.py
454
3.875
4
number = int(input('Введите число ')) try: # код, кот может вызвать исключит ситуацию result = 100 / number except: # что делать, если произошла исключит ситуация print('Деление на 0') else: # что делать, если ошибок не было print('Все хорошо') finally: print('Выполняется всегда')
8e6104c420947e90ac59264a528cd49db4b747a2
aaajeong/LectureScore-Calculator
/Cal.py
1,395
3.703125
4
# PythonLecture 클래스 정의 # <멤버변수> # 1차 시험점수 - First_g # 2차 시험점수 - Second_g # 3차 시험점수 - Third_g # 결석횟수 - abs_num # # <멤버함수> # 3개 시험의 평균 점수 산출 함수 - exam_avg # 3개의 점수를 20%, 30%, 50% 가중치로 평균 산출 함수 - weighted_avg # 최종 성적을 입력받아 학점을 부여하는 함수 - get_Alphabet # * 초기화 함수에서 각 점수들이 0 점으로 초기화 되도록. class PythonLecture: def __init_...
b5d78dcb91679f58cbcfcc4e1fbdfe423f723cc6
arunachalamev/PythonProgramming
/DC20191115maxOfSubarray.py
685
3.703125
4
import collections def maxOfSubArray(input, k): result = list() dq = collections.deque() if len(input) <=3: return max(input) if not input: return None for i in range(k): while dq and input[dq[-1]]<input[i]: dq.pop() dq.append(i) result.append(in...
5608950716f00783d9580c586ad4218f62d527de
dhgrainger/intro_to_python
/back_to_basics_loops.py
192
3.765625
4
condition = 1 while condition < 10 : print (condition) condition += 1 exampleList = [1,6,7,3,6,9,0] for x in exampleList: print(x) for x in range(1,11): print('range ', x)
26bd92618c2c6e48fbf0820322be41e938a65f75
igor1/uber_expression
/comp.py
1,717
4.09375
4
#!/usr/bin/env python3 def is_int(e): try: int(e) return True except: return False def is_op(e): return e in "+-" def compute(op1, op, op2): if op == '+': return int(op1) + int(op2) elif op == '-': return int(op1) - int(op2) else: assert Fal...
9b772a25b9ff41f591e2832db7a0c0dae4ea5129
CSeven19/PythonLevelUp
/pythonLevel3/pygame/pygamenew2old/pygameWork9.py
3,054
3.765625
4
# # 向量 # # 1向量类 import math class Vector2(object): def __init__(self, x=0.0, y=0.0): self.x = x self.y = y def __str__(self): return (self.x, self.y) @classmethod def from_points(cls, P1, P2): return cls(P2[0]-P1[0], P2[1]-P1[1]) # 我们可以使用下面的方法来计算两个点之间的向量 def get_m...
8321cf0a0d8130372d9dd2a16ed245bfed0b964e
mauro40ar/primer-a-o-python2017
/apŕender a pensar como un programador con python/capitulo 4 condicionales y recursividad/recursividad.py
155
3.59375
4
def cuenta_atras(n): if n>0: print("%s"%(n)) print (cuenta_atras(n-1)) else: print("buen viaje") n=3 cuenta_atras(n)
1e5829e0bbece906b517eb34891eb5e38edc8c81
mikeevmm/FisicaComputacional
/Folha1Ex5.py
552
3.859375
4
# ~*~ encoding:utf-8 ~*~ from functools import reduce def factorial(n : int): if n == 0: return 1 return reduce(lambda x,y: x*y, range(2, n+1)) def binom(n : int, m : int): return factorial(n)/(factorial(m) * factorial(n - m)) * 0.5**n def binomsum(n : int): return sum(binom(n, m) for m in r...
70512f7b03df23673bd8b8d2ebed09ebcfcbc427
cuiweiyu/python-
/机器学习/回归/lr.py
441
3.5
4
import matplotlib.pyplot as plt import seaborn as sns; sns.set() import numpy as np rng = np.random.RandomState(1) x = 10 * rng.rand(50) y = 2 * x - 5 + rng.randn(50) plt.scatter(x, y) from sklearn.linear_model import LinearRegression model = LinearRegression(fit_intercept=True) model.fit(x[:, np.newaxis], y) xfit...
50e5a57d8a7f2ec45f52c319f60ba24003eecd6d
mkf/stacjetrm
/ownlib/lang/english.py
3,571
3.578125
4
# -*- coding: utf-8 -*- class english: u"""This is an English language file""" def __init__(self): lang = "en" @property def dictu(self): slo = { "badwaittime": "Incorrect waiting time", "badstacparam": "Incorrect station parameter", "badlang": "Incorrect language", "badpracy": "Incorrect work mod...
ff51e69e0dfdd02627c3eab41c73e9fe47ac9645
ipeterov/random-stuff
/Анаграммы/fill_base.py
150
3.546875
4
from anagram import * a = wordbase() words = open('words.txt', 'r') for word in words: word = word.strip('\n') a.add_word(word) a.dump_base()
52e722d6d76de7c34da0be0b17bc7b492492f87f
IgorProninP/Codewars
/snail.py
2,119
4.3125
4
""" Snail Sort Given an n x n array, return the array elements arranged from outermost elements to the middle element, traveling clockwise. array = [[1,2,3], [4,5,6], [7,8,9]] snail(array) #=> [1,2,3,6,9,8,7,4,5] For better understanding, please follow the numbers of the next array consecutively: ar...
87cadc8f61ef779b84130a5fa47ca88d2a3dc66c
karim-eddin/python-datastructure
/DequeWithStacks.py
1,910
3.890625
4
import ArrayStack class DequeWithStacks: def __init__(self): self.s1 = ArrayStack() self.s2 = ArrayStack() def __len__(self): return len(self.s1) + len(self.s2) def is_empty(self): return len(self) == 0 def add_first(self, elem): self.s1.push(elem) def a...
76b5d6de270719c8834401bf85c74d4aeda67f8e
abhishekthukaram/Course-python
/Practice-Problems/cumulativelist.py
317
3.859375
4
def cumulative_sum(list1): for i in range(1, len(list1)): list1[i] = list1[i] + list1[i - 1] return list1 print add_one_by_one([1, 3, 6]) print add_one_by_one([1, -1, 2]) def cumulativelist(list1): new = [] cum = 0 for i in list1: cum += i new.append(cum) return new
ddc35edfbc3d79d29dd9200a56ea1856e4a822e2
cmibarnwell/python
/oldProgs/CompoundInterestCalculator.py
431
3.828125
4
print("Compound Interest :") amount = input('1000') amount = float(amount) rate = input('5') time = input('10') time = float(time) compoundTimes = input('4') compoundTimes = float(compoundTimes) total_amount = amount * ((1 + ((float(rate)/100))/4)**(compoundTimes*time)) print('\nTotal Amount = $%0.2f' %tot...
8091391ddc822f3f916bcab095c876e89f7f44c1
sakshammudgal1908/Python-Programs
/PracticeSets/practiceset5(dictationary).py
1,662
4
4
#hindi to english translation Translation={"pagal":"idiot", "sundar":"beautiful", "phela":"first", "koshish":"try", "akl":"intelligent"} print("Choose among the following options: \n ",Translation.keys()) a=input("Enter your Hindi Word\n") print("The meaning pf...
69dcd426a89d830e111435477bde902c100c8092
Daboni/PS
/python/약수의 합2.py
93
3.609375
4
n = int(input()) res = 0 for i in range(1,n+1): res = res + n//i*i print(res)
e07402d4d3c6a529d7cb9bcd90eaee55557c2b41
ThienStai/mess-attack-plus
/mess-attack-plus.py
2,899
3.578125
4
from pyautogui import alert, typewrite, FAILSAFE, press, MINIMUM_DURATION, FailSafeException from time import sleep from os import system from pyinputplus import inputInt, inputFloat MINIMUM_DURATION = 0.0001 def countdown(): for i in range(3): print("Attack start in %s " % (3-i)) sleep(1) def...
162af3270b0d761c68cf1ba9b7c76086f4fee35f
ramaisgod/My-Python-Practice
/prog16_File_Writing.py
899
3.875
4
# Open file in write mode # f = open("ram2.txt", "w") # f.write("I am 30 years old.") # f.close() # """ # This will open ram2.txt file and replace all the contents. # But If file does not exists then it will create new file and replace all the contents. # """ # Open file in append mode # f = open("ram3.txt"...
4e30a9c3fabbee61fedcc2d6d7f6155d86a75371
Aasthaengg/IBMdataset
/Python_codes/p03837/s949044893.py
1,806
3.5625
4
from collections import defaultdict from heapq import heappop, heappush class Graph(): def __init__(self): self.graph = defaultdict(list) def __len__(self): return len(self.graph) def add_edge(self, src, dst, weight=1): self.graph[src].append((dst, weight)) def get_nodes(s...
44c5e85c094a7aee3ced64a4f6e5b26fb7964c5d
Silentsoul04/PythonCode
/dummy-web-server.py
1,192
3.609375
4
#!/usr/bin/env python """ Very simple HTTP server in python. Usage:: ./dummy-web-server.py [<port>] Send a GET request:: curl http://localhost:8080 Send a HEAD request:: curl -I http://localhost:8080 Send a POST request:: curl -d '["foo", {"bar":["baz", null, 1.0, 2]}]' http://localhost:8080 """ i...
4b4dc1aa8a474140a1915a983d2c252d4c1b8a37
qmnguyenw/python_py4e
/geeksforgeeks/python/python_all/77_15.py
3,120
4.28125
4
Python – Test Record existence in Dictionary Sometimes while working with pool of records, we can have problem in which we need to check the presence of particular value of a key for existence. This can have application in many domains such as day-day programming or web development. Lets discuss certain ways ...
b57a9f9a3bb44c2edf82b26e7acd9fb0cc2eb49b
PeterBeard/math-experiments
/keith.py
3,159
4.03125
4
"""Find all the Keith numbers in a given range and attempt to cluster them.""" import argparse def get_digits(value): """Return a list containg the digits of the given integer.""" digits = [] for d in str(value): digits.append(int(d)) return digits def is_keith(value, showSteps=False): "...
b53cb10d37bde850bde4d80195e4f4ef701f8740
AdarshRise/SCC-SIST-Algorithms
/fibnocii/python/fibnocii.py
435
3.84375
4
def fibo(): num1,num2,into,i =0,1,0,0 into=int(input("Enter the limit for the number of output from the series:- ")) while(i<into): print(" num ",i+1,": ",num1+num2," ") num1=num1+num2; # moving to the next number by swap num2=num1-num2; num1=num1-num2; num2...
53d16fd66ed9bc622497acdc04b0062aded270f0
JohnSdev/ASTEROIDS
/circ.py
814
3.703125
4
from labb import shape from point import Point class Circle( shape ): def __init__( self, pos, radius): super().__init__( pos ) self._radius = float( radius ) def area(self): return 3.14159 * self._radius ** 2 def circumference(self): return 2 * 3.14159 * self._radius def dra...
d50d3c1892fbc00ec62979443a7b1df8d249929d
n-sarraf/bootcamp
/bootcamp_utils.py
751
3.578125
4
# Bootcamp utils: A collection of statistical functions. # Proved useful to 55 students. import numpy as np def ecdf(data): ''' Compute x, y values for an empirical distribution function ''' # Sort data x = np.sort(data) y = np.arange(1, 1+len(x)) / len(x) return x, y def draw_bs_reps...
ad4db92102fd3a0ebec75ccaa28b3adb797d2c3e
ginug/python_django_react
/words.py
751
4.125
4
#!/usr/bin/env python3 """ This script is used to get the contents of any site and then split that into individual words""" from urllib.request import urlopen from sys import argv def fetch_words(url): """ Gets words from URL Args- URL Returns- List of words """ wi...
022cc3dcca5093a78f207c1c01d0193e66432499
Tamalika1995/Udemy_Practice
/Practice_100/p83.py
268
3.875
4
'''By using list comprehension, please write a program to print the list after removing the 2nd - 4th numbers in [12,24,35,70,88,120,155].''' orig_list = [12,24,35,70,88,120,155] new_list = [i for (j, i) in enumerate(orig_list) if j not in range(2,5)] print(new_list)
de2ef9c5a86549b48130e99fc912b0fa77a534fe
Filipe-Seixas/engi89_python_exam_prep
/study.py
2,552
4.65625
5
# W3Schools - https://www.w3schools.com/python/exercise.asp?filename=exercise_syntax1 # Create a list 1-5 and iterate through it mlist = [1, 2, 3, 4, 5] for x in mlist: print(x) # Print the 3rd number print(mlist[2]) # Print list backwards print(mlist[::-1]) # Create a dictionary with key value firstname and lastn...
1e727ff85fc0f9c7a666d02292269be945f340ff
Ashasrinivas/100programs
/ex_23.py
169
4.125
4
n = int(input("enter the number : ")) x = n ** 2 print(x) # using function def square(): num = int(input("enter the value : ")) return num ** 2 print(square())
63e0d13ac575596107b0b6b6041390b60babf435
huangyingw/submissions
/987/987.vertical-order-traversal-of-a-binary-tree.233996575.Accepted.leetcode.py
602
3.734375
4
from collections import defaultdict class Solution(object): def verticalTraversal(self, root): x_to_y_and_val = defaultdict(list) def helper(node, x, y): if not node: return x_to_y_and_val[x].append((-y, node.val)) helper(node.left, x - 1, y - 1...
0d3d94d9b38f2e1a4671cfd9a8b8345468d4b6d1
larrythwu/python-tensorflow-exercises
/KNN/knn.py
1,562
3.609375
4
import sklearn from sklearn.utils import shuffle from sklearn.neighbors import KNeighborsClassifier import pandas as pd import numpy as np from sklearn import linear_model, preprocessing # preprocessing -> convert test in data file to numerical values data = pd.read_csv("car.data") print(data.head()) le = preprocessin...
3500e06650f4847919416a3b09b844863f3fa1b2
tw3rp/makers-row
/parse.py
1,554
3.5625
4
import fileinput import math import operator pairs = dict() #dictionary of associations def initial_parser(lines): parser = getresult(lines) def getresult(lines): global minimum i=0 for line in lines: each_word = line.splitlines()[0].split(',') if(i==0): minimum=int(each_wor...
c400fa13e11e284ecd722a0016e4d37c4221ccbb
Hadamanthis/Mestrado
/Dissertacao/normalizacao.py
904
3.65625
4
# Dado um vetor com uma quantidade R de imagens, quero amostrar D imagens de forma que o vetor fique com amostras temporais igualmente espaçadas import math def normalizar(V, R, D, verbose = False): if (R > D): while (len(V) > D): # multiplos a serem retirados n = math.ceil(len(V)/abs(len(V) - D)) if ...
958666b9f608133d862524481715c0d08bb1674f
divyanshAgarwal123/PythonProjects
/aptech learning/nested loop 2.py
157
3.9375
4
x=int(input("enter how many rows you want")) n=1 for i in range(1,x+1): for j in range(1,i+1): print(n,"\t",end="") n=n+1 print("")
0111f0c7d0a225034f26dcec17e55afa610f04d4
adrienpaysant/AI-Hearc
/TP/TP2/2.2_a_Star_villes/CityLink.py
2,102
3.984375
4
import os class City : """ Class that represent a city in traveller's issue """ def __init__(self,name,x,y): self.name = name self.X = int(x) self.Y = int(y) self.links = [] self.parent=None def __str__(self): return str(self.name) def __lt__(se...
afb0d2a0fb1492d0728424b8d7bda187efdc3ced
boothresearch/puzzles-purple
/word-count/word_count.py
516
3.546875
4
def count_words(sentence): #remove the space thing s = s.replace("\n"," ").replace("\t"," ") #handle apostrophe s = s.replace("'s","ag96") #handle punctuation s_new = s.translate(str.maketrans('', '', string.punctuation)).lower() #word list s_list = (s_new.split(' ')) #count the ...
668e422f3ba95181321636d152f566a62d510ba8
chaitanyanarukulla/code-katas
/sort_by_binary_ones.py
491
3.875
4
"""Kata: Sort By Binary Ones - implement a function that sort a list of integers based on it's binary representation. #1 Best Practices Solution by biskinis & others def sortByBinaryOnes(numList): def key(n): s = format(n, 'b') return -s.count('1'), len(s), n return sorted(numList, key=key)""...
caeba3a535bb7c284284fb0a6330845769350d71
LucaLabio/ExerciciosPython
/dia4/exercicio08.py
658
3.875
4
"""Dados o preço de um produto e um percentual de desconto, escreva um algoritmo que calcula e mostra o valor do desconto e o novo preço do produto dado o percentual. E se, ao invés de um desconto, fosse um aumento. O que muda no seu algoritmo?""" preco = float(input("Digite o preço do produto: ")) desconto = int(input...
1ebc5688396e37ed74ccd72819aa0faf21ddd6e0
dheinz0989/FileSizeDistributor_for_Multiprocessing
/src/multithread_for_file_processor.py
4,285
3.5625
4
''' This module contains a class which can be use to split all files in a given directory in separate bucket such that the sum of all the bucket's file size are highly equally distributed. The initial idea of this class was script, in which a huge number of files was processed in a long "for" loop containing many check...
4ad19fa16f0f9e8283e6c073656c304b6aad9968
m-letourneur/teads-hw
/dynamic_auction.py
4,510
3.71875
4
from copy import copy from typing import Optional, Tuple class BadFormatException(Exception): pass class Bid(object): """ A bid refers to a bid amount (euros), and a buyer (index) """ def __init__(self, buyer_id: int, bid_value: float): """ Cons...
bdfb2a73e02eff9443f4edb66ec8c33c581bf503
Calvinjmin/Interview_Questions
/Python/Basic_Data_Types/tuples.py
422
4.15625
4
""" HACKERRANK PROBLEM: https://www.hackerrank.com/challenges/python-tuples/problem Description of the problem: Compute the hash of a tuple, given a list of integers Basic Solution: Use the mapping function to create a list and covert it into a tuple """ if __name__ == '__main__': n = int(input()) integer_li...
73db57217fd0bdad5ea7cee3c0d2c116ba1ccb26
LarisaOvchinnikova/python_codewars
/The Office V - Find a Chair.py
492
3.546875
4
# https://www.codewars.com/kata/57f6051c3ff02f3b7300008b def meeting(rooms, need): if need == 0: return 'Game On' arr = [] rest = need for el in rooms: if rest > 0: chairs = el[1] - len(el[0]) if chairs > 0: arr.append(chairs) if chairs < rest else arr.app...
53c4c85f5854389ad2cc560e8c9400c33b89bde0
zhanzhuang/python-base
/4_字符串/hm_19_字符串拆分和拼接.py
243
3.515625
4
# 将字符串中的空白字符全部去掉 # 再使用 " " 作为分隔符,拼接成一个整齐的字符串 poem_str = "登鹳雀楼\t 王之涣 \t 白日依山尽 \t \n " print(poem_str) print(poem_str.split()) print("a".join("qwer"))
8f84faa3c6e8b586f66b5f1495a34d0043944adf
daki0607/Project-Euler
/problem 43.py
1,285
3.71875
4
""" The number, 1406357289, is a 0 to 9 pandigital number because it is made up of each of the digits 0 to 9 in some order, but it also has a rather interesting sub-string divisibility property. Let d1 be the 1st digit, d2 be the 2nd digit, and so on. In this way, we note the following: d2d3d4=406 is divisible by 2 d...
3751df3e96c5085ab1dcaea1128379dd217fcf48
ramonvaleriano/python-
/Livros/Introdução à Programação - 500 Algoritmos resolvidos/Capitulo 3/Exercicio 3a/Algoritmo113_se24.py
398
3.953125
4
# Program: Algoritmo113_se24.py # Author: Ramon R. Valeriano # Descritption: # Developed: 24/03/2020 - 17:42 # Updated: number1 = float(input("Enter with first number: ")) number2 = float(input("Enter with second number: ")) if number1 != number2: if number1 > number2: aux = number1 number1 = numb...
e9aaa5a2f17ef0afc64329ff018be2212d084be2
aacharyakaushik/i_code_in_python
/leetcode/Plus_one.py
469
3.65625
4
# -*- coding: utf-8 -*- """ @author: Kaushik Acharya """ from typing import List def plusOne(self, digits: List[int]) -> List[int]: # print(digits[-1]) # print(digits[:-1]) # print(set(digits)) if digits[-1] != 9: digits[-1] += 1 elif set(digits) == {9}: digits = [1] + [0] * len(d...
b43459222654a5ade40999f6c59893bf04a3023b
jyoon1421/py202002
/project/timeline_class.py
2,880
3.59375
4
import datetime as dt import time # 타임라인 클래스 class Timeline: timelinelist = [] def __init__(self, member, writetime, booktitle, star, review, absnum): self.member = member.nick self.writetime = writetime self.booktitle = booktitle self.star = star self.review = revie...
fb3a66fc22c66c1aef72a5a8598128715c494e52
beginstudy/python_newstudy
/confirmed_users.py
619
3.828125
4
#首先,创建一个待验证用户列表 #和一个用于存储已验证用户的空列表 未验证用户 = ['北极星','南极星','猎户星','中子星'] 已验证用户 = [] #验证每个用户,直到没有未验证用户为止 #将每个经过验证的列表都移到已验证用户列表中 while 未验证用户: 当前用户 = 未验证用户.pop() print("验证用户:" + str(当前用户)) 已验证用户.append(当前用户) #显示所有以验证的用户 print("\n下列用户已经得到确认:" + str(已验证用户)) for 用户 in 已验证用户: print(用户)
f8896cf3d84197910172846af0ea4da8fcf15021
mohmilki/IF1311-10220013
/main-latihanoperasilogikadanbolean.py
2,170
3.75
4
#latihan soal boolean dan komparaasi # --------0++++++++5---------8+++++++++11----------- print ("====================Kasus irisan==================") print ("--------0++++++++5---------8+++++++++11-----------") inputUser = float(input("Masukkan nilai lebih dari 0 dan kurang dari 5 \n lebih dari 8 dan kurang dari...
15e845e82dd94e84be6f8c1c474ce45e70c0403a
NFollett89/refresher
/data-structures/stack/stack.py
1,220
3.96875
4
#!/usr/bin/env python2 import copy class NFStack(object): def __init__(self): self.stack = [] # Informal string representation of the Stack def __str__(self): return "%s" % self.stack[::-1] # Iterator implementation def __iter__(self): for data in self.stack[::-1]: ...
4bce2dc3642a5d776ba9d107850bfaa84a09824e
MrHamdulay/csc3-capstone
/examples/data/Assignment_2/eyrros001/question1.py
227
4.09375
4
year = eval(input("Enter a year:\n")) if (year%400==0): print(year,"is a leap year.") elif(year%100!=0 and year%4==0): print(year,"is a leap year.") else: print(year, "is not a leap year.")
ccdb67a782d453f29f6e39be9205f1ba9f16ea7c
jovenan/Exercicios-python
/aula format.py
550
3.671875
4
N = "Samuel" i = 25 print ("nome: {} idade: {}".format(N,i)) #indice: preencher / alinhar / largura / .precisão/ print ("nome {0:*^18.8} , idade {1}" .format(N,i)) #para strings #indice : preencher/ alinhar/ largura/ .precisao # <>^ 10 .2 #para Numeros #indice : preencher/ alinhar/ sinal/ largura/ .precisao/...
c8a529b8f4d471b3b00d4166a9a0ac95b69fee0d
saumye4696/codeforces-and-leetcode
/BubbleSort.py
373
3.9375
4
def bubble(arr): for i in range(len(arr)): for j in range(len(arr) -i - 1): if(arr[j] > arr[j+1]): arr[j] , arr[j+1] = arr[j+1], arr[j] return arr # after every iteration, the next largest number will # be sent to the end in its correct position l1 = [9,6,4,3,6,4...
230b83cd4ffb738e104c8a1fe4872a9d0e15eff0
kirkbroadbelt/Python
/Final For Statistical Programming/data.py
2,251
3.890625
4
class Data: def __init__(self, x, y): """ (Data, list, list) -> NoneType Create a new data object with two attributes: x and y. """ self.x = x self.y = y def num_obs(self): """ (Data) -> int Return the number of observations in the data set....
cefc9b56bd381a641745d013007e5b6857909d4d
rudbog011/rudbog011-Python_05
/work_5_1.py
243
3.65625
4
print('Введите пароль') password = input() print('Введите повторно пароль') password2 = input() if password == password2: print('Все окей!') else: print('Пароли не совпадают!')
d421ad1b8f0788434f56556094950964405a2c4c
fangzongzhou/pythonLearnProject
/basics/generator.py
215
3.546875
4
g=(x*x for x in range(10)) for n in g: print(n) def fib(max): n, a, b = 0, 0, 1 while n < max: print(b) a, b = b, a + b n = n + 1 return 'done' for f in fib(6): print(f)
d9e59616f4a88a7551f5ebbc345235e1bc9bb07b
theChristopher16/CPA
/backend/Challenges/binary/binary8.py
164
3.5
4
import sys argv = sys.argv bintext = argv[1] + argv[2] #print bintext print (''.join([bin(ord(c))[2:].rjust(8,'0') for c in bintext])) #ASCII --> Binary in utf-8
5cbdaba0ed057f5fea3b2a3968b930716e400b76
stefanin/Python
/4_FUNZIONI_LISTE.py
2,546
4.15625
4
#_______________ ciclo for con range for count in range(1,10): print (count) ''' Funzioni sono un strumento per strutturare il codice creando un blocco si definiscono come segue : def nome_funzione(parametro1, parametro2, ..): corpo della funzione xxxx xxxxx xxxx return <risultatao...
3136600150093b384b38e365e681fe58c92f9756
Rhysj125/tensorflow
/src/linear-regression.py
4,056
3.625
4
import tensorflow as tf import numpy as np import math import matplotlib.pyplot as plt import matplotlib.animation as animation def normalize(list): normalise_list = list / np.linalg.norm(list) return normalise_list num_house = 160 np.random.seed(42) # Generate some house sizes house_size = np.random.randint...
6ce46ce069dbd6b815bb40918622dc45b6127c2c
VictorScheike/debug_code
/ex19.py
1,161
4.25
4
#Here we define cheese_count and boxes_of_crackers def cheese_and_crackers(cheese_count, boxes_of_crackers): print(f"You have {cheese_count} cheese!") print(f"You have {boxes_of_crackers} boxes of crackers!") print("That's enough for a party!") print("Get a blanket. \n") #Here we give the function on l...
dc1df4e1271132b5966afcd78bcbab1f4eca7656
lhwisdom07/Temperature-Converter
/Temperature _Converter.py
540
4.09375
4
fahrenheit = eval(input("Enter the temperature in Fahrenheit: ")) tempInC = (fahrenheit - 32) * 5/9 print( "The temperature in Celsius is", tempInC, "degrees" ) fahrenheit = eval(input("Enter the temperature in Fahrenheit: ")) tempInC = (fahrenheit - 32) * 5/9 print( "The temperatu...
c07f741113c4a8eed7a89e12caf896b5fabc46fd
wbkoetsier/PythonSnippets
/codewars/tests/kyu6/test_equal_sides_of_an_array.py
1,267
3.578125
4
from unittest import TestCase from codewars.kata.kyu6.equal_sides_of_an_array import find_even_index class Test(TestCase): def test_find_even_index1(self): self.assertEqual(find_even_index([1, 2, 3, 4, 3, 2, 1]), 3) def test_find_even_index2(self): self.assertEqual(find_even_index([1, 100, 5...