blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
e950c5cee913072ae91fdefca5511395000c9278 | AssiaHristova/SoftUni-Software-Engineering | /Programming Fundamentals/dictionaries/softuni_parking.py | 743 | 3.921875 | 4 | n = int(input())
users = {}
for i in range(n):
command = input().split()
if 'register' in command:
username = command[1]
plate_num = command[2]
if not username in users:
users[username] = plate_num
print(f"{username} registered {plate_num} successfully")
... |
2dd42095e9421c895f3494b15b670b96a0ec549a | AssiaHristova/SoftUni-Software-Engineering | /Programming Basics/for_loop/hospital.py | 461 | 3.890625 | 4 | days = int(input())
patients_done = 0
patients_left = 0
doctors = 7
for day in range(1, days + 1):
patients = int(input())
if day % 3 == 0:
if patients_left > patients_done:
doctors += 1
if patients <= doctors:
patients_done += patients
else:
patients_done += doctor... |
7b0b50a2a1e4f6b8c5aaa3d53296c73703a8057b | AssiaHristova/SoftUni-Software-Engineering | /Python Advanced/stacks_and_queues/matching_brackets.py | 184 | 3.515625 | 4 | line = input()
s = []
for i in range(len(line)):
char = line[i]
if char == '(':
s.append(i)
elif char == ')':
j = s.pop()
print(line[j:i + 1])
|
0f25c7fe9cdde20c80e1a4abb0154200b91eca3b | AssiaHristova/SoftUni-Software-Engineering | /Programming Basics/exams/excursion_sale.py | 558 | 3.625 | 4 | sea_count = int(input())
mountain_count = int(input())
packet_type = input()
price = 0
while packet_type != "Stop":
if packet_type == "sea":
if sea_count > 0:
price += 680
sea_count -= 1
elif packet_type == "mountain":
if mountain_count > 0:
price += 499
... |
7c94fd7a926688dcf371030715a9c2f4e8c13f01 | AssiaHristova/SoftUni-Software-Engineering | /Programming Fundamentals/basics_syntax/patterns.py | 169 | 4.0625 | 4 | num = int(input())
for i in range(1, num + 1):
symbol = '*'
print(f'{symbol * i}')
for i in range(num - 1, 0, -1):
symbol = '*'
print(f'{symbol * i}')
|
630c63d8645e7a6f4be179eccdd96e6d2c87e678 | AssiaHristova/SoftUni-Software-Engineering | /Python OOP/testing/cat_tests.py | 1,446 | 3.71875 | 4 | class Cat:
def __init__(self, name):
self.name = name
self.fed = False
self.sleepy = False
self.size = 0
def eat(self):
if self.fed:
raise Exception('Already fed.')
self.fed = True
self.sleepy = True
self.size += 1
def sleep(self):
if not self.fed:
raise Excepti... |
56cdd8aa896a0c30e6c5d4c637cf1bb133d546d1 | AssiaHristova/SoftUni-Software-Engineering | /Python OOP/inheritance/random_list.py | 709 | 3.71875 | 4 | import random
class RandomList(list):
def get_random_element(self):
ele = random.choice(self)
self.remove(ele)
return ele
# test first zero
import unittest
from unittest import mock
class RandomListTests(unittest.TestCase):
def test_zero_first(self):
mocked_choice = lambda ... |
453a741b3231e66ae8797b6ed0d1a2a17be0549a | AssiaHristova/SoftUni-Software-Engineering | /Python OOP/defining_classes/project_2/trainer.py | 1,025 | 3.71875 | 4 | from project_2.pokemon import Pokemon
class Trainer:
def __init__(self, name):
self.name = name
self.pokemon = []
def add_pokemon(self, pokemon: Pokemon):
filtered_pokemons = [p for p in self.pokemon if p == pokemon]
if filtered_pokemons:
return "This pokemon is al... |
251e74141d0e2deb8df877cb77bdf9dafaf440c4 | moriano/deep-learning | /introTensorFlow/mnist.py | 3,404 | 4.34375 | 4 | import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
"""
Explore the dataset
Note that the X_train/y_train are not to be used directly in tensorflow,
except for evaluation purposes, this is here solely so one can easily look ... |
270a8943a447d7991fc9d82fda1ab65a81cd1a7a | RomanovMaxim/python-oop | /3. overload/indexer.py | 230 | 3.578125 | 4 | class Indexer:
def __getitem__(self, index):
return index ** 2
if __name__ == '__main__':
X = Indexer()
print(X[5])
for k in range(5):
print(f'{X[k]}', end=' ')
print(f'\n{Indexer()[11]}')
|
29fea4a3a53595102f307e2b5c0e88523d972574 | feocco/exercismPy | /meetup/meetupbackup.py | 1,019 | 4.28125 | 4 | import calendar
import datetime
def meetup_day(year, month, day, param):
weekdays = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
numOfDays = calendar.monthrange(year, month)
mydict = {}
tempList = []
meetupday = 0
#Creates dictionary with days of month & what weekday ... |
ef4f870d5ec7f37f26321c3d15cef0e4dc33a788 | feocco/exercismPy | /sieve/sieve.py | 277 | 3.796875 | 4 | def sieve(limit):
composites = []
primes = []
for number in range(2,limit + 1):
if number not in composites:
primes.append(number)
counter = 2
value = 0
while value < limit:
value = number * counter
composites.append(value)
counter += 1
return primes |
16b0f7617bf462dc06661dacbbb06f3d402aea60 | nitinjugal17/PythonPuzzle | /test.py | 1,781 | 3.765625 | 4 | # -*- coding: utf-8 -*-
from random import randint
import sys
# getting 10000 digit number using randint
rand_number = randint(10,9999**5630)
#print 'Random String Type :',type(rand_number)
#print 'Random String :',rand_number
#checking for the size of randint
#print 'Random String Length :',sys.getsizeof(rand_numb... |
b9e5c245fec7abd0e2f6e3d2c4ca58748d5dac37 | xaelek/python-practice | /reverse_text.py | 471 | 3.765625 | 4 | def reverseList(text):
textList = []
count = 0
for c in text:
textList.append(c)
for i in textList:
tempLetter = ""
tempLetter = textList.pop()
textList.insert(count, tempLetter)
count += 1
txet = "".join(textList)
return txet
#textList = ['a', 'b', '... |
956194ad4fada3d74792523abfa1403bd5f3df5c | Fazendaaa/the-python-mega-course | /src/SQL/postgre.py | 2,075 | 4.1875 | 4 | """This is a introduction program to Postgre -- see this video for more info: \
https://www.youtube.com/watch?v=YyAEho7sDro -- ps: mute this video and watch it\
with two times velocity"""
import psycopg2
# ---------------------------- FUNCTIONS ----------------------------- #
def create_table(filename):
... |
0cee0dc1b8a5283ec0b440affabef802955dcca4 | Fazendaaa/the-python-mega-course | /src/gui.py | 1,536 | 4.0625 | 4 | """This a simple program to convert minutes to seconds -- vice-versa"""
# pylint: disable=unused-import
from tkinter import *
# ------------------------ GLOBAL VARIABLES -------------------------- #
WINDOW = Tk()
FLAG = True
TEXT1 = StringVar()
TEXT2 = StringVar()
VALUE = StringVar()
TEXT1.set("Minutes:")
TEX... |
eab1ae22ebce3f782a3008939aaf4cc75a562191 | Fazendaaa/the-python-mega-course | /src/webscrapping/content.py | 361 | 3.640625 | 4 | """Examples of Python interacting with HTML"""
import requests
from bs4 import BeautifulSoup
REQ = requests.get('http://pythonhow.com/example.html')
SOUP = BeautifulSoup(REQ.content, 'html.parser')
print(SOUP, "\n")
CITIES = SOUP.find_all('div', {'class': 'cities'})
for ITEM in CITIES:
print(ITEM.find_all('h2')[0... |
9b726c035743cb5e057ba2aa862d0663d13923f1 | Shiva-Tripathi/Web-Scrap | /Project.py | 13,348 | 3.546875 | 4 | #PROJECT INCLUDES 2 SYSTEMS :
#1- RAILWAY ENQUIRY SYSTEM AND 2- MOVIE ENQUIRY SYSTEM
# Modules used : BeautifulSoup4 , requests , Selenium , time
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options impo... |
3f518765237f80fd34f5d74def9b62fb0688e870 | SumukhC/TwitterTextCaptureAndAnalysis | /TwitterTextAnalysis/ResultFetching.py | 1,650 | 3.53125 | 4 | from collections import defaultdict
from collections import Counter
#List of files according to the question asked
FileA = "./MaximumNoOfTweets.txt"
FileB = "./MaximumNoOfTweetsEveryHour.txt"
FileC = "./MaximumNoOfFollowers.txt"
FileD = "./MaximumNoOfRetweets.txt"
#The file to be read from
ResultFile_PATH =... |
feb26d978cd31cbaf61c35fddbd50378c92e0d94 | jinlin82/2020-python-learning-master | /Week2-Numpy/cy/zuoye1.py | 3,721 | 3.828125 | 4 | #1. 分别创建一个列表,元组,字典,并提取其子集
list1 = [1,2,'hello'] #列表
list1[1:3]
tuple = (1,2,'hello') #元组
tuple[1:3]
sex = ['男','男','女'] #字典
height = [183,181,165]
dict1 = {'sex':sex,'height':height};dict1
#2. 利用 numpy 生成一个一维数组和二维数组
import numpy as np
np.array([1,2,3,np.nan,5]) #一维数组
np.array([[1,2],[3,4],[5,6]]) #二维数组
#3. 0-100... |
b2629613b35800967ba7a509da594145400767e1 | jinlin82/2020-python-learning-master | /Week1-Basics/py_xiexinyue.py | 1,588 | 3.875 | 4 | 3+2
import matplotlib.pyplot
matplotlib.pyplot.plot([1,10])
import math
math.sin(3.14)
math.cos(0)
import numpy
numpy.random.rand(10)
import numpy as np
np.sinc(0)
import matplotlib.pyplot as plt
plt.plot([2,5])
import math as m
m.sin(0)
from math import sin
sin(0)
import numpy.compat
import matplotlib.pyplot
a... |
a7d3768571c181c73f9e6eacc973e52a9d9f3dd7 | jinlin82/2020-python-learning-master | /Week1-Basics/py_wangyue.py | 1,435 | 3.734375 | 4 | 3+2
import math
math.sin(3.14)
import matplotlib.pyplot
matplotlib.pyplot.plot([1,10])
import matplotlib.pyplot as plt
plt.plot([1,10])
import math as m
m.sin(0)
from math import sin
sin(0)
dir(__builtins__)
sys.builtin_module_names
from stdlib_list import stdlib_list
libraries = stdlib_list("2.7")
help("modul... |
bf5e6b2419b7e4efa46b9665f30577f93a5a036c | sk-ip/python-projects-for-absolute-beginners | /rolling dice simulator.py | 492 | 4.65625 | 5 | #
# Rolling dice simulator
#
# this is simple program in which the user has to provide the minimum
# and the maximum number for the dice which has n sides. the computer
# the computer will automatically roll the dice and give the number which
# shows up.
#
#
from random import randint
print... |
9103eb907d34cbb06a115f64eefda2b6816049a4 | gesley531/exercises | /exercicios/ex057.py | 313 | 3.890625 | 4 | # Gender Analyzer
gender = str(input('\n\033[32mPlease inform your gender [M/W]: ').upper().strip())
while gender != 'M' and gender != 'W' and gender != 'MAN' and gender != 'WOMAN':
gender = str(input('Please, inform a valid gender: '))
print('\n\033[33mYour gender has been added to the list!')
# END
|
42da4e5e8a9cb13011b5495ef030508da3309157 | gesley531/exercises | /exercicios/ex040.py | 512 | 3.515625 | 4 | # Analizador de notas
from time import sleep
fn = float(input('\nplease inform the students first note: '))
sn = float(input('\nNow, inform the second note: '))
calc = (fn + sn) / 2
sleep(2)
if calc >= 7.8:
print(f'\n\033[0:34mYour average is {calc:.1f}, congratulations YOU were APPROVED!!!\033[m')
elif calc ... |
eb101e75f5e06c30ad24290464cf2ba45a366e2d | gesley531/exercises | /exercicios/ex053.py | 341 | 3.890625 | 4 | # Detector de palíndromo
frase = str(input('\n\033[33mDigite uma frase: ').strip().upper())
palavras = frase.split()
junto = ''.join(palavras)
inverso = junto[::-1]
print(junto, inverso)
if inverso == junto:
print('\033[31mEstá frase é um PALÍNDROMO!!!')
else:
print('\033[31mEstá frase NÃO É UM PALINDROMO... |
c77754e99ac52ade5b750a569c192734766cf2d9 | irsol/python-exercises | /sequence_of_numbers.py | 466 | 4.3125 | 4 | # The filter will return all items from the list values which return True
# when passed to the function checkit. checkit will check if the value is in
# the set. Since all the numbers in the set come from the values list,
# all of the original values in the list will return True.
values = [1, 2, 1, 3]
nums = set(val... |
e2bf6cd58c35370f55ac340fcdfce82a8d22a8ee | irsol/python-exercises | /first_n_fibonacci_function.py | 429 | 3.96875 | 4 | #
# def fibo(num):
# n1 = 0
# n2 = 1
# result = [n1, n2]
# print("Fibonacci sequence: ")
#
# for n in range(2, num):
# n3 = n1 + n2
# result.append(n3)
# n1 = n2
# n2 = n3
# print(result)
#
# fibo(5)
def fibo(num):
result = [0, 1]
print("Fibonacci sequen... |
411c9c46e64c588e9b7d70cd079e9aab4885da71 | irsol/python-exercises | /boolean_practice/boolean_exercises.py | 3,448 | 4.53125 | 5 | # 3.1. Expression that evaluates to True if both variables are True
# and that evaluates to False otherwise
x = True
y = True
print(x and y)
# 3.2. Expression that evaluates to True if x is False and evaluates
# to False otherwise
x = False
y = True
print(not x)
# 3.3. Expression that evaluates to True if at least ... |
feaf58d0266bbc5a9d418e18cae61ae374a2a2ff | nabiharaza/Xcode-Sharding-and-Batching | /XCode.py | 18,691 | 3.53125 | 4 | map_right_rotated_to_original = []
map_left_rotated_to_original = []
final_right_rotated_matrix = []
final_left_rotated_matrix = []
def input(matrix_dimensions):
left_matrix = [[str(j) + "," + str(i) for i in range(matrix_dimensions)] for j in
range(matrix_dimensions)]
right_matrix = left_m... |
74f9c48e729e08149f3bfe2c5a3fb1f1326be2ad | sTayal11235/Auto_Mailer | /AutomatedMailSender/sendingServer.py | 984 | 3.625 | 4 | import pandas as pd
import smtplib, ssl
from email.mime.text import MIMEText
def sendingMail(Sender_mail, Sender_password, excel_location, subject, eMail):
# setting up server and logging in to the sender's mail through the server
# server 465 is secure server hence it is used
server = smtplib.SMTP_SSL('s... |
0a2bf1026c2cf9af0a86486feaf732943ccd148c | beferg/lpthw | /ex5.py | 704 | 4.03125 | 4 | my_name = 'Byron Ferguson'
my_age = 39 # not a lie
my_height = 68 # inches
my_weight = 240 # pounds
my_eyes = 'Hazel'
my_teeth = 'White'
my_hair = 'Black'
weight_in_kg = my_weight * .454
height_in_cm = my_height * 2.54
print(f"Let's talk about {my_name}.")
print(f"He's {my_height} inches tall.")
print(f"He's {my_weig... |
86b134d43107e0d11a069002f3fd9a1ff3c6b2da | SiddharthandTiger/Sid | /lottery no. 15654 .py | 125 | 3.625 | 4 | a=int(input("Enter your Ticket number"))
if(a==15654):
print("You won!!!")
else:
print("Better luck next time")
|
8e1c3911502b4d87f6da8cfe9da94c11571b79a3 | SiddharthandTiger/Sid | /code 4.py | 805 | 4.03125 | 4 | import random
coin =('heads','tails')
heads, tails = 0, 0
games=0
print('Hit x to exit')
while True:
flip= random.choice(coin)
your_choice = input('Type heads or tails')
if your_choice == 'x' or your_choice =='X':
print("GAME OVER :(")
print('Coin flipping stats:')
print('... |
377441518ab87e71cf2cb4190b427f2fd64fe166 | SiddharthandTiger/Sid | /greater no between three no.s finder.py | 271 | 4.0625 | 4 | a=int(input("Enter 1 no."))
b=int(input("Enter 2 no."))
c=int(input("Enter 3 no."))
if(a>b and a>c):
print(a,"is greater than",b,"and",c)
elif(b>a and b>c):
print(b,"is greater than",a,"and",c)
elif(c>a and c>b):
print(c,"is greater than",a,"and",b)
|
e4028d081bf190085f0b10a0c2315d01038fad4d | degritsenko/first | /python_lessons/task_1.py | 375 | 4.03125 | 4 | hi = ('hey you')
print ('hi')
print (type(hi))
dig = (1)
print ('dig')
print (type(dig))
city = ('Moscow')
location = input('Where do you live?')
if location == city:
print ('Moscow is nice city i guess')
else:
print ('Nice city too')
age = input("How old are you")
if int(age) <= 30:
print ('You are so y... |
2685320a91e344fc2b024ef9be006a8738c83cd6 | onionc/network-chip | /ApplicationLayer/WebServer/Client.py | 715 | 3.5625 | 4 | # coding:utf-8
# HTTP客户端。 格式:client.py server_host server_port filename
from socket import socket, AF_INET, SOCK_STREAM
import sys
args = sys.argv[1:]
if len(args) != 3:
print(r"(参数不足) 格式:.\client.py server_host server_port filename")
exit()
host, port, filename = args
# 创建Socket, 建立连接
clientSocket = socket... |
f171e4bd701c23846eac53f281ba74d586c9aa12 | haryoiro/CS50IntroductionHaryoiro | /psets/dna/dna.py | 2,371 | 3.65625 | 4 | from csv import reader, DictReader
from sys import argv, exit
import re
def main():
nm, l, tx = 0, 0, 0
if len(argv) != 3:
print("Usage: python dna.py data.csv sequence.txt")
exit(1)
# ヘッダのSTR(Short Tandem Repeats)を取得
try:
with open(argv[1]) as ptr:
if (argv[1]... |
a744966b9633109a6ed924b41568e1fcc3227f56 | Misza1037/physEngine2 | /vector.py | 1,031 | 3.84375 | 4 | #vector.py
#class:Vector
class Vector:
#__init__:<vector>, <int/float>, <int/float>
def __init__(self, x, y):
if type(x) not in [int, float]: raise TypeError( 'Vector.__init__().x' )
self.x = x
if type(y) not in [int, float]: raise TypeError( 'Vector.__init__().y' )
... |
9712317a5c9aa6c08d1bc6d7c443309a77b08189 | YasukoSasai/AI | /ch03/neuralnet_mnist_batch.py | 1,282 | 3.671875 | 4 | # =============== mnistに対して推論処理 ====================
import sys, os
sys.path.append('../')
import numpy as np
import pickle
from dataset.mnist import load_mnist
from common.functions import sigmoid, softmax
# def get_data():
(x_train, t_train), (x_test, t_test) = load_mnist(normalize=True, flatten=True)
def init_net... |
04ba8796f5d464a87db61819d904a4b3c5a7ac12 | YasukoSasai/AI | /ch06/weight_init_activation.py | 1,882 | 3.515625 | 4 | import numpy as np
import matplotlib.pyplot as plt
def sigmoid(x):
return 1 / (1 + np.exp(-x))
x = np.random.randn(1000, 100) #入力値。1000*100配列の乱数(0以上1未満)
node_num = 100 #隠れ層のニューロン数
hidden_layer_size = 5 #隠れ層は5層
activations = {} #アクティベーションの結果を格納。ディクショナリ
for i in range(hidden_layer_size): #5回繰り返す
if i != 0: #i... |
cfdcb0036e67bfc0bdf2e2039688daa3353a4015 | Jumner/compSci | /python/20/11/18 Data Types - 3/main.py | 3,501 | 4.125 | 4 | from datetime import date
from math import pi
from numpy import mean
total = 20 + 32
print(total)
power = 5**2
print(power)
expression = (5+9) * (15-7)
print(expression)
hour = 9
minute = 10
hour -= 1
totalMinutes = hour*60 + minute
print(totalMinutes)
x = 2
y = x + x
print(y) # Adds integers
s = "2"
t = s + s
p... |
016d764ebd6b56aa9153fc926fa4e5518115d30a | Jumner/compSci | /python/20/11/30/Exercise7.py | 939 | 3.671875 | 4 | # Conditionals - Exercise #7
def calculate_total_price( price, coupon_code ):
taxPrice = price+price*0.13
if coupon_code == "BONUS" or coupon_code == "BONUS40":
return taxPrice * (1 - 0.4) # Make it clear that it's a 40% discount
return taxPrice
def cleanPriceCalc(price,coupon):
taxPrice = price+price*0.13
cou... |
c29c5018a0ef22378cf06f5adaafb484f4df1162 | Jumner/compSci | /python/20/11/20 Functions - 5/eval.py | 345 | 3.671875 | 4 | from math import pi # Import constant pi
r = 5 # Radius of 5
sphereVolume = (4/3)*(pi)*(r**3) # Calculate volume
print(sphereVolume) # print volume
ageYears = 1.5*10**10 # 15b years old
# ageYears = 15000000000 # These two are the same
ageSec = ageYears * 365.2422 * 24 * 60 * 60 # Calculate age in seconds
print(ageSe... |
0959672755cc0257659bef3c863b1a6e90941966 | Jumner/compSci | /python/20/11/20 Functions - 5/practice.py | 1,591 | 4.21875 | 4 | from math import sqrt,pi
def hypotenuse(a,b):
c = sqrt(a**2 + b**2)
return c # I really don't find this any easier to read tbh
a = float(input("Enter the length of side a"))
b = float(input("Enter the length of side b"))
c = hypotenuse(a,b)
print(f'The hypotenuse of your triangle is {c:.1f}')
def convert_to_fah(c... |
ec828a643118d9fcd3b6014c586e9e4487cd57d4 | sunnykan/disaster-response-ks | /models/utils.py | 860 | 3.578125 | 4 | import re
from nltk.stem.wordnet import WordNetLemmatizer
from nltk.tokenize import word_tokenize
from nltk.corpus import stopwords
from nltk.corpus import words
from typing import List, Set
# create a set of English words using a corpus
stop_words: List = stopwords.words("english")
vocab: Set = set(words.words()) - ... |
434d41e2492f8968fb96ac182899a9751d9064d2 | hardik-2104/DS-Interview-Prep | /data-science-prep-master/code/expected_flips_two_heads.py | 710 | 3.84375 | 4 | """
Empirical evaluation of Question 2 -- `Flips until two heads`
(solved analytically in the pdf file)
"""
from common import bernoulli
ZERO, ONE, TWO = 0, 1, 2
BACKWARD, FORWARD = 0, 1
def experiment(p: float) -> int:
state = ZERO
steps = 0
while state != TWO:
steps += 1
if state == ZER... |
5e5f329e68117257d919225a0a53267afaec82e1 | jpaulovic/Asteroids | /data/components/ship.py | 6,919 | 3.515625 | 4 | """
This module contain Ship controlled by user and
other objects, that have close relation to ship.
"""
import math
import random
import pygame as pg
from . import components, laser
from .. import prepare, tools
SHIP_ENERGY_LOSS = 20
SHIP_BLINK_SPEED = 400 # both times when ship is fully visible and transparent
B... |
9188ad1b5c3753086a05b08a9de0f5db5fc8c828 | taejin0527/Exercism | /python/0. DONE/pangram/pangram.py | 240 | 3.8125 | 4 | from string import ascii_lowercase
def is_pangram(sentence='abcd1234_dfka'):
# pangram == a sentence using every letter of the alphabet at least once
ALPHABET = set(ascii_lowercase)
return ALPHABET.issubset(sentence.lower())
|
ec3425b3f306cd348ba90f4db07bda66134b9910 | Kshitijthegreat/Python_GUI_TKinter | /main.py | 3,840 | 3.578125 | 4 | import tkinter as tk
from tkinter import filedialog
import os
apps = []
# Define a function to save app list in a text file
def save():
global apps
file = open('save.txt', 'w')
for app in apps:
file.write(app + '\n')
def clrsv():
file = open('save.txt', 'w')
file.write(... |
52254db2de9a054e7a5309c92e70fc9f1fc2c01a | yoonicode/of-Algorithms | /010. Algorithm Practice [알고리즘 연습]/Find_same_number.py | 869 | 3.828125 | 4 | ''' 가장 효율적으로 리스트에 중복 요소가 있는 element를 찾아내는 코드 '''
def find_same_number(some_list):
for i in range(len(some_list)):
if some_list[i] in some_list[i+1:]:
# i번째 인덱스 이후 리스트에서 현재 위치의 요소와 동일한 요소가 있다면
return some_list[i]
# 현재 요소를 반환하고 수행을 종료
''' Dynamin Programming의 Memoi... |
d981916c80a3a49038933cdd94b78f80eb768510 | yoonicode/of-Algorithms | /007. Divide and Conquer [분할 정복]/Sum 1 to N.py | 1,180 | 3.71875 | 4 | ''' 분할 정복을 이용해 start ~ end의 값을 모두 더하는 코드'''
def consecutive_sum(start, end):
sum_l = sum_r = 0
mid = (start + end) // 2
# 문제를 분할하기 위해 input을 모두 더한 후 절반으로 나누어 중간값을 찾는다.
if start == end:
return start
# 시작하는 수와 마지막 수가 같은 경우 문제를 더 이상 분할할 수 없으므로 그대로 반환한다.
sum_l += consecutive_sum(sta... |
02a58e1de5978ed28463dcb33142ca876904f3ea | yoonicode/of-Algorithms | /006. Brute Force [무작위 대입]/Short Distance.py | 1,534 | 3.515625 | 4 | ''' 2개 좌표간의 최단거리를 계산하여 가장 가까운 좌표 2개를 return하는 코드'''
from math import sqrt
# 제곱근 사용을 위한 sqrt 함수 import
def distance(store1, store2):
return sqrt((store1[0] - store2[0]) ** 2 + (store1[1] - store2[1]) ** 2)
# 제곱근을 사용하여 파라미터로 받은 2개 좌표간의 거리 계산 후 return
def closest_pair(coordinates):
min = 500
# 최... |
909ee7e553cfb7f549280fcfee3b3322b2ea0780 | p-b-j/uscb-das-container-public | /das_decennial/programs/sparse.py | 3,122 | 3.703125 | 4 | import scipy.sparse as ss
import numpy as np
class multiSparse:
"""
This class is used to store a multi-dimensional numpy array as a sparse array and transform it back to a dense array when needed.
"""
def __init__(self, array, shape=None):
"""
constructor for class multiSparse
... |
1e7bee00f037400fe88c50571a52e0bd7112c5b9 | p-b-j/uscb-das-container-public | /das_decennial/programs/engine/rngs.py | 4,879 | 3.515625 | 4 | """
Module implementing the DASRandom, the random number generator used by DAS.
Usage:
from programs.engine.rngs import DASRandom
rng_factory = DASRandom
rng = rng_factory().randomState()
rng.geometric(p) retruns a random geometric
RNGs (primarily those, based on hardware, i.e. using RDRAND instruction)
and wrapping th... |
bee1f4e87974dcaddcbfee5bf41f6c70bd8ee6cd | tzy19910421/tzy-s-repsitory | /黑色数学/30题.py | 233 | 3.671875 | 4 | # 234345456567
# 3 6 9 12
# 三个数一组,从4开始
a = [2, 3, 4]
num = int(input('输入你想得到的数的位数:'))
for i in range(3, num, 3):
a.extend([a[i - 3] + 1, a[i - 2] + 1, a[i - 1] + 1])
print(a[len(a) - 1]) |
776ed867d79102673914595c9f6dc3283e8e57ef | irayarka/Homeworks | /task_178c.py | 274 | 3.90625 | 4 | from math import sqrt
# getting input data
n = int(input())
sequence = [int(input()) for i in range(n)]
counter = 0
for element in sequence:
root = sqrt(element)
if root ** 2 == element and root % 2 == 0:
counter += 1
# printing the result
print(counter)
|
cba78b1091370d392117a7ecafca54c8900e8b03 | EuleeKwon0217/codefights | /18.palindromeRearranging.py | 241 | 3.578125 | 4 | def palindromeRearranging(inputString):
count = False
for i in set(inputString):
if inputString.count(i)%2 !=0:
if count:
return False
else:
count = True
return True |
005cd5fb0668caf0f6a1ced15f9ca15b82e0414b | saukumar95/python_tutorials | /quadraticEquation.py | 280 | 3.59375 | 4 | import cmath
a = int(input('Enter a: '))
b = int(input('Enter b: '))
c = int(input('Enter c: '))
# Calculating discrimant
d = (b**2)-(4*a*c)
# two solutions
sol1 = (-b - cmath.sqrt(d)/(2*a))
sol2 = (-b + cmath.sqrt(d/(2*a)))
print('Solutions are {0} {1}'.format(sol1, sol2))
|
1a5b2eea6874be406645184f1413a8d572e9aa26 | marezb/PhotoRawCleaner | /raw_cleaner.py | 2,117 | 4.03125 | 4 | '''
This is a simple program which I wrote to solve my problem with unnecessary photo raw files.
I always make photos in 2 formats jpg and raw. I usually watch photos on my computer and remove jpgs which I don't like.
As a result I stay with a bunch of unwanted raw files on my drive which take a lot of space.
To re... |
0f0816925739b982e1acec25f8dad926de5941c6 | turkeydonkey/nzmath3 | /sandbox/padic.py | 5,639 | 3.578125 | 4 | """
p-adic numbers and their rings / fields
"""
import nzmath.arith1 as arith1
import nzmath.rational as rational
import nzmath.ring as ring
class BasePadicInteger (ring.CommutativeRingElement):
"""
This is an abstract base class of p-adic integers.
"""
def __init__(self, p):
"""
Ini... |
e7d8d48120132bdefc07190b034293a5679ccd84 | turkeydonkey/nzmath3 | /sandbox/declarativegroup.py | 5,309 | 3.96875 | 4 | """
Group by declaration.
Some kind of structures is treated as a group by declaring it is a group.
"""
import nzmath.factor.methods as factor_methods
class Group (object):
"""
Declarative group class.
"""
def __init__(self, baseset, unity, op, inv, op2, properties):
"""
Group(basese... |
3f5e827ac432ba501aefcda2eeb14975d69b4688 | turkeydonkey/nzmath3 | /nzmath/sequence.py | 1,096 | 4.40625 | 4 | def generator_fibonacci(n=None):
"""
Generate Fibonacci number up to n-th term if n is assigned
else infinity.
"""
a = 0
b = 1
if None == n:
while True:
yield b
a += b
yield a
b += a
else:
count = 0
while True:
... |
81270203f3b1e48ab23a40e0f583a2161d86a3f7 | RyuuKumo/shellsort | /usingpython.py | 771 | 3.734375 | 4 | def shell(lista):
intervalo = len(lista) // 2
while intervalo > 0:
for p in range(intervalo):
reducir_busqueda(lista, p, intervalo)
# intervalo = intervalo // 2
intervalo //= 2
def reducir_busqueda(lista,inicio,salto):
for i in range(inicio + salto, l... |
e95b67cf7e25c45087a648982f861e89eaab26d0 | EriveltonGualter/Machine-Learning-Projects | /Project_1/tools.py | 13,687 | 3.796875 | 4 | # -*- coding: utf-8 -*-
import numpy as np
# ---------- Simple DataFrame class replace the function of pandas.DataFrame---------- #
class DataFrame:
def __init__(self, values, index, labels, father_pointer=1):
"""
Initialize class DataFrame
:param values: numpy.array -- values of data
... |
604aeb047ee13ceb828abb203f0443c52060211d | kjohhub/python | /turtle2.py | 1,105 | 3.65625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Jan 15 15:32:17 2021
@author: kjoh
"""
import turtle as t
#%% free line
def draw(head, dist):
t.setheading(head)
t.forward(dist)
def toleft():
draw(180, 15)
def toright():
draw(0, 15)
def toup():
draw(90, 15)
def todown():
draw(2... |
7a467ac1be9d76a108151833c423ba829c6ec5a9 | kjohhub/python | /exec,compile.py | 380 | 3.5625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Jan 15 13:26:21 2021
@author: kjoh
"""
#%% exec
exec("value = 3")
print(value)
#%% exec2
for n in range(10):
exec("""
for i in range(5):
print(i, end = ',')
print()
""")
#%%% compile
code = compile("""
for i in range(5):
print(i, end = ',')
print()
... |
30f15201cdbdf83c40ec1a6cad644a4c967a153e | lilachtech/lilachtech | /simulation.py | 4,504 | 3.734375 | 4 | from matplotlib import pyplot as plt
import random
import numpy as np
import csv
import pandas as pd
days = 20
population = 1000
ppl_to_meet_every_day = 10
fine = 200
enforcement_rate = 0.01
class Player(object):
def __init__(self, num, choice):
self.number = num
self.choice = choice
self.p... |
0b3ee52d22179e9081b1f207400be79518c27a35 | gurpsi/python_projects | /python_revision/13.2_Recurssion.py | 602 | 4.25 | 4 | from functools import lru_cache
# LRU cache = Least Recently Used Cache
@lru_cache(maxsize=1000) # Default is 128 (i.e last 128 values are cached)
def fibonacci_2(n):
# Check the input is a positive integer:
if type(n) != int:
raise TypeError("n must be positive int")
if n < 1:
raise Value... |
09c7b9f9bf2a80922627a8a0c41218ff0b8743a4 | gurpsi/python_projects | /specific file in all the folders and its sub folders leaving the 'Archive' folder and write output to file.py | 972 | 3.765625 | 4 | import os
def search_file(filename, search_path, output_file):
found_files = []
for root, dirs, files in os.walk(search_path):
if 'Archive' in dirs:
dirs.remove('Archive') # Exclude the 'Archive' folder from the search
if filename in files:
file_path = os.path.join(ro... |
4b357f5e5fbf5d1fd6a96de503adbb457489872b | gurpsi/python_projects | /Back to basics/HelloWorld.py | 730 | 4.25 | 4 | print('Hello world')
message = 'back to BASICS + Hello world'
# Lower function
print('message in lower case:',message.lower())
# Upper function
print('{}'.format(message.upper()))
# Count function
print('Count of back in message:',message.count('back'))
# Find function
print("Find where 'hello' word comes in the m... |
8575e32baca7eb7708f60d98ca66ffd9bbf553aa | gurpsi/python_projects | /GUI app/basic_tkinter.py | 272 | 3.9375 | 4 | '''
A basic GUI app.
'''
from tkinter import *
root = Tk()
theLabel = Label(root, text = 'This is my first GUI app')
theLabel.pack() # This actually puts the text in the GUI window.
root.mainloop() # This will keep the program running until we close the window manually. |
6e7ea24d28278492c8c19e7328d8ecf9cb3eacea | gurpsi/python_projects | /search content.py | 698 | 3.625 | 4 | import os
def search_files(directory, search_text):
for root, dirs, files in os.walk(directory):
for file in files:
file_path = os.path.join(root, file)
try:
with open(file_path, 'r') as f:
content = f.read()
if search_text in ... |
cea5f94f628ed13fcbf3bd05f3f1ad8f7f4f50dd | SriHarsha-Paladugula/Deep-Learning-For-Computer-Vision-with-Python | /Starter_Bundle/models/perceptron.py | 1,070 | 3.625 | 4 | import numpy as np
class Perceptron:
def __init__(self, N, alpha = 0.1):
self.weights = np.random.randn(N+1)/np.sqrt(N)
self.alpha = alpha
def step(self, x):
return 1 if x > 0 else 0
def fit(self, X, y, epochs = 10):
# insert a column of 1’s as the last entry in the ... |
1cf76fe320564896c0082a7951616c22521217cb | julian9319/python | /main.py | 200 | 3.875 | 4 | someElements=[
'a','b','c','b','d','m','n','n'
];
set1=set(someElements);
for i in set1:
if someElements.count(i) > 1:
print(i+' has duplicated.')
else:
print(i+' has not duplicated.'); |
c54f1480da54316ebd4c0911ee8afd56da9cc514 | tcatsuko/aoc2020 | /aoc01.py | 1,144 | 3.71875 | 4 | f = open('aoc01.txt','r')
problem_input = []
for line in f:
problem_input += [int(line)]
f.close()
def find_addend(my_array, my_sum, addends):
for number in my_array:
other_number = my_sum - number
if addends == 2:
if other_number in my_array:
return (number, other_n... |
df67d383e236d91f3fb780cfa89f6aaeea416d9b | tcatsuko/aoc2020 | /aoc03.py | 1,098 | 3.515625 | 4 | f = open('aoc03.txt','r')
problem_input = []
for line in f:
problem_input += [line[:-1]]
f.close()
# Determine width of slice
width = len(problem_input[0])
trees_found = 0
current_x = 0
current_y = 0
slope = [[1,1],[3,1],[5,1],[7,1],[1,2]]
current_slope = slope[1]
dx = current_slope[0]
dy = current_slope[1]
for li... |
1ac6638cb6dfa1c4c257206b5253167ca9c7dba5 | tcatsuko/aoc2020 | /aoc21.py | 2,441 | 3.609375 | 4 | f = open('aoc21.txt','r')
problem_input = []
for line in f:
problem_input += [line[:-1]]
f.close()
# Parse into ingredients and allergens
initial_ingredients = set()
allergens = set()
for line in problem_input:
split_line = line.split(' (contains ')
ingredients = split_line[0].split(' ')
for ingredient ... |
2783b2f01c79ea28436131a06fcdcea0fdbe78cb | poplol240/programs | /random_programs/calculator.py | 487 | 3.953125 | 4 | # This tings calculate anything... almost
# opp means operation
#do nothing
print ("Make an equasion and I will resolve it.")
nb = input("Chose a first num: ")
#nb.to_f
op = input("Chose a opperation: ")
#opp.to_f
nbb = input("chose another num: ")
#nbb.to_f
print (nb + op + nbb + " = ")
if op == "+":
... |
61dbde2f10dfba7a6dfc2c452b34da0f2b9e6a3b | poplol240/programs | /random_programs/noob_stuff.py | 195 | 3.890625 | 4 | n = int(input("Enter a year: "))
if n % 100:
if n % 400:
print("It is a leap year.☺")
elif n % 4:
print("It is a leap year.☺")
else:
print("It is a normal year.") |
cdb7bac5aaa1fd378a6f266834052caa50e9e8c1 | poplol240/programs | /random_programs/cave_escape.py | 11,873 | 4.09375 | 4 | #93
#yay
#100% me
import random
hp = 3
hot_dog = ""
cake = ""
burger = ""
room = 1
monster = False
num1 = 0
action = 0
last_action = 0
print("You fell in a cave.")
print("It is deep and dark, you can't see anything.")
print("You found a flashlite in your bag.")
print("Your goal is to escape.")
p... |
1cec538d15d09fd4bf17d041f56887e3a88b5d17 | yanzhh/Algorithms | /Data structures/queue/queue.py | 1,970 | 3.671875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Jul 5 10:41:22 2018
@author: Arc
"""
class queue(object):
def __init__(self, maxlength): #maxlength即队列最大的元素个数
self.q = []
self.head = self.tail = 0 #初始时 q.head = q.tail = 1
self.size = 0 # q.size变量记录了队列的实际长度
self.length = maxlength
... |
8087578ddce9c65fd18653cdb7fec677e782ea73 | alexnakagawa/tools | /ml/keras/keras_categorical.py | 789 | 3.75 | 4 | '''
This is an abstract example of using a Sequential keras model with Dense layers
to predict a category.
Inspired from the "Deep Learning" course on Datacamp.com
Author: Alex Nakagawa
'''
# Import necessary modules
import keras
from keras.layers import Dense
from keras.models import Sequential
from keras.utils impo... |
a04c513ec589f5416ea7066c7958fff264a00012 | alexnakagawa/tools | /ml/sklearn/pearson_and_PCA.py | 978 | 4.0625 | 4 | '''
This is an example of finding the Pearson correlation coefficient as well as Principal Component Analysis (PCA).
PCA transforms the data to align with the axes (mean of 0) without loss of information.
Inspired by the "Unsupervised Learning" course on Datacamp.com
Author: Alex Nakagawa
'''
import matplotlib.pyplot... |
be46eaa7dad6168eb7e0f5b4f8650757c50de349 | arpitg1304/Artificial-Intelligence | /hill_climb.py | 1,654 | 3.953125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Oct 4 18:26:43 2017
@author: Arpit
"""
import math
def cities():
distances = [[0 for i in range(8)] for j in range(8)];
x_y = [[2,3],[4,5],[7,3],[8,2],[2,7],[2,2],[3,7],[12,4]]
for i in range(len(x_y)):
for j in range(len(x_y)):
... |
c92fd4b14d2b6dba44cd61dd1217462cd3e46313 | awaddell77/Scrapers | /binarysearch.py | 590 | 3.6875 | 4 | #binary search for list
import time
def bsearch(lst, val):
low = 0
r = len(lst)-1
for i in lst:
if low > r: return -1
mid = (r + low)//2
if lst[mid] < val: low = mid + 1
elif lst[mid] > val: r = mid - 1
else: return mid
def linsearch(lst, val):
for i in lst:
if i == val: return val
return -1
testlst = ... |
8d282c1234970634ffd25cae063b56bd1c74c477 | mertsigirci11/Python-Calismalari | /Python/Fonksiyonel Programlama/İsimsiz(Lambda) Fonksiyonlar.py | 343 | 3.59375 | 4 | """
------------------İsimsiz(Lambda) Fonksiyonlar------------------------------------
"""
"""
-Bir fonksiyona isimlendirme yapmadan fonksiyonu kullanabiliyor olmamız.
"""
new_sum = lambda a,b : a+b
print(new_sum(6,5))
sirasiz_liste=[('b',3) , ('a',8) , ('d',12) , ('c',1)]
print(sorted(sirasiz_liste, key... |
9911d412c3e4dce495a65d8a5a2c4cc11fcddb8a | mertsigirci11/Python-Calismalari | /Python/Fonksiyonlar/Fonksiyonlara Giriş.py | 505 | 3.84375 | 4 | """
?print yazarak fonksiyonların özelliklerine bakabiliriz.
print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
Prints the values to a stream, or to sys.stdout by default.
Optional keyword arguments:
file: a file-like object (stream); defaults to the current sys.stdout.
sep: string inserted... |
5f6e5ff00b7f3113428d7adc61b05b85c2e5e5cb | naveenkumarkr723/OPENCV | /low pass filters.py | 707 | 3.625 | 4 | """
low pass filters do :
1.blurring the image
2.denoising the image
3.smoothing the image
"""
import cv2
import numpy as np
import matplotlib.pyplot as plt
path = "C:\\Users\\jadin\\Downloads\\misc\\misc\\"
path1 = path+"4.2.07.tiff"
img= cv2.imread(path1,1)
img =cv2.cvtColor(img, cv2.COLOR_B... |
8e64ac9a7c2c47e5d118900c9e5e08a29cfded0a | csfx-py/hacktober2020 | /fibonacci_dp.py | 211 | 3.5625 | 4 | dp = {}
def fib(n):
if n<2:
return n
if n in dp:
return dp[n]
ans = fib(n-1) + fib(n-2)
dp[n] = ans
return ans
n = int(input())
print(fib(n))
# Time Complexity: O(n)
# Space Complexity: O(n)
|
0a8d7255ea19f9f0e28c3ecb93c688f2d9162aac | csfx-py/hacktober2020 | /passgen.py | 499 | 3.875 | 4 | # importing module
import random
import string
def get_random_password_string(length):
password_characters = string.ascii_letters + string.digits + string.punctuation #taking randomg lett digits
password = "".join(random.choice(password_characters) for i in range(length))
print("Your Password is:"... |
96bbe43f3fbf50896089bc41cf78017a585d0e06 | csfx-py/hacktober2020 | /dict.py | 1,557 | 4.5625 | 5 | dict={'apple':5,'ball':2,'orange':3,'guava':4,'peach':69}
#A dictionary is a collection which is unordered, changeable and indexed. In Python dictionaries are written with curly brackets, and they have keys and values.
print(dict)#simple printing of all dict values and keys
for keys in dict:
print(keys)
... |
9bc3c83366a2c310525408a5fc49a05270eb046a | viniciusalveshax/object-detection-2021 | /IOU.py | 1,624 | 3.625 | 4 | def inside(boxA, boxB):
x1A, y1A, x2A, y2A = boxA
x1B, y1B, x2B, y2B = boxB
if (x1A <= x1B) and (y1A <= y1B) and (x2A >= x2B) and (y2A >= y2B):
return True
else:
return False
#Código original dessa função por Coutinho
# https://github.com/lucas-coutinho/
def IOU(boxA, boxB, debug=False):
# determine ... |
e82ee8eb627fe7f4a864336a1457f1e7f1ec663a | aapalo/aoc2019 | /2/code.py | 1,953 | 3.640625 | 4 | #!/usr/bin/python3
import time
''' ####### '''
date = 2
dev = 0 # extra prints
part = 3 # 1,2, or 3 for both
samp = 0 # 0 or 1
''' ####### '''
def day(te):
a = []
for i in te[0].split(","):
a.append(int(i))
idx = 0
if not samp:
a[1] = 12
a[2] = 2
while i... |
eb251211575a2db399bf10a136604ae9128d8ae9 | TheManWhoWasThursday/TomeRater | /TomeRater.py | 4,172 | 3.84375 | 4 | class User:
def __init__(self, name, email):
self.name = name
self.email = email
self.books = {}
def get_email(self):
return self.email
def change_email(self, address):
self.email = address
print("User email has been updated.")
def __repr__(self... |
a7a63a51c72b0f0617becd8e34f1e3635269479a | VaibhavDesai/Algorithms | /GeekforGeeks/findIsland.py | 1,243 | 3.8125 | 4 | #http://practice.geeksforgeeks.org/problems/find-the-number-of-islands/1
'''Please note that it's Function problem i.e.
you need to write your solution in the form Function(s) only.
Driver Code to call/invoke your function would be added by GfG's Online Judge.'''
# your task is to complete this function
# Your functio... |
5fc8fc76c6dd15aa5dcb41c053da11bd4868bc22 | Veritas-Codes/mad-libs | /horse-thief.py | 316 | 3.859375 | 4 | adj2=input('enter a adjective:')
verb2=input('enter a verb:')
noun3=input('enter a noun:')
noun4=input('enter a noun:')
verb5=input('enter a verb:')
adj6=input('enter a adjective:')
noun7=input('enter a noun:')
print(f"""
There was a {adj2} {noun3} who {verb2} a {noun4} and then {verb5} a {adj6} {noun7}.
""")
|
0533c1504376588e47ba8e6eccc1ded83b5781a3 | ajmath62/config | /log | 1,831 | 3.859375 | 4 | #!/usr/bin/env python
""" Log hours for today """
import argparse
import datetime
from pathlib import Path
import subprocess
parser = argparse.ArgumentParser(description='Log hours for a project')
parser.add_argument('filename', default='timesheet.txt', help='the timesheet file location',
nargs='?... |
113984940b0d5a75607f4c8208f50be2be22c2ed | hseifu/tic-tac-toe | /dumbtictactoe.py | 2,321 | 3.9375 | 4 | #! /usr/bin/env python3
# Done by Henok_S
import pyperclip
import random
def printBoard(board):
print(board['top-l'] + '|' + board['top-m'] + '|' + board['top-r'])
print('-+-+-')
print(board['mid-l'] + '|' + board['mid-m'] + '|' + board['mid-r'])
print('-+-+-')
print(board['low-l'] + '|' + board['lo... |
13390b7c818683a91067ab7c07af1298988599ee | MJ702/pythonprogamming | /pyton/numpy/Creation_of_array.py | 1,264 | 3.96875 | 4 | import numpy as np
# creation of array
a = np.array([[1, 2, 3, 4], [5, 6, 7, 8]], dtype=np.int32)
print(a)
print()
b = np.array([[34, 54, 73, 78], [78, 90, 91, 67]], dtype=complex)
print(b)
print()
# The function zeros creates an array full of zeros
c = np.zeros((3, 4))
print(c)
print()
d = np.ones((2, 3))
print(d)... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.