blob_id
stringlengths
40
40
repo_name
stringlengths
5
119
path
stringlengths
2
424
length_bytes
int64
36
888k
score
float64
3.5
5.22
int_score
int64
4
5
text
stringlengths
27
888k
5258200a2df010cfe8c97672312f3aee060f09b1
cjqian/ucl-rl-course
/maze_solver.py
7,234
3.9375
4
"""maze-solver.py: Gives a path through an input maze.""" """ Exercise adapted from Introduction to Reinforcement Learning lectures: http://www0.cs.ucl.ac.uk/staff/d.silver/web/Teaching_files/intro_RL.pdf """ __author__ = 'cjqian@' import sys import unittest from collections import deque """ Coordinate vectors....
6c759f8ce6a213323cb7067faf692857985132d2
arunvijay211/pypro
/pallindrome.py
166
3.671875
4
M=input() N=M print("Input:") print(M) sum=0 while(M>0): mod=M%10 M=M//10 sum=sum*10+mod print("Output:") if sum==N: print("yes") else: print("no")
ec1d4c3b898db3d4abe6e027a8924f2315cfc652
caoxiaoliang/LeetCode
/addTwoNumbers
1,134
3.546875
4
#!/usr/bin/python3 class ListNode: def __init__(self, x): self.val = x self.next = None def addTwoNumbers(self,l1,l2): carray = 0 current = ListNode(0) self = current while(l1!=None or l2!=None): if l1 == None: x = 0 else: x = l1.val if l2 == None: y = 0 else: y = l2.val ...
07613200ab9fbff8a5fb1a4f54ff948bea60679c
EwertonSantos2003/Ewerton_Programas
/python/poligono.py
341
3.875
4
a = float(input('Informe um valor para A: ')) b = float(input('Informe um valor para B: ')) if ((a > 0) and (b > 0)): c = 30 elif ((a > 0) and (b < 0)): c = 0 elif ((a < 0) and (b > 0)): c = -1 else: c = a * b * (-1) pol = (a * a) + (2 * a * b) + (b * b) + (c * a * c) print('O resultado do po...
e8df45eaf63c318f9ea9f679a364df5a402f7c29
gptech/python
/ex43.py
5,093
4.03125
4
from sys import exit from random import randint #So go back over the excercise 43 in case you're wondering but Zed does define his classes from lines here. #Creates a scene object to be referenced later class Scene(object): def enter(self): print "This scene is not yet configured. Subclass it and implement enter(...
af2bf4f21ea7c56c293ec2c0ab20bb52bb71d222
noevazz/learning_python
/097_investigating_classes.py
840
3.921875
4
""" getattr() function gets the current value of an attribute, it takes two arguments: - An object, and its property name (as a string), and returns the current attribute's value; isinstance() function checks the type if given value is an X type """ class MyClass: def __init__(self): self.a = 1 ...
a4dffe4298737030cd78c92a33271bc1b27cc04f
elias-sundqvist/tif160-group-4-project
/buzzer/buzzer.py
1,335
3.84375
4
import RPi.GPIO as GPIO import time buzzer_pin = 13 def buzz(frequency, length): # create the function "buzz" and feed it the pitch and duration) if (frequency == 0): time.sleep(length) return period = 1.0 / frequency # in physics, the period (sec/cyc) is the inverse of the frequency (cyc/s...
432870120634e1d3c667bca146e26a06ea0a2147
llh911001/leetcode-solutions
/reverse_words.py
242
4.5
4
#!/usr/bin/env python # encoding: utf-8 """ Given an input string, reverse the string word by word. For example, Given s = "the sky is blue", return "blue is sky the". """ def reverseWords(s): return ' '.join(s.strip().split()[::-1])
0b23f47f5102d4a73375937cb0fff880892dde91
kaashdesai1/Leetcode-Problems
/Search a 2D Matrix/solution.py
1,097
3.578125
4
class Solution: def searchMatrix(self, matrix: List[List[int]], target: int) -> bool: oneLine = self.searchVertical(matrix, target) print(oneLine) if oneLine is None: return False return self.searchHorizon(oneLine, target) def searchHorizon(self, line, target...
a3c2d944b36e7f68de42edcb767e8cda994ec1c9
nisacharan/algods
/LinkedLists/04_kRotate.py
467
3.796875
4
# This function should rotate list counter- # clockwise by k and return head node def rotateList(head, k): # code here currPntr = head #connecting last & first nodes while(currPntr.next!=None): currPntr=currPntr.next currPntr.next = head #go to kth node & break the chain currPnt...
9215c64666042bc9c982a0ab13b55f02a015d139
XIZEN7/gof
/papeles.py
2,224
3.90625
4
from abc import ABC, abstractmethod # Documentos nesesarios para ingresar a la universidad class Cedula(ABC): def implementacion(self): print("Fotocopia cedula") @abstractmethod def operacion(self): pass class Icfes(ABC): def implementacion(self): print("Puntaje icfes") ...
05fd244b78eeb12c3eac29fc8545d22acefb30c4
AndraPop29/Faculty
/Programmng Fundementals/laborator 2/f_functii.py
4,922
3.53125
4
from f_variabile import * from f_functii_secundare import * def ui_1(l): #descriere:adauga/insereaza un elev nou in lista #date int: reprezentand lista elevilor #date out:lista de elevi modificata dupa voia utilizatorului global y global n n=n+1 a=input("doriti sa adaugati un elev? ...
fb3943f6597791c537e94647203efca98f4f9adc
robertoffmoura/CrackingTheCodingInterview
/Python/Chapter 16 - Moderate/q11.py
322
3.71875
4
def divingBoard(shorter, longer, k): current = k * shorter result = [current] for i in range(k): current += longer - shorter result.append(current) return result def divingBoard2(shorter, longer, k): return [(k-i)*shorter + i*longer for i in range(k+1)] print(divingBoard(1, 3, 2)) print(divingBoard2(1, 3, 2)...
a7fe0563141a14dfba2ef4677dc11bbfd0b0b635
Saman-Afshan/Practice_automation
/Screenshot.py
707
3.546875
4
from selenium import webdriver class Screenshot: def scrnsht(self): driver = webdriver.Chrome(executable_path="F:\\Selenium_Pyhton\\chromedriver.exe") url = "https://www.amazon.com/" driver.maximize_window() driver.get(url) # to take screenshot driver.get_...
26e42c8be48e5430d268990940c6022243d5045b
call22/python2JS
/test/kmp.py
1,031
4.0625
4
print('Please input a pattern string:') pattern_istr = input() print('Please input a main string:') main_str = input() m_len = len(main_str) p_ilen = len(pattern_istr) if(p_ilen == 0): if(m_len == 0): print(0) else: print('Error: Pattern string cannot be an empty string.') else: pattern_str...
e36d791efa355218708c502c71eac679c488af8e
danielleappel/Numerical-Integration
/first_order_comapre.py
1,553
3.59375
4
import numpy as np import matplotlib.pyplot as plt from eulers_forward import eulers_forward from eulers_backward import eulers_backward import math # The differential equation to examine def f_prime(x, y): return x + 2 * y # The solution to f_prime def f(x): return -(2*x + 1)/4 + (5/4)*math.e**(2*x) # Set u...
5484201d951300fd3165f2e1af4dc4f10aff5c07
293660/DailyComit
/Dictionary/nested dict.py
125
4.15625
4
print("To convert list into a nested dictionary of keys") l=[1, 2, 3, 4] d=t={} for i in l: t[i]={} t=t[i] print(d)
c42869a5b6d2d2052c01b7305b35f59a03b2064a
YunJ1e/LearnPython
/DataStructure/Probability.py
1,457
4.21875
4
""" Updated: 2020/08/16 Author: Yunjie Wang """ # Use of certain library to achieve some probabilistic methods import random def shuffle(input_list): """ The function gives one of the permutations of the list randomly As we know, the perfect shuffle algorithm will give one specific permutation with the probabili...
4d0c8ef72a06307470360498fafe1717e5d9c1b3
felipellima83/UniCEUB
/Semestre 01/LogicaProgramacao/Prova1_Altair_Andre_Felipe/while_if_2_pedra_papel_tesoura.py
2,131
4.09375
4
#Curso: Ciência da Computação #Professor: Antônio Barbosa Junior #Disciplina: Lógica de programação #Alunos: Altair Correia Azevedo, André Luiz Vieira Mostaro e Felipe Ferreira Lima e Lima # While com if dentro 02 # JOGO PEDRA, PAPEL OU TESOURA - este programa recebe um número referente a uma opção e retorna o resulta...
8a8722d392aa70da52445342e3bea88b50c2ae41
zhlinh/leetcode
/0136.Single Number/solution.py
692
3.828125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' ***************************************** Author: zhlinh Email: zhlinhng@gmail.com Version: 0.0.1 Created Time: 2016-03-16 Last_modify: 2016-03-16 ****************************************** ''' ''' Given an array of integers, every element ...
7ae09ad099de3c81a4f91e2eaa2d84bc2b67bc2e
pawelpe90/self-taught-programmer
/rozdzial_15/python_lst272.py
1,006
3.625
4
class Card: suits = ["pik", "kier", "karo", "trefl"] values = [None, None,"2", "3", "4", "5", "6", "7", "8", "9", "10", "waleta", "damę", "króla", "asa"] def __init__(self, value, suit): """listy suit i value to liczby całkowite""" self.value = va...
ce91948bfb1a6032c391b98d3cf381e030ec5807
jaabberwocky/leetcode
/ctci/ch1_arraysAndStrings/4_palindrome_permutation.py
1,271
4.28125
4
import unittest def palindrome_permutation(s: str) -> bool: """ Given a string, write a function to check if it is a permutation of a palindrome. A palindrome is a word or phrase that is the same forwards and backwards. A permutation is a rearrangement of letters. The palindrome does not need to be li...
aa16a53b1b5b6b0df0328c78d85983200eca4f1d
bsimmooes/cei_import
/cei_import.py
10,727
3.515625
4
class ImportCei: """Script to generate the stocks' descriptions to use in "Declaração de Imposto de Renda Pessoa Física (DIRPF)" through CEI's reports. Help to fill the "Fica de Bens e Direitos. This class receive one specific file, that have some user informations about your stocks wallet. Th...
79ee838a3215e774ab44b185c9deb018e905a87a
caipen/CoKE
/corerank/corerank.py
5,755
3.796875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import math import copy import argparse import igraph # Reimplement min heap according to Introduction to Algorithms (3rd Edition). # Python heapq is great, however, it's necessary to track def parent(i): return (i - 1) // 2 def left(i): return 2 * i + 1 def right...
2bc1fbb19e7f029c3fe8bf6e59fa2f7ee7101d5b
subbuinti/python_practice
/dictonaries/wordcount2.py
258
3.703125
4
words = {} for str in input().split(): word = ("".join([ c if c.isalnum() else "" for c in str ])) if word not in words: words[word] = 1 else: words[word] += 1 for word in sorted(words): print(word, ": ", words[word], sep='')
896c5eefdd27787f0349926f5e098a9530ed8508
brosenberg/dnd
/magic-item-gen/pathfinder/magic_item_gen.py
2,225
3.53125
4
#!/usr/bin/env python import argparse import json import random import re def roll_table(table): table_max = sum(table.values()) roll = random.randint(1, table_max) current = 0 for i in table: current += table[i] if current >= roll: return i return None # Why store yo...
76809a22356bf42dd34f708d951328a84a62a880
strawsyz/straw
/ProgrammingQuestions/leetcode/854.py
1,501
3.703125
4
class Solution: def kSimilarity(self, A: str, B: str) -> int: # 字符串A和B def bfs(A_part): i = 0 while A_part[i] == B[i]: i += 1 for j in range(i + 1, len(A_part)): if A_part[j] == B[i]: # 如果找到了相同的字 ...
7fddd864e3427631ccbed359b786d3e9f9fe45ef
christensonb/Seaborn
/seaborn/sorters/sorters_2.py
2,573
3.796875
4
""" This just contains some standard functions to do sorting by """ __author__ = 'Ben Christenson' __date__ = "8/25/15" from random import random, seed class by_key(object): def __init__(self, keys): self.keys = isinstance(keys, list) and keys or [keys] def __call__(self, obj1, obj2): for key ...
677782a8ec2222c7bc07e148ae56fd401c590ddb
cristobal-Diaz/proyecto-1
/pr/hipotesis_2.py
1,085
3.578125
4
#Comparacion en los indices de obesidad entre LATAM - EEUU import pandas as pd import matplotlib.pyplot as plt #Crea un Data Frame del archivo csv def makeData(): data = pd.read_csv('suministro_alimentos_kcal.csv') return data def obesitypp(fila): perso = (fila["Obesity"]*fila["Population"])/100 ret...
f439f615537c72ce7163db404b28ecaba89c336a
ramtiwary/week_1
/wordlong.py
237
4.0625
4
def word_longest_length(word_list): word_length = [] for n in word_list: word_length.append((len(n),n)) word_length.sort() return word_length[-1][1] print(word_longest_length(["Python","Java","Azure"]))
549410b9c21d5974a8527b2cbef90fe813362fdf
ali-mahani/ComputationalPhysics-Fall2020
/PSet1/P4/classes/types.py
1,467
3.75
4
"""Define the types of Game of Life (GoL) initial conditions""" import numpy as np def loaf(): """Create the canvas with the initial values of the loaf""" canvas = np.zeros(shape=(6, 6), dtype=int, order='F') # make the loaf canvas[1][2] = 1 canvas[1][3] = 1 canvas[2][4] = 1 canvas[3][4] ...
2dfdb18800c5a5c2226d4fa6e90670f6b55956f0
ShreeyashPacharne/Rock-Paper-Scissors-Game
/rock_paper.py
1,596
3.875
4
import random a = ['rock' , 'paper' , 'scissors'] print("\nWelcome to the Rock Paper Scissors Game!\nHere you will compete with the computer") print("\nChoose any [R]ock , [P]aper , [S]cissors") name = input("\nPlease enter your name: ") comp_point = 0; user_point = 0; i = 0 while i<5: user = inp...
fb9ef5b3e901ac74579cc1de6c0c5bda98a7ce06
smarthitarth/python-scripts
/BitwiseANDforRange.py
1,214
3.734375
4
# -*- coding: utf-8 -*- """ Created on Tue Apr 28 14:05:29 2020 Given a range [m, n] where 0 <= m <= n <= 2147483647, return the bitwise AND of all numbers in this range, inclusive. @author: hitarth """ def msb(n): msb_p = -1 while (n>0): n = n >> 1 msb_p += 1 return msb_p def andOp(x, y):...
7d6860d5250092a2032197aff72f0bc5d8ff6b88
JosephLevinthal/Research-projects
/5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/225/users/3987/codes/1714_2525.py
66
3.78125
4
n= int(input("numero inteiro")) while(n < 1 and 1 > n): if(n%)
fae61f73e8d75c6152cd969bbcfd36fbecce99ce
minhvip2001/pythonproject
/Week1_PyThonBasic/Beginner/Exercise15.py
177
4.1875
4
def exponent(base, exp): result = 1 while exp > 0: result = result * base exp = exp - 1 print(base, "raises to the power of", exp, "is: ", result) exponent(5, 4)
9b1ddf2931914f5283c6b0c895cc8977e1dd1377
LambertlLan/python
/day05(列表、for、while、if、格式化)/input.py
119
3.671875
4
death_age = 80 input('name:') age = int(input('age:')) print('live:',death_age - age,'years') #不同类型不能运算
97fa29bde987e93950f5d4caadc54c3f499c1c22
amalfiyd/explore-repo
/12 - Python Algo and DS/Python Algo and DS/linkedList.py
2,167
4.28125
4
# Main class of LinkedList class LinkedList: # Initialization # Initialize the linked list with head == None def __init__(self): self.head = None # Print # Print through the elements of the linked list def print(self): pointer = self.head while pointer: print...
76dc9978caa0ce663ca8d5ff38f0e0888d22c6be
Zafarbek1097/python1
/2_dars.py
3,036
3.90625
4
# #o'zgaruvchi bu xotiraning nomlangan qismi # #int,float, string, list, dict # a = float(input('Shu yerda qiymat kiriting:')) # print(a) # #if shart operatorlari # b = float(input('2-sonni kiriting:')) # if a < b:#bu 1-shart # print("a b dan kichik")#shart tanasi # elif a > b:#bu shart 2 # print("a b dan katt...
acfbe90f2cda98e078d5272751158a1fc2d98d02
zhenggang587/code
/leetcode/ValidParentheses.py
592
4
4
class Solution: # @return a boolean def isValid(self, s): stack = [] map = {'[': ']', '{': '}', '(': ')'} for c in s: if not stack: if c not in map: return False stack.append(c) continue ...
70d40524661d3312eabc4059e9ed102e0d54d309
chenyun8019/py_study
/study/解包.py
291
3.578125
4
''' author:chenyun func:解包 ''' def get_name(a,b,c,d,e): print('a=',a) print('b=',b) print('c=',c) print('d=',d) print('e=',e) # name = ('孙悟空','唐僧','猪八戒','沙和尚','白龙马') # get_name(*name) a = ['赵','钱','孙','李','陈'] get_name(*a)
ac7ae09c36efbd1512057b1a0643572464441383
Ulysses-WJL/study
/interview/a.py
912
3.625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' Author: ulysses Date: 2020-09-10 18:05:37 LastEditTime: 2020-09-10 18:24:35 LastEditors: ulysses Description: ''' class Solution(object): def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] ...
3484c1f9116d7c9afb58a877bb484dca7a7a32ac
ankit1765/ProjectEuler_Problems
/Q#5.py
356
3.78125
4
#Question No. 5 #Ankit Mittal factors = range(20, 0, -1) # remove factors that are even divisors of larger ones. for factor in factors: for divisor in range( 1, factor ): if divisor in factors: if factor % divisor == 0: factors.remov...
2b3fce7d45c51ecff4baf7a7e32c9705f0ebebc7
JariGitmanen/python-commands
/duprem.py
195
3.921875
4
def no_duplicate(l): dup = [] [dup.append(x) for x in l if x not in dup] return dup a= input("Enter a sentence with duplicates: ") a=' '.join(no_duplicate(a.split())) print(a)
7f886e730029194cd64e7dd5353528aa78118549
the-pedropaulo/Repositorio-Pedro
/programatrabalho.py
4,308
4.25
4
# BIBLIOTECA PARA LIMPAR A TELA import os # MENU PRINCIPAL - INVOCADO NA ULTIMA LINHA PELO CÓDIGO -> menu() def menu(): print("### Calcular a quantidade necessária de metros de fio - 1") print("### Calcular a quantidade necessária de tinta - 2") print("### Sair - 3") opcao = int(input("Digite a opç...
e9fc76a05acb15a5fdf83332d8a226813ff7ec46
Shady-Data/05-Python-Programming
/studentCode/EmployeeClass.py
1,488
4.625
5
''' 4. Employee Class Write a class named Employee that holds the following data about an employee in attributes: name, ID number, department, and job title. Once you have written the class, write a program that creates three Employee objects to hold the following data: ​ Name ID Number ...
6cb989bafd76f2493a293a44fe57c1938710f9a9
shufay/CS2
/suung-cs2week3/warmup/ms.py
2,045
4.1875
4
''' 'gameboard' is the 2D string matrix representing the game board. It is a 2D numpy array. The function 'reveal' takes as arguments the 'click' x and y positions and reveals the board. To run, cd into the same directory and type 'py ms.py <x> <y>' into the terminal. <x> and <y> are the coordinates to be revealed....
a60a6d27fafca7bf7309d73b83ac9b5410913ab4
chazingtheinfinite/project_euler
/code/large-sum.py
474
3.5
4
#!/usr/bin/python """ Large Sum Author: Kevin Dick Date: 2018-09-25 --- Work out the first ten digits of the sum of the following one-hundred 50-digit numbers. """ num_file = '../data/large-sum.txt' nums = [] f = open(num_file, 'r') for line in f: nums.append(line.strip()) f.close() def brute_force(): total = 0 for...
38c293264e48280645af70ca23b4f18835bce8ce
StanfordVL/CS131_release
/fall_2019/hw0_release/imageManip.py
4,496
3.90625
4
import math import numpy as np from PIL import Image from skimage import color, io def load(image_path): """Loads an image from a file path. HINT: Look up `skimage.io.imread()` function. Args: image_path: file path to the image. Returns: out: numpy array of shape(image_height, imag...
95c68bdc977eac35938c4a4e96131d7cad322b23
ryanpinnock10/Dijkstra-s-Algorithm
/makePathString.py
1,816
4.21875
4
#!usr/bin/env python3 # Ryan Pinnock # Date: 12/12/2019 # Class: CSC- 321A # Professor: Salvador # Assignment: Implement a working version of Dijkstra's Algorithm following the implementation # guidelines shown in the Textbook and in the slides, subject to the following conditions: # The program should take a direc...
7daaa922ca91469e5f6d7574394706e8c2ca15cd
forlink/CSV_Toolkit
/csv_toolkit/csv_sort.py
709
4.03125
4
import csv import csv_converter # sort the csv file by certain column to put the similar record together for further analysis def sort_csv_byColumn(in_file, out_file,column_name): with open(in_file, 'rb') as f: reader = csv.reader(f, delimiter=',') fieldnames = next(reader) reader = csv.Dic...
dce55f5be83596aa3c00015eebfd2fd5f4d2cd98
madokast/pythonLearn
/WorkStation/Tools.py
1,080
3.71875
4
import time def currentTimeMillis(): """ 和 Java 方法 System.currentTimeMillis() 一样 :return: 自1970年某时开始的毫秒数 """ return int(time.time() * 1000.0) class Timer: __invokeTimes = 0 __startTime = 0 __StopTime = 0 __time = 0 @classmethod def invoke(cls): cls.__invokeTimes ...
2a604ebfea08c0ce7c402d5913c50aba3dc2dbc0
jakeee51/GeoLiberator
/GeoLiberator_Demo.py
1,573
3.65625
4
# -*- coding: utf-8 -*- ''' Author: David J. Morfe Application Name: GeoLiberator Demo Functionality Purpose: Demonstrate the address parsing module 'GeoLiberator' Version: Beta ''' #Single Address Test #Upload file for multiple addresses #Display liberated output from GeoLiberator import * import time ...
32629696b985351380a32440c1c8333c3325c0cb
pmd3d/Morse-Code-Translator
/translator.py
939
3.96875
4
#!/usr/bin/python # -*- coding: utf-8 -*- #convert a string of input text to morse code import serial #morse code array morseDict = { 'a':'13', 'b':'3111', 'c':'3131', 'd':'311', 'e':'1', 'f':'1131', 'g':'331', 'h':'1111', 'i':'11', 'j':'1333', 'k':'313', 'l':'1311', 'm':'33', 'n':'31', ...
3aa3e821bab48c98bff0d0a78b2066d831365746
karkonio/first_module
/vault77/levak/pao.py
359
4
4
a = input('a: ') a = int(a) b = input('b: ') b = int(b) math = input('Opeaziya(+ - * /): ') if math != '+' and math != '/' and math != '-' and math != '*': math = input('Neizvestaya operatsiya( + - * / ): ') if math == '+': print(a + b) if math == '-': print(a - b) if math == '*': print(a ...
3637d971d3a7e49950c896cd375b9fda4659f9ac
joeljsv/hacktober2021
/Python_codes/palindrome_string/palindrome.py
263
4
4
string=input("Enter a string:") length=len(string) mid=length//2 rev=-1 for a in range(mid): if string[a]==string[rev]: a+=1 rev=-1 else: print(string,"is a palindrome") break else: print(string,"is not a palindrome")
b5bcf9ebb8a2f6cc54b14987bd9466ea18ecebfb
opeolusola/postalProject
/definedFunctions.py
603
3.625
4
import requests as rq import pandas as pd, os #create a function that takes in one parameter which is postcode and extract city from the result of API call def getCity(postcode): #get the dynamic endpoint into a variable: end_point end_point = f"https://api.postcodes.io/postcodes/{postcode}" #store ...
04545c8427f280c89e5579a127a0df703fc4fb37
rafaelperazzo/programacao-web
/moodledata/vpl_data/303/usersdata/278/83257/submittedfiles/testes.py
213
4.03125
4
n = int(input("Digite um número não negativo: ")) while (n<0): n = int(input("Digite um número não negativo: ")) f=1 i=0 for n in range (0,n,-1): while (n>=i): f=1*n i=+1 print(f)
8c0fa609c7e87762011ba7a8edfa35e078a0847b
daniel-reich/ubiquitous-fiesta
/b67PHXfgMwpD9rAeg_8.py
149
3.84375
4
def plus_sign(txt): if txt[0]==txt[-1]=='+': return all(txt[i-1]==txt[i+1]=='+' for i in range(len(txt)) if txt[i].isalpha()) return False
e366499040b48c6f38355f40250cb4d9f36bdc5c
jcreighton669/Coffee-Machine
/Problems/Vowels and consonants/task.py
210
4.03125
4
consonant = "bcdfghjklmnpqrstvwxyz" vowels = "aeiou" string = input() for ch in string: if ch in consonant: print("consonant") elif ch in vowels: print("vowel") else: break
6614c426862499b09a994968ee7d2d14e374b6ba
jazdev/libLAFF
/laff/gemv.py
4,228
3.671875
4
from numpy import matrix from numpy import shape from numpy import transpose def gemv(trans, alpha, A, x, beta, y): """ Compute y := alpha * A * x + beta * y x and y can be row and/or column vectors. If necessary, a transposition happens with those vectors. """ """ Che...
cc29e9dbe103576e7dfb9a16b18adc528b5db6b9
nhsconnect/integration-adaptors
/pipeline/scripts/tag.py
1,431
3.671875
4
"""A module that provides functions to generate tags suitable for identifying specific CI/CD builds.""" import argparse def generate_tag(branch_name: str, build_id: str, git_hash: str) -> str: """Generate a build tag from the provided values. :param branch_name: The name of the branch this build is being pe...
8a309ef929ed5a26e0cb9f74bdf42dad6adf1502
bertohzapata/curso_python_uptap
/11-Diccionarios/ejercicio.py
639
3.9375
4
# A partir de un diccionario con 3 materias definidas # Solicita al usuario las calificaciones # y muestra los resultados de calificación por materia # así como su promedio import random materias = {"Programación web": 0, "Bases de datos": 0, "Fundamentos de prog.": 0} promedio = 0 print(materias) for asignatura, cal...
a8980e0a7af103f3ed6b21254fdcb465dedfe7d9
dogppatrick/python
/basic_class/c0214_class.py
1,077
3.671875
4
class Account: def __init__(self, no, balance=0): self.no = no self.balance = balance def dp(self, n): try: if n <= 0: raise ValueError self.balance = self.balance + n except ValueError: print("value error") def wd(self, n...
9aac6ddf3fd4e16c4ce94d8ac9f3d69d63d6ac4b
johnny1112/johnnycodd
/even.py
184
4
4
strating range= int(input("Enter the starting range: ")) ending range = int(input("Enter the ending range : ")) for i in range(starting range,ending range+1); if(i%2 == 0); print(i);
63047a4a7fc317254b5e7f944099d16e83a91de4
tanupat085/labs
/first.py
316
3.65625
4
from tkinter import * from tkinter import ttk def hello(): print('Hello world') print('Uncle Engineer') #main GUI = Tk() #title GUI.title('Basic GUI') #Setup paper GUI.geometry('500x500') #create butt BT1 = ttk.Button(GUI, text = 'Hello' , command=hello) BT1.place(x=250 , y=250) GUI.mainloop()
58f4edd08ab2ba418a5c3a09af80cb266c34ed88
hugo-wsu/python-hafb
/Day4/raise_to.py
591
3.796875
4
#!/usr/bin/env python3 """ Author : hvalle <me@wsu.com> Date : 8/12/2021 Purpose: Function Factory """ def raise_to(exp): def raise_to_exp(x): return pow(x, exp) return raise_to_exp # no () # -------------------------------------------------- def main(): """Make your noise here""" square =...
400f84f6fd8484a2d52d36d50b87a82abf4c101e
sharan-patil/programs
/Python Files/sqrt.py
298
3.796875
4
from sys import argv def fail(): print "The given number is not a perfect square!" exit(0) name, num_char = argv num = int(num_char) i = 1 while i != num: if i * i == num: break i = i + 1 if i == num: fail() break print "The square root of the given number is %d" % i
3c7f3cd01606bea0f82e87e42557989a37ca07ef
rafaelperazzo/programacao-web
/moodledata/vpl_data/148/usersdata/276/87535/submittedfiles/testes.py
182
3.71875
4
# -*- coding: utf-8 -*- #COMECE AQUI ABAIXO n = int(input('Digite o valor de n: ')) soma = 0 while (n>0): ultimo = n%10 soma = soma +ultimo n = n//10 print (soma)
098cc41b86c0e44f0c8297fa83ebdc32bf77c4fc
crisfelip/programacion1
/clases/clasesyobjetos/ejercicioclaseanimal.py
1,295
3.96875
4
class Perros(): '''esta es la clase perros puedes ver muchas caracteristicas de cada perro que este en la pase de datos ''' def __init__(self, razaentrada,tipodepeloentrada,estaturaEntrada,nombreEntrada,pesoentrada,edadEntrada): print (' soy un perro nuevo que habla con tigo jejeje...') s...
c4645a0e2713b81af79d019d126a38a7681fc915
Her204/Start_Code
/practica-en-python/excercises/excersise01.py
366
3.875
4
import excercise as ex def recursive_computer_lenguage_translator(z): if z == "": b = "" return b else: b = str(hex(ord(z[0]))) return b + " " + recursive_computer_lenguage_translator(z[1:len(z)]) a = input("Enter a input--") print(recursive_computer_lenguage_translator(...
f9dd74f2b5c9e99e0d7dac15c6176322c9395c20
shreykhare/LeetCodeSolutions
/InterviewBit/hash/longest_consecutive_sequence.py
1,873
3.90625
4
""" Longest Consecutive Sequence Problem Description Given an unsorted integer array A of size N. Find the length of the longest set of consecutive elements from the array A. Problem Constraints 1 <= N <= 106 -106 <= A[i] <= 106 Input Format First argument is an integer array A of size N. Output Format Retu...
420e18444178522d58a5c5f03be5ea09a331606f
lucasffgomes/Python-Intensivo
/seçao_05/exercicio_seçao_05/exercicio_17.py
650
4.09375
4
""" Faça um programa que calcule e mostre a área de um trapézio. Sabe-se que: A = ((basemaior + basemenor) * altura) / 2 Lembre-se a base maior e a base menor devem ser números maiores que zero. """ print() print("Vamos calcular a área de um trapézio.") base_maior = float(input("Digite o valor da base maior: ")) ba...
9f22a7971428a51cb11273711bdf85d63f25116f
krohak/Project_Euler
/LeetCode/Medium/BT Preorder Inorder/save/sol1.py
1,023
3.671875
4
class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def __init__(self): self.pre_index = 0 def buildTreeRecCaller(self, preorder, inorder): in_start = 0 in_end = len(inorder)-1 tree = self.buildTr...
6e1437dabd22b4156d35bba2ecbfbd5501e49046
szolnik3/Robots-and-Human-Rights
/human_rights_checker/Amendment_2.py
1,006
3.75
4
""" From the US Constitution Amendment II: A well regulated Militia, being necessary to the security of a free State, the right of the people to keep and bear Arms, shall not be infringed. Algorithm: Checks if agent's actions hinder or prohibit... 1. anyone from purchasing or owning a firearm... (as long as, that fir...
16cea49723d3acec7f4e4a502783279c6c9c8d84
liquidjoo/coding
/p/10809.py
263
3.546875
4
a = input() wordlist = [-1 for k in range(ord('a')-97, ord('z')-96)] for i in range(int(a.__len__())): index = ord(a[i]) - 97 if wordlist[index] == -1: wordlist[index] = i for j in range(int(wordlist.__len__())): print(wordlist[j], end=" ")
b99160abb4362b49bf682e5207057081cd3c74b0
lukasmartinelli/sharpen
/challenges/trees/count_inversions.py
1,839
3.703125
4
""" Given an array A, count the number of inversions in the array. Formally speaking, two elements A[i] and A[j] form an inversion if A[i] > A[j] and i < j """ class TreeNode(): def __init__(self, val, idx): self.val = val self.idx = idx self.left = None self.right = None def ...
6520f99985b5c4b2f9ed8efece7a5affeb19f89d
vlong638/VL.Python
/0.Basis/3.Algorithoms/Completed/2.114.不同的路径.py
1,257
3.828125
4
import datetime class Solution: #有一个机器人的位于一个M×N个网格左上角(下图中标记为'Start')。 #机器人每一时刻只能向下或者向右移动一步。 #机器人试图达到网格的右下角(下图中标记为'Finish')。 #问有多少条不同的路径? """ @param n and m: positive integer(1 <= n , m <= 100) @return an integer """ def uniquePaths(self, m, n): # write your code here x=0 y=...
6ab8da606c28c01e80d9a6d887960bf6a0c2545f
Sahu-Ayush/Python-Programs
/Order Linear Search.py
324
3.890625
4
# Array must be sorted def OrderLinearSearch(arr, n, data): for i in range(n): if arr[i] == data: return i elif arr[i] > data: return -1 return -1 num_ele = int(input()) arr = [int(x) for x in input().split()] data = int(input()) print(OrderLinearSearch(arr, num_ele, da...
ba0fd228666bbc4c67889082c22f390b665022b7
msllc/tutorial-python-tools
/Prime.py
432
3.90625
4
from math import sqrt def isPrime(number): if number <= 1: return False elif number == 2: return True elif number > 2: for i in range(2, int(sqrt(number))): if number % i == 0: return False return True def test_small_2(): assert isPrime(2) =...
a9310a6c761b62c0e5c93ecb14a3d72564098c5b
prakyath-arya/MACHINE-LEARNING
/decisionTreeClassification.py
1,242
3.65625
4
# -*- coding: utf-8 -*- """ Created on Fri Apr 3 16:40:39 2020 @author: arya """ #import packages import pandas as pd from sklearn import tree #title print('THIS IS A DECISION TREE CLASSIFICATION ALGORITM TO PREDICT IF X CAN WIN A TIC-TAC-TOE MATCH OR NOT BASED ON THE X-O-X TABLE') #import dataset d...
8566260a56d7460df40c9fe900deddc4c873deb1
muzindahub-2018-01/Thamue
/Project_Quiz 2.py
7,625
4.09375
4
import time wrong = 0 right = 0 question_number = 0 name = str(input("WHAT IS YOUR NAME?")) print( name + " SO YOU THINK YOU ARE SMART? " ) input("Press<Enter>") print(""" INSTRUCTIONS 1.Answer all ten questions correctly. 2.Use upper or lower case for the letters A,B,C,D or type the correct answer. """)...
cded0ff2f1dcea86cc837288d750959b394cda3f
ZhenyingZhu/StudyNotes
/python-example/Financial/week1.py
2,352
4.03125
4
from utils import calculator # Video 1: Path to Financial Security # compond growth rate growth_rate = 0.087 # Ron start saving $2000 per year since his age 21 to 31, and then stop saving more until age 55. ron_money = 0 for _ in range(21, 31): ron_money *= 1 + growth_rate ron_money += 2000 for _ in range(31...
7bca3e1cdc998f9b976bd2b69458de135902478b
Viteac/Database_of_people
/people_final_menu_edit.py
4,427
3.84375
4
import sys people = {1: {'name': 'John', 'surname': 'Mclachan', 'age': '27', 'city': 'London', 'sex': 'Male', 'married': 'Yes', 'phoneNo': '072374753'}, 2: {'name': 'Marie', 'surname': 'Rose', 'age': '22', 'city': 'London', 'sex': 'Female', 'married': 'No', 'phoneNo': '072374753'}, 3: {'name': 'Lun...
0cf6cce1d8545112cfdc08db18680d4e1e6ea7d0
NeonedOne/Basic-Python
/Second Lab (2)/16.1. bf.py
690
3.546875
4
# Алексей Головлев, группа БСБО-07-19 tape = [0 for _ in range(30001)] position = 0 f = False s = False for cmd in input(): test = tape[position] if cmd == '[': f = True elif cmd == ']': s = True elif f and not s and cmd == '-': tape[position] = 1 if f and s: f = Fal...
94bf3226b56be7e15412d4f71ef91ce22429aac4
MarinellaSimone/Python_Basics
/Exercises/Esercizi 5 Marinella Simone.py
1,291
3.8125
4
#!/usr/bin/env python # coding: utf-8 # In[3]: #Homework2 # In[9]: #Creo una matrice 3x3 con valori compresti tra 0 e 8 import numpy as np np.arange(9).reshape(3, 3) # In[21]: #Creo un vettore random con 30 elementi e trovo il valore medio a = np.random.rand(30) # In[22]: a # In[24]: np.mean(a)...
7b32c55a90309e4b8e658c6108dac9952df5a462
pooja89299/loop
/star.py
565
3.875
4
# n=int(input("enter the number")) # i=1 # while i<n: # j=1 # while j<i: # print("*"*j,end="") # j=j+1 # print() # i=i+1 # num=int(input("enter the num")) # if num>10: # print("your gessing low") # elif num==10: # print("your gesing equal") # else: # print( "your gessing hi...
4343ef849735d75c055341c6ad1df0d534f20158
mraniketr/HangMan
/final.py
3,144
4.1875
4
from tkinter import * import random, sys from typing import List root =Tk() # TODO try to load these from a text file WORD_LIST = [ "lion", "hippopotamus", "zebra", "leopard", "elephant", "jackal", "sealion", "bluewhale", "monkey", "dog", "cat", "camel", "girrafe", "dinosaur", "saket" ] GUESS_WORD = [] ...
b6f84bcb60a5c766d6df2930c4dcef14fdd54a57
nng555/vectorlib
/regression.py
1,379
3.828125
4
import numpy as np from vector import Vector from transform import LinearTransform """ This class implemenets a regression model as a """ class Regression: def __init__(self, in_dim, out_dim, lr): """ Initialize the transformation and hyperparameters. in_dim - input dimension of model ...
4d5232cf49999a7dfec43ff4e963eaa00ee7e37d
ivanovkalin/myprojects
/softUni/Journey.py
764
3.78125
4
budget = float(input()) season = input() destination = 0 type_holiday = 0 if budget <= 100: destination = "Bulgaria" if season == "winter": budget = budget * 0.7 type_holiday = "Hotel" elif season == "summer": budget = budget * 0.3 type_holiday = "Camp" elif budget <= 10...
1de8f7c792fce2fc2a473fe2e1d9c28bbc2e6ac4
huang147/STAT598Z
/HW/HW2/hw2p2sol.py
1,372
4.4375
4
""" Problem 2 : Write a Python program which takes as input an integer n and computes \sum_i^n (1/2)^i in three ways: using a for loop, using a while loop, and without using a loop (e.g., by using an analytic formula). Print out all three results. What happens when n is very large? Do you have any suggestions on how to...
af62e984fd3cded968a9570fff49bb5470e6a1b5
mattfaucher/CTCI
/Arrays_Strings/1_2.py
777
3.921875
4
''' Check Permutation: Given two strings, write a method to determine if one is a permutation of the other ''' def checkPermutation(string1: str, string2: str): """Function to check if a string is a permutation of the other Args: string1 (str): input string string2 (str): input string Retur...
ab2f898db8208da7d59eed937fa32719d3ef3e5f
jlicht27/cmps1500
/Final practice/edgetest.py
289
3.796875
4
graph = {'a': ['b', 'c'], 'b': ['a', 'c', 'e'], 'c': ['a', 'b', 'd'], 'd': ['a', 'b', 'c', 'e'], 'e': ['b', 'd'] } def isEdge(G,x,y): if y in graph[x]: return True else: return False print(isEdge(graph, 'a', 'e'))
395a4665ee5e28e973990ffb3b53a74d804ff230
fromgopi/DS-Python
/Design-Patterns/designpatterns/structural/proxy/request_proxy/base_subject/subject.py
515
3.515625
4
from abc import ABC, abstractmethod class Subject(ABC): """ The Subject interface declares common operations for both RealSubject and the Proxy. As long as the client works with RealSubject using this interface, you'll be able to pass it a proxy instead of a real subject. """ @abstractmethod ...
54d63234fbdf5101f78371a6ba4f6f1d5a860946
Nagendracse1/Competitive-Programming
/array/Nagendra/Find the maximum and minimum element in an array.py
582
3.96875
4
#link https://practice.geeksforgeeks.org/problems/middle-of-three2926/1 class Solution: def middle(self, A, B, C): #code here if (A > B and A < C) or (A < B and A > C): return A elif (B > C and B < A) or (B < C and B > A): return B else: return C...
47b0e77746547f77eb61a3febce4ea63c71c1c8c
ksjpswaroop/python_primer
/ch_2/odd.py
144
3.78125
4
# Exercise 2.3 n = 12 i = 0 while i < int(round(n / 2.)): print 2 * i + 1, i += 1 """ Sample run: python odd_list2.py 1 3 5 7 9 11 """
cf5d9665602642e26b8f87a4f99c239fbbe05f62
nattaphonBu/Backend-Developer-Questions
/question_3.py
747
3.796875
4
##The winning number is 120888 ##The output array should have: #[ 000088, 000188, 000288, ..., Etc ] # 1. run for loop from 000000 to 999999 # 2. check if the last 2 digit is same the last input 2 digits # 3. add the number to list def calculate_lottery_number(number): if len(number) < 6 or len(number) > 6: ...
b90f8040dbf883e9a288c757123e2f0d3a7ac86c
DVDBZN/Schoolwork
/CS136 Database Programming With SQL/PythonPrograms/PRA8 - Two Integer Calculator/Python_TwoIntCalc.py
786
4.0625
4
import sys intString1 = raw_input("Enter an integer:\t") intString2 = raw_input("Enter a second integer:\t") try: intInt1 = int(intString1) intInt2 = int(intString2) except: print "Exception thrown: invalid data type\n" sys.exit() choice = str(raw_input("Pick a number:\n\t1\taddition\n\t2\tsubtract...
b3abfda9551e6d7d40ca1b2e5dd6b56b570b22ca
kids0cn/leetcode
/Python语法/Python编程从入门到实践/第十章文件和异常/file_read.py
403
3.609375
4
with open('1.txt') as file: contents = file.read() # 所有内容都被读取 print(contents.rstrip()) # 删除行尾空格 # 逐行读取 filename = '1.txt' with open(filename) as fObject: for line in fObject: print(line.rstrip()) # 将文件中的各行存储在一个列表中 with open(filename) as f : lines = f.readlines() for line in lines: print...
6e94c5db6bfbf600418a7b9f0806401bd33ed740
GirugaCode/Rainbow-Checklist
/checklist.py
2,188
3.984375
4
# Creates our Checklist checklist = [] # Define Functions def create(item): checklist.append(item) def read(index): return checklist[index] def update(index, item): checklist[int(index)] = str(item) def destroy (index): checklist.pop(int(index)) def list_all_items(): index = 0 for list_ite...
12e629c43f49d9348d225751afa036f5e498385b
murtzdhulz/algorithms_practice
/python/parenthesis_all.py
920
4.03125
4
__author__ = 'Murtaza' # Get all combination of parenthesis for a given n. (n=number of parenthesis) def parenthesis_recurse(result,left_rem,right_rem,str): # print left_rem,right_rem if left_rem < 0 or right_rem < left_rem: print 'Invalid state' return if left_rem==0 and right_re...