blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
545k
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
545k
d3c9c7f16f82ad09053a7fe7a33dc27d7ac78d34
barclayiversen/algos
/python/rotateimage.py
954
3.859375
4
a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] def rotateImage(a): rotatedImage = [] row = [] for i in range(len(a)): #print (a[i][0]) row.insert(0,a[i][0]) print (row) rotatedImage.append(row) print (rotatedImage) row = [] for i in range(len(a)...
941776d2971ca71a8f4b18b3dbbe440636f1e102
Lucas-stk/Arredondar
/arredondar.py
378
4.09375
4
import math num = int(input('Digite um numero: ')) raiz = math.sqrt(num) print('A raiz de {} é igual a: {}\n'.format(num, raiz)) p = int(input('Se deu número com vírgula, informe seu número novamente para ser arredondado: ')) print('\n') print('A raiz arredondada do número {} é igual a: {}\n'.format(num, math.floor(ra...
2b47b550001583c7a0f60d8b2022051796d39ad5
utkpython/utkpython.github.io
/session3/simulation.py
733
4.3125
4
# modeling the idea that "students getting ahead in life" # some start off in a higher spot # some have more skill, some less from random import randint import matplotlib.pyplot as plt def rand_walk(numSteps, position, skill): '''Returns a random walk list of size numSteps + 1. position is the starting pos...
e8dfbd374a4e41b94e3e934442dd1e19b14c70f1
utkpython/utkpython.github.io
/session2/googleTranslate.py
1,245
3.59375
4
#make sure you have already downloaded the module we will be using, i.e. # use the terminal or cmd.exe if you're on windows and type # pip install translate from translate import Translator abbreviations = {"Chinese": "zh", "Russian": "ru", "German": "de", "French": "fr",...
9f04f5a4f5617fe61474ad8603ac40e1d36dd56c
utkpython/utkpython.github.io
/session5/text_twist.py
1,502
3.53125
4
#!/usr/bin/env python from itertools import permutations f = open("dict.txt") i = 1 l = list() for line in f: stripped = line.rstrip("\r\n\t").lower() if ('\'' in stripped or len(stripped) not in range(1,7)): continue else: l.append(stripped) #print "Adding item " + str(i) ...
8837ef923fee380f553692e3c1a54d0688b63204
Giandomenico-bit/no_term
/TheSum.py
1,040
3.953125
4
# Si scriva un programma Python che, dopo aver chiesto all'utente # di inserire un numero intero da tastiera, lo sommi ad un altro # intero letto da un file di testo sum.dat. Infine aggiorni il # file sum.dat con il nuovo valore. Il programma tenga conto # del caso in cui il file sum.dat non esista. # Prima di aprire...
054e7e1c9593bf37a99438bce174cf2b1c05eb92
brojass/restaurant_eva
/MiniProyecto3_DSP/main.py
2,108
3.5
4
from random import seed, randint, choice, sample from restaurante import Restaurante from personas import Cliente, Cocinero, Repartidor ################################################################ ## No debe modificar nada en este archivo. ## Este archivo debe ser ejecutado para probar el funcionamiento ## ...
54e0970ec836655490bf75aa1e01dd03f5ea76e4
franghie/pytutorial
/ref_value_demo.py
595
3.703125
4
# All variable is a reference. In order to write a value, need to dereference. Scalar -> Need to use key or index llist = [['a', 'b'], ['c'], ['d', 'e']] for loc in llist: loc = ['a','b','c'] print(llist) llist = [['a', 'b'], ['c'], ['d', 'e']] for loc in llist: loc[0] = '1' print(llist) m = {'a'...
aee386e155e158d2e6265d991460a8dd22c5ae5b
mjanny1/TourneyPicker
/PrintBracket.py
3,999
3.96875
4
#!/usr/local/bin/python3 import json import collections """ main() round_of_64: list of teams in the round of 64 round_of_32: list of teams in the round of 32 sweet16: list of teams in the sweet 16 elite8: list of teams in the elite 8 final4: list of teams in the final 4 champion...
dcaa6a72ffbaa004429d64a153ba7442b1c231dd
PouringRain/Algorithmn
/18 Autumn recruit/bilibili/笔试_3.py
920
3.734375
4
# 结果:ac #!/bin/python # -*- coding: utf8 -*- import sys import os import re # 请完成下面这个函数,实现题目要求的功能 # 当然,你也可以不按照下面这个模板来作答,完全按照自己的想法来 ^-^ # ******************************开始写代码****************************** def compareVersionNumber(v1:str, v2:str): v1 = v1.split('.') v2 = v2.split('.') size1, size2 = len(...
aaee060f7c4e975723877e2ae20e3cee4b421fd7
PouringRain/Algorithmn
/48.py
1,510
3.75
4
# -*- coding:utf-8 -*- class Solution: def hasPath(self, matrix, rows, cols, path): # write code here def backtrack(matrix, i, j, curlen, path, mark): # print(mark) if i >= 0 and i < rows and j >= 0 and j < cols and matrix[i][j] == path[curlen] and mark[i][j]: ...
0d28fc589d7b6faad136c3d8d99c12669d8b04ae
PouringRain/Algorithmn
/7.py
304
3.640625
4
# -*- coding:utf-8 -*- class Solution: def jumpFloorII(self, number): # write code here if number==1 or number==0: return 1 if number==2: return 2 ans = 0 for i in range(number): ans+=self.jumpFloorII(i) return ans
b383b7a7dc2f92c6769850766a82e35281e7c2cd
PouringRain/Algorithmn
/46.py
507
3.6875
4
# -*- coding:utf-8 -*- class Solution: # 返回对应char def __init__(self): self.d = {} self.q = [] def FirstAppearingOnce(self): # write code here while self.q and self.d[self.q[0]]>1: self.q.pop(0) return self.q[0] if self.q else '#' def Insert(self, char)...
db55e3299e11401a3b59952024f27f7125a84648
PouringRain/Algorithmn
/9.py
468
3.5
4
# -*- coding:utf-8 -*- class Solution: def StrToInt(self, s): # write code here positive = 1; start = 0 lenth = len(s) res = 0 if lenth==0: return 0 #长度非法 if s[0]=='-': positive=-1 start = 1 if s[0]=='-' or s[0]=='+' else 0 for i in range(start, lenth)...
1f2bc5dc6ef4bfea807c23e3d45f792187e62fcc
SamuraiSigma/secret-santa
/secret_santa/santa/person.py
2,110
3.578125
4
"""Contains the Person class.""" from mail.mail_util import MailUtil class Person: """Represents a person participating in a Secret Santa event.""" def __init__(self, name, email, santa=None): """Initialize a Person object with the given attributes. Args: name: The person's nam...
baf7e5ff23326b4f927c0f1ae01f7b005a8e4291
CatboyCodes/The-Great-Turtle-Race
/turtle_race.py
1,215
3.921875
4
from turtle import * from random import randint speed() penup() goto(-140, 140) for step in range(15): write(step, align='center') right(90) for num in range(8): penup() backward(160) left(90) forward(20) ruby = Turtle() ruby.color("red") ruby.s...
c554bb6302dd44207de2c3cfaf13d016795ca4b2
pvkc8888/python-testprograms
/Algos Hackerrank/Strings/Anagram.py
988
3.8125
4
#!/bin/python3 import sys def anagram(s): if len(s) % 2 != 0: return -1 else: s1 = s[:len(s) // 2] s2 = s[len(s) // 2:] count = 0 Dict1 = {} Dict2 = {} # I thought i ll make two seperate dictionaries and count the common elements and subrtact it from th...
30b54859974a484100f00e3e679b55844d5021d7
pvkc8888/python-testprograms
/Algos Hackerrank/Strings/Gemstones.py
685
3.859375
4
#!/bin/python3 import sys # making set of the smallest string and checking if each character in that set exists in all the strings def gemstones(arr): minn = len(arr[0]) temp = '' for item in arr: if len(item) < minn: minn = len(item) temp = item sett = set(temp) ...
c0818c3f423ca95c4d06e928b3f499c1874018a8
pvkc8888/python-testprograms
/AutomatetheBoringStuff/Table_printer.py
508
3.71875
4
def PrintTable(tableData,maximum): for i in range(len(tableData[1])): for y in range(len(tableData)): print(tableData[y][i].rjust(maximum),end = " ") print("\n") tableData = [['apples', 'oranges', 'cherries', 'banana'], ['Alice', 'Bob', 'Carol', 'David'], ['dogs', 'cats', 'moose', 'g...
3fab4d91b10adc64cdfa0c81902e76598727f20d
pvkc8888/python-testprograms
/Algos Hackerrank/Warmup/Simple_Array_Sum.py
254
3.515625
4
#!/bin/python3 import sys def simpleArraySum(n, ar): total=0 for i in range(n): total = total+ar[i] return total n = int(input().strip()) ar = list(map(int, input().strip().split(' '))) result = simpleArraySum(n, ar) print(result)
f70b91de8207a202bede56b8263df0c95f7a7ac9
tonypdl/med_insurance_project
/script.py
7,375
3.5625
4
import csv import matplotlib.pyplot as plt with open("insurance.csv") as insurance_csv: insurance_dict = csv.DictReader(insurance_csv) # lists for each column age_list = [] sex_list = [] bmi_list = [] children_list = [] smoker_list = [] region_list = [] charges_list = [] for row...
649d01f961f988a352fdc04f20e2200f23afdc83
brianfong96/Logi-Helper
/common.py
592
3.625
4
import csv TEST_FILE = "test.csv" def isT(s): return s == 'T' def make_truth_table(f = TEST_FILE): with open(f) as csv_file: csv_reader = csv.reader(csv_file, delimiter=',') table = list() var = list() line_count = 0 for row in csv_reader: if line_count...
1a8ea5fd38814acccef18a034c45a807729fed24
victorpuerta/Python-Bootcamp
/Milestone Project/Game.py
5,965
3.90625
4
from random import shuffle from Card import * from Player import * class Game(): game = False cards = Card() deck = [] player2 = Player("Dealer") player1 = '' value_player1 = 0 value_player2 = 0 player_win = '' ''' /////////////////////////////////////////////// ...
1358dc77efa139cca90ea716628bf81c087cb5bd
federicodiazgerstner/ejercicios-programacion
/Ejercicios/Ejercicio 1.08.py
1,725
3.796875
4
def diadelasemana(dia,mes,año): if mes < 3: mes = mes + 10 año = año - 1 else: mes = mes - 2 siglo = año // 100 año2 = año % 100 diasem = (((26*mes-2)//10)+dia+año2+(año2//4)+(siglo//4)-(2*siglo))%7 if diasem < 0: diasem = diasem + 7 return diasem ...
804802ad78dec61a39763abbddb50da78cc1be58
federicodiazgerstner/ejercicios-programacion
/Ejercicios/Ejercicio 3.02f.py
856
3.546875
4
def creamatriz(n): filas = n columnas = n matriz = [] for f in range(filas): matriz.append([0] * columnas) return matriz def rellenamatriz(matriz): number = 1 for i in range(0, len(matriz)): # recorre filas counter = 0 # recorre columnas de últ...
d1253a1f63c4dbc6649066222df2df137c85cae2
federicodiazgerstner/ejercicios-programacion
/Ejercicios/Ejercicio 3.03.py
1,219
3.796875
4
import random def creamatriz(n): matriz = [] filas = n columnas = n for f in range(filas): matriz.append([0] *columnas) return matriz def rellena_matriz(matriz): largo = len(matriz) numbers = [] while len(numbers) < largo**2: fo...
c200895eecf26d39c4398457e3617d5045bea81c
federicodiazgerstner/ejercicios-programacion
/Ejercicios/Ejercicio 1.01.py
889
3.921875
4
def retornaMayorEstricto(a, b, c): """Toma tres valores y retorna el mayor estricto, o -1 de no existir / no ser estricto.""" mayor = -1 if a == b: return mayor elif a == c: return mayor elif b == c: return mayor else: if a > b: if a > c: ...
651d82a6cfb23944c2cf4872d714adaea6a99a9f
joyvai/Python-
/bagels.py
5,472
4.15625
4
# Bagels is a deduction game. # you are asking for 3-digit number with no repeating digits # and try to guess what the number is. # your opponent or computer gives you three clues: # Bagels = it means your three digits doesn't match the secret number # Pico = it means in your three digits one digit match the secret num...
1ae5d1eb7c5408cedc29486dbe1ee36a2a0df77c
joyvai/Python-
/stopwatch.py
1,615
4.28125
4
# stopwatch.py - A simple stopwatch program. # The stopwatch program will need to use the current time, so you will want to # import the time module. Your program should also print some brief instruc- # tions to the user before calling input() , so the timer can begin after the user # presses enter . Then the code will...
367e6b00d682b69e439b6ea1fe513ab2a013093f
joyvai/Python-
/hobby.py
99
3.609375
4
hobbies = [] for i in range(3): hobby = raw_input() hobbies.append(hobby) i += 1 print hobbies
4cb0e6419406286e87f84ece09c9baff8bd3cb5b
joyvai/Python-
/leapYear.py
590
4.15625
4
""" if (year is not divisible by 4) then (it is a common year) else if (year is not divisible by 100) then (it is a leap year) else if (year is not divisible by 400) then (it is a common year) """ def is_leap_year2(year): if year % 4 == 0: return True elif year % 100 == 1 : return False elif year % 400 =...
c7d9c05d7399a23938437d446aded16fc5bf74e5
joyvai/Python-
/power.py
99
3.5625
4
def power(x, n): result = 1 for i in range(n): result = result * x return result power(2,10)
77f124b59570ff9adf0e6c2ae20b726baa3e7fb4
joyvai/Python-
/OOP/classThree.py
510
3.859375
4
class Point: def __init__(self,x=0,y=0): self.x = x self.y = y def __del__(self): class_name = self.__class__.__name__ print class_name, "destroyed" pt1 = Point() pt2 = pt1 # pt2 = Point() pt3 = pt1 # pt3 = Point() print id(pt1), id(pt2),id(pt3) del pt1 del pt2 del pt3 class AnotherPoint: def __init__...
484f12a72bd38511751e533c0cff1fa2f5c8bab3
joyvai/Python-
/coinFlips.py
691
3.921875
4
from random import randint print ('I will flip a coin 1000 times.guess how many times it will come up heads.(Press enter to begin)') flips = 0 heads = 0 while flips < 1000: if randint (0,1) == 1: heads += 1 flips += 1 if flips == 900: print ( '900 flips and there have been ' + str(heads) + ...
1937e3f7cfc203bb9d7dba81a125934c3101cab9
joyvai/Python-
/guessTheNumberBook.py
517
3.859375
4
import random secretNumber = random.randint(1,20) print 'I am thinking of a number between 1 and 20.' for guessesTaken in range (1,7): print 'Take a guess.' guess = int(raw_input()) if guess < secretNumber: print 'your guess is too high.' elif guess > secretNumber: print 'Your guess is too high.' else: br...
5271871b1d83a2238c69103754aa804c222cfa01
joyvai/Python-
/classTHREE.py
265
3.59375
4
class Dog: tricks = [] def __init__(self,name): self.name = name self.tricks.append(name) def add_trick (self,trick): self.tricks.append(trick) d = Dog('dula') e = Dog('kuyr') d.add_trick('rool over') e.add_trick('tommy') print e.tricks print d.tricks
719c58919b58454e26a5413a131d23eb5712d812
suhailnajeeb/numerical-methods
/problem solutions/steepAsc.py
1,858
3.6875
4
from sympy import Symbol, Derivative from sympy.solvers import solve x = Symbol('x') y = Symbol('y') h = Symbol('h') #f = 2*x**2 - y + 3*x*y #values = (2,3) f = 3*x**2 - 2*y + x*y values = (2,1) def printline(): print('---------------------------------------------------------------------------------------') def s...
530fe5b55fe23ad17ac63c31fd7ccba2c2371a27
aaronBurns59/3rd-year-functions-python
/printList.py
404
4.40625
4
def printList(l): for x in l: print(x) list1 = [0,1,2,3,4,5,6,7,8,9,10] list2 = ['apple', 'orange', 'banana', 'pear', 'kiwi'] list3 = [0.1,2.0,3.3,4.5,8.5] choice = 0 while choice <= 0 or choice > 3: choice = int(input("Enter which list you want 1, 2 or 3: ")) if choice == 1: list = list1 elif ...
b06ef7146098feee3b49a67c411707b7805e534d
jchan221/CIS_2348_HW_3
/CIS_2348_10_15.py
910
3.953125
4
# Joshua Chan # 1588459 class Team: def __init__(self, name=None, team_wins=0, team_losses=0): self.name = name self.team_wins = team_wins self.team_losses = team_losses # The arguments are defined in the function above def get_win_percentage(self): result = self.team_wi...
c643875b3f5b48f71f59b6b43c6ba0e4186aaa86
arrayatsabitah/mongga
/modul.py
1,620
4.1875
4
# suatu objek dikatakan class jika punya atribut __init__ class orang: def __init__(self, nama, umur): #init tu ngejelasin tentang saya (self) self.nama = nama self.umur = umur # kayak buat ngenalin diri sendiri def jalan(self): print('orang jalan') def makan(self): ...
35460762532927939d78ef54a5aa3383133ce9b0
nadasal/markov_sentence_generator
/src/markov.py
3,506
3.875
4
# coding: utf-8 # In[130]: import random import re class markov(object): ''' A class that takes in a file and returns a sentence of a specified size generated using a Markov Chain markov contains 4 functions: words_from_file, triples, model, text...
e1e38cb6958d17fcd4a6fbd0d882366073206c41
SamNadjari/Algorithms
/closest_pair.py
4,019
4.0625
4
""" Sam Nadjari san7st Resources: https://www.programiz.com/python-programming/methods/list/sort Intro to Algorithms, Cormen et. al. Collaborators: Emily Nguyen """ import math import statistics as st def closest_pair_distance(file_data): file_data = file_data[1:] # convert file_data to a list of p...
0171ed375d5a918c433fb91b81ffa946df01bc68
BlackGrain/Test
/test.py
479
3.71875
4
import random a = "aaa" b = "456" c = "789" print(a + b) print("123" + "31232") d = "1234{}{}" print(d.format(a, c)) print(f"1234{a}{c}") print("------------------") a = random.randint(1, 100) number = input("input your number:") while True: number = int(number) if number == a: print("OK!") br...
fece97695eb63d2360d2bece67fe122ab4b2eace
BlackGrain/Test
/base_python/game/game.py
428
3.59375
4
class Game: def __init__(self, hp, power): self.hp = hp self.power = power def fight(self, enemy_hp, enemy_power): final_hp = self.hp - enemy_power enemy_fianl_hp = enemy_hp - self.power if final_hp > enemy_fianl_hp: print("I WIN!") elif final_hp > en...
53428eded49f679c51ea1bb77eba57e88e6cbeb8
BlackGrain/Test
/try.py
442
3.890625
4
try: num1 = int(input("input a number:")) num2 = int(input("input a numder:")) print(num1 / num2) except ZeroDivisionError: print("this is a except") except ValueError: print("error") else: print("none error") finally: print("--------------------") class MyException(Exception): def __i...
595c9c1d884fbf1c7351dbad937db3a0c02d439f
Nickum32/1133Lab6
/letterFreq.py
337
3.5625
4
punctuation="""' !@#$%^&*()1234567890,.?:;-[]_{}+=" """ my_file = input('enter the name of the file you qould like to check for word frequencies: ') fObj=open(my_file, 'r') my_string=fObj.read().replace('\n','') d = {} my_string=my_string.lower() for ch in my_string: if ch.isalpha(): d[ch] = d.get(ch, ...
9c3609c8b3aac28343445b212bbd4a15efe90ad2
vmcustodio/exercicios-python
/ex016.py
195
3.640625
4
salario = float(input('digite o valor do salario')) aumento = float(salario*0.15) nvsalario = float(salario+ aumento) print (' o valor do seu novo salario com o aumento de 15% é de:', nvsalario)
b82acbec54c9d49722564e0790ba96cbdc684bf0
vmcustodio/exercicios-python
/ex039.py
123
3.859375
4
nome = str(input('qual é seu nome?')) if nome == 'vanessa': print('que nome lindo!') else: print('bom dia', nome)
defbcc0600fcfc6daf4788cde184810e6b5346a1
vmcustodio/exercicios-python
/ex063.py
1,058
3.9375
4
#crie um programa que faça o computador jogar jokenpo com voce from random import randint itens = ('pedra', 'papel','tesoura') computador = randint(0,2) print('''ESCOLHA SUA JOGADA [0] pedra [1] papel [2] tesoura''') jogador = int(input('qual é sua jogada?')) print('-='*11) print('computador jogou {}'.format(itens[comp...
9ede3d9e62bceb5b524ede01671cb25446e10d01
vmcustodio/exercicios-python
/ex045.py
233
3.875
4
#faça um programa que leia um ano qualquer e mostre se ele é bissexto ano = int(input('digite um ano: ')) if (ano%4)==0 and (ano%400)==0: print('é um ano bissexto') else: (ano%100)==0 print('não é um ano bissexto')
1800aef3cb968897e3c59dfc2e621c2179407301
vmcustodio/exercicios-python
/ex071.py
298
3.984375
4
#desensvolva um programa que leia seis numeros inteiros e mostre a soma apenas daqueles que forem pares. se o valor digitado for impar, desconsidere-o soma = 0 for c in range (1,7): a = int(input('Digite um numero: ')) if a%2==0: soma += a print('A soma dos numeros pares é', soma)
a9758d30dfc4a4f01334272795325a7eb35e9733
vmcustodio/exercicios-python
/ex070.py
178
4.03125
4
#mostre a tabuada de um numero que o usuario escolher c = int(input('Digite um numero para saber sua tabuada: ')) for a in range (1,11): print('{} X {} = {}'.format(c,a,c*a))
ab5f02319cbd4c648f9f16c53fc07d0155731691
vmcustodio/exercicios-python
/ex060.py
625
4.0625
4
#triangulos, acrescentando o recurso de mostrar que tipo de triangulo sera formado: #equilatero:todos os lados iguais, isosceles, dois lados iguais, escaleno:todos os lados diferentes r1 = float (input('primeiro segmento: ')) r2 = float (input('segundo segmento: ')) r3 = float (input('terceiro segmento: ')) if r1 < r2 ...
1b1256fe48539050e39bc57e8e99ed13ce902e33
dantrim/dantrimania
/python/analysis/utility/plotting/m_py/scatterplot_matrix.py
3,573
3.859375
4
# coding: utf-8 """ Create a scatter-plot matrix using Matplotlib. """ from __future__ import division #, print_function #__author__ = "adrn <adrn@astro.columbia.edu>" # Standard library import os, sys # Third-party import numpy as np import dantrimania.python.analysis.utility.utils.plib_utils as plib plt = plib.i...
49a5c8340a23a0179d5d2c32c23e44e41d135c73
logancyang/yang-sentiment
/config.py
1,771
3.59375
4
""" A Pythonic config for yaml config file """ import json import yaml """ Handling configs for the service """ class BaseConfig: """ A base class for all Configs """ @classmethod def from_file(cls, filename: str) -> 'Config': """ Create a Config object from a file. Should be either yaml...
fa04caeba5337d320f650e41eba4a2db84b30ef2
Darbar937/pyscripts
/Random.py
1,423
3.953125
4
from random import randint while True: print("0===============0===========0===========0") print("¦ Random Number ¦ Roll Dice ¦ Flip Coin ¦") print("¦ (1) ¦ (2) ¦(3) ¦") print("0===============0===========0===========0") choice = input("Select an option ") if choice == "1...
4ae404c3dbd2e4dba615b7ecf4499c42a054f17d
Darbar937/pyscripts
/Mathematical/happy primes.py
1,378
3.703125
4
n1 = 0 n2 = 0 n3 = 0 n4 = 0 n5 = 0 n6 = 0 while True: print("+-*/=Happy Primes=/*-+") print("For help press enter.") number = input("Prime ") if number == "": print("Enter a number to see if it is prime or enter a prime to see if it is a happy prime. If it is not a happy prime it wont do anyth...
7a0266668c43b9820983c5706746a28d8e3cd39c
Eternity612/Python_notes
/01基础/05函数-下/07-名片管理系统-函数版.py
2,229
3.765625
4
#用来存储名片 card_info = [] def print_menu(): """打印菜单""" #1.打印功能提示 print("="*50) print(" 名片管理系统 v0.01") print("1.添加一个新名片") print("2.删除一个名片") print("3.修改一个名片") print("4.查询一个名片") print("5.显示所有的名片") print("6.退出系统") print("="*50) def add_new_card_info(): """新增名片""" new_n...
46c08356aa547145d970511308bb34a555d545f6
TheMajkySK/Learning
/Python programs/Grafika/9.3_ciary_for.py
179
3.5
4
import tkinter canvas = tkinter.Canvas(width = 1280, height = 720) canvas.pack() x = 10 for i in range(1,11): canvas.create_line(x, 100, x, 100) x += 10 canvas.mainloop()
33259a883d63574796e97da9ce598369b1dcd4f2
TheMajkySK/Learning
/Python programs/Noob level/uloha1.py
142
3.53125
4
a = float(input("Zadaj eurá: ")) b = float(25) * a print("Suma", a, "EUR je", b, "CZK") print() input("Stlač ENTER pre zatvorenie programu")
123dbc714b71100874c8ef7440a6604dd4ab34ae
TheMajkySK/Learning
/Python programs/Lvl 1 crook/26_kvadratickarovnica.py
1,401
3.890625
4
import math a = float(input("Zadaj a = ")) b = float(input("Zadaj b = ")) c = float(input("Zadaj c = ")) D = b ** 2 - (4 * a * c) """ if D < 0: print("Kvadratická rovnica nemá riešenie") else: if D == 0: # = je priradovaci prikaz, == sa pouziva na porovnavanie print("Kvadratická rovnica má ...
addc6b8efc81c9f8af541c0c629d49b6d36a3003
TheMajkySK/Learning
/Python programs/Lvl 1 crook/18_pyramidka3.py
253
3.828125
4
n = int(input("Zadaj počet riadkov: ")) for r in range(1, n + 1): for m in range(1, n - r + 1): print(" ", end = "") for h in range (1, r + 1): print("*", end="") print() print() input("Stlač ENTER pre ukončenie programu")
14f7aba4485c0bc4634699bebb13c5391cf615bf
TheMajkySK/Learning
/Python programs/Lvl 1 crook/42_rozklad_prvočísla.py
347
3.515625
4
""" vstup - číslo výstup - prvociselny rozklad čísla c = 56 56|2 28|2 14|2 7|7 1| """ cislo = int(input("Zadaj číslo a ja ho rozložím na prvočísla: ")) p = 2 while cislo > 1: if cislo % p == 0: if cislo <= 1: print(p) else: print(p, end="*") cislo //= p else...
bfac5338d0d6ffae85ab801d3ffe693fcbb7d0d8
TheMajkySK/Learning
/Python programs/Lvl 1 crook/1_cyklusinput.py
230
3.609375
4
n = int(input("Zadaj n: ")) sucet = 0 for i in range(n): #premenna i sa automaticky mení podla toho kolko krat cyklus prebehol sucet = sucet + i print("Súčet =", sucet) print() input("Stlač ENTER pre ukončenie programu")
12d96a4340c5add17425f815d86db7f39d2f63d7
TheMajkySK/Learning
/Python programs/Gettin harder/22_zoznam_dlzka.py
916
3.75
4
""" program vygeneruje postupnost reťazcov nahodenj dlzky z intervalju (1,20) vytvorte funkciu ktora bude mat ako parameter dany zoznam vystup funkice bude novy zoznamktory bude obsahovat dlzky stringov ktory bude obsahovať dlžky stringov daneho zoznamu """ import random def nahodne_slovo(): dlzka = random.randint...
d3f5fcca45a1c1184e12b3776c2864ab0ff2cb85
TheMajkySK/Learning
/Python programs/Lvl 1 crook/39_druha_odmocnina.py
292
3.65625
4
""" zistite druhu odmocninu cisla x bez volania funkcie math.sqrt(x) """ cislo = int(input("Zadaj číslo na odmocnienie: ")) a = 0 pocitadlo = 0 while a**2 < cislo: pocitadlo += 1 a += 0.01 print(f"Druhá odmocnina čísla {cislo} = {a}") print(f"Cyklus prebehol {pocitadlo}-krát")
3b0c41272207dec947831fd37ce031b258160398
fobbytommy/Algorithm-Practice
/10_week_2/smarter_sum.py
191
3.96875
4
sumArr = [0]; def smarter_sum(num): if num < 0: return None while len(sumArr) <= num: sumArr.append(sumArr[len(sumArr) - 1] + len(sumArr)) return sumArr[num] print(smarter_sum(3))
5c93d0b60d842cf06ecbb78f757900da1e3e25aa
fobbytommy/Algorithm-Practice
/09_week_1/insertAt.py
318
3.953125
4
# insertAt arr = [1, 2, 4, 5] def insertAt(arr, index, val): idx = len(arr) arr.append(0) # to prevent IndexError: list assignment index out of range if index < 0: index = 0 elif index > idx: index = idx for i in range(idx, index, -1): arr[i] = arr[i-1] arr[index] = val insertAt(arr, 2, 3) print(arr)
7412acf2022c4a9509ddd22859ba8f85422abf57
fobbytommy/Algorithm-Practice
/10_week_2/nth_largest.py
386
4.34375
4
# Given an array, return the Nth-largest element from python_modules import bubble_sort def nth_largest(arr, n): list_length = len(arr) if n <= 0 or list_length < n: return None sorted_arr = arr bubble_sort.bubble_sort(sorted_arr) return sorted_arr[list_length - n] arr = [23, 32, -2 , 6 ,2 ,7, 10, 3, 10, ...
8f4667338e761fca8b77a813d4f5ee957e0cbaa0
Akansha0211/Basics-of-try-except-revision
/Basics of try-except.py
1,461
4.1875
4
'''num1=input("Enter the first number \n") num2=input("Enter the second number \n") try: print("the sum of twoi numbers is", int(num1) + int(num2)) except Exception as e: print(e) print("This line is very important")''' #Will never come in except block '''a=[1,2,3] try: print("second element",...
7fa8a60d59174caffa40cfcb67474c8cdd7a1c30
Niccolum/intrst_algrms
/unpacking_flatten_lists/data.py
4,828
3.6875
4
import math import sys from typing import List, Dict, Tuple, Union, Iterator Num = Union[int, float] sys.setrecursionlimit(11000) def create_data_decreasing_depth( data: Union[List, Iterator], length: int, max_depth: int, _current_depth: int = None, _result: List = None ) -> L...
0fd73b873df2b08ee52c5ae9cb11f966cd05398e
poojan124/Competitive
/chess_ood_python/main_file.py
3,806
3.5
4
from abc import abstractmethod, ABCMeta from enum import Enum class spot(): def __init__(self, x, y, piece): self.x = x self.y = y self.piece = piece # object of piece type # getter and setter for x,y and piece def get_piece(self): pass class piece(metaclass=ABCMeta): ...
dbe97ae1e1ea3ff2348b752f03a553d380284d92
DanielElisenberg/aoc2020
/day01/day01.py
457
3.515625
4
import itertools with open('day01/input.data') as input: expense_report = [int(line) for line in input.read().splitlines()] combinations = list(itertools.combinations(expense_report, 2)) [product] = [x*y for (x, y) in combinations if x+y == 2020] print(f"first solution: {product}") combinations = list(itertools....
f3ab82c83ff0dbc1762e04b1233ee480b39438f7
kkinder/templatemail
/templatemail/engines/__init__.py
853
3.765625
4
from abc import ABC from typing import List, Dict class Engine(ABC): """ Defines the interface for engines, which are used to send email. """ def send_simple_message(self, from_address: str, to_addresses: List[str], subject: str, text_body: str = None, html_body: str = Non...
c02d702f696f16ddc8cfb773085cff8aeb8e1ee9
cocochrane/cs207binsearch
/test_binarysearch.py
4,034
3.640625
4
from binarysearch import binary_search import unittest import numpy as np class MyTest(unittest.TestCase): def setUp(self): self.inputt = range(10) def tearDown(self): del self.inputt #test showing that sorted array is necessary- 3 is present but returns -1 def test_...
adfe67028140b151fe3105555d9f5225fbe24c51
medapalli/Python_UNH
/Homework8/HW8_Prog1.py
3,569
4
4
class Animal(): def __init__(self, name): self.name=name def guess_who_am_i(self): print("I will give you 3 hints, guess what animal I am\n") while True: if (self.name=="Elephant"): print("I have exceptional mem...
ca15a01b08f4950f81b513171c8cbe88977b916c
medapalli/Python_UNH
/Homework5/HW5_Prog2_pytest.py
375
3.671875
4
def bunny_Ears(bunnies): if (bunnies == 0): return 0 elif ((bunnies%2) == 0): return 3 + bunny_Ears (bunnies-1) else: return 2 + bunny_Ears (bunnies-1) def testBunny1(): assert(bunny_Ears(0)==0) assert(bunny_Ears(1)==2) assert(bunny_Ears(2)==5)...
5b419da3a145a1d27443f1ca39a5e474fe687887
yr49/Summer2020
/system.py
5,919
3.5625
4
from customer import Customer from server import Server class System: time = 0 # This variable keeps track of the time lm = 0 # This variable serves as lambda, the mean arrival rate servers = [] queue = [] # This list contains all customers awaiting service fel = [] # This list keeps track of future...
de972f3ccf3bade1fd070d123468b09eaa0d6284
asouzajr/algoritmosLogicaProgramacao
/lingProgPython/programasBasicosPython/exemploProgramaLinhasQuebradas.py
277
3.9375
4
#Uma linha quebrada por contra-barra a = 7 *3 + \ 5 / 2 # Uma lista (quebrada por vígula) b = ['a', 'b', 'c', 'd', 'e'] #Uma chamada de função (quebrada por vírgula) #min() retorna o menor elemento de uma sequencia c = min(1,2,5,7, 11) #imprime todos na tela print(a,b,c)
d8b872f0044ba34b3687021c2ba7bcfc85970d20
asouzajr/algoritmosLogicaProgramacao
/lingProgPython/cursoemVideo/desafio009.py
531
4.09375
4
# Escreva um programa que leia um número inteiro, calcule e mostre # na tela a respectiva tabuada. print('='*88) nome = input('Qual o seu nome: ') print('Olá {}! Seja bem-vindo(a)!' .format(nome)) n = int(input('{}, para iniciar a operação algébrica digite o valor que deseja fazer a tabuada: ' .format(nome))) print('{...
9c511a9a74f9eccbed868ed190d3f58392157bed
asouzajr/algoritmosLogicaProgramacao
/lingProgPython/programasPython/testesCondicionais.py
479
4.375
4
x = -2 y = -3 if x == y: print("números iguais") elif x < y: print ("x menor que y") elif y > x: print("y maior que x") else: print ("algo deu errado") if x > y: if x > 0: print("x é maior que y e é positivo") else: print ("x é maior que y e é negativo") else: print ("y é menor que x") if x == y: prin...
46063ba565c272dc824a4c51d8b4d8918c063e21
asouzajr/algoritmosLogicaProgramacao
/lingProgPython/programasTiposVariaveisPython/programaUsandoDicionarios.py
1,320
3.53125
4
# Um dicionário é uma lista de associações compostos de uma chave única e estruturas correspondentes. # Dicionários são mutáveis, similar as listas. # A chave deve ser imutável, incluindo strings, tuplas ou tipos numéricos. # O dicionário não garante que as chaves estarão ordenadas e nem que a ordem original será manti...
2fd75e94132143e5dd86db2edd96a298438c1e34
asouzajr/algoritmosLogicaProgramacao
/lingProgPython/cursoemVideo/desafio007.py
518
3.953125
4
# Desenvolva um programa que leia as duas notas de um aluno, calcule e mostre # as notas e a média. print('='*40) nome = input('Qual o seu nome: ') print('Olá {}! Seja bem-vindo(a)!' .format(nome)) n1 = float(input('{}, para iniciar a operação algébrica digite a primeira nota: ' .format(nome))) n2 = float(input('{}, a...
7d375761179755d72e3db80f4bd50738f28dd22b
ParanoidAndroid19/cracking_the_coding_interview_python
/Ch1_Arrays and Strings/1_isUnique.py
1,203
4
4
# Naive Solution: # def isUnique(str1): # li = [] # for c in str1: # if c in li: # return "Not Unique" # li.append(c) # return "Unique" # A faster solution but still not the best solution. No nested loops at least. # def isUnique(str1): # dict = {} # # one loop to initi...
ab8efe63dd48efc395faf4364e636d151c48f66d
ParanoidAndroid19/cracking_the_coding_interview_python
/Ch3_Stacks and Queues/1_threeInOne.py
1,830
3.84375
4
# Here we are assuming the stacks sizes are predifined and they cannot exceed that size class MultiStack: def __init__(self, capacity): self.numStacks = 3 #number of stacks in array self.array = [0] * (capacity * self.numStacks) #thus the len of array is 2 * 3 = 6 self.sizes = [0] * sel...
06e2da343adb33a6af2ef52808605af5179fbc4c
ParanoidAndroid19/cracking_the_coding_interview_python
/Ch1_Arrays and Strings/6_strCompression.py
1,589
3.53125
4
# aabcccccaaa --> a2blc5a3 # Solution 1: # Firstly, to record the repeated chars I will use a bit vector ([0]*n) where index value will be the # ord (ASCII) of A-Z and a-z. In the same loop if the next letter is different than current letter # (st[i] != st[i+1]), I will append the required letters and its repetitions...
c789575a99dd549e0f5c09910e87a0e36e2fa260
ParanoidAndroid19/cracking_the_coding_interview_python
/Ch1_Arrays and Strings/7_rotateMatrix.py
630
3.78125
4
# Expected result # [ # [21, 16, 11, 6, 1], # [22, 17, 12, 7, 2], # [23, 18, 13, 8, 3], # [24, 19, 14, 9, 4], # [25, 20, 15, 10, 5]] # 1st column becomes the first row, the row has 1st column eles in rev order. Same for all cols and rows # O(NxN) def matrixRotate(matrix): revMatrix = [] l = len(matrix) ...
5af62b141b49ebcdaaa28cb6733d81ed92db509b
pseudoincorrect/Design_Patterns_Python
/10_Facade/facade_exo.py
2,049
3.734375
4
import os import unittest from random import randint class Generator: def generate(self, count): return [randint(1, 9) for x in range(count)] class Splitter: def split(self, array): result = [] row_count = len(array) col_count = len(array[0]) for r in range(row_coun...
c6c0c5f16113da61eb7a8facf7673fe1be9a70fa
raytso0831/unit-4
/printStars.py
121
3.515625
4
#Ray Tso #3/9/18 #printnStar.py def printnStars(num1): for i in range(1,num1+1): print('*'*i) printnStars(6)
94330a1e934faf3c644dace3f90b184020eda76e
mcharawi/neural-aixi
/other/network.py
3,705
4.03125
4
""" network.py ~~~~~~~~~ A module to implement the stochastic gradient descent learning algorithm for a feedforward neural network. Gradients are calculated using backpropagation. The network uses a hyperbolic tangent function as the activation function. """ import random import numpy as np class Network(object)...
8c4d57da1267b058b76250618f25893a4114949f
jonesy212/Sorting
/src/iterative_sorting/iterative_sorting.py
1,277
4.15625
4
# TO-DO: Complete the selection_sort() function below def selection_sort(arr): def selection_sort(arr): for i in range(0, len(arr)-1): cur__index = i smallest_index = cur_index #find the next smallest element q for x in range(cur_index, len(arr)): if arr[x] < arr[small...
839705bd77e6fe528da53fdfe43b41c42d8b5d37
volkanakcora/Volkan_Scripts
/Temel/Workshops/faktoriyelcalculate.py
319
3.875
4
# -*- coding: utf-8 -*- sayi = int(input("sayi : ")) faktoriyel = 1 if sayi < 0: print("negatif sayi olmaz") elif sayi == 0: print("faktoriyel = 1 " ) else: for i in range(1,sayi+1): faktoriyel = faktoriyel * i print("faktoriyel = ",faktoriyel) 0
de5a6cc4b4ae7bcd9284301f20403dd36bc715b5
volkanakcora/Volkan_Scripts
/Temel/Groupby(sql).py
445
3.9375
4
# -*- coding: utf-8 -*- import sqlite3 connection = sqlite3.connect("chinook.db") cursor = connection.execute("""select city,count(*) from customers group by city having count(*) > 1 order by city desc """) ###order by = sırala , asc , desc sıralama birimleri^### for row in cursor: ...
ed9c9b052b467e2c1e84fcb285760f0a00bd8096
volkanakcora/Volkan_Scripts
/Temel/Numpy/ıntro.py
354
3.5625
4
# -*- coding: utf-8 -*- import numpy as np #havaDurumu = [[12,21,31],[6,17,18],[11,12,13]] #print(havaDurumu) a = np.arange(15).reshape(3,5) # arrange fonksiyon baslangın dahil sonuncu dahil olmayan sayı verir print(a) print(type(a)) print("dimension =" + str(a.ndim)) b = np.arange(10) print(b) print(b.shape) pr...
18940dc416e64656105efeb1ba199213fb805bc8
volkanakcora/Volkan_Scripts
/Temel/Workshops/RecapASAL.py
263
3.703125
4
# -*- coding: utf-8 -* sayi = int(input("lütfen bir sayi giriniz")) AsalMi = "evet" for x in range(2,sayi): if (sayi % x) == 0: AsalMi = "hayir" break if AsalMi =="evet": print("bu sayi asaldir") else : print("asal değildir")
13aef50fe0e741016c23d22a31eadea9d187026a
volkanakcora/Volkan_Scripts
/Temel/Workshops/setUnion.py
182
3.75
4
# -*- coding: utf-8 -*- setA = {1,2,3,4,5} setB = {1,3,4,6,7,8} print(setA |setB) print(setA.union(setB)) print(setA.intersection(setB)) # kesişim print(setA.difference(setB))
12cf197ea5f63b0bb852af7c4baa45cb00754557
volkanakcora/Volkan_Scripts
/Temel/INSERT.py
1,853
3.828125
4
# -*- coding: utf-8 -*- import sqlite3 def selectop(): connection = sqlite3.connect("chinook.db") cursor = connection.execute(""" select FirstName,LastName from customers where FirstName like '%ja' """) for row in cursor: pr...
ae2eb6cb5e737cc4764ab424ae771d6915b7245a
volkanakcora/Volkan_Scripts
/MachineLearning/deneme2.py
1,173
3.59375
4
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*- import pandas as pd import numpy as np import matplotlib.pyplot as plt from sklearn.linear_model import LinearRegression from sklearn.preprocessing import PolynomialFeatures data = pd.read_csv("insurance.csv") print(data.columns) # x ekseni age = data.age.values.resh...
ffa36c59730e3b51e68a3ebf0ad20dedb6a2d28a
fefoglino/programmingFirstChallenges
/day1challenge7.py
471
3.890625
4
''' challenge 7 Write a Python program to remove and print every third number from a list of numbers until the list becomes empty. ''' listOfNumbers = [1, 2, 3, 4, 5, 6, 7, 8, 9] while True: print(listOfNumbers) print(listOfNumbers[2]) listOfNumbers.pop(2) if len(listOfNumbers)==2: break pri...
0930c4e4dca39c8d2f251d5df7b95df0a4761af7
suduk/real-python-test
/flask.blogapp2.d/sql.py
309
3.609375
4
import sqlite3 db_data=[("title1", "some post 1"),("title2","some post2...")] with sqlite3.connect("blog.db") as connection: cursor=connection.cursor() cursor.execute('drop table blog') cursor.execute('create table blog(title text, post text)') cursor.executemany('insert into blog values(?,?)',db_data)