blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
e18ee20a0a44f58da301e5ff659dcc90fd873c43
TatenLee/machine-learning
/bi/enterprise/l1_数据采集/rooting.py
1,227
4.0625
4
# !/usr/bin/env python # -*- coding: utf-8 -*- """ @author: lishuang @description: """ """ 0 10 0 5 2 5 """ def find_critical_num(target_num, power): """ 找到目标数字的开方临界数字 :param target_num: :param power: :return: """ low = 0 high = target_num while low < high: mid = (...
f76bb7f86a9ed155412e6ef8a36829c533b38748
maberf/python
/src/EstudoPOOClasses/pessoa.py
1,158
3.8125
4
# MÓDULO from datetime import date from random import randint # CLASSE PESSOA class Pessoa: '''Esta classe estabelece as características de uma pessoa.''' #variável da classe ano_atual = int(date.today().year) #variáveis das instâncias #construtor def __init__(self, nome, nasc, comendo=False)...
8344dde77c9fd5d8e8fb6ccd3d310fdf61266e04
pwr-kstasinski/Z03-24g
/Lab 5/Solutions/Calculate.py
3,756
3.859375
4
import math class Node: # Constructor def __init__(self, value): self.value = value self.left = None self.right = None operators = ['+', '-', '/', '*', '^', '!', 'sqrt', 'log', 'mod', 'abs'] order = {'+': 0, '-': 0, '/': 1, '*': 1, '^': 2, 'mod': 1, '!': 2, 'sqrt': 2, '...
5dbd0b4e6019b9ec363555c66fc67d1e5f250604
way2arun/datastructures_algorithms
/src/integers/numDistinct.py
1,937
3.765625
4
""" Distinct Subsequences Given two strings s and t, return the number of distinct subsequences of s which equals t. A string's subsequence is a new string formed from the original string by deleting some (can be none) of the characters without disturbing the remaining characters' relative positions. (i.e., "ACE" is a...
6ff57f12330f59ceb034aa54e5e9596f40df0c34
TailoFire/The-Weakest-Link
/bank.py
784
3.546875
4
class Bank(): def __init__(self): self.currentValue = 0 self.chain = [20, 50, 100, 200, 300, 450, 600, 800, 1000] self.chainIndex = 0 def moveUp(self): if self.chainIndex < len(self.chain) - 1: self.chainIndex += 1 def resetChain(self): self.chainIndex =...
f339ba0b64b926558f585f7baebba36c0cbfa32f
janenie/python_learning
/chapter13_class/time.py
530
3.71875
4
#!/usr/bin/env python class Time60(object): def __init__(self, hr, min_): self.hr = hr self.min = min_ def __str__ (self): return '%d:%d' % (self.hr, self.min) __repr__ = __str__ def __add__ (self, other): return self.__class__ (self.hr + other.hr, self.min + other.min) def...
729b5fad844b7d25b86c4707714d9e63e394d7f3
DDoeDDoe32/Python
/example/temp3.py
647
4
4
myList = ['abc', 123, 3.14, "a", True] """ print(myList) print(myList[0]) print(len(myList)) myList.append('Hello World') myList.append('Hello World') print(myList) myList.pop() myList.pop(2) print(myList) """ """ print(myList) myList.extend(['a', 'b', 'c']) print(myList) myList.insert(1, 'new data') print(my...
c2d6354a5b8657f872f569bf21836fa87fb04f0a
luandeomartins/Script-s-Python
/ex006.py
277
4.09375
4
numero1 = int(input('Digite um número: ')) numero2 = int(input('Digite outro número: ')) soma = numero1 + numero2 print('A soma entre {} e {} vale {}!'.format(numero1, numero2, soma)) #Programa que você digite dois números inteiros e ele faz a soma entre os dois números.
f21259f3f522440960fe97f851ee5014447ff719
dklickman/pyInitial
/Lab 9/lab9menu.py
1,817
4.15625
4
# Student Menu Constants look_and_print = 1 add_student = 2 change_GPA = 3 change_grade = 4 print_all_student = 5 quit_choice = 6 def main(): choice = 0 while choice != quit_choice: # give user a menu to choose from show_menu() choice = int(input("Enter the menu numb...
800864189595308f05a1691521416b79bdd889ba
elmoallistair/Codewars-Python
/src/Sum of Digits/code.py
359
3.609375
4
# Written: 20-Apr-2020 # https://www.codewars.com/kata/541c8630095125aba6000c00/train/python def digital_root(n): temp = sum([int(i) for i in str(n)]) if len(str(temp)) > 1: return digital_root(temp) else: return temp # if n >= 10: # return digital_root(sum([int(i) for i in st...
a63c1e5359604a127fe1274ced649df583afd344
amol3793/CSVParser
/csvparser2.py
4,051
3.5625
4
import csv class GetProductsInformation: def __init__(self,file_name): self._file_name=file_name #Reading csv file and returning list of the list of lines in csv files separated by ',' def get_csv_details_list(self): with open(self._file_name, 'rU') as csv_file: return list(list(re...
a67ff49534321b1ef5f34e72cf6906b372a5e99f
cryoMike90s/Daily_warm_up
/Basic_Part_I/ex_6_list_and_tuples.py
195
3.828125
4
def tuples_and_lists(*args): lista = [] for element in args: lista.append(element) return print("Tuple: ",args), print("List: ",lista) args = 1,2,3,4 tuples_and_lists(*args)
72ce92058265df85b71e0362c4a68d9d5aa6f800
L200170183/prak_ASD_E
/Tugas_Modul1_E/tugas_no.5.py
396
3.59375
4
from math import sqrt as sq def apakahPrima(n): n=int(n) assert n>=0 primakecil=[2, 3, 5, 7, 11] bukanprima=[0, 1, 4, 6, 8, 9, 10] if n in primakecil: return True elif n in bukanprima: return False else: for i in range(2,int(sq(n))+1): if(n%i==...
57ac219daf24b69f76028f1359c8cdec2fa25d21
abhirazz418/Hangman
/hangman.py
2,493
4.03125
4
# Name:- Abhay Kumar Modi import random import string def choose_word(): file=open("wordlist.txt",'r') s=file.readline() wordlist=s.split() return random.choice(wordlist) def is_word(s,r): if(r==s): return True else: return False def main(): guessTaken=0 k=0 m=0 print("Hello! Welcom...
8bf5a922d09b698bb4249965e977073982b6db5e
Varshugjsv/Varshuma
/one.py
249
3.5
4
string=raw_input() string=string.split() num=int(string[0]) key=int(string[1]) list1=[] string2=raw_input() string2=string2.split() for i in range(num): list1.append(int(string2[i])) sum1=0 for i in range(key): sum1=sum1+list1[i] print(sum1)
36c7bf8a1000dbaf684116dcd5fc90f15d789c82
yaolinxia/leetcode_study
/21. Merge Two Sorted Lists/Changhe.py
786
4.0625
4
#!/usr/bin/env python # _*_ coding:utf-8 _*_ # Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution: def mergeTwoLists(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: List...
3dfabba321398bcf8e5b7a654f5fb3c51ed09a58
JulienKhlt/TP-1-de-TD-Log
/Domino.py
5,560
3.796875
4
# TP of Julien Khlaut and Pierre Glandon import copy from MutableString import MutableString class Domino: """Insert Docstring Dominos size must uneven be and squared.""" DEFAULT_SIZE = 3 DISPLAY_SYMBOL = '*' def generate_pattern(self, value, size): """ Generate the pattern ...
e65af0fc1ab58f14ba067769767e5c416a190241
Talkal13/Cross_and_Nodes
/can.py
11,228
3.78125
4
from random import randint class game(): def __init__(self): self.game = [[" "," "," "], [" "," "," "], [" "," "," "]] self.players = ["X", "O"] def print_game(gms): for x in range(0, 5): if (x % 2 != 0): print("------") else: for y in range(0, 5): ...
904e3bec7e5fd81bdc6e881fc90823e129a6a588
liuzhidanhhh/LeetCodeSolution
/offer_22.py
749
3.734375
4
# Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def getKthFromEnd(self, head: ListNode, k: int) -> ListNode: length = 1 res_head = head cur_p = head while cur_p.next: if length...
4c90c8f6beefabbebcafadf30e9d5c8d452cf0f7
munnupsk/Problem-Solving-Ds-and-A
/Stack/Longest Common Parantheses.py
502
3.546875
4
#https://practice.geeksforgeeks.org/problems/longest-valid-parentheses/0 def findmax(s): stk=[] stk.append(-1) result=0 for i in range(len(s)): if s[i]=='(': stk.append(i) else: stk.pop() if len(stk)!=0: result=max(result,i-stk[len(st...
9c7a5f5ab42ee542115fc388126718596896389d
mohanpoddar/Python-for-Beginners
/Chapter 03 - Python Conditions And Decision Making/02.python-if-find-largest-numbers.py
614
4.34375
4
#!/usr/bin/env python # Understanding Python Conditions And Decision Making - if statement # A programme to find the largest numbers import time #:-------------------------------------------- Prog. - 01 --------------------------------------------: Num1 = int(input("Enter the first number : ")) Num2 = int(input("Ent...
ca6a430ad37099fd634ab1d07dd6aa80c5b68c1a
AkwGaniu/getting_started_with_python
/randomNum.py
170
3.765625
4
import random import sys num = int(input("How many random numbers do you want to generate")) for i in range(num): print(random.randint(0, 100), end=",") sys.exit()
d42604b91af8198748e3d8106b1a880833bdb7fc
sp00ks-L/LeetCode-Problems
/longestCommonSubsequence.py
1,257
3.59375
4
class LongestCommonSubsequence: def longestString(self, t1, t2): ''' Uses actual string in dp therefore to return answer you must use len(dp) ''' dp = [["" for x in range(len(t2))] for y in range(len(t1))] for i in range(len(t1)): for j in range(len(t2))...
8e368a90c8808a2df51f19ff3a59b4bacfe57f8e
amps93/PythonStudy
/00_SideStudy/01_Algorithm/22_recursive_function.py
675
3.8125
4
#팩토리얼 구현 예제 #반복적으로 구현한 n! def factorial_iterative(n): result = 1 #1부터 n까지의 수를 차례대로 곱하기 for i in range(1, n+1): result *= i return result #재귀적으로 구현한 n! def factorial_recursive(n): if n <= 1: #n이 1이하인 경우 1을 반환 return 1 #n! = n*(n-1)!를 그대로 코드로 작성 return n*factorial_recursive(n...
2d6761f5dcf162ab21d943863febda63ff3f0d19
rasql/tk-tutorial
/docs/basic/button1.py
358
3.546875
4
"""Create buttons with actions.""" from tklib import * class Demo(App): """Create different buttons.""" def __init__(self): super().__init__() App.root.title('Button Demo') Button() Button('Print self', 'print(self)', padding=10) Button('Hello', 'print("Hello " ...
a2f9e5c3961f0cc76c98012fffe572d9c4b01d65
iesabadellDam/marcos
/Ejercicio7.py
353
3.96875
4
'''Ejercicio 7: ''' A = int(input("Introduzca el primer número: ")) B = int(input("Introduzaca el segundo número: ")) SUMA = A + B RESTA = A - B MULTIPLICACION = A * B DIVISION = A / B print("La suma es: ", SUMA) print("La resta es: ", RESTA) print("La multiplicación es: ", MULTIPLICACION) print("La divisió...
7a353c8d7ab9db182a7f304a4d86221f0d0d473b
YeskendirK/CtCI-6th
/Chapter 5. Bit Manipulation/pairwise_swap.py
562
3.65625
4
def pairwise_swap(x): even_mask = 0b10101010101010101010101010101010 odd_mask = 0b01010101010101010101010101010101 return (x & even_mask) >> 1 | (x & odd_mask) << 1 import unittest class Test(unittest.TestCase): def test_swap_odd_even_bits(self): self.assertEqual(pairwise_swap(42), 21) ...
e3911d44e12220a54f276d017dd85c5e20f3b215
tomdom35/Project-Euler-Challenges
/Euler Problem 17 - Jan 18, 2016 - Number Letter Counts - Python/Euler Problem 17 - Jan 18, 2016 - Number Letter Counts - Python.py
1,276
3.859375
4
one = 'one' two = 'two' three = 'three' four = 'four' five = 'five' six = 'six' seven = 'seven' eight = 'eight' nine = 'nine' ten = 'ten' eleven = 'eleven' twelve = 'twelve' thirteen = 'thirteen' fourteen = 'fourteen' fifteen = 'fifteen' sixteen = 'sixteen' seventeen = 'seventeen' eighteen = 'eighteen' nineteen = 'nine...
e621257cd48f9c732f0850757e34bb67d924eadb
nicohervith/Python
/Compra_helado.py
1,021
4.0625
4
tenes_ganas_de_helado_input= input("tenes ganas de comer helado ( si / no ):") if tenes_ganas_de_helado_input == "si": tenes_ganas_de_helado = True elif tenes_ganas_de_helado_input == "no": tenes_ganas_de_helado = False else: print("no se que dijiste, pero hagamos de cuenta que no") tenes_plata_input = ...
71ac107be7196f9e012858f770565831d1977da8
Kang-Hoon/Python_reviews
/190405_lec/190405_2.py
306
4.03125
4
#스크립트 모드 #집그리기 import turtle turtle.Turtle() t1 = turtle t1.shape("turtle") size = int(input("집의 크기는 몇 픽셀로 할까? ")) angle = 90 t1.fd(size) t1.rt(angle) t1.fd(size) t1.rt(angle) t1.fd(size) t1.rt(angle) t1.fd(size) t1.rt(30) t1.fd(size) t1.rt(120) t1.fd(size)
b86e0efbe269ed139a32f192ac0fca5c5ae174d6
tengthan/python_game
/map.py
2,527
3.546875
4
from resource import Resource, Wood, Food, Gold from soldiers import * class Map: def __init__(self, size,water_locations, wood_locations, food_loacations, gold_locations): self.resources = {} self.thing_at = self.resources self.width, self.height = size for w in water_locatio...
e529cb94e83cc02bff6db569e2b839df075bf568
pandiyan07/python_2.x_tutorial_for_beginners_and_intermediate
/samples/conceptual_samples/class/property_demonstration.py
1,437
4.3125
4
# this is a sample python script program which is used to demonstrate the # concept of using the property function in the pythonic class implementation . class democlass(object): # object is a (global) variable. By default it is bound to a built-in class which is the root of the type hierarchy. # without the ...
fd2dcbd9f789cc18adbb5d20532b7d5f25f21c64
Mi7ai/Algoritmia2
/Lab/L1/ex3.py
147
4.3125
4
dic = {"Name1": 18, "Name2": 18, "Name3": 18} name = input("Name: ") if name not in dic: print("No sé su edad!") else: print(dic[name])
462b0ff29094a60126c851b50701106eed56f218
angknight/si206-Project2
/project_2.py
11,521
3.90625
4
# Your name: Angelina Knight # Your student id: 41683569 # Your email: angiemk@umich.edu # List who you worked with on this homework: from bs4 import BeautifulSoup import requests import re import os import csv import unittest def get_titles_from_search_results(filename): """ Write a function that creates a ...
281927cdb402baa9687afd26238a053d54a82087
AssaultKoder95/spoj-solutions
/STRHH-half-of-the-half.py
141
3.734375
4
t = int(raw_input()) for i in range(0,t): nText = "" text = raw_input() for r in range(0,len(text)/2,2): nText += text[r] print nText
16a91e90290c131040d71229445728f12da54e27
sarthak2424/pySUb
/pysub.py
108
3.734375
4
num1=input("enter a number") num2=input("enter a second number") result=int(num1) - int(num2) print(result)
1e168e68c5e30ec57ae1ac8ceefcfc31e33a1c60
MrHamdulay/csc3-capstone
/examples/data/Assignment_9/pllkiy001/question3.py
1,052
4.125
4
#program to verify if sudoku grid is or isnt valid #kiyarah pillay #17 may 2014 #make into list sudoku=[ ] valid=True #sudoku grid is 9X9 for i in range(9): #add the input sudoku.append(input()) g=[ ] for i in range(9): g.append(sudoku[i][0:3]) for i in range(9): g.append(sudoku[i][3:6]) ...
dc8d8bb4187d02bc30671830c7ddd7ea6814c30f
Matheuspaixaocrisostenes/Python
/ex011.py
306
3.765625
4
larg = float(input('qual a largura da sua parede? ')) alt = float(input('Qual a altura da suaa parede : ')) a = larg * alt print('sua parede tem a dimensão de {}x{} e sua area tem {}m²'.format(larg,alt,a)) Tinta = a / 2 print('Para pintar a parede Você vai precisar de {} litros de tinta'.format(Tinta))
d20e03efafbd72374ad17361e1272fe2d80c30ce
haeke/datastructure
/bin_tree.py
2,153
4.46875
4
""" create binary tree that implements a search() and print_tree() the tree is printed in pre-order traversal """ #initial setup for a node, setup an object with a value, left and # right nodes are set to null initially """ all other nodes will populate using left or right node parameter example - ...
3b5bdb41dfd14bab0fb964a11b7f1a62f0d3172d
Natnaelh/Algorithm-Problems
/Dynamic Programming/DagShortestPathDp.py
1,492
3.734375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon May 4 23:05:41 2020 @author: natnem """ class Graph(object): def __init__(self,G): self.graph = G def itervertices(self): return self.graph.keys() def Inverse_neighbors(self,u): neighbors = [] for x in self....
b62b7eea0b1a0c76287affee442a12866732b34b
ashutoshpandey/python
/SquareModule.py
226
3.734375
4
class Square: def __init__(self, x): # self is 'this' here, __init__ is constructor self.x = x def area(self): return self.x*self.x def perimeter(self): return 4*self.x
d3a69b4157e96c7a58f1181b2635a9d7a01665ec
981377660LMT/algorithm-study
/14_并查集/经典题/区间并查集/D - Linear Probing-哈希线性探测.py
1,531
3.703125
4
# 哈希线性探测 # 线性探测 linear probing # 初始时数组长度为2**20 全为-1 # 有set get两种操作 # 每次set操作都会从xi开始向右找到第一个-1的位置,然后将其置为xi # 每次get操作都会返回xi索引处的值 # !区间并查集维护每个连通分量的端点 加速查找过程 # !带合并方向的并查集 class UnionFindArray: def __init__(self, n: int): self.part = n self._n = n self._parent = list(range(n)) ...
f62f059b34b61f774d5372ff7250b41fa125e03d
leesohyeon/Python_ac
/1105/functionex/FunTest06.py
560
3.828125
4
def sum(num1,num2): #num은 마치 리스트 자료형처럼 적용된다 return num1+num2 result = sum(10,20) print("두수의 합=",result) def sum(*num): tot=0 for i in num: tot+=i return tot r1=sum(10,20,30) r2=sum(1,2,3,4,5,6,7,8,9,10) print(r1) print(r2) def calc(res,*num): if res == "덧셈": tot=0 for i...
c859b33a6eb056b031e01c193e1b4d3dedb8ae77
mu683yue/learn_and_exe_python_upTogit
/learnPy/python_ex/email_comp.py
408
3.5
4
#!/usr/bin/python3 #-*- coding:utf-8 -*- import re def is_valid_email(addr): if re.match(r'^[0-9a-zA-Z.]+@+[0-9a-zA-Z]+.com$',addr): print(addr) return True else: print('they don\'t match') return False assert is_valid_email('someone@gmail.com') assert is_valid_email('bill.gat...
db92fb398b14221ed6f2d9b95fee58e27c78fcf4
DeepakTSeervi/BlackJack
/BlackJack.py
4,898
4.375
4
import random # creating a dictionary represting all cards along with their values cards = {'2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9, '10': 10, 'jack': 10, 'queen': 10, 'king': 10, 'ace': (1, 10)} def random_card(): ''' returns a random card NOTE: This returns key of the dictionary ...
01c3908cbdce041d0af6bd4ae3d1982e0365865d
amalmhn/PythonDjangoProjects
/object_oriented_programming/polymorphism/verride.py
236
3.9375
4
class Person: def __init__(self,age,name): self.name=name self.age=age def __str__(self): return self.name p=Person(25,'Person1') print(p) #if we are printing an object __str__() method will execute
54f664a16b935297db6593e2879e29ea822ff47e
anirudhasundaresan/leetcode_solutions
/fall_internship_session/38_Count_and_Say.py
1,170
4.4375
4
#!/home/anirudha/anaconda3/bin/python ## Problem Statement ## ''' The count-and-say sequence is the sequence of integers with the first five terms as following: 1. 1 2. 11 3. 21 4. 1211 5. 111221 1 is read off as "one 1" or 11. 11 is read off as "two 1s" or 21. 21 is read off as "one 2, then one 1...
15906686a90a7fc175de5a42074e9f6a35bb0c2b
AllisonBolen/DedadlockTutorial
/deadlock.py
7,439
3.984375
4
class deadlock(object): ''' A deadlock tuytorial has state: the current state of the game numProcs: the number of processes numResc: teh number of resources steps: list of steps to do procList: from 0 to numProcs rescList: from numProcs to the resource number ...
f3c39ce5c7097cf9202168d94be53cd541e2bd82
ponnuru171/Python-1
/online/login program.py
246
3.65625
4
x=int(input("enter loin id")) y=int(input("enter password")) if x == 123456: print("continue") if y == 98765: print("login sucessfull") else: print("enter password correctly") else: print("enter loin id correctly")
46d850ff71b9b4e509998c57a00385a646499c65
SHLIM1103/python-basic
/day01/mission05-2.py
367
3.640625
4
import random a = random.randrange(1, 7) # 끝값은 (원하는수 + 1) 로 적용 b = random.randrange(1, 7) print("a 주사위의 숫자는 %d 입니다" % a) print("b 주사위의 숫자는 %d 입니다" % b) if a > b: print("a 주사위가 이겼습니다 !") elif a < b: print("b 주사위가 이겼습니다 !") else: print("비겼습니다 !")
eb184d02b1a0da8a3f296bb6a91fc2bda1848c3b
leandroflima/Python
/Invertendo_sequencia.py
218
4.0625
4
lista = [] numero = -1 while(numero != 0): numero = int(input("Digite um número: ")) if (numero !=0): lista.append(numero) for indice in range(len(lista)-1,-1,-1): print(lista[indice])
84c084c070831004d54935c3ac58fc028f6d616a
ethomas2/snippets
/log.py
1,300
3.546875
4
records = [] indent = 0 def pretty_print_records(records): for record in records: indent=' '*record['indent'] fname=record['fname'] retval=record['retval'] args=', '.join(map(str, record['args'])) kwargs=', '.join( '{}={}'.format(argname, argval) fo...
d0e5dc7b8f1c56db4cf391b765e8dbd58145fd27
saminmustakim/Prime-Number
/prime_number/prime_number.py
290
3.828125
4
import math def prime_number(n): if n < 2: return False if n == 2: return True if n % 2 == 0: return False m = math.sqrt(n) m = int(m) + 1 for x in range(3, m, 2): if n % x == 0: return False return True
552c66e01fc3fa092c1af8d29237ce719bcb9096
FranciscoDMO/Laboratorios-de-algoritmia
/m.py
2,023
3.5625
4
''' Podemos usar um (multi) grafo pesado para representar um mapa de uma cidade: cada nó representa um cruzamento e cada aresta uma rua (etiquetada com o respectivo comprimento). O objectivo deste problema é determinar o tamanho de uma cidade: a distância entre os seus cruzamentos mais afastados. A entrada consistirá...
7ba0637ac0e3542f60d9880a513370c09ac655e1
profHydee/mypython.com
/login page/deebee.py
4,006
4
4
import sqlite3 class MyDatabase: def __init__(self): self._deebee=sqlite3.connect("StaffRecord.db") self._deebee.row_factory=sqlite3.Row self._deebee.execute("create table if not exists StaffLogin(ID integer primary key autoincrement, Name Text, Password Text)") self._deebee.commit(...
0b8039c70c0a10223496037a8035c6805a42613e
ernandez-ds/avaliacao-de-expressoes
/ClasseExpressao.py
11,907
4
4
# -*- coding: utf-8 -*- from Pilha import * class Expressao: """Classe que serve para instanciar objetos com atributo denominado exp, que recebe uma string, expressao InFixa""" def __init__(self,exp=""): """ Construtor padrão da Classe Expressao com um argumento que pode ser passado ou não""" self.__exp=...
a57fc01e27707081c83cd0f4f73902a616454026
dl57934/python-learning
/ch6/ch6-5/lev-distance.py
950
3.609375
4
def calc_distance(a,b): if a == b : return 0 a_len = len(a) b_len = len(b) matrix = [[] for i in range(a_len+1)] for i in range(a_len+1): matrix[i] = [0 for i in range(b_len+1)] for i in range(b_len+1): matrix[0][i] = i for i in range(a_len+1): matrix[i][0]...
7fce90c7655a82c82d3852cd12c0c13d683d2efc
smksevov/Grokking-the-coding-interview
/topological sort/all tasks scheduling orders.py
2,171
4.03125
4
# There are ‘N’ tasks, labeled from ‘0’ to ‘N-1’. # Each task can have some prerequisite tasks which need to be completed before it can be scheduled. # Given the number of tasks and a list of prerequisite pairs, # write a method to print all possible ordering of tasks meeting all prerequisites. # Example: # Input: ...
5f3ff24a3915cf90d8c26f69510e3bb8f8561302
ananyajana/practice_problems
/binary_tree_vertical_view.py
5,759
4.09375
4
INT_MAX=1000000 # hd is a component in the node to capture the horizontal distance # of the node from the root class QueueNode: # fn to initialize the node object def __init__(self, data): self.data = data self.next = None class MyQueue: def __init__(self): self.front = None ...
be821362113b7364c215f7e0e9c2cbeecab20ef5
KareliaConsolidated/Data-Structures-and-Algorithms
/45_Practice/03_Practice_Code_Frequency_Counter.py
874
3.953125
4
# Write a function called same, which accepts two arrays. The function should return True, if every value in the array has its corresponding value squared in the second array. The frequency of values must be the same. ############### METHOD 01 ############### def same(arr1, arr2): if len(arr1) != len(arr2): return ...
87993f539d0271a857f6fd47e452254e73d0b247
Aasthaengg/IBMdataset
/Python_codes/p00005/s191881532.py
287
3.578125
4
def gcd(a, b): if (a % b) == 0: return b return gcd(b, a%b) def lcd(a, b): return a * b // gcd(a, b) while True: try: nums = list(map(int, input().split())) print(gcd(nums[0], nums[1]), lcd(nums[0], nums[1])) except EOFError: break
172152affdc01341b19fd74e6434639fca022307
SAMLEVENSON/ACET
/Holiday.py
174
3.5625
4
def main(): Holiday=str("Saturday,Sunday") a=(raw_input("Enter the Day:")) if a in Holiday: print("Yes" ) else: print("No") if __name__ == '__main__': main()
7aa0a393be321bc1f7ab7b7a246018f2d472db81
yurisimao/PYTHON-INIT-PROJECTS
/enumerate.py
121
3.765625
4
any_list = ["bola", "acabate", "cachorro"] for i, nome in enumerate(any_list): #Trás o indice e o valor print(i, nome)
d026e3e1b12fc4e2e4d870175672b4dc962e3e4a
Vagacoder/Codesignal
/python/Arcade/Python/P05CountBits.py
1,158
4.21875
4
# # * Python 05, Count Bits # * Easy # * Implement the missing code, denoted by ellipses. You may not modify the pre- # * existing code. # * Implement a function that, given an integer n, uses a specific method on it # * and returns the number of bits in its binary representation. # * Note: in this task and most of...
0431b2e4c359aed10c7900ab697c1b0fde77b92f
Violatsai/IntroToPythonUdacityProjects
/Other_Projects/inheritance.py
770
4.03125
4
class parent(): def __init__(self,last_name,eye_color): print("parent constructor called.") self.last_name = last_name self.eye_color = eye_color def show_info(self): print("Last name:" + self.last_name) print("Eye color:" + self.eye_color) class child(parent): def __init__(self, last_name, eye_color, num...
44346a553ce7bb40bd1979a78c049cada5846418
aponamarev/AIND-Sudoku
/solution.py
9,633
3.6875
4
assignments = [] rows = 'ABCDEFGHI' cols = '123456789' def cross(A, B): "Cross product of elements in A and elements in B." return [s+t for s in A for t in B] def diagonal(A,B): assert len(A)==len(B), "Error: lists of wrong size provided. A - {}, B - {}".format(len(A),len(B)) return [A[i]+B[i] for i ...
a5e967ce188ee20d99693a38829be930f5219a80
hoshinotsuki/DataStructures_Algorithms
/data_structures/stack.py
578
3.671875
4
class Stack: def __init__(self): self.head = None def push(self, value): self.head = Node(value, next_node=self.head) def pop(self): if self.is_empty(): return None poped = self.head self.head = poped.next return poped.value def peak(self): ...
9645553e9439806422e4224f7107f8d7402cbb21
Aleks4920/Python_Algorithms
/Sort/BubbleSort.py
346
3.984375
4
def bubble(list): indexeingLength = len(list) - 1 sorted = False while not sorted: sorted = True for i in range(0, indexeingLength): if list[i] > list[i+1]: sorted = False list[i], list[i+1] = list[i+1], list[i] return list print(bubble([5,8...
01aa8f4a3b88efbfcba4e1c1f18d6d507fc04e2d
tdicola/sinobit-micropython
/examples/microbit/radio.py
971
3.828125
4
# A micro:bit Firefly. # By Nicholas H.Tollervey. Released to the public domain. import radio import random from microbit import display, Image, button_a, sleep # Create the "flash" animation frames. Can you work out how it's done? flash = [Image().invert()*(i/9) for i in range(9, -1, -1)] # The radio won't work unle...
6a618d688fb660e0c3bd490e35fa4d40f9e70cc4
panikdkernel/python-training
/HighSal.py
672
3.921875
4
def highestSalary(d): #Function definition max=0 l=[] for key,value in d.items(): if value>max: max=value #Logic for maximum salary #g=key for key,value in d.items(): if(value==max)...
6588a60ff88e62bc3a8046c04e7620fb297da6ec
Tanu-N-Prabhu/Python
/src/tuples.py
235
4.25
4
tuple1 = (1, "Hi", True, 8.999) print(tuple1) tupleEmpty = () print(tupleEmpty) # Accessing the tuple by Index tuple2 = (1, 2, 3, 4, 5) print(tuple2[4]) print(tuple2[1]) # Slicing the tuples print(tuple2[1:3]) print(tuple2[:3])
d42d6e6328a03b28ec3bc5891f6001cdc0a6bfdb
jaentrouble/MLhomework
/hoeffding.py
886
3.671875
4
# flip 1000 coins 10 times each # run 100,000 times # tail = 0, head = 1 # c1 = first coin, crand = random coin from 1000 coins, cmin = coin which had minimum frequency of head (1) # v1 = 'fraction of heads' from c1 -> same to vrand, vmin import random import numpy as np import openpyxl as op #wb = op.Workbook() #ws ...
10731a7eb2edce97150a4c9fe2523f5e8bdde331
lindseysather/CSV_Assignment
/sitka4.py
1,630
3.59375
4
import csv import matplotlib.pyplot as plt from datetime import datetime open_file = open("death_valley_2018_simple.csv", "r") csv_file = csv.reader(open_file,delimiter=',') header_row = next(csv_file) print(type(header_row)) for index, column_header in enumerate(header_row): print(index, column_header) #u...
31df53c00e05dc70787e9a89b0e4c95ed63cdc08
hjk1995/diet-buddy-poc
/poc.py
1,925
3.578125
4
import json with open('dishes.json', 'r') as f: dishes_dict = json.load(f) def findNutrientsByDiet(dish, field): nutrientObj = {} for nutrient in dish['nutrients']: if nutrient['name'] == field: nutrientObj = nutrient return "Value: ",nutrientObj['value']," and Percentage: ",nutrien...
b5c1d60ef90a5fdcba551efc08b85cba8b18df34
jasonbraganza/pym
/code/matrixmul.py
567
3.96875
4
#!/usr/bin/env python n = int(raw_input("Enter the value of n: ")) print "Enter values for the Matrix A" a = [] for i in range(0, n): a.append([int(x) for x in raw_input("").split(" ")]) print "Enter values for the Matrix B" b = [] for i in range(0, n): b.append([int(x) for x in raw_input("").split(" ")]) c = ...
37a3607008694a40033ca8e5ad0762f2e6a2d5da
Erynvorn/Training-Python-2019
/removeEveryOtherChar.py
280
3.546875
4
def remove_every_other(my_list): i = 0 ret = [] while my_list != []: if i % 2 == 0: ret.append(my_list.pop(0)) else: my_list.pop(0) i+=1 return ret pass def remove_every_other(my_list): return my_list[::2]
b63266478d7658fc39cea46c6bde1c56b8c47e19
thileepand/Python_Automation
/Documents/workspace_python/seleniumwd2/workingwithelements/WorkingwithElementList.py
817
3.515625
4
from selenium import webdriver from selenium.webdriver.common.by import By import time class WorkingwithElementList(): def test(self): baseURL = 'https://letskodeit.teachable.com/p/practice' driver = webdriver.Firefox(executable_path="/home/nadmin/Documents/driver/geckodriver") driver.get...
a7990e613c020e0fbea633eaf98b847bd1df316b
zhangweijiqn/testPython
/src/TensorflowTest/SkFlowTest/test.py
1,815
3.71875
4
import random """https://github.com/tensorflow/skflow""" __author__ = 'zhangwj' import tensorflow.contrib.learn as skflow from sklearn import datasets, metrics #Simple linear classification: iris = datasets.load_iris() classifier = skflow.TensorFlowLinearClassifier(n_classes=3) classifier.fit(iris.data, iris.target)...
88b37b326228521b62b2c552921d2a6488ce3bdf
cherrux/Data_Science_Desafio_Latam
/desafio6/letra_i.py
459
3.765625
4
n = int(input("ingrese tamaño de letra i ")) superior_inferior = "" medio = "" simple = 0 n_mitad =0 mitad ="" inpar ="" if n % 2 ==0: simple = 1 m_mitad = int(round(n/2, 0)) for i in range(m_mitad-simple): mitad += " " for i in range(n): superior_inferior += "*" for i in range(n): if simple != 0...
108d64bf5b15eea5b76f9d43c4d66f742217f575
jjwalkerwvu/finance
/codes/data_cleaning/fred_csv_reader.py
926
3.9375
4
""" Created on Friday March 13 @author: Jeffrey J. Walker fred_csv_reader.py This function reads csv files downloaded from FRED website and automatically puts them into a useful format based on the type of data (bond yield, initial claims, unemployment, etc.) Inputs: filename - filename, must be a string...
d75a34af3224b028ac516a278b9a438ee926d7d8
zumbipy/CreateDir
/cdir.py
4,411
3.84375
4
import os import argparse class CreateDir(object): """Esta Classe criar um nome ou nomes definidos pelo usuário. Tendo como objectivo agilizar a criação de varias pastas com nomes parecidos ou ate diferentes com numeração no começo ou no final """ def __init__(self, total_pasta, nome_past...
8a61bb13eb8cd486ff82f4bec0be2b10606c28c1
sirtyman/linked_list
/linked_list/linked_list.py
2,409
3.90625
4
class Element: def __init__(self, data, index): self.data = data self.index = index self.prev_pointer = None self.next_pointer = None class LinkedList: def __init__(self, collection=[]): self.collection = collection self.first_element = None self.last_e...
010e12b279f0281c1d628ca6f0057cb548b61018
ErikHendriks/PythonScripts
/mit6001.py
6,734
4.15625
4
def sqrtBisec(x): ''' Find square root of x with a divide and conquer approach. ''' epsilon = 0.00000000001 guesses = 0 low = 0.0 high = x ans = (high + low)/2.0 while abs(ans**2 - x) >= epsilon: guesses += 1 print(ans) if ans**2 < x: low = ans...
23459e43f768775f8d53c20b16860fb464319a9a
bitsreset/python
/prtc_mks_pythn_race_timing.py
597
3.984375
4
#Each day, you run 10 km, and want to know how long, on average, that run #takes. Write a program that asks the user how long it took to run 10 km today. #The programs continues to ask how long (in minutes) it took, until the user #presses Enter. At that point, the program exits—but only after calculating #and displayi...
eb1dd024363047d35b83f364cc0ba3b464a2768f
JoanWu5/jianzhi-offer
/面试题12矩阵中的路径.py
1,106
3.734375
4
class Solution(object): def exist(self, board, word): """ :type board: List[List[str]] :type word: str :rtype: bool """ m = len(board) n = len(board[0]) def helper(board,i,j,word,length): if length == len(word): return True ...
8a055b5c6683b898281727a7d580120c02a0225b
jpsalviano/ATBSWP_exercises
/chapter9/backupFileExtensionToZip.py
983
4.40625
4
#! python3 # This code is part of the book Automate the Boring Stuff with Python by Al Sweigart # backupFileExtensionToZip.py - Copies all files of same extension in a folder into a ZIP file. import zipfile, os def backupFileExtensionToZip(folder, extension): # Create the ZIP file. zipFilename = '{}Files.zip'...
2a77ba1240fee1a96cf2153048747d143c764ec5
ZheWang711/DataStructures_in_Python
/test_decorator.py
1,739
3.59375
4
__author__ = 'WangZhe' # -------------- closures ------------------ # def outer(x): # x = 1 def inner(): def innner(): print(x) return innner return inner def my_filter(function, list): return [x for x in list if function(x)] # def list_sort(index, l): # retrive = [l[i...
d46de2a14bc744f741197b6c6eb3195041ffcf4c
cocoaButterCoder/TheCodeBook
/multiRailFence.py
1,257
3.75
4
#! /usr/bin/env python3 import math print('Please enter your plaintext message:') plaintext = input().lower() print('How many rails would you like to use?') numberOfRails = int(input()) print('Removing whitespace...') plaintext = ''.join(plaintext.split(' ')) print('Removing punctuation...') for character in plain...
74ad5fe90beb7b955599af8482853917680ea7f9
truzmeto/AlgorithmsPython
/recursion.py
1,591
4.09375
4
def reverse(s): """ Recursive function to reverse the string. """ #base case if len(s) <= 1: return s else: #join last element to the reverse of the rest return s[-1] + reverse(s[:-1]) def permute(s): """ Recursive function to find all permutations of ...
d078fabd7bd7810f1b32f5aad15d3ee10671e042
shaniavina/Leetcode_Python
/349_intersection_of_two_arrays.py
513
3.515625
4
class Solution(object): def intersection(self, nums1, nums2): """ :type nums1: List[int] :type nums2: List[int] :rtype: List[int] """ lookup = {} for num in nums1: if num in lookup: lookup[num] += 1 else: ...
572ae0d845ba92838cb4bfc67b440cbe448dec38
ashishiit/workspace
/LovePython/SizeOfTree.py
1,216
3.515625
4
''' Created on Dec 30, 2016 @author: S528358 ''' # from aifc import data class Node: def __init__(self,data): self.data = data self.left = None self.right = None class Size: def __init__(self): self.root = None def Insert(self,data): NewNode = Node(data) if s...
8f6f3fc7425ea698cb10bb1047f337b9042b220e
heronc95/Assignment-3
/mongodb_setup.py
1,338
3.8125
4
""" Write code below to setup a MongoDB server to store usernames and passwords for HTTP Basic Authentication. This MongoDB server should be accessed via localhost on default port with default credentials. This script will be run before validating you system separately from your server code. It will not actually be u...
19566999ee392d6c0670fcb21163f980a216d330
Qu3d45/ZeroToMasterPython
/ex67_tricky_counter.py
184
3.90625
4
# counter # count every number in list and print the total sum my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] counter = 0 for i in my_list: counter += i print(i) print(counter)
70be010611864003a6bab5985ed0cb8ec6fdb6cc
JosephM98/User-input-and-math
/user input and math
1,431
3.984375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Aug 27 10:52:59 2021 @author: joseph """ day = "Thursday" print(type(day)) day = 32.5 print(type(day)) day = 19 print(type(day)) day = 3j print(type(day)) expenses1 = input("How much did you spend on Sunday?") expenses2 = input("How much did you spend...
e30248ad17cc709606dd7c2942038254bb24726d
tonymtran36/Python-Basics
/Classwork/Functions.py
713
4.03125
4
import math def say_hello(): print('hello') say_hello() def greeting(name): print('Hello %s' %(name)) greeting('Jose') def is_prime(num): ''' Naive method of checking for primes. ''' for n in range(2,num): if num % n == 0: print(num,'is not prime') ...
41983dfd9e78530fe9bcd96bf077b19c38878b9c
Abarnaalex/abarnaalex
/Number.py
292
3.9375
4
def check_pow(N, k): if k < 0 or N < 0: raise ValueError("k and N must be greater than 0") if k == 0 and N == 1: return True if k in (0, 1) and N != 1: return False num = k while num < N: num *= k return num == N
8482d68f2588774154a67e4c848658e1660dbcc0
mryilanc1/Python-temel-kodlar
/Koşullu durumlar/Basit Hesap makinesi.py
747
4.0625
4
# coding: utf-8 # In[12]: print(""" ******************************************** Python'la Tek işlemlik Hesap Makinesi İşlemler; 1-Toplama 2-Çıkarma 3-Çarpma 4-Bölme ********************************************""") işlem = input("İşlemi Giriniz:") a = flo...
d6059ecdf09b34e9c605fc23b880665072cdc149
chrislucas/code-wars-python
/algorithm/ds/Dijkstra/solver/DijkstraWithAdjacencyMatrix.py
2,072
4.125
4
''' https://www.geeksforgeeks.org/greedy-algorithms-set-6-dijkstras-shortest-path-algorithm/ ''' class Graph(): INF = 1 << 31 def __init__(self, vertices): self.vertices = vertices self.matrix = [[0 for c in range(0, self.vertices)] , [0 for r in range(0, self.vertices)]] ...
bfdb74b71086278055635d301ef505a7ecd12960
sagargharge/Python-Programs-on-Lists
/25.random_permutation.py
636
4.03125
4
# Question - 1.25 (**) Generate a random permutation of the elements of a list. import random def rnd_permu(L): result = list(L) random.shuffle(result) return result # Example l = ['a','b','c','d','e','f','g','h','i','j'] print l print "\r" print "The random list looks like: " print rnd_per...
56d8b0471d72709bb8b9a342398424ac9f8a54ef
kidoh80/Codewars
/Python/bit_counting.py
671
3.953125
4
/* https://www.codewars.com/kata/526571aae218b8ee490006f4 Write a function that takes an integer as input, and returns the number of bits that are equal to one in the binary representation of that number. You can guarantee that input is non-negative. Example: The binary representation of 1234 is 10011010010, so the f...