blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
acb22f0030401ef8656f539f7662107996fcf4f8 | salupsjr/cursoPythonGuanabara | /Exercicios/ex30Aula10.py | 150 | 4.125 | 4 | num = int(input('Digite um número: '))
print("\nO número {} é PAR.".format(num) if num % 2 == 0 else "\nO número {} é IMPAR.".format(num, num))
|
2d2a19cffe383c51d971a1ddb443c7840d8856f1 | salupsjr/cursoPythonGuanabara | /Exercicios/ex48aula2M2.py | 184 | 3.71875 | 4 | soma = 0
quant = 0
for c in range(1, 501, 2):
if c % 3 == 0:
soma += c
quant += 1
print('A soma de todos os {} valores solicitados é de {}.'.format(quant, soma)) |
d1fe5424ae6f692acf340c0ce56cac2c0416f473 | salupsjr/cursoPythonGuanabara | /Exercicios/ex56aula2M2.py | 793 | 3.609375 | 4 | somaIdade = 0
mIdade = 0
nmVelho = ''
totMF = 0
p = int(input('Quantas pessoas deseja cadastrar? R: '))
for c in range(1, p+1):
print('DADOS DA {}ª PESSOA'.format(c))
nome = str(input('Digite o nome:')).strip()
idade = int(input('Digite a idade:'))
sexo = str(input('Digite o sexo [M / F]:')).strip().upp... |
744df7ff1e1d2b26b4eebeab558b9f1e0b9fd8aa | salupsjr/cursoPythonGuanabara | /Exercicios/desafio15Aula7.py | 751 | 3.796875 | 4 | #-*-coding:utf8;-*-
#qpy: console
#Escreva um programa qua pargunta a
#quantidada da Km parcorridos por um
#carro alugado e a quantidada de dias
#pelos quais ele foi alugado.
#Calcule o preço a pagar.
#sabando que o carro custa RS60 por dia
# a RS0.15 por Km rodado.
qtdKm = float(input ('Quantos quilômetros for... |
55a29267be71e10638c8bb12146200f6c9a2ac9e | davidbeg/EulerProject | /euler37.py | 1,100 | 3.65625 | 4 | from math import floor, sqrt
def is_prime(x):
if x < 2:
return False
for i in range(2, floor(sqrt(x)) + 1):
if x % i == 0:
return False
return True
selected = set()
primes = set()
for i in range(10, 10 ** 6):
if len(selected) == 11:
break
good_trucations = []
... |
71ef1c6c1088711f07f0bdac3c066b0b73ea5731 | davidbeg/EulerProject | /euler58.py | 411 | 3.78125 | 4 | import math
def is_prime(x):
for i in range(2, math.floor(math.sqrt(x)) + 1):
if x % i == 0:
return False
return True
x = 1
total = 1
iteration = 1
primes = 0
while primes / total >= (.1 if x > 1 else 0):
for _ in range(4):
x += 2 * iteration
if is_prime(x):
... |
3f37d64b34a17a6d289f79efb00b7635383553bc | davidbeg/EulerProject | /euler61.py | 1,519 | 3.609375 | 4 | from math import sqrt
def is_triangle(n):
return (sqrt(1 + 8 * n) - 1) % 2 == 0
def is_square(n):
return sqrt(n) % 1 == 0
def is_pentagonal(n):
return (sqrt(1 + 24 * n) + 1) % 6 == 0
def is_hexagonal(n):
return (sqrt(1 + 8 * n) + 1) % 4 == 0
def is_heptagonal(n):
return (sqrt(9 + 40 * n) +... |
c1cce25f8a38f7e6e0bbfff2fdbb7b9b15dba065 | Wijantra/unittesting-Wijantra | /fraction_test.py | 6,311 | 4.15625 | 4 | import math
import time
import unittest
from fraction import Fraction
class FractionTest(unittest.TestCase):
"""Test the methods and constructor of the Fraction class. """
def test_str(self):
f = Fraction(3, -1)
self.assertEqual("-3", f.__str__())
f = Fraction(0, 5)
self.asser... |
54f47e2196d8742a70a7476fc8658a1941b7cebd | nchibana/DS-Unit-3-Sprint-1-Software-Engineering | /module4-software-testing-documentation-and-licensing/employee_class_test.py | 632 | 3.875 | 4 | import unittest
from class_example import Employee, Teacher
class EmployeeTest(unittest.TestCase):
def test_name(self):
employee_test1 = Employee('Test', 'User', 60, 20)
self.assertEqual(employee_test1.fullname(), 'Test User')
def test_salary(self):
employee_test2 = Employee('Amanda',... |
5dc714e184f66e234cfae1e49f541867479ec618 | premkashyap/PythonTrilogyPluralsight | /PythonGettingStarted/Module8/generators.py | 634 | 3.6875 | 4 | def gen123():
yield 1
yield 2
yield 3
g = gen123()
print(next(g))
print(next(g))
print(next(g))
for i in gen123():
print(i)
def take(count, iterable):
counter = 0
for item in iterable:
if counter == count:
return
counter +=1
yield item
def distinct(iterab... |
41de945927dfb327917816a06477c8fab882538c | premkashyap/PythonTrilogyPluralsight | /PythonGettingStarted/Module6/dict.py | 612 | 3.75 | 4 | dict1 = {'prem':'kashyap', 'anita':'gautam'}
dict2 = [('Prem', 'Kashyap'),('Anita', 'Gautam')]
dict3 = dict(prem='kashyap', anita = 'gautam')
dict4 = dict1.copy() #2 methods of shallow copying the dictionary
dict5 = dict(dict2)
dict1.update({'anil':'kaushik', 'pawan':'mourya'})
print(dict1)
for d in dict1:
print(d,... |
e3c8721e5324789892e145d341cb20d4b4e53938 | premkashyap/PythonTrilogyPluralsight | /PythonGettingStarted/Module7/exception.py | 989 | 3.59375 | 4 | import sys
import os
def convert_to_int(x):
try:
i = int(x)
return i
except (ValueError, TypeError) as e:
print("Conversion Failed {}.".format(str(e)), file=sys.stderr)
#raise #to re raise the exception
def sqrt(x):
if x < 0:
raise ValueError("Can't find the square ... |
eb9597f0ce37b1adf01fdb129104731a5a267a50 | ankigupt0000/UVA_online_judge | /ComputationalGeometry/11479/11478-IsThisTheEasiestProblem.py | 536 | 3.640625 | 4 | if __name__ == "__main__":
n=int(input())
for i in range(n):
a,b,c=map(int,input().split())
print("Case ",i+1,": ",end="",sep="")
if(a<=0 or b<=0 or c<=0):
print("Invalid", sep="")
elif((a+b)<=max(a,b,c) or (b+c) <= max(a,b,c) or (c+a) <=max(a,b,c)):
print... |
c5f5b8263f5c47d3124ec4d751cd8fc0f2eb95bb | greenbender/aoc | /2015/day05/solve.py | 961 | 3.609375 | 4 | import sys
strings = [l.strip() for l in sys.stdin]
def nice1(string):
vowels, double = 0, False
for i in range(len(string)):
if i > 0:
if string[i-1:i+1] in ('ab', 'cd', 'pq', 'xy'):
return False
if not double and string[i-1] == string[i]:
do... |
898a5b030e5b496c7b29ca4409f82f3f741964f0 | greenbender/aoc | /2020/day10/solve.py | 2,040 | 3.84375 | 4 | import sys
adapters = list(sorted(map(int, sys.stdin)))
adapters.append(adapters[-1] + 3)
def combos(s):
'''Get number of combinations for given list of sequential adapters when
one or two adapters is removed, then perform the same operation recursively
for each subset of sequential adapters that can be... |
e2ad78f57e45e75b40dcb491436a27a3d27b48a7 | cezcub/banking | /bank.py | 6,113 | 3.828125 | 4 | import string
from random import choice
import time
import json
from accounts import Account, Checking, Savings
import constants
nums = []
mylist = []
usernames = []
# Read file for account info
with open(constants.filename , "r") as file2:
length = len(file2.readlines())
file2.seek(0)
for i i... |
35afbce36cbd240f0c5a689669a6d2e934629bd6 | swiddiws/pyBible | /cinema.py | 846 | 4.40625 | 4 | films = {
"Shrek":[3,2],
"Bourne":[17,2],
"Kids":[17,2],
"Dumbo":[3,2]
}
while True:
choice = input("What film would you like to watch? ").strip().title()
if choice in films:
# pass # tells the program to just pass this section by
age = int(input("How old are you? ").strip... |
79b4d0d998563d54b27c3c439849afd271010af1 | swiddiws/pyBible | /functionplay.py | 2,230 | 4.5 | 4 | # functions and creating them
# simple add function example
#def add(x,y):
# return = x + y
# reverse function
#def rev(text):
# return text[::-1]
# Global Variable, make sure scopes do NOT overlap
a = 100
def f1():
# Local Variable, which are destroyed when function is finished
b = 90
b = b + a
... |
07c0c5e0faab60f784920b3d08648497cd1b4d3b | wlgud0402/pyfiles | /function_fibo_global.py | 497 | 4.0625 | 4 | #global 키워드>> 외부의 변수 설정한 값을 가져옴
#사용법 global 변수이름
counter = 0
def fibonacci(n):
print("fibonacci({})을 구합니다".format(n))
global counter
counter += 1
if n == 1:
return 1
if n == 2:
return 1
else:
return fibonacci(n-1) + fibonacci(n-2)
print(fibonacci(10))
print("fibonacci(1... |
00645012284567ffd878570734bb529e4a2410b3 | wlgud0402/pyfiles | /if_elif.py | 612 | 3.703125 | 4 | #세개 이상의 조건을 연결하는것 >>>elif if조건문과 else 구문 사이에 입력한다
# if 조건A:
# 조건A가 참일때 실행
# elif 조건B:
# 조건B가 참일때 실행
# elif 조건C:
# 조건C가 참일때 실행
# .
# .
# .
# else:
# 모든조건이 거짓일때 실행
import datetime
now = datetime.datetime.now()
month = now.month
if 3<= month <=5:
print("현재는 봄입니다")
elif 6<= month <=8:
... |
5e9cec6bd03e819abd3fde15bab800121c170d54 | wlgud0402/pyfiles | /module_import_random.py | 956 | 3.765625 | 4 | #random모듈>>>랜덤한 값을 생성해줌
import random
print(random.random()) #그냥 import random 했을시 random모듈의 random 을 호출해야함
#그러므로 print(rando())이 불가능하다
print(random.uniform(2.5,10.0)) #random float: 2.5 <=x <10.0
print(random.expovariate(1/5)) #interval between arrivals averaging 5 second... |
bf343caefe4aaf794dc283dd8ac3520fe4450bdc | wlgud0402/pyfiles | /string_problem.py | 1,158 | 4.125 | 4 | #문자열 사이에 공백이 문자로 인식되는 경우를 막기 위한 해결방법
test = (
"이렇게 입력해도 "
"하나의 문자열로 연결되어 "
"생성됩니다."
)
print(test)
#\n은 마지막 줄에는 붙이지 않습니닸!!!!!
number = int(input("정수입력>>"))
if number % 2 == 0:
print(("입력한 문자열은 {}입니다.\n"
"{}는 짝수입니다."
).format(number, number))
else:
print(("입력한 문자열은 {}입니다.\n"
"{}는 홀수입니다."
... |
fe0284790170fa35ea9b559069f0d5510c268171 | wlgud0402/pyfiles | /function_fibo_early_return.py | 694 | 3.984375 | 4 | #조기 리턴
dictionary = {
1:1,
2:2
}
def fibonacci(n):
if n in dictionary:
return dictionary[n]
else:
output = fibonacci(n-1) +fibonacci(n-2)
dictionary[n] = output
return output
print(fibonacci(10))
#사용후 줄어들은 들여쓰기 else 제거됨
dictionary_early = {
1:1,
2:2
}
def fibonacc... |
66bcb0a55f39f6dd30c2946981e4164c3346899e | wlgud0402/pyfiles | /function_fibonacci.py | 272 | 3.6875 | 4 | #재귀함수를 이용한 피보나치 수열 구하기 232p
#토끼 번식 문제
def fibonacci(n):
if n == 1:
return 1
if n == 2:
return 1
else:
return fibonacci(n-1) + fibonacci(n-2)
#시간이 오래걸렸다
print(fibonacci(7))
|
2c886c98a586fd5fb1509a0660f41cebe0611c55 | wlgud0402/pyfiles | /function_use.py | 581 | 4.15625 | 4 | #기본 함수의 활용
#일반적으로 값을 만들어 리턴하는 형태로 많이 쓰임
def sum_all(start, end):
output = 0
for i in range(start , end+1):
output += i
return output
print(sum_all(2, 5))
print()
print()
#키워드 매개변수를 사용해서 (?, ?, ?) range에서 세번째인자는 범위사이의 차이값
def sum_all2(start=0, end=100, step=1):
output2 = 0
for i in ran... |
e7be94d1ddd699d1667ee6486bc6b032cc210001 | wlgud0402/pyfiles | /d/d.py | 564 | 3.546875 | 4 | #BeautifulSoup 모듈로 날씨 읽어오기 >>>크롤러
from urllib import request
from bs4 import BeautifulSoup
print(bs4)
# target = request.urlopen("http://www.weather.go.kr/weather/forecast/mid-term-rss3.jsp?stnId=108")
# soup = BeautifulSoup(target, "html.parser")
# for location in soup.select("location"):
# print("도시:", locat... |
a97a11c9e7d39120ba5b6bfc8783132463d97946 | wlgud0402/pyfiles | /tuple_lambda4.py | 233 | 3.515625 | 4 | #인라인 람다 >>>>람다를 함수의 매개변수에 바로 넣음
list_input_a = [1,2,3,4,5]
output_a = map(lambda x:x*x, list_input_a)
print(list(output_a))
output_b = filter(lambda x:x<3, list_input_a)
print(list(output_b)) |
82b0f01d404e7bcd74065c7cb146d53b22969e3b | surajjagadeesh/projects | /DijkstraMaze/GridProblem/point.py | 1,099 | 3.9375 | 4 | #Basic point class with a comparable, toString, and a function to check if
#it is a valid point given a size of a square grid.
#@author: Suraj Jagadeesh
#@version: 6/22/2017
class Point:
#Constructor, takes x and y values
#@param value: A list with two indices, the first being the x value, the
#second bein... |
cfabf1a04e0eecfd485d615ae26e98640c7ecb4d | VinceSJ/coding_challenge_rm | /q1/q1b.py | 6,217 | 4.5625 | 5 | #!/usr/bin/env python3
# Should work fine with python2 as well, but testing and development was done in 3.
# Q1b
# Given a list of positive numbers, write a function that prints the following
# "fizz" if number is divisible by 3
# "buzz" if number is divisible by 5
# "fizzbuzz" if number is divisible by 3 and 5
#
# Do... |
b0c09e31b5765921eab7e87a1bbb033c9995dc3f | box/rotunicode | /rotunicode/rotunicode.py | 3,777 | 3.796875 | 4 | # coding: utf-8
from __future__ import unicode_literals
import codecs
import six
class RotUnicode(codecs.Codec):
"""
Codec for converting between a string of ASCII and non-ASCII chars
maintaining readability.
>>> codes.register(RotUnicode.search_function)
>>> 'Hello Frodo!'.encode('rotunicode')
... |
06ed218eb62922f576871ee6e6f49aa3b98800f9 | Dawid12/Pacman2d | /Move.py | 459 | 3.640625 | 4 | import Enums
class Move:
def __init__(self, x, y):
self.x = x
self.y = y
@classmethod
def initWithDirection(cls, direction):
if direction == Enums.Direction.Up:
return cls(0, -5)
elif direction == Enums.Direction.Down:
return cls(0, 5)
elif dir... |
d9f55780bce84856e41b7290855a8709fc1708ad | aakash7781/machine-learning | /simple linear regression (basic implementation).py | 568 | 3.640625 | 4 | import matplotlib.pyplot as plt
import matplotlib.style as style
import numpy as np
x=np.array([1,2,3,4,5,6,7,9,10])
y=np.array([6,5,10,12,13,14,21,23,24])
mc=0
bc=0
n=5
lr=0.01
itr=100
yp=np.array([])
def plot() :
style.use("ggplot")
plt.scatter(x, y, marker="o")
plt.plot(x, yp, color="g")
... |
83533555ff9facae90eab0324ddfcc4d86833ed0 | Sijango/sandbox_py | /hard_enlarge.py | 891 | 3.953125 | 4 | #Задача заключается в том, что нужно реализовать функцию enlarge, которая увеличивает переданное "изображение"
#в два раза: каждый "пиксель" удваивается по горизонтали и вертикали. Изображением служит список строк, а пиксели в нём — символы строк.
curry = lambda f: lambda x: lambda y: f(x, y)
compose = lambda f: lamb... |
9841257be2ead44dc19879815dedd32c54f342ed | Sijango/sandbox_py | /transposed.py | 355 | 3.828125 | 4 | # Транспонирование матриц
def transposed(matrix):
len_of_x = len(matrix)
len_of_y = len(matrix[0])
trans_matrix = []
for y_items in range(len_of_y):
temp = []
for x_items in range(len_of_x):
temp.append(matrix[x_items][y_items])
trans_matrix.append(temp)
return trans_matrix
print(transposed([[1, 2], [3, ... |
fbee095a90e018b181fcfa829a615fb974c55d12 | Sijango/sandbox_py | /Test1.py | 324 | 3.828125 | 4 | def fib(number):
first = 0
second = 1
index = 2
if number and index <= number:
while index <= number:
result = first + second
first = second
second = result
index += 1
return result
elif number == 1:
return 1
else:
return 0
print(fib(3))
print(int('1000', 2))
result = format(8, 'b')
print(res... |
e716d3bf3427dbb947fa995556d0b352a3f13c03 | EvanBudin/hello | /.vscode/kinter.py | 374 | 3.5 | 4 | from tkinter import *
root = Tk()
root.geometry("800x400")
def fuckOff():
print("Fuck Off")
myEntry = Entry(root, width= 5)
myLabel1 = Label(root, text= "Hello World")
myLabel2 = Label(root, text= "Twinkle Twinkle Asshole")
myButton = Button(width=10,height=4,text= "Press Me", command= fuckOff)
myEntry.grid(row=0,c... |
08193a2285cb0edff21fdf195f30088be1142a80 | EvanBudin/hello | /.vscode/wordChanger.py | 367 | 3.796875 | 4 | input1 = input("Enter First Word: ")
input2 = input("Enter Second Word: ")
counter = 0
print(input1)
print(input2)
if len(input1) == len(input2):
while input1 != input2:
input1 = list(input1)
input2 = list(input2)
input1[counter] = input2[counter]
counter = counter + 1
print(input1... |
3aa84bea28989346c2bd22a70cc2bd5e0d490ca4 | EvanBudin/hello | /.vscode/rollerGUI.py | 1,017 | 3.84375 | 4 | import random
from tkinter import *
def getBoth():
counter = 0
diceAnswer = diceEntry.get()
typeAnswer = typeEntry.get()
diceAnswer = int(diceAnswer)
typeAnswer = int(typeAnswer)
myList = []
while counter < diceAnswer:
myList.append(random.randint(1,typeAnswer))
counter = cou... |
94ca95a333f338f8d357159275657bf8702274bc | Ni4ka1991/funcLengthDirection | /funcLengthDirection.py | 431 | 4.09375 | 4 | #!/usr/bin/env python3
from os import system
from sys import argv
length = int( argv[1] )
direction = argv[2]
system( "clear" )
def drawLine( length, direction ):
if( direction == "h"):
print( "-" * length )
elif( direction == "v" ):
for i in range( length ):
print( "|\n" )
else:
p... |
2497e350dbe6b76bdef5d1640480421d7b1ee26f | divyam02/SCMP-M2019 | /HW_3/problem_1_a.py | 2,448 | 3.75 | 4 | import numpy as np
from numpy.linalg import norm
from numpy.linalg import solve
import matplotlib.pyplot as plt
def gen_hilbert_matrix(n):
"""
# Generate Hilbert matrix with entries
"""
temp = np.ones(shape=(n, n))
for i in range(n):
for j in range(n):
temp[i, j] = 1/(i+j+1)
# Change hilbert matrix entry... |
e86eda6550658198ee8e27c9889bde043f18629a | bledidalipaj/hackerrank | /maximum_element.py | 1,983 | 4.0625 | 4 | """
You have an empty sequence, and you will be given N queries. Each query is one of these three types:
1 x -Push the element x into the stack.
2 -Delete the element present at the top of the stack.
3 -Print the maximum element in the stack.
Input Format
The first line of input contains an integer, N. T... |
084a7547ac9c7b9cd35addc67ab5deb9fe707129 | bledidalipaj/hackerrank | /validate_email_addresses.py | 1,791 | 4.34375 | 4 | # You are given an integer N followed by N email addresses. Your task is to print a list containing only valid email addresses in
# lexicographical order.
# Valid email addresses must follow these rules:
# It must have the username@websitename.extension format type.
# The username can only contain letters, digits, ... |
e444fdb5a2e69a04a66b3df43d1ecf98aab8acc2 | agarwalmani/Computer-Vision | /Resize.py | 495 | 3.53125 | 4 | # Program to resize a image.
# Author:- Mani Agarwal
# Email:- maniagarwal@jklu.edu.in
import cv2
img=cv2.imread("Taylor1.jpg",1) # 1 is for coloured image.
img_1=cv2.imread("Taylor1.jpg",0) # 0 is for converting the image into gray.
resized_image=cv2.resize(img,(400,400)) # For resizing the image
c... |
c1505921c96981b3085b40347cbe56bdd22c78c2 | ordepdev/problems | /python/mergeSort.py | 610 | 3.84375 | 4 | def merge(left, right, lt):
result = []
i, j = 0, 0
while i < len(left) and j < len(right):
if lt(left[i],right[j]):
result.append(left[i])
i += 1
else:
result.append(right[j])
j += 1
while i < len(left):
result.append(left[i])
i += 1
while j < len(right):
result.append(right[j])
j += 1
pr... |
5ea43692606f5b459215a61d125575ead7c89a4e | kbrakke/PowerGridSim | /board_setup_class.py | 8,502 | 3.828125 | 4 | import pprint
import matplotlib.pyplot as plt
import networkx as nx
import random
""" this file would contain all the functions to create a random playing board given the continent and number of players.
so given either north america or europe and the number of players it will randomly choose the right number of ... |
4afcd427102b67f50f4ef92556f59700a9048cc1 | jasonku/Project-Euler | /src/022.py | 885 | 3.96875 | 4 | '''
Using names.txt (right click and 'Save Link/Target As...'), a 46K text file containing over five-thousand first names, begin by sorting it into alphabetical order. Then working out the alphabetical value for each name, multiply this value by its alphabetical position in the list to obtain a name score.
For example... |
093c6f3756aa4289fb058369b0db8ea205946dec | jasonku/Project-Euler | /src/020.py | 384 | 4.03125 | 4 | '''
n! means n x (n ? 1) x ... *3*2*1
Find the sum of the digits in the number 100!
'''
from util import *
def main():
return sumDigits(factorial(100))
# return sumDigits(93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000... |
269939dd331e6ed6e49f6ce0ba9c70f0a467f4ea | jasonku/Project-Euler | /src/035.py | 718 | 3.90625 | 4 | '''
The number, 197, is called a circular prime because all rotations of the digits: 197, 971, and 719, are themselves prime.
There are thirteen such primes below 100: 2, 3, 5, 7, 11, 13, 17, 31, 37, 71, 73, 79, and 97.
How many circular primes are there below one million?
'''
from util import *
def rotate(str):
... |
1b17e706f1a6a96c4b7d10a5ee76e4613ab0e87e | JoLuMTavares/Python | /kata27.py | 6,334 | 3.953125 | 4 | """
++++++++++++++++ Back to Python ++++++++++++++++
**************** Binary Tree. This time it's the main exercise.
Definition: According to Wikipedia, a complete binary tree is a binary tree "where every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as ... |
fd25856a9317a907b8f4e116b5697e055e5335ba | JoLuMTavares/Python | /kata5.py | 5,849 | 4.1875 | 4 | """
In this kata, you must create a digital root function.
A digital root is the recursive sum of all the digits in a number. Given n, take the sum of the digits of n. If that value has more than one digit, continue reducing in this way until a single-digit number is produced. This is only applicable to the natural nu... |
8289d8873ac84125c8c59bb10e282a89ef945960 | ywyogesh0/python-project | /Python-Files/raw_input.py | 529 | 4.03125 | 4 | names = input('Enter Names : ').title().split(",")
assignments = input('Enter Assignments Count : ').split(",")
grades = input('Enter Grades : ').split(",")
for name, assignment, grade in zip(names, assignments, grades):
message = "Hi {},\n\nThis is a reminder that you have {} assignments left to \
submit before yo... |
3cd9a191db55a4133727bb0cc555dd92c6fd321d | sylwia95u/Moje-projekty | /kalkulator.py | 835 | 3.640625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Dec 28 18:41:56 2019
@author: Sylwia Urban
"""
def dodawanie(x, y):
return x + y
def odejmowanie(x, y):
return x - y
def mnożenie(x, y):
return x * y
def dzielenie(x, y):
return x / y
num1 = float(input("Wprowadź pierwszą liczbę: "))
num2 = float... |
bc8971cf6db71c8d6b67c620023ec14f1a9da824 | Krish-Mahajan/DataStructures | /Python/Geek/binarytree/binary_tree.py | 15,819 | 3.59375 | 4 | from __future__ import annotations
from typing import List, Set, Dict, Tuple, Optional
import sys
class Node(object):
'A node class to represent individual Node'
def __init__(self, item:Optional[int]=None)->None:
if item is not None:
self.__key = item
self.__parent = self.__le... |
7c9b1b2aa350c208270d61efd3c2b55696179bb9 | Krish-Mahajan/DataStructures | /Python/Geek/sorting/quick_sort.py | 1,085 | 3.8125 | 4 | from __future__ import annotations
from typing import List, Set, Dict, Tuple, Optional
import sys
class QuickSort(object):
def sort(self,arr:List[int])-> List[int]:
return self.__sort_util(arr,0,len(arr)-1)
def __sort_util(self,arr:List[int],low:int,high:int) -> List[int]:
if ( low < hig... |
0eb022d1b83731d3daf8b35263c95e78502f3280 | Krish-Mahajan/DataStructures | /Python/Geek/linklist/link_list.py | 5,949 | 3.9375 | 4 | from __future__ import annotations
from typing import List, Set, Dict, Tuple, Optional
import sys
class Node(object):
'''Node class to represent node of a linkList'''
def __init__(self,data:int,next:Node=None,prev:Node=None)->None:
self.data = data
self.next = next
self.prev = prev... |
2c7a0283de7d7441a34ab428241e0ccd77c975a1 | BrianCodeItUp/python-practice | /image_proccess/jepg_to_png_convetor.py | 556 | 3.640625 | 4 | from sys import argv
from os import *
from PIL import Image
# grab first and second arguments
image_folder = argv[1]
output_folder = argv[2]
# create folder to put converted images
if not path.exists(output_folder):
mkdir(output_folder)
print("Directory " , output_folder , " Created ")
for filename in listd... |
f8bcc4b0aff1cc792c25c16e64fe8766f3a33896 | fernando44/Estudando-Python | /atividades01/Exercicio04/Exercicio04.py | 148 | 4.03125 | 4 | var1 = int(input('Digite um número: '))
print('Analizando o valor {}, seu antecessor é o {} e o seu sucessor é {}'.format(var1, var1-1, var1+1))
|
007b19e1f941ae17676e8f3ec91ff7a2b740d86e | HollowJH/Tic-Tac-Toe | /Tic-Tac-Toe/task/tictactoe/tictactoe.py | 1,720 | 3.796875 | 4 | game = [[" ", " ", " "], [" ", " ", " "], [" ", " ", " "]]
count = 0
def show():
print("---------")
print("|", " ".join(game[0]), "|")
print("|", " ".join(game[1]), "|")
print("|", " ".join(game[2]), "|")
print("---------")
def check():
x = list("".join(game[0] + game[1] + game[2]))
if x... |
212c6b319e1777e97e9cba1117dff115489423de | stephenmkbrady/DataStructs-Algorithms | /Basic Algorithms/complete_PlacingParantheses.py | 1,563 | 3.515625 | 4 | # Uses python3
import math
def evalt(a, op, b):
if op == '+':
return int(a) + int(b)
elif op == '-':
return int(a) - int(b)
elif op == '*':
return int(a) * int(b)
else:
assert False
def get_max_value(dataset):
operators = []
numbers = []
for i in dataset:
... |
65900894d1aa2f1022b122d9eb3113b91424fbea | stephenmkbrady/DataStructs-Algorithms | /Basic Algorithms/complete_FibLast.py | 194 | 3.703125 | 4 | #python3
n = int(input())
def lastFib(n):
fibArray = [0,1]
for i in range(2,n+1):
fibArray.append((fibArray[i-1] + fibArray[i-2])%10)
return fibArray[-1]
print(lastFib(n)) |
7fcff1327a169a6e37649221cac90b9d943c629a | FonziePants/adventofcode | /solutions/day21/day21.py | 5,069 | 3.734375 | 4 | def read_data(file_path,debug=True):
file = open(file_path, "r")
recipes = []
ingredients = {}
allergens = {}
for line in file:
if not line.rstrip():
continue
recipe = Recipe(line.rstrip())
recipes.append(recipe)
for ingredient in recipe.ingredients:
... |
cb67ecf87ce57312f6dc3e1d7ddbec3ea5475a9a | FonziePants/adventofcode | /solutions/day16/day16.py | 4,280 | 3.5 | 4 | class Field:
def __init__(self, line):
parts = line.split(": ")
self.name = parts[0]
self.values = []
value_ranges = parts[1].split(" or ")
for value_range in value_ranges:
halves = value_range.split("-")
for i in range(int(halves[0]),int(halves[1])+1)... |
72df4b4c34e0f89be2fc4c7662ad4e63a47a85b3 | FonziePants/adventofcode | /solutions/day18/day18.py | 3,970 | 3.703125 | 4 | def read_data(file_path,debug=True):
file = open(file_path, "r")
data = []
for line in file:
if not line.rstrip():
continue
data.append(line.rstrip().replace(" ",""))
file.close()
if debug:
print(data)
return data
def evaluate_expression(problem, deb... |
b7e5abd431341eff486c96446b396c6b513be5d4 | DiBoS290699/Numerical-method | /Lab_2/Lab_2.py | 3,336 | 3.5625 | 4 | import numpy as np
import matplotlib.pyplot as plt
"""
f1: cos (x + 0.5) - y - 2 = 0
f2: sin y - 2x - 1 = 0
"""
zero = np.zeros(2) # вектор нулей (0, 0)
"""Создаётся и возвращается система из двух функций в конкретной точке"""
def function(x):
# x, y = x[0], x[1]
return np.array([(np.cos(x[0] + 0.5) - x[1]... |
d74dbbb2ca790b6978756d0679c8745d8d9e60dd | estraviz/exercism | /python/leap/leap.py | 291 | 3.75 | 4 | def leap_year(year):
if is_divisible_by(year, 400):
return True
elif is_divisible_by(year, 100):
return False
elif is_divisible_by(year, 4):
return True
else:
return False
def is_divisible_by(number, amount):
return number % amount == 0
|
4f73d59802aa94159d607701960f233fcaed0217 | Cornejo99/Tarea_03 | /trabajador.py | 700 | 3.765625 | 4 | #Ricardo Cornejo Lozano
#Calcula el pago de un trabajador conforme a sus horas de trabajo.
def hnormal(horas):
total =(pago*horas)
return total
def hextra(horas2):
adicional = (pago*.75)
total1 = ((adicional+pago)*horas2)
return total1
def main():
global pago
horas = int(inp... |
83372534f0663bbaeddea7e1357906685d5dd966 | cglorsung/NNPlayground | /XOR.py | 1,675 | 3.53125 | 4 | # Author : Conor Lorsung
# Purpose: This project is simply a neural network playground
# for me to learn more about building neural networks,
# their implementations, and their strengths/weaknesses
import numpy as np
# Number of iterations of training
iterations = 1000
# Logistic sigmoid function
... |
f5d9fdce4d3794e4a41731c56fb63a69fa0e909c | GMSANTANA/desafiosPython | /Desafio02.py | 298 | 3.78125 | 4 | # Armazenar uma string 'exemplo ' em uma variavel com espaço em branco, depois exibir
# o resultado na tela
nome = 'exemplo '
print(nome.rstrip()) # para a direita
nome2 = ' exemplo'
print(nome2.lstrip()) # para a esqueda
nome3 = ' exemplo '
print(nome3.strip()) # para ambos os lados
|
8929d878c0136e2e0766c686cfcd59c1bfb61db8 | GMSANTANA/desafiosPython | /desafio10.py | 284 | 4.1875 | 4 | # Mostre o ultimo elemento da lista, passando a posição de forma negativa e explique .
lista = ['motos', 'carros', 'barcos', 'aviões']
print(lista[-1])
#coloquei o " -1 " para chamar o ultimo elemento da lista e assim se colocar '-2' chama o penultimo e assim por diante
|
ea6fc0292f1e0d6cae5d8360348851308d9827c2 | aronmalkine/chess.py | /board.py | 3,405 | 3.625 | 4 | # board.py
import curses
import pieces
import history
class Square(object):
_board = None
_x = 0
_y = 0
_horiz = None
_vert = None
piece = None
def __init__(self, board, x, y):
self._board = board
self._x = x
self._y = y
self._horiz = self._board.x_values[x]
self._vert = s... |
f4918f1e3f7fa6ef97a698a437b94bbc9211c3fb | srivishnu36/RPSLS-and-DateTime | /rpsls.py | 1,858 | 3.921875 | 4 | import random
import sys
def nametonumber(name):
if(name=="rock"):
return 0
elif(name=="spock"):
return 1
elif(name=="paper"):
return 2
elif(name=="lizard"):
return 3
elif(name=="scissors"):
return 4
else:
return False
def nu... |
b1252b356cf8683501c6ea754aa4ff1730004f12 | opencv/open_vision_capsules | /tools/openvisioncapsule_tools/command_utils.py | 571 | 3.546875 | 4 | import sys
from argparse import ArgumentParser
by_name = {}
"""A dict that maps command names to their corresponding function"""
def command(name):
"""A decorator that associates command functions to their command name."""
def wrapper(function):
by_name[name] = function
return wrapper
def sub... |
cca8d7524c3368292b38ca57e9289977cd168fa2 | opencv/open_vision_capsules | /vcap/vcap/caching.py | 561 | 3.65625 | 4 | def cache(method):
"""Caches the result of a method call. Caches are specific to the instance
of the object that this method is for.
"""
def on_call(self, *args, **kwargs):
name = method.__name__
try:
return self._cache[name]
except AttributeError:
# Crea... |
d97ccc07bc0c89c29721822f0795cf3f6b7b0f46 | franciellelopes/TrabalhoDSOO | /tela/abstract_tela.py | 2,053 | 3.8125 | 4 | from abc import ABC, abstractmethod
import os
class AbstractTela(ABC):
@abstractmethod
def __init__():
pass
def le_numero_inteiro(self, mensagem: str, opcoes_validas: []):
while True:
valor_lido = input(mensagem)
try:
inteiro = int(valor_lido)
if len(opcoes_validas) > 0 and ... |
f76031917f8b4eb6d4d15f017d83ee27143e8014 | Matt-Hurd/42-mod1 | /parse_file.py | 683 | 3.5625 | 4 | import sys
import re
def parse_file(inputfile):
try:
with open(inputfile, 'r') as f:
points = []
for line in f.readlines():
group = []
for point in line.strip().split(' '):
m = re.match("^\(([0-9]+),([0-9]+),([0-9]+)\)$", point)
... |
7d24966fcc24534063554395be16021816f8b2c4 | amandanagai/bootcamp_prep | /dictionary_solutions.py | 711 | 3.65625 | 4 | {tup:job for tup, job in [("name", "Elie"), ("job", "Instructor")]}
states = dict(zip(["CA", "NJ", "RI"],["California", "New Jersey", "Rhode Island"]))
vowels_values = {}
vowels = ["a", "e", "i", "o", "u"]
for item in vowels:
vowels_values[item] = 0
# OR:
{item:0 for item in ["a", "e", "i", "o", "u"]}
dict(zip(... |
5b807e55ca372f5cba3687249265236a733031f1 | amandanagai/bootcamp_prep | /list_comprehesion_solution_py1.py | 664 | 3.5 | 4 | [print(val) for val in [1,2,3,4]]
[print(val*20) in [1,2,3,4]]
[person[0] for person in ["Elie", "Tim", "Matt"]]
[number for number in [1,2,3,4,5,6] if number % 2 == 0]
[val for val in [1,2,3,4] if val in [3,4,5,6]]
[''.join([name[i] for i in range(len(name)-1, -1, -1)]).lower() for name in ["Elie", "Tim", "Matt"]]
"".... |
70bba8b2c468b287caba595e29b4f55a950d1c32 | hmanjarawala/Python | /Functional Programming/Recursion/Sum Of Fibbonacci Nos.py | 433 | 4.1875 | 4 | """""
This script will calculate nth fibbonacci numbers
"""""
def fibbonacci(n):
if n == 0 or n == 1:
return 1
else:
return fibbonacci(n-1) + fibbonacci(n-2)
intNumber = 5
try:
intNumber = int(input("Enter the number: "))
except ValueError:
print("Entered value is not valid integer number")
print("continue pr... |
057c4cee70a710b8db421f3a62951281f671cca6 | Super-Qian/algorism_with_python | /counting_sort.py | 631 | 3.703125 | 4 | #!/usr/bin/env python
# coding=utf-8
# 序列元素必须是整数
# 元素的最大值不能大于等于序列的长度
def counting_sort(nums, k):
temp_nums = []
new_nums = nums[:]
for j in range(0, k):
temp_nums.append(0)
for j in range(0, len(nums)):
temp_nums[nums[j]] = temp_nums[nums[j]] + 1
for j in range(1, k):
temp... |
ae72398d5c4d9e78ab405ce6ed368aa3a00bc7a1 | Sugandha05/learn-python | /add.py | 241 | 3.78125 | 4 |
def subtract10AndAdd(a,b):
a-=10
b-=10
sum=a+b
minus=a-b
return sum
x = int(input("provide a number"))
y = int(input("provide a number"))
z = int(input("provide a number"))
output=subtract10AndAdd(x,y)
print(output)
|
7cc8a68fea4bb57fab7550731b1ab183a408cb27 | Sugandha05/learn-python | /while_loop_list.py | 280 | 3.609375 | 4 | book = ['ram', 'shyam', 'su', 'mo']
page = 0
# while book is not finished (till 6)
# read(print) and update page number
# while condition is true do following
while page != 4:
# print(page!=4)
print(book[page])
page = page + 1
#print(book[page])
print(page!=4)
|
62b2ac5076886a286a013e22158d007123854fcc | ipashi/leetcode | /last stone weight leetcode-1046.py | 1,079 | 3.546875 | 4 | import heapq
class Solution:
def lastStoneWeight(self, stones: List[int]) -> int:
# by deafult heapq in python is a min-heap
# but we require max-heap so we need to convert every
# value to negative to convert smallest value to biggest
stones = [-1*i for i in stones]
#... |
6a19bc221a3f02d2ea17b64f30886a4bc4830982 | q798010412/untitled2 | /6.19/train5.py | 2,156 | 3.71875 | 4 | class Node:
def __init__(self,data):
self.data=data
self.next=None
class LinkList:
def __init__(self):
self.head=None
def insert_head(self,data):
new_node=Node(data)
if self.head:
new_node.next=self.head
self.head=new_node
def insert_tali(self,... |
dc6f34ab30b25c455c6527ee3a9648fc4bca93e9 | q798010412/untitled2 | /6.19/111.py | 1,736 | 3.75 | 4 | class Node:
def __init__(self,data):
self.data=data
self.next=None
class LinkList:
def __init__(self):
self.head=None
def insert_head(self,data):
new_node=Node(data)
if self.head:
new_node.next=self.head
self.head=new_node
def insert_tail(self,... |
f72dee00a77c17c35b645f43fa419a0cf1fb94d6 | q798010412/untitled2 | /6.23/栈_train.py | 1,766 | 3.984375 | 4 | # 数组
# class Stack:
# def __init__(self,limit=10):
# self.stack=[]
# self.size=0
# def __str__(self):
# return str(self.stack)
# def push(self,data):
# self.stack.append(data)
# self.size+=1
# def pop(self):
# if self.stack:
# self.stack.pop()
... |
cce37860e8278c38533411135f64b17992257bf8 | q798010412/untitled2 | /6.19/train.py | 1,651 | 3.90625 | 4 | from typing import List
class Node:
def __init__(self,data):
self.data=data
self.next=None
def __repr__(self):
return 'Node(%s)'%(self.data)
class LinkList:
def __init__(self):
self.head=None
def insert_head(self,data):
new_node=Node(data)
if self.head:
... |
84e5501b98da657f4824ad74f1fb054b992c711b | nzh1992/Interview | /algorithm/p3.py | 490 | 4.03125 | 4 | # -*- coding: utf-8 -*-
"""
Author: niziheng
Created Date: 2021/6/10
Last Modified: 2021/6/10
Description:
"""
# 问题:
# 请写出一个函数,满足以下条件
# 1. 该元素是偶数
# 2. 该元素在原list中是在偶数的位置(index是偶数)
def filter_numbers(number_list):
return [i for i in number_list if i % 2 == 0 and number_list.index(i) % 2 == 0]
if __name__ == '__m... |
318f5a6792eeddf6ba9de651dbf63d5f49340b47 | nzh1992/Interview | /py_language/builtin_structure/p4.py | 533 | 3.75 | 4 | # -*- coding: utf-8 -*-
"""
Author: niziheng
Created Date: 2021/6/4
Last Modified: 2021/6/4
Description:
"""
# 问题:
# 将字符串"k:1 |k1:2|k2:3|k3:4",处理成字典{k:1, k1:2, ...}
def str_to_dict(s):
d = {}
for iterms in s.split('|'):
k, v = iterms.split(':')
d[k] = v
return d
def str_to_dict2(s):
... |
a1d79a4a94fc874ba551b3b85295f1c49a6fed67 | fangniu/leetcode | /questions/437_路径总和 III.py | 1,274 | 3.859375 | 4 | # -*- coding: utf-8 -*-
"""
给定一个二叉树,它的每个结点都存放着一个整数值。
找出路径和等于给定数值的路径总数。
路径不需要从根节点开始,也不需要在叶子节点结束,但是路径方向必须是向下的(只能从父节点到子节点)。
二叉树不超过1000个节点,且节点数值范围是 [-1000000,1000000] 的整数。
示例:
root = [10,5,-3,3,2,null,11,3,-2,null,1], sum = 8
10
/ \
5 -3
/ \ \
3 2 11
/ \ \
3 -2 1
返回 3。和等于 8 的路径有:
... |
b6b84950c987f21ae8751863e00061aaec8ba6b4 | fangniu/leetcode | /sorts/quick_sort.py | 835 | 4.09375 | 4 | # -*- coding: utf-8 -*-
import random
def quick_sort(sorting, left, right):
if left >= right:
return
i = left
j = right
pivot = sorting[i]
while left != right:
while left < right and sorting[right] >= pivot:
right -= 1
while left < right and sorting[left] <= pi... |
cc51655b48be6bc732f933ae0dc6cd42a94572b5 | LivJH/Leeds_practicals | /practical_3.py | 4,242 | 3.5 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Sep 18 11:00:28 2018
@author: gyojh
"""
# -*- coding: utf-8 -*-
"""
Created on Tue Sep 18 09:42:25 2018
@author: gyojh
"""
# Set up variable
y0 = 50
x0 = 50
## this makes a copy of model.py so it can be used for this prac
# Import random and set a random number between 0-... |
fb2253ba1e0f8341a37bab8df7d364473d10b1e2 | kabirsrivastava3/rock-paper-scissors | /rock-paper-scissors.py | 647 | 3.859375 | 4 |
import random
def playGame():
inputUser = input("What's your choice? 'R' for rock, 'P' for paper, 'S' for scissors\n")
computer = random.choice(['R', 'P', 'S'])
if inputUser == computer:
return 'It\'s a tie'
#R > S, S > P, P > R
if checkWin(inputUser, computer):
return 'Yay!! You... |
d6df8f6fbb4b3928735c7902b84d38d76a5e89a9 | sanjeev30798/Codechef-Accepted-solution | /UTMOPR.PY | 245 | 3.53125 | 4 | import math
n=(int)(input())
while(n>0):
n-=1
l1,k=map(int,input().split(" "))
l=list(map(int,input().split(" ")))
sum1=sum(l)
if(sum1%2==0):
if(k==1):
print('odd')
else:
print('even')
else:
print('even')
|
3ee9a184bc9eb93dae4f27e705bb747fbe41a937 | Arpan-Mishra/Scrabble_Combination_Maker | /scrabble.py | 1,958 | 3.703125 | 4 | import itertools, twl
# Function to create a set of all the possible combinations of letters
def randomize(word):
t = []
comb = set()
for i in range(2, len(word) + 1):
t = list(itertools.permutations(word, i))
for j in range(0, len(t)):
comb.add(''.join(t[j]))
return... |
9b4e94f5cccecfb995b865a86b631fcbb9259e8d | gregorovitz/formation_front-end_developpeur | /python/pythonProject/animalerie/models/animal.py | 2,334 | 3.59375 | 4 | from datetime import datetime
import random
from abc import ABC
class Animal(ABC):
def __init__(self, name, poids, taille, sexe, birthdate: datetime, date_arrive, cri='jce crie', prob_death=0.0):
self.__name = name
self.__poids = poids
self.__taille = taille
self.__sexe = sexe
... |
659cf8bab72e07184242386f2337546b7fd2af5d | gregorovitz/formation_front-end_developpeur | /python/collection/collection/ex5_tri_fusion.py | 961 | 3.625 | 4 | def affichage_list(list):
print(list)
def fusion(gauche ,droite):
resultat = []
index_gauche, index_droite = 0, 0
while index_gauche < len(gauche) and index_droite < len(droite):
if gauche[index_gauche] <= droite[index_droite]:
resultat.append(gauche[index_gauche])
index... |
1d3904c53d4dbd1df3df9357fc6de79f02b142fd | neriunam/spark-training-python | /LambdaPythonDemo.py | 291 | 3.703125 | 4 | def duplicate(i):
return i * 2
def square(i):
return i * i
def operation(top, f):
print("\nStart 1, top: " + str(top) + ", function: " + str(f))
for i in range(1, top + 1):
print(i, f(i))
operation(5, lambda i: duplicate(i))
operation(5, lambda i: square(i))
|
3345aff70948155a5065a120c6f574df67208813 | kiyonatsu/Python-project-1 | /py project hand washing.py | 2,972 | 3.84375 | 4 |
# importing modules
# ... YOUR CODE FOR TASK 1 ...
import pandas as pd
import numpy as np
# Read datasets/yearly_deaths_by_clinic.csv into yearly
yearly =pd.read_csv('datasets/yearly_deaths_by_clinic.csv')
# Print out yearly
# ... YOUR CODE FOR TASK 1 ...
yearly
# Calculate proportion of deaths per no. births
# ..... |
36e7736fc6840052ab67da435ba4a8ff14af76b4 | CorgiDev/PythonPractice | /Learning Python/Ch2/self_practice.py | 754 | 4 | 4 | import math
##########################################################
class Simple():
def Add(x, y):
return (x+y)
class Advanced(Simple):
def Inverse(x,y):
sum = Simple.Add(x,y)
return(1/sum)
def Inverse2(x,y):
sum = Simple.Add(x,y)
return(1/sum)
# This o... |
e7c60a5ce2dc23e889a2c4140631b330b65fa848 | amroakmal/Face-recognizer | /PCA_scklearn.py | 699 | 3.59375 | 4 | from sklearn.decomposition import PCA
# #############################################################
# pca using sklearn built in functions
# input:
# alpha: pca variance threshold
# output:
# train_data_transformed: train_data after applying pca
# test_data_transformed: test_data after applying pca
# #########... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.