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
44db42b91a850f6b167a1d62ece5fd5e57de8fb5
civrev/PythonTutorials
/MachineLearning/iris2.py
2,060
3.625
4
#iris machine learning testing, part 2 #to use go to terminal and type: #python3 ~/Documents/pyfiles/iris2.py #which by the way, is just the absolute file path of iris2.py on my computer #made based on the class I got from DataCamp.com 'Supervised Learning with scikit-learn' #imports from sklearn import datasets from ...
d31a0044b5417b8bd3eb3c8f758c6ed5d90d62b4
civrev/PythonTutorials
/ReinforcementLearning/TicTacToe/tic_tac_toe.py
9,390
4
4
#python3 ~/PythonTutorials/ReinforcementLearning/tic_tac_toe.py #Iterative Re-enforcement learning agent, Value function #Made from a class I got on Udemy #"artificial intelligence reinforcement learning in python" by The LazyProgrammer import random ''' reinforcment learning favors objects over scripting code at a h...
cc6a9f81d17cb287b77a72c599a863b5735e91be
civrev/PythonTutorials
/MachineLearning/congress.py
3,727
3.671875
4
#machine learning with the 1984 Congressional Voting database #this is help for advanced metrics in classification models #coincidentally, it also helps with databases from the internet #and organizing data #made based on the class I got from DataCamp.com 'Supervised Learning with scikit-learn' #python3 ~/Documents/pyf...
92e273b5073e0f66d1830559112d827e897d293f
civrev/PythonTutorials
/Databases/census5.py
5,168
3.9375
4
#census5.py #based on a course I got from DataCamp.com "Introduction to Databases in Python" #SQLite, Math Operators, Case Statements import pandas as pd import matplotlib.pyplot as plt from sqlalchemy import create_engine, Table, MetaData from sqlalchemy import select, or_, and_, not_, desc from sqlalchemy import fun...
e07a199e2217d8912b7ef2152254d0019e425c08
thiagonferrari/PythonNt
/app/inicio.py
478
4
4
# #----- Impressão # print('\n') # print('*' * 50) # print('Ola', 'Joelma', 'do Calypso') # print('Ola' + 'Chimbinha' + 'do Calypso') # print('*' * 50) #----- Pegar entrada do usuário nome = input('Digite seu nome: ') sobrenome = input('Digite seu sobrenome: ') #----- Usando format para concatenação de string print('...
b90011bdc1047488714cff2d3a37c0b38bed7ebe
Alesxander36/Curso_de_Python3
/python_basico_(logica_de_programacao)/aula20.py
499
3.890625
4
# Indices # 0123456789.................33 frase = 'o rato roeu a roupa do rei de roma' # Iterável tamanho_frase = len(frase) print(tamanho_frase) contador = 0 nova_string = '' input_do_usuario = input('Qual letra deseja colocar em maiuscula: ') # Iteração <- Iterar while contador < tamanho_frase: letra =...
04edc373194d0ed388757c5f84f9986cf343fa90
Alesxander36/Curso_de_Python3
/python_basico_(logica_de_programacao)/aula12.py
519
4.03125
4
# Operadores lógicos """ and, or, not in e not in # (verdadeiro E False) = Falso comparacao1 and comparacao2 # Verdadeiro OU Verdadeiro comp1 or comp2 a = 2 b = 3 if not b > a: print('B e maior do que A') else: print('A e maior do que B') """ usuario = input('Nome de usuario: ') senha = input('Senha do us...
30f5ea5e2b6b058c8d129cd99ab3afb005354abd
Alesxander36/Curso_de_Python3
/python_basico_(logica_de_programacao)/aula11.py
498
3.9375
4
# Operadores Relacionais """ == Igualdade > Maior que >= Maior que ou igual a < Menor que <= Menor que ou igual a != Diferente """ nome = input('Qual e o seu nome? ') idade = input('Qual e a sua idade? ') idade_limite = 18 idade = int(idade) # LIMITE PARA PEGAR EMPRESTIMO idade_menor = 20 # Muito jovem idade_maior ...
bd06c2169a9773fda55163237818f325d8c377fc
wxtjzmyt/python-code
/turtle/五角星(循环两次).py
1,313
3.546875
4
# coding=utf-8 # 这是画一个五角星 """ import turtle turtle.forward(100) turtle.right(144) turtle.forward(100) turtle.right(144) turtle.forward(100) turtle.right(144) turtle.forward(100) turtle.right(144) turtle.forward(100) """ # 这是循环画两个五角星 """ # import turtle for i in range(2): turtle.forward(300) turtle.right(144) ...
4ffc687522f5e49d4bfdad0588af66ee75035b23
Andzerakk/home
/2nd task AD.py
416
4.03125
4
n1 = input("Please enter first number") n2 = input("Please enter second number") if n2.isdigit() and n1.isdigit(): n1_1 = int(n1) n2_2 = int(n2) if n1_1 > 0: if n2_2 > 0: print(n1_1 + n2_2, "\n", n1_1 - n2_2, "\n", n1_1 / n2_2,"\n", n1_1 ** n2_2) else: print('enter va...
7a88a4450c09373052b810edeadcfca38f07bb47
nissy-shota/ImageProcessing4python
/Histogram_Normalization.py
1,600
3.625
4
""" Histogram normalization ヒストグラム正規化を実装せよ。 ヒストグラムは偏りを持っていることが伺える。 例えば、0に近い画素が多ければ画像は全体的に暗く、255に近い画素が多ければ画像は明るくなる。 ヒストグラムが局所的に偏っていることをダイナミックレンジが狭いなどと表現する。 そのため画像を人の目に見やすくするために、ヒストグラムを正規化したり平坦化したりなどの処理が必要である。 このヒストグラム正規化は濃度階調変換(gray-scale transformation) と呼ばれ、 [c,d]の画素値を持つ画像を[a,b]のレンジに変換する場合は次式で実現できる。 今回はimori_dark.jpgを...
133d9a25e1366e5aa9ef33cfe8ed3f733263dd9b
akashvishwa/General_Python_programs
/reverse_number.py
139
4.03125
4
n=int(input("Enter the number for sum:")) s=0 r=0 num=n while num>0: r=num%10 s=s*10+r num=num//10 print('Sum of digit is: ',s)
a654b2d6dfe40307b71aeb731585aeb7ad6bb227
JakeRead-GH/Research-Co-op
/Waterloo Computing Contest/Problem S2 (old).py
284
3.921875
4
t = int(input() ) num = int(input() ) for a in range(num): if a > 1: for i in range(2, a): print(a, i) if (a % i) == 0: print(a,"is not a prime number") else: print(a,"is a prime number")
02f9c974baec193750ebe8ebcbec90c3a7f9960c
Yemmm/AlgorithmsAndDataStructures_freeCodeCamp
/quicksort_strings.py
571
4.09375
4
def quicksort(values): if len(values) <= 1: return values less_than_pivot = [] greater_than_pivot = [] pivot = values[0] for value in values[1:]: if value <= pivot: less_than_pivot.append(value) else: greater_than_pivot.append(value) print("%15s %1...
ef6289001735b85aec690c9c4173c9c4b4f5da0d
rahlk/leetcode-samples
/array/3Sum/global_worst.py
727
3.5
4
class Solution(object): def threeSum(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ nums.sort() result = set() l = len(nums) if (l<3): return result for i in range(0,l): j = i+1 k = l-1 ...
00a7856bbfb3690bf77899cfa4ce5e1c59b43191
saifeemustafaq/Magic-Maths-in-Python
/test.py
892
4.25
4
print "" print " Please press enter after each step!" print "" print ' Think of a number below 10...' a=raw_input( ) print ' Double the number you have thought.' b=raw_input() c= int(input(" Add something from 1-10 with the getting result and type it here (type only within 1-10...
85f11d93c2b76f8a0f8def3f861002cb73056ef9
Hariharan-K/python
/remove_all_occurrences.py
1,086
4.34375
4
# Remove all occurrences of a number x from a list of N elements # Example: Remove 3 from a list of size 5 containing elements 1 3 2 3 3 # Input: 3 5 1 3 2 3 3 # Output: 1 2 # Input: 4 7 1 4 4 2 4 7 9 ######################## import sys def remove_all_occurrences(mylist,n): # loop to traverse each element in list...
b68c2c507980032894a5f75f3a3c619b28b559d1
Hariharan-K/python
/max_sum_of_non_empty_array.py
1,411
4.28125
4
""" Given an array of integers, return the maximum sum for a non-empty subarray (contiguous elements) with at most one element deletion. In other words, you want to choose a subarray and optionally delete one element from it so that there is still at least one element left and the sum of the remaining elements is maxim...
b6949b34babd036f89f656d5a50d65afd8d77358
XuHaoIgeneral/PyTest
/basis/Interview.py
577
3.65625
4
# def singleton(cls): # instances = {} # a=[] # def getinstance(*args, **kw): # if cls not in instances: # instances[cls] = cls(*args, **kw) # return instances[cls] # return getinstance # # @singleton # class MyClass: # def __init__(self,a): # self.a=a...
06d3fd0ed8b73fc3d9ff52ed9c219a0d12c2aa7d
XuHaoIgeneral/PyTest
/basis/data structure/LinkedList.py
2,377
3.90625
4
class Node(object): def __init__(self, value=None, next=None): self.value = value self.next = next class LinkedList(object): def __init__(self, maxsize=None): self.maxsize = maxsize self.root = Node() self.length = 0 self.tailnode=None def __len_...
8b9dde9cd475ce03cea0244578507a9681030c74
XuHaoIgeneral/PyTest
/basis/yuesefuRing.py
623
3.65625
4
class MyClass(object): data = "This is class data" def instance_method(self): print("实例方法,只能被实例对象调用,可以访问实例属性%s" % self.data) @staticmethod def static_method(): print("是静态方法,不能访问类属性或者实例属性") @classmethod def class_method(cls): print("是类方法,可以访问类属性%s" % c...
590b94c5d4f22205de204630b5cb1452978c2149
XuHaoIgeneral/PyTest
/basis/data structure/1.py
762
3.546875
4
# def code(func): # data={} # # def wrapper(n): # if n in data: # return data[n] # else: # res=func(n) # data[n]=res # return res # return wrapper # # @code # def fib(n): # if n<=2: # return 1 # else: # ...
bb9fed21e40b850fd755cfbd2a2407c6653257b2
XuHaoIgeneral/PyTest
/basis/leetcode/119. 杨辉三角 II.py
550
3.625
4
class Solution: def getRow(self, rowIndex, rowlists=[], rows=1): """ :type rowIndex: int :rtype: List[int] """ if rowIndex < 0: return rowlists lists = [] for i in range(rows): if i == 0 or i == rows-1: lists....
de2318e0e48f591e07074c66b6fe9bd924fbd358
xuzhanhao06/PythonBase
/20200602随机分配办公室.py
553
4.125
4
#将8人分配3教室 ''' 1. 准备数据 2.分配 3.验证 ''' import random #1. teachers=['A','B','C','D','E','F','G','H'] offices=[[],[],[]] #2. for name in teachers: #列表追加数据--append extend insert num=random.randint(0,2) offices[num].append(name) print(offices) #3. #办公室+个编号 i=1 for office in offices: #打印人...
9c1f17f9b7ab6d330f5337bc10e0d13a9ffe0f11
xuzhanhao06/PythonBase
/20200603-4公共运算符.py
1,031
3.90625
4
str1 ='aa' str2="bb" list1 = [1, 2] list2 = [10, 20] t1=(1,2) t2 = (10,20) dict1={'name':'Python'} dict2={'age': 30} print('------- +: 合并 -----------------') print(str1+str2)#aabb print(list1+list2)#[1, 2, 10, 20] print(t1+t2)#(1, 2, 10, 20) #print(dict1+dict2)#报错!!! 不支持合并 print('------- *: 复制 -------...
daa49e627678759b587970b503fb3ce53ebd287d
xuzhanhao06/PythonBase
/20200602元组操作.py
543
3.953125
4
''''' 元组数据不支持修改,只支持查找 ''''' t1 = ('aa', 'bb', 'cc', 'bb') #1. 下标 print(t1[0])#aa #2. index() print(t1.index('bb'))#1 #print(t1.index('bbb'))#报错 #3. count() print(t1.count('aa'))#1 print(t1.count('aaa'))#0 #4. len() print(len(t1)) #4 print('元组数据修改(元组里的数组)----------------------------------------') ...
a859cf7b8c1e199bc6a6ed9c4e649f1b0ea344cb
xuzhanhao06/PythonBase
/20200602元组.py
422
4.1875
4
#如果想要存储多个数据,但是这些数据是 不能修改的数据 ,----元组 #元组特点:定义元组使用小括号,且逗号隔开各个数据,数据可以是不同的数据类型。 t1=(10,20,30) print(t1)#(10, 20, 30) print(type(t1))#<class 'tuple'> t2=(10,) t3=(10) print(type(t2))#'tuple' print(type(t3))# 'int' t4=('aaa') print(type(t4))# 'str' t5=('aaa',) print(type(t5))#tuple
b9e7920c1b6b74300069d0743890c814d00092b0
TWICENayeon/Python-Projects
/SMTPdw1636.py
2,209
3.578125
4
# Deryck Wong dw1636 from socket import * msg = "\r\n I love computer networks!" endmsg = '\r\n.\r\n' # Choose a mail server (e.g. Google mail server) and call it mailserver #Fill in start mailServer = 'smtp.nyu.edu' #Fill in end # Create socket called clientSocket and establish a TCP connection with mailserver...
35043ba58a8246fb25f9b407e7803be6a849ea47
4RG0S/2021-Spring-Jookgorithm
/박준서/[21.04.02]15828.py
266
3.5625
4
from collections import deque n = int(input()) buf = deque() packet = input() while packet != '-1': if packet == '0': buf.popleft() elif len(buf) < n: buf.append(packet) packet = input() print(' '.join(buf) if len(buf) > 0 else 'empty')
1b0d72c293ea1073005b46e0d0c116e7ccf83b83
Ermako27/python-labs-1st-course
/qsort/sheiker_sort_defend.py
637
3.578125
4
import random as r M = int(input('Введите размер массива: ')) print() mass = [r.randint(0,20) for x in range(M)] print('Неотсортированный массив: ', mass) start = 0 end = len(mass) - 1 while start <= end: #print(left,right) for i in range(start, end): if mass[i] > mass[i + 1]: ...
ea67333ddb63e7c0a5dd88e453eaaa6e595ed0e2
Ermako27/python-labs-1st-course
/teams_files/защита/zashita.py
375
3.546875
4
f = open('f1.txt','a') f.write('\n') f.close f = open('f2.txt','w') f.close() with open("f1.txt") as f: for line in f: f2 = open('f2.txt') if line not in f2: f2.close() f2 = open('f2.txt','a') f2.write(line + '\n') f2.close() f2 = ...
67b11dab80dc5450d56055ab9395babacb34b410
Ermako27/python-labs-1st-course
/tablica.grafik.py
3,090
3.5625
4
# Ермаков Максим ИУ7-14 # Таблица значений, график # 1) Вывод таблицы значений from math import sin xmin = float(input('Введите минимальное значение аргумента: ')) xmax = float(input('Введите максимальное значение аргумента: ')) step = float(input('Введите щаг: ')) xm = xmin xx = xmax s1 = 0 s2 = 0 sc = 0...
1cb4762b17608f9f3d686eaf8d0ffd1095699cec
sullivan29/python3
/classAndcollections.py
2,325
3.90625
4
#!/usr/bin/env python3 import sys from collections import Counter class Person(object): """ 返回具有给定名称的 Person 对象 """ def __init__(self, name, grade): self.name = name self.grade = grade def get_details(self): """ 返回包含人名的字符串 """ return self.name ...
1087bf275435dae9eb265928248a105889ac30e3
blopah/python3-curso-em-video-gustavo-guanabara-exercicios
/Desafios/Desafio 55.py
408
3.9375
4
print("""Faça um programa que leia o peso de cinco pessoas. No final, mostre qual foi o maior e o menor peso lidos.""") me = 0 ma = 0 for c in range(1, 5, 1): a = float(input('Insira o peso em Kg: ')) if c == 1: me = a ma = a else: if a > ma: ma = a if a < me: ...
efa1a18e6b182fcbaa86daf082a810a60e8444aa
blopah/python3-curso-em-video-gustavo-guanabara-exercicios
/Desafios/Desafio 71.py
1,005
4.03125
4
print('''Crie um programa que simule o funcionamento de um caixa eletrônico. No início, pergunte ao usuário qual será o valor a ser sacado(número inteiro) e o programa vai informar quantas cédulas de cada valor serão entregues. Obs: Considere que o caixa possui cédulas de R$50,00 R$20,00 R$10,00 E R$1,00''') print('...
582cf83b3909814f9723e0b8c12beb02998919d4
blopah/python3-curso-em-video-gustavo-guanabara-exercicios
/Desafios/Desafio 90.py
466
3.84375
4
print('''Faça um programa que leia nome e média de um aluno, guardando também a situação em um dicionário. No final, mostre o conteúdo da estrutura na tela.''') aluno = dict() aluno['nome'] = str(input('Insira o nome: ')) aluno['nota'] = float(input('Insira a nota: ')) if aluno['nota'] < 7: aluno['nota'] = 'repro...
6bf8f7719b02ee3488eac36634105577791fa4ba
blopah/python3-curso-em-video-gustavo-guanabara-exercicios
/Desafios/Desafio 1.py
168
4
4
# Desafio 1 n1 = float(input('Digite um número!! ')) n2 = float(input('Agora outro!!! ')) s = int( n1 / n2 ) print('A divisão entre {} e {} é {}'.format(n1, n2, s))
64447553a171b36d2bc965b88bb792217a487eea
blopah/python3-curso-em-video-gustavo-guanabara-exercicios
/Desafios/Desafio 8.py
183
3.765625
4
print('Conversor de metros para milimetros e centimetros') m = float(input('Digite em metros: ')) cm = m*100 mm = m*1000 print('\nCentimetros = {} \nMilimetros = {}'.format(cm, mm))
01f95dc0f3968a86326ed66b4cacd25d149bde99
blopah/python3-curso-em-video-gustavo-guanabara-exercicios
/Desafios/Desafio 34.py
466
3.96875
4
print("""Escreva um programa que pergunte o salário de um funcionário e calcule o valor do seu aumento. Para salários superiores a R$1.250,00 calcule um aumento de 10%. Para os inferiores ou iguais, o aumento é de 15%.""") sal = float(input('Digite o salario: ')) lim = float(1250.00) if sal > lim: saln = (sal*1.1...
ee787b8693abf199834f0609994d9925652106f1
blopah/python3-curso-em-video-gustavo-guanabara-exercicios
/Desafios/Desafio 50.py
282
3.9375
4
print("""Desenvolva um programa que leia seis números inteiros e mostre a soma apenas daqueles que forem pares. Se o valor digitado for ímpar, desconsidere-o""") s = 0 for c in range(1, 7, 1): n = int(input('Digite um número: ')) if (n%2) == 0: s += n print(s)
306f89d3f7f0fd508e214e569239dbf3e61e6cdc
blopah/python3-curso-em-video-gustavo-guanabara-exercicios
/Desafios/Desafio 62.py
992
4
4
print("""Melhore o Desafio 61, perguntando para o usuário se ele quer mostrar mais alguns termos. O programa encerra quando ele disser que quer mostrar 0 termos..""") print("""Exercício 51: Desenvolva um programa que leia o primeiro termo e a razão de uma PA. No final mostre os 10 primeiros termos dessa progressão....
cd7c3a47679a65b9407bcfeaef137f302f55390f
blopah/python3-curso-em-video-gustavo-guanabara-exercicios
/Desafios/Desafio 60.py
685
4.09375
4
print("""\033[1;30mFaça um programa que leia um número qualquer e mostre o seu fatorial.\033[0;0m\n""") # Usando while # n = int(input('Digite um número: ')) # c = n # r = n # while c > 1 : # c -= 1 # r = r * c # print(r) # print('O fatorial de {} é {}'.format(n, r)) # Usando for n = int(input('Digite...
82fbd8ceddd27ea3d8493fa3c3cf6fb3911e32f9
blopah/python3-curso-em-video-gustavo-guanabara-exercicios
/Desafios/Desafio 49.py
228
3.765625
4
n = int(input('Digite um número para ver a taboada dele! ')) m = int(input('A taboada de quantos números? '))+1 print('Tabuada do "{}" em "{}"x:'.format(n, m)) for c in range(0, m, 1): print('{}*1 = {}'.format(n, (n*c)))
f10801c46813dddbd49554968a239ce7a40bef23
blopah/python3-curso-em-video-gustavo-guanabara-exercicios
/Desafios/Desafio 84.py
1,153
3.953125
4
print('''Faça um programa que leia nome e peso de várias pessoas, guardando tudo em uma lista. No final, mostre: A) Quantas pessoas foram cadastradas. B) Uma listagem com as pessoas mais pesadas. C) Uma listagem com as pessoas mais leves.''') p = list() ps = list() pl = list() pp = list() while True: keep = '0' ...
552976e456b6e6cc795fdb17f3285436ebf19c25
blopah/python3-curso-em-video-gustavo-guanabara-exercicios
/Desafios/Desafio 87.py
993
4.0625
4
print('''Aprimore o desafio anterior mostrando no final: a) A soma de todos os valores pares digitados. b) A soma dos valores da terceira coluna. c) O maior valor da segunda linha.''') li = [[],[],[]] for c in range(0, 3, 1): for co in range(0, 3, 1): li[c].append(int(input(f'Insira um valor para a posiçã...
034d37c3bf03040802b10320d372c7e62ddf4c2f
blopah/python3-curso-em-video-gustavo-guanabara-exercicios
/Desafios/Desafio 23.py
327
4.03125
4
print("""Faça um programa que leia um número de 0 a 9999 e mostre na tela cada um dos dígitos separados.""") num = input('digite um número de 4 dígitos: ') nume = num[:4] u = num[3] d = num[2] c = num[1] m = num[0] print('O número é {}. \nUnidade {}. \nDezena {}. \nCentena {}. \nMilhar {}.'.format(nume, u, d, c, m))
99875a824f4b5698e80a7ee51e877450a73bc531
age-kevin/python-test01
/com.age.python/Test05-列表去重.py
635
3.703125
4
import itertools import random myList = [random.randint(20, 30) for i in range(15)] print(myList) # 一、新列表收集法,只收集不重复的元素 # myNewList = [] # # for ele in myList: # if ele not in myNewList: # myNewList.append(ele) # # print(myNewList) # 二、将原列表传给set集合,自动去重 # myNewList = list(set(myList)) # print(myNewList) #...
ec7f65e151cc53d9de5bb61f8aa93bac59b8155d
sugapriya98/suga
/maximum.py
155
3.84375
4
x=int(input("\nenter the value of x")) y=int(input("\nenter the value of y")) z=int(input("\nenter the value of z")) c=max(x,y,z) print("maximum value",c)
456f3bb61a3597c469a3bfd749661f8b64b5288c
NicholasFay-CIS/Algorithms
/HW02/backup.py
3,026
3.734375
4
import sys import string def get_vertices(inputfile): """ FILE obj -> int returns the number of vertices in the list this also reads through the first line of the file """ return int(inputfile.readline()) def get_edges(inputfile): """ #FILE obj -> int returns the number of edges in the list this also reads ...
01e1cc61948bb150d97d3c292450fada73b2632b
nuaalht/python
/test_name_funciton.py
870
3.5
4
# import unittest # from name_function import get_formatted_name # # class NamesTestCase(unittest.TestCase): # """测试name_function.py""" # # def test_first_last_name(self): # """能够正确处理像Jains Joplin这样的姓名吗?""" # formatted_name = get_formatted_name('jains', 'joplin') # self.assertEqual(forma...
6a5b9c7a0a22d31fdcd3da9a631b17217b2ffd16
vvkhandekar110988/Coursera_Final_course_file_funtion_dictionart
/false_value.py
742
3.90625
4
punctuation_chars = ["'", '"', ",", ".", "!", ":", ";", '#', '@'] def strip_punctuation(str1): for ch in punctuation_chars: str1 = str1.replace(ch, '') return str1 def get_neg(str1): str1_lower = str1.lower() str1_lower_strip = strip_punctuation(str1_lower) str1_lower_strip_list = str1_l...
24fab334bdad2da4f28060f6c9a95838a4d5bf48
wzj207/tkinter-learning
/13_checkboxes.py
494
3.609375
4
from tkinter import * from PIL import ImageTk,Image root = Tk() root.title('Learn Tkinter') root.iconbitmap('./images/favicon.ico') # add icon root.geometry('400x400') # var = IntVar() var = StringVar() c = Checkbutton(root, text='Check this box, I dare you!', variable=var, onvalue='on', offvalue='o...
2e4d4d306f0a8dab485552ecca7df03dda05e713
wzj207/tkinter-learning
/08_addingRadioButtons.py
911
3.734375
4
from tkinter import * from PIL import ImageTk,Image root = Tk() root.title('Learn Tkinter') root.iconbitmap('./images/favicon.ico') # add icon # r = IntVar() # r.set('22') # r.get() TOPPINGS = [ ('Pepperoni', 'Pepperoni'), ('Cheese', 'Cheese'), ('Mushroom', 'Mushroom'), ('Onion', 'Onion'), ] pizz ...
603a8c689f3e6f620467fd98c8569e43f746835c
priyansh0079/Design-Analysis-of-Algorithm-labs
/LAB 3/Lab 3.py
5,271
3.765625
4
#-----------------------------------Heap sort----------------------------------------------------------------------# import random import time #Code for fourth part is written first import os #so as to avoid the addition of memory utilized ...
b886161f88d7cf28898cdef6b047f3dd5cd7107c
kfpotts1/klml_supervised
/klml_supervised/name_tools.py
2,729
3.59375
4
import numpy as np def gen_hash_features(name, B=256, FIX=4, method='basic'): """ Generates a vector of features given a person's name. Extracts and hashes features for a given name. Focuses on the beginning and endings of the words (prefix and suffix). Syntax: features[i] = gen_hash_fea...
4a7706af1fd8e5d0daaabf75392d62f1c4321812
falloutcoder/python-sorts
/shell_sort.py
977
3.625
4
""" |-----------------------------------------------------------| | Shell Sort | |-----------------------------------------------------------| |Type || In-place comparison sort | |Worst case performance || O(n2) | |Best ...
e15702fa179f9f1966b78e154a1512f4c907eee7
avinashselvam/ID5030_iitm
/ass0/pingpong.py
351
3.875
4
n = 100 for i in range(1,n+1): div_by_two = False div_by_three = False if i%2 == 0: div_by_two = True if i%3 == 0: div_by_three = True if div_by_two and div_by_three: print("pingpong") elif div_by_two: print("ping") elif div_by_three: print("pon...
d72a6d57abac65389ad5dda6f63b7f6910219bf2
Mythyndian/Python
/minesweeper.py
1,933
4.03125
4
import random def get_number(a, b, text): while True: number = int(input(text)) if a <= number <= b: return number else: print(f"Podaj liczbe calkowita z zakresu {a} - {b}") def lay_mines(number_of_mines, rows, columns): mines = set() while len(mines) < nu...
a55c3a51e98a6f6b35450a9ac7ce14f36689cbcb
Mythyndian/Python
/zad7.py
664
3.640625
4
class TV: def __init__(self): self.volume = 0 self.chanel = 0 def change_chanel(self): while True: chanel = int(input('Input channel: ')) if chanel in range(1, 101): self.chanel = chanel break def change_volume(self): ...
d72644e3fc842966782f9745f696e5fc4f97e1da
Mythyndian/Python
/zad2.py
981
3.546875
4
import random class Coin: def __init__(self): self.side = "orzel" def throw(self): self.side = random.choice(["orzel", "reszka"]) def show_side(self): return self.side zlotowa = Coin() dwa_zlote = Coin() piec_zloty = Coin() wygrane = 0 przegrane = 0 for i in range(100): sal...
feb56976564ffc9050e2fbfc0538ac172fb9b10b
huangzhilv/PythonPro
/python_demo/error_debug_test/debug.py
2,261
4.1875
4
import logging print('''---------------------调试--------------------- ''') # 需要一整套调试程序的手段来修复bug。 # 第一种 方法简单直接粗暴有效,就是用print()把可能有问题的变量打印出来看看: # 用print()最大的坏处是将来还得删掉它,想想程序里到处都是print(),运行结果也会包含很多垃圾信息。所以,我们又有第二种方法。 def foo(s): n = int(s) print('>>> n = %d' % n) return 10 / n def main(): foo('0') # ma...
e80b3af1c0e4c36c65116188cb4a8d47bf7b6e82
huangzhilv/PythonPro
/python_demo/com_build_in_module/hashlib1.py
2,340
3.71875
4
import hashlib print('''---------------------hashlib--------------------- ''') # 摘要算法简介 # Python的hashlib提供了常见的摘要算法,如MD5,SHA1等等。 # 我们以常见的摘要算法MD5为例,计算出一个字符串的MD5值: md5 = hashlib.md5() md5.update('how to use md5 in python hashlib?'.encode('utf-8')) print("MD5\t", md5.hexdigest()) md51 = hashlib.md5() md51.update('how t...
93d0a14587a957f614156b680182c8b8ade320f5
huangzhilv/PythonPro
/appium_demo/utils/file_utils.py
512
3.625
4
""" 文件操作工具类 """ # 读取文件内容:得到的数据是list{每个item是每行的数据} def read_file(file_path='cursors.txt'): with open(file_path, 'r', encoding='utf-8') as f: _cursors = f.readlines() return _cursors def save_file(file_path='data.txt', string=''): with open(file_path, 'w', encoding='utf-8') as f: f.write(s...
f398f63722bbc7361943d84f629334a9b880ed88
huangzhilv/PythonPro
/python_demo/func_program/higher_order_func/__init__.py
307
4.15625
4
# 高阶函数 # 变量可以指向函数 print("abs(-10)=", abs(-10)) print("abs=", abs) # 可见,abs(-10)是函数调用,而abs是函数本身。 f = abs print("\nf(-10)=", f(-10)) # 传入函数 # 一个最简单的高阶函数: def add(x, y, f): return f(x) + f(y) print(add(-5, 6, abs))
81062dae72817eb8c65da9a33a9d1e83bc969f6c
huangzhilv/PythonPro
/python_demo/oop_program/access_control.py
1,845
3.71875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- ' a test module ' __author__ = 'zhaoyj' print('''---------------------类和实例--------------------- ''') # 在Class内部,可以有属性和方法,而外部代码可以通过直接调用实例变量的方法来操作数据,这样,就隐藏了内部的复杂逻辑。 # 如果要让内部属性不被外部访问,可以把属性的名称前加上两个下划线__, # # 在Python中,实例的变量名如果以__开头,就变成了一个私有变量(private), # # 只有内部可以访问,外部不能访问,所...
234ee019e7a4fd7ed1cec2330e45eacca0206e3c
ldunphy1/504
/dijkstra.py
4,547
4.25
4
# -*- coding: utf-8 -*- ''' Python implementation of dijkstra's algorithm: The value that is used to determine the order of the objects in the priority queue is distance. When a vertex is first created distance is set to a very large number. Will use this to compare the efficiency between priority queue data struc...
6ca784c1bbf55b75d11799de4d6768c2f5fe71e4
notregret/Very-simple-hash-table
/Task1.py
709
3.796875
4
class Table: def display_hash_table(self): for i in range(len(self.hashtable)): print(i, end=': ') for j in self.hashtable[i]: print(j, end=' ') print() def __init__(self): self.main_number = int(input()) self.HashTable = [...
f2c7af0f0476c87c296edec363cfeb57f9149df1
FranciscoAlexAQ/sistema_escolar
/conn.py
2,662
3.703125
4
import sqlite3 # classe para a conexão class Conn: def __init__(self) -> None: self.criarTabelas() # criar a conexão def criarConn(self): try: self.conn = sqlite3.connect('banco_de_dados.db') print('Conectado ao banco de dados!') except Exception as e: ...
7cb9735d6e8c25d21f8bae96ca9780332eab0d27
kanglicheng/learn-python-2020
/yinqi/week3.py
2,359
4.21875
4
# examples of dictionary # Dict = {'Tim': 18,'Charlie':12,'Tiffany':22,'Robert':25} # print(Dict) # del Dict ['Charlie'] # print(Dict) # t = "Tim" in Dict # print(t) # res = {} # print("x" in res) """"""""" problem 1 """"""""" def get_rainfall(dat): res = {} for x in dat: city = x[0] amount...
e0d6766f7479eb2e5add03ea12078607ab117de6
kanglicheng/learn-python-2020
/stephen/week1.py
1,026
4.09375
4
""" Chooses a random integer in [0, 100]. Asks user to enter a guess, terminates only when user guesses correctly """ import random def guessing_game(): number = random.randint(1, 5) while True: guess = int( input("Please enter a number between 1 and 5 (inclusive) ")) if guess == n...
d4d202ce605312997e6c5e52b81c5fe4a8b360dc
Eliale/Python_Aprende
/funciones.py
780
3.65625
4
#Determina si un numero es primo o no def is_primo(num): if num<=1: return False es_primo = True for x in range(2,num): if(num%x==0): es_primo=False return es_primo ## Numeros primos hasta un limite def num_primo(num): for x in range(num+1): if (is_primo(x)): print(x," es un numero primo") num_primo...
c0337d726e173a7af73fe0b029b32c9385cf88ba
FengyiLi1102/Python-Learning
/remove_whitespace.py
331
3.75
4
def remove_whitespace(File): """ This function aims to remove the whitespace or newlines in each line of the given file :param File: given file (txt) :return: none """ new_file = [] for line in File: new_line = line.strip() new_file.append(new_line) return n...
41ff1eddb02393895225916b1454850c5316ffee
FengyiLi1102/Python-Learning
/palindrome.py
488
4.0625
4
def first(word): return word[0] def last(word): return word[-1] def middle(word): return word[1: -1] def is_palindrome(word): """ Check whether the word is mirror symmetry. :param word: :return: None """ word_test = list(word) word_compare = word_test.copy() word_test.r...
9fd8b191b77e79f0c6e335ddefc35817e5edddd6
FengyiLi1102/Python-Learning
/check_fermat.py
749
4.21875
4
import math def check_fermat(a, b, c, n): if n <= 2 or type(a and b and c and n) is not int or a * b * c < 0: raise ValueError oo = 1 for b in range(1, b): for a in range(1, a): for n in range(2, n): c = math.log((a**n + b**n), n) if t...
a9101a3e65d51efa558687737fff62208b29aa3b
FengyiLi1102/Python-Learning
/in_bisect.py
657
3.71875
4
import remove_whitespace as rw myfile = open('D:\Imperial College London\Year 1\MSE101\Computing\words.txt') words_list = rw.remove_whitespace(myfile) def is_bisect(word_list, word): """ Find whether the word is in the dictionary or not by using bisect method. :param word_list: dictionary provided :par...
83a3ffe20be01f35ca056c07b3d85efeb4dda5b6
FengyiLi1102/Python-Learning
/has_duplicates.py
296
3.765625
4
def has_duplicates(alist): """ Check whether there is any character showing up for more than one times. :param alist: provided list :return: True for YES and False for NO """ for char in alist: if alist.count(char) != 1: return True return False
79246b69dfa908ebacec958ef23d5eebe1675aae
FengyiLi1102/Python-Learning
/Disease_prediction.py
11,124
4
4
import numpy as np import random as rd import matplotlib.pyplot as plt import statistics as sta # decide what the person will do def randomEvent(listProb): """Takes a list of probabilities and return an index proportional to the probability in listProb[index]. Input: a list of numbers, must ad...
826c13de0548eaae1f9c1feadf6113ba450bbf18
TlME/PythonDrill_5
/test.py
403
3.65625
4
import time pastTime = int(time.time()) time.sleep(10) currentTime = int(time.time()) diff = [0,0,0,0] def timeConvert(remainder, diff): diff[0] = remainder // 86400 remainder = remainder % 86400 diff[1] = remainder // 3600 remainder = remainder % 3600 diff[2] = remainder // 60 diff[3] = remain...
19c93fcd020809922efe6e9441c99832c8db80e5
luciomolina365/ScrabbleAR_Grupo18
/jugabilidad/jugarComputadora.py
10,577
3.84375
4
import random from jugabilidad.corroborarPalabra import __retorno_informacion from Objetos import CLASS_tablero """En esta hoja, lo que hacemos, setear la IA en todos sus aspectos, desde la dificultad elegida por el usuario, hasta la cantidad de veces que va a intentar hacer una palabra asi tambien como elegir una pos...
c702a1355b9688ac31eb5f513f2d151be4f47134
LABETE/Python2_Homework
/Archives_Homework/src/archivesziped.py
710
3.5625
4
import zipfile import os import glob def zippedfiles(zipfilename): path = os.getcwd() zip_file = os.path.join(path, os.path.basename(zipfilename)+".zip") files_to_zip = [os.path.basename(fn) for fn in glob.glob(zipfilename+"\*") if os.path.isfile(fn)] zf = zipfile.ZipFile(zip_file, "w", zipfile.ZIP_DEF...
f139acbcaffd17d99bdb3ed0397d52686484f6af
ellymeng/Disease-Transmission-Analysis-Toolkit
/shortest_temporal_path.py
3,619
3.5
4
import sys sys.path.append("../") import pandas as pd import matplotlib.pyplot as plt import pickle import openpyxl as xl from openpyxl import Workbook import xlsxwriter as xlsx # Dijkstra's Algorithm: SP(i,j,t)=length of the shortest path from i to j after time t def shortest_path(i,j,t): # first make sure sp(...
bee2a5b4ec1c35807834fa2001cc85ef6ce05119
erinspace/spark_github
/helpers.py
1,614
3.8125
4
""" A bunch of helper functions that, when fixed up, will return the things we need to make this website work! These functions use the weather and twitter APIs!!! """ ## Import python libraries we need up here. ############################################### ### Problem One! ### #########...
3b0ba410283e8a5a28078fb56a363e74c00023ee
Beyzacbn/Programlama_Laboratuvar-
/matris_det.py
1,780
3.890625
4
# 2*2lik bir matrisin determinantını bulan fonksiyon matrix_1=[[1,2],[3,4]] matrix_2=[[13,2,3,4],[5,6,7,8],[92,10,31,42],[13,134,15,16]] print(matrix_1,matrix_2) def det_from_2_by_2(m_1): s_1=m_1[0][0]*m_1[1][1] s_2=m_1[0][1]*m_1[1][0] s_3=s_1-s_2 return s_3 print(det_from_2_by_2(matrix_1)) #1 satır 1 sütu...
1cab81ab36c237cc16149fa8b9a2b143ed08de3f
Beyzacbn/Programlama_Laboratuvar-
/listede_eleman_frekansı.py
748
3.84375
4
#kendisine gönderilen listenin frekans tablosunu geri döndüren fonksiyon my_list=[2,3,5,8,6,4,3,6,2,3,5,6] #liste a=[6,3] #tupple veri değiştirilmez #son halini biliyorsan kullanmak mantıklı b=(6,3) #sözlük c={6:3} #sözlük my_list=[2,3,5,8,6,4,3,6,2,3,5,6] def my_freq(list): freq_dict={} for i in list: ...
7ffc76410fdce9abee95ae3fc4ac1b1b3230971f
mrahrauld/CTDB
/Week2/MakeYourOwn.py
799
3.75
4
# Create a shifted dictionary for a letter def code_dico(letter): shift= ord(letter) - 96 dico = {} # filling the dico with the shifted letters as values for l in 'abcdefghijklmnopqrstuvwxyz': dico[l]= chr((ord(l)-97+shift)%26 +97) return dico # Create list of shifted dictionary for t...
90c6b33481735935b0199d8f52d6bf46b690ad00
SalihTalha/OpenCV-Image-and-Video-Processing
/build/IntroductionToImageProcessing/7-EdgeDetection.py
648
3.53125
4
import cv2 import numpy as np img = cv2.imread("./../../data/koltuk.jpg",0) height,width = img.shape kernelX = np.zeros((3,3)) kernelX[0,0] = -1 kernelX[1,0] = -2 kernelX[2,0] = -1 kernelX[0,2] = 1 kernelX[1,2] = 2 kernelX[2,2] = 1 print(kernelX) kernelY = np.zeros((3,3)) kernelY[0,0] = -1 kernelY[0,1] = -2 kernelY[...
6181d24425e3d1f10eb49b2131380deb324a2965
dipinder2/function_basics_2
/functions-basics-2.py
1,257
4.0625
4
#1. Countdown - recursively def countdown(num, ret_list): if num<0: return 0 ret_list.append(num) countdown(num-1,ret_list) return ret_list print(countdown(5,[])) #2. Print and Return def print_and_return(l1): print(l1[0]) return l1[1] print_and_return([1,2]) #3. First Plus Length def ...
7bb3fd83c75400cf21e849e29494e117a57befa6
EchoDemo/Python
/Python_elementary/unit5/class.py
948
4.125
4
#coding:utf-8 #1、创建dog类: class Dog(object): """docstring for Dog""" def __init__(self, name,age): """初始化属性name和age""" self.name = name self.age = age self.master_numbers=0 #为属性指定默认值 def sit(self): print(self.name.title()+" is now sitting.") def roll_over(self): print(self.name.title()+" rolled over."...
e832abb0aa4eb61822c58068c5ff12dfc06851cd
EchoDemo/Python
/Python_elementary/unit2/list_sort.py
540
4.25
4
#coding:utf-8 #1、使用sort()对列表进行永久性排序; cars=['bmw','audi','toyota','subaru'] cars.sort() #按字母顺序排列(永久性的) print(cars) cars.sort(reverse=True) #按字母逆序排列(永久性的) print(cars) #2、使用函数sorted()对列表进行临时排序; cars=['bmw','audi','toyota','subaru'] print(cars) print(sorted(cars)) #临时排序; print(sorted(cars,reverse=True)) print(cars) #3、...
af8c527939c88a42b22ca354443e814d78722960
Colfu/codewars
/old/6th Kyu/highest_rank_number_in_array.py
1,734
4.03125
4
# Complete the method which returns the number which is most frequent in the given input array. **Cr.1 # If there is a tie for most frequent number, return the largest number among them. **Cr.2 # # Note: no empty arrays will be given. # # Examples # [12, 10, 8, 12, 7, 6, 4, 10, 12] --> 12 # [12, 1...
88f55010db0303121f3c6ba25cba54efe923589f
Colfu/codewars
/6th_kyu/autocomplete_yay.py
2,620
4.21875
4
# It's time to create an autocomplete function! Yay! # The autocomplete function will take in an input string and a dictionary array # and return the values from the dictionary that start with the input string. **Cr.1 # If there are more than 5 matches, restrict your output to the first 5 results. **Cr.2 # If there a...
97d57246dc666f1467d558dbbe93dca6afb379cb
GiorgosPerrakis/My-Code
/Python/Project 3/word_morph.py
6,177
3.65625
4
from collections import deque # libraries that i use import argparse import Levenshtein import sys import time parser = argparse.ArgumentParser() # parameters for input parser.add_argument("dictionary", help="name of diction...
4bd344cd6f856b24372ca7883eb491ae432dc170
kguddeta/LSTM_Stock_Prediction
/Src/predict_lstm.py
5,189
3.53125
4
#@Kemal H Guddeta # Implementation of LSTM using keras tensorflow backend import os os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' import numpy import matplotlib.pyplot as plt import pandas as pd from pandas import read_csv import math import keras from sklearn.preprocessing import MinMaxScaler from sklearn.metric...
cc0c46f64512705f77f195539e24d9f884d10fdd
harshil1903/leetcode
/Math/0050_pow(x,n).py
1,249
3.640625
4
# 50. Pow(x, n) # # Source : https://leetcode.com/problems/powx-n/ # # Implement pow(x, n), which calculates x raised to the power n (i.e., xn). class Solution: def myPow(self, x: float, n: int) -> float: if n == 0: return 1.0 if n == 1: return x res = 1.0 ...
1609ebc72a0b9e172ce7bd11285a33b01aad42fc
harshil1903/leetcode
/Tree/0572_subtree_of_another_tree.py
1,469
3.796875
4
# 572. Subtree of Another Tree # # Source : https://leetcode.com/problems/subtree-of-another-tree/ # # Given the roots of two binary trees root and subRoot, return true if there is a subtree of root with the same structure and node values of subRoot and false # otherwise. # # A subtree of a binary tree tree is a tree ...
5ccf89c99da17a506073fb94c6133529c3b14a1c
harshil1903/leetcode
/Array/0015_three_sum.py
1,385
3.5625
4
# 15. 3Sum # # Source : https://leetcode.com/problems/3sum/ # # 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. # # Notice that the solution set must not contain duplicate triplets. from typing import List ...
c09145457e00cb8f1ab272bc64427518c78b4899
harshil1903/leetcode
/Sort/1528_shuffle_string.py
933
3.765625
4
# 1528. Shuffle String # # Source : https://leetcode.com/problems/shuffle-string/ # # Given a string s and an integer array indices of the same length. # # The string s will be shuffled such that the character at the ith position moves to indices[i] in the shuffled string. # # Return the shuffled string. from typin...
c6098cc1078ed435b3055d4980d93662d32feb2f
harshil1903/leetcode
/String/0763_partition_labels.py
887
4.09375
4
# 763. Partition Labels # # Source : https://leetcode.com/problems/partition-labels/ # # You are given a string s. We want to partition the string into as many parts as possible so that each letter appears in at most one part. # # Return a list of integers representing the size of these parts. from typing import Li...
69f5d722577c77b81da6e6c89cd7e9c2f47bba53
harshil1903/leetcode
/String/1221_split_a_string_into_balanced_strings.py
786
3.96875
4
# 1221. Split a String in Balanced Strings # # Source : https://leetcode.com/problems/split-a-string-in-balanced-strings/ # # Balanced strings are those that have an equal quantity of 'L' and 'R' characters. # # Given a balanced string s, split it in the maximum amount of balanced strings. # # Return the maximum amoun...
6a14c5390b43652cb28a9d597a0583186e6cd015
harshil1903/leetcode
/Array/0053_maximum_subarray.py
1,140
3.984375
4
# 53. Maximum Subarray # # Source : https://leetcode.com/problems/maximum-subarray/ # # Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum. # # A subarray is a contiguous part of an array. from typing import List class Solution: ...