blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
99868f04dc780e7e54ebcd607b97e0347d4cf51b
brn016/cogs18
/18 Projects/Project_jaz023_attempt_2018-12-12-11-46-14_JanaeZhang_final_project/JanaeZhang_final_project/my_module/functions.py
1,505
3.96875
4
#!/usr/bin/env python # coding: utf-8 # In[12]: """All of this is code taken from A3. end_chat has been modified to also recognize 'bye' and 'goodbye'. prepare_text has been modified so that 'big bear' can be recognized as one phrase""" #Remove the punctuation of the input def remove_punctuation(input_string): ...
49da24eb16e4f97d7cc853419f6612ed424b2fc3
PhamQuocDatAI/Code
/Bài 6.py
1,160
3.578125
4
# Tạo 1 list gồm các số ngẫu nhiên rồi tìm giá trị lớn nhất trong list (Ko dùng hàm max) import random n = int(input('Bạn muốn list có bao nhiêu phần tử: ')) a = int(input('Nhập giá trị đầu trong đoạn: ')) b = int(input('Nhập giá trị cuối trong đoạn: ')) c = int(input('Step: ')) while a>=b: print('Bạn nhập giá trị ...
760f24285b9c71af36f048b39153ed0b062bba87
KFredlund/AirBnB_clone
/tests/test_models/test_city.py
630
3.5625
4
#!/usr/bin/python3 """ Tests for class City """ import unittest from models.base_model import BaseModel from models.city import City from tests.test_models.test_base_model import TestBaseModel class TestCity(TestBaseModel): """ City Tests """ def __init__(self, *args, **kwargs): """ Constructor attr...
6790550aa02d37f3e6d311a37b3b97b428ba8272
eldadmwangi/sifu
/graphs/dfs.py
985
4.15625
4
''' Graph depth first search Given an undirected graph of integers graph, represented by an adjacency list, and an integer root, create a function that prints its values in depth first search, by considering the vertex whose value is root as the arbitrary node. Example 1: Input: graph = { "5" : [8, 1, 12], "8"...
41f2dbbda9aa256e9e9a315aed3de1aa545ae072
scottkuma/AdventOfCode2019
/Day1/day1-1.py
150
3.5625
4
def fuel(mass): return(int(mass) // 3 - 2) data = open('day1.txt').readlines() sum = 0 for mass in data: sum += fuel(int(mass)) print(sum)
38233251c0f9853ed7f8bbc5315ab730d7af854d
mandrei28/Teme-AI
/CA_Marcu_Andrei_Cristian/Code/Cars.py
9,415
3.5
4
from search import Problem import math from queue import * import random class Cars(Problem): def __init__(self, initial, goal = None): """ Define goal state and initialize a problem """ self.goal = goal self.matrix_size = int(math.sqrt(len(initial))) self.total_iteratio...
a3fa5ab755ee970ad4ff984bcecefac8a8437caf
akshaali/Data-Structure-
/Linked List/SinglyLinkedList/SimpleImplimentation.py
3,207
4.0625
4
class Node: def __init__(self, data): self.data = data self.next = None class LinkedList: def __init__(self): self.head = None #Tells length def listLength(self): currentNode = self.head length = 0 while currentNode is not None: length +=1 ...
55b40fceb8d99994dd2200eeb35f7ae22ce5913c
Iamprakashkhatri/basics
/listtodictionary.py
338
3.734375
4
def Convert(lst): res_dct = {lst[i]: lst[i + 1] for i in range(0, len(lst), 2)} return res_dct # Driver code lst = ['a', 1, 'b', 2, 'c', 3] print(Convert(lst)) list=[1,2,3,4] for i in range(0,len(list)): print(i) lst = ['a', 1, 'b', 2, 'c', 3,None] p={ lst[i]:lst[i+1] for i in range(0,len...
66a9e4ce203098c75b645588ffbb3cf11e54e547
Rupinderkaur28/emailer
/input.py
1,098
4
4
import re class User: def __init__(self, firstname, lastname, age): self.firstname = firstname self.lastname = lastname self.age = age def user_input(self): # firstname = input('enter firstname:') # lastname = input('enter lastname:') # age = int(input('enter a...
0213715ca932d1e2c3d0f2c6b28a89bf7ce29369
janehuynh3012/Bioinformatics
/PatternCount.py
363
3.953125
4
# Input: A Pattern and a Text # Output: The number of occurences of the Pattern def PatternCount(Text, Pattern): count = 0 for i in range(len(Text)-len(Pattern)+1): if Text[i:i+len(Pattern)] == Pattern: count = count+1 return count Pattern = "AAA" Text = "GACCATCAAAACTGATAAACTACTTAAAA...
d57b41f3012b1d822c646ff4502e7d8937b6b4f4
semi-cheon/programmers
/level1/201118_programmers_약수의 합.py
860
3.8125
4
# python 코딩 테스트 연습 # 작성자: 천세미 # 작성일: 2020.11.18.W # 문제: 약수의 합 ### 문제 설명 ### 정수 n을 입력받아 n의 약수를 모두 더한 값을 리턴하는 함수, solution을 완성해주세요. ### 제한 사항 ### n은 0 이상 3000이하인 정수입니다. ### 입출력 예 ### n return ### 12 28 ### 5 6 ### 입출력 예 설명 ### 입출력 예 #1 ### 12의 약수는 1, 2, 3, 4, 6, 12입니다. 이를 모두 더하면 28입니다. ### 입출력 예 #2 ### 5의 약수는 1, 5입니...
e9dd2af212b0d6dfa8db5ce0ed5cbbedb785762c
lucasbezerra06/Exercicios
/exe034.py
261
3.703125
4
salario = float(input('Digite o salário do funcionário: R$')) if salario > 1250.00: aumento = 10 else: aumento = 15 novo = salario + salario * (aumento / 100) print('O seu aumento foi de {:.0f}%, e seu novo salario é R${:.2f}'.format(aumento, novo))
273e76e909d1c3d17d6e51a4d496ceaf2309e8a5
brthngnsh/Algorithms-in-python
/String/int_to_string.py
408
3.90625
4
def int_to_string(x): is_negative = False if x < 0 : x,is_negative = -x , True s=[] while True: s.append(chr(ord('0') + x%10)) x//=10 if x == 0 : break return ('-' if is_negative else '')+''.join(reversed(s)) def main() : number = i...
edae47f89bcd63dc2cd5e25af9304c74516a600e
abhikbanerjee/Python_DataStructures_Interviews
/interview_questions/Recursion_DP/GenerateParanthesis.py
709
3.59375
4
from typing import List # Generate all possible paranthesis combination given the number of paranthesis - LC 22 def generateParenthesis(n: int) -> List[str]: def gen_paran_helper(current_str: str, final_list: List[str], open_count, close_count, max_str): if len(current_str) == max_str * 2: final_list.append(cur...
b0b7726e38c649621b149fdfa658a1b8144ed11b
Tejas-Naik/-100DaysOfCode
/Day17/creatingclasses.py
795
3.84375
4
class User: def __init__(self, name, id): # Initializing an attribute name and id self.name = name self.id = id self.followers = 0 self.following = 0 def celebrity_mode(self): # when you are calling a method you can change the attribute of tha class or add another o...
9688bb2bcaf6d8a544fcb35e961c867f303eb7a1
chenjyr/Miscellaneous
/helper.py
1,207
3.515625
4
import os import re import urllib2 def retrieveSourceFromURL(url): """ Returns the GET data from url """ usock = urllib2.urlopen(url) data = usock.read() usock.close() return data def parse(data, pattern): """ Returns the list with each n-tuple corresponding to a row in the table we are i...
a8305297f877f66e06179078be5b4422f48670d7
monaabd27/9.66_project
/intention.py
17,611
3.859375
4
import pyAgrum as gum import pyAgrum.lib.notebook as gnb from dijkstra import DijkstraSPF, Graph import numpy as np #the way the norms impact is thru the utility #for a given desire and norm we have our utility, # we can find the utility and best descision #we dont know the desires and norms from the influence diagra...
3adb7a9cf1f00081c90d0dfdb4ed3868bc511e8a
yuxiyve/paper-scissors-stone
/paper scisser stone.py
486
4.09375
4
import random player = int( input("please input stone(1)/ scissors(2)/ paper(3):")) computer = random.randint(1, 3) print("you are:", player, "-", "computer is:", computer) if (player == 1 and computer == 2) or \ (player == 2 and computer == 3) or \ (player == 3 and computer == 1): print(" ...
f91c1c2f92174ea1e003653b2c5010341159b61c
sunny1986/Misc
/entertainment_center.py
2,672
3.703125
4
######################################################################################## # Description: # This program launches a webpage to show details about a few of my fav movies # # Steps: # 1. Create instances of movies # 2. Pass the movie data to a function to launch a webpage # 3. Useful pre-defined class va...
bfde7c05a55074c6a2fafd4fc44a7c166230ca06
slavaider/python
/repeat_from_book/11_fruits.py
330
3.734375
4
if __name__ == '__main__': fruits = {'apples': 10} if 'bananas' in fruits: fruits['bananas'] += 1 else: fruits['bananas'] = 0 # if 'pears' not in fruits: alternate # fruits['pears'] = 0 # fruits['pears'] += 1 fruits.setdefault('pears', 0) fruits['pears'] += 1 prin...
8f85492e0c634645c72d5db999f4492946712fc8
xinBrueck/Interview-Coding-Practice
/possible_ways_for_string_encoding.py
3,305
3.625
4
##Given the mapping a = 1, b = 2, ... z = 26, and an encoded message as a string, ##count the number of ways it can be decoded. ##we can assume the encoded message is decodable ##for example 111 can be decoded as aaa, ak, ka ##I have implemented this using a tree structure ##starting at index 0 for the message ##if I...
88dabe5f5c2c07cf0057ae76c1564f01e84127a3
ChrysostomouNikolas/Bio
/GA.py
5,041
4.03125
4
#Nikolas Chrysostomou #Computer Science Year3 #Biocomputaion import random # since we ll be using random in our code we need to call in the random library _N=10 #Gene length _P=10 #Population Size _MR=1 #mutation rate class Individual: def __init__(self, genes = None):# we create the cals...
2c617db24122bb70053a51060811ce4e7cdc05a7
JoseVictorAmorim/CursoEmVideoPython
/cursoemvideo/ex053.py
424
3.734375
4
frase = str(input('Qual a frase a ser analisada? ')).strip().lower() fsem = frase.split() j = ''.join(fsem) nletras = len(j) inverso = '' for c in range(nletras-1, -1, -1): inverso += j[c] if inverso == j: print('A frase digitada, ao contrário, fica: {}, portanto se trata de um palindromo!'.format(frase)) else:...
16a8cf989abcb82da31df0d0869645c77fb376c7
rams1996/Trees
/sum-root-to-leaf-numbers/sum-root-to-leaf-numbers.py
1,025
3.640625
4
# Definition for a binary tree node. # class TreeNode: #     def __init__(self, x): #         self.val = x #         self.left = None #         self.right = None from collections import deque class Solution:    def sumNumbers(self, root: TreeNode) -> int:        if not root:            return 0        result=0    ...
c28b787346f9f9c98537bfa16a2d4597704ecb6f
papasanimohansrinivas/c-language
/function4.py
266
3.8125
4
from function2 import stringreverse from function3 import fun from function3 import swap string=raw_input('enter a string ') n=input('enter a number') x=input('enter a number') y=input('enter a number') fun(n) print stringreverse(string) print swap(x,y)
fb3da8d010a558b5ad280829ff6934f5c27cc901
alvaro-barrera/python-level-2
/mix_sort.py
1,222
3.765625
4
import random def mixt_sort(list): if len(list) > 1: middle = len(list) // 2 left = list[:middle] right = list[middle:] print(left, '*' * 5, right) # llamada recursiva en cada mitad mixt_sort(left) mixt_sort(right) # Iteradores para recorrer las do...
6c87db060b5ede6d38f03d586a371a4997673a1b
tatebury/parkingGarage
/parkingGarage.py
1,941
3.90625
4
class ParkingGarage: def __init__(self, tickets=10, parkingSpaces=10, currentTicket={}): self.tickets = tickets self.parkingSpaces = parkingSpaces self.currentTicket = currentTicket def takeInput(self): action = input("Would you like to: Park, Pay or Leave? ") ...
bd7f62fbfc22d2c3f9af7ef003f328ff75c9ea31
slavka414/Python
/homework3/3/main.py
529
4.03125
4
# Реализовать функцию my_func(), которая принимает три позиционных аргумента и возвращает сумму наибольших двух аргументов. s1 = int(input('Введи первое число: ')) s2 = int(input('Введи второе число: ')) s3 = int(input('Введи третье число: ')) def max_sum(sl1, sl2, sl3): l = [sl1, sl2, sl3] l.remove(min...
5f07495d9987e6c1c168d6c59d774d888c762509
zeeshan13026/PythonRefresher
/27_class_composition/code2.py
434
4.34375
4
''' Composition >>>>>>> has a relationship''' class BookShelf: def __init__(self, *books): self.books = books def __str__(self): return f"Bookshelf with {len(self.books)} books" class Book(BookShelf): def __init__(self,name,): self.name = name def __str__(self): retur...
4568eeb53973135e44b5d7d66681a1b8cc30eae4
rajlath/rkl_codes
/codechef/TWOVSTEN.py
150
3.65625
4
''' 3 10 25 1 ''' for _ in range(int(input())): n = int(input()) if n % 10 == 0:print("0") elif n % 5 == 0:print("1") else:print(-1)
6a974ca742e83ea70b3211a91f1b9fc11e80a429
daniel-reich/turbo-robot
/bdsWZ29zJfJ2Roymv_24.py
730
4.03125
4
""" Write a function that swaps the first **pair** (1st and 2nd characters) with the second **pair** (3rd and 4th characters) for every quadruplet substring. ### Examples swap_two("ABCDEFGH") ➞ "CDABGHEF" swap_two("AABBCCDDEEFF") ➞ "BBAADDCCFFEE" swap_two("munchkins") ➞ "ncmuinhks" s...
4e9e6a7c6e748ea5a1bcd7cf5dc8e297fea915c4
shortthirdman/code-eval-challenges
/hard/climbing_stairs.py3
199
3.984375
4
import fileinput def stairs(a): b = c = 1 for _ in range(a-1): b, c = c, b + c return c for line in fileinput.input(): if not line == '\n': print(stairs(int(line)))
ccbf7c2de2cd72b9d0dc6e04d7b3203f47e8c3f8
artemyk/redundancy
/convex_maximization.py
5,073
3.640625
4
""" Code for maximizing a convex function over a polytope, as defined by a set of linear equalities and inequalities. This uses the fact that the maximum of a convex function over a polytope will be achieved at one of the extreme points of the polytope. Thus, the maximization is done by taking a system of linear ineq...
866e74750ea247f7bbe24203f017bd1d800b882d
jj-a/basicPython
/section03/02-reference.py
1,006
3.90625
4
# section03 / 02-reference.py # 값에 의한 호출 (Call by Value) : 정수, 실수, 논리값, 문자열 # 객체 참조에 의한 호출 (Call by Object Reference): 리스트, 튜플, 딕셔너리 # Call by Object Reference = Call by Sharing # Call by Object Reference는 자바의 Call by Reference와 다름 *** a = 100 b = 200 print(a, b) # 객체의 참조 (list, dictionary, tuple) foo = [1, 2, 3] bar...
c70842b3c7dc6dfb6ea6d210a37c4c7109b642c1
chenxiang97/study_base
/python_study/study_mooc/study_4.3.1.py
799
3.875
4
#random库:使用生成随机数的python标准库 """ 基本随机数函数: seed(N):初始化给定的随机数种子,默认为当前系统时间 random():生成一个[0.0,1.0]之间的随机小数 扩展随机数函数: randint(a,b):生成一个[a,b]之间的整数 gettrandbits(k):生成一个 k 比特长的随机整数 uniform(a,b):生成一个[a,b]之间的随机小数 randrange(m,n[,k]):生成一个[m,n)之间以 k 为步长的随机整数 choice(seq):从序列中随机选择一个元素 shuffle(seq):将序列seq中的元素随机排列,返回打乱后的序列 """ #CalPiV1.py...
bbed21345b19ff30bc3d92bec8fd4d38c5f68be8
Aasthaengg/IBMdataset
/Python_codes/p03986/s326524480.py
204
3.515625
4
X = input() stack = [] for c in X: if not stack: stack.append(c) continue if stack[-1] == "S" and c == "T": stack.pop() else: stack.append(c) print(len(stack))
758c37616695ad2defb5fce8cadb2a41c02fc66a
elrui/olimpiadas
/olimp.py
6,016
4.21875
4
''' Comentarios: ** La tarea requiere que las cosas se guarden en un archivo, el programa al arrancar deberia leer el archivo y actualizar su contenido ** También indica que se deben usar funciones. Supongo que se refiere a las funciones que definimos ayer Para la pregunta 1, estoy asumiendo que se puede: - Agregar ...
f49a79b968e22bdbb833b2d996ef78da4c1a52d1
jayshreeuw/Python
/DataTypes/Tuples/SpecialOperators.py
448
3.765625
4
#!/usr/bin/python # 0 1 2 3 4 #Left to Right Indexing # -5 -4 -3 -2 -1 #Right to Left Indexing tup1 = ('python', 'linux', 1997, 2000, 70.25) tup2 = (1,2,3,4,5,6,7) print(tup1, tuple(enumerate(tup1))) print(tup2, tuple(enumerate(tup2))) print(tup1, type(t...
f02c3f4c39690f1027918f14318b60c1eea896b3
MickeysClubhouse/environment
/Playground.py
1,418
3.5
4
import numpy from constant import * class Playground: """ class playground is a dimension_x* dimension_y grid mark the objects' position be shown by show() in trustGame.py """ dimension_x = 0 dimension_y = 0 grid = numpy.zeros((1, 1), dtype=int) apples = [] def __init__(self, ...
2409655be586c521398df433a8c4d93e0e616fcf
SudoKIngpin/PythonProgramsRemote
/factorial.py
316
4.21875
4
##'''Program for calclating trailing zeroes in python''' fact=1 num=int(input("Enter no :")) for i in range(1,num+1): fact=fact*i print("Factorial of given number is :",fact) fact1=str(fact) print(fact1) ct=0 for i in fact1: if i=='0': ct+=1 print("Given factorial contains",ct,'trailing zeroes ')
320839d8b4c747477e2b79658e7e8dfc7811b322
OlgaP-1/lesson_1
/task_6.py
540
3.78125
4
day_a = int(input('Введите колличество пройденных километров за один день: ')) day_b = int(input('Введите желаемое расстояние в километрах: ')) km_day = int(day_a * 0.1 + day_a) day_x = 1 while km_day < day_b: if km_day < day_b: km_day = km_day * 0.1 + km_day day_x += 1 else: co...
03489dd84bb2cecc2564df6511c53075ef9b4433
blaze0004/Geeks
/datastructures/Graph/DFS_BFS/count-number-nodes-given-level-using-bfs.py
834
3.703125
4
from collections import defaultdict class Graph: def __init__(self, vertices): self.V = vertices self.graph = defaultdict(list) def addEdge(self, src, dest): self.graph[src].append(dest) self.graph[dest].append(src) def countNodeAtGivenLevel(self, root, level): visited = [False]*self.V levels = ...
2c7716fade4cb55bdbabd2c20a6736868aeb1c18
kvraiden/Basics-For-Python
/VSCODE Programs/Basics/construct2.py
215
3.765625
4
#Deleting an object class Point(object): def __init__(self,x=0,y=0): self.x = x self.y = y p1 = Point(1,2) print((p1.x,p1.y)) del p1.y print(p1.x) print(p1.y)#It must show an error
6c1e1a00884b1c2e1b1574784e8e91f41e4e5e87
Ritabina20/LGMVIP--DATA-SCIENCE
/Iris_classificatio.py
2,359
3.890625
4
import numpy as np import matplotlib.pyplot as plt import pandas as pd import seaborn as sns import scikitplot as skplt df=pd.read_csv("http://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data", names = ["sepal length", "sepal width", "petal length", "petal width", "class"]) #it will show 1st 5 values ...
7001c5c6bf96cd0d4f1198e0f1b4776fe1d4575e
fralychen/Python_study
/mintues.py
238
3.796875
4
#!/usr/bin/python mintues = int(input("Enter mintues: ")) def Hours(b): n=b / 60 m=b % 60 print("%d H,%d M" %(n,m)) if mintues < 0: try: raise ValueError except ValueError: print("this is negative number.") else: Hours(mintues)
fbcc282f072c403bedb9dfbd7544f72ac0000a86
bernardli/leetcode
/1-50/37_Sudoku_Solver.py
2,816
3.609375
4
from typing import List class Solution: def solveSudoku(self, board: List[List[str]]) -> None: """ Do not return anything, modify board in-place instead. """ self.board = board self.sample = set([i for i in range(1, 10)]) self.block = [[set() for i in range(3)] for ...
31e5f2ab1ac90068b49baea1f627323faad89ddd
ruslan-rv-ua/python-essential
/source/types_and_data_structures/numbers/examples/eq_le.py
367
3.53125
4
class V: def __init__(self, value): self.value = value def __eq__(self, other): return self.value == other.value def __lt__(self, other): return self.value < other.value def __repr__(self): return f'{self.__class__.__name__}({self.value})' v1 = V(1) v2 = V(1) v3...
c424bbfab922ec5bc244ba6246d72936de7061fc
samuelcorralesc/programacion
/6_3.py
235
3.859375
4
cromos = [] num = int(input()) while num!=0: cromos.append(num) num = int(input()) if num > 682: print('Ingrese un número de cromo entre 1 y 682') del cromos[-1] continue print(len(set(cromos)))
b235174d56acfe8c03597f7d6aa42055afca35e8
DmitryVGusev/Python_lessons_basic
/lesson04/home_work/hw04_easy.py
2,336
4.25
4
# Все задачи текущего блока решите с помощью генераторов списков! """ Не уверен, что корректно lambda-функцию заводить в переменную. По крайней мере, PEP8 просит так не делать. Но хотелось показать лаконичность решения. """ # Задание-1: # Дан список, заполненный произвольными целыми числами. # Получить новый список,...
bd4901b46921ab0bd710d3aa744b6c5c4eb31765
sivatmam/CCPS109
/main.py
2,796
3.984375
4
#!/usr/bin/python # # Course: CCPS 109 # Lab: 3 File IO and Modules # Due Date: Mar 16th @ 23:00 hrs # # Student: Sivatma Maharaj # Student ID: 501043693 import weatherstat month = {"1":"JAN","2":"FEB","3":"MAR","4":"APR","5":"MAY","6":"JUN"} weather = {} weather_avg = {} weather_maxmin = {...
7ec1226e5e763ef3c1f7f475b30f1866dec627d3
EricksonSiqueira/curso-em-video-python-3
/Mundo 1 fundamentos basicos/Aula 7 (operadores aritmeticos)/Desafio 005.py
451
3.859375
4
#Faça um programa que leia um número inteiro e mostre o seu sucessor e o seu antecessor. co = {'l': '\033[m', 'vm': '\033[31m', 'az': '\033[34m', 'vd': '\033[32m', 'ro': '\033[35m', 'am': '\033[33m'} n1 = int(input(f"{co['az']}Digite um número:{co['l']} ")) ant = n1-1 suc = n1+1 print(f"{co[...
79e360c45585b71c8a2ff0edb6d15a1c238bf8d8
garyliton/algo-review
/is_crypt_solution.py
471
3.75
4
def isCryptSolution(crypt, solution): hashmap = {} for row in solution: hashmap[row[0]] = int(row[1]) res = [0, 0, 0] for i in range(len(crypt)): exp = 0 word = crypt[i] for j in range(len(word) - 1, -1, -1): res[i] += hashmap[word[j]] * (10 ** exp) ...
8ae04f5259dc8a9d6f493d1206e26c7a4fdf9835
honchen22/LeetCode
/算法/Python/319. Bulb Switcher.py
1,483
3.5625
4
class Solution: def bulbSwitch(self, n): """ :type n: int :rtype: int """ ''' 一个开关i被拨动的次数就是i的约数的个数,比如第8个开关,它被拨动了4次,分别在轮数=1,2,4,8时,而1,2,4,8就是8的约数。 所以题目就变成了求1-n中每个数i的约数个数,如果约数个数是奇数,则开关是开的。 那么下一步就是求i(i≤n)的约数个数,约数是成对存在的,即2是8的约数,那么 8÷2=4也是8的约数,其中有一种特殊情况,就是i为完全平方数,比如9跟它的约数3,因此, 如果i是完全平方数,那么i的...
dcb38a25e127f67e35735d74698cd6e5452aa929
AnshumanSinghh/DSA
/Sorting/quick_sort.py
3,870
4.21875
4
def partition(arr, low, high): ''' This function returns partition index of an array. ''' pivot = arr[high] # let the last elemnt be pivot i = low - 1 # initializing index of smaller element for j in range(low, high): # we will loop from low to high - 1 if arr[j] < pivot: # if l...
9e3fffb901bf092fa74e97fb2a85d09af06f5b46
nrohankar29/Python
/Binary_Search.py
518
3.65625
4
def bin_search(arr,left,right,ele): arr.sort() if right >= left: mid = left + ((right - left) // 2) if arr[mid] == ele: return (mid+1) elif arr[mid] > ele: return bin_search(arr,left,mid-1,ele) else: return bin_search(arr,mid+1,rig...
5106424397c9324f2f729c6887ca28516ad8b6a6
Kawser-nerd/CLCDSA
/Source Codes/AtCoder/abc082/B/4839434.py
161
3.8125
4
s = input() t = input() s = sorted(s) t = sorted(t, reverse=True) sl = "".join(s) tl = "".join(t) if sl < tl: print("Yes") else: print("No")
b19e7c0db991f5e09d898397bfdfcc25d2b4f412
KaloMendez/Tareassemana6
/ejercicio3.py
1,472
3.65625
4
def free(row, col): """ Determina si la casilla rowxcol está libre de ataques. @param row: Fila @param col: Columna @return: True si la casilla está libre de ataques por otras reinas. """ for i in range(8): if tablero[row][i] == 'R' or tablero[i][col] == 'R': return False ...
e36bba790a3e4caaaca2b9c003df8ae26c8728eb
RajaSekar1311/Data-Science-and-Visualization-KITS
/Data Visualization/VisualizeStudentMarks.py
948
3.859375
4
import pandas import matplotlib.pyplot as plt #create the dataframe from CSV file using pandas MyDataFrame=pandas.read_csv('ZPHighSchoolGuntur.csv') print(MyDataFrame.shape) print(MyDataFrame.describe()) ''' #Representation of data as a histogram MyDataFrame.hist() #For displaying the plot plt.show() ''' #R...
8b5f5e38cdade0e515d52c83ae4fabbdf15bcc9c
graphtobinary/Basic-mathematics-python-program-example
/convert_celsius_to_fahrenheit.py
298
4.53125
5
# Python Program to convert temperature in celsius to fahrenheit # change this value for a different result celsius = float(input('Enter celsius: ')) # calculate fahrenheit fahrenheit = (celsius * 1.8) + 32 print('{0} degree Celsius is equal to {1} degree Fahrenheit'.format(celsius,fahrenheit))
ca5b588e36565f0379c52ef7c743189b45c4bb4a
JoseK21/MetodosNumericos
/sne_ud_3.py
2,183
3.5
4
''' Metodo 0zban , Homeier Computers and Structures Performance of cubic convergent methods for implementing nonlinear constitutive models Pag.3 M3 - 0zban (2004) [23], Homeier (2005) [24] Ecuación (9) Ejemplo : sne_ud_3("x**3 + 6*x**2 - 18",3,0.0001,1) ''' import matplotlib.pyplot as plt from sympy import Symbol, sy...
3ab8c061a9f46abf47b4e0d718bf764f9cad4247
realvesd/exercicios-python
/codigoproduto.py
252
4.0625
4
prod = str(input("Qual o código do produto? ")) if prod == '1': print("Pizza!") elif prod == '2': print("Hamburger!") elif prod == '3': print("Refrigerante!") elif prod == '4': print("Batata frita!") else: print("Produto não encontrado")
2be73c31d9eebe67db6672a5336d97714516be18
sasakishun/atcoder
/ABC/ABC070/C.py
410
3.671875
4
def gcd(a, b): while b > 0: tmp = a a = b b = tmp % b return a def lcm(a, b): tmp = gcd(a, b) return (a//tmp) * b n = int(input()) t = [0 for i in range(n)] for i in range(n): t[i] = int(input()) t = sorted(t) _sum = t[0] for i in range(1, n): # print("sum:{} t:{} lcm...
1d35079bbdb3378e1be3e343ae45ea09cda8339b
yz830620/oop_prctice
/other/typing_test.py
455
3.921875
4
from typing import List class Contact: """class of contact""" all_contacts: List['Contact'] = [] def __init__(self, name: 'str', phone:'str'): """init the class""" self.name = name self.phone = int(phone) Contact.all_contacts.append(self) def __repr__(self) -> str: ...
93cd65b6df3ce8c6423b07a9be0cde12b2af30ce
zjs1224522500/Python-learn
/oop/test_rectangle.py
1,155
3.671875
4
from .rectangle import Rectangle from unittest import TestCase from .two_d_point import TwoDPoint class TestRectangle(TestCase): def test_center(self): self.example = Rectangle(0, 1, 3, 1, 3, 0, 0, 0) self.assertTrue(self.example.center() == TwoDPoint(1.5, 0.5)) def test_area(self): ...
440c675b88ebd80990dbb3d20a9d9558203c708b
chapman-cpsc-230/hw2-sweet116
/cooling.py
218
3.859375
4
T = float(input('enter the temperature of tea')) T_a= float(input('enter the ambient air temperature')) k = 0.055 rateofcooling = -k * (T - T_a) print('The rate of cooling is', rateofcooling, 'degrees per minute')
5f6a0a347d709fe1bfb00cc096225f403b108d89
himala76/Codding_Class_Lesson_2
/Random_randint_module.py
189
3.625
4
#testing random module in python # this codes show how to use the random module in python import random random_number = random.randint(-10,10) print "The number is: " + str(random_number)
3262b924ba9bc70a9fe88735e55e54485c16a0ee
BoatInTheRiver/codes_algorithm
/剑指Offer/剑指 Offer 64. 求1+2+…+n.py
248
3.546875
4
#coding:utf-8 ''' 求 1+2+...+n ,要求不能使用乘除法、for、while、if、else、switch、case等关键字及条件判断语句(A?B:C)。 ''' class Solution: def sumNums(self, n): return n != 0 and n + self.sumNums(n - 1)
2d1d912843c65dfabe278497ecc3011b961bd530
Tomcruseal/sage
/caesar.py
555
3.796875
4
letters=['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'] def get_index(char): for i in xrange(len(letters)): if char==letters[i]: return i def caesar(message,x): cipher_message=[] for char in message: new_index=(get_index(char)+x)%26 new_char=letters[...
c5eaabd73e6c5c7b0369623b85c94dcf0f4ec991
atronk/python
/low-level/loops/while_loop.py
303
3.5
4
x = 0 while x < 10: x += 1 print("x = ", x) list1 = [10, 100, 1000] list2 = [4, 5, 6] for i in list1: for j in list2: print(i * j) for num in range(100): if 55 <= num <= 66: print(num) for num in range(100): if num > 50: break else: print(num)
0d3ba5ec0cea7f3be2181492dd8bd1ecfadd4e09
leochen4891/interviewquestions
/python/Easy/ReverseInteger.py
538
3.859375
4
__author__ = 'Lei Chen' ''' Reverse digits of an integer. Example1: x = 123, return 321 Example2: x = -123, return -321 ''' class Solution: # @param {integer} x # @return {integer} def reverse(self, x): rev = int(str(x)[::-1].replace('-','')) if x < 0: rev = 0-rev if rev > 214748365...
2b60dfa53751ebb88c3468515f429606a811b6f0
alexcatmu/CFGS_DAM
/PRIMERO/python/ejercicio80 funcionparametro.py
432
3.75
4
''' 2.4) Programeu un procediment “mes_mes” que rebi un valor sencer com a paràmetre per referència, i n’incrementi en una unitat el seu valor. ''' #programa suma #funciones def mes_mes(lista): for i in range(len(lista)): lista[i] = lista[i] + 1 #programa array_numeros = [1,4,654,4,6,234] print...
3b65cc70e4b68fb30959a5e341c20ed02c86ce99
mwolkowi17/test_repo
/pytania.py
412
3.703125
4
dane=input('podaj prosze imię, nazwisko') telefon=input('podaj numer telefonu') print(dane.isalpha()) print(telefon.isdigit()) dane=dane.title() telefon=telefon.replace('-','').replace(' ','') print(telefon) print("Imię kobiece:", dane.endswith("a")) personal=dane+' '+telefon print(personal) print(len(personal)) letter...
d097e79e680b2d230707ac465e0710461f90d07d
debjit31/Data-Science-With-Python-DataCamp-
/tweets.py
716
3.640625
4
import pandas as pd tweets_df = pd.read_csv('tweets.csv') print(tweets_df.columns) print(tweets_df) print('\n') def count_entries(df, *args): count_cols = {} for col_name in args: if col_name not in df.columns: raise ValueError('Column '+ col_name + 'not present in the dataframe '+df) ...
82a18b803d43abfffefbb3f2fd28035214dfe03e
changethisusername/uzh
/Informatik1/MidtermsInfk/midterms hs19/to_binary.py
466
4.125
4
def to_binary(number): binarynumber="" if (number!=0): while (number>=1): if (number %2==0): binarynumber=binarynumber+"0" number=number/2 else: binarynumber=binarynumber+"1" number=(number-1)/2 else: bi...
c3b46fcba1c14b541aaf8be61a05c5f74df35aee
xacaxulu/niece-python-lessons
/src/Megan_textanalytics.py
1,898
3.8125
4
#This is text analytics.py # a complete program to split words def wordcount(userwords): wordlist=userwords.split() wordcount = dict() for word in wordlist: if word in wordcount: wordcount[word] += 1 else: wordcount[word] = 1 ''' for key,value in wordcount.i...
c3114f6ee4a726ed1f39265b3bf8b7349fa3791c
pyVoice/pyVoice
/src/core/modules/tts.py
2,190
3.515625
4
""" **Text to Speech (TTS) engine** Converts text into audio. Works in Windows (using the SAPI engine) and other platforms, using `gTTS`. """ import platform from tempfile import NamedTemporaryFile as named_temp_file from playsound import playsound from src import settings from src.core.modules import log engine =...
976d7c839aefc7c5fe85c333b0514f1803656a4e
Graey/pythoncharmers
/guessinggame.py
1,159
4.21875
4
#Question : Write a while loop that compares the player's guess to our number. If the player guesses correctly, break from the loop. Otherwise, tell the player if they're warmer or colder, and continue asking for guesses. #Answer : while True: # we can copy the code from above to take an input guess = int(in...
6d731009056e73f1801c4c07f302e6fc7bf3b625
AdamZhouSE/pythonHomework
/Code/CodeRecords/2552/60602/296317.py
921
3.578125
4
def makeIntList(list): count = 0; ans=[]; while (count < len(list)): try: ans.append(int(list[count])); except Exception as e: count+=1; continue; count += 1; return ans; stringSize=makeIntList(input().split(" ")); n=stringSize[0]; m=stringSize...
bc0cbca503d6fc053c9361c3b5d951e9c4f503bb
mivargas/Master-python
/1-script/14listas/predefinidas.py
688
4.3125
4
cantantes = ["drake", "talia", "big ariana", "Sia"] numeros = [1,2,5,8,3,4] #ordenar lista print(numeros) numeros.sort() print(numeros) #añadir elementos en una posicion especifica cantantes.insert(3, "reik") print(cantantes) #eliminar elementos cantantes.pop(1) #por indice cantantes.remove("reik") #por valor print(...
003a0a4cd42e2e747de939f5f6b60f0dd027cb0e
pinkston4/Solutions_to-Matasano_code_challenges
/crypto_pals_python/Set_1/challenge_five.py
1,718
3.578125
4
#! /usr/bin/env python3 """ Challenge 5 of the CryptoPals challenges objective: Take the opening stanza of 'ICE ICE BABY' by Vanilla Ice, dubbed an important work of English Literature by the creators of the challenge...trolltrolltroll... and encrypt it using a repeating key xor """ def repeating_key_xor(message, k...
856b4d59e0572898fa605e37cf70ad38d487f5a9
DanielYu0864/100-Days-of-Python
/Day 19 Instances, State and Higher Order Functions/Etch-A-Sketch App/main.py
713
3.703125
4
from turtle import Turtle, Screen timmy = Turtle() screen = Screen() def move_forwards(): timmy.forward(10) def move_backwards(): timmy.backward(10) def turn_counter_clockwise(): timmy.left(5) def turn_clockwise(): timmy.right(5) def clear_drawing(): timmy.reset() # Reset all timmy on the Screen...
c3a56eb2507e57201b9cda02204da75556f80ec4
itsolutionscorp/AutoStyle-Clustering
/all_data/exercism_data/python/rna-transcription/1ee7e3fa4be04724977a6b728a4adeab.py
673
4.15625
4
""" Exercise 4: RNA transcription """ def to_rna(dna): """ Takes the string 'dna' and calls the generator 'transcribe' to convert each nucleotide of the chain individually. Joins into one string. """ result = '' for letter in transcribe(dna): result = ''.join([result, letter]) r...
a9a0c38703eb99dcb18fabbe8c5b0b3e2142e857
rodrigor10/comp110-21f-workspace
/exercises/ex03/tar_heels.py
415
3.75
4
"""An exercise in remainders and boolean logic.""" __author__ = "730400384" # Begin your solution here... selected_number = int(input("Enter an int: ")) if (selected_number % 2 == 0) and (selected_number % 7 == 0): print("TAR HEELS") else: if selected_number % 2 == 0: print("TAR") else: i...
0f188050ea2c0b00814d30f2173a97c9fa87513f
Torugo/temperature-station
/phant.py
1,665
3.640625
4
#!/usr/bin/python import httplib, urllib # http and url libs used for HTTP POSTs class Phant(object): def __init__(self, pubkey, pvtkey): self.server = "data.sparkfun.com" # base URL of your feed self.publicKey = pubkey # "zD9obXl4K3UM1E0MY5q2" # public key, everyone can see this self.pri...
6ed7b2fad09c1f5c75079fb7264f94a171fc397f
JeffreybVilla/100DaysOfPython
/Beginner Day 5 Python Loops/CarlGaussAddUpTo100.py
412
3.875
4
""" Carl Gauss exercise 1 + 2 + 3 + 5 + ... 96 + 97 + 98 + 99 + 100 flip numbers around 100 + 99 + 98 + 97 + 96 ... + 5 + 4 + 3 + 2 + 1 100 + 1 = 101 99 + 2 = 101 98 + 3 = 101 97 + 4 = 101 96 + 5 = 101 There is 50 pairs of 101 50*101 = 5050 """ #Add up all numbers from 1 to 100 #Add will add every number in this ...
54ad1766b4310ea8f1760071d9bcb4d648ec36b7
ayushiagarwal99/leetcode-lintcode
/leetcode/sort/1658.minimum_swaps_to_arrange_a_binary_grid/1658.MinimumSwapstoArrangeaBinaryGrid_zheyuuu.py
2,862
4.09375
4
# Source : https://leetcode.com/problems/minimum-swaps-to-arrange-a-binary-grid/ # Author : zheyuuu # Date : 2020-08-02 ##################################################################################################### # # Given an n x n binary grid, in one step you can choose two adjacent rows of the grid and s...
f0c261192afa5a7e59bdfdbc63872a22ca6dd773
guhaigg/python
/month02/day14/thread_lock.py
358
4.125
4
""" 线程锁 """ from threading import Thread,Lock lock = Lock() # 锁对象 a = b = 1 def value(): while True: lock.acquire() if a != b: print("a = %d,b = %d" % (a, b)) lock.release() t = Thread(target=value) t.start() while True: lock.acquire() # 上锁 a += 1 b += 1 lock....
41773b0d827e75e38b905c4d73353472b54ce5e6
BrettMcGregor/udemy-colt-steele
/double_return.py
510
3.796875
4
''' @double_return def add(x, y): return x + y add(1, 2) # [3, 3] @double_return def greet(name): return "Hi, I'm " + name greet("Colt") # ["Hi, I'm Colt", "Hi, I'm Colt"] ''' def double_return(fn): def wrapper(*args, **kwargs): return [fn(*args, **kwargs), fn(*args, **kwargs)] return wrapp...
dcf2f99a380cf0b2030c47a549775290d54fb4b2
cloudmesh/cloudmesh-analytics
/tests/utilities/type_scraper.py
1,355
3.96875
4
import re class TypeScraper: """Scrape types from a string. Using the regular expression to match the keywords that imply the types. A type table for matching the types from the string is required Examples: 'boolean, optional, default True' = bool 'int or None, o...
35a46d83d715c5b480dc5556bbdd33522a78a60e
Gellett/Gellettleather
/Gellettleather_database.py
644
3.53125
4
import sqlite3 conn = sqlite3.connect('gellettleather.db') c = conn.cursor() def create_table(): c.execute('CREATE TABLE IF NOT EXISTS varer( varer_image_path text, varer_text text, varer_cost text, ID text)') def data_entry(_path, _text, _cost, _ID): c.execute('INSERT INTO varer (varer_image_path, varer_tex...
3ce5f6c0e90a455009901b93902d9d75414af33a
DastanB/BF-Django
/week1/codeingBat/string-2/02.py
140
3.625
4
def count_hi(str): s = 0 for i in range (len(str)-1): if str[i] == 'h' and str[i+1] == 'i': s += 1 return s
e341e2cc0ed5934a74f94d129940b5b1da220bed
Beomi/snue_it
/duplicated_apply.py
1,510
3.546875
4
import csv import collections print('서울교육대학교 학생 IT지원국에서 제작한\n임용고시 강의실 대여 중복처리 프로그램입니다.') print('code by Junbum Lee') print('문제가 있는 경우 jblee+help@student.snue.ac.kr로 문의주시기 바랍니다.') file_name = input("사용하실 파일 이름을 입력해 주세요(~~.csv): ") reader = csv.DictReader(open(file_name,encoding='utf8')) result = {} for row in reader...
7254a92d583da742f8f05bedc4cd12b680b5e64b
0range-z/Object-Oriented-Design-Autotest
/HW6自动测评/HW6_generator.py
965
3.625
4
from random import randint, random, choice TIME_MAX = 5 def generate(length, num_elevator): id = [] ans = [] # ans: time id from to for i in range(length): # generate time ans.append([TIME_MAX*random()]) # generate id id.append(i+1) ans.sort() ...
e208c42c144220b9ff5330963799418a70552182
ramkumar1819/python
/equality or sum=5 or diff=5 return true else false.py
312
3.9375
4
# Python program that will return true if the two given integer values are equal or their sum or difference is 5 a=int(input("enter the 1st number:")) b=int(input("enter the 2nd number:")) if a==b: print("true") elif a+b==5: print("true") elif (abs(a-b)==5): print("true") else: print("false")
c2d522b2bd858a5741768c3d8867281f62b4d333
albertoriva/arutils
/enumerate.py
1,980
3.75
4
#!/usr/bin/env python import sys class Enumerator(object): v = 1 step = 1 inputs = [] argsmode = False def parseArgs(self, args): prev = "" if "-h" in args or "--help" in args: self.usage() return False for a in args: if prev == "-i": ...
078e862877f043921913549e02d34e991dab40a7
basakrajarshi/LC_March_2020
/Top Int Ques/029_divide_two_integers.py
1,919
3.75
4
class Solution(object): def divide(self, dividend, divisor): """ :type dividend: int :type divisor: int :rtype: int """ if dividend == (-2)**31 and dividend == 1: return dividend if dividend == (-2)**31 and divisor == -1: retur...
95baba61dbe962ed0eee86d936862ff7b16adb10
SuHyeonJung/iot_python2019
/01_Jump_to_python/0_example/9_0711/7_324.py
198
3.703125
4
multiplication_table = int(input("구구단을 출력할 숫자를 입력하세요(2~9): ")) result = 0 for index in range(1,10): result = multiplication_table * index print(result, end=' ')
5daebdcede0b14e4dc6b59e0d86aeb5b3728d67e
Zaitov-RM/Home_Works
/Курс Основы Python.Домашки/Модули/moduls2.py
584
4.28125
4
''' Создайте модуль. В нем создайте функцию, которая принимает список и возвращает из него случайный элемент. Если список пустой, функция должна вернуть None. Проверьте работу функций в этом же модуле ''' from random import choice spis=['1','2','3','4'] spis2=[] def choicelist(lst): if lst: retu...
7b66cf753ded33f44466bf062fb11d9520e054fb
byunys/iteration
/credit_card_instructions.py
575
3.828125
4
# Here’s to test whether or not credit card number is valid: # 0) Double alternating digits starting with the first digit in the sequence. # 1) If the doubling resulted in a number with two digits, add them together to get a single digit number # 2) Add # 3) Check to see if the sum is evenly divisible by 10 #Assign...
5eb6141a022e8e0b421ff0930ddda1fe2fc78e7f
shineloveyc/Data_Structure_Algorithm
/Udacity_Data_Structure_Algorithm/quicksort.py
758
3.96875
4
"""Implement quick sort in Python. Input a list. Output a sorted list.""" def quicksort(array): qs(array, 0, len(array) - 1) return array def qs(array, l, r): #left bound and right bound #base case ==>left index must less than right, if equal, point the same number if l >= r: return p = partit...