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 |
|---|---|---|---|---|---|---|
5bd67cbc73b0ae70dfd44f36c04f58da3df0312b | amrahat/distributed-market-based-algorithm | /idmb.py | 1,723 | 3.5 | 4 | from input import generate_input
# input: ('agent': (taskid, cost)
def should_swap_tasks(agent1, agent2, allocated_task, agent_task_input):
task1 = allocated_task[agent1]
task2 = allocated_task[agent2]
current_total_cost = task1[1] + task2[1]
cost_after_swapping = agent_task_input[agent1][task2[0]] ... |
e4960cabf2330beb1601b933756820e83b9f87f0 | rickjiang1/python-automate-boring-stuff | /RegExp_Basic.py | 915 | 4.375 | 4 | #regular expression basics!!
#this is the way of how to define a phonenumber
'''
def isPhoneNumber(text):
if len(text)!=12:
print('This is more than 12 digit')
return False
for i in range(0,3):
if not text[i].isdecimal():
return False #no area code
if text[3]!='-':
... |
05df0ae4085eb0564e84076e48e8e69f52475700 | kn33hit/Coursework | /GL_backup/201/PJT/PJT1/project1.py | 6,635 | 3.921875 | 4 | # project1.py
# Neh Patel
# November 14, 2013
# Section 17
# npatel10@umbc.edu
# Autofill project
#------------------------------------------------------------------------------
# printGreeting: prints a greeting
def printGreeting():
print("THIS IS THE AUTOFILL PROGRAM!")
# readFile: reads the file and counts the... |
d337523cd9af9acdcb78db9d17f73c5017b1c98e | kn33hit/Coursework | /GL_backup/201/LABS/LAB5/lab5.py | 1,018 | 3.765625 | 4 | # file: lab5.py
# author: Neh Patel
# date: 10/3/2013
# section : 17
# email : npatel10@umbc.edu
# description : this program determines whether a number is perfect or not
def main():
# declaring variables
total = 0
divisor = 0
flag = True
num = 0
# input
while (flag):
tr... |
8d9101c37e2587fd6ee19f2e4858f9001266ebdc | kn33hit/Coursework | /GL_backup/201/HW/HW8/hw8.py | 6,854 | 4.375 | 4 | # file: hw8.py
# author: Neh Patel
# date: 11/6/2013
# section: 17
# email: npatel10@umbc.edu
# description: reads a cipher file, then a regular file. And according to the
# user input in the main menu converts the reuglar file into a
# translated file from the cipher file. also lets the u... |
f879a08b49902e4e9bd8aeb5ec95d3ce6db22c70 | gibernaut1/tkinter | /menusuperglavn.py | 1,598 | 3.8125 | 4 | from tkinter import *
from tkinter import messagebox
def inserta():
#messagebox.showinfo("пример ввода\вывода", message.get())
#print(message.get())
a=messagea.get()
print(a)
def insertb():
#messagebox.showinfo("пример ввода\вывода", message.get())
#print(message.get())
b=messageb.get... |
f67ceced60252425dfa1b97d3e94d6a5bac8841e | LordTesseract/CET086 | /Relatório 3/rKutta4.py | 1,208 | 3.9375 | 4 | #Falta Polir / Ready
# Implementação do método Runge-Kutta de 4ª ordem.
#Entrada: Espreção, x0, y, x, h
entrada = open("tKutta4.in","r")
saida = open("tKutta4.out","w")
def dydx(x, y):
solucao = eval(expressao)
return solucao
# Finds value of y for a given x using step size h
# and ini... |
a237956929688eb01259ece580c0a5f60a67ac17 | fddn/JetBrainsAcademy_SimpleChatBot | /Problems/Very odd/main.py | 122 | 3.84375 | 4 | dividend = int(input())
divisor = int(input())
if (dividend // divisor) % 2 != 0:
print(True)
else:
print(False)
|
0d2591cd1bf015005903105fcf5cbd6eb3c7f50a | BenMob/BlackJack | /dealer.py | 1,006 | 4.03125 | 4 | '''
By Benjamin
'''
class Dealer:
'''
INPUT: None
This is the dealer's class.
'''
def __init__(self):
self.cards = [] # Place holder for the dealer's cards
self.hidden_card = 0 # Place holder for the hidden card
# ----------------------------
def hide_first_card(self):
... |
81db3dfa72c53d5f3e6c37bab8ff0ce40f40339b | juliorenner/adventOfCode_2018 | /day02/2.py | 1,059 | 3.578125 | 4 | import os
currentDir = os.path.dirname(__file__)
with open(os.path.join(currentDir, 'input.txt'), 'r') as inputFile:
input = inputFile.read().split('\n')
def getStringsDifference(lines):
for i, line in enumerate(lines):
for j in range(i+1, len(lines)-1):
nextLine = lines[j]... |
bdaae05c57947cf10aef600b9922ea761215d43a | deusBellator/hello-world | /psswdgen.py | 450 | 3.96875 | 4 | #random password generator
import random
import string
def pw_gen(size, chars=string.ascii_letters + string.digits + string.punctuation + string.ascii_lowercase + string.ascii_uppercase):
return ''.join(random.choice(chars) for _ in range(size))
name = input('What is your username?')
print ('Your user... |
6023f12c4c5163004ab56b62d9efa4e8dcf4dc63 | BonySmoke/CodingQuestionsAndAlgorithms | /Student's_Friendship_Relations.py | 2,286 | 4 | 4 | '''
A classroom consists of N students, whose friendships can be represented in an adjacency list.
For example, the following descibes a situation
where 0 is friends with 1 and 2, 3 is friends with 6, and so on.
friendship_dict = {
0: [1, 2],
1: [0, 5],
2: [0],
3: [6],
4: [],
5: [1],
6: [3],
}
Each student ca... |
4b94e5f1b047e987076f4a43dc8bce74defde912 | roussePaul/kampala | /trajectory_generator/scripts/trajectory_generato.py | 4,599 | 3.875 | 4 | #!/usr/bin/env python
#This file contains a class consisting of functions that may be used when generating trajectories
#The functions have been found to be useful earlier.
#The functions include
#rotating a coordinate system by angles [theta_x, theta_y, theta_z]-
#offseting a position by a certain vector [x, y, z]-
#... |
6cd613c8facc1d6a432700e9bfef6d3b6c9c87ef | momokawa/physically_based_animation_assignment1 | /task1/particle.py | 2,916 | 3.625 | 4 | import copy
import numpy as np
class Particle2D:
""" A Particle class for 2D """
def __init__(self, position, velocity, force, mass, time_step):
self.position = position
self.velocity = velocity
self.force = force
self.previous_position = position
# self.previous_positi... |
c48ac6d235b4b1a0a0e3026a8bb120f885124c49 | matejur/AdventOfCode2020 | /Day15.py | 797 | 3.5 | 4 | def simulate(numbers, turns):
alreadySpoken = {}
prev = 0
for turn, number in enumerate(numbers):
alreadySpoken[int(number)] = [turn + 1]
prev = int(number)
for turn in range(len(numbers) + 1, turns + 1):
if len(alreadySpoken[prev]) > 1:
newNumber = alreadySpoken[pr... |
dae04957d9ae205e0e0de62f251d257b1aeb1017 | nirajagarwal91/Deep-Learning | /DogsVsCats_Classification.py | 1,117 | 3.609375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Aug 18 21:20:05 2018
@author: Niraj
"""
# Building Convolutional Neural Network
from keras.layers import Conv2D
from keras.models import Sequential
from keras.layers import MaxPooling2D
from keras.layers import Flatten
from keras.layers import Dense
classify = Sequential()... |
6277d6ccf93af8966f334c6a4b535cab3e644d67 | tharunpeddisetty/Polynomial-Regression | /PolynomialLinearRegression.py | 1,651 | 3.96875 | 4 | # Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Importing the dataset
dataset = pd.read_csv('/Users/tharunpeddisetty/Desktop/Machine Learning A-Z (Codes and Datasets)/Part 2 - Regression/Section 6 - Polynomial Regression/Python/Position_Salaries.csv')
X = dataset.iloc... |
28c50d97f9ecd89211f494a20d12eba57a859d92 | PatrickKelly95/Python-Assignment-1 | /database/models.py | 1,765 | 3.671875 | 4 | # Program Name: models
# Purpose: Creates individual tables in database for each statistic
from database.database import db
# Create table based on age statistics
class Age(db.Model):
id = db.Column(db.Integer, primary_key=True)
average_age = db.Column(db.Integer, unique=False)
min_age = db.Column(db.Int... |
8dc42dd94d17d1ec46b3fd77cb50d00e4060bab5 | wonjongah/DataStructure_CodingTest | /fastcampus/코딩테스트_면접/02. 알고리즘 이론/recursive4.py | 179 | 3.8125 | 4 | def func(data):
if data == 1:
return 1
elif data == 2:
return 2
elif data == 3:
return 4
else:
return func(data-1) + func(data -2) + func(data - 3)
print(func(5)) |
bc2ff3174a5dff69f9ccd40cc95125bd2e92efe4 | wonjongah/DataStructure_CodingTest | /fastcampus/코딩테스트_면접/03. 유형별 문제 풀이/키로거_my.py | 514 | 3.640625 | 4 | testcase_num = int(input())
password = []
for i in range(testcase_num):
right, left = list(), list()
pass_input = input()
for char in pass_input:
if char == "<":
if left:
right.append(left.pop())
elif char == ">":
if right:
left.a... |
edfa4002b2c84fcf74efe0065b9a9de4bfc6975f | wonjongah/DataStructure_CodingTest | /fastcampus/코딩테스트_면접/03. 유형별 문제 풀이/수 정렬하기.py | 346 | 3.578125 | 4 | n = int(input())
array = list()
for _ in range(n):
array.append(int(input()))
for i in range(n):
# 가장 작은 원소의 인덱스
min_index = i
for j in range(i + 1, n):
if array[min_index] > array[j]:
min_index = j
array[i], array[min_index] = array[min_index], array[i]
for i in array:
pr... |
69d97fbe5830fa04bada7d0f0967759997063fd2 | wonjongah/DataStructure_CodingTest | /practice/같은 문자쌍.py | 218 | 3.71875 | 4 | def is_same(string1, string2):
s1 = list(string1)
s2 = list(string2)
if sorted(s1) == sorted(s2):
return True
else:
return False
print(is_same("yes", "sey"))
print(is_same("uy", "ui")) |
e15ff1a16228c2f53e15133f4af01049bd7713f9 | maggeek/tree-search-algorithms | /iddfs.py | 1,421 | 3.703125 | 4 | import puzzle
"""
Class DFS inherits from Puzzle class.
It performs an iterative deepening depth-first search.
"""
class IDDFS(puzzle.Puzzle):
def iddfs(self):
"""perform an iterative deepening depth-first search"""
explored = 0
depth_limit = 10000
for depth in range(dep... |
18f12f920e908d0fb23b6035626156acbfc0aba6 | srajeevteaching/lab-4-katie-chris-eleni-1 | /.github/lab4.py | 754 | 3.875 | 4 | # Programmers: Katie, Chris, Eleni
# CS151, Dr. Rajeev
# October 7, 2021
# Lab 4
plan = input("Enter your plan")
plan = plan.strip().lower()
data = input("Enter the amount of data(GB) used")
data = float(data)
import math
if plan == "green":
if data > 2.0:
price = 49.99 + 14.99 * (data - 2.0)
coup... |
b1fbf38690dd22889466e71473a09332bae70b4e | digaji/lambda-function-exercises | /no4.py | 351 | 3.75 | 4 | # Lambda func to extract year, month, date, and time
import datetime
rightNow = datetime.datetime.now()
def extract(y):
year = lambda x: x.year
month = lambda x: x.month
date = lambda x: x.day
time = lambda x: x.time()
print("Year: {}, Month: {}, Date: {}, Time: {}".format(year(y), month(y), date(y... |
3cf8e1bdbdd55eabec6c305181a39103c88b4fed | MarksLuscas/firstProjectWithFlask | /webapp/vsearch.py | 979 | 4.03125 | 4 |
def buscarVogais(phrase: str) -> set: # mostra o tipo da variável que espera receber e se algo dê errado, ele mostra qual tipo de dado era para ter passado
vowels = set('aeiou')
return vowels.intersection(set(phrase)) #set(letters) -> cria um obj conjunto a partir dos caracteres nas variavel letters
# print(busca... |
20f0f9b17e623409d6a8b0b03cf1e81d81673a04 | Kennedy-Njeri/All-python | /oop.py | 597 | 3.8125 | 4 | #class Dog():
#Class Object Attribute
# species = 'mammal'
# def __init__(self,breed,name):
# self.breed = breed
# self.name = name
#myDog = Dog(breed='Bulldog',name='Huskie')
#print (myDog.breed)
#print (myDog.name)
#print (myDog.species)
class Circle():
pi = 3.14
def __init__(s... |
81c049631b64733a1583de85fdd078133dfd1476 | Kennedy-Njeri/All-python | /scope.py | 753 | 4.25 | 4 | #x = 25
#def my_func():
# x = 50
#return x
#print(x)
#print(my_func())
x = 25
def my_func():
x = 50
return x
#print(x)
#print(my_func())
my_func()
print (x)
#example 2
name = "kennedy"
def full():
#name = "sammy"
def hello():
print ("hello "+ name)
hello()
full(... |
cbe382de202ed259aa895249ea07a1508f770ff2 | luischitala/Python | /funciones.py | 239 | 3.546875 | 4 | def checar_entrada(edad):
if edad < 18:
print("No puedes entrar")
elif edad >= 21:
print("Puedes entrar y puedes beber")
else:
print("Puedes entrar pero no puedes beber")
edad = 18
checar_entrada(edad) |
368d7c6b72420cb02a77c60bfe09a6a5a5742c7d | luischitala/Python | /adivina.py | 4,347 | 4.03125 | 4 |
#Queremos poner la opción de volver a jugar generando número diferente
import random
def jugarf():
intentos = 0
numero_aleatorio = random.randint(1,10)
print("Bienvenido a Adivina el número")
print("Estoy pensando en un número del 1 al 10")
print("Adivina cual es")
print("Solamente tienes 5 int... |
fad659a950108ac733dc6821e1506181c21c7fe5 | makaiolam/conditions-and-loops | /main.py | 1,955 | 4.125 | 4 |
# first = input("what is your first name")
# last = input("what is your last name")
# print(f"you are {last}, {first}")
#loops
#-----------------------------
# print(1)
# print(2)
# print(3)
# print(4)
# print(5)
#while loop
# while loop takes a boolean epxression (t/f)
#boolean operations
#---------------------... |
d26cd8f44b032e6233a2aa5399b4623ce2b3cfaf | TL-Web30/CS35_IntroPython_GP | /day1/00_intro.py | 1,407 | 4.25 | 4 |
# This is a comment
# lets print a string
# print("Hello, CS35!", "Some other text", "and theres more...")
# variables
# label = value
# let const var (js)
# int bool short (c)
# first_name = "Tom"
# # print("Hello CS35 and" , first_name)
# num = 23.87
# # f strings
# my_string = " this is a string tom"
# print(m... |
a71ac1490707ec9a7728aa0da57e09047f227fc0 | urusha-shrestha/sudoku_solver | /solverMethods.py | 1,757 | 3.609375 | 4 | import math
def print_board (Board):
size=len(Board)
a=int(math.sqrt(size))
for i in range(size):
if i % a == 0 and i != 0:
print("-------------------------------------")
for j in range(len(Board[0])):
if j % a == 0 and j != 0:
print(" | ", end="")
... |
124f530bdbc414563779d2461eca28be2f294bec | juliangarcia1/python_curse_01_fundamentals | /03_funciones_de_cadenas.py | 480 | 3.609375 | 4 |
def modifica_cadena(param):
# Todas mayusculas
print('Texto original:\r{}'.format(param))
text = param.upper()
print(text)
# Todas minusculas
text = param.lower()
print(text)
# Titulo
text = param.title()
print(text)
# Slice positivo
text = param[2:]
print(text)
# Slice negativo
text = param[-2:]
print... |
ec2f33e5e4d9897ca91d49946678b4e4aa57423b | starinfinity/Python-for-beginners | /code/removeduplist.py | 337 | 3.609375 | 4 |
list = []
len = input("length of list\n")
for i in range(int(len)):
list.append(input("\n"))
i = 0
j = 0
length = int(len)
while i < length:
if j < length:
if i != j and list[i] == list [j]:
list.pop(j)
length -= 1
else:
j += 1
else:
i +... |
a2e6bb46d0bfbb8ffa5b3dbe8844c8f7eaa3bbee | JVvix/pysnakegame | /turtle_graphics.py | 386 | 3.78125 | 4 | from turtle import*
def main():
speed("fastest")
background()
pu()
home()
pod()
speed("normal")
head()
shell()
feet()
tail()
done()
def background():
size=0
for i in range (350) :
if i%2==0:
colour = "blue"
else:
colour ="red"
... |
0aa13119deaa026d9a0114d78d15e7cb2cc712a9 | lurailabs/CodeChef | /Practice - Easy/Paying_up.py | 815 | 3.953125 | 4 | #!/usr/bin/env python3
def dinamic_algorithm(values, m):
matrix = []
for x in range(len(values)):
row = [1]
for y in range(1, m+1):
if values[x] == y: row.append(1)
elif x-1 >= 0 and matrix[x-1][y] == 1: row.append(1)
elif x-1 >= 0 and y-values[x] >= 0 and ma... |
213dfd0dc2c4f430c3e0d2a249afe20c02246f7d | JwowSquared/holbertonschool-higher_level_programming | /0x07-python-test_driven_development/5-text_indentation.py | 465 | 3.75 | 4 | #!/usr/bin/python3
"""This module holds the function text_indentation, for Python 0x07 Task 4"""
def text_indentation(text):
"""prints the given text with aditional newlines after punctuation"""
if type(text) is not str:
raise TypeError("text must be a string")
line = ""
for c in text:
... |
a89560c21e5c80e26bad34adbbc3be721fb33429 | JwowSquared/holbertonschool-higher_level_programming | /0x03-python-data_structures/8-multiple_returns.py | 163 | 3.5625 | 4 | #!/usr/bin/python3
def multiple_returns(sentence):
i = len(sentence)
if sentence is None or i == 0:
return (0, None)
return (i, sentence[0])
|
b0411a2abcf06ddca7a949a8cc125d33545eaf2d | JwowSquared/holbertonschool-higher_level_programming | /0x10-python-network_0/6-peak.py | 366 | 3.71875 | 4 | #!/usr/bin/python3
"""x"""
def find_peak(nums):
"""x"""
if nums is None or nums == []:
return None
length = len(nums)
if length == 1:
return nums[0]
if nums[0] > nums[1]:
return nums[0]
if nums[-1] > nums[-2]:
return nums[-1]
if length == 2:
ret... |
d3a99189196bb623e1cd59adb1407d0b56d2333d | JwowSquared/holbertonschool-higher_level_programming | /0x0B-python-input_output/4-append_write.py | 168 | 3.84375 | 4 | #!/usr/bin/python3
"""x"""
def append_write(filename="", text=""):
"""x"""
with open(filename, "a") as f:
total = f.write(str(text))
return total
|
dea877bd85f96fbc69f71af2ffe21047d56789df | JwowSquared/holbertonschool-higher_level_programming | /0x04-python-more_data_structures/0-square_matrix_simple.py | 160 | 3.65625 | 4 | #!/usr/bin/python3
def square_matrix_simple(matrix=[]):
new = []
for row in matrix:
new.append(list(map(lambda x: x**2, row)))
return new
|
34ca0dcd4b1d1fe1187faa5e271f7cd58a8766f1 | JasonLuis/python-basico | /estrutura_de_repeticao_for.py | 549 | 4.3125 | 4 | """
## Estrutura de repetição – for
"""
print(1)
print(2)
print(3)
print(4)
print(5)
for numero in range(1, 6):
print(numero)
5 + 4 + 3 + 2 + 1
print("\n\n")
for numero in range(5, 0, -1):
print(numero)
print("\n\n")
soma = 0
for numero in range(1, 6):
soma = soma + numero
#print(soma)
print(soma)
print... |
2af5eac331b19227d740a92f52baeda283019cee | JasonLuis/python-basico | /modulos_uteis_random_time.py | 1,030 | 4.0625 | 4 | ## Biblioteca random
'''
https://docs.python.org/3/library/random.html
'''
import random
#imprimir um numero randomico
randomico = random.random()
print(randomico)
#imprimir um numero randomico de 1 a 10
numero = random.randint(1,10)
print(numero)
#imprimir um numero randomico de 0 a 10 multiplos de 3
numero = ran... |
1adbdcca3ede34214bccdb3d832d85c97358af9c | JasonLuis/python-basico | /modulos_uteis_math_datetime.py | 1,159 | 3.515625 | 4 | #Módulos úteis
## Biblioteca Math
'''
https://docs.python.org/3/library/math.html
'''
import math
#raiz quadrado
raiz = math.sqrt(9)
print("raiz quadrada: ",raiz)
#seno
seno = math.sin(45)
print("seno: ",seno)
#coseno
coseno = math.cos(45)
print("coseno: ",coseno)
#logaritmo
logaritmo = math.log(1000, 10)
print("l... |
2a1cfed0aa07d5c0947cda003e5528ef98d826d0 | JasonLuis/python-basico | /exercicios/exercicio8.py | 705 | 3.9375 | 4 | '''
1. Considerando o dicionário com o nome dos alunos e suas respectivas notas abaixo, crie uma estrutura de repetição para percorrer cada elemento do dicionário para gravar cada aluno em um novo arquivo de texto
– Cada aluno deve ocupar uma linha do novo arquivo de texto
– O formato deve ser: nome,nota (Pedro,8.0)
– ... |
47f92fa3cff07076aae8fa8f19121988a2ecc6e2 | felipegrabowsky/Knn-Classifier-on-Iris-Data | /find_k_nearest_neighbors.py | 2,266 | 3.78125 | 4 | from create_data import *
import numpy as np
from integerize_labels import *
from split import *
#########
#Name; Felipe Marujo Grabowsky
#UNI: fm2579
# This program contains a function that returns a numpy matrix with the k
#nearest neighbors of a test point
#######
def find_k_nearest_neighbors(test_point, train... |
02db9edf1d86ddcdec8e6fc696509d00fa4b51ee | gauravkarkal/Design-and-Analysis-of-Algorithms | /krushkal_test.py | 690 | 3.6875 | 4 | n=5
graph=[[1,2,4],[2,3,3],[2,4,1],[1,4,8],[4,3,7],[3,5,8],[4,5,3]]
graph.sort(key=lambda x:x[2])
parent=[-1]*(n+1)
final=[]
count=0
def get_parent(node):
if parent[node]==-1:
return node
else:
return get_parent(parent[node])
def union(a,b):
pa=get_parent(a)
pb=get_p... |
fe1d32ca7ca7139be3bc1a601e80f0c9491a9326 | paulknewton/pi-tank-watcher | /alarm.py | 904 | 3.71875 | 4 | def is_event_logged(event, events):
"""
Check if an event was logged in events
:param event: the event to check
:param events: the list of events already logged
:return: true if the event has been logged, otherwise false
"""
return event in events
def is_last_event_greater(gt, events):
... |
c9f895e39f838b4309b2c6fb269dd18885f6c08d | shourjyab/pythonlearningatm | /forloop.py | 68 | 3.53125 | 4 | total=0
for num in range(101):
total=total+num
print(total)
|
6e23d4c49376430ff7df94a3253b6ed5b29c1949 | quanchangjun/python-demo | /task/day3.py | 1,424 | 3.984375 | 4 | '''
Day 3 视频观看:
6)Beautiful Soup的安装和使用
💯Day 3 作业:
1. 使用 Beautiful Soup 筛选器代替正则表达式进行图书名字筛选。
2. 通过搜索引擎了解 Xpath 的功能并比较和 Beautiful Soup 的差异。
参考资料:
Beautiful Soup:https://www.crummy.com/software/BeautifulSoup/bs4/doc/index.zh.html
XPath:https://developer.mozilla.org/zh-CN/docs/Web/XPath
... |
177276e237051a9e0da5ed001f04bcad9e7c667c | shantanudwvd/PythonHackerrank | /Minimum elements to make median X.py | 564 | 3.53125 | 4 | queries = int(input())
for i in range(queries):
size, x = map(int, input().split())
array = list(map(int, input().split()))
array.sort()
if size % 2 == 0:
median = (array[int(size/2) - 1] + array[int(size/2)]) / 2
else:
median = array[int(size/2)]
if size % 2 == 0:
... |
2cd170ce68a387116ff6889e242ad6da1183b105 | shantanudwvd/PythonHackerrank | /ReversalAlgo.py | 529 | 3.796875 | 4 | def rverseArray(arr, start, end):
while start < end:
temp = arr[start]
arr[start] = arr[end]
arr[end] = temp
start += 1
end = end - 1
def leftRotate(arr, d):
if d == 0:
return
n = len(arr)
rverseArray(arr, 0, d - 1)
rverseArray(arr, d, n - 1)
rve... |
38d1cb07d41406599aae11153c6e1614205fc0e7 | shantanudwvd/PythonHackerrank | /FindMultipleLeftRotations.py | 451 | 3.5625 | 4 | def preprocess(arr, n):
temp = [None] * (2 * n)
for i in range(n):
temp[i] = temp[i + n] = arr[i]
return temp
def leftRotate(arr, n, k, temp):
start = k % n
for i in range(start, start + n):
print(temp[i], end=" ")
print("")
arr = list(map(int, input().split(" ")))
n = len(ar... |
8041ffc6751e27319561e58d6f9e71410d172ca6 | shantanudwvd/PythonHackerrank | /countcharactersinstring.py | 584 | 3.640625 | 4 | name = input("Enter a string: ")
i = 0
list = []
i = 0
while i < len(name):
char = name[i]
if name.count(char) <= 1:
print(char, end=" ")
print(name.count(char), end="\n")
i += 1
elif name.count(char) > 1 and i == 0:
list.append(char)
print(char, end=" ")
... |
109edd3da8002ac844e0be1249b136f21c428efc | jhen852/htc-1 | /pregunta_2.py | 2,345 | 3.859375 | 4 |
lista_persona=[]
sw = True
def listar_persona():
if len(lista_persona) == 0:
print('Lista vacia')
else:
print(lista_persona)
def agregar_persona():
persona = input('Ingrese datos de la persona ')
lista_persona.append(persona)
print('Persona agregada!')
def ... |
166366c2f5457e02d5aee7dd44936a966ca17f56 | tringhof/pythonprojects | /ex15.py | 806 | 4.21875 | 4 | #import argv from sys module
from sys import argv
#write the first argv argument into script, the second into filename
script, filename = argv
#try to open the file "filename" and save the file object into txt
txt = open(filename)
print "Here's your file %r: " %(filename)
#use the read() command on that file object... |
97e2d43df79c0b589bb6d494a568428d6a14f781 | adrianaryaputra/pokemeow-auto-hunt | /src/tools/formatcmd.py | 224 | 3.515625 | 4 | from datetime import datetime
def dateprint(msg):
print(f"""[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] {msg}""")
def dateinput(msg):
return input(f"""[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] {msg}""") |
8474a79e397fbdaeae2dd51d7fbc45fee29271d3 | kubas1129/WDI | /ZadanieLiczbyPierwsze.py | 1,563 | 3.703125 | 4 | #Jakub Pałka
import matplotlib.pyplot as plt
import time
def primeEratostenes(n):
if (n < 2): return -1
primes = [i+1 for i in range(n)] #init tablicy liczb
primes.remove(1) #usuwamy 1
j = 0 #counter while
start_time = time.time()
while j < len(primes):
numberToCheck = primes[j]
... |
f286fe6424a794424c9f93717b8c2ea254f160d8 | kubas1129/WDI | /lab7.py | 1,682 | 3.6875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Nov 20 08:41:57 2017
@author: palkjaku
"""
ceny = {1:1,2:3}
def primeEratostenes(n):
if (n < 2): return -1
primes = [i+1 for i in range(n)] #init tablicy liczb
primes.remove(1) #usuwamy 1
j = 0 #counter while
while j < len(primes):
numberToChe... |
831352bf70e6115048ad48ce58d28c23a8c5dcd5 | fredericobe/Cf2.Nlp | /v0/Cf2.Nlp/intent.py | 2,533 | 3.53125 | 4 | from phrase import Phrase
class Intent:
"""An Intent has a collection of Training Phrase, and possible responses."""
def __init__(self):
self.Name = ""
self._trainingPhrases = []
self.Parameters = {}
self.Responses = []
self.Corpus= []
self.InputContexts = []
... |
5b91c3e4783f66430668dd9d0f3c0b427342e460 | fredericobe/Cf2.Nlp | /v0/Cf2.Nlp/wordProcess.py | 1,168 | 3.703125 | 4 | import nltk
from nltk.stem import RSLPStemmer
class WordProcess:
"""WordProcess is low level class to pre process words, performing task as clearing stop words, stemming the words and creating tokens from word"""
def __init__(self):
pass
def Tokenize(self,sentence):
sentence = senten... |
a071f8b8b8283a0009c8ce894ac6797e3c5ca933 | sagarsv04/DeepLearningIntro | /TensorFlowClassification/tensorflow_classification.py | 3,438 | 3.828125 | 4 | import pandas as pd # A beautiful library to help us work with data as tables
import numpy as np # So we can use number matrices. Both pandas and TensorFlow need it.
import matplotlib.pyplot as plt # Visualize the things
import tensorflow as tf # Fire from the gods
import os
# os.g... |
3868ad37a26a7ca1b5799e155c5433200e5c98ff | bmilne-dev/cli-games | /hangman.py | 2,259 | 4.40625 | 4 | # a hangman program from scratch.
from random import randint
filename = "/home/pop/programming/python_files/word_list.txt"
with open(filename) as f:
words = f.read()
word_list = words.split()
# define a function to select the word
def word_select(some_words):
"""choose a word for hangman from a word list"""... |
3c2ab8a5ca9b1be068faf446e6e06fcbaae52880 | Damodaran-D/python | /waiter2.py | 1,122 | 3.71875 | 4 | class Stack:
def __init__(self):
self.items = []
def isEmpty(self):
return self.items == []
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
def peek(self):
return self.items[len(self.items)-1]
def size(s... |
a0d9a0f4e22b64bd699822de42b60655e4713979 | snigdhayan/QuantumComputing | /SuperdenseCoding.py | 1,351 | 3.8125 | 4 | """Superdense coding in Cirq."""
# Imports
import cirq
# Helper function for visualizing output
def bitstring(bits):
return ''.join('1' if e else '0' for e in bits)
# Create two quantum and classical registers
qreg = [cirq.LineQubit(x) for x in range(2)]
circ = cirq.Circuit()
# Dictionary of operations for each... |
9040e4ac53ff3cb8910f822ad15b2cb26c88d73b | HectorGit/starter-snake-python | /app/testFile.py | 6,564 | 3.703125 | 4 |
#kinsol research...
def main():
#data = {}
data = {"game": {"id": "game-id-string"},"turn": 1,"board": {"height": 11,"width": 11, "food": [{"x": 7,"y": 0}],"snakes": [{"id": "snake-id-string","name": "Sneky Snek","health": 100,"body": [{"x": 5,"y": 5}]}]},"you": {"id": "snake-id-string","name": "Sneky Snek","heal... |
2863a8b66e1925c0b4cb733309b63cedc56fc76a | philipdexter/aoc | /2022/2/1.py | 781 | 3.65625 | 4 |
with open('input.txt') as f:
lines = f.read().strip().split('\n')
def score_choice(choice: str) -> int:
match choice:
case 'X':
return 1
case 'Y':
return 2
case 'Z':
return 3
def score_winner(other: str, you: str) -> int:
if other == 'A' and you == 'X' or other == 'B' and you == '... |
4ed343e9e1a2d9960e16f2dafe3e5c81b6a29ac4 | philipdexter/aoc | /2022/4/1.py | 369 | 3.5 | 4 | with open('input.txt') as f:
lines = f.read().strip().split('\n')
def fully_contains(a: int, b: int, c: int, d: int) -> bool:
return a >= c and b <= d or c >= a and d <= b
num = 0
for line in lines:
first, second = line.split(',')
a, b = first.split('-')
c, d = second.split('-')
if fully_contains(int(a), ... |
6f8b0e28fbf52b4f72a2e89fbdb556c3edb384b0 | philipdexter/aoc | /2022/3/2.py | 424 | 3.515625 | 4 |
with open('input.txt') as f:
lines = f.read().strip().split('\n')
def priority(c: str) -> int:
return 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'.index(c) + 1
assert priority('a') == 1
assert priority('A') == 27
agg = 0
for i in range(0, len(lines), 3):
line1, line2, line3 = lines[i:i+3]
in_all = ... |
ab86239d551767d3de2bb3b19c7564168488470c | jfruizg/BFSphy | /BFSapl.py | 594 | 4.03125 | 4 | import collections
# funcion en donde vamos a agregar el grafo y la raiz
def bfs(graph, root):
visited, queue = set(), collections.deque([root])
visited.add(root)
while queue:
elemento = queue.popleft()
print(str(elemento) + " ", end="")
# si no esta visitada entonces la agregamos... |
baa0e82ebbe2f709c25bbfbc928cb2bf72ec76b0 | cballsy/raspberry-pi | /reflex_game/reflex_game.py | 2,959 | 3.578125 | 4 | # import modules
import RPi.GPIO as GPIO
import time
import random
def right_wins():
global right_score
right_score += 1
GPIO.output(13, True)
time.sleep(1)
GPIO.output(13, False)
def left_wins():
global left_score
left_score += 1
GPIO.output(15, True)
time.sleep(1)
GPIO.out... |
4b4a167aaefb2d6ccb840937f02b32a2fab0ae71 | jamesledwith/Python | /PythonExercisesWk2/4PercentageFreeSpace.py | 627 | 4.28125 | 4 | #This program checks the percentage of disk space left and prints an apropiate response
total_space = float(input("Enter total space: "))
amount_used = float(input("Enter amount used: "))
free_space_percent = 100 * (total_space - amount_used) / total_space;
print(f"The percentage of free space is {free_space_perc... |
1aa0b37bbe5ba3552103beb6b0aadc6a21061c04 | jamesledwith/Python | /PythonExercisesWk1/10GenerateRandomPassword.py | 427 | 3.84375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Sep 23 12:10:39 2020
@author: James
"""
import string
from random import randint
from random import choice
print("This program generates password")
firstWord = input("Enter the first word: ")
secondWord = input("Enter the second word: ")
randDigit = randint(0,9)
ran... |
d3071d6ccbe27bca1a77040d0e3bb588eec38eee | jamesledwith/Python | /PythonExercisesWk1/5AreaAndPerimeter.py | 419 | 3.953125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Sep 22 21:17:50 2020
@author: James
"""
print("This program calculates the area and perimeter of a rectangle")
length = float(input("Enter the length in meters: "))
width = float(input("Enter the width in meters: "))
area = length * width
perimeter = 2* (length + width) ... |
25f42be209ce937b382bd74243f2ce5a4df391c5 | jamesledwith/Python | /PythonExercisesWk2/3MatchResults.py | 472 | 4.125 | 4 | #This program displays a match result of two teams
hometeam_name = input("Home team name? ")
hometeam_score = int(input("Home team score? "))
awayteam_name = input("Away team name? ")
awayteam_score = int(input("Away team score? "))
if hometeam_score > awayteam_score:
print("Winner: ",hometeam_name)
elif away... |
1de73cda72d4391293a1631173215ba74174d025 | jamesledwith/Python | /PythonExercisesWk1/11VoltageToDC.py | 327 | 4.40625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Sep 23 12:59:21 2020
@author: James
"""
import math
print("This program calculates the Voltage in a DC Circuit")
power = int(input("Enter the power: "))
resistance = int(input("Enter the resistance: "))
voltage = math.sqrt(power * resistance)
print(f"Voltage is {volta... |
aabb0fee36bc18c5a53dbcc3dfcc66486e14fa2f | jamesledwith/Python | /PythonExercisesWk1/14DistanceBetweenTwoPoints.py | 527 | 4.03125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Sep 23 13:33:44 2020
@author: James
"""
import math
print("This program calculates the distance between two points")
x1 = int(input("Enter the x-coordinate of the first point: "))
y1 = int(input("Enter the y-coordinate of the first point: "))
x2 = int(input("Enter the x-coo... |
59b6961385536a2c378c4b711c6895a6ce2b7108 | jamesledwith/Python | /PythonExercisesWk11/functions.py | 2,567 | 3.625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Jan 2 13:39:08 2021
@author: James
"""
from bs4 import BeautifulSoup
import requests
import pandas as pd
def pretify_soup(soup):
return soup.prettify()
def find_hrefs(soup):
"""
Parameters
----------
soup : BeautifulSoup Object
Soup ob... |
b5721d6b22a14dc058b9ee4d825c7a9ef6149f60 | alittlefish128/workStar | /FirstDay/Myfirst.py | 4,880 | 3.59375 | 4 |
# print("hello world")
# print("abc")
# print('你好')
# if 1==1:
# print("1的确等于1")
# else:
# print("1是不等于1的")
# print('程序结束')
# print('ab\'c')
# print("bc'd")
# s1='hello"world'
# s2="hello'world"
# s3="""abc
# bcd
# def"""
# s4='''a
# b"""
# c
# d'''
# s5='中文';#这个是注释
# # 你好
# if 1==1:
# print('a')
# e... |
8248cd572a6cbb38e698d636e27603ee508504e3 | tpsimopoulos/Tic-Tac-Toe | /Single Player vs AI/player.py | 4,521 | 3.921875 | 4 | import random
import math
class Player:
def __init__(self, letter):
self.letter = letter
class RandomPlayer(Player):
def __init__(self, letter):
super().__init__(letter)
def get_move(self, game):
"""This function selects a random spot on the board from the available moves."""
... |
e8cd3d172cba768564a53ad50340913e243ef8fa | hsalluri259/scripts | /python_scripts/odd_even.py | 946 | 4.53125 | 5 | #!/opt/app/python3/bin/python3.4
'''
Ask the user for a number. Depending on whether the number is even or odd, print out an appropriate message to the user. Hint: how does an even / odd number react differently when divided by 2?
Extras:
If the number is a multiple of 4, print out a different message.
Ask th... |
1746b077b77a2e8569e7b2c2c96968fc63485386 | Pufke/SearchEngine | /SearchEngine/parserGraph/Graph.py | 5,983 | 3.828125 | 4 | from set import *
class Graph:
def __init__(self, directed=False):
self._outgoing = {}
self._incoming = {} if directed else self._outgoing
class Vertex:
"""Lightweight vertex structure for a graph."""
__slots__ = '_element'
def __init__(self, x):
"""Do not ... |
01a2437c1c7948c2157cfbead2262637ad942de9 | christinasherin4/python-notes | /teamvsforloop.py | 283 | 4.03125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat May 16 00:58:38 2020
@author: Christina
"""
teams = ['Dragons','Wolves','Pandas','Unicorns']
for home_team in teams:
for away_team in teams:
if home_team != away_team:
print(home_team + "vs" + away_team) |
8df5c0ed74684dca3e1b2d85e276b70b7f1408f1 | christinasherin4/python-notes | /contacts.py | 1,221 | 3.59375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Jun 23 07:54:25 2020
@author: Christina
"""
'''name=input("Enter the name")
age=int(input("Enter the age"))
#phno=int(input("Enter the phone number"))
print("My name is :",name)
print("My age is:",20)'''
'''salary =int(input("Enter the employees salary"))
da... |
82e696a4d5bf908f93c256f5d8c89ffc7c48c4e8 | milden6/nlp-tasks | /task_3/common_utils.py | 1,006 | 3.5 | 4 | import tokenizator
import os
import re
# create dict from text with key and value(word count)
def create_dict(text):
words_dict = {}
words_list = tokenizator.get_words(text)
for word in words_list:
if word in words_dict:
word_count = words_dict.get(word)
words_dict[word] =... |
10b1b51007d72997d423df36c55a987f27208f4f | ragnarokkrr/rgn_py_sketch | /generator.py | 1,395 | 3.796875 | 4 | def simple_generator():
yield 1
yield 2
yield 3
def test_simple_generator():
generator = simple_generator()
print next(generator)
print next(generator)
print next(generator)
def my_gen(n):
yield n
yield n + 1
def test_my_gen():
g = my_gen(6)
print next(g)
print ne... |
5f33814fd3a76665dd4deef46a623231757236b1 | MrWQ/Parser | /Analysis/Stack.py | 1,323 | 4.25 | 4 | class Stack(object):
# 初始化栈为空列表
def __init__(self):
self.items = []
# 判断栈是否为空,返回布尔值
def is_empty(self):
return self.items == []
# 返回栈顶元素
def peek(self):
if (self.is_empty() == False):
return self.items[len(self.items) - 1]
# 返回栈的大小
def size(self):
... |
8026ce987b2ed319dee7faf702c82772be01e708 | dzhonapp/python_programs | /Loops/averageRainfall.py | 1,003 | 4.375 | 4 | '''Write a program that uses nested loops to collect data and calculate the average rainfall
over a period of years. The program should first ask for the number of years. The outer loop
will iterate once for each year. The inner loop will iterate twelve times, once for each month.
Each iteration of the inner loop will ... |
2a01fa4ae6ce346f1ff91345f3a7319a963d2ad5 | dzhonapp/python_programs | /Loops/calculation_factorial_of_number.py | 496 | 3.921875 | 4 | '''In mathematics, the notation n! represents the factorial of the nonnegative integer n . The
factorial of n is the product of all the nonnegative integers from 1 to n. For example,
7! = 1 x 2 x 3 x 4 x 5 x 6 x 7 = 5,040
and
4! = 1 x 2 x 3 x 4 = 24
Write a program that lets the user enter a nonnegative integer and the... |
88e5b97445cd2ecbaf8dd5d54ce39aa3fc1bbd16 | dzhonapp/python_programs | /Loops/budgetAnalysis.py | 842 | 4.09375 | 4 | '''3. Budget Analysis
Write a program that asks the user to enter the amount that he or she has budgeted for
a month. A loop should then prompt the user to enter each of his or her expenses for the
month and keep a running total. When the loop finishes, the program should display the
amount that the user is over or und... |
94b675bb81acbb2d07829c4180920a36bb601b8b | dzhonapp/python_programs | /Basics/Celsius to Fahreneit Temperature Converter.py | 429 | 4.25 | 4 | '''9. Celsius to Fahrenheit Temperature Converter
Write a program that converts Celsius temperatures to Fahrenheit temperatures. The formula
is as follows:
F =9/5C+32
The program should ask the user to enter a temperature in Celsius, and then display the
temperature converted to Fahrenheit.
'''
fahreneit= int(input('... |
e3f1b8b9ea8f7a164a264126615e694621d27abf | dzhonapp/python_programs | /test.py | 1,067 | 3.796875 | 4 | def series_sum(n):
sum = 0
if n == 1:
return format(float(n), ",.2f")
for i in range(1, n * 3 + 1, 3):
sum += 1 / i
return format(float(sum), ",.2f")
# Happy Coding ^_^
#print(series_sum(2))
def series_sum(n):
return '{:.2f}'.format(sum(1.0/(3 * i + 1) for i in range(n)))
def... |
e0ac95b4e74c52e064806926b74dd0d74951d9ba | dzhonapp/python_programs | /functions/stadiumSeating.py | 1,231 | 4.09375 | 4 | '''
7. S tadium Seating
There are three seating categories at a stadium. For a softball game, Class A seats cost $20,
Class B seats cost $15, and Class C seats cost $10. Write a program that asks how many
tickets for each class of seats were sold, and then displays the amount of income generated
from ticket sales.
'''
... |
d5e74ba40cbea50dad5cfa8407b6f7d6941b8617 | dzhonapp/python_programs | /Loops/tuitionIncrease.py | 474 | 3.796875 | 4 | '''
10. T uition Increase
At one college, the tuition for a full-time student is $8,000 per semester. It has been
announced that the tuition will increase by 3 percent each year for the next 5 years. Write
a program with a loop that displays the projected semester tuition amount for the next 5
years.
'''
tuition =8000;... |
8d0ae7668e921e6e0047c1143cfbcdbf56f701a6 | dzhonapp/python_programs | /functions/milesPerGallon.py | 507 | 4.34375 | 4 | '''Miles-per-Gallon
A car’s miles-per-gallon (MPG) can be calculated with the following formula:
MPG = Miles driven / Gallons of gas used
Write a program that asks the user for the number of miles driven and the gallons of gas
used. It should calculate the car’s MPG and display the result.
'''
def mpgCalculate():
... |
ebec474eb20cfa6f338595a9bccf23b95a541dfd | dzhonapp/python_programs | /Loops/oceanLevels.py | 382 | 4.3125 | 4 | '''
Assuming the ocean’s level is currently rising at about 1.6 millimeters per year, create an
application that displays the number of millimeters that the ocean will have risen each year
for the next 25 years.
'''
millimeters=1.6
for years in range(25):
print("Year #", years+1)
print('Millimeters risen so far... |
295565787d34136cec096c6c2c11fcb88491aa72 | StewartTristan/matasano-cryptopals | /src/polynomial.py | 3,149 | 4.1875 | 4 | """Functions to deal with polynomials f(x), e.g. f(x) = 3x^3 - 2x^2 + x - 5."""
from . import mod
class Polynomial:
"""Representation of a polynomial f(x) = c[n]*x^n + ... + c[1]*x + c[0]."""
def __init__(self, coefficients):
"""Represents f(x) = c[n]*x^n + ... + c[1]*x + c[0]."""
assert l... |
6bf98412d2ef46c8bea31c3d5f12cfb2365c8ca7 | ZapAnton/black_red_tree | /python/tree_node.py | 1,165 | 3.578125 | 4 | from enum import Enum
NODE_TYPE = Enum('NODE_TYPE', 'BLACK RED')
class TreeNode:
def __init__(self, item: int, node_type: NODE_TYPE):
self.item = item
self.node_type = node_type
self.left_child = None
self.right_child = None
self.parent = None
def get_uncle_node(... |
23866c7ac5260b48b5cf27fa8b825af270055aae | fsalazarsch/cursos_nullpointerex | /Python/mate.py | 2,333 | 3.625 | 4 | def menu():
opcm = 0
while(opcm != 5):
op2 = 'y'
op4 = 'y'
print "1) Elegir 'p','q' y 'e'"
print "2) Sacar Modulo"
print "3) Decodificar"
print "4) Sacar decodificado Modulo"
opcion = (int) (raw_input("SELECCIONE UNA OPCION: "))
if(opcion == 1):
rsa = RSA()
if(opcion == 2):... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.