blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
05d683032bc22d9fdd1be54f063458f66dec6468
StartMake111/Programming
/Practice/11/Python/code.py
83
3.53125
4
a = int(input()) st = int(input()) b = a for i in range (st-1): a *= b print(a)
0a5e3546209242d0bbec8e2305fe10ed19a6a890
giach/coding-spells
/Python/minheap.py
2,122
3.71875
4
class MinHeap: def __init__(self): self.arr = [] self.size = 0 def add_node(self, value): self.arr.append(value) idx = len(self.arr) - 1 self.bubble_up(idx) def bubble_up(self, idx): if idx == 0 or idx == 1: return p_idx = int((idx - ...
25d4233e15caef8ec09770c9da6e30f2c409d1ff
giach/coding-spells
/Python/tree.py
1,705
4.03125
4
class Node: def __init__(self, data): self.left = None self.right = None self.data = data def insert(self, data): tmp = Node(data) if self.data > data: if self.left != None: self.left.insert(data) else: self.left = ...
5f628943fb1fcd78564469cc1a14d250521ff35e
lundstrj/counterstrings
/counterstrings.py
473
3.84375
4
import sys def counter_string(target_length = 0, spacer="*"): pointer_length = target_length ret = "" while target_length > len(ret): to_add = str(pointer_length) ret = to_add+spacer+ret pointer_length-=(len(to_add)+1) if pointer_length == 1: ret = spacer+ret ...
35974dac5b1ece53da389ba9443589c753960f0a
alvasenj/GIW
/practica1/ejercicio1_1.py
1,118
3.828125
4
# -*- coding: utf-8 -*- """ Editor de Spyder Este es un archivo temporal """ def desplazamiento(cadena, desplazamiento): cadena = cadena.upper(); cadena2 = ""; for i in range(0,len(cadena)): if ord(cadena[i]) > 64 and ord(cadena[i]) < 91: cadena2 += chr((((ord(cadena[i])-65) ...
b301fa168de60588f8fdebc36d973edd1904a0dc
Midhili2003/Encode-and-Decode
/encode decode.py
338
3.890625
4
import base64 str = input("Enter a string to encode and decode: ") str_enc = str.encode(encoding='utf8') print("The encoded string in utf8 format is : ",str_enc) bs64str_enc = base64.b64encode(str_enc) print("The encoded string in base 64 format is ",bs64str_enc) print("The decoded string is : ",str_enc.decode('...
333e5437666c8f46768e7cd396c624537a139640
brandcm/Archaic_Splicing
/data/introgressed_refs/new_reference/add_variants_to_FASTA.py
2,024
3.546875
4
# Colin M. Brand, University of California San Francisco, 05/25/2022 # This script adds variants to a reference sequence using separate variant and FASTA files per chromosome. import argparse def parse_args(): parser = argparse.ArgumentParser() parser.add_argument( "--variants", type=str, required=True, help...
6e9884551a1f13b51805b0b7a6ade6475ee32089
Moeen-Farshbaf/assignment-2
/dice.py
613
4.1875
4
import random dice_active = True turn_active = True while dice_active: player_says = input("Enter 'roll' to roll the dice:\n"+"if it's a 6 you'll get to roll again.") dice = random.randint(1,6) if player_says == 'roll': print ("Your number is; "+str...
ff65c7a4a32c8f4ccb7da85e677927db98ebcaa6
rudrut/data_analytics-python-exercises-2020
/rudi_rutanen-python_harjoitus-5.py
1,141
3.890625
4
import numpy as np import pandas as pd import seaborn as sns import matplotlib.pyplot as plt import statistics as st n = 10 # Amount of entries in each column. # Initializing arrays with random values in given ranges genderArray = np.random.randint(0, 2, n) heightArray = np.round_(np.random.uniform(140,210,...
9b034331825841b19ff3e4ea54c1b6feb96bfd99
rudrut/data_analytics-python-exercises-2020
/rudi_rutanen-python_harjoitus-3.py
679
3.515625
4
import numpy as np import random as rand # a) tas = np.random.rand() print("A random float number from a uniform distribution 'tas' between 0 and 1: " + str(tas)) # b) tasd = np.full(20, 0) for i in range(tasd.size): tasd[i] = np.random.randint(101,201) print("A NumPy array of 20 random integers fr...
fa0a9ca2932102298b3881ae1abd962c199f6fe9
coatk1/playground
/code/modules/utils.py
831
3.6875
4
from typing import Dict, List, Union def get_leaves(item: Union[Dict, List], key: Dict = None) -> List: """get_leaves. Return all key: values recursively. Parameters ---------- item : Union[Dict, List] The dictionary. key : Dict, optional The key., by default None Return...
8f6aeefcd4748274cceac724906c3f38529f1644
shamsow/django-binge
/helpers.py
2,245
3.78125
4
import os import json import requests url = "https://api.themoviedb.org" api = os.getenv("API") # Fetches the required data from the api when the path url is provided and returns it as JSON def get_items(path): try: location = url + path r = requests.get(location) items = r.jso...
7db13a27e09586b196a448fd52f0bf317caadf17
jagjag/Python-002
/week08/week08-2.py
342
3.65625
4
def square(x): return x * x # map(函数, 序列) def new_map(func, seq): i = 0 m = list(range(len(seq))) for elem in seq: m[i] = func(elem) print(m[i]) i += 1 return m def map_square(elem): return list(elem) if __name__ == '__main__': print(new_map(square, map_square((...
753fb53f90d863edf3473b110bc8f637eb458526
tgkd/test
/1/1_6.py
163
3.609375
4
n = input() i = 1 result = 1 multi = 1 while i <= n: print(i) multi = multi * i+1 + i+2 result = multi + result i += 1 print(multi) print(result)
bd2f829ffe459345acc89d9086dea268e51bbecd
tgkd/test
/2/9.py
136
3.546875
4
B = 0 A = 1 m = int(input()) for k in range(1, m + 1): A = 1 for i in range(1, k + 1): A = i * A B = B + A print(B)
f08f63b42b52e233b278680bd2b5cc30d93742b8
tgkd/test
/2/6.py
402
3.6875
4
# Вводится последовательность чисел и количество максимумов k, которое нужно найти. # Заполнить массив max[k], саму последовательность в массиве не хранить. max_count = int(input()) i = 0 max_list = [] while True: new_numb = int(input()) max_list.append(new_numb)
66f174cdf1317b3b94ce176cbe170eede5e2b6e0
alyssalukpat/homework-11
/02 - Rock and Mineral Clubs.py
3,059
4.03125
4
#!/usr/bin/env python # coding: utf-8 # # Rock and Mineral Clubs # # Scrape all of the rock and mineral clubs listed at https://rocktumbler.com/blog/rock-and-mineral-clubs/ (but don't just cut and paste!) # # Save a CSV called `rock-clubs.csv` with the name of the club, their URL, and the city they're located in. # ...
8168a8a92032979b1d1ee98df44b0744fdde0753
Dixonal45/unit_2
/sphere.py
757
4.125
4
# problem 1 volume_of_sphere = (4 / 3) * (3.14) * (5 ** 3) print("The volume of the sphere is", volume_of_sphere) # problem num_books = 60 book_cost = ((0.6 * 24.95) * num_books) + 3 + (0.75 * num_books - 1) print("The total wholesale cost for the books are", book_cost) # problem is not working running_time = (((2 *...
1156454950615683dbe3d4e5e120479a31629e85
alvintanjianjia/CompetitiveProgrammingScripts
/FooBar/probabilities_old.py
1,981
4.0625
4
# Python implementation of the above approach from typing import List import numpy as np # Function to multiply two matrices A and B def multiply(A: List[List[float]], B: List[List[float]], N: int) -> List[List[float]]: C = [[0 for _ in range(N)] for _ in range(N)] for i in range(N): for ...
d30b45e08f20cc42df1fb32d99c3c7bce4a1e087
lilrob33/The-Tech-Academy-Basic-Python-Projects
/Python_drill.py
2,007
3.734375
4
# # Python: 3.8.1 # # Author: Pedro Suarez # # Purpose: The Tech Academy first Python drill. # For this drill, you will need to write a script that # will check a specific folder on the hard drive, verify whether # those files end with a “.txt” file extension and if they do, # print those qualifying file na...
5551b3b4a4be85c7e18fc49f2fcc80d851c8ac59
rvsmegaraj1996/Megaraj
/experience function.py
379
3.71875
4
def demo(): exp=int(input("tell us experience: ")) skill=input("tell us skill ") if exp>=4 and exp<6 and skill == 'python' or skill=='java': return "promoted as team lead" elif exp>=6 and exp<10 and skill == 'aglie' or skill=='developer': return "promoted as project manager" return "B...
ff1ee432a60ad5e84229a5509c303faa1b15db11
rvsmegaraj1996/Megaraj
/flash sale.py
523
3.84375
4
#flash sale turns=int(input("Tell us how many times you wish open the sales: ")) for one in range(1,turns+1): stock=int(input("tell us stock for the sale: ")) qty=0 for time in range(1,31): required=int(input("tell us how many quantity you want: ")) if required<=stock: stock-=req...
814b07f8885664b213ee74cb749f91bbb7dc0ecc
rvsmegaraj1996/Megaraj
/alp.py
222
3.546875
4
''' ABCDE FGHIJ KLMNO PQRST UVWXY ''' for row in range(1,6): for alp in range(1,6): if alp%2==0: print(A,end=" ");alp+=26 else: print(Z,end=" ");alp+=26 print()
3f2ff6bbb0bffbd88c4b49b9a1f1298e31fa6d92
rvsmegaraj1996/Megaraj
/flody.py
348
3.78125
4
''' ***** **** *** ** * ''' n=5 for row in range(n,0,-1): for col in range(1,row+1): print("#",end=" ") print() ''' 1 2 3 4 5 6 8 10 12 14 15 16 17 19 21 ''' data=1 n=5 for row in range(n,0,-1): for col in range(1,row+1): print(data,end=" ") if row%2==0:data+=2 ...
656514b99cdea789964357aa7953218554958272
Aranatell/UNECON-s-python
/2_sem_files/interval_fun.py
75
3.640625
4
#sum def y(x): return(x**2+3) print(sum(y(a) for a in range(10,31,2)))
e35d34a6304b901dce276c224d3bc916cbf12f19
lachibal2/planetary_model
/main.py
5,172
3.671875
4
from turtle import * from tkinter import * import math import argparse #calls global variable isRunning to continue drawing global isRunning isRunning = True p = argparse.ArgumentParser() p.add_argument('-s', '--show', help="shows variable information", required=False, type=str, default='False') args = p.p...
d5233f24a754536238d9d4a69cd59fdaad2362e6
bedgerotto/curso-python
/aula 2/bloco2/17.py
293
4
4
n1 = float(input('Digite o primeiro número: ')) n2 = float(input('Digite o segundo número: ')) n3 = float(input('Digite o terceiro número: ')) ordenado = sorted([n1, n2, n3]) ordenado.reverse() print('O maior número é: ' + str(ordenado[0]) + ' e o menor número é: ' + str(ordenado[2]))
30db27ecd4d94dd93339882610e9290c1925dc2c
bedgerotto/curso-python
/aula 1/exercicio.py
275
3.59375
4
try: file = open('nomes.txt', 'r') newFile = open('nomeSeparados.txt', 'w') for line in file: newFile.write('|'+'|'.join(list(line.upper()))) except FileNotFoundError: print('Deu ruim.') finally: file.close() newFile.close() print('Sucesso.')
0f6b0e98481433b3f173c715f4e9d6d07d471543
bedgerotto/curso-python
/aula 2/bloco3/20.py
764
4.03125
4
nome = input('Digite seu nome: ') while len(nome) <= 3: nome = input('Digite seu nome: ') idade = int(input('Digite sua idade: ')) while (idade < 0 or idade > 150): idade = int(input('Digite sua idade: ')) salario = float(input('Digite seu salário: ')) while salario <= 0: salario = float(input('Digite seu...
c38a9f12c333ec1489a324554229410fe9143de6
Uttam1982/PythonTutorial
/08-Python-DataTypes/Python-Iteration-Skills /07-Comprehensions-As-Alternatives.py
2,462
4.71875
5
#-------------------------------------------------------------------------------------------- # 7. Consider Comprehensions As Alternatives #-------------------------------------------------------------------------------------------- # If the purpose of the iteration is to create a new list, dictionary, or set object ...
5e6f85683fe741a037dfa9dc018decfa767e8807
Uttam1982/PythonTutorial
/14-Python-Advance/06-python-regex/03-python-RegEx/01-Search-functions/01-python-functions.py
4,805
4.3125
4
# The available regex functions in the Python re module fall into the following three categories: # Searching functions # Substitution functions # Utility functions # The following sections explain these functions in more detail. #---------------------------------------------------------------------------------------...
10e3e31953426da93d4d313c2dae1237fd661bd2
Uttam1982/PythonTutorial
/14-Python-Advance/06-python-regex/01-MetaCharacters/14-Quantifiers/04-greedy.py
3,072
3.734375
4
#-------------------------------------------------------------------------------------------- # *? # +? # ?? #-------------------------------------------------------------------------------------------- # The non-greedy (or lazy) versions of the *, +, and ? quantifiers. # When used alone, the quantifier metacharacter...
a4f817d6dc6e82d13fed495590902bd21548b01c
Uttam1982/PythonTutorial
/03-Python-Function/13-Using-args-and-kwargs-to-call-a-function.py
829
4.46875
4
# Using *args and **kwargs to call a function def myFun(arg1,arg2,arg3): print('arg1: ',arg1) print('arg2: ',arg2) print('arg3: ',arg3) # Now we can use *args or **kwargs to # pass arguments to this function : args = ('welcome','to','python') myFun(*args) print("------------------------------------------------...
5de8cd36072a46cbe61f9a89397cbf010fc66bbb
Uttam1982/PythonTutorial
/11-Python-Object-Oriented-Programming/04-Python-Delete-Object/01-delete-an-object.py
865
4.5625
5
# Delete the Object # We can delete the properties of the object or object itself by using the del keyword. # Any attribute of an object can be deleted anytime, using the del statement. class Employee: # class variables id = 10 name = 'Alex' def display(self): print(f"#Id{self.id} - Name: {self.name}") ...
10c1d9aa90a77da0335a3e4b667c7158d0830f85
Uttam1982/PythonTutorial
/14-Python-Advance/06-python-regex/01-MetaCharacters/02.2-square-brackets.py
4,310
4.53125
5
# [] # Specifies a specific set of characters to match. #------------------------------------------------------------------------------------------ # Characters contained in square brackets ([]) represent a character class # —an enumerated set of characters to match from. A character class metacharacter # sequence wi...
72532e240ae7a73d0937e1f3fd4b2cd17b3fd669
Uttam1982/PythonTutorial
/14-Python-Advance/06-python-regex/01-MetaCharacters/15-Grouping/09-lookahead-assertion.py
3,384
4.0625
4
# Lookahead and Lookbehind Assertions # Lookahead and lookbehind assertions determine the success or failure of # a regex match in Python based on what is just behind (to the left) or ahead # (to the right) of the parser’s current position in the search string. #-----------------------------------------------------...
e9ac4dc8d5179e4aa29b569f9c28f17db89c93f9
Uttam1982/PythonTutorial
/14-Python-Advance/05-python-decorators/02-Decorators-in-python.py
2,202
4.71875
5
#---------------------------------------------------------------------------------------- # Decorators in Python #---------------------------------------------------------------------------------------- # Functions and methods are called callable as they can be called. # In fact, any object which implements the specia...
3c816aacb61b90ae46942c75acc5b17fa73c3445
Uttam1982/PythonTutorial
/14-Python-Advance/06-python-regex/02-Modified-Regular-Expression-Matching-With-Flags/07-re-UNICODE-ASCII-LOCAL.py
1,553
3.640625
4
# re.A # re.ASCII # re.U # re.UNICODE # re.L # re.LOCALE #---------------------------------------------------------------------------------------------- # Specify the character encoding used for parsing of special regex character classes. # re.U and re.UNICODE specify Unicode encoding. # Unicode is the default, so th...
e12910506b89e883a787ec24d884f0141966cf4d
Uttam1982/PythonTutorial
/14-Python-Advance/02-python-Generators/02-Create-Generators.py
1,073
4.59375
5
# A simple generator function def my_gen(): n = 1 print('This is printed first') # The generator function contains yeids statements yield n n += 1 print('This is printed second') yield n n += 1 print('This is printed third') yield n # It returns an object but does not start execution immediatel...
addebdbb1484adacefce4b92501d061efba9776c
Uttam1982/PythonTutorial
/01-Python-Introduction/10-Python-Namespace-Scope/04-python-scopes.py
946
4.625
5
# Example of Scope and Namespace in Python def outer_function(): y = 20 def inner_function(): z = 30 print("z = ",z) inner_function() print("y = ",y) x= 10 outer_function() print("x = ",x) # Here, the variable x is in the global namespace # Variable y is in the local namespace of outer_function()...
879a6bc92d60bd489b15be56fe5584d872602375
Uttam1982/PythonTutorial
/11-Python-Object-Oriented-Programming/01-Python-OOPS/08-OOPs-dir-function.py
419
4.125
4
# dir() function # Now that you have the class declared, you can use the dir() function to list its members: class Animal: pass a = Animal() print(dir(a)) print() o = object() print(dir(o)) #------------------------------------------------------------------------------- class Dog: name ='snoowy' def __init...
f056794c847d47b2d8b4f60654bdf45509b50806
Uttam1982/PythonTutorial
/14-Python-Advance/05-python-decorators/03-Decorators-in-python.py
1,291
4.53125
5
#---------------------------------------------------------------------------------------- # Decorators in Python #---------------------------------------------------------------------------------------- # Basically, a decorator takes in a function, adds some functionality and returns it. def make_pretty(func): def ...
3e0ca21b94671bbe8a73d298ef62702faa526309
Uttam1982/PythonTutorial
/10-Python-Exceptions/08-Try-except-and-finally-block.py
1,715
3.5625
4
#-------------------------------------------------------------------------------- # Try, except, and finally block #-------------------------------------------------------------------------------- # The following code explains how error gets caught in the try block and # gets printed in the except block and then the f...
0024a07868721afbc67530d5502d1aee84be23e7
Uttam1982/PythonTutorial
/05-Build-in-function/04-python-ascii.py
748
4.25
4
#Python ascii() # The ascii() method return a string containing a printable representation of an object # It escape the non ascii characters in the string using \x, \u or \U escapes # ascii() method takes an object like (string, list etc) # *****************************************************************************...
963c21dcb3fda320cc53ce7e08d427b37c2d8aea
Uttam1982/PythonTutorial
/08-Python-DataTypes/Tuples/02-create-one-element-tuple.py
535
4.46875
4
# Creating a tuple with one element is a bit tricky. # 1. Having one element within parentheses is not enough. # 2. We will need a trailing comma to indicate that it is, in fact, a tuple. my_tuple = ("python") print("tuple without trailing comma: ",type(my_tuple)) # <class 'str'> #Creating a tuple having one eleme...
c0cf47a2dfe8f2288b49dee427a566aa6769aefa
Uttam1982/PythonTutorial
/14-Python-Advance/06-python-regex/01-MetaCharacters/13-Special-sequence/09-Anchor-word-boundary.py
2,399
4.1875
4
#---------------------------------------------------------------------------------------------- # \b # Anchors a match to a word boundary. #---------------------------------------------------------------------------------------------- # \b asserts that the regex parser’s current position must be at the beginning or end...
57d108432df93b0a0def7c563f769bbb7bd3659d
Uttam1982/PythonTutorial
/14-Python-Advance/06-python-regex/04-Match-Object/01-Match-Methods/06_match_expand_method.py
1,029
3.71875
4
# match.expand(<template>) #-------------------------------------------------------------------------------------------- # Performs backreference substitutions from a match. # match.expand(<template>) returns the string that results from performing # backreference substitution on <template> exactly as re.sub() would ...
92a7639e5feaf69a3466f10f96229ba995a1c8cf
Uttam1982/PythonTutorial
/08-Python-DataTypes/Tuples/05-slicing-tuple.py
551
4.71875
5
# # Accessing tuple elements using slicing # We can access a range of items in a tuple by using the slicing operator colon :. my_tuple = (12,23,34,45,56,67,78,89,90) #element 2nd to 4th print('element 2nd to 4th: ',my_tuple[2:5]) #elements beginning to 2nd print('elements beginning to 2nd: ',my_tuple[:2]) print('ele...
90d29039130234f66b7db583958d6de7f4d4c7f0
Uttam1982/PythonTutorial
/14-Python-Advance/06-python-regex/01-MetaCharacters/06-Star-symbol.py
543
4.0625
4
#------------------------------------------------------------------------------------- # * - Star #------------------------------------------------------------------------------------- # The star symbol * matches zero or more occurrences of the pattern left to it. #----------------------------------------------------...
3fdb5328ade90d418f256988a406cd3fe031cf56
Uttam1982/PythonTutorial
/11-Python-Object-Oriented-Programming/01-Python-OOPS/05-OOPs-Inheritance.py
794
4.1875
4
# Inheritance # Inheritance is a way of creating a new class for using details of an existing # class without modifying it. The newly formed class is a derived class (or child class). # Similarly, the existing class is a base class (or parent class). #-----------------------------------------------------------------...
92b1a037dde32a3574422f7edb4f06d867855e94
Uttam1982/PythonTutorial
/14-Python-Advance/06-python-regex/01-MetaCharacters/14-Quantifiers/03-question-marks-symbol.py
1,585
3.875
4
#-------------------------------------------------------------------------------------------- # ? #-------------------------------------------------------------------------------------------- # Matches zero or one repetitions of the preceding regex. # Again, this is similar to * and +, but in this case there’s only a...
ba6778cf9bc6091564e0bfa23dcc79c0e6edb9da
Uttam1982/PythonTutorial
/06-Python-Modules/09-python-reloading-module.py
329
3.578125
4
# Reloading a module # Now if our module changed during the course of the program, we would have to reload it # Python provides a more efficient way of doing this. We can use the reload() function # inside the importlib module to reload a module. import importlib import my_module import my_module importlib.reload(m...
1b31566cc4ecd23c8e17866b56c4a8565c9af540
Uttam1982/PythonTutorial
/08-Python-DataTypes/Lists/List-Methods/04-remove-method.py
1,480
4.4375
4
# Python List remove() #************************************************************************************************** # 1. The remove() method removes the first matching element (which is passed as an argument) # from the list. # 2. list.remove(element) # 3. If the element doesn't exist, it throws ValueError: lis...
40c880e0acb9b09fbb0268e570c2c5a13a8dc9b3
Uttam1982/PythonTutorial
/14-Python-Advance/06-python-regex/03-python-RegEx/02-Substitution-functions/02-re-sub-function.py
4,720
3.78125
4
#-------------------------------------------------------------------------------------------- # re.sub(<regex>, <repl>, <string>, count=0, flags=0) #-------------------------------------------------------------------------------------------- # Returns a new string that results from performing replacements on a search ...
2796c87eef274d9c8797c3f6fe0887f1ba21a98b
Uttam1982/PythonTutorial
/03-Python-Function/07-Call-by-reference.py
450
3.796875
4
# Example 1 Passing Immutable Object (String) def change_string(str): str = str + "How are you ?" print("Inside function str = ",str) string1 = "Hi I am there, " change_string(string1) print("outside function str = ",string1) #Example 2 Passing Mutable Object (List) def change_list(lst): lst.append(50) lst...
a436013cb89b8dc34ecbb04c06a97ca8332b447e
Uttam1982/PythonTutorial
/09-Python-FileIO/02-Python-Directory/01-Get-Current-Directory.py
651
3.65625
4
#************************************************************************************** # Get Current Directory #************************************************************************************** # We can get the present working directory using the getcwd() method of the os module. # This method returns the curren...
de334064379a1ff665f269eed3385b4088661044
Uttam1982/PythonTutorial
/08-Python-DataTypes/Lists/02-access-element-list.py
807
4.53125
5
# How to access elements from a list? # 1. We can use the index operator [] to access an item in a list. # 2. In Python, indices start at 0. So, a list having 5 elements will have an index from 0 to 4. # 3. Trying to access indexes other than these will raise an IndexError. # 4. The index must be an integer. # 5. W...
109be0f9eddccd637669e6a720d0579b15ddd47c
Uttam1982/PythonTutorial
/14-Python-Advance/06-python-regex/01-MetaCharacters/02.1-square-brackets.py
1,939
4.25
4
#------------------------------------------------------------------------------------------- # [] - Square brackets #------------------------------------------------------------------------------------------- # Square brackets specifies a set of characters you wish to match. #-------------------------------------------...
0141acea551065b7cb8f6918ea99f710317a54be
Uttam1982/PythonTutorial
/01-Python-Introduction/06-Python-TypeConversion/03-Implicit-type-conversion.py
1,078
4.53125
5
# Type Conversion # The process of converting the value of one data type (integer, string, float, etc.) # to another data type is called type conversion. Python has two types of type conversion. # 1. Implicit Type Conversion # 2. Explicit Type Conversion # 1. Implicit Type Conversion # In Implicit type conversion, ...
00fb9c0fde99c3fa8cbee81d793c7ceb6efc14c6
Uttam1982/PythonTutorial
/10-Python-Exceptions/06-Try-with-Multiple-except-Blocks.py
1,647
4.25
4
#-------------------------------------------------------------------------------- # Try with multiple except blocks #-------------------------------------------------------------------------------- # If multiple errors may arise after the execution of one try block, # we may use multiple except blocks to handle them....
73599494304bd91ef702d23f8f6cb2a6e07d64bd
Uttam1982/PythonTutorial
/11-Python-Object-Oriented-Programming/03-Python-Constructor/02-python-parameterize-constructor.py
374
3.984375
4
# Parameterized Constructor class Employee: """This is an Employee Class""" #Parameterized constructor have two attributes id and name def __init__(self, id, name): self.id = id self.name = name def display(self): print(f"#Id: {self.id}, Name: {self.name}") emp1 = Employee("Sam", 23) emp2 = E...
5b009fafa45e60b69e5b45efe0c17721c755fc88
Uttam1982/PythonTutorial
/08-Python-DataTypes/String-Format/01-basic-formating-string.py
443
3.71875
4
# Example 1: Basic formatting for default, positional and keyword arguments # default arguments print("Hello {}, your balance is {}.".format("Sara", 450.3456)) # positional arguments print("Hello {0}, your balance is {1}.".format("Sara", 450.3456)) # keyword arguments print("Hello {name}, your balance is {blc}.".for...
0bbaad10588d6f2114d3dc6fd445da41e6224fa2
Uttam1982/PythonTutorial
/09-Python-FileIO/02-Python-Directory/06-Removing-Directory-or-File.py
251
3.734375
4
# Removing Directory or File # A file can be removed (deleted) using the remove() method. # Similarly, the rmdir() method removes an empty directory. import os #removing a file #os.remove('file1.txt') #removing a directory os.rmdir('new-test')
402252d39b42df58ea5d88777ab959e50f6a87d3
ArisPython/PythonDasarRWID
/main.py
1,528
3.890625
4
# konstruksi dasar python # sequential = eksekusi berurutan # print('hello world') # print('by aris winandi') # print('semarang') #percabangan # ingin_cepat = True # if ingin_cepat: # print('jalan lurus aja') # else: # print('belok ke kanan') #perulangan # jumlah_anak = 4 # for index_anak in range (1, jumlah...
4ff2c1d6264eed3c7b9bbfd1a4a8892ecc5de6a4
SaladBreaker/Astar-with-pygame
/structures.py
1,577
4.0625
4
from math import sqrt from symbol import continue_stmt class Node: def __init__(self, position, parent): """ Simple node with the purpuse of being used in teh A* algorithm :param position: is atuple of int elemnts of form: (x,y) where y is the depth 0 <= y < m | m is the size of a...
1c5c61b0ea9a97617555bdfcba8050846bab5556
carnmt/Quant-Finance
/library/market_data.py
2,341
3.578125
4
# -*- coding: utf-8 -*- """ Created on Mon Jun 8 12:36:30 2020 @author: Juani """ class MarketData(): """ This class is the container for all the market data objects. A Named market data object should be provided for look up. """ def __init__( self , *args, **kwargs ): self._stocks = kwargs['...
e7b487fd76c291b98fdf0f84e0a0c47c75941adb
minjun0622/CSCI127
/pset31.py
440
3.640625
4
#Name: Minjun Seo #Email: minjun.seo58@myhunter.cuny.edu import pandas as pd import matplotlib.pyplot as plt first = input("Enter name of input file:") second = input("Enter name of output file:") homeless = pd.read_csv(first) homeless["Fraction Single Women"] = homeless["Single Adult Women in Shelter"]/homeless["To...
c7b9ca4e1b3561c10ab7bb6b4d708cb450c06ef4
minjun0622/CSCI127
/pset21.py
353
3.59375
4
#Name: Minjun Seo #Email: minjun.seo58@myhunter.cuny.edu import matplotlib.pyplot as plt import numpy as np x = input("Enter dimensions. Number only:") name = input("Enter name of file:") sz = int(x) image = np.ones((sz,sz,3)) for i in range(sz): if ((i % 2) == 0): image[i,:,0] = 0 image[i,:,2]...
c99b6b417948be1d41066647d8f084779a7425ce
minjun0622/CSCI127
/pset30.py
242
3.609375
4
#Name: Minjun Seo #Email: minjun.seo58@myhunter.cuny.edu import pandas as pd filename = input("Insert file name:") average = input("Choose one to average:") stars = pd.read_csv(filename) aggregate = stars.groupby('Star type').mean() print(aggregate[average])
2797eaf5f53c7cb604a74ef5f41d72140bbef23a
minjun0622/CSCI127
/pset49.py
330
3.828125
4
#Name: Minjun Seo #Email: minjun.seo58@myhunter.cuny.edu def backup(n): return(n * 1.0875) def main(): price = float(input("Enter the price of item:")) counter = 0 while price > 0: counter += backup(price) price = float(input("Enter price of item:")) print("Total is ", counter) i...
3f46635fee056a84afcd68e5c3833ec6dfd724bf
krishan711/aoc-2020
/day5-2/main.py
2,434
3.546875
4
import logging import time import math from typing import List from typing import Optional import dataclasses import click def get_seat_from_string(seatString: str)-> (int, int): maxRow = 127 minRow = 0 maxCol = 7 minCol = 0 rowString = seatString[:7] colString = seatString[7:] for charact...
e767dd60e78ae43f3f7997742b0d85459eeb1756
tatusharma/beginner
/palindrome1.py
202
4.375
4
#To check whether the word is a palindrome c=input("Enter the word you want to check: ") if(c==c[::-1]) print("The word is a palindrome") else print("The word is not a palindrome")
4d7b853dcc5d39c9a9e6d03112ac52da4dff797e
icehofman/solveet-problems
/merge-sort-py/merge_sort.py
1,010
4.28125
4
# # solution to 'merge sort' problem in python # def merge_sort(numbers): """Entry point of the algorithm""" n = len(numbers) if(n == 1): return numbers left = merge_sort(numbers[:(n/2)]) right = merge_sort(numbers[(n/2):]) return merge(left, right) def merge(left, right): "The most complicated method, it m...
e028c1319b92d1eff830215ada24756e7bd8f1a3
BryanPutra/listanddictionarypractice
/number1.py
335
3.5
4
inventory = {'gold':500, 'pouch' :['flint','twine','gemstone'], 'backpack':['xylophone','dagger','bedroll','bread loaf']} inventory ['pocket'] = ['seashell','strange berry','lint'] inventory ['backpack'].sort() inventory ['backpack'].remove('dagger') inventory ['gold'] += 50 print(inventory['backpack']) print(inv...
490dfa86f5c38983bfca4a6ebd95c29a115db0c3
steveyang95/tools
/tools/stopwatch.py
2,131
4.21875
4
import time class StopwatchLap: def __init__(self, start_time=time.time(), end_time=time.time()): """ :param start_time: :param end_time: """ self.start = start_time self.end = end_time def calculate_time_elapsed(self): return self.end - self.start ...
ab6e87c662be10f962b10e820bd657fb5266195c
nguyenthanhlong8520/FRIDAY
/craw/draw.py
505
3.59375
4
# importing modules import matplotlib.pyplot as plt import numpy as np # assigning x and y coordinates language = ['C','C++','Java','Python'] users = [80,60,130,150] # depicting the visualization index = np.arange(len(language)) plt.bar(index, users, color='green') plt.xlabel('Users') plt.ylabel('Langu...
19a8f9d70823223e6a0cb79f78867c0b64ffef03
nmbenzo/scraping-books
/menu.py
1,722
3.8125
4
import logging from app import books logger = logging.getLogger('scraping.menu') def print_best_books(): logger.info('Finding best books by rating...') best_books = sorted(books, key=lambda x: x.rating * -1)[:10] # this will give us the top ten books for book in best_books: print(book) def pr...
def8bac0599fea4c03d8e9c79eeadb6d8a5cf03a
SibiSagar/Daily-challenge
/cw`.py
1,044
4.125
4
'''triple_double(num1, num2) which takes numbers num1 and num2 and returns 1 if there is a straight triple of a number at any place in num1 and also a straight double of the same number in num2. If this isn't the case, return 0 Examples triple_double(451999277, 41177722899) == 1 # num1 has straight triple 999s...
3a1820a08bb09e0a5f92dbafaf88786380b2d009
OffTheMark/csgames_2017_ai_prep
/pathfinding/breadth_first_search.py
730
3.75
4
from pathfinding.solver import Solver from collections import deque class BreadFirstSearchSolver(Solver): """ BFS solver implementation \n Based on http://bryukh.com/labyrinth-algorithms/ """ def solve(self): start = self.find(self.START) finish = self.find(self.FINISH) que...
9b457966a06cc525b22a26d4f3c303e0eed827ae
18803836226wmm/numpy_pandas_matplotlib_practices
/numpy_practices/numpy_2.py
1,571
3.53125
4
import numpy as np """ numpy 常用方法 ndim:返回int 表示ndarray的维度 shape:返回的尺寸 几行几列 size:返回数组元素的个数 dtype:返回数组中元素的类型 运算 直接可以在每个元素加减乘除 """ # arry0=np.array([1,2.3,2,3],dtype='int') # print(arry0) # x=np.linspace(1,5,5,endpoint=False) # print(x) # x2=np.zeros(3,int)+2 # print(x2) # arr1=np.arange(1,7).reshape(3,2) # arr2=np.arange...
e44f822594d8e5dea5a571e554d4ee50675a3105
ahmdeen/Bioinformatic-Algorthims
/Ros4E_EulerianCycle.py
2,760
3.8125
4
""" Eulerian Cycle Problem Find an Eulerian cycle in a graph. Given: An Eulerian directed graph, in the form of an adjacency list. R """ '''Functions''' """ def EulerianCycle(edges): '''Creates a EulerianCycle from the given edges''' thisNode = edges.keys()[0] ePath = [thisNode] while True: ePath.append(edge...
bb1732159fdfddf3a9c0f32412ae27eeb6303ae2
ahmdeen/Bioinformatic-Algorthims
/Ros9A_FarthestFirst.py
1,561
3.828125
4
""" Given: Integers k and m followed by a set of points Data in a m-dimensional space. Return: A set Centers consisting of k points (centers) resulting from applying FarthestFirstTraversal(Data, k), where the first point from Data is chosen as the first center to initialize the algorithm. """ from scipy.spatial impo...
8a389f934f2dcb10cd322675fc458e12fdd0cdbd
ahmdeen/Bioinformatic-Algorthims
/Ros4D_DebruijnFromKmers.py
978
3.53125
4
""" De Bruijn Graph from k-mers Problem Construct the de Bruijn graph from a collection of k-mers. Given: A collection of k-mers Patterns. Return: The de Bruijn graph DeBruijn(Patterns), in the form of an adjacency list. """ '''Functions''' def deBruijnFromKmers(kmers): dbDict = dict() i = 0 for kmer in kmers: ...
d7a06785ece465212997c4f114ce96d01ce60162
ahmdeen/Bioinformatic-Algorthims
/Ros4B_OverlapGraph.py
805
3.71875
4
""" Overlap Graph Problem Construct the overlap graph of a collection of k-mers. Given: A collection Patterns of k-mers. Return: The overlap graph Overlap(Patterns), in the form of an adjacency list. """ '''Definitions''' def OverlapGraph(dna): checker = lambda pair:pair[0][1:] == pair[1][:-1] printer = lam...
26cc659f995a05a7f4b37fc781462463ecbb0b07
ahmdeen/Bioinformatic-Algorthims
/Ros4F_EulerianPath.py
1,587
3.953125
4
""" Eulerian Path Problem Find an Eulerian path in a graph. Given: A directed graph that contains an Eulerian path, where the graph is given in the form of an adjacency list. Return: An Eulerian path in this graph. """ from Ros4E_EulerianCycle import eulerian_cycle '''Functions''' def EulerianPath(edges): '''Re...
087ba276c1f8417fbb60b734981d6ccf98453642
JordanJssh/Taller2
/EstrellaNLados_JordanSanchez.py
364
3.640625
4
import turtle import math t=turtle.Pen() angulo=0 x=int(input("Ingrese el valor de lados: ")) t.reset() angulo=360//x if x%2!=0: print("Impar") for i in range(x): t.right(((x-2)*180)/x) t.forward(100) t.right(((x-2)*180)/x) else: print("Par") for i in range(x): t.forwar...
eff04f01aed54bbe05056588999aea1d148c968f
Tkr-Karan/HacktoberFest_2021
/Binary_Search.py
653
4.03125
4
def Binary_Search(lst,l,r,ele): if(l<=r): mid = l + (r-l)//2 if(lst[mid] == ele): return mid elif(lst[mid] >= ele): return Binary_Search(lst,l,mid-1,ele) else: return Binary_Search(lst,mid+1,r,ele) return -1 print('Enter the Size of the LI...
fe8eb57fa32282f361605ecb274a3caa6a54b520
rohitsingh0812/multirobotnav
/problems.py
3,293
4.0625
4
""" problems.py Author: Ariel Anders aanders@mit.edu This file has three different test problems. a and b are from the paper. c generates a random problem. """ import random """ Robots are in a square. Each moves to location +8 distances away """ def get_problem_a(): starts = [(0,4), (1,4), (2,...
53758043c7e655a723efd7010592156121c9883c
EcholotFisher/good_news_everyone
/Functions/.ipynb_checkpoints/datasets-checkpoint.py
1,556
3.578125
4
def load_stratified_dataset(path, labels, samples_per_label, random_seed=42): """ Load from dataset, stratify labels Inputs: path (path to dataset) labels (name of column to stratify by) samples_per_label (number of samples per label) random_seed: (to get articles, defaul...
86267aa9202cb9ad11dac19a06dab6d7e22c3104
jiaoxijia/Python
/2018.2.1/3.22/ans0201.py
261
3.515625
4
#! --*-- coding:utf-8 --*-- import pandas as pd import os df = pd.read_csv("spider.log",delimiter=',',names=['date','www','film','piao','aa']) print df.columns df.dropna() # print df.columns df['www'] == r"http://www.movie.com/dor/" # print df # print df
fb4769a62e9ba8bf0af4ebd435740d008a482fc2
jiaoxijia/Python
/2018.2.1/3.15.py
914
3.890625
4
#coding:utf-8 def func(a ,b=5, c=10): print 'a is ',a, 'and b is ', b, 'and c is ',c def say(message,times=1): print message * times def total(a=5,*numbers,**phonebook): print "a",a #遍历元组中的所有数组 for single_item in numbers: print "single_item",single_item #遍历字典中的所有项目 for first_part,...
ccb91879ad52aa68d42e972c3a920cfc3aa03002
jiaoxijia/Python
/untitled2/demo22.7.py
871
3.59375
4
# -*- coding:UTF-8 -*- import time ticks = time.time() print '当前时间戳为:',ticks #获取当前本地时间 # 格式化成2016-03-20 11:45:39形式 print time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) # 格式化成Sat Mar 28 22:24:24 2016形式 print time.strftime("%a %b %d %H:%M:%S %Y", time.localtime()) # 将格式字符串转换为时间戳 a = "Sat Mar 28 22:24:24 2016"...
8b6400d26105e12a749e6f8a1193485be0b0631c
JakiShaik/Datastructures
/longest.py
495
3.703125
4
def longest(a): llp,hp = _longest(a) return llp def _longest(a): if a == [] or (a[0] == [] and a[2] == []): return 0,0 llength,lhgt = _longest(a[0]) rlength,rhgt = _longest(a[2]) if a[0] == [] or a[2] == []: lp = max(1+lhgt+rhgt,llength,rlength) h = 1 + max(lhgt, rhgt) ...
6f982fd8178c5ebbee82b43f62b6065960808fbd
JakiShaik/Datastructures
/bsts.py
244
3.515625
4
def bsts(n): bsts = [1] return _bsts(n,bsts) def _bsts(n,bsts): for i in range(1,n+1): sum = 0 for j in range(1,i+1): sum += bsts[j-1]*bsts[i-j] bsts.append(sum) return bsts[n] print(bsts(5))
0fda34bf1cffdfdf80c90e720bb0cb32a6d22fe7
horacepan/gcnn
/dataset.py
950
3.5
4
import numpy as np import util import pdb class Dataset(object): ''' Simple class that deals with spitting out batch sizes for training. The index gets reset(to 0) and the data/labels are shuffled once the index gets too high. ''' def __init__(self, data, labels, batch_size): self._data...
122e29bfb8a0f70e10f4ed279642355c80f5bd22
nlsandler/responsebot
/seq2seq.py
12,042
3.53125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ A module for training sequence-to-sequence models in Keras, based on https://blog.keras.io/a-ten-minute-introduction-to-sequence-to-sequence-learning-in-keras.html The main difference is that it uses a word-level model with an Embedding layer, instead of a character-le...
1e1f8041b140be821ab51111ecd62bf588d7366f
makinwab/allocaciones
/models/office.py
834
3.734375
4
from room import Room from random import randint class Office(Room): # can accomodate max_spaces = 6 spaces = [] occupied = {} def create(self, data): rooms = super(Office, self).create(data)["office"] self.spaces = list(set(self.spaces + rooms)) print "Offices created" ...
d11d2a930f6683f743d57e531a87546ed8a0aab4
ClayTaylor/learning-python-pycharm
/object-functions/object-functions.py
461
3.796875
4
from Studentagain import Student #Importing the file Studentagain and importing the class Student student1 = Student("Oscar", "Accounting", 3.1) #Variable student1 is a Student Object with attributes. student2 = Student("Phyllis", "Business", 3.8) #Variable student2 is a Student Object with attributes. print(student1...
9f23729aede0b656b0b6780377061956068b52b1
ClayTaylor/learning-python-pycharm
/better-calculator/better-calculator.py
383
4.375
4
num1 = float(input("Enter the First Number: ")) op1 = input("Enter the First Operator: ") num2 = float(input("Enter the Second Number: ")) #num3 = float(input("Enter the Third Number: ")) if op1 == "+": print(num1 + num2) elif op1 == "-": print(num1 - num2) elif op1 == "/": print(num1 / num2) elif op1 == ...
46b54dd2193022ff9f31bdb25910f0b9873a902e
Dvaraz/PY111
/Tasks/a1_my_queue.py
1,173
4.15625
4
""" My little Queue """ from typing import Any from collections import deque queue = deque([]) def enqueue(elem: Any) -> None: """ Operation that add element to the end of the queue :param elem: element to be added :return: Nothing """ print(elem) queue.append(elem) return None def...