blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
545k
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
545k
e3581004a1dffa98a99e8c08cfe52c78395e5331
RoaRobinson97/python
/binarySearch/main.py
1,079
4.125
4
#RECURSIVE def binary_search_recursive(arr, low, high, x): if high >= low: mid = (high + low) if arr[mid] == x: return mid elif arr[mid] > x: return binary_search_recursive(arr, low, mid - 1, x) else: return binary_search_recursive(arr, mid + 1...
79d2a1c0760091b04219a2349db39d72995fc3b8
kamsusasiteja/LeetCode
/leet1stranagramornot.py
266
3.5
4
from itertools import permutations s=input() t=input() l=list(permutations(s)) perms=[] # string="" for i in l: string="" for j in i: string=string+j perms.append(string) if t in perms: print("True") else: print("False")
b16e2817ec03097dd4629fc3efd3b5206028edbd
yeshuping2003/machinelearning
/Chapert01监督学习/bike_sharing_prepro.py
1,003
3.5625
4
# 我的数据预处理程序 # 做成适合随机森林回归算法所需的数据集: # 具有列名,前部列是特征列,最后1列是目标值,用逗号分隔的.csv文件。 # 供bike_sharing.py使用。 # 读取导入的数据集,合并data和 target , # 加上数据集,命名为 housing里的特征名 housing.feaure_names, # 保存为 .csv文件。 # 验证的数据:housing.csv(california_housing), bike_day.csv, boston_housing_prices.csv # 读取数据集 from sklearn.datasets.california_housi...
b5b3584faeb11e8078f51aa3950779a775a291b6
Kjain2021/LCA
/Lowest_Common_Ancestor/LCA.py
2,606
3.5
4
class Node: def __init__(self, info): self.info = info self.right = None self.left = None self.level = None def __str__(self): return str(self.info) class BST: def __init__(self): self.root = None def build(self, val): if self.root == None: ...
30c2f43d22e30ade58e703b3ac64176db33a3cbf
juancarlosqr/datascience
/python/udemy_machine_learning/02_simple_linear_regression/01_simple_linear_regression.py
2,083
4.21875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Jul 19 13:49:10 2018 @author: jc """ import pandas as pd import numpy as np import matplotlib.pyplot as plt # data preprocessing # import dataset dataset = pd.read_csv('salary_data.csv') x = dataset.iloc[:, :-1].values dependant_column_index = 1 y = ...
7fff1cd2a7541c8d8e93bf3851ff7a5b11ddc544
juancarlosqr/datascience
/python/playground/oop/Coche.py
1,437
3.875
4
#!/usr/bin/python # Begin Definicion de Clases class Coche: mygasolina = 0 def __init__(self,tipo = "Coche"): print "Se ha creado un nuevo " + tipo print " - Valor inicial de Gasolina: " + str( self.mygasolina ) + " litro(s)" def setGasolina(self, gasolina): self.mygasolina += gasolina self.printGasolina...
6c7e286da33f567d191ba38b7d0fa3730c72e371
pkuhad/python-stunts
/syntax-practices/iterators-generators.py
1,469
3.90625
4
''' Patterns for syntax best practices ''' ''' Built in 'itr' function -- >>> i = iter('abc') >>> i.next() 'a' >>> i = iter([1,2,3]) >>> i.next <method-wrapper 'next' of listiterator object at 0x7f8cb6952c90> >>> i.next() 1 >>> ''' def infinite_numbers(): count = 0 while True: count += 1 yield...
db5c4b84ba7b844ce623d5c61e8d995e33190e00
UTKARSHBHA/HackerRank
/prob3.py
532
3.71875
4
n = int(input("no. of students")) subjects = ["maths", "physics", "chemistry"] marks = [] name = [] dicf = {} for i in range(n): d = input("name").split() name.append(d[0]) for y in range(1, 4): marks.append(float(d[y])) dic = dict(zip(subjects, marks)) print(dic) dicf[name[i]] = dic...
30cdc53ed76aee456d078fe503799ad45e77645c
gaoyaoxin/makeYourOwnNeuralNetwork
/2.4.2.initialization.py
774
3.953125
4
# neural network class definition class neuralNetwork: # initialise the neural network def __init__(self, inputnodes, hiddennodes, outputnodes, learningrate): #set number of nodes in each input, hidden, output layer self.inodes = inputnodes self.hnodes = hiddennodes self.onodes =...
c93cd1c08428e91fed5db78f0a21b252132c62f7
naveen0508/python
/gcd_backwards.py
306
3.546875
4
# -*- coding: utf-8 -*- """ Created on Sun May 14 23:25:56 2017 @author: Naveen GCD program without lists and scanning backwards """ def gcd(m,n): i = min(m,n) while i > 0: if (m%i) == 0 and (n%i) == 0: return(i) else: i -= 1 print(gcd(14,63))
c46de2fe37fbb876263058e2d3b1d19d99b2204d
naveen0508/python
/reversing_string_iterative.py
240
4.03125
4
def reverse(input): return ''.join([input[i] for i in range(len(input)-1, -1,-1)]) s = 'reverse' print(reverse(s)) # Approach 2 def reverse2(inp): l = list(inp) l = reversed(l) return ''.join(l) s = 'reverse' print(reverse2(s))
9feb3ebd98f1deecd86a925c5d387aca12777391
Kum4yk/python-programming-spec
/02.OOP-and-design-patterns-in-Python/week 2/review/screen_w2.py
11,621
3.890625
4
import pygame import random import math class Vec2D: """ класс 2-мерных векторов """ def __init__(self, x, y=0): if ((type(x) == tuple or type(x) == list) and (type(x[0]) == int or type(x[0]) == float) and (type(x[1]) == int or type(x[1]) == float)): ...
d24c91d3fcba9dc6bda8bc77d26e7ef99d9f82c5
bankirus01/python
/Module_3/Mod_3_Home_work_3/fibo_recur.py
298
3.953125
4
num = int(input("Введите число: ")) a = [] def fibo(n): if n == 1 or n == 2: return 1 return fibo(n - 1) + fibo(n - 2) while num > 0: a.append(fibo(num)) num -= 1 print("Сгенерированная последовательность: " + str(a[::-1]))
5015cd9eba20661351fc2889f93c88843e7041c9
bankirus01/python
/sort_descending.py
834
3.75
4
#сортировка по убыванию #создаем список, обычный массив: arr = [1, 58, 12, 96, 45, 72, 22, 59, 27 ,63, 100, 159, 7] #вычисляем длину списка массива n = len(arr) #внешний цикл отсчитывает количество "проходов" по массиву for j in range(0,n-1): #вложенный цикл сравнивает i-ый c i+1 -ым элементом и при необходимости м...
22ebee6a673d7af7cc1a34744d4efeaa07e5c92b
lukasz-lesiuk/algo-workshop
/algo-workshop.py
729
4.40625
4
def get_even_numbers(x, stop, z): """ Returns a list containing first 'x' even elements lower than 'stop'. Those elements must be divisible by 'z'. """ raw_list = [] for i in range(1,(stop//2)): raw_list.append(2*i) # print(raw_list) list_sorted = [] for element in raw_list...
80db067d637b2b7a1b07159e5d0fdaf0208f8295
cnu-pai/2020SUMMER-AlgorithmStudy
/이택/2587.py
179
3.71875
4
NumberList = [int(input("")) for _ in range(5)] average = (sum(NumberList)/len(NumberList)) print(int(average)) NumberList.sort() mid = (len(NumberList)//2) print(NumberList[mid])
208a0b62f0c0cd6471be28eae44cd309c39e1230
cnu-pai/2020SUMMER-AlgorithmStudy
/최수연/재귀/p1629.py
303
3.5
4
A, B, C = map(int, input().split()) def multiply(a, b, c): if b == 0: return 1 % c if b == 1: return a % c if b % 2 == 0: return pow(multiply(a, b//2, c), 2) % c else: return (multiply(a, b//2, c) * multiply(a, b//2 + 1, c)) % c print(multiply(A, B, C))
71c4b61ee65ceb5042908accca49af509fc43210
cyr1z/python_education
/python_lessons/02_python_homework_exercises/ex_03_lists.py
1,208
4.34375
4
""" Exercise: https://www.learnpython.org/en/Lists In this exercise, you will need to add numbers and strings to the correct lists using the "append" list method. You must add the numbers 1,2, and 3 to the "numbers" list, and the words 'hello' and 'world' to the strings variable. You will also ha...
01263219b0e7f14b8bf5b93f910d8d9ec0d64670
cyr1z/python_education
/python_lessons/data_structures/hash_table.py
3,451
4.0625
4
""" hash table """ from linked_list import LinkedList def hash_func(value): """Method for calculating the hash code""" return sum(ord(item) for item in str(value)) % 30 class HashTable(LinkedList): """This is the hash table class""" class Node: """hash list node""" def __init__(se...
4daf2b43622010879345f69ab42161d91a071072
cyr1z/python_education
/python_lessons/02_python_homework_exercises/ex_07_conditions.py
592
3.8125
4
""" Exercise: https://www.learnpython.org/en/Conditions Change the variables in the first section, so that each if statement resolves as True. """ # change this code NUMBER = 16 SECOND_NUMBER = 0 FIRST_ARRAY = [1, 2, 5] SECOND_ARRAY = [1, 2] if __name__ == "__main__": if NUMBER > 15: print("1")...
d30825744eaf8cbdb839513844c14698275fa15d
MSoup/Edabit-Exercises
/[VeryH]Persistence/persistence.py
787
3.828125
4
def additive_persistence(n): def getNewTotal(num): return sum([int(i) for i in str(num)]) #First iteration 1 count = 0 #Keep going until len(n) == 1 #Preserve original n for good practice newN = n while len(str(newN)) != 1: newN = getNewTotal(newN) #Increase count every loop count += 1 ...
ef4619a779123fc322adc2baf411554da57182bf
oceanmycaptain/python-
/实验代码.py
281
3.625
4
def twoSum(nums,target): if len(nums) <=1: return False for i in range(len(nums)): for j in range(i+1,len(nums)): if nums[i]+ nums[j]==target: return (i,j) nums = [2,7,11,15] target = 18 a = twoSum(nums,target) print(a)
957d98fec95811e6f23b48e0787dd09f43681d45
oceanmycaptain/python-
/实验代码2.py
323
3.5
4
def twoSum(nums,target): if len(nums)<=1: return False buff_dict = {} for i in range(len(nums)): if nums[i] in buff_dict: return [buff_dict[nums[i]],i] else: buff_dict[target-nums[i]] = i nums = [2,7,11,15] target = 18 a = twoSum(nums,target) print...
453843b50792ff7f17968025de45a4849ccee725
CKKH/airport-challenge-py
/src/airport.py
1,575
3.609375
4
''' Airport module ''' from src.weather import Weather class Airport: ''' Creates Airport ''' hanger_capacity = 2 def __init__(self, weather=Weather()): self.hanger = [] self.weather = weather def land(self, plane): ''' Lands planes in hanger if conditions met ''' s...
558b7a708a563d3b1c50a620dbbe1d28945800c8
chenzhaoplus/testpy
/test_numpy/std_np.py
271
3.640625
4
# 计算标准差,意味着大多数值在平均值的 0.9 范围内,即 86.4 的正负 0.9 范围内 import numpy speed = [86, 87, 88, 86, 87, 85, 86] mean_value = numpy.mean(speed) print("平均值:", mean_value) x = numpy.std(speed) print("标准差:", x)
b1c07fc50fc857513d26c4a6a3d1da16cdcb5766
swenqi/ds_salry_proj
/data_cleaning.py
3,359
3.640625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Jun 13 23:38:58 2020 @author: Nikki """ import pandas as pd df = pd.read_csv('glassdoor_jobs.csv') # ============================================================================= #Data Cleansing: # Salary parsing - only keep numeric part # Deleted ...
b438568874a86460ed5d0f89dc7c2753fc98d1fc
GaneshaKS99/Mini-DBaaS-for-RideShare
/assignment_1/CC_1628_1731_1746.py
18,831
3.640625
4
from flask import Flask, render_template,\ jsonify,request,abort, Response import json import requests from datetime import datetime app=Flask(__name__) import sqlite3 """This function is used to read database and send the response. First we create final columns from the columns list. There might be more than one co...
8b9d35551a9f5b123a30c3e63ddf7f637eec279a
collins73/python-practice-code
/app.py
823
4.21875
4
# A simple program that uses loops, list objects, function , and conditional statements # Pass in key word arguments into the function definition my_name def my_name(first_name='Albert', last_name='Einstein', age=46): return 'Hello World, my name is: {} {}, and I am {} years old'.format(first_name,last_name, a...
78152bb26ab4c0ef44bfafc86f84e1dd88856ec8
Dsljlbaby/Scrapy_study
/douban_spider/DouBanSpider_top250.py
1,713
3.546875
4
#!/usr/bin/env python # -*- coding:utf-8 -*- import re import urllib2 from bs4 import BeautifulSoup class DouBanSpider_top(): def __init__(self): print ''' --------------------------------------- author: Dsljlbaby time: 2016-01-09 target: DouBan_top250 a...
9dfc5aac2701db5524ae5e6a9ebb22c9e2f430a3
radzieckianton/tictactoe
/tictactoe.py
5,969
4.28125
4
import random import sys """This is the simple well-known game. Tic tac toe. First you will be asked to pick a number from 1 to 20, and if your number will be greater than computer's number you will start the game. 'X' always starts. You are choosing the field on the board by entering number from 1 to 9.""" def pr...
84c2cd87987fd4df0e1dafbbc51fbd1b1a8743fd
PrasannaSM/Data-Structures
/test.py
596
3.609375
4
from linked_list.linked_list import LL if __name__ == "__main__": obj = LL() obj.insert_first(1) obj.insert_first(2) obj.insert_first(3) print('-'*60) print('LENGTH: {}'.format(obj.get_length())) print('-'*60) print('LIST CONTENTS') print('-'*60) obj.traversal() print('-'...
bdca6027182fcef9ae7b02da45110e8dd53009e7
OskarMulcan/Repozytorium
/losowanieNicku.py
301
3.578125
4
kotely = '(ФДФ)' print(kotely) owcaUzytkownik = input('Podaj ile kotelow chcesz wygenerowac :) ') try: owcaUzytkownik = int(owcaUzytkownik) except ValueError as owcaError: owcaUzytkownik = 1 print('Program potrzebuje liczby, a nie ciągu znaków!') print ('(ФДФ)' * owcaUzytkownik)
f263d88bd8b44659f3d31e0b3d6437e87b0bd1fc
tlvince/scripts-python
/sanitise.py
1,971
3.578125
4
#!/usr/bin/env python3 # Copyright 2011 Tom Vincent <http://www.tlvince.com/contact/> """Sanitise the given string(s) into (a subset of) ASCII.""" import argparse import string import unicodedata import re import random def removeAccents(str): """Remove any form of UTF-8 accents. See: http://stackoverflow.c...
a1305f000e94efcabf139c9ca27b0d71381e5947
tlvince/scripts-python
/word-frequency.py
1,113
3.875
4
#!/usr/bin/env python3 # Copyright 2011 Tom Vincent <http://www.tlvince.com/contact/> """Count the frequency of unique words in a file. See: https://code.activestate.com/recipes/576699/#c4 """ import re import sys import argparse from collections import Counter def words(f): """Return each word in a line.""" ...
d4be869edfb8bcb9c2a68863f5f70ac195ce870f
prashantkadam-py/deepdive_part3
/coding_exercises/custom_classes_hashing_18.py
655
3.984375
4
class Person: def __init__(self, name): self.name = name def __eq__(self, other): if isinstance(other, Person): return self.name == other.name else: return False def __hash__(self): return hash(self.name) if __name__ == "__main__...
56dd164a8c0f81ea124b852bb353741b5e3792df
Shea-Wolfe/Road-Rage
/road_rage_classes.py
4,117
3.546875
4
import numpy as np import random import statistics as st import matplotlib.pyplot as plt import math class Car(): def __init__(self, location, current_speed=25, limit=33): self.max_s = limit #In meters per second truncating 33.333 to 33 self.length = 5 #In meters self.cs = current_speed #...
93cc40f5254d05be0c3c14e11bc4abb2af0e9cc0
iqra-javed/Knapsack
/knapsack.py
4,072
4.0625
4
#!/usr/bin/python import sys from collections import namedtuple Item = namedtuple('Item', ['index', 'size', 'value']) # GREEDY IMPLEMENTATION # def knapsack_solver(items, capacity): # valuable_chosen_items = [] # total_cost_of_chosen_items = 0 # running_total_cost = 0 # # variables for print statements # ...
65b201111e73cadf767681292edd197223221917
przemaj1990/AP_Migration
/Python_for_NetEng/25_scheduling_network_task.py
717
3.5625
4
import schedule import time import datetime def job(): TNOW = datetime.datetime.now().replace(microsecond=0) print( str(TNOW) +" Print 5 sec interval for 3 times") def minjob(): TNOW = datetime.datetime.now().replace(microsecond=0) print('\n' + str(TNOW) +" This prints every min \n") schedule.every(...
11cc0567301f59718b8ca6760aa50a23bc52582b
Aish32/data-chronicles
/Preprocessing Structured Data/handling-imbalanced-classes-with-downsampling.py
1,055
3.75
4
# the strategy is to randomly sample without replacememtn from the minority class to create a new subset of observation equal in size ato the minority class # load libraries import numpy as np from sklearn import datasets # load iris data iris = datasets.load_iris() # extract x and y x = iris.data y = iris.target ...
4a7e69a05989bcfea1ca3144105d996e771d803b
Aish32/data-chronicles
/Preprocessing Structured Data/handling-outliers.py
757
3.984375
4
# load library import pandas as pd import numpy as np # create dataframe houses = pd.DataFrame() houses['Price'] = [534433, 392333, 293222, 4322032] houses['Bathrooms'] = [2, 3.5, 2, 116] houses['Square_Feet'] = [1500, 2500, 1500, 48000] """ To handle outliers we can : 1. Drop : not a great option we lose a lot of ...
28a38bdecc637e0dbb391259074b716c702eeb07
Aish32/data-chronicles
/Preprocessing Dates and Times/encoding-days-of-the-week.py
164
3.5
4
# load libray import pandas as pd # Create dates dates = pd.Series(pd.date_range('2/2/2002', periods=3, freq='M')) # show days of the week dates.dt.weekday_name
505556fc408b1d10d8f6c475db70c434537b86f7
Aish32/data-chronicles
/Preprocessing Text/stemming-words.py
487
3.765625
4
""" Stemming reduces a word to its stem. The result is less readble by humans but makes the text more comparable across observations. It identifies and remove affixes while keeping the root meaning of the word. """ # load library from nltk.stem.porter import PorterStemmer # create word tokens tokenized_words = ['i'...
e3c17a09380aed8762c4e6f9972e60116a908198
Aish32/data-chronicles
/Basics/making-simulated-regression-data.py
1,111
3.53125
4
# load libraries import pandas as pd from sklearn.datasets import make_regression # generate features, outputs and true coefficients of 100 samples features, output, coef = make_regression(n_samples=100, # three features n_features=3, ...
896dd732e80ea78e5f3300f29ffb1086012cb67d
Aish32/data-chronicles
/Preprocessing Dates and Times/breaking-dates-and-times.py
383
3.5
4
# load library import pandas as pd # create data grames df = pd.DataFrame() # create five dates df['date'] = pd.date_range('1/1/2001', periods=150, freq='W') # Create features for year, month, day, hour, and minute df['year'] = df['date'].dt.year df['month'] = df['date'].dt.month df['day'] = df['date'].dt.day df['h...
3e27bc4517116fd8b265cb482f156e960597822b
Aish32/data-chronicles
/Preprocessing Structured Data/detecting-outliers.py
994
3.515625
4
# load libraries import numpy as np from sklearn.covariance import EllipticEnvelope from sklearn.datasets import make_blobs # Create simulated data X, _ = make_blobs(n_samples = 10, n_features = 2, centers = 1, random_state = 1) # Replace the first observation's ...
58c609aad8ef68f5b2568df50b61de01e7480e83
Aish32/data-chronicles
/Basics/loading-features-from-dictionaries.py
507
3.546875
4
from sklearn.feature_extraction import DictVectorizer # create a dictionary soccer = [ {'name': 'Vigil Van Dyke', 'position':'defender','age': 33.}, {'name': 'Mane', 'position':'attack','age': 12.}, {'name': 'Tret Anold', 'position':'winger','age': 18.}] # convert dictionary to feature ma...
aa7440a3240c4591dad976b4e600a0d16f033d0f
Aish32/data-chronicles
/Core Concepts/XGboosting/decision_tree_again.py
920
3.65625
4
import pandas as pd from sklearn.model_selection import train_test_split from sklearn.tree import DecisionTreeClassifier import xgboost as xgb import matplotlib.pyplot as plt import numpy as np df = pd.read_csv('datasets/ames_housing_trimmed_processed.csv') X = df.loc[:, df.columns != 'SalePrice'].values y = df['Sale...
28362ec25ef038988aaf93016c6e248eb4029e98
Aish32/data-chronicles
/Recreating John Snow's Ghost Map/script.py
3,519
3.90625
4
# coding: utf-8 # Loading in the pandas module import pandas as pd # Reading in the data deaths = pd.read_csv('datasets/deaths.csv') # Print out the shape of the dataset print(deaths.shape) # Printing out the first 5 rows print(deaths.head(5)) # Cholera attacks! # Summarizing the content of deaths deaths.info() # ...
e97cfd7ae04abd2fae6bdf0f5e1ae4985c39dd65
nikokydes/NikoEDA
/NikoEDA/EDA.py
571
3.640625
4
import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns class eda: def __init__(self): """ Generic class for performing EDA on a Pandas dataframe in preparation for applying machine learning algorithms. Attributes: df (Pandas dataframe) """ self.df = p...
f19b9dea2cdbf9d1ae985214ba886a130f688479
benpmeredith/NSSD-app
/app/models.py
665
3.609375
4
"""Define models for storing user data.""" from app import db import datetime class Search(db.Model): """Search persistence model.""" id = db.Column(db.Integer, primary_key=True) user_id = db.Column(db.String()) search_string = db.Column(db.String()) datetime = db.Column( db.DateTime, def...
0bdce2aeb3ad49c2a86ae442e354bdb9cedae33b
Ararad1962/Python_education
/Func.py
230
3.828125
4
def hello(): print (" Привет, мир! ") x = int (input ("Введите первое число")) y = int (input ("Введите второе число")) def sum(a,b): return a+b z= sum(x,y) hello() print (z)
e57442562d99b1c65cecbeef8a9915670fb9a34c
KikiPadoru/PraktikaSaltAndPepper
/9.py
737
3.515625
4
def more_return(my_dict,new_dict): for k, v in my_dict.items(): if(v>9): new_dict[k]=v return new_dict def connect_dicts(dict1,dict2): a = sum(dict1.values()) b = sum(dict2.values()) new_dict = more_return(dict1, more_return(dict2,new_dict=dict()))if a>b else more_retur...
68947e2d0e2ecce6baa0de5f2424eca92614217d
KikiPadoru/PraktikaSaltAndPepper
/11-12.py
1,355
3.5625
4
class Dessert: def __init__(self,name='',calories=0): self.__name = name self.__calories = calories @property def name(self): return self.__name @name.setter def name(self,name): self.__name = name @property def calories(self): return self....
df33f5bd5a545f78509b9562730a147e683db3cb
Zakaria9494/python
/learn/oop/Library.py
2,238
3.875
4
class Library: authors = [] books = [] def add_author(self, author): self.authors.append(author) def remove_author(self, id): for author in self.authors: if author.id == id: self.authors.remove(author) return print("author with id", ...
9ef773c250dab6e409f956fb10844b1e3a22015f
Zakaria9494/python
/learn/tuple.py
804
4.25
4
#A tuple is a collection which is ordered and unchangeable. # In Python tuples are written with round brackets. thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango") print(thistuple[1]) # negative Indexing #Print the last item of the tuple: print(thistuple[-1]) #ran...
3ed4f75101ba106f3f783cf68255ca35c585ad45
Zakaria9494/python
/learn/if-anweisung.py
687
3.765625
4
'''x = int(input("please enter an integer")) if x < 0: x = 0 print("negative changed to zero") elif x == 0: print("zero") elif x == 1: print("Single") else: print("more")''' #measure some strings words = ['cat', 'window', 'defenestrate'] for w in words: print(w, len(w)) def ask_ok(retries=4, ...
978ed5bafbf3c3d796963d6152818fa68c230c52
Zakaria9494/python
/learn/inputuser.py
1,838
4.28125
4
# pyhon 3.6 input() # python 2.7 raw_input() # to get the functions of python in console # first step python eingeben #second step dir() #third step dir("") name =input("Was ist deine Name ? :") if len(name)< 2: print ("zu kurz") elif name.isalpha(): age = input("bitte geben Sie Alter ein: ") if age.isal...
f35511d367a14e7912983d941ced675bfec958a7
FranciscaLjubetic/python_fundamentals
/funciones_basicas-2.py
980
3.53125
4
def regresiva(a):#cuenta regresiva: hace una lista que va de atras pa delante a partir del numero x=[] for i in range(0, a+1): x.append(a-i) return x regresiva(9) def printandreturn(lst): print (lst[0]) return lst[1] printandreturn([1,2,3,4]) def firstpluslength(lst): #devuelv...
1c22adb5dba8c8f15905388ee99c5659d60dbb0c
raberin/leetcode-questions
/py/1-two_sum.py
914
3.8125
4
# // Given an array of integers, return indices of the two numbers such that they add up to a specific target. # // You may assume that each input would have exactly one solution, and you may not use the same element twice. # // Example: # // Given nums = [2, 7, 11, 15], target = 9, # // return [0, 1]. # BRUTE FORCE # ...
e29a66a3557e2eabca2ebe273f0454222479c015
ericocsrodrigues/Python_Exercicios
/Mundo 03/ex074.py
552
4.125
4
""" Exercício Python 074: Crie um programa que vai gerar cinco números aleatórios e colocar em uma tupla. Depois disso, mostre a listagem de números gerados e também indique o menor e o maior valor que estão na tupla. """ from random import randint n = (randint(1, 10), randint(1, 10), randint(1, 10), randint(1, 10), ra...
afe415188eeef22b2c1a9a762602725ab91c3207
ericocsrodrigues/Python_Exercicios
/Mundo 01/ex031.py
762
3.984375
4
""" Exercício Python 31: Desenvolva um programa que pergunte a distância de uma viagem em Km. Calcule o preço da passagem, cobrando R$0,50 por Km para viagens de até 200Km e R$0,45 parta viagens mais longas. """ print("""\033[0;34mExercício Python 31: Desenvolva um programa que pergunte a distância de uma viagem em K...
fab5b905167cae15f72c4fb613e84f59f745e0d0
ericocsrodrigues/Python_Exercicios
/Mundo 03/ex092.py
1,023
3.875
4
""" Exercício Python 092: Crie um programa que leia nome, ano de nascimento e carteira de trabalho e cadastre-o (com idade) em um dicionário. Se por acaso a CTPS for diferente de ZERO, o dicionário receberá também o ano de contratação e o salário. Calcule e acrescente, além da idade, com quantos anos a pessoa vai se ap...
882c5146a6d9fe84f9ced73249ac3e6a305b9de5
ericocsrodrigues/Python_Exercicios
/Mundo 03/ex087.py
956
4.09375
4
""" Exercício Python 087: Aprimore o desafio anterior, mostrando no final: A) A soma de todos os valores pares digitados. B) A soma dos valores da terceira coluna. C) O maior valor da segunda linha. """ pares = contpar = somacoluna = maior = 0 matriz = [[0, 0, 0], [0, 0, 0], [0, 0, 0]] for l in range(0, 3): for c i...
ee165e82f4f4497cef8e66d116a14313f609eb43
ericocsrodrigues/Python_Exercicios
/Mundo 02/ex052.py
433
4.0625
4
""" Exercício Python 52: Faça um programa que leia um número inteiro e diga se ele é ou não um número primo. """ num = int(input('Digite um número: ')) cont = 0 for x in range(1, num + 1): if num % x == 0: print('\033[34m', end=' ') cont += 1 else: print('\033[31m', end=' ') print(f...
39461100d0a24ca1afecb91bbe628f319c6c56c0
ericocsrodrigues/Python_Exercicios
/Mundo 03/ex081.py
869
4.1875
4
""" Exercício Python 081: Crie um programa que vai ler vários números e colocar em uma lista. Depois disso, mostre: A) Quantos números foram digitados. B) A lista de valores, ordenada de forma decrescente. C) Se o valor 5 foi digitado e está ou não na lista. """ lista = list() cont = 0 while True: lista.append(int...
2572f07a5e1b2320bd3f19825b35eea43d963348
ericocsrodrigues/Python_Exercicios
/Mundo 02/ex062.py
764
4.21875
4
""" Exercício Python 62: Melhore o DESAFIO 61, perguntando para o usuário se ele quer mostrar mais alguns termos. O programa encerrará quando ele disser que quer mostrar 0 termos. """ barra = '\033[36m=\033[m' * 22 print(barra) print('\033[35m10 TERMOS DE UMA P.A\033[m') print(barra) n = int(input('Primeiro termo: '))...
f9b83bbc0e3b5b579f2ac7a831da9b2b890bd283
ericocsrodrigues/Python_Exercicios
/Mundo 01/ex008.py
344
4.09375
4
""" Exercício Python 8: Escreva um programa que leia um valor em metros e o exiba convertido em centímetros e milímetros. """ medida = float(input('Informe um distância em metros: ')) cm = medida * 100 mm = medida * 1000 print(f'A medida de \033[1;34m{medida}\033[mm corresponde a \033[7;30m{cm:.0f}\033[mcm e \033[7;30...
87c22b1d1b3f88e3737e20ac246dcf0cc300c793
ericocsrodrigues/Python_Exercicios
/Mundo 03/ex078.py
643
4.125
4
''' Exercício Python 078: Faça um programa que leia 5 valores numéricos e guarde-os em uma lista. No final, mostre qual foi o maior e o menor valor digitado e as suas respectivas posições na lista. ''' lista = list() for x in range(5): lista.append(int(input(f'Digite um valor para a posição {x}: '))) print(f'O mai...
6067632653c7bf25ed2be308ee26ab093663f42e
ericocsrodrigues/Python_Exercicios
/Mundo 01/ex029.py
459
4.0625
4
""" Exercício Python 29: Escreva um programa que leia a velocidade de um carro. Se ele ultrapassar 80Km/h, mostre uma mensagem dizendo que ele foi multado. A multa vai custar R$7,00 por cada Km acima do limite. """ vel = int(input('Informe a velocidade do carro: ')) if vel > 80: d = vel - 80 multa = 7 * d ...
318313d2936e6d3c1173a6197f6bb0b1c6775a6d
ericocsrodrigues/Python_Exercicios
/Mundo 02/ex043.py
771
4.03125
4
""" Exercício Python 43: Desenvolva uma lógica que leia o peso e a altura de uma pessoa, calcule seu Índice de Massa Corporal (IMC) e mostre seu status, de acordo com a tabela abaixo: – IMC abaixo de 18,5: Abaixo do Peso – Entre 18,5 e 25: Peso Ideal – 25 até 30: Sobrepeso – 30 até 40: Obesidade – Acima de 40: Obesidad...
04a58934e0022a7bd4d4dff6f11e21e8ad1eaea7
shimla1501/hacktoberfest-1
/Solutions/palindrome.py
171
3.859375
4
n=int(input("Enter any number")) a=n rev=0 while n>0: rev=rev*10+n%10 n=n//10 if rev==a: print("Palindrome") else: print("Not palindrome")
509bc9d0d6546ce4d4594c0b16b35cc039a39bb4
Luiza-Teixeira/Desafio-curso-em-video
/desafio 0010.py
134
3.796875
4
dinheiro = float(input('Quanto você tem na carteira?')) dolar = dinheiro/3.27 print('Você tem em dólar:{:.1f}'.format(dolar))
968706855a6afb5c776a12d972bc2f7e9fac827c
Luiza-Teixeira/Desafio-curso-em-video
/desafio 009.py
532
3.96875
4
num = int(input('Digite um valor para vê sua tabuada: ')) print('{} x {} = {}'.format(num, 1, num * 1)) print('{} x {} = {}'.format(num, 2, num * 2)) print('{} x {} = {}'.format(num, 3, num * 3)) print('{} x {} = {}'.format(num, 4, num * 4)) print('{} x {} = {}'.format(num, 5, num * 5)) print('{} x {} = {}'.forma...
558d0a6e9d6195ca55545dd57032461c102ad87d
Luiza-Teixeira/Desafio-curso-em-video
/desafio 018.py
817
3.96875
4
import math angulo = float(input('Digite o angulo que você deseja: ')) seno = math.sin(math.radians(angulo)) cosseno = math.cos(math.radians(angulo)) tangente = math.tan(math.radians(angulo)) print('O ângulo de {} tem o seno {:.2f}'.format(angulo,seno)) print('O ângulo de {} tem o cosseno {:.2f}'.format(angulo,co...
8c0eb4f8b18546acd72b222d8468c56d3ff9f93a
Namratabhatt/PYTHON
/LONGEST_FIBO.py
819
4.09375
4
'''GIVEN AN ARRAY WITH ELEMENTS SEPARATED USING COMMA(,) YOU HAVE TO FIND THE LARGEST FIBONACCI SERIES POSSIBLE OUT OF THE GIVEN ELEMENTS IN THE ARRAY AND PRINT IT EX:I/P:2,6,3,5,8,9 O/P:2,3,5,8 ''' istring=list(map(int,input().split(","))) leng=len(istring) new_string=[] for i in range(0,leng): fo...
31f938a98e45a500bde80c53364f9855dde2a3bb
Namratabhatt/PYTHON
/bracket_validater.py
739
3.984375
4
'''BRACKET_VALIDATOR: compute the position at which the brackets loose its completeness ex:input:[][ output:4''' def validator(string): count=0 list=[] for b in string: if(b=='[' or b=='{' or b=='()'): list.append(b) count+=1 continue ...
7d04d967719fbec6058addd071a869befa8dbe2a
doctorsmonsters/coverage
/tutorial.py
208
3.734375
4
def say_hello(name=None): if name != "": print("Hello", name) else: print("Hello Stranger") if __name__ == "__main__": say_hello(input("What's your name? ")) # pragma: no cover
ebdde2b5175da8f090004c82ca7f6b85a995368f
sbuss/pyspellsug
/trie.py
3,463
4.25
4
class TrieNode(object): """ A node in a Trie, intended for dictionary lookups. >>> t = TrieNode() >>> t.insert('salmon') True >>> 'salmon' in t True >>> t.lookup('sal') False >>> t.lookup('salmon') True """ def __init__(self): self.children = {} self.is_t...
89d56e31f80950b8003903c7d20044b62d56a72a
eventuallyrises/Python
/CW_find_the_next_perfect_square.py
821
4.15625
4
#we need sqrt() so we import the build in math module import math #we start the function off taking in the square passed to it def find_next_square(sq): #for later we set up the number one higher than the passed square wsk=sq+1 # Return the next square if sq is a square, -1 otherwise #here we look to see...
7047f3f389372509d6be0c13984145dcafe5eb1e
xmen1412/oop
/oop_staff_python.py
1,018
3.5625
4
class Karyawan: jml_karyawan = 0 #Class variable #constructor def __init__(self,kid,nama,jabatan,pendidikan): self.kid = kid self.nama = nama self.jabatan = jabatan self.pendidikan = pendidikan Karyawan.jml_karyawan += 1 #method def infoKar...
19c5a6fc7d9a250ee4edadaea91f0c5aa31f819f
guzmananthony37/Homework
/3.18.py
546
3.875
4
#Anthony Guzman 3.18 CIS2348 1503239 paintColors = {'red':35, 'blue':25, 'green':23} h = int(input("Enter wall height (feet):\n")) w = int(input("Enter wall width (feet):\n")) area = h*w round(area) print("Wall area:",area,"square feet") galls = area / 350 print("Paint needed:","{...
5dda120154fa92f82b8444b2cee63dc29e26d095
SAICHARAN007/Python
/exercise18.py
328
3.6875
4
#functions def print(*info): name, contact=info print(f"the information details are name:{name} and contact:{contact}") def print(name, contact): name,contact=info print(f"the information details are name:{name} and contact:{contact}") #this one takes no arguments def print_none(): print("I got not...
66c042036c2332172612393afd22ed91582cdef8
SAICHARAN007/Python
/exercise8.py
262
3.609375
4
formatter="{}{}{}" print(formatter.format(1,2,3)) print(formatter.format('one','two','three')) print(formatter.format(true,false,true)) print(formatter.format(formatter,formatter,formatter)) print(formatter.format("print what ever","you want","by using print"))
11473b3046b6a2b3df4c0c596b6e6d06107f8a34
amirji/xnet
/neural_network.py
1,505
3.609375
4
import numpy as np class Neural_Network(object): def init_(self): #Define HyperParameters self.inputLayerSize = 2 self.outputLayerSize = 1 self.hiddenLayerUnitSize = 3 #Weights Parameters self.W1 = np.random.randn(self.inputLayerSize,self.hiddenLayerUnitSize) ...
6ab5bde505ab49bad84e7a774bc4106641eb0b19
isralimas/cursos_gausss
/adios_amigos.py
451
3.546875
4
matrox = ("matrix",'perro',10) print matrox[2] print matrox[1] + str(matrox[2]) + matrox[0] tupla = ('perro','gato') print tupla tupla = ('gato') print tupla tupla = ('gato',) print tupla diccionario = {'primero':'gato','segundo':'perro'} print diccionario print tupla[0] print diccionario['primero'] tupla = ('per...
71081e756acafa26fd88ae72804989d30bb439be
mg-glb/ai-curated-notes
/Cognitive Class/0 - Applied Data Science with Python/1 - Python for Data Science/helloWorld.py
251
4.09375
4
print("Hello Python 101!") x="Lizz" print(x[0:2]) y=[0,"Hello"] y.append(1) print(y) A=['1','2','3'] for a in A: print(2*a) print(int(3.2)) A='1234567' print(A[1::2]) A=[1,'a'] B=[2,1,'d'] print(A+B) a=set(A) print(a) for n in range(3): print(n)
10ff11a07e15dcb31dfe96190c2b2991ee1b762b
mg-glb/ai-curated-notes
/Cognitive Class/1 - Cognitive Analytics/1 - Machine Learning with Python/supportVectorRegression.py
1,912
3.9375
4
#This small demo is about svm's. However you should take a more indepth course about this method. from sklearn.svm import SVR import numpy as np #Import the libraries to draw the plots. import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from sklearn import decomposition #Set the random seed to ens...
f5e1d5d7befc5a71139d9bdcf3d38f47cb9ecbd7
mg-glb/ai-curated-notes
/Cognitive Class/1 - Cognitive Analytics/1 - Machine Learning with Python/rfSkulls.py
1,670
3.703125
4
#Now we are going to use Random Forests to determine the classes of the data in skulls.csv import numpy as np import pandas from sklearn.ensemble import RandomForestClassifier from sklearn.model_selection import train_test_split from sklearn import metrics #These imports are used to create the tree image from sklear...
ffdcc0fb2ef981afd245ced60cf9f101b1a000c9
mg-glb/ai-curated-notes
/Cognitive Class/0 - Applied Data Science with Python/3 - Data Visualization with Python/scatterPlots.py
5,116
3.78125
4
import numpy as np # useful for many scientific computing in Python import pandas as pd # primary data structure library import matplotlib as mpl import matplotlib.pyplot as plt mpl.style.use('ggplot') df_can = pd.read_excel('https://ibm.box.com/shared/static/lw190pt9zpy5bd1ptyg2aw15awomz9pu.xlsx', ...
47bf33f0d3773066f9e623491531b3c163a378d5
aegglin/python-challenges
/quiz/quiz_brain.py
897
3.515625
4
class QuizBrain: def __init__(self, questions_list): self.question_number = 0 self.questions_list = questions_list self.score = 0 def next_question(self): curr_q = self.questions_list[self.question_number] self.question_number += 1 user_response = input(f'{self.q...
66790024aec9fd6ef606a4238e1ca9609b4345cf
aman1000/Python-Basic-Codes
/Electricity_Bill.py
202
4.03125
4
print("**Electricity Bill**") a=float(input("Enter Meter Reading:")) if (a<=100): amnt=a*5.95 else: amnt1= 100*5.95 amnt2=(a-100)*6.95 amnt=amnt1+amnt2 print("Total Bill Amount:",amnt)
ecc3a6b5b28b13535319b316e1f0a6110fdb155e
anurag423/133TeamPython
/TeamPython/Program_Code_Smoothing_Team_10.py
4,202
3.640625
4
''' =============================================================================== ENGR 133 Program Description Program runs operations on input images and outputs them following user instructions. Assignment Information Assignment: Team Python Project Author: Anurag Numboori, anumboor@pur...
4280cf078525da6fad206ace2d787bae8d7b1d3d
iverson52000/DataStructure_Algorithm
/LeetCode/0127. Word Ladder.py
1,068
3.765625
4
""" *127. Word Ladder Given two words (beginWord and endWord), and a dictionary's word list, find the length of shortest transformation sequence from beginWord to endWord, such that: 1. Only one letter can be changed at a time. 2. Each transformed word must exist in the word list. Note that beginWord is not a transform...
9df754d058c462d1aabd53b523ea95fa7e07a89a
iverson52000/DataStructure_Algorithm
/LeetCode/1170. Compare Strings by Frequency of the Smallest Character.py
855
3.921875
4
""" 1170. Compare Strings by Frequency of the Smallest Character Let's define a function f(s) over a non-empty string s, which calculates the frequency of the smallest character in s. For example, if s = "dcce" then f(s) = 2 because the smallest character is "c" and its frequency is 2. Now, given string arrays queri...
0775e2adf4ec232960c96e2f803012e552deb116
iverson52000/DataStructure_Algorithm
/LeetCode/0113. Path Sum II.py
680
3.671875
4
""" 113. Path Sum II Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum. """ #recursion class Solution: def pathSum(self, root: TreeNode, sum: int) -> List[List[int]]: if not root: return [] res = [] path = [] self.dfs(root, sum, r...
a0ee0c304b41e6c29cb0800c0d1c045d3cbb2ae2
iverson52000/DataStructure_Algorithm
/LeetCode/0818. Race Car.py
1,429
4
4
""" 818. Race Car Your car starts at position 0 and speed +1 on an infinite number line. (Your car can go into negative positions.) Your car drives automatically according to a sequence of instructions A (accelerate) and R (reverse). When you get an instruction "A", your car does the following: position += speed, spee...
5ef60120bcaa7a2d09905a907227064763bfedf6
iverson52000/DataStructure_Algorithm
/LeetCode/0792. Number of Matching Subsequences.py
794
3.671875
4
""" 792. Number of Matching Subsequences Given string S and a dictionary of words words, find the number of words[i] that is a subsequence of S. """ #hashmap+binary search+recursion class Solution: def numMatchingSubseq(self, S: str, words: List[str]) -> int: m_idx = collections.defaultdict(list) ...
8597d82bc2cd6b729174cf74c7f6893129aa70ca
iverson52000/DataStructure_Algorithm
/LeetCode/0005. Longest Palindromic Substring.py
1,190
3.734375
4
""" 5. Longest Palindromic Substring Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000. """ #Two pointer class Solution: def longestPalindrome(self, s: str) -> str: if not s: return '' res = '' for i in range(len(s)): ...
f8183c0ada78525a5f77b06e7d880459f5dc89b2
iverson52000/DataStructure_Algorithm
/LeetCode/0332. Reconstruct Itinerary.py
962
3.609375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Oct 20 11:02:18 2019 @author: alberthsu """ """ 332. Reconstruct Itinerary Given a list of airline tickets represented by pairs of departure and arrival airports [from, to], reconstruct the itinerary in order. All of the tickets belong to a man who dep...
f94e968b2c2c3ee1bd5e832bb53bad47b0d7dac8
iverson52000/DataStructure_Algorithm
/LeetCode/0032. Longest Valid Parentheses.py
594
3.5625
4
""" Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring. """ #stack+two pointers class Solution: def longestValidParentheses(self, s: str) -> int: if not s: return 0 stack = [] res = 0 left = -1 ...