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
58eaa6b048e32a21d784ed1fc2d682669c17bb49
SectumPsempra/scraping
/news_scrape_clean.py
2,950
3.546875
4
import requests import bs4 text= "fishing dispute in south china sea" result_per_page = 10 # The area specific url uses google china(asian)/us domain, this is based on # the fact that if you are based out of a certain location, google will show # results specific to that location first asian_url = f"https://google....
1100e78bf96b1e19d6b73917eb9138392f25333b
mwong510ca/Learning
/python/MOOC UM/hw13.1.py
490
3.515625
4
import urllib import xml.etree.ElementTree as ET from BeautifulSoup import * url = "http://python-data.dr-chuck.net/comments_271023.xml" #raw_input('Enter URL: ') html = urllib.urlopen(url).read() soup = BeautifulSoup(html) data = urllib.urlopen(url).read() tree = ET.fromstring(data) results = tree.findall('comments...
649e95f974abdcdbb63709df56b18dd95568dcfd
Ganeshatmuri/sortingvalues
/linearsearch.py
160
3.703125
4
def linear_search(arr,x): for i in range(len(arr)): if arr[i]==x: return i return -1 print(linear_search([1,2,3,4,5,10,3,7,1,2],5))
8026684ab01a7974f410d766346a6410eed47ada
herok97/Programmers-algorithms
/연습문제.py
1,085
3.75
4
def my_solution(n): answer = '' while n is not 0: k = n % 3 if k == 0: answer = '4' + answer elif k == 1: answer = '1' + answer else: answer = '2' + answer n = (n - 1) // 3 return answer def best_solution(n): # 출처 https://p...
d020d4a32b7a6b4d62b80a73c0f3687874c79feb
Strangedip/Rock-Paper-Scissor-game
/main2.py
830
4.1875
4
#create rock paper scissor game using functions import random def gamewin(comp, player): if comp == player: return None elif comp == "r": if player=="p": return True else : return False elif comp == "p": if player=="s": ret...
0e341f6c52e039d68033d014c01e0ff0759a0aa9
vermuz/python_learning_source_code
/iterator.py
347
3.6875
4
__author__ = 'kathiria' class MyIterator(object): def __init__(self, steps): self.steps = steps def next(self): if self.steps == 0: raise StopIteration self.steps -=1 return self.steps def __iter__(self): return self for e1 in MyIter...
fc9e61e6202bdaa9dcf036a513620ded86e50423
vermuz/python_learning_source_code
/expression_tree.py
1,932
3.828125
4
__author__ = 'kathiria' class ExprNode(object): def __init__(self, value=None, left=None, right=None): self.value = value self.left = left self.right = right def evaluate(self): if self.value == "+": return self.left.evaluate() + self.right.evaluate() ...
387303edeaeaa9c492b46086817506fa42b25d97
vermuz/python_learning_source_code
/threading_queue.py
866
3.625
4
__author__ = 'kathiria' import threading import time import Queue job_queue = Queue.Queue() class count_stuff(threading.Thread): """ A thread class that will count a number, sleep and output that number """ def __init__(self, start_num, end, q): self.num = start_num ...
1880ada1eae6b12eb58ecdceda9d6beb25f93e0c
vermuz/python_learning_source_code
/multitask.py
619
3.640625
4
__author__ = 'kathiria' from collections import deque tasks = deque() def run(): while tasks: task = tasks.popleft() try: next(task) tasks.append(task) except StopIteration: print('Task done') def countdown(n): while n > 0: ...
37a96ed4a21585843524f1d910cca1ef6b221ba8
vermuz/python_learning_source_code
/stack_implementation.py
2,398
3.71875
4
__author__ = 'kathiria' class Stack: def __init__(self): self.items = [] def is_empty(self): return self.items == [] def push(self, item): self.items.append(item) def pop(self): return self.items.pop() def peek(self): return self.items[l...
bd0a34c9d2e38feb14f180e1f9ffef647c53b3de
kggen/fundamentals-of-python
/vgetov/chapter2/ex16.py
172
3.6875
4
print("Q: What is the difference between the following two strings? 'n' and '\\n'?") print("A: 'n' is a one letter string literal, '\\n' is a special new_line character.")
409a7c153b0f060756acc04dec8174784c3e0183
kggen/fundamentals-of-python
/dgyurov/chapter_4/uniq or duplicat.py
543
3.859375
4
print("Please enter four integer values.") num1 = int(input("Enter number 1: ")) num2 = int(input("Enter number 2: ")) num3 = int(input("Enter number 3: ")) num4 = int(input("Enter number 4: ")) num5 = int(input("Enter number 5: ")) if num1 == num2 or num1 == num3 or num1 == num4 or num1 == num5: print('DUPL...
051ccd8f8d0f47f4f6ddac1fa5460d7b5522645c
Procta/Python-Data-Structures
/linked_list.py
1,858
4.0625
4
from node import Node class LinkedList: def __init__(self, value=None): self.head_node = Node(value) def get_head_node(self): return self.head_node def insert_beginning(self, new_value): new_node = Node(new_value) new_node.set_next_node(self.head_node) self.head_n...
d7726b01bddf327561c0914c1c7db68433f840b1
spacecowboy2049/clouds
/Linux/python/1/Activities/05-Variable-Dissection/UNSOLVED-Variables-Dissect.py
1,714
4.3125
4
# Part 1 # ===================================== # Prints: [FILL IN] variable_one = 10 print(variable_one) print(type(variable_one)) # Prints: [FILL IN] variable_two = 5 print(variable_two) # Prints: [FILL IN] sum_of_variables = variable_one + variable_two print(sum_of_variables) # Prints: [FILL ...
5ed1db8a2d8f7813940a88b36c8bc6f41a560737
tthoraldson/intro-neural-network
/demo.py
1,925
3.90625
4
from numpy import exp, array, random, dot class NeuralNetwork(): def __init__(self): # seed the number generator random.seed(1) # assign random weights to the synapses self.synaptic_weights = 2 * random.random((3, 1)) - 1 # the sigmoid function def __sigmoid(self, x): ...
6a8275919c7a4ea051163baa6bbd7f39de2ce2ff
drmenghan/PyS
/CC150/Ch1.py
917
3.8125
4
#test one string has all unique characters def test1_1(test_str): for i in range(len(test_str)): for j in range(i+1, len(test_str)): if (test_str[i] == test_str[j]): return False return True test1_1("a b c") test1_1("abcc") #What if blank doesn't count #reverse string def...
051defdc32dce589e0153e0f2fe8883f7977d20c
mohit-mhjn/byproduct_inventory_opt
/src/postprocessor.py
10,090
4.03125
4
""" The results obtained from the pyomo model is in form of numeric indices This program is used to parse the solved model instance and map the results back in the form of user defined descriptions which results in an understandable form of output and collect + foramt the results in form of predefined tables pandas i...
09172aacd60e7d7b00b39fffe191ccb571fe0665
brdyer/DAEN_500_Fall_2020_Final_Exam
/DAEN_500_final_prob_1.py
892
4.1875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Oct 8 08:21:51 2020 @author: braddyer """ # get user input of range for analysis usr_range_start = int(input('Enter the low end of the range you want to try: ')) usr_range_end = int(input('Enter the high end of the range you want to try: ')) # determ...
091ada3f799114adc8a614852e1f9108cd8ea63b
microwu/leetcode
/202004/98.py
982
3.96875
4
# Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Tree: def __init__(self,treeList): if len(treeList) == 0: return None self.root = TreeNode(treeList[0]) def init(node,ind...
690954769c6e7cbf9e7e194a52bbee4c1038eaf8
microwu/leetcode
/202004/23.py
1,292
3.796875
4
from typing import List from node import * # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def mergeKLists(self, lists: List[ListNode]) -> ListNode: if len(lists) == 0: return None elif...
d1212e151341a9ff51df9043313c3c8ecb3d6ad1
microwu/leetcode
/202003/289.py
2,999
4
4
''' 如果活细胞周围八个位置的活细胞数少于两个,则该位置活细胞死亡; 如果活细胞周围八个位置有两个或三个活细胞,则该位置活细胞仍然存活; 如果活细胞周围八个位置有超过三个活细胞,则该位置活细胞死亡; 如果死细胞周围正好有三个活细胞,则该位置死细胞复活; if 1: if [0,1] : 0 elif [2,3]: 1 elif [4:8]: 0 elif 0: if 3: 1 [0,1,0], [0,0,1], [1,1,1], [0,0,0] [0,0,0], [1,0,1], [0,1,1], [0,1,0] 来源:力扣(...
38cbdae4f90f92caa1847b9cf84ad27fdc164ee6
microwu/leetcode
/202003/foobar.py
1,162
3.65625
4
import threading class FooBar: def __init__(self, n): self.n = n self.lockFoo = threading.Lock() self.lockBar = threading.Lock() threadFoo = threading.Thread(target=self.foo,args=(lambda : print("foo",end=''),)) threadBar = threading.Thread(target=self.bar,args=(lambda : prin...
ce2668ed5ed7ee1dd9af35fc8760469cfbc8b950
sahlamina/mvc_flask
/app.py
1,600
3.59375
4
from flask import Flask, render_template # importing flask # importing render_template() # in order for us to udr flask, we need to create an instance of our app # app = Flask(__name__) # # syntax to create flask instance # # # these are called decorators and the below is the syntax for decorators to create a web rout...
dbd0eab9495b0fd6b3f9846aec1a94ee4182ca12
WearyPupil/Cargo_Imaginary_Company
/puerto.py
12,674
3.6875
4
from estructuras_de_datos import ArrayStack; from estructuras_de_datos import ArrayQueue; class Puerto: """Modelado del problema planteado.""" # Constantes del problema MAX_CONTENEDORES = 990; MAX_AUTOS = 371; MAX_PILAS = 200; MAX_COLAS = 25; class _Cuaderno: """Clase l...
cda4e775a4fda25815eb20ef3de2fad07e0c0830
aayanqazi/python-task
/05.py
94
3.734375
4
inp = int(input("Enter Number: ")) val ={x: x**2 for x in range(inp+1) if(x != 0) } print(val)
bba9992941a29ff78ed89bda264fe5be571e4d0a
ChaeLinYeo/BAEKJOON
/3009.py
333
3.734375
4
location = [list(map(int, input().split())) for _ in range(3)] x1 = location[0][0] y1 = location[0][1] x2 = location[1][0] y2 = location[1][1] x3 = location[2][0] y3 = location[2][1] if(x1 == x2) : x = x3 elif(x2 == x3) : x = x1 elif(x1 == x3) : x = x2 if(y1 == y2) : y = y3 elif(y2 == y3) : y = y1 elif(y1 == y3) : y = ...
865cd57f64c4811d050e31f204ccad2065b87e22
ChaeLinYeo/BAEKJOON
/1284.py
289
3.515625
4
while(True): answer=1 num = "" num = input() if num == "0": break else: numlist = [int(i) for i in num] for j in range(len(numlist)): if numlist[j]==1: answer+=2 elif numlist[j]==0: answer+=4 else: answer+=3 answer+=1 print(answer) num = "" answer = 1
be76860ce49c55f59ee2efb67c6822bff909869c
ChaeLinYeo/BAEKJOON
/1629.py
426
3.5625
4
# 시간초과를 피하기 위해 분할정복을 해야됨. # A^50 = A^(25*2) : B가 짝수일때 # A^51 = A^(25*2+1) = A^(25*2)*A : B가 홀수일때 A,B,C = map(int,input().split()) def divide(A,B): if B==1: return (A%C) elif B==2: return ((A*A)%C) else: temp = divide(A, B//2) if B%2 == 0: # B가 짝수이면 return ((temp*temp)%C) else: # B가 홀수이면 return ((temp...
be19d3ba134b506f1c79bb3de545951d3f8e3347
ChaeLinYeo/BAEKJOON
/1929.py
420
3.6875
4
# M이상 N이하의 소수를 모두 출력 # 에라스토네스의 체 # 시간을 줄이기 위해 i의 제곱근까지 확인하면 된다. import math def isPrime(num): if num == 1: return False n = int(math.sqrt(num)) for i in range(2, n+1): if num%i==0: return False return True m,n = map(int, input().split()) for i in range(m,n+1): if isPrime(...
4ea45618dafd0527ca0e769a3305e8f70cc852a6
detkid/LanguageProcessingPractice
/LPP#1-10/#6.py
219
3.5625
4
def ngram(list, n): result = [] for i in range(len(list) - n + 1): result.append(list[i:i + n]) return result stc = 'I am an NLPer' print(ngram(stc, 2)) words = stc.split() print(ngram(words, 2))
ae175d534e0a919bd52ab470a59967d8f4842e44
VineetPrasadVerma/GeeksForGeeks
/InterviewCorner/RemoveDuplicatesFromArrayInPlace.py
160
3.671875
4
arr = [0, 1, 1, 1, 2, 2, 3, 4, 4, 5, 6, 7, 7, 7, 8, 9, 9] for i in range(len(arr)-1): if arr[i] != arr[i+1]: print(arr[i], end=" ") print(arr[-1])
202bed7b10572d8dda012a37632454b75a305f69
VineetPrasadVerma/GeeksForGeeks
/SudoPlacementCourse/RotatingAnArray.py
441
3.828125
4
n = int(input()) for _ in range(n): final_ans_list = [] size_of_array = int(input()) array_elements = input() rotate_array_element = int(input()) list_of_elements = [i for i in array_elements.split()] list_of_elements = list_of_elements[rotate_array_element:] + list_of_elements[:rotate_array_...
3b65b5be1694c7966067466ffe0b139fcdfe02e3
VineetPrasadVerma/GeeksForGeeks
/SudoPlacementCourse/IntegerIsPowerOf8.py
339
3.8125
4
import math test_cases = int(input()) for _ in range(test_cases): num = int(input()) temp = num counter = 0 ans = 1 while num != 0 and num != 1: num = num / 8 counter += 1 for i in range(0, counter): ans *= 8 if ans == temp or ans == 8: print("Yes") else: ...
bcd10109033b3d7bd2b8388c2aa75327bda7b25b
VineetPrasadVerma/GeeksForGeeks
/Tree/PostOrdeViaInAndPreOrder.py
500
3.703125
4
def print_post_order(inorder, preorder, n): if preorder[0] in inorder: root = inorder.index(preorder[0]) if root != 0: print_post_order(inorder[:root], preorder[1:root+1], len(inorder[:root])) if root != n-1: print_post_order(inorder[root+1:], preorder[root+1:], len(inorder[root+1:...
9f23605567ec5b63ee474991627f0cf3872f2c79
VineetPrasadVerma/GeeksForGeeks
/Revision/ManualSorting.py
201
3.640625
4
lst = [3, 4, 1, 2, 5] for i in range(len(lst)): for j in range(i+1, len(lst)): if lst[i] > lst[j]: temp = lst[i] lst[i] = lst[j] lst[j] = temp print(lst)
bd2f1531a79febc7044ce3b0f4635ec4d4e1f9da
VineetPrasadVerma/GeeksForGeeks
/Stack/PrintBracketNumber.py
328
3.5625
4
n = int(input()) for _ in range(n): stack = [] expression = input() count = 1 for i in expression: if i == "(": stack.append(count) print(count, end=" ") count += 1 elif i == ")": temp = stack.pop() print(temp, end=" ") ...
6dbcef1878f13fd398c8e66aa9b172901885d574
VineetPrasadVerma/GeeksForGeeks
/InterviewCorner/IceCreamParlor.py
1,658
3.5625
4
def whatFlavors(cost, money): cost_dict = {} a = 0 b = 0 for i in cost: if i not in cost_dict: cost_dict[i] = 1 else: cost_dict[i] += 1 if money % 2 == 0: if money//2 in cost_dict: if cost_dict[money // 2] == 2: temp = cost...
814c8976ff1c61d82f0582a2e5efc6603935b8ab
VineetPrasadVerma/GeeksForGeeks
/Recursion/substringwithsamefirstandlast.py
239
3.609375
4
def substring(s): ans = [] if s == "": return ans for i in range(len(s)): temp = s[:i+1] if temp[0] == temp[-1]: ans.append(temp) return ans + substring(s[1:]) print(substring("abcab"))
d1838514a492e62c6e49c2858b9c819fc6b7b56c
VineetPrasadVerma/GeeksForGeeks
/InterviewCorner/CountConsecutiveOneInBinaryFormOfNum.py
709
3.546875
4
consecutive_ones_count = 0 lst_consecutive_ones_count = [0] n = int(input()) binary_form = "{0:0b}".format(n) for i in range(len(binary_form)): if i == 0: if binary_form[i] == "1": consecutive_ones_count = 1 else: if binary_form[i] == "1": if binary_form[i-1] == "1": ...
ce08fb289b1d56f432dcfe7ccb8385d270fc89ee
VineetPrasadVerma/GeeksForGeeks
/InterviewCorner/RemoveGivenElement.py
117
3.59375
4
arr = [10, 20, 10, 30, 10, 40, 10, 50] ans = [] n = 10 for i in arr: if i != n: ans.append(i) print(ans)
a2043c57b071a4ff54928281715279c30d3bfb23
VineetPrasadVerma/GeeksForGeeks
/LinkedList/SinglyLinkedList.py
3,097
4.09375
4
class Node: def __init__(self, data): self.data = data self.next = None class LinkedList: def __init__(self): self.head = None def insert_at_front(self, data): new_element = Node(data) curr_element = self.head if curr_element is None: self.head ...
3752d843b3add4fcfe78f2ab6b1468941f28d4f2
Abhay0899193/FinalYear
/WiKI.py
412
3.703125
4
import wikipedia import nltk _text=input("What do you want to search: ") for word,pos in nltk.pos_tag(nltk.word_tokenize(str(_text))): if (pos == 'NN' or pos == 'NNP' or pos == 'NNS' or pos == 'NNPS'): cxz=word #for word,ne in nltk.ne_chunk(nltk.pos_tag(nltk.word_tokenize(str(_text)))): # ...
c736a176b942789ad97d3c03e005556592b95548
WhyseRabbit/Intro_to_Python
/assignments/A12_parameter_packs.py
274
3.5625
4
""" Assignment 12 Create a function with the `*args` parameter. The function should handle an unbounded number of inputs without error. """ import statistics def CR(*args): return statistics.mean(args) levels = (16, 16, 16, 16, 14, 15, 11, 11, 5) print(CR(*levels))
e0dc5c4554d63f96288fdc9291fce0246bc18ebf
akul1507/Sudoku-Generator-Solver
/sudoku.py
6,855
3.53125
4
import random import time as t from tkinter import * from copy import deepcopy from tkinter import messagebox from sudokuFrame import sudokuFrame class sudoku: # variables: root = Tk() def __init__(self): # set title self.root.title('Sudoku Solver') # Disable resizing of the f...
1a2289ff2f57c10628c8d20be5d29f5336f9bd9a
Nashrahkhan22/Hangman_game
/hangman.py
1,622
3.90625
4
# -*- coding: utf-8 -*- """ @author: Nashrah """ #step 1 imorting and random import random print("This is Hangman game,\nTotal lives=4") list=["pea","mango","orange"] x=random.choice(list) #step=2 slpiting the word in list and joining amd for __ m=" ".join(x) l=m.split() m=["__"] for r in range(len(l...
8a4b0aa07100258990004eaf91fdc1a8206a872a
vngilev/python_study
/purepython/stepikcourse/02/01/task_03.py
362
3.546875
4
class NonPositiveError(Exception): pass class PositiveList(list): def __init__(self, seq=()): super().__init__(self) def append(self, x): if x > 0: super().append(x) else: raise NonPositiveError("NonPositiveError") test = PositiveList() test.append(5) #te...
326f6c03ba0baabd552d3459ad60fd63e5dffc92
netlian/AAMLP-Project
/learningcurve.py
1,239
3.921875
4
from sklearn.model_selection import learning_curve import numpy as np import pandas as pd import matplotlib.pyplot as plt # For ploting def plot_learning_curve(clf, x_train, y_train, model_name): ''' Plot the learning curve of a given classifier. ''' cv = 5 y_train = np.array(y_train).reshape(y_train...
52dd5fe7b47937c54454611d661b5b09bd821d9c
alexhein189/actual_capstone_project
/comparing_distances.py
1,192
3.515625
4
from distance import distance from vulnerable_person import vulnerable_person from volunteer_2 import new_volunteer class distance_chooser: def __init__(self, vulnerable_longitude: vulnerable_person.longitude, vulnerable_latitude: vulnerable_person.latitude, volunteer_longitude: new_volunteer.lon...
8d1331e8965c5830b9337d7577020e6fdd1e1f72
alexhein189/actual_capstone_project
/distance.py
616
3.921875
4
import math class distance: def __init__(self, latitude1, longitude1, latitude2, longitude2): self.latitude1 = latitude1 self.longitude1 = longitude1 self.latitude2 = latitude2 self.longitude2 = longitude2 # TODO: Inside the distance, you need to update it, calculate distances...
08821606ed86eb6fadfd3914e0637f67c16a26c7
mturpin1/CodingProjects
/Python/nfl.py
824
3.796875
4
nfl = { 'NFC': { 'North': ['Bears', 'Packers', 'Vikings', 'Lions'], 'South': ['Saints', 'Panthers', 'Buccaneers', 'Falcons'], 'East': ['Redskins', 'Cowboys', 'Eag;es', 'Giants'], 'West': ['Rams', 'Seahawks', 'Cardinals', '49ers'] }, 'AFC': { 'North': ['Bengals', 'Ravens...
651d4ded3f2b151553b44c300998d6352c69a76e
mturpin1/CodingProjects
/Python/encrypt.py
385
4.21875
4
import os plainText = input('Please enter a word you would like encrypted - ').lower().strip() key = int(input('Please enter an encryption key (it can be any whole number) - ')) alphabet = 'abcdefghijklmnopqrstuvwxyz' encryptedText = '' for letter in plainText: index = alphabet.find(letter) encryptedText += (al...
9396dfbe14ea36acd6ee4a834061de35b86db2aa
mturpin1/CodingProjects
/Python/tictactoe.py
2,048
3.90625
4
board = [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '] current_player = 'X' marks_on_board = 0 def display_board(board): print(f'{board[0]} | {board[1]} | {board[2]} ') print(f'===========') print(f'{board[3]} | {board[4]} | {board[5]} ') print(f'===========') print(f'{board[6]} | {board[7]} | ...
6901e6ebd9bbb23b25900ae8176c639ae42f2447
mturpin1/CodingProjects
/Python/debugging1.py
167
4.09375
4
num = int(input('How old are you? ')) def vote_check(age): if num <= 18: print('You cannot vote!') else: print('You can definitely vote!') vote_check(num)
b3116b23c454985cdc1c5a6c00d8e6b4123d596a
mturpin1/CodingProjects
/Python/curfew_checker.py
911
4.3125
4
age = input('How old are you?: ') age = int(age) time = input('What hour is it?: ') time = int(time) def curfew_check(): if age >= 0 and age <= 12: print('\"Get off the computer, please.\"') elif (age > 12 and age <= 16) and (time >= 0 and time <= 8): print('\"You should be asleep!\"') elif ...
9010433a78968302b4fa6961e81ad695c4bc6bc3
mturpin1/CodingProjects
/Python/Seth'sCipher.py
1,055
3.609375
4
import os import random numbers = [25, 64, 69, 24, 32, 37, 44, 50, 55, 60, 72, 32, 45, 49, 62, 67, 71, 74, 79, 82, 88, 94, 10, 13, 17, 28] numbers2 = [25, 64, 69, 24, 32, 37, 44, 50, 55, 60, 72, 32, 45, 49, 62, 67, 71, 74, 54, 82, 88, 94, 10, 13, 17, 28] letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k',...
dfcc64126ae03f7328660a14a3f87cf4056416d6
mturpin1/CodingProjects
/Python/debugging3.py
340
4.28125
4
color = input('Pick a color. ') def color_choice(color): if color == 'red' or color == 'Red': print('You chose red.') elif color == 'blue' or color == 'Blue': print('You chose blue.') elif color == 'orange' or color == 'Orange': print('You chose orange.') else: print('You screwed something up.')...
2d444b5d848b70d4a4475ef819ab84caa814113d
SHPStudio/LearnPython
/pachong/error.py
739
3.703125
4
# 爬虫还会遇到很多的错误 #URLError # 这个错误的产生原因有以下几个 # 1.网络无连接 本地上不了网 # 2.连接不到特定服务器 # 3.服务器不存在 from urllib import request,response # try: # request.urlopen('http://www.shpcoder.cn') # except request.URLError as e: # print(e.reason) # HTTPError # 这个是比如遇见404 500 这种有关http状态码错误等等的可以捕捉这个错误 # 然后根据返回的状态码去进行下一步处理 # 301 重定向 处理方式是重...
7b62c3824d332f64cba621ce991237cafcc09118
SHPStudio/LearnPython
/basic/iteration.py
978
4.125
4
# 迭代器 # Iterator 可以使用next()不断获取值的对象 并且可以使用isinstance()判断对象是否是迭代器 # Iterable 是可以使用for迭代去获取值的对象 叫可迭代对象但并不一定是Iterator # 比如generater生成器一定是迭代器对象 list tuple set等等可能就不是迭代器对象 # 但是他们可以使用iter()变为迭代器对象 from collections import Iterable,Iterator print(isinstance('adfa',Iterable)) print(isinstance([1,1,2,3],Iterable)) print(isinstan...
2b17cad3878503fa39c8a43971faf70755657af9
SHPStudio/LearnPython
/module/pv_module.py
215
3.515625
4
# 私有模块 def _private_1(name): print("Hello %s" % name) def _private_2(name): print("Hi %s" % name) def greeting(name): if len(name) > 3: _private_1(name) else: _private_2(name)
82d1d51d0e345fc1a9ba908123f2ec46929f1b59
haidarknightfury/PythonBeginnings
/100Days/Day10- Automate Boring Stuffs/orderfiles.py
721
3.984375
4
import shutil, os, sys def moveFiles(destFolder, extension): """ method to move files in a directory with a specific extensions to a destFolder """ if destFolder not in os.listdir(): os.mkdir(destFolder) for fileName in os.listdir(): if fileName.lower().endswith(extension): ...
f7c232511fc417ab06eda7a8b4c14f86cbc1414d
haidarknightfury/PythonBeginnings
/100Days/Day10- Automate Boring Stuffs/stringformating.py
176
3.546875
4
def printDetails(name, surname, age): print(f"Name is {name}, surname is {surname} and age is {age}") if __name__ == "__main__": printDetails('haidar', 'dargaye', 25)
2bd3a45c37847bb50328ab0fab1dadfbf8761252
haidarknightfury/PythonBeginnings
/100Days/Day10- Automate Boring Stuffs/graph.py
1,935
3.765625
4
from collections import deque class Graph(): def __init__(self): self._graph = {} def add(self, vertex_st, vertex_end): if vertex_st not in self._graph: self._graph[vertex_st] = {vertex_end} else: self._graph[vertex_st].add(vertex_end) def delete_link...
64fcd6f6c9f39a9406783103f3bfc60b7d7d46fe
haidarknightfury/PythonBeginnings
/100Days/Day1 - Basic Python/2.perimeter.py
147
3.953125
4
import math r = float(input('Enter Radius : ')) p = 2*math.pi* r a = math.pi * r**2 print('Radius %.1f , Perimeter %.1f , Area %.1f' % (r, p,a))
a9042e33d9a85d4a4329f85024ffde27f0503528
haidarknightfury/PythonBeginnings
/Programs/SearchEngine/OtherPrograms/Symmetric.py
626
4.34375
4
# A list is symmetric if the first row is the same as the first column, # the second row is the same as the second column and so on. Write a # procedure, symmetric, which takes a list as input, and returns the # boolean True if the list is symmetric and False if it is not. def symmetric(lists): if lists == []: ...
01288e7f242f2aad2de7275ab73f7bfa2cab56bb
haidarknightfury/PythonBeginnings
/100Days/Day7 - Advanced Object Oriented Python/3.Clock.py
1,045
3.9375
4
from time import time, localtime, sleep class Clock(object): def __init__(self, hour=0, minute=0, second=0): self._hour = hour self._minute = minute self._second = second # Class method - return an instance of the class # cls is the constructor method @classmethod def now...
6064a9d694219a77a99b8f3e60d908d1933ff40c
haidarknightfury/PythonBeginnings
/100Days/Day10- Automate Boring Stuffs/delete_less_than_k.py
94
4.125
4
lists = [1,1,1,1,2,2,2,3,3,2,1,3,2,2] res = [x for x in lists if lists.count(x) >3] print(res)
472ccad84b405f7c85a368ff73d4882b52c29b63
haidarknightfury/PythonBeginnings
/100Days/Day3 - Intro to Loops/7.sumeven.py
174
3.578125
4
sum = 0 for x in range(2, 102, 2): sum += x print('Sum is %.1f' % sum) sumy = 0 for y in range(1, 101): if(y % 2 == 0): sumy += y print('Sum is %d' % sumy)
1e951346e8e76304a79f761ab81cbf7a5f3334b4
haidarknightfury/PythonBeginnings
/Programs/SearchEngine/OtherPrograms/IdentityMatrix.py
696
4.1875
4
# Given a list of lists representing a n * n matrix as input, # define a procedure that returns True if the input is an identity matrix # and False otherwise. # An IDENTITY matrix is a square matrix in which all the elements # on the principal/main diagonal are 1 and all the elements outside # the principal diagonal ...
872a5f291810571ed9d0a15a4931d77c5a847527
haidarknightfury/PythonBeginnings
/100Days/Day5 - Advanced Data Structures/exercises/dayspassed.py
392
3.8125
4
def isLeap(year): return year % 4 == 0 def diffdays(year, month, date): daysofmonth = [[31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31], [ 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]][isLeap(year)] total = 0 for index in range(month - 1): total += daysofmonth[index] return tota...
946833b6f8f89ed914ccdf9fe14b3dea226d5121
beknazar1/code-platoon-self-paced
/week-1-challenges/armstrong_numbers.py
612
4.1875
4
import math def find_armstrong_numbers(numbers): OUTPUT = [] for number in numbers: # Leverage python libraries to easily split a number into a list of digits DIGITS = [int(digit) for digit in str(number)] # Length of DIGITS list will be the exponent per defintion of Armstrong numbers ...
de2b9b632f2abbac3236925918e343870ef4ec44
vernittyagi/General-Algorithms
/second_largest.py
419
3.90625
4
# Second Largst element in an array def sort(num): for i in range(len(num)-1,0,-1): for j in range(i): if num[j]>num[j+1]: temp = num[j] num[j] = num[j+1] num[j+1] = temp return num def secondlargest(num): t =sort(num) re...
19b6c5f1d4354a65b5976ad20945e1a8dedcae72
zhan3870/db-project
/DBEngine.py
5,503
3.5
4
import sqlite3 from Parser import Parser import time class DBEngine: def __init__(self): self.conn = sqlite3.connect('./database/test.db') self.c = self.conn.cursor() self.p = Parser() def write_states(self): self.c.execute("Drop table state") self.conn.commit() ...
d42e67147a1222caeaa547d013741f55c7894669
griffithcwood/Image-Processing
/imageOpen.py
828
4.15625
4
#!/usr/bin/env from tkinter import filedialog from tkinter import * import tkinter as tk # neede for window def prompt_and_get_file_name(): """prompt the user to open a file and return the file path of the file""" # TO DO: add other file types!!!!!!!!!!!!!!!!!! try: img_file_name = filedialog...
21ed7512858a5208d9341f94f3d037e2f4baa8fa
Farbod909/pong
/game.py
5,642
3.796875
4
import pygame import sys from colors import * from pygame.locals import * class Game: """A class that encapsulates all game data and generic functions. Args: size ((int, int)) color: (Color or (int, int, int)) Attributes: state (State): The current state of the game. ...
8a67e98a3a82bf1f8c391c86be2ea6103ef2967a
andresdeluna27/compilador
/compilador/Nodo.py
940
3.578125
4
class Nodo(object): def __init__(self, nombre): self.nombre = nombre self.hijos = [] self.hermano = None self.padre = None def agregar_hijos(self, obj): self.hijos.append(obj) def agregar_hermano(self, obj): self.hermano = obj def agregar_hermano(self, ...
e4cb9e66f175b1592651288b1e683c4eed214a05
G-dab/Python-
/python/学习1/数据类型转换 第4课.py
356
4
4
# 2021/7/12 #17:18 name='张三' age=38 #print('我叫'+name+'今年'+age+'岁') 不同的数据类型相连接会报错 #只能通过数据类型转换来实现 #用str函数转换 print('我叫'+name+'今年'+str(age)+'岁') #注意,int()函数是可转浮点数,而不能转浮点数的字符串 print(str(True)) print(int(True)) print(float(True))
556a17cec32108159336f1f8939fe51bb0c06dc4
G-dab/Python-
/python/学习1/多分支结构 判断成绩级别 第5课.py
375
3.515625
4
# 2021/7/16 #14:54 ''' 90-100 A 80-89 B 70-79 C 60-69 D 0-59 E ''' score = int(input('请输入一个整数成绩')) if 89<score and score <100: print('级别为 A') elif 70<=score and score<90: print('级别为 B') elif 60 <= score and score < 80: print('级别为 C') elif 0<=score and score<60: print('级别为 D') else: print('成绩不合...
72b840a1618a274cd2e076fd0a796fe2dcae79f3
Skumbatee/bc-9-oop
/student.py
2,003
4.1875
4
import datetime map_ = { 'UG': 'Uganda', 'KE': 'Kenya', 'NG': 'Nigeria', 'TZ': 'Tanzania' } class Student(object): #declaring a variable Id with a value zero which is an instance variable Id = 0 #Create an empty dictionary attendace that stores the attendance of the students ...
bc1ee0291cbae492970bbfb832d88dec25e16d00
vr97/finalyearproject2018-19
/Code/Scripts/DateFormatting.py
2,302
3.5
4
# module to format the tweet time Thu Feb 28 14:51:59 +0000 2019 # converting that day to 28, month to 2, hour 14 and min 51 import csv def format_date_string(date_str): """ :param date_str: expects the format Thu Feb 28 14:51:59 +0000 2019 :return: a dictionary containing day,month,hour,min """ # ...
29c40880efc487f798cf3226f76cf73806b1bd22
shebeerki/Algorithms
/mergesort.py
654
3.875
4
def mergesort(arr): if len(arr) == 1: return arr m = len(arr) / 2 l = mergesort(arr[:m]) r = mergesort(arr[m:]) if not len(l) or not len(r): return l or r result = [] i = j = 0 while (len(result) < len(r) + len(l)): if l[i] < r[j]...
62bd3ea837ff9e338ce5811f7c3397bcb33fa848
snehkothari/Expertrons
/Expertrons_Sneh_Kothari_Question2.py
363
3.90625
4
list1=[] size1=int(input("Enter size of list 1")) for i in range(0,size1): list1.append(input("Enter element")) list2=[] size2=int(input("Enter size of list 2")) for i in range(0,size2): list2.append(input("Enter element")) final_list1=[] for item in list1: if item in list2: list2.remove(item) else: final_l...
185d4efb9c59566222535b61dbf9db1f49f1870b
appanacca/meetup_python_iterators_presentation
/iterative_example.py
1,260
3.671875
4
from itertools import repeat, accumulate from typing import Iterator from more_itertools import iterate from functools import partial import numpy as np def iterate_v1(f, x): while True: yield x x = f(x) def iterate_v2(f, x): yield x yield from iterate_v2(f, f(x)) def iterate_v3(f, x) -> ...
fa3178341710179b2b5f7158c5610eef35b20b74
GQ312/Chapter1-Part3
/Task1.py
218
4.03125
4
def summ(): num1 = int(input("Write your first number: ")) num2 = int(input("Write your second number: ")) num3 = int(input("Write your third number: ")) return f"Summ is {num1+num2+num3}" print(summ())
5639d16d6e21b10909431e07ef2d063b90879895
GQ312/Chapter1-Part3
/Task6.py
510
4.03125
4
# def count(): # nums = input("Write your numbers: ") # odds = 0 # evens = 0 # for i in nums: # if i % 2 == 0: # odds += 1 # else: # evens += 1 # print(odds) # print(evens) # print(count()) def count(nums): odds = 0 evens = 0 for i in n...
755d0e2146a09e1a3b29344b282f73d2e1b043d3
kumarun91/World-Happiness-Report
/finalModel.py
1,983
3.59375
4
# -*- coding: utf-8 -*- """ Created on Thu May 04 03:43:47 2017 @author: arun """ # -*- coding: utf-8 -*- """ Created on Tue May 02 01:21:30 2017 @author: arun """ #from __future__ import division import numpy as np import pandas as py import math import matplotlib.pyplot as plt from sklearn import...
9a62e7ad3113ae97d67e5cd56c874b4871e19888
lmoberly1/Blackjack
/blackjack.py
6,198
3.859375
4
import random import time # Creates deck and randomizes it deck = [1,2,3,4,5,6,7,8,9,10,10,10,10,11] * 4 # Deck is total of 52 cards random.shuffle(deck) # Creates bank bank = 500 # Start function def startUp(bank): print('---------------------------------------------') print(' Welcome to t...
4a9564d6da266582c60efeeb935005b50d535e0d
qinggeng/tools
/python/workingHours.py
291
3.890625
4
#-*- coding: utf-8 -*- import datetime def dateRange(startDate, endDate): day = startDate while day < endDate: day = day + datetime.timedelta(1) yield day def workdays(startDate, endDate): return filter(lambda x: x.weekday() != 5 and x.weekday() != 6, dateRange(startDate, endDate))
02a352200e2bc69d329407f0f2ecabb94c579d6f
salmaanMSA/PythonPrograms
/multiples of 3 and 5.py
126
3.90625
4
a= int(input("Enter the limit=")) for i in range(1,a+1): if(i%3==0): print(i) elif(i%5==0): print(i)
7d88337099383086b730612716a8d2b7f424eed8
salmaanMSA/PythonPrograms
/ODD AND EVEN DISPLAY.py
133
4.0625
4
a= int(input("ENTER THE LIMIT = ")) for i in range(0,a+1): if (i%2==0): print(i,"EVEN") else: print(i,"ODD")
1a4a3ffe60bbbc7f8ae67aac52581dd38f6447e9
salmaanMSA/PythonPrograms
/amstrong no.py
232
4.0625
4
num=int(input("ENTER THE NUMBER:")) sum=0 temp=num while temp>0: rem=temp%10 sum=sum+rem**3 temp=temp//10 if (num==sum): print("It is amstrong number") else: print("It is not an amstrong number")
836ff783ff616ef9973f93f67af532acaa18497c
subbak2/TIL
/1911/1103/practice.py
76
3.71875
4
dic = {'a':"a", 'b':"b", 'c':"c"} print(dic['a']) print(dic.get('b','a'))
25f4d99f9dd32a9ac8d5d2ddab5959822c0c932f
Dhan-shri/If-else
/schedule.py
669
4.34375
4
time=float(input("enter a time")) # time is given in 24 format if time>6 and time<=7: print("morning exercise") elif time>7 and time<=8.30: print("breakfast") elif time>8.30 and time<=9.30: print("english activity") elif time>9.30 and time<=13: print("coding time") elif time>13 and time<=14.30: pri...
2fa561ed99ee6265ec62fd40ab0d6e88fa36a430
sherhan013/python
/pass_check1.py
307
3.609375
4
login = input('Введите свой логин: ') password = input ('Ввежите свой пароль: ') while len(password) <7: print('Длина пароля менее 7 символов') password = input ('Ввежите свой пароль: ') print('Пароль принят') input()
2c7e6315023114edefbb6881e4d36648f689aa97
connor-ruff/PythonWithBrad
/elif.py
463
3.953125
4
def main(): num1 = input('Gimme A Damn Number: ') num1 = int(num1) num2 = input('Gimme Another Number: ') num2 = int(num2) maxNum = input('Enter the Max Number: ') maxNum = int(maxNum) if ( num1 + num2 > maxNum ): print(f'{num1} + {num2} > {maxNum}') elif (num1 + num2 < ma...
6ad261c07c02890a8317074765f39ad2147a9e1f
786951355/python_2017
/miniblog/hello.py
220
3.53125
4
from datetime import datetime, timedelta delta = timedelta(minutes=30) start = datetime(2017, 3, 8, 12, 6, 35, 544302) now = datetime.now() m = now - start print(now) print(start) print(m.total_seconds())
fec3537dbd183aaa3144329d15c41a900c1fec0a
GayatriHungund81194/CryptologyNumberSequence
/numbersequence.py
7,040
3.640625
4
if __name__=="__main__": count3_1 = 0 count4_1 = 0 count5_1 = 0 count6_1 = 0 count7_1 = 0 count8_1 = 0 count9_1 = 0 count10_1 = 0 count11_1 = 0 number = 4 flag5 = 0 flag4 = 0 flag6 = 0 flag7 = 0 flag8 = 0 flag9 = 0 flag10 = 0 flag11 = 0 coun = ...
b9162a92ccd91e5b7b8e6db6a7c34550eb7a7b3b
Exodus5656/hacktoberfest
/future_value.py
636
4.0625
4
'''Future Value function that I was working on.''' def main(): #Variables for the formula that can be found here #(http://financeformulas.net/Future_Value_of_Annuity.html) P = float(input("Enter your monthly investment into the account")) yearly_rate = float(input("Enter the percent of return. '10% = ...
598456d564fca4c32421dc2b4af4aaf46b8076b6
ThomasUren1/Practicals2019-CP1404
/Prac_4/list_exercises.py
1,642
4.09375
4
"""exercise in lists for Prac 04, CP1404""" ######################################################################################################################## # Part 1 - Basic list operations ################################################################################################...
5594045bc784e31df8c812fd45f49395189df99f
UjjwalGupta-Git/Vision-Assistant
/main/speechFunctions.py
1,912
3.59375
4
from PyDictionary import PyDictionary from playsound import playsound from gtts import gTTS import wikipedia import requests import platform import os import json # Function to convert text to speech def Speak(command): tts = gTTS(text=command, lang='en', slow=False) filename = "buffer.mp3" tts.save(filen...
838888a1bb8d41d46e1fcfa8f74ac05fb95fe150
wonjaeL/study
/phase03/animal.py
249
3.5
4
class Animal: def __init__(self, name, age, leg_count): self.name = name self.age = age self.leg_count = leg_count ## 다리개수를 출력하는 함수구현 def print_legs(self): print(self.leg_count)