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 |
|---|---|---|---|---|---|---|
f3ac62e200e2831be9ddee68fdd6cce86aced67d | oriys/oreo | /83.remove-duplicates-from-sorted-list.py | 530 | 3.609375 | 4 | #
# @lc app=leetcode id=83 lang=python3
#
# [83] Remove Duplicates from Sorted List
#
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def deleteDuplicates(self, head: ListNode) -> ListNode:
p, q = ListNode(-1), he... |
1a19c7bc3909f4d01095ab55d5bfccfe67c17cfe | Speedsting/ImgProcessingGUI | /image_open.py | 1,296 | 3.71875 | 4 | #!/usr/bin/env
#imageOpen.py
__author__ = "Beckwith, Fletcher, & online sources"
__version__ = "2.0"
'''
Provides a function to bring up a file open dialog box. Much of the code is
there to deal with tkinter issues that arise when trying to use askopenfilename.
2/2/18: confirmed functioning properly in all cases
'''... |
2e25dace558147b388add1d28b583d56caccc0a1 | serenatse98/Checkers-AI | /Checkers_Student-master/src/checkers-python/StudentAI.py | 4,095 | 3.734375 | 4 | from random import randint
from BoardClasses import Move
from BoardClasses import Board
import timeit
# The following part should be completed by students.
# Students can modify anything except the class name and exisiting functions and varibles.
class StudentAI():
def __init__(self, col, row, p):
self... |
c778b78b297cd3c0ae94fe559957d9b6cac3b000 | podhornyi/beetroot | /algorithms/runner.py | 930 | 3.609375 | 4 | from algorithms import fibonacci_search, binary_search
def run():
_range = 0, 500, 2
data = list(range(*_range))
fibonacci_res = []
binary_res = []
start_lookup = -1000
end_lookup = 1000
for i in range(start_lookup, end_lookup):
try:
fibonacci_res.append(fibonacci_se... |
83a7a7116c500102f6a882f116238f78a80afac6 | podhornyi/beetroot | /lesson_20_context_manager/tasks.py | 333 | 4 | 4 | total = 1
def is_palindrome(looking_str: str, index: int = 0) -> bool:
if len(looking_str) <= 1:
return True
if index == len(looking_str) // 2:
return True
return looking_str[index] == looking_str[-(index + 1)] and \
is_palindrome(looking_str, index + 1)
print(
is_palindr... |
2219cafe2f3ffebc576730f45d0a6c99087b13b4 | podhornyi/beetroot | /lesson_19_types/type_hinting.py | 915 | 3.515625 | 4 | import typing
from abc import abstractmethod
def print_user_info(
name: str, age: int, hobby: typing.List[str] = None
) -> None:
print(f'My name is {name}, I am {age} age old\n'
f'My hobbies: {hobby}')
def list_returner() -> dict[str, list[list[int]]]:
return dict(s=[[1,2,3,4], [5,6,78]... |
5b94f9776e64340ee04b2772dbbc1c0ead79b514 | thiagokanagushiku/Python-Exercises | /Fundamentals/Exer.012.py | 173 | 3.515625 | 4 | P = float(input('Qual é o preço do produto? R$'))
print(f'O preço do produto que custava R${P:.2f}, na promoção com o desconto de 5% vai custar R${P*0.95:.2f}')
|
24edd220a0cce3b0ca97a3925ddda3523ae9d062 | thiagokanagushiku/Python-Exercises | /Fundamentals/Exer.008.py | 111 | 3.859375 | 4 | m = float(input('Digite uma medida em metros:'))
print(f'A medida de {m} corresponde a {m*100}cm e {m*1000}mm') |
5df6ee2b22724c49a37f8276b10e6e3b290c1769 | thiagokanagushiku/Python-Exercises | /Control Structures/Exer.040.py | 365 | 3.84375 | 4 | n1 = float(input('Primeira nota:'))
n2 = float(input('Segunda nota:'))
média = (n1 + n2) / 2
print(f'Tirando {n1:.1f} e {n2:.1f}, a média do aluno é {média:.1f}')
if média >= 7:
print('\33[34mO aluno está APROVADO\33[m' )
elif 7 > média >= 5:
print('Você está de RECUPERAÇÂO!')
elif média < 5 :
print('\33[31... |
3e941c2505aa668545f266b6036179163a93dd1e | thiagokanagushiku/Python-Exercises | /Fundamentals/Exer.003.py | 125 | 3.796875 | 4 | x = int(input('Digite um valor:'))
y = int(input('Digite outro valor:'))
print(f'A soma entre {x} e {y} é igual a {x + y}')
|
adc7238d1a3d0f60dade08a7fdbd0542b273eae1 | thiagokanagushiku/Python-Exercises | /Control Structures/Exer.037.py | 535 | 4.0625 | 4 | n = int(input('Digite um número inteiro:'))
print('''Escolha uma das bases para conversão:
[ 1 ] converter para Binário
[ 2 ] converter para Octal
[ 3 ] converter para Hexadecimal''')
opção = int(input('Sua opção:'))
if opção == 1:
print(f'{n} convertido para Binário é igual a {bin(n)[2:]}')
elif opção == 2:
pr... |
0290b9924a9a0021b18a156b58659b8021c4429c | kisung5/CE4302-vector_processor | /Compiler/data_to_mif_python/img_handler.py | 2,864 | 3.53125 | 4 | from PIL import Image
import numpy as np
import sys
def txt_to_mif():
# This function extracts the data from the source text file.
# Image in '6.txt' file, using int values
data_file = open("Compiler/data_to_mif_python/input.txt", "r")
lines = data_file.readlines()
data_file.close()
# data_str... |
017500efe7712f0907d6095c5f6673a0e2fc1b7e | jshields405/Hw1 | /main.py | 3,643 | 4.21875 | 4 | # Author Jack Shields jcs6283@psu.edu
gradepoint1 = input("Enter your course 1 letter grade: ")
credit1 = input("Enter your course 1 credit: ")
if (gradepoint1 == 'A' or gradepoint1 == 'a'):
print("Grade point for course 1 is: 4.0")
gradepoint1 = 4.0
elif (gradepoint1 == 'A-' or gradepoint1 == 'a-'):
prin... |
c23c82aa45964042b6841349c63afc295d4e8605 | rakin000/NumericalMethods | /test.py | 1,204 | 3.65625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Jul 3 08:37:28 2021
@author: SlaughterHouse
"""
import matplotlib.pyplot as plt
import numpy as np
import sympy
def linear_regression(x,y,special=False):
if len(x) != len(y):
print("Invalid Argument: incompatible length.")
return
... |
f2ad1b2a1fb184d6decfed6a4f0759a45a8aa971 | andriitkach1969/Python-course | /src/lesson6_tasks/task1.py | 421 | 3.90625 | 4 | import src.lesson6_tasks.globals as g
# все чудово
totalWords = 0
findWords = 0
char = input('Please enter one symbol to search: ')
for word in g.text.split():
totalWords += 1
if word[0] == char:
findWords += 1
print('There are {0} words in text and {1} of its start(s) with symbol {2}.'.format(totalWo... |
036a6cc731a3f7d5f875e36b4c748cee1562f2ab | HollyBakez/Interview-Practice | /Linked Lists/linked-list.py | 1,164 | 3.734375 | 4 | class Node:
def __init__(self, data=None):
self.next = None
self.data = data
class SlinkedList:
def __init__(self):
self.head = None
def push(self, new_data):
new_node = Node(new_data)
new_node.next = self.head
self.head = new_node
def delete_node(self... |
4ccd157d9d27aa0effaaaa42ca14b91d91a9e7cb | HollyBakez/Interview-Practice | /Linked Lists/Return_Kth_Last.py | 2,336 | 3.765625 | 4 | '''
Return Kth to Last:
Implement an algorithm to find the kth to last element of a singly linked list
Ex)
Input: linked_list, k = 3
A -> B -> C -> D -> None
Output: B
'''
class Node:
def __init__(self, data=None):
self.next = None
self.data = data
class SLinkedList:
def __init__(self):
... |
9b5f15ecf8c540c972cfeeb3fa24c98d4fc9fd1a | GGGWB/LeetCode | /practice/222.py | 365 | 3.671875 | 4 | # def sushu(n):
# for i in range(2,n):
# if n%i==0:
# break
# else:
# print(n)
# def main():
# for i in range(101):
# sushu(i)
# main()
# while True:
# try:
# x = int(input("请输入一个数字: "))
# break
# except ValueError:
# print("您输入的不是数字,请再次尝试输入!")
from queue import Queue
a = -float('inf')
print(a) |
cfb9132f9625a9daa806e81ebf853e52425b9154 | GGGWB/LeetCode | /sort/insertionSort.py | 332 | 3.953125 | 4 | def insertionSort(arr):
for i in range(len(arr)):
preIndex = i-1
current = arr[i]
while preIndex >= 0 and arr[preIndex] > current:
arr[preIndex+1] = arr[preIndex]
preIndex-=1
arr[preIndex+1] = current
return arr
a = [1, 3, 5, 9, 6, 8, 0]
b = insertionSort... |
e4f5a027d5f59f8849a8a374bb6d3427255a370c | GGGWB/LeetCode | /practice/332.py | 481 | 3.765625 | 4 | #
# 判断N是否可由2、5、7相乘得到,如果可以,返回1,否则返回0
# @param N int整型 乘积
# @return int整型
#
def is_product(N):
print(N)
# write code here
while N % 2 == 0: # 化为奇数,个位是 1, 3, 5, 7 ,9
N /= 2
while N % 5==0: # 去除5的干扰,个位是1, 3,
N /= 5
while N % 7==0:
N /= 7
if N == 1:
print('行')
print(' ')
return
else:
print(N)
print... |
885c34593da895b61f60578146f2f17f56ca5667 | lemon-l/Online-Judge | /基础练习/基础练习FJ的字符串.py | 611 | 3.671875 | 4 | '''
Description
FJ在沙盘上写了这样一些字符串:
A1 = “A”
A2 = “ABA”
A3 = “ABACABA”
A4 = “ABACABADABACABA”
… …
你能找出其中的规律并写所有的数列AN吗?
Input
输入描述:
仅有一个数:N ≤ 26。
输入样例:
3
Output
输出描述:
请输出相应的字符串AN,以一个换行符结束。输出中不得含有多余的空格或换行、回车符。
输出样例:
ABACABA
'''
n = int(input())
s = ''
for i in range(n):
... |
3bf4dd9227c2473ea80cbafce0becca12d2ffbbe | lemon-l/Online-Judge | /算法训练/黑色星期五.py | 1,655 | 3.640625 | 4 | '''
Description
问题描述
有些西方人比较迷信,如果某个月的13号正好是星期五,他们就会觉得不太吉利,用古人的说法,就是“诸事不宜”。请你编写一个程序,统计出在某个特定的年份中,出现了多少次既是13号又是星期五的情形,以帮助你的迷信朋友解决难题。
说明:(1)一年有365天,闰年有366天,所谓闰年,即能被4整除且不能被100整除的年份,或是既能被100整除也能被400整除的年份;(2)已知1998年1月1日是星期四,用户输入的年份肯定大于或等于1998年。
输入格式:输入只有一行,即某个特定的年份(大于或等于1998年)。
输出格式:输出只有一行,即在这一年中,... |
3298c39be803e4b721e7d441149265c82fcdd822 | samc1213/ShopGUI | /TextInput.py | 746 | 3.546875 | 4 | import Tkinter as tk
from Constants import BACKGROUND_COLOR, TEXT_COLOR
class TextInput(tk.Entry):
def __init__(self, master, row, column, screen_height, font_fraction):
tk.Entry.__init__(self, master, font=('Helvetica', int(font_fraction * screen_height)),
background=BACKGROUND_... |
ce342fb42d131adfacce454ba2b55d7fd3b2be7f | etensor/tests-tec | /listas-conjuntos.py | 504 | 3.734375 | 4 | lista1 = [2,5,2,1,1,5,8,2,3]
lista2 = [4,2,7,5,9,1]
# A = lista1, B = lista2
# (1) : AnB | (2) : B\A
def intersec_listas(A: list, B: list):
C = [x for x in A if x in B]
print(' A n B : ', C)
def B_dif_A(A: list, B: list):
C = [x for x in B if x not in A]
print(' B \ A : ', C)
def main():... |
4d958cd5c394fd27e09703eaf02a5193c88523fa | tanadonparosin/Project-Psit | /time-count.py | 546 | 4.125 | 4 |
# import the time module
import time
# define the countdown func.
def countdown(t):
big = 0
t += 1
while t != big:
hours = big//3600
left = big%3600
mins, secs = divmod(left, 60)
timer = '{:02d}:{:02d}:{:02d}'.format(hours, mins, secs)
print(timer... |
994fdcc63863bf26194b5a4d8bb20579fb4d03ef | lethisa/python | /playground/basic python V3/function.py | 666 | 4.0625 | 4 | """
learn function syntax in python
"""
# function definition
def minutes_to_hours(second, minutes=60):
hours = minutes / 60 + second / 3600
return hours
print(minutes_to_hours(300))
# function without any parameter
def say_hello():
return "Hello"
# age function
def age_foo(age):
new_age = float(age... |
dda3c16e4e6f35256e2976cd8913cb41bcc843c9 | codeswithjon/100daysofcode | /jsonlesson.py | 241 | 4.09375 | 4 | jsondata = {
"employee":{ "name":"Bill", "age":30, "city":"New York" }
}
for data in jsondata:
if jsondata["employee"]["name"] == "John":
print(jsondata["employee"]["name"])
else:
print("Oops, His name ain't John!") |
dfe3befb2618ffd8c705ec7ffa0bd7bbbe1f4a58 | JimApostolou/sudoku_solver | /sudoku_solver_v1.py | 1,904 | 3.640625 | 4 | sudoku_box= [
[5,3,0,0,7,0,0,0,0],
[6,0,0,1,9,5,0,0,0],
[0,9,8,0,0,0,0,6,0],
[8,0,0,0,6,0,0,0,3],
[4,0,0,8,0,3,0,0,1],
[7,0,0,0,2,0,0,0,6],
[0,6,0,0,0,0,2,8,0],
[0,0,0,4,1,9,0,0,5],
[0,0,0,0,8,0,0,7,9]
]
def solve(board):
find = find_empty(board)
if not find:
return True
... |
dea459be91db309b7634dad9363f3b52d026f294 | Baoza-J/WeChat | /python3中的控制语句/15-while-break.py | 85 | 3.71875 | 4 | n = 1
while True:
n += 1
if n >3:
break
print("lalala")
print()
|
2a0636618fbed0c3d114f59e3fbbd679b53952ce | GanapathiAmbore/Advanced-Python-Programming | /oops/Revision.py | 584 | 3.90625 | 4 |
class Employee:
def __init__(self,name,role,salary,department):
self.name=name
self.role=role
self.salary=salary
self.department=department
def company(self,company):#instance method
print(self.name+' Belongs to:'+company)
@classmethod
def place(cls):
... |
f4b32570c279dd6fde6059908e81e2512c4398e2 | GanapathiAmbore/Advanced-Python-Programming | /oops/python_quiz.py | 739 | 3.75 | 4 | '''numbers_list=[num for num in range(20)]
even_numbers_list=[num for num in range(24) if num%2==0]
comman_elements=set(numbers_list).intersection(even_numbers_list)#[0,2,4,6,8,10,12,14,16,18]
diff_elements=set(numbers_list)-set(even_numbers_list)
diff_elements1=set(even_numbers_list)-set(numbers_list)
print(numbers_li... |
96a2780cd38e41c8697acc08f02731117495e6c9 | GanapathiAmbore/Advanced-Python-Programming | /oops/miniproject.py | 929 | 3.65625 | 4 | class Voter:
def __init__(self,name,age):
self.name=name
self.age=age
def eligible(self,dob,state):
if self.age>=18:
print("{} is Eligible for voting and his age is {} and DOB is {} and his from {}".format(self.name,self.age,dob,state))
else:
print("{} is... |
b5de600dbd62c4e99123f2b33e75c27bf59e5a7e | liuyuzhou/learnpythontoproject | /chapter6/zip_func_use.py | 159 | 3.53125 | 4 | student = ['xiaomeng', 'xiaozhi', 'xiaoqiang']
number = [1001, 1002, 1003]
for name, num in zip(student, number):
print(f'{name}的学号是:{num}')
|
9b9ec5fec1cb88dea5e23c18c0211c25c729f357 | liuyuzhou/learnpythontoproject | /chapter6/exp_normal.py | 181 | 3.640625 | 4 | # name='xiaomeng'
if (name := 'xiaomeng') == 'xiaomeng':
print('hello')
elif name == 'xiaozhi':
# 预留,先不做任何处理
pass
else:
print('nothing')
|
13298de8d4e9380ba225847d42457c9ad55afe81 | liuyuzhou/learnpythontoproject | /chapter6/boolean_oper.py | 491 | 4.0625 | 4 | if (num := 10) <= 10:
if num >= 5:
print('num的值介于5到10之间')
else:
print('num的值不介于5到10之间')
else:
print('num的值不介于5到10之间')
# 简洁写法方式一
if 5 <= num and num <= 10:
print('num的值介于5到10之间')
else:
print('num的值不介于5到10之间')
# 简洁写法方式二
if 5 <= num <= 10:
print('num的值介于5到10之间')
e... |
2d36fb1f234bea026d5a37e6b605fd1628a2e544 | liuyuzhou/learnpythontoproject | /chapter17/query_data.py | 1,015 | 3.5 | 4 | import pymysql
def query_data():
# 打开数据库连接
db = pymysql.connect("localhost", "root", "root", "test")
# 使用cursor()方法获取操作游标
cursor = db.cursor()
# SQL 查询语句
income = 10000
sql = f"SELECT * FROM EMPLOYEE WHERE INCOME > {income}"
try:
# 执行SQL语句
cursor.execut... |
39d9d4e49ef40c33957b0d2f1da653732ab16cd9 | ThaisMB/Curso-em-Video-Python-Exercicios | /ex104.py | 416 | 3.609375 | 4 | def leiaInt(msg):
ok=False
valor=0
while True:
print('='*60)
n=str(input(msg))
if n.isnumeric():
valor=int(n)
ok=True
else:
print('\033[31mERRO!Digite um número inteiro válido.\033[m')
if ok:
break
return valor
... |
3363f9c2730f30fcf2551a4ac70bf41cba20506f | ThaisMB/Curso-em-Video-Python-Exercicios | /ex032.py | 321 | 3.859375 | 4 | from datetime import date
ano = (int(input('Qual ano você quer analisar?Se quiser analisar o ano atual digite 0.')))
if ano==0:
ano= date.today().year
if ano % 4 == 0 and ano % 100 != 0 or ano % 400 == 0:
print('O ano {} é BISSEXTO.'.format(ano))
else:
print('O ano {} NÃO é BISSEXTO.'.format(ano))
|
5b06bd89f849a145f4528cdf9e47e90ffc85a07d | ThaisMB/Curso-em-Video-Python-Exercicios | /ex073.py | 779 | 4.03125 | 4 | times = ('São Paulo','Atlético-MG', 'Flamengo', 'Palmeiras','Internacional', 'Grêmio', 'Fluminense', 'Santos', 'Corinthians','Ceará SC', 'Bragantino', 'Atlético-GO', 'Fortaleza', 'Athlético-PR','sport Recife', 'Bahia', 'Vasco da Gama', 'Coritiba', 'Goiás','Botafogo')
print('-=-'*40)
print(f'Lista de Times do Brasileir... |
3ad33e59b4f42f1d1a90eb7fc4a81f2b8ea5c2de | ThaisMB/Curso-em-Video-Python-Exercicios | /ex039.py | 610 | 4.03125 | 4 | from datetime import date
ano = int(input('Ano de Nascimento:'))
aatual = date.today().year
idade = aatual-ano
print('Quem nasceu em {} tem {} anos em {}.'.format(ano, idade, aatual))
if idade<18:
tempo= 18-idade
aal= aatual+tempo
print('Ainda faltam {} anos para o alistamento.'.format(tempo))
pri... |
25734b32829f2e18b1b9c1fb4b5b1adddd504c8b | ThaisMB/Curso-em-Video-Python-Exercicios | /ex036.py | 437 | 3.734375 | 4 | casa = float(input('Valor da casa: R$'))
salc = float(input('Salário do comprador: R$'))
tempo = float(input('Quantos anos de financiamento?'))
prestação = casa/(tempo*12)
pmáxima = salc*(30/100)
print('Para pagar uma casa de R$ {:.2f} em {:.0f} anos a prestação será de R$ {:.2f}.'.format(casa, tempo, prestação))
if ... |
bea473724db6a486c94bb48ef73ff40205dfe95c | ThaisMB/Curso-em-Video-Python-Exercicios | /ex089.py | 696 | 3.734375 | 4 | turma=[]
while True:
nome=(str(input('Nome:')))
n1=(float(input('Nota 1:')))
n2=(float(input('Nota 2:')))
media=(n1+n2)/2
turma.append([nome,[n1,n2], media])
resposta=(input('Quer continuar? [S / N]'))
if resposta in 'Nn':
break
print(turma)
print('=-'*30)
print('-'*20)
print(f'{"No... |
b9a407aa60dc5c34ce8d13eff65f204738fea490 | ThaisMB/Curso-em-Video-Python-Exercicios | /ex100.py | 478 | 3.53125 | 4 | from random import randint
from time import sleep
números=list()
def sorteia():
print('Sorteando 5 valores da lista:',end='')
for c in range(0,5):
valor=randint(0,10)
números.append(valor)
print(valor, end=' ', flush=True)
sleep(0.5)
print('PRONTO!')
def somaPar():
... |
cc6bec65cde28cc8324852c3523dd7a929e50597 | ThaisMB/Curso-em-Video-Python-Exercicios | /ex102.py | 538 | 3.921875 | 4 | def fatorial(n, show=False):
"""fatorial(n,show=False):
Calcula o fatorial de um número inteiro
Args:
n (int): recebe o número do qual se quer o fatorial
show (bool, optional): mostra o processo
Returns:
f: resultado do fatorial de n
"""
f=1
for c in range(n,0,-1... |
576ba3e91b2f8bbb86ba333fa2b33be3401c9882 | ThaisMB/Curso-em-Video-Python-Exercicios | /ex020.py | 231 | 3.59375 | 4 | from random import shuffle
n1=input('Primeiro Aluno:')
n2=input('Segundo Aluno:')
n3=input('Terceiro Aluno:')
n4=input('Quarto Aluno:')
lista=[n1, n2, n3, n4]
shuffle(lista)
print('A ordem de apresentação é: {}'.format(lista))
|
b785be0f246112f68c7da56f91192d2f938084c6 | ThaisMB/Curso-em-Video-Python-Exercicios | /aula08.py | 120 | 3.96875 | 4 | import math
n=int(input('Digite um número:'))
raiz=math.sqrt(n)
print('A raíz quadrada de {} é {}.'.format(n,raiz))
|
661d44100546002353fe180857a02f232aec9a42 | ThaisMB/Curso-em-Video-Python-Exercicios | /ex091.py | 546 | 3.609375 | 4 | from random import randint
from time import sleep
from operator import itemgetter
jogos={ 'jogador1': randint(1,6),
'jogador2': randint(1,6),
'jogador3': randint(1,6),
'jogador4': randint(1,6) }
ranking= list()
print('Valores sorteados:')
for k,v in jogos.items():
print(f'{k} tirou {v} no da... |
76fe9b2ece4c55a731dc993d4477fb058129647a | ThaisMB/Curso-em-Video-Python-Exercicios | /ex012.py | 196 | 3.65625 | 4 | preco=float(input('Qual o preço do prduto? R$'))
desconto=preco*5/100
print('O produto que custava R${:.2f}, na promoção com desconto de 5% vai custar R${:.2f}.'.format(preco, preco-desconto)) |
6f7c1bc64ff1eb8e9ffbb4abb6c3ef1b063fd9a2 | ThaisMB/Curso-em-Video-Python-Exercicios | /ex054.py | 382 | 3.9375 | 4 | from datetime import date
maiores = 0
menores = 0
for c in range (1,8):
ano=int(input('Em que ano a {}º nasceu?'.format(c)))
atual= date.today().year
if atual-ano>21:
maiores += 1
else:
menores += 1
print('Ao todo tivemos {} pessoas maiores de idade.'.format(maiores))
print('E ta... |
4b7abf9fa0526e99247bc52754279a2ac227c27f | adblockplus/web.adblockplus.org | /services/firebase/utils/html_extender.py | 1,075 | 4.03125 | 4 | """
A simple script to add `.html` extensions to file names
usage: `html_extender.py [-h] dir_path`
"""
import argparse
import os
from pathlib import Path
def is_html_file(path):
with open(str(path), 'r') as reader:
return reader.readline().startswith("<!DOCTYPE html>")
def is_html_file_without_ext(path... |
e87191dbacfef51036b30f2fd84997367ddd5d89 | WakouTTD/learn-python | /attended/lesson11_codestype.py | 447 | 4.3125 | 4 | # pythonは1行が80文字を超えると折り返せというルール
# 長い文字列連結でバックスラッシュ
s = 'aaaaaaaaaaaaaaa' + \
'bbbbbbbbbbbbbbb'
print(s)
x = 1 + 1 + 1 + 1 + 1 + 1 + 1 + \
1 + 1 + 1 + 1 + 1 + 1
print(x)
print('------------------')
# もしくはパレンティス
s = ('aaaaaaaaaaaaaaa' +
'bbbbbbbbbbbbbbb')
print(s)
x = (1 + 1 + 1 + 1 + 1 + 1 + 1 +
... |
37af5ba9203ddb25eb64e16d0a53541061e45c5b | kuncara15/Chapter-5 | /Chapter 5/6 latihan 2 chapter 5.py | 691 | 3.703125 | 4 | from random import randint
print("Hai.. nama saya Mr. Lappie, saya telah memilih sebuah bilangan bulat secara acak antara 0 s/d 100. Silakan tebak ya!!!")
score = 100
AngkaRahasia = randint(0, 100)
while(True):
if(score < 1):
print("\nAnda sudah tidak diperbolehkan bermain karena score sudah habis")
... |
ccf940e0b2250e898fc34b14455a1c71be2e3d1e | mf4lsb/Algorithms | /hackerrank/strings/super_reduced_string.py | 366 | 3.671875 | 4 | import re
def super_reduced_string(input_string):
regex = re.compile(r'(\w)(\1)')
match = regex.search(input_string)
while match:
input_string = input_string.replace(match.group(), '')
match = regex.search(input_string)
return input_string if input_string else 'Empty Stri... |
bce598357923bcca6b6b7de4fde59d969a880c42 | mf4lsb/Algorithms | /hackerrank/python/XML 1 - Find the score.py | 338 | 3.96875 | 4 | # https://www.hackerrank.com/challenges/xml-1-find-the-score
import xml.etree.ElementTree as etree
xml = ""
for _ in range(int(input())): xml += input()
tree = etree.ElementTree(etree.fromstring(xml))
root = tree.getroot()
score = len(root.attrib)
for child in root.findall(".//"):
score += len(child.attrib)... |
2286bac14fa3bbfdee27a85a0f4430c31ec8a07b | mf4lsb/Algorithms | /hackerrank/python/Validating Roman Numerals.py | 345 | 4.15625 | 4 | # https://www.hackerrank.com/challenges/validate-a-roman-number/
def validateRomanNumeral(roman_numeral):
import re
return True if re.search(r"^M{0,3}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})$", roman_numeral) else False
if __name__ == "__main__":
roman_numeral = input()
print(validateRom... |
64ff52f379c2681eb20281d2a0801d09cc61b287 | mf4lsb/Algorithms | /hackerrank/python/DefaultDict.py | 555 | 3.921875 | 4 | # https://www.hackerrank.com/challenges/defaultdict-tutorial
from collections import defaultdict
def getIndices(d):
for e in d['b']:
if e in d['a']:
indices = [i + 1 for i, x in enumerate(d['a']) if x == e]
print(' '.join([str(x) for x in indices]))
else:
prin... |
3142824694c993292621993962f610f85a4cc662 | mf4lsb/Algorithms | /hackerrank/contests/30DaysofCode/Day 12: Inheritance!.py | 561 | 3.734375 | 4 | // https://www.hackerrank.com/contests/30-days-of-code/challenges/day-12-inheritance
class Grade(Student):
def __init__(self, firstName, lastName, phone, score):
Student.__init__(self, firstName, lastName, phone)
self.score = score
def calculate(self):
if self.score < 40: return 'D'
... |
56973aedd81e2bd1bf651ba51237d634046f3598 | amber1710/Converter | /Temperature convertor/tester.py | 1,435 | 4.3125 | 4 | from tkinter import *
#function to create a window
root = Tk()
root.geometry('550x300')
root.title("Conversions")
root.configure(background="turquoise")
#functions to create a label
label = Label(root, text="Press")
label.grid(row=0, column=0, columnspan=3)
label2 = Label(root, text="°Celsius")
label2.grid(row=0, col... |
531e9a35027f7e58777312cc7a65b7594716a633 | amber1710/Converter | /Operators/tuples.py | 233 | 4 | 4 | def distance_from_zero(number):
if type(number) == int or type(number) == float :
positive = abs(number)
print("The number :\n", positive , "true")
else:
print("Nope")
distance_from_zero("dfkk")
|
54184563e1aa3f600bd61fc8d016547a496f8dfc | AnilKOC/some-scripts | /game.py | 267 | 3.703125 | 4 | import random
x=1
y=101
while True:
number=random.randint(x,y)
print("Is your number is? ",number)
answare=input("Upper or Lower?")
if answare == "u":
x=number
if answare == "l":
y=number
if answare == "t": break |
c02aa901d795f6ed60a09cb3aee1ee1c3e61ced3 | AnilKOC/some-scripts | /prime-num-is-it.py | 406 | 4.125 | 4 | import math
def main():
number = int(input("Enter your number :"))
isprime = True
for x in range(2, int(math.sqrt(number) + 1)):
if number % x == 0:
isprime = False
break
if isprime:
print("Your number is an prime number : "+str(number))
else:
print("S... |
50a1ca0a0b6dcbca34eda3762bcbd22d4841cebe | erkang123/python14 | /day4/列表生成式及生成器.py | 163 | 3.796875 | 4 | #Author:Erkang
#列表生成式
[i*2 for i in range(10)]
def func(args):
print(args)
[func(i) for i in range(10)]
#列表生成器
(i*2 for i in range(10))
|
b3ebb7fc25518cf653f3974a996aa23357652449 | erkang123/python14 | /day1/passwd.py | 321 | 3.734375 | 4 | #Author:Erkang
import getpass
_username="erkang"
_password="123"
username=input('name:')
# password=getpass.getpass('password')
password=input('password')
if _username==username and _password==password:
print('welcome user {name} login ...'.format(name=username))
else:
print('inviled username or password') |
a6ddf4d555fdf5b21061281a3507b9e13bca7cfc | erkang123/python14 | /day7/反射1.py | 444 | 3.609375 | 4 | def bulk(self):
print("%s is yelling..."%self.name)
class Dog(object):
def __init__(self,name):
self.name = name
def eat(self):
print("%s is eating..."%self.name)
d = Dog("NiuHanYang")
choice = input('>>:').strip()
# print(hasattr(d,choice))
# print(getattr(d,choice)())
if hasattr(d,choic... |
a8bf589746531639819242f5ed3b132bba7c82a7 | kiolo45/Practica-en-Python | /generador_contraseña.py | 901 | 3.578125 | 4 | import random
# funcion grnerador de contraseña
def generar_password():
mayusculas = ['A', 'B', 'C', 'D','E','F','G','H','I','J','K','L','M','N','Ñ','O','P','Q','R','S','T','U','V','W','X','Y','Z']
minusculas = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','ñ','o','p','q','r','s','t','u','v','w','x'... |
a7ae2759142986393d8a9bed3ed7e9be9b9d1716 | kiolo45/Practica-en-Python | /ejercicio_condicio.py | 231 | 4.09375 | 4 | # -*- coding: utf-8 -*-
# definimos la variable numero
numero = int(input("Escribe un numero: "))
if numero > 5:
print("Es mayor a 5")
elif numero == 5:
print("Es igual a 5")
else:
print("Es menor a 5")
|
ecb497a5eb065d8962f680c8a905859e21705626 | kylepadernilla/cps842Assign2 | /test.py | 165 | 3.8125 | 4 | test = dict()
test['a'] = ['pie','apple']
if 'pineapple' not in test['a']:
print("test 1 complete")
if 'pineapple' not in test['b']:
print('test 2 complete') |
e3d0290ea0c118c282b4a49d9375ddb7ca6aaed3 | paulinho-16/MIEIC-FPRO | /FPRO PLAY/CountingElements.py | 151 | 3.53125 | 4 | def count_until(tup):
contador = 0
for i in tup:
contador += 1
if type(i) == tuple:
return contador-1
return -1 |
ed377da0800f83f5b35cf6ca51a9f691b2691a2e | paulinho-16/MIEIC-FPRO | /PEs/PE3 - Treino/interleave.py | 264 | 3.78125 | 4 | def interleave(alist1,alist2):
result = []
for index,element in enumerate(alist1):
if type(element) != list:
result += [element] + [alist2[index]]
else:
result += (interleave(element,alist2[index]))
return result |
b9345e5c9ef6e1dc59b68e78c04606c7b19f51e9 | paulinho-16/MIEIC-FPRO | /REs/RE06/NomesFormais/formal.py | 373 | 3.546875 | 4 | def formal(name):
lista=name.split()
nomes=len(name.split())
pontos=''
ultimo_nome = lista[nomes-1]
if ultimo_nome[0]!=ultimo_nome[0].upper():
ultimo_nome=ultimo_nome[0].upper()+ultimo_nome[1:]
abreviaturas = lista[:nomes-1]
for i in abreviaturas:
pontos+= i[0].upper()+'. '
... |
bb73eeba2467babe7815addc855ab1c95690e735 | paulinho-16/MIEIC-FPRO | /REs/RE10/Calculadora/calculator.py | 475 | 3.671875 | 4 | def calculator(expr):
if type(expr) == int:
return expr
if type(expr[0]) == tuple:
novo_n1 = calculator(expr[0])
else:
novo_n1 = expr[0]
if type(expr[2]) == tuple:
novo_n2 = calculator(expr[2])
else:
novo_n2 = expr[2]
if expr[1] == '+':
result = no... |
075f41bda255446ee45e8faf311d424457fe344b | paulinho-16/MIEIC-FPRO | /REs/RE04/FizzBuzz/fizzbuzz.py | 270 | 3.75 | 4 | n=int(input('Enter a number: '))
result=""
for i in range(0,n+1):
if (i%3==0 and i%5!=0):
result+='Fizz '
if (i%3!=0 and i%5==0):
result+='Buzz '
if (i%3==0 and i%5==0):
continue
if(i%3!=0 and i%5!=0):
result+= str(i)+ ' ' |
f91b057d48e4848eb87726a92f879e9ca586c315 | paulinho-16/MIEIC-FPRO | /REs/RE09/PalavrasIsomórficas/isomorphic.py | 1,352 | 3.765625 | 4 | def isomorphic(astring1,astring2):
dicionario1 = {}
dicionario2 = {}
for i in range(len(astring1)):
if astring1[i] not in dicionario1:
dicionario1[astring1[i]] = 1
else:
dicionario1[astring1[i]] += 1
for j in range(len(astring2)):
if astring2[j] not in dic... |
33172d984eede4a2b46db08b333818d13a2cec31 | paulinho-16/MIEIC-FPRO | /REs/RE09/NumeraçãoRomana/roman_to_integer.py | 414 | 3.75 | 4 | def roman_to_integer(astring):
dicionario = {'I':1,'V':5,'X':10,'L':50,'C':100,'D':500,'M':1000}
result = 0
for i in range(len(astring)):
if i == len(astring) - 1:
result += dicionario[astring[i]]
elif dicionario[astring[i]] < dicionario[astring[i+1]]:
result -= dicio... |
563e7c5fe5f0cfdaac5172fb6280fbd70ec8f633 | paulinho-16/MIEIC-FPRO | /PEs/PE1 - Treino/question2.py | 236 | 3.890625 | 4 | d = int(input('Enter a digit: '))
num = int(input('Enter a number: '))
result = 0
copia_num = num
while copia_num != 0:
digito = copia_num%10
if digito > d:
result += 2*digito
copia_num = copia_num//10
print(result) |
98e0e872f48074896756d6789971e685c47ccea8 | paulinho-16/MIEIC-FPRO | /FPRO PLAY/PatternHunting.py | 547 | 3.578125 | 4 | def pattern_hunting(l1,l2,p):
result = []
def procurar(l_1,l_2):
for index,string in enumerate(l_1):
substrings = []
for i in range(len(string)):
for j in range(i,len(string)):
substrings += [string[i:j+1]]
for substring in substrin... |
efc657bf82e49c685bd69d0bb58f3ea94cce8452 | zlogdanbr/mypython | /src/ebook.py | 747 | 3.515625 | 4 | import sys
import os
import pathlib
from pathlib import Path
mydir = "C:\\Users\\Administrador\\Biblioteca do calibre"
myext = "zip"
myextfinal = ".cbz"
def list_files(dir):
for root, dirs, files in os.walk(dir):
for name in files:
fext = getextension(name)
if ( fext... |
8b89fef3e3f0004286d33eec5497faa547ab8888 | honjy/foundations-homework | /01/homework-1-hon.py | 4,230 | 4.09375 | 4 | #Jing Yi Hon
#May 23, 2016
#Homework 1
name = input("What, Good Sir, is your name?")
print("I bid thee good day " + name)
year_of_birth = input("What year were you born in?")
if int(year_of_birth) > 2016:
year_of_birth = input("Are you sure? Try again")
age = 2016 - int(year_of_birth)
print("You are", age,... |
7fce8e0908dc2640c849a358c77ec8be98f85b56 | RegAse/w_FK2014 | /Hrópmerkt.py | 139 | 3.921875 | 4 | x = int(input())
print(x,"! = ",sep="",end="")
for y in range(1,x + 1):
if x == y:
print(y,end="")
else:
print(y,"x ",end="")
input() |
cdd441521a3c0a8a6c3b88d24ac37f32016ca380 | PranavAnand587/10_Days_Of_Statistics_In_Python | /Day 1/Standard_Deviation.py | 342 | 3.671875 | 4 | # Enter your code here. Read input from STDIN. Print output to STDOUT
import math
n = int(input())
arr = list(map(int,input().split()))
def mean(a):
s = sum(arr)
return s/n
def std_dev(a,size,mu):
dis = 0
for i in a:
dis+= (mu-i)**2
return round(math.sqrt(dis/size),1)
mu = mean(arr)
pri... |
1f04758c64cfdfa4954b1d51e9e56c35c5a79e2c | RohanRatwani/SSW-810 | /HW_05_Rohan_Ratwani/inclass.py | 102 | 3.546875 | 4 | def inclass(a:int):
s=(input("Enter integers to be reversed : "))
print(s[::-1])
inclass(int)
|
15649f0363f66abfd2d70b4e134dd6187782c6c0 | RohanRatwani/SSW-810 | /Practice.py | 763 | 3.984375 | 4 | import random
from typing import Iterator,Optional,List
def random_integer_generator(minimum: int, maximum: int) -> Iterator[int]:
#while True:
#for i in range(0,10):#random.randint(minimum,maximum+1):
i = random.randint(minimum,maximum)
yield i # return a random integer between 0 and 10 inclusive.
d... |
d295b35955c349efaef24cde657b95e397890889 | RohanRatwani/SSW-810 | /generators.py | 15,036 | 3.71875 | 4 | from typing import List,Dict,Tuple,DefaultDict
from collections import Counter,defaultdict
import random, string, os,sys
from typing import Iterator,Optional,Any,Sequence
from datetime import datetime, timedelta
# def generator_function() -> List[int]:
# generator_list:List[int] = [[1,2,3],[4,5,6],[7,8,9]]
# f... |
2e4554a4e5d00dedfdf276f950446273d40f45c0 | LyndonGingerich/hunt-mouse | /input.py | 1,224 | 4.40625 | 4 | """Helper methods for getting user input"""
def get_bool_input(message):
"""Gets boolean input from the terminal"""
values = {'y': True, 'yes': True, 'n': False, 'no': False, '': False}
return get_dict_input(message, values)
def get_dict_input(message, values):
"""Selects value from a dictionary by ... |
3eae55bc366283fd90e8ac2d373770079968e639 | lysergiad/Violent-python-workthrough | /dictionary-512.py | 889 | 3.5 | 4 | from passlib.hash import sha512_crypt
hash = sha512_crypt.hash("egg",salt = "HX")
def testPass(cryptPass):
salt = cryptPass.split('$')[2]
dictFile = open('dictionary_512.txt','r')
for word in dictFile.readlines():
word = word.strip('\n')
cryptWord = sha512_crypt.hash(word,salt... |
14989fb13ed1002e52e12729432f3da6301762b2 | ibrahimalmakky/py4ai | /session3.py | 817 | 3.703125 | 4 | # Class
class Experiment:
optims = ["SGD", "ADAM"]
def __init__(self, epochs, learning_rate: int, optim="SGD"):
self.epochs = epochs
self.lr = learning_rate
self.optim = optim
def train(self):
print("training..")
for epoch in range(0, self.epochs):
prin... |
556f21faacf3d14bd98d61f7369b13b4c07243de | Grover0/STBP_Calc | /Lib/Cross_section.py | 1,845 | 3.578125 | 4 | class Cross:
def __init__(self, forces, concrete, reinforcement):
self.forces = forces
self.concrete = concrete
self.reinforcement = reinforcement
self.notes = []
class Circle(Cross):
def __init__(self, forces, concrete, reinforcement, diameter):
super().__ini... |
6520fb3344f0becd9f77ad3708deb7b44cc9956c | danieljhegeman/2_3_tree | /twoThreeTree.py | 443 | 3.59375 | 4 | import Tree
class twoThreeTree():
def __init__(self, vals=[]):
self.__treePtr = Tree.twoThreeTree()
for val in vals:
self.insert(val)
def insert(self, val):
return Tree.addNode(self.__treePtr, val) == 1
def remove(self, val):
return Tree.removeNode(self.__treePtr, val) == 1
def conta... |
c7a1ed5b4d9eff957d6cebf924aeeb9ab8e0da53 | codingXllama/Tkinter-with-Python | /FirstApp/app.py | 829 | 4.4375 | 4 | import tkinter as tk
# Creating the window
window = tk.Tk()
# Creating a window title
window.title("First Application")
# Creating the window size
window.geometry("400x400")
# creating the LABEL
title = tk.Label(text="Welcome to my First Tkinter APP!",
font=("Times New Roman", 20))
# Placing the ti... |
41a862c0580de95a2589f347101430808473d053 | sarahady1/newforumsworkshop | /atmsolution/listatm.py | 1,482 | 3.8125 | 4 |
class ATM():
def __init__(self,atm_balance,bank_name):
self.balance=atm_balance
self.bank_name=bank_name
self.withdrawal_list=[]
def withdraw(self,request):
self.print_sep()
print "CURRENT BALANCE="+str(self.balance)
print "Request="+str(request)... |
7127aa2e9dee9065479321dafa99bdb4a6eac90f | coreyarch1234/Tweet-Generator | /hacker_rank_problems/reading_raw_input.py | 508 | 3.875 | 4 | # Task
# Read a line of input from stdin and save it to a variable, . Then print the contents of to stdout.
#
# Input Format
#
# A single line containing sentence .
#
# Constraints
#
# Output Format
#
# Print the contents of to stdout.
#
# Sample Input
#
# How many chickens does it take to cross the road?
# Sample Ou... |
3813ccf85d5136d2e028717370697c331b9c98d7 | geocarvalho/python-ds | /python-base/escola_v2_com_sets.py | 1,180 | 4.1875 | 4 | #!/usr/bin/env python3
"""Exibe relatório de crianças por atividade.
Imprimir a lista de crianças agrupadas por sala
que frequentas cada uma das atividades.
"""
__version__ = "0.1.1"
########################################################
# ATENçÃO: MODIFIQUE ESSE CÓDIGO! #
# Tente utilizar dic... |
1107ac945cf3b379a8be5386035c850063314981 | LeleCastanheira/cursoemvideo-python | /Exercicios/ex029.py | 489 | 3.828125 | 4 | '''Escreva um programa que leia a velocidade de um carro
Se ele ultrapassar 80km / h, mostre uma mensagem dizendo que ele foi multado
A multa vai custar R $ 7,00 por cada Km acima do limite.'''
velocidade = int(input('Qual é a velocidade atual do carro? '))
if velocidade > 80:
multa = (velocidade - 80) * 7
pri... |
39c745abdbfa3e556113efe662a8215254bfc7dd | LeleCastanheira/cursoemvideo-python | /Exercicios/ex021.py | 341 | 3.546875 | 4 | # Faça um programa em Python que abra e reproduza um arquivo mp3
'''import pygame
pygame.init()
pygame.mixer.music.load('ex021.mp3')
pygame.mixer.music.play()
pygame.event.wait()
Esse método do professor não funcionou'''
from pygame import mixer
mixer.init()
mixer.music.load('ex021.mp3')
mixer.music.play()
input('Está... |
bb12d07df682d88020559ed1a2e2d4bb8afe1556 | LeleCastanheira/cursoemvideo-python | /Exercicios/ex014COLORIDO.py | 145 | 3.8125 | 4 | t = float(input('Informe a temperatura em °C: '))
print('\033[1;4;32m''A temperatura de {}°C correspode a {}°F!''\033[m'.format(t, 9*t/5+32))
|
1d6b889ec8c0d1dbff4a7e7fcb063e0f3649969a | LeleCastanheira/cursoemvideo-python | /Exercicios/ex014.py | 235 | 4.28125 | 4 | # Conversor de temperatura: escreva um programa que converta uma temperatura digitada em ºC para ºF
c = float(input('Informe a temperatura em °C: '))
f = 1.8 * c + 32
print('A temperatura de {}°C corresponde a {}°F!'.format(c, f)) |
ba6864644c6e198496d96e667097dfff0b1f9f09 | LeleCastanheira/cursoemvideo-python | /Exercicios/ex009COLORIDO.py | 519 | 3.671875 | 4 | n = int(input('Digite um número para ver sua tabuada: '))
print('¨'*20)
print(n, 'x 1 =''\033[7;31;40m', n, '\033[m')
print(n, 'x 2 =''\033[7;31;40m', n*2, '\033[m')
print(n, 'x 3 =''\033[7;31;40m', n*3, '\033[m')
print(n, 'x 4 =''\033[7;31;40m', n*4, '\033[m')
print(n, 'x 5 =''\033[7;31;40m', n*5, '\033[m')
print(n, '... |
9d0f531bb514451c66badae1260de76edd8c6b48 | LeleCastanheira/cursoemvideo-python | /Exercicios/ex033.py | 484 | 4.03125 | 4 | '''Faça um programa que leia três números e mostre qual é o maior e qual é o menor
'''
n1 = float(input('Primeiro valor: '))
n2 = float(input('Segundo valor: '))
n3 = float(input('Terceiro valor: '))
#Verificando o MENOR
menor = n1
if n2 < n1:
menor = n2
if n3 < n1:
menor = n3
print('O menor número digitado é {... |
a4c8719cf2beff89de0b48c65d6a9a50173c7e58 | LeleCastanheira/cursoemvideo-python | /Exercicios/ex035COLORIDO.py | 384 | 3.921875 | 4 | print('\033[1;34m''-='*15)
print('Analisador de Triângulos')
print('-='*15, '\033[m')
r1 = float(input('Primeiro segmento: '))
r2 = float(input('Segundo segmento: '))
r3 = float(input('Terceiro segmento: '))
if r2 < r1 + r3 and r3 < r1 + r2 and r1 < r2 + r3:
print('Os segmentos acima PODEM FORMAR triângulo!')
else:... |
629362d018a3139c2af085b3725ffa963c789144 | LeleCastanheira/cursoemvideo-python | /Exercicios/ex011.py | 463 | 4 | 4 | # Faça um programa que leia a largura e a algura de uma parede em metros, calcule a sua área e a quantidade de tinta necessária para pintá-la, sabendo que cada litro de tinta pinta uma área de 2m²
l = float(input('Largura da parede: '))
h = float(input('Altura da parede: '))
a = l * h
q = a / 2
print('Sua parede tem a ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.