blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
34fb214e5915af00e86ededf88c9f127a2c149e1
jayudhandha/python-exercise-m1-batch
/FunctionsExample.py
1,202
3.734375
4
# Functions # listA = [1,2,2,2,2,2,2,3,3,4,5,6] # print(set(listA)) # Function defination # Function body/suite # Function call # def greetings(): # print("Welcome to Vadodara..!!") # for i in range(5): # greetings() # def sum(a,b): # # print(a+b) # return a+b # c = sum(5,10) # print(c) ########### Types ...
8f4fe350b41d11e1711e976e11d4978d6e350f40
benkeanna/pyladies
/06/hangmen/hangmen.py
1,824
3.8125
4
import random import hangmen_men words = ['vločka','sníh','kopec'] word = random.choice(words) # vyber slova pro hru string = '-' * len(word) print(string) # vypsani prvniho prazdneho pole mistakes = 0 def hangmen_choice(mistakes): # funkce vrati obrazek obesence podle poctu chyb index = mistakes - 1 return...
02ef01b04e02c73a8198937da17b8694b42734d5
shkennedy/TicTacToe
/single/GameBoard.py
1,652
3.921875
4
class GameBoard: def __init__(self): self.board = [['.' for x in range(3)] for y in range(3)] # Attempt to place piece at position x, y def place(self, piece, x, y): if (self.board[x][y] != '.'): raise Exception('Position already used') self.board[x][y] = piece ...
f8554490eff7704815fba1a8877bb043ee9edbce
cwza/leetcode
/python/316-Remove Duplicate Letters.py
806
3.6875
4
from collections import deque ''' https://leetcode.com/problems/remove-duplicate-letters/discuss/889477/Python-O(n)-greedy-with-stack-explained ''' class Solution: def removeDuplicateLetters(self, s: str) -> str: "Greedy, Time: O(n), Space: O(n)" last_occur = {ch:i for i, ch in enumerate(s)} ...
7a06d394a2fa25daaad6ad1bbbe8e00663cc1b14
sarahlecam/Honeypot
/Functions/sarah.py
1,101
3.625
4
import string import random passChars = [] length = 0 nDigits = 0 nLetters = 0 nSpecial = 0 def syntax(p): global passChars, length, nDigits, nLetters, nSpecial passChars = list(p) # print (passChars) length = len(passChars) # print (length) for i in range(length): # print (i) if (passChars[i] in string.asc...
5f889a016908ee3f3420aa381e9458c9f598ab50
orel1108/hackerrank
/practice/python/regex_and_parsing/intro_to_regex_module.py
163
3.703125
4
#!/usr/bin/env python import re t = int(raw_input().strip()) for _ in range(t): f = raw_input().strip() print bool(re.match(r"[+-]?(\d*)[.](\d+)$", f))
0acf05599180d61929b344c310d0a03839703f13
Levalife/DSA
/tree/BalancedBinaryTree.py
1,391
4.125
4
# -*- coding: utf-8 -*- ''' Property of Balanced Binary Tree: absolute value (abs) of difference of left subtree and right subtree must be lower or equal to 1. Height of leaf is -1 Overall tree mite look as balanced (height left - height right <= 1) but if one of subtrees is unbalanced all tree is unbalanced Height ...
bc5161b01dc34eed708a30738986441e7140bb30
cravo123/LeetCode
/Algorithms/1110 Delete Nodes And Return Forest.py
1,837
4.03125
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None # Solution 1, recursion, # kinda like post-order traversal in a sense that # we deal with left and right children first, and then parent node class Solution...
952686f6c78493144aaaccf021738bf1f5725d89
saridha11/python
/fact.py
133
3.890625
4
def main(): n=5 fact=1 for i in range(1,6): fact=fact*i print("the fact is:") print(fact) main()
4b8200ee227a30b0e19648ba59b208046f880980
profepato/clases_estructura_2018
/repaso/main.py
5,886
3.859375
4
""" lista_jugadores = list() jug = dict() dorsal dor nombre nom país pai posición pos """ lista_jugadores = list() def cargar_jugadores(): j1 = dict() j2 = dict() j3 = dict(); j4 = dict(); j1["dor"] = 10 j1["nom"] = "Messi" j1["pai"] = "Argentina" j1["pos"] = "d"...
df8eb39b3933b9b0ed743a2ef9db34bacb6bf8bc
cbabalis/Elita
/node/message.py
2,453
3.875
4
#!/usr/bin/env python # -*-coding: utf-8-*- import pdb class Message: """ Represents a message. A message should contain: (a) the content to be sent (b) the sender (c) the recipient (d) the size of message, in bytes. """ def __init__(self, sender='', recipient='', co...
b28ece32ca47fb9c1966ef45470dd0d8176de64d
savadev/interviewbit
/Backtracking/kth-permutation-sequence.py
1,271
4.1875
4
''' The set [1,2,3,…,n] contains a total of n! unique permutations. By listing and labeling all of the permutations in order, We get the following sequence (ie, for n = 3 ) : 1. "123" 2. "132" 3. "213" 4. "231" 5. "312" 6. "321" Given n and k, return the kth permutation sequence. For example, given n = 3, k = 4, ans...
c86f24887a2e9ecd685a922933fb111731212fd3
MrSandstrom/LearnPyton
/lesson3/test1.py
1,038
4.375
4
#!/usr/bin/env python3 def swap_characters(name, password): first_name_char = name[0] last_name_char = name[len(name)-1] first_password_char = password[0] last_password_char = password[len(password)-1] # char array, replace char values modified_name = list(name) modified_name[0] =...
71cfa9edcb6400ce8be1356c0fb6075fff03c1e1
Nitin-Diwakar/100-days-of-code
/day30/problem_solving1.py
689
4.0625
4
date=input("Enter the date: ") dd,mm,yy=date.split('/') dd=int(dd) mm=int(mm) yy=int(yy) if(mm==1 or mm==3 or mm==5 or mm==7 or mm==8 or mm==10 or mm==12): max1=31 elif(mm==4 or mm==6 or mm==9 or mm==11): max1=30 elif(yy%4==0 and yy%100!=0 or yy%400==0): max1=29 else: max1=28 if(mm<1 or mm>...
0049b82fe4643b6b5f0a98d8714be4585ebd138f
Jaeker0512/gocrack-algorithm
/滑动窗口/76.最小覆盖子串.py
3,122
3.578125
4
# # @lc app=leetcode.cn id=76 lang=python3 # # [76] 最小覆盖子串 # # https://leetcode-cn.com/problems/minimum-window-substring/description/ # # algorithms # Hard (40.26%) # Likes: 925 # Dislikes: 0 # Total Accepted: 104.3K # Total Submissions: 258.3K # Testcase Example: '"ADOBECODEBANC"\n"ABC"' # # 给你一个字符串 s 、一个字符串 t ...
031ac91b1c24248effd6034725896722ff97c06f
czx94/Algorithms-Collection
/Python/LeetCode/199.py
821
3.671875
4
# Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def rightSideView(self, root): """ :type root: TreeNode :rtype: List[int] """ if not root: ...
80f5300a807cb605500f405a1299c8d8c178e167
Gambrinius/Python_Course
/week6/sort_students.py
390
3.5
4
input_file = open('input.txt', 'r', encoding='utf-8') student_list = [] for line in input_file: surname, name, school, score = line.split() student_list.append([surname, name, score]) student_list.sort(key=lambda s: s[0]) input_file.close() with open('output.txt', 'w', encoding='utf-8') as output_file: f...
d1ac7fe1d58e233a84e8d338ca109bdf649d3a83
dougaoyang/struct_code
/queue/array_queue.py
1,413
3.8125
4
class ArrayQueue: def __init__(self, max_length): self.arr = [] self.max_length = max_length for _ in range(max_length): self.arr.append(None) self.head = 0 self.tail = 0 def enqueue_old(self, item): """"该方法会让数组即使有空间也无法加入元素""" if self.tail =...
e27e565275ba447a8541bb96f423f66bcd3b64a8
dooking/CodingTest
/Algorithm/정렬.py
1,430
4
4
def insert_sort(A): for i in range(1,len(A)): for j in range(i,0,-1): if A[j - 1] > A[j]: A[j - 1], A[j] = A[j], A[j - 1] def select_sort(A): for i in range(len(A)-1): min_index=i for j in range(i+1,len(A)): if(A[i]>A[j]): min_inde...
37bfa7c222df103c8b6830595480c97e52da946a
VirusPC/learnTensorflow
/Basis/constant_add.py
899
3.5625
4
import tensorflow as tf import matplotlib as plt # 数据集可视化 import numpy as np # 低级数字Python库 import pandas as pd # 较高级别的数字Python库 # TensorFlow 提供了一个默认图。不过,我们建议您明确创建自己的 Graph,以便跟踪状态 # Create a graph g = tf.Graph() # Establish the graph as the "default" graph with g.as_default(): x = tf.constant(8, name="x_cons...
3092778611d8aa2dda6794f1046af41e5022e592
Garth-brick/Othello
/othello_board.py
1,617
3.953125
4
# this file has one function which flips all the pieces that need to be flipped after every turn and returns the new board # if check=True, then it returns a boolean value denoting whether a move results in any flips def flippy(board, row_change, col_change, check=False): from itertools import permutations ...
6d52d3a5f2561425d0669a332779e76db1c32980
papomail/unittest_workshop
/calc.py
425
3.890625
4
def add(a,b): return a + b def substract(a,b): return a - b def multiply(a,b): return a ** b def divide(a,b): if b == 0: raise ValueError('Cannot divide by 0') return a/b def complicated_function(a,b,c,d,e,f): the_value=add( substract(multiply(a,b),divide(d,c)), e ) print(f'...
fab648a2a7f6f459a2a111d55387766bc19fb051
matthew9510/artificial_intelligence
/Assignments/Assignment04/backtrack.py
3,694
3.609375
4
import csp_lib.sudoku as CSP from csp_lib.backtrack_util import (first_unassigned_variable, unordered_domain_values, no_inference) def backtracking_search(csp, select_unassigned_variable=first_unassigned_variable, ...
b33c76432dd3ee4d767e23afe68848c202662cc9
hydrotop/PythonStudy
/test/156.py
223
3.5625
4
import os from os.path import exists, isdir, isfile files=os.listdir() for file in files: if isdir(file): print('DIR: %s' %file) for file in files: if isfile(file): print('FILE: %s'%file)
60e40f419ed8efd1bf40c3d712c16acd72eba60f
ravi4all/ML_WeekEnd_Feb
/03-Functions/02-MoreAboutFunction.py
316
3.875
4
""" def fib(n): a, b = 0, 1 while b < n: print(b) a, b = b, a+b print() fib(2000) """ # Function with return def fib2(x): result = [] a, b = 0, 1 while b < x: result.append(a) a, b = b, a+b return result m = fib2(100) print(m)
1faa44e2351644caab903ff3e084b849375fd5f8
alex-mitrevski/brsu_digital_exam_tools
/exam_user_utilities/generate_student_exam_sheets.py
7,146
3.765625
4
""" @author: Mohammad Wasil @contributors: Mohammad Wasil, Alex Mitrevski @email: mwasil@outlook.co.id Copyright 2019, DigiKlausur project, Bonn-Rhein-Sieg University Generates a PDF file with exam sheets for all students. The PDF file is generated using data from csv_student_list_file, whose header is given as ...
52adfa729368c843b4508c6a4bf72ea5dd4d7297
dannymulligan/Project_Euler.net
/Prob_061/prob_061.py
6,393
3.875
4
#!/usr/bin/python # # Project Euler.net Problem 61 # # Triangle, square, pentagonal, hexagonal, heptagonal, and octagonal # numbers are all figurate (polygonal) numbers and are generated by # the following formulae: # # Triangle P(3,n) = n(n+1)/2 1, 3, 6, 10, 15, ... # Square P(4,n) = n^(2) ...
cda9413cbda28bc5172176bffee4ee4e6d093a98
Courage-GL/FileCode
/Python/month02/day14/exsercise/exercise01.py
705
3.671875
4
""" 创建两个线程 同时执行 一个负责打印 1---52 52个数字 另外一个线程打印A--Z 26个字母 要求 12A34B """ from threading import Thread,Lock lock01 = Lock() lock02 =Lock() def print_number(): # rang(start,end,step) for i in range(1,53,2): lock01.acquire() print(i) print(i+1) lock02.release() def pr...
239bdbec4d799733e1f3bacd13bbc2153b861fb9
msaiganesh/isayorganic
/final.py
2,071
3.84375
4
import pandas as pd import datetime as dt from pandas import ExcelWriter #import data from the datap = pd.read_csv("check.csv") bigdata = datap #applying lamda evaluation bigdata['ORDER_DT'] = bigdata['ORDER_DT'].apply(lambda x: dt.datetime.strptime(x,'%d-%b-%y')) bigdata['DELIVERY_DATE'] = bigdata['DELIVERY_D...
ee70e43ecdd63cea924968d5afe1cce75fcce268
JaeHeee/algorithm
/algo/sort/countingsort.py
245
3.53125
4
count = [0]*5 numbers = [1,3,2,4,3,2,5,3,1,2, 3,4,4,3,5,1,2,3,5,2, 3,1,4,3,5,1,2,1,1,1] for i in range(30): count[numbers[i]-1] += 1 for num, c in enumerate(count): for j in range(c): print(num+1, end=" ")
a5a58384432cb65c0e1e3c412d1495db0b5ba8ca
leakey1905/chordRecog
/tests/testnn.py
1,595
3.71875
4
import sys sys.path.insert(0, "..") import neuralnet as nn import activation as act import numpy as np import matplotlib.pyplot as pl ''' This script tests the implemented neural network as a simple universal function approximator. Tries to learn y(x) = 0.5*sin(x) ''' np.seterr(all='raise') numTrain = 250 def f(x):...
5c097120a0a36473a047b66ba77ef51da118bc84
itsolutionscorp/AutoStyle-Clustering
/assignments/python/wc/src/952.py
413
4.25
4
def word_count(phrase): """ Returns every word in the given `phrase` and the number of times it occurs. :param phrase: String. :return: Dict mapping word to number of occurrences of word. """ words = phrase.split(" ") word_counts = {} for word in words: if word not in word_counts.key...
3a7d817d4dbe507d6863bd5256e39c3d4cbd4e4d
daseulKim/dspy
/ds_algorithm/example/py0215/ex1.py
528
3.765625
4
#-*- coding: utf-8 -*- # 1부터 n까지 연속한 숫자의 제곱의 합 import datetime import example.py0209.sumAtoB as dsSum def squareSum(n): sum= 0 st = datetime.datetime.now() for x in range(n+1): sum += x**2 print "1 계산 끝 ",datetime.datetime.now()-st return sum def squareSum2(n): st = datetime.datetime...
5fd69720f4bce46505ca2e3bf2008db82868cc39
randyharnarinesingh/udemy_11-essential-coding-interview-questions
/rotate.py
1,535
4.03125
4
def view_arrays(field) : for row in field: print(' '.join(list(map(str, row)))) def rotate(given_array,n) : new_array = [ [0 for _ in range(n)] for _ in range(n)] for i in range(n) : for j in range(n) : new_array[j][n-i-1] = given_array[i][j] return new_array def increment...
34b986095407c75c672e1a8f408702b056dbf207
akhandatascience/AI_Programming_-with_Python
/PythonProgramming/LambdaExpressionQuiz.py
2,034
4.21875
4
""" AI and deep learnin with Python Functions Lambda Expressions Created on Sat Aug 28 19:16:23 2021 Created on Sat Aug 28 12:52:52 2021 """ # Problem-1 """ Quiz: Lambda with Map map() is a higher-order built-in function that takes a function and iterable as inputs, and returns an iterator that applies ...
9e1b8cae86fd543d7ea8efecd871886f4ff0f927
andongluis/442_project
/processing/dataset.py
1,564
3.5
4
''' Class for the dataset Can return various parts of the dataset depending on what you need ''' class Dataset: def __init__(self, flags): ''' Initializes flags Potential flags: - "images": True/False - "fc": True/False ''' self.flags = flag...
b15c803a5ace8980a0e64d2cdaa79a730ed0a88a
rhartman93/jQueue
/myQueue.py
996
3.625
4
class myQueue: def __init__(self): self.people = [] def push(self, person): if person not in self.people: self.people.append(person) return 1 else: return 0 def serve(self): if(len(self.people) > 0): return self.people.pop(0) ...
ce89a7e77f42131764dd1dda66acbc90467594f9
maj3r1819/Hackerrank
/Python/grading.py
337
3.53125
4
def gradingStudents(grades): mylist = [] for i in grades: if i >= 38 and i % 5 != 0: rem = i % 5 if rem >= 3: i = 5 - rem + i mylist.append(i) elif rem < 3: mylist.append(i) else: mylist.append(i) ...
a0b32adebd8938f1bf9ca8aa37707a14b23c0e91
ILIFTWM/Demo_Day
/.idea/Demo0707/data structure.py
12,977
3.8125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2019/7/7 21:00 # @Author : WM # @File : data structure.py '''学习内容: 字符串的使用 - 计算长度 / 下标运算 / 切片 / 常用方法 ''' #字符串不能被修改.字符串表达形式:可以使用单引号('……'),双引号("……") ;特殊字符会使用反斜杠来转义 #s[i]索引, # s[i:j]分片,切片的开始总是被包括在结果中,而结束不被包括。这使得 s[:i] + s[i:] 总是等于 s; # 切片的索引有默认值;省略开始索引时默认为0,省略...
6d1d96b6ca22e5cbd0802358a2b90d5e2d289d8a
TommyHuang-dev/shapeDefense
/functions/components.py
3,125
3.609375
4
import pygame from pygame import gfxdraw # various methods for drawing components such as grids and paths on the tower defence game # this method draws a grid!! # border draws a border around the grid, of the same colour as the grid itself # offset offsets the lines drawn in the grid, negative values are recommended...
31473f4af6217b67b5a694311cbe2f794ebaa26d
stalk-calvin/Python-Algorithms
/calvin/data_structure/linkedlist.py
6,764
3.8125
4
class ListNode(object): def __init__(self, value=None, next=None): self.value = value self.next = next def getNodes(self,r): if self is None: return r if self.next: self.next.getNodes(r) r.insert(0,self.value) return r def __repr__(s...
a8412028b030bbe0af587ef504ad7c0c1e682ef2
PBLaycock/python-learning
/basic/1/weight_converter.py
469
4.125
4
user_weight = input("Weight: ") user_weight_unit = input("Lbs or Kg: ") converted_user_weight = "unknown" weight_unit = user_weight_unit.lower() if weight_unit == "lbs": converted_user_weight = round(float(user_weight) / 2.20462262, 2) elif weight_unit == "kg": converted_user_weight = round(float(user_weight...
d9ee626d2a5c04913cdae97cb032ee04742780f2
mohitraj/mohitcs
/Learntek_code/25_Sep_18/sort_merge1.py
556
3.8125
4
list1 = [1,2,3,7,8,13,14,20,30,31] # sorted n list2 = [5,7,9,10,21,24,25] # sorted m #merge it sorted ''' list1.extend(list2) #n+m (10+10) 100 list1.sort() # (n+m) print (list1) ''' len_list1 = len(list1) # 8 , n 8 len_list2 = len(list2) # 7 , m 4 list3 = [] n= 0 m = 0 while n<len_list1 and m <len_l...
e0e44ff09d7d0ae412ed4ecdd9ac4bdb1bbd7e13
danieltoms/Test
/new_algorithms.py
6,360
3.796875
4
import re import random import csv StackArray = [] StackMaximum = 0 StackPointer = 0 def BubbleSort(my_list): for count in range (0, len(my_list)-1): for count2 in range (0, len(my_list)-1): if my_list[count2].get_username() > my_list[count2+1].get_username(): temp = my_list[co...
ff881e7ae49b717651d3904baf71c9def2fd0d59
dmegaffi/challenges
/p8_2.py
2,907
4.3125
4
import sys class Television(object): """ A virtual television """ def __init__(self, model, channel, volume): self.model = model self.channel = channel self.volume = volume print("\n\t\tThe television turns on") print("\t\tYour television is a model " + model + "\n") def countchange(): ...
790fc8c462a80f14ad7da22bd5fd6fc664f8cdf9
bopopescu/Python-13
/Cursos Python/Exercícios Python - Curso em video - Guanabara/Exercício Python #013 - Reajuste Salarial.py
175
3.671875
4
salario = float(input('Digite o salário do funcionário')) com_15 = salario + (salario * 15 / 100) print(f'O salálario do funcionário com 15% de aumento ficará: {com_15}')
9ad1f762c129f9269170f7b435026cfd8a0977e0
indrajeet007/LPTHW-Python
/ex12.py
211
4.09375
4
age = input("How old are you ? ") height = input("How tall are you ? ") weigh = input("How much do you weigh ? ") print("So, you are %r years old, %r centimeters tall and %r kilograms." % (age, height, weigh))
fbf3528238720f2a4a56a5524a27b461251d9195
jburgoon1/python-practice
/35_two_oldest_ages/two_oldest_ages.py
1,053
4.0625
4
def two_oldest_ages(ages): """Return two distinct oldest ages as tuple (second-oldest, oldest).. >>> two_oldest_ages([1, 2, 10, 8]) (8, 10) >>> two_oldest_ages([6, 1, 9, 10, 4]) (9, 10) Even if more than one person has the same oldest age, this should return two *distinct*...
ce4012913e6da6cb73c446fa7f7d63cbfec56bf3
jwbargsten/python-timethese
/src/timethese.py
11,061
4
4
import functools import logging import statistics as stat import time import timeit from more_itertools import quantify __version__ = "0.0.3" def print_time_df(fn): """Decorator to print run time when piping pandas DataFrames In addition to the run time, it also prints the shape of the resulting dataframe....
f4a32086308e4c505bf8a2f2da97c62255c853c6
1505069266/python-
/pythonic和python杂记/None.py
653
3.84375
4
# None 空 # 误区: None不等于字符串 None不等于空的列表 None不等于0 print(None == 0) print(None == {}) print(None == '') print(type(None)) def func(): return None print(None == func()) # True False 对应关系 # 自定义的对象 # 实例默认是True class Test: # 实例是True还是False取决于类的__len__和__bool__方法 __bool__的返回值大于__len__ def __len__(s...
2a126f1bca8efd37517617d95a9b688876ae0b95
choupingru/leetcode
/easy/python/1616.py
929
3.5625
4
def checkPalindrome(input): while input[0] == input[-1]: input = input[1:-1] if not input: return True return False class Solution: def checkPalindromeFormation(self, a: str, b: str) -> bool: sz = len(a) ah, at, bh, bt = 0, sz-1, 0, sz-1 if sz <= 2:re...
6d7d5614d950220507a404e74da52cbdfa82a818
KrishnaRauniyar/Python_assignment
/num1.py
362
4.34375
4
# Write a Python program to count the number of characters (character # frequency) in a string. Sample String : google.com' # Expected Result : {'o': 3, 'g': 2, '.': 1, 'e': 1, 'l': 1, 'm': 1, 'c': 1} str = input("Enter a string: ") dict = {} for i in str: keys = dict.keys() if i in keys: dict[i] += 1...
1d77e0a8ef51773ed65dc245cf50bd7e30bf7ebe
moqidimoc/DATA-MINING
/classification.py
11,185
3.515625
4
# -*- coding: utf-8 -*- """ Created on Sat Feb 6 10:19:37 2021 @author: Asus """ # Here we will import the requested libraries import numpy as np import pandas as pd from prettytable import PrettyTable import matplotlib.pyplot as plt import seaborn as sns from sklearn.preprocessing import OrdinalEncoder...
226ac7f8f3d39051ae7fcb0412b74395ca1a0adb
MUBEENAUQI/Hacktoberfest2021_beginner
/Python3-Learn/anagram.py
331
3.640625
4
s1 = input() s2 = input() l1 = [] l2 = [] for c in s1: if c.isalpha(): l1.append(c.lower()) for c in s2: if c.isalpha(): l2.append(c.lower()) l1.sort() l2.sort() if len(l1)!=len(l2) : print("No") else: for i in range(len(l1)): if l1[i]!=l2[i]: print("No",end='') break else: print("Ye...
50023ddad90430e999e881f53bbbecf2f1f6533f
Cmoen11/IS-105_2016_Gruppe-2-
/uke7_oppgaver/chattebot.py
2,840
3.546875
4
import speech_recognition as sr import pyttsx engine = pyttsx.init() engine.setProperty('rate', 100) voices = engine.getProperty('voices') #engine.setProperty('voice', voices[0].id) r = sr.Recognizer() m = sr.Microphone() def input_voice() : try : with m as source: r.adjust_for_ambient_noise(source)...
6a4f5cb5ad06bdf6711b5820462127766dba65e9
TiffanySantos/LearnPython3theHardWay
/ex15.py
205
3.546875
4
from sys import argv script, filename = argv txt = open(filename) #open the textfile print(f"Here's your file {filename}") print(txt.read()) # call a function called read to the txt file txt.close()
d1fe9c83c119b40edcb40191ea8ae2d71cb65c62
sandraransed/varuprisdatabas.py
/Varuprisdatabas.py
5,116
3.8125
4
#Databas som uppdateras kontinuerligt när man matar in data class Grocery: def __init__(self, name, code, quantity, price): self.name = name self.code = code self.current_quantity = quantity self.starting_quantity = quantity self.price = price def get_name(self): ...
3b9eb3f5ea243edd29ea86c33027517cd26e95cb
RaySmith55/pythonscripts
/dice.py
84
3.765625
4
import random number = random.randint(1, 6) print("The number is: " + str(number))
e6c6978c6d400ccc379253c3d9ec56576afc0e18
nikhilvarshney2/GUVI
/Player/set-5/46.py
80
3.515625
4
import math u = int(input()) print("{0:.1f}".format(math.sin(math.radians(u))))
cb03ba7f7baac1aea25d628c339917de67d34b41
ycherches/KM
/LR2/LR2_3.py
434
3.53125
4
class my_defaultdict: def __init__(self, **kwargs): self.elements = dict(kwargs) def __repr__(self): return str(self.elements) def __getitem__(self, key): return self.elements[key] def __setitem__(self, key, elem): self.elements[key] = elem if __name__ == '__main__': test = my_defaultdict(a = 1, b = 2...
0a90142bbc7d82bb3829e769ae193e35ae3833dc
herojelly/Functional-Programming
/Chapter 3/3.1.py
315
4.09375
4
def main(): import math print("This program calculates the volume and surface area of a sphere.") radius = eval(input("Enter the radius of the sphere: ")) V = (4/3) * (math.pi) * (radius ** 3) A = 4 * (math.pi) * (radius ** 2) print("The volume is", V, "and the surface area is", A) main()
de31c33e8a0989e9d9658c0be76017b23a800360
renanaquinno/python3
/#ATIVIDADES_FABIO/#Atividade_Fábio_01_Introducao/fabio01_18_comprimento_circunferencia.py
195
3.59375
4
#entrada raio = input("Informe a valor do raio da circunferencia: ") #processamento comprimento = 2 * 3,14 * raio #saida print("O comprimento dessa circunferencia é: ",comprimento,)
b3ee0202dfdcb96eea09a51f54ce004fca5dc06f
raghukhanal/Python3
/MainFunction.py
954
4.125
4
def main(): print("Hello World") # Nothing happens with just those two lines of code # Must call the function main to get executed ############################################################## #Declare a variable and initialize it f = 0 # print("f is", f) #re-declaring the variable w...
52b3caf9c7d3fd25252fc2c51f5527de059c81b1
Durkastan/durkabot
/src/extensions/meme/psst.py
614
3.515625
4
psst_txt = """ ┳┻| ┻┳| ┳┻| psst! hey kid! ┻┳| ┳┻| ┻┳| ┳┻| ┻┳| ┳┻| ┻┳| ┳┻| ┻┳| ┳┻| _ ┻┳| •.•) {0} ┳┻|⊂ノ {1} ┻┳| {2} ┳┻| {3} ┻┳| {4} ┳┻| """ def split_txt(txt, num_segments): words = txt.split(' ') step = len(words) // num_segments ls = [] for i in range(num_segments): line =...
00d6e81f80442c29565129246f045ccc295dabb5
GMwang550146647/network
/1.networkProgramming/2.parallelProgramming/PPT_DEMO/4.coroutines/5.协程不轮转问题.py
1,947
3.640625
4
import asyncio from threading import current_thread, Thread import random import time """ 要使用await ,就要用async await 后面接的一定要是asyncio中写好的阻塞方法 """ class AsyncioRun(): def __init__(self): self.p = [] async def func(self, t, ith, task_load): print("Start : Thread {} received task {} -> {}ms".f...
005056754b1b097f33d0bad87340b8461f7802bb
yiranzhimo/Python-Practice
/Day-1_3.py
163
3.703125
4
num=int(input("请输入您的数字:")) dic=dict() if num<=0: print("输入不规范!") for i in range(1,num+1): if i>0: dic[i]=i*i print(dic)
cfb27a50484357367b5a0eee2c8359f29922235a
SREEMT/QuadraticCalculator
/main.py
195
3.65625
4
import cmath a = int(input("a: ")) b = int(input("b: ")) c = int(input("c: ")) d = (b**2) - (4*a*c) sol1 = (-b-cmath.sqrt(d)/(2*a)) sol2 = (-b+cmath.sqrt(d)/(2*a)) print(sol1) print(sol2)
1ca84c9ecd8b24984ad26fe56e9e2df594879532
Lasrix/DoorGame
/Original_Door_Game.py
2,421
3.765625
4
import time delay = 0.5 def win(): time.sleep(delay) print("You win!") def kill(): time.sleep(delay) print("You died!") def Dining(): room_builder([False, True], "The Dining", True, ["Win", "Dining"]) def Bathroom(): room_builder([True, False], "The Bathroom", True, ["Bathr...
224216622163cdacb2841b6ab4bf50e31fc66aa0
iWanjugu/ThePython
/comments_break.py
514
3.875
4
__author__ = 'iWanjugu' # single line comment """ multiple line comment """ #concatenating string and number - use ',' instead of '+' print (9, "Bucky") magicNumber = 26 for n in range (101): #looking through 0 -100 to check ifour magic number is in there if n is magicNumber: print(n, " ...
ff983edef1aa0dcb6e5973057d65e675b9167358
Maroonlk/untitled2
/04.py
469
3.953125
4
class A(object): def __init__(self, name, age): self.__name = name self.age = age def say(self): print("{0}, {1}".format(self.__name, self.age)) bob = A("bob", 22) bob.say() bob._A__name = "ad" print(bob._A__name) #访问私有成员 print(dir(bob)) #访问私有成员 class MyObject(object): def _...
f88ffaa31af887ee84c99a444f24b6f3136b3c28
rohan8594/DS-Algos
/leetcode/medium/Trees/BinTreeToLinkedList.py
1,124
4.3125
4
# Given a binary tree, flatten it to a linked list in-place. # For example, given the following tree: # 1 # / \ # 2 5 # / \ \ # 3 4 6 # The flattened tree should look like: # 1 # \ # 2 # \ # 3 # \ # 4 # \ # 5 # \ # 6 class TreeNode: def _...
a9ca267d3155da029c1cc831458dc77eedd08250
erjan/coding_exercises
/lintcode/print_x.py
502
3.734375
4
''' Enter a positive integer 'N'. You need to return a list of strings as shown in the Example. ''' class Solution: """ @param n: An integer. @return: A string list. """ def print_x(self, n: int) -> List[str]: A = [[''] * n for i in range(n)] for i in range(n): for j i...
3a4fd29f5868c53480bbe2f5fa858c709cddbd7a
kaushal/redditroll
/condescending.py
1,252
3.953125
4
import sys from random import choice def generate_reply(post): """ Runs through the logic of creating a comment to post as a reply to another post. If the post is not worth replying to, an empty string will be returned. Arguments: post - The post that is potentially being replied to. """ #Makes it easier f...
86f54be9d82f6b7bb315f6274f0dab7485cacd7f
edkb/CustomersBackend
/app/models.py
504
3.65625
4
from typing import Optional from pydantic import BaseModel, validator class Customer(BaseModel): id: int name: Optional[str] = None age: Optional[int] = None city: Optional[str] = None @validator('age') def age_must_have_1_to_3_digits(cls, v): digits = len(str(v)) if digit...
41292ce0cafcfafdf02eb65bde130dd8ba9ab8cb
AllieChen02/LeetcodeExercise
/BfsAndDfs/P863AllNodesDistanceKInBinaryTree/AllNodesDistanceKInBinaryTree.py
1,954
3.828125
4
import unittest from collections import deque, defaultdict from typing import List class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def distanceK(self, root: TreeNode, target: TreeNode, K: int) -> List[int]: map = ...
10f10581305634ca8bd365231546b1382f17525a
masterjr86/Python_algorithms
/Lesson_1/task_6.py
554
4.25
4
""" Задача 6. ВПользователь вводит номер буквы в алфавите. Определить, какая это буква. Ссылка на алгоритм: https://drive.google.com/file/d/1kfmj55BP0r2TTdRCvURNO_teIC6VbR4K/view?usp=sharing Допущение: Пользователь вводит номер буквы английского алфавита и знает,что их там 26. """ n = int(input('Введите номер буквы...
86db09305907386815cbc3f5ab816c1ff5e010fc
aman3434/WIPRO-PYTHON-PJP
/TM02/Dictionary/Handon_4.py
135
3.890625
4
dict={1:10, 2:20, 3:30, 4:40, 5:50} for i in dict: print(i) for j in dict: print(dict[i]) for k in dict: print(k,dict[k])
991adadd7c903bde24df656a0e2bebed6555fa43
rusticmystic/demo_sources
/python/kushal.py
1,111
3.65625
4
# This uses urllib2 and dowloads pdf files from a site import urllib2 def check_url_valid(url): try: file_name = url.split("/")[-1] url_valid=urllib2.urlopen(url) except urllib2.HTTPError, e: url_valid = None except urllib2.URLError, e: url_valid = None except httplib.H...
6a1e3617c7e6b4ef433e633341063c1b919edcaf
vokeven/CourseraPythonHSE
/Week5/Количество различных элементов.py
416
3.515625
4
# Дан список, упорядоченный по неубыванию элементов в нем. # Определите, сколько в нем различных элементов. def differenceElem(xList): numX = 1 for i in range(len(xList)-1): if xList[i] != xList[i+1]: numX += 1 return numX xList = list((map(int, input().split()))) print(differenceEle...
d6b4da5c02f84a51a610cefd17c9935c9ddc770c
westjac/AlgorithmOne_CENG325
/AlgorithmOne_JacobBWest.py
4,835
3.90625
4
# Jacob B. West # November 3, 2021 # CENG-325 Algorithm 1 # Dr. Karlsson # See bottom of file for main- all four algorithms will execute their associated examples provided def MultiplicationOne(multiplier, multiplicand): originMultiplier = multiplier originMultiplicand = multiplicand product = 0b00000000 ...
9a12b4dfaffe74918ccc22589e3ede8805e90f3a
MayaGuzunov/AssignementsPythonDTU
/Exercise 5B.py
1,149
4.34375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Oct 6 20:42:43 2021 @author: mayaguzunov """ print("Please input a temperature: ") x = float(input()) print(x) print('Please input the unit of temperature(Celsius,Fahrenhei, or Kelvin)') y=input() print(y) print('Please input the unit to convert to(...
b60f05fdb1afbc7e9cbb454a995315e74cb1758d
joewaldron/ALevel
/filesandfun.py
739
3.828125
4
data = "Hello everyone!\nHow are you?" multi = ["Line 1","Line 2","Line 3"] f1 = open("test2.txt","w") for eachline in multi: f1.writelines(eachline+"\n") f1.close() file = open("test.txt","w") #w or write mode will replace the entire file file.write(data) file.close() file = open("test.txt","a") #a or append mo...
9d1c2179f4b3fe0452d04295b3f8313257fed1b8
Shogun89/Hackerrank
/Python/Strings/swap-case.py
339
4.0625
4
def swap_case(s): def switch_case(s): if s.isupper(): return s.lower() elif s.islower(): return s.upper() else: return s result = ''.join(map(switch_case, s) ) return result if __name__ == '__main__': s = input() result = swap_case(s...
46e4fce4b43aa7280101ab40600d0e29dbb64917
IIC2233-2016-1/syllabus
/Ayudantias/AY10 - Repaso de MidTerm/decorators_example_1.py
796
3.703125
4
def constructor(param1, param2): print('Construimos el decorador') def decorador(funcion): print('Construimos la funcion') def funcion_nueva(*args, **kwargs): print('Comenzamos') print('Usamos los parámetros\n{0} {1}'.format(param1, param2)) funcion(*args, *...
43690de083b86e347d690c575aa4defd0ac22e63
MuhammedAkinci/pythonEgitimi
/python101/08.08.19/untitled0.py
128
3.71875
4
sayı = int(input("sayı giriniz: ")) if sayı < 10 : print("sayı 10dan küçük") else: print("sayı 10dan büyük")
aeb3c456c9b734307a9a69f09e7a3511d9af6074
jberardini/Interview-Cake-Problems
/get_time.py
1,995
4.03125
4
def get_time(flight_length, movie_lengths): """ My first attempt. Note, this doesn't work. I originally wrote the solution without the second part of the if statement, but this gives a false positive if there is one movie that is exactly half the flight length. >>> get_time(60, [30, 30, 15, 60]) Tru...
2c38b781f56162103b29aca439e113e411001fd5
charleycornali/codeeval_challenges
/longest_lines.py
1,241
4.65625
5
# -*- coding: utf-8 -*- """ Write a program which reads a file and prints to stdout the specified number of the longest lines that are sorted based on their length in descending order. INPUT SAMPLE: Your program should accept a path to a file as its first argument. The file contains multiple lines. The first line ind...
df5288485f204691ae87ebf13d4d50c600ae7b25
LukaszMaruszak/Python
/Graph.py
4,379
3.609375
4
class Edge: """Klasa dla krawędzi z wagą.""" def __init__(self, source, target, weight=1): """Konstruktor krawędzi.""" self.source = source self.target = target self.weight = weight def __repr__(self): """Zwraca reprezentację napisową krawędzi.""" i...
423c4bce8a24dab811d171cd25d6d5f974301a44
realyuyangyang/Python3Michigan
/course_2_assessment_3/ac10_9_11.py
313
4.0625
4
# Provided is a string saved to the variable name s1. Create a dictionary named counts that contains each # letter in s1 and the number of times it occurs. s1 = "hello" counts = {} for letter in s1: if letter not in counts: counts[letter] = 0 counts[letter] = counts[letter] + 1 print(counts)
ef3f5ebca3863d248bc170493237756d4167a772
AzUAC-849i/Calculator
/rvfet.py
1,518
4.125
4
print('Enter 1 for Adding, Enter 2 for Substraction , Enter 3 for Multpling and Enter 4 for Dividing.') main_q = input(': ') if main_q == '1': print('Enter Numbers For Adding') given1 = input('Enter 1st Number Here: ') given2 = input('Enter 2nd Number Here: ') try: numb1 = int(given1) numb2 = int(given...
b734dbe2174cfb2b89516328f039dde84e5e9593
guduxuespn/pythonLearn
/demo/function/functionDemo.py
294
3.765625
4
from functools import reduce def square(x): return x * x print(square(5)) # python内建的map函数使用示例 r = map(square, [4, 3, 7, 12, 34, 6]) print(list(r)) # python内建的reduce函数 def fn(x, y): return x * 10 + y reduce(fn, [2, 4]) reduce(fn, [2, 4, 1, 7, 5])
7f06aab9dc56c8d8c2272b657ae71d139decb406
DavidYopp/ELToro
/GIL Limitations/GIL_Example.py
1,078
3.875
4
import time from threading import Thread from multiprocessing import JoinableQueue, Process num = 0 #our countdown method def countdown(num): while num < 100000000: num += 1 #a single process example (normal execution) start_time = time.time() countdown(num) end_time = time.time() delta = end_time - sta...
7746d0ac22bdcee006b0663b8823d5562ce226b6
wqh872081365/leetcode
/Python/199_Binary_Tree_Right_Side_View.py
1,108
4.3125
4
""" Given a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom. Example: Input: [1,2,3,null,5,null,4] Output: [1, 3, 4] Explanation: 1 <--- / \ 2 3 <--- \ \ 5 4 <--- """ # Definition for...
e360c626c7b0f2d371ab0e1d4d4fc61358da7fef
ajvarshneya/fractals-and-curves
/draw_lines.py
2,001
3.84375
4
# # draw_lines.py # # A.J. Varshneya # ajvarshneya@gmail.com # # Functions used to compute pixel lines and draw to canvas. # import math from utilities import * # Implements algorithm based on digital differential analyzer algorithm def dda_line(point1, point2): # List of pixels that will be built line_pixels = []...
df8432317f7f58fa5285117bfce9d9aa4dcff161
HarikaGurram/Python_ICP3
/inheritance.py
2,678
4.0625
4
class Employee: #creating an Employee class emp_count = 0 #creating a variable emp_salaries = [] #creating a list def __init__(self, name, family, salary, department): #creating a _...
7d8137baccab2a791c7e06c17bc3753099f3998f
kevinoyovota/Zuri-Team
/Budget App.py
2,266
3.84375
4
class Budget: def __init__(self, category, balance = 0.00): self.category = category self.balance = balance def deposit(self, amount): self.balance += amount print("You have deposited %.2f Naira in '%s' budget.\n" % (amount, self.category)) return def with...
3d2c80d9ba4c9082abdec474857b606b23ad7893
IvanEvan/leetcode-menu
/450. 删除二叉搜索树中的节点.py
1,875
3.8125
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def deleteNode(self, root: TreeNode, key: int): def get_left_max(sub_root: TreeNode): wh...
1147a042e01e0518f6691e9be89d7acdc7861ed0
nataliaguerreroc/Project-1-PacMan-Search
/search.py
11,310
4.09375
4
""" Integrantes del grupo: Natalia Guerrero Caicedo Alejandro Ayala """ import util class SearchProblem: """ This class outlines the structure of a search problem, but doesn't implement any of the methods (in object-oriented terminology: an abstract class). You do not need to change anything in this...
926e5207e91333d5225217d72282d37f5384b2b8
martinklamrowski/project-blue-jeans
/pyrobo/robo.py
15,032
3.671875
4
import math import time import keyboard import utils.constants as consts import utils.vec as vec class Robo(object): """Class to model the Robo behaviour. :param vel_x: The x-component of the Robo's velocity. :type vel_x: float :param vel_y: The y-component of the Robo's velocity. :type vel_y: ...
26ac65d0e132390834464277e9bb4be68b93c8ba
Connor-Cahill/tweet-generator
/source/histogram.py
801
3.8125
4
import string class Histogram: ''' histogram class holds methods used accross all implementations ''' def __init__(self, file=None): self.tokens = 0 self.types = 0 def create_text(self, file): ''' Takes in file and returns list of lower case, puncaution stripped text ''' with open(file) as wo...