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 |
|---|---|---|---|---|---|---|
fca162ced3097f8ce00761a4632bd4cfa36a5f19 | MatheusPatriota/CodigosIFPE2019.2 | /AGOSTO2019/conceito.py | 528 | 3.765625 | 4 | def conceito(nota):
if nota <= 10 and nota >= 8.5:
print("seu conceito eh A")
elif nota < 8.5 and nota >= 7.0:
print("seu conceito eh B")
elif nota < 7.0 and nota >= 5.0:
print("seu conceito eh C")
elif nota < 5.0 and nota >= 3.0:
print("seu conceito eh D")
else:
... |
071848923a436e5a055c7b961b3c67cc57864af1 | MatheusPatriota/CodigosIFPE2019.2 | /NOVEMBRO2019/Recursividade/fibonacci.py | 148 | 4.03125 | 4 | def fibonacci(x):
if x == 0:
return 0
elif x == 1:
return 1
return fibonacci(x-1) + fibonacci(x-2)
print(fibonacci(10)) |
92224c2ddbf66e2be0c6871a6f3b453442608b54 | MatheusPatriota/CodigosIFPE2019.2 | /AGOSTO2019/sistemaInteligente.py | 1,162 | 4.0625 | 4 | # Aluno: Matheus da Silva Coimbra Patriota - 20192EWBJ0027
# Curso: Engenharia de Software
# adivinha que numero to pensando xD
comecoUser = int(input("Digite o inicio do intervalo: "))
fimUser = int(input("Digite o fim do intervalo: "))
lista = list(range(fimUser+1))
numero = int(fimUser/2)
comeco = comecoUser
fim ... |
73f2fa36d6ceffea3759939882d8e30f05ae48fc | MatheusPatriota/CodigosIFPE2019.2 | /SETEMBRO2019/Prova02/MatheusPatriotaQ2.py | 547 | 3.96875 | 4 | #Aluno: Matheus da Silva Coimbra Patriota
# Matricula: 20192EWBJ0027
# Engenharia de Software
# variaveis
divisores = []
somaDivisores = 0
print("** Bem vindo ao Descubra se seu numero é perfeito ou não **")
numero = int(input("Informe um número para começar: "))
# listas para encontrar divisores do numero
for i in... |
97176823c0ed9b863f6d03dab40db0baaf25adc4 | MatheusPatriota/CodigosIFPE2019.2 | /NOVEMBRO2019/ProvaNovembro2019/MatheusPatriotaQ2.py | 928 | 4.0625 | 4 | # Aluno: Matheus da Silva Coimbra Patriota
# Matricula: 20192EWBJ0027
# Curso: Engenharia de Software
# funcao para encontrar os elementos repetidos entre duas listas
def repetidosListas(lista1,lista2):
# lista que irá armazenar os valores repetidos
listaFinal = []
# for para cada elemento da lista1
fo... |
7eccf5204d8c9ccfbc54f29fc3f38a449b0d44c3 | MatheusPatriota/CodigosIFPE2019.2 | /AGOSTO2019/exercicioP51E16.py | 258 | 3.890625 | 4 | import math
def calculoHip(c1, c2):
x = math.sqrt((c1**2) + (c2**2))
return x
cateto1 = input("digite o cateto: ")
cateto2 = input("digite o cateto: ")
hip = calculoHip(int(cateto1), int(cateto2))
print("a hipotenusa é: {0:0.1f}".format(hip))
|
d9abf465cea11dcb1ed0c72f589f658954c5033b | MatheusPatriota/CodigosIFPE2019.2 | /SETEMBRO2019/ListaDeExercicios/questao5.py | 1,131 | 3.953125 | 4 | # Aluno: Matheus da Silva Coimbra Patriota
# Matricula: 20192EWBJ0027
# Engenharia de Software
# Faça um programa que recebe um valor em segundos. Converta o valor recebido para o formato HH:MM:SS,
# onde HH é a quantidade de horas, MM é a quantidade de minutos e SS é a quantidade de segundos. Lembre
# que 1 hora equ... |
90c662b92699177c2e4db6179abebafa1876866c | MatheusPatriota/CodigosIFPE2019.2 | /AGOSTO2019/desafio.py | 1,668 | 4.09375 | 4 | # Assunto : Conhecimento gerais
def iniciarQuiz():
pontuacao = 0
print ("BEM VINDO - VAMOS INICIAR O QUIZZ:")
nome = input("DIGITE SEU NOME: ")
print ("Vamos lah " + nome.upper())
p1 = input(" qual a capital do Brasil? \n A)RIO DE JANEIRO \n B)BRASIL \n C)CARIOCA \n D)BRASILIA \n")
if p... |
537acce320c3248573abb9883a5474b863265382 | Zuzukin-dp/introPython_BAV | /HomeWorks/BAV_HW_2.py | 1,957 | 4.03125 | 4 | # Home work 2
#
# Beshliu Aleksandr
#
###############################
# 1) Написать программу, которая считывает введенное число и выводит умноженное на 2 значение, если это число
# делится на 5 и выводит 0 в других случаях. Т.е. если ввести 15, то выведет 30, а если 13, то 0.
value = int(input("Введите знач... |
e804042c7867084e4ec7f793b1a4bdc73d11d06d | brendano/cmdutils | /summary | 3,094 | 3.953125 | 4 | #!/usr/bin/env python2.7
r"""
Summary statistics for a list of numbers or strings (on stdin).
Loosely inspired by R's summary(): call on anything, learn something.
* Number, number of types (unique values)
* Value counts -- if small number of unique values
-c: force showing these counts
* Quantiles -- even ... |
1cd44332160f7f3420fb017118a6e501ecf6b00e | DrFrasierCrane/Agent12 | /Agent12.py | 12,771 | 3.875 | 4 | # Agent12 written by Tyler Sartin 23 April 2013
# Enjoy!
from random import randint
# This class defines the Player. The player has a 'moves' attribute that inclues all possible
# moves they can perform.
class Player(object):
moves = ["Punch", "Kick", "Stab", "Shoot", "Run"]
# The fight method marks the start of... |
cf329e4edc18ec2ec09c51386da109446b5a49d2 | lsilvamiguel/usercode | /Python/sigRound.py | 795 | 3.84375 | 4 | # #!/usr/bin/python
# Evaluates the digits to be used with the round function in order to have
# the first two significant figures
def sigRound(error):
tempErr = error
digits = 0
if( int(tempErr) == 0 ):
while (int(tempErr) == 0):
tempErr = tempErr*10
digits += 1
else:... |
13c88ffd58b096511ee71e2752e0dc588c71cfed | lchoe20/lchoe20.github.io | /challenge1.py | 806 | 4.21875 | 4 | #challenge 1 prompt: create a guess the number uding a while loop
from random import * #import * is a wild card that says import all information
aRandomNumber = randint(1,20) #inclsuive
#generates a randominteger
guess = input("Guess a number between 1 and 20 inclusive: ")
#assume user's guess is equal to 5
if not... |
02719df93bb349f849b90bb69ee18078799a3bc2 | lchoe20/lchoe20.github.io | /scores_data_science.py | 866 | 3.59375 | 4 | # importing plotting tools
import matplotlib.pyplot as plt
# importing school_scores database and python api
import school_scores
years = []
AL_scores = []
MA_scores = []
scores = school_scores.get_all()
print(scores[0]["Gender"]["Female"]["Math"])
for row in (scores):
print(row["State"]["Name"],row["Year"])
#... |
9334fe32d625f2d0851683ad26500a501356db51 | moskalev/canvas-student-list | /calls.py | 2,943 | 3.5625 | 4 | # __author__ = 'dimitrios'
import requests
import itertools
from functools import reduce
class APICalls(object):
"""
Class that simulates the low level API calls.
For now, only implements get (for reading only purposes)
Code based on https://github.com/hawesie/python-canvas-api
Canvas API returns ... |
b3374efe8d0c2de9576d49d78c8d10081001f987 | jordipiqueselles/tops | /utils/timing.py | 1,244 | 3.5 | 4 | # coding=utf-8
"""
Utilities to profile the execution time
"""
from time import time
class TimeCounter:
def __init__(self):
self.temp_time = 0
self.acum_time = 0
self.n_starts = 0
def reset(self):
self.temp_time = 0
self.acum_time = 0
self.n_starts = 0
de... |
6140a6b5f84b8d2097fe35f49d4d457151691e3b | keerthana20656/Data-Structures | /Linkedlist/creating a linkedlist.py | 985 | 3.90625 | 4 | class Node():
def __init__(self,data=None,next=None):
self.data=data
self.next=next
class Linkedlist():
def __init__(self):
self.head=None
def print(self,s):
if self.head==None:
print("linkedlist is empty")
return
itr=self.head
lstr=''
... |
0a2c635b30ba3fceb06674f761530776ee51e64e | qhb1001/A-simple-interpreter | /PYTHON/code/failed/grammar.py | 5,071 | 3.65625 | 4 | import exceptions
import lexical
# first deal with the brackets
def check_brackets(lines):
line_number = 0
# if last
if lines == None:
exit()
for line in lines:
stack = []
line_number += 1
for token in line:
# if this is a '(', then just push it into the s... |
51129115ad46ddf1473960ece4fc29e4e395cf5b | Kiri28/Machine_learning_case | /ranking reviews by positivity/main/from_csv_to_sql_with_lemm.py | 1,006 | 3.59375 | 4 | import csv
import sqlite3
import re
import math
from lemmatiz import lem
def inserting(title,text,score):
# Создаем соединение с нашей базой
conn = sqlite3.connect('scores_list.db')
cursor = conn.cursor()
# Делаем INSERT запрос к базе данных
cursor.execute("insert into table_1 values (?,?,?)",[(tit... |
0a558595aad49fd35f1a556da1a3bdf7a6308271 | toTheMirza/sample | /PYTHON/Scheme Emulator/scheme_tokens.py | 5,302 | 3.5 | 4 | """The scheme_tokens module provides functions tokenize_line and tokenize_lines
for converting (iterators producing) strings into (iterators producing)
lists of token descriptors. A "token descriptor" here refers to a pair (syntax, value), where
* value is either value denoted by the token (an integer in the case ... |
d0b53772a655a36e17d5b047fd0d9fd893d3670d | jy2671/logs-analysis | /news.py | 2,775 | 3.640625 | 4 | #!/usr/bin/env python
import psycopg2
def db_connnect():
# create and return a database connection and cursor
conn = psycopg2.connect("dbname=news")
cursor = conn.cursor()
return cursor, conn
def db_disconnect():
# disconnect connection
cursor, conn = db_connnect()
cursor.close()
de... |
43a48624884c0b0065759e5bdcfc7468ddeb2169 | adammelancon/PiFaceRelayFun | /kbpress.py | 934 | 3.859375 | 4 | #!/usr/bin/env python
#This script controls the piface relays from the keyboard.
#It controls the built-in relay which is hooked up to a small motor or light.
import piface.pfio as pfio
pfio.init()
print "A = Turn on relay."
print "B = Turn off relay."
print "C = Exit the script."
def checkbuttons():
decide = r... |
0495b04e661b38016f1daa0a0e894c67aaa2b479 | itgsod-Gustav-Wolgast/reddit | /reddit/spell_checker.py | 225 | 3.609375 | 4 | class SpellChecker(object):
def __init__(self, data):
self.data = data
def check_if_alot(self):
for s in self.data.split(" "):
if s == "alot" or s == "Alot":
return True
|
330cdbfd84956da11f555c4f0b34fcc298b778e6 | pablo-var/data-structures-and-algorithms | /algorithmic-toolbox/week3_greedy_algorithms/1_money_change/change.py | 335 | 3.515625 | 4 | # Uses python3
import sys
def get_change(m):
n_coints = 0
while m >= 10:
n_coints += 1
m -= 10
while m >= 5:
n_coints += 1
m -= 5
while m >= 1:
n_coints += 1
m -= 1
return n_coints
if __name__ == '__main__':
m = int(sys.stdin.read())
print(... |
c5341a4b73215cba806152a2a8682047a57f46cc | pablo-var/data-structures-and-algorithms | /data-structures/week1_basic_data_structures/1_brackets_in_code/check_brackets.py | 984 | 3.9375 | 4 | # python3
from collections import namedtuple
Bracket = namedtuple("Bracket", ["char", "position"])
def are_matching(left, right):
return (left + right) in ["()", "[]", "{}"]
def find_mismatch(text):
opening_brackets_stack = []
opening_brackets_stack_position = []
for i, next in enumerate(text):
... |
d99a4fe087cbb884ad872cfebf9b4806fd6ab55e | firetheworld/pythonExercise | /myFunction.py | 1,207 | 3.90625 | 4 | #!/usr/bin/env python3
import math
def my_abs(x):
if x >= 0 :
return x
else:
return -x
def my_abs_checkParm(x):
if not isinstance(x, (int, float)):
return TypeError('bad operand type')
if x > 0:
return x
else:
return -x
def move(x, y, step, angle=0):... |
278597b789075960afb774815cf487ca6fc22cff | appledora/SecurityLab_2_3 | /Task_2/CeaserCipher.py | 1,575 | 4.1875 | 4 | import string
import time
alpha = string.ascii_letters
def ceaser_decrypt_without_key(target):
print("DECRYPTING....")
key = 0
while key <= 26:
temp = ""
for char in target:
if char.isalpha():
temp += alpha[(alpha.index(char)-int(key)) % 26]
... |
ba39f50f2d6d38da719f27b8ed121b7e24ed0f75 | ziluke/PLF | /Prolog/Lab1_PLF/Problem_2.py | 1,708 | 3.671875 | 4 | '''
a.) Substitute the i-th element from a list with a value v
substitute(l1...ln, i, v) = - [] , n=0
- v U l2...ln , i=0
- l1 U substitute(l2...ln, i-1, v), i>0
'''
def isEmpty(list):
if not list:
r... |
2e3c13b7d32bd82d09820c8a7836b3b984d4417c | farellf/pykue | /ISP/ISP_exerc/module_1_exerc.py | 8,237 | 4.25 | 4 | """
This code contains my solutions for Interactive Scription with Python
Course, Rice University on Coursera : Module 1 exercises
@__f_f__, April 2018.
"""
import math
import random
def is_number(s):
try:
float(s)
return True
except ValueError:
pass
try:
import unicodedata... |
0308366defd3a3ee7fcb0db5762e632097a89cc9 | Yashvir-Rana/dailyvscode | /.vscode/words = ['cat,', 'mouse', 'dog'].py | 122 | 3.953125 | 4 | words = ['cat,', 'mouse', 'dog']
for word in words[:]:
if len(word) > 3:
words.insert(0, word)
print(words[0]) |
7ce08fa9c2cee801d5e7e9aa35dde64c2a844db7 | Yashvir-Rana/dailyvscode | /tricks/kidsprojects/hexspiral.py | 224 | 3.546875 | 4 | import turtle as tur
colors = ['red', 'purple', 'blue', 'green', 'yellow', 'orange']
t = tur.Pen()
tur.bgcolor('black')
for x in range(90):
t.pencolor(colors[x%6])
t.width(x/100+1)
t.forward(x)
t.left(59)
|
8e437190f46e4cb89f3017ce877c2cf7fbae1551 | moonesque/hacker-rank | /2nd_lowset_grade.py | 630 | 3.828125 | 4 | import sys
def second_lowest_grade():
physic_students = []
for _ in range(int(input())):
name = input()
score = float(input())
physic_students.append([name, score])
physic_students = sorted(physic_students, key=lambda x: (x[1], x[0]))
second_lowest_grade = 0
for i in... |
7e53a39b1e74db9b98846c6ae7fc9336049e4742 | fatowl-dev/spartacamp-task_d | /my_counter_v3.py | 692 | 3.828125 | 4 | class MyCounterV3:
def __init__(self, value, step):
self.value = value
self.step = step
def count_up(self):
self.value += self.step
def count_down(self):
self.value -= self.step
if __name__ == '__main__':
counter1 = MyCounterV3(value=1, step=2)
print(counter1.valu... |
5a5a2160373a515fa069d08a42dea00199d2188b | raulzitoe/pvp-raycast | /minimap.py | 2,008 | 3.828125 | 4 | import pygame
import constants as c
class Minimap:
"""
Class to hold the minimap info and draw it into a surface
"""
def __init__(self, square_size):
self.square_size = square_size
self.surface = pygame.Surface((self.square_size*c.MAP_WIDTH, self.square_size*c.MAP_HEIGHT)).convert()
... |
acaacb6a092ff081f1fb09e90391750dd7a4b25e | bhoy-troy/notebooks | /jupyter/wikipedia_table/core.py | 8,732 | 3.5 | 4 | """This module us used to scrape data from the table containing the prime ministers in
https://en.wikipedia.org/wiki/List_of_prime_ministers_of_the_United_Kingdom
Example:
To run the application run the command below::
$ python core.py
"""
import configparser
import datetime
import logging
import os
imp... |
751038984b9b60026f3436044d9d76f4c8ad8996 | Trethtzer/Introduction-to-python-udacity | /l2_1.py | 493 | 3.84375 | 4 | def which_prize(points):
prize = ""
if points <= 50 and points >= 0 :
prize = "wooden rabbit"
elif points > 150 and points <= 180 :
prize = "wafer-thin mint"
elif points > 180 and points <= 200 :
prize = "penguin"
if prize == "" :
return "Oh dear, no prize this time."... |
9802d5ff29b357a696ef27482b55450c1ea6f20e | DomaninaDaria/my_python_hw | /11-14.py | 1,707 | 4.21875 | 4 | import math
print("Exercise number 11")
def degrees_in_radians(degrees):
return (degrees * math.pi) / 180
degrees1 = 45
degrees2 = 40
degrees3 = 60
print("Cos of degrees(%d)= %.4f" % (degrees1, math.cos(degrees_in_radians(degrees1))))
print("Cos of degrees(%d)= %.4f" % (degrees2, math.cos(degrees_in_radians(d... |
e5538d87c10af195cb83c6a25673f92efe640c74 | DomaninaDaria/my_python_hw | /test_9.py | 371 | 3.703125 | 4 | value = int(input("Input value of elements in list: "))
lst = [0] * value
for i in range(value):
print("Input element in list number", i+1)
lst[i] = int(input())
print(lst)
max_value = 0
for i in range(value):
if abs(lst[i]) > max_value:
max_value = abs(lst[i])
for i in range(value):
lst[i] /= m... |
9603b36b1bba94a0929fb0c2d436e6257184fef8 | elizabethdaly/collatz | /collatz.py | 519 | 4.3125 | 4 | # 16 sept 2019 collatz.py
# n is the number we will perform Collatz on.
# n = 20
# Request user input.
n = int(input("Please enter an integer n: "))
# Keep looping until n = 1.
# Note: Assumes Collatz conjecture is true.
while n != 1:
# Print the current value of n.
print(n)
# Check if n is even.
if n % ... |
86a4705098304fc2ca978f539d789cdeeaee83ca | BlakeTacklind/MarchMaddessCalculator | /Tournament.py | 3,315 | 3.6875 | 4 | #!/usr/bin/env python3
import csv
import math
FILE_NAME = "players.csv"
class Team(object):
"""docstring for Team"""
def __init__(self, name, rank, location, power):
super(Team, self).__init__()
self.name = name
self.rank = int(rank)
self.location = location
if self.location == "West":
self.locationV... |
f5ae0d36c8379433c3402effb370dd355ccf00ec | ariqsss/FP_PROGJARC_Kel3 | /Chat tictacnumeric/client_game.py | 4,737 | 3.65625 | 4 | import socket
import select
import sys
import msvcrt
import pickle
flag = 1
finish = 0
board = [None] + list(range(1, 10))
number = []
sets = [
(1, 2, 3),
(4, 5, 6),
(7, 8, 9),
(1, 4, 7),
(2, 5, 8),
(3, 6, 9),
(1, 5, 9),
(3, 5, 7)
]
def draw():
print(board[1], board[2], board[3])
... |
d012a8af6bcb54851db9493f338da201562048ba | backstopmedia/maker | /Giraffe/onArg.py | 965 | 3.5625 | 4 | #
# onArg
#
import sys
# function
def colour(redV, greenV, blueV):
''' assign colours to LEDs '''
# driver file to be opened
f = open("/dev/pi-blaster", "w")
# build string to assign colours
s=("25=" + str(redV) + "\n" + "24=" + str(greenV) + "\n" "23=" + str(blueV) + "\n")
# w... |
2d0da772303ac46285ea43b6283a17c4823e52f3 | Noah-Huppert/ksp-sandbox | /src/lib/velocity.py | 1,716 | 4.53125 | 5 | """ calc_energy calculates the kinetic energy for a given body traveling in 1D
Arguments:
- m (float): Mass of body
- v (float): Velocity of body
Returns:
- float: Kinetic energy of body
"""
def calc_energy(m, v):
# Ensure kinetic energy is negative if velocity is negative
# (Separate logic necess... |
8ec55afc83baba89fe556a7e7ede56196a5a4c92 | lovelysusie/titanic_exercise | /titanic_rf.py | 9,287 | 3.828125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Jan 22 15:12:56 2017
@author: Susie
"""
import csv as csv
import numpy as np
csv_file_object = csv.reader(open('/Users/Susie/Documents/titanic_exercise/train.csv', 'rb')) # Load in the csv file
header = csv_file_object.next() # Skip the fist line as it is a header
data=[... |
bb7d9b45b5c78630da587ad2a44df8f6510c64c9 | seanre31/python-fun | /cards.py | 1,243 | 3.859375 | 4 | import random
card_signs =['Heart','Club','Diamond','Spade']
num_gen = random.randint(1, 13)
sign_gen = random.choice(card_signs)
card_gen = num_gen, sign_gen
if num_gen == 1:
print("Ace", "of", sign_gen)
elif num_gen == 11:
print("Jack", "of", sign_gen)
elif num_gen == 12:
print("Qu... |
aa9da4ab8b706f7ab8c6963b72f0b78be6afdb54 | seanre31/python-fun | /grid.py | 225 | 3.796875 | 4 | width = int(input("Please enter a width for your grid:"))
rows = int(input("Please enter the amount of rows in your grid:"))
for x in range(rows):
for y in range(width):
print('*',end = ' ')
print()
|
b6e5c3b806fd20b5484beffe8c2c6d11c753739f | kssvrk/dsalgos | /leetcode/linked_list/reverse_nodes_in_k_groups_25.py | 2,900 | 3.71875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Jun 6 23:32:33 2021
@author: radhakrishna
"""
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
from math import ceil,floor,log
class Solution:
d... |
bd597c44d15356aee6b80eab3fe31ed1c4ef6189 | Shatalin89/normal | /learner.py | 735 | 3.609375 | 4 | from people import People
class Learner(People):
def __init__(self, lastname, middlename, name, gender, age, parents, subject = None):
People.__init__(self, lastname, middlename, name, gender, age)
self.parents = parents
if subject:
self.subject = subject
else:
... |
2801333709f62497a68f7925030ddbe55a0397b6 | MrZebarth/PythonCheatSheet2019 | /Conditionals.py | 977 | 4.40625 | 4 | # Conditionals
# We want to be able to make decisions based on our variables
# We use the "if" statment with a condition to check for a result
num1 = int(input("Enter a first number: "))
num2 = int(input("Enter a second number: "))
if num1 > num2:
print(num1, "is greater than", num2)
elif num1 < num2:
print(num... |
7bf9d6a299f8d511f2b879b5eba3d35dc8d0a803 | mnessens7/Algorithm | /sort/merge_sort_1.py | 373 | 3.875 | 4 | def merge_sort(a):
if len(a) < 2:
return a
c = len(a)//2
return merge(merge_sort(a[:c]), merge_sort(a[c:]))
def merge(x, y):
if len(x) < 1:
return y
if len(y) < 1:
return x
if (x[0] > y[0]):
return [y[0]]+merge(x, y[1:])
else:
return [x[0]]+merge(x[1... |
ea65375093dc90f4a6d036475d563d96560163e0 | ZakharovIvan/- | /Db_lab1/entity.py | 803 | 3.546875 | 4 | class country:
unique_id = 0
def __init__(self, name, mainl, currency):
self.id = country.unique_id
self.name = name
self.mainl = mainl
self.currency = currency
self.c_ids = []
country.unique_id += 1
def out(self):
print str(self.id) + ': ' + self.nam... |
9ba9939b3286eda0417a67317f695e14206ae44d | Chris-Meyers/cfsm-project | /reduce.py | 1,805 | 3.5625 | 4 | # reduce.py - now just check syntax of a program
def prettyReduceStack(stack, msg="Reduce Stack") :
ans = []
for item in stack :
if type(item) == type("") : ans.append(item)
else : ans.append("*S%d" % item.stateNo)
return msg + ": " + "--".join(ans)
def syntaxCheck(states, program) :
... |
9ee2baa70b74d051c22d4cab361bd93395564197 | christophermoutin/MITx-6.00.1x | /Problem2/usingBisection.py | 3,466 | 3.828125 | 4 | """
You'll notice that in Problem 2, your monthly payment had to be a multiple of $10. Why did we make it that way?
You can try running your code locally so that the payment can be any dollar and cent amount
(in other words, the monthly payment is a multiple of $0.01). Does your code still work? It should,
but you m... |
4cbca772f78ecbc144cd50e9d50cda346980000d | kilala-mega/practice_everyday | /different-ways-to-add-parenthesis.py | 1,195 | 3.5 | 4 | class Solution:
def diffWaysToCompute(self, expression: str) -> List[int]:
@functools.lru_cache(None)
def search(start:int, end:int) -> List[int]:
res = []
if end-start == 1:
res.append(int(tokens[start]))
return res
for k in range(... |
e24d54343aa9976372a8c282d7a8c076e3f102a2 | kilala-mega/practice_everyday | /maximum-width-ramp.py | 780 | 3.5625 | 4 | """
(i,j) i < j and nums[i] <= nums[j], width is j-i
maximum width of a ramp
[9,8,1,0,1,9,4,0,4,1]
[(1,9),(4,8),(9,5)]
"""
class Solution:
def maxWidthRamp(self, nums: List[int]) -> int:
res = 0
stack = [] # items is (value, index)
for i in range(len(nums)-1,-1,-1): # from right to left
... |
e984a9b7015196f7358b333f7b862956f1128dd4 | kilala-mega/practice_everyday | /307. Range Sum Query - Mutable.py | 2,019 | 3.625 | 4 | class Node:
def __init__(self, start, end):
self.start = start
self.end = end
self.left = None
self.right = None
self.total = 0
class NumArray:
def __init__(self, nums: List[int]):
def _createSegTree(nums, l, r):
if l > r:
retu... |
0de9e48cd4ac97d224b9c64cff929a66e0d478b9 | kilala-mega/practice_everyday | /tree-of-coprimes.py | 1,554 | 3.640625 | 4 | """
represent a graph with edges:
graph[node1] = node2
graph[node2] = node1
root node is node 0 -> start from node 0
note the number is between 1 and 50
DFS
use a list (parent node) path to store: value -> (node index, depth) to exclude duplicate search on the gcd of the same value
"""
class Solution:
def getCopr... |
46c1fefb2806f0609d561ab3319cf43f07fb7d76 | kilala-mega/practice_everyday | /1028. Recover a Tree From Preorder Traversal.py | 912 | 3.65625 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def recoverFromPreorder(self, S: str) -> TreeNode:
idx = 0
stack = [] # the path from root t... |
76babe4545891b5bad75794840a1770014292627 | trallen09/Election_Analysis | /Python_practice.py | 1,821 | 4.09375 | 4 | # counties_dict = {"Arapahoe": 422829, "Denver": 463353, "Jefferson": 432438}
# for county in counties_dict:
# print(counties_dict[county])
# for county, voters in counties_dict.items():
# print(county, voters)
# for key, value in counties_dict.items():
# print(str(key) + "county has " + str(value)... |
ccccdf98136b87d3b147c9a9cc9395845569f733 | 0x4e3/lp | /hw1/while_loop.py | 1,172 | 3.890625 | 4 | # coding=utf-8
"""
To use this script, do not forget to run
export PYTHONPATH=PYTHONPATH:./
in the ~/Projects/personal/learn_python directory.
"""
from lesson1.answers import get_answer
persons = ["Вася", "Маша", "Петя", "Валера", "Саша", "Даша"]
def find_person(name):
iterations = 0
while persons:
... |
21f82801b5d324d0aac073dfc36a691a4d92e687 | jagadeesh1414/assign5_note_M2.py | /assign5_prog6_M2.py | 263 | 3.640625 | 4 | import math
Radians60 = math.radians(60)
sin60 = math.sin(Radians60)
sin60Rounded = round(sin60,2)
Radians90 = math.radians(90)
tan90 = math.tan(Radians90)
tan90Rounded = round(tan90,2)
print("Sin60:{}".format(sin60Rounded))
print("tan90:{}".format(tan90Rounded)) |
11e60e6e914cbff0a22389aca3b23c5dd7b17eff | SumirVats2003/lsmake | /lsmake.py | 254 | 4.03125 | 4 |
def createList(n):
"""
This function creates a list of given indices
"""
m = []
for i in range(n):
num = int(input("Enter num: "))
m.append(num)
return m
# New functions will be added in the future
|
e957cb1c881194614a3d58e36d953c14a59da8b7 | sidamarnath/CSE-231-Labs | /lab12.py | 2,876 | 4.25 | 4 | #########################################
# lab12.py
# ALgorithm
# Create a vector class
# Have program do calculations
#########################################
class Vector():
def __init__(self, x = 0, y = 0):
self.__x = x
self.__y = y
#self.__valid = self.__validate()
... |
adbe15cb36083194aa46ab708ce15c24a07628d6 | sidamarnath/CSE-231-Labs | /lab08b.py | 1,648 | 4.15625 | 4 | ###############################
# lab08b.py
# Algorithm
# Prints out student scores alphabetically
# If name appears more than once in file, add scores together
###############################
# read file function to open and read file
# takes in dictionary and filename as argument
def read_file(dictionary, f... |
f38d740d18f8ad7993cf4e99debabd8215484735 | saniemi/SamPy | /sandbox/compareNNtoRF.py | 5,736 | 3.75 | 4 | """
Binary Classification Example
=============================
A simple example comparing Random Forests to a Neural Network (MLP) using
a fake binary classification data with 50 features. None of the models
are optimised, they rather demonstrate the techniques than aim for an
optimal performance.
Dependencies
----... |
76df340c475bcaa464e235ea98e1395dfb68cbec | BrPetrus/SeminarkaHra | /board.py | 4,155 | 3.8125 | 4 | import queue
import tkinter
class Board:
rows = 7
col = 8
colours = {
-1: 'gray',
-2: 'blue',
1: 'green',
0: 'brown'
}
def __init__(self):
self.map = [[0] * self.rows] * self.col
self.generateMap()
def generateMap(self):
self.map = ... |
90acab1cc62a4f946bb8bf51cbca223b6d7d33ee | CNBorn/udacity-cs212 | /exam3-2.py | 10,242 | 4.65625 | 5 |
"""
UNIT 3: Functions and APIs: Polynomials
A polynomial is a mathematical formula like:
30 * x**2 + 20 * x + 10
More formally, it involves a single variable (here 'x'), and the sum of one
or more terms, where each term is a real number multiplied by the variable
raised to a non-negative integer power. (Remembe... |
fae73e5d939a9ded5ac5c513eb1fab9c810d2c9f | MurdockDM/keahua-arboretum-the_nightingale_castle | /actions/release_animal/select_animal.py | 901 | 3.6875 | 4 | import os
from .print_title import print_title
INDEX = 0
def build_select_animal_menu(animal_list, input_text = "Choose an Animal to release"):
"""
Creates Select Animal Menu
"""
os.system('cls' if os.name == 'nt' else 'clear')
print_title()
animal_instance_list = ["" for i in animal_list]... |
d12c29fe56d2bf767d2c032d0fc9602b243c8895 | MurdockDM/keahua-arboretum-the_nightingale_castle | /actions/cultivate_plant/plant_biomes_menu.py | 3,154 | 3.515625 | 4 | import os
# from plant_menu import run_plant_menu
def plant_biomes(arboretum, plant, menu, plant_menu, error_message="Select the number of the biome"):
"""Displays the appropriate biomes for the plant"""
os.system('cls' if os.name == 'nt' else 'clear')
env_char = {
"rivers": True if hasattr(plant,... |
5359bb54cfc0ed5ced5829543b4f1ccc678b8132 | maslovvladimir/dwave-traceroute | /Grid.py | 2,289 | 3.546875 | 4 | #coding=utf-8Ы
import networkx as nx
import matplotlib.pyplot as plt
#pass
#numrow = 5
#numcol = 10
# Процедура создания сеточного графа
# numrow - количнство рядов, numcol - колонок
# obstacles - список препятсвий. Стиреть узлы
def CreateGridGraph(numrow, numcol, obstacles):
G = nx.Graph() # 0 - 1 ... |
add6452ba2be0da1104520fa6a6616aeee6b574a | kjais1720/Hand-Cricket | /handcricket.py | 3,427 | 4.0625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Jan 19 20:38:00 2021
@author: kjais
"""
target=0
import random
play=''
def toss(t,p,n):
e=[]
if (p+n)%2==0:
e=['odd','Odd','ODD']
else:
e=['even','Even','EVEN']
if t in e:
bb=input("You won the toss. What do you ... |
3bb6d95502446c35cdbfed74b9067dc54d6d165f | 0rps/lab_from_Alex | /school_42/d02/ex04_ft_print_comb.py | 579 | 4.1875 | 4 | # Create a function on display all different combination of three different digits in ascending order,
# listed by ascending order - yes, repetition is voluntary.
def print_comb():
number = ''
flag = False
for i in range(10):
for k in range(i+1, 10):
for l in range(k+1, 10):
... |
326925b153c9b870613513fbe4d9cbd5b4a59e1d | 0rps/lab_from_Alex | /school_42/d02/ex07_ft_print_combn.py | 1,223 | 3.90625 | 4 | # Create a function that displays all different combination of N numbers by ascending order.
# 0 < n < 10
def print_comb():
while True:
try:
n = int(input("Enter the number. "))
if n < 0 or n > 10:
print("0 < n < 10")
continue
break
... |
853d446d3a645383144d77dabea2b4bcf414e4ab | 0rps/lab_from_Alex | /school_42/proj02/ex00_eval_expr.py | 2,624 | 3.875 | 4 | def is_number(number):
try:
float(number)
return True
except ValueError:
return False
def calculate(arg1, op, arg2):
if op == "+":
return arg1 + arg2
elif op == "-":
return arg1 - arg2
elif op == "/":
return arg1 / arg2
elif op == "%":
re... |
96822b326f6ba8764bb66e2d1d6ce6d17a788929 | smehmood/advent-of-code | /2020/day10/solveA.py | 491 | 3.515625 | 4 | import sys
def main():
inp = [int(line.strip()) for line in sys.stdin]
inp.sort()
prior = 0
ones = 0
threes = 1 # for the last adaptor
for i in inp:
if i - prior == 1:
ones += 1
elif i - prior == 2:
print("Two!")
elif i - prior == 3:
... |
d47247209a04ee2c5fdbdf801d6a803c959bb4f2 | smehmood/advent-of-code | /2019/day4/solveB.py | 878 | 3.53125 | 4 | import sys
def good_pw(pw_int):
pw = str(pw_int)
if len(pw) != 6:
return False
run_length = 1
double = False
last = None
for char in pw:
if last is not None and last > char:
return False
if last == char:
run_length += 1
else:
i... |
3073648ca92e727b4ef8c6d0425eb7abab5fd917 | smehmood/advent-of-code | /2019/day3/solveB.py | 3,942 | 3.578125 | 4 | import sys
def contains(s1, p1):
low = min(s1[0], s1[1])
high = max(s1[0], s1[1])
return p1 >= low and p1 <= high
def intersect(s1, s2):
s1_src = s1[0]
s1_dst = s1[1]
s2_src = s2[0]
s2_dst = s2[1]
s1_is_horizontal = is_horizontal(s1_src, s1_dst)
s2_is_horizontal = is_horizont... |
0dcdbb0bfbc03bebfe99c2c693354589bc197965 | ibukun-koyer/availability_py | /schdule_find.py | 7,323 | 3.703125 | 4 | #import the random generator library
import random
#import np
import numpy as np
#create random name stream
names = ["tonya","william", "samuel", "matt", "johnny", "cage", "lucas","will","jake","mary","olivia", "mike","rice","indigo","justin","blake", "red","black","lucas","tran","alex","judy","alex","violet","sin... |
50be34abd688b7245b3b51a71f78955e4ad7adc6 | AmaniAlshami/100DaysOfCodePython | /Day30-ForLoop2.py | 194 | 4.03125 | 4 | # print even number 0 - 100
for x in range(0,101,2):
print(x)
# nested for loop
# print pattren
for y in range(6):
for x in range(y):
print("* ",end="")
print("")
|
30e0f787987fff37c343d38d8412b3505a625a9b | AmaniAlshami/100DaysOfCodePython | /Day28-WhileLoop.py | 330 | 4.03125 | 4 | # print 5 numbers
i = 1
while i < 10:
print(i)
if i == 5 :
break
i +=1
print("__________________")
# skip number 5
j=0
while j < 10:
j+=1
if j == 5 :
continue
print(j)
print("__________________")
a = 1
while a <= 10:
print(a)
a+=1
else:
print(f"{a} is greater than ... |
136c541291619609fb6c51228909abddfd1e3943 | AmaniAlshami/100DaysOfCodePython | /Day29-ForLoop.py | 145 | 3.78125 | 4 | for a in "Amani":
print(a)
color = ['Red','Pink','Green','Black','whiat']
for i in color:
print(i)
if i == "Green":
break
|
346d832403aed93e5d54335110f1b08b930dd5c5 | AmaniAlshami/100DaysOfCodePython | /Day60-61.py | 282 | 3.6875 | 4 | #Challenge1
# create tuple and convert to string by using JSON
import json
week = ('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday')
print(json.dumps(week))
#Challenge2
import re
txt = 'data is the new oil'
ser = re.search('data',txt)
print(ser.group())
|
f02757535c417deb74506e3ee04fbeb5d49c8443 | AmaniAlshami/100DaysOfCodePython | /Day25-26.py | 330 | 4.0625 | 4 | set1 = {1,3,5,7,8}
# add (4,8,12)
set1.update([4,8,12])
print(set1)
# remove '8'
set1.remove(8)
print(set1)
# delete all items
set1.clear()
print(set1)
#######################
# create dictionary
dic1 = {'name':'pigeon','type':'bird','skin cover':'feathers'}
print(dic1)
print(dic1['type'])
dic1['skin cover'] = 'Pl... |
1544febd4fb040a72aa124e7077a90c74617ce9f | KmSlime/cse-ppl | /04_Functional-Programming/practice/run.py | 688 | 3.734375 | 4 | # [[1,2,3], [4,5,6], [7], [8,9]] -> [1,2,3,4,5,6,7,8,9]
arr = [[1,2,3], [4,5,6], [7], [8,9]]
#### Method 1: Use sum()
print(sum(arr, []))
# interator: arr, start: []
# such as reduce()
#### Method 2: Use reduce()
from functools import reduce
print(reduce(lambda lst, ele: lst + ele, arr, [])) # such as sum()
#### ... |
02f79ca7541c812dcc9cb33a4ae7ff5647171bed | KmSlime/cse-ppl | /04_Functional-Programming/practice/lambda.py | 618 | 3.59375 | 4 | arr = [1, 2, 3, 4, 5, 6, 7, 8]
sqr = (i ** 2 for i in arr) # return iterator
print(list(sqr))
'''
[1, 4, 9, 16, 25, 36, 49, 64]
'''
cube = [i ** 3 for i in arr] # return list
print(cube)
'''
[1, 8, 27, 64, 125, 216, 343, 512]
'''
sqr_range_20_40 = [i ** 2 for i in arr if i ** 2 < 40 and i ** 2 > 20]
print(sqr_range... |
28839cbb687200ad2c3bc24a94b02a2e328a82df | vlvanchin/learn | /learn_python/others/sampleClass.py | 358 | 3.859375 | 4 | class testClass (object):
print "creating a new class\n---------------------"
number = 5
def __init__(self, string):
self.string = string
def printClass(self):
print "number = %d"% self.number
print "string = %s"% self.string
tc = testClass("five")
tc.printClass()
tc.number ... |
20cc7f1c4ff34b334763271c8ea7ccd73071786f | vlvanchin/learn | /learn_python/others/ver3/isOddOrEven.py | 259 | 4.46875 | 4 | #!/usr/bin/env python3
def even_or_odd(number):
'''determines if number is odd or even'''
if number % 2 == 0:
return 'Even';
else:
return 'Odd';
userinput = input("enter a number to check odd or even:");
print (even_or_odd(int(userinput)));
|
9d0a9da807d2ddf9612f66e9fbb133b1246141dc | lalith1403/oopFundamentals | /Inheritance/accessSpecifier.py | 356 | 3.78125 | 4 | # Public attribute
class Car:
numberOfWheels = 4
_color = 'black'
__yearOfManufacture = 2017 # internally _Car_yearOfManufacture
class BMW(Car):
def __init__(self):
print("Protected attribute color: ", self._color)
car = Car()
print("Public: ", car.numberOfWheels)
bmw = BMW()
print("Private att... |
4169025bd628ec489f4fa5fe8ca1a9b3931ba64b | lalith1403/oopFundamentals | /Methods&Attributes/methods.py | 371 | 3.8125 | 4 | # What are instance methods? Methods that make use of self parameter
class Employee:
def employeeDetails(self):
self.name = "Lalith"
@staticmethod
# Used when none of the attributes are sent as parameters
def welcomeMessage():
print("Welcome to our Organization")
e1 = Employee()
e1.em... |
96826ad442f1372a374732982eea868a7b0a02d7 | tandiawanedgar/EdgarTandiawan_ITP2017TugasAldi2 | /PR1.py | 163 | 4.125 | 4 | def loopMain():
word = input('write your word')
wordname = word.split()
print(wordname)
for x in wordname:
print(x[0].upper())
loopMain()
|
c15d6eff08a854ceca3d5ff8170bf22018a82f55 | lrnewsom/CS115CurrencyConverter | /USD.py | 636 | 3.875 | 4 | class USD:
conversion = {'Euro': 0.84, 'Yen': 104.65, 'Bitcoin': 0.000063, 'Peso': 20.42, 'Pound': 0.76, 'Dong': 23176.0,
'Robux': 286, 'GTA$': 56021.38, 'XAU': 0.000532176}
name = "United States Dollar ($)"
key = ""
amount = 0
def __init__(self, other_currency, value):
... |
5b70737cc0b53a66b07885fcb3a1d95d638815cb | BradNeuberg/andrew-ng-course | /linear_regression_1/linear.py | 1,007 | 3.546875 | 4 | import numpy as np
import matplotlib.pyplot as plt
import matplotlib.lines as mlines
NUM_FEATURES = 1
NUM_ITERATIONS = 1500
def prepare_data():
x = np.loadtxt('ex2x.dat')
x = x.reshape(len(x), 1)
x = np.insert(x, 0, values=1.0, axis=1)
y = np.loadtxt('ex2y.dat')
y = y.reshape(len(y), 1)
retu... |
04c9257f27839c65ca637735c8c4dec5e25cf052 | testtestae/workingWithComponentsPythonGroup1 | /components/CakeIsALieGame.py | 440 | 3.6875 | 4 | import random
rand_num = random.randint(0, 1000)
game_status = True
def cakeisalie():
print("привет это игра взломай пароль");
cakeisalie()
while game_status:
a = int( input("взломай пароль: ") )
if a == rand_num:
print("хакер!")
game_status = False
elif a > rand_num:
print("попробуй меньш... |
a84d0072bc7cf8c28e35a25dc20904f336ed3bb1 | xotrs/hacker-rank | /easy/if-else.py | 306 | 3.890625 | 4 | #!/bin/python3
def foo(x):
if x % 2 == 1 and x <= 100:
return "Weird"
elif x % 2 == 0 and 5 >= x >= 2:
return "Not Weird"
elif x % 2 == 0 and 20 >= x >= 6:
return "Weird"
elif x % 2 == 0 and 20 < x <= 100:
return "Not Weird"
N = foo(int(input()))
print(N)
|
df9644fcb9efa9e65607178c9e6864006d54f3bd | gresakowski/Guess-the-word | /functions0.py | 6,309 | 3.65625 | 4 | import math
# funkcja służąca do stworzenia listy graczy
def players_list(players0):
while True:
player = input("Podaj imię gracza: ")
player = player.capitalize()
if player not in players0:
players0.append(player)
elif player in players0:
print(f'G... |
50203e8df46785142dcb1ef21342f99f5f3130c6 | ShristiC/Python-Games | /WarCardGame/Player.py | 1,044 | 3.890625 | 4 | """
Player class for the War Card Game
- holds a player's current list of cards
- player should be able to add / remove cards to their "hand"
- player can add single or multiple cards to their "hand"
- need to translate a deck of cards with top / bottom to Python list
"""
# pop(0) from the list --> taking the top ca... |
d46d6e0a8e63ca3ae1f83ecb50707a4f3fa48538 | grrtvnlw/grrtvnlw-python-103-medium | /tip_calculator2.py | 991 | 4.25 | 4 | # write a tip calculator based off user input and quality of service and divide bill in equal parts
# get user input for total bill amount, quality of service, how many ways to split, and tip amount
total_bill = float(input("Total bill amount? "))
service_level = input("Level of service - good, fair, or bad? ")
split =... |
add11dd9454927d4503453798eb2352253671c37 | adalloul0928/Leetcode_Hell | /Archive/searchRotatedArray_33.py | 1,037 | 3.546875 | 4 | class Solution:
def search(self, nums, target):
if nums:
S = 0
E = len(nums) - 1
return self.helper(nums, S, E, target)
else:
return -1
def helper(self, nums, S, E, target):
mid = (S+E)//2
# print(mid)
if nums[m... |
c1cd99451c2509dc0cfd698315729bcc2d314425 | adalloul0928/Leetcode_Hell | /Archive/Facebook/Trees & Graphs/flattenBinaryTreeLinkedList.py | 1,082 | 3.890625 | 4 | # Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def flatten(self, root: TreeNode) -> None:
"""
Do not return anything, modify root in-place instead.
"""
if root:
... |
9ae79a4e87809bcf034037017bb344f972eb1c43 | adalloul0928/Leetcode_Hell | /Archive/Amazon/longestPalindromicString.py | 979 | 3.625 | 4 | class Solution:
def longestPalindrome(self, s: str) -> str:
myArr = [[0 for x in range(len(s))] for x in range(len(s))]
start = 0
maxPalindrome = 0
for x in range(len(s)):
myArr[x][x] = 1
maxPalindrome = 1
start = x
# two letters in a row... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.