blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
991fd2fe91a1b0d1e79685102eca3c1d3d0fab04
alexandraback/datacollection
/solutions_5738606668808192_0/Python/aggelgian/C.py
758
3.71875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import itertools, math def prep(): print ("Case #1:") n, nums = 16, [] nums = ["".join(num) for num in itertools.product('01', repeat=n) if num[0] != '0' and num[n-1] != '0'] i, found, expected = 0, 0, 50 while found < expected: sol = solve(nums[i]) if ...
51a365210f8885fbb9e06e112924140d37debdaf
Schnei1811/PythonScripts
/TutorialSeries/ReinforcementLearning/FishSchools/FishSchools.py
10,374
3.53125
4
import pygame import numpy as np import logging import random import time from math import sqrt, fabs, atan2, degrees, pi #np.set_printoptions(threshold=10000) class Animal: def __init__(self, color, x_boundary, y_boundary): self.score = 0 self.hunger = 100 self.currentdirection = random.ra...
158da877b7ff17292ec033c2e41728e356ce9a48
AdamZhouSE/pythonHomework
/Code/CodeRecords/2908/60752/246012.py
297
3.65625
4
num=int(input()) book=[] for n in range(num): word=input().split() word=list(''.join(word)) word.sort() word=''.join(word) has=False for w in book: if w==word: has=True if not has: book.append(word) print(len(book),end='')
d2752c75f1e4fa556766cb1c798d6d3d07bba6f1
Jason-leung123/Git_hub_Learning_Python
/user_input&while_loops.py
6,890
4.53125
5
#---------------Simple input() greetings = input("If you type something here, it will repeat the input again") print(greetings) #---------------Writing clear prompts name = input("Please enter your name") print(f"Hello, {name}!") #--------------Using int() to accept numerical input height = input("What is your height...
343304c7c0948b42d56041af2220d1864330b6d9
idnbso/cs_study
/mathematics/series/series_ap.py
1,109
3.75
4
""" Given the first 2 terms A and B of an Arithmetic Series, tell the Nth term of the series. Input: The first line of input contains an integer, the number of test cases T. T testcases follow. Each testcase in its first line should contain two positive integer A and B(First 2 terms of AP). In the second line of every...
1159485c36bf525ce0b683ddd198e318651b6261
zramos2/data-structures-and-algorithms
/two-pointer/LC167_two-sum-II-input-array-sorted.py
671
3.625
4
class Solution: def twoSum(self, numbers: List[int], target: int) -> List[int]: # two pointer approach: # if sum is > target, right pointer moves # if sum is < target, left pointer moves # adds 0 to beginning of the list numbers.insert(0,0) left ...
38c32aa33c5e35af70c9c83feed7fa49f7416e06
David-M-Dias/Exercicios-do-curso-de-Python
/Mundo2/Listas.py
556
4.15625
4
Lista = [1,2,3] # Criando lista e adicionando valores a mesma. print(len(Lista)) # Contando quantidade de itens na lista. print(Lista) # imprimindo a lista. Lista = Lista + [4,5,6] # Adicionando novos valores a uma lista já existente. print(Lista) # imprimindo lista atualizada. print(Lista[:3]) # imprimindo os val...
e3b382594066e8039b71bd6ac7b0fe723aa0ece0
zdravkog71/SoftUni
/OOP/ClassAndStaticMethodsExercise/project/gym.py
1,935
3.578125
4
class Gym: def __init__(self): self.customers = [] self.trainers = [] self.equipment = [] self.plans = [] self.subscriptions = [] @staticmethod def is_added(objects, object): if object in objects: return True return False def add_cust...
faf4840b8226c54ecf73dd9b9b3653f997b6389a
vurise/PythonClasses
/classes-2.py
1,207
4.15625
4
#classes encapsulates 2 thngs- variables / attributes and functions/methods #recangle class- #length -var #width- var #area- funct/ method / var #perimeter - funct #diagnol- var #color- func #constructor/ init method #1. function #2. this function gets automatically invoked when i make an instance #3. to...
27f91101ef2e6ab5057c03503919eadf22420da7
distractedpen/datastructures
/BST.py
2,546
3.875
4
import random class Node(): def __init__(self, data): self.data = data self.left_child = None self.right_child = None class BinarySearchTree(): #Binary Tree algorithms def __init__(self): self.root = None def insert(self, data): new_node = Node(data) if ...
591bf66bfac89e32091a618fd7ff84367c76b6b8
champagnepappi/python_kickstart
/reverse.py
155
4
4
def reverse(text): string = "" l = len(text) while l > 0: string += text[l-1] l -= 1 return string print reverse("KEvin")
11953a278ea44485e74d7629778de32c4dfa9191
Franklin-Wu/project-euler
/p042.py
1,544
3.90625
4
# Coded triangle numbers # # The nth term of the sequence of triangle numbers is given by, t_n = n(n+1)/2; so the first ten triangle numbers are: # 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ... # # By converting each letter in a word to a number corresponding to its alphabetical position and adding these values we form a ...
35cf802d36d245dc02a5ea7c2e5f7e1732b0d76d
TassioSales/Python-Solid
/exercicio-04.py
285
3.625
4
def maior_numero(objeto): return max(objeto) def menor_numero(objeto): return min(objeto) listaNumero = [x**2 for x in range(155, 255)] maior = maior_numero(listaNumero) menor = menor_numero(listaNumero) print(f"O maior numero e {maior}") print(f"O menor numero e {menor}")
d8361a949b9431ce05a71ee497d76d92f63c6354
ColdGrub1384/Pyto
/Pyto/Samples/Pandas/plotting.py
583
3.90625
4
""" An example of plotting with Pandas. Taken from http://queirozf.com/entries/pandas-dataframe-plot-examples-with-matplotlib-pyplot. """ import pandas as pd import matplotlib.pyplot as plt df = pd.DataFrame({ 'name':['john','mary','peter','jeff','bill','lisa','jose'], 'age':[23,78,22,19,45,33,20], 'gend...
13f2a2ea674030d436e34d03f8829fb5f10e319c
paulorleal1991/prl1991
/ex008_prl1991.py
1,094
4.03125
4
'___Curso_de_Python___' '___Aluno_Paulo_R_Leal___' '___Exercicio_008____' print('') print('_' *40) print('Conversor de Medidas') m = float(input('Digite o Valor em Metros \n')) dm = m * 10 cm = m * 100 mm = m * 1000 print('') print('#' *40) print('{} Metros Equivale a:\n{:.0f} Centimetros ou {:.0f} milímetros'.format(m...
14328ac205eb0f3d73dac335c90e14dc9c9ef164
grishutenko/grishutenko.github.io
/python_labs/tests1.py
721
3.796875
4
def test(n): try: num = int(n) return 0 except: print('нельзя преобразовать в число') return 1 def tests(): test_result = 0 print('test 1') test_result = test_result + test([1]) print('test 2') test_result = test_result + test('-1') print('test 3') te...
057c3c0baf5c797e571f89e65d7b404d43e059b4
0xecho/KattisSubmissions
/digits.py
170
3.625
4
while 1: inp = input() if inp=="END": break # inp = int(inp) c=0 while inp!="1": inp = str(len(inp)) c+=1 print(c+1) # print(len(str(inp)))
349b3c9befeee7cded9e01e8ba9c769f8ee012f0
GiantSweetroll/Computational-Mathematics
/mid_exam/GardyanPrianggaAkbar_2301902296_COMP6572_L2AC.py
4,504
3.609375
4
from math import pi import matplotlib.pyplot as py import sympy as sp import numpy as np import time x = sp.Symbol('x') y = sp.Symbol('y') n = sp.Symbol('n') #No 1 #a #X for tools and equipment #Y for materials for EACH cloth revenueEq = (1.5*x + 2*x)*(n/2) totalCostEq = y + x*n profitEq = revenueEq - totalCostEq #...
a74cfee77c8cf0ea166aac5d9d12be6d4b9a07e5
ZenVendor/Python
/CheckIO/Elementary/Elementary_19.py
525
3.8125
4
def most_frequent(data): most = '' count = 0 for word in data: if data.count(word) > count: most = word count = data.count(word) return most if __name__ == '__main__': #These "asserts" using only for self-checking and not necessary for auto-testing assert most_fr...
8457b7e4b22ea3e752719969002f4c73972f2afb
chenxk/StudyDemo
/com/study/ai/np/NumpyDtype.py
2,133
3.515625
4
''' NumPy 数字类型是dtype(数据类型)对象的实例,每个对象具有唯一的特征。 这些类型可以是np.bool_,np.float32等。 https://www.yiibai.com/numpy/numpy_data_types.html numpy.dtype(object, align, copy) 参数为: Object:被转换为数据类型的对象。 Align:如果为true,则向字段添加间隔,使其类似 C 的结构体。 Copy? 生成dtype对象的新副本,如果为flase,结果是内建数据类型对象的引用 字节顺序取决于数据类型的前缀<或>。 <意味着编码是小端(最小有效字节存储在最小地址中)。 >意味着...
dcf610152c74efbaabe85f08f442ca810331779c
Maureen-max/Mad-Lib-Game-python
/Mad_lib Game.py
216
3.578125
4
color = input("Enter a color :") curtains = input("Enter the curtain type :") name = input("what is your name :") print("Roses are color", color) print("The curtain type is",curtains) print("My name is", name)
2178b61a092d0c0e769c2c8ec692ea402546304f
breezekiller789/LeetCode
/204_Count_Primes.py
1,887
3.8125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # https://leetcode.com/problems/count-primes/ # Sieve of Eratosthenes的核心概念是用消去的方法,一開始我們就準備size為n的陣列 # 陣列都是布林值,我們從頭把那些不可能是質數的位置改成false,最後再算出陣列中是 # true的個數就好,那他的想法是,一個數的平方不可能是質數,就像13^2 = 169,不可能是 # 質數,再者,一個數平方往後的倍數,一定也不是質數,以下舉例, # 3 * 3 = 9 # 3 * 4 = 12 # 3 * 5 = 15 # 3 * 6...
593dc5360fad48880763e6b5d6d30cd7660ece80
elena0624/leetcode_practice
/Challenge_Running_Sum_of_1d_Array1.py
167
3.796875
4
# -*- coding: utf-8 -*- """ Created on Mon May 3 15:32:32 2021 @author: ppj """ nums = [3,1,2,10,1] for i in range(1,len(nums)): nums[i]+=nums[i-1] print(nums)
578e730a33da41fc216864829e4a16d8b6852539
thoufiqzumma/tamim-shahriar-subeen-python-book-with-all-code
/all code/p.fstring application. formatted string.py
59
3.65625
4
num1 = 20 num2 = 50 print(f"{num1} + {num2} = {num1+num2}")
454d90555e21e50b6f9351fbf16bb13d938ca943
dataCalculus/fibonacci
/upgrade_1.py
1,632
4.125
4
class Fibonacci(): def __init__(self,start): self.start = start self.fibonacciList=[] def printSequence(self,count): """ instant generation count --> length of fibonacci sequence """ firstStep = self.start nextStep = self.start f...
4df514a30dc4f82b93d72baf9807f4d7caa83d1e
AmbyMbayi/CODE_py
/WebScraping/Question6.py
387
3.703125
4
"""write a python program to extract and display all the headers tags from en.wikipedia.org/wiki/Main_Page """ from urllib.request import urlopen from bs4 import BeautifulSoup html = urlopen('https://en.wikipedia.org/wiki/Main_Page') bs = BeautifulSoup(html, "html.parser") titles = bs.find_all(['h1','h2','h3', 'h4', '...
a00c1c4a2319b4d9564eac7519a93d2fa866c0c4
gistable/gistable
/all-gists/5653532/snippet.py
975
4.125
4
# coding=UTF-8 """ Faça um Programa que leia um número inteiro menor que 1000 e imprima a quantidade de centenas, dezenas e unidades do mesmo. Observando os termos no plural a colocação do "e", da vírgula entre outros. Exemplo: 326 = 3 centenas, 2 dezenas e 6 unidades """ number = int(raw_input("Digite um numero: ...
262732c239ba84810a2334d2d51d336ac4b1001e
mohsenuss91/simple_neural_network
/neuralnet
3,865
3.640625
4
#!/usr/bin/python """Perform K-folds cross-validation on a simple neural network. Data is read from a ARFF file. Results are written to stdout. """ import optparse import math import random import utils from SimpleNeuralNetwork import SimpleNeuralNetwork def mean(list_of_numbers): """Returns the arithmetic mean o...
a2ed44022aee1ebf941aca86e5f3c08502ab3765
luca16s/INF1025
/Exercicios/ListaStrings/Exe3.py
887
4.1875
4
'''3. Crie as funções abaixo e teste-as no interpretador. a. Faça uma função que receba uma string e retorna uma string com os caracteres de índices pares b. Faça uma função que receba uma string e retorne uma cópia desta string invertida c. Faça uma função que recebe o nome de uma pessoa e a data de nascimento ('dd/mm...
09e50bd2c35e73310492cb64e7cb50bf72b45a14
Jtaylorapps/Python-Algorithm-Practice
/remDups.py
687
3.75
4
# Remove duplicates from an array in O(n) time def remove_duplicates(input_array): # Create hash map / dictionary to add unique values of input_array to output_map = {} for element in input_array: # O(n) output_map.update({element: element}) # Create array that will contain sorted_output with ...
df672caed394e5baf248196ce8789ba0e213181b
robertvari/python_alapok_211106_1
/07_conditions.py
530
4.34375
4
number = 5 # True #if number != 10: # this runs if True # print("Number is not equal to 10") # True and True if number >= 5 and number <= 10: print("Number is between 5 and 10") # False or True if number < 5 or number > 10: print("Number is less than 5") print("Number i...
ecb08a634f1c3bfb84a39d762d41292b2bba43fc
nghoiwa/python
/reverse_linked_list.py
1,820
4.03125
4
class Node: def __init__(self, value=0, next=None) -> None: self.value = value self.next = next return def print_list_element(head): return head.value def print_full_list(head): if head != None: print(print_list_element(head)) print_full_list(head.next) else: ...
a417031d2f2d7a37e460f3d5ff48751459f28bf1
mengnan1994/Surrender-to-Reality
/py/0633_sum_of_square_nums.py
665
3.921875
4
""" Given a non-negative integer c, your task is to decide whether there're two integers a and b such that a^2 + b^2 = c. Example 1: Input: 5 Output: True Explanation: 1 * 1 + 2 * 2 = 5 Example 2: Input: 3 Output: False """ import math class Solution: def judge_square_sum(self, c): square_set = set([]) ...
f22ac16019ccb69a5f853c3b85056a3559cd865b
jreiher2003/code_challenges
/project_euler/mult_3_5.py
159
3.765625
4
def multiple_3_5(n): x = 0 for i in range(n): if i % 5 == 0 or i % 3 == 0: x += i return x print multiple_3_5(10) print multiple_3_5(1000)
a23561d9d3e5da1c5a4fd48b2e6c40a8b8cf7d1b
scheidguy/Advent_of_Code
/2018/day1-1.py
145
3.578125
4
f = open('day1_input.txt') text = f.readlines() f.close() freq = 0 for line in text: line = line.strip() freq += int(line) print(freq)
e5176f31aac53425400899e4f3af439814cdecf1
kooshanfilm/Python
/basic_python/basics/decorator2.py
485
3.578125
4
def new_dectorator(func): def wrap_func(): print("start") func() print("end after func") return wrap_func @new_dectorator def func_need_dec(): print("this func needs decorator") func_need_dec() #another example: """ def my_decorator(func): def function_that_runs_func(): ...
383aa00bfc4f6c81f3595a2f19132df7db52d25c
AleksandrFresh/training_dv
/py_clw/cl2.1.py
554
3.640625
4
#a=[] #a=map(int, input("Введите 10-ть чисел через пробел: ").split()) #m = max(a) #print(m) #iteres = int(input("введите колво итраций: ")) #myMax=0 #for i in range (iteres): # a = int(input("enter num: ")) # if a > myMax : # myMax = a #print(myMax) iteres = int(input("введите колво ...
176bf8f6e0d50fcd71dfdde67287145e373229d6
emmaping/leetcode
/Python/Unique Binary Search Trees II.py
858
3.90625
4
# Definition for a binary tree node # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: # @return a list of tree node def generateTrees(self, n): return self.generate(1,n) def genera...
8128be54ce84e3fb2bbef9945b2938aff170c053
ritishadhikari/Scikitlearn
/sklearn_training_model.py
1,285
3.65625
4
from sklearn.datasets import load_iris #Importing the Dataset from sklearn.neighbors import KNeighborsClassifier #Importing the Classifier from sklearn.linear_model import LogisticRegression iris = load_iris() #Instantiating the Dataset X = iris.data y= iris.target knn= KNeighborsClassifier(n_neighbors=1) #I...
7b077c7c3c9774862a549b5ebff603fa6a2c173d
YikangGui/leetcode
/Tree.py
516
3.71875
4
def inOrder_Iterative(root, indexes): res = [] stack = [] node = 1 while stack or node != -1: while node != -1: stack.append(node) node = indexes[node-1][0] node = stack.pop() res.append(node) node = indexes[node-1][1] return res def inOrder_R...
d0397fa0157469ecd0c06a10449b0b2af54af35e
mohammedthasincmru/royalmech102018
/roc.py
494
4.15625
4
import random a={1:'r',2:'p',3:'s'} while True: p=input("your choice r/p/s: ") c=a[random.randint(1,3)] print("you chose:",p,"computer chose:",c) if(p==c): print("draw") elif(p=="r"): if(c=="p"): print("computer wins") elif(p=="p"): if(c=="s"): print("computer wins") elif(p=="s"): if(c=="r"): ...
32658f13d542d0fa6dd1b546101457b9215f6773
jayw117/Light_Switch_Flow
/light_switch.py
4,658
3.734375
4
#Jason Wong # Problem: Have n lights and switches that are inside a floor plan. Ergonomic if each switch can be # seen by a light. One switch per light from graph import * from copy import deepcopy from collections import defaultdict Walls = [(1,2),(1,5),(8,5),(8,3),(11,3),(11,1),(5,1),(5,3),(4,3),(4,1),(1,1),...
266f16638743c35b42d2997b8df36cbfa6484038
shrutipai/CS-88
/lab02/lab02_extra.py
1,736
4.15625
4
# Optional lab02 questions. def square(x): return x * x def twice(f,x): """Apply f to the result of applying f to x" >>> twice(square,3) 81 """ "*** YOUR CODE HERE ***" def increment(x): return x + 1 def apply_n(f, x, n): """Apply function f to x n times. >>> apply_n(increment, ...
adf1b78b321775b51437a06429af0e88109af0a6
Evacolone/Algorithm-Python
/Sort Algorithm/merge_sort.py
862
3.890625
4
# encoding=utf-8 # date: 2016-09-22 # gaooz.com # 归并排序 # 归并 def merge(list, left, mid, right): i = left j = mid + 1 temp = [] while i <= mid and j <= right: if list[i] < list[j]: temp.append(list[i]) i = i+1 else: temp.append(list[j]) j = ...
62a2004fd02bde274ffe6284b6c74bc4b92f6126
Janragnak-X/14_S_calBMI.py
/R2a.py
369
3.546875
4
class BMI: def __init__(self,myWeight, myHeight,myName): self.myWeight = myWeight self.myHeight = myHeight self.myName = myName def calBMI(self): currentBMI = self.myWeight / (self.myHeight * self.myHeight) return currentBMI #testing person = BMI (60, 1.5,"John") print(p...
2e1e07e3f9365c5fae2866b1f952727a63d8601a
basiledayanal/PROGRAM-LAB
/CO1.pg19.py
176
3.90625
4
a = int(input("Enter 1st number: ")) b = int(input("Enter 2nd number: ")) i = 1 while i<=a and i<=b: if a%i==0 and b%i==0: gcd = i i = i + 1 print("GCD is", gcd)
3bab800b54117c8d55102580480eb09ffff56f2d
lkoj/CSE
/notes/Adventure Game.py
5,150
3.625
4
class Room(object): def __init__(self, name, north=None, south=None, east=None, description=""): self.name = name self.north = north self.south = south self.east = east self.description = description class Player(object): def __init__(self, starting_location): s...
9bd59b9bcfbe9e0c4b8aee1ed19c8b666160e197
akashjain15/hackerrankpythonpractice
/numpy-doTncross.py
439
3.8125
4
import numpy numpy.set_printoptions(sign=' ') n = int(input()) lis = [] for i in range(n): m = list(map(int,input().split())) lis.append(m) arr1 = numpy.matrix(lis,int) lis.clear() for i in range(n): m = list(map(int,input().split())) lis.append(m) arr2 = numpy.matrix(lis,int) print(arr1*ar...
1f21521bfee9a81a7d241feed6a27d9ba40fd131
juansalomon/TIC
/menuoperacion.py
1,196
3.984375
4
def menu_operacion(): Seguir="Si" num1=input("Dime un numero: ") num2=input("Dime otro numero: ") while (seguir=="Si"): print "Que deseas hacer con los numeros: " print "1.Devolver la suma de las cifras pares" print "2.Devolver la suma de las cifras impares" print...
978aa8c1939a20a4cb6e59ddbdd585c2b62b57e2
JeanMarieN/CPH-Sentiment-Analysis
/preparation/from_json_to_words.py
4,266
3.5
4
''' This code is a json extractor, that takes a json file as input, targets a, then collects and cleans the data. In this case from json to ready-to-go words for NLP ''' ''' The code can be modified and adapted to fit different kind of json data and different targets''' import json ...
aba872040bd32bb67041143f7658337606adc213
hasson82/AI_ex2
/SearchAlgos.py
4,162
3.65625
4
"""Search Algos: MiniMax, AlphaBeta """ from utils import ALPHA_VALUE_INIT, BETA_VALUE_INIT #TODO: you can import more modules, if needed from state import get_move_between_states class SearchAlgos: def __init__(self, utility, succ, perform_move, goal=None): """The constructor for all the search algos. ...
0db67f1192996609e0487dd50fb00bd910446373
AP-MI-2021/lab-2-RuginaAlex
/main.py
2,270
3.859375
4
def get_base_2(n): ''' Algoritmul de schimbare a unui numar din baza 10 in baza 2 :param n: Numarul citit :return: Returnam numarul in baza 2 ''' r=0 p=1 nr=0 while n!=0: r=n%2 n=n//2 nr=nr+r*p p=p*10 print (nr) def test_get_base_2(): asse...
a78dfcfbb6f7060870c2261d71c9c80329ffb357
Pirens/Projet3OC
/macgyver.py
2,673
3.90625
4
class Macgyver: ''' Init the coordinates and the objects variable ''' def __init__(self, ord, abs, nbr_objects): self.ord = ord self.abs = abs self.nbr_objects = nbr_objects ''' Move right ''' def right(self, display_map): if (display_map[self.ord][self.abs + 1] == 'N')...
76fa3ea5c8d0b43b085ff0d6c17b38df7a730cd4
usmanchaudhri/azeeri
/hackerland/cut_a_tree_recursive.py
2,060
3.546875
4
from collections import defaultdict class Graph: # sum = [1500 1300 1100 ] value = [100, 200, 100, 500, 100, 600] def __init__(self, noOfNodes): self.totalSum = sum(self.value) self.noOfNodes = noOfNodes self.graph = defaultdict(list) def addEdge(self, u, v)...
bcecb98449072cf8acbf7485ecadf4f7322a2d79
koltpython/python-exercises-spring2020
/section4/starter/hangman.py
1,045
4.1875
4
import random def pick_random_word(): """Returns a random word from a list of predefined options""" word_list = ['PYTHON', 'PUMPKIN', 'QUEEN', 'ISTANBUL', 'PENINSULA', 'ARCHIPELAGO', 'COFFEE', 'ADDICTION', 'CHARISMA', 'KUCU'] # Return random integer in range [a, b], including both end points. # r...
43e2a20a73a67d4798f4e5a150f581a59f3d5bc6
drhanfastolfe/python
/beginners_tutorial/strings.py
105
4.03125
4
s = "hello maam" print(s) print(s[1]) print(s.upper()) print(s.replace("maam", "leo")) print(s[0:5])
cabebde2d0c6709b3ecd0c1b605cbdc3b740e812
mfre1re/Diversas-atividades-em-Python
/Atividades - Python/Exerc.002 - Conversor de Bases (Bin, Octal, Hexa).py
438
4.1875
4
numero = int(input('Digite um número: ')) conversor = int(input('Escolha qual será a opção de conversão do seu número, sendo: \n1 - Binário \n2 - Octal \n3 - Hexadecimal \n')) if conversor == 1: print('O número em binário é {}.'.format(bin(numero)[2:])) elif conversor == 2: print('O número em Octal é {}.'.forma...
df4c913bad612d3024a03ab8756f572e50d4a280
MrHamdulay/csc3-capstone
/examples/data/Assignment_4/stkthe002/boxes.py
928
3.984375
4
def print_square(): print('*'*5) for i in range(3): print('*' + ' '*(5-2) + '*') print('*'*5) def print_rectangle(width, height): print('*'*width) for i in range(height-2): print('*' + ' '*(width-2) + '*') print('*'*width) def get_rectangle(width, height): ...
9f21cdc765f12172464ea89b5fb1e34af867c9c5
hcwhwang/ttbb
/t.py
178
3.65625
4
wList = ['c','d'] word = 'a_b_c' word.split("_") print word.split("_")[0] #word = word[len(word.split("_")[0])+1:] print word if not any( w in word for w in wList): print 'test'
6e77def2c55cb44cd90a398ffa45a63ff5b6f840
vinay-chowdary/python
/16_CSVfiles.py
1,751
3.875
4
import csv # reader() and writer() functions # For Writing: with open('myfile.csv', 'w', newline='') as fp: w_obj = csv.writer(fp) mylist = [['Ram', 'Manager', 75000], ['Lakshmi', 'Asst. Manager', 60000], ['Kumar', 'Clerk', 30000], ['Raja', 'Peon', 10000]] w_obj.writerows(mylist) # For Readin...
a2607a69c36a1a1896adaa23a4ce1f4f055708c3
whjwssy/Machine-Learning
/knn/knn.py
2,560
3.59375
4
import math import operator #读取文件,获取147个训练数据集 def getTrainingSet(filename,trainingSet=[]): fp = open(filename) dataset = [] for linea in fp.readlines(): #数据预处理 line = linea.replace('\n', '').replace('\t', ',') linetest = line.split(',') dataset.append(linetest) fp.close(...
f5070ae20fac032e457d1c30d2b501f7ec43382e
enzostefani507/python-info
/Test/test_empresa.py
929
3.609375
4
import unittest from empresa import Empleado class TestEmpleado(unittest.TestCase): @classmethod def setUpClass(cls): print("set up class") @classmethod def tearDownClass(cls): print("tear down class") def setUp(self): print("setup") self.emp1 = Empleado("axel", "...
2561e0b30a9f1b52c8b4686ce20702edc29d30b2
BranFerr/Rectangle_and_Temp_Converter
/Rectangle.py
258
4.125
4
h = input('What is the Height/Length of the Rectangle?\n') h = int (h) w = int (input('What is the Width of the Rectangle?\n')) x = int (h) * w x = str (x) h = str (h) print ('The area of a rectangle of Height/Length '+h+' and width ',w,' is '+x)
c2e472911f0ff5945eeeb2f4beb27f88600ee9ae
SergeiLSL/PYTHON-cribe
/Глава 10. Исключения Exceptions/5.4 Инструкция raise/5.4.3 Инструкция raise.py
1,549
4
4
""" 5.4 Инструкция raise https://stepik.org/lesson/427822/step/1?unit=417707 """ """ Где нам это понадобится? """ # # try: # [1, 2, 3][8] # except (KeyError, IndexError) as error: # можно добавить несколько исключений # print(f'fLogging error: {repr(error)}') # fLogging error: IndexError('list index out of r...
05d95493cb4858b3dc7c36eb93ae29c723db59b6
LukeMowry/Projects
/Project20-UnitConverter.py
1,853
4.5625
5
""" Unit Converter (temp, currency, volume, mass and more) - Converts various units between one another. The user enters the type of unit being entered, the type of unit they want to convert to and then the value. The program will then make the conversion. """ init_unit = input("Please enter your current unit o...
5d40e99c21e4d8d04570129651748bd1ecca103a
pehia/ze-camp-2019
/Programming Intro/sarath.py
287
4.15625
4
a=int(input("enter the first number :")) b=int(input("enter the second number :")) c=int(input("enter the third number :")) if((a>b) & (a>c)): print(str(a)+"is the biggest number : ") elif((b>c)): print(str(b)+"is the biggest number :") else: print(str(c)+ "is the biggest number ")
30149d0416e1784e95035347f87821997e4a7e44
SuHyeonJung/iot_python2019
/03_Bigdata/01_Collection/03_Web_crawling/02_Reguar_Expression/99_example/29_exam.py
429
3.703125
4
import re text = "The following example creates an ArrayList with a capacity of 50 elements. Four element are then added to the ArrayList and the ArrayList is trimmed accordingly." result = re.compile("\d+") m = result.finditer(text) print(m) for i in m: print(i.group()) print("Index position:", i.start()) # f...
d72e66e97e12860cbc668f27d8e6f3354bf61bf7
Aasthaengg/IBMdataset
/Python_codes/p02880/s683315519.py
124
3.5625
4
n=int(input()) ans = "No" for i in range(1,10): if n%i==0 and n//i<10 : ans = "Yes" break print( ans )
0da7dbf45f722d5af8af47c09c6150d33a68469f
kevinchritian/UG10_E_71210797
/4_E_71210797.py
660
3.84375
4
def angka_terbesar (a, b, c): if a > b and a > c: return a elif b > a and b > c: return b return c def angka_terkecil (a, b, c): if a < b and a < c: return a elif b < a and b < c: return b return c def nilai_tengah (a, b, c): if (b > a > c) or (c > a > b):...
d918beaca24f5c3590140d8ede001c872284a907
Valen0320/FuncionesBasicas
/prg_funciones_Basicas4.py
858
3.625
4
# -*- coding: utf-8 -*- """ Created on Tue Mar 16 10:33:52 2021 @author: Valen """ # Leer dos numeros y calcular la combinatria de esos dos numeros # Declaracion variables fact_M=1 fact_N=1 fact_MN=1 # Entradas ve_M=int(input("Digite M: ")) ve_N=int(input("Digite N: ")) # Calcular el factorial de M...
6ab01b8960e3d99ca63df71f72aea8d57ac106f6
hyeonhoshin/atom-editor-test
/Ch05/예외처리/filter.py
371
3.828125
4
# -*- coding: utf-8 -*- # positive.py ''' def positive(l): result = [] for i in l: if i > 0: result.append(i) return result print(positive([1,-3,2,0,-5,6])) ''' ''' def positive(x): return x > 0 print(list(filter(positive,[1,-3,2,0,-5,6]))) ''' #Using with lambda and filter func ...
2a678a53e17a27eba4ab19686dedb5771b078d5c
piotrnarecki/lista1Python
/l1z6.py
1,232
4.03125
4
def countParagraphs(filePath): file = open(filePath, "rt") paragraphsCount = 0 data = file.read() lines = data.split("\n") for i in lines: if i: paragraphsCount += 1 print("This is the number of lines in the file") file.close() return paragraphsCount def countWord...
6e7133150b24b2449429858972ab6ac03bfeebc8
ifat-tamir/python
/01_introduction/hot.py
101
3.84375
4
celsius = input("please enter degrees: ") fahrenheit = float(celsius) * 9 / 5 + 32 print(fahrenheit)
3da37548ff288a2d45d72235a45ada0b72f04069
shashank-indukuri/hackerrank
/StrongPassword.py
2,163
4.28125
4
# Louise joined a social networking site to stay in touch with her friends. The signup page required her to input a name and a password. However, the password must be strong. The website considers a password to be strong if it satisfies the following criteria: # Its length is at least . # It contains at least one digi...
34aeb294d992035c5a8ccc8fa712c9568e033ce8
sarthak-chakraborty/Machine-Learning-Assgn
/Assignment2/Part 1/Part1.py
7,293
3.5
4
import numpy as np import pandas as pd # Reading data in DataFrame df1 = pd.read_csv("./dataset for part 1 - Training Data.csv") df2 = pd.read_csv("./dataset for part 1 - Test Data.csv") # Converting to integer encoding df1 = df1.replace(to_replace=['high','med','low','yes','no'],value=[2,1,0,1,0]) df2 = df2.replace(...
60edc42c4983fc568d2809a20a6a8c1f9af5c45e
rafaelperazzo/programacao-web
/moodledata/vpl_data/3/usersdata/130/564/submittedfiles/ex1.py
187
4.0625
4
# -*- coding: utf-8 -*- from __future__ import division a=input('digite um valor:') if a<0: a= a**2 print ('%.2f' % a) else: a= a**0.5 print('%.2f' % a)
84457f5c41fc632f079e55dd7010419bf3b7bf88
bnjbvr/ProjectEuler
/finished/problem20.py
473
3.90625
4
# -*- coding:utf-8 -*- # http://projecteuler.net/problem=20 # Find the sum of the digits in the number 100! # Returns the sum of digits of the integer n. def sumOfDigits(n): sum = 0 while n >= 10: sum += n % 10 # adds last number n /= 10 sum += n # adds the last number a last time (n == n%10 since n < 10) retu...
0afb04d9e6d70bf6d96472ff1e4a86d946dede77
Wuzhibin05/python-course
/Course/Section-1/day2/code/test1.py
1,936
3.984375
4
#! /usr/bin/env python # -*- coding: utf-8 -*- # __author__ = "Wu zhi bin" # Email: wuzhibin05@163.com # Date: 2021/4/13 # # 1、判断下列逻辑语句的True,False. # print(1 > 1 or 3 < 4 or 4 > 5 and 2 > 1 and 9 > 8 or 7 < 6) # T # print(not 2 > 1 and 3 < 4 or 4 > 5 and 2 > 1 and 9 > 8 or 7 < 6) # F # # # 2、求出下列逻辑语句的值。 # # print(8 ...
ec66de38dac48ea5f6fe47e58a548247a0c3d786
danielmedinam03/Diplomado-Python2021
/EjerciciosVarios/SumarDosNumeros.py
126
3.8125
4
numero1=int(input("Numero 1: ")) numero2=int(input("Numero 2: ")) suma=numero1+numero2 print("Suma: ",suma,(type(suma)))
c69495f65f5d5e9cedb5c30a8cb3ae46781c2482
kasikritc/classic_snake_game
/Snake.py
2,939
3.90625
4
SQUARESIZE = 20 WIDTH = 35 # number of squares that can fit the width of the screen HEIGHT = 35 # number of squares that can fit the height of the screen class Snake: ''' @attributes: body = (list) storing the x and y coordinates according of each segment to box number (not acco...
9fcd6637d89d2fcc65de3a494556853b409a9983
oxxostudio/python
/demo/a14.py
696
3.75
4
class human(): def __init__(self, name=None): if name: self.name = name else: self.name = '???' def talk(self, msg): print(f'{self.name}: {msg}') class Taiwan(human): def __init__(self, name, age=None): super().__init__(name) # 繼承 human 的 name ...
ba61fc910765399ed6db13aa02c0d97ce15ac1a4
shloknangia/Machine-Learning-Algorithms
/examples/text_learning.py
884
3.859375
4
from sklearn.feature_extraction.text import CountVectorizer vectorizer = CountVectorizer() string1 = "Hi this machine learning class is great great great class" string2 = "Hello the class will start late" string3 = "Hi this class will me most excellent" email_list = [string1, string2,string3] bag_of_words = vectoriz...
aad7ea9b1de87d4df0eff9783dd7d70d10c7d360
wangJmes/PycharmProjects
/pythonProject/pythonStudy/chap13/demo2.py
409
3.8125
4
# 练习 # 开发者:汪川 # 开发时间: 2021/8/23 16:24 class Student: def __init__(self, name, age): self.name = name self.__age = age def show(self): print(self.name, self.__age) stu = Student('张三', 20) stu.show() # 在类的外部使用name与age # print(stu.age) print(dir(stu)) print(stu._Student__age) # 在类的外部可以通...
62e8d4d97f599f7563f1779409b1a3b5188f9cc1
emeshch/peer_code_review_2018
/8_вложенные_словари/4_tyhvop.py
2,660
3.765625
4
# Вам нужно написать программу, которая загадывает слова.В задании обязательно использовать словарь. # Программа должна уметь загадывать как минимум 5 разных слов (с разными подсказками). # Кроме того, желательно, чтобы слова и подсказки хранились в отдельном csv-файле, # который загружался бы при запуске прогр...
274120f76163e45d01aa3c8dd0e8a00249fcd3aa
Jimin2123/BaekJoon
/bronze/2750.py
203
3.515625
4
# 수 정렬하기 [ 티어 : 브론즈 1 ] # https://www.acmicpc.net/problem/2750 N = int(input()) values = [] for i in range(N): values.append(int(input())) values.sort() for i in values: print(i)
f94b8d4a92067d8d1877bcdde862f9a22daadd9c
hatmle/Python-code
/Exercises/11-hasPathWithGivenSum.py
1,164
3.71875
4
# Given a binary tree t and an integer s, determine whether there is a root to leaf path in t # such that the sum of vertex values equals s. # [input] tree.integer t # A binary tree of integers. # Guaranteed constraints: # 0 ≤ tree size ≤ 5 · 104, # -1000 ≤ node value ≤ 1000. # [input] integer s # An integer. # Gu...
50e218e10fb25b6cb3bee2b650d49c32af762083
Shaydaeva/Basic-Python
/home_work_05/5.1.py
712
4.375
4
""" Можно запрашивать название файла у пользователя, в моём случае с расширением, но можно и по умолчанию указать расширение, и у пользователя запрашивать только имя файла""" file_name = input("Enter file name with the extension") print("Enter your content") # Запись данных ввода, ограничение - пустая строка ...
2fb1ccb61f473b4ce18c02cf43a8898a88c815a6
juuhi/Python---DataStructure
/BubbleSort.py
809
4.40625
4
# Bubble sort using python # This code has the worst case complexity as O(n*n), that is when the list is in the reverse order #This code has the best case complexity as O(n) as it traverse the list once with the inner loop, #if nothing is swapped then it will exit the code and doesn't traverse the list once again. de...
ef49636610d94dbbcb88be0773140b6c5beb8622
balasekharnelli/Python-Basics
/Basics-1/loops-2.py
251
4.25
4
#Create a for loop that prompts the user for # a hobby 3 times, then appends each one to hobbies. hobbies = [] hobbies_count = 3 for hobby in range(0, hobbies_count): value = input("Enter your hobby: ") hobbies.append(value) print(hobbies)
4319a950a75d8e6409c1ecc8b5c65b735a772d11
Krishnaanurag01/PythonPRACTICE
/Stringsplit.py
107
3.5
4
import re from typing import Pattern Pattern=r"[ .,_'?!@]+" s=input().strip() print(re.split(Pattern,s))
85ff9390af3175f23e11e7d5f58019bb2ffeabfa
EstephanoBartenski/Aprendendo_Python
/Exercícios_parte_1/exercício__074.py
416
3.703125
4
# maior e menor valores em tupla from random import randint sorteio = (randint(0, 9), randint(0, 9), randint(0, 9), randint(0, 9), randint(0, 9), randint(0, 9), randint(0, 9), randint(0, 9), randint(0, 9), randint(0, 9)) print('Os valores sorteados foram: {}.'.format(sorteio)) print('O maior valor sorte...
263b698c2d5ee6cd368b4ed10b89e303e6ea2674
sky-dream/LeetCodeProblemsStudy
/[0168][Easy][Excel_Sheet_Column_Title]/Excel_Sheet_Column_Title_3.py
296
3.59375
4
# leetcode time cost : 40 ms # leetcode memory cost : 13.6 MB # Time Complexity: O(N) # Space Complexity: O(1) class Solution: def convertToTitle(self, n: int) -> str: # A ascii is 65 return "" if n == 0 else self.convertToTitle((n - 1) // 26) + chr((n - 1) % 26 + 65)
11b63f89786d216e81b20b30336f5fdd48b271e1
lhaislla/Introducao-a-programacao
/gerando_numeros_aleatorios.py
468
3.90625
4
# Programa que gera numeros aleatórios e coloca em uma tupla # Mostra a listagem dos números gerados # Indica o menor e o maior valor que estão na tupla import random sorteio = (random.randint(0, 10),random.randint(0, 10),random.randint(0, 10),random.randint(0, 10),random.randint(0, 10)) print(f'Valores sorteados:',...
c6f4902282e33b9141cfb8f97047d009d6f5a7d0
Oscarpingping/Python_code
/01-Python基础阶段代码/01-基本语法/Python分支-优化案例.py
2,197
3.5625
4
# Python版本的问题 # 思路, 语法 -> 工具 # Python3.x # 使用注释, 理清楚, 具体的实现步骤 # 代码填充 # 输入 # 身高 personHeight = input("请输入身高(m):") personHeight = float(personHeight) # 体重 personWeight = input("请输入体重(kg):") personWeight = float(personWeight) # 年龄 personAge = input("请输入年龄:") personAge = int(personAge) # 性别 personSex = input("...
fafba52c190eb20239fd2eee2b428bcf0789a867
axellbrendow/python3-basic-to-advanced
/aula013-indices-e-fatiamento-de-strings/aula13.py
638
3.96875
4
""" Manipulando strings * String índices * Fatiamento de strings [início:fim:passo] * Funções built-in len, abs, type, print, etc... Essas funções podem ser usadas diretamente em cada tipo. """ # positivos [012345678] texto = 'Python s2' # positivos -[987654321] print(texto[2:6]) print(texto[:6]) # Eq...
d5febee17c663072625f70edc87e367abb8e67f4
ponvizhi19/Python-Internship
/Day5.py
1,034
4.34375
4
# 1)Create a function getting two integer inputs from user. & print the following: #Addition of two numbers is +value x=int(input("enter the first number:")) y=int(input("enter the second number:")) def add(a,b): print ("the sum is",+a+b) add(x,y) #Subtraction of two numbers is +value x=int(input("enter the first nu...
5502fa3455cd798fb7da1234b0b1dc261a4d049b
raunakpalit/myPythonLearning
/venv/map/map_intro.py
1,594
3.84375
4
# Wrap each of the 4 blocks of code in function definitions, then use the timeit module to # time each one. # # Remember to import timeit at the start of the file. # # My solution will use a slightly different approach, to save time in the video. The test of # whether your solution works is if successfully times all 4 ...
24a581c97b6ddb4508464753de4d075e07720a60
tjbaesman/CSCI-Final-Projects
/PycharmBlackjack/Blackjack_Gameplay.py
4,790
3.578125
4
# TJ Baesman # CSCI 101 - Section D # Blackjack - Gameplay functions from Blackjack_Hand import Hand def deal_new_hands(player_hand, dealer_hand, deck): player_hand.rand_hand(deck) dealer_hand.rand_hand(deck) def make_bets(player_hand): bet_choice_unmade = True print("You have $%d" % player_hand.fu...
4592ad56580e910d04cf621ce715b5ca78a79491
PauDuna/FeF_ej
/ej3/ej3.py
720
3.5625
4
import collatz import time start = time.time() secuencia2 = [] #sec de collatz mas larga hasta el momento numero = 1000000 b = list(range(2,numero+1)) for i in b: a = collatz.collatz (i) if len(a) > len(secuencia2): secuencia2.clear() secuencia2 = a c = set(secuencia2) #hace lo que le...
f4a909437ea389c3ba37b3d01a84a825047a0b0d
jiangjinju/Algorithms
/DP_Cuttingrod.py
1,040
3.671875
4
#Algorithms-Lab9-Dynamic Programing-cutting rod problem #c is unit cutting cost #n is rod total length import copy def OPT(price,n,c): profit=[0 for x in range(n+1)] cutlength=[] #the lenght of each piece profit[0]=0 profit[1] = price[0] cutlength.append([]) cutlength[0]=[] cu...