blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
d8934ad267ed1e02c9cc609bcf333d30f90d72ef
JonasAraujoP/Python
/desafios/desafio003.py
238
3.9375
4
"""Crie um programa que leia dois números e mostrre a soma entre eles""" x1 = int(input('Digite um número inteiro: ')) x2 = int(input('Digite outro número inteiro: ')) soma = x1 + x2 print(f'A soma de {x1} + {x2} é igual a {soma}')
7a07017dfad85df43dace040c37d7131bb46469d
goodmami/pydmrs
/pydmrs/matching/common.py
1,091
3.546875
4
def are_equal_nodes(n1, n2): """Returns True if nodes n1 and n2 have the same predicate and sortinfo.""" return n1.pred == n2.pred and n1.sortinfo == n2.sortinfo and n1.carg == n2.carg def are_equal_links(l1, l2, dmrs1, dmrs2): """Returns True if links l1 and l2 have the same link label and their s...
d0fb9c93e3f84385763132287c685f56e4c26068
calvinfroedge/Factorials
/forLoop/for.py
272
4.125
4
import sys def factorial(number): product = 1 for i in range(number): product = product * (i + 1) #This will also work: #for i in range(number + 1) # if i > 0: product = product * (i) return product number = int(sys.argv[1]) print(factorial(number))
2ac2e14b947a8e0734340f5bd08862954645c813
SOURADEEP-DONNY/WORKING-WITH-PYTHON
/PRA practice/PRA1.py
1,220
3.765625
4
class Employee: def __init__(self,employeeId,employeeName,gelnRole): self.employeeId=employeeId self.employeeName=employeeName self.gelnRole=gelnRole self.status="In Service" class Organization: def __init__(self,employeeList): self.employeeList=employeeList ...
c4167ce0440026258141ff33fb5c0ba2404938fa
Artarin/study-python-Erick-Metis
/operation_with_files/exceptions/words_counter.py
488
3.96875
4
"""this program search and counting quontity of simple word in text.file""" pre_path = "books_for_analysis//" books = ["Életbölcseség.txt", "Chambers's.txt", "Crash Beam by John Barrett.txt" ] for book in books: print (book +':') with open (pre_path+book, 'r', encoding='utf-8...
ef79d66df178986222288328d66bb6daa3a4b3f1
tanyuejiao/python_2.7_stuty
/lxf/class2.py
1,908
4.125
4
#!/usr/bin/python # coding:utf-8 import types '''获取对象信息 当我们拿到一个对象的引用时,如何知道这个对象是什么类型、有哪些方法呢? 使用type() 首先,我们来判断对象类型,使用type()函数: 基本类型都可以用type()判断:''' print type(123) # <class 'int'> print type('str') # <class 'str'> print type(None) # <type(None) 'NoneType'> # 如果一个变量指向函数或者类,也可以用type()判断: def abs(): pass class Ani...
aa321b38167013ce2065bd7ab5904d4b03531bd3
MYMSSENDOG/leetcodes
/5342.py
759
3.59375
4
class ProductOfNumbers: def __init__(self): self.q = [0] self.zero = 0 def add(self, num: int) -> None: if num == 0: self.zero = 0 else: self.zero +=1 prev = self.q[-1] if prev == 0: self.q.append(num) else: ...
45ac29731a0cc535df4b340cb5cc8ac33d7faaef
MariaTrindade/CursoPython
/exercises/04_While/exe_07.py
861
3.984375
4
""" Crie um programa tabuada que permita ao usuário solicitar quantas vezes ele quiser, encerrando quando o mesmo responder não querer mais utilizar o programa, então finalize o programa com uma mensagem de agradecimento. """ from time import sleep resposta = '' while True: num = int(input('Digite um número para...
801ff85c4d046ed033f90f2a07f76de0f362bd7b
ColtanF/QuizGenerator
/randomQuizGenerator.py
7,358
3.765625
4
#! python3 # atbsRandomQuizGenerator.py - Creates quizzes with questions and answers in # random order, along with the answer key import random import pyinputplus as pyip import sys import time # parseCSV(filename): # This function parses the first two items in each line of a csv into a dictionary, # w...
98a3333b35be10432866b70d8c8f17041f15bdb8
santidev10/scripts_week4
/untitled1.py
6,927
4.03125
4
# -*- coding: utf-8 -*- """ Created on Sat Apr 7 22:46:44 2018 learnpython2org.py @author: santi """ # NUMPY ARRAYS # Numpy arrays are great alternatives to Python Lists. Some of the key advantages # of Numpy arrays are that they are fast, easy to work with, and give users the # opportunity to perform calculations a...
dfbce9470c844c17a10c601eca96b1de327e37b3
erjan/coding_exercises
/minimum_number_of_days_to_eat_n_oranges.py
1,738
3.953125
4
''' There are n oranges in the kitchen and you decided to eat some of these oranges every day as follows: Eat one orange. If the number of remaining oranges n is divisible by 2 then you can eat n / 2 oranges. If the number of remaining oranges n is divisible by 3 then you can eat 2 * (n / 3) oranges. You can only choo...
f576082d45209e7973d17cca05ec0e82c35f1f86
Kokonaut/fundamentals-lab-2
/lab.py
1,329
4.28125
4
""" Our functions will be imported into the game engine and used to make decisions for our sprite. Input 'coord_name' will be in format: {letter}{number} For example: a3 b5 e9 etc. Think of it like chess positions. ie b2 will be here: 3 | 2 | x 1 | 0 | _ _ _ _ a b c d Given a position of our spr...
aee95209d8cde11997fd95fe57ba8c2d88f4d6f1
utsav-crypto/Coding
/array/array_3.py
202
3.84375
4
'''Kth MAX AND MIN ELEMENT OF AN ARRAY''' def kth_max_min(arr, k): pass arr = [12, 45, 23, 24, 46, 44, 35] result = kth_max_min(arr, 3) print("MAX = ", result[0], "MIN = ", result[1])
bb7b1acaf887a82998b6dfb724606bf62c385bb3
arovit/Coding-practise
/misc/smallest_difference.py
480
3.5
4
#!/usr/bin/python def find_small_diff(a,b): a = sorted(a) b = sorted(b) i = j = 0 min = 999999999999999999 min_a = 0 min_b = 0 while (i < len(a)) and (j < len(b)): if abs(a[i]-b[j]) < min: min = abs(a[i]-b[j]) min_a = a[i] min_b = b[j] if (a[i] < ...
ed0be8c5cc5d9b05f072ca45bb25e2f8d199437d
Dhanaskv/Python
/simpleInterestNormal.py
168
3.859375
4
#!/usr/bin/python P=int(input("The principal amount is :")) T=float(input("The time of periods :")) R=float(input("The rate of interest :")) print((P*T*R)/100)
c21f03eda22f80d3ea66ca52739df541edeb9634
Seariell/basics-of-python
/hw5/task_6.py
1,646
3.96875
4
# homework lesson: 5, task: 6 """ Необходимо создать (не программно) текстовый файл, где каждая строка описывает учебный предмет и наличие лекционных, практических и лабораторных занятий по этому предмету и их количество. Важно, чтобы для каждого предмета не обязательно были все типы занятий. Сформировать словарь, соде...
a643f532c53ac1223953596bb1cd442f443020b2
theond/leetcode_solution
/python/baseStruct/BaseArray.py
152
3.578125
4
# 创建字符串 s1 = str() s2 = "improvegogogo" #字符串长度 s2Len = len(s2) # print(s2Len) # 切割字符串 subS2 = s2[-3:] # 等同于s2[10:13]
99cbe2195b5cb23a81d612beb4b265d6b3fb242e
Luid101/CSC108-assignments
/game_data.py
19,900
3.75
4
class Location: def __init__(self, position, visit_points, brief_description, long_description, available_moves, items, is_locked=False, key="", open_text="", closed_text=""): ''' Creates a new location. Data that could be associated with each Location object: a po...
aca317a1acf23f9f849d00fa931bedb40e3bc805
learnerofmuses/slotMachine
/jan29.py
617
3.8125
4
#In this program you will perfrom password validation. A website is #publication the following password rules: #1. length: at least 6 characters and no more than 10 #2. the password must include at least ONE special character #(the character which is not a letter and not a digit) import random def random_string(siz...
658af03cda8901181f8ab898d3e2553ecd3277a8
JosephLevinthal/Research-projects
/5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/224/users/4375/codes/1753_3089.py
247
4.125
4
num=int(input("digite um numero:")) cont=0 soma=0 while(num!=0): soma=soma+num num=int(input("digite um numero:")) if(soma<0): print(soma) print("Esquerda") if(soma>0): print(soma) print("Direita") if(soma==0): print(soma) print("Inicial")
3544e13e0b4bef8b7847b2f9e03ad68026c82379
njsqr/PythonSource
/nwzy/T1087_NO.py
707
3.796875
4
#!/user/bin/env python # _*_ coding:utf-8 _*_ """ 题目描述: 统计每个元音字母在字符串中出现的次数。 输入: 输入数据首先包括一个整数n,表示测试实例的个数,然后是n行长度不超过100的字符串。 输出: 对于每个测试实例输出5行,格式如下: a:num1 e:num2 i:num3 o:num4 u:num5 样例输入 1 aeiou 样例输出 a:1 e:1 i:1 o:1 u:1 """ n=int(input()) num1=num2=num3=num4=num5=0 str=[] for i in range(0,n): str=input() num1+=...
abad91436184d80839f80855cc18361b4a5bcf20
songhuijuantianxiezuo/all
/20180819/1.py
5,455
3.515625
4
#c:\users\lenovo\appdata\local\programs\python # import math # from selenium import webdriver # browser=webdriver.Chrome() # browser.get('http://www.kugou.com/') # button1=browser.find_element_by_css_selector('.searh_btn').click() # checkbox1=browser.find_element_by_css_selector('.search_icon.checkall').click() # butt...
d35f817aa4fa70bc002f45d5125fe5817c45e226
jellywoon/lalala
/circle.py
735
3.5625
4
import pygame import random class Circle: def __init__(self, x, y, color, radius, thickness, direction): self.x = x self.y = y self.radius = radius self.thickness = thickness self.color = color self.direction = direction def make_circle(self, screen): ...
ccfe736ed86399007828c7a807a2b78ab42b96f0
amandamorris/hackerrank
/thirty_days_code/day14.py
578
3.8125
4
class Difference: def __init__(self, a): self.__elements = a def computeDifference(self): """Finds the maximum difference between any two elements in self.__elements""" length = len(self.__elements) max_diff = abs(self.__elements[0] - self.__elements[1]) for i i...
655e50b2cd79d8a2aec0cc4d82c1e987266d41fa
j-hermansen/in4110
/assignment4/4-3/instapy/__init__.py
3,580
3.796875
4
import cv2 import numpy as np from numba import jit def greyscale_image(input_filename, output_filename=None): """Function to read image and make it greyscale. :param filename: image name in filepath :return: new greyscaled 3d array that represents image """ image = cv2.imread(input_filename) ...
a965483570109c674e7fd291c7e4b599df2339e9
pbarton666/learninglab
/kirby-course/py_waldo.py
1,015
3.78125
4
# -*- coding: utf-8 -*- """ Created on Mon Apr 17 17:23:45 2017 @author: Kirby Urner Example of the "Where's Waldo" genre: https://i.ytimg.com/vi/SiYrSYd7mlc/maxresdefault.jpg Extract "Waldo" from each data structure """ data = {"id:":["Joe", "Smith"], "mother": ["Judy", "Smith"], "father": ["Waldo...
c0a7fe91425c4319203b8bbd0e3698e75889bc90
mihaelacr/ProjectEuler
/Problem84.py
3,515
3.640625
4
import random from itertools import count boardtxt = """go a1 cc1 a2 t1 r1 b1 ch1 b2 b3 jail c1 u1 c2 c3 r2 d1 cc2 d2 d3 fp e1 ch2 e2 e3 r3 f1 f2 u2 f3 g2j g1 g2 cc3 g3 r4 ch3 h1 t2 h2""" board = boardtxt.split() JAIL = board.index("jail") GO = board.index("go") NPLACES = len(board) NSIDES = 4 posit...
ca101ee61e787b02f03db74bfbce1829dcd34ede
JAreina/python
/4_py_libro_1_pydroid/venv/4_py_libro_1_pydroid/clases_objetos/py_6_herencia_sobrecarga_operadores.py
838
3.90625
4
class X(): def __init__(self,first,last,pay): self.f_name = first self.l_name = last self.pay_amt = pay self.full_name = first+" "+last def make_email(self): return self.f_name+ "."+self.l_name+"@xyz.com" # sobrecsrga operador + def __add__(self,other):...
359ac8fa648d7500615b8900f1481c0f6484f208
helgirfer/EjercicioCalificaciones
/test/calificaciones_test.py
777
3.5
4
''' Created on 5 oct. 2021 @author: Usuario ''' import unittest from main.calificaciones import calcula_nota_cuestionario from main.calificaciones import lee_datos_cuestionario class calificaciones_test(unittest.TestCase): def test_calcula_nota_cuestionario(self): aciertos, errores, res...
916f46b401004840eaf73094ee23f1f3ab1291e3
JakobSonstebo/IN1900
/Oblig/Uke 38/quadratic_roots_error.py
1,629
4.25
4
from math import sqrt import sys def find_roots(a, b, c): """Function that takes a, b, c and returns the roots of a the polynomial ax^2 + bx + c""" x = (-b + sqrt(b*b - 4*a*c))/(2*a) y = (-b - sqrt(b*b - 4*a*c))/(2*a) return x, y coeff = ['a', 'b', 'c'] ...
46a475d3e5d82ff1f867d4a32477837691f14733
siunixdev/python_pro_bootcamp_2021
/day6/defining-and-calling-python-function.py
224
3.5625
4
# how to write function ''' def function_name(): do this then do this finally do this ''' def my_function(): print("Hello!") def my_function2(name): print(f"Hello {name}!") my_function() my_function2("Abdillah")
de94e5c2a1da1d4a5086e7457b8770d1296e5e32
yuan-88/Data-Structures-and-Algorithms-using-Python
/sort/selection_sort.py
364
3.953125
4
# Selection sort # Author: Y. def selection_sort(arr): for i in range(len(arr)): min_ind = i for j in range(i+1, len(arr)): if arr[j] < arr[min_ind]: min_ind = j arr[i], arr[min_ind] = arr[min_ind], arr[i] if __name__=="__main__": arr = [6, 1, 0, -2, -4, 3...
e49dda7d45bcdcfa7d03848390f72eec155fe70e
serinamarie/CS-Hash-Tables-Sprint
/applications/lookup_table/lookup_table.py
2,083
3.59375
4
# Your code here import random import math def slowfun_too_slow(x, y): # let v be x ^ y v = math.pow(x, y) # let v be v*(v-1)*(v-2)...(v-n) where (v-n) = 1 v = math.factorial(v) # set v equal to the floor division result of the sum of x and y v //= (x + y) # let v be the remainder of ...
d8e6bbdea7e4b337dd00e78227c186fc2dd8a728
arjun-krishna/Multi-Layered-Perceptron
/src/MLP.py
5,874
3.640625
4
""" @author : arjun-krishna @desc : The MLP class, with the methods to train and test """ from __future__ import print_function import numpy as np from mnist_reader import display_img def sigmoid(x, derivative=False) : if derivative : y = sigmoid(x) return y*(1 - y) else : return 1 / (1 + np.exp(-x)) def rel...
56b3d416719e531525e3809c3698dd6a56c2c447
andrewbates09/maxit
/playmaxit.py
5,849
3.734375
4
#!/usr/bin/python3 # # Author : Andrew M Bates (abates09) # ''' IMPORTS ''' #import curses # for coloured triangulation import os import random # simple cross platform clear screen def clearScreen(): if os.name == 'posix': os.system('clear') else: os.system('cls') # print the basic intr...
3317a02a650c2e988e337e2c4690e6e2e54e40ac
christopher-burke/python-scripts
/cb_scripts/demo/asyncio_demo_2.py
1,535
4.09375
4
#!/usr/bin/env python3 """Asyncio demo finding next prime numbers for a list.""" import asyncio from math import sqrt from functools import reduce def factors(n): """Find all factors of a number n. https://stackoverflow.com/questions/6800193/what-is-the-most-efficient-way-of-finding-all-the-factors-of-a-...
adac82f3ced96c7b3bc2f7f6b6bd41a783e04504
josivandodosanjos/ALGO_REDES_2016_2_LISTA4
/Lista2.2_Quest1.py
567
4
4
senhas = [ input("1° - Usuario Cadastre sua primeira senha: "), input("2° - Usuario Cadastre sua segunda senha: "), input("3° - Usuario Cadastre sua terceira senha: "), input("4° - Usuario Cadastre sua quarta senha: ")] input("=============LOGIN==============") login1 =...
495ef8d344ab329e125ad642c6140b689c7c273d
derekfulmer/netutils
/netutils/interface.py
4,428
4.15625
4
"""Functions for working with interface.""" from .variables import BASE_INTERFACES, REVERSE_MAPPING def split_interface(interface): """Split an interface name based on first digit, slash, or space match. Args: interface (str): The interface you are attempting to split. Returns: tuple: T...
cba4a454fce841f7bb2099d818e95308e1ad80c6
aswath1711/code-kata-player
/set5_10.py
236
3.59375
4
# -*- coding: utf-8 -*- """ Created on Fri Jul 19 23:50:04 2019 @author: New """ num = int(input()) a =0 for i in range(2,num): if num%i ==0: a = 1 print("yes") break if a==0: print("no")
a333c94336ae9bb7131c837127266399edfb67b7
francescaberkoh/UnitSix
/03.py
545
3.90625
4
''' Created on Apr 17, 2019 @author: s271486 ''' class Information(): def __init__(self, person, address, postal_code): self.person = person self.address = address self.postal_code = postal_code user = input("Enter your name:") useraddress = input("Enter your address:") user...
f198c9aa582996d7a0ea6d58b44f99cd3bf7702d
631068264/learn_science
/learn_sklearn/预处理.py
1,675
3.578125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- """ @author = 'wyx' @time = 2017/6/18 14:27 @annotation = '' """ """ 文字信息 转化为数字 """ """ Dealing with categorical features in Python ● scikit-learn: OneHotEncoder() ● pandas: get_dummies() """ """ In [3]: df_origin = pd.get_dummies(df) In [4]: print(df_origin.head()) mpg d...
a0fd344d0c45ce50367ce78b85565d04f02987ae
kwonbora1004/python
/20200523/test.py
355
3.921875
4
# print("Hello World Python") # if True: # print("True") # else: # print("False") # a = 1 # b = 2 # c = 3 # total = a + \ # b + \ # c # print(total) # total1 = a+ b +c # print(total1) # msg='안녕하세요' # msg1="안녕하세요" # print(msg) # print(msg1) ''' 여러라인 주석 print(msg) print(msg) print(msg) print(msg) '''...
2677bf06bd507748a12bb10ff3884f046c0b785f
hrushigade/learnpython
/divisiblebygivennumber.py
194
3.875
4
lower=int(input("enter lower range limit")) upper=int(input("enter upper range limit")) n=int(input("enter the no to be divided")) for i in range(lower,upper+1): if(i%n==0): print(i)
592a76ad05ac4db53930f4c886c5c4a7074f1544
amard07/LeetCode
/ExtraCandies.py
321
3.53125
4
class Solution: def kidsWithCandies(self, candies: List[int], extraCandies: int) -> List[bool]: max_candy_amount = max(candies) for index in range(len(candies)): if candies[index] + extraCandies >= max_candy_amount: yield True else: yield False...
9db6b0d09b10a43f753aab755f3ae003a92263c2
1158990163/PYnotebook1
/Day02_26/test.py
180
3.53125
4
t=(0,0) tps=[] tps.append(t) tps.append(t) tps.append(t) tps.append(t) tp=[(1,2),(2,3),(3,3),(1,4)] tp.sort() print(tp) print(tp[1][1]) print(tps) for i in range(3): print(i)
75d3bc79c9fb838972bb64712b36e7cd07dc411f
proRamLOGO/Competitive_Programming
/Leetcode_30DaysChallenge/1_6_Anagrams.py
695
3.546875
4
primes = [] def __init__primes() : global primes primes = [2] isprime = [True for i in range(102) ] for i in range(3,102,2) : if isprime[i] : primes.append(i) for j in range(i*i, 102, i) : isprime[j] = False def groupAnagrams( strs ) : globa...
9c31e7146fdf668def279997ed31a05fe2d5a8a5
yanjieren16/coding-problem
/Flatten_Binary_Tree2LL.py
943
4.0625
4
""" Given a binary tree, flatten it to a linked list in-place. """ # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None # use stack to pre-order traversal class Solution(object): def flatten(self, ...
d7ea51cc390ba0e11e1e6c671342d210303e3632
KerwinTy/PythonTutorial01162018
/ARGEPARSE.py
269
3.65625
4
import argparse parser = argparse.ArgumentParser() parser.add_argument("arianne") args = parser.parse_args() print(args.arianne) if args.arianne == "Maganda": print ("Panget ako") elif args.arianne == "Mataray": print ("Tru") else: print ("Manlilibre ako")
619d317ee55a9b7d33b6b4c01614acfd02e88e68
mauricio208/pythonScripts
/binary-tree.py
1,160
3.875
4
class Tree: def __init__(self, data=None): self.__l = None self.__r = None self.data = data def add_l(self, data): self.__l = Tree(data) return self.__l def add_r(self, data): self.__r = Tree(data) return self.__r def l(self): return self....
bf9d66394a2a7b3eb4f884989e59965beb627bc3
little-alexandra/nlp_study_group
/1_zn/zn_问答系统&文本纠错_0404/algorithm-complexity.py
1,944
3.5
4
#!/usr/bin/env python # coding: utf-8 # ### 时间复杂度和空间复杂度 # # 这是任何AI工程师必须要深入理解的概念。对于每一个设计出来的算法都需要从这两个方面来分析 # O(N), O(N^2) : o notation # In[ ]: int a = 0, b = 0; ''' 复杂度是相对于问题的大小的, 排序算法: 问题大小是:要被排序的数组的长度 复杂度:相对于长度(正比,N^2, logN) ''' for (i = 0; i < N; i++) { a = a + rand(); b = b + rand(); } ##2*N = ...
db00d30521887c638fd47b68ae6371d27f962156
BenDosch/holbertonschool-higher_level_programming
/0x03-python-data_structures/10-divisible_by_2.py
599
4.21875
4
#!/usr/bin/python3 def divisible_by_2(my_list=[]): bool_list = [] for i in range(len(my_list)): if my_list[i] % 2: bool_list.append(False) else: bool_list.append(True) return bool_list def main(): my_list = [0, 1, 2, 3, 4, 5, 6] list_r = divisible_by_2(my_li...
380f577eef62b388224573cdbd32ca3afae27f65
khaledshishani32/data-structures-and-algorithms-python
/linked-list-insertions/linked_list_insertions/linked_list_insertion.py
920
4.1875
4
class Node: def __init__(self, data): self.data = data self.next = None class LinkedList: def __init__(self): self.head = None def printList(self): temp = self.head while temp : print(temp.data, end="->") temp = temp.next ...
181b17327110aea0b12797552de8eb52f43a7038
vasavi-test/python
/repo_commands.py
309
3.5
4
import re x="hi this is vasavi. i am working in accenture 9598878675" y=re.search('i',x) print y.group() if re.findall('vasavi',x)!=-1: print "found" else: print "not found" z=re.findall("\d{10}",x) for i in z: print i print re.findall("^hi.*9598878675$",x) email = "rkalyan@gm.com" ph_no = "9121244241"
129661c6836af176101f2b3c41f835073cce406f
uniroma2-algorithms/ingegneria-algoritmi-2018
/python/generator/fibonacci.py
883
3.625
4
""" File name: fibonacci.py Author: Ovidiu Daniel Barba Date created: 10/12/2018 Python Version: 3.7 Generator dei numeri di Fibonacci """ from itertools import islice def fibGen(): """ Generator dei numeri di Fibonacci. Rispetto all'iterator, è una funzione :return: """ p...
2f5191c402c894a161091309a9b8ea7bf9cdd8cb
StephenLingham/MachineLearning
/raymondTitanicForest.py
2,887
3.59375
4
from sklearn.ensemble import RandomForestClassifier import pandas from sklearn import tree import pydotplus from sklearn.tree import DecisionTreeClassifier import matplotlib.pyplot as plt import matplotlib.image as pltimg import numpy as np import types from sklearn import metrics from sklearn.model_selection import t...
dca453c1551fd732e110706bec1465dafc93e813
rendoir/feup-iart
/src/network.py
8,609
3.515625
4
import random import numpy as np class CrossEntropyCost(object): @staticmethod def fn(a, y): """Return the cost associated with an output ``a`` and desired output ``y``.""" return np.sum(np.nan_to_num(-y*np.log(a)-(1-y)*np.log(1-a))) @staticmethod def delta(z, a, y): """Return ...
c68bdf4de0eb6e6dda0a2fdc071f23edec3d6185
falakjain98/10-Days-of-Statistics
/Day 1/Standard-Deviation.py
300
3.78125
4
# Enter your code here. Read input from STDIN. Print output to STDOUT import math n = int(input()) a = input() nums=[] for i in a.split(' '): nums.append(int(i)) mean = sum(nums)/n sqd = [] for i in range(n): sqd.append((nums[i] - mean)**2) sigma = round(math.sqrt(sum(sqd)/n),1) print(sigma)
2347d5071cf613004a8216fa9fb0be9b65196f09
Vaibhav3007/Python_List
/LongestInList.py
303
4.03125
4
a = [] n = int(input("Enter the number of elements in list: ")) for x in range(0,n): elements = input("Enter element" + str(x+1) + ":") a.append(elements) maxx = 0 for i in range(n): if len(a[i]) > maxx: maxx = len(a[i]) j = i print("Longest word in the list",a,"is",a[j])
2b16a928176dd829c28fe2ee5c95ed94658c6008
yashkumarsingh99/tathastu_week_of_code
/day1/Prog2.py
132
4.15625
4
number = float(input("Enter the number to get the square root: ")) sqrt = number ** 0.5 print("Square root of", number ,"is", sqrt)
3d562305318506e69eed83fe88f4676d09d57f90
isisisisisitch/geekPython
/homework/listpractice02.py
292
3.9375
4
# 2. 2.1给定2个list 2.2从这2个list当中取出公共部分 # # list1=[1,2,3,4] # # list2=[1,2,5] # # Com = [1,2] list1=[1,2,3,4] list2=[1,2,5] com=[] for i in range(len(list1)): for j in range(len(list2)): if list2[j]==list1[i]: com.append(list2[j]) print(com)
cfeb2b9d36ddfb3b7d545256ef6947293b5cea0f
aditidesai27/wacpythonwebinar
/DAY02/2.1declaring_attribute.py
230
3.53125
4
class Student: def __init__(self, first, last, enroll): self.fname = first self.lname = last self.roll = enroll st1 = Student("Neeraj", "Sharma", 31) print(st1.fname) print(st1.lname)
ece8b4216d88d61ec1faa60a79d6ab2b5699b7f0
ManuelsPonce/ACC_ProgrammingClasses
/COSC1336-IntroToProgramming/Test/Test 2/2-1.py
1,634
4.0625
4
def main(): try: numGrade1=float(input('Enter first grade: ')) #ASKS USER FOR 5 GRADES numGrade2=float(input('Enter second grade: ')) numGrade3=float(input('Enter third grade: ')) numGrade4=float(input('Enter fourth grade: ')) numGrade5=float(input('Enter fif...
0a38bae9b3bc7b08f98d8f59f692170b3e393700
JeffLutzenberger/project-euler
/20.py
180
3.515625
4
def fact(n): ans = 1 for i in range(1, n): ans *= i return ans ans = fact(100) sum_digits = 0 for i in str(ans): sum_digits += int(i) print(sum_digits)
97adf67e15070c180fe64d956d430197ae4d038e
panasabena/PythonExercises
/Ejercicio 11 Udemy de 0 a Master.py
278
4.15625
4
#(3) Escribir un programa que pregunte al usuario su edad y muestre #por pantalla todos los años que ha cumplido (desde 1 hasta su edad). edad=int(input("Ingrese su edad: ")) numero=0 while numero< edad: numero+=1 print("Usted ha cumplido", numero, "años alguna vez")
6102ef9f156e84f8fdea6bf7016802a5e415e103
KubaWasik/object-oriented-programming-python
/student.py
4,962
3.953125
4
class Pupil: """Klasa Pupil zawierająca dane o uczniu oraz jego ocenach i wagach""" grades = [1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5, 5.0, 5.5, 6.0] def __init__(self, name="Nieznane", surname="Nieznane"): self.name = name self.surname = surname self.marks = {} @property de...
88b49484b94ec00a2700245de6aab09c02e5ad13
homawccc/PythonPracticeFiles
/simple_addition.py
155
3.515625
4
def simple_addition(num1, num2): answer = num1 + num2 print(answer) simple_addition(123,456) x = [ [2,6],[6,2],[8,2],[5,12] ] print(x[2][0])
6ae8fd546159d8e5653db74c3d6469a892eb4ea3
Colaplusice/algorithm_and_data_structure
/LeetCode/week_38/107_二叉树的层次遍历2.py
1,645
3.984375
4
# 给定一个二叉树,返回其节点值自底向上的层次遍历。 (即按从叶子节点所在层到根节点所在的层,逐层从左向右遍历) # 例如: # Definition for a binary tree node. from collections import deque, defaultdict class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def levelOrderBottom(self, root): ...
3130937d3e55207ee020c8c35ad40b892c1d23f7
stanislavkozlovski/python_exercises
/hackerrank/algorithms/strings/camel_case.py
186
4.15625
4
# https://www.hackerrank.com/challenges/camelcase string = input() upper_case_words = 1 for char in string: if char.isupper(): upper_case_words += 1 print(upper_case_words)
9c14a4f7a72c6f7c0d7861c469d7ff5981b335e2
nlscng/ubiquitous-octo-robot
/p000/problem-74/CountInMulitiplicatinoTable.py
1,288
3.890625
4
# Good morning! Here's your coding interview problem for today. # # This problem was asked by Apple. # # Suppose you have a multiplication table that is N by N. That is, a 2D array where the value at the i-th row and # j-th column is (i + 1) * (j + 1) (if 0-indexed) or i * j (if 1-indexed). # # Given integers N and X, ...
05f33d7507e4025c012f35241413ccf03d5b0139
scMarth/Learning
/python/rounding.py
1,261
4.03125
4
import decimal # python by default will round down on a half decimal: # php by default rounds up half decimals print(0.5555) print(round(0.5555, 3)) # https://stackoverflow.com/questions/33019698/how-to-properly-round-up-half-float-numbers-in-python num = 0.5555 dec = decimal.Decimal(num) # rounded = dec.quantize(d...
da2e01fc589fc1c569a5fe0e4e0a7275a11d49a4
rhkd1129/Algorithm
/inflearn/sec02/8/AA.py
450
3.640625
4
# 뒤집은 소수 import sys #sys.stdin = open('input.txt', 'rt') n = int(input()) arr = list(map(int, input().split())) def reverse(x): str_x = str(x) tmp = '' for i in range(len(str_x)): tmp += str_x[len(str_x)-i-1] return int(tmp) def isPrime(x): for i in range(2, x): if x%i==0: ...
319a09ad13f7ca9a46a22db583928752b8f109be
VilenShvedov/Myprojects
/hometask002.py
611
3.8125
4
'''user_number = input('Enter some number please from 1 to 100') if int(user_number) % (3 or 5) == 0: print(str(user_number) + ' FizzBuzz') elif int(user_number) % (3 or 5) == 1: print(str(user_number)) elif pint(user_number) % 3 == 0: print(str(user_number + ' Is a fizz')) if int(user_number) % 5 ==...
15827661617839596229859a1a6d99c5c20d89b3
hershsingh/manim-dirichlet
/play.py
10,400
3.921875
4
#!/bin/python ### # from manim import * import manim class Example(manim.Scene): def construct(self): circle = manim.Circle() # create a circle circle.set_fill(manim.PINK, opacity=0.5) # set the color and transparency anim = manim.Create(circle) self.play( anim ) # show the cir...
136fd7da997780307137197a91f108864e4e3b83
Yasin-Shah/dataquest-projects
/Project 9 - Working with Data Downloads/enrollment.py
812
3.578125
4
import pandas as pd data = pd.read_csv("data/CRDC2013_14.csv", encoding = "Latin-1") data["total_enrollment"] = data["TOT_ENR_M"] + data["TOT_ENR_F"] all_enrollment = data["total_enrollment"].sum() school_enrollment = [ 'SCH_ENR_HI_M', 'SCH_ENR_HI_F', 'SCH_ENR_AM_M', 'SCH_ENR_AM_F', 'SCH_ENR_AS_...
83feaeb5c4761021cfff63227c09d1d64ba4f907
JCOUO/0820
/THE USELESS THING.py
1,961
3.625
4
# -*- coding: utf-8 -*- """ Created on Thu Aug 20 11:11:38 2020 @author: user """ d = {} print ("THE USELESS THING EVER !!!!") while True : print('1.SET ') print('2.LIST ALL THE WORD ') print('3.ENG TO CH ') print('4.CH TO ENG ') print('5.TEST ') print('6.QUIT ') ...
4e8a1820a6a2471ad67290e96d0f6c29ea47f42e
Chalmiller/competitive_programming
/python/leetcode_top_interview_questions/dynamic_programming/jump_game.py
536
3.90625
4
from typing import * import unittest class Solution: def canJump(self, nums: List[int]) -> bool: max_reach, n = 0, len(nums) for i, num in enumerate(nums): if max_reach < i: return False if max_reach >= n-1: return True max_reach =...
031ca253207b074370573b421b1356c89274d245
wufanwillan/leet_code
/Maximum Depth of Binary Tree.py
1,117
4.03125
4
# Given a binary tree, find its maximum depth. # The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # se...
e0b348468128281de8f6be605b7bbaa5b0d9f521
sarahhabershon/birdoftheyear_preferential_voting
/preferential_voting.py
2,056
3.578125
4
import csv import copy import codecs data = open('votes_all.csv', encoding="utf8") vote_list = csv.reader(data) finalScores = [] def cleanData(x): clean_birds = [] for row in x: length = len(row) makeListsEqualLength(row, length) clean_birds.append(row) return clean_birds def makeListsEqualLength(row, lengt...
b56ef0e786627a2a5edcb4329c52795a9713bcfd
WeDias/RespCEV
/Exercicios-Mundo2/ex049.py
172
3.953125
4
num1 = int(input('Digite Um Numero Para Ver Sua Tabuada:')) num2 = 0 for num2 in range(1, 11): mult = num1 * num2 print('{}X{} = {}'.format(num1, num2, mult))
1ed76c415eb2d7d1081a6bd1793c24257d91494f
liweiwei1419/Machine-Learning-is-Fun
/Mathematics-learning/fibonacci_demo.py
625
4
4
class Fibonacci(object): ''' 返回一个 fibonacci 数列''' def __init__(self): self.fList = [0, 1] # 设置初始的列表 self.main() def main(self): listLen = input("请输入的 fibonacci 数列的长度:") while len((self.fList)) < int(listLen): self.fList.append(self.fList[-1] + self.fList[-2]) ...
11d30722b9e1bcefe29127ad51752c47d12b6d81
FelixZFB/Python_advanced_learning
/02_Python_advanced_grammar_supplement/001_9_高级语法(魔法属性-init-module-class-call)/002_魔法属性__call__str__方法.py
760
4.09375
4
# __call__方法:实例化对象后面加括号,触发执行。 # 注:__init__方法的执行是由创建对象自动触发的,即:对象 = 类名() ; # 而对于 __call__ 方法的执行是由对象后加括号触发的,即:对象() 或者 类()() class Foo(object): def __init__(self): pass def __call__(self, *args, **kwargs): print("__call__") def __str__(self): return "获取对象描述时候自动调用" obj = Foo() # 自动执...
44a84208fbff9098bfa62e57c0e815a42bfa2bf1
kthdd1234/basic-python-syntax
/class instance.py
839
3.9375
4
# 클래스(class): 함수나 변수들을 모아 놓은 집합체 # 인스턴스(instance): 클래스에 의해 생성된 객체, 인스턴스 각자 자신의 값을 가지고 있다. numbers1 = [] numbers2 = list(range(10)) characters = list('Harry') print(characters) numbers1 == list # 같지 않음 # 클래스 만들기 # 클래스와 인스턴스를 이용하면 데이터와 코드를 사람이 이해하기 쉽게 포장할 수 있다. class Human(): """person""" def speak(person): ...
0883ee1e5d6b72ca1c2c31980b1b5aefb40744dd
green-fox-academy/Atis0505
/week-05/day-03/min_max_diff.py
561
3.953125
4
# Create a function called `min_max_diff` that takes a list of numbers as parameter # and returns the difference between maximum and minimum values in the list # Create basic unit tests for it with at least 3 different test cases def min_max_diff(number_list): if len(number_list) == 1: return number_list[0...
1a4d4960ad651a4cf7bb48859a4252b6d4a00e1c
Tesla99977/Homework-Tasks-
/Python ДЗ/14.py
157
3.671875
4
s = float(input()) r = float(input()) k = float(input()) if (s**0.5)/2 > r and ((s**0.5-k)/2 >= r) : print("Можно") else: print("Нельзя")
109026b92a9c40e56c91c9e2ccba768b70331047
Muhammad-CS/Missing-Operator-Calculator
/Missing Operator Calculator.py
2,339
3.765625
4
import itertools string='1?2?3' def operation_counter(string): count = 0 for i in string: if (i == '?'): count += 1 else: pass return count def q_positions(string): positions = [] for i in range(len(string)): if (string[i] == '?'): ...
49c74b6bd6ee672a40cc576d8c97150f42e9eb99
igorverse/CC8210-programacao-avancada-I
/aulas_de_lab/aula6/ex3.py
1,216
4.15625
4
''' Faça uma função chamada contaPalavras que receba uma String e que conte a quantidade de incidências de todas as palavras em uma String, assim listando todas as palavras e suas quantidades, considere como palavras as que tenha uma quantidade igual ou maior que duas letras. A função deverá retornar duas listas, uma ...
d603810654801fe020a313b7aee9802b175413e2
Victor-Light/illumio-coding-challenge
/firewall.py
3,451
3.609375
4
import csv class FireWall: def __init__(self,filePath): with open(filePath) as csvFile: #form a rule map self.inTcp = {"port":[], "ip_address":{}} self.inUdp = {"port":[], "ip_address":{}} self.outTcp = {"port":[], "ip_address":{}} self.outUdp = {...
fe559f4d82572758b44b4896ee105bef4a41e93c
micheofire/studenttestscore
/app.py
692
3.625
4
import pandas as pd import numpy as np import streamlit as st import pickle from sklearn.linear_model import LinearRegression loaded_model = pickle.load(open("finalized_model.sav", 'rb')) st.title("STUDENT TEST SCORE PREDICTION APP") st.write("Please input the student details in the sidebar") gender = st.sidebar.sel...
cc43718830c72934dca478386debdd4a863a69cf
C-CCM-TC1028-111-2113/homework-2-AdrielOlvera
/assignments/02Licencia/src/exercise.py
515
3.90625
4
def main(): #Escribe tu código debajo de esta línea age=int(input("Ingresa tu edad: ")) io=str(input("¿Tienes identificación oficial? (s/n)")) if age>=18: x=True elif 18>age>=0: x=False elif age<0: print("Respuesta incorrecta") x=False if io=="s": y=True elif io=="n": y=False else: ...
fae8ad9595533a95d46058b28d49f304782d221a
francocurses/curses-chess
/source/player.py
1,625
3.6875
4
from pieces.pawn import Pawn from pieces.knight import Knight from pieces.bishop import Bishop from pieces.rook import Rook from pieces.queen import Queen from pieces.king import King class Player(): """ A player in chess. """ def __init__(self,name,pstring): self.name = name self.getpc...
b89b86cc89a94e32efb10d4ca2f738bc78a61a38
francosbenitez/unsam
/06-organizacion-y-complejidad/05-busqueda/busqueda-en-listas.py
854
3.96875
4
""" Ejercicio 6.13: Búsqueda lineal sobre listas ordenadas. Modificá la función busqueda_lineal(lista, e) de la Sección 4.2 para el caso de listas ordenadas, de forma que la función pare cuando encuentre un elemento mayor a e. Llamá a tu nueva función busqueda_lineal_lordenada(lista,e) y guardala en el archivo busqueda...
1fc4a78f1d56fd6990274b51c029a5ae11c1a989
Suykim21/python_references
/algos/basics.py
2,615
4.125
4
# Print 1-255 # for x in range(1,256): # print(x) # Print odd numbers from 1 to 10 # for x in range(1,11): # if(x%2==1): # print(x) # Print the sumof al the odd numbers from 1 to 10 # sum = 0 # for x in range(1, 11): # if(x%2==1): # sum = sum + x # print(sum) # def addOddNumbers(numb...
77096beb877dbf605f71ee1314e146f88d2dfcc8
maxymkuz/cs_3
/Alko/exam/exam_second.py
1,383
4.15625
4
def recursive_solution(x, speed, position): if x == position: return "" if x == position + speed: return "A" sequence = "" while x > position + speed: sequence += "A" position += speed speed *= 2 left_before = x - position left_after = position + speed -...
84c62dc434432290f05e21a2cb21827ad3574772
bashenov98/BFDjango2020
/Week 1/hackerrank/medium/minions.py
284
3.5
4
vowels = ['A', 'E', 'I', 'O', 'U'] s = raw_input() a = 0 b = 0 for i, c in enumerate(s): if c in vowels: b += len(s) - i else: a += len(s) - i if a == b: print "Draw" elif a > b: print 'Stuart {}'.format(a) else: print 'Kevin {}'.format(b)
3ec0e5c9a46da229ab167205ef3455629b91387b
stefaluc/algorithms
/mirror_tree.py
2,115
3.890625
4
#!/usr/bin/python class TreeNode(): def __init__(self, value): self.left = None; self.right = None; self.data = value; def bfs(node): if node == None: return print(node.data) queue = [] queue.append(node.left) queue.append(node.right) for i in queue: ...
6ce5c40e98faad0128315b8d4caed965dab2a827
Unique-Red/HardwaySeries
/ex39sd.py
336
3.65625
4
states = { 'Lagos': 'LA', 'Ondo': 'ON', 'Calabar': 'CA', 'Ogun': 'OG', 'Benin': 'BE' } cities = { 'LA': 'Island', 'ON': 'Ondo town', 'OG': 'Ota' } cities['CA'] = 'Awka' cities['BE'] = 'Edo' print('-' * 5) print("OG State has: ", cities['OG']) print("LA State has: ",...
1b37916a1f394ea8eecc9f9499ac8f8a85f3399f
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/056_Merge_Intervals.py
1,029
3.84375
4
# Definition for an interval. # class Interval(object): # def __init__(self, s=0, e=0): # self.start = s # self.end = e c_ Solution o.. ___ merge intervals """ :type intervals: List[Interval] :rtype: List[Interval] """ __ intervals is N..: r_...
26f85908f72a11b89f731bc00f11da2f1e7f8224
EduardoMachadoCostaOliveira/Python
/CEV/ex070.py
1,222
3.921875
4
# Crie um programa que leia o nome e o preço de vários produto. # O Programa deverá perguntar se o usário vai continuar. No final mostre: # A) Qual é o total gasto na compra. # B) Quantos produtos custam mais de R$ 1000. # C) Qual é o nome do produto mais barato. print('-' * 30) print('{:-^30}'.format(' LOJA SUPER BAR...
d22bbde0e626f90c742d28b3af711a2a35552888
salihdeg/wp-message-sender
/WhatsAppMessageSender/Business/fileReader.py
363
3.53125
4
# -*- coding: UTF-8 -*- import pandas as pd contacts = "" numbers = "" names = "" def save_contacts_from_file(file_path): global contacts global numbers global names contacts = pd.read_excel(file_path) numbers = pd.DataFrame(contacts, columns=['Number']).values.tolist() names = pd.DataFrame(c...
f739a159ddfde1ad4c37f71e190b0f0d491499cc
yongzhuo/leetcode-in-out
/hot/a15_three_sum_closest.py
2,166
3.515625
4
# !/usr/bin/python # -*- coding: utf-8 -*- # @time : 2020/1/3 19:20 # @author : Mo # @function: 16.最接近三数之和 # 给定一个包括 n 个整数的数组 nums 和 一个目标值 target。找出 nums 中的三个整数,使得它们的和与 target 最接近。返回这三个数的和。假定每组输入只存在唯一答案。 # 例如,给定数组 nums = [-1,2,1,-4], 和 target = 1. # 与 target 最接近的三个数的和为 2. (-1 + 2 + 1 = 2). # 来源:力扣(LeetCode) # 链接:h...