blob_id
stringlengths
40
40
repo_name
stringlengths
5
119
path
stringlengths
2
424
length_bytes
int64
36
888k
score
float64
3.5
5.22
int_score
int64
4
5
text
stringlengths
27
888k
87a93fa069a3d6e9f4a839ae98d0a5e805f7210b
arod0214/python_intro_projects
/Rolling Two Dice.py
231
4.125
4
# Write a program that simulates rolling two 6-sided dice and tells the user the results of the two rolls and their sum. rollFirst = int(input("Roll 1:")) rollSecond = int(input("Roll 2:")) print("Sum:",(rollFirst + rollSecond))
ce97fd23900c559f4244f93268126610cfbc1519
MadSkittles/leetcode
/129.py
615
3.578125
4
from common import TreeNode class Solution: def sumNumbers(self, root): self.result = 0 if root: self.f(root, root.val) return self.result def f(self, node, num): if node.left is None and node.right is None: self.result += num r...
679eb24f7b03de63264ca8c8b4ebd99afbc6a78a
ChromeUniverse/preparatorio-obi
/Aulas/5/comandos.py
894
3.796875
4
# coding: utf-8 linhas = ['ana', 'beatriz', 'clara'] linhas # lista de strings >>> string ' '.join(linhas) '--'.join(linhas) s = ''.join(linhas) s s = ' '.join(linhas) # string >>> lista de strings s.split() s = '--'.join(linhas) s s.split() s.split('--') s = '1 2 3 4' l = s.split() l [1, 2, 3, 4] nums = [] l for ...
f8f709c4095527c249906ea206e1db851f6fd7f4
6igsm0ke/Introduction-to-Programming-Using-Python-Liang-1st-edtion
/CH02/EX2.18.py
637
4.34375
4
# (Current time) Listing 2.7, ShowCurrentTime.py, gives a program that displays the # current time in GMT. Revise the program so that it prompts the user to enter the # time zone in hours away from (offset to) GMT and displays the time in the specified # time zone. import time tzo = eval(input("Enter the time zone off...
b13ddef541bdaac4c0cc3b2b4923edd2bdc7bc6b
tteearu/learning_code
/Python/Codeclub/calculator/calculator_original.py
1,502
3.765625
4
class Calculator: def calculate(self, input_string): tehe = [] operators = ['+','-','*','/'] result = 0 temp = "" special = ['*','/'] for x in input_string: if x in operators: try: tehe.append(float(temp)) except ValueError: pass tehe.append(x) temp = "" else: temp += ...
44455b2adc666ee595188a6561999faaa322d4c6
tejas77/codechef-python
/Beginner/FLOW004/main.py
115
3.546875
4
t = int(input()) while t > 0: number = list(input()) print(int(number[0]) + int(number[-1])) t = t - 1
e7cb6140348156333a2c3f553c83909c1fa4031e
MohamadShafeah/python
/Day1/02Formatting/O004formattingBasics.py
339
3.65625
4
# 1 classical printf emulate frm_str = "Hello Mr.%s %s talented Guy" val_info = ('Scahin', "Super") print(frm_str % val_info) val_info = ('Scahin', 1000) # 1000 convered as string print(frm_str % val_info) frm_str = "Hello Mr.%s %.3f talented Guy" val_info = ('Scahin', 1000) # 1000 taken as float print(fr...
551df71fa265ec0a82acbb1cad6ea1b40d8327c6
manish1822510059/Python-1000-Programs
/List/3_Traverse_list_using_loop.py
129
3.984375
4
myList = ["iphone",'Mi','Vivo','Oneplus','Samsang','Oppo'] print("All items of the List") for item in myList: print(item)
996d9d4b9475e1778a821214d2a47511cbb90104
AdamZhouSE/pythonHomework
/Code/CodeRecords/2465/60708/302131.py
328
3.65625
4
def find(list): for i in list: sum=0 for j in list: if j>=i: sum=sum+1 if sum<=i: return sum if __name__ == '__main__': temp=input() for i,j in enumerate(temp): if j=='[': break list=eval(temp[i:len(temp)]) print(fin...
85875bb767ccda41f1f04c97686d1ce9b1152b35
willscarvalho/Jogo_da_Velha
/src/funcoes.py
6,727
4.1875
4
def criar_tabuleiro(): """ Função que cria o tabuleiro das posições do jogo. Return: retorno uma listas contendo outra 3 listas respectivamente com os valores vazio do tabuleiro -> representação de matriz em python. """ tabuleiro = [[' ', ' ', ' '], [' ', ' ', ' '], [' ', ' ', ' ']] return ...
cd1c4c92cd56ad9df1457e6fc9c774029ff3c9ea
Musawir-Ahmed/OOP
/WEEK-3/PRODUCT-LIST-(OOP).py
2,780
3.609375
4
import os # DECLARING A OST TO STORE PRODUCT DATA productrecord = [] # DECLARING CLASS class productinfo: ProductId = 0 Name = "" Price = 0 Category = "" Brandname = "" Country = "" # HEADER FUNCTION def header(): print("**********************************************...
1f9e52e3c321e66142c3b8ea0ff638a816b091d2
Holarctic/Python-programming-exercises-master
/Answears/question3.py
120
3.640625
4
n = int(raw_input()) d = dict() for i in range(1, n + 1): d[i] = i*i #for i in range(1, n + 1): # d[i] = i*i*i print d
150355d299dd9523f597aa1fd68b0a8bb2f81972
yodeng/sw-algorithms
/pythonic/tree/binary_tree.py
2,473
3.859375
4
#!/usr/bin/env python # encoding: utf-8 """ @author: swensun @github:https://github.com/yunshuipiao @software: python @file: binary_tree.py @desc: 二叉树的构造 @hint: 对左右子树分别插入 """ class Node: def __init__(self, data): self.data = data self.left_child = None self.right_child = None def ...
5e1586b64218a125f588e9ef8f07f1774dfe2151
code-evince/CipherSchools_Assignment
/Assignment-2/Print All Possible Combination Mobile.py
942
3.859375
4
hashTable = ["", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"] def printWordsUtil(number, curr, output, n): if(curr == n): ans ='' for i in output: ans+=i print(ans,end=' ') return for i in range(len(hashTable[number[curr]])): ...
13376868f0514f690adeb0ce2a21637acddb5fee
zc-cris/python_demo01
/primary02/demo14_计算连续数字的方法2.py
322
3.859375
4
# _Author: zc-cris string = "232jj2kj2" for i in string: if i.isalpha(): string = string.replace(i, " ") print(string) # 232 2 2 string = string.split() # If sep is not specified or is None, any # whitespace string is a separator and empty strings are # removed from the result print(len(string)) # ...
5602a41cc004b3074a2b2d88059ec2328579b2c6
kambizmir/MLND-Capstone-Micromouse
/robot.py
35,780
4.28125
4
import numpy as np from maze import Maze import turtle import sys from collections import deque from random import randint import time class Robot(object): def __init__(self, maze_dim): ''' Use the initialization function to set up attributes that your robot will use to learn and navigate...
f67907a2b696d950b0501b829d52f144ab1fc86d
fdas3213/Leetcode
/540-single-element-in-a-sorted-array/540-single-element-in-a-sorted-array.py
756
3.59375
4
class Solution: def singleNonDuplicate(self, nums: List[int]) -> int: left, right = 0, len(nums)-1 while left<right: mid = left+(right-left)//2 right_even = (right-mid)%2==0 if nums[mid]==nums[mid+1]: if right_even: #after remov...
15120915bb131571dfa7186d017d8f9c78587e20
Camomilaa/Python-Curso-em-Video
/ex025.py
115
3.59375
4
nome = str(input('Digite seu nome completo: ')).strip() print('Seu nome possui silva: {}'.format(' Silva' in nome))
ae0a4ed4d5dc90f4ce82758977ba43375d4e32a7
adamelid/PythonVerk
/Assignment13/pullingLeversForCoins.py
3,696
4.0625
4
#Algorithm is as follows: #While not at final tile. #----Show possible directions. #----Player chooses direction. #----Check if direction is valid. #----Move to chosen tile if valid. #Print victory result. #Set static variables. # - x, y, walls(west, north, east, south), lever. Tile1 = 1,1,1,0,1,1,0 Tile2 = 2,1,1,...
e5269fae32ae2a37d62205ebe8e1deb691f4caf3
fatmasener/CreativeHubYazilim
/Python Dersleri/Ders-8/menu.py
1,317
3.734375
4
class MenuItem: # Menudeki her bir icecegi modeller def __init__(self,isim,su,sut,kahve,maliyet): self.isim = isim self.maliyet = maliyet self.icerikler = { "su": su, "süt": sut, "kahve":kahve } class Menu: """Iceceklerle Menuy...
c2ba09d9312d4c1e2371dd787e405e1fdb61547b
dr-dos-ok/Code_Jam_Webscraper
/solutions_python/Problem_158/671.py
552
3.5
4
def solve(X, R, C): ans = solve_(X, R, C) return "GABRIEL" if ans else "RICHARD" def solve_(X, R, C): if X == 1: return True if X == 2: return R % 2 == 0 or C % 2 == 0 if X == 3: return (R, C) in ((2, 3), (3, 2), (3, 3), (3, 4), (4, 3)) if X == 4: return (R, C) i...
17422917dcff0d4b3a54bd78e50ab07ccccafd29
Rookie-cprime/CS_learn
/class_1/part_2/homework/homework/prc_4.py
1,016
3.8125
4
def monthday(balance,annualInterestRate,minimum_money,day = 0): balance -= minimum_money if(balance<=0 or day>12): return day else: return monthday(balance+balance*(annualInterestRate/12),annualInterestRate,minimum_money,day+1) def paying_debt(balance,annualInterestRate): BOL = True ...
a3d91aa435bc7102e92bc1184e620b56b97cc440
iccowan/CSC_117
/exam_1_practice/number_2.py
527
4.34375
4
# Exam 1 Practice # Question Number 2 # Biking Mileage # Initialize variables new_day = float(input('How many miles did you ride on day 1? ')) total_miles = 0 day = 1 # Runs a loop until the user doesn't input anything while new_day != '': new_day = float(new_day) if new_day >= 0: total_miles += new_d...
1dcfa3e6201696a56abcfa423a413128bd8216b7
mustbepro/toggl-api
/togglin.py
5,201
3.765625
4
#!/usr/bin/python3 from random import randint import calendar from collections import defaultdict array = [1, 2 ,3 ,4, 5] week = [] #for i in array: # week.append(randint(4,7)) total_time = 20 count = 0 #while (count < total_time): # entry = randint(4,7) # # if((entry + count) < total_time): # week...
1391a0b1711c6302fe4fbec23bab5654bd1f4ada
Marciom99/DNA-Sequence-Analysis
/Option2.py
4,722
3.734375
4
from sys import exit import Interface, Modulos def exercicio2(): escolha = str(input(f""" 2 {'*'*20} \ta. Inserir uma sequência \tb. Remover uma sequência \tc. Mostrar o número de ocorrências de uma determinada base ou sub-sequência e uma lis...
f6ef79c9ff1626b30d593a88f3297d98c1079b79
FrederikWilmotte/adventofcode2019
/Advent8p2.py
1,560
3.53125
4
# Advent8 - Part2 # Day 8: Space Image Format def printLayer(layer,wide): layer = makeLayerReadable(layer) startlayer = 0 stoplayer = wide while startlayer + wide <= len(layer): print(layer[startlayer:stoplayer]) startlayer = startlayer + wide stoplayer = stoplayer + w...
6c9797b0658dbf0edb0a0f5a0d244906e666e449
sranjani47/LetsUpgrade-AI-ML
/files/solution/day5/d5.py
1,888
4.3125
4
#!/usr/bin/env python # coding: utf-8 Q1. Write a Python program to find the first 20 non-even prime natural numbers. # In[1]: def check_prime(input_number): if input_number > 1: for i in range(2, input_number): if (input_number % i) == 0: res = "No" break ...
02d7bb4a5f9f5fb5177a5eb083a1299e44e2229e
ArthurErn/lista_python
/Lista02Ex14.py
530
3.828125
4
aluno = input("Digite o número de identificação do aluno\n") ME = int(input("Informe a média nos exercícios do aluno \n")) nota1 = int(input("Informe a primeira nota da prova \n")) nota2 = int(input("Informe a segunda nota da prova \n")) nota3 = int(input("Informe a terceira nota da prova \n")) if nota1 < 0 or nota2 <...
251ac6134ca3a9513b2566c1e620217bf33143c7
tathagatoroy/Automata-Theory
/q4/Q4.py
8,190
3.765625
4
''' code to minimize dfa ''' import json import sys ''' function to print dfa optimally ''' def print_dfa(dfa): print("states : ") for i in dfa['states'] : print(i) print("transition :") for s in dfa['transition_function'] : print("old state : {0} , input : {1} and next state : ...
2899e955f821a7b6178474e968e5d4b55a65a820
woowei0102/code2pro
/data/clean_data/A2/27.py
113
3.78125
4
def factorial (n): temp=1 for i in range (1,n+1): temp *= i return temp print(factorial(10))
66e70d6da3c1aeca7585356fbd3b75c27781de51
teodornedevski/openCVvisualCode
/test1/test1/turtleDrawing.py
1,436
4.09375
4
import turtle turtle.color('red', 'yellow') turtle.begin_fill() def Draw (elements[]): for i in elements.length() : if elements[i] == "circle": turtle.left(20) if elements [i+1] == "up": turtle.forward(10) elif elements [i+1] == "back": t...
5698c967e99e2dda8c274dccf4c0408cfc37a11a
SMHari/Python-problems
/Module 4/11_rand_array.py
574
3.75
4
import numpy as np if __name__ == '__main__': np_rand_arr = np.random.randint(1, 1000, size=(3, 3)) # sorting by 1st column sort_column1 = np_rand_arr[np_rand_arr[:, 0].argsort()] # sorting by 2nd column sort_column2 = np_rand_arr[np_rand_arr[:, 1].argsort()] # sorting by 3rd column sort_c...
22dac0a644bdfe6b0e757d863c1fc0bb1ecd9682
mkarp94/ice_project_files
/ICE 0.0/Purchase_Class.py
2,439
3.703125
4
#implementation of a purchase for the purposes of evaluating categories of rewards class purchase(object): def __init__(self, tag = None, unit_price = None, quantity = 0, company = None, product_description = None): self.tag = tag self.unit_price = unit_price self.quantity = quantity ...
a5ada341354f7128df71f4d2269c0fc851a5cbc1
nmarun/LearningPython
/16FunctionBasics.py
199
3.546875
4
# Function basics # arguments are type-insensitive # allows for polymorphism def times(x, y): return x*y times(3, 4) # shows 12 times('a', 3) # shows 'aaa' times([1, 2], 2) # shows [1, 2, 1, 2]
2e3faee059571c559cde8500f30cdaf01e9944fc
vapoorva/LetsUpgradeDataScience
/Day 2/Q1.py
115
3.921875
4
list=[] for i in range(0,10): n= int(input("Enter number:")) if n%2==0: list.append(n) print(list)
1a01f9c449e61d3386243cff4ec7834ffa0cf719
odys-z/hello
/challenge/leet/medium/q377.py
2,135
3.8125
4
''' 377. Combination Sum IV https://leetcode.com/problems/combination-sum-iv/ Given an integer array with all positive numbers and no duplicates, find the number of possible combinations that add up to a positive integer target. Example: nums = [1, 2, 3] target = 4 The possible combination ways are: (1, 1, 1, 1) (1...
930299807e2b082e365f41392de09a65d2469625
UNSC1419/TestPy
/ah_28_字符串的查找和替换.py
1,026
4.4375
4
temp_str = "hello 123123123 world" # 1. 判断是否以指定的字符串开始 print(temp_str.startswith("hello")) # 2. 判断是否以指定的字符串结束 print(temp_str.endswith("world")) # 3. 查找指定字符串,返回该字符串的索引位置,不存在则返回-1 # index同样可以查找,但是不存在会报错 print(temp_str.find("llo")) print(temp_str.find("ABC")) # 通过参数来指定查找范围0开始到整个字符串长度间 print(temp_str.find("world", 0, len(...
f077c91328d9fefac19322ce9181e41ab76bce67
Harjacober/LeetCodeSolvedProblems
/Bitwise AND of Number Range.py
424
3.578125
4
from math import log,floor # This algorithm is not correct def bitwise(m,n): diff = n-m binary = list(bin(m)[2::]) for j in range(len(binary)): if binary[j]=="1": a = len(binary)-1-j factor = 2**a d = diff-(diff//factor)*factor if diff+d>factor: ...
acb901f2f52aec5a7b0745747e7d61e628b4c61d
victor01001000/math_gen
/math_algorithms/math_lib/Polynomial.py
3,227
4.4375
4
#!/usr/bin/env python3 import random class Polynomial(): """ Description: A polynomial is described as a list of monomials. The initializer's default parameter is an empty list of monomials; however, it it has defualt parameters to generating a random equation. """ def __init__(self, ter...
0a1d89fcdfde41c3912ad565620a2fdccb886e37
JuanmaLambre/TpDataMasters
/Pruebas/Perceptron/perceptronMulti.py~
4,416
3.515625
4
# # ACLARACION: En realidad aca no estoy haciendo Perceptron, simplemente estoy # categorizando con la recta y=x a fin de simplificar las cosas. # # A diferencia de perceptron.py este codigo grafica # (cant_reviews_pos; cant_revies_neg) por cada par de palabra que exista # IMPORTANTE: A difrenecia de perceptron simple ...
a5355844bd1a97f28bd3d646dac5c0a002ddaf64
SonaArora/Python-on-hands
/string/find_substring.py
641
4.03125
4
#TASK:In this challenge, the user enters a string and a substring. You have to print the number #of times that the substring occurs in the given string. String traversal will take place from #left to right, not from right to left. #Input Format:The first line of input contains the original string. The next line contain...
3d5af46e02de9807539ee55095b773a6f83084c2
janne02/ViopePython
/9.2 listan käyttäminen.py
895
3.796875
4
def selection(): try: selection=int(input("Haluatko \n(1)Lisätä listaan \n(2)Poistaa listalta vai\n(3)Lopettaa?:")) return selection except Exception: return "wrong" def secondaction(selection, memo): if selection == 1: memo.append(input("Mitä lisätään?: ")) elif...
e27bd3480bcb94e89d06a9d2557a9c57714cfcb5
jayceazua/wallbreakers_work
/practice_facebook/sub_left_leaves.py
1,005
4.0625
4
""" Find the sum of all left leaves in a given binary tree. Example: 3 / \ 9 20 / \ 15 7 There are two left leaves in the binary tree, with values 9 and 15 respectively. Return 24. """ # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # ...
6d4ebb93de1100fd52bc56159a7f9df3dfb49b42
leonparte/Python-Crash-Course-Learning-Projects
/Chapter 7/Test_7.1.py
1,051
4.125
4
# 函数input()的工作原理 # 从对函数input()的简单使用开始 print("\n-----------------------------------------\n") message = input("Tell me your favorite player:") print(message) # 编写清晰的程序 print("\n-----------------------------------------\n") print("What is your name?") name = input() print("You are", name.title()) # 使用...
36d3b1a5c46cfa0aefe7466867f8eadd10b0d6e3
hb162/Algo
/Algorithm/Ex_060420/Ex_Run-Length.py
903
4.21875
4
""" Run-length encoding is a fact and simple method of encoding strings. The basic idea is to represent repeated successive characters as a single count and character. For ex, the string "AAAABBBCCDAA" would be encoded as "4A3B2C1D2A". Implement run-length encoding and decoding. U can assume the string to be encoded h...
fba411311b12df6d3045514628f936a278dd2c56
siowyisheng/crypty
/crypty/crypty.py
1,231
3.734375
4
from cryptography.fernet import Fernet def encrypt(s, key=None): """Takes UTF-8 string and optional key(bytes or UTF-8), and spits UTF-8 token""" if key is None: key = Fernet.generate_key() try: f = Fernet(_to_bytes(key)) except binascii.Error: raise ValueError('The key was n...
79f2ffdc5bfef1d364087676915ba780d86d5a52
jedzej/tietopythontraining-basic
/students/myszko_pawel/lesson_03_functions/01_collatz.py
833
4.5625
5
# Write a function named collatz() that has one parameter named number. # If number is even, then collatz() should print number // 2 and return # this value. If number is odd, then collatz() should print and return # 3 * number + 1. # Then write a program that lets the user type in an integer and that # keeps calling c...
5d22a80f66c53304917c56c8b9e25e1aff8a7718
tuncatunc/algorithms
/DataStructures/Graph/Bfs/Minimum steps to reach any of the boundary edges of a matrix/solution.py
1,816
3.609375
4
from collections import namedtuple Point = namedtuple('Point', 'row col') Q = namedtuple('Q', 'point distance') class Graph: def __init__(self, matrix): self.matrix = matrix self.ROWS = len(matrix) self.COLS = len(matrix[0]) def isEdge(self, point): return (point.row == 0 or p...
2b419f06830c791d1c3af3dcce62faf97daf9aab
JasonDev-Coder/tictactoe
/tictactoe.py
5,761
3.953125
4
""" Tic Tac Toe Player """ import math import copy X = "X" O = "O" EMPTY = None counter = 0 def initial_state(): """ Returns starting state of the board. """ return [[EMPTY, EMPTY, EMPTY], [EMPTY, EMPTY, EMPTY], [EMPTY, EMPTY, EMPTY]] def player(board): """ Returns ...
b227fa6b56ae39490dfc59d5185110552a2f96f2
dreilly369/Py
/FizzBuzz/multiplesOf3or5.py
118
3.984375
4
the_sum = 0; for i in range(1,1000): if i % 3 == 0 or i % 5 == 0: the_sum += i print("The sum is: %d" % the_sum)
adfa638bdede78564ce5307b9999e05f6f549efc
LaundroMat/kodi-screentalk
/script.service.screentalk/resources/lib/fractional_seconds.py
535
4.03125
4
def convert_dict_to_fractional_seconds(hours=0, minutes=0, seconds=0, milliseconds=0): fractional_seconds = 0.0 fractional_seconds += milliseconds / 1000.0 fractional_seconds += seconds fractional_seconds += minutes * 60 fractional_seconds += hours * 60 * 60 return fractional_seconds def conve...
d15c4da8f399c0fcd9e82b3e6693e6dea693b088
blhwong/algos_py
/grokking_dp/knapsack_dp/count_subsets/main.py
923
3.859375
4
""" Problem Statement Given a set of positive numbers, find the total number of subsets whose sum is equal to a given number 'S'. Example 1: Input: {1, 1, 2, 3}, S=4 Output: 3 The given set has '3' subsets whose sum is '4': {1, 1, 2}, {1, 3}, {1, 3} Note that we have two similar sets {1, 3}, because we have two '1' i...
f80835ecffbd8e0ca45997a667c632715ba3de07
anhpt1993/spiral
/spiral.py
603
3.78125
4
import turtle as t import math while True: try: radius = float(input("Nhập giá trị bán kính lớn nhất của đường xoắn ốc: ")) if radius > 0: break else: print("Nhập số dương nhé bạn!") print() except ValueError: print("Nhập giá trị là số nhé bạn...
03566e8cdb51d947490fc8f0b35e4acc27b41c24
RuzhaK/PythonOOP
/IteratorsAndGeneratorsExercise/CountdownIterator.py
363
3.6875
4
class countdown_iterator: def __init__(self,count): self.count = count def __iter__(self): return self def __next__(self): if self.count<0: raise StopIteration() temp=self.count self.count-=1 return temp iterator = countdown_iterator(10) for ite...
10ae638358f99a4ae5ab601933c4163762fca761
victoriaparkhomenko885/homework_strings_other
/Task1.py
149
3.71875
4
text = 'Я учусь программированию в BRAIN' result = ' '.join(word[0].upper() + word[1:] for word in text.split()) print(result)
47f79eb41255e58d8157565c0316ec2864564c9f
xprilion/-_-
/^__^/2.5.py
1,334
3.671875
4
from LinkedList import LinkedList # def sumList(a, b): # if a.head == None: # return b # elif b.head == None: # return a # c = [] # ta = a.head # tb = b.head # carry = 0 # while ta != None and tb != None: # s = ta.data + tb.data + carry # c.append(s % 10) ...
c73665ca48e0ff5ec4681c0d2a010d749a7bff57
collin-clark/python
/server-by-port.py
883
3.9375
4
#!/usr/bin/python # Demo server to open a port # Modified from Python tutorial docs import socket import subprocess print "---------------------------------------------------------" print "This script will open any TCP port that is not currently" print "in use. Below are the ports in use. Any port < 1024 will" print...
db1455b8e53097f0e6a79b58babec7f3ac18e555
gjedlicska/speckle-py
/specklepy/objects/units.py
1,604
3.5
4
from specklepy.logging.exceptions import SpeckleException UNITS = ["mm", "cm", "m", "in", "ft", "yd", "mi"] UNITS_STRINGS = { "mm": ["mm", "mil", "millimeters", "millimetres"], "cm": ["cm", "centimetre", "centimeter", "centimetres", "centimeters"], "m": ["m", "meter", "meters", "metre", "metres"], "km...
b56914b0a8aac1226fc47cf60a1ddff8c2386d82
melissapott/codefights
/adjacent.py
489
4.25
4
"""Given an array of integers, find the pair of adjacent elements that has the largest product and return that product.""" def adjacentElementsProduct(inputArray): products = [] for x in range (0,len(inputArray)-1): products.append(inputArray[x]*inputArray[x+1]) return max(products) # expected result = 21 input...
c3a6ca654d161f8894fdba561f4d43c5cc363e77
noamalka228/PythonExercise
/Bank.py
7,164
4.25
4
import sqlite3 import socket con = sqlite3.connect('mydb.db') cur = con.cursor() # running steps: # 1. run Database first. # 2. run Bank # 3. run Atm # each run of the Database file deletes the Bank table contents. # So running it once and then preforming only 2nd and 3rd steps is the optimal action. # python interp...
80621f0bc511a2f91efc98192616b18dbc68259b
shoobham1011/NewProjectLAB
/Labratory/Lab2/Question3.py
299
3.625
4
''' Price of a house is $1M. If buyer has good credit, they need to put down 10% otherwise they need to put down 20% print down the payment. ''' buyer_credit = True price = 1000000 if buyer_credit: down_pay = 0.1 * price else: down_pay = 0.2 * price print(f'Down payment is ${down_pay}')
042c6e961f512b112e8e0a92b14b7cdbb00ca570
kruthikapalleda/Python-Project-1
/sortingPy.py
2,107
3.671875
4
import sys class Emplyoee: def __init__(self,eno,ename,esal,eaddr,sortingKey="ENO"): self.eno = eno self.ename = ename self.esal = esal self.eaddr = eaddr def __lt__(self,other): if self.sortingKey == "ENO": return self.eno < other.eno elif self.sortingKey ==...
b5b3334200f7cb3ced7c3bc6843c4ab7cfa15477
KudynDmytro/Practice
/hw4.py
2,389
3.828125
4
#1.Найти все числа, что нацело делятся на 7 впромежутке от 1 до 50 z = input('enter a number:') def first_ex(x): if x.isnumeric(): for i in range(1, int(x)): if i % 7 == 0: print(i) else: print('Error: you entered not a number!') return first_ex(z) #2.На...
a51fea67ff9a3362f94fa101d8abaac6f4f290d3
Amberttt/Python3-Test
/REGExpressions.py
19,268
3.5625
4
# Python3 正则表达式 # 正则表达式是一个特殊的字符序列,它能帮助你方便的检查一个字符串是否与某种模式匹配。 # Python 自1.5版本起增加了re 模块,它提供 Perl 风格的正则表达式模式。 # re 模块使 Python 语言拥有全部的正则表达式功能。 # compile 函数根据一个模式字符串和可选的标志参数生成一个正则表达式对象。该对象拥有一系列方法用于正则表达式匹配和替换。 # re 模块也提供了与这些方法功能完全一致的函数,这些函数使用一个模式字符串做为它们的第一个参数。 # 本章节主要介绍Python中常用的正则表达式处理函数。 # re.match函数 # re.match 尝试从字符串...
20f7834a0700706479f41d7ef7a81d9e5c0c15e2
escharf72/Engineering_4_Notebook
/arrays.py
114
3.625
4
def myFunc(a): b = [] for stuff in a: b.append(stuff**2) return(b) myArr = [1,3,6,23] print(myFunc(myArr))
cc37fdd4e673ff3fc16abf82bed8454416d58619
skizap/DDos
/bot.py
159
3.59375
4
import urllib url = raw_input ("url :") with open ("123.txt",'r') as f: for i in f : x = urllib.urlopen (i.strip()+url) print x.getcode()
f110037bfd574542f0653c40184e70c58ba768e8
mew177/MJW_Egan
/LeetCode/121. Best Time to Buy and Sell Stock.py
332
3.90625
4
""" Question: 1. Will there be negative value? 2. How largest would the price can be? Idea: 1. Use dynamic program """ prices = [7,1,5,3,6,4] maxDiff = 0 lowest = float('inf') for price in prices: lowest = min(lowest, price) maxDiff = max(maxDiff, price - lowest) pri...
861b86669573b739121d414562e0418a2d48a594
TianrunCheng/LeetcodeSubmissions
/distribute-candies/Accepted/3-2-2021, 2:27:12 AM/Solution.py
344
3.71875
4
// https://leetcode.com/problems/distribute-candies class Solution: def distributeCandies(self, candyType: List[int]) -> int: types = set() n = len(candyType) for c in candyType: types.add(c) t = len(types) if t < n//2: return t else: ...
84e30e8203f9c9e49ab18230265538fa9c9c4e2b
dbtomato/PythonStudy
/每周作业/郭岳雄/第三周/Queue_code.py
2,907
4
4
#!/usr/bin/env python # -*- encoding: utf-8 -*- # Python37-32 ''' @Author : {Gavin Guo} @License : (C) Copyright 2019-2024, {Daxiong's Company} @Contact : {878953027@qq.com} @Software: PyCharm @File : Queue_code.py @Time : 2020/3/1 12:20 @Desc : ''' ''' 代码引用来自:https://www.cnblogs.co...
85b4585fcbca078f95cc280d245b56590982c907
glendaascencio/Python-Tutorials
/Working_With_Lists.py
424
4.0625
4
# Combining two lists numbers = [1, 2, 3, 4] letters = ['a', 'b'] glenda = numbers + letters glenda # see how many methods a declared variable has dir(glenda) glenda.reverse() print 'See what happens when you use the reverse function = ', glenda glenda.append(23) print 'See what happens when you use the append funct...
a855de7b2a36267f1f1b6136e0efa1de94d224c9
felipesilvadv/felipesilvadv-iic2233-2017-1
/Tareas/T02/Partida.py
10,774
3.65625
4
from Planeta import Planeta from EDD import ListaLigada class Partida: def __init__(self, infeccion=""): if infeccion: self.planeta = Planeta(infeccion) self.planeta.agregar_vecinos() self.planeta.agregar_aeropuertos() else: self.planeta = None ...
cdf6b00aca3cf129335b0a604a7725a9998cc5bb
AkankshaKaple/Python_Data_Structures
/list/samllest_element_list.py
222
4.15625
4
#This is the program to find the smallest element in the list list = [11,13,4,15,6,27,28,1] j = len(list) min_val = list[0] for i in range(0,len(list)): if min_val > list[i]: min_val = list[i] print(min_val)
ef7db260c7c1268f6bbc62fd00abfaf9c907007a
AlexMenor/practicas_aprendizaje_automatico
/p2/p2.py
20,660
3.515625
4
#!/usr/bin/env python # coding: utf-8 # # Práctica 2 de AA # ## Ejercicio 1 import numpy as np import matplotlib.pyplot as plt # Fijamos la semilla np.random.seed(4) def simula_unif(N, dim, rango): return np.random.uniform(rango[0],rango[1],(N,dim)) def simula_gaus(N, dim, sigma): media = 0 out = np...
d629a90b679bfe39cbb85b9f46cc697f12024b7a
triggeron/DeepLearningProjects
/porto-seguro-safe-driver-prediction/safe_driver_model.py
2,986
3.546875
4
import torch from torch import nn, optim import torch.nn.functional as F import matplotlib.pyplot as plt import numpy as np class Network(nn.Module): def __init__(self, input_size, output_size, hidden_layers, drop_p=0.5): ''' Builds a feedforward network with arbitrary hidden layers. Arguments...
021b6e2f0cd03ee7e0b708b952c72ed8c2d41058
SOURADEEP-DONNY/WORKING-WITH-PYTHON
/xc.py
76
3.640625
4
n=int(input()) s=0 for i in range(n+1): s=s+i avg=s//n print(avg)
62ffebfe2a1f8845c8349d2095196472c3c87e70
thioaana/DataStructuresAndAlgorithms
/AlgorithmsOnGraphs/Week4PathsInGraphs/NegativeCycle.py
2,555
3.578125
4
#Uses python3 class Graph: def __init__(self, vertices): self.V = vertices # No. of vertices self.graph = [] self.count = 0 def importEdge(self, u, v, w): self.graph.append([u, v, w]) # The function detects negative weight cycle def isNegativeCycle3(self, src): ...
674bc94ea7171bb2cf1cad0feb41f83e9331d4c6
vegavazquez/2018-19-PNE-practices
/client-server/client.py
539
3.640625
4
import socket # SERVER IP, PORT IP = "212.128.253.64" PORT = 8080 # First, create the socket # We will always use this parameters: AF_INET y SOCK_STREAM s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # establish the connection to the Server (IP, PORT) s.connect((IP, PORT)) # Send data. No strings can be send...
c4e8da0b87f7f28183e19fdb5d12df95304e69ff
jasonusaco/Leetcode-Practice
/DP&Recursion/9.5.py
352
3.5
4
""" """ class Permutation: def getPermutation(self, A): if not A: return [] elif len(A) == 1: return [A] res = [] for i,c in enumerate(A): for s in self.getPermutation(A[:i]+A[i+1:]): res.append(c+s) res.sort(rev...
23f5bf3ce3f6c68593039f53ab918bcb946c19f6
yosiasz/myPython
/Excel/math.py
440
3.5625
4
import pandas as pd from IPython.display import display pd.set_option('display.max_rows', None) pd.set_option('display.max_columns', None) pd.set_option('display.width', None) A = pd.read_excel("./data.xlsx", sheet_name=0) df = A[ (A.Tmax > 0) & (A.Tmin > 0)] #Average df['avg'] = df.iloc[:,1:3].mean(axis=1)...
52c94667cfbff24d3cdef69dcf1d1c6724132b04
Bishopbhaumik/python_test
/oop_7.py
773
3.75
4
class Phone: def __init__(self,brand,model_name,price): self.brand=brand self.model_name=model_name # self.__price=price self.price=max(price,0) # self.complete_sp=f"{self.brand} {self.model_name} and price {self.price}" def make_a_call(self,phone_no): pri...
9eb6603a5e2f9076599d12661b1695b89861f65a
jaresj/Python-Coding-Project
/Check Files Project/check_files_func.py
2,635
3.609375
4
import os import sqlite3 import shutil from tkinter import * import tkinter as tk from tkinter.filedialog import askdirectory import check_files_main import check_files_gui def center_window(self, w, h): # pass in the tkinter frame (master) reference and the w and h # get user's screen width an...
1c37469179a06a3d8cff34bacedb29f928db0cac
Titing1234/Titing_Praktikum-Pewarisan
/pewarisan.py
852
3.84375
4
class Buah(object): def __init__ (self, a, k, m): self.apel = a self.kelapa = k self.mangga = m def jumlahBuah(self): return self.apel + self.kelapa + self.mangga def cetakData(self): print("Apel\t: ", self.apel) print("Kelapa\t: ", self.kelapa) print("Mangga\t: ", self.mangga) def ce...
5a3e7947d7c4957b25b605b67c2b668d430a18ff
hasnainhs/Data-Science
/Machine Learning for Data Science/Linear Regression/MultipleLinearRegression.py
3,776
3.59375
4
""" @author: Hasnain """ import pandas as pd import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D def cost_function(X, y, weights): m = len(y) predictions = np.dot(X,weights) J = np.sum((predictions-y)**2)/(2*m) return J def gradient_descent(X, y, alpha, epochs, w...
35b05e8d2855e9ab1774f58665f70ffe3ec9715c
betty29/code-1
/recipes/Python/440657_Determine_functiexecutitime_Pythonic/recipe-440657.py
2,051
3.953125
4
""" Determine function execution time. >>> def f(): ... return sum(range(10)) ... >>> pytime(f) (Time to execute function f, including function call overhead). >>> 1.0/pytime(f) (Function calls/sec, including function call overhead). >>> 1.0/pytime_statement('sum(range(10))') (Statements/sec, does not include...
f28beb15cf3f38bb2fd6a3901f6165dea07bd8cc
Boot-Camp-Coding-Test/Programmers
/day9/problem4/[최중훈] 최대공약수와 최소공배수.py
407
3.71875
4
def solution(n, m): def gcd(n, m): # 최대공약수 찾는 재귀함수 if m == 0: return n if n < m: (n, m) == (m, n) return gcd(m, n%m) gcd_num = int(gcd(n, m)) # 최대공약수 함수를 사용해서 구한 gcd lcm_num = int(n*m / gcd_num) # 두 수를 곱하고 gcd로 나누어주면 lcm answer = [gcd_num, lcm_num] r...
81a647cea375db2e363c14804d5e999728812e04
Spinnerka/Python-Coursera-Assignments
/Ex5_LargestSmallestNumber.py
1,045
4.21875
4
#5.2 Write a program that repeatedly prompts a user for integer numbers until # the user enters 'done'. Once 'done' is entered, print out the largest and # smallest of the numbers. If the user enters anything other than a valid # number catch it with a try/except and put out an appropriate message and # ignore the ...
f8a1ce49c2bd811dfc1f9a59369e983e43031908
sreegayathri/6044_CSPP1
/CSPP1/cspp1-assignments/m5/square_root_bisection.py
219
3.8125
4
num_va = int(input()) epsilon = 0.01 low = 0 high = num_va avg = (low/high)/2 while abs(avg**2-num_va) >= epsilon: if avg**2 < num_va: low = avg else: high = avg avg = (low+high)/2 print(avg)
5bb2cd18d84a087f8419d185798f550694676567
aixiu/myPythonWork
/图灵学院/python基础/ls-15-python.py
4,450
3.875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # 变量的三种用法 class A(object): def __init__(self): self.name = 'haha' self.age = 18 a =A # 属性的三种用法 # 赋值 # 读取 # 删除 a.name = '量子' # del a.name # print(a.name) # 类属性 property # 应用场景 # 对变量除了普通的三种操作,还想增加一些附加的操作,可...
ef2a30844644e63d0b76084419e4fc174d4560b9
choroba/perlweeklychallenge-club
/challenge-183/lubos-kolouch/python/ch-1.py
519
4.125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- def remove_duplicates(lst): # Convert each list to a tuple so it can be added to a set tuples = [tuple(i) for i in lst] # Create a set to remove duplicates, then convert each tuple back to a list return [list(i) for i in set(tuples)] list1 = [[1, 2], [3,...
764c12b2747c115339cab9ea7c029b6191789ca6
VigneshLearning/SeleniumPythonWorks
/Demo/InheritYMethOveridDemo.py
477
3.890625
4
class Parent: def __init__(self): print("This is Parent Class") def ParFunc(self): print("This is Parent Function") obj = Parent() obj.ParFunc() class Child(Parent): def __init__(self): print("This is Child Class") def ChildFunc(self): print("This is Child Function") ...
dc460d5b76fed59d1c37b71282e3e6561779607d
MW-2005/print
/print_secondary.py
1,026
4.6875
5
# --------------- Section 2 --------------- # # Relevant Documentation # print() # python.org | https://docs.python.org/3/library/functions.html#print # W3Schools | https://www.w3schools.com/python/ref_func_print.asp # Read about the sep argument on the W3Schools documentation. sep is an optional argum...
f302a726a04443663cd116c69ab50717c370cda6
ruanbekker/simple-etl
/src/etl.py
1,818
3.578125
4
import pandas as pd import logging def score_check(grade, subject, student): """ If a student achieved a score > 90, multiply it by 2 for their effort! But only if the subject is not NULL. :param grade: number of points on an exam :param subject: school subject :param student: name of the student ...
b9b3d875bb63bd35b5db8fb876f92ce50409c1c5
t3h2mas/gibson
/plugins/msg_stack.py
465
3.75
4
#!/usr/bin/python2 class MsgStack(object): def __init__(self): self._stack = [] def push(self, msg): self._stack.insert(0, msg) # !lifo def pop(self): return self._stack.pop() def isEmpty(self): return self._stack == [] # test if __name__ == '__main__': ...
f9f0354f3376a88bc70da4e14ce689a8c8085539
wmn7/python_project
/python_second_flask/sqlalchemy_test.py
2,823
3.640625
4
from sqlalchemy import create_engine,Column,Integer,String from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker from sqlalchemy.orm import relationship from sqlalchemy import ForeignKey engine = create_engine('mysql://root:Wangmaonan1@localhost/shiyanlou') user_data = engine...
3c77bdb32bb23f5ebc79033fbefbc5ec09588bc0
rohmdk/python-proj1
/goodmorgan.py
156
4.09375
4
#greeting = "Good morning" #print(input("what is your name ? ")) #print(greeting) name = input("Please enter your name : \n") print("Good morning," +name)
a5018330fa7123c7a25585b7d7047f501aecb7bf
kzh980999074/my_leetcode
/src/Tree/110. Balanced Binary Tree.py
1,009
3.984375
4
''' Given a binary tree, determine if it is height-balanced. ''' class TreeNode: def __init__(self,x): self.val=x self.left=None self.right=None 'false' def isbalanced(root): if not root :return True l=-1 i=0 stack=[[],[]] stack[0].append(root) while stack[i%2]: ...
d632ff768758195fefc983304238de01272faf05
QinmengLUAN/Daily_Python_Coding
/LC23_mergeKLists_heap.py
1,194
3.734375
4
""" 23. Merge k Sorted Lists Hard: Linked list, heapq My first Hard question. Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity. Example: Input: [ 1->4->5, 1->3->4, 2->6 ] Output: 1->1->2->3->4->4->5->6 """ # Definition for singly-linked list. # class ListNode: #...
86bd5697802516c3a7f2b4c9263fed46bf6ff5be
thiagor83/estudos
/PhytonExercicios/ex010.py
200
3.71875
4
n1 = float(input('Quanto dinheiro você tem ai mano? R$')) n2 = float(input('Qual a cotação do dolar hoje?')) print('Com R${:.2f} reais, você consegue comprar ${:.2f} dolares!'.format(n1,(n1/n2)))
19d18d8506d203d04fde4660f71f7fab08120d7a
UnB-KnEDLe/Regex
/regex/atos/cessoes.py
6,098
3.65625
4
import re from typing import List, Match import pandas as pd from atos.base import Atos def case_insensitive(s: str): """Returns regular expression similar to `s` but case careless. Note: strings containing characters set, as `[ab]` will be transformed to `[[Aa][Bb]]`. `s` is espected to NOT contain s...
64fe3eed495a3516b479fa128d5cc5136f1eef7f
alissonoliveiramartins/Python-Fundamentos-para-Analise-de-Dados
/Resposta_Exercicios/calculadora_v1.py
1,200
4.25
4
# Calculadora em Python # Desenvolva uma calculadora em Python com tudo que você aprendeu nos capítulos 2 e 3. # A solução será apresentada no próximo capítulo! # Assista o vídeo com a execução do programa! print("\n******************* Python Calculator *******************") def menu(): opcao = ['Soma','Subtraç...