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
fb5a9f19bdf79c6a60a46ae4d04795a8dcfaa367
YuanXianguo/Python-IT-Heima
/基础班/Python数据结构与算法/3、树/堆.py
1,844
3.515625
4
import heapq class HeapPreQueue(object): """优先队列——堆""" def __init__(self, heap_lst): self.heap = heap_lst heapq.heapify(self.heap) # 使用列表创建最小堆 def enqueue(self, elem): """向最小堆添加元素""" heapq.heappush(self.heap, elem) def dequeue(self): """弹出最小堆中的最小值""" ...
1bb5b9df95b47f6fcfe2e8c2f4de20e0d71f80ef
alimadeoliveiranatalia/Python
/mostra_maior_e_menor.py
380
4.0625
4
# Programa que armazena uma sequência de 5 valores inteiros e mostra o menor maior valor TAM = 5 valores = [] for i in range(0,TAM): valores.append(int(input(f'Informe o valor {i+1} da lista ' ))) print(f'O maior número é: {max(valores)} na posição {valores.index(max(valores))}') print(f'O menor número é: {min(valo...
60407cd27f03352fe7f46c09b115278dc62b24cf
rizqiyi/Functional-Programming
/src/modul_4/modul_4_3.py
608
3.8125
4
# Closure # def generator(y): # def multi(x): # return x * y # return multi # try1 = generator(int(input("Masukkan nilai 1 - 1 : "))) # print(try1(int(input("Masukkan nilai 1 - 2: ")))) # try2 = generator(int(input("Masukkan nilai 2 - 1: "))) # print(try2(int(input("Masukkan nilai 2 - 2: ")))) # D...
6d49301c3b68d15b1750fb734ad0bae4f8b9c184
Aasthaengg/IBMdataset
/Python_codes/p02419/s749988048.py
198
3.640625
4
w= input().casefold() cnt = 0 while(1): snt = input() if snt == "END_OF_TEXT": break sntt = snt.casefold() words = sntt.split() cnt += words.count(w) print(cnt)
c1ff3a1547125b4d3a88be8be7c7be385f20f0ed
LuqiPan/Life-is-a-Struggle
/10_Sorting_and_Searching/1_sorted_merge/sorted_merge.py
328
3.875
4
# a is the longer array def sorted_merge(a, b, m, n): cur = m + n - 1 i = m - 1 j = n - 1 while j >= 0: if a[i] > b[j]: a[cur] = a[i] i -= 1 else: a[cur] = b[j] j -= 1 cur -= 1 a = [1,2,5,6,0,0] b = [3,4] sorted_merge(a, b, 4, 2) ...
b9b8edec4634f2d6056d46a2960012b9364ae8b0
krishnareddygajjala/flash
/Practice/interview_programs/swapping.py
365
3.90625
4
a = 10 b = 15 print "before swapping a =%s and b = %s"%(a,b) a,b = b,a print "after swapping a =%s and b = %s"%(a,b) print "******************************************************" a = input("enter first number: ") b = input("enter second number: ") print "before swapping a =%s and b = %s"%(a,b) a,b = b,a pr...
24e7814e211119f56fac9eb95c9eb8b474b7a077
A-dot-35/DataStuctures-Algorithms
/HashTables/exercises.py
7,915
4.25
4
# Will use python dictionaries as it provides same functionalities as own implementation ''' Description: Function that returns wheather a list is a subset of another. Input: list1 and list2. Neither contain duplicate values Output: Boolean Time Complexity: O(m+n) Space Complexity: O(n) ''' def is...
828f4f76797ef3b4d16ef409373f5df0679a60c1
Nigirimeshi/leetcode
/0026_remove-duplicates-from-sorted-array.py
2,384
4.15625
4
""" 删除排序数组中的重复项 链接:https://leetcode-cn.com/problems/remove-duplicates-from-sorted-array 给定一个排序数组,你需要在原地删除重复出现的元素,使得每个元素只出现一次,返回移除后数组的新长度。 不要使用额外的数组空间,你必须在原地修改输入数组 并在使用 O(1) 额外空间的条件下完成。 示例 1: 给定数组 nums = [1,1,2], 函数应该返回新的长度 2, 并且原数组 nums 的前两个元素被修改为 1, 2。 你不需要考虑数组中超出新长度后面的元素。 示例 2: 给定 nums = [0,0,1,1,1,2,2,3,3,4], 函数...
6fde4f2643b49e806149ee30cb2b47fad522bb36
LVO3/python-2021
/test4.py
199
3.515625
4
print("you""need""python") print("you" + "need" + "python") print("you", "need", "python") print("".join(["you", "need", "python"])) # youneedpython # youneedpython # you need python # youneedpython
ffd77cf137cc998143d742bc2c3c6778e41bf05b
Python87-com/PythonExercise
/day10_20191114/old_exercise/22222.py
643
4.5
4
""" (扩展)一个小球从100m的高度落下   每次弹回原高度的一半.   计算:总共弹起来多少次(最小弹起高度0.01m). 总共走了多少米 """ # 小球一共走了多少米 初始化有个下落的100米高度 sum = 100 # 小球弹的次数 count = 0 # 设定下落高度 米 height = 100 # 最小弹起高度0.01m 当高度大于0.01米的时候小球才能弹起 while height / 2 > 0.01: # if height / 2 < 0.01: # break # 下一次的起/落高度 ...
2532dac4ac0acfef20d24910e5ead6c79e025987
b10n1k/Python_Workshop
/Person.py
623
4.09375
4
#!/usr/bin/env python #Filename: Person.py class Person: """This is the super class of Person""" def __init__(self, name=""): """constructor""" self.name=name self.introduce() print ">>>>" self.check_empty_name() #import more details def introduce(self): ...
64a3a679977e07b5ec160402331b35c5bb074529
nickfang/classes
/projectEuler/webScraping/problemTemplates/469.py
642
3.84375
4
# Empty chairs # # #In a room N chairs are placed around a round table. #Knights enter the room one by one and choose at random an available empty chair. #To have enough elbow room the knights always leave at least one empty chair between each other. # # #When there aren't any suitable chairs left, the fraction C of e...
ccdd7e175081607700a4493194c70d3e87bd6b23
dlopezg/leetcode
/easy/shuffle.py
592
3.78125
4
# Given the array nums consisting of 2n elements in the form [x1,x2,...,xn,y1,y2,...,yn]. # Return the array in the form [x1,y1,x2,y2,...,xn,yn]. # # EXAMPLE: # Input: nums = [2,5,1,3,4,7], n = 3 # Output: [2,3,5,4,1,7] # Explanation: Since x1=2, x2=5, x3=1, y1=3, y2=4, y3=7 then the answer is [2,3,5,4,1,7]. class S...
d847a06437ea041d95a0d5c8136a536181cb2bc0
rafaelsucra/coursera-test
/site/multiplos_3_ou_5.py
915
3.6875
4
import numpy as np import pandas as pd v_ENTRADA = int(input("Digite um valor, para identificar multiplos de um numero: ")) v_MULTIPLO_1 = int(input("Digite o primeiro numero: ")) v_MULTIPLO_2 = int(input("Digite o segundo numero: ")) lista_archive_1 = [] lista_archive_2 = [] lista_archive_1_2 = [] for v_loop in ran...
830e015ca6b13174db55106826997674a79f6ca4
Azoacha/cs234
/a3/a3q2.py
1,664
3.921875
4
## ## =========================================================================== ## Azoacha Forcheh (20558994) ## CS 234 Fall 2017 ## Assignment 03, Problem 2 ## =========================================================================== ## ## from dataStructures import PriorityQueue import check # TODO: add desi...
13df07071748e19c6b99a0bb14d298a87531701e
kilura69/softuni_proj
/2_advanced/exam_prep/2020-10-24-03_list_pureness.py
1,678
3.828125
4
''' Write function called best_list_pureness which will receive a list of numbers and a number K. You have to rotate the list K times (last becomes first) to find the variation of the list with the best pureness (pureness is calculated by summing all the elements in the list multiplied by their indices...
dcb80262399dddc11dceb0b8547bf09f6e7dedfc
hongfeng2013/algorithm009-class01
/Week_01/solution155_min_stack.py
1,046
3.9375
4
class MinStack(object): def __init__(self): """ initialize your data structure here. """ self.normal_stack = [] self.min_stack = [] def push(self, x): """ :type x: int :rtype: None """ if len(self.min_stack) != 0: if ...
65df62ab7adebd18e16b280ee4773a91d1c868b3
bobrolevv/contest2
/test.py
387
3.765625
4
# работа из дома d = int(input()) res = d stroka = "" while res != 1: if res % 2: stroka = (stroka + "1") #print(f'=={res % 2}=={stroka}') else: stroka = (stroka + "0") #print(f'=={res % 2}=={stroka}') if res == 2: stroka = (stroka + "1") break res = res // 2 ...
50ac6e9c15caf68f5cf8ceac4ab062d881e3f1b6
dexterpengji/practice_python
/leetcode/hard/median-of-two-sorted-arrays.py
773
4.15625
4
""" There are two sorted arrays nums1 and nums2 of size m and n respectively. Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)). You may assume nums1 and nums2 cannot be both empty. Example 1: nums1 = [1, 3] nums2 = [2] The median is 2.0 Example 2: nums1 = [1, 3] num...
2c83b3c03417938432c7624fb5b0fc0222772920
michaelgruczel/machine-learning-tutorial
/example-pycharm-tensorflow-2/main-cnn.py
3,600
4.03125
4
# First we want to import the libraries we need # this is TensorFlow and the Keras libs from tensorflow for machine learning # and some usefull libs like numpy (handling data) and matplotlib (print graphs) import tensorflow as tf import numpy as np # Main function # In PyCharm you can execute the code, by clicking on...
5f22532b5a4d82d32c607a6643e167bde027a08d
frekkanzer2/PythonTests
/Exercises/AddAttributeToClass.py
577
3.625
4
class EmptyClass: @classmethod def adderAttribute(cls, attrName: str, value) -> bool: if getattr(cls, attrName, None) is None: setattr(cls, attrName, value) return True else: return False class EmptySubClass(EmptyClass): pass item = EmptyClass() print(...
2ec35f0fa87291f38ac056672e495e4267c01154
yzl232/code_training
/mianJing111111/Google/Given a NxN matrix which contains all distinct 1 to n^2 numbers, write code to print sequence of increasing adjacent sequential numbers.py
1,227
3.875
4
# encoding=utf-8 ''' Given a NxN matrix which contains all distinct 1 to n^2 numbers, write code to print longest sequence of increasing adjacent sequential numbers. ex: 1 5 9 2 3 8 4 6 7 should print 6 7 8 9 ''' # 这是O(n4) 有O(n2)解。 用fill dp. # word search 变体 class Solution: # @param board, a list of lists of 1 ...
08513c4fec2c3a20d3e9e7dc2e8399729ded257b
thomasscarroll89/python-washu-2014
/day3/speak.py
313
3.75
4
def speak(message): if ("?" in message) and (message.upper() == message) and message != "?": return "Woah, chill out! Sure." if "?" in message: return "Sure." elif message == "": return "Fine. Be that way!" elif message.upper() == message: return "Woah, chill out!" else: return "Whatever."
4cce59525c32c390d75d3ab02ab2e3158a996819
sanketb412/PythonBasic
/Datastructure/Basic/reverse.py
188
3.671875
4
# ''"" # @Author: Sanket Bagde # @Date: 2021-08-08 # @Last Modified by: # @Last Modified time: # @Title : Print user Input in Reverse # ''' print(input("Enter First and last name:- ")[::-1])
6c7eb142263e573ca658d5f485efe06b97b10617
tildesarecool/ReallyHadtoPython
/automate boring stuff/web scraping lesson 38.py
6,484
3.578125
4
# web browser module # lesson 38 / chapter ? # pages 233 - 236 # decided to skip ahead to webscraping. just skipped over some further filesystem stuff and the debugger stuff # summmary # ? = says group matches zero or one times # * = zero or more times # + = one or more times # { } = match specific number of times # ...
67029629c7c64d330bb58cd4b3ea923a89555104
omarn33/Battleship
/Battleship.py
41,583
3.890625
4
#Omar N #CIS 1400 #Battleship Game #7/24/19 #This project is a one player Battleship game against the CPU. #The user first sets up their ships and then alternates turns with the CPU #in guessing the coordinates of the enemy's ships. The first to destroy the #opponent's ships wins the game! import random name = "" #Us...
7708f5f5f7bca5ae804a08a78ed06e97332e75f5
DianaHuisen/Programming1
/les5/die.py
244
4.125
4
name = input("What is your name: ") age = eval(input("What is your age: ")) if age >= 18: print("Please vote!") else: print("You're too young little one") print("Thank you for giving me your data "+name+", soon you will be hacked...")
a5a4d1cba4fca7ced1dc024607ad60e3ddd03408
dadcp88/python
/PracticeDaniel/Daniel/src/Udemy_Course/Seccion1/booleansandcomparisons.py
1,280
4.25
4
# # Booleans / True / False # truthy = True # falsy = False # age = 20 # is_over_age = age>= 18 # greather than # #the result for is_over_age and age 20 is True # print(is_over_age) # is_under_age = age<= 18 # less than # is_twenty = age == 20 #equal than # # #and & or python # # print(bool(34)) #print True # print(boo...
c45503d463483f883271c203dfb8040cd45510a8
BriskYunus/yunusrepo
/RPSGame.py
2,633
4.125
4
from random import randint mylifebar = 3 pclifebar = 3 z = 0 # available weapons => store this in an array choices = ["Rock", "Paper", "Scissors"] player = False # make the computer pick one item at random computer = choices[randint(0, 2)] while player is False: print("") print("Select your item!") prin...
c6082096934bc4e1bc05bf4a3fb89f5d2b08cd2b
hevalenc/Curso_Udemy_Python
/aula_128_patterns.py
1,743
4.125
4
#aula sobre Simple Factory Method """ Na programação POO, o termo factory(fábrica) refere-se a uma classe ou método que é responsável por criar objetos. Vantagens: Permitem criar um sistema com baixo acoplamento entre classes porque ocultam as classes que criam os objetos do código cliente. Facilitam a adi...
3225fd8fd84f9a0d4ede558bc21126bf949c0161
willyudi/pythonexercicios01
/exercicio01_williano_02.py
200
3.90625
4
#!/usr/bin/env python # encoding: utf-8 metros = float(input ('Digite o valor em metros: ')) milimetros = float(metros * 1000) print ('O valor convertido em milímetros é: %.0f ' % milimetros + 'mm')
c612a370c5dcae1d41d39ca7c4682ff7d225a660
pareeknikhil/Natural-Language-Processing
/Bigram Maximum Entropy Markov model (MEMM) to do Part of Speech Tagging/trial.py
999
3.515625
4
import re word = "eEkuuhjhefkj" prefixes =[] suffixes = [] # print(re.search(r'-',string1)) for i in range(1,5) : print(i) if(i<=len(word)) : prefixes.append([i,word.lower()[:i]]) for i in range(-1,-5,-1) : if(-i<=len(word)): suffixes.append([-i,word.lower()[i:]]) list1 = prefixes + suffixes # d...
c99e26aaf091da0e64130229e0862270645e284d
jahvelelliottophs/year10POPHS
/03 function input.py
190
4.0625
4
#the input function #allows human / users to enter #data in your program #by using the keyboard #the data is stored in a variable age = int(input("enter age >>>")) print(age)
2a5920d752f5b30b97fad8774c19a053975828ff
981377660LMT/python_cookbook
/src/7_函数/7_函数/3_partical固定参数值.py
467
3.671875
4
# artial() 可以更加直观的表达你的意图(给某些参数预先赋值)。 import math from functools import partial def distance(p1, p2): x1, y1 = p1 x2, y2 = p2 return math.hypot(x2 - x1, y2 - y1) points = [(1, 2), (3, 4), (2, 3), (1, 1)] # 到(2,2)的距离进行排序 # 相当于points.sort(key=lambda point: distance(point, (2, 2))) # key仍然是C...
1d7e0b63b5ff82b39b27352c2756c0bbd5e98020
Shota3yo/ABC_C
/C - Sum of gcd of Tuples (Easy).py
194
3.609375
4
K = int(input()) ans = 0 import math for i in range(1, K+1): for j in range(1, K+1): s=math.gcd(i, j) for k in range(1, K+1): ans += math.gcd(k, s) print(ans)
d6f45c7ef0699d4a5f239654f33cf15dedc18073
prajwal60/ListQuestions
/learning/ConditionalStatement And Loops/Qsn29.py
389
4.15625
4
# Write a Python program to print alphabet pattern 'X'. result = '' for row in range(0,7): for col in range(0,6): if ((col ==0 or col ==5)and (row !=2 and row !=3 and row!=4)or(row ==2 or row ==4)and (col == 1 or col == 4) or (row ==3)and (col==3 or col ==2)): result = result+'*' else:...
703bf4af4849b704401628fe9217ac9f63f04814
raianmol172/data_structure_using_python
/Tree_data_structure/Binary_tree/bottom_view.py
866
3.78125
4
class Node: def __init__(self, data): self.data = data self.left = None self.right = None def bottom_view(root): if root is None: return None else: q = [root] m = dict() hd = 0 root.hd = hd while len(q): temp = q.pop(0) ...
191e38ec913939d94d6f2775d10a1e6e61fd4c5d
MeghaSajeev26/Luminar-Python
/Data collections/List/multiply total elements.py
91
3.890625
4
#multiplication of total elements of the list l=[1,2,3] s=1 for i in l: s=s*i print(s)
fb83add7d4b80bdeccd477d34e172c3becb29789
Elvolox/ExerciciosPythonCurso
/Desafio74.py
385
3.9375
4
from random import randint num = (randint(1,10), randint(1,10), randint(1,10), randint(1,10), randint(1,10)) print('Os valores sorteados foram: ', end='') for n in num: # PRINTA OS NÚMEROS SEM VIRGULA E PARENTES print(f'{n} ', end='') #print (f'Os valores foram {num}') print(f'\nO maior nú...
5d492123466e49eba199c94cdc13f307b38f10b4
ziwenyu/firstgit
/calculator.py
978
4.0625
4
'''num1 = raw_input("give me the first number:") num2 = raw_input("give me the second number:") to_do = raw_input("What do you want to do with these two numbers? choose between 'add','substract','mutiply','divide'") if to_do == add: print num1+num2 elif to_do == substract: print abs(num1-num2) elif to_do == mutiply: ...
56d8adbddf8c08719c45e1a47c642320fcfcbfb9
shakeelsubratty/Population-Coding-in-RNN
/pop_coding.py
3,014
3.5625
4
# Implementation of method for encoding and decoding single values and Pandas dataframes to and from a population code # specified by function parmeters. import numpy import pandas from sklearn import preprocessing import matplotlib as mlp mlp.use('TkAgg') from matplotlib import pyplot # Code a single value into th...
35b7201fb5c2bbf797b479e5202c34272d7f53f9
UserWangjn/3.0
/second.py
246
3.765625
4
#!/usr/bin/env python # _*_ coding:utf-8 _*_ __author__ = 'YIMAO' import datetime import time def secondding(seconds): for i in range(seconds): # now = datetime.datetime.now() # print "计时",seconds-i time.sleep(1)
fc8b2db135be642d0a02164c808e6cd834e50a27
JosephLevinthal/Research-projects
/5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/223/users/4177/codes/1630_2924.py
156
3.546875
4
var1=int(input("a posicao inicial do movel(metros)")) var2=int(input("a velocidade do movel")) var3=int(input("o intervalo de tempo")) S=var1+var2*var3
09fd7e2681649d7dcdb2e6f8613f9eed93b90dea
pedrolisboaa/curso_python
/1_python_basico/5-operadores.py
349
3.9375
4
""" Operadores aritméticos + - * / // ** % () """ nome = 'Pedro' idade = 28 print(f'{nome},tem {idade} anos!') print('Multiplicação', 10 * 10) print('Adição', 10 + 10) print('Subtração', 10 - 2) print('Divisão', 10 / 2) print('Divisão de inteiro0', 10 // 3) print('Divisão', 10 / 3) print('Modulo', 10 % 5) print(10 ** 2...
203a07d5b1b33e981f93a50fe1b102422366001d
finalyearProjct/math-visualisation
/Documentation-Monte Carlo/source/monto.py
4,151
4.28125
4
"""Monte_carlo object This object creates an animation on how monte carlo works by estimating the value of pi """ class Monte_carlo: """ parameters: time_interval(float):time interval for the animation """ def __init__(self,time_interval): # Constructor self.np_0=np ...
1d8a09203459225a4e6192702b3552b432f83155
DongjunLim/teamplace
/10주차/LeetCode_94_Binary_Tree_Inorder_Traversal/dongjun.py
554
3.546875
4
''' 1. 문제접근 중위순회를 재귀적으로 구현해 풀었습니다. 2. 성능 Runtime: 24ms Memory Usage: 14.1MB Time Complexity: O(N) ''' class Solution: ret = [] def inorderTraversal(self, root: TreeNode) -> List[int]: self.ret = [] return self.inorder(root) def inorder(self, node): ...
e05ad1d79ada374d3ab515078bcacad1c118c6af
PNorfolk/CHIPS-Water
/Relay/OffRelay.py
294
3.5
4
import Adafruit_BBIO.GPIO as GPIO #defining the GPIO pins fill="P8_9" drain="P8_15" #Setting up the pins GPIO.setup(fill, GPIO.OUT) GPIO.setup(drain, GPIO.OUT) #Setting the relay to turn both pumps off GPIO.output(fill, GPIO.LOW) GPIO.output(drain, GPIO.LOW) print ("Both Pumps turned off. ")
b8efdace3226a2585ddbb803f039efdc584f0bcb
yaritzaelena/EXAMENES-Y-TRABAJO-EN-CLASE
/Gato.py
1,537
3.765625
4
class Pila: def __init__(self): self. __pi = [] def len (self): return len(self.__pi) def is_empty(self): return len(self.__pi) == 0 def push (self, e) : return self.__pi.append(e) def pop(self): if self.is_empty(): raise MiGatito('Stack...
c945fb19aa419bb02465ae6ff1d904e905698b4a
rajeevdodda/Codeforces
/Contests/Div#642/c.py
339
3.703125
4
# def single_integer(): return int(input()) def multi_integer(): return map(int, input().split()) def string(): return input() def multi_string(): return input().split() n = single_integer() for i in range(n): temp = (single_integer() -1) // 2 print(str(int(4 * (temp + 1) * temp * (2 ...
9785dfea38cf0b51f63163464071e85b5c4967a8
firewood1996/faas-sim
/sim/logging.py
2,204
3.515625
4
from datetime import datetime, timedelta from typing import Dict, NamedTuple class Clock: def now(self) -> datetime: raise NotImplementedError() class WallClock(Clock): def now(self) -> datetime: return datetime.now() class Record(NamedTuple): measurement: str time: int fields...
e7c96312ff0a624f6a22f634b9dac65c30654535
antoniofurioso/learn_openCV
/bitwise_operation.py
945
3.5625
4
import cv2 as cv import numpy as np '''Bitwise operator are 4 and these execute binary operation''' blank = np.zeros((400,400), dtype='uint8') rectangle = cv.rectangle(blank.copy(), (30,30), (370,370), 255, -1) circle = cv.circle(blank.copy(), (200,200), 200, 255, -1) cv.imshow('Rectangle', rectangle) cv.ims...
4f9dfd3b020decdbc7e246a52d962f313c598ddb
UlvacMoscow/Examples_tests
/digital_mult.py
387
3.65625
4
from functools import reduce """ х никогда не будет итерироваться по последнему элементу, у никогда не будет первым элементом """ def checkio(number: float) -> float: return reduce(lambda x, y: int(x) * int(y) if x != "0" and x != '.' else int(x), str(number)) print(checkio(10888888)) # print(01)
07d2cf5dc89e2daa448c616b23921ca160eb3128
Suyash906/Backtracking-2
/78_Subsets_Binary_Num_Mapping.py
1,070
3.53125
4
# Time Complexity : O(2^n * n) # Space Complexity : O(1) # Did this code successfully run on Leetcode : Yes # Any problem you faced while coding this : No # Problem Approach # 1. Suppose len of nums is 3 ([1,2,3]) # 2. The binary represenation with max len 3 range from(000 to 111) # Dec Bin Subset # 0 0...
7c9609d9484e92f92dcc8654b23ea6bb225edff5
mokkeee/CodeIQ_python
/codeiq_2513.py
442
3.84375
4
#!/usr/bin/env python # -*- coding: utf-8 -*- from itertools import combinations def has_256sum(_nums) -> bool: pairs = combinations(_nums, 2) match_pairs = list(filter(lambda x: x[0] + x[1] == 256, pairs)) return len(match_pairs) > 0 try: while True: input() nums = [int(x) for x in...
a29a6feee3ea6cd68210c30179f225d692581daa
InternityFoundation/ML_Prakhar
/PolynomialRegression/PolynomialRegression.py
1,967
3.6875
4
# -*- coding: utf-8 -*- import numpy as np import pandas as pd import matplotlib.pyplot as plt dataset=pd.read_csv("Position_Salaries.csv") X = dataset.iloc[:, 1:2].values #matrix of features y = dataset.iloc[:, 2].values from sklearn.linear_model import LinearRegression reg1=LinearRegression() reg1.fit(X,y) from ...
1cb1fa5e9ed78d5a8a26715b71ce04fece4dd17b
Jiaweihu08/DS-Alg
/Course3/week1_decomposition1/Coding_challenge/ex2.py
737
3.6875
4
#python3 import sys class Vertex: def __init__(self, key): self.key = key self.visited = False self.adj_vertex = [] def explore(self): self.visited = True for v in self.adj_vertex: if not v.visited: v.explore() def main(): lines = sys.stdin.read().strip().split('\n') # lines = '''4 4 # 1 2 # 3 2...
94fa6b517329b9920b1d520cc661985fafeb304b
samhabib/Pramp_Questions
/TrieSearchEngine.py
2,784
4.28125
4
''' Input: root_dict - A root node for our trie dictionary that we will navigate to see if it has the next letter in the string to move forward and repeat site_string - The site string that we will be checking to see if it has been visited by the crawler Output: True or False whether or not the site_string was a...
156903e8d7ba68247529f7acdf62394152c0fc7a
mazimidev/daen500
/def_score.py
549
4.03125
4
def computegrade(rawscore): if s >= 0 and s <= 1: if s >= 0.9: grade = 'A' elif s >= 0.8: grade = 'B' elif s >= 0.7: grade = 'C' elif s >= 0.6: grade = 'D' elif s <0.6: grade = 'F' else: grade = 'Not valid ...
ce168a657038a3fe6c05d24767bc0df4f539d5fd
Car-byte/CAP-4630
/min-max/board.py
6,080
3.8125
4
import math class Board: def __init__(self): self.board = [[' ', ' ', ' '], [' ', ' ', ' '], [' ', ' ', ' ']] # check if board is full def full(self): for arr in self.board: for item in arr: if item ==...
6245805def56babba7dbe0c06db2f2b44e5506d3
yyangyncn/core_programming
/core_programming/chapter8/e_8-9.py
199
3.890625
4
# fibo def fibonacci(num): if num in [1, 2]: return 1 else: return fibonacci(num - 1) + fibonacci(num - 2) for eachNum in range(1, 10): print(eachNum, fibonacci(eachNum))
98b8ded1440df37f6da0e39d504f7bc6ed28ae15
vubon/Python-core
/list example/one.py
84
3.65625
4
numbers = [1,5,3,4,6,9,7,8] numlist = sorted(list(set(numbers))) print(numlist[-2])
267d9e8a284836f6ed014d526244d5f33a09ec26
joelomax/AWS-Restart
/composite_data_types_solution.py
1,744
4.15625
4
# Lab 8: Composite Data Type import csv import copy #Exercise 1: Car Inventory # Define a dictionary to hold our data. myVehicle = { "vin" : "<empty>", "make" : "<empty>", "model" : "<empty>", "year" : 0, "range" : 0, "topSpeed": 0, "zeroSixty": 0.0, "mileage": 0 ...
0586931332ab8822eef6d84c12a9c94266a2b2dd
jemtca/CodingBat
/Python/AP-1/score_up.py
807
3.953125
4
# the "key" array is an array containing the correct answers to an exam, like {"a", "a", "b", "b"}. the "answers" array contains a student's answers, with "?" representing a question left blank # the two arrays are not empty and are the same length # return the score for this array of answers, giving +4 for each corre...
99ed82103081af6bd3d568b23474380f19a0e9b7
danebista/LeetCode-Algorithms
/Algorithms-LeetCode/11-20/19. Remove Nth node from the end of a singly linked list.py
793
3.671875
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode: templist=head l=self.findLengthOfLinkedList(templist) m=l-n-1...
0e38bcb95b938ae8efb2a6d55fd30c2738147028
fjxc1893/Study
/numpy_study/7_split.py
457
3.5625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- __author__ = "xtsheng" import numpy as np A = np.arange(12).reshape((3,4)) print(A) B = np.split(A, 2, axis=1) #按列将矩阵分成2等分 print(B) C = np.split(A, 3, axis=0) #按行将矩阵分成3等分 print(C) D = np.array_split(A, 3, axis=1) #按列将矩阵分成3份 print(D) print(np.vsplit(A, 3))#纵向分割成3等份 print(n...
f2e1054fbdea264206cac7d9c4f9b09c35f0ca8e
peya8291/NLP
/Yan-Peng-assgn3-part2-option2.py
4,780
3.53125
4
#!/usr/bin/env python # coding: utf-8 # In[1]: from collections import Counter from collections import defaultdict import numpy as np import math import random import re # In[2]: text = open("hobbit-train.txt",'r',encoding='utf-8') text=text.read() # In[3]: len(text) # In[4]: sentenceEnders = re.compile(...
42550260e9935d5112310bfdfd2b00eab2507fa9
gshen2/tkinter_stuff
/tkinterEx3.py
975
3.703125
4
import tkinter as tk from tkinter import ttk win = tk.Tk() win.title('Python GUI') # Label a_label = ttk.Label(win, text='Hello World!') a_label.grid(column=0, row=0) # Button def click_me(): action.configure(text='** I have been Clicked! **') a_label.configure(foreground='red') a_label.configure(text='...
734985a2e8e551fe4aabd792cd1295488559ac9d
Maninder-mike/100DaysWithPython
/intermediate/algorithms/comb_sort.py
631
3.609375
4
# TODO "This code is not working yet." def getNextGap(gap): gap = (gap * 10) / 13 if gap < 1: return 1 return gap def comb_sort(nums): shrink_fact = 1.3 gaps = len(nums) swapped = True i = 0 while gaps > 1 or swapped: gaps = int(float(gaps) / shrink_fact) swa...
4799ea25678d86d6fd117d3f6429f4a7e6a9a28d
kafelka/python_module2
/Chapter 10 Dictionaries/phonebook.py
3,511
3.96875
4
# -*- coding: utf-8 -*- """ Created on Mon Dec 17 15:09:58 2018 @author: mag """ phoneBook = {} #phoneBook = {"Joan": ("753", 13, "NW3 5GH", "London", 34), # "Eddie": ("225", 7, "AB10 1EZ", "Aberdeen", 28), # "Natalie": ("477", 5, "L1 0RD", "Liverpool", 26), # "Veronica": ("850", 21...
b6a7ce4e0706eb40789ebbb9d3902d5d4a78e5a0
Ligenmt/leetcode
/001两数之和.py
643
3.609375
4
def twoSum(nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ nummap = {} for i in range(len(nums)): nummap[nums[i]] = i for i in range(len(nums)): complement = target - nums[i] if nummap.get(complement) and nummap[complement] != i: ...
3e0849f6a9f7c95a02d41c1caa595372b196d333
tonydavidx/Python-Crash-Course
/Chapter6/glossary.py
603
3.859375
4
concepts = { 'for' : '\ta infinite loop when used program will run utill requirements satisfied\n', 'list' : '\tstores multiple number or strings\n', 'if' : '\tusing boolean operators if statements run the program\n', 'tupl' : '\ttupl is similar to list but you cant edit a tuple once created\n', 'c...
3ceee6b801ba0f690094d025137a90baaec1b029
DenBlacky808/Algo
/Lesson_1/Task_6.py
131
3.5
4
print('Введите номер буквы в алфавите ') n = int(input('n = ')) n = n + 96 char_1 = chr(n) print(char_1)
2e7f0b5f4a15e598a8770f732aece1617ee18187
Rodin2333/Algorithm
/剑指offer/03从尾到头打印链表.py
583
3.828125
4
#!/usr/bin/env python # encoding: utf-8 """ 输入一个链表,按链表值从尾到头的顺序返回一个ArrayList。 """ class Solution: def __init__(self): self.arrayList = [] def printListFromTailToHead(self, listNode): """ :param listNode: 链表的头指针 3->2->1 :return:返回从尾部到头部的列表值序列,例如[1,2,3] """ if not...
aa0a739c4071dafae518d377559943db6a2ad4c6
L3-S6-Projet/bdd_api
/scolendar/exceptions.py
1,049
3.578125
4
class TeacherInChargeError(Exception): def __init__(self, message: str = ''): """ Creates a new instance of this exception. This particular exception should be raised when a teacher is in charge of a particular subject, but the user is trying to remove it from that same subject. Thi...
16768d2e4d34ffbfffa170a7aa0b015a1726a71a
mohsinhassaan/Project-Euler
/SmallestMultiple.py
340
3.953125
4
multiple = 0 num = 0 nums = [x for x in range(1, 21)] while multiple == 0: num += 2 * 3 * 5 * 7 * 11 * 13 * 17 * 19 isMultiple = False for n in nums: if num % n != 0: isMultiple = False break else: isMultiple = True if isMultiple: multiple = n...
2cd02b67db76d9bbccd0d4dface9aab31cf6bd7c
Harin-Kaklotar/python-test
/ex8_printing_printing.py
1,864
4.71875
5
# printing printing # this all examples are base on book 'Learn python The Hard way' # and I add some extra examples on my own # here we are using python v 2.7 formator = "%r" print formator # it will print %r #but if we vant pass some valuse so what should we do?? let's see print formator %'Hello Harin' # stri...
7fc4cd330fc8df6e5ceaad7c9961bc83e8cee8d2
rvillaester/python-basic
/introduction/basic.py
458
3.609375
4
# this is an example of a comment def statement(): 'This function just shows different kind of statements' x = 'single line statement' i=1; j=2; team='Super Insurance' # multiple statements in a single line a = 1 + 2 + 4 \ + 5 + 6 + 3 \ - 7 - 4 b = (3 + 5 + 7 + 8 - ...
6f8f13721129b9e6943e0c7b98a82a0806f1c35b
AlejandroL12/ejercicios_act15
/assignments/00HelloWorld/src/sumaNnums.py
282
3.828125
4
def suma_N_numeros(N): s=0 for i in range (1,N+1): s=s+i return s def main(): #escribe tu código abajo de esta línea N=int(input("Dame un número: ")) suma=suma_N_numeros(N) print(suma) if __name__=='__main__': main()
9e8fec2e4da917aaca66ea8c2383218cd52ab61d
brucekwak/Programmers_algorithm_practice
/lv1_K번째수.py
380
3.765625
4
# UTF-8 # [풀이 #1] for문 활용 def solution(array, commands): answer = [] for command in commands: i, j, k = command target_num = sorted(array[(i-1):j])[k-1] answer.append(target_num) return answer # [풀이 #2] map 활용 def solution(array, commands): return list(map(lambda x:sorted...
1a53a1dc026d52b44e296f47dabe8599261fa582
behappyyoung/PythonSampleCodes
/Algorithm/Suffix_Tree2.py
3,576
3.78125
4
class SuffixTree(object): class Node(object): def __init__(self, lab): self.lab = lab # label on path leading to this node self.out = {} # outgoing edges; maps characters to nodes def __init__(self, s): """ Make suffix tree, without suffix links, from s in quad...
80e63d611d568d12d3172021e1b81dfcd2e94d3d
sidv/Assignments
/sufail/aug19/shape.py
318
3.9375
4
import math class shape: def area(self,length=0): self.length=length return (math.pow(length,2)) class square(shape): def __init__ (self,length): self.length=length def area(self): return (super().area(self.length)) l=int(input("Enter length")) sh=shape() sq=square(l) print(sh.area()) print(sq.area())
d9455664e107e7bbff5886348936028cc3d1bf9c
eloghin/Python-courses
/PythonZTM/100 Python exercises/12. Day03-even-digits.py
1,360
4.15625
4
""" Write a program, which will find all such numbers between 1000 and 3000 (both included) such that each digit of the number is an even number.The numbers obtained should be printed in a comma-separated sequence on a single line. """ # *********** # ** SOL 1 ** # *********** def check_even(digit): if digit%2...
d364671e91e4a41ee92b548d85f40271f0036080
RGero215/Interview_Questions
/product_of_array_except_self.py
1,093
3.828125
4
class Solution(object): def productExceptSelf(self, nums): output = [1] * len(nums) print("Output: ", output) prod = 1 print("**************************") for i in range(len(nums)): output[i] *= prod prod *= nums[i] print("Output: ...
9eb3a3ecf39bec45c5b2c131e9a7439b7ee3b662
SaraSat/PracticasAlventia
/python/clases.py
1,034
4.375
4
# fichero clases.py """ Este es el constructor de la clase Animal, donde self es la propia instancia de la clase, el primer parámetro que recibe el método, la clase tiene dos funciones, info y mover""" class Animal: def __init__(self, nombre, npatas, puedo_volar=False): self.nombre=nombre sel...
8ed8acfedc97590d27ba615823a606b2d75310b4
nuydev/my_python
/power_number.py
227
3.90625
4
#สร้างเลขยกกำลังในlist number = [1,2,3,4,5,6,7] ''' #std for i in range(len(number)): number[i]=number[i]**2 print(number) ''' #ลดรูป number = [i*i for i in number] print(number)
778bb3d253c5c53934e0817760f2977cda96c572
nabilahmed06/Advanced-Algorithsm-and-Data-Structures-
/q6/tree.py
619
3.609375
4
def enumerate_tree_for_n_value(a): """ This functions takes a list/list of list and does pre order traversal and generates the bit string :param a: List/List of List :return: A list containing the valid substring """ b = [] for i in range(len(a)): for j in range(len(...
3488c1d87ff31171d9e3a680d19a89d2b924672a
Impact-coder/hackerrank-problem-solving-solution
/Sales by Match.py
757
3.8125
4
#!/bin/python3 import math import os import random import re import sys # # Complete the 'sockMerchant' function below. # # The function is expected to return an INTEGER. # The function accepts following parameters: # 1. INTEGER n # 2. INTEGER_ARRAY ar # def sockMerchant(n, ar): # Write your ...
1f13e3e81b4e87158d20cd93977035f590af1a33
moskalenk/Python_automation
/codewar/positive_negativ_sum.py
392
3.65625
4
def count_positives_sum_negatives(arr): pos, neg = 0, 0 if len(arr) == 0 or arr == 0: return list() else: p = [el for el in arr if el > 0] for el in arr: if el > 0: pos+=el else: neg+=el return [pos, neg] count_positives...
4b68cc66ba067f06849a68a289e17222050fb326
rmags/LPTHW
/ex8.py
555
3.703125
4
# Assigning a variable to be a string compromised of 4 potential modifiable # sub-strings that can be defined by the user, each separated by a space formatter = " %r %r %r %r" # printing 6 different statements using formatting variable's print formatter % (1,2,3,4) print formatter % ("one", "two", "three", "four") p...
aa1bf095585f16ce9ee5b5276930913c2730522b
Krieglied/Assignments
/PythonProjects/CH02/per2H.py
2,530
4.34375
4
#Performance Lab 2H #Robert John Graham III #September 6 2018 """ Create a program that takes input of a group of students' names and grades... then sorts them based on highest to lowest grade. Then calculate and print the sorted list and the average for the class. (Hint: Use Dictionaries!) """ import ...
f49b063a9e5548f11ad726e46de71af2bef2ae32
abijithring/classroom_programs
/42_classes_objectoriented/inheritance/2_multilevel.py
240
3.546875
4
## multilevel class x: def m1(self): print "In method1 of X" class y(x): def m2(self): print "In method2 of Y" class z(y): def m3(self): print "In method3 of Z" z1 = z() z1.m1() z1.m2() z1.m3()
0cb17071a6e40b350e211ca455c2fef89d30be89
bencouser/project_euler
/28.py
531
3.703125
4
# starting at 1 and moving right and out in a clockwise direction gives the form #seewebsite # the sum of the diagonals is 101 # what is the sum of the numbers on the diagonals in a 1001 by 1001 spiral formed by the same # way # top right corner of square is always the dimension of the square, squared # 1 = 1**2, 9 =...
2869b3f55c49d854605616df216b821ef6a4890e
itsolutionscorp/AutoStyle-Clustering
/all_data/exercism_data/python/anagram/0b3bc844005b408ca59f98a59affb10b.py
320
3.65625
4
def detect_anagrams(word, candidates): word_lower = word.lower() word_lower_sorted = sorted(word_lower) def is_anagram(candidate): if candidate.lower() == word_lower: return False return sorted(candidate.lower()) == word_lower_sorted return filter(is_anagram, candidates)
ec1af7348cd2a815363e930a63b3d5d270d79002
h1kkan/raspberrypi
/take_photo.py
829
3.703125
4
#!/usr/bin/env python # # Wait for a button to be pressed on _PIN_IN. When the button is pressed, # illuminate the LED on _PIN_OUT as well as take a photo with the picamera # import RPi.GPIO as GPIO import picamera import time GPIO.setmode( GPIO.BCM ) _PIN_IN = 4 _PIN_OUT = 17 GPIO.setup( _PIN_IN, GPIO.IN, p...
0e4b602bace70638e9db90f73760b5102e12980d
yinzishao/de
/t/AbstractFactory.py
1,510
3.71875
4
#coding=utf-8 """ 抽象工厂模式 创建一系列产品 sql与access 工厂 分别创建 各自的方法 """ __author__ = 'yinzishao' class IUser(): def InsertUser(self): pass def GetUser(self): pass class IDepartment(): def InsertDepartment(self): pass def GetDepartment(self): pass class SqlUser(IUser): d...
c4640aa192c2a9a4d3ff47c7686ed6fed42df3b6
yangyeh/first
/test.py
179
3.90625
4
#for letter in 'Yang': #print("each letter is:"+ letter) # '''這是github的demo'''test def h2(): print('hello this is from coworker') def h5(): pass
aee5e2dc078b3bff318cb1bacb4a0ca5443e6b26
xanwerneck/analisedealgoritmos
/trab_2/deploy/order_plan.py
799
4.03125
4
import sys def order_by_x(lista): return mergesort(lista, lambda pt1,pt2: pt1.x < pt2.x) def order_by_y(lista): return mergesort(lista, lambda pt1,pt2: pt1.y < pt2.y) def mergesort(array, compare): if len(array) <= 1: return array else: first_half = mergesort(array[:len(array)/2], compare) seco...
6aa36b2bf305855c3f6a6a8d3bf9c3109a831124
jugani/hackerrank-python
/validemail.py
844
3.546875
4
import re def fun(s): # return True if s is a valid email, else return False if (s.find('@') == -1 or s.find('.') == -1): return False if (s.count('@') > 1 or s.count('.') > 1): return False [username, website] = s.split('@') if len(username) == 0 or len(website) == 0: ...
2d8bf76a7263c3e88e9e8c1dc145faf2a24f7348
uncle-pecos/calc_test-main
/calculating/brackets_del.py
1,221
3.734375
4
def brackets(br_array): #находим выражение во внутренних скобках и передаем далее выражение без скобок i = 0 br_array_l = [] while i < len(br_array): if br_array[i] == ')': #идем по массиву, пока не найдем закрывающую скобку temp_...
e6c16721dfd885574f5618a3b54c97402df83f07
nickleechn/Learning-Rep
/May 28| Should I Interpret.py
2,515
4.125
4
# Hello, world. name = input("Can I have your name, please? ") print(name, ", that's a nice name!") print("--------") user_age = int(input("May I ask how old are you? ")) print("Got it! You are", user_age, " years old") member = int(input("Do you have an account number? ")) if member == 5212419: print("--------") ...