blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
b50c668c4c45f37217dfd6ade5a9e5de105ba91e
tjsaotome65/sec430-python
/module-06/transcript.py
544
3.5
4
""" File: transcript.py Project 10.10 This module defines the Transcript class. """ class Transcript(object): """This class represents transcript of chat messages.""" def __init__(self): """Creates a list of messages.""" self.messages = ["No messages yet!\n"] def __str__(self): ""...
22fed7a45b55c4a9542c2d6e8691239161905e2d
yang199811225430/yang1
/python/untitled1/day1.py
26,296
3.859375
4
#!/usr/bin/python #定义一个解释器 #-*- coding:utf-8 -*- 定义编码方式 #print('hello',123,456,789) 输出 # a=input('请输入密码:') #print(a) #a,b,c='ycx',1,2.1 #print(b+c) #print(type(c)) # a='asbf1234de' # print(a[2::-2]) #b=a.upper() #b=a.replace(' ','',3) #b=a.split('bf') #b=a.rstrip() #b=a.startswith('asb') #b=a.endswith('de') #c='+'....
4b382a778e2d2aba9bca7cc8abee78535f523409
Jadams29/Coding_Problems
/Regular_Expressions/RegEx_MatchEmail.py
720
3.828125
4
import re # ---------- PROBLEM ---------- # Match email addresses # 1. 1 to 20 lowercase and uppercase letters, numbers, plus ._%+- # 2. An @ symbol # 3. 2 to 20 lowercase and uppercase letters, numbers plus .- # 4. A period # 5. 2 to 3 lowercase and uppercase letters # \d : [0-9] ----> an number 0-9 # \D : [^0-9] ...
8bb7c7b6eea59dadbde8a20abcb0728dd5217533
ddawidowicz/pywing
/pywing/norm_data.py
680
4.125
4
# Usage: # normalize(X) # # Input: # X = a numpy array of numbers where each column is a different feature # and each row is a different observation # # Outputs: # X_norm = normed X array (mean=0, std=1) # mu = mean used in norming # sigma = std used in norming # import numpy as np def normalize(X): num_r...
5c9c89c341c0a7f81ba9cc78c8a241530d50b12a
Livenai/100-lambs
/scripts/geometry.py
6,144
4
4
from math import sqrt class Point: def __init__(self, x, y): self.x = float(x) self.y = float(y) def __str__(self): return "(x: {0}, y :{1})".format(self.x, self.y) def __repr__(self): return "(x: {0}, y :{1})".format(self.x, self.y) def __add__(self, other): ...
9787cfeccc688635a52cefe11ad6d3172f77ed50
lulini1/Code-book
/Exercise/知识.py
1,265
3.828125
4
#作图程序模版 ##•首先,导入turtle模块 ##•然后,生成一只海龟 ##•可以做一些初始化设定 ##•程序主体:用作图语句绘图 ##•最后结束作图 ##•可选隐藏海龟:t.hideturtle() # 1. 导入海龟模块 import turtle n = 300 # 2. 生成一只海龟,做一些设定 t = turtle.Turtle() t.pencolor("black") # 画笔颜色 t.pensize(n*0.10) # 画笔粗细 t.fillcolor("yellow") # 3. 用海龟作图 #for i in range(5): #t.forward(50) #t.right(60) ...
8350dd1c2f852c0bd55658ddf21e4ae3e3a06205
ITianerU/algorithm
/leetcode/22_括号生成/python.py
1,075
4.0625
4
""" 给出 n 代表生成括号的对数,请你写出一个函数,使其能够生成所有可能的并且有效的括号组合。 例如,给出 n = 3,生成结果为: [ "((()))", "(()())", "(())()", "()(())", "()()()" ] 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/generate-parentheses """ from typing import List class Solution: def generateParenthesis(self, n: int) -> List[str]: r...
c4ac3b74c9d4677cdd90c55e89cfe81f23c342f0
dsuyash08/Miscellaneous-Algorithms-Unordered
/data structure week 1/data structure week 1/tree-height.py
1,399
3.71875
4
# python3 import sys, threading from collections import deque sys.setrecursionlimit(10**7) # max depth of recursion threading.stack_size(2**27) # new thread will get stack of such size class TreeHeight: def read(self): self.n = int(sys.stdin.readline()) self.parent = list(map...
38da91009c281aee57076aafbe360111fe8bb3e2
sandhyaramavathu/pythonprograms
/80.py
168
3.6875
4
n = int(raw_input()) digits = [] while n>0: r = n%10 if r&1! = 0: digits.append(str(r)) n = n/10 digits = reversed(digits) print (" ".join(digits))
eb5cb4fd744625e2daf9780811bac643c0819898
chanakyack15/code-in-python
/max.py
261
4.125
4
value=int(input("enter 1st no")) value1=int(input("enter 2nd no")) value2=int(input("enter 3rd no")) print ("MAX no in all 3 no is:") print (max(value,value1,value2)) print ("MIN no in all 3 no is:") print (min(value,value1,value2)) input("enter to exit")
8690400786239d6f14a22d39637f027d2df5c15d
vaibhavg12/udacity-introduction-to-python
/project/analyze_data_chicago.py
4,723
3.5
4
import pandas as pd path = "C:\\Users\\gv01\\Desktop\\googleSync\\LEarning\\Udacity\\Data Scientists Foundation\\python\\Resources\\" filename = 'chicago.csv' chicago_df = pd.read_csv(path+filename) # df.head(), df.columns, df.describe(), df.info() # df['column_name'].value_counts(), df['column_name'].unique() def ...
6d13073c4510cc78690909a2d6b0c7b6fba067d6
PrarabdhGarg/CryptocurrencyTrial
/blockchain.py
3,530
3.875
4
# -*- coding: utf-8 -*- """ Created on Thu May 28 17:43:53 2020 @author: prara """ import datetime import hashlib import json from flask import Flask, jsonify # Building the blockchain class Blockchain: def __init__(self): self.chain = [] self.create_block(proof = 1, prev_hash = '0') ...
c0563073d63d71e6aa8d6f5d830586202b0ca360
Jexan/ProjectEulerSolutions
/src/E020.py
299
3.6875
4
# Get the sum of the digits of factorial of 100. # OPTIMAL (<0.1s) # # APPROACH: # Get the factorial, convert the number to string and sum all the digits. from math import factorial LIMIT = 100 def sum_fact_digits(n): return sum(map(int, str(factorial(n)))) result = sum_fact_digits(100)
6fa4724896eeb16797cd61cad4113f7e7dfeb13c
ryandawsonuk/UdemyMachineLearningAtoZPythonAndR
/17 - Apriori Association Rule Learning/Apriori_Python/apriori.py
1,404
3.703125
4
# Apriori # Importing the libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd # Importing the dataset #The data set needs to be transformed to a list of lists dataset = pd.read_csv('Market_Basket_Optimisation.csv', header = None) transactions = [] for i in range(0, 7501): #our master lis...
4dd5ffa53c4986b5c1726ec2e2b16d01a07b8cb2
Alex7lav81/Group_22
/Python_HW/HW_4/Task_2.py
1,719
3.921875
4
''' Задача №2 ===== Обменник ===== Создать скрипт, который будет запускаться из консоли 1 раз, выдавать результат и зарываться. 1. На вход обменнику вводишь количество денег int. 2. На выходе в консоль выводится отввет в таком виде: "Вы ввёли int (Валюта)" "Конвертированная сум...
0c6d396ce9e7830d888da0e77204992c40c91cc2
shubhamoli/solutions
/leetcode/medium/1414-Min_fib_sum_k.py
856
3.5
4
""" Leetcode #1414 """ class Solution: # It is guaranteed that for the given constraints # we can always find such fibonacci numbers that sum k. def findMinFibonacciNumbers(self, k: int) -> int: #find fib numbers up to k fibo = [1,1] while fibo[-1] <= k: fibo.append(...
08f769856ca72e30a3d85fb8e6f8946252cce02f
AleksMaykov/GB
/lesson1_normal.py
1,849
4.03125
4
import time # Задача: используя цикл запрашивайте у пользователя число пока оно не станет больше 0, но меньше 10. # После того, как пользователь введет корректное число, возведите его в степерь 2 и выведите на экран. # Например, пользователь вводит число 123, вы сообщаете ему, что число не верное, # и сообщаете об диап...
df1283b20d8eb7a8c35641d128d0a57df25e431e
Serjeel-Ranjan-911/CSES-Solution
/Introductory Problem/Tower of Hanoi/sol.py
250
3.6875
4
n = int(input()) print(2**n - 1) def toh(n,source,destination,aux): if n == 1: print(source,destination) return toh(n-1,source,aux,destination) print(source,destination) toh(n-1,aux,destination,source) toh(n,1,3,2)
c34ba7b063c024a76776566bc092cfffc35e62da
mousemgr/CETI-Python
/AdivinarNumeroWhile.py
752
3.703125
4
import random respuesta = -1 piso = 0 techo = 50 intentos_jugador = 1 numero_random = random.randint(1,50) intentos_totales = 4 print(numero_random) print("Estoy pensando un numero entre 1 y 50") while respuesta != numero_random and intentos_jugador<=intentos_totales: respuesta = int(input("Intento " + str((inte...
b711cb64f4762919774c5d28911bcb3a41022ead
davidozhang/codeforces
/life_without_zeroes.py
368
3.6875
4
#!/usr/bin/python ''' Problem 75A: http://codeforces.com/problemset/problem/75/A Solved on: 2015-03-08 Result: Accepted 92 ms 8 KB ''' def main(): first, second=raw_input(), raw_input() if (int(str(int(first)+int(second)).replace('0','')))==int(first.replace('0',''))+int(second.replace('0','')): print 'YES' else...
49c58812085b9bb9d521523a19e6ec2d5f7dcdd6
Parya1112009/mytest
/revstring.py
142
3.890625
4
import string str1 = "this is new york" a = str1.split() a.reverse() print a result = " ".join(a) s = type(result) print result print s
624ab4273f05b0acae793703dd00304c977ba260
benzoa/pythonStudy
/basics/ex21_exception.py
2,518
3.90625
4
try: x = int(input("number: ")) y = 10 / x print(y) except: print("exception occured") print("=" * 40) val = [10, 20, 30] ''' try: idx, x = map(int, input("index and number: ").split()) print(val[idx] / x) except ZeroDivisionError: print("The number cannot be divided by zero.") except In...
968f4d2e8516d8045ef3507ddf3205a50ebf4705
kevinrajk/pythonprogramming
/basicstring.py
1,088
4.125
4
program: print("Hello World") print("Hello ") a=10 b=20 c=a+b print(c) mystring='hi python'+' programming' print(mystring[2:9]) print(mystring.split(' ')) print(mystring.find('p')) print(mystring.replace('hi','hello')) print("the length of the string is",len(mystring)) output: Hello World ...
4b3dac461a3afc90e0df95d73559fe960453331b
J-RAG/DTEC501-Python-Files
/Lab1-2-1q2.py
161
3.765625
4
# Lab 1-1-2 question 2 # By Julan Ray Avila Gutierrez, jra0108@arastudent.ac.nz first_name = input("Please enter your first name: ") print("Hi") print(first_name) print("Pleased to meet you.")
94e77c1f12be2d0e6c92d6bb8cefbc74caddc49a
ChaitanyaPuritipati/CSPP1
/CSPP1-Practice/cspp1-assignments/m10/how many_20186018/how_many.py
786
4.15625
4
''' Author: Puritipati Chaitanya Prasad Reddy Date: 9-8-2018 ''' #Exercise : how many def how_many(a_dict1): ''' #aDict: A dictionary, where all the values are lists. #returns: int, how many values are in the dictionary. ''' counter_values = 0 for i in a_dict1: counter_values = counter_...
5920ecffab483d5d8a99bcf4bdce9eff3cb72efe
AtindaKevin/BootCamp
/flow control/simapp.py
601
4.3125
4
"""Create a console application that asks that does the following -ask the user to set their pin -the user has three attempts to log in -if the user enters a wrong pin, he can reenter it and display the number of attempts left -if attempts are exhausted, display sim blocked """ set_pin = int(input("Set your pin:"...
aed693d0e3adfeebacb6d76c8b497828cb4c8b82
saurabhkulkarni77/Demonstration-of-vanishing-gradient-from-scratch
/SimpleNN_Comparison_of_sigmoid_Relu_Vanishing_gradient.py
2,114
3.6875
4
#For exploding gradient problem: #First introduced by mikolov. Its states that if value is above threshold value just cap it to 5 or something low. #Although being simplle it makes huge difference in RNNs #So why clipping doesnt solve vanishing gradient problem? because in vanishing gradient value gets smaller and ...
862b091109212d657725bdc8e29521b6371eea52
Lil-Bowie/python_feb_2017
/loop.py
382
3.6875
4
num = 1 for num in range(1,1000): print num #start my counter value = 5 for value in range(5,1000000) : if value % 5 == 0: print value #print the multiples of 5 def fSum(): i = 0 arr = [1,2,5,10,255,3] i = sum(arr) print i fSum() #take the sum of List. def fAvg(): i = 0 arr = ...
ba6f46765a407a20ee08e78d71e7eee646b5c9d5
Lee-W/leetcode
/problem/p_0094_binary_tree_inorder_traversal/solutions.py
737
3.921875
4
from typing import List, Optional # 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: """ Runtime: 39 ms (56.66%) Memory Usage: 13.8 MB (99. 3%) """ ...
d608414a105347004066fd7e6bf5426d3227ce79
Mikemraz/Data-Structure-and-Algorithms
/LeetCode/Search in Rotated Sorted Array.py
843
3.75
4
class Solution: """ @param A: an integer rotated sorted array @param target: an integer to be searched @return: an integer """ def search(self, A, target): # write your code here if len(A)==0: return -1 start = 0 end = len(A) - 1 while end-star...
0dac62fdc52bbb6c36ea63742ec3c4fa539b662e
ocdarragh/Computer-Science-for-Leaving-Certificate-Solutions
/Chapter 1/pg17.py
195
3.828125
4
# pi=3.14 # r=7 # answer=((4/3)*pi)*r**3 # print(answer) pi=3.14 r=7 answer=((4/3)*pi)*r**3 answer=round(answer,2) # 2 arguments (1st is the value,2nd is decimal places) print(answer)
67696159ca06382a84bb1140c061a7d6f85749e1
vasalf/mammoth-world
/W2/helpers/geom.py
4,581
3.546875
4
#!/usr/bin/python3 """This is a library that provides geometry classes and functions It is a part of mammoth-world project (https://github.com/vasalf/mammoth-world) """ from random import * from math import log """A place to import modules is up to that comment. """ __author__ = "vasalf" ...
59ad8ccdb912edae17904c8c1aee37990c8c7630
MUGABA/dataStructures-js
/python-d_and_algo/searchAlgo/linearSearch.py
184
3.78125
4
def linearSeach(array, item): if not array or not item: return for i in range(len(array)): if array[i] == item: return 1 return -1 print(linearSeach([1, 99, 45, 3, 7], 8))
547584e530bf58418ebdca1316d4f431d4d3c8ac
ClaudioChagas/Introducao-a-Ciencia-da-Computacao-com-Python
/corponumero.py
181
4
4
N = int(input("Digite um número: ")) soma=1 while (N > 0): resto= N % 2 N= (N - resto)/2 soma= soma + resto print("A soma dos números é: ", N)
916d4869d4849d3e3da1e311664aba88b31692c6
thephak/twitter_api
/app/twitter_api.py
3,425
3.671875
4
import requests import urllib.parse TWITTER_TOKEN = "" # REQUIRED DEFAULT_LIMIT = 30 TWITTER_API_BASE = "https://api.twitter.com/2" DEFAULT_TWEET_FIELDS = "author_id,created_at,entities,public_metrics" class TwitterAPI: def __init__( self ): self.headers = {"Authorization": "Bea...
962cf34cdb1d51118014544758c4746c21d11708
mbuon/Leetcode
/36. Valid Sudoku.py
1,346
3.78125
4
class Solution: def isValidSudoku(self, board): """ :type board: List[List[str]] :rtype: bool """ rows = {} cols = {} blocks = {} for i in range(0, len(board)): for j in range(0, len(board)): value = bo...
8b04a65e25666e033eebe5aafaa3f1507b9548d7
preston-scibek/Python
/ch7Exercise2.py
737
4.1875
4
__author__ = "Preston Scibek" # This Python file uses the following encoding: utf-8 #Encapsulate this loop in a function called square_root that takes a as a parameter, #chooses a reasonable value of x, and returns an estimate of the square root of a. def square_root(a): a = float(a) x = a + 1.0 y = (x + (a/...
00799642a9c66a8fbefc15da04008d5c615a00d3
sehgalsakshi/Content-Based-Recommendation-System
/preprocess.py
781
3.515625
4
import re from nltk.corpus import stopwords from nltk.tokenize import RegexpTokenizer #Utitlity functions for removing ASCII characters, converting lower case, removing stop words, html and punctuation from description def _removeNonAscii(s): return "".join(i for i in s if ord(i)<128) def make_lower_case(text): ...
50cc557f481c0756cfb92d9a3253707bebcc80e7
tnaswin/PythonPractice
/Aug20/argskwargs.py
1,252
3.984375
4
def some_args(arg_1, arg_2, arg_3): print("arg_1:", arg_1) print("arg_2:", arg_2) print("arg_3:", arg_3) my_list = [2, 3] some_args(1, *my_list) def some_kwargs(kwarg_1, kwarg_2, kwarg_3): print("kwarg_1:", kwarg_1) print("kwarg_2:", kwarg_2) print("kwarg_3:", kwarg_3) print kwargs = {"kwa...
55c9d26a3411ce12d84cb21bd769a7cd19aaee4f
priyanshuc4423/snakegame
/scoreboard.py
1,004
3.828125
4
import turtle as t class ScoreBoard(t.Turtle): def __init__(self): super().__init__() self.hideturtle() self.point = 0 with open("data.txt",mode="r") as file: self.high_point = int(file.read()) self.penup() self.goto(0,280) self.c...
6d794be32f19f61cce03a54fa7c3df93bbf9247c
Aish32/data-chronicles
/Preprocessing Structured Data/handling-imbalanced-classes-with-upsampling.py
1,084
3.890625
4
""" In upsampling, for every observation in the majority class, we randomly select an observation from the minority class with replacement. The end result is the same number of observations from the minority and majority classes. """ # load libraries import numpy as np from sklearn import datasets # load iris data ir...
ccbe6b67877e7fbce4206bd759ff12280eeca577
gogopavl/hadoop-streaming-tasks
/task3/mapper.py
754
3.953125
4
#!/usr/bin/env python2 # task3/mapper.py import sys from collections import defaultdict numberOfActors = 0 def map_function(line): """If a person's record contains "actor" or "actress" in their profession field returns 1 Parameters ---------- line : String type A line from the input stream ...
f50bd90ed7c20b46670b66568af84f7227fc80ba
liorch1/learning-python
/100.py
360
3.9375
4
#!/usr/bin/env python36 ##### #name: lior cohen #date: 11/6/18 #description: get a name and age from the user and tell #them the year they will turn 100 years old #### name = str(input("please entar your name: ")) age = int(input("please enter yout age: ")) year = (str((2018 - age) +100)) print("{}, will be 100 ye...
5fe193f603c26f995005cfb34f6b92f6a1fb29b2
micjo/snippets
/python/decorating_with_class_function.py
897
3.53125
4
#!/usr/bin/python class Foo: def timer(orig_func): import time def wrapper(): start_time = time.time() result = orig_func() end_time = time.time() delta_time = end_time - start_time print "{} ran for {} seconds".format(orig_func.__name__, ...
c588a13cf4a9bf2b84ddfaf209c9e5a9fe617995
daniel-reich/ubiquitous-fiesta
/gphnuvoHDANN2Fmca_0.py
116
3.578125
4
def odd_sort(lst): odds = iter(sorted(i for i in lst if i%2)) return [next(odds) if n%2 else n for n in lst]
977ea5a145764351e0a9d798077fab0176352bc8
snehahegde1999/sneha
/session-4.py
93
3.75
4
n=7 if n>3: print ("the condition is true") if n<5: print ("the condition is false")
c1918447e030eb87fcc464643e6a6c4a8c8c24a1
DDR7707/Final-450-with-Python
/Arrays/10.Sorting Negative , positive Numbers.py
1,451
4.1875
4
# Loumtors , horesrs algo def rearrange(arr, n ) : # Please refer partition() in # below post # https://www.geeksforgeeks.org / quick-sort / j = 0 j = 0 for i in range(0, n) : if (arr[i] < 0) : temp = arr[i] arr[i] = arr[j] arr[j]= temp j = j...
fe05844faf110d4bdea209c19263b64f3e3c524b
ArhiTegio/GB-Higher-Mathematics
/Lesson_3/Lesson3.py
5,216
3.609375
4
import matplotlib.pyplot as plt import numpy as np from pylab import * from mpl_toolkits.mplot3d import Axes3D import math # Урок 3 # Задание 1.2 # Напишите код на Python, реализующий расчет длины вектора, заданного его координатами. (в программе) # def LineLengthXY(x1, y1, x2, y2): # return math.sqrt((x1 - x2) ...
ad56824ffee92a92048ba8e22b75b9e55aa99d48
WAT36/procon_work
/procon_python/src/atcoder/arc/past/B_026.py
298
3.671875
4
import math n=int(input()) divisor=[] for i in range(1,int(math.sqrt(n)//1)+1): if(n%i==0): divisor.append(i) divisor.append(n//i) #print(divisor) sum_div=sum(set(divisor))-n if(sum_div<n): print("Deficient") elif(sum_div>n): print("Abundant") else: print("Perfect")
3cb618b5cc690c85d0e1ecd9e27f817e3791b3dd
gaoi311/python_learning
/day26/4.转义符.py
582
3.71875
4
# 正则表达式中的转义 : # '\(' 表示匹配小括号 # [()+*?/$.] 在字符组中一些特殊的字符会现出原形 # 所有的 \w \d \s(\n,\t, ) \W \D \S都表示它原本的意义 # [-]只有写在字符组的首位的时候表示普通的减号 # 写在其他位置的时候表示范围[1-9] # 如果就是想匹配减号 [1\-9] # python中的转义符 # 分析过程 '\n' # \转义符 赋予这个n一个特殊的意义 表示一个换行符 # print('\\n') # print\\n('C:\\next') # print(r'C:\next') # '\\\\n' '\\n' # 结论 # r'\\n...
07a6252f51ff3c179ef3dcee4cd0cd33cb8db813
nanduvankam/DSP-LAB
/Day1/leapif.py
190
3.953125
4
n=input("enter year="); if (n%4==0): print n,"is leap year" elif (n%100==0): print n,"is not a leap year" elif (n%400==0): print n,"is leap year" else: print n,"is not leap year"
665468a26c2a4d8a27757314ee3ec8ae722f29d5
jjsalomon/python-analytics
/numpy/numpy1 - Checks and Generation.py
2,237
4.25
4
# -*- coding: utf-8 -*- """ Created on Sat May 13 16:48:11 2017 This script is for learning about numpy library for Data Science Projects @author: azkei """ # importing NumPy module withing Python session import numpy as np # Using ndarray - the heart of the library a = np.array([1,2,3]) # Checking the newly creat...
a14d2a5d5ae5a39147973299e29bacc0f9d8d4fe
fbarneda/pythonProjects
/Blackjack Game/main.py
7,905
4.21875
4
""" This is the Blackjack game """ import random suits = ('Hearts', 'Diamonds', 'Spades', 'Clubs') ranks = ('Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Jack', 'Queen', 'King', 'Ace') values = {'Two': 2, 'Three': 3, 'Four': 4, 'Five': 5, 'Six': 6, 'Seven': 7, 'Eight': 8, 'Nine': 9, 'Ten': ...
e23bb744472afc4a44c1253dec7890a14dd70cdc
SeanPeer/Ex3_OOP
/tests/Test_G.py
1,449
3.921875
4
from DiGraph import DiGraph def build_graph(name="g"): print(f"Creating Graph {name}:") g = DiGraph() print("adding nodes [0,4] \n" "adding edges: [0,1], [0,2], [1,2], [2,3] ,[3,4]") for i in range(5): g.add_node(i) g.add_edge(0, 1, 1) g.add_edge(0, 2, 1) ...
f235024fa26be8992292125e8dda449454fe9393
XuShaoming/CompVision_ImageProc
/project1/code/task1.py
5,801
3.578125
4
import numpy as np import cv2 import math import mynumpy as mnp VERTICAL_SOBEL_3BY3 = np.array([[1,0,-1], [2,0,-2], [1,0,-1]]) HORIZONTAL_SOBEL_3BY3 = np.array([[1,2,1], [0,0,0], [-1,-2,-1]]) def texture_filtering(...
860e71bd4526e21b3dc7bc103f0a34c06cc52340
KAU93/hhhomework
/core/classes.py
1,284
4.09375
4
class Car: # Реализовать класс машины Car, у которого есть поля: марка и модель автомобиля # Поля должны задаваться через конструктор def __init__(self, mark, model): self.mark = mark self.model = model class Garage: # Написать класс гаража Garage, у которого есть поле списка машин ...
7635fbfbdf3f8639c31e6f1a6c6f6e0f33f71256
Alogenesis/Basic-Python-Udemy
/21ForLoop.py
1,478
4.09375
4
# For Loop are repeat every single thing in list[] blog_post = ['The 10 Coolest math functions in Python', 'How to make HTTP requests in Python', 'A tutorial about data type in Python'] for post in blog_post: print(post) sep = '-------------------------------' print(sep) # ...
a7206a21c98268ead84e302bec276d973d52b0ab
xLuis190/Python-School-work
/fib.py
246
3.625
4
def fib(n): previous, result = 0 , 1; x = 0 while(x < n -1): temp = result result = previous + result previous = temp x = x +1; return result; fib(8)
5e8a626435c65238b03db48eef3127cb100f2752
91xie/FYP2
/Archive/DateTimeCheck1.py
846
3.765625
4
# keep adding a random number to a list of numbers # if a timer constant is exceeded, process the data # see what you get from datetime import datetime, date, time, timedelta import time from random import randint deltamin = 1 now = datetime.now() now_plus_delta = now + timedelta(minutes = deltamin) print "now " +...
ae0f11eae522ca9dfaf5f59f79414d7e4cc5c249
davll/practical-algorithms
/LeetCode/1-two_sum.py
762
3.5625
4
def two_sum_v1(nums, target): lut = {} for i in range(len(nums)): if nums[i] in lut: return [lut[nums[i]], i] else: lut[target - nums[i]] = i def two_sum_v2(nums, target): n = len(nums) index = list(range(n)) index.sort(key = lambda i: nums[i]) l, r = 0, ...
ecf247561a725796ad3aec445ec1398e16e521be
yaolinxia/algorithm
/a常用函数python汇总.py
1,018
3.90625
4
# 给定一个字符串,转化为列表 """ 2,3,4,1 ['2', '3', '4', '1'] [2, 3, 4, 1] """ def str2list(s="[2,3,4,1]"): s_cut = s[1:-1] print(s_cut) s_l = s_cut.strip().split(',') print(s_l) l = [] for c in s_l: l.append(int(c)) print(l) # 字典里面基于字进行排序 def sorted_dict(d={"a":3, "f":5, "b":6}): s_d = sort...
d92122d3b8c292c1fbd66dc23cee18dec4afcf70
anshu0157/AlgorithmAndDataStructure
/AlgorithmAndDatastructure_Python/DataStructure/1_LinkedList.py
1,613
3.828125
4
class Node : def __init__(self, data, next=None): self.data = data self.next = next def init(): global node1 node1 = Node(1) node2 = Node(2) node3 = Node(3) node4 = Node(4) node1.next = node2 node2.next = node3 node3.next = node4 def delete(del_data): global ...
31edd7da1a77ccacf1fc06a43b15207be088dc01
chuanyuj/product
/product.py
495
3.8125
4
products = [] # 有一個叫做 products 的空清單 while True: # 進入迴圈 name = input('請輸入商品名稱:') # 請使用者輸入商品名稱,創建為 name if name == 'q': # 如果使用者輸入 q break # 離開程式 price = input('請輸入商品價格:') # 請使用者輸入商品價格,創建為 price products.append([name, price]) # 把 p 這個清單裝到 products 這個清單裡 print(products) products[0][0] # products 清單的第 0 格中的第 0 格
792be0535b784a2eadfbaf2f150c5d0b5d9e59d5
TungTNg/itc110_python
/Assignment/pizzaCalculator.py
902
4.5625
5
# pizzaCalculator.py # A program to calculate the cost per square inch of a circular # by Tung Nguyen import math def main(): # declare program function: print("This program calculates the cost per square inch of a pizza.") print() # prompt user to input the pizza diameter in inches: diameter...
940d1334f74438e609f0e25255fbe6c722c506f5
Mamonter/GB_les_Petryaeva
/bas/less4/ex5.py
794
4.15625
4
#Реализовать формирование списка, используя функцию range() и возможности генератора. #В список должны войти четные числа от 100 до 1000 (включая границы). #Необходимо получить результат вычисления произведения всех элементов списка. #Подсказка: использовать функцию reduce(). from functools import reduce def my_func(e...
c641a2f9241152be9c8f1eb96892772300f34827
swathythadukkassery/60DaysOfCode
/Backtracking/knight.py
981
3.796875
4
def possible(board,rownew,colnew,n): if(rownew>=0 and rownew<n) and(colnew>=0 and colnew<n) and board[rownew][colnew]==0: return True return False def find(board,n,move,row,col): rowInc=[2,1,-1,-2,-2,-1,1,2] colInc=[1,2,2,1,-1,-2,-2,-1] if move==(n**2): for i in range(n): ...
7173544be821a1ec4e5df9c9907debf09ee4e2a5
tonabarrera/problemas
/fibo.py
189
3.5625
4
def fib(n): a,b = 1,1 contador = '' for i in range(n-1): a,b = b,a+b if a > n: break contador = contador + '%s ' % a return contador k = int(raw_input()) print fib(k)
e542e3ae5324e91c5420cfa66bb7dbd878fd5009
apoorvaagrawal86/PythonLetsKodeIt
/PythonLetsKodeIt/Basic Syntax/numbers.py
192
3.875
4
int_num = 10 float_num = 20.0 print(int_num) print(float_num) a = 10 b = 20 print("*********") add = a+b print(add) sub = b - a print(sub) mul = a*b print(mul) div = b/a print(div)
5b42d22a4e26e93ef4bcf9e6d2bd3e14df50e74d
cjstaples/morsels
/snippets/all_unique/unique.py
153
3.5625
4
def is_all_unique(lst): return len(lst) == len(set(lst)) x = [1,1,2,2,3,2,3,4,5,6] y = [1,2,3,4,5] is_all_unique(x) # False is_all_unique(y) # True
3a625245a43638e3fba0179872f91907385d8958
davidcoxch/PierianPython
/6_Methods_and_Functions/paper_doll.py
373
4.1875
4
""" PAPER DOLL: Given a string, return a string where for every character in the original there are three characters¶ paper_doll('Hello') --> 'HHHeeellllllooo' paper_doll('Mississippi') --> 'MMMiiissssssiiippppppiii' """ def paper_doll(text): st = '' for x in text: st = st + x*3 return st print(p...
cb28c7cbabfd134ac2eb312cd65252394de02e51
TetianaHrunyk/DailyCodingProblems
/challenge7.py
470
4
4
def is_char(code): return 0 if code > 26 or code < 1 else 1 def decode(code): code_str = str(code) if len(code_str) == 1: count = 1 elif len(code_str) == 2: count = 1 + is_char(code) else: count = decode(int(code_str[1:])) if is_char(int(code_str[:2])): c...
dd26253d30182bf69a27068ac02f6c4dd48c2043
qmnguyenw/python_py4e
/geeksforgeeks/algorithm/hard_algo/5_19.py
6,844
3.71875
4
Program to generate all possible valid IP addresses from given string | Set 2 Given a string containing only digits, restore it by returning all possible valid IP address combinations. A valid IP address must be in the form of **A.B.C.D** , where **A** , **B** , **C** and **D** are numbers from **0 – 255**....
444e1da5d03416dafbaf831c109362c761b3afb3
tobiasjpalacios/TP2-AED
/Tiempo.py
573
3.53125
4
import time #import random inicio = time.time() ahora = inicio fin = inicio + 240 #turno = (fin - inicio) #print(turno) while (ahora < fin): actual = int(ahora - inicio) if actual > 180: hora = 4 #print("Hora 4 Minuto", actual) elif actual > 120: hora = 3 ...
6fc50fbcdc621b69437752cbdff1150d42ebf558
LucasGVallejos/Master-en-MachineLearning-y-RedesNeuronales
/01-PrincipiosYFundamentosDePython/09-Listas.py
695
3.75
4
sabores = ["chocolate","crema americana","vainilla", True, 20] sabores2 = ["chocolate amargo","CREMA del CIELO", False, -20] print("\nla lista contiene: ",sabores) print("\nen la posicion 4 esta: ", sabores[4]) elementoEliminado = sabores.pop(4) print("\nel elemento que se elimino es: ",elementoEliminado) print("la ...
746f99ba639120f73fd8457a7a418eb8ac8e6133
gsrr/leetcode
/leetcode/823. Binary Trees With Factors.py
4,203
3.78125
4
''' Method1 這個問題直覺想法就是bottom-up的暴力法方式. 一個兩個for loop的方式, 但會遇到一個問題, 那就是新增加的值要如何再與前面的值相乘? (append? 那會造成list亂掉, 所以只好新增一個新的list來儲存) 然後重跑迴圈, 繼續將這個list互乘, 直到list不會再增加為止. Method2 感覺只是對array裡面的值一直在互乘而已, 所以用dictionary來存次數. Method3 感覺並不需要新的dp, 也就是可以拿掉外面迴圈. (但array需要先sort, 這樣的話, 前面乘就代表該值已經固定了) ex: 若6之前的人都已經乘完, 那代表6最多就是目前這個次數. 所以...
f679bda14e06f181042000c8406ffc076bf2040a
aalsher/CodingProgression
/Python/ScoresAndGrades.py
441
3.734375
4
import random random_num = random.randint(60,100) def ScoresAndGrades(random_num): if random_num >= 60 and random_num <= 69: grade = "D" if random_num >= 70 and random_num <= 79: grade = "C" if random_num >= 80 and random_num <= 89: grade = "B" if random_num >= 90 and random_num ...
edd453776f5ce410e2d3ccf8468347acf5d3da09
arun5061/Python
/Revision/input_for.py
311
3.671875
4
list=[] x=int(input('Enter no of students:')) for i in range(x): list.append(input('Enter student name{}:'.format(i))) print(list) d=dict() s=0 for j in list: val=input('Enter value{}:'.format(s)) s+=1 d[j]=val print('d:',d) for k,v in d.items(): print('Key:',k,'\t','value:',v)
2a9ac6b28f0e209758a71741f4601682856db8f8
morawer/practicaNate1
/ejercicio1.py
365
3.828125
4
frase_usuario = input("Introduce un texto: ") simbolos = [" ", ".", ","] espacio = 0 punto = 0 coma = 0 for caracter in frase_usuario: if caracter is " ": espacio += 1 elif caracter is ".": punto += 1 elif caracter is ",": coma += 1 print("El texto contiene {} espacios, {} punto...
b84616ed8b95f93e5cb7aff57c22d1ed6d86570f
marshallgrimmett/CS-undergrad-projects
/principlesProg2/topic6/dynamicStrong.py
651
3.671875
4
# Python is dynamic and strong typed # Strong typing in Python print "The answer is " + 7 # Runtime error # Problems with dynamic myVariable = 7 myVaraible = myVariable + 10 print myVariable # When run prints: 7 # This is because we created another variable 'myVaraible' ...
300bf4aa09cb9e9b48bcbf088a3d6176fab41cf8
zhoucong2/python-
/exercises/week_exe.py
184
3.640625
4
y=["星期一","星期二","星期三","星期四","星期五","星期六","星期天"] s=int(input("请输入数字")) if s in range(1,8): print(y[s-1]) else: print("无效")
7e3bd6e77106881622b9a89c6dcd0f54b55cee1a
alex-moffat/Python-Projects
/Tkinter Phonebook/SQL_functions.py
3,518
3.625
4
# PYTHON: 3.8.2 # AUTHOR: Alex Moffat # PURPOSE: General use SQLite3 functions """ TAGS: SQL, sqlite3.version, error handling, connect, cursor, execute, CREATE, INSERT, SELECT slice, upper, fetchall, isinstance, ValueError as """ # ============================================================================ #===== ...
cfe32eb727b56a5eb301261f3cc3d7a0a0b25ea6
ashi1994/PythonPractice
/PythonOops/VariablePython.py
443
3.84375
4
''' Created on May 19, 2018 @author: aranjan ''' ''' In Python when you want to use the same variable for rest of your program or module you declare it a global variable, while if you want to use the variable in a specific function or method, you use a local variable. ''' class VarTest: a=101 pri...
d201f4f9ac0f383d07451a860327a06e50ebc778
mytwenty19/weight_tracker
/date_utils.py
3,146
3.671875
4
from datetime import date import datetime import dateutil.parser import csv import pandas as pd import calendar import matplotlib.pyplot as plt # Define a function that converts a date to a string def date2str(date_obj): return date_obj.isoformat() # Define a function that converts a date string to a date object ...
5b8c03f05910c635e28c9084ee5ebfaa417d44cd
mwesigwapita/AIMB
/server/helpers/password_hasher.py
467
3.546875
4
# Import libraries from Crypto.Hash import SHA256 # Class that hashes the password class PasswordHasher: def hash_password(self, password: str, salt: str = None) -> str: # Create salted password if (salt): salted_password = str.encode(password + salt) else: salted_...
23d9d18d27f1a18d08beee5dc348801ad42192c3
Apologise/Python_sublime
/第八章/8-9魔术师.py
253
3.640625
4
magicians = ['杨浩','刘谦','我','我'] def make_great(lists): for i in range(len(lists)): lists[i] = "The Great" + lists[i] def show_magicians(): for i in range(len(magicians)): print(magicians[i]) make_great(magicians[:]) show_magicians()
a649cf0242341e4828c337092c5c6e07ac63cea6
Slawak1/pands-problem-set
/plotfunction.py
847
3.703125
4
# Problem No 10 # Problem No. 9 # Slawomir Sowa # Date: 11.02.2019 # Write a program that displays a plot of the functions x, x2 and 2x in the range [0, 4]. import matplotlib.pyplot as plt import numpy as np x = np.arange(0.0,4.0,0.2) # NumPy arange() function returns evenly spaced numeric value with step 0.2 ...
8c348ff9bd810a51e2271a5b402c23edbeada4ff
fitrepoz/810A
/810A/test.py
363
3.515625
4
import re def main(): filename = "hw5_text.txt" output = '' with open(filename) as f: for line in f: if line.rstrip().endswith('\\'): next_line = next(f) line = line.rstrip()[:-1] + next_line output += lin...
ed4a89966ff99e2a41125bdee54bf3f0d284794f
All4nXp/Tarea_06
/Tarea 6 final.py
1,519
3.8125
4
#encoding: UTF-8 #Autor: Allan Sánchez Iparrazar def cazeriaInsectos(): dias = 0 insectosCazados = 0 faltantes = 30 while faltantes <= 30 : insectos = int(input("Numero de Insectos cazados hoy")) insectosCazados = insectosCazados + insectos dias = dias + 1 faltantes = faltantes - insectos if fa...
5f8e6e2b03f9e0d7cafe6a621e8e53d38223d647
anlutfi/MScCode
/Space.py
12,574
3.5625
4
##@package Space # File containing Cell, Grid and GameSpace class definitions from GameObject import GameObject X = 0 Y = 1 Z = 2 D3 = 3 D2 = 2 cellassert = "Cell." class Cell: """a Grid object's cell""" def __init__(self, xb, xe, yb, ye): """Cell.__init__(self, xb, xe, yb, ye) Initial...
59809770870b0cd2b7f77a209987aa9d94900feb
DavidCichy/w05_si
/exercises.py
3,244
4.28125
4
import poker_hand_logic def most_frequent_number_in_array(array): ''' Check what is the most frequent number in an array. >>> most_frequent_number_in_array([3, 3, 3, 2, 2, 2, 4, 4]) 3 >>> most_frequent_number_in_array([3, 3, 3, 5, 5, 5, 7, 7, 0, 2, 2, 2]) 5 ''' array.sort() dict_...
8c6832edb946dd22e78330a981126b275a448f0b
TianyuYang/ZOLA
/Math 480Hw5.py
1,279
3.84375
4
Homework 5 Part 1 # this is a method that can calculate large number mod faster def modular_exponent(base, exponent, mod): exponent = bin(exponent)[2:][::-1] x = 1 power = base % mod for i in range(0, len(exponent)): if exponent[i] == '1': x = (x * power) % mod power = (powe...
4aed3b4e8c69d552384a1c2d4b68b816ad31249d
Ge0dude/PythonCookbook3
/Chapter1/1.2UnpackingArbitraryLength.py
1,513
3.8125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Apr 18 08:21:34 2017 @author: brendontucker this section seems really useful for data processing, especially for really ugle data """ '''can use Python star expressions (*expression) to accomplish this goal''' testList = list(range(24)) def drop_f...
bd9dbf29b7052ee159755edd39610dc4cc137211
Programmable-school/Python-Training
/lesson/lessonSet/main.py
774
4.03125
4
""" 集合型 """ # 順序なし、重複を許されないデータ型 values1 = set([0, 1, 2, 3, 4]) values2 = {0, 1, 2, 3, 4} print(values1) # {0, 1, 2, 3, 4} print(values2) # {0, 1, 2, 3, 4} values3 = {0, 0, 1, 1, 2, 3, 4, 0, 5, 6} print(values3) # {0, 1, 2, 3, 4, 5, 6} # 要素の確認 print(4 in values1) # True print(10 in values1) # False # 値を追加 valu...
d8156bfc7612ccb0e7ab19598c3d07bd73dd7f2b
CJLucido/Excel
/addLineToExcel.py
1,624
3.71875
4
#!!!!!!This will overwrite your excel file!!!!!!!!!!!! # excel file must have an empty first column import pandas as pd import os from openpyxl import load_workbook file=input('File Path: ') pth=os.path.dirname(file) df=pd.read_excel(file) file_cols = list(df)#Alternate to # file_cols = df.columns...
f513d16416a4e571044a044fe03d141e9ff85fd1
mischelay2001/WTCSC121
/CSC121FinalProject_WakeMartUpgrade/scan_items.py
5,636
4.375
4
__author__ = 'Michele Johnson' """ 3. scan_prices Write a scan_prices function for the customer to order items. First call the read_price_list function to read the price list from a text file. Display all items in the price dictionary. Then use a loop for the customer to enter product code of each item ...
a43bb19ea5e718524d772fe5c72d50d7728eb071
elinfalla/CMEEGroupWork
/Ioan/Code/LV3_2.py
2,343
3.953125
4
#!/usr/bin/env python3 """Defining and plotting a discrete-time version of the Lotka-Volterra model of population dynamics for inputted parameters.""" ### The Lotka-Volterra model ## Imports import scipy as sc import numpy as np import scipy.integrate as integrate import matplotlib.pylab as p import sys # Define th...
45e19880d1efb152f4a3f563ebc15d76d0dee5c7
deimelperez/HackerRank
/Problem Solving/Sock Merchant.py
431
3.640625
4
import math import os import random import re import sys # Complete the sockMerchant function below. def sockMerchant(ar): colors = list(set(ar)) count = 0 for i in range(0, len(colors)): count += ar.count(colors[i]) // 2 print(ar.count(colors[i]) // 2) return count if __name__ == '...
fe1bcd5c512785eac2412e63d47ab84a728d2820
shishujuan/rsa-algrithm
/pow.py
1,047
3.984375
4
#!/usr/bin/env python # -*- coding: utf-8 -*- from time import clock import time def pow_simple(a, e, n): """ 朴素法模幂运算:a^e % n """ ret = 1 for _ in xrange(e): ret *= a return ret % n def pow_simple_optimized(a, e, n): """ 朴素法模幂运算优化:基于 a ≡ c(mod n) => ab ≡ bc(mod n),即 ab mod n...
586a16baab0ffcf457ac8198e1a116001d281a77
das-jishu/data-structures-basics-leetcode
/Leetcode/medium/sum-root-to-leaf-numbers.py
1,522
4.1875
4
""" # SUM ROOT TO LEAF NUMBERS Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number. An example is the root-to-leaf path 1->2->3 which represents the number 123. Find the total sum of all root-to-leaf numbers. Note: A leaf is a node with no children. Example: Input...
bdedfe502202378b017639280cece219ee539e4f
JonathanVose/CMPT-120L-910-20F
/Assignments/Assignment 9/App_Calculator.py
435
4
4
import Calculator x = int(input("Please enter a number: ")) y = int(input("Please enter another number: ")) functions = Calculator.Calculator() print(functions.addition(x,y)) print(functions.subtraction(x,y)) print(functions.division(x,y)) print(functions.multiplication(x,y)) print(functions.exponent(x,y)) prin...