blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
545k
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
545k
ac90fbf7a7f20018e17262fe544729fb722609a7
june07/packagecontrol.io
/app/templates/helpers/date_diff.py
1,182
3.75
4
import calendar import time from datetime import datetime from dateutil import parser def date_diff(this, date, upper): """ Pybars helper for generating a date diff """ if not isinstance(date, datetime): date = parser.parse(date) first = int(calendar.timegm(date.timetuple())) second...
bf484056e7ebb3aa9d3ead9a2f64f7cbb033f6f2
evural/hackerrank
/cracking/chapter2/sum_lists.py
1,529
3.75
4
import sys sys.path.append('/home/ersan/Desktop/algorithm/hackerrank/cracking/data_structures') from linked_list import LinkedList def list2int(arr, base): result_sum = 0 digit = 1 for i in range(0, len(arr)): result_sum += (arr[i] * digit) digit *= base return result_sum def sum_list...
c2c7913c5164e3b87dc53022ad7eeec2497cf516
evural/hackerrank
/cracking/chapter1/urlify.py
762
3.90625
4
# Iterate over the string starting from the end to use the extra buffer at the end # If there is a space, replace with %20; otherwise copy the original character def urlify(text, real_size): if len(text) == real_size: return text j = len(text) - 1 for i in range(real_size-1, -1, -1): if tex...
3cf8c28b06e50bf446701066958e4e04079e777d
evural/hackerrank
/cracking/chapter1/is_unique_bitwise.py
535
4.15625
4
# 1. Initialize a checker variable to 0 # 2. For each character in the text, shift left bits of 1 # 3. If bitwise AND of this value returns a number other than 0, return False # 4. Bitwise OR this value with the checker variable def is_unique(text): checker = 0 for c in text: val = ord(c) - ord("a") ...
37a85496bc682a7bc49ef6ad06fc42a81113eec1
evural/hackerrank
/cracking/chapter4/is_route_exist.py
1,656
3.578125
4
import sys sys.path.append('/home/ersan/Desktop/algorithms/hackerrank/cracking/data_structures') from queue import Queue from dag import generate_random_graph def is_route_exist(graph, node1, node2): return check_route(graph, node1, node2) or check_route(graph, node2, node1) def check_route(graph, s_node, d_nod...
07d1147e4537b7d4bfc5fa372584a78986d0d0e9
mklabar/csc4750-lab1
/chat_client.py
1,687
3.765625
4
from socket import * from struct import * import sys #if the command line argument is missing the IP/hostname or port number an error is printed if len(sys.argv) !=3: print("\nInvalid syntax: please enter the IP address or hostname followed by the port number\n") exit() #setup socket to connect to server, arg 1 is ...
a99ad3be85dad9698d4316e9e8d3ccb6399e5e8a
Mr-AB007/Python-Practice
/SumofMidelle3Digit.py
652
4.09375
4
#Find the sum of middle 3 digit of 5 digit number and if number of digits is not equal 5 then find product of all digit s = input("Enter the number ") n = int(s) print("number of digit {}".format(len(s))) if(len(s)!= 5): mul = 1 while(n > 0): mul *= n%10 n //= 10 print("...
0ccefd9c84e3604ed843c774550012cf75b03eba
ansjcy/clode
/evaluator/app/utils.py
314
3.96875
4
import math def inverse(u, v): """inverse(u:long, v:long):long Return the inverse of u mod v. """ u3, v3 = int(u), int(v) u1, v1 = 1, 0 while v3 > 0: q=divmod(u3, v3)[0] u1, v1 = v1, u1 - v1*q u3, v3 = v3, u3 - v3*q while u1<0: u1 = u1 + v return u1
2e48086e0a2f5f1e483c7ce75c64d546fecb1370
VishalVimal/python-project
/cooding anna execise/guss_number.py
832
3.890625
4
import random random_number=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20] total_chance=5 reming_chance=0 guss_number=random.choice(random_number) while True: user_guss=int(input("Enter the number between 1 to 20 :")) if total_chance<reming_chance: print("sorry u have lost the game") ...
ae5cc300bd613f39db96587fe53c8f707da6be53
EssamB13/puzzle-solver
/grid_peg_solitaire_puzzle.py
3,323
3.5
4
from puzzle import Puzzle class GridPegSolitairePuzzle(Puzzle): """ Snapshot of peg solitaire on a rectangular grid. May be solved, unsolved, or even unsolvable. """ def __init__(self, marker, marker_set): """ Create a new GridPegSolitairePuzzle self with marker indicating...
16bc4d68a5171b94aca7ff760d8ca5cd8a41cf62
shrujan/python-learn
/Day2/Q2.py
254
4.03125
4
List1 = [47,11,42,102,13] def findMax(list): maximum = 0 for l1 in list: if l1 > maximum: maximum = l1 return maximum maximum = findMax(List1) print('Max value = ', maximum ) # # OR # print("Max == ",max(List1))
968a4358d06e7a752e5150693e40bc8689a5126f
shrujan/python-learn
/Assignment/Q5.py
939
3.671875
4
import re urlFile = open('TextFiles/url.txt', "r") while True: str = urlFile.readline() if str: # check for http or https 0 or more at beginning # :// 0 or more # www - 1 or more # a-zA-Z0-9, 1 or more # .com $ - at the...
081a2d4d12ae193eca2aa1078c3c72504b5d2855
Snatiolam/Analisis-numerico
/Methods/Python/biseccion.py
1,207
3.5
4
#!/home/salzatec1/miniconda3/bin/python import math def biseccion(func, a, b, Nmax, tol): if a > b: print("'A' cannot be greather than 'B'") return fa = func(a) fb = func(b) pm = a + (b-a)/2 fpm = func(pm) E = 1000 count = 1 print("|{i:^3}|{a:^20}|{xm:^20}|{b:^20}...
7063411334398b17a0488f39618a3a01b62d9cfa
BCarter93/TP3
/TP3.py
5,056
3.671875
4
import ast print print(" Bienvenido al analizador de ambientes Estaticos y Dinamicos") global Estatico global Dinamico global EstaticoLet global DinamicoLet Estatico= [] Dinamico= [] EstaticoLet= [] DinamicoLet= [] def Inicio(): print NombreArchivo=input("Ingrese el nombre del archivo que desea analizar: ") ##RAW...
2662ba46e26dc5bdfadd8d143cb9d5fbed7a4d53
emielver/project-euler-hacking
/problem3.py
456
3.625
4
import math number = 600851475143 def primeFactorFinder(number): primes = [] divis2 = False while number % 2 == 0: if not divis2: primes.append(2) divis2 = True number = number/2 for i in range(3, int(math.sqrt(number)) + 1, 2): while number % i == 0: ...
92051f6811c29c8c769246462e56a07b78d7801f
emielver/project-euler-hacking
/problem641.py
513
3.609375
4
import time def incrementDice(dice, n): for i in range(n, len(dice), n): dice[i] += 1 return dice def count(dice): c = 0 for i in range(1, len(dice)): if dice[i] % 6 == 1: print(i) c += 1 return c for p in range(9, 10): start = time.time() n = 10 *...
a23bc62025141f95dd7948c0567bd12dcf1797c8
emielver/project-euler-hacking
/project17b.py
1,731
3.78125
4
ones = ["one", "two", "three", "four", "five", "six", "seven", "eight", "nine"] tens = ["teen", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"] hundreds = "hundred" thousands = "thousand" def length(n): inWords = "" string = str(n) if len(string) == 2: tenColumn = int(s...
bf37863f3d904f7f0cc53fa3303149613b80b693
emielver/project-euler-hacking
/problem29.py
175
3.71875
4
numbers = [] for a in range(2, 101): for b in range(2, 101): power = a ** b if power not in numbers: numbers.append(power) print(len(numbers))
a5667e89cc780415092f0c9caf4dbd9b1c359758
fhernand23/cursoSistemasInteligentes2019
/tp2/neural-network-2layer.py
3,090
4.125
4
# two layer neural network sample import numpy as np class NeuralNetwork(): def __init__(self): # Seed the random number generator np.random.seed(1) # Single neuron - 3 input connections - 1 output connection # Random weights 3 x 1 matrix, in the range -1 to 1 and mean 0. s...
e9c401d810cca9344ae01fbf784537454f9991d6
Sh0ckT/Devoir-Probl-me
/Probleme.py
647
3.8125
4
Transformer = ['Legend Class', 'Core Class', 'Deluxe Class', 'Voyager Class', 'Leader Class', 'Titan Class'] # cite les differentes tailles de transformer disponibles price = [11, 17, 23, 31, 47, 60] # cite les prix de chaque catégorie somme = int(input("Entrer une somme: ")) # demande a l'utilisateur de dire quelle s...
2824d16bb0d6d0715e0c355f275958fbc43d83ea
RyanD1996/FYP
/FYP/pong.py
12,363
3.515625
4
import pygame import random import numpy as np import sys FPS = 60 # Game window dimensions WINDOW_WIDTH = 500 WINDOW_HEIGHT = 420 GAME_HEIGHT=400 # Size of the paddle PADDLE_WIDTH = 15 PADDLE_HEIGHT = 60 PADDLE_BUFFER= 15 # Size of the ball BALL_WIDTH = 20 BALL_HEIGHT = 20 MAX_SCORE = 11 # Spe...
f02dfe03efde84e6492a6dec2a3898159eca968a
eliassim/LearnPython
/game01.py
11,407
3.875
4
import random ,time from tkinter import messagebox class Score: PointsArr = [None] * 2 def __init__(self): self.PointsArr[0] = 0 self.PointsArr[1] = 0 def addPoints(self, player, points): self.PointsArr[player-1] += points def addPoint(self, player): self.Point...
86b26c4297a1c08488d85bbec62f3b9146b20e69
avocardio/MLinPractice
/test/feature_extraction/hash_vector_test.py
1,303
3.515625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ A class to test the HashingVectorizer Created on Thu Oct 14 14:51:00 2021 """ import unittest import pandas as pd import numpy as np import pdb from code.feature_extraction.hash_vector import HashVector class HashVectorTest(unittest.TestCase): def setUp(self):...
838468f6ac2279a4404159872ac8748678d79a03
Rudolfowich/HomeWork
/Hw2/Fizz-Buzz.py
345
3.8125
4
f = int(input('введите число fizz ')) b = int(input('введите число buzz ')) op = int(input('Введите число S ')) for i in range(1, op): if i % f == 0 and i % b == 0: print('FB') elif i % f == 0: print('F') elif i % b == 0: print('B') else: print(i) #be happy
40e93474f0ead39e71a828c2ee8b72444955c084
NickSadjoli/Week4_GlobalForecast_COVID19
/notebooks/data_retreiver.py
2,256
3.640625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Apr 1 05:25:58 2020 @author: josephinemonica """ import pandas as pd import numpy as np def string_to_integer(s): # e.g. '1,439,323,776' ---> '1439323776' s = s.replace(",","") # Convert string to integer s = int(s) return ...
e1810b4761fcc0e5bd3c9d13defc209e1a779533
LiubaKarlina/ParadigmHomework
/model.py
4,551
3.671875
4
class Scope(object): def __init__(self, parent = None): self.parent = parent self.dict = dict() def __getitem__(self, key): if key not in self.dict: if self.parent: return self.parent[key] else: return self.dict[key] def __setitem__(sel...
68d2086e24af7d138ac4d2fd71691b2337a4c46a
yumengzou/PythonEx
/PythonEx/ClassObject/SuperC.py
1,159
3.640625
4
''' Created on Jun 3, 2017 @author: yumeng.zou ''' ## Superclass ## inherit methods from the superclass by class_name(superclass) class Filter(): def init(self): self.blocked=[] def filter(self,seq): return [i for i in seq if i not in self.blocked] class SPAMFilter(Filter): d...
8ea907c4d0a631e607d3e138597737196751059c
razi21-meet/meet2019y1lab3
/lab_3.py
259
3.890625
4
print('hello world') print("hello wolrd") print("hello tamar") print("hello gil") #print('hello world') user = input("say something! ") string = 'go to surf'.upper() user = 'DABK'.lower() happy = 'hAVE fUN'.swapcase() print(user) print(string) print(happy)
70e9075afd47443a993e4be807274629de87329d
Kevin8523/scripts
/python/python_tricks/class_v_instance_variables.py
1,110
4.15625
4
# Class vs Instance Variable Pitfalls # Two kind of data attributes in Python Objects: Class variables & instance variables # Class Variables - Affects all object instance at the same time # Instance Variables - Affects only one object instance at a time # Because class variables can be “shadowed” by instance variables...
edf6c4206d19b4fc30d512f7592cbbc8ebcd44ff
Kevin8523/scripts
/python/python_tricks/string_formatting.py
751
4.09375
4
# String Formatting: # 4 ways: Old, New, Literal, Template # Rule of Thumb: Use Literal (python 3.6+) unless strings are user-supplied then use Template Strings errno = 50159747054 name = 'Bob' # Old Style 'Hello %s' % name # New Style 'Hello {}'.format(name) 'Hey {name}, there is a {errno} error!'.format(name=name...
701c22b62921af1315710489d3f1935a28079b07
burgonyapure/cc1st_siw
/calc.py
494
4.28125
4
def f(x): return { '+': int(num1) + int(num2), '-': int(num1) - int(num2), '*': int(num1) * int(num2), '/': int(num1) / int(num2) }.get(x, "Enter a valid operator (+,-,*,/)") while True: num1 = input("\nEnter a number,or press a letter to exit\n") if num1.isdigit() != True: break y = input("Enter ...
cff7f99ff2fe67ef77dfdd2cb796a43179be9cb5
hyojuntak/Day73
/Argorism.py
364
3.6875
4
def numnum(): S = input() result = 1 for i in range(len(S)): if S[i]=='0': if i==0: pass if i>0: result += int(S[i]) elif S[i]=='1': if i==0: pass if i>0: result +=int(S[i]) else: result *= int(S[i]) print(r...
3cf3cde35fddfb0029dc4a674cbbab590453fad2
kit-leonzhang/CODE-questions
/easy questions/二叉树的最大深度.py
973
3.546875
4
import collections class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def maxDepth(self, root: TreeNode) -> int: if not root: return 0 queue = collections.deque([...
346ea1ae2d42f82da561e8cd8ed8725e72b9ca15
kit-leonzhang/CODE-questions
/easy questions/多数元素.py
577
3.5625
4
def majorityElement(nums: list) -> int: nums.sort() return nums[len(nums)//2] def majorityElement2(nums) -> int: cur = nums[0] count = 0 for _ in nums: if cur == _: count += 1 else: count -= 1 if count == 0: cur = _ ...
2d910be7a8c6ef06b9c15b531cf39510d1fb374f
robifis/Python-Trivia-Quiz-Game
/quiz.py
4,517
3.96875
4
#!/usr/bin/python3 # """ # GOAL: Create a Quiz Game that pulls data from an online API.(Multiple choice) # TODO: # 1) Get the API loaded correctly # 2) Display the data to the user # 3) Count Score # 4) Display Score after X number of questions # 5) Play Again? # """" import requests, pprint, json, base64, random fr...
0e76971f4c57f194f05cbccf3803771fa24c9e02
hack-e-d/codekata
/sign.py
216
4.25
4
#to find if positive ,negative or zero n=int(input()) try: if(n>0): print("Positive") elif(n<0): print("Negative") else: print("Zero") except: print("Invalid Input")
f7d503987f53b01f5b9b40794ab9b04f75991e9b
tirthbal/AlgorithmsAndDataStructures
/python/queue.py
905
3.859375
4
class Queue: def __init__(self): self.capacity = 100 self.container = [0 for i in range(0, 100)] self.front = 0 self.rear = 0 def enqueue(self, data): if self.rear == 0: self.container[self.rear] = data self.rear += 1 return if self.front == self.rear and self.front != 0 : print 'Queue O...
27d3aa560986e2b840dab0c1962275659ad17f96
tirthbal/AlgorithmsAndDataStructures
/python/binary_search_tree.py
6,251
3.796875
4
class Node: def __init__(self): self.left = self.right = None self.data = None class BinarySearchTree: def __init__(self): self.root = Node() self.inorder_list = [] def __search_helper(self, curnode, target): if not curnode: return None if curnode.data == target: return curnode if curnode.da...
eefcbe2426f4069c8fcbe4c52dc15b9160b2fec6
tirthbal/AlgorithmsAndDataStructures
/python/binary_special_tree.py
768
3.578125
4
from queue_ll import Queue from stack_ll import Stack class Node: def __init__(self, data=None): self.left = None self.right = None self.next_right = None self.data = data class BinarySpecialTree: def __init__(self): self.root = Node() def connect_right_node(self): if not self.root: return qu ...
368a3c42c28dc2f40b1840c22ddca8dda02fd63a
Sivaji-Marripudi/TCS_NQT_2020
/vowels_remove.py
256
3.6875
4
text = input('enter text : ') d = {i:0 for i in 'aeiou'} vowels = [] for char in text: if char in d: d[char] += 1 for i,j in d.items(): vowels.append(i) print(i,j) new_text = [i for i in text if i not in vowels] print(''.join(new_text))
b0161aab5b52a307139c00bc7ed719b047899c0e
MateusPeschke/CursoPython
/Aula06/Banco_de_Dados.py
632
3.890625
4
import sqlite3 conn = sqlite3.connect("Aula06\exeple.db") c = conn.cursor() #Creat Table c.execute('''CREATE TABLE stocks (date text, trans text,symbol text, qty real, price real)''') c.execute("DELECTE from stocks VALUES") # Incsert a row of data c.execute("INSERT INTO stocks VALUES ('2006-01-05','BUY',...
09ef1c55af9f1f38626bd25869f703b023405f5d
MateusPeschke/CursoPython
/Aula05/Exercicios02.py
580
3.515625
4
# Questão 1 lista = [x*3 for x in range(34)] print(lista) # Questão 2 lista_par = [x for x in range(100) if x%2 == 0] print(lista_par) # Questão 4 import matplotlib.pyplot as plt def Jur_compostos(tempo,capital,taxa): taxa = taxa / 100 montatante = capital * (1 + taxa) ** tempo return round(montatan...
842829ec4c71e1b6c5f766e75baba66398bd3b99
lexiaoyuan/PythonCrashCourse
/python_07_function/music.py
510
3.96875
4
def make_album(singer, album, numbers=''): albums = {'singer': singer, 'album': album} if numbers: albums['numbers'] = numbers return albums print(make_album('张靓颖', '终于等到你')) print(make_album('邓丽君', '我只在乎你', 20)) print(make_album('汪小敏', '笑看风云')) while True: singer = input("请输入歌手:") if not...
74a34133f6c72a99bdf9c41761be511edde10fcd
lexiaoyuan/PythonCrashCourse
/python_04_if/conditional_tests.py
513
3.953125
4
car = 'subaru' print("Is car == 'subaru'? I predict True.") print(car == 'subaru') print("Is car == 'audi'? I predict false") print(car == 'audi') s1 = "String1" s2 = "string2" s3 = "string1" s4 = "String1" print(s1 == s4) print(s1 == s2) print(s1.lower() == s3) n1 = 20 n2 = 8 print(n1 == n2) print(n1 != n2) print(...
ee0f4c99c4928bee8028e29474839f998e326206
lexiaoyuan/PythonCrashCourse
/python_11_data/cube.py
399
3.8125
4
import matplotlib.pyplot as plt x_values = list(range(1, 6)) y_values = [x**3 for x in x_values] plt.plot(x_values, y_values) plt.title("Cube of value") plt.xlabel("Value") plt.ylabel("Cube of value") plt.show() x_values = list(range(1, 5001)) y_values = [x**3 for x in x_values] plt.scatter(x_values, y_values, c=...
d76f6a16d3a3b484ab9f8f3d7bda2bcad0e8c691
lexiaoyuan/PythonCrashCourse
/python_04_if/magic_number.py
357
3.984375
4
answer = 17 if answer != 42: print("That is not correct answer. Please try again!") age = 19 print(age < 21) print(age > 21) print(age <= 21) print(age >= 21) age_0 = 22 age_1 = 18 print(age_0 >= 21 and age_1 >= 21) print(age_0 >= 21 or age_1 >= 21) requested_toppings = ['mushrooms', 'onions', 'pineapple'] prin...
5a4a6a654a442b6ca43758d869b2e8f2072811e0
noctildon/noctildon.github.io
/DS_ambassador/codes/mod_child.py
378
3.5625
4
""" Purpose of self-made modules: modulize the code Write the code to a file, use import to import the file Module ~ python file ~ package ~ library """ e_num = 2.7 def circle(r): return 3.14 * r**2 print('Can you see me? - mod1.py') print(f'__name__ in mod1.py: {__name__}') if __name__ == '__main__': # mo...
c126cbbb519dd3e384ed102f286ffe73d99dc2fc
decordoba/basic-python
/basic/basic/basic_plot_tooltip.py
6,692
3.75
4
import matplotlib.pyplot as plt import numpy as np import pandas as pd import mpld3 from mpld3 import plugins def plot_df_with_tooltip(df, y_column, x_column=None, tooltip_columns=None, tooltip_title_column=None, tooltip_style=None, title=None, style="o", color="", show=True): """Plot sca...
a8c28d2602f9400fae0baad00135c1612187f4f9
tasnimz/labwork
/LAB 3.py
1,934
4.1875
4
##LAB 3 ##TASK 1 ##TASK 2 ##TASK 3 st = []; # Function to push digits into stack def push_digits(number): while (number != 0): st.append(number % 10); number = int(number / 10); # Function to reverse the number def reverse_number(number): # Function call to push number's...
4187f05af07ed92b9618962691cc53e6be1d49c2
okharatov/Python_lessons_basic
/lesson02/home_work/hw02_normal.py
5,248
3.8125
4
# Задача-1: # Дан список, заполненный произвольными целыми числами, получите новый список, # элементами которого будут квадратные корни элементов исходного списка, # но только если результаты извлечения корня не имеют десятичной части и # если такой корень вообще можно извлечь # Пример: Дано: [2, -5, 8, 9, -25, 25, 4] ...
e8dd4de32faab93616736cc6eb84dd074b6574e5
gwq888/learn_scrapy
/gui/测试:文本框.py
656
3.640625
4
import tkinter def sayHello(): pass main = tkinter.Tk() # 按钮 myButton = tkinter.Button(main,text='点击我',width=20,command = sayHello) myButton.pack() ''' main:将文本框给放到窗口中 show:文本框输入内容后,显示什么, 比如show='*',那么在文本框输入完内容后,内容就全部显示*,这样就可以做密码来用的 width:宽度50,height:不可以设置,会报错,因为没有这个height属性 bg:文本框的背景颜色 fg:...
a5984ab073b33c50e4c8149a845c484f51f5b286
NimbleBoxAI/Nimblebox-TCS-Webinar-Week1
/Homework/Homework 3/grader.py
640
3.65625
4
import requests import pickle import pandas user_id = open('/home/admin_/nimblebox-comput-server/user.txt').read() def grader_1(df): try: file = open('check.pkl', 'rb') data = pickle.load(file) file.close() grade=0 if(df.equals(data)): grade=100 data = {...
333eb5c9dbe87203134dd79acb8cb9380c2d7bfa
jainsiddharth99/Basic-Coding-Problems
/mergestring2.py
233
3.5625
4
ar1=[-5,3,6,12,15] ar2=[-12,-10,-6,-3,4] n=len(ar1)+len(ar2) ar1.extend(ar2) ar1.sort() if n%2==0: median=ar1[int(n/2)]+ar1[int((n/2)+1)] print (median) else: median=ar1[int(n/2)] print (median)
6f0c7affdd87750d4b996b795c3c747707261793
jainsiddharth99/Basic-Coding-Problems
/remove3rdno.py
544
3.96875
4
def remove(list): #index postions # 1 2 3 4 5 6 7 8 9 # 0 1 2 3 4 5 6 7 8 pos=2 # to remove index=0 # current length=len(list) # till at least one element is left while length>0: # 0 = (2+0)%9=2......1st iteration # 2 = (2+2)%8=4......2nd iteration # so...
88db8bcb7afbed7736a6d2431dc46013a956a77c
jainsiddharth99/Basic-Coding-Problems
/factorial.py
270
4.03125
4
def factorial(n): if n==1: return n else: return n*factorial(n-1) num=int(input('factorial of: ')) if num<0: print ('incorrect input') elif num==0: print ('factorial of', num ,'is 1') else: print(factorial(num))
6c6de9b83348d93610b6500ecb87c1407b727dde
jainsiddharth99/Basic-Coding-Problems
/linear_search.py
194
3.875
4
numbers_list=[1,2,3,4,6,9,11] number_to_find=9 for index, element in enumerate(numbers_list): if element == number_to_find: print(index)
3c1092ef16c862560a5a1eadd1b821dc33872f8a
masteryolo24/lit_training
/bt1/algorithm_2.py
350
3.828125
4
count = -1 def equal(x, y): global count count +=1 for i in range(0, 1): if x == y: break else: if x * 2 < y: x *=2 equal(x, y) elif x * 2 == y: x *=2 equal(x, y) elif x * 2 -1 == y: x = x * 2 - 1 count +=1 equal(x, y) else: x -=1 equal(x, y) equal(2, 11) prin...
1c2b00b03eaca7479280bdc25ebc26f56739e7a1
Joe-Nash/hypatia
/hypatia/physics.py
1,224
4.0625
4
"""Physical attributes of things. """ import pygame class Velocity(object): """Eight-directional velocity.""" def __init__(self, speed, up=0, up_right=0, up_left=0, left=0, right=0, down=0, down_right=0, down_left=0): self.speed = speed s...
510c8fb39775e157617535aa8f6c3509a5832ecf
AnliYang/HB_Ex_20160119_flask_intro
/nice.py
3,252
3.578125
4
from random import choice from flask import Flask, request # "__name__" is a special Python variable for the name of the current module # Flask wants to know this to know what any imported things are relative to. app = Flask(__name__) AWESOMENESS = [ 'awesome', 'terrific', 'fantastic', 'neato', 'fantabulous', '...
62e68908d10d9d5361626149398ff1c34b9b299e
SergeShumilov/Diffie-Hellman
/Deffi-Hellman.py
1,317
4
4
"""This is simple script for Diffie-Hellman's protocol""" import random def isPrime(n): """check if the number is prime""" if n % 2 == 0: return n == 2 d = 3 while d * d <= n and n % d != 0: d += 2 return d * d > n def number_generation(): """These numbers are not kept in se...
167e10cce15a0230c46d2aa7fcd0425692d1a20e
RamonBomfim/decida-por-mim
/decida-por-mim-main/main.py
1,702
3.96875
4
from time import sleep import random class DecidaPorMim(): def __init__(self): self.respostas = [ 'Não faço ideia.', 'Só sei que nada sei.', 'Tá maluco?', 'Com certeza... não.', 'É claro que sim.', 'Tá pegando fogo bicho!!!', ...
a7a34aad0081a8c8221380904f31f86db256cca1
algobot76/lintcode-python
/lintcode/596_minimum_subtree/solution1.py
894
3.75
4
""" Definition of TreeNode: class TreeNode: def __init__(self, val): self.val = val self.left, self.right = None, None """ import sys class Solution: """ @param root: the root of binary tree @return: the root of the minimum subtree """ def findSubtree(self, root): _, s...
56a99d737a1ae86f6b31a180c5bc9a319bf06461
Alenshuailiu/Python-Study
/first.py
202
4.1875
4
num=input('Enter a number ') print('The number you entered is ',num) num=int(num) if num > 10: print('you enter a number > 10') elif num > 5: print('you enter a number >5 <10') else: print('Others')
4a1af3186741b12b6e167fe12d1546dbc3cafdf2
AP-MI-2021/lab-1-Rubben23
/main.py
869
3.609375
4
''' Returneaza true daca n este prim si false daca nu. ''' def is_prime(n): # codul vostru aici if n < 2: return False for i in range (2 , n//2+1 ): if n % i == 0: return False return True ''' Returneaza produsul numerelor din lista lst. ''' def get_product(lst): # codul vostru aici ...
99172b472e16be402826cbd617a36adc189251ca
sipeckatarina/Project-Euler
/34_Digit_factorials.py
372
3.734375
4
def fakulteta(x): a = 1 for i in range(1, x + 1): a *= i return a def is_sum_fifth_power_digits(x): num_str = str(x) s = 0 for i in range(len(num_str)): s += fakulteta(int(num_str[i])) if s == x: return True return False l = [a for a in range(3, 1000000) if...
bbbf423915c8e0eda4802c2ef7bb1f2c91481c0a
cicorias/new-algorthim-work
/py/BstWalkOne.py
565
4.09375
4
def print_bst_level(root): """Prints the tree in level order.""" if root is None: return print_bst_level(root.left) print(root.data, end=' ') print_bst_level(root.right) def print_levels_bst(root): """Prints the tree in level order.""" if root is None: return q = [] ...
2af6246b724eaaecdc7030edd82f5199e56ebcab
RoundTower-io/python_class
/test_driven_lab/lab05_pexpect_dos_calculator_code.py
717
3.578125
4
# # A PExpect example that uses DOS to multiply 2 numbers. # 1 - Pexpect spawns a DOS shell # 2 - It waits for the DOS prompt ending in '>' # 3 - It then sends 'set /a <number1>*<number2>' to DOS # 4 - It looks for a response that is a single number # 5 - We read the output line, strip off whitespace, and con...
2629993019765a1539f0b4bc08574a7f81444ae6
RoundTower-io/python_class
/example_code/datatypes.py
186
3.734375
4
letters = ['a', 'b', 'c'] print(letters[1]) # b letters.extend(['d', 'e', 'f']) print(letters[4]) # e greek = {'a': 'alpha', 'o': 'omega', 'g': 'gamma'} print(greek['o']) # omega
c4291aaa613bb38dd6fae10eddc80d3978eb0164
RoundTower-io/python_class
/example_code/whileloops.py
213
3.984375
4
var = 10 while var > 0: print ('Current variable value: %d' % var) var = var - 1 while True: number = input('Enter a number: ') if number == 0: break print('You entered: %d' % number)
0501089bafc9bc2a488e9c4cf2e0689e26db6ff7
jenyton/Sample-Project
/operators.py
551
4.34375
4
##Checking the enumerate function print "##Checking the enumerate function##" word="abcde" for item in enumerate(word): print item for item in enumerate(word,10): print item mylist=["apple","mango","pineapple"] print list(enumerate(mylist)) ##Checking the Zip function print "##Checking the Zip function##" name = [...
28eff2e8d9bd7c53c19fcfd778eefc046c0e96e4
annahedstroem/mapreduce_python
/reducer.py
3,222
3.71875
4
#!/usr/bin/python import sys def aggregation(list): # Sort the list in case of tie, we use the first in lexicographical order. list.sort()gi # Retrieve the city which held the most number of matches for each country. max_key_city, max_count_city = max(list, key=lambda x:x[2])[1:] # Empty list fo...
bd66f90e6ae41c24f865d082b50156232d2770db
sattyamtripathi/backup
/bill.py
654
4.09375
4
#! /usr/bin/python3 print ("##" * 20) print (" RECEIPT ") print ("##" * 20) roti_price=10 rice_price=50 curry_price=80 roti_quantity=int(input("Enter the quantity of Roti:")) rice_quantity=int(input("Enter the quantity of Rice:")) curry_quantity=int(input("Enter the quantity of curry:")) roti_amount= roti_price ...
8a049e86c1ce9c1f9001279d288a0a6a5bda311d
trinitycompany/ajeeshwal
/add2.py
204
3.78125
4
def add2(n1, n2): s = n1 + n2 return s print add2(3, 4) def add3(n1, n2, n3): s = n1 + n2 + n3 return s print add2(3, 4, 5) def add3(n1, n2, n3, n4): s = n1 + n2 + n3 +n4 return s print add2(3, 4, 5, 6)
9cbd943934eb2662d71031354b06e7549fdc0577
dlydb/Cracking_Interview
/3_2.py
779
3.734375
4
from NodeWithMin import * class Stack(object): def __init__(self, head = None): self.head = head def pop(self): if self.head != None: cur = self.head self.head = cur.get_next() def push(self, data): cur = NodeWithMin(data) cur.set_next(self.head) ...
2e67bd03e5290911a68a824d9a73528745ac76f3
SanderKit/SanderKulma
/Ülesanne04SK.py
2,906
3.546875
4
#Sander Kulma IT20 #25.11.2020 #Ülesanne04 print("*******MMPANK*******") konto = 10000 aeg = 5 intress = 0.05 alg = konto print("Aasta \t Algsumma \t Intress \t Aasta lõpuks") for i in range(aeg): algsumma = konto konto = konto+konto*intress print(f"{i+1} \t {algsumma: .2f} \t {algsumma*intr...
09f4e7fa3fff116668ba2953f5af08c266ecdf62
Pablo1012/LeitorProjct
/ManipulacaoString.py
1,685
3.765625
4
''' References: Manipular string: https://wiki.python.org.br/ManipulandoStringsComPython Manipular arquivo: https://panda.ime.usp.br/pensepy/static/pensepy/10-Arquivos/files.html ''' import os def cls(): os.system('cls') def abrir_a(): input_file=raw_input("Digite o caminho do arquivo: ") ar...
4c29fed9ec8dc023b7ae3319d309d553fd6376ad
salamwaddah/nd004-1mac
/Strings & Lists/password.py
488
3.53125
4
def good_length(s): return len(s) > 7 and len(s) < 65 # This should print False, because it's under eight characters. print(good_length("2short")) # This should print True, since it's between eight and 64 characters long: print(good_length("nice password, yo")) # This should print False, since it's over 64 chara...
06d3d8d79590a6a8ebcced86bb114bd2cf4778b7
salamwaddah/nd004-1mac
/Functions/Part One/11b_stairs.py
263
4
4
# Write code to draw the staircase # pattern above. The modulo operation # might be useful! import turtle t = turtle.Turtle() t.width(5) t.color("green") for n in range(7): t.forward(30) if n % 2 == 0: t.left(90) else: t.right(90)
2dc2047d4eeec2e5e562b33ee2204e1d93a2def0
AMOviedo15/Homework3
/Zylabs10-17.py
1,176
4.03125
4
# Aaron Oviedo 1990958 class ItemToPurchase: def __init__(self): self.item_name = "none" self.item_price = 0 self.item_quantity = 0 def print_item_cost(self): print(self.item_name + " " + str(self.item_quantity) + " @ $" + str(self.item_price) + " = $" + str(self....
19d9287f06d132b047c26b8387df3d312098fa9d
sofiasolomon0914/Integration
/Schedule Planner.py
4,525
4.1875
4
# Sofia Solomon # This program will help people use their free time more effectively by asking what they have done and # what they feel like doing to generate suggestions of what they can do in their free time. print("\nHello! I will ask you some questions to help you figure out what you should be doing right now. \nP...
ce4b0dc728962d144973298bf3271056da236771
BerkanBR/Sudoku
/checkColumnas.py
1,425
3.671875
4
def checkColumnas(sudoku): numeroDeFilas = len(sudoku) indexFilaActual = 0 for fila in sudoku: for numero in fila: indexFilaSiguiente = indexFilaActual + 1 while indexFilaSiguiente < numeroDeFilas: try: posicionNumeroFilaSiguiente = s...
b38ac7f2a180d8a10135f2fb992bcaa6e049d45c
wustone1995/SI507-FINAL
/basic_functions.py
2,416
3.59375
4
import json import os def cache_read(): ''' Function that reads the cache file Parameters ---------- None Returns ------- cache: dict The cache file. ''' cache_file = 'cache.json' if os.path.exists(cache_file): with open(cache_file, 'r') as f: cache...
877455a09ffc6a48e8909b0b9f6f38fc1b5daf18
catwe/learnning
/对象属性与类属性/对象属性与类属性.py
728
3.828125
4
class Person(object): name = '这是类属性' def __init__(self, name): # pass #这是对象属性 self.name = name #调用 per = Person('tom') #调用对象属性,对象属性优先级高于类属性,当属性名相同时,对象属性作用优先 print(per.name) #调用类属性 print(Person.name) #动态的添加属性,但是只作用于本对象,例如添加一个per2对象时,动态添加的属性不会作用 per.age = 21 print(per.age) # per2 = Person('wc') #调用age属性就会报错 #...
cbb1a199c058a18b82b39d3ff2e2e9b13380fdaa
scimaksim/Python
/words.py
277
4.03125
4
def longest(*args): longest_word_length = 0 longest_word = '' for arg in args: if len(arg) > longest_word_length: longest_word = arg if longest_word: return longest_word else: return None longest('hi', 'hello', 'python')
6b3304cba582263037d6537d4238dc98a4a87a95
scimaksim/Python
/spam.py
2,836
4.03125
4
# ----------------------------------------------------------------------------- # Name: spam # Purpose: Compute a 'spam indicator' for a phrase # # Author: Maksim Nikiforov # Date: 10/22/2016 # ----------------------------------------------------------------------------- """ This program classifi...
be816514611c8d61ad89075366c6c78ad478cc40
aldogutierrez/Sorting_Algorithms
/Python/MergeSort.py
914
4.03125
4
def mergeSort(array, p, r): if p < r: q = (p + r) // 2 mergeSort(array, p, q) mergeSort(array, q + 1, r) merge(array, p, q, r) def merge(array, p, q, r): n1 = q - p + 1 n2 = r - q leftArray = [0] * (n1 + 1) rightArray = [0] * (n2 + 1) for i in range(0, n1): ...
3351bfce7f290ff9a6d9492b21e694ce36102c1b
frankj-rpi/CoffeeAgent
/price_identify.py
1,681
3.8125
4
""" Code chunk that will take input and determine if there is a price present in it follows a rule of the price being followed by the currency or preceded by $ """ def priceIdentify(sentence): currencies = ['dollar', 'yuan', 'kuai', 'RMB'] curr = 'None' price = -1 for i in currencies: ...
94f5ada9311273132d98c602e20da831ef4c0f44
blueocean1/AB-Tasks
/hw_1.py
1,330
3.890625
4
str1 = "The Zen of Python, by Tim Peters" print(str1) dzen = "Beautiful is better than ugly.\nExplicit is better than implicit.\nSimple is better than complex." \ "\nComplex is better than complicated.\nFlat is better than nested.\nSparse is better than dense." \ "\nReadability counts.\nSpecial cases aren...
08910701fbbb3bdcdd885d261e704b5eab67af2c
geekchick/machinelearning-regression
/simple_linear_regression_NBA.py
1,287
3.859375
4
# Simple Linear Regression # Import Libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd # Import dataset dataset = pd.read_csv('NBA.csv') X = dataset.iloc[:, 1].values y = dataset.iloc[:, :-1].values print(X.shape) print(y.shape) # Splitting the dataset into Train and Test from sklearn.c...
915927d8c4cbf8a7e3637850d3b9d87b98be6c29
mithrandil444/Make1.2.3
/song.py
2,076
4.28125
4
#!/usr/bin/env python """ This is a Python script that will display the lyrics of a song """ # IMPORTS __author__ = "Sven De Visscher" __email__ = "sven.devisscher@student.kdg.be" __status__ = "Finished" # CONFIGURING I/O def main(): class Song: # Define class Song def __init_...
1b7c27d06ea330117048a22a8f335656915435ea
Sampatankar/BasicPythonTutorials
/Ch10.py
6,964
4.71875
5
# Chapter 10: Operations Involving Dictionaries: # In Python, a dictionary is a collection of well-arranged pieces of information. You may create a dictionary in order to collate and store in one place, all the information relating to a particular person or subject: # #Example 1: Building a Basic Dictionary: im...
8bcea73e89c4516a2b873f23772982557ba0fe9d
Sampatankar/BasicPythonTutorials
/Ch13.py
3,096
4.90625
5
# Chapter 13 - Operations Using Defined Functions: # Example 1: def welcome_user(): """Write a short welcome message.""" print("Welcome, buddy!") welcome_user() # Example 2: def welcome_user(username): """Write a short welcome message.""" print("Welcome, " + username.title() + "!") ...
899efde4f89825dc9c84c1f8d92f88cc33ba904e
AtilioA/algoritmos-teoria-dos-grafos
/labT/connected_graph.py
2,179
3.75
4
class Vertice(object): def __init__(self, rotulo): self.rotulo = rotulo self.visitado = False class Grafo(object): def __init__(self): self.vertices = set() self.vertice_mark = [] self.arestas = set() def adicionar_vertice(self, vertice): self.vertices.add(v...
581c03fe0968dd689cdc9f5c259906ed9b2f39a5
asadrahman3697/capitals_quiz
/capitalquiz.py
1,859
3.84375
4
#!/bin/env python # randomQuizGenerator.py - creats quizzes with questions and answers import random import re from Capitals import Capitals def get_valid_response(input_text, validate_list): check_response = [] while not check_response: response = input(input_text).upper() if response == 'Q': return None ...
3da216050ff4d76013231ef9477a1ddddae9f853
TardC/books
/Python编程:从入门到实践/code/chapter-11/test_employee.py
673
3.609375
4
import unittest from employee import Employee class EmployeeTestCase(unittest.TestCase): """Test Employee.py""" def setUp(self): """Create a Employee object.""" self.my_employee = Employee('tard', 'c', 150000) def test_give_default_raise(self): """Test the default arg...
7c15e7da522f8da6d4c2ad3542f0d8df2e9b06fe
TardC/books
/Python编程:从入门到实践/code/chapter-6/cities.py
867
3.921875
4
cities = { 'beijing': { 'country': 'china', 'population': 100, 'fact': 'politics, economy, culture center', }, 'shanghai': { 'country': 'china', 'population': 90, 'fact': 'economy, culture center' }, 'hangzhou': { 'count...
86d8c9b80943d5e739da6b5f9792250657a8616e
TardC/books
/Python编程:从入门到实践/code/chapter-5/favorite_fruits.py
429
4.0625
4
favorite_fruits = ['apple', 'banana', 'watermelon'] if 'apple' in favorite_fruits: print("You really like apples!") if 'banana' in favorite_fruits: print("You really like bananas!") if 'watermelon' in favorite_fruits: print("You really like watermelons!") if 'orange' in favorite_fruits: print(...
9714b90a7aa37ffb8b7bcfb8f747d27221d05612
TardC/books
/Python编程:从入门到实践/code/chapter-8/magicians.py
538
3.953125
4
def make_great(magicians): """Add 'the Great' to the name of all magicians.""" index = 0 while index < len(magicians): magicians[index] = 'the Great ' + magicians[index] index += 1 return magicians def show_magicians(magicians): """Show the name of all magicians in list mag...
22f541beb554065ec4ed505f4c8272c543ba5836
TardC/books
/Python编程:从入门到实践/code/chapter-5/conditional_tests.py
2,281
3.734375
4
car = 'subaru' print("Is car == 'subaru'? I predict True.") print(car == 'subaru') print("\nIs car == 'audi'? I predict False.") print(car == 'audi') fruit = 'apple' print("\nIs fruit == 'apple'? I predict True." ) print(fruit == 'apple') print("\nIs fruit == 'banana'? I predict False.") print(fruit == '...
7bb70913cdf52e393eb1923409135b9723d5aa87
TardC/books
/Python编程:从入门到实践/code/chapter-8/shirts.py
247
3.6875
4
def make_shirt(shirt_size='L', printed_words='I love Python'): print("T-shirt's size is " + shirt_size + " and it's printed words is " + printed_words + ".") make_shirt() make_shirt('M') make_shirt(printed_words="Hello World")