blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
0809fca93211dc2be8b4d69d394e4100679cf7df | rhyshardwick/maths | /numbers/sum_of_amicables.py | 754 | 4.34375 | 4 | print("Calculates the sum of amicables up to n")
n = int(input("Enter n: "))
# Flowchart
# calculate the sum of the proper divisors
# test to see if the sum fo the proper divisors of the result is the same
# test to ensure the numbers are not the same
# if not, add to list
# sum list and print sum
def sum_of_divisors... |
d962de0a283f1f7d7c8533c3fbe24c35e6594347 | shreyaswaikars/ATAdemoPOM | /demoPython.py | 1,379 | 4.03125 | 4 | # Variable
# number=15
# numberFloat=19.53
# nameString="ATAVirtualMeetup2"
# flagChar='Y'
# bool=True
# print(number, numberFloat, nameString, flagChar, bool)
# Lists
# fruits = ["Cherry", "Apple", "Banana", "Mango", "Orange", "Pear", "Grapes"]
# years = [3, "1998", 12.43, 2012, "2015"]
# print(fruits)
# ... |
0f53abb46ca674a4162d359d65bb2e43314f598b | farahalomar/python | /list_dicts_task.py | 954 | 3.828125 | 4 | print("Welcome to The Special Recruitment Program, please answer the following questions:\n")
skills=["python","c++","javascript","juggling","running","eating"]
cv={}
cv["name"]=raw_input("Name: ").title()
cv["age"]=int(raw_input("Age: "))
cv["experience"]=int(raw_input("How many years of experience do you have? "))
... |
7f41635463dde5156c8d7d8e0ae0dde5633debcf | user4040784679a/code | /code/code1/tf_ops/nn_distance/tf_nndistance.py | 2,870 | 3.5 | 4 | """ Compute Chamfer's Distance.
Original author: Haoqiang Fan.
Modified by Charles R. Qi
"""
import tensorflow as tf
from tensorflow.python.framework import ops
import sys
import os
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
nn_distance_module=tf.load_op_library(os.path.join(BASE_DIR, 'tf_nndistance_so.so'... |
fdb15f5002bb6d37de7bf9bda41bfb92cd21fab6 | Shanice-W/IS-362 | /IS362_Project_1.py | 890 | 3.75 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[10]:
import pandas as pd
import numpy as np
path_to_file = open("C:\\Users\shani\Downloads\Project_1.csv")
airlines = pd.read_csv(path_to_file)
print(airlines)
# In[12]:
airlines = airlines.drop(airlines[airlines.status == 'on time'].index)
airlines2 = airlines.sort... |
8d477986b711ad167d0594d558d2f7829c774321 | gotmarko/ddcs | /codescreen.py | 3,253 | 3.90625 | 4 | #!/usr/bin/env python3
import argparse
import csv
import ipaddress
import json
import sys
def read_server_csv_file(fname):
"""
Read a server csv file
Expects a csv file of the format
hostname, serial_number, ip_address, netmask, gateway_ip
Arguments:
fname {str} -- file name of ... |
c7db2888d85701884b812eeaab319ab4ec099cee | carlos-paezf/Metodos_Numericos_Python | /Biseccion.py | 1,154 | 3.859375 | 4 | #Implementación del método de bisección y algunos casos de salida
from math import *
def pol(x):
return x**3+4*x**2-10
# retorna pol(x) = x^3 + 4x^2 -10
def trig(x):
return x*cos(x-1)-sin(x)
# retorna trig(x) = xcos(x-1) - sin(x)
def pote(x):
return pow(7.0, x)-13
# retorna pote(x) = 7^x - 13
def bisec(... |
36cb1edfa0d42746e07a595c0fdf9cc3d668bc3f | Ketil/python-scripts | /textgenerator.py | 2,788 | 3.78125 | 4 | #!/usr/bin/env python3
'''Simple program doing markov analysis of text, based on state of the previous
words, and generates text based on that. '''
import sys
import random
import re
def add_space(text):
'''Adds space before punctuation to separate it from a word'''
return re.sub(r'([!,.:;?])', r' \1', text)
... |
dee5288655fb90d351328dc77a25e786f0ee7648 | Matheus-Alborghetti/programacaoEstr | /Exerc02/exercicio18.py | 579 | 3.84375 | 4 | salarioB = float(input('Insira seu salário bruto: '))
valorP = float(input('Insira o valor da prestação: '))
calcEmpr = salarioB - (salarioB * 30 / 100)
if valorP > calcEmpr:
print(f'O valor não pode ser concedido\nLimite de 30% do salário bruto')
# A prefeitura de São José da Serra abriu uma linha de crédito pa... |
98e8fbad6a2010cb708bde9359691c74fa625988 | shubham-automation/python-exercise | /dictionary-problems/sorting_dictionary.py | 187 | 3.515625 | 4 | d = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
sorted_tuple = sorted(d.items(), key = lambda kv:kv[1]) #kv[1]=sort by values & kv[0]=sort by keys
sorted_dict = dict(sorted_tuple)
print(sorted_dict) |
2b08c14ccf0242381dbb013d7e08b09bf039660d | akosourov/codility-tasks | /6 - Sorting/distinct.py | 1,215 | 3.875 | 4 | """
Write a function
def solution(A)
that, given a zero-indexed array A consisting of N integers,
returns the number of distinct values in array A.
Assume that:
N is an integer within the range [0..100,000];
each element of array A is an integer within the range
[−1,000,000..1,000,000].
For example, given array A... |
69b9a3fe042d570684d2bee5a8d41c73743b2be0 | kzhangkzhang/eLearning | /BigData/Self-learning/Python/MyFirstPython/Circle.py | 2,451 | 4.125 | 4 | # reference: F:\Working@Knowles\Oracle\Development\BigData\KevinPractice\Udemy\JoseP_GoFromZerotoHeroinPython\Complete-Python-Bootcamp\Kevin_Object_Oriented_Programming.ipynb
class Circle(object):
# class object attributes
pi = 3.1415926
# Circle get instantiated with a radius (default is 1)
def __init__(s... |
0eba43bea1ddf3d6e30b34dd2c1148506e0b5de0 | xhan91/advent-of-code | /2017/day1/second.py | 355 | 3.59375 | 4 | #!/usr/bin/python
import sys
input = sys.argv[1]
arr1 = list(input)
arr2 = list(input)
input_arr = arr1 + arr2
sum_num = 0
length = len(arr1)
steps = length / 2
for index, num in enumerate(input_arr):
num = int(num)
if index == length:
break
else:
sum_num += num if num == int(input_arr[in... |
c574f3322e47da045c689924cd8d232d87dcb928 | Meet953/python | /pyrhon/Crucial Info/strings/string2.py | 355 | 4.5 | 4 | #2. TO READ A STRING AND DISPLAY IT IN REVERSE ORDER..
str=raw_input("Enter the string:")
print"\tThe string in reverse order is --->"
l=len(str)
for a in range(-1,(-l-1),-1):
print str[a],
print
... |
fa0a7739da3de152c9b72ecde0120a9b6c448b84 | murakumo512/Alpro-Python-2019-2020 | /Pertemuan 8/35.py | 273 | 3.6875 | 4 | text = 'abcdefg'
print(text[:10])
def myfunc(a,b):
if a > 3:
return b,a
else:
return a,b
swap = myfunc
for i in range(6):
i,s =swap(i,0)
print(i)
a = open("lorem1.txt")
b= a.read().split()
c = len(max(b))
print(c) |
ab14419b4aa9ef66bccccd351938641597c0a7bd | Santos1000/Curso-Python | /PYTHON/pythonDesafios/desafio025.py | 110 | 3.8125 | 4 | n = str(input('Digite o nome completo:')).strip()
print('Seu nome tem silva? {}'.format('SILVA'in n.upper()))
|
485f5fd2608f39d57762351b097b7075d3365ad9 | IngridFCosta/exerciciosPythonBrasil | /EstruturaDeRepetição/ex31.py | 540 | 3.90625 | 4 | print('Para encerrar o programa digite -1')
while True:
total=0
cont=0
preço= True
listaPreço=[]
while preço > 0:
preço=float(input(f'Produto {cont+1} R$:'))
listaPreço.append(preço)
total+=preço
cont+=1
if preço==-1:
print('Encerrando o caixa...')
... |
5426987d97bbcc9c59ae001484480023160fb939 | sdrsnadkry/pythonAssignments | /Functions/15.py | 182 | 3.65625 | 4 | lists = [1,2,3,4,5,6,7,8,9,0]
even = list(filter(lambda x: x%2 == 0 , lists))
odd = list(filter(lambda x: x%2 != 0 , lists))
print("Even nos: ", even)
print("Even nos: ", odd)
|
0b97071dec954ad6e8a16f70cc9d031bd4f596b1 | abdibogor/Thenewboston | /03_Software Engineering/000_Python 3.4/054_Finding Most Frequent Items.py | 735 | 3.984375 | 4 | from collections import Counter
text = "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. "\
"Stet clita kasd gubergren consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore ... |
b1042024cd723bb1a8c58d1663c030bb1af38385 | MartyRadka/cviceniPython | /programs/NEW/serazeni_seznamu.py | 1,194 | 3.71875 | 4 | # Úkol 6 - Had byl pyšný na to, že je první v abecedě. Dokud nepřiletěla "andulka".
# Abys uklidnila hada, vytvoř funkci, která zvířata seřadí podle abecedy, ale bude ignorovat první písmeno
# (t.j.: vrátí ["had", "pes", "andulka", "kočka", "králík"])
# postup: Máš seznam hodnot, které chceš seřadit podle nějakého k... |
eadaa8c5117b6ba32c816ff33fc43aa4a6603fcc | fbyter/sword-pints-offer | /Python/JZ37/JZ37.py | 1,217 | 3.59375 | 4 | # -*- coding:utf-8 -*-
class Solution:
def GetNumberOfK(self, data, k):
# write code here
if not data:
return 0
return self.biSearchLast(data, k) - self.biSearchFirst(data, k)
def biSearchFirst(self, data, k):
index = self.biSearch(data, k)
if index>... |
fdc93ad52fd87e7ed1f5c2f30a87f9b2055f4804 | stokelycw/ltc | /classes.py | 791 | 3.578125 | 4 | #Working with classes
class MyClass:
variable = "to print"
def function(self):
print("This is a message inside the class.")
myobjectx = MyClass()
myobjectx.function()
myobjecty = MyClass()
myobjecty.variable = "yakcity"
#Then print both values
print(myobjectx.variable)
print(myobjecty.variable)
clas... |
c5036a78cd57fe4d42d72208c1cbb78097dfa423 | sprax/1337 | /python2/l0236_lowest_common_ancestor_of_a_binary_tree.py | 2,547 | 3.734375 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
# Two pass to find path from root to p and q.
class Solution(object):
def lowestCommonAncestor(self, root, p, q):
"""
:type root:... |
c4724bbfa4c890ba05069b22475782a18c2b3829 | EahanZhang/learn_python3_with_liaoxuefeng | /5_functional_programming/1_high_order_function/5.1.2_filter.py | 2,143 | 3.6875 | 4 | #/usr/bin/python
# -*- coding: utf-8 -*-
"""
@author: Ehang Zhang
@file: 5.1.2_filter.py
@time: 2018/7/13 11:17
"""
# filter()函数用于过滤序列
# filter(function_name, iterable)
# filter()函数把传入的函数依次作用于每个元素,然后根据返回值是True还是False决定是否保留该元素。
# filter()函数返回的也是一个惰性序列Iterator
def is_odd(n):
return n % 2 == 1
print(list(filter(is_... |
b3fa878db22f7386e5645fe86e495942be12ef1b | LuisaE/cs257 | /books/books.py | 2,687 | 4.0625 | 4 | # Claire Williams and Luisa Escosteguy
# Revised by Claire Williams and Luisa Escosteguy
import argparse
import csv
import sys
def get_parsed_arguments():
"""
Returns arguments from argparser.
"""
parser = argparse.ArgumentParser(description='Process books.csv using a keyword from the title, an author, or a rang... |
175f54b134ae83b2bab325126c15162f9a4c574e | Neves-Roberto/python-course | /desafio8.py | 263 | 3.921875 | 4 | #Escreva um programa que leia um valor em metros e exiba o valor convertido em centimetros e milimetros
valor_metros = int(input('Digite um valor em metros: '))
print('valor em centrimetros : {} valor em milimetros: {}'.format(valor_metros*100,valor_metros*1000)) |
ca03d32d8f58b369ba1569e1717f6d8d5b2345e6 | AdamZhouSE/pythonHomework | /Code/CodeRecords/2730/60731/313950.py | 411 | 4 | 4 | n=int(input())
a=[]
for i in range(n):
d=input()
f=input()
a.append(d)
a.append(f)
if a==['3', '40 50 60', '2', '4 5']:
print(1)
print(1)
elif a==['3', '40 50 70', '2', '2 5'] or a==['3', '40 50 70', '2', '1 4']:
print(0)
print(0)
elif a==['3', '40 50 70', '2', '1 5']:
print(0)
p... |
98f922d078effccd0eb7fa1341357131d817350e | snapf/python-1811 | /Week3/lab03_C.py | 1,871 | 4.125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Mar 1 11:22:56 2021
Author: Roman Takhovskiy
zID: z5364695
Date: 1/1/2021
Program description:
This program takes inputted altitude from user and determines in which layer is inputted altitude.
Data dictionary:
Constants:
TROPOSHERE_MIN =... |
ca6862c97c4ea39444296a79f4538ac40d81350e | czod/MPYLibs | /physClassLib.py | 3,401 | 4.09375 | 4 | """ Math and physics class definitions from Introduction to Programming,
although most of these are perfectly well managed by SumPy functions."""
class Vec2D:
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, other):
return Vec2D(self.x + other.x, self.y + other.y)
d... |
8e73bc05c6543472a29114ae62316ab250dac3fc | rafa761/leetcode-coding-challenges | /2020 - august/012 - add two numbers.py | 2,351 | 3.796875 | 4 | """
You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse
order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Ex... |
2ca5c0b0eac88ff0fe49da258414034871d49ca8 | vidyasagarr7/DataStructures-Algos | /GeeksForGeeks/Tree/FoldableBinaryTree.py | 1,383 | 4.0625 | 4 | from GeeksForGeeks.Tree.BinaryTree import BinaryTree
from GeeksForGeeks.Tree.Convert2Mirror import create_mirror
"""
Foldable Binary Trees
Question: Given a binary tree, find out if the tree can be folded or not.
A tree can be folded if left and right subtrees of the tree are structure wise mirror image of each othe... |
db590f92967c900ebd31f6557aa85f6cc8ad5802 | yordan-marinov/advanced_python | /multidimensional_lists/diagonal_difference.py | 548 | 3.703125 | 4 | def get_abs_difference(n) -> int:
matrix = [[int(e) for e in input().split()] for _ in range(n)]
def primary_diagonal() -> int:
return sum([matrix[i][i] for i in range(len(matrix))])
def secondary_diagonal() -> int:
side_length = len(matrix) - 1
return sum([matrix[i][side_length - ... |
acd4a2f121a673887cd60dc279e2fb3cec9f2a97 | b1ueskydragon/PythonGround | /leetcode/p0008/test_myAtoi.py | 1,926 | 3.578125 | 4 | import unittest
from leetcode.p0008.solve import Solution as A
from leetcode.p0008.solve01 import Solution as B
class MyAtoiTest(unittest.TestCase):
def test_case01(self):
a, b = A(), B()
target = "42"
self.assertEqual(42, a.myAtoi(target))
self.assertEqual(42, b.myAtoi(target))
... |
673958c49db85d2e07cebb6c739ced269689425e | hguochen/code | /python/questions/ctci/recursion_and_dp/coins.py | 905 | 3.578125 | 4 | """
CtCi
8.12 Given an infinite number of quarters(25), dimes(10), nickels(5) and pennies(1), write
code to calculate the number of ways of representing n cents.
"""
def ways(n, coins):
"""
Time: O(mn)
Space: O(mn)
where m is number of coin denominations, n is size of n input
"""
if n < 1:
... |
78d4919665725db3be2610de163f0a9f46cdb6a3 | sorozcov/PYTHON-PROGRA-B-SICA-2018 | /EJERCICIOS VARIOS/ciclos/ciclos.py | 1,163 | 3.953125 | 4 | #Universidad del Valle
#Silvio Orozco Carne 18282
#Fecha 16-02-18
#El programa pedira ingresar start, stop y setp
inicio=int(input("Ingrese un numero con el cual generar e iniciar el ciclo: "))
fin=int(input("Ingrese un numero con el cual finalizara: "))
paso=int(input("Ingrese el paso con el que se incrementara el val... |
d2d9087c81df1d08284292af083b337a5352585a | VitalyVasin/budg-intensive | /day_3/comprehensions/task_1/implementation.py | 1,804 | 3.90625 | 4 | from math import sqrt
list1 = [12, 2, 17, 44, 131]
list2 = [127, 69, 144, 0, 1024]
list3 = [8, 6, 5, 4, 7]
list1_out = []
list2_out = []
list3_out = []
def great_comprehension(list1, list2, list3):
"""
Возвращает список с перемноженными элементами списков list1, list2 и list3 согласно условию
"""
for... |
efb1830d87e4f2f1cc64bee362c4e1b9b7775c8c | sanghvip/LearnPythonHardWayExercise | /ex4.py | 810 | 4.0625 | 4 | cars=100
space_in_a_car=4.0
drivers=30
passengers=90
cars_not_driven=cars-drivers
cars_driven=drivers
carpool_capacity = cars_driven * space_in_a_car
average_passengers_per_car = passengers / cars_driven
print("There are", cars, "cars available.")
print("There are only", drivers, "drivers available.")
pri... |
4e542e3f4ade727e2cf50f3a05e8869a54174fdb | Gnagdhar/Learning- | /Basics Programs in Python/RotateElements.py | 213 | 3.890625 | 4 | def rotateRight(list,n):
print(list)
print(list[-n:]+list[0:-n])
def RotateLeft(list,n):
print(list[0:n]+list[n:])
list=[10,20,30,40]
n=2
rotateRight(list,n)
list=[50,60,70,80]
n=2
RotateLeft(list,n)
|
28d7c306e512565f9b5763cc11c0e3b0f8508f77 | Divyakennady/AI-based-health-club-management-system | /appendlist.py | 90 | 3.578125 | 4 | list=[]
list1=[1,2,3]
list.append(list1)
list2=[4,5,6]
list.append(list2)
print(list) |
e8a6b814ba5d639351f7902bb13ae393659fd4b7 | b-ark/lesson_13 | /Task3.py | 780 | 4.09375 | 4 | # Write a function called `choose_func` which takes a list of nums and 2 callback functions.
# If all nums inside the list are positive, execute the first function on that list and return the result of it.
# Otherwise, return the result of the second one
def choose_func(nums: list, func1, func2):
new_list = remove... |
79204bfa9ab9a71bdf256f1aacf7853eccbedd6e | stephwag/ProjectEuler | /primes.py | 611 | 4.09375 | 4 | from math import *
#function to test if prime
def isPrime(n):
num = int(floor(sqrt(n)))
if n >= 2:
for i in range(2,num+1):
if n % i == 0:
return 0
else:
return 0
return 1
#some tests yo
'''
assert isPrime(2) == 1
assert isPrime(3) == 1
assert isPrime(4) == 0
assert isPrime(5) == 1
assert isPrime(7)... |
ae605f24b96b0c1439e55b4beb39aa79dba17db0 | atique08642/Basic-Common-Codes | /Occurance of a number.py | 215 | 3.734375 | 4 | def occurance (num,target):
li = list(num)
counter = 0
for element in li:
if element == target:
counter += 1
print(counter)
num = input()
target = input()
occurance(num,target)
|
f6455dc348dc3b4b23fd23d25b46bf94161aa791 | wutobias/collection | /python/spatial.py | 1,622 | 4.0625 | 4 | ### Written by T. Wulsdorf @ AG Klebe Marburg University
### Please contact via tobias.wulsdorf@uni-marburg.de
import numpy as np
def rotate_check(matrix):
if not (0.99 < np.linalg.det(matrix) < 1.01):
raise Warning("Warning: Determinant of rotation matrix is %s. Should be close to +1.0." %np.linalg.det(matrix))... |
58f22ca7ed201e16c00bf8c4dc9e4ffc4ed2ab10 | tea2code/make-it-hit | /graphics/tkdrawerfactory.py | 1,060 | 3.71875 | 4 | from data import circle
from data import rect
from graphics import tkcircledrawer
from graphics import tkrectdrawer
class NotDrawableError( Exception ):
''' Exception thrown if a not drawable object should be drawn. '''
class TkDrawerFactory:
''' Factory for tk drawer classes. '''
def createFrom( se... |
a50143ee47092b169246617dfe88440e46958996 | Linkin-1995/test_code1 | /day02/demo06.py | 1,150 | 4.28125 | 4 | """
核心数据类型
Python变量没有类型
"""
# 1. 字符串str:存储文本
name = "悟空"
str_number = "100" + "1" # 文字拼接
print(str_number) # "1001"
# 2. 整形int:存储整数
number01 = 100 + 1 # 数学运算
print(number01)
# 3. 浮点型float:存储小数
number02 = 100.1
# 4. 类型转换
# 结果 = 数据类型(待转数据)
"""
引入
# input的结果是字符串str,如果需要数学运算,则需要类型转换。
str_age = in... |
17ce962a35ce20df9c0a9d0f920e937b552db3c4 | alhambrasoftwaredevelopment/FIAT-LINUX | /early archive/TileGame000.py | 2,824 | 3.8125 | 4 | # Pygame sprite Example
import pygame
import random
from settings import *
def draw_grid():
for x in range(0, WIDTH, GRIDSIZE):
pygame.draw.line(screen, GREEN, (x, 0), (x, HEIGHT))
for y in range(0, HEIGHT, GRIDSIZE):
pygame.draw.line(screen, GREEN, (0, y), (WIDTH, y))
class Tile(pygame.spri... |
72e2c3753fe24d3093fec00ad5c91e5ab75dbc06 | VestOfHolding/Cryptography | /IndexOfCoincidence.py | 663 | 3.6875 | 4 | from LetterFrequency import calcLetterFrequency
def findIndexOfCoincidence(message):
"""Given a message, find the possible IC. Works better the longer the message.
Args:
message - The message to evaluate. Assumed to have no punctuation.
Returns:
The IC of the text."""
message = mes... |
3e22a09f7520a13ae2342c79b05098d5fc928db3 | wumirose/LAUTECH-SKill-Acquisition-Program | /myMod.py | 1,720 | 4.34375 | 4 | """Module docstrings.
This module demonstrates how to create a python module that can be imported into python code for reusability
Available Functions: This module harbours 5 functions which are:
func1() :It takes one no parameter but 'Hello Stranger'
greet(name) :It takes one parameter which is name and return 'Hel... |
e473ea603b3cdc32cd1e097f5c7480d6632c1729 | TS-N/holbertonschool-higher_level_programming | /0x04-python-more_data_structures/1-search_replace.py | 125 | 3.90625 | 4 | #!/usr/bin/python3
def search_replace(my_list, search, replace):
return [n if n != search else replace for n in my_list]
|
92d64f2dbaabb93b4bfce8f14762141337acbdc0 | lordpews/python-practice | /tut16.py | 325 | 3.734375 | 4 | """lis1 = [[1, "one"], [2, "two"], [3, "three"], [4, "four"], [5, "six"]]
kik = dict(lis1)
for d,e in kik.items():
print(d,e)
"""
# list with random data print no. greater than 6
lista = [2, 3, 6, 8, 10, "harry", "jerry"]
for x in lista:
if str(x).isnumeric() and x>6:
print(x)
else:
print()... |
d315839abd847aafa66df4139c1a4502bd13eae6 | KFredlund/holbertonschool-higher_level_programming | /0x07-python-test_driven_development/4-print_square.py | 739 | 4.53125 | 5 | #!/usr/bin/python3
def print_square(size):
"""Function that prints a square with the character #
Args:
size: size of the square
Returns:
A square of #s the size of @size
Raises:
TypeError: If size is not an int, or if a float and < 0
ValueError: if size is less than 0
... |
e480ffe43723f9e519b540e4041c3870809cfd64 | cd-chicago-june-cohort/Python_OOP_Alyssa | /animal.py | 1,913 | 4.15625 | 4 | class Animal(object):
def __init__(self, name, health):
self.name = name
self.health = health
def walk(self):
self.health -= 1
return self
def run(self):
self.health -= 5
return self
def display_health(self):
print "Health of", self.name, "=", self... |
b980e2fc6cce099e76949226604c00dfc6ef782f | vpalex999/my_grokking_algorithms | /03_recursion/04_count.py | 133 | 3.734375 | 4 | """
Recursion in list
"""
def count(arr):
if not arr:
return 0
return 1 + count(arr[1:])
print(count([1, 2, 9]))
|
5ac74437b7d2f9ebefd20ff609e129c2d9f807d7 | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/python/difference-of-squares/75f264eeae0b40f7a853d2cf82e67d68.py | 203 | 3.828125 | 4 | def difference(max_):
return square_of_sum(max_) - sum_of_squares(max_)
def square_of_sum(max_):
return sum(range(max_ + 1)) ** 2
def sum_of_squares(max_):
return sum(x**2 for x in range(max_ + 1))
|
2543722896eda999a08c1e9b57199b3de8cb7a2b | blessyann/MonCo-DataImmersive | /chapter7_10.py | 790 | 4.4375 | 4 | # Exercise 7.10 Dream Vacation: Write a program that polls users about their dream vacation. Write a prompt similar to, "If you could visit one place in the world,
# where would you go?" Include a block of code that prints the results of the poll.
responses = {}
polling_active = True
while polling_active: ... |
2b7711efc5a6850317b8c74da96cc2f50877215d | antakij1/Fake_News_Decider | /tree.py | 1,422 | 3.53125 | 4 | import pickle
from sklearn import tree
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
###change these paths to be specific to your computer###
train = pickle.load(open("C:/Users/Joe/PycharmProjects/fakenews/data/train_array.pkl", 'rb'))
labels = pickle.load(open("C:/Use... |
0e41291ee2115a1e7921ddeff7d3ce5465489dcf | GuilhermeRamous/python-exercises | /soma.py | 478 | 4.03125 | 4 | # Retorna a soma de todos elementos da lista, exclusive o primeiro número par
def soma(lista):
n = 0
soma = 0
for i in lista:
if i % 2 == 0 and n == 0:
n += 1
else:
soma += i
return soma
num_elementos = int(input("Número de elementos da lista: "))
print()
list... |
4684421b1c05f1df3a325bb441470267fb1fcb59 | kideok/kideokKim | /1010.py | 1,147 | 3.8125 | 4 |
# def bubbleSort(a) :
# count = 1;
# for i in range(0,len(a)):
# for j in range(i+1,len(a)):
# if(count % 10 == 1 and count % 100 != 11) :
# print count,"(st comparison)"
# elif(count % 10 == 2 and count % 100 != 12) :
# print count,"(nd comparison)"
# else :
# print count,"(th comparison)... |
255a3db5d7a41ab65e3a9c5147c26b8d4a153cbb | huangshaoqi/programming_python | /XDL/python/Part_1/Day10/3.py | 656 | 3.671875 | 4 | from functools import wraps
def outer(func):
"""
1.This is outer function doc
"""
print("1This is outer function\n", outer.__name__, outer.__doc__)
# @wraps(func)
def inner():
"""
2.This is inner function doc
"""
print("2This is inner function\n", inner.__name_... |
2b9c7a403f2c5ea6c7e99fa9aa2270aef61da409 | Ccuevas3410/LeetCode | /CodePath/Week-Three/Hackerrank Sandbox/Excel_Column_Number.py | 753 | 4.375 | 4 |
# Complete the 'excel_column_to_number' function below.
#
# The function is expected to return an INTEGER.
# The function accepts STRING column as parameter.
#
# Given a column as represented in excel, return
# its corresponding column number.
#
# A-> 1
# B -> 2
# AA -> 27
# AB -> 28
def excel_column_to_n... |
b4ef63eeaa36c364e31818cfbfee0ad8d11b7e46 | jinjinanan/document | /Python/Demo/AsyncIO/asyncIO.py | 876 | 3.703125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import asyncio
import threading
# @asyncio.coroutine #把一个generator标记为coroutine类型,然后,我们就把这个coroutine扔到EventLoop中执行。
# def hello():
# print('hello world!')
# # 异步调用asyncio.sleep(1):
# r = yield from asyncio.sleep(1)
# print('hello again')
#
# # 获取EventLoop:
... |
103cf5cd1674738fdf28294e46a6e94f23bb053b | ravijaya/july23 | /demoio.py | 379 | 3.703125 | 4 | """demo for the IO"""
try:
name = input('enter the name :')
city = input('enter the city :')
zip_code = hex(int(input('enter the postal code :')))
print('name :', name)
print('city :', city)
print(zip_code)
print(type(zip_code))
except ValueError as error:
print(error)
except Exception ... |
eb0997c91bfb9a5ec23b7f0317f748c64ee7a9ea | alessandroliafook/P1 | /unidade4/converte_matricula/converte_matricula.py | 332 | 3.703125 | 4 | # coding: utf-8
# Conversão de Matrículas na UFCG
# (C) / Alessandro Santos, 2015 / UFCG - PROGRAMAÇÃO 1
mat_antiga = raw_input()
mat_nova = ""
for numero in range(len(mat_antiga)):
if numero == 0:
mat_nova += "1"
elif numero == 5:
mat_nova += "0" + mat_antiga [numero]
else:
mat_nova += mat_antiga [numer... |
b26280c4560fdbab54192eb4db10c0093b5524ee | Osama-Yousef/data-structures-and-algorithms-1 | /challenges/fifo_animal_shelter/fifo_animal_shelter.py | 1,724 | 3.9375 | 4 | class Node:
'''
Doubly linked Node (Generic Pet Construct)
'''
def __init__(self, pet_type, prev, next):
self.pet_type = pet_type
self.next = next
self.prev = prev
class AnimalShelter:
'''
FIFO based class which holds only dogs and cats.
The shelter operates usin... |
08e1c92bd6e8d72f6812b0b218448e3c56ea23e5 | Apple7724/Probe | /30_function_выбор максимального числа из введенных.py | 315 | 3.671875 | 4 | import math
def maximum (x,y,z,a,b,c):
#return x + y + z
return max (x,y,z,a,b,c)
x = int(input (' введи 6 любых чисел через enter '))
y = int(input ())
z = int(input ())
a = int(input ())
b = int(input ())
c = int(input ())
k = maximum (x,y,z,a,b,c)
print ('maximum =',k)
|
37a6ef25ff0264802c1ac0251f6426263da59286 | vikbehal/Explore | /EfficientCoding/CoinChange.py | 604 | 4.03125 | 4 | def coin_change(amount, change):
if amount in change:
return 0, amount
chosen_coin = 0
for coin in change:
if coin < amount:
chosen_coin = coin
break
return amount-chosen_coin, chosen_coin
remaining_amount = 8
change = [1, 5, 3, 6]
change.sort()... |
9738630ee77b9209668ae18a9ba59c1a9a880cb2 | laurenfb/cs-fun-practice-2017 | /stacks-and-queues/queue.py | 611 | 4 | 4 |
class Queue(object):
def __init__(self):
self.queue = list()
def __repr__(self):
string = "queue"
for element in self.queue:
string += "->"
string += str(element)
return string
def __len__(self):
return len(self.queue)
def enqueue(sel... |
ee3b518509098bc6b990c34ac28d5cac8ffafa69 | DingoAteMyAiBot/Sorter | /main.py | 1,087 | 4.03125 | 4 | import numpy as np
import math
numbers = ""
sorted1 = []
current = 0
floored = 0
ceiling = 0
numbers = input("array of numbers separated by space: ")
numbers = numbers.split()
sorted1 = [int(numeric_string) for numeric_string in numbers]
sorted2 = np.sort(sorted1)
total = 0
finalmedian = 0
print(" ")
print("ORDERED: "... |
01cee57f37f731c0a5f39f7f0213202386637967 | zjahid19/snakegame | /score.py | 1,592 | 3.8125 | 4 | from turtle import Turtle
import os
class Scoreboard(Turtle):
def __init__(self):
super().__init__()
self.read_file = open('score.txt', mode='r')
self.score = -50
self.high_score = self.read_file.read()
self.read_file.close()
self.color("white")
self.hideturt... |
12d2046caab97e619ffaf3781aa1432e54abc4d4 | Zuce124/Algorithm_Learning | /Extra_Algo.py | 716 | 3.59375 | 4 | #items = ["apple", "pear", "orange", "banana", "apple",
# "orange", "apple", "pear", "banana", "orange",
# "apple", "kiwi", "pear", "apple", "orange"]
#filter = dict()
#for item in items:
# filter[item] = 0
#result = set(filter.keys())
#print(result)
#counter= dict()
#for item in i... |
cded5621b2c2819a61475bfa42934047b3e83e1b | Qkessler/100daysofPython-files | /days/10-12-pytest/practice/practice_fstrings.py | 344 | 3.859375 | 4 | # You have to be MIN_DRIVE or more to drive. Let's print with f-strings
# to test it.
MIN_DRIVE = 18
def can_you_drive(name, age):
string = ""
if age >= MIN_DRIVE:
string = f"{name} is old enough to drive"
else:
string = f"{name} is not old enough to drive"
return string
print(can_y... |
86b9504257c7784eda1b28d5567882a2236ed355 | krishppuria/Python-work | /Code_challenge/zoo1.py | 540 | 3.796875 | 4 | #Code Challenge to read the zoo.csv file using readlines and print integrating the list
while (True):
try:
file = open('C:/Users/Krishna/Desktop/Python work/Files/zoo.csv', 'r')
#print("Enter 5 students name: ")
itter_list=file.readlines()
for lines in itter_list:
... |
39fb6200fa1ddda2cb8f24592d22e043474049cf | rusben/python-exercices | /217-exemple de menu.py | 601 | 3.75 | 4 | #!/usr/bin/env python2.7
# -*- coding: utf-8 -*-
edades = { 'Paco': 20, 'Luis': 25, 'Lucas': 30 }
nombre = 'Luis'
edad = edades[nombre]
print edad
def sumar(a, b):
return a + b
def restar(a, b):
return a - b
def multiplicar(a, b):
return a * b;
num1 = raw_input("Num1: ")
num2 = raw_input("Num2: ")... |
23766d7fb5d0559b23fb053161737997e33f2169 | bubblegumsoldier/kiwi | /kiwi-user-manager/app/lib/Authenticator.py | 1,117 | 3.609375 | 4 | from werkzeug.exceptions import abort
class Authenticator(object):
def __init__(self, user_database_connection):
"""
Should be used to create an Authenticator object.
The Authenticator class should be used to check whether given credentials are
valid and stored within the database.... |
6183338f47e92267c2a36b84e6e29a3a0283c257 | mukhad/MyPyEducations | /py_progs/test_almost_factorial.py | 709 | 3.703125 | 4 | """
Реализуйте функцию almost_double_factorial(n), вычисляющую произведение всех нечётных натуральных чисел,
не превосходящих nnn.
В качестве аргумента ей передаётся натуральное (ноль -- натуральное) число n⩽100
Возвращаемое значение - вычисленное произведение.
Комментарий. В случае, если n = 0, требуется вернуть 1.
"... |
0b855011842baad797b07494036cd2245e200fce | djoul2706/botList | /my_tokenize.py | 379 | 3.578125 | 4 | # -*- coding: utf-8 -*-
import nltk
from nltk.tokenize import WhitespaceTokenizer
from nltk.tokenize import SpaceTokenizer
from nltk.tokenize import RegexpTokenizer
data = "Vous êtes au volant d'une voiture et vous roulez à vitesse"
#wst = WhitespaceTokenizer()
#tokenizer = RegexpTokenizer('\s+', gaps=True)
token=Whit... |
0c873e59c9b007a3479c1baff44a57c8bfdb8dad | cmmerritt/regex-engine-python | /Problems/Delete from squares/main.py | 164 | 3.671875 | 4 | key_val = int(input())
popped = squares.pop(key_val, "There is no such key")
if key_val in squares:
print(squares)
else:
print(popped)
print(squares)
|
c1af6cda70175c7e7fbdadf0ecdf46edf4531af6 | angryreid/PythonLearning | /exe9_迭代.py | 1,149 | 3.5625 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
__author__ = 'derek'
# iteration
s = '123456789'
# for ch in s:
# print(ch)
# 字典
d = {'name':'ddd','age':34,'sex':'woman'}
for key in d:
print(key)
print('----')
for val in d.values():
print(val)
print(d.items())
for k,v in d.items():
print(k,'--',v)
# ... |
ffbad1ffdafe2e9cb0c630acaeacd3d6d46f71f5 | isabellyfd/python_lessons | /prime.py | 590 | 4.09375 | 4 |
num = int(input("Digite um numero:\n"))
count = 2
primes = []
if num != 1:
while count <= num:
if count == 2:
primes.append(count)
else:
a = 2
isprime = True
while(a < count):
if count%a == 0:
isprime = False
... |
4890b0a16826101ee6911d78845ea08fb3d3e182 | sindhuula/sem3 | /NLP/sselvar4_HW2/findsim | 2,456 | 4.1875 | 4 | #!/usr/bin/env python
import argparse
import random
import sys
import math
import operator
import collections
# This function converts the file into a dictionary where the word is the key and all subsequent column values act as a list which is the value of the dictionary.
def read_file(lexFile):
dictionary = {}
with... |
eb7c1f1ab7a52a37a2c94ec903d3a1262f0b71dc | zerohk/python | /c6_10favo_num.py | 443 | 3.65625 | 4 | favo_num = {
"tom":[22,3,4,23,45],
"jerry":[46,7,8,21],
"jack":[20,53,32,99,520,666],
"rose":[45]
}
for person,numbers in favo_num.items():
if len(numbers) == 1:
print(person.title() + "'s favorite number is:")
for number in numbers:
print(number)
else:
p... |
951aea14754f3ca2420fba281a0b31c27ccd1b50 | erinmcavoy/pa3 | /pa3.py | 4,433 | 3.96875 | 4 | # Programmers: [Erin McAvoy]
# Course: CS151.05, Dr. Isaacman
# Date: [10/8/19]
# Programming Assignment: [PA3]
# Problem Statement: [calculates the score of a quiddich game, calculates qb rating, calculates gymnast score]
# Data In: [completions, attempts, passing yards, touchdown passes, interceptions, number of ... |
d974e78ca248bb2322da4ca150b523610bdb67df | AranzaCarolina/Primerrepo | /evidenciaWhile.py | 763 | 4.125 | 4 | #Menu Ciclico
while True:
print("operaciones: [1]suma, [2]resta, [3]multitplicacion, [4]division, [5]salir")
eleccion = input("Selecciona una de las opciones anteriores: ")
if eleccion == "1" or eleccion == "2" or eleccion == "3" or eleccion == "4":
n1 = int(input("introduce el primer numero: "))
... |
b89b7866433bd739d6f2bc99e7ec56b82ce34a54 | Patrick-Lennon/DigitRecognizer | /Digimon.py | 1,035 | 3.609375 | 4 | import matplotlib.pyplot as plot
from sklearn.tree import DecisionTreeClassifier
import numpy as np
import pandas as pan
"""
Using scikit-learn to predict what numbers the hand-written digits are
#author Patrick Lennon
"""
#panda data converted to a matrix so it's a 2d array
data = pan.read_csv('data/tra... |
76286a5941259b15c9cdfc934f1382078edee002 | YonatanEizenberg/Catan_Project | /client/Dice.py | 1,039 | 3.609375 | 4 | import pygame
class Dice(pygame.sprite.Sprite): # Class for 2 Dices on the PyGame screen
path = [(673, 366), (727, 366)] # 2 Screen locations for the 2 Dices
counter = 0 # Counter for the dices
def __init__(self, num): # Initialises the Dice
... |
c359ffe45c7895627e199782d034b09116ac7825 | vitvara/comprograming-1.1 | /ex5/doctest_ex.py | 3,260 | 4.0625 | 4 | def string_interleave(s1, s2):
"""[summary]
Args:
s1 (string): some word
s2 (string): some word
Raises:
TypeError: Input s1 and s2 must be str.
Returns:
string: s1 swap with s2 or s2 swap with s1
>>> string_interleave("abc", "mnopq")
'manbocpq'
>>> string_... |
259b9a7b6659e1a3e47d1c548d57da996c95fe7d | SixingYan/algorithm | /linkage/002AddTwoNumbers.py | 3,004 | 3.8125 | 4 | """
You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Ex... |
7e062da8145df775c10d4622e6e177736e8afef7 | CharlotteGenius/python-bible | /python/intersect.py | 533 | 3.9375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Sep 28 13:32:51 2018
@author: xiangyinyu
"""
#!/usr/bin/python
class Point:
def __init__(self,x,y):
self.x = x
self.y = y
def ccw(A,B,C):
if (C.y-A.y)*(B.x-A.x) > (B.y-A.y)*(C.x-A.x):
return True
def intersect(A,B,C,D):
if ccw(A,... |
8b40828b2c581e28db9f804e02708bf92c31c7b1 | sanqit/text-based-browser | /Problems/Buying books/task.py | 262 | 3.65625 | 4 | n = int(input())
book_shelf = []
readed = []
for _ in range(n):
cmd = input().split(" ", 1)
if cmd[0] == "BUY":
book_shelf.append(cmd[1])
elif cmd[0] == "READ":
readed.append(book_shelf.pop())
while readed:
print(readed.pop())
|
a6d64eeb0048935692e20b9196a1fd9762d67737 | Bikram-Gyawali/pythonprojectsdaily | /hangman/haangman.py | 3,883 | 4.03125 | 4 | import time
import random
print("Welcome to the hangman word guessing game")
name = input("Enter your name: ")
print("hello"+name+" best of luck")
time.sleep(3)
print("Loading...")
time.sleep(3)
def main():
global count
global display
global word
global alreadyGuessed
global playgame
global l... |
6133c6abf3063a9ff688fdad433cd761e7211a6a | stanislavkozlovski/python3_softuni_course | /2.Strings and Basic Data Structures/05.Mutual_Interests.py | 474 | 3.921875 | 4 | ivan = ['пушене', 'пиене', 'тия три неща', 'коли', 'facebook', 'игри', 'разходки по плажа', 'скандинавска поезия']
maria = ['пиене', 'мода', 'facebook', 'игри', 'лов със соколи', 'шопинг', 'кино']
print("Their mutual interests are: ")
for interest in set(ivan).intersection(set(maria)): #cast the lists into a set to us... |
e15ef909b6e66f6b0bd3c141c0c00f06e29209b3 | Mendes3/learning-python | /ifeliflelse.py | 259 | 4.09375 | 4 | age = 13
if age < 21:
print("No beer for you!")
name = "dinda"
if name == "Bucky":
print("hey there bucky")
elif name == 'lucy':
print("hey there lucy")
elif name == 'bud':
print("hey there bud")
else:
print('please sign up for the site')
|
b01b27a73ea0542e98ae5241d27606ea7b9cfd17 | DavidLohrentz/LearnPy3HardWay | /ex43.py | 5,058 | 3.640625 | 4 | from sys import exit
from random import randint
from textwrap import dedent
class Scene(object):
def enter(self):
print("This scene is not yet configured.")
print("Subclass it and implement enter().")
exit(1)
class Engine(object):
def __init__(self, scene_map):
self.scene_ma... |
df0fc255f5e7fcabc5cd798bade192aaeab141f2 | GSCrawley/refactoring | /2_inline_method.py | 362 | 3.703125 | 4 | # by Kami Bigdely
# Inline method.
# TODO: Refactor this program to improve its readability.
class Person():
def __init__(self, age):
Person.age = age
def enterClub(age):
if Person.age > 18:
print("Come on in!")
else:
print("Sorry, no minors allowed.")
... |
c99e731e5d060f8cdda386eb67d2562c382c0af9 | xp1902/PythonCode | /Pythoncode_Learn/file.py | 334 | 4.09375 | 4 | string = ""
birthday = input("please input your birthday num as a numstring: ")
with open('pi_digits.txt') as fp:
for line in fp:
string += line.strip()
if birthday in string:
print("your birthday is in the first million digits of pi")
else:
print("regret, your birthday is not in the first million d... |
80d0a83287e6f7f62a8a93a20fbd1f9a8782c436 | ContactLenz/Lab-2-Pattern-Matching | /pattern.py | 2,381 | 3.6875 | 4 | class Pattern:
def __init__(self, pattern, wildcard = None):
self.pattern = pattern
self.wildcard = wildcard
self.case_sensitive = False
def set_case_sensitive(self, case):
self.case_sensitive = case
def _new_wildcard(self, pattern, wildcard, text, start = 0):
p_ind... |
c50c072855a07e6e9d2232fdf073a48e27476232 | mozaican/Practice-Python | /largest_number.py | 448 | 4.03125 | 4 | """ Return the largest numbers in lists.
Return a list consisting of the largest number from each provided sub-list.
"""
def largest_numbers(lyst):
largest_numbers = []
for sublyst in range(len(lyst)):
largest = 0
for number in range(len(lyst[sublyst])):
if lyst[sublyst][number]... |
d9702cbad4e2755716647edbdef55aac3daf5e39 | VazMF/cev-python | /PythonExercicio/ex113/teste.py | 452 | 4.15625 | 4 | # Reescreva a função leiaInt do desafio 104, incluindo agora a possibilidade da digitação d eum número tipo inválido.
# Aproveite e crie também uma função leiaFloat com a mesma funcionalidade
from PythonExercicio.ex113.ex113 import leiaInt
from PythonExercicio.ex113.ex113 import leiaFloat
n1 = leiaInt('Digite um núme... |
5ea746dcbfddec803b107cc44f306ccc82d9f767 | JC-Jeyci/Aprendiendo_python | /curso_basico_normal/programs/tur.py | 406 | 3.9375 | 4 | import turtle
# La libreria de turtle sirve para crear programas graficos en python
def make_line_and_turn(test, largo):
test.forward(largo)
test.left(90)
def make_square(test):
largo = int(input())
make_line_and_turn(test, largo)
def main():
window = turtle.Screen()
test = turtle.Turtle()
... |
d601faf523962972ae27392a5868ae68085571f3 | Pedro0901/python3-curso-em-video | /Python 3 - Mundo 3/Scripts Python - Mundo 3/Aula19a.py | 238 | 4.125 | 4 | #Dicionario dentro de uma lista
brasil = list()
estado1 = {'UF': 'Rio de Janeiro', 'Sigla': 'RJ'}
estado2 = {'UF': 'São Paulo', 'Sigla': 'SP'}
brasil.append(estado1)
brasil.append(estado2)
print(brasil)
print()
print(brasil[0]['UF'])
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.