blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
e203b0450d45446a5c9ef5f962e3a6420e72f0de | borislavstoychev/Soft_Uni | /soft_uni_OOP/Iterators and Generators/exercise/prime_numbers_8.py | 302 | 3.78125 | 4 | def is_prime(num):
for factor in range(2, num):
if num % factor == 0:
return False
return True
def get_primes(some_list):
for el in [num for num in some_list if num > 1]:
if is_prime(el):
yield el
print(list(get_primes([2, 4, 3, 5, 6, 9, 1, 0]))) |
7bdb4b754c7a11cff2a48bd3f059778abf80e518 | borislavstoychev/Soft_Uni | /soft_uni_fundamentals/Dictionaries/lab/1_bakery.py | 187 | 3.6875 | 4 | foods = input().split()
foods_dic = {}
for index in range(0, len(foods), 2):
key = foods[index]
value = foods[index + 1]
foods_dic[key] = int(value)
print(foods_dic)
|
3e904ccea3800a3af90f61194e0e3ada8fec9b66 | borislavstoychev/Soft_Uni | /soft_uni_fundamentals/Dictionaries/exercises/06_courses.py | 507 | 3.59375 | 4 | def get_info(my_dict):
for (key, value) in dict(sorted(my_dict.items(), key=lambda el: -len(el[1]))).items():
print(f'{key}: {len(value)}')
print('--' + ' ' + "\n-- ".join(sorted(value)))
return exit()
curses = {}
while True:
line = input()
if line == "end":
get_info... |
c8b7afd6a664a024e8353f637a195da14be571da | borislavstoychev/Soft_Uni | /soft_uni_fundamentals/final_exam_preparation/15 August 2020/1_the_imitation_game.py | 739 | 3.75 | 4 | line = input()
commands = input()
while not commands == "Decode":
try:
command, number_of_letters = commands.split("|")
number_of_letters = int(number_of_letters)
if command == "Move":
line = line[number_of_letters:] + line[:number_of_letters]
except ValueError:
... |
a2378ca8d7d7fb365ba67a3536e6f46535347a5e | borislavstoychev/Soft_Uni | /soft_uni_advanced/Lists as Stacks and Queues/lab/2_matching_brackets.py | 197 | 3.5625 | 4 | line = input()
start = []
for index in range(len(line)):
if line[index] == "(":
start.append(index)
elif line[index] == ")":
print(line[start.pop():index + 1])
|
33aa5069349dab772d2b7d5b72b9f660c9e51441 | borislavstoychev/Soft_Uni | /soft_uni_OOP/Encapsulation/exercise/wild_cat_zoo_1/project/zoo.py | 3,718 | 3.796875 | 4 | class Zoo:
# Private attribute animal_capacity: number
# Private attribute workers_capacity: number
# Private attribute budget: number
# Public attribute name: string
# Public attribute animals: list (empty upon initialization)
# Public attribute workers: list (empty upon initialization)
def... |
4291a372ccbf07ad41ebda728f4ef1114e69697d | borislavstoychev/Soft_Uni | /soft_uni_basic/Conditional Statements/advanced/more_exercise/01. Rectangle of 10 x 10 Stars.py | 191 | 3.6875 | 4 | for i in range(9):
print(chr(42), end='')
for j in range(9):
print(chr(42))
for k in range(9,):
print(chr(42), end='')
for j in range(1):
print(chr(42), end="") |
918e0ffd95c248f6af1b12227f2ed45af6e4da10 | borislavstoychev/Soft_Uni | /soft_uni_fundamentals/final_exam_preparation/final_13_12_2020/2.3.py | 553 | 3.671875 | 4 | import re
pattern = r"!(?P<command>[A-Z][a-z]{2,})!:\[(?P<message>[a-zA-Z]{8,})\]"
n = int(input())
for _ in range(n):
data = input()
if re.match(pattern, data):
command, message = data.split("!:[")
command = command[1:]
message = message[:-1]
letters_list = []
... |
a944263a2af276db4a8624a0a54669cf2b068db6 | borislavstoychev/Soft_Uni | /soft_uni_basic/Nested Loops/more_exercises/01. Unique PIN Codes 2.py | 252 | 3.734375 | 4 | n1 = int(input())
n2 = int(input())
n3 = int(input())
for i in range(2, n1 + 1, 2):
for j in range(2, n2 + 1):
for k in range(2, n3 + 1, 2):
if j == 2 or j == 3 or j == 5 or j == 7:
print(f"{i} {j} {k}") |
3f849e9f634396b67906c6536751af8604151dc7 | borislavstoychev/Soft_Uni | /soft_uni_basic/While Loop/lab/07. Min Number.py | 183 | 3.9375 | 4 | import sys
data = input()
min_num = sys.maxsize
while data != 'Stop':
num = int(data)
if num < min_num:
min_num = num
data = input()
print(min_num) |
b7c3725197afb39f400bf31960d3bef46599566d | borislavstoychev/Soft_Uni | /soft_uni_OOP/Testing/lab/testings/test_car_manager_4.py | 2,511 | 3.625 | 4 | from car_manager_4 import Car
import unittest
class CarTest(unittest.TestCase):
def setUp(self) -> None:
self.car = Car(2007, "Mercedes", 10, 70)
def test_constructor(self):
self.assertEqual(2007, self.car.make)
self.assertEqual("Mercedes", self.car.model)
self.assertEqual(10... |
7ef3dc0ac59d0b610ab31ac9eb7d2b7f7915216d | borislavstoychev/Soft_Uni | /soft_uni_basic/Conditional Statements/advanced/exercise/08. On Time for the Exam.py | 1,380 | 4.125 | 4 | hour_exam = int(input())
minute_exam = int(input())
arrival_hour = int(input())
arrival_minute = int(input())
total_exam_minutes = hour_exam * 60 + minute_exam
total_arrival_minutes = arrival_hour * 60 + arrival_minute
if total_exam_minutes - 30 <= total_arrival_minutes <= total_exam_minutes:
print('On t... |
c6614d76a9e56c0da8f8c9df99c7ab68f39a1ecd | borislavstoychev/Soft_Uni | /soft_uni_basic/For Loop/exercise/03. Odd - Even Position.py | 984 | 3.671875 | 4 | import sys
n = int(input())
even_max, odd_max = (-sys.maxsize, -sys.maxsize)
odd_min, even_min = (sys.maxsize, sys.maxsize)
sum_even = 0
sum_odd = 0
for i in range(1, n + 1):
num = float(input())
if i % 2 == 0:
sum_even += num
if num > even_max:
even_max = num
i... |
8578254e24dab2ec3e093ff6167347a088fe3c53 | borislavstoychev/Soft_Uni | /soft_uni_basic/Nested Loops/lab/04. Sum of Two Numbers .py | 545 | 3.609375 | 4 | starting_number = int(input())
last_number = int(input())
magic_number = int(input())
combinations = 0
is_found = False
for i in range(starting_number, last_number + 1):
for j in range(starting_number, last_number + 1):
combinations += 1
if i + j == magic_number:
print(f"Combina... |
9481109ba0d19ce64b31935f40f7e65a54955428 | borislavstoychev/Soft_Uni | /soft_uni_OOP/EXAM_10_04_2020/testing/tests/test_train.py | 1,319 | 3.6875 | 4 | from unittest import TestCase, main
from project.train.train import Train
class TestTrain(TestCase):
def setUp(self) -> None:
self.train = Train("Bobby", 5)
def test_constructor(self):
self.assertEqual("Bobby", self.train.name)
self.assertEqual(5, self.train.capacity)
self.a... |
c30dfbcc866d0be2306476e9f098aa523a5230da | borislavstoychev/Soft_Uni | /soft_uni_fundamentals/Regular Expressions/exercises/04_extract_emails.py | 220 | 3.84375 | 4 | import re
email = input()
pattern = r"(^|(?<=\s))[a-zA-Z0-9]+[\._-]?[a-zA-Z0-9]+@[a-zA-Z]+\-?[a-zA-Z]+(\.[a-zA-Z]+\-?[a-zA-Z]+)+\b"
matches = re.finditer(pattern, email)
for match in matches:
print(match[0]) |
61f16d107543a6d9c771425116c3941fd3e7c063 | borislavstoychev/Soft_Uni | /soft_uni_fundamentals/final_exam_preparation/15 August 2020/02_ad_astra.py | 456 | 3.640625 | 4 | import re
line = input()
pattern = r"(#|\|)(?P<name>[A-Za-z ]+)\1(?P<date>\d{2}/\d{2}/\d{2})\1(?P<calories>([0-9][0-9]{0,3}|10000))\1"
total_calories = 0
for match in re.finditer(pattern, line):
total_calories += int(match.group(4))
print(f"You have food to last you for: {total_calories // 2000} days!")
fo... |
3473b00828e9762a3734f052cf42c762c598fd80 | ageichik2015/laboratornay5 | /Perebor.py | 236 | 3.890625 | 4 | y=int(input('Введите значение y: '))
a=int(input('Введите значение a: '))
p=int(input('Введите значение p: '))
for x in range(0,p):
if (a**x)%p==y:
print("x =", x)
break
|
e35b30944c21aff75dd69a24ee4c4b67645118d0 | Abhi-tech-09/Python-Data-Visualisation | /graph1.py | 987 | 3.65625 | 4 | # Shows the sales of furniture , clothing and electronics throughout the year.
from main import *
import matplotlib.pyplot as plt
Month = ["Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
f = [0 for i in range(12)]
c = [0 for i in range(12)]
e = [0 for i in range(12)]
fo... |
26e482f706e411db83bdd137b34efdd1116680aa | myricoi/bootcamp19 | /test_prime.py | 1,187 | 4.1875 | 4 | import unittest
import prime
# returns a list
# returns a message for wrong input
# returns correct list for small input
# returns correct list for large input
# Empty list if there are no primes
class Prime_test(unittest.TestCase):
def test_returns_a_list(self):
a=prime.gen_prime(0)
self.assertTrue(isinstance(a,... |
2786a39d2b48542d27e27e8b2f15d8e6246e9218 | myricoi/bootcamp19 | /voter.py | 2,597 | 3.8125 | 4 | class Voters(object):
no_of_voters=0
results={'trump':0,'bush':0,'clinton':0,'sanders':0}
def show_no_of_voters(self,category):
raise NotImplementedError
def vote(self,vote_who):
raise NotImplementedError
def show_results(self,category):
raise NotImplementedError
class Democrat_voters(Voters):
no_of_v... |
4f75b517101586f7f73ea70d520b53f5b9d57623 | Nmazil-Dev/Learning | /index.py | 907 | 4.28125 | 4 | #Practicing indexes Codecademy
# [] after a string will show that character
def bingo():
print "BINGO"
word = "bingo"
# len(*variable*) will show the length/amount of characters that a string is
word1 = len(word)
first_letter = "BINGO"[0]
print "The first letter of BINGO is " + str(first_letter)
print... |
57c926d8aab3c8f9d31d79a44fc31e39d00a19bd | ogeorg/quizz | /QuizzReader/reader.py | 2,482 | 3.609375 | 4 | #!/usr/bin/env python
from xml.dom import minidom as DOM
class Question:
"""
A question object is made of a question and an answer
"""
def __init__(self, question, answer):
self.question = question
self.answer = answer
def __str__(self):
return "%s -> %s" ... |
35fcf1cc1168cef1da4f30c9c21499a4af52350a | momotaro98/python-codes-for-learning | /quick_sort.py | 371 | 3.78125 | 4 | def quick_sort(arr):
left = []
right = []
if len(arr) <= 1:
return arr
pivot = arr[0]
arr = arr[1:]
for ele in arr:
if ele <= pivot:
left.append(ele) # 手続きしてる
elif ele > pivot:
right.append(ele)
left = quick_sort(left)
right = quick_sort(ri... |
ccefd1611c6265f16b99009ad5f9a0d9dc8a9c1a | Scott-E-G/Python-Playyground | /productofn.py | 236 | 4 | 4 | x = 1
prod = 1
n = input("Please enter a positive, non zero integer: ")
#while x != n:
# prod = x * prod
# x = x + 1
#prod = prod * n
for x in range(1, n+1):
prod = x * prod
print (prod)
print('Your total is ' + str(prod)) |
4a0c0cc28eb064332c4ddedda314cad7db67268d | Loldozen/GoogleWebScraping-CLI | /imageScraper.py | 1,595 | 3.65625 | 4 | #! python3
# This program accepts a url as a string, scrapes
# the Google images and returns the url of the first image
"""
ToDo:
1. Get the search keyword for the CLI
2. Create a directory for the images
3. Download the pages with the requests module
4. Find the url of the image
5. Download the image
6. Save the imag... |
6d3caf1b1879a1a8a381e6dec86f220c28b32884 | tagonata/daily_programming | /daily_programming/200307_51.py | 1,597 | 3.984375 | 4 | class Node(object):
def __init__(self, data, next=None):
self.data = data
self.next = next
class LinkedList(object):
def __init__(self):
self.head = None
def insert(self, data):
if self.head is None:
self.head = Node(data)
else:
current = se... |
fb9b0498bedb4b6c858c56eaefc8fcfb14ee4ccf | tagonata/daily_programming | /daily_programming/200406_59.py | 353 | 3.53125 | 4 | # 09/04/2019
def solution(input_list):
index = 0
for _ in range(len(input_list)):
if input_list[index] == 1:
input_list.append(1)
input_list.pop(index)
else:
index += 1
Input_list = [1, 0, 1, 0, 1, 0, 0, 1]
print(f'Input: {Input_list}')
solution(Input_list... |
9771aacdce94f294c58168a4c80835ee38039f94 | tagonata/daily_programming | /daily_programming/200113_8.py | 659 | 3.8125 | 4 | def second_big_number(number_list):
if number_list[0] > number_list[1]:
first = number_list[0]
second = number_list[1]
else:
first = number_list[0]
second = number_list[1]
for cur_num in number_list[1:]:
if cur_num > second:
if first > cur_num:
... |
15462987ff54e64f2ef82b066c02cb390beb5bf2 | tagonata/daily_programming | /daily_programming/200107_3.py | 366 | 3.640625 | 4 | def a_func(x, y, string):
if x == 0 and y == 0:
print(string)
return
elif x == y:
a_func(x-1, y, string + "(")
elif x == 0:
a_func(x, y-1, string + ")")
else:
a_func(x-1, y, string + "(")
a_func(x, y-1, string + ")")
N = 3
open = N - 1
close = N
start_st... |
89e119f6aef89680c9364f4db9182cc77e289f9d | tagonata/daily_programming | /daily_programming/200112_5.py | 495 | 4.03125 | 4 | def search(Input_list, target):
Input_dict = dict(zip(Input_list, range(len(Input_list))))
# print(Input_dict)
# for item in Input_dict.popitem():
# print(item)
for value, index in Input_dict.items():
set = target - value
if set in Input_dict.keys():
return [index, ... |
e9f7357b8a713d2b0c7c284cdc28fd7b59f08b57 | tagonata/daily_programming | /daily_programming/200226_34.py | 1,597 | 3.90625 | 4 | def Quick_sort(input_list):
def sort(start, end):
if start >= end:
return
mid = partition(start, end)
sort(start, mid - 1)
sort(mid, end)
def partition(start, end):
pivot = input_list[(start + end) // 2]
while start <= end:
while pivot > ... |
40b20a4c85bbc5ef5bae8f856f09da26e28f84cd | tagonata/daily_programming | /daily_programming/200227_41.py | 1,251 | 3.9375 | 4 | class Node(object):
def __init__(self, data):
self.data = data
self.left = None
self.right = None
class BinarySearchTree(object):
def __init__(self):
self.root = None
def insert(self, input_list):
self.root = self._insert_value(input_list)
def _insert_value(se... |
1bf925def67fd390d1aa19354f35f7e46a35b29c | tagonata/daily_programming | /daily_programming/200227_39.py | 1,575 | 4.0625 | 4 | class Node(object):
def __init__(self, data):
self.data = data
self.next = None
class LinkedList(object):
def __init__(self):
self.head = None
def insert(self, data):
self._insert_value(self.head, data)
def _insert_value(self, node, data):
if node is None:
... |
9bde1b3d29528f78da3776b6850c736027296883 | mmajia/repository01 | /Mysql练习/books查询数据.py | 633 | 3.828125 | 4 | from a创建连接数据库 import db,cursor
"""
cursor.execute("select * from books")#查询books表记录
#result1 = cursor.fetchone()#返回的是一个元组,表里的第一条记录
#result1 = cursor.fetchmany(2)#返回的是一个元组,表里的几条记录,括号里不给值默认是1
#result1 = cursor.fetchall()#返回的是一个元组,表里的所有记录
print(result1)
cursor.close()
db.close()
"""
"""
# n = 70
# cursor.execute(f"SELECT ... |
352d100f1297037dfe1cafb21d72cf6538cb62ea | seangsokhai/game_card | /Deck-Of-Cards-Python/card.py | 1,339 | 3.90625 | 4 | import random
class Card(object):
def init(self, suit, val):
self.suit = suit
self.value = val
# Implementing build in methods so that you can print a card object
def unicode(self):
return self.show()
def str(self):
return self.show()
def repr(self):
return... |
9cd6f110cb7002341b61ee14e84c58544ada25c6 | trainorpj/paradise-lost | /python/helpers.py | 3,091 | 3.65625 | 4 | """
This module offers some helper functions for the
non-computational aspects of this project. For example,
it has functions that use regular expressions to parse
the text---not particularly interesting, topologically
"""
import re # regular expression library
import json
import itertools
def getWindow(text, firs... |
185cd84a5f61ce99daeaea09a9cc5c2844ad0f6e | barbaramchd/quocabot | /bot.py | 2,042 | 3.640625 | 4 | import requests
import json
def get_answer():
# get the input
user_input = input()
# check if input can be converted to int
# if yes, return int
if user_input.isnumeric():
return int(user_input)
# if not, call nlu server
# return intent
else:
url = "http://localhost:500... |
2bc89954d1f209ea36d1618ed171716c397488e1 | Lv296TAQC/python_tasks | /tasks/task_178d.py | 1,008 | 4.28125 | 4 | """
This module solves task 178_г from zadachi.pdf.
"""
from sys import argv
def task_function(numbers):
"""
Description: convert string into int,
checks how many numbers in list are less than
the sum of the previous and next numbers.
Args: list of strings in int number... |
2bf294fce7e4c54bd0d63fbcdb0938fa565f936d | Lv296TAQC/python_tasks | /tasks/task_330.py | 763 | 3.75 | 4 | # -*- coding: utf-8 -*-
"""This module solves the task 330 from zadachi.pd"""
from tasks.task_227 import divisor
def minus_last(num: int) -> int:
"""
the sum of all the divisors except itself
:param num: int numbers
:return: int sum of all the divisors except itself (num)
"""
sum_div = 0
... |
2161abfac4233055f8d415a82d156f1fc6416594 | Lv296TAQC/python_tasks | /tasks/task_86g.py | 318 | 3.90625 | 4 | """Finding interchangeable sum of digits n"""
def total_sum1(number):
"""Method finding total_sum"""
array = [int(d) for d in str(number)]
sum1 = 0
for index, element in enumerate(array):
if index % 2 == 0:
sum1 += element
else:
sum1 -= element
return sum1
|
ba6e939a8bf3c36017dcb5949f9d7395bd14e425 | Lv296TAQC/python_tasks | /tasks/task_88.py | 508 | 3.921875 | 4 | # -*- coding: utf-8 -*-
"""This module solves the task 88a from zadachi.pd"""
def three_go_in(numb: int) -> bool:
"""
checks for the entry of 3 to the square of the number
:param numb :int any number
:return:True if 3 entry to the square of the number
False if 3 not entry to the square of ... |
26b5c847f31fa676a92fa152894e57877d6a08ce | Lv296TAQC/python_tasks | /tasks/task_178b.py | 676 | 4.03125 | 4 | # -*- coding: utf-8 -*-
"""This module solves the task 178b from zadachi.pd"""
import math
def count_sq(posl: list) -> int:
"""
count the number is the square root of a even number
:param posl:list contains numbers
:return:int count of the number which is a square root of a even number
"""
po... |
465dd0d9e39146a282c88dfd2e70e1b805f6c089 | vmthanh/coding-revise | /leaders-in-an-array.py | 688 | 4.0625 | 4 | """
Given an array of positive integers. Your task is to find the leaders in the array.
Note: An element of array is leader if it is greater than or equal to all the elements to its right side.
Also, the rightmost element is always a leader.
"""
def leader_arr(arr):
res = str(arr[len(arr)-1])
maxVal = arr[len... |
d57428f8418491c57fb8ad20dab80847a208055b | hari526/Hari-Python | /Examples/prize.py | 516 | 4 | 4 | def which_prize():
points = int(input("enter the points they scored : "))
if(points <= 50):
print("Congratulations! You have won a wooden rabbit!")
elif(points >=51 and points <= 150):
print("Oh dear, no prize this time.")
elif(points >=151 and points <= 180):
print("Congratulati... |
c49fabde241d4e305b8a3ce19c20735178136b39 | hari526/Hari-Python | /Udacity/IntroductionToPythonProgramming/Lesson2/If_1.py | 315 | 3.875 | 4 | #First Example - uncomment lines or change values to test the code
phone_balance = 7.62
bank_balance = 1984.39
#phone_balance = 12.34
#bank_balance = 25
if phone_balance < 10:
phone_balance += 10
bank_balance -= 10
print("Current Phone Balance: ",phone_balance)
print("Current Bank Balance: ",bank_balance)
|
de6c2ab60eed14c6077ffd3156bcf2064f988446 | slsefe/data-structure | /python/03_stack/stack.py | 2,730 | 4.34375 | 4 | from typing import List
class SqStack:
'''顺序结构的栈,使用python的内建类型list列表实现'''
def __init__(self, data: List[int]):
'''初始化'''
self.items = data
print(self.items)
def size(self):
'''栈元素个数'''
print('the stack has ' + str(self.items.__len__()) + ' elements')
return... |
683b23e3e54dc8aa92b48d7a84cd758c46c329e7 | seansweeney/esri2open | /Install/esri2open/topojson/bounds.py | 475 | 3.65625 | 4 | from mytypes import Types
class Bounds(Types):
def __init__(self):
self.x0=self.y0=float('inf')
self.x1=self.y1=-float('inf')
def point (self,point):
x = point[0]
y = point[1]
if x < self.x0:
self.x0 = x
if x > self.x1:
self.x1 = x
... |
f2ddff5128722da60cdce7d2f08814de44bed2b7 | AdkPete/Meteor_Stats | /test_stats.py | 1,371 | 3.5 | 4 | ###All that this script really does is plug data into scipy.
###Mostly here so that I can keep track of which test is which
import scipy.stats as stats
import sys
import numpy as np
import unittest
import mass
def t_test(mean , A , B = None):
'''
Takes in an array or list A and a mean to compare to.
Tests to see... |
8986f6ce5686c218099082f39eb7cd37831f9370 | 0bruhburger0/fin_bot | /table.py | 3,886 | 3.90625 | 4 | import sqlite3
from typing import Dict, List, Tuple
conn = sqlite3.connect("db.db", check_same_thread=False)
cursor = conn.cursor()
# Таблица с расходами
cursor.execute("""create table if not exists expense (user_id integer,
id integer primary key,
amount integer,
crea... |
faa941c84977d56d71a62ae89242190db278fc31 | Yursksf1/example | /amotizacion_ej3.py | 1,503 | 3.5625 | 4 | def amortizacion_1(monto, periodo, t_interes):
'''
Geneate calculation of payments
:params: monto monto a prestar. Ie, 1000000
:params: periodo tiempo de plazos. Ie, 24
:params: t_interes tasa de interes. Ie, 0.1
'''
mensaje = '''Vamos a calcular la amortizacion de {monto}
a un plazo de... |
324f55ad78aedabf91772378b6eb662fb38b78a5 | ihaku4/leetcode | /intersection_of_two_linked_lists.py | 1,027 | 3.6875 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# @param two ListNodes
# @return the intersected ListNode
def getIntersectionNode(self, headA, headB):
if headA is None or headB is None:
... |
faa011fce8b9925862312a815be6650258bfb6c9 | ihaku4/leetcode | /valid_palindrome.py | 1,088 | 3.78125 | 4 | class Solution:
# c should be upper case, before call
def isAlpha(self, c):
return c >= 'A' and c <= 'Z' or \
c >= '0' and c <= '9'
# @param s, a string
# @return a boolean
def isPalindrome(self, s):
s = s.upper()
head = 0
tail = len(s) - 1
while... |
e34d393b720e2a2a511cbc348a0e0d7c77233b04 | ihaku4/leetcode | /same_tree.py | 2,126 | 3.65625 | 4 | # Definition for a binary tree node
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# @param p, a tree node
# @param q, a tree node
# @return a boolean
def isSameTree(self, p, q):
if not p and not q:
... |
78131b187daa22815dc2cd1c66b0d734b86aacd8 | ihaku4/leetcode | /clone_graph.py | 1,463 | 3.765625 | 4 | # Definition for a undirected graph node
class UndirectedGraphNode:
def __init__(self, x):
self.label = x
self.neighbors = []
class Solution:
# @param node, a undirected graph node
# @return a undirected graph node
def cloneGraph(self, node):
if not node:
return None... |
b88e6da17199abe68c3eca5aef9822869f50bfd8 | ihaku4/leetcode | /zigzag_conversion.py | 836 | 3.546875 | 4 | class Solution:
# @return a string
def convert(self, s, nRows):
if nRows == 1: # TODO test remove this
return s
m = {}
for i in range(1, nRows + 1):
m[i] = []
i = 1
add = 1
for c in s:
m[i].extend(c) # XXX
if i == ... |
77093ee07a084661ed0c41bc3b5dadb8dfca40cb | emanuelepesce/NetworksSimulator | /source/DirectedNetworkAnalyzer.py | 14,043 | 3.5625 | 4 | #----------------------------------------------------------------------
# DirectedNetworkAnalyzer
#
# Contains the class which implements methods for analyzing graphs
#
# Author: Emanuele Pesce
#----------------------------------------------------------------------
import NaiveDirectedGraph as ng
import sys
... |
25874544136c9280ddd9e6c7378bb17aab8dca73 | Walter0210/pruebaDevEMSER | /suma.py | 1,618 | 3.984375 | 4 | import logging
logging.basicConfig(filename="logger.txt", level=logging.DEBUG)
def operacion(flag):
strRes = False
try:
a = float(input('Ingrese un numero: '))
b = float(input('Ingrese otro numero: '))
if flag:
res = a + b
strRes = ('\t' + str(a) + ' + ' + str(b)... |
cabf6a29d428014400f224faaa7025bbdab64d88 | PrVrSs/tng | /patterns/behavioral/cor/py_pattern/cor.py | 532 | 3.515625 | 4 | """
Exercise from https://python-3-patterns-idioms-test.readthedocs.io/en/latest/FunctionObjects.html
Implement Chain of Responsibility to create an “expert system” that solves problems by successively trying one solution
after another until one matches. You should be able to dynamically add solutions to the expert sy... |
0ea091b7e3bf0beb05e08f978af7cc9c06cf6a00 | fformenti/University_of_Washington | /Introduction to Data Science/assignment3/answer4.py | 771 | 3.703125 | 4 | import MapReduce
import sys
"""
Inverted Index using Python MapReduce Framework
"""
mr = MapReduce.MapReduce()
# =============================
# Do not modify above this line
def mapper(record):
# key: person
# value: friend
person = record[0]
friend = record[1]
mr.emit_... |
7bb472d4d1d61682c15e6d91122c40bf4ec4ce49 | rpmoore8/leetcode_problems | /leetcode_problems/queue_reconstruction_by_height.py | 1,224 | 4.09375 | 4 | """
//////////////////////////////
Queue Reconstruction By Height
//////////////////////////////
Suppose you have a random list of people standing in a queue. Each person is described by a pair of integers (h, k), where h is the height of the person and k is the number of people in front of this person who have a heig... |
022f45d41364875974de0ab96fe788a411b64bdf | KritikaVersha/Machine-Learning-Recommendation-System-based-on-Facebook-likes-and-interests | /Source Code and files/Part1a/Histogram.py | 1,583 | 3.53125 | 4 | #!/usr/bin/env python
import string
import matplotlib.pyplot as plt
import numpy as np
file1 =open('C:\\Users\\Kri89\\Desktop\\reduced1.csv', 'r')
likes={}
xplot=[]
yplot=[]
alnum = set(string.letters + string.digits)
for i in file1.readlines():
list1= i.replace("\n","").split(",")
list1.remove(list1[0])
... |
b20660dd1f85cfb9e14fd3f15c5542ef2912d53d | oakejp12/AutomateExpenseReports | /src/parser.py | 1,545 | 3.609375 | 4 | '''
Parse the Outlook message bodies into
a readable format.
'''
from outlook import messageBodies
import re
from decimal import Decimal
class Parse():
def __init__(self, body):
self.body = body
self.visaSearch = r'(Visa \*[0-9]+)(.*)\$([0-9]+.[0-9]+)'
def __searchForFare__(s... |
b98dcd5d12088c692103e26bdfca94cddeb35586 | mmalarz/google-competitions | /problem-a-2014.py | 4,680 | 3.78125 | 4 | import itertools
TEST_FILE_NAME = 'A-small-practice.in'
STRING_TO_INT_NUMBERS_MAPPING = {
'1111011': 9,
'1111111': 8,
'1110000': 7,
'1011111': 6,
'1011011': 5,
'0110011': 4,
'1111001': 3,
'1101101': 2,
'0110000': 1,
'1111110': 0,
}
INT_TO_STRING_NUMBERS_MAPPING = {
9: '1111... |
149144b34e4516c147bc4085f76c00191c68d338 | CptLemming/blackjack-tech-test | /tests/test_game.py | 4,830 | 3.734375 | 4 | import unittest
from unittest.mock import patch
from game import Deck, Game, Player, Dealer
class TestDeck(unittest.TestCase):
"""
Test the Game class from the Game library
"""
def test_check_returns_dealer_when_player_is_bust(self):
dealer = Dealer()
deck = Deck()
with patch... |
0e93ce4cce181b519d155e10f0c9360c75761087 | GemmaYoung/MIT_6.01SC_Solutions | /ProblemWk.1.4.9.py | 454 | 3.765625 | 4 | def extractTags(s):
L = []
record = False
for letter in s:
if record == True:
if letter == ']':
record = False
L += [elementOfL,]
elementOfL = ''
else:
elementOfL += letter
else:
if letter == ... |
3d9bbd22491ab1f4a4407a2e317c3d16f6f830b9 | GemmaYoung/MIT_6.01SC_Solutions | /ProblemWk.1.3.6.py | 3,073 | 3.5 | 4 | class Polynomial:
# Delete the pass statement below and insert your own code
def __init__(self, coefficients):
self.coeffs = [float(c) for c in coefficients]
self.highExpo = len(self.coeffs) - 1
def coeff(self, i):
if i > self.highExpo:
return 0
elif i >= 0:
... |
79d98d8c1e2234ef02bef5d97c126608b6ea6b74 | GemmaYoung/MIT_6.01SC_Solutions | /ProblemWk.1.4.3.py | 293 | 3.578125 | 4 | def evenSquares(L):
return [e**2 for e in L if e%2== 0]
##print evenSquares([])
##print evenSquares([1, 2, 3])
##print evenSquares([-2, -2.2, 0, 78.7])
def sumAbsProd(L1, L2):
return sum([abs(e1 * e2) for e1 in L1 \
for e2 in L2])
print sumAbsProd([2,-3], [4,-5])
|
f813d6f8358b22564686794747cf50e291d49bec | biggus-dickus/python-bootcamp | /homeworks/functions-test.py | 5,213 | 4 | 4 | # Make every even letter uppercase
def myfunc(input_str):
str_arr = list(input_str)
str_arr[0] = str_arr[0].lower()
for i, char in enumerate(str_arr):
if (i + 1) % 2 == 0:
str_arr[i] = char.upper()
return ''.join(str_arr)
print(myfunc('Anthropomorphism'))
# LESSER OF TWO EVENS:
#... |
571384c100ef1e121855d2bb8daec02636fad69f | mranta-ai/Opportunities_of_AI | /_build/jupyter_execute/2_3_IMDB_example.py | 12,871 | 4.25 | 4 | ## NLP example - IMDB
In this example, we build a simple neural network model to predict the sentiment of movie reviews.
First, we load the IMDB data that is included in the **Keras** library (part of **Tensorflow**). Also, we load the **preprocessing** module.
from tensorflow.keras.datasets import imdb
from tensorf... |
e4d1d8b243a453dbabe58ba3563ba3a21eb82c6f | Eminentzeal/add.py | /add.py | 181 | 4 | 4 | a = int(input("enter first number: "))
b = int(input("enter second number: "))
c = int(input("enter third number: "))
sum = a + b + c
print("The sum of the three number is:", sum) |
cd990d0c775c83b70db89867b99e19c9c4c4259c | matthavik/Advent-of-Code-2020 | /Day 03 - Toboggan Trajectory/D3 Python Part 1-2.py | 992 | 3.90625 | 4 | # Maybe more condensed than it needs to be... but it was fun! Tried two different methods
# Part 1 - using a generator!
def mountain_line():
count = -3
for line in open("input.txt"):
count = (count + 3) % (len(line) - 1)
yield line[count]
mountain_gen = mountain_line()
trees = sum(char == "#"... |
fe71cf1153da23fdae3fcc429f59ffa3ff03a434 | SudharshanNagarajan17/Breaking-RSA-using-ECM | /RSA-encryption.py | 891 | 4.03125 | 4 | def encrypt(pk, plaintext):
# Unpack the key into it's components
key, n = pk
# Generate the ciphertext based on the plaintext and key using a^b mod m
cipher = [pow(plaintext,key,n)]
return cipher
if __name__ == '__main__':
print "\nEnter the public key {e,n} for encryption:\n"
e = int(inpu... |
3401ea4c81cd15c20350dff74ecd6d6cbeb41e17 | gabrielmilano/infosatc-lp-avaliativo-01 | /exerc26.py | 185 | 3.640625 | 4 | num =int(input("Digite um valor em metros quadrados para converter em hectares :"))#receber valor para calculo
H = num*0.0001#calcular conversao em hectares
print(H)#mostrar resultado
|
855bb1daa9450079e197a138ff7d648f8dc56547 | IanWells2000/canvas | /user_active_courses.py | 701 | 3.5625 | 4 | # Using the canvas api to query Canvas LMS to locate active courses for a user
# Before using the canvas api instantiate a new canvas object
# Import the Canvas class
from canvasapi import Canvas
# Canvas API URL
API_URL = "https://canvas.instructure.com/"
# Canvas API key
API_KEY = "your access token here"
# Initial... |
2a9dae05f85638fde7e875b43c1e9d77d8f37cce | gwccu/day3-anagarcia02 | /practiceDay4.py | 596 | 4.03125 | 4 | mysteryNumber = 42
guess = int(input("Guess a number."))
while guess != mysteryNumber:
guess = int(input("Sorry! Guess again."))
print("Nice job, you guessed 42.")
#
strength = 5
print('Your strength is at 5.')
strength += 1
while strength < 10:
print('Your strength has increased to ' + str(strength))
st... |
ef23fed68d409fdcfab8ee342a4220809675a434 | wclaus22/kaggletools | /kgtools/utils.py | 425 | 3.546875 | 4 | """utils module"""
def class_weights(dataframe, column):
"""generate class weights from a dataframe and its resp. label column"""
weights = {}
for item in dataframe[column].unique():
weight = (
(1 / (len(dataframe[dataframe[column] == item]) / len(dataframe[column])))
* 1
... |
1abaac29d8f0bad1157648af3640c0634397e2f0 | poojasgada/codechefsolns | /Practice-Easy/Easy-HOTEL.py | 2,148 | 3.625 | 4 | '''
Created on Jun 21, 2013
@author: psgada
'''
'''
A holiday weekend is coming up, and Hotel Bytelandia needs to find out if it has enough rooms to accommodate all potential guests. A number of guests have made reservations. Each reservation consists of an arrival time, and a departure time. The hotel managemen... |
d6ac16b8e5e567160711c2ace181059ef4d1b28d | poojasgada/codechefsolns | /Practice-Easy/Easy-COOLING.py | 1,921 | 4.03125 | 4 | '''
Created on May 15, 2013
@author: psgada
'''
'''
The chef has just finished baking several pies, and it's time to place them on cooling racks.
The chef has exactly as many cooling racks as pies. Each cooling rack can only hold one pie, and each pie
may only be held by one cooling rack, but the chef isn't ... |
dacc3d740aafc3b9b803d2737721fa4d46ccb909 | poojasgada/codechefsolns | /Practice-Easy/Easy-AMMEAT2.py | 1,106 | 3.546875 | 4 | '''
Created on Jul 3, 2013
@author: psgada
'''
import sys
from math import floor
#Ha, we dont really need to find primes
def primes_sieve_way(n):
prime_dict = {}
for i in range(2, n+1):
prime_dict[i] = True
for i in range(2, n+1):
for j in range(i+i, n+1... |
6d24223065d8218d3018e3e58ec1e2e2efb47aaf | poojasgada/codechefsolns | /Practice-Easy/Easy-HS08TEST.py | 1,558 | 4.15625 | 4 | '''
Created on May 14, 2013
@author: psgada
'''
'''
Question:
Submit
All Submissions
All submissions for this problem are available.
Pooja would like to withdraw X $US from an ATM. The cash machine will only accept the transaction if X is a multiple of 5, and Pooja's account balance ha... |
566121d3455917f809945082c952b9343af03114 | poojasgada/codechefsolns | /Practice-Easy/Easy-VOTERS.py | 3,325 | 3.796875 | 4 | '''
Created on Jun 12, 2013
@author: psgada
'''
'''
As you might remember, the collector of Siruseri had ordered a complete revision of the Voters List. He knew that constructing the list of voters is a difficult task, prone to errors. Some voters may have been away on vacation, others may have moved during the... |
fea14286b2a578736504a4b61f35880b1da9f93d | poojasgada/codechefsolns | /Practice-Easy/Easy-DIRECTI.py | 2,908 | 4.0625 | 4 | '''
Created on Jun 23, 2013
@author: psgada
'''
'''
Chef recently printed directions from his home to a hot new restaurant across the town, but forgot to print the directions to get back home. Help Chef to transform the directions to get home from the restaurant.
A set of directions consists of several instru... |
ccebc0327eca5c97fdecadf35ffbfd9a56686385 | nikolakasev/aoc2020-python | /day15.py | 1,352 | 4.09375 | 4 |
def remember(memory, number, turn):
if number in memory.keys():
history = memory[number]
if type(history) is tuple:
# the number was spoken twice already, shift turns - forget at history[0]
memory[number] = (history[1], turn)
else:
# the number was spoken... |
b7e65fb15c7c30d84684f4be48548ad739ab8bfc | nikolakasev/aoc2020-python | /day2.py | 501 | 3.625 | 4 | import re
reg = r"(\d*)-(\d*)\s(\w*):\s(\w*)"
p = re.compile(reg)
a = []
for line in open('day2.txt').read().splitlines():
a.append(line)
count = 0
for password in a:
groups = p.match(password).groups()
i = int(groups[0])
j = int(groups[1])
letter = groups[2]
password = list(groups[3])
i... |
546f4dc04553f9d75ce138d3c3ae5caf8b0f6f26 | crunes/steven-universe | /scrape_wiki.py | 12,613 | 3.609375 | 4 | '''
STEVEN UNIVERSE: Scrape Steven Universe Wiki and analyze transcripts
Author: Charmaine Runes
This file scrapes the Steven Universe Wiki for season data and episode
transcripts, storing them in CSV files to export into a SQLite database later.
'''
import sys
import os
import csv
import bs4
import re
import dateti... |
07700ab28619f3f4440e90f982ff6fc5de3e43f5 | flavian-anselmo/data-structures-and-algorithms-in-python | /binary_tree/binary_tree2.py | 2,237 | 3.78125 | 4 | class Node:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
class BinarySearchTree:
def __init__(self):
self.root = None
def insert(self, value):
if self.root == None:
self.root = Node(value)
else:
se... |
ad61164144730ec038abd249b05f464f1af30f51 | HungryAdi/Coursework | /Probability&Statistics/hw7code/pagerank_demo.py | 1,827 | 3.609375 | 4 | '''
UCI CS177: Markov chains and Pagerank
This is DEMONSTRATION code:
- It gives an example of how to construct a state transition matrix
for the web link data, and use it to predict "random surfer" behavior.
- You may (but do not have to) reuse parts of this code in your solutions.
- It is NOT a ... |
38bc271247db31e36c724bc0ca1f026c1777ab80 | KierenJackson/Sandbox | /password_entry.py | 403 | 4.25 | 4 | """Kieren Jackson."""
MIN_LENGTH = 6
def main():
print_password = ""
password = input("Please enter your password: ")
while len(password) < MIN_LENGTH:
print("Password must at least be {} characters long".format(MIN_LENGTH))
password = input("Please enter your password: ")
for char i... |
1a8e9658d95d1224138c3e8cf8346617053b01b8 | imlegend19/CS-4101-Worksheet-Solutions | /Work Sheet 2/function.py | 1,418 | 3.78125 | 4 | import matplotlib.pyplot as plt
import numpy as np
FibArray = [1, 1]
N = 10
def fibonacci(n):
if n < 0:
print("Incorrect input")
elif n <= len(FibArray):
return FibArray[n - 1]
else:
temp_fib = fibonacci(n - 1) + fibonacci(n - 2)
FibArray.append(temp_fib)
return te... |
2cdd1d8b209ce3eaab83d0f7a817557b166c779d | xdemon1975/python | /edu/hello.py | 1,463 | 3.78125 | 4 | #!/usr/bin/python3
##strMyName = "xdemon"
##print(strMyName)
##
##nSecondNum = 20
##print(nSecondNum)
##
##print(12* 34)
##print(2**3)
##a = 20
##b = 20
##print(a > b)
##
##a = int(input("a="))
##b = int(input("b="))
##
##if a > b :
## print("value=" + str(a))
##elif a < b :
## print(b)
##else :
## print("s... |
534c226651d1d5b6f2208548977e4ae405596f7e | aamir7shahab/FellowshipPrograms | /PythonDataStructureProgrmas/ListAllFile_14.py | 125 | 3.703125 | 4 | # 14. Write a Python program to list all files in a directory in Python.
from subprocess import call
call("ls", shell=True)
|
83c8b65edf06f15ae4d7692415c97a6eefe7cc16 | aamir7shahab/FellowshipPrograms | /Basic Python/Factors.py | 853 | 4.03125 | 4 | class Factor:
# Definning constructor method
def __init__(self,number):
self.number = number
# Method to print element of the list
def printNumberOfList(numberList):
print("Factors are :", end=' ')
for i in numberList:
print(i, end=' ')
print()
# Method to find prime or not
def isPrime(number):
f... |
7844c9464b9cd505029c55a04fb16a87f2bd2a4e | benji822/100_days_of_python | /day_2/ex_2_1.py | 384 | 3.96875 | 4 | # 🚨 Don't change the code below 👇
two_digit_number = input("Type a two digit number: ")
# 🚨 Don't change the code above 👆
####################################
#Write your code below this line 👇
num_1 = int(two_digit_number[0])
num_2 = int(two_digit_number[1])
result = num_1 + num_2
print(f"The result is {two_di... |
8d40e90caf6a740efbbfcff0dd36a1502dad9f52 | Akenne/CheckiO | /Home/The Flat Dictionary.py | 1,359 | 4.3125 | 4 | """
Python dictionaries are a convenient data type to store and process configurations.
They allow you to store data by keys to create nested structures.
You are given a dictionary where the keys are strings and the values are strings or dictionaries.
The goal is flatten the dictionary, but save the structures in th... |
8eae838da7124b775432c4fa1eb6ea40a3601fac | Akenne/CheckiO | /Home/How to find friends.py | 2,205 | 4.125 | 4 | """
Sophia's drones are not soulless and stupid drones; they can make and have friends.
In fact, they are already are working for the their own social network just for drones!
Sophia has received the data about the connections between drones and she wants to know more about relations between them.
We have an array of... |
db8317767bbfe0e792371bf60b6c831c845d4564 | Akenne/CheckiO | /Library 2.0/Digits multiplication.py | 422 | 3.96875 | 4 | """
You are given a positive integer. Your function should calculate the product of the digits excluding any zeroes.
For example: The number given is 123405. The result will be 1*2*3*4*5=120 (don't forget to exclude zeroes).
"""
def checkio(number):
sum = 1
for i in range(len(str(number))):
if int(str(... |
28370a038682edae892b320cbccdff78e8bfc509 | kushagrasharma13/hacker-rank-30-days-of-code | /Day 25 Running Time and Complexity.py | 448 | 4.0625 | 4 | import math
def check_prime(n):
if n==1:
return False
if n==2:
return True
if n>2 and n%2==0:
return False
max_divisor=math.floor(math.sqrt(n))
for i in range(3,1+int(max_divisor),2):
if n%i==0:
return False
return True
T=int(input())
... |
479db33c41c8451242972ab0766ec3fdd92c86d4 | idawod/day2 | /1/animals/fish.py | 184 | 3.578125 | 4 | class Fish:
def __init__(self):
# Fish class
self.members = ['Aborre', 'Salmon', 'SomeCoolFish']
def printMembers(self):
for member in self.members:
print '\t%s' % member
|
76100d504159f7ec2e785564cba7f3ef79dad47c | learncodesdaily/PP-Pattern | /Downward Right Half Pyramid Pattern.py | 201 | 3.65625 | 4 | def starPattern(n):
for i in range(n, -1, -1):
for j in range(0, i + 1):
print("* ", end="")
print("\r")
n = int(input("Enter Pattern Size : "))
starPattern(n) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.