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 |
|---|---|---|---|---|---|---|
cc4567c9e791a28967438b7ee366c65991c648f2 | marvinusarif/evolve_ml | /gradient_descent/gradient_descent.py | 573 | 3.796875 | 4 |
def f_x(x):
ret=x**4 -3*x**3+2
return ret
def f_prime_x(x):
ret=4*x**3-9*x**2
return ret
def gradient_descent():
x_old=0.0
x_new=6.0
precission=0.00001
max_iter=1000
# learning_rate=0.01
learning_rate=0.0001
# learning_rate=0.1
iter=0
while abs(x_new-x_old)>precissi... |
1647f7d1e4a3ce1e0f7d6ac7c13f71ea8fee18af | marvinusarif/evolve_ml | /NLP/example_remove_stop_words.py | 520 | 3.65625 | 4 | # load data
filename = 'metamorphosis_clean.txt'
file = open(filename, 'rt')
text = file.read()
file.close()
# split into words
from nltk.tokenize import word_tokenize
tokens = word_tokenize(text)
# convert to lower case
tokens = [w.lower() for w in tokens]
words = [word for word in tokens if word.isalpha()]
# filter o... |
34cbdb4a529aed15eb8e907166a3ba3dc1142556 | ankit2100/DataStructures_Python | /DoublyLinkedList.py | 1,081 | 3.90625 | 4 | __author__ = 'ankit.b.patel'
class Node:
def __init__(self,data):
self.data = data
self.next = None
self.prev = None
class Linkedlist:
def __init__(self):
self.head = Node(None)
def AddNode(self,data):
newnode = Node(data)
currnode = self.head.nex... |
93c234da4e370fe8f461333046881c517847b856 | nileshgulve/Python_Tutorial | /tuple_set.py | 848 | 3.984375 | 4 | # tuple is almost same as list, tuple is imutale but list is mutable
tup = (21,36,13,14,25)
tup
(21, 36, 13, 14, 25)
tup[1]
36
tup[1] = 50
Traceback (most recent call last):
File "<input>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
# value assignment is not possible in tuple
tup.c... |
f9d5f62e4c017c92b7474d5f68c7c474875fa66d | MohitPuri1996/Urlshortner | /check.py | 170 | 3.59375 | 4 | import string,random
length=7
final=""
char=string.digits+string.ascii_uppercase+string.ascii_lowercase
for _ in range(length):
final+=random.choice(char)
print final |
fa0876deb90ccee84d3433dbe8b4f9d1fda3fabb | cotyq/discompsci | /TP2/Personas.py | 1,617 | 3.765625 | 4 | """
4. Personas
Construya una estructura de clases que represente una serie de personas caracterizadas por el nombre (compuesto de
nombre de pila y dos apellidos) y el número del DNI. Debe ser posible imprimir los datos completos de una persona y
devolver el nombre o el DNI independientemente.
"""
class Persona:
... |
95836498b122e16d07842b9683b6af601b2e5170 | ES2Spring2019-ComputinginEngineering/project-one-bluemessagegang | /PendulumSimulation.py | 1,188 | 3.640625 | 4 | """ Here is our pendulum situation. For some reason we are getting
an index out of bounds error during the while loop but I can't figure
out why. We are also still having issues with the time step even though
we feel as though it should be working (compared to the model)
This code was made by Grace Anderson and Bowton ... |
ff85b59aa8da651d0741cd12b90b9a811cc1a408 | leo-morita/snake-projeto | /br/com/unifil/project/snake/Main/TestandoPyGame.py | 3,042 | 3.671875 | 4 | import pygame
print("Welcome to Snake-project")
print("Teste")
def main():
# Iniciar o pygame
pygame.init()
# Carregar e definir o logotipo
logo = pygame.image.load("logo32x32.png")
pygame.display.set_icon(logo)
pygame.display.set_caption("Snake")
# Crie uma superfície na tela que tenha ... |
e0d1607626934f908eb4d08d95ad5611fcafd7fe | marcellasiqueira/programacao1 | /matrizmenor/matrizmenor.py | 685 | 3.578125 | 4 | # coding: utf-8
# Matriz Menor
# 2017, Marcella Siqueira / UFCG, Programação 1
# Matrícula: 117110492
def matriz_menor(matriz, matriz2):
nova_matriz = []
for i in range(len(matriz)):
nova_matriz.append([])
for i in range(len(matriz)):
for j in range(len(matriz[i])):
if matriz[i][j] < matriz2[i][j]:
nova... |
b437f478abe10f06c0fcfa8f63ab4ef0317f8f65 | marcellasiqueira/programacao1 | /buscamatriz/buscamatriz.py | 431 | 3.6875 | 4 | # coding: utf-8
# Busca em Matriz
# 2017, Marcella Siqueira / UFCG, Programação 1
# Matrícula: 117110492
def busca_matriz(m, e):
for i in range(len(m)):
for j in range(len(m[i])):
if m[i][j] == e:
return (i, j)
else:
return None
matriz = [
[2, 3, 5, 3, 1],
[3, 2, 1, 5, 6],
[1, 2, 3, 2, 1],
]... |
d1bcd4c6265cf9fe0f146f9bf5785afa6be5e43d | marcellasiqueira/programacao1 | /coluna/coluna.py | 374 | 3.515625 | 4 | # coding: utf-8
# Coluna
# 2017, Marcella Siqueira / UFCG, Programação 1
# Matrícula: 117110492
def coluna(matriz, i):
nova_matriz = []
for j in range(len(matriz)):
nova_matriz.append(matriz[j][i])
return nova_matriz
M = [[1,1,1,1],[2,2,2,2],[3,3,3,3]]
assert coluna(M,0) == [1,2,3]
assert coluna(M,1) == [1,2,... |
76141fd127577454b11df946e88d9c1a1bce82df | marcellasiqueira/programacao1 | /treinos (nenhuma questão específica)/matriculas.py | 323 | 3.640625 | 4 | # coding: utf-8
N = int(raw_input())
pos_maior, digitos = 0, [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
for i in range(N):
matricula = raw_input()
for digito in matricula:
dig = int(digito)
digitos[dig] += 1
for i in range(1, 10):
if digitos[pos_maior] < digitos[i]:
pos_maior = i
print pos_maior, digitos[pos_maio... |
f8e31d5deb59eb12cca3dae518530a53d3da21c7 | marcellasiqueira/programacao1 | /dobradas/dobradas.py | 624 | 3.828125 | 4 | # coding: utf-8
# Palavras com Letras Dobradas
# 2017, Marcella Siqueira / UFCG, Programação 1
# Matrícula: 117110492
N = int(raw_input())
palavras, dobradas, nao_dobradas = [], [], []
for i in range(N):
palavras.append(raw_input())
for palavra in palavras:
for i in range(len(palavra) - 1):
if palavra[i] == pal... |
6311f583768f7e432a9cc0acfdfb63200f682f51 | marcellasiqueira/programacao1 | /conjuntos/conjuntos.py | 426 | 3.640625 | 4 | # coding: utf-8
# Conjuntos Maiores
# 2017, Marcella Siqueira / UFCG, Programação 1
# Matrícula: 117110492
limite, num = int(raw_input()), int(raw_input())
mconj, mnum = [], []
for i in range(num):
soma = 0
while True:
conjunto = int(raw_input())
if conjunto < 0: break
soma += conjunto
if soma > limite:
mc... |
6e6009698f920a27c72e90785a21b95b923f82e2 | marcellasiqueira/programacao1 | /octal/octal.py | 379 | 3.828125 | 4 | # coding: utf-8
# Convertendo um Número Octal em um Número Decimal
# 2017, Marcella Siqueira / UFCG, Programação 1
# Matrícula: 117110492
octal = raw_input()
cont, soma = len(octal) - 1, 0
for i in range(len(octal)):
print "%i * 8^%i = %i" % (int(octal[i]), cont, int(octal[i]) * 8 ** cont)
soma += int(octal[i]) * ... |
c7443b333e6f8b64ca5e5d55c3cdaf0b64c8e291 | Necrolord/LPI-Course-Homework-Python-Homework- | /Exercise2-2.py | 1,123 | 4.53125 | 5 | #!/bin/usr/env python3.6
# This method is for reading the strings
def Input_Str():
x = str(input("Enter a String: "))
return x
# This method is for reading the number.
def Input_Num():
num = int(input("Enter a number between 1 and 3 included: "))
if ((num < 1) or (num > 3)):
print('The number ... |
413d4d337238250c43c15b22333c9b1e6a807c38 | sarah105/frist-x-o | /X O.py | 7,884 | 4 | 4 | import random
def printBoard():
for i in range(1,10):
if(i%3==0):
print(arr[i])
else:
print(arr[i],end="|")
arr=[0,1,2,3,4,5,6,7,8,9]
print("if you want play with computer enter pc else enter friend : ")
choise=input()
while(choise != "pc" and choise!= "frie... |
93789f47559c7db71cb84bab5ee6487d9acb6efd | Elionidas/Networking_Practice | /StructPackaging.py | 1,200 | 3.671875 | 4 | """
Lab 3A.py
Name: Elias Perez
Date: September 14th, 2018
"""
'''
Using the struct package from the python library, pack the values (1, 2, -3, -4) as the following data types (unsigned short, unsigned int, signed short, signed int)
1 as an unsigned short
2 as an unsigned int
-3 as a signed short
-4 as a signed int
Wr... |
450b5ad525a46108ebf79eed1c8bc334a40ef324 | Elionidas/Networking_Practice | /SimpleClient.py | 389 | 3.5625 | 4 | import socket
#Specify server IP and Port (where data is being transmitted)
HOST = 'localhost'
PORT = 8888
#Create socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#Initiate a connection
s.connect((HOST, PORT))
#Send data
s.sendall('Hello my name is World')
#Receive data (buffer)
data = s.recv(1024)
#Close ... |
97d2b2e035a8e0487990c8b35362440f899e80e4 | saurabhchobey/Data-structure | /bst3.py | 348 | 3.546875 | 4 | a=[]
b= int(input())
target=int(input())
for i in range(0,b):
c=int(input())
a.append(c)
def linear(a,target):
for j in len(a):
if a[i]==target:
return True
return False
def binary(a,target):
low=0
high=len(a)-1
while low<high:
mid=(low+high)//2
if target==a(mid):
return Tru... |
5c8a3842f80279a0f15ea37094bbabc6e5942845 | jookies/jasmin | /jasmin/routing/Bills.py | 3,091 | 3.84375 | 4 | """
Bills are objects containing amounts to be charged on users
"""
import uuid
class InvalidBillKeyError(Exception):
"""Raised when a bill key is not valid
"""
class InvalidBillValueError(Exception):
"""Raised when a bill value is not valid
"""
def randomUniqueId():
"""Returns a UUID4 unique ... |
dcb0bda589cba60a2bc460bca8621ad20c4752c0 | programmingthomas/iOS-Fonts | /list.py | 267 | 3.5 | 4 | sixFonts = open("ios6fonts.txt").read().split("\n")
sevenFonts = open("ios7fonts.txt").read().split("\n")
f = open("newios7fonts.txt", "w")
for newFont in sevenFonts:
if not newFont in sixFonts:
print(newFont);
f.write(newFont + "\n")
f.close() |
ca678ec3f72318c43ecfbdadf2f1c37783003236 | bharadwaj6/lottery_ticket_checker | /main.py | 5,861 | 3.734375 | 4 | class LotteryNumberValidator(object):
def __init__(self, strings):
self.strings = strings
self.valid_string_mappings = {}
self.is_validated = False
def _are_sequential_indexes(self, non_indices):
"""Check if the given indices are sequential two digit numbers"""
continuou... |
c1745c3bc39848e7487f29407de2f63a298316e9 | doum1004/code_assessment | /leetcode/leetcode_python/search-suggestions-system.py | 1,882 | 3.65625 | 4 | from typing import List
import bisect
"""
https://leetcode.com/problems/search-suggestions-system/submissions/
"""
class Trie:
def __init__(self):
self.children = {}
self.string = ''
self.cache = []
def addWord(self, s):
trie = self
for c in s:
if c not... |
2fa8392e1c59b5bad86b4aaab58434f92091c958 | doum1004/code_assessment | /leetcode/leetcode_python/largest-bst-subtree.py | 860 | 3.625 | 4 | """
https://leetcode.com/problems/largest-bst-subtree/submissions/
"""
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def largestBSTSubtree_BSF(self, root: TreeNode) -> int:
def countBS... |
3f891c5339f933a900b026d6d2c5f77b1ccc47d4 | doum1004/code_assessment | /leetcode/leetcode_python/count-and-say.py | 604 | 3.5 | 4 | """
https://leetcode.com/problems/count-and-say/
"""
class Solution:
def countAndSay(self, n: int) -> str:
if n == 1:
return "1"
elif n == 2:
return "11"
res = ''
result = self.countAndSay(n-1)
pre = ' '
count = 0
for c in res... |
cfa1acb09ddaeb5ca6013d2155f5c4a0adb646f2 | doum1004/code_assessment | /leetcode/leetcode_python/all-nodes-distance-k-in-binary-tree.py | 1,610 | 3.921875 | 4 | from typing import List
import collections
"""
https://leetcode.com/problems/all-nodes-distance-k-in-binary-tree/
solution1. Get target distance and path to target (DSF). DSF to get distnace from target (if node is in path, -1. else +1)
solution2. Save parent info(DSF). Iterate from target with parent as child as we... |
9a5520b827c2e289b0ca820995326b13e552c7ec | doum1004/code_assessment | /leetcode/leetcode_python/network-delay-time.py | 1,455 | 3.5625 | 4 | from typing import List
import collections
import heapq
"""
https://leetcode.com/problems/network-delay-time/
"""
class Solution:
def networkDelayTime_dijkstra(self, times: List[List[int]], N: int, K: int) -> int:
#build graph
g = collections.defaultdict(list)
for u,v,w in times:
... |
42b5a258cfd58eed41179a74725c4f7c3ec5aade | X-Crux/guess_word | /main.py | 1,327 | 3.890625 | 4 | from random import choice
def start_game():
words_bank = [
'дорога', 'мороженое', 'дерево',
'телефон', 'аккредитация', 'шапка',
'страна', 'лето', 'пароход'
]
secret_word = choice(words_bank)
# print(secret_word)
gamer_word = ['*'] * len(secret_word)
print(''.join(gam... |
8c9ea0992cdd777b06b412defdbec651f2eff659 | KarlHeitmann/project-euler | /26-50/problema31.py | 281 | 3.71875 | 4 | for a in range(200,0,-200):
print a
for b in range(a, 0, -100):
for c in range(b, 0, -50):
for d in range(c, 0, -20):
for e in range(d, 0, -10):
for f in range(e, 0, -5):
for g in range(f, 0, -2):
for h in range(g, 0, -1):
|
a6f64be86d26ce6ef4c5b17bf2a792a352db1a56 | ali97730/mypythoncode | /list2.py | 430 | 3.921875 | 4 | fname = input("Enter file name: ")
if len(fname) < 1 : fname = "mbox-short.txt"#if user dont give any file name
fh = open(fname)
count = 0
for line in fh:
line=line.rstrip()
if not line.startswith("From:") : continue
words = line.split()
#print(words)
email = words[1]
count = count +1
print... |
997a66c250ad736aa9caa0cb7be9c8f04c907803 | esme/algorithms | /python/queue.py | 604 | 3.84375 | 4 | class Node:
def __init__(self, data):
self.data = data
self.next = None
class Queue:
def __init__(self):
self.head = self.tail = None
def isEmpty(self):
return self.head == None
def enqueue(self, item):
temp = Node(item)
if (self.tail == None):
self.head = self.tail = temp
... |
7ac7abdc90a09c7032818b375a787dbf1d3cfdc2 | esme/algorithms | /python/unordered_list.py | 1,009 | 4.03125 | 4 | class Node(object):
def __init__(self, value):
self.value = value
self.next = None
class UnorderedList(object):
def __init__(self):
self.head = None
def is_empty(self):
return self.head is None
def add(self, value):
temp = Node(value)
temp.next = self.head
self.head = temp
de... |
9b5ad27a160f8a19d505d96fca3642909659fead | shafaypro/AndreBourque | /assignment1/assignment2.py | 168 | 3.6875 | 4 | # Create a program which creates the Boolean Table for the AND GATE?
B_input = str(input("Enter the Bth Value"))
if A_input == 'T' and B_input == 'T':
print ("True")
|
23c4b91775a740a59ad4970b20935d3cfb50e768 | shafaypro/AndreBourque | /assignment1/mood2.py | 2,454 | 4.53125 | 5 | mood = input('Enter the mood of yours (angry,sad,happy,excited)') # we are taking an input in the form of a string
"""
if mood == "angry": # check the value of the variable mood if the value is angry compares that with angry
print("Your %s" % mood) # the variable mood value is then replaced in the place of %s
prin... |
4af27721ff410ec474483a35f3f9051308e15911 | Serruhb/Python-Challenge | /PyBank/main.py | 1,777 | 3.671875 | 4 | #Budget_Data
import csv
import os
budget_data = os.path.join("budget_data.csv")
with open(budget_data,newline="") as budge_data:
read_budget = csv.reader(budge_data,delimiter = ",")
#Find the total month in the data set
netTotal = 0
count = 0
greatestInc = 0
greatestDec = 0
lastMon... |
dc648e1a2591d3d0f9a19d7aa6b1c569fb64e1f7 | ronkagan/web-scraping-and-automation | /cl/list-practice/04-readlines.py | 463 | 3.609375 | 4 | # define empty list
urls_list = []
# open file and read the content in a list
with open('listfile.txt', 'r') as filehandle:
urls = [current_url.rstrip() for current_url in filehandle.readlines()]
# Having opened the file listfile.txt in line 5, re-establishing the list takes place entirely in line 6.
# In a `for` loo... |
128b512d5f90071d68b8d39397741ee5405708e6 | Reykjabik/I-m-Feeling-Lucky-Google-Search | /feelingLucky.py | 1,864 | 3.78125 | 4 | #! python3
'''
It would be nice if I could simply type a search term on the command line and have my computer automatically open a browser with all the top search results in new tabs. Let’s write a script to do this.
This is what your program does:
- Gets search keywords from the command line arguments.
- Retrieve... |
a32dd03d61e16ffdc48bb04ee4715b4fabeb500d | marciorgb/computacao-evolutiva | /CP/selecao.py | 2,273 | 3.578125 | 4 | from statistics import mean
from codificacao import start_population
from fitness import *
from Seleção import *
from cruzamento import *
from substituição import *
from graficos import *
import matplotlib.pyplot as plt
import random as r
import copy
import time
def selecao_prob(population, fitness, fitness_avg):
... |
5d069d42d975537546427ffa5b70c79548c1ed29 | sharang1996/python-code-dump | /argraw.py | 508 | 3.71875 | 4 | from sys import argv
script,user_name=argv
prompt='> '
print "Hi %s im the %s script"%(user_name,script)
print "I would like to ask you a few questions"
print "Do you like me %s"%(user_name)
ans=raw_input(prompt)
print "where do you live %s" %(user_name)
lives=raw_input(prompt)
print "what kind of computer do you have?... |
d5760056d5a3651e177ebe06ac66e7769eb4450d | franciscomunoz/pyAlgoBook | /chap3-Algorithm_Analysis/R-3.3.py | 512 | 3.765625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Dec 11 19:20:38 2016
@author: francisco
"""
import matplotlib.pyplot as plt
import numpy as np
n = np.arange(1,30,1)
f_n1 = 40*np.power(n,2)
f_n2 = 2*np.power(n,3)
fig, an = plt.subplots()
an.plot(f_n1)
an.plot(f_n2)
#Find the index in which fn_1 start exhibiting better pe... |
30db7f2a89d91bdd140df331d0b039d896803ee1 | franciscomunoz/pyAlgoBook | /chap4-Recursion/C-4.19.py | 1,890 | 4.4375 | 4 | """Function that places even numbers before odd
if returns are removed in the else condition, the recursion
tree becomes messy as shown :
(0, 6, [2, 3, 5, 7, 9, 4, 8])
(1, 6, [2, 3, 5, 7, 9, 4, 8])
(2, 5, [2, 8, 5, 7, 9, 4, 3])
(3, 4, [2, 8, 4, 7, 9, 5, 3])
(4, 3, [2, 8, 4, 7, 9, 5, 3])
(3, 4,... |
ceb05061f9cfe8ca73a4a3aa8a78cdff34dd007e | franciscomunoz/pyAlgoBook | /chap1/R-1.7.py | 169 | 4.15625 | 4 | #!/usr/bin/python
n = int(input("Type the number for the odd squared sum : "))
value = sum([i*i for i in range(0,n) if i & 1 != 0])
print("The sum is : " + str(value))
|
7981d8de44f4d1aaaab8aec30ea50b9fb1a87c48 | franciscomunoz/pyAlgoBook | /chap5-Array-Based_Sequences/C-5.13.py | 1,095 | 4.125 | 4 | """The output illustrates how the list capacity is changing
during append operations. The key of this exercise is to
observe how the capacity changes when inserting data to an
an array that doesn't start at growing from size "0". We
use two arrays, the original from 5.1 and another starting
to grow from a different va... |
1c21065d7f6f684e6bead35fd67b85ba24175f5d | franciscomunoz/pyAlgoBook | /chap5-Array-Based_Sequences/C-5.24.py | 1,606 | 3.953125 | 4 | """This short program illustrates the amount of microseconds required for
removing elements in the beginning, middle and end of a list"""
import sys # provides getsizeof function
from time import time
if __name__ == '__main__':
tests = []
tests.append([0]*100)
tests.append(... |
6fec80167c6661496d21ed4018871507540e77e7 | franciscomunoz/pyAlgoBook | /chap6-Stacks_Queues_and_Dequeues/P-6.32.py | 3,824 | 3.9375 | 4 | """Give a complete ArrayDequeue implementation of the double-ended queue ADT
as sketched in Section 6.3.2"""
from exceptions import Empty
class ArrayDequeue:
"""FIFO queue implementation using a Python list as underlying storage."""
DEFAULT_CAPACITY = 10 # moderate capacity for all new queues
... |
efd406bd5d1378e7d1d38e2329d5039fdd069730 | franciscomunoz/pyAlgoBook | /chap5-Array-Based_Sequences/P-5.35.py | 2,019 | 4.25 | 4 | """Implement a class , Substitution Cipher, with a constructor that takes a string
with 26 uppercase letters in an arbitrary order and uses that for the forward
mapping for encryption (akin to the self._forward string in our Caesar Cipher
class ) you should derive the backward mapping from the forward version"""
impor... |
7cdb2ee2fcae8617dfbd5cb6bd5916ac2a69dfb9 | franciscomunoz/pyAlgoBook | /chap4-Recursion/P-4.24.py | 1,211 | 3.796875 | 4 | """Recursive function which solves the following sum puzzle
boy + girl = baby
b o y g i r l a
indexes 0, 1, 2, 3, 4, 5, 6, 7
weights THIS IS WHAT WE PERMUTATE AND MAKE THE SUM (initially same as index)
Many permutations will be created for assigning weights to each word. When a
pe... |
70c89a16f0dd95bffafcf463ea8e6ed7fc766064 | franciscomunoz/pyAlgoBook | /chap1/R-1.15.py | 300 | 3.734375 | 4 | #!/usr/bin/python
def repeatedElements(data):
dataLen = len(data)
for i in range(0,dataLen):
for j in range(0,dataLen):
if i != j:
if data[i] == data[j]:
print("Index {0} and {1} repeat is value with {2}".format(i,j,data[i]))
values = (4,3,5,67,8,8,2,4,5)
repeatedElements(values)
|
36bba347db716ae6e25e237d1bc99292ab8d7b9b | stewartyoung/DeepRL-PM | /src/portfolio-management/utils/dataPreprocessing.py | 7,234 | 3.609375 | 4 | """
Creates a multiIndexed pandas dataframe for stock data with financial and non-financial features
MultiIndex(levels=[['Stock1', ..., 'StockN'], ['close', 'high', 'low', 'open', 'feature']],
labels=[[0, 0, 0, 0, 0, ..., N, N, N, N, N], [0, 1, 2, 3, 4, ..., 0, 1, 2, 3, 4]],
names=['StockName', 'Price'])
"""
import... |
e0bb980636408dfbbe5798a07001fa37291814e9 | brennanharrison/Kattis | /lineup.py | 332 | 3.875 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[11]:
n= int(input())
x = 0
oL = []
while x < n:
u = input()
oL.append(u)
x+=1
oLSort = oL[:]
oLSort.sort()
oLReverse = oLSort[:]
oLReverse.reverse()
if oL == oLSort:
print('INCREASING')
elif oL == oLReverse:
print('DECREASING')
else:
print(... |
e1c2fa8cd520219dfc5b7d328266ceaf9ffadc1a | brennanharrison/Kattis | /moscowdream.py | 244 | 3.578125 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[ ]:
a, b, c, n = [int(x) for x in input().split()]
if a == 0 or b == 0 or c == 0:
print('NO')
elif n == 1 or n == 2:
print('NO')
elif a + b + c < n:
print('NO')
else:
print('YES')
|
6df1bbf079215f8a3435c34d597f9dd18a273e6d | brennanharrison/Kattis | /provincesandgold.py | 446 | 3.625 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[4]:
goldPower = 3
silverPower = 2
copperPower = 1
g, s, c = [int(x) for x in input().split()]
g = g*goldPower
s = s*silverPower
c = c*copperPower
t = g + s + c
if t >= 8:
print('Province or Gold')
elif t >= 6:
print('Duchy or Gold')
elif t >= 5:
print('Duchy... |
6eb58136cfb959d3ed0624b935390f2aa2948f28 | brennanharrison/Kattis | /judgingmoose.py | 236 | 3.875 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[7]:
x, y = [int(x) for x in input().split()]
if x == 0 and y ==0:
print('Not a moose')
elif x > y:
print('Odd', x+x)
elif x < y:
print('Odd', y+y)
else:
print('Even', x+y)
|
28ccf3631624583b3bcff63e5eb433215f03046a | brennanharrison/Kattis | /quickestimates.py | 188 | 3.6875 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[2]:
n = int(input())
x = 0
output = []
while x < n:
i = input()
output.append(len(i))
x+=1
for i in output:
print(i)
|
e3783947e0d6613d0ca3cd71d7efebd9d88c90d5 | Rastowerin/stock_market | /create_db.py | 341 | 3.5625 | 4 | import sqlite3
con = sqlite3.connect('companies.db')
cur = con.cursor()
cur.execute("DROP TABLE companies")
s = ''
for year in range(2006, 2022):
s += "c{} INTEGER,".format(year)
cur.execute("CREATE TABLE companies ("
"name STRING NOT NULL,"
"{}"
"cap INTEGER NOT NULL"
... |
1b3cbb62a21a8a51a604990299fef7fd348f4573 | shivupoojar/openfaas-pi | /serverless/fpressure/handler.py | 638 | 3.65625 | 4 | import requests
def handle(req):
"""handle a request to the function
Args:
req (str): request body
"""
# Get the value from the http request body Extract string value, Ex:
# Pressure= 1010.19090 Split by =, convert it into float
URL = "https://api.thingspeak.com/update?api_key=LJC420IXZO... |
272379b05a98438d3f9e91f62f5d4d87f2cba29e | jesusa2624/PYTHON-BASCIO | /comparaciones.py | 971 | 4.03125 | 4 | # and para comparar si dos valores son verdaderos.
# or para comparar si dos valores son falsos.
# not para invertir el valor booleano.
# == Compara dos valores y te dice si son iguales o no.
# != Compara dos valores y te dice sin son diferentes o no.
# > Compara si es mayor que otro valor.
# > Compara si es menor que ... |
a0a782a0885231bc87f26140f3d7ed488656afcf | avikarto/keygen | /keygen.py | 1,312 | 3.828125 | 4 | # Generates a random password of user-identified length.
# Password must contain at least one upper-case letter, one
# lower-case letter, one number, and one special character.
from random import randint
letters = "abcdefghijklmnopqrstuvwxyz"
numbers = "1234567890"
specials = "!@#$%^&*?~_+-=."
options = letters+... |
0756de75692a2eb778285ddfee2f4cd9bff86c4a | willianjeff/modulo01 | /exercicio8.py | 173 | 3.75 | 4 | gh = 0
mh = 0
gh = float(input('Quanto você ganha por hora: '))
mh = int(input('Informe quantas horas foram trabalhadas: '))
print('O valor total do salario é', gh * mh) |
53cbfd4b21d71ddcfed863740deda6ba964101f6 | aptlin/arler | /arler/Utilities/operate.py | 400 | 3.53125 | 4 | import itertools
def findRoot(digraph):
candidates = [node for node in digraph if digraph.in_degree(node) == 0]
if not candidates:
raise ValueError("No root found, aborting.")
if len(candidates) > 1:
raise ValueError("More than one tree in the hierarchy, aborting.")
return candidate... |
fa09d83420f6f53123cbb1185ded7c9b434df7d9 | ferb2015/TargetOfferByPython | /44. 构建乘积数组.py | 1,647 | 3.546875 | 4 | """
题目描述
给定一个数组A[0,1,...,n-1],请构建一个数组B[0,1,...,n-1],其中B中的元素B[i]=A[0]*A[1]*...*A[i-1]*A[i+1]*...*A[n-1]。不能使用除法。
"""
# 这题脑回路好难,必须要看答案。
class Solution:
def multiply(self, A):
if A == None or len(A) <= 0:
return
length = len(A)
aList = [1] * length
for i in range(1, length)... |
9c5a407459551b2758ac191b712bbc0db2842187 | ferb2015/TargetOfferByPython | /25. 把数组排成最小的数.py | 1,699 | 3.5 | 4 | """
题目描述
输入一个正整数数组,把数组里所有数字拼接起来排成一个数,打印能拼接出的所有数字中最小的一个。例如输入数组{3,32,321},
则打印出这三个数字能排成的最小数字为321323。
"""
# 这题和“字符串的排列”那题是一样的,都是全排列。 把数组变成一串数字:int(''.join([str(t) for t in arrSs]))
class Solution:
def PrintMinNumber(self, numbers):
if not numbers:
return ""
def Permutation(start... |
cee4a7e5c0489843bbe2a00b34dc5726fbcdaa2b | ferb2015/TargetOfferByPython | /20. 字符串的排列.py | 838 | 3.640625 | 4 | # 字符串的全排列。
# 递归核心思想:可以写成诸如f(n) = f(n+*) ....的表达式
class Solution:
def Permutation(self, ss):
if not ss:
return []
def Permutation(startIdx):
if startIdx >= len(arrSs):
clone = ''.join(arrSs)
res.append(clone)
else:
... |
514fa1ec0de61465d378152e4ef82fcd4100ef56 | ferb2015/TargetOfferByPython | /46. 表示数值的字符串.py | 1,238 | 3.890625 | 4 | """
题目描述
请实现一个函数用来判断字符串是否表示数值(包括整数和小数)。例如,字符串"+100","5e2","-123","3.1416"和"-1E-16"都表示数值。
但是"12e","1a3.14","1.2.3","+-5"和"12e+4.3"都不是。
"""
# 这题看的别人的https://www.nowcoder.com/questionTerminal/6f8c901d091949a5837e24bb82a731f2
class Solution:
# s字符串
def isNumeric(self, s):
# write code here
sign, ... |
7d23d152c92d02d00e6b0b1167439aae595f468e | rpereira91/interview-questions | /LeetCode Questions/Stacks/1021. Remove Outermost Parentheses/solution.py | 580 | 3.546875 | 4 | class Solution(object):
def removeOuterParentheses(self, S):
"""
:type S: str
:rtype: str
"""
stack = ""
count = 0
inner_stack = ""
for i in range(len(S)):
inner_stack += S[i]
if S[i] == '(':
count += 1
... |
a2b3162654d3634416fd76c02c6fc02591cd6c0a | rpereira91/interview-questions | /Mock Interviews/mock_5.py | 1,359 | 3.640625 | 4 | class Solution(object):
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
num_set = set(nums)
maj = len(nums)/2
for n in num_set:
if nums.count(n) >= maj:
return n
def searchRange(self, nums, target):
... |
a30227d59212105c34155902380e4e2b77af91ca | Rostislav9821/Lab_rab_10 | /pr3.py | 285 | 3.5625 | 4 | #!/usr/bin/evn python3
# -*- config: utf-8 -*-
def secret():
while True:
a = int(input("a = "))
b = int(input("b = "))
if a == 0 or b == 0:
break
s = a * b
print(s)
if __name__ == '__main__':
secret() |
327aec15b0671df66563bee0f7380d9c13b31433 | latimercaleb/Python-Practice | /hangman.py | 748 | 3.9375 | 4 | # Hangman game
import time
name = input("Welcome to the game, enter your name: ")
print("Alright {0}, the game is starting...\n".format(name))
print("Hangman.start")
time.sleep(1)
secretWord = "Megaman"
guessedLetters = ''
totalTurns = 10
while totalTurns > 0:
failed = 0
for char in secretWord:
if cha... |
292e468c2c0233ab27db7c211613711e1ed6c596 | ramyasutraye/python_programming | /beginner/sum_natural.py | 136 | 3.953125 | 4 | n=int(input(""))
if(n<0):
print("Enter a positive number")
else:
sum=0
while(n>0):
sum=sum+n
n=n-1
print(sum)
|
3ebf6f81f72ed66e7c67c469e1b21436b31393b8 | ramyasutraye/python_programming | /beginner/word_max.py | 123 | 3.828125 | 4 | first=input("")
second=input("")
x=len(first)
y=len(second)
if(x==y):
print(second)
else:
print(max(first,second))
|
a9315380a3a1f3bdf71359536125c3bf71b27603 | ramyasutraye/python_programming | /odd_even.py | 88 | 4 | 4 |
num=int(input(""))
if num%2==0:
print ("even")
else:
print ("odd")
|
b80638464a60893887bdb8f31b8ff4a604cb3637 | raveenabeharry/cus1166_techDay | /useCase/app.py | 1,627 | 3.59375 | 4 | from flask import Flask, request
from pymongo import MongoClient
from bson.json_util import dumps
client = MongoClient('local.host:27017')
db = client.db
app = Flask(__name__)
''' Creating GET REST API Using Python Flask and MongoDB
Fetch the employee data from the MongoDB database through the
.find() metho... |
5b849d76347be999a381d810b7d70410ec13c334 | mallory-jpg/bank | /bank_admin.py | 1,749 | 3.65625 | 4 | # bank account administration: welcome, login, operations, set pw, cancel account
# from bank_customers import User
from bank_customers import Users, USER_INFO
# from bank_customers import save_user_info
BANK_NAME = 'No Cap'
# USER_INFO = {}
class Admin(Users):
def __init__(self, username='admin', password='000... |
7ed258a07a00f7092741efd7b9cef6dc69cdc4b8 | Marlon-Poddalgoda/ICS3U-Unit3-06-Python | /guessing_game.py | 980 | 4.25 | 4 | #!/usr/bin/env python3
# Created by Marlon Poddalgoda
# Created on December 2020
# This program is an updated guessing game
import random
def main():
# this function compares an integer to a random number
print("Today we will play a guessing game.")
# random number generation
random_number = rando... |
560d376d9f809af247284fd69018ee96ca4c3b26 | Robert-stacs/Robert2 | /rob27.py | 57 | 3.6875 | 4 | a=int(input())
while a%2==0:
a= int(input())
print(a) |
357c794ff639e2b1c4bff78057fe7c8414ebca28 | Robert-stacs/Robert2 | /rob28.py | 69 | 3.515625 | 4 | a=int(input())
n=1
while a!=0:
n*=a
a=int(input())
print(n)
|
b1931b7708def6f9a26aa7d0e6a6a4981d4046d4 | Robert-stacs/Robert2 | /rob41.py | 329 | 3.578125 | 4 | import random
z=int(input("Введите длину массива: "))
def mas(z):
a=[]
for i in range(z):
n=random.randint(10,99)
a.append(n)
return a
def print_mas(a):
for i in range(len(a)):
print(a[i],end=",")
print(a[len(a)-1],end=".")
print()
arr = mas(z)
print_mas(arr)
|
159e5ce87e6312ba08c69437c0b5738c21172f7a | feer921/PythonStudy | /05-转换为整数.py | 392 | 3.765625 | 4 | a = '31'
b = int(a)
print(a) # 31
print(b) # 31
# 虽然上面输出没有问题,但是数据类型是不一致的
# print(a + 1) # 报错
print(b + 1) # 32
x = 'hello'
y = int(x) # ValueError: invalid literal for int() with base 10: 'hello' 如果字符串不是一个合法的数字会报错
print(y)
x = '1a2c'
y = int(x, 16) # 以16进制进行转换
print(y) # 6700
|
51aff9787d103ec0da42fea79160f770b42601f0 | BenAychh/advent_of_code_2019 | /day_04/__init__.py | 1,649 | 3.859375 | 4 | from typing import Dict
def problem_1(start: int, end: int) -> int:
count = 0
for n in range(start, end + 1):
if is_valid(n):
count += 1
return count
def problem_2(start: int, end: int) -> int:
count = 0
for n in range(start, end + 1):
if is_valid_2(n):
co... |
6d1c77fa6f5bc9041e7406399b1f51669347f445 | Johannyjm/c-pro | /tmp/ndc001/ah.py | 84 | 3.734375 | 4 | t = int(input())
def f(n):
return n*n + 2*n + 3
print(f(f(f(t) + t) + f(f(t)))) |
1d9a63e125bce03254dbc617116677380f6de5a8 | Johannyjm/c-pro | /AtCoder/othercontests/yvc006/g.py | 209 | 3.703125 | 4 | def main():
h = int(input())
now = h
count = 1
res = 0
while now > 0:
res += count
now //= 2
count *= 2
print(res)
if __name__ == '__main__':
main() |
bfa89bfdd82c7c782880de9d71831d127c0f122c | Johannyjm/c-pro | /AtCoder/abc/abc234/a.py | 87 | 3.890625 | 4 | def f(x):
return x**2 + 2*x + 3
t = int(input())
print(f(f(f(t) + t) + f(f(t))))
|
d44c82206eec3266666e7e7f3fca54c7b7ea3bef | Johannyjm/c-pro | /AtCoder/agc/agc017/a.py | 239 | 3.640625 | 4 | n = int(input())
even = []
odd = []
for i in range(1<<n):
cnt = 0
for j in range(n):
if i & (1<<j):
cnt += 1
if cnt%2 == 0: even.append(i)
else: odd.append(i)
print(len(even), len(odd))
|
b9c0da9edb227d5902b580b659accb877b9adeb4 | Johannyjm/c-pro | /AtCoder/othercontests/yvc010/g.py | 367 | 3.65625 | 4 | def main():
s = input()
if s[0] != 'A':
print('WA')
exit()
if s[2: -1].count('C') != 1:
print('WA')
exit()
for c in s:
if ord('A') <= ord(c) <= ord('Z'):
if c not in ('A', 'C'):
print('WA')
exit()
pri... |
153ad0ad0c4055c8a857b9e10e91fe6d23023846 | Johannyjm/c-pro | /AtCoder/benkyokai/digit.py | 136 | 3.578125 | 4 | def digit(n: int) -> int:
ret = 0
while n:
n //= 10
ret += 1
return ret
print(digit(12345))
|
972d3ccf6784e5915cc7ff1a7c4cb8359436ee55 | Johannyjm/c-pro | /AtCoder/othercontests/typical90/aa.py | 143 | 3.546875 | 4 | n = int(input())
userset = set()
for i in range(n):
user = input()
if user not in userset:
print(i+1)
userset.add(user) |
3c5c81127af828c4ce7b543e073f1739575e21fe | Johannyjm/c-pro | /AtCoder/abc/abc247/c.py | 125 | 3.515625 | 4 | n = int(input())
prev = '1'
res = '1'
for i in range(1, n):
res += ' ' + str(i+1) + ' ' + prev
prev = res
print(res)
|
390aa830f349ae185c712ac0981c3a8462bace83 | Johannyjm/c-pro | /AtCoder/othercontests/0624/b.py | 97 | 3.515625 | 4 | s = input().split('+')
# print(s)
res = 0
for c in s:
if('0' not in c): res += 1
print(res) |
383f5db60c6d10990aed116a8f97642e050abd4b | chriskha/Tanto | /src/town.py | 1,870 | 3.515625 | 4 | from src import rules
class Town:
def __init__(self):
self.general_maids_pile = []
self.chief_maids_pile = []
self.private_maids_pile = []
self.private_maids_up = []
self.love_cards_pile = []
self.event_cards_pile = []
self.town_set = dict()
def... |
9430520d1c45393d762c1ac94a50eb39cc0541e2 | dyrroth-11/Python-MiniProjects | /Dynamic Address book without GUI/Address_book.py | 3,954 | 4 | 4 | #!/usr/bin/env python3
"""
Created on Thu Apr 23 19:21:42 2020
@author: Ashish Patel
"""
"""
Problem: Task: Create an small address book
Case: Write an address book program in python which have the following option:
1. Add_contact
2. Display_contact
3. Delete_contact
... |
e1ca0a5b07190dedf569c4050175d9a6cbffb0a5 | dkosloff/fantastic-barnacle | /BioInformatics I/reverseComplement.py | 597 | 3.640625 | 4 | def Calulate(pattern):
result = ''
for i in range(len(pattern)-1, -1, -1):
if(pattern[i] == 'A'):
result += 'T'
elif(pattern[i] == 'T'):
result += 'A'
elif(pattern[i] == 'G'):
result += 'C'
elif(pattern[i] == 'C'):
resul... |
69ffdfee405cfbd137047d7d5828df6e96de0082 | dkosloff/fantastic-barnacle | /BioInformatics I/RandomizedMotifSearch.py | 2,585 | 3.53125 | 4 | import GreedyMotifSearch as gms
import ProfileMostProbableKmer as pMostProb
import random
def Search(dna, k, t):
'''Finds strings of length 'k' in all the strings in dna
which are close matches to each other. It does this by starting with
a random k-length substring from each dna string and building a pr... |
cdb1f71a630aa12809058e742a8612327426c897 | MuhanguziDavid/MyDiary | /api/modals/user.py | 1,178 | 3.546875 | 4 | from cryptography.fernet import Fernet
from api.database.db import DatabaseConnection
class User:
con = DatabaseConnection()
con.create_table_users()
con.create_table_entries()
cursor = con.cursor
dict_cursor = con.dict_cursor
def __init__(self, username, email, password):
self.usern... |
f9ddfee528a7e7a9fdbe31bff98ce60965a2963b | Md-Sabbir-Ahmed/52_Problems----Tamim_Shahriar_Subeen_Book | /problem05.py | 151 | 3.5625 | 4 | z=int(input())
for i in range(z):
a=int(input())
for l in range(a):
print("*"*a)
if i<z-1:
print()
else:
break
|
be96737a1d402ab265b23a27470a5c0bf16dc45b | annagrace-phillips/Pandas | /pandas_series.py | 837 | 3.765625 | 4 | import pandas as pd
grades = pd.Series([87,100,94])
print(grades)
same_grade = pd.series(98.6, range(3))
print(same_grade)
#0 98.6
#1 98.6
#2 98.6
#dtype: float64
print(grades[0])
grades.count()
grades.mean()
grades.min()
grades.max()
grades.std()
print(grades.describe())
#you can specify custome indices with ... |
d9661c1325586fec794633120d750a27e128c7e9 | johnathan79717/competitive-programming | /AtCoder/arc106/arc106_a/main.py | 173 | 3.75 | 4 | N = int(input())
A = 1
while 3 ** A <= N:
B = 1
while 3 ** A + 5 ** B <= N:
if 3 ** A + 5 ** B == N:
print(A, B)
exit(0)
B += 1
A += 1
print(-1)
|
929fe74cf178696112e00951edf6c24ea9f4a737 | johnathan79717/competitive-programming | /CodeChef/LTIME17/main.py | 250 | 3.765625 | 4 | T = int(input())
for t in range(T):
N = int(input())
S = input()
done = False
for s in S:
if s == 'Y':
print('NOT INDIAN')
done = True
break
elif s == 'I':
print('INDIAN')
done = True
break
if not done:
print('NOT SURE') |
b9862bf717d958e138ffeb6918d21f5fe164a780 | Lutshke/Python-Tutorial | /variables.py | 882 | 4.40625 | 4 | "This is where i will show you the basics ok?"
# to add comments to code you need to start with a hashtag like i did
# there are a few types of numbers
# there are "ints" and "floats"
# an int is a full number (10, 45, 100..)
# an float is (0.1, 1,5...)
# an int or float are variables so they save values
... |
d20d46dbe49bf1acf282dbda8f63c9c371972765 | TSJarek/my-first-blog | /python-intro.py | 485 | 3.8125 | 4 | def hi(im):
print('Hej, '+im+'!')
print('Jak się masz?')
volume=int(input(" Siła głosu: "))
imie=str(input(" Imie: "))
hi(imie)
if volume < 20:
print("It's kinda quiet.")
elif 20 <= volume < 40:
print("It's nice for background music")
elif 40 <= volume < 60:
print("Perfect, I can hear all the de... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.