blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
b900952f7bde69faa25689a6a1cc9ba55c7972fa
Typical-dev/STD-deviation
/std-dev.py
589
3.890625
4
import csv with open("data.csv", newline = "") as f: reader = csv.reader(f) file_data = list(reader) data = file_data[0] def mean(data1): total_marks = 0 total_entries = len(data1) for marks in data1: total_marks += float(marks[1]) mean = total_marks/total_entries return...
dd9d3fc3a9f025769bc8e44a100eb42ec427cca7
nag-sa/testpython
/set.py
1,321
4.375
4
""" SET 1. A set is a collection which is unordered, unchangeable*, and unindexed. 2. Sets are unordered, so you cannot be sure in which order the items will appear. 3. Sets cannot have two items with the same value, not allowed duplicate values. 4. Set items are unchangeable, but you can remove items and add new ite...
cf5c42683a8b63c336e99e3cfb2cd675611d4c27
MitsurugiMeiya/Leetcoding
/leetcode/String/基础/14. Longest Common Prefix(最长相同前缀).py
1,422
3.796875
4
""" Write a function to find the longest common prefix string amongst an array of strings. If there is no common prefix, return an empty string "". Example 1: Input: ["flower","flow","flight"] Output: "fl" Example 2: Input: ["dog","racecar","car"] Output: "" Explanation: There is no common prefix among the input strin...
b3b6d4ed548c926ccb1777361b4c0662e228767d
rahuldbhadange/Python
/interview-preparation/fibonaci.py
167
3.6875
4
a, b = 0, 1 for i in range(0, 11): print("......",i) print(a) # if a == 13: # continue a, b = b, a+b ab = 1,2,3,4 print(ab, type(ab)) help
aae38e16170a2c2bc18c469b991bd9651dd580e0
iamsureshtumu/py-prgms
/python programs/varargs.py
1,057
3.84375
4
#varargs : variable arguments #two types are i) packing ii) unpacking #i) packing #eg 1: def packing_demo(*var): # star defines 0 to n variables for packing print(*var) print(var) print(type(var)) print("_"*50) packing_demo() packing_demo(10) packing_demo(1,2) packing_demo(1,2,3,4) packing_demo(1,2,...
77762d8b4100063603005cdf89bf267363c809d5
somphorsngoun/python_week_14
/python/week14-3.py
249
3.71875
4
# MAIN CODE array2D = eval(input()) # Write your code here ! for n in range(len(array2D)): for r in range(len(array2D[n])): if array2D[n][r] == 7: array2D[n].pop(r) array2D[n].insert(r,8) print(array2D)
2a51f8dadcf3a4c72fc4fbadabbc00ad540ff5c0
tardisgallifrey/ldap
/change.py
2,676
3.546875
4
#!/usr/bin/python # # LDAP modify utility in Python # to modify or delete people # in LDAP # # 8/21/2011 DEV # import cgi, commands, os # base strings needed for ldap changes search="ldapsearch " modify="ldapmodify" delete="ldapdelete" filename="-f single.mod" host="-h localhost " auth="-x -w password -D 'cn=Manager...
9191a08145c73aa037678a3692235cd452f356db
mrliangcb/python_basic
/3.算法/剑指offer_python练习/4.06从上到下打印二叉树(按层打印).py
522
3.875
4
# 按层从上到下吗,还是深度遍历(前中后序)那样 # 按层 def PrintTB(root): if not root: return [] res=[] res_val=[] res.append(root) #根节点入队 while len(res)>0: #只要队里有元素,就继续遍历 node=res.pop(0) #拿出待处理元素0 res_val.append(node.val) #将本节点的值输出 if node.left: #遇到一个元素就把左右孩子加入队列后边 res.append(node.left) if node.right: res.append(no...
b4e908493003e105b9d459446d8611ef218634d3
dotokbit/HULKulator
/Hulkulator.py
2,358
3.703125
4
#Hulkulator 2.1 from colorama import init from colorama import Fore, Back, Style init () print (Fore.BLACK) print (Back.RED) print ("Hi! Let's do some MATHemagic!") def loop (): while True: try: print (Fore.BLACK) print (Back.YELLOW) a=float(input ("Tell me the first num...
74d8a740423d6a8d6bcf71b35d675323b6b6e80c
vincentzhang/coding-practice
/sorting/merge_sort.py
1,086
4.0625
4
# space: O(n), not in-place def merge_sort(unsorted): if len(unsorted) > 1: # print 'len of unsorted', len(unsorted) # Divide until only 1 item left in the list idx_mid = int(len(unsorted) / 2) left = unsorted[0:idx_mid] right = unsorted[idx_mid :] merge_sort(left) ...
cd5c78a29d32aa67a5743e965995164790e51bb3
FrauHelga/Homework_Python
/D1/Arifmetic.py
727
4.09375
4
#! /usr/bin/env python # -*- coding: utf-8 -*- import sys def arithmetic (x, y, operation): if (operation == '+'): return x+y elif (operation == '-'): return x-y elif (operation == '*'): return x*y elif (operation == '/'): try: return x/y except ZeroDivisionError: return "Деление на 0" else: r...
4d2c7dfdc9f17f38ee3ffd1c7eef9d57e349531f
ErikLindeman12/CSCI_1133
/Labs/Lab7/reverse.py
142
3.828125
4
def reverse(teststring): newstring = "" x = len(teststring)-1 while x >=0: newstring+=teststring[x] x-=1 return newstring
58298c6dc2d4539f8701133fd954422015e7e26a
DavLivesey/greedy_algoritms
/List_symbols.py
657
3.921875
4
def is_correct_bracket_seq(sequence): element_dict = { 'begin_symbols': ('[', '(', '{'), 'finish_symbols': (']', ')', '}') } start = 0 end = -1 open_symbol = element_dict['begin_symbols'].index(sequence[start]) close_symbol = element_dict['finish_symbols'].index(sequence[end]) ...
536cb5e6441daa05905d18ab5874bdca2de5707b
lakshyarawal/pythonPractice
/Sorting/minimum_difference.py
895
3.90625
4
""" Minimum Difference between elements: given an array we have to find the minimum difference between two elements among all the elements in the array""" import sys from quick_sort import quick_sort_hoare """Solution""" def min_difference(arr) -> int: min_diff = sys.maxsize for i in range(len(arr)): ...
23e48170e277716b0666de92eba57797e73be729
Niloy28/Python-programming-exercises
/Solutions/Q51.py
361
4.4375
4
# Define a class named Circle which can be constructed by a radius. The Circle class has a method which can compute the area. class Circle(object): PI = 3.1416 def __init__(self, radius): self.radius = radius def area(self): return Circle.PI * self.radius ** 2 circle = Cir...
9c67d7d6d6c3a43d00108e1b5b1f26c25f96b2c0
mathans1695/Geektrust-Traffic
/test_helper.py
1,084
3.859375
4
import unittest from helper import filter_vehicles, calculate_time from orbit import Orbit from vehicle import Vehicle class TestHelper(unittest.TestCase): def setUp(self): # create three instance of vehicle self.bike = Vehicle("bike", 10, 2, ["sunny", "windy"]) self.tuktuk = Vehicle("tuktuk", 12, 1, ["sunny",...
6a75535a061369ffc3af6ba1f78b5f082ab08f6e
JoaquinAguilar/Python_Practices
/python_course/datatype.py
442
3.578125
4
#Strings print("Hello wolrd") print('Hello world') print('''Hello world''') print("""Hello world""") #Integer print(30) #Float print(30.1) #Boolean True False #List [10, 20, 30, 55] #Se puede cambiar ['Hello', 'Bye', 'Adios'] [10, 'Hello', True, 10.2] [] #Tuples (10, 20, 30, 55) #No se pue...
43ca1e1c53caf7ac35c9fd562b3b82a45218df2c
aaskov/non-linear-signal-processing-toolbox
/nn/nn_forward.py
961
3.53125
4
# -*- coding: utf-8 -*- """ Neural network - nsp """ import numpy as np def nn_forward(Wi, Wo, train_inputs): """ Propagate exaples forward through network calculating all hidden- and output unit outputs. Args: Wi: Matrix with input-to-hidden weights.\n Wo: Matrix with hidden...
7a080e15999983fc904eb2fb690e8f7a66808d4a
cs50/cscip14315
/2021-06-30/grade5/grade.py
469
3.921875
4
def main(): score = int(input("What's the score? ")) letter_grade = get_letter_grade(score) print(letter_grade) def get_letter_grade(score): if score <= 100: if score >= 90: return "A" if score >= 80: return "B" if score >= 70: return "C" ...
3ad048c48e9553b893552da486aff5442543f208
rlavanya9/cracking-the-coding-interview
/recursion/magic-array.py
798
3.71875
4
# def magic_array(myarr): # return magic_array_helper(myarr, 0) # def magic_array_helper(myarr, i): # if not myarr: # return -1 # while myarr: # if myarr[i] == i: # return i # magic_array(i+1) def magic_array(myarr, low, high): if high >= low: mid = (lo...
581480787d8ff00791f109e73b0efaaea9dce218
whsu/sps
/priority.py
770
3.765625
4
''' A simple priority queue for pixels. Each pixel has an integer intensity between 0 (black) and 255 (white). Pixels closer to the ends of the spectrum have higher priority than pixels closer to the middle. ''' from heapq import * def get_priority(intensity): return min(intensity, 255-intensity) class PriorityQue...
9bbe069f04b838789233956a1128e97d495a360b
MichaelLenghel/python-concepts-and-problems
/data_structures/Trees/binary_tree2.py
2,492
3.984375
4
class Node: def __init__(self, key): self.key = key self.previous = self.next = None self.tail = self.head = None class BinaryTree: def __init__(self, key = None): self.key = key self.left = self.right = None self.counter = 0 self.tree_vals = [] def insert(self, root, key): if root ==...
d04451b499094a708a578022764d9363fe713a04
Shoncito92/Evaluacion_m3
/main.py
3,152
3.71875
4
class Inventario: def __init__(self, nombre, nombre_archivo): self.nombre = nombre self.nombre_archivo = nombre_archivo self.elementos = [] def __crear_archivo(self): pass def agregar(self, elemento): self.elementos.append(elemento) return self.elementos ...
db602afe7ec4200fbaea9c9e7cbbf7fb8b38e157
slake516/web_scraping_challenge
/Mission_to_Mars/scrape_mars.py
4,443
3.5
4
#!/usr/bin/env python # coding: utf-8 from splinter import Browser from bs4 import BeautifulSoup import pandas as pd import requests import time def scrape_info(): # Using Splinter to initialize Chrome browser executable_path={'executable_path':'C:\\Users\\slake\\Downloads\\chromedriver_win32\\chromedriver....
5e4bd1bd980012ffb6d7d9238347e54d84ece7b9
mdizhar3103/Python-Design-Patterns
/Strategy-Pattern/variations.py
862
4.15625
4
# Strategy Pattern Implementation from abc import ABCMeta, abstractmethod class Order(object): pass class ShippingCost(object): def __init__(self, strategy): self._strategy = strategy def shipping_cost(self, order): return self._strategy(order) # function strategy def fedex_strat...
208b540e92cadabbd589e861bbceb3848ff7bf77
rafaelperazzo/programacao-web
/moodledata/vpl_data/59/usersdata/231/31003/submittedfiles/testes.py
213
4
4
# -*- coding: utf-8 -*- v=int(input('digite um número qualquer :')) n=20 if v==n: print('acertou') elif v>n: print('valor é menor') elif v<n: print('valor é maior') else: print('fim de jogo')
d68d82a1fb0d1a1cac4d99baa788f0189980a7d8
ademaas/python-ex
/round3/power.py
703
4.1875
4
def main(): inp1 = input('Enter a positive integer to be tested:\n') number = int(inp1) if(number % 2 == 0): quetient = number/2 while(quetient!=0 or quetient!=1): if(quetient%2==0): number = quetient quetient = number/2 ...
fc737a0663d96ac2471c3292f2dbab37ae125963
JohnnyAIO/Python
/Elif.py
379
4
4
categoria = int(input("Ingrese la categoria: ")) if categoria == 1: precio = 10 elif categoria == 2: precio = 18 elif categoria == 3: precio = 23 elif categoria == 4: precio = 26 elif categoria == 5: precio = 31 else: print("Categoria invalida, digite un valor entre 1 y 5") prec...
5bc8ea611db2d688f6c9dfe11424308e51f09d57
az-ahmad/python
/projects/banks.py
7,034
4.28125
4
""" Start by creating a few 'bank accounts' following terminal instructions. These accounts will be stored in a new 'bankdata.txt' file. You can then check the accounts, deposit and withdraw. You can also check all the users of a bank and all the users of the specific branch too. """ class Bank: def __init__(sel...
a2273127be9edce49025bb29edd58b88b3c1b86f
AbdulShaq/Python
/VendingMachine/VendingMachine/vend.py
5,437
3.984375
4
"""A vending machine program that will read the products and keep count of credit and return change and product """ # MCS 260 Fall 2020 Project 2 # Abdul Shaqildi # Declaration: I, Abdul Shaqildi, am the sole author of this code, which # was developed in accordance with the rules in the course syllabus. import s...
ebaa9388dc4cfaaf8e5e70379fe8f973b85cfaa0
Vijay-Arulvalan/Codex
/Python/crash/person.py
357
3.96875
4
def build_person(first_name, last_name, age = ' '): #age is optional """Return a dictionary of information about the person""" person = {'first': first_name.title(), 'last': last_name.title(), 'age': int(age)} return person if age: person['age'] = age return person test = build_person('...
7b554d3d1a784aa74818f63e0594b1eec75a3c8d
mengyangbai/leetcode
/tree/recoverbinarysearchtree.py
628
3.609375
4
# Definition for a binary tree node class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def recoverTree(self, root): swap = [None, None] self.prev = TreeNode(float('-inf')) def dfs(node): if node: ...
60ec26676576bbd3ad3f1081110796e283b363c7
maolintuntun/AI-Robotic-arm-
/python practice/T66-三个数字按大小输出.py
318
4
4
# -*- coding: utf-8 -*- """ Created on Wed Sep 27 17:34:39 2017 @author: lenovo """ n1=int(input('n1=:\n')) n2=int(input('n2=:\n')) n3=int(input('n3=:\n')) def swap(p1,p2): if p2>p1: p1,p2=p2,p1 return p1,p2 n1,n2=swap(n1,n2) n1,n3=swap(n1,n3) n2,n3=swap(n2,n3) print(n1,n2,n3)
118d5b32f5b2fe91b394cbd6ab6f3df53ed941ba
pak21/aoc2018
/09/09-2.py
987
3.65625
4
#!/usr/bin/python3 import sys class Marble: def __init__(self, value): self.value = value self.prev = self.next = self def insertafter(self, after): after.prev = self after.next = self.next after.next.prev = after self.next = after def remove(self): ...
972258f67467fd76ffea463fb821338c1be74364
beczkowb/algorithms
/bit_manipulation/bit_parity.py
706
3.609375
4
import unittest def has_odd_parity(n): odd_parity = False while n: n &= (n-1) odd_parity = not odd_parity return odd_parity class HasOddParityTestCase(unittest.TestCase): def test(self): self.assertEqual(has_odd_parity(0b1100), False) self.assertEqual(has_odd_parity(0...
ab146224f8228fcb93e94d6bc9daa0f257a3d78a
sanjurosaves/holbertonschool-higher_level_programming
/0x04-python-more_data_structures/0-square_matrix_simple.py
131
3.546875
4
#!/usr/bin/python3 def square_matrix_simple(matrix=[]): squares = [[e ** 2 for e in row] for row in matrix] return squares
6f2d1aa97c9892f097af7d8ecca29ea9b08d0e4c
sergey-tovmasyan/Intro-to-Python
/Week-3/Practical/problem11.py
117
3.53125
4
set1 = {1,2,3,4,5} set2 = {4,5,6,7,8} print("Intersection:",set1.intersection(set2)) print("Union:",set1.union(set2))
eb4b2dece44a059716f5a6a45a1318a59ab29957
MONISHA68/PROJECT-
/create quiz game.py
5,768
3.9375
4
class quiz: def question1(self): print("You chose the hard difficulty") print("Where is the Great Victoria lake located?") answer1 = input("A) Canada B)West Africa C)Australia D)North America") score=0 if answer1 == "C": print("Correct") score = score+1 prin...
c637f56be82b2ea7ae71402556256a1fdc69328e
GuilhermeRamous/python-exercises
/fibbonnacci_recursive.py
219
3.53125
4
def fib(n, numeros=[0, 1]): if len(numeros) == n: return numeros else: soma = [numeros[len(numeros) - 1] + numeros[len(numeros) - 2]] return soma + fib(n, numeros + soma) print(fib(5))
3341d5ebdd7bf043bcf4ad45811ec2a90632a394
zak39/exercices-python
/bonnes-pratiques/script.py
1,454
3.765625
4
# -*- coding:utf-8 -*- import doctest, unittest def Somme(a,b): # Les trois guillemets permet de creer un DocString. # Un DocString permet de creer une documentation. """ Cette fonction permet de faire la somme de a et de b. >>> Somme(2,3) 5 """ res = a+b return res class MyTest(u...
724cff1498cfeae9d3e4f5ffe7712853d4748343
dsubhransu/pythonbeginner
/Day6_assignment/hierarchical_inheritance.py
1,519
4.03125
4
class Person: def get_details(self): self.firstname = str(input("first")) self.lastname = str(input("last")) self.age = int(input("age")) def show_person_detail(self): print("firstname:", self.name) print("lastname:", self.lastname) print("age:", self.age) clas...
530a49288974021e8b4bb4772688fce21c79b3db
dyfloveslife/SolveRealProblemsWithPython
/Practice/House.py
1,446
3.78125
4
class Home: def __init__(self, new_area, new_style, new_addr): self.area = new_area self.style = new_style self.addr = new_addr self.left_area = new_area self.contain_items = [] def __str__(self): message = '房子的面积是%d,可用面积是%d,户型是%s,地址是%s' % (self.area, self.left_a...
45cb8ce7a1c5224d8a9f487683cb14f841ef78c7
Yaachaka/pyPractice1
/bhch06/bhch06exrc02.py
353
4.28125
4
""" bhch06exrc02.py: A simple way to estimate the number of words in a string is to count the number of spaces in the string. Write a program that asks the user for a string and returns an estimate of how many words are in the string. """ string = input('Enter a string:') count = string.count(' ') + 1 print('Total nu...
7cf74c8d3875f07e0a85b090917e4d181e37a46e
TingtingHu33/python_libraries
/pandas/DataFrame.py
1,567
3.671875
4
#!/usr/bin/env Python #-*- coding: utf-8 -*- #--Python_Version:2.7.10 ''' DataFrame是一个表格型数据结构,含有一组有序的列,可以看做由Series组成的字典 构建DataFrame的方法有很多,最常用的是直接传入一个由等长列表或NumPy数组组成的字典 ''' __author__ = 'AJ Kipper' from pandas import Series,DataFrame import pandas as pd import numpy as np data = {'name':['Cat','Dog','Bug'], ...
c038aeea58af447662f9ad545af895de499adc9a
Nityam79/pythonPractice
/prac6/numtopan.py
207
3.53125
4
import numpy as np my_list = [11, 12, 13, 14, 15, 16, 17, 18] print("List to array: ") print(np.asarray(my_list)) my_tuple = ([18, 14, 16], [11, 12, 13]) print("Tuple to array: ") print(np.asarray(my_tuple))
f7af4b1d7f3f63e2c3a2415cc1514ac53fd6d028
supermitch/python-sandbox
/random/sum_diagonal.py
959
4.34375
4
""" Given a square matrix of size , calculate the absolute difference between the sums of its diagonals. Input Format The first line contains a single integer, . The next lines denote the matrix's rows, with each line containing space-separated integers describing the columns. Output Format Print the absolute diff...
54990a595247a933f11ecc786b689c5d0389ef6a
kellibudd/code-challenges
/removefromll.py
1,323
4
4
# Singly-linked lists are already defined with this interface: # class ListNode(object): # def __init__(self, x): # self.value = x # self.next = None # def removeKFromList(l, k): """ Source: https://app.codesignal.com/interview-practice/task/gX7NXPBrYThXZuanm Given a singly linked list of integer...
5298dcfbb55b6540f946132cd0e208afa49d0ebd
etwum/Python-Portfolio
/Intro_to_Python/Module 08/module 08 practice.py
4,994
4.09375
4
# -*- coding: utf-8 -*- """ Created on Mon Nov 13 16:49:52 2017 @author: Emmanuel """ #***********************Classes #Example 1 class Customer(object): id = None #Data in a class is definedd as variables (called Fields) Name = None def ToString(self): return str(self.id)...
9cf0ee4c89e5212a2f9b7f7c6918224c51841f2c
korcsmarosgroup/iSNP
/analytic-modules/text-iterator/text_iterator.py
2,852
3.578125
4
import argparse import os.path import sys class TextIterator: def __init__(self, input_file, output_folder): self.input_file = input_file self.output_folder = output_folder def check_params(self): if not os.path.isfile(self.input_file): print("ERROR! the specified input f...
8c3bde21e21a6a911700ed40d06ab82cdbb66b39
CuteSmartTiger/basic_python
/operate_dict/dict_search.py
277
3.65625
4
# 方法1 person = {'name':'liuhu','age':18} dic = {'e': 7,'a': 1, 'd': 4, 's': 5} print(person['name']) # 方法2 res = person.get('name','mei') print(res) res = person.get('nam','mei') print(res) # 方法三: res = person.setdefault('na1','def') print(res) print(person)
3366d0b13061d8b829d946e71079a810db9eff76
yunzhuz/code-offer
/37.py
1,012
3.734375
4
class treenode: def __init__(self,data,left=None,right=None): self.data = data self.left = left self.right = right def xuliehua(node,l): if not node: l.append('$') return else: l.append(node.data) xuliehua(node.left,l) xuliehua(node.right,l) ...
16055f6e3feb791ce2eda84215cc9a6752003b70
panchaly75/MyCaptainPythonProjects
/Assignment_1.3.py
2,053
4.15625
4
#Q3_Create a Calculator. opt = 1 #for each operation define a function def addition(a, b): return a+b def subtract(a, b): return a-b def multiply(a, b): return a*b def divide(a, b): return a/b def pwr(a, b): return a**b d...
6edc5faaed64a3a53991108f76dd0e13f641677c
kantal/WPC
/ISSUE-5/SOLUTION-2/buffon.py
1,390
3.84375
4
# ---buffon.py --- Sebastian Plamauer --- # This program calculates Pi using the solution of Buffons needle problem. import random import math #Output Info print 'This program calculates Pi using the solution of Buffons needle problem. You will have to enter the length of the needle, the width of the stripes and the ...
ff45cc17bce3c3880ec8757d67026fd0f8cf6a80
Anna123097/Pyton-Learning
/4.kp/Untitled-1.py
175
3.609375
4
""" ?Найти все делители числа n и вывести их на экран. """ n=int(input("n= ")) for i in range(1,n+1): if(n%i==0): print(i)
b787e6cf9389721f4cd45b1ad2bc9ef4414770d8
dliuzhong/learning_git
/python/py/array2str.py
258
3.890625
4
def array2str(array): str = '' for i in range(len(array)): if i == (len(array) - 1): str += 'and ' + array[i] else: str += array[i] + ', ' return str print(array2str(['apple', 'bananas', 'tofu', 'cats']))
97762fcae98644bc27dc6cd1f755c6e3aae56935
django/django
/tests/model_inheritance/models.py
4,829
3.765625
4
""" XX. Model inheritance Model inheritance exists in two varieties: - abstract base classes which are a way of specifying common information inherited by the subclasses. They don't exist as a separate model. - non-abstract base classes (the default), which are models in their own right with ...
5f7bb1ee4e4d959cfd11333bddfd09f8a1cb4e3c
leowebbhk/objectOrientedTicTacToe
/board.py
2,860
3.78125
4
class Board: #object which houses the playing field def __init__(self, width, height): self.width = max((width, height)) self.height = min((width, height)) self.cells = [[0 for cell in range(self.width)] for row in range(self.height)] #the cells of the tic tac toe board self.winner =...
b66be199cffd69730d158bc6e618daa662a8b847
jarvis-1805/DSAwithPYTHON
/Conditionals and Loops/Sum_of_Even_Numbers.py
384
4.34375
4
''' Sum of Even Numbers Given a number N, print sum of all even numbers from 1 to N. Input Format : Integer N Output Format : Required Sum Sample Input 1 : 6 Sample Output 1 : 12 ''' ## Read input as specified in the question. ## Print output as specified in the question. n = int(input()) i = 1 sum = 0 while i<=...
f37b0e098d2bdac042e1185de377f05d6170148e
djanshuman/Algorithms-Data-Structures
/Python/DataStructures_Implementation/MaxHeap.py
2,524
3.8125
4
''' Created on 09-May-2021 @author: dibyajyoti ''' import sys class MaxHeap: def __init__(self,maxsize): self.maxsize=maxsize self.size = 0 self.heap=[0]*(self.maxsize+1) self.heap[0]=sys.maxsize self.front=1 def insert(self,element): if(self.size >= self.m...
16d88ff074d7729eee6c9742129b155368641e9d
mddeloarhosen68/Object-Oriented-Programming
/Abstract Class & Abstract Method.py
272
3.640625
4
from abc import ABC, abstractmethod class Computer(ABC): @abstractmethod def process(self): pass class Laptop(Computer): def process(self): print("It's Running") #com = Computer() com1 = Laptop() #com.process() com1.process()
c9ccba66bd7e3747b7d904891072f6c0f6c0594d
ricardodong/cmput-663-project
/manual create data/dictionaryCreator.py
1,195
3.5625
4
def inDict(dict, key): try: a = dict[key] except KeyError: return False, 0 else: return True, a if __name__ == '__main__': words = open("wordData.txt",'r', encoding='utf-8') wordsTrainSet = open("wordsTrainSet.txt",'w', encoding='utf-8') wordsTestSet = open("w...
7eb3eb45ab44506d6c61a272658c6963e39f8d7e
gabriellaec/desoft-analise-exercicios
/backup/user_305/ch27_2019_04_04_18_32_31_785347.py
126
3.59375
4
a=int(input('quantos cigarros voce fuma for dia?')) b=int(input('ha quanto anos fuma?')) y = a*10 z = y * 365*b/1440 print (z)
6d50c503e13cce8b70b514863ccedc8d070e259a
kondraschovAV1999/TAU.LAB1
/test27.py
296
3.53125
4
inFile = open('input.txt') wordDict = {} for line in inFile: words = line.split() for word in words: wordDict[word] = wordDict.get(word, 0) - 1 # for i in wordDict.items(): # print(i[::-1]) answer = sorted([i[::-1] for i in wordDict.items()]) for i in answer: print(i[1])
c72c32bb67802045fea916f29c979b883d2a28e5
Mariamjaludi/algorithms-practice
/python/populateSuffixTrie.py
762
3.75
4
class SuffixTrie: def __init__(self, string): self.root = {} self.endSymbol = "*" self.populateSuffixTrie(string) def populateSuffixTrie(self, string): for i in range(len(string)): self.insertSubstringStartingAt(i, string) def insertSubstringStartingAt(self, i, ...
9615f5fa9074792390d67ac1de0a239922fc5dc4
tainanboy/leetcode
/53_MaximumSubarray/sol.py
400
3.9375
4
import math def maxSubArray(nums): """ :type nums: List[int] :rtype: int """ maxList = nums[:] for i in range(1,len(nums)): if maxList[i-1]+nums[i] > nums[i]: maxList[i] = maxList[i-1]+nums[i] print(maxList) print(nums) return max(maxList) nums = [-2,1,-3,4,-1,2...
04635a2a652012bbf1b2dd3528cb8f7d0ce0f786
jdarangop/holbertonschool-machine_learning
/supervised_learning/0x05-regularization/0-l2_reg_cost.py
697
3.84375
4
#!/usr/bin/env python3 """ L2 Regularization Cost """ import numpy as np def l2_reg_cost(cost, lambtha, weights, L, m): """ calculates the cost of a neural network with L2 regularization cost: (numpy.ndarray) the cost without regularization. lambtha: (float) regularization parameter. weigh...
577cdca8b5375f4dd13424f7cb80312450d984e2
noahj08/rlcard
/rlcard/games/nolimitholdem/round.py
4,759
3.796875
4
# -*- coding: utf-8 -*- ''' Implement Limit Texas Hold'em Round class ''' from rlcard.games.limitholdem.round import LimitholdemRound class NolimitholdemRound(LimitholdemRound): ''' Round can call other Classes' functions to keep the game running ''' def __init__(self, num_players, init_raise_amount): ...
2d5e49899bae0c113a6c8193bd56a4c4b6418b3a
thaleaschlender/GAME_AI
/Coin.py
4,130
3.640625
4
import random import pygame # Color of the coin (YELLOW) COIN_COLOR = (255,255,0) class VirtualCoin(pygame.sprite.Sprite): """Virtual parent class of coin that has all the same variables and functions except anything required with drawing to screen.""" def __init__(self, DISPLAYSURF, speed, width, height...
1688931574417255c939b02be04bd2d14818dcda
Balaji-Ganesh/Furnishing-OpenCV-Basics
/Grounding_roots_of_core/Operations on mixing, adding images.py
666
3.515625
4
import cv2 # Importing two images img1 = cv2.imread('messi5.jpg', 1) img2 = cv2.imread('opencv-logo.png', 1) # Resizing images so as to avoid RED colored Greeting After executing... img1 = cv2.resize(img1, (500, 600)) img2 = cv2.resize(img2, (500, 600)) # Merging two images, NOTE: To merge two images both of...
9f5957a7bf61130b6987702576f496d95412ddb7
marvincosmo/Python-Curso-em-Video
/ex023 - Separando dígitos de um número.py
432
3.828125
4
""" 23 - Faça um programa que leia um número de 0 a 9999 e mostre na tela cada um dos dígitos separados. """ from time import sleep n = int(input('Informe um número: ')) print(f'Analisando o número {n}...') sleep(2) u = n // 1 % 10 # u = n % 10 (esta forma é mais econômica, mas a outra é mais didática) d = n // 10 % ...
56ac90bb3c9c3171a578ec3aa0f29ac836461315
vidyabhandary/algorithms
/src/vendingmachine.py
1,450
4.28125
4
''' A vending machine has the following denominations: 1c, 5c, 10c, 25c, 50c, and $1. Your task is to write a program that will be used in a vending machine to return change. Assume that the vending machine will always want to return the least number of coins or notes. Devise a function getChange(M, P) where M is how m...
2363bac7e111ec7a5bcbed14d70cfbe7a963f1cd
MatrixManAtYrService/MathScripts
/listTopologies.py
4,042
3.75
4
# https://github.com/MatrixManAtYrService/MathScripts/blob/master/listTopologies.py # Consider the discrete topology on X # X_Discrete = { {} {a} {b} {c} {a,b} {a,c} {b,c} {a,b,c} } # Let the set Y contain all nontrivial elements of X_discrete # Y = { {a} {b} {c} {a,b} {a,c} {b,c} } # Notice that for any subset Z of...
fb6e40198a90315f178625254ae60a66d9afa97a
emacenulty/py-121-code
/code-snippets/count_most_common_letter_in_text_solution.py
2,029
4.0625
4
import string from operator import itemgetter #use a dictionary to count the most common letter in the text text=""" Computer programming is the process of designing and building an executable computer program to accomplish a specific computing result or to perform a specific task. Programming involves tasks such as:...
b98b3620ac9d8c9be34f59bc55d4956df064449b
mjayfinley/python-practice
/algorithms/pyramid.py
612
4.4375
4
userInput = int(input("Enter the number of rows: ")) row = 0 #outer loop for number of rows and number of spaces while(row < userInput): row += 1 spaces = userInput - row #inner loop to print a space while space counter is less than number #of spaces, for both side of pyramid? spaces_counter = 0 ...
3254930c4b31d1056df3dec3250a908535c15b49
k-harada/AtCoder
/ABC/ABC201-250/ABC216/C.py
350
3.5625
4
def solve(n): res = ["A"] for c in bin(n)[3:]: res.append("B") if c == '1': res.append("A") return "".join(res) def main(): n = int(input()) res = solve(n) print(res) def test(): assert solve(5) == "ABBA" assert solve(14) == "ABABAB" if __name__ == "__m...
fb351c69957e5422d8579e25cade8ad23cdf7874
AbdullBIDB/python-challenge
/PyBank/main.py
1,809
3.6875
4
import os import csv import statistics as s data_csv = os.path.join ("Resources", "budget_data.csv") #determine the list of date = [] pl = [] #read the file with open(data_csv, newline="") as csvfile: csvreader = csv.reader(csvfile, delimiter=",") csv_header = next(csvfile) #insert the column into the li...
910f29ed66f868de9692e4530113752112cfbd90
raahim007/string-manipulation-AS
/String Validation/string validation.py
564
4
4
Format = True String1 = input("Enter the string \'aaaa-999-AAA\' : ") if len(String1) != 12: Format = False if Format: if String1[4:5] != "-" or String1[8:9] != "-": Format = False if Format: for pos in range(4): chr1 = String1[pos:pos+1] if chr1 < "a" or chr1 > "z": ...
e4c33984a7e67fc74f105245006d8f7f9b18fb43
supreme-gentleman/udacityProgrammingFoundationsPython
/07-MakeClasses-AdvancedTopics/inheritance.py
1,246
4.5
4
# -*- coding: utf-8 -*- class Parent(): def __init__(self, last_name, eye_color): print("Parent constructor called!") self.last_name = last_name self.eye_color = eye_color def show_info(self): print("Last Name - " + self.last_name) print("Eye Color - " + self.eye_color) # Definir una clase Child que hered...
69f5c132572ec6b683ad4c5f473b56be533bf750
Dhanya-bhat/MachineLearning_Programs
/3-9-2020/CountNoOfEle-p3.py
313
4.25
4
3.Write a Python program to count the number of elements in a list within a specified range. def count_range_in_list(li, min, max): ctr = 0 for x in li: if min <= x <= max: ctr += 1 return ctr print("the count is :") list1 = [10,20,30,40,40,40,70,80,90] print(count_range_in_list(list1, 10, 80))
63c47566743f1075b6cd57d686b5395b6a8a58e3
realme1st/algorithm_Theory
/insertion_sort.py
369
3.796875
4
def insertion_sort(data): for index in range(len(data)-1): for index2 in range(index+1,0,-1): if data[index2]< data[index2-1]: data[index2],data[index2-1] = data[index2-1],data[index2] else: break return data import random data_list = random.sampl...
358751e4f2de353830cfbe2df1774d7afb4cb01b
bsilver8192/SHRC-Arm
/shrc/control_loops/python/util.py
1,834
3.671875
4
from __future__ import print_function import sympy import sympy.core.cache @sympy.cache.cacheit def dcm_to_quaternion(dcm): """Converts a Direction Cosine Matrix to a Quaternion. Args: dcm: A 3x3 sympy.matrices.Matrix representing the DCM. Returns: A 4-tuple representing the 4 elements of the quaterni...
1a213a7523dd9c7847a18c73ddf720b2e4a7c862
maksympc/pythontutorial
/datacapm/1 Intro to Python for Data Science/chapter 3/sc2.py
406
4.4375
4
# chapter 3 # Import package # Definition of radius r = 0.43 # Import the math package import math from math import radians # Calculate C C = 2*math.pi*r Crad = radians(360)*r # Calculate A A = math.pi*r**2 Arad = radians(180)*r**2 # Build printout print("Circumference: " + str(C)) print("Circumference using radia...
c4766e74c819cc7c9aeea5443fecee0dd97e9820
jagtapshubham/Python
/Dictionary/SumAllValuesInDict.py
300
4
4
# Problem: Sum all the Dictionary values #!/usr/bin/python3 def main(): dict1={1:100,2:300,3:50} #Solution 1 dictsum=0 for x,y in dict1.items(): dictsum=dictsum+y print(dictsum) #Solution 2 print(sum(dict1.values())) if __name__=='__main__': main()
4fe850ac3db843fd23fd61cbfd4c5d50f5bb839b
MeetLuck/works
/diveintopython/UnitTest/division_tutorial.py
1,276
4.09375
4
''' divmod(x,y) -> (quotient, remainder) return the tuple ( (x-x%y)/y, x%y ) div,mod = divmod(x,y), div*y + mod == x ''' def divmod2(x,y): ''' using ONLY add, substract q = 0 while x >= y: x -= y q += 1 return q,x ''' quotient = 0 remainder = x while remainder...
b2c36ab1542a55c1a93a0b2532acccdad6663051
Zeqiang-Lai/KE103
/sequence-labeling/sequence-labeling-pytorch/model/net.py
8,249
4
4
"""Defines the neural network, losss function and metrics""" import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from seqeval.metrics import f1_score class Net(nn.Module): """ This is the standard way to define your own network in PyTorch. You typically choose the components...
43c1cb06aecbb4910ed0f3e8187e5828f4a596dd
rheehot/Development
/하루에 한개씩 문제 풀기/Python/Programmers/모든 문제/Level 1/make_sosu.py
393
3.640625
4
# programmers, phase1 : 소수 만들기, python3 from itertools import combinations def check_sosu(n): if n != 1: for i in range(2, n): if n % i == 0: return False else: return False return True def solution(numbers): result = [sum(i) for i in list(combinations(nu...
71fe5258486ce6d2604c8065e563899e7ad9a8b3
vandebettio/desenvolvimentopython-exercicios
/py002.py
269
4.1875
4
# aprendendo os comando input e format nome = input('Digite seu nome: ') print('Seja bem vindo, {}!'.format(nome)) print('Qual a sua idade?') idade=input('Digite sua idade: ') print(format(nome)+' você esta em plena forma com seus {}'.format(idade)+' anos de idade.')
c15e21daebe5a5647d8ce92ed25bb3037687db92
meetashok/cs50
/pset7/houses/roster.py
664
3.8125
4
from sys import argv, exit import csv import cs50 # ensure that user has provided a house as command line argument if len(argv) != 2: print("Usage: python import.py <house>") exit(1) # initialize db db = cs50.SQL("sqlite:///students.db") # select relevant data based on house data = db.execute("SELECT fir...
cb518ec514400d570c6f5b4ef6f3a429f857e87b
anisha1208/Algopylib
/src/Algopylib/puzzle/sudoku.py
3,051
4.25
4
from typing import List, Tuple, Union def create_board() -> List[List[int]]: """Creates a board for sudoku Returns: a(List[List[int]]) : List of List that represents a sudoku board """ a : List = [] for i in range(9): b : List[int] = [int(x) for x in ...
8e64baa81ba42eb10f5d9bb5d527dd474f120cbb
soothingjennyg/cs350
/project/reverse.py
512
4.21875
4
#!/usr/bin/python # # This program generates a list of random numbers # # Usage: ./numgen.py <range> [<repeats>] # where 'range' is the range of numbers to use in the array (ex: 1-101) # and repeats is the number of times to repeat the numbers # # For example ./numgen.py 4 2 will output a shuffled list of: [1, 2, 3, 1,...
8c9bcc7710fe253d99c831fc530ea96d9032b0a8
alexaoh/pastime
/python/os_script.py
759
3.984375
4
#Prints out all filenames in your root path import os #Solution #1 def list_all_files_recursively(root): paths = os.listdir(root) for path_name in paths: if os.path.isfile(root+path_name): print(path_name) elif os.path.isdir(root+path_name): list_all_files(root+path_name...
7b37d8888ecdc5d022d67705b90eb25bb2528ae6
hakanozbek64/VeriGorsellestirme_Matplotlib
/Figureler Subplotlar ve Axeslar _ Figure Özelleştirme_grafik özelleştirme/graph.py
419
3.734375
4
import matplotlib.pyplot as plt import numpy as np x = np.arange(1,6) y = np.arange(1,11,2) fig = plt.figure() axes1 = fig.add_axes([0.1,0.1,0.8,0.8]) axes2 = fig.add_axes([0.2,0.5,0.2,0.3]) axes1.plot(y,x) axes1.set_xlabel("Outer X") axes1.set_ylabel("Outer Y") axes1.set_title("Outher Graph") axes2.plot(x,y) ax...
af971e5a0e18bb2368d3fab7533896a680694158
Tmk10/exercism.io
/prime-factors/prime_factors.py
293
3.734375
4
def prime_factors(natural_number): result =[] divider =2 while natural_number > 1: if divmod(natural_number, divider)[1] == 0: result.append(divider) natural_number = natural_number // divider else: divider +=1 return result
57ba29067d065cf5b4f5faa1a2ac1ce5e4018246
Roninho514/Treinamento-Python
/ex054.py
416
3.984375
4
from datetime import date AnoAtual = date.today().year MaiorIdade = 0 MenorIdade = 0 for c in range(1,8): pessoa = int(input('Digite o ano que a {}ª pessoa nasceu:'.format(c))) if AnoAtual - pessoa >= 18: MaiorIdade += 1 else: MenorIdade += 1 print('Ao todo tivemos {} pessoas maiores de ida...
85aeef3b8c0cadc7fc754005948d184ecea959fb
teodorstrut/PSO-Disjoint-Subsets
/Main.py
357
3.703125
4
from Iteration import Iteration class Main: def __init__(self, iterations): self._iterations = iterations self._iter = Iteration() def main(self): for i in range(self._iterations): self._iter.run() for i in self._iter.getSwarm(): print(i.fitness(), i.po...
7ec0eeeb1689e6c1974a8fd9ec3b57dba7bc681f
mrusinowski/pp1
/09-DefensiveProgramming/z7.py
254
3.625
4
wzrost = int(input('Wprowadź wartość wyrażona w cm: ')) waga = float(input('Wprowadź wartość wyrażona w kg: ')) assert type(wzrost)==int and 150<=wzrost<=220 and type(waga)==float and 40.0<=waga<=150.0 print(f'BMI wynosi: {waga/(wzrost/100)**2}')
6e05098ed00c9e35fa58a5fbd18726eb7d3ae71a
LuciaIng/TIC_20_21
/contraseña_2.py
322
4.03125
4
'''Introduce un nombre y un apellido. Genera una contrasena a partir de 3 letras del nombre y tres del apellido.''' def contrasena_2(): nombre=raw_input("Nombre: ") apellido=raw_input("Apellido: ") contrasena=nombre[-3:]+apellido[-3:] print("Contrasena: ",contrasena) contrasena_2() ...
473626f2fa00ef96e36fcf273315e828a3bc2523
nicolas4d/Problem-Solving-with-Algorithms-and-Data-Structures-using-Python
/code/palindrome.py
966
3.796875
4
def reverseStr(str): if len(str) <= 1 : return str else : return reverseStr(str[1:]) + str[0] def removeSpaceAndPunctuation(str): i = 0 strLen = len(str) punSym = [" ", ",", ';', "'", '.', '’', '-'] while i < strLen: if str[i] in punSym : str = str[0:i] + st...
97c547c919d05e35774597b9df8eae8e2932636a
chandler-shepard/github-portfolio
/Python/Banquet_donations/Banquet_donations.py
3,429
3.9375
4
# Make sure you have also downloaded donation.py and have it saved in the # same location as Banquet_donations.py import donation amount = donation.get_donation() # this will make the 200 donations then it will sort the number also in order # from least to greatest. def get_donations(num): total = [] for i in ...
48f62eb86528107202a3294d93344f259d8bf497
solouniverse/Python
/DS/LinkedList/Prog_ReverseList.py
1,818
4.15625
4
import Prog_LinkedListUtil as util class Node: def __init__(self, value): self.value = value self.next = None class LinkedList: def __init__(self): self.head = None def push(self, value): newNode = Node(value) newNode.next = self.head self.head = newNode ...