blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
6d0a425e68560d831d5e7d13bb4e0ff47b47fe69 | FPPYTHON-21/ac-helloworld-Chepexz | /assignments/00HelloWorld/tests/test_exercise.py | 1,443 | 3.71875 | 4 | import pytest
import src.exercise
from tests.input_data import input_values
# Define the parametrization based on the inputs from the input_data file
@pytest.mark.parametrize('value, result, message', input_values)
def test_exercise(value, result, message):
"""
Tests the code in src.exercise using the inputs ... |
063a9bed8bfa1cdc52073e66cf88bde331034519 | wvdb/pocPython1 | /paps/introduction/FileLees.py | 217 | 3.578125 | 4 | file = open('FileLees.txt')
for line in file:
counterOfChars = 0
for char in line.strip():
# print (char)
counterOfChars += 1
print ("er zijn", counterOfChars, "chars in de regel <<<", line.strip(), ">>>")
|
3b51c6b69472acfb105874ccc2b828ae47f3697d | Rifleman354/Python | /Python Crash Course/Chapter 9 Exercises/Imports/pythonGlossary2.py | 475 | 3.5625 | 4 | from collections import OrderedDict
python_glossary = OrderedDict()
python_glossary['variables'] = 'storing individual pieces of information'
python_glossary['if_statements'] = 'conditional statement that returns a boolean value'
python_glossary['boolean'] = 'true or false value'
python_glossary['string'] = 'a... |
4f7a86c1c55b103702f0b640d7dd90c7831338fd | rafaelperazzo/programacao-web | /moodledata/vpl_data/333/usersdata/297/100397/submittedfiles/contido.py | 473 | 3.703125 | 4 | # -*- coding: utf-8 -*-
def contido(a,b,n,q):
q=0
for i in range(0,n,1):
if a[i] in b:
q=q+1
return print(q)
n=int(input('digite o numero de elementos que a lista a tera: '))
m=int(input('digite o numero de elementos que b lista a tera: '))
a=[]
b=[]
for i in range(0,n,1):
a.append(... |
942b18371711e06099250b0134d5d26a810cbaeb | AlwaysSmiling/OCR-Project-Creation | /GAR/spell_check.py | 553 | 3.515625 | 4 | from spellchecker import SpellChecker
import io
with io.open('raw_output.txt', 'r', encoding='utf-8') as c:
content = c.read()
content_list = content.split()
correct_list = []
spell = SpellChecker()
for words in content_list:
if spell.known([words]):
correct_list.append(words)
... |
d82157fedfba1634e8ab6edfe7e679f470936e89 | weixunhe18/NBA-assist-thesis | /ultimateParsing.py | 7,361 | 3.6875 | 4 | import pandas as pd
import csv
import numpy as np
import glob
def assistDetection(input_team, input_year):
'''
user inputs a specific team and year, then the function pulls up the names of everyone
on the relevant roster and searches through the 82 games of data to look for passing activity
between players on... |
a43794257b6ad4b157f50d536f5e9849791b0acd | abhisheksaxena1998/DataStructures-Algorithms-Python | /strings/anagrams.py | 250 | 3.859375 | 4 | def anagrams(a,b):
if(sorted(a)==sorted(b)):
return True
return False
while True:
try:
a,b=map(str,input("Enter a and b: ").split())
print(anagrams(a,b))
except:
print("invalid input!")
break |
b40377573b87a873791b08d90fb6e4bcba1f055d | su-ram/Problem-Solving | /백준/문자열/단어 정렬.py | 154 | 3.734375 | 4 | n = int(input())
words = [ input() for _ in range(n)]
words = set(words)
words = sorted(words, key=lambda x : (len(x), x))
[print(word) for word in words] |
4856f077fb3f17959ab48b801884513104983b5d | YulongWu/AlgoExercise_CPP | /leetcode/2016/55_JumpGame.py | 595 | 3.71875 | 4 |
class Solution(object):
def canJump(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
if not nums or len(nums) == 0:
return False
flags = [False] * len(nums)
flags[0] = True
i, max = 0, 1 #performance error: don't use max to improve ... |
a06fae99a09bcabc51613a1cff9e3ed88db5949b | HongSun2da/Python | /nadocoding/webscraping/project.py | 2,212 | 3.5 | 4 | import requests
from bs4 import BeautifulSoup
def create_soup(url):
headers = {"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36"}
res = requests.get(url, headers=headers)
res.raise_for_status()
soup = BeautifulSoup(res.... |
4bcbb884bfee0213539f3811261358372367d90e | ubiratann/CK0048 | /derivacao/polinomio.py | 1,055 | 3.59375 | 4 | def polinomio(x,poli):
y = 0
a = len(poli)-1
for i in range(0,len(poli)):
y+= poli[i]*pow(x,a)
a -= 1
return y
def gerarpolinomio(grau):
poli = []
flag = True
flag2 = False
while flag:
lista = input("Insira os coeficientes, separados por vírgulas(,) >>... |
6e1ed97a62748d96a525c8f533e69240517d0aad | chuypy/TareaParaExamen | /Multiplo.py | 646 | 4.0625 | 4 | numero=int(input("dame un numero entero: "))
#se almacenan valores booleanos la evaluacion de residuales. Si el residual es cero, quiere decir que el numero es multiplo
esMultiplo3=((numero%3)==0)
esMultiplo5=((numero%5)==0)
esMultiplo7=((numero%7)==0)
#cuando se usa and, se resuelve por erdadero si todas las ... |
06616757641239693eb242c93f47af24f174d038 | claudiodornelles/CursoEmVideo-Python | /Exercicios/ex024 - Verificando as primeiras letras de um texto.py | 288 | 3.96875 | 4 | """
Crie um programa que leia o nome de uma cidade e diga se ela começa ou não
com o nome "SANTO".
"""
# Recebendo os dados do usuário
cidade = input('Digite o nome de uma cidade: ').lower()
# Processamento dos dados]
cidade_lista = cidade.split()
print('santo' in cidade_lista[0])
|
6959ff12e6f7a76c035099db7d389f8ce07ab562 | itomoki/develop-python | /code9_1.py | 362 | 3.578125 | 4 | def squareRootExhaustive(x, epsilon):
"""xとepsilonを性のfloat型とし、かつepsilon < 1であるとする
y*yとxのゴザがepsilon以内であるようなyを返す"""
step = epsilon**2
ans = 0.0
while abs(ans**2 - 2) >= epsilon and ans*ans <= x:
ans += step
if ans*ans > x:
raise ValueError
return ans
|
7bac18dc3d3ec13fef5494e5a4d48de956327b40 | FelixTheC/hackerrank_exercises | /hackerrank/birthdayCakeCandles.py | 459 | 3.765625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@created: 09.05.20
@author: felix
"""
import math
import os
import random
import re
import sys
# Complete the birthdayCakeCandles function below.
def birthdayCakeCandles(ar):
max_ar = max(ar)
return sum([1 for i in ar if i == max_ar])
if __name__ == '__main_... |
ccc73e7cb905a8070e71148626f5d0b74392373c | jainrahul5977/python | /ques7_1.py | 274 | 3.515625 | 4 | l = eval(input("enter the list"))
print("a " , len(l))
print("b" , l[-1])
print("c" , l.reverse())
if 5 in l:
print("yes")
else :
print("no")
print(l.count(5))
l.pop(0)
l.pop(-1)
l.sort()
print(l)
count=0
for item in l:
if item<5:
count+=1
print(count)
|
0ff6b31b0dd48b9381d6ef11b31b2b9f80d1fdc2 | martinahra/my-first-blog | /test.py | 448 | 3.953125 | 4 | print('Hello, Django girls!')
if 3>2:
print('Funguje to!')
name ='Sonja'
if name == 'Martina':
print('Ahoj Martina!')
elif name == 'Janka':
print('Ahj Janka!')
else:
print('Ahoj!')
def hi():
print('Ahoj!')
print('Ako sa mas?')
hi()
def hi(meno):
print('Ahoj' + meno + '!')
hi('Katka')
def hi(meno):
print('Ah... |
73cc90f928c08c805af79d8598717a25f91b9952 | THPY2020/groupsix | /app/utilities/__init__.py | 1,416 | 4.09375 | 4 | from datetime import datetime, timedelta
# Various helper functions. Formatting, datetime helpers etc.
def print_dict(my_dict):
for key, value in my_dict.items():
print(f'{key}: {value}')
def divider():
print('-' * 150)
def nextdate(date1, span=1):
"""
Calculates next date
:param date... |
fe5bd4169ae53354946fc717c327b2a56c8639b1 | hevi1991/python3-demos | /37-use-asyncio.py | 4,810 | 3.796875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
使用异步IO(协程)
"""
import time
import asyncio
now = lambda: time.time()
def define_a_async_job():
"""
定义一个协程
:return:
"""
async def do_some_work(x):
print('Waiting: ', x)
start = now()
# 写成执行的函数
coroutine = do_some_work(2)
... |
3ebeee5fca7fd899f1049417df4902975c75b593 | anonymousraft/Python | /Day1/variable_and_input.py | 168 | 4.21875 | 4 | #this programs ask user to enter his/her age and store in variable called age
age = input('Hello user Pls How old Are you:')
print('ok so you are ' + age + 'Years old') |
76211418e9bcd6edfe259556c70f09c90ada4744 | cheddalu/py4e | /5-2a.py | 911 | 4.125 | 4 | """5.2 Write a program that repeatedly prompts a user for integer numbers until the user enters 'done'.
Once 'done' is entered, print out the largest and smallest of the numbers.
If the user enters anything other than a valid number catch it with a try/except and put out an
appropriate message and ignore the numbe... |
8b76b1cf58b9ff9ad98e6c2da956439eaf3eb917 | Filjo0/PythonProjects | /Ch5.py | 1,205 | 4.6875 | 5 | """
Chapter 5.
2. Write a program that allows the user to navigate the lines of text in a file. The
program should prompt the user for a filename and input the lines of text into a
list. The program then enters a loop in which it prints the number of lines in the
file and prompts the user for a line number. Actual... |
9a009b2b9cb417e14eab3c86518c392ea9c50b53 | fabianllanten/ejercicios-creditos-3 | /ejercicio8.py | 181 | 3.703125 | 4 | numero = int(input("ingrese el valor"))
xciento = int(input("ingrese el porcentaje"))
por = (numero*xciento)/100
print("el "+str(xciento)+" % "+"de "+str(numero)+" es "+str(por)) |
d36507ef073b8ea630abad11086699840af6825b | sang4-uiuc/Daily-CC | /D8 UnivalTree.py | 2,290 | 4.25 | 4 | # A unival tree (which stands for "universal value") is a tree where all nodes under it have the same value.
# Given the root to a binary tree, count the number of unival subtrees.
# For example, the following tree has 5 unival subtrees:
# 0
# / \
# 1 0
# / \
# 1 0
# / \
# 1 1
class Node:
... |
d61bd53448eede46e4a86eaa7262f1306c8727c0 | alexforcode/leetcode | /200-299/209.py | 984 | 3.859375 | 4 | """
Given an array of positive integers nums and a positive integer target,
return the minimal length of a contiguous subarray [numsl, numsl+1, ..., numsr-1, numsr] of which the sum is greater
than or equal to target.
If there is no such subarray, return 0 instead.
Constraints:
1 <= target <= 10**9
1 <= nums.l... |
89366de09bc69fe13f4e905fa1c3bb311521e072 | sharad73/sct-py | /gcd.py | 1,839 | 4.375 | 4 | #!/usr/bin/python3
#Function to find the greatest divisor of two number
#Multiple function finds multiples of given number starting from one to max i.e given number
def multiple(m):
multiple = []
for i in range(1,m+1): #Added m+1 because the range excludes the max value in iteration
if m % i =... |
9fa0569f36ac80ec6227536d1c523e2813cb7535 | sarveshggn/Python | /square_area.py | 311 | 4 | 4 | class Square():
def __init__(self,side = 1):
self.side = side
def area(self):
print("Side length is "+ str(self.side))
print("Area of square is:")
return self.side**2
my_square = Square() #### PUT VALUES OF LENGTH AND BREADTH HERE####
print(my_square.area())
|
6c6639c59e5f116421568bacdc8394e36f5ee17f | luckyzachary/Algorithms | /Python3/leetcode/66_plus_one.py | 668 | 3.671875 | 4 | class Solution:
def plus_one(self, digits):
"""
:type digits: List[int]
:rtype: List[int]
"""
if digits[0] == 0:
return [1]
for i in range(len(digits) - 1, -1, -1):
if digits[i] == 9:
digits[i] = 0
else:
... |
24a4b9246a9b15334bebc45c532a25bd81266918 | lmy269/practices | /python/Tree/101SymmetricTree.py | 813 | 3.921875 | 4 | import collections
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def isSymmetric(self, root: TreeNode) -> bool:
if not root:
return True
... |
8a1e7911656c28a3e65c8201d066cbf10c7daf2c | thanasibakis/AntAlmanac-Course-Data | /Date.py | 2,182 | 3.78125 | 4 | # Description: a class representation of an enrollment date
# Author: Thanasi Bakis
# A date code is the integer index of the possible enrollment dates
# Converts a date code (0, 1, 2) to something human-readable (mon wk 8, tues wk 8, ...)
DATECODE_TO_TEXT = ("Monday of week 8", "Tuesday of week 8", "Wednesday of week... |
9d882c44f06089763f8d217816644de358585bc6 | shankar7791/MI-10-DevOps | /Personel/Rajendar/Python/Practice/23feb/prac4.py | 430 | 4.1875 | 4 | # Program 4 : Write a Python program to count the number of even and odd numbers from a series of numbers.
even = 0
odd = 0
n1 = int(input("Enter the start no: "))
n2 = int(input("Enter the end no: "))
num1 = n1
while n1 < n2:
if(n1 % 2 == 0):
even += 1
else:
odd += 1
n1 += 1
print(f"Even... |
cf41383964172c71dadf134b2105a345294fa66e | Zerobxx/Practice | /y16m7_calc/calc.py | 3,359 | 3.671875 | 4 | #conding=UTF-8
#This is a simple calculator
import re
import functools
def remove_duplicates(formula):
formula = re.sub(r'\+\s*\+', '+', formula)
formula = re.sub(r'\+\s*\-', '-', formula)
formula = re.sub(r'\-\s*\+', '-', formula)
formula = re.sub(r'\-\s*\-', '+', formula)
return... |
cb802cea7165b4e84a16fa26ff0b257751ca15cf | VeronicaDem/KPKU2021 | /сортировки и поиск/HeapSortPy.py | 1,715 | 3.96875 | 4 | # Реализация пирамидальной сортировки на Python
# Процедура для преобразования в двоичную кучу поддерева с корневым узлом i, что является индексом в arr[]. n - размер кучи
def heapify(arr, n, i):
largest = i # Initialize largest as root
l = 2 * i + 1 # left = 2*i + 1
r = 2 * i + 2 # right = 2*i + 2
... |
b938b4c679cc03f47a526371df3a550edaf71a74 | hyo-eun-kim/algorithm-study | /ch14/saeyoon/ch14_12_saeyoon.py | 855 | 3.5625 | 4 | """
## 14-12. 이진 탐색 트리 노드 간 최소 거리
두 노드 간 값의 차이가 가장 노드의 값의 차이를 출력하라.
"""
import sys
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def __init__(self):
sel... |
7ed0030d6abc8fad9df2ceeaa3a9222690ac9c0c | guzhoudiaoke/leetcode_python3 | /35_search_insert_position/35.py | 822 | 3.609375 | 4 | import bisect
class Solution:
def searchInsert(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
l, r = 0, len(nums)-1
while l <= r:
m = (l + r) // 2
if nums[m] < target:
l = m + 1
... |
cb8d1a9cfe99c49fdc28ff4e586a35592ea5b9f9 | yurilimak9/python-curso-em-video | /exercícios/ex062.py | 474 | 3.765625 | 4 | print('-' * 23)
print('{:-^23}'.format(' Exercício 062 '))
print('-' * 23)
term = int(input('Primeiro termo: '))
reason = int(input('Razão da PA: '))
counter = 1
limit = 10
while counter <= limit:
print('{}'.format(term), end=' -> ')
if counter == limit:
print('PAUSA')
limit += int(input('Qua... |
736d1a1fc08f82b4da4ef2ad765da18cf246ad9f | let369/Using-Python-to-Access-Web-Data | /crawler.py | 554 | 3.53125 | 4 | import urllib
from BeautifulSoup import *
url = raw_input('Enter URL - ')
cou = raw_input('Enter count: ')
pos = raw_input('Enter position: ')
count = int(cou)
position = int(pos)
name_list = list()
i=0
html = urllib.urlopen(url).read()
soup = BeautifulSoup(html)
tags = soup('a')
print 'Retrieving:',url
while(i<cou... |
2ed0064917f7bcd30e42fd739db8aa3248428822 | denamyte/Python-misc | /hyperskill/Quick_sort_in_Python__The_number_of_recursive_calls.py | 572 | 3.796875 | 4 | recursive_count = 0
def quick_sort(lst, start, end):
if start >= end:
return
j = partition(lst, start, end)
quick_sort(lst, start, j - 1)
quick_sort(lst, j + 1, end)
global recursive_count
recursive_count += 2
def partition(lst, start, end):
j = start
for i in range(start ... |
d8a9530663b133d3350bbeccf3988c2a8f738d16 | jvkus/PyGame-SkEtch | /main.py | 1,987 | 3.59375 | 4 | # Author: Joanna Kus
import pygame as pg
from time import sleep
r = int(input("Pick a red value."))
g = int(input("Pick a green value."))
b = int(input("Pick a blue value."))
bgColor = (r, g, b)
White = (255, 255, 255)
(width, height) = (700, 700)
coords = [350, 350]
oldCoords = [350, 350]
drawBool = True
cursorBool... |
d3f028e191281680d095421ab81dcba40fda67fe | ayush879/python | /first.py | 67 | 3.5 | 4 | #3
import re
str1="MCA department"
print(re.findall(r'^\w+',str1))
|
97a72b2629cb11f5b59050a496aa12ccacb1bbfb | zuqingxie/Githubfirst | /Package_learning/type_object_class.py | 534 | 3.828125 | 4 | # Zuqing xie
# Uni Stuttgart
# developing time 2021/7/22 15:40
print(type(type))
print(type(int))
class person:
pass
a = person()
print(type(a))
print(type(person))
#结论:person这个类是由type这个方法生成的对象,和int,str概念一样
print(person.__base__)
#结论,如果没有特殊说明继承关系的话,
# 所有的类都会继承object类。而且object是最顶层的基类
#type也是一个类,但是同时也是一个对象
pri... |
8aa46d992f396862344dffb29d658fa6e478d435 | ht-dep/Algorithms-by-Python | /Python Offer/02.The Second Chapter/11.Min_Num_in_Array.py | 766 | 3.765625 | 4 | # coding:utf-8
'''
求旋转数组的最小值
'''
def min(array):
if len(array) <= 0 | (array == None):
return None
first = 0
last = len(array) - 1
mid = (first + last) / 2
if first == last:
return array[first]
while first + 1 != last:
if array[mid] > array[first] and array[mid] > arr... |
cb873e61018ac92f1d366aa21cbbfcb40f36fcf7 | makeesyai/makeesy-python | /python_basics/functions/function_mutable_object_argument_default.py | 881 | 4.21875 | 4 | # Never use mutable object as default function argument
# (default values of the arguments are evaluated ***only once*** when the control reaches the function)
def add_item_to_dict(key, value, target_dict=None):
if target_dict is None: # if target_dict is not passed as an argument create an empty dict
tar... |
690ef66a3dc356c61a5ff998e8bea660a754ef5b | odubno/algorithms | /array_sequences/anagram_check.py | 3,032 | 3.96875 | 4 | import re
from collections import defaultdict
from collections import Counter
def anagram(s1, s2):
"""
:param s1: string
:param s2: string
:return:
Checking if two strings match
"""
s1 = re.findall('\w', s1.lower())
s2 = re.findall('\w', s2.lower())
s3 = []
if len(s1) != len(s2)... |
e13b5c79ab86e5f3e46d21f9c050fcb5702c9ec6 | AmitKulkarni23/Leet_HackerRank | /Amazon_OA/distance_between_nodes_bst.py | 2,225 | 3.734375 | 4 | # https://leetcode.com/discuss/interview-question/376375
# Solution in the same link as above
# Time -> O(N * H) where N is the number of nodes
# Space -> O(N)
class TreeNode:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def insert_into_bst(root, node):
... |
241435205d0d9c8cfa2ff0e541714bac95ef0abb | AnchitSajalDhar/python-course | /case study2 module3/program1.py | 1,044 | 3.8125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Sep 5 19:20:16 2020
@author: Hp
"""
import pandas
list1=[]
#str1=input("enter the profession")
pd=pandas.read_csv("bank-data.csv")
len1=len(pd.job)
print(pd)
#print(pd)
for i in range(len1):
if (pd.job[i]) not in list1:
list1.append(pd.job[i])... |
989bb1a97d56810274e370ac2c9d8c96f36f5042 | amandamaurell/python-exercises | /display_inventory.py | 618 | 3.703125 | 4 | def displayInventory(inventory):
print("Inventory:".center(20,'-'))
item_total = 0
for k, v in inventory.items():
print( str(k.ljust(12,'.')) + ':' + str(v).rjust(7))
item_total = item_total + v
print( 'The total of items is : ' + str(item_total))
def addToInventory(inventory, addedItems):
for i in ... |
77909b5c3d05a9818fe7902875d003ad072c30be | JingSun70217/Sales-Forecasting-System | /measures/objectives.py | 967 | 4.15625 | 4 |
def abs_sales_diff(pred, target):
"""
Calculates sum of absolute sales differences per day for an item
E.g.
pred = [1, 2, 3]
target = [0, 1, 1]
return 1 + 1 + 2 = 4
:param pred: Array of predicted sales units for an item
:param target: Array of actual sales units for an item
:return... |
a00081cb09f00c7ca17ebeda69428772f379e11d | neilrobertson/BICRCode | /Classifier/classification.py | 1,219 | 3.75 | 4 | class Column(object):
def __init__(self, name, value):
self.name = name
self.value = value
def getName(self):
return self.name
def toString(self):
return str(self.value)
class ListColumn(Column):
def __init__(self, name, values):
super(ListColumn, self)... |
e42dc864eb7e919b00e9f52cc5d5b002289a9477 | aayzaa/checkers-ai | /checkers/constants.py | 1,499 | 3.796875 | 4 | """Holds the constants for a checkers game.
(CC) 2020 Alex Ayza, Barcelona, Spain
alexayzaleon@gmail.com
"""
BOARD_DIMENSION = 8
"""int : Dimension of the board.
Usually, a checkers board is 8x8. If this field is modified, the board will shrink
or grow accordingly.
"""
ROWS_OF_PIECES = 3
"""int : Rows that... |
e1152f117a0096b2912aa4b233cd5f3f5be8816d | anguiclavijods/holbertonschool-higher_level_programming | /0x08-python-more_classes/0-rectangle.py | 240 | 3.640625 | 4 | #!/usr/bin/python3
"""Class Rectangle
"""
class Rectangle():
""""Rectangle empty
Define class Rectangle
That function, with self for created class
Pass is for say that is empty
"""
def function(self):
pass
|
7e48eedbc9ec61ba736c66f89c514a3b7aa56d57 | henchhing-limbu/Interview-Questions | /Greedy-Algorithms/non_overlapping_intervals.py | 1,775 | 4.28125 | 4 | """
Given a collection of intervals, find the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping.
Example 1:
Input: [[1,2],[2,3],[3,4],[1,3]]
Output: 1
Explanation: [1,3] can be removed and the rest of intervals are non-overlapping.
Example 2:
Input: [[1,2],[1,2],[1,2]]
... |
0892d895485ea0db895d6ec93fc65bfb52871a3d | mgbo/My_Exercise | /2018/My_students/3_tretiy_kontest/arr_01_even_odd.py | 344 | 3.609375 | 4 |
#n = int(input())
num = list(map(int,input().split()))
#print (num[0])
list_even = []
list_odd = []
for i in range(num[0]):
if i%2 == 0:
list_even.append(num[i+1])
print (list_even)
else:
list_odd.append(num[i+1])
print (list_odd)
str_1 =' '.join(str(n) for n in list_even)
print (str_1)
print (' '.join(st... |
91a482c1dfa649f3dd8d693908806566dc102a96 | timvan/Introduction-to-Interactive-Python | /collatz_conjecture.py | 415 | 4.09375 | 4 | # Collatz Conjecture
# If number is odd: 3n + 1
# If number is even: n/2
# Will always converge to 1
def run(num):
global num_list
if num % 2 > 0:
num_new = 1 + num * 3
else:
num_new = num / 2
print num_new
num = num_new
num_list.append(num_new)
return num
num = 23
nu... |
1a837a1878bf11b4b2e435f88574e951dc42a012 | dstoner05/important-work | /Python Development Work/HW3.py | 1,392 | 3.6875 | 4 | import sys
import json
import re
###opens the file and loads the json data. Runs a for loop to append all tweets to the list called contents.
class Dataset():
def __init__(self, path):
self.contents = []
with open (path, encoding = 'utf8') as handle:
data = json.load(handle)
... |
1d248707dbf4a428507b93141c3b30bc20ac48a9 | junpil-an/beakjun_coding | /기본 문제/9012.py | 364 | 3.625 | 4 | '''
( ) 의 갯수
'''
for _ in range(int(input())):
cnt = 0
bracket = input()
for i in bracket:
if i == '(':
cnt +=1
elif i == ')':
cnt -= 1
if cnt < 0:
print('NO')
break
if cnt == 0:
print("YES")
elif cnt ... |
1d1bb126a0c14e34c4c9e6e1e9ed0dc9a397fc22 | gitrookie/codesnippets | /pycode/test.py | 972 | 3.515625 | 4 | # Adding thousand separator in a number
import time
def Timer(f):
def wrapper(n):
start = time.time()
f(n)
return time.time() - start
return wrapper
@Timer
def f2(n):
r = []
for i, c in enumerate(reversed(str(n))):
if i and (not (i % 3)):
r.insert(0, ',')
... |
3eec0e540b8f0fe43e5cf6237871373fc7eeca2a | atomic01/Other | /calculate_pi.py | 5,416 | 3.9375 | 4 | import random
def generate_pi(number_of_dots):
dots_in_the_circle = 0
dots_in_total = 0
for i in range(number_of_dots):
x = random.uniform(0,1)
y = random.uniform(0,1)
distance = x * x + y * y
if distance < 1:
dots_in_the_circle += 1
dots_in_total += 1
... |
b092f67867d417c5d0ff3eacfa570432f93c4a0e | neoxie/geektime_python | /16_passvalue/main.py | 298 | 3.6875 | 4 | a = 1
b = a
print(id(a))
print(id(b))
a += 1
print(id(a))
print(id(b))
print('================')
l1 = [1, 2, 3]
l2 = [1, 2, 3]
l3 = l2
print(id(l1))
print(id(l2))
print(id(l3))
print('=================')
def func(dd):
dd['a'] = 10
dd['b'] = 20
d1 = {'a': 1, 'b': 2}
func(d1)
print(d1)
|
32444d21a5be73c7ee68629d914d8f53d0f60138 | mootfowl/dp_pdxcodeguild | /python assignments/lab19_palindrome_anagram.py | 1,426 | 4.15625 | 4 | '''
LAB19 - Palindrome and Anagram
PALINDROME:
A palindrome is a word that's the same forwards or backwards, e.g. racecar.
Another way to think of it is as a word that's equal to its own reverse.
Write a function check_palindrome which takes a string, and returns True if the string's a palindrome, or False if it's no... |
2af5a2cd54770c3badcea2d0ff69c0f53da29661 | haozi12/PythonWorks | /MathClass.py | 863 | 3.828125 | 4 | class method():
def __init__(self,a,b,c,d,e):
self.a = float(a)
self.b = float(b)
self.c = float(c)
self.d = float(d)
self.e = float(e)
def add(self):
return self.a + self.b + self.c + self.d + self.e
def average(self):
return (self.a +... |
d1315b14bd8658363808aefc40b51d31dbeb9f70 | astikanand/Interview-Preparation | /Data Structures/9. Hash/2_check_if_array_is_subset.py | 705 | 3.9375 | 4 | def check_if_arr_is_subset(arr1, arr2):
my_hash = {}
for i in arr1:
my_hash[i] = True
status = True
for i in arr2:
if not my_hash.get(i, False):
status = False
break
if status:
print("True")
else:
print("False")
print("Example-1: c... |
269a283f1f9ea9f1955064eceb19929c89ae6d02 | dodieboy/Np_class | /PROG1_python/coursemology/Mission51-VitalityPoints.py | 1,887 | 4.125 | 4 | #Programming I
#######################
# Mission 5.1 #
# Vitality Points #
#######################
#Background
#==========
#To encourage their customers to exercise more, insurance companies are giving
#vouchers for the distances that customers had clocked in a week as follows:
#########################... |
fbbafdf5d6bb927a8d68b80103c9a5409d56da3a | paalso/learning_with_python | /ADDENDUM. Think Python/16 Classes and functions/16-2.py | 2,707 | 4.5 | 4 | '''
Exercise 16.2.
1. Use the datetime module to write a program that gets the current date and
prints the day of the week.
2. Write a program that takes a birthday as input and prints the user’s age and
the number of days, hours, minutes and seconds until their next birthday.
3. For two people born on different ... |
af967a9a2863e53d032e89b5750c51941da9fa7e | choijeonghwa/hphk_003 | /dict.py | 5,203 | 3.671875 | 4 | """
파이썬 dictionary 활용 기초!
"""
# 1. 평균을 구하세요.
iu_score = {
"수학": 80,
"국어": 90,
"음악": 100
}
# 답변 코드는 아래에 작성해주세요.
print("=====Q1=====")
# 1. iu_score라고 하는 dic 변수에서 value값만 뽑아내보자.
total_score = 0
count = 0
# 2. 뽑아낸 값들의 총 합을 구한다.
for score in iu_score:
total_score = total_score + iu_score[score]
count... |
db0fcd8697a7cd0de667b4bfb656ab6739725216 | RobertNguyen125/Udemy-Python-Bootcamp | /8_setAndTuples/2_set.py | 368 | 3.671875 | 4 | # Like a maths sets
# do not have duplicate values
# no order
# cant be accessed by index
a = set({1,2,3,4,5,5,3})
print(a)
# set method
# .add()
a.add(6)
print(a)
# .remove()
a.remove(6)
print(a)
# .discard()
a.discard(7)
maths = {'Duc', 'Tri', 'Linh', 'Vu'}
biology = {'Diep', 'seoton', 'ai do', 'ai vay', 'Duc'}... |
50e88cfcd7fa98707a703012129d92a7c68d5a9e | BAFurtado/Talent_vs_Luck | /simulation.py | 2,457 | 3.5625 | 4 | """ This module runs successively game turns
"""
import pickle
import pandas as pd
from collections import defaultdict
import game_on
def statistics(n):
""" This function calls individual games up to N
and organizes the dictionaries in DataFrame lines
:param n: number of times to run individual... |
b21fafd79d41b425a9cbb527eb0b96bc3543ea85 | florespadillaunprg/t06_florespadilla | /flores/multiples/ejercicio07.py | 1,455 | 3.640625 | 4 | import os
# BOLETA DE VENTA
# declarar variables
cliente,numero_de_DNI,numero_de_RUC,kg_de_pollo,kg_de_res,precio_de_kg_de_pollo,precio_de_kg_de_res="",0,0,0,0,0.0,0.0
# INPUT
cliente=os.sys.argv[1]
numero_de_DNI=int(os.sys.argv[2])
numero_de_RUC=int(os.sys.argv[3])
kg_de_pollo=int(os.sys.argv[4])
kg_de_res=int(os.sy... |
87bba9d21a3f0c434aa94d58b765544ae7f625cc | beOk91/code_up | /code_up1254.py | 102 | 3.65625 | 4 | text1,text2=input().strip().split()
for i in range(ord(text1),ord(text2)+1):
print(chr(i),end=" ") |
98a10e70c535e5cc0722e652cdfc77ba6f41fbc6 | eriknylander99/IS602 | /hw6.py | 4,928 | 4.25 | 4 | __author__ = 'Erik Nylander'
import numpy as np
import random
import timeit
def sortwithloops(lst):
'''This sort is based off of things I found when researching the
quicksort algorithm. The sort takes a list as an input and
sorts the list by randomly selecting a pivot and then sorting
the list into t... |
92c700f4f637d720c25ef63e8927076febaec27c | mrsgasby/python-challenge | /PyBank/main.py | 3,257 | 4 | 4 | # import libraries
import os
import csv
# define a function that can be called repeatedly
def PyBank(usr_filename):
# create file path
csvpath = os.path.join('../Resources', usr_filename)
#list to store data
monthList = []
revenueList = []
# read in the data file
with open(csvpath, newli... |
fa9c13e0e21d4644f0e052b25924127ed57a79c6 | kboomsliter/risk | /risk.py | 827 | 3.8125 | 4 | # RISK classes
class Player:
def __init__(self, name):
self.name = name
# order and color to be assigned during init phase of game play
class PlayerColors:
def __init__(self):
self.colors = ['red', 'blue', 'green', 'yellow']
def assign(self, color, player):
player.... |
49ac76d290ede8fb6420e51cde43297a2c5d1f90 | ch1huizong/study | /lang/py/rfc/07/date.py | 816 | 3.71875 | 4 | # -*- coding:UTF-8 -*-
import time
class Date(object):
def __init__(self,year,month,day):
self.year = year
self.month = month
self.day = day
@classmethod # 与类有关的属性
def now(cls):
t = time.localtime()
return cls(t.tm_year, t.tm_mon, t.tm_mday)
@classmethod
... |
5c5e5391c604a793818ae7e8796d38504d473f0e | ZachKeeffe/cp1404practicals | /prac_03/shop_calculator.py | 574 | 3.984375 | 4 | def main():
item_count = int(input("Number of Items: "))
total_price = 0
while item_count < 0:
print("Invalid number of items.")
item_count = int(input("Number of Items: "))
for i in range(item_count):
price = int(input("Please enter the price of item " + str(i + 1) + ": "))
... |
db92d18afd72d98e7d273933bee7ec3b3c1028f9 | iqbal-lab-org/BIGSI | /bigsi/bloom/bit_matrix_writer.py | 2,522 | 3.640625 | 4 | import os
from typing import BinaryIO
from bitarray import bitarray
ROWS_PER_SLICE = 80 # must be divisible by 8. somewhere around 80 seems optimal
class BitMatrixWriter(object):
"""
Writer to store a bit matrix in a binary file. The matrix is stored row by row, sequentially.
:Example:
>>> bitarray... |
5a885230c92420610bfc14b9bc0d35c6e79b9aa3 | Anthncara/MEMO-PersonnalChallenges | /Python Challenges/SecondsToMinutesConverter/TimeConverteribrahim.py | 883 | 4.0625 | 4 | def convertMillis(millis):
seconds=(millis//1000)%60
minutes=(millis//(1000*60))%60
hours=(millis//(1000*60*60))%24
d = [hours,minutes,seconds]
return (d)
print("### This program converts milliseconds into hours, minutes, and seconds ###")
print("To exit the program, please type 'exit'")
print("Ple... |
abfea363d481a6e51587a30dd5fba6390209cc60 | Lingrui/Leetcode | /Algorithms/Easy/Reverse_string.py | 254 | 4.03125 | 4 | #!/usr/bin/python
class Solution(object):
def reverseString(self,s):
'''
:type s : str
:rtype: str
'''
return s[::-1]
if __name__ == '__main__':
x = str(input("input a string:"))
print("Reversed string is :",Solution().reverseString(x))
|
441308aa484443fab3a1899ab670a2130e575e01 | PabloFreitas-lib/Cal_Numerico-UFSC-2018.2 | /atividades/aula_1/pi1.py | 286 | 3.59375 | 4 | import matplotlib.pyplot as plt
N=1000
pi = 4.0
vetor_pi = [0]*N
vetor_pi[0] = pi
numerador = -4
denominador = 3.0
for i in range(1,N):
pi += numerador/denominador
numerador *= -1
denominador += 2.0
vetor_pi[i] = pi
#print(i,pi)
plt.plot(vetor_pi)
plt.show()
|
bb3ce29311ab9b2da984beb65926acc8c45678ee | rao003/StartProgramming | /PYTHON/einstieg_in_python/Beispiele/kopieren.py | 425 | 3.84375 | 4 | # Modul copy
import copy
# Kopie einer Liste, Methode 1
x = [23,"hallo",-7.5]
y = []
for i in x: # Elemente einzeln kopieren
y.append(i)
print("dasselbe Objekt:", x is y)
print("gleicher Inhalt:", x == y)
print()
# Kopie einer Liste, Methode 2
x = [23,["Berlin","Hamburg"],-7.5,12,67]
y = copy.deepcopy(... |
52104136e4253a0ca3f8376c7f3eb5ed60f12862 | Gentility01/python-codes | /youtube/unpackaging.py | 154 | 3.53125 | 4 | cordinates = (1,2,3)
# x = cordinates[0]
# y = cordinates[1]
# z = cordinates[2]
# x*y*z
print(cordinates)
x, y, z = cordinates
print(x)
print(x * y * z) |
4ab08c98cb2a1327960942cc804be6fba9baf0c9 | siddhichechani22/Handwritten-Digit-Recognitions-using-different-methods | /verify_image.py | 406 | 3.78125 | 4 | import numpy as np
from PIL import Image
number = int(input("what's the number: "))
img = Image.open('sample%d_r.png'%(number)).convert('L')
img_arr = np.array(img)
#print img_arr.flatten()
WIDTH, HEIGHT = img.size
data = list(img.getdata())
data = [data[offset:offset+WIDTH] for offset in range(0, WIDTH*HEIGHT, ... |
dfb7322b8969fb86811b13f0b6a418648039b9df | FouedDadi/holbertonschool-higher_level_programming | /0x0C-python-almost_a_circle/tests/test_models/test_rectangle.py | 560 | 3.640625 | 4 | #!/usr/bin/python3
"""
creating class rectangle
"""
import unittest
from models.rectangle import Rectangle
class testRectangle(unittest.TestCase):
"""
testing class rectangle
"""
def test_typeerror(self):
"""
testing type error
"""
with self.assertRaises(TypeError):
... |
7a1c77e84e1ba5128629d6b8c9bcafe544b3d5d2 | Michel-Manuel/Data-Structures-Projects | /Practice1.py | 204 | 3.59375 | 4 | def NumberofWords(a):
sentence = a.split()
print("The number of words are " ,len(sentence))
def main():
NumberofWords("The quick brown fox jumps over the lazy dog")
main()
|
8ddea171613105464137bfc5e9a3538e8337190c | ruinanzhang/Leetcode_Solution | /68-Subsets.py | 1,485 | 3.796875 | 4 | # Tag:Recursion
# 78. Subsets
# -----------------------------------------------------------------------------------
# Description:
# Given a set of distinct integers, nums, return all possible subsets (the power set).
# -----------------------------------------------------------------------------------
# Example:
# Inp... |
9ea64fd9e743e7b576346159df65a0b503f7fa40 | WBingJ/Wong-Bing-Jie | /Lab 1.1.py | 226 | 3.65625 | 4 | # Student ID: 1201200237 #
# Student Name: Wong Bing Jie #
print("i like Python")
person = input("Please enter your name: ")
print("Hello ",person)
# Lab 1.2 get input teo numbers and display the sum of the teo numbers
|
9c02f7664c0e6713ccfb17dd65af5c7c6b1ac1ab | itsrbpandit/fuck-coding-interviews | /problems/find_minimum_in_rotated_sorted_array.py | 1,485 | 3.828125 | 4 | # coding: utf-8
"""
https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/
"""
from typing import List
import sys
class Solution:
def findMin(self, nums: List[int]) -> int:
last_num = -sys.maxsize
for num in nums:
if num < last_num:
return num
e... |
886ae1a6ddd5c5e6b8a246539c600979f4a1f112 | chashiv/AutomatedTasksWithPython | /debugWithLogging.py | 949 | 3.890625 | 4 | # Author : Shivam Chauhan
# Date : March 6, 2019
# This is a simple demonstration to use/implement debugging with
# logging module
'''
2019-04-06 22:19:11,484 - DEBUG - Came Inside Function
2019-04-06 22:19:11,484 - DEBUG - i : 1 total : 1
2019-04-06 22:19:11,484 - DEBUG - i : 2 total : 2
2019-04-06 22:19:11,48... |
9872e1ec5b3419cb8b4f18e363ba64a5b1082986 | TetianaSob/Python-Projects | /loops_controlled_exit.py | 548 | 4.0625 | 4 | #Controled exit
# while True:
# command = input("Type 'exit' to exit: ")
# if (command == "exit"):
# break
for x in range(1, 101):
print(x)
if x == 3:
break
# 1
# 2
# 3
######### Adding a break
times = int(input("How many times do I have to tell you? "))
for tim... |
2c7c7104f893ca3c850d9dbfa2c16b7e9088dea8 | phmartinsconsult/curso_python_3_luis_otavio | /Aula_13_Função_Len.py | 271 | 4 | 4 | '''
A função LEN
'''
usuario = input("Digite seu usuário: ")
qtd_usuario = len(usuario)
print("")
if qtd_usuario < 6:
print("Você deve inserir um usuário com, pelo menos, 6 dígitos.")
else:
print("Usuário correto. Você foi cadastrado no sistema.")
|
0b86d27ead49222ecd51fc0a2d49e43d07990be8 | ymeraz52/MyRepo | /Nested.py | 121 | 4.09375 | 4 | num = int(intput("Give me any number:"))
if num < 0:
print("Your number is negatice")
elif num > 0:
while count < |
5cce774f4a8eae952c2fc26e15a291d232e536b3 | ferguson-cole/AI_CheckersPlayer | /ai.py | 9,895 | 3.71875 | 4 | from lib import abstractstrategy
from math import inf
class AlphaBetaSearch:
def __init__(self, strategy, maxplayer, minplayer, maxplies=3,
verbose=False):
""""alphabeta_search - Initialize a class capable of alphabeta search
problem - problem representation
maxplayer - ... |
c962f73ff54d203bcd1cb0edf9e7ca731d5f5a11 | suryamahato4444/laboratory | /python_lab_1/que5.py | 1,107 | 4.3125 | 4 | '''a school decidesd to replace the desk in three classrooms.Each desk sits two student
Given the number of each class, print the smallest possible number of desk that can be purchased
.the program should read three integers:the number of student in each of three classes a,b,c respectively
In the first there are three ... |
914175617ed0267168b06116e30ea8c37be3ab3f | chimel3/stormbowl | /createplayers.py | 3,440 | 3.9375 | 4 | import config
import classes.player
import classes.club
def create_players():
'''
ABOUT:
Creates the players for the game.
gametype tells us whether it's a single game or a league so that we can generate the right number of players.
names set to None will allow us to randomly generate them.
... |
6fd35e53d5ee8c61d0d2a06dbcb14c69209be7bc | SudoBobo/data_structures | /yandex_taxi_2.py | 1,174 | 3.84375 | 4 | number_of_lines = int(input())
current_day = int(input())
class DayLog:
def __init__(self, log_type, day_number, clients_count):
self.log_type = log_type
self.day_number = day_number
self.clients_count = clients_count
log = []
for _ in range(0, number_of_lines - 1):
# arrival 3 2
... |
9a439f688a0109eb247a64de2d05d3adbc6436a7 | rajatjoshi2711/MIT-PythonBasics | /Codes/UsingFunctions.py | 473 | 3.890625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Sep 19 22:45:42 2018
@author: Rajat
"""
#Functions example
def addNumbers(firstNum, secondNum):
sum = firstNum+secondNum
return sum
firstNumber = 10
secondNumber = 20
sum = addNumbers(firstNumber, secondNumber)
print(sum)
#Functions hands o... |
95a8767e37bab2f4699642a88d258c0bb7b9bac0 | linsalrob/EdwardsLab | /fasta/length_filter.py | 891 | 3.765625 | 4 | """
Filter a fasta file on length
"""
import os
import sys
import argparse
from roblib import stream_fasta
def length_filter(f, l, verbose=False):
"""
Filter a fasta file based on the minimum length, l
:param f: fasta file
:param l: minimum sequene length
:param verbose: more output
:return:
... |
74be32c271ae3fa3066908ef531305adf6cdbf3d | alefaggravo/seq3-studyhall | /roll-the-dice/main.py | 1,801 | 3.9375 | 4 | """
Roll some dice and try to be the one with
the highest rolls!
"""
import random
num_players = 2 # TODO: make this dynamic (command line arguments?)
num_dice = 2 # TODO: make this dynamic (command line arguments?)
num_sides = 6 # TODO: make this dynamic (command line arguments?)
num_times = 5 # TODO: mak... |
135c0001614f9164975fc72d962af6b44508032c | ITSJKS/100-Days-of-ML-Code | /Naive Bayes/nb_author_id.py | 1,417 | 3.703125 | 4 | #!/usr/bin/python
"""
Lesson 1 (Naive Bayes) mini-project.
Use a Naive Bayes Classifier to identify emails by their authors
authors and labels:
Sara has label 0
Chris has label 1
"""
import sys
from time import time
sys.path.append("../tools/")
from email_preprocess import preprocess
from ... |
b2defe6f369adefea96e7eabd71170bfc0994b09 | Tanmay53/cohort_3 | /submissions/sm_107_hasmuddin/week_20/day_4/session_1/pkgs/operations.py | 150 | 3.921875 | 4 | def factorial(n):
if n == 1 or n == 2:
return n
else:
return n * factorial(n-1)
def cube(number):
return pow(number, 3)
|
f3cccb37adf5e7081b49438f0fed8b785059a440 | romeucampos/password-manager | /password_manager.py | 2,751 | 3.671875 | 4 | import sqlite3
import sys
import create_db
class Data:
def __init__(self):
self.base = sqlite3.connect('base.db')
self.funcs = {
'o': self.options,
'l': self.listed,
'v': self.views,
'i': self.insert,
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.