blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
3.06M
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
3.06M
37ae656e2c6b97bc2bf5a22635781f3dbf7a14eb
TommasU/slash
/src/modules/scraper.py
11,638
3.671875
4
""" Copyright (C) 2021 SE Slash - All Rights Reserved You may use, distribute and modify this code under the terms of the MIT license. You should have received a copy of the MIT license with this file. If not, please write to: secheaper@gmail.com """ """ The scraper module holds functions that actually scrape the e-co...
34e7a519195586c1d7da3f3778a7c9b3bd67aa72
USTBlzg10/-offer
/src/main/Python/nowcoder/S64_MaxInWindows.py
654
3.890625
4
class MaxInWindows: def maxInWindows(self, num, size): queue, res, i = [], [], 0 while size > 0 and i < len(num): if len(queue) > 0 and i-size+1 > queue[0]: #若最大值queue[0]位置过期 则弹出 queue.pop(0) while len(queue) > 0 and num[queue[-1]] < num[i]: #每次弹出所有比num[i]小的数字...
6bf1a7a45ed0de19a26f37ce8fa0ae0cf1b0d584
USTBlzg10/-offer
/src/main/Python/nowcoder/S7_Fibonacci.py
237
3.921875
4
class Fibonacci: def fibonacci(self, n): res = [0, 1] while len(res) <= n: res.append(res[-1] + res[-2]) return res[n] if __name__ == '__main__': test = Fibonacci() print(test.fibonacci(3))
35478e13d532b176a7801e0243e3c63a6d8a598a
USTBlzg10/-offer
/target/classes/nowcoder/S37_GetNumberOfK.py
1,209
3.5
4
class GetNumberOfK: def GetNumberOfK(self, array, k): first = self.getFirstK(array, k, 0, len(array)-1) last = self.getLastK(array, k, 0, len(array)-1) return last - first+1 #递归找第一个k def getFirstK(self, array, k, start, end): if start>end: return -1; mid =...
ba5a21d92b939e66430fb55dc37c95d5df15f4ae
USTBlzg10/-offer
/src/main/Python/nowcoder/S38_TreeDepth.py
415
3.59375
4
import PrintTreeLayer class TreeDepth: def TreeDepth(self, root): ld = self.TreeDepth(root.left) rd = self.TreeDepth(root.right) if ld > rd: return ld +1 else: return rd +1 if __name__ == '__main__': test = TreeDepth() p = PrintTreeLayer.PrintTreeLayer() arra...
00edefb2099e7fa02a234e8ab8b1115ba4808d1a
USTBlzg10/-offer
/target/classes/nowcoder/S56_DeleteDuplication.py
1,025
3.75
4
import Array2List class ListNode: def __init__(self, x): self.val = x self.next = None class DeleteDuplicatioin: def deleteDuplication(self, pHead): # write code here if pHead == None or pHead.next == None: return pHead new_head = ListNode(-1) new_head...
fb607a73cd1e7aed4fcab22e550c7199c1b5a54c
USTBlzg10/-offer
/src/main/Python/nowcoder/S28_MoreThanHalfNum.py
774
3.609375
4
class MoreThanHalfNum: def moreThanHalfNum(self, array): if len(array) == 0: return 0 result = array[0] count = 1 for i in range(len(array)): if count == 0: result = array[i] count = 1 else: if array[...
63a26910331f260b978048f14f56990fdd15653b
USTBlzg10/-offer
/src/main/Python/nowcoder/S62_KthNode.py
639
3.671875
4
import PrintTreeLayer class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class KthNode: def kthNode(self, root, k): self.res = [] self.dfs(root) return self.res[k-1] if 0 < k <= len(self.res) else None def dfs(self, root): ...
c00774661e59ba9008bbf5d456c493fb3c395a12
USTBlzg10/-offer
/target/classes/nowcoder/S59_ZPrint.py
925
3.703125
4
import PrintTreeLayer class ZPrint: def Print(self, pRoot): if not pRoot: return [] nodeStack = [pRoot] result = [] while nodeStack: res = [] nextStack = [] for i in nodeStack: res.append(i.val) if i.left...
611c5db0bf4ee59131fc59b83842c7dc433fb444
mekhrimary/python3
/factorial.py
1,417
4.25
4
# Вычисление факториала числа 100 различными методами # Метод 1: рекурсия def recursive_factorial(n): if n == 0: return 1 else: return n * recursive_factorial(n - 1) print(f'Метод 1 (рекурсия) для числа 100: {recursive_factorial(100)}') # Метод 2: итерация + рекурсия def iterative_and_recur...
bfba95ff46cc7730d8736d352b900c4dd89d00c4
mekhrimary/python3
/countdown.py
1,121
4.15625
4
# Recursive function as a countdown def main(): """Run main function.""" number = get_number() while number == 0: number = get_number() print('\nStart:') countdown(number) def get_number() -> int: """Input and check a number from 1 to 100.""" try: num = int(input...
fadc2a22e5db5f8b2887067699ee05c721328e7c
mekhrimary/python3
/lettersstatsemma.py
1,818
4.125
4
# Use string.punctuation for other symbols (!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~) import string def main() -> None: '''Run the main function-driver.''' print('This program analyzes the use of letters in a passage') print('from "Emma" by Jane Austen:\n') print('Emma Woodhouse, handsome, clever, and r...
cdd7cb1b03ee7c58f8e9c29af32f686cb75161da
mekhrimary/python3
/guessnumber.py
496
3.8125
4
import random number = random.randint(1,20) guess = int(input("Загадано число от 1 до 20. Какое? >>> ")) while guess != number: if guess < number: print("\n:( Ваше число слишко маленькое...\n") else: print("\n:( Ваше число слишком большое...\n") guess = int(input("Попытайтесь угадать ещё раз...
aea112fb26c1ba6d6753f70035ccc5a1b9dbccc1
prudhvi1995srinivas/lab-6
/task2.py
388
3.6875
4
import math class rectangle(): x=0 y=0 p1=rectangle() width=100 height=200 def find_center(p1,width,height): center=((p1.x+height/2),(p1.y+width/2)) return center print(find_center(p1,width,height)) class point(): x=1 y=2 p1=point() dx=4 dy=8 def move_rectangle(p1,dx,dy): move=((p...
175d75d23f451cb2d09f21798ad09c96d863009c
leonlinsx/ABP-code
/Python-projects/smart_calculator_wo_eval.py
11,636
3.90625
4
''' jetbrains academy calculator calculator class that can take inputs and do math with basic operators + - * / (int division) and () are supported can also store variables by setting with = sign does not use eval(), works with strings and regex Other references https://levelup.gitconnected.com/how-to-write-...
6ee057f17a4b7b82142808545a47ae6b5d0cc2bf
leonlinsx/ABP-code
/Python-projects/crackle_pop.py
682
4.3125
4
''' recurse application Write a program that prints out the numbers 1 to 100 (inclusive). If the number is divisible by 3, print Crackle instead of the number. If it's divisible by 5, print Pop. If it's divisible by both 3 and 5, print CracklePop. You can use any language. ''' class CracklePop: def __in...
817a4229ed79058b6661f8b5e9a800c9b40c9d3b
leonlinsx/ABP-code
/Rice Fundamentals of Computing specialisation/Principles of Computing/Part 1/Week 4 Yahtzee strategy.py
3,630
3.703125
4
""" Planner for Yahtzee Simplifications: only allow discard and roll, only score against upper level http://www.codeskulptor.org/#user47_1qZHxsY3PG_2.py """ # Used to increase the timeout, if necessary import codeskulptor codeskulptor.set_timeout(20) def gen_all_sequences(outcomes, length): """ I...
52a286f663ed2b7a704bd80414b5b6c64516f6c2
moliming0905/Python
/Spider/getBaiduTiebaInfo.py
1,582
3.703125
4
#!/usr/bin/env python #-*- coding:utf-8 -*- import urllib import urllib2 def loadPage(url,filename): """ 作用:根据URL发送请求,获取服务器响应文件 url:需要爬取的url地址 filename:处理的文件名 """ print "Download "+filename headers = { "User-Agent":"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/5...
7ac7725e1646bee203a765d7f7a47e57c2d47064
jobartucz/Intro-to-Machine-Learning-with-Python
/174_building_first_model_k_nearest_neighbors.py
1,013
3.65625
4
import numpy as np import matplotlib.pyplot as plt import pandas as pd import mglearn from IPython.display import display from sklearn.datasets import load_iris from sklearn.model_selection import train_test_split iris_dataset = load_iris() from sklearn.neighbors import KNeighborsClassifier X_train, X_test, y_trai...
3ed94fab5e5f0a813ab6d1e63f1bec718a58e5fb
bgmichelsen/FacialDist_OpenCV
/main.py
11,135
3.578125
4
""" This program demonstrates how to use a single camera for depth sensing. It uses the triangle similarity method to calculate the distance between a detected face and the camera. To use the program, the focal length of the camera must first be calibrated. Then, the facial detection algorithm can be run...
51eafb313e57712744f2b43619a40b9e257e9794
Akanksha-Pandey/Data-Science-projects
/Combining Data With Pandas-344.py
1,264
3.59375
4
## 1. Introduction ## import pandas as pd happiness2015 = pd.read_csv("World_Happiness_2015.csv") happiness2016 = pd.read_csv("World_Happiness_2016.csv") happiness2017 = pd.read_csv("World_Happiness_2017.csv") happiness2015['Year'] = 2015 happiness2016['Year'] = 2016 happiness2017['Year'] = 2017 ## 2. Combining Data...
93125aab8b77d25b1ff27de299ca1dcce619e239
oscarfresnou/cse
/notes/Oscar Alejandro - Lucky's 7.py
623
3.765625
4
import random roll_again = "yes" money = 15 rounds = 0 while money > 0: print("rolling dice...") Dice_1 = random.randint(1, 6) Dice_2 = random.randint(1, 6) print("the values are...") print(Dice_1) print(Dice_2) rounds += 1 money -= 1 myrole = (Dice_1 + Dice_2) if myrole == 7: ...
6defe35d86efb9a61b9ab487863f29d6b3e3330f
oscarfresnou/cse
/notes/Oscar Alejandro - Mad Lib.py
772
3.84375
4
verb1 = input("Type in a verb': ") adjective = input("Type in a adjective': ") noun1 = input("Type in this noun': ") noun2 = input("Type in this noun': ") noun3 = input("Type in this noun': ") noun4 = input("Type in this noun': ") verb2 = input("Type in a verb': ") verb3 = input("Type in a verb': ") adjective2 = input(...
3cf416744427006eb159f42c7600897d9dd54cf9
AliceYang421/CS231_CNN
/assignment2/cs231n/cnn_code.py
7,518
3.75
4
def conv_forward_naive(x, w, b, conv_param): """ A naive implementation of the forward pass for a convolutional layer. The input consists of N data points, each with C channels, height H and width W. We convolve each input with F different filters, where each filter spans all C channels and has he...
e97d7d3353d9f95614575e9fc56a6013c3264878
fernandafrosa/turtle-crossing-game
/car_manager.py
820
3.96875
4
from turtle import Turtle from random import choice, randint COLORS = ["red", "orange", "yellow", "green", "blue", "purple"] STARTING_MOVE_DISTANCE = 5 MOVE_INCREMENT = 10 class CarManager: def __init__(self): self.cars = [] self.speed = STARTING_MOVE_DISTANCE def create_car(self): ...
c0dc591283a0052d83cdfa2c30775a14f9e73283
robinlin99/Restricted-Boltzmann-Machine
/RBM for MNIST/One-Hot-Encoding/RBMtesting10clampnew.py
2,428
3.53125
4
import numpy as np import math import time import tensorflow as tf import para #numpy.set_printoptions(threshold=sys.maxint) from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets('MNIST_data', one_hot=True) import matplotlib.pyplot as plt #yeah this is actually a shit method ...
6303fbb3deefadd0f234896bee39d2518d72fef0
Folzi99/Practice
/bmi_calculator.py
365
4.0625
4
name = input("Name: ") height_m = input("Height: ") h_1_m = float(height_m) weight_kg = input("Weight: ") w_1_kg = float(weight_kg) bmi = (w_1_kg / (h_1_m ** 2)) print("BMI: ") print(bmi) if bmi > 18.5 and bmi < 25: print(name, "is normal weight") else: if bmi > 25: print(name, "is overweight") ...
8546decb47470ba3f2624f63138fdbead425f145
zzid/Cloud_MSA_Multicampus_Education_First_phase_python
/Practice/Day_001/fahrenhet.py
168
3.703125
4
n = float(input('변환하고 싶은 섭씨 온도를 입력해 주세요\n')) print('섭씨 온도 : ',n) print('화씨 온도 : {:.2f}'.format((float(9/5) * n) + 32))
b5f72eb22efa2d2c13440e033d6fb32fef9d3c48
zzid/Cloud_MSA_Multicampus_Education_First_phase_python
/Practice/Day_004/class_ex_(cont).py
1,143
4.09375
4
''' class member >> default : public self.__someting : private @property # decorator (getter) def year(): return self.__year @year.setter # decorator (setter) def year(year): self.__year = year ''' class Product(object): def __init__(self, name): self.__name = name # private variable def __st...
9254ee5f16d1d6d4e5eb3fef56e5e00a096152f7
zzid/Cloud_MSA_Multicampus_Education_First_phase_python
/Practice/Day_002/gugudan.py
350
3.71875
4
while 1: print('구구단 몇 단을 계산할까요?(1~9) || 0을 입력하면 종료 됩니다.') n = int(input()) if n <0 or n>=10: print('1~9 범위의 숫자만 입력하세요') continue elif n == 0: print('Bye!') break for i in range(1,10): print('{} X {} = {}'.format(n, i, n*i))
cb16af0d20c2558dd5eb551832c09aa177c69194
eunyoungson/basic-2020
/조코딩/클래스.py
1,341
4
4
#클래스 : 반복되는 변수와 메소드(함수)를 미리 정해놓은 틀(설계도) class FourCal: pass a = FourCal() print(a) class Calculator: def __init__(self): self.result = 0 def add(self,num): self.result += num return self.result cal1 =Calculator() cal2 =Calculator() print(cal1.add(3)) print(cal2.add(4)) class FiveC...
20237b1027341cc43b61da5ce30b997a94f41b26
KelseyCortez/4.1.20-am
/Exercise3.py
353
3.9375
4
# madlib using input function name = '' color = '' result = '' start_lib = ('Please fill in the blanks below: ') my_lib = "___(name)___'s favorite color is ___(color)___" print(start_lib) print(my_lib) name = input('What is your name? ') color = input('What is your favorite color? ') result = f"{name}'s favorite ...
074efdefccf77f39fc91ea329ab3f164d94523a5
Joan61/alx-higher_level_programming
/0x04-python-more_data_structures/7-update_dictionary.py
424
4.0625
4
#!/usr/bin/python3 def update_dictionary(a_dictionary, key, value): ''' first check if key doesn't exist so you add, swapping the order of codeblocks would result in RunTimeError, Dictionary changed size during iteration. ''' if key not in a_dictionary: a_dictionary[key] = value ...
31883da9718081598720fa96f7703dc416fb09b0
Joan61/alx-higher_level_programming
/0x0B-python-input_output/5-save_to_json_file.py
427
3.875
4
#!/usr/bin/python3 """ module: 5-save_to_json_file contains save_to_json_file() function that writes an Object to a text file using a JSON representation: """ import json def save_to_json_file(my_obj, filename): """ Args: my_obj - object to serialize and store in file filename - name of file to s...
f8a938299d94e2feac6aa76011b898f3f05c5cf3
jmacs0606/codedump
/Python/PythonGen/name.py
109
4.125
4
name = '0' while name.isalpha() != True: name = input("Please enter a name: ") print("Your name is " + name)
32b936651827ad187b2157eedcc69bd2b3747082
jmacs0606/codedump
/Python/nn.py
1,239
3.703125
4
import math import numpy as np def sigmoid(x): return 1 / (1 + np.exp(-x)) def sigmoid_derivative(x): return x+(1-x) class neuron(): def __init__(self,inputWeight,outputWeight,nInput,nOutput): self.inputWeight = inputWeight self.outputWeight = outputWeight self.input=nInput ...
9726c8e61f6d02bd046b6145979bdbaff878608c
jdgreen/Project-Euler
/solutions/src/python/euler018.py
919
3.796875
4
#dynamic program to find highest path through a tree data file def best_path1(file): i = 0 #read in data points for line in reversed(list(open(file))): row = map(int,line.rstrip().split(" ")) #print row m = 0 for element in range(len(row)): if i == 0: i = 1 break elif sum[element] > sum[eleme...
842393b6e0f6a1711b5f81a3445de608a4881dd5
jdgreen/Project-Euler
/solutions/src/python/euler012.py
254
3.78125
4
#takes ages but does work - will try to find quicker method! def tri(divisors): tri = 0 div = 1 m = 0 while m <= divisors: m = 0 tri += div div += 1 for factor in range(1,tri+1): if tri % factor == 0: m += 1 return tri print tri(5)
4050f7d478d4f0723c3c53c63decaf15768f18e9
michaelstecklein/beagleboneblack
/securitycamera/PyDrive_tests/quickstart.py
942
3.515625
4
from pydrive.auth import GoogleAuth from pydrive.drive import GoogleDrive credentialsFile = "credentials.txt" print "Getting authorization..." gauth = GoogleAuth() # Try to load saved client credentials gauth.LoadCredentialsFile(credentialsFile) if gauth.credentials is None: # Authenticate if they're not ther...
e95cb5d4856f4903ed0e48fab43e721314740e38
kamarajanis/python-code
/Guess_num_extended.py
185
3.875
4
import random x=int(input("Guess and Enter that Number\n")) y=random.randint(0,100) if x==y: print("Correct") else: print("Wrong") print("The Answer is");print(y)
96746fa4a684f54e3698529900288ca9d8317ac1
nagachaitanya3217/highpeak_coding
/code.py
1,973
3.921875
4
#input is stored in a text file named "input_x.txt" , where x=1,2,3 ip_file=open('C:\\Users\\naga chaitanya\\Desktop\\HIGHPEAK_CODING\\input.txt') f_data=ip_file.readlines() #ouput is stored in a text file named "output.txt" op_file = open("C:\\Users\\naga chaitanya\\Desktop\\HIGHPEAK_CODING\\output.txt", "w") ...
75495c9b4ecd4f823458b68751b400ef2b5347b5
brucejzou/TruePill
/api/src/url_helpers.py
2,538
3.796875
4
import urllib.parse import tldextract from src.make_requests import make_request import re import requests def get_base_url(article_url): """ Takes the article url and returns the base url. Example: Input: https://www.cnn.com/2021/02/06/us/ben-montgomery-shot-moonlight-book-trnd/index.html Out...
d3a41510332b595ca636ec5f0ed4929ed6b5194c
KC-MSC-CS/RM
/practicals/practical7.py
698
3.828125
4
import pandas as pd data = {'Product': ['ABC','DDD','XYZ','AAA','CCC','PPP','NNN','RRR'], 'Price': [630,790,250,370,880,1250,550,700], 'Discount': ['No','Yes','No','Yes','Yes','No','No','Yes'] } df = pd.DataFrame(data, columns = ['Product','Price','Discount']) print(df) # randomly select a ro...
720c6d2c678ada2ee2b6e7014f25a2ac4dd8a748
gtshepard/TechnicalInterviewPrep2020
/assignments/week2/day3/garrison_shepard_lc_143.py
657
3.703125
4
def reorderList(self, head): if not head: return if not head.next: return if not head.next.next: return prev = head cur = head.next tail = prev while cur: tail = prev if not tail...
47a447ace9b2f03806fd71c27dfb3fbd7f9d916b
TianCccc/Leetcode
/20_Valid Parentheses/20.py
526
3.796875
4
# Valid Parentheses """ Input: s = "()" Output: true Input: s = "{[]}" Output: true Input: s = "([)]" Output: false """ def isValid(s): d = {')': '(', ']': '[', '}': '{'} stack = [] for i in s: if (len(stack) != 0) and i in d: # stack last element compared with eleme...
f27ff870ae722419454695cdc41d361a15d92f4a
TianCccc/Leetcode
/55_Jump Game/55.py
376
3.734375
4
# Jump Game """ Input: nums = [2,3,1,1,4] Output: True Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index. """ def canJump(nums): # Greedy farthest = 0 for i, jump in enumerate(nums): if farthest >= i and i+jump > farthest: # 当前位置能到达 and 下一跳超过farthest farthest = i...
1a421357528256390898c0ced93785163ca11100
ivan-nikolaev/tkinter_course
/tkinter_04_layout_management.py
942
3.671875
4
from tkinter import * class Window(Tk): def __init__(self): super(Window,self).__init__() self.title("Tkinter Label") self.minsize('500', 400) self.wm_iconbitmap("resourses/virus_coronavirus_medical_bacterium_cell_icon_142127.ico") self.create_layout() def create_layo...
9b1c7aae583a3cb1b7aaef37fa8155cbf8f259b4
Ayush-1211/Python
/Advanced OOP/5. class and static method.py
855
3.984375
4
''' 1. Instance Methods: The most common method type. Able to access data and properties unique to each instance. 2. Static Methods: Cannot access anything else in the class. Totally self-contained code. 3. Class Methods: Can access limited methods in the class. Can modify class specific details. ''...
518af208c37572b453efe7879fcd7855af6ce05c
Ayush-1211/Python
/Python Basics/31. Dictionary Methods-2.py
1,217
3.671875
4
print('Example 1::') dictionary = { 'basket' : [1,2,3], 'name' : 'Ayush', 'Hii' : 'Hello' } print('basket' in dictionary) print('age' in dictionary) print('Example 2::') print('basket' in dictionary.keys()) print('Ayush' in dictionary.values()) print(dictionary.items()) print('Example 3::') ...
2921ed666239fbc9748230bdcd331449068d54c8
Ayush-1211/Python
/Functional Programming/10. Set Comprehensions.py
242
3.71875
4
my_set = {char for char in 'Hello'} my_set2 = {num for num in range(0,10)} my_set3 = {num**2 for num in range(0,10)} my_set4 = {num**2 for num in range(0,10) if num % 2 == 0} print(my_set) print(my_set2) print(my_set3) print(my_set4)
81a06573758253956d2d5f7b06502b61e147d046
Ayush-1211/Python
/Python Basics/35. Sets Methods.py
1,023
3.984375
4
my_set = {1,2,3,4,5,6} your_set = {4,5,6,7,8,9,10} print('Example 1::') print(my_set.difference(your_set)) print('Example 2::') my_set.discard(6) print(my_set) print('Example 3::') my_set.difference_update(your_set) print(my_set) print('Example 4::') my_set2 = {1,2,3,4,5,6} your_set2 = {4,5,6,7,8,9,10...
1138c4e26dc7ee107a8ca4e322c0bf0af760f94a
Ayush-1211/Python
/Python Basics/6. Variables.py
172
3.578125
4
a = 10 b = a/2 c = b + 10 print(c) print('Constant Variables::') PI = 3.14 print(PI) print('Multiple Variables::') x,y,z = 1,2,3 print(x) print(y) print(z)
c87c61d1d41efa436ee37eaeae640d02e1b09a5b
Ayush-1211/Python
/Modules/Useful Modules.py
477
3.515625
4
from collections import Counter, defaultdict, OrderedDict import datetime li = [1,2,1,3,5,6,3,4,2,6,8,1,6] sentence = 'Blah Blah Blah thinking about Python' print(Counter(li)) print(Counter(sentence)) dictionary = defaultdict(lambda : 'Does not exist!!', {'a' : 1, 'b' : 2}) print(dictionary['c']) d = Orde...
789d2a03b20e29610aff7f43e66abe6214a8cbac
Ayush-1211/Python
/Advanced OOP/2. Creating Objects.py
397
3.53125
4
class PlayerDetails: def __init__(self,name,age): self.name = name #attributes self.age = age def run(self): print('Run') player1 = PlayerDetails('Ayush', 21) player2 = PlayerDetails('Kohli', 34) player2.attack = 50 print(player1.name) print(player1.age) print(player2.n...
6982b7b8cf932a3c9e59e5909c3dfd6d1d6716d0
Ayush-1211/Python
/Advanced OOP/9. Polymorphism.py
1,130
4.46875
4
''' Polymorphism: Polymorphism lets us define methods in the child class that have the same name as the methods in the parent class. In inheritance, the child class inherits the methods from the parent class. ''' class User: def sign_in(self): print('Logged I...
48b8821d70c96829fb66ca1d15d6d5af7c741847
Ayush-1211/Python
/Python Basics 2/24. Scope.py
719
3.546875
4
# Scope - what variables do I have access to? ''' Rules: 1. Start with local 2. Parent local? 3. Global 4. Built in python function ''' print('Example 1:') a = 1 # Global def parent(): # Parent scop a = 10 # Parent local de...
d9f4f930746297e0c52bcf68be0ff3b33fbdaf1b
Ayush-1211/Python
/Regular Expressions/3. Email Validation.py
151
3.578125
4
import re pattern = re.compile(r"\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b") string = 'ayushprajapati1211@gmail.com' a = pattern.search(string) print(a)
a4deb3fc04407566f9c44a36fc6cc90c3acd647c
togoh9175/03_Maths_Quiz
/01_MQ_Base_Component.py
3,182
4.125
4
print () print ("▁ ▂ ▄ ▅ ▆ ▇ █ ᴡᴇʟᴄᴏᴍᴇ ғᴇʟʟᴏᴡ ʙᴇɪɴɢs █ ▇ ▆ ▅ ▄ ▂ ▁") print () def yes_no (question): valid = False while not valid: response = input(question).lower() if response == "yes" or response == "y": response = "yes" return response elif response == "no" or response == "n": ...
452a67eb3363f2e9e5c69a7ea68e35b9d36afd2a
EchuCompa/Cursos-Python
/rebotes_saludo.py
222
3.640625
4
# rebotes.py # Archivo de ejemplo # Ejercicio altura = 100 """ for r in range(10): altura = altura*3/5 print(round(altura,4)) """ name = input("Decime tu nombre queride ") print("Que lindo nombre tenes", name)
8eea0dc95f7f192bff4ca5cee568f328ac73767a
EchuCompa/Cursos-Python
/generala.py
1,925
3.640625
4
# -*- coding: utf-8 -*- """ Created on Wed Aug 26 16:48:38 2020 @author: Diego """ import random from collections import Counter # Ejercicio 4.6 # def tirar(): # tirada = [] # for d in range(5): # tirada.append(random.randint(1, 6)) # return tirada def es_generala(tirada): #hard generala=...
406b4ac023dff30a1ecb90cbfb11c70ba4821b8e
EchuCompa/Cursos-Python
/esfera.py
226
3.765625
4
# -*- coding: utf-8 -*- """ Created on Wed Aug 5 17:50:55 2020 @author: Diego """ import math radio = int(input("Ingrese el radio de su esfera :")) print ("El volumen de su esfera es :" , (radio**3)*(math.pi)*4/3) math.pi
02af4760b1eaa0e35773e3ecc6d6302cf8a2218a
EchuCompa/Cursos-Python
/funciones.py
713
3.765625
4
# -*- coding: utf-8 -*- """ Created on Wed Aug 12 17:58:54 2020 @author: Diego """ # numero_valido=False # while not numero_valido: # try: # a = input('Ingresá un número entero: ') # n = int(a) # numero_valido = True # except: # print('No es válido. Intentá de nuevo.') # print(f...
e6744d713df469100966bb4b0d456d2741bcfafd
KerTakanov/CoursFabien
/lire_ou_pas.py
172
3.59375
4
nb_livres = int(input()) precedent = "" for i in range(nb_livres): livre = input() if len(livre) > len(precedent): print(livre) precedent = livre
c81a41956d33e229ac0c949801d6314cf11f671a
KerTakanov/CoursFabien
/phenomene_numerique.py
128
3.734375
4
nb = int(input()) while nb != 1: if nb % 2 == 0: nb //= 2 else: nb = nb * 3 + 1 print(nb, end=' ')
aa10290eae584e8fd9f8957627367d106904567a
Dios-Malone/projecteuler
/P010.py
924
3.921875
4
import math def isprime(num): assert isinstance(num,int) sqrt = int(math.sqrt(num)) if num==1 or num ==0: return False if num==2: return True elif num%2==0: return False else: for n in range(3, sqrt+1, 2): if num%n==0: return False return True def so...
cab604dc8d15cb7e9f9ceb11cc4ea8bf9d6371c5
ericraio/python
/kivy/quickstart.py
1,165
3.921875
4
""" First we import kivy and check if the current installed version will be enough for our application. If not, an exception will be automatically fired, and prevent your application to crash in runtime. You can read the documentation of kivy.require() function for more information """ import kivy kivy.require('1.3.0'...
bd25b715de543f5ad54f7adc3fa0da0f237f86dd
dartleader/Learning
/Python/How to Think Like A Computer Scientist/4/exercises/8.py
373
4.4375
4
#Write a function area_of_circle(r) which returns the area of a circle with radius r. def area_of_circle(r): """Calculate area of a circle with radius r and return it.""" #Docstring #Declare temporary variable to hold the area. area = 0 #Calculate area. area = 3.14159 * r #Return area. return area print(input(a...
83a6d2c8f96e0602d9146c8675081806c7ef2ec3
dartleader/Learning
/Python/How to Think Like A Computer Scientist/4/exercises/9.py
361
3.75
4
import turtle wn = turtle.Screen() wn.bgcolor("white") #Initialize tess and set attributes tess = turtle.Turtle() tess.color("black") tess.pensize(3) #Draw a five-pointed star def draw_star(t,sz): """Draw a five-pointed star of sz arm length with turtle t."""#Docstring for i in range(5): t.forward(sz) t.right(...
e8a1ae7e49ddf7c6930a045a9c37dd4326dda606
Anymatrix/Python
/TFIDF/Modules/Interfaces/SimilarityTable.py
1,311
3.609375
4
#!/usr/bin/env python # Creating table of texts' cosine similarity def CreateTable(cos, files_amount): table = [] for i in range(0, files_amount): line = [] if i < files_amount-1: CollectingLine(cos, line, i) for value in cos[i]: line.append(va...
af102afd0d84bf59d141716e84cb55228121ca22
hhoshino0421/PrimeDistribution
/PrimeDistribution/PrimeMain.py
4,327
3.890625
4
import sys import math #import numpy as np import array # 最大処理可能値定義 MAX_LIMIT_INDEX = 10000000 # 分割処理閾値 DIVIDE_LIMIT = 10000 # 使い方表示 def usage(): print("使い方") print(" python PrimeMain.py start end") print("") print("") # 引数チェック処理 def argv_check(args): if len(args) < 3: # 引数不足 p...
38f1fd9370a2cd3525c1c0f7050d5049d2a1e632
nilayarat/gaih-students-repo-example
/Homeworks/HW3.py
1,162
4
4
#HANGMAN GAME day 5 HOMEWORK import random words = ["leon", "apple", "summer", "banana", "book"] guess_number = 5 characters = [] #this list created to add using letters in case of repeating x = len(word) z = list('_' * x) print(' '.join(z), end='\n') while guess > 0: y = input("Guess a letter : ") if y in c...
529ab43dad95a108b543df8eb3a794395421e5da
Sukhrobjon/CS-1.3-Core-Data-Structures-SG
/challenges/dummy_testing.py
86
3.546875
4
s1 = set([1,2,3]) s2 = set([2 ,3, 4]) s3 = s1.difference(s2) print(s3) print(max(3,3))
d190d2073bc71b201cd5a4cdf229f13d5ed9a0b0
mincode/netdata
/netdata/workers/worker_storage.py
2,139
3.640625
4
# Storage for a table of worker instances from netdata.workers.json_storage import JSONStorage class WorkerStorage(JSONStorage): """ Table of worker instances stored in a json file; consisting of a list of pairs {'ip': ..., 'instance_id': ...} """ _instances_label = 'instances' # label in the d...
aca5226c069b815be77ad5800429d4e56d75cc0a
joannachoi/image_filters
/Output.py
754
3.65625
4
import Code from scipy.misc import ascent import numpy as N ascent = ascent() noisy_ascent = ascent + ascent.std()*0.5*N.random.standard_normal(ascent.shape) # Convolution Assignment3.convolution(ascent) Assignment3.convolution(noisy_ascent) print("Convolution: The robustness of the filter is relatively low to the pr...
05927e1712d5c218633f4d868f73f3ba8b84454d
wcski/aoc2019
/day1/d1p1.py
260
3.71875
4
input = open('input', 'r') inputSplit = input.read().split("\n") def calculateFuel(mass): massNum = int(mass) fuel = round(massNum/3) - 2 return fuel totalFuel = 0 for mass in inputSplit: totalFuel += calculateFuel(mass) print totalFuel
f8ad11a5952dd959d0c3c9eadf295638c5aa7ee9
olpotkin/algorithms-and-data-structures
/queue.py
650
4.09375
4
class Queue(object): # Constructor def __init__(self): self.queue = [] # Queue is empty list in the beginning # Is queue empty or not def isEmpty(self): return self.queue == [] # Insert element in queue def enqueue(self, data): self.queue.insert...
f0dc30a017fd5c3f4b33ddfd5e4469e5a91992ec
mihirp1/Python_Basics
/python_basics_itertools/solution.py
262
3.578125
4
from itertools import permutations def perm(): S, n = input().split(" ") n = int(n) S = str(S) list_s = list(S) list_s.sort() new = list(permutations(list_s,n)) for element in new: print("".join(element)) string = [] perm()
d7f50eac22164f4885e42d9e2fc20b984ccc75a6
mihirp1/Python_Basics
/Python_DataStruct_Basics/numpy_shape_reshape/solution.py
235
3.765625
4
import numpy def numpy_array(): numpy_array = numpy.array(list(map(int,input().split(' ')))) print(numpy.reshape(numpy_array,(3,3))) #print(numpy.reshape(numpy_array,(3,3))) if __name__ == "__main__": numpy_array()
b4f6d71f352434965960284a54113bc719abb2c6
Zidan2k9/PythonFundamentals
/loops.py
733
4.15625
4
# A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string). people = ['Zain','Rida','Zaid','Mom','Dad'] for person in people: print('Current person is ' , person) #Break out for person in people: if person == 'Zaid': break print('C...
3e525a576deccda073de297716d21a6a2858e114
jingruhou/practicalAI
/Basics/PythonTutorialforBeginners/03strings.py
512
4.125
4
course = "Python's Course for Beginners" print(course) course = 'Python for "Beginners"' print(course) course = ''' Hi houjingur, The support team ''' print(course) course = 'Python for Beginners' # 012345 print(course[0]) print(course[0:3]) print(course[:-1]) print(course[-1]) print(course[-2]) print(...
6d5429f80a35240ad5f3b0c226400771c2146e33
jingruhou/practicalAI
/Basics/PythonTutorialforBeginners/01app.py
354
3.984375
4
print("hello world") print(' o-----') print('******') print('*' * 10) price = 10 price = 20 print(price) full_name = 'xunfang Smith' age = 10 is_new = True # name = input('What is your name ?') # print('Hi ' + name) name = input('What is your name ?') favourite_color = input('What is your favourite color ?') pr...
56a64d560d9b729daa91d6ef0b264d63a7dc8310
jingruhou/practicalAI
/Basics/BeginnerPython/4-7_list操作示例.py
1,807
3.90625
4
tt = 'hello' list1 = [1, 4, tt, 3.4, "yes", [1, 2]] # 定义一个涵盖各种类型的list print(list1, id(list1)) # 将其内容及地址打印出来[1, 4, 'hello', 3.4, 'yes', [1, 2]] 2459221516936 # 比较list中添加元素的几种方法的区别 list3 = [6, 7] # 定义list3作为后面拼接实验使用 l2 = list1 + list3 # 使用+将list1与list3连接在一起,得到l2 print(l2, id(l2)) # 输出l2的内容及地址[1, 4, 'hello', 3.4...
107b4fcec2d89f36a3764f165d834023ff2f81e4
joyce-lam/prep
/strings/Q5.py
1,541
3.734375
4
# Justified Text # Given an array of words and a length L, format the text such that each line has exactly L characters and is fully (left and right) justified. # You should pack your words in a greedy approach; that is, pack as many words as you can in each line. # Pad extra spaces when necessary so that each line h...
06aa7d42c89f5f782b5cbcf0ff603e88920a69ab
joyce-lam/prep
/math/Q6.py
489
3.703125
4
# Rearrange Array # Rearrange a given array so that Arr[i] becomes Arr[Arr[i]] with O(1) extra space. class Solution: # @param A : list of integers # Modify the array A which is passed by reference. # You do not need to return anything in this case. def arrange(self, A): for i in range(len(A)...
35d69503f93de36ae9053b09d925e1f9ea975abc
joyce-lam/prep
/strings/Q1.py
563
3.9375
4
# Palindrome String # Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases. # Return 0 / 1 ( 0 for false, 1 for true ) for this problem class Solution: # @param A : string # @return an integer def isPalindrome(self, A): i = 0 j = len(A) - 1 ...
f9711fd2fd524ee4a75dd4a838d7320b12d05db0
joyce-lam/prep
/math/Q7.py
636
3.890625
4
# Grid Unique Paths # The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked ‘Finish’ in the diagram below). # How many possible unique paths are there? # Note: A and B will be such that the resulting answer fits in a 32 bit signed i...
ab766a90f11b3e50fc126ca2ed6df73aea58b877
joyce-lam/prep
/linked_list/Q6.py
750
3.859375
4
# List Cycle # Given a linked list, return the node where the cycle begins. If there is no cycle, return null. class Solution: # @param A : head node of linked list # @return the first node in the cycle in the linked list def detectCycle(self, A): slow_runner = A.next fast_runner = None if slow_runner: f...
b7e5646eb9fa043052a3c407efcd8352d7cfd668
Shlok347/Python_Assignment
/Question1_solution.py
219
3.5625
4
from math import * C,H = 50,30 def calc(D): return sqrt((2*C*D)/H) D = input().split(',') D = [int(i) for i in D] D = [calc(i) for i in D] D = [round(i) for i in D] D = [str(i) for i in D] print(",".join(D))
714be780f356d916fc66900961f8f9c8a9f419d1
JGhost01/Fundamento-ejecicios
/ejercicio_01.py
230
3.734375
4
#Crear una función que devuelva el número de palabras de una cadena de caracteres que le sea pasada como #argumento. Cuenta_palabras = "Hola Mundo" cuenta_palabras_part = Cuenta_palabras.split(' ') print(len(cuenta_palabras_part))
87930730f82be706e6dfd3a17a90355b438889df
jpfs2001/Modelagem-Matematica
/Projeto-5/geral.py
4,965
3.6875
4
# a classe abaixo define alguns métodos utilizados para matrizes class Matrizes: # produto entre duas matrizes def produtoMatriz(self, A, B): linA, colA = len(A), len(A[0]) linB, colB = len(B), len(B[0]) produto = [] for linha in range(linA): produto.append([]) ...
1733e7c758cb48f92c9798147b9d34146c3ac2b1
baviamu/set8-10.py
/middel.py
196
3.765625
4
sttg=list(input()) if len(sttg)%2==0: sttg[int(len(sttg)/2)] ='*' sttg[int(len(sttg)/2)-1]='*' else: sttg[int(len(sttg)/2)] ='*' for m in range(0,len(sttg)): print(sttg[m],end='')
787c9b97918daecc743c9cf2bbb123c3f2e15e67
baviamu/set8-10.py
/vowlornt.py
174
3.671875
4
nmbr = input() key = 'aeiou' for x in key: if x in nmbr: nmbr = '' break else: continue if nmbr == '': print('yes') else: print('no')
51f9a1607482265594555e7496c350ab2f1d82ad
parmar-mohit/Data-Structures-and-Algorithms
/Searching Algorithms/Python/Binary Search.py
861
4.15625
4
def binary_search( arr, len, num ) : ll = 0 ul = len - 1 mid = int( ll + ul / 2 ) while( ll < ul and mid < len ) : if arr[mid] > num : ul = mid - 1 elif arr[mid] < num : ll = mid + 1 else: break; mid = int( ul + ll / 2 ) ...
236b634d4754fef2a4a56e828e8ae04be0bcacb5
parmar-mohit/Data-Structures-and-Algorithms
/Searching Algorithms/Python/Linear Search.py
519
4.125
4
def linearSearch( arr, len , num): for i in range( len ) : if arr[i] == num : return i else: return -1 len = int( input( "Enter Length of Array : " ) ) arr = [] for i in range( len ) : arr.append( int( input( "Enter Value in Array : " ) ) ) num = int( input( "En...
3886714b6ad94e08ffd5c89750c68649c12d55d0
bihanviranga/virtual_memory
/vm_of_python_script/print_byte_string.py
320
3.84375
4
""" Print a bytes string (b"string"), and then read a char from stdin and prints the same string again. """ import sys s = b"VirtualMemory" # This ensures that we are using a bytes object. # The string will be saved as bytes, as ASCII values # in the virtual memory of the script. print(s) sys.stdin.read(1) print(s)
3cb4957c0ac193daada21bcef0ed175b3cf89e3d
Acee11/Studia
/Semestr1/Python/lista8/zad2.py
469
3.671875
4
def dodaj(L1,L2): carry = 0 res = [] if len(L1) > len(L2): L1r = list(reversed(list(L1))) L2r = list(reversed(list(L2))) else: L1r = list(reversed(list(L2))) L2r = list(reversed(list(L1))) for i in range(len(L1r)): carry += L1r[i] if i<len(L2r): carry += L2r[i] res.append(c...
7ac114a26dd48adfec08879b36ccd4b6c913797f
Acee11/Studia
/Semestr1/Python/lista7/zad5.py
2,085
3.5
4
# -*- coding: utf-8 -*- #może nie działać na linuxie(nie wiem dlaczego) from turtle import * delay(0) def square(b,c,x,y): color(c,c) pu() setpos(x,y) pd() begin_fill() fd(b) rt(90) fd(b) rt(90) fd(b) rt(90) fd(b) rt(90) end_fill() def deadOrAlive(P,y,x): cells = 0 f...
d7b44e3354a2a9b87d46bc5bc8b2488a20342c2d
jobvink/advent_of_code_2019
/day_6/main.py
1,717
3.796875
4
class Map: def __init__(self, orbits): self.map = dict() self.orbits = orbits self.orbits_required = 0 self.path = [] self.orbit_lenghts = dict() for orbit in orbits: if orbit[0] in self.map.keys(): self.map[orbit[0]].append(orbit[1]) ...
e6cd2449d5e6ee8b5acf5e96eff83e9b1f4743b6
JeroenGoddijn/Coding-Exercises
/WEEK01/Thursday/function_exercises.py
3,812
4.40625
4
# 1. Hello # Write a function hello which takes a name parameter and says Hello to the name. Example: hello('Igor') should print def sayHello(name): print("Hello,",name) sayHello(name = input("What is your name? ")) # 2. y = x + 1 # Write a function f(x) that returns x + 1 and plot it for x values of -3 to 3...
38ba38b00b9827b7d451145f107f081de9a668ae
JeroenGoddijn/Coding-Exercises
/WEEK01/Thursday/shapes_exercise3.py
2,359
3.8125
4
from turtle import * # Equilateral Triangle def eq_triangle(size, colour, fill_it): if fill_it: begin_fill() for i in range(3): pencolor(colour) forward(size) left(120) end_fill() else: for i in range(3): pencolor(colour) ...