blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
01db21a5b4469edf3192d8913ee7d2bb62019be9 | rogeriosilva-ifpi/teaching-tds-course | /programacao_estruturada/20192_186/Bimestral2_186_20192/Parte 1/prova harife e herbert/4°questao.py | 1,126 | 4.15625 | 4 | print('o animal é vetebrado ou invertebrado?')
palavra = input('resposta \n >>>>>>> ')
if palavra == 'vertebrado':
tipo_de_animal = input('o animal é ave ou mamifero? \n >>>>>')
if tipo_de_animal == 'ave':
alimento = input('é carnivoro ou onivoro? ')
if alimento == 'carnivoro':
prin... |
808e7451794566a0ac3bbf13ae0c9f08555c79e4 | skonienczwy/OOP_Python | /Car_Example.py | 297 | 3.703125 | 4 | class Car:
def __init__(self,marca,modelo):
self.marca = marca
self.modelo = modelo
def mostrarCarro(self):
print(f'A marca do carro é {self.marca} e o modelo é {self.modelo}')
x = Car('Audi','A3')
y = Car('Teste','Teste 2')
x.mostrarCarro()
y.mostrarCarro()
|
2bd274c6d4940ac53fd7e0cfecec71579d3b2511 | anjor/Coding-Problems | /ascii_ruler/ascii_ruler.py | 1,024 | 4.375 | 4 | #!/usr/bin/python
def populate_last_row(n):
""" Populates the last row for a size n ruler."""
row = []
for i in xrange(2**n+1):
if i%2==0:
row.append('|')
else:
row.append('_')
return row
def populate_prev_row(row, n):
""" This function is used to populate... |
b4bfa9dc5e3c371e4d215953835b0f273127442f | neharathig/Comprinno-Technologies | /catsanddog.py | 691 | 3.578125 | 4 | def main():
#Taking input for no of test cases
noc = int(input())
#check for validity of no of test cases
if noc < 1 or noc > pow (10,5):
print("Invalid no of Test cases. Please try again")
return
else:
test_cdl(noc)
def test_cdl(noc):
for i... |
fb67e689e7106c0768e2626bf1f209eb0623b74d | HampusMLTH/pypylon | /producer_consumer.py | 1,103 | 3.5625 | 4 | from queue import Queue
import random
import threading
MAX_QSIZE = 10 # max queue size
BUF_SIZE = 100 # total number of iterations/items to process
class Producer:
def __init__(self, queue, buf_size=BUF_SIZE):
self.queue = queue
self.buf_size = buf_size
def run(self):
for _ in rang... |
e9fe6f4aeed3ae684917f559f5d184b5fe058486 | liuyf8688/python-2.7.4-demos | /src/builtinModule/itertools.py | 393 | 3.921875 | 4 | # -*- coding: utf-8 -*-
'''
Created on 2017年12月15日
@author: tony
'''
import itertools, time
# 产生无限迭代器
'''
natuals = itertools.count(1)
for n in natuals:
print n
time.sleep(0.1)
'''
# 通过itertools.cycle('ABC'),产生一个无限循环这三个字符的迭代器
# 有限循环迭代器
ns = itertools.repeat('ABC', 10)
for n in ns:
print n |
1fbc6e3de5f0c3d39ceaa2d0463e4d5320bb80ec | haleekyung/python-coding-pratice | /baekjoon/2/Solution2562.py | 716 | 3.515625 | 4 | ## 20210720 - Bronze 2 2562번 문제 최대값 찾기
# 9개의 서로 다른 자연수가 주어질 때, 이들 중 최댓값을 찾고 그 최댓값이 몇 번째 수인지를 구하는 프로그램을 작성하시오.
# 예를 들어, 서로 다른 9개의 자연수
# 3, 29, 38, 12, 57, 74, 40, 85, 61
# 이 주어지면, 이들 중 최댓값은 85이고, 이 값은 8번째 수이다.
# 첫째 줄에 최댓값을 출력하고, 둘째 줄에 최댓값이 몇 번째 수인지를 출력한다.
# testcase : 3, 29, 38, 12, 57, 74, 40, 85, 61
numbers = []
fo... |
2e0b9b55997035ec3c7d3c453663583fed434623 | sroy8091/daily_coding_problem | /n_orders.py | 968 | 4.0625 | 4 | """
This problem was asked by Twitter.
You run an e-commerce website and want to record the last N order ids in a log.
Implement a data structure to accomplish this, with the following API:
record(order_id): adds the order_id to the log
get_last(i): gets the ith last element from the log. i is guaranteed to ... |
670a7c36c575d237933edb095a5946fb78a0adaf | turuga-2/pythonbysci2pro | /week3/problem2.py | 402 | 3.765625 | 4 | import sys
def main():
a = []
n = int(input("Enter the number of elements in list:"))
for x in range(0, n):
element = int(input("Enter element" + str(x + 1) + ":"))
a.append(element)
b = [sum(a[0:x + 1]) for x in range(0, len(a))]
print("The original list is: ", a)
print("The n... |
239a914e72729c7158162298c98cc98791737de5 | merrb/python-challange | /PyBank/main.py | 1,404 | 3.84375 | 4 | import os
import csv
#path to folder
path = "03-Python_02-Homework_Instructions_PyBank_Resources_budget_data.csv"
#variables
months = []
net_amount = []
changes = []
increase = []
decrease = []
#csvfile
with open(path) as csvfile:
#csv reader specifies delimter and varible that holds data
csvreader = csv.re... |
988387cfaf8a66d7dc89d03413f32fd97aabeda0 | bnm91/FantasyScraperAPI | /FantasyScraperAPI/fantasyScraperUtils/utils.py | 961 | 3.53125 | 4 | # transforms list of rows of csv strings into a single "cvs file" string that is presentable on the web
def csv_list_to_csv_string(csv_list):
csv_string = ''
for row in csv_list:
csv_string += row
csv_string += ' <br />'
return csv_string
def find_between_r(s, first):
try:
star... |
7b0c5bf3e235538f402a1f7ba44c0473852fb6c5 | Alan-Liang-1997/CP1404-Practicals | /prac_04/warp_up.py | 572 | 4.15625 | 4 | """
numbers = [3, 1, 4, 1, 5, 9, 2]
First, write down your answers to these questions without running the code, then use Python to see if you were
correct. What values do the following expressions have?
"""
numbers = ["ten", 1, 4, 1, 5, 9, 1]
print(numbers[0])
print(numbers[-1])
print(numbers[3])
print(numbers[:-1])
pr... |
ea6baabfb8c90cad855066f98dba3502abaadf74 | VladGPine/stepik_python_course | /lesson2_5_step10.py | 1,279 | 3.921875 | 4 | """
Напишите программу, на вход которой подаётся список чисел одной строкой. Программа должна для каждого элемента этого
списка вывести сумму двух его соседей. Для элементов списка, являющихся крайними, одним из соседей считается элемент,
находящий на противоположном конце этого списка. Например, если на вход подаётся ... |
5941a94780ff4158011b2792c16d6ed3773fffd6 | IamSadiq/web-scraping | /special-sequences.py | 563 | 3.546875 | 4 | import re
# special sequences
# \d --- matches any decimal digit [0-9]
regex = re.compile('\d')
# print(regex.match('6352778'))
# \D --- matches any non-digit character [^0-9]
regex = re.compile('\D')
# print(regex.match('adfdfg'))
# \s --- matches any whitespace character
regex = re.compile('\s')
# print(regex.matc... |
9fd7fa66c7f756936d5369fe0185266548950865 | edmilsonlibanio/Ola-Mundo-Python | /iapcompython/prog_4_7.py | 436 | 3.84375 | 4 | #Programa categoria x preço (com 5 categorias) utilizando #elif.
categoria = int(input('Digite a categoria do produto: '))
if categoria == 1:
preco = 10
elif categoria == 2:
preco = 18
elif categoria == 3:
preco = 23
elif categoria == 4:
preco = 26
elif categoria == 5:
preco = 31
else:
print('... |
5d5d6be924f29cea9d3ffde5bcb81999d7c39eee | samcan/nes-rle-decompress | /compress_rle.py | 2,786 | 3.5625 | 4 | import argparse
import os
MAX_BYTE_COUNT = 255
def main(input_file, output_file):
print('Input file:', input_file)
print('Output file:', output_file)
if os.path.isfile(output_file):
os.remove(output_file)
with open(input_file, 'rb') as f:
bytes_read = f.read()
... |
62f274a02b7e65fd0608554cb73514e830f145ee | rahelbelay/list_exercises | /prompt.py | 426 | 4.28125 | 4 | user_name = input("What is your name?")
# input -need to take it and save it somewhere
#variable names in python has _
#snake case
#java script camelCase
#print("Hello, ")
#print (user_name)
print ("Hello,", user_name, "!")
# String interpolating has three parts
#1 place holder
greeting = "Hello, %s!" % (user_name,)
#... |
74207adc27b29fa128f448fc109f53ebe5a9924f | PatrickJou/Machine-Learning | /Project1 - Supervised Learning/KNN_classifier.py | 2,213 | 3.546875 | 4 | import matplotlib.pyplot as plt
import numpy as np
from sklearn.model_selection import validation_curve
from sklearn.model_selection import ShuffleSplit
from sklearn.neighbors import KNeighborsClassifier
from plot_learning_curve import plot_learning_curve
def KNN_classifier(X, Y, datasource):
param_range = range... |
5ca83cb4d75c13e1402b4c363f7346369638ac4f | edithturn/Data-Structures-Algorithms | /stacks-queues/716-MaxStack.py | 1,455 | 3.828125 | 4 | '''
LeetCode:
716. Max Stack
Design a max stack data structure that supports the stack operations and supports finding the stack's maximum element.
Implement the MaxStack class:
MaxStack() Initializes the stack object.
void push(int x) Pushes element x onto the stack.
int pop() Removes the element on top of the stack... |
3a5f4038c4eec7223b6db8066d5059aa6057900b | NathanKinney/class_ocelot | /Code/tim/Python/lab03_grades.py | 712 | 3.890625 | 4 | while True:
try:
answer = float(input('What did you get on the test? > '))
break
except ValueError:
print('LIES! Try again.')
continue
if answer > 100:
mod_grade = 9
else:
mod_grade = answer % 10
if answer >= 90:
answer = 'A'
congrats = 'Good Job!'
elif answer >... |
20cc6e7783976b1255e54f3198325b6bedb65a0f | nearwalden/caltemp | /cal.py | 5,016 | 3.84375 | 4 | # Routines to create, analyze and plot different calendard models of temperature
import math
# we'll want pandas to structure the datasets
import pandas as p
# use numpy to do vector work
import numpy as np
# plotting routines
# import mapplotlib as plt
# months in order
months = ['january', 'february', 'march', 'ap... |
0564800b508cd52b3485a3aec7273ff3fa12b568 | GuyRobot/AIPythonExamples | /AILearning/NaturalLanguageProcessing/TextSentimentClassification.py | 3,914 | 3.609375 | 4 | from d2l import AllDeepLearning as d2l
from mxnet import nd, init, autograd, gluon
from mxnet.gluon import nn, rnn
from mxnet.contrib import text
from AI.AILearning.NaturalLanguageProcessing import TextClassification as loader
"""
In this model, each word first obtains a feature vector from the embedding layer. Th... |
a7f2199415de8a89c91e4927eacfe009998fdd65 | mercurist/Coursera | /Python Data Structures/strings.py | 235 | 3.859375 | 4 | str1 = "hello"
str2 = "world"
str3 = str1 + str2
print(str3)
str = "123"
istr = int(str) + 1
print(istr)
name = input("Enter: ")
print(name)
apple = input("Enter: ")
cost = int(apple) - 0.5 * int(apple)
print(cost)
|
549190dd4e839c758a943ebc14dbf848f6a6be7a | acp3012/utilities | /Find_Word_File.py | 597 | 3.6875 | 4 | import os
def find(lst, file):
lst = [ x.lower() for x in lst ]
found = False
if os.path.isfile(file):
print('it is a file')
with open(file,'r') as fh:
for line in fh:
line = line.lower()
found_text = [ x for x in lst if x in line ]
if len(found_text) > 0:
print('found..')
... |
10c178e55f5c3e6f848548989ff3b98b1b4a2470 | PARKINHYO/Algorithm | /BOJ/1546/1546.py | 400 | 3.546875 | 4 | N = int(input())
score = []
score = input().split()
score = [int (i) for i in score]
score.sort()
for i in range(0, N-1):
score[i] = float(score[i])/float(score[N-1])*100
score[N-1] = 100
sum = 0
for i in range(0, N):
sum += float(score[i])
average = float(sum)/N
if len(str(aver... |
0001a8300daeb9be2bf8e1f62a667301a43710b8 | hgargan/python_test_gargan | /hello.py | 1,613 | 3.609375 | 4 | #!/usr/bin/env python
a = "Once upon a time, a family of %d bears lived in the woods." % 3
mamabear = "Mrs. Bear"
papabear = "Mr. Bear"
babybear = "Lil Fuzzy"
b = "Their names were %s, %s and %s." % (mamabear, papabear, babybear)
print a
print b
x = 3
y = x+2
print "One day, the", x, "bears encountered another, lar... |
56407a5762950816008c7827036a9d103d5771db | fritzy/SleekXMPP | /sleekxmpp/util/misc_ops.py | 4,292 | 3.640625 | 4 | import sys
import hashlib
def unicode(text):
if sys.version_info < (3, 0):
if isinstance(text, str):
text = text.decode('utf-8')
import __builtin__
return __builtin__.unicode(text)
elif not isinstance(text, str):
return text.decode('utf-8')
else:
return ... |
237ba877d2f6e871311a101ba90247b4a0b1817c | jacquerie/leetcode | /leetcode/0090_subsets_ii.py | 916 | 3.734375 | 4 | # -*- coding: utf-8 -*-
class Solution:
def subsetsWithDup(self, nums):
result = []
self._subsetsWithDup(sorted(nums), [], result)
return result
def _subsetsWithDup(self, nums, current, result):
if not nums:
if current not in result:
result.append(c... |
1d46f0c34e39046145e2d32119d6f4745b27cb50 | jade0300/PYTHON_C109156229 | /6.兩數差值.py | 254 | 3.5 | 4 | tt=[]
tt=eval(input("輸入值為:"))
one=list(tt)
a=len(one)
one.sort()
two=""
for i in range(a):
two += str(one[i])
one.reverse()
yy=""
for i in range(a):
yy+=str(one[i])
print("最大值數列與最小值數列差值為:%d"%(int(yy)-int(two))) |
18ad6d0864c40ae84f010eaad2f936bf39395f05 | vishnupsingh523/python-learning-programs | /calculateElectricityBill.py | 722 | 4.125 | 4 | # defining main function here:
def main():
print("**** WELCOME TO THE ELECTRICITY BILL CALCULATOR ****\n")
units = int(input("Enter the number of units: "))
# calling the function calculateBill with the parameter units:
rateOfCharge = 0
if units>=0:
if units <= 150:
r... |
d48b7dc8bddf6750accf3f7c6aa9f3818ca7e85f | ucsb-cs8-s18/LECTURE-05-29-Recursion-part-2 | /addToEach_recursive.py | 293 | 3.609375 | 4 | def addToEach(value,aList):
if aList==[]:
return []
first = aList[0]
rest = aList[1:]
return [ first + value ] + addToEach(value,rest)
def test_addToEach_1():
assert addToEach(1,[3,4,5])==[4,5,6]
def test_addToEach_10():
assert addToEach(10,[3,4,5])==[13,14,15]
|
1fcfe9261eb441be7a4158d3d38474c731ec3e80 | Edceebee/python_practice | /Lists/checkElement.py | 440 | 4.09375 | 4 | # someList = ['a', 'b', 'c', 'b', 'd', 'm', 'n', 'n']
# newList = []
#
# for items in someList:
# if items not in newList:
# newList.append(someList)
# else:
# print(items, end=' ')
some_list = ['a', 'b', 'c', 'b', 'd', 'm', 'n', 'n']
# my_list = sorted(some_list)
duplicates = []
for i in some_... |
e3057ce8d6fff12e7e7ea599c93e0780a1c4b506 | Shumpy09/kurs-uDemy | /LVL 2/SEKCJA 4/52. Funkcja jako zmienna - LAB.py | 339 | 3.8125 | 4 | def double(x):
return 2 *x
def root(x):
return x**2
def negative(x):
return -x
def div2(x):
return x/2
number = 8
transformations = [double, root, div2, negative]
tmp_return_value = number
for transformation in transformations:
tmp_return_value = transformation(tmp_return_value)
print(tmp... |
d2d6a8dca4f45902c0fe0b7bc68ea224edab7ba2 | quyixiao/python_lesson | /sortTest/SortTest.py | 298 | 3.953125 | 4 | # 依次接收用户输入的3个数 ,排序后打印
# 1.转换int后,判断大小的排序,使用分支结构完成
# 2.使用max函数
# 3.使用列表的sort方法
# 冒泡法
nums = []
for i in range(3):
nums.append(int(input('{}:'.format(i))))
nums.sort(reverse=True)
print(nums)
|
62d96e42feed009565a43f94c501bef01e0a06d0 | luismvargasg/holberton-system_engineering-devops | /0x16-api_advanced/0-subs.py | 712 | 3.59375 | 4 | #!/usr/bin/python3
"""Function that queries the Reddit API and returns the number of subscribers
for a given subreddit. If an invalid subreddit is given, the function should
return 0.
"""
import requests
def number_of_subscribers(subreddit):
"""Function that returns the number of subscribers"""
url = "https:/... |
ee033722a288fd177d0caa7de45a949f135f38f2 | RajeevSawant/PYthon-Programming | /Functions_Homework.py | 2,074 | 3.703125 | 4 |
# Question 1
def vol(rad):
return((4.0/3)*3.14159*(rad*rad*rad))
pass
print "\nThe Volume of the Sphere is: %1.3f\n" %(vol(3))
# Question 2
def ran_check(num,low,high):
if num > low and num < high:
return True
else:
return False
print "Is the Number in Range? %s\n"%(ran_check(4,2,7))
# Quest... |
f5ee60fad7c2d543ead7e507fb2d83cdb67500b9 | dnmcginn57/2143-OOP-McGinn | /Assignments/homework-01.py | 2,984 | 4 | 4 | """
Name: David McGinn
Email: nicholasmcginn57@yahoo.com
Assignment:Homework 1 - Lists and Dictionaries
Due: 31 Jan 2016 @ classtime
"""
# 1.1 Basics
#A
a = [1, 5, 4, 2, 3]
print(a[0], a[-1])
# Prints: (1,3)
a[4] = a[2] + a[-2]
Print(a)
# Prints: [1,5,4,2,6]
print(len(a))
# Prints: 5
print(4 in a)
# Prints: tr... |
acba7bbab9b24588a9831941b7b6c9e9c02b5b70 | jasminsaromo/reinforcement_assignments | /reinforcement_jun24.py | 492 | 3.90625 | 4 | print("Please enter a number")
number = input()
firstpart, secondpart = number[:int(len(number)/2)], number[int(len(number)/2):]
def luck_check(number):
try:
sum1 = 0
for i in firstpart:
sum1 += int(i)
sum2 = 0
for i in secondpart:
sum2 += int(i)
if sum1 == sum2:
print(... |
b5db1041f5d68bf692fd5144550b0d4daff8d823 | DeepakRathod14/TestPython | /src/office/05DeclaredMainMethod.py | 729 | 3.703125 | 4 | # Empty class sample
class EmpltyClass:
def setterTest(self,x):
self.x=x
def getterTest(self):
print(self.x)
# Sample of Bean (Getter & Setter)
class Bean:
def __init__(self):
print("Const")
def setter(self, x,y,z):
self.x=x
... |
d0ea125743777ea8586b660440dd652e10ba47da | zozni/PythonStudy | /Regex/grouping4.py | 176 | 3.671875 | 4 | # 그룹핑된 문자열에 이름 붙이기 ?P<name>
import re
p = re.compile(r"(?P<name>\w+)\s+((\d+)[-]\d+[-]\d+)")
m = p.search("park 010-1234-1234")
print(m.group("name")) |
4bce5f49c82972c9e7dadd48794bcc545e25095b | miketwo/euler | /p7.py | 704 | 4.1875 | 4 | #!/usr/bin/env python
'''
By listing the first six prime numbers:
2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.
What is the 10001st prime number?
'''
from math import sqrt, ceil
def prime_generator():
yield 2
yield 3
num = 3
while True:
num += 2
if is_prime(num):
... |
57abf5d58c9a55043dccc51d9beba9156ac60ec9 | Wolverinepb007/Python_Assignments | /Python/perimeter.py | 250 | 4.0625 | 4 | l=int(input("Enter length of rectangle="))#Entering length.
b=int(input("Enter breadth of rectangle="))#Entering Breadth.
print("Area of the rectangle=",l*b)#Printing area.
print("Perimeter of the recatange=",2*(l+b))#printing Perimeter.
|
d5b98d6df8f3bd89486c9442933019bb84452b44 | stevemman/FC308-Labs | /Lab3/A1.py | 344 | 4.25 | 4 | # Ask the user to enter their age.
age = int(input("Please enter your age :"))
# Depending on the age group display a different ticket price.
if age > 0 and age < 18:
print("The ticket costs : 1.50£")
elif age >= 18 and age < 65:
print("The ticket costs : 2.20£")
elif age >= 65 and age < 100:
print("The ti... |
b7e963fb4cd7e452545ae46c50ef036bc0a97e60 | cynthziawong/python_for_everyone | /a_ex_6.5/a_ex_6.5.py | 358 | 4.09375 | 4 | # 6.5 Write code using find() and string slicing
# (see section 6.10) to extract the number at the end of the line below.
# Convert the extracted value to a floating point number and print it out.
text = "X-DSPAM-Confidence: 0.8475";
xyz = text.find('0') # Find 0 in text
abc = text[xyz : ] # Look up 0 and extract ... |
3af1ee0f10178adbb0628f6c4476108524f2b1ba | yogalin910731/studytest | /twokindstrees/printupanddown.py | 2,661 | 4.03125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/7/24 10:38
# @Author : fangbo
#三种难度
#打印 [1,2,3,4,5,6,7],
#打印 [[1], [2,3], [4,5,6,7]]
#打印 [[1], [3,2], [4,5,6,7]] 偶数层倒序
#
class Treenode:
def __init__(self,val):
self.val = val
self.lchild = None
self.rchild = None
... |
fa64141ea139a1e457bbf94956ea9957651b2967 | e1four15f/python-intro | /lesson2/ExC.py | 132 | 4 | 4 | n = int(input())
def factorial(n):
curr = 1;
for i in range(1, n+1):
curr *= i
return curr
print(factorial(n)) |
b7f8b4c60d8a6ceee742a905f03302c2906192b4 | alexchao/problems | /python/tree_problems_test.py | 807 | 3.546875 | 4 | # -*- coding: utf-8 -*-
import unittest
from tree_problems import find_lowest_common_ancestor
from tree_problems import TreeNode
class FindLowestCommonAncestorTest(unittest.TestCase):
def test_immediate_ancestor(self):
tree1 = TreeNode(1)
tree2 = TreeNode(2)
tree3 = TreeNode(3)
... |
77093e76c811582aff67d0c1ffeccc3e287c137a | lhm0421/codetest1 | /0303.py | 257 | 3.59375 | 4 | def solution(n):
sam3 = list()
answer = 0
while n >=3:
sam3.append(n%3)
n = n//3
sam3.append(n)
sam3.reverse()
for i in range(len(sam3)):
answer = answer + (sam3[i] * 3**i)
return answer |
e673925252e4877dff5f08a14b54318e9251d068 | KevinMichaelCamp/Python-HardWay | /Algorithms/Chapter4_Strings/09_Roman Numerals_to_Integer.py | 514 | 3.890625 | 4 | # Given a string containinga Roman Numeral representation of a positive integer, return the integer.
def romanNumeralToInteger(str):
rom_val = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
integer = 0
for i in range(len(str)):
if i > 0 and rom_val[str[i]] > rom_val[str[i-1]]:
... |
3c29950027644851ffb2a3e24db1b2ad653d4d0f | matoken78/python | /LP100Knocks/03-20.py | 519 | 3.75 | 4 | # 20. JSONデータの読み込み
# Wikipedia記事のJSONファイルを読み込み,「イギリス」に関する記事本文を表示せよ.
# 問題21-29では,ここで抽出した記事本文に対して実行せよ.
# https://docs.python.jp/3/library/json.html
import codecs
import json
def read(word):
for line in codecs.open(".\jawiki-country.json", "r", "utf-8"):
article = json.loads(line)
if article["title"... |
77a16720e92c25df25fe1ef57b1a4b107ef83e61 | CameronAF/Python | /Clustering/Simple/Simple_KMeans.py | 1,032 | 3.625 | 4 | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
sns.set()
from sklearn.cluster import KMeans
# Load the Data
if 1 == 0:
data = pd.read_csv('Country Clusters 1.csv')
else:
data = pd.read_csv('Country Clusters 2.csv')
print('The Data:\n', data, '\n')
# Plot the Data
plt... |
39de57699a2c867b80a4325230d840722c6de07c | nat-sharpe/Python-Exercises | /Day_4/pair4.py | 221 | 3.59375 | 4 | msg = raw_input('msg:')
word_histogram = {}
entry = ''
for char in msg:
if char != ' ':
entry = entry + char
elif char == ' ':
break
word_histogram[entry] = 0
print entry
print word_histogram |
4a766db54c590c126b8064336f27eed4296211bd | marcelogomesrp/python | /Classes/Pessoa.py | 295 | 3.921875 | 4 | #!/usr/bin/python
class Pessoa:
_nome = None
def __init__(self):
print("Pessoa criada")
def setNome(self, nome):
self._nome = nome;
print("Definido o nome como " + self._nome);
def getNome(self):
print(self._nome);
pessoa = Pessoa()
pessoa.setNome("Marcelo")
pessoa.getNome()
|
57076dd600591bd0761345c6b8d1cb8d300fa2fb | holdermatthew5/caesar-cipher | /tests/test_caesar_cipher.py | 1,004 | 3.546875 | 4 | from caesar_cipher.caesar_cipher import encrypt, decrypt, crack
# encrypt a string with a given shift
def test_encrpyt():
assert encrypt('best of times', 732) == 'ybpq lc qfjbp'
# decrypt a previously encrypted string with the same shift
def test_decrypt():
assert decrypt('ybpq lc qfjbp', 732) == 'best of t... |
c5f95eedf16aec9d017675d1f57ff769a964d992 | utkarsht724/PythonBasicPrograms | /String/Add_ing.py | 134 | 4.15625 | 4 | #program to add ing in a string
str=("bridgelabz")
print("Orginal string:",str)
str2=("ing")
str3=str+str2
print("new string::",str3)
|
4c562f4719bd74d295d03778bb8c125c192e3c17 | JaiJun/Codewar | /8 kyu/Short Long Short.py | 635 | 4 | 4 | """
Given 2 strings, a and b, return a string of the form short+long+short,
with the shorter string on the outside and the longer string on the inside.
The strings will not be the same length, but they may be empty ( length 0 ).
I think best solution:
def solution(a, b):
return a+... |
7975202d35c8c608c2c29b2d950a06244168cf1b | ekaropolus/metodos_rigurosos-1 | /tareas/test_intervalo_luis.py | 763 | 3.59375 | 4 | # -*- coding: utf-8 -*-
# Escribimos funciones con el nombre test_ALGO
from intervalo_luis import *
import numpy as np
def test_adicion():
a = Intervalo(1, 2)
b = Intervalo(2, 3)
c = a + b
# Quiero checar que c, definido asi, esta bien:
assert c.lo == 3 and c.hi == 5
def test_comparacion_lt()... |
fdde61aed122cc7acce8cc59b35dbff0312d3871 | Nicolas-Turck/POO_debutant | /ex3/library.py | 750 | 3.71875 | 4 | from book import *
from books_list import *
class Library():
"""class for range book objet and select it and return it """
def __init__(self):
self.book_all = list()
def add_book(self, book):
"""method for add book in the library """
self.book_all.append(book)
d... |
7f947754383074882157df20e8ea2b524ccbe614 | BMW-InnovationLab/BMW-TensorFlow-Training-GUI | /training_api/application/data_preparation/models/converter_configuration_enum.py | 456 | 3.828125 | 4 | from enum import Enum
class ConverterConfigurationEnum(Enum):
"""
A class Enum used to get supported labels type and corresponding format
"""
xml: str = "pascal"
json: str = "json"
@classmethod
def is_name_valid(cls, requested_format_name: str) -> bool:
format_name: bool = an... |
a01f9c145dd19c1a98a69116ba97feb525b10f0f | TsubasaKiyomi/python | /src/Closure.py | 1,516 | 4.4375 | 4 | """
引数piを初めに決めてしまう!後々用途によって使い分ける。
# f = outer(1,2)はdef outer(a,b):に入り、return a + b 1 + 2 となるが、return inner がまだ実行されていない
# return innerの返した物が f = outer(1,2)の f にあるのでまだ、実行されない。
# r = f()を実行すると。def inner() return a + b が実行される a + b には 1 と 2 が入っているので 3 が返ってくる。
#return innerでさらに返すので r = f() の r に 3 が入る。
def outer(a,b):
... |
07b24ad324e24cb0477aab45ec31f0283621aa8a | Valiter/Learning_Repository | /Learning/lesson_2_task_1.py | 1,549 | 3.78125 | 4 | ls = [1, "А", 1.3, False, 24]
print("Создать список и заполнить его элементами различных типов данных.\nРеализовать скрипт проверки типа данных каждого элемента.\nИспользовать функцию type() для проверки типа.\nЭлементы списка можно не запрашивать у пользователя, а указать явно, в программе.")
print("\n2 варианта в про... |
0aa548da5918b11d9d920ebb85b2523464046b2d | tinashechihoro/python_control_flow | /control_flow.py | 518 | 3.609375 | 4 | # ## control flow
# import os
#
# domain_list = ['www.yahoo.com', 'www.telone.co.zw', 'www.cnn.com']
# for domain in domain_list:
# downloaded_page = os.system('wget {0}'.format(domain))
# print(downloaded_page)
## the fomatting of python source code is based on PE
for n in range(2,10):
for x in range(2,... |
e05c8600549e4cd551996681d4ba5c82580bb9c3 | ConnorBrereton/Python-Design-Patterns | /template.py | 1,865 | 4.15625 | 4 | from abc import ABC, abstractmethod
class AbstractClass(ABC):
"""Implement the prototypes."""
def template_method(self):
self.base_operation1()
self.required_operation1()
self.base_operation2()
self.hook1()
self.required_operation2()
self.base_operation3()
... |
8ce926e3933e73729b9067cf8f051b4fb2945904 | shivrajek7/Demo | /Emp.py | 1,365 | 3.984375 | 4 | import datetime
print(datetime.datetime.now().year)
class Emp :
company = 'Infy'
def __init__(self,id,nm,age,address='Mumbai'):
self.eid = id
self.ename = nm
self.eage = age
self.eaddress = address
def showempdetails(self):
print('Emp Id -- ',sel... |
de69295b5df1d0a3664ecfab5eba02cdda7f5d84 | Pankhuriumich/EECS-182-System-folder | /Homeworks/HW8/GRADE/filterlines.py | 1,125 | 4.21875 | 4 | import sys
import pdb
def filterlines(filterstring):
'''
Print lines containing filterstring, ignoring characters prior to
filterstring on the line. Reads from standard input and writes to
standard output.
Example:
If filterstring is "SEARCH OUTPUT: ", it will look for this string
on each l... |
1d3ccd5fbde0dc5b227c1600843b50cbd8f838de | lemonataste/DataScience | /python/21-05-13format,문자열함수/Python04_13_strEx02_김기태.py | 327 | 4.1875 | 4 | # 문자열 인덱싱이란? 문자를 가리키는것
a="Life is too short, You need Python"
print(a[3],a[0],a[12],a[-1],a[-0],a[-2],a[-5])
#문자열 슬라이싱이란? 문자열을 잘라내는것.
print(a[0:4])
print(a[0:2],a[5:7],a[12:17])
print(a[19:])
print(a[:5])
print(a[:])
print(a[19:-7])
|
bc39873adb924fd4bf659d6331ebbeb7b6ab05da | sshleifer/cs231n_a2 | /assignment2/cs231n/torch_scratch.py | 3,574 | 4 | 4 | import torch.nn.functional as F
import torch
from torch import nn
import numpy as np
def three_layer_convnet(x, params):
"""
Performs the forward pass of a three-layer convolutional network with the
architecture defined above.
Inputs:
- x: A PyTorch Tensor of shape (N, 3, H, W) giving a minibatch... |
a2fc5ac502679b321b353438067c9e38d334835f | daedalus/misc | /rsa_conspicuous_check.py | 2,055 | 3.640625 | 4 | #!/usr/bin/env python
# Author Dario Clavijo 2020
# GPLv3
import gmpy2
import math
import sys
def rsa_conspicuous_check(N, p, q, d, e):
ret = 0
txt = ""
nlen = int(math.log(N) / math.log(2))
if gmpy2.is_prime(p) == False:
ret = -1
txt += "p IS NOT PROBABLE PRIME\n"
if gmpy2.is_pri... |
d2ad5c4c7b41b746bfe8e82d634bb97062995fd8 | DriesDries/shangri-la | /scripts/sample_codes/label_propagation.py | 2,613 | 4.21875 | 4 | # -*- coding: utf-8 -*-
"""
半教師あり学習(Label Propagation Algorithm)
ラベルなしデータに,周囲にあるデータのラベルの数などから,新たにラベルをつける.
実際に実装するときには,この後に改めてこのラベルを用いて教師あり学習(e.g. SVM)などで分類を行う.
==============================================
Label Propagation learning a complex structure
=========================================... |
d35316bd6c8ba4707f1637c7698f377341ab6f61 | quizl/quizler | /quizler/models.py | 4,255 | 3.5 | 4 | """OOP models for Quizlet terms abstractions."""
class Image:
"""Quizlet image abstraction."""
def __init__(self, url, width, height):
self.url = url
self.width = width
self.height = height
@staticmethod
def from_dict(raw_data):
"""Create Image from raw dictionary dat... |
4b604d8adff4b0f376d4c6ee5262e2968fb8283f | seven613/PyQt5 | /30个常用功能/09.输出某个路径下及其子目录下所有以html为后缀的文件.py | 344 | 3.828125 | 4 | '''
输出路径及其子目录下所有html为后缀的文件
'''
import os
def print_dir(filepath):
for i in os.listdir(filepath):
path =os.path.join(filepath,i)
if os.path.isdir(path):
print_dir(path)
if path.endswith(".html"):
print(path)
filepath ="e:\codes\python"
print_dir(filepath) |
60a99df7a20a1c01482a1c1e62e498645b280d60 | moshegplay/net4u | /defim.py | 480 | 3.6875 | 4 | def summary(ILS,Euro,USD):
count = ILS + (Euro*3.9) + (USD*3.4)
print("I have " + str(count) + " ILS")
return count
def tax(a,b,c):
ddddd=summary(a,b,c)
print(ddddd*1.17)
True
False
######################main dev
a = int(input("Enter how many shekels: "))
b = int(input("Enter ho... |
2cb40413d860c38dc8eb3ac413e4f7016868bfcc | dr-dos-ok/Code_Jam_Webscraper | /solutions_python/Problem_34/806.py | 979 | 3.59375 | 4 | #!/usr/bin/env python
fp = open('in.txt', 'rU')
lines = (line.rstrip("\n") for line in fp.xreadlines())
L, D, N = [int(val) for val in lines.next().split(' ')]
trie_root = {}
for word_index in range(D):
word = lines.next()
node = trie_root
for letter in word:
node = node.setdefault(letter, {})
n... |
d89eec5f31b56f6c4b5955fed09391ec38ec3e2b | Andyvn2/pythonfunctions | /randoms.py | 547 | 3.8125 | 4 | import random
def scoresandgrades(x):
x=10
y=0
while y<10:
random_num = random.randint(60,100)
if random_num<=100 and random_num>90:
print "Score:", random_num,";", "Your grade is: A",
if random_num<=90 and random_num>79:
print "Score:", random_num,";", "Your grade is: B",
if random_num<=79 and ra... |
11d7e73aa7e34a950f5c6c7413ed15459bab9521 | EfrainHSeg/semana6python | /problema(9).py | 340 | 4.125 | 4 |
b = int ( input ( "Ingrese el numero del angulo: " ))
if b == 0:
print("nulo")
elif 0<b<90:
print("agudo")
elif b==90:
print("recto")
elif 90<b<180:
print("obtuso")
elif b==90:
print("llano")
elif 180<b>360:
print("concavo")
elif b==360:
print("completo")
else:
print("no encontrado"... |
f23d45058252b2b8cd2580727ce9a5c904a8a39b | Pitrified/snippet | /python/bresenham/bresenham_generator.py | 2,600 | 3.625 | 4 | import logging
def bresenham_generator(x0, y0, x1, y1):
"""Yields the points in a Bresenham line from (x0,y0) to (x1,y1)
"""
# commented out for megafastperformance
# logline = logging.getLogger(f"{__name__}.console.generator")
# logline.setLevel("INFO")
# logline.setLevel("DEBUG")
#... |
683ba92de1d6cfc8a4c9fd99df1442f59ec00e39 | Lesikv/python_tasks | /python_practice/reach.py | 681 | 3.984375 | 4 | #!/usr/bin/env python
#coding: utf-8
def reach(x, y):
"""
You are in an infinite 2D grid where you can move in any of the 8 directions
You are given a sequence of points and the order in which you need to cover the points.
Give the minimum number of steps in which you can achieve it. You start from t... |
aff88c7e712228fd0a10965b53c40748b2b624ea | patriciobaez/algoritmos1 | /ejercicios/ejercicio12.py | 1,183 | 4.15625 | 4 | '''
1. Escribir una función que permita calcular la duración en segundos de un intervalo dado en horas,
minutos y segundos.
2. Usando la función del ejercicio anterior, escribir un programa que pida al usuario dos intervalos
expresados en horas, minutos y segundos, sume sus duraciones, y muestre por pantalla la durac... |
7009078ed0449ba6f081efa3ca38ad6175b69188 | sultanhusnoo/small_programs | /game_number_geussing.py | 2,601 | 4.125 | 4 | # Number geussing Game.
# User can choose a number and let computer try to geuss
# Or computer can choose a number and user has to geuss
# only bug to fix is if user inputs char for num
import random
def computer_geuss_number(x): # User has secret number. Computer tries to geuss
lower = 1
upper = x
while(True):
... |
6831327d71d97d717e4e771bd82fb6d7606d1483 | eunice-pereira/DC-python-fundamentals | /python102/small_3.py | 169 | 3.953125 | 4 | my_list = [10, 20, 30, 40, 50]
smallest = float("inf")
for num in my_list:
if num < smallest:
smallest = num
#easier built in method
print(min(my_list)) |
376f81e857306aa81dc45c04f24ea79f1d4a8c1b | Purushotamprasai/Python | /Atul_MD/002.py | 372 | 4.1875 | 4 | #union operation
a = {1,2,3,4}
b = {3,4,5,6}
print"******union operation**********"
print a|b # {1,2,3,4,5,6}
print a.__or__(b) # {1,2,3,4,5,6}
print a.union(b)
# update menethod
'''
after union operation the result we can store that particular variable
'''
print "a : ",a
print "b : ",b
a.up... |
47193fe6c97eb7f37aa859b78f3b4adcfe17d068 | awsserver/awsserver | /python/ex29.py | 620 | 4.0625 | 4 | #!/usr/bin/python
people = int(raw_input("Enter The number of People:- "))
cats = int(raw_input("Enter The number of cats:- "))
dogs = int(raw_input("Enter The number of dogs:- "))
if int(people) < int(cats):
print "Too Many cats! The world is doomed!"
if int(people) > int(cats):
print "Not many cats! The world i... |
b7bc8ea26c1bab83547b4802eb29a1bca6ef3c7b | Aitmambetov/2chapter-task17 | /task17.py | 2,403 | 4.3125 | 4 | """
Write the code which will write excepted data to files below
For example given offices of Google:
1)google_kazakstan.txt
2)google_paris.txt
3)google_uar.txt
4)google_kyrgystan.txt
5)google_san_francisco.txt
6)google_germany.txt
7)google_moscow.txt
8)google_sweden.txt
When the user will say “Hello”
Your code must co... |
8f43899b971ed1b50d7168ec2b3cd5fdc0513e2a | karanadapala/dsa_python_mit6.006 | /lecture4.py | 2,358 | 4.25 | 4 | '''
In this lecture version the concept of Heaps is covered.
We will be implementing the following concepts:
i. Max_heapify a.k.a Heapify the ds in descending Tree order.
ii. Extract_max - maximun number from the heap is extract and the rest of the heap is Heapified.
iii. Heap_Sort
A Heap is an array representation o... |
b863e75698d5f16c9b1690dc9d5de053707de296 | lycantropos/Project-Euler | /14.py | 642 | 3.75 | 4 | from typing import Iterable
from utils import odd
memoized_collatz_sequences_lengths = {}
def collatz_sequence_length(start: int) -> Iterable[int]:
term = start
length = 1
while term != 1:
if not odd(term):
term //= 2
else:
term = 3 * term + 1
try:
... |
d47247209a04ee2c5fdbdf801d6a803c959bb4f2 | smehmood/advent-of-code | /2019/day4/solveB.py | 878 | 3.53125 | 4 | import sys
def good_pw(pw_int):
pw = str(pw_int)
if len(pw) != 6:
return False
run_length = 1
double = False
last = None
for char in pw:
if last is not None and last > char:
return False
if last == char:
run_length += 1
else:
i... |
79f333db4bbddcf15eb15652b84d17cb15030ae3 | anafplima/ALGORITMOS | /algHash.py | 283 | 3.5625 | 4 | import collections
import string
maiusculas=collections.deque(string.ascii_uppercase)
minusculas=collections.deque(string.ascii_lowercase)
mensagem=(input("Digite a mensagem: "))
total=0
for i in range (len(mensagem)):
total+=ord(mensagem[i])
print("\nHASH: "+str(total%100)) |
ce2ef61159921e2d87aca000e5c59a8aed6e789d | anuranjanbose/Tic_Tac_Toe_py | /tictactoe.py | 4,371 | 3.75 | 4 | #from IPython.display import clear_output
import os
import random
def display_board(board):
print("\n"*100)
print("\t | |")
print("\t"+board[1] + " | " + board[2] + " | " + board[3])
print("\t | |")
print("\t- - - - -")
print("\t | |")
print("\t"+board[4] + " | " + board[5] + " | ... |
5c5aa07a122c350d52ab3d5d856064138e7896ee | abbas-sheikh-confiz/sql | /15_sql.py | 569 | 3.984375 | 4 | # Homework for SQL functions
# Show car models and total number of orders
import sqlite3
with sqlite3.connect('cars.db') as connection:
c = connection.cursor()
# Read data from inventory table
c.execute("SELECT Make, Model, Quantity FROM inventory")
cars = c.fetchall()
for car in cars:
print("Car Maker: {} - ... |
da699fa380438bd6a677884a2f2c8d6a0c8e574d | CamilliCerutti/Python-exercicios | /Curso em Video/ex076.py | 618 | 3.890625 | 4 | # LISTA DE PREÇOS COM TUPLAS
# Crie um programa que tenha uma tupla única com nomes de produtos e seus respectivos preços, na sequência. No final, mostre uma listagem de preços, organizando os dados em forma tabular.
print('~' * 40)
titulo = 'LISTA DE PRECOS'
print(titulo.center(30, ' '))
print('~' * 40)
lista = ('a... |
d4878969d21a3c4ab62e66be81e41f2854d91ca7 | cjineson/learning-python | /objects.py | 439 | 3.921875 | 4 | class Myclass(object):
def __init__(self,name):
self.name = name
print('Constructor creating object - ', self.name)
self.prefix = 'Hello'
def sayhello(self,suffix):
print(self.prefix + ' ' + suffix)
def __del__(self):
print('Destructor deleting object - ', self... |
50f8c224b903253c523d06c1026d5dcedad6ca5c | MrHamdulay/csc3-capstone | /examples/data/Assignment_1/crrlen001/question3.py | 992 | 3.96875 | 4 | firstname = input('Enter first name:\n')
lastname = input('Enter last name:\n')
money = eval(input('Enter sum of money in USD:\n') )
country = input('Enter country name:\n')
money30 = money*0.3
print('\nDearest', end=' ')
print(firstname, end='')
print('\nIt is with a heavy heart that I inform you of the dea... |
1cc69f2ea48049368048bb29224c149edb8f9e95 | yuki9965/PAT-1 | /PAT_B_TEST/1004_Tree_Traversals_Again.py | 2,274 | 3.75 | 4 | # -*- coding: utf-8 -*-
__author__ = 'Yaicky'
import sys
rlt = []
class Node(object):
def __init__(self, data=-1, lchild=None, rchild=None, parent=None):
self.data = data
self.lchild = lchild
self.rchild = rchild
self.parent = parent
self.count = 0
class BinaryTree(object... |
925331ad9553b6c4c87cb79dba0b776825ce23f4 | xiaoxiae/Advent-of-Code-2018 | /03/03-1.py | 649 | 3.546875 | 4 | from re import compile
input = open("03.in", "r")
data = input.read().splitlines()
total = 0
board = [[0] * 1000 for _x in range(1000)]
# put all of the pieces of fabric on the board
for line in data:
s = compile(" @ |: ").split(line)
start = tuple(map(int, s[1].split(",")))
size = tuple(map(... |
619580f3805ec431379ef1f07ef24654f35fa609 | diri-daniel/C.I.D.S_projects_ibinabo_daniel | /wk2/wk2_ex2.py | 399 | 3.5 | 4 | """ Question 2 doesnt have an example but here's my interpretation:
input a = 4
process is 4+44+444+4444
output 4936."""
def digit_multp(t, v):
b = 1
v = str(v)
p = v
while b < t:
p += v
b += 1
return int(p)
def incr_n(n):
n_n = 0
for x in range(1, n+1):
... |
be7291cf330aa1d583f9904f2671f36d9fc3759f | seamkh/codetest_2021 | /python/DataStructureWithPython/3-2 nodestack/nodestack.py | 962 | 4 | 4 | class Node:
def __init__(self,item,link):
self.item = item
self.next = link
def push(item):
global top
global size
top = Node(item, top)
size +=1
def peek():
if size != 0:
return top.item
def pop():
global top
global size
if size != 0:
top_item = to... |
b0d4ddee2143642fee23659331031ba05dae05db | Aasthaengg/IBMdataset | /Python_codes/p02795/s146411544.py | 104 | 3.8125 | 4 | l=[int(input()) for i in range(3)]
x=l[0]
y=l[1]
z=l[2]
if x<y:
print(-(-z//y))
else:
print(-(-z//x)) |
32d83c75c7c6a6c0d63b7f4ef68668b19fe2ebca | rogersineb/python_developer | /Ciencia_da_Computacao_USP_2/submissao_6_semana/fibonacci_recursivo.py | 453 | 3.734375 | 4 | def fibonacci(numero):
if numero < 2: # base da recursão
return numero
else:
return fibonacci(numero-1) + fibonacci(numero-2) #chamada recursiva
import pytest
@pytest.mark.parametrize("entrada, esperado", [
(0 , 0),
(1 , 1),
(2 , 1),
(3 , 2),
(4 , 3),
... |
6cc2fad20de15747225db199155e1c9cb238c863 | lsaruwat/address_book | /addressBook.py | 6,193 | 4.125 | 4 | #Assignment 3 Address Book
#CS310 Python
#By: Logan Saruwatari
#Date: 3/30/2016
#Copyright MIT license
import sqlite3
from os import system
from os import name as osName
class Interface(object):
enumColumn = ('fName', 'lName', 'phone', 'email')
def __init__(self): # Pretty much don't do anything. It feels wrong ... |
5584842fd704aeb58dbe254cd51324249fd17651 | zhaoxinnZ/HeadFirstPythonPractice | /12-3.py | 126 | 3.890625 | 4 | num = float(input())
if num > 0:
print(num, '是正數')
elif num == 0:
print('零')
else:
print(num, '是負數') |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.