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
0ae1145610b852e8f50363c1221cb96d74162a32
krstevkoki/vestacka-inteligencija
/lab1/tablica2.py
407
3.78125
4
# -*- coding: utf-8 -*- if __name__ == "__main__": m = input() n = input() x = input() # vasiot kod pisuvajte go tuka tablica = {} scope = range(int(m), int(n) + 1) for i in scope: result = i ** 3 tablica[result] = i if int(x) not in tablica.keys(): print("nema ...
2abf7670c4d02183632cf57708a69b8e95176d0a
GolamRabbani20/PYTHON-A2Z
/1000_PROBLEMS/ExamplesOnLists/Problem-11.py
415
3.734375
4
#Python Program to Find all Numbers in a Range which are Perfect Squares and Sum #of all Digits in the Number is Less than 10 m=int(input("Enter lower range:")) n=int(input("Enter upper range:")) x=[x for x in range(m,n+1) if (int(x**0.5)**2==x) and sum(list(map(int,str(x))))<10] print(x) ''' x=[] for i in range(m,n+...
dd857bf6348fbe9fc68affd328c24e1cb35cc085
lizhixin3016/leetcode-cn
/110.平衡二叉树.py
2,101
3.6875
4
# # @lc app=leetcode.cn id=110 lang=python3 # # [110] 平衡二叉树 # # https://leetcode-cn.com/problems/balanced-binary-tree/description/ # # algorithms # Easy (49.17%) # Likes: 209 # Dislikes: 0 # Total Accepted: 45.2K # Total Submissions: 91.2K # Testcase Example: '[3,9,20,null,null,15,7]' # # 给定一个二叉树,判断它是否是高度平衡的二叉树。...
3f0e431c42b28bc5594479fffe0eb0cc18e468d7
Shakirsadiq6/Create-Users
/Create-Users/src/WithDatabase/emails.py
556
4.3125
4
'''Email Validation''' __author__ = "Shakir Sadiq" class users_email: '''class for users email''' def __init__(self,email): '''constructor''' self.email = email email = input("Enter your email address: ") while "@" not in email: print("Your email address must have '@' in it") email = i...
20409fa8e57e35e126db9fc33a38300702db62db
jduan/learn_python_the_hard_way
/ex12.py
354
3.515625
4
# You can use 'pydoc raw_input' to get documentation from the command line. age = raw_input("How old are you? ") height = raw_input("How tall are you? ") weight = raw_input("How much do you weight? ") address = raw_input("Where do you live? ") print "So, you are %s old, %s tall, %s heavy, and you live in %s." % ( ...
a746ec1793d79679247384bcb8d9c3fed617d5fb
iagoamaro/aprendendo_python
/fatpy.py
174
4.0625
4
#calculador de fatorial fat = int(input("Digite um numero: ")) fat_total = 1 for i in range(1,fat+1): #print(i) fat_total = i * fat_total print(i, fat_total) input("")
8b98793b05a32f25b0738853bf460041d8901145
GBoshnakov/SoftUni-Fund
/RegEx/Furniture.py
526
3.578125
4
import re data = input() regex = r">>(?P<furniture>[a-zA-Z]+)<<(?P<price>\d+(\.\d+)?)!(?P<quantity>\d+)" total_money = 0 items = [] while data != "Purchase": match = re.match(regex, data) if match: current_furniture = match.groupdict() total_money += float(current_furniture["price"]) * int(c...
ba34f74ea2735e54c54e3e7889f24a6a2748c8a4
PolishDom/COM411
/basics/functions/beepbopreturn.py
599
3.875
4
def sum_weights (beepweight, bopweight): sumweight = int(beepweight + bopweight) return sumweight def calc_avg_weight(beepweight, bopweight): avgweight = (int(beepweight + bopweight) /2) return avgweight def run(): beepweight = int(input("What is beeps weight?")) print (beepweight) bopweight = int(inpu...
cebebbb9f959e581d3a237a7fbaa75eefc9fb1ef
jperrycode/full-python-scripts
/Module Scripts/abstraction.py
1,014
3.90625
4
# abstraction assignment from abc import ABC, abstractmethod # define a parent class class loan(ABC): l_amount = 5000 def loan_amount(self, l_amount): ## loan = l_amount print('Your owe {} on your car..'.format(l_amount)) return l_amount def monthly_payment(self, pay_amount): ...
1ae0bea74eadc754596700c6a5f6dfda8b35e51b
nighat3/breakout-game
/play.py
8,014
3.8125
4
# play.py # Nighat Ansari (na295), Kati Hsu (kyh24) # 8 December 2016 """Subcontroller module for Breakout This module contains the subcontroller to manage a single game in the Breakout App. Instances of Play represent a single game. If you want to restart a new game, you are expected to make a new instance of Play. ...
370fc45b3df47accb59bb98ae9b11a56f9bd5511
willxie/action-conditional-video-prediction-with-motion-equivariance-regularizer
/scripts/format_image_file_names.py
773
3.65625
4
import sys import os def is_int(s): try: int(s) return True except ValueError: return False def main(): """ Put enough prepending 0 padding according to the README """ if len(sys.argv) != 2: print("Usage: target_dir") exit() root_dir = os.getcwd() targe...
d403bbe92dc8dde267a3507c652739a0ca8becf4
wajeeh20-meet/meet2018y1lab5
/stringfun.py
89
3.609375
4
our_list = [1,2,1] if len(our_list) > 2 and our_list[0] == our_list[-1]: print(True)
4d28fed739a598dd48ee9504a81b4df526ed47db
arthtyagi/C02Emissions
/Multiple_Linear_Regression/C02Multiple.py
2,643
3.671875
4
import matplotlib.pyplot as plt import pandas as pd import pylab as pl import numpy as np # get the dataset using the link or download the dataset using curl in your Terminal curl -O https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/ML0101ENv3/labs/FuelConsumptionCo2.csv df = pd.read_cs...
4a7021073a55374c42c8d446556650a94ad7528d
s33Y377/Scripting
/Python/ItertoolsExp.py
105
3.640625
4
import itertools data = [3, 4, 6, 2, 1, 9, 0, 7, 5, 8] print(list(itertools.accumulate(data, max)))
2838860cc444b0b55b9e55c5153426e784995436
lex-koelewijn/handwritingrecog
/levenshtein.py
749
3.625
4
#Made by: s295454 #NLP, week 2 exercise 6 import sys import numpy as np def main(argv): s1 = sys.argv[1] s2 = sys.argv[2] min_distance(s1,s2) def min_distance(s1, s2): m = len(s1) n = len(s2) d = np.zeros((m+1,n+1)) for i in range(1,m): d[i,0] = i for j in range(1,n): ...
d959306eb3c33020b46ef7e88e0a6785813a5f40
duwaar/BalloonSat-Flight-Controller
/flight_controller_2.py
5,205
3.53125
4
#!/usr/bin/python3.4 ''' This is the flight controller program for a high-altitude balloon payload. The process herein allows for easy adding and removing of sensors, and simple, clear user interface on launch day. Elaine Jeffery 14 July 2017 ''' from fl_objects_2 import * def main(): #-------------------------...
64ff852d3897e637d4edd55a9953c1f5425eae0b
MisterXY89/intro-to-python
/session_4/section_1/tasks.py
871
4.1875
4
#------------------------------------------------------------------------------# # (1) # Write min. 2 functions which handle the reading, processing and visualization # of a time series of transactions for one location (dependet on an argument) # (you can use the sum, mean or median) for the transactions on one day. ...
19cab897d6ab33337061078cfeff89eea56594b7
quanee/Note
/Python/leaning python/base/Python_dict.py
302
3.609375
4
D = {'a': 1, 'd': 3, 'c': 2} print(D) Ks = list(D.keys()) Ks.sort() for key in Ks: print(key, '=>', D[key]) for key in sorted(D): print(key, '=>', D[key]) for c in 'moonboss': print(c.upper()) if 'f' in D: print(D['f']) else: print('None') value = D.get('x', 0) print(value)
f8b8bdf875b8cdbeda34e360d3950297a8fff6a1
roshangardi/Leetcode
/21.Merge Two Sorted Lists.py
2,119
4.25
4
# Developed this on my own after reading of algorithm: # Algorithm is : compare first element in each list, whichever ele is smaller, create its node and increment # the pointer for that list # Read comments for why recursive approach can lead to stackoverflow error for large lists: # https://leetcode.com/problems/merg...
3d7a0ffe60a88f50ceb3a32498299f921aeba787
ctajii/pathfinder_scripts
/poison_crafting.py
1,306
3.890625
4
def poison(): # Find original market value mvalue = input("What is the market value of the poison \n Value in GP: ") # Convert string to int mvalue = int(mvalue) # change market value to crafting value cvalue = .3333333 * mvalue difficulty_check = input("What is the DC...
d70762c81281a0edd10bee7a37907be83a7721fb
bschwyn/Think-Python
/exercises/2_Variables/exercise1.py
739
4
4
# Evaluate the following numerical expressions in your head, #then use the active code window to check your results: #This uses booleans to check whether my guess(on the right) is TRUE or FALSE # 1. 5 ** 2 print(5**2==25) # 2. 9 * 5 print(9 * 5 == 45) # 3. 15 / 12 print(15/12 == 1.25) # 4. 12 / 15 print(12/15 == ...
4c1827393ed0bae3dcb10e51acb4daf6985db686
atorch/markov_decision_process
/python/cake_eating.py
9,114
4.0625
4
import os import matplotlib.pyplot as plt import numpy as np from sklearn.linear_model import LinearRegression DISCOUNT_FACTOR = 0.9 VALUE_FUNCTION_CONSTANT_TERM = ( np.log(1 - DISCOUNT_FACTOR) + np.log(DISCOUNT_FACTOR) * DISCOUNT_FACTOR / (1 - DISCOUNT_FACTOR) ) / (1 - DISCOUNT_FACTOR) PLOT_DIR = "plots" ...
3e00e3a9107d097afa6fc17f93addffd7ddbd979
JorrgeX/CMPSC132
/Hsieh_Program9.py
3,274
3.953125
4
#Hsieh_Program9 #Yuan-Chih Hsieh #CMPSC132 Program9 import matplotlib.pyplot as plt class sales: def __init__(self, dollars, date): self.dollars = dollars self.date = date #dollars getter def get_dollars(self): return self.dollars #data getter def get_da...
11734e142f8710406d7003e27ca5000bf28356c7
mengyeli/HackerRank
/Python/DataTypes/NestedLists.py
204
3.640625
4
L = [] for _ in range(int(input())): L.append([input(), float(input())]) score = sorted(list(set([mark for name, mark in L])))[1] print('\n'.join([name for name, mark in sorted(L) if mark == score]))
b40ffe5b7b7a83f71824f279cc36527c12b33ad1
krasigarev/functions
/def_square.py
595
4.09375
4
n = int(input()) # вариант 1 def print_dashes(num): print("-"*(num*2)) def print_body(number): for i in range(1, number - 1): print("-" + "\\/"*int((2*number-2)/2) + "-") print_dashes(n) print_body(n) print_dashes(n) print("--"*2) # вариант 2 def print_dashes(num): print("-"*(num*2)) de...
7ef3b3d9ca4778da0e93147c13d545db8e315ef9
pombredanne/suffix_tree-1
/test_suffix_tree.py
2,749
3.5
4
import unittest from suffix_tree import SuffixTree class SuffixTreeTestCase(unittest.TestCase): def test_init(self): st = SuffixTree('foo') rows = st.get_rows() self.assertEqual(len(rows), 5) # root plus len(foo) + null term self.assertEqual(len(rows[0]), 1) # The root level ...
57bd1595ead671cbc0118ef3de8a5a018d693a32
sinooko/tinkering
/star.py
4,343
3.796875
4
from planet import Planet from roman import toRoman from random import randrange, randint from solar_calc import namer, log, radius_gen def planet_pop(mass, num=None, star_name=None): """ Takes in a number, star mass, and the star's name Returns a list of planet objects Roche L...
9f789d705f17c187306d3023e89460955c6f786d
Runthist/like
/krasov2.py
471
3.984375
4
a = float(input('Введите координаты центра круга:\nx = ')) b = float(input('y = ')) с = float(input('Радиус круга: ')) if с > 0: x = float(input('Введите координаты точки:\nx = ')) y = float(input('y = ')) if (((x-a)**2+(y-b)**2)<=(с**2)): print('Точка попала в круг!') else: print('Точка...
c10b0e4daf1735f0e4384fe51ce65b87bb0825f3
santiagoom/leetcode
/solution/python/155_MinStack_2.py
756
3.703125
4
from typing import List from utils import * class MinStack: def __init__(self): self.stack = [] self.min_stack = [] def push(self, x: int) -> None: self.stack.append(x) if not self.min_stack or x <= self.min_stack[-1]: self.m...
4a828ad2d0b8e6b6ff18f7b14ac139a631ef6ea9
RobolinkInc/RoPi
/RoPi_Python_Samples/1_topIRSensors.py
470
3.5
4
import RoPi as rp ropi = rp.RoPi() #create a while loop so we can read the top IR sensors while(1): leftIR, middleIR, rightIR = ropi.readTopIRsensors() print(leftIR, middleIR, rightIR) #this will print the information #you can test it this by placing your fingers #in front of the smart inventor bo...
581f61c95f2cec725e1101f08fa3f3a7e74d4d76
Darshitpipariya/Information_technology
/playfair.py
3,632
3.59375
4
def key_genarator(key): alphabet='abcdefghiklmnopqrstuvwxyz' key=key.replace(" ","") table=[] for char in key.lower(): if char not in table: if char=='j': char='i' table.append(char) for char in alphabet: if char not in table: table...
b4e18ca9e22ecde70bfa17eb2b596fa5846d6de8
PnuLikeLion9th/Summer_algorithm
/joonghoo/1주차/0621 행렬의 덧셈.py
551
3.8125
4
# 프로그래머스_행렬의 덧셈_자료구조_레벨 1 # 자료구조 리스트를 이용하여 같은열, 같은행에 있는 값을 더해주면 된다. def solution(arr1, arr2): answer = [[]] for i in range(len(arr1)): # arr1의 1차원 list 갯수만큼 반복 for j in range(len(arr1[i])): # arr[i]의 길이만큼 반복 arr1[i][j] += arr2[i][j] # arr1와 arr2의 같은열, 같은행의 원소를 더해준다 return arr1 arr...
34787232a2c7603d09d79e47f5819af3761176b2
savanibharat/PythonPrograms
/com/Core/Searching/RecursiveBinarySearch.py
847
3.96875
4
''' Created on Feb 8, 2014 @author: Savani Bharat ''' def binary_search(number_list, key, lower_bound, upper_bound): if (upper_bound < lower_bound): return None else: middle_position = lower_bound + ((upper_bound - lower_bound) / 2) if number_list[middle_position] > key: re...
9d24312111414e67a1d03b3f279a707dd2d5a6fa
samedhaa/Problem-Solving
/Random Questions from books/LinkedLists & Arrays/(2.1).py
862
3.671875
4
''' Write code to remove duplicates from an unsorted linked list. Follow up : how would you solve this problem is a temporary buffer is not allower ''' class Node: def __init__(self, val): self.val = val self.next = None def traverse(self): node = self while node != None: print(node.val) node = n...
7eb550737172eee56de37a9c71928cecb2a98c39
ppnp-2020/02-exercicios-funcoes
/saque/funcoes.py
569
3.8125
4
saldo = 1000 numero_conta = '1234-5' senha_conta = '112233' def efetuar_saque(): valor = input('Digite o valor desejado: ') if not valor.isnumeric(): print('O valor digitado é inválido') return valor = float(valor) if valor <= saldo: print('Saque efetuado') else: print('Saldo insuficiente...
29815dca943113fa31358d86bb17baf8ef6368f6
moontree/leetcode
/version1/457_Circular_Array_Loop.py
1,786
4.1875
4
""" You are given an array of positive and negative integers. If a number n at an index is positive, then move forward n steps. Conversely, if it's negative (-n), move backward n steps. Assume the first element of the array is forward next to the last element, and the last element is backward next to the first ele...
efd6df70b69011835ba89a46941a9697bfa933a6
LonelyRider-cs/Low_Resource_MT
/python/pipeline/pipeline_tokenizer.py
1,312
3.703125
4
from nltk.tokenize import word_tokenize from nltk.tokenize import RegexpTokenizer #this file is called when needing to tokenize anything. #the language's three letter code is used to distinguish between different types of tokenizers #to add a new langauge tokenizer follow the syntax below and replace 'tag' with the l...
f688bc7238a07c93485c2cd57e09044849c9b00b
GuanzhouSong/Leetcode_Python
/Leetcode/119. Pascal's Triangle II.py
371
3.5
4
class Solution: def getRow(self, rowIndex): """ :type rowIndex: int :rtype: List[int] """ rowIndex += 1 if rowIndex is 0: return [] res = [1] for i in range(1, rowIndex): temp1 = res + [0] temp2 = [0] + res res = [temp1[i] + temp2[i] for i in range(len(temp2))] ...
1398d87af178f0755b20592c064f4141e4773779
AdamZhouSE/pythonHomework
/Code/CodeRecords/2972/60678/294074.py
246
3.625
4
def findDifferIndex(s, t): for i in range(len(s)): if s[i] != t[i]: return i return len(s) n = int(input()) if n == 2: for i in range(n): s = input() t = input() print(s) print(t)
8d18fd059ff3de3a7634166389a03fe8c6a8b6ef
wanda93/Exercise-Chapter-4
/4.6.py
438
3.703125
4
def total (hour,rate): #bagian dari pendeklerasian fungsi jam = float(hour) byr = float(rate) if jam < 40: #bagian pengecekan byarn = jam * byr print byarn else : nrmal = 40 * byr ext = jam - 40 rte = (byr*3/2) * ext total = nrmal + rte print "pay :", float(total) ...
e5372e17bf9fa0e0337ed84cb4bfec86264bc88f
gurusms/stepik-base_and_use-python
/lesson13-step9.py
203
3.65625
4
def closest_mod_5(x): # y = int(x / div) * div + div y = x+5-x%5 if y % 5 == 0: return y return "I don't know :(" i = int(input ()) print (f"решение = {closest_mod_5(i)}")
5ece1f55959663326f7e20894ac5d7129f43375b
UendelSoares/Atividades_Python
/Lista de atividades 1/Atividade 02.py
401
3.875
4
#2. Fazer um algoritmo que leia o valor do salário mínimo e o valor do salário de uma #pessoa. Calcular e escrever quantos salários mínimos essa pessoa ganha. salario = float(input("Qual seu salario (R$)? ")) s_min = 1100 if (salario < s_min): print("Você recebe menos que um salario minimo") else: t_salario = ...
2afcb05988a59fa6e6d9d080ef88fced9c83ebe0
ronak007mistry/Python-programs
/palindrome.py
161
4.28125
4
string = input("Enter the string: ") rev_string = string[::-1] if string == rev_string: print("String is Palindrome ") else: print("String is not Palindrome")
efd3a4d8c53ce3baa477a6f6ed0174f0fe34a168
Ogaday/aoc19
/day_2_1.py
1,029
3.9375
4
""" Solution to Day 2 Part I of the Advent of Code https://adventofcode.com/2019/day/2 To get the answer, run: python -m day_2_1 """ from itertools import zip_longest from typing import List class OpCodeError(Exception): """ Raise when an invalid opcode is encountered. """ def run(intcode: List[i...
abe1211d505721bce3bf37cd5633cf31097c56d7
DarshanaPorwal07/Python-Programs
/%Calc.py
532
4.03125
4
total=int(input("enter the total marks:")) sub1=int(input("enter the marks of 1st subject:")) sub2=int(input("enter the marks of 2ns subject:")) sub3=int(input("enter the marks of 3rd subject:")) sub4=int(input("enter the marks of 4th subject:")) sub5=int(input("enter the marks of 5th subject:")) marks_obtained...
e1da8793a96bcca9eeed3836dc90565105508914
sanketag/startxlabs-assignment
/minTime.py
1,772
3.96875
4
"""Time required by all the customers to checkout.""" def get_checkout_time(cust,c_r): rem = c_r-1 """Recursive function to process next customers.""" def fun(e,f): nonlocal rem """Checking if suitable amount of cash registers are available""" if f==0: ...
0f81635e6ef977e7c31a35363d8382fe1d70195b
cesarco/MisionTic
/s5/5.1_input.py
106
3.703125
4
numero = input("Por favor digite un número: ") print("El número que el usuario ingreso es: ", numero)
08cf5a07d3fdfeb45b310796d0af907284c76dd9
tushargoyal02/PythonBasicsToAdVance
/sortingFunctions.py
511
4.1875
4
# sort the data structure in python nums = [1,0,-1,23,445] #using sorted function to sort the values - Return a list output =sorted(nums) print(output) #sorting result in reverse order output =sorted(nums, reverse=True) print(output) #sorting the data as per the length of the string #-- HERE WE HAVE K...
09e682fafcf6a4cf0dea5f064563967d8b2a89e2
justin-zimmermann/coursera-Data-Manipulation-at-Scale-Systems-and-Algorithms
/thinking-in-mapreduce/multiply.py
982
3.78125
4
import MapReduce import sys """ Word Count Example in the Simple Python MapReduce Framework """ mr = MapReduce.MapReduce() # ============================= # Do not modify above this line def mapper(record): matrix = record[0] row = record[1] column = record[2] value = record[3] if matrix == 'a':...
2b9703089160f683f812bd7652de065df3a1093c
spandanag333/python-programming-tasks
/task6.py
438
4.0625
4
A = int(input("enter the length of the first side of the triangle :")) B = int(input("enter the length of the second side of the triangle :")) C = int(input("enter the length of the third side of the triangle :")) if A==B and B==C and C==A: print("EQUILATERAL TRIANGLE") elif A!=B and B!=C and C!=A: print(...
ee15c8ead7f3e7ec6edff1572906a5a8b5cf6d35
chrislevn/Coding-Challenges
/Blue/Stack&Queue/Mass_of_Molecule.py
690
3.625
4
formula = input() result = 0 new_arr = [] for i in range(len(formula)): if formula[i] == "C": new_arr.append(12) if formula[i] == "O": new_arr.append(16) if formula[i] == "H": new_arr.append(1) if formula[i].isnumeric(): if formula[i-1] != ")": new_arr.appen...
8ec6285f15711b4090cd655372fe62935d44919c
hariomvc/python
/Savings_account.py
819
3.96875
4
annual_Inter_rate = 0 class SavingAccount: def set_balance(self, balance): self.saving_balance = balance def cal_monthly_interest(self, annual_Inter_rate): self.saving_balance += self.saving_balance * annual_Inter_rate /12 saver1 = SavingAccount() saver2 = SavingAccount() saver1.se...
e742f6301f749f957d2a01ff0c5087ee43ce4ac0
sendurr/spring-grading
/submission - Homework3/set2/JEREMY W ABRAMS_11058_assignsubmission_file_abramsjw_homework3/abramsjw_homework3/P1.py
329
3.796875
4
# Jeremy Abrams # CSCE 206 # Homework 3 - P1.py # February 18 2016 def area(vertices): x1 = vertices[0][0] x2 = vertices[1][0] x3 = vertices[2][0] y1 = vertices[0][1] y2 = vertices[1][1] y3 = vertices[2][1] area = (0.5)*((x2*y3) - (x3*y2) - (x1*y3) + (x3*y1) + (x1*y2) - (x2*y1)) return area print area([[0,...
6f7c8757988f6374e915560267af5dfd34c69b32
gunnerVivek/Foretelling-Retail-price-using-Multivariate-Regression
/utility_functions.py
1,591
3.890625
4
''' This module defines the various utility functions needed in the project. ''' import numpy as np import pandas as pd def threshold_data(data): ''' Apply thresholding to data. Threshold values are decided by using IQR. Maximum threshold value is 3rd Quartile adde...
35df57baf6fefa64ee4ef97d32123dd9a82969f0
dangrenell/exercism
/raindrops/raindrops.py
361
3.625
4
def convert(number): return_string = '' factor_dict = {3: "Pling", 5: "Plang", 7: "Plong"} try: for factor, string in factor_dict.items(): return_string += string if number % factor == 0 else '' return str(number) if return_string == '' else return_string except: ...
abe7e86864388aac5be95aab89f0317f37a567c8
SThornewillvE/Udemy_LazyProgrammer_Courses
/Linear_Regression/R_sq.py
722
3.609375
4
# -*- coding: utf-8 -*- """ Created on Thu Feb 7 10:49:43 2019 @author: sthornewillvonessen """ # Import Packages import numpy as np def R_sq_eval(y, y_pred): """ Compares predicted independant values and compares it with the real value to compare the R-squared value. :returns: r_sq ...
1dcebde42e7512b66620deb4ab99c6491a7c2060
Aasthaengg/IBMdataset
/Python_codes/p02256/s461624254.py
240
3.65625
4
def gcd(x, y): if x < y: tmp = x x = y y = tmp while y > 0: r = x % y x = y y = r return print(x) x_y = input() tmp = list(map(int, x_y.split())) x = tmp[0] y = tmp[1] gcd(x, y)
cb056e5898becf7722fef06fb09dc529973156bf
sirius0503/my_python_crash_course_codes
/transportation.py
223
3.921875
4
vehicles = ["trains" , 'vistara flight' , 'bullet train' , 'bicycle' , 'fast cars'] for index in range(len(vehicles)): print("I like to travel by " + vehicles[index] + " since ,I haven't driven cars or motorcyles ,etc")
7bd34ff0009b598c8185c67308a78a0fe5deb90d
SamuelMarsaro/Listas-Python-CESAR
/Lista 7/sam/q2_sam.py
847
3.734375
4
genetic_map = input() base = input() list_order = [] first = genetic_map[0] i = 0 biggest_sequence = -1 big_sequence = 0 if base in genetic_map: # Finding the position and the lenght of the biggest base sequence for character in genetic_map[1:]: if character == first[-1]: first +=...
d07527da91f4b3b54ef9ecb6c7cecb8d6c732f2b
fourohfour/HubskiScript
/Hubski/Hubski.py
1,637
3.53125
4
import requests import json from sys import exit from operator import itemgetter #Ask user for pub ID inputURL = input("Please paste the Hubski URL here: ") #Check if it's a full URL. If so, slice it to only have the pub ID left. if inputURL.startswith("https://hubski.com/pub?id="): pubID = inputURL[26:] else: ...
20ab9ad351538e367b9c65edee43a7659f0a908d
AngelSosaGonzalez/IntroduccionMachineLearning
/Machine Learning/IntroduccionML/Algoritmos/IntroKNNClasific.py
3,286
3.890625
4
""" Introduccion a la clasificacion: Este proyecto pondrmos ya a prueba lo aprendido en los otros proyectos de introduccion a los modulos encargados en Machine Learning, pero ahora no enfocaremos en la clasificacion pero antes de esto, ¿Que es clasificacion?: En pocas palabras un sistema de clasificación predice una c...
175bf3ad3c5888c6e9b7bbdccc5090980569fab9
Pigiel/udemy-python-for-algorithms-data-structures-and-interviews
/Mock Interviews/Social Network Company/On-Site-Question-2.py
587
3.65625
4
#!/usr/bin/env python3 def solution(id_list): # Initiate unique ID unique_id = 0 # XOR for every ID in id list for i in id_list: print('Current ID:\t' + str(i)) print('Unique ID:\t' + str(unique_id)) print('XOR result:\t' + str((unique_id^i))) # XOR operation unique_id ^= i return unique_id print('#...
857a99f2e300cf22d440a7596534962fdc8a1f52
FancyYan123/LeetcodeExercises
/lengthOfLongestSubstring.py
1,075
3.796875
4
""" 给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。 示例 1: 输入: "abcabcbb" 输出: 3 解释: 因为无重复字符的最长子串是 "abc",所以其长度为 3。 示例 2: 输入: "bbbbb" 输出: 1 解释: 因为无重复字符的最长子串是 "b",所以其长度为 1。 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/longest-substring-without-repeating-characters 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 """ class Solution: de...
04d8ea5e254d434f0ef9f4a93fd9bf3febf49b05
DawnEve/learngit
/Python3/pythonCodeGit/day11-RegExp/re2_split.py
785
3.875
4
import re # 用正则表达式切分字符串比用固定的字符更灵活 r='a b c'.split(' ') print('1: ',r) #['a', 'b', '', '', 'c'] #无法识别连续的空格,用正则表达式试试: r=re.split(r'\s+', 'a b c') print('2: ',r) # ['a', 'b', 'c'] #无论多少个空格都可以正常分割。 #加入,试试: r=re.split(r'[\s\,]+', 'a,b, c d ,e fg') print('3: ',r) #再加入;试试: r=re.split(r'[\s\,\;]+', 'a,b;; c d') p...
e352dd1f5e45fe4ade46c5e20b6c100046797af5
sibhatmeq/Python_simple-projects
/Slider.py
551
3.5
4
from tkinter import * from PIL import ImageTk, Image root= Tk() root.title("sliders in python") root.geometry("500x500") vertical = Scale(root, from_=0, to=200).pack() def slide(): my_label = Label(root, text=horizontal.get()).pack() root.geometry(str(horizontal.get()) + "x" + str(vertical.get...
18fc753813b05b116e0b06e5cbaae9232b03dc1f
adithya1010/Numerics-Solver
/Bigdata/pearson_correlation.py
1,464
3.53125
4
import numpy as np import math from numpy.core.fromnumeric import var print("Pearson Correlation (r)\nEnter the x values :") x = [] temp = float(input()) while(temp!=-1): x.append(temp) temp = float(input()) print("\nEnter the y values :") y = [] temp = float(input()) while(temp!=-1): y.append(temp) t...
a125f72b1242f8793626f03cfd4ec920f2b09bd7
tabish606/python
/threelarge.py
336
4.21875
4
def greater(num1,num2,num3): if num1>num2 and num1>num3: return f"{num1} is greater" elif num2 > num3: return f"{num2} is large" return f"{num3} is large" a = int(input("enter first number : ")) b = int(input("enter second number : ")) c = int(input("enter third number : ")) print...
b9160c083aead29a15a5dacc7f85ac22f33dbd0e
Cptgreenjeans/python-workout
/ch02-strings/e08_sort_string.py
215
3.9375
4
#!/usr/bin/env python3 """Solution to chapter 2, exercise 8: strsort""" def strsort(a_string): """Takes a string as input, returns a string with its characters sorted. """ return ''.join(sorted(a_string))
2158e87d8dada59686aa0c7202de825cf17acb5a
Marumarum/algorithms-practice
/#7Reverse_Integer.py
298
3.8125
4
def reverse(x): if x >= 2**31-1 or x <= -2**31: return 0 else: if x > 0: rever = int(str(x)[::-1]) else: rever = -int(str(-x)[::-1]) if rever >= 2**31-1 or rever <= -2**31: return 0 return rever print(reverse(120000000000))
770b3029b0da01d7f99e118bc8534187075b9507
philiprj/math_4_ml
/distances.py
8,452
3.625
4
# coding: utf-8 # ## Distances and Angles between Images import matplotlib as mpl import matplotlib.pyplot as plt import numpy as np import scipy import sklearn from ipywidgets import interact from load_data import load_mnist MNIST = load_mnist() images = MNIST['data'].astype(np.double) labels = MNIST['target'].as...
2c8a11a731093485853d385c5a822de8e53d2f7d
juliandunne1234/pands-problems-2020gmit
/w4_collatz/collatz.py
383
4.34375
4
#This program takes a number and # completes a calculation based # on whether the number is even or odd. x = int(input("Please enter any number: ")) # Even number is divided by 2; # odd number is * 3 and then add 1. while x != 1: if x == 0: break elif x % 2 == 0: x = x / 2 else: ...
a8ca9cc1a40397654c9791ec592176daa437bf14
fgokdata/python
/extra/def.py
131
3.84375
4
def multiply(mylist): mult = 1 for x in mylist: mult *= x return mult list1 = [3, 5, 6] print(multiply(list1))
0bbb8d620a8b0252054802c284035ed0004048be
qichaozhao/MIT-600v2
/lec4_problems/ps2/ps2_newton.py
2,819
4.03125
4
# 6.00 Problem Set 2 # # Successive Approximation # def evaluate_poly(poly, x): """ Computes the polynomial function for a given value x. Returns that value. Example: # >>> poly = (0.0, 0.0, 5.0, 9.3, 7.0) # f(x) = 7x^4 + 9.3x^3 + 5x^2 # >>> x = -13 # >>> print evaluate_poly(poly, x) # f(-...
be35f85f1b6859335374959ff46d1c850c46c17c
douradodev/Algoritmos-ADS
/ALG_2019_VICTOR_DOURADO-20210622T123110Z-001/ALG_2019_VICTOR_DOURADO/Atividade_Fabio01/Fabio01_16_AREA-QUADRADO.py
162
3.671875
4
# Entrada lado= int(input("Digite a medida do lado do quadrado: ")) # Processamento area= lado**2 # Saída print("A área do quadrado é {} .".format(area))
e8fc585e04e258910256e881025b1ab08a060ccf
songponlekpetch/coin_change
/src/coin_change.py
1,134
3.625
4
class CoinChange: def __init__(self, num_denomination, money, denomination): self.num_denomination = num_denomination self.money = money self.denomination = self._cut_coin_not_compute(denomination) def _cut_coin_not_compute(self, denomination): money = self.money for coi...
7519c4f6bf50c475c2b597cf4862dabba703cb6c
JustinZeyeum/Python3_Learning
/userInput.py
340
4.40625
4
# A program asking user to input hours and rate per hour, # which display the pay on the screen hrs = input("Enter Hours:") # user input hours rate = input("Enter Rate:") # user input pay rate gross_pay = float(hrs) * float(rate) # program compute the gross pay calculation print("Pay:", gross_pay) # the gross pay is ...
b47aed781388cd6c991c56dfb51d74877616f138
Ethan2957/p03.1
/square_diff.py
871
4.25
4
""" Problem: The function sq_diff takes a number, n, and then: * Adds all of the numbers from 1 to n and squares the answer. * Adds all of the square numbers from 1*1 to n*n It then subtracts the second number from the first and prints the answer. For example: sq_diff(4) = (1 + 2 + ...
5cb79f80399bd51c417b4c1d354585e58a6a71b8
anish531213/Interesting-Python-problems
/ads.py
350
3.53125
4
import os def rename_files(): file_list = os.listdir("/home/anish/Documents/prank") print(file_list) cur_dir = os.getcwd() os.chdir("/home/anish/Documents/prank") for file_name in file_list: os.rename(file_name, file_name.translate(None, "0123456789") os.chdir(cur_dir) rename_...
346afe7c4658363984e716c793bbc87856d70108
focks98/TesteFundamentos
/question5.py
1,018
3.9375
4
def multMatrix(matrixA, matrixB): matrixResult = [] for i in range(len(matrixA)): vectorAux = [] for j in range(len(matrixB[0])): sumAux = 0 for k in range(len(matrixB)): sumAux +...
8fa909ac2202ce75995408d2150755753751a2a8
eduvallejo/gauss
/pythonFractal.py
2,292
4.125
4
# <-- in python, hashtags are used to tell the computer that a line is not worth reading # much like in social media ##to run this you code need, python 2.7 and numpy ## here we have a scripted program, the computer reads each line, line by line, and then #excecutes them ## this section imports libraries t...
d140691a8644f3f254f12dd252dd8370bf6dd83f
wfeng66/DB_Course
/HW/Assignment1/HW1_weicong_#4.py
418
4.09375
4
# Write a program that accepts a sentence and calculate the number of uppercase letters and lowercase letters. # Suppose the following input is supplied to the program. # Input: Hello World # Output: UPPERCASE: 1, LOWERCASE: 9 s = input("Please input a string: ") cUpp, cLow = 0,0 for i in s: if i.isupper(): ...
5aa0aaed074667ae52a38736a4c3507d01c07166
SoniaZhu/Lintcode
/linkedin/191. Maximum Product Subarray [M].py
643
3.53125
4
# pay attention to 0 class Solution: """ @param nums: An array of integers @return: An integer """ def maxProduct(self, nums): # write your code here if not nums: return 0 res = prevMax = prevMin = nums[0] for num in nums[1:]: if num > 0: ...
11f434e211696e4d29a73b3ff21878b093faed1e
gamedevpy/python-projects-for-kids
/python-projects-for-kids/backpack1.py
6,503
3.796875
4
##------------------------------------------------------ ## ## By: Jessica Ingrassellino ## Publisher: Packt Publishing ## Pub. Date: April 14, 2016 ## Web ISBN-13: 978-1-78528-585-1 ## Print ISBN-13: 978-1-78217-506-3 ## ## Python Projects for Kids ## Chapter 7 - What's in your backpack? ## ## Did not follow the recip...
d94bc89530529c5c0f5de33ddf7dd4afb73aa184
operation-lakshya/BackToPython
/MyOldCode-2008/JavaBat(now codingbat)/Logic/luckySum.py
349
3.75
4
a=int(raw_input("\nEnter the value containing A\t")) b=int(raw_input("\nEnter the value containing B\t")) c=int(raw_input("\nEnter the value containing C\t")) if (a==13): print "\nThe sum is: 0" elif (b==13): print "\nThe sum is:",a elif (c==13): print "\nThe sum is:",a+b else: print "\nThe sum is:",a+b+c raw_inp...
b355bd5a519d65ea35d4e8d5e6a384424d79130a
lorischl-otter/Intro-Python-II
/src/player.py
1,237
3.75
4
# Write a class to hold player information, e.g. what room they are in # currently. class Player(): def __init__(self, name, location, items=[]): self.name = name self.location = location self.items = items # def try_direction(self, user_action): # attribute = user_action + '_...
d28a40a2bcc907182e7f131cbbed62f4cb871607
qmnguyenw/python_py4e
/geeksforgeeks/python/python_all/159_9.py
1,163
4.34375
4
Python | Sort all sublists in given list of strings Given a list of lists, the task is to sort each sublist in the given list of strings. **Example:** **Input:** lst = [['Machine', 'London', 'Canada', 'France'], ['Spain', 'Munich'], ['Australia', 'Mandi']]...
1fc6f6a2eda50f4e8029d1146530762bebaafd38
sumanth8ch/Python
/heap.py
926
3.78125
4
""" Max heap is implemented. For min heap, reverse the heapify function.""" def heapify(ar,size,i): largest = i lc = 2*i+1 rc = 2*i+2 if lc<size and ar[lc]>ar[i]: largest = lc if rc<size and ar[rc]>ar[largest]: largest = rc if largest != i : ar[i],ar[largest] = ar[l...
6c67b4004c296b7b85c553873f77fb90c0629b31
DragonWarrior15/tensorflow_and_mnist
/01_tensorflow_core.py
2,884
4.21875
4
# taken from # https://www.tensorflow.org/get_started/get_started # the central unit of data in tensorflow is called tensor # rank of a tensor is the no of dimensions in it # tensorflow graph is created using computational nodes import tensorflow as tf node1 = tf.constant(3.0, tf.float32) node2 = tf.constant(4.0) # ...
6a0c4897a20935cad7962c7270cd25fbf0d244dc
prathamesh201999/python1
/Exception_handling.py
365
3.90625
4
a = int(input('Enter the first value')) b = int(input('Enter the second value')) try: print("Connection open") print(a/b) k = int(input('Enter the value')) print(k) except ZeroDivisionError as e: print("Zero is not a valid input",e) except ValueError as e: print("Give the integer as input",e) ...
bb244880046b70001ab2353bf87b9708a29f3b72
Aniket-Bhagat/Computing_tools
/Files/Q15.py
407
3.9375
4
import sqlite3 conn = sqlite3.connect('company.db') x=raw_input('Employees having alphabets in there First Name\nAlphabet1 : ') y=raw_input('Alphabet2 : ') cursor = conn.execute('''SELECT F_NAME FROM EMPLOYEES WHERE F_NAME LIKE '%{}%' AND F_NAME LIKE '%{}%';'''.format(x,y)) # print "First name of all employee...
0ff4eb91c18c217fccce8250b86f4125e9018d28
adam-holder/python-4-everybody-michigan
/Python Code/Courses 1-4/numbersInHaystack.py
750
3.9375
4
import re #I called the file "actualfile.txt" name = input("Enter file:") handle = open(name) numberSum = 0 #This code goes line by line and finds each number in the line using Regular Expressions #for each line it saves a list in findNumbers (skips the line if there are no results to find) for line in handle: li...
168d811f616b28a9ad338c195785ed6760fe069c
adhishvishwakarma/DS-Algo
/Recursion/print_n.py
194
3.578125
4
def print_n_1(n): if n == 0: return print(n) print_n_1(n-1) print_n_1(10) def print_1_n(n): if n == 0: return print_1_n(n-1) print(n) print_1_n(10)
afd2b11dfaf18a6ec6bc4d2ea7d5f5979ec1d3ad
FedorPolyakov/python-algorithms
/Lesson3/les3_task5.py
1,326
4.15625
4
#В массиве найти максимальный отрицательный элемент. # Вывести на экран его значение и позицию в массиве. # Примечание к задаче: пожалуйста не путайте «минимальный» и «максимальный отрицательный». # Это два абсолютно разных значения. import random SIZE = 1_000 MIN_ITEM = -1_000 MAX_ITEM = 1_000 array = [random.rand...
1e6d2cba06eff3f5d66107b19f00db3d27beb431
inest-us/python
/tiny_python/list.py
460
3.859375
4
people = ['Paul', 'John', 'George'] people.append('Ringo') print('Yoko' in people) #False for i, name in enumerate(people, 1): print('{} - {}'.format(i, name)) print(people[0]) #Paul print(people[-1]) #len(people) - 1 => Ringgo print(people[1:2]) #['John'] print(people[:1]) #implicit start at 0 => ['Paul'] print...
92d70c1468dfa691a3360ed9fa11783bc1dd36fd
stkobsar/MasterDegreeDS
/MasterDegreeDS/second_semester_2020/DataScience_programming/activity_1/activity_7.py
626
3.515625
4
import pandas as pd import re import ssl ssl._create_default_https_context = ssl._create_unverified_context json_data = "https://data.nasa.gov/resource/y77d-th95.json" df_nasa = pd.read_json(json_data) #Names with more than 5 characters in the dataframe # Make a regular expression # to accept string starting with ...
4b3b35a33069d5dedc9a538629fb3bd8092f8807
qwe321as/Python
/06_함수/Ex02_func.py
829
4.09375
4
#-*- coding:utf-8 ''' Created on 2020. 10. 30. @author: user ''' def add(a,b=99,c=100): return a+b+c print(add(1)) print(add(1,2)) print(add(1,2,3)) def func(*args): for i in args: print(i,'/',end=' ') print('-----') func(1,2) func(1,2,3,4,5) func() d = {'b':2,'a':1,'c':3} def...
888bf34a36f7c72fd034733e5ed8606b4978b217
nerolin91/pythonPractice
/addValueAllCols.py
340
3.53125
4
def addValuesInAllCols (mat): colSum=[] sum=0 for i in range (len(mat)): for j in range (len(mat)): sum+=mat[j][i] colSum.append(sum) sum=0 return colSum mat = [ [1,2,3], [10,20,30], [100,200,300] ] list_sums_cols = addValuesInAllCols(mat) print (list_sums_cols) ...
4bca31d8426933bdce30a0a93e22cf0b9bcd0cbb
miguelesli/Prueba-Python
/ejercicio8d2upperylower.py
297
3.9375
4
### en una cadena se le puede cambiarel las letras de mayusculaa minuscula con Upper y lower mensaje7="HOLA MUNDO" mensaje7=mensaje7.lower() print(mensaje7) mensaje7=mensaje7.upper() print(mensaje7) mensaje2=input() mensaje2=mensaje2.lower() print("m2",mensaje2) input("::::::")
5790e7f5bebd1ec6b9bac89ee78951e0b7ab8457
tijus/machine-learning-projects
/Linear Regression/Main/sgd/sgd.py
2,049
3.578125
4
import numpy as np import matplotlib.pyplot as mp import random import os class SGD(): ''' Name: sgd type: class objective: This function is used to instantiate SGD class to train data using stochastic gradient descent ''' def __init__(self): ''' C...
49f532079dff2a55d5e2d07851049f2228de1710
DiaAzul/healthdes
/healthdes/Check.py
6,459
3.796875
4
""" HealthDES - A python library to support discrete event simulation in health and social care """ from typing import ( TYPE_CHECKING, ClassVar, ContextManager, Generic, MutableSequence, Optional, Type, TypeVar, Union, ) class Check: """ Class containing functions to check whe...