blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
873d8c7906704780c96b4a1f8906e711414bb138
Aswaglord/combined_programs
/number_game.py
625
3.953125
4
import random random_number = random.randint(1,100) number_guessed = False tries = 0 user_guess = int(input("what is your guess?")) while number_guessed == False: if tries == 9: print("YOU LOSE:(") number_guessed = True elif user_guess == random_number: print(f"congrats you guessed ri...
0bc6f0665608fbe2c2ecdb06a4b92847df64c2c7
NguyenBrianL97/Python-OOP-Chess
/Piece.py
431
3.84375
4
from abc import ABC, abstractmethod class Piece(ABC): white=True @abstractmethod def isWhite(self): pass def canMove(self): pass class Pawn(Piece): def isWhite(self): print("hi") print(self.white) def canMove(self): pass class Knig...
0a13b22992ac8973803e011b78d95e41e4f6fd41
adamcheasley/euler
/problem-019.py
315
3.515625
4
from datetime import datetime from dateutil.relativedelta import relativedelta d = datetime(1901, 1, 1) sundays_on_the_first = 0 while d.year < 2001: if d.weekday() == 6: print d.strftime('%Y/%m/%d %A') sundays_on_the_first += 1 d = d + relativedelta(months=1) print sundays_on_the_first
8cdd5a15d8ef410ee8fb9684054429c330b001d5
nikostsio/Project_Euler
/euler51.py
2,255
3.546875
4
from itertools import combinations, chain from functions import isPrime def sieve(n): try: is_prime = [0]+[0]+[1]*(n-2) except: print([1]*n) return for i in range(2, int(n**(1/2))+1): index = i*2 while index < n: is_prime[index] = 0 index += i primes = [] for i in range(2, n): if is_prime[i]: ...
e92221e9dd8c143a93449860fcdf17b418a62097
nikostsio/Project_Euler
/euler28.py
891
3.546875
4
def turn_right(curr_dir): curr_dir = [-curr_dir[1], curr_dir[0]] return curr_dir def spiral_of(n): spiral = [[0 for i in range(n)] for i in range(n)] pos = [n//2, n//2] direction = [0,-1] spiral[pos[0]][pos[1]] = 1 num = 2 while num<=n**2: if spiral[pos[0]+turn_right(direction)[1]][pos[1]+turn_right(direction...
6453544b462ec3b6a6a961349852ed718624541d
nikostsio/Project_Euler
/euler7.py
205
3.703125
4
from functions import isPrime def main(): num = 2 index = 1 while True: if isPrime(num): print(index, '-->',num) index+=1 if index==10002: break num+=1 if __name__ == '__main__': main()
2b842107e6a36452728400be6faf2f08eb1b0800
nikostsio/Project_Euler
/euler41.py
304
3.609375
4
from functions import isPrime, isPadnigital def same_digits(n): for i in str(n): if str(n).count(i)>1: return True return False def main(): for i in range(10001,10000000,2): if not same_digits(i) and i%10!=0: if isPrime(i) and isPadnigital(i): print(i) if __name__=='__main__': main()
de271bd9223dc57ad9ac6d854be7a71b434489c7
nikostsio/Project_Euler
/euler50.py
417
3.515625
4
from functions import sieve def main(): lim = 1000000 primes = sieve(lim) length = 0 largest = 0 last_prime = len(primes) # print(len(primes)) for i in range(len(primes)): for j in range(i+length, last_prime): s = sum(primes[i:j]) if s < lim: if s in primes: length = j-i # print(length) ...
66f795ce6b518553072d6c01b0b53eb6f491b9d8
hazardg/CP1404-Practicals-GeraldoGenesius
/Practical 1/menu_number_sequence.py
58
3.765625
4
a = float(input("Enter number: ")) b = a * a print (b)
8cfd121a14708e4c4146089827ebf8d2bc7b2b2b
nyhyang/Info206-Python
/HW1_Rainfall/HW1_nyhyang.py
1,298
3.953125
4
# Body def total_rain(): """find out the total usable data in the text file""" # read data from file and use data from each line with open('rainfall.txt', 'r') as fin: count_lst = [] for lst_lines in fin: lst_lines = lst_lines.split(" ") # added " " after discussion with YiFei for the ' 2' case item = ...
1404b08f1e5020346dd7b1a6c76b9b4b7d874eb5
nyhyang/Info206-Python
/HW3_Binary/hw3_starter_pack/hw3.py
1,555
4.09375
4
#--------------------------------------------------------- # Nancy Yang # nancy_yang@berkeley.edu # Homework #3 # September 20, 2016 # hw3.py # Main #--------------------------------------------------------- from BST import * def read_file(filename): with open(filename, 'rU') as document: text = document....
bb0696845160dbcd9ccb1157a7cfdf82623033b2
Roshgar/SmallVersionningPythonScript
/srcs/archiving.py
3,570
3.765625
4
# -*- coding: utf-8 -*- import utils import shutil import os import sys ''' Checks the archives to know if the version already exists in the project. If so the user has 3 choices : Overwriting, renaming and ignoring. ''' def checkArchives(projectName, versName, projectPath, archPath): path = archPath + "/" + projectN...
02147e298879402a52ad1f37c92ce093cca8d991
Lenee/Beginner-Python
/Distance_traveled.py
269
4.15625
4
#!/usr/bin/env python speed=60 time=1 distance=speed*time print('Travel 5 hours at 60 miles per hour = ',5*distance,' miles.') print('Travel 8 hours at 60 miles per hour = ', 8*distance,' miles.') print('Travel 12 hours at 60 miles per hour = ', 12*distance,' miles.')
0ed0800b909083e6f7eb1508a9d9b731292eadc2
anoopsingh/PerlPractice
/PythonLearning/python_q_nd_a/max_sum_array.py
276
3.5625
4
#!/usr/bin/python def max_sum(A): cur_max,tot_max = A[0], A[0] for x in A[1:]: cur_max = max(x,x+cur_max) tot_max = max(tot_max,cur_max) return tot_max a = [1, 2, -3, 3, -7, 5, 4, -1, 4, 5] #a =[-2,1,-3,4,-1,2,1,-5,4] aa = max_sum(a) print aa
a4138772867f66a537d665a5c39fa7868ca8289d
anoopsingh/PerlPractice
/PythonLearning/brkElsContinueLoop.py
264
3.796875
4
#!/usr/bin/python def func(a): for n in range(2,a): for x in range(2,n): if n % x == 0: print n, 'equals', x, ' * ', n/x break else: print n , "prime" continue func(200)
3ded5e97496c8a5ea7d53c9fc550ef2f47b17eed
anoopsingh/PerlPractice
/PythonLearning/prime.py
252
3.578125
4
def primes(n): ps, sieve = [], [True] * (n + 1) for p in range(2, n + 1): if sieve[p]: ps.append(p) for i in range(p * p, n+1, p): sieve[i] = False return ps prms = primes(100) print prms
ab4672bd0d94c888681e18cc90fe739a6ac763f6
joaomrcarvalho/advancedalgorithmscourse
/aula3.py
1,672
3.875
4
import random def brute_force(lista): count = 0 for i in lista: if i % 2 == 0: count += 1 return count def decrease_and_conquer(lista): is_even = (lista[0] % 2 == 0) if len(lista) == 1: return is_even elif len(lista) > 1: return is_even + decrease_and_co...
fca7730446dcefd76ac6db2116b75930e9390b3b
tonylixu/algorithm009-class01
/Week_02/1_two_sum.py
1,528
4.0625
4
def double_loop(n, t): """Calculate all the possible combinations with a double loop Then compare the sum with target, if equal, return Time complexity: O(n) Space complextity: n """ for i in range(len(n) - 1): for j in range(i + 1, len(n)): if n[i] + n[j] == t: ...
46e34b123897551c2a94fbcb88e79645e35ad519
tonylixu/algorithm009-class01
/Week_02/258_add_digits.py
732
4.03125
4
def recursive_method(n): if n < 10: return n total = 0 while n != 0: total += n % 10 n //= 10 return recursive_method(total) def loop_method(n): if n < 10: return n total = n while total >= 10: n = total temp = 0 while n != 0: ...
19b951ddee592225d0c3b0f93de416c2c7353143
tonylixu/algorithm009-class01
/Week_04/200_number_of_islands.py
1,319
3.984375
4
def numIslands(grid): """ Go through one element at a time in grid, if element is a 1, which means it is a piece of island. Then we do a DFS search based on this element. For each visited element, we set it to 0 to avoid duplication. ^ | <- 1 -> | V Time complexity: ...
c0220ba2ddf8f484841896ed789a3f2b99136c71
tonylixu/algorithm009-class01
/Week_06/64_minimum_path_sum.py
2,565
4.0625
4
""" Clarification: - If grid is empty, reurn 0 - All non-negative numbers - What if a number is 0? No impact Possible solutions: - Recursive - Dynamic programming """ class Solution: def minPathSum(self, grid: List[List[int]]) -> int: return self.recursive_optimized(grid) def recursive_opti...
56427cb910193e42fdc8f4adbb44e29f98c04f2a
tonylixu/algorithm009-class01
/Week_07/547_friend_circles.py
3,294
3.6875
4
""" Clarification: - What's the range of N: [1, 200] - Any invalid characters other than 0 or 1? - If M[i][j] = 1, then M[j][i] = 1 Possible solutions: - DFS: You can treat M as a graph, M= [1 1 0 0 0 0 1 1 0 0 0 0 0 0 1 1 1 0 0 0 1 1 0 0 0 0 1 0 1 0 0 0 0 0 0 1] M[i][j] = 1 means i...
fb24bc4633a6105016ef26482e09ceed4cf77134
tonylixu/algorithm009-class01
/Week_04/33_search_in_rotated_sorted_array.py
2,022
3.71875
4
class Solution: def search(self, nums: List[int], target: int) -> int: return self.direct_binary_search(nums, target) def direct_binary_search(self, nums, target): """ No rotated: 1 2 3 4 5 6 7 mid left rotated: pivot at the left side of the...
5b8752bd6922a241d681659b6c9a9025d8eaaa8d
tonylixu/algorithm009-class01
/Week_03/05_ti_huan_kong_ge_lcof.py
896
3.71875
4
def regex_method(s): """ Use regex sub :param s: String to process :return: Processed string Time complexity: O(2^M+N) = O(N). M is the size of the regex (To build a deterministic finite automaton) Space complexity: O(1) """ import re return re.sub(r' ', '%20', s) def iterative_m...
7e1a83492b868d7e92f333be5e35dbb66467f30a
tonylixu/algorithm009-class01
/Week_03/217_contains_duplicate.py
1,078
3.984375
4
class Solution: def containsDuplicate(self, nums: List[int]) -> bool: return self.set_method(nums) def set_method(self, nums): """ Use Python set(), to uniq all ekements of nums. Then compare the length of set and length of nums. 1. If len(set) = len(nums): return False ...
c65449a14a95774816605f54bf2c19176784a46b
tonylixu/algorithm009-class01
/Week_07/212_word_search_ii.py
2,237
3.90625
4
""" Clarification - All words contain small letters - The values of words are distinct - If not board, return [] Possible Solutions - Iterative words, based on https://leetcode.com/problems/word-search/ - Time complexity: O(N*m*m*4^k), N is the number of words, m is the board size, k is the average length ...
a5fac859555e9f08ea805a6b518d7ad246bd93b3
rishabkr/UI-based-Hand-Written-Digit-Recognition
/Image Testing/bg_test.py
361
3.515625
4
import tkinter as tk root = tk() cwgt=Canvas(root) cwgt.pack(expand=True, fill=BOTH) image1=PhotoImage(file="background1.png") # keep a link to the image to stop the image being garbage collected cwgt.img=image1 cwgt.create_image(0, 0, anchor=NW, image=image1) b1=Button(cwgt, text="Hello", bd=0) cwgt.create_window(20,2...
e763789a8d459bfc6b068cf0a1190b87f878c989
LieGeForTress/Learning
/tensorflow/1_practice_1.py
949
3.8125
4
#https://mofanpy.com/tutorials/machine-learning/tensorflow/example2/ #创建数据 #搭建模型 #计算误差 #传播误差 #初始会话 #不断训练 import tensorflow as tf import numpy as np #创建数据 x_data = np.random.rand(100).astype(np.float32) y_data = x_data * 0.1 + 0.3 #定义神经元可变参数 W = tf.Variable(tf.random_uniform([1],-1.0,1.0)) b = tf.Variable(tf.zeros([1]...
3afd3ab20fd3a175a1ea40a346988072d48d6168
harshitacodes/python
/LIST/bubblesort.py
593
3.953125
4
num_list=[24, 33, 44, 5, 21, 19, 23, 30] print("unsorted list:",num_list) for j in range (len(num_list)-1,0,-1): for i in range (j): if num_list[i]>num_list[i+1]: num_list[i],num_list[i+1]=num_list[i+1],num_list[i] list2=num_list else: list1=num_list print("sorted list:",num_list) num_list=[24, 33, 44,...
e3dfeaacb9a3d4dbc59e1a9219eb330f1b696219
harshitacodes/python
/LIST/city.py
116
3.71875
4
places=["delhi", "gujrat", "rajasthan", "punjab", "kerala"] i=-1 while i<len(places): print(places[i]) i=i-1
1dd2f977a835e473e82a4df9741aa4ce01f1a7f5
harshitacodes/python
/debugging/debugg3.py
425
3.8125
4
def numbers_less_than_twenty(list): counter = 0 while counter < len(list): item = list[counter] if item > 20: list.remove(item) else: counter += 1 return list num_list = [12, 312, 42, 123, 5, 12, 53, 75, 123, 62, 9] print(num_list) num_list_sub_20 = numbers_less_than_twenty(num_list) numb...
b303da07ceddbb01052a58719378459a24ba93e9
harshitacodes/python
/function/return1.py
541
4.21875
4
def calculator(number_x,number_y,operation): if operation =="addition": addition= number_x+number_y return addition elif operation =="subtraction": subtraction= number_x - number_y return subtraction elif operation == "multiply": multiply= number_x*number_y return multiply elif operation=="divide": di...
b069f016ebe098469c7d5b82af0fa2c2f896c911
harshitacodes/python
/function/secondmax.py
304
4.03125
4
def number(num1,num2,num3): if (num1>num2): if(num1>num3): print(num1) else: print(num3) elif(num2>num3): print(num2) else: print(num3) number1=int(input("enter the number")) number2=int(input("enter the number")) number3=int(input("enter the number")) number(number1,number2,number3)
57423fe79a1402941468d51c0785a49b8c21657d
yangzi33/csc148
/lectures/week6/lecture_linked_list_with_edits.py
6,018
4.0625
4
"""Linked List === CSC148 Winter 2019 === Department of Computer Science, University of Toronto === Module Description === This module contains the code for a linked list implementation with two classes, LinkedList and _Node. """ from __future__ import annotations from typing import Any, Callable, Optional, Union ...
dbad1067af224fa2ac7a88f9416b5babd8c9a9b0
ehan831/coding_study
/python/cWebConn/3_beautifulsoup_class/Ex02_seletor.py
916
3.6875
4
""" BeautifulSoup 모듈에서 - HTML의 구조(=트리구조)에서 요소를 검색할 때 : find() / find_all() - CSS 선택자 검색할 때 : select() / select_one() """ from bs4 import BeautifulSoup html = """ <html> <body> <div id='course'> <h1>빅데이터 과정</h1> </div> <div id='...
ace2b1fed4040db36e6a28cab1c5ab276f3584e4
ehan831/coding_study
/python/aBasic/e_file_class/Ex03_json.py
687
3.546875
4
import json f = open('../data/temp.json', 'rt', encoding='utf-8') json_data = f.read() data = json.loads(json_data) print(data) # # for item in data: # print('>', item) # (1) 이름: ㅇㅇㅇ # 번호: ㅇㅇㅇ # 직업: ㅇㅇㅇ # 형태로 출력해보기 for item in data: print('이름:', item) print('번호:', data[item]['No']) ...
70010c1df3fc11d3980020973427a92c51414a7b
ehan831/coding_study
/python/fc/section02-1.py
542
4
4
# print print('Hello Python!') print("Hello Python!") print("""Hello Python!""") print('''Hello Python!''') # Separator print('T', 'E', 'S', 'T') print('T', 'E', 'S', 'T', sep='') print('emailAddress', 'google.com', sep='@') # end print('Welcome To', end=' ') print('메뚜기 월드', end=' ') print('헬로우') # format print('{} ...
d72a378ff2978c6d1df59a01545a7073a0a0d116
Artur-Grigoryev/ICS3U-Unit3-01-Python
/Add_Two.py
454
4.03125
4
#!/usr/bin/env python3 # Created by Artur Grigoryev # Created on May 8, 2021 # This file adds two numbers entered by the user def main(): # Function that calculates the sum of both numbers number1 = int(input("Input your first number: ")) number2 = int(input("Input your second number: ")) # User inpu...
d82fb99d6f9f18d4541bbb9ce34f18d15a15e038
Abimbola-ai/Algoexpert.io-code-challenge
/Ultimate_tournament.py
483
3.671875
4
def tournamentWinner(competitions, results): current_winner = "" scores = {current_winner: 0} # Write your code here. for idx,lists in enumerate(competitions): result = results[idx] home, away = lists # print(result) winning_team = home if result == 1 else away if winning_team not in scores: sco...
17ff47b2b3e366a8f407fdc8b7a6432fa7eddfdc
johnmee/nigel
/canobox/triangles.py
1,891
3.65625
4
""" Primitives for modeling triangles """ import copy import random import numpy from matplotlib import pyplot class Triangle(object): """It's a triangle (2D)""" def __init__(self, x1, y1, x2, y2, x3, y3): self.x1, self.y1 = x1, y1 self.x2, self.y2 = x2, y2 self.x3, self.y3 = x3, y3 ...
f84c7a47a53f99db630b32c9ad8e0ae1fe05f3ac
hsanson/logo-playground
/solution04.py
968
4.28125
4
""" Solution 04 Objective: - Understand the concept of abstraction and how it can be used to reduce code duplication and maintenance. Documentation: - https://docs.python.org/3.7/library/turtle.html """ import turtle jim = turtle.Turtle() canvas = jim.getscreen() def start(): reset() draw_squa...
c5046a8ae2578c077d188311cbfa86b994b0de87
ftlka/problems
/leetcode/decode-string/solution.py
898
3.59375
4
def decodeString(s): if not s: return ar = [] i = 0 while i < len(s): if s[i].isdigit(): if i > 0 and s[i-1].isalpha(): ar.append('\'') ar.append('+') num = s[i] while s[i+1].isdigit(): i += 1 ...
85db6757b563d8d6537db064e1bd321070056bcc
ftlka/problems
/leetcode/linked-list-cycle/test_.py
694
3.5
4
from solution import ListNode, Solution s = Solution() # tail connects to 2 head = cur = ListNode(3) second = cur.next = ListNode(2) cur, cur.next = cur.next, ListNode(0) cur, cur.next = cur.next, ListNode(-4) cur.next.next = second assert s.hasCycle(head) # tail connects to 1 head = cur = ListNode(1) cur.next = ...
4d895940e873cc24eb422c5b15d2dcc6bf0e4bb7
ftlka/problems
/leetcode/edit-distance/solution.py
704
3.5
4
def minDistance(word1, word2): dp = [[0] * (len(word1) + 1) for l in range(len(word2) + 1)] # first row is from 0 to len(word1) + 1 for i in range(len(word1) + 1): dp[0][i] = i # same for first column for i in range(len(word2) + 1): dp[i][0] = i for i in range(1, len(word2...
31efcde5ec02cd4d7f7d762cfc5fe5e8f2186dd7
ftlka/problems
/leetcode/n-ary-tree-preorder-traversal/solution.py
545
3.6875
4
from collections import deque class Node(object): def __init__(self, val, children): self.val = val self.children = children class Solution(object): def preorder(self, root): if not root: return [] res = [] queue = deque() queue.append(root) ...
e77442849336ae8bd5a0108ef96c1bacbf9848c7
ftlka/problems
/leetcode/spiral-matrix-ii/solution.py
1,215
3.6875
4
def get_num(n): for num in range(1, n ** 2 + 1): yield num def generateMatrix(n): matrix = [[0] * n for i in range(n)] generator = get_num(n) left_bound, right_bound = 0, n - 1 upper_bound, lower_bound = 0, n - 1 row, col = 0, 0 while True: # right if not col <= r...
d1e9055ef98885bc6dd0ca1889698fb4761f4633
ftlka/problems
/leetcode/odd-even-linked-list/solution.py
848
3.890625
4
class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def oddEvenList(self, head): even_head = ListNode(0) odd = ListNode(0) root = odd counter = 1 while head: if counter % 2 == 0: # if its a fi...
068dc790d2a0f9fc2b335bc7607b8b2ef46021e6
carlosesh/cs50
/pset6/marioMore/mario.py
782
3.96875
4
from cs50 import * def main(): s = get_int("Height: ") pyramid(s) def pyramid(height): # check for correct usage if (height <= 0 or height >= 9): pyramid(get_int("Height?\n")) else: for i in range(height): temp = height - 1 - i # print spaces ...
94d9ea2e0f0776af9fbe69a97c3b6d9f991fceda
lukszyn/Python
/Zadanie1.py
531
3.734375
4
#ZADANIE 1 ## Napisz skrypt, który: ## wczyta dwie wartości należące do zbioru N={0, 1, 2, …} ## wyświetli wynik sumy w/w liczb ## wyświetli informację tylko w sytuacji, gdy suma liczb jest parzysta NAZWA1="Zadanie 1" print("program",NAZWA1) print('****************') print("Podaj liczbe naturaln...
3cfc32031c81ae3d12c316cc9293397a471fea95
lukszyn/Python
/Zadanie33.py
879
3.84375
4
# -*- coding: ISO-8859-2 -*- import os import m33 def menu(): plik = str(input("Podaj nazw pliku: ")) if os.path.isfile(plik): rejestr = open(plik, 'a+') print("Otwarto plik: {}".format(rejestr.name)) else: rejestr = open(plik, 'a+') print("Utworzono plik: {}"...
6abd43fe0684e692ff1b2604f511586fa65bb705
anuj3918/competitive_programming
/powerBinary.py
248
3.671875
4
def pow(x, n, d): if(n == 1): return x % d product = 1 halfN = n/2 product = pow(x, halfN, d) if(n % 2 == 0): product = product * product else: product = product * product * x return product % d
647057bc76615c28386b8f80ba4d46e506337e4f
anuj3918/competitive_programming
/lexical.py
567
3.640625
4
def nextPermutation(A): A = sorted(list(A)) swapped = False smallest = len(A)-1 for i in range(len(A)-1, 0 ,-1): if(swapped == True): break if(A[i] < smallest): smallest = i if(A[i] <= A[i-1]): continue temp = A[smallest] A...
caaedb282bc002805f1abb803b20cb42e0d473ac
mariasintea/AI-labs
/lab1-simplealgos/Lab1/Lab1 - extra/7.py
529
3.90625
4
# returns the k-th biggest element in given array # in: n - number of elements in array, elems - given array of elements, k - given index # out: the k-th biggest element in numbers def max_k(n, numbers, k): numbers.sort() return numbers[n - k] # tests max_k function # in : - # out : - def test_max_k(): as...
a70614d753495e953501bf432d885f21f6bfab6b
mariasintea/AI-labs
/lab1-simplealgos/Lab1/10.py
1,073
3.875
4
# returns number of ones at the end of given array # in: j - current index, array - given array # out: number of ones at the end of array def number_of_ones(j, array): if array[j] == 0 or j == 0: return 0 return number_of_ones(j - 1, array) + 1 # returns index of line containing most ones in a given m...
b918913f3470eb6174f245048110c2864b4bc0ce
rudolphlogin/Python_training
/class and modules/whileLoop.py
207
3.734375
4
#n = 5 #while n>0: # print(n) # n= n-1 #print("Blastoff") x = 10 while 1==1: x = x -1 if x == 0: print('reached') break y = 10 while y > 0: y -= 1 print(y)
55380a23d5f63f3054582c797f04c62fd397e4a2
rudolphlogin/Python_training
/class and modules/readfromtext.py
1,519
4.375
4
'''Demonstrate reading text from a file''' print('\n********* Iterating over lines ***************') '''Reading text from a file with default encoding''' with open('C:\\Users\\nbg4kdv\\Documents\\UPS\CDP\\Python\\class and modules\\pep20.txt') as textfile: for line in textfile: print(line,end='') print('\n**...
af4b86dd61e97779b5229cb37cc224dcb89b1167
yashbg/6w6l
/python/ls.py
404
3.5625
4
import argparse import os import sys parser = argparse.ArgumentParser(description='List the contents of a folder') parser.add_argument( 'path', metavar='path', type=str, help='the path to list' ) args = parser.parse_args() input_path = args.path if not os.path.isdir(input_path): print('The path...
7e5d300588c75f3533af50df451895953207d5d8
axrn/exercism-python-solutions
/acronym/acronym.py
95
3.78125
4
def abbreviate(words: str) -> str: return ''.join(x for x in words.title() if x.isupper())
2344593015d782ac5d25bffb887b8f78a686a95c
axrn/exercism-python-solutions
/scrabble-score/scrabble_score.py
313
3.53125
4
def score(word: str) -> int: SCORE = {'AEIOULNRST': 1, 'DG': 2, 'BCMP': 3, 'FHVWY': 4, 'K': 5, 'JX': 8, 'QZ': 10} LETTER_SCORE = {x: i for s, i in SCORE.items() for x in s} return sum(LETTER_SCORE[x] for x in word.upper())
dc1e088a93f0f622ea7b29ef9d1c6ef9a11bef50
axrn/exercism-python-solutions
/pangram/pangram.py
181
3.734375
4
def is_pangram(sentence): alphabet = map(chr, range(ord('a'), ord('z')+1)) sentence = sorted(set(x for x in sentence.lower() if x.isalpha())) return sentence == alphabet
1fecdcdd0903455f86cc2542d1b623bec65068fc
Didriksson/wallstreet_tycoon
/logic/chance.py
167
3.609375
4
import random # input: an int between 1 and 100 def applyChance(percentage): if random.randrange(1,100) < percentage: return True else: return False
25b22f2b51cf791933aea124a95fc230eb05484b
naumanafsar/cs101-in-python
/a04.py
1,975
4
4
## IMPORTS GO HERE ## END OF IMPORTS #### YOUR CODE FOR get_grade() FUNCTION GOES HERE #### def get_grade(grades): if round(grades >= 90): return "A+" if round(grades >= 86): return "A" if round(grades >= 82): return "A-" if round(grades >= 78): return "B+" if round...
68991a9e14a1272e1f2738d61ebc26b788bf109e
Muhammad-Bilal-MB/Multifunctional-Calculator
/calculator.py
3,937
3.96875
4
import math expression = "" def Sum(first_value , second_value): #Sum Function print(first_value + second_value) def Subtract(first_value , second_value): #Subtraction Function print(first_value - second_value) def Multiply(first_value , second_value): ...
93dad1bce2861277da1c8da801bef77d761aef84
wwunlp/sner
/sner/scripts/ner/namesfromrule.py
1,464
3.5625
4
"""Names from rule.""" from sner.classes import Rule def main(corpus, rule): """ Takes the overall corpus as input, as well as a single Rule object. Will return a Set of tokens satisfying the passed-in Rule, referred to in the code as 'names'. Args: corpus (set): Set of all Token objects ...
f0ddd7356adb456b2f38b2a639290ab085fdd598
tdeegan/Card-Game
/card_game_E(X).py
3,981
4
4
"""This program determines the expected value of a card game in which you randomly draw from a standard deck with the following rules: 1. Black card is worth $1 2. Red card is worth -$1 3. You can quit at any time. It employes elements of dynamic programming with a recursive solution and allows for the...
72521d4275b75a91647d267a69c82d3f6b380831
aaaaaaaaaron/svdCompression
/testing.py
938
3.703125
4
from numpy import zeros from numpy import array from numpy import add def addSimilarMatrices(a, b): """This adds two matrices of the same dimension""" for y in range(len(a)): for x in range(len(a[0])): a[y][x] = a[y][x] + b[y][x] return a a = [[1,2,3], [3,2,1], [3,3,3], ...
010df0d5ad08d7f4a67a0a5deb6f34d0a89d67c6
0orja/intro-final
/flybusters.py
13,525
3.515625
4
import sys import pygame import random """ Developers: Oorja (ojm238) and Yao (yx1441) Purpose: This final project is done in pygame. The goal is to "kill" flies in the D2 campus dining hall with a gun without hitting the cats. Flies appear at a gradually increasing probability and bounce around on the screen. If a fl...
e15e0403c7e59d6e2010e8f1f5b4465c716293f6
repoman322/mycode-dev
/cert/cert_req2.py
2,803
3.53125
4
#!/usr/bin/python3 """KEggert || FLASK Sample alta3research-requests02.py should demonstrate proficiency with the requests HTTP library. The API you target is up to you, but be sure any data that is returned is "normalized" into a format that is easy for users to understand.""" import requests import re from random i...
34b79d2e7fb73ba59b4b9d23e040820cf0709103
Krittika-Saha/Stock-News-Alert
/main.py
2,950
3.5
4
from requests import get STOCK = "TSLA" COMPANY_NAME = "Tesla%20Inc" from datetime import datetime, timedelta from twilio.rest import Client STOCK_ENDPOINT = "https://www.alphavantage.co/query" NEWS_ENDPOINT = "https://newsapi.org/v2/everything" STOCK_API_KEY = "_YOUR_API_KEY_" NEWS_API_KEY = "_YOUR_API_KEY_" account_...
ef1c0489b40827639f6751de0f3ac5795fd2e5ee
aniltrue/PingPongGNN
/venv/AI/PopulationSorter.py
1,059
3.640625
4
from AI.Species import Species def swap(species: list, index1: int, index2: int): temp = species[index1] species[index1] = species[index2] species[index2] = temp def basicSort(species: list, left: int, right: int): for i in range(left, right + 1): for j in range(i + 1, right + 1): ...
bd1ccccf6b4cd320f4a0e39bb7a2d1f7bd695161
proubatsis/NeoPixel-Strip-Message-Board
/tobytearray.py
594
4
4
#Converts the contents of 'letters.txt' into an array #that can be used by the arduino program. The result #of the conversion is in the file 'array.txt'. f = open("letters.txt", "r") lines = f.readlines() out = "{\n" for i in range(0, 26): startLine = i * 8 slice = lines[startLine + 1 : startLine + 8] o...
794c7f9aa42e765a22deb858602f9b861aa28796
DaPenguinNinja/Testing-Python
/List.py
382
4.03125
4
friends = ["Kevin","Jim","Jim"] print(friends) friends.append("Doug") print(friends) friends.pop() print(friends) print(friends.count("Jim")) print(friends.index("Jim")) print(friends.index("Jim")) for friend in friends: print(friend) print("This " + friend + " is cool.") numbers = [3,45,2,6,0,8,4,56, 48...
f44653f6e72aa45eae4a087df9c5137a712a1360
DaPenguinNinja/Testing-Python
/While.py
148
4.03125
4
#while i=1 num=float(input("Enter in a number: ")) while i<=20: print (num, '\n') i=num num+=1 print("You finished your loop")
528867e779743d3c783f154d508b01945f1caec6
sasimohan89/Python
/Python Basics I/passwordChecker.py
336
4.21875
4
# password checker program username = input('username: ') password = input('password: ') password_length = len(password) hidden_password = '*' * password_length print(username + ', your password ' + hidden_password + ' is ' + str(password_length) + ' letters long') print(f'{username}, your password {hidden_password...
c1b5e95c63464f84abdb7a47fbf7e96467ff9597
sasimohan89/Python
/Unit tests/test.py
675
3.5625
4
import main import unittest class TestMain(unittest.TestCase): def test_add_five(self): test_param = 10 result = main.add_five(test_param) self.assertEqual(result, 15) def test1_add_five(self): test_param = 'adfg' result = main.add_five(test_param) self.assertIs...
dbae342cd8de1b2c31f02e34415b63aa0a39d762
andrew12678/multilayer-perceptron-numpy
/src/activation/relu.py
1,061
3.84375
4
import numpy as np from .activation import Activation class ReLU(Activation): def __init__(self): super().__init__() self.input = None def forward(self, x: np.ndarray): """ Computes the ReLU activation function on a numpy array Args: x (np.ndarray): The arr...
75831cf940ee2a64d905922ca6e75843678e23a8
andrew12678/multilayer-perceptron-numpy
/src/activation/leaky_relu.py
1,310
3.75
4
import numpy as np from .activation import Activation class LeakyReLU(Activation): def __init__(self, c: int = 0.01): """ Accepts an argument for the slope of the leaky ReLU for negative values Args: c (): """ super().__init__() self.input = None ...
89e2e7f5974185e8e34d8a1d057eb3bb3093ec17
khatria/Data-Structures-in-Python
/Arrays/max_diff_btw_elements.py
713
4.0625
4
# -*- coding: utf-8 -*- """ Find the maximum distance between 2 elements in an array st larger element appears after the smaller number """ def max_diff(lst): ''' This function maintains track of min element and max diff, using which it finds the distance between 2 elements in the arrat Time -...
1f4f8a3cc3fa1bdc312203a5d789f40e574e8dcb
khatria/Data-Structures-in-Python
/Arrays/find_pair.py
364
3.765625
4
# -*- coding: utf-8 -*- """ Given an array A and a number x, find a pair(a, b) in A st a+b = x """ def find_pair(lst, x): dict_elem = {} for a in lst: b = x - a if dict_elem.get(b) != None: print('One such pair is ({}, {})'.format(a,b)) dict_elem[a] = 0 f...
8d124d4bfd72eec6412e0d117bc3dfdf632b852a
bordia98/kdtreesproject
/BalncedKD_NearestSearch.py
14,430
3.75
4
import random import sys,math from svg import Circle,Rectangle,Scene,Line,Rectangle,Text def colorstr(rgb): return "#%x%x%x" % (int(rgb[0]/16),int(rgb[1]/16),int(rgb[2]/16)) class treenode: def __init__(self): self.point=[] self.left=None self.right=None self.parent=None class kdtre...
e47e0706f0a987563dc7e8073330925c8dce8300
dicamposlima/FIT
/ED/Exercicios/27032020/ex_revisao_ac1.py
12,010
3.5
4
### Solução 1: # Dê uma descrição do funcionamento desse algoritmo. # Algo como: lê uma peça da lista, verifica se pode utilizá-la no jogo. Se puder, encaixa ela no início... # Qual parece ser a complexidade? O(n)? O(n**2)? # Dê características ao código. É um código legível? Por quê? É um código curto? É um código ...
ff05ee3fbf302bbdd6d0c9643d2ed3ea481293ad
dicamposlima/FIT
/ED/Exercicios/03042020/04_dicionarios.py
2,708
3.96875
4
import unittest #faça uma funcao que conta as letras de uma string #por exemplo, 'banana' tem 3 letras 'a' # a funcao recebe uma string e devolve um dicionário # por exemplo, conta_letras('banana') devolve {'b':1,'a':3,'n':2} def conta_letras(string): dicti = {} for letra in string: if letra not in dic...
785d504082b378ae6fe88c3ca5d0ec4d7a37560b
Yasthir01/Python-Crash-Course-textbook
/Python Crash Course 2nd time around/exercise_8.py
1,890
4.1875
4
# def city_country(city, country): # """Returns a city and its country""" # return f"{city.title()}, {country.title()}" # def make_album(artist, title, songs=None): # """Builds a dictionary containing information about an album""" # album_dict = { # 'artist': artist.title(), # 'title': title.title(), # } #...
25fa3086c9e71c9087e48f3b35da9d65e8938469
Yasthir01/Python-Crash-Course-textbook
/Python Crash Course 2nd time around/squares.py
630
4
4
squares = [] for value in range(1, 11): squares.append(value**2) print(squares) digits = [1,2,3,4,5,6,7,8,9,0] print(min(digits)) print(max(digits)) print(sum(digits)) squares2 = [value**2 for value in range(1,11)] print(squares2) for number in range(1,21): print(number) million = list(range(1, 1_000_001)) print...
2fd3fe2da2d90ba1234c12f2105f03e2cbde9dc5
yvonneyeh/dicts-restaurant-ratings
/ratings.py
1,681
3.875
4
"""Restaurant rating lister.""" # put your code here def restaurant_ratings(filename): # open score file opened_file = open(filename) # create empty dictionary ratings_dict = {} # read ratings in file, split lines: for line in opened_file: # strip the right whitespace from the line...
9e24667a8dbf61c8c40034b30bbaff51f4d59018
stellaligit/LeetCode
/Easy/SearchInsertPosition.py
703
3.875
4
# https://leetcode.com/problems/search-insert-position/ class Solution: def searchInsert(self, nums: [], target: int) -> int: for i in range(len(nums)): if nums[i] >= target: return i return i + 1 if __name__ == "__main__": try: test = Solution() a...
4276d79328be8c9ee1ec1cf38409e9bc1c8d6aee
subbareddykovvuri/Programming-Data-Structures-And-Algorithms-Using-Python-NPTEL
/Sample Online Test/Sample Online Test, Question 1.py
535
3.71875
4
myinput=''' (2,1,3) ''' def max3bad(x,y,z): maximum = 0 if x >= y: if x >= z: maximum = x elif y >= z: maximum = y else: maximum = z return(maximum) def max3good(x,y,z): if x >= y and x >= z: maximum = x elif y >= z: maximum = y else: maximum = z return(maximum) impo...
e508ea720013911bf4918f741b046d625a14fa9b
subbareddykovvuri/Programming-Data-Structures-And-Algorithms-Using-Python-NPTEL
/Sample Online Test/Sample Online Test, Question 6.py
451
3.671875
4
def sublist(l1,l2): for i in range(len(l2)-len(l1)+1): if l2[i:len(l1)+i]==l1: return True return False import ast def topairoflists(inp): inp = "["+inp+"]" inp = ast.literal_eval(inp) return (inp[0],inp[1]) fncall = input() lparen = fncall.find("(") rparen = fncall.rfind(")") fname = fncall...
5ce662d131e4159394df0650469bc598570ad537
subbareddykovvuri/Programming-Data-Structures-And-Algorithms-Using-Python-NPTEL
/Online Test 2/Online Test 2, Question 5.py
479
3.78125
4
def sumof3squares(n): a=int(n**(1/3)) b=int(a/2) for i in range(b,2*a): for j in range(b,2*a): for k in range(b,2*a): if i**2+j**2+k**2==n: return True return False import ast def toint(inp): inp = ast.literal_eval(inp) return (inp) fncall = input() lparen = fncall.find("(") rp...
37ff28359e53c8fc3222c4f827b595cf8b20fbf4
gaharavara/MachineLearning
/Simple Linear Regression/simple_linear_regression.py
1,799
4.375
4
# Simple linear regression import pandas import numpy import matplotlib.pyplot as plt dataset = pandas.read_csv('Salary_Data.csv') # Independent variable x = dataset.iloc[:, :-1].values # Dependent variable y = dataset.iloc[:, 1].values # Taking care of missing data # Encoding categorical data # Since y is depend...
cb90eef9cf9de60ac8443ea324f1e28d6248d72e
fivesmallrain5/ProForPi
/NEWPI/Five/Fothers/FDatatools.py
3,247
3.90625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- """ 用来多个key 对应一个value """ class Rome(): key = dict() value = dict() count = 0 def __init__(self, **args): for i, d in args.iteritems(): self.count += 1 self.key.setdefault(i, self.count) self.v...
981c03158b9923e32a03a7f6c419da9b5bc2f2a8
shinkyeongju/ex_python.github.io
/calcul.py
1,338
3.875
4
from tkinter import * def cal(): global col_index, s window = Tk() window.title('My Calculator') display = Entry(window, width = 33, bg = 'pink') display.grid(row = 0, column = 0, columnspan = 5) bt_list = '7,8,9,/,C,4,5,6,*,%,1,2,3,-,**,0,,=,+,←'.split(",") print(bt_list) col_index ...
1d2441f9f718cd40677791a00b1d10af934d489b
omars90/test15
/file1.py
216
4.0625
4
import numpy as np #input height in metrics height = float(input('Enter your height: ')) if 260>height>100: height=height*0.01 elif 0.8<height<8.53: height=height*30.48 height=round(height,2) print(height)
ced047c4244cc7e91a9536207a0a65cd97d0a182
kim-barker/Compression-Project
/3F7 FTR Folder/adaptive_huffman.py
4,578
3.734375
4
from math import log2, ceil from trees import * import collections def adaptive_huff(x, alphabet): y = [] # output # create starting tree xt xt = huffman(alphabet) # create dictionary to store weights of nodes w = {} for parent, childn, label in xt: w[label] = 1 # update...
cc646686c5ba51d9a706783d0ce04c6649c52824
sonwy102/melon-raffle
/version2/raffle.py
522
3.71875
4
"""Randomly pick customer and print customer info""" from random import choice import customers def print_random_customer(customers_file_path): """Take txtfile of customers and print random customer's info""" # Generate list of all customer objects from file customers_list = customers.get_customers_from_...
792141e7b3768b03dd9870f0a9cc79c9c2ff11b9
destpick/BasicPythonFunctions
/Hw3.py
10,781
3.921875
4
# Desta Pickering # Course 355: Homework 3 # Intro to Python3 in Linux from functools import reduce # Problem 1 Dictionaries # Part a: addDict() def addDict (inputted_dic): updated_dic = {} for course in inputted_dic: for day, hour in inputted_dic[course].items(): updated_dic[day]= update...
f436a72de6552ca74a2552171386a5736bdde15a
dikshabaviskar06/21-DAYS-PROGRAMMING-CHALLENGE-ACES
/pythonday20.py
1,581
3.890625
4
import pandas as pd import numpy as np #*************Indexing and selecting data********************** df = pd.DataFrame(np.random.randn(8,4),index=['a','b','c','d','e','f','g','h'],columns=['A','B','C','D']) #select all rows for specific column print(df.loc[:,'A']) #select all rows for multiple columns print(...
60bf896666f1acd95aca055ba1e94238dc45e7be
dikshabaviskar06/21-DAYS-PROGRAMMING-CHALLENGE-ACES
/pythonday16.py
1,878
3.53125
4
import pandas as pd import numpy as np #******series functionality******* s=pd.Series(np.random.randn(4)) print("original series",s) print("The axes are:",s.axes) print("Is the object empty?",s.empty) print("The dimensions of the object:",s.ndim) print("The size of the object:",s.size) print("The actual da...
74b4f6ba286d056859f8613d3020bf84e2b9506d
KyawHtetWin/Peer-to-Peer-File-Sharing-System
/Zero-Copy Send/server.py
748
3.609375
4
import socket import os import pickle """ This function sends a single specified file over the socket connection """ directory = "./shared_folder" def send_file(f_name, sock): with open(f_name, 'rb') as f: sock.sendfile(f, 0) s = socket.socket() s.bind(('localhost', 12345)) s.listen(5) while True: client_s...
399eac9cab95746fba65155222dc41094fd0f8f0
MClaireaux/Pong
/main.py
1,270
3.5625
4
from turtle import Screen from paddle import Paddle from ball import Ball from scoreboard import ScoreBoard import time screen = Screen() screen.setup(height=int(600), width=int(800)) screen.bgcolor("black") screen.title("Pong") screen.tracer(0) r_paddle = Paddle((350, 0)) l_paddle = Paddle((-350, 0)) b...