blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
31d0035d01ba78f8c6c09028322b4723faea9d85
hoangtv8699/ML-DL-start
/machine-learning/multilayer-neural-network.py
3,568
3.875
4
from __future__ import print_function import numpy as np from sklearn.neural_network import MLPClassifier def softmax_stable(Z): """ Compute softmax values for each sets of scores in Z. each ROW of Z is a set of scores. """ e_Z = np.exp(Z - np.max(Z, axis=1, keepdims=True)) A = e_Z / e_Z.sum(a...
bad7c60a04b0acb67051f91a12743f33e6e3d2a4
michaelhuo/pcp
/remove_duplicates.py
383
3.859375
4
def remove_duplicates(head): #TODO: Write - Your - Code if not head: return head keys = set() result = head keys.add(result.data) curr = result node = result.next while node: data = node.data print(keys) if data not in keys: keys.add(data) curr.next = node curr = curr.n...
8edc815fd89c831fc7a25275b12bd70b3623f264
RamonFidencio/exercicios_python
/EX068.py
925
3.5625
4
import random cont=0 while True: pc = random.randint(1,10) con=0 usu=int(input('Digite um valor: ')) pi = input('PAR ou IMPAR [P/I]: ').upper() prd= (usu*pc) cont +=1 if pi == 'P': if prd%2 ==0: print('\n\n','-'*30,'\nVOCE VENCEU !!!') print(f'Voce jogou {usu}...
60f33cb16e00b66eb9d659861d43d84804442d0f
haukurarna/2018-T-111-PROG
/projects/hw4/priceOfStock.py
1,516
4.1875
4
def get_shares(): ''' Returns a valid number of shares input by user ''' while True: try: shares = input("Enter number of shares: ") return int(shares) except ValueError: print("Invalid number!") def get_price_info_as_strings(): ''' Returns price info...
f12660c503d72f613ee60f63ac53594a631763f8
melvinanthonyrancap/Exercises-for-Programmers-57-Challenges-Python
/Answers/exercise23.py
1,400
3.703125
4
import os os.system('cls') user_input = input("Is the car silent when you turn the key? ") if user_input.lower() == "y" or user_input.lower() == "yes": user_input = input("Are the battery terminals corroded? ") if user_input.lower() == "y" or user_input.lower() == "yes": print("Clean terminals and try starting a...
43e8bbed07f817944989f61abd5805dd671fe48b
anujastrivedi/PycharmProjects
/MagnusTraining/Excercise1/Question9.py
477
4.25
4
# Print multiplication table of 24, 50 and 29 using loop def print_table(table): i = 1 while i <= 10: mul = table * i print(f"{table} * {i} = {mul}") i += 1 if __name__ == "__main__": while True: table = input("Enter number to print the table or \'q\' to exit : ") ...
5118cf1f0a9337a463d47734f08dbc44b67d3565
Yifei-Deng/myPython-foundational-level-practice-code
/29(b).py
355
4.25
4
''' 视频中老师演示的代码 python开发基础29-元组 ''' #元组的切片操作 a = (1,2,3,4,5,6,7) print(a[1:6]) #强制类型转换 b = ['@','!','#'] #list to tuple c = tuple(b) print(c) print(type(c)) print(tuple('okay')) #string to tuple ''' Outputs: (2, 3, 4, 5, 6) ('@', '!', '#') <class 'tuple'> ('o', 'k', 'a', 'y') '''
a5667049448db340c96e351b8bc68ab872c9e9e7
anton-dovnar/LeetCode
/HashTable/Easy/500.py
553
3.703125
4
""" Keyboard Row """ class Solution: def findWords(self, words: List[str]) -> List[str]: keyboard_row = [] for word in words: word_lower = word.lower() if set(word_lower) == set(word_lower) & set("qwertyuiop"): keyboard_row.append(word) elif set(...
1d3aa6ba62852fdcfe9a9d27e0992327e0f0e33c
yinhuax/leet_code
/datastructure/Stack/MinStack.py
650
3.546875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Author : Mike # @Contact : 597290963@qq.com # @Time : 2020/12/18 23:47 # @File : MinStack.py class MinStack(object): def __init__(self): """ initialize your data structure here """ self.min_stack = [float('inf')] self...
7050eb5e889c54d73ab268f10eb6d5d8376b6106
ecmadao/Coding-Guide
/Notes/Python/Python及应用/clicker.py
4,199
4.1875
4
import click import os """ $ pip3 install click """ @click.command() @click.option('--count', default=1, help='Number of hello') @click.option('--name', prompt='your name', help='Input your name here') def hello_prompt(count, name): """ prompt option, user must input a option """ print('{} says:'.format(name)) ...
7ed8670877d09283d913c498332eb6f112c99b1b
Miguelflj/Prog1
/sala/Ex2.8.py
178
3.96875
4
#UFMT Ccomp #Miguel Freitas #Soma com parada -1 def main(): soma=0 a=input("Digite um valor: ") while (a != -1): soma = soma + a a=input("Digite um numero: ") print(soma) main()
4c11ab726db9abc269c07936c87a48356eee5c4d
Allen8838/Data-Science-Projects
/NYC Taxi/Modeling/feature_engineering.py
5,299
3.9375
4
"""create additional features""" import pandas as pd import numpy as np def create_cols_distances(df): """distance may be a critical feature for predicting trip durations. creating a haversine distance, manhattan distance and bearing (direction the car is heading)""" #create a column for haversine distanc...
41a91ff436e6cf25479f28d166a4ea577644485c
YskSt030/LeetCode_Problems
/1578.MinimumDeletionCosttoAvoidRepeatingLetters.py
1,710
3.6875
4
""" Given a string s and an array of integers cost where cost[i] is the cost of deleting the character i in s. Return the minimum cost of deletions such that there are no two identical letters next to each other. Notice that you will delete the chosen characters at the same time, in other words, after deleting a char...
04fffac964ec14cd1985f2397cee9e31e4822d9a
OlgaDrach/7
/лаб.7 (А).py
524
3.734375
4
#а) Дан текст, за яким слідує крапка. В алфавітному порядку вивести на екран (по разу) #усі малі українські голосні букви, що входять в цей текст.(Драч Ольга 122_Д) s = int(input(‘Введіть речення ‘) s1 = {'a', 'е', 'и', 'і', 'о', 'у', 'я', 'ю', 'є', 'ї'} if s[-1] == '.': s.replace('.', '') b = list(s) s1...
b5007dd9d74717af69d7c2a8ae67bc997ec4ae8d
MaximZolotukhin/erik_metiz
/chapter_4/exercise_4.3.py
194
3.9375
4
""" Считаем до 20: используйте цикл for для вывода чисел от 1 до 20 включительно """ for number in range(1, 21): print(number, end=' ')
1d1d649df156c99f2b7a173038078104bd896ffa
justawho/Python
/chapter2Q13.py
147
4.15625
4
print ('For loop example:') for i in range(1,11): print (i) print() j = 1 print ('While loop example:') while j < 11: print (j) j= j+1
e6d6ad7dd795ba5987f6fe1a300798429644c9e4
alkrauss48/talks
/python-documentation/code/example3.py
252
3.53125
4
def generate_total_price(amounts): return sum( [amt for amt in amounts if isinstance(amt, (float, int)) and amt > 0 ] ) * 1.08 if __name__ == '__main__': print(generate_total_price([1.78, -100, 10.88, 5.23, 'a']))
05984eb9a2bf6a477b7379cfcff0f6110da4bbc0
BJamesLebo/FirstRepository
/MonthlyLoanPayment.py
414
4.03125
4
#This program calculates and returns the monthly payments for a loan def calculate_payment (principal,annual_interest_rate,duration): if annual_interest_rate==0: return principal/(duration*12) r = (annual_interest_rate/100)/12 #monthly interest rate n = duration*12 #no. of monthly payments during lo...
5a1096cff6d3cc4535c189b2338ed19c105e2834
Bovey0809/Algorithm
/leetcode/912.sort-an-array.py
947
3.609375
4
# # @lc app=leetcode id=912 lang=python3 # # [912] Sort an Array # # @lc code=start import random class Solution: def sortArray(self, nums): def merge(left, right): result = [] while left and right: if left[0] < right[0]: result.append(left.po...
ea714c60f77d0c935d37c7f673fee0a975c49bb2
BaN4NaJ0e/webDJ
/votedb.py
1,507
3.578125
4
# coding: utf-8 import sqlite3 import time def setupDB(): # open sqlite db connection connection = sqlite3.connect("uservotedb.db") cursor = connection.cursor() cursor.execute("""DROP TABLE IF EXISTS votedb """) cursor.execute("""CREATE TABLE IF NOT EXISTS votedb ( trackid INTEGER, userip TEXT, timestamp...
9474fd8021a2fee53eac5012f2695cbd75076aa2
SACHSTech/basic-practice-Ahastan
/cake_jog.py
652
4.59375
5
''' ------------------------------------------------------------------------------- Name: cake_jog.py Purpose: Find out how far the user mus jog based on how many slices of cake they had Author: Surees.A Created: 02/12/2020 ------------------------------------------------------------------------------- ''' # How much...
9a817af941b650647c8b24053bd1e9d921c0c9b1
charlcater/aoc2020
/day_09/aoc2020_09.py
1,843
3.71875
4
# Advent of Code 2020 # --- Day 9: Encoding Error --- def two_sum(nums, target): compls = set() for x in nums: if x in compls: return True compls.add(target - x) return False def part1(nums): # more efficient solution, O(n) for i, target in enumerate(nums[25:]): ...
2fcc30ffffb2f29cbc4c0214d863dab2fba009a1
LaurenKScott/COMP151-the-lighthouse
/adventure.py
1,431
4.28125
4
# File: adventure.py # A simple text adventure game """ HOW TO PLAY Objective - get to the top of the lighthouse and signal for help. Instructions - when prompted, enter a command into the terminal. commands are one or two word phrases consisting of a verb and a noun or direction. use commands to move around the map ...
3aa187ff23419ff03fa73b6e9f93d8a7f81af809
TunedMystic/django-file-upload
/picsApp/simpleFileSize.py
581
3.59375
4
""" Amtex Training Project "Image Upload Program" Sandeep Jadoonanan October 24, 2014 """ def getSize(amt): """ This function takes a file size (in bytes) and converts the output into readable format. Supports file sizes in: 'bytes', 'kb', and 'mb'. """ fmt = lambda x: "{:,}"....
6ccaf672427ecda1990573a8b3bc2fab89154247
vinaygupta7/my-projects
/python_learning/22_method_overriding.py
464
3.859375
4
class Rectangle(): def __init__(self,length,breadth): self.length=length self.breadth=breadth def getArea(self): print(self.length*self.breadth,' is area of rectangle') class square(Rectangle): def __init__(self,side): self.side=side Rectangle.__init__(self,side,sid...
4468d98bc7f05358a2ac8178677cb0d315070dd3
coy0725/leetcode
/python/876_Middle_of_the_Linked_List.py
657
3.875
4
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): # def middleNode(self, head): # """ # :type head: ListNode # :rtype: ListNode # """ # res = [] # whil...
8a71b43e06fbeeb5d90450c579ca6c99deb92eb5
vmilkovic/automate_the_boring_stuff_with_python
/Chapter 7/strongPasswordDetection.py
876
3.765625
4
import re, pyperclip passLength = re.compile(r'.{8,}') # >= 8 characters passUpper = re.compile(r'[A-Z]') # Contains an upper case letter passLower = re.compile(r'[a-z]') # Contains a lower case letter passDigit = re.compile(r'[0-9]') # Contains a digit def checkPasswordStrength(password): if passLength.search(pa...
e7c87c499b0bf9f28fc6ab3e8a3a3308c8d2ffd3
chav-aniket/cs1531
/labs/20T1-cs1531-lab02/reverse.py
1,617
4.28125
4
def reverse_words(string_list): ''' Given a list of strings, return a new list where the order of the words is$ For example, >>> reverse_words(["Hello World", "I am here"]) ['World Hello', 'here am I'] ''' ret = [] for x in string_list: t = x.split(" ") t.reverse() ...
2bc8f39dc9f4c208ffc943065172362597a23df6
arihant-2310/Python-Programs
/second smallest single number.py
172
3.890625
4
a=[] n= input('enter number of elements:-') for i in range(n): e= input('enter element') a.append(e) a.sort() print('second smallest element:-') print a[1]
fc1d0045d0d76916ddbb8c472180b746efa71f3f
hisubhajit/Python-demo
/conditionDemo1.py
338
4.15625
4
print("This a first conditional demo program"); x = input("Please enter something: "); print("You have entered: "+x+ " , which is a "+str(type(x))); ''' If condition below code is example of if condition in python ''' print("Demo for IF condition"); name = input("Enter your name: "); if(len(name) > 5): print("Your...
16cc0add8a50a930aa9c940b936688069b120ccd
mylove1/PythonSamples
/python3/algorithm.py
364
3.921875
4
#!/usr/bin/python3 # -*- coding: utf-8 -*- # -*- author: c8d8z8@gmail.com import random def createNumArrayList(): size = 10 num_array = [] for i in range(size): num_array.append(random.randint(1,100)) return num_array #print(createNumArrayList()) def quickSearch(num_array): if num_arr...
8d231062ba949cc95969e373fb5d9aa731ba40d9
colevahey/pickem
/.py/login.py
1,212
3.625
4
import json import hashlib import adduser users = open('./users.json', 'r') userdata = json.loads(users.read()) def login(): uname = input("\033[H\033[2JUsername?\n>> ") password = input("Password?\n>> \033[8m") print("\033[0m") hash_object = hashlib.sha224(password.encode()) hashpassword = hash_...
66b47bdcf0d23644c4a46ee3f3f80d277f4155fe
weidizhang/genesis-asset-trader
/backtest_strategy.py
2,937
3.6875
4
import pandas as pd from predict import Predict # Essentially, alternate buy and sell transactions by alternating minimas # and maximas; must start with a buy (minima) # # Used for backtesting, mimicking behavior of buying or selling on the first # received minima or maxima signal, and applying the rule that buys and...
9182abbec90ec73371bf7f172e00b5ead3c25198
preeyankae/Innovative-Hacktober
/python_strings/str5.py
458
3.96875
4
value = 20 str = 'This another way of a string with a value {}'.format(value) print(str) value = 30 str = f'This another way of a string with a value {value}' print(str) Umm, I'm the one that made this pull request, you deleted it and said there were conflicts but there weren't cause you then merged it back into the...
555671538d750d280fc0db0374d582b8e31ce57d
hanlulu1998/Coursera-Machine-Learning
/ex2-logistic regression/Python/ex2funcReg.py
2,362
3.75
4
import matplotlib.pyplot as plt import numpy as np from ex2func import sigmoid, plotData def mapFeature(X1, X2): # MAPFEATURE Feature mapping function to polynomial features # # MAPFEATURE(X1, X2) maps the two input features # to quadratic features used in the regularization exercise. # # ...
be8cf0b046e72e146be67f775b018e94f48720d6
hanwjdgh/NLU-basic
/8. Deep Learning/3. LSTM/test1.py
1,127
3.5
4
from keras.models import Model from keras.layers import Input, Dense, LSTM import numpy as np x = np.array([[[1.], [2.], [3.], [4.], [5.]]]) y = np.array([[6.]]) xInput = Input(batch_shape=(None, 5, 1)) xLstm = LSTM(3)(xInput) #Lstm = LSTM(3, return_sequences=False)(xInput) many-to-one을 의미 xOutput = Dense(1)(xLstm) ...
88ac87a1ea7e34476a3ca6407b7b7022b3a1c7c7
granth19/Old-Python-Stuff
/MyClassTestMultiple.py
1,652
3.859375
4
class Vehicle: def __init__(self,sp): self.wheels = 4 self.speed = sp def accelerate(self,value): self.speed+=value def __str__(self): return "A vehicle with " + str(self.wheels) + " wheels." def stop(self): temp = self.speed self.speed = 0...
fd38b4f0b16dee299739a1dc1369ecb6db2d5b81
msc-27/AoC2019
/day22/day22-2.py
2,099
3.546875
4
with open('input') as f: lines = [x.strip('\n') for x in f] ssv = [x.split(' ') for x in lines] # Code for arithmetic mod p def modexp(a,b,p): # Calculate a^b mod p r = 1 power = a while b: if b % 2 == 1: r = (r * power) % p power = (power * power) % p b //= 2 return r # Fe...
4aad30e7261c187f086d57e45d069cc697ecc6d1
npstar/HackBulgaria
/week0/3/wc.py
681
3.578125
4
import sys def main(): count = 0 if sys.argv[1] == "chars": filename = sys.argv[2] file = open(filename, "r") content = file.read() for i in content: count += 1 print(count) elif sys.argv[1] == "words": filename = sys.argv[2] file = open(...
a5344c28a56f096a315b5d8573682c745c4d2747
jreag1/Examples
/Project_Euler/E02.py
540
3.6875
4
#Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: #1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... #By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms. d...
b713922ac7562903228e8af3f6cf4bc8bedbd11e
liyunfei1994/MyProject
/Data Structure/convert_to_binary.py
318
3.71875
4
import stack def divideby2(number): remstack = stack.Stack() while number >0: rem = number % 2 remstack.push(rem) number = number // 2 binstring = "" while not remstack.isEmpty(): binstring += str(remstack.pop()) return binstring print(divideby2(23)) # 10111
5ddb6c3f20a3158c8031414c5824b3c147e394f9
ThapaKazii/Myproject
/test4.py
494
4.03125
4
# Take five marks input from the user and then input into the list and then print the sum of all marks TOC=float(input("Enter the marks of TOC: ")) Maths=float(input("Enter the marks of Maths: ")) Programming=float(input("Enter the marks of Programming: ")) Statistics=float(input("Enter the marks of Statistics: "...
4a051cba8cbd4680e9afb86d450c5868a24b6ee5
hksoftcorn/Algorithm
/p_stack_01/sol1.py
334
3.6875
4
stack = [] class Stack: def __init__(self): self.data = [] def is_empty(self): return False if len(self.data) else True def push(self, item): self.data.append(item) def pop(self): if not self.is_empty(): return self.data.pop() else: ...
c134f7b2c622dfe2bb8d629e8140a062944851ef
garciaha/DE_daily_challenges
/2020-08-23/sig_figs.py
1,679
4.65625
5
"""Significant Figures Write a function that takes in a string representation of an integer or decimal number and returns the number of significant figures in the number. Significant figures are an important part of science because they provide an easy way to show the precision of a measurement at a glance. In general...
5efc38849b4dc53d5825c3f7c079d6bde4cc2052
thefiltitoff/python_tasks
/pr4_extra/Objects.py
902
3.75
4
""" Использование встроенных функций Напишите код, который выведет на экране все переменные объекта произвольного пользовательского класса. Напишите код, который по имени метода, заданному строкой, вызовет этот метод в объекте некоторого пользовательского класса. """ import own_hash def get_object_variables(obj): ...
0009fe5b3b239edb8ece3d093120c1298fca62a3
dockerizeme/dockerizeme
/hard-gists/2b19fd6f758ffd2e8ab9ec7d1f3f4b2c/snippet.py
4,548
3.6875
4
# Toy example of using a deep neural network to predict average temperature # by month. Note that this is not any better than just taking the average # of the dataset; it's just meant as an example of a regression analysis using # neural networks. import logging import datetime import pandas as pd import torch import...
0fbdbf7b75de2cfc1dc460fc687303263522ed9e
roboteer5291/advent-of-code
/2019/Day 2/solution.py
2,329
3.796875
4
def parse_file(file_name): # File to data format file = open(file_name) text = file.read() return parse_other_input(text) def parse_other_input(text): # Other input to data format vals = text.split(",") ints = [] for i in vals: ints.append(int(i)) return ints def solve_part_1(d...
d8cdd92c743ca20158241c40c07a83cdc7795031
nathanlmetze/Algorithms_Python
/Algorithms.py
2,393
4
4
# ONLY ASSUMPTION IS THAT THE GRAPH IS SETUP THE SAME WAY USING A DICTIONARY # BY NATHAN M # Helper class used to store each node and what it is connected to class adjacency_list(object): def __init__(self, key): self.key = key self.connections = {} def add_adjacency(self, neighbor, weight = 0)...
efd11710b5fb7919c94ca23d5df1ca1a2765d687
banderquartz/Python-Learning
/weekly_exercises/odd_even.py
373
4.0625
4
''' Created on Nov 18, 2014 @author: mike ''' while True: try: num = int(input("Please enter an integer: ")) if num % 2 == 0: print("The number " + str(num) + " is even.") else: print("The number " + str(num) + " is odd.") break except ValueError: ...
2a89206f5d1375fba64768eb04f2cbb3e988ae69
wavesCHJ/First
/learn05_map_reduce_filter_sorted.py
3,942
3.96875
4
#map/reduce #我们先看map。map()函数接收两个参数,一个是函数,一个是Iterable, #map将传入的函数依次作用到序列的每个元素,并把结果作为新的Iterator返回。 def f(x): return x * x r = map(f, [1,2,3,4,5]) print(list(r)) r = map(str, [1,2,3,4,5]) print(list(r)) #再看reduce的用法。reduce把一个函数作用在一个序列[x1, x2, x3, ...]上, #这个函数必须接收两个参数,reduce把结果继续和序列的下一个元素做累积计算, #其效果就是: #reduce(f, [...
d34979539879f6e93d54cb0c4e7511a74a84f0d2
boboyiyi/learn_python
/book1/data_type/l_list.py
1,203
3.796875
4
# -*- coding: utf-8 -*- ''' 列表支持所有类似string的序列操作 ''' test_list = [180, 'fanbo', 1.80] print len(test_list) print test_list[0] # 索引 print test_list[:-1] # 切片 print test_list + [158, 'cxm', 1.58] # 连接 print test_list * 3 #类型特定的方法 test_list.append('hehe') print test_list # 这里貌似append的返回值是NONE,所以直接printf会打印NONE print test_...
582911f5be92b01103c01cc23201a7309f1f089c
GlauberC/UFRN
/CompeticaoProgramacao/aula01/d.py
140
3.5
4
testes = int(input()) for test in range(0,testes): n, m = input().split() x = int(int(n) / 3) y = int(int(m) / 3) print(x*y)
c48ca7c35767340f0d9d80e945db67281198dc01
Justinpy8/desktop_excercis
/Exc_3.4to3.7.py
2,047
4.15625
4
# 3.4 guests = ['Tony', 'Kevin', 'Holly'] print(guests[0] + ' I would like to invite you to our house warming party dinner.') print(guests[1] + ' I would like to invite you to our house warming party dinner.') print(guests[2] + ' I would like to invite you to our house warming party dinner.') # 3.5 print(guests[-1]...
5030639b7d50db1c67beb08985d44250705b1e91
pallavi12coder/pallaviuike2020
/6.py
971
3.859375
4
#To retrieve all records and columns from table import pymysql #STEP 1 : create connection string python with mysqlserver servername="localhost" username="root" password="" dbname="school_vedant" #dbname means database name try: con=pymysql.connect(servername,username,password,dbname) #con user defined obj...
791db0c033b27c2d95df208011c6cc4385b69c11
youthinnovationclub/2019MoonLanding50thAnniversaryProject
/PythonProject/terrain.py
2,090
3.84375
4
import turtle import random # TODO: decide off screen behaviour def getYPoint(x): """ Finds the y point of the line given an x """ global coords afterX = 0 afterY = 0 for coord in coords: if x == coord[0]: return coord[1] beforeX = afterX beforeY = afterY afterX = coord[0] afterY = ...
dc27b35a1e746758f8f72ba3cc2304c675c4ebb1
Tanay2112/Python-Codes
/sameRowWord.py
418
3.984375
4
word=input() r1="qwertyuiop" r2="asdfghjkl" r3="zxcvbnm" c=0 if word[0] in r1: for ch in word: if not ch in r1: c=-1 break elif word[0] in r2: for ch in word: if not ch in r2: c=-1 break else: for ch in word: if not ch ...
91f17d264faf50e1bbf3143b26b9090d3bc2212d
sgupta25/Python-Camp-2016
/guessing game 1-.py
1,961
3.84375
4
try: n=5 while n >0: n = n -1 print "you have five tries to sink a battle ship" print " you have to guess 5 numbers between 1-20" print "if you hit a mine, the game is over" x = raw_input ("enter a number") x = float (x) if x == 1: print 'no battle ship' print str(n)...
bb063e0516b9276c5684846ee4db0a2f2b83b154
sunweiye12/python-BasicLearning
/02_面向对象/py_02_基础语法.py
3,350
3.96875
4
# -----------------------------------知识点------------------------------------------- """ 1.内置函数( __方法名__ 格式的方法是 Python 提供的 内置方法 / 属性):一下是常用的内置方法 01 __new__ 方法 创建对象时,会被 自动 调用 02 __init__ 方法 对象被初始化时,会被 自动 调用 03 __del__ 方法 对象被从内存中销毁前,会被 自动 调用 04 __str__ 方法 返回对象的描述信息,print 函数输出使用(...
bc89cd2beacaedee09502e3f1d47d9694b95b554
SutronPyto/LinkPython
/src/dga.py
3,913
3.546875
4
# Example: demonstrates formatting a message in DGA format import re from sl3 import * class SetupError(Exception): pass def cell_sig_str_bars(): """ Returns the cell modem signal strength in bars :return: signal strength in bars (0 to 4) :rtype: int """ # assume there is no signal ...
fc10dd2e6bacc01aa1f752dafc9b47a2d989f55f
gurnit1/Python_Projects
/Practice of Computing Using Python/Facebook/Project07Facebook.py
3,223
3.890625
4
""" File of function stubs for Project 07 @author: enbody """ # Uncomment the following lines when you run the run_file tests # so the input shows up in the output file. # #import sys #def input( prompt=None ): # if prompt != None: # print( prompt, end="" ) # aaa_str = sys.stdin.readline() # aaa_str = ...
e4ffbe461144747dfa9860c573eb700e23a2b4d7
arovit/Coding-practise
/dynamic_prog/magic_index.py
724
3.890625
4
#!/usr/bin/python def find_magic_index(array, start, end, mlist): print "start %s end %s "%(start, end) if not (start < end): return mindex = (end - start)/2 if mindex == 0: return else: mindex += start if array[mindex] > mindex: find_magic_index(array, start,...
b78ba92d6fa9b2689ab326c7e01babc412c09622
ohadomrad/Examples
/ImagesWithKeras/ConvertImageWithKeras.py
1,074
3.625
4
# -*- coding: utf-8 -*- """ Created on Sun Nov 3 08:25:53 2019 Use Keras img_to_array() function to convert a loaded image in PIL format into a Numpy array (for deep learning models). Use Keras array to img() function to convert a Numpy array of pixels data into a PIL image. In the example, lo...
fb7935a3d1a600b40a4871e43a351b65bd0720a5
AmbujaAK/practice
/python/nptel-Aug'18/assg2.py
293
3.609375
4
def wellbracketed(s): depth = 0 for i in range(0,len(s)): if s[i] == '(': depth += 1 elif s[i] == ')': if depth > 0: depth -= 1 else : print('False') return depth == 0 s = input() wellbracketed(s)
2268b51b7c199f05fc84df48c7aeb5c4c287c075
Tinkotsu/geekbrains_hw
/task_3.py
957
3.703125
4
class Cell: def __init__(self, amount): self.amount = int(amount) def __add__(self, other): new = Cell(self.amount + other.amount) return new def __sub__(self, other): if self.amount - other.amount > 0: new = Cell(self.amount - other.amount) return n...
8f5ac614500148f59570dedbdb4f85b9ef46751a
benmaier/numpyarray_to_latex
/numpyarray_to_latex/utils.py
843
3.59375
4
""" Provide helper functions. """ import numpy as np def math_form(number, is_imaginary=False, mathform=True): r""" Convert a float number formatted in scientific notation to the corrsponding LateX format (e.g. ``2\times10^{2}``). """ if mathform: if 'e' in number: significand,...
f8d8894f176c023e7b1ef58254c9a478a28949a6
starman011/python_programming
/02_Lists&tuples/03_pr_03.py
82
3.578125
4
#to check that a tuple value cannot be changes a = (1,2,4,56,3) a[0] = 45 print(a)
54aae5f25aafd50666df3443b80c4ecd8305ea1c
SafonovMikhail/python_000577
/001146StepikPyBegin/Stepik001146PyBeginсh09p01st07TASK06_20210125.py
760
3.984375
4
# str1 = input() str1 = 'abcdefghijklmnop' # for i in range(0, len(str1) - 1, 2): for i in range(0, len(str1) - 1, 2): print(str1[i]) ''' На вход программе подается одна строка. Напишите программу, которая выводит элементы строки с индексами 0, 2, 4, ... в столбик. Формат входных данных На вход программе подаетс...
b7f126427439c26b649ee20394aea79b937b2af0
egreen18/DegreeDesign
/modelclass.py
1,111
3.796875
4
#Class object for storing data on each class class Class(object): #Initilzation and attribute definition def __init__(self): self.program = '' self.title = '' self.credits = 0 self.description = '' self.prereqs = [] self.terms = [] #Method for loadin...
0e52fae02742566e5d8ce662c68b71d3ae7fb5ec
jaitul25/Triangle567
/TestTriangle.py
827
3.515625
4
import unittest from Triangle import classify_triangle class TestTriangles(unittest.TestCase): def testEquilateralTriangle1(self): self.assertEqual(classify_triangle(5,5,5),'Equilateral Triangle') def testEquilateralTriangle2(self): self.assertEqual(classify_triangle(7,7,7),'Equilateral Tr...
9aaaf7ed305bfcdd73c288fc32f60a0d94eae08d
Textualize/textual
/src/textual/case.py
524
3.9375
4
import re from typing import Match, Pattern def camel_to_snake( name: str, _re_snake: Pattern[str] = re.compile("[a-z][A-Z]") ) -> str: """Convert name from CamelCase to snake_case. Args: name: A symbol name, such as a class name. Returns: Name in camel case. """ def repl(ma...
b69eb76a540a62c35230687927eef1aca6c77544
ayananygmetova/Web-Dev-2020
/week8/coding_bat/list-1.py
2,538
3.5625
4
<<<<<<< HEAD #first_last6 def first_last6(nums): if nums[0]==6 or nums[len(nums)-1]==6: return True else: return False #same_first_last def same_first_last(nums): if len(nums)==1: return True else: if len(nums)>1 and nums[0]==nums[len(nums)-1]: return True return False #make_pi def...
049313910326e74c095b85d9be4b331db9de906c
pranaymate/PythonExercises
/ex040.py
354
4.09375
4
first = float(input('First score: ')) second = float(input('Second score: ')) grade = (first + second) / 2 print('Getting {} and {}, the final grade will be {}'.format(first, second, (first+second) / 2)) if grade >= 7: print('The student has passed!') elif 5 <= grade < 7: print('the student in recovery.') else:...
0280579537e24b4a04d15821f3bf1687bf9e108c
HishamKhalil1990/math-series
/tests/test_series.py
1,756
3.71875
4
from math_series.series import fibonacci,lucas,sum_series def test_fibonacci(): expected = 3 input = 4 actual = fibonacci(input) assert actual == expected def test_lucas(): expected = 29 input = 7 actual = lucas(input) assert actual == expected def test_sum_series_fibonacci(): exp...
1fc6bd6244d3d98b338b6b813103dfc00f16e75f
ararage/flask_python
/classes_objects.py
844
3.640625
4
lottery_player_dict = { 'name':'Rolf', 'numbers':(5,9,12,3,1,21) } class LotteryPlayer: def __init__(self,name): self.name = name self.numbers = (5,9,12,3,1,21) def total(self): return sum(self.numbers) player = LotteryPlayer("Rolf") player.numbers = (5,9,12,3,1,21) pla...
d249827c01c6d14b04eb7bbdcfedbb82d9b16cf3
txqgit/LeetCode
/CodePython/DictTree/648_Replace Words.py
1,273
3.921875
4
class Node: def __init__(self, value=None): self.val = value self.is_leaf = False self.children = {} class Tire: def __init__(self): self.root = Node() def insert(self, word): node = self.root for w in word: if node.children.get(w, None) is None...
5b23048fc9a3c5f30b3e073cd75f5b0f729c1424
FluffyTrooper2001/cp1404practicals
/prac_08/unreliable_car.py
543
3.5625
4
from car import Car import random class UnreliableCar(Car): def __init__(self, fuel, name, reliability): super().__init__(fuel, name) assert reliability <= 100 and reliability >= 0 self.reliability = reliability def drive(self, distance): rand_num = random.randint(0,...
2896c7146083aacfc259dfd52cbc1616ed40a325
HolyQuar/git_operation
/python_operation/datad_structures_2/list_expressions_nested_functions.py
1,157
4.03125
4
if __name__=='__main__': from math import pi pi_str=[str(round(pi,i)) for i in range(1,6)] print(pi_str) # Consider the following example of a 3x4 matrix # implemented as a list of 3 lists of length 4 matrix = [ [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], ] # tra...
f2d36b59287c059a82b84db89fbe511b89560368
Akashdeep-Patra/problemSolving
/Math/Points inside Rectangle.py
2,246
3.578125
4
""" Points inside Rectangle Problem Description You are given a rectangle with co-ordinates represented by arrays A and B, where the sides might not be parallel to the x-y axis. Given N points on x-y plane whose co-ordinates are represented by arrays C and D, count the number of points that lie strictly inside the rect...
f869200706bae4f16b595ec8aa6f55c60233e156
kostyantynHrytsyuk/py-garch
/arrays.py
4,442
4.0625
4
""" File : arrays.py An Abstract Data Type (ADT) for presenting a collection with fixed size """ import datetime import ctypes import pandas as pd class Array(object): def __init__(self, length, values=None): """ Constructor for array creates inner collection and initialize it with value...
f81d1b37817d00eba34b59a5e5efc9bef35dbb7e
AK-1121/code_extraction
/python/python_26620.py
126
3.609375
4
# Format a string with a space between every two digits s = "534349511" print ' '.join([s[i:i+2] for i in range(0,len(s),2)])
b48e1aac779c177c26d24a0cf311478b55bef812
sonbui00/HackerRank-Algorithms
/Warmup/plus_minus_test.py
466
3.671875
4
import unittest from plus_minus import plusMinus class TestSimpleArrayFunction(unittest.TestCase): def test_plus_minus(self): data = [ [6, [-4, 3, -9, 0, 4, 1], ['0.500000', '0.333333', '0.166667']] ] for item in data: self.assertEqual( item[2] ,plusMinus(item[0], item[1]) ,"Test plusMinus() w...
dc57838e0bc565a41b975cfef11500ad7dc19ea8
SDSS-Computing-Studies/004d-for-loops-ssm-0123
/problem1.py
538
4.3125
4
#!python3 """ ###### Problem 1 Ask the user to enter in the width and height of a box. This should be an integer value less than 10 Draw a box filled with "*" symbols that matches the width and height. You will need 2 nested loops to draw the contents of 1 row and the number of rows. inputs: int number outputs: exa...
c1a4e5269a791e1fc2a928b2507f294e7f4ea8a7
deepakjoshishri/Movie-Website
/media.py
2,565
3.703125
4
#!/usr/bin/python # -*- coding: utf-8 -*- # Parent class class Media: """ This class provides a way to store generic information related to media""" # documentation for base class def __init__(self, title, poster_image, genre, trailer_youtube): self.title = title sel...
7c238959abf883312b033b8a08bab36f6d3dbd44
marcelo-py/Exercicios-Python
/exercicios-Python/dasaf075.py
567
3.765625
4
n1 = int(input('Digite um numero')) n2 = int(input('Digite outro número')) n3 = int(input('Mais um numro')) n4 = int(input('Agora o último numero')) lista = (n1, n2, n3, n4) print('os números digitados foram {}'.format(lista)) print('O número 9 apareceu {}x'.format(lista.count(9))) if 3 in lista: print('O numero 3 ...
c2e3c6e9d82c193fd87f48a9ab04fdfc3d11a167
bala4rtraining/python_programming
/python-programming-workshop/pythondatastructures/while/pass.py
243
4.03125
4
import random def m(): # Get random number. n = random.randint(0, 3) print(n) # Return true if number is less than 3. return n <= 2 # Call method until it returns false. while m(): # Do nothing in the loop. pass
997740da26865460380ef16e0ab706e89440e9bd
PanagiotisSamios/Pythonexer
/Askisi_6.py
509
3.921875
4
import calendar calendar.setfirstweekday(calendar.SUNDAY) month = int(input('Give month in number ')) if month > 12 or month < 0: print ('not valid month') else: year = int(input('Give year ')) print ('\t', '\t', calendar.month_name[month], year, '\n') print ("S\tM\tT\tW\tT\tF\tS") calendar = calendar.monthcalenda...
e1ad30ee912b198b04fba12066158921d22eb910
Yigang0622/LeetCode
/verifyPostorder.py
975
3.609375
4
# LeetCode # verifyPostorder # Created by Yigang Zhou on 2020/9/20. # Copyright © 2020 Yigang Zhou. All rights reserved. # 剑指 Offer 33. 二叉搜索树的后序遍历序列 # https://leetcode-cn.com/problems/er-cha-sou-suo-shu-de-hou-xu-bian-li-xu-lie-lcof/ from typing import List class Solution: def verifyPostorder(self, postorder: L...
6f330d23564fed43dbeb922543cb95796a0a1ae7
Sanchez-Antonio/python-learn-in-spanish
/colecciones/diccionarios.py
1,127
4.03125
4
#los diccionarios nos permiten además de almacenar cualquier tipo de valor # identificar cada elemento por una clave (Key). #Para definir un diccionario, se encierra el listado de valores entre llaves. # Las parejas de clave y valor se separan con comas, y la clave y el valor se separan con dos puntos. diccionario = ...
4544bba1424d1c381871ad48e51f5a390d74fd39
RP-Hall/harry-plotter
/src/Graph.py
4,289
3.59375
4
""" This is the class which represents a Graph object """ from parser import * import numpy as np class Graph: errorMsg = None def __init__(self, expr=None, filename=None, dim=None, xMin=None, xMax=None, yMin=None, yMax=None, plotType=None, lineType="Solid", opacity="additive", lineWidth=2, name = None, colSt...
718c40189800b016079665c375e55fef51b90fa1
rafaelmdurante/cs50pset
/psets/pset6/dna/dna.py
2,365
3.734375
4
# handle system args import sys # handle csv files import csv def main(): # validate args validate_args(sys.argv) # calculate short tandem repetitions match = find_match(sys.argv[1], sys.argv[2]) # print match print(match) def validate_args(args): # validate amount of args if len(arg...
b17fa0301cd45ffd97a23ba793da0ff18e8a196f
sum1t9/python-beginner
/exception handling.py
195
4.15625
4
while True: try: number = int(input("Enter a number :")) break except: print("You did not enter a number") print("Thank yor for entering a number")
b6ea536daa54288dd53f4a5a2841236cde8fdb18
rafaelperazzo/programacao-web
/moodledata/vpl_data/9/usersdata/134/4336/submittedfiles/crianca.py
398
3.734375
4
# -*- coding: utf-8 -*- from __future__ import division p1 = input('Digite o peso da criança da esquerda:') c1 = input('Digite o comprimento do lado esquerdo da gangorra:') p2 = input('Digite o peso da criança da direita:') c2 = input('Digite o comprimento do lado direito da gangorra:') if p1*c1==p2*c2: print('0'...
d5dff22deadad0d9f8e1724e204f0e3da2c2fc00
nyowusu/ProgramFlow
/while_loops.py
1,171
4.03125
4
import random highest = 10 play = ['yes', 'Yes', 'y', 'Y'] # guess = int(input("Guess a number between 1 and {} ".format(highest).strip())) guessAgain = 'y' numGuess = 0 # while guess != answer: # if guess > answer: # guess = int(input("Guess lower than {} ".format(guess).strip())) # else: # g...
f0c412a342d408369528ac7177748dae06b3e772
trevisanj/aleatools
/aleatools/scripts/text2png.py
2,969
3.703125
4
#!/usr/bin/env python """ Converts text to PNG image Creates specially to convert ASCII monospace diagrams to PNG image Based on gist: https://gist.github.com/destan/5540702 """ from PIL import ImageFont from PIL import Image from PIL import ImageDraw import argparse import sys import os def text2png(lines, fullpa...
126c4328120ea3dabd21940487431903c7ecd3e9
bilge-gocer/simple_python_projects_from_pycharm
/factors.py
308
4.1875
4
# Count factorial numbers in a given range def factorial(num): result = 1 for x in range(1, num + 1): result = result * x return result number1 = int(input("Enter a number: ")) number2 = int(input("Enter another number: ")) for n in range(number1, number2): print(n, factorial(n))
2eaaab2b0eb23e31f1a3575fa0e4a34d424599b2
uoayop/study.algorithm
/baekjoon/15953.py
975
3.578125
4
#15953 상금헌터 import sys def f1_money(a): if (a==1): return f1[0] elif (a==2 or a==3): return f1[1] elif (4<=a and a<=6) : return f1[2] elif (7<=a and a<=10) : return f1[3] elif (11<=a and a<=15) : return f1[4] elif (16<=a and a<=21): r...
698c03f0dde6490c074ffb09f82bec197504e09e
maumneto/IntroductionComputerScience
/CodeClasses/SequentialCodes/cod2.py
336
3.75
4
nome = input('Entre com o nome: ') matricula = int(input('Entre com a matrícula: ')) curso = input('Entre com o seu curso: ') idade = int(input('Entre com a sua idade: ')) email = input('Digite seu email: ') print('Nome: ', nome) print('matrícula: ', matricula) print('Curso: ', curso) print('Idade: ', idade) print('Em...
2edc16b0f632eb27070c07134a14f7cdadf5389d
AozzyA/homeCode
/boolean.py
690
3.96875
4
import ast # This is a boolean parser. It handles the following expressions # True and True X # True or True X # True and False X # True or False X # False and False X # False or True X # False and True X # False or False X userTyped = input('Enter a boolean experession.').strip() words = userTyped.split(' ') a = wo...
25f5b6f75e54838581efa34faa2afac035c4b42a
LowerDeez/python-cookbook
/memory_management_in_cyclic_data_structures(tree).py
4,331
3.859375
4
from typing import List, Dict, Optional import weakref """ A simple example of a cyclic data structure is a tree structure where a parent points to its children and the children point back to their parent. For code like this, you should consider making one of the links a weak reference using the weakref library. For e...
92d6a460fd63bb187d94fff02a4ced14f657656f
founek2/python
/docs/_lessons/lesson4/uniq.py
421
4
4
# that takes a list and returns a new list with unique elements of the first list def uniq(list): values = [] for x in list: if x not in values: values.append(x) return values assert uniq([1, 2, 3]) == [1, 2, 3] assert uniq([10, 10, 3]) == [10, 3] assert uniq([10, 2, 10]) == [10, 2]...