blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
40d18a6d692ccd9d75134c793a5e3d1731a09222
navneethkour/LeetCode-Python-1
/Number/CountPrimes.py
487
3.671875
4
# https://leetcode.com/problems/count-primes/ # Count the number of prime numbers less than a non-negative number, n. # https://discuss.leetcode.com/topic/65044/python-beat-99-97-with-idea-discription def countPrimes(self, n): if n <= 2 : return 0 res = 1 trueTable = [True]*n trueTable[0:2] = [False]*2...
7f44f3f0828f4328ea9eb7329af06983ddde8962
ACronje/rpc_microservice_challenge
/rpc_microservice_challenge/lib/square_odd_numbers.py
103
3.671875
4
def square_odd_numbers(*numbers): return [pow(number, 2) for number in numbers if number % 2 != 0]
382284dff526c17b857e5f3b7e081e0a0d4f92d6
tamasbrandstadter/python-learning
/week3/day1/carrier.py
1,927
3.515625
4
class Carrier(object): def __init__(self, ammo_store=500, hp=50): self.__aircrafts_f35 = [] self.__aircrafts_f16 = [] self.__ammo_store = ammo_store self.__hp = hp def add(self, aircraft): if aircraft.get_type() == 'F35': self.__aircrafts_f35.append(aircraft...
b6dd08888427a0ca2cef7d1ae9e662a7221a7db1
chesta123/PYTHON-codes
/tut11 dictationary.py
414
4.15625
4
mydict = {"drishti":"technical club of svnit","chrd":"fun club","acm":"coding club"} print("enter any name") word=input() print(mydict[word]) # my dictionary tells the hindi translation of words mydict={"crap" : "bakwas", "awesome" : "mast", "beautiful" : "sundar" } print("enter any english...
89bc7a5b6e474869e7e7d71d1e2397dbfaf4027e
saikrishna6415/python-problem-solving
/longestpalindrome.py
463
3.65625
4
def longestPalindrome(A): rev = A[::-1] l = len(A) while l > 0: for i in range(0, len(A) - l + 1): half = int(l / 2) print(half) left = A[i : i + half] print(left) right = rev[len(A) - (i + l) : len(A) - (i + l - half)] print(ri...
95aa2c6add87cec2b9bc80820725ff2dd7a5aa7f
jsmack/learn
/old/language/python/udemy/kame-python/basic/11_format.py
106
3.890625
4
print('Assignment is {}'.format("hoge")) name = "John" print("Hey, {}!! How are you doing?".format(name))
e55c323d4858123e674d83470098caa03a19fbfb
Kunj-Rajput/Python_task_1
/# task 1 q 5.py
179
3.921875
4
# task 1 q 5 x= eval (input ('Enter the value for x')) y= eval (input ('Enter the value for y')) z= x+y+30 #a=z + '30' print ('Final Output: {}'.format(z)) # python version 3
308efd5517fe52b04d636f9b6b3e7da04e8f4025
royabouhamad/Algorithms
/Sorting/MergeSort.py
774
3.953125
4
def mergeSort(list): if len(list) > 1: mid = len(list)/2 leftHalf = list[:mid] rightHalf = list[mid:] mergeSort(leftHalf) mergeSort(rightHalf) i, j, k = 0, 0, 0 while i < len(leftHalf) and j < len(rightHalf): if leftHalf[i] < rightHalf[j]: ...
696fbf428e0bc1780c8e40a0a279497baa1b012e
leonardodamasio/learningPython.py
/Python_if_elif_else.py
708
3.84375
4
# coding: utf-8 # In[ ]: nome= str(input("Digite seu nome:\n")) idade = int(input("\nDigite sua idade:\n")) print("\n{0}, sua idade é {1} anos.".format(nome, idade)) if idade >= 18: def func(): cnh = input("\nVocê já tirou sua habilitação? (s/n)\n") if (cnh == "s") or (cnh == "n"): ...
ac25029d0cc88a44138c4616479570ad63a54968
singularitti/lazy-property
/lazy_property/__init__.py
4,026
3.625
4
__version__ = "0.0.1" from functools import update_wrapper class LazyProperty(property): def __init__(self, method, fget=None, fset=None, fdel=None, doc=None): """ Create an instance of a ``LazyProperty`` (or ``LazyWritableProperty``) inside a class ``C``'s declaration, this instance will ...
9a940834e90a446c77d91ba4f5e5568358560f0a
santosdave/assignment
/assignment/a program to sum two numbers.py
106
3.546875
4
numa = 20 numb = 30 sum = numa + numb print("Sum of {0} and {1} is {2}" .format(numa, numb, sum))
1138aeeb7c8e087dfb2c847436630bfcbf57dd86
sharadbhat/Competitive-Coding
/LeetCode/Short_Encoding_Of_Words.py
419
3.5625
4
# LeetCode # https://leetcode.com/problems/short-encoding-of-words/ class Solution: def minimumLengthEncoding(self, words): """ :type words: List[str] :rtype: int """ words = set(words) words2 = words.copy() for word in words2: for i in range(1, l...
8b69569af9b24f3bc5a091420b0216528d1e5bf8
mosesxie/CS1114
/HW #4/hw4q3.py
667
3.984375
4
userExpression = input("Enter a mathematical expression: ") spaceIndex1 = userExpression.find(" ") spaceIndex2 = userExpression.find(" ", spaceIndex1 + 1) firstNumber = int(userExpression[:spaceIndex1]) secondNumber = int(userExpression[spaceIndex2 + 1:]) if userExpression[spaceIndex1 + 1: spaceIndex2] == "+": ...
776e35c626cb41c06bf225341f102351643cba2b
carlosgm128/python
/generadores2.py
277
3.890625
4
print("Generador 2") print("Un generador es una calse especian de funcion por la que nos permite generar valores los que podemos iterar") print("Ejemplo") def generador(n,m,s): while(n <= m): yield n n += s print("Si llamas la funcion Generador con 3 parapetros")
f45e8ef92652ec4eb2bb644608f0a4085c238714
daranzolin/codewars
/kata.py
2,963
4.3125
4
"""" A Narcissistic Number is a positive number which is the sum of its own digits, each raised to the power of the number of digits in a given base. Your code must return true or false (not 'true' and 'false') depending upon whether the given number is a Narcissistic number in base 10. """" def narcissistic( value ):...
3ef9183a5391bb813baa201a3adccd676c49f421
srgiola/UniversidadPyton_Udemy
/Fundamentos Python/Variables.py
809
4.21875
4
# clic derecho sobre el nombre del archivo (Pestaña superior) en # "Open Preview to the side" para ver como funcionara el programa # en tiempo real y con los valores de las variable. x = 3 y = 5 z = x + y print(z); w = z #Aca "w" y "z" ocupan la misma dirección de memoria #id(x) #Eso sirve para visualisar la direcci...
2621bf93b2bcf8a9d94a31e673ce79b5869fbb78
JerryHaaser/Sorting
/src/iterative_sorting/iterative_sorting.py
1,062
4.09375
4
# TO-DO: Complete the selection_sort() function below thing = [7, 15, 2, 58, 9] def selection_sort( arr ): # loop through n-1 elements for i in range(0, len(arr) - 1): cur_index = i smallest_index = cur_index # TO-DO: find next smallest element # (hint, can do in 3 loc) ...
a0b17b335f0d27e18d1d24af6b89ad6bc67b0f17
fernandavincenzo/exercicios_python
/0-25/013_Aumento.py
138
3.515625
4
s = float(input('Qual é o seu salário? ')) ns = s+(15*s/100) print('O seu novo salário, com o aumento de 15% é de {:.2f}'.format(ns))
e4bee5eb52e44c487138d870a30efe9e9d0ad8a3
arpiagar/HackerEarth
/magic_dictionary/magic_dict.py
1,311
3.578125
4
class MagicDictionary { /** Initialize your data structure here. */ public MagicDictionary() { this.trie = new Trie(); } /** Build a dictionary through a list of words */ public void buildDict(String[] dict) { for (int i =0; i < dict.length; i++){ String word = doct[i];...
29f6dab79c501d94fe299aef49fc56c66d8a73bf
Hixtink/Matplotlib_Tutorials
/01_绘制直线.py
379
3.71875
4
import matplotlib.pyplot as plt; import numpy as np; """ matplotlib官方教学教程网址:https://matplotlib.org/tutorials/index.html 构建一条y = 2x + 1 的直线 """ # 构建X方向的值, 1.初始值 2.结束值 3.分成多少份 X = np.linspace(-5,5,10); # 构建Y方向的值 Y = 2*X + 1; # 绘制直线, X ,Y 的坐标点 plt.plot(X,Y); # 显示 plt.show();
ceafed9040c05c4e1b147558d7b8c5e95017a45d
itsolutionscorp/AutoStyle-Clustering
/all_data/exercism_data/python/difference-of-squares/3f35b7dbbd81440fa5d12b0e7b229825.py
222
3.953125
4
def square_of_sum(num): return sum([x for x in range(num + 1)])**2 def sum_of_squares(num): return sum([x**2 for x in range(num + 1)]) def difference(num): return square_of_sum(num) - sum_of_squares(num)
e2df939dc8ca442ce7e5e7f20e56a9a57b11de80
apolanco18/CS334
/HW1/q1.py
2,787
3.796875
4
import numpy as np import numpy.testing as npt import time def gen_random_samples(): """ Generate 5 million random samples using the numpy random.randn module. Returns ---------- sample : 1d array of size 5 million An array of 5 million random samples """ ## TODO FILL IN ...
fab0b63c044f03fbe961a5e7cb5b29ea7d705361
danghuuken/ZenReach
/functional_test.py
1,951
3.5625
4
import unittest import magic_sauce import os class HighestSuitibilityScoreTest(unittest.TestCase): # Read in test input file def setUp(self): test_input_file_dir = os.path.join(os.getcwd(), "TestInputFiles") self.simple_customer_input = os.path.join(test_input_file_dir, "simple_customer_input.txt") self.test...
9810f97d3d2d0e0b83383a7825c857622bcf2643
godoydud/ClassCodes
/Lista Repetições/ex5.py
498
3.703125
4
numeros = list(map(int, input().split())) # Entrada de dados soma = 0 # Seta as variáveis em 0 qntd = 0 for num in numeros: soma = soma + num # Soma recebe soma + num digitado media = soma/len(numeros) # Calculo da média, soma dividido pela quantidade de números digitados for num in numeros: if num < media:...
fd09cebdb6500a98c3aefebcaf43909924235597
wanlq623/Studypython
/basic/less14.py
831
4.5
4
# 请补全以下代码: class Person: def __init__(self,name): self.name = name def show(self): print('大家注意了!') print('一个叫“%s”的人来了。' % self.name) # 子类的继承和定制 class Man(Person): def __init__(self): Person.__init__(self,name='范罗苏姆') def show(self): print('大家注意了!') ...
1a25c8c5aa1c152344fe9bdbeba0195042e43b9f
TheGreatSea/Traduc
/ex.py
3,839
3.765625
4
class data: def __init__(self, name, types, value): self.name = name self.types = types self.value = value def verifyVariable(variable): try: variable = int(variable) return variable except ValueError: print("error") pass pc = 0 while (pc < len(cua...
045f24c0c74bacf3d3f96f74ea9462ba4aa461c4
atrivedi8988/DSA-Must-Do-Questions
/45_Minimum Jumps To Reach The End/Ideal Solutions/minJumpsToEnd.py
834
4.125
4
# Min Jumps Steps to reach end def minJumpsToEnd(jumps): # Initialize Variable countSteps = 0 maxDistance = 0 currentDistance = 0 for index in range(len(jumps)): # Since we need to minimize the steps, therefore # 1. First move to the current Distance index value # 2. From...
cd4650ea12a3905774d7f0f842d3d3c8eb2188a4
wuhanbronzer/PC
/learning/intr to algrithms.py
1,165
3.796875
4
#insertion-sort #升序 '''class sort_algri: def __init__(self,lis): self.lis = list(lis) def ascending(self): target = self.lis for i in range(len(target)-1, -1, -1): key = target[i] j = i + 1 while j < len(target) and target[j] < key: ta...
918e4363c4aa9dc999dfe56c99cf7ed522852a60
4cylinder/codility
/binarygap.py
1,847
3.765625
4
''' A binary gap within a positive integer N is any maximal sequence of consecutive zeros that is surrounded by ones at both ends in the binary representation of N. For example, number 9 has binary representation 1001 and contains a binary gap of length 2. The number 529 has binary representation 1000010001 and conta...
5ca31e3ba9c7afd2e25ba194707b3737f88b5f6b
Boberkraft/Data-Structures-and-Algorithms-in-Python
/chapter6/C-6.21.py
970
3.9375
4
""" Show how to use a stack S and a queue Q to generate all possible subsets of an n-element set T nonrecursively. Use the stack to store the elements yet to be used to generate subsets and use the queue to store the subsets generated so far. Hmmm the truth is that i only used queue """ from collections import dequ...
6d27551bbd3a4ae27408f6a21e88d1bec4aba7bb
bullethammer07/python_code_tutorial_repository
/python_concepts_and_basics/python_inbuilt_set_methods.py
21,609
3.53125
4
# -------------------------------------------------------------- # Python set inbuilt methods # -------------------------------------------------------------- # add() : Method adds a given element to a set. If the element is already present, it doesn't add any element. # clear() ...
09f694cd9b2aec187e7ab89aaa6de444eebf1fc4
mathews19/projetoPython
/ex15.py
660
4.0625
4
from sys import argv script = argv # file_name = argv Nessa linha recebemos/descompactamos os parametros recebidos file_name = input("Digitev aqui o nome do arquivo") txt = open(file_name) # Nessa linha abrimos o arquivo que recebemos como parametro no command line print(f"Here\'s your file {file_name}: ") print(txt....
adb0fcff2f41faf8fd56b07460bc2c5262c3b801
garethbowles/tictactoe
/tictactoeboard.py
1,978
3.953125
4
#!/usr/bin/env python import logging __version__ = '0.0.1' logging.basicConfig(level=logging.INFO) class TicTacToe(object): """ Calculate the results of a TicTacToe game given a player ID and a 2-dimensional array containing the cells that the player occupies. Currently supports a 3x3 board and ...
834c310cb8046ef6178c343b549092b6dea86bd2
AMyachev/bachelor_degree
/amyachev_degree/exact_algorithm.py
1,539
3.8125
4
from amyachev_degree.core import JobSchedulingFrame def johnson_algorithm(frame: JobSchedulingFrame) -> list: """ Compute solution for case of 2 machines of flow job problem by Johnson's algorithm. Parameters ---------- frame: JobSchedulingFrame frame with exactly 2 machines Retu...
f03f056950e83329574a92b0668bc572a84e8898
kelpasa/Code_Wars_Python
/6 кю/Balance the arrays.py
350
3.5
4
''' https://www.codewars.com/kata/58429d526312ce1d940000ee/train/python ''' def balance(arr1, arr2): set1 = set(arr1) set2 = set(arr2) arr1_c = [] arr2_c = [] for i in set1: arr1_c.append(arr1.count(i)) for i in set2: arr2_c.append(arr2.count(i)) if sorted(arr1_c) == sorted...
f1aac6e3350fcf17d894548dc31da74cbef1bf98
ktamilara/player-set-1
/3a.py
97
3.515625
4
n1=int(input()) rem1=0 while n1!=0: temp1=n1%10 rem1=(rem1*10)+temp1 n1=n1//10 print(rem1)
c1f68dd6e82d98bd9e0cbf2de91a712d0cf0216e
shankarapailoor/Project-Euler
/Project Euler/utils/sieveofatkin.py
915
3.8125
4
from math import sqrt, floor from copy import deepcopy def sieve(x): limit = x isPrime = [False for i in range(5, limit)] for x in range(1, int(floor(sqrt(limit))) +1): for y in range(1, int(floor(sqrt(limit)))+1): n = 4*x**2 + y**2 if n <= limit and (n%12 == 1 or n %12 == 5): isPrime[n-5] = not isPrime...
0657eec1116efbd99b71b7db78c4d0ed34438ee3
Nahid5/Project-Euler-Problems
/Problem9.py
708
4.28125
4
''' Problem 9 A Pythagorean triplet is a set of three natural numbers, a < b < c, for which, a2 + b2 = c2 For example, 32 + 42 = 9 + 16 = 25 = 52. There exists exactly one Pythagorean triplet for which a + b + c = 1000. Find the product abc. ''' import random """ a+b+c = 1000 a < sidesTotal/3 a < b < sidesTotal/2 c = ...
4dc55e0f8b1a68a6f2fdce0a271534a12841667e
lebronbolt/beginnerprojects
/XandO.py
2,992
3.96875
4
print("this really is my first python file") #Develop code for XandO terminal game #construct input for XandO box xando = {'7':" ", '8': " ", '9':" ", '4': " ", '5': " ", '6': " ", '1': " ", '2': " ", '3': " "} board_keys = [] for key in xando: board_keys.append(key) #print XandO box to begin game def printboa...
4e15006b97a80770c2987e4c9620ad3ffe1d0c3e
vporta/DataStructures
/fundamentals/average.py
430
3.71875
4
""" average.py $ python fundamentals/average.py 10.0 5.0 6.0 """ import sys class Average: @staticmethod def main(*args): count, _sum = 0, 0.0 a = list(*args) while count < len(a): value = float(a[count]) _sum += value count += 1 average = _...
cc43c03d67f39cc9a9cad8480613be08c90bdc88
rahuladream/Python-Exercise
/Edugrade/prime_till_no.py
411
3.859375
4
"""You will get a number in input you have to get all the prime no.s till that no Example - Input - 10 Output -[2,3,5,7] Explanation - First element of input list is 4 so multiply the whole list by 4 and return the output list.""" def main(i): arry = [] for i in range(2,i): if i > 1: for j in range(2, i): ...
7c96a310acf3a1c3a754e87be8e631d1c0691fce
franklin18ru/bilaleigaTinna
/data_access/carsDataAccess.py
8,685
3.5
4
import csv import os from datetime import date, timedelta # Data access that has anything to do with cars # class CarsDataAccess: def __init__(self): self.cars = self.getAllCars() # get all cars in the system in store them in a dictionary # def getAllCars(self): car_list = [] with op...
1af78c50379c74529bbe8cf66f7e785c57596a90
clipklop/PYT8-frii
/hw10/basic_flask_tasks.py
1,137
4.125
4
""" 1) Повторить basic.py 2) добавить route который принимает 2 числа и возвращает их сумму 3) добавить route который принимает три строки и возвращает самую длиннную """ from flask import Flask app = Flask(__name__) @app.route('/') def home(): return '<br><br><br><br><br><br><b>hello dude!</b>' @ap...
209f3aacadf0336cc4834a0376ec77f77ae3038a
clairefischer/npfl104
/hw/python/xyz_there.py
587
3.765625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Mar 20 16:27:13 2019 @author: clairefischer """ #10 def xyz_there(str): bool=False if len(str)<=2: return False elif len(str)==3: if str=='xyz': return True else: return False elif len(str)>3: if 'xyz' in str: ...
f691ed16d80ec3cc0870a51e4a4e0f9f0067fb41
D-sourav-M044/NSL_RA_TRAINNING
/Python_Basic/week_01/list.py
890
3.828125
4
data = [1,2,3] print(data + [4,5,6]) print(3 in data) print([2] in data) #append data.append(10); print(data) #insert data.insert(1,'b') print(data) #index print(data.index('b')) try: print(data.index(5)) except : print("the searching element is not in list") #count print(data.count(2)) #build_in_function ...
d26b1ec53eba9f9d862642d413b1274287a482c4
Donavan-Tay/2021-Complete-Python-Bootcamp-From-Zero-to-Hero-in-Python
/BlackJack.py
7,885
4.15625
4
import random # Global variables to create cards suits = ('Hearts', 'Diamonds', 'Spades', 'Clubs') ranks = ('Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Jack', 'Queen', 'King', 'Ace') values = {'Two': 2, 'Three': 3, 'Four': 4, 'Five': 5, 'Six': 6, 'Seven': 7, 'Eight': 8, 'Nine': 9, 'Te...
cd717674f5ce71adb362d5cdb1964751cbeac2d5
JorinW/DebtCalculator
/debt_calculator.py
3,052
4.375
4
#!/usr/bin/env python3 """Simple command line python script that outputs a spreadsheet of data about your debt payments. Jorin Weatherston August, 2017""" import csv import sys, getopt from math import floor def main(argv): ## initialization ## # initialize argument variables initial_debt = 0 interest_...
589d7da90df38fb46cbb303dc689027fcbf8c104
hanguangchao/python_learn
/basic/9.py
455
3.671875
4
# -*- coding=utf-8 -*- def repeater(value): while True: new = (yield value) if new is not None: value = new r = repeater(42) print r.next() print r.send("Hello World!") def triangles(): ls = [] while True: ls.insert(0, 1) for k, v in enumerate(ls[1:-1], 1): ...
24d8a3712a6bb4fddcfa05564e8c411bab920db0
Yeshwanth115/Python
/positive or negative.py
92
3.828125
4
n=int(input()) if(n>0): print('%d is positive' %n) else: print('%d is negative' %n)
bbcc7334dc05555730ec90a034a7a9d88b14818c
shkwhr/study-python
/dictoionary.py
412
3.71875
4
# coding: utf-8 item_dic = {'醤油': 100, '砂糖': 80, '胡椒': 70} item_dic2 = sorted(item_dic, reverse=True) for (name, price) in item_dic.items(): print(name + 'は' + str(price) + '円です') print('Price Only') for name in item_dic: print(str(item_dic[name]) + '円') else: # forloopが終わったら出力 # breakした場合はelseは通らない ...
59a1146910cbe2fe79f662959648b56f8adcb676
bedros-bzdigian/intro-to-python
/week5/Homework/problem6/customer.py
316
3.75
4
from productchek import check def main (product,num,price): def buy(product,num,price): a = check(product,num) if a == True : print ("You bought",product,"and spent",num*price) else: print ("Sorry! We are out of the product") main("candy",11,3)
c414a70c8ec5f01ab75377a780aabf7d6875cf97
Piyawan00/calculeter
/menu.py
1,401
4.09375
4
import one #prototype import two import three import four Add=1 Substeact=2 Multiply=3 Divide=4 Quit=5 def main(): chioce = 0 while chioce !=Quit: display_manu() chioce =int(input("Selec your operation")) if chioce ==Add: num1=float(input("Enter you first number: ")) ...
cf07d3eb81547bc5e66bad2f4b1333becdf592ff
LeeHeejae0908/python
/Day02/str_swap.py
534
3.9375
4
''' * 문자열 알파벳 형태 변경 메서드 1. lower(): 영문 알파벳을 모두 소문자로 변경 2. upper(): 영문 알파벳을 모두 대문자로 변경 3. swapcase(): 영문 대소문자를 각각 반대로 변환 4. capitalize(): 문장의 맨 첫글자만 대문자, 나머지는 소문자 5. title(): 각 단어의 맨 첫글자만 대문자, 나머지는 소문자 ''' s = 'GOOD morNing !! mY nAme IS LeE' print(s) print(s.lower()) print(s.upper()) print(s.swapcase()) print(s.cap...
8eb943f0ad70308aecd62c854f0bab9804d1f651
OhOHOh/LeetCodePractice
/python/No206.py
815
3.84375
4
# -*- coding: UTF-8 -*- # Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def reverseList(self, head): ''' 递归方式 ''' def reverse(pre, cur): if cur is None...
89f39a069591a613d990f06efa182fa834429ffa
JPChaus/362HW-4
/listAvg.py
895
3.96875
4
def main(): list_length = uInput("How big do you want the list? Positive integer value only: ", 1) my_list = [] for i in range(0, list_length): my_list.insert(i, uInput("Enter a number to add to the list. Integer value only: ", 0)) answer = calculateAvg(my_list) print("Average of the list: "...
b0066c4e983a4159abefce606eb3e00f4e701893
phumin1994/AiTasks
/Task4/task4.py
1,930
3.5
4
import pandas as pd import numpy as np from sklearn.cluster import KMeans from sklearn.preprocessing import LabelEncoder from sklearn.preprocessing import MinMaxScaler train = pd.read_csv('train.csv') test = pd.read_csv('test.csv') print("***** Train_Set *****") print(train.head()) print("\n") print("***** Test_Set **...
ace972b63fb4b7bf760930360eedd9a8c4de1f49
MatthewDaws/CodeJam
/2015_1b/c_slow.py
1,790
3.65625
4
import sys from collections import namedtuple Group = namedtuple("Group", ["degree", "hikers", "minutes"]) def cost_zeros(time, zero_hikers): count = 0 for g in zero_hikers: for k in range(g.hikers): min = (g.minutes + k) * 360 count += max(1, time // min) return count ...
8b8b35661ac269c345d2c95df876e59a6753a379
lglucin/VendingMachine
/vendingMachine.py
5,519
3.625
4
from stock import Stock from product import Product import locale locale.setlocale( locale.LC_ALL, '' ) class VendingMachine(): def __init__(self, stock = Stock(100)): self.credit = 0 self.stock = stock self.change = {"20":20, "10":10, "5":5, "1":1, "Q":0.25, "D":0.10, "N":0.05, "P":0.01} ...
a04b1756b7d01e7dacca43e5c880116547e39976
franslay/smell_me
/BigramModel.py
3,042
3.515625
4
from LanguageModel import LanguageModel import random class BigramModel(LanguageModel): def __init__(self): super().__init__() self.unigramcounts = dict() self.unigramcounts[self.STOP] = 0 self.bigramcounts = dict() self.N = 0 # REQUIRED FUNCTIONS from abstract pare...
786a7037884a872201e8191442cca1a377683737
RiderLai/pytest
/study/dictionary.py
1,161
3.765625
4
a = 1 '''test1''' alien_0 = {'color': 'green', 'points': 5} print(alien_0['color']) print(alien_0['points']) alien_0['a'] = 'a' print(alien_0['a']) print(alien_0) # alien_0['color'] = 'red' # print(alien_0) # del alien_0['color'] # print(alien_0) alien_0[1] = 1 for key, value in alien_0.items(): print("key:" ...
13e44f6a62e15e0a8b36fc55f3ffe163a5927b5f
m04kA/my_work_sckool
/pycharm/GeekBrains/python_lvl_1/lesson_7/task_2.py
1,074
3.890625
4
from abc import ABC, abstractmethod class Сlothes(ABC): def __init__(self, name): self.name = name self.material = None @abstractmethod def calc_expenditure(self): return self.material @property def show_material(self): return f'Вот нужный материал {self.material}...
0c1036ef4d65d2b9c3dde229f3c2b56cb2aaaa9a
paulrigor/Combining-existing-sequence-analysis-methods-with-graph-displays-for-visualization
/preprocessing/computedistances.py
2,639
3.578125
4
"""Computes a pairwise distance matrix from a BLAST alignment.""" import argparse from typing import Callable, TextIO, Tuple def short_hamming(ident: int, len1: int, len2: int) -> float: """Compute the normalized Hamming distance between two sequences.""" return 1 - ident / min(len1, len2) def parse_line(l...
9b2ef854c0bd1bbfba36f3953ffd0b898294024a
breezescut/zbin
/Python/Design of Computer Programs/Leeson1.py
356
3.765625
4
#! /usr/bin/env python # coding=utf-8 def ss(num): total = 0 for i in range(num+1): total += i #print("%d:%d" % (i, total)) return total def poker(hands): return max(hands) def hand_rank(hand): if __name__ == "__main__": num = int(input("Input num:")) p...
bbdef231a1257b47700c621c0e9e8295f1311cfb
HackerWithDrip/Python-PasswordManager
/PasswordManager.py
3,116
3.859375
4
import re class BasePasswordManager: def old_passwords(self): old_pass = ['247abc', 'abc247', '247365bac', '247365bac$'] self.old_pass = old_pass[-1] return self.old_pass def get_password(self): current_pass = self.old_pass self.current_pass = current_pass ret...
91982e583cd2bc10b0fc58c31982782ce4945214
fotavio16/PycharmProjects
/PythonExercicio/ex012.py
207
4.03125
4
nome = str(input('Qual é o seu nome? ')) if nome == 'Fernando': print('Que nome bonito!') elif nome == 'Felizberto': print('Você deve ser muito feliz!') print('Tenha um bom dia, {}!'.format(nome))
71be98bc23e62aed4a6a9052a15aa5fee3611ec6
sbobbala76/Python.HackerRank
/0 - Tutorials/10 Days of Statistics/Day 0 - Mean Median and Mode.py
801
3.90625
4
def mean(values: list) -> int: length = len(values) result = 0 for value in values: result += value result /= length return result def median(values: list) -> float: length = len(values) values = sorted(values) if length % 2 != 0: return values[length // 2] else: return (values[length // 2] + values[le...
96d60712dbd534c6e1cb1db473c5066c158bfd23
GovorunV/file
/file.py
698
3.640625
4
'''str=input("vedite text:") #записть в файл str += "\n" file = open('date/text.txt','a') file.write(str) file.close() try: file = open('date/text.txt', 'rt') # чтение з файла for line in file: print(line) file.close() except FileNotFoundError: print("Fail ne daiden") ''' # Исключения!!! useri...
be59ce0e978c8423d278b586c5379c26aeb94545
syn7hgg/ejercicios-python
/8_6/2.py
1,076
3.59375
4
class Persona: def __init__(self): self.rut = "" self.nombre = "" def setRut(self, rut): self.rut = rut def setNombre(self, nombre): self.nombre = nombre def getRut(self): return self.rut def getNombre(self): return self.nombre def __str__(s...
601c5c6d68645a68c2edfdae1e8bf02b04f57162
petersdana/PythonLab
/know_the_anagram.py
961
4.25
4
#Enter a word whose anagram you would like to know #The computer gives a set of valid and meaningful anagrams word = input ("\n Enter a word: ") word = word.upper() # To match dictionary format l_word = len(word) ana_words = list() dictionary = open ("dictionary.txt") for d_word in dictionary: d_word = d_word....
26e81356afa13ebf41f74c59643b4e54f27a2d0f
SWUFE-labs/python_with_corey
/oop_classes/run_oop_05.py
845
3.9375
4
"""This is the user interface script to the 'oop.py' employee class file""" from oop_05 import Employee emp_1 = Employee('george', 'kaimakis', 50000) emp_2 = Employee('TEST', 'EMPLOYEE', 60000) # # this is equivalent to __str__ and str(): # print(emp_1) # These pairs are equivalent - this is for the official obj...
83b82b62b171f439ec340c59044712dff45ae6fb
howard31622/fibonacci-algorithm
/fib3.py
272
3.75
4
count = 0 def fibonacci(n): global count if not isinstance(n, int): print ('Invalid Input') return None if n < 0: print ('Invalid Input') return None count = (( (1 + (5 ** 0.5))/2) ** n)/(5 ** 0.5) fibonacci(5) print(count)
e70fee8f17850e9d1607713b657420c0f213aa0b
fugbk/pystu-N27
/day5-1 面向对象核心概念/t.py
392
3.65625
4
# encoding = utf-8 __author__ = "Ang Li" class Person: age = 100 def __init__(self, name): self.name = name tom = Person('Tom') print(tom.age) # tom 中没有定义age,访问的是类的,如果类中没有会接着访问上层的父类的 print(*tom.__dict__.items()) # 但是这种访问,是直接访问,tom实例并不会 并不会新增一个age属性。
8f076f012de7d9e71daff7736fc562eff99078aa
kartikay89/Python-Coding_challenges
/countLetter.py
1,042
4.5
4
""" Write a function called count_letters(text, letter), which receives as arguments a text (string) and a letter (string), and returns the number of occurrences of the given letter (count both capital and small letters!) in the given string. For example, count_letters('trAvelingprogrammer', 'a') should return 2 an...
72402629bb93281bbec810bc4d52bb909b20adcd
cannonja/tensorflow
/tensorflow/examples/tutorials/mnist/my_files/MNIST_exp/single_layer.py
1,626
3.734375
4
import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data ## Read and unpack images mnist = input_data.read_data_sets('MNIST_data', one_hot=True) ## Launch interactive session ## Interavtive session allows us to interleave operations that build graph ## with those that run/execute graph ## R...
c9a44ae6392b9f829606cb0ea52a8c3e2ca5ae8f
tomdottom/programming-excersises
/hacker_rank/PALG-2-simple-array-sum/python/main.py
314
3.5625
4
#!/bin/python3 import sys def parse_input(text): lines = text.split('\n') n = int(lines[0]) numbers = [int(i) for i in lines[1].split()] return n, numbers def main(n, numbers): return sum(numbers) if __name__ == '__main__': args = parse_input(sys.stdin.read()) print(main(*args))
e1f29bcd3953484dbae8e45e55fee4d85346488d
ailic96/mandelbrot
/functions.py
2,714
4.28125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- import argparse import numpy def mandelbrot(x, y, maxit): """ Computes real and imaginary numbers, number of iterations returns value of current iteration. Takes input of complex numbers: x - real value y - imaginary value maxit - maximum i...
68b04d2aff18d8bdaaaa684140e10729f5a8390c
sethuramvinoth/DataStructures
/Array/ClassAndObjects.py
1,571
4.40625
4
class MyClass: "Description of the Class Comes here!!!" a = 10; def func(self): print('Hi') print(MyClass.func); print(MyClass.a); print(MyClass.__doc__); # whenever an object calls its method, the object itself is passed as the first argument. So, ob.func() translates into MyClass.func(ob). # In...
9aa96e9c47f0109ff061d0ce0b3718e69e53b95c
kenandres/Python_Program_Flow
/ifChallenge.py
311
4.15625
4
name = input("Please enter your name: ") age = int(input("Please enter your age: ")) if 18 <= age < 31: print("Welcome to the club, {0}!".format(name)) elif age < 18: print("Please come back in {0} years.".format(18 - age)) else: print("Sorry, {0}, you're not welcome here.".format(name))
03c211b6f2e345d7bc99e0a96e26d810085046d6
gniadoo/Simple_banking_system
/main.py
7,773
3.90625
4
import sys import sqlite3 from random import randint # Creating database try: con = sqlite3.connect("card.s3db") except sqlite3.Error as error: print('Failed to connect SQLite: ', error) sys.exit() cur = con.cursor() cur.execute("CREATE TABLE IF NOT EXISTS card(" "id INTEGER PRIMARY KEY AUTOIN...
aeaaf247c9f355528f2313e5a60046bd0ddf1701
PrayasMishra/basic-calculator
/calc.py
1,985
3.5625
4
from tkinter import * w=Tk() w.title("my Calculator") w.geometry("260x240") exp="" def clear(): global exp exp="" v.set(exp) def btnclk(n): global exp exp+=str(n); v.set(exp) def calculate(): global exp res=eval(exp) v.set(res) v=StringVar() E=Entry(w,text="",bg="aq...
57e1a1887edc29dc97a69f4c860fe6f9cb833fe9
ncy906302/okonomiface
/cs.py
158
3.515625
4
import numpy as np def CalculateSimilarity(a,b): a = np.array(a[:]) b = np.array(b[:]) return sum(a*b)/ (sum(a*a) **0.5 ) * (sum(b*b) **0.5)
9fa42681e84ebaae9d4323370259342b2820b0ed
Mike-Whitley/Programming
/cosc367 AI - Machine learning/lb9q5.py
1,378
3.578125
4
import csv def learn_likelihood(file_name, pseudo_count=0): with open(file_name) as in_file: training_examples = [tuple(row) for row in csv.reader(in_file)] #open the csv file as read in all the values true_values = 0 row_count = 0 likelihoods = [] for row in training_examples: ...
4bc01cc5d6ea25762c811c747d78c76e13bdc1f2
Keftcha/codingame
/training/medium/conway-sequence/python.py
520
3.53125
4
r = int(raw_input()) l = int(raw_input()) liste = [r] for _ in range(l -1): liste_suivante = [] pointeur_rouge, pointeur_bleu = 0, 0 while pointeur_bleu < len(liste): while (pointeur_rouge < len(liste)) and (liste[pointeur_rouge] == liste[pointeur_bleu]): pointeur_rouge += 1 li...
d8e0455d47fc664f8ec900b5cb6ca0730a0de514
anasahmed700/python
/5thClass/Dictionary.py
3,517
3.890625
4
# DICTIONARY 1 # e.g; dict = {'key': 'value'} profile = {'name': 'Anas', 'age': 24, 'email': 'anasahmed700@gmail.com'} print(profile) print(profile['name']) print(profile['age']) # DICTIONARY 2 profile = {'name': 'Anas', 'age': 24, 'email': 'anasahmed700@gmail.com', True: 'working', 5: True} print(profile[Tru...
0e1d66d35116674a8bafb1fabd2de1847d6fcc15
aquatiger/assignments
/fibo.py
243
3.609375
4
global steps steps = 0 def fibo(n): global steps steps += 1 if n <= 2: return 1 return fibo(n-1) + fibo(n-2) for i in range(20): steps = 0 print(str(i) + ' ' + str(fibo(i)) + ' ' + str(steps)) print(fibo(10))
8b252a0a235157a98e7b18ac690527cd74824cc9
ceharrin/legendary-octo-giggle
/src/main.py
2,790
4
4
import random import src.BinManager as BinManager # Some constants and default values min_int = 20001 max_int = 380000 bin_size = 36000 range_size = 1000 num_bins = 10 # Main entry point. Prompt for user input and then create the bins based on the provided input. # Generate the random numbers and bin them. # Output...
ac5f72205adb4c5c3efd2339a62414bb0d30e658
abhidurg/CSE_480_Database_Systems
/proj04/CRUD_principles.py
325
3.5625
4
import sqlite3 def crud(conn): conn.execute("INSERT INTO students VALUES ('Cam', 98, ''); ") conn.execute("UPDATE students SET grade=100 WHERE name='Josh';") conn.execute("UPDATE students SET grade=grade-10, notes='SUCKER' WHERE name LIKE '%z%'") conn.execute("DELETE FROM students WHERE grade <=...
0b662dc40c78bd7488e0a5a06dad2930f8d58ace
sfeng77/myleetcode
/perfectSquares.py
734
3.890625
4
""" Given a positive integer n, find the least number of perfect square numbers (for example, 1, 4, 9, 16, ...) which sum to n. For example, given n = 12, return 3 because 12 = 4 + 4 + 4; given n = 13, return 2 because 13 = 4 + 9. """ #ACCEPTED class Solution(object): def __init__(self): self.d = {0:0...
9ab5421fa8b620e360afe5081e14b64cfeeeafe6
allen880117/Othello-IntroAI-GroupProject
/Othello-Src-Python/othello.py
1,897
3.734375
4
#!/usr/bin/env python3 import display import othello import board import player import game_util import coord class Othello(): """ Class: Othello """ def __init__(self): self.board = board.Board() self.player_black = player.Player() self.player_white = player.Player() def do_pre_...
685b938734e206efa305d03636fc5b26fa6cbbf6
dfeusse/2018_practice
/dailyPython/07_july/23_smallestInArray.py
686
4.34375
4
''' Find the smallest integer in the array Given an array of integers your solution should find the smallest integer. For example: Given [34, 15, 88, 2] your solution will return 2 Given [34, -345, -1, 100] your solution will return -345 You can assume, for the purpose of this kata, that the supplied array will not b...
d45ed169b854ad1602277079a3ff18df306daf7c
BYU-ACM/warm-up-day-2-tehrmc08
/sol.py
2,808
4.28125
4
def Binary_Search(arr, to_find): """A direct implementation of Newton's Method (For sanity assume that func and func_prime define there own division correctly, that is, don't cast anything to a float) params: arr (a list ordered from least to greatest) to_find (the item to find in arr) ...
3c3c8ac1cb37a49fc3bcd310186c3d756630a289
thewinterKnight/Python
/dsa/miscellaneous/quicksort.py
1,067
4.03125
4
# Quick Sort import random def create_array(m, M): arr = list(range(m, M+1)) random.shuffle(arr) return arr def create_array_wt_duplicates(m, M, num_duplicates): arr = list(range(m, M+1)) # print(arr) arr.extend(generate_random_list(m, M, num_duplicates)) random.shuffle(arr) return arr def generate_ran...
feac0b03affbecf09ea2e611d6f05a699ad82e6d
narangmohit3121/Python
/DictionaryPractice.py
288
3.71875
4
directions = {'North': 'N', 'South': 'S', 'West': 'W', 'East': 'E' } for direction in directions.keys(): print(direction) def make_dictionary(**kwargs): return kwargs print(make_dictionary(one='one', two='2', three=3))
859580e90ce38cfc9514fb75b75f381aa4aaf2ae
colafson/Virtual_Sommolier_CPSC322
/mysklearn/.ipynb_checkpoints/myutils-checkpoint.py
13,937
3.5
4
import math import numpy as np import random #import mysklearn.mypytable as mypytable #this is used to get the total number of occuances of #each diffrent value for a certain column in a table def get_table_frequency (table, header_id): col = table.get_column(header_id) ids = [] values = [] for val i...
5c6043e2a822c8db84f00666f4f27d96fd89398b
ChickenBC/Python-homework
/Chapter10/10-6.py
266
4.0625
4
try: x = input("Enter a number:") x = int(x) y = input("Enter a number:") y = int(y) except ValueError: print("Sorry, I really need a number.") else: sum = x + y print("The sum of " + str(x) + " and " + str(y) + " is " + str(sum) + ".")
cdc53f48838f5cfcad170c98ea9fd468d675ba92
nibsdey/Udemy_SelfDrivingCar
/finding-lanes/lanes_v1.py
1,068
3.796875
4
import cv2 import numpy as np image = cv2.imread('test_image.jpg') lane_image = np.copy(image) # Change to gray scale to convert it from multi-channel (RGB) to single channel image which is easier to process gray = cv2.cvtColor(lane_image, cv2.COLOR_RGB2GRAY) #cv2.imshow('result', gray) # Gaissian filter # Kernel of...
82883d73c3cd0c71ac0002ef74cf90c3d4a7e35d
lepangdan/tensorflow_learning
/try.py
19,132
4.1875
4
# empty = 'empty' # # # def is_link(s): # """s is a linked list if it is empty or a (first, rest) pair""" # return s == empty or (len(s) == 2 and is_link(rest(s))) # # # def link(first_s, rest_s): # """construct a linked list from its first element and rest""" # assert is_link(rest_s), "rest must be a l...
dfe42ed7244c19677a4b7e908e65fd2ca8b57429
armsiwadol69/Python_ss2
/WORK I/ex2.3 dic.py
607
3.859375
4
#2.3 Dictionary #Ex1 dic1 = { "Name" : "Plume", "Class" : "Vanguard", "Rarity" : 3 } print(dic1,type(dic1)) #ex2 dic1 = { "Name" : "Plume", "Class" : "Vanguard", "Rarity" : 3 } print(dic1["Name"],"Is",dic1["Class"]) #ex3 dic1 = { "Name" : "Plume", "Class" : "Vanguard", "Rarity" : 3 }...
c4862502ee055bf006035e0157c37ac58ee0d87e
eclipse-ib/Software-University-Fundamentals_Module
/08-Mid_Exam/More exams/2/2-Shopping_List.py
893
4.0625
4
groceries = input().split("!") while True: command_no_splt = input() if command_no_splt == "Go Shopping!": break command = command_no_splt.split() main_command = command[0] item = command[1] if main_command == "Urgent": if item not in groceries: groceries.insert(0, ...
7d3f907c51f789461210fddb8c0c84482f89856a
aspittel/open-file-python
/script.py
98
3.5
4
with open("input.txt") as text: for line in text: print("-------") print(line)