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 |
|---|---|---|---|---|---|---|
a6c8cfd4cb0d605e9b12cce52bcd8a33d75cbdcd | ItsMeVArun5/Hakerrank | /problem_solving/plusMinus.py | 685 | 3.9375 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
# Complete the plusMinus function below.
def plusMinus(arr):
positive_elements = 0
negative_elements = 0
zero_elements = 0
for x in arr:
if x > 0:
positive_elements += 1
elif x == 0:
zero... |
e2672d51c9bc1818b6558b0867ab7666c21f4b49 | Youngfellows/HPyBaseCode | /codes/day02/1.py | 304 | 3.5 | 4 | #1. 提示并获取用户名
userName = input("请输入用户名:")
#2. 提示并获取密码
passwd = input("请输入密码:")
#3. 判断用户名和密码都相等,根据判断的结果显示信息
if userName=="dong" and passwd=="123456":
print("登陆成功,欢迎进入xxxx系统")
|
7cc40c7abe268563a860421b46d4058e52bd9315 | luilui163/PythonBook | /Python-03数据处理/Reference/code/chp7-cleanup-数据清洗1.0/import_csv_找出需要清洗的数据.py | 3,344 | 3.78125 | 4 | #-*-coding:utf-8_-*-
"""
Description:
清洗数据之替换标题:将mn-headers.csv中标题与调查数据一一对应,这样就有了可读性较强的问题和答案
拓展:
①:Python 列表生成式的格式:
[func(x) for x in iter_x]
等效为
new_list = []
for x in iter_x:
new_list.append(func(x))
"""
from csv import DictReader
data_rdr = DictReader(open('../../data/unicef/mn.csv', 'rb'))
header_rdr = Di... |
e82ede17a708cfb6c2b45e98ed0245673d11f634 | Dranixia/TTT | /game.py | 553 | 3.953125 | 4 | """
Butynets' Danylo
Task 3 Lab 13 UCU
Python 3.8
"""
from board import Board
def play():
"""
Simulate Tic Tac Toe.
:return: str
"""
game = Board()
while True:
game.human()
state = game.check_win("o")
if state:
return state
game.computer()
... |
e8fd812f687cd3857b67a4677a6652a60a3042a9 | mayelespino/code | /EXERCISES/DynamicProgramming/Python/gridTravelTab.py | 566 | 3.734375 | 4 | #
#
#
def gridTravel(rows, cols):
table = [[0 for i in range(cols+1)] for j in range(rows+1)]
table[1][1] = 1
for i in range(rows):
for j in range(cols):
table[i][j+1] += table[i][j]
table[i+1][j] += table[i][j]
table[i+1][cols] += table[i][cols]
for j in range(... |
60dc024310defe5fb2ea8d12ecd91965d9151681 | mayelespino/code | /LEARN/python/functional-programming-tools/functional-programming.py | 538 | 4.15625 | 4 | #!/usr/bin/python
#https://docs.python.org/2/tutorial/datastructures.html
#---- filter ----
print "---- filter ----"
def isEven(x): return x % 2 == 0
myList = (filter(isEven, range(1,20)))
for N in myList:
print N
#---- map ----
print "---- map ----"
seq1 = range(1,10)
seq2 = range(101,110)
def addThem... |
5493b5abb8eeda5182d9d6cff4571f5c5d18469d | mayelespino/code | /LEARN/python/elevator2/elevator2.py | 1,670 | 3.75 | 4 | from multiprocessing import Pool
import sys
def f(x):
elevator_number, current_floor, requested_floor = x
if current_floor <= 0 or requested_floor <= 0:
print("Invalid floor.")
sys.stdout.flush()
return(elevator_number, current_floor, requested_floor)
elif current_floor == reques... |
23ca47392ab160cca4022919b61fd19029b6b99b | mayelespino/code | /DATASTRUCTURES/python-binary-tree/binaryTree.py | 1,274 | 4.03125 | 4 |
class node:
def __init__(self, data):
self.left = None
self.right = None
self.data = data
def add(self, data):
if data < self.data:
if self.left is None:
self.left = node(data)
else:
self.left.add(data)
else:
... |
44fdde6a86c68721203312b2c696e8d8f1261b33 | mayelespino/code | /LEARN/python/countTheWords/fileSpliter.py | 903 | 4.0625 | 4 | """
Splits a text file in to words conaining 250 words each.
Removes none alphabet characters.
Takes only one parameter, the name of the file to split.
Author: Mayel Espino.
Jul 22,2017
"""
import sys
import re
if len(sys.argv) != 2 :
print("usage: to split")
sys.exit(1)
else:
file = sys.argv[1]
with ope... |
621af16811b653b2b6d2664fbcf94734f420a170 | mayelespino/code | /EXERCISES/DynamicProgramming/Python/fibTab.py | 317 | 3.828125 | 4 | #
# Dynamic solution to Fibunacci series, using tables
#
def fib(num):
table = [0] * (num + 1)
table[1] = 1
for i in range(2, num + 1):
table[i] = table[i-1] + table[i-2]
return table[num]
if __name__ == "__main__":
print(fib(6))
print(fib(7))
print(fib(8))
print(fib(50)) |
f533bf49fc9e1131c57ec2bc73efa5eedb07ce51 | mayelespino/code | /LEARN/python/graph-data-structure/graph1.py | 3,327 | 3.671875 | 4 | #!/usr/local/bin/python3
from random import randint
graph = {}
def add_node(node, g, *edges):
"""
:param node: the starting point
:param g: The dictionary which contains it all.
:param edges: Something like 'ab','bc'....
:return: None
"""
if node not in g:
vertices = []
exi... |
8a9c06197ace906c3c11090b5c0396def91b541d | mayelespino/code | /LEARN/python/parse-and-add-ints/parse-and-add-ints.py | 607 | 3.921875 | 4 | #!/usr/local/bin/python3
"""
partse numbers out of a given string and
"""
import re
def parse_and_sum_ints(string):
numbers = re.split("\D+", string)
total = 0
for number in numbers:
if number == '':
continue
total += int(number)
print(number,)
print("-----")
ret... |
08693ca174d12eff737cc6a467d1159652787a31 | astralblack/Calculator | /calc.py | 1,262 | 4.5 | 4 | # Astral's Calcultor
# Date: 9.27.18
# Menu
print("Hello welcome to my calculator!\n")
print("1: Addition")
print("2: Subtraction")
print("3: Multiplication")
print("4: Division\n")
# Functions
def addition():
num1 = int(input ("What is the first number?"))
num2 = int(input ("What is the second ... |
20ad22f4d17ceabb7db074c9adf03919cc20ab45 | shehuabu/pythonforbeginer | /login1.py | 5,701 | 3.921875 | 4 | # lecturer Management System
"""
Fields :- ['ID', 'First Name', 'Last Name','Email', 'Phone', 'Course']
1. Add New lecturer
2. View lecturer
3. Search lecturer
4. Update lecturer
5. Delete lecturer
6. Quit
"""
import csv
# Define global variables
lecturer_fields = ['ID', 'First Name', 'Last Name','Email... |
d2889eede15ac96bd172d021e70a9dd1865fc12c | sandeepkp07/python | /basics/permutation.py | 300 | 3.921875 | 4 | import sys
def permutation(x, y):
if len(x)==len(y):
c= sorted(x)
d= sorted(y)
if c==d:
print "true\n"
else:
print "false\n"
a = raw_input("enter first string\t")
b = raw_input("enter second string\t")
print permutation(a,b)
if __name__=="__permutation__":
permutation(a,b)
|
16ac536cb6b4455c8747441d03ca72208552dbd3 | sandeepkp07/python | /basics/permtnlist.py | 404 | 3.53125 | 4 | z=[]
import sys
def perms(x, y):
for f in y:
if len(f)==len(x):
c=sorted(f)
d=sorted(x)
if c==d:
z.append(f)
return z
a=raw_input("enter the initial string\t")
n=int(input("number of strings to be checked\t"))
b=[0 for i in range(n)]
for i in range(n):
b[i]=raw_input("enter t... |
e32010b220a5bc045da60dd26df2e4907cc24979 | jerryliu688/test_py | /algorithm/string/reverseWords.py | 222 | 3.9375 | 4 | def reverseWords(s):
l=s.split()
print(l)
print(l[::-1])
return " ".join(s.split()[::-1])
if __name__ == "__main__":
print(reverseWords("the sky is blue "))
s="the sky is blue"
print(s[::-1])
|
7577da415dd6d102bde498ea1f34f59b44cd056a | jerryliu688/test_py | /algorithm/search/linear.py | 257 | 3.859375 | 4 | def linearSearchUnsorted(arr, value):
i = 0
size = len(arr)
while i < size:
if value == arr[i]:
return True
i += 1
return False
if __name__ == '__main__':
a = linearSearchUnsorted([1, 2, 3], 3)
print(a)
|
9993b385b9723b079d775b5ba565c2cddb7de8a4 | jerryliu688/test_py | /algorithm/list/linkedlist.py | 606 | 3.9375 | 4 | from algorithm.list.Node import *
class LinkedList:
def __init__(self):
self.head = None
def addTail(self, v):
newnode = Node(v)
if (self.head == None):
self.head = newnode
else:
curr = self.head
while (curr.next != None):
cu... |
39f13545b456ef8f1cc85b94e2f5ec7ef8d29d34 | jerryliu688/test_py | /algorithm/common/permutation.py | 1,018 | 3.9375 | 4 | def permutation(result, str, list):
"""
取一个数组的全排列
list:为输入列表
str:传空字符串
result: 为结果列表
"""
if len(list) == 1:
result.append(str + "," + list[0])
else:
for temp_str in list:
temp_list = list[:]
temp_list.remove(temp_str)
... |
a74e8692f0c5fe0e7331eacfbc5e3ed0ad338e5c | jerryliu688/test_py | /algorithm/array/RotateArray.py | 327 | 3.6875 | 4 | def roate(arr, start, end):
while (start < end):
arr[start], arr[end] = arr[end], arr[start]
start += 1
end -= 1
if __name__ == '__main__':
arr = [1, 2, 3, 4, 5, 6, 7]
k = 2
n = len(arr)
roate(arr, 0, n - k - 1)
roate(arr, n - k, n - 1)
roate(arr, 0, n - 1)
prin... |
801bfde8a50b2a008f8bc760015caf0d2825c138 | carlosrmd/Setlan | /sl_symtab.py | 3,410 | 3.5 | 4 | # -*- coding: utf-8 -*-
# # # # # # # # # # # # # # # # # # # # # # # #
# TRADUCTORES E INTERPRETADORES CI3725 #
# Tercera entrega del proyecto. #
# Definicion de la Tabla de Simbolos #
# Autores: Carlos Martínez - 11-10584 #
# Christian Teixeira - 11-11016 #
# # # # # # # # # # # #... |
50858a7f7e434c88e372c9b47c3ca64376a8b377 | Niteesha97/CS5590PythonDeepLearning | /icp 3/source/a.py | 1,212 | 3.921875 | 4 | class Employee:
empCount = 0
tsal = 0
avgsal = 0
def __init__(self, name, family, salary, department):
self.name = name
self.family = family
self.salary = salary
self.department = department
Employee.empCount += 1
Employee.tsal += int(salary)
def ave... |
9ec86ad4537048e1f2c8725bd1934ffaaf7e8b89 | kjagoo/Fizzbuzz | /car.py | 1,057 | 3.6875 | 4 | class Car(object):
num_of_doors=4
def __init__(self,name='General',model='GM',car_type='saloon',speed=0):
self.name=name
self.model=model
self.car_type=car_type
self.speed=speed
self.num_of_wheels=4
if name == "Pors... |
6873b522169569c7e04a6e39c065fdab343f6405 | Sabdix/Python-Tutorials | /Dictionaries.py | 465 | 4.25 | 4 | # A dictionary is a collection which is unordered, changeable and indexed.
thisDict = {
"apple": "green",
"bannana": "yellow",
"cherry": "red"
}
print(thisDict)
#Changing elements
thisDict["apple"] = "red"
print(thisDict)
#Create dictionary with method
thisdict = dict(apple="green", bannana="yellow", che... |
abbc2b40c22b26f2c2305a5b69b91cb8ccb63b9a | Sabdix/Python-Tutorials | /Json.py | 1,302 | 4.4375 | 4 | # importing JSON
import json
# If you have a JSON string, you can parse it to convert it in to a dictionary
# some JSON:
x = '{ "name":"John", "age":30, "city":"New York"}'
# parse x:
y = json.loads(x)
# the result is a Python dictionary:
print(y["age"])
#If you have a Python object, you can convert it into a JSON... |
5e44a8c1f6fe05525aacd26f0f03e5d37114476c | JuanSch/ejemplo_python | /Ejercicio 7 PRACTICA 2.py | 244 | 4.125 | 4 | cadena = input('Ingrese un string ')
cadenaInvertida = cadena[::-1] #invertimos la cadena
if (cadena == cadenaInvertida):
print('la palabra ingresada es palindrome')
else:
print('La palabra ingrtesada no es palindrome') |
bb985c5810aafd2798063e6bacdb466304e009eb | RbertoVil/generate-possible-combinations | /src/python3/generate.py | 1,804 | 4.0625 | 4 | import random
def numberSentences():
#This function ask to the user the number of sentences to use
while True:
try:
numberSent = int(input('Pls enter the number of sentences that you\'ll working on: '))
break
except ValueError:
print("pls enter a integer")... |
82a67d4a9ccaf8ff36bdd8a2e9d00961f4d81e8c | ADJet1437/Algorithms | /python/reverse_string_tree.py | 1,008 | 3.828125 | 4 |
a = "abcdefghijklmn"
class Node():
def __init__(self, x):
self.value = x
self.child = None
class TreeObject():
def __init__(self):
self.root = None
def insert(self, node):
node = Node(node)
if self.root is None:
self.root = node
else:
... |
0a1ff344ad23fd48f250ffdaa1d55df8919ac5b9 | vinay-iyengar/Bootcamp-Projects | /demo1.py | 350 | 3.84375 | 4 | x=[]
y=[]
for i in range(0,4):
name=input("Enter name")
usn=int(input("Enter Usn"))
x.append(name)
y.append(usn)
print(x)
print(y)
dictionary = dict(zip(y, x))
print(dictionary)
print("\n")
a=[]
n=int(input("Enter the total no of words"))
for i in range(0,n):
word=input("Enter the list words")
... |
b4f91ac8312e99876e34a282487f6e7c659b7d18 | sangeetjena/datascience-python | /Dtastructure&Algo/Tree/BinarySerchTree.py | 895 | 3.984375 | 4 | class node:
def __init__(self,value):
self.value=value
self.left=None
self.right=None
def insert_to_tree(self,head,node):
if (head.value>node.value):
if (head.left==None):
head.left=node
else:
self.insert_to_tree(head.left,n... |
fe31756b42314a01b1bb6dab60a2f91edb65c9e5 | sangeetjena/datascience-python | /hacker_rank/data_structure/sparce_array.py | 621 | 3.8125 | 4 | """There is a collection of input strings and a collection of query strings. For each query string, determine how many times it occurs in the list of input strings.
For example, given input and , we find instances of ', of '' and of ''. For each query, we add an element to our return array, ."""
strings = ['abc'... |
4e55b12d1513cb0784894c841445e77fe864381c | sangeetjena/datascience-python | /Dtastructure&Algo/sort/bubble_sort.py | 606 | 3.796875 | 4 | def hipify(value,n,i):
largest=i
l=2*i+1
r=2*i+2
if l<=n and arr[i]<arr[l]:
largest=l
if r<=n and arr[largest]<arr[r]:
largest=r
if i!=largest:
value[largest],value[i]=value[i],value[largest]
print(largest, i)
print(value)
hipify(value,n,largest)
... |
8ff072c81aaa660f8a1c6b30ea55a319ac420d80 | sangeetjena/datascience-python | /Dtastructure&Algo/algo/travel_to_moon.py | 597 | 3.609375 | 4 | def journeyToMoon(n, astronaut):
x=1
for i in range(0,len(astronaut)):
for y in astronaut[i]:
for z in range(i+1,len(astronaut)):
print(astronaut[z])
print(astronaut)
print(" ",y)
if y in astronaut[z]:
print... |
bbfa000ad67f734df09ed03e70d85119123cfef0 | sangeetjena/datascience-python | /Dtastructure&Algo/algo/water_supply.py | 826 | 4.1875 | 4 | """Given N cities that are connected using N-1 roads. Between Cities [i, i+1], there exists an edge for all i from 1 to N-1.
The task is to set up a connection for water supply. Set the water supply in one city and water gets transported from it to other cities using road transport. Certain cities are blocked which mea... |
69dd6757e7b627153e5cc693962cbdfddf6c1b5e | COSJIE/meachine-learning | /04_函数/hm_07_改造函数.py | 362 | 3.6875 | 4 | def sum_2_num(num1, num2):
""" 对两个数求和"""
# 返回结果
return num1 + num2 #回车后直接顶格,函数结束
# # return表示返回.后续的代码都不会被执行
num = 100 #不执行此句
# 调用函数,并使用result变量接收计算结果
# 返回值
result = sum_2_num(10, 20)
print("计算结果为:%d" % result)
|
31f5356fbb1ea5ff2a95bd742f1a3c4efa0b6be0 | COSJIE/meachine-learning | /05_高级数据类型/hm_08_格式化字符串.py | 334 | 3.734375 | 4 | info_tuple = ("小明", 18, 1.85)
# 格式化字符串后面的()本质上是元组
# print("%s的年龄是%d岁,身高是%.2f米" % ("小明", 18, 1.85))
print("%s的年龄是%d岁,身高是%.2f米" % info_tuple)
info_str = "%s的年龄是%d岁,身高是%.2f米" % info_tuple
# <class 'str'>
print(type(info_str))
print(info_str)
|
6e363f232d0f0345d446bcfbf7a7b9a649ec6470 | COSJIE/meachine-learning | /04_函数/hm_09_函数嵌套调--打印分隔线.py | 426 | 4.25 | 4 | # 定义一个print_line函数打印 * 组成的一条分隔线
# def print_line():
# print("*" * 50)
# print_line()
# 定义一个print_line函数打印 任意字符 组成的一条分隔线
# def print_line(char):
# print(char * 50)
# print_line("-")
# 定义一个print_line函数打印 任意字符 任意次数的组成的一条分隔线
def print_line(char,times):
print(char * times)
print_line("-", 10) |
455ceda6f07ef72fad474d1e8fc8c98b031078ca | COSJIE/meachine-learning | /02_分支/hm_03_逻辑运算演练.py | 225 | 3.828125 | 4 | # 练习1
# 定义一个整数变量age,判断年龄是否正确
age = 100
# 要求年龄在0-120岁之间
"""
age >=0 and age <= 120
"""
if age >= 0 and age <= 120:
print("年龄正确")
else:
print("年龄错误")
|
11b6270e0cc2a0267847d8095d43484716c27332 | COSJIE/meachine-learning | /03_循环/hm_01_重复执行.py | 403 | 4.09375 | 4 | # 打印5遍 Hello Python
# 1.定义一个整数变量,记录循环次数
i = 1
# 2.开始循环
while i <= 5:
# <1>希望在执行内执行的代码
print("Hello Python")
# <2>处理计算器(i = i + 1)
i += 1
# 3. 观察一下,循环结束后,计算器i的数值 是多少
# 循环结束后,之前定义的计数器条件的数值是依旧存在的
print("循环结束后,i = %d" % i) |
a776355dd87ff80e58efdd61abb33ceaea269c4b | Mitrajit/Student-grade-prediction | /predict-grade.py | 2,082 | 3.8125 | 4 | # To add a new cell, type '# %%'
# To add a new markdown cell, type '# %% [markdown]'
# %% [markdown]
# <h1>Predicting final grade</h1>
# This code uses <b><i>Linear regression algorithm</i></b> to create a model using the student performance data set from UCI "https://archive.ics.uci.edu/ml/datasets/Student+Performanc... |
ae1afd27a72b8500a952eae6c0679bfee433cd3d | FredBotham/Computer-Science | /Currency Converter 1.1.py | 974 | 3.9375 | 4 | from time import sleep
import math
# Establishing dictionary of rates
rates = {"EUR": 0.9, "USD": 0.77, "JPY": 0.0074}
# Create function to calculate conversion
def convert(amount, currency):
total = amount / rates.get(currency.upper())
return round(total, 2)
print("{}\n Currency Converter v1.1 \n{}".format(... |
00503cb30615d01facc609ef894f0ee570717a96 | kajaltingare/Python | /Basics/verbing_op.py | 328 | 4.4375 | 4 | # Write a program to accept a string from user & perform verbing operation.
inp_stmt=input("Enter the statement: ")
if(len(inp_stmt)>=3):
if(inp_stmt.endswith("ing")):
print(inp_stmt[:-3]+'ly')
else:print(inp_stmt+'ing')
else:
print('Please enter verb atleast 3 or more number of characters in... |
58b6f4caa8b080662653399a75cff2afc9ff6691 | kajaltingare/Python | /Basics/Patterns/pattern6_LL.py | 334 | 4.125 | 4 | # Write a program to print LowerLeft side pattern of stars.
def Pattern6(n):
for i in range(1,n+1):
for _ in range(0,n-i+1):
print('*',end='')
print()
def main():
n = eval(input('Enter the no of rows want to print pattern: '))
Pattern6(n)
if __name__ == '__main__':... |
13d8afaee11157c961071f9060187f7656b2cd56 | kajaltingare/Python | /Basics/UsingFunc/replaceCharByNumCnt.py | 677 | 4.0625 | 4 | # Write a program to accept a string which has repetitive characters consecutively & optimize the storage space for it.
#Ex. 'aaabbcccdee' : a3b2c3d1e2
def replaceCharByNumCnt(inpString):
result = ""
i = 0
while(i<len(inpString)):
cnt = 1
ch = inpString[i]
while(i+1!= len(i... |
cc512ebdf7ea3c9089adb048233263543ee0d007 | kajaltingare/Python | /Basics/arithmatic.py | 517 | 3.921875 | 4 | # Arithmatic operations with free fall code using function
def myAdd(a,b):
return (a+b)
def mySub(a,b):
return (a-b)
def myMul(a,b):
return (a*b)
def myDiv(a,b):
return (a/b)
print("Free fall at begin!")
def main():
a,b=eval(input("Enter the no.s: "))
print("Addition: ",myAdd(a,b))... |
c0af2569858fa4b0d2e8d8c2246d7948a8d97841 | kajaltingare/Python | /Basics/UsingFunc/fibboSeriesWithUpperLimit.py | 433 | 4.21875 | 4 | # Write a program to print fibonacci series with given upper limit, starting from 1.
def fiboSeries(upperLmt):
a,b=1,1
print(a,b,end='')
#for i in range(1,upperLmt):
while((a+b)<=upperLmt):
c=a+b
print(' %d'%c,end='')
a=b
b=c
def main():
upperLmt = eval(i... |
7e1f112c039a4edb73d9e98c3ec920392e4c5c07 | kajaltingare/Python | /Basics/UsingFunc/countOfConsonents.py | 489 | 3.8125 | 4 | # Write a program to accept a string from user & print count of consonents in it.
def cntConsonent(inpString):
count = 0
for i in inpString:
if(i in "aeiouAEIOU"):
continue
else:
count+=1
return count
def main():
inpString = eval(input('Enter... |
9bab0f1e2406e218185f9b56fdb195db7a5185e6 | kajaltingare/Python | /Basics/if_else.py | 252 | 4.0625 | 4 | #Write a program to accept no of donuts as an input, if >10 print many else print it's quantity.
inp_donut = eval(input("Enter the no of donuts: "))
if(inp_donut>10):
print("No. of donuts: Many")
else:print("No. of donuts are %d"%inp_donut)
|
9b4de2ccf3539b1f714c3855bff8989f19f433fa | kajaltingare/Python | /Basics/min_of_3.py | 260 | 4.21875 | 4 | # Write a program to accept three numbers from user & find minimum of them.
n1,n2,n3=eval(input("Enter the 3 no.s: "))
if(n1<n2 and n1<n3):print("{0} is minimum".format(n1))
elif(n2<n1 and n2<n3):print('%d is minimum.'%n2)
else:print('%d is minimum.'%n3)
|
831023701ff1b841124a34e1eebb20f05489cc6a | kajaltingare/Python | /Basics/UsingFunc/isDivisibleByEight.py | 481 | 4.34375 | 4 | # Write a program to accept a no from user & check if it is divisible by 8 without using arithmatic operators.
def isDivisibleByEight(num):
if(num&7==0):
return True
else:
return False
def main():
num = eval(input('Enter the number: '))
result = isDivisibleByEight(num)
i... |
a8c06bb0934f021d06a854bba1861b83d31bd4e1 | kajaltingare/Python | /Basics/basic_str_indexing.py | 676 | 4.65625 | 5 | #String-Immutable container=>some basics about string.
name="kajal tingre"
print("you entered name as: ",name)
#'kajal tingre'
print("Accessing 3rd char in the string(name[2]): ",name[2])
print("2nd including to 5th excluding sub-string(name[2:5]): ",name[2:5])
print("Printing alternate char from 1st position(nam... |
c7ccaa99c7ea5c5b9141e22dbf4ffdf302648d39 | edgedown/alta17active | /notebook/evaluation.py | 5,261 | 3.515625 | 4 | from dataset import Dataset
from sklearn.metrics import f1_score, make_scorer
import itertools
import matplotlib.pyplot as plt
import numpy as np
import random
f1_scorer = make_scorer(f1_score)
def plot_learning_curve(train_sizes, train_scores, test_scores):
plt.clf()
plt.figure()
plt.xlabel("N training... |
7400c3ea5b9bbdffc633bd22c137863e269cfdcf | amaan28/Assignment2 | /Assignment2/codes/Assignment2.py | 527 | 3.828125 | 4 | import random
n=500000
Toss_odd=0 #Number of experiments ended in odd number of tosses.
for i in range(n) :
C=1 #Variable that keeps account of the of the outcome of each toss. 0->HEADS and 1->tails.
Toss=0 #Number of tosses in each experiment.
while C!=0 :
C=random.randint(0,1)
... |
a7161cda64a24da7444da7ee0b74416c09133c0a | ekeilty17/Personal-Projects-In-Python | /Data_Structures/Graph/Old/test.py | 745 | 3.703125 | 4 | from graph import *
from traversal import *
from path import *
from TopOrdering import *
from Dijkstra import *
G = graph()
G.addVertex(5)
G.addEdge(0,1,True,1)
G.addEdge(0,2,True,1)
G.addEdge(0,3,True,1)
G.addEdge(0,4,True,1)
G.addEdge(1,3,True,1)
G.addEdge(2,1,True,1)
G.addEdge(2,4,True,1)
G.addEdge(3,4,True,1)
G.ad... |
56c80af13fb3f477cc756ebfb3e9f9034c212093 | ekeilty17/Personal-Projects-In-Python | /Data_Structures/binary_search_tree.py | 6,504 | 4.15625 | 4 | from binary_tree import BinaryTree
# TODO: make a custom compare function so that you can call add() to a tuple or a list (add a variable unpack=True to add_in_order)
class BinarySearchTree(BinaryTree):
"""
Implements a binary search tree where the user no longer has control over the configuration of nodes.
... |
28f5fcbe7826c0f862b90bea093e5403d5ba75f9 | ekeilty17/Personal-Projects-In-Python | /Sorting/bubble_sort.py | 993 | 3.890625 | 4 | from sorter import Sorter
class BubbleSort(Sorter):
name = "Bubble Sort"
def __init__(self):
super(BubbleSort, self).__init__()
def sort(self, L):
for i in range(len(L)-1):
for j in range(1, len(L)-i):
if L[j-1] > L[j]:
L[j-1], L[j] = L... |
6538809ca8184e122b01e91044238dd29c4d393b | ekeilty17/Personal-Projects-In-Python | /SCP/greedyCost.py | 1,739 | 3.984375 | 4 |
# Algorithm is trying to balance sets covered and cost of using the set
# Essentially minimizes this quanitity
# Cost(E) / | diff(E, s) |
def greedyCost(U, S, coverage):
# U = universal set
# S = set of subsets
# coverage = percent of U that we want to over with sets in S
u = U.copy()
# u is... |
c2cc8a6c3e699641b2edecee5969456d7e6b7af4 | ekeilty17/Personal-Projects-In-Python | /Data_Structures/Graph/Old/traversal.py | 2,481 | 3.890625 | 4 | class queue:
def __init__(self):
self.store = []
#had to rename the queue functions
def push(self, val):
self.store += [val]
#so that it works generally
def pop(self):
if self.store == []:
return False
r = self.store[0]
self.store = self.store[1:... |
b44acc22513157267bffcba62e948abc1385162c | ekeilty17/Personal-Projects-In-Python | /Math/perfectsquare.py | 2,070 | 3.921875 | 4 | import math
from decimal import *
#We can start using properties of sqrts to eliminate some
#For example: sqrts always end in [0, 1, 4, 5, 6, 9]
#and the digital sum of a sqrt is always [1, 4, 7, 9]
def getDigits(n):
out = []
while n != 0:
out = [n%10] + out
n /= 10
return out
def DigitalS... |
ea6b2f0acd490c5f1ca13d6c316fd8e584ed4cd7 | ekeilty17/Personal-Projects-In-Python | /Useful/WritingToConsole/progress_bar.py | 783 | 3.609375 | 4 | from sys import stdout
from time import sleep
# Simple example of replacing a line
stdout.write("This will be replaced: HELLO")
stdout.flush()
sleep(1)
stdout.write("\rThis will be replaced: BYE \n")
stdout.flush()
# A bit more complex but can be very useful
def progressBar(name, value, endvalue=100, bar_length = 50... |
55681e3cd66095da06a3d1758ff35a3855fb93c6 | ekeilty17/Personal-Projects-In-Python | /Math/factors.py | 524 | 3.5625 | 4 | def factors(n):
if n == 0:
return []
if n < 0:
n *= -1
if n == 1:
return [1]
f = [1,n]
for i in range(2,n//2+1):
if n % i == 0:
f += [i]
return sorted(f)
def num_factors(n):
f = 1
counter = 0
while n % 2 == 0:
counter += 1
... |
6c2f4e89767fb3393bedd8c051d193800bb2af0e | ekeilty17/Personal-Projects-In-Python | /Data_Structures/ConvertGtoB/b_tree.py | 1,323 | 3.90625 | 4 | class binary_tree:
def __init__(self,val):
self.val = val
self.left = None
self.right = None
def AddLeft(self,B):
self.left = B
return True
def AddRight(self,B):
self.right = B
return True
def Add_in_order(self, val):
# Error case
... |
bdbe65504050673005000c57e6a7d11696d11356 | ekeilty17/Personal-Projects-In-Python | /Useful/encrypt.py | 446 | 3.625 | 4 | def encrypt(s, key):
out = ''
for i in range(0,len(s),len(key)):
for j in range(0,len(key)):
if i+j < len(s):
out += chr( ord(s[i+j]) ^ ord(key[j]) )
return out
S = "Hello, how are you. I am coding in Pythong and stuff"
print "Original:"
print S
print
key = "wowww"
S_n... |
b8996d07573b6a16e36634092dbfb5ea16a27d69 | ekeilty17/Personal-Projects-In-Python | /Math/gcd.py | 191 | 3.703125 | 4 | def gcd(a, b):
#accounting for this annoying case
if b > a:
a, b = b, a
#gcd(a,b) = gcd(b,a%b) --> Euclid's Algorithm
while b != 0:
a, b = b, a%b
return a |
0c937fe3bbe0f39686f89d4dc4bba934baff2f55 | ekeilty17/Personal-Projects-In-Python | /Math/convert_to_binary.py | 266 | 3.78125 | 4 | def binary_iter(n):
B = 0
t = 1
while n != 0:
B = B + t*(n%2)
t *= 10
n //= 2
return B
def binary_rec(n):
if n == 0:
return 0
return n%2 + 10*binary_rec(n//2)
print binary_iter(57)
print
print binary_rec(57)
|
0d099c9407f64f115d642fd880e820a45b506be1 | lindaandiyani/Tugas-Modul-Satu-JCDS | /kalkulatorSederhana.py | 427 | 4.03125 | 4 | def calc():
angka1 = int(input('masukkan angka pertama : '))
arit = input('masukkan operator aritmatika :')
angka2= int(input('masukkan angka kedua : '))
if arit == '/':
print(angka1/angka2 )
elif arit == '+':
print(angka1+angka2)
elif arit == '-':
print(angka1-angka2)
... |
7efe4f407e0750c5571ef8c208779dec41294ec7 | whoji/training-ground | /torch/official_tutorial/part6_save_load_model.py | 4,302 | 4 | 4 | # https://pytorch.org/tutorials/beginner/saving_loading_models.html
'''
torch.save: Saves a serialized object to disk. This function uses Python’s pickle utility for serialization. Models, tensors, and dictionaries of all kinds of objects can be saved using this function.
torch.load: Uses pickle’s unpickling facilitie... |
7e8e45ee373be5edef41fb645306687fb8b62910 | 1amG4bor/PythonPractice | /bubble_sort.py | 426 | 3.9375 | 4 | # Bubble-sort
def __bubble_sort(data):
counter = None
while counter !=0:
counter = 0
for i in range (0, len(data)-1):
if data[i] > data[i + 1]:
temp = data[i]
data[i] = data[i + 1]
data[i + 1] = temp
counter +=1
retu... |
1d0054aa7c66f1e2a3f7d84d48ddb8cb26371023 | winterwindwang/MachineLearning | /chapter_01.py | 1,623 | 3.515625 | 4 | import numpy as np
from sklearn import preprocessing
data = np.array([[3, -1.5 , 2, -5.4], [0, 4, -0.3, 2.1], [1, 3.3, -1.9, -4.3]])
# 标记编码
# 定义一个标记编码器
label_encoder = preprocessing.LabelEncoder()
# 创建一些标记
input_classes = ['audi', 'ford', 'audi', 'toyota', 'ford', 'bwm']
# 标记编码
label_encoder.fit(input_classes)
print(... |
0283978e822d19259adec7481a5aa0e2a9139482 | MadlesSs/adventOfCode2020 | /src/day2/password_philosophy.py | 980 | 3.5625 | 4 | f = open('input.txt', 'r')
lines = f.readlines()
# part 1
correct = 0
for line in lines:
line = line.replace(" ", "")
firstHalf, password = line.split(':')
firstNum, secondNumAndChar = firstHalf.split('-')
char = secondNumAndChar[-1]
secondNum = secondNumAndChar[:-1]
counter = 0
for characte... |
2ccde51a423dbb3d45cebc22c638a7fb4cdfd699 | asdhamidi/DSA | /Tree/binary_search_tree.py | 6,283 | 4.21875 | 4 | """
Code for a Binary Search Tree.
"""
from simple_tree import Tree, Node
class BST(Tree):
"""
A class to represent a Tree.
...
Attributes:
----------
root : Node
Points to the root Node.
Methods:
-------
search(root, data):
Method to search for an element in the tr... |
99dfadc802ad2a53cf80a747a71504445306f36b | asdhamidi/DSA | /Queue/postfix.py | 1,999 | 3.796875 | 4 | class Conversion:
def __init__(self):
self.top = -1
self.stack = []
self.output = []
self.result = []
self.precedence = {'+':1, '-':1, '*':2, '/':2, '^':3}
def is_empty(self):
return self.top == -1
def peek(self):
return self.stack[self.top]
def... |
52410a4f0b12e85bbc9cc83010b8fa891463c706 | amithKadasur/python-scraps | /python-scraps/classes.py | 1,170 | 4.0625 | 4 | '''class it out'''
class Car():
def __init__(self, name, manufacturer):
self.name = name
self.manufacturer = manufacturer
def get_details(self):
print('car name is ' + self.name + ' and manufacturer is ' + self.manufacturer)
my_car = Car('mustang', 'ford')
my_car.get_details()
clas... |
cb5db998be2582e1c84e0fe8337f5808ad1cac51 | ppyy-hub/bbbb | /py_ws/day2/作业 11.5.py | 1,189 | 3.71875 | 4 | # 1.统计
# 统计在一个队列中的数字,有多少个正数,多少个负数,如[1, 3, 5, 7, 0, -1, -9, -4, -5, 8]
list1=[1, 3, 5, 7, 0, -1, -9, -4, -5, 8]
a=[x for x in list1 if x>0]
print("正数的个数有:",len(a))
b=[y for y in list1 if y<0]
print("负数的个数有:",len(b))
# 2.字符串切片
# 字符串 "axbyczdj",如果得到结果“abcd”
a="axbyczdj"
print(a[::2])
# 3.字符串切割
# 已知一个字符串为“hello_world_”,... |
a5bfffaf30fdcd4af6c5d53a22f03bcce36f0b12 | kookminYeji/SW-Proj2-class1-3 | /Byeongjo/Byeongjo_week4/assignment4_factorial_combination_20171593.py | 263 | 4.03125 | 4 | def factorial(n) :
if n == 1 or n == 0:
return 1
else :
return n * factorial(n-1)
n = int(input("Enter n : "))
m = int(input("Enter m : "))
c = factorial(n)
d = factorial(m)
e = factorial(n-m)
print("C(",n,",",m,")" + "=", int(c/(d*e))) |
b1dcd5ceabb7908a338473c818a788bac1981ab3 | kookminYeji/SW-Proj2-class1-3 | /assigement5_20171579.py | 702 | 3.90625 | 4 | import time
def fibo(n):
if n <= 1 :
return n
else :
first, second = 1, 1
for i in range(n-1):
first, second = second, first+second
return first
def fibo_recursive(n):
if n <= 1 :
return n
else :
return fibo_recursive(n-1) + fibo_recursive(... |
461b61c0db5e9a8b5b29322601674432b94c133f | calleja/trading | /quantopianSeries/momo.py | 11,019 | 3.734375 | 4 |
# coding: utf-8
# # Momentum Strategies
# By Evgenia "Jenny" Nitishinskaya and Delaney Granizo-Mackenzie. Algorithms by David Edwards.
#
# Notebook released under the Creative Commons Attribution 4.0 License.
#
# ---
# Momentum trading refers to a general class of strategies which extrapolate from existing trends. ... |
baf5a5119c3e459ae5a4f72bb18accaccdd616c6 | tetsuzawa/research-tools | /pyresearch/modules/decorators.py | 822 | 3.5625 | 4 | import time
from functools import wraps
def stop_watch(func):
@wraps(func)
def wrapper(*args, **kwargs):
print("############### START ###############")
start = time.time()
result = func(*args, **kwargs)
elapsed_time = time.time() - start
print("############### END #... |
e0518a1c8079e3e47dcd93cf86dcec85f4db7a35 | paulsuh/AdventOfCode2020-code | /Day-09/XmasCipher2.py | 1,643 | 3.5 | 4 | #!/Users/plsuh/Projects/AdventOfCode2020-venv/bin/python
from sys import stdin
from itertools import combinations, accumulate
# read in asm code text
fullNumListInput = stdin.read().splitlines()
# transform into ints to avoid casting later
fullNumList = list(map( lambda x: int(x), fullNumListInput ))
window = 25
... |
d20cf77ba7db6585606e155c50a674beaaa36ba4 | xkingslayer/Python-Wage-Calculator | /test.py | 566 | 3.84375 | 4 | ####Pay Calculator####
hoursWorked = int(input('How many hours did you work this week?'))
hourlyPay = int(input('How much did you make per hour?'))
weeksPerMonth = 4
print(f'You made {hoursWorked*hourlyPay} this week.')
print(f"You'll make {hourlyPay*hoursWorked*weeksPerMonth} this month, great job!")
print(f'Please c... |
0e3f6374fc46e8e7fa6c9d03112b2328610884bd | softjech/Algorithm | /Max_subArray_kadane.py | 192 | 3.625 | 4 | def maxSubArray(nums):
a=nums[0]
m=nums[0]
for i in range(1,len(nums)):
a=max(nums[i]+a,nums[i])
if(m<a):
m=a
return m
|
6d3f92f7d567c474ff9549d282d17fdef889e6f2 | CloudGIT001/object-oriented-notes | /面向对象_v5.py | 1,442 | 3.9375 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:xieshengsen
"""
成员修饰符
私有:
只能类自己本身成员内部可以访问
共有:
pass
ps: 不到万不得已不要在外部强制访问私有成员,_类名__xxxx
"""
class Foo:
def __init__(self,name):
self.__name = name # 将name设置为私有普通字段
def f1(self):
print(self.__name)
obj = Foo("h... |
8c935192eba619062f11f3bc740589bd3ecf469c | Rahul2706/Python_Exercises | /ex4.py | 225 | 3.953125 | 4 | #WAP in python that takes minutes as input,
#and display the total number of hours and minutes
mins = int(input("Enter minutes"))
hours = mins/60
cal = hours , mins
print("total no. of hours and minutes:" , cal) |
c8edacfcf534226a096ebfdf22850fc7ca4547eb | ejsejda/PhD_thesis-Chapter_3 | /removeDuplicates.py | 3,866 | 4.09375 | 4 | #### REMOVING SEQUENCES REDUNDANCY #####
### This code was used in chapter 3 for removing ###
### PHI-base version 3.2 redundant sequences ###
########################################################
import sys
#class declaration with both attributes we need
class Fasta:
... |
d43d61120a13946bf8002fb6c819bd66861bb641 | juandavid9611/NumericalMethods | /ParcialNumerico/punto3c.py | 548 | 3.8125 | 4 | from math import exp, expm1, log
def f(x):
return x**4 - x - 1
def f1(x):
return x**4
def f2(x):
return x
def df(x):
return 4*(x**3) - 1
def newtonMethod(p0, TOL, maxIterations):
for i in range(0, maxIterations):
p = p0 - (f(p0)/df(p0))
if(abs(p - p0) < TOL):
print "... |
d6a69f03aef049d77d73a485d1165911538ea37a | jcolvert99/Numpy | /MyArrays2.py | 2,455 | 3.875 | 4 | import numpy as np
#ROWS - students / COLUMNS - each test
grades = np.array([[87,96,70],[100,87,90],[94,77,90],[100,81,82]])
#give you all the grades for student 1: [100,87,90]
student1 = grades[1]
# "row , column"
student0_test1 = grades[0,1]
# ":" represents sequential values and the upper bound is not including... |
13157e75bf616c5a481865ea21757ae84643b806 | CodeFreezers/DSA-GFG | /Maths/Computing Pow/Python/main.py | 262 | 3.96875 | 4 | #1
def power (x, n):
res = 1
for i in range(n):
res = res * x
return res
#2
def power(x, n):
if n == 0:
return 1
temp = power (x, int(n/2))
temp = temp * temp
if n % 2 == 0:
return temp
else:
return temp * x
print(power(5, 3))
|
6a15fe90cb5845b16e2700cf6b6a6d3fdecec245 | CodeFreezers/DSA-GFG | /Recursion/Palindrome/Python/main.py | 276 | 3.8125 | 4 | #1
def CheckPalindrome(s):
return helperCheck(s, 0, len(s) - 1)
def helperCheck(s, start, end):
if start >= end:
return True;
return (s[start] == s[end]) and helperCheck(s, start + 1, end - 1)
print(CheckPalindrome("abbcdba"))
print(CheckPalindrome("abbcbba"))
|
29e92473c08b995bffd3d4d18eabb942cbca82fc | gherbin/kilobots | /state.py | 273 | 3.578125 | 4 | from enum import Enum
class State(Enum):
"""
represents the state of a robot
"""
START = 'start'
WAIT_TO_MOVE = 'wait_to_move'
MOVE_WHILE_OUTSIDE = 'move_while_outside'
MOVE_WHILE_INSIDE = 'move_while_inside'
JOINED_SHAPE = 'joined_shape'
|
99f8941a47961762cc405e44775d9e999b12e6e6 | BAGABR1/repo-github | /task_3_3.py | 405 | 3.578125 | 4 | def thesaurus(*args):
names = {}
names_list = []
time_names = []
for i in args:
names_list.append(i[0])
names_list = set(names_list)
for i in names_list:
for k in args:
if i == k[0]:
time_names.append(k)
names[i] = time_names
time_names... |
84c0ac4d37d9f01d4be2c27d9fff4c58e846cfac | Ahemmetter/spielereien | /sudoku.py | 4,756 | 3.75 | 4 | import numpy as np
import time
import random as r
filename = "sudoku-task1.txt"
with open(filename, "r") as f:
"""Opens the text file and converts it to a numpy integer matrix. Prints puzzle."""
values = list(f.read().replace(" ", "").replace("\n", ""))
values = map(int, values) # ma... |
37b984192e711577f0704e988f01b641d2c439ad | Gab-km/papylon | /papylon/gen.py | 5,436 | 3.78125 | 4 | """Classes and functions to deal with generators."""
import random
import itertools
import bisect
class StopGeneration(StopIteration):
"""Signal the end from Gen.generate()."""
def __init__(self, trial_to_generate, *args, **kwargs):
StopIteration.__init__(self, *args, **kwargs)
self.trial_to_... |
d8a3d1a529fd1ead0131cc1c2783c941ea748645 | rexnsutton/Python-masterclass | /interpolation.py | 255 | 3.765625 | 4 | age = 24
print("My age is %d years" % age)
major = "years"
minor = "months"
print("My age is %d %s, %d %s" % (age, major, 6, minor))
print("PI is approx. %f" % (22 / 7))
print("John" + "Cleese")
days = "Mon, Tue, Wed, Thu, Fri, Sat, Sun"
print(days[::5]) |
bb77706354d7d998dbd3a8035f3593f27158a342 | IanRiceDev/Prime-Numbers | /sieve_of_eratosthenes_prime_test/prime1.py | 1,243 | 4 | 4 | import sys
number = input("Enter number: ")
if int(number) == 0:
print(number, "is not a prime number")
input("Ending program")
sys.exit()
elif int(number) == 1:
print(number, "is not a prime number")
input("Ending program")
sys.exit()
elif int(number) == 2:
print(number, "is a prime n... |
094559f9145b0d98920ed6960f275c0de68f0d48 | Ahed-bahri/Python | /squares.py | 250 | 4.25 | 4 | #print out the squares of the numbers 1-10.
numbers=[1,2,3,4,5,6,7,8,9,10]
for i in numbers:
print("the square of each number is : ", i**2)
#mattan strategy
for i in range(1,11):
print("the square of each number is : ", i**2)
|
2ec7441b006d13495eb6fca8719d436e3fcf4329 | RaquelPeralta/LearningPython | /TheLuckyGameR&D.py | 1,538 | 4.0625 | 4 | import random
def dice():
'''returns a random number 1-6'''
result = random.randint(1, 6)
return result
# class Player:
#
# def __init__(self, x, y):
# self.x = x
#
# def move(self, result, horizontal_move, vertical_move):
# self.x = x + result
map = [
[1, 0, 0, 0],
[0,... |
911586f14cd6afc6da4d0228143cca1784e50afd | slxndsay/CSC-280 | /lab5p23.py | 2,366 | 3.640625 | 4 | # Lab 5
# Problem 2 and 3
# Name: Sophia Lindsay
from lab5p1 import Student
# Problem 2: Subclass (Phd Students)
class Phd(Student):
def __init__(self, name, year, gpa, current_classes,
advisor, numberOfResearchPapers):
super().__init__(name, year, gpa, current_classes)
self.advisor = advi... |
5a8ffa6388ed804fdcb88503dd5f573c0f47b638 | AleksandrSolonov/bowling | /bowling.py | 703 | 3.5625 | 4 | class Player:
def __init__(self, name):
self.name = name
self.points = []
players = []
players_count = int(input("How many players?"))
for i in range(players_count):
players.append(Player(input("Input name player" +str(i+1))))
string = ''
for player in players :
print(player.name)
for player in players : ... |
4a657f6cd09195f450f288c77b65e1964042d0d1 | TestowanieAutomatyczneUG/laboratorium_14-marekpolom | /src/sample/fizzBuzz.py | 333 | 3.546875 | 4 | class FizzBuzz:
def game(num):
if not str(num).isnumeric():
return "ValueError"
if((int(num)%15) == 0):
return "FizzBuzz"
elif((int(num)%3) == 0):
return "Fizz"
elif((int(num)%5) == 0):
return "Buzz"
else:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.