blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
545k
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
545k
c389a6e023cbaa3c3236af9621f656264354e90e
PashaBrychuk/training
/codingbat_centered_average.py
412
3.703125
4
def centered_average(nums): s = 0 b =[] for i in range(len(nums)): if nums[i] not in b: b.append(nums[i]) smallest = b[0] biggest = b[0] for i in range(len(b)): if b[i]<smallest: small = b[i] if b[i]>biggest: biggest = b[i] b.remove(biggest) b.remove(smallest) for i in b...
2c3914cfd731034edbc29e860ade03e90decd64e
gramanicu/Diode
/Diode.py
1,078
3.59375
4
# Copyright 2019 Grama Nicolae & Enache Liviu import matplotlib.pyplot as plt import numpy as np # Specific Values I0 = 10**-9 n = 2 # Voltage range vstart = 0.0 vstop = 0.91 vstep = 0.01 Vd = np.arange(vstart, vstop, vstep) # Creates the voltages array # A function to compute the result of the Shockley Formula d...
c72f07976c3d40c88fbef5a39d3bdab8f0a5f202
divyashree-dal/PythonExercises
/Exercise22.py
673
4.625
5
'''Question 54 Define a class named Shape and its subclass Square. The Square class has an init function which takes a length as argument. Both classes have a area function which can print the area of the shape where Shape's area is 0 by default. Hints: To override a method in super class, we can define a method with ...
c75cb25ef545a9e8edbcf122aeb5ec34b9cb418d
divyashree-dal/PythonExercises
/Exercise12.py
492
3.90625
4
'''Question: Write a program that computes the value of a+aa+aaa+aaaa with a given digit as the value of a. Suppose the following input is supplied to the program: 9 Then, the output should be: 11106 Hints: In case of input data being supplied to the question, it should be assumed to be a console input.''' import mat...
56d6989fde04fd21a235b54bebef3ca4a135da80
EvanKiser/Linear-Algebra
/vector.py
9,191
3.859375
4
import sys import math class Vector(object): def __init__(self, coordinates): try: if not coordinates: raise ValueError self.coordinates = tuple(coordinates) self.dimension = len(coordinates) except ValueError: raise ValueError('The co...
1d43db04cd4b373e7c07ab9fefef9a6d4094f019
deepakmethalayil/PythonCrash
/name_cases.py
507
3.890625
4
name= "eric" message= f"Hello {name.title()} , would you like to learn some Python today?", print(message) Person_Name = "Deepak Methalayil" print(Person_Name.lower()) print(Person_Name.upper()) print(Person_Name.title()) # excercise 2.5 print("Albert Einstein once said, “A person who never made a mistake never tri...
8fd1d34b6a98d4f171c8b7bd138f892a3861800e
deepakmethalayil/PythonCrash
/list_study.py
785
4.125
4
members = ['uthay', 'prsanna', 'karthick'] members_master = members print(members) # print the entire list print(members[0]) # print list items one by one print(members[1]) print(members[2]) msg = "Hello!" print(f"{msg},{members[0].title()}") print(f"{msg},{members[1].title()}") print(f"{msg},{members[2].title()}") #...
f3c9bcb5caef26c16c6071a9cc469a60a709275d
the-pawns/test
/hantower.py
269
3.90625
4
#hantower count=0 def hanoi(n,r,l,m): global count if n==1 : print('{}:{}->{}'.format(1,r,l,)) count+=1 else : hanoi(n-1,r,m,l) print('{}:{}->{}'.format(n,r,l)) count+=1 hanoi(n-1,m,l,r) hanoi(30,'a','b','c')
ddbc5954c2f8c7c975504eff8ef2d21d4a047b06
the-pawns/test
/DayDayUp.py
286
3.640625
4
#DayDayUp def upup(df): day=1 for i in range(365): if i%7 in[6,0]: day=day*(1-0.01) else: day=day*(1+df) return day dayfactor=0.01 while upup(dayfactor)<37.78: dayfactor+=0.001 print('工作日的努力参数是:{:.3f}'.format(dayfactor))
8d8136e1cd8e2208e9a9a58190ed0f7bcf9b2400
arrudolph11/arrud-local
/HW3.py
3,390
4.21875
4
# Your name: Amanda Rudolph # Your student id: 87253704 # Your email: arrud@umich.edu # List who you have worked with on this homework: # import the random module for use in this program import random # Create the class Magic_8 class Magic_8: def __init__(self, answer_list): self.answer_lis...
343755a8ff4184aaea59fe5237044b33a5387a34
krprabhatSingh/setone
/fundamentaldatatype.py
3,256
3.984375
4
"""Data Type : """ """ In python data type represent the type of data present inside a variable In python we are not required to specify the type explicitly. Based on value provided, the type will be assigned automatically, hence python is dynamically typed language. """ """ Python contain the following inbui...
7a10a03b52a9dc78341de9c14aff86ee05645c31
ahtrotta/HarvardX-CS50-Solutions
/pset6/hello.py
189
3.71875
4
# import the get_string function from the cs50 library from cs50 import get_string # prompt user for their name and print the response print("hello, " + get_string("What is your name?\n"))
294c3433b72d51db34599fec2bf0867361a7fe8f
Nekonoha/AtCoder
/abc058/abc58b.py
141
3.671875
4
import itertools O = list(input()) E = list(input()) print("".join(itertools.chain(*zip(O, E))) + (O[-1] if len(O) is not len(E) else ""))
cf8681968737810bff921cebe1241507b1dc3c12
Nekonoha/AtCoder
/abc038/abc38b.py
184
3.53125
4
HW1 = set(map(int, input().split())) HW2 = set(map(int, input().split())) res_len = len(HW1) + len(HW2) res = HW1 | HW2 if res_len is len(res): print("NO") else: print("YES")
d26d2a0ef2074fa27c3528f8a5e487f5def5b307
PlumpMath/DesignPatterns-436
/Decorator/decorator.py
480
3.828125
4
from functools import wraps def make_doomtag(function): @wraps(function) # Inner function def decorator(): # Take return value of the function being decorator returnValue = function() # Add new functionality to the function being decorator return "<doom>" + returnValue + "</doom>" return decorator # Ap...
0e9fd6cd4deafab1ca8f6fcdba4a6a8a0248f64e
ttp2542/UntilYouScript
/RandomWeapons.py
1,331
3.6875
4
import random weaponLst = ["Engraved Arming Sword", "Rokari Keenblade", "Heartsplitter", "Vestal's Wrath", "Spellsword's Charm", "Duelist's Edge", "Mistcutter", "Gemini Stranded", "Gemini Esper", "Ritual Dagger", "High Arcanist's Blade", "Knight-blooded Crest"] random.shuffle(weaponLst) usedWeapons = set() def getWea...
94e1bc4fb1eaaa1171f20111eb957e9a2f48a229
eryndi/Learning-Python
/ZCasino/ZCasino.py
1,387
3.96875
4
from random import randrange from math import ceil def valid_num(num): try: return int(num) except ValueError: print(num, "is not a whole number. Try again.") return False def valid_bet(bet): try: bet = valid_num(bet) except ValueError: return False if be...
0c885c721e116d2ed482bf53bae8590df0db711e
gauvansantiago/Practicals
/Prac_02/exceptions_demo.py
1,020
4.46875
4
# Gauvan Santiago Prac_02 Task_04 exceptions_demo try: # asks to input numerator and denominator numerator = int(input("Enter the numerator: ")) denominator = int(input("Enter the denominator: ")) # while loop will prevent ZeroDivisionError and ask for a valid denominator while denominator == 0: ...
0e3c410f09b8f0a1036ff12a6f5417bf138c7326
sicoyle/Research
/dynamic_fib.py
221
3.640625
4
#!/usr/bin/python def Fib(n): if n < 2: return n fibPrev = 1 fib = 1 for num in xrange(2,n): fibPrev, fib = fib, fib + fibPrev return fib Fib(40)
272ddfc8a1209e937ebbfddea4605defc4a5f327
ljm9748/Algorithm_ProblemSolving
/practice/0217_practice/1_이정민.py
591
3.859375
4
# string 입력 input_string= input() answer='' # 뒤에서부터 읽어서 집어넣기 for char in range(len(input_string)-1,-1,-1): answer += input_string[char] # slice notation이용 slice_notation=input_string[::-1] # reverse이용 my_reverse=''.join(reversed(input_string)) # swap 이용하기 list_input_string=list(input_string) for char in range(...
41ccb20409b83f80959a344602f32d0ab0dd7957
ljm9748/Algorithm_ProblemSolving
/practice/0406_practice/SWEA_5176_이진탐색_이정민.py
367
3.5625
4
# 배열에 트리만들기 def make(idx): global number if idx<=N: make(2*idx) # 왼쪽 서브트리 tree[idx]=number number+=1 make(2*idx+1) # 오른쪽 서브트리 for tc in range(int(input())): N=int(input()) tree=[0]*(N+1) number=1 make(1) print('#{} {} {}'.format(tc+1, tree[1], tree[N/...
41bbd6db515bee85e88047635cf01e7125b6e908
ljm9748/Algorithm_ProblemSolving
/practice/0405_practice/SWEA_1231_중위순회_이정민.py
860
3.625
4
def infix(root): # 중위순회 if tree[root][0] != -1: infix(tree[root][0]) print(word[root],end='') if tree[root][1] != -1: infix(tree[root][1]) for tc in range(10): V=int(input()) tree=[[-1,-1] for _ in range(V+1)] # 노드관계 word=['']*(V+1) # 알파벳 저장 for i i...
b1a753ae41e0f414b732a2ecbb0cf4818446b2bd
ljm9748/Algorithm_ProblemSolving
/practice/0303_practice/연습문제1_큐구현_이정민.py
1,865
4.03125
4
# 리스트큐 class ListQueue: def __init__(self): self.queue=[] def enQueue(self,A): self.queue.append(A) def deQueue(self): return self.queue.pop(0) def isEmpty(self): if len(self.queue)==0: return True else: return False def Qpeek(self)...
2218eea70c2e1e4d5366fbf697e6a6921902323d
ljm9748/Algorithm_ProblemSolving
/practice/0223_practice/SWEA_1234_비밀번호_이정민.py
514
3.53125
4
T=10 for tc in range(T): testcase, input_string=input().split() my_stack=[] for char in input_string: # 입력만큼 순회 if len(my_stack) == 0: # stack이 비었다면 my_stack.append(char) elif my_stack[-1] == char: # stack 마지막과 현재 char가 같다면 my_stack.pop() else: # 둘다아니라면...
1fc92f21f21485f503dd835e3d85415f33b28109
SKTPausanias/machine_learning_bootcamp-42AI
/day00/ex07/prediction.py
890
3.890625
4
import numpy as np from tools import add_intercept def predict_(x, theta) -> np.ndarray: """Computes the vector of prediction y_hat from two non-empty numpy.ndarray. Args: x: has to be an numpy.ndarray, a vector of dimension m * 1. theta: has to be an numpy.ndarray, a vector of dimension 2 * 1. Returns: y_hat a...
72063a86af726a71014064536a49fd091e46bc31
SKTPausanias/machine_learning_bootcamp-42AI
/day02/ex06/gradient.py
1,000
3.984375
4
import numpy as np from prediction import predict_ from tools import add_intercept def gradient(x, y, theta): """Computes a gradient vector from three non-empty numpy.ndarray, without any for-loop. The 􏰀→ three arrays must have the compatible dimensions. Args: x: has to be an numpy.ndarray, a matrix of dimension ...
372dbe969529bcf290b19676e3f1ffdd856919ed
SKTPausanias/machine_learning_bootcamp-42AI
/day01/ex03/gradient.py
1,284
4.09375
4
import numpy as np from prediction import predict_ def simple_gradient(x, y, theta): """Computes a gradient vector from three non-empty numpy.ndarray, without any for-loop. The 􏰀→ three arrays must have compatible dimensions. Args: x: has to be an numpy.ndarray, a vector of dimension m * 1. y: has to be an numpy....
40373887744c72495d7a8f27af36dc95e2644845
SKTPausanias/machine_learning_bootcamp-42AI
/day03/ex12/confusion_matrix.py
1,332
3.875
4
import numpy as np def confusion_matrix_(y_true, y_hat, labels=None): """ Compute confusion matrix to evaluate the accuracy of a classification. Args: y_true:a numpy.ndarray for the correct labels y_hat:a numpy.ndarray for the predicted labels labels: optional, a list of labels to index the matrix. This may be u...
835795ce2c4900d5bb69a7837ea311ef2ea98825
SKTPausanias/machine_learning_bootcamp-42AI
/day01/ex05/fit.py
1,334
3.875
4
import numpy as np from prediction import predict_ from tools import add_intercept from vec_gradient import gradient def fit_(x, y, theta, alpha, max_iter): """ Description: Fits the model to the training dataset contained in x and y. Args: x: has to be a numpy.ndarray, a vector of dimension m * 1: (number of tra...
4ed3fa7f42ff7e18e2109ccc526bf111449b72cd
fkebur/ASGToPython
/Chapter3/projectile.py
1,437
3.90625
4
# -*- coding: utf-8 -*- # projectile.py # Python 3.6 """ Author: Kebur Fantahun Created: Sat Aug 11 01:42:20 2018 Modified: Sat Aug 11 01:42:20 2018 Description: copy of Kinders code from python book ================================================== Calculate how long an object is in the air when thrown from a spec...
c6bfa6d8025b37eb3ea1c06a69f71de67d084af3
fkebur/ASGToPython
/Chapter4/PlotExamples/MultiplePlots.py
341
3.578125
4
# -*- coding: utf-8 -*- # Python 3.6 # MultiplePlots.py """ Author: Kebur Fantahun Created: Tue Aug 14 16:59:31 2018 Modified: Tue Aug 14 16:59:31 2018 Description: plot two lines with customization(embellishment) """ import numpy as np, matplotlib.pyplot as plt x = np.linspace(0,1,51) y1 = np.exp(x) y2 = x**2 plt.p...
07555fa2fc2c5c0b896456f7f494fe075935910f
Jaysparkexel/Two-Pointers-1
/Problem1.py
1,685
3.828125
4
# Time Complexity : O(n) # Space Complexity : O(1) (If we don't consider returned list) # Did this code successfully run on Leetcode : Yes # Three line explanation of solution in plain english: # - Take two pointer one for 0 at start and one for 2 at the end. Take 3rd index for current element that runs till k. # - If...
99d9bba4b90cb496b0a8d13bf8bf91ce5c6ec7f8
Katylub/Katylub-Dona-Problems-Set-2019
/Exercise 1/sumupto(1).py
331
4.03125
4
# Katylub, Exercise 1 # Write a program that asks the user to input any positive integer and outputs the # sum of all numbers between one and that number. #Use positive number n = int(input("Input a positive number: ")) #I have found the information doing research - www.w3resource.com sum_num = (n * (n + 1)) / 2 prin...
be66d8122bed208253f122af5dbd90d4b10f76cf
jonathanan/supermarket
/app.py
1,846
3.703125
4
#!/usr/bin/env python3 import supermarket_register import json import os def print_menu(): print('1. List products') print('2. Add a product') print('3. Remove a product') print('4. Calculate total of products') print('5. Save and exit') if __name__ == '__main__': # Read config and create Sup...
d10583315e0018a81b31f26e8dce41b4deb746cb
RodrigoExposito/deep_learning_A_Z
/Volume 1 - Supervised Deep Learning/Part 1 - Artificial Neural Networks (ANN)/Section 4 - Building an ANN/ann.py
5,014
3.546875
4
# Artificial Neural Network # Installing Theano # pip install --upgrade --no-deps git+git://github.com/Theano/Theano.git # Installing Tensorflow # pip install tensorflow # Installing Keras # pip install --upgrade keras # Part 1 - Data Preprocessing # Importing the libraries import numpy as np import matplotlib.pyp...
e97412f695bfe04968240b2e60362559a621220a
intertag/CodeCamp2021-Intro
/SongGenerator.py
523
3.78125
4
def print_spam_line(): line = "spam spam spam spam" line_in_upper = make_uppercase(line) print(line_in_upper) def print_spam_line_with_words(word_1, word_2): print(f"{word_1} SPAM, {word_2} SPAM") def make_uppercase(some_string): string_in_upper = some_string.upper() return string_in_upper ...
c0e65eb038c91897b6cb206b7bb02446938cc0ee
jakecren/Keyboard-Kombat
/titleScene.py
3,537
3.765625
4
""" Imports """ import pygame from functionality import button """ Set Global Variables """ titleImg = pygame.image.load("images/titleScreen.png") white = (255, 255, 255) black = (0, 0, 0) """ Class-Start """ class titleScene: """ Title/Menu Scene Methods: runScene(gameDisplay, clock, master...
a26da98cd7f927a76810f2b9f97a60e896cbd5ee
Anjalibhardwaj1/GuessingGame
/GuessingGame.py
2,370
4.28125
4
#December 30 2020 #Guessing Game #This program will pick a random number from 1 to 100, and #it will ask the user to guess the number. from random import randint #Welcome Message and Rules print("\n---------------------- Guessing Game ------------------------------") print("Welcome!") print("In this game I wi...
4f6a63656ac3f156cebce81bad9d503b57411327
rahulyerva/Python_ICP
/ICP-2/Week-2_Python1.py
224
3.703125
4
items = [] a = int(input("enter first value")) b = int(input("enter second value")) for i in range(a, b): s = str(i) if (int(s[0])%2!=0) and (int(s[1])%2!=0) and (int(s[2])%2!=0): items.append(s) print(items)
df3d979d805b78466275b8b88ce80b8755689554
Microstrong0305/coding_interviews
/66.构建乘积数组/66.构建乘积数组.py
350
3.6875
4
# -*- coding:utf-8 -*- class Solution: def multiply(self, A): # write code here B = [1]*len(A) front = 1 tail = 1 for i in range(0,len(A)): if i > 0: front *= A[i-1] tail *= A[len(A)-i] B[i] *= front B[len(A)...
dc38d56a26d7d71865bcdd52c1b8029be2327c17
Microstrong0305/coding_interviews
/34.二叉树中和为某一值的路径/34.二叉树中和为某一值的路径.py
948
3.71875
4
# -*- coding:utf-8 -*- # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: # 返回二维列表,内部每个列表表示找到的路径 def FindPath(self, root, expectNumber): # write code here if root is None: return [] self...
698fe0d59bb083a6cad4454d44a1e12d0fe27877
Microstrong0305/coding_interviews
/33.二叉搜索树的后序遍历序列/33.二叉搜索树的后序遍历序列.py
596
3.6875
4
# -*- coding:utf-8 -*- class Solution: def VerifySquenceOfBST(self, sequence): # write code here if len(sequence) == 0: return False return self.check(sequence,0,len(sequence)-1) def check(self,arr,start,end): if start>=end: return True root = arr[...
efe74b32ed76cb91a932349ff2cca847f46bc646
Microstrong0305/coding_interviews
/57.和为S的连续正数序列/57.和为S的连续正数序列(bin search).py
888
3.671875
4
# -*- coding:utf-8 -*- class Solution: def FindContinuousSequence(self, tsum): # write code herewww def binsearch(arr,target): low = 0 high = len(arr) - 1 while(low <= high): mid = low + (high-low)//2 if arr[mid] == target: ...
6bf4b1ffab890c2ebadf78f5e1baa083f33f39f1
Microstrong0305/coding_interviews
/58.左旋转字符串/58.左旋转字符串.py
465
3.703125
4
# -*- coding:utf-8 -*- class Solution: def LeftRotateString(self, s, n): # write code here if len(s)==0: return s s = list(s) def flip(s,start,end): for i in range(start,(start+end)//2 + 1): s[i],s[end-i+start] = s[end - i+start],s[i] ...
51f727d8a00ece32288362beb0d8cd02bec7a83d
apatel81/CSC349
/Assignment3/test.py
4,029
3.984375
4
# Ajay Patel # Assignment 3 from queueArray import * class Vertex: def __init__(self, key, discovered): self.id = key self.discovered = False self.adjacent_to = [] def add_neighbor(self, v): self.adjacent_to.append(v.id) def getConnection(self): return self.adjac...
11d0892f9aa939701c1dc9dd5348d917f101e30b
yisuspeace/Tecnicas3
/clase2/rombo.py
179
3.734375
4
lado = int(input("Introduce longitud: ")) for x in list(range(lado)) + list(reversed(range(lado-1))): print('{: <{w1}}{:*<{w2}}'.format('', '', w1=lado-x-1, w2=x*2+1))
533939a2ccc27f4979d13c8630e1d5e80ae960b2
nbrown273/du-python-fundamentals
/modules/module1_classes/exercise1.py
639
3.8125
4
class MyTestClass(): class_var = 'this is a class variable' _other_var = 'the leading underscore on this one tells the users they probably shouln\'t mess with it' def my_class_func(): pass # do stuff here def my_other_func(): pass # do more stuff here ############################# ...
ed294c0d77434c644a4805c6f7a04b1789e1019d
nbrown273/du-python-fundamentals
/modules/module11_list_comprehensions/exercise11.py
1,384
4.34375
4
# List Comprehension Example def getListPowN(x, n): """ Parmaeters: x -> int: x > 0 n -> int: n >= 0 Generate a list of integers, 1 to x, raised to a power n Returns: list(int) """ return [i**n for i in range(1, x) if i % 2 == 0] # Dictionary Comprehension Example def getDictC...
c31def3740279384a242bf7e981b657293964d3e
Jerusha551/tcs
/tcs digital sample queries/1.py
113
3.578125
4
al=int(input()) l=[] for i in range(al): l.append(int(input())) sn=int(input()) l.sort() print(l[sn-1])
9f440eacbaaa57536a186a5214def3076054fb5e
flaviorangel/ross
/ross/fluid_flow/fluid_flow.py
16,711
3.84375
4
import numpy as np import matplotlib.pyplot as plt import sys class PressureMatrix: r"""This class calculates the pressure matrix of the object with the given parameters. It is supposed to be an attribute of a bearing element, but can work on its on to provide graphics for the user. Parameters -...
9daaa0a25e36cabd72471bf3f813e74d190e388a
amandabral/patternprinting
/pat6.py
257
3.96875
4
n=int(input()) sp=1 for i in range(n+1,0,-1): if i==n+1: for j in range(2*n): print("*",end="") print() for j in range(i+1): print("*",end="") for j in range(sp+1): print(" ",end="") sp=sp+2 for j in range(i+1): print("*",end="") print()
7a908de493d066a09a9f28bd99f1fd906cbcfcee
GregHegseth/code42cli
/src/code42cli/file_readers.py
2,680
3.765625
4
import csv import click from code42cli.click_ext.types import AutoDecodedFile from code42cli.errors import Code42CLIError def read_csv_arg(headers): """Helper for defining arguments that read from a csv file. Automatically converts the file name provided on command line to a list of csv rows (passed to comm...
92c57fcc0249328a51d255b9aca1ea4337f89c39
zcoder233/nn
/labml_nn/normalization/group_norm/__init__.py
3,069
3.53125
4
""" --- title: Group Normalization summary: > A PyTorch implementation/tutorial of group normalization. --- # Group Normalization """ import torch from torch import nn from labml_helpers.module import Module class GroupNorm(Module): r""" ## Group Normalization Layer """ def __init__(self, groups...
944c75e7a291f45a079886fa2cd78979a1bf64c1
manmodesanket/hackerrank
/problem_solving/min_swap.py
663
3.546875
4
def minimumSwaps(a): swaps = 0 swaped = False temp = 0 for i in range(0,len(a)): for j in range(0,len(a)): if a[j] == j+1: #print(a[j]) #print("correct position") #print(a[j]) continue else: a...
2cad47a5a9905de6a6dfc562e71db4f8a6e66ac9
manmodesanket/hackerrank
/problem_solving/string.py
683
4.34375
4
# You are given a string and your task is to swap cases. In other words, convert all lowercase letters to uppercase letters and vice versa. # # For Example: # # Www.HackerRank.com → wWW.hACKERrANK.COM # Pythonist 2 → pYTHONIST 2 # Input Format # # A single line containing a string . # # Constraints #0<=len(s)<=1000 # #...
e2d2427a83622575fbae296f80f55304b9aa77e6
vbronfman/Develop
/Mobilieye_home_test.py
3,112
4.28125
4
# you can write to stdout for debugging purposes, e.g. # print("this is a debug message") # # You are given a list of names of new employees in a company. You need to generate a company email address for each of them. The name of each person consists of two or three parts: a first name, an optional middle name, and...
44955f0b6797fb1267e59eb5610cdcb13253f715
vbronfman/Develop
/cloudity_test.py
580
3.734375
4
# you can write to stdout for debugging purposes, e.g. # print("this is a debug message") #@ Cloudity test: find min number not presented . def solution(A): # write your code in Python 3. A.sort() min=1 if A[-1] < 0: return 1 for i,value in enumerate(A): i...
7c9776a5a3e0d0e6cee8f1a38be3b0bff9657887
asf89/pl-training-codes
/Python/FirstClassExample/main.py
287
3.890625
4
from student import Student student1 = Student("Carlos", 20) student2 = Student("Luísa", 18) student3 = Student("Bruno", 22) if __name__ == '__main__': print(f'{student1.name}, {student1.age}') print(f'{student2.name}, {student2.age}') print(f'{student3.name}, {student3.age}')
3ab6fe8875983ba2142d2649588433ed4ee15b36
qlou/coding_execrise
/cracking_coding_interview/Python/problem1_2.py
936
3.703125
4
# str_1 = "instagram" # str_2 = "margatsni" str_1 = "instagram" str_2 = "margrtsni" class Solution: # Implement the first solution, sort two strings def check_permutation_1(self, str_1, str_2): if len(str_1) != len(str_2): return False else: str_1 = sorted(str_1) str_2 = sorted(str_2) for i in ra...
e29284516318ad80bc7f765a33a3b7557de8187b
ChrisSCorliss/Project-4
/input_gathering.py
214
3.828125
4
# Patrick print('We will ask you for three inputs.') path = input("Copy/ paste file path: ") file_name = input("What would you like the file called? ") destination = input('Where would you like the file to go? ')
b0501c367054fd431821e9626e1ba01622ab09c4
grrrhhh/euler
/p01.py
302
4.03125
4
""" Find the sum of all the multiples of 3 or 5 below 1000. """ def p1(n = 1000): return sum(set(range(0,n,3) + range(0,n,5))) print p1() """ Other Solutions: sum(i for i in range(1000) if i % 3 == 0 or i % 5 == 0) sum(filter(lambda n: n % 3 == 0 or n % 5 == 0, range(0, 1000))) """
c34a4b5c159f105c8719f91bc4cb8d4fac789042
grrrhhh/euler
/p06.py
279
3.84375
4
""" Sum square difference Sum of Squares - Square of sums """ def p6(n): sum_of_squares = 0 square_of_sums = 0 for i in range(0, n+1): sum_of_squares += i * i square_of_sums += i return abs(sum_of_squares - (square_of_sums ** 2)) print p6(10)
54bbe18a7f1e8c137c2d43f9ccc75bd1ea3273e9
smjedael/python-challenge
/PyBank/main.py
2,839
3.8125
4
#PyBank Script #Import modules import os import csv #Request path and filename of data file csvpath = input('Please enter path and filename of data file (e.g. "datafolder/datafile.csv"): ') #Declare and initialize variables to store data total_revenue = 0 prev_revenue = 0 sum_revenue_chg = 0 max_revenue_chg = 0 max_r...
05123558c3106adf2a806e63bdc203a5aed80ede
Brainiak-inc/EPAM_TASKS
/task_4.py
197
4.03125
4
def factorial_count(n): factorial = 1 while n > 1: factorial *= n n -= 1 return factorial n = int(input('Введите число:')) print(factorial_count(n)) input()
4d97da83215734d677dd6b7bc15c527b9e6ee262
srs0447/Basics
/8-calculator.py
817
4.15625
4
# Basic calculator that do the basic calculations like addition, subtraction, multification etc # declaring the global variables print("This is the basic calculator") print("\n********************************************\n") print("$$$$$$^^^^^^********^^^^^^^$$$$$$$$$$") number1 = float(input('Please Enter the first nu...
18b832fbe6501c10aaf39a222fed8d354fa063a4
lxj0276/note-1
/algorithm/top_interview/grab.py
1,170
3.5625
4
# you can write to stdout for debugging purposes, e.g. # print("this is a debug message") def solution(A): # write your code in Python 3.6 pseudo_periods = {} length = len(A) if length < 3: return -1 result = 0 diff = A[1] - A[0] c = 0 for i in range(length - 1): if A[...
61aeb7c2ed5280752e2a0c24c72a90dc2ab36316
Christopher-Li/Traffic_Lights
/Scripts/calcSingleXOneWayTime.py
2,211
3.609375
4
def fileToArray(vehicleRouteFileName): vehicleRouteData = open(vehicleRouteFileName,'r') vehicleRouteDataArray = [] for line in vehicleRouteData: vehicleRouteDataArray.append(line.split()) vehicleRouteData.close() return vehicleRouteDataArray def calcSingleXOneWayTotalTime(vehicleRouteFileName,trafficLightFileN...
b9457ddf378ff0ce54ed3fe6ccca17d1640579aa
the-carpnter/codewars-level-7-kata
/common_substring.py
163
3.609375
4
def substring_test(s1, s2): if s1 and s2 and len(s1) > 1: return True if s1[:2].lower() in s2.lower() else substring_test(s1[1:], s2) return False
dacc5877a9c49695a6120178800928118eccfdf6
the-carpnter/codewars-level-7-kata
/balanced_number.py
264
3.5625
4
def balanced_num(number): n = str(number) l = len(n)//2 if len(n)%2==0: x, y = sum(map(int,n[:l-1])), sum(map(int,n[l+1:])) else: x, y = sum(map(int,n[:l])), sum(map(int,n[l+1:])) return 'Balanced' if x == y else 'Not Balanced'
338c5fd01c1d83de5586b347dcabeae06dbcbbfc
the-carpnter/codewars-level-7-kata
/rule_of_divisibility_7.py
136
3.5
4
def seven(m, steps=0): if len(str(m)) <= 2: return m, steps return seven(int(str(m)[:-1]) - 2*int(str(m)[-1]), steps+1)
93cb8d51ea184942aae12f260c36e871b9a64081
the-carpnter/codewars-level-7-kata
/is_this_a_triangle.py
165
3.59375
4
from itertools import permutations def is_triangle(a, b, c): for x,y,z in permutations([a,b,c]): if x >= y + z: return False return True
c2a8af27de33f9ae63b11f32c94b5f9369a55e27
the-carpnter/codewars-level-7-kata
/palindrome_chain_length.py
281
3.515625
4
def reverse(n): k = [] while n: n, m = divmod(n, 10) k += [str(m)] return int(''.join(k)) def is_pal(n): n = str(n) return n == n[::-1] def palindrome_chain_length(n): return 0 if is_pal(n) else 1 + palindrome_chain_length(n + reverse(n))
1c74a2f2bf7ef024046969b4b8dd0ebd7a3bf509
the-carpnter/codewars-level-7-kata
/next_prime.py
285
3.921875
4
def is_prime(n): if n == 2: return True if n < 2 or n % 2 == 0: return False for i in range(3, int(n**0.5)+1, 2): if n % i == 0: return False return True def next_prime(n): return n + 1 if is_prime(n + 1) else next_prime(n + 1)
254279112a324e00d76fab732511d660216ac099
the-carpnter/codewars-level-7-kata
/sum_of_two_lowest_positive_integers.py
224
3.6875
4
def sum_two_smallest_numbers(n): k = [n[0], n[1]] if n[0] < n[1] else [n[1], n[0]] for x in n[2:]: if x < k[1]: k[1] = x if x < k[0]: k[0], k[1] = k[1], k[0] return sum(k)
92c1c662600fdc1e01b1e4c12aba431680709306
the-carpnter/codewars-level-7-kata
/perfect_squares_perfect_fun.py
256
3.75
4
def square_it(digits): try: digits = str(digits) n = len(digits)**0.5 x = n if n%1 else int(n) return '\n'.join(digits[i:i+x] for i in range(0,len(digits),x)) except TypeError: return 'Not a perfect square!'
96a6d904da139c434a08efc633ecf849bc6ef2b5
the-carpnter/codewars-level-7-kata
/return_the_missing_element.py
131
3.59375
4
def get_missing_element(seq): for i, x in enumerate(sorted(seq)): if i != x: return x - 1 return x + 1
6210b8b36e62f86e4631cb389c9b1c0314573a51
the-carpnter/codewars-level-7-kata
/every_archer_has_its_arrows.py
131
3.5
4
def archers_ready(archers): for x in archers: if x < 5: return False return True if archers else False
b7341f228d1fc848f24326a63a4659ed93ff2078
DaniilAnichin/for_TA
/merge.py
863
4.125
4
#!usr/bin/python # -*- coding: utf-8 -*-# from math import log def merge_sort(num_list): half_len = len(num_list) / 2 if len(num_list) > 2: return merge(merge_sort(num_list[:half_len]), merge_sort(num_list[half_len:])) elif len(num_list) == 2: return merge(num_list[:1]...
620fa1e9e728bd01e1f0c5b5a9a17b524474aed1
Whoami8322/cajeroautomatico
/cajeroautomatico.py
3,612
3.84375
4
# Cajero Automático from random import randrange saldo = randrange(0,9000000) print("Welcome al Cajero Automático") print("") print("1. Opciones Disponibles") print("2. Cuenta de Ahorro") print("3. Cuenta de Debito") print("4. Pagos de Facturas") print("5. Enviar Dinero") print("6. Nequi") print("7. Tarjeta de Credi...
405ede2a0e02a39fbcf880f99041843bf2553493
ShiplakeCS/ShipShape
/code.py
2,291
3.53125
4
import time # Import the Time library # from gpiozero import CamJamKitRobot # Import the GPIO Zero Library CamJam library class DistanceSensor: def __init__(self): self.d = 10 def increase_distance(self, x): self.d += x def decrease_distance(self, x): self.d -= x @proper...
81ac54b4e078f0200a266f3ab54b8c8cd5bb7506
HanJaeSeob/LeetCode
/reverseString.py
388
4.0625
4
# -*- coding: utf-8 -*- # Reverse string # 2017-7-18 by lee def reverseString(string): #return ''.join(list(string)[::-1]) ''' l = list(string) n = len(l) for i in range(int(n/2)): tmp = l[i] l[i] = l[n-i-1] l[n-i-1] = tmp return ''.join(l) 以上是正确的 ''' l = list(string) l.reverse() return ''.join(l) ...
ed9aa397381fe0aa2bf53f7da4bbbb8ed275d74a
Johnnyboycurtis/TSI
/TSI/Differencing.py
232
3.609375
4
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Sun May 14 13:00:53 2017 @author: jonathan """ import numpy as np def diff(x, n=1): s = x for i in range(n): s = s[:-1] - s[1:] return s
5fc8e610e39460d5e0d92dd192ea95f66e712ac7
dimasiklrnd/python
/using arrays/The maximum number of consecutive 1.py
1,949
4.09375
4
'''Вводится последовательность, состоящая только из 0 и 1. Необходимо найти максимальное количество 1, идущих подряд (без 0 между ними). Формат входных данных В первой строке задается натуральное N<=10000 , длина массива, далее идут N чисел 0 или 1 -- элементы массива. Каждое число вводится с новой строки. Формат вых...
a741440bb77561ffe74fa934e66d6769500e6645
dimasiklrnd/python
/lessons/files_and_exceptions/write.py
537
3.53125
4
file_write = 'lessons/files_and_exceptions/programming.txt' with open(file_write, 'w') as file_object: file_object.write('Мне нравится программировать\n') file_object.write('Мне нравится программировать!!!\n') with open(file_write, 'a') as file_object:# атрибут 'a' добавляет в файл не перезаписывая его, 'r+' ...
9391f59583e564e45ae7531e64619505fdccc764
dimasiklrnd/python
/using arrays/Belonging to a circle.py
3,001
4.1875
4
'''Даны координаты точки и радиус круга с центром в начале координат. Определить, принадлежит ли данная точка кругу. Напомним, что круг – это часть плоскости, состоящая из всех точек окружности и всех точек, лежащих внутри окружности. Формат входных данных Три целых числа на одной строке: координата точки по оси x, ко...
867bb442738e2ef4dfc3e1314ae9c39add11f1b5
dimasiklrnd/python
/highlighting numbers, if, for, while/The number of elements equal to the maximum.py
1,314
3.796875
4
'''Последовательность состоит из натуральных чисел и завершается числом 0. Всего вводится не более 10000 чисел (не считая завершающего числа 0). Определите, сколько элементов этой последовательности равны ее наибольшему элементу. Числа, следующие за числом 0, считывать не нужно. Формат входных данных Вводится последов...
e3ca668d88674d2934ac7994f959d526b392cc59
dimasiklrnd/python
/highlighting numbers, if, for, while/The number of even elements.py
610
4.28125
4
'''Посчитать количество четных элементов в массиве целых чисел, заканчивающихся нулём. Сам ноль учитывать не надо. Формат входных данных Массив чисел, заканчивающийся нулём (каждое число с новой строки, ноль не входит в массив) Формат выходных данных Одно число — результат.''' n = int(input()) x = 0 while n != 0: ...
680d65a2d69e6556dfe194f53e9cc494771b7723
dimasiklrnd/python
/practic/Non-unique_Elements.py
2,395
3.53125
4
''' Дан непустой массив целых чисел (X). В этой задаче вам нужно вернуть массив, состоящий только из неуникальных элементов данного массива. Для этого необходимо удалить все уникальные элементы (которые присутствуют в данном массиве только один раз). Для решения этой задачи не меняйте оригинальный порядок элементов. Пр...
d86455da04d7e2f9c25b1452e173255a8bc5f0a2
apojomovsky/cuatro_en_linea
/tests/test_strategy_emtpiest_column.py
3,573
3.75
4
#!/usr/bin/env python import unittest from board_builder import BoardBuilder from game.gameboard import GameBoard from game.gameboard import BoardIsFull from game.emptiest_column_strategy import EmptiestColumnStrategy class TestEmptiestColumnStrategy(unittest.TestCase): def setUp(self): self.strategy = Emp...
6d7547cd1bf7253528d12f1161b6bdebd27166b9
PeteMurray/Python-RPG
/rpg.py
2,181
3.765625
4
import re import random # Inventory system class Item(object): def __init__(self, name, attack, armor, weight, price): self.name = name self.attack = attack self.armor = armor self.weight = weight self.price = price class Inventory(object): def __init__(self): s...
86a9b496e5f8fef5e87d46aedfc02ffb6e74ef58
grshprajapat/summer2k19
/summmer19/python_task19/google2.py
671
3.5625
4
#!/usr/bin/python3 from googlesearch import search import time #import speech_recognition as sr #r = sr.Recognizer() #with sr.Microphone() as source: ''' #take input from user to search on web print('speak anything:') audio=r.listen(source) try: text = r.recognize_google(audio) print('you said: {}'.fo...
378d7dabedfb90e43c443e4325300d39857b9093
NatanStein/IA-do-Ramo
/Estudo/perceptron2.py
366
3.59375
4
# -*- coding: utf-8 -*- """ Created on Fri May 1 13:50:20 2020 @author: Natan Steinbruch """ import numpy as np def soma(e,p): return e.dot(p) #dot = produto escalar def stepFunction(soma): if(soma >= 1): return 1 return 0 # # Bloco Principal # entradas = np.array([-1,7,5]) pesos = np.array([0.8...
d0ad5dd7e1e3fcb6555e8573b7802d23dc345e9f
si7eka/XiaoXiang-python
/案例7--模拟之掷骰子/模拟掷骰子1.0.py
2,571
4.15625
4
""" 案例描述: 通过计算机程序模拟投掷骰子,并显示各种点数的出现次数及频率 比如,投掷2个骰子50次,出现点数为7的次数是8,频率是0.16 案例分析: 如何通过Python模拟随机事件?或者生成随机数? random模块 遍历列表时,如何同时获取每个元素的索引号及其元素值? enumerate() 函数 知识点: random模块 用于生成随机数 常用函数 函数 含义 random() 生成一个[0, 1.0)之间的随机...
fd30955f277397a4520fb5d05a2e4a99da00725b
si7eka/XiaoXiang-python
/案例3--基础代谢率(BMR)计算/BMR3.0.py
1,911
4.03125
4
""" 作者:李征 功能:计算用户BMR 版本:3.0 """ def main(): """ 主函数 """ yes_or_no = input('输入任意键继续,退出请输入no。') while yes_or_no != "no": print('请输入以下信息,用空格分割') # 输入提示 input_str = input('性别 体重(KG) 身高(cm) 年龄:') # 输入内容赋值给变量input_str str_list = input_str.split(' ') # 使用input....
bbbac97db52c79674684601e12be34092c6d3f8f
si7eka/XiaoXiang-python
/案例2--分形树的绘画/五角星2.py
1,369
4.3125
4
""" 作者:李征 功能:五角星绘图 版本:2.0 新增:循环操作 turtle库说明: 形状绘制函数 turtle.forward(distance) 画笔向前移动distance距离 turtle.backward(distance) 笔画向后移动distance距离 turtle.right(degree) 绘制方向向右旋转degree度 turtle.exitonclick() 点击关闭图形窗口 (左) ...
1f8cc07be011c3187950f1a79db3c94468a2ac72
mckaymckay/shuati
/数组/27.py
693
3.703125
4
# 移除元素 def removeElement(nums, item): length = len(nums) if length != 0: return 0 i = 0 j = 0 while j < length: if nums[j] != item: if i != j: nums[i] = nums[j] i += 1 j += 1 return i, nums[:i] nums = [1, 2, 6, 3, 3, 4, 3, 5, 3, 6...
2b650fcac768efb526637ed23ed1718c70ba48d6
mckaymckay/shuati
/test.py
4,511
3.546875
4
# arr = [1,2,2,4,5] # length=len(arr) # nums=list.copy(arr) # for i in range(1,length+1): # if i in arr: # arr.remove(i) # else: # notfound=i # print((arr[0],notfound)) # print(nums) # print('----------------------------------') # arr = [1,2,2,4,5] # count={} # for i in arr: # count[i]=coun...
4a3ea3651d039f41ccd542d369f1adfe90d9841e
mckaymckay/shuati
/链表/707.py
2,720
3.71875
4
# 设计链表 # 定义结点 class ListNode(object): def __init__(self, value=0): self.value = value self.next = None # 定义链表 class MyLinkerList(object): def __init__(self): self.head = None self.size = 0 # 遍历 def tranverse(self): start = self.head while start: ...
12996a83f0aa5ec81a3c617ffb453a3c4df8d35e
geekbert/pythoncharlesseverin
/pythoncharlesseverin/05_searchbooleaninloop.py
184
3.890625
4
found = False print 'Before', found for value in [9, 41, 12, 3, 74, 15] : if value == 3 : found = True print found , value print 'After', found
e6ad956c342406cfbe324d59624d420d9f697b55
geekbert/pythoncharlesseverin
/pythoncharlesseverin/05_averageinloop.py
220
3.71875
4
count = 0 sum = 0 print 'Before', count, sum for value in [9, 41, 12, 3, 74, 15] : count = count + 1 sum = sum + value print count, sum , value print 'After', count, sum , sum / count