blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
b43da9d53ae5e8689a3d6d93c96c45e6551a69a0
JVorous/ProjectEuler
/problem33.py
1,453
3.765625
4
from fractions import Fraction def main(): a = 10 b = 10 fract_list = set() while len(str(a)) < 3: if a % 10 != 0 and b % 10 != 0 and a /b < 1: red_a = 0 red_b = 0 #check if a and b are of non-trivial format str_a = str(a) str_b = str(...
bd8dce29ec3fed1d6b8cb5b469a529f95b04873d
owenxu10/LeetCode
/sort.py
723
3.984375
4
def selectSort(nums): for i in range(0, len(nums)): smallestIndex = i for j in range(i, len(nums)): if nums[j] < nums[smallestIndex]: smallestIndex = j change(nums, i, smallestIndex) return nums def insertSort(nums): for i in range(1, len(nums)): ...
1531336114f6235b88386b10cca46a9d53399d0f
JngHyun/Algorithm
/Inflearn/섹션 6(완전탐색,DFS)/DFS_이진트리순회.py
802
4
4
# DFS : 깊이 우선 탐색 (재귀 이용) # BFS : 넓이 우선 탐색 (queue 이용) # 1 # /\ # 2 3 # /\ /\ # 4 5 6 7 #DFS #전위순회 : (부 왼 오) 1 2 4 5 3 6 7 #중위순회 : (왼 부 오) 4 2 5 1 6 3 7 #후위순회 : (왼 오 부) 4 5 2 6 7 3 1 def DFS(v): if v>7: return else: #stack 그려서 확인해보기 #print(v,end = ' ') #전위...
139a8af9dd11cf28a988ae837ffad9ba54c2acef
Hugocorreaa/Python
/Curso em Vídeo/Desafios/Mundo 1/ex012.py
327
3.640625
4
# Faça um algoritmo que leia o preço de um produto e mostre seu novo preço, com 5% de desconto. preçoProduto = float(input("Qual o valor do produto? R$")) desconto = preçoProduto * 0.05 preçoDesconto = preçoProduto - desconto print("O preço do produto com 5% de desconto será R${:.2f} reais".format(preçoDesconto))
31fe631c72c7f275c3d385b76ac97806f3f3636c
GabrielRomanoo/Python
/Aula 9/ex2.py
558
4.09375
4
# Faça uma função que retorne a quantidade de # espaços presentes em uma string. from functools import reduce x = 'Universidade Catolica de Santos' espaco = list(filter(lambda s: s==' ', x)) #filter(funcao, sequencia) #Retorna lista que pode ser de tamanho diferente da #sequencia original. Retorna na ve...
e461914fa964bc36bb817fa4454a251d5523d62e
SanjeevkMishra/Generic_Training_Python_INFY
/Fundamental Programming Part 1/Assignment 2/calculate_bill_amount.py
1,608
3.890625
4
''' Problem Statement FoodCorner home delivers vegetarian and non-vegetarian combos to its customer based on order. A vegetarian combo costs Rs.120 per plate and a non-vegetarian combo costs Rs.150 per plate. Their non-veg combo is really famous that they get more orders for their non-vegetarian combo than the vegetar...
3526abc6a3f7eca145116b4491a58af102f171e7
v3g42/wordsearch
/wordsearch.py
836
3.796875
4
#!/usr/bin/env python import time import argparse from grid import Grid def get_user_input(): """ defines argument parser to take dimensions of the grid """ parser = argparse.ArgumentParser( description='Please provide the dimensions of the grid') parser.add_argument( 'x', metavar='int', type=int, default=10,...
11c3f1c1c86383ef303f7772a54369609254255e
marciof/tools
/puzzles/uncoupled_integers.py
918
4.09375
4
#!/usr/bin/env python3 # -*- coding: UTF-8 -*- """ Find the only two integers that appear an odd number of times in a sequence of `integers`. """ import unittest def find(integers): """ Time: O(n) Space: O(1) https://www.careercup.com/question?id=16306671#commentThread16306671 """ x_y_xor =...
6e3c749c809681b45660258ca362814b0d135a32
lizetheP/PensamientoC
/CalendarioAgo20L/informacion/autoestudioStrings.py
366
4.34375
4
cadena = "Computacion" print(cadena[0 : 3]) print(cadena[ : 3]) print(cadena[3]) print(cadena[6: ]) print(cadena[-6: ]) print(cadena.find('o')) print(cadena.replace('o', 'u')) print(cadena.upper()) print(cadena.lower()) print(cadena.capitalize()) print('u' in cadena) """ print(str[3 : 8]) print(str[ : -3]) print(str...
b00a90327fa7a4e8ea86dc649bf23223fb184eeb
jayceazua/wallbreakers_work
/company/zendesk.py
2,830
4.34375
4
""" Write an `encrypt` and a `decrypt` method. Each should accept a `key` and a `message`. encrypt(key, message) should reorder the alphabet by moving the key's letters to the front. Then, it should return a string with the message's letters swapped out for their index in the new alphabet. Assume that the key will not...
0561a11162860bd54e056150645b16daf3e29b48
mairbek/CS231A-Computer-Vision-From-3D-Reconstruction-to-Recognition
/ps2_code/fundamental_matrix_estimation.py
6,706
3.5
4
import numpy as np from scipy.misc import imread import matplotlib.pyplot as plt import scipy.io as sio from epipolar_utils import * ''' LLS_EIGHT_POINT_ALG computes the fundamental matrix from matching points using linear least squares eight point algorithm Arguments: points1 - N points in the first image that m...
a7fb12cac76a371b2c762f7f52346a7ba286e01e
qingyueyang/Algorithms_DataStructure_Questions
/jumpSearch.py
536
3.96875
4
def search(arr, n, key): # Travers the given array starting # from leftmost element i = 0 while (i < n): # If key is found at index i if (arr[i] == key): return i # Jump the difference between # current array element and key ...
20c18ea492d988728000eab454351f6a6c9bb31e
dev-juri/FizzBuzz
/FizzBuzz.py
254
4.09375
4
print('Input a number') num= int(input()) if ((num%3==0) & (num%5==0)): print('FizzBuzz') elif (num%3 == 0): print('Fizz') elif (num%5 == 0): print('Buzz') else: print('Number is not divisible by 3 and 5')
94a4ede627c1c75005d62fe6ca02dfef022a76c7
Diegooualexandre/PycharmProjects
/pythonProject/desafio056.py
908
3.859375
4
# Programa que mostra o peso das pessoas # Autor: Diego L. Alexandre | Data: 14/07/2021 soma_idade = 0 media_idade = 0 maior_idade_homem = 0 nome_mais_velho = '' total_mulher20 = 0 for p in range(1, 5): print(f'---- {p}ºPESSOA ----') nome = str(input('Digite nome: ')).strip() idade = int(input('Digite idade...
f2d291cd86ff974b9199dc05c36fb33b42b6c079
singalen/hige_class
/foxcross/foxcross.py
1,046
3.75
4
# -*- coding: utf-8 -*- def _is_cross_at(a, x, y): if x <= 0 or x >= len(a)-1: raise IndexError(x) if y <= 0 or y >= len(a[0])-1: raise IndexError(y) return a[x][y] == '#' and a[x][y-1] == '#' and a[x][y+1] == '#' and a[x-1][y] == '#' and a[x+1][y] == '#' def is_crosses(a): n = len(...
09aed5c6da964f91430c50c2202c7430998b0a02
LeeJiangWei/convex-optimization-assignment
/three_points_interpolation.py
2,288
3.515625
4
import matplotlib.pyplot as plt import numpy as np def f(x): return x ** 3 - 2 * x + 1 def three_points_interpolation(x1, x2, x3, threshold, f): xs = np.inf while True: A = np.array(([x1 ** 2, x1, 1], [x2 ** 2, x2, 1], [x3 ** 2, x3, 1])) A_inv = np.linalg.inv(A) b = np.array([f(...
f1ac39a76fcb5681eaa810e1cb2ca436492f377c
JitSheng/bt3103
/solution_template/template_6.py
885
3.5625
4
class Cell(): def __init__(self,cell_size=20,color=(255, 255, 255),x_position=None,y_position=None): self.cell_size = cell_size self.x_position = x_position self.y_position = y_position self.color = color class Snake(): def __init__(self, cell_size=20, x_position=0, y_position=...
687aab6228975e2ac17623e420bcf129d56b2017
codeWriter9/cautious-python-learner
/Capitalize.py
247
3.578125
4
''' Created on 20-May-2019 @author: Sanjay Ghosh ''' def solve(s): a = s.split(" "); s = ''; for i in range(len(a)): s = s + a[i][0:1].upper() + a[i][1:] + " " ; return s; if __name__ == '__main__': print(solve(input()));
a08c0cfd42c4abbe643e239006e81879c402f6c8
shareneelie/python-tutorial-
/tebak2.py
465
3.71875
4
""" import random play = True while play : kunci = random.randint(1, 11) """ """ print(kunci) """ guess = int(input('please enter your guess (1-10) : ')) if guess == kunci: print('selamat!') coba = input('mau main lagi? (y/n) :') if coba == 'y' : continue...
aa8ac8559c9046ed6c8dc5f1a5609e8891b61dc4
shofiulalamshuvo/Python-Projects-by-Shuvo
/Tell a story.py
697
3.8125
4
import random When = ['A few years ago', 'Yesterday', 'Last night', 'A long time ago','On 30th Sep'] Who = ['a rabbit', 'an elephant', 'a mouse', 'a turtle','a cat'] Name = ['Ali', 'Mariam','Dip', 'Hasan', 'Shuvo'] Place = ['Spain','Antarctica', 'Germany', 'Venice', 'Mars'] Went = ['cinema hall', 'university','sem...
5637f973ef6b3b0acb6b68c336015baa3c7a0e6d
adh2004/Python
/Lab13/DriveCarNew/Car.py
495
3.609375
4
class Car: def __init__(self, car_make, car_model): self.__make = car_make self.__model = car_model self.__speed = 0 def accelerate(self): self.__speed += 5 def decelerate(self): self.__speed -= 5 if self.__speed < 0: self.__speed = 0 def ge...
6f096143ff669be0e3a3872d2b016ca5880e4947
Raj-Python/python-training
/ps_functions_demo.py
1,458
3.65625
4
from sys import stderr, exc_info from traceback import print_tb print '\n\n' print '1 -------------- funtion where exception is printed to the error device ---------------------' def power(x,n=0): return x ** n try: print power(4, 3) print power(4) except TypeError as err: print >>stderr, 'blah ...
99287625f93178121348f29be94671668635f2bd
selavy/tables
/tests/stresstest.py
1,582
3.578125
4
#!/usr/bin/env python import argparse import random class Op: INSERT = 0 ERASE = 1 FIND = 2 MISS = 3 SIZE = 4 MAX = 5 def parse_args(): parser = argparse.ArgumentParser() parser.add_argument("-n", "--nops", type=int, default=100, help="Number of opera...
b97bc2419e862ed72cd6b015617e28f6c43aa877
shivasapra/spy_chat-application
/spy_detail.py
1,887
3.984375
4
from spy_details import Spy # function defined for taking details from spy def spy_detail(): spy = Spy(" ", " ", 0, 0.0) # taking name from user if invalid taking name again temp = 0 while temp == 0: spy.name = raw_input("\n****************\nEnter Name") try: if type(int(sp...
01ea2e5cbef9fc5f77aaa7571ad5c02f45f7e3eb
metrossb/git-learning-course
/lib/fibonacci.py
385
3.84375
4
class Fibonacci: def getTerms(self, terms = 10): if terms < 1: return [] elif terms == 1: return [1] elif terms == 2: return [1, 1] else: # Implement an algorithm vals = [1, 1] for i in range(1,terms-1): ...
26a0de2a5596c453319bf1832d27411ff51c36f6
karri-sek/craftingPython
/testMultipleFlags.py
594
4.0625
4
x , y , z = 0, 1, 0 if x == 1 or y == 1 or z == 1: print("passed") if x == 1 or y ==1 or z == 1: print("passed") else: print("fail") if 1 in (x, y, z): print("1 is present in either x , y , z") if x or y or z: print('passed') if any((x, y, z)): print("passed") x , y , z = 0, 0, 0 if x ==...
2cd47b05a30bec95de86b9ab0c8e458d22cebfd6
kevinsu628/study-note
/leetcode-notes/easy/array/1_twoSum.py
1,229
3.9375
4
''' Question: Given an array of integers, return indices of the two numbers such that they add up to a specific target. You may assume that each input would have exactly one solution, and you may not use the same element twice. Approach 1: Brute Force The brute force approach is simple. Loop through each elemen...
51abcf4e3518de95229e2204a77f7b4492733bf2
hmchen47/Programming
/Python/UoM/book-exercises/purify.py
557
4.28125
4
''' purify Define a function called purify that takes in a list of numbers, removes all odd numbers in the list, and returns the result. For example, purify([1,2,3]) should return [2]. Do not directly modify the list you are given as input; instead, return a new list with only the even numbers. ''' d = [4, 5, 5, 4...
842d81171140c5d97122beeab62daf03f013ea90
lowrybg/SoftuniPythonFund
/dictionaries/capitals.py
381
3.5
4
line = input().split(', ') my_dict = {} counter = 1 country = [] while counter <= 2: for n in range(len(line)): if counter ==1: country.append(line[n]) else: my_dict[country[n]] = line[n] counter+=1 if counter >2: break line = input(). split(', ') for ...
3728c0602605c264e70d5e3547ef9af4a33d740f
GeoffVH/Python-Practice
/CCTC python/Chapter 1 questions.py
3,115
4.15625
4
#////////////////////////////////////////# # Question 1 #Is Unique: Implement an algorithm to determine if a string has all unique characters. #What if you can't use additional data structures? def is_Unique(str1): return len(str1) == len(set(str1)) #No additional data structures def is_Unique_a...
f6c853249889a207abfce4ae58d2bdd0f6b11b9f
austinmw/Python-code
/super_function.py
591
4.03125
4
# Basic example class This_is_a_very_long_class_name(object): def __init__(self): pass class Derived(This_is_a_very_long_class_name): def __init__(self): super().__init__() #1 This_is_a_very_long_class_name.__init__(self) #2 # Both 1 and 2 do the same thing, but 1 is a lot easier # Multip...
7c5e1640f5c76badf1717c88bdcbd02bc54cea2f
saurabhchris1/Algorithm-Pratice-Questions-LeetCode
/Majority_Element.py
617
3.796875
4
# Given an array of size n, find the majority element. The majority # element is the element that appears more than ⌊ n/2 ⌋ times. # # You may assume that the array is non-empty and the majority element always exist in the array. # # Example 1: # # Input: [3,2,3] # Output: 3 # Example 2: # # Input: [2,2,1,1,1,2,2] # Ou...
fa28fc36769184c5a38527c8cdf0a5ff0e14fac5
someMadCoder/mpt
/19.py
696
3.765625
4
import itertools def getNum(): while type: num = input('Длина строки = ') try: int(num) except ValueError: print('"' + num + '"' + ' - не является числом') else: break return int(num) myList = [] myLen = getNum() myStr = input("Количество си...
25b97010c637525d2345cd95615fc0faf0e01191
Samitific/Piscine-Python
/day01/ex05/all_in.py
1,568
4.0625
4
#!/usr/bin/env python3 # -*-coding:utf-8 -* def arg_list(chaine): """traite les parametres fournis dans la ligne de commande""" liste = [item for item in chaine.split(',')] liste = [item.lstrip().rstrip().title() for item in liste if item != '' and item != '\t'] # print(liste) return liste def rev...
a29ed12c6fdecfa537521a683410a1036e363ea1
bismayan/bigdata_python
/python_misc/angle.py
143
3.953125
4
from math import * (a,b)=(int(input("Input side {}:".format(_))) for _ in range(2)) print "{}°".format(int(floor((atan2(a,b)*180/pi)+0.5)))
bd93606677bdec76d0d37b13dec03abffc157b44
xdc7/PythonForInformatics
/chp_03/ex_01.py
281
4.15625
4
hours = float(input("Enter the number of hours worked: ")) rate = float(input("Enter the rate per hour: ")) salary = 0 if hours < 40: salary = hours * rate else: salary = (hours * rate) + (hours - 40) * 1.5 * rate print(("Your salary for the week is {}").format(salary))
c8851a5c2dde183b6ce3fbc9452db2e51dc7c08f
satot/project_euler
/solutions/23.py
680
3.609375
4
def is_abundant(n): divs = set() for i in range(1, n//2+1): if n % i == 0: divs.add(i) return sum(divs) > n def find_abundant(n): abds = set() for i in range(n): if is_abundant(i): abds.add(i) return abds def non_abundant_sums(n): abds = find_abundan...
b75da4bdfc0aaf8f2437b3ea5af3eb8827f1e487
manjitborah2710/Transposer
/transpose.py
244
3.59375
4
import math notes=['A','A#','B','C','C#','D','D#','E','F','F#','G','G#'] a=input("From : ") b=input("To : ") ind_a=notes.index(a) ind_b=notes.index(b) diff=ind_b-ind_a for i in range(12): print(notes[i]," --> ",notes[(i+diff)%len(notes)])
ad07de80c8a3a426fe6b8121f36d8ce5b1657471
yebanxinghui/py_program
/py_program/子串出现次数.py
1,551
3.53125
4
def findstr1(): count = j = 0 string = input('请输入目标字符串:') ch = input('请输入子字符串(两个字符):') len1=len(string) len2=len(ch) for i in range(0,len1): while i+j<len1 and ch[j] == string[i+j]: if j == len2 - 1 : count += 1 j = 0 break ...
63417e897ad65248967df829fd419127955fb670
Aasthaengg/IBMdataset
/Python_codes/p02819/s080641923.py
272
3.671875
4
import math X = int(input()) ans = 0 while ans == 0: factor = 0 if X % 2 == 0 and X != 2: X +=1 continue for divisor in range(2, X // 2): if X % divisor == 0: factor += 1 if factor == 0: ans =X X +=1 print(ans)
b6ad725e19b4a7cd64d5741c5bdba99ed3d07709
alvarogomezmu/dam
/SistemasGestion/Python/1ev/Hoja6/Ejercicio03.py
295
4.28125
4
#_*_coding:utf-8_*_ # Pedimos al usuario que introduzca un string cadena = raw_input("Introduce una cadena: ") # Guardamos la cadena al reves en otro string cadena2 = cadena[::-1] # Comparamos ambas cadenas if cadena == cadena2 : print "Son palindromos" else : print "No son palindromos"
7249f59a20f7a1c5384d8b53313efff5602460c0
MrZhangzhg/nsd_2018
/weekend1/py0102/fib_func.py
766
3.921875
4
# def gen_fib(): # fib = [0, 1] # n = int(input('length: ')) # for i in range(n - 2): # fib.append(fib[-1] + fib[-2]) # # print(fib) # # a = gen_fib() # 函数默认返回None # print(a) # def gen_fib(): # fib = [0, 1] # n = int(input('length: ')) # for i in range(n - 2): # fib.append...
b47ae92e0c82fde8870963c1142737a18acc9678
nihathalici/Break-The-Ice-With-Python
/Python-Files/Day-11/Question-43.py
342
4.15625
4
""" Question 43 Question: Write a program which can filter() to make a list whose elements are even number between 1 and 20 (both included). Hints: Use filter() to filter elements of a list. Use lambda to define anonymous functions. """ def even(x): return x % 2 == 0 evenNumbers = filter(even, range(1, 21)) pri...
8ac4c3f5abc0c39c09bbc738d98492ff5a815fdb
sunnysunita/stack
/Minimum bracket Reversal.py
265
3.71875
4
list = input() def fun(list): s = [] for e in list: if e is "{": s.append(e) elif e is "}": s.pop() # print(s) l = len(s) if l%2 != 0: return -1 else: return l//2 print(fun(list))
80e1df15c0f1c427e6823ac78b80bdc598d8d0f4
impankaj91/Python
/Chepter-7-Loops/exmple-prime_number.py
255
4.125
4
#Check Prime Number. number=int(input("Enter The Number :")) prime=True for i in range(2,number): if(number%i==0): prime=False break if prime: print("Number is Prime.") else: print("Number is not Prime.")
445a15297e05f662726ba2ac89f4d53193aa3b7e
qiblaqi/Stevens-Python-Course-ByQ.Zhao
/810/HW03_Qi_Zhao.py
7,588
3.96875
4
""" this is a program use Class to handle two Fractions plus, minus, mutiply, divide and check-out if they equals to each other upgraded with unittest module to build a test suite Written by Qi Zhao """ import unittest as ut class TestFraction(ut.TestCase): """ Test class of fraction which includes testing '+-*...
8c04f626b6668b00ad18c8b87943505f960b7b51
hiys/PYTHON
/pythonScripts/PyScripts/PyScripts7/test_if.py
259
4
4
if 10 > 0: print('yes') print('ok') if 10 > 100: print('yes') else: print('no') if -0.0: print('yes') # 任何值为0的数字都是False if 100: print('true') if ' ': print('oooookkkkk') # 任何非空对象都是True,空为False
0e92a4abac179ac2b6e9db54c750c790ab401855
pmkhedikar/python_practicsRepo
/concepts/sample_1.py
511
3.78125
4
#!/bin/python3 import math import os import random import re import sys # Complete the twoStrings function below. if __name__ == '__main__': #fptr = open( os.environ['OUTPUT_PATH'], 'w' ) q = int(input()) for q_itr in range( q ): s1 = input() s2 = input() def twoStrings(s1, s...
28dd26faeb518328009b5b8609c12616eb6dd775
515ek/python-BST
/soln09.py
704
4.125
4
#!/usr/bin/python ## Name: Vivek Babu G R ## Date: 03-10-2018 ## Assignment: Implementing the Binary Search Tree DataStructure ## Question: 9. Add method the check whether two BSTs are same. Provide test cases. ################################################################################################# from soln01...
509be3c3904dc8197fcd2a8162d2039a907391b5
nassarnour/python-datastructures
/pythonDictionaries/count.py
751
4.1875
4
# The following python program utilizes dictionaries to count and keep track of different words in a txt file # and then prints the most occuring word, and the number of times it appears. name = input('Enter the files name: ') handle = open(name) counts= dict() for line in handle: words=line.split() for word...
ed47410a2f58f8076e68b88c77429fe977df4f6e
jasapluscom/PYTHON
/JASAPLUS.COM TRAINING MATERIALS/tkinter/button_sample.py
519
3.921875
4
#!/usr/bin/env python3 ''' button_sample.py for course material at www.jasaplus.com ''' from tkinter import Tk, Button, messagebox def OnClick(num): messagebox.showinfo("Information","I got clicked at " + str(num)) window = Tk() window.title("button sample") window.geometry("600x400+300+10") btn = Button(window, ...
1efa4d0843cf3ffb43ee8491fdbaf7c25722738b
nsmith0310/Programming-Challenges
/Python 3/LeetCode/lc1171.py
923
3.515625
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def removeZeroSumSublists(self, head: ListNode) -> ListNode: if head==None:return head l = [] while head!=None: l.append...
5de63b91c4615c16070218e0e86f945fb5b934f8
wdahl/AI-Uniformed-search
/hw1/scource code/G2_matrix_bfs_queue.py
1,801
3.5
4
def bfs(matrix, start): states = [] queue = [start] parents = {} while queue: currElement = queue.pop(0) if currElement not in states: states += [currElement] if currElement is 6: path = [currElement] while currElement is not 11: ...
73a7fbbd36f8415415564e117b7d58301ad8dc1e
mackenzielarson/SonomaState
/CS115/Lab08/lab08d.py
2,272
3.6875
4
__author__ = 'Mackenzie' """ Program: CS 115 Lab 08 (lab08d.py) Extra Credit Author: Mackenzie Larson Description: This program uses the graphics package to animate a group of circles to rotate around each other. """ from graphics import * row1_balls = [] row2_balls = [] # Variables win = GraphWin('An...
3009c1c2a4bf306ca500daf5e58b44cd21579435
caglalogy/Countries-and-Languages
/lang.py
2,350
3.921875
4
import json # Opening JSON file with open('country-by-languages.json') as json_file: data = json.load(json_file) listOfLists = list() for sub_dict in data: listOfLists.append(list(sub_dict.values())) def list_countries(listOfLists): i = 1 country_list = list() for countries in listOfLists: ...
0a8d337aa61e72ffabae4c435ad2d4c8e481aa09
YSQC/PythonCode
/H_Model/卷积神经网络/手工实现/Activations.py
965
3.90625
4
import numpy as np class Relu: """Relu层""" def __init__(self): self.mask = None def forward(self, x): self.mask = (x <= 0) out = x.copy() out[self.mask] = 0 return out def backward(self, dout): dout[self.mask] = 0 dx = dout return dx ...
812eab134a0cfff4ff776c4b4dd648f6361d9725
luis-ibanez/Dominion
/src/app/dominion/unitTest/boardTest.py
2,527
3.671875
4
''' Created on 22/04/2012 @author: ender3 ''' import unittest import random from board import Board from card import Card class Test(unittest.TestCase): def setUp(self): self.board=Board() self.num_players=4 def test_board_initialization(self): # make sure the shuffled seq...
d80b172eff081c4e30e0d49243cdf19bb2bfd162
moment0517/Foundations_of_Algorithms
/QuickSort.py
375
3.734375
4
def quick_sort(arr): if len(arr) <= 1: return arr pivot = arr[0] arr_p1 = [] arr_p2 = [] for i in range(1, len(arr)): item = arr[i] if item <= pivot: arr_p1.append(item) else: arr_p2.append(item) arr_p1 = quick_sort(arr_p1) arr_p2 = qu...
092737312371d79d7222b74716e506716dfbc388
ridongwang/tsdro
/src/helpers.py
6,075
3.625
4
""" Helper functions used to parse data. """ import networkx as nx import numpy as np import itertools from math import sin, cos, asin, radians, sqrt, atan2, degrees import math import sys def gen_shortest_paths(edges, facilities, demandNodes): """ Return shortest path lengths from facilities to demandNodes...
097c8532fa1598e23df3bc7e695264a6995f1885
rajatdiptabiswas/competitive-programming
/LeetCode/959 Regions Cut By Slashes.py
3,604
3.578125
4
#!/usr/bin/env python3 from typing import List class UF: def __init__(self, n: int) -> None: self.parent = [i for i in range(n)] self.size = [1 for _ in range(n)] def find(self, p: int) -> int: while p != self.parent[p]: p = self.parent[self.parent[p]] return p ...
a60ffd69846eb3c404c5367f5c04c29b217d3f9d
middlehuang/CSIE-HW
/Information_Security_Class/hw5/DSA.py
5,698
3.84375
4
import sys import random import math import hashlib def generateLargePrime(keylength): while True: # generate random bits num = random.getrandbits(int(keylength)) # apply a mask to set MSB and LSB to 1 num |= (1 << int(keylength) - 1) | 1 if isPrime(num): ...
e661bfabbb699da2641bc9644c7aaf514466058f
Manevle16/PythonUTDDataScienceWorkshop
/October27/DSPython/12_MatPlotLibFunc.py
813
4.375
4
# Plotting Library for Python # Similar feel to MatLab's graphical Plotting # Conda Install matplotlib # Visit matplotlib.org # important link is gallery import matplotlib.pyplot as plt import numpy as np x = np.linspace(0, 5, 11) #Returns 11 evenly spaced numbers from 0 to 5 y = x ** 2 print(x) print(y) # FUNCTIONAL m...
586f413cb3f08f4cf65eb03c77320b882f601fae
elJuanjoRamos/Curso-Python
/Leccion06-Colecciones/main.py
3,121
4.46875
4
# LISTAS nombres: str = ['Juan', 'Karla', 'Ricardo', 'Maria'] print(nombres) # acceder de forma inversa print(nombres[-1]) # acceder un rango de valores, sin icluir hasta el indice superior print(nombres[0:2]) # ir del inicio de la lista al indice sin incluirlo print(nombres[:3]) # ir desde e indice indicado hasta ...
9c1ba3d9d00cf59c27f66ea481e61f87c278cf8a
ach-orite/leetcode
/leetcode60PermutationSequence.py
1,726
3.671875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2018/12/14 9:38 # @Author : qkwu # @File : leetcode60PermutationSequence.py # 使用老的递归求下一个permutation k次方法 超时,只能通过分析结果来找规律 import math class Solution: # @param {integer} n # @param {integer} k # @return {string} def getPermutation(self, n, ...
dfa8c6c55adb576b4ed98be846a14cc1b8536729
green-fox-academy/FKinga92
/week-02/day-02/factorio.py
177
4.09375
4
# - Create a function called `factorio` # that returns it's input's factorial def factorio(num): fact = 1 for i in range(1, num+1): fact *= i return fact
fe73ffe82b8c7bc14f7d0463a077a80516cf95a6
jiejie168/array_leetCodes
/UniquePaths.py
1,830
3.9375
4
__author__ = 'Jie' """ 62. Unique Paths A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below). The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below). How many ...
05d0585a96c96cf9615fb0fe94b7a7571942d6b3
Edu93Reis/aulaPoo-Python
/T2/T3/Celular.py
1,654
3.5
4
from Bateria import Bateria class Celular: __identificador = 0 def __init__ (self, __nomeUser, __bateria): #identificador é um elemento estático e precisa do nome da classe antes do elemento para funcionar Celular.__identificador += 1 self.__nomeUser = __nomeUser self.__bateri...
b4840b623df06aebf5ce380c444af96574ca9254
ishikaanugupta/Phone-book
/gui.py
2,185
3.75
4
from tkinter import * import sqlite3 window=Tk() window.title("Address Book") window.geometry('300x350') def submit(): conn=sqlite3.connect('phone_book.db') c=conn.cursor() c.execute("INSERT INTO phone VALUES(:txt1,:txt2,:txt3,:txt4)", { 'txt1':txt1.get(), ...
24af02185e7c3320aa614e377e0d3c8e13dfee23
mentor22/PyTest
/pytest/OOP's/Firstclass.py
726
3.75
4
class First: def method1(self): print("Welcome to Method 1 :","Manoj Moolchandani") print("I have a system with",self.cpu ,"and",self.ram) def __init__(self,cpu,ram): self.cpu=cpu self.ram=ram def compare(self,other): if(self.ram==other.ram): ...
70ca3f70ad593d57d004be0bd533f155a8032dbc
DarthOpto/python_projects
/pig_latin/pig_latin_generator.py
838
4.1875
4
""" A pig latin generator. Take input of a word or phrase from a user then - If a word begins with a consonant, then move that consonant to the end and add "ay". If the word begins with a vowel, add "way" to the end. """ import string VOWELS = ['a', 'e', 'i', 'o', 'u'] CONSONANTS = ['b', 'c', 'd', 'f', 'g', 'h', 'j', ...
e03aa88c35f324f46f5414c05ce8f736ecfa4675
heyf/cloaked-octo-adventure
/leetcode/0103_binary-tree-zigzag-level-order-traversal.py
1,261
3.71875
4
# # @lc app=leetcode id=103 lang=python3 # # [103] Binary Tree Zigzag Level Order Traversal # from typing import List # Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None # @lc code=start class Solution: def zigzagL...
d2da69bb9539b9482d17a830bba075003f3934ba
hurricane618/ARTS
/Algorithm/company/vivo_2021_1.py
925
3.890625
4
# 拓扑排序的问题 # 采用优先队列实现 from queue import PriorityQueue class Solution: def compileSeq(self , input ): # write code here data_list = input.split(",") l = len(data_list) pre = [] vis = [False]*l queue = PriorityQueue(l) n = 0 result = "" for data ...
97adc09638514e8ea6a73d1c3a54681b1b4fd0c2
m-hildebrandt/NECTR
/datahelper.py
20,438
3.515625
4
import pandas as pd import numpy as np import random from enum import Enum from scipy.sparse import csr_matrix class Sampling(Enum): """ Class used to represent the various mechanisms for sampling negative examples CONSTRAINED_RANDOM: Rather than getting negative examples by randomly corrupting true t...
c586124dfb2e3772b054a5759c33c1ae73b4cc32
ethancaballero/myia
/myia/utils/profile.py
4,356
3.546875
4
"""Utilities to help support profiling.""" from time import perf_counter as prof_counter # noqa def _unit(secs): return "%.3gs" % secs def print_profile(prof, *, indent=0, sums=None): """Print a visualisation of a profile.""" total = prof.pop('__total__') runtime = 0 ind = " " * indent if ...
1911212e2e657efe5d82e2c71e19691b915552bd
Adriel-M/HackerRank
/Learn/Artificial Intelligence/Natural Language Processing/From Paragraphs to Sentences/paragraph2sentence.py
1,775
3.9375
4
""" With the assumption that there won't be a quote for the last sentence. Need to improve abbreviation detection. Overall, this is not a good implementation as there are too much assumptions with no basis. """ entry = input().strip() def is_abbreviation(sentence): """ Evaluate a word to be an abbreviation i...
cefdfafa0bf5bb6f9a3632b82dcc7a7dad854fdb
egortcevasofia/the_basics_of_programming_in_python
/4_week/Исключающее ИЛИ.py
205
4.09375
4
def xor(x, y): if (x == 1 and y == 0) or (y == 1 and x == 0): return 1 elif (x == 0 and y == 0) or (x == 1 and y == 1): return 0 x = int(input()) y = int(input()) print(xor(x, y))
57521e80e0e9ff520c3abc6caf223ed67173b955
aakashsbhatia2/k-means
/kmeans.py
6,558
3.8125
4
import csv import math import random import sys import matplotlib.pyplot as plt from scipy.spatial import distance def calculate_distance(point1, point2, type): """ Here, I am calculating the distance between point 1 and point 2. The distance metric is based on the "type" parameter. There are 2 types of ...
bc26eaf42883124b997cf6a4a736273724ed7431
ptsiampas/Exercises_Learning_Python3
/07_Iteration/Exercise_7.26.11.py
686
4.25
4
# Revisit the drunk pirate problem from the exercises in chapter 3. This time, the drunk pirate makes a turn, # and then takes some steps forward, and repeats this. Our social science student now records pairs of data: # the angle of each turn, and the number of steps taken after the turn. Her experimental data is # [(...
6be3bebde1fdd30509f912208c9b278f1f774c85
msolone/Code_Wars_Katas
/Python/7 Kyu/minimum_steps.py
1,374
3.875
4
# Given an array of N integers, you have to find how many times you have to add up the smallest # numbers in the array until their Sum becomes greater or equal to K. # Notes: # List size is at least 3. # All numbers will be positive. # Numbers could occur more than once , (Duplications may exist). # Threshold K will ...
3554146912ba53ad028b1dcb546b3c9120ae1c02
EduardCosmin/Python
/learn_python/Errors_and_exception_handling_8/errors_and_exception_handling.py
3,039
4.625
5
#Errors and exceptions handling #We use three keywords for this: # try: This is the block of code to be attempted (may lead to an error). # except: Block of code will execute in case there is an error in try block. # finally: A final block of code to be executed , regardless of an error. #Example def add(n1, n2...
7d1b1750caf0e327c092a9a5d23af3a754db163d
jailukanna/Python-Projects-Dojo
/05.More Python - Microsoft/04.inheritance_student.py
800
3.984375
4
class Person(): def __init__(self, name): self.name = name def say_hello(self): print(f'I am Hello {self.name}') class Student(Person): def __init__(self, name, school): super().__init__(name) self.school = school def sing_school_song(self): print(f'Ode to {se...
4c23e316b37181d2d987dc043ee5d1f25df0a3d0
IsAlbertLiu/Python-basics
/basic/CG平台题目/cg_06_1.py
548
4.0625
4
# 请编写一个程序,实现删除列表重复元素的功能。 # 【输入形式】输入一行数据,以空格作为间隔。 # 【输出形式】输出删除重复元素的一行数字,以空格作为间隔。 # 【样例输入】5 12 9 12 6 23 9 5 # 【样例输出】5 12 9 6 23 arr = input() new_arr = arr.split(' ') no_repeat_arr = [] str = '' # 遍历 for i in new_arr: if i not in no_repeat_arr: no_repeat_arr.append(i) # print(new_arr) # print(no_repea...
7674cfdda561240673885530dfa356fc20cef58e
unaidelao/python-exercises
/absp/collatz.py
1,362
4.53125
5
#!/usr/bin/env python # -*- coding: utf-8 -*- """Practice Projects: The Collatz Sequence. Write a function named collatz() that has one parameter named number. If number is even, then collatz() should print number // 2 and return this value. If number is odd, then collatz() should print and return 3 * number + 1. Th...
7c8d4617fe0b4fe1a38e7bb84c0a882a54ff7780
timelyanswer/python-hafb_KHK
/Day 1/my_list.py
770
3.796875
4
#!/usr/bin/env python3 """ Author : t11 <me@wsu.com> Date : 8/9/2021 Purpose: """ import argparse # -------------------------------------------------- def main(): """Make your noise here""" r = [4, -2, 10, -18, 22, 55, 2, 77] # Slicing print(r[2:6]) print(f'len of linst {len(r)} ') print(f...
b134907535caa80cea8ee7941263c33d96d78523
johndoubleday1/Caesar
/Caesar.py
1,075
3.953125
4
import string import collections def caesar(rotated_string, number_to_rotate_by): letters = collections.deque(string.ascii_letters) letters.rotate(number_to_rotate_by) letters = ''.join(list(letters)) return rotated_string.translate(str.maketrans(string.ascii_letters, letters)) while True: ...
79c233a64d1e8c851691803af698b3bf5987210a
Fabricio-Lopees/computer-science-learning
/exercises/01.python-for-everybody/chapter05/exercise02.py
431
4.125
4
maximum = 0; minimum = 0; guard = None; while guard != "done": try: number = input("Enter a number: ").lower() if number == "done": print("Highest number entered: ", maximum) print("Lowest number entered: ", minimum) guard = number else: number = float(number) if number > maximum: maximum = ...
e8bccfe56389dfbeb3440d0a1c535850ba930477
Shirmyyy/CS313E
/Work.py
2,041
3.75
4
# File: Work.py # Description: Assignment8 # Student Name: Shimin Zhang # Student UT EID: sz6939 # Course Name: CS 313E # Unique Number: 51350 # Date Created: 10/6/2018 # Date Last Modified: 10/6/2018 #function to find v def find_v(n,k,hi,lo): mid = lo + (hi - lo)//2 #if he fi...
68b4081f5ffbe467430d67bfedc0afd2c238196e
problems-forked/Dynamic-Programming
/Longest Common Substring/main.py
1,426
3.78125
4
def find_LBS_length(nums): maxLength = 0 for i in range(len(nums)): c1 = find_LDS_length(nums, i, -1) c2 = find_LDS_length_rev(nums, i, -1) maxLength = max(maxLength, c1 + c2 - 1) return maxLength # find the longest decreasing subsequence from currentIndex till the end of the array def find_LDS_len...
16ebb397f31a29c6cf6667a2c2b6404e99fa1f28
NileshSavale/Python-3.X
/Pattern2.py
331
3.78125
4
#!/user/bin/python #Pattern 2: #***** 1 #**** #** #* def pattern2(no): for i in range(1,no+1): for j in range (1,no-i+2): print('*\t',end='') print ("\n") def main(): no=eval(input("Enter Number to for pattern2:")) pattern2(no) if __name__=='__main__': ...
6ac2d6c9610c9eb2124a09ec108ec2956a2e5c23
Qiujm/MyPython
/leetCodeAlgorithm/sorts/mergeSort.py
694
3.671875
4
def partition(lyst, left, right): middle = (left+right) //2 piv = lyst[middle] lyst[right]=piv boundary=left for index in range(left,right): if lyst[index] <piv: # lyst[index],lyst[boundary] = lyst[boundary],lyst[index] swap(lyst,index,boundary) boundary +...
4639cf59202cdf856e3eb6db5ca25aea8f553ba5
VagrantXD/Stajirovka
/7kyu/oddoreven.py
524
4.0625
4
#!/bin/python3 #Task: #Given an array of numbers (a list in groovy), determine whether the sum of all of the numbers is odd or even. # #Give your answer in string format as 'odd' or 'even'. #If the input array is empty consider it as: [0] (array with a zero). #Example: #odd_or_even({0}, 1) returns "even" #odd_or_eve...
32570dda016cebe08c1256a0a1b89382915ac704
gprolog/python-for-learn
/GitHub/0002.py
1,392
3.59375
4
#0002,将生成的激活码保存到oracle数据库中 import string import random import cx_Oracle forselect=string.ascii_letters +string.digits def codes(count,length): #生成激活码 for x in range(count): Re='' for y in range(length): Re+=random.choice (forselect) yield Re #yield生成器,有返回值 pr...
5b6449d250a418f1acd5749420b9937499e4a4ed
himichael/LeetCode
/src/1401_1500/1404_number-of-steps-to-reduce-a-number-in-binary-representation-to-one/number-of-steps-to-reduce-a-number-in-binary-representation-to-one.py
333
3.609375
4
class Solution(object): def numSteps(self, s): """ :type s: str :rtype: int """ n = int(s,2) res = 0 while n!=1: if n&1==1: n += 1 res += 1 else: n //= 2 res += 1 ...
3e4f6f4a5cc70efd3a66910c8c3ce14214ed417c
gemapratamaa/codingproblems
/Divide.py
469
4
4
def divide(dividend: int, divisor: int) -> int: answer = 0 if dividend < 0: return divide(-dividend, divisor) * -1 if divisor < 0: divisor *= -1 while dividend - divisor >= 0: dividend -= divisor answer += 1 return -answer ...
30d5b7a266e5356f636a49eae169a97245d2eb28
PierAr/Python_Exercises
/Lists/lists.py
551
4.46875
4
#create and print a list first_names = ["pier", "allyson", "tony", "kevin", "paolo"] print(first_names) #print a specific list item --> list number starts from 0 print(first_names[1].title()) print(first_names[3].title()) #calling for item in -1 position gives bacj the last item print(first_names[-1].title()) #use it...
598dd7d52d4dd0cb4f18630a4f7463858f877691
AndrewAct/DataCamp_Python
/Analyzing Police Activity with Pandas/Preparing the Data for Analysis/Examining_the_Dataset.py
276
4
4
# 5/11/2020 # Import the pandas library as pd import pandas as pd # Read 'police.csv' into a DataFrame named ri ri = pd.read_csv('police.csv') # Examine the head of the DataFrame print(ri.head()) # Count the number of missing values in each column print(ri.isnull().sum())
206f66d416950e685de0f3103a5cfc1c9d915cb3
yguo18/Zero-Stu-Python
/PygameForKey/randomCircle.py
686
3.5625
4
''' Created on 2016.11.29 @author: yguo ''' import pygame import random pygame.init() size = [400, 300] screen = pygame.display.set_mode(size) clock = pygame.time.Clock() count = 0 red = pygame.Color('#FF8080') blue = pygame.Color('#8080FF') white = pygame.Color('#FFFFFF') black = pygame.Color('#000000') done = False...
22f8c77fa2d00aff5d82b0a88d148bed36bb7f73
PedroLSF/PyhtonPydawan
/12a - CHALLENGE_Basic/12a.3_Classes.py
4,277
4.03125
4
### 1-Setting Up Our Robot # Define the DriveBot class here! class DriveBot: def __init__(self): self.motor_speed = 0 self.direction = 0 self.sensor_range = 0 robot_1 = DriveBot() robot_1.motor_speed = 5 robot_1.direction = 90 robot_1.sensor_range = 10 ### 2- Adding Robot Logic class Dri...
62ede1f35d72bef8204ca106948614e28ae1d99e
windard/leeeeee
/216.combination-sum-iii.py
1,415
3.703125
4
# coding=utf-8 # # @lc app=leetcode id=216 lang=python # # [216] Combination Sum III # # https://leetcode.com/problems/combination-sum-iii/description/ # # algorithms # Medium (52.54%) # Likes: 674 # Dislikes: 34 # Total Accepted: 131.7K # Total Submissions: 249.9K # Testcase Example: '3\n7' # # # Find all poss...
ccfb5c03b8cac3ce160cb137c8b7eb63dca10603
ljungmanag42/Project-Euler
/PE-007.py
528
3.84375
4
# ProjectEuler 7 ''' By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13. What is the 10 001st prime number? ''' ################### # Answer = 104743 ################### def is_prime(x): if x==1 or x==2: return True for f in xrange(2,int(round(x**...