blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
664faab7305013a9058641f1d2868d5aa64d0446
1666202295/test
/knowledge/python_set.py
1,603
4.09375
4
# 集合 items = {"arrow", "spear", "arrow", "arrow"} # 集合会自动去重 print(items) # 集合中是否包含某值 if "rock" in items: print("rock exist") else: print("not found") # 集合的声明 pets = set() # 参数的添加 pets.add("cat") pets.add("dog") pets.add("pig") print(pets) # 参数的删除 pets.discard("cat") pets.discard("tiger") # 删除不存在的参数时不会报错 pri...
23574145c715b88c7a444565800447d08e4d0806
alisa-fh/GitHub-network-analysis
/modules/data_process.py
2,703
3.6875
4
import pandas as pd import requests import json import networkx as nx import os from modules import config from modules import plotting def github_request_by_url(url): ''' This function allows any request using any url. Common endpoints for this project: "https://api.github.com/users/" "https://api....
cc6ed7f80e8f44e3eeab779c5b85bd6141d742f1
Nik-Kaz/domaci_predavanje5
/zadatak3_strana4.py
301
3.578125
4
""" Date su stranice a i b pravougaonika. Naći njegov obim i površinu. """ a = int(input("Unesite stranicu a pravougaonika: ")) b = int(input("Unesite stranicu b pravougaonika: ")) povrsina = a * b obim = (2*a) + (2*b) print(f"Povrisna pravougaonika je {povrsina}, a obim je {obim}")
2f3a355d49a672ada5ccfca1584a30ee0883cc24
denisvieriu/Python-problems
/1/prob3.py
579
3.953125
4
''' Created on Mar 3, 2017 @author: Denis ''' ''' Find two coprime integers in the range 1e50..1e51. ''' import random def gcd(x, y): ''' GCD using Euclidean algorithm Input : x,y - 2 integers Output : gcd(x, y) ''' c = 1 while c: c = x % y x = y y = c retu...
89e24a8fe9b6322d703b8f15ff5069c059f3b8c8
denisvieriu/Python-problems
/1/prob7.py
1,076
4.1875
4
''' Created on Mar 3, 2017 @author: Denis ''' ''' Check the minimum security requirements of a password (at least one digit, one symbol, one lower, one upper, length 12..14). ''' def read_user_command(): return input("Enter the password : ") def check_pass(passw): ''' Checks the strength of a passwo...
9ce7541af45f36d617d7efaf6c0ea5b24a50b4bb
delpinolisette/Graphs
/krusals.py
669
3.8125
4
# krusals.py # this is my implementation of Krusal's Greedy Algorithm # to find a minimal spanning tree # source : https://www.geeksforgeeks.org/kruskals-minimum-spanning-tree-algorithm-greedy-algo-2/ from collections import defaultdict #build the graph class , the grpah object with its methods class Graph #c...
f7ad645af209d58994eda7484368027f5a518f71
andrewvue/PythonATM
/ATMScript.py
2,527
4.1875
4
''' Andrew Vue SNHU IT140 20EW3 ATM Script ''' import sys #account balance account_balance = float(500.25) #<--------functions go here--------------------> #printbalance function def balance(): global account_balance print("Your current balance: \n" + str(account_balance)) return account_b...
0edfad8cc9e27de09d0ccac2e599bf6372c55f0c
Kvn12/MC102
/Lab8-refatorado.py
6,672
4.21875
4
def variavel(expressao): '''Recebe uma lista cujos itens sao termos de uma expressao e verifica se e uma expressao de atribuicao de variavel. Parametros: expressao --- lista a ser avaliada ''' if not expressao[0].isdigit() and expressao[1] == '=': return True else: return Fal...
475417c5fbb2f0fd796a851a784942f9406a6718
mlrcbsousa/pirple
/python-is-easy/if_statements.py
460
4.15625
4
""" Third Homework Assignment for the Pirple course Python is Easy - If statements """ def conditional(a, b, c): a = int(a) b = int(b) c = int(c) # This condition is overridden by the one after # if (a == b) and (b == c): # return True if (a == b) or (a == c) or (b == c): return True elif (...
94ace902d934bfab81e2d8c9b9b051053a4a5f68
JackUnderwood/vista-test
/sandbox/splitter.py
846
3.875
4
__author__ = 'John Underwood' def split(line, types=None, delimiter=None): """ :param line: string of delimited text :param types: list of data types, e.g. [str, int, float] :param delimiter: default splits all white space :return: list This split alters the traditional split by converting a s...
4588ffc6fd053cf0a1261e36fe73712107fd6d6c
Anjalkhadka/datatypelab
/tuple/qn7.py
181
4
4
'''Write a Python program to get the 4th element and 4th element from last of a tuple.''' tuple=(1,2,'n','h',5,6,8,9,'l','k') tf=tuple[3] print(tf) #FROM LAST tl=tuple[-4] print(tl)
110f3c02ccd19043b45ef7a2aee489461aa64dd7
Anjalkhadka/datatypelab
/set/qn5.py
150
4.09375
4
'''Write a Python program to remove an item from a set if it is present in the set.''' s5={1,2,3,'Nepal','India','China'} s5.remove('India') print(s5)
84126aa7e01dc634405357db74296ecc20a1c87e
verilogtester/pyalgo_love
/build_BST_from_Array.py
1,731
3.921875
4
""" Given a sorted array, convert an array into BST""" class Node: def __init__(self, data): self.data = data # Root Node self.left = None # Left Child self.right = None # Right Child # set data def setData(self, data): self.data = data # get data ...
e283ba98927c4ba96e63808cbb64368cf2ce3f29
verilogtester/pyalgo_love
/binary_search_algorithm.py
662
3.75
4
class binaryS(object): def binarysearch(self, dataset, item): datasize = len(dataset) loweridx = 0 upperidx = datasize while loweridx < upperidx: mididx = (loweridx + upperidx) // 2 if dataset[mididx] == item: return item if item >...
3aa7612e4d7cf43c80bd993d291a00589113ee58
verilogtester/pyalgo_love
/Target_sum_problem_using_recursion.py
992
3.984375
4
# Recursive Pattern for finding subset for the Target sum in a list. """ input is a list i.e. [3,5,7,8,9] output : [[5, 7], [3, 9]] Assumptions: Patten is to have two branches and pass one element as height goes up ROOT ...
a895b5550b222005c68e94a70e2b5362ef7a66c4
pothireddysusmitha/Inbspace-15thmay-B1-IOT
/tuple dict.py
211
4.03125
4
a = int(input("enter data for a:")) b = int(input("enter data for b:")) dictionary = {a,b} print("dictionary:"dictionary) Tuple =[a] Tuple.append(b) print("Tuple:"Tuple) List = (a,b) print("List:"List)
6b1899cd8fd1f3f8b35b9f6e2dfaef0358c54028
gopinathrajamanickam/PythonDS
/Stack.py
790
4.03125
4
# Implment a Stack in Python # The default data structure list can be used as Stack # A Stack data structure implements LIFO # Key functions # getSize() # isEmpty() # push() # pop() # peek() # __str__() class Stack: def __init__(self): self.stack = [] def getSize(self): return len(self...
2af7266f7f55b4e27341e72d290ca06cd941dc13
dickrsunny/data-structure-and-algorithm
/排序/计数排序.py
491
3.5625
4
class CountingSort: def countingSort(self, A, n): # write code here _max, _min = max(A), min(A) site = [0] * (_max - _min + 1) sorted_A = [0 for _ in range(n)] for i in A: site[i - _min] += 1 k = 0 for j in range(_max - _min + 1): for _...
9ce79b65f41e8af7c7ba3598f91bc45fdfc9945d
dickrsunny/data-structure-and-algorithm
/算法题/数组中第k小的数.py
1,638
3.578125
4
#coding: utf-8 """ 解题思路: 类快速排序算法: 随机选择一个元素作为枢纽元,然后将数组分为左右两部分, 根据左右两部分的大小来决定递归的区间,平均时间复杂度为O(N), 但是最坏时间还是O(N^2)。这里跟快速排序有所不同,快速排序平均时间复杂度为O(NlgN), 因为它需要递归调用两个部分,而寻找第K小的元素只需要考虑其中的一半 """ class Solution(object): def find_kth_min(self, list_, k): if not list_: return length = len(list_) ...
3b31deb8e9a13dbe6c926d1b1b78986d5fbd3417
dickrsunny/data-structure-and-algorithm
/算法题/和为S的两个数字.py
883
3.796875
4
# coding: utf-8 """ (尼玛,被题目唬住了-_-!) 题目描述: 输入一个递增排序的数组和一个数字S, 在数组中查找两个数,是的他们的和正好是S, 如果有多对数字的和等于S,输出两个数的乘积最小的。 输出描述: 对应每个测试案例,输出两个数,小的先输出。 """ class Solution(object): def FindNumbersWithSum(self, array, tsum): # write code here if not array or tsum <= array[0]: return [] low...
27d2f7ce464a62c08cf9b68ab27bfb0164529694
dickrsunny/data-structure-and-algorithm
/算法题/Josephus.py
2,755
3.625
4
#coding:utf-8 """ 假设有n个人围坐一圈,现在从第k个人开始报数,报道第m个人退出, 然后从下一个人开始继续报道并按同样规则退出,直到所有人退出, 请按顺序输出各出列人的编号 """ def josephus_based_list(n, k, m): _list = list(range(1, n + 1)) i = k - 1 for _ in range(n): # num from 0 to n - 1 count = 0 while count < m: if _list[i] > 0: ...
4eb7bd5c31f443845a3a445a8b3625668c7e3a61
dickrsunny/data-structure-and-algorithm
/排序/有序矩阵查找.py
394
3.546875
4
class Finder: def findX(self, mat, n, m, x): # write code here i = 0 # j = m - 1 while i < n and j >= 0: if mat[i][j] == x: return True elif mat[i][j] < x: i += 1 else: j -= 1 return False ...
2352c1630f9d026180e450dde58407a67a18bd93
dickrsunny/data-structure-and-algorithm
/算法题/最长无重复子串.py
1,383
3.890625
4
# coding: utf-8 """ Complexity Analysis Time complexity : O(n). Index j will iterate n times. Space complexity : O(m). m is the size of the dict. 详细解释参考:https://leetcode.com/problems/longest-substring-without-repeating-characters/solution/ """ """ Given a string, find the length of the longest substring without re...
615427ad1c95cd2d905f1116def994da45cea06d
dickrsunny/data-structure-and-algorithm
/算法题/二分查找变形问题.py
1,672
3.671875
4
# coding: utf-8 # 变体一:查找第一个值等于给定值的元素(变体三的特殊情况) def bsearch(a, n, value): if not a: return -1 low = 0 high = n - 1 while low <= high: mid = low + ((high - low) >> 1) if a[mid] >= value: high = mid - 1 else: low = mid + 1 if low < n and a[lo...
0e36530c30b907e3d9acad0af3b964993c33b0d5
dickrsunny/data-structure-and-algorithm
/算法题/二叉树的镜像.py
2,460
3.609375
4
#coding: utf-8 """ 操作给定的二叉树,将其变换为源二叉树的镜像: 二叉树的镜像定义: 源二叉树 8 / \ 6 10 / \ / \ 5 7 9 11 镜像二叉树 8 / \ 10 6 / \ / \ 11 9 7 5 """ # -*- coding:utf-8 -*- # class TreeNode: # def __init__(self, x): # self.val = x # ...
6bf8e514ef0d9f00d37369587d3f822fda1e760f
dickrsunny/data-structure-and-algorithm
/算法题/把数组排成最小的数.py
887
3.953125
4
# coding: utf-8 """ 输入一个正整数数组,把数组里所有数字拼接起来排成一个数, 打印能拼接出的所有数字中最小的一个。例如输入数组{3,32,321}, 则打印出这三个数字能排成的最小数字为321323。 """ class Solution(object): def PrintMinNumber(self, numbers): # write code here if not numbers: return '' length = len(numbers) if length == 1: ...
eaefb9129f90fe755537aa657fd78f39eeaff8e0
dickrsunny/data-structure-and-algorithm
/队列/队列(顺序表实现2).py
1,924
3.609375
4
class Queue: def __init__(self): self.elems = [None] * 4 self.head = 0 self.count = 0 self.rear = 0 @property def is_empty(self): return self.count == 0 @property def length(self): return len(self.elems) def __extend(self): _list = [None...
eca50c1a88ab1e671da8f28922979fe1a8e6089e
dickrsunny/data-structure-and-algorithm
/算法题/n阶乘递归与非递归解.py
418
3.78125
4
#coding: utf-8 class Solution: def n_factorial(self, n): if n <= 1: return n return n * self.n_factorial(n - 1) def n_factorial_non_recursively(self, n): if n <= 1: return n res = 1 while n > 1: res = res * n n = n - 1 ...
ac69a7ad69bdf558b6f47ec2db725b222add7bc6
dickrsunny/data-structure-and-algorithm
/链表/双链表.py
1,833
3.734375
4
from exceptions import ValueError class UnderFlow(ValueError): pass class LNode(object): def __init__(self, elem, prev=None, _next=None): self.elem = elem self.prev = prev self._next = _next class DoubleLList(object): def __init__(self): self.head = None self.re...
bb501d6fa2d0b713febe82389df0dc032c6d8f20
BrichtaICS3U/activity-design-a-ui-gothanimegf
/menuTemplateButtonClass.py
6,112
3.875
4
# Menu template with button class and basic menu navigation # Adapted from http://www.dreamincode.net/forums/topic/401541-buttons-and-sliders-in-pygame/ import pygame, sys pygame.init() pygame.mixer.pre_init(frequency=44100, size=-16, channels=2, buffer=4096) pygame.mixer.music.load('SpongeBob.mp3')#https://www.youtu...
4906d072f5da408d6e5352938b862e46a7ef554d
njgupta23/LeetCode-Challenges
/sorting-searching/merge-sorted-arr.py
739
4.375
4
""" Merge Sorted Array Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array. Note: - The number of elements initialized in nums1 and nums2 are m and n respectively. - You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additiona...
a117398259c4f592eb8dd42b9e0627047a17b936
njgupta23/LeetCode-Challenges
/integer/rev-int.py
629
4.125
4
# Reverse Integer # Given a 32-bit signed integer, reverse digits of an integer. # Example 1: # Input: 123 # Output: 321 # Example 2: # Input: -123 # Output: -321 # Example 3: # Input: 120 # Output: 21 def reverse(x): if x >= 0: y = [int(num) for num in str(x)] else: y = [int(n...
32e6e1ae0be300d247f39dd0c65f6bdc59023692
hostjbm/py_gl
/T3. Code Testing/Mocks/permutation_demo.py
267
3.515625
4
import itertools name = 'достаточно длинное имя' def real(name): if len(name) < 10: raise ValueError('String too short to calculate statistics.') y = 0 for i in itertools.permutations(range(len(name)), 10): y += sum(i) print(y, i) real(name)
3a20e5650ec3e9524609371102820ffd3b0b5c88
hostjbm/py_gl
/session1/session1_code.py
2,924
3.515625
4
thisdict = { "model": "Mustang", "year": 1964 } cars = [1, "Ford", "Volvo", "BMW"] def func(x, y, z=0, *args, **kwargs): if kwargs.get('brand', '') == 'Ford': print("Get Ford auto") print(x, y, z, type(args), type(kwargs), args, kwargs) class BaseParams: """Base param class...
6e808146eb26c51d89506f7715eec8996e7e16dd
hostjbm/py_gl
/T3. Code Testing/Pytest/base_code.py
627
3.5
4
# This is a base code for testing with pytest and unittest or nose # we will start from unitest because of it's builtin library # unitest cmd for testing - testing> python -m unittest test_math.py # pytest cmd for testing - python -m pytest or py.test -v def add(x, y): """Add function""" return x + y def ...
3739bd0dd91143bef5a7411ef3a8fe2c4cb8f02a
hostjbm/py_gl
/T3. Code Testing/Mocks/dates.py
269
4.34375
4
from datetime import datetime def is_weekday(): """ Python's datetime library treats Monday as 0 and Sunday as 6""" day = datetime.today() print(day) return 0 <= day.weekday() < 5 # Test if today is a weekday assert is_weekday() print(is_weekday())
a626f73f562abb429c26ecdcfda2e8e2a1a78e47
HimanshGupta10/SE_Assignment
/111803087_test_sum.py
726
3.96875
4
def summ(args): if isinstance(args, (int, float)): return args elif isinstance(args, (dict, str)): return "Invalid Input" total = 0 try: for value in args: total += value return total except TypeError: return "Invalid Input" testing_set = [[15,'me'], {"a":58, "b":9}, 10, [78, 899, 67264], (537, 48...
61e5548084e62fd5a4cf56be66a1d6b31bdb41e1
aieml/ML-IP-Workshop
/codes/3.0 Python Array.py
110
3.765625
4
array=[[1,2], [5,6], [8,9]] for (x,y) in array: print('x:',x) print('y:',y)
09acfedc2f4daecdd788cee76b20e9cc3c7ed931
yhw-miracle/data_structure
/Python/pure_handwriting/demo001_search.py
1,609
3.8125
4
# -*- coding: utf-8 -*- # @Time: 2019/7/18 21:06 # @Author: yhw-miracle # @Email: yhw_software@qq.com # @File: demo001_search.py # @Software: PyCharm import random def single_search(data_list, value): """ 简单查询 :param data_list: 查询数据列表,如:[1, 20, 23, 32, 21] :param value: 查询值,如:32 :return: 查询结果,如,"d...
37980b1491df19938b4fcb581fa4bb9afd74c14d
doceo/lab
/python/esercizi/eser_001.py
525
4.125
4
x = input("inserisci un numero: ") y = input("inserisci un altro numero: ") stringa_uno = input("inserisci una parola: ") stringa_due = input("inserisci una seconda parola: ") print("il più grande dei due è: ") if x>y: print(x) else: print(y) print("la lunghezza della prima parola è: ") print (len(stringa_uno))...
1ca368888c417eb4e33c9b685630bab7ef152196
doceo/lab
/python/esercizi/eser_007_mcm.py
397
4.0625
4
#acquisisco input di tipo numerico e lo converto direttamente in intero x = int(input("inserisci un numero: ")) y = int(input("inserisci un altro numero: ")) multiplo_x = x multiplo_y = y while multiplo_x != multiplo_y: if multiplo_x < multiplo_y: multiplo_x = multiplo_x + x else: multiplo_y = multiplo_y +...
712b01b3ccbd3edc19a1e649fe8d85e1306b7b7e
rojinamaharjan123/pythonassignment3
/partA/Insertion_sort.py
352
4.1875
4
unsorted_list=[4,6,7,8,2,4,5,9] def Insertion_sort(arr): count=len(arr) for i in range(1,count): temp=arr[i] j=i-1 while j>=0 and temp<arr[j]: arr[j+1]=arr[j] j=j-1 arr[j+1]=temp print("The sorted list using insertion sort is:") Insertion_sort(uns...
18ad418a9e104c0207c07cf5bceaa638674a0550
emilyalice2708/readability-python
/readability.py
1,244
3.8125
4
from cs50 import get_string #Define a method to count letters def letter_count(string): count = 0 for i in range(len): if string[i].isalpha(): count += 1 return count #Define a method to count words def word_count(string): count = 0 for i in range(len): if string[i] == ...
aa90a58b84cbf9e1dd01d7805b58c070b832d549
netprog-uniroma2/OPP
/ctrl/ryu/app/beba/echo_server.py
1,323
3.578125
4
#!/usr/bin/env python """ An echo server that uses select to handle multiple clients at a time. Entering any line of input at the terminal will exit the server. """ import select import socket import sys if len(sys.argv)!=2: print("You need to specify a listening port!") sys.exit() host = '' port =...
e51ba9357fc185c025e2c6524b62f70f1822d658
natelee3/python1
/box.py
373
4.21875
4
#Prints a box #Given a height and width, print a box consisting of * characters as its border rows = int(input("Width? ")) columns = int(input("Height? ")) for i in range(rows): for j in range(columns): if (i == 0 or i == rows - 1 or j == 0 or j == columns - 1): print('*', end = ' ') ...
19c88623fe5389a37d78b83293dcba9add2db71c
natelee3/python1
/day_of_the_week.py
289
4.375
4
#Day of the Week #Given a number 0-6, prints the corresponding day of the week day_key = { "0": "Sunday", "1": "Monday", "2": "Tuesday", "3": "Wednesday", "4": "Thursday", "5": "Friday", "6": "Saturday" } day = str(input("Day (0-6)? ")) print(day_key[day])
5c09d379a8bccb9d8443b5cfa605881d72bd569c
gusmairs/sql-projects
/sqlite-demo/insert.py
725
4.09375
4
# Creating and inserting into a sqlite db # Note two approaches to Python variables being incoporated into the # SQL code: with '?' and a tuple of values, or with ':var' and a # dictionary of values # See 'insert2.py' for use of a generator object import sqlite3 as sql db = 'data/insert.db' con = sql.connect(db) c = ...
ebbec97bf15a926897f042508e1f51a399a0dee1
hualcosa/Pandas
/page_visits_funnel/script.py
2,416
3.546875
4
import pandas as pd # Import the dataframes visits = pd.read_csv('visits.csv', parse_dates=[1]) cart = pd.read_csv('cart.csv', parse_dates=[1]) checkout = pd.read_csv('checkout.csv', parse_dates=[1]) purchase = pd.read_csv('purchase.csv', ...
886906e537c70262bc301ac8c067a03808573a54
tonbadal/rnn_lm
/rnn.py
21,225
3.71875
4
# coding: utf-8 from sys import stdout import time import numpy as np from rnnmath import * class RNN(object): """ This class implements Recurrent Neural Networks. You should implement code in the following functions: predict -> predict an output sequence for a given input sequence ...
b393daf70cbc833cd8c71173b2f6f9e7f5791bfe
abhishekparakh/ThinkPython3-2edition
/Practice Code.py
214
3.890625
4
''' Scratch pad for practice code while reading the book "Think Python 3 - Second Edition" ''' import turtle def gcd(a, b): if b == 0: return a else: return gcd(b, a%b) print(gcd(27,15))
2817b7a02761e4450d0e22cc5049af3498964dd9
rupol/cs-module-project-hash-tables
/hashtable/hashtable.py
7,343
4.125
4
class HashTableEntry: """ Linked List hash table key/value pair """ def __init__(self, key, value): self.key = key self.value = value self.next = None # Hash table can't have fewer than this many slots MIN_CAPACITY = 8 class HashTable: """ A hash table that with `cap...
960e2ff8f9acb31bc7925d68b59a7505adb494ec
Praveenendran/Praveenendran
/cart.py
1,913
3.96875
4
while True: product={"101":["samsung",20000,20], "102":["Poco",30000,10], "103":["Iphone",50000,7], "104":["AsusLaptop",15000,40], "105":["Mouse",1000,15]} cart={} ch=input("Enter your choice : 101.Samsung mobile 102.Poco Mobile 103.Iphone 104.Asus Laptop 105.Mouse").split() n=len(ch)...
fcac9a0e323b697ee368fb96593c9d73fab3a819
TheProgramMaster/My-Python-Password-Manager
/myPythonPasswordManager.py
2,514
3.96875
4
import os.path def checkExistence(): if os.path.exists("info.txt"): pass else: file = open("info.txt","w") file.close() def appendNow(): file = open("info.txt",'a') print() print() userName = input("Please enter the user name: ") password = input("Please enter the pa...
807a50f0f3aecaff5d96cdc85a8be3755acea79e
nekoTheShadow/my_answers_of_yukicoder
/0500.py
329
3.640625
4
import math, sys if __name__ == '__main__': n = int(input()) if n > 100: answer = ''.join('0' for _ in range(12)) print(answer) sys.exit() answer = math.factorial(n) display = answer % (10 ** 12) print(display if math.floor(math.log10(answer)) < 12 else '{0:012d}'.format(d...
5bfb440d54b9c46c21fa8c56577bf162fa6ad0c7
nekoTheShadow/my_answers_of_yukicoder
/0036.py
281
4.03125
4
import math if __name__ == '__main__': n = int(input()) cnt = 0 prime = 0 for prime in range(2, int(math.sqrt(n)) + 1): while n % prime == 0: cnt += 1 n //= prime if n != 1: cnt += 1 print("YES" if cnt >= 3 else "NO")
697383b35ed88de537b4621ff1b762a94243e189
nekoTheShadow/my_answers_of_yukicoder
/0458.py
565
3.625
4
import math if __name__ == '__main__': n = int(input()) primes = list(range(n + 1)) primes[0] = primes[1] = None ht = {0 : 0} for prime in primes: if prime is None: continue if prime <= math.sqrt(n): for non_prime in range(prime * 2, n + 1, prime): primes[non_prime] = ...
176d99a8f20398d0981e3a2b0c293610cd7e6f4b
earmingol/Personal-Collection
/Search-Algorithms/GeneticAlgorithm_ANN_architecture.py
14,420
3.5625
4
# coding: utf-8 # Author: Erick Armingol # Genetic Algorithm to find the best ANN architecture import numpy as np import pandas as pd import math import random import time from sklearn.neural_network import MLPClassifier from sklearn.model_selection import cross_val_score from sklearn.pipeline import Pipeline from skl...
53103f09efeb20203d09956cf0d65fb5631a81df
acreally/leetcode
/src/unique_binary_search_trees/solution.py
723
3.53125
4
class Solution: def numTrees(self, n: int) -> int: if n == 0 or n == 1: return 1 cache = {0: 1, 1: 1} return self.compute(n, cache) def compute(self, n: int, cache): if n in cache: return cache[n] level = n // 2 left_subtrees = 0 r...
093b2c701b73096a24ce6f78ee05c99abcc8c7d3
acreally/leetcode
/src/h_index_ii/solution.py
375
3.5
4
from typing import List class Solution: def hIndex(self, citations: List[int]) -> int: if citations is None: return None if not citations: return 0 h = min(1, citations[len(citations) - 1]) for i in range(len(citations) - 2, -1, -1): h = max(min(...
25d1516005f75fabfa4cce956e4162f9fa22c73d
abanoubmilad/Algorithmic-Thinking
/graphs/in_degree_distribution.py
459
3.578125
4
""" Created on Sep 1, 2014 @author: abanoub milad nassief """ def in_degree_distribution(digraph): """" take in param graph, output in degree distribution dictionary """ digraph = compute_in_degrees(digraph) graph = {} for degree in range(len(digraph)): count = 0 for node in digrap...
a3276c162cc7e62e0c99914de82db50edae9b72a
al-mahi/AI_II_CS5793
/BasicClassifiers/BasicClassifiersSimpleData.py
6,367
3.953125
4
#!/usr/bin/python """ Author: S M Al Mahi CS5793: Artificial Intelligence II Assignment 1: Basic classifiers Solution for Part 2,3,4 """ from __future__ import print_function import numpy as np import matplotlib.pyplot as plt from KDTree import cKDTree if __name__ == "__main__": """ Part#2 Constructing a si...
efef8772f7aad4c5f1be72655574f7fca0878341
mwegrzyn/nistats
/examples/05_complete_examples/plot_haxby_block_classification.py
6,892
3.78125
4
""" Decoding of a dataset after glm fit for signal extraction ========================================================= Full step-by-step example of fitting a GLM to perform a decoding experiment. We use the data from one subject of the Haxby dataset. More specifically: 1. Download the Haxby dataset. 2. Extract the ...
6de8c902eb09d586afa7e944426143feb2796aa9
kvjl/WordCount
/wordcount.py
814
3.953125
4
print("Input file name below. The file MUST be in the same directory as the program") filename = input() import sys import re charcount=0 def charcounter(x): global charcount if x <= 25: with open(filename, 'r') as file: data = file.read().replace('\n', '').lower() y = data.rsp...
754bef9c7285fd99aef066d8162ae86b0f15ff96
mango51/pythonPractice
/파이썬/pythonpractice07_stars3.py
189
3.515625
4
lines = int(input("줄 수를 입력해주세요 : ")) for i in range(lines): print(' '*(lines-i), end='') for j in range(0,i+1): print('*','',end='') print()
f82d43e1031824fd8c341f7e741e52de068e4ae7
mango51/pythonPractice
/파이썬/classpractice.py
822
3.78125
4
class Supermarket(object): def __init__(self, location, name, product, customer): self.location = location self.name = name self.product = product self.customer = customer def printLocation(self): print(self.location) def changeCategory(self, new_product):...
d857cb507bf1a4c08485c0d1fb96a667a3571a13
mango51/pythonPractice
/학교파이썬수업/coinanswer.py
648
3.6875
4
money, c500, c100, c50, c10 = 0,0,0,0,0 #교환할 돈과 각 동전 개수를 저장할 전역변수 설정 money = int(input('돈: ')) c500 = money//500 money %= 500 c100 =money//100 money %= 100 c50 = money//50 money%= 50 c10 = money//10 money%= 10 print('%d %d %d %d %d' %(c500, c100, c50, c10, money)) money2, c50000, c10000, c5000,...
1bba169460439a3f3ce68037c5da0ed8df32c4b2
mango51/pythonPractice
/파이썬/pythonpractice03.py
2,208
3.546875
4
answernum = int(input('')) #숫자를 입력받는 변수 answercount = 0 #숫자를 하나씩 올려나갈 변수 #list() 함수는 문자열을 한 글자씩 잘라주는 함수 #예를 들어 a = list('apple')이라고 하면 a=['a','p','p','l','e']로 입력한 문자열이 잘려서 리스트로 출력 for i in range(1, answernum+1): number = str(i) game = list(number) #입력한 수까지 돌기 > number는 1~입력한 수까지 돌기 #입력한 수...
f9ce0cc848e52d37fc49ebbc5985b10f3aa06579
mango51/pythonPractice
/학교파이썬수업/dictionaryanimal.py
588
3.59375
4
animals = {'개':'강아지','호랑이':'개호주','곰':'능소니','말':'조랑말','닭':'병아리','고등어':'아기생선','명태':'노가리'} while (True): oneanimal = input(str(list(animals.keys())) + ' 중 새끼 이름 알고 싶은 동물은? ') if oneanimal in animals: print('<%s>의 새끼는 <%s>입니다.'%(oneanimal, animals[oneanimal])) # oneanimal = 키값, animals[onea...
a9cb0d1bfedcac357cb357727b7c682197d6a2f6
mango51/pythonPractice
/학교파이썬수업/selfstudy4-2.py
346
3.796875
4
num = 0 num2=0 result=0 i=0 #전역변수 초기값 설정 num = int(input('시프트할 숫자는? ')) num2 = int(input('출력할 횟수는? ')) for i in range(1,num2+1): result=num<<i print('%d << %d = %d' %(num, i, result)) for i in range(1,num2+1): result = num>>i print('%d >> %d = %d' %(num, i, result))
0ab8583405ea33d43d57c6f5a0bcf70bc2c632d8
mango51/pythonPractice
/학교파이썬수업/numadding.py
280
3.71875
4
num1,num2,num3,answer =0,0,0,0 num1 = int(input('첫 번째 숫자? ')) num2 = int(input('두 번째 숫자? ')) num3 = int(input('더할 숫자? ')) for i in range(num1,num2+1,num3): answer += i print('%d +%d +...+%d는 %d입니다.'%(num1,num1+num3,num2,answer))
9806dcab8386c472065ed5a97bbc7e48e7fb8d71
mango51/pythonPractice
/파이썬/if2.py
261
4.03125
4
while(1) : name = input("이름을 입력하세요. ") if (name == "홍길동"): gender = "남자" elif (name =="성춘향"): gender= "여자" else: gender = "모르겠어요" print(gender)
7b94bd3c61ab6ee0bf884ea1143beb8509b651ae
mango51/pythonPractice
/파이썬/tkinterpractice05.py
549
3.6875
4
from tkinter import * import tkinter.messagebox import tkinter.simpledialog mainFrame= Tk() Label1 = Label(mainFrame, text='예') Label1.pack() Label2 = Label(mainFrame, text='아니오') Label2.pack() def selecting(): result = tkinter.messagebox.askyesno('예 아니오 퀴즈','어렵습니까?') if result == True: ...
e34cd6576157032c58ba2d1694147961c14c1437
Maulik5041/PythonDS-Algo
/Interview Prep 1/Strings/remove_duplicates.py
2,276
4.375
4
"""Remove duplicates from the string in-place. In Python, strings are immutables and thus not possible to update a string in-place. So instead, we convert this string to an array class and give it a termination character \\0, which is a null character in a lower level language. If in an array, this character is found, ...
ff663c82c024393a3a4d3f00ac9d0fadcbf273b6
Maulik5041/PythonDS-Algo
/Hash Table/searching_hashtable.py
2,667
3.6875
4
"""Searching in a Hash Table""" class HashEntry: def __init__(self, key, data): self.key = key self.value = data self.nxt = None class HashTable: def __init__(self): self.slots = 10 self.size = 0 self.bucket = [None] * self.slots self.threshold = 0.6 ...
3e6b3c6aaa1b0b3cce2b55123d5b7ef323ca4c8b
Maulik5041/PythonDS-Algo
/Graphs/Topological Sort/alien_dictionary.py
1,230
3.515625
4
from collections import deque def find_order(words): if len(words) == 0: return "" in_degree = {} graph = {} for word in words: for char in word: in_degree[char] = 0 graph[char] = [] for i in range(0, len(words)-1): w1, w2 = words[i], words[i+1] ...
8221060d91290bf979474f93fde9471a77abfa32
Maulik5041/PythonDS-Algo
/Interview Prep 1/Stacks, Queues and Deques/stack_using_queues.py
2,158
4.28125
4
"""Implement a stack using Queue data structure""" from collections import deque class StackUsingQueue_1: def __init__(self): self.queue1 = deque() self.queue2 = deque() def push(self, data): self.queue1.append(data) def size(self): return len(self.queue1) + len(self.q...
6599fe087ffc218057a9278877b88e18be1d0da0
Maulik5041/PythonDS-Algo
/Interview Prep 1/Stacks, Queues and Deques/two_stacks_in_array.py
1,539
3.75
4
"""Implement two stacks in an array""" import numpy as np class TwoStacks: def __init__(self, n): self.size = n self.arr = np.zeros([n], dtype=int) self.top1 = -1 self.top2 = self.size def push1(self, val): if self.top1 < self.top2 - 1: self.top1 = self...
34ab291303ebb62cd8f0441b1decf0eff7b56add
Maulik5041/PythonDS-Algo
/Interview Prep 1/Trees/traversals.py
4,553
4
4
from collections import deque class Node: def __init__(self, value): self.value = value self.left = None self.right = None class BinaryTree: def __init__(self, root): self.root = Node(root) def print_tree(self, traversal_type): if traversal_type == "preorder":...
8f4fef0547b1de09c6f042226a417eeff6dfb10b
Maulik5041/PythonDS-Algo
/LinkedList/Singly Linked List/length_of_linked_list.py
2,733
4.28125
4
# Calculating the length of a linked list # Creating a Node class class Node: def __init__(self, data): self.data = data self.next = None # Creating a Linked List class class LinkedList(): def __init__(self): self.head = None def print_list(self): cur_node = self.head while cur_node: print(cur_node...
da78f3c87c2a999dca87b71ea5a5c40e5cc31fad
Maulik5041/PythonDS-Algo
/top k elements/freq_sort.py
611
4.1875
4
from heapq import heappop, heappush def sort_char(str): freq_char_map = {} for char in str: freq_char_map[char] = freq_char_map.get(char, 0) + 1 max_heap = [] for char, freq in freq_char_map.items(): heappush(max_heap, (-freq, char)) sorted_str = [] while max_heap: fr...
f4d90e5c7d0cfb73670a869760cb1b7d4bbe3fd7
Maulik5041/PythonDS-Algo
/Dynamic Programming/Bottom-up dynamic programs/catalan_numbers.py
1,033
3.6875
4
"""Catalan numbers solutions""" # Recursion: O(n!) Factorial complexity def catalan_recursion(n): if n == 0: return 1 sum_val = 0 for i in range(n): sum_val += catalan_recursion(i) * catalan_recursion(n - 1 - i) return sum_val print(catalan_recursion(4)) # Top-down Memoization: O...
e776f7dbe0504603df6ffcf85125657bf3fbdbe9
Maulik5041/PythonDS-Algo
/Practice/merge_sorted_lists.py
421
3.984375
4
"""Merging two sorted lists""" def merge_arrays(lst1, lst2): ind1 = 0 ind2 = 0 while ind1 < len(lst1) and ind2 < len(lst2): if lst1[ind1] > lst2[ind2]: lst1.insert(ind1, lst2[ind2]) ind1 += 1 ind2 += 2 else: ind1 += 1 if ind2 < len(lst2...
24e941d9a34a42eee8530a454e418373f3d30f9e
Maulik5041/PythonDS-Algo
/Graphs/is_tree_undirected_graph.py
4,557
4.09375
4
"""Find out if an undirected graph is a tree""" class Node: def __init__(self, data): self.data = data self.next_element = None class LinkedList: def __init__(self): self.head_node = None def get_head(self): return self.head_node def is_empty(self): if(self....
e00116de10527fed5044e168659878ad731212a5
Maulik5041/PythonDS-Algo
/Binary Search/searching_an_element.py
1,417
4
4
"""Searching for a target element by Linear Search and Binary Search""" # Linear Search def linear_search(data, target): for an_index, _ in enumerate(data): if data[an_index] == target: return True return False # Binary Search - Iterative def binary_search_iterative(data, target): l...
a3f3437483a7a7ff33a1a509c53e14781eca61ac
Maulik5041/PythonDS-Algo
/Interview Prep 1/Array/anagram_check.py
1,163
4.15625
4
"""Check if the given two strings are anagram""" def anagram(str_1, str_2): if str_1 and str_2: str_1 = str_1.lower().replace(" ", "") str_2 = str_2.lower().replace(" ", "") if not str_1 and not str_2: return True if (not str_1 and str_2) or (not str_2 and str_1) or (len(str_1) ...
ecb27a806da230f7341641bae56d6b785e390f3e
Maulik5041/PythonDS-Algo
/Dynamic Programming/knapsack_top_down_memoization.py
1,279
3.8125
4
"""Time Complexity = O(N * C) Space Complexity = O(N * C) """ def solve_knapsack(profits, weights, capacity): # create a two dimensional array for memoization dp = [[-1 for x in range(capacity + 1)] for y in range(len(profits))] return knapsack_recursive(dp, profits, weights, capacity, 0) def knapsac...
6da8e1cecf519b31d1287ea0f54ee155589247c4
Maulik5041/PythonDS-Algo
/Interview Prep 1/Array/array_pair_sum.py
839
4.03125
4
"""Output the unique pairs from the array to adds up to the given key""" def pair_sum(an_array, key): if (not an_array) or (len(an_array) <= 1) or (not key): return None seen = set() pairs = set() for a_value in an_array: target = key - a_value if target in seen: ...
62a4ed197b0ec79806633b82a34f4bc514cc3d6f
Maulik5041/PythonDS-Algo
/Recursion/sum_from_1_to_n.py
267
4
4
"""summing up the numbers from 1 to n""" def sum_till(target_number): # Base Case if target_number == 1: return target_number else: return target_number + sum_till(target_number - 1) if __name__ == '__main__': print(sum_till(20))
f078b803189c95201f636ce2919e91194c82ec15
kms70847/Advent-of-Code-2016
/day04.py
785
3.5
4
from collections import Counter def rot(s,amt): return "".join(chr((ord(c) + amt - ord("a")) % 26 + ord("a")) if c.isalpha() else c for c in s) def is_valid(row): d = Counter(row["name"].replace("-","")) x = sorted(d.items(), key=lambda t: (-t[1],t[0])) checksum = "".join(t[0] for t in x[:5]) retu...
0e97ae896d71e4295e297e5a622571eacb7b612c
kynants/Average_Rainfall
/src.py
1,200
4.5625
5
# Design a program that uses nested loops to collect data and calculate the # average rainfall over a period of years. The program should first ask for # the number of years. The outer loop will iterate once for each year. The # inner loop will iterate twelve times, once for each month. Each iteration of # the inner lo...
ae66ad95e2c42f4bf2f1a0d28849f844ab3ce7dc
canvas-J/sharp_algo
/Sort_Algorithm/bubble_sort.py
423
3.671875
4
# -*- encoding=utf-8 -*- # 冒泡排序 def bubble(l): lens = len(l) while lens > 0: # 遍历所有元素个遍数 for j in range(lens-1): # 一圈冒出一个最大值,前面冒过的不再遍历 if l[j] > l[j+1]: l[j],l[j+1] = l[j+1],l[j] lens -= 1 print(l) if __name__ == '__main__': l = li...
d596287e0ae3668827d51d0679bba36b46b51d2d
R3mmurd/Pong
/paddle.py
1,489
3.875
4
"""Paddle This module an the implementation of the class Paddle Author: Alejandro Mujica (aledrums@gmail.com) Date: 07/09/2020 """ import pygame from constants import VIRTUAL_HEIGHT class Paddle: """ Paddle to be controlled by a player """ def __init__(self, x, y, width, height, color=(255, 255, 2...
38d48db3cb0551a732ed7627367d5541709f05d5
jblprav/jblpravdemo
/repofunc.py
126
3.8125
4
x=int(input("Enter x ")) y=int(input("Enter y ")) print("hello") z=x+y print("sum is ",z) print("hi") print("some extra text")
b99845bc24cea927a0b3d900e139058a15480c1b
kajamalie/Kaggle
/createandusemodels.py
4,001
3.53125
4
#Create and Train a linearregression algorithm with the training data. lin_model = LinearRegression() lin_model.fit(X=X_train, y=y_train) #Make prediction using the training and test data #TRAIN DATA y_train_pred = lin_model.predict(X_train) mean_absolute_error(y_train, y_train_pred) # 0.2976086979535834 np.sqrt(me...
41942cfac464de97b3df5e87869dd968503e490a
battlerhythm/algorithms-python
/myds/sort.py
2,043
3.75
4
def bubbleSort(alist): loopCount = len(alist)-1 while loopCount != 0: for i in range(len(alist)-1): if alist[i] > alist[i+1]: alist[i], alist[i+1] = alist[i+1], alist[i] loopCount -= 1 return alist def insertionSort(alist): i = 0 while i < len(alist)-...
e0329f3fb4e19229891fbb6d92c21409745c56bc
poojamadan96/code
/Inheritance/drivedClassConstructor.py
422
4.03125
4
# In default case the constructor of dervided class is fired class base: def __init__(self): print("fire House") def show(self): print("HEllo") class derived(base): # In case of inheritance if we make a constructor then it will print first of all its value like fire derived in this case later def __init__(self...
1e6c1bdc4f587cac1e1f0485b5a78d71d5967e93
poojamadan96/code
/Inheritance/superExample.py
512
4.21875
4
class base: def __init__(self): super().__init__() print("base") class subchild: def __init__(self): print("Sub child") class superchild(base,subchild): # vase is parent class , subchild is child class def __init__(self): super().__init__() print("HEllo") ob=superchild() # First It will go to superchild wi...
4e942925f8c991316124abb1e247d4fe7457c205
poojamadan96/code
/string/palandrome1.py
161
3.984375
4
#Ram kumar sharma === r k sharma name=input("Enter name") namespace=name.split() newname='' size=len(name) for x in namespace(): newname.append(namespace[0]) print (newname)
74ada75d6a73e14c01aefebb067297eb29d35652
poojamadan96/code
/Inheritance/employeeClass.py
509
3.5
4
#employeeClass.py class Employee: def setEmployee(self): global name,salary li=[] sli=[] for x in range(3): na=input('Name') sal=(int)(input("Salary")) li.append(na) sli.append(sal) name=li salary=sli class Transaction: def mTrans(self): global day dli=[] for x in range(3): d=(int)(input("Da...
378559506b2a199f3841bff89e76076d7222d346
poojamadan96/code
/cronological-dict.py
371
3.9375
4
#create a dictionary for the grand parent name and then the kids he has then the kids he has #{ram:{a:{b}}} grandfinal={} gname={} fname={} for x in range(1): gname=input("Enter name of Grand Parent ") fname=input("Enter name of father") uname=input("enter your name") grandfinal[gname]=fname for x,y in grandfinal....