blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
d0578ce01323c857e044bae64306c3e5e5542c25 | Rebaiahmed/Hackerrank_challenges | /Regex/Re.split.py | 94 | 3.578125 | 4 | import re
list =re.split("[,.]+",input())
for i in list :
if(i.isdigit()):
print(i)
|
174b14c2a1c28d757eac0dffe72e1b2b0db742dc | supergravity/PythonLearning- | /MIT_Computation/Programming_Python/Week2/exercise_2.py | 351 | 3.84375 | 4 | def gcdRecur(a, b):
'''
a, b: positive integers
returns: a positive integer, the greatest common divisor of a & b.
'''
if (a == 0):
return b
elif (b == 0):
return a
else:
if(b >= a):
return gcdRecur(a,b%a)
else:
return gcdRecur(a%... |
53abb9ea60d0c10f23471c97cd608d9e2a378b1d | Aasthaengg/IBMdataset | /Python_codes/p03108/s967526997.py | 2,197 | 3.703125 | 4 | class UnionFind():
#https://note.nkmk.me/python-union-find/
#note.nkmk.me 2019-08-18
def __init__(self, n):
self.n = n
self.parents = [-1] * n
def find(self, x):
if self.parents[x] < 0:
return x
else:
self.parents[x] = self.find(self.parents[x]... |
0cd5bb5aa1d61e9042f226c140a267603984c85d | bmrahman24/Python-learner | /welcome.py | 550 | 4.0625 | 4 | #text_to_print="Hello world"
#print(text_to_print)
#number1 = 10
#number2 = 5
#result = number1 + number2
#print(result)
# "number1=10
# print(number1)
#
# number1=15
# number1=18
# print(number1)
#
# number1= "Hello"
# print(number1)"
#name=input("what is your name ? ")
#print("Welcome to pytho... |
0c1a0e4d53e789094fceb4c78d61f01433fb659a | iPrograms/PowerAnalysisCPU | /args.py | 5,451 | 3.578125 | 4 | #!/usr/bin/env python2.7
'''
File name: args.py: process command line argument(s)
Author: Manzoor Ahmed
: Pierre Vachon
Date created: 11/06/2017
Date last modified: 11/06/2017
Python Version: 2.7
Version 1.0
'''
import sys
class InputChecker:
def __init__(self):
... |
a53855c25710b700969e308fe91f65fa5c72cbd5 | hahahayden/CPE101 | /Project1 Turn IN/skater.py | 1,604 | 4.1875 | 4 | # Project1
#
# Name: Hayden Tam
# Instructor: S.Einakian
# Section:05
import math
import funcs
def main():
pounds=float(input("How much do you weigh (pounds)? "))
distance=float(input("How far away your profesor is (meters)? "))
object=(input("Will you throw a rotten (t)omato,banana cream (p)ie, (r)ock, (l)ig... |
f3d9e126d310657b86a870044ef6df21c9868bcb | joyceyu6/coding_courses | /2021_4_19_to372/322.coin-change.py | 2,052 | 3.78125 | 4 | '''
You are given coins of different denominations and a total amount of money
amount. Write a function to compute the fewest number of coins that you
need to make up that amount. If that amount of money cannot be made up by
any combination of the coins, return -1.
You may assume that you have an infinite number of... |
4fbb490d83b8422cb97f2bab928c6be789ad35fd | ciesielskiadam98/pp1 | /02-ControlStructures/PESEL.py | 453 | 3.609375 | 4 | pesel = input("Podaj PESEL: ")
if (pesel[9] == "0" or pesel[9] == "2" or pesel[9] == "4" or pesel[9] == "6" or pesel[9] == "8"):
plec = "Kobieta"
else:
plec = "Mężczyzna"
a = pesel[0:2] #zmienna pomocnicza do przechowania elementów str jakos int
b = pesel[2:4] #jak wyżej
a = int(a)
b = int(b)
if b <= 12:... |
d7a631f66af089cb529c569fd99a4e89e4409e9e | akhasaya/Leetcode-practice | /remove_stones.py | 1,128 | 3.625 | 4 | # https://leetcode.com/problems/most-stones-removed-with-same-row-or-column/
# I coded this after reading the answer provided in leetcode
# this code looks much cleaner than any code i have written before
class Solution(object):
def removeStones(self, stones):
ls = len(stones)
adj_list = [[] for i ... |
14224991630e9f7a12869e48d46d478714e83bc3 | YangAusDu/python-notes | /process/self_defined_proccess.py | 429 | 3.53125 | 4 | from multiprocessing import Process
class MyProcess(Process):
def __init__(self,name):
super(MyProcess,self).__init__()
self.name = name
def run(self):
p = 1
while True:
print("{}--------->self-defined, p: {}".format(self.name, p))
p +=1
if _... |
a6446519a4745b3d5d72e3876025f1e8b56d8917 | qxlei/item_based_movie_recommendation | /t.py | 180 | 3.625 | 4 | dic={'1': {'1': 5, '2': 3}, '2': {'1': 4}}
for user, items in dic.items():
for i in items.keys():
print(i,'a')
for j in items.keys():
print(j, 'bb') |
ca469058c67bd106d90fddc1b88b5ffba3b66bcb | NelsonarevaloF/holbertonschool-higher_level_programming | /0x0C-python-almost_a_circle/models/base.py | 2,213 | 3.578125 | 4 | #!/usr/bin/python3
"""in this module is the base function"""
import json
class Base:
"""This class will be the “base” of
all other classes in this project."""
__nb_objects = 0
def __init__(self, id=None):
"""this initialize the values
depending the value of size"""
if id is no... |
6753341c5411df41eed409a1c366e5bc7ff8ce94 | LucasDM19/botfair | /Stats.py | 1,829 | 3.5625 | 4 | """
Uma classe apenas para obter os dados do Json, com estatisticas.
"""
class SoccerStats():
def __init__(self, url='http://foob.ar/resource.json'):
self.url = url
def getStats(self):
try:
from urllib.request import urlopen
except ImportError:
from urllib2 import urlopen
... |
0407de5239993ae7db769eaaadc635c1591abeff | yonginggg/MassiveDatasetsML_school | /神经网络/前馈神经网络.py | 1,852 | 3.734375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2019/11/4 15:52
# @Author : YangYusheng
# @File : 前馈神经网络.py
# @Software: PyCharm
# coding:utf-8
import numpy as np
import pandas as pd
class NeuralNetwork():
# 随机初始化权重
def __init__(self):
np.random.seed(1)
self.synaptic_weights = 2... |
26dff8a8b553e40a2128a74fb970363f95988e1e | saumil-jain/date_utils_web | /dateutils/datediff/models.py | 1,605 | 3.578125 | 4 | from django.db import models
import datetime
def process_input_date(input_date):
"""Parse the input date string and return a date object
The object returned is of the type datetime.date.
:param input_date: The date in the ISO format yyyy-mm-dd
:return: A datetime.date object representing the input d... |
4fd296b0960827c87e7a4961ff8c607989f0e2f1 | KoreyEnglert/another-in-class | /leap_year_error_handling.py | 352 | 4.125 | 4 | c = False;
while not c:
year = input("Enter a year to check: ");
try:
year = int(year);
c = True;
except:
print("That is not an integer!");
if year % 4 == 0:
if year % 100 == 0 and year % 400 != 0:
print(str(year) + ' is not a leap year.');
else:
print(str(year) + ' is a leap year.');
else:
print(str(y... |
b8e6d62a98a1a3df450d87e8efb4cbcd1ed2f261 | Nunez350/DeepLearningWithR | /multi_layer_neuron/Multiple_Neuron_Classification.py | 4,634 | 3.609375 | 4 | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from numpy import exp
from numpy.random import uniform
df = pd.read_csv("iris.csv")
df = df.drop([df.columns[0]], axis=1)
df = df.reset_index(drop=True)
# Multiple Neuron Classification Normalized by Softmax Function
def multiple_neuron_classifica... |
d545f1d7754437961a7f7ff6d492ebb217400ab6 | Aditya7799/171IT204_Sem3 | /DSA/Lab1/fib.py | 89 | 3.859375 | 4 |
n=input("enter number: ")
a=0
b=1
for i in range(n):
print(a)
temp=b
b=a+b
a=temp |
e53f085278bac99953ce851b190fc2bf32dff3a4 | apostlepaul/leetcode | /725_split_linked_list.py | 1,258 | 3.75 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def splitListToParts(self, root, k):
"""
:type root: ListNode
:type k: int
:rtype: List[ListNode]
"""
total_node_num... |
779f4ac37fe780dbd8da90236d11c2abac63b397 | hariharan-m/EC504 | /Server/kdTree.py | 4,950 | 3.5 | 4 | import numpy as np
import queue as Q
class Node:
def __init__(self, data, lchild=None, rchild=None):
self.data = data
self.lchild = lchild
self.rchild = rchild
class KdTree:
def __init__(self):
self.kdTree = None
def create(self, dataSet, depth): # create kd tree, retur... |
520119ee576866dc1a91a76aed4af5a88a900fbd | MrHamdulay/csc3-capstone | /examples/data/Assignment_3/ndxshe013/question4.py | 545 | 4.03125 | 4 | import math
def palindrome(a):
s = str(a)
if(s == s[::-1]):
return True
else:
return False
def prime(a):
for i in range(2,int(math.sqrt(a))+1):
if(a%i == 0):
return False
return True
def main():
N = eval(input("Enter the star... |
a5928c524079ff7de9b6eda462a91b1c86cd687b | jbanerje/Beginners_Python_Coding | /kth_element.py | 169 | 3.953125 | 4 | #Finding kth element in list
userElement = [1,2,3,4,5]
userChoice = int(input('Enter the kth element #: '))
print('Kth element is :', userElement[userChoice])
|
2e3c12e482f4f938157d166d4a02f9a8284f8f0b | JavierCamposCuesta/repoJavierCampos | /1ºDaw/ProgramacionPython/Python/ej_bucles3/ej1.py | 1,674 | 4.09375 | 4 | '''Ejercicio 1 Diseñar un programa que calcule el perímetro de una figura geométrica. Para ello debemos preguntar “¿Cuántos lados
tiene la figura?”. Luego debemos pedir la longitud de cada uno de los lados y mostrar el perímetro. Se debe garantizar que
los datos son correctos.
Created on 17 Nov 2020
@author: estudia... |
61e943b502ab48f3cbaf6bbc5fb1c7b47a7fcf40 | surenderpal/Durga | /Exception Handling/else_block.py | 356 | 3.796875 | 4 | # for x in range(10):
# if x>5:
# break
# print('Current item',x)
# else:
# print('Congrats!!')
# try:
# print('try')
# print(10/0)
# except:
# print('except')
# else:
# print('else')
# finally:
# print('finally')
try:
print('try')
else:
print('else')
finally:
prin... |
df3526265cf2bc8fb9b4e56d203e669a0ea29ecf | Nihadkp/MCA | /Semester-01/Python-Programming-Lab/Course-Outcome-1-(CO1)/17-Sort-in-Dictionary/Sort_dictonary.py | 791 | 4.0625 | 4 | # user inpupt section - errror in this
# """ dictCount = int(input("Enter the number of dictionary values"))
# dictItem = {}
# for i in range(dictCount) :
# name = input()
# values int(input())
# dictItem[name] = values
# ""
#
dict1 = {}
print(type(dict1))
limit = int(input("Enter the limit"))
for i in ra... |
046b988c338ceda80b10adb08b16f22a56f8ab98 | Yogesh-B/PROJECTS | /Python/Pract12.py | 986 | 4.03125 | 4 | # Using Function
def isPrime(num):
print('\nUsing Function')
flag = False
if num > 1:
for i in range(2, num):
if (num % i) == 0:
flag = True
break
return flag
def printMessage(number,result):
if result:
print(number, "is not a Prime Number... |
78f79e9feb36c8783f3284163002733edcc434ad | crystalDf/Grokking-Algorithms-Chapter-04 | /BinarySearch.py | 452 | 3.890625 | 4 | def binary_search(arr, item):
if len(arr) == 0:
return None
mid = len(arr) // 2
guess = arr[mid]
if guess == item:
return guess
if guess > item and mid > 0:
return binary_search(arr[:mid], item)
elif guess < item and mid < len(arr) - 1:
return binary_search(arr... |
58c93d9857d9dc866f7f736d5bf7b55c59d677b2 | siva4646/DataStructure_and_algorithms | /python/backtracking/generate_paranthesis.py | 874 | 3.875 | 4 | """
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
Example 1:
Input: n = 3
Output: ["((()))","(()())","(())()","()(())","()()()"]
Example 2:
Input: n = 1
Output: ["()"]
"""
class Solution(object):
def generateParenthesis(self, n: int):
result ... |
99ec918009a73d74c31892c4fdc017a960d20612 | zxun1/hacker_rank | /nested-list.py | 517 | 3.9375 | 4 | # Get all students and scores
students = []
for _ in range(int(raw_input())):
name = raw_input()
score = float(raw_input())
students.append([name,score])
# Find the second lowest score
scores = []
for student in students:
scores.append(student[1])
second_lowest_score = sorted(set(scores))[1]
second_lo... |
0c7e386aab0709747768ecf1c9d5d47b508cf50e | dettore/learn-python-exercises | /_beginners python 3 source files/33-functions.py | 233 | 4 | 4 | # Learning function
# def is short for: define
def PrintSomeStuff():
print('Stefan just ate some chicken.')
print('Now is time for exercise.')
def PrintSomeMoreStuff():
print('***** Second.')
PrintSomeMoreStuff()
|
13e930bc684ffdd597be6a601e05d9609621417c | danielrhunt/python | /operator_practice.py | 2,221 | 4.5 | 4 | # #practicing with boolean logic
#
# print(5==5) #will print True
# print(5==6) #will print False
#
# comparison operators include:
# x != y #x does not equal y
# x > y #x is greater than y
# x < y #x is less than y
# x >= y #x is greater than or equal to y, need that order for operators
# x <= y #x is less than or equ... |
ee8b716c6ecdb46ddc1f42d2d9f5bd23133bb61b | Pramod123-mittal/python-prgs | /oops_eleven.py | 880 | 4.21875 | 4 | # polymorphism-->ability to take various forms
print(5 + 6)
print('5' + '6')
# super keyword and overiding
class A:
classvar1 = 'i am a class variable inside class A'
def __init__(self):
self.var1 = 'i am inside class A"s constructor'
self.classvar1 = 'instance variable in class A'
se... |
741749f34a6a51c1dc95e930ff9b529510dcdee0 | shenzhiyong17/python_homework | /data_structure/common/gen_rand.py | 585 | 3.59375 | 4 | #!/usr/bin/env python
# date: 2016-2-2
import random
import string
def gen_rand_list(num, start=0, stop=1000):
lst = []
for i in range(num):
x = random.randint(start, stop)
lst.append(x)
return lst
def gen_rand_string(length):
s = string.letters + string.digits
result = ''
f... |
b8be002a273d2bd8d4a2e2770f584a2aeb63e0aa | faiztherocker/Python | /Word_count.py | 1,065 | 3.71875 | 4 | import operator
"""
#Set basics
setone = {'again':1,'back':2}
print(setone['again'])"""
def start():
word_list = []
fr = open('FinalPaper.txt','r')
content = fr.read()
words = content.lower().split()
for eachh_word in words:
#print(eachh_word)
word_list.append(eachh_word)
cle... |
5f925cc3b5ea02f94fcee3d4ad765f32d5711bda | petitviolet/project_euler | /48.py | 256 | 3.5625 | 4 | # -*- encoding:utf-8 -*-
def num(n):
return n ** n
def order_10(n):
s = str(n)
return s[-10:]
def main():
n = 0
for i in xrange(1, 1000):
n += num(i)
ans = order_10(n)
print ans
if __name__ == '__main__':
main()
|
7fc81d71099e2a8910daf6ada29e6a36c26fe218 | xing3987/python3 | /base/面向对象/_30_eval.py | 378 | 3.546875 | 4 | # 执行函数
input_str = input("请输入计算题\n")
print(eval(input_str))
# 警慎使用eval()函数,容易产生漏洞,特别是eval(input())直接执行用户输入的内容
#系统自带执行指令的方法
#__import__('os').system('pwd')
# 如果input中输入导入os模块,执行系统命令就太可怕了:
# eval("__import__('os').system('pwd')")
|
531e6fcb5bc1a461b53128c41588c6c89b6dbd8b | stefan9090/applied-AI-practicum | /exercises_6/cards.py | 3,313 | 3.734375 | 4 | import random
import math
from functools import reduce
import operator
def individual(min_val, max_val):
"""
This function returns an individual which consists of 10 unique numbers.
"""
value_list = [i for i in range(min_val, max_val+1)] #generate a list of 1 to 10
random.shuffle(value_list) #shuf... |
a143d2c7b103e336f7498e312f85c4887314c5bc | abigail-hyde/flood-agh54-bjw68 | /Task1D.py | 1,047 | 3.53125 | 4 | from floodsystem.geo import rivers_with_station
from floodsystem.geo import stations_by_river
from floodsystem.stationdata import build_station_list
def run():
"""Requirements for Task 1D"""
# Create a list of stations
stations = build_station_list()
# Create list of rivers
rivers = rivers_with_s... |
1b658c9bebc19e4e5135828b3321c766541f128d | museRhee/basicPython | /findNum.py | 730 | 3.859375 | 4 | '''
enter m, and find n.
enter 0, program exit.
n satisfies the following condition.
1.sum of integers from 1 to n is same or less than m
2.n is the biggest one which satisfied the condition 1.
'''
while (True) :
m = int(input("Enter the number m: "))
if (m == 0) : #program exit ... |
bca74cd8cff526bd933971bbb0c0088c3376c3e4 | kikijtl/coding | /Candice_coding/Leetcode/Remove_Duplicate_Array.py | 1,371 | 3.671875 | 4 | def removeDuplicates(A):
n = len(A)
if n == 0:
return n
i = 0
j = 0
while i < n and j < n:
if A[j] == A[i]:
j += 1
else:
i += 1
A[i] = A[j]
#return the length of array
return i+1
def removeDuplicates2(A):
n = le... |
8353c22928b60f236cba618965664867310aaa04 | EEJDX/AlgorithmExperiments | /naive.py | 612 | 3.546875 | 4 | def naive(a, b):
x = a
y = b
z = 0
while x > 0:
z = z + y
x = x - 1
return z
def rec_naive(a, b):
print("count me!")
if a == 0:
return 0
return b + rec_naive(a-1, b)
def russian(a, b):
x = a; y = b
z = 0
while x > 0:
if x == 7 and z == 84: p... |
521c70f3c4cc641772a908a1f8b7838f0fcec2e9 | DeVinhoOne/python-currency-converter | /converter.py | 1,047 | 3.546875 | 4 | import requests
from show_additional_info import show_additional_info
print('\n\t\t===Currency Converter===')
show_info = input('\tDo You need additional info?(y/n) ').lower()
if show_info == 'y':
show_additional_info()
elif show_info == 'n':
pass
class Converter:
def __init__(self):
self.amoun... |
c70a383882f321c812e0fc70cc91e3b6b1600672 | SkipDigit/battleship | /gui.py | 872 | 3.59375 | 4 | import tkinter as tk
'''
top=tk.Tk()
A1=tk.Button(top, text='A1')
A2=tk.Button(top, text='A2')
B1=tk.Button(top, text='B1')
B2=tk.Button(top, text='B2')
A1.grid(row=0,column=0)
A2.grid(row=0,column=1)
B1.grid(row=1,column=0)
B2.grid(row=1,column=1)
top.mainloop()
'''
class Application(tk.Frame):
def __init__(s... |
8a35f686e92f8a22f1b34b06d4218c6402bec33f | davidwarshaw/leetcode | /google/Flatten-Nested-List-Iterator.py | 3,028 | 4.3125 | 4 | #!/usr/bin/env python
"""
This is the interface that allows for creating nested lists.
You should not implement it, or speculate about its implementation
"""
class NestedInteger(object):
def __init__(self, nested):
self.items = nested
self.is_list = True if type(nested) == list else False
de... |
cf51e04818edf0d092e808589e7c844a06e3a534 | HARICHANDANAKARUMUDI/chandu | /vowel.py | 269 | 4.125 | 4 | val1=input()
if val1>='a' and val1<='z' or val1>='A' and val1<='Z':
if val1=='a' or val1=='e' or val1=='i' or val1=='o' or val1=='u' or val1=='A' or val1=='E' or val1=='I' or val1=='O' or val1=='U':
print("Vowel")
else:
print("Consonant")
else:
print("Invalid")
|
c0d446274aa2210d354f1a798e5a0032713d73b0 | LionWar22/Lista_de_exercicios | /ex04.py | 1,148 | 4.25 | 4 |
# v = float(input("Velocidade em km/h: "))
#
# t = float(input("Tempo em h : "))
#
# s = v * t
#
# print("Distancia de {} Km".format(s))
#Aperfeiçoando o exercicio
def calcDistancia(): #Função calcula a distancia
v = float(input("Velocidade em km/h: ")) #As variaveis necessarias para o calculo são criadas dent... |
72aa8888a7462e9ea15e7b555ab016d8474a113a | sukaran/NLTKBook | /ch2_exercises.py | 19,500 | 3.546875 | 4 | import nltk
import re
from nltk.corpus import gutenberg
from nltk.corpus import brown
from nltk.corpus import state_union
from nltk.corpus import wordnet as wn
from nltk.corpus import swadesh
from nltk.book import text1 as mobydick #mobydick
from nltk.book import text2 as sense_and_sensibility #sense_and_sensibility
fr... |
5539d7df9d444008e030b596dc0668a513425ae5 | AlexanderOnbysh/edu | /bachelor/generators.py | 3,744 | 3.765625 | 4 | # yield and yield from difference
# yield
def bottom():
return (yield 42)
def middle():
return (yield bottom())
def top():
return (yield middle())
>> gen = top()
>> next(gen)
<generator object middle at 0x10478cb48>
# ----------------------
# yield from
# is roughly equivalent to
# ***
# for x in iter... |
30d6024e4d23a769faba97c186b42446c27d74b1 | shen-huang/selfteaching-python-camp | /exercises/1901100142/1001S02E03_calculator.py | 659 | 4.03125 | 4 | operator=input('请输入运算符(+、-、*、/):')
first_number=input('请输入第一个数字:')
second_number=input('请输入第二个数字:')
a=int(first_number)
b=int(second_number)
print('operator:',operator,type(operator))
print('first_number:',first_number,type(first_number),type(a))
print('second_number:',second_number,type(second_number),type(b))
prin... |
361cd3e8e13a25c1a69376f12b9d4a86598b937b | Tammon23/30-Day-LeetCoding-Challenge-April-2020 | /Min_Stack.py | 1,185 | 3.9375 | 4 | class MinStack:
def __init__(self):
"""
initialize your data structure here.
"""
self.minEl = None
self.stack = []
def push(self, x: int) -> None:
if len(self.stack) == 0:
self.minEl = x
self.stack.append(x)
return
... |
315bee72a88ca73d7ef58bd891b4535cf5922148 | mveselov/CodeWars | /tests/beta_tests/test_data_reverse.py | 621 | 3.625 | 4 | import unittest
from katas.beta.data_reverse import data_reverse
class DataReverseTestCase(unittest.TestCase):
def test_equals(self):
self.assertEqual(data_reverse(
[1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0]),
[1, ... |
4b23b8a6afb26eaeecaf19a84e2fd9de428b9e8f | rileyL6122428/data-science-from-scratch-notes | /09-exercises/basic_idea_grad_descent.py | 1,646 | 4.09375 | 4 | from functools import reduce
from matplotlib import pyplot
def sum_of_squares(vector):
return reduce(lambda cumulative, next: cumulative + next ** 2, vector)
print('sum of sqaures([1, 2]) = %s' % sum_of_squares([1, 2]))
# gradient is the vector of partial derivative
# gives the input direction in which the funct... |
f371c6132d7d8a3b1ccc8cc7115f426aed949820 | jooyoung0878/AI-project | /Classification regression/naive.py | 1,962 | 3.546875 | 4 | import numpy as np
import matplotlib.pyplot as plt
from sklearn.naive_bayes import GaussianNB
from sklearn.model_selection import train_test_split
from sklearn.model_selection import cross_val_score
from utilities import visualize_classifier
#input file containing data
input_file = 'data_multivar_nb.txt'
#loa... |
edf8da572ce51e97a9fdc5911a2295c9893fc312 | AlekseiBulygin/Python | /Geometry_alorithms/triangulate/wrapper_Shewchuk_mesh_generator.py | 798 | 3.625 | 4 | """
Triangulation between two polygons (convex or concave hull)
Use Triangle - python wrapper around Jonathan Richard Shewchuk’s
two-dimensional quality mesh generator.
"""
import matplotlib.pyplot as plt
import triangle as tr
polygon = [[0, 0], [0, 4], [2, 4], [2, 5], [3, 5], [3, 8], [6, 4], [6, 0]]
offset_polygon = ... |
29aa6a97d9cbff5c0c67dc065dd8a01fe3cc0d4e | CNife/leetcode | /Python/leetcode/list.py | 1,451 | 3.875 | 4 | from typing import Optional, List
class ListNode:
def __init__(self, val: int):
self.val: int = val
self.next: Optional[ListNode] = None
def __eq__(self, o: object) -> bool:
return isinstance(o, ListNode) and self.val == o.val and self.next == o.next
def __str__(self) -> str:
... |
369b97985606b47fca998605d312eef0836fa36a | Anshelen/algorithms-explore | /sorts/quicksort.py | 2,294 | 3.796875 | 4 | """
Быстрая сортировка. Сложность в худшем случае О(n^2), обычно O(n*log n).
Осуществляет неустойчивую сортировку на месте.
"""
from sorts.partitions import partition, three_way_partition
def quick_sort_random(lst, l=0, r=None):
"""
Рекурсивный алгоритм быстрой сортировки с случайным выбором разделителя.
... |
d737d104f521ce3eb127f2d8d2e73a17dae5b220 | jbmenashi/coding-lessons | /Pathrise/SWEWorkshop2/merge_arrays.py | 395 | 3.703125 | 4 | def mergeArrays(arr1, arr2):
i = 0
j = 0
arr3 = []
while i < len(arr1) and j < len(arr2):
if arr1[i] < arr2[j]:
arr3.append(arr1[i])
i = i + 1
else:
arr3.append(arr2[j])
j = j + 1
while i < len(arr1):
arr3.append(arr1[i])
i = i + 1
whil... |
3bb47b2469d3be526b8f3be8396b991a901437db | burak-aytac/Python_exercises | /password_reminder.py | 269 | 4.1875 | 4 | my_name = "burak"
new_name = input("Lütfen isminizi giriniz : ")
password = "W@12"
if new_name.lower() == my_name:
print("Hello, {}! The password is : {}".format(my_name.upper(),password))
else:
print("Hello, {}! See you later.".format(new_name.upper())) |
cae6b5ecf988908a852804c6eee1ad517a9adff0 | Maxim-Deriuha/education_py | /test/test14.py | 170 | 3.65625 | 4 | n = input()
n = int(n[1:])
a =''
s=[]
for i in range(n):
a = input()
r = a.find('#')
if '#' in a:
a=a[0:r]
s.append(a.rstrip())
print(*s,sep='\n') |
bf2bb12a25164db3fa245642c5c6286d834b57cb | tub212/PythonCodeStudy | /Python_Study/LAB/LAB_prime.py | 699 | 4.125 | 4 | """prime number"""
def is_prime(number):
"""
int -> int
This programme is check prime number in range your input
"""
if number < 2:
return False
if number == 2:
return True
if not number & 1:
return False
for i in xrange(3, int(number**0.5)+1, 2):
... |
546921bba4b751b42c1e6e6115062859c370235a | ThoughtProvoking/LPTHW | /oop_test.py | 3,692 | 3.609375 | 4 | import random
from urllib.request import urlopen
from sys import argv
# store website url
WORD_URL = 'http://learncodethehardway.com/words.txt'
# create empty list
WORDS = []
# create snippets and phrases dict
PHRASES = {
'class %%%(%%%):': 'Make class named %%% that is-a %%%.',
'class %%%(object):\n\tdef __i... |
6384ac2f2cf6ff08c2df8cbd61bf7e9c10290796 | anonymous-acorn/python | /20200618 for문 리스트.py | 318 | 4.125 | 4 | for x in range(0,3):
print(x)
print("==========")
a=[1,2,3,4]
print(a)
print("==========")
for x in a: #[2,4,6,8]
print(x)
print("==========")
for x in range(3): #엔트리에 x번 반복하기랑 기능 비슷
print("반복")
print("==========")
a.append(10) #리스트에 10추가
print(a)
|
94e20a1f2d830404727f4468aceabd3fc88c4e21 | dgaldel/Puesta-en-producci-n-segura | /ejercicio1.py | 1,398 | 4.15625 | 4 | # hacer un pseudocodigo para introducir las edades de los 25 alumnos de la clase
# y sacar la edad mayor , la edad menor , numero de edades pares , numero de edades # impares y el factorial del mayor primo
import random
contador = 0;
mayor = 0;
menor = 0;
total_pares = 0;
total_impares= 0;
mayor_primo=0;
boolean = 0;... |
118b5b95935e0002ead29be79fe91f4612cc8c6c | Dqvvidq/Nauka | /listy[].py | 1,565 | 4.1875 | 4 | #metoda upper
print("Witaj")
print("Witaj".upper())
#metoda replace
print("Witaj".replace("j", "m"))
#tworzenie listy
fruit = ["mango", "banan", "gruszka"]
print(fruit)
#metoda append czyli dodawanie nowego elementu na koncu listy
fruit.append("pomelo")
fruit.append("figa")
print(fruit)
#w l... |
2692cc19c897c4f562ea9f5ce39b9d379687e124 | NinjaOnRails/del-unneeded-files | /delUnneededFiles.py | 1,098 | 3.796875 | 4 | #! /usr/bin/env python3
# delUnneededFiles - Deletes all files AND folders of certain size in KB
import shutil, os
folder = input("Enter path to the folder: ")
size = int(input("Size in KB: "))
def delUnneededFiles(folder, size):
filesFound = 0
for foldername, subfolders, filenames in os.walk(folder):
... |
94f7991fb39d9d512122f0fc838bae3762b13056 | joaopalmeiro/pybites | /Beginner-Bites/019.py | 372 | 3.640625 | 4 | from datetime import datetime, timedelta
NOW = datetime.now()
class Promo:
def __init__(self, name: str, expires: datetime) -> None:
self.name = name
self.expires = expires
@property
def expired(self) -> bool:
return NOW > self.expires
past_time = NOW - timedelta(seconds=3)
pro... |
10991e261fcfa235304a189e0d236a36c1d36a78 | inv-Karan/pytut | /dictionaries.py | 227 | 3.859375 | 4 | mydict = {'key1':123, 'key2':{'subkey2':100},'key3':[0,1,2], 'key4':['a','b','c']}
print(mydict)
print(mydict['key1'])
mydict['key5'] = "NEW VALUE"
print(mydict)
print(mydict.keys())
print(mydict.values())
print(mydict.items()) |
4edc0b940d2de8528df9c30938c9e5282b5539e4 | magedu-pythons/python-14 | /zhangjingwen/week13/mysingleton.py | 3,062 | 4.03125 | 4 | # 1、python 中如何实现单例模式,尽可能多的写出实现方式
# 方法一:将单例类定义和实例化放在一个py文件中,使用时从该模块导入
class Singleton:
def __init__(self):
pass
def foo(self):
print('this is a singleton!')
singleton = Singleton()
# 方法二:使用装饰器
def Mysingleton(cls):
_cls = []
def _singleton(*args, **kwargs):
if cls not in _cl... |
d258dbad06e5ccfc18b1b691e5a9a68d14debc01 | adrianrocamora/kng | /py/random/default.py | 390 | 3.734375 | 4 | import random
# Random float x, 0.0 <= x <= 1.0
print(random.random())
# Random float x, 1.0 <= x <= 10.0
print(random.uniform(1, 10))
# Integer from 0 to 9
print(random.randrange(10))
# Even integer from 0 to 100
print(random.randrange(0, 101, 2))
# Single random element
print(random.choice('abcdefghij'))
# Shuffle a ... |
cbbdb3a33d762e15ffe63e0759ae2d9c0439d939 | mary-tano/python-programming | /python_for_kids/book/Examples/hello3.py | 1,598 | 3.8125 | 4 | # Приветствие с кнопками
from tkinter import *
# Функция для события
def button1Click() :
Display.config(text="Это здорово!")
def button2Click() :
Display.config(text="Это радует!")
def button3Click() :
Display.config(text="Все возможно.")
def button4Click() :
Display.config(text="Это огорчает!")
def button5Cl... |
4bd3f36470010a6623e71bd4589a339169041515 | HudaFiqri/belajarPython | /LAB/ChatBot/#1 tanya waktu/Chat Bot tanya waktu.py | 819 | 3.890625 | 4 | from datetime import *
while True:
data = input('>>> ')
if (data == 'jam?' or data == 'jam'):
if (datetime.now().hour < 12):
print('sekarang jam {jam}:{menit} pagi'.format(jam=datetime.now().hour, menit=datetime.now().minute))
elif (datetime.now().hour < 15):
print('s... |
014b0be9368afce938098731a55561d32e294e76 | jeromesolomon/scu-coen283-os-scheduling-simulator | /scu-coen283-os-scheduling-simulator/os-scheduling/os-scheduling/RR.py | 1,881 | 4 | 4 | import Process
import Machine
from collections import deque
class RR:
def __init__(self, quantum):
self.myQueue = deque()
self.size = 0
self.quantum = quantum
def __str__(self):
"""
Private method used to print a queue neatly.
:return: a string
"""
... |
053bbb9c336b4c31d8d1488b2ba7c8dbcb792bca | AdrianPratama/AdrianSuharto_ITP2017_Exercise5 | /Exercise5-3.py | 418 | 3.875 | 4 | def hypotenuse(a,b):
try:
return (a+b).sqrt()
except TypeError:
return None
c = int(input("Please input number 1 here"))
d = int(input("Please input number 2 here"))
hypotenuse(c,d)
e = str(input("Please input string 1 here"))
f = str(input("Please input string 2 here"))
hypotenuse(e,f)
g = i... |
333d24643a325626604de8b0103e4d2384668a60 | codingeverybody/parallel-study-python-ruby | /Comment/1.py | 240 | 3.59375 | 4 | '''
조건문 예제
egoing
2015
'''
# user input password
input = 33
real_egoing = 11
#real_k8805 = "ab"
if real_egoing == input:
print("Hello!, egoing")
#elif real_k8805 == input:
# print("Hello!, k8805")
else:
print("Who are you?")
|
bfc20910104361da115de3bee5fe97ad99b605be | lux-ed/Python_katas | /7_kyu/complementary_dna.py | 620 | 3.625 | 4 | #In DNA strings, symbols "A" and "T" are complements of each other, as "C" and "G".
# My solution
def dna_strand(dna):
dicti = {"A":"T", "T":"A", "C":"G", "G":"C"}
return "".join(dicti[x] for x in dna)
#dna_strand("ATTGC")
#Clever
def dna_strand1(dna):
return dna.translate(str.maketrans('ATCG', 'TAGC'))... |
587bcaaf30d9f61742ed32c4d854e13140d9a37d | demelue/easy-medium-code-challenges | /Python/String/reverse_words_in_string.py | 1,072 | 3.90625 | 4 | def reverse_words_in_string_v1(s):
s = s.split(' ')[::-1]
out = []
for i in range(len(s)):
out.append(s[i] + ' ')
return ''.join(out)
def reverse_words_in_string_v2(s):
s = reversed(s.split(' '))
out = []
for val in s:
out.append(val + ' ')
return ''.join(out)
def rever... |
d2b337d937b591d2e0db292ddd479806330a4683 | DL-py/pandas-notebook | /024创建DataFrame.py | 1,045 | 3.765625 | 4 | """
创建DataFrame:
"""
import pandas as pd
import numpy as np
pd.set_option('display.max_rows', None)
pd.set_option('display.max_columns', None)
# 通过字典来创建:
# 生成的DataFrame数据的列表可能不是按字典顺序的,可以通过columns关键字加以指定,同样可以指定
# index的值
DataFrame = pd.DataFrame({'id': [100, 101, 102], 'color': ['red', 'blue', 'green']},
... |
f9aebc368fbc8ddea9a0e3a8f04dcb123a963964 | cvmsprogclub/2016-cyoas | /10.py | 4,466 | 4.1875 | 4 | score = 0
print("THIS IS A FIVE QUESTION MULTIPULE CHOICE QUIZ. YOUR GRADE WILL BE PRINTED AT THE END OF THE QUIZ, AS WELL AS A COMMENT. TEST VERSION 1.1.1")
print()
user = input("START THE TEST?")
if user == "Yes":
print("QUESTION 1: WHICH OF THE AIRCRAFT ARE MADE OUT OF COMPOSITE MATERIALS?")
print("A: ... |
94fed23a7ffddeaa52530895c9d36daa4685e16f | Joycici/Coding | /Python/Exercise/ex25.py | 1,633 | 4.15625 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
'''
Exercise 25: Even more Practise
This is not a script which can be run.
'''
"""
__author='Joycici'
__version__='1.0'
"""
'''
import os
#获取当前工作目录
>>>os.getcwd()
#更改当前工作目录
>>>os.chdir('d:\')
>>>os.getcwd()
可以import当前目录下的.py文件
import a
or
from a import *
'''
# 空格拆分
def br... |
45f8a960818baaecd10dbb13caf1f99b00754a73 | CrazyJ36/python | /tk_minimal_example.py | 466 | 4.09375 | 4 | #!/usr/bin/env python3
from tkinter import *
# Create Tk root(whole window) widget.
# One root per program, initialized before any widgets.
root = Tk()
# text Label as child view of root window
widget = Label(root, text="Window Text")
# Pack first widget. Sizing widget to fit into given text, and make it visible.
wid... |
d0db99420c24dd128cdf5e9de3081ea42d04ede1 | mjbrann4/python_training | /py_data_sci_1/9_df_manipulation/10_groupby_transformation.py | 833 | 3.75 | 4 | import pandas as pd
# apply distinct transformations to distinct groups
# changes dataframes in place
def zscore(series):
return (series - series.mean()) / series.std()
auto = pd.read_csv('data/auto-mpg.csv')
print(auto.head())
# apply to one series
z = zscore(auto['mpg'])
print(z.head())
# we can calculate z ... |
e7a5747be56ec1f10dbfd7ee22a0df21db71ed3e | iamvimal28/data_structures_and_algorithms | /python/selectionsort.py | 485 | 4.0625 | 4 |
#Selection sort has the time complexity for O(n^2) (Big O of n squared)
def selection_sort(arr, arr_len):
for i in range(0,arr_len-1):
minimum = i #Assuming minimum value index to be id
for j in range(i+1,arr_len):
if arr[j]< arr[minimum] :
minimum = j
#Swapping elements
temp = arr[i]
arr[i] = arr[mi... |
aa4e7a672f093f69e651e5377059de81f88d21d4 | StjepanPoljak/tutorials | /python/data-model/dictionary-ex.py | 1,808 | 4.15625 | 4 | #!/usr/bin/env python3
# NOTE: this is just an example of how dict works
# internally; subclass dict only if you want to
# extend it.
class MyDict(dict):
def __missing__(self, key):
raise Exception("Key {} not found.".format(key))
def __getitem__(self, key):
val = dict.__getitem__(self, key)
return val
de... |
86c4f3b39dfb97ec9d23051be16eee2e0541a107 | Gootle/Python | /HOMEWORK/BMI1.py | 2,434 | 3.8125 | 4 | Python 3.6.2 (v3.6.2:5fd33b5, Jul 8 2017, 04:14:34) [MSC v.1900 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> def bmi_app()
SyntaxError: invalid syntax
>>> def bmi_app():
height = input('tall')
weight = input('weight2')
bmi_value = int(weight)/(int(height)/100)**2
pr... |
ae2e6f62dda7e7e2a7a47b475607d3287bd32be1 | VSNorman/PZ_1 | /PZ_1_1.py | 600 | 4.21875 | 4 | # Поработайте с переменными, создайте несколько, выведите на экран,
# запросите у пользователя несколько чисел и строк и сохраните в переменные, выведите на экран.
a = 'Гулять'
b = 'Вася'
print(f"{a}, {b}")
Number_1 = int(input("Введите любое число - "))
Number_2 = int(input("А теперь другое любое число - ")... |
abc4a138da96e28eef96d1db715b4c40e649c2c8 | baaanan01/practice3-4 | /23_3.py | 366 | 3.546875 | 4 | strs = input().split(' ')
d = ['а', 'у', 'е', 'ы', 'а', 'о', 'э', 'я', 'и', 'ю']
c = 0
check = False
for el in strs:
i = 0
for e in el:
if e in d:
i += 1
if c == 0:
c = i
else:
if c != i:
print('Пам парам')
check = True
if not check:
print... |
03a4b965384ef86d5f45959172255835efc5f006 | Martins-Okounghae/Data_Structure | /hash_table.py | 1,079 | 4.59375 | 5 | #Accessing values in dictionary
print("----------------------------------")
print("Declaring a dictionary")
print("------------------------------------")
dict = {'Name':'Zara', 'Age': 7, 'Class': 'First'}
print("----------------------------------")
print("Accessing the dictionary with its key")
print("--------------... |
19152ca23faac5b6ef69cf18d486d31d79b215b2 | prathameshk03/The-Drinking-Game | /The Drinking Game 3.0.py | 3,265 | 4.03125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Jul 8 20:30:07 2021
@author: Dell
The Drinking Game 3.0
Added=>menu driven,activity addition possible, display activity list,bug fixes
"""
import random
names = []
actions = ["dances","sings","gets slapped by person to their right",
"gets slap... |
cabfc267708a4ad2cdfcfea0989a4240824b19e1 | IPanhui/python | /learn/07_面向对象/ph_03_设置对象属性.py | 436 | 3.640625 | 4 | class Cat:
def eat(self):
print("%s爱吃鱼" %self.name)
def drink(self):
print("%s爱喝水" %self.name)
#创建猫对象
tom = Cat()
# 可以使用 .属性名 利用赋值语句就可以了
tom.name = "Tom"
tom.eat()
tom.drink()
print(tom)
# 再创建一个猫对象
lazy_cat = Cat()
lazy_cat.name = "大懒猫"
lazy_cat.drink()
lazy_cat.eat()
print(lazy_cat)
... |
0783aa3975d1b51b720fef98f39cb2800ae1ef66 | adrija24/languages_learning | /Python/Day 4/To pop an element.py | 98 | 3.9375 | 4 | """To pop an element"""
num=[6,0,-6,-1,9]
n=int(input("Enter position: "))
num.pop(n-1)
print(num) |
2703b4ec05cf824b3a9ee3aa972e8f43547a8436 | liujwplayer/python | /c3.py | 774 | 3.828125 | 4 | import time
import datetime
#创建停车场对象
class Park(object):
pass
def printo(self):
self.start()
print('开始计时')
#当前线程休眠
time.sleep(2)
print('购物中')
self.end()
print('结束计时')
print('输出计费单')
self.money()
#费用计算
def money(self):
t... |
f3cc986b4c129cc5f741a3560bc022ba204b1880 | 2226171237/Algorithmpractice | /字节/反转链表 II.py | 1,865 | 3.78125 | 4 | '''
反转从位置 m 到 n 的链表。请使用一趟扫描完成反转。
说明:
1 ≤ m ≤ n ≤ 链表长度。
示例:
输入: 1->2->3->4->5->NULL, m = 2, n = 4
输出: 1->4->3->2->5->NULL
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/reverse-linked-list-ii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
'''
class ListNode(object):
def __init__(self, x):
self.val = x
s... |
0db0e6a29f4407c68f16cb885db6abb04cf2986e | talesritz/Learning-Python---Guanabara-classes | /Exercises - Module III/EX102 - Fatorial def() True.py | 1,316 | 4.28125 | 4 | #Crie um programa que tenha uma função fatorial() que receba dois parâmetros: o primeiro que indique o número a calcular e o outro chamado show, que será um valor lógico (opcional) indicando se será mostrado ou não na tela o processo de cálculo do fatorial.
def cabecalho(msg):
print('='*40)
print('{:^40}' .fo... |
c2bb7f1942fdaa30152dac04c6302895ff15b844 | brineryte/ztm_python | /practice_exercises/ex_password_checker.py | 231 | 3.546875 | 4 | from getpass import getpass
print('Login')
print()
user = input('Please enter user name')
password = getpass(prompt='Please enter password', stream=None)
print(f'{user}, your password {password} is {len(password)} letters long')
|
46d51048a78a4f9245d6adc018d6c1067dd47433 | hunter-cameron/Bioinformatics | /python/compare_two_lists.py | 3,290 | 3.640625 | 4 | #!/usr/bin/env python
import argparse
import sys
import os
description = """
Author: Hunter Cameron
Date: Oct 19, 2015
Description:
Small utility for comparing two lists. It outputs the elements that
are only present in one of the lists and elements that are present in
both. Allows each list of elements to be output... |
f2f85020abe494365e1b3732e28d3b732354a879 | venkatesh-vk/Project-eluer-Python | /1.Multiples of 3 and 5.py | 348 | 4.09375 | 4 | '''
If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9.
The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.
'''
#try using arthmetic progression
n=int(input("Enter"))
a=[]
for i in range(1,n+1):
if i%3==0 or i%5==0:
... |
51ef79a6c359b3efd74217546352bb03d1a56dfe | Melo15Zhang/python | /4-4/helloworld.py | 166 | 3.75 | 4 |
# -*- coding: utf-8 -*-
print("Hello", ",", "Python")
# print会在,后面自动加上一个空格
name = input("Please enter your name: \n")
print("hello,", name)
|
2abbb1dd6d30d7ddca433ac42ce20ad3c61d0652 | jonathanxqs/Leetcode_rhap | /64.py | 527 | 3.53125 | 4 | class Solution(object):
def reverseString(self, s):
"""
:type s: str
:rtype: str
"""
return s[::-1]
# #字符串的反转
# def reverse (s):
# rt = ''
# for i in range(len(s)-1, -1, -1):
# rt += s[i]
# return rt
# def reverse2 (s):
# li = list(s)
# li.reverse()
# rt = "".join... |
bd83846e565390d79da82a00ee598bef52b81aaf | chasecolford/Leetcode | /problems/1160.py | 1,259 | 3.953125 | 4 | """
You are given an array of strings words and a string chars.
A string is good if it can be formed by characters from chars (each character can only be used once).
Return the sum of lengths of all good strings in words.
Example 1:
Input: words = ["cat","bt","hat","tree"], chars = "atach"
Output: 6
Explanation:... |
6c5edbce0eec8779c5639d4064575722bf201734 | varunmuriyanat/programming_machinelearning | /code/12_classifiers/plot_perceptron_model.py | 2,289 | 3.84375 | 4 | # Plot the model function of a perceptron on a dataset with two input variables.
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm
from mpl_toolkits.mplot3d import Axes3D
import seaborn as sns
sns.set()
def sigmoid(z):
return 1 / (1 + np.exp(-z))
def forward(X, w):
weighted_sum =... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.