blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
3.06M
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
3.06M
0e1ce99931ee6f4f9b9a6ecc04078b90035c8c1a
Zhenxingzhang/py2ml
/LinearRegression/LR.py
3,375
3.6875
4
from numpy import loadtxt, zeros, ones, array, linspace, logspace from pylab import scatter, show, title, xlabel, ylabel, plot, contour import numpy as np #Evaluate the linear regression def compute_cost(X, y, theta): ''' Comput cost for linear regression ''' #Number of training samples m = y.size ...
421b98ca633b94e3f60f2887c00b0f1997a6beec
xredian/EpamPython2019
/01-Data-Structures/hw/secter_deze/secret_deze.py
1,220
3.796875
4
pizza = {"dough", "tomatoes", "pepperoni", "ground pepper", "sweet basil", "a lot of cheeeese", "onion", "garlic", "salt", "oregano"} shaverma = {"lavash", "cucumbers", "tomatoes", "sauce", "fried chicken", "onion", "cabbage"} if pizza.isdisjoint(shaverma) is True: print('имеют общие элементы') else: ...
d919843b86ecfbea850a34a3d0461abcdd9a05e3
AndreyOliveira2019/FinalRound-Python-Lesson
/code.py
3,243
3.890625
4
# Item 1 da Lista de exercícios - Você tem uma lista de número: [6,7,4,7,8,4,2,5,7, 'hum', 'dois']. #A ideia do exercício é tirar a média de todos os valores contidos na lista, porém para fazer o cálculo #precisa remover as strings. lista = [6, 7, 4, 7, 8, 4, 2, 5, 7, 'hum', 'dois'] lista.remove('hum') lista.remove(...
39074f8e4e73c89668c56da2a4c07e2c4fa1beaa
wencaizhang/learn-python
/demo.py
1,198
3.65625
4
# 从 flask 这个框架中导入 Flask 这个类 from flask import Flask, redirect, url_for import config # 初始化一个 Flask 对象 # Flask() 需要传递一个参数 __name__ # 1. 方便 flask 框架寻找资源 # 2. 方便 flask 插件比如 Flask-sqlalchemy 出现错误的时候寻找问题所在的位置 app = Flask(__name__) app.config.from_object(config) # @app.route 是一个装饰器 # @开头,并且在函数上面,就说明是一个装饰器 # 这个装饰器的作用是做一个 u...
df968f4a057fb8d98111729759b1ef5ddb2eb2b2
dirtypy/python-train
/cn/yanxml/hello/firstStep.py
265
4.125
4
#!/usr/bin/python3 #coding=utf-8 #Python3 编程第一步 #Python3 first step of programming #Fabonacci series a,b=0,1 while b < 10: print (b) a,b=b,a+b; i=265*256 print ("i 's value is : ", i); a,b=0,1 while b<1000: print(b,end=",") a,b=b,a+b
f76d7cbb421a9c7e5515977fadb12346e14fc908
dirtypy/python-train
/chenwj/loop.py
179
3.90625
4
arr = ["arr1", "foo", "bar"] for i in arr: print(i) print(range(5)) print(list(range(5))) print("--------") limit = 5 while limit > 0: print("haha") limit -= 1 print("-------")
bd4fc37ac97ba3a9a02d8ccf7b271f862d342ec7
qinritukou/Streamlit-APP
/iris-eda-app.py
3,587
3.609375
4
import streamlit as st import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import os from PIL import Image, ImageEnhance, ImageFilter """ A Simple Iris EDA App""" st.title("Iris EDA App") st.text("Built with Streamlit") # Headers and Subheader st.header("EDA App") st.subheader("Iris Dataset...
11100cc48dcbfdadf4b9c920e3cde5f69605450b
jackle98/Binary-Search-Tree
/Binary_Search_Tree.py
14,067
4.15625
4
class Binary_Search_Tree: # TODO.I have provided the public method skeletons. You will need # to add private methods to support the recursive algorithms # discussed in class class __BST_Node: # TODO The Node class is private. You may add any attributes and # methods you need. Recall that attributes in ...
6520dce3670879db07f871dd84414d9681254226
eglrp/gps_simulater
/com/nuaa/gps/nrc/utils/file_reader_utils.py
704
3.6875
4
import os def readFile(filePath): try: file_object = open(filePath, "r", encoding="utf-8") all_the_text = [] line = str.lower(str.strip(file_object.readline())) while line: all_the_text.append(line) line = str.lower(str.strip(file_object.readline())) exc...
e874316e44e77730423ffe10d62363800ca80191
rajpranesh/email_slicer
/slicer.py
204
4.0625
4
#!usr/bin/env python3 # pip install regex import re email=input(" Enter the Email:") # spliting the email mail=re.split('@', email);print( "\n User name is :" ,mail[0],"\n Domain name is :",mail[1])
4f99e50f21e0f3d8204bb9c8b275f851a0d8d75e
DDaaaaann/Project_Euler
/python/exc6.py
690
3.96875
4
# Sum square difference # # The sum of the squares of the first ten natural numbers is, # 1^2 + 2^2 + ... + 10^2 = 385 # # The square of the sum of the first ten natural numbers is, # (1 + 2 + ... + 10)^2 = 55^2 = 3025 # # Hence the difference between the sum of the squares of the first ten natural # numbers and the sq...
afebc658717b8f3badb5ee990c9d9e48ef32bc0e
makyca/Hacker-Rank
/Power-Mod_Power.py
286
4.25
4
#Task #You are given three integers: a, b, and m, respectively. Print two lines. #The first line should print the result of pow(a,b). The second line should print the result of pow(a,b,m). a = int(raw_input()) b = int(raw_input()) m = int(raw_input()) print pow(a,b) print pow(a,b,m)
e0f20d297d8816da124a9f4e8a41a23e680e95b7
makyca/Hacker-Rank
/Sets-Symmetric_Difference.py
719
4.28125
4
#Task #Given 2 sets of integers, M and N, print their symmetric difference in ascending order. The term symmetric difference indicates #those values that exist in either M or N but do not exist in both. #Input Format #The first line of input contains an integer, M. #The second line contains M space-separated integers...
8f6a0b68353c38fad53150c779444b96abc1b8e5
levi-terry/CSCI136
/hw_28JAN/bool_exercise.py
1,284
4.15625
4
# Author: LDT # Date: 27JAN2019 # Title: bool_exercise.py # Purpose: This program is comprised of several functions. # The any() function evaluates an array of booleans and # returns True if any boolean is True. The all() function # evaluates an array of booleans and returns True if all # are True. # Function to eval...
1c73961f953b4686742f415bc9aaf2fe389f8d14
levi-terry/CSCI136
/hw_30JAN/recursion_begin.py
1,860
4.15625
4
# Author: LDT # Date: 27JAN2019 # Title: recursion_begin.py # Purpose: This program implements two functions. # The first function accepts an int array as a parameter # and returns the sum of the array using recursion. The # second function validates nested parentheses oriented # correctly, such as (), (()()), and so o...
7868d39dfc5a0e63481d605c23d303303c851bb9
levi-terry/CSCI136
/hw_28JAN/three_true.py
912
4.34375
4
# Author: LDT # Date: 27JAN2019 # Title: three_true.py # Purpose: This program implements a function which returns # True if 1 or 3 of the 3 boolean arguments are True. # Function to perform the checking of 3 booleans def three_true(a, b, c): if a: if b: if c: return True ...
f9646e355ca1ee3d740e122152613929508bb03d
theprogrammer1/Random-Projects
/calculator.py
342
4.34375
4
num1 = float(input("Please enter the first number: ")) op = input("Please enter operator: ") num2 = float(input("Please enter the secind number: ")) if op == "+": print(num1 + num2) elif op == "-": print(num1 - num2) elif op == "/": print(num1 / num2) elif op == "*": print(num1 * num2) else: print(...
c9d95a53a7d91e4b1b5e869087d44c05b0b26c85
theprogrammer1/Random-Projects
/watercheck.py
425
4.09375
4
# Just a simple water check!:) print("Welcome to WaterCheck") goal = input("How much ml of water do you plan to drink today? ") print("Come after a day and then enter how much you drank") water = input("How much ml of water have you drank today? ") if goal > water: print("You have completed your goal") if goal < wat...
4850957307ebf48b4b68b3fba2c2b8eab6c50d33
khsoumya9/myfirstrepo
/h1.py
125
3.734375
4
a=input() b=input() ss='''Hello a b! You just delved into python.''' ss=ss.replace("a",a) ss=ss.replace("b",b) print(ss)
01bce66b0481bae0cc2aa36695e5c41ac141545d
Gage77/School-Work
/Spring 2018/Principles of Programming Languages/python_project_2/yield_blac9605.txt
2,838
4
4
################################################## # Functions from class ################################################## # Function to determine if a passed in number is a prime number # NOTE: This function was developed in class by Dr. Cheng def is_prime(n): if n < 2: return False i = 2 while ...
a99115780a4b7f04114673fc6b89ea37eeed30c0
bhargavi-Thotakura/beginner_python
/score.py
490
4
4
#print(type(score)) try: score = float(input("Enter Score: ")) #score = float(score_pt) #print("Calculationg Grade") if 0.0 < score < 1.0 : if score >= 0.9 : print(score,'A') elif 0.8 <=score: print('B') elif 0.7 <=score: print(score,'C') elif 0.6 <=sc...
badd56b2e9f432c29e29017921f0fefa39429136
CankayaUniversity/ceng-407-408-2017-2018-project-what-will-my-gpa-be
/src/reports/StudentSemester.py
4,971
3.5625
4
import csv import pandas as pd path="data/grade2.csv" def get_semester_success(studID,course,filename): grades= pd.read_csv(path) grades.sort_values("StudID", inplace=True) grades = grades.drop(grades[grades.Grade == 'S'].index) grades = grades.drop(grades[grades.Grade == 'U'].index) grades = ...
66afd8353ae48aa03ac42674765b59b18884d19a
wjwainwright/ASTP720
/HW1/rootFind.py
2,848
4.28125
4
# -*- coding: utf-8 -*- def bisect(func,a,b,threshold=0.0001): """ Bisect root finding method Args: func: Input function that takes a single variable i.e. f(x) whose root you want to find a: lower bound of the range of your initial guess where the root is an element of [a,b] b...
94931a464b5629d682c7b028165f634ffb14258c
rishik-bot/Fibonacci-Series
/Fibonacci Series.py
182
3.625
4
#!/usr/bin/env python # coding: utf-8 # In[ ]: n=int(input()) #write your code here x=[0,1] for i in range(n-2): x.append((x[i]+x[i+1])) for i in range(n): print(x[i])
1aeca2090233ef2eb5eb8357c10c8fef50813def
leilanorouzi/radar_imaging_improvement
/geometry.py
4,107
3.765625
4
import numpy as np # import matplotlib.pyplot as plt # from sympy import * import math import cmath def vec_mag(a:list) -> list: ''' Takes a vector as a list and calculates the magnitude of the vector :param a: the list of components of a vector :return: the magnitude of the vector ''' return...
62f3757e7a3995704446919760897ad09d656bd7
jdemeo/CS7641-Machine-Learning
/Assignment2/travelingsalesman.py
7,118
3.640625
4
# traveling salesman algorithm implementation in jython # This also prints the index of the points of the shortest route. # To make a plot of the route, write the points at these indexes # to a file and plot them in your favorite tool. import sys import os import time import csv import java.io.FileReader as FileReader...
fe0e8af3b6d088f25a8726e32abe1ab08c03b8c3
vickyjeptoo/DataScience
/VickyPython/lesson3a.py
381
4.1875
4
#looping - repeat a task n-times # 2 types :for,while, #modcom.co.ke/datascience counter = 1 while counter<=3: print('Do Something',counter) age=int(input('Your age?')) counter=counter+1 #update counter # using while loop print from 10 to 1 number=11 while number>1: number=number-1 print(number...
e9a0af2257266fa452fddf4b79e1939784bca493
vickyjeptoo/DataScience
/VickyPython/multiplication table.py
204
4.21875
4
number = int(input("Enter a number to generate multiplication table: ")) # use for loop to iterate 10 times for i in range(1, 13): print(number, 'x', i, '=', number * i) #print a triangle of stars
32bdec09e8dc8ef94efd14ff0ab50b7585fdda7d
vickyjeptoo/DataScience
/VickyPython/lesson5.py
1,511
4.25
4
#functions #BMI def body_mass_index(): weight=float(input('Enter your weight:')) height=float(input('Enter your height:')) answer=weight/height**2 print("Your BMI is:",answer) #body_mass_index() #functions with parameters #base&height are called parameters #these parameters are unknown,we provide them...
1b8c5a9c64bfdc6ba17b366609f40b1e019734e6
karthikbhoshle/Color_guessing_Game.
/colourgame.py
1,705
3.84375
4
from tkinter import * import time import random colour=['Red','blue','Green','Pink','Yellow','Orange','Purple','Brown'] score1=0 timeleft=60 global st def startgame(event): if timeleft==60: countdown() if timeleft!=0: nextcolour() def nextcolour(): global score1 ...
82375abb8be64e12d97b4ae42817d7f291517647
SohaHussain/30-days-of-ML
/cross validation.py
1,243
3.53125
4
# In cross-validation, we run our modeling process on different subsets of the data to get # multiple measures of model quality. import pandas as pd # read the data data = pd.read_csv("file") # select subset of predictors cols_to_use = ['Rooms','distance','landsize','buildingarea','yearbuilt'] x = data[co...
cbb152031fb1a9b78eb596d07caa517d830748f0
Aamecstha/pythonClass
/Tasks/task8.py
450
3.90625
4
# 5. Print the sum of given lists: # a) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] # b) [1, 2, ‘3’, 4, 5, ‘6’, 7, 8, 9, 10] # Note: Both lists should have same sum a=[1,2,3,4,5,6,7,8,9,10] b=[1,2,'3',4,5,'6',7,8,9,10] sumA=0 sumB=0 for i in range(len(a)): sumA+=a[i] print(f"the sum of list a is: {sumA}") for j in range(len...
6c29609d8a5ab1027cdff8124b794110b5a9e7fa
Aamecstha/pythonClass
/functionPart3.py
1,132
4.1875
4
# def main(): # def inner_func(): # print("i am inner function") # # def outer_func(): # print("i am outer function") # # return inner_func,outer_func # # print(main()) # inf,onf=main() # inf() # onf() # def main(n): # def add(a,b): # return a+b # def sub(a,b): # ...
89317aed4fce90370625b512b6d4b782cfd46b9a
Aamecstha/pythonClass
/closure.py
146
3.640625
4
def multiplier(n): def times(a): return a*n return times times3=multiplier(3) print(times3(10)) del multiplier print(times3(10))
002dded20087e4723842ac4074a5f75c23814a88
Aamecstha/pythonClass
/functionPart2.py
559
3.78125
4
# def func(*args): # return args # # a,b=func(1,2) # print(a) # print(b) # #having dictinary paramter using double * # def dfunc(**args): # print(args) # # dfunc(name="amit",contact=9813) # #referencing function # def func(args): # print(args) # # f=func # f(1) #example of referencing def welcome(nam...
a4322a82e093af0b6a1a4acdfcbb5540b7084db5
PragmaticMates/python-pragmatic
/python_pragmatic/classes.py
675
4.25
4
def get_subclasses(classes, level=0): """ Return the list of all subclasses given class (or list of classes) has. Inspired by this question: http://stackoverflow.com/questions/3862310/how-can-i-find-all-subclasses-of-a-given-class-in-python Thanks to: http://codeblogging.net/blogs/1/...
d721726856b94d33bfd6035d80a03140e73c7377
gsime1/recurse_centre_application
/game_of_fifteen/supporting_funcs.py
1,916
3.96875
4
#!/usr/bin/python3 ############### # generalised # # funcs # ############### def is_legal_argv(arg_vec, desired_len, arg_to_check, within_range): """ generalised func to check that argument vector of a program contains # elements and one of them is within a range. :param arg_vec: argv. :param desired_len: ...
45d4b3553e5287745a658037afb082414ff1fdca
tommidavie/Practise-Python
/Mulit_di_lists.py
626
3.921875
4
def dub_loop_print(L): for i in range(0, len(L)): output = "{} :{}".format(i, L[i]) print(output) for j in range(0,len(L[i])): output = "{} : {}".format(j, L[i][j]) print(output) dub_loop_print() def main(): my_list=[ ["Nia", "Blond", "16"], ...
bbf2d3478a74caf1156c2a174a2674366244857c
Code-JD/Python_Refresher
/02_string_formatting/code.py
731
4.21875
4
# name = "Bob" # greeting = f"Hello, {name}" # print(greeting) # name = "Ralph" # print(greeting) # ---------------OUTPUT------------- # Hello, Bob # Hello, Bob # name = "Bob" # print(f"Hello, {name}") # name = "Ralph" # print(f"Hello, {name}") # ---------------OUTPUT------------- # Hello, Bob # Hello, Ralph ...
03b2d33c5226d40fd6697a86a906ac944696c183
MrDaGree/nts370
/project3.1/main.py
554
3.5
4
import requests from bs4 import BeautifulSoup # Get page contents for song lyrics and then make soup page = requests.get('https://www.jiosaavn.com/lyrics/no-sugar-coated-love-lyrics/M1s8ZCR0BHI') soup = BeautifulSoup(page.text, 'html.parser') #use soup to find the p tag with the class 'lyrics' lyrics = soup.find("p",...
3136aa7493867c41daa510e21bb3f75439104472
ptersnow/zumbis
/Lista 02/questao04.py
272
3.96875
4
# -*- coding: utf-8 -*- a = float(input("Informe o primeiro número: ")) b = float(input("Informe o segundo número: ")) c = float(input("Informe o terceiro número: ")) maior = a if maior < b: maior = b if maior < c: maior = c print "O maior valor é %f" %maior
706574f380f628cd5e45dc2ebda0a62b974745f2
ptersnow/zumbis
/Lista 01/questao06.py
211
3.59375
4
# -*- coding: utf-8 -*- dst = float(input("Informe a distância a ser percorrida (km/h): ")) vel = float(input("Informe a velocidade média (km/h): ")) print "O tempo de viagem vai ser de %3.2f" %(dst / vel)
cdd8c4cf7a4780746d96e86b6a0a2c3deda95483
ptersnow/zumbis
/Lista 02/questao01.py
378
3.96875
4
# -*- coding: utf-8 -*- a = float(input("Informe o primeiro lado: ")) b = float(input("Informe o segundo lado: ")) c = float(input("Informe o terceiro lado: ")) if (abs(b - c) > a) or (a > b + c): print "Não é um triângulo" else: print("É um triângulo "), if (a == b) and (a == c): print "equilátero" elif b =...
cd48013f2f21d47eaff5ff24c9bee5f2df376d08
ptersnow/zumbis
/Lista 01/questao04.py
297
3.734375
4
# -*- coding: utf-8 -*- salario = float(input("Informe o salário: ")) porcentagem = float(input("Informe a porcentagem de aumento: ")) aumento = salario * porcentagem / 100 print "O salário vai ser aumentado em %3.2f e o novo valor do salário vai ser de %3.2f" %(aumento, salario + aumento)
e3730d1cd31561e569fc89e8b92aad2e58359817
prashant523580/python-tutorials
/exercise/cube_finder.py
110
3.546875
4
def cubes_fun(n): cubes = {} for i in range(1, n+1): cubes[i] = i ** 3 return cubes print(cubes_fun(10))
b09b2657f56cb03fae84b598ce256753b6eb4571
prashant523580/python-tutorials
/conditions/neg_pos.py
336
4.4375
4
#user input a number ui = input("enter a number: ") ui = float(ui) #converting it to a floating point number #if the number is greater then zero # output positive if ui > 0: print("positive number") #if the number is less then zero #output negative elif ui < 0: print("negative number") #in all other case else: ...
4f22f4049c54ffec182d62dc07f1860a0db63411
prashant523580/python-tutorials
/list.py
4,164
4.34375
4
#list : list is a collection which is ordered and changeable. Allows duplicate members #tuple : Tuple a is collection which is ordered and unchangeable. Allows duplicate members #set : Set is a collection which is unordered and unindexed. No duplicate members #dictionary: Dictionary is a collection which is unordere...
489611d9ef3bb631d70001481204933797dbf743
jessepisel/pyvista
/examples/01-filter/distance-between-surfaces.py
3,014
4
4
""" Distance Between Two Surfaces ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Compute the average thickness between two surfaces. For example, you might have two surfaces that represent the boundaries of lithological layers in a subsurface geological model and you want to know the average thickness of a unit between those boundari...
0840ba2e96e38dbc2e0380930fa8336a0eade6d9
qa1010/lclnew101
/crypto/caesar.1.py
666
3.921875
4
def alphabet_position(letter): alphabet = "abcdefghijklmnopqrstuvwxyz" position = alphabet.index(letter.lower()) return position def rotate_character(char, rot): if not char.isalpha(): return char else: alphabet = "abcdefghijklmnopqrstuvwxyz" position = alphabet_position(cha...
514b84c88a3267724ec94f30dc2317e00ab911cb
deepak1214/CompetitiveCode
/LeetCode_problems/add-binary/Solution.py
869
3.9375
4
# -*- coding: utf-8 -*- """ Created on Mon Oct 5 2020 @author: Shrey1608 """ ''' Given two binary strings, return their sum (also a binary string). The input strings are both non-empty and contains only characters 1 or 0.''' # Approach : 1) basic binary conversion into int then compute the sum and then convert agai...
ebf441da39af7584d30fd716f1c74400ce069600
deepak1214/CompetitiveCode
/Hackerrank_problems/Sherlock and valid strings/solution.py
809
4.0625
4
# Logic # Create a frequency list for all alphabets, # next compare the frequency of all alphabets from b to z with # frquency of a, iteratively. If the frequencies don't match # subtract the a's frequency from the current letter's frequency. # Compare the frequency of the letter with a's frequency again, if they # don...
16b70546373b4ae43fc32b86721ddfd48c85a6f1
deepak1214/CompetitiveCode
/LeetCode_problems/kth_factor_of_n/solution.py
717
3.53125
4
# This the main class for the solution class Solution: # This class takes two integer n and k as input def kthFactor(self, n: int, k: int) -> int: # Here n is the number and k is the kth factor. ls = [] # Initialize the empty list i = 1 while...
3cc16bd73aad0ed9d2dcd3b10a4baa6c3109c901
deepak1214/CompetitiveCode
/LeetCode_problems/Find_the_Difference/solution.py
480
3.671875
4
from collections import Counter class Solution: def findTheDifference(self, s: str, t: str) -> str: cts=Counter(s) ctt=Counter(t) for i in ctt.keys(): if ctt[i]>cts[i]: return i return "" # make a frequency map of both the strings # iterate over keys of st...
73de9b28562810d43cd8658762da3d17b3928cac
deepak1214/CompetitiveCode
/Hackerrank_problems/Solve_me_first/Solution2.py
232
3.6875
4
#Author : @shashankseth01 #Simple solution for Solve_me_first in python language a=int(input("First integer")) #input first integer b=int(input("Second integer")) #input second integer print(a+b) #Calculate and print sum
35042b6261b0945c17e7d916a520258f8f6cd259
deepak1214/CompetitiveCode
/Hackerrank_problems/Find_a_point/solution.py
766
3.546875
4
#!/bin/python3 import os import sys import math # # Complete the findPoint function below. # def findPoint(px, py, qx, qy): # calculate the distance between x axis and y axis dis_x = qx-px dis_y = qy-py # return it by adding the last/outer point (qx and qy) # with the distances in each axes re...
60d4056c02f09768f15b63263fcc1932ffba1e57
deepak1214/CompetitiveCode
/Codeforces_problems/Domino Piling/solution.py
477
3.609375
4
m, n = map(int, input().split()) #taking m and n as input #since each small domino is of size 2x1, it can be said that the total number of dominos which can be fitted #is equal to MxN divided by 2, but this can give a decimal answer. What the question asks for is the maximum #number of complete squares. #converting o...
d2255ab562eeadc3c2bb54352ef41d82f4bcbb17
deepak1214/CompetitiveCode
/Codeforces_problems/Team/solution.py
447
3.984375
4
n = int(input()) #taking number of test cases as input sures = [] #list for appending sureties of all 3 count = 0 for i in range(0,n): x = [int(x) for x in input().split()] #taking 3 elements as list together and appending in list sures[] sures.append(x) if x.count(1)>=2: #if more than 2 people are sure, th...
37db4f12c64e3b39d0b94aec53181f943b1f22b4
deepak1214/CompetitiveCode
/Codeforces_problems/Reverse Binary Strings/solution.py
1,173
3.71875
4
# We need to make our string alternating, i. e. si≠si+1. When we reverse substring sl…sr, # we change no more than two pairs sl−1,sl and sr,sr+1. Moreover, one pair should be a # consecutive pair 00 and other — 11. So, we can find lower bound to our answer as maximum # between number of pairs of 00 and number of pair...
4b465cd68d64ec76f22a248d2354650ab16fa7f4
deepak1214/CompetitiveCode
/Hackerrank_problems/kangaroo/solution3.py
757
3.984375
4
''' LOGIC: First, we compare the first kangaroo's location with the second one. if same then they will meet at the starting point. Second, if first kangaroo's location and rate bothe are heigher or visa-verse then there is no chance of them meeting at same place. Else if their location are ...
18a181e6826df72713c9e72d744869d9bca0d27d
deepak1214/CompetitiveCode
/GeeksForGeeks/Blum Integer/solution.py
686
3.765625
4
# Function to cheek if number is Blum Integer def isBlumInteger(n): prime = [True]*(n + 1) # to store prime numbers from 2 to n i = 2 while (i * i <= n): if (prime[i] == True) : # Update all multiples of p for j in range(i * 2, n + 1, i): prime[j] = False i = i + 1 # to check if the giv...
27f45ed864265007ea2374663ead7353d2ac6434
deepak1214/CompetitiveCode
/Codeforces_problems/Way too long words/solution.py
427
3.75
4
n = int(input()) #input number of test cases words = [] #list of all test cases for i in range(0,n): word = str(input()) words.append(word) #appending test cases in list for word in words: if len(word)<=10: #if word length less than 10 print(word) else: print(word[0]+str((len(word)-2)...
6d8d75053d9d281db48f32327598b55e1010ee78
deepak1214/CompetitiveCode
/InterviewBit_problems/Sorting/Hotel Booking/solution.py
1,298
4.34375
4
''' - A hotel manager has to process N advance bookings of rooms for the next season. His hotel has C rooms. Bookings contain a list A of arrival date and a list B of departure date. He wants to find out whether there are enough rooms in the hotel to satisfy the demand. - Creating a function hotel which will take 3 ...
874cedd8b735f1de2254b0b794aca9cb9287b5fd
deepak1214/CompetitiveCode
/LeetCode_problems/Array Partition 1/solution(1).py
425
3.8125
4
#we first sort the array, then we traverse the array by a step of 2 hence we get the required sum. we need the minimum value of a pair #so if the array is [2,1,3,4] it sorts to [1,2,3,4] then it takes the sum of 1 and 3 which is required. class Solution: def arrayPairSum(self, nums: List[int]) -> int: nums=...
f04d14e394c9dbd416600c6a182c00b1aa9e7a3e
deepak1214/CompetitiveCode
/Hackerrank_problems/MinimumHeightOFTriangle/solution.py
189
3.78125
4
import math # To use ceil function b, a = map(int, input().split()) # To take input h = (2*a)/(b) # Getting height if h > int(h): print(math.ceil(h)) else: print("%.0f" % h)
4eb966b642158fd2266ae747d4cd6fcf694acfe2
deepak1214/CompetitiveCode
/LeetCode_problems/Invert Binary Tree/invert_binary_Tree.py
1,436
4.125
4
from collections import deque class TreeNode: def __init__(self,val): self.val = val self.left = None self.right = None def insert(root,node): if root is None: root = node else: if root.val < node.val: if root.right is None: ...
63dbb827fb90c21fbbebcf701b7af3bfe57c2a33
deepak1214/CompetitiveCode
/Codeforces_problems/Young Physicist/solution.py
382
3.640625
4
n = int(input()) # no. of vectors sumx = 0 sumy =0 sumz = 0 # take coordinates of vector and add it to the # sum of respective coordinate for i in range(n): x,y,z = map(int, input().split()) sumx += x sumy += y sumz += z if sumx == 0 and sumy == 0 and sumz == 0 : print("YES") # A body is at equ...
c36dabe9eea95263cf06357b2af587e472bba5cd
deepak1214/CompetitiveCode
/Hackerrank_problems/loops/Solution1.py
319
4.09375
4
if __name__ == '__main__': n = int(input()) for integer in range(n): #run the loop for n times. square = integer * integer # multiply integer * integer which will give you square of number and store it into square variable. print(square) # print the result.
d4cc2c4c13be0e76bb0b78f50f32dacef61b63ee
deepak1214/CompetitiveCode
/Hackerrank_problems/counting_valleys/solution.py
1,605
4.125
4
# Importing the required Libraries import math import os import random import re import sys # Fuction For Counting the Valleys Traversed. Takes the number of steps(n) and The path(s[D/U]). Returns the Number. def countingValleys(n, s): count = 0 number_of_valleys = 0 # Initialized Variables...
e55e8eaa27eb6c68240a0822e94abdb9d3d557be
strawlab/braincode
/braincode/dice.py
1,625
3.640625
4
from __future__ import division import numpy as np def dice_coefficient(A, B): """find dice distance between sets of ints A and B A and B are each a sequence of ints: >>> A = {1, 3, 4, 9} >>> B = {3, 5, 9} >>> result = dice_coefficient( A, B ) >>> result == 4.0/7.0 True """ overl...
26614f5cbe266818c5f34b536b9f921c922a18d2
WSMathias/crypto-cli-trader
/innum.py
2,012
4.5625
5
""" This file contains functions to process user input. """ # return integer user input class Input: """ This class provides methods to process user input """ def get_int(self, message='Enter your number: ', default=0, warning=''): """ Accepts only integers """ hasInputN...
a5fdc1f7df72593019f30b58daf3592d561dafa1
No31LE/Lessson_2
/Score_Tester_thingy.py
240
4
4
a = float(input('Math Score')) b = float(input('English Score')) if a >= 90 and b >= 90: print('You got 1 billon dolars') elif a <= 89 and b <= 89: print('here is the extra homework') elif a <= 89 or b <= 89: print('再加油')
4568b974c04565f28d350c3138cbbe250170577b
983bot/pyneng
/06_control_structures/task_6_2b.py
1,234
3.75
4
# -*- coding: utf-8 -*- """ Задание 6.2b Сделать копию скрипта задания 6.2a. Дополнить скрипт: Если адрес был введен неправильно, запросить адрес снова. Ограничение: Все задания надо выполнять используя только пройденные темы. """ check = False while not check: ip = input("enter IP address: ") ipcheck = ip...
b76b9aaa2581473624e311da1306aff5bedc5e0d
luckcul/LeetCode
/algorithms/Implement Queue using Stacks/ImplementQueueUsingStack.py
1,276
4.21875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Date : 2016-11-30 21:13:57 # @Author : luckcul (tyfdream@gmail.com) # @Version : 2.7.12 class Queue(object): def __init__(self): """ initialize your data structure here. """ self.stack = [] def push(self, x): """ ...
474fc7b19b2ed4e0503b438c2aeed857ff82d5b1
luckcul/LeetCode
/algorithms/Merge Sorted Array/MergeSortedArray.py
705
3.859375
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Date : 2016-11-10 12:32:46 # @Author : luckcul (tyfdream@gmail.com) # @Version : 2.7.12 class Solution(object): def merge(self, nums1, m, nums2, n): """ :type nums1: List[int] :type m: int :type nums2: List[int] :type n: i...
8536c4a3c8b820e85032ae33f26e5bdee12da50a
luckcul/LeetCode
/algorithms/Lowest Common Ancestor of a Binary Tree/LowestCommonAncestorOfABinaryTree.py
973
3.96875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Date : 2016-12-08 14:41:40 # @Author : luckcul (tyfdream@gmail.com) # @Version : 2.7.12 # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class S...
072a260cbc74dccd5ab9298e4cadd77816fd5161
luckcul/LeetCode
/algorithms/Valid Sudoku/ValidSudoku.py
1,548
3.609375
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Date : 2017-01-18 21:39:19 # @Author : luckcul (tyfdream@gmail.com) # @Version : 2.7.12 class Solution(object): def isValidSudoku(self, board): """ :type board: List[List[str]] :rtype: bool """ ret = True for i in ...
0eff36426cf8db8a1c68275d1381f123eeaae419
j611062000/leetcode
/Medium/300_Longest Increasing Subsequence.py
2,593
4.0625
4
# binary search function # Input: array, target element, lower bound and upper bound # Output: the position for insertion def BS(arr, element, lo, hi): while lo <= hi: median = (lo + hi) // 2 pivot = arr[median] # We don't take any action if the element is already in the array # Thus...
67ca7730a218ab769922c10e2ba9156e771047f6
skemaite/Vestigia
/login.py
1,661
4.09375
4
from tkinter import * class LoginWindow: def __init__(self): self.win = Tk() # reset the window and background color self.canvas = Canvas(self.win, width=600, height=500, bg='white') self.canvas.pack(expand=YES, fill=BOTH) # show window in center of the screen ...
9869ffeb1565bdb2454e1b10a900e66fcb7fbfde
SharvaniPratinidhi/Minesweeper
/DrawGraphs.py
1,008
3.5
4
import matplotlib.pyplot as plt import pandas as pd import numpy as np FinalScoreAverage = [] numberOfMines = [2, 4, 6, 8, 10, 12, 14, 16] dataMinesweeperWithMines = pd.read_csv("MinesweeperStatsWithMines.csv") FinalScoreAverageWithMines = [] dataMinesweeper = pd.read_csv("MinesweeperStats.csv") for number in...
8b4c3cbade5d37f12cd2c6423346c605f2c30c81
Basicula/Labs
/4thCourseS2/AI/ScheduleGenerationGeneticAlgorithm/lesson.py
319
3.53125
4
class Lesson: def __init__(self, room, time, teacher, group, subject): self.room = room self.time = time self.teacher = teacher self.group = group self.subject = subject def __repr__(self): return self.subject.name + "\n" + repr(self.room) + "\n" + self.teacher
bfcddfa1d60791fb41302d2c159e2474862a8b42
Artork/learn-homework-1
/3_for.py
1,238
3.84375
4
""" Домашнее задание №1 Цикл for: Оценки * Создать список из словарей с оценками учеников разных классов школы вида [{'school_class': '4a', 'scores': [3,4,4,5,2]}, ...] * Посчитать и вывести средний балл по всей школе. * Посчитать и вывести средний балл по каждому классу. """ def main(): scool_10 = [ {'s...
3e217032e4ae721c1f79ead362958b8cb89a6ed2
0ce38a2b/MITx-6.001
/Problem Set2/Problem 2.py
1,068
4.0625
4
''' Now write a program that calculates the minimum fixed monthly payment needed in order pay off a credit card balance within 12 months. By a fixed monthly payment, we mean a single number which does not change each month, but instead is a constant amount that will be paid each month. Start with $10 payments per mont...
20191d04dad06de1f7b191ed7538828580eac557
jeremycross/Python-Notes
/Learning_Python_JoeMarini/Ch2/variables_start.py
609
4.46875
4
# # Example file for variables # # Declare a variable and initialize it f=0 # print(f) # # # re-declaring the variable works # f="abc" # print(f) # # # ERROR: variables of different types cannot be combined # print("this is a string" + str(123)) # Global vs. local variables in functions def someFunction(): glo...
6ec438602e86c1eeebbab11746d4445b84e0187a
jeremycross/Python-Notes
/Essential_Training_BillWeinman/Chap02/hello.py
365
4.34375
4
#!/usr/bin/env python3 # Copyright 2009-2017 BHG http://bw.org/ x = 42 print('Hello, World. %d' % x) #you can use ''' for strings for '"' for strings, either works # above line is legacy from python 2 and is deprecated print('Hello, world. {}'.format(x)) # format is a function of the string object print(f'Hello, world...
898a5ee2154ab6b1600cfd98a36223e58b7865c2
itb-ie/turtle-geometry-book
/chapter1.py
28,012
3.703125
4
import time import turtle from spanish_text import text class Chapter1(): def __init__(self, screen, font, font2, sleep_time): self.screen = screen self.font = font self.font2 = font2 self.sleep_time = sleep_time if self.sleep_time > 0:\ self.draw_speed = 1 ...
b6b54c7b8a99785ed3946f870e435f9dd0230251
LizaChelishev/homework2111
/question1.py
1,352
4
4
class Grade(): def __init__(self, id, subject_name, student_id, grade): self.id = id self.subject_name = subject_name self.student_id = student_id self.grade = grade def __str__(self): return f'Hello student: {self.student_id}, {self.id}/t your grade in {self.subject_name} is:{...
6a2928e4bfce469b9681a4f263dd43d95b0d5c7f
AmiMunshi/mypythonprojects
/semiprime
1,014
4.15625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Sep 5 15:16:46 2019 @author: maulik """ def prime(num): for i in range(2,num): if num % i ==0: #print("Not prime") return False break else: return True #print("prime") def semiprime(...
0db21245eb1b59e9be8b81d6f5cc5f9af796324d
Varunb002/Auto-Rearranger
/auto-rearranger.py
4,546
3.765625
4
#code written by Varun Salian import os, shutil #imports operating system and file move modules y = input("ENTER THE DIRECTORY PATH\t : ") #Directory where the files should be rearranged os.chdir(y) #Change Current directory to the above specified path z = y+"\Apps and Games" #Folder names for Apps and Games(Spec...
b7cc1493e75d86e8a485c20ab1695cdc1e6cd47e
NMRayhan/python-Programming
/1stProgram.py
386
3.75
4
print("I'm Nur Mohammad Rayhan", end=", ") print("I'm Studying Software Engineering", end=", ") print("I'm always Speed my Time With My Laptop Because I Love My Laptop") number1 = 10 number2 = "Hello" n = type(number2) print(n) n = type(number1) print(n) n = type(002.972) print(n) n = type(bool) print(n) a = 1 b =...
037c1f60407a74eec26dbd89a1df79dd1eb527f2
iamdlfl/ChordProTransposer
/definitions.py
10,041
4.0625
4
import os import os.path from os import path import re """Definitions This section defines various functions and variables. Functions file_name() determine_direction() determine_halfsteps() key_test() new_song_file() transposition_function() key_test_final() Variables newsong \S+...
706a49e9ac5c97d20df4505c7e08b9d08dc0f1d0
max4211/arabic-digit-recognition
/src/d02_intermediate/data_summary.py
1,747
3.59375
4
from matplotlib import cm from matplotlib import colors as mcolors from matplotlib import colorbar import matplotlib.pyplot as plt # to view graphs """The goal of this file is to explore differences among digits for normalization e.g. # of blocks, average blocks, variance in blocks, etc.""" DATA_PATH = "data...
6b0321d1262d8095a1240afb806161cbc6b0b1fe
FranciscoPereira987/TpAlgo1
/mezcla.py
2,387
3.59375
4
def abrir_archivos(l_ar_entrada): """ [Autor: Ivan Coronel] [Ayuda: Recibe una lista con nombres de archivos csv. Los abre y devuelve una lista con sus manejadores de archivo.] """ l_manejadores = [] for ruta in l_ar_entrada: l_manejadores.append(open(ruta, "r"))...
9fbd24524c7fbeec9a79c7f6a2ecdc1d6992ab08
Crewcop/pcc-exercises
/chapter_three_final.py
822
4.21875
4
# 3-8 # list of locations destinations = ['london', 'madrid', 'brisbane', 'sydney', 'melbourne'] print(destinations) # print the list alphabetically without modifying it print('\nHere is the sorted list : ') print(sorted(destinations)) # print the original order print('\nHere is the original list still :') print(dest...
b54af1405cc5f73c587a8cecdad00c57dce43b17
nikipr1999/Python-Patterns
/Pyramid.py
326
3.59375
4
n=6 for i in range(n): for j in range(2*n): if(j>=(n-i) and j<=(n+i)): print('*',end=' ') else: print(' ',end=' ') print() for i in range(n): for j in range(2*n): if(j>=(n-i) and j<=(n+i)): if (j-(n-i))%2 == 0: print('*',end=' ') else: print(' ',end=' ') else: print(' ',end=' ') p...
d01085794db2c0a08953b8ac6e23bc5d69ba4036
naosz/machinelearning_beginning
/regressiondemo.py
1,477
3.71875
4
#learning to us regression modell #first thing i realized is i dont know shit about regression, time for youtube import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import numpy as np from sklearn import datasets, linear_model import pandas as pd from sklearn.model_selection import train_test_split...
cb8de3f51ed304f477061e8fd2f2a9aff3859dce
Valetron/PAVY
/task.py
14,364
3.65625
4
############## # 11.09.2019 # ############## import random def task3(): print("Задача №3\n") cubeEdge = int(input("Ребро куба: ")) V = cubeEdge ** 3 S = (cubeEdge ** 2) * 4 print("Объем куба - {}, площадь боковой поверхности - {}\n".format(V, S)) def task4(): print("Задача №4\n") num1 = i...
ece713949a6fe5d6007d8b6f0e4df72ec7324d60
XilongPei/py2asqlana
/OperateDbMysql.py
3,414
3.53125
4
#!/usr/bin/env python # coding=utf-8 import MySQLdb def connectdb(): print('连接到mysql服务器...') # 打开数据库连接 # 用户名:hp, 密码:Hp12345.,用户名和密码需要改成你自己的mysql用户名和密码,并且要创建数据库TESTDB,并在TESTDB数据库中创建好表Student db = MySQLdb.connect("localhost","hp","Hp12345.","TESTDB") print('连接上了!') return db def createtable(db)...
1ada6bf3e4d3a9fadb02900045c958eeec86e77e
yuqinghuang01/StarterHacks2019-Albedo-Satellite
/write txt file.py
550
3.53125
4
import serial #module used for working with serial inputs/outputs serialport = "com13" #the serial port baudrate = 9600 #serial ports rate filename = "file.txt" #name of file outputfile = open(filename, "w") #opens a file ser = serial.Serial(serialport, baudrate) #opens serial port for x in range (0, 26): #...
e369f259258893f8bc6409a08ec41016d56f7ce8
Kirkules/ProjectEuler
/ProjectEuler1-9/ProjectEuler4.py
1,231
3.796875
4
""" Created by Kirk Anthony Boyer 7/5/2012 Solution to Project Euler Problem 4 Problem: A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 99. Find the largest palindrome made from the product of two 3-digit numbers. Idea: Brute...
3af4756acb606121324d854600391453b1469dc9
Kirkules/ProjectEuler
/ProjectEuler30-39/ProjectEuler38.py
3,998
4.03125
4
""" Created by Kirk Anthony Boyer 7/19/2012 Solution to Project Euler Problem 38 Problem: Take the number 192 and multiply it by each of 1, 2, and 3: 192 1 = 192 192 2 = 384 192 3 = 576 By concatenating each product we get the 1 to 9 pandigital, 192384576. We will call 192384576 the concatenat...