blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
bc4d41e348d92f4f932e0dac299d6025e4fc2221 | dreamofwind1014/gloryroad | /练习题/2020.06.18练习题--赵华恬.py | 2,965 | 3.953125 | 4 | # 练习171:不区分大小写对包含多个字符串对象的列表进行排序,显示排序后的结果还需要显示大小写不变的原字符串
# l = ["Abc", "zhangsan", "gloryroad", "nanjing"]
# print(sorted(l))
# 练习172:一个数如果恰好等于它的因子之和,这个数就称为完数,
# 例如6的因子为1, 2, 3,而6 = 1 + 2 + 3,因此6是完数,
# 编程找出1000之内的所有完数,并按6 its factors are 1, 2, 3 这样的格式输出
# 遍历1000以内的数#用数自身遍历除以小于数自身的数,求约数,所有约数和等于数自身
# for i in range(1, 1... |
3af1f947862099145d100d986ad158586368d47b | thetrashprogrammer/StartingOutWPython-Chapter3 | /fat_and_carbs.py | 1,491 | 4.375 | 4 | # Programming Exercise 3.7 Calories from Fat and Carbohydrates
# May 3rd, 2010
# CS110
# Amanda L. Moen
# 7. Calories from Fat and Carbohydrates
# A nutritionist who works for a fitness club helps members by
# evaluating their diets. As part of her evaluation, she asks
# members for the number of fat grams and carbohy... |
35cf58ab0216092a7f64fa19a89acab686194db7 | pshenoki/PythonALg | /Orlov_Vadim_les_3/task_3_les_3.py | 1,350 | 4.03125 | 4 | """В массиве случайных целых чисел поменять местами минимальный и максимальный элементы. """
import random as r
SIZE = 10
MIN_ITEM = 0
MAX_ITEM = 100
array = [r.randint(MIN_ITEM, MAX_ITEM) for _ in range(SIZE)]
print(array)
if array[0] > array[1]:
spam_max, spam_min = array[0], array[1]
max_ind, min_ind = 0, ... |
69d3656cd6c33453c0d8b6d87947723af9eb3356 | pshenoki/PythonALg | /Orlov_Vadim_les_3/task_1_les_3.py | 609 | 3.953125 | 4 | """В диапазоне натуральных чисел от 2 до 99 определить,
сколько из них кратны каждому из чисел в диапазоне от 2 до 9"""
LEFT_BOARD_i = 2
RIGHT_BOARD_i = 99
LEFT_BOARD_j = 2
RIGHT_BOARD_j = 9
for j in range(LEFT_BOARD_j, RIGHT_BOARD_j + 1):
count = 0
for i in range(LEFT_BOARD_i, RIGHT_BOARD_i + 1):
if... |
78709068dc408fb29864ccc26c0898cfa3147211 | Mi-clouds/git_homework | /bankapp/exception_handling_task/savings_account.py | 2,477 | 3.6875 | 4 | from account import Account
from insufficient_funds_exception import InsufficientFunds
from max_number_withdrawals import MaxNumberOfWithdrawals
class SavingsAccount(Account):
def __init__(self, name, balance, interest_rate, withdrawal_num_limit, num_of_withdrawals):
Account.__init__(self, name, balance)
... |
ee4a430f250014f9f2bdc7edc69b02766cfb6388 | Mi-clouds/git_homework | /bankapp/client_script.py | 986 | 3.5625 | 4 | from employee import Employee
from customer import Customer
from exception_handling_task.savings_account import Savings_account
from current_account import Current_account
#Employee and Customer classes both inherit from Person class
#each greeting method is encapsulated in the relevant class
#Inheriting Employee from... |
acf7f4a2e51f1eca3b379ccbccd8aeabc333be27 | mooseman/moose_parse | /groupparser.py | 1,127 | 3.625 | 4 |
# groupparser.py
# This code counts the number of occurrences of each character-type
# in the input. It could be adapted to count the number of tokens
# as well.
# This code is released to the public domain.
# "Share and enjoy...." ;)
import string, itertools, curses, curses.ascii
def test(input... |
5838440bbbd4f0af0061cf519c4541d18f415b73 | brobusta/ctci | /python/chapter-4/MinimalTree.py | 635 | 3.546875 | 4 | class TreeNode(object):
def __init__(self, data = None, left = None, right = None):
self.data = data
self.left = left
self.right = right
def createMinimalBST(A):
N = len(A)
if N == 0:
return None
mid = N / 2
root = TreeNode(A[mid])
root.left = createMinimalBST(A[... |
cfec8d825f316ed4af01ff7cb8b3be8a4ab93b57 | brobusta/ctci | /python/chapter-4/CheckBalanced.py | 1,007 | 3.6875 | 4 | import sys
class TreeNode(object):
def __init__(self, data = None, left = None, right = None):
self.data = data
self.left = left
self.right = right
def __str__(self):
return str(self.data)
def CheckBalanced(root):
height, balanced = CalHeight(root)
print "height =",heig... |
7dcc48ffebb1ae534fa973cab9d70c77e7b7a610 | wade-sam/variables | /Second program.py | 245 | 4.15625 | 4 | #Sam Wade
#09/09/2014
#this is a vaiable that is storing th value entered by the user
first_name = input("please enter your first name: ")
print(first_name)
#this ouputs the name in the format"Hi Sam!"
print("Hi {0}!".format(first_name))
|
452252aeb474b5b4d684adc7263e04e636763405 | lianemeth/hackerrank | /twins.py | 554 | 3.640625 | 4 | def twins(lower_limit, upper_limit):
array = [True] * (upper_limit + 1)
array[0] = array[1] = False
for (i, isprime) in enumerate(array):
if isprime:
for n in xrange(i*i, len(array), i):
array[n] = False
count = 0
for i in range(lower_limit, len(array) - 2):
... |
0b93d92d1723d83b14f61a60e1ea87d61c2b7a2b | naichao/deeptest | /第二期/深圳--奶茶哥/快学Python3/task_date_time.py | 1,854 | 3.734375 | 4 |
from datetime import date, datetime,time
__author__ = u'奶茶哥'
if __name__ == '__main__':
# 获取今天的日期
today = date.today()
print('今天日期是:%s' % today)
# 把年月日分开年月日三部分获取,然后展示
print('今天日期是:%s %s %s' % (today.day,today.month,today.year))
# 获取星期几对于的序号
weekday_num = today.weekday()
print('今天wee... |
0713f2aa877dcdcad3ad4700fcb423c95cd27ab7 | naichao/deeptest | /第二期/深圳--奶茶哥/first_task/my_sort.py | 1,244 | 3.890625 | 4 | import random
class MySort:
def __init__(self,start,end,count):
'''
初始化
生成随机数,返回排序后的结果
start, end为限制随机数生成的范围
count为生成的随机数个数
'''
self.start = start
self.end = end
self.count = count
def __mysort__(self):
'''生成数据并排序'''
lis... |
662903f992e036d174c71e420cfbd07998ad79f3 | cameronabel/advent2020py | /day3/day3.py | 942 | 4.0625 | 4 | import sys
def part_one(array, over, down):
"""Returns the number of trees encountered in the given array at the given slope"""
trees = 0
col = 0
for line in array[down::down]:
col += over
if col >= len(line):
col -= len(line)
if line[col] == '#':
trees ... |
7af6bcfb8ae5eac8862f30e232755bbdcf122d34 | egallop/learn-arcade-work | /Lab 06 - Text Adventure/lab_06.py | 2,367 | 3.65625 | 4 | import arcade
total_score = 0
# Welcome statement
print("Welcome to the rock and roll pop culture Quiz")
# line break
print()
# question about REM
print ("Who wrote the song Losing my Religion in 1991? ")
print ("A) Judas Priest\n"
"B) Pantera\n"
"C) R.E.M.\n"
"D) Iron Maiden")
answer_REM = input... |
9cbc19445225bebe3b0a672cdd9779bea3e645f5 | MohammadMahdiOmid/Mathematical_Of_AI | /orthogonality/inner_product_features.py | 1,713 | 3.765625 | 4 | import math
import fractions
import matplotlib.pyplot as plt
import numpy as np
import sympy as sy
# computing x**T Ay
def lengthOfVector(x):
result = 0
sum = (x[0] ** 2) - (x[0] * x[1]) + (x[1] ** 2)
result = math.sqrt(sum)
print("result is:", result)
def orthogonal(x, y):
# dot product
mul... |
a91cbef788753abfacad5c3263fd87e3668a9f01 | ErikWhiting/precalhelp | /precalhelp.py | 698 | 3.984375 | 4 | import factor
import trigfunctions
import raddegree
def getFactors() :
print "enter number to be factored"
x = eval(raw_input("> "))
factor.Factor(x)
User_Prompt()
def getFunctions() :
trigfunctions.Find_Functions()
User_Prompt()
def Conversion() :
raddegree.Get_Answer()
User_Prompt()
def User_Prompt() :... |
911643de6eb6c03967499faa03e2c6efbbc2aefe | MrFunnyide/Study-Python | /Belajar/OperasiDanEkspresi/operasiBit.py | 433 | 3.5 | 4 | print(11 >> 1) # 11 = 1011 binner >> kekanan 1 jadi 101, 101 = 5 desimal ( right shift )
print(2 << 2) # 2 = 10 binner >> kekiri 2 jadi 1000 ( ditambahkan 0 ), 1000 = 8 desimal ( left shift )
print(5 & 3) # 5 = 101 dan 3 = 011 , 101 & 011 = 001 , 001 = 1 desimal (AND)
print(5 | 3) # 5 = 101 dan 3 = 011, 101 | 0... |
b2207a262e2e839f63072621144b06d9997c1316 | MrFunnyide/Study-Python | /Belajar/perulangan/ListComprehnsion1.py | 901 | 4.09375 | 4 | # contohKe3 menemukan item yang ada di kedua list
list1 = ['d', 'i', 'c', 'o']
list2 = ['d', 'i', 'n', 'g']
duplikat = []
for a in list1:
for b in list2:
if a == b:
duplikat.append(a)
print(duplikat) # output ['d','i']
# dibandingkan dengan
# contohKe4 Implementasi dengan list c... |
44239c05cae934363078d8829baf0c6fdce1c378 | MrFunnyide/Study-Python | /Belajar/Method/StaticMethod.py | 587 | 3.671875 | 4 | # sebuah fungsi yang mengubah metode menjadi metode statis (static method).
# Metode statis (static method) tidak menerima masukan argumen pertama secara implisit.
# contohnya :
class Kalkulator:
"""contoh kelas kalkulator sederhana"""
def f(self):
return 'hello world'
@staticmethod
... |
607f2c0b64c5135c729c98e4511c9cf65799bdd2 | MrFunnyide/Study-Python | /Belajar/OperasiListSetandString/inAndNotIn.py | 280 | 3.5 | 4 | # in dan not in = mengetahui sebuah nilai atau objek dalam list
# dan kasih nilai boolean
kalimat = 'Belajar Python di dalam Dicoding sangat menyenangkan'
print('Dicoding' in kalimat)
print('tidak' in kalimat)
print('Dicoding' not in kalimat)
print('tidak' not in kalimat)
|
541dd4981725c9e37816b577351cb8c13911624e | muhamadsechansyadat/learn-python-kelas-terbuka | /old/3/Main.py | 461 | 3.5 | 4 | # list itterable
jajan = ['baso', 'cimol', 'cilok', 'cilor']
for beli in jajan:
print(beli)
# string itterable
varString = 'sechan'
for nama in varString:
print(nama)
print(100*"=")
# for in for
varBuah = ['semangka', 'melon', 'jeruk', 'anggur']
varSayur = ['timun', 'tomat', 'cabai', 'selada']
varDataBela... |
3b7c810d3fecf7cf7be61a0383f967f34e43eb15 | wce-mtu/ev-smart-charge | /Simulation_1/singleCar.py | 2,907 | 3.8125 | 4 | def main():
car1 = make_car()
calc_rate_options(car1)
class Car(object):
# inputs
timeParked = 0
stateOfCharge = 0
batCapacity = 0
maxChargeRate = 0
# outputs
chargeRate = 0
priceRate = 0
balance = 0
def make_car():
car = Car()
car.timeParked = float(i... |
b75efc543c76cd6aebd0a6c1a53d12c62797e4a9 | PathomphongPromsit/LAB-Programming-Skill | /code/reverse-111629.py | 651 | 3.921875 | 4 | from __future__ import print_function
def reverse(string_list,start_index,stop_index):
start_index -= 1
stop_index -= 1
reverse_list = string_list[start_index:stop_index+1]
LRevese= len(reverse_list)
for i in range(1,LRevese+1):
string_list[start_index] = reverse_list[-i]
start_index += 1
return string_list
... |
6373bd20e4938d78d4a7ebb16abe3aa4e2487edf | Pappa/exercism | /python/rotational-cipher/rotational_cipher.py | 396 | 3.890625 | 4 | import string
lower = string.ascii_lowercase
upper = string.ascii_uppercase
def rotate(letters, rotation):
mapped = [_map(l, rotation) if l.isalpha() else l for l in letters]
return ''.join(mapped)
def _map(letter, rotation):
alphabet = (lower, upper)[letter.isupper()]
for i, c in enumerate(alphabet):
if c == ... |
2c7d72136cf270bb2e1b965dc715db6027adfeda | Pappa/exercism | /python/isbn-verifier/isbn_verifier.py | 351 | 3.515625 | 4 | def verify(isbn):
chars = [c for c in isbn if c.isdigit() or c == 'X']
if len(chars) != 10:
return False
digits = [int(c) if c.isdigit() else 10 for idx, c in enumerate(chars) if c.isdigit() or (c == 'X' and idx == 9)]
multipliers = range(1, 11)[::-1]
return sum([d * m for (d, m) in zip(di... |
58c83c8518650bf3d81f0ba7d61b8fe2be538248 | Pappa/exercism | /python/pig-latin/pig_latin.py | 603 | 3.828125 | 4 | from string import ascii_lowercase
vowels = set(['a', 'e', 'i', 'o', 'u'])
consonants = set(ascii_lowercase) - vowels
def translate(phrase):
return ' '.join([translate_word(word) for word in phrase.split()])
def translate_word(word):
if word[0:3] in ['squ', 'sch', 'thr']:
word = word[3:] + word[0:3]... |
3f00d473d5ca721799a446f7d38f2a685c44934c | Pappa/exercism | /python/nth-prime/nth_prime.py | 333 | 3.734375 | 4 | def nth_prime(n):
if n < 1: raise ValueError
candidate = 2
primes = []
while len(primes) < n:
if is_prime(candidate):
primes.append(candidate)
candidate += 1
return primes.pop()
def is_prime(n):
for i in [2, 3, 5, 7, 9]:
if (n % i == 0):
return n == i
return all(False for i in range(11, n, 2) if (n... |
124bfa11a7c1c566422faad790e410707941b542 | Babecherry/CP1404_Practicals | /prac_03/oddnames.py | 325 | 3.8125 | 4 | """Sable Ching"""
def get_name():
global main
def main():
while True:
name = str(input("Please enter your name: \n"))
if name == '':
print("Invalid, please enter your name.")
else:
print(name[1::2])
break
get_name()... |
6e769e65c9b4b5961ba912822edd2594e7327d01 | jobassous/flask_app | /strings.py | 249 | 3.53125 | 4 | orphan_fee = 200
teddy_bear_fee = 121.08
total = orphan_fee + teddy_bear_fee
name = "Joseph Bassous"
print(name, "the total will be", total)
print("%s, the total will be, %d" % (name, total))
print("{} the total will be ${}".format(name, total)) |
f64a7d1200db59192b0688977ab0d1be841231fc | ganjunhua/python | /numpytest/testnumpy.py | 389 | 3.546875 | 4 | import numpy as np
#切片
array=np.random.randint(1,10,16).reshape(4,4)
print(array)
#取出第一行所有值
#print(array[0])
#取出第一列所有值
#print(array[:,0])
#取出第一行和第三行
#print(array[1::2])
#取出第二列和第四列
print(array[::,1::2])
#取出第一行和第三行第二列和第四列
#print(array[0::2,1::2])
#c[2,1] = c[2][1]
#c[1,1,1]=c[1][1][1] |
805fafe1749557d9dad0a9b823bee4f30bb53399 | Nicholas-Nwanochie/python-work | /for-loops.py | 989 | 4.09375 | 4 | for name in friends:
print(name)
" for loop with numbers, last number is not shown"
for index in range(3, 10):
print(index)
friends = ["jim", "beth", "kevin"]
for index in range(len(friends)):
print(friends[index])
friends = ["jim", "beth", "kevin"]
for index in range(5):
if index == 0:
print... |
7909e0bf65ecb58fcef8817a8255efa18bd460fd | pankhurisri21/100-days-of-Python | /day1-exercise4.py | 132 | 4.28125 | 4 | #length of a string and variables
str=input("Enter the string\n")
print("The length of string "+"'"+str+"'"+" is:")
print(len(str))
|
d4fa98e23180564af50fc81547c953792c055d5f | pankhurisri21/100-days-of-Python | /19-dictionary.py | 91 | 3.5 | 4 | #dictionary
mydict={
"name":"John",
"age":21
}
print(mydict) #{'name': 'John', 'age': 21}
|
8a5739c9a6e6fc0209dfc47ec3879afad8a78a8a | pankhurisri21/100-days-of-Python | /sum_prog2.py | 245 | 3.8125 | 4 | #sum of n numbers
numbers=[1,2,3,4,5]
print("Sum of numbers in the list = ", sum(numbers))#sum of numbers in the list
print("Sum of numbers in the list and the start number =",sum(numbers,20))#sum ofnumbers in the list + the start number given
|
d490e1f73448f32eb150b3994f359cffb155acc4 | pankhurisri21/100-days-of-Python | /variables_and_datatypes.py | 548 | 4.125 | 4 | #variables and datatypes
#python variables are case sensitive
print("\n\nPython variables are case sensitive")
a=20
A=45
print("a =",a)
print("A =",A)
a=20#integer
b=3.33 #float
c="hello" #string
d=True #bool
#type of value
print("Type of different values")
print("Type of :",str(a)+" =",type(a))
print("Type of :",s... |
f33e0bc2471b0dabd1ba19519be80b3428e9a197 | triplejingle/cito | /Eva/Applicatie/Backend/PythonPrototypes/Prototypes/MemoryTest/BinarySearchTree.py | 1,852 | 3.625 | 4 | from VariableNode import VariableNode
class BinarySearchTree(object):
def __init__(self):
self.root = None
def find(self, key):
if self.root.key == key:
return self.root
if self.root.key < key:
return self.__find(self.root.right, key)
if self.root.key ... |
a3217003bf74872adb90e519b0a04a8606b8af4e | flxsosa/CodingProblems | /morsels_1.py | 1,983 | 3.96875 | 4 | '''
I'd like you to write a function that accepts two lists-of-lists of numbers and returns one list-of-lists with each of the corresponding numbers in the two given lists-of-lists added together.
It should work something like this:
>>> matrix1 = [[1, -2], [-3, 4]]
>>> matrix2 = [[2, -1], [0, -1]]
>>> add(matrix1, ma... |
ebb0a699bca0308d439959ad77f323fd94776774 | JingqiDuan/Hash-Code-2018 | /Vehicle.py | 2,183 | 3.78125 | 4 | from Point import Point
class Vehicle:
# #
# Init function
#
# city is a link to the parent
# index is the number associated with the vehicle
def __init__(self, city, index):
self.position = Point(0,0)
self.index = index
self.city = city
self.inRide = False
... |
f501c9f172241079ef33440ccaac5cf3e473bc48 | vanjara/problems | /cyclelist.py | 2,236 | 3.953125 | 4 | # /usr/bin/python2.7
# Converting Sam's Java code to Python
from nose.tools import assert_equal
class Node (object):
def __init__(self, value):
self.value = value
self.next = None
# Algorithm using extra space. Mark visited nodes and check that you
# only visit each node once.
def hasCycle(nod... |
04676613eb281256e87c53bcf7f3dfabe4e19663 | LucasXS/PythonExercicios | /exer013.py | 382 | 3.59375 | 4 | #LER O SALÁRIO DE UMA FUNCIONÁRIA E MOSTRAR SEU NOVO SALÁRIO COM 15% DE AUMENTO
nomeFuncionario = input('NOME FUNCIONARIO: ')
salarioAtualFunc = float(input('SALÁRIO ATUAL R$'))
novoSalario = salarioAtualFunc + (salarioAtualFunc * 15/100)
print('O Funcionário {} deixará de receber {:.2f} e passará a receber {:.2f}'.f... |
d02db2c39a06353f685bff400170807e67fc1993 | LucasXS/PythonExercicios | /exer010.py | 322 | 3.515625 | 4 | #LER QUANTO DINHEIRO UMA PESSOA TEM E CONVERTER P/ OUTRAS MOEDAS - 07/02/2021
emReal = float(input('Quanta grana você tem? R$'))
emDolar = emReal / 5.37
emEuro = emReal / 6.47
emIene = emReal /0.051
print('R${} reais dá exatamente \n${:.2f} dolares \n€{:.2f} Euros \n¥{:.2f} Ienes'.format(emReal, emDolar, emEuro, emIen... |
c0f6cb573875db49cc49a94920e44a4f04030e23 | LucasXS/PythonExercicios | /exer017.py | 530 | 3.9375 | 4 | #ler o comprim cateto oposto e cateto adjacente (triag. retang). Cal. e mostre o compr. da hipotenusa.
print("="*25)
print('{:=^25}'.format('SEJA BEM VINDO!!'))
print("="*25)
import math
print("Insira o cateto oposto e adjacente para calcular a hipotenusa!")
catOposto = float(input('Digite o valor do cateto oposto: '... |
475999ede4a2eb11fe5a11028966331fb5c33f42 | LucasXS/PythonExercicios | /exer003.py | 326 | 3.875 | 4 | #SOMAR DOIS NUMEROS E MOSTRAR NA TELA, USAR O .FORMAT.
n1 = int (input('Digite um valor: '))
n2 = int (input('Digite um valor: '))
s = n1 + n2
#print('A soma entre',n1, 'e', n2,' vale', s) sem o .format
print('A Soma entre \033[4;33m{}\033[m e \033[4;35m{}\033[m vale \033[1;31;46m{}\033[m'.format(n1, n2, s)) #com o .f... |
941bb40a625b55519e563120b4d84652c580b84f | aaronhoby/csua-git-workshop | /best.py | 373 | 3.765625 | 4 |
def main():
person_a = "Yi"
superlative_a = "dankest"
person_b = "Ni"
superlative_b = "weebest"
name = "Garcia"
position = "professor"
print("{0}: {1} is the {2} {3}!".format(person_a, name, superlative_a, position))
print("{0}: {1} is the {2} {3}!".format(person_b, name, superlative_... |
e62f086dd89dd61ef0bc10ca8203fc3ba11e0190 | beibeisongs/K-Means-Realizing | /K-Means Test1.py | 9,280 | 4.40625 | 4 | # encoding=utf-8
# Date: 2018-7-22
# Author: MJUZY
"""
The Analysis of K-Means algorithm:
* Advantages:
Easy to be Realized
* Disadvantages:
Probable to Converge to a local minimum value
Converge to a local minimum value: 收敛到局部最小值
* IDEA of K-Means:
First, we s... |
a272f4c2b2f76f6b8ea4ba0d7d157eec6a8e4f45 | SanFullStack/MyHTML | /moviename.py | 2,523 | 3.84375 | 4 | import random
def choose():
List=[junglebook,titanic,dearzindagi,deshdrohi,stree,fan,tamasha,thappad,sexeducation]
secret=random.choice(list)
return secret
def moviename():
p1name=input("Player 1 please enter your name :")
p2name=input("Player 2 please enter your name :")
pp1=0
pp2=0
tu... |
3c2ca2d36af1386e0259d7b72efea78b6dfc7486 | ameet-1997/Machine-Learning | /Boston_House_Prices/boston_price.py | 775 | 3.890625 | 4 | import pandas as pd
from sklearn.datasets import load_boston
# boston is a dictionary
boston = load_boston()
# Store the data and target in respective variables
data = boston.data
target = boston.target
# Convert to pandas dataframe and assign column names to dataframe
(data, target) = (pd.DataFrame(data), pd.Dat... |
ecd41eb8842c8e498b92a82c7559dbfb9ef89a52 | haved/haved.github.io | /assets/tasks/bus/impl.py | 1,669 | 3.71875 | 4 | #!/bin/env python3
n = int(input())
trips = []
for _ in range(n):
times = input().split(' ')
trips.append((int(times[0]), int(times[1])))
# Sort by decreasing arrive_time when the leave_time is the same
trips.sort(key=lambda x:x[1], reverse=True)
# By increasing leave_time
trips.sort(key=lambda x:x[0])
trips... |
2ab9aadcc835b15bd2d5c16450bdeec70e2c40df | 00008883/seminar8 | /task1.py | 173 | 3.53125 | 4 | student1 = ('00008883', 19, 'Tashkent')
student2 = ('00009623', 18, 'Andijan')
print(student1[0]>student2[0])
print(student1[1]>student2[1])
print(student1[2]>student2[2]) |
4ba1e62b154b3b46c84c4a94ce09fceaced1d982 | lvrohai/rhprapy | /days100/days1_15/12/untitled/re_operation.py | 2,391 | 3.53125 | 4 | import re
def main():
username=input("请输入用户名")
qq = input("请输入QQ")
# match方法的第一个参数是正则表达式字符串或正则表达式对象
# 第二个参数是要跟正则表达式做匹配的字符串对象
# 用正则表达式匹配字符串 成功返回匹配对象 否则返回None
m1 = re.match(r'^[0-9a-zA-Z_]{6,20}$',username)
if not m1:
print('请输入有效的用户名')
m2 = re.match(r'^[1-9]\d{4,11}$',qq)
if ... |
c3178ae575e71a862d6c43c8a7a00ea81b706226 | kaciyn/set09103 | /battleship.py | 1,526 | 3.765625 | 4 | from flask import Flask,redirect,url_for
app = Flask(__name__)
@app.route('/')
def battleship():
from random import randint
board = []
#board build
for x in range(5):
board.append(["O"] * 5)
def print_board(board):
for row in board:
print " ".join(row)
#intro
... |
300d9dbb91d2c5dd41f05aba997593774157f7b0 | MattWarren97/PatienceSolver | /Move.py | 551 | 3.546875 | 4 | from Card import Card
class Move:
def __init__(self, card, newPos, oldPos):
self.card = card
self.newPos = newPos
self.oldPos = oldPos
def getPosStr(self, pos):
return "(" + str(pos[0]) + "," + str(pos[1]) + ")"
def __repr__(self):
toPrint = ""
toPrint += "Move: " + str(self.card)
toPrint += " from ... |
697648a2525e9e48b9e1260fd07c41375d977e57 | MilaMaest/NumPy_Tutorials | /numpy_tuto2.py | 682 | 3.546875 | 4 | import numpy as np
x = np.array([
[2,8,6],
[5,9,3],
[9,6,7]
])
print(x)
y = np.array([
(1,1,1),
(2,2,2),
(3,3,3)
])
print(y)
# Specify the type of array explicitly
z = np.array([ [7,8,7,8], [5,9,5,9] ], dtype=float)
print... |
d6bc3dc3ede95a6049fa9d1ed185087bf1475833 | HeWei-imagineer/Algorithms | /Leetcode/002_Add_Two_Number.py | 1,470 | 3.65625 | 4 | # Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def addTwoNumbers(self, l1, l2):
num1,num2,i=0,0,0
while(l1):
num1 = num1 + l1.val*10**i
l1 = l1.next
i+=1
... |
d9f185d9097e1341c3769d693c9976e25eea6d23 | HeWei-imagineer/Algorithms | /Leetcode/hanoi.py | 591 | 4.15625 | 4 | #关于递归函数问题:
def move_one(num,init,des):
print('move '+str(num)+' from '+init+' to '+des)
print('---------------------------------')
def hanoi(num,init,temp,des):
if num==1:
move_one(num,init,des)
else:
hanoi(num-1,init,des,temp)
move_one(num,init,des)
hanoi(num-1,temp,init... |
36ad67d73e00225de0b641daea241b9810071915 | HeWei-imagineer/Algorithms | /Leetcode/009_Palindrome_Number.py | 958 | 3.546875 | 4 | class Solution:
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
s = str(x)
star,end=0,len(s)-1
while star<end:
if s[star]==s[end]:
star += 1
end -=1
else:
break
return False if star<end else ... |
d6de93d7b9a1ce5be40af662edee4f86e69f840d | HeWei-imagineer/Algorithms | /Leetcode/023_Merge_k_Sorted_Lists.py | 1,395 | 4.0625 | 4 | #Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
#cool, harder ac one time
class Solution:
def mergeKLists(self, lists):
if len(lists)>1:
middle = len(lists)//2
return self.merge(self.mergeKLists(lists[:middle]),
sel... |
bb0185098dcf19ccbf277239364d8e46fa6d7e88 | nimberledge/MiscScripts | /rotate180.py | 656 | 3.875 | 4 | test_matrix = [[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
[13, 14, 15, 16]]
def rotate180(matrix):
new_matrix = [None for i in range(len(matrix))]
# Here's the algorithm
# Take the i-th row, reverse it
# Insert as the N-1-ith row
for i, row in enumerate(m... |
e6486c00528623a4f674b57a36abc8dd0b759ea8 | Thorchy/advent-of-code-2017 | /day_02/day_02.py | 1,689 | 4 | 4 | import csv
import os
LARGEST_SMALLEST = False
def largest_smallest(filepath):
with open(filepath) as f:
csv_reader = csv.reader(f, delimiter='\t')
checksum = 0
# Create checksum with the largest - smallest integer
for row in csv_reader:
row = map(int, row)
... |
60517bb8871144f55f41e4931167fec7379cf83e | swansonk14/graphing_fleas | /board.py | 8,028 | 3.859375 | 4 | import pygame
import random
from constants import COLOR_MAP
from helpers import row_column_to_pixels
from square import Square
class Board:
"""A Board contains, controls, and displays all Squares and Fleas in the simulation."""
def __init__(self,
screen,
num_rows,
... |
647fc365d85cfbd23b7a576c16a59f72507018e5 | glareprotector/glare | /my_lists.py | 8,619 | 3.90625 | 4 | class my_list(list):
@classmethod
def get_class(cls):
return cls
def __repr__(self):
ans = ''
for item in self:
ans = ans + repr(item) + '\n'
return ans
# NOTE: think about how this should be organized when i have time. maybe have a class that pairs an obj... |
b6830ff43c0f5203e8c77a87a73b939dd51d761b | AnushkaZ44/SDP-Task-1 | /Gross salary.py | 140 | 3.703125 | 4 | BS= float(input("Enter Basic Salary :"))
TA = BS * 0.4;
DA = BS * 0.2;
HRA = BS * 0.3;
GS = BS + DA + HRA + TA;
print('Gross Salary = ',GS)
|
8aa017212b91c72541f1a7b1117f0c776745e255 | darkhorse1998/100-Days-Of-Self-Customised-Data-Science-Helper-Modules | /code/Day_3/skewness.py | 5,503 | 3.71875 | 4 | import pandas as pd
import numpy as np
def skew_stats(df_col):
"""
Input: Pandas Series Data format (single column)
Output: void type
Prints: skew_tye, skewness, comment
"""
try:
skew = df_col.skew()
if skew>0:
if skew <= 0.5:
skew_tye =... |
352995fc9653e83111180dcaba567b53ea0f649f | liyingliincsvw/test | /project C.py | 1,643 | 3.546875 | 4 | # -*- coding: utf-8 -*-
from sklearn.cluster import KMeans
from sklearn import preprocessing
import pandas as pd
import numpy as np
data = pd.read_csv('CarPrice_Assignment.csv', encoding='gbk')
#print(df1)
d = pd.read_excel('Data_Dictionary_carprices.xlsx')
df = pd.DataFrame(data)
aa = []
aa = list(df.col... |
bd423b580d1f126737fe06dcadbecd35ca5e3e59 | SruthiSudhakar/DLHW1 | /1_cs231n/cs231n/classifiers/softmax.py | 2,599 | 3.546875 | 4 | import numpy as np
from random import shuffle
import pdb
def softmax_loss_vectorized(W, X, y, reg):
"""
Softmax loss function, vectorized version.
Inputs:
- W: C x D array of weights
- X: D x N array of data. Data are D-dimensional columns
- y: 1-dimensional array of length N with labels 0...K-1, for K clas... |
016b921a2195604125f98d94315328dea06d5c6c | pilino1234/AdventOfCode2015 | /5/Day5.py | 930 | 3.71875 | 4 | from itertools import groupby
def is_nice(string):
if has_vowels(string, 3):
if has_rep_letter(string, 2):
if has_no_bad_string(string):
return True
return False
def has_vowels(string, number):
return sum(map(string.count, "aeiou")) >= number
def has_rep_letter(stri... |
c398458e39a43152c60f040d0500246e3d9d8cbd | pilino1234/AdventOfCode2015 | /1/day1-2.py | 260 | 3.53125 | 4 | moves = {"(": 1, ")": -1}
def move(filename):
floor = 0
with open(filename) as file:
for pos, i in enumerate(file.read()):
floor += moves[i]
if floor < 0:
return pos + 1
print(move("day1-1-input.txt"))
|
b5c48a38649438e70f5e61fb800022584835f24e | rbk2145/DataScience | /010_Merging DataFrames with pandas/2_Concatenating data/2_Appending & concatenating DataFrames.py | 1,292 | 3.984375 | 4 | ####Appending DataFrames with ignore_index
# Add 'year' column to names_1881 & names_1981
names_1881['year'] = 1881
names_1981['year'] = 1981
# Append names_1981 after names_1881 with ignore_index=True: combined_names
combined_names = names_1881.append(names_1981, ignore_index=True)
# Print shapes of names_1981, name... |
d5d0940641384b80a06069ef0b9d54491c807328 | rbk2145/DataScience | /010_Merging DataFrames with pandas/3_Merging data/2_Ordered merges.py | 897 | 3.671875 | 4 | #####Using merge_ordered()
# Perform the first ordered merge: tx_weather
tx_weather = pd.merge_ordered(austin, houston)
# Print tx_weather
print(tx_weather)
# Perform the second ordered merge: tx_weather_suff
tx_weather_suff = pd.merge_ordered(austin, houston, on='date', suffixes=['_aus', '_hus'])
# Print tx_weather... |
b2eb51f1c07dc6b03bd49499e392191e4578a2ed | rbk2145/DataScience | /9_Manipulating DataFrames with pandas/2_Advanced indexing/1_Index objects and labeled data.py | 814 | 4.4375 | 4 | ####Index values and names
sales.index = range(len(sales))
####Changing index of a DataFrame
# Create the list of new indexes: new_idx
new_idx = [month.upper() for month in sales.index]
# Assign new_idx to sales.index
sales.index = new_idx
# Print the sales DataFrame
print(sales)
######Changing index name labels
... |
8bb960dd2df317cd9e7fbb3bfb96b6313995e11d | weiteli/leetcode2018-19 | /LC257.py | 766 | 3.8125 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def binaryTreePaths(self, root):
"""
:type root: TreeNode
:rtype: List[str]
"""
self.res = []
... |
b05c9ea0da1f1562bece1f4d881a054b0f4e97df | weiteli/leetcode2018-19 | /LC515.py | 1,546 | 3.75 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def largestValues(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
if root == Non... |
c41f102a86b292fc338d6c7f3bbe689f02151f1c | davidthaler/arboretum | /arboretum/forest.py | 6,303 | 3.53125 | 4 | '''
Class Forest implements a random forest using the trees from tree.py.
author: David Thaler
date: September 2017
'''
import numpy as np
from . import tree
from .base import BaseModel
class Forest(BaseModel):
'''
Class Forest implements random forest classification and regression
models using trees fr... |
4d66085eb9572ff519aaefb16281b587aac2cb1a | SVdeJong/day2 | /project_tip_calculator.py | 952 | 3.96875 | 4 | #If the bill was $150.00, split between 5 people, with 12% tip.
#Each person should pay (150.00 / 5) * 1.12 = 33.6
#Format the result to 2 decimal places = 33.60
#Tip: There are 2 ways to round a number. You might have to do some Googling to solve this.💪
#HINT 1: https://www.google.com/search?q=how+to+round+number+to... |
fe541905e877fa7b24a95d6b8916e14896be514e | lalitkapoor112000/Python | /Character in name.py | 236 | 4.03125 | 4 | name,key=input("Enter your name and a character seperated by comma:").split(",")
print(f"Length of your name is {len(name.strip())}")
print(f"Hi {name} ,{key} is {name.lower().strip().count(key.lower().strip())} times in your name")
|
f932a3cdb88fa9c1735bb68c4f6684e6e1d12066 | lalitkapoor112000/Python | /Finding position of String in a name.py | 187 | 3.78125 | 4 | def pos(l,key):
for index,name in enumerate(l):
if key==name:
return index
else:
return -1
l=['Lalit','lalit']
print(pos(l,'lalit'))
|
20aee8962ae91f40d0edd2672d76e08476382e74 | lalitkapoor112000/Python | /Number Guessing Game Modified.py | 250 | 3.78125 | 4 | import random
num=random.randint(1,101)
x=int(input("Guess a number:"))
k=0
while x!=num:
if x>num:
print("Too high")
else:
print("Too Low")
x=int(input("Guess again:"))
k+=1
print(f"You Won,in {k} times")
|
2fb3f8899a33dc03d137260b9a03068282a8bb70 | lalitkapoor112000/Python | /List Comprehension Example.py | 142 | 3.78125 | 4 | l=[]
while 'q' not in l:
l.append(input("Enter string to list and enter q to exit:"))
l.remove("q")
l=[i[::-1] for i in l]
print(l)
|
7301647ec241cedae05a63daeffb6417f45dcc91 | lalitkapoor112000/Python | /Removing Data from list.py | 215 | 3.953125 | 4 | fruits=['apple','orange','grapes','mango','peach']
fruits.remove('orange')
print(fruits)
fruits.pop()
print(fruits)
del fruits[1]
print(fruits)
fruits.pop(1)
print(fruits)
for i in fruits:
print(i)
|
7b84e2c07f670b19006381635e712aacf14bc43e | lalitkapoor112000/Python | /List Squaring.py | 245 | 3.796875 | 4 | def listSquare(m):
sq=[]
m.remove('q')
for i in m:
sq.append(int(i)**2)
return sq
l=[]
i=0
while 'q' not in l:
l.append(input("Enter list elements and enter to stop:"))
print(listSquare(l))
|
0c37fdab26b134508e03c706c7833d5b73ba3896 | BryanCAlcorn/NumberGuesses | /Number Guesses.py | 2,652 | 4.09375 | 4 | import random;
# Rolls 1-50, and has user guess until they are correct.
def spinner():
spin = random.randint(1,50);
while(True):
Target = input('Pick a number(1-50): ');
if(Target > spin):
print 'Too high';
elif(Target < spin):
print... |
c31cfdfc797c4f40d719d1ef28549059c291c76f | SandjayRJ28/Python | /Python Ep 03 Strings.py | 1,539 | 4.21875 | 4 | #Variablen defineren gaat heel makkelijk heeft het een naam en waarde het its done
Voor_naam = "Sandjay"
print(Voor_naam)
#Je kan stringe combineren met +
Achter_naam = "Jethoe"
print(Voor_naam + Achter_naam)
print("Hallo" + Voor_naam + "" + Achter_naam)
#Je kan functies gebruiken om je string aan te passen
zin = "Ik... |
183a316c248315e2fad1ece6eeeb2f53506bb770 | boogiedev/pair-programming-exercises | /andrei-aroosh/group_project/main.py | 733 | 3.8125 | 4 | from libs.map import *
class Character:
def __init__(self, name, cord):
self.name = name
self.cord = cord
def change_cord(self):
ui = input("Where would you like to move?: ")
if ui.lower() == "up":
self.cord=self.cord[0],self.cord[1]-1
elif ui.lower() == "... |
f471530103696bc3d847968fa6ba67f00b02617e | mobibridge/assingments | /test_fizzbuzz.py | 427 | 4 | 4 | import unittest
from fizz import fizz_buzz
class FizzBuzzTest(unittest.TestCase):
"""Testing FizzBuzzTest
"""
def test_returns_fizz_when_divisible__by_three(self):
"""Test return fizz when input is divisile
"""
self.assertEqual(fizz_buzz(3),"fizz")
def test_returns_buzz_when_divisible__by_five(self):
"""... |
a991555e799064d6a89f9c0c1cc460fcf41ce8ea | TazoFocus/UWF_2014_spring_COP3990C-2507 | /notebooks/scripts/cli.py | 664 | 4.21875 | 4 | # this scripts demonstrates the command line input
# this works under all os'es
# this allows us to interact with the system
import sys
# the argument list that is passed to the code is stored
# in a list called sys.argv
# this list is just like any list in python so you should treat it as such
cli_list = sys.argv
... |
870ba0cb86c6b9b3892a9df89066f3c5adc8e037 | ysguoqiang/abigproject | /python_socket_server/server.py | 654 | 3.515625 | 4 | #!/usr/bin/python
# -*- coding: UTF-8 -*-
# 文件名:server.py
import socket # 导入 socket 模块
s = socket.socket() # 创建 socket 对象
host = "127.0.0.1" #socket.gethostname() # 获取本地主机名
port = 12345 # 设置端口
s.bind((host, port)) # 绑定端口
s.listen(5) # 等待客户端连接
c,addr = s.... |
223976072a2bab6eca68dc1eed3de5d707703317 | sumit-jaswal/competitive_programming | /check_sum.py | 397 | 3.71875 | 4 | # Find the numbers in an array that add upto a specific value and return true else return false.
# Input : [4,7,1,-3,2], 6
# Output : ([4, 2], True)
def two_sum(list,k):
sum = []
for i in range(0,len(list)):
for j in range(0,i):
if(list[j]+list[i]==k):
sum += [list[j]]
sum += [list[i]]
if(len(sum)!=0... |
bee0307649c0eab9a8f0a1abdf48deddb9709d68 | 99sujeong/py-data | /python/tokenize.py | 362 | 3.53125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Nov 24 21:13:09 2020
@author: Park
"""
from nltk.tokenize import word_tokenize
text = "I am actively lookin for Ph.D. students. and you are a Ph.D student."
print('=>', text); print()
print('=>', word_tokenize(text)); print()
from nltk.tag import pos_tag
x = word... |
2b9170d094bf3a1bd3a254aa8b7a9fa9e16f5cc0 | 99sujeong/py-data | /data/iris-ANN-simple.py | 951 | 3.578125 | 4 | from sklearn.datasets import load_iris
import pandas as pd
# iris데이터셋을 iris라는 변수에 저장
iris = load_iris()
# to excel... by Uchang
df = pd.DataFrame(data=iris['data'], columns = iris['feature_names'])
df.to_excel('iris.xlsx', index=False)
print(iris['data'][0:10])
X = iris['data']
y = iris['target']
from sklea... |
88453495020770a660950be174fbe255f1b6ec3b | 99sujeong/py-data | /python/201006.py | 1,151 | 3.59375 | 4 | #알고리즘
'''
n=int(input())
if (n%3==1):
print(n, "3의 배수가 아니다.")
else:
print(n, "3의 배수이다.")
m=352 # 거스름돈
#100원
m100=0
while m>=100:
m100 += 1
m-=100
print("100원 동전 =>", m100)
# 10원
m10 = 0
while m>=10:
m10 += 1
m-=10
print("10원 동전 =>", m10)
# 1원
m1 = 0
while m>0:
... |
f68f8aaf53e834b5b3297a2852518edba06ebbe0 | denrahydnas/SL9_TreePy | /tree_while.py | 1,470 | 4.34375 | 4 | # Problem 1: Warm the oven
# Write a while loop that checks to see if the oven
# is 350 degrees. If it is, print "The oven is ready!"
# If it's not, increase current_oven_temp by 25 and print
# out the current temperature.
current_oven_temp = 75
# Solution 1 here
while current_oven_temp < 350:
print("The oven is... |
78c6cd735ab26eabf91d6888118f9e5ec1320ccf | denrahydnas/SL9_TreePy | /tree_calc.py | 746 | 4.28125 | 4 | # Step 1
# Ask the user for their name and the year they were born.
name = input("What is your name? ")
ages = [25, 50, 75, 100]
from datetime import date
current_year = (date.today().year)
while True:
birth_year = input("What year were you born? ")
try:
birth_year = int(birth_year)
except Valu... |
823bf53c272967e7b32ef32d2831a867d8996f2b | prabhus489/Python_Bestway | /Factorial_of_a_Number.py | 700 | 4.09375 | 4 | def fac_of_num():
global num
factor = 1
flag = True
while flag:
flag = False
try:
num = int(round(float(input("Enter the Number: "))))
if num == 0:
print("The Factorial of Zero is One")
flag = True
else:
... |
528a622f441ed7ac306bc073548ebdf1e399271e | prabhus489/Python_Bestway | /Length_of_a_String.py | 509 | 4.34375 | 4 | def len_string():
length = 0
flag = 1
while flag:
flag = 0
try:
string = input("Enter the string: ")
if string.isspace()or string.isnumeric():
print("Enter a valid string")
flag = 1
except ValueError:
prin... |
dca6907cca6ed9a0d94ba80a2ec3f49c6e16bd10 | PauloHMTeixeira/Tic-Tac-Toe-jogo-da-velha-. | /JogoDaVelha.py | 2,148 | 3.859375 | 4 | # Paulo Henrique Melo Teixeira e Pedro Henrique Bezerra Buarque de Paula
board = ['_'] * 9
def print_board():
print(board[0] + '|' + board[1] + '|' + board[2])
print(board[3] + '|' + board[4] + '|' + board[5])
print(board[6] + '|' + board[7] + '|' + board[8])
print_board()
contador = 0
while True:
x... |
03fe80d2380837c73c218a6f5c65df137499b3ca | williamnie2088/Data_structure_sample | /Stack/stack_string_reverse.py | 568 | 3.84375 | 4 | class Stack():
def __init__(object):
object.items = []
def push(object, item):
object.items.append(item)
def pop(object):
return object.items.pop()
def is_empty(object):
return object.items == []
def revert(stack, input_str):
for i in range (len(input_str)):
... |
5d29efc5569e4828d8d725a0d32bc8239ec3af6e | yangtau/algorithms-practice | /practice/weekly-contest-178/rank-teams-by-votes.py | 1,262 | 3.5 | 4 | '''
https://leetcode.com/problems/rank-teams-by-votes/
'''
class Solution:
def rankTeams(self, votes: [str]) -> str:
ranks = {c: [0]*len(votes[0])+[c] for c in votes[0]}
for vote in votes:
for i, c in enumerate(vote):
ranks[c][i] -= 1
return ''.join(sorted(ranks... |
0dfa3cb523658865490771059f6f825088505cdf | marlhakizi/Greetings | /timing.py | 617 | 3.96875 | 4 |
#function taking in 2 parameters hr and period and returns a meal recommendation
def mealrec(hr,period):
if period=='AM':
if hr>=5 and hr<=11:
return("Breakfast TIME!!")
else:
return("It's too early! Go TO BED!!")
elif period=="PM":
if hr==12 or hr<=3:
... |
8f70f9fe6fd173ff692a7ea76f3f3a4b79ec88ed | HelloYeew/helloyeew-computer-programming-i | /6310545566_Phawit_ex4/coffee_machine_2.py | 7,234 | 4.15625 | 4 | import sys
# function zone
def summary():
global water, milk, coffee_beans, disposable_cups, money
print("The coffee machine has:")
print(f"{water} of water")
print(f"{milk} of milk")
print(f"{coffee_beans} of coffee beans")
print(f"{disposable_cups} of disposable cups")
if money != 0:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.