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 |
|---|---|---|---|---|---|---|
0299fb95efbcc4469587cbc52f89a93337b9a661 | cmkobel/sclir | /sclir.py | 2,383 | 3.53125 | 4 |
import sys
import re
import time
import math
import pyperclip
class sclir:
'''
~ Todo ~
* blink ord ved linjeskift?
* keyboard controls
* venstre: Gå en sætning tilbage
* højre: ?
* op/ned: juster hastighed
* q quit
* use curses?
* brug farver
'''
def __init__(self,
wps = 8,
text="No text... |
a0061e1798d815e63d48c4be7536f9fc8cae59c6 | quangthang100793/Visualization-by-Pyspark | /line-3.py | 243 | 3.5 | 4 | import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
from pandas import read_csv
df = read_csv('sales-by-years-1.csv')
print(df)
df.plot(x='years',y='sales',rot=30,title='Sales by Years')
plt.tight_layout()
plt.show() |
67b4a70b626569fecd7eceaf125fd7082dd3c5dd | BenSnowden/random-map-generation | /src/main.py | 1,676 | 3.625 | 4 | from generateMap import make_world
from pygame.locals import *
import pygame
from time import sleep
from PIL import Image
dimension_of_screen = (1000, 800)
"""
dimension of map (x,y) used in map generation and setting the pygame screen size
"""
def init_display():
global screen
screen =... |
f49e8ca3f8df6981038a6a7fc52b518f6c0fa40f | tomi8a/algoritmosyestructuradedatos | /clase1/act1.py | 115 | 3.796875 | 4 | from cmath import pi
r= float(input('ingrese radio del circulo'))
a = pi*r**2
a= round(a,2)
print('el area es',a) |
6cb4981ac678cc3bca8a2d9f19eb6972e08bad81 | tomi8a/algoritmosyestructuradedatos | /CLASE 13/indexacion_numerica_1.py | 960 | 4.1875 | 4 | # Recordemos el manejo de índices y slicing
# con strings
var = 'Algoritmos y estructura de datos'
print('La primera letra es: ' + var[0])
print('La última letra es: ' + var[-1])
print('Las primeras 3 letras son: ' + var[0:3])
print('Las primeras 3 letras son: ' + var[:3])
print('Las últimas 3 letras son: ' + va... |
ba120b4c0dfc1f9fea6a40862649e5fde150e35e | tomi8a/algoritmosyestructuradedatos | /taller repaso/punto4.py | 664 | 3.5 | 4 | import csv
def Departamento(nombreArchivo):
file = open(nombreArchivo,encoding='UTF-8')
lines = csv.DictReader(file,delimiter = ',')
diccdep = {}
listamun = []
i = 0
for aux in lines:
if i == 0:
depante = aux['Departamento']
dep = aux['Departamento']
mun = au... |
da31a7846b4a369419e8c4b8b5f84da1965ee021 | jwu910/Class | /Week1/Problem2.py | 425 | 3.84375 | 4 | # Problem 2
# Python 3.5
# Find how many times 'bob' occurs in the string
# Test string
s = 'slkasjlhwebobal;skdhowubobobalskhe' # 3 appearances
# ----------------------copy below this line -----------------------
total = 0
for l in range(0,len(s)):
while l <= (len(s)-2):
if s[l] == 'b' and s[l+1] == 'o' ... |
bbc9d1d58aa8b5c128632393f874cf502dd674d4 | NathanPbi/python | /ex005.py | 202 | 3.890625 | 4 | number1 = int(input ('Digite primeiro número: '))
number2 = int(input('Digite segundo número: '))
result = int(number1 + number2)
print('A soma entre {} e {} é: {}'.format (number1, number2, result)) |
b6730ad646a8bc0ff0e11254b6e2fdcb83c25e39 | NathanPbi/python | /ex002.py | 93 | 3.5 | 4 | name = input ('Digite o seu nome ')
print('Olá', name, 'como vai?')
R = input ('resposta: ') |
d6e645d7889b9c297a8e238498b0c0bc97e864d3 | claytoncampos/desafios-python-dio | /desafio-02-preenchimento-de-vetor.py | 862 | 3.671875 | 4 | # Desafio 02 - Preenchimento de Vetor
# Você recebeu o desafio de ler um valor e criar um programa que coloque o valor lido na primeira posição de um vetor N[10].
# Em cada posição subsequente, coloque o dobro do valor da posição anterior. Por exemplo, se o valor lido for 1,
# os valores do vetor devem ser 1,2,4,8 e... |
0d1bf03841f8f59757ff8d2f69d1fc140907af4a | prachi182/Python_Assignment1 | /python_training/module9/game1.py | 1,883 | 3.8125 | 4 | import random
from itertools import product
class Card:
suit = ('Hearts', 'Spades', 'Clubs', 'Dimonds')
faces = ('two', 'three', 'four', 'five', 'six', 'seven', 'eight',
'nine', 'ten', 'jack', 'queen', 'king', 'ace')
values = {'two': 2, 'three': 3, 'four': 4, 'five': 5, 'six': 6, 'seven... |
fff4d3bc71a3306226203808c3404d093317eada | TheMaksoo/classlist | /main.py | 958 | 4.0625 | 4 | classList=[{"name":"Bob","number":560292,"email":"bob@example.com"},{"name":"Alice","number":293737,"email":"alice@example.com"},{"name":"Joe","number":127350,"email":"joe@example.com"},{"name":"Rick","number":947463,"email":"rick@example.com"}]
newname= ''
for student in classList:
print(student["name"])
find ... |
92c666f80bf975daafa0b3396e9e6ff22253b710 | jimmo/micropython | /tests/basics/fun_calldblstar4.py | 566 | 3.6875 | 4 | # test calling a function with multiple **args
def f(a, b=None, c=None):
print(a, b, c)
f(**{"a": 1}, **{"b": 2})
f(**{"a": 1}, **{"b": 2}, c=3)
f(**{"a": 1}, b=2, **{"c": 3})
try:
f(1, **{"b": 2}, **{"b": 3})
except TypeError:
print("TypeError")
# test calling a method with multiple **args
class A:... |
c4d376629d684b96efb5a084f0a2e97be6229e2e | nikuthapa/Python-Assignment | /Functions/Question17.py | 168 | 3.90625 | 4 | x = input("Enter string:")
y = input("Enter letter from x value or any other letters: ")
begin_char = lambda a: True if a.startswith(y) else False
print(begin_char(x))
|
358f917f74d9036a9ccc595e68b92c6aa49623a8 | nikuthapa/Python-Assignment | /Functions/Question15.py | 413 | 4.03125 | 4 | list_num = [1, 2, 3, 4 ,5 ,6, 7, 8, 9, 12, 14, 19, 21, 24, 27]
even_number = list(filter(lambda a: a % 2 == 0, list_num))
odd_number = list(filter(lambda a: a % 2 != 0, list_num))
print("Actual list of integers before filter: \n", list_num)
print("\nList filtering with even numbers elements from actual list: \n", even_... |
869f035b3746560f131a26ee9015fed52447aca4 | nikuthapa/Python-Assignment | /Functions/Question13.py | 314 | 3.8125 | 4 | def sort_list_tup (data_list):
data_list.sort(key= lambda a: a[1])
return data_list
data_list = [('Apple', 50), ('Mango', 23), ('Biscuits', 45), ('Orange', 15), ('Pineapple', 33) ]
print("List of tuples before sorting: \n", data_list)
print("\nList of tuples after sorting: \n", sort_list_tup(data_list))
|
a6ec4005fe3c1c871deb5f3206ef3194233413db | idealblack/labs | /utils.py | 10,967 | 3.84375 | 4 | # -*- coding: utf-8 -*-
"""
Some potentially useful functions you can optionally use in your COMP0088
coding assignments.
You are not required to use these functions. If you prefer to write these things
your own way, you are welcome to do so.
"""
import numpy as np
import numpy.random
import matplotlib
import matplo... |
a232a9c5393c12787db2e242b6704b0e4686e233 | talakalo/DevOpsExpertsProject | /MainGame.py | 740 | 3.5 | 4 | from Live import welcome, load_game, get_chosen_game, get_game_difficulty, choose_level
import MemoryGame
import GuessGame
import CurrencyRouletteGame
class MainGame:
welcome(name=input("Please Enter You Name:" + "\n"))
game_number = load_game()
difficulty = choose_level()
if int(game_number) == 1:... |
7f06f59955270d8bc970e23cf798c0d6cd540671 | Mercy435/w3-schools-python | /python while.py | 1,368 | 4.03125 | 4 | i = 1
while i < 6:
print(i)
i += 1 # this prints i as long as it is less than 6
# while loop needs a break else it continues forever
print()
i = 1
while i < 6: # this prints from 1 till 3
print(i)
if (i == 3):
break
i += 1
print()
i = 0 # this prints 1 till 5 but omits the number 3
... |
ecd3af3cacc15e37e062761cb975c67b69101743 | Mercy435/w3-schools-python | /python try....except.py | 899 | 4.0625 | 4 | '''
The try block lets you w3shool a block of code for errors.
The except block lets you handle the error.
The finally block lets you execute code, regardless of the result of the try- and except blocks.
'''
try:
print(x)
except:
print("An exception occurred")
#print(x)
try:
print(x)
except NameError:
prin... |
3ad6e2d4e164f17ff9bc25f4aad746548d138ae4 | shreyasmurthy24/ChatBot | /FinanceHelperBot/obj/Release/Package/PackageTmp/Load_Data.py | 3,234 | 3.53125 | 4 | import sqlite3
import csv
conn = sqlite3.connect('./mysqlite.db')
cur = conn.cursor()
cur.execute('''CREATE TABLE USERS
(USER_ID INT PRIMARY KEY NOT NULL,
User_SEQID TEXT NOT NULL,
User_Name TEXT NOT NULL);''')
reader = csv.reader(open('./users.csv', 'r'), delimiter=',')
next(re... |
4ae134d8385bd4b2d237e62e4e4518367d241c0d | fastscript/PY111-april | /Tests/b0_test_linear_search.py | 617 | 3.515625 | 4 | import unittest
import numpy as np
from Tasks.b0_linear_search import min_search
class MyTestCase(unittest.TestCase):
def test_min(self):
arr = [i for i in range(10)]
self.assertEqual(min_search(arr), min(arr), "Minimal element is wrong, right answer: " + str(min(arr)))
arr = [i for i in range(10, -3, -1)]
... |
5393e9b7e152fe40d8f0c232e71d1c5236f68947 | parlad/PythonExe | /whileLoopsLocal.py | 205 | 3.984375 | 4 | password =''
while password != 'admin':
password = input("enter the password!!")
if password=='admin':
print("you are logged in ")
else :
print("sorrey, Try again")
|
056e35aeda75e05089ce22698aac8fb057ae4ffd | rundongliu/leetcode-python | /Combinations.py | 478 | 3.546875 | 4 | class Solution:
# @return a list of lists of integers
def combine(self, n, k):
res = []
lst = []
self.rec(lst,1,n,k,res)
return res
def rec(self,lst,from_num,n,num_left,res):
if num_left==0:
lst = lst[:]
res.append(lst)
ret... |
b78bdf9e29682f36c175634795ab23eaedffd7f7 | rundongliu/leetcode-python | /Add Two Numbers.py | 758 | 3.6875 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# @return a ListNode
def addTwoNumbers(self, p1, p2):
front = ListNode(0)
p = front
carry = 0
while p1 or p2:
if not ... |
6f03bed6b911205a49cbd0776eb3aba99e22983c | rundongliu/leetcode-python | /Sort List.py | 1,019 | 3.875 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# @param head, a ListNode
# @return a ListNode
def sortList(self, head):
if not head or not head.next:
return head
p = head
... |
593758a986b1e6bb3dbd137ee734a7ae6d682ba9 | ceejtayco/python_starter | /show_stars.py | 239 | 3.890625 | 4 | #Write a function called show_stars(rows). If rows is 5, it should print the following:
# *
# **
# ***
# ****
# *****
def show_stars(limit):
for x in range(1,limit+1):
print('*' * x)
show_stars(int(input('Enter a limit: '))) |
f3b36b0d425a27a84edce61bd93de52c69ec90fe | ceejtayco/python_starter | /longest_strings.py | 455 | 4.125 | 4 | #Given an array of strings, return another array containing all of its longest strings.
def longest_string(inputList):
newList = list()
longest = len(inputList[0])
for x in range(len(inputList)-1):
if longest < len(inputList[x+1]):
longest = len(inputList[x+1])
for x in inputLi... |
eab7db0160e4e7dfc0da0690f114d51b49cbd69a | Haris-HH/CP3-Haris-Heamanunt | /Exercise_5_2_Haris_Heamanunt.py | 262 | 4.28125 | 4 | distance = int(input("Distance (km) : "))
time = int(input("Time (h) : "))
if(distance < 1):
print("Distance can not be less than 1 km")
elif(time < 1):
print("Time can not be less than 1 hour")
else:
result = distance / time
print(result,"km/h") |
50e5ff2058fcd013680a6537382f9842d95ed86a | silverland79/Bezier | /src/bezier.py | 1,180 | 3.65625 | 4 | #!/usr/bin/env python
"""bezier.py: Magical bezier curve generation"""
import math
__author__ = "Wesley Soo-Hoo"
__license__ = "MIT"
def bezier(points, t):
if len(points) == 1:
return points[0]
else:
return (1-t)*bezier(points[:-1], t) + t*bezier(points[1:], t)
if __name__ == '__main__':
... |
e4fe180d9bd2ebf9635b8a83275c88761a0328b6 | Shivamshukla14/Tkinter | /Digital_calculator/digitalCalc.py | 4,651 | 3.546875 | 4 | from tkinter import *
class App(Frame):
def __init__(self,master):
super(App,self).__init__(master)
self.task=""
self.UserIn = StringVar()
self.grid()
self.create_wid()
def create_wid(self):
self.font = ("Helvetica",12,"bold")
self.bg= "light green"
... |
5ab394824aeefc95b70186b496dce4fce9665566 | tschoi6712/doItPandas | /code/ch4-2.matplotlib.py | 2,254 | 3.796875 | 4 | """
Matplotlib is a Python 2D plotting library
: https://matplotlib.org
"""
### 04-2 Matplotlib 라이브러리 자유자재로 사용하기
# 기초 그래프 그리기 ― 히스토그램, 산점도, 박스 그래프
import seaborn as sns
import matplotlib.pyplot as plt
"""
tips 데이터 집합 - 식당에서 팁을 지불한 손님의 정보
- total_bill, tip, sex, smoker, day, time, size(인원수)
"""
tips =... |
a35579071e4898f68cd56d9173daa3b5c6ec903e | csfulop/sicp_python | /ramanujan_generator.py | 1,700 | 3.5 | 4 | """
Solution with recursive python generator for SICP exercise 3.71
This is the fastest one.
There are two other versions:
-one in ch35_streams.py based on streams
-one in ramanujan.py which is a naive implementation and checks every int
"""
import itertools
def integers_from(n):
while True:
yield n
... |
bc6025f53053e894e6040e174f5737b564ec5c9e | myron-z-zhang/machine_learn | /re_maxmatch.py | 4,332 | 3.5625 | 4 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
import os
import string
import random
import math
import sys
def main():
#reload(sys)
#sys.setdefaultencoding('utf-8')
#sys.setdefaultdecoding('utf-8')
#create an list for storage all file'words
words = []
newsclass = ['auto','business','sports']
del_estr = string.... |
e069267305c2f21c0ae83503a1a18236043ef848 | davidfic-testing/save-spend-share | /save_spend_share/database.py | 545 | 3.9375 | 4 | import sqlite3
from sqlite3 import Error
db_name = 'sss.db'
def connect_to_db():
""" connects to sqlite db specified as `db`
and returns a cursor to it
"""
try:
conn = sqlite3.connect(db_name)
c = conn.cursor()
return c
except Error as e:
print(e)
def get_k... |
647ee6960b3d2473089ba25ebf603486ecd9baf0 | jeremietd/Assessment | /QuestionAnswer.py | 767 | 3.515625 | 4 | import json
from random import randint
def load_json():
with open('./sample.json') as f:
data = json.load(f)
return data
def generator(data):
question_num = len(data)
no = randint(0, question_num - 1)
# Indexing
q = list(data.keys())[no]
answer = data[q][0]['answer']
opt... |
d3b8d719e27d137f9b017b6d36904eb5cd068c5f | mdmyr/Python-Project | /Classes/Python_001/RevisionFolder/March06.py | 221 | 3.96875 | 4 |
#Lets create a simple class and use this class in other class .
def printer(input):
#takes in the input and prints on the screen and returns to the caller.
print(':: You have entered this ::')
print(input)
|
5b88fa1471ac7232570a9e1d6eb7f2f16dafcc6e | trite/tritepython | /TriteEulerPython/Problems 001-025/Problem002.py | 519 | 3.859375 | 4 | print('''
Each new term in the Fibonacci sequence is generated by adding the previous two terms.
By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose values do not exceed four million,
find the sum of the even-valu... |
6567abd350ecaba02243a84e7e8812cfb9e206d4 | DonMarik/flask_hello_world | /hello_world.py | 795 | 3.609375 | 4 | from flask import Flask
app = Flask(__name__)
@app.route("/hello")
def say_hi():
return "Hello World!"
@app.route("/hello/<name>")
def hello_person(name):
html = """
<h1>
Hello {}!
</h1>
<p>
Here's a picture of a kitten. Awww...
</p>
<img src="http://placekitten.com/g/200/300">
... |
420c9af7d599e9b735059991967a1129f05ebdd5 | HorseSF/pp_Python | /sample/08_break.py | 80 | 3.703125 | 4 | # break 结束循环
n=1
while n<5:
if n==3:
break
n+=1
print(n) |
b71674d73888fd96399b939c824f748e78d65eec | HorseSF/pp_Python | /sample/07_while_for.py | 162 | 3.921875 | 4 | # while循环
# 1+2+3...+10
n=1
sum=0
while n<=10:
sum=sum+n
n+=1
print(sum)
# for循环
# 1+2+3...+10
sum=0
for x in range(11):
sum=sum+x
print(sum) |
c1d96deff7119ed62538cfd4ea5c63e5e85262c6 | yurmor/nameit | /examples.py | 1,796 | 3.671875 | 4 | from nameit import Nameit
import requests
import bs4
from bs4 import BeautifulSoup
from collections import Counter
if __name__=='__main__':
# Let's look on list of Nobel Laureates in Physics
ref = 'https://www.nobelprize.org/prizes/uncategorized/all-nobel-prizes-in-physics/'
# obtain the page to work with
... |
b91c12557a48056ba55735c132ec54210168f3ad | Astromax/Rosalind_scripts | /Rosalind Finding a Motif in DNA.py | 2,278 | 3.984375 | 4 | #!/usr/bin/env python
# coding: utf-8
# Given two strings s and t, t is a substring of s if t is contained as a contiguous collection of symbols in s (as a result, t must be no longer than s).
#
# The position of a symbol in a string is the total number of symbols found to its left, including itself (e.g., the positi... |
383cd867c393b32c6655c8c5bfbbd8baba60ad6a | LeilaRzazade/python_projects | /guess_number.py | 802 | 4.1875 | 4 | #This is random number generator program.
#You should guess the random generated number.
import random
random_num = random.randint(1,100)
user_input = int(input("Guess the number: "))
if (user_input == random_num):
print("Congratulations! Guessed number is: ", user_input)
while(user_input != random_num):
... |
1a1bc29064fa0af88324ebe48326b70f181a8c8e | nafanh/Starting-out-with-python-4th-editionv2 | /Ch 7/Lo Shu magic square.py | 871 | 3.515625 | 4 | # def magic_sq(square):
# for row in range(len(square)):
# total = 0
# for col in range(len(square)):
# total += square[row][col]
#
a = [[4,9,2],[3,5,7],[8,1,6]]
def magic_square(a):
for row in range(len(a)):
total_r = 0
for col in range(len(a)):
total_r +... |
b7e78275f30e927620c70b375b195608924f41f5 | nafanh/Starting-out-with-python-4th-editionv2 | /Ch 7/Name Search.py | 796 | 3.6875 | 4 | def get_gnames():
infile = open('GirlNames.txt','r')
gnames = infile.readlines()
for i in range(len(gnames)):
gnames[i] = gnames[i].rstrip('\n')
infile.close()
return gnames
def get_bnames():
infile = open('BoyNames.txt','r')
bnames = infile.readlines()
for i in range(len(bnames... |
21bcddbf837defc17af79ee24100ad51c09501e8 | Omkar-97/linked_list | /single_list.py | 2,783 | 3.9375 | 4 | class Node:
def __init__(self, data, next_node=None):
self.data = data
self.next_node = next_node
def get_data(self):
return self.data
def set_data(self, val):
self.data = val
def get_next_node(self):
return self.next_node
class LinkedList:
def __init__... |
ec35a381564362fcb7edfdfc841f16b64edb7b22 | legrandp/xdsme | /XOconv/pycgtypes/vec3.py | 14,507 | 4.34375 | 4 | #####################################################################
# vec3 - 3-dimensional vector
#
# Copyright (C) 2002, Matthias Baas (baas@ira.uka.de)
#
# You may distribute under the terms of the BSD license, as
# specified in the file license.txt.
##########################################################... |
4f8686f815a0f47d40b96cd5d9f6491d490a6159 | jlast35/hello | /python/data_structures/queue.py | 1,905 | 4.34375 | 4 | #! /usr/bin/env python
# Implementation of a Queue data structure
# Adds a few non-essential convenience functions
# Specifically, this is a node intended for a queue
class Node:
def __init__(self, value):
self.value = value
self.nextNode = None
class Queue:
def __init__(self):
self.head = None
self.tail =... |
19ddf024888165c182eb013b15db5bed4e789528 | jlast35/hello | /python/download_file/download_file.py | 510 | 3.625 | 4 | #!/usr/bin/env python
import urllib2
url_of_file_to_download = "http://ia.media-imdb.com/images/M/MV5BMTkxNDYxOTA4M15BMl5BanBnXkFtZTgwNTk0NzQxMTE@._V1__SX1377_SY720_.jpg"
image_file = urllib2.urlopen(url_of_file_to_download)
output_file = open("matrix.jpg","wb")
output_file.write(image_file.read())
output_file.clos... |
c071ba07ff7f8d96f75e324ace2deba1cc7be3f6 | jlast35/hello | /python/data_types/numbers.py | 2,708 | 3.90625 | 4 | #numeric types - int, long, float, complex
#real types - int, long, float
#integer types - int, long
#there are also rational and integral number types apparently...
#you may not use most of these ever except int and float for basic math
#just be aware that other types do exist, and research the documentation as need... |
3e050d6106b4233df2d4da740532be297a806218 | jlast35/hello | /python/data_types/dictionaries.py | 3,111 | 4.28125 | 4 | d = {} #create an empty dictionary
d = dict() #cast an empty dictionary from nothing
d = {'a': 1, 'b': 1} #initialize a dictionary from literals
d2 = dict([('x',1), ('y',2)]) #cast a dictionary from a list if 2-tuples
print d2
d2 = dict(qa=1,r='arr',s=3) #this form only works if the keys given are strings
print d2
... |
a85ed45ab1cca024eaa0f2bd8045e990e82546f0 | VCoyote/CS440-War-Game | /game_board.py | 4,463 | 3.71875 | 4 | '''
Created on Oct 29, 2012
@author: Dan Pang
'''
'''
# Board class
# board: A 2D array of tuples, where the first number is the point value
# and the second number is the player that holds the space.
# open: A list of open spaces, implemented as a dictionary
# taken... |
5b89a2fafc10a83cb443a84c031d2865fa84ba43 | Ryang20718/Zillow-Scrape | /readlistings.py | 172 | 3.59375 | 4 | import csv
f = open('redfin.csv')
csv_f = csv.reader(f)
for row in csv_f:
for col in range(len(row)):
if(col <= 13 and col >=6 ):
print(row[col]) |
f3a4ec59541cf2fcb2f2d93771e3ecba8c80b9dd | RoseBL/web_crawler | /5_1_selenium引入概述.py | 2,377 | 3.796875 | 4 | """
selenium:自动化测试工具
可以打开浏览器,然后像人一样去操作浏览器
可以从selenium中直接提取网页上的各种信息
环境搭建:
1.pip install selenium -i 清华源
2.下载浏览器驱动https://npm.taobao.org/mirrors/chromedriver,根据自己浏览器的版本选择
3.把解压的浏览器驱动,chromedriver放在python解释权所在的文件夹下
"""
# 让selenium启动谷歌浏览器
from selenium.webdriver import Chrome
# 用于模拟键盘输入
from selenium.webdriver... |
c2aac0fe8b972fa6095b137abfe710245b0b2e4b | RoseBL/web_crawler | /4_2_多线程.py | 795 | 4.03125 | 4 | from threading import Thread # 线程类
# 第一种写法:基于函数
# def func():
#
# for i in range(100):
# print("func", i)
#
#
# if __name__ == '__main__':
# t = Thread(target=func,args=("周杰伦",)) # 创建线程并给线程安排任务,传递参数必须是元祖
# t.start() # 多线程状态为可以开始工作状态,具体的执行时间由CPU决定
# for i in range(100):
# print("mai... |
9f23d98304305c4b565ffcdab6620b862f4d6fb3 | LaelaAnggraeni/Bootcamp | /coba5.py | 205 | 3.75 | 4 | username: input("Masukan username")
password: input("Masukan password")
while(username!="username" and password!="password")
print("sorry username and password incorrect please re-enter for validation") |
289151b0c7ad3b92cebe5932531c61ee5fec6d04 | LaelaAnggraeni/Bootcamp | /coba7.py | 943 | 4.0625 | 4 | users = {}
status = ""
while status != "q":
status = raw_input("Are you a registered user? y/n? Press q to quit: ")
if status == "n": #create new login
createLogin = raw_input("Create login name: ")
if createLogin in users: # check if login name exist in the dictionary
... |
309aa5d472dced6856fc6d42748b84153de0b221 | Lakhanbukkawar/Test5_Corrections | /question_10.py | 51 | 3.9375 | 4 | list1 = [3,4,5,20,5,25,1,3]
print(list1.reverse())
|
4507a1216b2b5b6d8213131b95d4d5f55f87fcfe | ntcho/Sunrin2017 | /Software/Web Programming/Project10/ex_turtle_01.py | 468 | 3.59375 | 4 | import turtle
turtle.speed(5)
for i in range(6):
# hexagon draw
turtle.forward(50)
turtle.left(60)
turtle.penup()
turtle.setx(-100)
turtle.sety(0)
turtle.pendown()
for i in range(5):
turtle.forward(50)
turtle.left(108 + 36)
turtle.penup()
turtle.setx(100)
turtle.sety(0)
turtle.pendown()
for i ... |
e41d18fff27f1d412c19c3767b26af6b9d01afc1 | ntcho/Sunrin2017 | /Software/Web Programming/Project05/exercise.py | 481 | 3.890625 | 4 | # Chapter 6
# Exercise 6.1
def problem1():
print ("Problem 1 [Revert string]")
input_string = raw_input("Input string : ")
index = len(input_string) - 1
output_string = ""
while index >= 0:
output_string += (input_string[index])
index -= 1
print output_string
def problem2():
... |
519afbabca9ec3e7c08a14ab2b21d52e23310316 | ntcho/Sunrin2017 | /Software/Web Programming/Project07/exam_05.py | 286 | 3.71875 | 4 | array = [-10.6, 0, 1, 18, 23.6, 45, 63, 86.1]
input_number = float(input("Enter number: "))
if array.index(input_number) >= 0:
print str(input_number) + " is in room number " + str(array.index(input_number) + 1)
else:
print str(input_number) + " is not in any of those rooms!"
|
bd2a8bba022aed1dbb8b891db7df699b34f11f3d | chandana341/chandana520 | /days.py | 88 | 3.890625 | 4 | c=str(input())
if(c=="Sunday" or c=="Saturday"):
print("yes")
else:
print("no")
|
01c0c3ec06a133189dc7dde2774bdb06a683663f | Rongchangle/My_pytorch_tutorial | /data_load_and_process/creat_landmark_dataset.py | 1,782 | 3.5 | 4 | """Create a sample face landmarks dataset.
Adapted from dlib/python_examples/face_landmark_detection.py
See this file for more explanation.
Download a trained facial shape predictor from:
http://dlib.net/files/shape_predictor_68_face_landmarks.dat.bz2
"""
import dlib
import glob
import csv
from skimage import io
... |
6ee1802591df7ab4f3449c0bc7f303cc3d795fd7 | YuliiaAntonova/leetcode | /height_checker.py | 437 | 3.828125 | 4 | class Solution:
def heightChecker(self, heights):
sorted_list = sorted(heights)
count=0
for i in range(len(heights)):
if heights[i] != sorted_list[i]:
count += 1
return count
if __name__ == '__main__':
solution = Solution()
print(solution.heightCh... |
6e23154d95be339c11d9b5e3e2b1484c6a6d8c03 | YuliiaAntonova/leetcode | /find_the_highest_altitude.py | 505 | 3.859375 | 4 | # Input: gain = [-5,1,5,0,-7]
# Output: 1
# Explanation: The altitudes are [0,-5,-4,1,1,-6]. The highest is 1.
class Solution:
def largestAltitude(self, gain):
res = [0] # created list res
for i in range(len(gain)):
res.append(res[i]+gain[i]) # add to new li... |
2bb03b26a4554f78c897815138c6bf675ddfe96e | YuliiaAntonova/leetcode | /reverse integer.py | 786 | 4.125 | 4 | # Given a signed 32-bit integer x, return x with its digits reversed.
# If reversing x causes the value to go outside the signed 32-bit integer range [-231, 231 - 1], then return 0.
class Solution(object):
def reverse(self,n):
y = str(abs(n)) # Create a variable and convert the integer into a string
... |
63f154344a6c0dcd0b5cbc57c9bd366b83435d6f | YuliiaAntonova/leetcode | /merge_strings_alternatery.py | 722 | 4.03125 | 4 | # You are given two strings word1 and word2. Merge the strings by adding letters in alternating order, starting with word1. If a string is longer than the other, append the additional letters onto the end of the merged string.
#
# Return the merged string.
class Solution:
def mergeAlternately(self, word1, word2):
... |
22e01cb295e1bd44afd60af23f8e06c256f7a77d | gsuss27/modulo-2 | /sumatodos.py | 393 | 3.515625 | 4 | def normal(x):
return x
def cuadrado(x):
return x*x
def sumaTodos(limitTo, f):
resultado=0
for i in range (0, limitTo+1): #llega solo hasta limitto x eso se pone mas 1 (el ultimo no lo cuenta)
resultado+=f(i) #busca el primer i y lo mete en la funcion y el valor que le da le suma
return ... |
24e52d0b6c4f1246043822c429a7568773c7e531 | zeddinarief/pemjar | /googlebooks.py | 535 | 3.515625 | 4 | import urllib.request, json
isbn = input("isbn number : ")
api_key = "AIzaSyAqd-hGvKYCUu4ueaLKo9dVFt65pJ2zOYg"
with urllib.request.urlopen("https://www.googleapis.com/books/v1/volumes?q=isbn:"+isbn+"&key="+api_key) as url:
data = json.loads(url.read())
print("judul : "+data["items"][0]["volumeInfo"]["title"])... |
73da38df798ccf3fec7a3143415f61b75a487f85 | urbaneriver426/binary-tree | /binary_tree.py | 4,391 | 3.609375 | 4 | class BSTNode:
def __init__(self, key, val, parent):
self.NodeKey = key
self.NodeValue = val
self.Parent = parent
self.LeftChild = None
self.RightChild = None
def GetLeftChild(self):
return node.LeftChild
def GetRightChild(self):
return self.RightChild
def GetValue(self):
return self.NodeV... |
f37738d19fcf4a17a14b4d9e3728b8a0c277c1a1 | aaronn18120/OBHS-2.7-practice-internal-ANelson | /Samwitch shop excellence 2 1-9-21.py | 4,475 | 4.3125 | 4 | #create a subrountine for the breadtype
from datetime import date
today = date.today()
print("Today's date:", today)
#this function checks if the user name is vaild
def force_name(message, lower, upper):
while True:
name= str(input(message)).title()
if len(name) >=lower and len(name) <=u... |
74379d8f9ec577e8fb766bc4465b142598189d4d | thieu1995/machine_learning | /6_google_trace/tensorflow/exam3.py | 1,619 | 3.703125 | 4 | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Sat Jan 13 13:51:27 2018
@author: thieunv
1. Class methods and static methods (https://www.youtube.com/watch?v=rq8cL2XMM5M)
"""
class Employee:
# class variable
num_of_emps = 0
raise_amount = 1.04
def __init__(self, first, last, pay)... |
63f2dcbea5aedb09a471902b3d5233284e38b09b | tbd5675/CS1Fall2017 | /word_play.py | 1,308 | 3.71875 | 4 | """
Tate Dyer
HW5
"""
def check_deletions(word, file):
check=""
counter=0
word=word.lower()
for line in file:
new_word=line.strip()
for i in range (0,len(word)):
for j in range (0, len(word)):
if word[i]==word[i-1]:
break
... |
96c3826319c7590389735f44667628b0db3c4e78 | tbd5675/CS1Fall2017 | /muddle.py | 1,817 | 3.9375 | 4 | """
Tate Dyer
Lab 5
"""
import string
"""
constant function that can be changed to have a different number of rotations
"""
def CHANGE():
return 11
"""
Function that checks if file is a mud file or a txt file and determines the action that can be taken for each.
"""
def check_suffix(file):
i... |
b8e37a18cbc1329e85639c104d9276c3223bb344 | peteyb37/PeteyBuddsMedium | /SudokuSolver.py | 3,876 | 3.84375 | 4 |
initList = ['1', '2', '3', '4', '5', '6', '7', '8', '9']
allSquares = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I']
spaces = {}
squares = {}
def initSpaces():
print("Enter number of spots to be filled: \n")
num = input()
print("Enter spaces to be filled: (Use: <spot> <value>)(Example: A4,2): \n")... |
ea54898a431e20a4ef16ab56c42c1aaa1d1f1032 | ksonuraj1/Python-projects-for-software-developer | /Tic-Tack-Toe/Tic-Tack-Toe.py | 10,237 | 4.3125 | 4 | def welcome_players():
player1 = ''
# player2 = ''
player1_name, player2_name = '', ''
player_dict = {}
# shows welcome screen
print("\nWelcome to Tic Tac Toe!\n")
while len(player1_name) <= 0:
player1_name = input("Player 1, what is your name?: \n")
if l... |
f85989960291e12d48cef2f4b56bf5efed9319d8 | Neloh/language-classifier | /scraper/get_data.py | 5,570 | 3.71875 | 4 | """
This module exposes two objects. The first is GetArticles which can be used to grab data
from Wikipedia. This scraper also performs basic document sanitizing, such as removing
punctuation, HTML tags, and citation brackets. I recommend scraping less than 100 articles
per API call. The second object, Database, create... |
29a891c4b6e33cdc6dcbc0d8a17345d08990f332 | zhaozongzhao/learngit | /arithmeticstudent/paint/pentagram_v4.0.py | 1,877 | 4.21875 | 4 | ''''
作者:赵宗召
功能:绘制五角星
版本:v3.0
时间:2017.11.19
功能:turtle库常用函数
V1.1 新增功能:使用循环画五角星
v1.2 将画五角星封装成函数
V2.0 设置画笔的颜色和宽度
V3.0 循环和函数的结合,递归
v4.0 树形图
'''
import turtle
def tree_pentagram(distance):
if distance > 5:
# 绘制右侧树枝
if distance < 20:
turtle.pencolor("green")
... |
32ef3ab78641baf26167ab94d0548e62b6c1bde8 | zhaozongzhao/learngit | /Basic_grammar/数据库学习/sqlite(创建掺入).py | 460 | 3.765625 | 4 | import sqlite3
#连接数据库
coon = sqlite3.connect('test1.db')
#创建一个cursor
cursor = coon.cursor()
#执行一个数据sql,创建user表
cursor.execute('create table user(id varchar(20) primary key , name varchar(20))')
#执行插入语句
cursor.execute('insert into user(id,name) values (\'1\',\'TOM\')')
#获取插入的行数
print(cursor.rowcount)
#关闭cursor
c... |
e95a5e64da8f08ecedc664ea8d7781315e437941 | zhaozongzhao/learngit | /arithmeticstudent/savemoney/money_challenge3.0.py | 1,213 | 3.9375 | 4 | '''
作者:赵宗召
时间 2017/11/12
功能52周存钱计划
增加功能:是用户能查询每周的存款金额
'''
import math
def money_inqure(list,week):
saving_week_money=list[week-1]
print(saving_week_money+10)
def count(money_per_week,total_week,increase_money):
money_list = []
# while i<=total_week:
for i in range(total_week):
# 更新账... |
b30baf94720713a95257cae99da1d3439b836dff | zhaozongzhao/learngit | /Basic_grammar/进程线程学习/多线程修改变量.py | 1,186 | 4.09375 | 4 | #python中多线程编程,模型复杂,容易发生冲突,必须用锁加以隔离,同时,又要小心死锁的发生。
#Python解释器由于设计时有GIL全局锁,导致了多线程无法利用多核。多线程的并发在Python中就是一个美丽的梦
# 多线程和多进程最大的不同在于,多进程中,同一个变量,各自有一份拷贝存在于每个进程中,互不影响,而多线程中,
# 所有变量都由所有线程共享,所以,任何一个变量都可以被任何一个线程修改,因此,线程之间共享数据最大的危险在于
# 多个线程同时改一个变量,把内容给改乱了。
import time,threading
#毛毛的银行存款
balance = 0
lock = threading.Lock()
def ... |
6a478246b34c7ea9bf21dcc217a148c868c81fbc | zhaozongzhao/learngit | /Basic_grammar/实例练习/hellword.py | 573 | 4 | 4 | #记录输入两个数之和
import cmath
class us():
#计算输入两个数之和
def us2(self,x,y):
return float(x)+float(y)
#计算一元二次方程
def us3(self,a,b,c):
d = (b**2)-4*a*b
if d>=0:
x1 = (-b-d/(2*a))
x2 = (-b+d/(2*a))
return x1,x2
else:
... |
bb16855470675b979f7399f4a6857caee10cd401 | zhaozongzhao/learngit | /Basic_grammar/日期和时间/datetime验证.py | 528 | 3.59375 | 4 | from datetime import datetime
now = datetime.now()
print(now)
print(type(now))
#获取指定日期和时间
dt = datetime(2015,4,19,12,20) #用指定的日期时间创建
print(dt)
print(dt.timestamp()) #datatime转换为timestamp
#将timestamp转换datetime,使用datatime提供的fromtimestamp()
import time
t = time.time()
print(datetime.fromtimestamp(t))
#字符串转换为datetime... |
f5243dd7f99ecd12d7f92f8fedf04d497503e881 | zhaozongzhao/learngit | /arithmeticstudent/data/whitch_day_1.0.py | 891 | 3.984375 | 4 | '''
作者: 赵宗召
时间:2017/11/26
功能:输入某年某月某日,判断这是一年的第几天
'''
from datetime import datetime
def main():
''''
主函数
'''
input_str_date = input('请输入某年某月某日 YY/MM/DD:')
inpur_date = datetime.strptime(input_str_date,format('%Y/%m/%d'))
#获取年月日Sublime Text)
year = inpur_date.year
month = inpur_date.mo... |
c6348dc08efc398ffa00482beb49d6fa192abcd6 | zhaozongzhao/learngit | /arithmeticstudent/exchange/exchange_v1.1.py | 642 | 3.984375 | 4 | ''' 汇率计算
作者: 赵宗召
版本:v1.1
'''
#汇率
USD_VS_RMB = 6.77#大写的参数表示不会轻易改变
kind_str_value = input('请选择货币种类 :1.人民币 2.美金')
if kind_str_value=='1':
rmb_str_value = input('请输入人民币金额:')
rmb_value = eval(rmb_str_value)#将string转化为数字
usd_value = rmb_value / USD_VS_RMB#汇率计算
print('美元金额: ' , usd_value)
elif ki... |
db75ca21b0c3893afc49eb487036a63d61d6529b | zhaozongzhao/learngit | /Basic_grammar/string/string2.py | 553 | 3.96875 | 4 | #python字符串内建函数
str = 'hello'
print(str.capitalize()) #将字符串的第一个字母变成大写
print(str.center(20,'*')) #返回一个原字符串居中,使用元素填充,默认填充字符是空格
print(str.count('o')) #查询字符在字符串中出现的次数
print(str.find('h')) # 查询字符串中是否包含元素
name = ['adam', 'LISA', 'barT']
#map函数使用
def normailze(x):
str = x.capitalize()
return str
h = list(map(... |
46afadff2594b85d500c22823e02457bea7c5070 | SpyderLord/TensorFlow_Learning | /TensorFlow_Actions/Acion1.py | 2,405 | 4.09375 | 4 | import tensorflow as tf
import numpy as np
# import input_data
from tensorflow.examples.tutorials.mnist import input_data
mnist=input_data.read_data_sets("/home/spyder/TensorFlow_Learning/TensorFlow_Actions/MNIST_data/",one_hot=True)
# from mnist import read_data_sets
# mnist=read_data_sets("/home/spyder/TensorFlow_Le... |
cc54a0283f674a4091d9d3a26f3b70459245119e | JaffarA/ptut | /python-4.py | 1,626 | 4.4375 | 4 | # introduction to python
# 4 - io, loops & functions cont..
# functions can take multiple arguments, default arguments and even optional arguments (part of *args)
def introduce(name='slim shady', age, hobby='fishing'):
return print(f'Hi, my name is {name}. Hi, my age is {age}. Hi, i like this "{hobby}"')
# this code... |
93d4dc0260e121e474e97c535637d639542047d3 | spijs/Capita | /Constraint/scripts/preprocess.py | 2,813 | 3.640625 | 4 | __author__ = "Wout & Thijs"
import csv
from datetime import *
import math
def load_prices(filename):
'''
Load a given csv file into memory
:param filename: file to be loaded
:return: list containing the data from the file
'''
data = []
with open(filename) as csvfile:
reader = csv... |
752902e03b1ef58fb89269326592e5f947aedc70 | spijs/Capita | /Solution.py | 2,250 | 3.546875 | 4 | import numpy as np
import Logger
from time import *
class Solution:
def __init__(self, employees):
self.employees = employees
def to_string(self):
return str(self.employees)
'''
Return the relative cost of this solution. This is based on the optimal cost
'''
def get_cost(self,... |
f582182fa22bf30ac920cdee3ba00af34f605301 | TheGuardianWolf/tellmefacts | /client/client/services/events.py | 1,213 | 3.609375 | 4 | from threading import Event
from queue import Queue
class DataEvent(Event):
"""
Represents an event that is optionally associated with data (like a
message).
"""
def __init__(self, type):
super(DataEvent, self).__init__()
self.type = type
self.data = Queue()
class EventMa... |
50cf68578be78a3317b50985a6ac58e5b7630795 | teekwak/codefights | /interviewPractice/python/arrays/first_duplicate.py | 669 | 3.734375 | 4 | def first_duplicate(a):
seen = set()
unique = [num for num in a if num in seen or seen.add(num)]
return unique[0] if len(unique) > 0 else -1
if __name__ == '__main__':
print(first_duplicate([2, 3, 3, 1, 5, 2]) == 3)
print(first_duplicate([2, 4, 3, 5, 1]) == -1)
print(first_duplicate([1]) == -1)
print(first_dupl... |
07899e72ed5eb012e3734e2bd01b0afd3dc4e698 | karenlopez-13/Curso-de-Python-main | /funcionEjecucion.py | 1,038 | 4.1875 | 4 | #Metodos especiales y cuando hay 1 o 2 guiones bajos son metodos privados
nombre = "Karen Lopez"
print("Primero")
print(nombre[2:4:2])
#strip quita los espacios de una cadena de texto ejemplo: "blusa azul" pasa a "blusaazul"
#no jalo el strip así que pusimos en su lugar "replace"
#lower lo hace minuscula
def valida_pa... |
bff292a49a88f3beb29f8feff77797093209b23e | avi-01/BITW_ASSIGNMENT | /python/Q9_merge_sort.py | 905 | 3.9375 | 4 | def merge(a,l,h):
mid = int((l+h-1)/2)
print(l,h,mid)
i = l
j = mid+1
temp = []
while i<=mid or j<=h:
print(i,j)
if j>h:
temp.append(a[i])
i += 1
elif i>mid:
temp.append(a[j])
j += 1
elif a[i]>a[j]:
temp... |
f70c3e4378f9b11df45bfd76058b4723075d34b1 | ekcaroline/all-python | /pythonprojects/project3-creditcard.py | 1,966 | 3.953125 | 4 | def is_valid_CC(creditnum):
if not creditnum.isdecimal():
return False
if len(creditnum) < 12 or len(creditnum) > 17:
return False
if creditnum[0] == 4 or creditnum[0] == 5 or creditnum[0] == 37:
return False
#luhns algorithm
totalone = 0
for digit i... |
958eb66236948a31b7e9d8233666cced8aad46fa | ekcaroline/all-python | /pythonlabs/lab1a.py | 119 | 3.75 | 4 | t = 2
height = -16*pow(t, 2) + 53*t + 5
print("The height of the ball after 2 seconds is ", height, " ft.", sep="")
|
9e31cc0550152d786872efcbacca450240595b17 | ekcaroline/all-python | /pythonlabs/lab2b.py | 180 | 4.09375 | 4 | int_inch = int(input("Enter a measurement in inches: "))
float_inch = float(int_inch)
new_cm = float_inch * 2.54
print(float_inch, "inches is equal to", new_cm, "centimeters")
|
f45d55e7d4a63bd22af1db6778c3bf5ff02b389d | mlin1025/pismart_ros | /scripts/pismart/led.py | 2,092 | 3.5 | 4 | from basic import _Basic_class
from pwm import PWM
class LED(PWM):
Led1 = 9
Led2 = 8
BRIGHT = 75
RUNING = 30
DIMING = 5
OFF = 0
LED_PIN = {'led1':9, 'led2':8}
LED_GRP = {9:'LED.LED1', 8:'LED.LED2'}
BRIGHT_X = 100 #h... |
8eaec24f8915619b706fe273f9784f68eb11e637 | aquatix/python-utilkit | /utilkit/fileutil.py | 3,800 | 3.5625 | 4 | """
File/directory helper functions
Copying of file trees, creating directories, reading files and more
"""
import os
import datetime
import shutil
from collections import OrderedDict
def copytree(src, dst, symlinks=False, ignore=None, rename=None):
"""
Copy a tree of files and dirs and merge into existing di... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.