blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
2e18828ffb8c2066745d3939d643d9dab296413a
WPettersson/kidney_utils
/kidney_utils/graph.py
17,736
3.6875
4
"""A directed graph representing kidney patients and donors.""" try: from queue import Queue except ImportError: from Queue import Queue import community import networkx from progressbar import ProgressBar, Bar, Percentage class Vertex(object): """A vertex in a directed graph.""" def __init__(self, d...
7f16ba35671249d6c1a90ee142900b25fd838cfe
hiroshi-horiguchi/100knocks
/000.py
97
3.609375
4
str = "stressed" n_str = "" for i in range(len(str)): n_str = n_str + str[-i-1] print(n_str)
d9d5d5c55e3739a1f4ce8c73bf24f1d5124eabc8
prabalbhandari04/python_
/wap1.py
107
4.03125
4
n=int(input("enter number")) if n%2==0: print("number ids even") else: print("number is odd")
b120950654b9575e1b3184e1a19c6de492d24f7e
rrwt/daily-coding-challenge
/daily_problems/problem_101_to_200/problem_192.py
943
4.25
4
""" You are given an array of non-negative integers. Let's say you start at the beginning of the array and are trying to advance to the end. You can advance at most, the number of steps that you're currently on. Determine whether you can get to the end of the array. For example, given the array [1, 3, 1, 2, 0, 1],...
87b8a18c15f84db1b5792af69a54d2f2dc705deb
sumit-mandal/machine-learning-complete
/part-1 Data Preprocessing/P14-Part1-Data-Preprocessing/Section 3 - Data Preprocessing in Python/Python/data_preprocessing_templates.py
829
4.03125
4
# Data Preprocessing Template # Importing the libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd # Importing the dataset dataset = pd.read_csv('Data.csv') X = dataset.iloc[:,:-1].values #it means we take all rows and all columnns except last Y = dataset.iloc[:,3].values #it shows all row...
6c69009ebdaf8d82df2de466a6e5f38609be00d5
farhanr8/PyExercises
/Codewars/ex29.py
1,837
4.15625
4
''' https://www.codewars.com/kata/calculating-with-functions/ ''' def operate(x, func): operation = func[0][0] if operation == '+': result = x + int(func[0][1]) elif operation == '-': result = x - int(func[0][1]) elif operation == '*': result = x * int(func[0][1]) elif op...
4c6a4eda89d87e4d98576de3097a49cbf245e399
Sanchezt99/numericalapp
/src/numericalapp/Equation_Systems/Methods/gaussSimple.py
2,856
3.5625
4
import numpy as np def gauss_enter(a,size): print(f"a {a} \n size {size}") A = a[0:-size] b = a[-size::] print(f"A {A} \n b {b}") A = np.array(A).reshape(size,size).astype(np.float64) b = np.array(b).reshape(size,1).astype(np.float64) return A,b def gauss_elimination(a,b):...
37ce6139868ea2ee70b5fff97ea7ae4a4e5a29d7
Rishabhh/LeetCode-Solutions
/Arrays/419_Battle_ships_in_a_board.py
646
3.796875
4
class Solution: def countBattleships(self, board): """ One-pass, O(1) space complexity. Check if 'X' is left-most point of a ship. :type board: List[List[str]] :rtype: int """ res = 0 for r, row in enumerate(board): for c, val in enumerate(...
8fcc4929eb930f87f4068a2e616cfeafe2108b7b
JeromeSivadier/pyWebCrawler
/pyWebCrawler.py
4,861
3.515625
4
# coding=utf-8 import urllib2 from BeautifulSoup import BeautifulSoup __version__ = "0.1" AGENT = "%s/%s" % (__name__, __version__) class Fetcher(object): """ This class is designed to Fetch an URL and take all the links on the distant-page. It will add the new urls to the URLS variable """ ...
cc613fb770a59a8cf7163cb42b541fedf6183bc1
cheungnj/exercism
/python/armstrong-numbers/armstrong_numbers.py
258
3.890625
4
def is_armstrong(number): num_string = str(number) value = 0 length = len(num_string) for c in num_string: digit = int(c) value += digit**length if value > number: return False return value == number
dc619d397dab64a29b13ea560488141bb7f69da6
minggaaaa/pycharm
/20211101/ex02.py
284
3.859375
4
# # tuple = immutable = # list = mutable # alist = [1,2,3] btuple = (1,2,3) print(alist) print(btuple) for i in alist: print("alist i = ",i) for i in btuple: print("btuple i = ",i) alist[1] =5 print(alist) # btuple[1] = 5 # print(btuple) s1 = "abcde" s1[2] ='c' print(s1)
ee9fd8f76026b384b69342c22b350004ecf16d0c
brunocous/kbc_pyspark_training
/tests/test_distance_metrics.py
804
3.546875
4
"""Exercise: implement a series of tests with which you validate the correctness (or lack thereof) of the function great_circle_distance. """ import math import pytest from exercises.unit_test_demo.distance_metrics import great_circle_distance def test_great_circle_distance(): # Write out at least two tests for...
cb8bd3f916370af063097baa82efbead39585059
aerodame/sampler
/Algorithms/PairsSearch/Python/pairs_store.py
1,080
3.859375
4
""" PairsStore - Storing pairs of numbers and their sum key. Note that this is a general purpose pairs store that could store pairs for numerous keys (hence the use of a Hashmap). A simpler version of this would just be a list to store pairs for ONE key. """ class PairsStore: def __init__(self): # Initia...
80989c0e5a09e2f3e9a4f68d8d5371a5422c347c
vipinpillai/ricochet-robots
/Ricochet.pyde
8,770
4.0625
4
"""This program sets up and displays a puzzle based on the game Ricochet Robots. The solve() method contains code to compute the solution to the puzzle.""" path_to_file_containing_puzzle = "test" from Robot import Robot from Robot import Node import time def solve(): """This method will compute and return...
496027764e253a16a16269652e8287bad5472268
camilaffonseca/Learning_Python
/Prática/ex036.py
669
4.1875
4
# coding: utf-8 ''' Escreva um programa em Python que leia um número inteiro qualquer e peça para o usuário escolher qual será a base de conversão: 1 para binário, 2 para octal e 3 para hexadecimal. ''' numero = int(input('Digite um número inteiro: ')) base = input('''Escolha a base para conversão... \n[...
a91ac887afda4916573496a0f689ad38918b49f2
prolo09/pari_2020
/part2/ex5/ex5.py
2,162
3.9375
4
#!/usr/bin/env python import readchar listCharAsc = [] def printALLCharsUpTO(): print ("intreduza um carater :") stop_char = readchar.readchar() charInAscii = ord(stop_char) # ord serve para por em ascii for x in range(32, charInAscii): xChar = chr(x) # passa de ascii para o seu carater ...
4d4ea6eca9acb6ba0e19212d3ecf3d0474f20d99
tmayphillips/DigitalCrafts-Assignments
/day08_text_editor.py
615
3.90625
4
with open('learning_python.txt', 'w') as file_object: file_object.write("In Python you can create and use variables.\n") file_object.write("In Python you can create classes.\n") file_object.write("In Python you can do unit tests.\n") file_object.write("In Python you can create and edit files.\n") with ...
63d48fffd6364197ce1266ef2778b1b75a357eb3
chrzhang/euler
/p050ConsecutivePrimeSum/p050.py
2,127
3.6875
4
import math import time """ The prime 41, can be written as the sum of six consecutive primes: 41 = 2 + 3 + 5 + 7 + 11 + 13 This is the longest sum of consecutive primes that adds to a prime below one-hundred. The longest sum of consecutive primes below one-thousand that adds to a prime, contains 21 terms, and is equ...
27b57390514e7d43677f29d20d1d439d0bd575cf
projectinnovatenewark/csx
/Students/Semester2/lessons/students/3_classes_and_beyond/18_access_modifiers/18_access_modifierstodo.py
983
4.15625
4
""" ToDo for 18_access_modifiers """ # TODO: Section 4 # Define a class called "User" that has the public instance attribute "username" and the private # instance attribute "password". Then define a method within the "User" class called # "check_password()" that will take an input with the question reading "What is t...
458476227113d539676d599a0754d6c7c8dd46a3
miaviles/Data-Structures-Algorithms-Python
/linkedLists/right_shift.py
2,375
4.0625
4
""" Right Shift A Singly Linked List Given the head of a singly linked list, rotate the list k steps to the right. Example 1: Input: k = 2 1 -> 2 -> 3 -> 4 -> X Output: 3 -> 4 -> 1 -> 2 -> X Example 2: Input: k = 4 4 -> 1 -> 6 -> 7 -> X Output: 4 -> 1 -> 6 -> 7 -> X Constraints k >= 0 """ class Node: def __i...
27002ad6d683367124f023b14b446b929f042cc6
umnstao/lintcode-practice
/bfs/tree(no need to check)/70.binaryTreeLevelTraversal.py
812
3.828125
4
""" Definition of TreeNode: class TreeNode: def __init__(self, val): self.val = val self.left, self.right = None, None """ class Solution: """ @param root: The root of binary tree. @return: buttom-up level order in a list of lists of integers """ def levelOrderBottom(self, root...
e8342235babeb31ed1b2600b6d5d731604812f16
mariuszurbaniak/CodeWars
/nameInText.py
145
3.890625
4
def name_in_str(str, name): it = iter(str.lower()) print(all(c in it for c in name.lower())) name_in_str("Across the rivers", "chiis")
8955ac2f774c8bc3f74eff39de10b044a55987e9
CollegeBoreal/INF1042-202-20H-02
/P.Projets/300115140/b300115140.py
1,450
4.125
4
# -*- coding: utf-8 -*- """ Created on Wed Apr 8 14:21:40 2020 Conception d'un jeu dela tortue avec Python Turtle Graphics @author: zacks """ import turtle import random zack = turtle.Turtle() # Utilisation des variables zack = turtle.Turtle() zack.color("red") zack.pensize(5) zack.shape("turtle") zack.forwar...
a3ad0a6233acf99fc8b0a18d5856b86637332748
ksmdeepak/Leetcode
/Python Solutions/Rotate_Array_189.py
685
3.53125
4
class Solution: def rotate(self, nums, k): """ :type nums: List[int] :type k: int :rtype: void Do not return anything, modify nums in-place instead. """ k=k%len(nums) start =0 count =0 while count < len(nums): current = start ...
e75926826748fcd818d1f7fa153ca42785a62fb2
pengshishuaia/OA_TEST
/test_case/生成器和迭代器/生成器的应用.py
853
4.03125
4
''' 进程---》线程---》协程 生成器;generator 生成器一般应用在协程上面,意思就是生成器交替执行 定义生成器的方式: 1,通过列表推导式 g = (x for x in range(6)) 2,函数+yield def func(): 。。。 yield 相当于return g = func() 产生元素 1,next(generator) ---每次调用都会生产一个新的元素,如果元素产生完毕,再次调用的话就会产生异常 2,生成器自己的方法: g.__next__() g.send(value) ''' def tarde1(i): for i in ra...
ade79fb0adaa2141143b383ed323a0873383a42f
erfannoury/new-eleusis
/Game.py
11,448
3.65625
4
""" Contains the Player and Scorer classes """ import random from rule_functions import * import phase2 class Player: """ The Player class which contains the logic of the New Eleusis game. Parameters ---------- cards: list The initial list of legal cards from the dealer which starts the g...
ae03842ad370c886f70585c3407726b5229f32cf
twinkle2002/Python
/altrnatvconstructor.py
825
3.828125
4
class Employee: no_of_leaves = 8 def __init__(self,name,salary,role): self.name = name self.salary = salary self.role = role def printdetails(self): return f"name is {self.name}. salary is {self.salary}. and role is {self.role}" # classmethod # def change_leaves(cls...
a9e4642163c21bbe5e1cde0ef11851f5659694fe
Protino/HackerRank
/Algorithms/Implementation/SherlockAndTheBeast.py
177
3.75
4
for _ in range(int(raw_input())): y=int(raw_input()) z=y while(z%3!=0): z-=5 if(z<0): print '-1' else: print z*'5'+(y-z)*'3'
ba14ab08a00494523afdb0b86e3e4c066b812908
florekem/python_projekty
/codewars/codewars8.py
824
3.734375
4
""" pytania: 1. Dlaczego po apostrofie (lub innym znaku z poza alfabetu .title() podnosi do uppercase? c = "'" whereisit = [pos + 1 for pos, char in enumerate(words_upper) if char == c] to jakbym zapisal to tak: enum = enumerate(words_upper) [x for x, char in enum if char == c] -> iterator [x+1 for x,ch...
37abfd49c7d22d3e3443d08078e161087e82d7fa
Christy538/Hacktoberfest-2021
/PYTHON/BFS.py
621
4.125
4
graph = { '5' : ['3','7'], '3' : ['2', '4'], '7' : ['8'], '2' : [], '4' : ['8'], '8' : [] } visited = [] # List for visited nodes. queue = [] #Initialize a queue def bfs(visited, graph, node): #function for BFS visited.append(node) queue.append(node) while queue: # Creating loop to vis...
51454b13d0e8f13c9aea938595ad25ec81e3c0de
JenySadadia/MIT-assignments-Python
/Assignment2/Exercise2.4.py
650
4.03125
4
##Author : Group 4 ##Assingnment 2 ## --------------------Exercise 2.4.1-------------- import math import random def rand_divis_3(): number = random.randint(0,100) print ("number: " +str(number)) if number%3 == 0: return True else: return False print rand_divis_3() ...
6e7f66b357fe987e7f07b6fca47180a570211106
DmitriiBaranovskii/learn-homework-1
/3_for.py
881
4.0625
4
""" Домашнее задание №1 Цикл for: Оценки * Создать список из словарей с оценками учеников разных классов школы вида [{'school_class': '4a', 'scores': [3,4,4,5,2]}, ...] * Посчитать и вывести средний балл по всей школе. * Посчитать и вывести средний балл по каждому классу. """ import random def main(): grades ...
2fe992b1d202abf66d1aabb205981a65aec183d4
kvijayenderreddy/march2020
/userDefinedFunctions/function.py
1,126
4.28125
4
# list = [1,2,3,4,5] def myName(name="Rayesa"): print("My Name is", name) # print("My Name is " + name) # myName(list) def listItertion(list): for i in list: print(i) # listItertion(list) def myNewName(name='Anjali'): returnString = "My Name is" + name print(returnString) return retur...
e21cd44fcf2235ecaf33ee5553b0654685c0f279
michaelhuo/pcp
/98.py
1,554
3.78125
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def isValidBST(self, root: TreeNode) -> bool: def _isValidBST(root: TreeNode) -> (bool, int, int): ...
d26f0fd56aebfffba575a1799e5b8e109afa8726
mason-larobina/projecteuler-py
/006/6.py
715
3.90625
4
#!/usr/bin/python # Mason Larobina <mason.larobina@gmail.com> # === Problem 6 ============================================================== # The sum of the squares of the first ten natural numbers is, # 1^2 + 2^2 + ... + 10^2 = 385 # # The square of the sum of the first ten natural numbers is, # (1 + 2 + ... + 1...
c9cd9aff0bf2935a85e1af761e37d0658aa0758f
MikeMinheere/1.3.1-Werken-met-condities
/game.py
7,328
3.609375
4
#Mike Minheere 99067548 import time def path1(): print('je komt een verlaten dorp tegen, wat doe je?') verlatenDorp = input('huizen doorzoeken (1) of doorlopen? (2) ') if verlatenDorp == '1': time.sleep(2) print() print('je gaat de huizen doorzoeken en je vind niet veel.') t...
c1e15fc34fabdd4339276cc4563c9644ccb2c8e7
Meghashrestha/pythonassignment02
/20.py
771
4.0625
4
# 20. Write a Python class to find the three elements that sum to zero # from a list of n real numbers. Input array : [-25, -10, -7, -3, 2, 4, 8, 10] Output : [[-10, 2, 8], [-7, -3, 10]] def three_element(arr, n): found = True for i in range(0, n - 2): for j in range(i + 1, n - 1): for k ...
884920a2199ae56380b35c18414b185bb5ca2e24
Indi44137/Functions
/Development 1.py
481
4.125
4
#Indi Knighton #6/12/2014 #Development 1 hours = int(input("Please enter the amount of hours: ")) minutes = int(input("Please enter the amount of minutes here: ")) seconds = int(input("Please enter the amount of seconds here: ")) def calculate_seconds(hours, minutes, seconds): hours = minutes * 60 m...
4f62b4725401590f00361d0cb4c311fe538908c2
mihirchakradeo/leetcreator
/main.py
456
4.1875
4
leet = {'a':'4','b':'13','c':'(','d':'[)','e':'3','f':'f','g':'6','h':'|-|','i':'|','j':'j', 'k':'|<','l':'1','m':'m','n':'/\/','o':'0','p':'|>','q':'q','r':'|2','s':'5','t':'7','u':'|_|','v':'\/', 'w':'w','x':'}{','y':'y','z':'2'} def convertToLeet(inp): a=[] arr = inp.split(" ") for word in arr: for i in word:...
aa6e5f8aaa4c218408472956b83a6ca07ba59fcb
anuroopmishra21/practice_codes_python
/binary_search_in_list.py
351
3.65625
4
l=list(map(int, input("Enter the list ").split(" "))) n=int(input("Enter the element to be searched ")) c=0 low=0 high=len(l)-1 while low<=high: mid=(low+high)//2 if n== l[mid]: c=1 break elif n<l[mid]: high=mid-1 else: low=mid+1 if c==1: print("Element found") else: ...
f113f8a1f4c7b50a7017ad3d6e64b76ec61a8d32
chw3k5/philsGroup
/intoToPython.py
6,586
4.25
4
""" Comments - This is a multi-line comment This is a brief introduction to python, written in Python 3 """ # this is a single line comment """ The print state statement """ # simple example print("Here is a simple print example.") # compound example, the elements in the print statement are separated by commas , pr...
d781dc0ed39f1ee55c98b5bd2fa38cb3a4bfc663
GredziszewskiK/spoj
/prime_t.py
407
3.765625
4
# link do zadania # https://pl.spoj.com/problems/PRIME_T/ from math import sqrt from sys import stdout, stdin def is_prime_number(number): x = int(number) y = sqrt(x) if x < 2: return 'NIE\n' for n in range(2, int(y)+1): if x % n == 0: return 'NIE\n' return 'TAK\n' for ...
2a7a9663b472ca24e68dffaa908aed565c417d3a
WoodyLuo/PYTHON
/Lecture07/ex05_CircleWithPrivateRadius.py
462
3.640625
4
''' Exercise05 - CircleWithPrivateRadius Functions. Chung Yuan Christian University written by Amy Zheng (the teaching assistant of Python Course_Summer Camp.) ''' import math class Circle: def __init__(self, radius=1): self.__radius = radius def getRadius(self): return self.__radius de...
859e39398ddc0e4998680a13272e992252f42cfd
1179069501/-
/4.16/demo/users/middleware.py
572
3.6875
4
#定义一个中间件用到的闭包 def my_decorator(func): print('init') def wrapper(request): print('视图函数执行之前,调用的区域') response = func(request) print('视图函数调用之后,调用的函数') return response return wrapper def my_decorator1(func): print('init2') def wrapper(request): print('视图函数...
ce2a183433226c291f139bcd8d65021dcfbdc227
Kwpolska/adventofcode
/2015/14-reindeer-olympics.py
1,398
3.59375
4
#!/usr/bin/python3 class Reindeer(object): # I feel like doing OOP today. name = "Santa" speed = 0 fly_time = 0 rest_time = 0 distance = 0 in_fly = 0 in_rest = 0 points = 0 def __init__(self, name, speed, fly_time, rest_time): self.name = name self.speed = int(sp...
2d2a7e90a9cdc787228df0e5126b3a78bdeb45cf
aschiedermeier/Programming-Essentials-in-Python
/Module_6/6.1.4.9.reflectInspect.py
880
3.625
4
# 6.1.4.9 OOP: Method # Reflection and introspection # The function named incIntsI() gets an object of any class, # scans its contents in order to find all integer attributes with names starting with i, # and increments them by one. class MyClass: # define class pass obj = MyClass() # create object obj.a = 1 ...
4a241dbbbb655be8c6a541c1ce86dc2117555319
dongyingdepingguo/PTA
/pta_practice/PTA1038.py
925
3.546875
4
# !/usr/bin/env python # _*_ coding: utf-8 _*_ """ 1038 统计同成绩学生 (20 分) 本题要求读入 N 名学生的成绩,将获得某一给定分数的学生人数输出。 输入格式: 输入在第 1 行给出不超过 10**5 的正整数 N,即学生总人数。随后一行给出 N 名学生的百分制整数成绩, 中间以空格分隔。最后一行给出要查询的分数个数 K(不超过 N 的正整数),随后是 K 个分数,中间以空格分隔。 输出格式: 在一行中按查询顺序给出得分等于指定分数的学生人数,中间以空格分隔,但行末不得有多余空格。 输入样例: 10 60 75 90 55 75 99 82 90 75 50 3...
70dbfdbeaa4a5914a5f9183e17dea0782d97782f
xinlongOB/python_docment
/面向对象/父类的私有属性和方法.py
1,542
4.34375
4
# 在父类定义的私有方法或属性 子类不能直接访问 """ class A: def __init__(self): self.num1 = 100 self.__num2 = 200 def __test(self): print("私有方法 %d %d" % self.num1,self.__num2) class B(A): def demo(self): pass #1、访问父类的私有属性 # print("访问父类的私有属性 %d" % self.__num2) #2、调用父类的私有方法...
e603f6094d8c34c90126d5f9c46f08b9aa91fc55
saiteja6969/Gitam-2019
/PYTHON2019 (1).py
988
3.875
4
#!/usr/bin/env python # coding: utf-8 # In[1]: print("HELLO WORLD") # In[4]: print("hello") # In[8]: x=1 y=2 z=x+y print(z) # In[14]: y=11 z=12 w=100 x=y*z*w print("value of x is ",x) # In[16]: initialmarks=600 TotalMarks=900 percentage=(initialmarks/TotalMarks)*100 print(percentage) # In[18]: p...
773ce1d2a9975b48df7a742b84445952877392a7
bentd/think-python
/14.5.2.py
465
3.609375
4
def sed(pattern,replacement,file1,file2): try: file1=open('file1.txt','r') file2=open('file2.txt','w') for line in file1: if pattern in line: file2.write(line.replace(pattern,replacement)) else: file2.write(line) file1.close() fil...
805a828ae43db181206996bcba14d3edde27cfe8
LiangFei90/PythonDataAnalysis
/Study/starCpy
314
3.890625
4
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Mon May 22 17:29:29 2017 @author: frank 题目:用*号输出字母C的图案。 """ for i in range(12): if i<2 or i>9: print '**************' elif i==2 or i==9: print '**** **' else: print'****'
8c9c8211f6a733a8a2d88a7a096eb662d0e10bb6
AntoniyaV/SoftUni-Exercises
/Fundamentals/01-Basic-Syntax-Conditional-Statements-and-Loops/09-easter-cozonacs.py
553
3.703125
4
budget = float(input()) flour_price = float(input()) eggs_price = 0.75 * flour_price milk_price = (flour_price + (0.25 * flour_price)) / 4 cozonac_price = eggs_price + flour_price + milk_price colored_eggs = 0 cozonac_count = 0 lost_eggs = 0 while budget > cozonac_price: colored_eggs += 3 cozonac_count += 1 ...
f28874928fedc481cf0d83f3f841495682a65a18
hanqizheng/Algorithm
/Easy/JewelryAndStone.py
871
3.90625
4
""" 给定字符串J 代表石头中宝石的类型,和字符串 S代表你拥有的石头。 S 中每个字符代表了一种你拥有的石头的类型,你想知道你拥有的石头中有多少是宝石。 J 中的字母不重复,J 和 S中的所有字符都是字母。字母区分大小写,因此"a"和"A"是不同类型的石头。 示例 1: 输入: J = "aA", S = "aAAbbbb" 输出: 3 示例 2: 输入: J = "z", S = "ZZ" 输出: 0 注意: S 和 J 最多含有50个字母。 J 中的字符不重复。 """ # 这道题就是考了一个count函数 class Solution: def numJewelsInStones(self, J,...
2bf104bbb3c9a41d56921c47f4a8e0a02caaf7d7
Sona1414/luminarpython
/flow controls/looping/forloop/demo.py
198
4.09375
4
#for loop #initialisation --i #condition---range(low,upp) #upp-1 is executed #increment can be mentioned in range function for i in range(1,11,1): print(i) for i in range(1,11,2): print(i)
34f43bf294d27961b95985ae2b5f7faa15b74802
1170300523/code
/python/agriothm homework/Biscuit allocation.py
453
3.53125
4
# 贪心策略: 先满足贪婪因子小的孩子 def Biscuit_allocation(): k = 0 s = list(map(int, input("input s: ").split())) f = list(map(int, input("input f: ").split())) s = sorted(s) f = sorted(f) while len(s) and s[0]<f[-1]: for j in f: if j >= s[0]: f.remove(j) s....
0788092b33d91955c27ab4ea465aaaa739da0f7e
matchallenges/Portfolio
/2021/PythonScripts/leet_code_2.py
821
3.6875
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def addTwoNumbers(self, l1, l2): str_list1 = [str(i) for i in l1] str_list2 = [str(i) for i in l2] l1_joined = ''.join(str...
0651c2a413ab40e73fb1e007e88cabc4e16496cf
Jane-Zhai/LeetCode
/easy_math_013_Roma2Int.py
407
3.5
4
class Solution: def romanToInt(self, s): """ """ dic = {'I':1, 'V':5, 'X':10, 'L':50, 'C':100, 'D':500, 'M':1000} ans = 0 for i in range(len(s)): if i < len(s)-1 and dic[s[i]]<dic[s[i+1]]: ans -= dic[s[i]] else: ...
5509c5336a4f6be517027aea952032b1717aa90a
onyonkaclifford/data-structures-and-algorithms
/data_structures/trees/avl_tree.py
6,261
3.921875
4
from binary_search_tree import BinarySearchTree from tree import Tree class AVLTree(BinarySearchTree): """An AVL tree is a binary search tree that is balanced. Whenever an item is inserted or deleted, the tree rebalances itself. This ensures an a worst case search time of O(logn). Instantiate an AVL tree...
8c59200ffd5df27a6c3a77e41512f9fac5178c95
Aplex2723/Introduccion-en-Python
/Clases y Objetos/POO.py
929
4.15625
4
'''Ejemplo de implementacion con programacion Estructurada''' clientes = [ {'Nombre' : 'Hector', 'Apellido' : 'Costa Guzman', 'ine' : '111111111A'}, {'Nombre' : 'Pedro', 'Apellido' : 'Casillas Torres', 'ine' : '222222222B'} ] def mostrar_clientes(clientes, ine): for c in clientes:# le asignamos a ...
3a1cdff326a1b4b6748659272be79664bd4bb36d
Ayruahs/HuluHangmanChallenge
/Hangman.py
3,150
3.640625
4
""" The logic of my code is as follows: I first check for the most frequent letters in the hangman phrase. After there is only one guess left, I use regular expressions to check for specific words from the list of most used words provided by Google, which is recorded in the "count_1w.txt" text files. """ import json i...
efd7cb48fe786a8b8948881d889e2b30a0fdcd4d
GustavoJatene/practice
/059.py
1,032
3.953125
4
sair = False n1 = int(input("Digite o primeiro valor: ")) n2 = int(input("Digite o segundo valor: ")) opc = int maior = n1 while not sair: print("-" * 30) print("[1] Para SOMAR\n[2] Para MULTIPLICAR\n[3] Para MAIOR\n[4] Para NOVOS NUMEROS\n[5] Para SAIR") print("-" * 30) opc = int(input("Digite a opção:...
69dae8eb1c8e3d63e74eaa0355e2f4fc6a83e964
Panda0229/flasky
/04_request.py
1,028
3.59375
4
from flask import Flask, request app = Flask(__name__) # 接口 api # 127.0.0.1:5000/index?city=shenzhen&country=china 问号后面的成为查询字符串(QueryString) @app.route("/index", methods=["GET", "POST"]) def index(): # request中包含了前端发送过来的所有请求数据 # form和data是用来提取请求中的数据 # 通过request.form可以直接提取请求中的表单格式的数据,是一个类字典的对象 # 通过get方法只能拿到多个同名参...
c6a561bc50981ff655be602259e9afd936476b1a
parulc7/100-Days-of-NLP
/Day 1/re.py
297
4.375
4
# Matching Regular Expressions in a string import re words = ['Hello', 'this'] expression = '|'.join(words) print(re.findall(expression, 'Hello world This is Parul', re.M)) # Reading from a file and splitting into strings with open('test.txt') as f: words = f.read().split() print(words)
d127694ba04fb31705a229392c7e6db3605cce98
geriwald/coding-exercises
/DailyCodingProblem/P03_serializeTree.py
1,226
4.1875
4
# Good morning! Here's your coding interview problem for today. # This problem was asked by Google. # Given the root to a binary tree, implement serialize(root), which serializes the tree into a string, # and deserialize(s), which deserializes the string back into the tree. # For example, given the following Node cla...
03e403bac3c2e041c9dfacdc5c6604f534207072
gurmehar98/PracticeProblems
/MaximumDepthOfN-aryTree.py
899
3.625
4
class Node(object): def __init__(self, val, children): self.val = val self.children = children class Solution(object): def maxDepth(self, root): if root == None: return 0 return(self._helper(root)) def _helper(self, root): if root == None: ret...
fb3f11bb3eafe33f7cb30e98c089d8806ed93b73
yeonkyu-git/Algorithm
/백준/B_1427.py
908
4.125
4
def sorting (numbers): if len(numbers) <= 1: return numbers mid = len(numbers) // 2 before_list = numbers[:mid] after_list = numbers[mid:] before_list = sorting(before_list) after_list = sorting(after_list) return merge(before_list, after_list) def merge(left, right): result = [...
edcfc333d2d7a07a3915f282608bc4c75287fe3c
csula-students/cs4660-fall-2017-OnezEgo
/cs4660/graph/graph.py
8,721
4
4
""" graph module defines the knowledge representations files A Graph has following methods: * adjacent(node_1, node_2) - returns true if node_1 and node_2 are directly connected or false otherwise * neighbors(node) - returns all nodes that is adjacency from node * add_node(node) - adds a new node to its i...
c199984b3de228c3c5ce68009fb5898aa94c7624
vektorelpython24proje/temelbilgiler
/HUNKAR/OOP_/Generators.py
227
3.609375
4
import random as rnd liste = [i for i in range(1000)] def luckies(liste,count): for i in range(count): yield rnd.choice(liste) for item in luckies(liste,3): print(item) print(rnd.sample(liste,3))
4786ad99401f82f44a763a25ca7714bc584c2aad
Gutu-Ivan/Bazele-programarii
/02.10.19/3.py
250
3.96875
4
a = input ("Введите основание:") a = int(a) b = input ("Введите основание:") b = int(b) h = input("Введите высоту:") h = int(h) print ("Площадь трапеции равна:", int(1/2*(a+b)*h))
543bb6b85e932e11b2ed087b78c69cb82e2d4af8
qq122716072/ai_note
/numpy_demo/numpy02.py
209
3.65625
4
import numpy as np a = np.array([1,2,3,4,5,6]) #变矩阵 b = a.reshape(3,2) print(b) print(np.sum(b, axis=1)) p = np.array([2,2]) print(p-b) #距离计算 欧氏距离 print(np.sum((p-b)**2, axis=1)**0.5)
d4988376f26201b5ffbd21b10dd9901426a6eef4
brn016/cogs18
/18 Projects/Project_k4carr_attempt_2018-12-12-11-27-27_SnakeWithExtraCredit/SnakeWithExtraCredit/my_module/functions.py
7,716
3.75
4
# coding: utf-8 # In[ ]: import turtle import random import os from time import sleep class food(): def __init__ (self, foodChar, terminal): self.foodChar = foodChar self.terminal = terminal def foodShape(self): shapes = ["arrow", "turtle", "circle", "triangle", "class...
770c6063732e81270a65e5e202c8c145a56e10cc
LinglingJ/Python
/DecryptFile.py
1,345
3.609375
4
#Given an encypted text try to decrypt import os, sys def main(): #Open input file and save into message EncryptedFile = 'SomeCipherText.txt' if not os.path.exists(EncryptedFile): print('------------------------Could not find input file----------------------') quit() fileObj = open(Encr...
c63b27dd013ec74ae6c1decee24d2804055432e0
AaronLi/DNA-Codons
/levenshtein.py
2,124
3.53125
4
class Levenshtein: alphabet = "abcdefghijklmnopqrstuvwxyz " def __init__(self, **weight_dict): self.w = dict(((letter, (7, 1, 6)) for letter in Levenshtein.alphabet + Levenshtein.alphabet.upper())) if weight_dict: self.w.update(weight_dict) def get_distance(self, s, t): ...
7de5eae167fa9cb5411abab797f4da5a65f16c99
himma-civl/30daysofpython
/Day6_Practices.py
1,132
3.953125
4
# -*- coding: utf-8 -*- """ Created on Tue Mar 9 00:33:38 2021 @author: yesye """ # Day 6 - 30DaysOfPython Challenge # Practices empty = () sisters = ('Ina', 'Rushia') brothers = ('Angus', 'Izumi') siblings = sisters + brothers print('I have', len(siblings) , 'siblings.') siblings = list(siblings) siblings.appe...
9761e93381f85d1b47c1f4df86b1f8ce19e75fbc
ErlangZ/projecteuler
/36.py
225
3.671875
4
def is_bin_palindromes(x): bstr = bin(x)[2:] return bstr[::-1] == bstr def is_int_palindromes(x): s = str(x) return s[::-1] == s print sum([i for i in xrange(1000000) if is_int_palindromes(i) and is_bin_palindromes(i)])
20da3dfe4bd89485c26425353fb1867f82155cd6
brandonjohnbaptiste/python-book-problems
/ch1-numbers/number_guess.py
1,215
4.3125
4
import random # standard guessing game def guessing_game(): rand_num = random.randint(0, 100) # Loop until number found while True: guess = int(input('Enter Your Guess: ')) if guess == rand_num: print(f'{guess} is the correct guess!') break elif guess < ra...
4508a8d9cb718b05baddd3bbed0b18d86555b618
JoaoZati/ListaDeExerciciosPythonPro
/EstruturaDeRepeticao/Ex_43.py
2,276
3.671875
4
#%% 43 - Cardapio Lanchonete """ O cardápio de uma lanchonete é o seguinte: Especificação Código Preço Cachorro Quente 100 R$ 1,20 Bauru Simples 101 R$ 1,30 Bauru com ovo 102 R$ 1,50 Hambúrguer 103 R$ 1,20 Cheeseburguer 104 R$ 1,30 Refrigerante 105 R$ 1,00 Faça um program...
39ac5774d88f38099ea499447f80cceec55acca2
fuenfundachtzig/Pythonkurs1
/notebooks/source/solutions/titanic_chk.py
433
3.71875
4
import sqlite3 conn = sqlite3.connect('titanic.db') curs = conn.cursor() curs.execute('''SELECT * FROM titanic''') # fetch all entries in 1 go alld = curs.fetchall() print(len(alld)) print(alld[0]) # (0, u'male', 22.0, 7.25, u'S', u'Third', u'man', None, u'Southampton') # select entries 3rd class and male...
041bf343bca267524d8e46d80e1396a4af4b8b12
Michaela192/ENGETO-Projekt2
/Projekt_2.py
4,506
3.671875
4
import random ODDELOVAC = 47 * '-' #Program pozdraví užitele a vypíše úvodní text print('Hi there!') print(ODDELOVAC) print('I´ve generated a random 4 digit number for you.') print('Let´s play a bulls and cows game.') print(ODDELOVAC) #Program dále vytvoří tajné 4místné číslo (číslice musí být unikátní a nesmí začína...
6f0b494a2e71648f090de154e87063ce13114e84
JDavid121/Script-Curso-Cisco-Python
/130 functions and arguments.py
348
3.8125
4
# -*- coding: utf-8 -*- """ Created on Sun Feb 23 11:46:55 2020 @author: David """ # part 1 def myFunction(n): print("I got", n) n += 1 print("I have", n) var = 1 myFunction(var) print(var) def myFunction(myList1): print(myList1) myList1 = [0, 1] myList2 = [2, 3] myFunct...
398c87f7cb322279c2a32c5dc0c0e53e79f0d020
austin72905/python-lesson
/file_operation/file_operation.py
1,350
4.21875
4
##文件(file) #1. I/O (Input/Output) #2. 操作文件的步驟 # (1) 打開文件 # (2) 對文件的操作( 讀、寫 ),然後保存 # (3) 關閉文件 ##打開文件 #1. 語法 open(file) #2. 參數 file : 路徑 #3. 返回值: 打開的文件(obj) #4. 路徑用/ 取代\ ,或是 \\ ## 讀取文件內容 #1. 語法 文件物件.read() #2. 可將內容存成一個str ##關閉文件 #1. 語法 文件物件.close() #2. 如果代碼執行完,文件會自動關閉,會自己是放掉資源,但如果下面還有代瑪,還是要自己關掉 ##自動關閉 ...
91558328185d9140b1a2b66e1f8c5b7cdc82a94b
andrejeller/Learning_Python_FromStart
/Exercicios/Fase_07_OperadoresAritimeticos/Exercicio_013.py
343
3.8125
4
""" Desafio 013 - Faça um algorítimo que leia o salário de um funcionário e mostre seu novo salário, com 15% de aumento. """ salario = float(input('Salario: ')) aumento = salario * 1.15 # jeito 1 aumento2 = salario + (salario * 15 / 100) # jeito 2 print('O novo valor do se salario com 15% de aumento é de R${:.2f}.'....
9f9d9c69b51d21f1c12cb8e6cfd40598ea718401
Adison25/CS362-hw2
/leapWithErrorHandling.py
582
4.1875
4
print("Program checking to see if a year is a leap year or not") run = 1 while run == 1: year = input("Please enter a year: ") #check input if year.isnumeric(): #if info is valid if int(year) % 4 != 0: print(str(year) + " is a common year") elif int(year) % 100 != 0: ...
21953cb54cfc5bb3ad9312472bb873ea2f9dd60c
wolffam/CodingPractice
/Python/Fibonacci_recursive.py
329
3.71875
4
# Create fibonacci sequence based on input (list containing starting int) and stops before a provided max number def fib(seq, max_num): if len(seq) == 1: seq.append(seq[0]) while seq[-1] + seq[-2] < max_num: seq.append(seq[-1] + seq[-2]) fib(seq, max_num) return seq print(fib([1]...
a76938022cd8ed5e991ab7d69a27b9bf0f25717b
QuantumNinja92/hackerrank
/intro to statistics/1/day1.py
1,216
3.84375
4
# Enter your code here. Read input from STDIN. Print output to STDOUT from __future__ import division N = int(raw_input()) S = raw_input() As = S.split(" ") for i in range(0, N): As[i] = int(As[i]) def InsertionSort(Arr): check = 0 n = len(Arr) index = 0 while( check == 0): if (Arr[index] ...
e7f0208b24090c8a25f5372a415f6be335b456cd
povert/Programming
/python/装饰器实现单例/了解装饰器变量.py
828
3.703125
4
# 自定义一个容器,类,看容器会实例化几次 class Hodect(): def __init__(self,name): self.li = list() self.name = name print(self.name+'容器实例化') def __del__(self): print(self.name+"容器删除") def S(func): h = Hodect('傅雨') def wrap(*args,**kwargs): if func not in h.li: h.li.appe...
598dc1c6301f27ff5593ac193151b8f336961dd6
I-will-miss-you/CodePython
/Curso em Video/Duvidas/d010.py
607
3.625
4
#Proposta 4: #Escreva um programa para calcular o tempo de vida de um fumante. Pergunte a quantidade de cigarros fumados por dia e # por quantos anos ele fumou. Considere que um fumante perde 10 minutos de vida a cada cigarro, calcule quantos dias # de vida um fumante perderá. Exiba o total em dias. qtdCigarros = int...
a7aeb9aaa6aa0c5cd21408873645ae636ababf34
imatyukin/python
/PythonCrashCourse/chapter_09/exercise9_14.py
913
3.734375
4
#!/usr/bin/env python3 from random import randint class Die(): def __init__(self, sides=6): '''N-гранный кубик''' self.sides = sides def roll_die(self, throws): '''Вывод случайного числа от 1 до количества сторон кубика с иммитацией количества бросков''' nums = [randint(1, sel...
5fda270a7bc285b564fa6890dcb309c125d641e3
Taoge123/OptimizedLeetcode
/LeetcodeNew/python/LC_042.py
1,363
3.765625
4
""" The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped. Thanks Marcos for contributing this image! Example: Input: [0,1,0,2,1,0,1,3,2,1,2,1] Output: 6 """ class Solution: def trap(self, height): left, right = 0,...
d10d970e4759e9330a4c64104150002b25409041
aliumaev/PythonLesson
/Task#3.py
440
3.75
4
# Lesson #1 # 3. Узнайте у пользователя число n. Найдите сумму чисел n + nn + nnn. # Например, пользователь ввёл число 3. Считаем 3 + 33 + 333 = 369. while True: n = input("Please enter integer number n: ") if n.isdigit(): n = int(n) result = n+n*n+n*n*n print(f"n+n*n+n*n*n = {n}+{n}*{...
cc761cec65900a54059da17b2f433b399675377d
tsmchoe/cs591_c2_assignment_6
/problem_3/problem_3_test.py
933
4.03125
4
import unittest from problem_3 import string_multiplication class TestStringMethods(unittest.TestCase): def test_string_multiplication(self): self.assertEqual(string_multiplication('0','0'), '0', 'string_multiplication("0","0") should return "0"') self.assertEqual(string_multiplication('12','6'), ...
0afbd9e73d731d26bdccdd56efd42f0787b48fc1
AmauryOrtega/scripts-simulacion
/Binomial_Dados.py
495
3.625
4
import random n_corridas = 50 n_lanzamientos = 51 P = 1.0/6.0 respuesta = 0.0 # Cuantas veces se obtuvieron 20 veces el numero 3 luego de n_lanzamientos for corrida in range(n_corridas): # INICIO Corrida numero_3es = 0 for lanzamiento in range(n_lanzamientos): R = random.uniform(0, 1) if R < P: numero_3es +=...
a73c1e9bb149d6d68b750f41fc8f9e2e0742f3aa
aj2010adil/HackerRank-Python
/Print Function
249
4.09375
4
#!/bin/python from __future__ import print_function if __name__ == '__main__': n = int(raw_input()) #taking input from user for i in range(1,n+1): print(i,end='') #end="" is used for printing the output in the same line
44e4a9c5c57a9e799d7933573cea95fb3501d884
ivanakonatar/Homework04
/zad6.py
219
3.625
4
#za dati broj vratiti listu pozicija na kojima se pojavljuje u proslijedjenom nizu niz=[1,2,3,4,5,3,7,7] broj=3 pozicije=[] for i in range(len(niz)): if niz[i] == broj: pozicije.append(i) print(pozicije)
4eaa7c71f152841032f0e834e74e840476b1c0df
Gulnaz-Tabassum/hacktoberfest2021
/Python/Factorials_of_large_numbers.py
483
3.8125
4
class Solution: def factorial(self, N): fact = 1 while(N>=1): fact = fact * N N = N-1 return str(fact) if __name__ == '__main__': t=int(input()) for _ in range(t): N = int(input()) ob = Solution() ans = ob.factorial(N) ...
82318bae4d37238cb94a00b1f1d4af01d3692eb4
arundaniel-kennedy/Cryptographic-Algorithms
/CNS-dany/diffie.py
188
3.53125
4
p = int(input("Enter p")) k = int(input("Enter k")) a = int(input("Enter a")) b = int(input("Enter b")) c = (k**a)%p d = (k**b)%p ssk1 = (d**a)%p ssk2 = (c**b)%p print(ssk1,ssk2,c,d)
a1fa9660bd5ae4d2d4614d5aa3a5ac1056cf242e
siokas/Python-Class1
/project2/Motor.py
221
3.625
4
class Motor: isBig = False def __init__(self, port, isBig=False): self.isBig = isBig if isBig: print(port + " MOTOR is big") else: print(port + " MOTOR is small")
9670c33ccf6ab9ce46680c31409fdd968584e639
pengzhefu/LeetCodePython
/array/easy/q189.py
2,133
4.21875
4
# -*- coding: utf-8 -*- """ Created on Mon Mar 25 09:47:18 2019 @author: pengz """ ''' Given an array, rotate the array to the right by k steps, where k is non-negative. Example 1: Input: [1,2,3,4,5,6,7] and k = 3 Output: [5,6,7,1,2,3,4] Explanation: rotate 1 steps to the right: [7,1,2,3,4,5,6] rotate 2 steps to th...
2c3b8adfa38c6e514bebd2061edf8475a30e3ae3
JimmyRomero/AT06_API_Testing
/JimmyRomero/Python/Exam/Employee_commercial.py
764
3.546875
4
from Python.Exam.Person import Person class EmployeeCommercial(Person): def __init__(self, name, pieces, department, num): super().__init__(name, pieces) self.department = department self.id = "CE-00" + str(num) self.salary = 0 self.discount = 0 def get_id(self): ...
f23dd5bb31fd50a0c2877041d1220f8ac9168266
escoffier/algorithm-py
/myList.py
1,007
3.796875
4
from typing import List class MyList: def __init__(self, parameter_list:List): self.vaules = parameter_list def __iter__(self): print('MyList::__iter__') return MyListIterator(self) def length(self): return len(self.vaules) def at(self, i:int): return self.vau...