blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
c65cf13178f85b7c42e7f694764ee598d903b853 | keys4words/python | /specialist02/016_home-work.py | 2,850 | 3.90625 | 4 | import abc
from random import randrange
class IShape(abc.ABC):
@abc.abstractmethod
def get_perimeter(self):
pass
@abc.abstractmethod
def get_area(self):
pass
@abc.abstractmethod
def get_description(self):
pass
class Circle(IShape):
PI = 3.14
def __init__(self, r... |
1c1fcd288838c2da7cc5442246c4d7eaa8f72be2 | keys4words/python | /specialist02/012_dependency-inversion.py | 2,108 | 3.625 | 4 | #problem
# class FileRead:
# def __init__(self, name):
# self.__name = name
# def read(self):
# print(f'Read from file {self.__name}')
# return 'File was written'
#
# class KeyboardRead:
# def readln(self):
# print('Read from keyboard')
# return 'Input from keyboard w... |
eef70e861f496ce1fcae01298891e160c06e6100 | keys4words/python | /specialist01/009_strings.py | 304 | 3.90625 | 4 | name = 'Popandopulo'
if name.startswith('Pop'):
print('yes')
if 'a' in name:
print('string consists \'a\'')
if name.find('dop') != -1:
print('string has substring "dop"')
delimeter = '_*_'
mylist = ['Бразилия', 'Россия', 'Индия', 'Китай']
print(delimeter.join(mylist)) |
485da79c10f32d4239fefbd2c9d52eb3ea38c017 | keys4words/python | /teclado_flow/oop/car.py | 819 | 3.984375 | 4 | class Car:
def __init__(self, brand, model, year):
"""инициализация атрибутов автомобиля"""
self.brand = brand
self.model = model
self.year = year
self.mileage = 0
def description(self):
desc = str(self.year) + ' ' + self.brand + ' ' + self.model
return d... |
33df95ee3d14760502705fd8ffb733b3dcf691c6 | keys4words/python | /teclado_flow/programmingKnowledge/52.py | 184 | 3.90625 | 4 | def add(x, y):
sum = x+y
return sum
def main():
x = int(input("Num 1: "))
y = int(input("Num 2: "))
z = add(x, y)
print(z)
if __name__=="__main__":
main() |
c509d6ebaec73257fe0698c88f662a34cfc4bb50 | keys4words/python | /teclado_flow/socratica/lambdas.py | 429 | 3.8125 | 4 | def f(x):
return 3*x + 1
print(f(3))
x_ = lambda x: 3 * x + 1
print(x_(3))
full_name = lambda fn, ln: fn.strip().title() + " " + ln.strip().title()
print(full_name(' MAX ', 'zharnikov'))
scifi_authors = ["Isaac Asimov", "Ray Bradbury", "Robert Heinlein", "Arthus C.Clarke", "Frank Herbert", "Orson Scott C... |
7094be379f30b6bd17611a8cbd7f09ee48e695b3 | keys4words/python | /specialist02/003_class_attributes.py | 316 | 3.828125 | 4 | class Person:
legs = 2
count = 0
def __init__(self, name):
self.name = name
Person.count += 1
def show(self):
pass
person = Person('Max')
person1 = Person('Max')
person2 = Person('Max')
print(person.legs, person.name)
print(Person.legs, 'number of persons =', Person.count) |
d901d33a97ab9c209dd7bcdfcedacdcf2e6ca1d0 | keys4words/python | /specialist02/026_priority_queue.py | 1,087 | 3.875 | 4 | class Queue:
def __init__(self):
self.__data = list()
def enqueue(self, item):
self.__data.append(item)
def dequeue(self):
if len(self.__data) > 0:
return self.__data.pop(0)
return None
def rear(self):
if len(self.__data) > 0:
return self._... |
3f98c86c6bfd262c9b7fd6249d9534a2fc448771 | keys4words/python | /teclado_flow/perestanov.py | 514 | 3.828125 | 4 | def generate_numbers(N:int, M:int, prefix=None):
""""Generate any numbers
at N-dimensional system
with length = M"""
prefix = prefix or []
if M == 0:
print(prefix)
return
for digit in range(N):
prefix.append(digit)
generate_numbers(N, M-1, prefix)
... |
8fc74df131520df1766b614810543945db422a72 | keys4words/python | /tkinter/004.py | 546 | 3.75 | 4 | from tkinter import *
root = Tk()
colors = {
"#ff0000": 'red',
"#ff7d00": 'orange',
"#ffff00": 'yellow',
"#00ff00": 'green',
"#007dff": 'blue',
"#0000ff": 'dark blue',
"#7d00ff": 'violet'
}
l = Label(root)
e = Entry(root, width=30, justify='center')
l.pack()
e.pack()
def get_color(text_c... |
d9b961eb17cb60229fd7b7b6a05a9339c01b16ff | keys4words/python | /teclado_flow/oop_w4myself/classes.py | 944 | 3.78125 | 4 | class Person:
# name = "John"
def __init__(self, name, age=20):
self.name = name
self.__age = age
# def get_age(self):
# return self.__age
#
# def set_age(self, age):
# if age in range(1, 101):
# self.__age = age
# else:
# print("age ... |
fbc500895db453719d126d984505c3690a84a325 | keys4words/python | /teclado_flow/programmingKnowledge/nested_functions.py | 535 | 3.890625 | 4 | def outerFunction(text):
def innerFunction():
print(text)
return innerFunction
a = outerFunction('Max')
del outerFunction
a()
def pop(list):
def get_last_item(my_list):
return my_list[len(list) - 1]
list.remove(get_last_item(list))
return list
a = [1, 2, 3, 4, 5]
print(pop(a))
pr... |
61bf93debef569e07c5c4bdd98c2691baf0e8d7d | keys4words/python | /teclado_flow/regularka_w4myself/regularka.py | 1,321 | 3.78125 | 4 | import re
# s = 'Это просто строка текста. А это еще одна строка текста.'
s = '''Это просто строка текста.
А это ещё одна строка текста.
А это строка с цифрами: 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 10, ٢, €, £, ¥, $
А это строка с разными символами: "!", "@", "-", "&", "?", "_"
a\\b\tc
test string'''
# pattern = 'строка'
#t... |
0ee4debf74053d558559cc906d371257341fbac5 | keys4words/python | /teclado_flow/list_methods.py | 363 | 3.71875 | 4 | l = [1, 2, 3, 'hello', ['test', 10], 'world', True]
# l[:2] = ['Maximus', 'wins']
l.append('new')
names = ['Ivanov', 'Petrov', 'Sidorov']
l.extend(names)
l2 = ['hey', 'hello']
l += l2
l.insert(4, False)
l.remove('hello')
print(l.pop(2))
print(l.count('new'))
l3 = ['hello', 'hi', 'max', 'knew', 'oath']
l3.sort(reverse=... |
8dfc9d9257a4ed6854ece19e2470eb89e7bd57ce | SiERic/paradigms-au-2017 | /hw5/yat/model.py | 4,378 | 3.671875 | 4 | class Scope:
def __init__(self, parent=None):
self.data = dict()
self.parent = parent
def __setitem__(self, key, value):
self.data[key] = value
def __getitem__(self, key):
if key in self.data:
return self.data[key]
if self.parent:
return sel... |
8242e2eb55ad59d6c17497e56df4cc150fc78a33 | jpchato/data-structures-algorithms-portfolio | /python/array_shift.py | 766 | 4.3125 | 4 | '''
Feature Tasks
Write a function called insertShiftArray which takes in an array and the value to be added. Without utilizing any of the built-in methods available to your language, return an array with the new value added at the middle index.
Example
Input Output
[2,4,6,8], 5 [2,4,5,6,8]
[4,8,15,23,42], 16 [4,8,1... |
8fd9c4937bf6beb4f1656e6340cc850878997ab1 | anmmoinuddin/Python | /Online Course/Computing in Python II/CPII part1 (if else).py | 3,911 | 3.9375 | 4 | ##Control Structure
#if
myNum1=3
myNum2=2
if myNum1<myNum2:
print("myNum2 is greater than myNum1")
print("Yes it is!")
print("Yes it is!")
print("Execution complete")
#---------------------------------------------------------------------------------
#Thedangers of Scope
myNum1=3
myNum2... |
1da7c1d557882c31dc47f49b93c7dcb2271c8d3d | anmmoinuddin/Python | /Online Course/Computing in Python II/CPII part2(for loop).py | 2,453 | 4.0625 | 4 | ##for loop
for i in range(1,11):
print("Before addition: ", i)
i+=1
print("After addtion: ", i)
#---------------------------------------------------------------------
##sum=0
##for i in range(1,11):
## nextNumber=int(input("Enter the number #" +str(i )+ ":"))
## sum+=nextNumber
##p... |
1eaaf5a8f56ff216acf966e83f9637eed110ec1b | vpn1997/Tensorflow_learn | /mnist_tut.py | 1,314 | 3.5625 | 4 | import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
mnist =input_data.read_data_sets("/tmp/data",one_hot=True)
#hidden layers
n_nodes_hl1= 500
n_nodes_hl2= 500
n_nodes_hl3 =500
n_classes= 10
batch_size=100
x=tf.placeholder('float',[None,784]) #data
y=tf.placeholder('float') #label of... |
4904bca0f64ddcb70b8b43063042d08668e43d78 | py-study-haili/py01 | /python_01基础/随机数的处理.py | 268 | 3.703125 | 4 | # 随机数的处理
# 导入随机数函数
import random
randomNum = random.randint(1,10)
print(randomNum)
player = int(input('请出拳'))
if randomNum > player:
print('电脑赢')
elif randomNum == player:
print('平局')
else :
print('玩家赢') |
6564c40f0de9ea6a55d726bdd0667a8da7ee943f | py-study-haili/py01 | /python_01基础/格式化输出.py | 739 | 4.0625 | 4 | # 定义字符串变量 name 输出 我的名字叫 小明, 请多多关照!
name = "小明"
print("我的名字叫%s" % name)
# 定义整数变量 student_no,输出 我的学号是000001
student_no=1
print("我的学号是%06d" % student_no)
# 定义小数 price、weight、money,
# 输出 苹果单价 9.00 元/斤,购买了5.00斤,总共45.00元
price=8.5
weight=7.5
money=price*weight
print("苹果单价 %.02f 元/斤,购买了 %.02f 斤, 总共 %.02f 元" % (price,weigh... |
d66ad48816e85da3ff11176811a21db44c14f0fb | py-study-haili/py01 | /python_01基础/07_运算.py | 139 | 3.65625 | 4 | # 字符串运算
first_name='三'
last_name='张'
print(last_name+first_name)
print((last_name+first_name)*100)
# print(last_name+10) |
f449517cb5002d99c03b6a0460984637862a4887 | nayaran/principles_of_computing | /poc_part2/wordwrangler/binary_search.py | 1,003 | 4 | 4 | # Binary Search
def binary_search(given_list, item):
if len(given_list) == 1:
return item == given_list[0]
mid = len(given_list)/2
if item < given_list[mid]:
return binary_search(given_list[:mid], item)
else:
return binary_search(given_list[mid:], item)
... |
549ec726db339d539742e8df7525c42eba31c7a9 | nayaran/principles_of_computing | /poc_part1/yahtzee/enumeration.py | 4,068 | 3.953125 | 4 | """
Functions to enumerate sequences of outcomes
Repetition of outcomes is allowed
"""
def gen_all_sequences(outcomes, length):
"""
Iterative function that enumerates the set of all sequences of
outcomes of given length
"""
ans = set([()])
for dummy_index in range(length):
temp = set... |
afbd3b02a4f65592e32049a798a5a35333d874b3 | rtmooy/Earthqake-Sorting-Program | /quakeFuncs.py | 3,460 | 3.578125 | 4 | from urllib.request import *
from json import *
from datetime import *
from operator import *
# GIVEN FUNCTIONS:
# Use these two as-is and do not change them
def get_json(url):
''' Function to get a json dictionary from a website.
url - a string'''
with urlopen(url) as response:
html = re... |
0295d42f23433cac8dda7174deeba95d8167bb3f | rohitn12/Algorithms | /selectionSort.py | 347 | 3.75 | 4 | def selectionSort(array):
lengthOfArray = len(array)
for i in range(lengthOfArray):
for j in range(i+1 , lengthOfArray ):
if(array[j] < array[i] ):
temp = array[j]
array[j] = array[i]
array[i] = temp
return array
#test
selection... |
2f16f55d15a88310a8dda76efb696948bf0f108c | AkankshaRaut/MyPython | /swapping with third.py | 180 | 3.96875 | 4 | a=int(input("Enter the value of a :"))
b=int(input("Enter the value of b :"))
temp=a
a=b
b=temp
print("after swapping")
print("value of a :", a)
print("value of b :", b)
|
7760bced0fda93dac93490c8d85a9baa9423506d | AlKoAl/Progect | /progect2/by100mc.py | 2,322 | 3.609375 | 4 | """
Производит интерполяцию исходной последовательности RR-интервалов, и выводит значения графика через каждые
100 миллисекунд.
Интерполяция проводится путём линейных сплайнов, мировые стандарты - кубическая интерполяция, поэтому нужно переделать
"""
def approximate(x, y):
# Приписывает после координат точек (все... |
4bb7055a7cd86b7b8e54f7d1ac1016b23a19127d | montanarice/DailyProgrammer | /challenge_330_easy/BoxTheCircles.py | 2,688 | 3.859375 | 4 | input = [[1, 1, 2], [2, 2, 0.5], [-1, -3, 2], [5, 2, 1]]
class Circle():
"""A circle object"""
def __init__(self, input_coord):
self.x = input_coord[0]
self.y = input_coord[1]
self.r = input_coord[2]
def left_xcoord(self):
"""Return leftmost coordinate"""
return s... |
5332542eca544e73bb048cfeced7812d506d9943 | Ambush3/BMI-Calculator | /BMI calculator.py | 524 | 4.21875 | 4 | print("Lets find your BMI")
height = float(input("Enter your height in m: "))
weight = float(input("Enter your weight in kg: "))
bmi = weight/(height**2)
print("Your bmi is {0} and you are: ".format(bmi), end='')
if ( bmi < 18.5):
print("underweight.")
elif ( bmi >= 18.5 and bmi < 25 ):
print("nor... |
03bd93a8885ac1784ee1cc09dd66ed5f9f6794e0 | saikiran-007/Hackerrank-coding-solutions | /Lily's Homework | 1,085 | 3.6875 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
#
# Complete the 'lilysHomework' function below.
#
# The function is expected to return an INTEGER.
# The function accepts INTEGER_ARRAY arr as parameter.
#
def lilysHomework(arr):
# Write your code here
ind={}
for i in range(len(arr... |
bf0f887b9beac4338399852a188b0da2c5c169a3 | royalbhati/100-Days-of-Code | /bfs_python.py | 890 | 3.78125 | 4 | from collections import defaultdict
class Graph:
def __init__(self):
self.graph=defaultdict(list)
self.queue=[]
self.visited=set()
def add_edge(self,u,v):
self.graph[u]=v
def bfs(self,node):
self.queue.append(node)
print(self.queue)
while sel... |
f624019c7b7abee8a6d77b27b5de5d5009da2a87 | windKusanagi/LeetCode-Python | /LeetCode/No.1-No.99/LeetCode(71-80)/Q77.py | 658 | 3.609375 | 4 | from itertools import combinations
class Solution:
def combine(self, n, k):
return list(combinations([i for i in range(1, n+1)], k))
'''
class Solution:
def combine(self, n, k):
result = []
self.combineNK(n, result, 0, [], k)
return result
def combineNK(self, n,... |
a76e3e1fab2c799f2a28bb98a233f5f9271937a3 | windKusanagi/LeetCode-Python | /LeetCode/No.1-No.99/LeetCode(51-60)/Q56.py | 1,161 | 3.828125 | 4 | # Definition for an interval.
class Interval(object):
def __init__(self, s=0, e=0):
self.start = s
self.end = e
# To print the result
def __str__(self):
return "[" + str(self.start) + "," + str(self.end) + "]"
class Solution(object):
def merge(self, intervals):
... |
1b2800641a9ed15a824f727a5db565562fec51a7 | windKusanagi/LeetCode-Python | /LeetCode/No.1-No.99/LeetCodeCasualQ/Reverse Words in a String III.py | 398 | 3.65625 | 4 | class Solution(object):
def reverseWords(self, s):
"""
:type s: str
:rtype: str
"""
if not s:
return s
collect = s.split(" ")
result=[]
for i in range(len(collect)):
result.append(collect[i][::-1])
return " "... |
9ec025280e0928d3407c766182734e5986d67e95 | windKusanagi/LeetCode-Python | /LeetCode/No.1-No.99/LeetCode(91-100)/Q100.py | 945 | 3.859375 | 4 | # Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def isSameTree(self, p, q):
flag = True
flag = self.isSame( p, q)
return flag
def isSame(... |
ac92e4aa4af90c75c27f9dbd7cc5ea75e156a2a0 | windKusanagi/LeetCode-Python | /LeetCode/No.100-No.150/LeetCode(111-120)/Q117.py | 1,452 | 3.890625 | 4 | # Definition for binary tree with next pointer.
class TreeLinkNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
self.next = None
def __repr__(self):
if self is None:
return "Null"
else:
return "{} -> {}... |
94b64c054b74370b2c7c3a16543f2e1e73ba0427 | windKusanagi/LeetCode-Python | /LeetCode/No.1-No.99/LeetCodeCasualQ/HammingDistance.py | 539 | 3.703125 | 4 | class Solution(object):
def hammingDistance(self, x, y):
str1 = str(bin(x))[2::]
str2 = str(bin(y))[2::]
temp =""
if len(str2)>len(str1):
return self.hammingDistance(y,x)
for i in range(len(str1)-len(str2)):
temp+= "0"
str2 = temp + st... |
bf2abce8c19dca715bde6d8bc3124c48acd440bb | windKusanagi/LeetCode-Python | /LeetCode/No.1-No.99/LeetCode(10-20)/Q19.py | 868 | 3.734375 | 4 | class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
def myPrint(self):
print(self.val)
if self.next:
self.next.myPrint()
class Solution(object):
def removeNthFromEnd(self, head, n):
if not head:
return he... |
bf2b3998c2d6ea066d6d1605d5fab0194f4c5d82 | windKusanagi/LeetCode-Python | /LeetCode/No.1-No.99/LeetCode(10-20)/Q14.py | 573 | 3.65625 | 4 | class Solution(object):
def longestCommonPrefix(self, strs):
result="";
if not strs:
return result;
for i in range(len(strs[0])):
temp= strs[0][i];
for j in range(len(strs)):
if len(strs[j]) < i+1:
return resu... |
873ea0ffee033cb9652107fc800c1ff4aa6d4902 | lvergergsk/Algorithms-and-Libraries | /LeetCode/[0002]Add_Two_Numbers/Solution.py | 1,695 | 3.765625 | 4 | # # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
@staticmethod
def get_carry_on(num):
if num >= 10:
return num - 10, 1
else:
return num, 0
@staticmethod
def n... |
6f95a1e3c79e4a5b7722a2d9bca6f2e48ce551d7 | wangshubing1/Python3 | /Triangel.py | 383 | 3.875 | 4 | #Topic : 杨辉三角
#File Name : Triangle.py
#Author : Jack Cui
#Created : 8 April 2016
def triangles():
a = [1]
while True:
yield a
a = [sum(i) for i in zip([0] + a,a + [0])]
if __name__ == '__main__':
h = int(input('请输入您要显示的最大行数:'))
tri = triangles()
for n i... |
0a58cb2c1dc35acb144e58527d2fb64236404979 | DIOGO-MOTA/AulasPython | /aula6.1ex.py | 506 | 3.90625 | 4 | # Dada um lista contendo as notas de alunos
# em uma disciplina, escreva uma expressão para:
# notas = [9,7,7,10,3,9,6,6,2]
# a) Encontrar quantos alunos tiraram nota 7
# b) Encontar a Maior nota
# c) Ordernar a lista de Notas
# d) A média das notas
notas = [9,7,7,10,3,9,6,6,2]
# a) print(notas.count(7))
# b)
... |
d8959d24b459e8d1f7629043f774a1068042b96e | moomoo-95/programmers | /Practice problem/String handling basic/String handling basic.py | 239 | 3.546875 | 4 | # 연습문제 문자열 다루기 기본 Level 1
def solution(s):
if len(s) != 4 and len(s) != 6:
return False
for i in range(len(s)):
if ord(s[i]) > 57 or ord(s[i]) < 48:
return False
return True
|
404f3d680a3588a76dffe54cc1671c0aef731df8 | moomoo-95/programmers | /Practice problem/Harshad number/Harshad number.py | 219 | 3.625 | 4 | # 연습문제 하샤드 수 Level 1
def solution(x):
z = x
y = 0
while z > 0:
y += z%10
z -= z%10
z /= 10
if ((x % y) == 0 ):
return True
else:
return False
|
397fc94b41673eeb5d495af35e9d082adf24ef92 | moomoo-95/programmers | /Practice problem/return middle word/return middle word.py | 251 | 3.859375 | 4 | # 연습문제 가운데 글자 가져오기 Level 1
def solution(s):
if len(s) % 2 == 1:
return s[(len(s)) // 2]
else:
return s[(len(s)-1) // 2:((len(s)-1) // 2)+2]
s = solution("abcde")
print(s)
s = solution("wear")
print(s)
|
db82ddf681837b4a3e143e42d938c265a0ef6a90 | c-node/pygame-rainfall | /RAINFALL.PY | 3,766 | 3.625 | 4 | # Rainfall
# Demonstrates object animation
# Churchill - 9/24/2016
import pygame, random
from colour import Color as colour
pygame.init()
SIZE = [640, 480]
screen = pygame.display.set_mode(SIZE)
clock = pygame.time.Clock()
done = False
guy = pygame.image.load("rainfallguy.png").convert()
raindrops = []
for i in ... |
d6992f73e139ef7ebccf52de555248a70bde5591 | sepidehsaran/appfs | /Dinsel/ex5/ex5.py | 7,668 | 3.78125 | 4 | #!/usr/bin/env python3
import sys
import numpy as np
import matplotlib.pyplot as plt
from collections import defaultdict, deque, OrderedDict
from random import shuffle, choice
class Graph():
"""This class provides the basic functionality for graph handling."""
def __init__(self):
"""Initialize the di... |
aa081727ddb45c3116ba517de2d27cf8c684f050 | sepidehsaran/appfs | /tapia/exercise1/ex1.py | 2,825 | 3.609375 | 4 | """@package docstring
Author: Roxana Tapia Campos
Module: Advanced practical programming skills for scientists
SS17 - TU Berlin
Exercise 1: GeoMean
"""
import sys
import math
LINES_COUNT = 0
VALID_VALUES_LOC1 = 0
LOG_SUM_LOC1 = 0
VALID_VALUES_LOC2 = 0
LOG_SUM_LOC2 = 0
def read_file(filename):
"""
Reads ... |
f0678a807bc4d5be440dd742a8fc6fbbf3e3f281 | Harshith-droid/SkillShare_Course | /LinkedSelectionSort.py | 1,091 | 3.59375 | 4 |
from doublylinkedlist import DoublyLinkedList
def selectionsort(numberlist):
for i in range(len(numberlist) - 1, 0, -1):
max_position = 0
for j in range(1, i + 1):
if numberlist[j] > numberlist[max_position]:
max_position = j
temp = numberlist[i]
number... |
c41603591d68144f755ce18c5468a72dbbccb6d0 | thiagosantanap/Projeto-PI | /Backend/ordenacao/heap.py | 819 | 3.78125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat May 4 15:20:43 2019
@author: CASA
"""
def heapify(lista, tamanho, indice):
largest = indice
left = 2 * indice + 1
right = 2 * indice + 2
if(left < tamanho and lista[indice] < lista[left]):
largest = left
if(right < tamanho and lista[l... |
3912b2d5734f70f43afec7fdded003bcd11f3386 | J-amelie/AJOU_python | /조건문 예제_if~else.py | 407 | 3.84375 | 4 | denominator = int(input('분모를 입력하세요 : '))
numerator = int(input('분자를 입력하세요 : '))
if denominator == 0 :
print('분모가 0입니다.')
else :
if numerator > denominator :
print('가분수입니다.')
else :
print('진분수입니다.')
print('ans = {} / {} = {}'\
.format(numerator, denominator, nume... |
eabb28a7dc7d4d0f70c2e6c947f91f1e238187df | PierreGauthier/Regital | /navigation/currency.py | 755 | 3.515625 | 4 |
class CurrencyError(Exception):
def __init__(self):
self.value = 0
# Change une chaine de caractere de la forme 12,25,54 (livre, sou, denier) une un entier (la valeur en denier)
def currencyToNumber(strValue):
listValue = strValue.split(',')
if len(listValue) == 3 :
return (int(listValue[0])*240)+(int(listV... |
790722f6251625fbed6ef0b3fa8a03ad141466a6 | MaukWM/Spectrangle | /agents/human_agent.py | 1,278 | 3.53125 | 4 | import random
import move
import state
from agents import agent
class HumanAgent(agent.Agent):
def get_move(self, s: state.State) -> move.Move:
possible_moves = s.get_all_possible_moves(self.index)
possible_moves = list(possible_moves)
while True:
print("Hand index, Row and C... |
12ac37c1930e06134834ad5fd470558b4511a4ca | yegomeister/netacadpython | /another/dummy.py | 412 | 3.953125 | 4 |
def find():
s1 = input('What letters are we looking for?\n')
s2 = input('Where are we looking?\n')
if s2.find(s1[0]):
index_l = [s2.find(l, s2.find(s1[0]), len(s2)) for l in s1[1:]]
print(index_l)
return all(x > x+1 for x in range(len(index_l) - 2))
else:
return False
... |
bb11d4acaa15e9cf75b4adcd0e93f7d7ffebc184 | yegomeister/netacadpython | /another/tictactoe.py | 3,169 | 3.6875 | 4 | from random import randrange
board = [[1, 2, 3], [4, "X", 6], [7, 8, 9]]
b2 = board[:]
# pos = {1: board[0][0], 2: board[0][1], 3: board[0][2], 4: board[1][0], 5: board[1][1], 6: board[1][2], 7: board[2][0], 8: board[2][1], 9: board[2][2]}
def display_board(board):
print("+-------+-------+-------+")
print("... |
f760809dc143f3cf54b451970ca5d7f5ac07f30e | mathisgr/py-problems | /p0003.py | 1,197 | 3.625 | 4 | import math
def p0003fast(n):
largest_prime_factor = 1
# lets deal with 2
while n % 2 == 0:
n = n/2
remaining_n = n
if remaining_n == 1:
return 2
starting_factor = 3
while remaining_n > 1 and starting_factor < math.sqrt(remaining_n):
if remaining_n % starting_f... |
1ce750d4d04311d65db29c37be28ae93d8996ad9 | biagioboi/Programmazione-Avanzata | /sumGenerator.py | 288 | 3.890625 | 4 | #funzione generatrice che prende in input n e restituisce un iteratore degli interi 0..1..3..6.. l'iesimo elemento scandito dell'iteratore è (0+1+...+i-1)
def generatore(n, somma = 0):
for i in range(0, n):
somma+=i
yield somma
for x in generatore(10):
print(x) |
95b1bbb0522f5eb6403bb4954d4b914b5739ca12 | muhadyan/Day-10-Modul-1 | /Day10Task.py | 1,515 | 3.765625 | 4 | class student:
def __init__(self, nama, usia):
self.nama = nama
self.usia = usia
data = [
{'nama': 'Andi', 'usia': 21},
{'nama': 'Budi', 'usia': 22},
{'nama': 'Caca', 'usia': 23},
{'nama': 'Deni', 'usia': 24}
]
def creatObj(x):
nama = x['nama']
vars()[nama] = student(x[... |
0a0f77de3a3a7799b00044a4dece02e404675f71 | ivv1as/Cp4 | /4.py | 286 | 3.78125 | 4 | years= int(input('Введите число лет '))
exp = int(input('Введите число экспонатов '))
a = int(years*365*24//(8*(60/5)))
b = int(exp//(8*(60//5)//365)
print('Количество экспонатов ',a)
print('Количество часов ',b) |
4a26d608b1519a4a9c4d3c6a2992d2c19a010856 | thiriaung05/Learning-Python | /list.py | 274 | 3.9375 | 4 | Inputloop=input("Enter the number:")
loop=int(Inputloop)
num=[]
for i in range(0,loop):
number=input("Enter the list number:")
num.append(int(number))
num1=num[0]
num2=num[loop-1]
if num1==num2:
print("Result is True")
else:print("Result is False") |
416d903481d196cb05569e3c882cd8b64ab4b569 | manoharaswal/Python | /Set.py | 198 | 3.71875 | 4 | my_set1 = {1,2,5,7,5,10,8,2,1}
my_set2 = {2,5,9,11,15,20}
print(my_set1)
print("Union = ",my_set1 | my_set2)
print("Intersection = ",my_set1 & my_set2)
print("Difference = ",my_set1 - my_set2)
|
c6b050dcf9db106e8dfdccfb0a2167ee8c719954 | manoharaswal/Python | /ForLoop.py | 224 | 4 | 4 | students = {
"male": ["Ram", "Syam", "Mohan", "Raj"],
"female": ["Rita", "Sita", "Geeta"]
}
for key in students.keys():
for name in students[key]:
if "S" in name:
print(name)
|
5801740e7237f74a9af0571f401751b9d7005cc6 | pau1fang/learning_notes | /数据结构与算法/剑指offer_python语言/question39_数组中出现次数超过一半的数字.py | 1,721 | 3.6875 | 4 | def more_than_half_num(arr, length):
if arr is None or length<=0:
return 0
mid = length >> 1
start = 0
end = length - 1
index = partition(arr, length, start, end)
while index != mid:
if index > mid:
index = partition(arr, length, start, index-1)
else:
... |
56631cc023e7783d480d08b8be46a4961303a976 | pau1fang/learning_notes | /数据结构与算法/剑指offer_python语言/question15_二进制中1的个数.py | 407 | 3.65625 | 4 | def number_of_1(num):
n = 0
while num:
if num & 1:
n += 1
num >>= 1
return n
# def num_of_1(num):
#
# n = 0
# flag = 1
# while flag:
# if num & flag:
# n += 1
# flag <<= 1
# return n
def num_of_1(num):
count = 0
while num:
... |
92dbf926b50ed08586a0250f1973ae0f261f26cc | pau1fang/learning_notes | /数据结构与算法/DataStructures/graph.py | 1,770 | 3.703125 | 4 | class Vertex:
def __init__(self, key):
self.id = key
self.connected_to = {}
def add_neighbor(self, nbr, weight=0):
self.connected_to[nbr] = weight
def __str__(self):
return str(self.id) + " connectedTo: " + str([x.id for x in self.connected_to])
def get_connections(sel... |
ce831942aef14a175861da0dcfeb47104bac5580 | pau1fang/learning_notes | /数据结构与算法/DataStructures/chapter05/排序/bubblesort.py | 714 | 3.96875 | 4 | def bubble_sort(alist):
for i in range(len(alist)-1, 0, -1):
for j in range(i):
if alist[j]>alist[j+1]:
alist[j], alist[j+1] = alist[j+1], alist[j]
def bubble_sort2(alist):
"""冒泡排序的改进,判断一次遍历有没有发生交换,如果没有就表明已经排序好了"""
change = True
length = len(alist)-1
while (lengt... |
541bcbf149b25743035d9986dc5b7e230805d345 | pau1fang/learning_notes | /数据结构与算法/剑指offer_python语言/question43_1到n整数中1出现的次数.py | 625 | 3.515625 | 4 | def sum_of_1(n):
number = 0
while n > 0:
if n % 10 == 1:
number += 1
n //= 10
return number
def solution1(n):
count = 0
for i in range(1, n + 1):
count += sum_of_1(i)
return count
def solution2(n):
if n<10:
return 1
num_list = list(str(n))
... |
7df329401e26b9bd24b8368419fc104f226454c0 | pau1fang/learning_notes | /数据结构与算法/DataStructures/chapter05/排序/insectionsort.py | 645 | 3.953125 | 4 | def insertion_sort(alist):
# for i in range(1, len(alist)):
# j = i-1
# temp = alist[i]
# while (j >=0) and (alist[j]>temp):
# alist[j+1] = alist[j]
# j -= 1
# # if j!=i-1:
# alist[j+1] = temp
for index in range(1, len(alist)):
position = i... |
a8014a30282bab8f7c40e400e1a950afe0b14ebf | pau1fang/learning_notes | /数据结构与算法/DataStructures/chapter03/汉诺塔.py | 328 | 3.703125 | 4 | def moveTower(height, fromPole, toPole, withPole):
if height>=1:
moveTower(height-1, fromPole, withPole, toPole)
moveDisk(fromPole, toPole)
moveTower(height-1, withPole, toPole, fromPole)
def moveDisk(fp, tp):
print(f'moving : {fp} -----> {tp}')
moveTower(3,"最初塔","目标塔","中间塔") |
82f361fc9231541a923a2c071e14c9b8e6780f88 | cnagadya/bc_16_codelab | /Day_three/wordcount.py | 599 | 4.1875 | 4 | """ words function to determine the number of times a word occurs in a string"""
def words(input_string):
#dictionary template to display words as keys and occurances as values
words_dict = {}
#splitting string into list to enable iteration
words_list = input_string.split()
#iterate through the list to... |
702dea7b0fd8e61aa5be1bb862f3e9e60236e2e0 | suntzualex/rover_challenge | /perception.py | 10,389 | 3.53125 | 4 | import numpy as np
import cv2
# Identify pixels above the threshold
# Threshold of RGB > 160 does a nice job of identifying ground pixels only
def color_thresh(img, rgb_thresh=(160, 160, 160)):
# Create an array of zeros same xy size as img, but single channel
color_select = np.zeros_like(img[:,:,0])
... |
5f062450807dcfd7b3215941ce63883ac18021bd | NoelTautges/advent-of-code-2020 | /02-password-policy.py | 741 | 3.625 | 4 | #!/usr/bin/env python3
def main():
range_valid = 0
position_valid = 0
with open("02.txt") as passwords:
for line in passwords:
values, letter, password = line.strip().split(" ")
first, second = [int(val) for val in values.split("-")]
letter = letter[0]
... |
40a93421a49f035b34efded0098111b22703e1ba | NoelTautges/advent-of-code-2020 | /08-infinite-loop.py | 1,022 | 3.59375 | 4 | #!/usr/bin/env python3
from collections import defaultdict
def run_instructions(instructions):
i = 0
run = set()
acc = 0
while i not in run and i < len(instructions):
run.add(i)
ins, num = instructions[i]
i += num if ins == "jmp" else 1
acc += num if ins == "acc" else... |
f8a6f73c71addd00234e620f141aabd2fd275683 | kathryn-rowe/Udemy_Py-Data-Structures | /Array_Practice/sent_rev.py | 1,297 | 3.875 | 4 | def rev_sent(sent):
"""Given a string of words, reverse all the words.
>>> rev_sent('This is the best')
'best the is This'
>>> rev_sent(' space here' and 'space here ')
'here space'
"""
sent = sent.split(" ")
open_sent = ""
for word in sent[::-1]:
open_sent = open... |
1797340623026198a04a67ebbcf0f603532a5794 | kathryn-rowe/Udemy_Py-Data-Structures | /Stack-Queue_Practice/balance_paren.py | 2,600 | 4.09375 | 4 | def balance_paren(s):
"""Given a string of opening and closing parentheses, check whether it is balanced."""
if s == "":
return ""
if len(s) % 2 != 0:
return False
# create stack for each symbol
parens = []
brackets = []
curly = []
for item in s:
if item == "(... |
296146e5ea5c1303e377534b3a2a10f544090712 | kathryn-rowe/Udemy_Py-Data-Structures | /Trees_Graphs/BST_search_find.py | 2,246 | 4.03125 | 4 | # Build a binary search tree
class TreeNode(object):
def __init__(self, data, left=None, right=None, parent=None):
self.data = data
self.left = left
self.right = right
self.parent = parent
def __repr__(self):
"""Debugging-friendly representation."""
return "<Bi... |
e3170a6329a9c59e1012f30ae1fd355193cdd64c | ClaudiaLLX/tester | /testing/test_pytest_1.py | 1,500 | 3.859375 | 4 |
from python.calc import Calc
import math
class TestCalc:
def setup(self):
self.calc = Calc()
def test_add_1(self):
num = self.calc.add(1, 2)
print(num)
assert 3 == num
def test_add_2(self):
num = self.calc.add(-1, -2)
print(num)
assert -3 == num
... |
8017fa6c3427f2fd92f5ac9409ea63d78e7ef6f2 | ksu-is/video-poker-tutor | /Source 2/deck.py | 1,166 | 3.6875 | 4 | import random
from card import Card
class Deck():
def __init__(self, exclude=None):
self.cards = []
cards_list = []
for suit in ['H', 'D', 'S', 'C']:
for rank in ['2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K', 'A']:
cards_list.append(rank+suit)
... |
9e3efa90309eb631a8d4fd8c892ca14c71db7c6a | saeedsaeedj/python-class | /ex10_1.py | 339 | 3.5 | 4 | import numpy as np
import matplotlib.pyplot as plt
x=2
i=x**2
x=np.arange(0,2*np.pi,0.1)
y=np.sin(x)
z=np.cos(x)
if (np.sin(90)==1):
print('darage ast')
else:
print('radiyan ast')
plt.plot(y)
plt.plot(z)
q=np.linspace(-1,1,num=500)
print(q)
print(q[53])
plt.figure()
plt.plot(np.sin(2*np.pi*... |
b655020a54886c4249132e7f433283cd0bba2650 | saeedsaeedj/python-class | /045.py | 119 | 4.0625 | 4 | #45
s=0
while (s<=50):
x=int(input('please enter your number : ')
s=x+s
print ('total is over 50')
|
3ba5adf3dfceea19a2d84aa3e983951341f10e92 | elvisasante323/code-katas | /python_code/regex.py | 515 | 4.4375 | 4 | # Learning about regex
import re
# Search the string to see if it starts with 'The' and ends with 'Spain'
text = 'The rain in Spain'
expression = re.search('^The.*Spain$', text)
if expression:
print('We have a match!\n')
else:
print('There is no match!\n')
# Find all lower case characters alphabetically betw... |
c832e0c70807081aa70e37f32a67ea1e2c59dca7 | yash-agrawal20/Python-Project | /Quiz_Game/quiz-game-start/quiz_brain.py | 1,057 | 3.921875 | 4 | #asking the questions
#checking if the answer was correct
#checking if we are at the end of the quiz
class QuizBrain:
def __init__ (self, q_bank):
self.question_number = 0
self.score = 0
self.question_list = q_bank
#method
def still_has_questions(self):
if self.questio... |
d209aca5d752ee6aba0b6a1e120d363951a5fbf7 | yash-agrawal20/Python-Project | /Black_Jack_Game/main.py | 2,708 | 4.09375 | 4 | ############### Blackjack Project #####################
############### Our Blackjack House Rules #####################
## The deck is unlimited in size.
## There are no jokers.
## The Jack/Queen/King all count as 10.
## The the Ace can count as 11 or 1.
## Use the following list as the deck of cards:
## cards = [11... |
149ad71e35c7ec02255033543e951b4534d62375 | Luisa158/LaboratorioRepeticionRemoto | /mayor.py | 385 | 3.6875 | 4 |
positivos=0
negativos=0
ceros=0
i=0
for i in range(0,11):
a=int(input("Introduzca un valor: "))
if a==0:
print (a)
ceros=ceros+1
elif a>0:
print(a)
positivos=positivos+1
else:
print(a)
negativos=negativos+1
print("los positivos son: ", positivos)
print(... |
bdb6cf75b2adcaf9d8fb65760bbe2707bec03ece | dderking/funnyAlgorithms | /PrintMatriz/JustificadoADireitaLinha.py | 525 | 3.6875 | 4 | #O primeiro argumento recebe uma lista e o segundo um inteiro com o tamanho que cada valor da lista vai ficar.
def JustificadoDireitaLinha(lista, t):
final = ""
for i in range(len(lista)):
if i == 0:
final += "%*s" %(t, str(lista[i]))
else:
final += "%*s" %(t+1, st... |
5184153b70a2c81b6a4efdaa6eb107b2289f94d0 | Joshua-C-Bryant/python-exercises | /function_exercises.py | 7,252 | 4.09375 | 4 | # 1
# Define a function named is_two.
# It should accept one input and return True if the passed input is either the number or
# the string 2, False otherwise.
# function accepts one input and return True if the passed input is either the number or
# the string 2, False otherwise.
def is_two(n):
# checks to see... |
c86c6efda326ce2efee29b99423b2202b81e62f9 | kevinelstri/kaggle_Titanic | /Getting_Started_With_Python.py | 2,077 | 3.78125 | 4 | # -*-coding:utf-8-*-
######################
# by kevinelstri
# 数据集:train.csv
# Getting Started With Python
######################
import csv as csv
import numpy as np
######################
# Titanic
######################
# ---------------------
# csv 读取csv文件,并转换成矩阵形式
# ---------------------
csv_file_o... |
215950378bbcd2f020be5ebfb49cd5c7b5a9aa07 | cgisala/Capstone-Intro | /Lab1/Part2:_list_of_classes.py | 432 | 4.21875 | 4 | #Variable
choice = 'y' #Initializes choice to y
classes = [] #Declares an empty array
#Loops until the user enters 'n' for no
while(choice == 'y'):
semesterClass = input("Enter a class you are taking this semester: ")
classes.append(semesterClass)
choice = input("Do you want to add more y or n: ")
pri... |
c3495f7dac153764fdc1ce63c88bcde0ae6b05e3 | cgisala/Capstone-Intro | /List_Comprehensions.py | 157 | 3.8125 | 4 | strings = ['pizza', 'Beyonce', 'cat']
lengths = []
for string in strings:
length = len(string)
lengths.append(length)
print(f'lengths: {lengths}')
|
ac9b1df2921614d3fc1845fe8b52ce65ca53e13f | baallezx/rsp | /devtest/q1/1.py | 1,245 | 3.8125 | 4 | import math
def _get_distance(vec_a, vec_b):
return math.sqrt( ( vec_b[0] - vec_a[0] ) ** 2 + (vec_b[1] - vec_a[1]) ** 2 )
def get_points(vec_a, vec_b):
"""
return the points that intersect
"""
# a = (r02 - r12 + d2 ) / (2 d)
distance = _get_distance( vec_a, vec_b )
try:
# a = (r02 - r12 + d2 ) / (2 d)
a = ... |
ad9431376cb21d18ca9d6fa272bd7ea4ae01572f | BrunoAlz/design-patterns-python-master | /structural/adapter/adapter_1.py | 2,244 | 4.28125 | 4 | """
Adapter é um padrão de projeto estrutural que
tem a intenção de permitir que duas classes
que seriam incompatíveis trabalhem em conjunto
através de um "adaptador".
"""
from abc import ABC, abstractmethod
class IControl(ABC):
@abstractmethod
def top(self) -> None: pass
@abstractmethod
def right(se... |
972c11fb7b7ed641e65d1038bc92f5e777aaa5ca | BrunoAlz/design-patterns-python-master | /behavioral/strategy/strategy_1.py | 2,073 | 4.1875 | 4 | """
Strategy é um padrão de projeto comportamental que tem
a intenção de definir uma família de algoritmos,
encapsular cada uma delas e torná-las intercambiáveis.
Strategy permite que o algorítmo varie independentemente
dos clientes que o utilizam.
Princípio do aberto/fechado (Open/closed principle)
Entidades devem se... |
f494a23aa5ae7dd8e7f87e521fad4779e62c5118 | BrunoAlz/design-patterns-python-master | /behavioral/template_method/template_method_2.py | 1,909 | 4.3125 | 4 | """
Template Method (comportamental) tem a intenção de definir
um algoritmo em um método, postergando alguns passos
para as subclasses por herança. Template method permite
que subclasses redefinam certos passos de um algoritmo
sem mudar a estrutura do mesmo.
Também é possível definir hooks para que as subclasses
utili... |
43718615b775e7fb9d9fc1ce59befa7ecde6b57c | BrunoAlz/design-patterns-python-master | /structural/composite/composite.py | 2,923 | 3.984375 | 4 | """
Composite é um padrão de projeto estrutural que permite que
você utilize a composição para criar objetos em estruturas
de árvores. O padrão permite aos clientes tratarem de maneira
uniforme objetos individuais (Leaf) e composições de
objetos (Composite).
IMPORTANTE: só aplique este padrão em uma estrutura que poss... |
8a7a4d5be8010b2198b3fc212d2660a98edfb977 | evanrushton/project-euler | /primeFactorGraph.py | 6,255 | 3.796875 | 4 | from primeSieve import *
# import math
import random
import time
import matplotlib.pyplot as plt
import numpy as np
# GLOBAL VARS
primes = []
integer = 0
# Arrays to store (int, time) pairs for each algorithm
brute_div = []
brute_no_div = []
recurse_set_div = []
recurse_set_no_div = []
recurse_list_div = []
recurse_lis... |
f411a7dc7b60fd417559979832c565d8cf075f87 | evanrushton/project-euler | /p41.py | 721 | 3.5625 | 4 | from primeSieve import *
import itertools
digits = [9, 8, 7, 6, 5, 4, 3, 2, 1]
# create ordered list of 9-digit pandigitals
# 9 + permutations of 87654321 and first that isPrime is solution
def pandigitize(nums):
pans = []
start = nums[0]
end = nums[1:len(nums)]
perms = itertools.permutations(end)
for p in pe... |
7f289631c24b6bb0f0e3da7fdeeba3bfe28aaa04 | evanrushton/project-euler | /p53.py | 341 | 3.578125 | 4 | import itertools as it
import math
def combinations(n, r):
return math.factorial(n)/(math.factorial(r) * math.factorial(n-r))
# TESTS
nCr = 0
count = 0
for n in xrange(1,101):
for r in xrange(2,n-1):
nCr = combinations(n, r)
if nCr > 10 ** 6:
count += 1
print "{}, {}".format(n, r), combinatio... |
a5c58a83a940d7e62bc3b57d0b1ba1c41470a460 | evanrushton/project-euler | /p03.py | 672 | 3.53125 | 4 | import math
input_value = int(input("Enter value for n"))
sieve_max = 5000000
# max_range = int(math.ceil(math.sqrt(input_value)) + 1)
max_range = int(math.ceil(math.sqrt(sieve_max)) + 1)
primes =[]
factors =[]
value = input_value
sieve = [True] * sieve_max # sieve[n] returns true if n is prime
for i in range(2, max... |
4c385a8cf6661153f48eb21cfd73f8961541c244 | evanrushton/project-euler | /p29.py | 165 | 3.671875 | 4 | powers = []
for a in range(2, 101):
for b in range (2, 101):
term = a ** b
if term not in powers:
powers.append(term)
print powers
print len(powers)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.