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 |
|---|---|---|---|---|---|---|
a0d89a7047bf548895e3843ee0f0b33f66b0f3c6 | Lancaster-Physics-Phys389-2020/phys389-2020-project-Pennellium | /Billiard.py | 1,625 | 3.734375 | 4 | import numpy as np
import math
import copy
import scipy.constants
import matplotlib.pyplot as plt
class Particle:
"""
Class to model a massive particle in a gravitational field.
It will make use of numpy arrays to store the position velocity etc.
Working directly from past exercises...
mass in... |
7df9b2b3d58e10b414083b062f5f919abf7d9d82 | Dzm1992/learning_python_classes | /buda_z_lodami.py | 1,130 | 3.609375 | 4 | #9.6
class Restaurant():
"""Tworzy restauracje."""
def __init__(self, restaurant_name, cuisine_type):
"""Inicjalizacja atrybutów."""
self.restaurant_name = restaurant_name
self.cuisine_type = cuisine_type
def describe_restaurant(self):
"""Opisuje restauracje."""
print("Nazwa restauracj... |
ae7242f5bbd3c4f900c4afc60c1d6c5987ce121d | dlkogan/pythonStudies | /sinCosinTan.py | 176 | 3.953125 | 4 | #This program prints a sine cosine and tangent table
import math
count = 0
while(count <= 3):
print math.sin(count), "\t", math.cos(count), "\t", math.tan(count)
count+=.1
|
dcc758f9d540eee592ac57146b2e2b9d410b691f | isaiahchen28/ProgrammingMLM | /WeeklyProgrammer/GreatestCommonDivisor.py | 358 | 3.609375 | 4 | # Find the greatest common divisor of 2 numbers.
import random
import time
def gcd(x, y):
if y == 0:
return x
else:
return gcd(y, x % y)
a = random.randint(50, 100)
b = random.randint(50, 100)
t0 = time.clock()
print("GCD of {0} and {1} is {2}.".format(a, b, gcd(a, b)))
t1 = time.clock()
pri... |
9f961f9c93ec737586a142c69ad2c0a22845499a | isaiahchen28/ProgrammingMLM | /WeeklyProgrammer/LargestPrimeFactor.py | 415 | 3.515625 | 4 | """
Project Euler - Problem 3
The prime factors of 13195 are 5, 7, 13 and 29. What is the largest prime
factor of the number 600851475143?
"""
import time
def largest_prime_factor(n):
i = 2
while i * i < n:
while n % i == 0:
n = n / i
i += 1
return n
t0 = time.clock()
print(... |
b0b96575b671273da07fd0cdd9bb07db95e8f680 | inwk6312winter2019/openbookfinal-SaiSowmithK | /task1.py | 460 | 3.703125 | 4 | def unique_words(file):
opened_file = open(file, 'r')
allWords = [line.split(',') for line in opened_file.readlines()]
unique_list = list()
for i in allWords:
if i in unique_list:
pass
else:
unique_list.appe... |
0125643a553393fd65a66501521c2053836000ab | ztomsy/ztom | /ztom/datastorage.py | 3,216 | 3.578125 | 4 | import collections
import os
import csv
from . import utils
from pathlib import Path
"""
Class allows creation of csv based data storage. It' possible to save data from the list or nested dicts.
In case of nested dics: the columns mapped to nested dict fields should contain "__" as attribute delimeter
for example: ... |
8fb289e04bfb15cd383cdd7c10886f07c09035cb | AntoniyaV/SoftUni-Exercises | /Advanced/Python-advanced-course/03_multidimensional_lists/exercise/04_matrix_shuffling.py | 1,294 | 3.75 | 4 | def command_is_valid(some_command):
some_command = some_command.split()
if some_command[0] == 'swap' and len(some_command) == 5:
return True
return False
def coordinate_is_valid(coordinates_to_check, valid_range):
for value in coordinates_to_check:
if value not in range(valid_range):
... |
e028d06190d0bcebf08d5a1ff6663942ff108e24 | AntoniyaV/SoftUni-Exercises | /Basics/02-Conditional-Statements/08-scholarship.py | 742 | 3.78125 | 4 | income = float(input())
avg_score = float(input())
min_salary = float(input())
import math
social = math.floor(min_salary * 0.35)
excellence = math.floor(avg_score * 25)
if income < min_salary:
if avg_score >= 5.5:
if social > excellence:
print(f"You get a Social scholarship {social} BGN")
... |
0186b4890296a6500ee22dd6a8d2fb9133f94cff | AntoniyaV/SoftUni-Exercises | /Fundamentals/02-Data-Types-and-Variables/01-integer-operations.py | 169 | 3.6875 | 4 | number_1 = int(input())
number_2 = int(input())
number_3 = int(input())
number_4 = int(input())
result = int((number_1 + number_2) / number_3) * number_4
print(result) |
9865dab98986337b3f68d2636aff493e3458339a | AntoniyaV/SoftUni-Exercises | /Fundamentals/08-Text-Processing/04-caesar-cipher.py | 104 | 3.796875 | 4 | message = input()
encrypted = ""
for el in message:
encrypted += chr(ord(el) + 3)
print(encrypted) |
fe425930092c3b511b4466c0a8fb760ac30357d8 | AntoniyaV/SoftUni-Exercises | /Basics/01-First-Steps/03-deposit-calculator.py | 135 | 3.53125 | 4 | deposit = float(input())
period = int(input())
increase = float(input())
sum = deposit+(period*((deposit*increase/100)/12))
print(sum)
|
546c7b5c6c3f55b5abd586c36eabb4f69d98e151 | AntoniyaV/SoftUni-Exercises | /Advanced/Python-oop-course/03_attributes_and_methods/lab/integer.py | 1,242 | 3.875 | 4 | class Integer:
def __init__(self, value):
self.value = value
@classmethod
def from_float(cls, value):
if not type(value) == float:
return "value is not a float"
return cls(int(value))
@classmethod
def from_string(cls, value):
if not type(value) == str:
... |
1f1106aa2f0b6812fe1f7771ab5754a373447f4d | AntoniyaV/SoftUni-Exercises | /Advanced/Python-advanced-course/exam_preparation/Jun_27_2020/bombs.py | 1,409 | 3.734375 | 4 | from collections import deque
def is_pouch_filled(bomb_pouch):
for bomb in bomb_pouch:
if bomb_pouch[bomb] < 3:
return False
return True
def get_result_message(bomb_pouch):
if is_pouch_filled(bomb_pouch):
return "Bene! You have successfully filled the bomb pouch!"
return ... |
335fbdf5d4a0e98c08e00b093a2b05a4e5d23fc5 | AntoniyaV/SoftUni-Exercises | /Advanced/Python-advanced-course/02_tuples_and_sets/exercise/01_unique_usernames.py | 161 | 3.75 | 4 | def print_result(result):
for x in result:
print(x)
n = int(input())
names = set()
for _ in range(n):
names.add(input())
print_result(names)
|
6eacfa755f7403624457860f43bec4e098460ada | AntoniyaV/SoftUni-Exercises | /Fundamentals/Mid-Exam-Preparation/March-2019-01-spring-vacation-trip.py | 954 | 4 | 4 | days = int(input())
budget = float(input())
people = int(input())
fuel_per_km = float(input())
food_person_day = float(input())
hotel_person_night = float(input())
total_food = food_person_day * people * days
total_hotel = hotel_person_night * people * days
if people > 10:
total_hotel *= 0.75
current_expenses = t... |
408a5237a624e3f342b2bed3117806dc61a0a8bf | AntoniyaV/SoftUni-Exercises | /Advanced/Python-oop-course/exam_preparation/Exam_10_Apr_2021/project/aquarium/base_aquarium.py | 1,911 | 3.6875 | 4 | from abc import ABC, abstractmethod
from project.decoration.base_decoration import BaseDecoration
from project.fish.base_fish import BaseFish
class BaseAquarium(ABC):
fish_types = ["FreshwaterFish", "SaltwaterFish"]
@abstractmethod
def __init__(self, name: str, capacity: int):
self.name = name
... |
8b5d25c20c1c1b20ff5b5c5f732213adc70708ed | AntoniyaV/SoftUni-Exercises | /Fundamentals/04-Functions/more-01-data-types.py | 392 | 3.875 | 4 | def data_type_operations(type_of_data, some_data):
result = None
if type_of_data == "int":
result = int(some_data) * 2
elif type_of_data == "real":
result = f"{float(some_data) * 1.5:.2f}"
elif type_of_data == "string":
result = "$" + some_data + "$"
return result
data_ty... |
2f76b33373b93ea9c3d2ea0a4102f4cb0168fd3b | AntoniyaV/SoftUni-Exercises | /Advanced/Python-advanced-course/exam_preparation/Aug_19_2020/taxi_express.py | 684 | 3.890625 | 4 | from collections import deque
def is_time_enough(customer_time, taxi_time):
return customer_time <= taxi_time
customers = deque([int(x) for x in input().split(", ")])
taxis = [int(x) for x in input().split(", ")]
total_time = 0
while customers and taxis:
customer = customers[0]
taxi = taxis.pop()
... |
f7adb9c76349c631a1f460f8d0c8d1b5582f6239 | AntoniyaV/SoftUni-Exercises | /Fundamentals/07-Dictionaries/01-count-chars-in-a-string.py | 236 | 3.765625 | 4 | words = list(input())
symbols = {}
for char in words:
if not char == " ":
if char not in symbols:
symbols[char] = 0
symbols[char] += 1
for key, value in symbols.items():
print(f"{key} -> {value}") |
52bcaf06c01180abb9e2ad3e57b16a2d934c8c73 | AntoniyaV/SoftUni-Exercises | /Advanced/Python-advanced-course/02_tuples_and_sets/exercise/06_longest_intersection.py | 684 | 3.734375 | 4 | def get_numbers_in_a_range(range_info):
start, end = range_info.split(',')
start, end = int(start), int(end)
return set(num for num in range(start, end + 1))
n = int(input())
first_range = set()
second_range = set()
longest_intersection = []
for _ in range(n):
info_first, info_second = input().split... |
08d01d6125d6a8f2b359a5318eaa128ab9eda150 | AntoniyaV/SoftUni-Exercises | /Advanced/Python-advanced-course/03_multidimensional_lists/exercise/08-miner.py | 1,589 | 3.5 | 4 | def get_start_coordinates(matrix):
for r in range(len(matrix)):
if 's' in matrix[r]:
return [r, matrix[r].index('s')]
def get_current_position(command, r, c):
if command == 'up':
r -= 1
elif command == 'down':
r += 1
elif command == 'left':
c -= 1
elif c... |
25cec0431bd323b878d4525110cfdf35626f5b19 | AntoniyaV/SoftUni-Exercises | /Advanced/Python-advanced-course/05_functions_advanced/lab/rounding.py | 162 | 3.640625 | 4 | def round_numbers(*args):
return [round(n) for n in args]
nums = [float(x) for x in input().split()]
rounded_nums = round_numbers(*nums)
print(rounded_nums) |
aa8a25d4d1ad74298ab02541890278b7f7a80bf4 | AntoniyaV/SoftUni-Exercises | /Advanced/Python-advanced-course/04_comprehensions/lab/even_matrix.py | 204 | 3.515625 | 4 | n = int(input())
matrix = []
for _ in range(n):
row = [int(x) for x in input().split(', ')]
matrix.append(row)
new_matrix = [[num for num in r if num % 2 == 0] for r in matrix]
print(new_matrix) |
da622749fe14ae3962a71cb06bdcc4c5ea912251 | AntoniyaV/SoftUni-Exercises | /Fundamentals/03-Lists-Basics/10-bread-factory.py | 1,032 | 3.703125 | 4 | str_events = input()
events = str_events.split("|")
energy = 100
coins = 100
managed = True
for evnt in events:
event = evnt.split("-")
name_or_ingredient = event[0]
number = int(event[1])
if name_or_ingredient == "rest":
if energy + number > 100:
number = 0
else:
... |
b105816d5224d12dc83ef871404dbfde6fab3d9b | AntoniyaV/SoftUni-Exercises | /Basics/01-First-Steps/05-birthday-party.py | 114 | 3.5 | 4 | rent = int(input())
cake = rent*0.2
drinks = cake-(cake*0.45)
anim = rent/3
sum = rent+cake+drinks+anim
print(sum) |
9ff1e086817be01e8be985ef3222f9c0a756fe42 | AntoniyaV/SoftUni-Exercises | /Fundamentals/07-Dictionaries/07-student-academy.py | 688 | 3.78125 | 4 | n = int(input())
students = {}
for num in range(n):
student_name = input()
student_grade = float(input())
if student_name not in students:
students[student_name] = [student_grade]
else:
students[student_name].append(student_grade)
students_to_remove = []
for student, grade in student... |
df5d6e92489030104c2ae424f0fcaef0f7f0ae82 | AntoniyaV/SoftUni-Exercises | /Advanced/Python-advanced-course/01-lists-as-stacks-and-queues/exercise/03-fast-food.py | 820 | 3.640625 | 4 | <<<<<<< HEAD
from collections import deque
quantity = int(input())
orders = deque(int(x) for x in input().split())
print(max(orders))
for _ in range(len(orders)):
if orders[0] <= quantity:
quantity -= orders[0]
orders.popleft()
else:
break
if not orders:
print('Orders complete')
... |
24334f441a6ec58348ae6bc16ae068a5a862d616 | AntoniyaV/SoftUni-Exercises | /Advanced/Python-oop-course/10_testing/exercise/vehicle/test/test_vehicle.py | 2,124 | 3.796875 | 4 | from project.vehicle import Vehicle
import unittest
class VehicleTests(unittest.TestCase):
fuel = 50
capacity = fuel
horse_power = 20
fuel_consumption = 1.25
def setUp(self):
self.car = Vehicle(self.fuel, self.horse_power)
def test_vehicle_init__expect_parameters_to_be_set(self):
... |
4ea92839a03047ad8ec3b36d7b400793a4a41d3a | AntoniyaV/SoftUni-Exercises | /Basics/Exam-Preparation/03-mobile-operator.py | 1,096 | 3.921875 | 4 | contract_period = input()
contract_type = input()
mobile_net = input()
months = int(input())
price_month = 0
if contract_type == 'Small':
if contract_period == 'one':
price_month = 9.98
if contract_period == 'two':
price_month = 8.58
elif contract_type == 'Middle':
if contract_period == 'o... |
161fc07a120fbea06661cc6dd0b28ed2e4d5dc4b | AntoniyaV/SoftUni-Exercises | /Basics/03-Conditional-Statements-Advanced/04-fishing-boat.py | 622 | 3.859375 | 4 | budget = int(input())
season = input()
fishermen_count = int(input())
price = 0
if season == "Spring":
price = 3000
elif season == "Summer" or season == "Autumn":
price = 4200
elif season == "Winter":
price = 2600
if fishermen_count <= 6:
price -= price * 0.1
elif 7 < fishermen_count <= 11:
price ... |
8903eb84e5d0cd65b921028fd02cf2f56867021e | AntoniyaV/SoftUni-Exercises | /Basics/06-Nested-Loops/02-equal-sums-even-odd-position.py | 350 | 3.9375 | 4 | number_1 = int(input())
number_2 = int(input())
for num in range(number_1, number_2 + 1):
num_str = str(num)
even_sum = 0
odd_sum = 0
for i, digit in enumerate(num_str):
if i % 2 == 0:
even_sum += int(digit)
else:
odd_sum += int(digit)
if even_sum == odd_su... |
1868b6e6bb85251029dbfb223d1703d3189f2d68 | AntoniyaV/SoftUni-Exercises | /Fundamentals/Mid-Exam-Preparation/Dec-2019-02-archery-tournament.py | 1,015 | 3.703125 | 4 | targets = input().split("|")
targets = [int(n) for n in targets]
command = input()
points = 0
while not command == "Game over":
if "Shoot" in command:
start_index = int(command.split("@")[1])
length = int(command.split("@")[2])
if 0 <= start_index < len(targets):
position = 0
... |
3eb2bb2b8596a5d9098413c8dd7baa9ff1337c08 | AntoniyaV/SoftUni-Exercises | /Fundamentals/Final-Exam-Preparation/02-problem.py | 554 | 3.890625 | 4 | import re
num_lines = int(input())
pattern = r'^(.+)>(?P<numbers>\d{3})\|(?P<lower>[a-z]{3})\|(?P<upper>[A-Z]{3})\|(?P<symbols>[^<>]{3})<\1$'
for n in range(num_lines):
password = input()
if not re.match(pattern, password):
print("Try another password!")
continue
matches = re.finditer(pa... |
759e3250aebf72e8d8767554b9d738e649732289 | AntoniyaV/SoftUni-Exercises | /Fundamentals/09-Regular-Expressions/more-04-nether-realms.py | 727 | 3.53125 | 4 | import re
demon_names = input().split(',')
demon_names = [n.strip() for n in demon_names]
demons = {}
for name in demon_names:
char_matches = re.findall(r'[^0-9\+\*\./-]', name)
demon_health = sum([ord(sym) for sym in char_matches])
number_matches = re.finditer(r'[\+-]?\d+(\.\d+)?', name)
demon_dam... |
4ffd66b8d2fe39f9b2fa0a3df2f05053c294b25a | AntoniyaV/SoftUni-Exercises | /Advanced/Python-advanced-course/05_functions_advanced/exercise/sort.py | 143 | 3.890625 | 4 | def sort_numbers_ascending(nums):
return sorted(nums)
numbers = [int(x) for x in input().split()]
print(sort_numbers_ascending(numbers))
|
3e256a91eec09b3c709b1e60879744f5562e399d | AntoniyaV/SoftUni-Exercises | /Advanced/Python-advanced-course/01-lists-as-stacks-and-queues/exercise/07-robotics.py | 1,348 | 3.625 | 4 | from collections import deque
def robot_working_time(robots_input):
robot_dict = {}
for pair in robots_input:
robot_name, process_time = pair.split('-')
robot_dict[robot_name] = int(process_time)
return robot_dict
def transform_time_to_seconds(input_time):
hs, ms, ss = input_time.s... |
6dd56eb469e8efc09a0d9bec47e31d6537611d5e | AntoniyaV/SoftUni-Exercises | /Fundamentals/01-Basic-Syntax-Conditional-Statements-and-Loops/more-01-find-the-largest.py | 154 | 3.859375 | 4 | number = input()
list_number = list(number)
list_number.sort(reverse=True)
new_number = ""
for i in list_number:
new_number += i
print(new_number) |
fa9a1d4f77de55a2b682e46f541b9dfadf940376 | gulimujyujyu/gulimujyujyulearnpython | /learn_python_the_hard_way/ex8.py | 977 | 3.5 | 4 |
#!/usr/local/bin/python
# -*- coding:utf-8 -*-
import re
formatter = "%r %r %r %r"
print formatter % (1, 2, 3, 4)
print formatter % ("One", "Two", "Three", "Four")
print formatter % ('One', 'Two', 'Three', 'Four')
print formatter % (True, False, False, True)
print formatter % (formatter, formatter, formatter, forma... |
59816af4ae411ca804d5f51fa9680f07a6742e6a | jaywagger/python | /python_basic_grammar/00_data_type.py | 1,369 | 4.09375 | 4 | #ctl+1
#ctl+`
# 출력해보기
print('Hello World!')
# 프로그래밍 언어의 기본 3가지
# 1. 변수 저장 - 무엇을 저장할 수 있을까?
number = 10
string = '10'
boolean = True #시작을 대문자로
#파이썬에는 값이 없다는 뜻인 None 타입이 존재
nothing = None #시작을 대문자로
print(number, string, boolean, nothing)
print(type(nothing)) #타입 확인
# 1.1 정수형
number = 10
float_num = 1.3
complex_num = ... |
137ac9dc453bf53dbde7f1bf4ca0f5fd86e0a025 | Erotemic/xdoctest | /dev/talk.py | 4,978 | 4 | 4 | """
https://tohtml.com/
"""
import operator
# def paragraph(text):
# r"""
# Remove leading, trailing, and double whitespace from multi-line strings.
# Args:
# text (str): typically in the form of a multiline string
# Returns:
# str: the reduced text block
# """
# import re
# ... |
fe562ae965712f30bc6bfcd177d1af7c4b2f4d48 | niemtec/Keras-Experiments | /TensorFlow Tutorials/Text-Classification.py | 5,373 | 3.796875 | 4 | # Classification of movie review sentiment (pos/neg) by analysing review text
# Binary Classification Example
import tensorflow as tf
import matplotlib.pyplot as plt
from tensorflow import keras
import numpy as np
print(tf.__version__)
imdb = keras.datasets.imdb
(train_data, train_labels), (test_data, test_labels) =... |
416a7a9f512fa1a0c9dcde4a2333083dc90988d0 | szymon123xxx/Metody-numeryczne | /lista5/zad3.py | 559 | 3.5 | 4 | import numpy as np
import matplotlib.pyplot as plt
from scipy.interpolate import CubicSpline
Re = [0.2, 2, 20, 200, 2000, 20000]
Cd = [103, 13.9, 2.72, 0.8, 0.401, 0.433]
#Nakładanie podwójnej logarytmicznej skali
cs = CubicSpline(np.log(Re), np.log(Cd))
xs = np.arange(0.2, 20000, 0.1)
y2 = np.exp(cs(np.log(xs)))
fi... |
ab918d0a8208af649ff2b51e588003ceb628fbc7 | RenanBertolotti/Python | /Curso Udemy/Modulo 07 - Base de Dados - SQLite, MySQL e MariaDB/Aula01 - SQLite - Usando o modulo sqlite3/main.py | 910 | 3.71875 | 4 | import sqlite3
conexao = sqlite3.connect('basededados.db')
cursor = conexao.cursor()
cursor.execute("CREATE TABLE IF NOT EXISTS clientes("
"id INTEGER PRIMARY KEY AUTOINCREMENT,"
"nome TEXT NOT NULL,"
"peso REAL"
")")
cursor.execute("INSERT INTO clientes(no... |
f0338f415d9ae800498899ab3d3b5196d77ca867 | RenanBertolotti/Python | /Curso Udemy/Modulo 03 - Python Intermediário (Programação Procedural)/Aula 18 - Exercicio/Aula18.py | 335 | 3.9375 | 4 | #SOmando a partir de uma lista, usando a list Comprehension
carrinho = []
carrinho.append(("produto1", 20))
carrinho.append(("produto2", 30))
carrinho.append(("produto3", 50))
soma = sum([valor for i,valor in carrinho])
print(soma)
""" TESTE 1 - DEU CERTO!!!
soma = 0
for i,valor in carrinho:
soma += valor
pr... |
949a2795ceaa4ead3944c8bc00e7b969e815840b | RenanBertolotti/Python | /Uri Judge - Python/URI-1035.py | 638 | 3.671875 | 4 | """Leia 4 valores inteiros A, B, C e D. A seguir, se B for maior do que C e se D for maior do que A, e a soma de
C com D for maior que a soma de A e B e se C e D, ambos, forem positivos e se a variável A for par escrever a
mensagem "Valores aceitos", senão escrever "Valores nao aceitos".
Entrada
Quatro números inteiro... |
73d72bbbb4f8faaaec855dba33ee87022c88c824 | RenanBertolotti/Python | /Exercicios para a Felipeia/Exercicio3.py | 369 | 4.03125 | 4 |
def divisivel(x, y):
if y % x ==0:
return 1
else:
return 0
if __name__ == "__main__":
numero1 = int(input())
numero2 = int(input())
print(f"Numero {numero1} e divisivel por {numero2}?: ")
resposta = divisivel(numero1, numero2)
if resposta == 1:
print("É divisivel"... |
6a775778e7f1f8f2bb00f09d41124b1091ccc64f | RenanBertolotti/Python | /Curso Udemy/Modulo 04 - Pyhton OO/Aula17 - Metodos Magicos/main.py | 854 | 3.71875 | 4 | # https://rszalski.github.io/magicmethods/
class A:
def __new__(cls, *args, **kwargs):
return super().__new__(cls)
def __init__(self):
print("Eu sou o Init")
def __call__(self, *args, **kwargs):
resultado = 0
for i in args:
resultado += i
return resul... |
94be99b86bc081e32058eaafbfcdbea47df8a7d1 | RenanBertolotti/Python | /Uri Judge - Python/URI-1036.py | 953 | 3.96875 | 4 | """Leia 3 valores de ponto flutuante e efetue o cálculo das raízes da equação de Bhaskara.
Se não for possível calcular as raízes, mostre a mensagem correspondente “Impossivel calcular”,
caso haja uma divisão por 0 ou raiz de numero negativo.
Entrada
Leia três valores de ponto flutuante (double) A, B e C.
Saída
Se nã... |
6c5155cd03a0219f37566a46e68b629720962910 | RenanBertolotti/Python | /Curso Udemy/Modulo 02 - Pyhton Basico/Aula 04 - Dados Primitivos/aula04.py | 636 | 4.15625 | 4 | """
Tipos de dados
String - str == Texto 'assim' ou "assim"
Inteiro - int == 1, 2, 3, 4, 5
Float - real/flutuante = 1.12313, 2.465456, 3.465465
Bool - Booleane/logico = true or false
"""
print("Luiz", type("Luiz"))
print(10, type(10))
print(10.5, type(10.5))
print(True, type(True))
print("Renan"=="Renan", type("Renan... |
4b1e09d72605b75fe73fd47b79e0e1508169672e | RenanBertolotti/Python | /Curso Udemy/Modulo 02 - Pyhton Basico/Aula 31 - Exercicio Valide um CPF/Aula31.py | 2,271 | 3.703125 | 4 | """
CPF = 168.995.350-09
--------------------------------------------------
1 * 10 # 1 * 11 = 11 <-
6 * 9 # 6 * 10 = 60
8 * 8 # 8 * 9 = 72
9 * 7 # 9 * 8 = 72
9 * 6 # 9 * 7 = 63
5 * 5 # 5 * 6 = 30
3 * 4 ... |
e1a422898de6efb51dd0081bb6b0c1fc798cd957 | RenanBertolotti/Python | /Curso Udemy/Modulo 03 - Python Intermediário (Programação Procedural)/Aula 27 - Try, Except - Tratando Exceçoes em Python/Aula27.py | 1,226 | 4.125 | 4 | """
Try / Except em python
#Try/Except basico
try:
a = 1/0
except NameError as erro:
print("erro", erro)
except (IndexError, KeyError) as erro:
print("erro de indice", erro)
except Exception as erro:
print("ocorreu um erro inesperado")
else:
print("Seu codigo foi afetuado com sucesso")
finally:
... |
ab3b6ff33a72e7faf8585b895b20c29cc4e181f2 | RenanBertolotti/Python | /Curso Udemy/Modulo 03 - Python Intermediário (Programação Procedural)/Aula 15 - Dictonary Comprehension/Aula15.py | 393 | 3.984375 | 4 | """
Dictionary COmprehension - sao utilizadas para otimizaçao(performance) e escrever menos
"""
lista = [
("chave1", "Renan"),
("chave2", "Maria"),
]
d1 = {x : y for x,y in lista}
#ou
d1 = dict(lista)
d1 = {y:x for x,y in lista}
d1 = {x: y*2 for x,y in lista}
d1 = {x: y.upper() for x,y in lista}
d1 = {x for... |
adc3fbcdb265986176a399a56eab291a73677ffa | RenanBertolotti/Python | /Curso Udemy/Modulo 03 - Python Intermediário (Programação Procedural)/Aula 22 - Combinations. Permutations e Product - Itertools/Aula 22.py | 990 | 4.0625 | 4 | """
Combinations , Permutations e Product - Itertools
Combinations - Ordem nao importa
Permutations - Ordem importa
Ambos não repetem valores unicos
Product - Ordem importa e repete valores unicos
"""
from itertools import combinations
pessoas = ["Renan", "Ana", "Maria", "Rose", "Leticia"]
for grupo in combinations(... |
b3c34ff9360802a9cb5a9469d30138954731b9f2 | RenanBertolotti/Python | /Uri Judge - Python/URI-1142.py | 427 | 3.859375 | 4 | """
Escreva um programa que leia um valor inteiro N. Este N é a quantidade de linhas de saída que serão apresentadas na
execução do programa.
Entrada
O arquivo de entrada contém um número inteiro positivo N.
Saída
Imprima a saída conforme o exemplo fornecido.
"""
casos_teste = int(input())
valor = 1
for i in range... |
793da7be7badc41e11f5327992fc481d7f36b53f | RenanBertolotti/Python | /Curso Udemy/Modulo 04 - Pyhton OO/Aula13 - Classes Abstratas/conta.py | 1,212 | 3.953125 | 4 | from abc import ABC,abstractclassmethod
class Conta(ABC):
def __init__(self, agencia, conta, saldo):
self._agencia = agencia
self._conta = conta
self._saldo = saldo
@property
def agencia(self):
return self._agencia
@property
def conta(self):
return self._... |
5c7d0c9f5a8a6263b6a338493b37a0f879e6bb35 | marcoshung/EmailAutomator | /email_window.py | 1,660 | 3.609375 | 4 | #Marcos Hung
from tkinter import *
class Email_Window:
def __init__(self, display_text):
self.root = Tk()
self.display_text = display_text
self.send_all = False
self.skip_all = False
self.send = False
def do_nothing(self):
print("Nothing")
def send_emai... |
e3b1316f30318aefc72598f57ecaeaac86ca2409 | NeniscaMaria/AI | /1.RandomVariables/lab1TaskC/main.py | 2,428 | 4.21875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Feb 29 15:54:46 2020
@author: nenis
"""
from sudoku import Sudoku
from geometricForms import GeometricForms
from cryptoarithmeticGame import CryptoarithmeticGame
def showMenu():
print("\nPlease choose one from below:")
print("0.Exit")
print("1.Sudoku")
print(... |
1f20aa38385440a39ae985715a94bac51a5046f3 | NeniscaMaria/AI | /1.RandomVariables/lab1TaskC/sudoku.py | 4,685 | 4.125 | 4 | # -*- coding: utf-8 -*-
import numpy as np
class Sudoku:
def __init__(self, sizeFromUser, trials):
self.noOfTrials=trials
self.boardSize = sizeFromUser
self.board=[]
def validateRow(self,row):
'''
DESCR: checks if a row is valid and returns a list with the numbers f... |
9dc0ace25823943ea6f22668a05cf6fbf0c1dd1b | kukgini/my-py | /cp1_1_09_step_game.py | 555 | 3.6875 | 4 | def func(record):
if record == 0:
return 1
elif record == 1:
return 2
return 0
def solution(a,b):
cnt = 0 # A 의 계단 위치
results = []
for i in range(len(a)):
if a[i] == b[i]:
a.append(cnt)
continue
elif a[i] == func(b[i]):
cnt = c... |
7086002fb588207e810e8fee0fa1127ec8ac08c0 | kukgini/my-py | /4-3-dict.py | 409 | 3.703125 | 4 | #!/usr//bin/python
#
# https://wikidocs.net/72
dic = {}
dic['dictionary'] = '1. A reference book containing an ...'
dic['pythin'] = 'Any of various nonvenomous snakes of the ...'
print dic['dictionary']
smalldic = {'dictionary' : 'reference', 'python' : 'snake'}
print smalldic['python']
print smalldic
family = {'bo... |
36fef064de541024872d445def4c56a0400f5446 | kukgini/my-py | /cp1_3_03_chess_bishop.py | 1,397 | 3.796875 | 4 | # 비숍 위치가 주어졌을 때 한번에 잡히지 않도록 체스 말을 놓을 수 있는 빈칸 갯수 반환
# 예:
# [D5] ==> 50
# [D5, E8, G2] => 42
#
# 힌트: ord 는 ascii code 를 반환해 줌
def code_to_pos(code):
x = ord(code[0]) - ord('A') # A = 0, B = 1, ..., H = 7
y = int(code[1]) - 1 # board 의 좌표가 0 부터 시작하므로 1다 을 뺀다.
return (y, x)
def move(board, position, di... |
b030c618f676f38f45ec28180e7d9f0b81de3bb7 | jigshahpuzzle/yelpdatachallenge | /basicparsing.py | 4,707 | 3.609375 | 4 | # This file contains scripts to parse data from the Yelp JSON and conduct basic maniuplations.
import json
# DESCRIPTION:
# Reads data in from "data" directory
# INPUT:
# "business" for business data
# "checkin" for checkin data
# "review" for review data
# "tip" for tip data
# "user" for user data
# OUTPUT:
# L... |
cfd40b3aac0c66750c048a7c85dc3cfcdbd79e31 | TsabarM/MIT_CS_Python | /analyze_song_lyrics.py | 2,085 | 4.6875 | 5 | # Analyze song lyrics - example for use python dictionaries
'''
In this example you can see how to create a frequency dictionary mapping str:int.
Find a word that occures the most and how many times.
Find the words that occur at least X times.
'''
def lyrics_frequencies(lyrics):
'''
Creates a Dictionary with... |
6869dec3ad14fa47b771d892b9d73dc8f1ad446c | sofiaalvarezlopez/Quantum-Network-Entanglement-Routing | /src/main/quantum/topo/Link.py | 4,653 | 3.90625 | 4 | """This class represents a link between two nodes: n1 and n2"""
import numpy as np
class Link:
count = 0
# The constructor of the link. Parameters:
# A given topology topo.
# Two nodes (n1 and n2), which form the link.
# The length l of the link.
# assigned, which is true if there is one qubi... |
5dea6c39f01ccaa6ae5e4be072648aa53089c2ac | luginin-Ivan/dz-by-algoritm- | /9.py | 160 | 3.859375 | 4 | a = int(input("значение а: "))
b = int(input("значение b: "))
while True:
if a == b:
print(a)
break
elif a >b:
a = a-b
else:
b = b-a |
109b446b6866d1210a767d35f37ad6b25b835d3b | luginin-Ivan/dz-by-algoritm- | /18.py | 174 | 3.765625 | 4 | a = int(input("введите a :"))
b = int(input("введите b :"))
c = int(input("введите c :"))
min=a
if min>b:
min=b
elif min>c:
min =c
print(min)
|
650743e11876815e348183c572e9dd38a50e2a6f | 1Yasmin/compis3 | /myParser.py | 658 | 3.65625 | 4 | def Expr():
Stat()
def Stat():
value = 0
Expression(value)
print(value)
def Expression(result):
result1, result2
Term(result1)
while:
Term (result2)
result1 += result2
|"-"Term(result2)
result1-=result2
return result=result1
def Term(result)
result1,result2... |
74d4219b6e5cb9ed22413b2576d86607548c7525 | LHYi/HW1-2 | /Li/DigitAlarm.py | 2,359 | 3.5625 | 4 | alarmhour,alarmmin=eval(input("请输入响铃时间(时,分):"))
print("时钟启动,闹钟将在{}:{}时响起".format(alarmhour,alarmmin))
import turtle
import time
import random
import winsound
R=0.00
G=0.00
B=0.00
def changecolor():
global R
global G
global B
i = time.time()
random.seed(i)
R=random.random()
random.seed(i+1)
... |
7cd555982b5638760f807e5f442128a42e4f382b | Manasmalhotra/BASICS-WITH-PYTHON | /sum of digits.py | 119 | 3.953125 | 4 | x= int(input("enter a number"))
sum=0
while x>0:
r= int(x%10)
sum= sum+r
x=int(x/10)
print(sum)
|
6a1e0064b267811493483be24bbd4093f3ca5085 | Manasmalhotra/BASICS-WITH-PYTHON | /reverse string.py | 115 | 3.703125 | 4 | string=input("enter string")
z=string[::-1]
print(z)
w=string.split()
t=w[::-1]
print(t)
print(" ".join(t))
|
4781b70b5e658b982f86c4f3fefeb0a502fe2ab6 | hardeek100/Python-Scripts | /graph_traversal.py | 1,000 | 3.78125 | 4 | # Graph traversal
def view_adjacencyMatrix(mat):
print("Adjacency Matrix: ")
for i in mat:
print(i)
def graph(mat):
vertices = []
edges = []
weights = {}
for i in range(len(mat)):
vertices.append(mat[0][i])
for j in range(i, len(mat)):
if type(mat[j][i])... |
0c44b0e48001a0e4d44e14924576942642d5feaf | nickverschueren/Advent2020 | /Advent13/chinese.py | 1,210 | 3.65625 | 4 | # A Python 3program to demonstrate
# working of Chinise remainder
# Theorem
# Returns modulo inverse of a with
# respect to m using extended
# Euclid Algorithm. Refer below
# post for details:
# https://www.geeksforgeeks.org/multiplicative-inverse-under-modulo-m/
def inv(a, m) :
m0 = m
x0 = 0
x1 = 1
i... |
21adc48ddb32d1cda096f640c6849ae9cb3eeeda | nickverschueren/Advent2020 | /Advent2/main.py | 1,616 | 3.546875 | 4 | from console import sc
from console.constants import ESC
from console.utils import wait_key
class row:
def __init__(self, min, max, letter, password):
self.min = min
self.max = max
self.letter = letter
self.password = password
def readInput():
rows = []
inputFile = open('... |
7f73503a89e0b259c736d9f2ced90c3404c48a46 | nickverschueren/Advent2020 | /Advent5/tests.py | 610 | 3.546875 | 4 | import unittest
from main import binaryCountStr
class TestBinaryCountStr(unittest.TestCase):
def test_binaryCountStr1(self):
actual = binaryCountStr('BFFFBBFRRR','BR')
expected = 567
self.assertEqual(expected, actual)
def test_binaryCountStr2(self):
actual = binaryCount... |
21c81dc1fb6912de7b72e32c981a9b38cfc99381 | BouSenna/AddTheNumbersGame | /AddTheNumbersGame.py | 4,677 | 3.5 | 4 | import math
import pygame
import time
from random import randint
moves = [(1, 0), (-1, 0), (0, 1), (0, -1)]
def make_board():
ret = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
for i in range(3):
for j in range(3):
ret[i][j] = randint(-1, 1)
return ret
def valid(x, y):
return x >= 0 and x ... |
ed18f10714265cc14f508f6fca7e297f82bf457a | leonard-seydoux/frontiers_in_earth_sciences | /linear_regression/losses.py | 1,303 | 3.578125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Linear regression illustration.
Author: Leonard Seydoux
Email: leonard.seydoux@univ-grenoble-alpes.fr
Date: Nov. 2019
"""
import numpy as np
from matplotlib import pyplot as plt
# Show data
n = 200
np.random.seed(1)
x = np.random.randn(n)
a = .7
b = -.5
c = -1
d = -... |
934913ea4b0753b8df0e211270f113853fc5464a | Othmanbdg/Frigo | /test_knnnn.py | 4,466 | 3.578125 | 4 | import random
from tkinter import *
ingredient=['sauces','yaourts','fruits','legumes','viandes','eau','soda','glace','fromage','lait']
temoin=['sauces','yaourts','fruits']
prsn=[]
path=r"C:/Users/Vil/Desktop/"
def gens(num):
var = 1
secu=[]
prsn.clear()
for i in range(num):
a = ... |
9060484f8d432cad0fdc09841d059018ed87a43c | JCode1986/python-data-structures-and-algorithms | /challenges/left_join/left_join.py | 3,016 | 4.09375 | 4 | class HashMap:
def __init__(self, size):
self.size = size
self.map = [None] * self.size
self.index = -1
def __str__(self):
"""
Method from HashMap that prints indices, keys, and values in map
In: None
Out: string
"""
if self.map is not N... |
0e61d1baa0e9ae984dd83cf27ac96d4c7e6c509f | JCode1986/python-data-structures-and-algorithms | /sorts/insertion_sort/insertion.py | 430 | 4.21875 | 4 | def insertion_sort(lst):
"""
Sorts list from lowest to highest using insertion sort method
In - takes in a list of integers
Out - returns a list of sorted integers
"""
for i in range(1, len(lst)):
j = i - 1
temp = int((lst[i]))
while j >= 0 and temp < lst[j]:
lst[j + 1] = lst[j]
... |
9deea6ea1a9374b470c84692cd9a5284c4c17a38 | Hong-Jun-Ho/Python | /venv/Programmers/level2/Printer.py | 534 | 3.796875 | 4 | def printer(priorities, location):
answer = 0
print_list = [(pro, i) for i, pro in enumerate(priorities)]
print_list_max = max(print_list)[0]
while True:
if print_list[0][0] == print_list_max:
temp = print_list.pop(0)
answer += 1
if temp[1] == location:
... |
dbf75cf67dc130d79331207514dbef045016e9a2 | Hong-Jun-Ho/Python | /venv/Programmers/level1/Descending.py | 336 | 3.609375 | 4 | def solution(s):
q = []
for c in range(len(s)):
q.append(ord(s[c]))
q.sort()
q.reverse()
for c in range(len(q)):
q[c] =(chr(q[c]))
result = ''.join(q)
return result
print(solution("Zbcdefg"))
## 다른사람의 풀이
## def solution(s):
## return ''.join(sorted(s, reverse=True))... |
4259524693b87e290644eabafe6bc38fad49cd92 | shreyansh-sh1/twoc-python-assingment2 | /question 2.py | 246 | 3.9375 | 4 | print("Enter Size: ")
N = int(input())
for i in range(N):
for k in range(N):
if (i == k) or ((N - k -1) == i):
print('*', end = '')
else:
print(' ', end = '')
print('')
# Code by Shreyansh Sharma |
c26b94302d24c116dadd2d5dfc0ef051cb43f1a2 | TheFaro/DataAnalysis | /UI/investing_currency_cross_api.py | 4,240 | 3.53125 | 4 | '''
This file contains a class that defines the api for retrieving currency crosses data from investing.com
'''
import investpy
import tkinter.messagebox as mb
class CrossesAPI:
def __init__(self, cross=None, from_date=None, to_date=None, country=None):
self.cross = cross
self.from_date = fro... |
ac2a6df1feb2db1ed431e01ca3a3324d922238c7 | TheFaro/DataAnalysis | /UI/investing_etfs_api.py | 3,999 | 3.5 | 4 | '''
This file contains a class that defines the api for retrieving etf data from investing.com
'''
import investpy
import tkinter.messagebox as mb
import requests
import json
class ETFSAPI:
def __init__(self,etfs=None,country=None,from_date=None,to_date=None):
self.etfs = etfs
self.country = c... |
3090a91c2716eb23ec72016f8096b2d3d7682331 | MarcusLampa/Python_Transmission | /Plot_SubPlots.py | 509 | 3.65625 | 4 | import random
import matplotlib.pyplot as plt
from matplotlib import style
style.use('fivethirtyeight')
fig = plt.figure()
def CreatePlots():
xs = []
ys = []
for i in range(10):
x = i
y = random.randrange(10)
xs.append(x)
ys.append(y)
return xs, ys
ax1 = fig.add_su... |
68066ebc4953005ba19f5ada8a584e421540cf3d | Patrick-Ali/AndromedaChatbot | /controller.py | 1,136 | 3.515625 | 4 | import dataControl as data
import wordAnlysis as word
class AnalyseInput:
def __init__(self):
print("Class initalized")
def analyseWord(self, words):
element = word.testForWord(words,[])
print("Element is ", element)
words = []
if ',' in element[0]:
print... |
d5dbc26d20f1d08f667eefef95a857b117645005 | DaniilBornosuz/daniil | /slovar.py | 202 | 3.765625 | 4 | # -*- coding: utf-8 -*-
slovo=input("Введите слово: ")
slovar={}
for i in slovo:
if i not in slovar:
slovar[i]=1
else:
slovar[i]=slovar[i]+1
print(slovar)
|
c0b0c81885f653b3c781b21a2e7cce55aa4468f6 | pyrateml/agent | /utilities/random_process/wiener.py | 4,832 | 3.671875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = 'cnheider'
from math import sqrt
import matplotlib.pyplot as plt
import numpy as np
from scipy.stats import norm
from utilities.random_process.random_process import RandomProcess
class WienerProcess(RandomProcess):
def __init__(self, delta, dt, initial... |
b4b9e56ac093d825c3af2df115b027cfd8d138d3 | leejh3224/pyleetcode | /counting_bits/solution.py | 862 | 3.625 | 4 | from typing import List
# 1472. Design Browser History
# Difficulty: Medium
# Time Complexity: O(N)
class Solution:
def countBits(self, num: int) -> List[int]:
dp = [0] * (num + 1)
# Least Significant Bit (LSB) is always 0 for even numbers and 1 for odd numbers
# It means if we right shif... |
64e1e05b54ee58cfb3dfd01051122cf4961f84ae | leejh3224/pyleetcode | /sort_integers_by_the_power_value/solution_brute_force.py | 713 | 3.765625 | 4 | # 1387. Sort Integers by The Power Value
# Difficulty: Medium
# Time Complexity: unknown
class Solution:
def getKth(self, lo: int, hi: int, k: int) -> int:
# Brute force
# compute power of every numbers in range
v = sorted(list(range(lo, hi + 1)), key=lambda e: self.get_power(e))
re... |
3e8e0b802a7b0f10c4c581e40259c0604129a221 | leejh3224/pyleetcode | /construct_k_palindrome_strings/solution.py | 876 | 3.640625 | 4 | # 1400. Construct K Palindrome Strings
# Difficulty: Medium
# Time Complexity: O(N)
class Solution:
def canConstruct(self, s: str, k: int) -> bool:
# length of smallest possible palindrome is 1
# so if k exceeds length of s, it's not possible to construct k palindromes
if len(s) < k:
... |
045423deceb1192ff345c22b54dd3bc4fad9974c | leejh3224/pyleetcode | /replace_words/solution_trie.py | 1,826 | 4 | 4 | from typing import List
class Node:
def __init__(self):
self.children = [None] * 26
self.isWord = False
class Trie:
def __init__(self):
self.root = Node()
# `insert` follows formal Trie implementation
def insert(self, word):
node = self.root
for i in range(l... |
7d3c90a2accd4343182f11d4416562b4baaf8c80 | pardo2410/Baraja | /main.py | 624 | 3.8125 | 4 | '''
import cartas
b1 = cartas.crea_baraja()
bm = cartas.mezclar(b1)
print(bm)
Jugadores = int(input('Numero de jugadores: '))
cartas_j = int(input('Numero de cartas: '))
metodo_r = input('Desea cambiar el metodo de repartir S/N: ')
if metodo_r =='N':
metodo_r = False
else:
metodo_r = True
print(cartas.reparte(b... |
44ab114c60cb01bda254b731bd6c5096ba4ba730 | bilaluali/maxSAT | /instance.py | 3,188 | 3.640625 | 4 | from logging import warning
class PackageNotFoundException(Exception):
"""Raised when a package is not defined in valid packages"""
pass
class UnexpectedPackagesException(Exception):
"""Raised when number of packages defined in 'p', is different
with len of 'list'"""
pass
class Instance:
... |
0f33dac8ba1300d357df2e0b79ad6e4733343c9e | Pucadopr/Algorithms_practice | /codility_practice.py | 1,638 | 3.859375 | 4 | # List of Algorithms/Functions from Codility practices
def getfactorial(n):
'''
Get the factorial of a given number
'''
factorial = 1
for i in range(1, n+1):
factorial*=i
return factorial
# Algorithm to determine maximum number of consecutive 1s in a Binary number
def solution(n):
... |
4473a00c4e185286b116c206c17e1dba79603bed | JBW77/python-challenge | /PyBank/main2.py | 798 | 3.625 | 4 | import os
import csv
# Path to folder
csvpath = os.path.join("Downloads", "budget_data.csv")
# Open the CSV
with open(csvpath,newline ='') as csvfile:
csvreader = csv.reader(csvfile, delimiter=',')
csv_header = next(csvreader)
months = []
for row in csvreader:
months.append(row[1])
... |
a3154200beab4765d7c8177e01cc426ef4ec63b0 | kfcole20/python_practice | /math_practice.py | 1,021 | 4.625 | 5 | # Assignment: Multiples, Sum, Average
# This assignment has several parts. All of your code should be in one file that is well commented to indicate what each block of code is doing and which problem you are solving. Don't forget to test your code as you go!
# Multiples
# Part I - Write code that prints all the odd nu... |
404c5cd7f34836b70d2eb951764f4381d65f8eb8 | Edre2/StarkeVerben | /main.py | 2,763 | 4.15625 | 4 | import csv
import random as rando
# The prompt the user gets when he has to answer
PROMPT = "> "
# The numbers of forms of the verbs in franch and german
NUMBER_OF_FORMS_DE = 5
NUMBER_OF_FORMS_FR = 1
# Gets the verbs from verbs.csv
def get_defs():
verbs = []
with open('verbs.csv', 'r') as verbs_file:
read... |
584c5f4001acaf49483381af86083d9453c755db | eSuminski/Python_Primer | /Primer/examples/key_word_examples/key_word_examples.py | 987 | 4.125 | 4 | from to_import import MyClass as z
# from indicates where the code is coming from
# import tells you what code is actually being brought into the module
# as sets a reference to the code you are importing
my_list = ["eric", "suminski"]
for name in my_list:
print(name)
# for is used to create a loop, and in is use... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.