blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
fcfb08c49955b7776f1787cb51b7259d52e7a592
Bulgakoff/Python_Algos
/Урок 1. Практическое задание/task_8.py
1,822
3.5625
4
""" Задание 8. Определить, является ли год, который ввел пользователем, високосным или не високосным. Подсказка: Год является високосным в двух случаях: либо он кратен 4, но при этом не кратен 100, либо кратен 400. Попробуйте решить задачу двумя способами: 1. Обычное ветвление 2. Тернарный оператор П.С. - Тернарные ...
f6a09619d980ee0af57cbbe4bc5846141095e71b
LSSTC-DSFP/LSSTC-DSFP-Sessions
/Sessions/Session15/Day1/oop/camping/two_classes/camping.py
1,637
3.59375
4
import operator class Camper: max_name_len = 0 template = '{name:>{name_len}} paid ${paid:7.2f}' def __init__(self, name, paid=0.0): self.name = name self.paid = float(paid) if len(name) > Camper.max_name_len: Camper.max_name_len = len(name) def pay(self, amount):...
b4ece7180624ce6fd0c2943d337ee19e5c05b4e4
rpgiridharan/Ullas_Class
/Day9/8_foo.py
650
4.0625
4
# decorator: # we wish to extend the functionality of a fn def embellish(f): # f is the function that we wish to decorate # inner is the function that will get called when we call the original function which we have decorated. So, inner must ideally have the same number of parameters as the original (unless, you wish...
f9804e3d2306f2f2a10e028c6842396fcec9ac0d
anhaidgroup/py_stringmatching
/py_stringmatching/similarity_measure/partial_ratio.py
4,390
3.625
4
"""Fuzzy Wuzzy Partial Ratio Similarity Measure""" from __future__ import division from difflib import SequenceMatcher from py_stringmatching import utils from py_stringmatching.similarity_measure.sequence_similarity_measure import \ SequenceSimilarityMeasure clas...
21f72a4e449db097ef3b69f0fe130766a85d9850
kamikazeren/Phys-177_Spring-Quarter_2016
/Week 4 - Lab/ex2.py
1,755
3.78125
4
""" Renata Koontz SID: 861166139 Due: April 26, 2016 11:00 pm Exercise 2 Week 4 """ import math import numpy as np import numpy.linalg as lin import array import matplotlib.pyplot as plt import pdb accuracy = 1e-10 initial = 0.0 final = 1.0 def p(x): y=(924.0*x**6)-(2772.0*x**5...
db2f563196cd231f2aff6f28d8d6d0ba177346bf
QitaoXu/Lintcode
/interviews/MS/firstUniqCharIndex.py
582
3.5
4
class Solution: """ @param s: a string @return: it's index """ def firstUniqChar(self, s): # write your code here alp_to_times = {} for c in s: if c not in alp_to_times: alp_to_times[c] = 1 ...
b27131a89c2a12a6a286ea4d3dd52351c3bead16
gyan-garcia/ML_Training
/ann_mnist_classification.py
2,301
3.9375
4
# -*- coding: utf-8 -*- """ Created on Fri Sep 22 14:30:12 2017 @author: ggarcia """ import keras from keras.datasets import mnist from keras.models import Sequential from keras.layers import Dense import matplotlib.pyplot as plt # Function to display the one dimentional array into a 2 dimentional digi...
978debb050f28e666aeae39fb04bb5921459c1dd
wjosew1984/python
/ceropositivonegativo.py
192
4.0625
4
n=int(input("ingrese un numero: ")) if n==0: print("el numero es cero") else: if n>0: print("el numero es positivo") else: print("el numero es negativo")
7dfba0b38a356fabd235bc530eb91b92c3194201
kongaeri/fun_project1
/fib.py
179
3.734375
4
#!/usr/bin/python2.7 fibo=[] fibo.append(0) fibo.append(1) fibo.append(1) n = input("Enter the n: ") for i in range(3, n+1): fibo.append(fibo[i-2]+fibo[i-1]) print (fibo[n])
4be631db8c722a66acc3554580031c1d135ffe7e
nellaG/project_euler
/p13.py
624
3.625
4
# Problem 13 Large Sum: # Work out the first ten digits of the sum of the following # one-hundred 50-digit numbers. import os def main(): digits = '' large_sum = 0 with open('p13file', 'r') as f: digits = f.read() f.close() digits_list = digits.split('\n') for digit_line in digits_list: lar...
20f58f4301710f2d49dcbef63a2ed4f8f2d12d82
kimsunsoo/pre-education
/quiz/pre_python_15.py
452
3.75
4
"""15. 주민등록번호를 입력하면 남자인지 여자인지 알려주는 프로그램을 작성하시오. (리스트 split 과 슬라이싱 활용) 예시 <입력> 주민등록번호 : 941130-3002222 <출력> 남자 """ num = input('주민등록번호 : ') num_split = num.split("-") # print(num_split[1][0]) if num_split[1][0] == '3' or '1': print('남자') elif num_split[1][0] == '4' or '2': print('여자')
c991bf8b32c7cf9f92524cf13158461822cce9e7
sfdjj/leetcode
/python/addTwoNumbers/Solution.py
1,014
3.578125
4
class Solution: def addTwoNumbers(self, l1, l2): if l1 is None or l2 is None: return l2 if l1 is None else l1 head = None pre = None r = 0 while l1 and l2: sum = l1.val + l2.val + r x = int(sum % 10) r = int(sum / 10) ...
0cad2f83c43cdcd6925a8c81d78e3b25ec20e1ed
bruninhaout/Python-course-udemy
/exercicios/secao4/Ex07.py
219
4.15625
4
# ler em graus Fahrenheit, converter para graus Celsius fahr = float(input('Insira a temperatura em graus Fahrenheit = ')) celsius = 5 * (fahr - 32) / 9 print(f'A temperatura {fahr}°F em Fahrenheit é {celsius}°C')
cb4a0f81cf6c2b0740467867dba19348b458da7a
ksayee/programming_assignments
/python/CodingExercises/MaxDiffBetween2SubsetsOfMElements.py
1,044
3.953125
4
''' Maximum difference between two subsets of m elements Given an array of n integers and a number m, find the maximum possible difference between two sets of m elements chosen from given array. Examples: Input : arr[] = 1 2 3 4 5 m = 4 Output : 4 The maximum four elements are 2, 3, 4 and 5. The minimum f...
3b07d28769d6fa7af09c98404b94e63a3a86f6c6
Arjun-Pinpoint/InfyTQ
/Programming Fundamentals using Python/Day 4/Assignment 33.py
668
4.15625
4
''' Write a python program to display all the common characters between two strings. Return -1 if there are no matching characters. Note: Ignore blank spaces if there are any. Perform case sensitive string comparison wherever necessary. Sample Input Expected output "I like Python" "Java is a very popular language" li...
119c0fd8d4ea889d57e744de6869c056c804a5c6
seanrsinclair/AdaptiveQLearning
/multi_dimension/tree_model_based_multiple.py
12,989
3.625
4
import numpy as np import matplotlib.pyplot as plt import matplotlib.patches as patches ''' Implementation of a tree structured used in the Adaptive Discretization Algorithm''' ''' First defines the node class by storing all relevant information''' class Node(): def __init__(self, qVal, rEst, pEst, num_visits, n...
9602e30bc269ff2c6df9171c458918c84dd6b638
cladren123/study
/AlgorithmStudy/백준/6 유니온파인드/2 친구 네트워크.py
972
3.671875
4
def find(friend) : global parent if friend == parent[friend] : return friend else : parent[friend] = find(parent[friend]) return parent[friend] def union(x,y) : global parent global answer x = find(x) y = find(y) check = parent[y] if x != y : for ...
dbdc8b08e774551d0352f57760bf531a6022fd29
Kawser-nerd/CLCDSA
/Source Codes/AtCoder/arc005/A/4902042.py
204
3.546875
4
n = int(input()) s = input().rstrip('.').split() ans = 0 for i in range(n): if s[i] == 'TAKAHASHIKUN'\ or s[i] == 'Takahashikun'\ or s[i] == 'takahashikun': ans += 1 print(ans)
7f358679ba57a65742a6fade783323eb49dc5ad2
Lioscro/ist4-pcp-analysis
/solvers/example/student3/testing.py
744
4.09375
4
def _findDedups(s): ''' Given a string, finds all the possible deduplications as a list of strings. This list is sorted by decreasing duplication size, which is equivalent to sorting by increasing deduplication string length. ''' l = len(s) dedups = set() # Iterate through all possible ...
ed46a0113eac43229c4f17a3c1e65ea10c804cd5
Amogh1226/python-games-programs-drawings
/PythonTutorials/list.py
160
3.546875
4
A=[1,2,3.15,'edureka'] print(A) print(A[1]) A[1] = 'Changed 2nd element' print(A) B = ([1,2,4], 4, 'third element', (2,4,5)) print (B[3][2])
b2d3bb9c86176bcf7f159eee28a596e87b216ef8
Yuchen112211/Leetcode
/problem1029.py
1,401
3.78125
4
''' 1029. Two City Scheduling Easy There are 2N people a company is planning to interview. The cost of flying the i-th person to city A is costs[i][0], and the cost of flying the i-th person to city B is costs[i][1]. Return the minimum cost to fly every person to a city such that exactly N people arrive in each city...
f90634e46a7d5a129c2e98848bc2cd237f4259d3
Carrot97/LeetCodeClassic
/two_points/16_threeSumClosest.py
1,001
3.5
4
def threeSumClosest(nums: list, target: int) -> int: def helper(ans, diff, a, b, c): val = a + b + c diff_ = abs(val - target) if diff_ < diff: diff = diff_ ans = val return ans, diff n = len(nums) nums.sort() diff = 1e8 ans = 0 for first ...
794841fecf32e24edf6fbbed7e5d21570a904ae6
AshKnight99/Leetcode-problems
/Prob52.py
1,460
3.8125
4
""" 52. n-Queen II The n-queens puzzle is the problem of placing n queens on an nn chessboard such that no two queens attack each other. Given an integer n, return the number of distinct solutions to the n-queens puzzle. Example: Input: 4 Output: 2 Explanation: There are two distinct solutions to the 4-queens puzzle ...
0a68770ed58d98d0db033d1263a7d145c659ea32
npavlinov/OxfordHack2018
/back/Paragraph.py
686
3.78125
4
class Paragraph(object): def __init__(self, file_name, nb, keywords, text): self.file=file_name self.nb=nb#of the pargraph in the file self.keywords=keywords self.text=text def __str__(self): return str(self.file)+' §'+str(self.nb)+' - '+str(self.keywords) def __re...
a3f162835d6bf953c204b41cab0c2577c1f1625f
nikoWhy/softuniPython
/simple_calculations/ivan_money.py
379
3.78125
4
days_per_month = int(input()) dollars_per_day = float(input()) dollar_leva = float(input()) money_per_month = days_per_month * dollars_per_day money_per_year = money_per_month * 12 + 2.5 * money_per_month net_year_money = money_per_year - 0.25 * money_per_year dollars_per_day = net_year_money / 365 leva_per_day = ...
6de3d92ce07c5d2d361070d8f1b74411a961dabd
yhoiseth/paytext
/paytext/paytext.py
2,895
3.5
4
# pyre-strict """ This module helps you work with payment texts such as "*4321 29.06 USD 50.00 ITUNES.COM/BILL Rate: 1.0000". """ from re import compile as compile_regex from typing import List, Any import iso4217parse class PaymentText: """ Use this class to represent your payment text. """ parts: ...
dda63ff13b35c939acd7bde86b598fbde98d0b3c
dakshtrehan/Python-practice
/Conditionals and Loops/cat and mouse.py
316
3.625
4
import math def catAndMouse(x, y, z): print(math.fabs(x-z)) print(math.fabs(y-z)) if math.fabs(x-z)>math.fabs(y-z): return ("Cat A") elif math.fabs(x-z)<math.fabs(y-z): return ("Cat B") elif math.fabs(x-z)==math.fabs(y-z): return ("Mouse C") catAndMouse(1,2,3)
4042e01588822b8ecd39f0fad8dc8f752be4d55f
Jatin666/py-assignment
/py day6 part 2.py
1,490
3.96875
4
EXECUTE THE COMMAND PRINT "DOUBLE QUOTES" PRINT "SINGLE QUOTES" PRINT ''' MULTILINE''' STRING1='HELLO WORLD' STRING2= "WE'RE HERE#1!" STRING3='1234' STRING4="I SAID, "PULL IT OVER BY THE LLAMMA" NUMBER = 12 FLOAT = 3.14 ##PRINTING WITH DOUBLE QUOTES print ("DOUBLE QUOTES") DOUBLE QUOTES ##printing with singl...
9949f66fb8c3e48115c6800a49b458bb7f04acce
DHRUVSAHARAN/python-
/ch 6/practice_4.py
193
3.96875
4
usernme = input("enter your user name :") uname= (len(usernme)) if (uname>10) : print ("the name is long than 10 chracters") else: print ("the name is not 10 character long")
36dc64d04ff523cefa0b6528907102862620d873
Anantadhirya/python-xi1-danielanantadhirya
/18 Feb 2021_Nomor 05.py
216
3.546875
4
import itertools, random deck = list(itertools.product(range(1,14),["kriting", "hati", "wajik", "sekop"])) random.shuffle(deck) print("kamu mendapat: ") for i in deck[:5]: print("{} dari {}".format(i[0], i[1]))
d6516b35e35a94827a154e7e4647de3555a3f1ec
chloequinto/CS115
/map_reduce.py
1,070
3.796875
4
''' Created on Jan 25, 2018 @author: Chloe Quinto ''' ''' Range range(stop) -> [ 0, 1, 2,...stop-1] [0, stop) range(3)-> [0,1,2] range(start, stop) -> [start, start+1, ... stop-1] range(2,5) -> [2,3,4] range(start, stop, step) -> [start, stop) going up or down step units between ...
f6387a03b54881a1cd7e1d5d380989d929ebeba0
andrewquamme/CS151_Python
/Module 04/LoanAppTest2.py
1,237
4.21875
4
def getApproval(fico): ## Function to take FICO score as input and ## calculate if loan is approved or not. ## Returns a tuple containing approval Y/N and interest rate approval = 'Y' # Initialize approval to Yes if fico >= 760: # Determine interest rate based on FICO score ...
d36138b2701217357ef08bc5fd1c68a13da80478
jzlou/auto-hanabi
/player/playleft_basic.py
4,614
3.734375
4
import util import numpy as np class PlayLeftBasic: def __init__(self, n_players, n_handcards): r"""Initialize a player. Initialize all internal fields and prepare player object for gameplay. Parameters ---------- n_players : int Total number of players. ...
e14a8e3a6da716955f49ebec0328924cdbaaa721
christinandrea/lab-10-dictionaries
/exercise10.py
1,702
3.765625
4
#Christina Andrea Putri - Universitas Kristen Duta Wacana #Andi ingin menginput data pribadinya dan teman-temannya untuk keperluan pendataan liburan mereka. # Yang perlu diinput adalah nama, umur, dan destinasi pilihan masing-masing. # Namun, Andi salah menginput salah satu data dan salah satu temannya batal ikut ju...
0e4b879ec9118b7ed3bfe39e3b2bd6c150c72ca2
nishitpatel01/Data-Science-Toolbox
/unittest/101_circle_area/circles.py
185
4.03125
4
from math import pi def circle_area(r): if r < 0: raise ValueError("value is negative") if type(r) not in [int, float]: raise TypeError("not integer or type") return pi * r ** 2
fd50a3ee734e92b3009f002dd3da89acf8f213bc
tlee753/sharing-sequence
/demo.py
276
3.59375
4
import sys def demo(x): output = "AB" for i in range(x): temp = "" for l in output: if (l == 'A'): temp += "AB" else: temp += "BA" output = temp print(output) demo(int(sys.argv[1]))
32285d34681c303514d531d8babe1c46b16536e1
amit-kr-mishra/Python
/Test.py
239
3.734375
4
nums =[2,4,8,5,6] target=7 dict= {} for i in range(len(nums)): print("hello ", nums[i]) if nums[i] in dict: print(dict[nums[i]],i) else: dict[target-nums[i]]= i print("-----------------") print(dict)
e8b60b849aa71d3ff5edf3d308ae5130beb81704
emmadeeks/CMEECourseWork
/Week2/Code/cfexercises1.py
2,702
3.78125
4
#!/usr/bin/env python3 #Author: Emma Deeks ead19@imperial.ac.uk #Script: cfexercises1.py #Desc: Conditionals exercise containing 6 different foo_x calculation functions. # Later modified to make a module that tests the foo_x functions as well as runs test arguments #Arguments: No input #Outputs: The output of all ...
222c601fd6b01af2fcbc65f13d04f74987cc2f0b
tdabro/isapy8-tdabro
/06-tdabro.py
131
3.734375
4
def fibon(n): x,y,i=1,1,1 while i <= n: x, y = x + y, x print("y="+str(y)) i=i+1 print(fibon(5))
32af30dfa45a5cfb74286acfb23ca5d4cc8b03ee
maximashuev/mike_udemy_course
/my_decorator.py
1,210
3.5625
4
# Свою реализацию пишите внутри функции, не меняя её имя. # Функция должна быть использована в качестве декоратора для других функций. #solution 1 def my_decorator(func): def wrap(*args): print(*args) if isinstance(*args,(int,str,list,dict,bool,tuple,set)): print("Функция вернула значе...
083d97694dfddb56cf142440e0eda32bbf435ecf
Ankit10511/Prediction-Using-Linear-Regression
/Prediction of Data Using Linear Regression.py
1,038
3.5
4
#!/usr/bin/env python # coding: utf-8 # In[1]: import numpy as np import pandas as pd import matplotlib.pyplot as plt # In[12]: dfx = pd.read_csv('Linear_X_Train.csv') dfy = pd.read_csv('Linear_Y_Train.csv') dfx = dfx.values dfy = dfy.values x = dfx.reshape((-1,1)) y = dfy.reshape((-1,1)) print(dfx.shape, dfy....
a46fed7720a0ddbc102daa21d90d976254220011
Mohammed-Jasim/1_1
/Pair_programming.py
1,043
3.59375
4
import turtle as trtl import random t = trtl.Turtle() t.speed(0) def triangle(a): hyp = a* 2 **0.5 t.forward(a) t.left(135) t.forward(hyp) t.left(135) t.forward(a) def square(color,size): t.pencolor(color) t.fillcolor(color) t.begin_fill() for i in range(4): ...
4fd124a3e50526dc3abaf1463a4cd7c200bfcb86
nisheeth-golakiya/CSN212-HW
/Tutorial-3.py
3,767
3.984375
4
'''Implementation of Interval Tree by augmenting BST''' class Interval(object): '''Implementation of Interval data-type''' def __init__(self, low, high): super(Interval, self).__init__() self.low = low self.high = high class Node(object): '''Implementation of Node data-type''' def __init__(self...
6474c4422c8aaf58ee00695cf4f437b2c55259a3
upul/WhiteBoard
/algorithm/elements/rpn.py
731
3.59375
4
def rpn(expression): evaluator = [] OPERATORS = { '+': lambda x, y: y + x, '-': lambda x, y: y - x, '*': lambda x, y: y * x, '/': lambda x, y: y / x } for token in expression.split(','): if token in OPERATORS: evaluator.append(OPERATORS[token]( ...
8a5486352cd7f664a2e2c627a8a285444d62fe54
edu-athensoft/ceit4101python_student
/tuit_200202/py200306/output_formatting_3.py
301
3.75
4
""" try out all the number formatting type """ # case - d print("Hello {0}, your balance is {1:9d}".format("Adam", 230)) # case - c print("bin: {0:b}, oct: {0:o}, hex: {0:x}".format(12)) # integer numbers with minimum width filled with zeros print("{:05d}".format(12)) print("{:5d}".format(12))
eb8633691298999083ba911c5162641b9475cd9a
Debs-76/ProjetoLogicaComp
/functions.py
2,973
3.75
4
from ProjetoLogicaComp.formula import * def length(formula): """Determines the length of a formula in propositional logic.""" if isinstance(formula, Atom): return 1 if isinstance(formula, Not): return length(formula.inner) + 1 if isinstance(formula, Implies) or isinstance(formula, And)...
381e871b8535505dfa46cbe257ffffd8ddde3a85
SpacialCircumstances/WikiDateScraper
/src/wikidate.py
871
3.75
4
class WikiDate: def __init__(self): self.days = 0 self.month = 0 self.year = 0 def test_values(self): return self.days <= 31 and self.days >= 0 and self.month <= 12 and self.month >= 0 def get_date_string(self): days = "" if self.days < 10: days...
7f6d22fb16d49de1ccf83b571eec43135d580fa2
ItsFadinG/Python-100-Day-of-Code-Walkthrough
/100Python_Day_Code_Challenges/Day1-3/Date_Time_Module.py
2,026
4.0625
4
import datetime # Datetime.date # # get the date format d = datetime.date(2018, 8, 5) print(d) # today(): get today date today = datetime.date.today() print(today) print(today.day) print(today.year) print(today.weekday()) # Monday 0 # Sunday 6 print(today.isoweekday()...
486666e352ac9330389d6200d94e75fa352a1ea4
amildie/leetcode-solutions
/convert-integer-to-the-sum-of-two-no-zero-integers.py
274
3.578125
4
# https://leetcode.com/problems/convert-integer-to-the-sum-of-two-no-zero-integers/ class Solution: def getNoZeroIntegers(self, n: int) -> List[int]: for i in range(1, n): if '0' not in str(i) and '0' not in str(n-i): return [i, n-i]
58fd8fd878e20de1ec0f69751a33897aa5f753c1
andrefacundodemoura/exercicios-Python-brasil
/exercicios_python_brasil/lista01_estruturas_sequenciais/ex03soma03.py
247
3.84375
4
''' 03. Faça um Programa que peça dois números e imprima a soma. ''' n1= int(input('Digite o primeiro valor a ser somado : ')) n2= int(input('Digite o segundo valor a ser somado : ')) soma = n1+n2 print(f'A soma entre {n1} + {n2} = {soma} ')
0e2d0d6fe70b09f48c6f45fad3ffc85e86a9ee39
NilGamer/birthday_wisher
/main.py
1,061
3.609375
4
import smtplib import datetime as dt import pandas import random my_email = "email" password = "password" # read the csv file data = pandas.read_csv('birthdays.csv') now = dt.datetime.now() # create a tuple today = (now.month, now.day) # dictionary with key as monday,day tuple and value as row birthdays_dict = {(da...
c6a8fb7d8da5134dc1b2af40514f9c202010286b
milesmackenzie/dataquest
/step_2/data_analysis_pandas/getting_started_numpy/intro_numpy.py
1,185
3.859375
4
# using np.array to produce arrays and .shape to produce tuples import numpy as np vector = np.array([10, 20, 30]) matrix = np.array([[5, 10, 15], [20, 25, 30], [35, 40, 45]]) vector_shape = vector.shape matrix_shape = matrix.shape # reading data sets w/ numpy.genfromtxt() function producing # type <class 'numpy.nda...
c56ea949424ef4707699c1e285de2af7435c9795
amarnath2706/Python-Basics
/5.Loops.py
1,819
4.15625
4
#!/usr/bin/env python # coding: utf-8 # In[1]: st="Hello world" m="" for i in st: m=i+m print(m) # In[2]: st="Hello world" m="" for i in st: m=m+i print(m) # In[3]: #Reverse the string st="Hello world" m="" for i in st: m=i+m print(m) # In[12]: s="Hello Jasvee Adithri" m="" for i in s...
e4e6bfaf6fff25a7db941f97735f5cd6029af931
DannyHui/python
/Day01/ThreeLevelMenu/ThreeLevelMenu.py
1,617
3.53125
4
# ------------------------------- # Task Name:三级菜单 # Description : # 1、运行程序,输出一级菜单; # 2、选择一级菜单某项,输出二级菜单,同理输出三级菜单; # 3、允许用户选择是否退出; # 4、可以返回上一级菜单; # Author : Danny # date: 2017/10/31 # ------------------------------- import json # 读取菜单文件的数据 with open("menu.json", "r", encoding="utf-8") as f: data = json.load(f) prin...
33341040d0b7f9bc5f9b928fefd6a4ab129d462e
Miku-1/test
/1.py
6,186
4.03125
4
# # class Node(object): # # def __init__(self,value): # # self.value = value # # self.pnext = None # # # # class ChainTale(object): # # def __init__(self): # # self._head = None # # # 头插法 # # def add(self,value): # # node = Node(value) # # node.pnext = self._head ...
1b62d49d30c61fed59fbdff360401276adb9a48e
nurinamu/projects_100
/python/repeated_n_times.py
491
3.5625
4
from typing import List class Solution: def repeatedNTimes(self, A: List[int]) -> int: dic = {} for num in A : if num in dic : dic[num] += 1 else : dic[num] = 1 times = len(A) / 2 for key in dic : if dic[key] == ti...
77c8aa9b3521c66ab47a9adba78ee4914f2555c8
htl1126/leetcode
/222.py
932
3.625
4
# ref: https://discuss.leetcode.com/topic/17971/my-python-solution-in-o-lgn # -lgn-time # Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def countNodes(self, root):...
d85052e41d10b727641800242dcb13a208a56de7
arunchaganty/spectral
/python/optim/ProximalGradient.py
2,074
3.671875
4
""" General proximal gradient methods """ import scipy as sc from scipy import diag, array, eye, ones, sqrt, zeros from scipy.linalg import norm from util import ErrorBar class ProximalGradient: """A proximal gradient method consists of two steps: a convex gradient step and a proximal step """ def __...
601589760a5cae2506f706947dd9481c6632d0c9
itsolutionscorp/AutoStyle-Clustering
/all_data/exercism_data/python/difference-of-squares/e936b4f14fe8458cbd41822f4ce31829.py
276
3.828125
4
def difference(limit): return square_of_sum(limit)- sum_of_squares(limit) def square_of_sum(limit): a = range(limit+1) b = sum(a) return b*b def sum_of_squares(limit): squared = [a**2 for a in range(limit+1)] return sum(squared)
59d5f67ab4fd1cd3c8cda4072a7df48ae44be916
lifesailor/python-advanced
/1.logging/logging-a.py
805
3.765625
4
# logging by print def sqrt(x, guess=1.0): if x < 0: print("음수가 입력되었습니다.") raise ValueError print("Find sqrt of {} starting with guess {}".format(x, guess)) if good_enough(guess, x): return guess else: print("Guess is not good enough. Improve...") ...
fb955613f468b9bcd62bb93bfee0af1e63b88d75
bensoer/echo-acknak
/socketsystem.py
1,678
3.578125
4
__author__ = 'bensoer' from socket import * ''' SocketSystem is a general class for creating and managing udp sockets. It is intended to be inherited from by the client or server wishing to make socket connections ''' class SocketSystem: def __init__(self): self.__socketSystem = socket(AF_INET, SOCK_DGRAM...
f38a5073ea8cba20ab588aaf144cbe52ec0f872b
v4s1levzy/practicum_1
/19.py
686
4.15625
4
X = int(input("Сторона 1:")) Y = int(input("Сторона 2:")) Z = int(input("Сторона 3:")) if (X+Y <=Z) or (Y+Z <=X) or (Z+X <= Y): print("Треугольник с такими сторонами не существует:") if (X > Y and X > Z) and (X**2 == Y**2 + Z**2): print("Треугольник прямоугольный:") elif (Y > X and Y > Z) and (Y ** 2 == ...
84b7ebd5d7c7f0c85f0893e61199d39fc4f8f28d
juaneks/PruebaPython
/prueba.py
1,465
3.953125
4
#!/usr/bin/python #-*- coding: utf8 -*- # usando ninja IDE import string import miModulos.Calculos as cal def sacaIVA(valor,iva): total =0.0 if valor > 100: total = valor * iva else: total = "solo a valores mayor a 100 se saca IVA" return total # valor = raw_input("ingrese el valor :")...
d6b9ed8a2378fd56ca565ec7507794d01961f3e3
sgreenh23/Engineering_4_Notebook
/Python/AutomaticDiceRoller.py
358
3.96875
4
# Automatic Dice Roller # Written by SHoaplhliiae from random import randint print("Automatic Dice Roller") print("Press 'enter' to roll, 'x' to exit") answer = input() while answer.lower() == "": num = randint(1,6) print ("You rolled a", num) print ("Roll again?") answer = input() #while answer.l...
0d8bfd8f9c73d260c022aee0069c72dd172ff08b
abnormalmakers/generator-iterator
/iterable_fn.py
669
3.671875
4
l1=['中国移动','中国联通','中国电信'] l2=[10086,10010,10000,9999] for t in zip(l1,l2): print(t) for n,a in zip(l1,l2): print(n,a) print(dict(zip(l1,l2))) def myzip(iter1,iter2): it1=iter(iter1) it2=iter(iter2) while True: v1=next(it1) v2=next(it2) yield (v1,v2) for n,a in myzip(l1,l...
7893da0eb94c24ac54560ed1107dd7e808783bdb
amingst/crypto-price-predictor
/utils/data/Manipulators.py
1,229
3.875
4
import numpy as np def remove_zeros(data_in): """ Takes an input dataframe and removes zero valued indecies. Parameters ---------- data_in: pandas dataframe, required The input dataframe. Returns ------- data_out: pandas dataframe The original dataframe wit...
fbcb773914b679242707adc614e64d63d6e26314
pczerkas/yattag
/test/tests_indentation.py
2,275
3.5
4
import unittest from yattag import indent class TestIndent(unittest.TestCase): def setUp(self): self.targets = { '<p>aaa</p>': '<p>aaa</p>', '<html><body><p>1</p><p>2</p></body></html>': """\ <html> <body> <p>1</p> <p>2</p> </body> </html>""", '<...
668910e9beec2eb9ce06cc74e45a3eab8cc79d6e
TurboJapuraEfac/CS50-Python
/dict data strcuts.py
319
3.9375
4
from cs50 import get_string people = { "Brian": "+1-617-495-1000", "David": "+1-949-468-2750" } name = get_string("Name: ") if name in people: print(f"Number: {people[name]}") if name in people: number = people[name] #Search is auto handled using hash tables in built print(f"Number: {number}")
e18d1116a6418d47bde94e4431ffe7542aed0e9d
dimk00z/grokking_algorithms
/7_Dijkstras algorithm.py
2,088
3.859375
4
from pprint import pprint from copy import copy INFINITY = float('inf') def dijkstras_search(graph, start, finish): if start not in graph or finish not in graph: return 'Strange nodes have been given' if start == finish: return 'Start and finish must be different nodes' pprint(graph) ...
fd7b36774c4529396052585e429ce941102f15ed
arfio/PolyAlgo
/google_codejam_2010/StandingOvation.py
959
3.765625
4
def standing_ovation(path): with open(path, mode='r') as file: lines = file.readlines() test_case_number = 0 line_number = 1 while test_case_number < int(lines[0]): test_case_number += 1 # variables for this problem sum_persons_clapping = 0 ...
2ea4c4abe187f7f51f9e6a2e90fce65e1a9b783e
AdamZhouSE/pythonHomework
/Code/CodeRecords/2910/60672/315043.py
1,009
3.5
4
def nums(string): num='0123456789' nums=[] i=0 while i<len(string): midstring='' k=0 for j in range(i,len(string)): if string[j] in num: midstring+=string[j] k=k+1 else: break if midstring!='': ...
6f70c61887460f0372223e208de11c1fca8cc9a7
RamyaAddulla/Python-Basic-For-All-3.x
/Even_Odd.py
106
4.0625
4
n = int(input()) if n%2==0: print(n,"Given Number is Even") else: print(n, "Give number is odd")
c9c9ec2246c43cbd8e0ecb591390c8a2c9911c9b
sourabhgome/DataStructures
/AEQuestions/0020 - Monotonic_array/iterative.py
397
3.625
4
def isMonotonic(array): isNonDecreasing = True isNonIncreasing = True for i in range(1, len(array)): if array[i] < array[i-1]: isNonDecreasing = False if array[i] > array[i-1]: isNonIncreasing = False return isNonIncreasing or isNonDecreasing #Driver Code: array...
7283816067f24b29f5e1340af4da3e1965bcfe13
alluballu1/OOP-tasks
/Tasks/Exercise 8/HouseClass.py
1,681
3.875
4
# File name: HouseClass.py # Author: Alex Porri # Description: a class for a house # creating the class class House: def __init__(self, floors, windows, bed, surfaces, fridge, toilet_paper): self.__floors = floors self.__windows = windows self.__bed = bed self.__surfaces = surfaces...
b3a30cf45d0bf83a3ff7b967dba11496530f2864
MeetLuck/works
/thinkpython/word_frequency.py
1,917
4.09375
4
import string ''' chapter 13 case study: data structure selection ''' #--------- word frequency analysis ----------------- def process_file(filename): hist = dict() fp = open(filename) for line in fp: process_line(line,hist) return hist def process_line(line, hist): line = line.replace('-...
2152734434353c266b7c73526053f4e82319e2e9
filiperecharte/FEUP-FPRO
/FPROPlay/Py10/Celsius.py
147
3.5
4
# -*- coding: utf-8 -*- """ Created on Thu Dec 12 14:52:33 2019 @author: filip """ def to_celsius(t): return [round((i-32)/1.8,1) for i in t]
a4831e8f370c2550b712d21858115c5d85ef5627
RomaMol/MFTI
/DirOPP/Lec3/main4.py
2,105
4
4
# https://www.youtube.com/watch?v=WP2sqI2BkeY&list=PLA0M1Bcd0w8zo9ND-7yEFjoHBg_fzaQ-B&index=3 # ООП Python 3 #3: режимы доступа - public, private, protected. Геттеры и сеттеры class House: """Класс существительное с большой буквы x = 1 y = 1 атрибуты == данные def fun() - методы == функции STAT = 5 ...
0fb03651ad4c78e471e6a2bb069df693ebc0ad91
libertyfromthinking/code-up-python-algorithms
/basic_45.py
244
3.546875
4
i1, i2 = input("값을 두개 입력하면 합, 차, 곱, 몫, 나머지, 몫+나머지를 출력합니다 : ").split() i1 = int(i1) i2 = int(i2) if i1<i2: i1, i2 = i2, i1 print(f'{i1+i2}\n{i1-i2}\n{i1*i2}\n{i1//i2}\n{i1%i2}\n{i1/i2}\n')
0587180d62a81ec802bbe9742a4c759eb2d054cb
gustavo-pedroso/MazeSolver
/dfs_solver.py
925
3.59375
4
from queue import LifoQueue from solver import Solver class DFSSolver(Solver): @staticmethod def solve(graph): path = [] predecessor = {} my_set = set() stack = LifoQueue() stack.put(graph.begin) found = False while not stack.empty(): v =...
cceb6db0f0cb6c144f5dd16e7a577af8bcc86725
kerstinjw/leetcode
/006_ValidPalindrome.py
928
3.71875
4
#-*- coding:utf-8 -*- class Solution: # @param s, a string # @return a boolean def isPalindrome(self, s): if not s: return True sp = 0 ep = len(s) - 1 while sp < ep: while sp < ep: if ord(s[sp].lower()) >= ord("a") and ord(s[sp].lower()) <= ord("z"): break if ord(s[sp]) >= ord("0") and ord...
1b6608119cc2387083b659ceaf6916b8076e3fd8
ErickMwazonga/sifu
/recursion/learning/_max.py
228
3.78125
4
# Find the maximum element in a given array. def _max(nums: list[int]) -> int: if len(nums) == 1: return nums[0] sub_max = sub_max(nums[1:]) return nums[0] if nums[0] > sub_max else sub_max assert _max([2, 4, 6, 1]) == 6
3adef8b449e706157f69820becf46e2fabcde1fd
hky001/PythonStudy
/test.py
1,009
3.5
4
# def printPicnic(itemsDict,leftWidth,rightWidth): # print('PICNIC ITEMS'.center(leftWidth+rightWidth,'-')) # for k,v in itemsDict.items(): # print(k.ljust(leftWidth,'.') + str(v).rjust(rightWidth)) # picnicItems = {'sandwicher' : 4, 'apples' : 12,'cups' : 4,'cookies': 8000} # printPicnic(picnicItems,12...
4956d1d9bcd78dc74e4e129ed795ee0d75b6eedd
lwolczynski/Sudoku-Solver
/solver.py
8,149
3.671875
4
import time #used to check script's run time #class representing a single cell of sudoku board class Cell: def __init__(self, row_number, column_number, value): self.row = row_number #0 thru 8 self.column = column_number #0 thru 8 self.box = self.set_box_number() #0 thru 8 self.valu...
62cd1986bd9d1982046c3d2d38fe656b2324141a
ElianMelo/python
/Aulas/Mundo 02 Estruturas de Controle/Aula 14 - Desafio 61.py
206
3.8125
4
prm_termo = int(input("Primeiro termo: ")) razao = int(input("Razão: ")) dez_termos = prm_termo while dez_termos != prm_termo + (razao * 10): print(dez_termos, end=" ") dez_termos += razao
1d7179ca3e4a15d040bb4d913a8a9d2927ecfdd6
AshutoshDash1999/hackerrank-python-problems
/the-captains-room.py
558
3.625
4
# problem link = https://www.hackerrank.com/challenges/py-the-captains-room/problem # every one came with family except the captain # so if a room is assigned to a person with only one member then he must be captain # I m facing the problem of runtime error, it would be great if you can help me # in optimising the code...
1d9357be3025a576595c8552a0e990d1f2c1041d
gzgdouru/python_study
/python3_cookbook/chapter04/demo08.py
222
3.625
4
''' 跳过可迭代对象的开始部分 ''' import itertools if __name__ == "__main__": lines = [1, 1, 2, 3, 1, 4, 5] for i in itertools.dropwhile(lambda x: x == 1, lines): print(i, end=" ") print("")
fcb7d2bef80f8557d8eb84302b92fe5e739944d7
njpayne/pythagoras
/Archive/Falling_Distance.py
981
4.25
4
# The following forumla can be used to determine the distance that an object falls # due to gravity in a specific time period from rest: d = 1/2gt^2 # d = distance, g = gravity = 9.8 m/s^2, t = time in seconds that the object has been falling # Write a program that determines the distance in meters that an object has f...
a4d77118da3e56f5978a2d2101a8e83692b6be5c
jaimeliew1/Project_Euler_Solutions
/Python/113.py
1,130
3.796875
4
# -*- coding: utf-8 -*- """ Solution to Project Euler problem 113 - non-bouncy numbers Author: Jaime Liew https://github.com/jaimeliew1/Project_Euler_Solutions there are (9 + k - 1) choose k ways to arrange the digits 1,2,3,4,5,6,7,8,9 with repetition in ascending order in a k digit number. (see 'combination with re...
e1ade7eed72e2a8322fcea8188d9e86ec5a3dd6e
KotaroW/scratch-pad
/lambdatest.py
255
3.96875
4
#!/usr/bin/python # a lambda function within a dictionary myDictionary = { "val1" : 100, "val2" : 199, "lambda" : lambda : myDictionary["val1"] + myDictionary["val2"] } # call the lambda function - return value is 299 print ( myDictionary["lambda"]() )
e431b0bfbe8ed40520c62dbc44f7628f08b8c1de
Silentsoul04/FTSP_2020
/Extra Lockdown Tasks/Strings_Methods_Python.py
453
4.3125
4
''' Strings Methods in Python :- --------------------------- ''' str1 = 'PYTHON IS VERY SIMPLE' str2 = str1.lower() print(str2) print(str1) str1 = 'python is simple' str2 = str1.upper() print(str2) str1 = 'Python is very easy' str2 = str1.replace('easy','Very easy') print(str2) str1 = 'Python is simple simple and...
43203b25ad57052170a7d774b53aac3fda360ac9
Galahad3x/AdventOfCode2020
/day06/day06.py
727
3.546875
4
filename = "input.txt" def part_1(): with open(filename, "r") as f: answered = [] total = 0 for line in f.readlines(): if line == "\n": total += len(answered) answered = [] else: for c in line: if c != '\n' and c not in answered: answered.append(c) print("Part 1: ", total) def ...
f6424bda672f5d975bff3d64cfb42a67b854af30
mvpcom/highway-env
/highway_env/agent/abstract.py
998
3.640625
4
from __future__ import division, print_function from abc import ABCMeta, abstractmethod class AbstractAgent(object): """ An abstract class specifying the interface of a generic agent. The agent interacts with an environment that implements the highway_env.mdp.abstract.MDP interface. """ me...
7f7baddf0e0cd09d663b894317c09d16c1fce56c
sauuyer/python-practice-projects
/day5-number-checker.py
995
4.5
4
# Prompt: Ask the user to enter a number. Tell the user whether the number is positive, negative, or zero. def user_input_number_checker(): while True: try: entered_number = float(input("Enter a number: ")) break except ValueError: print("Enter a number value (5...
776acaba32cde4c363bd71f47b4cedf178d06528
nsm-lab/principles-of-computing
/mini_project0.py
7,984
3.59375
4
# Mini-project 0 for Principles of Computing class, by k., 06/13/2014 # clone of 2048 game; GUI is provided in codeskulptor (obscure Python interpretter for the class) at: # http://www.codeskulptor.org/#poc_2048_template.py def merge(line): ''' helper function that merges a single row or column in 2048 '''...
aefc15f05a6c004e21b3b929fb573d51bdff92ba
Mong-Gu/PS
/programmers/오픈채팅방.py
1,128
3.640625
4
def solution(record): arr = [] result = [] dic ={} # record의 각 원소를 공백 기준으로 잘라서 그 조각들을 arr의 각 원소로 append for i in range(len(record)): arr.append(record[i].split(' ')) # 딕셔너리 내부의 닉네임을 최종 상태까지 변경 for i in range(len(arr)): # Enter if arr[i][0] == 'Enter': ...
21b277374ef0dbadb97bc9ea929ba48ab7eee1b5
nakulgoud/pract
/pract/dsa/PYTHON/array/rotate.py
1,104
3.765625
4
''' Juggling algorithm: Link for problem: http://www.geeksforgeeks.org/array-rotation/ ''' def gcd(a, b): if b == 0: return a return gcd(b, a%b) def left_rotate_method1(arr, rotate_by): for i in range(0, gcd(len(arr), rotate_by)): temp = arr[i] j = i while True: ...
1f9c55907660ec23c5b0cf1b1365273af64bd30a
2019-fall-csc-226/t03-boustrophedon-turtles-barnwellj-wellst-t03
/t03_stub.py
1,649
4.15625
4
################################################################################# # Author: Jacob Barnwell Taran Wells # Username: barnwellj wellst # # Assignment: TO3 # Purpose: ################################################################################# # Acknowledgements: # # ###################################...
de4cb1312805b0e737a78e113f32b49f23e7cf0c
amirmohammadi318/class-phython
/S2.P02.py
126
3.953125
4
a=int(input("please enter a number": b=int(input("please enter a number": c=a%b ifc==0:print("bakhshpazir") else:print("not")
d2f970487ef80989117ba393e48f32afe42ff72d
alexgolec/career-advice
/code/interview-problems/ratio-finder/dfs.py
678
3.5
4
# A linear-time, recursive DFS-based solution. from collections import deque def __dfs_helper(rate_graph, node, end, rate_from_origin, visited): if node == end: return rate_from_origin visited.add(node) for unit, rate in rate_graph.get_neighbors(node): if unit not in visited: ...
cbdf344f5bd7049f642ea45602e0dd313cbe87e1
Mahany93/PythonStudyNotes
/Break_Continue_Pass.py
872
3.75
4
########################################## #-----------Break, Continue, Pass--------# ########################################## # # Continue # myNumbers = range(1,11) # for number in myNumbers: # if number == 2: # continue # Stop the current iteration (skip), and continue the loop. # print(number) #...