blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
545k
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
545k
761c0c65b7de3d20aea8c04eeda0b0a53191b794
AlecFaye/Coding-Practice
/August 2020/August 17/MixedFractions.py
226
3.546875
4
numerator, denominator = map(int, input().split()) while numerator != 0: div_mod = divmod(numerator, denominator) print(div_mod[0], div_mod[1], "/", denominator) numerator, denominator = map(int, input().split())
f56ad16d6f572d3cc8e8df5d4cdf6c554a8beb78
a455bcd9/clustering
/execution.py
3,395
3.5625
4
# coding: utf8 import sys import json from math import sqrt import random # Load input JSON file containing Twitter friends entries. input = open(sys.argv[1]) lines = [] for line in input: data = json.loads(line.decode('utf8')) for x in data: if (x['following']): follow = 1 else: ...
b61e50bea2e0e57b2eaccc99be274f355b9a6cf0
A432-git/Leetcode_in_python3
/77_组合.py
577
3.734375
4
# -*- coding: utf-8 -*- """ Created on Thu Jun 11 15:40:16 2020 @author: leiya """ class Solution: def combine(self, n: int, k: int) -> List[List[int]]: def dfs(path,k,depth,res,start,n): if depth == k: res.append(copy.deepcopy(path)) return for i...
690cff76e97dc6be28c4bfe239ec8b4c6d42824c
A432-git/Leetcode_in_python3
/49_字母异位词分组.py
334
3.578125
4
# -*- coding: utf-8 -*- """ Created on Tue Jul 21 09:52:27 2020 @author: leiya """ class Solution: def groupAnagrams(self, strs: List[str]) -> List[List[str]]: dict = {} for item in strs: key = tuple(sorted(item)) dict[key] = dict.get(key, []) + [item] return list(...
e4dc8b5fd2938a697029f0ca38cbf393493b908f
A432-git/Leetcode_in_python3
/946_验证栈序列.py
475
3.609375
4
# -*- coding: utf-8 -*- """ Created on Thu Sep 17 09:48:56 2020 @author: leiya """ class Solution: def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool: stack = [] start = 0 for num in pushed: stack.append(num) while stack and stack[-1] ==...
03dec76631aaacba74558f14752569c76bf9aa59
A432-git/Leetcode_in_python3
/226_翻转二叉树.py
1,566
3.796875
4
# -*- coding: utf-8 -*- """ Created on Fri May 8 11:57:52 2020 @author: leiya """ class Solution: def invertTree(self, root: TreeNode) -> TreeNode: if not root: return root.left, root.right = self.invertTree(root.right), self.invertTree(root.left) return root #层次遍历+...
14467e5b484badb293eb9b1e59e7a21093615c61
A432-git/Leetcode_in_python3
/树/104_Maximum Depth of Binary Tree.py
1,578
3.78125
4
# -*- coding: utf-8 -*- """ Created on Wed Sep 4 15:26:08 2019 @author: leiya """ #dfs或者bfs找到最大层数即是最大深度 # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def maxDepth(self, root: TreeN...
0072de31ee4e6c139480a0958004a4ae9f34949e
A432-git/Leetcode_in_python3
/88_Merge Sorted Array.py
5,283
3.8125
4
# -*- coding: utf-8 -*- """ Created on Wed Sep 4 09:29:08 2019 @author: leiya """ ''' 0702:从后向前比,即同时比两者最末尾的数,谁大谁放到nums1末尾0的位置上 思路是每次把所有大于nums2[n]的nums1中的所有值交换到后面,loop跳出后放以此n,可以概括成放尽可能多次的m,之后放一次n,然后移动nums2中的指针n ''' class Solution: def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None: ...
44f768df7f8fdf4e777ff9262c7338a7542d7d91
A432-git/Leetcode_in_python3
/106_从中序与后序遍历序列构造二叉树.py
656
3.734375
4
# -*- coding: utf-8 -*- """ Created on Sat Jun 20 09:03:47 2020 @author: leiya """ class Solution: def buildTree(self, inorder: List[int], postorder: List[int]) -> TreeNode: if not postorder or not inorder: return None root = TreeNode(postorder[-1]) index = inorder.index(root....
177426a694dde64e09edb729823f789b6b8be5a1
A432-git/Leetcode_in_python3
/605_Can Place Flowers.py
553
3.9375
4
# -*- coding: utf-8 -*- """ Created on Tue Feb 4 16:02:22 2020 @author: leiya """ class Solution: def canPlaceFlowers(self, flowerbed: List[int], n: int) -> bool: count = 0 for i in range(len(flowerbed)): if flowerbed[i] == 0 and (i == 0 or flowerbed[i-1] == 0) and (i+1 == len(flowerbe...
7e6b974fa593eab7a09741a79b6f686d1acea5d8
A432-git/Leetcode_in_python3
/23_合并K个排序链表.py
2,921
3.515625
4
# -*- coding: utf-8 -*- """ Created on Sun Jul 19 17:02:10 2020 @author: leiya """ ''' 0812 python3里heapq可以对编译器自有变量类型组成的元组进行比较; 比较的机制是从元组首位0开始,即遇到相同,就比较元组下一位,比如(1,2), (1,3),前者比后者小。 ''' #首先把所有链表里的第一个node放入最小堆,即构建大小为K的最小堆,每次弹出最小的 class Solution: def mergeKLists(self, lists: List[ListNode]) -> ListNode: i...
9d93f4ad8e66d27a5dd89e6012d5f175325cf5f5
A432-git/Leetcode_in_python3
/349_两个数组的交集.py
708
3.828125
4
# -*- coding: utf-8 -*- """ Created on Tue Jul 14 20:30:23 2020 @author: leiya """ #简单双指针 class Solution: def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]: if not nums1 or not nums2: return [] nums1Len = len(nums1) nums2Len = len(nums2) p1, p2 =...
8bf8929bbfe763af15cf61cdb294ca78b59bc057
annamwebley/PokerHand
/deck.py
2,626
4.15625
4
# Project 3b # Anna Markiewicz # May 12 # deck.py # Shuffle the Card objects in the deck import random from card import Card class Deck: """Card Deck, which takes self as input, and creates a deck of cards """ def __init__(self): self.cards = [ ] for suit in ['C', 'D', 'H', 'S']: ...
492eddbeffe120a0ca71fc4767ce8e6523b04978
lshpaner/python-datascience-cornell
/Analyzing and Visualizing Data with Python/Importing and Preparing Data/LoadDataset.py
2,531
4.125
4
#!/usr/bin/env python # coding: utf-8 # ## Analyzing the World Happiness Data # # # ### Preparing the data for analysis # In this exercise, we will do some initial data imports and preprocessing to get the data ready for further analysis. We will repeat these same basic steps in subsequent exercises. Begin by exe...
16a5b99a4e1c7049227e738128d3b382a60e2949
lshpaner/python-datascience-cornell
/Writing Custom Python Functions, Classes, and Workflows/Writing Docstrings/exercise.py
1,070
4.0625
4
# In the code editor, add the following docstring to the function # add_two_strings_with_separator. Remember that the docstring is part of the # function definition and therefore must be indented appropriately. """ Returns the concatenation of the first string and the second string, separated by the separator. """ ...
28b512c74e3fd196b8ca592e9c81d72bfe1f9672
lshpaner/python-datascience-cornell
/Constructing Expressions in Python/Computing the Average (Mean) of a List of Numbers/exercise3.py
975
4.53125
5
""" Computing the Average (Mean) of a List of Numbers Author: Leon Shpaner Date: July 19, 2020 In exercise3.py in the code editor window, create a new list containing a mixture of letters and numbers: my_other_list = [1, 2.3, 'a', 4.7, 'd'], and write an expression computing its average value using a similar expre...
98269365703f82e15da200949483316583454b29
lshpaner/python-datascience-cornell
/Writing Custom Python Functions, Classes, and Workflows/Simple Ciphers With Lists and Dictionaries/exercise.py
2,492
4.59375
5
""" Simple Ciphers With Lists and Dictionaries Author: Leon Shpaner Date: August 14, 2020 """ # Examine the starter code in the editor window. # We first define a character string named letters which includes all the # upper-case and lower-case letters in the Roman alphabet. # We then create a dictionary (using a ...
58b9212ff4aa3daffbf810013afad3a7cfae632c
lshpaner/python-datascience-cornell
/Writing Custom Python Functions, Classes, and Workflows/Basic Exception Handling/exercise.py
2,695
4.09375
4
""" Basic Exception Handling Author: Leon Shpaner Date: August 9, 2020 Exceptions are errors generated at runtime based upon the values of particular variables; that is, they are different than syntax errors which are always wrong and which can be detected when you try loading the code. By anticipating certain ty...
7bb7e2da671eb0e9d1640d22963fae78755ea136
lshpaner/python-datascience-cornell
/Writing Custom Python Functions, Classes, and Workflows/Building a Custom Class and Creating New Objects/exercise.py
3,082
4.375
4
""" Building a Custom Class and Creating New Objects Author: Leon Shpaner Date: August 16, 2020 Because the strings, dictionaries and functions work together to carry out various tasks, which we’d probably like to reuse, it makes sense to bundle them together in a new datatype, the ShiftCipher. We’re calling it a Shi...
9ff24847cde4e4740fa52e2116374ed6a1e2b065
Boris-0412/python-boris
/s2 lesson8/2-8-1.py
235
3.671875
4
class Student: def __init__(self, name, age): self.name = name self.age = age def get_older(self): print("My name is",s.name) print(s.age) s = Student("Boris", 14) s.get_older()
060467da007c90e930786d0e4cb38b8cb52940e5
eyjolfurben/Assignment5
/Fair traffic lights.py
1,316
4.28125
4
north_int = int(input("Number of cars travelling north: ")) south_int = int(input("Number of cars travelling south: ")) east_int = int(input("Number of cars travelling east: ")) west_int = int(input("Number of cars travelling west: ")) sum_of_all_cars = north_int + south_int + east_int + west_int north_counter = nort...
40e8297a49d670182f32093d2359282a8827a406
joinkumaresh/python-tutoring
/day06.py
921
3.859375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Jul 27 08:32:06 2020 @author: kudevara """ # letters = 'asdf' # asc_letters = sorted(letters) # print(asc_letters) # colors = ('r', 'o', 'y', 'g', 'b') # asc_colors = sorted(colors, reverse=True) # print(asc_colors) # search num = [3,7,1,4,2,8,5,6...
c4bedcb4f9462b2dec19aa823eddd438526e793f
prhod/mailsender
/src/mysmtp.py
2,001
3.5625
4
from smtplib import SMTP, SMTPAuthenticationError from email.base64mime import body_encode as encode_base64 import base64 class mySMTP(SMTP): def auth(self, mechanism, authobject, *, initial_response_ok=True): """Authentication command - requires response processing. 'mechanism' specifies which aut...
86f052fe6eebb9c0d9fa8baeccc9b1ed5326ce6b
Aranccar/Code
/SPOJ/CPTTRN4 - Character Patterns (Act 4).py
834
3.84375
4
t=int(input("")) while t!=0: numbers = (input("").split()) l=int(numbers[0]) c=int(numbers[1]) h=int(numbers[2]) w=int(numbers[3]) list1=['*','.'] # Этот лист отвечает за длину точек(наверное) list2=[] for i in range(w): list2.append(list1[1]) list2.append(list1[0]) ...
4bccdcdaf0500875ab339a80eb45f7eb8e8759ce
Aranccar/Code
/SPOJ/BSCXOR - XOR.py
108
3.65625
4
numbers = (input("").split()) a=int(numbers[0]) b=int(numbers[1]) if a == b: print(0) else: print(1)
dd8badeee89c91a9c8012c288090ad6611a97d30
rverdi642/Intro-Python
/src/days-2-4-adv/item.py
1,424
3.515625
4
from player import Player from room import Room class Item: def __init__(self, name, description, items): self.name = name self.description = description self.items = items def __str__(self): return self.name def on_drop(self): print(f"You have dropped {self.name}.")...
4de88d6fcb5c7bd6ff3d00dc099ae0dab15c00b2
jetalone85/hackerrank_python
/separate_the_numbers.py
1,561
3.6875
4
#https://www.hackerrank.com/challenges/separate-the-numbers/problem?utm_campaign=challenge-recommendation&utm_medium=email&utm_source=24-hour-campaign def findFirstNo(s): if len(s)>=2: for i in range(1,len(s)): if 2*i<=len(s) and int(s[0:i])+1==int(s[i:i+i]): return int(s[0:i]) ...
a396a5e524a2520379b414d8e007386916cbf450
jetalone85/hackerrank_python
/repeated_string.py
247
3.71875
4
#https://www.hackerrank.com/challenges/repeated-string/problem s=input() n=int(input()) f=s.count('a') no_of_strings=int(n/len(s)) chars_in_infinite=f*no_of_strings rem=n%len(s) rem_chars=s[0:rem].count('a') print(chars_in_infinite+rem_chars)
82356f764ec22d1f9738c95404be5cf6729d96b9
jetalone85/hackerrank_python
/palindrome_index.py
665
3.921875
4
#https://www.hackerrank.com/challenges/palindrome-index/problem?utm_campaign=challenge-recommendation&utm_medium=email&utm_source=24-hour-campaign def checkPalindrome(s): return s[::-1]==s def palindromeIndex(s): i=0 j=len(s)-1 index=-1 while(i!=j and abs(i-j)!=1): if(s[i]!=s[j]): ...
f74487a8cb5749cf9cd2057cff1988d27d41918f
jetalone85/hackerrank_python
/larry's_array.py
1,353
3.703125
4
#!/bin/python3 #https://www.hackerrank.com/challenges/larrys-array/problem?utm_campaign=challenge-recommendation&utm_medium=email&utm_source=24-hour-campaign import math import os import random import re import sys from collections import deque # Complete the larrysArray function below. def larrysArray(A): s=sorte...
02b69ebb898723cf6724a3ee2df03cbba9a75e14
praveenprabha/python-calculator
/calc.py
567
4.0625
4
def add_value(x,y): return x + y def substract_value(x,y): return ( max(x,y) - min(x,y) ) def multiply_value(x,y): return x * y def divide_value (x,y): pass def square_value (x): return x ** 2 x = int(input('Enter Value for X : ' )) y = int(input('Enter Value for Y : ' )) print(x,y) print("Addition Val...
366e6992360d48a5c7ea99ed3707c73cbdbd3af0
whitnyyoung/fifa-database-project
/fifa18.py
3,859
3.671875
4
import mysql.connector # Execute: # python3 fifa18.py # user is able to create a new addition to table called clubs def insertClub(): lastid = input("Id :") name = input("Club Name: ") clubcity = input("City: ") budget = input("Budget: ") mycursor = mydb.cursor() sql = "INSERT INTO clubs ...
3f8cf3e1b71e395ddf27dd8ca9b92e48f8442ac6
DamarisMariscal01/alive1
/LEVEL 5/DESCUENTOS.py
727
3.953125
4
#Inputs print ("Descuentos") cProductos = float(input("Dime la cantidad de productos que compraste: ")) pProductos = float(input("Dime el precio del artículo que compraste: ")) #Proceso precioTotal = cProductos * pProductos total = precioTotal descuento = 0 if precioTotal > 5000: descuento = precioTotal * 0.15 ...
fafe00b91316d040c1b2471d73ef4bcf5c986fd0
DamarisMariscal01/alive1
/LEVEL 4/SUELDOOOS - copia.py
580
4
4
#Inputs """sueldoMeses = float(input ("Escribe el sueldo que recibes mensualmente: ")) #Proceso quincena = 0.15 * 2 ahorroMes = sueldoMeses * quincena sueldoAhorrado = ahorroMes * 12 print ("Este es el dinero que te ahorras en un año: " , sueldoAhorrado) """ #Funciones def sueldooos (sueldoMeses): quincena = 0.15...
11c369f0cc962329885fbb687d99a5e5b63bbdba
DamarisMariscal01/alive1
/LEVEL 4/DESCUENTO - copia.py
450
3.890625
4
#Input """compra = int(input ("Dime el precio total de tu compra: ")) #Proceso descuento = compra - (compra * 0.15) print ("Este es el total a pagar con el descuento incluido: " , descuento) """ #Funciones def descuentoss (compra): descuento = compra - (compra * 0.15) return descuento print ("Este es el descu...
f635b72257b7ad2af542e9d683c64e82eef42b69
cecidisi/leetcode
/121.best_time_to_buy_and_sell_stock.py
1,354
3.953125
4
### Solve with one loop # The points of interest are the peaks and valleys in the given graph. # We need to find the largest peak following the smallest valley. # We can maintain two variables - minprice and maxprofit corresponding to the smallest valley and maximum profit # (maximum difference between selling pric...
bcdb572bcbba2ed318e0d0d9121285be989d6621
lastcanti/effectivePython
/item3helperFuncs.py
848
4.4375
4
# -----****minimal Python 3 effective usage guide****----- # bytes, string, and unicode differences # always converts to str def to_str(bytes_or_str): if isinstance(bytes_or_str, bytes): value = bytes_or_str.decode('utf-8') else: value = bytes_or_str return value # always converts to bytes...
5de29c05b235f185f4030c864e39406c48fb1319
isfaaghyth/algorithm-playground
/Word Search II/solution.py
2,547
4.03125
4
""" https://leetcode.com/problems/word-search-ii Given a 2D board and a list of words from the dictionary, find all words in the board. Each word must be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be use...
de993c8dc70770372986208128988000d1e4c6a1
isfaaghyth/algorithm-playground
/Copy List with Random Pointer/solution.py
943
3.8125
4
""" https://leetcode.com/problems/copy-list-with-random-pointer A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null. Return a deep copy of the list. """ # Definition for singly-linked list with a random pointer. # class RandomListNode(obje...
82432240017599a3053f014d96b2c423d658d913
isfaaghyth/algorithm-playground
/Prefix and Suffix Search/solution.py
1,364
3.875
4
''' https://leetcode.com/problems/prefix-and-suffix-search Given many words, words[i] has weight i. Design a class WordFilter that supports one function, WordFilter.f(String prefix, String suffix). It will return the word with given prefix and suffix with maximum weight. If no word exists, return -1. Examples: Input...
6f8e34a2ddf2a1cfd7434206e2d70089224523e3
pmeyers279/basketball_db
/basketball_db/db_utilities/teams.py
1,374
3.5
4
def get_team_shortnames(): TEAMS =\ ['ATL','BOS','BRK','CHI','CHA','CHO',\ 'CLE','DAL','DEN','DET','GSW','HOU',\ 'IND','LAC','LAL','MEM','MIA','MIL',\ 'MIN','NOP','NYK','OKC','ORL','PHI',\ 'PHO','POR','SAC','SAS','TOR','UTA','WAS'] return TEAMS def get_team_longnames(): ...
dca014bef7c07c1f91b5d666afeb53f930ff0892
shobnaren/python-codes
/Sorting Algorithms/Bubble_sort.py
391
4.21875
4
def Bubble_sort(arr): for k in range(0,len(arr)-2): for i in range(0,len(arr)-k-1): if arr[i+1] < arr[i]: temp = arr[i+1] arr[i+1]=arr[i] arr[i]=temp print(arr) print("Sorted array using Buble sort:",arr) if __name__ == '__ma...
32b042f4dffd6a61debca25c708a5d72c1c8f76f
PabloPenguin/GUI-Math-Quiz
/mathquiz1.py
3,025
3.96875
4
from tkinter import* import random class student: def __init__(self, name, age): self.name = name self.age = age class mathquiz: def __init__(self, parent): self.difficulty = IntVar() self.difficulty.set(0) self.frame1 = Frame(parent) sel...
4a2fe62bc3e44e9e069509c03ab6cf155e036cc3
brian-lai/projectEuler
/Problem 7.py
296
3.75
4
countPrime = 1 currentPrime = 0 count = 2 while countPrime <= 10001: for i in range(2,count): if count%i == 0: if i == count: countPrime += 1 currentPrime = count else: break count += 1 print currentPrime
974f5d29d466db5e97b3aaf4309f5ca10592c04a
By-hoon/Learn-python
/basic/basic_list.py
449
3.984375
4
def is_on_list(days, find): return find in days def get_x(days, index): return days[index] def add_x(days, value): return days.append(value) def remove_x(days, value): return days.remove(value) days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"] print("Is Wed on 'days' list?", is_on_list(days, "...
5a4b3a7586a70ef5cda52096e5d94e3bc8f897eb
Skharshavardhan/Day3-assesment
/test.py
382
3.890625
4
print("welcome to the gift giving event") amt = int(input('Enter the gifting person number: ')) if amt >= 1: print("1 has recived gift from 2") elif amt >= 2: print('2 has recived gift from 1') if amt >= 3: print("3 has recived gift from 4") elif amt >= 4: print('4 has recived gift from 5') if amt...
5353a7ee1b5e02c722ef4aa31f8bfa579bfbb5c9
alishakundert/codewars-kata
/6kyu/[6kyu]Loose_Change.py
409
3.703125
4
''' Loose Change https://www.codewars.com/kata/loose-change/python ''' def loose_change(cents): if cents<0: cents = 0 change_dict = {} type_arr = ['Quarters', 'Dimes', 'Nickels', 'Pennies'] value_arr = [25, 10, 5, 1] for index, value in enumerate(value_arr): change_dict[...
925ad7241a368914f447e1f3a66ead79bdbf8b51
alishakundert/codewars-kata
/7kyu/[7kyu]Growing_Plant.py
404
3.859375
4
''' Growing Plant https://www.codewars.com/kata/simple-fun-number-74-growing-plant/python ''' def growing_plant(upSpeed, downSpeed, desiredHeight): day = 1 height = 0 while height < desiredHeight: height += upSpeed #day if height >= desiredHeight: break else: ...
a7b76f87369eb8aa59e5d9846d3986f0e6240ba7
newnativeabq/games
/blackjack.py
9,872
4.03125
4
''' Foundations of a Simplified BlackJack Game ''' from random import shuffle import os class Deck(): ''' Create an instance of a shuffled deck of cards ''' num_cards = 52 suits = ['Heart', 'Spade', 'Diamond', 'Club'] digit_cards = list(range(2, 11)) special_cards = ['Jack', 'Queen', 'King'...
b6d7dc61719b28288b3bce4fa5c6e4fbe96a9bfb
MateusCohuzer/Algoritmos-UTFPR-M31-de-2020
/UTFPR/LISTA2.Matrizes&&Dict2.py
5,092
3.59375
4
#Mapas/Dicionarios: #Número 1) Boletim = {} def Nome_Dict(quantidade): escopo = list() escopo_nota = list() for i in range(quantidade): escopo.append(str(input(f'Nome do {i + 1}° aluno: '))) escopo_nota.append(float(input(f'Nota do {escopo[i]}: '))) for i in range(len(escopo)): ...
0f395b530cbbe6e29933489697cf60a51d47b15e
MateusCohuzer/Algoritmos-UTFPR-M31-de-2020
/UTFPR/Prova.while -3.py
438
3.984375
4
add = int(0) qnt = int(0) entrada = int(1) while entrada > 0: entrada = int(input('Insira um número inteiro positivo [Zero ou negativos para parar]: ')) if entrada > 0: add += entrada qnt += 1 print('Registrado com sucesso') else: print('Você digitou um número negativo/zero'...
ed3f9cabacd6174fd2963c7d818c65ebefb7ac46
MateusCohuzer/Algoritmos-UTFPR-M31-de-2020
/UTFPR/Prova.while -2.py
672
3.890625
4
txt = str('S') desconto = int(0) while txt == 'S': valor = float(input('Insira o valor do carro (sem desconto): ')) ano = int(input('Insira o ano de fabricação do veículo: ')) if ano <= 2010: desconto = float(valor * 0.2) elif ano <= 2020: desconto = float(valor * 0.15) elif ano > 2...
7b5834fb00594a70515b65364c16473c8253a005
chvjak/cj-2019-1
/cj_2019_3_tkg.py
1,032
3.890625
4
f = open("input3_raw.txt") def input(): return f.readline() import string def primes(N): is_prime = [True] * (N + 1) is_prime[0] = is_prime[1] = False for i in range(2, N + 1): j = 2 * i while j <= N: is_prime[j] = False j += i return {...
b3e1def8ddf9f58d9f4360b38ef6e89f6de97552
SachBar/Intelligent_Mueslis
/functions/MMSimulator.py
12,197
3.546875
4
#----------------------------------------------------# #------------ MuesliMaker simulation ----------------# #----------------------------------------------------# # This simulator is inspired by the banking pyknow system used in exercises """ Defining simulation parameters """ n_MM = 2 # number of mueslimaker ...
59bf7bbfca29659f3c60719162de5be3e9919170
RyanKopa/radius_csv_cleaner
/test_clean_csv.py
1,754
3.765625
4
"""This script contains the unit tests for csv_cleaner.py We compare the output of csv_cleaner.py's example.csv test to a manually parsed file to compare if the fixes the program makes are the same as the manual ones. After running csv_cleaner.py, make sure example_clean.csv is in the fixed_files directory. Then run t...
71c9bf5b59165ffac0aac03bc4d7f2cbee4c80ac
yizhiyan1992/LeetCode_problems
/20_Valid_Parentheses.py
813
4.03125
4
# Stack problem, easy, time complexity: O(n) # Three cases to output False # 1) mismatch '[' with '}' # 2) remaining brackets in stack ['{', '(', '('] # 3) When encounter a close bracket, the stack is empty. (important!) class Solution: def isValid(self, s: str) -> bool: parentheses=list(s) stack=[]...
9e8f15caa99bc7f157944a587c026b6e111896d7
yizhiyan1992/LeetCode_problems
/127_Word_Ladder.py
1,282
3.71875
4
''' Maze+BFS since each word can only be replaced by one letter, the edit distance is just 1. To find the unweighted shortest distance, we can use BFS. To build the adj list is time consuming for this problem. Instead, we can think it as a maze problem which has 26 directions for each letter. , and remove the visited n...
acce3a6f3d1eb864474ee6d774a632c613bd38c2
yizhiyan1992/LeetCode_problems
/678_Valid_Parenthesis_String.py
1,442
3.671875
4
''' stack problem First thought: can we use recursion? Because the len(str)<=100, and there is no way to do prunning and DP, so we cannot use recursion for this problem. Though2: Use stack. create two stacks PAR and STAR to store '(' and '*' seperately. There are two conditions that '*' cannot help, namely *( and )* w...
3e2d02bf506438c7bdc6c10fd6aecebcfa4ef4a0
yizhiyan1992/LeetCode_problems
/1087_Brace_Expansion.py
1,088
3.609375
4
#backtracking #Note that it needs to return lexicographical order, so we need to sort for the bracket. class Solution: def expand(self, S: str) -> List[str]: if not S: return [] res=[] S=list(S) Len=len(S) def processing_bracket(depth): bracket=[] whil...
8f5d56de39a6361a61bb7b9c8660ed2e517bcf6e
yizhiyan1992/LeetCode_problems
/49_group_anagrams_solution2.py
391
3.75
4
#approach2: categorize by sorted string # Two strings are anagrams if ond only if their sorted strings are equal #time complexity: O(nklogk) class Solution: def groupAnagrams(self, strs: List[str]) -> List[List[str]]: Dict={} for i in strs: x=sorted(list(i)) Dict.setdefualt(s...
12a34383fa4a9d47c1cb36c4afb42f8b4d04bdb1
yizhiyan1992/LeetCode_problems
/767_Reorganize_String.py
1,424
3.609375
4
''' priority queue problem First, we need to cnsider if the string that meets the requirement exist. If the most frequent element is larger than len(S)/2, then it must not exist. Second, how to build the proposed string? Condition1: two consecutive characters must not be the same Condition2: The elements with high...
a571dba7371339e9deb6f9bcf73291e7210c8e5c
Tina0716/age-knowledge
/7.18.py
1,297
3.921875
4
class student: def __init__(self): self.name='' self.ID=0 self.GPA=0.0 def readfromkeyboard(self): self.name=input("enter a name of student") self.ID=int(input("enter the ID")) def get_all_student_from_keyboard(self): global student_list student_list=[...
a22f8ee42c5360f9ba0ddd1ce455ffe6661d14b8
Tina0716/age-knowledge
/7.22 mylongint.py
596
3.796875
4
class mylongint: def __init__(self): self.mylongint_number=0 def read(self): self.mylongint_number=int(input('enter a number')) def __str__(self): return 'my longlist number:%d'%self.mylongint_number def __add__(self, other): addvalue=self.mylongint_number+other.mylongin...
ecca5b07e3db6e4b9ab22cc321d7d65615eab17c
alexbuldey/figures
/example01.py
479
3.84375
4
import turtle example = turtle.Turtle() example.color("cyan") example.speed(100) turtle.bgcolor("black") def draw_square(): for side_a in range(4): example.forward(100) example.right(90) for side_b in range(4): example.forward(50) example.right(90) example.penup(...
fb1ad54ea057517d7f0e25a5d551dd42307554c6
JijithaRK/positive
/number.py
107
3.890625
4
j = float(input()) if j > 0: print("Positive") elif j == 0: print("Zero") else: print("Negative")
66660b1065f8b2378dd768ab0e02a94ae07e90f1
alexrybalka/ss_projects
/chessboard.py
1,302
3.703125
4
class Chess(object): def __init__(self, height=0, width=0): self.height = int(height) self.width = int(width) self.white = '* ' self.black = ' *' self.result = '' def set_white_elements(self, white=str): self.white = white def set_black_elements(s...
6e27535bde7a1978b86b9d03381e72a745af83ed
VladislavRazoronov/Ingredient-optimiser
/examples/abstract_type.py
1,520
4.28125
4
class AbstractFood: """ Abstract type for food """ def __getitem__(self, value_name): if f'_{value_name}' in self.__dir__(): return self.__getattribute__(f'_{value_name}') else: raise KeyError('Argument does not exist') def __setitem__(self, value_name, ...
ba8e4b4844c231be57a40d211d6e2f71ea47ddc6
Confucius-hui/LeetCode
/算法/235. 二叉搜索树的最近公共祖先.py
1,199
3.84375
4
class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def lowestCommonAncestor(self, root, p, q): """ :type root: TreeNode :type p: TreeNode :type q: TreeNode :rtype: TreeNode ...
976eaf919283cc8096839413bd995721810703e6
Confucius-hui/LeetCode
/算法/31. 下一个排列.py
773
3.640625
4
class Solution(object): def nextPermutation(self, nums): """ :type nums: List[int] :rtype: None Do not return anything, modify nums in-place instead. """ for k in range(len(nums)-2,-1,-1): if nums[k]<nums[k+1]: for i in range(len(nums)-1,-1): ...
5b7a183e2fe7e8e7a19242caa02adebb58355419
Confucius-hui/LeetCode
/算法/110. 平衡二叉树.py
1,191
3.8125
4
# Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def isBalanced(self, root): """ :type root: TreeNode :rtype: bool """ def Hight(root): ...
3aec1353f64dac675dd3754bcfc06dca7dfa5c3f
Confucius-hui/LeetCode
/算法/101. 对称二叉树.py
1,082
3.859375
4
# Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def isSymmetric(self, root): """ :type root: TreeNode :rtype: bool """ '''中序遍历''' d...
d30b39de24b1a1692b5c27899af47a1a73b1d1e5
Confucius-hui/LeetCode
/从排序数组中删除重复项.py
1,180
4.1875
4
''' 给定数组 nums = [1,1,2], 函数应该返回新的长度 2, 并且原数组 nums 的前两个元素被修改为 1, 2。 你不需要考虑数组中超出新长度后面的元素。 ''' class Solution: def removerDuplicates(self,nums): ''' :param nums: list[int] :return: int ''' i = 0 while i<len(nums)-1: if nums[i] == nums[i+1]: ...
3b3f993e0ba2620ca818218e9285af42ba306468
Confucius-hui/LeetCode
/移除元素.py
464
3.546875
4
class Solution: def RemoveElement(self,nums,val): ##判断数组是否为空 if len(nums) !=0: length = len(nums) for i in range(length-1): if nums[i] == val: nums.remove(nums[i]) return len(nums) else: return 0 if __name_...
06e6b68f1ebcd2e34d6789cf49f680e6203cf929
Confucius-hui/LeetCode
/字节跳动/数组与排序/朋友圈.py
869
3.65625
4
class Solution(object): #BFS def findCircleNum(self, M): """ :type M: List[List[int]] :rtype: int """ n = len(M) count = 0 visited = [0 for i in range(n)] for i in range(n): if not visited[i]: count+=1 self.b...
498efd52ff80b4f7defd7b9fa0ca851e79ea39b7
Confucius-hui/LeetCode
/排序算法/Sort.py
1,873
4.15625
4
##快速排序、冒泡排序、归并排序 class Sort: def Quicksort(self,nums,start,end): if start<end: i = start j = end x = nums[start] while i<j: while i<j and nums[j]>x: j-=1 if i<j: nums[i] = nums[j] ...
2cfd54a7d4c7248ff8f8042d824e477e12fb2ec9
zincsoda/euler
/p14.py
522
3.515625
4
#!/usr/bin/python2.6 def collatz_list(n): l = [] r = n l.append(r) while r > 1: if r % 2 == 0: r = r/2 else: r = 3*r + 1 l.append(r) return l if __name__=="__main__": starting_number = 1 chain_length = 1 for i in range(500001,1000001): ...
a51b4d949503abd8c9a2967ef3b839eaa889dff4
cullinap/dev
/practice/creative.py
142
3.75
4
def pyramid(i,j): if i == 0: return print(''.join(["*" for x in range(j - i)])) pyramid(i-1,j) pyramid(5,6)
b0dd917c3e6953eec21d72f6b67e629408f51c60
cullinap/dev
/practice/ex3.py
344
3.84375
4
# run practice warm exercise def run_practice(): times = 0 i = 0 while True: one_run = input('Enter 10 km run time: ') if not one_run: break i += 1 times += float(one_run) average_time = times / i print(f'Average of {average_time: 2f}, over {i} runs...
8cb7df1c753f7b291e7a5777dec0825856fcbf03
cullinap/dev
/backtracking/robot_maze.py
2,389
3.984375
4
# base cases # if the robot is home the return current solution # if robot is out of bounds no solution # if robot on X obstacle no solution # recursive cases # solve for the subproblem if the robot goes right # return the solution if the sub problem is solvable # if not backtrack # solve for the subproblem if the rob...
519fa01c572236e8a9f6ddf84077095944c984d3
cullinap/dev
/games/simple_encryption.py
191
3.625
4
plain_text = "This is a test. ABC, abc" encrypted_text = "" for c in encrypted_text: x = ord(c) x+=1 c2 = chr(x) encrypted_text = encrypted_text + c2 print(encrypted_text)
cfd6e878df088bab388b7331d4d66bb9d274c150
den01-python-programming-exercises/exercise-2-29-greatest-jakeleesh
/src/exercise.py
449
4.0625
4
def main(): #write your code below this line num1 = int(input()) num2 = int(input()) num3 = int(input()) answer = greatest(num1, num2, num3) print("Greatest: " + str(answer)) def greatest(num1, num2, num3): if (num1 > num2 and num1 > num3): return num1 elif (num2 > num1 and num2...
ec1c056847d7581c8e68482c5509c690328cace0
ganya7/OpenCV
/image_manipulation/dilation.py
1,037
3.734375
4
import cv2 import numpy as np image = cv2.imread('images/opencv_inv.png', 0) # Dilation adds pixel to boundaries of objects in an image # Erosion removes pixels at the boundaries of objects in an image # opening erosion followed by dilation # closing dilation followed by erosion cv2.imshow('Original', image)...
380c5e85bd8c996ec4b903b28a3edb9ed01dadbd
ganya7/OpenCV
/image_manipulation/scaling.py
1,095
3.890625
4
import cv2 import numpy as np image = cv2.imread(r'C:\Users\Arvind\Desktop\input1.jpg') def display_image(name, image): cv2.imshow("" + name, image) cv2.waitKey(0) cv2.destroyAllWindows() """Interpolation is a method of constructing new data points within the range of a discrete set of kno...
8883bedf1b30105f55d03f70708c63f5c63f268d
mattgoff/sudoku_solver
/app.py
1,787
3.5
4
import os board1 = [ [7,8,0,4,0,0,1,2,0], [6,0,0,0,7,5,0,0,9], [0,0,0,6,0,1,0,7,8], [0,0,7,0,4,0,2,6,0], [0,0,1,0,5,0,9,3,0], [9,0,4,0,6,0,0,0,5], [0,7,0,3,0,0,0,1,2], [1,2,0,0,0,7,4,0,0], [0,4,9,2,0,6,0,0,7] ] board = [ [0,0,0,8,0,0,4,2,0], [5,0,0,6,7,0,0,0,0], [0,0,0,0,0,9,0,0,5], [7,4,0,1...
3db603960c5d8a5bdb8dce1d42026a39187a3006
ndimaria/thermal_lights_py
/LEDS.py
433
3.515625
4
import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) red = 22 yellow=27 green=17 GPIO.setup(red,GPIO.OUT) GPIO.setup(yellow,GPIO.OUT) GPIO.setup(green,GPIO.OUT) def blink_led(led): print("LED on") GPIO.output(led,GPIO.HIGH) time.sleep(1) print("LED off") GPIO.output(...
b3fd43df05c6b6d75ffef1175cfc9dd4bffbd064
Akash1684/ScriptsPy
/hash_map.py
1,000
4.03125
4
table = [None]*10000 def store( string): """Input a string that's stored in the table.""" hash_index = calculate_hash_value(string) if table[hash_index]: table[hash_index].append(string) else: table[hash_index]= [string] def lookup(string): """Re...
b5ee186a8b2846d4162788a20467d59f10932768
Anton-gb/base_python
/Timoshkov_Anton_dz_2_4.py
272
3.75
4
name_list = ['инженер-конструктор Игорь', 'главный бухгалтер МАРИНА', 'токарь высшего разряда нИКОЛАй', 'директор аэлита'] for i in name_list: n = i.split(' ') print(f"Привет, {n[-1].capitalize()}!")
7a721c1358eb5518b0d408b63c5d860f7f2b8651
WWEISONG/Python_Project_100d
/Day10-进程和线程/多线程.py
1,580
3.796875
4
from random import randint from threading import Thread from time import time, sleep ''' 线程和进程在代码实现上特别的想,从抽象理解上其都是任务 通过使用封装好的threading模块中的Thread类 ''' # def download(filename): # print(f'开始下载{filename}') # time_to_download = randint(5, 10) # sleep(time_to_download) # print(f'{filename} 下载完成,耗费了{time_to_d...
b1986cd40397b91addfd79e252a755e552c14c57
WWEISONG/Python_Project_100d
/Day13-常见算法/穷举算法.py
1,701
3.875
4
''' 穷举法,又称暴力破解法,对所有的可能性进行验证,直到找到正确答案 ''' # 例子:百钱百鸡和五人分鱼 # 公鸡5元一只 母鸡3元一只 小鸡1元三只 # 用100元买100只鸡 问公鸡/母鸡/小鸡各多少只 ''' 如果全买公鸡的话 最多能买20只 如果全买母鸡的话 最多能买33只 如果全买小鸡的话 最多能买100只 ''' def find_chicken(): for x in range(20): for y in range(33): z = 100 - (x + y) # 注意 买的小鸡的数量必须得是3的倍数 if 5 *...
3a58def2df1594a4667aa194343a860c5bd7870d
SH4D0WR1D3R/AlevelCoursework
/database_quiz.py
5,164
4.125
4
#DATABASE - QUIZ #CREATING AND INITIALISING TABLES import sqlite3 c = sqlite3.connect("quiz.db") cursor = c.cursor() def database_login(c, cursor): c.execute("""CREATE TABLE IF NOT EXISTS STUDENT (STUDENTID INTEGER PRIMARY KEY NOT NULL, FIRSTNAME TEXT NOT NULL, SURNAME TEXT NOT NULL, ...
5028d917ed565417dd9b544e9b25ec4a7624e95f
Korzeniewski/cdv
/programowanie_strukturalne/8_zasieg_zmiennych.py
1,339
3.640625
4
#zasięg zmiennych, zmnienne lokalne i globalne #precyzja liczby (zaokroglenie do 3 miejst po przecinku) x = "{0:.3f}".format(5) print(x) def plsToChf(value): kursChf = 3.7913 iloscChf = value / kursChf iloscChf = "{0:.4f}".format(iloscChf) print(f'ilosc CHF: {iloscChf}') plsToChf(400) # zadanie f...
8154af8c77e45ef9ffd67046c38fb20b825836f1
YoonHyunSung/flask_docker
/oop/contacts.py
1,206
3.90625
4
'''name phone email address ''' class Contacts(object): def __init__(self,name,phone,email,address): self.name = name self.phone = phone self.email = email self.address = address def to_string(self): print(f'{self.name},{self.phone},{self.email}.{ self.address}') def set_cont...
942518a5a65513819d62a49754a30ff3f63dec65
jg-725/StatsCalculator
/RandomGenerator/SeedNumGen.py
331
3.578125
4
from random import seed from random import randint import random def num_seed(): number = [] seed(1) for i in range(1): number.append(randint(0, 10)) return number def num_seed_float(): number = [] seed(1) for i in range(1): number.append(random.uniform(.5, 10.5)) ret...
51f735d779b373b58080fa4532175e3091d35df2
SupremeSadat/HackerRank
/Python Solutions/Strings/String Validators.py
504
3.828125
4
if __name__ == '__main__': s = input() alnum = False alpha = False digit = False low = False up = False for x in s: if x.isalnum() == True: alnum = True if x.isalpha() == True: alpha = True if x.isdigit() == True: digit = True ...
6ab45ac3f8166399194332a4a6fb84009efb48f4
agota9/python-for-person-in-everybody
/toc.py
631
3.5625
4
import re # Para meter python detrás de ''' en vscode: # Busca: \n^(```)\n(\S) # Sustituye por: \n$1python\n$2 # # En la versión española: # Busca \n^```(\S) # Sustituye por: \n```python\n$1 # # Para cambiar el formato de los títulos en la versión inglesa: # Busca: ^(#+\s)\[(.*)\]\((.*)\) # Sustituye por: $1$2 {$3} # ...
e4cf60bedc9df20bb65fdec96560b95f4d05d655
hankangbok/almanacautomation
/FindDaylightSavingsDates.py
933
4.21875
4
import calendar def findDSTforYear(year): Sundaycounter=0 #To find the 2nd Sunday in march for a given year for i in range(1,15): ScndSundayCheck=calendar.weekday(year, 3, i) if ScndSundayCheck==0: Sundaycounter+=1 if Sundaycounter==2: DSTStart=[year,3,i] arrayStart=''.join(str(DSTStart)) ...
c3e40c1a2d1ab0d3d6585e1e621aa836480f345f
nrb/solitaire_player
/solitaire_player/rules.py
1,241
3.71875
4
from solitaire_player.deck import Card def is_valid(current_card: Card, destination: Card) -> bool: """Checks two cards for a valid move A move is valid when: The color of the cards do not match The value of the current card is one less than the destination This function won't be used to...
6c28575e3349310483ef174339be6431c367d66e
songdichong/275_gomoku
/main.py
4,241
4.21875
4
from tkinter import * import math import ai ''' Board class init: self.frame: call tkinter frame self.canvas:structured graphics facilities. Almost all the function used in tkinter is from this ''' class Board: def __init__(self,master,height=0,width=0): self.frame = Frame(master) self.frame.pack() ...
bafed50c96c3d856d329b71cce6b8157e4362b90
AldreyG/JornadaPythonFaixaPreta-2--ByLearn
/venda.py
1,250
3.875
4
def validar_idade(idade): if idade < 18: print(f'\nDesculpe, você não tem a idade para prosseguir, {nome}.') return False else: print(f'\nVamos prosseguir, {nome}') return True def escolher_carta(): print('Escolha uma das opções abaixo (número): ') print('1 - Carro\n2 - Moto\n3 - Carro e moto') ...
33dc36e56241897c46e26a299c829d82cab621a9
gsireesh/pax_queueing
/naming.py
740
3.671875
4
import random import string names = [ "Tomas", "Marylou", "Rodolfo", "Edgar", "Stuart", "Saul", "Elwood", "Jayne", "Maureen", "Edmundo", "Broderick", "Marion", "Silvia", "Marcie", "Edith", "Jaime", "Juliet", "Karla", "Shelby", "Shelley", ]...