blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
41b07b7bb09a964323a2d0d2bcb35ab331062c30
Sanju7678/DevScript-Python-Bootcamp
/DevScript Python Bootcamp Project Horoscope.py
5,571
4.125
4
#Python Bootcamp Project: Applications that tells Horoscope by using Zodiac Sign print("Today's Horoscope") next = True while next == True: print(''' 1. Aries 2. Taurus 3. Gemini 4. Cancer 5. Leo 6. Virgo 7. Libra 8. Scorpio 9. Sagittarius 10. Capricorn 11. Aquarius 12. Pisces ''') s=int(input('Pick your sign numb...
45e4693649d25a1abf6383109038f2d77e038c2c
EndIFbiu/python-study
/02-运算符/02-逻辑运算符.py
548
3.84375
4
a = 0 b = 1 c = 2 print((a < b) and (c > b)) # True print((a > b) and (c > b)) # False print(a < b or c > b) # True print(a > b or c > b) # True print(not False) print(not c > b) # and运算符,只要有⼀个值为0,则结果为0,否则结果为最后⼀个非0数字 print(a and b) # 0 print(b and a) # 0 print(a and c) # 0 print(c and a) # 0 print(b and c)...
5e5d83a9ab3e9f6dae03baeaca04ead790e41f6c
MauriceMorrey/Python
/listsandstringspractice.py
476
3.71875
4
words = "It's thanksgiving day. It's my birthday too!" print words.find('day') print words.replace('day', 'month') x = [2,54,-2,7,12,98] print min(x) print max(x) y = ["hello",2,54,-2,7,12,98,"world"] print y[0] print y[len(y)-1] w = [] w.append(y[0]) w.append(y[len(y)-1]) print w x = [19,2,54,-2,7,12,98,32,10,-3,6...
b4624aeca77b6b3e9ea45436f2e90847ecda5d2d
rams4automation/SeleniumPython
/RegExp/Search.py
528
4.21875
4
# The search() function searches the string for a match, and returns a Match object if there is a match. # # If there is more than one match, only the first occurrence of the match will be returned: import re str = "The rain in Spain" x = re.search("ai", str) print(x) print("The first located in position:", x.start(...
0bef7e9ff096efec47cc04aac7fb87e1f38c9a7a
Early-woods/Python_Coding_Practice
/LinkedList/getIntersectionNode.py
604
3.90625
4
''' Write a program to find the node at which the intersection of two singly linked lists begins. ''' class ListNode: def __init__(self, val, next=None): self.val = val self.next = next def getIntersectionNode(headA, headB): p1, p2 = headA, headB while p1 != p2: p1 = headB if not p...
39c1c3480ec964548b312500bb9dd2d0d04582ab
vfhexteam/interview-task-1
/convertor/__main__.py
691
3.546875
4
import argparse import re import string KEY_FILE = 'key' def prepare_text_source(text: str): return re.sub(string.punctuation, '', text.lower()) def parse_args(): parser = argparse.ArgumentParser() parser.add_argument('source_text', type=str, help='Returns...
b08336c650466a98b7c489ebc8f5e79fca5a5ef1
rafaelpellenz/Curso-de-Python-exercicios
/ex015.py
263
3.703125
4
dias = int(input('Digite o número de dias: ')) km = float(input("Digite quantos km o carro rodou: ")) custoDiaria = dias * 60 custoKm = km * 0.15 valorTotal = custoKm + float(custoDiaria) print('O valor a ser cobrado é de R$ {:.2f}'.format(valorTotal))
21e74a344d53c002bf098b0dee04798fa1ea4ccc
TurquoiseHzy/CCompiler
/kmp.py
1,177
3.515625
4
def get_next(next, word, l): i = 0 j = -1 next[0] = -1 while i < l: if j == -1 or word[i] == word[j]: j += 1 i += 1 if i == l or word[i] != word[j]: next[i] = j else: next[i] = next[j] else: j = next[j] def str_kmp(next, text, word, l1, l2, result): i ...
c547c69bd8096f04ca3c787825d8f0723e805973
laxbista/Python-Practice
/String_Excercises/q2.py
272
4
4
# Exercise Question 2: Given 2 strings, s1 and s2, # create a new string by appending s2 in the middle of s1 def newString(s1, s2): MiddleS1 = len(s1) // 2 new_String = s1[:MiddleS1] + s2 + s1[MiddleS1:] print(new_String) newString("Ault", "Kelly")
70475137935f83421aaea43af6b5607ac606837c
www-wy-com/StudyPy01
/180202_input_output.py
1,233
4.21875
4
# -*- coding: utf-8 -*- import pickle # 用户输入内容 def reverse(text): return text[::-1] def is_palindrome(text): return text == reverse(text) something = input('enter text: ') if is_palindrome(something): print('yes, this is palindrome') else: print('no, this is not a palindrome') # 再议input birth=input('...
d92b762ed10016e14f309a58c4ba4edc0325812f
Yaz015/EjerciciosPython
/Guia2/E9.py
549
3.953125
4
#Pedirle al usuario que ingrese el monto disponible en su tarjeta de crédito. Evaluar si puede realizar una compra de $2500, # si puede indicar cuánto saldo le queda luego de efectuarla. Si no puede, indicar cuánto dinero le falta para poder realizarla. monto_disponible = int(input("Ingrese el monto disponible: ")) c...
b23c4da2e4228302f87d3aa14a3ac6f1a0675e7a
grace-omotoso/CIS-202---Python-Programming
/Chapter 5 - Code/Writing Your Own Value-Returning Functions/odd_even.py
531
4.15625
4
# A program to demonstrate how functions can return # Boolean values def main(): number = int(input('Enter a number: ')) if is_even(number): print('The number is even. ') else: print('The number is odd. ') def is_even(number): # Determine whether number is even. If it is, # ...
245d99b7246104c54b099d831e2e8f3b9a9d8bda
swang2000/DSAPractice
/Leet_maximumBinaryTree.py
558
3.734375
4
# Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def constructMaximumBinaryTree(self, nums): if len(nums) > 0: a = max(nums) root = TreeNode(a) root.lef...
dd2dfe5ef34f423e339ce1970453b05336d69640
alcebytes/Phyton-Estudo
/97_prog_funcional/04_4_higher_order_filter.py
638
3.734375
4
def isPrime(x): for n in range(2, x): if x % n == 0: return False else: return True fltrObj = filter(isPrime, range(10)) # Nº Primos de 1-10: [3, 5, 7, 9] print('Nº Primos de 1-10:', list(fltrObj)) # Programa para filtrar apenas os itens pares de uma lista lst = [1, 5, 4, ...
b70a87521d16490b190f26aa42c9454a4bb462b5
jusui/Data_Science
/Data_analysis/Titanic/Titanic_4.py
1,909
3.59375
4
import pandas as pd from pandas import Series, DataFrame import numpy as np import matplotlib.pyplot as plt import seaborn as sns """ Titanic dataset Paramters ------------------ SibSp : 兄弟姉妹と同乗 Parch : 両親と同乗 """ titanic_df = pd.read_csv('train.csv') ## 乗客が独身が既婚か調べる titanic_df['Alone'] = titanic_df.Parch + titan...
711d5861ce0a295d5bf6535386f79cf919036a14
ishankkm/pythonProgs
/leetcode/lengthOfLastWord.py
370
4.09375
4
''' Created on May 5, 2018 @author: ishank Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word in the string. If the last word does not exist, return 0. ''' def lengthOfLastWord(s): arr = s.strip().split(sep=" ", maxsplit=-1) return len...
5ff54c15752dc19a1bed1e4365c00c7977330152
aveekkar/MyRep
/primefactor.py
427
3.9375
4
import math print 'input number to factorize' try: num=int(raw_input('>')) except: print 'go learn numbers first!!' factors=list() temp=None def factorize(n): global temp r=int(math.ceil(math.sqrt(n))) if(r>1): for i in range(2,r+1): if((n%i)==0): factors.append(i) n=n/i temp=n factorize(n) ...
15227a683dcb41ffabbffb373a3ebfd540d3eecb
hellion86/pythontutor-lessons
/11. Словари/Номер появления слова.py
968
3.921875
4
''' Условие В единственной строке записан текст. Для каждого слова из данного текста подсчитайте, сколько раз оно встречалось в этом тексте ранее. Словом считается последовательность непробельных символов идущих подряд, слова разделены одним или большим числом пробелов или символами конца строки. ''' #Мое решение #Да...
f7c9c2f3b10ae602e5b14c8b2107734d0e3764c5
NareshKurukuti/python_part_one
/dictionaries.py
590
4.15625
4
# dictionaries # # It has Key, Value Pair my_dctry = {"key1":"value1", "key2" : "value2"} print(my_dctry['key1']) # dictionaries keys having lists my_dctry_one = {"key1":"value1", "key2": "value2", "key3": {'123':[1,2,3]}, "key4":"ATLP"} print(my_dctry_one['key3']['123']) print(my_dctry_one['key3...
50ac910a3e726e9a4838181b123981c552a12623
barros/practice
/python/num_valid_paths.py
1,246
3.640625
4
""" Given an n by m matrix of 0s and 1s, return the number of ways to reach the bottom right corner from the top left. Assume there will always be a 0 in the top left and bottom right corners. 0 represents an empty space while 1 represents a cell you cannot walk through. Input: [[0, 1, 0], [0, 0, 1], [0, 0, 0]] Out...
466f902bb7328e27056d914d6bfe916eaad126d5
nsuryateja/python
/RomanToIntegers.py
663
3.703125
4
# CXDC(Reverse of given string) - 100 -10 + 500 -100 Roman = {"I":1,"V": 5,"X": 10,"L": 50,"C": 100,"D": 500,"M": 1000} inputString = "CDXC" revString = inputString[::-1] #Adding the first char count = Roman[revString[0]] #Add or Substract for 1 to last but one character for char in range(1,len(revString) - 1): ...
48ca5f2eb1c7d20b63d73f05307b981e7b6514d5
rodumani1012/PythonStudy
/Workspace_Python/HelloPython/com/test01/Lambda.py
1,407
3.671875
4
# Lambda(람다) # var hap = function(a,b) { return a+b} 와 같은 식 hap = lambda a, b : a + b # lambda 파라미터 : 실행할 내용 print(hap(1,2)) gob = lambda a, b : a * b print(type(gob)) print(gob(3,4)) hap = lambda a,b,c : a+b+c print(hap(1,2,3)) min = lambda x,y : x if x < y else y # x < y가 true면 x 출력, 아니면 y 출력 print(min(4,5)...
e4167dc93c096149c0aefb2dc32f981a8e065df4
gkcksrbs/Baekjoon_CodingTest
/src/문자열/Baekjoon_10809_알파벳 찾기.py
1,382
3.625
4
# 1. 단어의 길이가 100을 넘지 않고 알파벳 소문자로만 이루어진 문자열을 입력받는다. # 2. 1번을 만족하지 않을 경우 다시 입력 받도록 한다. # 3. 길이가 26인 리스트를 하나 만들고 모든 원소에 -1로 초기화한다. # 4. 'a'의 아스키코드 값은 97이므로 문자열을 처음부터 가면서 리스트 (한 문자의 아스키코드 값 - 97)번째에 문자열의 위치를 저장한다. # 5. 해당하는 리스트 번째에 -1값이 아닌 다른 수가 저장되어 있다면 그냥 넘어간다. # 6. 각각의 알파벳에 대해서 처음 등장하는 위치를 출력한다. # 문자열 입력 while(True): ...
bb223f4f3a35de814ae68fb534e84816d0fec417
GDN2/DL
/DeepLearning/Legathy/dir5/function_lambda.py
608
3.75
4
def sum(x,y): s = x+ y return s result = sum(10,20) print(result) def multi_ret_func(x): return x+1,x+2,x+3 x=100 y = multi_ret_func(x) print(y) print(type(y)) def print_name(name, count=2): for i in range(count): print("name == ", name) print_name('DAVE') def mutable_immutable_func(int_x, i...
fea79b3ea81dfed6f26f5b0966d529edf133446c
MrHamdulay/csc3-capstone
/examples/data/Assignment_3/clcsha002/question1.py
205
3.984375
4
def rectangle(): x = eval(input("Enter the height of the rectangle: \n")) y= eval(input("Enter the width of the rectangle: \n")) for i in range (x) : print ("*" *y) rectangle()
ad638fc4992df101f7be267f3dbbf84f379cdced
DRMPN/PythonCode
/CodeWars/7kyu/list_filtering.py
222
3.828125
4
# In this kata you will create a function that takes a list of non-negative # integers and strings and returns a new list with the strings filtered out. def filter_list(l): return [i for i in l if isinstance(i, int)]
ab8a6639454501a4ffd22798de74a6ebf3781dc9
guojia60180/algorithm
/算法题目/算法题目/树/BST二叉查找树/LeetCode530二叉查找树中查找两个节点差的最小绝对值.py
756
3.78125
4
#Author guo # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def getMinimumDifference(self, root): #利用二叉查找树的中序遍历有序的性质,计算中序遍历 #临近两个节点之差的绝对值,取最小值 self.minDiff=int(f...
43f8d41964ea057b94363fa0020d0335194c824e
zhou7rui/algorithm
/sorting/python/merge_bu_sort.py
893
3.765625
4
# -*- coding: utf-8 -* ''' 并归排序 通过循环 至底向上的的形式实现 ''' import sort_helper def merge(arr,l,mid,r): aux = arr[l:r+1] i = l j = mid + 1 for k in range(l,r+1,1): if i > mid: arr[k] = aux[j - l] j +=1 elif j > r: arr[k] = aux[i - l] i +=1 ...
272c482c37bb789e8a710a6fc6e4ca65995b8d8e
JaocbHao/PythonLearn
/timeloop.py
247
3.8125
4
# Output the entire wizard’s spell by counting from 1 to N, giving one number and “Abracadabra” per line x = input() i = 1 #for number in range (int(x)): # print(x + "Abracadabra") while i < int(x)+1: print(i,"Abracadabra"); i = i+1;
fffb6036845d307c97b725f070f028e16d22955f
itroulli/HackerRank
/Python/Strings/011-alphabet_rangoli.py
577
3.78125
4
# Name: Alphabet Rangoli # Problem: https://www.hackerrank.com/challenges/alphabet-rangoli/problem # Score: 20 def print_rangoli(size): # your code goes here abc = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] ...
83fde3d99a143205999d6856b659eaff2690bdf9
89erik/NES-portal
/preprocessor/source.py
861
3.578125
4
import re from code import CodeException def intToBin8(num): if num < -127 or num > 0xFF: raise CodeException("value %d cannot be represented in 8 bits" % num) if num >= 0: return str(num) decval = 0xFF + num return "$" + hex(decval)[2:] def convertNegativeNumber(match): num = int...
af631370399ddd55d9eb01c72e01f9cbb9894b50
Ever1ck/Examen-Fundamentos-de-la-Programacion
/Examen3.py
514
3.515625
4
def Bonosueldo(): tvacuna = str() edad = float() genero = str() print("Ingrese la Edad del paciente") edad = float(input()) print("Ingrese el sexo del paciente V para masculino y F para Femenino") genero = input() if edad>=70: tvacuna = "Vacuna Tipo C" if genero=="F" and edad>=16 and edad<=69: t...
a0bf243480b693a93c25c50d57521db6016509c8
ankitoct/Core-Python-Code
/36. Formatting String/4. FormatMethodExample3.py
682
3.984375
4
# Comma as thousand Separator print("{:,}".format(1234567890)) #variable name = "Rahul" age= 62 print("My name is {} and age {}".format(name, age)) # Expressing a Percentage a = 50 b = 3 print("{:.2%}".format(a/b)) # Accessing arguments items value = (10, 20) print("{0[0]} {0[1]}".format(value)) # Format with Dict ...
0ce0a1aa480f97e14790fe5f91d2a67509062a0a
timeless0728/leetcode
/114.py
889
3.9375
4
# Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def flatten(self, root): """ :type root: TreeNode :rtype: void Do not return anything, modify root in-place...
6570a0c119673566a18dd950d251eec7ff85262f
DanyloTrofymov/LabsPy
/Lab3/Lab3.py
284
3.59375
4
#Трофимов Данило ІП-02 #Лабораторна робота 3 #Варіант 5 import math x = float(0.56) n = float(0) s = float(0) k = float(1) m = float(0.0001) while math.fabs(k) > m: k = ((-1)**(n))*((x**(2)*(n+1))/(2**n+1)) s = k + s n = n + 1 print("{:12.9f}".format(s))
17af41b501e894dd185b46cd054518631264d72d
Arnob71/Python
/CSE-1112/py6.py
236
4.28125
4
print("This is a program to print all odd numbers in a range limit") start = int(input("Enter the start number: ")) end = int(input("Enter the end number: ")) for i in range(start, end+1): if i % 2 != 0: print(i, end = " ")
587b8e9605b46beef0a224ced11f53b2f111d1b2
mayfer/transit
/schedule/gtfs.py
832
3.53125
4
from datetime import date, time, datetime, timedelta def parse_stop_time(departure_time): parsed_time = None try: parsed_time = datetime.strptime(departure_time, "%H:%M:%S") except Exception: # gtfs says: ## For times occurring after midnight on the service date, ## enter t...
f34af79b8bbbadce64c2cad16658d413f82f6c59
hakancelebi/coding-exercises
/if-elif-else_boy_kilo_indeks.py
293
3.890625
4
kilo = int(input("Kilonuz: ")) boy = float(input("Boyunuz: ")) indeks = kilo // (boy * boy) if (indeks < 18.5): print("ZAYIFSINIZ") elif (18.5 < indeks < 25): print("KİLONUZ NORMAL") elif (25 < indeks < 30): print("FAZLA KİLOLUSUNUZ") else: print("OBEZSİNİZ")
99b38def2e6d74336c826dd5b0d14f2ae7209ae0
sridevpawar/AlgoRepo
/CodeingQuestions/CodeingQuestions/printStringPermutations.py
439
3.8125
4
def printStringPermutations(str): if len(str) == 0: return [] if len(str) == 1: return [str] list = [] for i in range(len(str)): a = str[i] b = str[:i]+str[i+1:] for x in printStringPermutations(b): list.append(a + x) return list str1 = "ABC" str2 = "ABSG" an...
f0875af875ead951e7b9435f2165d0780fbfa7b0
wphyo3820/nba_fantasy
/rank.py
1,234
3.546875
4
import pandas as pd import numpy as np from sklearn import preprocessing default_cols = ["FGP", "FTP", "3PM", "PPG", "RPG", "APG", "SPG", "BPG", "TPG"] def get_rankings(data: pd.DataFrame, col_names: [str], n_results: int) -> pd.DataFrame: """ Creates scaled rankings based on data.csv Argument...
25c805c014a1702ed4af9a6e21b44ac0b436632f
aliattar83/python
/Code/Chapter 4/Programming Excercises/dollar_game.py
464
3.78125
4
DOLLAR = 100 def main(): pennies = int(input('Enter pennies: ')) nickels = int(input('Enter nickels: ')) dimes = int(input('Enter dimes: ')) quarters = int(input('Enter quarters: ')) calc(pennies, nickels, dimes, quarters) def calc(p, n, d, q): total = p + n * 5 + d * 10 + q * 25 if total == DOLLAR: print('...
7795951a71a6d8563524445a293b2ecf27dd737c
alexandrudsc/hackathon-whitehats
/server_client_/server.py
6,558
3.515625
4
#!/usr/bin/env python """ Multi-threaded TCP Server multithreadedServer.py acts as a standard TCP server, with multi-threaded integration, spawning a new thread for each client request it receives. """ import requests import json from argparse import ArgumentParser from threading import Lock, Thread from socket import...
6152d27ae783d28503f6bc1242bc5b02ee7b62f1
Orb-H/rushhour-gui
/src/solver.py
5,345
3.734375
4
def solve(board_start): # board format in a 2-dimensional list of cells visited = set() # visited board state queue = [] # BFS queue queue.append((board_start, '')) while len(queue) > 0: board, path = queue.pop(0) if stringify_board(board) in visited: continue if...
e1a63f81dd885fcac9da293475c43542d8530193
sairaja9/Tic-Tac-Toe-AI
/SaiTicTacToe.py
3,881
3.765625
4
#import colors def is_board_full(board): for lists in board: for item in lists: if item == " ": return False return True def is_valid_move(board, location): # Check if location is in range if location not in range(1, 10): return False row = (location -...
4da0a4b02f0086746de835e04296cb6902121de7
YG15/NLP-Project
/Yules_LD/yule_ind.py
3,770
3.546875
4
################################################ # Name: yules_ind # Author: Yonathna Guttel # Purpose: computes Yule's index which measure Lexical Diversity (LD) # Arguments: A text string # Returning: Its Yule indecies # date: 10.12.2017 # Version: 4 ############################################## def yules...
28e7e1e7eb984f0104a386833d3e168cfcef209f
johngriner91/ColorCube
/Python/main.py
1,100
3.984375
4
############################################################################## # Author: John Griner # File Name: main.py # Version: python 3.4 ############################################################################## #!/usr/bin/python # Grab the cube implementation from the Cube.py file from Cube i...
9272edbd5233b5da530c71c384510638a4e92301
Litao439420999/LeetCodeAlgorithm
/Python/findCircleNum.py
1,632
3.734375
4
#!/usr/bin/env python3 # encoding: utf-8 """ @Filename: findCircleNum.py @Function: 省份数量 熟悉 图 的表示方法 @Link: https://leetcode-cn.com/problems/number-of-provinces/ @Python Version: 3.8 @Author: Wei Li @Date:2021-07-11 """ import collections class Solution: def findCircleNum(self, isConnected): def dfs(i: in...
345fa8b7e394aa7596f0631c290debe4add92f55
nevesgil/mitx6002
/unit1/optimization_and_knapsack/generator2.py
2,016
4.1875
4
''' Write a generator that returns every arrangement of items such that each is in one or none of two different bags. Each combination should be given as a tuple of two lists, the first being the items in bag1, and the second being the items in bag2. ''' # Answer: def yieldAllCombos(items): """ Generates all ...
0308769982923a8f5463a7f7dd979ee0f87d3308
juandacoga/misiontic
/devuelta.py
294
3.765625
4
money = 200 value = 150 if (money < value): print('El dinero que tiene no es suficiente para esta compra.') else: change = money - value if (change == 0): print('No hay devuelta el dinero fue igual a la compra') else: print('Su devuelta es de: ' + str(change))
bcd8d6cf6ed7ff8a3482a0bd18e271dc562f5d11
Quantium/gettingInShape
/datastructures/linkedList/linkedList.py
1,797
3.765625
4
#!/usr/bin/python3 class Node: def __init__(self, dataval=None): self.data = dataval self.next = None class SLinkedList: def __init__(self): self.head = None def listprint(self): printval = self.head while printval is not None: print (printval.data) ...
c22c3b27487b3e5eaf38f40ef342e565a23c1886
Maymayjung/sea-c45-python
/hw/hw18/html_render.py
3,717
3.640625
4
#!/usr/bin/env python """ Python class example. """ # The start of it all: # Fill it all in here. class Element(object): IND_LEVEL = " " def __init__(self, name="", content="", **kwargs): self.name = name self.children = [content] if content else [] self.attributes = kwargs ...
a467639a935e1b2ffcb15b83ee665245299a09cb
Sathyanathan1994/Python_Problems
/Python_Assignment/Fibonacci_series.py
662
3.921875
4
# Fibonacci series class Fibonacci_Series: def __init__(self, limit, f, s): self.limit = limit self.f = f self.s = s def Operation(self): if self.limit < 0: return "invalid input" elif self.limit == 1 or self.limit == 2: return 1 else: ...
7c406454705fb1b57acbfbf1e7deb752d24e5b75
Soroushbolbolabady/hangman
/hangman.py
676
3.90625
4
import secrets Words = ["tehran" , "rasht" , "new york" , "texas" , "paris" , "berlin" , "rome" , "london" , "tokyo" ] hangman_word = secrets.choice(Words) letter_count = len(hangman_word) guess = 0 score = letter_count is_not_win = True while is_not_win: user_guess = input("Emter a Character : ") if user...
d4e5934a7922da0e46ed7dee0f70e8baaea20a17
zxwtry/OJ
/python/leetcode/P053_MaximumSubarray.py
556
3.5
4
#coding=utf-8 ''' url: leetcode.com/problems/maximum-subarray @author: zxwtry @email: zxwtry@qq.com @date: 2017年4月10日 @details: Solution: 59ms 53.69% ''' class Solution(object): def maxSubArray(self, n): """ :type n: List[int] :rtype: int """ ...
f0ed2373543bc447f4c1770497a92203fcad8584
jchen66/comp321
/contest2/pseudoprime.py
478
3.984375
4
import sys # check whether a number is prime def isPrime(num): for i in range(3, int(num**0.5)): if num % i == 0: return False return True for line in sys.stdin: num1, num2 = line.split() p = int(num1) a = int(num2) if not (p == 0 and a == 0): # built in function ...
2ea5a29933e8cb83d6c60a83d9308fbd8d120c2f
mcp-team/mcp-starter-pack
/solutions/roads_and_libs/sol.py
663
3.65625
4
def find(x): if x!= parent[x]: parent[x] = find(parent[x]) return parent[x] def union(x,y): global groups x_root = find(x) y_root = find(y) if x_root != y_root: groups -= 1 parent[x_root] = y_root q = int(raw_input()) for a0 in range(q): cities,roads,clibs,...
133ecf1bc5302d92f35cad58fcde4d8a2beb93f0
ie03-aizu-2019/ie03project-tsujigiri
/src/intersection.py
2,286
3.734375
4
""" The program to research there are intersections, mC2 times research """ import Cross_Checks # not need import Point import Line class intersection: def __init__(self, lines): self.Cpoints = self.func(lines) @classmethod def fun...
551d5432d8fb638f42e3d588ab3dff878e264238
brahamlir/figuras_bdd
/figuras/figura.py
1,185
3.578125
4
import math as m class Figuras: def cuadrado(self, lado): try: lado = float(lado) return lado * lado except Exception: return 'dato incorrecto' def rectangulo(self, base, altura): try: if base < 0 or altura < 0: ...
f070cf7943b1898c1a135a833551463a23c02e9b
redmage123/basicpython
/examples/calculator_test.py
1,174
3.765625
4
#!/usr/bin/env python import unittest # This is the class that we're going to test from calculator import Calculator """ Run this program by calling 'nosetests calculator_test.py' You must install nosetests manually via the pip command. If you don't have pip installed, then, again you need to install...
5b263383b91423f80097ce1241466a3800f8b343
patrickdavey/AoC
/2018/5/src/runner.py
839
3.546875
4
import string import re from collections import Counter class Runner(): def part1(self, test): finished = False length = len(test) while (finished == False): for char in string.ascii_lowercase: upper_char = char.upper() replace = f"{char}{upper_char}" test = test.replace(rep...
4b386ed8ca740085645767cb5f470a8c10a501b7
ajfm88/PythonCrashCourse
/Ch5/checking_usernames.py
1,293
4.34375
4
#Do the following to create a program that simulates how websites ensure that everone has #a unique username. #Make a list of five or ore usernames called current_users. #Make another list of five usernames called new_users. Make sure one or two of the new #Usernames are also in the current_users list. #Loop through th...
c98adcdda5425d10556b2ec471b3a41804099f88
sweetfruit77/Test
/python_study/day002_func002.py
303
3.84375
4
# call_by_value , call_by_reference def call_by_value(num,mlist): num = num+1 mlist.append("add1") num = 10 #인트는 10이라는 값이 들어감 mlist = [1,2,3] #리스트는 객체의 주소값이 들어감 print(num,mlist) call_by_value(num,mlist) print(num , mlist) # __name__ 변수
7099c39e40d9b8a6850e41fde6c2f10575592b6d
SalihTasdelen/Hackerrank_Python
/Itertools_Product.py
262
3.84375
4
# Enter your code here. Read input from STDIN. Print output to STDOUT from itertools import product alist = list(map(int, input().split())) blist = list(map(int, input().split())) tlist = list(product(alist, blist)) print(" ".join(str(item) for item in tlist))
9c288f8741996db0eb1bcfd9890ddc9ef58138b5
nanchano/Algorithms
/trees/binary_search_tree.py
4,733
4.125
4
# For this one we declare the node property inside the tree (self.node = None) instead of root as in the binary_tree and max_heap. # This updated references without having the parent property. # This means we have to instantiate a new BST when creating a left or right node. # Example: # bst = BST() # bst.n...
3f87dbbd47303aab82b10289e6f8b55b31be34ba
MykouNet/python_1
/exo1.3_identique_ou_pas.py
309
3.578125
4
#!/usr/bin/env python3 # ./exo1.3_identique_ou_pas.py prem_chain = input("Merci de saisir une premiere chaine ") seco_chain = input("Merci de saisir une seconde chaine ") if ( prem_chain == seco_chain ): print ("les 2 chaines sont identiques") else: print ("les 2 chaines NE sont PAS identiques")
0be10137ad48e0f90ba644389bf6316531338079
yordan-marinov/advanced_python
/error_handling/email_validator/email_validator.py
904
3.5625
4
from constants import MINIMUM_NAME_LENGTH, VALID_DOMAINS, AT_SYMBOL import exceptions def validate_email( email, length=MINIMUM_NAME_LENGTH, domains=VALID_DOMAINS, at_symbol=AT_SYMBOL ): def validate_at_symbol(): if at_symbol not in email: raise exceptions.MustC...
ee17aa2e426629166275f4829b2af7206c21d018
rajishwagh/Interview-Cake-problems
/get_products_of_all_ints_except_at_index.py
1,312
4.21875
4
''' Created on Jul 20, 2017 @author: rjw0028 ''' ''' You have a list of integers, and for each index you want to find the product of every integer except the integer at that index. Write a function get_products_of_all_ints_except_at_index() that takes a list of integers and returns a list of the products. ...
60ed27ceff30156bba18f33195a0cb5e1817d24a
HotSauceMan/BoardPrinter
/BoardPrinterProject/test/test_input_example.py
2,123
4.34375
4
""" Demo for how to use patch to override input's behavior when testing """ import unittest # import patch, the function that we will use # to replace the behavior of the normal input function from unittest.mock import patch from BoardPrinterProject.src.input_example import add2numbers_from_user, multi_li...
69e93fe8786635c22aa471daff969089dd51b60e
Tiberius24/Python_Training
/TPoint_Plotter.py
2,492
3.5625
4
import turtle wn = turtle.Screen() niko = turtle.Turtle() niko.shape('turtle') niko.speed(15) class TPointPlotter(): def __init__(self): """Initialize the class""" def create_dict_from_list(self, c_list): """Create a dictionary from list that was generated from a file.""" ...
3eee02c400c9f3f71a4a706e64c925751b5c1b86
meghnaraswan/PythonAssignments
/MRaswan_Assignment1/TotalPrice.py
543
4.28125
4
#Meghna Raswan #2337415 #raswan@chapman.edu #CPSC 230-10 (1515) #Assignment 1 #total price of an item #get puchase price and sales tax rate of item PurchasePrice_str = input("What is the purchase price of your item? ") SalesTaxRate_str = input("What is the sales tax rate? ") #convert input to float PurchasePrice_floa...
924c94cd7f992b992e00244b408bc35d43712189
WillyAgustriDjabar/Training-python-
/Dasar-Dasar Python/tkinker tutorial/icon.py
354
3.734375
4
from tkinter import * root = Tk() root.title("Simple Icon") root.iconbitmap('D:\Kuliah\icon\icon.ico') mylabel = Label(root, text= "budidaya ikan lele") mylabel.grid(row=0,column=2,padx= 50,pady= 5) mylabel2 = Label(root, text="budidaya geprek", bd=2, relief=SUNKEN) mylabel2.grid(row=1,column=2,columnspan= 2, stick...
8f10ea390d68cbb8760e872604ec428d633fc5da
evanchan92/git_terminal
/ex16-self testing.py
660
4.5
4
# testing filename = raw_input('''We're going to edit a file via this program, first, we need to type in the name of the file ... ''') print "We're going to erase %r." % filename print "if you want that, hit RETURN." raw_input("?") print "Opening the file..." target = open (filename,'w') print "Truncating the file...
f891287287ba4cfb2cf0c924fcd8dec54aed77f3
pas97363/exam
/3.py
968
3.828125
4
from collections import defaultdict class Graph: def __init__(self,vertices): self.V = vertices self.graph = defaultdict(list) def addEdge(self,u,v): self.graph[u].append(v) def printGraph(self): print(self.graph) def DLS(self,src,target,maxDepth): if src == targ...
7042c7773aa5b42498b908bd7d6109332a441c79
carolana/learning-area
/projects/python-theory/operadores-logicos-e-matematicos/operadores-logicos.py
103
3.640625
4
x = 3 y = 3 z = 3 #print(x == y and x == z) #print(x == y or x == z) print(x == y or x == z and y == x)
3194517355fd6efd0a4eba0d160cfbee8ee28b8f
jolinchen0102/Chess-AI
/play.py
1,805
3.875
4
"""Main entry point into the game""" import board import re import time class bcolors: HEADER = '\033[95m' OKBLUE = '\033[94m' OKCYAN = '\033[96m' OKGREEN = '\033[92m' WARNING = '\033[93m' FAIL = '\033[91m' ENDC = '\033[0m' BOLD = '\033[1m' UNDERLINE = '\033[4m' def check_inpu...
bb30d1e80d3f9f8b24b8dbd69110a529b0ab131a
UWPCE-PythonCert-ClassRepos/Wi2018-Classroom
/students/bryan/session02/fizzbuzz.py
862
4.03125
4
def fizzbuzz(): """print numbers from 1 to 100 inclusive. for multiples of 3 print fizz instead of numbers for multiples of 5 print buzz instead of numbers for multiples of both print fizzbuzz """ print("hi") idx = 1 while idx <= 100: if idx % 3 == 0 and idx % 5 == 0: ...
1f135ad2ed4b8ca1a3afd5496320dc4ed32df061
lyd0527/Clouseau
/modules/Storage/Chr.py
981
3.515625
4
#!/usr/bin/env python import logging logger = logging.getLogger(__name__) class Chr(object): """ Chromosome Variant object """ def __init__(self, chrom_name, position): self.chrom_name = chrom_name self.start = int(position) self.end = int(position) self.variants = {} #...
0337591adf1177272493ef89f1b36e6cd0f24639
protea-ban/LeetCode
/024.Swap Nodes in Pairs/Swap Nodes in Pairs.py
591
3.765625
4
# Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def swapPairs(self, head): """ :type head: ListNode :rtype: ListNode """ ret = cur = ListNode(0) cur.next = head # 终...
3759a6d475490af8b014d763a54721eb0b743b15
DomBrass/QMEEBootcamp
/Week2/Code/cfexercises1.py
601
3.734375
4
#!/usr/bin/env python3 # #Author: Dominic Brass #Script: cfexcercises1.py #Arguements: none #Date: Oct 2018 """Some loops demonstrating control flow.""" for i in range(3,17): print('hello') for j in range(12): if j % 3 == 0: print('hello') for j in range(15): if j % 5 == 3: print('hello...
1a9bf471c01a48ab0dd9ab72a613050368b9780b
will-hossack/Poptics
/examples/spectrometer/Spectrometer.py
1,795
3.859375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Example program to simulate a simple prism spectrometer. The system is set to min deviation at Mercury e line, then output angle are calcualted between Mercury i line and Helium r line by ray tracing """ import poptics.ray as r from poptics.spectrometer import Prism...
45db4ec678045e7381b1a580758d32873bb77de8
lauragustafson/BTB
/btb/selection/selector.py
2,076
3.828125
4
import numpy as np class Selector(object): def __init__(self, choices): """ Args: choices: a list of discrete choices from which the selector must choose at every call to select(). """ self.choices = choices def compute_rewards(self, scores): ...
0deff01c5d0f78c07bf32b025ca1cb48a25ac250
fzhao99/interviews
/ctci/chpt2/Q1.py
943
3.625
4
import sys sys.path.append("..") from data_structures.LinkedList import LinkedList def remove_dups(ll): if ll.head is None: return current = ll.head refTable = {current.value} while current.next: if current.next.value in refTable: current.next = current.next.next ...
8e9b898f03f3a2183664aeeaa1e1bf11e7672f70
Geodit/Homework
/task4_les3.py
1,302
4.4375
4
# 4. Программа принимает действительное положительное число x и целое отрицательное число y. Необходимо выполнить # возведение числа x в степень y. Задание необходимо реализовать # в виде функции my_func(x, y). При решении задания необходимо обойтись без встроенной функции возведения числа # в степень. # Подсказка: поп...
7d13d02872e3956872a19dc3d0e04fc50f1fab54
baradhwajpc/Learning
/Lectures/Day-3/dictionary and numpy.py
3,421
3.65625
4
# -*- coding: utf-8 -*- """ Created on Thu Oct 12 07:05:53 2017 @author: baradhwaj """ # List math_score_list = [95,67,88,45,84] type(math_score_list) print(math_score_list[2]) #Dictionary # Doubts # can we have a list as value ? - Yes '''what data types are permitted to the key - Immutable Data Types are allowed. ...
515744e01c708029ab558842c736a6ae3d8b8428
PrachiGupta123/MSCW2020_Python
/While_loops_Demo.py
261
4
4
""" While loop in python """ for no in range(10): print(no) print("printing in Reverse order") for no in range(10,0,-1): print(no) age = 12 while age<18: age += 1 print("You can not vote") if age == 18: break
05d9e48e563e01f98157111d0474415286ef612a
NickTrossa/Python
/pruebas/prueba_print_matriz.py
565
3.6875
4
# -*- coding: utf-8 -*- """ Created on Sat Jul 18 14:12:22 2015 @author: alumno """ #import numpy as np def printarray(mat,dig): """ Muestra en la consola la matriz con 'dig' cifras significativas. """ fil = mat.shape[0] col = mat.shape[1] fmt = '\%.%ie'%3 print('[[',end=" ") for i in...
171f34adcc0bf7a96fdd072cba3b9d061a2071ae
WuLC/NowCoder
/剑指offer/对称的二叉树.py
698
3.890625
4
# -*- coding: utf-8 -*- # Created on Fri Mar 09 2018 14:48:11 # Author: WuLC # EMail: liangchaowu5@gmail.com # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None # divide and conquer class Solution: def isSymmetrical(self, pRoot): if ...
65f03812c90c8eeb408d369ef9262e1ab7917367
PhilipHanke/legaltech
/geschwindigkeitsuebertretung.py
993
3.921875
4
def geschwindigkeitsuebertretung(): location = input("Wo bist Du gefahren? (innerorts, ausserorts, Autobahn)") geschwindigkeit = input("Wie schnell bist Du gefahren? ") geschwindigkeit = int(geschwindigkeit) if (((50 <= geschwindigkeit <= 70) and (location == "innerorts")) or ((120 <= geschwindigkeit ...
713189ded1bb62a2e4a892307da0456345a94ea4
IanCBrown/practice_questions
/picking_numbers.py
349
3.609375
4
#!/bin/python3 import math import os import random import re import sys # https://www.hackerrank.com/challenges/picking-numbers/problem def pickingNumbers(a): num = 0 freq = [0] * 100 for i in range(len(a)): freq[a[i]] += 1 for i in range(1, 100): num = max(num, freq[i] + fr...
80133290aa0e37615bffc78b0940962e7f117400
Matheus-Nazario/tudo_sobre_dicionario_modulos.py
/calcular_salario.py
1,594
4.09375
4
""" A função recebe como entrada dois parâmetros: Um dicionário contendo como chave o nome de um funcionário e como valor uma lista contendo email, salário-base e cargo desse funcionário. O nome de um funcionário. Observe abaixo um exemplo do formato do dicionário de entrada para a função: {'marcilio': ['marcilio@email...
c5601ebd19fda93e75d4ec897958428b71d95e87
sagarkamthane/selenium-python
/seleniumproject/Velocity/for loop.py
243
3.765625
4
for a in range(4) : for b in range(2) : print("Hi", end= "") print("sagar", end="") print("kamthane", end="") #prints in same line print("ok") for i in range(4): for j in range(3): print("*", end="") print("")
f8bf861d10c727b7bfde898fbe9841253c9b710e
salvador-dali/algorithms_general
/__competitions/2015/05_25_w15/02.py
423
3.5625
4
from Queue import PriorityQueue def solve(elements): maximum, q = 0, PriorityQueue() for a, b in elements: q.put((b, a)) while not q.empty() and q.queue[0][0] + 1 < len(q.queue): q.get() if len(q.queue) > a: maximum = max(maximum, len(q.queue)) return maxim...
81fb25f5142e3eb3d871bffe289dfc81a680b26c
WesleyEspinoza/CS-PythonWork
/CS1.2/FishPractice.py
687
3.859375
4
import sys import re, string, timeit, random from string import punctuation def strip_punctuation(s): return ''.join(c for c in s if c not in punctuation) def get_words(): word_dict = {} accumulator = 0 words = "one fish two fish red fish blue fish".split(' ') for word in words: if word ...
9a4922543e2cfb9c0ee57f68ea30fd376957425d
PTC-Education/PTCColab
/input_utils.py
4,855
3.96875
4
############################################# # # # User Input functions # # # ############################################# # readInTransformObject() - Creates transform args objects (as defined above) # Paramete...
be0ee839bb3324906cbcbc3aaedfa7cbc9e2dfac
yushinliu/leetcode
/data_structure/Balanced_binary_tree/recursive.py
567
3.671875
4
class Solution: def isBalanced(self, root): #recursive """ :type root: TreeNode :rtype: bool """ if not root: return True def depth(node): if not node: return 0 # leaves has no length left=depth(node.left) ...
e799f99edeb3b5e2b00b0b16f95ee50a46fc7100
raytwelve/LeetCode
/Easy/Best Time to Buy and Sell Stock.py
621
3.9375
4
''' https://leetcode.com/problems/best-time-to-buy-and-sell-stock/ Say you have an array for which the ith element is the price of a given stock on day i. If you were only permitted to complete at most one transaction (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit. No...
137c171a25ccc3c82fa0f68e33175fc5f6bc0361
jayjay1973/CIS115-Python-Labs
/williamPrudencio_lab5-23.py
2,955
4.0625
4
#Program, williamPrudencio_lab5-23.py, 02/16/19 ''' This program will use turtle graphics to display a snowman. There will be five different functions used to accomplish this task. ''' def main(): #draw the base drawBase(0, 0, 100 , "white") #draw the mid section drawMidSection(0, 175, 75, "white") ...
d759073a3c787b5b195f7979bcf58eed10a9129b
MiguelTamayo/Garrison_Siner_Tamayo
/backend/src/unittest/python/database_tests.py
5,505
3.5625
4
import unittest from database import Database import os class DatabaseTest(unittest.TestCase): def setUp(self): self.db = Database("test.db") self.account = { "username": "firstUser", "password": "p@55w0rd", "email": "name@email.com", "firstName": "john", "lastName": "smith", "phoneNumber": "12...
4139675f69c1716848394234be30ad6a70f7e90b
1769778682/python03
/class/c01_while循环.py
672
4.09375
4
# 需求: 打印 100 遍 "媳妇儿,我错了" # 定义重复次数计数器 num = 0 # 使用while判断条件 while num < 2: # 要重复执行的代码 print('嗨皮', end='') # 处理计数器数值 num += 1 print('循环结束') # 一般情况下,如果在循环中忘记修改循环条件,就会导致死循环 # (不修改条件,循环条件会一直处于满足状态,循环就会一直运行下去) # Python的计数方法 # 自然计数方法,从1开始:人类习惯 # 程序计数方法,从0开始:几乎所有的编程语言都从0开始 # 因此,如果没有特殊情况应该从0开始计数,结束值不需要带等号
6b259c81491ba7dc19ea09e43c1e8d7695c1574f
dimitar-daskalov/SoftUni-Courses
/python_advanced/labs_and_homeworks/02_tuples_and_sets_lab/03_record_unique_names.py
172
3.859375
4
number_of_names = int(input()) unique_names_set = set() for _ in range(number_of_names): unique_names_set.add(input()) for name in unique_names_set: print(name)