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
cf564056ed656f9afdc5d4702234aefba996317d
emilnorman/euler
/problem012.py
384
3.671875
4
import math def NumOfDivisors(num): divisors = 0 s = round(math.sqrt(num)) for i in range(1, s + 1): if num % i == 0: divisors += 2 return divisors + 1 # Generate triangular numbers triagNum = 0 current = 1 nod = 0 while(nod < 500): triagNum += current current += 1 ...
362732b4c04eb0b2a1a8530d9f501a8b707e5d20
oktavianidewi/interactivepython
/recursion_reverseWord.py
785
3.875
4
# recursively # write a function that takes string as parameter # and returns a new string that is reverse of the old string from stack import stack rev = stack() wordlist = [] reverseWord = "" # reverse word tanpa recursion def reverse(words): # 4, 3, 2, 1, 0 iterasi = len(words)-1 while iterasi >= 0: ...
bf8c910710b9bb56557b41628f9fcaad53ade019
excelkks/MachineLearning
/感知机/perceptron.py
1,210
3.625
4
class perceptron: ''' perceptron class, use Stochastic Gradient Descent to training coefficient ''' def __init__(self, x_train, y_train): self.x_train = x_train self.y_train = y_train self.w = np.ones((len(x_train[0]))) self.b = np.ones((1)) def sign(self, x_input): ...
c2aa268fac623483f54166ed94e01428e44df57c
CX-Bool/LeetCodeRecord
/Python/Array/88E. Merge Sorted Array.py
768
3.953125
4
# 执行用时: 44 ms, 在Merge Sorted Array的Python3提交中击败了99.73% 的用户 # 内存消耗: 6.5 MB, 在Merge Sorted Array的Python3提交中击败了86.92% 的用户 class Solution: def merge(self, nums1, m, nums2, n): """ :type nums1: List[int] :type m: int :type nums2: List[int] :type n: int :rtype: void Do not ...
3e55840c6e1eda86ba8f8aa34e0d61a8c3564871
voicezyxzyx/python
/Exercise/爬虫/yx_02_爬虫2.py
151
3.75
4
def sum_number(num): if num == 1: return 1 temp = sum_number(num - 1) return num + temp result = sum_number(1000) print(result)
570bdffc7adc4f60b0e6301331cc630c1a644df4
ishmam-hossain/problem-solving
/leetcode/222_count_complete_tree_nodes.py
478
3.71875
4
# Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def countNodes(self, root: TreeNode) -> int: self.total = 0 def count_nodes(head): if head is None: r...
1c78419875a72333fe8f2f1954516c79ad8811a5
ojasjoshi18/Ojas-Joshi
/Angstrom_number.py
579
3.75
4
#Name:Ojas Joshi #Gr no:11810839 #roll no:23 #Division:M def armstrong(n): #function to define armstrong number sum=0 t=n while t>0: d=t%10 #Separating out the number into indiviual digits sum=t**3 ...
b177ba463cc8d3a47178536520f1513bb0f38ceb
olliechick/instagram-unfollowers
/generate_dirs.py
2,586
3.9375
4
#!/usr/bin/python3 import errno import os from file_io import write_to_file STORE_LOGIN_DATA_PROMPT = "Do you want to store you login data on this computer? " \ "Note that it will be stored in plaintext, so don't do this on a shared computer." def get_boolean_response(prompt): response...
d78b72fd2c95c43ab76a2e97c17263c485de7ea4
pndx/learn-to-use-python
/PythonQuickTips2.py
421
3.78125
4
# Python Splat/Unpack Operator - Python Quick Tips my_list = ["hello", 'world', 4, 5] my_dict = {"apple": 1, "pear": 2, "orange": 3} function_args = {"name": "world", "age": 6} def test1(name, age): print(name, age) def test2(**kwargs): print(kwargs) def test3(*args): print(args) print(*my_list) pr...
5fc94675c4e94ebf87deca5648b813f4c3fcddc0
eopr12/pythonmine
/st01.Python기초/py09예외문/py09_01_Error.py
1,388
3.59375
4
# 교재 222-228페이지 # 숫자가 아닌 것을 정수로 변환하려고 할 때 # 숫자가 아닌 것을 실수로 변환 할 때 # 소수점이 있는 숫자 형식의 문자열을 int() 함수로 변환하려고 할 때 # IndexError 입력값 = int(input("숫자를 입력하세요.")) # 입력값 = "abc"이면 에러 발생 try: 입력값 = int(input("숫자를 입력하세요.")) # 입력값 = "abc"이면 에러 발생 입력값 = float(input("숫자를 입력하세요.")) # 입력값 = "abc"이면 에러 발생 입력값 = int(i...
2fc4acecfc788f5ad519829bc9ebd381355202ae
wakkpu/algorithm-study
/20 Summer Study/command-and-conquer/binary_search.py
867
4.1875
4
def binary_search(A, left, right, k): # A is list to input # left is the most left index # right is the most right index # k is the number we try to find # it cannot be reversed if left > right: return None # mid is the middle index mid = (left + right) // 2 # if the middl...
39bed9e7ea3fc2ba7d9788c5a1206fa8606b183b
therachelbentley/algorithms
/python-playground/mathlib/math_lib.py
3,071
3.984375
4
def _gcd(a, b): """Returns the greatest common divisor of two numbers. Params: a (int) b (int) """ a = abs(a) b = abs(b) if(a < b): a, b = b, a r = a % b if r == 0: return b else: return _gcd(b, r) def _lcm(a, b): "...
14334e83989e0302c99bbdf517bffaf2de6e2356
LoralieFlint/learning-python
/Lists.py
647
4.0625
4
# lists in python are arrays in javascript friends = ["Jess", "Jess", "Jess", "Hope", "Lexi", "Tattoo Girl"] # lists can hold stings numbers and booleans friends2 = ["Jess", 1, True] # index starts at 0 just like javascript print(friends[0]) # targeting index by negative numbers # starts at the last index of list # ...
8bb4930f77abe42a728d62a21c17690bd5985a34
LeandroBP/Python
/HandsOn/Aula03/funcoes.py
2,054
3.734375
4
#!/usr/bin/python import sys import json usuarios = [] def exibeMenu(): print "\n1 - Para cadastrar usuarios" print "2 - Para listar todos os usuarios" print "3 - Para deletar um usuario" print "4 - Para autenticar um usuario" print "5 - Sair" def cadastraUsuario(usuarios): with open("banco.tx...
e101d0202251923a727abc9cacd09359db7386cf
chanathivat/Python
/050264.py
3,851
3.65625
4
############################################################5.1#################################################################################################### class nisit: def __init__(self,name,province,year,department,sex): self.name = name self.province = province self.year = year ...
61497cccfc7d401400ef0a24a3cebf59ae1bbfce
optimus1810/crackingTheCodingIntPython
/binary_search_tree.py
3,731
3.890625
4
from Queue import Queue __author__ = 'Gaurav' class BSTNode: def __init__(self, content): self.content = content self.left = None self.right = None def insert(root, node): if root == None: root = node else: if root.content > node.content: if root.left i...
2d1a783822cf5778895eb3c98fc113e79160eb0a
siddharthcurious/Pythonic3-Feel
/Data-Structures/Graph/topological_sorting/topological_sorting.py
1,231
3.75
4
class Topological: def __init__(self, v, graph): self.v = v self.total_nodes = set(range(self.v)) self.graph = graph def print_nodes(self): print(self.total_nodes) def indegree_zero(self): child_nodes = [] for k, v in self.graph.items(): child_no...
dbd6172f19f90bedfa2f942c0133efa1900151c4
JArmour416/python-challenge
/PyPoll/main.py
3,098
3.5625
4
import os import csv election_csv = os.path.join("Documents", "GitHub", "python-challenge", "PyPoll", "election_data.csv") # Set variables total_votes = 0 khan_votes = 0 correy_votes = 0 li_votes = 0 otooley_votes = 0 # with open(election_csv, newline="", encoding='utf-8') as csvfile: with open(election_csv, newline...
de2c9e343c4ef9c735a3582f012e41e4146f157e
lucassilva-2003/Cursoemvideo_Python_100exs
/ex019.py
270
3.6875
4
# sorteio de alunos from random import choice a1 = input('Digite o 1 nome: ') a2 = input('Digite o 2 nome: ') a3 = input('Digite o 3 nome: ') a4 = input('Digite o 4 nome: ') escolha = (a1, a2, a3, a4) print('O aluno sorteado foi {}'.format(choice(escolha)))
1274ea5cab74389e68915793408c37b85b5274a3
devdutt-dikshit/furnish
/problems.py
910
3.5625
4
# solution 1 and 2 # https://github.com/hemanthmalik/furnish.git print('Solution for problem 1 and 2 are updated at https://github.com/hemanthmalik/furnish.git') # endpoints /register and /login for respective apis along with a token secured testapi for security validation # haven't added cors and allowed h...
37732912b9a5ec2c63c511cb4223d688404b409c
gaurav-dalvi/codeninja
/python/matrix_diagonal_print.py
1,321
4.4375
4
# https://www.ideserve.co.in/learn/print-matrix-diagonally#algorithmVisualization # Key points to remember: # 1: to understand what was the exact order of printing, had to watch video. Ask interviewer # 2: these two loops are very tricky # 3: understand to split this problem into two separate pair of for loops is the b...
d0c9ee11d96f4eb2cf9f98de4891a439f6f895eb
nyxtom/fbpuzzles
/puzzles/liarliar.py
3,415
3.828125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys import re colors = dict(red="\033[1;31m", nc="\033[0m") def print_error(message): """ Prints the appropriate error message to the user in full red color as it should be. """ print '%s%s%s' % (colors['red'], message, colors['nc']) class Puz...
2e92f456a5d3cf5ea78039b88453c2b260afbbc8
liemlyquan/project-euler
/p4.py
635
3.765625
4
''' Problem 4: A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99. Find the largest palindrome made from the product of two 3-digit numbers. https://projecteuler.net/problem=4 ''' first_number = 999 second_number = 999 array_of...
fe1fe83467d0cb87fc08d7ad78422a8d164150f9
neelamy/Leetcode
/Graph/140_WordBreakII.py
1,368
3.53125
4
# Source : https://leetcode.com/problems/word-break-ii/description/ # Algo/DS : Graph, DFS # Complexity : O() class Solution(object): def wordBreak(self, s, wordDict): """ :type s: str :type wordDict: List[str] :rtype: List[str] """ wordDict = set(wordDict) ...
65f06134a80f78a3ddcbef8529544fdb790abe1e
dianaparr/holbertonschool-higher_level_programming
/0x03-python-data_structures/8-multiple_returns.py
264
3.84375
4
#!/usr/bin/python3 def multiple_returns(sentence): if sentence == "": tuple_two = (len(sentence), None) else: # other form represents position 0 of the string with splice tuple_two = len(sentence), sentence[:1] return tuple_two
9e735698ecb205e83968bbee384732a132b1cb47
usac201602491/Proyectos980
/Ejemplos/Pogramacion Basica/Ejemplo3.py
194
3.671875
4
def esPar(num): if(num%2>0): return False else: return True for i in range(10): if(esPar(i)): print("Es par : ",i) else: print("Es impar : ",i)
56048abbfee557932a9dd38e3273addc907fd9e0
snowan/interviews
/2021/python/20.valid-parentheses.py
1,244
4
4
""" 20. Valid Parentheses Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. An input string is valid if: Open brackets must be closed by the same type of brackets. Open brackets must be closed in the correct order. Example 1: Input: s = "()"...
21b277478a5a1c7862ab8ddfee98b8d81126affe
serdarayalp/my-python-2
/MoneyInWallet.py
596
4
4
# Use raw_input to get info from the user nOnes = raw_input('How many ones do you have? ') nFives = raw_input('How many fives do you have? ') nTens = raw_input('How many tens do you have? ') nTwenties = raw_input('How many twenties do you have? ') # Use int to convert the inputted strings to integer values before mult...
c2e76e612150284541fb33ad2e3bd4792fd4a02a
raufmca/pythonCodes
/FileOperations2.py
1,139
4.34375
4
""" Uses Python's file class to store data to and retrieve data from a text file. """ def read_data(filename): """ Print the elements stored in the text file named filename. """ with open(filename) as f: for line in f: print(int(line) , end = ' ') def write_data(filename): """ Allows t...
3be0bf00a1d82d9a144b7a6f90a3dea5ccb66c71
liucheng2912/py
/leecode/数据结构/二叉树/先序遍历-迭代.py
2,387
3.75
4
''' 算法1:将根节点入栈,然后弹出栈顶元素,将值追加到res末尾,然后将右子节点和左子节点一次入栈,因为左子节点要先出栈,所以先入栈右子节点 算法2:cur指向root根节点,将值追加到末尾,将根节点入栈 然后让cur指向cur.left 继续上述操作 当cur为None时,弹出根节点,让cur指向cur.right 继续上述操作 算法3:父节点遍历后不入栈,将右子节点入栈 ''' class Solution: # 前序遍历 def pre_order(self, root): stack = [] # 将根节点入栈 stack.app...
35432eb5027ad1056bae19d52e9a9e01ef692c14
Owhab/Python-Codes
/StringFormating.py
293
4.1875
4
while True: print("Enter 'x' for exit.") string = input('Please Enter any string: ') if string == 'x': break else: new_string = string.replace(" ","") print("\n New String after removing all spaces: ") print(new_string, '\n')
b873739e464141263e4f399836e5b668bd5e3943
amy243/wallbreakers_week1
/stringmanipulation_q9.py
366
4
4
''' Write a function that reverses a string. link:https://leetcode.com/problems/reverse-string ''' class Solution: def reverseString(self, s: List[str]) -> None: def revv(start, stop, st): if start<stop: st[start],st[stop]=st[stop],st[start] revv(st...
80850428c02381c7461ace01f3ab4e05b72f510d
Bob-CHEN26/IBI1_2019-20
/Practical5/Exercise 7/powersof2.py
617
3.640625
4
# -*- coding: utf-8 -*- """ Created on Wed Mar 11 10:32:44 2020 @author: 10139 """ # Get the function ceil from math import ceil # Give x is a value x=1750 # Add a string variable s=str(x)+" is " # Find n which makes 2^n is closest number to x and smaller than x. for n in range (0, ceil(x**0.5)+1) : if (2**n < x)...
d04a9ff0572d8ed9364260823eb1c300922deb0d
NiCrook/Edabit_Exercises
/30-39/35.py
491
3.859375
4
# https://edabit.com/challenge/gbWDtMHtZARm7sdNA # Python has a logical operator "and". # The "and" operator takes two boolean values, and returns True if both values are True. def and_(bool1: bool, bool2: bool) -> bool: try: if bool1 and bool2: return True else: retu...
1e8e9ac6fc2290b6f7a0ca32802d8d8779f59ca7
peddroy/my-road-to-Python
/venv/Scripts/09_secao/53_listcomprehension.py
3,291
4.46875
4
""" LIST COMPREHENSION - PARTE 1 Utilizando List Comprehension podemos podemos gerar novas listas com dados processados a partir de outro iteravel. Sintaxe de List Comprehension [dado for dado in interavel] numeros = [1, 2, 3, 4] res = [numero * 10 for numero in numeros] print(res) def quadrado(valor): ret...
d31a1550ba1f32cb1f60c4e0bafbd01189764546
juliaheisler/CSE-231
/proj08.py
8,740
3.828125
4
############################################################################### # Computer Project 8 # # Algorithm # # Program uses 7 functions to take information provided in .csv file and\ # user's region input to create organized table and scatter plot. # # open_file: attempts opening file if it exists ...
2bb8dc9ee323c494bcee41020ca3939f10170a07
Erfan021/Implement_OOP_Python
/venv/Abstraction_and_Encapsulation.py
1,851
4.03125
4
class Library: def __init__(self, listOfBooks): self.availableBooks = listOfBooks def displayBooks(self): print() # Encapsulation being done print("Books in Library:") for books in self.availableBooks: print(books) def lendBook(self, requestedBook): if ...
24037d09430d35a666678c9639bd5ad12eb0a96b
bluepine/topcoder
/algortihms_challenges-master/general/odd_man.py
433
3.953125
4
""" In an unsorted array of integers each except one appear twice Find the element that appears once Idea: Do xor on array and the one that is left as a result is element that appears once """ def odd_man(array): if array is None or len(array) < 1: return False if len(array) == 1: return array...
bbcbbeac8350810bd6e2c1cc3252d0448b173c24
ARSimmons/IntroToPython
/Students/apklock/session02/sum_series.py
189
3.609375
4
def sum_series(l,m,n): # return the 'lth' place in the series with starting values of m and n if l == 1: return m if l == 2: return n return sum_series(l-2,m,n) + sum_series(l-1,m,n)
47a743a5f6b8b6c160db272423892512fb8273bb
linzhulz/CLRS
/chapter10_ElementaryDataStructure/chapter10.1-4.py
1,526
3.875
4
#!/usr/bin/env python # coding=utf-8 class Queue: def __init__(self, size): self.q = [0 for _ in xrange(size)] self.head = 0 self.tail = 0 self.size = size def enqueue(self, x): if (self.tail + 1) % self.size == self.head: raise Exception('overflow') ...
f993d49c0192e37c9f35b05d4f624bc80c3cd096
hky5401/MyAlgorithm
/Baekjoon Algorithm/Step/3_1차원 배열/7_4344_평균은 넘겠지_실수 자릿수 출력.py
432
3.546875
4
num = int(input()) result = [] for i in range(num): num_list = list(map(int, input().split())) people = len(num_list) - 1 avg = sum(num_list)-num_list[0] avg /= people count = 0 for j in range(1, len(num_list)): if(num_list[j] > avg): count += 1 re = count / people r...
21fee9082c166ae353507fc4c81024baf00b3d98
pingwindyktator/AdventOfCode
/2019/day_6/part_2_dijkstra.py
1,059
3.78125
4
def find_shortest_path(start, end, neighbours): import sys vertices = list(neighbours.keys()) distances = {v: sys.maxsize for v in vertices} distances[start] = 0 while vertices: current = min(vertices, key=lambda v: distances[v]) if distances[current] == sys.maxsize: break ...
ea90e3cf5a5e1d34a7f806dd4018b9c88ae6248c
anasvassia/Riddle-Maze
/maze_game.py
2,482
4.0625
4
# http://www.101computing.net/creating-sprites-using-pygame/ # http://www.101computing.net/pygame-how-to-control-your-sprite/ # https://stackoverflow.com/questions/28098738/changing-size-of-image # https://stackoverflow.com/questions/31570527/how-to-get-the-color-value-of-a-pixel-in-pygame # a maze game where in order...
0a77930e31eefbc949d6d6983b518bc8094632f3
mattmakesmaps/python-algorithms-data-structures
/recursion/turtle_fractal.py
1,037
4.125
4
import turtle import itertools colors = ['tan', 'yellow', 'tomato', 'violet', 'blue', 'LemonChiffon'] colorPicker = itertools.cycle(colors) def tree(branchLen, t): # Base case, branchLen less then 5 if branchLen > 5: t.color(colorPicker.next()) t.forward(branchLen) t.right(40) ...
746546a9118acd00262870fe6b5341eaf95932c2
alisen39/algorithm
/algorithms/sword_offer/25_mergeTwoLists.py
1,077
3.546875
4
#!/usr/bin/env python # encoding: utf-8 # author: Alisen # time: 2022/7/22 20:36 # desc: """ 剑指 Offer 25. 合并两个排序的链表 https://leetcode.cn/problems/he-bing-liang-ge-pai-xu-de-lian-biao-lcof/ """ class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def mergeTwoLi...
83943d7da7860592c34b57ec9ee3df26d3f01de0
dhbandler/Projects
/HangmanGraphics.py
4,572
3.6875
4
#Daniel Bandler #4/4/18 #HangmanGraphics.py --- makes a hangman game graphically from ggame import * from random import randint def pickWord(): #Selects the word num = randint(0,1) choices = ["praetor", "purgatory", "perestroika","airport","realpolitik","beelzebub","fraternal","schadenfreude","intelligen...
cf065520b4994e10a80c17c62aa81c53535600a7
Niguwa/848iPython
/digits.py
201
4.0625
4
string=input("enter string: ") count1=0 count2=0 for i in string: if(i.isdigit()): count1=count1+1 count2=count2+1 print("the number of digits is: ") print(count1)
1ca45414208e908aed7078974e28a13c69564583
thenerdpoint60/Sem_5
/SEM_5/AI/BFS.py
421
3.734375
4
g={'A':{'B','C'}, 'B':{'A','D','E'}, 'C':{'A','C'}, 'D':{'B','G'}} def bfs(g,s,goal): explored=[] queue=[s] while queue: node = queue.pop(0) if node not in explored: explored.append(node) neis=g[node] for nei in neis: queue.appe...
626475ef01013ce2bc88fedac15798b9ce21ad8b
JagadeeshVarri/learnPython
/Basics/prob_12.py
233
4.28125
4
# Write a Python program to print the calendar of a given month and year. import calendar year = int(input("Enter the year : ")) month = int(input("Enter the month : ")) print(" month calender : ") print(calendar.month(year, month))
05aeeacd3bfa9f1e67b61f67d83e000fe28ccf01
neethucmohan/solutions
/chapter2/reverseline.py
155
3.671875
4
#Problem 18 def reverse(fname): l=open(fname).readlines() r=map(lambda line:line.strip()[::-1],l) print '\n'.join(r) import sys reverse(sys.argv[1])
97d1219305140306d90c7356e7475ea2a81bb54c
Khalaf57/ml17kfma
/Python Scripts/Final_Model/agentframework.py
4,905
3.890625
4
# -*- coding: utf-8 -*- """ Created on Tue Dec 4 14:31:00 2018 @author: ml17kfma """ import random # random is a library contains many featurs and now it is imported # a classification of an agent characteristic and behavior that can move and eat and share with other agents within the environment given cla...
f19956ce276a8e493f5c8b5399732a092b41cd1c
qlhai/Algorithms
/程序员面试金典/01.03.py
884
3.5
4
""" 面试题 01.03. URL化 URL化。编写一种方法,将字符串中的空格全部替换为%20。假定该字符串尾部有足够的空间存放新增字符,并且知道字符串的“真实”长度。(注:用Java实现的话,请使用字符数组实现,以便直接在数组上操作。) 示例1: 输入:"Mr John Smith ", 13 输出:"Mr%20John%20Smith" 示例2: 输入:" ", 5 输出:"%20%20%20%20%20" 提示: 字符串长度在[0, 500000]范围内。 """ class Solution: def replaceSpaces(self, S: str, le...
62b75d82820bfe588b7404cf61f0561d976eaba1
jarvisi71729/Mega-Movie-Fundraiser
/01_Name_Not_Blank.py
309
3.8125
4
# Functions go here def not_blank(question): valid = False while not valid: response = input(question) if response != "": return response else: print("Sorry - this can't be blank") # Main routine goes here name = not_blank("What's your name? ")
307177ce185b797061df03cc0b2f94277832e762
xzmbghmf/Hacktoberfest_Event
/Make a Wish.py
1,393
3.890625
4
# Import the modules import sys import random ans = True while ans: question = raw_input("Ask if your wish will be granted: (press enter to quit) ") answers = random.randint(1,7) if question == "": sys.exit() elif answers == 1: print "Congratulations! The odds are in yo...
a253720337c9cab846961c31293e3d140a320225
SiddhantBhardwaj2018/ISTA-350
/lab10_solutions.py
11,161
3.828125
4
from bs4 import BeautifulSoup import json def make_soup(fname): """ This function takes a string as its only parameter. The string REPRESENTS the name of an html file. Your task is to CREATE and RETURN a BeautifulSoup object from the string parameter. """ return BeautifulSoup(open(fnam...
a65eecd4c8e3354758a741b09b49fe3525256c8d
wx1653265/my-summer
/cat.py
195
3.984375
4
cats=input("how many cats?") cats=float(cats) dogs=30 if cats<dogs: print"more dogs than cats." elif dogs<cats: print"more cats than dogs." else: print"same number of cats and dogs."
948dee36334fa4111d24ca0c287ebff399ed34ef
SemieZX/myleetcode
/q110.py
960
3.59375
4
class Solution: def isBalanced(self, root): """ :type root: TreeNode :rtype: bool """ def height(root): if root == None: return 0 return max(height(root.left),height(root.right)) + 1 if root == None: return True ...
7dc531f436fa15ea57909b1c9a25ee08ba611332
KleinTong/Daily-Coding-Problem-Solution
/min_sum_level/main.py
973
3.640625
4
from binary_tree import BTree from node import Node def level_split(root): def helper(node, level): if not node: return if level not in level_dict: level_dict[level] = [node] else: level_dict[level].append(node) helper(node.left, level+1) ...
cc4277de50313db57e219522193830190d42e6f1
L3onet/AlgoritmosOrdenamiento2019
/quicksort.py
821
3.71875
4
class QuickSort: def intercambia(self, A, x, y): tmp = A[x] A[x] = A[y] A[y] = tmp def Particionar(self, A, p, r): x = A[r] i = p - 1 for j in range(p, r): if (A[j] <= x): i = i + 1 self.intercambia (A, i, j) se...
8bb7db942185415f2c881b1c879d9960413520f1
pranaysathu/pythonTraining
/prime.py
165
3.53125
4
r = 1 while(r < 100): r = r+1 i = 0 con = 0 while(i <= r): i = i+1 if(r%i == 0): con=con+1 if(con ==2): print(r,end=" ")
a6373872488a3865d22117a7d5e26712311b0775
yangyuxiang1996/leetcode
/53.最大子序和.py
1,081
3.5625
4
#!/usr/bin/env python # coding=utf-8 ''' Description: Author: yangyuxiang Date: 2021-04-26 08:02:36 LastEditors: yangyuxiang LastEditTime: 2021-07-05 23:17:38 FilePath: /leetcode/53.最大子序和.py ''' # # @lc app=leetcode.cn id=53 lang=python # # [53] 最大子序和 # # @lc code=start class Solution(object): def maxSubArray0(se...
c294096eb6375db7ccb306a15563ce555cfd55d3
dev2404/Babber_List
/kadanes.py
293
3.5
4
#code def subarray(arr): currmax = maxi = arr[0] for i in arr[1:]: currmax = max(currmax+i, i) maxi = max(currmax, maxi) return maxi t = int(input()) for i in range(t): size = int(input()) arr = list(map(int, input().split())) print(subarray(arr))
eff1c1689f3411e6df31bf4d8c1cee219053eaab
rawnoob25/Optimization
/genBagCombinations.py
1,144
3.5625
4
# -*- coding: utf-8 -*- """ Created on Tue Jul 25 22:53:01 2017 """ def gen1BagCombo(L): for i in range(2**len(L)): out=[] for j in range(len(L)): if (i//(2**j))%2==1: out.append(L[j]) yield out def gen2BagCombo(L): for i in range(3**len(L)): out1...
c5ea220c6a17d5539cd0a75e11be05f9daa59ced
sora1441/4883-Programming-Techniques
/Assignments/A04/binary tree style 1.py
485
4.09375
4
from binarytree import Node root = Node(3) root.left = Node(6) root.right = Node(8) # Getting binary tree print('Binary tree :', root) # Getting list of nodes print('List of nodes :', list(root)) # Getting inorder of nodes print('Inorder of nodes :', root.inorder) # Checking tree properties ...
699aaa2417bfdf6a6895d0caacb21c5be1571d6c
sahilg50/Python_DSA
/Sorting/InsertionSortRecursion.py
996
4.28125
4
# Insertion Sort Using Recursion class InsertionSort: def __init__(self, array): self.array = array self.length = len(array) def __str__(self): return " ".join([str(item) for item in self.array]) def insertionSortRecursive(self, i=1): # Base Case if i == self.len...
759a3f376576c86a90301fa2633afb0c3da4f6b3
WhoisBsa/Curso-de-Python
/1 - Fundamentos/Calculadora.py
1,000
3.734375
4
from tkinter import * janela = Tk() def soma_click(): num1 = float(ed.get()) num2 = float(ed2.get()) lb["text"] = num1 + num2 def sub_click(): num1 = float(ed.get()) num2 = float(ed2.get()) lb["text"] = num1 - num2 def multi_click(): num1 = float(ed.get()) num2 = float(ed2.get()) ...
c3eb2b00c074ad73d6c617ea60dfd75bf7523254
mandulaj/Python-Tests
/Python/test.py
340
3.78125
4
class Animal(object): def __init__(self,a,b,c): self.a = a self.b = b self.c = 2*c def add(self,add): self.b += add c = Animal("ahoj",3,6) b = Animal("AHOJ",2,8) print (c.b) c.add(6) print (c.b) class Dog(Animal): def ADD(self): return 4 dog = Dog("Jakub",...
f2d55a138648d26e2dc9406674f0d47036b0eccc
lexruee/learning-python
/basics/zip.py
143
4.09375
4
#!/usr/bin/env python3 a, b, c = range(0, 10), range(10, 21), range(20, 31) zipped = zip(a, b, c) for a, b, c in zipped: print(a, b, c)
3760a35e73774c2b7814b13a2900bcf5198f7671
luciano-mendes-jr/Exercicios_Python3
/ex070.py
815
3.65625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Sep 12 10:44:25 2021 @author: luciano """ total = totmil = menor = cont = 0 barato = ' ' while True: produto = str(input('Nome do produto: ')) valor = float(input('Preço: R$ ')) cont += 1 total += valor if valor > 1000: ...
52a9a0aca34130e853048c3ddf0ce2c1239d486e
nelss95/Analisis1semestre2015
/Tarea1/InsertionSor/InsertionSort.py
373
3.953125
4
__author__ = 'nelson' def insertionSort(lista): for i in range(1, len(lista)): ValorActual = lista[i] position = i while position >0 and lista[position-1] > ValorActual: lista[position] = lista[position-1] position = position-1 lista[position] = ValorActual lista = [54,26,93...
f0785a73e11b3e04c2d28214aeeca6c74479a777
jinseok9338/Sudoku
/sudoku_board.py
11,084
3.734375
4
import turtle from random import randint, shuffle class Board: numberList = [1, 2, 3, 4, 5, 6, 7, 8, 9] counter = 0 def __init__(self): self.board = [[0 for _ in range(9)] for _ in range(9)] self.myPen = turtle.Turtle() self.myPen.speed(0) self.myPen.color("#000000") ...
ec04637919058dc2b4675994f1d069963f18e0eb
enigmatic-cipher/basic_practice_program
/Q69) WAP to sort three integers without using conditional statements and loops.py
261
3.859375
4
n1 = int(input("Enter first number: ")) n2 = int(input("Enter second number: ")) n3 = int(input("Enter third number: ")) n4 = int(input("Enter forth number: ")) n5 = int(input("Enter fifth number: ")) list = [n1, n2, n3, n4, n5] arr = sorted(list) print(arr)
12cb33d0a76f4bfbf97603afece6c20a55fe3da9
DiOsTvE/Python
/34 - ejer34.py
944
4.125
4
""" Introducir dos cadenas, decir si tienen la misma cantidad de caracteres, decir si no son iguales y cual es la más grande en longitud """ def pedir_cadena(): texto = input("Introduce la cadena: ") return texto def cuenta_caracteres(cadena1, cadena2): longitud1 = len(cadena1) longitud2 = len(cadena2) ...
e849edd9d6ecd6e932508136cc2f20e34217997e
asmakhanam54/EDM
/output.py
252
3.578125
4
dictOfList = { 'Boys':[72,68,70,69,74], 'Girls':[63,65,69,62,61] } listOfDict = [] len = len(dictOfList['Boys']) for i in range(0, len): listOfDict.append({'Boys': dictOfList['Boys'][i],'Girls': dictOfList['Girls'][i]}) print(listOfDict)
39e50504afb73da995e5f49ed5ff5cda3987d322
amoghrajesh/Coding
/extra_candies.py
182
3.546875
4
candies = [4,2,1,1,2] extraCandies = 1 m = max(candies) ans = [] for i in candies: if i+extraCandies>=m: ans.append(True) else: ans.append(False) print(ans)
d0d0910fc08e7934257fd32b3ba01fe94ccaface
ArkusNavrey/ADVENTURE
/NAGGAFLAGGA.py
1,689
3.84375
4
from Room import Room from inventory import Inventory from inventory import Stick print ' _____ __ __ __\n / ___// /__________ _____ ____/ /__ ____/ /\n \__ \/ __/ ' \ '___/ __ `/ __ \/ __ / _ \/ __ / \n ___/ / /_/ / / /_/ / / / / /_/ / __/ /_/ / \n/____/\__/_/ \__,' \ ...
028a0a3763cccdffe42e3b9cecebc1f3a8965c4b
MariaAndJava/PythonBoringStuff
/StopLight.py
552
3.5
4
berthaVonSuttner = {'belderberg_Ampeln':'green', 'platz_Ampeln':'red'} def switchLights(intersection): for key in intersection.keys(): light = intersection[key] if light == 'green': intersection[key] = 'yellow' elif light == 'yellow': intersection[key] = 'red' ...
54999660a6b7f518bcdefb9528f5fc0b12b25b58
msw1535540/ml_learn
/05_The_use_of_math_libraries/01_example.py
303
3.59375
4
# -*- coding: utf-8 -*- import numpy as np # 数据生成 # (列)reshape((-1, 1)): 1:一列,-1,算出来是多少就是多少行。 # (行)np.arange(6):在当前行数子上再加0,1,2,3,4,5(做一个广播) a = np.arange(0, 60, 10).reshape((-1, 1)) + np.arange(6) print(a)
5ad37a359ac19049a519faad582945bca70c4d6e
ophusdev/advent-of-code_2020
/2/day_2.py
2,363
3.515625
4
class DayTwo(): lines = [] valid_password = 0 valid_position = 0 def __init__(self): self.read_list() def read_list(self): with open('./_data/data_2.txt') as f: self.lines = [line.rstrip() for line in f] def part_one(self): for line in self.lines: ...
561bb0fd2c100544f8bce245ef9dbb548c7c9b8b
amirtha4501/PythonExercises
/altersorting.py
382
3.984375
4
import itertools a = [] n = int(input("Enter numeber of elements: ")) for i in range(0, n): ele = int(input("Element: ")) a.append(ele) a.sort() b = a.copy() b.sort(reverse=True) # Using zip we can access multiple lists simultaneously for (i, j) in zip(a, b): if i == j: print(i, end=" ") ...
b8682f7ba7118640a6f67c16984dc44154ffdbc0
jmwalls/iverplot
/iverpy/plots/base.py
792
3.515625
4
""" Plot interface class definition """ class Plot_object (object): """ Plot_object represents the interface class for a specific plot, e.g., a time series that plots both depth and altitude, or rph values plot object knows how to draw the specific plot including labels, legend, etc. Paramet...
229520867623f5ba4a49424ac0b583dfe9bba43c
zihaoy/cis472project
/perceptron.py
3,550
3.5625
4
import sys import re from math import log from math import exp #Some code use the homework code provided by Daniel Lowd <lowd@cs.uoregon.edu> MAX_ITERS = 100 # Load data from a file def read_data(filename): f = open(filename, 'r') p = re.compile(',') data = [] header = f.readline().strip() varna...
f2b2ba62b5b3e412cda386df385d9db2e81f9ec5
kareemawad2/python-For-beginners-
/Dictionary.py
591
3.703125
4
def main(): #student={'name':"wifi",'age':"15",'wepset':"https://www.youtube.com/",'slary':"2515.1,",'id':"1515615165"} student=dict(name="wifi",age="15",wepset="https://www.youtube.com/",slary="6515.1",id=51515456545) student['name']="kareem awad" del student["id"] print(student,type(student)) ...
8956e4d15be3616e2fe8040a1938a8ef0c97e71d
chrisliatas/py4e_code
/py4e_ex_02_03.py
99
3.828125
4
hours = input("Enter Hours: ") rate = input("Enter Rate: ") print("Pay:",float(hours)*float(rate))
959e70a1dd7d1d54cfe8edebd62821dccfbb9284
vishvapatel/Python
/pytohn GUI/login App/Loginpage.py
1,148
3.53125
4
from tkinter import * from tkinter import ttk from tkinter import messagebox layout = Tk() layout.resizable(False,False) layout.title("Login") def BUclick(): if( (userentry.get())=="admin" and (passwentry.get())=="1234"): messagebox.showinfo(title="Login Info",message="Welcome! to Python app") ...
caa34864905e6f2e9384faeda4c3a3c8cd8f10c3
jinlxz/CommandArgsParser
/cmd_arg_parser.py
3,559
3.6875
4
import sys class cmd_arg_parser(object): def __init__(self,cmd_args): self.index=1 """dictionary to store all command line arguments after parsing the command line successfully. the dictionary stores switch-styled options, key-value pair options, list of positional arguments. you can...
9875adbc48cbacdcb17d3971db3a65f9e374e43f
vaish28/Python-Programming
/JOC-Python/numpy_2-d.py
398
3.71875
4
# -*- coding: utf-8 -*- """ Created on Mon May 3 07:18:11 2021 @author: User """ ''' List slicing ''' import numpy as np array = np.zeros([2,4,3],dtype=np.uint8) print('Original array is: \n ',array, '\n') array[:,:2] = [5,5,5] print('After filling array by 5 array is : \n ',array,'\n') array[:,...
0b6957524d1212085a50ef2b5ef628636820d6ce
sameen964/python
/quadrant.py
451
4.21875
4
""" wap to get x and y coordinates from the user and print which quadrant it is in. """ x = int(input("Enter x coordinate ")) y = int(input("Enter y coordinate ")) print ("(x,y) = ({0}, {1})".format(x,y)) if ((x > 0) and (y > 0)): print ("Coordinate in Quadrant 1") elif ((x > 0) and (y < 0)): print ("Coordin...
db66a5a2ac714441f0bca4913e4e9422763af4ab
sssvip/LeetCode
/python/num485.py
1,092
3.859375
4
#!/usr/bin/env python # encoding: utf-8 """ @version: v1.0 @author: David @contact: tangwei@newrank.cn @file: num485.py @time: 2017/11/10 10:41 @description: Given a binary array, find the maximum number of consecutive 1s in this array. Example 1: Input: [1,1,0,1,1,1] Output: 3 Explanation: The first two d...
8101eafb4e1a296d814255993c74072d1cf7f7d5
vasilikikrem/pythonToSubmit
/ask7.py
428
3.8125
4
print "dwste tis lexeis xwrismenes me keno" # oles oi lexeis mazi words = raw_input() seperated = words.split(" ") # array kai se ka8e cell mia lexh ths eisodou maxLen = len(seperated[0]) # max len to mhkos ths prwths lexhs longestWord = "" for i in range (len(seperated)): if maxLen <= len(seperated[i]): # an einai...
808ffaa12922572f7312deaa29bb7d3af0325c71
edabrito7/sudoku-solver
/Soduku_solver.py
1,786
3.6875
4
# Sudoku solver sudoku = [ [0,6,3,0,8,0,4,0,0], [0,9,0,0,0,4,0,0,7], [4,0,0,0,2,0,0,0,0], [0,0,7,2,0,3,0,5,8], [0,5,0,0,4,0,0,0,0], [0,0,8,0,0,0,2,0,4], [6,0,0,0,0,0,7,0,0], [0,0,5,0,3,6,0,0,0], [0,3,0,8,7,0,0,2,6] ] def regla_1(sudoku,fila, num): #Chequea numeros por fila if num in sudoku[fil...
b3226581b74cf1a67e821110a869093ea1c96130
kononeddiesto/Skillbox-work
/Module24/01_fight/main.py
1,118
3.640625
4
import random class Unit: def __init__(self, name, health): self.name = name self.health = health def fight(self, enemy): print('Атакует {}'.format(self.name)) enemy.protection() print('У {} осталось {} здоровья. У {} осталось {} здоровья\n'.format( self.n...
e483415cd8e57415c7c6c0c5a88492b4d36e6a06
nophar16-meet/MEET-YL1
/OOP.py
574
3.71875
4
class Animal: def __init__ (self,name,age,color,size): self.name=name self.age=age self.color=color self.size=size def print_all(self): print(self.size) print(self.name) print(self.age) print(self.color) def eat(self,food): print("The animal "+self.name+" is eating "+food+" !") def sleep(self,h...
32a271ec4070c5567a4e02955b9100b9d3920f0b
bologno/SimpleFastFood
/store_user_register.py
3,083
3.5
4
import tkinter from store_user_login import StoreLogin from user_class import User from tkinter import messagebox class StoreRegClass(): ''' This class models the Register and LOgin for store system users. ''' def __init__(self): pass # self.name = '' # self.lastName = '' # ...
333c33030655e8bd627bdc8681c585fe17fe77f9
BrandonTrapp88/Practice.py
/months2.py
493
4.34375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Jul 15 22:52:36 2021 @author: brandontrapp """ # a program to print the month abbreviation, giving its number: def main(): #months is a list used as a lookup table months = ["Jan", "Feb", "Mar", "Apr", "May","Jun","Jul","A...
47ecdc1eb31038eaee1e697013e0b5eb0efd9275
ftczohaib/python_Assignments
/Assignment_3/Assignment3_3.py
596
3.9375
4
def AcceptData(): size = int(input("Enter The Number of Elements to Accept: ")); arr = list(); print("Enter the Numbers: ") for i in range(0,size,1): print("Enter the ",i+1," value: "); arr.append(int(input())); return arr; def GetMinimum(arr): min = arr[0]; for i in range(1...
7cfcad3c3365639d5b749d91c8b7881686104f23
yg42/iptutorials
/TB_IPR/TUT.IMG.stereology/python/section_spheres.py
2,054
3.515625
4
# -*- coding: utf-8 -*- """ Created on Fri Nov 4 09:50:35 2016 @author: Yann GAVET @ Mines Saint-Etienne """ import numpy as np import numpy.matlib as ml import matplotlib.pyplot as plt def generatePointsOnSphere(nb_points, R): """ Generate points on a sphere @param nb_points: number of points @ret...
18de3a14d402badd31b0be2feae55894e725c3e2
lgigek/alura
/python3/games/games.py
233
3.578125
4
import hangman import guess print("*************") print("Choose a game") print("*************") print("(1) Hangman \n(2) Guess") game = int(input("Which game: ")) if game == 1: hangman.play() elif game == 2: guess.play()
54db042a8c6808f0f85a364e9a7adda32183a693
bittu1990/python_code
/greedy_algo/min_non_increasing_sub_sequence.py
1,097
3.84375
4
"""Given the array nums, obtain a subsequence of the array whose sum of elements is strictly greater than the sum of the non included elements in such subsequence. If there are multiple solutions, return the subsequence with minimum size and if there still exist multiple solutions, return the subsequence with the maxi...
3c4a20b233860d202814087a9c658bc4d88aea54
critian-90/python-course
/Anidamiento_estructural.py/ciclo_for.py
656
3.953125
4
''' repetitiva_desde_1.py script e python que muestre los números enteros desde el 0 hasta el 13 usando un ciclo for ''' print ('Programa que muestra los numeros del 0 al 13 con for') for numero in range(14): print (f'{numero}') print('Fin del programa') print('Imprima los números pares desde el 2 al 20') prin...