blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
867baa780f44106a2b3e47450d40289198543d47
bssrdf/pyleet
/R/ReachANumber.py
1,620
4.1875
4
''' -Medium- *Math* You are standing at position 0 on an infinite number line. There is a goal at position target. On each move, you can either go left or right. During the n-th move (starting from 1), you take n steps. Return the minimum number of steps required to reach the destination. Example 1: Input: target...
5786d9adf5a557179d5e275ebec89823dd73e630
123biswash/leetCode
/printAllSubsets.py
574
3.65625
4
#[a,b,c,d,e] def printAllSubsets(arr): returnArr=[[]] # returnArr.append(['']) for i in range(0,len(arr)): for j in range(i+1,len(arr)+1): returnArr.extend([arr[i:j]]) for i in range(0,len(arr)): for j in range(i+1,len(arr)-1): tempArr=[] temp='' ...
809e44936f2b7de117cd4dff89e65e4fb4e7272d
prasad01dalavi/python_basics
/17.GlobalVsLocal.py
2,524
4.28125
4
my_list = [1, 2, 3] my_var = 5 global var2 var2 = 8 non_global_var = 7 def add_to_list(fun_list): fun_list.append(4) # Making changes to the list by appending print 'In add_list function, fun_list =:', fun_list # [1, 2, 3, 4] print 'In add_list function, my_list =:', my_list # [1, 2, 3, 4] def...
0ff93721318bae3b483ca2d9295d2e4d58a9b03b
JWang123456/feature-Extraction
/refer/matrices.py
2,342
4.34375
4
# use Numpy arrays instead of the native Python arrays import numpy as np # Create a matrix X = np.matrix('1 2; 3 4') # 2x2 matrix. semicolon separates rows print("X=", X) y = np.matrix('1;2'); print("y=", y) # 2x1 matrix yt = np.matrix('1 2'); print("yt=", yt) # 1x2 matrix v = np.array([1,2]) # 2 vecto...
e70d505d38d3a537b71ed82c2795d941b089f986
hero24/Algorithms
/python/sorting/merge_sort.py
739
4
4
#!/usr/bin/env python3 # You're a Timex watch in a digital age. # ~ Thomas Gabriel @ Die Hard 4.0 def merge_(lst_a,lst_b): ' merging function ' result = [] right = 0 left = 0 length = len(lst_a) if len(lst_a) > len(lst_b) else len(lst_b) for i in range(length): if lst_a[right] <= lst_b[...
7dd3ea5cd7b795042da8f6bd0205274ea3568fc9
jamesbellaero/UAV
/unit_conversions.py
1,951
4.0625
4
# -*- coding: utf-8 -*- """Handles converting units of latitude and longitude and distance. Latitude and longitude can be switched between decimal degrees, radians, and degrees, minutes, and seconds (e.g. 23° 32' 34.4432" N) and distance can be switched between feet and meters. """ from math import floor, pi from...
3ff776dbb066b5b7a1bd4c840785f86f72cdcdda
orazaro/udacity
/cs212/cond_probability.py
624
3.53125
4
import itertools from fractions import Fraction sex = 'BG' def product(*variables): return map(''.join, itertools.product(*variables)) two_kids = product(sex, sex) print two_kids one_boy = [s for s in two_kids if 'B' in s] print one_boy def two_boys(s): return s.count('B') == 2 def condP(predicate, event): ...
adc996b5d2f865ffd7faa071a09e3a074a89ae65
derricku/CSC232
/Homework8/HW8_24_skoll_P1.py
549
4.125
4
""" Homework 8 >Problem 1 Author: Derrick Unger Date: 3/7/20 CSC232 Winter 2020 """ # Bubble Sorting arr = [9, 3, 5, 6, 8.8, 5, 100, -5.5, 0, 2020] # Define your array here n = len(arr) # Define length of array here # Traverse through all array elements for i in range(len(arr)): # Last i elements are already ...
219951eaf8f2c266dc42f34070d6ff522390357d
sa3mlk/projecteuler
/python/euler14.py
375
3.71875
4
#!/usr/bin/env python def next(n): if n % 2 == 0: return n / 2 else: return 3 * n + 1; history = [0, 1] for i in range(2, 1000000): num_terms = 0 num = i done = False while num > 1 and not done: num = next(num) if (num < len(history)): num_terms += history[num] done = True num_terms += 1 histor...
bf604da1d82d6bf059b6ed721319632c33211563
ijockeroficial/Python
/CursoEmVídeo/Mundo 2/Laços/tabuada.py
506
4.1875
4
numero = int(input("Digite um número: ")) #Dessa forma aqui teria que fazer vários IF's.. ''' for x in range(1, 10): if numero == 1: print("{} x {} = {}".format(numero, x, (x * numero))) elif numero == 2: print("{} x {} = {}".format(numero, x, (x * numero))) ''' #Aqui já ficou mais simples e o c...
4409edcc81f9872f9d9e7ff1d77ad8f76dc1f212
12345k/GUVI-Beginner
/set-1/swap_odd_even_string.py
253
3.6875
4
print("Enter the string : ") string = str(input()) l=list(string) s="" for i in range(len(l)): if(i % 2 == 0): if(i+1<len(l)): s = s+l[i+1] else: s =s + l[i-1] if(len(l)%2!=0): s=s+l[len(l)-1] print(s)
dfa797b0261c9dcf2d01ad2e303191771d1e0aff
Gulomova/homework
/homework_1/task_3.py
249
3.921875
4
# TASK №3 def fibonacci(n=10, a=0, b=1): yield a yield b n -= 2 while n > 0: c = a + b a = b b = c yield c n -= 1 if __name__ == '__main__': for n in fibonacci(100): print(n)
8fbc63652dd29079944ed34314668e13d82a5fa8
xys234/Leetcode
/Algo/trie/implement_trie.py
1,217
4.125
4
""" """ class TrieNode: def __init__(self): self.children = {} self.endofword = False class Trie: def __init__(self): """ Initialize your data structure here. """ self.root = TrieNode() def insert(self, word: str) -> None: """ Inserts a...
998f4f42f63257f42e89abceaf15307bb7ecabf7
aismartbs/c_to_f
/temp.py
91
3.984375
4
c = input('PLease enter c degree') c = float(c) f = c * 9 / 5 + 32 print('f degree is', f)
ed22bd2c174e79c86ef8dee85fb7fde22d9f440f
jaxmann/python-training-videos
/Ex_Files_Python_3_EssT/Ex_Files_Python_3_EssT/Exercise Files/12 Classes/classes-working3.py
613
3.71875
4
#!/usr/bin/python3 # classes.py by Bill Weinman [http://bw.org/] # This is an exercise file from Python 3 Essential Training on lynda.com # Copyright 2010 The BearHeart Group, LLC class Duck: def __init__(self, **kwargs): self.variables = kwargs def quack(self): print('Quaaack!') def walk...
002f42f0e4bcf513f9c70a4175674af035043bfe
BrianPavillarCIS/2348HW
/HW2/7.25/main.py
1,424
3.828125
4
# Name: Brian Pavillar # ID: 1863509 # Function Definition def exact_change (change): # Define Variable numdollars = 0 numquarters = 0 numdimes = 0 numnickels = 0 numpennies = 0 # If there is no change if change == 0: print("no change") # While Loop ...
6056c9f278c1be5eb1838f1e7511a95c60a48825
jarkyll/Python
/ageupdated.py
524
4.09375
4
#! /usr/bin/env python #years again import sys if len(sys.argv) > 1: name = sys.argv[1] else: name = input("Please put your name: ") if len(sys.argv) > 2: age = int( sys.argv[2] ) else: age = int( input("Please put your age: ") ) hello = "Hello " + name + "," if age == 100: agestring = "You a...
6ebb2d74bbac8f3f13b5ae5d2621fc1aba0d1f95
dieenemy/tranxuantung-fundamental-c4e24
/session3/ex2.py
210
3.796875
4
while True: i = int(input("Guess my number (1-100): ")) if i < 51: print("Too small :(") elif 51 < i <= 100: print("Too large") else: print("Bingo") break
94994c96d4201d66957452aece6d714c68e1b621
jprinaldi/algo1
/pa1/inversions.py
1,264
4.53125
5
#!/usr/bin/env python3 """ Implementation of the Merge Sort algorithm in order to count the number of inversions in a list of integers. """ import argparse def read_file(filename): with open(filename) as f: return [int(line) for line in f] def _merge_sort(A, B, begin, end): if end - begin < 2: ...
786d9f9d163cbf6176ec5e7da33ae2f61138f04e
mnamysl/nat-acl2021
/robust_ner/hunspell.py
1,525
3.578125
4
import hunspell import codecs def _normalize_utf8(text): """ Normalizes text by replacing all non-latin-1 characters. """ text = codecs.encode(text, 'latin-1', 'replace') text = codecs.decode(text, 'latin-1', 'replace') return text def init_hunspell(lang, dictionary=None): """ Initial...
ac1f81577f0cb8510538c2e53bf5f3d763254810
indo-seattle/python
/rakesh/Exercise37.py
174
4.25
4
print("Exercise 37 - Tuple") print("Python print second largest number in the list.") myTuple = ("WA", "CA", "NY") print(myTuple) for element in myTuple: print(element)
1ce852ebe1cf981a6be375fa5a2b5f2e1db83204
jaykumarvaghela/myPythonLearning
/Python Language/testtttttttttt.py
63
3.546875
4
lst = [2,1,3] s = 0 for i in lst: s = s + (i-1) print(s)
1333a7d29fb7d0c4ce650e8b068f7556b4cbd988
HrkgFx/ENGETO_Python
/Poznamky a koncepty/zajimave_funkce.py
528
3.8125
4
# MAXIMALNI ITEM v LISTU def max(sequence): max_item = sequence[0] for item in sequence[1:]: if max_item < item: max_item = item return max_item # RAZENI LISTU listB = [24, 13, -15, -36, 8, 22, 48, 25, 46, -9] listB.sort(reverse=True) # listB gets modified print listB => [48, 46, 25...
c79a5759cc21fd15b7cec64f5a0039a4c2e2c9bd
nranmag/ejemspython
/Primeras_funciones.py
265
3.84375
4
print("Verificación de Acceso") edad_usuario=int(input("Introduce tu edad, por favor: ")) if edad_usuario<18: print("No puedes pasar") elif edad_usuario>100: print("Edad incorrecta") else: print("Acceso permitido") print("El programa ha terminado")
336d0677f8c9bd3dd5ca86e87814ab44618d920f
LourdesOshiroIgarashi/algorithms-and-programming-1-ufms
/Lists/Estrutura_de_Repetições_Aninhadas/Cauê/06.py
101
3.71875
4
n = 10 x = 10 while x <= n and x > 1: print(" " * (x - 2),"{0}".format(x)) x -= 1 print(1)
e0bff85c583d38d9ad9eb5b226e80a84ab43ff72
steren55/CodeTest
/Python/Python-Pratice/day01.py
523
4.375
4
""" DAY 1 """ ''' 單行註解用# 多行註解包在三個引號夾起來之間(單雙引號皆可) ''' msg = 'Hello World' print(msg) print('Hello World') #print('111') ''' print('Hello World') print('Hello World') print('Hello World') print('Hello World') print('Hello World') ''' # Homework # 1. import this # 2. import turtle turtle.pensize(4) turtle.pencolor('red...
e99cfc76c26583a08e28e47dc3cec9e42287b2bb
cat-in-the-box/lynnie-fein-schaffer
/4_marketing.py
163
4.09375
4
desired_pet = input("Do you prefer a pet that has fur?") if desired_pet == "Yes": print("Get cat or a dog!") elif desired_pet == "No": print("Get a fish!")
bf92577152052cab92a73ac34cb6055bb12397c6
peanut996/Leetcode
/Python/202. Happy Number.py
924
3.71875
4
#!/usr/bin/python3.7 # from typing import List """202. Happy Number 编写一个算法来判断一个数 n 是不是快乐数。 「快乐数」定义为:对于一个正整数,每一次将该数替换为它每个位置上的数字的平方和,然后重复这个过程直到这个数变为 1,也可能是 无限循环 但始终变不到 1。如果 可以变为  1,那么这个数就是快乐数。 如果 n 是快乐数就返回 True ;不是,则返回 False 。 """ class Solution: def isHappy(self, n: int) -> bool: def square(n: int) -> in...
87a890e0b750bee5b9743ae1d286073d815d8178
rcamjalli/pythonTerminalMaze
/MazeCreator.py
3,036
3.578125
4
from maze import MyPair from random import shuffle import curses import time # get the curses screen window screen = curses.initscr() # enable text color curses.start_color() # turn off input echoing curses.noecho() # respond to keys immediately (don't wait for enter) curses.cbreak() #hides the cursor curses.curs_set(...
30ef9d716f47d9da7269b4f6ed0196a8e7eb76ba
gitter-badger/yann
/yann/core/activations.py
8,988
3.609375
4
import theano.tensor as T from math import floor #### rectified linear unit def ReLU(x, alpha = 0): """ Rectified Linear Units. Applies point-wise rectification to the input supplied. ``alpha`` is defualt to ``0``. Supplying a value to ``alpha`` would make this a leay ReLU. Args: ...
83d3af6cad3b42c3c24d3efc084fc742e51fd3e4
AdrianDali/edd_1310_2021
/19noviembre_1310/linked_list.py
2,141
3.96875
4
class Nodo: def __init__(self, value, siguiente = None): self.data = value #falta encapsulamiento self.siguiente = siguiente class LinkedList: def __init__(self): self.__head = None def is_empty(self): return self.__head==None def append(self,value...
85fc3611499f1f0b4e31a5648853a8dcb3a98fc6
JohanCala/LaboratorioFuncionesRemotos
/mainPerfectnumberDos.py
405
4
4
def perfect_number(n): a=0 for i in range(1,n): if(n%i==0): a+=i if (a==n): print("this is a perfect number") else: print("this is not a perfet number") if a<=(n-3) and a>=(n+3): print("it's not an almost perfect number") else: print("it's an ...
f7f0c494b4e494ab659483540e29be0a96ac8c8c
ShaoxiongYuan/PycharmProjects
/1. Python语言核心编程/1. Python核心/Day05/exercise05.py
307
3.859375
4
# 方法一 length = int(input("请输入斐波那契数列长度:")) list1 = [1, 1] for _ in range(length - 2): list1.append(list1[-2] + list1[-1]) print(list1) # 方法二 def fibonacci(n): a, b = 1, 1 for _ in range(n): yield a a, b = b, a + b print(list(fibonacci(5)))
004a0c737b780893c969e66008945cc5216e9280
Timroman1993/matplotlib
/figure.py
341
3.546875
4
#coding=utf-8 import matplotlib.pyplot as plt import numpy as np x = np.linspace(-3,3,50) #-3~3中产生50个点 y1 = 2*x+1 y2 = x*x plt.figure() #figure中显示y1. plt.plot(x,y1) plt.show() plt.figure(num=2,figsize=(8,5))#一个figure管一段 plt.plot(x,y2) plt.plot(x,y1,color='red',linewidth=1.0,linestyle='--') plt.show()
5fc275eed2f2e00ab5c7690fcaa9188b441a2ac5
aditishastry/Gait-Phase-Identification
/hipAngleCalc.py
8,306
3.8125
4
import pandas from pandas import DataFrame import matplotlib.pyplot as plt # pip install pyquaternion import pyquaternion as pyq import math import numpy as np ''' Adds data to a dictionary dataset Inputs: - data: a dictionary that holds dictionary values e.g.) { 'MSW' : { 'Row' : [0,1,2..], 'Time' : [...] }...
2dc96615fbee16a18cf901d7cc90ad2b33f2fc70
miro6181/Algorithms-CSCI3104
/FA2019/PS9/Rogers-Michael-PS9b-Q2.py
248
3.78125
4
def optimalShake(arr): dp = list(range(len(arr)-1)) dp[0] = arr[0] dp[1] = max(arr[0], arr[1]) dp = [max(dp[i-1], dp[i-2] + arr[i]) for i in range(2, len(arr) -1)] return dp[-1] print(optimalShake([2,7,9,3,1]))
4c763408293ae9af9af5bfc3780fa89bd3631f5b
nsm-lab/DAT3
/code/99_regex_example.py
1,354
3.578125
4
''' CLASS: Regular Expressions Example ''' ''' Open file ''' # open file and store each line as one row with open('../data/homicides.txt', 'rU') as f: raw = [row for row in f] ''' Create a list of ages ''' import re ages = [] for row in raw: match = re.search(r'\d+ years old', row) if match: ...
28cee418befae60b127684a4ca36098ee5ad6134
jijojohn88/workspace
/test/src/tree/matrix.py
201
3.75
4
data = [[[1, 2],[3, 4]],[[5, 6],[7, 8]]] def fun(m): v = m[0][0] print(m) for row in m: for element in row: if v < element: v = element return v print(fun(data[0]))
73bcef36eef4ea4056591cb7ad3867df6f576562
Szubie/Misc
/Insertion sort practice.py
1,151
4.25
4
#Coding insertion sort by memory. def insert(x): """where x is a list of numbers, sort this list into ascending order""" #First, need to iterate over the length of the list, looking at each item. for num in range(1, len(x)): #To check each item, we need to hold the value of the item we are...
26df4ef7b96615a5956b01f5bd99c1ea81a2dc20
juliakarabasova/programming-2021-19fpl
/binary_search/binary_search.py
5,176
4.03125
4
""" Programming for linguists Implementation of the data structure "BinarySearchTree" """ class BinarySearchTree: """ BinarySearchTree Structure """ def __init__(self, root: int = None): self._root = Node(root) def add(self, element: int): """ Add the element ‘element’ a...
818a516719c9730811fbd927f725f79e439ccb66
iburn78/documentation
/Python/Machine_learning/MLcodes/Ch2_L6.Adv_Scrapping.py
1,840
3.515625
4
# Requests module # session.get(url) # session.post(url) # session.put(url) # session.delete(url) import requests # using get with requests module ''' session = requests.session() # session only needs to be created once url = "http://google.com" data = { "a":"10", "b":"20" } response = session.get(url, dat...
19e1c2d6a2e7f3728baed9dece0eb3a29b507798
HKuz/PythonWorkbookExercises
/1_IntroExercises/002_Hello.py
94
3.609375
4
#!/usr/bin/env python3 name = input('Please enter your name: ') print(f'Howdy do, {name}!')
b5f8712310ab2b85c5cdec2f35c2e01399b2c2e6
ketgo/quantum-computing
/src/quantum_computing/utils/torch.py
801
3.53125
4
""" PyTorch utility methods and classes """ import torch def kronecker(t1: torch.Tensor, t2: torch.Tensor) -> torch.Tensor: """ Computes the Kronecker product between two tensors. See https://en.wikipedia.org/wiki/Kronecker_product :param t1: first tensor :param t2: second te...
a10646288e414239b5180e15f74521bd6fc43c9d
codetalker7/angluin-style-learning
/new_answer_vector.py
4,162
3.859375
4
from typing import final import json from automata.fa.dfa import DFA import math # opening the primes list primes_file = open("primes.txt" , "r") llist = primes_file.read() primes_list = list(llist[:len(llist) - 1].split()) def get_vector_one_prime(A, n, max_length=None, prime=2): """ Input is a D...
d35bed1005ea49c9012998af4959112ae89c771a
abhatkar1/Python-Program-Solving
/Ch4_21.py
1,360
4.5
4
# (Science: day of the week) Zeller's congruence is an algorithm developed by # Christian Zeller to calculate the day of the week. The formula is # Write a program that prompts the user to enter a year, month, and day of the # month, and then it displays the name of the day of the week. Here are some sample # runs: # E...
ae885af7c8ffa38ebc223c6ad8f0ccd3d8fb7dfb
guilledmv/AbitOfPython
/swap.py
279
3.890625
4
# Our user need to give ourselves two values value1 = input("Put first value : ") value2 = input("Put Second value : ") # We use buble sort method to solve (I need an axiliary variable) aux = value1 value1 = value2 value2 = aux print("Values exchange are : ",value1," , ",value2)
afa1d5a309193e4ce2d6bf099f70a3bd901a4b61
drcrook1/AI_Accelerators_Quality
/src/web_app/WebApp/providers/helpers.py
203
3.671875
4
""" Author: David Crook Copyright: Microsoft Corporation 2019 """ def line_to_percent(slope, intercept, x): y = intercept + slope * x percent = ((y[-1] - y[0]) / y[0]) * 100 return float(percent)
ca6e0bc8735cb45c3f71bdaceb7431ac7b2ef8d9
sumit-jaswal/python-exercises
/100_6_formula.py
499
4.03125
4
# Write a program that calculates and prints the value according to the given formula: # Q = Square root of [(2 * C * D)/H] # Following are the fixed values of C and H: # C is 50. H is 30. # D is the variable whose values should be input to your program in a comma-separated sequence. # Input : 100,150,180 # Output : 1...
87342d3b85cc9dfbab056bdee50f97200c501cc4
iamkissg/nowcoder
/algorithms/coding_interviews/09_frog_jump_2_official.py
280
3.765625
4
# -*- coding:utf-8 -*- # 数学归纳法 # 1: 1 # 2: 2 # 3: 1 + 2 + 1 # 4: 1 + 1 + 1 + 2 + 3 class Solution: def jumpFloorII(self, number): # write code here return 2**(number-1) if __name__ == "__main__": sol = Solution() print(sol.jumpFloorII(3))
bf9f3cd3303886bba08935cd8188ae65008fdc34
josdyr/exercism
/python/rna-transcription/rna_transcription.py
548
3.515625
4
def to_rna(dna_strand): dna_strand = list(dna_strand) for idx, item in enumerate(dna_strand): if item == "G": dna_strand[idx] = "C" elif item == "C": dna_strand[idx] = "G" elif item == "T": dna_strand[idx] = "A" elif item == "A": dn...
6745b55ec1a47c9d703784a6d463b41eee720c52
elJuanjoRamos/Curso-Python
/Leccion14-Manejo-Excepciones/manejo_excepciones.py
291
3.53125
4
resultado = None a = 10 b = 0 try: resultado = a/b except Exception as e: print(f'Ocurrio un error: ', e) except TypeError as e: print(f'Ocurrio un error: ', e) except Exception as e: print(f'Ocurrio un error: ', e) print(f'Resultado { resultado }') print('Continuamos...')
1e0693c236eacb1d28873ca5161ea2c33d780d60
jm4ch4do/my_CWs
/5kyu/max_subarray_sum.py
3,457
4.0625
4
# ----- Problem: Maximum subarray sum (5ku) # ----- URL: https://www.codewars.com/kata/54521e9ec8e60bc4de000d6c def max_subarray_sum(_numbers): """ (list_of_int) -> int :param _numbers: list with a sequence of positive and negative ints :return: int with sum of the subarray with the maximum possible s...
522c899134cf2b1c411f61f573063cab1e1cfe00
artiom-zayats/advent
/2019/problem_3.py
1,318
3.53125
4
import math def load(filename): with open(filename) as f: content = f.readlines() # you may also want to remove whitespace characters like `\n` at the end of each line content = [x.strip() for x in content] return content directions = { "R":(1,0), "U":(0,-1), "L":(-1,0), "D":(0,1) } def trac...
47f2b89847f119527187d506e78208eb31927163
ddarkclay/programming-cookbook
/Harry_Python/Alternate_create_object.py
496
4.21875
4
#Using this method we can create object of the class without using constuctor using class method class Employee: no_of_leaves = 8 def __init__(self,name,sal): self.name = name self.sal = sal def printdata(self): return f"Name is : {self.name} and Salary is : {self.sal}" @class...
1c33881e0cb47e2ef3af7b93a58a44c66f0c4cd8
saetar/pyEuler
/not_done/py_not_started/euler_601.py
729
3.9375
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # ~ Jesse Rubin ~ project Euler ~ """ Divisibility streaks http://projecteuler.net/problem=601 For every positive number n we define the function streak(n)=k as the smallest positive integer k such that n+k is not divisible by k+1. E.g: 13 is divisible by 1 14 is divisib...
6230eec59eb0a982abb427f55e4778202df44be5
srpanall/evaluate_expression
/evaluate_expression/expression_parser.py
1,628
3.6875
4
""" The overall intent of this package is to evaluate mathematical expressions input as strings. This module defines major functions required for evaluating the expression. """ import re from parser_math_functions import func_mapper from formatting_functions import initial_prep from arithmatic import evaluate_terms fr...
60ccac782a5aaba4a0de9cffcf3b9f72391f4cf0
garethmullins/Python-Week4Practicals
/woefullyInadequateSecurityChecker.py
579
3.96875
4
""" A woeful security checker that checks the input against a list of strings contained in the username.txt file. """ __author__ = 'Gareth' def main(): # access the usernames username_list = open('usernames.txt', mode = 'r') username = input("Username: ") access_granted = False # check if the u...
b629b37aa6a43f10df0a8826e29975794a8f2f06
AkazaAkane/other-projects
/practice/PCC chapter3/invitation.py
431
3.765625
4
list = ['Giao','Master of Shadow','Jumo','Kunkun'] print("Invitation list:" + str(list)) list[2] = 'Black' print("Invitation list:" + str(list)) list.insert(0,'huohua') print("Invitation list:" + str(list)) list.append('Jumo') print("Invitation list:" + str(list)) for i in range(len(list)-2): list.pop() prin...
f9c9662a4545e80056abfc9e022b9bff7c3edb4e
Hemalatha30/mycodewash
/02-GOTjson.py
883
3.71875
4
#!/usr/bin/python3 ''' Author Hemasnet@yhaoo.com +Learning GITjson.py''' # Pull in json so that we can parse json import json def main(): # open thejonsnow.json file in read mode with open("jonsnow.json", "r") as gotdata: jonsnow = gotdata.read() # create a string of all the json GOTpy = ...
aefaa53549cc812f6a71e8959a51b85c12bc3c0b
nagarathnahb/ShortestDistance-RobotTravel
/robotDistance.py
1,652
4.25
4
import math dest = [0,0] def keepGivingDist(): print('Do you want to keep the robot moving? (yes or no)') if input().startswith('y'): print('Enter the direction you want the robot to travel in from current position ({},{}): ' '(UP/DOWN/LEFT/RIGHT)'.format(dest[0],dest[1])) ...
7504e5a6f727e278042a97cfc2997b68d0ffd1ec
ohio-university-cs3560-spring-2019/homework-3-asharma1999
/homework5.py
282
3.609375
4
import sys line_count = sys.argv[len(sys.argv) - 4] word_count = sys.argv[len(sys.argv) - 3] character_count = sys.argv[len(sys.argv) - 2] print("Number of lines") print(line_count) print("Number of words") print(word_count) print("Number of characters") print(character_count)
827d8f932d01967cd127d37acddf0459b0552918
kimalaacer/Head-First-Learn-to-Code
/chapter 12/palindrome_oop.py
619
4.09375
4
# this is a re-code of palindrome using Object Oriented Programming. class PalindromeString(str): def is_palindrome(self): i = 0 j = len(self) - 1 while i < j: if self[i] != self[j]: return False i = i + 1 j = j - 1 re...
8ab5e8bc33ee3222aaf1703f29e707519df343b7
varunvjha/Lets-UpgradeVarun
/Day 3 - Assignment 1.py
192
3.84375
4
#!/usr/bin/env python # coding: utf-8 # In[2]: n = int(input("Enter a number ")) sum1=0 i=1 while i<=n: sum1= sum1+ i i = i + 1 print(f"Sum of {n} numbers = {sum1}") # In[ ]:
080853892bac81acc904c5e6e719b836abca3802
adityad30/Trees-5
/116PopulatingNextRightPointersinEachNode.py
1,521
4.09375
4
""" // Time Complexity :O(n) // Space Complexity :O(1) // Did this code successfully run on Leetcode : YES // Any problem you faced while coding this : NA //Explanation: if node has both left and right child; set node.left.next = node.right if node.next it means that node has sibling,so nod...
deb8b4768913f92a6bde05a8fcc63c0c30a7fb81
nmessa/Python-2020
/Lab Exercise 9.28.2020/demo2.py
250
4.03125
4
## Lab Exercise 9.12.2019 Demonstration 2 ## Author: nmessa ## calculates the sum of the odd numbers <= 1000 total = 0 for number in range(1, 1001): if number%2 == 1: total += number print("The total is", total)
b4313c4fd2a130bd5a4f8da190ffeaa9ab0173cd
Sum4196/pythonScripts
/duplicatesinlisthelpreference.py
88
3.75
4
print(list(set([word[i] for word in ['cat','dog','rabbit'] for i in range(len(word))])))
a61a1043904ea3b32f74ce1dfd44cedef7528890
Beatriceeei/introduction_to_algorithm
/chapter12/tree_successor.py
637
3.984375
4
# -*- coding:utf8 -*- from chapter12.tree_minimum import tree_minimum, tree_maximum from chapter12 import prev_tree def tree_successor(x): if x.right: return tree_minimum(x.right) y = x.prev while y and x == y.right: x = y y = y.prev return y # head = prev_tree() # print tree_...
daf0dbfc26c9cf6c7e37ce21df4b4c280ef8399f
jinurajan/Datastructures
/LeetCode/monthly_challenges/2020/october_2020/1_number_of_recent_calls.py
4,009
3.953125
4
""" Number of Recent Calls You have a RecentCounter class which counts the number of recent requests within a certain time frame. Implement the RecentCounter class: RecentCounter() Initializes the counter with zero recent requests. int ping(int t) Adds a new request at time t, where t represents some time in millis...
14f023546cc9708cf7477a9e39a52a4e867ac213
Devendra33/Machine-Learning
/Udemy ML (A-Z)/Regression/Random Forest Regression/Random_Forest_Regression.py
906
3.578125
4
# Random Forest: it is a version of Ensemble learning # Ensemble learning: it is a learing in which many algoritms or a algorithm used many times and we put them # together to do much more powerfull than original one. import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn.ensemble ...
5974a10818179df8a740dd7f0ada33e8b5237e50
Nataliodg/Python
/POO/ClaseVariables.py
2,242
3.6875
4
#1) #Definir una clase Cliente que almacene un código de cliente y un nombre. # En la clase Cliente definir una variable de clase de tipo lista que almacene todos los clientes que tienen suspendidas sus cuentas corrientes. # Imprimir por pantalla todos los datos de clientes y el estado que se encuentra su cuenta corrie...
803963481e8ecec4ebaadc060cc45bc3fdba1427
DipeshBuffon/python_assignment
/DT7.py
257
4.21875
4
#Write a Python function that takes a list of words and returns the length of the longest one. n=int(input("Enter a number:- ")) list=[] for i in range(n): str=input("Enter string:- ") list.append(str) list.sort(key=len) print(list[-1])
6e75240d83fc6ccc61ac7a3b92d1af7ae5cb07c1
sivajayaraman/Interview-Preparation
/palindrome.py
289
4.3125
4
string=raw_input("Enter the string to Check whether it is Palindrome:") string=string.casefold() rev_string=reversed(string) print("The reversed string is "+rev_string) if list(string)==list(rev_string): print("The String is a Palimdrome!") else: print("The sting is not a Palindrome!")
6f1ac4f657e3480affe534fa9b9cdbc27888e413
v1ktos/Python_RTU_08_20
/Diena_5_strings/uzd2_g1.py
874
3.734375
4
fraze = input("Ievadiet minamo frazi: ") new_fraze = "" for i in fraze: if i != " ": new_fraze += "*" else: new_fraze += " " print(new_fraze) burts = input("Ievadiet minamo burtu: ") while fraze.find(burts) > -1: nr = fraze.find(burts) print(nr) fraze = fraze.replace(burts, "+", 1) #...
f1568a4a09e935fe798075c18557d39b354ac9b6
pacifastacus/gepitan-ex7
/ex7/utils/find_closest_centroids.py
1,309
3.90625
4
import numpy as np def d(p1, p2): return np.sum((p2 - p1) ** 2) def find_closest_centroids(X, centroids): """ Computes the centroid memberships for every example idx = find_closest_centroids(X, centroids) returns the closest centroids in idx for a dataset X where each row is a single example. i...
944bc94973acf6ef98c0dcdc3e32958a619075c1
EduardF1/python_essentials
/advanced_topics/functions/sort_iterables.py
1,610
4.4375
4
# sort() method = used with lists # sort() function = used with iterables # students = ["Klaus", "Jürgen", "Fritz-Patrick", "Hermmann", "Patrick", "Sebastian"] # students = ("Klaus", "Jürgen", "Fritz-Patrick", "Hermmann", "Patrick", "Sebastian") # sort array items alphabetically # students.sort() # for i in students:...
b7e1622d2b84b7c6164e7e5b4e508ab6ee1865a5
DuandSu/cohort4
/01-getting-started/src/python/read_file.py
1,109
3.84375
4
print ("-------------------------------------------------------------------------------") f = open("syntax.in", "r") countLines = 0 countChars = 0 countElse = 0 # # Note: Could have used "f.readline(), but also included elegant alorithm for using # for/in. I am used to having to check for EOF, so this works well for m...
95f7741d16dd9558032c9886f4563e4e4f8e1fae
rishabh-1004/projectEuler
/Python/euler010.py
495
3.5625
4
import time def sumofprimes(n): primeList=[True]*(n+1) p=2 while(p*p<=n): if primeList[p]==True: i=p*2 while i<n: primeList[i]=False i+=p p=p+1 sum=0 for i in range (2,n+1): if (primeList[i]): sum=sum+i return sum if __name__ == '__main__': start=time.perf...
e24b68c56d4b915718b59e3cf0c5edf40c36e8b7
ceucomputing/olevel
/worksheets/13 - Source Files/13q7.py
114
3.984375
4
x = int(input("Enter a positive integer: ")) while x > 0: print("Siti") x = x - 1 print("Completed")
c5a6ba10c63d4fdf3b867b488fb755b4df67f37b
katger4/uwmediaspace
/save_updated.py
1,266
3.515625
4
#!/usr/bin/env python import pickle from datetime import datetime ############################################################ def load_pickled(filename): with open(filename, "rb") as fp: # Unpickling return pickle.load(fp) def write_pickle(item, filename): with open(filename, "wb") as fp: #Pick...
6c5744b5d3d0cc3c8c3e7c6610ce9f95b89f44cf
akashgkrishnan/HackerRank_Solutions
/ds/allPaths.py
968
3.546875
4
from collections import defaultdict, deque class Graph: def __init__(self, v): self.graph = defaultdict(list) def addEdge(self, u, v): self.graph[u].append(v) def solve(source, destination, edges, n): g = Graph(v) for u,v in edges: g.addEdge(u, v) visited = set() q =...
855617d58f62244366608fb595ab78442718bd09
gabriellaec/desoft-analise-exercicios
/backup/user_166/ch82_2019_06_07_00_54_13_959623.py
184
3.796875
4
def primeiras_ocorrencias(string): dic={} for letra in string: if letra not in dic: dic[letra]= 1 else: dic[letra] += 1 return dic
831e24314c151a64c1b6fd76b1d47ef999a7d8dc
myungwooko/algorithm
/medium/1106_5_**longest_palindromic_substring_jc.py
861
3.703125
4
""" 5. Longest Palindromic Substring Medium Input: "babad" Output: "bab" Note: "aba" is also a valid answer. Example 2: Input: "cbbd" Output: "bb" """ class Solution(object): def longestPalindrome(self, s): res = "" for i, v in enumerate(s): tmp = self.helper(s, i, i) if ...
6493cfa9c8fb80173f2f6ca223fb2a721bc24441
NishkarshRaj/Programming-in-Python
/Module 1 Assignments/assignment14_2.py
263
4.3125
4
print("Sum of n natural numbers") num=int(input("Enter an integer: ")) sum=0 if(num>0): for x in range (1,num+1): sum=sum+x print(("Sum of natural numbers till %d is %d")%(num,sum)) else: print("You entered non-natural number")
55f783e489aa4e73631d1f77e03a3c74a6ac4493
succinction/Python
/file_read_first_lines.py
216
3.59375
4
## 1 ############################################# filename = "hello_kitty.txt" def read_first(num): with open(filename, "r") as txt: lines = txt.readlines() print(lines[:num]) read_first(3)
7e1356f55a01801ef867689c3f4ba657c45375b2
Tonow/RSA_Tp
/trait_entier.py
1,635
3.5
4
""" Fichier: python 3. Ecrit par : Tonow Le : Date Sujet: TODO """ from binascii import unhexlify def long_to_bytes(val, endianness='big'): """ Use :ref:`string formatting` and :func:`~binascii.unhexlify` to convert ``val``, a :func:`long`, to a byte :func:`str`. :param long val: The value to p...
ef09c05e89cf585b977311f025c40a1c80dc7317
jeellee/tools
/mainshi_2022/decorator.py
3,841
3.515625
4
# coding: utf-8 """ 装饰器 decorator <b><i>hello</i></b> """ def decorator(func): def warp(arg): try: return func(arg) except: print('error') return warp @decorator def divide(a): return 100/a divide(0) # 1. 装饰两次 def say(): return 'hello' def make_blob(func): ...
a061a263b8002461da9fb5cda6de8689e02f513f
nindalf/euler
/03-primefactor.py
1,227
4
4
import math import timeit """ This method proved too slow. Better to set it to -1 rather than removing the value from the sieve list. try: sieve.remove(current) except ValueError: pass #its already been removed When the list is really long, resizing it appears to be too expensive. The program now "removes" numb...
cd9b2f08e05cc07a920365e923d5bf65ae3f71b4
nithinveer/leetcode-solutions
/Sentence Similarity.py
1,853
3.53125
4
from collections import defaultdict class Solution(object): def areSentencesSimilar(self, words1, words2, pairs): """ :type words1: List[str] :type words2: List[str] :type pairs: List[List[str]] :rtype: bool """ if words1 == words2: return True ...
c3f4c5a2b728bbfe971e1b66e123b805401631f3
bhaveesh09/CS362
/unitTest.py
899
3.75
4
from programs import palindrome from wordCount import wordCount import unittest class testPalindrome(unittest.TestCase): def test_palidrome(self): case = palindrome("WOW") self.assertEqual(case, True) def test_palidrome2(self): case = palindrome("NOT A PALINDROME") ...
b708d3fb8ed9b23736b536d97cf5e28b85231d8f
inder0198/pythonProject
/insert tkinter.py
1,869
3.953125
4
from tkinter import * wind = Tk() wind.title("project1") wind.geometry("350x350") def sq(): data = int(e1.get()) l3.delete(0, END) l3.insert(0, str(data * data)) def prime(): n=int(e1.get()) if n>1: for i in range(2,n): if n%i==0: l3.delete(0, END) ...
05dc44c0d4c02af0a9419328368fa7797fe26f65
xandaosilva/cursoLogicaProgramacao
/Python/Consumo/main.py
227
3.859375
4
distancia: int; combustivel: float; consumo: float; distancia = int(input("Distancia percorrida: ")) combustivel = float(input("Combustível gasto: ")) consumo = distancia/combustivel; print(f"Consumo medio = {consumo:.3f}")
96dda37f94a9fdee6ed581693dc615e82a4f65b2
BigBrou/Algorithm
/graph/graphdfs.py
771
3.640625
4
graph = { 1: [2, 3, 4], 2: [5], 3: [5], 4: [], 5: [6, 7], 6: [], 7: [3] } def dfs_recursion(v, discovered=[]): discovered.append(v) for w in graph[v]: if not w in discovered: discovered = dfs_recursion(w, discovered) print(discovered) return di...
298ba18c6939d5875cdaa58f7acb016abc745e1b
vasetousa/Python-Advanced
/Exams/Taxi-Express-Aug-2020.py
1,126
3.78125
4
from collections import deque customers = deque([int(el) for el in input().split(", ")]) # time it takes to drive the customer to his/her destination taxi_vehicles = deque([int(el) for el in input().split(", ")]) # time they can drive, before they need to refill their tanks total_time = 0 # values of all custom...
2c2ba51b6df3b6c4a17530e725df65d795fbc44f
premsub/learningpython
/mult.py
166
3.828125
4
from sys import argv def multiply(*args): a,b=args c=a*b return c arg1,arg2,arg3=argv arg2=int(arg2) arg3=int(arg3) d=multiply(arg2,arg3) print "the result is=",d
d8c7b5a95486185c48cd0d76774246ac46bab785
tyler-bateman/ProgressionGen
/chordstomidi.py
1,566
3.625
4
""" Provides functionality to convert sequences of chords in string format into midi files """ from mxm.midifile import MidiOutFile T = 48 V = 64 def str_p(p): """ Converts the character format of a note into its respective pitch class """ return 11 if p == 'E' else 10 if p == 'T' else int(p) def s...
e658725573e01f387752dea9401e0f25dc05527e
Lalit78716/Machine-Learning-Projects
/ML-Preprocessor-CLI/feature_scaling.py
5,875
3.515625
4
import pandas as pd from data_description import DataDescription from sklearn.preprocessing import MinMaxScaler,StandardScaler class FeatureScaling: tasks=[ "\n1. Perform Normalization (MinMax Scaler)", "2. Perform Standardization (Standard Scaler)", "3. Show the Dataset" ...
93665a25778130d8c6c7fe90876ce0b2e25e4c55
SergeyLazarevich/HomeworkPython
/урок_3/задача_4.py
1,103
4
4
def my_func_1(x, y): """ возведение в степень с помощью оператора ** """ return x**y def my_func_2(x, y): """ возведение в степень с помощью цикла """ rez=1 if y<0: y=abs(y) for i in range(0,y): rez*=x return 1/rez else: for i in rang...
b888c117b900426f01475d156943a0bd09b46ec9
serlabel/tuenti-challenge-6
/09/immiscible.py
736
3.765625
4
#!/usr/bin/env python3 def immiscible(x): # Remove 2-and-5-factors zeros = 0 while x%10 == 0: zeros += 1 x //= 10 if x%2 == 0: while x%2 == 0: zeros += 1 x //= 2 elif x%5 == 0: while x%5 == 0: zeros += 1 x //= 5 # i...
67eeebb164318eaee1a35bdfc3e135f51e2a614e
Fhernd/PythonEjercicios
/Parte002/ex1111_hackerrank_matriz_identidad_numpy_identity.py
395
4.1875
4
# Ejercicio 1111: HackerRank Crear una matriz identidad con la función identity de NumPy. # Task # Your task is to print an array of size X with its main diagonal elements as 's and 's everywhere else. # ... import numpy as np np.set_printoptions(legacy='1.13') if __name__ == '__main__': n, m = tuple(map(int,...
70b0e249a4eaaab75e43833f199f825f0088e0a0
jyoung2119/Class
/Class/demo_labs/PythonStuff/Sockets/5_2_19Projects/servName.py
307
3.71875
4
import socket #Prompt for port number and protocol portNum = int(input("Input Port Number: ")) proto = (input("Input Protocol: ")) #Get service name from port number and protocol service_name = socket.getservbyport(portNum, proto) print("Port: " + str(portNum) + " => service name: " + service_name)