blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
a8ba28874e2364d7e356801451998561b61ecfb1 | daniel-reich/turbo-robot | /XQwPPHE6ZSu4Er9ht_10.py | 1,970 | 4.3125 | 4 | """
A number is Economical if the quantity of digits of its prime factorization
(including exponents greater than 1) is equal to or lower than the digit
quantity of the number itself.
Given an integer `n`, implement a function that returns a string:
* `"Equidigital"` if the quantity of digits of the prime factor... |
db92d6c44041067b4166da11227060bff483a822 | qiangayz/MyCode | /面向对象/继承1.py | 1,151 | 3.890625 | 4 | #coding=utf-8
class people(object):
# def __init__(self):
# self.age = 45
# print('People')
def sleep(self):
print(123)
class Relation(object):
def __init__(self):
print('Relation')
class Man(people,Relation):
def __init__(self):
super(Man,self).__init__() #这里继承... |
b30a7b6f6606c4c58a956fd5b40f8010eb860826 | gclegg4201/python | /blackjack.py | 1,616 | 3.5625 | 4 | from random import randint
def shuffle():
global deck
deck=[]
for suit in range(0,4):
for value in range(1,14):
if(value<10):
deck.append(value)
else:
deck.append(10)
for tweak in range(0,10):
deck.pop(randint(0,len(deck)-1))
def ... |
03c15b351bf6ae113a7e8eeb28a5afc9077fdbbf | SethBixler/Python-Projects | /clothingPicker.py | 3,609 | 4.03125 | 4 | # Author : Seth Bixler
# Description : Lab 3, CSCI 141
# File : clothingPicker.py
# Date : October 11, 2016
# Lines 1-5
# Ask the user if it is windy
# Receive input from user and save into a variable
# If it windy, output "Be sure to not bring an umbrella because it is windy."
# If it is not windy, output "It is not ... |
60e43fbf0eab1ab59a90e555c010d8297adfe9ae | alexchao/problems | /python/math_problems_test.py | 1,401 | 3.75 | 4 | # -*- coding: utf-8 -*-
import unittest
from math_problems import count_staircase_climb
from math_problems import is_power_of_three
class IsPowerOfThreeTest(unittest.TestCase):
def test_zero(self):
self.assertFalse(is_power_of_three(0))
def test_one(self):
self.assertTrue(is_power_of_thr... |
426550f2e9d95cdc2b615a9236dce6aa671d5083 | Jiezhi/myleetcode | /src/88-MergeSortedArray.py | 1,034 | 4.03125 | 4 | #!/usr/bin/env python
"""
https://leetcode.com/problems/merge-sorted-array/description/
Created on 2018-11-16
@author: 'Jiezhi.G@gmail.com'
Reference:
"""
class Solution:
def merge(self, nums1, m, nums2, n):
"""
:type nums1: List[int]
:type m: int
:type nums2: List[int]
... |
88437f63c3e2f6cec3102a73f42c1d08f206f07e | valdecler/estudo | /exercicio34.py | 639 | 4 | 4 |
#Crie um script com uma lista , exiba 2 msgs na tela, ambas vão ter interação
#com o loop for, a segunda msg estará fora do bloco, e so vai ser executada
#ao final do loop, apenas o ultimo elemento da lista aparecerá na 2msg,
#explique por que isso acontece.
nomes = [ 'rafael', 'danela', 'Carolina']
for no... |
14c36f02e70c67be9d3eaa43b7fdf8117f88e7fb | danmarton/code | /Python/prompt.py | 394 | 3.5 | 4 | from sys import argv
script, user_name = argv
prompt = 'Prompt: '
print "Hi %s, I'm %s!" % (user_name, script)
print "What do you want to say?"
likes = raw_input(prompt)
print "Where do yo live?"
lives = raw_input(prompt)
print "What kind of computer do you have?"
computer = raw_input(prompt)
print """
You said %... |
348e63307433a14fa6414cc4246ef55fbeba24fe | fountainhead-gq/MachineLearning | /Matplotlib/gallery/showcase/showcase-12.py | 4,919 | 4 | 4 | #coding = utf-8
#------------------------
# An implementation of the Domino Shuffling Algorithm on Aztec Diamond Graphs.
#------------------
import random
import matplotlib.pyplot as plt
import matplotlib.patches as mps
class Aztec_Diamond:
def __init__(self, n):
"""
Use a dict to represent a ti... |
96c9079163cbb37571ba2fec852bb0907838fc0a | rajureddym/python | /coding/problems/list_read_scores_find_runnerup.py | 351 | 3.796875 | 4 | if __name__ == '__main__':
n = int(input())
arr = map(int, input().split())
a = list(set(list(arr)))
print('printing list of scores after removing duplicates: ' + str(a))
print('printing list of scores after removing duplicates & sorting : ')
a.sort()
print(a)
print('runner up score in a... |
cfb8b0bfbffc17b6ee2a8959499b42e706482158 | lodgeinwh/Study | /Python/LeetCode/Algorithm/007. Reverse Integer.py | 441 | 3.703125 | 4 | # !/usr/bin/env python3
# -*- coding: utf-8 -*-
# @author: Lodgeinwh
# @file: 007. Reverse Integer.py
# @time: 2019/04/09 23:45:16
# @contact: lodgeinwh@gmail.com
# @version: 1.0
class Solution:
def reverse(self, x: int) -> int:
if x >= 0:
ans = int(str(x)[::-1])
else:
ans ... |
365c172f481c50a948643eca8dec761260940368 | salam1416/100DaysOfCode | /day11.py | 413 | 4.1875 | 4 | # Python Operators 2
# Logical Operators
x = 4
print(x > 2 and x < 10)
print( x < 2 or x > 0 )
print( not(x>3) )
print(x is 4)
print( x is not 3)
x = ['s','m']
y = ['s','m']
print(x is y)
print('s' in x)
print('m' not in y)
# Bitwise operators
# 1 is 01
# 2 is 10
print(1&2) # should be zero
# 3 is 011
# 7 is 111
print... |
b2b79819c2d71a9cb39b009eebcc80d84214bc48 | AtiqulHaque/geeksforgeeks | /nth-item-through-sum.py | 3,203 | 4.125 | 4 | """
Given two sorted arrays, we can get a set of sums(add one element from the first and one from second). Find the N’th element in the set considered in sorted order.
Note: Set of sums should have unique elements.
--------------------------------------------------
Input : arr1[] = {1, 2}
arr2[] = {3, 4}
... |
9c3c78034cdaa232dd3b7707eea5d32f6fd2cc96 | ramudasari123/PythonPractice | /UdemyDemo/Decorators.py | 841 | 3.703125 | 4 | def Master(name="ram"):
def child1(name):
print("I am child1 {}".format(name))
def child2(name):
print(f"I am child2 {name}")
if(name.upper()=="RAM"):
return child1
else:
return child2
calling=Master("nadi")
calling("nadi")
###Passing one method/function as arguments t... |
19839a9ccb9fb048dd8a03255080f10234f0fcf7 | JuanPyV/Python | /while/W5_A00368753.py | 152 | 3.65625 | 4 |
n = int(input("¿Hasta que numero? "))
c = 0
g = 0
while c < n:
g = g + 3.785
c = c + 1
print("%d gal. equivale a %.3f lts" % (c, g))
|
624841aa07b17ecc6b152d17d8ccc8aa7cb3a80f | Nubstein/Python-exercises | /Condicionais e Loop/Ex10.py | 644 | 3.71875 | 4 | #Meses com 31 dias: 1, 3, 5, 7, 8, 10 ou mês 12
#Meses com 30 dias: 4, 6, 9 e o mês 11.
#algo errado no código abaixo
d=int(input("Insira o dia: "))
m=int(input("Insira o mês: "))
a=int(input("Insira o ano: "))
if m==1 or m==3 or m==5 or m==7 or m==8 or m==10 or m==12: #meses com 31 dias
if d<=31:
... |
c85a59e2a9af8f1e9b515e9b2b08819c3cd7621f | petr-tik/misc | /zenhacks_jarjar.py | 536 | 3.515625 | 4 | #!/usr/bin/env python
# https://www.hackerrank.com/contests/zenhacks/challenges/pairing
N = int(raw_input())
def solve(Num):
res = {}
answer = 0
for x in xrange(Num):
shoe = raw_input()
res_k = shoe[:-2]
foot = shoe[-1:]
if not res.has_key(res_k):
res[res_k] = [... |
e2db677056ec0083d2e131bb7b12b9a7d085557e | calvinloveland/letterwords | /python/sort_by_size.py | 359 | 3.53125 | 4 | dictionary = list()
def get_dictionary():
file = open("dictionary.csv")
for line in file:
dictionary.append(line.strip())
def set_dictionary():
file = open("newdictionary.csv",'w')
for word in dictionary:
file.write(word + '\n')
get_dictionary()
dictionary.sort()
dictionary.sort(k... |
e3861e1c9c533ce8532028a64bef869860a5a2f0 | everqiujuan/python | /day08/code/09_不定长参数.py | 1,104 | 3.75 | 4 |
# 不定长参数
# *args: 可以接收任意数量的参数, 会接收到一个元组tuple
# args: arguments参数的意思
def fn(*args):
print(args) # (1, 2, 3)
fn(1, 2, 3, True, "a")
list1 = [1, 2, 3]
fn(*list1)
def fun(name, age, *args, sex='男'):
print(name) # 昆凌
print(age) # 25
print(sex) # 女
print(args) # ('中国台湾', '165',... |
4fff956bcb3566b527331f03a9b082d058f94dbc | medshi3/Exercices-from-practicepython.org | /exer15.py | 512 | 4.40625 | 4 | """"
Write a program (using functions!) that asks the user for a long string containing multiple words.
Print back to the user the same string, except with the words in backwards order. For example, say I type the string:
"""
def str_reverser(input = None):
if input != None:
data = ' '.join(input.split()[:... |
2bf025ff5245da47e18d897ab17c06f39d068bd8 | sunnyding602/CISC-610-O-LateSpring | /Assignment3/trees.py | 1,790 | 3.796875 | 4 | import csv
from bintree_tree import Tree
from collections import deque
class Trees:
leaf_count = 0
height = 0
def inorder(self, root_node):
current = root_node
if current is None:
return
if current.is_leaf:
self.leaf_coun... |
5b4073d2eb2ab52d27b0c7a394dae427ce0aa869 | g-buzzi/Padaria_GUI | /entidades/estocado.py | 802 | 3.8125 | 4 | from abc import ABC, abstractmethod
class Estocado(ABC):
@abstractmethod
def __init__(self, codigo: int, nome: str) -> None:
super().__init__()
self.__codigo = codigo
self.__nome = nome
self.__quantidade_estoque = 0
@property
def codigo(self) -> int:
return self... |
4da3fc15f4ff099bfbbd3b6fe84025731b426adc | ps9610/python-web-scrapper | /02-01/return_1.py | 534 | 3.875 | 4 | #print와 return의 차이에 대해서 알아보자
def p_plus(a, b):
print(a + b)
def r_plus(a, b):
return a + b
p_result = p_plus(2, 3)
r_result = r_plus(2, 3)
print(p_result, r_result)
#>>>5, None 5
#ㄴ>첫번째 5는 line 3의 print(a+b)
#ㄴ>두번째는 p_result = none, r_result = 5가 나왔다.
#none이 나온 이유는 p_plus는 되돌아오는 값이 없기 때문... |
544657a0c71184277472a0d8d54a4bee8fa3c827 | bk17Git/python | /calculator.py | 405 | 4.28125 | 4 | firstNo = int(input("Enter you first operand: "))
operator = input("Enter your operator: ")
secondNo = int(input("Enter your second operand: "))
if operator == "+":
print(firstNo + secondNo )
elif operator == "-":
print(firstNo - secondNo)
elif operator == "*":
print(firstNo * secondNo)
elif operator == "/... |
af4b61aee362544b2394e54e2ed19867ae5fdd44 | EddyYeung1/Top-75-LC-Questions | /Solutions/Group_Anagram.py | 2,030 | 4.15625 | 4 | '''
Given an array of strings, group anagrams together.
Example:
Input: ["eat", "tea", "tan", "ate", "nat", "bat"],
Output:
[
["ate","eat","tea"],
["nat","tan"],
["bat"]
]
'''
'''
Solution 1: we create a dictionary with a sorted word as a key and a list of anagrams as its value. The key here is by having the s... |
d043abe1af412fe40e964ae2ea8c530c99a0ffad | Yasmin-Core/Python | /Mundo_1(Python)/operacoes_aritmeticas/aula7_desafio13(porcentagem2).py | 171 | 3.53125 | 4 | salário= float(input('Qual é o seu salário ? R$'))
novo= salário + (salário * 15/100)
print ('O seu salario teve um aumento de 15% e passou a ser R$ {}'.format(novo)) |
678b06349751b40b9839816eb25b1e06fe5c2140 | trumiddd/LearningX | /advanced_ML/tree_ensembles/src/GradientBoostedTree.py | 1,926 | 3.609375 | 4 | """
GradientBoostedTree.py (author: Anson Wong / git: ankonzoid)
"""
import numpy as np
from sklearn.tree import DecisionTreeRegressor
class GradientBoostedTreeRegressor:
def __init__(self, n_estimators=20, max_depth=5,
min_samples_split=2, min_samples_leaf=1):
self.n_estimators = n_e... |
9d350c258a984ddb48a857df39e446196432c8c1 | JuanGinesRamisV/python | /practica 5/p5e7.py | 254 | 4 | 4 | #juan gines ramis vivancos p5e7
#Escribe un programa que pida la altura de un triángulo y lo dibuje de la siguiente manera
print('introduce la altura de tu trianuglo')
altura = int(input())
anchura = altura
for i in range(altura+1):
print('*'*(altura-(i*1)))
|
b4104021daa233e13de184c1775404a3ea97151b | chanson20/battleship | /main.py | 1,961 | 3.609375 | 4 | import batlib
import time
#Heart of the Game
def main():
global turn,message,debug,map,shipcol,shiprow
while turn > 0: #Loop until turns are gone
batlib.clear(100)
print "BATTLE SHIP"
batlib.clear(2)
if debug == True:
print 'Coordinates are %s row and %s colum' % (shiprow,shipcol)
print messag... |
e56869731f3da0b497e669d5a8852aca9cac7a5f | lincrampton/pythonHackerRankLeetCode | /complexNumberMultiply.py | 675 | 4.03125 | 4 | '''A complex number can be represented as a string on the form "real+imaginaryi" where:
real is the real part and is an integer in the range [-100, 100].
imaginary is the imaginary part and is an integer in the range [-100, 100].
i2 == -1.
Given two complex numbers num1 and num2 as strings, return a string of the compl... |
f408be4608e59ad50983997bd3a1ea06dc35b351 | Pshowo/fastAPI-encryptor | /vigenere/encryptor.py | 4,071 | 3.65625 | 4 | import numpy as np
import string
import random
class Vigenere:
def __init__(self, alphabet, **kwargs):
self.raw_alphabet = alphabet
self.alphabet = self.gen_alphabet(self.raw_alphabet)
self.key_length = kwargs['key_length'] if "key_length" in kwargs else 8
self._ke = None
... |
6f4cfb4dfbe20907586e4e3091b59f479554906d | zhchua/vigenere-c2pytest | /vigeneremain2.py | 629 | 4.0625 | 4 | # input is basically printf and scanf combined
text = input('Enter text (preferably without spaces):\n')
key = input('Enter key\n')
# force uppercase for simplicity
text = text.upper()
from vigenereenc import rptkey
key = rptkey(text, key.upper())
def cmd():
# This doesnt work without the int
act = int(input... |
e838ba47e848752abef9ebbed0d7dc30f826e93f | collective/p4a.common | /p4a/common/formatting.py | 5,105 | 4.03125 | 4 | from datetime import datetime
from datetime import timedelta
ONE_DAY = timedelta(days=1)
def day_suffix(day):
"""
Return correct English suffix (i.e. 'st', 'nd' etc.)
>>> day_suffix(1)
u'st'
>>> day_suffix(6)
u'th'
>>> day_suffix(21)
u'st'
>>> day_suffix(26)
u... |
557b6cdf4d1666d85b7758f7ac93d117dc0226f1 | Jiawei-Wang/LeetCode-Study | /283. Move Zeroes.py | 2,705 | 3.5 | 4 | # 解法1:使用新的array
class Solution:
def moveZeroes(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
# 创建一个新array
newArray = [-1] * len(nums)
# 遍历nums,如果元素非0,放进新array,同时统计0的总数
totalZero = 0;
for i in range(len(nu... |
ae16defe708591a78d085ad10f461c5c17f083a1 | m4mayank/ComplexAlgos | /kthsmallest.py | 1,357 | 3.9375 | 4 | #!/home/cloud_user/.local/share/virtualenvs/algo-9u7x6JDZ/bin/python3
class Node:
def __init__(self, data):
self.left = None
self.right = None
self.data = data
def insert(self, data):
if data < self.data:
if self.left is None:
self.left = ... |
4ce4c3d208e665c7b857bf01a51a60ff91f335ff | canicode/project_cs303e.py | /Try Except Q&A Files.py | 574 | 3.8125 | 4 | def main():
while True:
try:
guess = int(input("Please enter your quess: "))
except ValueError:
print("Sorry, please put it into Arabic Numbers")
continue
else:
print("You are correct")
break
while True:
... |
6c77837dbcde3a72b1eacb67e73d928b09586491 | OmarAbdelrazek/8-Puzzle | /8puzzle.py | 8,277 | 3.734375 | 4 | import time
import sys
from math import sqrt
from collections import deque
import heapq
goal = [0,1,2,3,4,5,6,7,8]
nodes_expanded = 0
moves =[]
explored = {}
frontier = []
board_length = 0
board_side = 0
frontier_U_explored = set()
class Board:
def __init__(self,state: list,parent = None,move = "initial",cost= 0)... |
0d58c220d7065a6ac461f38e400b43f0e4925a84 | msaintja/computer-vision-archive | /PS0/code/PS0-3-code/PS0-3-code.py | 954 | 3.515625 | 4 | # Importing the opencv library for Python
import cv2
# Importing numpy for matrices/images handling
import numpy as np
# Importing matplotlib.pyplot to embed images within this notebook
import matplotlib.pyplot as plt
# 1. Input images
# Loading the 2 images downloaded
# from http://sipi.usc.edu/database/database.ph... |
7280349bc990e074eb87acf4118935d7a7941156 | NarendraPutta/Python_Documentation_till_OOPs | /Tuples.py | 1,094 | 4.5 | 4 | Tuples: Tuples are similar to the list that is these are the group of different type
of elements. The different between list & tuple is list is mutable that is we can alter the list
whenever we want but once we create the tuple. We can alter it.
So, tuple is immutable.
tuple =() #tuples are identified by paranthesis
#... |
ed4377f23f9114e24ba34a94f0c103a5a5863d31 | nsoft21/programming | /Practice/13/Python/13.py | 510 | 3.75 | 4 | k = 0
while (k == 0):
try:
a = int(input('Введите число: '))
if a < 2 or a > 10**9:
print('Вводимое число должно быть в пределах от 2 до 10^9 включительно!')
else:
k = 1
except:
print("Неверный формат ввода. Попробуйте еще раз:")
num = 2
while a % num != ... |
61d5931963772a6962229178e64847151813fb9d | epamekids/Danik_chatbot | /inter_2.py | 673 | 3.625 | 4 | i = 0
s = 0
d = 0
gr = []
par = []
while i < 20:
print("Say something !")
z = input()
v = input("If you greet me, type 'gr', otherwise 'par' ")
if v == 'gr':
if s == 0:
gr.append(z)
print("Hello you too!")
elif s > 0:
if z in gr:
print("Hello you too!", "you have already wrote this")
else:
... |
e7f36451def6e1721e757594de8e330e47a47741 | pinturam/PyCodeChallenges | /Factorial.py | 330 | 4.28125 | 4 | # program to find factorial of a number
num = int(input('enter a number: '))
factorial = 1
if num < 0:
print('sorry, factorial does not exist for negative number')
elif num == 0:
print('factorial = 1')
else:
for i in range(1, num+1):
factorial = factorial*i
print('the factorial = ', ... |
a6b4c5ce8007f107a0824a3fafd6f33464e7888c | JorgeDPSilva/LCC | /2ºAno/2ºSemestre/LA2/retangulos.py | 1,270 | 3.703125 | 4 | import sys
'''
def make_rectangules(first_coordenates, second_coordenates):
for y in range(second_coordenates[1]-first_coordenates[1]+1):
for x in range(second_coordenates[0]-first_coordenates[0]+1):
print('#')
def main():
aux_list = []
for line in sys.stdin:
l... |
12e9c0ce7579da6bf49bcb9a9f7e9aa0ca54fba5 | RomainFloreani/Comp598-Project | /filtering_the_post.py | 3,446 | 3.8125 | 4 | import json
import pandas as pd
import re
import random
import argparse
def get_post_titles(inp):
"""
(file) --> (list)
this function takes as input a file with Reddit post collected with the reddit API
returns a list of all the titles of each of the posts.
"""
list_of_titles = []
file_in ... |
5ce7ba3e97884502cc37ba8bcb675dacf8844206 | Lor3nzoMartinez/Python | /SPR19/Quiz&EC/TakeHome_Quiz_5_2.py | 871 | 3.625 | 4 | import math
def circleArea(R):
A = math.pi*R**2
return round(A, 2)
def circleCircumference(R):
C = 2*math.pi*R
return round(C, 2)
def cylinderArea(R, H):
SA = (circleCircumference(R)*H)+(2*circleArea(R))
return round(SA, 2)
def cylinderVolume(R, H):
V = circleArea(R)*H
return rou... |
4dde3bf3ae91901d0769b95a004deb2450d0e0db | RianMarlon/Python-Geek-University | /secao5_estruturas_condicionais/exercicios/questao38.py | 2,838 | 4.1875 | 4 | """
38) Leia uma data de nascimento de uma pessoa fornecida através de três números
inteiros: Dia, Mês e Ano. Teste a validade desta data para saber se esta é uma
data válida. Teste se o dia fornecido é um dia válido: dia > 0, dia <= 28 para o mês
(29 se o ano for bissexto), dia <= 30 em abril, junho, setembro e novemb... |
1bce53158baf61b46e8f46a56d7b9dda229105e9 | SergeyMakhotkin/client_server_apps | /L_1/task_4.py | 629 | 3.625 | 4 | # Преобразовать слова «разработка», «администрирование», «protocol», «standard» из строкового
# представления в байтовое и выполнить обратное преобразование (используя методы encode и decode).
VAR_1 = 'разработка'
VAR_2 = 'администрирование'
VAR_3 = 'protocol'
VAR_4 = 'standard'
VAR_LIST = [VAR_1, VAR_2, VAR_3, VAR_4... |
6c16de233f4c52031b359daf0dccaeb054bece98 | Jaehi/python_practice | /데코레이터_사용하기/decorator_functools_wraps.py | 512 | 3.640625 | 4 | import functools
def is_multiple(x):
def decorator(func):
@functools.wraps(func)
def wrraper(a,b):
r = func(a,b)
if r % x == 0:
print(f'{func.__name__}의 반환값은 {x}의 배수가 맞습니다')
else:
print(f'{func.__name__}의 반환값은 {x}의 배수가 아닙니다')
... |
fb689bb13db17910ffe49b62f51a7590b672dccd | sudoheader/TAOD | /powerball_simulator_app.py | 2,211 | 4.28125 | 4 | #!/usr/bin/env python3
import random
print("---------------------Power Ball Simulator---------------------")
white_balls = int(input("How many white-balls to draw from for the 5 winning numbers (Normally 69): "))
if white_balls < 5:
white_balls = 5
red_balls = int(input("How many red-balls to draw from for the Pow... |
6f3fdfe71476b92790abdbca3efe1fc411a640b1 | alexandraback/datacollection | /solutions_2700486_0/Python/debiatan/B.py | 1,422 | 3.765625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
def read_int(f): return int(f.readline().strip())
def read_l_int(f): return [int(e) for e in f.readline().strip().split()]
possible_worlds = []
def simulate(world, N):
if not N:
possible_worlds.append(world)
return
x, y = 0, 0
wh... |
5794c78f3bf2909ea2b61cb1333a1f29ac94bb51 | manutdmohit/mypythonexamples | /pythonexamples/exceptionhandling2.py | 343 | 3.71875 | 4 | try:
x=int(input('Enter First Number:'))
y=int(input('Enter Second Number:'))
print('The result:',x/y)
except BaseException as msg:
print('The type of exception:',type(msg))
print('The type of exception:',msg.__class__)
print('The name of class',msg.__class__.__name__)
print('The Description... |
88b1cd889dae0c91d0a6058039cfb8abd46b9984 | mel-c-lowe/Python_Challenge | /PyPoll/main.py | 4,545 | 3.796875 | 4 | # Import OS and CSV modules
import os
import csv
# Establish file path
election_csv_file = os.path.join("Resources", "election_data.csv")
# Set up to read election_csv_file and refer to it as election_data
with open(election_csv_file) as election_data:
# Build the csvreader, print header to confirm document is... |
0e44a922469c03352806da764e57dfa0814af93c | mishaplx/hackerrank | /task_2_1_1.py | 602 | 3.625 | 4 | # задать список студентов с оценками (name scores) и вывести среднюю оценку зная имя студента
if __name__ == '__main__':
n = int(input())
sum = 0
answer = 0
student_marks = {}
for _ in range(n):
name, *line = input().split()
scores = list(map(float, line))
student_marks[name]... |
012e49f2772e6106a1d288550ccb5defe00088be | DZAymen/dz-Trafico | /dzTraficoBackend/dzTrafico/BusinessEntities/LCRecommendation.py | 677 | 3.546875 | 4 |
class LCRecommendation:
TURN_LEFT = -1
TURN_RIGHT = 1
STRAIGHT_AHEAD = 0
CHANGE_TO_EITHER_WAY = 2
change_lane = True
change_to_either_way = False
recommendation = 0
def __init__(self, lane, recommendation):
self.lane = lane
self.recommendation = recommendation
... |
99b44e11888b9edddfedbff223001c380b14d9ee | bzd111/PythonLearn | /decorator_use/decorator_def_with_args.py | 708 | 3.59375 | 4 | # -*- coding: utf-8 -*-
from functools import wraps
def decorate_args(name):
def warp(func):
@wraps(func)
def warp_func(*args, **kwargs):
print('{} say:'.format(name))
return func(*args, **kwargs)
return warp_func
return warp
@decorate_args(name='zxc')
def s... |
3b9e631b1cdf496234f6635dafafff14b9ce24b9 | haileytyler/cmpt120-tyler | /Classwork/1.7.19Classwork.py | 1,281 | 4.21875 | 4 | #Hailey Tyler
#Lab 3
from math import *
#4
#a
for i in range(1, 11):
print(i*i)
#b
for i in [1, 3, 5, 7, 9]:
print(i, ":", i**3)
print(i)
#c
x = 2
y = 10
for j in range(0, y, x):
print(j, end="")
print(x + y)
print("done")
#d
ans = 0
for i in range(1, 11):
ans = ans + i*i
print(i)
print(ans)
#2... |
1607fff42a84cbf0cfe8f2e29e65dda7ceedb23f | liusska/Python-Basic-Sept-2020-SoftUni | /ConditionalStatment/ex/2.BonusScore.py | 309 | 3.53125 | 4 | number = int(input())
bonus = 0
if number <= 100:
bonus += 5
elif number > 100:
if number > 1000:
bonus += number * 0.10
else:
bonus += number * 0.20
if number % 2 == 0:
bonus += 1
elif number % 10 == 5:
bonus += 2
print(bonus)
print(bonus + number)
|
dbf4b44474d1c922b694d4775333f9b091643d1e | vsofi3/UO_Classwork | /313/OwenMcEvoy_Lab3/OwenMcEvoy_MaxHeap.py | 4,422 | 3.953125 | 4 | class MaxHeap(object):
def __init__(self, size):
# finish the constructor, given the following class data fields:
self.__maxSize = size
self.__length = 0
self.__myArray = [] #i will be using the append feature, the list size is exactly how many items there are this way
'''... |
0f1eea9e2d131bef30feadf75380ed92a1f34c92 | imgsc/assistScript | /pokerLife/pokerLife.py | 836 | 3.8125 | 4 | '''
Listen to me
What's your poker life?
Please put your birthday
and you can see your life...
'''
import datetime,time
def getPoker(str):
t=time.strptime(str,'%Y-%m-%d')
y,m,d = t[0:3]
#print (datetime.datetime(y,m,d))
pokerNumber = ['Ace','Two','Three','Four','Five','Six','Seven','Eight','Nine','Ten','... |
15533ace6ab93490bfde15364120c5c0c3b5ae3c | darkframemaster/here-and-there | /python/pygame/day_three/day_three_arc.py | 585 | 3.96875 | 4 | #!/usr/bin/env python2.7
import math
import pygame
from pygame.locals import *
pygame.init()
screen=pygame.display.set_mode((600,500))
pygame.display.set_caption("Drawing Arcs")
while True:
for event in pygame.event.get():
if event.type in (QUIT,KEYDOWN):
#More Python Programming 30 gramming for the Absolute Begin... |
87cb54327684e8564caad04da370f993a1fc627a | 121jigowatts/til | /python/basis/file_operations/text_reader.py | 267 | 3.53125 | 4 | # text file reader
import os
path = './text.txt'
if os.path.exists(path):
with open('text.txt', 'r') as f:
print(f.read())
while True:
line = f.readline()
print(line, end='')
if not line:
break
|
a78727bba0ccf3ccd05747d64f47f375c36d2a36 | AugmentHCI/Tobii4C | /Experiment/Vector.py | 2,360 | 3.546875 | 4 | import math
import numpy as np
class Vector:
def __init__(self, p1, p2):
"""
:param p1: Coordinate
:param p2: Coordinate
"""
self.startPoint = p1
self.endPoint = p2
self.vector = self.calculateVector()
self.direction = None
self.setDirection... |
9e0b1c76f509e42f4384bb56bc96ca0191ac2967 | rahul-bhave/python-practice | /random_generator.py | 2,816 | 4.21875 | 4 | """
This script is an example of how to pick groups of 'r' people randomly from within a larger sample of N people such that no single person appears in two groups.
I find this script useful when I have to divide my employees into groups randomly
First Output:
$ python random_generator.py
Groups chosen are:
0. ('Shi... |
54572845440f7150285779f961629266fa23be08 | DoctorTeeth/diffmem | /ntm/memory.py | 1,878 | 4.09375 | 4 | """
Implements functions for reading and writing from and to the memory bank
via weight vectors as in section 3.
"""
import autograd.numpy as np
def read(mem, weight_vector):
"""
The reading procedure as described in 3.1.
weight_vector (w_t below) is a weighting over the rows such that:
1. \sum_i ... |
75a5b6d1b7e60a8d3ddf4c8732f6c1d041d7bc19 | AJEET-JAISWAL922/Condition | /Ifelse.py | 147 | 4.0625 | 4 | a=3
b=5
if b % a == 0:
print("b is divisible by a")
elif b+1 == 10:
print("increement in b produce 10")
else:
print("you are in else")
|
e3fcc01a7ba4d0084d536859d553cb71c889f555 | Ivan6248/uiuc | /leetcode/two-sum.py | 1,365 | 3.71875 | 4 | # Given an array of integers, return indices of the two numbers such that they add up to a specific target.
# You may assume that each input would have exactly one solution.
# Example:
# Given nums = [2, 7, 11, 15], target = 9,
# Because nums[0] + nums[1] = 2 + 7 = 9,
# return [0, 1].
# UPDATE (2016/2/13):
# The return... |
b5413854357454b58e843d3f2c7081e126f2785e | joook1710-cmis/joook1710-cmis-cs2 | /function.py | 3,016 | 3.859375 | 4 | #Added two arguements
def add(a,b):
return a + b
c = add(3, 4)
print c
#Subtraction two arguements
def sub(j,k):
return j - k
l = sub(5, 3)
print l
#Multiplied two arguements
def mul(r,t):
return r * t
e = mul(4,4)
print e
#Divided two arguements
def div(q,w):
return float(q / w)
y = div(2,3)
print y
#Def... |
ccec1917e26009da120a4f796c47720bd3f1dda8 | wpy-111/python | /month01/progect_month01/game2048/bill.py | 2,660 | 3.59375 | 4 | """
2048游戏核心算法
"""
import random
class GameCoreController:
def __init__(self):
self.list_merge=None
self.__map = [[0, 0, 0, 0],
[0, 0, 0, 0 ],
[0, 0, 0, 0 ],
[0, 0, 0, 0]]
self.__list_blank_location=[]
@property
def m... |
c342f4445e068d3cb94dad84361903773cb46255 | AdamZhouSE/pythonHomework | /Code/CodeRecords/2533/60643/235145.py | 183 | 3.78125 | 4 | lst=input()#输入默认是列表
even = []
odd=lst
for i in lst:
if i%2==0:
even.append(i)
for i in even:
if i in odd:
odd.remove(i)
res = even+odd
print(res) |
650746152141a9c2c46fe14a1f1c1483e98d3c46 | KRLoyd/holberton-system_engineering-devops | /0x18-api_advanced/0-subs.py | 953 | 3.5 | 4 | #!/usr/bin/python3
"""
Module for Task 0 of Holberton Project #314
"""
import requests
import sys
def number_of_subscribers(subreddit):
"""
Queries the Reddit API for the number of subscribers for a subreddit.
Subreddit is passed as an argument.
If the subreddit is not valid, 0 is returned.
"""
... |
5bd7d0acac6c14256f22f3ce09077888dbe8424d | JulyKikuAkita/PythonPrac | /cs15211/plusone.py | 2,818 | 3.640625 | 4 | __source__ = 'https://leetcode.com/problems/plus-one/'
# https://github.com/kamyu104/LeetCode/blob/master/Python/plus-one.py
# Time: O(n)
# Space: O(1)
# Array
#
# Description: Leetcode # 66. Plus One
#
# Given a non-negative integer represented as a non-empty array of digits, plus one to the integer.
#
# You may assu... |
4ca8f48590cab2de6ba8dd2656607f03ac40cb1e | cpfyjjs/python | /FluentPython/16协程/04让协程返回值(StopInteration).py | 525 | 3.90625 | 4 | from collections import namedtuple
Result = namedtuple('Result','count average')
def averager():
total = 0
count =0
average = None
while True:
num = yield
if num == None:
break
total +=num
count +=1
average = total/count
return Result(count,aver... |
246cdf8901d141ad8d1278ac283b6626458bcd7b | piweiblen/Number_Reader | /mlpt.py | 5,287 | 3.953125 | 4 | # defines a multilayer perceptron neural network class and associated algorithms
import numpy as np
import math
def sigmoid(x):
"""perform sigmoid function"""
if x < 0:
a = math.e**x
return a / (1 + a)
else:
return 1 / (1 + math.e**(-x))
def arr_sigmoid(arr):
"""perform sigmo... |
3bb25e45db2dfef9974ced3ac9d7ddceaa469e29 | Goom11/interview_practice | /islands/islands.py | 839 | 3.5 | 4 | #!/usr/bin/env python
import itertools as it
def islands(seq):
top = max(seq)
if top == 0:
return 0
seq = [list(group) for _, group in it.groupby(seq, lambda x: x == top)]
cur_islands = sum(1 for x in seq if top in x)
seq = list(it.chain(*seq))
seq = [el if el != top else top - 1 for e... |
43d8810f175171bd1568ffacea1a18f3368671f4 | hsiaohan416/stancode | /SC_projects/games/quadratic_solver.py | 938 | 4.25 | 4 | """
File: quadratic_solver.py
-----------------------
This program should implement a console program
that asks 3 inputs (a, b, and c)
from users to compute the roots of equation
ax^2 + bx + c = 0
Output format should match what is shown in the sample
run in the Assignment 2 Handout.
"""
import math
def main():
""... |
809812b090105adc4609194e8cb5cea78d22efdb | tcq1/epa | /epa_graphs.py | 4,363 | 3.5625 | 4 | import random
import copy
import collections
def choose_nodes(choosen, target_nodes, edges):
"""
choose `edges` nodes from `target_nodes`, whitout `chossen` and doubled nodes
Function is side effect free
@param choosen list of already chossen elements
@param list to choose elements from
@p... |
c57ecf5bf9ee70941186d6334e39ace1e1bc4f53 | shi429101906/python | /07_语法进阶/hm_16_多值参数.py | 282 | 3.6875 | 4 | def demo(num, *nums, **person):
print(num)
print(nums)
print(person)
# demo(1)
demo(1, 2, 3, 4, 5, name="小明", age=18)
# atuple = (2, 4, 6) 直接传递元祖跟上面的不一样, 相当于元祖中又放了一个元祖
# demo(1, atuple, name="小明", age=18)
|
7eb7ec200e6794859fcdb18e95127bf4f4667127 | estraviz/codewars | /7_kyu/Regex validate PIN code/test_solution.py | 1,064 | 3.53125 | 4 | from solution import validate_pin
def test_should_return_False_for_pins_with_length_other_than_4_or_6():
assert validate_pin("1") is False
assert validate_pin("12") is False
assert validate_pin("123") is False
assert validate_pin("12345") is False
assert validate_pin("1234567") is False
assert... |
0f253e5c5f347c7bdffef7ffb44801947f58b268 | JaeZheng/jianzhi_offer | /62.py | 768 | 3.75 | 4 | """
题目描述
给定一棵二叉搜索树,请找出其中的第k小的结点。例如, (5,3,7,2,4,6,8) 中,按结点数值大小顺序第三小结点的值为4。
"""
# -*- coding:utf-8 -*-
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
# 返回对应节点TreeNode
def KthNode(self, pRoot, k):
list = self.inorderTra... |
8456b880078e2a3dd496a83347cc22b49866896a | YashaswiniPython/pythoncodepractice | /13_Loops.py | 1,300 | 4.03125 | 4 | # Python file Created By Bibhuti
# for i in range(1,5) : # loop
# print(i)
#
# print("Value outside the loop ",i);
# for i in [1,2,8,5]:
# print(i);
#for i in (1,2,8,5):
#print(i);
# for i in {1,2,8,5}:
# print(i);
# for i in {1:2,"a":"Value of a",4:3}:
# print(i);
# for i in "Python" :
... |
dae5ae2efb31ebc3ef29a8cf9a6cd2e6a3e58ef9 | MinjeongSuh88/python_workspace | /20200720/test5.py | 230 | 3.6875 | 4 | # 사용자로부터 숫자를 입력받아 홀수인지 짝수인지 판단
num=int(input("숫자를 입력하시오"))
if num%2 == 0:
print(num,"은 짝수입니다.")
elif num %2 != 0:
print(num,"은 홀수입니다.")
|
ca92472288c720adf4bf3685d7e501e155785199 | MikiTeplitsky/PokerGame | /Poker_Game.py | 7,520 | 3.734375 | 4 | # Poker Game class
# high card, pair, two pair, three of a kind, straight, flush, full house,
# four of a kind, straight flush, royal straight flush(poker)
#
from Poker_Player import *
from Deck import *
from constants import *
from Poker_Table import *
# sum the values of the cards - working
def sum_of_cards(... |
d04c6e0d3219e1ba6beeede86aec0aa9d5cacad0 | footloops/Photo-To-ACSII | /PhotoToACSII/main.py | 1,499 | 3.859375 | 4 | from PIL import Image
#Sorted from darkest symbol to lightest
symbols = ["@", "#", "$", "%", "?", "*", "+", ";", ":", ",", "."]
#Convert the pixels to the proper corresponding ASCII text
def pixel_to_ascii(img):
pixels = img.getdata()
ascii_str = ""
for pixel in pixels:
#Divid the pixel
as... |
40f44b2177e12ad07ad2bb35f5a587bf1da687e5 | kavyakammaripalle/python | /Day10-Session.py | 549 | 3.578125 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[7]:
#classes:superclass-subclass
class A:
v1='iam variable one'
v2='iam variable two'
class B(A):
pass
a=A()
a.v1
b=B()
b.v2
# In[11]:
#Overwrite a variable
class A:
v1='iam variable one'
v2='iam variable two'
v3='iam variable three'
v4='i... |
8438e6eff938a5764c2c3e40ed668714c54773d0 | DanielWu18316/keyword-quiz | /main.py | 1,900 | 3.578125 | 4 | import random
def setup():
global info, keywords, desc
f = open("keywords.txt")
info = f.readlines()
f.close()
keywords = []
desc = []
for i in range(0, len(info), 2):
keywords.append(info[i])
for i in range(1, len(info), 2):
desc.append(info[i])
process()
def pro... |
b94abd64d9ffb4a2af109cfa34c4f34c5b0a9b7c | chaunceyt/apisnoop | /dev/user-agent-stacktrace/lib/utils.py | 291 | 3.5 | 4 | from collections import defaultdict
def defaultdicttree():
return defaultdict(defaultdicttree)
def defaultdict_to_dict(d):
if isinstance(d, defaultdict):
new_d = {}
for k, v in d.items():
new_d[k] = defaultdict_to_dict(v)
d = new_d
return d
|
8fd8d6873c0cf67ab012b1c3a52cd937193438de | chsclarke/Python-Algorithms-and-Data-Structures | /coding_challenge_review/LL_questions.py | 4,309 | 4.46875 | 4 | # -*- coding: utf-8 -*-
"""
This is an example of a Doubly Linked List in Python 3.
Copyright 2018 Chase Clarke cfclarke@bu.edu
"""
class Node:
def __init__(self,val):
self.val = val
self.next = None
self.prev = None
class LList:
def __init__(self, node):
self.head =... |
480753a9cf15b2ca18814ccfd7d0e2c79f6d6232 | zheng1073/Grokking-the-Coding-Interview-Patterns-for-Coding-Questions | /Pattern: Merge Intervals/Pattern_MergeIntervals.py | 1,935 | 4.28125 | 4 | """
Deals with overlapping intervals. In a lot of problems involving intervals, we either need to find overlapping intervals or merge intervals if they overlap.
Six ways 2 intervals can relate to each other.
1. 'a' and 'b' do not overlap; 'a' before 'b'
2. 'a' and 'b' overlap and 'b' ends after 'a'
3. 'a' comple... |
655447f43817d241cc30f6715596a2f631957820 | SNithiyalakshmi/pythonprogramming | /Beginnerlevel/oddeven.py | 117 | 3.78125 | 4 | a=int(input())
if(a==0):
print 'zero value'
elif(a>=1 and a<=100000):
print 'even value'
else:
print 'odd value'
|
3dd9e13d0dd32e098150e68b9ee292c05b615573 | ma-lijun/ISO100-Stock | /stk_prc.py | 3,128 | 3.53125 | 4 | #Created on 2015/06/15, last modified on 2016/05/04
#By Teague Xiao
#This script is aim to download the current price of a specific stock from SINA Stock
#The info of each column is: stock number, stock name, opening price today, closing price today, current price, highest price today,lowest price today,don't know, do... |
165384d3827b4f02899c3068d9794669ec08c926 | lixinchn/LeetCode | /src/0130_SurroundedRegions.py | 4,107 | 3.609375 | 4 | class Solution(object):
def solve(self, board):
"""
:type board: List[List[str]]
:rtype: void Do not return anything, modify board in-place instead.
"""
island_set = {}
mapping = [[]]
island_flipping = []
len_board = len(board)
island = 1
... |
98af31b797f940f1363a87fc228a360252ed753e | justega247/python-scripting-for-system-administrators | /bin/exercises/exercise-3.py | 1,644 | 4.25 | 4 | #!/usr/bin/env python3.7
# Building on top of the conditional exercise, write a script that will loop through a list of users where each item
# is a user dictionary from the previous exercise printing out each user’s status on a separate line. Additionally,
# print the line number at the beginning of each line, starti... |
2867d0b759a5b916311ad504b07f330a1772714a | himanshuchelani/Python_course | /day1/bhubali2vsdangal.py | 1,314 | 4.09375 | 4 |
"""
Code Challenge: Simple Linear Regression
Name:
Box Office Collection Prediction Tool
Filename:
Bahubali2vsDangal.py
Dataset:
Bahubali2vsDangal.csv
Problem Statement:
It contains Data of Day wise collections of the movies Bahubali 2 and Dangal
(in crores) for the first 9 days.
... |
f8282da37f8add94c6f7c3d9029cfe030912bc7b | baishuai/leetcode | /algorithms/p138/138.py | 1,327 | 3.90625 | 4 | # package p138
# A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null.
# Return a deep copy of the list
# Definition for singly-linked list with a random pointer.
class RandomListNode(object):
def __init__(self, x):
self.label... |
9367598b75c333e2ac61f561483a5dc5f1510f1d | tylerkrupicka/practice | /ch2/28.py | 691 | 4.03125 | 4 | # Loop Detection
# return the node at loop beginning of circular linked list
from linked_list import *
def detect_loop(l):
r1 = l.head
r2 = l.head
first = True
while(first or r1 != r2):
first = False
r1 = r1.next
r2 = r2.next.next
if r1 == None or r2 == None:
... |
a0fc2bab6e7fd99b8686c01cf245e4812cbf56e4 | JSNavas/CursoPython2.7 | /Metodos de los Diccionarios/Metodo del() y clear().py | 980 | 4.375 | 4 | # encoding: utf-8
dic = {'nombre': "", 'apellido': ""}
print
dic['nombre'] = raw_input("Ingrese su nombre: ")
dic['apellido'] = raw_input("Ingrese su apellido: ")
print
print dic['nombre'], dic['apellido']
print
print "(1) Si desea eliminar su nombre."
print "(2) Si desea eliminar su apellido. \n"
n... |
d397d4ceb5ab9ad3bf39f05c7b66f78efdadcf87 | vianairan/JobDash-Assignment---Iranga-Samarasingha | /Assignment - Iranga Samarasingha/Part 2 - Word Cloud Script/word_clouds.py | 2,840 | 4.21875 | 4 | # -*- coding: utf-8 -*-
"""
Date: Jan 23rd, 2015
@author: Iranga Samarasingha
Purpose: Assignment for JobDash
Question: Write a stand alone Python script that creates word clouds.To do this, you'll first need to build the data. Write code that takes a long string and builds its word cloud data in a dictionary, where t... |
c15f7b0e33b8a26518310e14d2202e9230a65504 | ynsong/Introduction-to-Computer-Science | /a05/a05q2.py | 2,532 | 3.703125 | 4 | ##==============================================================================
## Yining Song (20675284)
## CS 116 Spring 2017
## Assignment 05, Problem 2
##==============================================================================
import check
## list_stat(lst) produces a list containing exactly 5 n... |
2faf41a82ad05bdf0e42ea280eb88da6b43569fa | pallav12/numerical_techniques | /nt.py | 1,999 | 3.640625 | 4 | import sys
import argparse
global a
global df
def fx(n):
return eval(a.replace('x',str(n)))
def dfx(n):
return eval(df.replace('x',str(n)))
def solve(l,r,n):
mid=(l+r)/2
print('lower limit {}, upper limit {}, iteration {}, fx(mid) {}'.format(l,r,n,fx(mid)))
if(n==0):
return fx(mid)
i... |
30304588c5dc46f32bd13a4617e16ac9b577425b | mskl/fit-bi-zns-homeworks | /ulohy/02/Graph/Node.py | 2,799 | 3.53125 | 4 | class Node:
def __init__(self, id, name="Unnamed node"):
"""
Generate a new node.
:param id: unique id
:type id: int
:param name: name of the node
:type name: str
"""
self.edges_out = set()
self.edges_in = set()
self.height = 0
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.