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 |
|---|---|---|---|---|---|---|
c3dcef35700e216406eddc219016db33bce7fe3d | s-projects18/s-projects18-fcc-67 | /password_cracker.py | 1,280 | 3.609375 | 4 | import hashlib
def get_list(path):
"""import file and return ist as a list"""
try:
file_handle = open(path, 'r')
l = file_handle.read().splitlines(0)
file_handle.close()
return l
except:
print("Error: Can't open file: ", path)
exit()
def check_hash(pw, hash):
"""create sha1-hash of p... |
852f3e05f8a265d7e617e1a09fc2e196bdd3a720 | JasonQVan/PythonProject | /CoffeeMachine.py | 4,051 | 4.03125 | 4 |
machinewater = 400
machinemilk = 540
machinebeans = 120
Cups_Coffee = 0
money = 550
disposable_cups = 9
water = 200
milk = 50
coffee_beans = 15
expwater = 250
expbeans = 16
latwater = 350
latbeans = 20
latmilk = 75
cappuwater = 200
cappumilk = 100
cappubeans = 12
def actionbuy():
global ma... |
9e916359181dffc198cd068ba90876f77f1c3181 | MeSabya/LeetCodeProgramsInPython | /DynamicProgrammingPattern/0-1KnapSackPattern/EqualSubsetSumPartition.py | 1,671 | 3.890625 | 4 | # Equal Subset Sum Partition
# Given a set of positive numbers, find if we can partition it into two subsets such that the sum of elements in both subsets is equal.
'''
Input: {1, 2, 3, 4}
Output: True
Explanation: The given set can be partitioned into two subsets with equal sum: {1, 4} & {2, 3}
Input: {1, 1, 3, 4, 7... |
3b675c6ca6697cfc958d015c3a722f6ad7bd520d | MeSabya/LeetCodeProgramsInPython | /KthSmallestNumberiMSortedLists.py | 689 | 3.75 | 4 | from heapq import *
# Kth Smallest Number in M Sorted Lists
def find_Kth_smallest(lists, k):
minHeap = []
for i in range(len(lists)):
# push the number, index, source list
heappush(minHeap, (lists[i][0], 0, lists[i]))
popCount , popedNumber = 0, 0
while minHeap:
poped... |
890540caa1d454ce7c0d7dd0944d8fde13ed3193 | aernesto24/Python-el-practices | /Basic/Python-university/Functions/ArithmeticTables/arithmeticTables.py | 2,650 | 4.46875 | 4 | """This software shows the arithmetic tables based on the input the user provides, it can show:
multiplication table, sum tablet, etc. """
#Function to provide the multiplication table from 0 to 10
def multiplicationTables(LIMIT, number):
counter = 0
print("Tabla de multiplicar de " + str(number))
for... |
5110752aefe10ccc2e99f096ac6389a8952eaa90 | aernesto24/Python-el-practices | /Basic/Python-university/OOP/rectangle.py | 504 | 4.03125 | 4 | class Rectangle:
def __init__(self, base, height):
self.base = base
self.height = height
def rectangle_area(self):
return self.base * self.height
"""Enter the values for the new object"""
b = int(input("Enter the base of the rectangle: "))
h = int(input("Enter the ... |
8b6ac384b77f1ecd82910ddc7e112aefeb009286 | wehsu01/WendyHsu | /1.py | 780 | 4.03125 | 4 | # test
# test 2
print('hello wowrld')
#input output
example = input('eat ')
print('i want', example,'!')
#multiple variables
fruit = 'apple'
count = '3'
print ('i want', count, fruit, '!')
print ('i want ' + count, '' + fruit + '!')
print (f'i want {fruit}!')
print (f'i want {fruit.upper()}!')
print ('i want {}!' .fo... |
6d20f8b4ffd792c366121e90c357f3f0ad1bc885 | superjodash/advent2019 | /Day02/computer.py | 2,098 | 3.5 | 4 | class Computer:
instrptr: int = 0 # Instruction Pointer
memory = [] # memory
ops = {1: 4, 2: 4, 99: 1} # OpCodes {code: parameter count }
def __init__(self, memory=[]):
if len(memory) > 0:
self.memory = memory.copy()
def run(se... |
7ee07359620921d8c24994c108d538433bd8feb5 | Mr-Aouadi/Python | /Vache Toureaux 2C.py | 3,041 | 3.5625 | 4 | #Jeux Vache Toureaux (2 chiffres)
def Random_Func(Usd_Nr):
#definir un nombre aleatoire apar les nombres deja choisis
import random
rand_Nr=random.choice([i for i in range(0,9) if i not in Usd_Nr])
return rand_Nr;
def Check_Res(Gss_Res):
#traiter le resultat de vérification
if Gss_Res=='2T0V':... |
39253b7455c25108306b182530fcde8ad768589b | lijianmin01/2020_Sophomore_rewiev | /python计算生态/整理/0815ques.py | 55,357 | 3.953125 | 4 | """
1. 编写一段程序,由键盘赋值两个变量a,b,当a和b都是浮点数时输出以a为实部,b为虚部的复数的共轭复数,
如果a和b都是整数,则输出a除以b保留两位小数的结果,如果都不是,则分别输出a和b的类型。
"""
# # 判断数据类型 (假设只有三种数据: 字符 、 整形 、 浮点型)
# def cnt_type(cnt):
# str_type = ['string','int','float']
# flag = None
# # 先除去 . 对字符串的影响
# strs = cnt.split(".")
# if len(strs)>2:
# # 只有浮点数... |
34d07d301c51eb60fb65744aa271b202234c1afa | chapman-phys220-2017f/cw-03-jare-od | /gaussian.py | 1,857 | 3.765625 | 4 | #!/usr/bin/env python3
"""This module has three seperate functions. g(x) takes a numerical input and
calculates the value of the Gaussian normalized function at that point. Interval
splits a range between a and b into equal portions of length dx. Then, it calculates
the value of an arbitary function at those points.... |
dbcfa10e99fc3f6bd734fed712d85f2f8cf2f0be | craigrmills/RobotsVsDinosaurs | /robot.py | 388 | 3.515625 | 4 | class Robot:
def __init__(self, name):
self.name = name
self.health = 100
self.weapon = None
def attack(self, dinosaur):
dinosaur.health = dinosaur.health - self.weapon.attack_power
print(self.name + " attacked " + dinosaur.name + " with it's " +
self.weap... |
92ea6debe104642ad84b3011de602e8ff78f1184 | roberto-informatorio/POO | /caso 2.py | 1,117 | 3.625 | 4 | class Vehiculo:
def __init__(self, color,ruedas):
self.color = color
self.ruedas = ruedas
class Coche(Vehiculo):
def __init__(self,color,ruedas,velocidad,cilindradas):
Vehiculo.__init__(self, color, ruedas)
self.velocidad = velocidad
self.cilindradas = cilin... |
69a1092855d5b68b1c59d7b8b941ed16f73b2c1c | acquatellamax/meeting_updater | /get_meeting_function.py | 755 | 3.5 | 4 | # AUXILIARY SCRIPT TO GET SCHEDULED MEETINGS IN A LIST
import requests
import json
from values import token
# Header for API calls
headers = {
'Authorization': f'Bearer {token}'
}
# Request for list of scheduled meetings:
web_current_meetings = "https://webexapis.com/v1/meetings?meetingType=scheduledMeeting"
curr... |
15a69ecb35cec652121faaf582966f25ea7dad8b | gaoyangthu/leetcode-solutions | /004-median-of-two-sorted-arrays/median_of_two_sorted_arrays.py | 1,815 | 4.28125 | 4 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
"""
There are two sorted arrays nums1 and nums2 of size m and n respectively.
Find the median of the two sorted arrays.
The overall run time complexity should be O(log (m+n)).
Example 1:
nums1 = [1, 3]
nums2 = [2]
The median is 2.0
Example 2:
nums1 = [1, 2]
nums2 = [3... |
17b53610d7777fc9618665a21b5f48e3b1454295 | mohammedh123/adventofcode2020 | /day23/main.py | 3,311 | 3.5625 | 4 | from collections import deque
from copy import deepcopy
from itertools import chain
from operator import attrgetter
class CupNode:
def __init__(self, val, next=None):
self.val = val
self.next = next
class CupSet:
def __init__(self, list_of_cup_values):
self.original_length = len(list... |
430368c9ecc695d4a0c938db759d74652de0da69 | siddhantkakkar/s.kakkar | /searching_idct.py | 409 | 3.78125 | 4 | n1 = input()
n = int(n1)
phonebook = {}
for i in range(0, n):
key_val = input()
list1 = key_val.split(' ')
key = list1[0]
value = list1[1]
phonebook[key] = value
while True:
test_key = input()
if test_key == '':
break
if test_key in phonebook:
ans = phoneb... |
333b02a1345cf4cb341a080893defc67f4db0e94 | siddhantkakkar/s.kakkar | /cut_rod.py | 1,953 | 3.90625 | 4 | import time
def cut_rod(plist, rode_size, dict1):
key = rode_size
# print "I have enter the def"
# print "key: rod_size", rode_size
# print "plist", plist
maxp = 0
if 0 >= rode_size:
return 0
if key in dict1:
maxp = dict1[key]
# print "key, maxp found", key... |
50f7729c7ff52d23285db88cef048b147eba0041 | Hudaal/Small_projects | /Rock_paper_scissors/Aksjon.py | 500 | 3.703125 | 4 | """Aksjons metoder, overloading"""
class Aksjon:
def __init__(self, val):
if isinstance(val, str):
val = {'Stein': 0, 'Saks': 1, 'Papir': 2}[val]
assert isinstance(val, int) & (val >= 0) & (val < 3)
self.value = val
def __eq__(self, other):
return self.value == othe... |
3153c6df49836cc64a8b4cf94a57c9bcf1b30927 | dgibbs11a2b/Module-9-Lab-Assignment | /Problem2NumList10.py | 711 | 4.1875 | 4 | #----------------------------------------
#David Gibbs
#March 10, 2020
#
#This program will use a while loop to append the current
#value of the current counter variable to the list and
#then increase the counter by 1. The while loop then stops
#once the counter value is greater than 10.
#------------------------------... |
6efd4db15c5bd72c01c320701715f3845ca25b4c | wanglun0318/pythonProject | /register.py | 1,587 | 4.15625 | 4 | # 注册新用户
def new_user():
username = input("请输入用户名:")
while username in accounts:
username = input("此用户名已经被使用请重新输入:")
else:
accounts[username] = input("请输入你的密码:")
print("注册成功,赶紧试试登录吧!")
# 用户登录
def old_user():
username = input("请输入用户名:")
while username not in accounts:
p... |
4764110d5c381f3322608d31b9498f87139a3d8d | wanglun0318/pythonProject | /mageic/iteratortest.py | 1,071 | 4.1875 | 4 | """
迭代是重复反馈过程的活动,其目的通常是为了接近并到达所需的目标或结果。每一次对过程的重复
被称为异常“迭代”,而每一次迭代得到的结果会被用来作为下一次的迭代的初始值
迭代器就是实现了__next__()方法的对象,用于遍历容器中的数据
__iter__(self) 定义当迭代容器中的元素的行为
__next__() 让对象可以通过next(实例名)访问下一个元素
"""
import datetime as dt
class LeapYear:
def __init__(self):
self.now = dt.date.today().year # 获取当前年份
def... |
c4c743fe497c8199d44382b9cb12b8603f5b0772 | wanglun0318/pythonProject | /threadingtest/mythread.py | 713 | 3.59375 | 4 | # coding=utf-8
import threading
import time
class MyThread(threading.Thread):
def __init__(self, name=None):
super().__init__(name=name)
# 线程体函数
def run(self):
# 当前线程对象
t = threading.current_thread()
for n in range(5):
# 当前线程名
print('第{0}次执行线程{1}'.... |
2c3247f1d594f0b16838c4652da30b0ae213ac06 | Hajime115/PythonLeaning | /solid/open_closed.py | 3,220 | 3.53125 | 4 | """開放閉鎖の原則
クラス、モジュール、関数等のソフトウェアの部品は拡張に対しては開いており、修正に対しては閉じているべき
・アプリケーションに変更があった場合、コードを追加して拡張し容易に対応できる
・モジュールの動作を変更する場合には、ソースコードを直接修正するようなことはないようにする
[開放閉鎖の原則を守った場合]
・機能拡張が用意になりソフトウェアの拡張性が向上する
・機能拡張時にテストをする際に、拡張機能だけを実施すればよく、元のソースコードはテストをしなくてよいため、保守性も向上する
"""
from abc import ABCMeta, abstractmethod
# 以下の実... |
5f2419e31f13480b0f111e5bed2fcdd596583808 | LuisCarlosVanegas/python-soccer-league | /TALLER1a/pitsluis.py | 1,769 | 3.609375 | 4 | Python 2.7.5 (default, May 15 2013, 22:43:36) [MSC v.1500 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> #Taller clase 3 variables y operaciones en python
>>> #Formula 1 con dos mecanico con rueda
>>> #Conocer tiempo en pits
>>> #Asignacin de variables llanta 1: m1= m... |
4f1a8bb336eacbb1aec1deef159d6850fd89bd2c | saadbinmehmood/python | /class_mod.py | 4,106 | 4.5 | 4 | """A class that can be used to represent a car."""
class Car:
"""A simple attempt to represent a car."""
def __init__(self, make, model, year):
"""Initialize attributes to describe a car."""
self.make = make
self.model = model
self.year = year
self.odometer_reading = 0
... |
88a7b88a03606a092f532f6a4601c54dcd653351 | stjordanis/HackerRank-2 | /birthdaycakecandles.py | 227 | 3.765625 | 4 | import sys
arr = [3, 1, 2, 3]
n = len(arr)
def birthdayCakeCandles(n, ar):
max_height = max(ar)
max_count = 0
for i in ar:
if i == max_height:
max_count += 1
return max_count
print (birthdayCakeCandles(n ,arr))
|
53d711bc38f788303101a22b3c897cd51679eaa3 | stjordanis/HackerRank-2 | /marcscupcakes.py | 583 | 3.640625 | 4 | import more_itertools as mit
from pprint import pprint
c = [1, 3, 2]
n = len(c)
possible_miles = []
def random_permute_generator(iterable, n):
for _ in range(n):
yield mit.random_permutation(iterable)
possible_combos = (list(set(list(random_permute_generator(c, 20)))))
for combo in possible_combos:
... |
1656bde0a6e2c99cc6f077930ebf514706b04fe5 | fcifglez/Viagogo_Test | /events.py | 2,874 | 4 | 4 | #! /usr/bin/python
from generator import generate_world, X_MAX_COORDINATES, Y_MAX_COORDINATES, \
MAX_EVENTS_TO_FIND
"""
Function manhattan_distance().
:param x: x coordinate where the loop is working.
:param y: y coordinate where the loop is working.
:param x_coord: x coordinate the user inserted it in the te... |
935026fb0d4a747c28646f7cbc85c490e7285366 | LimbDarkening/University-Challenge | /UC_comp.py | 3,243 | 3.59375 | 4 | import wikipedia as wiki
import pandas as pd
from bs4 import BeautifulSoup
from datetime import datetime
def get_tables(title):
"""Get result tables from wikipedia titles"""
page = wiki.page(title)
soup = BeautifulSoup(page.html(), 'html.parser')
tables = soup.findAll("table", class_ = "wikita... |
84cce619cee66ec68eb13425e3d6c11ef2cb6ec1 | JonasKanuhsa/Python | /Survey/Survey.py | 573 | 4.1875 | 4 | '''
Make a program that can take survey information.
@author: Jonas Kanuhsa
'''
question = "What is your name?"
name = input("What is your name")
print(name)
response = "What is your favorite color?"
color = input("What is your favorite color?")
print(color)
var = = "What city did you grow up in?"
city = inp... |
34470c1a094803d2d08a3beb8a85fa948159e985 | NeveIsa/gatm | /accessories/scripts/generate_flip_table_alt.py | 543 | 3.8125 | 4 | elements = {"I" : [0,1,2], "f" : [0,2,1], "fr": [2,1,0], "fr^2": [1,0,2], "r": [2,0,1], "r^2": [1,2,0]}
def flip(elem1, elem2):
return [elem2[elem1[n]] for n in range(3)]
def name_from(elem):
for key in elements:
test_elem = elements[key]
if elem == test_elem:
return key
return... |
55e140f825c683bc5e7942b4167eb7dbe5e86bba | barmfield/Scikit-Classification-Demo | /malefemale.py | 1,920 | 3.6875 | 4 | from sklearn import tree
from sklearn import svm
from sklearn.neural_network import MLPClassifier as mlp
# features: height, weight, shoe size
X = [[70., 195., 10.], [73., 185., 11.], [63., 168., 7.], [60., 150., 8.], [65., 180., 9.], [73., 162., 11.], [65., 126., 7.], [63., 145., 7.], [62., 150., 9.], [68., 175., 9.]... |
ddec556daa5ef5f7ea3f0fa843117f6a04c4a7f7 | Karnak123/maznet | /xor.py | 544 | 3.8125 | 4 | """
Example of a function that can't be learned
with a simple linear model is XOR
"""
import numpy as np
from maznet.train import train
from maznet.nn import NeuralNet
from maznet.layers import Linear, Tanh
inputs = np.array([[0, 0], [1, 0], [0, 1], [1, 1]])
targets = np.array([[1, 0], [0, 1], [0, 1], [1, 0]])
net ... |
180fa2f991fb5f5b34455b3fdf283e956839364a | MarkF88/sudoku | /test.py | 3,194 | 3.640625 | 4 | import unittest
import main
class TestSquareMethods(unittest.TestCase):
def test_standard_create(self):
clue = main.ClueSquare(1)
def test_illegal_value_create(self):
with self.assertRaises(ValueError):
main.ClueSquare(0)
with self.assertRaises(ValueError):
m... |
2b7c14dabdd2f157a22aa5b51f40a07f46919826 | Raymond-He/HW | /GreedisGood.py | 2,730 | 3.71875 | 4 | # ===================================邱寶=================================
def score(dice):
buf_sum=[]
point={'trione':1000,'six':600,'trifive':500,'four':400,'three':300,'two':200,'one':100,'five':50}
for i in range(1,7):
dice_num = dice.count(i) #1~7 出現次數
if dice.count(i) == 4:
i... |
322cb9ef6c5cebfcbd6f764fe9d07b6e903f49b7 | Raymond-He/HW | /CenturyFromYear.py | 584 | 3.625 | 4 | def century(year):
if year<100: #one centry equal 100 years
return 1
else:
if year%100 != 0:
return int(year//100)+1
else:
return int(year//100)
# 測試
print(century(1705)) # , 18, 'Testing for year 1705')
print(century(1900)) # , 19, 'Testing fo... |
3568060ba5e5b2ee3f6f960e1b19010bda9580c4 | Raymond-He/HW | /class03_homework.py | 4,623 | 3.890625 | 4 | class course(): #課程的所有資料
def __init__(self,code,subject,credits,classification,intro,teacher,time):
self.code=code
self.subject=subject
self.credits=credits
self.classification=classification
self.intro=intro
self.teacher=teacher
self.time=time
def show(se... |
19cd3ea326470e33e33e732ca2f8b8ca3b90059b | MistyLeo12/Learning | /Python/Functional-Programming/Learning-Concepts.py | 3,553 | 3.921875 | 4 | """
Since all of my classs are focused on OOP, we never have learned functional
programming. In order to become a better programmer I want to learn about functional programming.
I feel like it will help my code logic, writing less buggy code, provide a new way of thinking how to approach problems,
and create interest... |
f0345277450b059093e85d4a310eddb279d501ea | MistyLeo12/Learning | /Python/double_linked.py | 1,967 | 4.21875 | 4 |
class Node(object):
def __init__(self, data = None):
self.data = data
self.next = None
self.prev = None
class doublyLinkedList(object):
def __init__(self):
self.root = Node()
self.size = 0
def get_size(self):
current = self.root
counter = 0
... |
c4129c116967c65bdcee3cbdcf55b61c80c2a0d3 | kin6jam3s/PythonProject | /statistics_standin_for_python.py | 2,931 | 3.90625 | 4 | import statistics
def mean(data):
# return 0
total = 0.0
count = 0
for x in data:
count += 1
total += x
print('the count is {:,}'.format(count))
print('the total is {:,}'.format(total))
Ttal = total / max(1, count)
print(' The total is: {}'.format(Tt... |
da11b4c7fdf486d72914db90af4b471bb91709bf | ErickMwazonga/learn_python | /others/mothly_rate.py | 1,097 | 4.1875 | 4 | import locale
# set the locale for use in currency formatting
result = locale.setlocale(locale.LC_ALL, '')
if result == 'C':
locale.setlocale(locale.LC_ALL, 'en_US')
# display a welcome message
print("Welcome to the Future Value Calculator")
# print()
choice = 'Y'
while choice.lower() == 'y':
# get input from the ... |
9993613685661b02c2bdcaa37735d768fe2caeaa | ErickMwazonga/learn_python | /lists/commad_list.py | 118 | 3.84375 | 4 | list = range(0, 10)
for i in list:
if list[i] == list[-1]:
print(i)
else:
print(i, end=', ')
|
4379aa92dfb3e93b93043afc2424c78c5eaad094 | ErickMwazonga/learn_python | /strings/make_ing_form2.py | 596 | 4.09375 | 4 | def make_ing_form(verb):
vowels = 'aeiou'
if verb.endswith('ie'):
return verb[:-2]+'ying'
elif verb.endswith('e'):
return verb[:-1]+'ing'
elif verb.endswith('ie'):
return verb[:-2]+'ying'
elif(len(verb) == 3) and (verb[0] not in vowels) and (verb[1] in vowels) and (verb[2] no... |
1dec9dc034a58bad85bc7c26098fbdb012550b49 | 09-03/Infa | /Exam/UPD/1.py | 636 | 3.765625 | 4 | """
Написать программу, которая объединяет и выводит текст из двух внешних файлов,
предварительно проверив не совпадает ли он.
"""
import filecmp
if filecmp.cmp("1.1.txt","1.2.txt", shallow=False):
print("Контент совпадает")
else:
print("Контент не совпадает")
f1 = open("1.1.txt", 'a+', encoding="utf-8")
f2 = ... |
cfb07f516526667d6ca2333615152e93b299ea41 | 09-03/Infa | /University_Python/Fib_and_NOD.py | 455 | 3.671875 | 4 | def fib(n):
if n == 0 or n == 1:
return 1
else:
return fib(n-1)+fib(n-2)
def fib_series(n):
for num in range(n):
if num == n-1:
print(fib(num))
else:
print(fib(num), end = " ")
def NOD(a,b):
while a != 0 and b != 0:
if a ... |
c75f229bf209fb251f09cac3f2c7746a8c834007 | 09-03/Infa | /Exam/UPD/7.py | 591 | 4.125 | 4 | """
Реализовать программу, способную находить наибольший и наименьший элемент в
списке и менять их местами. Список задается с клавиатуры
"""
list = [int(i) for i in input("Введите список чисел через пробел: ").split()]
max_value = max(list)
min_value = min(list)
for n in range(len(list)):
if list[n] == min_value:
... |
428db350d117addcda175705712278fe8a86fb30 | 09-03/Infa | /University_Python/median.py | 1,252 | 3.75 | 4 | import random
massive_n = [i+1 for i in range(int(input("Введите длину массива n: ")))]
def iter(list):
massive_m = []
m=int(input("Введите длину итогового массива m: "))
counter = 0
done = False
i = 1
while not done:
if random.random() < 1/len(list):
x = list[i-1]
... |
7a9d255c768443b4f985a5dfec562565f7944dad | 09-03/Infa | /University_Python/Text_Finder.py | 1,833 | 4.03125 | 4 | def sorting_and_printing(dictionary, label):
ans = ""
sorted_dict = {k: v for k, v in sorted(dictionary.items(), key = lambda item: item[1], reverse = True)}
values_view = sorted_dict.values()
value_iterator = iter(values_view)
max_value = next(value_iterator)
print(f"Наиболее {label} сл... |
d620371ad14eed959059b7340b06a8b356a9d1e0 | Ishant-Dhall/CSE5APG--Advance-Python | /Text file Analysis.py | 3,644 | 3.96875 | 4 | #!/usr/bin/env python
# coding: utf-8
# Task 1: Printing the file contents
with open("/Users/ishantdhall/Desktop/BusRouteLA.txt",'r') as file: # File path (Please enter your file path)
for line in file:
for word in line.split(":"):
print(word)
#Task ... |
404e87af19af52627120f2671bfc1cdc8ebf9d75 | W25306/Algorithm | /JH/solution_2021_03_05.py | 574 | 3.640625 | 4 |
from collections import deque
n = int(input())
array = list(map(int, input().split()))
array.sort()
m = int(input())
x = list(map(int,input().split()))
def binary_search(array,target,start,end):
while start <= end:
mid = (start + end) // 2
if array[mid] == target:
... |
2b6941b6d4efd6954368da6a008a96fceb7dbcc4 | W25306/Algorithm | /JH/solution_2021_01_25.py | 1,388 | 3.71875 | 4 | import math
def getDayName(a,b):
months = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
days = ['FRI', 'SAT', 'SUN', 'MON', 'TUE', 'WED', 'THU']
return days[(sum(months[:a-1])+b-1)%7]
def solution(n):
answer = 0
three_answer = []
while(n >= 1):
number = n % 3
three_answer.in... |
5559bd491bc42c83588b9064df0c9227e58f0e49 | Lolita05/python_homework | /4.lists_tuples_cycles/4.7.py | 306 | 3.828125 | 4 | # Программа, отбирающая из коллекции чисел только чётные, а затем считающая их сумму
interesting_numbers = (3, 2, 5, 7, 14, 26, 32, 31, 37)
b = []
for i in interesting_numbers:
if i % 2 == 0:
b.append(i)
s = sum(b)
print(s)
|
e83ee4d36747a07dcbce79881baaf48fd70f9bdc | Lolita05/python_homework | /11.numpy_random_simulations/11.4.py | 798 | 3.71875 | 4 | #random walk 1d
import random
import numpy as np
import matplotlib.pyplot as plt
#возможности ходить вверх или вниз
prob = [0.05, 0.95]
#начальная точка
start = 0
positions = [start]
#генерим рандомные точки
rr = np.random.random(1000)
downp = rr < prob[0]
upp = rr > prob[1]
for idownp, iupp in zip(downp, upp):
... |
52fc72662294719facdecf31effb521654736591 | Lolita05/python_homework | /3.numbers_booleans_conditions/3.3.py | 1,966 | 4.09375 | 4 | # Вывод таблиц истинности
# not
def NOT(a):
if(a == False):
return True
elif(a == True):
return False
def main():
print("| a | not a |")
print("-------------")
for a in [False, True]:
print('|', a, '|', NOT(a), '|')
main()
# or
def OR(a, b):
if a is True:
re... |
fca8476742f6fd8a9163c1b448766ec7d8630678 | Lolita05/python_homework | /5.sets_dicts_strings/5.7.py | 478 | 3.734375 | 4 | #Разверните строку всеми известными вам способами
#1
s = 'agatacaca' [::-1]
print = s
#2
s1 = 'agatacaca'
s2 = ''
i = len(s1)-1
while (i>=0):
s2 = s2 +s1[i]
i = i-1
print(s2)
#3
def r(s):
if len(s) == 0:
return s
else:
return r(s[1:]) + s[0]
s1 = 'agatacaca'
s2 = r(s1)
print(s2)
#4
s ... |
3a1ec66f75079c122d1422a16a6588f00d74c85a | Lolita05/python_homework | /6.functions/6.1.py | 182 | 3.546875 | 4 | #flat list
def flatten(li):
return sum(([x] if not isinstance(x, list) else flatten(x)
for x in li), [])
l = [[1, 2, 3], [4, 5, 6], [7], [8, 9]]
print(flatten(l)) |
ad48eda38d19bb76847d08e4aa8fbdab718581bf | cesarbhering/30-days-of-code-HackerRank | /26-NestedLogic.py | 743 | 3.578125 | 4 | DataDevolucao = list(map(int, input().split(" ")))
DataPrevista = list(map(int, input().split(" ")))
if DataDevolucao[2] == DataPrevista[2] and DataDevolucao[1] == DataPrevista[1]:
if DataDevolucao[0] <= DataPrevista[0]:
print("0")
elif DataDevolucao[0] > DataPrevista[0]:
print((int(DataDevoluc... |
85c7222686015f91f512afc68fa49a2d3689f67a | edithclaryn/march | /hobbies.py | 251 | 4.28125 | 4 | """Create a for loop that prompts the user for a hobby 3 times, then appends each one to hobbies."""
hobbies = []
# Add your code below!
for i in range(3):
hobby = input("Enter your hobby: ")
print (hobby)
hobbies.append(hobby)
i += 1 |
0a2280f39b0f3bcc6ed11af2df1001813cc342b9 | edithclaryn/march | /battleship.py | 945 | 4.21875 | 4 | """Create a 5 x 5 grid initialized to all 'O's and store it in board.
Use range() to loop 5 times.
Inside the loop, .append() a list containing 5 "O"s to board.
Note that these are capital letter "O" and not zeros."""
board = []
for i in range(0,5):
board.append(["O"]*5)
print (board)
#Use the print command to displa... |
c8c29d8d657fd8ab858e7135ecb18c5d94976487 | M-Isonni/Python_binary_search | /aiv_python_func.py | 612 | 3.984375 | 4 | def binary_search(my_list: list, k: float, head_index: int, tail_index: int):
if head_index >= tail_index:
return "not found"
index = head_index+(tail_index-head_index)//2
if(k < my_list[index]):
index -= 1
index = binary_search(my_list, k, head_index, index)
return index
... |
967cd4aa51942d592efd9535b0bc3f21d89a98d9 | CookieNoob/Reaction-Diffusion-Simulation | /RD_Grafics.py | 856 | 3.515625 | 4 | # Create window and display functions to visualize the simulation results
import pygame
pygame.font.init()
class display:
def __init__(self, sizeX, sizeY, initialgrid, scalefactor):
self.sizeX = sizeX
self.sizeY = sizeY
self.window = pygame.display.set_mode( (scalefactor * sizeX, scalefact... |
3ddc69ffc512f525362567e96874d3d822760aeb | saramargolin/TurtleDesignProject | /myfunctionfile.py | 1,342 | 3.859375 | 4 | #Create a polygon function that accepts a turtle, side, and distance.
#myfunctions file
def polygon (t,s,d) : #parameters -> (information)
a = 360/s #angle variables is inside the function
t.begin_fill()
for times in range (s) :
t.forward(d)
t.right(a)
t.end_fil... |
6f037a9c5198c85d043cf623330602e760dca527 | saigjiej/python_study | /1차원 배열/3052.py | 402 | 3.53125 | 4 | # 3052번 : 나머지
arr = [] # 리스트 초기화
for i in range(10): # 10번 반복 (수 10개 입력)
n = int(input()) # 수 입력
arr.append(n % 42) # arr에 입력받은 수를 42로 나눈 나머지를 저장
arr = set(arr) # 중복된 값 자동으로 중복 제거
print(len(arr)) # 서로 다른 값이 몇 개 있는지 출력하기 위해 len() 이용하여 arr 길이 출력 |
c9aeab596521c7726b83ada84d42dc6c30e46aef | nimishkapoor/Machine_leaning | /ml12decisiontree.py | 795 | 3.5625 | 4 | import pandas as pd
from sklearn.preprocessing import LabelEncoder
from sklearn.tree import DecisionTreeClassifier
df=pd.read_csv('https://raw.githubusercontent.com/codebasics/py/master/ML/9_decision_tree/salaries.csv')
inputs=df.drop('salary_more_then_100k',axis='columns')
target=df['salary_more_then_100k']
le_... |
a2cc25fdde811676e069c62b1929cf6a5a3909da | albertyumol/code_demo | /knn_from_scratch.py | 5,006 | 4.03125 | 4 | # -*- coding: utf-8 -*-
"""K-Nearest Neighbor Algorithm From Scratch.
KNN predicts a target variable based on feature variables.
The algorithm requires a training set to use for prediction.
The prediction will be done by looking into K number of
nearest neighbors in the training set, and get the mode
(if classifi... |
1bad4337c3402841af19907cf385d53cae534574 | dalisyron/faylManayjer | /terminal_ui.py | 197 | 3.734375 | 4 | import item
def printItemList(item_list):
mx = 0
for i in item_list:
mx = max(mx, len(i.name))
for i in item_list:
print('{}{}{}'.format(i.name, ' ' * (mx + 5 - len(i.name)),i.date)) |
33687e2c0e74847820148b9af07a76f7018c018e | SamadFelouach/SnakeGame | /script.py | 1,274 | 3.828125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Sep 2 12:43:06 2020
@author: Avicii
"""
import turtle
import time
delay =0.1
#set up the screen
window =turtle.Screen()
window.title("my amazing game by @Avicci")
window.bgcolor("green")
window.setup(width=600 , height =500)
window.tracer(0)#turn off the screen updates
... |
4e829fdec4c5fffd5bef7308c6e9c44862338c7e | bettyariyani/Python-Beginner | /숫자 맞추기 게임_연습.py | 418 | 3.859375 | 4 | from random import randint
x = randint(1,20)
for i in range(1,5):
if i < 5:
y = int(input("기회는 %d 번 남았습니다.:" %(5 - i)))
if x > y:
print("UP")
elif x < y:
print("DOWN")
else:
print("CORRECT %d번만에 맞췄습니다." %(5 - i))
break
i... |
40dc21c2a29813e203d6ba0a3146f252f7b5b886 | woxiaosa/ML_code | /提升方法/AdaboostClassification.py | 2,750 | 3.59375 | 4 | '''
Adaboost 分类算法
'''
import numpy as np
import pandas as pd
def clf_great_than_(x_, v_):
"""
weak learner
:param x_:
:param v_: threshold
:return: classify results
"""
y_ = np.zeros(x_.size, dtype=int)
y_[x_ > v_] = 1
y_[x_ < v_] = -1
return y_
def clf_less_than_(x_, v_):
... |
6d8bcd126f40f120873fb0de59adb9e2fe2e4e1e | wulandy/pyds | /bracket.py | 852 | 3.65625 | 4 | import argparse
from itertools import izip
def bracketMatch(s):
q=list();
left=('(','[','{')
right=(')',']','}')
all=set(left) | set(right)
dic = dict(izip(right, left))
for i in s:
if i in all:
if i in left:
q.append(i)
else:
if q=... |
0636306eeab9e035d7323d0da46e626fb550a25a | wulandy/pyds | /BST.py | 2,111 | 3.625 | 4 | #coding=utf-8
#二叉搜索树的创建
import argparse
from binarytree import Node,pprint
def insertBST(s,node):
if s==None:
s=node
elif node.value<=s.value:
s.left=insertBST(s.left,node)
else:
s.right=insertBST(s.right,node)
return s
def createBST():
N=None
list=[41 ,467 ,334 ,500, 1... |
9d44db64af8758f0140ac0e7167610023eceb89b | BMoClay/chandlers-flictionary | /api/simple_conv_nn.py | 1,985 | 3.71875 | 4 | # used code from https://blog.algorithmia.com/convolutional-neural-nets-in-pytorch/
# import linear algebra and data manipulation libraries
import numpy as np
import pandas as pd
# import pytorch
import torch
from torch import nn
import torch.nn.functional as F
class SimpleCNN(nn.Module):
#Our batch shape for i... |
291b9fcbb8a201634e37bc6ffded8ca809404b6e | nahymeee/comp110-21f-workspace | /exercises/ex05/utils.py | 1,120 | 4.125 | 4 | """List utility functions part 2."""
__author__ = "730330561"
def only_evens(first: list[int]) -> list[int]:
"""Gives back a list of only the even numbers."""
i: int = 0
evens: list[int] = []
while i < len(first):
if first[i] % 2 == 0:
evens.append(first[i])
i += 1
ret... |
1fa3d5c779bd42bc85ff4587596622425cafbd31 | nahymeee/comp110-21f-workspace | /exercises 2/ex04/utils.py | 941 | 3.828125 | 4 | """List utility functions."""
__author__ = "730330561"
def all(list: list[int], number: int) -> bool:
"""Checking for the number."""
i: int = 0
while i < len(list):
if list[i] == number:
return True
i += 1
return False
def is_equal(first: list[int], second: list[int]) ->... |
7f55bd221b61b10d7fc5022233b4d71c45768eed | charlesboudousquie/FuzzyChess | /takagi_sugeno.py | 2,145 | 3.546875 | 4 | import fuzzy_number as fn
class Consequence:
# Consequence part for the fuzzy system
def __init__(self, line):
self.line = line
def __call__(self, inputs):
result = 0
# multiple antecedents
for x, a in zip(inputs, self.line):
result += x * a
... |
c697f07cf7e0d05c8a130ecdab1d38e5e16497e8 | iamgoangle/python-101 | /example/07_in_operation.py | 170 | 4 | 4 | #!/usr/bin/python
lists = ['a', 1, 2, 3, True]
if ( 'a' in lists ):
print 'Yeh, your search is in list'
else:
print 'Sorry!, we did not found your search!!' |
1c3804aa69cd247abd5e567121bcf815a3f84f07 | williamlhunter/DiceSim | /dist_transformer.py | 1,093 | 3.671875 | 4 | # DiscreteDist is a class that extends list with changes to magic methods such that mathematical operations behave like they do on discrete probability distributions.
# I wrote this to work on dice, so it only supports ptobability distributions with a sample space in the set of natural numbers
class DiscreteDist(list):... |
305d7a62241225d85577ee03a012fc7cadbacb0f | RonanChance/Rorschach | /PsychProject.py | 3,675 | 3.828125 | 4 | import os
# Initializing some variables
a = 0
b = 0
c = 0
d = 0
e = 0
f = 0
g = 0
L = 0
# Question List
question = "What Emotion did the Image Elicit"
options = "A.Fear\nB.Violence\nC.Sadness\nD.Joy\nE.Disgust\nF.Suprise\nG.Trust"
# start of actual program
print("_____________________________________________________... |
73e05950c6286e9f4d3835c6d00d487be2cf7565 | Godsmith/adventofcode2015 | /day24/main.py | 3,071 | 3.65625 | 4 | __author__ = 'Filip'
from operator import mul
def step_through_set(current_set, remainder, target_sum, possible_sets):
for value in remainder:
new_set = current_set | {value}
new_remainder = remainder - {value}
sum_ = sum(new_set)
if sum_ < target_sum:
step_through_set(... |
dd48757d02b87fbc03d83f79cbbb1151e06d54f1 | Godsmith/adventofcode2015 | /day19/main2.py | 1,339 | 3.703125 | 4 | __author__ = 'Filip'
class Replacement:
def __init__(self, s):
split_string = s.split(' ')
self.source = split_string[0]
self.target = split_string[2][:-1]
self.num_molecules = sum(1 for c in self.target if c.isupper())
def __repr__(self):
return '({}, {}, {})'.format(s... |
7c15838e130ead199b37aec0c5d8c4eceaf6c785 | Godsmith/adventofcode2015 | /day12/main2.py | 449 | 3.5625 | 4 | __author__ = 'Filip'
import json
number_sum = 0
def parse(object):
global number_sum
if type(object) is list:
for i in object:
parse(i)
if type(object) is dict:
if 'red' in object.values():
return
for i in object.values():
parse(i)
if type(o... |
cbd1fffa49978be8ee5de594a445e857ecc28863 | Godsmith/adventofcode2015 | /day07/main.py | 1,561 | 3.515625 | 4 | __author__ = 'Filip'
from collections import defaultdict
def parse(value):
if value.isdigit():
return int(value)
else:
return wires[value]
def exists(value):
return value.isdigit() or value in wires
def all_input_exists(input_list):
for inp in input_list:
if not exists(inp):
... |
db7140ca11b509575bc7980bdd9774400c61776e | binnz/leetcode-for-practice | /array/1424-diagonal-traverse-ii.py | 472 | 3.640625 | 4 | """
Leetcode 1424
https://leetcode-cn.com/problems/diagonal-traverse-ii/
Input: nums = [[1,2,3,4,5],
[6,7],
[8],
[9,10,11],
[12,13,14,15,16]]
Output: [1,6,2,8,7,3,9,4,12,10,5,13,11,14,15,16]
"""
def findDiagonalOrder(nums):
res = []
for i ... |
0eb9b9cd9beda67126fa01ae724651526c3f2dff | binnz/leetcode-for-practice | /one_to_five_h/33-search-in-rotated-sorted-array.py | 2,359 | 4.0625 | 4 | """
Leetcode 33
https://leetcode-cn.com/problems/search-in-rotated-sorted-array/
"""
def search(nums, target):
length = len(nums)
left = 0
right = length - 1
if not nums:
return -1
while left < right:
mid = (left + right) >> 1
if nums[mid] == nums[right]:
... |
d9d213d4ae71f475898ee3c3e321317da9e7567a | santiagoHV/pygroup-2021-1 | /Clase3/funciones.py | 1,085 | 4.0625 | 4 | # nombre = input('Ingrese su nombre: ')
# edad = int(input('Ingrese su edad: '))
def verificar_edad(nombre, edad):
notificacion = ''
if edad > 18:
notificacion = f'{nombre} es mayor de edad'
#saludo(nombre)
elif edad == 18:
notificacion = f'{nombre} es mayor de edad, ya puedes ir p... |
885caf90bdcd4a50179894a92e3a07bdfe323e50 | rupertotorres1/UBCCourseScraper | /main.py | 2,420 | 3.671875 | 4 | import xlrd
# Use the excel workbook with the courses
book = xlrd.open_workbook("UBCCourseSubjects.xlsx")
courseList = []
# Read each sheet (each sheet is for a subject)
for sheet in book.sheets():
startRow = 0
endRow = 0
noCourses = False
# Mark the row where the offered courses would start to be listed in t... |
2ba75aaee15e9d2f92ca598ca67146c8f7132661 | mucheniski/python-exemplos | /lacos-repeticao-for.py | 137 | 3.53125 | 4 | listaNumeros = [1,2,3,4,5]
listaString = ["um","dois","tres"]
listaMultipla = ["um",2,3.0,True]
for i in listaNumeros:
print(i) |
d49b2a57a3f29f1cfb2d8f32d7a0edba81a2d92d | mucheniski/python-exemplos | /exercicios/equancao-segundo-grau.py | 451 | 3.90625 | 4 | # Escreva um programa que resolva uma equação de segundo grau.
# Δ = b2 – 4ac
from math import sqrt
a = int(input("Digite o valor de A: "))
b = int(input("Digite o valor de B: "))
c = int(input("Digite o valor de C: "))
delta = b**2 - 4*a*c
raiz_delta = sqrt(delta)
if raiz_delta < 0:
print("Delta n... |
a5d9456a0bfc97f70d8555b4c9ce4f34c543edb3 | mucheniski/python-exemplos | /exercicios/operacao-matematica.py | 477 | 4.125 | 4 | # Escreva um programa que receba dois números e um sinal, e faça a operação matemática definida pelo sinal.
n1 = int(input("Digite o primeiro número: "))
n2 = int(input("Digite o segundo número: "))
operacao = input("Digite o sinal da operação: ")
calculo = 0
if operacao == "+":
calculo = n1 + n2
elif o... |
ce7564f4777b5aea262e43b1b3a536035838cb0c | billturner/roguelike_tcod | /functions/randomize.py | 747 | 3.78125 | 4 | from random import randint
from typing import Dict, List
def from_dungeon_level(table: List, dungeon_level: int) -> int:
for (value, level) in reversed(table):
if dungeon_level >= level:
return value
return 0
# TODO: should this return 0 by default?
def random_choice_index(chances: List... |
be4255e432f58cd4006eedd38468a37f7a3e6065 | gagank02/UIUC-CS196-MiniGame-Collection | /fallingObjects/all_elements.py | 3,981 | 3.75 | 4 | import pygame
from random import randint
from fallingObjects.constants import *
class Drop_Block(pygame.sprite.Sprite):
"""determines properties and behaviors of falling objects
Attributes:
__horizontal_move_direction (int): direction of movement of drop block
... |
ce024a4b4621a3c0ab2cb38e0cc3f3fcc090df0f | OleksandrMakeiev/python_hw | /solve_quadratic_equation.py | 968 | 3.734375 | 4 | import math
print('Home Work 19.11.17')
print('----------------------------------------------------------------------------------------------')
print()
print('17 Написать функцию решения квадратного уравнения.\nОпределение функции:def solve_quadratic_equation(a, b, c): # return 2 valuespass')
print()
print('Введите зн... |
a58771ea2b2da493ae6cc1cd157973672c6b8c66 | OleksandrMakeiev/python_hw | /def group_by_surname.py | 986 | 4 | 4 | # 22
string = input("Введите имена и фамилии студентов через запятую на английском языке (пример: John White, Gregory House, Jack Smith, Jay Z): ")
list_of_enrollees = string.split(",")
def group_by_surname(list_of_enrollees):
enrollees_AtoI = 0
enrollees_JtoP = 0
enrollees_QtoT = 0
enrollees_UtoZ = 0... |
2fa26ba8b2a8d65a7ba9b25563ead016a244d4e6 | Ficcadenti/Codewars | /Python/Permutations/it/raffo/codewars/kata.py | 228 | 3.890625 | 4 | '''
Created on 27 ago 2020
@author: raffa
'''
import itertools as it
def permutations(string):
return [''.join(strn) for strn in
list(set(it.permutations(string, len(string))))]
print(permutations('ab')) |
3fd917110db090012e1414ffd14bb3d78ba0adf2 | DePavelPo/python_training | /2/third_example.py | 1,781 | 4.03125 | 4 | # Написать программу декодирования телефонного номера для АОН.
# По запросу АОНа АТС посылает телефонный номер, используя следующие правила:
# — Если цифра повторяется менее 2 раз, то это помеха и она должна быть отброшена
# — Каждая значащая цифра повторяется минимум 2 раза
# — Если в номере идут несколько цифр подряд... |
95b0343744ac233509f835174d0d0c42e3b3ed17 | Anush-Sa/HTI-3-Group-3-Anush-Sahakyan | /Homework_5/is_palindrome.py | 264 | 4.09375 | 4 | def is_palindrome(p):
if len(p) < 1:
return True
else:
if p[0] == p[-1]:
return is_palindrome(p[1:-1])
else:
return False
s = str(input("Enter string: "))
print("Yes" if is_palindrome(s) == True else "No" )
|
0bf2ebd61d238be82fe7050be8809b8197dd6791 | Anush-Sa/HTI-3-Group-3-Anush-Sahakyan | /Homework_2/is_lucky.py | 243 | 3.609375 | 4 | line = input()
divider = len(line) // 2
line1 = line[:divider]
line2 = line[divider:]
sum_1 = sum([int(i) for i in list(line1)])
sum_2 = sum([int(i) for i in list(line2)])
if sum_1 == sum_2:
print('Yes')
else:
print('No')
|
279f27468b66098f475328b88ea1d69756ce0577 | marc9323/cis-2531 | /Lab 3/Marc-Holman-17-WIFI-Diagnostic-Tree.py | 2,063 | 4.0625 | 4 | """
Marc D. Holman
9 / 9 / 2019
CIS 2531 Introduction To Python Programming
Lab 3: WI-FI Diagnostic Tree
"""
# define some constants
SUCCESS = "Great! Exiting program..."
DID_IT_FIX = "Did that fix the problem?"
# initial output, welcome
print("Welcome to WIFI Diagnostic Program:")
print("Start by reboo... |
764273f5fcb3abc201ed80578b94ce3f3767e444 | marc9323/cis-2531 | /scratchpad/zip.py | 91 | 3.734375 | 4 | one = ['a', 'b', 'c', 'd']
two = ['1', '2', '3', '4']
a = zip(one, two)
print(list(a)) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.