blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
5d3941860a11594b919ab06131c26ac6ad37de1e
AdamZhouSE/pythonHomework
/Code/CodeRecords/2063/60581/238546.py
132
3.609375
4
str = list(input()) judge = True for i in range(0,len(str)): if str[i]!=str[len(str)-i-1]: judge = False print(judge)
75082b988949518887f76045916f595774c8c944
rodrigocruz13/holbertonschool-machine_learning
/unsupervised_learning/0x01-clustering/1-kmeans.py
4,644
3.984375
4
#!/usr/bin/env python3 """ PCA: principal components analysis """ import numpy as np def initialize(X, k): """ Funtion that initializes cluster centroids for K-means: Args: - X numpy.ndarray Array of shape (n, d) containing the dataset that will be u...
ce6dc826697b19ef60194695b286515143cc8a34
svw-epg/DateEngine
/Week1_NA/Action.py
1,766
3.890625
4
# # Action1: 求2+4+6+8+...+100的求和,用Python该如何写 # # result = 0 # a = 2 # while a <= 100: # result = a + result # a += 2 # print(result) # # Action2: 统计全班的成绩 # import pandas as pd # # score = pd.DataFrame({'语文': [68, 95, 98, 90, 80], # '数学': [65, 76, 86, 88, 90], # ...
6c738bd444d75faf0598a1ef42d8e667c51acc0a
Gingervvm/JetBrains_Hangman
/Problems/Difference of times/task.py
282
3.71875
4
first_hour = input() first_mins = input() first_seconds = input() second_hour = input() second_mins = input() second_seconds = input() print(int(second_seconds) + int(second_mins) * 60 + int(second_hour) * 3600 - (int(first_seconds) + int(first_mins) * 60 + int(first_hour) * 3600))
98131f5fcfbb2e5a9c0498e23af9cbc4a3ad6500
saurabhkawli/PythonHackerRankCodes
/MatrixRotation.py
139
3.65625
4
mat=[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]] for i in range(mat): for j in range(mat): print(mat[i][j])
f1da9a28e245622c1356c9f714dba3c7cff97c1a
DStheG/ctci
/01_Arrays_and_Strings/09_String_Rotation.py
1,080
4.09375
4
#!/usr/bin/python """"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" 1.9 String Rotation Assume you have a method isSubstring which checks if one word is a substri- ng of another. Given two strings, s1 and s2, write code to check if s2 is a rotation of s1 using only one call to isSubstr...
ac4065c06c5b81ac5879c1f355e8982375697a59
marinella2012/python_tasks_ibs
/task6.py
943
3.921875
4
# Есть класс Animal c одним методом voice(). # class Animal: # def voice(self): # pass # 1. Создать от него три класса наследника и для каждого сделать свою # реализацию метода voice(). # 2. Создать по одному экземпляру всех наследников и вызвать для каждого # переопределенный метод voice(). class Animal(): def __i...
bbefe3abc82b8de0f7e5bea44d948b072d58e7cf
Shilpa25453/codeigniterproject
/python/class.py
524
4.125
4
'''class myclass: x=5 p=myclass() print(p.x)''' '''class myclass: a=20 def function(self): print("hello") p=myclass() print(p.a) p.function()''' '''class person: def __init__(self,name,age): self.n=name self.k=age p=person("john",36) print(p.n) print(p.k)''' '''class person: ...
b7f9bf9426b4a3a2ef7223ccf1ee96d60e854c26
nathanramnath21/project-106
/project106/cups-of-coffee-and-less-sleep.py
208
3.53125
4
import plotly.express as px import csv with open('cups of coffee vs hours of sleep.csv', newline='') as f: df=csv.DictReader(f) fig=px.scatter(df, x="sleep in hours", y="Coffee in ml") fig.show()
763ace5028414f8a92c4314e07496bb07dbbc100
tabithableil/library
/sort/insertion_sort.py
711
4.375
4
def insertion_sort(lst): """ insertion sort: compare all the elements previous to the newly 'inserted' element. if the new element is smaller, then 'shift' the previous element(s) forward in the list until the end of the list is reached or a position is found where the element to the left is smaller...
17f12a02a912a9e118a8f0692e8ee4c233ddb1dd
chc1129/python_jisen
/05/isDefArg.py
5,170
3.953125
4
# 関数のさまざまな引数 # 位置引数 - 仮引数名を指定しない実引数の受け渡し def increment(page_num, last): next_page = page_num + 1 if next_page <= last: return next_page raise ValueError('Invalid argument') increment(2, 10) # 位置引数による関数呼び出し print( increment(2, 10) ) # 実引数が足りない # increment(2) # increment(2) # TypeError: increment() missin...
148f13e0b4781925768e94a2d6524f1ef73e710c
sushiljacksparrow/geeks
/graph.py
2,726
3.984375
4
class adj_node: def __init__(self, data): self.vertex = data self.next = None class Graph: def __init__(self, vertices): self.V = vertices self.graph = [None] * self.V def add_edge(self, src, dest): # create destination node and add src to destination node n...
cd311b951f5d5438637893d26f13a6f151d008ea
tulcas/master-python
/07-ejercicios/ejercicio_01.py
359
4.1875
4
""" Ejercicio 1 - Crear dos variables: pais y continente - Mostrar el valor por pantalla - Poner comentario indicando tipo de dato """ pais = "España" # string continente = "Europa" # String print(f"La variable pais contiene: {pais} y es del tipo: ", type(pais )) print(f"La variable continente contiene: {continente...
8a45e93a248855cfa66334ff425bcd920c2885dc
ubushan/facedetect
/findface.py
1,057
3.734375
4
""" Face Recognition https://face-recognition.readthedocs.io/en/latest/usage.html """ import face_recognition # Loads the image into numpy array image = face_recognition.load_image_file(r"faces/people.jpeg") # Find all the faces in the image face_locations = face_recognition.face_locations(image) # print('Faces dete...
511f0ae81dbff231884563acca686e1180f664d8
ahmedmeshref/August-LeetCoding-Challenge
/day_20/Reorder_List.py
806
3.859375
4
# Definition for singly-linked list. class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def reorderList(self, head: ListNode) -> None: """ Do not return anything, modify head in-place instead. """ cu...
bef00c17aa625b0ea4ff55d0563636992fa28091
bbuluttekin/MSc-Coursework
/PoPI/question3.py
678
4.03125
4
class ManhattanTaxi: '''implement the class''' def __init__(self, initX, initY, consuption, init_fuel): self.X = initX self.Y = initY self.pos = (self.X, self.Y) self.cons = consuption self.fuel = init_fuel def moveto(self, toX, toY): self.distanc...
134abf747fe81498780e8a841048ea561450c549
vall/project_euler
/pe_21.py
492
3.5
4
#!/usr/bin/env pypy # -*- coding: utf-8 -*- from __future__ import print_function import math def get_divisors(x): res = [1] for i in range(2, int(math.sqrt(x))+1): if x % i == 0: res.append(i) res.append(x/i) return res def main(): res = 0 for i in range(10000): ...
f4f8dd7d06ee034c71067294d8cd66df416ba6ea
tomorrowdevs-projects/challenges
/challenges/intermediate/the-merchants-guide-to-the-galaxy/solutions/fdb86/input.py
861
3.59375
4
from re import search from bot import Bot class InputBot: def __init__(self, prefix: str = '', suffix: str = ''): self.prefix = prefix self.suffix = suffix self.bot = Bot(prefix=self.prefix, suffix=self.suffix) def __str__(self): return "{}\n{}".format(self.bot.items, self.b...
2d61255a0af3801cadb732163994035a2f7ebd73
tiaotiao/leetcode
/198-house-robber.py
624
3.5625
4
class Solution: def rob(self, nums): """ :type nums: List[int] :rtype: int """ robCurr = 0 robPrev = 0 robPrePrev = 0 for num in nums: # print(num, robCurr, robPrev, robPrePrev) curr = num + max(robPrev, robPrePrev) ...
01e0f72de557d75ba2bda4d4a7afb5a93591d925
sassyst/leetcode-python
/leetcode/BFS/solution_127.py
1,235
3.53125
4
""" LeetCode Word Ladder""" class Solution: def ladderLength(self, beginWord, endWord, wordList): """ :type beginWord: str :type endWord: str :type wordList: List[str] :rtype: int """ if endWord not in wordList: return 0 wordDict = set(wo...
04361a2c63ae2cd97994dc7d6ca9fc3024ec1205
Artimi/intervaltree
/test/optimality.py
1,259
3.59375
4
""" intervaltree: A mutable, self-balancing interval tree for Python 2 and 3. Queries may be by point, by range overlap, or by range envelopment. Test module: IntervalTree optimality Copyright 2013-2014 Chaim-Leib Halbert Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file excep...
c073a7037b858c6065d3e1f2814c047b58371773
sky7sea/KDD_Daily_LeetCoding_Challenge
/0329-0404 (Week_1)/RobertHan/235.Lowest Common Ancestor of a Binary Search Tree/solution.py
1,064
3.71875
4
# 235. Lowest Common Ancestor of a Binary Search Tree # https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/ # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None # 6->2->4 root-> l -> ...
7a7ff0a77a32c13b67334c17c4d93d92d818939b
django-group/python-itvdn
/домашка/starter/lesson 4/Marukhniak Denys/Lesson_4_3.py
166
3.8125
4
n = int(input('Enter number (n) of n!: ')) n_res = 1 print(f'{n}! = ', end='') while n > 0: print(f'{n}', end=' * ') n_res *= n n -= 1 print(f'= {n_res}')
af99fbb510ed56e64d0dd5d150750817f19f9bd6
px1916/algorithm004-01
/Week 02/id_111/leetcode_1_111.py
2,576
3.515625
4
# 两数之和 """ 给定一个整数数组 nums 和一个目标值 target, 请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。 示例: 给定 nums = [2, 7, 11, 15], target = 9 因为 nums[0] + nums[1] = 2 + 7 = 9 所以返回 [0, 1] """ #暴力解法 遍历每个元素 i 查看是否存在元素 j = target - i #这样时间复杂度就是O(n^2) class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: for i in r...
094c141d2842c0ad71281749ccf4440fd67a504a
narendra-ism/Python_tutorial_basic_
/Pyhton tutorial /93List_and_Function_strings_in_lists.py
268
4
4
# -*- coding: utf-8 -*- """ Created on Fri Mar 9 15:31:13 2018 @author: narendra """ n = ["Michael", "Lieberman"] # Add your function here def join_strings(words): result="" for item in words: result+=item return result print (join_strings(n))
c8a25104afa6e168ec2317cb9da649a0aeb7d662
python-advance/sem5-oop-Kseniaveh
/VarTask/forma 3.1.py
4,405
3.75
4
""" Вариативная самостоятельная работа 3.1 Разработка прототипа приложения “Регистрация на конференцию” на основе фрагмента технического задания с использованием ООП. Также в данном задании реализованы getter,setter,deleter для полей формы год рождения и email (задание - Инвариантное работа: 2.2) """ """ Импортируе...
baad13efaba3509893d368f8cf5531f90832e96e
love-adela/algorithm-wiki
/snippets/tree/Tree/sorted_list.py
1,478
3.8125
4
TABLE = [ ("alice", 1), ("bob", 2), ("lisa", 17), ("rachael", 34), ] ORDERED_LIST = [] # =========================================== def add(arr:list, new_value:str, lo=0, hi=None) -> list: new_arr = add(arr, new_value) if lo < 0: raise ValueError('lo have to be non-negative') if ...
d99e907a94fca5da099be377f042e128a10e556a
anthoniusadi/linear-regression-from-strach
/linreg.py
1,091
3.5
4
import numpy as np #!Y = a+bx #? a = (sum(y)*sum(x**2) - sum(x)*sum(x*y)) / ( n*sum(x**2)- (sum(x))**2 ) #? b = ( n*(sum(x*y)) - sum(x)*sum(y)) / ( n*(sum(x**2)) - (sum(x)**2) ) def regresor_fit(x,y): global fx n = len(x) denominator = ((n * (sum(x**2))) - (sum(x)**2)) a = ( ((np.sum(y) * n...
e0c127e5d817408712625f00db7f9e68e83ef839
alanvitalp/FUP
/código.py
541
3.8125
4
string = str(input("Digite o número identificador: ")) vetor = [] print (f"Número identificador: \"{string}\"") for i in range(0, 8): num = string[i] vetor.append(ord(num)) soma = sum(vetor) print ("Soma dos caracteres ASCII:", end=" ") for i in range(0, len(vetor)): if i == len(vetor)-1:...
97f3af71a1621bd4f65e654c47e3b644c6c3b6eb
johnboscor/codingpractice
/Math/factorial-triling-zeros.py
566
3.78125
4
#https://www.interviewbit.com/problems/trailing-zeros-in-factorial/ num=100 i = 5 zeros = 0 while True: rem = num // i i *= 5 zeros += rem if rem <= 0: break print(zeros) #method which fails for long numbers but works otherwise. ''' from math import factorial n=9938 def fact(n): if n > 0: ...
a7e0b524576dfd6a9ab9649f58050aaf78492d0c
JhonatanMarinS/Almacenamiento
/Python/Ejercicio profe 10.py
623
3.984375
4
#Ejercicio profe 10 """ Calcular las raíces de una ecuación cuadrática. Suponga que los datos ingresados no generan raíces imaginarias. """ from math import sqrt a=int(input("inserte el coeficiente de a: ")) b=int(input("inserte el coeficiente de b: ")) c=int(input("inserte el coeficiente de c: ")) if (...
5c8b3db7c87a66c8cbfd057a4420efc63016e82d
rounaksalim95/Final-Project-In-AI
/first_network.py
3,261
3.5625
4
# Get read the input data from MNIST from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets('MNIST_data', one_hot=True) import tensorflow as tf sess = tf.InteractiveSession() # Build placeholder nodes for input images and target output classes x = tf.placeholder(tf.float32, sh...
00fd19abb547411f5fc8cd398fffcbb6dab7c873
JohnRhaenys/escola_de_ferias
/DIA_01/introducao_python/aula/linguagem_python/00_input/string.py
104
3.59375
4
# Lendo uma string do usuario string = input('Insira uma string: ') print('String inserida:', string)
86c458cfecf254ccd52f1a3455ee2b907111620d
ChizeaU/python-programming
/unit-2/homework/hw-5.py
403
3.828125
4
temperature_readings = [25, 18, -5, 11, -3, -15, 8, -18, 6, 13] positive_mean = 0 negative_mean = 0 for n in temperature_readings: if n > 0: positive_mean = positive_mean + n/6 print (f"Average of positive readings {positive_mean}") for no in temperature_readings: if no < 0: negative_...
46f1079091965daa3eaecbdef7a6e071ea3a2ba4
kulkabhijeet/Python_Start
/guess1.py
680
4
4
guess = 10 our_num = 42 result = False for i in range(1,11): your_num = int(input('Enter the number: ')) if your_num == our_num: print('You are correct') result = True break ...
5f2f8ccf1b5a6d2441dbc13040b85e030f43490d
hungdoan888/algo_expert
/indexEqualsValue2.py
609
4.125
4
# -*- coding: utf-8 -*- """ Created on Sat Feb 6 15:01:04 2021 @author: hungd """ def indexEqualsValue(array): # Write your code here. return indexEqualsValueHelper(array) def indexEqualsValueHelper(array): # Write your code here. l = 0 r = len(array) - 1 while l <= r: m = (l + r) //...
a613437b871d92dac6daac895cb9521337e0483f
MingjunGuo/python__offer
/递归和循环/29_顺时针打印矩阵.py
1,395
3.953125
4
# -*- coding:utf-8 -*- class Solution: # matrix类型为二维列表,需要返回列表 def printMatrix(self, matrix): ''' 题目描述 输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字, 例如,如果输入如下4 X 4矩阵: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 则依次打印出数字1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10. ...
f0dc60e4121d40d4f01dbaeed2d2fc6704cedd79
NyangUk/Python
/day12/10799_re.py
164
3.546875
4
s =input() re =0 stack =[] for i in range(len(s)): if s[i] =='(': re+=1 elif s[i] ==')': if s[i-1] =='(': else: re +=1
21f9e00bdcd5c12a9c490bf5a847a890ed6bc46d
wodishenga/python
/pyBasic/raiseException.py
706
3.859375
4
#coding=utf-8 class ShortInputException(Exception): """自定义异常""" def __init__(self, length, atleast): self.length = length self.atleast = atleast def __str__(self): msg = "你输入的长度是"+str(self.length) +",但是长度至少要"+str(self.atleast) return msg def main(): try: string = input("请输入一个字符串:") if len(string) < ...
5e66d22c963a5bb66686a46055750db055fda6fc
DiamondGo/leetcode
/python/SearchA2DMatrixII.py
1,836
3.875
4
''' Created on 20160502 @author: Kenneth Tse Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties: Integers in each row are sorted in ascending from left to right. Integers in each column are sorted in ascending from top to bottom. For example, ...
ab7d07504782ed14059e14735a0473ba4f465d6f
Won-Andwon/RNN_Mood_QA
/model/memory_module.py
2,988
3.546875
4
# 如果熵增有逆过程,那一定是意识、理智、思维的产生和进化 # 宇宙绝大部分都是平衡的,熵增或许也有与之对应的过程,从信息量的变化的角度,或能推算产生智能需要耗费的“代价” # 大脑没有乘法器,激活、抑制应为“累加”的结果 # 大脑不求和 # 大脑的识别应该更为灵活和分布式 比如 n个神经元 每个神经元有m种激活状态 那么,可以产生m的n次方个编码 # 本代码模拟神经元(机器) “陈泳昌”作为一个词汇 激活负责此词汇的神经元 在大脑中 应该是 (i, j){第ni个神经元在mj状态} # 通过神经元之间的激活与抑制(递质传递) 以及阈值(接受器, acceptor)作用 确定下一时刻的神经整体网络状态(即联想、回忆等) # 本文 ...
174a2051d9f14e1ff52438c5096e88637a66320f
achernet/decorated
/src/decorated/test/decorators_test/conditional_test.py
1,046
3.53125
4
# -*- coding: utf-8 -*- from decorated.decorators.conditional import Conditional from unittest2.case import TestCase class ConditionalTest(TestCase): def test_string(self): @Conditional(condition='a == 1') def foo(a, b): return a self.assertEqual(1, foo(1, 1)) self.asser...
19f8515defc26ca58bc695cd8351bd8bbc999825
paty0504/nguyentienthanh-fundamental-c4e13
/ss1/turtle-ex.py
339
3.875
4
from turtle import * shape('turtle') speed(-1) color('yellow') begin_fill() #draw a square for i in range(4): forward(100) left(90) # #draw a circle circle(100) ### #draw a right triagle for i in range(3): forward(100) left(120) ## #draw a multicircle for i in range(12): circle(100) right(60) ## end...
39867b68fdf29e694c4a40904cfe3e8a33cd459a
belisariops/ConvNetwork
/NeuralLayer.py
791
3.578125
4
from abc import ABC, abstractmethod from scipy import exp class NeuralLayer(ABC): def __init__(self): self.outputFeatureMap = None self.kernels = [] self.deltas = [] self.inputFeatureMap = [] self.nextLayer = None self.previousLayer = None @abstractmethod de...
46755cbed0d7a9d568918f049c483569e7716089
GuilhermoCampos/Curso-Python3-curso-em-video
/PythonExercicios/Mundo 1/3_operadores_aritimeticos/ex014.py
147
3.9375
4
cel = float(input('Informe a temperatura em celsius: ')) fah = (cel * 9/5) + 32 print('{}ºC convertido em Fahrenheit é {}ºF.'.format(cel, fah))
416aacb713c66d1ffc95d0904efb4faefc6417ef
ElisaPiperni/second-homework
/Sorting/Insertion Sort - Part 1.py
301
3.703125
4
#Insertion Sort - Part 1 n = int(input()) arr = list(map(int, input().split())) value = arr[n-1] i = n-2 while (i >= 0) and (arr[i] > value): arr[i+1] = arr[i] i -= 1 s = ' '.join(str(i) for i in arr) print(s) arr[i+1] = value s = ' '.join(str(i) for i in arr) print(s)
61e4761edd241dd46339d15023fdb8309aff0d70
zhousir1234/zhourui
/python应用/PY05.py
564
3.53125
4
import pandas as pd df1=pd.DataFrame({'A':['A1','A2','A3','A4'], 'B':['B1','B2','B3','B4'], 'C': ['C1', 'C2', 'C3', 'C4'], 'D': ['D1', 'D2', 'D3', 'D4']},index=[1,2,3,4]) print(df1) df2=pd.DataFrame({'B':['B2','B4','B6','B8'], 'D': ['D2', 'D...
2836d6671301a44def5b0fb7d9ec828e8c305c7e
ryanwilkinss/Python-Crash-Course
/Do it Yourself/Chapter 3/3-8.py
1,638
4.8125
5
# Store the locations in a list. Make sure the list is not in alphabetical order. locations = ['himalaya', 'andes', 'tierra del fuego', 'labrador', 'guam'] # Print your list in its original order. Don’t worry about printing the list # neatly, just print it as a raw Python list. print("Original order:") print(location...
8503feae90e118844cbf868936aab5c58b9bdf38
mugabwa/zookeeper
/RockPaper/RockPaperGame.py
1,589
3.71875
4
# Write your code here import random outcome = ["rock", "paper", "scissors"] name = str(input("Enter your name: ")) print("Hello,", name) fl = open('rating.txt', 'r') score = 0 if fl.mode == 'r': content = fl.readlines() for x in content: if name in x: y = x.split(" ") score += ...
bae3435d23ac5b8c487ad4a0de6744ad7c83302f
abhi9835/python
/super_class_methods.py
1,101
4.25
4
"""super method""" class Person(): country = 'India' def __init__(self): print("Initialising Person..\n") def takeBredth(self): print('I am breathing...') def getLife(self): print('Love your life') class Employee(Person): company = 'Honda' def __init__(self...
f071a9ab87be6aa8e81397254854fcd3d5e2b64b
EzhilarasanME/guvi-task-
/stonepaper.py
876
3.90625
4
print('R for rock\nP for paper\nS for scissor\nFirst player to score 5 points wins.') p1=0 p2=0 while p1<5 or p2<5: x = input('Player 1 chooses: ') y = input('Player 2 chooses: ') if x==y: print('Draw') elif (x=='r' or x=='R') and (y=='p' or y=='P'): p2 = p2 + 1 ...
c7ea601d521e90dfb9817137b0b08d3be846d6c5
libinjungle/LeetCode_Python
/LearnedWhileCoding/22.py
566
3.53125
4
class solution(object): def generateParenthesis(self, n): ''' two recursions to update parenthesis got so far. :param n: :return: ''' def tracking(res, s, open, close, n): if len(s) == 2 * n: res.append(s) return if (open < n): tracking(res, s+'(', open+1, ...
c45e405f95b6ebabcc15943c95c5081f8fbb7ad4
HuipengXu/data-structure-algorithm
/reversed.py
471
3.796875
4
from single_linked_list import SingleLinkedList def reverse_single_linked(single_linked): prev = None node = single_linked.head while node: after = node._next node._next = prev prev = node node = after single_linked.head = prev return single_linked if __name__ == "_...
85cfc666c0db37e780723a7d4618e49d3b7f15c8
reshmaladi/Python
/1.Class/Language_Python-master/Language_Python-master/LC7_HW3_DictionaryArgumentsPassing.py
304
3.765625
4
def check(*b,**d): print(type(b)) print(type(d)) for x in b: print(x) for x in d: print(x,d[x]) print(b) print(d) x,y=eval(input("Enter two Numbers")) details = input("Enter in format of dictionary")# not considered as key value pair when passed in function print(details) check(x,y,details)
c29c6fb92336dab32e2f96c09bbcefe99a3b81b2
reyllama/leetcode
/Python/C122.py
969
4.125
4
""" 122. Best Time to Buy and Sell Stock II You are given an array prices where prices[i] is the price of a given stock on the ith day. Find the maximum profit you can achieve. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times). Note: You may not engage i...
980d6be756ee35f66e21dc288c6474e5cdfa791d
itsolutionscorp/AutoStyle-Clustering
/all_data/exercism_data/python/allergies/a170cdc064a942e18e2a229b7f827f51.py
499
3.6875
4
class Allergies(object): allergies = [ "eggs", "peanuts", "shellfish", "strawberries", "tomatoes", "chocolate", "pollen", "cats" ] def __init__(self, score): score = score & 0xff # obtain 8 least significant bits self.list = [ ...
f49c76770e46599f082ab800a7913bb351ded7ee
JVFray/python-projects
/quadratic.py
500
4.21875
4
print('Hello!!') print('Lets do some quadratic stuff') print('Welocme to the program! Please enter the value of A,B,C and X at the corresponding prompts') a = int(input('What is the value of A ')) b = int(input('What is the value of B ')) c = int(input('What is the value of C ')) x = int(input('What is the va...
2097d604f939e7b75d48042503398145642f9d6e
xiaket/exercism
/python/beer-song/beer_song.py
1,182
3.953125
4
#!/usr/bin/env python #encoding=utf8 HEADER = "{start} bottles of beer on the wall, {start} bottles of beer." TAIL = "Take one down and pass it around, {remains} bottles of beer on the wall." TWOTAIL = "Take one down and pass it around, 1 bottle of beer on the wall." ONEHEADER = "1 bottle of beer on the wall, 1 bott...
af5243a8dd268e261cf1e483e4ace89f3b802637
linzhiqidhs/NumberBases
/DecToBin.py
164
3.71875
4
def DecToBin(n): if n > 1: DecToBin(n//2) print(n % 2, end = '') integer = input("Enter an integer: ") dec = int(integer) DecToBin(dec)
7ab95eb122038f0b2fbaae610eb9c1b20cf9ab4b
IntroProgramacion-P-Oct20-Feb21/trabajofinal-1bim-rennypomx
/Taller7/Problema03.Py
319
3.921875
4
contador = 3 contadorElementos = 1 numero = 2 cadena = "" cadena = f " { cadena } { numero } " while ( contadorElementos <= 5 ): numero = numero + contador cadena = f " { cadena } { numero } " contador = contador + 2 contadorElementos = contadorElementos + 1 print ( f " { cadena } \ n " )
567aa357a9d929a483f7a96f6b013644e9379279
Errolyn/school-scripts
/scratch.py
1,002
3.921875
4
# def findValue(nums, size, value): # for index in range(size - 1): # if nums[index] == value: # return index # return -1 # def main(): # print(findValue([1,2,3,4,5,6,7], 6, 4)) # main() def output_answer(found, index): if found: print("That name was found ...
34c098090ebb34e34f50ca4fb38316ffcf3e50c4
felipovski/python-practice
/intro-data-science-python-coursera/curso2/semana4/ex1_ordenacao.py
268
3.640625
4
def ordenada(lista): fim = len(lista) for i in range(fim-1): posicao_do_menor = i for j in range(i+1, fim): if lista[j] < lista[posicao_do_menor]: return False posicao_do_menor = j return True
3a709166e31830bb407ac06f6552ee2862aa7a15
tangmaoguo/python
/learn_python/function/def_function.py
584
3.984375
4
#自定义函数 def my_abs(x): if not isinstance(x,(int,float)): raise TypeError('bad operand type') if x >= 0: return x else: return -x def nop(): return 1 pass print(my_abs('a')) print(my_abs(-99.43)) import math def move(x,y,step,angle): nx = x + step * math.cos(angle) ...
a4285a5e007e9b953f765d6ab0ecaeda8b7c9066
nkwarrior84/Programing-Solution
/32.py
364
4.625
5
''' Define a function which can print a dictionary where the keys are numbers between 1 and 3 (both included) and the values are square of keys. Hints: Use dict[key]=value pattern to put entry into a dictionary. Use ** operator to get power of a number. ''' def printDict(): d=dict() d[1]=1 d[2]=2**2 ...
13cc97dc3669cf8242bced6b41f19f277bb8bc8a
Sperthix/login-system
/main.py
1,563
3.59375
4
import sys def prihlasenie(): uspech = False f = open("login.txt", "r") meno = input("Zadajte prihlasovacie meno: ") meno = meno + "\n" heslo = input("Zadajte heslo: ") heslo = heslo + "\n" for x in f: # print("Aktualny zaznam je: " + x) # print("Zadane meno je: " + meno) ...
2f802f78d38f25ddbc44038ac0dd17ae12c53318
minavyoussef/jobs-coding-exercises
/Intercom-CustomerRecords/Services/FileLoader/StreamFileLoader.py
486
3.734375
4
class StreamFileLoader: """ Class StreamFileLoader represents reading file as stream if it is too big to be fitted in the memory. """ def __init__(self): self._input_file = None def load(self, input_file): self._input_file = input_file def read(self): if self._input_fi...
33d189ca9e320b099cb29a7a08836c53b24274b8
ViniciusSchutt/Python
/Varied codes/Check if n is a perfect number.py
688
3.890625
4
# 1 = Crie uma função que receba 1 número inteiro como parâmetro e verifique se ele é # perfeito, ou seja, se a soma dos seus divisores exceto ele mesmo dá o próprio número, # a mensagem se o número é perfeito ou não deve ser mostrada no programa principal n = int(input("Enter any int number: ")) sum = 0 # esse parâ...
9f9d60db314a8eb7be2dc918a8c3a4e3901ea7c2
charlescheung3/Intro-HW
/Charles Cheung PS11.py
424
4.3125
4
#Name: Charles Cheung #Email: charles.cheung24@myhunter.cuny.edu #Date: February 06, 2020 #This program asks the user for a noun and two verbs. Using the words the user entered, print out a new sentence of the form: If it VERB1 like a NOUN and VERB2 like a NOUN, it probably is a NOUN. noun1 = input("") verb1 = input("...
3891ae74c2fc01699769e779d8bbcc54d9aac4f1
no52/classifymarks
/classify/classify.py
933
3.734375
4
#!/usr/bin/env python3 import sys def getData(f): results = [] for line in f: number, mark = line.strip().split() results.append( [number, int(mark)] ) return results def thoseInRange(data, lower, upper): students = [] for [number, mark] in data: if lower <= mark < upper...
f2ce2ad7ad3703bb800c7fc2dfd79b6bab76d491
thedern/algorithms
/recursion/turtle_example.py
835
4.53125
5
import turtle max_length = 250 increment = 10 def draw_spiral(a_turtle, line_length): """ recursive call example: run the turtle in a spiral until the max line length is reached :param a_turtle: turtle object "charlie" :type a_turtle: object :param line_length: length of line to draw :t...
ff7507d6f00f06456e1bb64fd96a78573c6ce646
aminuolawale/Data-Structures-and-Algorithms-in-Python-exercises
/Chapter 1 - Python primer/reinforcement/R-1.4__squaresSum__.py
272
4.28125
4
# Write a short Python function that takes a positive integer n and returns the sum of the squares of # all the positive integers smaller than n. def squares_sum(n): sum = 0 for number in range(0,n): sum+=number**2 return sum print(squares_sum(3))
1beeeb392484ac1b951b5fa1900d5eff33b56772
drewbrew/advent-of-code-2019
/day24.py
9,741
3.71875
4
"""Day 24: Game of life""" TEST_INPUT = """....# #..#. #..## ..#.. #....""".split('\n') def parse_input(lines: list, part_two: bool = False) -> set: grid = set() for y, line in enumerate(lines): for x, char in enumerate(line): if char == '#': if part_two: ...
19cc516ff18694c005dc0201ef293ffe1c887232
SWIN91/codewarspython
/codewarspython/usdtocny.py
586
4.21875
4
# Create a function that converts US dollars (USD) to Chinese Yuan (CNY) . # The input is the amount of USD as an integer, and the output should be a string that # states the amount of Yuan followed by 'Chinese Yuan' # For Example: # usdcny(15) => '101.25 Chinese Yuan' # usdcny(465) => '3138.75 Chinese Yuan' # ...
a474df052cc87eadd7fe6c6b3dacdbbd86f90e2c
dstark85/mitPython
/midterm/deep_reverse_open.py
248
3.984375
4
def deep_reverse(L): ''' assumes L is a list of lists whose elements are ints Mutates L such that it reverses its elements and also reverses the order of the ints in every element of L. It does not return anything ''' pass
dc780531d256e999e92f3bde232151f5541f2e34
Coalin/Daily-LeetCode-Exercise
/381_Insert-Delete-Getrandom-o1-Duplicates-Allowed.py
1,843
3.921875
4
import random import math class RandomizedCollection: def __init__(self): """ Initialize your data structure here. """ self.idx = dict() self.nums = [] def insert(self, val: int) -> bool: """ Inserts a value to the collection. Returns true if the collec...
f153ce39788836f9f710dc03417d3f65e55124ae
tongjintao/project-euler
/util.py
2,488
4.03125
4
from math import sqrt def gcd(a, b): """ Compute the greatest common divisor of a and b. """ while b != 0: (a, b) = (b, a % b) return a def lcm(a, b): """ Compute the least common multiple of a and b. """ return a // gcd(a, b) * b def prime_sieve(n): """ Retur...
a046f4c793e87ff49346d79b30dfe030ed5b166c
ysy-law/python
/oop.py
3,349
3.765625
4
''' 面向过程的程序设计把计算机程序视为一系列的命令集合,即一组函数的顺序执行。为了简化程序设计,面向过程把函数继续切分为子函数,即把大块函数通过切割成小块函数来降低系统的复杂度。 而面向对象的程序设计把计算机程序视为一组对象的集合,而每个对象都可以接收其他对象发过来的消息,并处理这些消息,计算机程序的执行就是一系列消息在各个对象之间传递。 ''' ''' 和普通的函数相比,在类中定义的函数只有一点不同,就是第一个参数永远是实例变量self,并且,调用时,不用传递该参数。除此之外,类的方法和普通函数没有什么区别,所以,你仍然可以用默认参数、可变参数、关键字参数和命名关键字参数。 ''' class Student(object)...
0c2519b329fc42b60dfc8e7f955050e8452518af
M45t3rJ4ck/Py-Code
/HD - SD/Task 5/example.py
9,289
4.4375
4
#Welcome to the example file for task '4.5'. #************* HELP ***************** # REMEMBER THAT YOU IF YOU EVER NEED ANY HELP AT ALL, EMAIL US ON STUDENTS@HYPERIONDEV.COM # Visit www.rmoola.com/advice.html for all the ways you can get free help! #===== Functions in Python===== #Recall from the previous task: # A...
7ab4d5a6ec326abafe5e6e6c4eeab5533df86b50
sarthakbansalgit/basic-python-
/binarysearhitretve.py
421
3.75
4
def bsearch(n,key): low = 0 mid = 0 high = len(n)-1 while low <= high: mid = (low+high)//2 if n[mid]< key: low = mid+1 elif n[mid]> key: high = mid-1 else: return mid return -1 n = [1,2,3,4,5,6,7,8,9] key = 7 result = bsearch(n,key...
6533c176fd7daec5bbcb2d24e8b91cdf3c6e6bea
zhoupengzu/PythonPractice
/Practice/practice7.py
853
3.96875
4
# 变量作用域 # python里面没有块级作用域 # 只有函数才能形成一个作用域 # 作用域都是相对来说的 # global只能修饰全局变量,对于嵌套不好使 def scope(): # c = c +1 #这里不能修改全局变量 global c # 要使用全局变量,则需要提前使用global修饰,然后才能修改其值 c = c + 1 for x in range(1, 5, 2): a = 'a' for y in range(4, 1, -2): b = 'b' #正常来说,下面的应该是打印不出来的,但实际情况是它打印出...
bfd2e52063ae5e6ad75a54a26f744b4a7739c89e
Raspeball/Project-Euler
/py_source/projecteuler12.py
568
3.75
4
import numpy as np def trianglenum(n): #computes the n-th triangle number trinum = (n*(n+1))/2 return trinum def divnum(x): d = 0 largeds = [] for i in xrange(1,int((np.sqrt(x) + 1))): if x % i == 0: d = d + 1 if i*i != x: largeds.append((x / i)) else: continue totd = d + len(largeds) return...
27c39c5df47a53856a411d14bbaad00e0cda44b4
avaiyang/Linkedlist
/linkedlist.py
2,160
4.375
4
############################################### # Program to create a linked list, and insert # # at different positions. # # # # # ############################################## class Node(): #initialising the node def __init__(self, data): self.data = data s...
a75790c4bacd9b7a05462416d6e9391193e10e16
cosmolgj/vs_my_tiny_project
/crawler.py
618
3.625
4
from urllib.request import urlopen from bs4 import BeautifulSoup html = urlopen("http://www.naver.com") # html = urlopen("https://www.python.org/about") # html = urlopen("https://book.naver.com/bestsell/bestseller_list.nhn") #bsObject = BeautifulSoup(html, "html.parser") # print(bsObject.head.find("meta", {"name":"de...
d810d75d532b0f1cac4a1802d4bd70c439d9b41d
yankee-kate/Coursera
/week4/min4.py
166
3.546875
4
def min4(a, b, c, d): min1 = min(a, b) min2 = min(c, d) return min(min1, min2) a = input() b = input() c = input() d = input() print(min4(a, b, c, d))
b71a006d8d7b6be3a95bc3890004e2ae84824479
mpatriak/Python-GUI-for-Games
/rockpaperscissors.py
3,470
4.28125
4
#!/usr/bin/env python2 # Extra modules used from Tkinter import * from ttk import * import random def gui(): # Set each move to a specific number # Once a selection is made by the player, # it will be equated to that specific variable. rock = 1 paper = 2 scissors = 3 # Text represen...
638160a663554552e962f17195ce6aa947f7597e
arshad115/leetcode-august-2020
/5-add-and-search-word-data-structure-design.py
1,709
4.09375
4
# ------------------------------------------------------- # Add and Search Word - Data structure design - https://leetcode.com/explore/challenge/card/august-leetcoding-challenge/549/week-1-august-1st-august-7th/3413/ # ------------------------------------------------------- # Author: Arshad Mehmood # Github: https://gi...
170f77977c9e36f84fb41e761f64fed46331c4c7
NeroCube/leetcode-python-practice
/medium20/singleNonDuplicate.py
463
3.59375
4
''' 540. Single Element in a Sorted Array [題目] 每個數都會出現兩次,找出唯一一個單獨的數 [思考] 每個數都會出現兩次 希望自己可以消滅自己 邏輯異或 ''' class Solution(object): def singleNonDuplicate(self, nums): """ :type nums: List[int] :rtype: int """ result = 0 for index in range(len(nums)): resu...
64c5bd791accfd7c9b2b9a2ae50248cb3070d78b
dlingerfelt/DSC510Summer2020
/HOLDMAN_DSC510/Assignment 3.1.py
1,325
4.625
5
#DSC 510 #Week 3 #Programming Assignment 3.1 #Sarah Holdman #06/21/2020 #This program will do the following: #Display a welcome message #Get the company name #Give the number of feet of cable #Evaluate the cost #Display the calculated information #Retrieve the company name company = input('Welcome! Which company are ...
196b59178da6539a65c18400791af755ac3441b6
zhong950419/Leetcode
/778. Swim in Rising Water.py
1,955
3.5625
4
# 这题目难度很高,是说一个NxN矩阵有深度,然后下雨了必须填满才能游过去,每个时间帧可以游无限的距离 #所以就变成了 m时间 0,0 到 n,n有一条连接的通路 m最小是多少 # 因为这道题说了每一个element都是unique的,所以可以通过二分来进一步缩短时间 # 主要套路还是BFS, 直接 class Solution(object): def swimInWater(self, grid): """ :type grid: List[List[int]] :rtype: int """ width = len(grid) ...
e224d4691624e036c01a9f82ce127b6dcde9b38a
yfeng2018/IntroPython2016a
/students/MikeSchincariol/session3/rot13.py
1,653
3.796875
4
#!/usr/bin/python3 def rot13(text): # Create the translations tables to feed to str.translate() lc_first_half = "abcdefghijklm" lc_second_half = "nopqrstuvwxyz" lc_translate = str.maketrans(lc_first_half + lc_second_half, lc_second_half + lc_first_half) uc_first_...
dab2014ff412661b3c2b1d7c1cc0f7d53be4842f
Adasumizox/ProgrammingChallenges
/codewars/Python/8 kyu/AddLength/add_length_test.py
1,427
3.5625
4
from add_length import add_length import unittest class TestAddLength(unittest.TestCase): def test(self): self.assertEqual(add_length('apple ban'),["apple 5", "ban 3"]) self.assertEqual(add_length('you will win'),["you 3", "will 4", "win 3"]) self.assertEqual(add_length('you'),["you 3"]...
02662b1ff58b2603fc7dd2110a339f3a498e692e
Bonnieliuliu/LeetCodePlayGround
/Companies/Hulu/Sep_10_p4.py
650
3.578125
4
# -*- coding:utf-8 -*- """ author:Bonnieliuliu email:fangyuanliu@pku.edu.cn file: Sep_10_p4.py time: 2018/9/10 18:52 """ class Solution(object): def Count(self, m, n): if m == 2 and n == 2: return 3 if m == 3 and n == 2: return 7 if m == 2 and n == 3: ret...
fbea8e1951b8b2fb7b557b044fb420a848be3d0e
M074MED/Age_Calculator
/Age_Calculator.py
1,141
4.0625
4
from tkinter import * from tkinter import messagebox age_calc = Tk(className=" Age Calculator By M074MED") # or age_calc.title("Age Calculator") age_calc.geometry("400x200") the_age = Label(age_calc, text="Enter Your Age", height=2, font=("Arial", 20), bg="black", fg="white") the_age.pack() age = StringVar...
71590c08a2441cd523a1c24d1905ae0fd33db063
laurent-dragoni/lascon_project
/hexagonal_network.py
13,639
3.734375
4
#!/usr/bin/env python2 # -*- coding: utf-8 -*- import numpy as np import matplotlib.pyplot as pl def in_hexagon(x, y, Cx=0.0, Cy=0.0, R=1.0): """ Returns true if the point of coordinates (x,y) is in the hexagon centered at (Cx,Cy) and of radius R """ V3 = np.sqrt(3) # (x,y) has to v...
5a705604836b7af383458e55c4d615fea91533a3
ansh0l/Euler
/010/summation_of_primes.py
433
3.6875
4
import math NUMBER = 2000000 prime_numbers = [2] candidate = 3 while candidate < NUMBER: candidature_holds = True for prime in prime_numbers: if candidate % prime == 0: candidature_holds = False break elif prime > math.floor(math.sqrt(candidate) + 1): break...
4c6b27cd693bb19f30d885c24c6ab59840a0dd55
raulterraferrao/Judge-Online
/HackerEarth/Life, the Universe, and Everything.py
235
3.75
4
#https://www.hackerearth.com/practice/basic-programming/input-output/basics-of-input-output/practice-problems/algorithm/life-the-universe-and-everything/ while True: entry = int(input()) if entry == 42: break; print(entry)
df679f4017418bbf56e9e04c32c8391374928a65
kavener/Spider
/5/Hike_MongoDB.py
481
3.625
4
import pymongo client = pymongo.MongoClient(host='localhost', port=27017) db = client.test collection = db.students student1 = { 'id': '20170101', 'name': 'Jordan', 'age': 20, 'gender': 'male' } student2 = { 'id': '20170102', 'name': 'Mary', 'age': 21, 'gender': 'female' } # result ...
292dee0c705a7325e0349b1d21d1aefe35a07ff9
Rodrun/weatherguess
/test_collection.py
1,337
3.546875
4
import unittest import requests from collection import Collection class TestCollection(unittest.TestCase): def setUp(self): # Get the sample JSON data self.data = requests.get("http://samples.openweathermap.org/data/2.5/weather?zip=94040,us&appid=b6907d289e10d714a6e88b30761fae22").json() ...
5b2b2f44a07e74aaf08ab54fb943949b52650016
velpuri1035/My-Solutions
/heap_tree/minimum_awerage_waiting_time.py
2,186
4.25
4
# Source: # https://www.hackerrank.com/challenges/minimum-average-waiting-time/problem # Question: # Orders in pizza counter will come at different point of time and differnt type of pizza takes different amount of time. # Process the order such that average waiting time of customer is less # Solution: # Non-premptiv...
ea8febc93569585cf551613d78da307bc2117bef
aparna-narasimhan/python_examples
/Binary Trees/sum_of_kth_smallest_bst.py
567
3.796875
4
sum=0 count=0 def find_sum_of_kth_smallest(root,k): if(root == None): return global count global sum find_sum_of_kth_smallest(root.left,k) count += 1 #print(root.data) if(count<=3): sum = sum + root.data find_sum_of_kth_smallest(root.right,k) return(sum) class Node: def __init__(self,data): ...