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 |
|---|---|---|---|---|---|---|
3fb85328349ab06c136f9c7b43c7b111c5a15782 | lodi-jesse/aula_python | /desafio018.py | 394 | 3.96875 | 4 | from math import radians, sin, cos, tan
angulo = float(input('Digite o ângulo: '))
seno = sin(radians(angulo))
print('O ângulo de {} tem o seno de {:0.2f}'.format(angulo,seno))
cosseno = cos(radians(angulo))
print('O ângulo de {} tem o cosseno de {:.2f}'.format(angulo,cosseno))
tangente = tan(radians(angulo))
pr... |
e2b1bfadf1897ac854a7e49e3b124b7416553af6 | lodi-jesse/aula_python | /desafio073.py | 709 | 3.8125 | 4 | import os
os.system('cls')
lista_brasileirão = ('Flamengo','Internacional','Atlético-MG','São Paulo','Fluminense','Grêmio','Palmeira','Santos','Athetico-PR','Corinthians','Bragantino','Ceará','Atlético-GO','Sport Recife','Bahia','Fortaleza','Vasco da Gama','Goiás','Coritiba','Botafogo')
print('-='*30)
print(f'Lista... |
f5b05ac0de2aa72baae02f6cf9c077b6e774bf93 | lodi-jesse/aula_python | /desafio028.py | 744 | 4.125 | 4 | #Escreva um programa que faça o computador sortear um número de 0 ate 5 e pesa para o usuário tentar descobrir qual foi o número escolhido pelo computador.
# O programa deverá escrever na tela se o usuário venceu ou perdeu.
from random import randint
from time import sleep
sorteado = randint (0, 5) #faz o computado... |
c3abe97e132863aad884f02483eb98672ebb6fb7 | lodi-jesse/aula_python | /desafio032.py | 506 | 4 | 4 | # Faça um programa que leia um ano qualquer e mostra se ele é BISSEXTO.
from datetime import date #Puxar a data atual independente o sistema ou aprelho utilizado
print('DESCUBRA SE O ANO É BISSEXTO')
print('='*30)
ano = int(input('Digite o ano exemplo."XXXX" ou digite "0" para o ano atual: '))
if ano == 0:
a... |
306a9e1e6c52bdb1c0d9b527acc853792e23214c | lodi-jesse/aula_python | /desafio085.py | 610 | 4.09375 | 4 | '''Crie um program onde o usuário possa digitar 7 valores numéricos e
cadastre-os em uma lista única que mantenha separados os valores pares e
ímpares. No final mostre os n=valores pares e impares em ordem crescente.'''
from os import system
system('cls')
lista = [[],[]]
for cont in range(0,7):
n = int(inpu... |
9454b32184aa1c29ad0db72ec564036666dff0f9 | EnriqueStrange/portscannpy | /nmap port-scanner.py | 1,508 | 4.1875 | 4 | #python nmap port-scanner.py
#Author: P(codename- STRANGE)
#date: 10/09/2020
import argparse
import nmap
def argument_parser():
"""Allow target to specify target host and port"""
parser = argparse.ArgumentParser(description = "TCP port scanner. accept a hostname/IP address and list of ports to"
... |
e50090c7f43d6196e5d0b0da2580643e04b6606b | jmctsm/Python_03_Deep_Dive_Part_04_OOP | /Section_10_Enumerations/03 - Customizing and Extending Enumerations.py | 7,663 | 3.9375 | 4 | def line_break():
x = 0
print("\n\n")
while x < 20:
print("*", end="")
x += 1
print("\n\n")
line_break()
from enum import Enum
from typing import OrderedDict, Type
class Color(Enum):
red = 1
green = 2
blue = 3
def purecolor(self, value):
return {self: value}... |
ebd204d5053a5fbbfbb2b7a1cb3d4d7b7fa2e6e3 | jmctsm/Python_03_Deep_Dive_Part_04_OOP | /Section_10_Enumerations/01 - Enumerations.py | 4,019 | 3.59375 | 4 | def line_break():
x = 0
print("\n\n")
while x < 20:
print("*", end="")
x += 1
print("\n\n")
line_break()
import enum
class Color(enum.Enum):
red = 1
green = 2
blue = 3
class Status(enum.Enum):
PENDING = 'pending'
RUNNING = 'running'
COMPLETED = 'completed'
cl... |
7923acb33239bbbe2d73250f9e4568c1c36fdc1f | jmctsm/Python_03_Deep_Dive_Part_04_OOP | /Section_06_Single_Inheritance/02 - The object Class.py | 1,926 | 3.734375 | 4 | def line_break():
x = 0
print("\n\n")
while x < 20:
print("*", end="")
x += 1
print("\n\n")
line_break()
print("type(object): " + str(type(object)))
print("type(int), type(str), type(dict): " + str(type(int)), str(type(str)), str(type(dict)))
line_break()
class Person:
pass
prin... |
d7e354c8bb26a2a85766892cc01dba8504b26b81 | einyan03/Algorithm_Exercises | /jewelsAndStones.py | 421 | 3.65625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Apr 23 09:34:42 2020
@author: Einyan
"""
def numJwelsInStones(J, S):
h = {}
count = 0
for i in S:
if i not in h:
h[i] = 1
else:
h[i] += 1
print(h)
for j in J:
if ... |
d517ca7cfe2ec076733917e8f1d774f8eca52e1f | einyan03/Algorithm_Exercises | /bestTimeToBuyAndSellStock.py | 1,523 | 3.859375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Apr 15 02:27:14 2020
@author: Einyan
"""
"""
If you were only permitted to complete at most one transaction
(i.e., buy one and sell one share of the stock),
design an algorithm to find the maximum profit.
Example 1:
Input: [7,1,5,3,6,4]
Output: 5
Explanatio... |
0dd3441b24d9c65bc2c0bdfe20612dfcfcf55482 | nadiyasalma/Nadiya-Salma_I0320071_M.Wildan-Rusydani_Tugas3 | /I0320071__Exercise 3.1-3.10.py | 2,150 | 4.375 | 4 | #exercise 3.1
#cara mengakses nilai di dalam list python
list1 = ['fisika', 'kimia', 1993, 2017]
list2 = [1, 2, 3, 4, 5, 6, 7]
print("list1[0]: ", list1[0])
print("list2[1;5]: ", list2[1:5])
#exercise 3.2
list = ['fisika', 'kimia', 1993, 2017]
print("Nilai ada pada index 2: ", list[2])
list[2] = 2001
print("Nilai ba... |
e1468e8873140de01842b77aec9d7d4a566ae476 | JoseGRuiz/ToolsForCSProject | /Code/get_image.py | 4,508 | 3.953125 | 4 |
import os
import os.path
import csv
import urllib.request
from PIL import Image
'''
Change these fields as needed.
The folder paths below are relative paths, change them to absolute paths if needed.
'''
# this folder will hold the files that has the URLs, this folder is required to be
# created befo... |
9c1dae13e310463e81915648c8614a71517309ae | luvlee-liu/Flask_Tutorial | /code/create_table.py | 565 | 3.859375 | 4 | import sqlite3
connection = sqlite3.connect('data.db')
cursor = connection.cursor()
# entries = [
# (1, 'bob', 'asdf'),
# # (2, 'jose', 'asdf'),
# # (3, 'ana', 'asdf')
# ]
create_table = "CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, username text, password text)"
cursor.execute(create_table)
... |
f2550a81f9003146c67cecae2658209272baf04f | AlexOUKS/TicTacToe_PiE2018 | /test_game.py | 560 | 3.515625 | 4 | from unittest import TestCase
from game import Game
from board import Board
from player import Player
class TestGame(TestCase):
def test_checkWin(self):
player1 = Player()
player2 = Player()
game = Game(player1, player2)
board = Board(game)
game.setBoard(board)
test... |
fe534e83eee05ea1fdf0a410ff00be93e19f8902 | msk4862/DS-Algo | /Practice/EulerProject/16_powDigitSum.py | 191 | 3.9375 | 4 |
def main(pow):
num = str(2**pow)
sum = 0
for digit in num:
sum += int(digit)
return sum
if __name__ == '__main__':
pow = int(input())
print(main(pow))
|
84d3c8ed7bcb4e88b96b75726bc35325ba3915b6 | dantangfan/leetcode | /MinStack.py | 1,012 | 3.9375 | 4 | class MinStack(object):
def __init__(self):
"""
initialize your data structure here.
"""
self.stack = []
self.size = 0
self.min = 0
def push(self, x):
"""
:type x: int
:rtype: nothing
"""
if self.size and self.stack[self.mi... |
5ef26593df9f1fb12c6ad8300952d1012a03dd45 | dantangfan/leetcode | /addTwoNumbers.py | 892 | 3.578125 | 4 | # coding:utf-8
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
# 本题就是一个简单地链表大数加法,连翻转都不用。
class Solution(object):
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:r... |
895752f64e2ad131aacc5b5cea29d26b9a3e1506 | dantangfan/leetcode | /IntersectionofTwoLinkedLists.py | 1,190 | 3.578125 | 4 | # coding:utf-8
# 查找两个链表的脚垫
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def getIntersectionNode(self, headA, headB):
"""
:type head1, head1: ListNode
:rtype: ListNode
"""... |
05895db4c92a5ec055d369f070ba500aa62b06b1 | saralkbhagat/leet | /Linkedlist/Reverse LL/206.reverse-linked-list.py | 1,248 | 4.0625 | 4 | #
# @lc app=leetcode id=206 lang=python3
#
# [206] Reverse Linked List
#
# https://leetcode.com/problems/reverse-linked-list/description/
#
# algorithms
# Easy (57.16%)
# Total Accepted: 699.7K
# Total Submissions: 1.2M
# Testcase Example: '[1,2,3,4,5]'
#
# Reverse a singly linked list.
#
# Example:
#
#
# Input:... |
b0bf215435b8171cf20e28e5513c897bd46b424f | sumitsharmamanit/Multi_Layer_Perceptron | /data_collection.py | 1,146 | 3.65625 | 4 | import pandas as pd
from sklearn.preprocessing import MinMaxScaler
from sklearn.model_selection import train_test_split
'''This Class will preprocess the data an apply min max normalisation'''
class MyCollection:
def __init__(self):
self.x_train = None
self.x_test = None
self.y... |
4aef877aea1638c5ffc28ec876ab6748edd5d638 | dillonmabry/reddit-comments-tool | /reddit_extract/process.py | 566 | 3.59375 | 4 | import multiprocessing
from multiprocessing.pool import ThreadPool
class MultiProcess(object):
def __init__(self, threads):
"""
Args:
threads: number of threads to use
"""
self.threads = threads
self.pool = ThreadPool(threads)
def __exit__(self, exc_type, e... |
cc4089c610657a6ff8b7ee8a2be7e77ef8026683 | madewithbytes/mappa | /snippets/02_analize_shape_data.py | 1,213 | 3.65625 | 4 | #!/usr/bin/env python
import pandas as pd
import shapefile as shp
def read_shape_file(*, file_path, encoding="ISO-8859-1"):
"""Reads the shape file and specifies shp file encoding."""
return shp.Reader(file_path, encoding=encoding)
def prepare_data_frame(*, shape_file):
"""Transforms the shapefile into... |
983eb4d5c81f5529161610bfc32ef983c0969393 | navazl/hackerrank | /30daysofcode/day6.py | 469 | 3.65625 | 4 | # Enter your code here. Read input from STDIN. Print output to STDOUT
number = int(input(''))
s = []
for i in range(0, number):
s.append(str(input('')))
for p in range(0, number):
palavra = s[p]
n = len(palavra)
string_par = []
string_impar = []
for i in range(0, n, 2):
string_par.a... |
6b7cca7f74ab5a62a2b591b4c595cbdf2fa2fb06 | SmithSamuelM/gem | /gem/ray.py | 1,386 | 3.75 | 4 | import gem.vector as vec
# Ray Class
class Ray(object):
def __init__(self, startVector, dirVector):
''' Initiated a ray with the start vector and direction vector. '''
self.start = startVector
self.dir = dirVector
self.distance = self.dir.magnitude()
self.dir.i_normalize()
... |
f484aab33a5142f6fbe20f6072e035339f561d0b | programmer290399/Udacity-CS101-My-Solutions-to-Exercises- | /CS101_Shift_a_Letter.py | 387 | 4.125 | 4 | # Write a procedure, shift, which takes as its input a lowercase letter,
# a-z and returns the next letter in the alphabet after it, with 'a'
# following 'z'.
def shift(letter):
ASCII = ord(letter)
if ASCII == 122 :
return chr(97)
else :
return chr(ASCII + 1)
print shift... |
1dfdbea98e9c3d8cd06d6a904850f6bb45d70fdf | ravi9607/basic-program-by-python | /character.py | 106 | 4 | 4 | name=input("Enter your name: ")
age=input("Enter your age: ")
print(" hello "+name+"! you are "+age)
|
3ed66c113224389fdac3324400d3c3dde1a48eec | Hinthusiast/testcode | /changeside.py | 215 | 3.59375 | 4 | class Square:
def __init__(self,side):
self.s1 = side
def change_size(self):
newSide=int(input('Please enter new dimension:'))
self.s1-=newSide
sqr=Square(125)
sqr.change_size()
|
f8cb0644d7cf1c074ff53db18f617aaceac512f3 | jmmander/Complex-data | /recursivedrawings.py | 1,365 | 3.546875 | 4 | import turtle
def draw_triangle(coord, colour, myturtle):
myturtle.fillcolor(colour)
myturtle.up()
myturtle.goto(coord[0][0],coord[0][1])
myturtle.down()
myturtle.begin_fill()
myturtle.goto(coord[1][0],coord[1][1])
myturtle.goto(coord[2][0], coord[2][1])
myturtle.goto(coord[0][0], coor... |
c199984b3de228c3c5ce68009fb5898aa94c7624 | vektorelpython24proje/temelbilgiler | /HUNKAR/OOP_/Generators.py | 227 | 3.609375 | 4 | import random as rnd
liste = [i for i in range(1000)]
def luckies(liste,count):
for i in range(count):
yield rnd.choice(liste)
for item in luckies(liste,3):
print(item)
print(rnd.sample(liste,3))
|
134e6aa207aa0a66b4da18abefff8ba91609aeac | vektorelpython24proje/temelbilgiler | /IBRAHIM/OOP/örnekler/sifreuretici.py | 853 | 3.640625 | 4 | # xsifre=input("Şifre Giriniz: ")
# class SifreUretimi():
# def __init__(self,var1,var2):
# self.var1=var1
# self.var2=var2
# self.xsifre=xsifre
# def ContMechanism(self,sifre):
# k=bharf = kharf = nchar = num = False
# ncharList=(""" -_,;.:!'^+%&/()=?><#$½{[]}|*\æß@€~¨`... |
62c129920b2c9d82d35eaba02a73924596696280 | Maxrovr/concepts | /python/sorting/merge_sort.py | 1,982 | 4.21875 | 4 | class MergeSort:
def _merge(self, a, start, mid, end):
"""Merges 2 arrays (one starting at start, another at mid+1) into a new array and then copies it into the original array"""
# Start of first array
s1 = start
# Start of second array
s2 = mid + 1
# The partially so... |
820b5e744bfab4977eea78b66111a9ceb2e84411 | S-King/Leetcode | /DataStructures/DataStructureExamples.py | 4,221 | 3.96875 | 4 | import random
'''The goal here is to recreate as many data structures as possible with the least amount of libraries'''
def initialize_matrix():
''' How to initialize a zero matrix '''
matrix = [[0 for column in range(5)] for row in range(2)]
print(matrix)
def stack_implementation():
'''
Python St... |
1f0582a6c5b39d1f4bdf79a82c6a98d49d1ae6cb | S-King/Leetcode | /Merge Intervals.py | 1,049 | 3.9375 | 4 | from typing import List
class Solution:
def merge_binary(self, intervals: List[List[int]]) -> List[List[int]]:
# If we have two or less intervals we can
if len(intervals) == 1:
return intervals
# Check if we should merge
elif len(intervals) >= 2:
... |
bb72fb5d14663bdb9c07bfd69cf5aac641b7b5e6 | BoricAcid/aPC | /computeSets.py | 856 | 3.71875 | 4 | import numpy as np
import itertools
def multiSet(k, M):
"""Computes all combinations of M bins containing
number from 0-k keep those who sums upp to k
Params:
k: max order of polynomial
M: number of dimensions (bins)
Return:
mSet: list of arrays which sets sums up to order k
"""
result = i... |
2b598e49f13437d8433512492582e2a473e8f6a0 | Shawnnn/usePython | /olympics_medals/olympics_medals.py | 1,704 | 3.75 | 4 | #!/usr/bin/env python
#-*-coding:utf-8-*-
class Medals(object):
def __init__(self):
self.countries = ["China", "America", "Russia"]
self.gold = [10,8,6]
self.silver = [1,2,15]
self.bronze = [11,13,15]
self.info_dict = {}
for i in range(0, len(self.countries... |
d5b850ec0a77df5a9544a467aeafea2d14cb22b2 | Shawnnn/usePython | /guess_num/guess_num_web_func.py | 3,849 | 3.71875 | 4 | import random
import requests
def round_per_game(rand_num, bingo, times): # 内层循环抽象为函数B, 返回每一次游戏需要多少轮才猜出
while bingo == False:
guess = int( input("please input an integer between 1 and 100..\n"))
times += 1
if rand_num > guess:
print("too small, try again!")
elif rand_num... |
3bb6a89bef6198f2470f72b43df65a91270fcd78 | dnhansen/project-euler-python | /pe_007.py | 606 | 3.921875 | 4 | import math
def primes(n):
# Gets the first n primes
if n == 1:
return [2]
else:
prime_list = [2]
k = 3
while len(prime_list) < n:
prime = True
root = math.floor(math.sqrt(k))
for p in prime_list:
if ... |
215dc2dbca0d5fcd7f9790bd26594ca52f87c207 | fnz/ProjectEuler | /55.py | 458 | 3.640625 | 4 | def is_palindrome(string):
for i in range(0, len(string) / 2):
if string[i] != string[-i - 1]:
return False
return True
def is_lychrell(x):
for i in range(50):
x += int(str(x)[::-1])
if is_palindrome(str(x)):
return False
return True
def main():
... |
e472962603e836afe380d09c83501b39d5d3e8df | Vijayasree-123/Assignment-4 | /assignment 4.py | 1,373 | 4.09375 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
# 1. function that returns first and last digit of a number
def firstDigit(n):
while n>=10:
n=n/10;
return int(n)
def lastDigit(n):
return(n%10)
n=98562;
print(firstDigit(n),end=" ")
print(lastDigit (n))
# In[2]:
# 2.generating first n number of ... |
ef77122d85c2c7ad8449784513ac242f2939924e | nlatham1999/Poker_Analysis | /PokerAnalysis.py | 11,562 | 3.515625 | 4 | import math
import json
import os
import random
import copy
import numpy as np
import matplotlib.pyplot as plt
# Global Variables
num_players = 5
use_given_community_cards = False
commmunity_cards_given = [
{"rank": "10", "suit": "spades"},
{"rank": "9", "suit": "spades"},
{"rank": "King", "suit": "diamond... |
fd304992abbd5e3ce64a7d1ec6e8bafbffb66c39 | pjalali/password.py | /functions.py | 318 | 3.640625 | 4 | def isInt(s):
try:
int(s)
return True
except ValueError:
return False
def validateInput(userInput, switches):
for i in range(1, len(userInput)):
for switch in switches:
if str(userInput[i]).lower() == str(switch).lower():
switches[switch] = True |
afb3933e42590d007816d1b2c3906bd751d507a6 | GuilhermeSSx/NappAcademy1 | /semana 01/exercicio01.py | 160 | 3.78125 | 4 |
nome = input('Digite seu nome: ')
idade = int(input('Digite sua idade: '))
print(f"seu nome é: {nome}")
print(f"sua idade daqui a 5 anos será: {idade + 5}") |
2b2e28a1e24d1384a992c8260909ff5684ff71ce | GuilhermeSSx/NappAcademy1 | /semana 03/exercicio02.py | 1,370 | 3.875 | 4 | import csv
def find_start_subtring_credit_card(lista, parametro='303'):
"""
Função que recebe a lista com todos os registros carregados de um
arquivo CSV via Reader e busca a string 'parâmetro' como início
do campo 'Cartão de Crédito'.
Args:
lista (List): [description]
parametro (... |
3c6dbefefce01e25290841bbcfe2d4976b85a034 | GuilhermeSSx/NappAcademy1 | /semana 03/exercicio04.py | 1,541 | 3.828125 | 4 | import csv
def find_born_in_month(lista, paramether='03'):
"""
Função que recebe a lista com todos os registros carregados de um
arquivo CSV via Reader e busca os clientes nascidos no mês 'paramether'.
Args:
lista (List): Lista de tuplas
paramether (str, optional): Mês de nascimento c... |
a5333dc221c0adcb79f583faceb53c7078333601 | tocheng/Book-Exercises-Intro-to-Computing-using-Python | /Book-Chapter5_2-Range.py | 1,922 | 4.21875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Dec 29 09:48 2020
Introduction to Computation and Programming Using Python. John V. Guttag, 2016, 2nd ed
Book Chapter 5 Structured types, mutability and higher-order functions
Ranges
@author: Atanas Kozarev - github.com/ultraasi-atanas
RANGE the Theory
The range function t... |
0240f939041db7bfe697fecd110ca33dd83f84b8 | tocheng/Book-Exercises-Intro-to-Computing-using-Python | /Book-Chapter2_2-FE-odd-number.py | 1,173 | 4.46875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Nov 11 09:54:53 2020
Introduction to Computation and Programming Using Python. John V. Guttag, 2016, 2nd ed
Book Chapter 2 Finger Exercises - Find the largest odd number
@author: Atanas Kozarev - github.com/ultraasi-atanas
"""
# edge cases 100, 2, 3 an... |
32edc5c1c32209e99e6b51d2bf0cb14ba3f1a07c | tocheng/Book-Exercises-Intro-to-Computing-using-Python | /Book-Chapter2_3-Exercises-LargestOddNumberOf10.py | 1,186 | 4.28125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Nov 13 14:15:03 2020
Introduction to Computation and Programming Using Python. John V. Guttag, 2016, 2nd ed
Book Chapter 2 Finger Exercises
Largest Odd number of 10, using user input
Prints the largest odd number that was entered
If no odd number was entered, it should print ... |
58311f98171a2a3faeb736a5f3a09f9ad17a4ad6 | csheare/Gamblers_Ruin | /gamble.py | 1,234 | 3.53125 | 4 |
from players import Players,Player
import random
import sys
class Gamble:
def __init__(self, players):
self.players = players
def play(self,num_games,total_games):
current_games = total_games
for i in range(num_games):
print("Game Number: "+ str(current_games))
... |
45fb9cf424d68f5de97c737ae02fa80dc4fb9b6a | EhsanPoorshakoor/project_euler_solution | /tamrin17.py | 816 | 3.703125 | 4 | # euler 30
def jam(number):
sum_num = 0
for j in range(len(number)):
sum_num += int(number[j]).__pow__(5)
return sum_num
list_adad = []
for i in range(2,1000000):
adad = str(i)
hasel = jam(adad)
if hasel == i:
list_adad.append(int(hasel))
#print(list_adad)
... |
b4eacc7cd9b376392afb7bbb4187ca7dc96f3492 | xkal36/principles_of_computing | /merge.py | 1,601 | 3.90625 | 4 | """
Merge function for 2048 game.
"""
def slide_list(line):
"""
Slides all of the non-zero tiles slid over to the
beginning of the list with
the appropriate number of zeroes at
the end of the list
"""
slided = []
for num in line:
if num != 0:
slided.append(num)
... |
c0268b71976d4e5d72f3d6b5fc551eace11280c1 | AntoineBoulat/MDI721 | /session3/extract_beer_infos.py | 1,004 | 3.625 | 4 | import requests
from bs4 import BeautifulSoup
def get_soup_from_url(url):
res = requests.get(url)
soup = BeautifulSoup(res.content, 'html.parser')
return soup
def extract_beer_infos(url):
# Example url: https://www.beerwulf.com/fr-fr/p/bieres/brouwerij-t-verzet-super-noah.33
soup = get_soup_from_u... |
339db2b38d2ed516eb560a02a0496f4d4ceec28f | alexTheSciGuy/python | /condition.py | 297 | 3.828125 | 4 | a =1
b = 2
print('\nVariable a Is :', 'One' if(a==1) else 'Not One')
print('Variable a Is :', 'Even' if(a%2==0) else 'Odd')
print('\nVariable b Is :', 'One' if(b==1) else 'Not One')
print('Variable b Is :', 'Even' if(b%2==0)else 'Odd')
max = a if(a>b) else b
print('\nGreater Value Is:' , max) |
c3762c38b4b6c2ddb480818483257ec6b04b5357 | MrZiemni0k/Learning | /Done/100DaysChallenge/#009-Secret_Auction/Secret_Auction.py | 1,154 | 3.828125 | 4 | import os
import Art
#HINT: You can call clear() to clear the output in the console.
print(Art.logo)
player_dict = {}
while True:
name_key = input("What's your name? ")
if name_key in player_dict.keys():
print("Name already taken. Provide different name")
else:
name_bid... |
fb2865bedcf6011884b2cf4cd1f6a8728b4d51b0 | MrZiemni0k/Learning | /Done/100DaysChallenge/#029-#030-Password_Manager/main.py | 4,783 | 3.59375 | 4 | import tkinter as tk
from tkinter import messagebox
import random
import pyperclip
import json
# ---------------------------- PASSWORD GENERATOR ------------------------------- #
LETTERS = ['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',... |
cbea5aa6134b904da49885d532c06320acf57cbf | MrZiemni0k/Learning | /Done/100DaysChallenge/#022-Pong_Game/board.py | 1,581 | 4 | 4 | from turtle import Turtle
class Board(Turtle):
def __init__(self,width,height):
super().__init__()
self.width = width
self.height = height
self.penup()
self.hideturtle()
self.pencolor('white')
self.setheading(90)
self.draw_center()
... |
c52de823f8f8c4ddaa71b330bea5c6be7cca7497 | Caturprass/PRAKTIKUMIOT_ | /main.py | 1,195 | 3.765625 | 4 | from gpio import *
from time import *
#GPIO (General Purpose Input/Output) merupakan library yang digunakan untuk mengontrol GPIO Raspberry
#Pi menggunakan Python. GPIO merupakan pin atau tempat yang digunakan sebagai input dan output
#Fungsi digitalRead berguna untuk membaca input pada pin yang ditentukan. digita... |
8af86e620f32afe56f46894d0794daa085cab4b6 | danhhong/pygame_lesson | /game_lesson1.py | 798 | 3.5 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Nov 28 15:48:31 2020
filename: game_lesson1.py
pip3 install pygame
@author: danhhong
"""
import pygame
# window size, title
surface = pygame.display.set_mode((800,400))
pygame.display.set_caption('My First Game')
# change background
surface.fill([0,100,255])
# display text
... |
34d26c478973fa9f7683a0a0513ba57fab90f0fd | JacobRichardson/hackerrank | /src/preorder-tree-traversal/preorder-tree-traversal.py | 614 | 3.890625 | 4 | """
Implements a solution to the pre-order tree traversal Hackerrank problem.
https://www.hackerrank.com/challenges/tree-preorder-traversal/problem
"""
__author__ = "Jacob Richardson"
def pre_order(root):
""" Preforms a pre order tree traversal and prints the order on a single line space separated."""
... |
1cec8ec49c517530d9375f38a985b7cd4579fd66 | dholth/pyzaa | /pyzaa.py | 3,069 | 3.515625 | 4 | # -*- coding: utf-8 -*-
# pyzaa, reference implementation for PEP 441.
#
# Daniel Holth <dholth@gmail.com>
import argparse
import os.path
import stat
import sys
import zipfile
class TruncatingZipFile(zipfile.ZipFile):
"""ZipFile that can pop files off the end. This works for ordinary zip
files that do not con... |
3a486c0ef2f228be0644c8c5d57f440a74399ff2 | 4no3/pyfunc | /find_divisors.py | 397 | 3.8125 | 4 | def find_divisors(n):
lst_divisors = []
last = int(n ** .5) + 1
for a in range(1, last):
if n % a == 0:
lst_divisors.append(a)
b = n // a
if b != a:
lst_divisors.append(b)
lst_divisors.sort()
return lst_divisors
# ===== 動作確認 =====
... |
75b78e12c9b181d2869522f6a42528b82535279c | slime103/NYU_Networking_Project1 | /Assignment1/concatenation_client.py | 1,688 | 3.59375 | 4 | import sys
import os
import random
import string
# TODO: Import socket library
import socket
RAND_STR_LEN = 10
# Random alphanumeric string
def rand_str():
ret = ''
for i in range(RAND_STR_LEN):
ret += random.choice(string.ascii_lowercase + string.ascii_uppercase + string.digits)
return ret
NU... |
8e04e0bc3911f87b01ccab4a8d70101f53bff593 | stulew93/die-simulator | /dicesimulator.py | 1,773 | 4.4375 | 4 | import random
def die_face_generator(digit: int) -> str:
"""
Function to create a basic render of a die face, of value equal to digit. If digit is not an integer between 1
and 6, function will return a warning.
:param digit: Any integer.
:return: str
"""
full_line = "-----------"
middl... |
c0d4478a7027f38df1bba11db6d26b1b8fde22bd | unclelaozhang/Python_fishc | /MIN的实现过程.py | 135 | 3.65625 | 4 | def min(x):
least = x[0]
for each in x:
if each < x:
least = each
return least
print(min('123456789')) |
b81374dada33503ab1e650c241620307acd19350 | unclelaozhang/Python_fishc | /list_number调整打印样式.py | 249 | 3.625 | 4 | member = [1,2,3,4,5,6,7,8,9,10]
# count = 0
# length = len(member)
# while count < length:
# print(member[count],member[count+1])
# count += 2
for each in range(len(member)):
if each % 2 == 0:
print(member[each], member[each+1]) |
d26e6a05aace39697078f3774103349683c657af | unclelaozhang/Python_fishc | /P009_7.py | 230 | 3.765625 | 4 | #原代码如下,要求优化以提高运行效率:
# i = 0
# string = 'ILoveFishC.com'
# while i < len(string):
# print(i)
# i += 1
i = 0
string = "ILVOEFISHC.COM"
n = len(string)
while i < n:
print(i)
i += 1 |
7721eabfd56d5f61dab0983e1359d43847a0b583 | NikeSmitt/python-project-lvl1 | /brain_games/games/calc_game.py | 589 | 3.578125 | 4 | import random
import brain_games.game_loop
GAME_MESSAGE = "What is the result of the expression?"
TOP = 30
BOTTOM = 1
def add_(a, b):
return a + b, f"{a} + {b}"
def sub_(a, b):
return a - b, f"{a} - {b}"
def mult_(a, b):
return a * b, f"{a} * {b}"
def calc_game():
a = random.randint(BOTTOM, TOP... |
69bd785e7974ad4000543b3d9b947b14b389e7ca | NikeSmitt/python-project-lvl1 | /brain_games/games/even_game.py | 479 | 3.65625 | 4 | import random
import brain_games.game_loop
WELCOME_MESSAGE = 'Answer "yes" if the number is even, ' \
'otherwise answer "no".'
TOP = 100
BOTTOM = 1
def is_even(value) -> str:
return "yes" if value % 2 == 0 else "no"
def even_game():
value = random.randint(BOTTOM, TOP)
right_answer = ... |
1b049dc1145f1269bcbf38c96965fa0b13d585ca | guyjacks/codementor-learn-python | /string_manipulation.py | 872 | 4.1875 | 4 | print "split your and last name"
name = "guy jacks"
# split returns a list of strings
print name.split()
print "/n"
print "split a comma separated list of colors"
colors = "yellow, black, blue"
print colors.split(',')
print "\n"
print "get the 3rd character of the word banana"
print "banana"[2]
print "\n"
blue_moon... |
9fe43a3331f779b4fc6b0361099a90d163b8ae6b | in-darkphoenix/Thepython | /errorhandling.py | 227 | 3.828125 | 4 | print(5)
int(9)
int(6)
print(70)
print(69)
a = 5
b = "6"
print(int(6.9))
print(str(a)+b)
def div(x,y):
try:
return(x/y)
except ZeroDivisionError:
return "Division with 0 is meaningless"
print(div(1,7))
|
c565a7e5db7f648e04ecc85ac119bbdb24e53c29 | junil95/hello-world | /testboundedqueue.py | 4,097 | 4.03125 | 4 | import unittest
from boundedqueue import BoundedQueue
class TestBoundedQueue(unittest.TestCase):
'''Test all functions of BoundedQueue'''
def setUp(self):
self.boundedqueue = BoundedQueue(10)
def test_half_capacity_bounded_queue(self):
"""Tests if the queue and dequeue functions w... |
1f623fd29c479392260f12331a0feb416280222b | janzolau1987/study-py | /helloworld.py | 1,503 | 4.09375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# 单字符串
print('Hello, world!')
# 会依次打印每个字符串,遇到逗号","会输出一个空格
print('The quick brown fox', 'jumps over', 'the lazy dog')
# 打印整数
print(300)
print(100 + 200)
print("100 + 200 = ", 100 + 200)
# 输入输出
# name = input('please enter your name : ')
# print('Hello,', name)
# print ... |
17056f8959cad1014a2ff6575b7a9bc1c3e379cc | GinnyJourney/Getting-started-with-Python-2 | /snake.py | 6,652 | 3.703125 | 4 | import pygame
import sys
import copy
import random
class Snake(object):
def __init__(self, head, direction, length, body, score, fruit_pos):
"""
Initializing the snake.
"""
self.head = head
self.direction = [dx, dy] = direction
self.length = length
... |
e3553fdbc2a578a9e949e79bc97221493d3dc021 | damianwidomski/litery-oraz-okulary | /sketch_190613a.pyde | 1,341 | 3.703125 | 4 | def setup():
size(400,400)
textSize(70)
def draw():
background(0)
text("D", width/2-50, height/2)
text("W", width/2+20, height/2)
fill(155)
print(mouseX,mouseY)
if keyPressed:
fill(1)
if key == 'W' or key == 'w':
fill(255, 0, 0)
text("... |
d65a751c08cec033eadf717a7a3d24fdc987b2b0 | apervomaiskaya/Learning_Python | /Код к книге Изучаем Питон/Standard libraries.py | 1,436 | 3.625 | 4 | from random import randint
print(randint(1, 696))
from random import choice
players = ['charles', 'martina', 'michael', 'florence', 'eli']
first_up = choice(players)
print(first_up)
class Die():
def __init__(self, sides):
self.sides = sides
def roll_die(self, sides):
from random import randin... |
3488477c917b9dd7ba66ae6167e7f65099765775 | soerili/studipbot | /db_utility.py | 1,673 | 3.53125 | 4 | import os
import sqlite3
from exceptions import DatabaseError
class DatabaseConnection:
def __init__(self, data_directory, db_file):
self.db_file = db_file
self.data_directory = data_directory
os.makedirs(self.data_directory, exist_ok=True)
try:
conn = self.get_db_conne... |
d6604d4cf2009ba2483d30323e71b084f0163767 | Epsiloneta/app_PDsimilarity | /menus_info.py | 13,830 | 4.1875 | 4 | import Tkinter as tk
from help_dialogs import CustomText
# \TODO add references
def about_homology():
win = tk.Toplevel()
win.title("Homology and Persistent Homology")
about = '''
-------------------------------------------------------------------
HOMOLOGY
-----------------... |
a9558c7e63dcf294c9ce474946d614fbaf7b8bc9 | kalefish52/hw4_hyphaltip_template | /rand_shuffle_seqs.py | 442 | 3.5 | 4 | #!/usr/bin/env python3
# Using python write a tool which generates a random subsampling tool
# for sequences. Given a FASTA sequence database file, generate a new
# file which is a random subset these sequences selecting only 10% of
# them. Make this 10% an option in the program so it is easy to change
# to 20%, etc.
... |
1bf33ec4425ead3f9a09885b71522c5130e85f97 | zaitsevayulia/-4 | /laba4.py | 2,456 | 3.828125 | 4 | class Garbage:
def __init__(self, name):
self.name = name
self.usefull = 100
def message(self):
print('Разделяйте мусор правильно!')
class Organic(Garbage):
def __init__(self, name, size):
super().__init__(name)
self.size = size
def foodworm(self... |
b29c05d866cf64dcbd56ea12371cbe5ca69f823f | ngecu/FREE-UDEMY-API | /backend.py | 1,518 | 4 | 4 | import sqlite3
#Make a connection with the database
def connect():
conn = sqlite3.connect('source.db')
cur = conn.cursor()
cur.execute("CREATE TABLE IF NOT EXISTS courseM (id INTEGER PRIMARY KEY,link TEXT,title TEXT ,headline TEXT,instructor TEXT,rating TEXT,review TEXT )")
conn.commit()
conn.clos... |
b5afd457fb7212f501db1ddb485a8a8f6668ab49 | naocandu/Algorithms_Design_and_Analysis_Part_1 | /week1.py | 1,507 | 4.03125 | 4 | """
The file "IntegerArray.txt" contains all of the 100,000 integers between 1 and 100,000 (inclusive) in some order, with no integer repeated.
Your task is to compute the number of inversions in the file given, where the ith row of the file indicates the ith entry of an array.
Because of the large size of this array, ... |
6660ada6462249706663ea7d4102c68e6c914a3d | mistybreezy/PizzaAPI | /tests/class_tests/test_drink.py | 1,304 | 3.609375 | 4 | from classes.Item import Item
from classes.Drink import Drink
from classes.Menu import Menu
# Assume menu is correct.
data = {"pizza": {"size": {"S": 0.8, "M": 1.0, "L": 1.5}, "type": {"pepperoni": 2, "margherita": 3, "vegetarian": 4, "Neapolitan": 1, "Yuwan": 2, "NewType": 5}, "topping": {"olives": 3, "tomatoes": 1, "... |
2154291515f1a95d48841f87332d858d973f59ef | tpbarron/mentee_networks | /learning_rates.py | 4,409 | 3.765625 | 4 | from __future__ import division # which forces / to adopt Python 3.x's behavior that always returns a float.
import matplotlib.pyplot as plt
scaler = 1
convergence = 15*scaler
num_epochs_to_learn_representation = 0.6667*convergence
thresh = 0.001
# this is the learning rate (a funtion of iteration). Later i shold be... |
6b3a616b1c1dfbb11074003fb5495e5a557e6fcb | YosselinAngeles/Conduccion_de_Calor | /Calibracion_2.py | 2,779 | 3.765625 | 4 |
import Funciones_D as fun
import numpy as np
import matplotlib.pyplot as plt
# Programa principal
print()
print("+----------------------------------------------------+")
print("| Solucion de la transferencia de calor |")
print("+----------------------------------------------------+")
# Datos de entrad... |
42d80cb278f7959b629cd64973709a92f452f6c2 | srdecny/diasys | /hw1/minDistUtil/levenshtein.py | 3,050 | 3.703125 | 4 | from collections import deque
import itertools
import sys
def Levenshtein(firstString, secondString, delimiter, printDistance, printAlignment, printError, out=sys.stdout):
wer = {"sub" : 0, "add" : 0, "remove" : 0}
correctWords = 0
minimumDistance = 0
words_first = firstString.split(delimiter)
wo... |
02e44dffef6fd1bb5da6c0cf06c4a00bc6c121c0 | gop50k/Python3 | /src/c2/calc-fee.py | 988 | 3.84375 | 4 | # coding: UTF-8
# 遊園地の入場料を計算するプログラム
# 人数の入力
children = int(input("子供料金(13歳未満)は何人?"))
normal = int(input("通常料金(14〜64歳)は何人?"))
elder = int(input("年配者料金(65〜歳)は何人?"))
# 集計
total_num = children + normal + elder
children_price = children * 500
normal_price = normal * 1000
elder_price = elder * 700
total_price = children_pri... |
fb5e4d4e15d22b4948f05ce63b282a5c796e0d7f | Yuzu/Hangman | /main/Hangman.py | 10,011 | 4.25 | 4 | #Hangman.py
#Tim Wu
import string
#setStage will define the underscores + guessing areas for the user. Stage when used in context of this whole program will refer to where letters and underscores are displayed.
def setStage(userstring):
indexposition = 0
stage = ""
#Making punctuation and whitespac... |
927d2e6c354be36e1cb2433f72e72fcf8dd32e7a | dhirajgidde/PyGames | /HeliCop.py | 2,950 | 3.59375 | 4 | # Basic Initialization of pygame
import pygame
import random
import time
pygame.init()
from pygame.locals import (K_UP,K_a,K_s,K_d,K_w,K_DOWN,K_LEFT,K_RIGHT,K_ESCAPE,KEYDOWN,QUIT)
# Set the screen
screen_height=600
screen_width=800
screen=pygame.display.set_mode([screen_width,screen_height])
class Player(pygame.spri... |
eefa71d84e703e4a55cc4a976fb92ba9fe3315bf | awaelchli/pytorch-mosaic | /assignment1_test.py | 3,050 | 3.703125 | 4 | import numpy as np
import matplotlib.pyplot as plt
import os
import utils
from assignment1 import Assignment1
def make_folders():
os.makedirs('output/A1_test/features', exist_ok=True)
os.makedirs('output/A1_test/neighbors', exist_ok=True)
def test_grid():
patch_size = 32
original_width = 100
ori... |
d8f90ea74ea250e3ef20f5f6f9d70a42beb623a4 | dellumdeus/donbeer | /donbeer/configuration.py | 843 | 3.609375 | 4 | import pygame
class Configuration:
"""
This class defines a configuration for the game object.
It is customizable for following attributes:
- window-width/height
- fps
- color
- fullscreen
"""
def __init__(self, width, height, color):
self.window_width = wi... |
d73229dd8ee6fa39da14511c41f91aa0ec80b593 | Babavalichetlu/HackerRankingTest | /HackeRrankProblems/src/com/hackerranker/Spring Training(Python) All test cases passed | 1,084 | 3.734375 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
#
# Complete the 'getMostVisited' function below.
#
# The function is expected to return an INTEGER.
# The function accepts following parameters:
# 1. INTEGER n
# 2. INTEGER_ARRAY sprints
#
def getMostVisited(n, sprints):
# Write your co... |
2693b1f1b272bbdbdd2570514e1d3eca5ef86ae9 | Chris-gde/exercicios | /algoritmo-Fabiano/05-04-exe6.py | 635 | 3.984375 | 4 | '''
7) Faça um programa que o usuário informe a quantidade de alunos de uma turma, o sistema deve ler o peso e altura de cada aluno, ao final informar a média dos pesos, alturas e imc.
'''
qtd=int(input("Digite a quantidade de alunos da sua turma: "))
peso=0
altura=0
for i in range(0, qtd):
peso = int(input(... |
d5865fa2c46f960631b5f99abebb30a4b21704c2 | Chris-gde/exercicios | /algoritmo-Fabiano/17-05-exe1.py | 396 | 3.765625 | 4 | '''
1) Faça um algoritmo para ler a idade de 5 pessoas e informar qual foi a maior idade informada.
'''
m=0
i1=int(input("Informe a idade "))
if(i1>m):
m=i1
i2=int(input("Informe a idade "))
if(i2>m):
m=i2
i3=int(input("Informe a idade "))
if(i3>m):
m=i3
i4=int(input("Informe a idade "))
if(i4>m):
... |
b67babb057054f9c58063cee41fdbc8244d23071 | Chris-gde/exercicios | /algoritmo-Fabiano/22-3-exe1.py | 249 | 4.21875 | 4 | '''
1) Escreva um algoritmo para ler um valor e escrever o seu antecessor.
usuario informa um valor
valor=valor - 1
'''
num=int(input("Digite um numero qualquer: "))
valor=num - 1
print("O antecessor do numero digitado é: ", valor)
|
af1368faa37377ce0f6df653891f9104d5cd23b6 | Chris-gde/exercicios | /algoritmo-Fabiano/03-05-exe4.py | 699 | 4.15625 | 4 | '''
(4) - Faça um programa para uma loja de tintas. O programa deverá pedir o tamanho em metros quadrados da área a
ser pintada. Considere que a cobertura da tinta é de 1 litro para cada 3 metros quadrados e que a tinta é vendida
em latas de 18 litros, que custam R$ 80,00. Informe ao usuário a quantidades de latas d... |
3d0785a60c2af05e31ac80f61d05accc32a7b5e0 | Chris-gde/exercicios | /algoritmo-Fabiano/31-05-desafio2.py | 585 | 4.15625 | 4 | '''
Faça um programa onde o usuário informe a km inicial no momento que o tanque é cheio, no próximo abastecimento
o usuário deve informar os km percorridos e a quantidade de combustível necessária para completar o tanque (l).
O sistema deve informar a o consumo médio (km/l).
'''
n=int(input("Informe a kilometrage... |
10e4800a12979cad6ddb5c80f13e5243a8770bfc | julivanespi/py_comm | /v1/py_comm_c.py | 303 | 3.734375 | 4 | # Import socket module
import socket
# Create a socket object
s = socket.socket()
print("Created Socket.")
# Define the port on which you want to connect
port = 12345
# connect to the server on local computer
s.connect(('127.0.0.1', port))
print("Client Connected.")
# close the connection
s.close()
|
427e6f0978cd52b339ef4f89256ace7ff9298c4d | learnthecraft617/dev-sprint1 | /RAMP_UP_SPRINT1/exercise54.py | 291 | 4.21875 | 4 |
def is_triangle (a, b, c):
if a > b + c
print "YES!"
else
print "NO!"
is_triangle (4, 2, 5)
#5.4
question = raw_input('Please enter 3 lengths to build this triangle in this order (a, b, c)/n')
length = raw_input (a, b, c)
is triangle (raw_input)
|
1214263aaf06e8add1559ebd93809acebd221500 | jennyyu73/projecteuler | /9 special pythagorean triplet.py | 301 | 3.859375 | 4 | #9 special pythagorean triplet
import time
start=time.time()
a=0
b=0
c=0
while a+b+c!=1000 or a+b+c<1000:
for m in range(500):
for n in range(500):
a=m**2-n**2
b=2*m*n
c=m**2+n**2
print(a*b*c)
end=time.time()
print(end-start,"seconds")
|
68bbcc21f7e05cc005278bd43faa3b30bf9330f1 | rev0lver/arithmetic | /tree_traversal.py | 1,165 | 3.703125 | 4 | # -*- coding:utf-8 -*-
'''
a
/\
b c
/\ /
d e f
'''
class BinaryTreeNode(object):
def __init__(self, data=None, left=None, right=None):
self.data = data
self.left = left
self.right = right
def __str__(self):
return str(self.data)
n1 = BinaryTreeNode(data="D"... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.