blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
aea7836f08d592b045334c13180b01d41acd9d90
Randle9000/pythonCheatSheet
/pythonCourseEu/1Basics/24OOPrograming/Ex1.py
249
3.65625
4
#In fact, everything is a class in Python. x = 42 print(type(x)) #--------------------------------- class Robot: pass if __name__ == "__main__": x = Robot() y = Robot() y2 = y print(y == y2) print(y == x)
f8137076318aa192f55f0334f29d325505cdba17
wegesdal/udacity-ml
/Supervised_Learning/linear_regression3.py
957
3.96875
4
# Add import statements from sklearn.preprocessing import PolynomialFeatures from sklearn.linear_model import LinearRegression import numpy as np import pandas # Assign the data to predictor and outcome variables # Load the data train_data = pandas.read_csv('data2.csv') X = np.reshape([train_data['Var_X']], (20, 1)) y...
705c5c0bc4e22b1b334bf6891dad00b8bf60c3fb
DidiMilikina/DataCamp
/Data Scientist with Python - Career Track /25. Introduction to Deep Learning in Python/03. Building deep learning models with keras/03. Fitting the model.py
958
4.21875
4
''' Fitting the model You're at the most fun part. You'll now fit the model. Recall that the data to be used as predictive features is loaded in a NumPy matrix called predictors and the data to be predicted is stored in a NumPy matrix called target. Your model is pre-written and it has been compiled with the code from ...
af4d6fb2b148eb3c94a1e83d6de949dd27e54d03
Ethan-Hill/Ember-Dragon
/Map.py
7,129
3.65625
4
import inquirer import os import SamTheSmith import Village import Cave import End from termcolor import colored xLimit = 10 yLimit = 10 xPos = 1 yPos = 1 SamVisited = False PeterVisited = False CaveVisited = False EndVisited = False VillagePeopleX = 1 VillagePeopleY = 3 SamTheSmithX = 1 SamTheSmithY = 6 CaveX = 7...
a6a465ef4de0e0663590011fa6ab507ca502429d
shagunattri/PythonScripts
/python/solves/D6/1_0.py
697
3.765625
4
# Check password def is_low(x): for i in x: if 'a'<=i and i<='z': return True return False def is_up(x): for i in x: if 'A'<=i and i<='Z': return True return False def is_num(x): for i in x: if '0'<=i and i<='9': ...
7e517a0e0dc0b9995dbc988be0d2d539c3f3a33e
ekarlekar/MyPythonHW
/0fibbonaccirecursion.py
244
3.9375
4
def fib(n): if (n==1): return (1) elif (n==0): return (0) else: return (fib (n-1)+ fib(n-2)) n=int(raw_input("Type in a number:")) y=0 x=0 while x<=n: x= fib(y) if (x<=n): print(x) y=y+1
5b9e965e0424f80b13d54f4cf0523204fb5fa8bc
ricardoBpinheiro/PythonExercises
/Projetos/projeto1.py
652
3.671875
4
# Seu script deve gerar um valor aleatório entre 1 e 6(ou uma faixa que você definir) # e permitir que o usuário rode o script quantas vezes quiser. import random import time resposta = str(input('Você gosta de jogar dados? ')) c = 'SIM' while c == 'SIM': if resposta in 'simsSimSIM': print('Rodando o dad...
cb641f455c8ed32c5894dbe0f7227ed5ce9c6f46
b1ueskydragon/PythonGround
/dailyOne/P276/trie.py
868
3.59375
4
class Node: def __init__(self, char='*'): self.char = char self.children = {} # {char : Node} self.index = 0 self.word_end = False def cons(root: Node, word: str): curr = root for char in word: for node in curr.children.values(): if node.char == char: ...
559572af9370c5801278858835de5e7d5c02efc2
cwallaceh/Python-Exercises
/flatten_tree_to_linked_list.py
2,121
4.15625
4
# Flatten a binary tree into linked list # Given a binary tree, flatten it into a linked list. # After flattening, the left of each node should point to # NULL and right should contain next node in level order. class BinaryTree(): def __init__(self): self.left = None self.right = None self...
fa06ce33ea1d16c151c6c8ec0123be29a392a462
caiosuzuki/exercicios-python
/ex039.py
403
4.0625
4
from datetime import date ano = int(input('Informe seu ano de nascimento: ')) idade = date.today().year - ano if idade < 18: print('Você ainda vai se alistar ao serviço militar! Falta(m) {} ano(s)!'.format(18-idade)) elif idade == 18: print('Você deve se alistar esse ano ao serviço militar!') else: print('S...
de8f1b975afad9ae373293f8db3086b5521e7393
smithajanardan/janardan_python
/Books.py
3,821
3.765625
4
# File: Books.py # Description: Compares the vocabulary in two books. # Student Name: Smitha Janardan # Student UT EID: ssj398 # Course Name: CS 303E # Unique Number: 52220 # Date Created: 11/19/10 # Date Last Modified: 11/29/10 import string # Create word dictionary from the comprehe...
9cafbcb47eacf896d26bb3e858a4dfc23c6ede90
DainaGariboldi/Daina
/Numero triandulado.py
95
3.625
4
N = int(input()) for R in range (1, N + 1): print(' '.join(str(e) for e in range(1, R +1)))
6646a8b7a4f4ad312921284239906b3e2553eb3a
Kshitiz1403/GeekWeek-Local
/Kshitiz1403/Array3.py
429
4.15625
4
import array arr = array.array('i', [1, 2, 3]) print ("The new created array is : ",end=" ") for i in range (0, 3): print (arr[i], end=" ") print("\r") arr.append(4) print("The appended array is : ", end="") for i in range (0, 4): print (arr[i], end=" ") arr.insert(2, 5) print("\r...
966a31113e51f7f55dafc60a58cae0df749c0a1c
moshlwx/leetcode
/CODE/剑指 Offer 28. 对称的二叉树.py
1,888
4.125
4
r''' 剑指 Offer 28. 对称的二叉树 请实现一个函数,用来判断一棵二叉树是不是对称的。如果一棵二叉树和它的镜像一样,那么它是对称的。 例如,二叉树 [1,2,2,3,4,4,3] 是对称的。 1 / \ 2 2 / \ / \ 3 4 4 3 但是下面这个 [1,2,2,null,3,null,3] 则不是镜像对称的: 1 / \ 2 2 \ \ 3 3 示例 1: 输入:root = [1,2,2,3,4,4,3] 输出:true 示例 2: 输入:root = [1,2,2,null,3,null,3] 输出:false ...
982955e713495bbf8e34d5561d1712bde4d25910
Pxshuo163/GitDoc
/Python/ValidPhoneNumber.py
1,528
3.765625
4
# 手机号码校验 # 校验准则 移动,联通,电信 CN_mobile = [134, 135, 136, 137, 138, 139, 150, 151, 152, 157, 158, 159, 182, 183, 184, 187, 188, 147, 178, 1705] CN_union = [130, 131, 132, 155, 156, 185, 186, 145, 176, 1709] CN_telecom = [133, 153, 180, 181, 189, 177, 1700] # 校验长度是否符合 def valid_length(num): if len(num) == 11: ...
6df091e896cc18b28e24237f17a0c8ab682459e2
Wangyandong-master/MedicalNer
/Vocab.py
3,715
3.578125
4
PAD = "<<PAD>>" UNK = "<<UNK>>" NUM = "<<NUM>>" OUTSIDE = "O" class Vocab: def __init__(self, filename=None, encode_char=False, encode_tag=False): self.max_idx = 0 self.encoding_map = {} self.decoding_map = {} self.encode_char = encode_char self.encode_tag = enc...
0318e00a37bb0a332fb8034c38083e6d900f0570
BoyaChiu/Python_Basic_note
/08_面向对象.py
5,537
4.75
5
# 面向对象 # 类的定义 ''' 基本形式: class ClassName(object): Statement 1.class定义类的关键字 2.ClassName类名,类名的每个单词的首字母大写。 3.object是父类名,object是一切类的基类。在python3中如果继承类是基类可以省略不写。 ''' class Fruits: fruit = 'xxxxxxx' list1 = [] def __init__(self,name,color='red',weight=90): self.na...
ec81e45353cb20332d5b864941a93a3f3292a47e
Fayozxon/python-quests
/Birinchi qism/48.4-musbatlar.py
250
3.65625
4
# a, b va c a = int(input('a: ')) b = int(input('b: ')) c = int(input('c: ')) # Tekshirish: if a > 0: print(a, 'ning kvadrati -', a**2) if b > 0: print(b, 'ning kvadrati -', b**2) if c > 0: print(c, 'ning kvadrati -', c**2)
cfc243618aff89547e241d5f37d3f68755b4c7c9
drybell/coding-problems
/may/may102020/attempt1problem2.py
751
3.984375
4
# This problem was asked by Jane Street. # cons(a, b) constructs a pair, and car(pair) and cdr(pair) # returns the first and last element of that pair. # For example, car(cons(3, 4)) returns 3, and cdr(cons(3, 4)) returns 4. # Given this implementation of cons: def cons(a, b): def pair(f): return f(a, ...
a80df3ebd58df8e023373649ec070fed16836595
Wajahat-Ahmed-NED/WajahatAhmed
/waji.py
538
3.515625
4
class Myemployee: def __init__(self,fnaem,lname,cnic,email,address,salary,post): self.firstname=fnaem self.lname=lname self.cnic=cnic self.email=email self.address=address self.salary=salary self.post=post ali=Myemployee("Ali","Khan","42102156578687",...
9c910a6823d935cbc7604531d1c22a272ff4b096
alading241/metaapi-python-sdk
/lib/clients/methodAccessException.py
1,013
3.5
4
class MethodAccessException(Exception): """Exception which indicates that user doesn't have access to a method. """ def __init__(self, method_name: str, access_type: str = 'api'): """Inits the method access exception. Args: method_name: Name of method. access_type: ...
095a2bc06e271807f87cd0f37e56634778dcc11d
gayathrimaganti/maganti_gayathridevi_spring2017
/Python Assignment-3/Q1_Part_2.py
1,968
3.75
4
# coding: utf-8 # NYC Vehicle Collision Analysis #1.For each borough, find out distribution of each collision scale. (One car involved? Two? Three? or more?) (From 2015 to present) #2.Display a few rows of the output use df.head(). #3.Generate a csv output with five columns ('borough', 'one-vehicle', 'two-vehicles', ...
6d75e370ab4bc70c1a2c6e36e77e93e3559acb46
akashshegde11/python-practice
/Introduction/intro_2.py
142
4.03125
4
# Demo of conditional statement num = int(input("Enter a number: ")) if(num > 15): print("Good number!") else: print("Bad number!")
f69afd92deeb7037b73240ad72e81a271823018a
miltonleal/MAC0110_Introduction_Computer_Science_IME_USP
/Ex. do Paca/Aula 17/P_17.14.py
369
3.625
4
# Função elimina_repetidos(x) que devolve uma lista contendo os elementos da lista x sem repetição. a = [1,1,1,1,1,2,3,4,5] def elimina_repetidos(a): i = 0 result = [] for i in range (len(a)): #while i < len(a): if not (a[i] in a[i+1:]): result.append(a[i]) i += 1 r...
fc0f10d875dca362b0e0bdde56994edc9bc4d155
matthew-samyn/challenge-sentiment-analysis
/app/app.py
2,456
3.609375
4
from PIL import Image from utils.streamlit_functions import * import streamlit as st st.set_page_config(layout="wide") header = st.container() plots = st.container() scrape_section = st.container() # Handles the sidebar option st.sidebar.title("Sentiment analysis") brooklyn_99_button = st.sidebar.selectbox("What sho...
72274d59f3a3a93c4f7225348918bd3c5a4411d4
jlucasldm/ufbaBCC
/2021.2/linguagens_formais_e_automatos/listas/semana_3/encaixa_ou_nao_II.py
739
3.84375
4
#funcao principal Encaixa ou Nao def solucao(a, b): #procurar na string a, a partir do índice (len(a) - len(b)) #ate o fim de a, pela string b #string.fin(substring) retorna -1 caso nao encontre a substring em #questao. caso contrario, retorna o index de onde a substring comeca #retorna '...
667218b768f34f7e1344554c108322e92751deac
jhiltonsantos/ADS-Algoritmos-IFPI
/Atividade_Fabio_01/fabio01_17_area-retangulo.py
267
3.78125
4
# entrada base = float(input('Qual a medida da base do retangulo? ')) altura = float(input('Qual a medida da altura do retangulo? ')) # processamento area_retangulo = base * altura # saida print ('A area do retangulo é de: {}'.format(area_retangulo))
746f2e2a89edcb56369a94eb59a888781e3fc234
dcwales/leevs_space
/Complex.py
898
3.53125
4
""" CMod Ex2: methods for complex numbers represented as Numpy 1*2 arrays """ import math import numpy as np # Complex conjugate def conj(c): return np.array([c[0], -c[1]]) # Square modulus def normSq(c): return c[0]**2 + c[1]**2 # Modulus def norm(c): return math.sqrt(normSq(c)) # Multiplication of...
873ca708b169bb7b0417bedbe1776665a08dc0f2
DanAmador/RMP
/TZMap.py
6,796
3.65625
4
""" This program defines a class that stores the trapezoidal map. It also provides related helper functions. Author: Ajinkya Dhaigude (ad8454@rit.edu) """ class TZMap: def __init__(self, root): self.root = root self.adjMatrix = None self.allPNames = [] self.allQNames ...
c33d51d98f3363cbd92b99940b4d1a51bbd5e7f1
akaProgramer/python_tkinter
/tk_button_pracice.py
927
3.5625
4
from tkinter import * root = Tk() def button1_message(): print("hello from button 1") def button2_message(): print("hello from button 2") def button3_message(): print("hello from button 3") def button4_message(): print("hello from button 4") def button1_message(): print("hello from button 1") root...
90daa8bad236485b1dc4edc69520fc82e757b8ff
lakshmiPrasanna-chebrolu/PythonProjects
/audioSeg&Recog/sr.py
414
3.546875
4
import speech_recognition as sr AUDIO_FILE=("audio-extract.wav") # use audio file as source r=sr.Recognizer() with sr.AudioFile(AUDIO_FILE) as source: audio=r.record(source) try: print("audio file contains:"+r.recognize_google(audio)) except sr.UnknownValueError: print("Google cannot understand") ...
8321da83525bb6e85ce9aee62448682b13bd3c9f
CrispthoAlex/holbertonschool-higher_level_programming
/0x0A-python-inheritance/1-my_list.py
409
4.09375
4
#!/usr/bin/python3 """ class MyList from list: def print_sorted(self): that prints the list, but sorted (ascending sort) """ class MyList(list): """ Args: list from main """ def print_sorted(self): """ Public instance method that prints the list, but sorted (ascending sort) ...
7f94d60cee39cc8d66f64fb1ab2457be7fa574be
SmischenkoB/campus_2018_python
/Dmytro_Shalimov/1/7.py
1,698
4.28125
4
<<<<<<< HEAD print("Bob is a lackadaisical teenager. In conversation, his responses are very limited.") print("Bob answers \"Sure.\" if you ask him a question.") print("He answers \"Whoa, chill out!\" if you yell at him.") print("He answers \"Calm down, I know what I'm doing!\" if you yell a question at him.") print("H...
8b06a072633043fa28466d4830059d5144253750
Malvtrics/ML
/LeeCode/LIS问题.py
1,600
3.6875
4
#LIS longest increasing sequence 最长上升子序列问题 #300 题目 https://leetcode-cn.com/problems/longest-increasing-subsequence/ #思路:用一个dp数组来保存历史最长子序列长度,这个是有了思路之后自己写出的代码,没有直接参考答案,复杂度O(N*N) #需要进一步优化为nlogn, 先按照思路解决面试17.08题 https://leetcode-cn.com/problems/circus-tower-lcci/ class Solution(object): def lengthOfLIS(self, nums): ...
2562f03842838fe680fdf60f5589166058747d1e
xxxwtc88/scir-training-day
/2-python-practice/5-numpy/listcount.py
308
3.609375
4
#!/usr/bin/env python import numpy as np import time tStart = time.time() x = np.random.randint(10, size=(10000000)) x = list(x) y = np.random.randint(10, size=(10000000)) x = list(y) for i in range(10): t=0 for j in range(10000000): t+=x[j]*y[j] tEnd = time.time() print "it cost %f sec" %(tEnd-tStart)
489245c445d42e2a8da39facd3fe2187bc1f2a68
adilsachwani/PythonCrashCourse_Solutions
/7_8.py
362
3.578125
4
sandwich_orders = ['club','bbq','egg','special'] finisjed_sandwiches = [] while sandwich_orders: current_sandwich = sandwich_orders.pop() print("We have made for " + current_sandwich.title() + " sandwich.") finisjed_sandwiches.append(current_sandwich) print() for sandwich in finisjed_sandwiches: prin...
bdbd4ce977f91119243314bc0153d0cad2cb317e
moon-light-night/learn_python
/complete - area.py
317
4.09375
4
print('Расчет площади прямоугольника по известным сторонам') a = float(input('Введите значение стороны a: ')) b = float(input('Введите значение стороны b: ')) s = a * b print('Площадь прямоугольника: ', s)
9bfa80c6ca8d734c57d5cad32cf889c15fc45414
pedropmedina/python-bootcamp
/testing/tests.py
1,394
3.765625
4
import unittest from activities import eat, is_funny, nap class ActivityTest(unittest.TestCase): def test_eat_healthy(self): """eat should have a positive message for healthy eating""" self.assertEqual( eat("broccoli", is_healthy=True), "I'm eating broccoli, because it is ...
fbe9e6621156390808b59caf6a4c4ea9da5ca7de
nakahatar111/Python_Games
/tictactoe.py
4,215
4.03125
4
class TicTacToe: board = [" "] * 10 player1 = "X" player2 = "O" db = False playersTurn = 0 P1win = 0 P2win = 0 def __int__(self, _db): self.db = _db self.start() self.resetGame() def instruction(self): print("When it's your turn type the number to re...
726d31dbe3b03c0b463252e7d594a3dd5558b9c7
mukeshv483/python_demo_programs
/Python-programs/Python-Training/python_programs3/pythonQno60/FilePackage/filefunc.py
1,607
3.96875
4
import os; def readfile(file1): file = open(file1, "r") print "reading file" str1=file.read() print str1 file.close() def writetofile(file1): file = open(file1, "w") print "writing to the file" for num in range(0,5): str2=raw_input("enter string to write to file") file.write(str2) ...
34027116c6f161102d06e3a28b1b1ba759ff609a
haiyuanhe/learn_python
/sword_offer/reverse_list.py
673
3.9375
4
# -*- coding:utf-8 -*- class ListNode: def __init__(self, x): self.val = x self.next = None # 翻转链表 # 链表 class Solution: # 返回ListNode def ReverseList(self, head): p = None while head: tmp = head.next head.next = p p = head h...
7007ff4c5d4cd9ae59ba9642bf27f5b38c6af4d1
artbb/gb_python
/hw3_2.py
1,048
4.25
4
""" 2. Реализовать функцию, принимающую несколько параметров, описывающих данные пользователя: имя, фамилия, год рождения, город проживания, email, телефон. Функция должна принимать параметры как именованные аргументы. Реализовать вывод данных о пользователе одной строкой. """ def user_data(name, surname, bir...
2d0a7d53f633390da81528ea288b1c001bec18ce
VinayakBagaria/Python-Programming
/New folder/Queen's Attack.py
1,892
3.640625
4
def check(y,x): for i in range(0,obstacle): if(x==ob_x[i] and y==ob_y[i]): return 1 return 0 sidelength,obstacle=input().split(' ') sidelength,obstacle=[int(sidelength),int(obstacle)] """ (y,x) 4,4 and size 8,8 left : 4,3 4,2 4,1 [decrease x till 1] right : increase x increas...
c6538401bc363fa3683b236fa06e9e10c5adc1cb
Rishiidc/z-score
/file.py
683
3.96875
4
file1 = open("intro","r") data = file1.readlines() #print(data) for line in data: print(line) temp = "things cup cars drinks" print(temp.split(',')) def printmyname(i): for a in range(i): print("I am Rishi") #printmyname(1) def USDintoINR(money): print("1 Dollar is equal to 72 ...
57015d9c969acdb8d3faf748b61c69c25da3ed16
Aden-Q/LeetCode
/code/684.Redundant-Connection.py
845
3.5
4
class UF: def __init__(self, n): self.parent = list(range(n)) def union(self, key1, key2): if not self.isConnected(key1, key2): root1 = self.find(key1) root2 = self.find(key2) self.parent[root1] = root2 def find(self, key): while self...
dd42a1ea14efc7e512257394b90066bda8510bb4
IAMJINU/ProjectEuler
/python/ex06_SumSquareDifference.py
1,148
3.75
4
#ex06_SumSquareDifference.py #total execution time : 0.0010006427764892578 #value : 25164150 import time def computeSumOfSquare(): sumOfSquare = 1 for i in range(2, 101): sumOfSquare = sumOfSquare + (i * i) return sumOfSquare def computeSquareOfSum(): squareOfSum = 0 for i in range(1,...
56d6438431c0455f6686dc3d10695847356e465a
stevensonmat2/code-class
/spelling.py
267
3.90625
4
word = input('write a word: ').lower() if 'c' in word and 'ei' in word: ei_pos = word.index('ei') c_pos = word.index('c') if c_pos < ei_pos: print('pass') elif 'ei' in word: print('fail') elif 'ie' in word: print('pass')
89a72e3c16565e53a460d6e331a0004a4427b523
masakiaota/kyoupuro
/practice/E_ABC/abc129_e/abc129_e.py
3,499
3.515625
4
# https://atcoder.jp/contests/abc129/tasks/abc129_e # 桁DPの理解が深まる一問 # 詳しくはeditorial参照 import sys read = sys.stdin.readline ra = range enu = enumerate class ModInt: def __init__(self, x, MOD=10 ** 9 + 7): ''' pypyじゃないと地獄みたいな遅さなので注意 ''' self.mod = MOD self.x = x % MOD de...
3cb83fc01ddbf2c347a0ed8a7214733c2229b77b
juny02/python-and-structure
/BST/BTS.py
3,283
3.8125
4
from treenode import TreeNode class BTS: def __init__(self): self.root = None def get_root(self): return self.root def preorder_traverse(self, cur, func): if not cur: return func(cur) self.preorder_traverse(cur.left, func) self.preorder_travers...
4ff5a49dd85379d00161f5887ac7744fef7c4141
aeasyo/python-learning
/py.project/神经网络处理房价数据.py
3,234
3.625
4
#import…as是一种导入库的方法 import numpy as np # 定义存储输入数据x和目标数据y的数组 x, y = [], [] for sample in open("E:\_Data\prices3.txt", "r"): x.append([float(sample.split(",")[0]),float(sample.split(",")[1])]) y.append(float(sample.split(",")[2])) x, y = np.array(x), np.array(y) # sigmoid激活函数定义 def sigmoid(x): retu...
cf21c44e854ee9be64892012e3d6d72c9884c8ad
asenath247/COM404
/windows-layouts/4-images/2-swapping.py
1,965
3.546875
4
from tkinter import * class Gui(Tk): def __init__(self): super().__init__() # load resources self.cactusleaves_image = PhotoImage(file="U:/Problem Solving/COM404/windows-layouts/4-images/cactusleaves.gif") self.palmtree_image = PhotoImage(file="U:/Problem Solving/COM404/windows-la...
5049410b8b6f2276b69ee3d5815a7bb73276eceb
Mayur710/calendar
/exercise 12.py
260
4.21875
4
"""Q)Write a Python program to print the calendar of a given month and year. Note : Use 'calendar' module""" import calendar year = int(input("Please enter your year: ")) month = int(input("Please enter your month: ")) print(calendar.month(year, month))
1aadd4f7f24f7dff07b175f22e15a8515d7dc4c1
mtgsjr/Machine_Learning
/prog02.py
705
3.59375
4
import cv2 # Importa o OpenCV captura = cv2.VideoCapture(0) # liga a webcam while(1): # Enquanto verdade ret,frame = captura.read() (b, g, r) = frame[200, 200] frame[198:202, 198:202] = (0, 0, 255) frame[10:90, 10:90]...
a2cc1f90ce3cf700960b370d2dd7bd666edc059f
hujianli94/Python-code
/14.Python高阶学习(包和模块)/导入和使用标准模块和三方模块/random随机数模块.py
737
3.71875
4
#!/usr/bin/env python #-*- coding:utf8 -*- import random #取 10 ~20 之间的3个随机数 for i in range(3): a = random.randrange(10,20) print(a,end=" ") if __name__ == '__main__': checkcode = '' #保存验证码的变量 for i in range(4): index = random.randrange(0,4) #生成一个0~3中的一个数 if index !=...
5b7b24ad75d9caca83888935266565992ddb4826
MitchellK/cp1404practicals
/prac_02/exceptions_demo.py
1,031
4.4375
4
""" CP1404/CP5632 - Practical Answer the following questions: 1. When will a ValueError occur? - When a numerator or denominator that is not a number is entered. Such as an 'A' or an '!' 2. When will a ZeroDivisionError occur? - when you enter the denominator as 0. 3. Could you change the code to avoid the poss...
5446081831c9e3b3ea2431af36b1fbafb79f86e4
BrianARuff/Python-Code
/99 bottles song.py
398
3.90625
4
for i in range(99,0,-1): if i == 1: print(i, "bottle of beer on the wall", i, "bottle of beer.") print("Take one down, pass it around.\n") print(i-1, "bottles of beer on the wall.") print("Now go home and don't drive while drunk.") else: print(i, "bottles of beer on the w...
873163f952e1f1b9d6677c8a499f5759b574f838
XyK0907/for_work
/LeetCode/HashTable/560_subarray_sum_equals_k.py
633
3.515625
4
class Solution(object): def subarraySum(self, nums, k): #mei zuo chu lai """ time O(n) space O(n) 前缀和 + 哈希表优化 :type nums: List[int] :type k: int :rtype: int """ dic = {0:1} sum, res = 0, 0 for each in nums: sum += ea...
25e33f22e3027ed4b95e60fba400dcee95c47029
Kunal352000/python_program
/delete.py
244
4.0625
4
from array import* arr1=[1,2,3,4],[5,6,7,8] print("before delting the elements.") print(arr1) del(arr1[0][1]) #del(arr1[1]) print("After delting the elements.") for i in arr1: for x in i: print(x,end=" ") print()
bc67338b2a5b8d8d2b44ac8a29c6575061bac9b8
therexone/sem4-uni
/OSTL/exp3-lists.py
7,879
4.59375
5
# menu driven program to illustrate use of list print("-----------List Demo Program----------") even_list = [] odd_list = [] merged_list = [] raw_list = [] choice = '' def parity(n): return True if n % 2 == 0 else False def add_integer_to_list(val): even_list.append(int(val)) if (val.isdigit() and parity(i...
07e143023cd029ecdfc4cb89d3cd0be4c26554f9
robintux/Python-ML
/scikit-learn/Examples/Feature_Selection.py
2,886
3.875
4
# Feature Selection for Machine Learning # http://machinelearningmastery.com/feature-selection-machine-learning-python/ # This section lists 4 feature selection recipes for machine learning in Python # 1. Univariate Selection # Feature Extraction with Univariate Statistical Tests (Chi-squared for classification) impo...
158fe369db68b828c1b7857966ac8011609a4cdb
acidjackcat/codeCampPython
/Training scripts/lesson8_classes.py
1,264
3.9375
4
class Animate: pass class Animals(Animate): def breathe(self): print('Breath') def move(self): print('Move') def eat_food(self): print('Eat') class Mammals(Animals): def feed_young_with_milk(self): print('Feed youngs with milk') class Giraffes(Mammals): de...
69ea4fb8bca69db935b8f1d6cc7eb83540d9a1fd
armohamm/studyingPython
/Exercise 2/Exercise2.py
169
4.125
4
number = input("Enter a number: ") rest = int(number) % 2 if rest > 0: print(str(number) + " is an odd number.") else: print(str(number) + " is an even number.")
9b49241b472f933c9ef226466ab1f7ffe6b401b9
waldisjr/JuniorIT
/_2019_2020/Homeworks/_9_ hw_on_09_11_2019/_1.py
233
3.578125
4
str1 = input('Enter string: ') new = '' t = 0 while t + 2 < len(str1): if str1[t].islower() and str1[t+1].isupper() and str1[t+2].islower(): new = new + ' ' + str1[t] + str1[t+1] + str1[t+2] t += 1 print(new)
ed08df05ccc35b794ff1f96df12b6edff8b72d4c
vitkhab/Project-Euler
/0045/solution.py
1,116
3.96875
4
#!/usr/bin/env python from time import time from math import sqrt def hexagonal(n): return n * (2 * n - 1) def is_natural_number(n): return n % 1.0 == 0 and n > 0 def solve_quadratic_equation(a, b, c): root1 = (-1.0 * b + sqrt(b**2 - 4.0 * a * c)) / (2.0 * a) root2 = (-1.0 * b - sqrt(b**2 - 4.0 * ...
3c9ed75dbe304b16f373aab43ad2540dcc482a7d
vinaynayak2000/Email_Slicer
/Email_slicer.py
222
3.8125
4
try: u=input("Enter Email : ").strip() email=u.split('@') username=email[0] domain=email[1] print("Your USERNAME is",username,"and your DOMAIN is",domain) except: print("Enter Valid Email")
c5d33fa71ba3f7f83cce310f9d22781370566875
HenriqueRenda/CIFOProject
/charles/mutation.py
996
3.765625
4
from random import randint, uniform, sample def random_mutation(individual, mutation_rate): """[summary] Args: individual ([type]): [description] Returns: [type]: [description] """ for i in range(len(individual)): if(uniform(0, 1)<mutation_rate): individual[i]...
b25ee6d11e83343ac29b7c13f1d9cdc0294a3001
mlazza/estudos
/Studies/livro_Python/48_cubos.py
163
3.8125
4
#4.8 Cubos. Crie lista dos 10 primeiros cubos e laco for para exibir lista = [] for cubo in range(1,11): lista.append(cubo**3) for cubo in lista: print(cubo)
9ff7ca162e94d7948e9d179786ccfc23352db5df
ahemd1252005/cs50ide
/buildingblocks/pset7/houses/import.py
2,028
4.4375
4
# In import.py, write a program that imports data from a CSV spreadsheet. import csv import sys import cs50 # Your program should accept the name of a CSV file as a command-line argument. # Check for correct number of args. if len(sys.argv) != 2: print("Usage: python import.py data.csv") sys.exit(1) # Check f...
fc3fce8b730dd7224bedd0784ae5c4719fdc810f
Nikikapralov/Advent-of-Code-2020
/Day_4_Task_1.py
745
3.765625
4
import re pattern = r'\b\w+|\W+' passport = '' all_passports = [] valid_passports = [] def is_passport_valid(passport): if 'byr' in passport and 'iyr' in passport and 'eyr' in passport and 'hgt' in passport and 'hcl' in passport and 'ecl' in passport and 'pid' in passport: return True else: re...
155bede2552d0f71e0c361261ea5dba964eb0c2e
ivanwakeup/algorithms
/algorithms/prep/ctci/1.3_is_str_permutat_of_palin.py
740
4.21875
4
''' need to check if a string is a permutation of a palindrome examples: "baa" = yes "aabb" = yes "aabab" = yes if strlen is even, all characters must appear even number of times if strlen is odd, all chars must appear even num of times except 1 approaches: 1. could sort the string, and keep track of the number of t...
5c70309cb6fa1eadfd3a56e8dd41ef35f54fb118
BryanYunche/Python-Exercicios-Basicos
/carrinho_de_compra.py
1,264
4.125
4
#Exercício Python 70: Crie um programa que leia o nome e o preço de vários produtos. O programa deverá perguntar se o usuário vai continuar ou não. 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. #inicio da variavel de soma dos...
3ef71d05d07110e0c914e33a4b7d2756cc6a1260
Kestajon/MLP_NeuralNetwork
/AnnComp.py
16,149
3.78125
4
import numpy as np import matplotlib.pyplot as plt import math import sys import csv import pickle # Used to serialise Neural_Networks for later use # ANN Neural Network Class, adapted from stephencwelch's code on GitHub # https://github.com/stephencwelch/Neural-Networks-Demystified # # This Neural_Network class has a...
e76a4b56ed283fc900bac90ccfafe440d4e88b83
NahshonSatat/KNN
/Point.py
2,183
3.890625
4
# 315823880- nahshon satat import math import doctest as doctest class Point(): def __init__(self, x, gender, y): self.x = float(x) self.gender = int(gender) self.y = float(y) self.dis = float(0.0) def pr(self): print("First number = " + str(self.x)) print("S...
62ad131c3d6874a06d354233d550f9c6d576ba4f
3Juhwan/Python-Algorithm-Team-Notes
/Math/prime_number.py
366
3.75
4
import math # 소수 판별 함수 def is_prime_number(x): # 2부터 x의 제곱근까지 for i in range(2, int(math.sqrt(x)) + 1): # x가 해당 수로 나눠떨어진다면 if x % i == 0: return False # 소수가 아님 return True # 소수임 print(is_prime_number(4)) # False print(is_prime_number(7)) # True
87314bfed6e6735749e76b964b99ec3fada66328
rapkeb/Data-Bases
/ass4/DB1/hw4.py
1,644
3.953125
4
import sqlite3 import csv # Use this to read the csv file def create_connection(db_file): """ create a database connection to the SQLite database specified by the db_file Parameters ---------- Connection """ pass def update_employee_salaries(conn, increase): """ Parameters ...
9058db0b007fc924e8f632dc401b22fcd67137ce
saierding/leetcode-and-basic-algorithm
/leetcode/math and bit manipulation/Power of Two.py
637
3.921875
4
# 231. Power of Two class Solution: # 笨办法直接循环到这个数,用2的n次方去判断。 def isPowerOfTwo1(self, n): i = 0 while i < n: if 2 ** i == n: return True elif 2 ** i > n: return False i += 1 return False # bit, 位方法,2的次方有特性,和比他小一个的数...
d6a30247c5476506b965028ce8acee8196b5415b
SoenMC/Programacion
/Ejercicio42.py
1,033
4.125
4
##Realizar un programa que lea los lados de n triángulos, e informar: #a) De cada uno de ellos, qué tipo de triángulo es: #equilátero (tres lados iguales), isósceles (dos lados iguales), o escaleno (ningún lado igual) #b) Cantidad de triángulos de cada tipo. cont1=0 cont2=0 cont3=0 n=int(input("Ingrese la ca...
f4809e55ef3075e4e0d0b5ecf9b590fc53572671
ScroogeZhang/Python
/day12 面向对象基础1/05-对象属性的增删改查.py
2,676
4.125
4
# -*- coding: utf-8 -*- # @Time : 2018/7/31 13:53 # @Author :Hcy # @Email : 297420160@qq.com # @File : 05-对象属性的增删改查.py # @Software : PyCharm class Dog: """狗类""" def __init__(self, age = 0, color = 'white'): self.age = age self.color = color class Student: def __init__(self, name='胡晨宇', se...
45f4387cdf2ff3eb3cf4552f18f85bcd4b9496ec
pakruslan/Decorators
/tasksdecorator.py
2,672
4.03125
4
import time from datetime import datetime import functools # 1. Напишите функцию say_whee, которая печатает «Whee!». Примените к этой функции # декоратор, который будет запускать функцию say_whee только в течение дня (9:00 — # 21:00), чтобы не беспокоить соседей. # def data(fn): # def wrapper(): # if 9 >=...
fecf921269a4135ef7e264719942c73491a3f41d
s3714217/IOT-OnlineLibrary
/reception/db_context.py
1,443
3.671875
4
import sqlite3 from sqlite3 import Error class DbContext: sql_create_users_table = 'CREATE TABLE IF NOT EXISTS Users (username TEXT PRIMARY KEY, password TEXT NOT NULL,' \ ' first_name TEXT NOT NULL, last_name TEXT NOT NULL, email TEXT NOT NULL);' def __init__(self, database_name...
7d4b8b3e32d32b0b499f0086d11ce7a08f9a485c
VictoriaSainter/CS50_pset6
/sentiments/analyzer.py
1,391
3.609375
4
import nltk class Analyzer(): """Implements sentiment analysis.""" def __init__(self, positives, negatives): self.positiveList = [] self.negativeList = [] with open(positives) as positivesFile: for _ in range(35): next(positivesFile) ...
3cf28520a4f34481edc5b72d65c79738221b47f5
hascong/ExerciseForPython
/helloworld.py
486
4.125
4
#!/usr/bin/python3 # # Example file for HelloWorld # def someFunction(): # Global F globalF = "def"; print(globalF) def main(): print("Hello World!") # Declare a variable and initialize it f = 0; print(f) # Re-declaring the variable works f = "abc" print(f) # Different types cannot be combi...
7ffd86393583a00a033ebacd0335180e17bf3d5d
AddisonG/codewars
/python/sum-of-pairs/sum-of-pairs.py
227
3.59375
4
def sum_pairs(array, target): passed = set() for i in range(0, len(array)): element = array[i] if (target - element) in passed: return [target - element, element] passed.add(element)
f2da79290394fe9050fa870c6e26b7f9cc46e629
devluke88/Python-CC
/cw.47.py
707
3.890625
4
# In the following 6 digit number: # 283910 # 91 is the greatest sequence of 2 consecutive digits. # In the following 10 digit number: # 1234567890 # 67890 is the greatest sequence of 5 consecutive digits. # Complete the solution so that it returns the greatest sequence of five consecutive digits foun...
7e50ca5014b0e4b7f940905aea3230f67914d87a
greenfox-velox/timikurucz
/week-03/day-1/33-for.py
77
3.5
4
af = [4, 5, 6, 7] # print all the elements of af for i in af: print (i)
d3b00f0349bc555bcac2a7369afe5682bc4360d4
MaciejChoromanski/design-patterns-python
/design_patterns_python/template_method.py
1,024
4.1875
4
# Example of 'Template-method' design pattern from abc import ABC, abstractmethod class AbstractClass(ABC): """Abstract Class""" @abstractmethod def do_something(self) -> None: pass @abstractmethod def do_something_else(self) -> None: pass def template_method(self) -> None:...
965cb54b06c699c0b41de6dfccfee905ad088d43
hitrzajc/mid_programming
/book/fibonaci.py
230
3.828125
4
def fibonaci(n, a=1, b=1): for i in range(n): a, b = b, a+b return a #print(fibonaci(6)) def fib(n, a=1, b=1): for i in range(n): c = a a = b b = c+b return a #print(fib(100000))
5f35d8c94a506101c3c23e71bd104711143122d5
t-tagami/100_knock
/Chapter_02/src/knock_16.py
483
3.59375
4
# 16. ファイルをN分割する # 自然数Nをコマンドライン引数などの手段で受け取り,入力のファイルを行単位でN分割せよ.同様の処理をsplitコマンドで実現せよ. num_split = int(input()) num_line = sum(1 for _ in open('../data/hightemp.txt')) with open('../data/hightemp.txt') as f: for num in [(num_line + i) // num_split for i in range(num_split)]: for _ in range(num): print(f.readl...
09422e393cb45b0be67fb0f19629ea07d942f424
uwspstar/DataStructures-Algorithms
/Data-Structure/Python/sort/sort-insertion-sort.py
1,764
4.21875
4
# range(start, stop[, step]) def insertion_sort(arr): n = len(arr) for i in range(1, n): current = arr[i] for j in range(i-1, -2, -1): # need to use -2, not -1 for end ?? if (current < arr[j]): arr[j+1] = arr[j] else: break arr[...
e72e1f81ef3444afc1ba1f487be01c4e37352efd
humford/ProjectEulerSolutions
/Other/Python2.7/Problem30.py
230
3.609375
4
def digits(n): return [int(i) for i in str(n)] def digitnthPowers(n): powers = [] for x in range(2, 355000): if sum([d**n for d in digits(x)]) == x: powers.append(x) return sum(powers), powers print(digitnthPowers(5))
4d7ee424b753285b6c90c4ba27eee00e64085d0d
crusenov/HackBulgaria-Programming101
/week0/sp1/22_calculate_coins/solution.py
387
3.703125
4
def calculate_coins(num): d = {} coins = [100, 50, 20, 10, 5, 2, 1] num *= 100 for i in coins: count = 0 while num % i >= 0 and num // i != 0: count += int(num // i) num %= i d[i] = count return d def main(): print(calculate_coins(0.53)) pr...
ffc149d053127edeb1c819fc429bab034a2a1b13
victorspgl/P2-AB2018
/Vector.py
5,064
4.15625
4
# Clase que representa un vector y contiene las funciones de ordenacion # Javier Corbalan y Victor Soria # 15 Mayo 2018 import random class Vector: """ Constructor """ def __init__(self, size): self.size = size self.elements = [] for i in range(0,size): self.elements.a...
96bdea4ac63d709c012d4cf694e8d9399f84d18e
vamsitallapudi/Coderefer-Python-Projects
/programming/dsame/linkedLists/problems/Problem5.py
608
3.8125
4
# find nth node of linked list from the last in single scan without using any other data type like hashmap etc. from dsame.linkedLists.problems.BaseLinkedList import BaseLinkedList def nth_node_from_end(head, n): p, temp = None, head for i in range(1, n): if temp: temp = temp.next whil...
05d40ca989c3349ade58bb07af4e849ea275f27b
845318843/20190323learnPython
/withKid/代码清单5-end.py
1,058
4.03125
4
# test items # anser = input("key a num,please!") # print(type(anser)) # key in 12, will be stored as string form # num = float(input()) # using float() can solve it # print(num) # try items # item1 # firstname = "ke" # lastname = "zj" # print(firstname+lastname) # item2 # firstname = input("hi,key your firstname") # ...
a9f80499ff95d51bf2472876fc1845237fd6df51
ceik/langunita
/algorithms/clustering/union_find.py
5,680
3.765625
4
#!/usr/bin/env python3 class UnionFind(): """ Implement a very basic Union Find datastructure.""" def __init__(self, components=[]): self.mapping = [c for c in components] self.cluster_count = len(self.mapping) def find(self, x): """ Find & return the group that x belongs to.""" ...
ee59ca6b78442b4ba31f6d647e7d09b2f80bb837
pushparajkum/python
/10lecture_9feb/toggle.py
384
3.984375
4
# wap to accept a number, bit position and number of bits to toggle from bit position. def toggle_bits(n, pos, bits): x = 1 << bits x = x << (pos - bits) return n ^ x def main(): n, pos, bits = eval(input("Enter number, bit position and number of bits to toggle :: ")) res = toggle_bits(n, pos, bits) p...
b6f776d864771c951c6c4faed5c9e0688637099f
gaurikossambe/bank
/09_Tuples_Sets.py
2,917
4.4375
4
# Tuples empty_tuple = () emp_IDs = 'P873874', "E948573", 46, "P248723" #emp_IDs = ('P873874', "E948573", 46, "P248723") # both are fine # print object types print(type(empty_tuple)) print(type(emp_IDs)) print(type(emp_IDs[1]) is int) print(emp_IDs) # use tuple constructor to create a tuple of letter...
e1bc8d977089d4e4513523a782f81b7682cd04c5
trebor97351/Python-calculator
/main.py
958
4.15625
4
print("This is John's awsome (basic) calculator here are a few ground rules:") print("1. Only use two numbers") print("2. No fractions") numb = input("What is your first number?") #ask for the users input print("1 = Add") print("2 = Subtract") print("3 = Divide") print("4 = Times") print("5 = Square") print("6 = Cube"...
e6cc93b02acde36df324eed58108ec1aaa797e65
RennanFelipe7/algoritmos20192
/Lista 2/lista02ex06.py
800
4.09375
4
print("Digite 3 numeros inteiros diferentes") Num1 = int(input("Digite seu primeiro numero: ")) Num2 = int(input("Digite seu segundo numero: ")) Num3 = int(input("Digite seu terceiro numero: ")) if Num3 > Num2 and Num2 > Num1: print(Num3,Num2,Num1) elif Num2 > Num3 and Num3 > Num1: print(Num2,Num3,Num1) elif Nu...
9f8c0e82289b3dded8e4818d8e69a7b2d3d9d6d2
EvgeniiMorozov/studying_Python
/main/lessons/lesson_16/lesson_16.py
5,562
4.09375
4
import turtle # Введение в ООП. class Car: count = 0 # аттрибут класса (общий для всех экземпляров класса) # Конструктор объекта, экземпляра (вызывается при создании объекта) def __init__(self, mark, wheels, speed): Car.count += 1 self.mark = mark # переменные, поля, аттрибуты s...