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
1b7ac78ee87e9cc93e3a1b24b6956b7e30c53f5d
iHuntersteam/iHunters
/crawler/crawler_python/example_parse.py
790
3.796875
4
from parse import RobotsParser, SitemapParser import logging import sys """ Example of parsing 1. Parse robots.txt and search link on a sitemap inside. 2. Parse sitemap and print all url's from it. """ logging.basicConfig(level=logging.DEBUG, stream=sys.stdout) parsing_url = 'https://geekbrains.ru/' robots_reader = R...
13a4f8de9184906b08638353d56f6f8aefe5f6b4
vaemavric/Projects
/Python/cipheradv.py
6,379
4.375
4
#=-=-=-=-=-=-=-=-=-=-=-==-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=# # cipheradv.py # # a python script to encrypt and decrypt a message or file using a specified- # # cipher ...
8cfbb74f6e650961fcd5095616cf7efebf3b57e1
vaemavric/Projects
/Python/chess.py
13,832
3.90625
4
#!/bin/env python2.7 #=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-# # chess.py # # pyth...
e6365f84982e570816cb0843cc0ce3b24c04dc38
sazlin/data-structures
/dll.py
2,595
4.03125
4
class Node(object): def __init__(self, val, prev, next): self.val = val self.prev = prev self.next = next class DLinkedList(object): """A simple doubly linked list""" def __init__(self): self._head = self._tail = None self._size = 0 def insert(self, val): ...
db8a869acffea0a21b1a988e41c05724aafe2d34
bradfordrmc/Lab10
/lab10 pt1.py
377
4.09375
4
import matplotlib.pyplot as plt #imports the graphing function library plt.plot([0,1,2,3,4], [0,1,4,9,16]) #picks points on the graph using x and y coordinates with two arrays plt.ylabel('y') #label for the Y-axis of the graph plt.xlabel('x') #label for the X-axis of the graph plt.axis([0, 4, 0, 16]) #sets the scale fo...
ac25ca73d0bf56b3121dcd8c876bae987a961f94
lonperman/ProyectoIA
/BFS.py
4,620
3.640625
4
import queue ##El módulo queue implementa colas multi-productor y multi-consumidor. #Es especialmente útil en la programación en hilo cuando la información debe intercambiarse de forma segura entre varios subprocesos. matriz = [ ["3","2","1","3","*" ], ["3","#","0","3","3"], ["3","3","#","#","3"], ["3...
8364b704a8261dc3ffc774e747dfd430550cc587
jarmer7043/Functions_Parameters-Global_Variables
/diceRoller.py
1,748
4.21875
4
#Dice rolling program #Aim is to roll a 6 or roll a number twice in a row import random import time s1 = "- - - - -\n| |\n| O |\n| |\n- - - - -\n" #the dice prints s2 = "- - - - -\n| O |\n| |\n| O |\n- - - - -\n" s3 = "- - - - -\n| O |\n| O |\n| O |\n- - - - -\n" s4 = "- - - ...
e9e7349b0a6280829f827a0ece552c8b65b184b4
just-hg/Data-Structures-and-Algorithms
/排序/bubble_sort.py
289
3.71875
4
def bubble_sort(data): for i in range(len(data)-1,-1,-1):# 第一次扫描 n 个数,依次递减 for j in range(i): if data[j] >= data[j+1]: # 比较相邻的两个数 data[j],data[j+1] = data[j+1],data[j] # 满足条件则交换数据的位置
868dd764b8351cb936e4ea6642509b17ce42ff34
siavashhakim/Cracking_coding_intervew
/alter_sort.py
235
3.78125
4
def alter_sort(list): list.sort() output = [] for i in range(0,int(len(list)/2)): output.append(list[len(list)-i-1]) output.append(list[i]) return output list = [4,3,5,4,1,2,9] print(alter_sort(list))
c007219a3c64283b6685183944ae712ee41ae58f
temasuperstar/py
/ya.py
1,576
3.734375
4
# Задача-1: # Дан список фруктов. # Напишите программу, выводящую фрукты в виде нумерованного списка, # выровненного по правой стороне. # Пример: # Дано: ["яблоко", "банан", "киви", "арбуз"] # Вывод: # 1. яблоко # 2. банан # 3. киви # 4. арбуз # Подсказка: воспользоваться методом .format() s = ["яблоко", "банан", ...
3b5ff6ad01281b22e609b605a24ecfc50cde6a32
joserc87/pawn-puzzle
/pawn.py
2,855
3.96875
4
class Pawn: def __init__(self, name): self.name = name self.color = u'' self.position = (-1, -1) def can_move(self, row, col=None): p = row if col is None else (row, col) diff = (p[0] - self.position[0], p[1] - self.position[1]) return self.can_move_relative(dif...
f5ceb20aa8d65362feb31952d8519c6dc0aaa73c
davelnewton/online-classes
/udacity/cs373/unit01/1.6-generalized-uniform-distribution.py
277
3.875
4
# Multiplying a single-element array creates # a 1-d array containing the original element. # Initial code. n = 5 p = [1.0 / n] * n print p # Returns a uniform probability array of size n. def uniform_probability(n): return [1.0 / n] * n print uniform_probability(10)
01e8055ce77a801dda3c743d7759b18988587f2d
SiDdHaRtHrAjDaSh/hci-review3
/helpdesk.py
3,100
3.875
4
import speech_recognition as sr import pyttsx3 def SpeakText(command): # Initialize the engine engine = pyttsx3.init() engine.say(command) engine.runAndWait() r = sr.Recognizer() def helpdesk(): SpeakText("Welcome to the helpdesk! say list to get an idea of the commands avail...
ff308dfc41e11e9018fb1dcff547efe1b3fd11be
coffee-code88/python
/tic_tac_toe_board_full.py
2,284
4
4
from random import randint from time import sleep # init board db_list=[[0, 0, 0], [0, 0, 0], [0, 0, 0]] # print board with item in list def print_board(): for row in db_list: row = [str(i) for i in row] print " ".join(row) print db_list print_board() username = raw_input("Enter your name: "...
a7c82065a8ecec056c16283114e0c93d3d84e0c1
rhansolo/Collab-Code
/util/db.py
5,298
3.78125
4
import sqlite3 def create(): '''Creates db and sets up the three tables''' DB_FILE="discobandit.db" # db used for this project. delete file if you want to remove all data/login info. db = sqlite3.connect(DB_FILE) # Open if file exists, otherwise create c = db.cursor() # Facilitate db operations # Cr...
6d379d8e994fa589bd54c6c2377e731d56de4a45
NarutoScoo/facial_keypoint_detection
/models.py
11,143
3.609375
4
## Define the convolutional neural network architecture # This file contains multiple architecture, which were used while # building up to the final architecture # The one on top is the final architecture used import torch import torch.nn as nn import torch.nn.functional as F # can use the below import should you cho...
8b3e3533a7fe7c91e1b6c0ff39f914e300b18695
giko99/praxis-academy
/novice/01-01/list.py
1,128
4.0625
4
#list squares = [1, 4, 9, 16, 25] print (squares) print (squares[0]) print (squares[-1]) print (squares[-3:]) print ('______________________________________') print (squares + [36,49,64,81, 100]) print ('______________________________________') cubes = [1,8,27,65,125] print (cubes) cubes [3] = 64 print (cubes) cub...
d2e028bfc8bb528f5c553219e9303ee2d0e988c5
giko99/praxis-academy
/novice/03-02/logical_operator.py
116
3.953125
4
x = float(input ("enter the number : ")) print(x > 3 and x < 10) print(x > 3 or x < 4) print(not(x > 3 and x < 10))
cd7d4fe6d1a4d1472c49d12bf4f759977be05f96
giko99/praxis-academy
/novice/01-01/number.py
515
3.765625
4
#number print (2+2) print (50-5*6) print ((50-5*6)/4) print (8/5) print (17/3) print (17//3) print (17%3) print (5*3+2) print ('_____________________') #calculate power print (5**2) print (2**7) print ('_____________________') #equal sign width =20 height= 5*9 print (width*height) print ('_____________________') #f...
f472dc85204fbd4e1ca792dfae5988cb0afd0d88
Tavish-Jain/Python-Codes
/Character count.py
447
3.8125
4
a=input("Enter a string value: ") c=0 for i in range(65,91): b=chr(i) d=a.count(b) c+=d print("Number of capital letters is:",c) e=0 for i in range(97,122): b=chr(i) d=a.count(b) e+=d print("Number of Small letters is:",e) f=0 for i in range(0,10): b=str(i) d=a.count(b) f+=d print("N...
3bb3c0df5ed873e46efc6119292945c8a8b805e4
Tavish-Jain/Python-Codes
/Test.py
1,016
4.0625
4
print("first pattern") for a in range(1,7): for b in range(1,a): print(b,end="") print() print("\n") print("second pattern") i=int(input("enter a number")) a=0 for b in range(0,i+1): a+=b else: print(a) print("\n") print("third pattern") n=int(input("enter a number whos table should be displayed...
08aafab3d39b88e88835a2a215edb061808a8dd3
notariuss/pythonhw
/basics/ex8.py
176
3.75
4
#!/bin/python3.6 import random def game(start, end): random_int = random.randint(start, end) if int(input("Enter int: ")) == random_int: pass else print("Try again!")
f74a9179d69a3f625a19a7688a9ff452c2b2b651
samahmood1/Python-Basic
/for_challenge2.py
854
4.375
4
#!/usr/bin/env python3 farms = [{"name": "NE Farm", "agriculture": ["sheep", "cows", "pigs", "chickens", "llamas", "cats"]}, {"name": "W Farm", "agriculture": ["pigs", "chickens", "llamas"]}, {"name": "SE Farm", "agriculture": ["chickens", "carrots", "celery"]}] animals = ["cats", "chickens", "cows",...
9d9a858e694376a6f29541cfc54d21b8e49e44d8
Manbir-ss/Python
/python programme/count_4.py
219
3.734375
4
def count_list(nums): count=0 for num in nums: if num==4: count=count+1 return count print(count_list([1,4,6,7,4,6,4,8,4,9,4,2,4])) print(count_list([1,4,2,3,6,4,2,8,9,7,4]))
9ca92b5f121723702b7901dfa4d2d3f86885b077
rnagle/pycar
/project1/step_2_complete.py
810
4.25
4
# Import built-in python modules we'll want to access csv files and download files import csv import urllib # We're going to download a csv file... # What should we name it? file_name = "banklist.csv" # Use urllib.urlretrieve() to download the csv file from a url and save it to a directory # The csv link can be found...
26de134f97c2e8fc59d344048c9e66e5b382fad5
vivekbhadra/python_samples
/problem_of_escaped_sum.py
712
3.828125
4
''' SUMMER OF '69: Return the sum of the numbers in the array, except ignore sections of numbers starting with a 6 and extending to the next 9 (every 6 will be followed by at least one 9). Return 0 for no numbers. ''' """ Spyder Editor This is a temporary script file. """ def summer_69(mylist): flag = False ...
2f00505d175bd72b047b898d367fc9a201b9c0e8
vivekbhadra/python_samples
/count_prime.py
684
4.125
4
''' COUNT PRIMES: Write a function that returns the number of prime numbers that exist up to and including a given number count_primes(100) --> 25 By convention, 0 and 1 are not prime. ''' """ Spyder Editor This is a temporary script file. """ def isprime(num): flag = True for n in range(2, (num // 2) + 1): ...
4c07369fa09da1872a5a354fa0223fe5d4a6f6b0
mike-jolliffe/GSI
/WaterData/NWIS_getter.py
1,677
3.578125
4
import requests import json class Getter(): """Get specified data via USGS's NWIS API""" def __init__(self, bbox, type='S', start_date=None, end_date=None): self.base_url = 'https://waterservices.usgs.gov/nwis/dv/?format=json' self.type = type self.headers = { "Accept-Encoding": "gzip, d...
e65fc3402480b5d09d574edca7732fce3e28f7f5
mmhorst/top10
/gettweets.py
6,956
3.8125
4
# This script gathers Tweets using a Twitter API and counts the most common # content words from two different twitter handles specified by the user. # Excludes stopwords, URL links, hashtags, retweets, and mentions (@example) from word counts # The script then displays the top ten most frequent words in a bar plot. # ...
3ce88c331e657667ce39650478fc4b0526a69af1
constant-learning/Dobble
/dobble.py
12,918
4.03125
4
#Dobble generator to store 57 unique cards in a dictionary with keys of 1 -57 and values of sets # all of which are related by only one card # figure out what numbers to write on each card nIm = 8 n = nIm - 1 r = range(n) rp1 = range(n+1) c = 0 dict_card_nums = {} # instruction dictionary - crack the code num_set = ...
e56fe33e23be731de75a530f6dd0073fabebfc15
hbariki/Algorithms-and-Datastructures
/question5.py
1,006
3.984375
4
class Node(object): def __init__(self,data): self.data = data self.next = None class LinkedList(object): def __init__(self,head=None): self.head = head self.length = 1 def append(self, new_element): current = self.head if self.head: while current....
7c17a65ad812f60e2a73af5156368ecfe8d70317
jfxugithub/python
/面向对象的高级编程/createClassDynamic__type.py
970
3.640625
4
""" 动态创建类: type(类名,父类集合,属性字典) 类名:动态创建类的名字 父类集合:创建的类所要继承的父类set集合,可以为空 属性字典:创建属性,已字典的形式入参 """ """=====================添加属性=====================""" People = type("People", (), {"name": "小东", "sex": "woman"}) peo = People() print(peo.name, ":", peo.sex) """=====================添加继承=====================""...
0f9c5818d270deb7ac1d18e8538656c23d57f76d
jfxugithub/python
/面向对象的高级编程/多重继承.py
559
3.953125
4
#!/usr/bin/evn python3.5 # -*- coding: utf-8 -*- ################################# #和java不同的是Python是可以多重继承的 ################################# class Animal(object): type = 'animal' class Runable(object): def run(self): print('I can run...') class Dog(Animal,Runable): def __init__(self): se...
2d9c5c0675d2f9c99dc74b539bf7e5d411327dad
jfxugithub/python
/面向对象编程/类和实例以及访问控制/Student.py
2,456
3.96875
4
#!/usr/bin/evn python # -*- coding: utf-8 -*- ######################################################### #类的定义方式如下: # 关键字 类名(继承对象名): # pass #如果没有具体的继承对象就填写object,这是所有的类最终都会继承的类 ################################################### ''' class Student(object): name = '' age = 0 sex = '' score=0 d...
3b638c7d702fcb837b861dadd24082da060f487c
jfxugithub/python
/面向对象编程/继承和多态/Animal.py
1,376
4.09375
4
#!/usr/bin/evn python # -*- coding: utf-8 -*- ############################# #定义一个父类 ############################# class Animal(object): def run(self): print('Animal is running') ############################# #定义两个个Animal的子类 #覆盖run方法,实现多态 ############################# class Dog(Animal): def run(self): ...
50cb4c163fc222e1f3b33cf9ab80e185647b42db
jfxugithub/python
/debug.py
534
3.890625
4
""" 断言: asset 判断条件,提示信息 如果不满足判断条件就会报错 """ import logging import pdb def get_num(nu): assert nu != 0, 'nu 不能等于0' return 10 / nu # get_num(0) print("=" * 30) """ logging """ logging.basicConfig(level=logging.INFO) for i in range(10): logging.info(i) print("=" * 30) """ pdb:python 自带模块 """ d...
559e6721d46d0156427efb46a07815d8852c85d8
jfxugithub/python
/面向对象的高级编程/staticmethod.py
475
4.15625
4
""" 静态方法定义: 通过修饰器staticmethod来进行修饰,可以不用传参数,第一参数默认为cls 加载时机:随着类的加载而加载 """ class Student: address = "太阳系" def __init__(self, name, age): self.name = name self.age = age @staticmethod #修饰静态方法 def get_address(): return Student.address print(Student.get_addr...
8ac54294c6679b0478ead656acd08d3fc8b19cb8
DracoKali/python_demo
/ScoresAndGrades.py
549
4.03125
4
import random def scores_grades(TestScore): score = random.randrange(60, 100) if (score <= 69 and score >= 60): print 'Score:', score, '; Your score is D' elif (score <= 79 and score >= 70): print 'Score:', score, '; Your Score is C' elif (score <= 89 and score >= 80): print 'Sc...
c2584885ffe0c36a368361fb12220c4263d80ad2
Daomaster/GradeTrack
/util/school-randomizer/_student.py
2,326
3.609375
4
import json import _course import _grade class Student(): def __init__( self, _id, first = "Student\'s first Name", last = "Student\'s Last Name" ): self.id = _id self.first = first self.last = last self.courses = {} self.grades = {} def add( self, item ): if i...
717f322356962fb6fd13819bdeb5f133f56a0553
Mathtzt/Python
/collections/src/Collections-pt1/aula2.2.py
1,502
4.34375
4
##Esse arquivo foi criado para o estudo das Coleções no python em especial as listas e tuplas. from abc import ABCMeta, abstractmethod, ABC class Conta(metaclass=ABCMeta): def __init__(self, codigo): self._codigo = codigo self._saldo = 0 def deposita(self, valor): self._saldo += valo...
3c043341d16e6c27c947230779d248f00b72a6c6
glennpantaleon/python2.7
/doughnutJoe.py
2,197
4.4375
4
''' A program designed for the purpose of selling coffee and donuts. The coffee and donut shop only sells one flavor of coffee and donuts at a fixed price. Each cup of coffee cost seventy seven cents and each donut cost sixty four cents. This program will imediately be activated upon a business. \/\/\/\\/\/\/\...
2fcc9e48ca762b7ce8a7818e567c956e82427a36
rlhjansen/zsb_halma
/zsb2/class_independent_functions.py
1,535
3.546875
4
# translates a movestring, i.e. f4a1, to coordinate set i.e. [[5,3],[0,0]] def to_coordinates(movestring, boardsize): startpoints_x = [] startpoints_y = [] x_coords = [] y_coords = [] returnlist = [] for i in range(len(movestring)): if not movestring[i].isdigit(): startpoint...
2f8861a8d5d3c2d1697436e94c4ebd6da2f36316
miblazej/pie
/lista_start_stop.py
3,366
3.65625
4
from list1 import ListNode from lists_function import add_end # Funckja przyjmujaca trzy elementy : # Pierwszy czlon listy # start oraz stop, elementy listy od start do stop wlacznie powinny miec zamieniona kolejnosc # pierwszy element czlonu listy ma indeks jeden zakladam ze glowa nie jest pustym elementem def odwr...
3ad5238209acc1b4ab1061b19b89412b3c2a4114
miblazej/pie
/list1.py
555
3.953125
4
# linked list exercises class ListNode: def __init__(self, data=0, next_node = None): self.data = data self.next = next_node return def merge_lists(L1, L2): # stworzyc pierwszy element listy dummy_head = tail = ListNode() while L1 and L2: if L1 < L2.data: ...
1bf0f3611ba809c9cd4630bcf7484dd72607da8c
miblazej/pie
/rearenge.py
117
3.625
4
def rearange(A): for i in range(len(A)): A[i:i + 2] = sorted(A[i:i + 2], reverse=i % 2) return A
02287045fa63bfadccbaad71e9f60e68996d6baf
Albkset/Assessment-2real
/Assessment 2/Lucky-uncicorn.py
293
4.03125
4
# Ask the user if they have played before' question = input("HAVE YOU PLAYED BEFORE " + "YES, NO").lower() #If they say yes, out 'program continues' if question == "yes": print("program continues") # If they say no, output 'display insturctions' else: print("display instructions")
b61ab3fc3c7c7e16749e216a51e90c3eea0a30dc
NBerlin/LearningPython
/Shit/Primtal.py
291
3.875
4
def prime(number): oldnum = number factor = 1 while number > 1: factor += 1 if number % factor == 0: if 1 < factor < oldnum: return False number //= factor return True for x in range(1,int(input())): print(prime(x))
524ef43044aecfce1db501fd999d7095af765dce
erickclasen/PMLC
/activations/sigmoid_orig.py
1,042
3.59375
4
import numpy as np from matplotlib import pyplot as plt #### Miscellaneous functions def sigmoid(z): """The sigmoid function.""" return 1.0/(1.0+np.exp(-z)) def sigmoid_prime(z): """Derivative of the sigmoid function.""" return sigmoid(z)*(1-sigmoid(z)) #----------------------------------------- for ...
7f7d73dd0b2be68187d745c8a3893d52a587a2e3
erickclasen/PMLC
/xor/xor_nn_single_layer.py
1,571
4.21875
4
import numpy as np # sigmoid function def nonlin(x,deriv=False): if(deriv==True): return x*(1-x) return 1/(1+np.exp(-x)) print("XOR: With a hidden layer and the non-linear activation function on the output layer.") print("Fails!") ''' 2 inputs 1 output l0 is the input layer values, aka X l1 is the hi...
0e201fb73204fb9a639b99b863e1237406b152c6
XSpursJ/100PythonExercises
/answers/q14.py
211
3.90625
4
userInput = input('Please enter a line:') uc = 0 lc = 0 for c in userInput: if c.isupper(): uc += 1 if c.islower(): lc += 1 print('Upper case:' + str(uc)) print('Lower case:' + str(lc))
f5cc27cc743d6a47ab67f848babb2658bc47bf21
XSpursJ/100PythonExercises
/answers/q34.py
116
3.765625
4
def printD(): d = {} for x in range(1, 21): d[x] = x**2 for x in d: print(x) printD()
19f4e12e0bf048cbcec20190c90e180b6b11abf3
XSpursJ/100PythonExercises
/answers/q66.py
139
3.546875
4
def myGenerator(n : int): for x in range(n + 1): if x % 2 == 0: yield x l = [x for x in myGenerator(10)] print(l)
86b747b0c91df1922970e406030cadc1a71dff4c
XSpursJ/100PythonExercises
/answers/q36.py
125
3.765625
4
def printL(): l = [] for x in range(1, 21): l.append(x) for x in range(5): print(l[x]) printL()
c224d606eae3bfa8d1fd7f976084da3a548da1e9
XSpursJ/100PythonExercises
/answers/q91.py
319
3.53125
4
class Person(): def getGender(self): return 'unknown' class Male(Person): def getGender(self): return 'Male' class Female(Person): def getGender(self): return 'Female' my1 = Person() print(my1.getGender()) my2 = Male() print(my2.getGender()) my3 = Female() print(my3.getGender())
1dce6ba1cb12ed8d6a441b697dfe7a725bb57b89
XSpursJ/100PythonExercises
/answers/q3.py
282
3.953125
4
tempNumber = 0 try: tempNumber = int(input('Pelase type a positive integer:')) except: print("Invalid input.") d = dict() if(tempNumber > 0): for i in range(1, tempNumber + 1): d[i] = i * i print(d) else: print("You need to enter a positive integer.")
c0675f554761dc69a5af52cedb45ad4e7bca5312
EricWord/PythonStudy
/17-exception/exception_demo7.py
425
3.75
4
class LengthError(Exception): def __init__(self, x, y): self.x = x self.y = y def __str__(self): return "长度必须要在{}至{}之间".format(self.x, self.y) password = input("请输入您的密码:") m = 6 n = 12 if m <= len(password) <= n: print("密码正确") else: # 使用raise关键字抛出一个异常 raise LengthError(m, ...
36e12284f8456141abeebea884b7b18720ac35ac
EricWord/PythonStudy
/06-in/in_demo.py
228
3.890625
4
word = 'hello' x = input("请输入一个字符:") # 判断用户输入的字符在字符串里是否存在 for c in word: if x == c: print("你输入的内容存在!") break else: print("不存在")
69f69f00c1ab48c332d0456a508cf6a37d8eac41
EricWord/PythonStudy
/19-regex/regex_demo3.py
535
3.5625
4
import re m = re.search(r"m.*a", "o3rjomjadas") # 匹配到的结果字符串的开始和结束下标 print(m.span()) # 获取匹配的字符串结果 print(m.group()) # group方法表示正则表达式的分组 # 1.在正则表达式里使用()表示一个分组 # 2.如果没有分组,默认只有一组 # 3.分组的下标从0开始 # groupdict作用是获取到分组组成的字典 # (?P<name>表达式) 可以给分组起一个名字 # 通过名字获取到的是一个字典 # 通过下标获取到的匹配到的字符串
6a30f9875e5957d261d87f1cfebc9b545a47f36d
EricWord/PythonStudy
/06-in/in_demo2.py
149
4.09375
4
word = 'hello' x = input("请输入一个字符:") if word.find(x) == -1: print("您输入的内容不存在!") else: print("存在!")
528fe10a3837b48c23906ea6f329a27306c1d8b7
EricWord/PythonStudy
/16-file/file_demo8.py
1,317
3.59375
4
import json file = open("names2.txt", "w", encoding="utf8") # file.write("张三") # write时,只能写入字符串或者二进制 # file.write(12) # 类似字典、列表、数字等都不能直接写入到文件里 # 想要写入上述内容的话有两种方法: # 第一种方法:将数据转换成为字符串 使用repr/str 更多的情况是使用json # json的本质就是字符串,区别在于json里要使用双引号表示字符串 # 第二种方法:将数据转换称为二进制 使用pickle模块 names = ["张三", "tom", "jack", "lily"] # json里将...
f020ba2c7f5fb2fbe2aeac267f325ae8cb8a5421
EricWord/PythonStudy
/13-func/func_demo.py
892
3.625
4
def say_hello(name, age, city="深圳"): ''' say hello :param name: :param age: :param city: 缺省参数,只能放在参数列表中最后一个位置 :return: ''' print("大家好,我是{},我今年{}岁了,我来自{}".format(name, age, city)) # 如果没有传递缺省参数的值,就是用缺省参数的默认值 say_hello("jack", 19) # 大家好,我是jack,我今年19岁了,我来自深圳 # 如果传递了缺省参数的值,就是用传进来的值 say_hel...
74448ee6579f6583b3a4e84961daaec0ca4e17be
EricWord/PythonStudy
/03-while/while_demo.py
146
3.828125
4
x = 0 while x < 10: print("hello,world") x += 1 print("--------------") i = 1 sum = 0 while i <= 100: sum += i i += 1 print(sum)
e8ba7790392eb1d931ae5789dfe4e3dd61ee1e79
EricWord/PythonStudy
/08-list/list_demo10.py
554
3.90625
4
import copy # 浅拷贝 nums = [1, 2, 3, 4, 5] nums1 = nums # 这个既不是深拷贝也不是浅拷贝 nums2 = nums.copy() # 浅拷贝 ,两个内容一模一样,但是不是同一个对象 nums3 = copy.copy(nums) # 和 nums.copy()功能一样,都是浅拷贝 # 深拷贝只能使用copy模块来实现 words = ["hello", "good", [100, 200, 300], "yes", "hi", "ok"] # words1是word的浅拷贝 words1 = words.copy() # words[0] = "你好" # words[2...
96f687733caa4f952d87cc4c778d98ca72448e7e
EricWord/PythonStudy
/19-regex/regex_demo2.py
421
3.625
4
# 正则查找相关的方法 import re m = re.match(r"hello", "world hello good morning") print(m) m = re.search(r"hello", "world hello good morning") print(m) m2 = re.search("x", "sdgfjhsdlxxvsllxjlxjxgixguitxcvxgtix") print(m2) m3 = re.finditer("x", "sdgfjhsdlxxvsllxjlxjxgixguitxcvxgtix") print(m3) for t in m3: print(t) prin...
d4c087281c53abba01592cbdea52519f20505bae
EricWord/PythonStudy
/20-thread/thread_demo6.py
522
3.609375
4
# 进程之间通信 import os, multiprocessing from queue import Queue def producer(x): for i in range(10): print("生产了++++++++pid{} {}".format(os.getpid(), i)) x.put("pid{} {}".format(os.getpid(), i)) def consume(x): for i in range(10): print("消费了--------{}".format(x.get())) if __name__ == "_...
b97c82a755402de4122da0ea3aabece8555100a8
Covvperwood/my_python
/kt1_Теряев_Артем.py
1,208
3.890625
4
try: ##конструкция для обнаружения ошибок о неисправности файла filepath = 'file.txt' with open(filepath, 'r') as fio: result = fio.readlines() except BaseException as e: print("Сведения об ошибке", e) import csv def csv_reader(file_obj): with open(file_obj) as csvfile: ##Стандартные действ...
e3a5b0dc55063c453af118723a1ad7f55ac9410b
MasterCoookie/tensorflow
/image_classification.py
2,574
3.859375
4
'''Learning to classify images using fashion mnist (Recognizing elements of clothing). While preping the data we need to change to remove the saturation making each pixel either 0 or a 1. ''' import PIL.ImageOps import tensorflow as tf import numpy as np import matplotlib.pyplot as plt from PIL import Image from skim...
7af9b51d53e482d6350549746b2114d49231007f
LouisaJohnston/whiteboard-wednesday-count-of-pos-and-sum-of-negs
/solution.py
335
3.53125
4
def count_positives_sum_negatives(arr): if arr == []: new_array = [] return new_array else: pos_sum = 0 neg_sum = 0 for i in arr: if i > 0: pos_sum += 1 else: neg_sum += i new_array = [pos_sum, neg_sum] r...
ab10d9f94b703a34ead4ce8fb9c43aedd9e09eed
2000Varun/GUI-Stopwatch-with-Python
/Stopwatch.gui.py
1,420
3.5625
4
# -*- coding: utf-8 -*- """ Created on Sat Apr 4 19:44:36 2020 @author: Navee """ import tkinter as tk import tkinter.font as TkFont from datetime import datetime def run(): current_time = datetime.now() diff = current_time-start_time txt_var.set('%d.%02d' %(diff.seconds,diff.microseconds/...
cccef19a22c207f3e2e9ef362926c49f0fdf7296
open-nlp/leetcode
/easy/26.remove_duplicate_from_sorted_array.py
1,316
4
4
#!usr/bin/env python # -*- coding:utf-8 -*- """ @author:junxu @email: xujunrt@163.com @time: 2019-03-08 18:50 """ """ Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length. Do not allocate extra space for another array, you must do this in place with...
e58c9a043715a93e4169a2724a1de6b940d316a3
DavTho1983/Classes
/circle.py
295
3.890625
4
class Circle() : pi = 3.14 def __init__(self, radius) : self.radius = radius def area(self) : return (self.radius**2)*Circle.pi def set_radius(self, new_r) : self.radius = new_r myc = Circle(3) myc.set_radius(999) print(myc.radius) print(myc.area())
5a9568556b0b17e3a2f0d65b1b29896dfa30eda2
alby5062/TwitterAnalyzer
/Function/Punctuation_mark.py
488
3.515625
4
from termcolor import colored def punctuation_mark(sentences): result_pm = [] punctuation_marks = [',','?','!','.',';',':','\\','/','(',')','&','_','+','=','<','>','"'] for s in sentences: new = s for p in punctuation_marks: if new.find(p) > -1: new = ...
f2df8fbf7a32a1d88b97d0bc4bc41a6ece7df77a
lucarp/ter-sentiment-analysis
/Algorithms/confusion_matrix.py
2,553
3.578125
4
import numpy as np import matplotlib.pyplot as plt def plot_confusion_matrix(cm, normalize=False, title=None, cmap=plt.cm.Blues, target_names=None): """ This function prints and plots the confusion matrix. ...
1b544dd9bf6518a53f3e272e66d8c914fcad09f0
kriksorum/decrypt
/GammaCode.py
884
3.53125
4
alphabeth = "абвгдеёжзийклмнопрстуфхцчшщъыьэюя 0123456789" def decrypt(code, gamma): codeLen = len(code) gammaLen = len(gamma) #Формируем ключевое слово(растягиваем гамму на длину текста) keyText = [] for i in range(codeLen // gammaLen): for symb in gamma: keyText.append(symb) ...
031ef3667a7c4fa777f136d34e583261f4c47ad4
AlejandroSotoCastro/adventofcode-2018
/12.py
2,131
3.53125
4
f=open("6.txt","r")#abrir el documento y guardar linea a linea en una lista. #f=open("6prueba.txt","r") lista=f.readlines() #separar coordenadas x y for n in range(len(lista)): lista[n]=lista[n].split(", ") lista[n][0]=int(lista[n][0]) lista[n][1]=int(lista[n][1]) def mandis(a,b): a[0]=(a[0]) a[1]=(a[1]) b[0...
ab1fbeffa9256813783f94277a97d0e03845c172
CodeBattleCommunity/codebattle-bomberman-clients-2020
/CodeBattlePython/codebattleclient/internals/Board.py
4,305
3.5625
4
from math import sqrt from codebattleclient.internals.Element import Element from codebattleclient.internals.Point import Point class Board: """ Class describes the Board field for Bomberman game.""" def __init__(self, board_string): self._string = board_string.replace('\n', '') self._len = ...
5877fc07af787c39d19f4427cef1173258d224e5
q654528967/Demo
/python/demo20_args.py
367
3.78125
4
def indexOf(myList,index,*start): if len(start)>0: for key in range(start[0],len(myList)): if(myList[key]==index): return myList[key] else: return -1 else: for key in range(len(myList)): if(myList[key]==index): return myList[key] else: return -1 result...
4c9382265d81b118fa223f14ed09323ed9cb628e
q654528967/Demo
/python/demo13_operators.py
204
3.640625
4
count=0 count+=1 num1=int('1011100',2) num2=int('0001011',2) print(num1&num2) print(num1|num2) name1='jack' name2='tom' print(name1 is name2) myList1=[1,2,3] myList2=[1,2,3] print(id(myList1),id(myList2))
e6d35fe1778ac718abac4c2a4d777bae33ea0977
q654528967/Demo
/python/demo22_keywords.py
188
3.59375
4
#默认值参数 def myFunc(arg1,arg2=6): print(arg1,arg2) myFunc(2) myFunc(5) myFunc(6) myFunc(2,5) #g关键字参数 def keyWord(arg1,arg2): print(arg1,arg2) keyWord(arg2=10,arg1=2)
79c0650d09d0c2d530ac4b2e1bdf49965d01de25
yhindy/wallscraper
/wallscraperutils.py
1,392
3.546875
4
""" This module contains methods that are useful for the wallscraper.py module. """ import requests import time baseurl = 'https://www.reddit.com/r/' def query(subreddit): """ This functions takes a subreddit and returns the json data by using the requests library to download the data from a specifi...
a7a210d85a8be29fc15cd4d3b5daf5f35f19ffd0
jiyeonBaek/2015Python
/PLec1/PLec1/PLec1.py
689
3.890625
4
#print("Here are the num! {0:d},{1:4d}. ".format(7,8)) #ctrl+kc : 주석처리 ku : 주석해제 #salary=int(input("Please enter your salary : ")) #bonus =int(input("Please enter your bonus : ")) #paycheck = salary + bonus #paycheck2=float(salary) + float(bonus) #print(paycheck) #print(paycheck2) #print(type(paycheck)) #num=5.67 #p...
240e5c872c22040dccbabc263201f9e8bd006b81
Drummerboy444/memoization_speed_test
/factorial.py
207
3.984375
4
def list_factorial(numbers): results = [] for n in numbers: results.append(factorial(n)) return results def factorial(n): if n is 0: return 1 return n * factorial(n - 1)
8d764d588205566023cde227edd314455cf89a6d
mariavidrasc19/plusivo-tutorials
/RPI Lesson 02 Dim an LED/main.py
1,583
4.09375
4
from time import sleep #we import the sleep module from the time library import RPi.GPIO as GPIO #we import the RPi.GPIO library with the name of GPIO GPIO.setmode(GPIO.BOARD) #we set the pin numbering to the GPIO.BOARD numbering #for more details check the guide atached to this code GPIO.set...
c2b9f5c03a258fb31df5917fa17864cd1368268d
mariavidrasc19/plusivo-tutorials
/RPI Lesson 04 Dimming an RGB LED/main.py
2,959
3.96875
4
from time import sleep #we import the sleep module from the time library import RPi.GPIO as GPIO #we import the RPi.GPIO library with the name of GPIO GPIO.setmode(GPIO.BOARD) #we set the pin numbering to the GPIO.BOARD numbering #for more details check the guide attached to this code GPIO.se...
277fcc4c6dd5ae9d85ad2ef6ba08201158dcc214
mariavidrasc19/plusivo-tutorials
/ESP Lesson 02 Dim an LED/main.py
837
3.96875
4
#use these libraries to declare used pins and PWM from machine import Pin, PWM #for delay from time import sleep #first, define the pins used by the led LED = Pin(12, Pin.OUTPUT) #D6 #and the pwm for led pwm = PWM(LED) #for board execute the instructions continuously we make an infinite loop while True: #PWM is g...
a9d70691a2c7e14dc2f5b42e13d4862423e5d49e
mariavidrasc19/plusivo-tutorials
/ESP Lesson 06 RGB LED and Ultrasonic/main.py
2,046
3.671875
4
#use these libraries to declare used pins from machine import Pin, PWM import machine #for delay from time import sleep import time #utime is an library used for getting the current time and date #measuring time intervals, and for delays import utime #set the mode of the pins used by the RGB LED as OUTPUT red = Pin(12...
d913750edf0540313f824f0d9645963885a23d8b
xuzhuzhuzi/mark-in-time
/rules.py
1,970
3.75
4
class Rule: """ the base class of all rules """ def action(self, block, handler): handler.start(self.type) handler.feed(block) handler.end(self.type) return True class HeadingRule(Rule): """ the title takes one line, and it`s less than 70 character, and ...
4bd8c946e94a55a9021e9abf6e93eb464bb206a7
simsab-ufcg/ndvi-finder
/modules/errorHandler.py
768
3.515625
4
def throwError(step, code): ''' Takes a code of error and print its message (in case of a known error). In case of a unknown error, halts program execution. ''' exit_code = (code >> 8) signal_code = (255 & code) switch = { (1 << 3): 'Could not open TIFF file.', (2 << 3): 'Could not read from TIFF file.', ...
4c3373988da231ad5ad845499acbb46d48b1e6b8
ishanparikh/Predicting-Corporate-Bankruptcy-using-Ensemble-Learning
/logistic_regression.py
5,436
3.53125
4
###### importing libraries ################################################ import math import numpy as np from sklearn.base import BaseEstimator from sklearn.base import ClassifierMixin """ This script holds all the classes needed, to build the LogisticRegression. """ ###### logistic regression ###############...
68f9ddea5bf2e090210ea9cb0da3c3f3184ace7b
danielalienyi/word-link-puzzle-python
/word_puzzle.py
2,849
3.890625
4
def getWords(): # Opens a file named 'words.txt' and extracts all the words in it as list # 'words.txt' contains 50000+ dictionary words filename = "words.txt" fh = open(filename,"r") # read file words = fh.readline().split(" ") # read the content and split into list f...
71716899604df84cc40aa5650cad8dc91df5c05c
shouvikbj/IBM-Data-Science-and-Machine-Learning-Course-Practice-Files
/Python Basics for Data Science/loops.py
532
4.34375
4
num = 2 # for loop in a range for i in range(0, num): print(i + 1) for i in range(num): print(i + 1) # for loop in case of tuples names = ("amrita", "pori", "shouvik", "moni") for name in names: print(name) # for loop in case of lists names = ["amrita", "pori", "shouvik", "moni"] for name in names: ...
50ddad96e2ec171219c8ccfe97514d274e1860c8
bibliotecadebabel/EvAI
/Factory/AbstractFactory.py
283
3.625
4
from abc import ABC, abstractmethod class FactoryClass(ABC): def __init__(self): self.dictionary = {} self.createDictionary() @abstractmethod def createDictionary(self): pass def findValue(self, key): return self.dictionary[key]
531886a8fc26e213ee98a5de9a2310308bb0b33d
RuomeiYan/CCC-My-solutions
/2005/05-J2.py
325
4
4
print("Enter lower limit of range") l = int(input()) print("Enter upper limit of range") u = int(input()) n = 0 for i in range(l,u+1): count = 0 for j in range(2,i): if i % j == 0: count += 1 if count == 2: n += 1 print("The number of RSA numbers between",l,"and",u,"i...
a2ffb096ad9f144fb6e19aaf0608819ac9322df4
RuomeiYan/CCC-My-solutions
/2007/07-J4.py
226
4.0625
4
a = input("Enter first phrase> ") b = input("Enter second phrase> ") a = sorted(list("".join(a.split()))) b = sorted(list("".join(b.split()))) if a == b: print("Is an anagram.") else: print("Is not an anagram.")
fc242d1dbf25c3fca401aa9df9283ca868419d33
RuomeiYan/CCC-My-solutions
/2005/05-S1.py
606
3.5
4
t = int(input()) keyboard = {"ABC":2, "DEF":3, "GHI":4, "JKL":5, "MNO":6, "PQRS":7, "TUV":8, "WXYZ":9} numbers = [] for _ in range(t): numbers.append(input()) numbers[-1] = numbers[-1].replace("-", "") for i in range(t): temp = "" for j in range(10): if numbers[i][j].isdigit(): ...
7ce90dc3e4f6601d8960c78c5b5c649265d4d6a4
RuomeiYan/CCC-My-solutions
/2010/10-J1.py
144
3.890625
4
n = int(input()) if n == 1 or n == 9 or n == 10: print(1) elif n == 2 or n == 3 or n == 7 or n == 8: print(2) else: print(3)
a9473563a5bd07c97a76189d2996a5d09d39702f
RuomeiYan/CCC-My-solutions
/2006/06-J2.py
413
3.765625
4
x = int(input("Enter m: ")) y = int(input("Enter n: ")) def way(m, n): if n >= 10: return "There are 9 ways to get the sum 10." if m > 9: m = 9 n = n+m-9 if n == 1: return "There is 1 way to get the sum 10." if n < 0: n = 0 return "There are "+str(...
1d43f400384e06b2f2f80f7cf825dd2e5409cd1f
RuomeiYan/CCC-My-solutions
/2006/06-S2.py
303
3.921875
4
plain = input() cipher = input() encrypted = input() tran = {} for i in range(len(plain)): if "A" <= cipher[i] <= "Z" or cipher[i] == " ": tran[cipher[i]] = plain[i] for i in encrypted: if i in tran.keys(): print(tran[i], end="") else: print(".", end="")
ec0bea079ae5dd31a1bde2a74bf2646beee4fce8
RuomeiYan/CCC-My-solutions
/2009/09-J4.py
863
3.546875
4
text = ["WELCOME", "TO", "CCC", "GOOD", "LUCK", "TODAY"] w = int(input("Enter w: ")) while text: t = [] s = [] l = w+1 # Put the maximum amount of words into the current line while text and len(text[0]) < l: t.append(text[0]) s.append(".") l -= len(text[0])+1 ...
bf17cae741ab0e46989d8e99c72f7eb4ef7bad61
hemanthpratury/Data-Structures-Solving-Using-Python
/Array Sequences/ArrayPairSum_sol2.py
458
3.6875
4
def pair_sum(arr,sum): seen = set() output = set() for ele in arr: print('element: %s' %ele) target = sum-ele print('target: %s' %target) if target not in seen: seen.add(ele) print('seen %s' %seen) else: output...