blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
3.06M
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
3.06M
c56d992234d558fd0b0b49aa6029d6d287e90f2a
ARSimmons/IntroToPython
/Students/Dave Fugelso/Session 2/ack.py
2,766
4.25
4
''' Dave Fugelso Python Course homework Session 2 Oct. 9 The Ackermann function, A(m, n), is defined: A(m, n) = n+1 if m = 0 A(m-1, 1) if m > 0 and n = 0 A(m-1, A(m, n-1)) if m > 0 and n > 0. See http://en.wikipedia.org/wiki/Ackermann_funciton Create a new module called ack.py in...
b731cd49d33058ceecdcfbe9206a318acf2c8e94
ARSimmons/IntroToPython
/Students/CarolynEvans/session01/print_grid.py
1,963
3.96875
4
# This was my first attempt. # This one prints the number of boxes horizontal and vertical based on the 'x' parameter, # and the size of each box is determined by the 'x' parameter as well. def grid1(x): for a in range(0,x,1): for b in range(0,x,1): print '+', for c in range(0,x,...
4172dee9755569557a7540f5a9e390ed325ba9ea
ARSimmons/IntroToPython
/Students/apklock/session01/grid_n.py
195
3.609375
4
def grid_n(n): #n rows & columns a = ' + ----' b = ' | ' for i in range(n): print a * n, '+' print b * n, '|' print b * n, '|' print b * n, '|' print b * n, '|' print a * n, '+'
089d34b6bd25080e2c89f9273294aa368888e54e
ARSimmons/IntroToPython
/Students/A.Kramer/session02/series.py
977
4.0625
4
def fibonacci(n): """Return Fibonacci number""" if n <= 1: return n else: return fibonacci(n-1) + fibonacci(n-2) def lucas(n): """Return Lucas number""" if n == 0: return 2 if n == 1: return 1 return lucas(n-1) + lucas(n-2) def sum_series(n, x=0, y=1): ...
d5071d9e6bac66ad7feae9c7bdaafb086c562f0f
ARSimmons/IntroToPython
/Students/SSchwafel/session01/workinprogress_grid.py
1,630
4.28125
4
#!/usr/bin/python #characters_wide_tall = input('How many characters wide/tall do you want your box to be?: ') ## ## This code Works! - Commented to debug ## #def print_grid(box_dimensions): # # box_dimensions = int(box_dimensions) # # box_dimensions = (box_dimensions - 3)/2 # # print box_dimensions # # ...
37da6e5d8f0bd569cb5dd18b2d22b967cc918698
ARSimmons/IntroToPython
/Students/SSchwafel/session02/ack.py
1,413
4.03125
4
#!/usr/bin/python print """ This program performs Ackermann's Function, as defined by: A(m,n) = n+1 if m = 0 A(m-1) if m > 0 and n = 0 A(m-1, A(m, n-1)) if m > 0 and n > 0 """ m = raw_input("Please provide a value for m: ") n = raw_input("Please provide a value for n: ") m = int(m) n = ...
688ede91119829d5ec4b75452ef18a5a29d6bd29
akidescent/GWC2019
/numberWhile.py
1,018
4.25
4
#imports the ability to get a random number (we will learn more about this later!) from random import * #Generates a random integer. aRandomNumber = randint(1, 20) #set variable aRandomNumber to random integer (1-20) #can initialize any variable # For Testing: print(aRandomNumber) numGuesses = 0 while True: #set a ...
694c11011b30fe791dcc3dda50955d0a3610380f
Diogo-Miranda/Curso-Python-3
/exercicios/exercicio001-func.py
1,161
4.28125
4
""""" 1 - Crie uma função que exibe uma saudação com os parâmetros saudacao e nome """"" def saudacao(saudacao="Seja bem-vindo", nome="Diogo"): print(f'{saudacao} {nome}') saudacao("Olá", "Erika") """"" 2 - Crie uma função que recebe 3 números como parâmetros e exiba a soma entre eles """"" def sum(n1=0, n2=0, n3...
e6f8ad728761f86cd0c386274b973b79f1627fbb
Diogo-Miranda/Curso-Python-3
/aula002-print/aula002.py
470
3.859375
4
# Function print # print(123456) # print('Diogo', 'Araujo') # Por padrão será exibido com espaço print('Diogo', 'Araujo', sep='-') # Utiliza como separador o '-', pelo 'sep' # print('João', 'e', 'Maria', sep='-', end='') # 'end' evita quebra de linha print('João', 'e', 'Maria', sep='-', end='###') # 'end' evita que...
b7b9c629c2b6cff7847670fe6d5b8246c4561185
Diogo-Miranda/Curso-Python-3
/desafios/desafio003-validor-de-cpf.py
649
3.5625
4
cpf = ''.join((''.join(input("Informe o CPF (XXX.XXX.XXX-XX): ").split('.'))).split('-')) # Validar primeiro dígito firstSum = 0 for index, counter in enumerate(range(10, 1, -1)): firstSum += (int(cpf[index]) * counter) # print(f'{cpf[index]} * counter = {firstSum}') # Verificar primeiro dígito firstDigit = 1...
aaf79bf8be2cb6bc5ffff9eaf9359ad89b3c5721
Diogo-Miranda/Curso-Python-3
/aula001-comments/aula001.py
560
3.8125
4
# Isso é um comentário # Python é uma linguagem interpretada --> interpretador lê o código e "mostra" # !!! Da esquerda para direita, de cima para baixo !!!! # A cerquilha é ignorada pelo Python print('Linha 1') # Comentário na frente... Dar 2 espaços antes (PEP 8) # Falando sobre do que se trata essa linha print('L...
ff58e6494e52b91fe263ede7285051cf8b72efe1
Diogo-Miranda/Curso-Python-3
/aula005-operadores-aritmeticos/aula005.py
298
4.0625
4
""" +, -, *, /, //, **, %, () // -> Divisão inteira ** -> Exponenciação """ print("10*10:", 10*10) print("10+10:", 10+10) print("10**2:", 10**2) print("10-10:", 10-10) print("10//3:", 10//3) print("10%3:", 10 % 3) print("Diogo * 10", 10 * "Diogo ") print("Diogo" + " Araujo") # Concatenação
c8cfcca4a1dafe3c9b4bb95d10f55d9fcc7be39c
vc64/JottoRL
/jotto.py
743
3.578125
4
from mastermind import Mastermind from player import Player class Jotto: def getDictionary(): file = open("C:/Users/viche/Desktop/vc/code/JottoPy/raw_words.txt", "r") words = file.readlines() return [n[:-1] for n in words] def playGame(): dictionary = Jott...
34695558e746ecc0cf28f8b29d36a1bbd394607c
ishleigh/genuis
/ifState.py
130
3.984375
4
print ('What is your name?') myname = input() if myname == 'ash': print('Hello ash') else: print ('Hello stranger')
a6fec6831fb18fc4a52e275942b8a5a7f7c41533
ydieh/Cliente-Servidor
/servidor/servidor_tcp.py
1,063
3.71875
4
from socket import * #importamos la libreria socket #creamos el objeto socket socketServidor= socket(AF_INET,SOCK_STREAM) #establecemos la coneccion con el metodo bind este recibe una tupla posee el host y el puerto donde esta escuchando socketServidor.bind( ('localhost',21562) ) #establecemos la cantidad de peticiones...
cd63b35811dc77c215fb241b60e5d40bddb0b5cc
dimitri20/lSystem
/lSystem.py
3,171
3.734375
4
def intoList(str): return [ch for ch in str] def intoString(ls): a = '' for i in ls: a += i return a class lSystem: def __init__(self, axiom, rules): self.axiom = axiom # string self.rules = rules # rules in dictyonary A -> AB is the same as {'A':'AB'} ...
c6715969636e91454f9c8ee5a38270468e1547fd
znadrotowicz34/cmpt120nadrotowicz
/rover.py
256
3.53125
4
# rover.py # A program to calculate how long it takes a photo from Curiosity to reach NASA def main(): time = (34000000/186000) # Evaluates the distance in miles divided by the miles in seconds print("It will take " + str(time) + " seconds.") main()
418bbdc25d439c6d9f7e88f7c8d4127397bf0fc4
wiecodepython/Exercicios
/Exercicio 2/H0rus1/exercicio_semana2.py
491
3.5625
4
from math import pi, pow, sqrt #2 print (10%3) #3 print (13*0) print (13*1) print (13*2) print (13*3) print (13*4) print (13*5) print (13*6) print (13*7) print (13*8) print (13*9) #4 aula_semana=2 semana=4 meses=4 aulas_total= aula_semana * semana * meses aulas_minimo= aulas_total*0.75 print (aulas_minimo) #5 raio=2 a...
6a7ac03762ff46b3a6cc977aaa27bee21a46b880
wiecodepython/Exercicios
/Exercicio 2/lateixeiraa/exercicio_semana2.py
352
3.828125
4
import math #Questão 2. print(10%3) #Questão 3. print(13*0) print(13*1) print(13*2) print(13*3) print(13*4) print(13*5) print(13*6) print(13*7) print(13*8) print(13*9) print(13*10) #Questão 4. a=2*4 b=(a*75)/100 print(b) #Questão 5. a=3.14*(2**2) print(a) print("Hello world") #Questão 6. s=65*1000 t=17+(23*60)+(3...
4ff2b4316f03556cd8ef992efc1121b7e6c4fe18
wiecodepython/Exercicios
/Exercicio 2/AdrianneVer/Exercicio_Apostila.py
1,244
4.5625
5
# >> Python como Calculadora from math import pi, pow, sqrt print("Hello, world!") # Hello, world #------------------Operadores matemáticos---------------# # Operador Soma (+) print(3 + 5) print(9 + 12) print(7 + 32) print(4.5 + 7.3) print(7.9 + 18.2) print(3.6 + 34.1) # Operador Subtração (-) print(9-7) print(15-20...
5e2eb36a37be8745e4c16fbf6de0ff648fccadfc
wiecodepython/Exercicios
/Exercicio 2/AdrianneVer/Exercicio02.py
1,338
4.03125
4
#-------------Exercício 02 ------------------# from math import pi #1. Faça todos os exemplos da apostila da "Semana # 2". # Está no arquivo "Exercícios_Apostila" # 2. Calcule o restante da divisão de 10 por 3. print(10 % 3) # 3. Calcule uma tabuada do 13. for i in range(1,11): print( i, "x", 13,"=", i * 13) # ...
fb5a71f4da1a8dd3bef7a0cbeb4ca16b045a148d
BackupTheBerlios/guitarportfolio-svn
/trunk/gui/wikiparser.py
10,770
3.59375
4
import re import os.path import appcfg import viewmgr def maketable(page): """ Create table from || ... || syntax which is very convenient in simple markups to create a HTML table without much fuss Example: || this is a || table || || neat || huh || ...
2dc4a8e0af99819007fb58afc4c7cc785e6f096c
ddowns-afk/python
/problem_5.py
446
3.578125
4
import random #a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] #b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] #for item in set(a): # if item in set(b): # print(item) a = [] b = [] max_size = random.randint(5,100) max_size2 = random.randint(5,100) for i in range(max_size): a.append(random.randint(1,100)) ...
fd209e7a16173ea745027758da57d79b9501ca47
ddowns-afk/python
/problem_3.py
276
4.0625
4
#a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] #b = [] #for item in a: # if item < 5: # b.append(item) #print(b) a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] less_than = int(input('Enter a number: ')) for number in a: if number < less_than: print(number)
2cdbe4efaae07132f56ca0d213b50a10f5882504
Paramonov-Sergey/Tasks
/game.py
3,213
3.8125
4
from abc import ABC, abstractmethod from random import randint class Ishape(ABC): @abstractmethod def get_perimetr(self): # возврвщает периметр фигуры pass @abstractmethod def get_area(self): # возвращает площадь фигуры pass @abstractmethod def get_descriptio...
2dbeabf760fb71cb4d4c1745eac213b57eda3b6d
BugCatcherNate/voiceParse
/environment/lib/python3.6/site-packages/transcribe/utils.py
4,088
3.734375
4
# -*- coding: utf-8 -*- from __future__ import unicode_literals, division, print_function, absolute_import import datetime import re from datetime import timedelta class Time(timedelta): """Prints time in the format of HH:MM:SS, it will also parse values and normalize their values""" @property def min...
a26b5eba783751d5bb2d5a412a279798c747de87
paindespik/python
/perso/fonction.py
294
3.75
4
def Accueil(): print("Bonjour Aventurier") def CreerSonPersonnage(): pseudo = input("quel est ton nom?") race = "" while(race != "humain" or race != "nain" or race != "elfe" or race != "mage"): race = input("De quelle race es-tu? : (humain, nain, elfe, mage)") def
c7ea64496d03c1484840d9d206b1ecf4ca87c4da
Clery123/AOC2020
/Day4_Part1.py
406
3.75
4
def passport(): f = open("data.txt","r") count =0 password ="" checker =0 for line in f.readlines(): password+=line if(line=="\n"): if("byr:"in password and "iyr:" in password and "eyr:" in password and "hgt:" in password and "hcl:" in password and "ecl:" in password and ...
1afb65dc1e1ecd177f436facffa3cc76124e418c
Milesjpool/e-probs
/016.py
243
3.625
4
__author__ = 'Miles' def pow_sum(index): power = str(2**index) total = 0 for i in range(len(power)): total += int(power[i]) return total print(pow_sum(1000)) #Or in 1 line #print(sum([int(i) for i in str(2**1000)]))
312cd194432eb0712e402fb6a46d0c91b6e042fb
Milesjpool/e-probs
/004.py
396
3.59375
4
__author__ = 'Miles' def palindrome(): largest = 0 for x in range(100, 999): for y in range(100, 999): curr = x*y if palin_chk(curr) & (curr > largest): largest = curr return largest def palin_chk(number): rev = str(number)[::-1] if str(number) == ...
1b6459200c691ab68b0f13bee46351103c0d3af5
ZeHaoW/LeetCode
/728/Solution.py
582
3.515625
4
class Solution(object): def selfDividingNumbers(self, left, right): """ :type left: int :type right: int :rtype: List[int] """ res = [] for num in range(left, right + 1): flag = 1 ss = str(num) if '0' in ss:continue ...
2f0441a609d7cd10c09547e49778abd4789f0ac9
ZeHaoW/LeetCode
/88nice/Solution.py
833
3.59375
4
class Solution(object): def merge(self, nums1, m, nums2, n): del nums1[m:] del nums2[n:] print nums1, nums2 if m == 0: nums1.extend(nums2) print nums1 return tmp = 0 for i in nums2: for j in range(tmp, len(nums1)+1): if j == len(nums1): ...
a59f161f9c25f7172eb80e9b8954051bddc8a7a1
ZeHaoW/LeetCode
/342nice/Solution.py
621
3.75
4
class Solution(object): # 最普通的做法 def isPowerOfFour(self, num): """ :type num: int :rtype: bool """ if num <= 0 :return False while num != 1: if num % 4 != 0: return False num /= 4 print num return True ...
5e1f92db11669a87362f097fe00e6ab0db792273
ZeHaoW/LeetCode
/326/Solution.py
110
3.5625
4
class Solution(object): def isPowerOfThree(self, n): n = float(n) while n > 1: n = n/3 return n == 1
cc4b027439324cd10fc389296ae9f09f1e95ffa0
pcampeti/gwent
/gwent/utils.py
3,530
3.625
4
import astropy.units as u import numpy as np def make_quant(param, default_unit): """Convenience function to intialize a parameter as an astropy quantity. Parameters ---------- param : float, or Astropy Quantity Parameter to initialize default_unit : str Astropy unit string, sets a...
b22dfd9e830bfc051d947ac9b46fa443196759fa
steve7158/Python-test
/python/threading_test.py
369
3.515625
4
from threading import Thread import time i=0 def getnumber(Thread): while(True): i=i+1 def squaring(Thread): while(True): i=i**2 print(i) t1=getnumber() t2=squaring() # t1=threading.Thread(target=getnumber) # t2=threading.Thread(target=squaring) t1.start() t2.start() ...
ae3f10dfd5bd124e39ddc7c5b22519bfe31f2eb5
steve7158/Python-test
/python/test/list.py
638
3.671875
4
# word='akarsh s good boy' # str=word.split() # print(str) # # # for x in str: # newlist=list(x) # test=newlist.append('ay') # test.join() # print(test) # # print(newlist) # # nes='worf' # print(nes[0]) def pig(word): st = word.split() print(st) i=0 for err in st: first_l...
462d18a4f229d6ad3a7541b23243659137bd031a
steve7158/Python-test
/python/codechef.py
763
3.578125
4
# varible p1 # varible p2 # varible X # variable t # # input(x) alien = {'color': 'green', 'points': 5} print("The alien's color is " + alien['color']) fav_numbers = {'eric': 17, 'ever': 4} for name, number in fav_numbers.items(): print(name + ' loves ' + str(number)) print(fav_numbers.items()) for name,nu...
2b1f23f387fccd56cb01a32777889479a4177931
Pikomonto/IntroToHadoopUdacity
/Extra/index_by_student_mapper.py
1,147
3.90625
4
#!/usr/bin/python # this mapreduce program indexes all the nodes by student id import sys import csv # dictionary that contains the student id as the key and # a list of node ids as the value students = {} # use CSV reader for reading the TSV reader = csv.reader(sys.stdin, delimiter='\t') # skip the header next(r...
575824308970ab765d5a91e2fbc66faca596ec9d
Pikomonto/IntroToHadoopUdacity
/Extra/top10_scored_questions_reducer.py
1,072
3.640625
4
#!/usr/bin/python import sys import operator # dictionary that contains the question id as the key and # and its score as the value questions = {} # read from the output of mappers for line in sys.stdin: # divide the row using the tab as splitter data_mapped = line.strip().split("\t") # if there aren't exac...
5dc500f037289628af00e65f5001cf84c1ebdd60
DyogoBendo/Algoritmo-Teoria-Pratica
/Conceitos Básicos/bubblesort.py
338
3.921875
4
def bubblesort(a): for i in range(len(a)): for j in range(len(a) - 1, i, -1): if a[j] < a[j-1]: anterior = a[j] a[j] = a[j-1] a[j-1] = anterior if __name__ == '__main__': entrada = list(map(int, input().split(', '))) bubblesort(entrada) ...
7161fe4167bfe262a049e245f499bde157d75d69
DyogoBendo/Algoritmo-Teoria-Pratica
/Ordenação Linear/bucket-sort.py
555
3.5
4
import math from random import random def bucket_sort(A): n = len(A) B = [[] for _ in range(n)] for i in range(n): B[math.floor(n * A[i])].append(A[i]) # temos os baldes criados agora, e depois precisamos apenas ordenar cada balde individualmente, e concatená-los print(B) ...
afd0cd0a50fc33e4ff296d40502ed6146c5c73ee
DyogoBendo/Algoritmo-Teoria-Pratica
/Algoritmos Gulosos/seletor_atividades.py
1,536
3.65625
4
def recursive_activity_selector(a, r:list, k, n): m = k + 1 while m <= n and a[m]["start"] < a[k]["finish"]: # encontrar em Sk a primeira atividade que termina m += 1 if m <= n: r.append(a[m]) recursive_activity_selector(a,r, m, n) return r def greedy_activity_select...
39006dcc1fd07a74f69c9709efec9d5daa5e712e
snail15/CodingDojo
/Python/week3/Hospital/hospital.py
1,371
3.65625
4
class Patient(object): def __init__(self, id, name, allergies): self.id = id self.name = name self.allergies = allergies self.bedNumber = None class Hospital(object): def __init__(self, name, capacity): self.patients = [] self.name = name self.capacity = ...
e0d179d73498a579b25b847b8dd6021f2ba584b2
snail15/CodingDojo
/Python/week3/Functions/functions.py
625
3.96875
4
def oddoreven(): for i in range(1, 2001): oddeven = "" if i % 2 == 0: oddeven = "even" else: oddeven = "odd" print("Number is {0}. This is {1} number.".format(i, oddeven)) oddoreven() a = [2,4,10,16] def muliply(lst, val): for i in range(len(lst)): ...
1ccdd3c559bd039785d9cd6412000c4b4da8e73e
snail15/CodingDojo
/Python/week3/Car/car.py
581
3.6875
4
class Car(object): def __init__(self, price, speed, fuel, mileage): if price > 10000: self.tax = 0.15 else: self.tax = 0.12 self.price = price self.speed = speed self.fuel = fuel self.mileage = mileage self.displayAll() def displa...
6e53d955acd35f5f1da0fcdde636fa234e57bfcb
snail15/CodingDojo
/Python/week3/Dictionary/dictionary.py
227
4.375
4
dict = { "name": "Sungin", "country of birth": "Korea", "age": 30, "favorite language": "Korean" } def printdict(dict): for key in dict: print("My {0} is {1}".format(key, dict[key])) printdict(dict)
701e6139893470bd899773e763370a82d346c6f5
Miguel235711/Competitive-Programming-3-Solutions-by-Miguel-Mu-oz-
/Section 1.3.3/12403 - Save Setu/Python/main.py
197
3.546875
4
def main(): t,k = int(input()),0 for _ in range(0,t): lineT = input().split() if(lineT[0]=='donate'): k+= int(lineT[1]) else: print(k) main()
b0d05636b2fbe926c52cfc6445cbaa443a867ea7
EugeneStill/PythonCodeChallenges
/longest_increasing_subsequence.py
1,109
3.828125
4
import unittest class LongestIncreasingSubsequence(unittest.TestCase): """ Given an integer array nums, return the length of the longest strictly increasing subsequence. Input: nums = [10,9,2,5,3,7,101,18] Output: 4 Explanation: The longest increasing subsequence is [2,3,7,101], therefore the len...
2e2b58e032cff365376170d115d8a59f61933831
EugeneStill/PythonCodeChallenges
/task_scheduler.py
4,693
3.921875
4
import unittest from heapq import heappush, heappop from collections import Counter class LeastInterval(unittest.TestCase): """ Given a characters array tasks, representing the tasks a CPU needs to do, where each letter represents a different task. Tasks could be done in any order. Each task is done in one ...
82bfe904974ee729e320e9b9242b399381580756
EugeneStill/PythonCodeChallenges
/three_sum.py
1,808
4.0625
4
import unittest class ThreeSum(unittest.TestCase): """ Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0. The solution set must not contain duplicate triplets. Input: nums = [-1,0,1,2,-1,-4]...
42f6e8a1a8cbd172c92d6ba4ad7a115ac3982bb7
EugeneStill/PythonCodeChallenges
/open_the_lock.py
2,132
4.125
4
import unittest import collections # https://www.geeksforgeeks.org/deque-in-python/ class OpenTheLock(unittest.TestCase): """ You have a lock in front of you with 4 circular wheels. Each wheel has 10 slots: '0' through '9'. The wheels can rotate freely and wrap around: for example we can turn '9' to be '0...
29e646fbd9495c5b4c705058a2656267e40b5276
EugeneStill/PythonCodeChallenges
/string_to_int.py
2,393
4.0625
4
import unittest class MyAtoi(unittest.TestCase): """ Implement the myAtoi(string s) function, which converts a string to a 32-bit signed integer (similar to C/C++'s atoi function). The algorithm for myAtoi(string s) is as follows: Read in and ignore any leading whitespace. Check if the next char...
3ea411d749f483c8fd5c63ad0ac7fd8a5c8c0a01
EugeneStill/PythonCodeChallenges
/rotting_oranges.py
2,767
4.125
4
import unittest from collections import deque class OrangesRotting(unittest.TestCase): """ You are given an m x n grid where each cell can have one of three values: 0 representing an empty cell, 1 representing a fresh orange, or 2 representing a rotten orange. Every minute, any fresh orange t...
512f73f9a75a20524108b92cf150bab449d5b8f7
EugeneStill/PythonCodeChallenges
/ll_remove_nth_from_end.py
1,178
3.796875
4
import unittest import helpers.node as nd import helpers.linked_list as linked_list class LLRemoveNthFromEnd(unittest.TestCase): def remove_nth_from_end(self, head, n): # given the head of a linked list, remove the nth node from the end of the list and return its head. # Constraints: # Th...
f47d79346964ed555e0fd11fab38028e1d47545a
EugeneStill/PythonCodeChallenges
/archive/sumDiagonals.py
590
3.6875
4
def sum_diagonals(l1): total = 0 for i in range(len(l1)): if len(l1) % 2 == 1 and i == len(l1) // 2: total += l1[i][i] * 2 else: total += l1[i][i] + l1[i][-1 - i] print(total) return total list1 = [ [ 1, 2 ], [ 3, 4 ] ] sum_diagonals(list1) # 10 list2 = [ ...
8e7c24760f49dc43bd2fc82e24d1fa55adc6c79e
EugeneStill/PythonCodeChallenges
/climb_stairs.py
838
4.03125
4
import unittest class ClimbStairs(unittest.TestCase): def climb_stairs(self, n): """ :type n: int :rtype: int """ # memoization # memo = {} # memo[1] = 1 # memo[2] = 2 # # def climb(n): # if n in memo: # re...
9caaec3d474d8123e9999eb09fb55c4d4d05a5de
EugeneStill/PythonCodeChallenges
/my_pow.py
1,232
3.96875
4
import unittest class MyPow(unittest.TestCase): def my_pow(self, x, n): """ :type x: float :type n: int :rtype: float """ # Deal with negative exponents (returns fractions) if n < 0: x = 1 / x n = abs(n) # Iterate: r...
59a8864a5f317ead31eb8d93246776eed2342fec
EugeneStill/PythonCodeChallenges
/word_break_dp.py
1,621
4.125
4
import unittest class WordBreak(unittest.TestCase): """ Given a string s and a dictionary of strings wordDict, return true if s can be segmented into a space-separated sequence of one or more dictionary words. Note that the same word in the dictionary may be reused multiple times in the segmentation....
26d1d171bfa5feab074dd6dafef2335befbc4ca7
EugeneStill/PythonCodeChallenges
/unique_paths.py
2,367
4.28125
4
import unittest import math class UniquePaths(unittest.TestCase): """ There is a robot on an m x n grid. The robot is initially located at the top-left corner (i.e., grid[0][0]). The robot tries to move to the bottom-right corner (i.e., grid[m - 1][n - 1]). The robot can only move either down or right ...
b3debc6360defa49a91e882595af8af4512f3088
EugeneStill/PythonCodeChallenges
/combination_sum.py
3,426
3.859375
4
import unittest class CombinationSum(unittest.TestCase): def combination_sum(self, candidates, target): """ :type candidates: List[int] :type target: int :rtype: List[List[int]] """ res = [] print("\n") def dfs(target, index, path): print...
fdd5987f684a90e78ba5622fd37919c43951bd20
EugeneStill/PythonCodeChallenges
/course_prerequisites.py
2,711
4.34375
4
import unittest import collections class CoursePrereqs(unittest.TestCase): """ There are a total of num_courses courses you have to take, labeled from 0 to num_courses - 1. You are given an array prerequisites where prerequisites[i] = [ai, bi] meaning that you must take course bi first if you want to t...
efd75aa5cd6b702ce97d3d65891a3b6b04c4fc88
EugeneStill/PythonCodeChallenges
/ll_intersection.py
1,658
3.546875
4
import unittest import helpers.node as nd import helpers.linked_list as linked_list class LLIntersection(unittest.TestCase): def get_ll_intersection(self, head_a, head_b): # return node where 2 linked lists intersect (same node, not same value), else return null p1, p2 = head_a, head_b wh...
cdd94c864dbd014a91f8a644be0dcb3f0a953f29
EugeneStill/PythonCodeChallenges
/bubble_sort.py
5,066
4.3125
4
import unittest class bubbleSort(unittest.TestCase): """ According to Wikipedia "Bubble sort, sometimes referred to as sinking sort, is a simple sorting algorithm that repeatedly steps through the list to be sorted, compares each pair of adjacent items and swaps them if they are in the wrong order. Th...
197e86111f7b6a2f527cbb3821eea868f5854a14
EugeneStill/PythonCodeChallenges
/circular_queue.py
2,326
4.03125
4
import unittest # Implement the MyCircularQueue class: # # MyCircularQueue(k) Initializes the object with the size of the queue to be k. # int Front() Gets the front item from the queue. If the queue is empty, return -1. # int Rear() Gets the last item from the queue. If the queue is empty, return -1. # boolean enQueu...
57d16b965de6e4f82979f42656042af956145410
EugeneStill/PythonCodeChallenges
/reverse_polish_notation.py
2,516
4.21875
4
import unittest import operator class ReversePolishNotation(unittest.TestCase): """ AKA Polish postfix notation or simply postfix notation The valid operators are '+', '-', '*', and '/'. Each operand may be an integer or another expression. The division between two integers always truncates toward ...
927f6d21ef2e40c73584774e5552f5c9b20c7fa8
EugeneStill/PythonCodeChallenges
/valid_sudoku.py
3,247
4.09375
4
import unittest import collections class ValidSudoku(unittest.TestCase): """ Determine if a 9 x 9 Sudoku board is valid. Only the filled cells need to be validated according to the following rules: Each row must contain the digits 1-9 without repetition. Each column must contain the digits 1-9 without...
d6aee9df432eb39722be0826b2001b1ff7a5f443
EugeneStill/PythonCodeChallenges
/roman_to_int.py
692
3.65625
4
def romanToInt(s: str) -> int: vals = { 'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000, 'IV': 4, 'IX': 9, 'XL': 40, 'XC': 90, 'CD': 400, 'CM': 900 } end = len(s) total = i = 0 w...
5c23f52eb2173562f3bb3c1cb33453b9357a70a5
EugeneStill/PythonCodeChallenges
/ll_is_cycle.py
1,273
3.859375
4
import unittest import helpers.node as nd import helpers.linked_list as linked_list class LLCycle(unittest.TestCase): def is_ll_cycle(self, ll): # does linked list have a cycle (eg. tail points to node inside list) slow = fast = ll.head # if ll has no cycle then when there is no fast.next...
0c939767444695f6b1f57851892d7b8077950dd9
thekirjava/BSU
/Parallel computings/pythonProject/EllipticGroup.py
470
3.515625
4
class Point: def __init__(self, x, y): self.x = x self.y = y class EllipticGroup: def __init__(self, a, b, M): self.__a = a self.__b = b self.__M = M self.__points = self.__generatePoints() def __generatePoints(self): result = [] for i ...
47656bdd5d6b6f46cb957f38ecc32184198f9829
MariamBilal/python
/List.py
1,008
4.65625
5
# Making and Printing list my_list = ['fish','dog','cat','horse','frog','fox','parrot','goat'] print(my_list) #Using Individual Values from a List for i in my_list: print(i) #Accessing elements in a List print(my_list[0]) #To title the the items in list. print(my_list[2].title()) #To print last character from t...
34ea7ef5105281eeeab40bbde93544741ef061f8
tobias290/Dijkstras
/dijkstras_algorithm.py
9,963
4
4
from graph import Graph, Node, WeightedEdge from visit import Visit class Dijkstra: """ Dijkstra's shortest path algorithm """ def __init__(self, graph: Graph): """ Dijkstra initializer :param graph: The weighted graph to use for the algorithm """ s...
0b5665f9d3f0db2a0b851b3f8c737980161e3f32
TheCoffeMaker/BikeRental
/src_python/RentByHour.py
703
3.546875
4
from Rental import Rental import unittest class RentByHour(Rental): def __init__(self, quantity): self.setCost(5) self.setQuantity(quantity) def getTotalCost(self): return self.getCost() * self.getQuantity() class RentByHourTest(unittest.TestCase): def test_creation(self): ...
3687c04d9938c085358686d3cc5790895ca2e82c
whitelaw-josh/Py_DS_JW
/ML_Regression.py
2,996
3.59375
4
#x, y = Gapminder data # Import numpy and pandas import numpy as np import pandas as pd # Read the CSV file into a DataFrame: df df = pd.read_csv('gapminder.csv') # Create arrays for features and target variable y = df['life'].values X = df['fertility'].values # Print the dimensions of X and y before reshaping prin...
3b9ebdfb11e0faead0172d8d54a956a9f0d715e9
serrHendrik/MLP_workspace
/Task1/PLA.py
2,709
3.8125
4
# -*- coding: utf-8 -*- """ Created on Sat Mar 9 18:48:47 2019 @author: Hendrik Serruys """ """ Change the game_code (CTRL+F) to change the game: The Prisoner's Dilemma Game (0) The Matching Pennies Game (1) PLA: Probabilistic Learning Automata Implementation based on PROBABILISTIC LEARNING AUTOMATA (Kehagias), s...
b82bdeb20e5649734c71d429efef425a9fef3db1
luisdiaz9/python-challenge
/PyBank/main.py
1,570
3.515625
4
import os import csv from statistics import mean month = [] PAndL = [] PAndLChange = [] budget_csv = os.path.join( "budget_data.csv") with open(budget_csv, 'r') as csvfile: csvreader = csv.reader(csvfile, delimiter=',') csv_header = next(csvreader) for row in csvreader: month.append(row[0]) ...
dba76da6f026cc872d50512bd7adae4b8b04d88f
rshaver/python_experience
/ryan_shaver_project_one.py
5,226
4.3125
4
#### -----------------------0. MENU ---------------------- choice = 1 while ((choice == 1) or (choice == 2) or (choice == 3) or (choice == 4)): print () print ("-------------------------------") print ("Main Menu:") print ("1. Travel Time") print ("2. Cost of Gas") print ("3. Used Value") prin...
ace257dcc836fe88ca7345327c762b4c6ba144ec
codilty-in/math-series
/codewars/src/k_primes_most_upvoted.py
527
3.828125
4
"""Module to solve https://www.codewars.com/kata/k-primes/python.""" def count_Kprimes(k, start, end): return [n for n in range(start, end+1) if find_k(n) == k] def puzzle(s): a = count_Kprimes(1, 0, s) b = count_Kprimes(3, 0, s) c = count_Kprimes(7, 0, s) return sum(1 for x in a for y in b for ...
4bc82f2bdf496610241ad272ee9f76b69713c51d
codilty-in/math-series
/codewars/src/highest_bi_prime.py
1,100
4.1875
4
"""Module to solve https://www.codewars.com/kata/highest-number-with-two-prime-factors.""" def highest_biPrimefac(p1, p2, end): """Return a list with the highest number with prime factors p1 and p2, the exponent for the smaller prime and the exponent for the larger prime.""" given_primes = set([p1, p2]) ...
d20b15088e93c670f2ddd84ec8d2b78ad0d63199
codilty-in/math-series
/codewars/src/surrounding_prime.py
1,328
4.25
4
def eratosthenes_step2(n): """Return all primes up to and including n if n is a prime Since we know primes can't be even, we iterate in steps of 2.""" if n >= 2: yield 2 multiples = set() for i in range(3, n+1, 2): if i not in multiples: yield i multiples.updat...
7a291a64dea198b5050b83dc70f5e30bcf8876f5
codilty-in/math-series
/codewars/src/nthfib.py
524
4.1875
4
"""This module solves kata https://www.codewars.com/kata/n-th-fibonacci.""" def original_solution(n): """Return the nth fibonacci number.""" if n == 1: return 0 a, b = 0, 1 for i in range(1, n - 1): a, b = b, (a + b) return b #better solution def nth_fib(n): """Return the nth f...
a2b63bfd632c1a95435e3e675dc1da72677c152e
ryant030408/machine_learn
/scikit_learning/learning_SVC_predicting.py
641
3.546875
4
from sklearn import svm from sklearn import datasets #load dataset digits = datasets.load_digits() #SVC is an estimator class tha implements support vector classification #we set gamma value manually, but we can find good values automatically using grid search or cross validation clf = svm.SVC(gamma=0.001, C=100.) #c...
ab422e8642acc1232f1401f590ab9aa5c1408db2
solbol/python
/Lesson 4/Lesson 4.5.py
186
3.578125
4
from functools import reduce def my_func(prev_el, el): return prev_el * el my_list = [el for el in range(100, 1001) if el % 2 == 0] print(my_list) print(reduce(my_func, my_list))
962976fae682d60bdd70fccd0975c2209f89baa4
ytoo883/hello
/guessing game.py
331
3.921875
4
import random computers_number = random.randint(1,100) prompt = 'What is your guess? ' while True: players__guess = input(prompt) if computers_number == int(players__guess):# print('Correct!') break elif computers_number > int(players__guess): print('To low') else: print...
549c56a1351db27c644118d42bb7397d36599bc6
hinetg/99-CapstoneProject-201930
/src/m1_robot_code.py
3,434
3.65625
4
""" Capstone Project. Code to run on the EV3 robot (NOT on a laptop). Author: Your professors (for the framework) and Triston Hine. Spring term, 2018-2019. """ # DONE 1: Put your name in the above. import mqtt_remote_method_calls as mqtt import rosebot import m2_robot_code as m2 import m3_robot_code as m3...
9b4a1f7ef0879176a70ee0324c49914d24c76c80
achiengcindy/Lists
/append.py
347
4.375
4
# define a list of programming languages languages = ['java', 'python', 'perl', 'ruby', 'c#'] # append c languages.append('c') print(languages) # Output : ['java', 'python' ,'perl', 'ruby', 'c#', 'c'] # try something cool to find the last item, # use **negative index** to find the value of the last item print(language...
a6472666b4492832b2b5d7cc6e92329bd41ed9f3
Kalpavrikshika/python_modules
/numpy_nditer1.py
262
3.546875
4
import numpy as numpy a = numpy.arange(0,60,5) a = a.reshape(3,4) print ('Original array is:') print (a) print ('\n') print ('Transpose of original array is:') b = a.T print (b) print ('\n') print ('Modified array is:') for x in numpy.nditer(b): print (x)
7b007445fe03024abe23df2c305cc00ef15e5a74
Kalpavrikshika/python_modules
/decorators.py
320
3.859375
4
#returning functions from within functions def hi (name = "b"): def greet(): return ("Now you're in the greet() function") def welcome(): return ("Now you're in the welcome() function") if name == "yasoob": return greet else: return welcome a = hi() print(a) print(a())
bc61ed1661aea602e175547c978fd86355eb9f54
Kalpavrikshika/python_modules
/itertools_cycle.py
189
3.65625
4
'''cycle function returns an iterator that repeats the arguments. comsumes quite a bit of memory.''' from itertools import * for i in zip(range(7), cycle(['a', 'b', 'c'])): print(i)
a90d7f1f35ac62134113a2ff86543dca2475b7f2
Kalpavrikshika/python_modules
/map_1.py
168
3.78125
4
def multiply(x): return(x*x) def add(x): return (x+x) funcs = [multiply, add] for i in range(5): value = list(map(lambda x: x(i), funcs)) print(value)
1b568ea8e151946699b4f2cca200145c22c84dcc
Kalpavrikshika/python_modules
/reduce.py
230
3.828125
4
from functools import reduce # without reduce tool product = 1 list = [1, 2, 3, 4] for num in list: product = product * num print (product) #with reduce tool product = reduce((lambda x, y: x * y), [1,2,3,4]) print (product)
b268ea4c09ff7c6fd273416f176cd58b287908cb
Kalpavrikshika/python_modules
/itertools_zip.py
145
4.4375
4
#zip() returns an iterator that combines the elements for several iterators #into tuples. for i in zip([1, 2, 3], ['a', 'b', 'c']): print(i)
f67e4f6597ba7ddb16877514b7ff693c33037393
Kalpavrikshika/python_modules
/numpy_unique.py
781
3.734375
4
import numpy as numpy a = numpy.array([5,2,6,2,7,5,6,8,2,9]) print ('First array:') print(a) print('\n') print('Unique values of first array:') u = numpy.unique(a) print(u) print('\n') print('Unique array and indices array:') u, indices = numpy.unique(a, return_index = True) print (indices) print('\n') print('We ca...
3f6b96c926ba0a75c76d66a6159dcd22f7de5bdf
Kalpavrikshika/python_modules
/re_anchoring.py
673
3.578125
4
from re_testpattern import test_patterns test_patterns('This is some text -- with punctuation.', [ #^ anchors 'start of string, or line' (r'^\w+', 'word at start of the string'), #\A anchors 'start of string' (r'\A\w+', 'word at start of string'), #\w - alphanumeric \S - non-whitespace $ - end of string or line (r'\w+...
22f6661380854f99784da89ef255e6afab0cf3d7
Kalpavrikshika/python_modules
/numpy_slicing.py
239
3.84375
4
import numpy as numpy a = numpy.array([(1,2,3,4) , (3,4,5,6)]) print (a) #2 element of zeroth element print(a[0,2]) #2nd element of zeroth and first indec print(a[0: ,2]) b = numpy.array([(8,9), (10,11), (12,13)]) print(b) print(b[0:2,1])
0ad67b362805af46f8714824ef3d4faa5d00cfee
YI75/CSc59005_Challenges
/Question2/code_challenge2.py
712
3.6875
4
from typing import Annotated #Sample inpuit A = [1,2,3,4,5,6,6,7,8,9,10] #Binary Seach Function with Recursion def binarySearch(A,low,high,x): if high >= low: mid = (high + low)//2 if A[mid]==x: return mid elif A[mid] > x: return binarySearch(A, low, mid-1,x) ...
39de2d3985f181ff8cb48bcc5a1ec4b5b1ba3aec
ILYSHI/Python-code
/simple_drawings_wall.py
524
3.734375
4
import simple_draw as sd def brick(x,y): point1 = sd.get_point(x, y) point2 = sd.get_point(x + brick_lengh, y + brick_height) sd.rectangle(point1, point2, 'white', int(brick_lengh/20)) brick_lengh=20 brick_height=int(brick_lengh/2) limit=1000 sd.resolution = (limit, limit) sd.background_color = 'red' for...
636963a5fd32dd8c25dbc87efdb0dbbe412efaf5
ILYSHI/Python-code
/Наследование классов.py
300
3.625
4
import time class Loggable: def log(self, msg): print(str(time.ctime())+": " + str(msg)) class LoggableList(list,Loggable): def append(self,b): self.log(b) return super(LoggableList,self).append(b) z = LoggableList() z.append('Hello!') z.append('Good bye') print(z)
69eacf701d8fb7696b287a2ea0d222607dbe4937
ILYSHI/Python-code
/Задачки/Проверка анаграмм.py
229
3.5625
4
a = [i for i in input().lower()] b = [i for i in input().lower()] a.sort() b.sort() flag = True if len(a) == len(b): for i in range(len(a)): if a[i] != b[i]: flag = False else: flag = False print(flag)
7aa65b1cc3fdbd831a7a2a67389eeda6b3dd1318
kingsansuen/LPTHW
/Ex45/ex45.py
11,455
3.578125
4
from sys import exit import time import random from random import randint import threading class mainroom(object): def intro(self): print "Please select a game:" print "1. Guesting Number" print "2. Guesting Number (versus computer version)" print "3. Moster Fighter" playe...