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 |
|---|---|---|---|---|---|---|
f06a59233c6ebdbd37e9da2a4ca06321ca839055 | clwater/lesson_python | /old/learn_old/if.py | 693 | 4.125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#if 注意条件后加: 自上至下 某个符合后则忽略后面的
# age = 20
# if age >= 6:
# print('teenager')
# elif age >= 18:
# print('adult')
# else:
# print('kid')
# birth = input('birth: ')
# #通过int()将input得到的str类型转换为int类型
# birth = int(birth)
# if birth > 2000:
# print '00后'
# else :
#... |
9bd43e7c98c9d694f252fadc1a8075bced36ca74 | michalShawat/Stenography-project | /cifar10 Stenography/encoder3.py | 3,777 | 3.609375 | 4 | from PIL import Image
import numpy as np
'''
create a bin string of the code and
encode in the image in the 3-th layer
here we encode in ered pixel only
'''
def encode_image(img, malicious):
length = len(malicious)
binstring=getByte(length)
for c in malicious:
binstring+=getByte(ord(c))
encode... |
8b74339f4ebc2af3bdd85ea480fb08300c736d82 | lTocquetCPE/TPCSDEV2 | /windows/MainWindow.py | 2,043 | 3.765625 | 4 | """
class containing the display logic and the layout of the main window
Also manages the popups necessary to make the game work
11/12/20
by Loïc (Pyrrha) TOCQUET
"""
from tkinter import Tk, Label, Canvas, Button, Entry, Toplevel
class MainWindow(Tk):
# init manages the layout of the window
def __init__(se... |
5358bd76c9bb73d36bdfddd4a078eaf4ad4488e1 | JpBongiovanni/PythonFunctionLibrary | /collatz.py | 384 | 3.96875 | 4 |
def collatz(num):
try:
terms = []
while num != 1:
if num % 2 == 0:
num = num / 2
terms.append(int(num))
else:
num = 3 * num + 1
terms.append(int(num))
print(terms)
return terms
except:
... |
226925d424f1a680351695938dfd0380b6eabee2 | JIdigit/Part2-Task3 | /task3.py | 77 | 3.9375 | 4 | num=int(input())
print("Previous is "+str(num-1)+" and next is " +str(num+1)) |
c64653506bb3b2eaca0fe0c38a9354bb34dc0f0b | Calvin-Brown-Software/Python-Graph-Maker | /Source.py | 2,844 | 3.8125 | 4 | #The imported modules:
from tkinter import *
class Dot:
def __init__(self, canvas, x, y):
self.canvas = canvas
self.id = PhotoImage(file = "C://Dot.gif")
self.canvas.create_image(x, y, image = self.id)
#The 'x' global variable:
x = [-3, -2, -1, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
y = []
def gr... |
3a1617ce56abb6e147be81be71a7dd74b9e0d7c1 | bluesaiyancodes/DailyEssentialCode | /HaacktoberFest 2019/isArmstrong.py | 249 | 3.75 | 4 | def is_armstrong(n):
m=0
t=n
#flag = False
while n>0:
r=(n%10)
#m += r ** 3
m=m+(r*r*r)
n=n/10
print m
if m==t:
#flag = True
print "Yes it is armstrong"
'''else:
print "Not it is not armstrong"'''
return flag
is_armstrong(153)
|
12fd7ae41f492a7cb882e38fcdb9d729d6289189 | rmesquita91/exerciciosPOOpython | /exercicio03.python.py | 1,007 | 4.46875 | 4 | """
Faça um Programa que leia três números e mostre o maior e o menor deles.
"
print ('************************************************************')
print ('*** INFORMA O MAIOR E MENOR NUMERO ************************')
print ('***************** RAFAEL MESQUITA *************************')
print ('****** SISTE... |
54aa8af3f0c7180bc346b64f6c3b8ea56a6937a3 | nogia/git_repo | /HA_Analytics/HA_Anal1/HA_Analytics_1.py | 948 | 3.578125 | 4 | import pandas as pd
data = pd.read_csv("../turnover.csv")
data.info()
print(data.head())
print(data.salary.unique())
# Change the type of the "salary" column to categorical
data.salary = data.salary.astype('category')
# Provide the correct order of categories
data.salary = data.salary.cat.reorder_categories(['low','med... |
05496d6763ef4cceada00790ca47f09afd818d90 | usman-pervaiz/LAB-01 | /4.py | 117 | 4.1875 | 4 | r=float(input("Enter the value of radius:"))
v=(4*((3.142)*(r**3))/3)
print("The value of sphere is: ",v," m**3")
|
e0aea95c21e5134bef5cf6501033d9b9d7d8119a | hwichman/CYEN301 | /KeyedCaesar/KeyedCaesar.py | 1,330 | 4.21875 | 4 | import sys
alphabet = "abcdefghijklmnopqrstuvwxyz"
### Main ###
# Check for arguments
if sys.argv < 3:
raise Exception("CaesarCipher.py <1-25> <alphabetKey>")
try:
# Make sure second argument is an int
numKey = int(sys.argv[1])
except:
print "Key must be an integer."
alphaKey = sys.arv[2]
# New al... |
9d81984caca44ffc2d40c3def8eef8f47b406800 | Naatoo/Learning | /Fluent_Python/01_Data_Model/Rectangle.py | 734 | 3.578125 | 4 | from collections import namedtuple
from random import randint
Rect = namedtuple("Rectangle", ["length", "width"])
class Rectangle:
lengths = [randint(1, 20) for x in range(10)]
widths = [randint(1, 10) for y in range(10)]
def __init__(self):
self._dimensions = [Rect(length, width) for length, wi... |
72bfcd1413f09d162ec07edf0e8fcfd2e7c84010 | mmlynarik/python-weekend-ba-task | /src/args.py | 1,992 | 3.96875 | 4 | import argparse
class Args:
"""Class for reading and validating program's input arguments."""
def __init__(self):
args = self.parse_args()
self.validate_args(args)
self.csvfile = args.csvfile
self.origin = args.origin
self.destination = args.destination
self.ba... |
3f03a6d797572cac62614dddbfa57bd4d3b36db8 | vladi837/tms-21 | /hw05/task_5_4.py | 310 | 4 | 4 | '''Для заданного числа N составьте программу вычисления суммы
S=1+1/2+1/3+1/4+...+1/N, где N – натуральное число. [02-3.2-ML21]'''
n = int(input('Введите число: '))
s = 0
for i in range(1, n + 1):
s = s + 1 / i
print(s)
|
9ecdbc97860f063c4fc5dc74ea1c672c8c279212 | vladi837/tms-21 | /hw06/task_6_1.py | 729 | 3.9375 | 4 | import random # создаем матрицу(1задание)
def createArray():
r=0
n = int(input('Enter first index matrix: '))
m = int(input('Enter second index matrix: '))
array = []
for i in range(n):
array.append([])
for j in range(m):
array[i].append(random.randint(0,100))
... |
f0394902274f210b1d0c372094460f1c14b6c668 | dugarab/ds200 | /Barplot.py | 1,202 | 3.515625 | 4 | import pandas as pd
import matplotlib.pyplot as plt
import sys
#create dataframe from csv
df=pd.read_csv('GenderRatioInstitutes2012-13.csv',encoding='latin1', header=None, names=['Institutions', 'All', 'SC', 'ST', 'OBC', 'PWD', 'Muslim', 'Other Monrities', 'Foreign Students'])
combinedList = []
#create a list... |
52cf091cbdc7ffc94b3bf2048aa0be2939b907a7 | LTimusk/Y10Design-PythonLT | /testString.py | 176 | 3.921875 | 4 | givenString = "Hello"
numChars = len(givenString)
print (numChars)
newString = ""
for x in range(0, numChars, 2):
# print (newString)
print (newString + givenString[x]) |
46de16ab985ac320d4bdf6d7189b4bccbfca3bfe | luizsac/dio-cde-desafios-python | /triangulo.py | 230 | 3.671875 | 4 | a = [float(x) for x in input().split()]
#complete o desafio
if a[0] + a[1] > a[2] and a[0] + a[2] > a[1] and a[1] + a[2] > a[0]:
print(f"Perimetro = {sum(a):.1f}")
else:
print(f"Area = {((a[0] + a[1]) * a[2]) / 2:.1f}")
|
2a4a4034e78d0dca4a5e3429fc29e0df2cfbb35e | popovata/ShortenURL | /shorten_url/app/utils.py | 393 | 4.21875 | 4 | """
A file contains utility functions
"""
import random
import string
LETTERS_AND_DIGITS = string.ascii_letters + string.digits
def get_random_alphanumeric_string(length):
"""
Generates a random string of the given length
:param length: length of a result string
:return: a random string
"""
... |
ddb3595d2d4a595cf12dba45235c64d1428ab7ec | Walkingstickscout/BeeasonVanHoesenJacobBrim_1_4_7 | /BeeasonVanHoesenJacobBrim1_4_7.py | 496 | 3.5 | 4 | from __future__ import print_function
import PIL
import matplotlib.pyplot as plt
import os.path
def picture_alteration(original_image):
print('What alteration would you like to do to the picture?', '\n')
alteration=['RoundCorners', 'Frame', 'CornerCut', 'Swirl', 'ColorChange', 'AddText', 'AddShape']
for a... |
39fb958a80e79695d39dd5a15cfa0940f1866fb0 | jatimberlake2/CS260 | /Lab3/eight.py | 371 | 3.8125 | 4 | from grid import Grid
from arrays import Array
def main():
cube = Grid(3,3)
for i in range(cube.getHeight()):
for j in range(cube.getWidth()):
cube[i][j] = Array(3)
for x in range(cube.getHeight()):
for y in range(cube.getWidth()):
for z in range(len(cube[x][y])):
cube[x][y][z] = str(x)+str(y)+str(z)
... |
eaafa2ee40e258b1e5cf15d43fa473814af138f4 | luke-de-vos/word-maker | /makeWord.py | 8,014 | 3.53125 | 4 | '''
Luke De Vos
Generate words with char ngrams and markov chains
'''
'''
TODO
add --help
'''
import random
import sys
import re
import time
from sty import fg, bg, rs
'''
FUNCTIONS ==
'''
#returns true if passed string has a non-whitespace next char in passed list
def canContinue(passKey): #(string)
global gramD
... |
c3fcf76fafbe695330426aa02215e829176d2e52 | LukeStanislawski/Medilanac | /utils/merkle.py | 1,494 | 3.84375 | 4 | from utils import crypt
def merkle_tree(data : [str]):
"""
Generates a merkle tree for a list of strings.
Merkle tree leaves are hashes of the combination of two item hashes.
E.g. if len(data) == 6, len(mtree[-1]) = 3
data: List of items to generate merkle tree for
"""
if data is None or len(data) < 1:
retu... |
97ca6177ca87fad898af40a0b77a618a34110d40 | GabrielRioo/Curso_em_Video | /Curso_Python/Exercícios/ex025.py | 270 | 4.0625 | 4 | # Crie um programa que leia o nome de uma pessoa e diga se ela tem "SILVA" no nome
# Em qualquer lugar tenha o silva. Retornar true ou false
nome = str(input("Digite o seu nome: ")).strip().upper()
print('SILVA' in nome, "\n", nome)
#OU
print('SILVA' in nome.upper()) |
3e34aff568ec6791a2cb378f93a45ce714083911 | GabrielRioo/Curso_em_Video | /Curso_Python/Exercícios/ex016.py | 401 | 4.25 | 4 | # Crie um programa que leia um numero Real qualquer pelo teclado e mostre na tela a sua porção inteira
# Ex: Digite um numero: 6.127, o numero 6.127 tem a parte inteira 6.
num = float(input('Digite um numero: '))
print('O numero digitado foi {} e em inteiros é: {}'.format(num, int(num)))
# OU
from math import trunc
p... |
36e8cabf026426a7aa857f12bbd7d44f6760c4b3 | GabrielRioo/Curso_em_Video | /Curso_Python/Desafios_Scripts/02_DataNascimento.py | 167 | 3.78125 | 4 | input ("Informe o dia, mes e ano de seu nascimento.")
dia = input("Dia: ")
mes = input("Mes: ")
ano = input("Ano: ")
print("Você nasceu em: ", dia,"/", mes,"/", ano)
|
5f7d8068e478ec41d044e710c80bfd8f6a2047c8 | GabrielRioo/Curso_em_Video | /Curso_Python/Exercícios/ex038.py | 636 | 3.890625 | 4 | # Escreva um programa que leia dois números inteiros e compare-os, mostrando na tela uma mensagem: O primeiro valor é
# Maior. O segundo valor é Maior. Não existe valor maior, os dois são iguais
n1 = int(input('Digite um numero: '))
n2 = int(input('Digite o segundo numero: '))
color = {
'limpa':'\033[m',
'verm... |
eb8becca5bf33912facd41178ee8c3ea667cf65c | GabrielRioo/Curso_em_Video | /Curso_Python/Exercícios/ex033.py | 676 | 4.03125 | 4 | # Faça um programa que leia tres numeros e mostre qual é o maior e qual é o menor
n1 = int(input("Digite o primeiro numero: "))
n2 = int(input('Digite o segundo numero: '))
n3 = int(input('Digite o terceiro numero: '))
menor = n1
if n2 < n1 and n2 < n3:
menor = n2
if n3 < n1 and n3 < n2:
menor = n3
maior = n1... |
f37120fe666220c390e4f1b0cef108e28ea53032 | GabrielRioo/Curso_em_Video | /Curso_Python/Exercícios/ex034.py | 495 | 3.890625 | 4 | # Escreva um programa que pergunte o salario de um funcionario e calcule o valor do seu aumento.
# Para salarios superiores a R$1250,00, calcule um aumento de 10%
# Para as inferiores ou iguais, o aumento é de 15%
salario = float(input('Qual é o seu salário? '))
if salario >= 1250:
aumento = salario * 0.10
pri... |
f2fba366bd724b0bbcb6d9ef80cad1edcb1e546e | AswinSenthilrajan/PythonRockPaperScissor | /PaperStoneScissor/StonePaperScissor.py | 848 | 4.1875 | 4 | from random import randrange
options = ["Scissor", "Stone", "Paper"]
random_number = randrange(3)
user_option = input("Choose between Paper, Scissor and Stone:")
computer_option = options[random_number]
def play():
if computer_option == user_option:
user_optionNew = input("Choose again:")
elif compute... |
01f037a7b031a05b6965a377c691e5369c9ba1a4 | qq252223804/mysite | /login/__init__.py | 703 | 4.09375 | 4 | #带参数的装饰器函数
# Python也支持带参数的装饰器,比如刚刚的cost_time加入一个报警机制,如果函数执行耗时大于3秒,就发出警告。
import random
import time
#
# def cost_time(warn=3):
# def wrap(func):
# def in_wrap():
# start_time = time.time()
# result = func()
# cost = time.time() - start_time
# print("cost time... |
2311b07ae564fd53cabee5532a39392c9e86793c | hiteshvaidya/Football-League | /football.py | 2,397 | 4.25 | 4 | # Football-League
#This is a simple python program for a Football League Management System. It uses sqlite and tkinter for managing database and UI.
#created by Hitesh Vaidya
from tkinter import *
import sqlite3
class App:
def __init__(self,master):
frame = Frame(master)
frame.pack()
a=St... |
713077769607bf2ae5c385f61feda5361d415c4a | UrszulaT/nauka_pytona | /piec.py | 216 | 3.96875 | 4 | samochody = ('syrena' , 'polonez', 'opel' , 'kia')
print(samochody[0])
print(samochody[2])
for s in samochody:
print(s)
for idx in range( len(samochody)) :
print("idx: " + str(idx) + " : " + samochody[idx])
|
6d84e2397e130ff7e8986fd7f55f29e7a6b489db | Stanislaw-Golebiewski/LPO-LSR-projekt | /dino_chrome/controller/simple_controller.py | 1,671 | 3.515625 | 4 | import time
from pykeyboard import PyKeyboard
class SimpleController:
def __init__(self, window_size):
self.window_width = window_size[0]
self.window_height = window_size[1]
self.k = PyKeyboard()
self.ground_y = None
self.flying = None
def take_action(self, data):
... |
3c26fc28292de5d2de2f93e53195986ef70d3f79 | KacyInGitHub/Yoyo | /interview_tests/test4.py | 528 | 3.578125 | 4 | # -*- coding:utf-8 -*-
# author: lining3
# date: 2020/11/19 2:07 下午
# file: test4.py
# IDE: PyCharm
# closure
def outer():
x = 10
y = [4]
def inner():
nonlocal x # 两种内函数修改外函数临时变量的办法:1、nonlocal修饰内函数使用的临时变量;2、外函数临时变量类型为可变类型
x += 1
print(x)
y[0] += 1
print(y[0])
... |
4351eeb895adae036c7d6de6ad4c6c79fee34805 | KacyInGitHub/Yoyo | /test5.py | 495 | 3.90625 | 4 | # -*- coding:utf-8 -*-
# author: lining3
# date: 2020/11/11 8:05 下午
# file: test5.py
# IDE: PyCharm
def formate_list(l):
middle = []
if isinstance(l, list):
pre = l[0:1]
middle = l[1:3]
last = l[3:]
middle.extend(pre)
middle.extend(last)
return middle
def formate_... |
4c631a1823264b5a829793c8f42459fd6bcab37e | KacyInGitHub/Yoyo | /test9.py | 419 | 3.921875 | 4 | # -*- coding:utf-8 -*-
# author: lining3
# date: 2020/11/12 10:33 上午
# file: test9.py
# IDE: PyCharm
def bubble_sort(l):
if isinstance(l, list):
for i in range(len(l)-1):
for n in range(len(l)-1-i):
if l[n] > l[n+1]:
l[n], l[n+1] = l[n+1], l[n]
return l
... |
1d60b9414efde1059d1868b31ae2f6fdd1862475 | Sudhakaran7/Goat-Latin | /convert.py | 450 | 3.734375 | 4 | class Solution(object):
def toGoatLatin(self, S):
"""
:type S: str
:rtype: str
"""
def convert(S):
vowel = set('aeiouAEIOU')
for i, word in enumerate(S.split(), 1):
if word[0] not in vowel:
word = word[1:] + word[:1]... |
2541b58048a273a757541d64790f30504eeaa9a6 | devdo-eu/zombreak | /logic/city_card.py | 464 | 3.703125 | 4 | from enums.zombie import ZombieType
class CityCard:
def __init__(self, zombie: ZombieType = ZombieType.ZOMBIE):
if zombie == ZombieType.SURVIVOR:
raise Exception('Card cannot be init with survivor on top!')
self.active = True
self.top = ZombieType.SURVIVOR
self.bottom =... |
2a6d9ec5ef2edab67f8e6c92a3b57e6e4d3d78cb | liuYfaiz/pythonProject | /test.py | 470 | 4 | 4 |
def binary_search(array,num):
"""
this is a test py
"""
if not array:
return -1
mid = 0
left = 0
right = len(array)-1
while left < right:
print(left,right)
mid = (right+left)//2
print(mid)
if array[mid] == num:
return mid
elif ar... |
5796e0f31fee84484281773ce99d2e6455372124 | EvanJMiller/DeepLearning | /Homework4/nn_img2num.py | 4,455 | 3.71875 | 4 | import torch
import torch.nn as nn
import torchvision
import torchvision.transforms as transforms
import neural_network
import torch.nn.functional as F
import numpy as np
import torch.optim as optim
import numpy
#import any other packages you might need from pytorch
class NnImg2Num(nn.Module):
def __init__(self... |
a7b12e408d7eb1e471bd4e66e1b25c59443c3c6d | fanxingzhang/leetcode-grind | /valid-parentheses.py | 594 | 3.609375 | 4 | class Solution(object):
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
l = []
for c in s:
if c == '(' or c == '[' or c == '{':
l.append(c)
else:
if len(l) == 0:
return False
... |
eb2682c50d7dfa38182c3be74a92d4a3dede13ed | a01037479/Python_OOP_Projects | /Assignments/Assignment 2/file_handler.py | 647 | 4.03125 | 4 | """
This module contains FileHandler static class
"""
class FileHandler:
"""
Static class that manages files from reading and writing
"""
@staticmethod
def write_line(path, lines):
"""
The method append a specified line to a specified file path, creates
the file if the fil... |
7221dd3471462ba9485841693719ca76003194e4 | a01037479/Python_OOP_Projects | /Assignments/Assignment 2/test_controller.py | 9,849 | 3.671875 | 4 | import os
from unittest import TestCase
from unittest import mock
from controller import Controller
from card_manager import CardManager
from exception import InvalidCardTypeError, InvalidCardBalanceError, \
InvalidDateFormatError, DuplicatedNameError, NameNotFoundError, \
EmptyCardManagerError, InvalidSexError... |
fe337e6e7a665c9e2dfaa6cdf2a987deb925cc1f | a01037479/Python_OOP_Projects | /Assignments/Assignment 4/garment_abstract_factory.py | 8,746 | 4.03125 | 4 | """
This module contains the Abstract Factory Pattern for a garment factory.
"""
from abc import ABC
class BrandFactory(ABC):
"""
BrandFactory defines the interface for three types of the garment that
abstract factory pattern is responsible to create.
"""
def create_shirt_men(self, **kwargs):
... |
005bc682e8f6d16732f760390ab01bb4d6df0331 | a01037479/Python_OOP_Projects | /Labs/Lab 9/producer_consumer.py | 4,193 | 3.546875 | 4 | """
This module contains a Queue class that manages CityOverheadTimes objects,
two thread classes and main method.
"""
import datetime
import threading
import time
from city_processor import CityOverheadTimes, CityDatabase, ISSDataRequest
class CityOverheadTimeQueue:
"""
A Queue structure that makes a list ... |
fd74efc16709f810a46fb1442edbe477ec904dd2 | fossilet/project-euler | /pe1.py | 1,110 | 3.921875 | 4 | #! /usr/bin/env python3
# encoding: utf-8
'''
http://projecteuler.net/problem=1
If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.
'''
# Since May 22 2012
from projecteuler import c... |
59a9f08095acfaa8a8cb354ebe922ecc0fa3b2ae | Pubudu-Anuradha/Marks_predictor | /predictmarks.py | 899 | 3.71875 | 4 | import pandas as pd
import matplotlib.pyplot as plt
hscores=pd.read_csv("student_scores.csv")
print(hscores.head(5))
plt.scatter(data=hscores,x="Hours",y="Scores")
plt.xlabel("Hours Studied")
plt.ylabel("Scores obtained")
plt.title("Hours studied vs Scores obtained")
plt.show()
X=hscores['Hours']
Y=hscores['Scores... |
485e111034537f739fd793a309d28913c2eeed81 | mattcl/euler | /problem_1/natural_numbers.py | 139 | 3.84375 | 4 | sum = 0
x = 3
while x < 1000:
if x % 5 is not 0:
sum += x
x += 3
x = 5
while x < 1000:
sum += x
x += 5
print sum
|
2224d73582b20f4542eb637c3a40579571ed4ac3 | azzaHA/Movie-Trailer | /media.py | 1,220 | 4.21875 | 4 | """
Define Movie class to encapsulate movies attributes and methods
"""
class Movie():
"""
Define attributes and methods associated to Movie objects
* Attributes:
title (string): Movie name
story_line (string): Brief summary of the movie
trailer_youtube_id (string): trailer ID on ... |
0b628b236933568babba8e3d633d312c47cb2153 | MinWooPark-dotcom/learn-pandas | /Part1/1.26_df_to_df.py | 824 | 3.625 | 4 | import pandas as pd
import seaborn as sns
titanic = sns.load_dataset('titanic')
df = titanic.loc[:, ['age', 'fare']]
print(df.tail())
print('\n')
print(type(df))
print('\n')
addition = df + 10
print(addition.tail())
print('\n')
print(type(addition))
print('\n')
subtraction = addition - df
print(subtraction.tail())
p... |
b237e700a8917f1512da6cae54aaab3dd46eaa29 | HuuZ43/nguyenhuuanh-d4e16 | /Session4/homework/excersices2.py | 138 | 3.953125 | 4 | x = [1,6,8,1,2,1,5,6]
a = int(input("Enter a number: "))
count = len([i for i in x if i == a])
print(f'{a} appears {count} times in list') |
f480408dfaeb60ea8e179b9ed023738dfc7e9209 | cgwu/objc | /Python/Except.py | 559 | 3.96875 | 4 | #!/usr/bin/env python3
# 常见异常继承图
'''
object(
BaseException(
Excpetion(
ArithmeticError,
EnvironmentError(
IOError, OSError
),
EOFError,
LookupError(
IndexError, KeyError
),
ValueError
)
)
)
'''
# 跳出多层循环的一种方法
class FoundException(Exception): pass
try:
for x in range(10):
for y in... |
e794cfa068e88f907bdfd726d3d5fe04ae67450f | suicaa/Algorithm-OJ | /second smallest.py | 279 | 3.8125 | 4 | def second_smallest(arr):
a = 0
while a < n:
if arr[a + 1] - arr[a] > 0:
break
else:
a += 1
return arr[a + 1]
n = int(input())
arr = []
for i in range(n):
arr.append(int(input()))
print(second_smallest(arr))
|
17d0c583e7231d7abd0632a619b3cd0eee06d7c7 | suicaa/Algorithm-OJ | /height.py | 282 | 3.53125 | 4 | class TreeNode:
def __init__(self, value):
self.value = value
self.left_child = None
self.right_child = None
def height(root):
if root:
return 1 + max(height(root.left_child), height(root.right_child))
else:
return -1
|
a0605f552ae2e94693255c3b48d33879fa4525b2 | suicaa/Algorithm-OJ | /have a try.py | 650 | 3.640625 | 4 | def mat_multi(a, b):
c = [[0, 0], [0, 0]]
for i in range(2):
for j in range(2):
for k in range(2):
c[i][j] += a[i][k] * b[k][j]
print(c)
return c
def power(y, m):
if m == 1:
return y
z = y
y = mat_multi(y, y)
h = 1
while h <... |
dd3c9970dad9e74ff3658be2fc021395071bde96 | suicaa/Algorithm-OJ | /k_th_smallest.py | 218 | 3.6875 | 4 | def k_th_smallest(arr, k):
arr.sort(reverse=False)
print(str.split(arr))
return arr[k - 1]
arr = input().split(" ")
arr = [int(x) for x in arr]
k = int(input())
print(k_th_smallest(arr, k))
|
2296ed16224f7e5cbdb5c96e4a245d79ae36b2c1 | suicaa/Algorithm-OJ | /e^x.py | 271 | 3.828125 | 4 | def exp(epsilon, x):
e = 0
cur = 1
n = 1
while cur >= epsilon:
e += cur
cur = cur * x / n
n += 1
e += cur
return e
epsilon = float(input())
x = float(input())
result = exp(epsilon, x)
print("%.6f" % result)
|
b6f2f851a0e493a66150c7dab6483e21f7c17090 | Eolynas/mac_gyver_python_game | /MacGyver.py | 3,511 | 3.703125 | 4 | # -*- coding: utf-8 -*-
import Items
import constances
import level
class MacGyver:
"""
Mac Gyver move
"""
def __init__(self, my_level: level.Level):
# self.structure = my_level.structure
self.instance_level = my_level
# Line horizontal
self.case_x = 0
... |
5fbd659a458450537031dbd8af2b26ffe6fb872a | itsfarooqui/Python-Programs | /Program1.4.py | 288 | 3.765625 | 4 | #1.4. Call each class by creating an object to it.
class Fruit:
def __init__(self, name, color):
self.name = name
self.color = color
def myfunc(abc):
print("This is a " + abc.name)
print("Mango is " + abc.color)
p1 = Fruit("Mango", "Yellow")
p1.myfunc() |
07259591c3726a289514c4b6c1d0691f32bc30fc | itsfarooqui/Python-Programs | /Program16.py | 212 | 4.03125 | 4 | #16. Write a function to get the difference of largest and smallest value.
arr = [2, 4, 6, 8, 10]
x = max(arr)
y = min(arr)
res = x - y
print("Difference of largest and smallest value is: ", res)
|
36a3e44f366e2bcf8bbab61ce3cee2f551acd80b | itsfarooqui/Python-Programs | /Program15.py | 275 | 4.125 | 4 | #15. Write a method to find number of even number and odd numbers in an array.
arr = [8, 4, 3, 6, 9, 2]
i = 0
for i in range(0, len(arr)):
if arr[i]%2 == 0:
print("Even Number: ", arr[i])
else:
print("Odd Number: ", arr[i])
i = i +1 |
0dcc6fbc8d86b866e43b7971fd285f685e03cef4 | mithundeshmukh8/Machine-Learning-NPTEL- | /Week-1/01-Linear Regression/01-Linear Regression.py | 2,114 | 3.96875 | 4 | import numpy as np
from sklearn import linear_model
import matplotlib.pyplot as plt
#1. Prepare a synthetic dataset using the equation:
# y = x/2 + sin(x) + E, where E~N(0,1) is the Gausian noise to add randomness to the data
number_of_samples = 200
x = np.linspace(-np.pi, np.pi, number_of_samples)
y = 0.5 * ... |
7dec748535edbdb77f07f699a3e9bdde7db612dd | mulshankar/LaneDetection_Sankar_SDCND | /myCode.py | 11,658 | 3.984375 | 4 | #importing some useful packages
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import numpy as np
import cv2
%matplotlib inline
#reading in an image
image = mpimg.imread('test_images/solidWhiteRight.jpg')
#printing out some stats and plotting
print('This image is:', type(image), 'with dimensions:', ... |
133bad3b0c83798e22235437b237a4662641c5a8 | UmarAhmed/Fundamentals | /BST.py | 2,309 | 4.0625 | 4 | # BST requires:
# all values to the left are smaller
# all values to the right are larger
# items are unique
class TreeNode:
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
class BST:
def __init__(self):
... |
fbe6b39955d708c613855a095a2461e7876885e9 | JulianP911/Taller1_Infracomp | /Taller1 - Python/Thread2.py | 923 | 3.71875 | 4 | # Creacion de threads en Python utilizando clases
import logging
import threading
import time
import random
# Logger Config
format = "%(asctime)s: %(message)s"
logging.basicConfig(format=format, level=logging.INFO, datefmt="%H:%M:%S")
# Clase
class Exmple_Thread(threading.Thread):
#Constructor
def __init__(s... |
fd70b09062b20ab68b8ef0c7065da2ec49290430 | fintechilla/RPAd | /wqu/wqu_tools/sieve_ex5.py | 1,939 | 3.640625 | 4 | import lec2 as lec2
def list_true(n):
nums = []
nums.append(False)
nums.append(False)
for i in range(2, n + 1):
nums.append(True)
return nums
assert len(list_true(20)) == 21
assert list_true(20)[0] is False
assert list_true(20)[1] is False
def mark_false(bool_list, p):
len_list = l... |
c90c04532f3db8d0f27f825c68e4869109edda6b | raviguru123/google-python | /list1.py | 1,581 | 3.75 | 4 | def match_ends(list):
count=0;
for str in list:
if(len(str)>=2 and str[0]==str[-1]):
count+=1;
return count;
def begin(val):
if(val[0]=='x'):
return 'a';
return val;
def front_x(list):
return sorted(list,key=begin);
# print front_x(['mix', 'xyz', 'apple', 'xanadu'... |
e5f993b8b0efa5531cd7e2330bc3f4c804045a93 | touloumisk/Skyline-Queries | /Intro/main.py | 1,720 | 3.5625 | 4 | from __future__ import division
import matplotlib.pyplot as plt
import Point
import Naive
import itertools
import BlockNestedLoop as BL
import Divide_and_Conquer as DC
if __name__ == '__main__':
#open file to read points
file = open("points.txt","r")
#list to save the points
list = []
... |
f5a2480e310a03ef2d1ef87ece23a7e8ff53e23f | rachel6854/Arrays--Solutions-to-LeetCode-Questions | /pancake_sorting.py | 639 | 3.828125 | 4 | #Pancake Sorting
#https://leetcode.com/problems/pancake-sorting/
#Time Complexity: O(n*2)
#Space Complexity: O(n)
class Solution(object):
def pancakeSort(self, A):
"""
:type A: List[int]
:rtype: List[int]
"""
result = []
for i in range(len(A) - 1, 0, -1):
... |
2a958d6a3fa7bddb71ba84590fe882b8cf008b1a | anoddnumber/BoredGameStats | /src/utilities/restaurant_utilities/restaurant_chooser.py | 1,542 | 4.09375 | 4 | import random
possible_lunch_places = [
'8 ounce',
'Santouka',
'Taco Chukis',
'Kedai Makan',
'Swish Swish',
'Boiling Point',
'Portage Bay',
'''Zeek's Pizza''',
'Lola',
'Cheesecake Factory',
'Cedars',
'Jon\'s Fried Rice',
'Tofu House',
'Din Tai Fung',
'Pho',
... |
acaf144e831cb8b72ae02430200179b1b6103c1a | anoddnumber/BoredGameStats | /src/utilities/game_statistics_implementations/game_statistics_implementations.py | 3,798 | 3.859375 | 4 | def game_statistics_caroline(game_results):
"""
This function will generate all the analysis results on mean,
win precentage and winning streak.
"""
player_average_score_caroline(game_results) # average score of each player
player_win_percentage_caroline(game_results) # win percentage of players... |
6ccd84cf89711a5338fa9e21d5bf2acb6f8270b2 | nandorhegyi/Simple-Python-Games-and-Starter-Projects | /Flappy_Bird/settings.py | 1,134 | 3.515625 | 4 | import pygame
class Settings:
"""A class to store all settings for the game."""
def __init__(self):
"""Initialize the game's static settings."""
# Screen settings.
self.screen_width = 1200
self.screen_height = 800
self.bg_colour = (255, 255, 255)
# Pipe setti... |
960bc02fa729a588f9220769365fd4194fc7e0a3 | thinkphp/rabin-miller | /rabin-miller.py | 2,613 | 4.21875 | 4 | # Miller-Rabin Probabilistic Primality Test.
#
# It's a primality test, an algorithm which determines whether a given number is prime.
#
# Theory
#
# 1. Fermat's little theorem states that if p is a prime and 1<=a<p then a^p-1 = 1(mod p)
#
# 2. If p is a prime x^2 = 1(mod p) or(x-1)(x+1) = 0 (mod p), then x = 1 (mod ... |
6ffde0098cabecd63e49220bcb814ea2061a35f3 | Fatiherik/Pycoders-Python | /4.week/4Q.py | 259 | 3.859375 | 4 | def greatest_common_divisor(n1,n2):
common_divisor=[]
min_number=min(n1,n2)
for i in range(1,min_number+1):
if n1%i==0 and n2%i==0:
common_divisor.append(i)
print(max(common_divisor))
greatest_common_divisor(15,25) |
a81533756831398c267996d6c88215a359a041bd | Fatiherik/Pycoders-Python | /1.week/q1.py | 437 | 3.75 | 4 | name=input("name and surname: ")
mid=int(input("midterm exam score (0-100): "))
final=int(input("final exam score (0-100): "))
attendance=int(input("number of class you attend (0-20): "))
course_grade=mid*0.3+final*0.5+attendance*5*0.2
print(name)
print("midterm exam grade: "+str(mid))
print("final exam grade: "... |
4bde022da4c15e85b8585d5ba1a0229e181c9a43 | Fatiherik/Pycoders-Python | /4.week/2Q.py | 148 | 3.640625 | 4 | def exact_divisor(n):
list=[]
for i in range(1,n+1):
if n%i==0:
list.append(i)
print(list)
exact_divisor(12) |
add04c0c962feb681cb189fd73e35940e71bbdd7 | caiovictorpcb/wiki-py | /main.py | 658 | 3.65625 | 4 | import requests as r
from bs4 import BeautifulSoup
def pedir_nome():
while True:
nome = input("Digite o nome da pessoa: ")
nome = nome.title()
nome = nome.split()
if len(nome) == 2:
nome = nome[0] + "_" + nome[1]
return nome
else:
... |
15b439cc89bae13fbfd7a981ce68aa5c23ecaf0f | randcyp/FIT2085 | /Practical 1/Exercise 1 - task_1.py | 1,633 | 4.21875 | 4 | # Non-assessed practical
"""
This module demonstrates a way to interface basic list
operations.
"""
__author__ = "Chia Yong Peng"
from typing import List, TypeVar
T = TypeVar('T')
list_of_items = []
def print_menu() -> None:
"""
Prints the menu.
"""
menu_items = ["append", "reverse", "print", "pop... |
6a00a2625bdd3ba97efbc2262b15582ad72fa003 | Prashant960/git-GITHUB | /thread_1.py | 454 | 3.515625 | 4 | import threading
import numpy as np
def power_3(x):
print(f'\nCube({x}) : {x**3}')
def power_2(x):
print(f'Square({x}) : {x**2}')
if __name__ == '__main__':
num = np.array([1,2,3,4,5])
for i in num:
t1 = threading.Thread(target=power_3, args=(i,))
t2 = threading.Thread(target=power_2, ... |
461c5e56da879c382f30317af48f304d8e33840d | Frindge/Esercizi-Workbook | /Exercises Workbook Capit. 1/Exercise 033 - Sort 3 Integers.py | 697 | 4.1875 | 4 | # Exercise 33: Sort 3 Integers
# Creare un programma che legga tre numeri interi dall'utente e li mostri in ordine ordinato
# (dal più piccolo al più grande). Usate le funzioni min e max per trovare il valore più piccolo e
# quello più grande. Il valore medio può essere trovato calcolando la somma di tutti e tre i val... |
234eecbbed9d0a542fc46c1fa4e3d58fa759fc16 | Frindge/Esercizi-Workbook | /Exercises Workbook Capit. 1/Exercise 020 - Ideal Gas Law.py | 1,370 | 3.859375 | 4 | # La legge dei gas ideali è un'approssimazione matematica del comportamento dei gas al variare di pressione,
# volume e temperatura. Di solito viene enunciata come:
# PV=nRT
# dove P è la pressione in Pascal, V è il volume in litri, n è la quantità di sostanza in moli, R è la costante
# dei gas ideali, pari a 8.314 J ... |
2544ea85dff7a9b54d91dc8c9d9d565dff3c27ac | Frindge/Esercizi-Workbook | /Exercises Workbook Capit. 2/Exercise 048 - Birth Date to Astrological Sign.py | 2,149 | 4.09375 | 4 | # Exercise 48: Birth Date to Astrological Sign
# Capricorn December 22 to January 19
# Aquarius January 20 to February 18
# Pisces February 19 to March 20
# Aries March 21 to April 19
# Taurus April 20 to May 20
# Gemini May 21 to June 20
# Cancer June ... |
f2ecc8e613d2efad15b6512c69750b70390bb7e5 | Frindge/Esercizi-Workbook | /Exercises Workbook Capit. 1/Exercise 031 - Units of Pressure.py | 394 | 3.546875 | 4 | # Exercise 31: Units of Pressure
# Libbre per pollice quadrato
psi = 0.145038
# atmosfere
atm = 0.00986923
# millimetri di mercurio
mmHg = 7.5006
KPa=float(input("iserisci un valore in kilopascal: "))
a=KPa * psi
b=KPa * atm
c=KPa * mmHg
print("""la conversione da kilopascal in Libbre per pollice quadrato è:%.2... |
583f9a7bf7f1aa39295f404f8ad42ba4c529abb3 | Frindge/Esercizi-Workbook | /Exercises Workbook Capit. 2/Exercise 040 - Sound Levels.py | 845 | 4.4375 | 4 | # Exercise 40: Sound Levels
# Jackhammer 130 dB
# Gas Lawnmower 106 dB
# Alarm Clock 70 dB
# Quiet Room 40 dB
Sound=float(input("Enter a number to define a sound level in decibels: "))
if Sound > 130:
Sound="The sound level is louder than a Jackhammer"
elif Sound == 130:
Sound="The sound level is Jackhammer"... |
93153b09c6c76b9e8b7daf4643d507e2a4bbacde | Frindge/Esercizi-Workbook | /Exercises Workbook Capit. 2/Exercise 051 - Roots of a Quadratic Function.py | 547 | 4.1875 | 4 | # Exercise 51: Roots of a Quadratic Function
import math
a=float(input("Enter the value a: "))
b=float(input("Enter the value b: "))
c=float(input("Enter the value c: "))
discriminant = (b**2) - (4 * a * c)
print(discriminant)
if discriminant < 0:
print("has no real roots")
elif discriminant == 0:
result =... |
22c14c12f08fcc25ab970493f8ef05cb5b73982b | Frindge/Esercizi-Workbook | /Exercises Workbook Capit. 2/Exercise 035 - Even or Odd.py | 208 | 4.125 | 4 | # Exercise 35: Even or Odd?
number=int(input("Enter a valid integer number: "))
number1=number % 2
if number1 == 0:
number1="the number is even."
else:
number1="the number is odd: "
print(number1)
|
767d3c80de4e3a27add6cc33722002c8855dcb8c | IIInvokeII/1st_sem_python | /Codes/16 - computing n.py | 168 | 4.0625 | 4 | x=int(input("Enter a number: "))
n=int(input("Enter the no. of terms: "))
s=0
for i in range(n):
s+=x
x=x*10 + x
print("The computation results in: ",s)
|
c6a9fddd1ba85e3f0f14043cc169979794d4aaac | IIInvokeII/1st_sem_python | /Codes/PTQ G3.py | 2,515 | 3.9375 | 4 | print("Welcome to Personality Test Quiz 1.0 !!")
print("Shall we begin? Press Enter.")
input()
A=0
B=0
print("Would you rather be the ")
print("A. Smartest person around")
print("B. Most charming person")
x=str(input())
if(x=='A'):
A+=1
print("Would you rather")
print("A. Always tell the truth")
pr... |
ff91b552194ec1c7b263e1cdec5ec70a3e8e8346 | IIInvokeII/1st_sem_python | /Codes/mfunc.py | 1,230 | 4.09375 | 4 | def newmat(r,c):
A=[[0 for i in range(c)] for j in range(r)]
for i in range(r):
for j in range(c):
A[i][j]=int(input("Enter value: "))
return A
def addmat(A,B):
r1=len(A)
c1=len(A[0])
r2=len(B)
c2=len(B[0])
if(r1==r2 and c1==c2):
mat=[[0 for i... |
989f802cf8e09f17cbadd0b9046ea6dea1fae43f | IIInvokeII/1st_sem_python | /Codes/3.2 - Armstrong Number.py | 301 | 4 | 4 | n=int(input("Enter a number: "))
c=n
s=0
d=0
while(c>=1):
c=c/10
d+=1
c=n
while(c>0):
r=c%10
s=s+r**d
c=c//10
print("The sum of the digits to the power",d,"is: ",s)
if(n==s):
print(n,"is an Armstrong number.")
else:
print(n,"is not an Armstrong Number")
|
fab1a5d468fc9faa0fc0918179e42ea38bc7271a | PascalTruglio/Adventure-Game | /src/utility.py | 1,430 | 3.953125 | 4 | """
Utility module for reusable functions
"""
def draw_table_centered(window, headers: list, items: dict):
"""
draw a centered table in the specified window
:param window: window to be drawn to
:param headers: header row values
:param items: table items as a dict, dict must have same amount of
... |
202613b6a592f7a92b50329809bb29047e04899b | DavisFTW/Stars | /stars.py | 266 | 4 | 4 | def star(n : int ):
for i in range(n): # pirma iteracija = i=0
print( " " * (n - i), "*" * (i * 2 + 1)) # 1, 3, 5...
for i in range(n, -2, -1):
print(" " * (n - i), "*" * (i * 2 + 1))
uInput = int(input("number: "))
star(uInput)
|
e9a982187672d55121fa7d85858b43f45bd85cab | TomGlynne-Jones/physics | /lattice_models/game_of_life.py | 2,426 | 4.0625 | 4 | from lattice_models import *
import matplotlib.pyplot as plt
class GameOfLife:
def __init__(self, n, m, lattice_type=SquareLattice2):
""" Conway's Game of Life
Args:
n (int): size y
m (int): size x
lattice_type: valid lattice subclass, default = SquareLattice2
... |
bef8b7bf5ae1209237d99415a889a55b65b3c21e | fbglucky/algorithms | /data_structures/backtracking.py | 1,341 | 3.921875 | 4 | board_size = 4
board_example = [[False for x in range(board_size)] for y in range(board_size)]
def n_queens():
recursive_n_queens(board_example, 0)
def recursive_n_queens(board, row):
if row == len(board):
# done, print the result
display_board(board)
else:
for col in range(len(b... |
1d3b6ada371c41b5dc7277216045fbc73670cc29 | slicedbread/File-Name-Randomizer | /AdjNounAdj.py | 1,379 | 3.5 | 4 | __author__ = 'Ian'
import random
def random_name():
return random.choice(adj) + random.choice(nAdj) + random.choice(noun)
adj = [
"red",
"blue",
"dangerous",
"large",
"weaponized",
"nerfed",
"fangorius",
"glorious",
"menacing",
"sexy",
"random",
"green",
"spic... |
86b45e5c963a22f9153280ba6e750cc24f3a4e1d | wwwjfy/projecteuler | /10.py | 309 | 3.6875 | 4 | primes = [2, 3]
i = 5
while True:
sqrt_i = int(i ** 0.5)
for prime in primes:
if sqrt_i < prime:
primes.append(i)
break
elif i % prime == 0:
break
else:
primes.append(i)
i += 2
if i >= 2000000:
break
print sum(primes)
|
dd40c153e0a1373dedc550f6d29bcc215350a8bf | taoyuc3/SERIUS_NUS | /5.22_Mat1.py | 502 | 3.640625 | 4 | from matplotlib import pyplot as plt
x = [2, 5, 8, 10, 14]
y = [17, 12, 16, 6, 9]
x2 = [3, 6, 9, 11, 16]
y2 = [30, 6, 15, 7, 3]
x3 = [1, 7]
y3 = [9, 7]
x4 = [4, 12, 15]
y4 = [8, 8, 19]
x5 = [13, 17]
y5 = [2, 5.5]
plt.bar(x, y, align='center')
plt.bar(x2, y2, color='green', align='center')
plt.bar(x3, y3, color='orange'... |
b971b310ae02ec049a32d1bebca9ea41a6ac5fb1 | taoyuc3/SERIUS_NUS | /5.28.py | 1,699 | 4.125 | 4 | # https://machinelearningmastery.com/tutorial-first-neural-network-python-keras/
from keras.models import Sequential
from keras.layers import Dense
import numpy
# fix random seed for reproducibility
numpy.random.seed(7)
# Load pima indians dataset
dataset = numpy.loadtxt("pima-indians-diabetes.data.csv", delimiter=",")... |
709aac4c02464b94ee8fe7775845a60b661c6cf6 | Nana-Antwi/UVM-CS-21 | /energy.py | 971 | 3.875 | 4 | #Nana Antwi
#CS 21
#Assignment 7
#kineticenergy.py
#design a program that asccept mass and velocity as inputs and returns the kinetic energy
#declare varaibles
mass= 0.0
velocity = 0.0
KE = 0.0
#define function
def main():
#exception statements
try:
#declare constants in the function
kin... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.