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 |
|---|---|---|---|---|---|---|
d21654d6676a801a7bcd687ab4a258c83a5f26f6 | afterlunch/cybersec | /sem1/maths/P2CSN17003/3Second.py | 392 | 3.84375 | 4 | #prime number or not
m=input("Enter a number : ")
flag=0
if m<0:
print "Prime Numbers should be +ve"
exit(0)
if m>1000000 :
print "Out of limit exeeded 10^5"
exit(0)
if m==1 or m==0 :
print m,"is niether prime nor Composite"
exit(0)
for i in range(2,(m/2)+1):
if m%i==0:
flag=1
break
if flag==0:
... |
536ac6bb3f18dd56c5696a4a6c5331b08925b84a | afterlunch/cybersec | /mypy/codeforces/chatroom.py | 124 | 3.8125 | 4 | s=raw_input()
ab=set(s)
sr="hello"
abc=set(sr)
if ab-abc:
print"YES"
else:
if(abc==ab):
print"NO"
else:
print"YES"
|
d82dae3305cc188c6fc0c4137a8ce948194b02bf | rodhoda2020/PyCharm-Library | /Personal Projects/Data_Cleaning.py | 2,763 | 3.59375 | 4 | import pandas as pd
import numpy as np
import re
df = pd.read_csv(r'C:\Users\Rod Hoda\Documents\PyCharm\BL-Flickr-Images-Book.csv')
# with pd.option_context('display.max_rows', None, 'display.max_columns', None):
# print(df.head())
to_drop = ['Edition Statement',
'Corporate Author',
'Corpora... |
62c53cc383e7d637f36789721777fc3552ae278c | rodhoda2020/PyCharm-Library | /Personal Projects/Click_Counter.py | 555 | 3.5 | 4 | import tkinter as tk
from tkinter import ttk
count = 0
def clicked(): # without event because I use `command=` instead of `bind`
global count
count = count + 1
label1.configure(text=f'{count} accounts completed')
windows = tk.Tk()
windows.title("Click Counter")
label = tk.Label(windows, text="Click ... |
e25f09b3df43066e0c3fa6efd53e918b86c64c25 | rodhoda2020/PyCharm-Library | /Python_Data_Science_Handbook/NumPy/Intro_to_NumPy.py | 32,382 | 4.09375 | 4 | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn; seaborn.set()
def Fixed_Type_Array_in_Python():
# This was the traditional way of writing arrays
import array
L = list(range(10))
A = array.array('i', L)
print(A)
# 'i' is to indicate the contents are intege... |
47b6d9d3e18a539cb26fe66604cbb6bbc2ce8450 | kayleenliu/password_retry | /password.py | 412 | 4.03125 | 4 | # test password
password = 'a123456'
p = input ('input your password please:')
n = 3
while n > 0:
n = n - 1
if p == password:
print('access successfully')
break
else:
if n > 0:
print('password is not correct! you have', n, 'trials left')
p = input ... |
bcad3a96a4910421a5da8ef0ec363ded61caa4c7 | saiprasad88/python | /test18.py | 164 | 3.8125 | 4 | friends =["John", "Jim", "Phillip","Michel", "pierre"]
print(friends[-1])
print(friends[1:])
print(friends[1:3])
friends[1]= "Mike"
print(friends[1])
print(friends) |
bc6bd24382630f127b8c95f7a80f7e8302decb3e | dallonf/advent-of-code-2018 | /pysrc/challenges/day_12_subterranean_sustainability.py | 4,176 | 3.5 | 4 | import re
from typing import Dict, List, NamedTuple
Pots = Dict[int, bool]
Rules = Dict[str, bool]
class Input(NamedTuple):
initial_state: Pots
rules: Rules
test_input = """initial state: #..#.#..##......###...###
...## => #
..#.. => #
.#... => #
.#.#. => #
.#.## => #
.##.. => #
.#### => #
#.#.# => #
#.##... |
b2fbd75dc3955daea5e7330b9fb7f530b4444224 | jsrv/Algorithms_Fall_16 | /oop.py | 6,795 | 4.34375 | 4 | # oop.py
"""Introductory Labs: Object Oriented Programming.
<Juan S Rodriguez>
<Math 320>
<September 8>
"""
def test_backpack():
testpack = Backpack("Barry", "black") # Instantiate the object.
if testpack.max_size != 5: # Test an attribute.
print("Wrong default max_size!")
for item in ["pencil", "p... |
0be1caf4027aa210a3a084c7a299432bb86e1e87 | davidmparrott/cs121 | /hw7.py | 6,933 | 4.4375 | 4 | #David Parrott
#XXXX
#CS 121
#Assignment 7
#computing the Mandelbrot sequence and visualizing it in both Black and White
#and color versions as a bitmap named Mandelbrot.bmp
#mset() produces the B&W image
#msetColor() produces a color image
#Helper functions are used to handle some of the computational work.
#inMSet(... |
53e5540e4da4a336518a504850c11a74d1fbbb63 | XiaoA/python-ds | /34_same_frequency/same_frequency.py | 976 | 4.0625 | 4 | """Sometimes, I think too far 'inside the box' on these kinds of problems. I thought the best (naive) way would be to split the integers, sort the integers, rejoin them, and then compare the count. It was not the most efficient, but simple. I couldn't find a way to iterate over the integers to make it work.' SB's solut... |
afaf0b4d56ec34e86b518d0b0f05a5b31c19e9dc | XiaoA/python-ds | /33_sum_range/sum_range.py | 1,279 | 4.125 | 4 | def sum_range(nums, start=0, end=None):
"""Return sum of numbers from start...end.
- start: where to start (if not provided, start at list start)
- end: where to stop (include this index) (if not provided, go through end)
>>> nums = [1, 2, 3, 4]
>>> sum_range(nums)
10
>>>... |
a98e1b2e456350c563c4c75e1709ea626fb88f60 | DanielHit/data-analysis-demo | /list.py | 676 | 3.984375 | 4 | # test
lists = [1, 3, 2]
print sorted(lists)
print lists
print lists.reverse()
print len(lists)
for i in lists:
print i
print "hello" + str(i)
for i in range(1, 10, 2):
print i
members = list(range(1, 10))
print members
i = 2
print i ** 2
squares = []
for i in range(1, 10):
squares.append(i **... |
8a8a9b209a7bf544b31937ebd1ef76221fe35934 | DanielHit/data-analysis-demo | /test.py | 298 | 3.515625 | 4 | from collections import OrderedDict
from random import randint
# test different order diction
favorite_languages = OrderedDict()
favorite_languages["jen"] = "python"
for k, v in favorite_languages.items():
print k.title(), v
x = 10
while x > 5:
x = randint(1, 100)
print x
print x
|
db5bda23063dd911bf1288cddf8a1f4544a3f34a | gdollard/Blockchain | /Casper.py | 1,998 | 3.5 | 4 | from CasperNode import CasperNode
import random
# each block will bet against a block using its stake. If they are selected to add the block they will
# earn a reward proportional to their stake.
# if however they are seen to misbehave their stake is slashed
# Author: Glenn Dollard
class Casper:
stake = 0;
... |
67901816b71d7069f2618cc504d6d9865f7ed5a3 | gdollard/Blockchain | /HashCheck.py | 1,889 | 3.609375 | 4 | import datetime
import hashlib
def hash_this_data(data_to_hash, use_date=False):
hash_algorithm = get_hash_algorithm()
if use_date:
timestamp = datetime.datetime.now()
hash_algorithm.update(str(timestamp).encode('utf-8'))
hash_algorithm.update(data_to_hash.encode('utf-8'))
return hash... |
0b8f73154f0449f120bac151cc4ff40906850bea | GoForWalk/PythonPractice | /forPractice.py | 436 | 3.703125 | 4 | # 출석번호 1 2 3 4, 앞에 100을 붙이기로 함 -> 101, 102, 103, 104
students = [1,2,3,4,5]
print(students)
students = [i + 100 for i in students]
print(students)
# 학생 이름을 길이로 변환
students1 = ["Iron man", "Thor", "Groot"]
students1 = [len(i) for i in students1]
print(students1)
# 핵생이름을 대문자로
students1 = ["Iron man", "Thor", "Groot"]
s... |
3366941adf275972c168c24c43be49480565676e | GoForWalk/PythonPractice | /method_overriding.py | 2,024 | 3.671875 | 4 | # 일반 유닛
class Unit:
def __init__(self, name, hp, speed):
self.name = name
self.hp = hp
self.speed = speed
def move(self, location):
print("[지상 유닛 이동]")
print("{0} : {1} 방향으로 이동합니다. [속도 {2}]".format(self.name, location, self.speed))
# 공격 유닛
class AttackUnit(Unit... |
086e34e9ecb96eca8a40dba72b96679ca0e3c685 | GoForWalk/PythonPractice | /function_quiz.py | 878 | 3.859375 | 4 | '''
Quiz) 표준 체중을 구하는 프로그램을 작성하시오
* 표준 체중 : 각 개인의 키에 적당한 체중
(성별에 따른 공식)
남자 : 키(m) x 키(m) X 22
여자 : 키(m) x 키(m) X 21
조건1 : 표준 체중은 별도의 함수 내에서 계산
* 함수명 : std_weight
* 전달값 : 키(height), 성별(gender)
조건2 : 표준 체중은 소수점 둘째자리까지 표시
(출력 예제)
키 175cm 남자의 표준 체중은 67.38kg 입니다.
'''
person_Height = 180
gender ... |
2a5576f2f7f10af9f2f23ad68f7270d85e9ef6e3 | Chaser/PythonHardWay | /Ex27/Ex27_MemorizingLogic.py | 2,805 | 4.34375 | 4 | def break_words(stuff):
"""This function will break up words for us."""
words = stuff.split(' ')
return words
def sort_words(words):
"""Sorts the words."""
return sorted(words)
def print_first_word(words):
"""Prints the first word after popping it off."""
word = words.pop(0)
... |
f4eb450d385512c5a8c0aa4f1b046c02b0d2b89c | prybintsev/python_tricks | /metaprogramming/03_dynamic_properties.py | 629 | 3.75 | 4 | # One of the possible usage of the metaclass is creating dynamic attributes
#
class AttributeMultiplier(type):
def __init__(cls, what, bases, attrs_dict):
for attr in attrs_dict:
for idx in range(1, 4):
setattr(cls, '{}_{}'.format(attr, idx), attrs_dict[attr])
super(A... |
45fd466c0cfd03262a9baad12133103943aa88c6 | sanket-k/Assignment_py | /python-files/Question 3.py | 2,008 | 4.4375 | 4 |
# coding: utf-8
# ### Question 3
# ### Note: problem similar to Question 2
# Write a program which takes 2 digits, X,Y as input and generates a 2-dimensional array. The
# element value in the i-th row and j-th column of the array should be i*j.
#
# Note: i=0,1.., X-1; j=0,1,¡ Y-1.
#
# #### Example
#
# Suppose th... |
91aa975e7eab7396508087436896aa5b5271a016 | MatthewHardcastle/Basic-Port-Scanner | /main.py | 647 | 3.609375 | 4 | import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)#using an ipv4 connection and its going to scan tcp
s.settimeout(5)
def port_scanner(host, port):
if s.connect_ex((host, port)):
print("error-port is closed")
else:
print("The port is open")
def main():
ip ... |
b99a5aedf64646175d968d64a4ab92bc7ae70a9c | marysimonyan/homework | /hw7_Mary.py | 1,373 | 3.671875 | 4 | """
Homework
Mary Simonyan
"""
"""
problem 1
"""
# import math
#
# list_of_numbers_2 = [3, 5, 15, 2, 9, 11, 10]
#
# result = math.prod(list_of_numbers_2)
# print(result)
"""
problem 2
"""
# list_with_duplicates = ['a', 'b', 'ab', 'a', 'c', 'ab', 'd', 'hh', 'k', 'hh']
#
# list = []
# for i in list_with_duplicates:
# ... |
8c91da32c3a8cfd3c5c4804964209a7df5f1fdd5 | KalinHar/OOP-Python-SoftUni | /decorators/08_store_result.py | 534 | 3.765625 | 4 | class store_results:
def __init__(self, func):
self.func = func
def __call__(self,*args):
with open('result.txt', 'a+') as f:
f.write(f"Function '{self.func.__name__}' was called. Result: {self.func(*args)}\n")
# def store_results(func):
# def wrapper(*args):
# return ... |
ab4216252416679138e20fa13c9abdb37f7c73cc | KalinHar/OOP-Python-SoftUni | /workshop/hash_table.py | 2,142 | 4.21875 | 4 | class HashTable:
""""The HashTable should have an attribute called array of type: list, where all the values will be stored.
Upon initialization the default length of the array should be 4.
After each addition of an element if the HashTable gets too populated,
double the length of the array ... |
5ff84b727ba58d9fc3440c4eba80d0e23138a113 | KalinHar/OOP-Python-SoftUni | /iterators-and-generators/02-dictionary-iterator.py | 751 | 3.859375 | 4 | # class dictionary_iter:
# def __init__(self, dict_obj):
# self.dict_obj = dict_obj
# self.keys = list(dict_obj.keys())
#
# def __iter__(self):
# return self
#
# def __next__(self):
# while self.keys:
# result = self.keys[0], self.dict_obj[self.keys[0]]
# ... |
e0219a4cbd9d1680efc95ddfbff1beae1a2d1447 | KalinHar/OOP-Python-SoftUni | /exams/apr2020/tests/test_beginner.py | 1,377 | 3.78125 | 4 | from unittest import TestCase, main
from project.player.beginner import Beginner
class TestBeginer(TestCase):
def setUp(self):
self.pl = Beginner("Beg")
def test_init_correct(self):
self.assertEqual("Beg", self.pl.username)
self.assertEqual(50, self.pl.health)
self.assertEqual... |
6fc4386e8e78f7879f8bcb92f3d53c7e71134eb4 | KalinHar/OOP-Python-SoftUni | /static-and-class_metods/integer.py | 1,912 | 3.765625 | 4 | class Integer:
def __init__(self, value):
self.value = value
@classmethod
def from_float(cls, float_value):
if isinstance(float_value, float):
return cls(int(float_value))
return f'value is not a float'
@classmethod
def from_roman(cls, value): # can "pip instal... |
7040606f2427cdc7c1951eb0b7d35fc0217eeb8f | impelfin/rpi_with_iot | /python/p31_class3.py | 830 | 3.953125 | 4 | class SmartPhone:
def __init__(self, brand, maker, price):
self.brand = brand
self.maker = maker
self.price = price
def __str__(self):
return f'str : {self.brand} - {self.maker} - {self.price}'
class Galaxy(SmartPhone):
def __init__(self, brand, maker, price, country):
... |
1566312d7e3d08e0ef65829be44e2fe618f17129 | impelfin/rpi_with_iot | /python/p23_factorial.py | 184 | 4.125 | 4 | def factorial(n):
if n <= 1:
return 1
else:
return n * factorial(n - 1)
n = input("Input number : ")
print("{} factorial is {}".format(n, factorial((int(n))))) |
6df25cb538cd96fb524edab9a82fadd582946573 | impelfin/rpi_with_iot | /python/p35_pickle.py | 436 | 3.6875 | 4 | import pickle
class SmartPhone:
def __init__(self, brand, maker, price):
self.brand = brand
self.maker = maker
self.price = price
def __str__(self):
return f'str : {self.brand} - {self.maker} - {self.price}'
object = SmartPhone("IPhone", "Apple", 10000)
f = open("test.pickle", ... |
1f50649081aea79af1939379cc4b6487eb4eb5e0 | impelfin/rpi_with_iot | /python/p33_file2.py | 196 | 3.578125 | 4 | f = open("out.txt","w")
f.write("This file is %s \n" % ("out.txt"))
f.write("end of file")
f.close()
f = open("out.txt","r")
line = 1
while line:
line = f.readline()
print(line)
f.close() |
e7470e8c811ed80da92505ab2920deeae900fefd | mmecoco/Workshop_AI | /phase1/ANN.py | 2,450 | 3.828125 | 4 | # Le but de cette exercice est d'apprendre au model d'un ANN comment faire une multiplication par 2 d'un nombre donnée
# build a model that can predict the result of the input x by y that are given
import tensorflow.compat.v1 as tf
import numpy as np
tf.disable_v2_behavior()
# ======================================... |
ca9f63443de9fec1a3a19c7f5ad8dba9b25e782e | dneelyep/Programming-Directory | /Python/TextGame2.5/menu.py | 814 | 3.65625 | 4 | import helpstuff
import quitgame
#The main menu
def mainmenu():
menutext = "\n=========================\nT E X T - G A M E - 2.5\n=========================\n\nHello, and welcome to Text Game 2.5!\n"
print menutext
print "To start the game, type 'start'. For help, type 'help'. Or, if you're a lose... |
f51387ba917f1c009773e4282629de4e6551f801 | dneelyep/Programming-Directory | /Python/TextGame3/main.py | 8,093 | 3.578125 | 4 | import prettytext
import helpmenu
def inputprompt():
global pinput
pinput = raw_input("\nPlease enter your choice: ")
def stats():
#- Display player stats in a fixed box at the bottom of the screen, have them update in response to changes (real-time)
# - TODO: Implement bars for all stats - IE instead... |
f5c8ff2994d6fa686393515465c61cc9e521d60b | jadidaniel/Python-2 | /Searching Algorithms/Interpolation Search.py | 1,373 | 3.765625 | 4 | """
The idea of formula is to return higher value of pos
when element to be searched is closer to arr[hi]. And
smaller value when closer to arr[lo]
pos = lo + [ (x-arr[lo])*(hi-lo) / (arr[hi]-arr[Lo]) ]
arr[] ==> Array where elements need to be searched
x ==> Element to be searched
lo ==> Starting index in arr[... |
8ece00d716a888419482b5006c82309d8007a7e2 | cingpo/imooc-machine-learning | /chapter5/regression_in_sklearn.py | 1,386 | 3.703125 | 4 | """
5-9 使用scikit-learn解决回归问题
"""
from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.neighbors import KNeighborsRegressor
from sklearn.model_selection import GridSearchCV
boston = datasets.load_boston()
X = boston.data
y = bo... |
0ceaa553451790c7efd64540a1adb3349c0c8f6a | cingpo/imooc-machine-learning | /chapter3/data_loading_and_simple_data_exploring.py | 799 | 3.6875 | 4 | """
3-12 数据加载与简单数据探索
"""
import matplotlib.pyplot as plt
from sklearn import datasets
iris = datasets.load_iris()
print(iris.keys())
print(iris.data.shape)
print(iris.target.shape)
# 前两个维度
X = iris.data[:, :2]
print(X.shape)
y = iris.target
# fancy indexing
plt.scatter(X[y == 0, 0], X[y == 0, 1], color="red", marker... |
1cf3ba0880b7ef3946721452cf5d667af6342edc | cingpo/imooc-machine-learning | /chapter4/train_test_split.py | 794 | 3.59375 | 4 | """
4-3 训练数据集 测试数据集
"""
import sklearn.model_selection as sk_model_selection
from sklearn import datasets
import chapter4.core.model_selection as my_model_selection
from chapter4.core import knn
iris = datasets.load_iris()
X = iris.data
y = iris.target
# ########## 自定义的 train_test_split ##########
X_train, X_test, ... |
ac47b21de130b8f6d28425d80f81a68cd72922ac | cingpo/imooc-machine-learning | /chapter8/polynomial_regression_and_pipline.py | 1,507 | 3.8125 | 4 | """
8-2 scikit-learn中的多项式回归与Pipeline
"""
import matplotlib.pyplot as plt
import numpy as np
from sklearn.linear_model import LinearRegression
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import PolynomialFeatures
from sklearn.preprocessing import StandardScaler
x = np.random.uniform(-3, 3, size=100... |
166a8cd0e09fbec739f43019659eeaf98b1d4fa4 | bliutwo/codeforces | /wrong_subtraction/python/wrong_subtraction.py | 677 | 3.65625 | 4 | import argparse
def wrong_subtraction(n, k):
output = n
for i in range(k):
string_n = str(output)
if string_n[len(string_n) - 1] == '0':
output = int(string_n[:-1])
else:
output -= 1
return output
# d = "Do the wrong subtraction as per https://codeforces.com... |
e0486d997ce22af195a235bf9552241581ca8e9b | xiaocainiaogithub/algorithm010 | /Week08/merge.py | 1,003 | 3.53125 | 4 | from typing import List
class Solution:
def merge(self, intervals:List[List[int]])->List[List[int]]:
intervals.sort(key = lambda x:x[0])
merged = []
for interval in intervals:
#如果列表为空,或者当前区间与上一区间不重合,直接添加
if not merged or merged[-1][1] < interval[0]:
merged.append(interval)
else:
#否则的话,我们就可以与上一区间... |
27ae94ff015613aecaaa2359a21a51117732dee6 | everqiujuan/python | /day10/code/06_快速排序.py | 900 | 3.84375 | 4 |
# 快速排序
# [4,1,6,3,8,5,0,9,7,2]
# [4,1,3,0,2] [5] [6,8,9,7]
# [1,0,2] [3] [4] [5] [6,7] [8] [9]
# [][0] [1,2] [3] [4] [5] [6][7][] [8] [9]
# [][0] [1][2][] [3] [4] [5] [6][7][] [8] [9]
# 快速排序
def quick_sort(mylist):
# 判断临界值
i... |
2777acf9d2f2467191d3227386993968e22a57d7 | everqiujuan/python | /day04/code/07_列表list的方法2.py | 1,441 | 4.125 | 4 |
# index() : 找出指定元素在列表中第一次出现的下标
list1 = [11, 22, 33, 66, 22, 22, 33, 44]
print(list1.index(33)) # 2
# print(list1.index(100)) # 报错, ValueError: 100 is not in list
# 内置函数/内置方法
# max() : 找列表中的最大值
m = max(list1)
print(m)
# min() : 找最小值
print(min(list1))
# sum() : 求和
print(sum(list1))
# 排序
# sor... |
e542c39b036173198db1d19f045a3959957d5d6f | everqiujuan/python | /day13/code/06_多重继承.py | 1,265 | 4.1875 | 4 |
# 人 Person
# 员工 Employee
# 主管 Manager
# 继承:从一般(父类)到特殊(子类)
# 父类
class Person(object):
def __init__(s, name):
s.name = name
print("Person,self:", id(s))
def run(self):
print(self.name, "在跑步")
# 子类
class Employee(Person):
def __init__(self, name1, age):
... |
d1023d4bd13bfcd90019ba15d89f53aab7f84e9c | everqiujuan/python | /day10/code/02_calendar.py | 1,591 | 4 | 4 |
# 万年历
# b 判断是否为闰年
def is_leap(year):
if (year%4==0 and year%100!=0) or year%400==0:
return True
return False
# C 某月的总天数
def get_mon_days(year, month):
days = 31
if month == 2:
if is_leap(year):
days = 29
else:
days = 28
elif month in ... |
a4869b974be1a713ccfe4bbf2306b40df4d288fd | everqiujuan/python | /day06/code/04_字典dict.py | 3,645 | 3.703125 | 4 |
# 字典dict, dictionary
#
# 列表: 一般保存相同类型的多个数据
# list = [1,2,3,4]
#
# 字典: 一般保存同一事物的不同类型的数据
# 比如:人是姓名,年龄,qq....
# dict = {"name": "宝强", "age": 36}
#
#
# 字典dict
person = {"name": "辣子鸡", "age": 20, 'qq': 43242}
print(person) # {'name': '辣子鸡', 'age': 20, 'qq': 43242}
print(type(person)) # <clas... |
0b90ab7fc1d10b8afc3ba92b7b9420169cec8d00 | everqiujuan/python | /day05/code/01_Day04作业.py | 2,562 | 3.75 | 4 |
# 用for - in语句实现下面的编程题目
#
# 初级
# 1.
# 求1 --100之间可以被7整除的数的个数
count = 0
for i in range(1, 101):
if i%7 == 0:
count += 1
print(count)
# 2.计算从1到100以内所有奇数的和。
s = 0
for i in range(1, 101):
if i%2:
s += i
print(s)
# 3.计算从1到100以内所有能被3或者17整除的数的和。
s = 0
for i in range(1, 101):
... |
9e85a6e4a93f39ec590dca94eb8cba822c941010 | everqiujuan/python | /day14/code/05_类方法和静态方法.py | 847 | 3.765625 | 4 |
class Person:
def __init__(self, name):
self.name = name
# 成员方法
def run(self):
print("跑步")
# 类方法: 可以使用类名来调用,能够使用类属性,但是不能使用对象属性
# 一般当功能跟类中的其他对象或方法无关时,可以使用类属性,可以一定程度节省内存
@classmethod
def eat(cls):
print(cls == Person) # True
p2 = cls('刘翔')
... |
f2d1cdcbd86af861339970878e3c4bcecd5bf9df | everqiujuan/python | /day09/code/07_迭代器&迭代器对象.py | 1,326 | 4.3125 | 4 |
from collections import Iterator # 迭代器
from collections import Iterable # 可迭代对象,迭代器对象
# 迭代器
# 迭代器对象:可以使用for-in循环遍历的
# 迭代器对象:可以使用for-in循环的
# list, tuple, dict, set, str, generator对象 都是迭代器对象
print(isinstance([1, 2], Iterable)) # True
print(isinstance((1, 2), Iterable)) # True
print(isinstance({}, Iterab... |
e8654e844820b29390da53455f17ee9090f107fc | everqiujuan/python | /day06/code/07_选择排序.py | 1,462 | 3.796875 | 4 |
# 选择排序
#
# [8,9,5,6,7,4,3,2,1] # 升序
# 第1趟 i=0 [1, 9,8,6,7,5,4,3,2]
# 第2趟 i=1 [1,2, 9,8,7,6,5,4,3]
# 第3趟 i=2 [1,2,3, 9,8,7,6,5,4]
# 第4趟 i=3 [1,2,3,4, 9,8,7,6,5]
# 第5趟 i=4 [1,2,3,4,5, 9,8,7,6]
# 第6趟 i=5 [1,2,3,4,5,6, 9,8,7]
# 第7趟 i=6 [1,2,3,4,5,6,7, 9,8]
# 第8趟 i=7 [1,2,3,4... |
9b71d3c023f0735685df6cfa1c0877312c895395 | everqiujuan/python | /day13/code/10_方法的重写.py | 336 | 3.78125 | 4 |
# 方法的重写
class Person:
def __init__(self, name):
self.name = name
def sleep(self):
print("睡7个小时")
class Man(Person):
def __init__(self, name):
Person.__init__(self, name)
def sleep(self):
print("睡24个小时")
man = Man('老宋')
man.sleep()
|
42ac2f54ba00afbf0b9002e8e5a441e3db7e24c2 | everqiujuan/python | /day11/code/07_深度遍历目录.py | 1,716 | 3.703125 | 4 |
# 深度遍历(了解)
# 栈:后进先出
import os
# 遍历目录
def getAllDirAndFile(sourcePath):
# 创建栈
stack = [] # []
stack.append(sourcePath) # [newdir]
while True:
if len(stack) == 0:
break
# 从栈的右边取文件名
dirPath = stack.pop() # []
# 获取sourcePath所有子文件夹和子... |
0e305d2eeff96f018576dd3091c073ae214c4724 | everqiujuan/python | /day14/code/06_类的特殊属性.py | 481 | 3.65625 | 4 |
class A:
pass
class Pig(A):
def __init__(self, name, age, sex):
self.name = name
self.age = age
self.sex = sex
def hello(self):
print("你好!")
# 对象
p = Pig("佩奇", 3, '女')
print(Pig.__name__) # Pig
print(p.__dict__) # {'name': '佩奇', 'age': 3, 'sex': '女... |
2cde25ce8ed173086c0d48c6ec01be895e91f467 | everqiujuan/python | /day10/code/01_Day09补充作业.py | 3,623 | 3.84375 | 4 |
# 1.简述必需参数、关键字参数、默认参数、不定长参数的区别
# 必需参数:必需要传的参数,形参数量和实参数量要一致,按顺序
# 关键字参数:在函数调用时,可以通过形参名赋值,可以不按顺序
# 默认参数:形参给默认值,函数调用时可以不用传参
# 不定长参数:
# *args: 接收多个必需参数(位置参数),会接收一个元组
# **kwargs: 接收多个关键字参数, 会接收一个字典
# 2.写函数,计算传入字符串中单个【数字】、【字母】、【空格] 以及 【其他】的个数
def fn1(str1):
count1 = 0
count2 = 0
count... |
07d65b2922b2652545c090df844d2b8bc0bb1025 | everqiujuan/python | /day06/code/01_复习.py | 9,544 | 3.734375 | 4 |
''''''
'''
Day01:
软件:python3.6, python3.7
pycharm
Day02:
计算机基础
数据存储原理
进制转换
原码,反码,补码
输入:input(),输出:print()
注释:
# 单行注释
"""
多行注释
"""
Day03:
数据类型:
number, boolean, string, list, dict, set, tuple, None, b... |
ae58544830841451663926b689eec081b35fc0e5 | gimyoni/CodeUp | /Py/1159.py | 92 | 3.5625 | 4 | a = int(input())
if (a>=50 and a<=70) or (a%6==0):
print("win")
else:
print("lose")
|
00ac6c81b925bb81c0a1fc0fb1dba70de6423368 | gimyoni/CodeUp | /Py/1286.py | 87 | 3.53125 | 4 | arr = []
for _ in range(5):
arr.append(int(input()))
print(max(arr))
print(min(arr))
|
836e37691f1a6a25da3b0e9e20ee001a38ff460f | qqdog1/trading-platform-python | /engine/trading_elements.py | 1,241 | 3.578125 | 4 | # 這個物件應該要細到以strategy為單位
# 目前就讓所有strategy共用一個
from engine.order_manager import OrderManager
from engine.price_cache import PriceCache
class TradingElements:
_order_manager = None
_price_cache = None
def __init__(self):
self._order_manager = OrderManager()
self._price_cache = PriceCache()
... |
16f2e42d8edfd401f09d30a67f7a887f68050c0a | Ercion/python_aws_rds_mysql | /pythonandAws.py | 918 | 3.890625 | 4 |
# We will use the pymysql package to connect to the database. After that, we will use Pandas for data analysis.
# In[1]:
import pandas as pd
import pymysql
# Connect to database
# To connect to the database, we use the connect function from pymysql. The connect function returns a Connection object.
# In[2]:
h... |
29060aa9a1cf80ca5baead0e4c33af3f573a05e0 | karslio/PYCODERS | /Assignments-04-functions/7-pythagoras.py | 302 | 3.859375 | 4 | def pythagoras():
lists = []
for a in range(3, 98):
for b in range(a + 1, 99):
for c in range(b + 1, 100):
if c * c == b * b + a * a:
lists.append((a, b, c))
return f'(between 1-100) ----->: {str(lists)[1:-1]}'
print(pythagoras())
|
095114a40bc82a495672242c8050faafd0ce8ce5 | karslio/PYCODERS | /Assignments-02/fibonacci.py | 271 | 4.03125 | 4 | # 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144
n1 = 0
n2 = 1
fibo = [0]
number = int(input('plese enter a number I will show you unmtil this number fibonacci numbers'))
while n2 < number:
nth = n1 + n2
n1 = n2
n2 = nth
fibo.append(n1)
print(tuple(fibo))
|
a352cb58f7c04e49769d48edab362c55e03a2142 | karslio/PYCODERS | /Assignments-04-functions/11-equal_reverse.py | 242 | 4.25 | 4 | def equal_reverse():
word = input('enter a word')
newString = word[::-1]
if word == newString:
return True
else:
return False
print(equal_reverse())
# Ex: madam, tacocat, utrecht
# Result: True, True, False
|
23d62fff333ca280629a72db13eb93880ad13077 | Bighaohaohao/python-study | /Design_Patterns/Test2.py | 1,061 | 3.75 | 4 | # class User(object):
# __instance = None
# def __init__(self,name):
# self.name = name
# def __new__(cls,name):
# if not cls.__instance: # 保证 object.__new__()方法只会执行一次
# cls.__instance = object.__new__(cls)
# return cls.__instance
# u1 = User("张三")
# u2 = User("李四")
# ... |
c835c5f63b7491226213d13997594d98a4c4331e | Bighaohaohao/python-study | /Design_Patterns/Test6.py | 1,008 | 3.828125 | 4 | class Person(object):
def __init__(self,name):
self.name = name
def work(self):
print(self.name+"开始工作")
factory = Steel_Axe_Factory()
axe =factory.create_axe()
axe.cut_tree()
class Axe(object):
def __init__(self,name):
self.name = name
def cut_tree(self... |
b8d11e9ff40749f2de4f0f89bc8b28bd8c7935c4 | jso/py-bikevis | /bikevis/analyses/basic.py | 4,872 | 3.609375 | 4 | import sqlite3
import matplotlib.pyplot as plt
from util import put_add, put_list, put_val, traverse
from cdf import cdf
def demographics(con):
data = {}
cur = con.cursor()
cur.execute("SELECT gender, birth_year, COUNT(trip_id) trip_count "
"FROM trips WHERE gender NOT NULL AND birth_year NOT NUL... |
6c9c21c685c14aa3bdf2a4f48ea2f84410ab5e09 | chamindu123/Physics | /RandomWalk.py | 1,021 | 3.765625 | 4 | import math
import pylab as plt
from random import randint
def randwalk(): #returns a list of displacements with each step
x = 0
y = 0
coord = []
for i in range(0,100):
a = randint(1,4)
if a == 1: #up
y+=1
elif a == 2: #down
y-=1
elif a == 3: #rig... |
117945e0a9362a99392b652055d5c2c3dc3532ec | uporabniskoime77/projektna | /zelvica.py | 791 | 3.828125 | 4 | import math
import turtle
okno = turtle.Screen()
zelva = turtle.Turtle()
def pozicija(x, y, r, koordinate):
for fi in range (360):
seznam = []
x = lokacijax
y = lokacijay
y += math.sin(math.radians(fi)) * r
x += math.cos(math.radians(fi)) * r
seznam.append(round(x, ... |
e60092841b2a03431bc0f4bc4f04d69ca18b4f15 | phoenixaustin81/Gess-Game-Interactive | /game.py | 17,958 | 3.984375 | 4 | import pygame
from board import Board
from piece import Piece
from stone import Stone
from constants import *
class GessGame:
"""
The GessGame class is used to make and play a game of Gess - a Chess/Go variant board game.
The game board is stored in a Board object, and managed by the Board class.
Game... |
55aa5c2b12663d078a37ff58edcda05416d69f04 | madisonstewart2018/quiz1 | /main 6.py | 1,184 | 4.46875 | 4 | #this function uses the variables matrix and vector.
def matVec(matrix, vector):
'''
The function takes in a matrix with a vector, and for each element in one row multiplies by each number in the vector and then adds them together. Function returns a new vector.
'''
new_x = []
for i in range(len(matrix)):
... |
486fbb61df8d067c76a97a10c5d0b20343ae3d23 | julius-risky/Data-Science | /Data_Visualization/scater-plot.py | 480 | 3.65625 | 4 | # generate related variables
from numpy import mean
from numpy import std
from numpy.random import randn
from numpy.random import seed
from matplotlib import pyplot
# seed random number generator
seed(1)
# prepare data
data1 = 20 * randn(1000) + 100
data2 = data1 + (10 * randn(1000) + 50)
# summarize
print('data1: mean... |
a0995989bccc791a091a079aff89ad77705e8f14 | julius-risky/Data-Science | /Data_Analyst/DF_from_dict.py | 333 | 3.640625 | 4 | import pandas as pd
# Creating series from dictionary
dict_series = {'1':'a',
'2':'b',
'3':'c'}
ex_series = pd.Series(dict_series)
print(ex_series)
# Creating dataframe from dictionary
df_series = {'1':['a','b','c'],
'2':['b','c','d'],
'3':[2,3,'z']}
ex_df = pd.DataFrame(df_series)... |
405a2630aec1ec2c1642399555748f4a97a0a996 | justindodson/PythonML | /CNN/CNN Tutorial Image Recognition Project/my_cnn.py | 5,790 | 4.0625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Jun 21 20:51:02 2018
@author: justindodson
"""
# Creating a simple image recognition pipeline
# PART 1 - Building the CNN
# import the required packages and libraries
from keras.models import Sequential
from keras.layers import Convolution2D
from k... |
5c6c73ea7efc5cc34809a5ed1d2ef21a7d11d739 | MikeChunko/Rogue | /map_objects/tile.py | 440 | 3.5625 | 4 | # File name: tile.py
# Author: Michael Chunko
# Python Version: 3.7
# This file contains the class representing a tile on a map
class Tile:
def __init__(self, blocked=True, block_sight=None, seen=False):
self.blocked = blocked
# By default, a blocked tile also blocks sight
if block_sight... |
1f7f95fa884ad37773057479a1b5a0d76d8c54ca | Jaideep-C/tic_tac_toe-minMax-bot | /plane.py | 2,342 | 3.515625 | 4 | class Plane:
def __init__(self, length):
self.length = length
self.__activateCells()
super().__init__()
def __activateCells(self):
self.__plane = []
for i in range(self.length):
col = []
for j in range(self.length):
col.append('_'... |
4053d43ee0f5ca199252135d105ced32944898b6 | MichaelMullet/github-upload | /MITx Class/Unit 2/cubeRoot.py | 519 | 3.84375 | 4 | cube = .5
epsilon = 0.01
num_guesses = 0
low = 1
fractionLow = 0
fractionHigh = 1
high = cube
guess = (high + low)/2.0
while abs(guess**3-cube) >= epsilon:
if cube >= 1:
if guess**3 < cube:
low = guess
else:
high = guess
guess = (high + low)/2.0
num_guesses +=... |
081346e448fc60eec12caf9bab5aca15080bb962 | BrianClark1/Python-for-Everybody-Specialization | /Chapter 11/11.2.py | 827 | 4.21875 | 4 | #Looking inside of a file, Extracting numbers and summing them
name = input("Enter file:") #Prompt User to input the file
if len(name) < 1 : name = "RegexRealSum.txt" #Allows user to simply press enter to open specific file
handle = open(name) #assigns the file to a variable name
inp = handle.read() #Reads the entir... |
53aa62901cf03b3723af12c2674a27913030831a | mbrousil/afs505_u1 | /assignment2/ex6.py | 851 | 3.765625 | 4 | # Define number of people
types_of_people = 10
# Create string statement on types
x = f"There are {types_of_people} types of people."
# Define binary variable
binary = "binary"
# Define contraction variable
do_not = "don't"
# Create string statement on binary knowers
y = f"Those who know {binary} and those who {do_not... |
5cb8fcdd66f158a4e55b15af31e0de250d2b0824 | babjo/py-deep-learning | /FCNN/main.py | 466 | 3.53125 | 4 | from NeuralNetwork import NeuralNetwork
x = [0.0, 0.0]
y_target = [0.3]
nn_ = NeuralNetwork(2, 1, 1)
nn_.alpha_ = 0.1
for unused in range(100):
nn_.setInputVector(x)
nn_.propForward()
y_temp = nn_.copyOutputVector()
print y_temp
nn_.propBackward(y_target)
'''
a = MatrixMN()
a.initialize(2, 3)
... |
794a91271b5a41dff665a996e8031800b9b9100f | lkwilson/personal-finances | /ira_or_roth.py | 1,151 | 3.765625 | 4 | import numpy as np
from tools import *
"""
This tool lets you figure out how much money you're missing out on if you
contribute to a Roth IRA.
Since tax gets applied beforehand, you don't get any interest on it.
If you want to have 100k when you retire, then invest only in Roth. If you
want to have a smaller income,... |
b0322eb4275aecfff9de18fba4f0e629fa21b08a | Manel-Bel/random_games | /x_o_2.py | 2,078 | 3.75 | 4 | from random import randint as ri
from timeit import default_timer as timer
tableau = [ ' ' for x in range(10)]
# le dessin du tableau
def affiche_tableau(board):
print(' '+board[1]+' '+'| '+board[2]+' '+'| '+board[3]+' ')
print('-----------------')
print(' '+board[4]+' '+'| '+board[5]+' '+'| '+... |
a21e41f817127e30ac57fd02a568fc68ea48fdf3 | mariamaftab35/git-init-project | /task7.py | 884 | 3.859375 | 4 |
"""Write a program that calculates and prints the value according to the given formula:
Q= Square root of [(2*C*D)/H]
Following are the
"""
import math
c = 50
h = 30
value = []
items = [x for x in input().split(',')]
for d in items:
value.append(str(int(round(math.sqrt(2*c*(d)/h)))))
print(','.join(val... |
3c3ace32863a254a36d4e6d42daace38dfa1a008 | BankBoy22/pyton | /0605 팡썬.py | 1,089 | 3.609375 | 4 | while True:
print("="*30)
print("1. n까지 정수의 합")
print("2. n~m까지 k의 배수의 합")
print("3. 구구단 출력")
print("4. 종료")
print("="*30)
menu=int(input("정수를 입력하세요(1~4):"))
if menu==1:
n=int(input("하나의 정수를 입력하세요=>"))
sum=0
for i in range(n+1):
sum=sum+i
... |
0c9ecd9b1c03b4d9f8ed219b16b47b22c7c8c0e9 | adventurouscricket/alien_invasion_game | /alien.py | 1,321 | 3.796875 | 4 | """Alien"""
import pygame
from pygame.sprite import Sprite
class Alien(Sprite):
"""A class to represent a single alien in the fleet."""
def __init__(self, ai_setting, screen):
"""Initialize the alien and set its starting position."""
super().__init__()
self.screen = screen
... |
f9ddc7d5c1236760550c5d868536c748d1769e88 | nazhimkalam/Complete-Python-Crash-Couse-Tutorials-Available | /completed Tutorials/bubbleSort.py | 706 | 4.28125 | 4 | #The main difference between bubble sort and insertion sort is that
#bubble sort performs sorting by checking the neighboring data elements and swapping them if they are in wrong order
#while insertion sort performs sorting by transferring one element to a partially sorted array at a time.
#BUBBLE SORT
myList = [15,24... |
59d9aadc63ec61a3dbb57509805f40c402b3df43 | nazhimkalam/Complete-Python-Crash-Couse-Tutorials-Available | /OOP tutorials/Constructor_In_Inheritance.py | 3,051 | 4.625 | 5 | # PARENT constructor and CHILD constructor
# ---> If you don't have child constructor then by default it will run the parent constructor, we have to use child object.
class Parent:
def __init__(self):
print('Parent Constructor...')
class Child(Parent):
pass # Child class empty and no constru... |
b87526548062f13ae7e10e90185550b9c896cee5 | nazhimkalam/Complete-Python-Crash-Couse-Tutorials-Available | /completed Tutorials/global, local, nonlocal scope variables.py | 1,113 | 4.59375 | 5 | #The nonlocal keyword is used to work with variables inside nested functions,
#where the variable should not belong to the inner function.
#Use the keyword nonlocal to declare that the variable is not local.
#Example 01 (with nonlocal)
def myfunc01():
x = "John" #x is 'John'
def myfunc02():
nonlocal x ... |
6448ae886dcdee89dd148cb3fffdf355e6e11394 | nazhimkalam/Complete-Python-Crash-Couse-Tutorials-Available | /completed Tutorials/basics.py | 842 | 4.09375 | 4 | #variables in python
integers = 10
decimals = 10.23
booleans = True
strings = "Nazhim"
print('This is an integer ', integers)
print('This is a decimal ', decimals)
print('This is a boolean ', booleans)
print('This is a string ', strings)
#operational calculation
num1 = 5
num2 = 3
print('Addition =>', num1 + num2)
pr... |
ecb8d4da4fc6fd875c8b03f2c7c68f7e94da849e | domagojb/webcomic | /webcomic.py | 10,095 | 3.78125 | 4 | """
Requires python3 and higher.
This module checks for new specified comics and loads them.
Every comic is defined as a new object of the class ComicLoader.
The class takes two main parameters:
siteURL : The URL of the webcomic that is going to be loaded.
pathImgURLexp : The regular ... |
85727b65b94fff3d2b66e2db7d3e68f386ca5cbc | rajesh994/AeroPython | /vortex.py | 2,915 | 3.5625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri May 11 17:15:16 2018
@author: rajerame
"""
import math
import numpy
from matplotlib import pyplot
#vortices
gamma = 5.0 # strength of vortex
Nv=300 #number of vortices
a=1 #distance between vortices
x_vortex=numpy.aran... |
e2d9a579165d3a52a8ad178f73ce19ce136223d4 | yang6543/leetcode | /selectsort.py | 270 | 3.640625 | 4 | # encoding: utf-8
def selectSort(relist):
for i in range(len(relist)):
for j in range(len(relist)-i):
if relist[i] > relist[i+j]:
relist[i],relist[i+j] = relist[i+j],relist[i]
return relist
print(selectSort([56,12,80,91,20])) |
e8c201121920d11750abb911a55c1a7c21f9a751 | AtelliAndressa/Seguranca_da_informacao_Python | /gerador_wordlists.py | 413 | 3.96875 | 4 | # wordlists = lista de palavras usado para comparar a autenticação de um dispositivo,
import itertools #fornece iteração como combinações e permutação sem repetição
string = input("String a ser permutada: ")
resultado = itertools.permutations(string, len(string)) # caracteres e quantas permutações fará
for i in res... |
bd3b5d954412ab1c3878f8d32f1b82c6fe6003dd | dimok106/stepic-python | /Lesson3_2-6.py | 345 | 3.578125 | 4 | s = input()
a = input()
b = input()
result = ""
if a in s:
if a in b :
result = "Impossible"
else:
result =0
while a in s:
s = s.replace(a, b)
result = result +1
if result > 1000:
result = "Impossible"
break
else:
r... |
641dc5e6585fef6a6bdf3e203f8814abb6c01034 | dimok106/stepic-python | /Lesson2_2-5.py | 218 | 3.796875 | 4 | import datetime
year, month, day = input().split()
date =datetime.date(int(year), int(month), int(day))
days_var = int(input())
date =date + datetime.timedelta(days= days_var)
print (date.year, date.month, date.day)
|
cb069468fbd1b53a1105c0414eea58ff3501bd8e | Sandy4321/Comparison-of-folder-in-two-directories | /June 23 2019/getSize.py | 682 | 3.71875 | 4 | import os
def convert_bytes(num):
"""
this function will convert bytes to MB.... GB... etc
"""
for x in ['bytes', 'KB', 'MB', 'GB', 'TB']:
if num < 1024.0:
return "%3.1f %s" % (num, x)
num /= 1024.0
def get_size(start_path = '.'):
total_size = 0
for... |
ee9e7af06d173872648edb0c4ae4ce925981a930 | saketborse/Blink-to-Roll-Dice-with-Eye-Detection | /diceroll.py | 648 | 4.15625 | 4 | import random
def dice():
# range of the values of a dice
min_val = 1
max_val = 6
# to loop the rolling through user input
roll_again = "yes"
# loop
while roll_again == "yes" or roll_again == "y":
#print("Rolling The Dices...")
#print("The Values are :")
... |
640105be8d17e3c96c41ae36178420591140f9db | zlatnizmaj/Advanced_Algorithm | /Bai tap Python_KHMT/SingleLinkList_Ok.py | 1,339 | 3.640625 | 4 | # -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
class Node:
def __init__(self, val):
self.val = val
self.next = None
class SLLList:
def __init__(self):
self.head = None
self.tail = None
def isEmpty(self):
return self.... |
5188f613b74d54b508b9caf003cb37805066409f | zlatnizmaj/Advanced_Algorithm | /Moj practice MIT 60001/Lecture codes/lecture2_branching.py | 474 | 4.09375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Jul 14 11:29:42 2018
EDX, MIT 6000x
Braching, Iteration
@author: MrGao
"""
x = int(input('Enter an integer: '))
if x%2 == 0:
print('')
print('Even')
else:
print('')
print('Odd')
print('Done with condititonal!!')
# Nested conditionals
if (x%2 == 0):
if x%3... |
38046e10dae2b71511ac3ed4a02078ddd4a66412 | facultyai/faculty-xval | /faculty_xval/splitting.py | 2,000 | 3.578125 | 4 | import numpy as np
class RollingWindowSplit(object):
"""
Class generating the training/test indices for a rolling window
cross validation, simulating for example daily retraining of a model.
Useful for time-series problems.
Note
----
Complies with Scikit-Learn conventions for cross-va... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.