blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
10397f689131b3cc91b483f99c272137092c7296 | RupchandraKhatri/Binary-Adder | /19031837-Rup Chandra Khatri/Program/main.py | 1,525 | 3.96875 | 4 | from forInput import *
from conversion import *
from adder import *
while True:
x = input("Enter d for decimal number and b for binary number : ")
if x == "d":
num_1, num_2 = forDecimal()
bin_1 = decToBin(num_1)
bin_2 = decToBin(num_2)
output = binaryAdder(bin_1, bin_2)
elif x == "b":
st... |
5792465e13a4485ce3f717841876bf36be6bdfd7 | HariRaghavendarRaoBandari/SDN_Introduction_Course | /rot13.py | 1,790 | 3.8125 | 4 | #! /usr/bin/env python2
"""
A program which uses Caesar cipher encryption technique
"""
__author__ = "Hari Raghavendar Rao"
key_cipher = {'a': 'n', 'b': 'o', 'c': 'p', 'd': 'q', 'e': 'r', 'f': 's', 'g': 't', 'h': 'u',
'i': 'v', 'j': 'w', 'k': 'x', 'l': 'y', 'm': 'z', 'n': 'a', 'o': 'b', 'p': 'c',
... |
3052450e4cf2a9ac6b6c1720fc672d9db02c389e | Kaminaru/IN1000 | /Oblig6/egenOppgave6.py | 1,527 | 3.65625 | 4 | # Skriv en klasse Person med en konstruktør som tar imot navn og alder. I
# tillegg skal konstruktoren ha en tom liste hobbyer . Skriv en metode
# leggTilHobby som tar imot en tekststreng og legger den til i hobbyer -
# listen. Skriv ogsaa en metode skrivHobbyer . Denne metoden skal skrive alle
# hobbyen... |
b5e6c71ad16c7ca7ecd443292e198bd721e2a11a | Kaminaru/IN1000 | /Oblig6/person.py | 994 | 3.578125 | 4 | class Person:
def __init__(self,navn,alder):
"""
Oppretter person med gitt navn, alder og tomt liste med person hobbyer
"""
self._navn = navn
self._alder = int(alder)
self._hobbyer = []
def leggTilHobby(self,string):
"... |
65595417d9ce725772487268350acec959d2ab29 | Deepak11python/Python_Code | /ex4_table.py | 189 | 3.78125 | 4 | ## Date : 01-APR-2019
## TaBLE
##
##
##
##
var1 = input("Enter the number to print table")
i = int (1)
while (i < 11 ):
print (var1, "*", i, "===>", int (var1)*int(i) )
i = i + 1
|
5318ed8a85ade19c0fa758e1efa956420231e394 | eduardojordan/Practicas-Python | /KC_EJ12.py | 298 | 3.96875 | 4 | entrada = input ("Escribe una consonante o vocal en minuscula, que yo te digo que es:")
#Creo una tupla
vocales = ("a","e","i","o","u")
#Nota personal para referenciar la tupla se usa "in"
if entrada in vocales:
print ( entrada, "Es una vocal")
else:
print (entrada, "es una consonante")
|
d0b122d17dc975a88bc0d1c82c1b20a7e402094f | eduardojordan/Practicas-Python | /KC_EJ24.py | 574 | 4.09375 | 4 | diccionario= {}
while True:
nombre = input("Introduzca Nombre:")
notaUno = int(input("escriba Nota:"))
notaDos = int(input("escriba Nota:"))
notaTres = int(input("escriba Nota:"))
calculo = ((notaUno + notaDos + notaTres) / 3)
diccionario[nombre]=calculo
#Para presentar en orden descendiente por valor
... |
3589bebc609e72fb216f4558ce1c8611bd788784 | eduardojordan/Practicas-Python | /KC_EJ21.py | 191 | 4.0625 | 4 |
numero = input ("Introduce un numero ")
numero = int(numero)
rango = range(1,10)
for elemento in rango:
producto = numero * elemento
print ( numero,"X",elemento,"=", producto)
|
53af7ccbcc224abdd31f8f5b62b0b6cfccfabd1e | eduardojordan/Practicas-Python | /KC_EJ07.py | 353 | 3.78125 | 4 | numberOne = input ("Escribe una nota")
numberTwo = input ("escribe segunda nota")
numberThree = input ("escribe tercera nota")
numberOne = int(numberOne)
numberTwo = int(numberTwo)
numberThree = int(numberThree)
suma = (numberOne + numberTwo + numberThree)
calcula = (suma / 3)
if calcula < 4:
print ("No Apto" )
el... |
8675fdb97daffc1c5e503fb3bf61b44f731bbb6f | dariuscatinas/connect4 | /ConnectFour/GameSimulation.py | 7,252 | 3.5625 | 4 | from Domain import Square
from prettytable import PrettyTable
import copy
class GameSimulation:
""" The class which simulates the game """
def __init__(self):
self._board = [[Square() for j in range(7)] for i in range(6)]
def __str__(self):
t = PrettyTable(['0', '1', '2', '3',... |
409dabf119e7c50e6fb2bd0735faf27ddee0e43d | abhiunix/python-programming-basics. | /slicingAndIndexing.py | 1,071 | 4.5625 | 5 | #Quiz: Slicing Lists
#Select the three most recent dates from this list using list slicing notation.
#Hint: negative indexes work in slices!
eclipse_dates = ['June 21, 2001', 'December 4, 2002', 'November 23, 2003',
'March 29, 2006', 'August 1, 2008', 'July 22, 2009',
'July 11, 2010',... |
b05f1f14a338d93ebd569f7586339a26dc581d17 | abhiunix/python-programming-basics. | /NestedDictionary.py | 891 | 4.5625 | 5 | #Compound Data Structures
#We can include containers in other containers to create compound data structures.
#For example, this dictionary maps keys to values that are also dictionaries!
elements = {"hydrogen": {"number": 1,
"weight": 1.00794,
"symbol": "H"},
... |
7b147bd62620257bce5a9bf3df49ecce49c18ee0 | jalexanderqed/cs263-languages-project | /pi/python/pi.py | 262 | 3.578125 | 4 | def pi(iterations):
multiplier = 1.0
posOrNeg = -1.0
denom = 3.0
for i in range(iterations):
multiplier = multiplier + posOrNeg/denom
denom = denom + 2
posOrNeg = posOrNeg * -1
return 4.0 * multiplier
print pi(10000)
|
c21e59ca845109c0bc2b468655c054e605b6ce4a | rralcala/temp-control | /weather_service.py | 1,030 | 3.75 | 4 | import requests
def get_temp(api_key: str):
# base_url variable to store url
base_url = "http://api.openweathermap.org/data/2.5/weather?"
# Give city name
city_name = "5809844"
# complete_url variable to store
# complete url address
complete_url = base_url + "appid=" + api_key + "&id=" +... |
b5bda7bf6463f68663a823080679f63f44af3ae2 | KELLYCELIS/Curso-python | /ejercicios_secuenciales/poo/animales.py | 1,120 | 3.84375 | 4 | # class Mamiferos:
# def __init__(self, tipo_animal, genero, color, habitat, tipo_alimentacion):
# self.tipo_animal = tipo_animal
# self.genero = genero
# self.color = color
# self.habitat = habitat
# self.tipo_alimentacion = tipo_alimentacion
# class Carnivoros(Mamiferos):... |
d016a88feb7103aa588b724439fe3c16021cdbf7 | jkeupp/treegame | /treegame/example_hex.py | 4,973 | 3.546875 | 4 | import numpy as np
import pygame as pg
import hexy as hx
def make_hex_surface(color, radius, border_color=(100, 100, 100), border=True, hollow=False):
"""
Draws a hexagon with gray borders on a pygame surface.
:param color: The fill color of the hexagon.
:param radius: The radius (from center to any ... |
36a3b54dc9297b9520822785f4fc8b2dd365e4db | RileyWaugh/ProjectEuler | /Problem100.py | 1,789 | 3.609375 | 4 | #Problem: If a box contains 3 blue disc and 1 yellow disc, the probability of drawing two blue discs without replacement
# is (3/4)*(2/3) = 1/2. The same is true for a box with 15 blue discs and 6 yellow discs: the probability is (15/21)*(14/20) = 1/2
# for the first (integer) case where there are o... |
b6635fc1af31a8138fd5efb61bcd59c9f296f63d | RileyWaugh/ProjectEuler | /Problem2.py | 863 | 4.0625 | 4 | #Problem: find sum of all even fibonacci numbers under 4,000,000 (sum of 0,2,8,34, etc
#The key thing to realize is that even fibonacci numbers occur every three terms: (0),1,1,(2),3,5,(8),13,21,(34),
#this makes sense: even, odd, (even+odd)=odd, (odd+odd)=even, (odd+even)=odd, (even+odd)=odd, (odd+odd)=even, etc
d... |
8b0b953d4bd04f24bc5b7d68513bf29a7b12f45e | RileyWaugh/ProjectEuler | /Problem63.py | 1,035 | 4.09375 | 4 | #how many n-digits numbers are nth powers of integers? (e.g. 125 is a 3rd power and is 3 digits long)
import math
from time import time
def main():
#The Strategy: We use some maht to solve this. So what does n-digt mean, mathematically? It means this: if a number q is k-digts long,
#that means k-1 <= log10(q)... |
13e0fdb89416f54c31f6832a00cf0060f9163ae1 | RileyWaugh/ProjectEuler | /Problem60.py | 3,359 | 3.796875 | 4 |
import math
from time import time
def sieveOfEratosthenes(x):
#Produces a list of numbers under x, also tells if they are prime.
#this is to create an O(1) prime checker for primes under x
ar = []
flick = True
for i in range(-1,x):
ar.append(flick)
flick = not(flick)
ar[1] = T... |
ccb5f30d967166e3acbb32fe97b044d4be1b561d | RileyWaugh/ProjectEuler | /Problem38.py | 2,662 | 4.1875 | 4 | #Problem: Take the number 192 and multiply it by each of 1, 2, and 3:
# 192 × 1 = 192
# 192 × 2 = 384
# 192 × 3 = 576
# By concatenating each product we get the 1 to 9 pandigital, 192384576. We will call 192384576 the concatenated product of 192 and (1,2,3)
# The sa... |
92819abe5e0434066a5c4aede47e1306465df178 | RileyWaugh/ProjectEuler | /Problem31.py | 1,339 | 3.625 | 4 | #Problem: If the denominations of money (below 2 pounds) in England are 200p, 100p, 50p, 20p, 10p, 5p, 2p, and 1p (p is for pence),
# how many unique combinations of any amount of coins are there that add up to exactly 200p (2 pounds)?
import math
from time import time
def countCoinCombos(amt,coinvals,pro... |
23a07dc91802f7d9099642d1fdabe3ee765a6649 | RileyWaugh/ProjectEuler | /Problem66.py | 3,214 | 4.03125 | 4 | #Problem: consider the Diophantine equation x^2-Dy^2=1. for any non-square value of D, we can find the minimum x value that has a y value that makes the
# equation true. So for D=3: 2^2-3*1^2 = 1 and for D=6: 5^2-6*2^2 = 1.
# Find the value of D<=1000 that has the largest corresponding minimum x value... |
b78f065d093435bb649e089577e62753e52ebb25 | RileyWaugh/ProjectEuler | /Problem87.py | 1,676 | 3.578125 | 4 | import math
from time import time
def sieveOfEratosthenes(x):
#Produces a list of numbers under x, also tells if they are prime.
#this is to create an O(1) prime checker for primes under x
ar = []
flick = True
for i in range(-1,x):
ar.append(flick)
flick = not(flick)
ar[1] =... |
c8ac8e53dff00e51b3bad3d93fb52b9f199425cc | RileyWaugh/ProjectEuler | /Problem17.py | 2,607 | 3.90625 | 4 | #Problem: How many letters total are there in the numbers: "one", "two", ... "one hundred and fifty-seven", ... "nine hundred and niety-nine", "one thousand"?
# (ignore spaces and hyphens)
import math
#needless test -- thought I had wrong answer, but I just typed it in wrong
'''def countActualLetters(str):
sum = ... |
b1a9f3a21a4ea9cde0a941bcfb604b316245a121 | RileyWaugh/ProjectEuler | /Problem77.py | 2,858 | 3.734375 | 4 | import math
from time import time
def sieveOfEratosthenes(x):
#Produces a list of numbers under x, also tells if they are prime.
#this is to create an O(1) prime checker for primes under x
ar = []
flick = True
for i in range(-1,x):
val = 1
if flick:
val = 0
ar.a... |
86d20d433d268edd42ce2215352bd4e8039fdf1f | RushRpy/dice-rolling-simulator-python | /dice.py | 370 | 4.0625 | 4 | import random
def dice_simulate():
number = random.randint(1,6)
print(number)
while(1):
flag = str(input('Do you want to dice it up again? (enter y and if not enter n) '))
if flag == 'y':
number = random.randint(1,6)
print(number)
else:
print('Endi... |
6bb410d90ef446f77708aba9c90bad88ab7fedbf | appleface2050/sgg | /util/fun_.py | 947 | 3.578125 | 4 | import random
def shuffle(lis):
for i in range(len(lis) - 1, 0, -1):
p = random.randrange(0, i + 1)
lis[i], lis[p] = lis[p], lis[i]
return lis
def get_current_accuracy_by_distance(weapon, distance):
if not weapon:
return 0
else:
result = 0
if distance <= weapo... |
3971e774b14d1d8fbbf2051f980e1350b2828a89 | biradarganesh25/Gesture-Recognition | /create_dataset.py | 6,305 | 4.03125 | 4 | # Creates dataset
import sys,time
sys.path.append('/home/ganesh/PycharmProjects/Gesture To Text/lib/x64')
# Importing Leap SDK
import Leap
# The dataset contains the distance of all the bones in all the fingers
# to the palm center, the distance of thumbs to all the finger tips.
# This is all per frame. For one trai... |
59ebb38a65b2606e2d7bd15b70003aa00349c292 | wolaoa/leetcode | /python/leet_048.py | 1,060 | 3.625 | 4 | class Solution(object):
def rotate(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: void Do not return anything, modify matrix in-place instead.
"""
n = len(matrix) - 1
middle = n / 2 + 1
# 注意区分奇数阶 和偶数阶的区别
if n % 2 == 0:
# 奇数阶,防止对称轴... |
9470f2e5aba54612531fac380adcf231a8673e25 | Thokozani51/Compulsory-Task-20 | /task_manage.py.py | 7,610 | 4.25 | 4 | from datetime import date #importing of an automatic setting of the current date
user_name = ""
user_name = input("Enter your user_name: ") #user_name input
user_password = input("Enter your user_password: ") #user_password input
while True:#using the while loop for the process of noting messages of when th... |
2bd92a4ab17aa3dc7d2e00d7c8c1274dc1bb798d | Jonayne/Cryptography_Algorithms | /Lenstra.py | 5,057 | 3.703125 | 4 |
import random
import math
def mcd(a, b):
'''
Función que regresa el máximo común divisor entre a y b.
'''
if abs(a) < abs(b):
return mcd(b, a)
while abs(b) > 0:
_,r = divmod(a,b)
a,b = b,r
return a
def inverso_modular(a, b):
'''
Función que realiza el algoritmo extendid... |
62ff78da87123bc0fd1f3ffd300669e533954c91 | josenavarro-leadps/class-sample | /drawColorGrid.py | 683 | 3.75 | 4 | import turtle
def drawSquare(myTurtle):
myTurtle.forward(20)
myTurtle.right(90)
myTurtle.forward(20)
myTurtle.right(90)
myTurtle.forward(20)
myTurtle.right(90)
myTurtle.forward(20)
def drawSquareColor(myTurtle):
count = 0
while count < 5:
myTurtle.color('red')
drawSquare(myTurtle)
... |
9d5ef84788ea1072ab6b6ad00e7828057a13be31 | josenavarro-leadps/class-sample | /5-4WritingHTML/primeLister.py | 300 | 3.765625 | 4 | def isPrime(myNum):
for numbers in range(2,myNum):
if myNum % numbers == 0:
return False
return True
List = []
for numbers in range (2,10000):
n = isPrime(numbers)
if n == True:
List.append(numbers)
myFile = open("thePrimes.txt", "w")
myFile.write(str(List))
myFile.close()
print(List)
|
9effe53d3e991ea2b0c6eb4d6679f9b07049c8fe | Akosua19/Python-Projects | /atm_program.py | 2,414 | 3.890625 | 4 | class ATM:
def _init_(self, name, balance, pin):
self.name = name
self.__balance = balance
self.__pin = pin
def withdraw(self, amount):
self.__balance -= amount
def get__balance(self):
return self.__balance
def get__name(self):
return self.__name
... |
e3baeaba7dcd602346aa7b2eae903add6dbbe001 | St1904/GB_python_2 | /lesson_1/work_6.py | 608 | 3.671875 | 4 | # Создать текстовый файл test_file.txt, заполнить его тремя строками: «сетевое программирование», «сокет», «декоратор».
# Проверить кодировку файла по умолчанию. Принудительно открыть файл в формате Unicode и вывести его содержимое.
import chardet
with open('test_file.txt', 'rb') as f:
coding = chardet.detect(f.r... |
95ca97b668727d8571a3ac657038b90ad8727053 | nicmolica/snarl | /Snarl/src/Game/turnorder.py | 2,513 | 3.90625 | 4 | from .actor import Actor
class Turnorder:
"""Keeps track of a turn ordering. Contains methods to add, remove, and get the next
entity in the order.
"""
def __init__(self, init_order: list):
""" Creates a Turnorder object, which is used by the Gamemanager to handle
the logic behind ensur... |
b8c7da34227a5fedd478652b6a63ca4854eb553d | nicmolica/snarl | /Snarl/src/Game/utils.py | 708 | 4 | 4 | """This file holds utility methods. When adding functions to this file, please be very thorough
with the docstrings.
"""
def grid_to_string(grid: list) -> str:
"""Given a 2D list of characters, return a string of the characters in grid form.
Taken from
https://stackoverflow.com/questions/17870612/prin... |
35d565b5d49200e957d02d803ab4625e38698b06 | mryanjulian/Programming-Portfolio | /Cracking_the_Coding_Interview/CCI_5.7.py | 119 | 3.53125 | 4 | import sys
n = int(sys.argv[1],2)
def swap(n):
return ((n&0xAAAAAAAA)>>1)|((n&0x55555555)<<1)
print bin(swap(n)) |
e21013b4b440237e6f0f831bf7c98ee377f73502 | mryanjulian/Programming-Portfolio | /Project_Euler/PE-Problem-72.py | 462 | 3.546875 | 4 | #This program counts the number of reduced proper fractions n/d with d<=1000000.
f = open("primes.txt")
primes = [int(prime) for prime in f.readlines()]
f.close()
def phi(n):
i = 0
m = n
factors = []
while m>1:
if m%primes[i] == 0:
factors.append(primes[i])
while m%primes[i] == 0:
m = m/primes[i]
i+... |
510cb516f184cc089af7d9d529da918138242d5d | mryanjulian/Programming-Portfolio | /Project_Euler/PE-Problem-92.py | 499 | 3.734375 | 4 | #This program computes the number of number chains formed by iterating a function that sums the squares of the digits of each number that end at the value 89.
#Note that any such number chain eventually arrives at 1 or 89.
def chain(n):
next = 0
for i in range(0,len(str(n))):
next += (n%10)**2
n = n/10
return ... |
95601affbced03705ab36699eccd3e543d943658 | mryanjulian/Programming-Portfolio | /Project_Euler/PE-Problem-9.py | 317 | 3.59375 | 4 | #There exists a unique pythagorean triple such that a^2 + b^2 = c^2 and a + b + c = 1000
#This program computes this triple and prints the product abc
for a in range(1,1001):
asquared = a**2
for b in range(a+1,1001):
bsquared = b**2
c = 1000-a-b
if c>b and asquared+bsquared == c**2:
print a*b*c
break
|
337badd9ea1320483c0e2c711f8705a453316494 | mryanjulian/Programming-Portfolio | /Project_Euler/PE-Problem-23.py | 679 | 3.5625 | 4 | #This problem finds the sum of all positive integers that cannot be written as the sum of two abundant numbers, where abundant numbers have the property that the sum of their proper divisors is larger than the original number.
#Construct a list of abundant numbers:
abundant = []
for i in range(2,28124):
divisorsum = ... |
5749e388dc2fd333fb8bcf18a2c27e8b1ac48344 | mryanjulian/Programming-Portfolio | /Cracking_the_Coding_Interview/CCI_2.7.py | 1,200 | 3.703125 | 4 | import sys
import LinkedList
list1 = sys.argv[1].split()
root1 = LinkedList.Node(list1[0])
for i in range(1,len(list1)):
root1.append(list1[i])
list2 = sys.argv[2].split()
root2 = LinkedList.Node(list2[0])
for i in range(1,len(list2)):
root2.append(list2[i])
def prll(root):
curr = root
ll = ''
whi... |
c41b58e84570b0b2d5620be1955f0d4109691996 | mryanjulian/Programming-Portfolio | /Project_Euler/PE-Problem-27.py | 918 | 3.609375 | 4 | #This program determines the product of the coefficient, a and b, of the quadratic n^2+an+b that produces the largest number of primes for consecutive values of n, starting with n = 0, for |a|<1000 and |b|<=1000.
f = open("primes.txt")
primes = [int(prime) for prime in f.readlines()]
f.close()
primes = primes[0:5000]... |
9e91d6a7c0858b9160f8a8c305a21ca5566af7b4 | akilobane/PythonBeginnerProjects | /Calc3.py | 1,945 | 4.15625 | 4 | #My calculator version 3
import math
def addition(x, y):
sum = x + y
return sum
def subtract(x, y):
sum = x - y
return sum
def multiply(x, y):
sum = x * y
return sum
def divide(x, y):
sum = x / y
return sum
def square(x):
sum = math.sqrt(x)
return sum
... |
456e6b326589f65f95c9d36c9518e85d7c4a9788 | Caden4357/bootcamp-public- | /functions_basic2.py | 4,550 | 4.1875 | 4 | #Create a function that accepts a number as an input. Return a new list that counts down by one, from the number (as the 0th element) down to 0 (as the last element).
#Example: countdown(5) should return [5,4,3,2,1,0]
def countdown(num):
my_list = []
for num in range(num,-1,-1):
my_list.append(num)
... |
5d86d2d6f1ab8859f5ffb9d804a915b0006b3747 | d3239939/mycode | /if-test/if-hostname2.py | 364 | 3.8125 | 4 | #!/usr/bin/env python3
#hostname = 'MTG'
hostname = input("What is your hostname? ")
hostname = hostname.upper()
if hostname == 'MTG':
print('The hostname was found to be MTG.')
print('The hostname matches expected config.')
else:
print('The hostname does not match the expected config.')
print('Exiting the sc... |
474bd058879d720da8cbd347301344781bde40f4 | Tuiba/Finding-the-second-largest-number-in-a-list | /Finding the second largest number in a list.py | 173 | 4.125 | 4 | l=[]
n=int(input("Enter number of elements:"))
for i in range(1,n+1):
b=int(input("Enter element:"))
l.append(b)
l.sort()
print("Second largest element is:",l[n-2])
|
1b37a26f495de9119db6d1ab47a6e8b725b7d3de | AlexVillagran/curso-basico-python | /Ej7-Listas.py | 1,354 | 4.28125 | 4 | demo_lista = [1, 'Hola', 1.34, True , [1, 2, 3]]
colores = ['red', 'green', 'blue']
numbers_list = list((1, 2, 3, 4)) # Pasamos como argumento una tubla al metodo list
print (numbers_list)
print (type(numbers_list))
r = list(range(1,11)) #Formas de crear listas numericas
print(r)
print(type(colores))
#print(dir(colo... |
c51a018629cee035eb9aa76f22b15b2b08e7eac0 | itwebMJ/algorithmStudy | /Lv0__1_to_15/13.자릿수더하기.py | 316 | 3.546875 | 4 | '''
자릿수 더하기
자연수 N이 주어지면, N의 각 자릿수의 합을 구해서 return 하는 solution 함수를 만들어 주세요.
예를들어 N = 123이면 1 + 2 + 3 = 6을 return 하면 됩니다.
'''
def solution(n):
answer = 0
for i in str(n):
answer += int(i)
return answer
|
853ef4e7b04231817e46c31dfc9e88b1555506c2 | itwebMJ/algorithmStudy | /Lv0__16_to_30/16.py | 646 | 3.515625 | 4 | '''
문제 설명
문자열 s의 길이가 4 혹은 6이고, 숫자로만 구성돼있는지 확인해주는 함수, solution을 완성하세요.
예를 들어 s가 "a234"이면 False를 리턴하고 "1234"라면 True를 리턴하면 됩니다.
제한 사항
s는 길이 1 이상, 길이 8 이하인 문자열입니다
'''
def solution(s):
answer = True
x=0
answer = (len(s) ==4 )or (len(s)==6)
try:
for i in range(0, len(s)):
if type(int(s[... |
b0547ccbd9d07fd30bba6dc2ce8e695a930cc0fc | itwebMJ/algorithmStudy | /Lv0__1_to_15/15.정수 제곱근 판별.py | 554 | 3.734375 | 4 | '''
정수 제곱근 판별
임의의 양의 정수 n에 대해, n이 어떤 양의 정수 x의 제곱인지 아닌지 판단하려 합니다.
n이 양의 정수 x의 제곱이라면 x+1의 제곱을 리턴하고,
n이 양의 정수 x의 제곱이 아니라면 -1을 리턴하는 함수를 완성하세요.
'''
#Math.sqrt(n) 제곱근 구하는 함수
#math.pow(n, 2) n의 2 제곱
import math
def solution(n):
answer = math.sqrt(n)
if answer % 1 == 0:
answer = math.pow(answer+1, 2)
else... |
f00084596d4ea02e79f82897b82e0737ae7b8415 | rainmayecho/applemunchers | /28.py | 232 | 3.671875 | 4 | import time
time.clock()
total = 0
for x in range(0,501):
if x == 0:
total += 1
else:
n = 2*x
m = (2*x+1)**2
total += 4*m-6*n
print total
print str(time.clock()*1000)+"ms"
|
42ff4f19e0406b63a7a99c72eae244c2163bfd49 | rainmayecho/applemunchers | /131.py | 530 | 3.515625 | 4 | import time
def is_prime(n):
if not n % 2:
return False
if not n % 3:
return False
for m in xrange(6,int(n**.5)+1, 6):
if not n % (m+1):
return False
if not n % (m-1):
return False
return True
time.clock()
cubes = [n**3 for n in xrange(1,600)]
c... |
3c558e4ab8bc13b30600b48694e98fee665118ad | rainmayecho/applemunchers | /7.py | 342 | 3.78125 | 4 | def create_primes():
primes = []
for x in range(2,1000000):
if is_prime(x):
primes.append(x)
print primes[10000]
def is_prime(a):
if a==2:
return True
if a<2:
return False
for x in range(2,a**.5+1):
if a%x==0:
return False
else... |
cc0cc470bcc182707bee2072e5007b305ad3d8c1 | rainmayecho/applemunchers | /10.py | 320 | 3.90625 | 4 | import math
def is_prime(a):
if a==2:
return True
for x in range(2,a**.5+1):
if a%x==0:
return False
else:
return True
def sum_prime():
sumPrime = 0
for x in range(2,2000):
if is_prime(x):
sumPrime += x
print sumPrime
|
954823ccb8faba984cecaa8beed4c7b73c13661c | rainmayecho/applemunchers | /5.py | 554 | 3.875 | 4 | def create_primes():
primes = []
for x in range(2,20):
if is_prime(x):
primes.append(x)
return primes
def is_prime(a):
if a==2:
return True
if a<2:
return False
for x in range(2,a**.5+1):
if a%x==0:
return False
else:
... |
e7e5c5a12d2160bfbdb3aa8eb09df7b667911baf | rainmayecho/applemunchers | /4.py | 381 | 3.703125 | 4 | def func():
i=900
palindrome = 0
for x in range(i,1000):
for y in range(i+1,1000):
if is_palindrome(str(x*y)) and x*y > palindrome:
palindrome = x*y
return palindrome
def is_palindrome(input):
string = list(input)
string.reverse()
if list(input) == stri... |
3186ac5202d6f2bf0832eef87b83f5c158d56833 | kiana-mohseni-hs/complete-python-course | /Exercise1/quiz.py | 1,010 | 3.96875 | 4 | """
sample `questions.txt` file:
1+1=2
2+2=4
8-4=4
task description:
- read from `questions.txt`
- for each question, print out the question and and wait for the user's answer
for example, for the first question, print out: `1+1=`
- after the user answers all the questions, calculate her score and write it to the `... |
3b9c1acba3741393a28b585c1c09cd59d47ef9e2 | VladGPine/stepik_python_course | /lesson2_3_step7.py | 266 | 3.65625 | 4 | """
Вычислить среднее арифметическое чисел в диапазоне [a, b],
если эти числа кратны 3
"""
a, b = (int(i) for i in input().split())
c = [i for i in range(a, b + 1) if i % 3 == 0]
print(sum(c) / len(c))
|
517367bd62df1419c40e2bb2e85c20983eb47c36 | VladGPine/stepik_python_course | /lesson2_6_step9.py | 975 | 3.765625 | 4 | """
Напишите программу, которая считывает список чисел lstlst из первой строки и число xx из второй строки, которая
выводит все позиции, на которых встречается число xx в переданном списке lstlst.
Позиции нумеруются с нуля, если число xx не встречается в списке, вывести строку "Отсутствует" (без кавычек, с
большой бук... |
ba08107ef17c73976f5304635cefe70006dcc090 | anis016/Web-Scraping | /chapter_1/beautifulsoup.py | 348 | 3.5 | 4 | from urllib.request import urlopen
from bs4 import BeautifulSoup
html = urlopen("http://www.pythonscraping.com/pages/page1.html")
# default parse is "html.parser"
bsObj = BeautifulSoup(html.read(), "html.parser")
# below all the 3 produces same output
print(bsObj.h1)
print(bsObj.body.h1)
print(bsObj.html.body.h1) # ... |
019a6539665d5a487e6fc7a43ccb6604abdf2637 | 14masterblaster14/PythonTutorial | /P1_basics.py | 17,563 | 4.46875 | 4 | #############################
# 1 # Python Indentations
#############################
print("Hello, World!") # O/P : Hello, World!
if 5 > 2:
print("Five is greater than two!") # O/P : Five is greater than two!
"""
if 5 > 2:
print("Five is greater than two!")
O/P :
It will give error
File "Hello.py... |
d14503ec2152b8c379e6ed1d5240f6a6b3d0fe10 | denissemo/Labs | /Laba_8_GItHub/laba_8_3.3.1_(b).py | 1,592 | 3.5 | 4 | # Семенов Денис КНІТ 16-А
"""Условие: бинарный поиск"""
from timeit import timeit
setup = '''
import numpy as np
from random import randint
while True:
try:
l_arr = int(input('Please enter length of array: '))
if l_arr < 1:
print('Please enter correctly number\\n')
continue... |
f9d8d53931f20aa87bbfabfaaba8d2efb1976da3 | denissemo/Labs | /Laba_8_GItHub/laba_8_11(b).py | 1,723 | 3.828125 | 4 | # Семенов Денис КНІТ 16-А
"""Условие: элементы линейного массива циклически сдвиньте на к позиций влево
(без выполнения лишних сдвигов)"""
import numpy as np
def shift_a(a, k):
while k != 0:
m = a[0]
for i in range(len(a) - 1):
a[i] = a[i + 1]
a[len(a) - 1] = m
k -= 1
... |
54148509ccb2e60c11b3344f37ccdec191107ce9 | denissemo/Labs | /Laba_8_GItHub/laba_8_11(a).py | 1,705 | 3.578125 | 4 | # Семенов Денис КНІТ 16-А
"""Условие: поверните квадратный массив на 90 грудусов по часовой стрелке."""
import numpy as np
while True:
try:
while True:
n = int(input('Input tapes: '))
if n < 2:
print('input correct number\n')
continue
brea... |
3167b825929f1a97e2da9cdd77b614bfafa7d307 | Aleksi-Karhu/Distributed-systems-final-project | /client.py | 2,161 | 3.5 | 4 | import xmlrpc.client
import time
# Sources:
# https://www.mediawiki.org/wiki/API:Info
# https://docs.python.org/3/library/multiprocessing.html#managers
# https://github.com/rklabs/WikiRacer/blob/master/wikiracer.py
# https://github.com/stong1108/WikiRacer/blob/master/wikiracer_threaded.py
# https://www.kite.co... |
83bd036213462622efd26e6141de046ebbfc9806 | rynsollars/Project-Euler | /problem 9.py | 678 | 4.25 | 4 | __author__ = 'ryansollars'
# A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
#
# a2 + b2 = c2
# For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2.
#
# There exists exactly one Pythagorean triplet for which a + b + c = 1000.
# Find the product abc.
import time
t1 = time.time()
prod = 1
for a i... |
f45cd8d5e15748f8cf4c2c2b28a3071bf55f4ef8 | Psyborgg/To-Do | /tododb.py | 823 | 3.671875 | 4 | import sqlite3
class Database:
def __init__(self, db):
self.db = ""
self.conn = sqlite3.connect(db)
self.cur = self.conn.cursor()
self.cur.execute("CREATE TABLE IF NOT EXISTS todo (id INTEGER PRIMARY KEY, tasks text)")
self.conn.commit()
def insert(self, tasks):
... |
104841c69732221a6ae9b538d7d949a1b9cc0c75 | vardakisDev/Python_1 | /Exercise8/traffic_lights.py | 2,101 | 4 | 4 |
import random
class Light:
def __init__(self , name , numberofcars , color):
self.name = name
self.numberofcars = numberofcars
self.color =color
def return_green(a , b ,c):
if a.numberofcars<b.numberofcars:
if b.numberofcars>c.numberofcars:
b.color="green"
... |
8091f084741f9360833fb0045f7ad518fd9771c9 | civic/CodeEval | /easy/017_HappyNumbers/happynum.py | 431 | 3.59375 | 4 | import sys
def is_happy_num(n, history=None):
sumsq = sum([int(d)**2 for d in str(n)])
if sumsq == 1:
return 1
if history == None:
history = set()
if sumsq in history:
return 0 #cycle loop
else:
history.add(sumsq)
return is_happy_num(sumsq, history)
with o... |
db0b994c12f5244022f92841e810c07ec8372495 | KeerthiGL/training-class | /sums.py | 163 | 3.828125 | 4 | def sum(x, y):
sum = x + y
if sum in range(15, 20):
return 20
else:
return sum
print(sum(10, 6))
print(sum(10, 2))
print(sum(10, 12))
|
d1d732f8d6050733a970fd5a28a83e56a3a59a3f | KeerthiGL/training-class | /pswd.py | 434 | 3.53125 | 4 | pasw='PAssword1!!'
S = ['!','@','#','$','%','~','`','^','&','*','(',')','_','+','=','-']
upper,lower,number,special = 0,0,0,0
for n in pasw:
if n.islower():
lower=1
if n.isnumeric():
number=1
if n.isupper():
upper+=1
if n in S:
special+=1
if len(pasw) >= 6 and len(pasw... |
aba2e6b394a8238c7a0bda6db01aa892c40b1e5d | KeerthiGL/training-class | /yes or no.py | 141 | 4 | 4 | Join = input('Would you like to join me?')
if Join == 'yes' or 'Yes':
print("Great," + myName + '!')
else:
print ("Sorry for asking...")
|
efd58e40e9c49c49284bcfccf08898fcf7ddef3b | KeerthiGL/training-class | /lower to upper.py | 228 | 4.3125 | 4 | print("Enter 'x' for exit.");
string = input("Enter any string to convert in uppercase: ");
if string == 'x':
exit();
else:
string_in_uppercase = string.upper();
print("\nString in Uppercase =",string_in_uppercase);
|
953130e6f31ba72c0132ac9cd7f197d1a3329d19 | ahwi/PythonNote | /code/learnPython/chapter38/classError2.py | 695 | 3.515625 | 4 | class Tracer:
def __init__(self, aClass):
self.aClass = aClass
def __call__(self, *args, **kwargs):
self.wrapped = self.aClass(*args, **kwargs)
return self
def __getattr__(self, item):
print(f"Trace: " + item)
return getattr(self.wrapped, item)
@Tracer
class Pers... |
e8ff8297c8d6f768821977c89b92a327d8e5c35d | ahwi/PythonNote | /code/fluentPython/chapter_19/Class_19_3_1.py | 2,291 | 4.03125 | 4 | class Class: # 定义Class类,这个类有两个类属性:data数据属性和prop特性
data = 'the class data attr'
@property
def prop(self):
return 'the prop value'
def main():
obj = Class()
print(vars(obj)) # vars函数返回obj的__dict__属性,表明没有实例属性
print(obj.data) # 读取obj.data,读取的是Class.data的值
obj.data = 'ba... |
a5faa938eba9c4b46de093bfc68d2815567cf56e | ahwi/PythonNote | /code/fluentPython/chapter_14/14_3_testIterator.py | 819 | 3.625 | 4 | from collections import Iterable, Iterator
from abc import abstractmethod
class MyIterator(Iterable):
__slots__ = ()
@abstractmethod
def __next__(self):
raise StopIteration
@classmethod
def __subclasshook__(cls, C):
if cls is MyIterator:
if (any("__next__" in B.__dict... |
ccdfc0cb7da23c0f5340f3b7300806f61ec4566e | geraldung/SlytherLisp | /slyther/repl.py | 780 | 3.765625 | 4 | def repl(intepreter):
"""
Take an interpreter object and give a REPL on it. Should not return
anything: just a user interface at the terminal. For example::
$ slyther
> (print "Hello, World!")
Hello, World!
NIL
> (+ 10 10 10)
30
When the user presses ^D ... |
7126ee6db07e7bf3b3dd96b78e11f1bdcda928c3 | osmart/Yatzy-Refactoring-Kata | /python/yatzy.py | 7,404 | 4 | 4 | from collections import Counter
class Yatzy:
"""
Class to score Yatzy simple dice game. This class interface
is deprecated and will be dropped in a future release. Please
update to use the YatzyClean class.
See https://github.com/emilybache/Yatzy-Refactoring-Kata
"""
def __init__(self, d... |
3b533a7a978df2d1cde42f21e9eb725a48a1367f | vishnkr/DS_and_ALGS | /Leetcode/Easy/containsDuplicates.py | 432 | 3.609375 | 4 | #problem: https://leetcode.com/problems/contains-duplicate
class Solution(object):
def containsDuplicate(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
dict = {}
if len(nums)==0:
return False
for i in nums:
if i in d... |
a30657afa493f73231b7fae887813f7006058e64 | vishnkr/DS_and_ALGS | /Leetcode/Easy/remove_ll_duplicates.py | 462 | 3.515625 | 4 | class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def deleteDuplicates(head):
if not head:
return
current = head
prev = None
while current!=None:
if prev!= None and current.val == prev.val :
prev.next = current.next
current... |
2c7b443390bcdd8fe9b19177d24f6ca7fd7e4983 | vishnkr/DS_and_ALGS | /Leetcode/Medium/add-twoNums.py | 861 | 3.765625 | 4 | #problem: https://leetcode.com/problems/add-two-numbers/
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
if not l1 or not l2:
r... |
41f216059f782d55fd57be131566f2c5d9a4b25e | Gonzalo77-hub/poo-python | /Usuario.py | 1,448 | 3.8125 | 4 | class User: # aqui está lo que tenemos hasta ahora
def __init__(self, name, email):
self.name = name
self.email = email
self.account_balance = 0
# agrega el método deposit
def make_deposit(self, amount): # toma un argumento que es el monto del depósito
self.account_balance ... |
63afd17a5286e8679c954583cfce8b6330246312 | adanvr/python_morsels | /float_range.py | 890 | 3.796875 | 4 | class float_range:
def __init__(self, start, stop, step):
if stop == None:
start, stop = 0, start
self.start = start
self.stop = stop
self.step = step
def __iter__(self):
x = self.start
if self.step > 0:
while x < self.stop:
... |
640e73eefe6080d08bc704b235641266662dff37 | adanvr/python_morsels | /point_morsels.py | 1,247 | 3.859375 | 4 | class Point:
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
def __eq__(self, anotherpoint):
return self.x == anotherpoint.x and self.y == anotherpoint.y and self.z == anotherpoint.z
def __add__(self, anotherpoint):
new_x = self.x + anotherpoint... |
a1ca5c34aad668ff6dc44ba20bebd6acb1d5e988 | adanvr/python_morsels | /deep_add.py | 750 | 3.84375 | 4 | from typing import List
def flatten(l : list) -> list:
for item in l:
if hasattr(item, "__iter__") and not isinstance(item, str):
for x in flatten(item):
yield x
else:
yield item
def deep_add(L : list, start = 0) -> int:
''' Function takes a nested list ... |
6bc39e1a8e87aed62bf259ef30abbec48aaaf689 | Kshitij-Jha/Hangman | /Hangman.py | 2,525 | 4.125 | 4 | # -*- coding: utf-8 -*-
"""
@author: KSHITIJ
Credits: Web Dev Junkie: "youtube.com/channel/UCsrVDPJBYeXItETFHG0qzyw"
https://github.com/chrishorton
"""
#functions
def pr(A):
for i in A:
print(i," ",end = "")
#STEP 1: setup the word and hidden list
word = list("mediterranean".up... |
28a462ebc5aa7480d25368b5ae2dbc0cbd221614 | letroot/python-fp | /3_higher_order.py | 4,992 | 3.859375 | 4 | """Demonstrating higher-order functions
Where we make the case for eliminating the
iterate-mutate anti-pattern and use
higher-order functions instead.
"""
import csv
import random
from functools import partial, reduce
from math import hypot
from operator import add, mul
from pprint import pprint
# What are higher-or... |
627aaea3eeb49c2f3319640656509ce5e4cf4852 | dinhlong1/BaiTap | /82.py | 224 | 3.953125 | 4 | a=float(input("Nhap a"))
b=float(input("Nhap b"))
c=float(input("Nhap c"))
if a>=b:
if a>=c:
print(a)
else:
print(c)
elif b>=a:
if b>=c:
print(b)
else:
print(c)
|
4dd6e5a8904c45b7342bdb2137aadd075cbbbb7d | dinhlong1/BaiTap | /115.py | 1,030 | 3.765625 | 4 | # Bài 115: Viết chương trình nhập họ tên, điểm toán, điểm văn của 1 học sinh. Tính điểm trung bình và xuất ra kết quả
#Hàm kiểm tra điểm nhập vào
def is_score(value):
return value.isdigit() and float(value).is_integer() and 10 >= int(value) >= 0
#Hàm tính điểm trung bình của 2 môn
def average_two_score(name, firs... |
50d61c8e93d66f688756eafa9c81c76bdd035652 | dinhlong1/BaiTap | /476.py | 1,535 | 3.9375 | 4 | #Bài 476: Hãy khai báo kiểu dữ liệu biểu diễn khái niệm hỗn số trong toán học và
# định nghĩa hàm nhập, hàm xuất cho kiểu dữ liệu này
import mangsonguyen as sn
class mixedNumbers():
def __init__(self,integer,numerator,denominator):
self.integer = integer
self.numerator = numerator
self.deno... |
30f918c560858354792390fa9db8d38822c90f88 | dinhlong1/BaiTap | /113.py | 1,154 | 3.59375 | 4 | #Bài 113: Lập chương trình tính sin(x) với độ chính xác 0.00001 theo công thức:
# Sin(x) = x – x^3/3! + x^5/5! + … + (-1)^n . x^2n + 1/(2n + 1)!
#Hàm kiểm tra giá trị có phải là số hay ko
def is_number(value):
return value.isdigit() and float(value).is_integer() and int(value) >= 0
# Giải hàm số Sin(x) = x – x^3... |
f9b31c92339fbe3204dff55bf5c14401d11b85e8 | dinhlong1/BaiTap | /117.py | 952 | 3.890625 | 4 | # Bài 117: Viết chương trình nhập n và tính tổng S(n) = x + x^2 + x^3 + … + x^n
def is_number(value):
return value.isdigit() and float(value).is_integer() and int(value) > 0
# Tính hàm S(n) = x + x^2 + x^3 + … + x^n
def caculate_sum( target_number , x):
#Gắn tống bằng biến sum
Sum = 0
#Dùng vòng lặp... |
ef0d78edab9a08b85fe411ab5772095a1a3ab215 | dinhlong1/BaiTap | /127.py | 1,538 | 4.03125 | 4 | #Bài 126: Viết hàm tính tổng các giá trị âm trong mảng 1 chiều các số thực
#Hàm kiểm tra đây có phải là số thực
def is_float(value):
try:
float(value)
return True
except ValueError:
return False
#Hàm kiểm tra đây có phải là số nguyên
def is_option(value):
try:
int(value)
... |
7ab91918b1c1fbdfd24d81691326c459ccca4428 | dinhlong1/BaiTap | /90.py | 588 | 3.671875 | 4 | #Bài 90: Viết chương trình tìm số nguyên dương m lớn nhất sao cho 1 + 2 + … + m < N
def FindLargestInteger(Number):
Sum = 0
integerNumber = 0
while Sum<Number:
integerNumber = integerNumber + 1
Sum = Sum + integerNumber
return integerNumber
if __name__ == '__main__':
n = input("Nh... |
9f80190b7df7df98b771e77f35595a5ec126f8f0 | dinhlong1/BaiTap | /479+486-492.py | 2,469 | 3.53125 | 4 | # Bài 479: Hãy khai báo kiểu dữ liệu biểu diễn khái niệm đơn thức P(x) = ax^n trong toán học và
# định nghĩa và định nghĩa hàm nhập, hàm xuất cho kiểu dữ liệu này
import mangsonguyen as sn
class monomial():
def __init__(self,a,n):
self.a = a
self.n = n
def set_a(self,a):
self.a = a
... |
b87b9118f0a429f3ad3562e843e734a8736c36c7 | henriquekr/NB_classifier | /ecommerce_NB_classifier.py | 8,918 | 3.5 | 4 | # Title: NB Classifier for e-commerce detection
# Language: Python (3.x)
# Author: Henrique Kokron Rodrigues
#
# Description: This script takes as input a list of urls with labels indicating whether
# it's an e-commerce or not. It then scrapes the websites to get the visi... |
ea4fabae95412949c357618936140258a72b82bc | shruti280401/python | /day2.py | 181 | 3.875 | 4 | try:
n =float(input("Enter ur height in feet:"))
if n >= 6.5:
print("allowed")
else:
print("not allowed")
except ValueError:
print("its a string")
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.