blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
6307cc796b641c709b706ca732cb3e17f5671a50 | tubarvex/wierdCalculator | /main.py | 1,068 | 4.21875 | 4 | #first_name = "Enes"
#last_name = "Varol"
#full_name = first_name+""+ last_name
#print("Hello "+full_name)
#print(type(name))
#age = 21
#age += 2
#print(type(age))
#print("your age is: "+str(age))
#print(type(age))
#height = 250.5
#print(height)
#human = False
#print(human)
# name = "enes asdasd "... |
20488b0172b5aca750c205797a4ea9bcb5d5ecac | vbukovska/SoftUni | /Python_fundamentals/Dictionaries/force_book.py | 1,130 | 3.765625 | 4 | def add_user(user, side, book):
for force in book:
if user in book[force]:
return book
if side not in book:
book[side] = []
if user not in book[side]:
book[side].append(user)
return book
force_book = {}
while True:
command_line = input()
if 'Lumpawaroo' in ... |
f450fa92302347aca878514cd9dad2914ce44208 | Emma-ZSS/repo-zhong253 | /repo-zhong253/labs/lab02/loan.py | 236 | 4.09375 | 4 | loan_amount = float(input("Enter a loan amount: "))
annual_r = float(input("Enter an annual interest rate: "))
n = float(input("Enter a loan duration in months: "))
r = annual_r/12
payment = r*loan_amount/(1-(1+r)**(-n))
print(payment)
|
0c46ad728cd1aecbc3e7adaf661f1bcfaf1af1bb | joakincl/Programas | /programas/programa2.py | 150 | 3.890625 | 4 | print ("Valor de c?")
c = input()
print ("Valor de d?")
d = input()
def potencia(c,d):
print c,"elevado a la potencia", d,"es", c**d
potencia(c,d) |
6bb87cc73bdbfc64326f2934dea2d6a4bbb21389 | TheSinding/AiExercices | /3/a*2.py | 2,207 | 3.65625 | 4 | class Node:
def __init__(self, state, hFunction, parent=None):
self.state = state
self.hFunction = hFunction
self.parentNode = parent
def path(self):
currentNode = self
path = [self]
while currentNode.parentNode:
currentNode = currentNode.parentNode
... |
bc092b917c82ea0b5ea6420beec299c46f6e93cc | Andrew-Finn/DCU | /Year1/ca117/Lab05.2/q2_052.py | 552 | 3.59375 | 4 | import sys
def main():
for l in sys.stdin:
line = l.strip().lower()
vowels = "aeiou"
for letter in line:
if len(vowels) != 0:
if letter in vowels[0]:
line = line.replace(letter, "", 1)
vowels = vowels.replace(letter, "", 1... |
859e67730c3ea54c64fbf63b603a6e2747392e6a | lfjd05/Introduction_to_algorithms_completion | /Leetcode/removeElement.py | 1,072 | 3.625 | 4 | """
给定一个数组 nums 和一个值 val,你需要原地移除所有数值等于 val 的元素,返回移除后数组的新长度。
不要使用额外的数组空间,你必须在原地修改输入数组并在使用 O(1) 额外空间的条件下完成。
"""
class Solution:
def removeElement(self, nums, val):
"""
:type nums: List[int]
:type val: int
:rtype: int
"""
if len(nums) == 0:
return 0
... |
5c917ec117fb2f9dddb54c276f3b0b594a8eb0a8 | Gustaft86/trybe-exercises | /modulo4_ciencia/bloco_36/dia_2/exercicio_dia_6_bonus.py | 716 | 4.0625 | 4 | # Exercício 6: Escreva um algoritmo recursivo que resolva o problema da torre
# de hanoi, seguindo as instruções:
# Assim como na imagem abaixo, a torre deve conter 3 discos, e três colunas;
# Os discos começam alinhados na primeira coluna, e devem ser organizados
# respeitando a ordem de tamanho, na última coluna.
d... |
af328e3777d1f32e3f7ca30d9a6f951051cd1fa6 | DaronKihn/python_lab | /python_lab_2/11_2_filtr.py | 300 | 3.84375 | 4 | print("Количество строк:")
n = int(input())
for i in range(n):
text = input()
if text[0] == "%" and text[1] == "%":
print(text[2:])
elif text[0] == "#" and text[1] == "#" and text[2] == "#" and text[3] == "#":
continue
else:
print(text) |
17ed985ddf8fb033bc88dabb65886079094a02a9 | pollsmor/softdev | /10_mongo/mongo.py | 3,904 | 3.703125 | 4 | #Team Rocket | Kevin Li & Jason Zheng
#SoftDev pd2
#K10 -- Mongo Import/Export
#2020-02-29
#Pokédex (https://raw.githubusercontent.com/Biuni/PokemonGO-Pokedex/master/pokedex.json)
#First, the JSON file is opened. Then, the built-in json library is used to parse the JSON.
#Next, insert_many inserts the data one JSON el... |
cf1672f7e92bda65eb295721bbb78b8a4d7cd044 | enasuzuki/Python-Practice | /BankAccount.py | 2,414 | 4.03125 | 4 | class BankAccount:
def __init__(self, balance, deposit, withdraw, level):
self.balance = int(balance)
self.level = level
def Balance(self): #function
if self.balance >= 0:
print("Your balance is $" + str(self.balance))
def Deposit(self,amount_deposit): #function
if amount_deposit > 0 and a... |
4aa056b28a558e2979f0dc0c4c1a59b6c1a73759 | herisson31/Python-3 | /Cadastro de Notas.py | 913 | 3.96875 | 4 | from tkinter import *
##Definindo a funçãos que salva os dados em um aquivo##
def SalvarDados():
arq = open("Notas.txt","w")
arq.write("Diciplina: %s \n"%(diciplina.get()))
arq.write("Nota: %s \n"%(nota.get()))
arq.write("Verificação: %s \n"%(verificacao.get()))
print('Dados armazenados com sucess... |
5d2856e5740e04d7fef87f85fc1e705c9b39d4d8 | neuma-script/pool-experiment | /Pool_script.py | 3,806 | 3.828125 | 4 | # Author: Varunil N. Shah
# This first for loop is for all the runs in the experinment
import random, datetime, functions
import pandas as pd
visualTrial = True
kinesticTrial = True
for runNumber in range(1, 3):
runTime = str(datetime.datetime.now().time())
df_output = pd.DataFrame(columns = ['Run Number', 'Run Ti... |
91a7aaa12e2e137b80b1dab2a10f89900b1a6bed | ansariyusuf/Shapes_Studio | /L systems yusuf.py | 8,419 | 3.71875 | 4 |
from Tkinter import *
from turtle import *
import random
class Application(Frame):
def __init__(self, master):
""" Initialize the frame."""
Frame.__init__(self, master)
self.grid()
self.create_widgets()
def create_widgets(self):
self.labels = []
self.ruleBoxes = []
self.interpBoxes =... |
cf63069b8fb41f38c1f757e04670cb92c05163bd | kyoppii13/algorithm_deta_structure | /part_3/3_4.py | 314 | 3.703125 | 4 | def select_sort(X):
for i in range(len(X)-1):
minj = i
for j in range(i+1,len(X)):
if(X[j] < X[minj]):
minj = j
X[i],X[minj] = X[minj],X[i]
return X
if __name__ == "__main__":
X = list(map(int, input().split()))
X = select_sort(X)
print(X)
|
fb19eb59d2901c49910ed6b5ee85ca433bb94319 | tnperez/codeatiu2021 | /Meeting3/pal.py | 910 | 3.71875 | 4 | # ello
# 4/2 = 2
def pal(s):
l = len(s)
l = l//2 # 7//2 = 3 or 7%2 = 1
# firstHalf = ""
# secHalf = ""
# #for loops here
# return firstHalf == secHalf
for i in range(l):
if(s[i] != s[len(s) - i - 1]):
return False
return True
def pal1(s):
l = len(s) #elle -> ... |
16014eeb740a4842671ef37ba85955469894829d | yixinglin/sobot-rimulator | /supervisor/slam/graph/baseclass/Vertex.py | 611 | 3.5 | 4 | """
The parent class of any types of vertex
"""
import numpy as np
class Vertex:
def __init__(self, pose, sigma):
"""
A vertex class. It is a component of a graph
:param pose: a vector of pose
:param sigma: a covariance matrix, uncertainty of measurement
"""
... |
4c3dffa9a51ac17062400d641385de1411f93c97 | whereisyou/reptile | /zero_05_求和,求乘阶.py | 651 | 4.03125 | 4 | def sum_zero():
"""0到100求和"""
zero = 0
sum1 = 0
while zero < 100:
zero += 1
sum1 += zero
print(sum1)
def factorial_zero():
"""求任意数的阶乘"""
number = float(input("请输入数字:"))
i = 1
sum2 = 1
if number > 0 and number%1==0:
while i < number+1:
sum2 ... |
292cf7308b409a77c2c7a03a9369225a6f773c58 | aaron-lebo/prosterize | /prosterize.py | 1,345 | 3.5625 | 4 | from sys import argv
from PIL import Image, ImageDraw, ImageFont
img = Image.open(argv[1])
text_path = argv[2]
out_path = argv[3]
font_path = argv[4]
font_size = int(argv[5])
file = open(text_path, 'rb')
text = ' '.join(file.read().replace('\n', ' ').replace('\r\n', ' ').split())
file.close()
# crea... |
8f6474922325eb09b7193c8688c910bd957e43c5 | TrueCookie/CtapooPy | /file2.py | 241 | 3.84375 | 4 | def fract_sum(num):
num_str = str(num)
num_sum = 0
dot_index = num_str.find('.')
fract_part = num_str[dot_index+1:]
for i in fract_part:
num_sum = num_sum + int(i)
return num_sum
print(fract_sum(input()))
|
7f019f3b4fe92e9b80a9d8393802210796e957c6 | levabala/python-uni | /sorts/bubble.py | 359 | 3.78125 | 4 | from sorts.sortInfo import SortInfo
def bubbleSort(arr, progress=lambda x: x):
swaps = 0
compares = 0
n = len(arr)
for i in range(n):
for j in range(0, n-i-1):
if arr[j] > arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j]
swaps += 2
compares += 1
progress(i / n)
return So... |
5cefba80f878e7024d7b4addc38c35dff3c525b0 | kanikashridhar/Python_decorators | /rate_limiting_decorator.py | 923 | 3.53125 | 4 | """ Algorithm to limit the rate of incoming requests."""
import time
import unittest
# Decorator to limit incoming request as per the rate.
def my_rate_limiter_decorator(max_transaction, max_time):
rate = max_transaction / max_time
interval_within_per_second = 1.0 / float(rate)
def my_rate_limiter(func):
las... |
64ca7143a825ca5ec0c36891eff018cf941686c1 | williammmmmmmmm/python_homework | /实验2_special.py | 318 | 3.8125 | 4 | pw=input("请输入密码六位:")
x=0
y=""
for a in pw:
x = x + int(ord(a))
print("ASCII值求和为:" ,x)
for a in pw:
y= y + str(ord(a))
print("ASCII值前后拼接结果为:" ,y)
print("ASCII值前后拼接后反转结果为:" ,y[::-1])
print("最后加密后的密码为:" , int(y[::-1])+int(x)) |
e0a81f914eecf77394a4e7c2fb9e4ed6ededc166 | woodelf7/rps | /starters.py | 181 | 3.84375 | 4 | def subber(x, y):
"""return y - x"""
return y - x
def choice():
"""returns choice in lowercase"""
choice = raw_input("Enter a choice: ")
return choice.lower()
|
021d780aa0659506e6dfa32b18ac0568415ff6e5 | bbuchake/learn-python | /Candy and Pie Store/piestore.py | 852 | 4.0625 | 4 | #Create the pie list
pieList = ["Pecan", "Apple Crisp", "Bean", "Banoffee", "Black Bun", "Blueberry", "Buko", "Burek", "Tamale", "Steak"]
#Display list for user
for pie in pieList:
print("(" + str(pieList.index(pie)) + ") " + pie)
#variable for storing another order boolean
orderAgain = "y"
numberOfPies = [0,0,... |
c2bb3d06cb3a0f3a7b6346842e285094065fa703 | joseph-mutu/JianZhiOfferCodePics | /[一个数一个数计算]整数中1出现的次数.py | 445 | 3.53125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2019-08-31 15:05:25
# @Author : mutudeh (josephmathone@gmail.com)
# @Link : ${link}
# @Version : $Id$
import os
class Solution:
def NumberOf1Between1AndN_Solution(self, n):
count_1 = 0
for i in range(1,n+1):
tem_str = [tem for tem in str(i)]
fo... |
6be3cb8a7d2fc6eabcee4aa6cf4d91b1947897d4 | RossCZ/PythonLearning | /topics/5_advanced/hashing.py | 1,017 | 4.375 | 4 | print(hash(1))
print(hash("hello"))
# hash of immutable objects only
print(hash((1, "a")))
# error - hash of mutable objects not possible
# print(hash([1, 2]))
# print(hash({"a": 111}))
# hashable class
class Dog:
def __init__(self, name, dog_id):
self.name = name
self.dog_id = dog_id
# ove... |
4b0dbbbb20de602d271b0f46c2074e347593de8e | jamilcse13/python-and-flask-udemy | /20. tupleBasicOperation.py | 849 | 4.25 | 4 | tuple1, tuple2 = (122, 'abc', 'xyz'), (456, 'mno')
#len() function
print('len() function')
print(tuple1, tuple2)
print('First tuple length: ', len(tuple1))
print('Second tuple length: ', len(tuple2))
input()
#max() function
tuple1, tuple2 = ('math', 'abc', 'xyz'), (456, 222, 756, 125)
print('max() function')
print(tup... |
1f361ab2cab873162ba5944ea554240f891b4a8c | lb8ovn/CoffeeOOP | /Simple_Math.py | 123 | 3.625 | 4 | def stutter(word):
new_word = list(word)
print(((str(new_word[0]+new_word[1])+' ... ')*2)+word+'?')
stutter('increasing') |
955331ecd0b70046d0ebc2dd2d4ab9281dfbe7b9 | shriharis/Code_Python | /modules/try_xcept.py | 192 | 3.71875 | 4 | """
errror handling
"""
import re
def validate(username):
try:
if( bool(re.match("^[a-zA-Z]", username))):
print(username)
except:
print("invalid input")
|
22289b89cd572c025ee9b9dd8cd56276ac941592 | ashishjayamohan/Tread | /scripts/matrix_functions.py | 7,694 | 3.5625 | 4 | from itertools import tee
def determinant(matrix, __len=None, __nocheck=False):
if type(matrix) == list and len(matrix) == 0:
return 1
elif (not __nocheck) and len(matrix) != len(matrix[0]):
raise TypeError("Table must be a square")
else:
size = __len or len(matrix)
if size... |
4df9440b9ad22bc93298a8e4b279d2470469f4dc | tanx-code/levelup | /design_patterns/factory.py | 1,863 | 4.4375 | 4 | """工厂模式
所有工厂模式都是用来封装对象的创建。
之所以不用函数,是因为函数不好扩展。
工厂本身也可以作为抽象类,视为一个简单工厂(这时候把创建对象的
那个函数当做虚函数),然后在其上派生出具体工厂类,再覆盖那个用
来创建对象的函数,就可以使得加工方式改变的时候不必重写某个工厂
了,只需要继承基类然后重新申明一个工厂类就行了。
"""
from abc import ABC, abstractclassmethod
class Pizza(ABC):
@abstractclassmethod
def making_step_1():
...
@abstractclas... |
8284c35a80abfb258ab16b6eb7ca19c0c079bfd9 | mirszhao/python-base | /basefile/tuple.py | 339 | 3.671875 | 4 | #coding:utf-8
#tuple file 元组
#python 2.7.6
classmates=('Sean','Jack','Mirs')
print classmates
print classmates[0]
t=(1,2)
print t
t=()
print t
t=(1,) #元组只有一个元素时
print t
#可变的元组, 指向永远不变,但指向本身的list是可变的
t=('a','b',['A','B'])
print t
t[2][0]='C'
print t
|
fa96cb045856c9059479adc53c816267cf908069 | AnastaFilatova/Open_files_Tasks | /linecounter.py | 1,498 | 3.75 | 4 | # Содержимое исходных файлов в результирующем файле должно быть отсортировано по количеству строк в них
# (то есть первым нужно записать файл с наименьшим количеством строк, а последним - с наибольшим)
# Содержимое файла должно предваряться служебной информацией на 2-х строках: имя файла и количество строк в нем
from p... |
7143c6a95337e990ec8353819c9e6738b90169b4 | 1f604/questions | /programming questions/trivial questions/print_circle.py | 1,717 | 4.125 | 4 | #program to print a circle in python
#creds to Tycho for idea behind print_circle()
#2nd algorithm appears to be faster by some unknown factor judging from tests...
import sys
import math
import time
radius = 15
min_radius=12
def circle():
result = ""
for i in range(-radius, radius):
for j in range(-ra... |
937b587c45f428883d62bd80e217fca247d3398c | D4rkdev1987/CodeWars | /Regex_Validate_PIN_Code-7KYU.py | 581 | 4.09375 | 4 | import re
def validate_pin(pin):
return re.search('^(\d{4}|\d{6})$', pin) != None
'''
def validate_pin(pin):
if re.match(r'^\d{4}$', pin) or re.match(r'^\d{6}$', pin):
return True
else:
return False
'''
print(validate_pin('945940'))
'''
Description:
ATM machines allow 4 or 6 digit PIN cod... |
6a6f5ada0172d1a8a44cf8beb808d4885f55abc7 | hahahafree/learning__python3 | /005_高级特性/005_4 生成器/Fibonacci_3.py | 1,132 | 3.84375 | 4 | #!/bin/usr/env python3
# -*- coding:utf-8 -*-
#例子1
def fab_1(x):
n,a,b = 0,0,1
while n < x:
print(b)
a,b = b,a+b
n = n+1
return 'done'
a_1 = fab_1(5)
print('斐波那契數列x=5:',a_1)
#例子2
def fab_2(x):
n,a,b = 0,0,1
L = []
while n < x:
L.append(b)
a,b = b,a+b
... |
65bf2ef38e2682fecab3c046a7e343d9ad9b5cee | Chalayyy/challenge_solutions | /escape_pod.py | 9,859 | 3.6875 | 4 | """
The problem:
Given a list of entrances, a list of exits (which are
disjoint from the entrances), and a matrix indicating the maximum
number of individuals that can travel down a hallway each time unit
from one room(the matrix row) to another (the matrix column), find the
maximum number of individuals that can be s... |
d7b5ccf1ac4922f98632040a8ce1e7af05bade8c | swapniljathar/CSE231 | /Labs/lab09.partc.py | 627 | 3.671875 | 4 |
import random
def sub1( size ):
values = list()
for i in range(size):
values.append(0)
return values
def sub2( values, size ):
for n in range(100000):
i = random.randint(0,size-1)
values[i] += 1
def sub3( values, size ):
for i in range(size):
print("\t", i,... |
1f4a8bdc795d02f6fcc2587dfd2754499d9d9eae | jacklau1803/Tiny_Language_Interpreter | /TLI.py | 10,121 | 3.671875 | 4 | #! /usr/bin/env python3
import fileinput
import sys
# used to store a parsed TL expressions which are
# constant numbers, constant strings, variable names, and binary expressions
class Expr :
def __init__(self,op1,operator,op2=None):
self.op1 = op1
self.operator = operator
self.op2 = op2
... |
a0b0864c2ab4efca6b8bae0a1035c263c2ab0717 | sagarsetru/fiberviewCameraSimulation | /testclassgaussian.py | 1,073 | 3.53125 | 4 | class Gaussian:
"""Class to make single Gaussian Profile"""
# def __init__(self,sigma,center_x,center_y,dark=0,readnoise=0,height=40000):
def __init__(self,sigma,height=40000):
self.sigma = sigma
# self.center_x = center_x
# self.center_y = center_y
# self.dark... |
671ae613e2ac06dd2fca14845732694e1be7764c | jeremy812/distrogenerator | /discretedistrogenerator.py | 3,177 | 3.515625 | 4 | #from mythos.domain.generators.generator import Generator
import random
'''
An implementation of the alias method using Vose's algorithm. The alias method samples random values from a discrete
probability distribution in O(1) time after O(n) preprocessing time.
'''
class DiscreteDistributionGenerator:
# preproc... |
cf53e598e432842a191dfc1a9eeee2ed0ab14ecf | OscarOzaine/Hackerraank | /algorithms/sorting/merge-sort.py | 755 | 4.03125 | 4 | def mergesort( aList ):
_mergesort( aList, 0, len( aList ) - 1 )
return aList
def _mergesort( aList, first, last ):
# break problem into smaller structurally identical pieces
mid = ( first + last ) / 2
if first < last:
_mergesort( aList, first, mid )
_mergesort( aList, mid + 1, last )
# merge solved pi... |
44bda587f84287a877d465df6d7fdc56516a5015 | JunctionChao/LeetCode | /Math/string-to-integer.py | 520 | 3.5 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Date : 2019-09-16
# Author : Yuanbo Zhao (chaojunction@gmail.com)
import re
def myAtoi(str: str) -> int:
str = str.strip()
str = re.findall('(^[\+\-0]*\d+)\D*', str)
try:
result = int(''.join(str))
return max(-2**31, min(result,2**31-1))
... |
44651f67888102a509664d3bd88dfdf4440285a5 | abomark/ud036_StarterCode | /media.py | 473 | 3.546875 | 4 | class Movie:
""" This class provides a blueprint for
creating instances of movies
attributes:
title: A movie title
poster_image_url: Takes a url path of a image
trailer_youtube_url: Takes a url path to a url video
"""
def __init__(self, title, poster_image_url, ... |
3b7f382aba85b4bca50a12f8a748519a154b886e | zhangjia517/PythonTrialProject | /BMI.py | 303 | 3.859375 | 4 | L = float(input('请输入你的身高:'))
W = float(input('请输入你的体重:'))
bmi = float(W/(L**2))
print(bmi)
if bmi > 32:
print("严重肥胖")
elif bmi > 28:
print("肥胖")
elif bmi > 25:
print("过重")
elif bmi > 18.5:
print("正常")
else:
print("轻")
input()
|
b5eb2d85834650047986905a243f449be6193ffb | CompSciCardwell/GalaxyBrain | /Perceptron.py | 874 | 4.34375 | 4 | """This is a simple model of a perceptron based on Nahua Kang's Deep Learning tutorial
on towardsdatascience.com"""
class Perceptron:
def __init__(self, inputs = [1, 1, 1], weights = [6, 2, 2], bias = -5):
self.sum = 0
self.bias = bias
self.inputs = inputs
self.weights = weights
... |
bb153ae1f0fe8f0d3c2ea638b013105a9b2c04de | satuhyva/100daysOfPython | /Day 002/number_manipulation.py | 575 | 3.953125 | 4 | print(round(8 / 3, 2)) # 2.67
print(round(8 / 3, 5)) # 2.66667
print((8 // 3)) # 2
print(4 / 2) # 2.0
result = 4 / 2
result /= 2
print(result) # 1.0
score = 55
score += 1
score -= 1
score *= 2
score /= 3
# f-strings
print("Your score is " + str... |
14da07c5536d0e2c823656a87bf77b6881871453 | latelypro/study | /AtCoder/ABC101-200/ABC146/B.py | 209 | 3.640625 | 4 | n=int(input())
s=input()
max_code=ord('Z')
converted = ''
for item in s:
code = ord(item)
code += n
if code > max_code:
code -= 26
converted = converted + chr(code)
print(converted)
|
d7d2574273a2ac04e4ee5357c5bcda9c738d4fd9 | borator/PythonAdvanced | /05-Functions/Exercise/06. Recursion Palindrome.py | 418 | 4.1875 | 4 | def is_palindrome(s):
result = False
if len(s) < 1:
result = True
else:
if s[0] == s[-1]:
result = is_palindrome(s[1:-1])
return result
def palindrome(*args):
word = args[0]
result = f"{word} is not a palindrome"
if is_palindrome(word):
result = f"{word}... |
4e645f0c66a23bc33c01b9ad78105a705905d93c | vochong/project-euler | /python/euler57.py | 240 | 3.59375 | 4 | def euler57():
acc = 0
m, n = 3, 2
for _ in range(1000):
if len(str(m)) > len(str(n)): acc += 1
tmp = n
n = m + n
m = n + tmp
return acc
if __name__ == "__main__":
print euler57()
|
a429f671ae4f03808bd23dba829eb0516751d036 | gabrieleliasdev/python-cev | /ex075.py | 649 | 4.1875 | 4 | """ 075
Desenvolva um programa que leia quatro valores pelo teclado e guarde-os em uma tupla. No final, mostre:
A) Quantas vezes apareceu o valor 9.
B) Em que posição foi digitado o primeiro valor 3.
C) Quais foram os números pares.
"""
lst = tuple(int(input('\nDigite o {}º numero: '.format(i+1))) for i in... |
ed3575bf3c276d31b2a59527e33d86fc6dbcace3 | vikramforsk2019/FSDP_2019 | /forskfssdpday21codechallenges/House Data.py | 1,963 | 3.609375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Jun 29 11:54:16 2019
@author: vikram
"""
"""
Code Challenges 02: (House Data)
This is kings house society data.
In particular, we will:
• Use Linear Regression and see the results
• Use Lasso (L1) and see the resuls
• Use Ridge and see the score
"""
... |
2aaa2214dca4eec9be0ae736a2624b9fa38c80d4 | Vika-Zil2020/python | /unique.py | 200 | 3.9375 | 4 | inputed_element =input("enter elements")
my_list =[]
def unique(inputed_element):
for i in inputed_element:
if i not in my_list:
my_list.append(i)
return my_list
print(unique(inputed_element)) |
b0a6b59dc1169e5dc1b3f2eae3e2de26360d580e | mnowotka/sda_tdd | /fib.py | 563 | 3.828125 | 4 | class Fibbonacci:
def __init__(self, n):
self.n = n
self.current = 0
self.iteration = 0
self.next = 1
def __next__(self):
print("method __next__ returned!")
if self.iteration == self.n:
raise StopIteration
self.iteration += 1
ret = self... |
b60e1d2c3268f50e784da5e1494536df333b462c | Maryville-SWDV-600-Sum18-4/test-mvu-jcarter8 | /leaderboard.py | 1,329 | 4.125 | 4 | #File: leaderboard.py
#Author: Jerry Carter
#GitHub: mvu-jcarter8
#Write a program that processes a file with video game scores and then outputs the highest score for each difficulty level. Within the file each line contains a player's name, the difficulty level, and their score
#create player class to store name, di... |
2e84e778bab5e1c00d557e900babb38b34405f22 | linkluky/HomeWork-Programing-python | /hw1 5.py | 191 | 3.78125 | 4 | Base = 0
height = 0
prompt = '-->'
total = 0
print(f"height?")
height = input(prompt)
print(f"Base?")
Base = input(prompt)
total = .5 * float(Base) * float(height)
print(total)
|
477ccd4d75a8cc41ce60f9a9431edbd253a293eb | stwcloudy/LeetCode | /Medium/33. Search in Rotated Sorted Array.py | 1,729 | 3.8125 | 4 | """
这题比之后有重复数字的稍微简单一点,由于序列极具特征,序列分为两段分别都是升序,且
第一段的最小的数都比第二段中最大的大,所以依旧可以用二分查找的思想在里边.
mid = (l+r) >>1
1.若nums[mid] == target:直接返回mid
2.由于序列中不存在重复数字,所以可以利用nums[mid]和nums[l]或nums[r]的关系判断它所在区域,以nums[l]为例
2.1 若nums[mid] >= nums[l],说明要么mid == l 要么 nums[mid]在第一段中,此时判断target与nums[mid]的关系
如果target处于nums[l],nums[mid]之间,则r... |
8caedfc132680f2d4a016ced771ae88b8269a785 | UWPCE-PythonCert-ClassRepos/SP_Online_PY210 | /students/mgglez/lesson08/test_circle.py | 3,380 | 3.71875 | 4 | #!/usr/bin/env python
# ------------------------------------------------------------------------------ #
# Title: Lesson08 - Circle Class Exercise
# Description: Assignment from Lesson08 - Circle Class Exercise
# ChangeLog (Who,When,What):
# Mercedes Gonzalez Gonzalez,02-05-2021, Created Circle Class Unit Tests
# ----... |
2846bcdf75bbed3bd359498c8fc1794beafab0e7 | hichingwa7/python_problems | /pruner.py | 777 | 3.71875 | 4 | # date: 10/09/2019
# developer: Humphrey Shikoli
# programming language: Python
# description: program that reads in a JSON file and stores in a dictionary and
# performs a number of manipulations on them
import json
babynames = {}
newdict = {}
babytext = {}
with open("baby_names.txt") as infile:
babynames = json... |
deb4c1741895edf68195ea5bf0c7352d196a7f25 | BRPawanKumarIyengar/Sample_Unit_Test_Cases | /Unit_Test_Samples/test_Sample_Calc.py | 1,080 | 3.515625 | 4 | import unittest
import Sample_Calc
class test_Sample_Calc(unittest.TestCase):
def test_Add_num(self):
self.assertEqual(Sample_Calc.Add_num(10, 5), 15)
self.assertEqual(Sample_Calc.Add_num(-10, 5), -5)
self.assertEqual(Sample_Calc.Add_num(-10, -5), -15)
def test_Subtract_nu... |
c73e614e0acc3fff3ed23743cf30971b5a65e925 | weeeBox/codingbat-python-recursion | /recursion2/R06_splitOdd10.py | 1,445 | 4.09375 | 4 | from unittest import TestCase
from typing import List
def splitOdd10(nums: List[int]) -> bool:
"""
Given an array of ints, is it possible to divide the ints into two groups, so that the sum of one group is a
multiple of 10, and the sum of the other group is odd. Every int must be in one group or the other... |
0a7e4a98693288a5d87521692e4d14eeb678294b | whsair/Archive | /CMPSC 442 Spring 2020 Artificial Intelligence/hw3.py | 13,395 | 3.625 | 4 | ############################################################
# CMPSC 442: Homework 3
############################################################
student_name = "Hongshuo Wang"
############################################################
# Imports
############################################################
... |
486d95a47e6e2dff536ff410b9242a6408326a70 | rob93c/Exercism | /python/scrabble-score/scrabble_score.py | 821 | 3.890625 | 4 | def score(word):
up = word.upper()
count = 0
for letter in up:
if letter == 'A' or letter == 'E' or letter == 'I' or letter == 'O' or letter == 'U' or \
letter == 'L' or letter == 'N' or letter == 'R' or letter == 'S' or letter == 'T':
count += 1
elif letter == 'D' or ... |
fdcdc5828705a2d0ea939cdedb0d4b4cce698a2d | limkeunhyeok/Data-Structure | /data structure/priority queue/priorityQueue.py | 581 | 3.640625 | 4 | from heapq import heappush, heappop
class PriorityQueue:
def __init__(self):
self.queue = []
def enqueue(self, rank, data):
heappush(self.queue, (rank, data))
def dequeue(self):
if not self.queue:
return 'empty'
return heappop(self.queue)
def s... |
ea1c825abc9a1e95a8de8f1588050b2084914c00 | tseth92/python_concepts | /closures_and_decorators.py | 1,727 | 4.15625 | 4 | # a language is said to have first class functions:
# functions treated as object and can be assigned, passed, returned
# Decorators use Closures in an easy way so that the closured function can be executed
from functools import wraps # see at last for why it is needed
def log_you(log_me):
print('in log_you')
@... |
1b9208519f79a315a4df8f60c6c3b6fffc502aa3 | Ariyanayagam/python_guvi | /check_if_array_is_sorted.py | 124 | 3.609375 | 4 | sx=int(input())
sx=[int(x) for x in input().split()]
s1=sorted(sx)
if(sx==s1):
print("yes")
else:
print("no")
|
ca92f11ed595651a07e0cc86de708f0116a24180 | SYAN83/DataStructuresandAlgorithmsSpecialization | /DataStructures/week2_priority_queues_and_disjoint_sets/1_make_heap/build_heap.py | 850 | 3.890625 | 4 | # python3
def build_heap(data):
"""Build a heap from ``data`` inplace.
Returns a sequence of swaps performed by the algorithm.
"""
n = len(data)
swaps = list()
def swap(i):
left, right = 2 * i + 1, 2 * i + 2
min_ = i
if left < n and data[i] > data[left]:
m... |
91900c738a5b8eeb8c7b80ffe688cbae6ec8b363 | lalit97/DSA | /random/non-repeating.py | 400 | 3.765625 | 4 | '''
https://practice.geeksforgeeks.org/problems/non-repeating-element/0
'''
from collections import Counter
def non_reapeat(lis, n):
d = Counter(lis)
for item in lis:
if d.get(item) == 1:
return item
if __name__ == '__main__':
for _ in range(int(input())):
n = int(input())
... |
3f25faf163e6fde520365037088a66720ddbf000 | ArielAyala/python-conceptos-basicos-y-avanzados | /Unidad 10 - Métodos - Colecciones/MetodosDiccionarios.py | 906 | 4.09375 | 4 |
# El método get busca un elemento a partir de su clave y si no lo encuentra devuelve un valor por defecto
colores = {"amarilo": "yellow", "azul": "blue", "verde": "green"}
print(colores.get('azul', 'No se encuentra'))
# El método keys() genera y retorna una lista de los llaves del diccionario
print(" La lista de keys... |
025d68cdb8da53e5c6d9d69ecc419353f69e5720 | ashishpal07/HackerRank_Python | /3o Days of Code (Python)/Day 6 Let's Review.py | 177 | 3.71875 | 4 | # Let's Review
# Enter your code here. Read input from STDIN. Print output to STDOUT
for i in range(int(input())):
s = input()
print(s[0:len(s):2],s[1:len(s):2])
|
1f3f16aa8ce15a3988f7c92b1d998275942beac5 | waszko/Advent-of-Code-2018 | /day19/19_1.py | 3,358 | 3.671875 | 4 |
input_file = "input.txt"
def get_input():
return open(input_file, 'r').read()
def get_opcodes():
# Addition:
def addr(a, b, c, r): # stores into register C the result of adding register A and register B.
r[c] = r[a] + r[b]
def addi(a, b, c, r): # stores into register C the result of adding re... |
50b54f6c43850ac5b57af6b67c459a85f3568844 | SauronsEyes/Python_3_for_Dummies | /classes.py | 321 | 3.734375 | 4 | class calculator:
def addition(x,y):
added=x+y
print(added)
def subtraction(x,y):
sub=x-y
print(sub)
def multiplication(x,y):
mult=x*y
print(mult)
def division(x,y):
div=x/y
print(x/y)
calculator.addition(10,2... |
f52155048541765d7a40eb1dd3d7bf16f8daaab9 | andrezafeu/practicing_python | /python_classes.py | 933 | 3.78125 | 4 | import random
# All classes inherit from object
class Character:
def __init__(self, name, **kwargs):
self.name = name
for key, value in kwargs.items():
setattr(self, key, value)
# Thief class inherits from Character
class Thief(Character):
# attribute
sneaky = True
def _... |
717c5275041018c93f096693658ac6815c942537 | karan-balu/FTPforUntrustedServers | /client/FinalClient.py | 2,705 | 3.78125 | 4 |
'''
DIRSEARCH <directory> <filename>
DIRSEARCH looks for the file in the given directory or its
subdirectories. If it finds the file, it sends back the location.
DOWNLOAD <filename>
DOWNLOAD requires the full file path, or at least the relative path,
of the file. It sends the contents of the f... |
79072e55960b5de9f56486db34748bfaa55c08b9 | FayazGokhool/University-Projects | /Python Tests/General Programming 2.py | 2,320 | 4.125 | 4 | def simplify(list1, list2):
list1_counter,list2_counter = 0,0 #This represents the integer in each array that the loop below is currently on
list3 = [] #Initialise the list
list1_length, list2_length = len(list1), len(list2) #Gets the length of both lists and stores them as varibales so they don't have to be called... |
d3fba5f082007680a033b6b3023ad90c1eed1402 | Jorholt/AppBio | /Ass2/readFastq.py | 267 | 3.546875 | 4 | entry = input('Enter fastq(.fq) filename: ')
file = open(entry)
numseq = 0
seqlist = []
for line in file:
if line.startswith('@'):
seq = line[1:].rstrip()
seqlist.append(seq)
numseq += 1
print(numseq)
for acc in seqlist:
print(acc)
|
d7f9e715ab7a986f402ff03a749133549d51258a | AshwineeKSharma/PythonLearning | /Chapter08_Function&Recursion/01_FunctionIntro.py | 890 | 4.15625 | 4 | # A Function can be defined as a group of statement(Codes) preforming the specific task.
# Functions usually "take in" data, process it, and "return" a result.
# Once a function is written, it can be used over and over and over again.
# Functions can be "called" from the inside of other functions.
# E.g. Func() --... |
1b74e9ca3c625ffccfad02f0d18efdb78e4a6af6 | Ajay-Puthiyath/Luminar_Django | /Luminar_Project/Flow_Controls/Looping_Statements/While_Loop/Reversing_Numbers.py | 146 | 3.9375 | 4 | number = int(input("Enter the number "))
res = 0
while(number!=0):
digit = number%10
res = res*10+digit
number = number//10
print(res) |
742b355baefa55bc874e14ad5eb57961ffd8a5ba | ishantk/PythonSep72018 | /venv/Session26.py | 1,610 | 4.03125 | 4 | import pandas as pd
import matplotlib.pyplot as plt
from scipy import stats
data = pd.read_csv("advertising.csv")
# print(data)
X = data["TV"].values
Y = data["Sales"].values
print(">>>>>>>>>>>>>>>X><<<<<<<<<<<<<<<")
print(X)
print(">>>>>>>>>>>>>>>>Y<<<<<<<<<<<<<<<")
print(Y)
print(">>>>>>>>>>>>>>>><<<<<<<<<<<<<<<")... |
72b86c405a613bd88bffe7119c1579b1f8dcb28b | pankajrastogi/test | /substring.py | 257 | 3.8125 | 4 | #!/usr/bin/python
testVar = raw_input("Enter a string :")
str1 = int(input("Enter a source range: "))
str2 = int(input("Enter a destination range: "))
#for n in range(str1, str2+1):
# print(testVar[n])
final = testVar[str1:str1+str2-1]
print final
|
f24a9a5d7b0257be81eb34ad8bdd358b0dea5f1d | karthikdaws/python | /ex3.1.py | 1,379 | 4.4375 | 4 | print "I will now count my chickens" #Outputs the statement
print "Hens", 25.3 + 30.2 / 6 #Outputs "Hens" and then computes the number of hens.
print "Roosters", 100 - 25 * 3 % 4 #Outputs "Roosters" and then computes the number of hens.
print "Now I will count the eggs:" #Outputs Statement
print 3 + 2 + 1 - 5 + 4 % ... |
df338b907c86a5cf060b3d790900341974511a78 | Cyndrome/basic-image-filter | /main.py | 4,085 | 4.5625 | 5 | """
Image Filter application
Allows the user to upload an image and apply a filter to it. Offers a variety of filters to choose from.
Also allows the user to apply a custom filter by multiplying each of the RGB values of each pixel by their
desired number.
"""
DEFAULT_FILE = '/images/lil_josh.png'
from... |
c6aef8ce84837abd6d0f14441920d0319e17825d | kmulligan48/data440 | /mulligan-03/hw3.MLP.py | 911 | 3.578125 | 4 | import hw3_4_a_gendata
import numpy as np
import matplotlib.pyplot as plt
from sklearn.neural_network import MLPRegressor
from sklearn.model_selection import KFold
# generates data & split it into X (training input) and y (target output)
X, y = hw3_4_a_gendata.genDataSet(10000)
neurons = 100 # <- number of neurons ... |
0c939f6ecd611f50687f9b5ac5cea02817cbacad | heitorbelloni/project-euler | /006/006.py | 518 | 3.5 | 4 | import timeit
def timed_execution(function, *args):
start = timeit.default_timer()
function(*args)
end = timeit.default_timer()
return (end - start)
def main():
limit = 100
sum = 0
sum_of_squares = 0
for i in range(1, limit + 1):
sum += i
sum_of_squares += i * i
s... |
92550a4e557a58b430d696bcba2dff852560c278 | afcarl/machine-learning-python-examples | /supervised-learning/04-linear-regression-scoring.py | 1,138 | 4.1875 | 4 | # This example use the boston dataset to illustrate how to use the
# LinearRegression linear model
# Outcome: the regressor score and root mean square error
# Import necessary modules
from sklearn import datasets
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error
from skle... |
8b711a46d768d47667a3d8a212ffcf1499c8c2b6 | troj4n/Trees | /internal_nodes.py | 599 | 3.703125 | 4 | import timeit
#initialise node
class Node:
def __init__(self,data):
self.data=data
self.left=None
self.right=None
self.hd=None
def findInternalNodes(root):
if root==None:
return
if root.left!=None or root.right!=None:
print root.data,
findInternalNodes(ro... |
dc8c0b03cb455e1e2f00ebb0dc3917bcb39a74b6 | AiZhanghan/Leetcode | /code/19. 删除链表的倒数第N个节点.py | 531 | 3.671875 | 4 | # Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
dummy = ListNode(0)
dummy.next = head
first = dummy
for _ in range(... |
3a38d29b199c3bd39b604d21e98ce927f7d37b32 | pildurr/character_count | /character_counts/character_counts.py | 506 | 4.15625 | 4 | import string
promt = input("Enter a sentence: ")
upper = 0
lower = 0
digits = 0
punctuation = 0
for char in promt:
if char in string.ascii_uppercase:
upper += 1
elif char in string.ascii_lowercase:
lower += 1
elif char in string.digits:
digits += 1
elif char in string.punctua... |
e8a524a7d47db6a6e121ac600211b6330824f134 | league-python-student/level0-module0-Skywing609 | /_02_code_flow/_b_pentagon_crazy.py | 2,039 | 4.09375 | 4 | import random
import turtle
# Returns a random color!
from turtle import Turtle
def get_random_color():
return "#%06X" % (random.randint(0, 0xFFFFFF))
def get_next_color(i):
return colors[i % len(colors)]
# ====================== DO NOT EDIT THE CODE ABOVE ===========================
if __name__ == '__... |
2176ebc4d113be2ea61fed7915a7aa639b06a4ce | JiangHuYiXiao/PythonStudy | /Python基础&并发编程/day15/复习.py | 1,791 | 3.8125 | 4 | #-*- coding:utf-8 -*-
'''
一、迭代器
1、可迭代的对象调用了__iter__()方法后就是一个迭代器
2、可迭代的(Iterable)
可以被for循环的都是可迭代的
可迭代的内部一定包含__iter__()方法
可迭代协议
3、迭代器(Iterator)
迭代器内部包含__next__()和__iter__()方法
迭代器一定可迭代的,可迭代不一定是迭代器
迭代器协议
4、迭代器取值(__next__)
通过迭代器内置方法__next__()方法进行取值
二、生成器
1、生成器的本质是迭代器,具有迭代器的所有特性
2、生成器的生成方式有:
... |
38f905af22057f78b14a7034630d3819f0141dfa | mebaidoo/Maame-Esi-Baidoo-Codecademy-Project-7 | /Maame Esi Baidoo Medical Insurance Project Strings.py | 2,150 | 3.75 | 4 | medical_data = \
"""Marina Allison ,27 , 31.1 ,
#7010.0 ;Markus Valdez , 30,
22.4, #4050.0 ;Connie Ballard ,43
, 25.3 , #12060.0 ;Darnell Weber
, 35 , 20.6 , #7500.0;
Sylvie Charles ,22, 22.1
,#3022.0 ; Vinay Padilla,24,
26.9 ,#4620.0 ;Meredith Santiago, 51 ,
29.3 ,#16330.0; A... |
e9450ce39d3a3d6755f60a4615fdebf38a926a3a | piano-man/AI_codes | /SectionA/AI/Saboo/tic_tac_toe_alpha_beta.py | 3,827 | 3.65625 | 4 | import copy
def terminal_state(board,maxp):
for j in range(3):
c = 0
d = 0
for i in range(3):
if board[j][i]=='X':
c=c+1
elif board[j][i]=='O':
d=d+1
if (c==3 and maxp==1) or (d==3 and maxp==0):
re... |
cb80b4755d37b37f5e1c1a51cf1e0a519249dc07 | yujin0719/Problem-Solving | /프로그래머스/lv2.타겟넘버 bfs ver.py | 432 | 3.609375 | 4 | # 타켓넘버 BFS로
from collections import deque
def solution(numbers, target):
answer = 0
queue = deque([(0,0)])
while queue:
total, idx = queue.popleft()
if idx == len(numbers):
if total == target:
answer += 1
else :
number = numbers[idx]
... |
2a470020d036b28a1cbc3008e73a973d9fe045d7 | HullTed2/DEVASC | /printCircum.py | 649 | 4.625 | 5 | # Print the circumference for circles with a radius of 2, 5, and 7
radius1 = 2
radius2 = 5
radius3 = 7
# Formula for a circumference is c = pi * diameter
# Formula for a diameter is d = 2 * radius
pi = 3.14 # (Will hardcode pi in this example)
circumference1 = pi * radius1 * 2
print ("Circumference of a circle with a... |
6ced4ea71a352927d927365ec36852d4f9b10dd2 | abudish/Course_Materials_and_Certificates | /edX/Introduction into Programming - Python (MIT)/Lectures/Lec 11/L_11_Problem_5(hashSet).py | 2,550 | 4.03125 | 4 | class hashSet(object):
def __init__(self, numBuckets):
'''
numBuckets: int. The number of buckets this hash set will have.
Raises ValueError if this value is not an integer, or if it is not greater than zero.
Sets up an empty hash set with numBuckets number of buckets.
'''
... |
318383adb2f33d775a2a4761a83862ffe3eeca48 | stavitska/amis_python71 | /km71/Stavytska_Anastasia/task3.py | 760 | 3.59375 | 4 | def count(list,i,counter): #Використовуємо для знаходження кільк. ел. в групах
if i < len(list):
m = findGroup(list,i,0,1)
if counter < m[0]: #Знаходження найбільшої групи із всіх
counter = m[0]
return count(list,i + 1,counter)
else:
return counter
def findGroup(list,i,indicator,k): #Викори... |
57082a037caa7a78680d4a138d68133e0cea78b8 | PanaitNicolae/Exercitii | /FIRST_EXERCISES/Dec_with_param.py | 331 | 3.65625 | 4 |
def do_it_n_times(n):
def inner_function(func):
def wrapper_repeat():
for i in range(n):
func()
return wrapper_repeat
return inner_function
@do_it_n_times(7)
def count_to_five():
for i in range(5):
print(i+1, end = " ")
print()
coun... |
b8a896dd12f649d74c8602f97cf1b2fcbe6c55f4 | super-haribo/baekjoon | /baekjoon-20061.py | 3,147 | 4 | 4 | ########################################################################
# TREAT GREEN AND BLUE AREA EQUALLY AFTER ADDED BLOCK
# WHEN ADDING A BLOCK, ADDED POSITION CHANGED FOR BLUE AREA
# AND THE BLOCK WILL PLACE ON THE 2ND ROW
# 초록 영역과 파란 영역에 블록이 추가 된 이후의 처리는 동일하게 진행
# 블록이 각 영역에 추가될 때, 두번째 row (idx==1)에 포함되... |
c23279cd3a4d61d214f108a1bf6aa480c6c83caf | GZHOUW/Algorithm | /LeetCode Problems/Hash Table/Group Anagrams.py | 2,467 | 4.3125 | 4 | '''
Given an array of strings, group anagrams together.
Example:
Input: ["eat", "tea", "tan", "ate", "nat", "bat"],
Output:
[
["ate","eat","tea"],
["nat","tan"],
["bat"]
]
Note:
All inputs will be in lowercase.
The order of your output does not matter.
'''
class Solution:
'... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.