blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
529ed8b188e4ecb5a05d28a5b431150aae425239 | Sakina28495/Fashion | /demo.py | 215 | 3.53125 | 4 | def codemaker(urstring):
output=list(urstring)
print(output)
for index,letter in enumerate(urstring):
for vowels in 'aeiou':
if letter==vowels:
output[index]='x'
return output
print(codemaker('Sammy')) |
3456da0d36a1771bce68108957a7e6713aea83b4 | eltobito/devart-template | /project_code/test2.py | 515 | 3.828125 | 4 | import Image
picture = Image.open("picture.jpg")
# Get the size of the image
width, height = picture.size()
# Process every pixel
for x in width:
for y in height:
current_color = picture.getpixel( (x,y) )
print current_color
####################################################################
... |
7dd133e44d846b84c1cda13c84ff3dc50aed1148 | jadynk404/CMPT120-Project | /dictionary.py | 1,169 | 3.984375 | 4 | #Worked with Emmanuel Batista
def main():
title = "Interactive Dictionary"
print(title)
myFile = input("Please input the name of your file: ").strip()
myFile = myFile.lower()
with open(myFile, "r") as myFile: #reads file and assigns value to variables
dictionary = myFile.readlines()
... |
7db722bc3d5e417139bb055937e9315289f90b52 | cgraaaj/PracticeProblems | /Add two numbers as a linked list/main.py | 1,176 | 3.796875 | 4 | # Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution:
result = None
def addTwoNumbers(self, l1, l2, c=0):
v1 = []
v2 = []
res = []
while l1:
v1.append(l1.val)
... |
fbb3938b667cba8afe5144c023cacbd833028f03 | crashtack/exercism | /python/clock/clock.py | 1,144 | 4.34375 | 4 | class Clock(object):
""" A Clock class that ignores date """
def __init__(self, hours=0, minutes=0):
""" Initialize the Clock object """
self.hours = hours % 24
self.minutes = minutes
self.time_min = (self.hours * 60) + self.minutes
self.time_min = self.time_min % 1440
... |
11aad31a77cdbca35a0961b5cfb1c46d56c438c4 | miguelencastillogar/SeleniumPythonGitJenkinsAllureReporting | /Ejemplos_Python/11-input-2.py | 562 | 4.03125 | 4 | # Formulamos los mandatos que debe cumplir el usuario
pregunta = '\nAgrega un numero y te dire si es par o impar '
pregunta += '(Escribe "Cerrar o cerrar" para salir de la aplicacion) '
# Variable booleana que mantendra el while iterandose
preguntar = True
while preguntar:
numero = input(pregunta)
if numero... |
f877815460bf804c8756d2dbb49cbe2cea568e10 | miguelencastillogar/SeleniumPythonGitJenkinsAllureReporting | /Ejemplos_Python/14-clases-5.py | 2,681 | 3.9375 | 4 | class Restaurante:
def __init__(self, nombre, categoria, precio):
# Por defecto estas variables estan publicas
# self.nombre = nombre
# self.categoria = categoria
# self.precio = precio
# Para hacerlas PROTECTED unicamente al inicio del nombre
# del atributo le agr... |
11743b0257a83b0df21ab3daadcb2483468eaa83 | miguelencastillogar/SeleniumPythonGitJenkinsAllureReporting | /Ejemplos_Python/05-numeros-2.py | 401 | 3.828125 | 4 | def suma(a=0, b=0):
print(a + b)
suma(2, 3)
suma(4, 1)
suma(8, 12)
suma()
def resta(a=0, b=0):
print(a - b)
resta(2, 3)
resta(4, 1)
resta(8, 12)
resta()
def multiplicacion(a=0, b=0):
print(a * b)
multiplicacion(2, 3)
multiplicacion(4, 1)
multiplicacion(8, 12)
multiplicacion()
def division(a=0, b... |
87267ed67fb71ac07755fff6f81fb02f2f7b4a95 | miguelencastillogar/SeleniumPythonGitJenkinsAllureReporting | /Ejemplos_Python/10-diccionarios-1.py | 1,528 | 3.875 | 4 | # Creando un diccionario (objeto) simple
cancion = {
# llave : valor (Para agregar mas valores los separamos por comas)
'artista': 'Metallica',
'cancion': 'Enter Sandman',
'lanzamiento': 1992,
'likes': 3000
}
# Imprimir todos los valores
print(cancion)
# Acceder a los elementos del diccionario
pr... |
0f9b703805d7afabd6a9d0313076f003f0d16b3a | bobbyscharmann/flypy | /examples/main.py | 714 | 3.796875 | 4 | from flypy.neural_networks.activation_functions import Sigmoid, ReLU
from flypy.neural_networks import NeuralNetworkTwoLayers
import numpy as np
l = ReLU()
#l.plot(-10, 10, derivative=False)
print("Hello world.")
nn_architecture = [
{"input_dim": 2, "output_dim": 4},
#{"input_dim": 4, "output_dim": 6},
#{... |
1210ad4c30493aefaa6585472991a79894bdae58 | bobbyscharmann/flypy | /flypy/reinforcement_learning/cartpole/random_agent.py | 783 | 3.5 | 4 | """Implementation of the OpenAI Gym CartPole exercise with a random sampling of the action space.
In other words, a vey simplistic (or dumb) agent)"""
import gym
env = gym.make("CartPole-v0")
env.reset()
# Couple of variables for knowing when the episode is over
done: bool = False
# Keeping track of total aware and ... |
a899cbea277c1183228ac5f7396dce5347c69279 | numbertheory/nanogenmo | /verb.py | 991 | 3.5 | 4 | """Get a random verb, from a given tense"""
import random
def get(tense):
""" Get a verb in the right tense """
verbs = {'past': ['spoke', 'baked', 'competed',
'smoked', 'switched', 'unlocked'],
'present': ['speaks', 'bakes', 'competes',
'smokes', '... |
deb0106dadea39101d8c40357c3f41f9383a9937 | GarryK97/Python | /Hashtable/Task5.py | 2,715 | 4.4375 | 4 | from Task3 import HashTable
def read_file_removesp(file_name):
"""
Read a text file and convert it to a list of words without any special characters.
:param file_name: File to read
:return: the list of words
"""
f = open(file_name, 'rt', encoding='UTF8')
file_list = []
for l... |
0d471841786f140724e55f0452db3469f9043be7 | GarryK97/Python | /Algorithms/Dijkstra&Bellman-Ford.py | 13,153 | 3.640625 | 4 | import heapq
"""
Graph implementation for best_trades
"""
class Trade_Graph:
def __init__(self, num_vertices):
"""
Initialize Graph object
:param num_vertices: Total number of vertices
:Complexity: Best Time: O(V), Worst Time: O(V), Auxiliary Space: O(V)
... |
b0f1454101fcd2aa96d12bc55bfa6aebcd002103 | VinceWu-bit/Decision-Chessboard-Puzzle | /env.py | 2,181 | 3.515625 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Time : 2021/6/12 18:15
# @Author: Vince Wu
# @File : env.py
import numpy as np
class ChessBoardEnv:
def __init__(self):
self.chessboard = np.array([0, 0, 0, 0])
self.key_dic = {0: 1, 1: 1, 14: 1, 15: 1, # 4维立方体编码规则
6: 2, ... |
606de1aa9e681af56f022880698088b3ea58904d | nidakhawar/PracticePythonExcercises | /AverageOfSubjects.py | 510 | 4.1875 | 4 | biology=float(input("Please input your Biology score:"))
chemistry=float(input("Please input your Chemistry score:"))
physics=float(input("Please input your Physics score:"))
if biology<40:
print("Fail")
if chemistry<40:
print("Fail")
if physics<40:
print("Fail")
else:
score=((biology+chemistry+physics)/3)
... |
2fe1eb2779838cbd559241374b9f94d6b36bc413 | KevinSilva11/Python_The_Huxley | /PH.py | 145 | 3.546875 | 4 | ph = float(input())
if ph < 7:
print('Acida')
else:
if ph > 7:
print('Basica')
else:
print('Neutra')
|
bc5650df61ac37eef9df8a63e2b7d0b147d512da | SuzaneFer/phyton-basico-graficos | /ComparandoGenomas.py | 799 | 3.5 | 4 | #Neste estudo de caso, faremos a comparação entre duas sequências de DNA:
# (1) ser humano; vs. (2) bactéria.
import matplotlib.pyplot as plt
import random
entrada = open("bacteria.fasta").read()
saida = open("bacteria.html","w")
cont = {}
# Dicionário
for i in ['A', 'T', 'C', 'G']:
for j in ['A',... |
976cc8ab3327128b679d3d205e8c2dc1b2daae0b | zacharykaczor/Small-Programs | /odd_numbers.py | 535 | 4.1875 | 4 | # Based on https://www.youtube.com/watch?v=LkIK8f4yvOU.
# The Difference of Two Squares.
number = int(input("Please enter a positive odd number: "))
while number % 2 == 0 or number < 0:
number = int(input(
"Please enter a positive number: " if number < 0
else "Please enter an odd number: "
))... |
c2f1391ee6e1ce4aa1cca4a81314f323495dc655 | ProspePrim/PythonGB | /Lesson 5/task_5_2.py | 985 | 3.96875 | 4 | #Создать текстовый файл (не программно), сохранить в нем несколько строк,
#выполнить подсчет количества строк, количества слов в каждой строке.
with open('test.txt', 'w') as my_f:
my_l = []
line = input('Введите текст \n')
while line:
my_l.append(line + '\n')
line = input('Введите... |
05da3490735523a90c3b6a6a206a5445ac6e8fa4 | ProspePrim/PythonGB | /Lesson 2/task_2_4.py | 524 | 4.03125 | 4 | #Пользователь вводит строку из нескольких слов, разделённых пробелами.
#Вывести каждое слово с новой строки. Строки необходимо пронумеровать.
#Если в слово длинное, выводить только первые 10 букв в слове.
a = input("введите строку ")
list_a = []
i = 0
list_a = a.split()
for _ in range(len(list_a)):
print(f"{list... |
cc84abe6637d76e56a7ac2c958ebd7c8a808c1c1 | ProspePrim/PythonGB | /Lesson 2/task_2_1.py | 628 | 4.125 | 4 | #Создать список и заполнить его элементами различных типов данных.
#Реализовать скрипт проверки типа данных каждого элемента.
#Использовать функцию type() для проверки типа.
#Элементы списка можно не запрашивать у пользователя, а указать явно, в программе.
list_a = [5, "asdv", 15, None, 10, "asdv", False]
def type_... |
8ff0adfd4e67aa0a69a45ebda1eb30ec290dcd49 | ProspePrim/PythonGB | /Lesson 7/task_7_1.py | 1,162 | 3.65625 | 4 | class Cell:
cells: int
def __init__(self, cells: int):
self.cells = cells
def __str__(self):
return str(self.cells)
def __int__(self):
return self.cells
def __add__(self, cells: 'Cell'):
return Cell(self.cells + cells.cells)
def __sub__(self, cells: 'Cell'):
... |
bce8bf614aca3883f2ac618caa8f00bc32a5dd73 | costacoz/python_design_patterns | /behavioral/iterator.py | 1,296 | 4.5 | 4 | # Iterators are built into Python.
# It can be engaged, using 'iter(arg*)' function
# arg* - can be list, tuple, dic, set and string.
# Below is the example of using it.
# fruits_tuple = {'apple', 'blueberry', 'cherry', 'pineapple'}
# fruits_tuple = ('apple', 'blueberry', 'cherry', 'pineapple')
# fruits_tuple = ['appl... |
a387b981c804a8e38ba20ce58d2417d82bc4dd89 | muhammadyou/PythonTutorial | /ThreadingExample.py | 1,758 | 4.09375 | 4 | import threading
import time
class Example(threading.Thread):
def run(self):
for _ in range(10):
time.sleep(1)
print(threading.current_thread().getName())
def example():
for _ in range(10):
time.sleep(1)
print("hELlo")
def example1(name, x):
print("From exa... |
717852b99833f1e2f9470bb7e906f0cb29d7874e | bjolley74/myTKfiles | /lesson1.py | 255 | 3.859375 | 4 | """lesson1.py - message box: creates a tk message box"""
from tkinter import *
from tkinter import messagebox
root = Tk()
root.withdraw()
messagebox.showinfo('Bobby\' World', 'Hello Y\'all! This is a message from Bobby\nThis is some really cool stuff') |
9c47ecc06cd8e6525255f441528d9deae2655c9f | jgu13/Miscellaneous | /Python/ecosys_simulator/ecosystem_simulator.py | 13,854 | 4.125 | 4 | # Jiayao Gu
# 260830725
import random
import matplotlib.pyplot as plt
class Animal:
# Initializer method
def __init__(self, my_species, row, column):
""" Constructor method
Args:
self (Animal): the object being created
my_species (str): species name ("Lion" or "Zebr... |
0b602263ce8b46a900c767c974efcce4ca0b2984 | JDWree/Practice | /Python/mastermind.py | 3,436 | 4.1875 | 4 | # Simple version of the game 'mastermind'
#----------------------------------------
# Version 1.0 Date: 5 April 2020
#----------------------------------------
# Player vs computer
# A random code gets initialized. The player has 10 guesses to crack the code.
# The game tells the player when it has a right digit i... |
059b163345985fdcfee9f3e410de39e001218782 | gagaspbahar/prak-pengkom-20 | /P02_16520289/P02_16520289_02.py | 744 | 3.5625 | 4 | # NIM/Nama : 16520289/Gagas Praharsa Bahar
# Tanggal : 4 November 2020
# Deskripsi: Problem 2 - Konversi basis K ke basis 10
#Kamus
#int sm = jumlah bilangan dalam basis 10
#int n = jumlah digit
#int k = basis awal
#int i = counter
#Inisialisasi variabel
sm = 0
n = int(input("Masukkan nilai N: "))
k = int(input("Mas... |
885e989095d06495061674fe1e2696b815df9463 | gagaspbahar/prak-pengkom-20 | /H03_16520289/H03_16520289_01.py | 436 | 3.609375 | 4 | # NIM/Nama : 16520289/Gagas Praharsa Bahar
# Tanggal : 15 November 2020
# Deskripsi: Problem 1 - Penulisan Terbalik
# Kamus
# int n = panjang array
# int ar[] = array penampung angka
#Algoritma
#Input
n = int(input("Masukkan N: "))
#Inisialisasi array dan memasukkan angka ke array
ar = [0 for i in range(n)]
for i i... |
5966f2409f0998aa515f8f40b56f3339a2d4298a | plaer182/Python3 | /test_random_symbol.py | 1,575 | 3.546875 | 4 | #!/usr/bin/env python3
from random_symbols import random_symbol
import string
def test_length_name():
"""
Check length of element in list of results
"""
try:
random_symbol(["Annannannannannannannannannannannannannannanna", "Boris", "Evgenia", "Viktor"])
except:
pass... |
2724d92157d61f930c089931f2b55042dcfe9f0e | plaer182/Python3 | /FizzBuzz(1-100)(hw2).py | 354 | 4.15625 | 4 | number = int(input('Enter the number: '))
if 0 <= number <= 100:
if number % 15 == 0:
print("Fizz Buzz")
elif number % 3 == 0:
print("Fizz")
elif number % 5 == 0:
print("Buzz")
else:
print(number)
elif number < 0:
print("Error: unknown symbol")
else:
... |
df113dafcc1cf93b98304cc6f8f33efbe0a2e296 | plaer182/Python3 | /fahrenheit_to_celsius(hw1).py | 158 | 4.125 | 4 | celsius = float(input('Enter the temperature in degrees to Сelsius> '))
fahrenheit = celsius * 1.8 + 32
print(str(fahrenheit) + ' degrees to Fahrenheit')
|
08fe50d6f996a359bd2346667554abde47a94c47 | Jamesbwwh/Minesweeper | /Minesweeper/Minefield.py | 3,057 | 3.78125 | 4 | import random
def generate(difficulty):
mineField = printMineField(difficulty)
height = len(mineField)
width = len(mineField[0])
ranges = width * height
mines = random.randint(ranges // 8, ranges // 7)
# mines = 4; # comment or remove this line. for testing only.
print "Difficulty: ", diff... |
f677307abacfa8b8c1e095bf3eeffaa1f94ffe0f | iman2008/first-repo | /random1.py | 187 | 3.875 | 4 | #defining 10 random number between 10 and 20
import random
def random_numer():
i=0
while (i<=10):
x = random.random() * 20
if 10 <= x <= 20:
print (x)
i=i+1
random_numer()
|
0f23631ef11d79a29889cb820371aa21ffaecde8 | iman2008/first-repo | /lab4task1.py | 336 | 3.765625 | 4 |
def sum_adder (mlist):
"""this will add up the content of the list"""
total = 0
s_list = mlist
for item in s_list:
if isinstance(item,int):
total = total + item
elif isinstance (item,list):
total=total+sum_adder (item)
else:
return "you have not select proper list"
return total
x = [90,10,11]
print... |
9b624ac6dee525b0da68baa1196f8b273486d237 | Mentos15/Python_2 | /paswords.py | 691 | 3.5625 | 4 | #! python3
# paswords.py
PASWORDS = { 'email': 'vital2014','vk':'Vital2014','positive':'vital2014'}
import sys,pyperclip
if len(sys.argv)<2:
print('Использование: python paswords.py[Имя учетной записи] - копирование пароля учетной записи')
sys.exit()
account = sys.argv[1] # первый аргумент командной строки - э... |
db6a67f488a152ccc2768d3d24728afb318f10de | CodecoolBP20172/pbwp-3rd-si-code-comprehension-kristofilles | /comprehension.py | 2,101 | 4.3125 | 4 | """Its a bot what randomly choose a number between 1 and 20, and the user need to guess within 6 round what
number was choosen by the bot."""
import random #import the random module
guessesTaken = 0 #assign 0 to guessesTaken variable
print('Hello! What is your name?') #print out this sentence
myName = input() #assig... |
19a4a42767f001a14afeb4debed9ef26c6e69afe | rdugh/pythonds9 | /pythonds9/trees/binary_tree.py | 1,028 | 3.8125 | 4 | class BinaryTree:
def __init__(self, key):
self.key = key
self.left_child = None
self.right_child = None
def insert_left(self, key):
if self.left_child is None:
self.left_child = BinaryTree(key)
else: # if there IS a left child
t = Binary... |
6ced4a96655281b60edd62a77ea9e76b6f79bd55 | brentEvans/algorithm_practice | /Python/algo.py | 2,264 | 3.640625 | 4 |
class Node:
def __init__(self, value):
self.val = value
self.next = None
class SLL:
def __init__(self):
self.head = None
def addBack(self,value):
new_node = Node(value)
if self.head == None:
self.head = new_node
else:
runner = ... |
07bd3a329eafee4c2398a08943aeb985a282b6f2 | onionmccabbage/pythonTrainingMar2021 | /using_ternary.py | 474 | 4.40625 | 4 | # Python has one ternary operator
# i.e. an operator that takes THREE parts
# all other operators are binary, i.e. they take TWO parts
# e.g. a = 1 or 3+2
# the ternary operator works like this
# 'value if true' 'logical condition' 'value if false'
x = 6
y = 5
print("x" if x>y else "y")
# alternative syn... |
8b08218eb70b47bfb0aa02cfacf775dcdb2a3089 | onionmccabbage/pythonTrainingMar2021 | /py2demo.py | 242 | 3.859375 | 4 | print "hello" # Python 2
print('also hello') # also works in Python 2
# division of ints
7/3 # is 2 in Py2 and 3 and a bit in Py 3
# py 2 has a 'long' data type - change it to 'float'
# some py 2 functions were re-defined in py 3
|
8b888a5341335f8976cfc23b7ede527047886ec3 | AnindKiran/N_Queen-s-Problem-Solution-in-Python | /Final N-Queens Project.py | 3,087 | 4.28125 | 4 | a="""This is a program used to display ALL solutions for the famous N-Queens Problem
in chess. The N-Queens Problem is a problem where in an N-sized chess board, we have
to place N Queens in such a way that no one queen can attack any other queen"""
print(a)
print()
a="""This program will take your input and will ... |
04860c836937ba8bc594c64d7c9b752ea564269e | jeremy-robb/KnoxClassRecommender | /tools.py | 3,239 | 4 | 4 | from lists import *
takeFrom = []
def chooseMajors():
print("")
print("To choose a major, type the first 3 letters of the specialization, followed by the first 2 letters of the degree")
print("Examples: CS BA (Computer Science BA) , MATBA (Math BA) , PHYMI (Physics minor)")
print("Choose major one")
... |
4a16ad732d79913225b5e89bc29acc27bf81937c | Lexical-Lad/Machine-Learning-Python-R-Matlab-codes | /Machine Learning A-Z Template Folder/Part 1 - Data Preprocessing/PreprocessingPractice.py | 1,626 | 3.609375 | 4 | import numpy as np
import pandas as pd
import matplotlib.pyplot as mlt
import os
#os.chdir(...)
dataset = pd.read_csv("Data.csv")
#splitting the dataset into the feature matrix and the dependent variable vector
X = dataset.iloc[:,:-1].values
y = dataset.iloc[:,-1].values
#conpensating for the missing values, if any
... |
3d0d26f588dfeb0d23e179fbdf94a6b35f0388a8 | lazyseals/crawler | /products/category_parser.py | 18,232 | 3.671875 | 4 | from products import items as d
# Foreach shop a unique parser must be written that executes the following steps:
# 1. Category name and product name to lower case
# 2. Check if a product in category name needs to be replaced by a mister m category
# 3. Determine mister m category based on a pattern in the product nam... |
653b56c505745fb2947589692c3a628d149d27ef | robertmplewis/playground | /wordquiz.py | 649 | 3.921875 | 4 | #!/usr/bin/env python
import operator
def main():
print word_count()
def word_count():
word_totals = {
}
book_contents = f.read()
book_contents = book_contents.replace('\n', ' ')
book_contents = book_contents.replace(',', '')
book_contents = book_contents.replace('.', '')
book_contents = book_conten... |
375b0579cdbe45e4a66d954f8d5e767f8ef70546 | justEhmadSaeed/ai-course-tasks | /Python Assignment 1/Part 2/Task 5.py | 261 | 4.28125 | 4 | # Write a list comprehension which, from a list, generates a lowercased version of each string
# that has length greater than five
strings = ['Some string', 'Art', 'Music', 'Artifical Intelligence']
for x in strings:
if len(x) > 5:
print(x.lower()) |
a54b52aee8ebf3cf44dc050ee68699aa4c6ee011 | justEhmadSaeed/ai-course-tasks | /Python Assignment 1/Part 3/Task 3.2.py | 306 | 3.6875 | 4 | # One line function for intersection
# Uncomment below code to generate random lists
intersection = lambda a, b: list(set(a) & set(b))
# import random
# a = []
# b = []
# for i in range(0, 10):
# a.append(random.randint(0, 20))
# b.append(random.randint(5, 20))
# print(intersection(a, b))
|
af2ca98dfba5c5fdf958422f55c0685bef3937e4 | JanBednarik/micropython-matrix8x8 | /examples/game_of_life.py | 1,870 | 3.5 | 4 | import pyb
from matrix8x8 import Matrix8x8
def neighbors(cell):
"""
Yields neighbours of cell.
"""
x, y = cell
yield x, y + 1
yield x, y - 1
yield x + 1, y
yield x + 1, y + 1
yield x + 1, y - 1
yield x - 1, y
yield x - 1, y + 1
yield x - 1, y - 1
def advance(board):
... |
c6324a495ce9b5cd11784e34e4da56c427482e1f | daniellopes04/uva-py-solutions | /list2/120 - Stacks of Flapjacks.py | 1,011 | 3.5 | 4 | # -*- coding: UTF-8 -*-
def main():
while True:
try:
unsorted = list(map(int, input().split()))
current = unsorted.copy()
final = sorted(unsorted)
N = len(final)
steps = []
for i in range(len(current) - 1, -1, -1):
ind... |
0babe69773bebc354b6da02c83f1fd151b4034dc | daniellopes04/uva-py-solutions | /list3/902 - Password Search.py | 943 | 3.5625 | 4 | # -*- coding: UTF-8 -*-
def main():
while True:
try:
line = input().strip()
while line == "":
line = input().strip()
items = line.split()
if len(items) == 2:
n = int(items[0])
text = it... |
8353125ae9724cfef90b738d8aad6998ca78f8fe | SpCrazy/crazy | /code/SpiderDay03/bs4_learn/hello.py | 283 | 3.5 | 4 | from urllib.request import urlopen
from bs4 import BeautifulSoup
response = urlopen("http://www.pythonscraping.com/pages/page1.html")
bs = BeautifulSoup(response.read(),"html.parser")
print(bs.h1)
print(bs.h1.get_text())
print(bs.h1.text)
print(bs.html.body.h1)
print(bs.body.h1)
|
4788dd580886d9d056d2c5847cacda6b2a95628e | SpCrazy/crazy | /code/SpiderDay1_Thread/condition/concumer.py | 821 | 3.78125 | 4 | import time
from threading import Thread, currentThread
class ConsumerThread(Thread):
def __init__(self, thread_name, bread, condition):
super().__init__(name=thread_name)
self.bread = bread
self.condition = condition
def run(self):
while True:
self.condition.acqu... |
8c0d380707fd8ed99cba1e6e44a13b63313bc0c7 | whlg0501/2018_PAT | /1004.py | 1,663 | 3.578125 | 4 | """
1004 成绩排名 (20)(20 分)
读入n名学生的姓名、学号、成绩,分别输出成绩最高和成绩最低学生的姓名和学号。
输入格式:每个测试输入包含1个测试用例,格式为
第1行:正整数n
第2行:第1个学生的姓名 学号 成绩
第3行:第2个学生的姓名 学号 成绩
第n+1行:第n个学生的姓名 学号 成绩
其中姓名和学号均为不超过10个字符的字符串,成绩为0到100之间的一个整数,这里保证在一组测试用例中没有两个学生的成绩是相同的。
输出格式:对每个测试用例输出2行,第1行是成绩最高学生的姓名和学号,第2行是成绩最低学生的姓名和学号,字符串间有1空格。
输入样例:
3
Joe Math990112 ... |
c9fd907f7db76ed478ad64875951242b3dcebf0f | whlg0501/2018_PAT | /1049.py | 1,239 | 3.5625 | 4 | """
1049 数列的片段和(20)(20 分)提问
给定一个正数数列,我们可以从中截取任意的连续的几个数,称为片段。例如,给定数列{0.1, 0.2, 0.3, 0.4},我们有(0.1) (0.1, 0.2) (0.1, 0.2, 0.3) (0.1, 0.2, 0.3, 0.4) (0.2) (0.2, 0.3) (0.2, 0.3, 0.4) (0.3) (0.3, 0.4) (0.4) 这10个片段。
给定正整数数列,求出全部片段包含的所有的数之和。如本例中10个片段总和是0.1
0.3 + 0.6 + 1.0 + 0.2 + 0.5 + 0.9 + 0.3 + 0.7 + 0.4 = 5.0。
输入格式... |
23d0b02ba64c2aca3becf467d88c692109aab9f8 | patnaik89/string_python.py | /condition.py | 1,696 | 4.125 | 4 | """
Types of conditional statements:-
comparision operators (==,!=,>,<,<=,>=)
logical operators (and,or,not)
identity operators (is, is not)
membership operators (in, not in) """
x, y = 2,9
print("Adition", x + y)
print("multiplication", x * y)
print("subtraction", x - y)
print("division", x/y)
pr... |
c0bd2b9a856537ea24d75bc6e73ec5396c0a987b | seanjib99/pythonProject14 | /python 1.py | 954 | 4 | 4 | #s.n students take k apples and distribute each student evenly
#The remaining parts remain in the basket.
#How many apples will each single student get?
#How many apples will remain in the basket?The programs read the numbers N and k.
N=int(input("enter the number of students in class")]
K= int(input("enter the numbe... |
59eb59d435bb953bdc73df7a5df3d285dbfd6c93 | cmillecan/holbertonschool-higher_level_programming | /0x01-python-if_else_loops_functions/1-last_digit.py | 460 | 4.03125 | 4 | #!/usr/bin/python3
import random
number = random.randint(-10000, 10000)
last_digit = abs(number) % 10
if number < 0:
last_digit = -last_digit
if last_digit > 5:
print("Last digit of {:d} is {:d} and is greater \
than 5".format(number, last_digit))
elif last_digit == 0:
print("Last digit of {:d} is {:d} and ... |
65ec659dbb339de8bfbfe81ae2556dcc314c8f0c | cmillecan/holbertonschool-higher_level_programming | /0x0B-python-input_output/13-student.py | 816 | 3.875 | 4 | #!/usr/bin/python3
""" Task 13 """
class Student:
"""Defines a student"""
def __init__(self, first_name, last_name, age):
"""
Instantiation
"""
self.first_name = first_name
self.last_name = last_name
self.age = age
def to_json(self, attrs=None):
"""... |
bb204dab03699a3aaa32f558c92fd8fc697449ab | arkkhanu/Final-Project-OCR | /Server/hough_rect.py | 6,941 | 3.609375 | 4 | """
Module for finding a rectangle in the image, using Hough Line Transform.
"""
import itertools
from typing import Union
import numpy as np
import cv2
import matplotlib.pyplot as plt
from scipy.spatial import distance
import consts
def find_hough_rect(img: np.ndarray) -> Union[None, np.ndarray]:
"""
Find ... |
b24585f353af5a15200c7c9ef10d920ed3862fc5 | SuryaDeepthiR/competitive-programming | /competitive-programming/Week2/Day-6/InPlaceShuffle.py | 449 | 3.9375 | 4 | import random
def random_number(floor,ceiling):
return random.randint(floor,ceiling)
def shuffle(the_list):
# Shuffle the input in place
length = len(the_list)
for i in range(0,length-1):
j = random_number(0,length-1)
the_list[i],the_list[j] = the_list[j],the_list[i]
sample_l... |
834612676d77e7be218b1898422ba94fff11196f | liadbiz/Leetcode-Solutions | /src/python/dynamic_programming/minimum-ascii-delete-sum-for-two-strings.py | 1,970 | 3.828125 | 4 | """
Given two strings s1, s2, find the lowest ASCII sum of deleted characters to make two strings equal.
Example 1:
Input: s1 = "sea", s2 = "eat"
Output: 231
Explanation: Deleting "s" from "sea" adds the ASCII value of "s" (115) to the sum.
Deleting "t" from "eat" adds 116 to the sum.
At the end, both strings are equa... |
38ca97cf3452797e9460b01dcf61559d53643669 | liadbiz/Leetcode-Solutions | /src/python/dynamic_programming/number_of_longest_increasing_subsequence.py | 1,446 | 3.984375 | 4 | """
673. Number of Longest Increasing Subsequence
source: https://leetcode-cn.com/problems/number-of-longest-increasing-subsequence/
Given an unsorted array of integers, find the number of longest increasing subsequence.
Example 1:
Input: [1,3,5,4,7]
Output: 2
Explanation: The two longest increasing subsequence are [... |
f21b75948484cc34cea7d9d166dc47e72611749d | liadbiz/Leetcode-Solutions | /src/python/degree_of_array.py | 1,373 | 4.15625 | 4 | """
Given a non-empty array of non-negative integers nums, the degree of this array is defined as the maximum frequency of any one of its elements.
Your task is to find the smallest possible length of a (contiguous) subarray of nums, that has the same degree as nums.
Example 1:
Input: [1, 2, 2, 3, 1]
Output: 2
Explan... |
7859a42286274f9710a439def03707787e93641b | liadbiz/Leetcode-Solutions | /src/python/greedy_algorithm/jump_game_2.py | 2,740 | 3.984375 | 4 | """
Given an array of non-negative integers, you are initially positioned at the first index of the array.
Each element in the array represents your maximum jump length at that position.
Your goal is to reach the last index in the minimum number of jumps.
Example:
Input: [2,3,1,1,4]
Output: 2
Explanation: The minim... |
56ea95418a0ec5e08e1b85a87c7cd257e38754d4 | liadbiz/Leetcode-Solutions | /src/python/dynamic_programming/Palindromic_string.py | 1,191 | 4 | 4 | """
#647 palindromic string
https://leetcode.com/problems/palindromic-substrings/
Given a string, your task is to count how many palindromic substrings in this string.
The substrings with different start indexes or end indexes are counted as different substrings even they consist of same characters.
Example 1:
Inp... |
426bcfbcc836cd23ca4f5e00057781bf180f22e1 | liadbiz/Leetcode-Solutions | /src/python/validate_binary_search_tree.py | 763 | 4.0625 | 4 | """
Given a binary tree, determine if it is a valid binary search tree (BST).
Assume a BST is defined as follows:
The left subtree of a node contains only nodes with keys less than the
node's key.
The right subtree of a node contains only nodes with keys greater than the
node's key.
Both the left ... |
3d6ff3e1c81878b956d537ba48a19df178ee55a5 | liadbiz/Leetcode-Solutions | /src/python/dynamic_programming/mininum_cost_for_tickets.py | 2,204 | 4.0625 | 4 | """
In a country popular for train travel, you have planned some train travelling
one year in advance. The days of the year that you will travel is given as an
array days. Each day is an integer from 1 to 365.
Train tickets are sold in 3 different ways:
+ a 1-day pass is sold for costs[0] dollars;
+ a 7-day pass is... |
498b0478db6e99d4bb321585b4c4fce7f2a9e269 | liadbiz/Leetcode-Solutions | /src/python/largest_common_prefix.py | 3,031 | 4.15625 | 4 | """
description:
Write a function to find the longest common prefix string amongst an array of strings.
If there is no common prefix, return an empty string "".
Example 1:
Input: ["flower","flow","flight"]
Output: "fl"
Example 2:
Input: ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix amo... |
36afe84aaa377106aa8a4eb6706c015a88fa7a49 | liadbiz/Leetcode-Solutions | /src/python/reverse_integer.py | 920 | 3.96875 | 4 | """
Given a 32-bit signed integer, reverse digits of an integer.
Example1:
Input: 123
output: 321
Example2:
Input: -123
Output: -321
Example3:
Input: 120
Output: 21
Notes: what if the result overflow?
what have learned:
1. in python 2, we can use cmp() function to get sign of the difference of two number a an... |
6aac68ffc80dba1f5c76492a7dc37016f632556d | liadbiz/Leetcode-Solutions | /src/python/power_of_four.py | 963 | 4 | 4 | """
Given an integer (signed 32 bits), write a function to check whether it is a power of 4.
Example 1:
Input: 16
Output: true
Example 2:
Input: 5
Output: false
Follow up: Could you solve it without loops/recursion?
"""
class Solution:
def isPowerOfFour(self, num):
"""
:type num: int
:rt... |
8cab006e87d608bdce1899e00044e13f8f09c3f2 | liadbiz/Leetcode-Solutions | /src/python/minimum_moves2.py | 990 | 4.03125 | 4 | """
Given a non-empty integer array, find the minimum number of moves required to make all array elements equal, where a move is incrementing a selected element by 1 or decrementing a selected element by 1.
You may assume the array's length is at most 10,000.
Example:
Input:
[1,2,3]
Output:
2
Explanation:
Only two... |
26715c6de77437da8a9084c3aea2db86910a527d | liadbiz/Leetcode-Solutions | /src/python/greedy_algorithm/split_array_into_consecutive_subsequences.py | 2,647 | 4.09375 | 4 | """
You are given an integer array sorted in ascending order (may contain
duplicates), you need to split them into several subsequences, where each
subsequences consist of at least 3 consecutive integers. Return whether you can
make such a split.
Example 1:
Input: [1,2,3,3,4,5]
Output: True
Explanation:
You can split ... |
49ebb1d0c3806b92ab6c158447171ceca908da42 | liadbiz/Leetcode-Solutions | /src/python/greedy_algorithm/course_schedule_3.py | 2,124 | 3.859375 | 4 | """
There are n different online courses numbered from 1 to n. Each course has some duration(course length) t and closed on dth day. A course should be taken continuously for t days and must be finished before or on the dth day. You will start at the 1st day.
Given n online courses represented by pairs (t,d), your tas... |
893104e3a4ade89aa31e82a18df0695a040fbd9e | liadbiz/Leetcode-Solutions | /src/python/range_sum_query.py | 771 | 3.71875 | 4 | """
# 303
Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive.
Example:
Given nums = [-2, 0, 3, -5, 2, -1]
sumRange(0, 2) -> 1
sumRange(2, 5) -> -1
sumRange(0, 5) -> -3
Note:
You may assume that the array does not change.
There are many calls to sumRange function.
Acc... |
be8da5d6998ab0d7cde8a800612dbabe81830c77 | liadbiz/Leetcode-Solutions | /src/python/onebit_twobit.py | 2,948 | 4.03125 | 4 | """
717. 1-bit and 2-bit Characters
We have two special characters. The first character can be represented by one bit 0. The second character can be represented by two bits (10 or 11).
Now given a string represented by several bits. Return whether the last character must be a one-bit character or not. The given stri... |
04d56f4cfc176ede74a148b901dad5120b4b1270 | Calico888/First-Steps---Quiz | /quiz 2.py | 6,549 | 4.25 | 4 | # Strings for the different difficulties
easy_string = """I have a __1__ that one day this __2__ will rise up, and live out the true meaning of its creed: We hold these truths to be self-evident: that all men are created equal.
Martin Luther King jr
The greatest __3__ in living lies not in never falling, but in __4__... |
a060b33270c6c736e397f22f81ebab6f68b1a4e8 | arcae/git_lesson-1 | /data/portcsv.py | 626 | 3.671875 | 4 | #using csv module
import csv
def portfolio_cost(filename):
'''
Computes total shares*proce for a CSV file with name,shares,price data'
'''
total = 0.0
with open(filename,'r') as f:
rows = csv.reader(f)
headers = next(rows) #skip first row for headers
for rowno, row in enumerate(rows,start=1):
try:
... |
a849d96ef408d998a3ec1b17ce74d6b02f7992ad | saurabhc123/unsupervised | /source/Ops.py | 630 | 4.09375 | 4 | from abc import ABC, abstractmethod
class Ops(ABC):
def __init__(self, name):
self.name = name
pass
@abstractmethod
def perform_op(self):
print ("Performing op:" , self.name)
pass
class Addition(Ops):
def __init__(self, name="Addition"):
Ops.__init__(self, nam... |
9516c757ff8eacaff3edb929e59fc7032610f4f1 | QuinPoley/ChessGame | /pieces.py | 8,000 | 3.703125 | 4 | class Piece:
def __init__(self, color, letter, number):
self.position = letter, number
self.letter = letter
self.number = number
self.color = color
self.hasMoved = False
def returnLegalMoves():
return None
def move(self, letter, number):
firstmov... |
8e03751fb6c7e483d09dec12e3606bef9a443189 | jtbarker/pyocto-wordcounter | /countwordfreq.py | 690 | 4.0625 | 4 | #! /usr/bin/python
""" this program breaks a string into a list of component words
and counts each word, by Jon Barker, 2014-1-7"""
# import matplotlib
# import os
# print(dir(matplotlib))
def main():
print "input a sentence and i will count the words for you"
sentence = str(input("your sentence: "))
main()
... |
d052bdd3529c7c444cbec14bc1fe3ce1ae5b6093 | shaikafiya/pythonprogramming | /pangram.py | 141 | 3.734375 | 4 | s=input()
n=[]
for i in s:
if(i not in n):
n.append(i)
if(len(n)==27 or len(n)==28):
print("yes")
else:
print("no")
|
88f49fdde71ecb4ffcdbe49a889e058190d0feb9 | shaikafiya/pythonprogramming | /even num between two intervals.py | 101 | 3.515625 | 4 | n,m=input().split()
n=int(n)
m=int(m)
for k in range(n+1,m):
if(k%2==0):
print(k,end=" ")
|
359d0387e3684f13ae34726654419d169fb22efb | frankc95/exercise | /workbook_01.py | 140 | 3.796875 | 4 | weight_lbs = input('Weight (lbs): ')
weight_kg = int(weight_lbs) * 0.45
txt = "your weight in kilograms is "
print (txt + str(weight_kg))
|
0194f671da5971a2f30a4df885e6318312f6c172 | jeremysinger/python-forloop-parser | /tests/test3.py | 277 | 4 | 4 |
for i in range(0,10):
for j in range(0,i):
for k in range(i,j):
print(i,j)
for a in range(5):
for b in range(2):
print('foo')
for x in range(a):
for y in range(a-1):
for z in range(y):
print('bar')
|
f9b68289368ca68d3bc557f7e11261c9d8683c79 | mikyqwe/python.py | /firstday.py | 483 | 4.09375 | 4 | """Write a script that writes the day of the week for the New Year Day, for the last x years (x is given as argument)."""
import time
saptamana=["Luni","Marti","Miercuri","Joi","Vineri","Sambata","Duminica"]
def f(x):
date="01-01"
for i in range(1,x+1):
currentYear=2020+1-i
currentdate=date+"-"+str(currentYear)
... |
057a72a1e97177d2266389973837f9edf8b67806 | deepalikushwaha18/SDET-Training-Python | /Activity2.py | 160 | 4.1875 | 4 | num=int(input("enter number:"))
mod = num % 2
if mod > 0:
print("You picked an odd number.")
else:
print("You picked an even number.")
|
5945cce076d47a3dc3f23ed6dad61a3153ae4721 | MarcPartensky/Python-Games | /Game Structure/geometry/version4/myrect.py | 7,466 | 4 | 4 | class Rect:
"""Define a pure and simple rectangle."""
def createFromCorners(corners):
"""Create a rectangle."""
coordonnates=Rect.getCoordonnatesFromCorners(corners)
#print("c:",coordonnates)
return Rect(coordonnates[:2],coordonnates[2:])
def createFromRect(rect):
""... |
e9432b4362be20638c2d72af1fb3a37f3e67c889 | MarcPartensky/Python-Games | /Game Structure/geometry/version5/mysyracuse.py | 1,528 | 3.53125 | 4 | from myabstract import Point,Segment
class Branch:
def __init__(self,n=1,g=0):
"""Create a branch."""
self.n=n
self.g=g
def children(self):
"""Return the childen branches of the branch."""
children=[Branch(self.n*2,self.g+1)]
a=(self.n-1)//3
if a%2==1:
... |
4a25f75e797b7ca5915b7c8689482a6f329a8af1 | MarcPartensky/Python-Games | /Game Structure/geometry/version3/mypoint.py | 6,376 | 4.09375 | 4 | from math import pi,sqrt,atan,cos,sin
import random
mean=lambda x:sum(x)/len(x)
import mycolors
class Point:
def random(min=-1,max=1,radius=0.1,fill=False,color=mycolors.WHITE):
"""Create a random point using optional minimum and maximum."""
x=random.uniform(min,max)
y=random.uniform(min,m... |
7c3ba27c237a61201655c18fd2520838b5215778 | MarcPartensky/Python-Games | /Mandelbrot/mandelbrot1.py | 1,621 | 3.640625 | 4 | import numpy as np
from matplotlib import pyplot as plt
from matplotlib import colors
#%matplotlib inline
settings=[-2.0,0.5,-1.25,1.25,3,3,80]
def mandelbrot(z,maxiter):
c = z
for n in range(maxiter):
if abs(z) > 2:
return n
z = z*z + c
return maxiter
def mandelbrot_set(xmin,... |
237174569b314b5ad7b2df0f9d0cc2bc80a5a3f2 | MarcPartensky/Python-Games | /Game Structure/geometry/version3/myvector.py | 8,935 | 3.71875 | 4 | from mydirection import Direction
from mypoint import Point
from math import cos,sin
from cmath import polar
import mycolors
import random
class Vector:
def random(min=-1,max=1,color=mycolors.WHITE,width=1,arrow=[0.1,0.5]):
"""Create a random vector using optional min and max."""
x=random.uniform... |
e4f909f0ecdf3f3529efe9de530ab31df9e4c1ed | MarcPartensky/Python-Games | /Game Structure/geometry/version4/myabstract.py | 74,221 | 3.9375 | 4 | from math import pi,sqrt,atan,cos,sin
from cmath import polar
from mytools import timer
import math
import random
import mycolors
average=mean=lambda x:sum(x)/len(x)
digits=2 #Number of digits of precision of the objects when displayed
class Point:
"""Representation of a point that can be displayed on screen.""... |
2114723258f1a9a8d3b0281676020098d7629943 | MarcPartensky/Python-Games | /Game Structure/geometry/version5/modulo.py | 1,888 | 3.6875 | 4 | import math
class Modulo:
def __init__(self, n, a=None):
"""'n' is the number, and 'a' is the modulo"""
if a == None:
self.a = float("inf")
else:
self.a = a
self.n = n % self.a
# Type conversions
def __str__(self):
return str(self.n)
de... |
5d304023128714c95e67ec1ed77c8d4f1b3f33a9 | MarcPartensky/Python-Games | /Intersection/myposition.py | 2,382 | 3.546875 | 4 | from math import sqrt,cos,sin
from cmath import polar
from numpy import array,dot
class Position:
base="xyztabcdefhijklmnopqrsuvw"
angle_base="ab"
def __init__(self,*data,base=None,system="cartesian"):
"""Save a position using cartesian coordonnates."""
self.system=system
if self.s... |
6a5961313d688e4136885a19f2cd33e6592ff4cd | LanHikari22/Mutu-chan | /Commands/botcmd.py | 3,002 | 3.765625 | 4 |
class BotCMD:
"""
abstraction class of a bot command. Create this for every command except very fundemental ones
Override methods as necessary.
"""
# execution activation command for when listening for mention commands
command = None
# defined error_code constants
SUCCESS = 0 ... |
58529d86ce20df905e85e7641408699ba48a0aa2 | YpchenLove/py-example | /8-list.py | 416 | 3.765625 | 4 | # l = [1, 2, 3, 4, 5]
# print(l[0])
# print(l[1: 2])
# print(l[-2: -1])
# print(l[:])
# print(l[0:5:2])
l = [1, 2, 1, 1, 3, 4, 5, -1]
l2 = [7, 8, 9]
print(l[-1:]) # [5]
print(l[-1::-1]) # [5, 4, 3, 2, 1]
print(len(l))
print(max(l))
print(min(l))
print(l.count(1))
l.append(88)
print(l)
l.pop()
print(l)
l.rem... |
a4682975b00b3a87be7e293ae844bd921e3d4db7 | zjipsen/chef-scheduler | /chef.py | 652 | 3.6875 | 4 | class Chef:
days_in_week = 5
def __init__(self, name, unavailable=[], since=6, times=0, vacation=False):
self.name = name
self.unavailable = unavailable
self.since = since
self.times = times
self.init_since = since
self.init_times = times
self.vacation =... |
6e9541ca3a2030a5fdcbd1f28d4937afe60ae03e | MeitarEitan/Devops0803 | /1.py | 449 | 3.671875 | 4 | my_first_name = "Meitar"
age = 23
is_male = False
hobbies = ["Ski", "Guitar", "DevOps"]
eyes = ("brown", "blue", "green") # cant change (tuple)
# myself = ["aviel", "buskila", 30, "identig"]
myself = {"first_name": my_first_name, "last_name": "Eitan", "age": age} # dictionary
print("Hello World!")
print(my_first_name... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.