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
a211d40579771d929d02a4017ca56f91b9b884c0
Eddie02582/CodeWars
/Kata 6/IP Validation/IP Validation.py
758
3.53125
4
def is_valid_IP(s): return s.count('.')==3 and all(o.isdigit() and 0<=int(o)<=255 and str(int(o))==o for o in s.split('.')) import re def is_valid_IP(strng): match=re.match(r"^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$",strng) if match: return all (str(int(n))==n and 0<=int(n)<=255 for n in match[0...
23980fc700955f1089500d02e15ae5a164b45936
Eddie02582/CodeWars
/Kata 4/Strings Mix/Strings Mix.py
709
3.53125
4
def mix(s1, s2): word=sorted(list(set(s1+s2))) msgs=[] for x in word: if ord('a')<= ord(x)<= ord('z') : s1_count=s1.count(x) s2_count=s2.count(x) max_count=max(s1_count,s2_count) if max_count >1: if s1_count>s2_count: ...
6983e30dd432c483ea564c165cd5ebddfc651581
LadaOndris/IPP-project
/interpret/frame.py
1,028
3.78125
4
from .return_codes import * """ The Frame class represents a container for a frame. The frame contains variables that can be worked with. """ class Frame: def __init__(self): self.variables = {} """ Adds a new variable to the frame. Raises an exception if the frame contains a...
4aa4af15fb30bb3d98da33a97190f8f577344d53
damayantinaik/Git-github_features_testing
/sorting_words.py
409
3.75
4
fname = input("Enter file name: ") fh = open(fname) lst = list() for line in fh: line = line.rstrip() words = line.split() for word in words: if word in lst: continue lst.append(word) lst.sort() print(lst[ :11]) print("Switch between branch, now I am in test branch") Pri...
f2f0dc7da7f646a4b647c49cef1810a3c73fb6d6
caged9/lrn-py
/1 half/Lesson 4/task_6.py
974
4.25
4
#В программе генерируется случайное целое число от 0 до 100. #Пользователь должен его отгадать не более чем за 10 попыток. После #каждой неудачной попытки должно сообщаться, больше или меньше #введенное пользователем число, чем то, что загадано. Если за 10 попыток #число не отгадано, вывести ответ import random p...
111d2814ccefb468c7c62abcf08708365d551426
caged9/lrn-py
/1 half/Lesson 3/task_1.py
626
4.125
4
#Выполнить логические побитовые операции «И», «ИЛИ» и др. над двумя #введенными пользователем числами. Выполнить над одним из введенных #чисел побитовый сдвиг вправо и влево на два знака a=int(input('Type a: ')) b=int(input('Type b: ')) print(a, ' = ', bin(a)) print(b, ' = ', bin(b)) print('a & b = ', a & b, '('...
6395d40c5c45e96234e092d1ed0406f0ed439a2c
adskevin/algoritmos2-2018-2
/Aula03/exercicio1/exercicio1.py
676
3.921875
4
"""Exercicio de colisao.""" def teste(ponto, retang): """Testa se ponto está dentro de retangulo.""" dimension = [0, 0] # print(retang[2], retang[3]) dimension[0] = retang[2] dimension[1] = retang[3] x = retang[0] y = retang[1] isIn = False while x < retang[0]+dimension[0]: ...
a895c6e9b65f5f1f0c82f65353e222074aaf1544
adskevin/algoritmos2-2018-2
/Avaliacao/Questao4/Prog.py
6,047
3.796875
4
"""Cria um rebatedor e retangulos que somem ao serem tocados por uma bola.""" from Rebatedor import rebatedor from Retangulo import retangulo from Bola import bola import random import pygame red = (255, 0, 0) green = (0, 255, 0) blue = (0, 0, 255) darkBlue = (0, 0, 128) white = (255, 255, 255) black = (0, 0, 0) pink...
5f6fd6ff884e7e9d24960d098b828850da8f95c6
Morgenrode/Euler
/prob6.py
272
3.75
4
'''prob6.py: find the difference between the sum of the squares of the first 100 natural numbers and the square of the sum''' sum_of_squares = sum([x ** 2 for x in range(1,101)]) square_of_sum = (sum([x for x in range(1,101)]))**2 print(sum_of_squares - square_of_sum)
531470e218f42e9f88b95968c05469ffd5e81554
Morgenrode/Euler
/prob4.py
725
4.1875
4
'''prob4.py: find the largest palidrome made from the product of two 3-digit numbers''' def isPalindrome(num): '''Test a string version of a number for palindromicity''' number = str(num) return number[::-1] == number def search(): '''Search through all combinations of products of ...
582118ddffffb55e6b40c94d1ebe5bc5065dcde6
KARSARANG/Sarang_Master_Talks
/Service2.py
4,957
4.15625
4
def displayEnggGoal(): Engggoal1="Innovation distinguishes between a leader and a follower.Do you\nA.agree, have an innovative thought(s) and enthusiastic to work on it\nB.agree, but like to have a routine life\nC.agree, but reluctant to exhibit as if what others might think\nD.agree, but never got encouragement f...
e86f88014bf14b7534ce8f52e5547fc1021742bb
Phil-D-Smith/neural-network
/neural_network.py
2,550
3.609375
4
import csv import os import numpy as np #set number digits after decimal point float_formatter = lambda x: "%.5f" % x np.set_printoptions(formatter = {'float_kind':float_formatter}) #sigmoid acrtivation function and derivate of sigmoid function def sigmoid(x, deriv = False): #derivative of sigmoid is x/1-x if(deri...
f4c6c7f622d77f355aee148cd166d10f0932d1a7
gentle-potato/Python
/08_list/list6_index.py
165
3.953125
4
# index() 메소드 a = [3, 6, 0, -4 ,1] b = a.index(3) # 없으면 에러 print(b) # in / not in if 2 not in a : print('Not exist') else : print('Exist')
d33c75bad768ead959783206677d47b5e37ce54d
gentle-potato/Python
/09_tuple/tuple.py
2,464
4
4
# 집합적 자료형 : tuple # 삭제, 변경, 추가 작업 불가 # 리스트 생성 : list() or [] # tuple 생성 : tuple() or () t1 = tuple() t2 = () t1 = (1, 2, 3) print(t1) print(type(t1)) t2 = 1, 3, 4 print(t2) t3 = t1, (5, 6, 7) print(t3) t4 = [1, 4], [5, 6] print(t4) t5 = tuple([1, 4]) # list -> tuple print(t5) # 튜플의 요소 다루기 # 요소 변경 불가 print(t1[2...
350a878652f28c761f76014dae0a6c315a441cae
gentle-potato/Python
/05_for/for_ex4.py
489
3.9375
4
# 이름 리스트에 해당하는 이름이 있는 경우 이름이 있음을 출력한다. names = ['홍길동', '이몽룡', '성춘향', '변학도'] inputName = input('이름 입력 : ') for name in names : if inputName == name : flag = True break # 반복문 탈출(종료) else : flag = False if flag == True : # True 없이 if flag : 만 입력해도 똑같음 print('명단에 있습니다.') else : ...
ea8ed328fc4be5c420d3f5e5cee9d5507a72f950
gentle-potato/Python
/18_OOP/05_클래스 상속.py
2,249
4.09375
4
# 클래스 상속(inheritance) class Car: number = 0 # 클래스 변수 num : 클래스 안에서 모든 인수들이 공유하는 변수 def __init__(self, speed=0, color='white'): self.color = color # 클래스 내에서만 사용하는 비공개 필드 self.speed = speed Car.number += 1 # 클래스 이름(Car)으로 def __str__(self): return '이 자동차의 색상은 %s이고,\n속도는 ...
4ddf3b37ca60615998a7091ffb6fddc762b89ccd
gentle-potato/Python
/06_while/while2_continue&break.py
383
3.921875
4
# continue문 : 조건이 참일 경우 반복문 계속 수행 x = 0 while x < 10 : x += 1 if x % 2 == 0 : # 짝수 continue print(x) # 무한 반복(Loop) # break문 : 조건이 참일 경우 반복문 종료 print('반복 시작') while True : answer = input('종료하려면 x 입력 : ') if answer == 'x' : break print('반복 종료')
02e71dff4f75261305d371b5191dd7cc04743bdb
gentle-potato/Python
/12_function/function1.py
818
3.828125
4
# 함수의 개요 # 함수 정의 def printHello() : print('Hello') def printName(name) : print(name) def area_square(width, height) : area = width * height return area # 함수 호출 printHello() printName('Lee') w = 10 h = 20 area = area_square(w, h) print(area) # 연습문제 def show_info() : print(f'{my_name}\n{my_age}...
dff23212b0e1df834c288cae140696f2ee7048ae
gentle-potato/Python
/04_if/if_ex2.py
337
4
4
# 입력한 정수가 양수, 음수, 0인 경우 number = int(input('정수 입력 : ')) if(number > 0) : print('양수') else : if(number < 0) : print('음수') else : print('0') # 또는 elif를 사용하여 if number > 0 : print('양수') elif number < 0 : print('음수') else : print('0')
a84797d3afa18f16b951c866278c34ccbe90feea
gentle-potato/Python
/05_for/for_ex3.py
1,731
3.921875
4
# 리스트에 저장되어 있는 성적에 따라 합격/불합격을 판별하시오. # 성적이 60점 이상이면 합격, 아니면 불합격 처리하시오. # 출력 양식 : 리스트 저장 순서에 따라 print('# 예시') scores = [90, 57, 88, 45, 78] num = 0 for score in scores : num += 1 if score >= 60 : result = '합격' else : result = '불합격' print('%d번 %d점 %s' % (num, score, result)) # =========...
d639321848b8b7d3d319aa635c7d8a91a45894af
gentle-potato/Python
/08_list/list4.py
1,368
3.671875
4
# 리스트의 일치 검사 list1 = [1, 2, 4] list2 = [2, 1, 3] # ==, !=, >, < print(list1 == list2) print(list1 != list2) print(list1 > list2) # 2차원 리스트 list3 = [[1, 2, 3, 0], [4, 5, 6, 1], [7, 8, 9, 6]] list4 = [[1, 2, 3], [1, 2], [1, 3, 4, 5]] print(list3) for i in list3 : print(i) for i in list4 : for j in i : ...
61c20ce32e0665cb8f6389e54e5044b46a9a4ba5
kregerator/Timer
/timer_one_big_script.py
764
3.671875
4
# Simple script to act as a timer in the terminal import datetime # build functions here def display_help(): print "s: start" print "p: stop" print "r: refresh" print "q: quit" print "?: show help" # main program var = 1 while var == 1: com = raw_input("Command: ") if com == 's': start_time = datetime.date...
18ad61fdcd1e71d6dd18ff18e293f6c81cfffb07
william-carvalho12/Curso-Python-FATEC
/decisao2.py
202
4.09375
4
idade = int(input("Digite o sua idade: ")) if (idade == 18): print("Você tem 18 anos!") elif (idade < 18): print("Você tem menos de 18 anos!") else: print("Você tem mais de 18 anos!")
1d420217bb5a4f41911ebeb62a60aae8b95752ff
acheimann/PythonProgramming
/Book_Programs/Ch2/futval.py
763
4.0625
4
#futval.py #A program to compute the value of an investment #carried 10 years into the future def main(): print "This program calculates the future value" print "of a ten-year investment." principal = input("Enter the initial principal: ") apr = input("Enter the annual interest rate: ") period...
166ed8b161017285f5fe6c52e76d8a985b6ba903
acheimann/PythonProgramming
/Book_Programs/Ch1/chaos.py
553
4.46875
4
# File: chaos.py # A simple program illustrating chaotic behavior. #Currently incomplete: advanced exercise 1.6 #Exericse 1.6 is to return values for two numbers displayed in side-by-side columns def main(): print "This program illustrates a chaotic function" x = input("Enter a number between 0 and 1: ") ...
1262c1d720d1a6d51261e0eb5ca739abe7545254
acheimann/PythonProgramming
/Book_Programs/Ch3/sum_series.py
461
4.25
4
#sum_series.py #A program to sum a series of natural numbers entered by the user def main(): print "This program sums a series of natural numbers entered by the user." print total = 0 n = input("Please enter how many numbers you wish to sum: ") for i in range(n): number = input("Ple...
431a0f0002427aa49f2cb3c4df8fb0fd3a6fa2ba
acheimann/PythonProgramming
/Book_Programs/Ch2/convert_km2mi.py
391
4.5
4
#convert_km2mi.py #A program to convert measurements in kilometers to miles #author: Alex Heimann def main(): print "This program converts measurements in kilometers to miles." km_distance = input("Enter the distance in kilometers that you wish to convert: ") mile_equivalent = km_distance * 0.62 print ...
1f58bb6b192ef3993a58b870f16d4c4329e4ea74
amjith/Cows_and_Bulls-Game
/cab.py
2,374
3.921875
4
#!/usr/bin/env python from random import randint; def check_chars(inp, actual): bull =0 cow =0 if not inp.isalpha(): print "Only alphabets are allowed\n" return (cow,bull) if len(inp) != len(actual): print "Input string must be %d chars\nTry again" %len(actual) ...
51d9fc444f6b810d59ac83653515553fabc28052
superpavelka/Python-basics
/py_tasks-4/py_tasks-4-1.py
545
3.96875
4
def get_str(name_, age_, city_): return name +', ' + age +', год(а), проживает в городе ' + city name = input('Введите имя: ') while True: age = input('Введите возраст: ') try: if int(age) < 0 or int(age) > 200: print('Ошибка ввода возраста!') else: break except...
a923de1a6e525028e8107360c39cfb391c86430f
superpavelka/Python-basics
/py_tasks-8/8/game.py
1,729
3.84375
4
import random def guess_the_number(): print('Загадайте число от 0 до 100 в уме и/или напишите его на бумаге') user_input = '<' number_min = 0 number_max = 100 incorrect_input = False is_winner = False count = 1 while not is_winner: if (number_min == number_max): p...
84104a65e5ca0693fc1b930ee08a0119bc3262e4
igor-korolev/algo
/graph/breadth_first_search.py
1,910
4.09375
4
"""Breadth first search implemented in python.""" from collections import deque def bfs(graph, start_from, searchable): """ Search for the shortest way of graph using deque. :param list graph: List of lists(adjacency matrix), that represents the graph. :param int start_from: Starting vertex. Search ...
ae9aba16ab6ca2855b287757c8e365057802d3e9
Neos-codes/LoFi-Gen
/generation/music_elements.py
7,237
3.65625
4
import random from utils import shuffled # local module # standar durations of notes NOTE_DURATIONS = [0.5, 1, 2] # The shortest note's duration MINIMAL_DURATION = 0.5 class Note(): ''' Note in MIDI ''' def __init__(self, tone=60, duration=1): self.tone = tone self.duration = duration d...
23c7fda618fa6321fe8cc8375ec574e3e597c753
jianzhnie/learnc
/Programming-Ability-Test/PATeasy2/easy11.py
202
3.59375
4
strN = str(input()) strdict ={} for s in strN: if s not in strdict: strdict[s]=1 else: strdict[s]+=1 for key in sorted(strdict.keys()): print(str(key)+":"+str(strdict[key]))
99829c2f612377d3ffe68d6a9d889ae3ddc371bb
sharkdeng/MY-leetcode
/app/src/main/java/com/anu/game/JZ50/Solution.py
374
3.53125
4
# -*- coding:utf-8 -*- class Solution: # 这里要特别注意~找到任意重复的一个值并赋值到duplication[0] # 函数返回True/False def duplicate(self, numbers, duplication): # write code here for n in numbers: if numbers.count(n) > 1: duplication[0] = n return True return Fa...
a54ded932bddc8caaaa2d963bb8d69d626072e44
sharkdeng/MY-leetcode
/app/src/main/java/com/anu/game/JZ59/a.py
2,196
3.96875
4
class TreeNode: def __init__(self, val): self.val = val self.left = None self.right = None def add(self, val): if val < self.val: if self.left is None: self.left = TreeNode(val) else: self.left.add(va...
dbf5952742bf7acb180ac858a0f663fa63c940a0
lyphilong/CS50x
/CS50's Introduction to Computer Science/Week 6 Python/hello/hello.py
77
3.671875
4
import cs50 string = input("What 's your name?\n") print(f"hello, {string}")
8e4c605d367d4498849d46b640bed1254f2207f6
Marlon-Camacho/Python-Curses
/secondtwoexercise.py
298
3.5
4
fname = input("Enter file name: ") fh = open(fname) count = 0.0 nume = 0.0 for line in fh: if not line.startswith("X-DSPAM-Confidence:") : continue num = float(line[19:]) count = count + 1.0 nume = nume + num result = nume/count print("Average spam confidence: "+str(result))
45b4cf3fd7e165e8c741d80694e34fe248e48780
va4oz/python_learning
/if_else.py
237
4.125
4
# -*- coding: utf-8 -*- a = 12 if a == 12: print("Верно") b = 13 if b == 12: print("верно") else: print("не верно") c = 5 if c < 2 or c > 3: print("не верно") elif c == 2: print("верно")
5e5a6e7cd0bb8e78e3a9e9665e36ef412e7229a4
nismod/smif
/src/smif/metadata/coordinates.py
4,445
4.1875
4
"""Each dimension of a multi-dimensional dataset can be indexed by a set of coordinates. Dimensions might be represented as Euclidean coordinates over a grid:: >>> x = Coordinates('x', range(0, 100)) >>> y = Coordinates('y', range(0, 100)) A subset of Local Authority Districts in England would be a region-ba...
20c671b1eec6c84a8f98ff00fd213fbbb33a9676
C-CCM-TC1028-102-2113/tarea-4-melylugo
/assignments/17NCuadradoMayor/src/exercise.py
230
3.859375
4
def main(): #Escribe tu código debajo de esta línea num=int(input("Escribe un numero : ")) acum=1 while (acum**2)<=num: acum=acum+1 print (acum) pass if __name__=='__main__': main()
34dcd74ea9a7f1f0d408a91e1ff06414da356af4
stefanrsathianathen/Poker
/tests/test_core.py
1,057
3.5
4
import unittest import context from core import core class TestCore(unittest.TestCase): def test_card(self): card = core.Card(("♠","s"), 1) self.assertEqual(card.value, 1) self.assertEqual(card.suit, ("♠","s")) def test_deck_length(self): deck = core.Deck() self.assert...
798d8eed90b0fe56dfb25927e917d74ec61335c7
thippo/Statistics_Python_Lib
/statspylib/ParameterEstimation/DetermineSampleSize.py
1,324
3.671875
4
import scipy.stats from .. import tools ''' 确定样本量(总体必须是正态分布) determine_population_mean_sample_size(population_standard_deviation,confidence_level,estimate_error) determine_population_proportion_sample_size(population_proportion,confidence_level,estimate_error) ''' def determine_population_mean_sample_size(population_...
ffcc02c0f9a0db8712910b31c3f430c52e9db4b5
rutgerfarry/cs325
/assignment1/enhanceddnc.py
2,759
3.734375
4
"""Determines the closest set of points from a file passed as a command line argument using a divide and conquer algorithm""" from sys import argv from shared import point_list_from_file, write_to_file, format_output, Point def enhanced_closest_pair_dnc(x_sorted_points, y_sorted_points): # Recursive cases if ...
3aa2246691fd1a71c218e8012aa43e7cdce07129
rutgerfarry/cs325
/assignment1/shared.py
1,244
3.921875
4
import math class Point(object): def __init__(self, x=0, y=0): self.x = x self.y = y def __str__(self): return "({0}, {1})".format(self.x, self.y) def __repr__(self): return "({0}, {1})".format(self.x, self.y) @staticmethod def distance(point1, point2): re...
a798f0655f66cc4ad9bf185697fda90895090f13
kiwifairy/Algorithm
/PrinciplesofComputing/7-FiftennPuzzle.py
20,489
3.578125
4
""" Loyd's Fifteen puzzle - solver and visualizer Note that solved configuration has the blank (zero) tile in upper left Use the arrows key to swap this tile with its neighbors http://www.codeskulptor.org/#user37_SFNzf37PYJ_187.py """ import poc_fifteen_gui class Puzzle: """ Class representation for the Fifte...
d5b3ecc6b890911755892eaa61cfe1aceefe0b78
Valeriy2013/PythonCourse
/Begginer/2_conditions.py
517
4.09375
4
number = int(input("What is your age? ")) # between 0 and 150 if number < 0 or number > 150: print("Not possible age!") # between 0 and 149 if number not in range(0, 150): print("Range check not passed") else: print("Passed check! Age: " + str(number)) if number <= 12: print("Child age: " + s...
1e190815b25b0c6b733b0472382cc87a78c5a74b
akrishna1995/emuedge
/bin/utils/topo.py
676
3.71875
4
import json # use adjacency list for representing network would be intuitive for human class topo: def __init__(self): self.graph=[] @staticmethod def read_from_json(filename): raw=open(filename).read() jdata=json.loads(raw) nodes=[] # init graph based on how many nodes we have node_count=len(jdata) ...
1f521f304e81cf003142d96786d3b944dd83abbf
rizkiulia/Python-List-and-Dictionary
/List Manipulation.py
128
3.609375
4
a = [ [5, 9, 8], [0, 0, 6] ] # change list value b = a[0] b[2] = 10 # change list value c = a[1] c[0] = 11 print(a)
76bbd9a65ec9214154ce205982bbcca07f7d6b06
harupapa-git001/Python
/PythonLibrary/SamplePy/SetType.py
3,636
4.125
4
type(set()) print(type) s = {"nya", "wan", "piyo", "chun"} s print(s)# s = set([1, False, "nya", "wan"]) s print(s)# s = set("nya") s print(s)# ''' 集合型集合はリストやタプルのように複数の要素をまとめて扱いますが、辞書のようにミュータブルで順序の概念がありません。 そして集合には「重複した要素を持たない」と言う特徴があります。 集合型のデータは波括弧({})の中に値をカンマで区切って指定するか、"set"と言う関数...
25f3f64f9415d8d0ae96e6437e67adf167a79107
harupapa-git001/Python
/PythonLibrary/SamplePy/UserInfo.py
346
3.78125
4
class UserInfo: def __init__(self, name, birth, address): print("initialize instance")#コンストラクタで初期化 self.name = None self.birth = 0 self.address = None '''taro = UserInfo() #ex1 ''' taro = UserInfo("taro", 1980, "tokyo") print(taro.name) print(taro.birth) print(taro.addres...
bc97d1db5ddcb6fc565d33ec616de361b119c5f9
harupapa-git001/Python
/PythonLibrary/SamplePy/RegularExpression.py
2,050
3.671875
4
import re #match #文字列の先頭のみ対象となる #group()はマッチした値を取得するメソッド pattern = "nya" text = "nya-nya-" res = re.match(pattern, text) print("[match()の実行結果]") print(res.group()) #search #最初にマッチした部分のみが対象となる #span()はマッチした箇所の開始位置と終了位置をタプルで取得するメソッド #group()はmatchと同様 res = re.search(pattern, text) print("\n[search()の実行結果]") print(res...
cec72b6df11da2df03451c829046c99e117b7058
harupapa-git001/Python
/PythonLibrary/SamplePy/ExtendingTheFramework.py
3,396
4.21875
4
#フレームワーク(手を加えない) class Calc: #初期化でカスタマイズ用の関数定義を受け取り登録 def __init__(self, operation_list): self.operation_dict = {} for operation_tuple in operation_list: (operation, method) = operation_tuple self.operation_dict[operation] = method #イベントドリブンで電卓...
49c7b044d509fa692d1676deb5dcc4134867d9af
harupapa-git001/Python
/PythonLibrary/SamplePy/ObjectReference.py
1,051
4.0625
4
a = [1, 2, 3] b = a a.append(4) print("a: " + str(a)) print("b: " + str(b)) ''' リストのオブジェクトに対して appendメソッドを呼び出すと、リストの末尾に要素を追加することができます。 appendしたあとの print出力を見ると変数 aに格納されているリストオブジェクトのデータがアップデートされています。 そして変数bに格納されているリストオブジェクトは変数aのものと同じなので、変数b自体に対しては操作をしていないのに中身が変わっていることがわかります。 変数に対する操作は変数が格納しているオブジェクトに...
6da75c58310747ecefca9a9e31c2e2171023f739
harupapa-git001/Python
/PythonLibrary/SamplePy/DataManipulationWithFunctions.py
1,845
4.0625
4
'''ex1 #フィルタ処理 def is_even(x): return x % 2 == 0 filter_object = filter(is_even, range(10)) print(list(filter_object)) ''' ''' Pythonの filter関数は第一引数に関数を受け取り、第二引数にリストを受け取ります。 渡された関数をリストの各要素に適用し、Trueとなった要素だけから構成されたフィルターオブジェクトを返します。 必要であればリスト型にキャストをします。filterという名前が示す通り、リストをフィルタ処理しています。 上記...
6ed6adba62bf6e04045948ff91e73cc38f4ec0d8
harupapa-git001/Python
/PythonLibrary/SamplePy/TernaryOperator.py
251
4
4
''' a = 5 if(a % 2 == 0): is_even = True else: is_even = False print(is_even) ''' a = 5 #(Trueの時に返る値) if(条件式) else(Falseの時に返る値) is_even = True if(a % 2 == 0) else False print(is_even)
49f2226860978022d578fd7451a3638e5e8daa2b
harupapa-git001/Python
/PythonLibrary/SamplePy/FunctionType.py
706
3.6875
4
#関数の定義 def test(): return 1 print("call test: {}".format(test())) print("type test: {}".format(type(test))) #関数を変数に代入 test2 = test print("call test2: {}".format(test2())) print("type test2: {}".format(type(test2))) ''' 型が'function'とでていて、関数型であることがわかります。 そしてオブジェクトであるため変数への代入もできており、なおかつそれを呼び出すこともで...
f34b60bffcc9ec6fc18b8becfb8a8a42f238c652
harupapa-git001/Python
/PythonLibrary/SamplePy/Polymorphism.py
6,969
3.53125
4
''' ポリモーフィズムポリモーフィズムは日本語で多態性と訳されます。 その意味をWikipediaで調べてみると以下のようにありました。 ポリモーフィズムあるいはポリモルフィズム(Polymorphism)とは、プログラミング言語の型システムの性質を表すもので、プログラミング言語の各要素(定数、変数、式、オブジェクト、関数、メソッドなど)についてそれらが複数の型に属することを許すという性質を指す。 多態性、多相性、多様性とも呼ばれる。 ポリモーフィズムの概念をある程度理解している私にも難しくてよくわからないです。 難しい説明よりも、簡単な例をあげて説明しましょうか...
b7929fa3eadb3bcd7eb2ae07b30520f18130a311
harupapa-git001/Python
/PythonLibrary/StandardLibrary/ENUM.py
558
3.765625
4
''' 7.enum "enum"は列挙型を扱うためのライブラリです。Python3.4から導入されました。 ''' #列挙型を扱う from enum import Enum #定義 class Color(Enum): red = 1 green = 2 blue = 3 #利用 print(Color.blue.name) print(Color.blue.value) #簡略化した定義 Language = Enum("Language", "jp en vn") print(Langua...
dd9bc487497da36094788b195cf37242d70ae7ad
harupapa-git001/Python
/PythonLibrary/SamplePy/GlobalVariables.py
2,574
3.71875
4
'''ex1 x = 5 def add(): #global x #global宣言 x += 1 print(x) add() print(x) ''' ''' 実行してみると分かりますが、実際はエラーが出てしまいます。 上記エラーを見ると、関数の中で「変数xに値が与えられる前に参照した」というような内容となっています。 結論から言いますと、プログラム1行目のxと関数内のxは別物です。 そのため関数内のxを使おうとしたところ、エラーが出てしまったのです。 関数内に存在しない1行目の変数xは「グローバルレベル」に存在する変数です。 ...
f2559481b96eb9d1d993ca690cd97412096902f4
KueiShengLin/LeetCode
/hard/merge-k-sorted-lists.py
1,043
3.640625
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None from heapq import heappush, heappop class Solution: def mergeKLists(self, lists: List[ListNode]) -> ListNode: lists = list(filter(None, lists)) if lists == [] : ...
1c386551e5094aee39c070c204466f6deb0614d7
EDalSanto/MIT-6.00.1x
/Hangman/getGuessedword.py
894
4.0625
4
def getGuessedWord(secretWord, lettersGuessed): ''' secretWord: string, the word the user is guessing lettersGuessed: list, what letters have been guessed so far returns: string, comprised of letters and underscores that represents what letters in secretWord have been guessed so far. ''' G...
0e343ad1a09e29eea40d7f6e853e7a720d4fc8b7
EDalSanto/MIT-6.00.1x
/nfruits.py
943
4.03125
4
def nfruits(fruit, eaten): """ fruit is a non-empty dictionary containing type of fruit and its quantity initially with Python when he leaves home (length < 10) eaten is a 'string' pattern documenting types and # of fruits eaten along journey. After each fruit he eats (except the last one...
f1860f33fa4fc2a271b29d751ca2700e8e7194a4
KaivalyaBhale/Basic-python-programmes
/adj-triangle.py
1,471
3.625
4
""" for i in range(1,8): for j in range(1,9): if(j==1 or j==8 or i==4): j in [1,8] print("*",end=" ") elif(i==2 and (j==2 or j==7)): (i==2 and (j in [2,7])) print("*",end=" ") elif (i == 3 and (j == 2 or ...
59b6788d33c2772f63c188c9ecaf9dec06690ce5
manchuran/data_structures
/nested_list_sum.py
586
4.09375
4
def nested_list_sum(lst): ''' Calculate sum of a nested list Input: Nested list (Lists) Output: Sum (Integer) ''' if lst == []: return 0 if type(lst[0]) is list: lst[0] = nested_list_sum(lst[0]) return lst[0] + nested_list_sum(lst[1:]) def main(): sample_list = ...
142e7ebbded7732b5b1fc1f854f907a3525a2b7c
stratisMarkou/online_textbook_preview
/sequence_modelling/alice_processor.py
560
3.5625
4
file = open('alice_in_wonderland_raw.txt', 'r') result = '' for line in file: if line is not '\n': stripped = line.strip() txt = stripped.replace(' ', ' ') txt = txt.replace('_', '') txt = txt.replace('`', "") txt = txt.replace("'", "") txt = txt.replace('\\', "") ...
8ff2c21511ce38f3675d5db0739497a615693984
CodeDrome/taylor-polynomials-python
/main.py
1,336
3.890625
4
import taylorseries import math def main(): """ Test the taylorseries module by printing sines of a range of angles using math.sin and then taylorseries.sine_of_radians with various degrees of the polynomial. """ print("----------------------") print("| codedrome.com |") print("| Ta...
35bd65c512aae27006c934dc97d36370424a5434
mmontone/acme
/acme/util.py
235
3.5
4
def all_subclasses(klass): subclasses = [] for cls in klass.__subclasses__(): subclasses.append(cls) if len(cls.__subclasses__()) > 0: subclasses.extend(all_subclasses(cls)) return subclasses
14947370a2398d52b270c1754d65bbaaa55e5ee9
marcolcal/seniorproject
/workHistory.py
1,716
3.59375
4
from datetime import date import statistics #returns an array with the average at 0 and the stdDev at 1 def workHistoryAnalyser(workHistory): dateProcessing = None startDateParse = None endDateParse = None tempArray = [] days = [] returnArray = [] for x in workHistory: dateProc...
c3be05ee5c96d43747da8573145a20feb5bc05eb
RamiroUribe/prueba
/Calculadora.py
1,771
3.859375
4
def suma(valor,total): return valor+total def resta(valor,total): return valor-total def producto(valor,total): return valor*total def division(valor,total): return total/valor def calculadora(): opc=0 valor=0 valor1=0 total=0 valor=(input("Ingrese número 1: ")) try: ...
8ae4d57b3b1a552f9f51a8ef5d8998e0cb3ec1bb
abhi9741/Computational-tracing-of-light-rays-inside-cavities
/b2.Eellipse.py
1,647
3.703125
4
# -*- coding: utf-8 -*- """ Created on Mon Nov 14 09:23:36 2016 @author: abhinav """ import math as ma a = input("Enter the value of major axis in meters : ") b = input("Enter the value of minor axis in meters : ") x1=float(input("enter the x co-ordinate of the starting point of the hole")) y1=float(input("enter ...
a642b8224de8cee29b7834e60df1c819ee86eafe
singhm007/python
/functions.py
2,100
4.09375
4
# simple functions with default values def print_name(name="Singh"): print(f"My name is : {name}") print_name("Ram") => My name is : Ram def add_num(n1=4,n2=6): return n1+n2 add_num() add_num(3) add_num(3,5) # Palendrome check def check_palendrome(mystr): return mystr == mystr[::-1] val = input("Inpu...
6025a9174d17b625ecbc1e0d5c9bccd34740d408
yukuku/advent2015
/8b.py3
116
3.59375
4
b = 0 for s in open('input8.txt').readlines(): b += 2 for c in s: if c == '\\' or c == '"': b += 1 print(b)
b73076082295334d0177ed754cdaf64a74f8b129
vikkianand08/Session1_Python_1
/Assgmt1.py
923
3.75
4
# -*- coding: utf-8 -*- """ Created on Fri Jan 11 08:22:12 2019 @author: Nutan Anand """ print("Asgmt1: Numbers are divisible by 7 but are not a multiple of 5, between 2000 and 3200") list1=[]; for i in range(200,3201): if (i %7 == 0) and (i%5 !=0) : list1.append(i) print(list1) print("A...
3d40a99ce2dd3e7965cf4284455091e715ca1227
Ray0907/intro2algorithms
/15/bellman_ford.py
1,630
4.1875
4
#!/usr/bin/python3 # -*- coding: utf-8 -*- # single source shortest path algorithm. from sys import maxsize # The main function that finds shortest # distances from src to all other vertices # using Bellman-Ford algorithm. The function # also detects negative weight cycle # The row graph[i] represents i-th edge with ...
b3c9975d25b8f4af74010f8450c58f06a4c0f832
Khaled-Issa/AI-based-Connect-Four-Game
/Interface.py
1,527
3.75
4
import numpy as np # Board creation def make_board(): rows, columns = 6, 7 board = [['0' for x in range(columns)] for y in range(rows)] #board=np.zeros((6,7)) return board def drop_piece(board,row,column,piece): board[row][column]=piece def column_is_not_full(board,col): return board[5][col] ...
c84794a9b55638cc082f8d7f436c4eb1f0a1d123
Carole-Ouedraogo/CP_Python_Challenges
/5easy-3.py
1,320
3.984375
4
''' Easy Question #3 This is an extension of question #2. Given a list of dictionaries, write a function admin that returns the name and birthdate of all users that are marked as "admin". For example: users = [ { 'name': 'Homer', 'role': 'clerk', 'dob': '12/02/1988', 'admin': Fal...
37c14289f39334172a4faf21cc9f4563c8be0837
fdgd1998/python
/claseNominas.py
993
3.65625
4
class Empleado: def __init__ (self, nombre, sueldo, hijos, cat): self.nombre = nombre self.sueldo = sueldo self.hijos = hijos self.cat = cat class Nomina: def __init__ (self, empleado, neto, irpf, extra_hijos): self.nombre = empleado.nombre self.sueldo = emplea...
7426ae59ea9886abebdb5d16fd46a2279228696c
fdgd1998/python
/modules/operaciones.py
2,672
3.875
4
# Librería que contiene métodos referentes a operaciones matemáticas. # Alumno: Fran Gálvez. 2º ASIR. # generarAleatorios -> dado un parametro, genera N numeros aleatorios entre 0 y 100 y los devuleve en una lista. # esNegativo -> verifica si un número es negativo o no. # ordearMayorMenor -> ordena una serie de númer...
a84b55d181ea97dde6c5c91a72eb0e96ef635bdb
fdgd1998/python
/modules/menu.py
264
3.78125
4
# Librería que coniene métodos referentes a la creación de menús. # Alumno: Fran Gálvez. 2º ASIR. # imprimirMenu -> dada una matriz de elementos, los imprime en forma de menú. def imprimirMenu(menu): for i in range(len(menu)): print("\t" + menu[i])
5fc181678851f9171e2cf31fc211d838ec4a8d38
MikaelEpelbaum/LeetCode-python
/Array/exo1.py
399
3.671875
4
def removeDuplicates(nums): i1 = 0 i2 = i1 +1 cnt = 0 while i1 < i2 < len(nums): if nums[i1] == nums[i2]: i2+=1 else: nums = nums[:i1] + nums[i2-1:] cnt+=1 i1 = cnt i2 = i1+1 return nums if __name__ == '__main__': prin...
72b761f6d15ad0992a56aa6d271ba5b5c83f3fbd
hotriluc/pyth_diploma
/untitled/arr_procedures.py
3,340
3.609375
4
import itertools import pickle import numpy as np # write string def writeListInFile(aList:list,filepath): f = open(filepath,"w") for i in range(0,len(aList)): f.write(str(i)+") "+str(aList[i])+"\n") f.close() # write binary mode def writeListInBinFile(aList:list,file_name): wit...
32732b99b08e1fa85034c35a98bebb1d9f022360
sksandy385/sk1
/skset.py
254
3.578125
4
a=set={1,2,4,68,38} #assings the value for tuple 'a' print(a) b=set={1,2,4,68,38} #assings the value for tuple 'b' print(b) print(a|b) #union print(a&b) # intersection print(a-b) #differnce print(b-a) print(a^b) #syymetric diiference
41624ab8e380eb679a764c6a2e1a4530709dd31d
VladTsarkov/data-vis
/10.py
467
3.671875
4
from matplotlib import pyplot as plt import random from math import sin,radians,cos import numpy as np """ 10) Закрасить пространство между графиками, используя модуль matplotlib """ x = np.arange(0,720,10) y = np.sin(np.radians(x)) y1 = np.cos(np.radians(x)) plt.title("y = sin(x), y1 = cos(x), x = (0,720)") plt.grid(T...
9493a012dd7980b36c0cc88dc2b3f64a140ab740
fantasticGo/linuxLearning
/practiceOne.py
407
3.9375
4
#! /usr/bin/env python3 # -*- coding: utf-8 -*- list_test = [x if x % 2 == 0 else -x for x in range(1, 11)] print(list_test) list_test = [x + 1 if x % 2 == 0 else -x for x in range(1, 11)] print(list_test) list_test = [x + 1 if x % 2 == 0 else -x for x in range(1, 20) if x % 3 == 0] print(list_test) print("测试中文") prin...
895bc64683349a2d9c33d1fd778be9f8a7cbdaeb
rshar007/neuralnetworks
/ch01/a_neuron.py
405
3.96875
4
#!/usr/bin/python import numpy as np '''Implementation of a simple artificial neuron in Python.''' class Neuron: def __init__(self, weights, bias, function): self.weights = weights self.bias = biad self.function = function def forward(self, inputs): logit = np.dot(inputs, sel...
2c2a406dda5fc5f191c04491551306271ed4cfb0
IdentityPython/pyFF
/src/pyff/decorators.py
876
3.5625
4
""" Various decorators used in pyFF. """ from pyff.logs import get_log __author__ = 'leifj' log = get_log(__name__) def deprecated(logger=log, reason="Complain to the developer about unspecified code deprecation"): """This is a decorator which can be used to mark functions as deprecated. It will result in ...
5187e0a4b8b8ce4a150a428b843561831114ca17
Harshala-Gaikwad/Tkinter
/radiobutton.py
595
3.90625
4
from tkinter import * def selection(): selection = "You selected the option"+str(radio.get()) label.config(text=selection) top = Tk() top.geometry("300x150") radio = IntVar() lbl = Label(text="Favourite programming language: ") lbl.pack() R1 = Radiobutton(top,text="C",variable=radio,value=1,comma...
7f965fcca14ea444d54f35ada5b42ea6e2346fad
Harshala-Gaikwad/Tkinter
/calculator2.py
3,174
4.0625
4
from tkinter import* top = Tk() top.title("Simple Calculator") e = Entry(top,bd=5,width=50) e.grid(row=0,column=0,columnspan=3) def button_click(number): curr = e.get() e.delete(0,END) e.insert(0,str(curr)+str(number)) return def button_clear(): e.delete(0,END) def button_add...
e9c98d8d13b3b55e9fd02d19d6ab17df4f1eb0d7
MohamedAamil/Simple-Programs
/BinarySearchWords.py
1,805
4.21875
4
""" BinarySearchWords.py To check whether a word is in the word list, you could use the in operator, but it would be slow because it searches through the words in order. Because the words are in alphabetical order, we can speed things up with a bisection search (also known as binary search), which is similar to ...
92f328387b9d1754ad0f5fc71d2626acd3c82666
MohamedAamil/Simple-Programs
/SumOfDigits.py
397
4.21875
4
""" SumOfDigits.py : Displays the Sum of Digits of the given Number """ def get_sumofDigits(Num): """ Calculates the Sum of Digits :param Num: integer , Number """ Sum = 0 while Num != 0: a = Num % 10 Sum = Sum + a Num = Num // 10 print("Sum of Digit...
c54431ad6f88e202fdf5868c2820adaa5b0f5c33
ckern-tgm/Programs
/KuscheltierPaul/src/timefile.py
1,800
3.765625
4
import time from datetime import datetime, timedelta def checkTime(): endtime = time.time() +5 while time.time() < endtime: print("hello") print(endtime) # Time in format HOUR:HOUR:MINUTE:MINUTE:SECOND:SECOND def getTimeHHMMSS(): return str(datetime.now().time())[0:8] # time in format HOUR:H...
19f41fdd281dd30e1d90a20784926327c364c432
applicationsbypaul/Finalproject
/Classes/ticket_database.py
2,063
4.0625
4
""" Program: ticket_database.py Author: Paul Ford Last date modified: 08/1/2020 Purpose: creates an a db object and manipulate data with with definitions. """ import sqlite3 def create_connection(db): """ Connect to a SQLite database :param db: filename of database :return connection if ...
9c325170226ece98b4cd121995080a670ae1fa96
huaiyudavid/python-practice
/answers/loops/loops_9.py
175
3.78125
4
age = float(input('Input dog age in human years: ')) dog_age = 0 for i in range(1, age+1): if i <= 2: dog_age += 10.5 else: dog_age += 4 print(dog_age)
57c130b3803fc7091ac2ac40021eb7596cfc0126
huaiyudavid/python-practice
/answers/exop/exop_1.py
110
3.890625
4
first = float(input('Input a number: ')) second = float(input('Input another number: ')) print(first + second)
135c44f2454f3a5933bf263615ff2fe321822cfa
huaiyudavid/python-practice
/answers/exop/exop_4.py
100
3.75
4
base = float(input('Input base: ')) height = float(input('Input height: ')) print(base * height / 2)
e54bb4460c6e1adde343f5494ad436885852fd0f
jplatipus/INM378_CityDspCoursework
/pythonCode/ImageCorrelation.py
10,047
3.5625
4
import sys import matplotlib.pyplot as plt import numpy as np from pythonCode.ImageClass import ImageClass import scipy.signal as sig class ImageCorrelation: # # Class that encapsulates the image correlation functionality: 2 correlation versions are available: # one is using a simple correlation implementa...
c6d578aa322d3794cc0c0d9a7c7e0d6fef59361e
AlexanderPlatinum/neural_network_labs
/main.py
5,540
3.5625
4
import math import random import json class Neuron: __count_of_inputs: int __inputs = [] __weights = [] __t_value: float def __init__(self, count_of_inputs: int): if count_of_inputs <= 0: raise ValueError("count of inputs in neuron can be biggest zero") self.__count_o...
0ddb120cfad24fcefdd2ea19ba8362b6fa66068d
MakinoAlan/W4156-Connect4
/Gameboard.py
3,746
3.5625
4
class Gameboard(): def __init__(self): self.player1 = "" self.player2 = "" self.board = [[0 for x in range(7)] for y in range(6)] self.game_result = "" self.current_turn = 'p1' self.remaining_moves = 42 def move(self, x, y, player): if player == 'p1': ...
f3c4bf26929a9275d00953650e677b8924d993cc
edselmario/menu4
/problema1.py
787
3.984375
4
import os def ejemplo1(): class Alumno: # inicializamos los atributos def inicializar(self): self.nombre = input("digite nombre: => ") self.nota = float(input("digite su nota: => ")) # función para imprimir los datos def imprimir(self): print("No...
72d7a8a092eb85bc7fffc61824d620050520f1f0
sajitron/py-camp
/dictio.py
1,533
3.8125
4
user_info = { "name": "Julien", "gender": "male", "is_awesome": True, 73: "magic number", "games": { } } artist = { "first": "Neil", "last": "Young", } full_name = f"{artist['first']} {artist['last']}" for key, value in user_info.items(): print(f"key is {key}, value is {value}") # This code ...