blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
45d3196f21b7489cb31fc4835562fe7c011b9884
kushrami/Python-Crash-Course-book-Exercise
/Exercise_5_2.py
638
4.40625
4
#more conditional test: car = 'ferrari' print(car == 'ferrari') print(car == 'tesla') print(car != 'tesla') print(car != 'ferrari') print(car == car.lower()) print(car == car.upper()) print(3 > 9) print(3 < 9) print(4 >= 5) print(4 <= 4) print(4 > 4) print(3 <= 7) print(6 < 7) print((3 > 4) or (3 < 4)) print((4 >= 3...
adf0bc809725419204321b2085216b9cf778fad3
taherpatan19/VLink
/Question1_TaherPatanwala.py
382
4.03125
4
def printArray(string, n): for i in range(n): print (string[i],end=" ") def sort(s,n): for i in range(1,n): temp=s[i] j=i-1 while j>=0 and len(temp)<len(s[j]): s[j+1]=s[j] j-=1 s[j+1]=temp if __name__== "__main__": arr=["Taher", "am", "I", "Pa...
2162157dc64423095e140b033335a6be7071abed
saitoasukakawaii/numerical-computation
/LU.py
870
3.828125
4
import numpy as np # 输入系数矩阵应以numpy中的array类型输入 # LU分解又称doolittle分解 def doolittle(a, n): # 主行 l = np.eye(n) u = np.zeros((n, n)) for i in range(n): for j in range(i + 1, n): # 乘子,用于消去第j行的i列 a[j, i] = a[j, i] / a[i, i] # 对i+1...n-1列 for k in range(i ...
a629f9b4b6aeea46f3cfd5c2edad5dfc1efce20b
MopkoBb/pythonAlgorithms
/isPopOrder.py
742
3.75
4
# 创建备用栈stack, 储存没有提前出栈的元素 # 在第一循环 # 1、如果pushV[0] == popV[0],将两个出栈,continue # 2、否则将pushV[0]压入stack # 跳出循环, 期待的结果应该是stack == popV[::-1] class Solution(): def isPopOrder(self, pushV, popV): if not pushV or not popV: return False if len(pushV) == 1 and len(popV) == 1 and pushV == popV: ...
5770f54b80a6e48b13729d9b55e40b2710e9b10a
blockchainassets/data-engineering
/data_science/pandas_datacamp/data_manipulation_with_pandas/02_Aggregating_data/06_Counting_categorical_variables.py
1,220
4.40625
4
''' Counting categorical variables Counting is a great way to get an overview of your data and to spot curiosities that you might not notice otherwise. In this exercise, you'll count the number of each type of store and the number of each type of department. The stores and departments DataFrames you created in the la...
7186d184923b45e67f243016c2c2e28604ba418b
sabrinachen321/LeetCode
/python/0173-BSTIterator.py
1,162
4.03125
4
from collections import deque # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class BSTIterator(object): def __init__(self, root): """ :type root: TreeNode """ ...
0d75e9f73576b5d7a89e5daaee917c4222947a5b
hypnopump/Math_of_Intelligence
/Newthons_method/new_rap.py
1,461
3.546875
4
import numpy as np import matplotlib.pyplot as plt from random import randint from sympy import * # Get an approximation by using n terms of Taylor series def taylor(function,x0,n): q = 0 for i in range(1, n+1): q = q + ((function.diff(x,i).subs(x,x0))*(x-x0)**i) / (np.math.factorial(i)) return q #...
d51349c45c5f2411281d77283e3849005277d392
mijanur-rahman-40/python_basics_with_simple_project
/data-structures_new-version/list.py
2,511
3.828125
4
from math import pi from collections import deque fruits = ['orange', 'apple', 'pear', 'banana', 'kiwi', 'apple', 'banana'] print(fruits.count('apple')) print(fruits.index('banana')) # Find next banana starting a position 4 print(fruits.index('banana', 4)) fruits.reverse() print(fruits) fruits.append('grape') fruits...
ff306a6deb9910f0187b0dfffb9e3f6568764c30
TetianaHrunyk/DailyCodingProblems
/challenge61.py
895
4
4
""" Implement integer exponentiation. That is, implement the pow(x, y) function, where x and y are integers and returns x^y. Do this faster than the naive method of repeated multiplication. For example, pow(2, 10) should return 1024. """ import timeit def trivialPow(num, p): res = 1 for i in range(p): ...
6e8c8f77a3acc7b450068127560f9a638126d4c1
yxudong/LeetCode
/617.合并二叉树.py
2,549
3.953125
4
# # @lc app=leetcode.cn id=617 lang=python3 # # [617] 合并二叉树 # # @lc code=start # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None # Tips: tree, depth-first-search class Solution: def mergeTrees(self, t1...
0bb90bff90e76d690b2fe6e0c3f0d06fa9e72ad3
lanpartis/jianzhiOffer_practice
/53_isNumeric.py
1,177
3.890625
4
# -*- coding:utf-8 -*- ''' 请实现一个函数用来判断字符串是否表示数值(包括整数和小数)。例如,字符串"+100","5e2","-123","3.1416"和"-1E-16"都表示数值。 但是"12e","1a3.14","1.2.3","+-5"和"12e+4.3"都不是。 ''' class Solution: # s字符串 def isNumeric(self, s): # write code here a=s has_e=False has_point=False num='' for ...
149cf39d3498306e5cd91f80537305c42fdb9adb
Cunningham-Wayne-Jeremy/lpthw
/015/ex15.py
896
4.40625
4
# imports the module argv from sys import argv # sets the arguments for this python script script, filename = argv # The open command opens the file and keeps it open waiting for other commands txt = open(filename, "r") # Prints a message usng the filename print(f"Here's your file {filename}:") # This will use the buil...
bd7ab8298c99f5f8ed67fba212db0b147ac6dbb3
MarcelaSilverio/exercicios-uri
/AD-HOC/python/problema2381.py
291
3.578125
4
# Autor: Marcela Prata Silverio # Turma: INF3A if __name__ == "__main__": alunos, sorteado = [int(val) for val in input().split()] ordem = [] for aluno in range(alunos): nome = input() ordem.append(nome) ordem.sort() print(ordem[sorteado-1])
5b73183d44e38b515da8e362dab1668a0bf6b78a
asthurer/Capital-One-Data-Challenge
/metrics.py
596
3.671875
4
def rate(df,n): null_series = df.isnull().sum() # The number of missing values from each column in your dataframe full_col_series = null_series[null_series == 0] # Will keep only the columns with no missing values df1 = df[full_col_series.index] b=df1.iloc[:,df1.shape[1]-1] a=df1.iloc[:,df1.columns.get_loc("SizeR...
395333233a95de4af07f108584a61dd574e5118b
Gavand/Python
/py6/fishcatch.py
1,858
4
4
''' Author: Gavin Andrews Date: 4/19/18 Description: The function of this program is to read a file, create a dictionary containing a description of fish with the observation, name, species, weight, length, height, width, and sex. Prints a report by reading the file, sending the number, nam...
6a46bd28b306261919255de4cf2100c559127e95
SiamiJW/LPTHW
/13/ex13.py
367
3.609375
4
"""Exercise 13: Parameters, unpacking, variables""" #using an input method to psas variables to a script (script is another) #name for a .py file from sys import argv script= argv print "The script is called:", script first = raw_input("Your first variable is:" ) second = raw_input("Your second variable is:" ) th...
8a7ba14fa6751ae8a0d20e24b7cda1b305088343
PriyanshiGupta88/100daysofleetcode
/https:/www.geeksforgeeks.org/find-xor-of-two-number-without-using-xor-operator/19(ii).py
148
3.640625
4
def myXOR(x, y): return ((x | y) & (~x | ~y)) x = int(input()) y = int(input()) print("XOR is" , myXOR(x, y))
193f37380b9383772081cdce1e03063a29f4849d
alyssa1996/CodingExercise
/Programmers/Level_1/부족한 금액 계산.py
159
3.578125
4
def solution(price, money, count): total_price = price*sum(range(1, count+1)) if total_price <= money: return 0 return total_price - money
57ece5d2a272068749ae86f07b4448545375cc95
syeluru/MIS304
/HW3/CheckPassword.py
1,320
4.0625
4
# Program to verify the password def checkPassword(password): # Length valid_length = False if len(password) >= 8: valid_length = True # Contains two digits num_digits = 0 valid_digits = False for i in range(len(password)): if password[i].isdigit(): num_digits += ...
161b978717104364402999115f48410115c1008a
osvaldoxdjr/python-execises-portuguese
/035_exe1.py
172
3.6875
4
""" Escreva uma função que obtenha a multiplicação de vários números de entrada """ def multiplicacao(*nums): mult = 1 for num in nums: mult *= num return mult
a39097a822a2a10b0db8fff795977e77dc76aab0
asmagsasp/biblia-catolica-json
/db.py
1,163
3.515625
4
import sqlite3 import atexit def get_connection(): global con if not con: con = sqlite3.connect('biblia.db') atexit.register(close_connection, con) return con def close_connection(some_con): some_con.commit() some_con.close() def create_database(cursor): # cria...
b52950074d92549e9ef47d52c9e44348eff4b22a
OniDaito/PythonCourse
/bomberman/part6/bomberman.py
1,735
3.515625
4
import pyglet from pyglet.resource import ResourceNotFoundException class Bomberman(): ''' This is a dictionary. It allows assignment of one thing to another ''' sprites = {} current_sprite = None dimensions = {} ''' This x and y is the bottom left of bomberman ''' x = 0 y = 0 sp...
177b93e5fb2d5eb8aa4d59a903c40379086d8a83
lz-purple/Source
/app/src/main/java/com/syd/source/aosp/external/toolchain-utils/mem_tests/utils.py
745
3.921875
4
"""Utility functions for the memory tests. """ from datetime import datetime def compute_total_diff(line, base_time): """ Computes the difference in time the line was recorded from the base time. An example of a line is: [4688:4688:0701/010151:ERROR:perf_provider_chromeos.cc(228)]... Here, the mo...
5e9c33b09d712bcf0eacef17691a829e55c46a50
zchen0211/topcoder
/python/leetcode/graph/399_evaluate_div.py
2,590
3.9375
4
""" 399. Evaluate Division (Medium) Equations are given in the format A / B = k, where A and B are variables represented as strings, and k is a real number (floating point number). Given some queries, return the answers. If the answer does not exist, return -1.0. Example: Given a / b = 2.0, b / c = 3.0. queries are:...
ad17429dee821bb9e4c113b0ccccbe7f7c8b1a5b
MartinMa28/Algorithms_review
/tree/0297_serialize_and_deserialize_binary_tree.py
1,450
3.859375
4
from collections import deque # Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Codec: def __init__(self): self.enc = [] def _preorder(self, root): if root: ...
86871d04d1fa1899d37d88beb68ae6477163457d
statisticallyfit/Python
/pythonlanguagetutorials/PythonTutorial/JohnZelle_PythonProgramming/Chapter6_Functions/ex14_squareNumbersFromFile.py
1,670
4.25
4
# JOB: open file, get sum of squares of numbers in file # ---------------------------------------------------------------------------- def isInteger(val): """ Returns true if string val is an integer. Note: having floats in strings throws value error. Arguments: val = value to check if integer ...
ac51980eb0d629490715b422bc29b1b38f6dad8e
AlexanderIvanofff/Python-Fundamentals
/Lists/mu_online.py
1,364
3.515625
4
dungeons_rooms = input().split('|') bitcoins = 0 health = 100 current_index = 0 dungeons_len = len(dungeons_rooms) while health > 0: for index in dungeons_rooms: tokens = index.split() type_meet = tokens[0] count = int(tokens[1]) if type_meet == 'potion': if health +...
2f8b00926601bd6a1f66944b0546bd2b4dec795e
reshmaladi/Python
/1.Class/PracticeInClass/class10/swap2.py
1,556
3.71875
4
#!C:\Python34 def swapbits(x,y,posx,posy, bits): print (" original x ", '{0:08b}'.format(x), end = "\n") print (" original y ", '{0:08b}'.format(y), end = "\n") #print mask for x x_mask=(1<<bits)-1 print (" mask ", '{0:08b}'.format(x_mask), end = "\n") x_mask=x_mask<<(posx-bits) print (" mask after bits sh...
132eee8877d1f0912db9de69f79f6a76d691b72a
leighton613/StanfordAlgos
/medianHeap.py
4,927
3.703125
4
# coding: utf-8 """ GOAL: 1. Median Maintenance algorithm; 2. you should treat this as a stream of numbers, arriving one by one; 3. Compute the last 4 digits of summation of all medians. """ class Heap: ## -------- Nonpublic Behavior def _parent(self, i): return (i - 1) // 2 def _left(self,...
c4915e564e8cb477b8a49af4ede4ebf6124673c9
borzunov/cpmoptimize
/tests/perfomance/geom_sum.py
960
3.703125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- import tests_common as common start = 3 coeff = 5 def naive(count): elem = start res = 0 for i in xrange(count): res += elem elem *= coeff return res def _optimal(first, count): # Returns (sum, coeff ** count) if count & 1: ...
d3506ebae4b104883c89606f7861475a48fd6cd2
divyak1995/PythonFiles
/reverseLinkedList.py
917
4.15625
4
#Find middle node in a linked list: class Node: def __init__(self,value): self.value=value self.nextl=None class LinkedList: def __init__(self): self.head=None def traversal(self): temp=self.head if temp is None: return while(temp is not None): print(temp.value,end=' ') ...
318ef5e0aa7a7f7c5c349c3964f7f0e126d43fc9
munikarmanish/cse5311
/algorithms/searching/binary.py
670
4.125
4
""" Binary search algorithm. """ def __binary_search(array, start, end, key): """ Returns the index of key in sorted array. Returns None if not found. """ if start > end: return mid = (start + end + 1) // 2 if key == array[mid]: return mid if key < array[mid]: retur...
b58e855cf0037b82ea85eacc7d3d762364ce2e47
Bazarovay/sprinter
/csv2json.py
558
3.5625
4
import csv, json def is_an_array(value): return "#" in value def load_from_csv(csv_file_path): data = [] with open(csv_file_path) as csvFile: csvReader = csv.DictReader(csvFile) for rows in csvReader: row_json = {} print(rows) for key, value in rows.items(): value = value.strip...
576c4eec3813d9ad763753e014cadcd34fee659e
chavezma/eddPeleaMonstruos
/src/Monstruo.py
2,927
3.53125
4
from Elemento import * class Monstruo(): # Un monstruo recibe el nombre y una lista de elementos def __init__(self, id, nombre, elementos): assert nombre, 'El nombre no puede ser vacio' self.nombre = nombre assert len(elementos) == 2, 'Debe tener dos elementos' self.elementos ...
d4a02d8c42cb5b67ffb2458ea8ee74a7c4a33fb1
JaeDukSeo/Personal_Daily_NeuralNetwork_Practice
/1_numpy/a_first_session_nov_18/1_activation_functions.py
6,396
3.859375
4
import numpy as np,sys #------ OUR ACTIVATION FUNCTIONS and it derivatives ------ def sigmoid(x): return 1 / (1 + np.exp( (-1) * x)) def d_sigmoid(x): return sigmoid(x) * (1 - sigmoid(x)) # Func: Very simple relu layer function def relu(x): temp = x>0 return x * temp # if x > 0: # ret...
50dbd1ff3cb0063a29a9e6a7ad0c3517c02da907
racarvajal/Tarea2_Astro_Stats
/Tarea2_p2_2.py
1,053
3.5
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # Generate numbers distributed as Standard Normal from Uniform distribution import numpy as np from numpy import random from scipy.special import erfinv import matplotlib.pyplot as plt import math N = 1000000 # Number of generated points # Generate uniform distribution...
6d071df49859c588bc0273705dd8594cca4d51e7
Sevansu/PythonBasicPrograms
/competitive level/SpiralMatrix.py
2,108
3.765625
4
def spiral_matrix(N): try: if N<=0: return ##########initialising a matrix and variables################## import math direction=1 mat_range=math.sqrt(N) mat_range=math.ceil(mat_range)+2 L,R,T,B=map(int,[(mat_range//2)-1]*4) #these four variabl...
db108679823ae5eeb244282840d06df94f1926c9
Ell-91/Coding-Interview-Prep
/Data Structure Implementation/linkedLists/linkedList_prac.py
2,819
4.0625
4
class Node: def __init__(self,data): self.data = data self.next = None class linkedList: def __init__(self): self.head = None self.numOfNodes = 0 def prepend(self,data): self.numOfNodes += 1 new_node = Node(data) #Dont need to check if list is NULL b/c if it is we'll just prepen...
9abcaa490f2917b0985a94cba90cb194aa6a3d10
On1-Tech/LuckyCrypt
/LuckyCrypt.py
11,019
3.734375
4
#coding:utf-8 #LuckyCrypt #by LuckySmile :) #Note for myself : 32 to 126 #imports import time import os def askValidText(what): msg = input(f"What is the {what} you want to crypt ? : ") while msg == "": msg = input("! Please write something : ") #Check that user doesn't write forbidden character...
8e8c5dbae19996577b91810dae7f6d5a3f6e749b
jw4590/ChinaLocal
/panorama - Guodong/python(react-gallery)/readfile.py
2,591
3.71875
4
import copy # Program to show various ways to # read data from a file. def readgallery(filename): # Creating a file file1 = open(filename, "r+") # readlines function print("Output of Readlines function is ") return(file1.readlines()) file1.close() def edittxt(txtList): new...
0c7b97c8fda5ce3648330e775c52eef90fb4369d
anantkaushik/leetcode
/1403-minimum-subsequence-in-non-increasing-order.py
1,824
3.765625
4
""" Problem Link: https://leetcode.com/problems/minimum-subsequence-in-non-increasing-order/ Given the array nums, obtain a subsequence of the array whose sum of elements is strictly greater than the sum of the non included elements in such subsequence. If there are multiple solutions, return the subsequence with mi...
d80532d859deecf3a87107332e981138dad43970
kmutya/Predictive-Maintainence
/cost_function.py
1,590
3.546875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Feb 7 14:37:05 2019 @author: Kartik """ import os import pandas as pd import math import numpy as np import matplotlib.pyplot as plt os.getcwd() os.chdir('/Users/apple/Google Drive/A&M/Summer 2018/Project/626') #import the data forecast_df = pd.rea...
5ec779d06f2cbfbb9b23862c57d6c3638747bde5
iam-sundar/learn_python
/data_types/string_package/str_demo.py
1,802
3.921875
4
# single line initialization name:str = 'Sundar' # multiple line initialization about_me:str = ''' I am software developer with 7+ years experience in enterprise application development. I have good knowledge in Core Java, Java8, Spring Framework, RESTful service, maven, GIT verison control, Sonar integration, Cassan...
169229f588c091791a492f4c430bde70ba552f66
AnastasiaYuHu/ANLY502
/PS04/wikipedia_by_month.py
1,727
4.09375
4
#!/usr/bin/spark-submit # # Problem Set #4 # Implement wordcount on the shakespeare plays as a spark program that: # a.Removes characters that are not letters, numbers or spaces from each input line. # b.Converts the text to lowercase. # c.Splits the text into words. # d.Reports the 40 most common words, with the most ...
8e9c3ab773527f18fcbf9b0c2cfab80029707ed5
DariaKrasnobaeva/Coursera_Python_for_Everybody_Specialization
/Course_1/ex_04_06.py
1,019
4.40625
4
#4.6 Write a program to prompt the user for hours and rate per hour using input to compute gross pay. #Pay should be the normal rate for hours up to 40 and time-and-a-half for the hourly rate for all hours #worked above 40 hours. Put the logic to do the computation of pay in a function called computepay() #and use t...
fd38c8b6a2ee5ad81d15b6e0163b0042d105193f
vid2408/Day3
/tuple_membership.py
110
3.671875
4
my_tuple = ('a', 'p', 'p', 'l', 'e',) print('a' in my_tuple) print('b' in my_tuple) print('g' not in my_tuple)
f2bd8feb042e0b592dee8cc6c4e710bbba0d7aed
niko1ai-krasavin/python-hw
/hw23.py
508
3.609375
4
#!/usr/bin/python3 import numpy as np def n_arr(input_array): if not input_array: return [] t = tuple(input_array) j = np.prod(input_array) start_array = [","] * j result_array = np.reshape(start_array, t) # or return without the function 'tolist()' for pretty output return result...
de95c79a8fe89086e72c8341e0a4cceab1ff5389
dohvis/kmu-sw-proj
/week5/김남재.py
759
3.71875
4
import time def fibo_list(n): fibolist = [0, 1] for i in range(1, n): fibolist.append(fibolist[i] + fibolist[i - 1]) return fibolist[n] def fibo_value(n): a, b = 0, 1 for i in range(n): a, b = b, a + b return a def fibo_rec(n): if n<=1: return n return fibo_rec(...
ca493773529c5b2689a0baa948cbcfbac74cc4b7
jefferson206/destravando-python
/exercicio23/exercicio23.py
547
3.6875
4
from listaExercicio.uteis.util import Util def main(): Util().enunciadoEmDuasPartes('LEIA UM NÚMERO REAL. SE O NÚMERO FOR POSITIVO IMPRIMA A RAIZ QUADRADA.', 'DO CONTRÁRIO, IMPRIMA O NÚMERO AO QUADRADO.', 80) valor = float(input(f'Digite um numero qualquer: ').replace(',', '....
e930a1e4a5d9eaca94d5653366569fe0e8e92b9c
yif042/leetcode
/Python3/no20_Valid_Parentheses.py
640
3.703125
4
class Solution(object): def isValid(self, s): """ :type s: str :rtype: bool """ stack = [] leftside = ("(","[","{") rightside = (")","]","}") d = {")":"(","]":"[","}":"{"} for char in s: if char in leftside: stack.a...
47271123ee3179ab3d85eb439aa8ee4ce97dccfa
Aplicity/algorithm_test
/2020W_final/q3_tree_size.py
1,132
4.15625
4
"""Tree size: CIS 211 Final Exam coding problem""" from typing import List class Tree: def size(self) -> int: """The size of a tree is the total number of nodes, including both internal and leaf nodes. """ raise NotImplementedError("Did you forget to implement size?") class Inner...
6d45a8ae9084155b987914af439e07ced0f9fd55
huyngopt1994/python-Algorithm
/green/green-03-loop/Vanya_and_Cubes.py
223
3.875
4
s = int(input()) height = 0 def need_cubes_for_index(index): count = 0 for i in range(index+1): count +=i return count while s >=0: height += 1 s -= need_cubes_for_index(height) print(height-1)
e96371a540a5a902b06e449882855d14c0d20501
Marist-CMPT120-FA19/Patrick-Sullivan-Project-10
/Project 10.py
804
3.890625
4
import string def censor(): fname = input("Enter filename: ") file = open("cen.txt", 'r').readlines() val = open("answer.txt", 'w') i = 'and' for i in file: words = i.split( ) for word in words: counter = 0 for letter in word: if not letter in ...
cffe973b153db29bc9b58010da4c7a0204a02169
bhanukirant99/AlgoExpert-1
/Arrays/TwoNumberSum.py
465
4.125
4
# time complexity = o(n) # space complexity = o(n) def twoNumberSum(array, targetSum): # Write your code here. dicti = {} for i in range(len(array)): diff = targetSum - array[i] # calculate diff between target and every other item in the array if diff in dicti: return ([diff, array[i]]) else: ...
4eb16cd121ef349b80c9dad90c4081c1da993c99
TheDG/MachineLearning_A-Z
/Machine_Learning_A-Z_Mine/Part 1 - Data Preprocessing/categorical_data.py
1,339
3.546875
4
# Data Preprocessing # Importing the libraries import numpy as np import pandas as pd # Importing the dataset df = pd.read_csv( '/Users/diegosinay/Downloads/ML/Machine Learning A-Z Mine/Part 1 - Data Preprocessing/Data.csv') x = df.iloc[:, :-1].values y = df.iloc[:, -1].values # Encoding categorical data from sk...
ead76eecd1792bc2c71a1568a45e27d75155ceff
itsolutionscorp/AutoStyle-Clustering
/all_data/exercism_data/python/bob/f329470657f144adb2c8f87cddebeb8b.py
1,568
3.65625
4
# Bob is a lackadaisical teenager. In conversation, his responses are very limited. import re class bob(object): @staticmethod def hey(greeting): if re.match(r"^\s*$", greeting): return 'Fine. Be that way!' # He says 'Fine. Be that way!' if you address him without actually saying anything. elif greet...
620f0995eccce872e86499d10f69d734d3287577
SumedhSingh12/Python-Data-structures
/Recursion/staircase.py
1,191
4.09375
4
'''Staircase problem with only two possibilities of steps: 1 & 2''' def staircase(n): if n==0 or n==1: return 1 else: return staircase(n-1) + staircase(n-1) def staircase_memo(n, cache=None): if cache == None: cache = [1,1]+([None] * (n)) if cache[n]: return cache[n] ...
60de4b08226f80e5a2f5d1186e14ca29c92d7ac4
rnsdoodi/Programming-CookBook
/Back-End/Python/Basics/Part -1 - Functional/06 - Decorators/Single Dispatch/01_basic_parser.py
2,621
3.625
4
from html import escape from decimal import Decimal def html_escape(arg): return escape(str(arg)) def html_int(a): return f'{a}(<i>{str(hex(a))}</i>)' def html_real(a): return f'{round(a, 2):.2f}' def html_str(s): return html_escape(s).replace('/n', '<br/>\n') def html_list(l): items = (f'...
ff24a3734a3731d98556d07d7e8f8b7c21b4dece
mrparkonline/py_basics
/solutions/headTails.py
639
4.0625
4
# Create a Python program that mimics the heads or tails game. The program should output either ‘H’ for heads or ‘T’ for tails randomly on each execution of the program. from random import choice print(choice('HT')) print(choice(['Heads', 'Tails'])) ''' # Using 5 print() statements, create a tiny Python program that...
13dda8a7e0b754e8b9613058373ed85c1dd165b1
WendingLin/Leetcode
/058_Length of Last Word.py
107
3.6875
4
#58.Length of Last Word def lengthOfLastWord(s): return len(s.rstrip(" "))-s.rstrip(" ").rfind(" ")-1
65b310417192270ca313b56d423b0cfad18df6b7
bhusalashish/DSA-1
/Data/Binary Trees/Mirror of Tree/Mirror of Tree.py
836
3.875
4
''' #### Name: Mirror of Tree Link: [link]() Level order only ''' def mirror( root ): if root == None: return 0 stack = [] stack.append(root) while stack: current = stack.pop() print(current.data, end=" ") if current.right: stack.append(current.right...
e2b8c5803bf0d1aa7e6f1bc52519916dab22d207
tino2002/VuNgocMinh-C4T8
/session11/bt34.py
690
4.03125
4
loop_count = 0 q1 = { "How many legs an octopus has :" : "" , '1' : "one leg", "2" : "two legs", '3' : "four legs", '4' : "eight legs" } q2 = { "How many legs an octopus has :" : "" , '1' : "six legs", "2" : "two legs", '3' : "one legs", '4' : "eight legs" } q3 = {"How many legs ...
5a9a063e71c18ec5e0f1a4456e4c077c5e84dde1
liquidhippo1/2.2.2
/prob_lending_club.py
809
3.5
4
import matplotlib.pyplot as plt import pandas as pd import scipy.stats as stats import numpy as np loansData = pd.read_csv('https://spark-public.s3.amazonaws.com/dataanalysis/loansData.csv') loansData.dropna(inplace=True) # no idea what this line means #loansData = loansData.splitlines() # we could also do data.spl...
2652284ae44f1f3f9e3665a5f99837cbae7d4227
vikanksha/Python-Book-Exercises
/chap3/ex11_house_credits.py
545
3.953125
4
#program for first time home buyer tax credits. # credit was only available to those who fullfill all criteria. house_cost = int(input("Enter total your total house cost:")) combine_income = int(input("Enter your total combine income:")) previous_house = eval(input("Any house owened in last 3 years ? ")) if (house_cost...
bf90e64c8250e4c8f85f3365b2e4ae7d84ac7e8f
RRCHcc/python_base
/python_base/day12/exercise03.py
1,033
4.46875
4
""" 练习: 实现向量类与整数做减法 乘法运算 """ class Vector: """ 向量 """ def __init__(self,x): self.x = x def __str__(self): return "向量的x变量是:%s"%self.x def __sub__(self, other): return Vector(self.x - other) def __mul__(self, other): return Vector(self.x * other) def _...
02aba0f62de930d1064a34b84e1a464cf88e2944
2234839/Python
/基础.py
553
4
4
print("输出") s="这是一个字符串" #s[0]#第一个字符 s=s[0:2]#分割出前两个字符 #s[2:]#第三个字符以后的 print(s) list=['abcd',123,2023,'john',70.2] tinylist=[123,'john'] print(list)#可以使用[:]来分割数组 tuple=('abcd',123,2023,'john',70.2)#元组 一个不可二次赋值的数组 dict={}#字典 通过键值对来存储数据 dict['one']="this is one" dict[2]="this is tow" tinydict={'name':'john','code':67...
e6fe57d587989c68369beb9a1710a4308ef863db
Jayesh598007/Python_tutorial
/Chap8_functions/12_prac7_strip.py
602
4.3125
4
#strip function ''' this = " Jayesh " print(this) # o/p is in the form of quote as given ie: with spaces print(this.strip()) # with this, o/p changes as the quote without strip ''' # remove a word and also strip the comment def remove_and_strip(string, word): newStr = string.replace(word, "") # func fo...
f7869ea1cbe2a963506f924f8e5bb6acc88681d1
gladiagit/uploaders
/python/nutriquery.py
3,695
3.671875
4
#!/usr/bin/python import os import sys import datetime import sqlite3 # a program that takes in a setings file containg the tabldelim file info, the database and the table to query # python nutriquery.py settings #def fileparser(file): # pass #def dataaccess(database, table, vof, values): # pass #def get_settings(...
94dc96f1e440f7d65ad71ebd336a0175834aa9b2
lunevods/practicum_1
/1.py
710
3.578125
4
""" Имя проекта: practicum-1 Номер версии: 1.0 Имя файла: 1.py Автор: 2020 © Д.Л Иоффе, Челябинск Лицензия использования: CC BY-NC 4.0 (https://creativecommons.org/licenses/by-nc/4.0/deed.ru) Дата создания: 11/11/2020 Дата последней модификации: 11/11/2020 Связанные файлы/пакеты: min,max Описание: Решение зад...
5c06b22477299c8a7b143c7abb5bbf6ff887c7e5
ethauvin/coding101
/episode15/codingYouTube101.py
3,730
4.03125
4
#!/usr/bin/env python # Coding YouTube 101 # # Written by Erik C. Thauvin (erik@thauvin.net) # http://erik.thauvin.net/ # http://github.com/ethauvin/coding101/ # May 1, 2014 # To warp long lines import textwrap # For making http requests import urllib2 # For decoding YouTube's API responses import json # Your YouTu...
7c480999560d2c9f8dc69db1e7ad5a7af6386ad0
Esot3riA/swea
/intermediate/4880_tournamant.py
726
3.640625
4
import sys sys.stdin = open("input.txt", 'r') def dfs(start, end): if end - start == 0: return start elif end - start == 1: return battle(start, end) else: center = (start + end) // 2 return battle(dfs(start, center), dfs(center + 1, end)) def battle(std1, std2): if (...
035656e408a12a4559fbf4c29c08b72db22c5e9b
vengadam2001/python
/turtlepackagefordrawing.py
366
3.875
4
import turtle as t import time as d for i in range(0,100): t.forward(1) t.left(10) t.circle(i) for i in range(0,100): t.forward(1) t.left(10) t.circle(100-i) d.sleep(1000000000) ''' write a python programme to check wether teh given year is leapyear or not using module write a py ...
b34f5870717df8595cacc4d2611d99ff4365abec
JamesFarrant/completepythonbootcamp
/blackjack.py
2,709
3.578125
4
from IPython.display import clear_output import random player_stand = False dealer_stand = False class Player(object): def __init__(self): self.hand = [] class Dealer(Player): def __init__(self): self.hand= [] def dealer_turn(self): switch = random.random() if switch >=...
dd9782d81e7dda5b61275113b3a17125fd5fa815
surendhar-code/Python-Programs
/Basic Programs/factorial_n.py
236
4.3125
4
# Develop a python program to find the factorial of a given number using while statement. n=int(input("Enter the number : ")) temp = n fact=1 while n>0: fact=fact*n n=n-1 print("The factorial of the number ",temp," is : ",fact)
93a3b7ca4902d1aa0af06c0f0d4a198fb71402a2
anjubagri123/python
/python in one video/main.py
13,953
4.15625
4
# import cv2 # import math # print("hello python") # comments not allowed here run thr code after removing comments. // hello python # print(9-0) #9 # is single line comment # print("9-0") #9-0 # print("yes") # can also mak...
b53200dacfd1fbc44fb73fa2629e3331434e281b
narenaruiz/Python
/P7/P7E6V2.py
673
3.96875
4
"""6.-Escribe un programa que lea el nombre de una persona y un carácter, le pase estos datos a una función que comprobará si dicho carácter está en su nombre. El resultado de dicha función lo imprimirá el programa principal por pantalla. Autor:Nicolás Arena Ruiz """ def Comprobacion(nombre, caracter): if...
3e4eb10815d1ed3d25c1864a2ab814273c676078
TheFriendlyCoder/school-scraper-old
/src/school_scraper/fsddistrict.py
1,761
3.515625
4
"""Primitives for reading francophone school district information""" from .fsdschool import FSDSchool class FSDDistrict: """Abstraction around school district data parsed from the district website """ DISTRICT_FIELD = "Région" def __init__(self, df): """ Args: df: Pandas d...
a4e340b949d00878a8b2b98bf63034f4e63d382d
khdc-me/classroom
/PracticePython_org/24_draw_game_board/draw_game_board.py
1,713
4.25
4
# # Draw a 'gameboard' according to dimensions that the user specifies # def get_dimensions(): """ Prompt user for board dimensions. - acceptable values for width and height are between 1 and 9 (inclusive) - will produce board anywhere from 1x1 to 9x9 ...
2ee3fa94099295b9de63869467ee98d49bc870fa
tusonggao/leetcode
/10.py
1,725
3.59375
4
class Solution: def __init__(self): self.cache = {} def isMatch(self, s, p): """ :type s: str :type p: str :rtype: bool """ if (s, p) in self.cache: return self.cache[(s, p)] if len(s)==0: if len(p)==0: ...
ae8fd2a52400f5873e6aeb2a23b9ff5922792d7c
EvgeniiRomanov/PythonPY100
/Занятие4/Домашнее_задание/task4/main.py
496
3.6875
4
def polin_number(a): num_a = [int(x) for x in str(a)] # if sum(num_a[:3]) == sum(num_a[3:]): # print(f"Число {a} Счастливое") # else: # print(f"Число {a} обычное") return [print(f"Число {a} Счастливое") if sum(num_a[:3]) == sum(num_a[3:]) else print(f"Число {a} обычное")] if __name__...
60b0e4372b8b02b994af79c9f676d7a221e2c435
Paul-Haley/LPTHW_python3
/ex37_break.py
239
3.828125
4
for i in range(0,10): for j in range(10, -1, -1): # we count backwards to -1 so we include 0 if(i == j): print("i == j, so we break") break else: print("i = %d, j= %d" % (i, j))
41ed3034cd95f996c3b64f39ff398d8e8ebceb24
MayerlyBustos/full-stack-python-programming-
/2.2+data_types.py
1,023
4.5
4
# data types help us store different type of data # we will go over each of these # ofcourse you can print them now we don't need to see them # some basic data types include # string nick_name = "raufie" city = 'lahore' # numbers age = 55 weight = 91.2 productivity_ratio = 0.97211 # group of similar data: arrays weight...
d1b677cf4e7ad175f514bb4f3327c805f6386dbc
ramonjunquera/GlobalEnvironment
/Python/standard/curso/07 Programación orientada a objetos/02 herencia.py
3,170
3.84375
4
#Tema: Herecia de clases #Fecha: 20221221 #Autor: Ramón Junquera # Herencia. Es la manera de compartir funcionalidades entre clases. # Se puede crear una clase tomando como base otra existente # Se mantendrán todas las propiedades (métodos y variables) de la clase original, # pero podremos añadir nuevas o modificar (...
5fc8c80fc05370a37d28523fda01cfa47af81692
gonzalob24/Learning_Central
/Python_Programming/Dynamic/fc_fib.py
359
3.625
4
# memoization # store duplicate subproblems: use an array or object: key --> f(n) value: return of f(n) def fib(n, memo={}): if n in memo: return memo[n] if n < 2: return n # save value in memo object memo[n] = fib(n - 1, memo) + fib(n - 2, memo) return memo[n] print(fib(6)) prin...
9887ed4b32ea850bbc6bf196d63fa4f0e810db5a
amirtip/laitecpython
/Tam2/tam2.py
180
4
4
x=int(input("Enter The Num:")) for i in range(1,x+1): print(" "*(x-i),end='') print(" * "*i," ") for i in range(x,0): print(" "*(x-i),end='') print(" *"*i)
0753f39d5d94c420a2e65db86555a8f31299b34c
MagdalenaSvilenova/Python-Fundamentals
/regex/furniture.py
507
3.734375
4
import re data = input() furniture = [] money = 0 pattern = r"^>>([a-zA-Z]+)<<([0-9]+\.?[0-9]+)!([0-9]+)$" while not data == 'Purchase': match = re.match(pattern, data) if match: name = match.group(1) price = float(match.group(2)) quantity = int(match.group(3)) ...
d7acb50d4239366eea2bf360c165d33abc213228
ShararAwsaf/Algorithms-Course
/Course-Contents/assignments/res/QuickSort-py/quicksort.py
1,037
3.578125
4
def quick_sort(A): def partition(s, e): # check if start item is greater than end item if s >= e-1: return # choose the start item as pivot p = A[s] # rest items arranged so that the items less than pivot are on left and geq items r...
89b4619afb4921d8e090d0edb83313ec8302011e
Hemiptera1/Juego_libro
/main.py
3,970
3.640625
4
import random import textwrap def marco_embellecedor(mensaje): marco = "-" * 72 print(marco) print(mensaje) print(marco, end="\n\n") def corre_juego(): seguir_jugando = "si" ancho = 72 linea_punteada = "-" * ancho medidor_salud = {"Jugador": 40, "Orco": 35} presentando(linea_punteada, ancho) misión(linea_...
85fe6c84d3f2f56d8e2e4053014b63ab223520d3
EngineerNV/movie_review_bayesian_classifier
/cleanData.py
2,301
3.890625
4
#!/usr/bin/env python from tempfile import mkstemp from shutil import move from os import fdopen, remove import string import os #this method is used to remove all of the punctuation, uppercase, and top 100 common words. It replaces the current text file with the new text file def remove_format(file_name): # ...
0fcd1e67aaaa647537f48ee941f19890ea15aac9
leemengtw/artificial-intelligence
/coding-minimax/gamestate.py
3,549
3.734375
4
import copy class GameState: """ Attributes ---------- _dim: tuple Represent the dimension of the board with (width, height) = (xlim, ylim), e.g., (3, 2) means the board look like [0 0 0] [0 0 0] _xlim: int width of the board _ylim: int height ...
2829e023c9dd199fc78b529b0ced68d329fe5db8
erikvanzijst/projecteuler
/q10.py
482
3.828125
4
def primes(max_n): # Taken from: # http://stackoverflow.com/questions/2068372/fastest-way-to-list-all-primes-below-n-in-python/2073279#2073279 numbers = range(3, max_n + 1, 2) half = max_n // 2 initial = 4 for step in xrange(3, max_n + 1, 2): for i in xrange(initial, half, step): ...
4f41b22660fb4c5e04454aa29e9e147a1d082b42
Aasthaengg/IBMdataset
/Python_codes/p00001/s495898030.py
82
3.640625
4
for i in sorted([int(input()) for _ in range(10)], reverse=True)[:3]: print(i)
300a85a9c2f4d10c2a994a19b1ec480378b22356
pavango/python_programs
/besic_programs/Area_Of_Pentagon.py
194
4.46875
4
#program to find area of circle side = int(input("Enter side value: ")) length = int(input("Enter the length value:")) area = (5/2)* length * side print("Area of Pentagon Is: {0}".format(area))
8f72c452989e3133d87942b01927c9099174e5c4
MoutyWong/Python3-learning-Notes
/day03/day03_Recursive.py
438
4.21875
4
#!/usr/bin/env python3 # -*- coding:utf-8 -*- # 递归函数recursive function def fact(n): if not isinstance(n, (int, float)): raise TypeError('bad operand type') if n == 1: return 1 return n * fact(n - 1) print(fact(100)) # 尾递归 def fact2(n): return fact_iter(n, 1) def fact_iter(num, product)...
668f7a4ddf42eb04ec8131f27f38e0456548ea53
seanahmad/etl-pipeline-example
/etl.py
753
3.609375
4
import pandas as pd # This part is abstraction on the extracting data from any datasources: DBs, APIs, etc. def extract_data(path): df = pd.read_excel(path) return df # Any needed data transformatiion could be performed in this part def transform(df): df['WITHDRAWAL AMT'].fillna(0, inplace=True) df['...
df1376a9975b46f4c7e85f64bacfdb6b73c93a94
Judice/-offer
/demo27.py
1,196
3.734375
4
# -*- coding:utf-8 -*- """ 请用递归方式实现二叉树的先序、中序和后序的遍历打印。 给定一个二叉树的根结点root,请依次返回二叉树的先序,中序和后续遍历(二维数组的形式) """ class Node: def __init__(self, x): self.val = x self.left = None self.right = None class TreeToSequence: def convert(self, root): res = [[],[],[]] self.preorder...
074cfc3356e5d999dec6752acee6c0bf32ae4b15
nd-cse-34872-su21/cse-34872-su21-examples
/lecture03/binary_search.py
1,397
4.21875
4
#!/usr/bin/env python3 def binary_search_iterative(data, target): ''' >>> binary_search_iterative([2, 5, 9], 2) True >>> binary_search_iterative([2, 5, 8, 9], 5) True >>> binary_search_iterative([2, 5, 8, 9], 0) False >>> binary_search_iterative([2, 5, 8, 9], 7) False...
16a048b09bd0f0c456175f1f633c2b0ded720f2a
lindamao/Plankton-Parachute
/Plankton Parachute.py
16,539
3.578125
4
##################################################################### # PLANKTON PARACHUTE # # ============================== # # NAME: LINDA MAO # # COURSE: ...
f0db9dae4dccb3ef341f721ff6cc9f7351d60149
AidenLuan/hlua2
/25478028_F1.py
3,974
4.03125
4
# -*- coding: utf-8 -*- """ Created on Tue Dec 18 2018 @author: luanhaoran """ # Student Name: Haoran Luan ;Student Number 25478028 # Start edit date 18 Dec 2018 last edit 19 Dec 2018 # In this task, there are three steps: # 1.Check the inputs integer and a list of positive integers # 2.After right input, starting Lo...
f78a648bc010fa4a785acb67ff1ed183759f80d3
CX-Bool/LeetCodeRecord
/Python/Medium/146. LRU缓存机制.py
965
3.65625
4
class LRUCache(object): def __init__(self, capacity): """ :type capacity: int """ self.capacity = capacity self.mem = {} self.use = [] def get(self, key): """ :type key: int :rtype: int """ if key in self.mem: ...