blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
97e3b6c670ca0ce6ddd02db55c7fcb4e16aa156c
Orig5826/Basics
/Lang/Python/py_base/15_map2.py
1,107
3.671875
4
import re def calc_add_custon(): while True: print('>> ', end='') content = input() if not isinstance(content, str): break if content == 'q': break # 对于:数字和运算符号的判断,暂没有想到合适的办法 # 取消开头和结尾的空格 content = content.strip() # re.sp...
c1d781121ddabf28a30f37676dee2770153fc93d
claxman/Clustering_Models
/hierarchical_clustering.py
1,294
3.625
4
# Author: Chaitanay Laxman # Importing the libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd # Importing the dataset dataset = pd.read_csv('Mall_Customers.csv') X = dataset.iloc[:, [3, 4]].values # Using the dendrogram to find the optimal number of clusters import scipy.cluster.hierarc...
f89dac9b2145ebdf5f674b4820df668b3f1330be
jdrestre/Online_courses
/Udemy/Python_Chirou/test_if.py
185
4
4
#/usr/bin/python3 nota = float(input()) if nota >= 6 and nota <= 10: print("pasó") elif nota < 6 and nota >=0: print("perdió") else: print("ingrese valor entre 1 y 10")
3a0f95ee5ddec0299dcd31db6f9d9cca3b1f442a
jorgeajimenezl/school-projects
/algebra/bisection.py
421
3.625
4
def bisection(f, a, b): # Initial condition assert f(a) * f(b) < 0, "sign(f(a)) != sign(f(b))" while abs(a - b) > 1E-10: m = (a + b) * 0.5 if f(a) * f(m) < 0: b = m else: a = m return a def main(): x = bisection ( f = lambda x: x**2 + 4*x +...
8060420958a34d3cdaf321c442aac70dba917480
marinisz/CEV_Python
/036.py
574
3.703125
4
print('\033[34mBem-vindo ao sistema de crédito!\033[m') print('-=-'*11) salario = int(input('\033[34mQual o eu salário? \033[m')) print('-=-'*11) casa = int(input('\033[34mQual o valor da casa que pretende comprar (meses)? \033[m')) print('-=-'*11) tempo = int(input('\033[34mEm quanto tempo você pretende pagar a ...
4cba449580a41a9be35ae1bdead5558510cb914b
hardeep0444/ailab
/percep.py
1,149
3.515625
4
import numpy as np import math th = 1 Epochs = 3 class Perceptron: def __init__(self,no_of_inputs,alpha=0.2): self.alpha = alpha self.weights = np.zeros(no_of_inputs+1) def net_input(self,inputs): yin = np.dot(inputs,self.weights[1:])+self.weights[0] return yin def train(self,tra...
7b57783f465c395a61278d2e13a76afe320b6a4f
GENGLEIN/PYTHON
/day1/login.py
1,074
3.625
4
#-*- coding:utf-8 -*- ################################################## #Filename: login.py # #Revsion: 1.0 # #Description login is test # #Date: 2017/01/13 # #Auther: genglei ...
8ebf27f0739faf2997558c78498fd912fdca923f
rup3sh/python_expr
/designpatterns/structural/singleton
745
3.9375
4
#!/bin/python3 class Singleton(): __single = None __right_way = False def __init__(self, name): print("Comes to init") if not Singleton.__right_way: print("Comes to err") raise RuntimeError("CREATE USING RIGHT WAY") if not Singleton.__single: self.x = name @classmethod def getInstance(cls, name...
4e165c870bb22e0241e715e5260a83d761a9a329
AyrtonDev/Curso-de-Python
/aula22b/aula22.py
237
3.875
4
from uteis.numeros import fatorial, dobro, triplo num = int(input('Digite um valor: ')) fat = fatorial(num) print(f'O fatorial de {num} é {fat}.') print(f'O dobro de {num} é {dobro(num)}') print(f'O triplo de {num} é {triplo(num)}')
554562b9af28dc8446e91575183089157963e275
rjsu26/ScheduleMe
/history_reader.py
11,562
3.59375
4
#! /usr/bin/env python """ Program to read all history from firefox in the system and use their frequency count for categorization purpose. To be used as cron job set to once every month.""" """ Format of data in HISTORY_FILE(which only has uncategorised data): { "website" : { "mozilla":{"site":["support...
82111550ad58675ae5ddfae99e2d8b7d44368a10
AcubeK/LeDoMaiHanh-Fundamental-C4E23
/Season 2/homework_no2/stars/4.c.py
144
3.6875
4
# print out 9 (stars and xs) in total for i in range(1, 10): if i%2 == 1: print("* ", end="") else: print("x ", end="")
8f27a6dc4d7975c6450d12945fc5a18c92ae889a
kamyu104/LeetCode-Solutions
/Python/reach-a-number.py
662
3.515625
4
# Time: O(logn) # Space: O(1) import math class Solution(object): def reachNumber(self, target): """ :type target: int :rtype: int """ target = abs(target) k = int(math.ceil((-1+math.sqrt(1+8*target))/2)) target -= k*(k+1)/2 return k if target%2 ==...
df8bb09d9c7fa0182fe8428db806d66ee31abbeb
mattkim8/CSI
/sierpinski.py
1,360
3.671875
4
# Problem Set 7, Part IV # Name: Kim, Matthew # Don't change/remove this line please. from Tkinter import * # Don't change this function please. def draw_triangle(p1, p2, p3): """Draw a triangle whose corners are given by tuples p1, p2, and p3.""" window.create_polygon(*(p1+p2+p3), fill='red3') # Don't change...
16c90b7e533f9850501bfcdf034f1a815d6b1e84
Goodleey/PraktikaPython5
/Praktika5.py
1,062
3.734375
4
import time # декаратор времени def time_this(NUM_RUNS=n): # число прогонов функции(n) def decorator(func): # декаратор, который принимает в значение другую функцию def func(*args, **kwargs): # нам не известно, сколько и какие будут аргументы у функции avg = 0 for i in range(NUM_RUNS...
66b1c1b83300b70c837f8e6f827e338793675187
jayounghoyos/My-Scripts
/Bucles.py
182
3.671875
4
#contador = 0 #print("2 elevado a la" + str(contador) + " es igual a: " + str(2**contador)) contador = 1 print("2 elevado a la" + str(contador) + " es igual a: " + str(2**contador))
889fdc994806d84b8978ea4658fa70a4794d0484
celticcow/led
/led.py
725
3.578125
4
#!/usr/bin/python3 import time import RPi.GPIO as GPIO def turn_led_on(color): GPIO.setmode(GPIO.BCM) GPIO.setup(color, GPIO.OUT) GPIO.output(color, True) #end of turn_led_on def turn_led_off(color): GPIO.setmode(GPIO.BCM) GPIO.setup(color, GPIO.OUT) GPIO.output(color, False) #end ...
a0f735a6d0f71332d287da2a901be7ad3cda9350
JackMGrundy/coding-challenges
/common-problems-leetcode/medium/longest-turbulent-subarray.py
3,417
3.546875
4
""" A subarray A[i], A[i+1], ..., A[j] of A is said to be turbulent if and only if: For i <= k < j, A[k] > A[k+1] when k is odd, and A[k] < A[k+1] when k is even; OR, for i <= k < j, A[k] > A[k+1] when k is even, and A[k] < A[k+1] when k is odd. ...
9168818ddf257975a7d1fdb7b8d67f12055f88b9
infern018/ML-Coursera-in-Python
/EX-1/ex1.1.py
1,775
3.734375
4
import numpy as np import matplotlib.pyplot as plt import pandas as pd data = pd.read_csv('ex1data1.txt', header = None, sep=",") X = data.iloc[:,0] y = data.iloc[:,1] m = len(y) X = X[:, np.newaxis] y = y[:, np.newaxis] theta = np.zeros([2,1]) iterations = 10000 alpha = 0.01 ones = np.ones([m,1]) X = np.hstack((o...
0ae8281b9c222e174432948d5d8433af17fafcee
tbindi/hackerrank
/chocolate_feast.py
741
3.578125
4
''' Little Bob loves chocolates, and goes to a store with $N in his pocket. The price of each chocolate is $C. The store offers a discount: for every M wrappers he gives to the store, he gets one chocolate for free. How many chocolates does Bob get to eat? I/P: 3 10 2 5 12 4 4 6 2 2 O/P: 6 3 5 ''' def chocolate_fea...
ececae10b18697efab08481fcd862f4b8219919f
tayjade/learning-python
/completed_lessons/word reverse script.py
181
4.03125
4
reverse = input("Type in a word") index = len(reverse) - 1 output = "" while index >= 0: output = output + reverse[index] index = index - 1 print(output)
40709ba151d336b2c474c220f21794e30ba1cbfc
manish4005/my_code
/chessQueenpy
943
3.796875
4
#!/usr/bin/python import sys # Problem Statement : Find the place of N queen in NxN chess box # such they do not kill them selves to_update = 10 queen_pos = [-25,-25,-25,-25] def isvalid(raw,col): global queen_pos #print "checking validation for {0}, {1} and current queen {2}".format(raw,col,queen_pos) for i in r...
cd23d7402f8f212dd8a57b9cbf0a85553426eab2
thepros847/python_programiing
/assingment/string_istitle_method.py
304
3.765625
4
txt = "Hello, And Welcome To My World!" x = txt.istitle() print(x) a = "HELLO, AND WELCOME TO MY WORLD" b = "Hello" c = "22 Names" d = "This Is %'!?" e = "theophilus" f = "prosperia" print(a.istitle()) print(b.istitle()) print(c.istitle()) print(d.istitle()) print(e.istitle()) print(f.istitle())
8d5217dc93c27b806aa6db88ccb60af09b03dbd7
reynardasis/code-sample
/ex16.py
646
4.125
4
from sys import argv script, filename = argv print "we're going to erase %r" %filename print "press ctrl+c if you dont want" print "Press enter if you want to proceed" raw_input("?") print "Opening file.." target = open(filename, 'w' , 'r') print "Erasing data in file..." target.truncate() print "Now im going to ...
452003fadc1b4ee159c716acf70aea09ef286b85
dlee533/comp1510-programming-methods
/Assignments/A4/question_3.py
787
3.515625
4
import doctest def dijkstra(colour_list: list) -> None: """sort the list :param colour_list: a list :precondition: cololur_list must be a list with any number of 'red', 'white', and 'blue' :postcondition: sort the list with value returned from second_character function :return: None """ c...
d279a67256599d2b7f9201e83b0d2ea365f9ad81
oaao/smsos
/smsos/classifiers/input.py
1,649
3.734375
4
import os import pandas class CsvDataInput: """ Ingests a classified CSV dataset as a pandas dataframe and distributes items into training and test data according to a given item count or decimal proportion. """ def __init__(self, filepath, training_cases=None, encoding='utf-8'): self...
cce715b6938e2f5c16d6ee158ebfa7e15b4e0645
samsolariusleo/cpy5python
/practical02/q11_find_gcd.py
725
4.28125
4
# Filename: q11_find_gcd.py # Author: Gan Jing Ying # Created: 20130207 # Modified: 20130207 # Description: Program to find the greatest common divisor of two integers. # main # prompt user for the two integers integer_one = int(input("Enter first integer: ")) integer_two = int(input("Enter second integer: ")) # fin...
24586b9f007be49feaced2d7daf64cd59e35f9be
morozov1982/python-checkio
/oop/the_warriors.py
6,696
4
4
""" ***** The Warriors *** (Simple) ***** ***(EN)*** I'm sure that many of you have some experience with computer games. But have you ever wanted to change the game so that the characters or a game world would be more consistent with your idea of the perfect game? Probably, yes. In this mission (and in several subseq...
c5e6ebcfb91bc63b4e520e6a63b8ffcb7ccb58cc
jkane002/tomas_python
/homework/unit_03/hw05.py
266
3.59375
4
import requests from bs4 import BeautifulSoup url = input("Enter a website to extract the URL's from: ") response = requests.get(url) page = response.content soup = BeautifulSoup(page, 'html.parser') for link in soup.find_all('a'): print(link.get('href'))
9edecbf7bd5f5afb31eafdef193a0ca04ec5a85e
benchng/python_onsite
/week_01/05_lists/Exercise_01.py
283
4.09375
4
''' Take in 10 numbers from the user. Place the numbers in a list. Using the loop of your choice, calculate the sum of all of the numbers in the list as well as the average. Print the results. ''' numbers = [1, 2, 3, 4, 5] sum = 0 for i in numbers: sum = i + sum print(sum)
576b007fdfa7c8cc983f6f9241118b85757b3be7
Alex-GCX/algorithm
/08.binary_search.py
2,233
3.765625
4
def binary_search(items, item): """二分法查找, 切片递归""" # 最优时间复杂度: O(1), 刚好要找的数就在中间 # 最坏时间复杂度: O(logn), 一直对半拆分, 直到拆到最后一层才找到元素, 共拆分了logn次 # 说明: 只能针对有序列表进行二分法查找 # 算法: 将有序列表对半拆分, 比较中间的元素和要找的元素, 若相等, 则找到了, 若比中间元素大, 则将右边列表切片出来递归调用, 继续寻找 # 使用切片只能判断元素是否在列表中, 而不能返回元素在列表中的下标位置 # 获取长度 length = le...
64c22bf8255a55cbed23b2a39b9f61d1626d87d1
burakbayramli/books
/Python_Scripting_for_Computational_Science_Third_Edition/py/regex/latex_subst.py
2,830
4.125
4
#!/usr/bin/env python """ This program investigates match and replacement involving words starting with a backslash. Such words are highly relevant when working with text in LaTeX format. The program identifies problematic characters that need a double backslash in the replacement string. For a right substitution, all ...
fb761f82946b04906b0afb4f62130a7cd0f498e7
NiceToMeeetU/ToGetReady
/Code/leetcode_everyday/0330.py
3,605
3.75
4
# coding : utf-8 # @Time : 21/03/30 10:39 # @Author : Wang Yu # @Project : ToGetReady # @File : 0330.py # @Software: PyCharm # Definition for singly-linked list. class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def ...
436974bf6f9725aa66ca63c3754c9d1e6d2e8c0b
yizhiyan1992/LeetCode_problems
/496_Next_Greater_Element_I.py
1,007
3.65625
4
#monostack problem #Keep the stack with decreasing order, when an element gonna be added in the stack, examine weather it is smaller than the peak element of the stack. # If yes, then put the element in the stack. If no, then pop the peak element and put the answer in array[stack[peak]]. Then, repeat this process until...
96c64fdfd4a2831871a61784c82675caad64a3de
vii-sem/vii-a-web-programs-DeepakPurohit_ENG17CS0062
/python program 4/program 4_thread.py
673
3.75
4
#Create Virtual Environment in Python2 ''' virtualenv -p `which python2` env source env/bin/activate ''' #copy the program in thread.py import _thread import time # Define a function for the thread def print_time(threadName, delay): count=0 while count <5: time.sleep(delay) coun...
eb58cf6d44f6c90444b3729b780a47284d5340eb
odys-z/hello
/challenge/leet/medium/q047.py
1,607
3.640625
4
from unittest import TestCase from typing import List from itertools import permutations class Solution2: ''' can't work in python 3.5? ''' def permuteUnique(self, nums: List[int]) -> List[List[int]]: return list( dict.fromkeys( permutations(nums) ).keys() ) class Solution: def permuteUni...
b25f4cdad748309ec1ae967bccf6ffade51044ba
sainad2222/my_cp_codes
/codeforces/382/A.py
346
3.828125
4
string = input().split("|") s = [len(x) for x in string] t = input() if (s[0] + s[1] + len(t)) % 2: print("Impossible") exit() mid = (s[0] + s[1] + len(t)) // 2 if not (s[0] <= mid and s[1] <= mid): print("Impossible") exit() string[0] += t[:mid - s[0]] string[1] += t[mid - s[0]:] print(stri...
b8041d9d964f868323b5a5d00fce79eee4e203e2
caleb0/ProjectEuler
/Questions 1-50/007.py
250
3.640625
4
# Problem 7 # 5th September 2016 # Python 2 def isPrime(n): for i in range(2, int(n**0.5)+1): if (n % i ) == 0: return False return True index = 1 num = 1 while index != 10001: if isPrime(num): index += 1 num += 2 print(num)
27ce45eb840660db8a1d7f8eedf9bd13fed94b2e
Yoodahun/Practice-RESTAPITest-on-Python
/CSV/CSVDemo.py
696
3.546875
4
import csv # Open the file and read with open('/Users/yoodahun/Documents/Github/Python/RestAPI-Testing-on-Python/utilities/practiceCSV.csv') as csv_file: csv_reader = csv.reader(csv_file, delimiter=",") # print(csv_reader) # print(dict(csv_reader)) name = [] status = [] for row in list(csv_re...
7d3abe8e4c22670fd6e72b28e1bdc178c2773865
Tymekkos/python-files
/RzutKostka/Proc4.py
1,534
4.0625
4
import random print("----------------------------") print("------ Dice Throwing -------") print("----------------------------") print("1 - Drawing ") print("2 - Quit") continuation = True operation = input("What will you choose ? - ") while continuation: res = random.randrange(1, 7) if opera...
7b511da832b6d985eada6c3691bf574f212acd19
sw30637/assignment8
/hh818/mergeByYear.py
401
3.703125
4
''' Created on Apr 14, 2015 @author: ds-ga-1007 ''' import pandas as p def merge_by_year(income, countries, year): '''merge two data sets by country names, and have three columns: Country, Region, and Income''' tempDf = p.DataFrame({'Country':income.ix['gdp pc test'], "Income":income.ix[year]}) mergedDf =...
468f09264e8b203f911845312f7db9d27592eb64
ZhouningMan/LeetCodePython
/dynamicprogramming/CoinsInALineII.py
1,529
3.6875
4
class Solution: """ @param values: a vector of integers @return: a boolean which equals to true if the first player will win """ def firstWillWin(self, values): if not values: return False n = len(values) if n < 3: return True dp = [0] * 3 ...
b1bae4b3c95226ba85208fe2f54aa9530e9ba585
knpatil/learning-python
/src/car.py
1,524
4.25
4
class Car: # constructor def __init__(self, make, model, year): self.make = make self.model = model self.year = year # odometer self.odometer_reading = 0 self.color = "red" # to string method -- means string representation of object def __str__(self): ...
a73f7a8016b7a8275e5a4e9c60b8b1bcf27f42b2
archenRen/learnpy
/leetcode/binary_search/code-69.py
308
3.53125
4
def mySqrt(x: int) -> int: def guess(mid): return mid * mid <= x lo = 0 hi = x + 1 ans = 0 while lo < hi: mid = (lo + hi) // 2 if guess(mid): ans = mid lo = mid + 1 else: hi = mid return ans print(mySqrt(231234))
b67926a1569c2e248232184d39f3e5d6a670d276
tomi77/python-t77-date
/t77_date/time.py
983
3.75
4
"""A set of datetime.time related functions""" from __future__ import absolute_import from datetime import datetime, time def diff_time(t1, t2): """ Calculates datetime.timedelta between two datetime.time values. :param t1: First time :type t1: datetime.time :param t2: Second time :type t2: d...
9b6049bf0bfa4303e4144fdcd2729dc5f269a7cf
aeronqu/projecteuler
/problem14.py
396
3.875
4
def collatzSeq(n): yield n while 1: if n == 1: break elif n % 2 == 0: n = n/2 yield n else: n = n*3 + 1 yield n def colatz(): for i in range(1,1000000): yield sum(1 for value in collatzSeq(i)) number = 0 for val...
ecba36c433819051003b329b4368ec0709c2c08d
khemadeepthi/python
/loops.py
820
4.03125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Dec 1 21:47:08 2018 @author: hema """ input_number = int(input("enter a number: ")) type(input_number) if(input_number < 10): print("input number is < 10") elif(input_number == 10): print("number is 10") else: print("input number is > 10")...
153aa9b3713cdf137d847860e43b861325f2a24c
amark02/ICS4U-Classwork
/Quiz2/test_evaluation.py
1,322
3.515625
4
import evaluation def test_average(): assert evaluation.average(1, 1, 1) == 1.0 assert evaluation.average(1, 2, 3) == 2.0 assert evaluation.average(3, 0, 0) == 1.0 def test_pieces_of_wood(): assert evaluation.count_length_of_wood([10, 12, 13, 10, 15], 10) == 2 assert evaluation.count_length_of_woo...
a38504fb9031d8aa7e4f804c147fdf7fc1f9100b
lucasbflopes/codewars-solutions
/7-kyu/map-function-issue/python/solution.py
309
3.875
4
def func(n): return int(n) % 2 == 0 def map(arr, somefunction): if not callable(somefunction): return 'given argument is not a function' elif any(str(n).isalpha() for n in arr): return 'array should contain only numbers' else: return [somefunction(n) for n in arr]
5359bdc2312603e6950b89c10eefb92ee16fa204
jddelia/think-python
/Section10/anagram.py
270
4.34375
4
# This program checks whether two words # are anagrams. def is_anagram(word1, word2): for i in word1: if i not in word2: break if i in word2 and i == word2[-1]: print(word1 + ' is an anagram of ' + word2 + '.') is_anagram()
bcabc538471d0925536463efca00cb6bf0e9edd5
AlexRuadev/python-bootcamp
/10 - Errors and Exceptions Handling/try_except_finally.py
1,004
4.28125
4
try: # introducing an error with "r" instead of "w" f = open('testfile', 'w') f.write('Write a test line') except TypeError: # if we have a type error, print the following print('There was a type error') except: print('There is another exception error') # Finally will always run the code, no...
5ed76ac888a1d0917832b9ed482aea6eb112b3f1
Favii4/Pruebas_de_conocimiento
/archivoParesImpares.py
750
3.671875
4
def num_pares(n=20): pares=[] contador = 0 numero = 0 while contador < n: if numero % 2 == 0: pares.append(numero) contador += 1 numero += 1 return pares def num_impares(n=20): impares=[] contador = 0 ...
a81c746208f502cbac9a4a4f591be5f131ad02cd
kanhaichun/ICS4U
/Shutupandbounce/Emma/FruitStand.py
7,000
4.09375
4
# -*- coding: utf-8 -*- """ Created on Mon Apr 16 16:27:32 2018 Porject name: Fruit Stand Purpose: to design a set of classes for a "Fruit Stand" application. Variables:name, quantity, price @author: fy """ class fruit: ''' This class organizes infomation for each fruit available at the stand. ''' #Pass...
bd79ed2f912fc5ff8b306ff49429e49e0f734c94
ccmiller214/python_api_class
/exchange.py
1,127
3.546875
4
#!/usr/bin/python3 import requests import json import argparse key = "LDLCS9364HNRRJEU" url = 'https://www.alphavantage.co/query?function=CURRENCY_EXCHANGE_RATE&from_currency={}&to_currency={}&apikey={}' def main(): try: if args.curto: toCurr = args.curto else: toCurr = input("Enter currency to c...
a3df4192584053b70855386b49501f85ae197c42
AKP101/Practice-Excercises-Python
/WritingToFiles.py
255
3.640625
4
# writing and appending to a file are different. writing poverwrites and appending adds text = "Sample Text to save\nA new Line!" saveFile = open("exampleFile.txt", "w") # open a new file to overwrite to it. saveFile.write(text) saveFile.close()
662f5f48447b93561747eb935777022b94b7be50
jborycz/Self-Taught-Programmer
/ch9-challenge/n2.py
87
3.515625
4
x = input("Write to a file: ") with open("writetofile","w+") as f: f.write(x)
a914d3e764f8d6a4081ca31b27b515a6c7731a8a
ericwu0930/leetcode
/Container With Most Water.py
352
3.609375
4
height=[1,8,6,2,5,4,8,3,7] left=0 right=len(height)-1 maxarea=(right-left)*min(height[left],height[right]) while left+1<right: if height[left]<=height[right]: left+=1 else:right-=1 newarea=(right-left)*height[left] if height[left]<=height[right] else (right-left)*height[right] if maxarea<newarea...
43fcd133cdb64467d96d3b01b055e848b435f428
trentmbx/GitHub
/LoginSys.py
5,122
3.890625
4
# coding: utf-8 # In[2]: get_ipython().run_line_magic('pylab', 'inline') from time import * # In[3]: usernames = [] passwords = [] emails = [] # In[ ]: #-Boolean creation-# usrn_check1 = False pswrd_check1 = False usrn_check2 = False pswrd_check2 = False fpass = False taken1 = False taken2 = False #-Ask us...
a23201b014fa9f2dc743feac342aa94d09eee6b0
MarcelArthur/leetcode_collection
/628_Maximum_Product_of_Three_Numbers.py
1,244
4.09375
4
# python3 ''' description: 维护一个最大堆和最小堆,遍历一遍数组,持续更新最大堆和最小堆的值,从而得到一个2个元素的最小堆和3个元素的最大堆. 时间复杂度O(n), 空间复杂度O(1) Given an integer array, find three numbers whose product is maximum and output the maximum product. Example 1: Input: [1,2,3] Output: 6 Example 2: Input: [1,2,3,4] Output: 24 Note: The length of the given array w...
80bc592b47ed3db15ed164b1e17508c099978dcf
codingple/PyNavi
/trajectory_clustering/z_clusering.py
3,150
3.71875
4
from itertools import combinations from driver import index, lat, lon, clustering_criterion, time import distance_calculator """ In clustering, every distance among GPS points are supposed to be calculated, and GPS clusters based on close interval are produced between two trajectories of each pair, which are comprised...
fc44764db5edf03211e637d0fd02a9eaf2bc80e7
martincastro1575/python
/3.- Introducing Lists/try_your_self/3-6 more_guests.py
832
3.8125
4
guests = ['margaret', 'simon', 'juana'] print('\t\nGuest list to dinner:',f"\n\tGuest number one: {guests[0].title()}", f"\n\tGuest number two: {guests[1].title()}", f"\n\tGuest number three: {guests[2].title()}") print("I've got had news for you, my dears!!!", "I've found a big table for ...
ab26ce1f3a122d1c30b032d52d5548ab41200a2a
AJsenpai/codewars
/order.py
1,174
3.921875
4
""" Your task is to sort a given string. Each word in the string will contain a single number. This number is the position the word should have in the result. Note: Numbers can be from 1 to 9. So 1 will be the first word (not 0). If the input string is empty, return an empty string. The words in the input String will o...
bbe7fb7d8f5bc7b1bc1bde3db889008c30e07a01
CaseyMcGuire/leetcode_old
/InvertBinaryTree/python/solution.py
487
3.546875
4
from collections import deque from TreeNode import * class Solution: # @param {TreeNode} root # @return {TreeNode} def invertTree(self,root): if root is None: return self._invert_tree(root) return root def _invert_tree(self, node): if node is None: ...
5e352b95e7eca27b124c6dbd2abb08ec5f3bd837
suacalis/VeriBilimiPython
/Ornek13_7.py
632
3.765625
4
''' Örnek 13.7: Soyut sınıf ve metot kavramını bir önceki örnek uygulama üzerinden açıklayalım. ''' from abc import * class Pizza(ABC): #üst soyut sınıf icerik = ['Peynir', 'Zeytin'] @classmethod #sınıf metodu @abstractmethod #soyut metot def getMalzeme(cls): return cls.icerik #DiyetPizza ...
32cf275e8646e74570ebaf3b1168ec1f54007f44
albiurs/edu_codecademy_learn_python_3
/src/01_syntax/08_calculations.py
1,065
3.875
4
""" 08_calculations @author created by Urs Albisser, on 2020-10-10 @version 0.1 """ # Calculations # # Computers absolutely excel at performing calculations. The “compute” in their name comes from their historical association with providing answers to mathematical questions. Python performs addition, subtraction...
b213e7068eb35cfcfff83e91a0a6497f66848cdb
keithxm23/CTCI
/Ch1_Arrays_and_Strings/q1_3.py
942
4.28125
4
#Check if one string is permutation of the other import sys if len(sys.argv) != 3: raise Exception("Please provide input string. Run 'python q1_3.py <string-here> <string-here>'") else: str1 = sys.argv[1] str2 = sys.argv[2] """ #method1 by sorting both if sorted(str1) == sorted(str2): print "Strings are anagra...
5c7f875bbe4f07cb1978255d1131ee8676a24eb4
xHammercillox/Kata1
/Kata1/1#if2.py
801
4
4
""" Escribir un programa para una empresa que tiene salas de juegos para todas las edades y quiere calcular de forma automática el precio que debe cobrar a sus clientes por entrar. El programa debe preguntar al usuario la edad del cliente y mostrar el precio de la entrada. Si el lciente es menor de 4 años puede e...
733d6127e88ebf391f58f4a3685b9ce735c2cd15
pavanq/Practice
/q23.py
556
3.953125
4
#n=input("No. of values:") #lst=[] #for i in range(0,n): #print i #lst[i]=input("Enter value:") #print lst lst=[1,2,3,4,5,6,7,8,9,10] value=input("Enter value to be searched:") def binary(data,key,start,end): mid=(start+end)/2 if data[mid]==key: return mid if data[mid]>key: ...
dd91e8cb0fd32b0b5e45195a084e1c806f2a38e8
sainihimanshu1999/Dynamic-Programming
/MinimumSubarrayMinProduct.py
549
3.6875
4
''' In this question we use monotonic stack, monotonic stack is a useful data structure which helps in knowing the boundary of things, used in many questions like maximum area in histogram etc ''' def minProd(self,nums): stack = [(-1,0)] running_sum = 0 max_sum = 0 nums.append(0) for v in nums: ...
a61df0bcce436d1eb14369d4a9a4e24f94374cfe
paulyun/python
/Schoolwork/Python/In Class Projects/3.10.2016/Notes.py
230
4.09375
4
print (format(y,'.2f')) # this code tells you to print only 2 decimal points. #the .2f means 2 decimal points. if it was .5f it would be 5 decimal points. 2**5 = 2 to the power of 5 or print ("using function pow() ..",pow(3, 5))
67343cc61852c0c78df55e439f2adda09e17745a
MarcoGorelli/rsmtool
/rsmtool/container.py
10,080
3.921875
4
""" Classes for storing any kind of data contained in a pd.DataFrame object. :author: Jeremy Biggs (jbiggs@ets.org) :author: Anastassia Loukina (aloukina@ets.org) :author: Nitin Madnani (nmadnani@ets.org) :organization: ETS """ import warnings from copy import copy, deepcopy class DataContainer: """ A clas...
d1aa5868314e78d4acc951a7ac2996eb4c69d105
isi-frischmann/python
/multiples.py
534
4.40625
4
# Part I - Write code that prints all the odd numbers from 1 to 1000. Use the for loop and don't use a list to do this exercise. for i in range (1, 1000): if i % 2 == 0: print i # Part II - Create another program that prints all the multiples of 5 from 5 to 1,000,000. for i in range (5, 1000000): ...
d15ce695b88491568046dce38def69a8c535cf4b
iamsamitdev/BasicAdvancePythonPRD
/pythongui/gui07.py
4,690
3.703125
4
from tkinter import * from tkinter import ttk mainfrm = Tk() mainfrm.title("โปรแกรมเครื่องคิดเลข") # แสดงข้อความที่ title bar # สร้างฟังก์ชัน calculate() กำหนดรูปแบบการคำนวณ def calculate(): result = 0 # ก่อนการคำนวณควรเซ็ตค่าผลลัพธ์เป็น 0 ทุกครั้ง entResult.delete(0, END) # เคลียร์ช่องผลลัพธ์ให้เป็นค่าว่...
1486e84c7e1dab4d52043a775a7d0d82c9cb20e6
speed785/Python-Projects
/main.py
1,502
4.0625
4
import Employee p1 = Employee.Employee() p2 = Employee.Employee() p3 = Employee.Employee() p1_Name = str(input("Please enter the Name for First employee: ")) p1_id = int(input("Please enter the Id Number for First Employee: ")) p1_Department = str(input("Please enter the Departmet of First Employee: ")) p1_Position =...
7d79ce9fe82653773c0a169c1e5bd436052b583e
rozeachus/Python.py
/takingAVacation.py
1,130
4.4375
4
""" This code is taken from the Python excercise 'Taking a Vacation' on CodeAcademy. It will calculate how much a trip will cost, taking into account the hotel, car hire, flights and spending money. """ # First we define the cost of the hotel, which is $140 per night def hotel_cost(nights): return 140 * nights # ...
0aff84adce41e42e273eed7c239eed58209312b6
EmilyOng/cp2019
/y5_practical3/q2_display_pattern.py
421
4.0625
4
#2 (Displaying patterns) q2_display_pattern.py #Write a function display_pattern(n) to display a pattern as follows: # 1 # 2 1 # 3 2 1 #... #n n-1 ... 3 2 1 def display_pattern(n): for i in range(n): for j in range(0,n-i-1): print(" ",end="") for k in ra...
17cbff8b56d99a94ba6d808d2372bc0071a501e8
TalhaYa/My_Python_Project
/MehmetAbiAperatif.py
1,996
3.75
4
tum_siparis = {"Siparisleriniz": [], "Hesabınız": []} aperatif = {"Kasarlı Tost": 6, "Kıymalı Tost": 8, "Sucuklu Yumurta": 10,"Karışık Tost": 10, "Sucuklu Tost": 7,"Soguk Sandvic":7} print("*****Aperatif ÇEŞİTLERİMİZ*****") print(aperatif) def siparis(yemek): siparis_listesi = [] ...
43423637f8bb846103623332dc6b3d8a6d1e9aec
tulioac/ExerciciosTST
/unidade05/abaixo_da_media/p.py
304
3.671875
4
lista = [] media = 0 valor = '' while(valor != 'fim'): valor = raw_input() if valor != 'fim': lista.append(float(valor)) media += float(valor) media /= len(lista) print "%.2f" % media for i in range(len(lista)): if lista[i] < media: print "%d %d" % (i+1, lista[i])
db3bbc96c2dc844c9ccd0df553e7cf7d881e4eb1
QiliWu/leetcode-and-Project-Euler
/leetcode/10-Regular Expression Matching.py
830
3.546875
4
class Solution(object): def isMatch(self, s, p): """ :type s: str :type p: str :rtype: bool """ if not p: # p = '' return not s # True if s = '', and False if not #bool(s): return False if s = '' # p[0] should = t[0] or '.', otherwise F...
68cceac8266799ce3bb1eaac29aed22a9b374c36
albusdunble1/Leetcode
/leet_code/easy/leet_robot.py
1,052
3.671875
4
class Solution(object): def judgeCircle(self, moves): """ :type moves: str :rtype: bool """ # vertical = 0 # horizontal = 0 # for move in moves: # if move == 'U': # vertical += 1 # elif move == 'D': # ...
d3eea85ab79961773f24f52b3b35dd8f5dd5d83b
srikanthpragada/PYTHON_07_SEP_2018_DEMO
/oop/mi.py
420
3.765625
4
class A: def print(self): print("print() of A") def add(self): print("add() of A") class B(A): def print(self): print("print() of B") def sub(self): print("sub() of B") class C(B,A): def print(self): print("print() of C") def fun(v): pass fun(10)...
37aedc746a3ac3bd0edfd58591442275c4837628
monkop/Data-Structure-in-Python
/Stack/stackArray.py
722
3.75
4
class StackArray: def __init__(self): self._data = [] def __len__(self): return len(self._data) def isempty(self): return len(self._data) == 0 def push(self,e): self._data.append(e) def pop(self) : if self.isempty(): print('stack is empty') ...
a535d1ce0fac7c3030509efbc6f15e814f453bfe
ceneri/CSBasics
/Queue.py
2,913
4.0625
4
#!/usr/bin/env python3 """ File: Queue.py Author: Cesar Neri <neri102xD@gmail.com> Date: 05/07/2019 Custom implementation of Queue using my custom LinkedList. Queue makes use only of LinkedList methods that would guarante an O(1) runtime for all of the Queue basic methods. """ from LinkedList import Lin...
b67122683f2509b193b3d5d6dea09687c06e04b3
hanjingfeng1971/appelpy
/appelpy/eda.py
2,886
3.96875
4
"""Methods for general exploratory data analysis. These are for analysis on datasets, rather than analysis on models. """ import pandas as pd import numpy as np import scipy as sp import matplotlib.pyplot as plt import seaborn as sns def statistical_moments(df, *, kurtosis_fisher=True): """Produce a dataframe w...
5f596f8bb8ce82aeb203b80efd6ca6938a32467e
GenosseBlaackberry/MIPT_B02-113
/lab 2 (Turtle 1)/Exercise 9.py
701
3.828125
4
import turtle turtle.shape('turtle') import math turtle.speed(10) def polygon(n, r, alpha, spin=1, par=True, T=True): pos =[] if par: a=r else: a=r*(2*math.sin(math.pi/n)) if T: turtle.penup() turtle.forward(a/(2*math.sin(math.pi/n))) turtle.left(spin*180-90*(n-2...
a2b1918de9aed6e5dad6ecc0aab03bdbada59d2c
mveselov/CodeWars
/katas/kyu_6/help_the_bookseller.py
370
3.53125
4
from collections import defaultdict OUTPUT = '({} : {})'.format def stock_list(books, categories): if not books or not categories: return '' book_quantity = defaultdict(int) for book in books: code, num = book.split() book_quantity[code[0]] += int(num) return ' - '.join(OUTPUT...
911e5dcb4612d47cf090accd862d035888c35611
jgarciaodowd/Boletin1
/main.py
5,541
3.96875
4
# Ej. 1: print("---EJERCICIO 1:") numero = int(input("Escribe un número entero: ")) print("La tabla de multiplicar es: ") for i in range(1, 11): print(f'{i} * {numero} = {i * numero}') # Ej. 2: print("---EJERCICIO 2:") def bucle(): for j in range(10, 20): print(j) bucle() ...
084f4ed722201763c9a1b9a4e70b26ed2dc94956
Zylophone/Programming-for-Sport
/pramp.com/as josvi/01-BST_successor_searh_scratch-work.py
1,218
3.75
4
Jose # 100 # / \ # 50 200 # / \ / \ # 10 70 150 300 # for a node n, if it has a right subtree then return the smallest in the right subtree, which is the left most node in the right subtree # if n does not have a right subtree, # look at the parent # if the successor was placed in the ...
d52fd774013246e530351ab32c89aa3d64a14fc5
artsiom-kotau/coursera-alg-spec
/alg-toolbox/week4_divide_and_conquer/1_binary_search/binary_search.py
874
3.828125
4
# Uses python3 import sys import math def do_search(left, right, a, x): mid = math.ceil((right + left) / 2) length = right - left if length == 0: return -1 if length == 1: return -1 if a[left] != x else left if a[mid] == x: return mid elif a[mid] < x: return do_...
d2c49855562d61ccd7a26e08b12a511b21a254b0
popuguy/ga-testing
/ga1.py
1,531
3.703125
4
import random POPULATION_SIZE = 100 CHROMOSOME_SIZE = 40 MAGIC_NUMBER = 42 RECOMBINATION_RATE = 0.7 MUTATION_RATE = 0.001 def split_every(s, n): split = [] while len(s) >= n: split.append(s[:n]) s = s[n:] return split def fitness(chrom): value = parse_chromosome(chrom) if value == MAGIC_NUMBER: return 2 #m...
cd0112fdc5011381b456da5d110749630682f00c
rokigeorg/CloudVision_AssableLine
/01_Camera/ImgStoredInDB/retrieveImgDB.py
429
3.625
4
import sqlite3 # create or connect to database conn = sqlite3.connect('testDB.db') # get the curser to do stuff in the db cur = conn.cursor() cur.execute("""SELECT name,bdata FROM pictures WHERE name == 'pic_4.png' """) data = cur.fetchone() # send all commands from the cursor to the db conn.commit() # close the ...
8e0a46f1d34c23f56b5694805327221d41f2f560
prachuryanath/DSA-Problems
/Easy/83. Remove Duplicates from Sorted List/ans.py
1,356
3.75
4
class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def deleteDuplicates(self, head: ListNode) -> ListNode: # if input head is NULL, return it # if input is single node, return it since there are no repetitions if not head...
5776e97f3d274d06dbe48b445370dfa290afd3e5
cairoas99/Projetos
/PythonGuanabara/exers/listaEx/Mundo2/ex067.py
262
3.84375
4
num = ctg = 0 while True: num = int(input('Insira um numero para fazer a tabuada ( negativo para parar): ')) print('='*62) if num < 0 : break for c in range(0, 11, 1): print(f'{num:^4} X {c:^4} = {num*c :^5}') print('=' * 62)
a2c55fbdc35ef473b4db76d7cd600cc8ec46e9ab
Domen1234/Programerski-Krozek
/srecanje2/Elif.py
183
3.703125
4
n = 10 if n % 2 == 0: print("Deljiv je z 2") elif n % 3 == 0: print("Deljiv je z 3") elif n % 4 == 0: print("Deljiv je z 4") else: print("Ni deljiv z niš od tega.")
c771da6a9f5d2fdcf575a1193101920d807bf120
Jason003/Interview_Code_Python
/stripe/vo/toy database.py
2,905
3.578125
4
import functools class Comparator: def __init__(self, key, direction): self.key = key self.signal = 1 if direction == 'asc' else -1 def compare(self, left, right): left.setdefault(self.key, 0) right.setdefault(self.key, 0) if left[self.key] < right[self.key]: ...
d94878215ecf281b803076c1058b92f7c5ba1b64
JejeDurden/TSP-Solver
/parser.py
434
3.5625
4
import argparse def parse_args(argv): parser = argparse.ArgumentParser() parser.add_argument("<salesmen>", type=check_positive, help="number of salesmen as a positive number (e.g: \"1\" or \"42\")") args = parser.parse_args() return args def check_positive(value): ivalue = int(value) if ivalue...
acafccc6c42a80814675b04367b9e55a3d850913
vinicius-gadanha/python-courses-cev
/MUNDO 3/ex088.py
655
3.671875
4
from random import randint from time import sleep print('=' * 60) print('{:^60}'.format('GERADOR DE JOGOS')) print('{:^60}'.format('PARA MEGASENA')) print('=' * 60) njogos = int(input('Digite a quantidade de jogos que você quer gerar: ')) print('=' * 60) print('{:^60}'.format(f'GERANDO {njogos} JOGOS...')...
11af499b75e3b70c1f0d8550212110bfb8c064bb
reddevil1996/Python-DS
/CheckInsertion.py
272
4.25
4
import InsertionSort as Is lst = [] size = eval(input('Enter the size of the list: ')) for i in range(size): n = int(input('Enter the number: ')) lst.append(n) print('Before sorting list is: ', lst) Is.Inssort(lst) print('After sorting list is: ', lst)
5c4dc54ea91230809df0b25196e8a53663fce28f
jamiezeminzhang/Leetcode_Python
/math/268_Missing_Number.py
875
3.9375
4
# -*- coding: utf-8 -*- """ Created on Sun Feb 21 13:43:21 2016 268. Missing Number Total Accepted: 39162 Total Submissions: 100071 Difficulty: Medium Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missing from the array. For example, Given nums = [0, 1, 3] return 2. ...
3ac1258bf21afaea944f502abbcfd4ea13a729da
SaiAnvitha-k/Bestenlist
/day2.py
1,123
4.28125
4
#How to print a value: print("30 days 30 hour challenge") print('30 days 30 hour challenge') #Assigning String to Variable: Hours = "thirty" print(Hours) #Indexing using String: Days = "Thirty days" print(Days[0]) #How to print the particular character from certain text: Challenge = "I will win" print(Challenge[...
f401499c50c5f5aec76be903116c672a6dfe3833
pogrebnyak/PythonBasic
/class/oop_car/cars.py
804
4.1875
4
class Car(object): """ self.price - чистая цена. Может быть изменена методом "Акция" self.skidka - по-умолчанию отсутсвует. Создаётся методом "Акция" """ def __init__(self, name, color, price): self.name = name if not isinstance(color, str): raise ValueError('color inco...