blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
3eca9943970648004052fadf5b40d01cccb3b0aa | shengzhc/sc-dp | /py/creational/singleton.py | 995 | 3.796875 | 4 | """
Singletone Pattern
"""
from threading import Lock, Thread
class SingletonMeta(type):
_instances = {}
_lock = Lock()
def __call__(cls, *args, **kwargs):
print(cls, cls._instances)
with cls._lock:
if cls not in cls._instances:
instance = super().__call__(... |
d640b1307e01dd35f2a4d60de8d620fa8f59d880 | shengzhc/sc-dp | /py/structural/facade.py | 1,146 | 3.703125 | 4 | """
Facade Pattern
1. Facade Pattern is "analog" to gateways which is a thin layer of interface
interacting with the big/complex sub-systems behind.
2. Facade itself combines how to use sub-system to achieve the final result,
but surface the result through interface back to application/client.
Application/c... |
50ab934efaaa98a79047b768426836048273e76d | leviliangtw/PYKT-MLLab | /demo6_ sort_dataset.py | 307 | 3.671875 | 4 | import matplotlib.pyplot as plt
from sklearn import linear_model
from sklearn import datasets
data1 = datasets.make_regression(6, 5, noise=5)
X = data1[0] # 6 samples, 5 features
y = data1[1] # 6 targets/values
print(X)
for i in range(5): # traverse each feature
plt.scatter(X[:, i], y)
plt.show() |
828fd58c5024dbb389d0ee75d3e197be3b847353 | victorteodoro/fluent-python-exercises | /ch01/example1-2.py | 1,870 | 4.0625 | 4 | from math import hypot
class Vector:
def __init__(self, x=0, y=0):
self.x = x
self.y = y
def __repr__(self):
return 'Vector(%r, %r)' % (self.x, self.y)
def __str__(self):
return 'Vector(%r, %r)' % (self.x, self.y)
def __pos__(self):
return Vector(self.x, self... |
07e06ddabd29c5161e4afe755ded7c0884d07fe8 | dreaminkv/python-basics | /practical-task-1/practical-task-3.py | 1,573 | 4.21875 | 4 | # 3: Создайте программу “Медицинская анкета”, где вы запросите у пользователя следующие данные: имя, фамилия, возраст и вес.
# Выведите результат согласно которому:
# Пациент в хорошем состоянии, если ему до 30 лет и вес от 50 и до 120 кг,
# Пациенту требуется заняться собой, если ему более 30 и вес меньше 50 или больш... |
96b2b953885bf2c4dd0f3e1748ef49938405da72 | dreaminkv/python-basics | /practical-task-2/practical-task-2.1.py | 655 | 4.09375 | 4 | #1: Даны два произвольные списка. Удалите из первого списка
# элементы присутствующие во втором списке.
my_list_1 = [2, 5, 8, 2, 12, 12, 4]
my_list_2 = [2, 7, 12, 3, 4]
for number in my_list_1[:]: # Здесь в цикле необходим срез, что бы цикл прошел по всему диапазону my_list_1,
# иначе из за удаления чисел, диапаз... |
601031d704100443f7ec9358a635343e4bcb3c4f | j3ff3r/ALP2 | /MosaicFunctions.py | 2,885 | 4.15625 | 4 | # Version 0.3 Veranstaltung: Objektorientierte Programmierung
# Author: Prof. Dr. Margarita Esponda
""" In this homework you have to program the inside of six diferent 'decide_color_..' functions.
The functions calculate and returns a color for each (x,y) position of a square of side = size.
T... |
51fe71be8db3008f4bb7f83167eabb2fdcaeebc5 | AnkitaJainPatwa/python-assignment1 | /Testapp/7Listprog.py | 273 | 4.21875 | 4 | List1=["A","B","a","b","C","1","2","2","3","4"]
List2=["1986","1989"]
print(List1)
#indexing list
print(List1[4])
print (List1[-2])
# Slicing into List
print(List1[1:5])
# Concatenate two list
print(List1+List2)
#Repeation of List Using * operator
print(List2 * 2)
|
3424492e85e980642155d60908f340509ac130f5 | woodchuckchoi/programming_languages | /python/socket_06.py | 1,127 | 3.796875 | 4 | import socket
import threading
# import queue
# I won't use queue here, I think queue is useful when processing a number of things with limited resources, but in the network
# environment, or just in my case, I want to have as many threads as the clients. One client will have one thread in this server.
# is it too idea... |
d938529a0480a25a430e802001205a280f09ebd3 | woodchuckchoi/programming_languages | /python/prime_number.py | 489 | 3.9375 | 4 | def prime_verification(target):
target = int(target)
flag = True
answer = [2,3,5]
for entry in answer:
limit = target/entry
if entry == answer[-1] and limit > entry:
answer.append(entry+1)
if limit.is_integer():
flag = False
break
return... |
aacd2b060fd20388a24df9c09e92c82098e75234 | kencruz/intern-ex-2021-google-code-sample | /python/src/video_playlist.py | 1,183 | 4.125 | 4 | """A video playlist class."""
class Playlist:
"""A class used to represent a Playlist."""
def __init__(self):
"""The Playlist class is initialized."""
self._playlists = {}
@property
def playlists(self) -> dict:
"""Returns dictionary of playlists."""
return self._playli... |
6fcb962ecb97b4ed74531aed1396f908b21b0e1a | frankie-s/Python_Course | /km2mi.py | 69 | 3.796875 | 4 | km = input("Enter the number of kilometers: ")
mi = km*.62
print(mi)
|
0b80f24ce87d8662d96ffb718da87a25f88bafbf | frankie-s/Python_Course | /money_bags.py | 15,647 | 3.640625 | 4 | import os
import csv
__author__ = 'frankie'
class Bank:
def __init__(self, name):
self._name = name
self._accounts = {}
def save(self):
writer = csv.writer(open('transaction_log.csv', 'ab'))
for k in self._accounts.items():
writer.writerow([k[0], k[1].owner, k[... |
3c25602ca4f5b9c10fd2d35ee08861989b635aa2 | luckylu03/lesson5Py | /sum.py | 199 | 4.21875 | 4 | # Finish the solution so that it returns the sum
# of all the multiples of 3 or 5 below the number passed in.
def solution(number):
return sum(n for n in range(number) if n % 3 == 0 or n % 5 == 0) |
a53d20d31d29c9514538207aac7fa85c8659bd39 | A-H-Nguyen/CS1800-Final-Project-Spring-2021 | /main.py | 3,589 | 3.96875 | 4 | import turtle
import numpy
import random
uin = input("Input the cardinality of a set as an integer:")
n = int(uin) #polygon of side n
permut = numpy.math.factorial(n) #we will need this for later
ang_sliced = 360 / n #we're going to be cutting up the polygons like a pizza. 360 / 5 would give 72 degrees, which a... |
d72630bda4a865f5e867bad4b3ca424cbcabaefe | robertshiple/pdxcodeguildlabs | /atm.py | 1,775 | 4.21875 | 4 | # ATM class containing two attributes: a balance and an interest rate
# a newly created account will have a balance of 0 and Interest rate of 0.1%
# check_balance() returns the account balance
# deposit(amount) deposits the given amount in the account
#check_withdrawal(amount) returns true if the withdrawn amount w... |
3a23cd806bba23d22794d5b3b8eba2e960f3aa0f | joe-nano/Practical-Cryptography | /simple_substitution.py | 1,079 | 3.734375 | 4 | alphabets = 'abcdefghijklmnopqrstuvwxyz'
#Encoding Function
def encode(string,key):
dict_encode = {i:j for i,j in zip(alphabets,key) }
encoded_string = []
for i in string:
if ord(i) >= ord('a') and ord(i) <=ord ('z'):
encoded_string.append(dict_encode[i])
else:
encoded_string.append(i)
print('\nThe e... |
1ab7634783e3edc18fba56b1dd65cf5dafca7eeb | CodecoolMSC2016/python-oop-si-exercises-Lovi96 | /3-phone-numbers/person.py | 762 | 3.90625 | 4 | class Person():
_name = None
_phone_number = None
def __init__(self, _name, _phone_number):
self._name = _name
self._phone_number = _phone_number
def is_phone_number_matching(self, input_phone_number):
self.input_phone_number = input_phone_number
if self._phone_number =... |
b078cc61e9d1cf1590e9f8c426e78c828a12ef85 | NicolasSeay/12th-Grade-Programs | /Basic programs/Digipokemon.py | 2,590 | 3.8125 | 4 | import random
#class
class Critter(object):
"""A virtual pet"""
def status(health, hunger, sleep, name, wins, losses):
print "Health", health
if health < 20:
print name," is low on health!"
print "Hunger", hunger
if hunger < 20:
print name, " i... |
a2cfa5794d93d876f93eed6a4f052b1f0df91d2b | NicolasSeay/12th-Grade-Programs | /Basic programs/Random Number.py | 294 | 3.875 | 4 | import random
number = random.randint(1,100)
guess = 0
print number
guess = raw_input("Guess: ")
while int(guess) != number:
if int(guess) > number:
print "Too high"
elif int(guess) < number:
print "Too low"
guess = raw_input("Guess: ")
print "Correct!"
|
1326bbfe7e5ff77f881b9bbc8fce60bed0427c45 | simuty/python | /session1/day06/summary.py | 1,156 | 3.6875 | 4 | a = 1
b = 2
c = 1
print(" a: %s \n b: %s \n c: %s" % (id(a), id(b), id(c)))
print(" -----")
x = [a, b, c]
print(" x: %s \n ------ \n x[0]: %s \n x[1]: %s \n x[2]: %s" %
(id(x), id(x[0]), id(x[1]), id(x[2])))
print(" -----")
y = x
x += [3, 4]
print(" x: %s, y: %s" % (id(x), id(y)))
x = x + [3, 4]
print(" -----")
... |
f37ade464304f99e5727217c2561242a185322fb | abhilive/python-development | /Working with Data/readingFiles.py | 1,541 | 4.125 | 4 | '''
Reading Files
We're downloading this file and will use the same for reading
!wget -O /resources/data/Example1.txt https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/PY0101EN/labs/example1.txt
/resources/data/Example1.txt
'''
example1="resources/data/Example1.txt"
file1 = open(examp... |
c9203c506c07fe86d06b07cd1064bbd687dbfb9d | abhilive/python-development | /Working with Pandas/loadingAndViewingData.py | 878 | 3.984375 | 4 | '''
Loading and Viewing data with Pandas
'''
import pandas as pd #pd referring panda dataframe
#csv_path='https://ibm.box.com/shared/static/keo2qz0bvh4iu6gf5qjq4vdrkt67bvvb.csv'
csv_path='resource/data/top_selling_albums.csv'
df = pd.read_csv(csv_path) #use read_excel to read excel file
df.head() #To examine first f... |
ff6239f4204835cbfea442d75f16f767325d1d81 | abhilive/python-development | /Challenges/print-usage.py | 326 | 4.0625 | 4 | """
Problem Statement:
Read an integer N.
Without using any string methods, try to print the following:
123....N
Note that "..." represents the values in between.
Source: https://www.hackerrank.com/challenges/python-print/problem
"""
if __name__ == '__main__':
num = int(input())
print(*range(1, num+1), se... |
94d003f93815d199edadb5008aea459770cac953 | eDerek/LeetCodeProblems | /Construct Binary Tree from Preorder and Postorder Traversal.py | 1,767 | 3.71875 | 4 | # Return any binary tree that matches the given preorder and postorder traversals.
# Values in the traversals pre and post are distinct positive integers.
# Example 1:
# Input: pre = [1,2,4,5,3,6,7], post = [4,5,2,6,7,3,1]
# Output: [1,2,3,4,5,6,7]
# Note:
# 1 <= pre.length == post.length <= 30
# pre[] and po... |
cc60e32de8cfc80c1c61fb60dd8ceec2e380e73d | eDerek/LeetCodeProblems | /Concatenated Words.py | 1,621 | 4.21875 | 4 | # Given a list of words (without duplicates), please write a program that returns all concatenated words in the given list of words.
# A concatenated word is defined as a string that is comprised entirely of at least two shorter words in the given array.
# Example:
# Input: ["cat","cats","catsdogcats","dog","dogcatsdo... |
573699ec919c9ed61cf7180a79f415de29142cb5 | lyubadimitrova/cl-classes | /Prog1/Lösungen/blatt 07/filestats.py | 1,869 | 4.40625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Created on Wed Dec 21 21:43:46 2016
@authors: Lyuba Dimitrova <dimitrova@cl.uni-heidelberg.de>
Martina Brauchler <brauchler@cl.uni-heidelberg.de>
Utaemon Toyota <toyota@cl.uni-heidelberg.de>
name: filestats.py
usage: import filestats (mod... |
99c0366d67969ccb92d079a1bed7b14d12d88c07 | lyubadimitrova/cl-classes | /Prog1/Lösungen/blatt 08/aufg26.py | 1,836 | 3.65625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Jan 5 09:29:32 2017
Created on Tue Jan 10 07:50:32 2017
authors: Lyuba Dimitrova <dimitrova@cl.uni-heidelberg.de>
Martina Brauchler <brauchler@cl.uni-heidelberg.de>
Utaemon Toyota <toyota@cl.uni-heidelberg.de>
name: aufg.26.py
usage: execute aufg.2... |
0f02a3464088e4c924a1c7596e1fe9f9b8abb787 | lyubadimitrova/cl-classes | /IBN/blatt9/aufg3.py | 4,519 | 3.53125 | 4 | import sys
if len(sys.argv) != 2:
sys.exit('Please give a quantum.')
else:
quantum = int(sys.argv[1])
def FCFS(seq):
schedule = []
turnaround_times = []
for i in range(len(seq)):
if i == 0:
turnaround_times.append(seq[0])
else:
turnaround_times.append(turnaround_times[i-1] + seq[i])
schedule.appe... |
94d93422d49072e25e895cfde1ee247424735e19 | lyubadimitrova/cl-classes | /Prog1/Lösungen/blatt 06/aufg20_final.py | 1,563 | 3.71875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Created on Thu Dec 1 20:11:23 2016
@author: Lyuba Dimitrova, Utaemon Toyota & Martina Brauchler
name: Aufg_20_checkSolution.py
Checks if a solution for a problem string is valid
usage: /Aufg_20_checkSolution.py
license: feel free to use
"""
def checkSol... |
6057c0c7be06d840fc0b851a1fde50a9fc34ddc8 | lyubadimitrova/cl-classes | /Prog1/Lösungen/blatt 09/aufg29.py | 744 | 3.53125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Jan 18 21:02:52 2017
@authors: Lyuba Dimitrova <dimitrova@cl.uni-heidelberg.de>
Martina Brauchler <brauchler@cl.uni-heidelberg.de>
Utaemon Toyota <toyota@cl.uni-heidelberg.de>
name: ngrams2.py
usage: Module to be used in Python Interpreter
... |
d208ff40664758c41b0b7da99ea057836fd133f1 | lyubadimitrova/cl-classes | /Prog1/Lösungen/blatt 05/aufg17_final.py | 943 | 3.875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Created on Fri Nov 11 22:59:00 2016
# author: Lyuba Dimitrova, Utaemon X & Martina Brauchler
# Aufgabenblatt 05, Aufgabe 17: Entfernt Stopworte aus einem String
def convert_str_to_ls(aString): # konvertiert String in Liste
ls_str1 = aString.split()
r... |
7e885cd59afa5a712d347a126498a183091cb55a | tahuff-byte/canvas | /canvas.py | 597 | 4.34375 | 4 | #Imports the turtle library
import turtle as trtl
#the turtle module pop up window
wn = trtl.Screen()
#ask to pick 2 colors
print("pick 2 colors")
#int vars so the program can gather user input
color_1 = input("What color would you like?: ")
color_2 = input("can you give me another color: ")
#putting the color ca... |
aae22ae01ff46c30ead11ee473a08df5592fc717 | Spawn1k/pytasks | /286.py | 142 | 3.828125 | 4 | from decimal import Decimal
a = Decimal(input())
b = Decimal(input())
if a > b:
print('>')
elif a < b:
print('<')
else:
print('=') |
831d9b713c90248774c56bdafa4a7f6ea910d587 | Spawn1k/pytasks | /80.py | 1,635 | 3.796875 | 4 | import sys
def is_digit(string):
if string.isdigit():
return True
else:
try:
float(string)
return True
except ValueError:
return False
fin = open('INPUT.TXT')
a = fin.readline()
zn = -1
if a == '' or a == '\n':
print('ERROR')
sys.exit()
osh = a.... |
4fad71e11c03fb00d8de77b27f590495f3b1082e | mishidemudong/mudong_leetcode | /树的最小深度BFS思路.py | 1,402 | 3.8125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Feb 9 16:18:18 2021
@author: liang
"""
'''
叶子节点就是深度的最后一个节点,叶子节点的性质,左右子孩子为空
'''
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self... |
708c022cf82aad2efd105125d72c791c602c1192 | mishidemudong/mudong_leetcode | /DFS排列组合字符串.py | 1,256 | 4.1875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Feb 9 16:18:18 2021
@author: liang
"""
import itertools
class Solution:
def permutation(self, s: str):
result=set()
for i in itertools.permutations(s):
string=''.join(i)
result.add(string)
return li... |
6e21a65f891a32c1b81c2f3310a0b9a67d58cc9d | mishidemudong/mudong_leetcode | /将排序数组转成二叉搜索树BST.py | 1,246 | 3.703125 | 4 |
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def sortedArrayToBST(self, nums: List[int]) -> TreeNode:
# def incert_bst(node, val):
# if node ... |
8040d2c47e5622bd0c881f7c8258b7e4791bca91 | mishidemudong/mudong_leetcode | /缺失的数字1.py | 177 | 3.734375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Feb 28 15:23:53 2021
@author: Administrator
"""
def missingNumber(nums):
return sum(list(range(0,len(nums)+1))) - sum(nums) |
537c7e329a9a8117cb11f42291a0e1aa3728c0d2 | mishidemudong/mudong_leetcode | /reversewords.py | 266 | 4.0625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Dec 23 17:05:21 2020
@author: liang
"""
def reverseWords(s: str) -> str:
a = s.split(' ')
a.reverse()
return ' '.join(a)
print(reverseWords("the sky is blue"))
#a = s.split(' ') |
856eae8f24ce97fa3f23e27b6ee488cd00c0370d | sumanth-vs/ProjectEuler | /euler23.py | 1,791 | 4.125 | 4 | '''
A perfect number is a number for which the sum of its proper divisors is exactly equal to the number. For example, the sum of the proper divisors of 28 would be 1 + 2 + 4 + 7 + 14 = 28, which means that 28 is a perfect number.
A number n is called deficient if the sum of its proper divisors is less than n and it i... |
9691ad5a8d1755b24339c1a16354f576606b1dc8 | sumanth-vs/ProjectEuler | /euler1.py | 714 | 4.25 | 4 | # If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
# Find the sum of all the multiples of 3 or 5 below 1000.
'''
def multiples(n, t1, t2):
sum = 0
m=1
while(t1*m < n):
sum += t1*m
m+=1
m=1
wh... |
9f398a8536023de3cb943dd3761792799f61f184 | sumanth-vs/ProjectEuler | /euler10.py | 1,269 | 3.8125 | 4 | # # The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
# # Find the sum of all the primes below two million.
import math
import timeit, time
def is_prime(i):
for ii in range(2, int(math.sqrt(i)+1)):
if i%ii == 0:
return False
return True
'''
def prime_sum(n):
odd_numbers = [(2*x +... |
df1e198b4707eea6da22989bd4044350e0f077e2 | HenriqueSamii/Assessment-Desenvolvimento-Python-para-Redes-e-Sistemas-Operacionais | /A4.py | 427 | 4.15625 | 4 | """4.Escreva um programa em Python que leia um arquivo texto e apresente na tela o seu conteúdo reverso
"""
import os
filePath =os.path.dirname(os.path.abspath(__file__))
input_arqSplit = filePath+"\\teste.txt"
if os.path.exists(input_arqSplit):
f = open(input_arqSplit, "r")
fText = f.read().split("\n")
... |
8817e28e79aa99775b2aaf0808ff3fed1cb5d08e | mikeribaudo/CIS1566_Second_Program | /assignment02.py | 878 | 3.890625 | 4 | import random
magic_number = random.randint(1,100)
tries = 7
counter = 0
print("Guess a number from 1 to 100. ")
# print(magic_number)
while True:
try:
user_input = int(input("You have {0} tries left:".format(tries)))
except (ValueError, TypeError):
print("Not an Integer! Try again.")
e... |
f92900e302c6dcf4e5490e444ccfcfdc2b54eea9 | amcharaniya/python_summer2021 | /HW/HW5_AmaanCharaniya | 2,411 | 3.96875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Aug 29 16:21:12 2021
@author: amaancharaniya
"""
class Node:
def __init__(self, _value=None, _next=None):
self.value = _value
self.next = _next
def __str__(self):
return str(self.value)
class LinkedList():
def __in... |
5142a2061f67f69daa9329dffe5abf27025dd2d8 | wfwf1990/python | /Day2/zuoye.py | 281 | 3.6875 | 4 |
#打印出所有三位数中的水鲜花数
num = 100
while num <= 999:
num1 = num // 100
num2 = num // 10 % 10
num3 = num % 10
if num == num1 ** 3 + num2 ** 3 + num3 ** 3:
print(num)
num += 1
ge = " "
str1 = input("str:")
print(str1.count(" "))
|
4016238b276b294df736b932569888e63758dc5f | wfwf1990/python | /Day6/9-目录遍历/3丶队列模拟递归遍历目录.py | 839 | 3.625 | 4 | # Author: wangfang
import collections
import os
def getAllDir(path):
#创建队列
queue = collections.deque()
#进队
queue.append(path)
while len(queue) != 0:
#取数据
getdir = queue.popleft()
#列出当前目录下的所有文件
filelist = os.listdir(getdir)
#判断文件是否是目录还是文件
for filename i... |
9e7527570e97d5c0a3e7f75d30f1385d9a4d4642 | wfwf1990/python | /Day6/1-装饰器/1丶装饰器.py | 636 | 3.875 | 4 |
'''
概念:是一个闭包,把一个函数当做参数返回一个替代版的函数,本质上就是一个返回函数的函数
作用:给函数增加功能
'''
'''
定义一个outer函数,把fun1函数当做参数传入outer函数的形式参数
在outer函数里定义一个新的函数,定义新功能,同时执行outer函数的参数的函数(也就是执行老的函数),返回新的函数
'''
#简单的装饰器
def fun1():
print("***************")
def outer(func):
def inner():
print("&&&&&&&&&&&&&&&")
func()
return inner... |
10865c6c33c7d4aed309d07afedf0360285eac0f | wfwf1990/python | /Day5/1-集合set.py | 1,311 | 4.125 | 4 | '''
set:类似dict,是一组key的集合,不存储value
本质:无序和无重复元素的集合
'''
#(1)创建
#创建set需要一个list或者tuple或者dict作为输入集合
#重复元素在set中自动被过滤
set1 = set([1,2,3,3,3,4,5,6])
set2 = set((1,2,3,3))
set3 = set({1:"tom",2:"jack"})
print(set1)
print(set2)
print(set3)
#(2)添加
set4 = set([1,2,3,3,3,4,5,6])
set4.add(7)
set4.add(6) #可以添加重复的,但是不会有效果
#set4.add(... |
1a171b0770b890a8358723de56c7c85e1cc9bf40 | wfwf1990/python | /Day6/12-类/4丶对象的初始状态(构造函数)/构造函数.py | 761 | 3.875 | 4 | # Author: wangfang
class Person(object):
def run(self):
print("run")
def eat(self,food):
print("eat " + food)
def openDoor(self):
print("opendoor")
def fillEle(self):
print("fill")
def closeDoor(self):
print(close)
def __init__(self,name,age):
#定义... |
0179f31e4ff9f98dc3521d5fcd373188ed050187 | wfwf1990/python | /看书笔记/看书练习/类/一个模块导入另外一个模块/car.py | 943 | 3.953125 | 4 | class Car():
def __init__(self,make,model,year):
self.make = make
self.model = model
self.year = year
self.odometer_reading = 0
def getDescriptiveName(self): #返回描述性信息
long_name = str(self.year) + " " + self.make + " "+ self.model
return long_name.t... |
c727cadb44c7e83e2eed53ebe330343e82fdb124 | wfwf1990/python | /Day6/10-时间相关模块/性能测试.py | 168 | 3.796875 | 4 | import time
time.clock()
def sum1(num):
sum = 0
for i in range(num + 1):
sum += i
return sum
res = sum1(10000000)
print(time.clock())
print(res)
|
fe7f9d446ad67f62a1cf21ce23269f0bc497ee49 | wfwf1990/python | /Day3/break语句.py | 378 | 4.15625 | 4 | '''
break语句:
作用:跳出for和while循环
注意:只能跳出距离他最近的那一层循环
'''
for i in range(10):
print(i)
if i == 5:
break
a = 1
while a <= 3:
print("test1!")
a += 1
if a == 2:
break
#注意:循环语句可以有else语句,break导致循环截止,不会执行else下面的语句
else:
print("test2!") |
1277642b5c35ab4bec3d1c2089bbc93d0aa03ac4 | webclinic017/aqua | /src/aqua/portfolio/strategy.py | 2,897 | 4.03125 | 4 | """
A strategy is a defined by the set of positions that result from a sequence of trades
made under the same guiding principles (i.e. the trading strategy).
"""
from collections import defaultdict
from typing import Optional
from aqua.security import Option, Stock
from aqua.security.security import Security
class ... |
71246f4530ec4331109065dd624e6f13e23ba661 | suminmoon/m44-python | /python-basic/lotto-app.py | 179 | 3.640625 | 4 | # 아래에 코드를 작성하세요.
import random
numbers = range(1,46)
lotto = random.sample(numbers, 6)
print(f'오늘의 행운의 숫자는 {sorted(lotto)} 입니다.')
|
ade3aad459b688de684d8a4f56d05ef4efaa02af | VenkataChadalawada/Machine-Learning | /cnn/cnn_mine.py | 4,707 | 3.515625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Oct 13 19:23:03 2018
@author: vchadalawada
"""
# Artificial Neural Network
# Installing Theano
# pip install --upgrade --no-deps git+git://github.com/Theano/Theano.git
# Installing Tensorflow
# Install Tensorflow from the website: https://www.tensor... |
7007a276bd542ea6967db775a16682065ea2edb0 | purple-lumpy/TemplateCFGMining | /EditDistance.py | 901 | 3.75 | 4 | # calculate edit distance
def levenshtein(first, second):
if len(first) == 0:
return len(second)
if len(second) == 0:
return len(first)
if len(first) > len(second):
first, second = second, first
first_length = len(first) + 1
second_length = len(second) + 1
distance_mat... |
d3ab38cf8b52918e7043fa3a04bdb9976527cf82 | Santosh-Sah/Auto_Encoder | /AutoEncoderTrainModel.py | 8,824 | 3.609375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Apr 27 07:29:55 2020
@author: Santosh Sah
"""
import numpy as np
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.optim as optim
import torch.utils.data
from torch.autograd import Variable
from AutoEncoderUtils import (readAutoEncoderXTrain, readNumbe... |
088233fbdf385d8f7d6fdcac6f48790d65b37b4c | YouThIU/arithmeticTest | /page/page_subtraction.py | 264 | 3.640625 | 4 | '被测功能的项目文件'
'相当于PO设计模式中页面对象层的封装'
class Number(object):
"""docstring for number"""
def __init__(self):
pass
def subtration_num(self,a ,b):
"""减法"""
subtractionnum = a - b
return subtractionnum
|
30bdf997985dae324ae7e988884dd1ac7ac3be38 | Smarties89/mps | /mps/randstr.py | 482 | 4 | 4 | import string
import random
def randstr(n=8):
"""
randstr creates a random string of numbers and upper/lowercase characters.
>>> randstr()
"0YH58H9E"
>>> randstr(5)
"0ds34"
This code is slighty modified version of
http://stackoverflow.com/questions/2257441/random-string-generation-w... |
9048647e1b65ec57108c6e21b51b34480b85cd5b | nunrib/Curso-em-video-Python-3 | /MUNDO 3/ex106.py | 1,105 | 4.125 | 4 | def manual():
"""manual
Está função serve para mostrar o manual de um comando que o usuário quiser,
sendo então uma central de ajuda para comandos do python.
"""
while True:
print('\033[1;32m~' * (len('CENTRAL DE AJUDA PYHELP') + 2))
print(f'CENTRAL DE AJUDA PYHELP'.center(l... |
beb279e316fc9d6cf920194b09e673aa276a82bf | nunrib/Curso-em-video-Python-3 | /MUNDO 3/ex099.py | 512 | 3.921875 | 4 | from time import sleep
def maior(* num):
"""maior
Essa função mostra o maior número de uma lista
"""
print('-=' * 40)
print('Analisando os valores passados...')
for c in num:
print(c, end=' ')
sleep(0.2)
print(f'Foram informados {len(num)} valores ao todo.')
if ... |
3550c239c09923470718b5cf6e5f7e9537d6c1cb | nunrib/Curso-em-video-Python-3 | /MUNDO 3/ex103.py | 672 | 3.671875 | 4 | def ficha(nome='', gols=0):
"""Ficha
Parâmetros:
nome (string): Nome do jogador
gols (int, optional): Gols marcados pelo jogador. Defaults to 0.
Returns:
lista: Lista com o nome do jogador e o tanto de gols que o mesmo fez
"""
print('-' * 50)
if len(nome)... |
08fe7e1105a20139b795f77c6d4f2e512e9cea72 | nunrib/Curso-em-video-Python-3 | /MUNDO 2/ex055.py | 339 | 3.859375 | 4 | maior = 0
menor = 0
for c in range(0, 5):
a = float(input('Digite o seu peso: '))
if c == 0:
maior = a
menor = a
else:
if a > maior:
maior = a
if a < menor:
menor = a
print(f'\nO maior dos pesos lidos foi {maior}Kg e o menor dos pesos lidos... |
ff966c988056a514add443a1e14a687d67713776 | nunrib/Curso-em-video-Python-3 | /MUNDO 3/ex078.py | 400 | 3.90625 | 4 | a = []
for c in range(0, 5):
a.append(int(input('Digite um número: ')))
print(f'O maior valor da lista foi {max(a)}, nas posições ', end='')
for pos, c in enumerate(a):
if c == max(a):
print(f'{pos}...', end=' ')
print(f'\nO menor valor da lista foi {min(a)}, nas posições ', end='')
for pos, c i... |
3caff51c60cfeb537a45652da7946dee7607d365 | nunrib/Curso-em-video-Python-3 | /MUNDO 1/ex026.py | 291 | 3.953125 | 4 | frase = input('Digite uma frase: ').upper().strip()
print('A letra A aparece {} vezes'.format(frase.count('A')))
print('A letra A aparece pela primeira vez no caractere {}'.format(frase.find('A')+1))
print('A letra A aparece pela última vez no caractere {}'.format(frase.rfind('A')+1))
|
be3843746d0a0a9d134bcb6601747c21e8d15ca1 | nunrib/Curso-em-video-Python-3 | /MUNDO 3/ex074.py | 273 | 3.890625 | 4 | from random import randint
rand = randint(0, 10), randint(0, 10), randint(0, 10), randint(0, 10), randint(0, 10)
print(f'Foram gerados os números {rand}')
print(f'\nO MAIOR dos números gerados foi {max(rand)}')
print(f'O MENOR dos números gerados foi {min(rand)}')
|
68fcd2b61ecb6f08a5a30ebf253b5cb27c81adb9 | nunrib/Curso-em-video-Python-3 | /MUNDO 3/ex072.py | 567 | 4.15625 | 4 | extenso = 'zero', 'um', 'dois', 'três', 'quatro', 'cinco', 'seis', 'sete', 'oito', \
'nove', 'dez', 'onze', 'doze', 'treze', 'catorze', 'quinze', 'dezesseis', \
'dezessete', 'dezoito', 'dezenove', 'vinte'
while True:
a = int(input('Digite o número que você deseja ver por extenso: (0 a 20) ')... |
2f1e5c898ed68f94fdefb9d381551feb2fbfe0dd | nunrib/Curso-em-video-Python-3 | /MUNDO 3/ex086.py | 240 | 3.96875 | 4 | n = list()
for c in range(0, 9):
n.append(int(input(f'Digite o valor que você quer colocar na posição {c}: ')))
print()
for c in range(0, 9):
print(f'[ {n[c]:^5} ]', end='')
if c == 2 or c == 5 or c == 8:
print('\n')
|
6d548c45d9d61422567b4091b7aeca643c505ded | nunrib/Curso-em-video-Python-3 | /MUNDO 2/ex058.py | 561 | 3.890625 | 4 | from random import randint
a = randint(0, 10)
print('-=-' * 11)
print('Será que você consegue me vencer?')
print('-=-' * 11)
b = int(input('Tente acertar o número que o computador pensou (entre 0 e 10): '))
cont = 1
while b != a:
print('ERRADO!')
if b > a:
b = int(input('Menos... Tente outro n... |
0b11b63eeecf13b3f2758f64a4999fd916a81e68 | nunrib/Curso-em-video-Python-3 | /MUNDO 3/ex096.py | 269 | 3.65625 | 4 | def area():
print('-' * 20)
print('CONTROLE DE TERRENOS')
print('-' * 20)
larg = float(input('LARGURA (m): '))
comp = float(input('COMPRIMENTO (m): '))
a = larg * comp
print(f'A área do terreno de {larg}x{comp} é igual a {a}m²')
area()
|
67b99d3109f8461eeafa7f0a6cca7fca4468a993 | jonathanhockman/lc101 | /chapter5/main_examples/py1.py | 260 | 3.5 | 4 | import py2
# py1 does not have a check for main so this
# code executes when it's imported
def print_names():
print("py1's name is:", __name__)
print("py2's name is:", py2.__name__)
def main():
print_names()
if __name__ == '__main__':
main() |
ee58edeae28e721ee9393f34ad35936c75113ebb | monkeylyf/interviewjam | /recursion/rocket_fuel_Parentheses_Combinations.py | 4,505 | 3.703125 | 4 | """rocket_fuel_Parentheses_Combinations
rocket fuel
Given numbers of (), [] and {}, print all valid combinations on the fly.
"""
def parentheseCombo(n1, n2, n3):
"""Functional programming style.
During recursion, no variables are modified inplace. Makes the code clean and neat.
The Java code below is i... |
4334017af7afc30a0febe0eee2250a25fcfc3257 | monkeylyf/interviewjam | /arr/leetcode_find_the_distance_value_between_two_arrays.py | 318 | 3.59375 | 4 | # https://leetcode.com/problems/find-the-distance-value-between-two-arrays
class Solution:
def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:
total = 0
for a in arr1:
if all(abs(a - i) > d for i in arr2):
total += 1
return total
|
a781c82fe8351baf35d7b2862b18238337100c87 | monkeylyf/interviewjam | /dynamic_programming/leetcode_House_Robber.py | 1,179 | 3.71875 | 4 | """House Robber
leetcode
You are a professional robber planning to rob houses along a street. Each house
has a certain amount of money stashed, the only constraint stopping you from
robbing each of them is that adjacent houses have security system connected and
it will automatically contact the police if two adjacent ... |
faf0cdafc1125ec744b539c0725dc1330427bfa3 | monkeylyf/interviewjam | /medium/leetcode_online_stock_span.py | 992 | 3.5625 | 4 | # https://leetcode.com/problems/online-stock-span/
class StockSpanner:
def __init__(self):
self.stack = []
def next(self, price):
stack = self.stack
res = 1
while stack and stack[-1][0] <= price:
res += stack.pop()[1]
stack.append([price, res])
retu... |
63d78533bb2deb55f9299c3250960bbaa1fad7a4 | monkeylyf/interviewjam | /dynamic_programming/leetcode_Decode_Ways.py | 1,107 | 3.921875 | 4 | """Decode ways
leetcode
A message containing letters from A-Z is being encoded to numbers using the
following mapping:
'A' -> 1
'B' -> 2
...
'Z' -> 26
Given an encoded message containing digits, determine the total number of ways
to decode it.
For example,
Given encoded message "12", it could be decoded as "AB" (1 2... |
148ebe9bcfdb7ea98a3d346dada94b561f75f01b | monkeylyf/interviewjam | /tree/leetcode_Odd_Even_Linked_list.py | 1,662 | 3.875 | 4 | """Odd even linked list.
leetcode
Given a singly linked list, group all odd nodes together followed by the even
nodes. Please note here we are talking about the node number and not the value
in the nodes.
You should try to do it in place. The program should run in O(1) space
complexity and O(nodes) time complexity.
""... |
7d0cf71f8723716c4ac7f7aaf79dddb0a56acf9b | monkeylyf/interviewjam | /hackerrank/hackerrank_Grid_Challenge.py | 835 | 3.953125 | 4 | """hackerrank_Grid_Challenge
https://www.hackerrank.com/contests/101hack18/challenges/grid-challenge.
"""
def main():
"""Swap is a hoax. You can rearange the string as you want.
So the only thing needs to be done is to compare the current
string to previous one and make sure it's strickly alphabetically
... |
228a7e8c489806065d9546106637ee083b273ece | monkeylyf/interviewjam | /bit/leetcode_Bitwise_And_Of_Numbers_Range.py | 1,420 | 3.734375 | 4 | """Bitwise and of numbers range
leetcode
Given a range [m, n] where 0 <= m <= n <= 2147483647, return the bitwise AND of
all numbers in this range, inclusive.
For example, given the range [5, 7], you should return 4.
"""
class Solution(object):
def rangeBitwiseAnd(self, m, n):
"""Convert both numbers to b... |
b2c51334d34586216ed943bc7b01a9889a906b83 | monkeylyf/interviewjam | /math/leetcode_Bulb_Switcher.py | 549 | 3.8125 | 4 | """Bulb switcher
leetcode
It's more a mind trick instead of an algorithm challenge.
"""
class Solution(object):
def bulbSwitch(self, n):
"""
:type n: int
:rtype: int
"""
# Only numbers can be expressed as i^2 will be switched in odd time
# to left to be on.
... |
3d12afd614df37e13a24f8b5cf74ebcbf9d13546 | monkeylyf/interviewjam | /misc/hackerrank_Cut_the_Tree.py | 1,278 | 3.671875 | 4 | """hackerrank_Cut_the_Tree
https://www.hackerrank.com/contests/w2/challenges/cut-the-tree
"""
def traverse(node, adj, visited):
s = [0]
preorder = []
while s:
node = s.pop()
if visited[node]:
continue
preorder.append(node)
visited[node] = True
for c... |
bbd06e970f33e0fd3225569ff5aedc8b24bb6c63 | monkeylyf/interviewjam | /recursion/Tail_Recursion.py | 1,005 | 4.375 | 4 | # Explain what is tail recursion and implement reverse a list using functional programming style
def rev(a):
"""Tail recursion.
rev([0, 1, 2, 3])
nested([], [0, 1, 2, 3])
nested([0] + [], [1, 2, 3])
nested([1] + [0], [2, 3])
nested([2] + [1, 0], [3])
nested([3], [2, 1, 0],... |
5dd7799441367003d9b984abfc4a9042c2740b93 | monkeylyf/interviewjam | /hackerrank/hackerrank_Sherlock_and_Anagrams.py | 801 | 3.78125 | 4 | """hackerrank_Sherlock_and_Anagrams.py
https://www.hackerrank.com/contests/w13/challenges/sherlock-and-anagrams
"""
from collections import Counter, defaultdict
def solve(s):
n = len(s)
pick_two = lambda x: x * (x - 1) / 2
total = 0
for i in xrange(1, n):
seen = defaultdict(int)
f... |
384ae7f3102fe9d7a8887ba762d5efe93b55e4ca | monkeylyf/interviewjam | /easy/leetcode_day_of_year.py | 260 | 3.5625 | 4 | # https://leetcode.com/problems/day-of-the-year
class Solution:
def dayOfYear(self, date: str) -> int:
year, month, day = map(int, date.split('-'))
return int((datetime.datetime(year, month, day) - datetime.datetime(year, 1, 1)).days + 1)
|
386590ec8d9392b281fe183db12dfd5f15890e7e | monkeylyf/interviewjam | /medium/leetcode_daily_temperatures.py | 617 | 3.5 | 4 | # https://leetcode.com/problems/daily-temperatures/
from typing import List
class Solution:
def dailyTemperatures(self, T: List[int]) -> List[int]:
if not T:
return []
n = len(T)
res = [0] * n
stack = []
for i, t in enumerate(T):
while stack and T[... |
62fb31cd7a50d0ec0f5d901d58d92f0c148e856e | monkeylyf/interviewjam | /arr/leetcode_Meeting_Rooms_II.py | 1,209 | 3.796875 | 4 | """Meeting Rooms II
leetcode
Given an array of meeting time intervals consisting of start and end times
[[s1,e1],[s2,e2],...] (si < ei), find the minimum number of conference rooms
required.
For example,
Given [[0, 30],[5, 10],[15, 20]],
return 2.
"""
import heapq
# Definition for an interval.
class Interval(objec... |
53a6ab6b0ede0ae7412f91a5f4f135c5ca39e80f | monkeylyf/interviewjam | /medium/leetcode_print_binary_tree.py | 1,468 | 4.03125 | 4 | # https://leetcode.com/problems/print-binary-tree/
from typing import List
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def printTree(self, root: TreeNode) -> L... |
73b25fad52a60848b16548d35b18bc038fd5ca46 | monkeylyf/interviewjam | /graph/topological_sorting.py | 1,759 | 4.125 | 4 | """Topological_Sorting
Find the topological order of a directed graph.
"""
def toposort_iterative(adj_list):
"""Finding the toposort order iteratively.
Using indegree of each vertex. It's guaranteed that there is at least one
vertex has 0 indegree otherwise there will be a cycle ih the graph that does
... |
3d194fe6b00d9b60abfc39614ac7ba62a6c99616 | monkeylyf/interviewjam | /str/leetcode_Maximum_Product_Of_Word_Lengths.py | 971 | 3.609375 | 4 | """Maximum product of word lengths
leetcode
"""
class Solution(object):
def maxProduct(self, words):
"""
:type words: List[str]
:rtype: int
"""
length = 0
masks = [0] * len(words)
base = ord('a')
# Calculate bit masks for a word.
for i, word ... |
eb7a5e50b555ee6a194a2db5210c470bc91f0070 | monkeylyf/interviewjam | /misc/decompress_data.py | 2,005 | 3.640625 | 4 | """decompress_data
3(a4(ab)) -> aababababaababababaabababab
"""
import unittest
class Decompressor(object):
def decompress(self, s):
(chars, digit, nested_data) = self._parse(s)
# Non-compressed data.
if chars is None and digit is None and nested_data is None:
return s
... |
8c3eec5bf76bdac552aabaea03211fcab0333a65 | monkeylyf/interviewjam | /graph/pinball_maze.py | 4,632 | 4 | 4 | """pinabll_maze
Find the exit of the maze for Mr.Pinball.
Assuming: Maze is represented as a matrix, 0: path, 1: wall.
Entrance is at ?? and exit is at ??.
There will be at least one path leads to the exit of the maze.
"""
class GraphSolution(object):
""""""
def __init__(self, maze):
... |
c4dca9df4e1af1b440758b7bbf63601d46892244 | monkeylyf/interviewjam | /medium/leetcode_minimum_numbers_of_function_calls_to_make_target_array.py | 919 | 3.609375 | 4 | # https://leetcode.com/problems/minimum-numbers-of-function-calls-to-make-target-array/
from typing import List
class Solution:
def minOperations(self, nums: List[int]) -> int:
if not nums:
return 0
n = len(nums)
count = 0
while any(nums):
all_zero = True... |
04ee57c9b1b5200242f702481703e663c0799646 | monkeylyf/interviewjam | /math/LinkedIn_Product_Sequence.py | 733 | 3.8125 | 4 | """LinkedIn_Product_Sequence.py
LinkedIn
Given a positive number A, output all possible sequence with product equal to
A. No duplicates and all factors should be no-descending order.
"""
def solve(n):
"""Factorization is a wrong direction.
Simple recursion should be good enough to solve this problem.
"""... |
fb576f425b6e09af8b6f5e0da5c1166c13b9ba62 | monkeylyf/interviewjam | /hackerrank/hackerrank_Two_String.py | 303 | 3.546875 | 4 | """hackerrank_Two_String.py
https://www.hackerrank.com/contests/101hack19/challenges/two-strings
"""
def main():
t = int(raw_input())
for _ in xrange(t):
a = raw_input()
b = raw_input()
print 'YES' if set(a) & set(b) else 'NO'
if __name__ == '__main__':
main()
|
2db736104adce46695cdf33bfffa6c81519ccedd | monkeylyf/interviewjam | /misc/hackerrank_Utopian_Tree.py | 394 | 3.875 | 4 | """hackerrank_Utopian_Tree
https://www.hackerrank.com/challenges/utopian-tree
"""
def solve(n):
height = 0
for i in xrange(n + 1):
if i % 2 == 0:
height += 1
else:
height += height
return height
def main():
T = int(raw_input())
for _ in xrange(T):
... |
0e025565f1ef544c5a97703158ddc01885633906 | monkeylyf/interviewjam | /arr/leetcode_Two_Sum_III_Data_Structure_Design.py | 1,347 | 3.875 | 4 | """Two Sum III data structure design
leetcode
Design and implement a TwoSum class. It should support the following
operations: add and find.
add - Add the number to an internal data structure.
find - Find if there exists any pair of numbers which sum is equal to the
value.
For example,
add(1); add(3); add(5);
find(4... |
8836cc41cd9e8e493242b30b3480bd3c1d1a8d3a | monkeylyf/interviewjam | /medium/leetcode_search_suggestions_system.py | 431 | 3.515625 | 4 | # https://leetcode.com/problems/search-suggestions-system/submissions/
class Solution:
def suggestedProducts(self, products: List[str], searchWord: str) -> List[List[str]]:
# Or build a prefix trie.
products.sort()
res = []
for i in range(1, len(searchWord) + 1):
prefix ... |
680e9aec0a2dfc48a3ee649037e91ef4024f4236 | monkeylyf/interviewjam | /tree/leetcode_Binary_Tree_Maximum_Path_Sum.py | 1,209 | 3.921875 | 4 | """Binary tree maximum path sum
leetcode
Given a binary tree, find the maximum path sum.
For this problem, a path is defined as any sequence of nodes from some starting
node to any node in the tree along the parent-child connections. The path does
not need to go through the root.
For example:
Given the below binary ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.