blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
4760ad625580dacdc8d5720dd32362b87db2807f
daniel-reich/turbo-robot
/Cm9fAzNkWWdzit23N_23.py
1,021
4.375
4
""" ![Mexican Wave Simulator](https://s3.amazonaws.com/edabit-images/mex.gif) _The wave (known as a Mexican wave in the English-speaking world outside North America) is an example of metachronal rhythm achieved in a packed stadium when successive groups of spectators briefly stand, yell, and raise their arms._ Cr...
a4cdeb5e04bd6851ad609bf9f9aa538aa4b36a3d
clairefischer/npfl104
/hw/python/array_front9.py
458
3.796875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Mar 20 16:27:12 2019 @author: clairefischer """ #8 def array_front9(nums): if len(nums)<=4: if 9 in nums: return True else: return False else: array=nums[:4] if 9 in array: return True else: return F...
95863c632fbbd23e30d40f8504a79af8fdb8119e
HarbyUK/ctci-practice
/solutions/python/ch4/4.1-routeBetweenNodes.py
1,958
4.0625
4
""" Given a directed graph, design an algorithm to find out whether there is a route between two nodes.a Assumptions: Directed graph is a one way street. Can potentially be cyclic - but not always Parent nodes can have any number of child nodes. 1. implement node data structure class. class node() ...
013ad3d5af9d114f9111b59dc0c4bf9cecfe3482
heitorchang/learn-code
/battles/interview/sorting/mergeKArrays.py
1,387
3.9375
4
description = """ Given K sorted arrays, return their sorted concatenation. Example For arrays = [[1, 3, 5], [2, 3], [2, 3, 5, 8]], the output should be mergeKArrays(arrays) = [1, 2, 2, 3, 3, 3, 5, 5, 8]. Input/Output [time limit] 4000ms (py3) [input] array.array.integer arrays An array of K one-dimen...
930f47bca75d0684ef81a6ad143dba66f8ac0f7f
Aasthaengg/IBMdataset
/Python_codes/p02900/s047271287.py
1,075
3.8125
4
from math import sqrt def is_prime(n): for i in range(2, int(sqrt(n))+1): if n % i == 0: return False return True def make_divisors(a, b): lower_divisors = [] upper_divisors = [] i = 1 n = min(a, b) m = max(a, b) while i*i <= n: if n % i == 0: ...
c9bcc9fc229b8b43b789d3a62d7609a9762bb603
biomlds/blupper
/blupper/mock_data.py
1,563
3.515625
4
import pandas as pd def ex_pedigree_six_animals(): """ Create an example DataFrame containing pedegree for 6 animals Table 2.1., p. 23 """ data_dict = {'Calf': [3, 4, 5, 6], 'Sire': [1, 1, 4, 5], 'Dam': [2, 'Unknown', 3, 2]} df = pd.DataFrame(data_dict) ...
c83d6003c5502fbf4aee1616d0bc7189c305769e
Peett2/infoshare
/day_5/imports.py
535
3.78125
4
from collections import defaultdict, Counter # my_dict = defaultdict(int) # print(my_dict['non_existing']) # zliczyć ile razy występuje każdy znak w stringu - wykorzystać słownik text = 'ala ma kota, kot ma ale' my_dict = dict() # the bad way for char in text: if char in my_dict: my_dict[char] += 1 ...
04353e9f8b9dc01ce465d516eedb7bb958d643b0
huitianbao/Python_study
/exe3advanced/10_class/first_stu.py
1,701
3.953125
4
# 一:定义一个学生类。有下面的类属性: # # 1 姓名 # 2 年龄 # 3 成绩(语文,数学,英语)[每课成绩的类型为整数] # # 类方法: # # 1 获取学生的姓名:get_name() 返回类型:str # 2 获取学生的年龄:get_age() 返回类型:int # 3 返回3门科目中最高的分数。get_course() 返回类型:int class Stu(object): def __init__(self,name,age,list_score): #检查姓名 if isinstance(name,str): self.name = name ...
fedeb8be5ea6418669478ce0a25fd260e9b2da20
syncopika/learningPython
/cs11projects/lab3/char_translator.py
1,503
3.75
4
#char_translator.py import random #generates and returns a string with a-z jumbled up def random_permute_chars(): letters = [] for i in range(97, 123): letters.append(chr(i)) random.shuffle(letters) return ''.join(l for l in letters) #CharTranslator class class CharTranslator: #init metho...
b85918de7f6b610433ea6e8c86c38385c9ffb67e
egorzakharov00/Machine-Learning-Clustering
/kmeans.py
7,098
3.953125
4
# import relevant libraries import math import csv import random import matplotlib.pyplot as plt import numpy # Function that computes the distance between two data points # that takes 2 lists of length 2 as parameters where # first element is x value and 2nd element is y value def distance(a, b): ret...
81276b139179ad7b3e6a19fd731348b169eb03f7
singhr2/Python101
/basics/ObjPersistence.py
3,665
3.90625
4
#ObjPersistence.py ''' object persistence — making objects live on after the program that creates them exits Object persistence is implemented by three standard library modules, available in every Python: a) pickle : Serializes arbitrary Python objects to and from a string of byte stream * convert object to a string...
dd29979bca488610fa1b536df2279f65b2db8543
JhonEddi/Repaso-de-pyhon
/ejercicio 91.py
452
3.78125
4
import time def segundos(h,m,s): return (h*3600) + (m*60) + s def horasMinutosSegundos(s): return [(s // 3600), ((s% 3600)// 60), ((s%3600)%60)] def cronometrar (h,m,s): s = segundos(h,m,s) tiempo = horasMinutosSegundos(s) print(tiempo[0], ":",tiempo[1],":",tiempo[2]) for x in range ...
ebd9b8289fa8cdd5db9d7257a26a1a5a72697710
KimLil/GB-algorithms
/task 2-8.py
801
4.1875
4
#8. Посчитать, сколько раз встречается определенная цифра в введенной последовательности чисел. # Количество вводимых чисел и цифра, которую необходимо посчитать, задаются вводом с клавиатуры. user_number = int(input("Введите число: ")) user_digit = int(input("Какую цифру нужно искать в числе?")) user_digits_sum = 0 ...
ea8b0b914b22ee440d5c83f4a824b2bdb3404955
DodiyaParth/Program_Storage
/PROGRAMS/Python/linked_list.py
3,186
4.40625
4
class LinkedList: """Defines a Singly Linked List. attributes: head - a pointer to the first node object """ def __init__(self): self.head = ListNode() """ This is the constructor. It tells you what are the attributes of all objects belonging to this class. You do not need to call the c...
afcd74b8e32441e3757a2c4a0daf2942536c2a9e
Ysnsn/python
/猜数字/Example_4_1.py
373
3.53125
4
# Example_4_1.py import random target = random.randint(1,1000) count = 0 while True: guess = eval(input('请输入一个猜测的整数(1至1000):')) count = count + 1 if guess > target: print('猜大了') elif guess < target: print('猜小了') else: print('猜对了') break print("此轮的猜测次数是:", count)
203ab44d27586b7b05757ba8934681e53ea4c4e3
sangm1n/problem-solving
/BOJ/10809.py
556
3.625
4
""" 알파벳 소문자로만 이루어진 단어 S가 주어진다. 각각의 알파벳에 대해서, 단어에 포함되어 있는 경우에는 처음 등장하는 위치를, 포함되어 있지 않은 경우에는 -1을 출력하는 프로그램을 작성하시오. """ string = list(input()) alphabet = [i for i in range(ord('a'), ord('z') + 1)] for i in range(len(alphabet)): if chr(alphabet[i]) in string: idx = string.index(chr(alphabet[i])) alpha...
80456e7d866eac5db49ccf4eec2f1d1fa3ff7b9e
projects-ls/Lambda-School-Day-116-119-Data-Structures
/binary_search_tree/binary_search_tree.py
1,546
3.78125
4
class BinarySearchTree: def __init__(self, value): self.value = value self.left = None self.right = None def insert(self, value): node = self if node == None: node.value = value return while True: if value < node.value: ...
0858985625611ff69f5897161dcb7b6fea13ae33
ponyatov/Q
/m.py
517
3.515625
4
class O: def __init__(self,V): self.val = V def __repr__(self): return '<%s>'%self.val def __add__(self,o): return self.__class__(self.val + o.val) A = O(123) ; print A B = O(4.56) ; print B print A+B class S(O): def __init__(self,V): O.__init__(self, V) ; self.nest = [] def __lshift__(self,o): s...
e6aff9556e5772b66360ba69a0dee72eca6050c4
ramonvaleriano/python-
/Livros/Introdução à Programação - 500 Algoritmos resolvidos/Capitulo 4/Exercicios 4a/Algoritmo281_Enq20.py
356
3.953125
4
# Program: Algoritmo281_Enq20.py # Author: Ramon R. Valeriano # Description: # Developed: 04/04/2020 - 11:53 # Updated: cont = 0 number = int(input("Enter with the %d° number: " %(cont+1))) bigger = number while number!=-999: cont+=1 if number>=bigger: bigger = number number = int(input("Enter wit...
bdd8c459304af246cb96051afccbb946b44cc641
No1CharlesWu/Python
/codewars/TakeATenMinuteWalk.py
1,593
4.34375
4
""" You live in the city of Cartesia where all roads are laid out in a perfect grid. You arrived ten minutes too early to an appointment, so you decided to take the opportunity to go for a short walk. The city provides its citizens with a Walk Generating App on their phones -- everytime you press the button it send...
82dc9e379474f7fba9e0ae9f7ac6aa83ed4611fd
pip-services3-python/pip-services3-commons-python
/pip_services3_commons/random/RandomInteger.py
2,553
4.125
4
# -*- coding: utf-8 -*- """ pip_services3_commons.random.RandomInteger ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Random integer implementation :copyright: Conceptual Vision Consulting LLC 2018-2019, see AUTHORS for more details. :license: MIT, see LICENSE for more details. """ from typing...
8f384bceefe2e1758c9697738639b5fb3adee2d3
Armando101/Programaci-n-Concurrente
/17-Eventos.py
1,401
3.546875
4
import time import logging import threading logging.basicConfig(level=logging.DEBUG, format='%(threadName)s : %(message)s') """ Un evento internamente contiene una bandera, verdadero o falso Por default la bandera comienza en falso Una vez la bandera cambia a verdadero se dispara una señal Todos los threads que se en...
c52a8994b50c56b775d95f46ce4b12d6119cbaa2
monkeynova/learn-python
/structures/BinaryTree.py
4,994
3.859375
4
class Node: def __init__( self, key, value ): self.key = key self.value = value self.parent = None self.left = None self.right = None def _debug( self, indent ): print "%s%r (%r) = %r" % ( indent, self.key, self.parent and self.parent.key, self.value ) ...
649128c9067a3aa50c10dad5ff4bb38c31be8b45
GeorgiyDemo/FA
/Course_II/ПП/part1/pract1/examples/example1.py
279
3.75
4
from tkinter import * root = Tk() c = Canvas(root, width=300, height=200, bg="white") c.pack() ball = c.create_oval(0, 100, 40, 140, fill="green") def motion(): c.move(ball, 1, 0) if c.coords(ball)[2] < 300: root.after(10, motion) motion() root.mainloop()
582ceccefd577497ed458d0088945daefe973eb5
lee2014/interview_code
/leetcode/91_decode_ways.py
1,959
4.34375
4
#!/usr/bin/env python # -*- coding: utf-8 -*- """ A message containing letters from A-Z is being encoded to numbers using the following mapping: 'A' -> 1 'B' -> 2 ... 'Z' -> 26 Given a non-empty string containing only digits, determine the total number of ways to decode it. Example 1: Input: "12" Output: 2 Explanat...
21e8b1d197a021931d8fbc7761798bd9c74884ca
petr-tik/lcthw
/test_data_structures.py
6,917
3.6875
4
#! /usr/bin/env python import unittest from data_structures import LinkedList, Stack, Node, Queue, Heap, BST_Node, BinarySearchTree import random as rnd class LinkedListTestCase(unittest.TestCase): def setUp(self): self.arr = [rnd.randint(0, 20) for x in xrange(10)] self.LL1 = LinkedList(self.ar...
b5d4199980b7a177709fe990a8f36c24423cfd0c
jacokyle/MTH325_Homework
/Programming Set 2.py
1,738
3.9375
4
# Kyle Jacobson # Professor Taylor # MTH 325 - 02 # 23 March 2020 # The following function takes two inputs: one a graph, # and the other a coloring of the vertices, # and determines whether or not the coloring is a # proper vertex-coloring of the given graph. def is_proper(pairs, coloring): # Loops through or...
c0d57b28a7842e9d37a8899f79b62c2da270d137
WojciechKusa/neural_games
/src/game/game.py
1,386
3.9375
4
import player class Game(object): """docstring for Game""" def __init__(self, arg): super(Game, self).__init__() self.arg = arg def start( self ): raise NotImplementedError( "This is an abstract class - this method have to be implemented" ) def play( self ): self.gene...
0fc5a12f17f4cd0ab3bc7d08542cb2c08bb36807
TobbyEchonga/calculating_with_spreadsheets
/main.py
2,409
3.5
4
import openpyxl inv_file = openpyxl.load_workbook('inventory.xlsx') product_list = inv_file["Sheet1"] # defining the dictionary products_per_supplier = {} total_value_per_supplier = {} products_under_10_inv = {} # product_row.max_row is the total number of rows in that specific sheet # print(product_list....
8c0a9326af8adaa042845865aab9828c4400e2a4
rajendrapallala/hackerrank-python-practice
/sets/check_strict_superset.py
303
3.640625
4
# Enter your code here. Read input from STDIN. Print output to STDOUT ss = set(map(int, input().split())) prt = 'True' for i in range(int(input())): sbs = set(map(int, input().split())) if ss.issuperset(sbs) and len(ss) > len(sbs): continue else: prt = 'False' print(prt)
8f6d211a8f8e3de020e27f728efce320a2ab5e32
cami-la/python_curso_em_video
/Mundo03:estruturas-compostas/exercicio-python#088-palpites-para-a-mega-sena.py
1,278
4
4
from random import randint from termcolor import cprint from time import sleep ''' Faça um programa que ajude um jogador da MEGA SENA a criar palpites. O programa vai perguntar quantos jogos serão gerados e vai sortear 6 números entre 1 e 60 para cada jogo, cadastrando tudo em uma lista composta. ''' def play(): exer...
575b5027c718f9bc72b453e35d4616915516823a
davdleet/hello-world-python
/week13class12.py
290
3.515625
4
# 파일을 읽고 단어 통계 구하기 f = open('memo2.txt', 'r', encoding='UTF-8') book = f.read() word_text = book.split(' ') line_text = book.split('\n') print('전체 단어수:', book.count(' ') + book.count('\n') + 1) print('전체 라인 수:', book.count('\n')) f.close()
8e7398f71c501d61700618363a93137a9c9d1568
tennyson-mccalla/PPaItCS
/8.5.py
682
4.09375
4
def prime(n): x = 0 if n % 2 == 0: return 2 elif n in [3, 5, 7]: print("\n{} is prime".format(n)) return n else: d = 3 while d <= n ** 0.5: if n % d == 0: print("\n{} is not prime".format(n)) return d elif n ...
81ac3bd6ea9a85320e19ea984c8e0924b41c6126
KevinHaoranZhang/Leetcode
/Sequence/q1-q99/q20-q29/q29/q29.py
197
3.828125
4
ans = int(dividend//divisor) if int(dividend//divisor) < dividend/divisor: ans = dividend/divisor if ans > 2**31 - 1: return 2**31-1 return int(ans)
00c70534e098d9b78bd2fc5afd4bccee51f55393
Grayhkamau/bus-fare-python-
/bus_fare_challenge.py
2,213
3.59375
4
# WRITE YOUR CODE SOLUTION HERE from datetime import datetime date = datetime.now() day = print('day: ' + str(date.strftime('%a'))) fare = int(100) fare_2 = int(80) fare_3 = int(60) thursday = print('Day: ' + str(today_date.strftime('%a'))) friday = print('Day: ' + str(today_date.strftime('%a'))) saturda...
b1f5967368f746a0d772ff4bd07544138bbf1499
kuihuar/datastruct
/ds40/treeSearch.py
946
3.671875
4
class TreeSearch(object): def __init__(self): ##队列 def BFS(self,graph, start, end): queue=[] visited=set() queue.append([start]) visited.add(start) while queue: node = queue.pop() visited.add(node) process(node) node...
10e1145a7c991fa399cc44208ec3ef43435c6ed3
ravichalla/wallbreaker
/week1/Transpose_a_matrix.py
848
4.03125
4
''' QUESTION: Given a matrix A, return the transpose of A. The transpose of a matrix is the matrix flipped over it's main diagonal, switching the row and column indices of the matrix. Example 1: Input: [[1,2,3],[4,5,6],[7,8,9]] Output: [[1,4,7],[2,5,8],[3,6,9]] Example 2: Input: [[1,2,3],[4,5,6]] Output: [[1,4],[...
a604c9ce001b1c1633420665aadc87b7e3a5df5c
jlassi1/holbertonschool-machine_learning
/math/0x03-probability/binomial.py
1,861
4
4
#!/usr/bin/env python3 """Binomail Distribution""" e = 2.7182818285 π = 3.1415926536 class Binomial: """Binomail Class """ def __init__(self, data=None, n=1, p=0.5): """intitialization of class Binomial""" self.data = data if data is None: if n <= 0: raise V...
9762e364c7ec58f5042363a7d702b14208408898
qmnguyenw/python_py4e
/geeksforgeeks/python/python_all/42_7.py
3,211
4.40625
4
Python – Convert String List to Key-Value List dictionary Given a string, convert it to key-value list dictionary, with key as 1st word and rest words as value list. > **Input** : test_list = [“gfg is best for geeks”, “CS is best subject”] > **Output** : {‘gfg’: [‘is’, ‘best’, ‘for’, ‘geeks’], ‘CS’: [‘i...
4a2ce9acfe5bb86eb2f6303316bc19a2cd805b6b
ironboxer/leetcode
/python/Offer28.py
1,283
3.6875
4
""" https://leetcode-cn.com/problems/transpose-matrix/ 剑指 Offer 28. 对称的二叉树 请实现一个函数,用来判断一棵二叉树是不是对称的。如果一棵二叉树和它的镜像一样,那么它是对称的。 例如,二叉树 [1,2,2,3,4,4,3] 是对称的。 1 / \ 2 2 / \ / \ 3 4 4 3 但是下面这个 [1,2,2,null,3,null,3] 则不是镜像对称的: 1 / \ 2 2 \ \ 3 3 示例 1: 输入:root = [1,2,2,3,4,4,3] 输出:true 示...
6a945c5654b07ebc30ab67ad900ab69ff3acc460
kameshkotwani/python_assignment
/assignment_2/area_trainer.py
5,254
4.15625
4
''' Assignment 2: Area Trainer Program: Reboot Academy This solution is created in python 3.6.4 CAUTION: MAY NOT WORK IN OLDER VERSION Solved by: Kamesh Kotwani ''' import math import random SCORE =0 #Global Score Variable #Function to keep track of score def increment(): global SCORE SCORE+=1 #Making a...
8b9aa985ecc2e5576af30dfb75c4405ec9357348
DeshErBojhaa/sports_programming
/leetcode/1320. Minimum Distance to Type a Word Using Two Fingers.py
992
3.546875
4
# 1320. Minimum Distance to Type a Word Using Two Fingers class Solution: def minimumDistance(self, word: str) -> int: N = len(word) word = [*map(lambda x: ord(x) - ord('A'), word)] def distance(n1, n2): a, b = divmod(n1, 6) a2, b2 = divmod(n2, 6) ...
be66c10237ff83640fa4947968b19b733704864f
fivepapertigers/envloader
/EnvironLoader/EnvironLoader/cli.py
818
3.5
4
from argparse import ArgumentParser def parse_args(): # Command - first positional parser = ArgumentParser(add_help=True, description=\ "A simple CLI utility to store and load environment variables") parser.add_argument(dest='command', type=str, choices=['load', 'store', 'init'], ...
805d893bcb7fe7ce217bfd04f7abd841c960edff
Chezhiankarthi/PYTHON-PROGRAMMING
/factorial.py
67
3.6875
4
num=int(input()) ac=1 for i in range(1,num+1): ac=ac*i print(ac)
ff7611cf34a336fed886ef9839b5d02112620841
RonnieTim/Datacamp
/DataAnalystTrack/sitecount.py
398
3.53125
4
import pandas as pd from matplotlib import pyplot as plt file = pd.read_csv('new10.csv', sep=',', header=0, nrows=10) df = pd.DataFrame(file) price = df['Price'] item = df['Product'] plt.style.use('seaborn-pastel') plt.scatter(item, price, label="Philadelphia", marker='s', linestyle='--') plt.xlabel("Items") plt.ylabe...
303d6a3d86c26e374da8abaf2be232a9e5e7f22e
basslabb/adventofcode
/2016/day1b.py
1,816
3.640625
4
def get_direction(current_direction, direction): if current_direction == "N" and direction == "L": current_direction = "W" elif current_direction == "N" and direction == "R": current_direction = "E" elif current_direction == "S" and direction == "L": current_direction = "E" elif...
3119588dc09b78ab5237f894fbb18d2d79f13cc7
adang1345/Project_Euler
/29 Distinct Powers.py
259
4.0625
4
"""Find the number of distinct terms in the sequence generated by a^b for integers a and b satisfying 2 <= a <= 100 and 2 <= b <= 100.""" sequence = set() for a in range(2, 101): for b in range(2, 101): sequence.add(a ** b) print(len(sequence))
6a4d01aad0c9871c75281d5e70fa2e45e2030b21
CarlosRodriguezzz/software_design
/module1/poo_property_decorator.py
1,200
3.78125
4
class Avion: def __init__(self, velocidad, altitud, roll, pitch, yaw): self.velocidad = velocidad self.altitud = altitud self.roll = roll self.pitch = pitch self.yaw = yaw self.__pasajeros = 0 def volar(self): return 'volando a {} metros de altitud y ...
8a431a13e10ea4e4f6b064fb31bd22bf128ea230
bch6179/Pyn
/longestConsecutive.py
1,842
3.75
4
# /** # * Given an unsorted array of integers, find the length of the longest # * consecutive elements sequence. # * # * For example, # * Given [100, 4, 200, 1, 3, 2], # * The longest consecutive elements sequence is [1, 2, 3, 4]. Return its # * length: 4. # * # * Your algorithm should run in O(n) c...
8464effba8cf78928f0d6690dfd830a64246a1be
GregorySkir/Gkime
/51.py
443
3.734375
4
import random def guess_my_number_again(num=None, tries=5): t=0 if num==None: num=random.randint(1,100) while t<tries: num2=random.randint(1,100) if num2>num: print('too high') elif num2<num: print('too low') else: retur...
56cbaef4d6761c2273a093d3f42d674f6c6ce04a
mqianliu/COVID-DST
/baseline/create_data.py
6,541
3.5
4
import json import re ''' The codes are modified from https://github.com/budzianowski/multiwoz ''' def insertSpace(token, text): sidx = 0 while True: sidx = text.find(token, sidx) if sidx == -1: break if sidx + 1 < len(text) and re.match('[0-9]', text[sidx - 1]) and \ ...
0e0fef7dc7562377f8026ed6d294c6786bd250df
nkarg/Funciones
/funcionC.py
143
3.640625
4
def mostrarParImpar(a): if a%2 ==0: for i in range(a+1): if i%2==0: print i else: for i in range(a+1): if i%2==1: print i
5d92b7bc1fbdf0e003929ea93bd89b69850cf15c
GeorgeGiann/InvoiceSamplingWithTrie
/SamplingWithTrie.py
3,382
3.625
4
from Trie import Trie import csv #open costumer_sample.csv file in order to read its content sample_file = open('customer_sample.csv') samples = csv.reader(sample_file) #create two Tries to find the rows needed according to samples CustomerTrie = Trie() InvoiceTrie = Trie() print 'Scanning sample file and creatin...
8eecf88f1c9e569482f71f41e222a8648f68da26
bakeunbi99/Python
/Example/book/4_3_Ex01.py
333
3.6875
4
# 원소가 한 개인 경우 t = (10, ) print(t) # 원소가 여러개인 경우 t2 = (1, 2, 3, 4, 5, 3) print(t2) # 튜플 색인 print(t2[0], t2[1:4], t2[-1]) # 수정 불가 # t2[0] = 10 #error # 요소 반복 for i in t2 : print(i, end=' ') # 요소 검사 if 6 in t2 : print("6 있음") else: print("6 없음")
4ca5274ebdc8119843e041580d3921cafe1fbb23
shafkat-khondker/graph-plotter
/polynomial.py
1,950
4.15625
4
""" This class allows the user to plot simple polynomial functions in the form of y=A*(x)^B Functions such as square roots are also supported """ import numpy as np import matplotlib.pyplot as plt from fractions import Fraction from function import * class Polynomial(Function): def __init__(self, A, B, x_start, x_en...
09f5a41cf0d808a278dc24f60f141e2e17a3873c
SummerCheng/CS61A-2017Fall
/lab/lab13/lab13.py
2,314
4.1875
4
## Generators def make_generators_generator(g): """Generates all the "sub"-generators of the generator returned by the generator function g. >>> def ints_to(n): ... for i in range(1, n + 1): ... yield i ... >>> def ints_to_5(): ... for item in ints_to(5): ... ...
7f3e52a526049dce331958411caffaf71b699949
Hitoshy/Maratona-de-Programacao
/Estudos/Python/Treinamento-pelo-app-Py/04.py
165
4.125
4
print(1) print("-100 e inteiro") #acentuacao nao e possivel colocar print(3.1415) #Convertendo string em int x = int("5") print(x) message = "10" print(int(message))
79ce16ef1f19b2dbd44618b11b435446d07075b8
Ontheway361/sense_coding
/chap22-basic_graph/bfs.py
797
3.84375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on 2020/08/05 author: relu """ from IPython import embed def bfs(adjlist, srcidx = 3): queue = [] search_idx = 0 queue.append(srcidx) while len(queue) < len(adjlist): node_idx = queue[search_idx] for idx, adj in enumerate(adjli...
418a901eeb8500b1f1ebad5af541a422fad13e00
KangSuzy/algorithms
/programmers/42577.py
482
3.640625
4
def solution(phone_book): hash_map = {} # phone_book 리스트를 해시로 변환 for phone_num in phone_book: hash_map[phone_num] = 1 for phone_num in phone_book: # 하나씩 늘려가면 비교 temp = '' for num in phone_num: temp += num # 접두어가 존재하는 경우와 자기 자신과 같을 경우 i...
9486114c5f822b639e1fc5d0fd9a158485dc6347
ThatsAMorais/breakin-and-poppin
/collision/Collision.py
1,383
3.6875
4
##### File : Collision.py #### Author : Alex Morais ### Description : An object repr. of a collision which clocks the time ### elapsed since the collision. It is updated via ### update() with the time since the previous update. ## class Collision(): # Supported types. This is weakly abstracted, but this is ...
44f1961fe4ce10dad55736e9682e7fc356a6c730
mateusvictor/OBI-2021
/Data Structures/Stack/postfix_expression.py
321
3.71875
4
def postfix_expression(expression): stack = [] for c in expression: if c.isdigit(): stack.append(int(c)) else: x = stack.pop() y = stack.pop() stack.append(int(eval(f'{y} {c} {x}'))) print(stack) return stack.pop() expression = '545*+5/' expression = '138*+' print(postfix_expression(expression)...
c14446a30f864ab68297dd9c2019ebfacd3333de
mjtsolo/Level_0
/Task 0.8.py
137
3.765625
4
time = 67.345 hours = int(time) minutes = (time*60) % 60 seconds = (time*3600) % 60 print("%d:%02d.%02d" % (hours, minutes, seconds))
8f5e6758e5c2e83bfa3c913908f39f15c680ded2
vtantonio20/TicTacToe
/tictactoe.py
4,815
3.75
4
class Board(): EMPTY_SPACE = " " def __init__(self): self.cells = ["_", " ", " ", " ", " ", " ", " ", " ", " ", " "] def display(self): print("\n" + self.EMPTY_SPACE + " %s | %s | %s " %(self.cells[7], self.cells[8], self.cells[9])) print(self.EMPTY_SPACE + "------...
931ebae52cfd7f62ba4a6369ae6cd6ac9b4342b2
jeongyongwon/Algo_Coding
/swexpert/홀짝일까.py
200
3.640625
4
import sys sys.stdin = open('홀짝일까.txt','r') for t in range(int(input())): num = int(input()) if num % 2 == 0 : print(f'#{t+1} Even') else : print(f'#{t + 1} Odd')
6cb017692a1e4fda5eef309e0208b74cd39e0acb
luyangong/lyg
/learn_python/ex8_92.py
774
3.828125
4
word = ['ADJECTIVE', 'NOUN', 'VERB', 'ADVERB'] file_in = open('test.txt') content = file_in.read() file_in.close() #print(content) content_list = content.split() #print(content_list) content_out = [] for i in content_list: if i[0] in 'aA': ch = 'an' else: ch = 'a' ...
33820d9571a280bc6a8b53546fe0cf28f03479ee
chaotic-enigma/MITx-6.00.1x-Introduction-to-Computer-Science-and-Programming-Using-Python
/ProblemSet2/2-2 Paying Debt Off In a Year.py
1,304
4.1875
4
# https://courses.edx.org/courses/course-v1:MITx+6.00.1x_6+2T2015/courseware/Week_2/Problem_Set_2/ # write a program that calculates the minimum fixed monthly payment needed # in order pay off a credit card balance within 12 months. # By a fixed monthly payment, we mean a single number which does not change each mont...
c66eed65653dabe87b5266e3bdcc32a3a884a71c
jaoguerreiro/Atividade_CES22_ExLab2
/main.py
2,371
3.609375
4
class Action: #Classe para acoes solicitáveis def execute(self): pass class Account: #Conta do Cliente def __init__(self, saldo, extrato): self.saldo = saldo self.extrato = extrato #Receiver class AccountAction(Account): #aqui se define as ações das funções def _...
51e3f44297384b95e3fca827c826ab13c04a4bfc
0ff5ec/Programming
/sortColors.py
1,005
4.25
4
# -*- coding: utf-8 -*- ''' Given an array with n objects colored red, white or blue, sort them so that objects of the same color are adjacent, with the colors in the order red, white and blue. Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively. Note: You are ...
329af48472857b0960076a8d2c97ae89e0237ee7
empty-spaces/school-work
/HPC et Simulation/Projet/src/utils.py
2,253
3.5625
4
import networkx as nx import matplotlib.pyplot as plt from os.path import basename, splitext def read_graph_from_file(filename): """ Read graph from a file. Args: filename (str): Path to the file containing the graph Returns: float: Density array: M array: Adjency Matrix ...
d8f35613a930b59421c46acf33a4e3bc2d91486d
TrellixVulnTeam/Demo_933I
/leetcode/88.Merge Sorted Array.py
1,246
3.9375
4
# Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one # sorted array. # # Note: # # # The number of elements initialized in nums1 and nums2 are m and n respectivel # y. # You may assume that nums1 has enough space (size that is equal to m + n) to h # old additional elements from nu...
def2013514323bd9ac0020c8df00fbbc3ad00ec1
ram3009/learning_phase
/bubble_sort.py
297
4.03125
4
def bubble_sort(datas): for x in datas: for i in range(0,len(datas)-1): if datas[i]>datas[i+1]: temp=datas[i+1] datas[i+1]=datas[i] datas[i]=temp print(datas) datas=[7,1,3,9,4,6] print(datas) bubble_sort(datas)
bd3b73f9ca36afcc6f6e8d7beb08c80e9557e9d8
hyeokjinson/algorithm
/정렬/나이순 정렬.py
286
3.5625
4
if __name__ == '__main__': n=int(input()) arr=[] tmp=1 for _ in range(n): a=list(map(str,input().split())) arr.append((int(a[0]),a[1],tmp)) tmp+=1 arr=sorted(arr,key=lambda x:(x[0],x[2])) for age,name,num in arr: print(age,name)
2453904a49406b5e1e5717402afe44b63f13e190
ssky10/2018-2_Python
/실습수업 과제/09_1116_과제1.py
311
3.546875
4
import random i = 0 while i < 3: a = random.randint(1,100) b = random.randint(1,100) while True : answer = int(input("%d + %d = " %(a,b))) if a+b == answer: i += 1 print("정답입니다!\n") break print("총 정답수 : %d 개" %i)
048350c8c0395f3dd07518b751a84db9b8d26c55
Ulremberg/LabProgramacao
/CanalDeTv.py
569
3.65625
4
canal = int(input()) #4 band 2 sbt 6 REDETV 9 RECORD if (canal == 13): print("Digite um numero de um canal de tv:") print("GLOBO") elif (canal == 9): print("Digite um numero de um canal de tv:") print("RECORD") elif (canal == 6): print("Digite um numero de um canal de tv:") print("REDETV!") elif...
3020f847c461d60d29b6c6a79fbb0adb3c45e258
clintjohns/clintjohns.github.io
/getperiods.py
2,248
3.6875
4
#!/usr/bin/env python # CJohns # March 2016 # get all of the teaching periods from now until the end of the school year, and store in to a database def parse(mydate): #print(mydate) import urllib2 try: #response = urllib2.urlopen('http://www.shpschedule.com') #response = urllib2.urlopen('http://web.s...
80486af42397de8fcbef9ab510d31fcce69eb131
kancha-supriya/python_samples
/decorator_new.py
1,123
3.9375
4
def add(a,b): return a+b def decor(func): def wrapper(a, b): print("checking.......") if isinstance(a, int) and isinstance(b, int): return func(a, b) else: return "Data should be integer" return wrapper add = decor(add) print(add(1, '2')) pri...
b4ab307854201f0a9ff72c907a65bf1fb8134888
Hongyiel/CS362
/Inclass/Week8/unittest_fibonacci.py
703
3.546875
4
import unittest import fibonacci class TestCaseFibo(unittest.TestCase): def test_case1(self): self.assertEqual(fibonacci.Fibonacci(10),10) def test_case2(self): self.assertIsNotNone(fibonacci.Fibonacci(5)) # get . if Fibonacci's value is exist def test_case3(self): self.asse...
f271f9686502904bda97b2fdfef753c73b10e2de
studyml-lab/Python-Basics
/6.dataframe2.py
3,676
3.921875
4
# data frame : 2 dimensional # rows == observations / samples # columns == features/ attributes # each column of different # within column we expect the data to be in same data type import pandas as pd print(pd.__version__) # to create data frame from an existing dict/map dict1 = {'names': ['ra...
58b05b2b7b4b85573fcf62e82f58a6cd438bb7e3
blank8/repo
/sheet.py
2,472
4.125
4
print("helloworld") # Mathmatical Operators a = 2 + 2 print(a) b = 7 - 4 print(b) c = 2 * 4 print(c) d = 8 / 2 print(d) e = 21 // 7 print(e) f = 7 % 2 print(f) # Function Definition def print_lyrics(): print("I'm a lumberjake, and I'm okay.") print("I sleep all night and I work all day") # Function Retu...
fd6663d150cc2b66be79a57d146a16d75ff3b2b4
tharsh1/Test
/EvaluateExpression.py
875
4.1875
4
# Expresion must contain single digit operands and only (+,-,/,*) operators are allowed def evaluateExpression(exp): expLength = len(exp) if (expLength == 0): return - 1 result = int(exp[0]) for e in range(1, expLength, 2): operator = exp[e] op2 = exp[e + 1] if (not op2.i...
bd8a96c5044ede38fe33f5816c54fe0e11ec8a35
jakeru/adventofcode
/2020/day11.py
3,796
3.8125
4
#!/usr/bin/env python3 # By Jakob Ruhe 2020-12-11 # 06:51 p1 solved import os import re import unittest from collections import defaultdict from collections import namedtuple FLOOR = "." EMPTY = "L" OCCUPIED = "#" OUTSIDE = " " DIRECTIONS = ((-1, 0), (-1, -1), (0, -1), (1, -1), (1, 0), (1, 1), (0, 1), (-1, 1)) def...
2ba9846afc8bd2403a670e33957a792a1d4335a0
wiput1999/Python101
/6 Extra 3/SuperEx3/7.py
153
3.546875
4
a = [] b = [] c = [] for i in range(10): a.append(int(input("Number : "))) for i in range(10): b.append(int(input("Number : "))) c = a + b print(c)
03d73e7e5abb5e74096bc545a8a1c05f5440bb43
hussamkhoury/Shami-Dialect-Identification
/ReadFile.py
3,081
3.546875
4
repeated_character = ['ب', 'ت', 'ل', 'ه', 'ر', 'م', 'ن', 'د', 'ف', 'ي', 'ه', 'خ', 'ص', 'ط'] Valid_character = ['ب','ت', 'ث', 'ج', 'ح', 'خ', 'د', 'ذ', 'ر', 'ز', 'س', 'ش', 'ص', 'ض', 'ط', 'ظ', 'ع', 'غ', 'ف', 'ق', 'ك', 'ل', 'م', 'ن', 'ه', 'و', 'ي', 'أ', 'إ', 'آ', 'ى', 'ؤ,', 'ئ ', 'ا', ' '] class Pr...
ab2413de3aee83c51e32eff16845e79a1d77bb2a
PandaWhoCodes/mera_photo
/mera_photo/file_handler.py
1,085
3.65625
4
""" All file handling functions. """ import glob import os from pathlib import Path def get_train_image(path): """ returns the one training image in each folder :return: image path """ images = glob.glob(path + "/*.jpg") return images[0] def get_images(path): """ Checks the folder for...
78d41275a69450f87241d0d1af77eeda084fe51a
faalkao/image_download
/small_area.py
3,131
3.5
4
import numpy as np import datetime import json from geojson import Polygon from sentinelsat import SentinelAPI, read_geojson, geojson_to_wkt print(''' You should have already installed numpy, json, geojson, and sentinelsat. ''') answer = input('Are you ready? [yes/no]: ') print('') if not answer in ('yes', 'YES', ...
02c0ef2c882e7f406caf6e08da1594f71d770d31
nsaintjust/projects
/diceroll.py
2,458
3.671875
4
import random def addToRange(numList): '''called with the number inputed by user and returns the range+1''' return [i + 1 for i in numList] def convToDict(seq): '''also called with number inputed by user and intializes a tracking dictionary {1:0,2:0,n:0} ''' tempDict = {} for i,item in enumer...
1d799bd871fb74cd2f80d7082f98f3e9bfbe92fa
josestg/Coding-Interview-py
/Array-String/isUnique.py
500
4.09375
4
""" Is Unique: Implement an algorithm to determine if a string has all unique characters. What if you cannot use additional data structures? """ def isUnique(string): # Asume 128 ASCII if len(string) > 128: return False char_set = [False]*128 for i in range(len(string)): char_in_int =...
93d95e63c4ad39a1c1002453c7c2dfe89fbc2624
Aswin2289/LuminarPython
/LuminarPythonPrograms/Operators/ArithematicOperator.py
452
4.3125
4
#+,-,*,/,%,//,**, num1=int(input("Enter ur num1")) #int() is using to type cast #print(type(num1)) to check the type num2=int(input("Enter ur num2")) add=num1+num2 print("addition=",add) sub=num1-num2 print("Substration=",sub) mul=num1*num2 print("Multiplication=",mul) div=num2/num1 print("division=",div) mod=n...
a2743cce5e1c7b142b729c950e9dbe7e84097d5a
Edward-Sekula/OS-GCSE-computing-course
/python/Rock, paper, scissors.py
812
3.640625
4
import random print('rock,paper,scissors') ch = ('r','p','s') ps = (0) cs = (0) while True: if ps<10 and cs<10: x = input() y = x[0].lower() z = random.choice(ch) if y == ('r') and z == ('s') or y == ('p') and z == ('r') or y == ('s') and z == ('p'): print('y...
21a8a69bbb9102b9e2aaa2312563d3e9aa86c207
TripleChoco/ubb
/sem2/Algoritmica Grafelor/practical work no. 2/main.py
6,319
4.0625
4
# 3. Write a program that finds the connected components of an undirected # graph using a depth-first traversal of the graph. #!/usr/bin/python3 # Design and implement an abstract data type directed graph and a function (either a member function or an external one, as your choice) for reading a directed graph from ...
2ab5821cff1f652846bc6c31fd934d3b97a3dec4
coole123/NPTEL_Assignments
/The Joy of Computing using Python/Assignments24_EMail.py
498
4.3125
4
''' Assuming that we have some email addresses in the "username@companyname.com" format, please write program to print the company name of a given email address. Both user names and company names are composed of letters only. Input Format: The first line of the input contains an email address. Output Format: Print ...
b196dc3cf9911b594b6e62e8a9b6490542da7a37
AzzyOxx/pec-atividades
/sem03-q4-acrescentaOuDescontaValorX.py
992
4.0625
4
#início de uma função nomeada "percentual", com dois argumetos def percentual(valor, porcentagem): #retorno da função para porcentagem descontada do "valor" return valor * (porcentagem / 100) #variável "pr", do tipo float, recebe um valor a partir da leitura do teclado pr = float(input("Preço: ")) #variável "v...
f773d3701ae38f93cff2fba843d3a5df1c3fbd59
RiddhiRex/Leetcode
/intersection-of-two-linked-lists.py
1,222
3.65625
4
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def getIntersectionNode(self, headA, headB): """ :type head1, head1: ListNode :rtype: ListNode """ if headA==...
3a91f0d2b2126a9f61db54b4a345f25a75843e52
Willyb15/data-analysis-python
/week1/day2-intro_python/warmups/warmup.py
1,339
4.125
4
# Problem 1 # def multiply(): # num1 = int(raw_input('Type a number')) # while num1 < 1: # num1 = int(raw_input('your number is negative, enter a positive')) # num2 = int(raw_input('Type a number')) # while num2 < 1: # num2 = int(raw_input('your number is negative, enter a positive')) #...
2adce5f8b219414c6ee7ac09299dc65c9b98c3a7
DoctorDroid/CodeSignal
/minimalNumberOfCoins.py
825
4.03125
4
def minimalNumberOfCoins(coins, price): ''' U- Use the least amount of coins to buy something given an array of coin values and a price. P- begining with the largest coin, use floor division to find the number of those coins that can be used, then send the remaining price to the next largest coin until...
c32dc21d3a4c78b5adf9d32b7e1ad2d0ceed5e71
MarcusbeloV2/Codekai_Feedback
/ExBonus--Duplicate_Letters.py
2,048
4.03125
4
#Duplicate encoder, write a program that convert a string into a new string, where if a chacracter is unique it becomes "(" if not, it becomes ")" x = input("Please write a word: ") len1 = (len(x)-1) #Here len1 will be used for index, which can´t have the same number as len because it starts with 0. i2 = -1 i = -1...
4b24bafe711957bb952c3b842c14e90cc0fe4f68
nurnaff/bangkit
/temp.py
6,114
3.609375
4
a = 5 print(a, "is of type", type(a)) x=[0]*10005; #inisialisasi array 0 sebanyak 10005; x[0]=0 x[1]=1; #x[1]=1 for j in range(2,10001): x[j]=x[j-1]+x[j-2] # Fibonacci print(x[10000]," ") x = [5,10,15,20,25,30,35,40] print(x[5]) print(x[-1]) print(x[3:5]) print(x[...
0d2b39553c7936f795782373d6f1d5827b233d34
nanli-7/algorithms
/33-search-in-rotated-sorted-array.py
2,928
4.03125
4
""" 33. Search in Rotated Sorted Array Topic: binary-search, array; (Medium Level) Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. (i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]). You are given a target value to search. If found in the array return its index, oth...
9023f105432861f688a9a64697f21a21195c0586
Jonie23/python-guessing-game
/modules/getGuessModule.py
588
3.90625
4
def getGuess(alreadyGuessed): # Returns the letter the player entered. This funcion makes sure the player entered a single letter and not somethig else. while True: print('Guess a letter.') guess = input() guess = guess.lower() if len(guess) != 1: print('Please enter ...
652753950d641e03cc2fb58e7f32e0f106c642db
lovekarlsson18/kyh-practice
/guessgame.py
910
3.5625
4
import random n = random.randint(1, 100) print("Jag tänker på ett tal mellan 1-100. Gissa vilket?") gissning = 0 def ask_number(): text = input("Din gissning: ") as_number = int(text) return as_number def mainloop(gissning): while True: as_number = ask_number() if as_number == n: ...