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 |
|---|---|---|---|---|---|---|
3460b726f7d5533c5cd881edc99f8b6419d978ea | N3mT3nta/ExerciciosPython | /old/ex018.py | 240 | 3.828125 | 4 | import math
ang = int(input('Digite o valor do ângulo:'))
sin = math.sin(math.radians(ang))
cos = math.cos(math.radians(ang))
tan = math.tan(math.radians(ang))
print('Seno: {:.2f}\nCosseno: {:.2f}\nTangente: {:.2f}'.format(sin, cos, tan))
|
96acfb2efce29918db51efe8bfc31e610982b079 | N3mT3nta/ExerciciosPython | /Mundo 1 - Fundamentos/ex016.py | 148 | 3.890625 | 4 | from math import trunc
num = float(input('Digite um número: '))
numtrunc = trunc(num)
print(f'O número {num} tem como parte inteira {numtrunc}.')
|
5aefb5a1e6e229de5a6356e902092aeade75a173 | N3mT3nta/ExerciciosPython | /Mundo 1 - Fundamentos/ex022.py | 310 | 3.8125 | 4 | nome = input('Digite seu nome completo: ').strip()
print('Em maiúsculas: {}'.format(nome.upper()))
print('Em minúsculas: {}'.format(nome.lower()))
ql = len(nome.replace(' ', ''))
print(f'Quantidade de letras no nome: {ql}')
qlpm = len(nome.split()[0])
print(f'Quantidade de letras no primeiro nome: {qlpm}')
|
c0ef6f145d65b4e413caf6e5992ed80042437664 | N3mT3nta/ExerciciosPython | /Mundo 2 - Estruturas de Controle/ex051.py | 215 | 3.84375 | 4 | pt = int(input('Primeiro termo: '))
razão = int(input('Razão: '))
pa = 0
print('Mostrando os 10 primeiros termos da PA inserida:')
for c in range(1, 11):
print(f'{pt}', end=' → ')
pt = pt + razão
print('FIM') |
fb04eb241781c1f37d7abe1700e51294096eec9e | N3mT3nta/ExerciciosPython | /Mundo 1 - Fundamentos/ex007.py | 137 | 3.75 | 4 | n1 = float(input('Primeira nota: '))
n2 = float(input('Segunda nota: '))
m = (n1+n2)/2
print(f'\033[32mA média do aluno é de {m:.1f}')
|
02d9e1fd29250820bebacb1eeb62156363dff7c1 | N3mT3nta/ExerciciosPython | /Mundo 2 - Estruturas de Controle/ex044.py | 1,251 | 3.875 | 4 | preço = float(input('Qual o preço do produto: R$'))
print('Digite o número referente ao método de pagamento desejado:')
print('1 - À vista em dinheiro ou cheque (10% de desconto)')
from time import sleep
print('2 - À vista no cartão (5% de desconto)')
print('3 - 2x no cartão (preço integral)')
print('4 - 3x ou mais no ... |
099b391b047593bbceaed299fa34910429c82fdf | N3mT3nta/ExerciciosPython | /old/ex009.py | 290 | 3.8125 | 4 | n = int(input('Digite um número:'))
print('-----------')
print(n,'x1 =', n*1)
print(n,'x2 =', n*2)
print(n,'x3 =', n*3)
print(n,'x4 =', n*4)
print(n,'x5 =', n*5)
print(n,'x6 =', n*6)
print(n,'x7 =', n*7)
print(n,'x8 =', n*8)
print(n,'x9 =', n*9)
print(n,'x10 =', n*10)
print('-----------') |
da8cca7641dfdf7ae865bad7230a2d3beecfb065 | N3mT3nta/ExerciciosPython | /old/ex011.py | 227 | 3.75 | 4 | a = float(input('Qual a altura da parede?'))
l = float(input('Qual a largura da parede?'))
ar = (a*l)
print('A área dessa parede vale {} metros quadrados'.format(a*l))
print('Você precisa de {} litros de tinta'.format(ar/2))
|
e0ffc6ba7632d67983b6b0f81e7249a22cf62182 | N3mT3nta/ExerciciosPython | /Mundo 1 - Fundamentos/ex031.py | 262 | 3.765625 | 4 | km = float(input('Qual a distância da viagem em Km: '))
if km <= 200:
print('O custo é de R$0,50 por Km e o valor da passagem será de R${}'.format(km * 0.5))
else:
print('O custo é de R$0,45 por Km e o valor da passagem será de R${}'.format(km * 0.45))
|
281619ccb93bc6447457769fb4a12024795a4b7d | N3mT3nta/ExerciciosPython | /old/ex006.py | 118 | 3.65625 | 4 | n1 = int(input('Digite um número:'))
print('Dobro:', n1*2)
print('Triplo:', n1*3)
print('Raiz quadrada:', n1**(1/2))
|
328b56606429328a856aa7181ed5f2bb9638a1ae | N3mT3nta/ExerciciosPython | /Mundo 2 - Estruturas de Controle/ex052.py | 337 | 3.921875 | 4 | tot = 0
num = int(input('Digite um número: '))
for c in range(1, num + 1):
if num % c == 0:
print('\033[32m')
tot = tot + 1
else:
print('\033[31m')
print('{} '.format(c), end=' ')
print(f'\033[mO valor {num} foi divisível {tot} vezes, portanto: ')
if tot == 2:
print('\033[32mÉ primo')
else:
print('\033[31mNã... |
54df8525dcd0a010920ae09730af369762729ae7 | udoy382/OopTutorials | /oop_2.py | 497 | 3.734375 | 4 | # Instance and class Variables
class Employee:
increment = 1.5
def __init__(self, fname, lname, salary):
self.fname = fname
self.lname = lname
self.salary = salary
self.increment = 1.4
def increase(self):
self.salary = int(self.salary * Employee.increment)
harr... |
b2ffd5ecb090ae6175f4a639823fe8fb9fa50523 | CarineGhisiCadorin/Exercicios_LP_B1 | /7.py | 363 | 3.90625 | 4 | print("Seja bem-vindo")
nome = print(input ("informe seu nome: "))
print("Ola")
a = float(input("Informe a primeira nota: "))
b = float(input("Informe a segunda nota: "))
d = (a+b)/2
if(d>= 7):
print("você passou, média:",d)
if(d < 7):
print("Sua média está baixa, média:",d)
if(d > 10):
print("Você digi... |
abe932ea52c4b8e39dc2abc568f408b069a1e0f2 | SamirIngley/Interview-Prep | /parenth.py | 400 | 3.984375 | 4 | # Imagine you are writing a function for a new code editor that will check
# if a string expression contains correctly balanced parentheses.
# this func will
for item in string:
if item == '(':
left += 1
elif item == ')':
right += 1
if right != left:
raise ERROR
USE A STACK add the open... |
c7b6128844066b7d9905b1c7cadfa3c12b91eb3b | arushi4580/Tanks112 | /graphics.py | 18,493 | 3.671875 | 4 |
#### Graphics Functions ####
import tankClass
import wallClass
import bulletClass
from tkinter import *
import math
def init(data):
data.margin = 50
data.timerCalls = 0
data.numLevels = 2
data.mode = "start"
data.level = "level1"
# makes a player tank
def makeTank(x, y, angle):
... |
9c793655a9c31d567e254c30eda2bc48b8935c13 | aghaznaw/ros | /FinalRelease/modelbuilder.py | 279 | 3.703125 | 4 | # Hello World program in Python
x = 20
while x < 80:
print("("+str(x)+", 30), ("+str(x)+", 31), ("+str(x)+", 32), ("+str(x)+", 33), ("+str(x)+", 34), ("+str(x)+", 35), ("+str(x)+", 36), ("+str(x)+", 37),("+str(x)+", 38),("+str(x)+", 39),("+str(x)+", 40),")
x = x +1
|
200295878db9a372ef13132c86a41c99a4fbd307 | jonas-graae/bikeshare_assignment | /bikeshare.py | 9,992 | 4.1875 | 4 | import time
import datetime as dt
import pandas as pd
import numpy as np
filters = {
'CITY_DATA': {
'chicago': 'chicago.csv',
'new york city': 'new_york_city.csv',
'washington': 'washington.csv'
},
'months': ['january', 'february', 'march', 'april', 'may', 'june' ],
... |
1f23bfe9500c5f4405f3f1ad69e472dd5a755a05 | NickPerez06/Python-miniProjects | /rpsls.py | 1,802 | 4.34375 | 4 | '''
This mini project will create the game rock, paper, scissors,
lizard, spock for your enjoyment.
Author: Nicholas Perez
'''
import random
def name_to_number(name):
'''converts string name to number for rpsls'''
number = 0
if( name == "rock" ):
number = 0
return number
elif ( name == "Spock" ... |
5714d95eec1170f8100f2da0c7617604d84c36e3 | IgorMChaves/lp2.2 | /a1b1 lp2.2/A1B1questão2.py | 219 | 3.796875 | 4 | menos = int (input('Informe o número de garrafas menores de 1L: '))
mais = int (input('Informe o número de garrafas maiores que 1L: '))
print ("O usuário receberá como reembolso: R$", ((menos * 0.10)+(mais * 0.25))) |
a00a8455669212df519d591803286efb95c6fddc | IgorMChaves/lp2.2 | /a1b1 lp2.2/A1B1questão8.py | 244 | 3.96875 | 4 | n = int(input("Informe um número e descubra seu n-ésimo termo da sequência de Fibonacci: "))
tx=1
ty=1
if (n==1) or (n==2):
print("1")
else:
count=3
while count <= n:
t = tx + ty
ty = tx
tx = t
count += 1
print(t) |
29bcc76645fbf2a3133fe36f2799a53ac5de279b | MicahJank/Intro-Python-I | /src/16_stretch.py | 1,893 | 4.3125 | 4 | # 3. Write a program to determine if a number, given on the command line, is prime.
# 1. How can you optimize this program?
# 2. Implement [The Sieve of
# Eratosthenes](https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes), one
# of the oldest algorithms known (ca. 200 BC).
import sys
import math
#... |
71eaf28404be7b55b9e86d60574b987eb266d239 | Roshan1115/PythonNTEL | /Week2/Assignment/primepartition.py | 764 | 4 | 4 | def PrimeCheck(num): # cheking for prime number
if (num == 0 or num == 1):
return False
elif num == 2:
return True
for i in range(2, num):
if (num%i == 0):
return False
elif i == num-1:
return True
def primepartition(m): # Checking for partition... |
975593f0223d47440fe0a62fc942ab022d41210e | Roshan1115/PythonNTEL | /Week4/Assignment/flatten.py | 273 | 3.8125 | 4 | result =[]
def flatten(l):
for i in l:
if listtype(i):
flatten(i)
else:
result.append(i)
return(result)
def listtype(l):
return(type(l) == type([]))
# print(flatten([1,2,[3],[4,[5,6]]]))
# print(flatten([1,2,3,(4,5,6)]))
|
3956e4abb9f24adb897e877fec2e707ecd2837e1 | Roshan1115/PythonNTEL | /Week3/RecursiveInsertionSort.py | 384 | 3.671875 | 4 | def RIS(LIST):
isort(LIST, len(LIST))
return(LIST)
def isort(LIST, k):
if k > 1:
isort(LIST, k-1)
insert(LIST, k-1)
def insert(LIST, k):
position = k
while (position > 0 and LIST[position] < LIST[position -1]):
LIST[position], LIST[position-1] = LIST[position-1], LIST[posit... |
349ff41e87e9ae1a922e307ad658d2236389f326 | Aabid92/Python-Codes | /my.py | 680 | 3.859375 | 4 | import datetime
# user_input = input("Enter the number:")
# if user_input == 12:
# for x in range(10):
# print(x)
# spam_amount = 0
# print(spam_amount)
# # Ordering Spam, egg, Spam, Spam, bacon and Spam (4 more servings of Spam)
# spam_amount = spam_amount + 4
# if spam_amount > 0:
# print("But ... |
61ad20e55120a3ddfa0806560cc1214045038de0 | ppyyyhhh/Learning-Python-on-Coursera | /Python data structure/week4-List/Quiz 8.4.py | 282 | 4 | 4 | fname = input("Enter file name: ")
fh = open(fname)
lst = list()
for line in fh:
words = list(line.split())
for word in words:
if word in lst: #check if the word exist in the list
continue
else:
lst.append(word)
print(sorted(lst)) |
a77b48bdc124c79dbdbb4c6f95c968eb0ea272d5 | ppyyyhhh/Learning-Python-on-Coursera | /Python data structure/week4-List/Lecture 8.3.py | 309 | 4.03125 | 4 | #split
abc = 'with three words'
stuff = abc.split()
print(stuff)
print(len(stuff))
for w in stuff:
print(w)
#Double split patter
line = "from stephenaoejggj@uct.ac.za Sat Jan 5 08:14:19 2020"
words = line.split()
email = words[1]
print(email)
pieces = email.split('@')
print(pieces)
host = pieces[1]
print('host=',h... |
a7391b38b6f4606e847f0ebf880e82b1b7be1d71 | gsepulv1/ST0245-08 | /taller_listas/3_notas.py | 611 | 3.953125 | 4 | # Se quiere realizar un programa que lea por teclado las 5 notas obtenidas por un
# alumno (comprendidas entre 0 y 10). A continuación debe mostrar todas las notas,
# la nota media, la nota más alta que ha sacado y la menor.
notas = []
for indice in range(1,6):
while True:
nota = int(input("Introduce la no... |
8684a5936ca3104146d65d0e7f18847358f9422c | gsepulv1/ST0245-08 | /busquedas/ordenamiento_insercion.py | 303 | 3.734375 | 4 | def Insercion(lista_a): #numeros es una lista
for i in range(1,len(lista_a)):
valor_a_ordenar =lista_a[i]
while lista_a[i-1] > valor_a_ordenar and i >0:
lista_a[i], lista_a[i-1]= lista_a[i-1], lista_a[i]
i = i-1
return lista_a
lista = [8,9,2,15]
print(Insercion(lista)) |
da1ed3d317cf49a0ad267e0e9a8b508917a54e9c | gsepulv1/ST0245-08 | /Listasenlazadas/crear un nodo.py | 1,217 | 3.953125 | 4 | class ListNode:
def __init__(self,datoInicial):
self.dato = datoInicial
### Podemos crear varias instancias de esta clase,
# cada una almacenando datos de nuestra elección.
# En el siguiente ejemplo, creamos tres instancias, cada una almacenando un valor entero
a = ListNode( 11 )
b = ListNode(... |
806c066eef33a87524f4b99234fa0f47a372465b | treymeares/Sporting-League-Manager-w-UI | /curling_league_manager/source/DuplicateEmail.py | 204 | 3.734375 | 4 | class DuplicateEmail(Exception):
"""
Exception class for duplicate email. Throws exception when email equal
to another email.
"""
def __init__(self, email):
self.email = email
|
99bfc65a4a0cffca30b37ff18a129edd81b8b359 | kom50/PythonProject | /Simple Code/Factorial.py | 369 | 4.21875 | 4 | # find factorial using loop
def fact(num): # 1st function
f = 1
for i in range(1, num + 1):
f *= i
return f
# find factorial using recursive function
def fact1(num): # 2nd function
if num == 1:
return 1
return num * fact1(num - 1)
# 1st function
print('Factorial : ', fact(4))... |
2dfd5159878e294a7c8a807c83671be05eaf60d3 | DavidPits/BookBuster | /DataCollecter/models.py | 331 | 3.53125 | 4 | from dataclasses import dataclass
@dataclass
class Book:
title: str
author: str
author_url: str
rating: float
voters_count: int
url: str
isbn: str
def __eq__(self, other) -> bool:
return self.title == other.title
def __hash__(self) -> int:
return hash(('title', se... |
e163b6187de872916018002a9af74e9d68304ccf | rajya-talatam/school_administration_tool | /mycaptain project.py | 1,203 | 4.03125 | 4 | #Project 1: Basic School administration tool
import csv
def write_into_csv(info_list):
with open("My_captain.csv","a", newline="") as csv_file:
writer = csv.writer(csv_file)
if csv_file.tell() == 0:
writer.writerow(["Name", "Age", "phone_Number", "Email_Id"])
writer.writer... |
b49205c73174bd5f08e7feae9392577c6e2d0879 | Curiosity8/SokoPy | /Stack.py | 805 | 3.890625 | 4 | # My implementation of Stacks, using linked list.
# Not 100% complete, yet sufficient for our needs.
class NodeStack:
def __init__(self, item):
self.item = item
self.next = None
class Stack:
def __init__(self):
self.first = None
self.last = None
self.N = 0
def __l... |
44369cfe4786399c11ea35e14e08f9db244fa55c | TopaGeor/Test-Dome-python | /find_two_sum.py | 1,191 | 3.796875 | 4 | #8. Two Sum
#Write a function that, when passed a list and a target sum, returns, efficiently with respect to time used, two distinct zero-based indices of any two of the numbers, whose sum is equal to the target sum. If there are no two numbers, the function should return None.
#For example, find_two_sum([3, 1, 5, 7... |
676fc4ab537a44df1f4adb9d88d8fe8068a9ce79 | yanngasner/algorithmsChallenge | /LeetCodeChallenges/maximumProductSubarray.py | 2,226 | 3.890625 | 4 | # Given an integer array nums, find the contiguous subarray within an array (containing at least one number) which has the largest product.
# Example 1:
# Input: [2,3,-2,4]
# Output: 6
# Explanation: [2,3] has the largest product 6.
# Example 2:
# Input: [-2,0,-1]
# Output: 0
# Explanation: The result cannot be 2, be... |
2248a3228b48815cc823849ba03c65339ad76c1e | ferdcoz/ClimateChangeLR | /ClimateChangeLR.py | 2,089 | 3.90625 | 4 | import matplotlib.pyplot as plt
import numpy as np
from sklearn.linear_model import LinearRegression
import seaborn as sns; sns.set()
yearsBase, meanBase = np.loadtxt('https://raw.githubusercontent.com/ferdcoz/ClimateChangeLR/master/5-year-mean-1951-1980.csv', delimiter=',', usecols=(0, 1), unpack=True)
years, m... |
6aa47cd97da9f307b127f9ba7df2b81325f5674b | tlkoo1/Lok.Koo-Chatbot | /ChatBotTemplate.py | 569 | 4.25 | 4 | #open text document stop-words.txt
file = open("stop-words.txt")
stopwords = file.readlines()
#function going through all stopwords
def removeStopwords(firstWord):
for word in stopwords:
next = word.strip()
firstWord = firstWord.replace(" " + next + " ", " " )
return firstWord
#while inpu... |
9f5e709d1439affa9ddd21111c0079a12f290abb | rhkdgh815/rhkdgh815 | /문29.py | 109 | 3.625 | 4 | amount = int(input("도형의 크기를 입력해주세요:"))
for i in range(1,amount +1):
print("*"*i) |
421aa8447f4efd5cfcb1c5741fcb095c4b72820c | rhkdgh815/rhkdgh815 | /문13.py | 148 | 3.6875 | 4 | num = int(input())
old = int(input())
rank = int(input())
if old >= 30 and age < 40:
if rank == 3 or rank == 5 or rank == 7:
print(num) |
2aa21f71d5a6c442eb4cdab1efe266876013bfff | rhkdgh815/rhkdgh815 | /문17.py | 273 | 3.84375 | 4 | num = int(input())
date = int(input())
if date % 2 == 0 :
if num % 2 == 0 :
print ("운행가능")
else :
print("운행 불가능")
if date % 2 == 1:
if num % 2 == 1 :
print("운행가능")
else :
print("운행 불가능")
|
e8ec416a7c37be2d6f3e12e541a837fc0ca292b0 | s19014/CodingBat | /python/Warmup-2/last2.py | 346 | 3.96875 | 4 | '''Given a string, return the count of the number of times that a substring
length 2 appears in the string and also as the last 2 chars of the string, so
"hixxxhi" yields 1 (we won't count the end substring).'''
def last2(str):
n = 0
for i in range(len(str)-2):
if str[-2:] == str[i] + str[i+1]:
... |
50e8a196778240e23745fc0bceaa646d4c619133 | s19014/CodingBat | /python/String-2/count_code.py | 322 | 4.09375 | 4 | '''Return the number of times that the string "code" appears anywhere in the
given string, except we'll accept any letter for the 'd', so "cope" and "cooe"
count.'''
def count_code(str):
cnt = 0
for i in range(len(str) - 3):
if str[i:i+2] == 'co' and str[i+3] == 'e':
cnt += 1
return cn... |
757e24923fbe27cd1237b6d94364d194521261db | h4x0rMadness/ec500-health-monitor | /generate_data.py | 1,142 | 3.5 | 4 | # coding: utf8
import time
import random
def generate_data():
Pulse = random.randint(0,100) #range from 20-60 is normal else it alerms
BP = random.randint(50,200) #range from 80-140 is normal else it alerms
OL = random.randint(30,150) #range from 60-110 is normal else it alerms
data = [Pulse,BP,OL]
... |
1f17c4f5d6d37144e216468e401e9abf0c4aa172 | rahul-bhave/python-practice | /test.py | 511 | 3.65625 | 4 | """
https://pypi.org/project/dacite/
https://github.com/Dobiasd/undictify
https://stackoverflow.com/questions/35282222/in-python-how-do-i-cast-a-class-object-to-a-dict/35282286
"""
from dataclasses import dataclass, asdict, field, InitVar
@dataclass
class User(object):
name: str
age: int
is_active: boo... |
073692fcf207631c93be6bafa320fe5bd990df04 | GroupD5Cov/D5VirtualRobotProject | /Startmenu-test/game.py | 5,533 | 3.5625 | 4 | from tkinter import *
root =Tk()
canvas = Canvas(width = 1280, height = 600, bg = 'silver')
canvas.pack(expand = YES, fill = BOTH)
gif1 = PhotoImage(file = 'startmenu2.gif')
canvas.create_image(30, 10, image = gif1, anchor = NW)
Start = Button(root, text="START", height = 4, width = 10,fg="green",)
Start.pac... |
b94ee15d64250a0bb93309f36e182fbb36e0bfb0 | shroukhegazi/CrowdFunding | /menu.py | 357 | 3.734375 | 4 |
def menuf():
print (" Welcome to Crowd site")
choice = input ("enter l for login or r for register:")
if (choice == 'l'):
import Login
Login.loginf()
elif (choice == 'r'):
import Registration
Registration.registerf()
else:
input("enter l for login... |
de711e114dff50abcdc3617db520ac95858fe20b | josephjkuang/PER-Response-Predictor | /IBM_data.py | 3,405 | 3.90625 | 4 | # Class that will take in a CSV of training data and convert it into a json.
# Each entry of the json will correspond to a single response
# They will generally have one label being its code (sometimes 2 if its a dual code)
import csv
import json
data = []
# Constants for the rows of certain fields in the csv file
s... |
88e824d748346db2a3cf149f8acf54f489c39c3d | lkesteloot/boggle | /boggle.py | 5,768 | 3.640625 | 4 | #!/usr/bin/python
# Copyright 2011 Lawrence Kesteloot
"""Solves a Boggle board using a variety of data structures."""
import random
from timer import Timer
import trie_dictionary
import prefix_dictionary
import binary_search_dictionary
import progressive_binary_search_dictionary
import progressive_text_binary_searc... |
67ab3cd5336041ab7d062a37c1199ddd68cc8332 | lkesteloot/boggle | /utils.py | 1,208 | 4.0625 | 4 | # Copyright 2011 Lawrence Kesteloot
def binary_search(words, word, low=0, high=None):
"""Return an (index, found) tuple, where index is either where the word was
found or where it should be, and found is whether it was found."""
if high is None:
high = len(words) - 1
while low <= high:
... |
25dfa071fd16723f978fa95379e89ab81cfe88b0 | PrincetonUniversity/hpc_beginning_workshop | /python/cpu/matrix_inverse.py | 112 | 3.640625 | 4 | import numpy as np
N = 3
X = np.random.randn(N, N)
print("X =\n", X)
print("Inverse(X) =\n", np.linalg.inv(X))
|
9abc1bad55de5672a1cd94f55629ffaeb65aa304 | Manueh452/Tabla-de-frecuencias | /TF.py | 768 | 3.96875 | 4 | import math
#DATOS INICIALES
numero_de_datos=int(input("introduca el numero de datos "))
Dato_menor=float(input("asigne dato menor "))
Dato_mayor=float(input("asigne dato mayor "))
Rango=Dato_mayor-Dato_menor
intervalos=1+3.3*(math.log(numero_de_datos))
round(intervalos)
Ampl_Clase=Rango/intervalos
round(Ampl_Clase)
Da... |
ef6c8b1057839016de9dd2b51ffd879435043270 | martinaobrien/pands-problem-sets | /sumupto.py | 1,128 | 4.28125 | 4 | # Martina O'Brien: 24 - 02 - 2019
# Problem Set Programming and Scripting Code 1
#Calculate the sum of all factorials of positive integer
# Input variable needed for calculation
# Int method returns an integer as per python programming
# input "Enter Number" will be visible on the user interface
# setting up va... |
e5d137aa16162464b1a8d64cef1f80884bc21e73 | waterrskiing/Python-work | /demo/ListOverlap.py | 439 | 3.828125 | 4 | '''
Created on Sep 15, 2015
Exercise for 2 lists interaction.
http://www.practicepython.org/exercise/2014/03/05/05-list-overlap.html
@author: TungPT10
'''
import random
# a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
# b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
# c = []
a = random.sample(range(100), 10)
b = random.... |
0debb74096cb6fb8c78922e17677242b87b884d9 | rmaur012/GraphicalSequenceAlgorithm | /GraphicalSequenceAlgorithm.py | 2,392 | 4.3125 | 4 | #Setting up the sequence list
try:
sizeOfSeq = raw_input("How many vetices are there? ")
sizeOfSeq = int(sizeOfSeq)
index = 0
sequence = [None]*sizeOfSeq
except ValueError:
print 'A Non-Numerical Value Was Entered. Please Try Again And Enter With A Numerical Value.'
quit(... |
6a95b20b133401fd1c9e25de6a7ec2d51724a281 | ganiganesh92/learningAlgos | /eratosthenes.py | 422 | 3.640625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Sieve of Eratosthenes
@author: sriram
"""
def printNPrimes(n):
flag = [True] * n
flag[0] = False
flag[1] = False
for i in range(2,n):
if flag[i]:
for j in range(i*2,n,i):
flag[j] = False
print([i for i in range(... |
9a1d07322402844b012482d97ada265df58287d6 | ganiganesh92/learningAlgos | /quickselect.py | 1,477 | 3.84375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Quickselect
@author: sriram
"""
import random
def _partition(arr, startIndex, stopIndex):
pivot = arr[(startIndex + stopIndex)//2]
while True:
while arr[startIndex] < pivot:
startIndex = startIndex + 1
while arr[stopIndex] > pivot:... |
96e5dbaebcd358e7090bcc96c3d0bd62d411d8e6 | ganiganesh92/learningAlgos | /dfs.py | 1,192 | 3.625 | 4 | import random
from collections import OrderedDict
class Graph():
def __init__(self):
self._graph = OrderedDict()
def __str__(self):
return ", ".join([v + " -> (" + ", ".join([w for w in self._graph[v]]) + ")" for v in self._graph])
def addEdge(self, v1, v2, w = 1):
if v1 not in se... |
84293f27bd7376c4b6518cdf3c3fd8e588e95460 | ganiganesh92/learningAlgos | /quickSort.py | 1,086 | 3.90625 | 4 | import random
def quickSort(li):
newList = list(li)
_quickSort(newList, 0, len(li) - 1)
return newList
def _getPivot(li, startIndex, stopIndex):
return li[int((startIndex + stopIndex)/2)]
def _partition(li, startIndex, stopIndex):
pivot = _getPivot(li, startIndex, stopIndex)
while True:
... |
89051fde90eb46f43ed952b4a8624625ef40fd1e | Luckykarter/Py_filesystem | /FS.py | 979 | 3.65625 | 4 | import os
import shutil
def printL(p, level):
t = str()
for _ in range(0, level):
t += "\t"
print(t + p)
def listAll(path, onlydirs = False, maxlevel = None, level=0):
printL(path, level)
for p in os.listdir(path):
cpath = os.path.join(path, p)
if os.path.isdir(cpath):
... |
6a5d0be802fd3022ffdcb6ee0b59907932ef3e14 | Spector255/Programming_I_2021-2022 | /uzdevumi/uzmini.py | 399 | 3.546875 | 4 | import random
def parbaude(skaitlis):
solis=1
sk = int(input("Ievadi skaitļi: "))
while sk != skaitlis:
if sk < skaitlis:
solis+=1
sk = int(input("Mini lielāku skaitli: "))
elif sk > skaitlis:
solis+=1
sk =int(input("Mini mazāku skaitli: "))
... |
d44ed7a6afcb6365919f872e9208dea91f7b3edb | ycoms1/HotelProject | /hotel_Devops/functions.py | 812 | 3.765625 | 4 | from hotel_Devops.hotel_func import *
def menu():
boolean = 0
while boolean == 0:
choice = input(
"Menu:\n1.search for available rooms\n2.search for specific date\n3.invitation\n"
"4.cancel order\n5.add days/rooms\n6.search for invitation\n")
if choice == "1":
... |
525f74a7ab297b1b4e3bc263ef89980e62c8e2fb | Booxworm/NTU_Food_Project | /main.py | 9,940 | 4.0625 | 4 | import gui
import algo
import db
def getInput(msg, options=False, exit=True):
"""
Prints out the input message, and lists out all the options provided
Accepts the input message, and a list of options [optional] as parameters
Adds an 'Exit' option as the last option if exit flag is set
Returns user ... |
58a97145ee2f87d9ed610bed4e3784a8d658da1a | llkenny/python_basics | /lesson_2.py | 6,072 | 3.859375 | 4 | # Создать список и заполнить его элементами различных типов данных.
# Реализовать скрипт проверки типа данных каждого элемента.
# Использовать функцию type() для проверки типа.
# Элементы списка можно не запрашивать у пользователя, а указать явно, в программе.
def exercise_1():
list = ["13", "test", "True", True, ... |
fc3f8c3a142ac5f85f5e69c6fe256f43e34346c1 | llkenny/python_basics | /basics.py | 4,133 | 3.765625 | 4 | # 1
i = 0
b = True
f = 0.2
s = "string"
print(f"{i} {b} {f} {s}")
i = int(input("Enter new integer value: "))
s = input("Enter new string: ")
print(f"{i} {b} {f} {s}")
# 2
# Пользователь вводит время в секундах.
# Переведите время в часы, минуты и секунды и выведите в формате чч:мм:сс.
# Используйте форматирование с... |
2337ab12379f9170895a9b44578a195f141dc30c | wapcaplet/ardiff | /arlog.py | 1,339 | 3.6875 | 4 | #! /usr/bin/env python
# logger.py
"""Print the serial output from an Arduino, with timestamps on each line.
Usage:
arlog.py [device] [baud]
Examples:
arlog.py # Log /dev/ttyACM0 at 9600 baud
arlog.py /dev/tty23 # Log /dev/tty23 at 9600 baud
arlog.py /dev/tty23 2400 # Log /d... |
2b8c207f3d366b935b16ec280c7c2b2b9c21a2d4 | matthewbro3/Kew_CSA_Test | /redlistCheck.py | 6,862 | 4.125 | 4 | #!/usr/bin/env python3
import sys, math
import matplotlib.pyplot as plt
check = sys.argv[1]
red = sys.argv[2]
growth = sys.argv[3]
"""
Define the first argument as the checklist file name ("check"), the second argument as the IUCN Red list filename ("red"), and the third argument as the growth forms list file name ("g... |
5e7fe25e22b34acc1c0132e069146a057090d559 | GeneralFich/wsb-tracker | /main.py | 535 | 3.703125 | 4 | import scraper
is_ready = False
year, month, date = None, None, None
subreddit = "wallstreetbets"
while not is_ready:
subreddit = input("Which subreddit do you want to scrape?:\n")
year = int(input("Start year: "))
month = int(input("Start month: "))
date = int(input("Start date: "))
if input("Rea... |
bfe9e924814c2e76c2c83f3f04cc21074029f73c | sidgan/Gender-Identifier | /gender_identifier.py | 713 | 3.5 | 4 | #!/usr/bin/python
def gender_features(word):
return { 'last_letter' : word[-1] }
#end
import random
import nltk
names = ([(name,'male') for name in ('C:\Users\ANMOL\Desktop\male.txt')] + [(name,'female') for name in ('C:\Users\ANMOL\Desktop\female.txt')])
random.shuffle(names)
featuresets = [(gender_fe... |
fb9f703f343390b168e06a11075376e93981bd48 | jmzhang18/Algorithm | /rotateMatrix.py | 283 | 3.78125 | 4 | #!/usr/bin/env python
def rotateMatrix(mat=[[]]):
result = [[0 for j in range(len(mat[i]))] for i in range(len(mat))]
for i in range(len(mat)):
for j in range(len(mat[i])):
result[j][len(mat[i])-1-i] = mat[i][j]
return result
print(rotateMatrix([[1,2,3],[4,5,6],[7,8,9]]))
|
96f3b06042264dcb35056f58928c69f5d9f423d6 | jmzhang18/Algorithm | /longestPalindrome.py | 1,159 | 3.53125 | 4 | # -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
def longestPalindrome(s):
"""
:type s: str
:rtype: str
"""
string_length = len(s)
table = [[0 for i in range(string_length)] for j in range(string_length)]
max_string_length = 1
start_i = 0
'''... |
65f9b8e59050b55116e4ccc04acf7947008f37db | hsrwrobotics/Robotics_club_lectures | /Week 3/Monday/recap exercise.py | 1,410 | 3.890625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Oct 28 18:39:01 2019
HSRW Robotics
@author: mtc-20
"""
# The safe and robust approach. A function that returns True or False and
# doesn't store the preset value any variable that can be accessed or modified
#function definition
def password(user_input):
if ... |
adab3d9ccab42569ced54c6fd3551335a7b34969 | hsrwrobotics/Robotics_club_lectures | /Week 2/Functions/func_echo.py | 1,497 | 4.375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Oct 21 16:15:36 2019
HSRW Robotics
@author: mtc-20
"""
# A function definition starts with the keyword def followed the function
# name which can be anything starting with an alphabet, preferably in
# lowercase followed by a colon {:}. The body(the block of code to... |
0ea0765b5bf285085d2586e901869881ac73471b | aperritano/cluster-cameratrap-data | /photo_dup.py | 3,388 | 3.5 | 4 | __author__ = 'aperritano'
# Hello, this script is written in Python - http://www.python.org
# doublesdetector.py 1.0p
import os, os.path, string, sys, sha
message = """
doublesdetector.py 1.0p
This script will search for files that are identical
(whatever their name/date/time).
Syntax : python %s <directories>
... |
f1f64999e3479ebe28fd774a7a4807c6e14681db | danilokevin/Lote-1---Python | /Lote 1/Ex15.py | 300 | 3.90625 | 4 | # Objetivo: Receba os valores de 2 catetos de um triângulo retângulo. Calcule e mostre a hipotenusa.
import math
c1=int(input("Qual o valor do primeiro cateto? "))
c2=int(input("Qual o valor do segundo cateto? "))
hip=math.sqrt((c1*c1)+(c2*c2))
print("O valor da hipotenusa é: ", hip) |
b746788b2a554acf3ce050acede7af3fb3ae19d3 | danilokevin/Lote-1---Python | /Lote 1/Ex24.py | 329 | 4.34375 | 4 | # Objetivo: Receba um valor inteiro. Verifique e mostre se é divisível por 2 e 3.
A=int(input("Digite um número: "))
if(A%6)==0:
print("SIM! É DIVISÍVEL POR 2 E 3")
elif(A%3)==0:
print("DIVISÍVEL SOMENTE POR 3")
elif(A%2)==0:
print("DIVISÍVEL SOMENTE POR 2")
else:
print("NÃO É DIVISÍVEL POR 2 OU 3") |
049a0c2190656397fe8a44f1fc56ef4364b664be | danilokevin/Lote-1---Python | /Lote 1/Ex25.py | 1,255 | 3.921875 | 4 | # Objetivo: Receba a hora inicial e final de um jogo (em horas e minutos). Calcule a duração do jogo sabendo que: Pode
# ter começado em um dia e terminado no outro, e a duração máxima é de 24 horas.
HI=int(input("Hora inicial do jogo: "))
MI=int(input("Minuto inicial do jogo: "))
HF=int(input("Hora final do jogo... |
b8bfd6660f9f4b1eefb4c8e2b34c21959414e7cb | danilokevin/Lote-1---Python | /Lote 1/Ex14.py | 241 | 3.796875 | 4 | # Objetivo: Receba 2 ângulos de um triângulo. Calcule e mostre o valor do 3º ângulo
a1=int(input("Valor do primeiro ângulo "))
a2=int(input("Valor do segundo ângulo "))
a3=180-(a1+a2)
print("O valor do terceiro ângulo é", a3) |
8e6ef217cfaae35fe1f4c603b33c7bce95e87c34 | danilokevin/Lote-1---Python | /Lote 1/Ex11.py | 227 | 3.5625 | 4 | # Objetivo: Receba o raio de uma circunferência. Calcule e mostre o comprimento da circunferência
raio=int(input("Qual o raio da circunferência? "))
circ=(raio*2)*3.14
print("O valor da circunferência é de", circ) |
fe66cf49408f028972af9e77c20db566718157c9 | abhayb443/PythonScripting | /Play with class objects and methods.py | 3,982 | 3.609375 | 4 |
"""
kirk = ["James Kirk", 34, "Captain", 2265]
spock = ["Spock", 35, "Science Officer", 2254]
mccoy = ["Leonard McCoy", "Chief Medical Officer", 2266]
class Dog:
# Class attribute
species = "Canis familiaris"
def __init__(self, name, age):
self.name = name
self.age = age
# Instanc... |
3d670997efade71895e51e0630c91c541929b036 | LuanFMelo/PPZPython | /classroom-exercises/TWP170 Fatorial.py | 467 | 3.765625 | 4 | #Calculem a média dos dez números
n = 1
soma = 0
while n <= 10:
x = int(input(f'{n} número: '))
soma = soma + x
n = n + 1
print(f'Média: {soma/10:.1f}')
#Contadores incremento constante
#Acumuladores variável
#Acumulador pode ser de produto
#fatorial de 10
#1 * 2 * 3 * ... * 9 * 10
############
... |
53f9bfd24b270ae354b517e6e6cec4cbdbb3dbc8 | LuanFMelo/PPZPython | /classroom-exercises/TWP150 Repetições imprimindo 1 até 3.py | 169 | 4.09375 | 4 | ##While interation##
#Use pythontutor.com to see step by step execution
x = 1 #Variable
while x <= 3: #Stop condition
print(x) #Action
x = x + 1 #Repeat block
|
a96e666a32c86321624bbf960657005a8a149685 | LuanFMelo/PPZPython | /list-of-exercises/Lista 1 - PPZPython/exercicio4.py | 266 | 3.765625 | 4 | salario_inicial=float(input('Digite o seu salário atual: '))
aumento=float(input('Qual a porcentagem de aumento? '))
aumento= (salario_inicial * aumento / 100)
print('O valor do aumento foi de: ', aumento)
print('O novo salário é: ', salario_inicial + aumento)
|
0b899b58d56e33ac2430b317ce1e73c2e0790da6 | hgm5361/TextCalculator | /Main.py | 4,830 | 4.34375 | 4 | """A text-based calculator program.
This program does several mathematical operations and prints the results."""
__version__ = '1'
__author__ = 'Hailey Merrifield'
def addition(x, y):
"""Adds x and y."""
return x + y
def subtraction(x, y):
"""Subtracts x and y."""
return x - y
def multiplication... |
a73d9e3938468f88fcf87c0ff928120779d2e65d | Antorojo1604/Ejercicjo2 | /Lista.py | 1,870 | 3.78125 | 4 | from Viajero import ViajeroFrecuente
import csv
class Lista:
___Lista=[]
def __init__(self):
self.__lista=[]
def agregarViajero (self, viajero):
self.__lista.append(viajero)
def testViajero (self):
archivo=open('D:/antonela/facultad/programaci... |
0161be485ecedd4e17fd86e5049d4ef2bea9191d | liyouzhang/Algos_Interviews | /sum_of_two_values.py | 1,254 | 4.375 | 4 | def find_sum_of_two_one(A, val):
'''
input - array of numbers; val - a number
output - bool
1. native:
- try all combinations of two numbers in array: 2 for loops
- for each, test if == target
'''
#1. naive approach
for a in A:
for b in A:
if b != a:
if a + b == val:
retur... |
50b40bb9f10c8abbe769296dea8d895e517ee13e | liyouzhang/Algos_Interviews | /819_most_common_word.py | 2,900 | 4.34375 | 4 | '''
Given a paragraph and a list of banned words, return the most frequent word that is not in the list of banned words. It is guaranteed there is at least one word that isn't banned, and that the answer is unique.
Words in the list of banned words are given in lowercase, and free of punctuation. Words in the paragr... |
7e1efffec2cc70ad5f71fc2cf866a16ff7e5d014 | lulumuts/Password-Locker | /locker-test.py | 1,553 | 3.890625 | 4 | import unittest #Importing the unittest module
from locker import User #Importing the class locker
class TestUser(unittest.TestCase):
'''
Test class that defines test cases for the user class behaviours.
Args:
unittest.TestCase: TestCase class that helps in creating test cases
'''
def setUp(s... |
d0446186eda33c4fc7a28cad1e80f67223799168 | mikebelanger/Sortify | /FolderManager.py | 4,791 | 3.796875 | 4 | import os
class File:
'''Gets extension, path, etc.'''
def __init__(self, full_file_path_name, extension=None, file_name=None, new_file_name = '', destination_path=''):
self.full_file_path_name = full_file_path_name
self.extension = extension
self.file_name = file_name
... |
edb646597e0e3c670bd710779b106a0cd53e2995 | lopez86/euler | /euler001_050/prob0038.py | 1,061 | 3.65625 | 4 | """ Solution to Project Euler #38
https://projecteuler.net
"""
import itertools
def pandigital_numbers():
#List of pandigital numbers as strings
pandigital = sorted( [ ''.join([str(b) for b in a]) for a in
itertools.permutations(range(1,10))],
reverse... |
0a576f397fdaceb668f9a183b9b3441fb160b131 | LiuMaoYang/opencv_notebook | /Python/pyramid.py | 1,468 | 3.96875 | 4 | #encoding:utf-8
import cv2
import numpy as np
import matplotlib.pyplot as plt
"""
pyramids can be used to accelerate coarse-to-fine search algorithms,
to look for objects or patterns at different scales,
and to perform multi-resolution blending operations
There are two kinds of Image Pyramids.
1) Gaussian Pyramid an... |
6d8a5852204d4addeffe1702178fa94073e999c9 | raul1rnjn535/Prep_Term | /Preparatory/Python/Lab1/Assignment1/14a.py | 119 | 3.9375 | 4 | x=int(raw_input())
if x>-1 and x<18:
print "child"
elif x>17:
print "adult"
else:
print "Invalid input!!!"
|
87ae2f7ef55554516cf8cdce8e1a57837533b3e8 | doraithodla/py101 | /learnpy3/word_freq_2.py | 783 | 4.15625 | 4 | # wordfreq2 - rewrite the wordfreq program to take the text from a file and count the words
def word_freq1(str):
"""
takes a string and calculates the word frequency table
:param str: string input
:return: frequency dictionary
"""
frequency = {}
for word in str.split():
if word in f... |
16ba194d28de4bf38a2764f173606bce7cde982b | doraithodla/py101 | /shapes.py | 282 | 4.28125 | 4 | from turtle import forward, right
def shape(sides,length):
for i in range(sides):
forward(length)
right(360/sides)
'''
length = int(input("Length: "))
sides = int(input("Number of sides:"))
'''
for sides in range(3,5):
shape(sides, 100)
|
7f7bc72b412846e06bf9b6b5a0c720a4bdc05798 | doraithodla/py101 | /learnpy5/dictionary.py | 2,124 | 4.625 | 5 | # Creating an empty Dictionary
Dict = {}
print("Empty Dictionary: ")
print(Dict)
# Creating a Dictionary
# with Integer Keys
Dict = {1: 'HP', 2: 'compaq', 3: 'dell'}
print("\nDictionary with the use of Integer Keys: ")
print(Dict)
# Creating a Dictionary
# with Mixed keys
Dict = {'Name': 'HP', 1: [1, 2, 3, 4]}
print(... |
d529ce658f479a159db9cc07057be296a7430631 | doraithodla/py101 | /string_manipulations/histogram.py | 251 | 4.09375 | 4 | s = input("Enter the string to remove duplicated from: ")
def remove_dup(list):
list2 = []
for elem in list:
if elem not in list2:
list2.append(elem)
return list2
print(remove_dup(s.split()))
print(set(s.split()))
|
4a0165488179d42b812833c3785396de14485717 | doraithodla/py101 | /pyData/write_csv.py | 346 | 3.671875 | 4 | import csv
def save_to_csv(links, filename):
"""
saves extracted data to a csv file
:param links: list of links
"""
csvFile = open(filename, 'w', newline='', encoding='utf-8')
csvWriter = csv.writer(csvFile)
csvWriter.writerow(["title", "link"])
for link in links:
csvWriter.wri... |
41b4bb8bda85667c76cc72387e98ef65fc4fd871 | doraithodla/py101 | /learnpy2/wordset.py | 328 | 4.125 | 4 | noise_words = {"if", "and", "or", "the", "add"}
def wordset(string):
"""
converts a list of words to a set
:param list: string input from the user
:return: set object
"""
string_set = set(string.split())
print(string_set)
print(noise_words)
wordset("a is a test to check the test of ... |
e63c1eb18d0ac5b181b8974b1bacbb378e7e34a7 | saisunillinusias/account-manager | /main.py | 1,689 | 3.59375 | 4 | from tkinter import *
import tkinter
import sqlite3
import os
from tkinter.ttk import LabeledScale
win=tkinter.Tk()
win.title("Account Log")
win.geometry("500x500")
def show():
LabeledScale.config( text = clicked.get() )
# Dropdown menu options
options = [
"Google",
"Facebook",
"tw... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.