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 |
|---|---|---|---|---|---|---|
3c19d3852b8761b543d9c93712b5ed1ed850c97b | doofenshmirtzInc/elem-ai | /jamcshan-samize-purama-a1/part3/assign.py | 3,509 | 3.890625 | 4 | #!/usr/local/bin/python3
# put your group assignment program here!
import sys
import os
import random
def evaluate_groups(groups, k, m, n, preferences):
set_of_groups = set()
score = 0
for person in groups:
person_group_string = '-'.join(groups[person])
if person_group_string not in set_of... |
afc14db293718244162d01ad8e56515313f0656c | amouhk/python | /morpion_gui.py | 2,191 | 3.546875 | 4 | # from tkinter import *
# from tkinter import ttk
#
#
# def on_click(px, py):
# print("Clic gauche sur le bouton (", px, ", ", py, ")")
# nbtn = Button(frame, command=lambda x=px, y=py: on_click(x, y), state=DISABLED, bg='blue')
# nbtn.grid(row=px, column=py, sticky=N + S + E + W)
#
#
# # Create & Configure... |
e66808449ab117b94e37dafe9a0a8d4b84de1445 | Dana-Lucas/CFD-Analysis-Project | /Lucas_SciModProject_QuiverPlot.py | 3,285 | 3.609375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Apr 19 15:38:29 2020
@author: Dana
"""
import numpy as np
import matplotlib.pyplot as plt
'''
This portion shows a quiver plot showing the magnitude of the
velocity at certain coordinates where the plates are stationary
'''
# Stationary plates
def velocity_lam... |
b502a5371041e0843d317d99533b3d7c96bf39d1 | ivelinakaraivanova/SoftUniPythonFundamentals | /src/Data_Types_Exercises/07_Water_Overflow.py | 458 | 3.90625 | 4 | n = int(input())
tank_capacity = 255
for row in range(1,n+1):
water = int(input())
tank_capacity -= water
if tank_capacity < 0:
print("Insufficient capacity!")
tank_capacity += water
print(f"{255 - tank_capacity}")
"""
total_liters = 0
for i in range(n):
liters = int(input())
if ... |
bc9c066d61d52244b6dfc68cbcb6d203570b7502 | ivelinakaraivanova/SoftUniPythonFundamentals | /src/Functions_Exercise/09_Factorial_Division.py | 235 | 3.8125 | 4 | def factorial(n):
fact = 1
for i in range(1, n+1):
fact *= i
return fact
first_input = int(input())
second_input = int(input())
division = factorial(first_input) / factorial(second_input)
print(f"{division:.2f}")
|
fdfe982bcaa80fd03c084414d84120c336fc111f | ivelinakaraivanova/SoftUniPythonFundamentals | /src/Mid_Exams/Mid_Exam_29_February_2020_Group1/01_Bonus_Scoring_System.py | 588 | 3.640625 | 4 | import math
students_count = int(input())
lectures_count = int(input())
additional_bonus = int(input())
max_bonus_points = 0
max_attendances = 0
for student in range(students_count):
student_attendances = int(input())
if lectures_count != 0:
total_bonus = student_attendances / lectures_count * (5 + a... |
24cfd12c46b6f0de079277388153a0ca48dac0a0 | ivelinakaraivanova/SoftUniPythonFundamentals | /src/Text_Processing_Exercise/06_Replace_Repeating_Chars.py | 172 | 3.59375 | 4 | data = list(input())
result_list = [data[0]]
for i in range(len(data)-1):
if data[i+1] != data[i]:
result_list.append(data[i+1])
print("".join(result_list))
|
31ea9e24751bbd624521c49ab790f78084f432dc | ivelinakaraivanova/SoftUniPythonFundamentals | /src/Functions_More_Exercises/02_Center_Point.py | 483 | 4.09375 | 4 | import math
def find_distance_to_center(x, y):
result = abs(math.sqrt((x**2) + (y**2)))
return result
first_point_x = float(input())
first_point_y = float(input())
second_point_x = float(input())
second_point_y = float(input())
if find_distance_to_center(first_point_x, first_point_y) <= find_distance_to_ce... |
c2efc6be56a9b724380e40f4af154fd8d544d237 | ivelinakaraivanova/SoftUniPythonFundamentals | /src/Basic_Syntax_More_Exercises/01_Find_The_Largest.py | 94 | 3.890625 | 4 | number = input()
largest_number = "".join(sorted(number, reverse=True))
print(largest_number) |
6e874398b8c826377e8b8bb06ca8b03122df666e | ivelinakaraivanova/SoftUniPythonFundamentals | /src/Final_Exams/Final_Exam_07_December_2019_Group1/01_Email_Validator.py | 1,140 | 4.0625 | 4 | def make(string, case):
if case == "Upper":
string = string.upper()
elif case == "Lower":
string = string.lower()
return string
def get_username(string):
if "@" in string:
ind = string.index("@")
return string[:ind]
else:
return -1
def encrypt(string):
... |
e1d1e87df42d669bfee79f26ed030f145ca73be4 | ivelinakaraivanova/SoftUniPythonFundamentals | /src/Final_Exams/Final_Exam_04_April_2020_Group2/03_Heroes_of_Code_and_LogicVII.py | 2,542 | 3.703125 | 4 | def cast_spell(hero_name, mp_needed):
if heroes[hero_name][1] >= mp_needed:
heroes[hero_name][1] -= mp_needed
return 1
else:
return -1
def take_damage(hero_name, damage):
heroes[hero_name][0] -= damage
if heroes[hero_name][0] > 0:
return 1
else:
heroes.pop(h... |
c0db066385b8be1739c22d34154c795e99f93281 | ivelinakaraivanova/SoftUniPythonFundamentals | /src/Final_Exams/Final_Exam_09_August_2020/01_World_Tour.py | 841 | 3.859375 | 4 | text = input()
while True:
data = input()
if data == "Travel":
break
split_data = data.split(":")
command = split_data[0]
if command == "Add Stop":
index = int(split_data[1])
string = split_data[2]
if 0 <= index < len(text):
text = text[:index] + string ... |
42b5454401c17c8562d4d3cb47f3575fc7535712 | ivelinakaraivanova/SoftUniPythonFundamentals | /src/Lists_Basics_More_Exercises/02_Tic_Tac_Toe.py | 871 | 3.609375 | 4 | first_row = list(map(int, input().split(" ")))
second_row = list(map(int, input().split(" ")))
third_row = list(map(int, input().split(" ")))
first_column = [first_row[0], second_row[0], third_row[0]]
second_column = [first_row[1], second_row[1], third_row[1]]
third_column = [first_row[2], second_row[2], third_row[2]]... |
d6acb7364656159948026c055b2ce3f68698943e | ivelinakaraivanova/SoftUniPythonFundamentals | /src/Final_Exams/Final Exam_Retake_13_December_2019/02_Boss_Rush.py | 619 | 3.609375 | 4 | import re
pattern = r'\|(?P<name>[A-Z]{4,})\|:#(?P<title>[a-zA-Z]+\s[a-zA-Z]+)#'
n = int(input())
for _ in range(n):
text = input()
if re.search(pattern, text) is not None:
matches = re.finditer(pattern, text)
for match in matches:
boss_name = match.group('name')
title... |
3e967538fbb7abb4559a46a5d06c017c550a2aa5 | ivelinakaraivanova/SoftUniPythonFundamentals | /src/Mid_Exams/Mid_Exam_29_February_2020_Group2/03_Heart_Delivery.py | 899 | 3.953125 | 4 | def jump(index):
if neighborhood[index] >= 2:
neighborhood[index] -= 2
if neighborhood[index] == 0:
print(f"Place {index} has Valentine's day.")
else:
print(f"Place {index} already had Valentine's day.")
neighborhood = list(map(int, input().split("@")))
current_index = 0
w... |
59744cc44bbcee9e51aab2f5513965ad9e87aef6 | ivelinakaraivanova/SoftUniPythonFundamentals | /src/Lists_Basics_Exercise/06_Survival_of_the_Biggest.py | 231 | 3.640625 | 4 | input_numbers = list(map(int, input().split(" ")))
n = int(input())
min_list = sorted(input_numbers)[:n]
result_list =[]
for item in input_numbers:
if item not in min_list:
result_list.append(item)
print(result_list) |
d796b7c16ba75323cf5fc1808bceac1b036166da | ivelinakaraivanova/SoftUniPythonFundamentals | /src/Functions_Exercise/07_Perfect_Number.py | 425 | 3.796875 | 4 | def is_perfect(number):
divisors_list = []
int_num = int(number)
if int_num > 0:
for d in range(1, int_num//2+1):
if int_num % d == 0:
divisors_list.append(d)
if int_num == sum(divisors_list):
return True
else:
return False
input_data = input()
i... |
3116c8cc9c4291df2770db271a96aaa6e2a7c575 | ivelinakaraivanova/SoftUniPythonFundamentals | /src/Data_Types_More Exercises/test.py | 74 | 3.5625 | 4 | list1=[3,4,5,6,7]
del list1[3]
print(list1)
list1.remove(5)
print(list1)
|
5b52810c905e0213d4e30a36931640fe503e8f09 | ivelinakaraivanova/SoftUniPythonFundamentals | /src/Lists_Advanced_Exercise/01_Which_Are_In.py | 265 | 4.15625 | 4 | first_list = input().split(", ")
second_list = input().split(", ")
result_list =[]
for item in first_list:
for item2 in second_list:
if item in item2:
if item not in result_list:
result_list.append(item)
print(result_list) |
b5abd9848b731aa8a03cba962555b14a507290b9 | ivelinakaraivanova/SoftUniPythonFundamentals | /src/Mid_Exams/Mid_Exam_Retake_07_April_2020/03_Moving_Target.py | 1,614 | 3.859375 | 4 | def add_target(input_targets, index_number, value_number):
if index_number in range(len(input_targets)):
input_targets.insert(index_number, value_number)
return input_targets
return False
def shoot(input_list, index_value, power_value):
if index_value in range(len(input_list)):
inp... |
9f53476b11036b2b366e2d78dd39e2b27a157288 | ivelinakaraivanova/SoftUniPythonFundamentals | /src/Final_Exams/Final_Exam_Retake_9_August_2019/03_Followers.py | 1,265 | 3.84375 | 4 |
followers = {}
while True:
data = input()
if data == "Log out":
break
split_data = data.split(": ")
command = split_data[0]
if command == "New follower":
username = split_data[1]
if username not in followers:
followers[username] = [0, 0]
elif command == ... |
7f0765ca0104655f75c63f799f12f3d05639addf | d17125388/assignment-2 | /test-scripts/csvdict.py | 630 | 3.734375 | 4 | import csv
def csv_to_dict(myfile):
try:
with open('file2.txt', newline='', encoding="ISO-8859-1") as file1:
reader = csv.reader(file1)
my_dict = {}
for row in reader:
if (row[1] in my_dict):
my_dict[row[1]] += 1
... |
fb2a40e552b6bcddefcd8693718848ad87407c26 | ashishihota/learning-Algorithms | /linked_list/linked_list_book.py | 1,123 | 4.15625 | 4 | class node(object):
def __init__(self, data):
self.data = data
self.next = None
def get_data(self):
return self.data
def set_next(self, next):
self.next = next
def get_next(self):
return self.next
def has_next(self):
return self.next... |
b3009ce6ba5d68a5e2e95777e79cd83b2b039c8e | Tom-Boyd/Kattis-Solutions-Python3 | /Tarifa.py | 97 | 3.546875 | 4 | x = data = int(input())
for i in range(int(input())):
data += (x - int(input()))
print(data)
|
b3469aa3961040dc139c5b3edbe95b8ca4f24590 | aishowdown/chickenAttack | /dumbplayer.py | 2,595 | 3.9375 | 4 | import actions
class Player:
#Get passed all the board information that never changes throughout the game.
#It is recommended that you store these in member variables since you will probably need to look at them later.
# PARAMS:
# money_payout_rates:
# This is a 50x50 2D array of floats betwee... |
0b246053cbffe4fa6a52f10f5a0982052cdebf4f | azdrachak/CS212 | /212/Unit2/HW2-2.py | 1,564 | 4.125 | 4 | #------------------
# User Instructions
#
# Hopper, Kay, Liskov, Perlis, and Ritchie live on
# different floors of a five-floor apartment building.
#
# Hopper does not live on the top floor.
# Kay does not live on the bottom floor.
# Liskov does not live on either the top or the bottom floor.
# Perlis lives on a h... |
73f9c102df6a749a36759ea146cfd406afb43fe1 | too-hoo/DataAnalysisInAction | /lesson11/dataclean.py | 2,197 | 3.640625 | 4 | # encoding=utf-8
import pandas as pd
from pandas import Series, DataFrame
data = DataFrame(pd.read_excel('data1.xlsx'))
df = DataFrame(data)
# index 可以去掉
df1 = DataFrame(data,index=[0,1,2,3,4,5,6,7,8,9,10],
columns=['No','name','Age','weight','M1','M2','M3','F1','F2','F3'])
# 在没有清洗之前,两种方式输出的数据是一样的,
# 清洗过后只是输出对应... |
8d2256d5a1eaff9c038086dcfeea1c0c78f9064f | johnstonstott/COMP_472_A1 | /src/path_finding.py | 10,429 | 3.640625 | 4 | # -------------------------------------------------------
# Assignment 1
# Written by Johnston Stott (40059176)
# For COMP 472 Section ABIX – Summer 2020
# --------------------------------------------------------
import math
import time
from queue import PriorityQueue
import constants
class Node:
def __init__(s... |
75fa0274e9cfd4193bb5d1730caf90b2b0c5b194 | edagotti689/PYTHON-7-REGULAR-EXPRESSIONS | /1_match.py | 508 | 4.15625 | 4 | '''
1. Match is used to find a pattern from starting position
'''
import re
name = 'sriram'
mo = re.match('sri', name)
print(mo.group())
# matching through \w pattern
name = 'sriram'
mo = re.match('\w\w\w', name)
print(mo.group())
# matching numbers through \d pattern
name = 'sriram123'
mo = re.match... |
a507289b0a9389458884a0416daad3702fb2fabe | IgorLuigi/Projeto---Construcao-de-Software | /src/venda.py | 1,467 | 3.703125 | 4 | import math
class Dinheiro():
def __init__(self, value=0.0, decimals=2, coin_name='R$', method='arredondar'):
self.decimals = decimals
self.coin_name = coin_name
self.value = self.handle_value(value, decimals, method)
@staticmethod
def handle_value(value, decimals, method='arredo... |
965d3cb5ae9807b7982c739ff943648539889bb5 | yorkuscix/PythonII | /Day 6 - Tuesday December 15/isometry_3d.py | 1,162 | 3.75 | 4 | import turtle
turtle.speed(0)
def drawBox(x, y):
turtle.penup()
turtle.setpos(x, y)
turtle.pendown()
turtle.color("red")
turtle.begin_fill()
turtle.setpos(x+87, y+50)
turtle.setpos(x+87, y+150)
turtle.setpos(x, y+100)
turtle.setpos(x, y)
turtle.end_fill()
turtle.color... |
f2c846624e9d54495bae1a627d72d76e50be2d05 | yorkuscix/PythonII | /Day 1 - Saturday November 28/additional_functions.py | 531 | 3.84375 | 4 | # this is a comment. Python ignores these lines
def f(x: float):
if x<0:
return "negative"
if x==0:
return "zero"
if x>0 and x<100:
return "small positive"
if x>=100:
return "large positive"
# g returns the middle element in the list l
def g(l: list):
length_of_l = ... |
cca611d67eedaf8ed33107c09150f75e852b12de | yang-zj1026/sudoku | /my_sudoku.py | 4,500 | 3.78125 | 4 | import time
'''
Class: Sudoku
Input: 9x9 array
function:
check(): check whether the number can be filled in the sudoku
solve(): wrapper of solve method
try(): solving process
get_param(): get the candidate numbers for a block
find_unsolved(): find the blocks that need to be filled
variable:
s... |
36a58a449c03bd9e444ab78a629bf0d7014224a7 | bhuvneshsaini/sequence_labelling | /prediction/before_prediction_addon_code.py | 1,819 | 3.640625 | 4 |
def replace_entities(item, dict_for_readable):
item_list=[]
item=item.split()
for items in item:
if items !="":
if items not in dict_for_readable.keys():
item_list.append(items)
if items in dict_for_readable.keys():
new_i... |
9f21b5f6933071fadbff1d88cb0dfb633adffe40 | DianaMoriarty/python | /Homework2/tic tac toe.py | 6,754 | 3.84375 | 4 | from random import randint, choice
DICTS = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
# функция возвращает размерность доски, введеную пользователем (есть проверка ввода)
def start() -> int:
print("Добро пожаловать в игру 'Крестики нолики'!")
print("Введите размерность доски (от 3 до 5)")
while True:
... |
b5381d8eaff910f7fdfbb3f9de35f53c9c316fc9 | hodgesjake/pyptos | /classicalciphers/classicalcipher.py | 972 | 3.671875 | 4 | """
Jake Hodges
"""
class ClassicalCipher(object):
def __init__(self, encrypted_msg=None, decrypted_msg=None, alpha=None):
self.encrypted_msg=encrypted_msg
self.decrypted_msg=decrypted_msg
if alpha==None:
self.alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
else:
self.... |
8d343ee1d1bf494dbeb26303747077aac981f335 | puspita-sahoo/hacker_rank | /pallindrom.py | 1,534 | 3.84375 | 4 | def pallindrome_creator(str):
if str == str[::-1]:
print("Pallindrome")
elif len(str) < 4 and str != str[::-1]:
print("Not possible")
elif len(str) > 3 :#and str != str[::-1]
for i in range(len(str)):
lst = list(str)
ch = lst.pop(i)
temp = "".join(... |
e2d249f22eeb90adb6fb80d8f2f57d9ea9eedfe3 | jamlem/Boeing-Rover-2-Team | /pretoria/camera_streaming/receive.py | 2,092 | 3.546875 | 4 | import cv2
import socket
import struct
import io
from PIL import Image
import numpy
# Network Info
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = socket.gethostname() # Gets the host name on which the server is located.
port = 60000
# Binds to a Host And Port.
# M... |
d56545807b51c45910a64ed1f343f9300110c8e2 | jamlem/Boeing-Rover-2-Team | /on_board/Rover_Software/Rover_Classes/rover_status.py | 1,973 | 3.578125 | 4 | import json
'''
Used to store the data that will be sent to the client
Represents the status of the Rover
Methods for converting to and from JSON files
Example JSON:
{
"battery_volt": 0,
"heading": 0,
"ir_elevation": 0,
"ir_heading": 0,
"is_valid": false,
"left_velocity": 0,
"ri... |
b0a08df2f473c1c4245c9ef43be7c2a6fe28f4e6 | Anotheroption4726/Learning | /Python/Practice/OpenClassrooms/calculateur-annee-bissextile.py | 475 | 3.890625 | 4 | #!/usr/bin/python3.8
# -*-coding:Utf-8 -*
#
print("Indiquez une année:")
userInput = input()
#
try:
userInput = int(userInput)
assert userInput > 0
except ValueError:
print("Ceci n'est pas une année")
except AssertionError:
print("l'année doit être un nombre positif supèrieur à 0")
else:
if (userInput % 4 == 0 and... |
cd2a9175753f444eecd151afd29af1aabbcfb11e | Anotheroption4726/Learning | /Python/Practice/CodeWars/Amidakuji.py | 3,282 | 4.125 | 4 | """
Amidakuji ( https://en.wikipedia.org/wiki/Ghost_Leg ) is a method of lottery designed to create random pairings between two sets comprised of an equal number of elements.
Your task is to write a function amidakuji that returns the final positions of each element. Note that the elements are an ascending sequence... |
53074c6ca916d527219db098de7c8af7aeeac101 | sumankumar1/python | /NeuralNetwork/rnn.py | 3,903 | 3.515625 | 4 | import numpy as np
def activation_function_output_layer(x):
return tanh(x);
def d_activation_function_output_layer(x):
return 1-np.square(tanh(x));
def activation_function_hidden_layer(x):
return np.maximum(x,0);
def d_activation_function_hidden_layer(x):
return int(x>0);
def error(network_output,exac... |
edbca151325884b09d8930f3d02c46873b8459e6 | silviani15/PrAlPro | /71200592_Video PrAlPro_B_2.py | 1,664 | 3.6875 | 4 | # Silviani Vanesha / 71200592
# Universitas Kristen Duta Wacana
# Informatika / 20
# Struktur Kontrol Percabangan
'''Doni adalah Mahasiswa Informatika UKDW Angkatan 2020. Suatu hari Doni mendapatkan
tugas untuk membuat kalkulator sederhana yang dapat menghitung sisa hasil bagi (modulus),
floor division, dan pem... |
3bd65e3f71300e23d8f879b1e05bae9a8f7c6771 | leer752/battleship | /code/foundation/prep.py | 8,699 | 3.5 | 4 | import pygame
from foundation import init_screen
from g_func import g_var
# Display separate small screen that holds player ships; player will drag & drop ships from this screen
def draw_ship_inventory(placed_ships, orientation):
inventory_rectangle = pygame.Surface((832, 200))
inventory_rectangle.fil... |
b2f2afbf8f51c887ce0a7ec9e611e10a17c71451 | Santiago-Czop/Algo1TP3 | /tortuga.py | 1,911 | 4.09375 | 4 | from vector import Vector
from pluma import Pluma
import math
class Tortuga:
""" Tortuga utilizada como metáfora para llevar a cabo operaciones de dibujado."""
def __init__(self, posicion=Vector(), orientacion=3*math.pi/2, pluma=Pluma()):
""" Crea una instancia de Tortuga.
Args:
po... |
a59503d23f606bad8fc8ff6c68001e6ea1783431 | Rd-Feng/holbertonschool-higher_level_programming | /0x0A-python-inheritance/1-my_list.py | 257 | 4.125 | 4 | #!/usr/bin/python3
"""Define MyList that extends list"""
class MyList(list):
"""add print_sorted instance method that prints the list in sorted order"""
def print_sorted(self):
"""print list in sorted order"""
print(sorted(self))
|
43f55b4f9ff499d1eb20a51d14d643b5f9ec8dd7 | Rd-Feng/holbertonschool-higher_level_programming | /0x0B-python-input_output/2-read_lines.py | 383 | 4.09375 | 4 | #!/usr/bin/python3
""" define read_lines function """
def read_lines(filename="", nb_lines=0):
""" reads nb_lines lines of the text file filename """
with open(filename, encoding='utf-8') as f:
ls = f.readlines()
if nb_lines <= 0 or nb_lines >= len(ls):
print(*ls, end="", sep="")
... |
c267019ce36e280bdd37eddc578b86dbefa15fde | Rd-Feng/holbertonschool-higher_level_programming | /0x0A-python-inheritance/7-base_geometry.py | 555 | 3.765625 | 4 | #!/usr/bin/python3
"""Define BaseGeometry class"""
class BaseGeometry:
"""basic geometry"""
def area(self):
"""return area of the instance"""
raise Exception('area() is not implemented')
def integer_validator(self, name, value):
"""validate value to be integer greater than 0"""
... |
28cffb14dd32bc7ab103e0c6a351b0936cfca0e2 | Rd-Feng/holbertonschool-higher_level_programming | /0x0B-python-input_output/7-save_to_json_file.py | 267 | 3.671875 | 4 | #!/usr/bin/python3
""" define save_to_json_file """
def save_to_json_file(my_obj, filename):
""" write an object to a text file using JSON representation """
with open(filename, 'w', encoding='utf-8') as f:
f.write(__import__('json').dumps(my_obj))
|
7e03882cde60e19a5de9948c9503044da9067b41 | Rd-Feng/holbertonschool-higher_level_programming | /0x0B-python-input_output/14-pascal_triangle.py | 395 | 3.6875 | 4 | #!/usr/bin/python3
""" define pascal_triangle function """
def pascal_triangle(n):
""" return a pascal triangle of n rows """
l = []
for i in range(n):
l.append([0 for e in range(i + 1)])
l[i][0], l[i][i], h, t = 1, 1, 1, i - 1
while h <= t:
l[i][h] = l[i - 1][h] + l[i ... |
9e8f9df1559b886305d64895386a45fb28c351ba | Alexie209/Savings-Calculator | /UI/console.py | 24,856 | 3.703125 | 4 | from Service.cost_service import CostService
from Service.income_service import IncomeService
from Service.savings_service import SavingsService
class Console:
def __init__(self, estimated_income_service: IncomeService, realized_income_service: IncomeService,
estimated_cost_service: CostSe... |
62e3752738f77f5c638ecbfcc3451b901338cec3 | vesnushka-sokol/test | /03_try_except/word_count.py | 819 | 4.15625 | 4 | def count_words(filename):
"""" Подсчет приблизительного количества строк в файле """
try:
with open(filename) as f:
content = f.read()
except FileNotFoundError:
with open('missing_files.txt', 'a', encoding='utf-8') as m:
m.write(filename + '\n')
# pas... |
414f85f5cf856c1ab0f5c625cd292041499bc0d2 | vesnushka-sokol/test | /01_basis/hello_admin.py | 564 | 3.578125 | 4 | names = []
if len(names) == 0:
print('We need to find some users!')
for name in names:
if name == 'admin':
print(f'Hello {name}, would you like to see a status report?')
else:
print(f'Hello {name.title()}, thank you for logging in again')
current_users = ['Eric', 'Maria', 'Alex', '... |
a41945a257f30ea34d37ebc25a4d516279c29a64 | Saisagar-singh/credit_cal_in_python | /Credit Calculator/Problems/How long is that word/task.py | 75 | 3.84375 | 4 | word = input()
x = len(word)
print("{} has {} letters".format(word, x))
|
6fa7f9448d9c41ef4cd9e433d5db69330d0f4538 | shrirangmhalgi/Python-Bootcamp | /26. Decorators/decorator_issue_solution.py | 602 | 3.515625 | 4 | from functools import wraps # NOTE THIS IMPORT
def log_function_data(function):
@wraps(function) # NOTE THIS LINE
def wrapper(*args, **kwargs):
"""I am a wrapper function"""
print(f"You are about to call... {function.__doc__}")
print(f"You are about to call... {function.__name__}")
... |
705cc760876474bc595a7244895ea27ecb875d76 | shrirangmhalgi/Python-Bootcamp | /25. Iterators Generators/iterators.py | 495 | 4.34375 | 4 | # iterator is object which can be iterated upon An object which returns data, one at a time when next() is called on it
name = "Shrirang"
iterator = iter(name)
print(next(iterator))
print(next(iterator))
print(next(iterator))
print(next(iterator))
print(next(iterator))
print(next(iterator))
print(next(iterator))
print... |
d7367c63223948b9886e5667e35f0319e2aca0b1 | shrirangmhalgi/Python-Bootcamp | /17. Functions/kwargs_unpacking.py | 187 | 3.71875 | 4 | def name(first, second):
print(f"{first} says hello to {second}")
names = {"first" : "shrirang", "second" : "mhalgi"}
name(**names)
# dictionary gets unpacked into keyword arguments |
2302ed436657bca98feffd12477b4294ba12313b | shrirangmhalgi/Python-Bootcamp | /8. Boolean Statements/conditional_statements.py | 789 | 4.125 | 4 | name = input("Enter a name:\n")
if name == "shrirang":
print("Hello Shrirang")
elif name == "suvarna":
print("Hello Suvarna")
elif name == "rajendra":
print("Hello Rajendra")
else:
print("Hello User")
# truthiness and falsiness
# (is) is used to evaluate truthiness and falsiness
# falsiness includes
#... |
d81cadb1c01234f822fab833bc67f06b8c0cfa10 | shrirangmhalgi/Python-Bootcamp | /20. Lambdas and Builtin Functions/builtin_functions.py | 1,851 | 4.125 | 4 | import sys
# 1. all() returns true if ALL elements of iteratable are truthy
print(all(list(range(10))))
print(all(list(range(1, 10))))
# 2. any() returns true if ANY of the element is truthy
print(any(list(range(10))))
print(any(list(range(1, 10))))
# 3. sys.getsizeof
print(sys.getsizeof([x % 2 == 0 for x in range(1... |
713b3b42119f727b8e3bc59a09a6f0f27e748339 | shrirangmhalgi/Python-Bootcamp | /12. Lists/lists.py | 1,903 | 4.53125 | 5 | # len() function can be used to find length of anything..
# lists start with [ and end with ] and are csv
task = ["task 1", "task 2", "task 3"]
print(len(task)) # prints the length of the list...
list1 = list(range(1, 10)) # another way to define a list
# accessing data in the lists
# lists are accessed like arra... |
2a08e14d4d0b7805a1d99d3a99e2145ee00ab945 | shrirangmhalgi/Python-Bootcamp | /29. Testing with python/test.py | 252 | 3.796875 | 4 | # assert statement is used to test something
# if a python file is run with -O flag, it ignores all the assertions
def add(x, y):
assert x > 0 and y > 0, "Both the numbers should be positive"
return x + y
print(add(1, 10))
print(add(-1, 10))
|
4a9158546b978eb121262bb114def980bfbc2ca9 | shrirangmhalgi/Python-Bootcamp | /30. File Handling/reading_file.py | 528 | 4.1875 | 4 | file = open("story.txt")
print(file.read())
# After a file is read, the cursor is at the end...
print(file.read())
# seek is used to manipulate the position of the cursor
file.seek(0) # Move the cursor at the specific position
print(file.readline()) # reads the first line of the file
file.seek(0)
print(file.readlines... |
134c621ca89c262856aa80818c916af4ab36e02e | shrirangmhalgi/Python-Bootcamp | /10. Loops/while.py | 119 | 3.640625 | 4 | condition = None
while condition != "shrirang":
condition = input("ah ah ah.. you didnt say the magic word...! : ") |
7020db9c0d66b9d83497aafb7897c2dee532a283 | shrirangmhalgi/Python-Bootcamp | /21. Debugging and error handling/debugging.py | 233 | 3.734375 | 4 | import pdb
first = "first"
second = "second"
pdb.set_trace()
result = first + second
third = "third"
result += third
print(result)
# common pdb commands
# l -> list
# n -> next line
# p -> print
# c -> continue / finishes debugging |
9b17a97a7db1d2b447a0e9285a53c428e706e37b | shrirangmhalgi/Python-Bootcamp | /17. Functions/scope.py | 365 | 4 | 4 | name = "shrirang"
def my_name():
global name
name += " mhalgi"
return f"your name is {name}"
print(my_name())
# you cant change the name value however you can declare a same variable which has local scope
def outer():
count = 0
def inner():
nonlocal count
count += 1
ret... |
d7df6511316ed65740cca6f8570f152fad2637fe | chivitc1/python-turtle-learning | /turtle15.py | 552 | 4.15625 | 4 | """
animate1.py
Animates the turtle using the ontimer function.
"""
from turtle import *
def act():
"""Move forward and turn a bit, forever."""
left(2)
forward(2)
ontimer(act, 1)
def main():
"""Start the timer with the move function.
The user’s click exits the program."""
reset()
sha... |
1731be54e0a9905f6f751a97808931ce54e0bec0 | chivitc1/python-turtle-learning | /menuitem_test.py | 1,121 | 4.28125 | 4 | """
menuitem_test.py
A simple tester program for menu items.
"""
from turtle import *
from menuitem import MenuItem
from flag import Flag
INDENT = 30
START_Y = 100
ITEM_SPACE = 30
menuClick = Flag()
def changePenColor(c):
"""Changes the system turtle’s color to c."""
menuClick.value(True)
color(c)
def ... |
4dfa7c1f1f9f51b838fcfb7e7d6c9f5f4fad2d42 | chivitc1/python-turtle-learning | /turtle17.py | 1,508 | 4.46875 | 4 | """
testpoly.py
Illustrates the use of begin_poly, end_poly, and get_poly to
create custom turtle shapes.
"""
from turtle import *
def regularPolygon(length, numSides):
"""Draws a regular polygon.
Arguments: the length and number of sides."""
iterationAngle = 360 / numSides
for count in range(numSides... |
205ea4e4c766478523e1ea6464fdde9be69bfb91 | chivitc1/python-turtle-learning | /turtle7.py | 583 | 3.546875 | 4 | from turtle import reset, pencolor, speed, width, onkey, listen, mainloop, forward, backward, right, left, clear
def main():
reset()
pencolor("blue")
speed(0)
width(2)
onkey(clear, "c")
onkey(lambda: forward(5), "Up")
onkey(lambda : backward(5), "Down")
onkey(lambda : right(5), "Right")... |
e1893128be5ef3b16c3d4b56de896a8ccd67fbc4 | jeppe742/FaceDetection | /hog.py | 5,444 | 3.921875 | 4 | import numpy as np
def get_gradient(img):
"""
Calculate the 1.order gradient of an Image
Params:
-------
img: Numpy array of input Image
Returns:
------
gradientx: Numpy array of horizontal gradient
gradienty: Numpy array of vertical gradient
"""
(n, m) = np.shape(img)
... |
bf19b38f9e6f42dda55e6cbed013463f0ee37d88 | muskanali-2001/area_of_circle | /area_of_circle.py | 157 | 4.28125 | 4 | import math
r = float(input("Input the radius of the circle: "))
area = math.pi* r * r
print("The area of the circle with radius {} is : {}".format(r,area))
|
129f8bbd14f28856b4227b7d542c25477d7422fb | chyavan-mc/My-Solutions-to-Leetcode-problems-using-Python-3 | /Add Digits.py | 314 | 3.515625 | 4 | class Solution:
def addDigits(self, num):
"""
:type num: int
:rtype: int
"""
lis = list(str(num))
while(len(lis)!=1):
summ = 0
for item in lis:
summ += int(item)
lis = list(str(summ))
return int(lis[0]) |
06c8d5f81ffda34d0693d721f857caf02f000eeb | ruben2732/ALGORITMIA | /SEMINARIOS/Seminario1/Ej3.py | 257 | 3.5 | 4 | from typing import Iterator
from SEMINARIOS.Seminario1.Ej2 import take
def squares1():
num=1
while True:
yield (num*num)+1
num+=1
if __name__ == "__main__":
n = 10
iter=squares1()
print(list(take(10, squares1())))
|
7f15205cb37d79211d25dd352afdd64a20dd4995 | shaishav-p/Inventory-Management-System | /source_code.py | 19,787 | 3.859375 | 4 | import os
import sys
import time
def Date(): # function returns current date
currentDateAndTime = time.asctime(time.localtime(time.time())) # gives current date and time
currentDateAndTime = currentDateAndTime.split()
del currentDateAndTime[-2] # removes time from list so the list now only contains the da... |
85c90222620112056beeca40bd89fa028eddaa37 | MichaelTennyson/OOP | /lab7(practice).py | 2,775 | 4.21875 | 4 | import string
# converts file into a list of strings
def create_data_list(data_file : string) -> list:
o_file = open(data_file, 'r')
data_list = []
for line_str in o_file:
data_list.append(line_str.strip().split(','))
return data_list
def monthly_averages(data_list : list) -> list:... |
72aa936d0a9cfb8dc81144536c647a756e3a11d7 | MichaelTennyson/OOP | /week10tut3b.py | 503 | 3.515625 | 4 | class Bank_account(object):
def __init__(self, IBAN, account_no, availabe_funds, transactions):
self.IBAN = IBAN
self.account_no = account_no
self.available_funds = availabe_funds
self.transactions = transactions
def deposit(self, money_deposit):
money_deposit +=... |
dab151fa8d3e2045bd5fab97d96c7ed1e1e9fe7f | MichaelTennyson/OOP | /lab3(practice).py | 516 | 4.5 | 4 | # The following program scrambles a string, leaving the first and last letter be
# the user first inputs their string
# the string is then turned into a list and is split apart
# the list of characters are scrambled and concatenated
import random
print("this program wil take a word and will scramble it \n")
... |
410f95e96136077229b92be51e1a5678bb1b855c | angelmorenocalvo/interfaz_grafica | /fixed.py | 1,587 | 3.546875 | 4 | #!/usr/bin/env python
# example fixed.py
import pygtk
pygtk.require('2.0')
import gtk
class FixedExample:
# This callback method moves the button to a new position
# in the Fixed container.
def move_button(self, widget):
self.x = (self.x+30)%300
self.y = (self.y+50)%300
self.fixed... |
48e8b7b1450c83c13b717e9a12a3c5a844addcb1 | Manevle16/UTDSpring2019 | /AdvancedAlgorithms/OptimalShelving/OptimalShelf.py | 6,506 | 3.625 | 4 | import heapq
import math
import statistics
import copy
def OptimalShelving(books, shelves, f, L):
#books.sort(reverse = True)
#print(books)
i = 0
j = 0
minSpace = L*f
print("j = 0 to 29")
while(j < len(books)):
print(" j =", j)
print(" if shelves[{4}][0]({0}) - ... |
4dc1066186351991f91bc01d23a889a27405cbbe | ChristianGold/TechTree | /class_tech.py | 393 | 3.734375 | 4 | __author__ = 'Christian'
class Tech:
createdTechs=0
def __init__(self,year):
self.__year=year
Tech.createdTechs+=1
def __del__(self):
Tech.createdTechs-=1
def __setYear__(self,year):
if (type(year)==int):
self.__year=year
print("year: ")
... |
a1ecc3e6030dfed648ebe45031bc04a0d60ba3b5 | McKizzle/CSCI-577-Computing-Derivatives | /convolver.py | 3,657 | 3.546875 | 4 | import numpy as np
import pylab as py
import matplotlib.pyplot as plt
import math as m
import scipy.signal as sig
def derive_dot(y,cf,lcf,rcf,h):
""" Calculates the derivative using the dot product.
:param y: The y values of the of the discretized function with step a size of h.
:param cf: The cent... |
59be48dda4f7248ad44bd11c049902b45ac2de81 | kahuria00/python-series | /list_methods.py | 3,510 | 4.25 | 4 |
import functools
import operator
import itertools
#accessing list items
#list indexing
companies = ["Apple","Huawei","Samsung","Infinix","Oppo","Nokia","BlackBerry"]
#positive indexing
print(companies[0]) #get first item in list
#negative indexing
print(companies[-1]) #gets last item in list
#range indexing
... |
415a67a9d93c18d9794baadf1c50d0eb9e51ae27 | Yvonnexx/code | /binary_search.py | 341 | 4.125 | 4 | #!/usr/bin/python
def binary_search(num, target):
length = len(num)
start = 0
end = length - 1
while start < end:
mid = start + (end-start)/2
if target > num[mid]:
start = mid + 1
else:
end = mid
return start
num = [1,2,3,4,5]
target = 3
print binary... |
3f2fdb84666486f7b7ceba5ec46e0b3e7b203f6b | Yvonnexx/code | /longest_valid_parentheses.py | 415 | 3.890625 | 4 | #!/usr/bin/python
def longest(s):
if s == '' or s == '(' or s == ')':
return 0
stack = [(-1, ')')]
maxlen = 0
for i in range(len(s)):
if s[i] == ')' and stack[-1][1] == '(':
stack.pop()
maxlen = max(maxlen, i-stack[-1][0])
else:
stack.append((... |
f1944db1a569de3888e4edd5b8d915a5589fdf41 | Yvonnexx/code | /missing_number.py | 550 | 3.875 | 4 | #!/usr/bin/python
def missing(num):
"""
tmp = 0
res = 0
for i in range(len(num)):
tmp += num[i]
for i in range(1, len(num)+2):
res += i
return res - tmp
"""
tmp = 0
temp = 0
for i in range(len(num)):
tmp ^= num[i]
print tmp
for i in range(1, l... |
041a3fc69fc859577d6b4fc5fc611d9c521be641 | Yvonnexx/code | /longest_substring_without_repeating_characters.py | 396 | 3.6875 | 4 | #!/usr/bin/python
def longest_substring(s):
maxlen = 0
start = 0
hashtable = [-1]*256
for i in range(len(s)):
if hashtable[ord(s[i])] != -1:
hashtable[ord(s[start])] += 1
start += 1
if i - start + 1 > maxlen:
maxlen = i - start + 1
hashtable[o... |
76ea694dac2f6c05ec7a14e1f8403d889264c83b | Yvonnexx/code | /binary_tree_level_order_traversal.py | 712 | 3.8125 | 4 | #!/usr/bin/python
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def levelOrder(root):
res = []
if not root:
return res
level = [root]
while level:
nextlevel = []
thislevel = []
for tmp in level:
... |
07019ba12a27eedc739a21d1bb1b540d28cdcff3 | Yvonnexx/code | /permutations2.py | 877 | 3.65625 | 4 | #!/usr/bin/python
def permute(num):
def dfs(num, valuelist):
if len(valuelist) == len(num):
res.append(valuelist[:])
return
for i in range(len(num)):
if num[i] in valuelist:
continue
valuelist.append(num[i])
dfs(num, valuel... |
15c33b5f061476c6d1122e9344b7415a776552be | Yvonnexx/code | /insert_sort_list.py | 969 | 4 | 4 | #!/usr/bin/python
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def insertSortList(self, head):
if not head or not head.next:
return head
dummy = ListNode(0)
dummy.next = head
curr = head
while curr.next... |
ff062da30025a5ef08a5bb40735559ba72b08207 | Yvonnexx/code | /divide_two_integers.py | 610 | 3.96875 | 4 | #!/usr/bin/python
def divide(dividend, divisor):
if (dividend < 0 and divisor > 0) or (dividend > 0 or divisor < 0):
if abs(dividend) < abs(divisor):
return 0
sum = 0
count = 0
res = 0
a = abs(dividend)
b = abs(divisor)
import pdb;pdb.set_trace()
while a >= b:
... |
9f988df47d26d9e7dae9fe05d4ef5a225fb1c630 | Yvonnexx/code | /dfs/missing_value.py | 247 | 4.03125 | 4 | #!/usr/bin/python
def missing_value(num):
x1 = num[0]
x2 = 1
n = len(num)
for i in range(1, n):
x1 = x1 ^ num[i]
for i in range(2, n+2):
x2 = x2 ^ i
return x1 ^ x2
num = [1,2,3,5]
print missing_value(num)
|
169bb5c0ccc76a586f0eeb11d13f19ed403dd4fa | Yvonnexx/code | /distinct_subsequences.py | 358 | 3.546875 | 4 | #!/usr/bin/python
def numDistinct(s, t):
cnt = 0
if len(s) == 0:
if len(t) == 0:
return 1
else:
return 0
if len(t) == 0:
return 1
for i in range(len(s)):
if s[i] == t[0]:
cnt += numDistinct(s[i+1:], t[1:])
return cnt
s = 'rabbbit'... |
498242e9fe6a45ee6b8f820ac528f7693b103f5f | szwank/Interviwe-task--movie-database-with-api | /SQLiteDatabase.py | 1,988 | 3.609375 | 4 | import sqlite3
from sqlite3 import Error
from Utils import Utils
class DatabasePathError(Exception):
"""Error for wrong database path"""
class SQLiteDatabase:
def __init__(self, path_to_database: str):
self.path_to_database = path_to_database
def create_connection(self):
... |
695ebc94c3b4b769187f5728f1060809aff2b4dc | Engineer1080/RaspberryLED-Control | /led.py | 2,322 | 3.734375 | 4 | import RPi.GPIO as GPIO
import time
#set color
red_led = 23 #connect your red LED to pin 23
green_led = 18 #connect your green LED to pin 18
yellow_led = 24 #connect your yellow LED to pin 24
#set pins
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(red_led,GPIO.OUT)
GPIO.setup(green_led,GPIO.OUT)
GPIO.se... |
5287031b2e38562feef2469c038d61a38d711935 | charup/pythonsamples | /lenStr.py | 266 | 3.859375 | 4 | def lenRecur(aStr):
'''
aStr: a string
returns: int, the length of aStr
'''
# Your code here
print aStr
if aStr[:] == '':
return 0
else:
return lenRecur(aStr[1:])+1
length = lenRecur('String')#'Ab')#
print length |
cb11cb884186dabcc3463f04dea3a019c52c87aa | shreyashpandey/toybox | /ctci/1/5/main.py | 995 | 3.609375 | 4 | #!/usr/bin/env python3
def one_away(s, target):
if len(s) == len(target):
# Replace
diffs = 0
for i in range(len(s)):
if s[i] != target[i]:
diffs += 1
return diffs <= 1
elif len(s)-1 == len(target):
# Delete
deleted = 0
for i i... |
e71efe7e9ca6afc0515af856477c1cf77e32c31e | shreyashpandey/toybox | /bfdbg/interpreter.py | 2,729 | 3.546875 | 4 | #!/usr/bin/env python3
import sys
from data import BrainfuckData
class BrainfuckProgram(object):
"""
This class represents a brainfuck program.
This takes a brainfuck program as a string in it's initializer.
It provides a .step() method to step through execution.
"""
def __init__(self, progr... |
ba3f31870005d1e5f5345ad427a7e353261db7f4 | shreyashpandey/toybox | /ctci/3/3/main.py | 710 | 3.765625 | 4 | #!/usr/bin/env python3
class StackSet:
def __init__(self, max_height):
self.stacks = [[]]
self.max_height = max_height
def push(self, v):
if len(self.stacks[-1]) < self.max_height:
self.stacks[-1].append(v)
else:
self.stacks.append([v])
def pop(self... |
dc84ceeb45538746bf97dded4386af41f765960a | AlejandroQR23/pong | /scoreboard.py | 742 | 3.671875 | 4 |
from turtle import Turtle
FONT = ("Courier", 60, "normal")
class Scoreboard( Turtle ):
def __init__( self ):
super().__init__()
self.color("white")
self.penup()
self.hideturtle()
self.l_score = 0
self.r_score = 0
self.update_score()
... |
f7b384ab7758a410febccf312e63fb6bbc1719a7 | Peduc/msu | /7sem/4 dictionary/linkedlist.py | 1,412 | 4 | 4 | class Node:
def __init__(self):
self.key = None
self.freq = 1
self.next = None
self.ops = 0
self.len = 0
class LinkedList:
def __init__(self):
self.head = None
self.len = 0
def __len__(self):
return self.len
def insert(self, key):
ops = 0
flag = False
curr = self.head... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.