blob_id
stringlengths
40
40
repo_name
stringlengths
5
119
path
stringlengths
2
424
length_bytes
int64
36
888k
score
float64
3.5
5.22
int_score
int64
4
5
text
stringlengths
27
888k
1e3d745bddc1d6af8510431dec4dff27f1f08db1
nimishbongale/5th-Sem-ISE
/SEE/Scripting/2/2b/2b.py
2,243
3.75
4
import pandas as pd from pandas import Series, DataFrame import numpy as np import matplotlib.pyplot as plt import seaborn as sns student_df = pd.read_csv("StudentsPerformance.csv") print("======Data Headers=======") student_df.head() print("=====Data Decription=====") student_df.info() student_df.describe() studen...
604708a7ada56fe57a4eb440cf1bf606c6da4619
omaransarispi/Towel
/src/Utils/Token/Tokenizer.py
2,078
3.859375
4
from abc import ABC, abstractmethod from typing import Optional from src.Utils.Token.Tokens import Tokens class Tokenizer(ABC): """The Tokenizer abstract class""" MAP_TO_ROMAN_NUMERAL_PATTERN = "MapToRomanNumeralPattern" INITIALIZE_CURRENCY_RATE_PATTERN = "InitializeCurrencyRatePattern" CONVERT_TO_AR...
f606c84b1771a68afdf6ea8fafb01d8655710eae
monk-after-90s/python
/producer_consumer_while.py
510
3.53125
4
import time from datetime import datetime def consumer(): temp_task = None while True: temp_task = yield f'{temp_task}完成,time:{datetime.now()}' print(f'\n处理{temp_task},time:{datetime.now()}') time.sleep(1) print(f'完成{temp_task},time:{datetime.now()}') task_handler = consumer(...
570803f08e14d1da71aac928d7cff5c8165c88f4
RakibRyan/nand2tetris-1
/Hack assembler/convert.py
1,374
3.625
4
""" Convert mnemonics into machine code @author:shubham1172 """ def dest(mnemonic): """ :param mnemonic: in original command :return: code for it """ data = ['', 'M', 'D', 'MD', 'A', 'AM', 'AD', 'AMD'] return bin(data.index(mnemonic))[2:].zfill(3) def comp(mnemonic): """ :param mnemo...
a9803600c015f01638000f9c589612d351668616
mturpin1/CodingProjects
/Python/madlib.py
1,921
4.25
4
import os def madLibs(): words = [] input('Hello, and welcome to Mad Libs! Press \'Enter\' to continue...') input('''Instructions-The program will ask you for 15 words(noun, adjective, verb, etc.) After you have given all 15 words, the program will print a story, using the random words you have chosen. Hold...
31dd023d8efa2107effc92321cdff0153df215b2
Cheng0639/CodeFights_Python
/Python/82_sortCodeFighters.py
1,693
3.640625
4
def sortCodefighters(codefighters): res = [CodeFighter(*codefighter) for codefighter in codefighters] res.sort(reverse=True) return list(map(str, res)) class CodeFighter(object): def __init__(self, username, id, xp): self.username = username self.id = int(id) self.xp = int(xp) ...
01bc5a10ad8558364f65ce8f1fcc52b55f47633b
jaechoi15/CodingDojoAssignments
/Python/PythonOOP/self_init.py
435
3.859375
4
# class User(object): # name = "Anna" # anna = User() # print "Anna's name:", anna.name # User.name = "Bob" # print "Anna's name after change:", anna.name # bob = User() # print "Bob's name:", bob.name class User(object): def __init__(self, name, email): self.name = name self.email = email ...
16896a65d972a80731959d6189e5a3962fe772ac
fsouza/fisl_concorrencia_paralelismo
/sum.py
414
3.875
4
# Copyright 2013 Francisco Souza. All rights reserved. # Use of this source code is governed by a BSD-style # license that can be found in the LICENSE file. import multiprocessing def power(value): return value * value if __name__ == "__main__": numbers = xrange(1, 20001) pool = multiprocessing.Pool(20)...
be2a55a6e97e56ea7d4933b1486ae4e1317c8105
pavipr/pavi-codekata
/iso.py
110
3.671875
4
n=input().split() for i in n: m=set(i) if len(n)==len(m): print("Yes") else: print("No")
1ed1246fa3c70f8faace6c7a2e087eb93d0dd3d3
mazh661/distonslessons
/Lesson5/ex7.py
212
3.65625
4
arr=[ [0,1,1], [1,0,0] ] # arr=[1,2,3] count=0 #take array for i in range(len(arr)): temparr = arr[i] #go into array for j in temparr: if j == 1: count=count+1 print(count)
7ae0deeeee344565c97681aeb58c1327ee8a427e
tacongnam/oneshotAC
/extra/scrape_cf_contest_writers.py
1,504
3.546875
4
"""This script scrapes contests and their writers from Codeforces and saves them to a JSON file. This exists because there is no way to do this through the official API :( """ import json import urllib.request from lxml import html URL = 'https://codeforces.com/contests/page/{}' JSONFILE = 'contest_writer...
f7348b13a294674fac9db9bc9f27ff5f00caa2f4
viver2003/school
/whole_or_decimal.py
300
4.34375
4
import math x=float(input('number')) if x == 0: print 'This number is niether positive nor negative!' elif x > 0: print 'This number is a positive number!' else: print 'This number is a negative number!' if x%2: print 'This is a even number!' else: print 'This is an odd number!'
fe9f8a1ae39343ed9fd54eb5851575e7726cdef5
drunkwater/leetcode
/hard/python/c0153_798_smallest-rotation-with-highest-score/00_leetcode_0153.py
1,600
3.53125
4
# DRUNKWATER TEMPLATE(add description and prototypes) # Question Title and Description on leetcode.com # Function Declaration and Function Prototypes on leetcode.com #798. Smallest Rotation with Highest Score # Given an array A, we may rotate it by a non-negative integer K so that the array becomes A[K], A[K+1], A{K+2]...
a72b9fcd754bb72e541bca208f3bcec9fee3c5c7
Vdknet/python_graph
/algorithms/dijkstra/dijkstra.py
945
3.515625
4
from structures.simple import Node, Edge def list_to_node_graph(g): graph = [] for i in range(len(g)): graph.append(Node(i)) for i in range(len(graph)): for e in g[i].keys(): val = g[i].get(e) edge = Edge(e, val, graph[e]) reverse_edge = Edge(i, val, gr...
a6ebe746f4ec6aee2c6be01c02e9167cd48e3a42
houcha/the-lord-of-the-strategy
/windows/image_states.py
1,034
3.546875
4
""" This module contains window image states (constant and temporary). """ from abc import ABC import time import pygame # State pattern. class ImageState(ABC): """ Base class of image states. """ def __init__(self, window): self.window = window def update(self): """ Is called to check...
792a79c9939f7caf1846023ea5839502ad6d7d80
bweedop/housingPrices
/housingPrice.py
12,923
3.671875
4
from sklearn.model_selection import train_test_split from sklearn import datasets, linear_model, tree from sklearn.linear_model import LinearRegression, LassoCV from sklearn.metrics import mean_squared_error, r2_score from sklearn.preprocessing import StandardScaler, Imputer from sklearn.neural_network import MLPRegres...
3ab1f0e168c80a9f70f9337b55f158f21d972b5b
sookoor/PythonInterviewPrep
/BinaryTree.py
10,125
3.84375
4
import sys class Node(object): def __init__(self, data = None): self.data = data self.children = [None, None] self.parent = None class BinaryTree(object): def __init__(self): self.root = None def _insert_node(self, root, data): if root is None: root = N...
345eea86c2944cf1e104d933ed8ad6fbe6eb820f
JuDa-hku/ACM
/leetCode/110BalancedBinaryTree.py
1,243
3.828125
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 root, a tree node # @return a boolean def calculateHeight(self, root): if root == None: return 0 i...
98e3a1bed80597b5e7b612ce9bc137fc9d695462
dvincelli/scalene
/scalene/reservoir.py
1,056
3.8125
4
import math import random class reservoir(): """Implements reservoir sampling to achieve the effect of a uniform random sample.""" sample_array = [] total_samples = 0 max_samples = 0 next_random_choice = 1 def __init__(self, size=0): self.max_samples = size self.total_samp...
c27771c971d25aaee04c402b81652af414e968e4
ynonp/python-examples
/05_syntax_lab/03.py
534
4.09375
4
""" Write a program that generates a random number between 1 and 10,000, and prints the sum of its digits. For example if the number was: 2345 the result should be: 14. """ from random import randint num = randint(1,10000) print "Starting with: %d" % num # Numeric calculation num_i = num sum_d = 0 while num_i != 0:...
dd44b2e6833089f7ae941c4c7d5aa17a8f0cde65
dannydoyunkim/mytask
/Python_Practice/Python실습-김도연/제공/M3/example/m3_3_breakTest_001.py
237
3.5
4
count = 1 result = 0 limit = int(input("어디까지 더할까요? ")) while count <= 1000: result = result + count count = count + 1 if count == limit: break print("1부터 %d까지의 합은: %d"% (count,result))
17cfded552b023bb7bf7f213f4425e6f939b4b1d
alzheimeer/holbertonschool-higher_level_programming
/0x03-python-data_structures/7-add_tuple.py
333
3.734375
4
#!/usr/bin/python3 def add_tuple(tuple_a=(), tuple_b=()): a = list(tuple_a) b = list(tuple_b) la = len(a) lb = len(b) if la < 2: for i in range(la, 2): a.append(0) if lb < 2: for i in range(lb, 2): b.append(0) nt = [a[0] + b[0], a[1] + b[1]] return...
2f16cec1cec7ce7b890042ab0c709368c341f288
Mohamedabdeltawab86/integration_vs_git
/algorithms - Harmash/evenBlock.py
282
4.21875
4
#take input from the user n = 0 m = 0 while n<=0 or m<=0: n = int(input('Enter a number of columns between 1-8: ')) m = int(input('Enter a number of hashes between 1-8: ')) #simple increasing block for i in range(1, n+1): print(" " * (n-i), end="") print("#" * m)
b0714244dd12fc90c710191bd24ce11da3027baa
sepehrs1378/CompilerFall2020
/Assignments/HW3/code.py
627
3.609375
4
def parseE(): parseT() parseEp() if tokern == "\$": return "success" else: return "error" def parseEp(): if token == "+": token = nextToken() parseE() elif token == "-": token = nextToken() parseE() elif token == "\$": return else...
59bb871db2fce0918657725714bddae33494d7f5
urbaneriver426/OrderedList
/OrderedList.py
3,578
3.875
4
class Node: def __init__(self, v): self.value = v self.prev = None self.next = None class OrderedList: def __init__(self, asc): self.head = None self.tail = None self.__ascending = asc def compare(self, v1, v2): if v1 < v2: return -1 elif v1 == v2: return 0 else: return +1 def add(se...
905db15d8313e14cdbaca48a206f2ea9c986f273
balibuxiaxue/python_study
/findstr().py
209
3.5625
4
def findstr(): a=input('请输入目标字符串:') b=input('请输入子字符串(两个字符):') a.count(b) print('子字符串在目标字符串中共出现', a.count(b) ,'次')
6c716afb8855aa3fd6ab658fbb8e408f3a1fb9ec
yaggul/Programming0
/week1/3-And-Or-Not-In-Problems/evenover20.py
224
3.96875
4
print() print('Welcome to even and over 20') print() num=int(input("please insern a number: ")) if num%2==0 and num>20: print() print("Yes it is!") print() else: print() print("No it isn't!") print()
e8e98e10ee2e0d87549d87a825616a92dc9fb7d6
AlexKaravaev/ifmo
/bachelor/SPO/lab4/task3/stability.py
1,726
3.71875
4
# Вывод матрицы def out(matrix): if matrix: for i in range (0, rows(matrix)): print(matrix[i]) return " " def rows(matrix): return len(matrix) # Проверка устойчивости по Гурвицу def gur(A): koef = [] k1 = -A[0][0]*A[1][1]*A[2][2]+A[0][0]*A[2][1]*A[1][2]+A[1][0]*A[2][2]*A[0][1]-A[1][0]*A[0][2]*A[2][1]-A[2][...
3333a54dfac2b98cdccd24d8e65d32a6ee47b828
Neha-kumari200/python-Project2
/Count_freq_list.py
384
4.09375
4
#Counting the frequencies in the list using dictionary in python def CountFrequency(my_list): freq = {} for item in my_list: if item in freq: freq[item] += 1 else: freq[item] = 1 for key, value in freq.items(): print("%d : %d"%(key, value)) my_list = [1, 1, ...
bfc6e7438acee469fa3f1966a3471bcd834d4901
jimwaldo/HarvardX-Tools
/src/main/python/classData/user.py
4,317
3.578125
4
#!/usr/bin/env python """ Object definition and utility functions for the course users (students) file Contains a definition of a user object, that holds all of the information found in the users file for each entry. There is a function that will build a dictionary, keyed by the user id, for all of those entries. Ther...
ca18ac4ee8c0ced3454a103ed3d64ac2723c79f4
Dynamonic/Slicer
/SliceTest/shape.py
5,360
3.6875
4
from SliceTest.point import Point from SliceTest.edge import Edge class Shape(object): MAX_X = 250 # USED FOR INTERSECTION ALGORITHM MAX_Y = 250 def __init__(self, data): self.points = data self.edges = [] self._gen_edges(self.points) def _gen_edges(self, lop): """ge...
08dedad167a35d0ddf353de0ee4e7cf6e2f3ca3c
ricardroberg/fullstack_bootcamp
/0 - DJANGO_COURSE_FILES/13-Python_Level_Two/part8.py
3,342
3.59375
4
import re patterns = ['term1', 'term2'] text = 'This is a string with term1, not not the other!' # for pattern in patterns: # print(f"I'm searching for {pattern}") # # if re.search(pattern, text): # print("MATCH!") # else: # print("NO MATCH!") match = re.search('term1', tex...
6aec09f3626d51fe389a5f6de34ea38ae8fa39e7
shuw/euler
/python/p23.py
2,126
3.90625
4
from math import * # Returns hash of prime factors + their power def findPrimeFactors(n, factors): if n == 1: return; secondLargestPrimeFactor = int(sqrt(n)) i = 2; while True: if i == n or i > secondLargestPrimeFactor: power = factors.get(n) if power == None: ...
862c729de4ac49f69f67baebdeba0e1c67b5b4b8
GuillaumeJouetp/Compression_de_texte
/huffman_VF.py
10,675
3.734375
4
# ALGRORITHME DE HUFFMAN : COMPRESSION DE DONNEES def TableDeFrequence (texte): """ Construction d'une table de fréquences @ Entrée: un texte @ type: string @ Sortie: un dictionnaire qui pour chaque caractère présent dans le texte lui associe sa fréquence @ type: dict """ table={} ...
80c0c78be87ef72de59b615edbc412e2fa61499e
UWPCE-PythonCert-ClassRepos/Self_Paced-Online
/students/AlyssaHong/Lesson10/mailroom_fp.py
6,156
4.03125
4
""" Author: Alyssa Hong Date: 1/12/2019 Update: Lesson10 Assignments > Mailroom, Object Oriented Mailroom """ #!/usr/bin/env python3 import os class Donor: def __init__(self, first_name, last_name, donations = None): self.first = first_name self.last = last_name self.donations = donation...
6147a3c4f0795100d24d465c6d0bff777ceb2138
pkc-3/Python_Q100
/Q1~Q50/Q5.py
203
3.640625
4
a = 10 b = 2 for i in range(1, 5, 2): a += i print(a+b) # i의 범위는 1~4까지 2씩 증가 i=1이고 그다음은 i=3 이고 끝 # 1일때 a= 11 b = 2 a+b = 13 # 3일때 a= 14 b = 2 a+b = 16
ae5e40fb4c0f91bc0e8bd684ee4b823e821b6ba6
AyaanShaikh1/Project-100-Class-Python
/biodata.py
322
3.828125
4
class Data : def __init__(self,name,age,hobby): self.name = name self.age = age self.hobby = hobby def greet(self) : print(f'Hello {self.name}') obj = Data(input('What is your name? : '),input('What is your age? : '),input('What is your hobby? : ')) obj.greet() ...
fd4865220d7f895e2ad88baabff2f38b8b2e5b3a
Prashantkankaria/learnpython_edx_Gtech
/GTx _CS1301xI/test_code_problem_7.py
804
3.5
4
current_hour = 5 current_minute = 32 current_section = "AM" due_hour = 6 due_minute = 0 due_section = "PM" #You may modify the lines of code above, but don't move them! #When you Submit your code, we'll change these lines to #assign different values to the variables. #Given the current time and deadline time represen...
c61ba444d1b99ed26e9b52936eaf0302b72691f3
djjohns/pysqlite3
/txt2csv.py
918
4.03125
4
#!/usr/bin/python #txt2csv.py written by David J. Johns II to aid in converting a tab #dilimited text file into a csv file for easier data manipulation #https://github.com/djjohns #import the csv library import csv #Prompts user for file name #if user presses enter, program will open specified txt file FileName = raw...
82c4d935534c2355bb5bd1391097a0684656e90d
Barabasha/pythone_barabah_hw
/task14.py
429
3.984375
4
def print_task(n) : print ('====================Task'+str(n)+'====================') return #===========================task14=========================== def is_even (number): if number % 2 == 0: return True else : return False print_task(14) number = int (input ("Input num...
935dc5f40e4e1025286125e13a8afa71f034d593
daniel-reich/ubiquitous-fiesta
/iuenzEsAejQ4ZPqzJ_13.py
127
3.703125
4
def mystery_func(num): s, mult = "", 1 while mult < num: mult *= 2 s += "2" return int(s[1:]+str(num-mult//2))
46dc7fe39f30aebb8d23c33f922e92e2edd5b129
cpr2mc/Programming101
/resources/example_lessons/unit_3/unit_3_lesson.py
4,328
4.4375
4
''' Programming 101 Unit 3 ''' # Datatype: boolean (bool) # True / False a = True b = False # print(a, type(a)) # True <class 'bool'> # print(b, type(b)) # False <class 'bool'> # in Python, booleans are capitalized # b = true # NameError: name 'true' is not defined # -----------------------------------------------...
89592b47de91b974e4deceb1eace4264f836ca84
WojciechBogobowicz/Unit_Test-Example
/bank.py
4,068
3.75
4
from bankaccount import BankAccount from random import randint, seed class Bank: def __init__(self, name): self.name = name self.accounts = {} self.account_num = 0 self.used_ibans = [] with open("iban.txt") as f: for line in f: line = line.strip(...
0507c0ae1a5e5cec82c8c973c0a5fbc6d1941c58
deepshringi/queensproblem
/Eightqueen.py
4,308
4.0625
4
#import random to generate random population import random #import sleep to slow down computation from time import sleep class EightQueens: #solution - one of the pre-defined soution to 8-Queen's problem solution = [3, 6, 2, 7, 1, 4, 0, 5] #computed_solution - this list will have the final computed so...
c89b47bbd248f5eaea15b37ca6f615225387ac4d
UConn-UPE/tutorials
/CSE2050/Unit_Testing/test_example_functions.py
1,321
3.765625
4
import unittest from example_functions import * class TestExampleFunctions(unittest.TestCase): def setUp(self): print('Start of a test method') def tearDown(self): print('End of a test method') @classmethod def setUpClass(cls): print('Start of a class') @classmethod d...
b95ffddc4accc6176ada2bd6ed98d30aa4e23a14
YuweiHuang/DSAA-Notes
/linklist/lc_19_delete_last_nnode_linklist.py
919
3.59375
4
# https://blog.csdn.net/qq_17550379/article/details/80717212 # Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def removeNthFromEnd(self, head, n): """ :type head: ListNode :...
4d2741408dbb38883178bd71f22ab50e88f757cd
kirthikartm/guvi
/natural.py
63
3.625
4
a=int(input("")) s=0 for i in range(1,a+1): s=s+i print(s)
2fe6fe78c213c50801bd38d957900a01dc9bd2e2
cmychina/Leetcode
/leetcode_回溯_子集.py
510
3.953125
4
""" 给定一组不含重复元素的整数数组 nums,返回该数组所有可能的子集(幂集)。 说明:解集不能包含重复的子集。 """ class Solution: def subsets(self, nums): res=[] n=len(nums) def backtrack(i,tmp): res.append(tmp) for j in range(i,n): backtrack(j+1,tmp+[nums[j]]) backtrack(0,[]) return r...
b2fc3b7602fdc97c345bb294c4b185f36acd2293
joao-felipe-santoro/data_sci_bikeshare
/chicago_bikeshare.py
10,551
4.03125
4
# coding: utf-8 # Here goes the imports import csv import matplotlib.pyplot as plt # Let's read the data as a list print("Reading the document...") with open("chicago.csv", "r") as file_read: reader = csv.reader(file_read) data_list = list(reader) print("Ok!") # Let's check how many rows do we have print("N...
b57eaffe6dfa4be2bf99770a3ba2b24baf056b00
YanceyZhangDL/Python_LearnDemo
/prac_5/prac_5_1.py
956
3.84375
4
#!/usr/bin/env python #coding:utf-8 #################################################### # Copyrignt (py) YanceyZ. All rights reserved. # # Author: YanceyZ # Mail: yanceyzhang2013@gmail.com # Description: #################################################### while True: try: summ = 0 iterr = 0 ...
2cf3fe5973e00ff63d730eb0905981600ce511d6
johnreyev/supercode-get-sheets-list
/main.py
1,154
3.515625
4
""" Import required libraries """ import json import requests URL = "https://sheets.googleapis.com/v4/spreadsheets/{spreadsheet_id}?&fields=sheets.properties&key={google_key}" def main(spreadsheet_id, google_key): """ Get spreadsheet list of sheets information. """ response = {} response["type"] = "erro...
9a068c074d546c64fc653505a12d855b84cacc45
J4TJR/RPC
/1.py
2,423
4.0625
4
import random import time #test for commit # Initialize Variables def isValidEntry(): invalid_entry = True while invalid_entry: user_choice = input('Rock? Paper? Scissors? ') if user_choice == 'Rock' or user_choice == 'Paper' or user_choice == 'Scissors': return user_cho...
75142b32ac7373d7256b0b5160aed46a6f257b18
rajui67/learnpython
/python_code_exaples/others/typename.py
1,030
3.84375
4
''' Function to return the typename of an object/instance ''' # from typing import Any # def typename(derive_the_typename_of_this_instance: Any,/) -> str: import typing def typename(derive_the_typename_of_this_instance: typing.Any,/) -> str: ''' Given a varaible of any type, returns the type name of the ...
b934d6599f01a28f1b3ddc3f149d3b6ab517ff4d
rehan-prass/tugas-pkl-pyhton
/kasir2.py
593
3.75
4
print("Source Code Kasir Dengan Python") x=str(input("Nama Barang : ")) y=int(input("Harga : ")) z=int(input("Jumlah Jual : ")) v=0 w=0 if (z in range (0,5)): v = 0 print("Tidak ada diskon") elif (z in range (5,11)): v = 5/100 print("Discount 5%") elif (z in range ( 11,21)): v = 10/100 ...
4baa9edde7c2de03c0bf63b04de1123779d566d4
blhwong/algos_py
/leet/reorder_list/main.py
678
3.640625
4
from data_structures.list_node import ListNode class Solution: def reorderList(self, head: ListNode) -> None: """ Do not return anything, modify head in-place instead. """ arr = [] if not head: return None curr = head while curr: ar...
2f06f8a4cef3b86f3bdfb86cf8b29bbc6aa2d9fb
amantyagi95/python-beginner-projects
/Hangman/hangman.py
2,357
3.984375
4
from random import choice from string import ascii_lowercase FILENAME = 'Hangman\\sowpods.txt' def get_rand_word(filename): with open(filename, 'r') as f: return choice([x.strip() for x in f]).lower() def print_game(wrong, word, letters): # Print wrong guesses print('\nWrong guess:', end=' ') ...
37a5a4ad1b5499d4286a9b1549d8247380838235
gurguration/python_course
/all.py
11,999
3.703125
4
# from abc import ABC, abstractmethod # class InvalidOperationError(Exception): # pass # class Stream(ABC): # def __init__(self): # self.opened = False # @abstractmethod # def read(self): # pass # def open(self): # if self.opened: # raise InvalidOperationErr...
5fa252ec038b246bff6615dcdfb99104de65a85e
Maxarre/CodingBat
/Python/Logic_1/alarm_clock.py
721
4.09375
4
# Given a day of the week encoded as 0=Sun, 1=Mon, 2=Tue, ...6=Sat, # and a boolean indicating if we are on vacation, # return a string of the form "7:00" indicating when the alarm # clock should ring. Weekdays, the alarm should be "7:00" and on # the weekend it should be "10:00". # Unless we are on vacation -- th...
253a681c677b34020eb48b07ad14426fdfe99ce1
rohitrs3/Python
/Sum of Natural Numbers.py
332
4.0625
4
#Program for Sum N natural numbers N=int(input("Enter the numbers : ")) Sum= N*(N+1)/2 print(Sum) ## n=eval(input("enter the number to add for natural number : ")) if(not instance(n,int)): print("Wrong Input") if(n>0): sum=(n*(n+1))/2 print("sum of natural numbers is ", sum) else: print("Error!!...
0e986cc7d5235e68d9a7f48c54422046e535dd60
Vampirskiy/helloworld
/venv/Scripts/Урок2/in_ex.py
383
3.734375
4
hero='superman' if hero.find('man') != -1: # Ищем слово мен 1 способ print('Есть!') if 'man' in hero: # Ищем слово мен 2 способ print('Есть!') goals = ['стать гуру языка питон', 'здоровье', 'накормить курицу'] if 'здоровье' in goals: print('все заебись!')
ed555bedb87042a81c11f1be06739a0b29eeb7d9
epenelope/python-playground
/heart.py
583
3.796875
4
import turtle turtle.bgcolor('black') turtle.pensize(2) def curve(): for i in range(200): turtle.right(1) turtle.forward(1) turtle.speed(2) turtle.color("red", "pink") turtle.begin_fill() turtle.left(140) turtle.forward(111.65) curve() turtle.left(120) curve() turtle.forward(111.65) turtle.end...
ee2b9e2d2be2754988911626649326f1a3389430
langtodu/learn
/study/class.py
1,182
3.953125
4
# -*- coding: utf-8 -*- ##类的构建方法介绍 #**************** 实例方法 ************** ## classmethod 修饰符对应的函数不需要实例化,不需要 self 参数,但第一个参数需要是表示自身类的 cls 参数,可以来调用类的属性,类的方法,实例化对象等。 ## classmethod和staticmethod都不能调用实例属性 class Test(object): def __init__(self, str="Hello istancemethod!"): self.init_str = str def add1(self, ...
c32b6844d21f7686bdbbe493159b1a447ef684ee
cvargas-xbrein/aws-glue-monorepo-style
/glue/shared/glue_shared_lib/src/glue_shared/str2obj.py
614
3.515625
4
import datetime import logging from typing import Tuple import dateutil.parser LOGGER = logging.getLogger(__name__) def str2bool(value): return value.lower() == "true" def comma_str_time_2_time_obj(comma_str: str) -> Tuple[datetime.datetime, ...]: """ Convert comma separated time strings into a list o...
7840462070b262c589723764b9314780f03b4a9a
nkrishnappa/100DaysOfCode
/Python/Day-#27/PythonArguments.py
872
4.4375
4
# Default Arguments def my_fn(a, b, c=5): pass my_fn(c=3, b=2, a=1) # Unlimited Arguments ''' # Problem def add(a, b): print(a + b) add(3,4) # 7 add(3, 4, 5) # TypeError: add() takes 2 positional arguments but 3 were given ''' # Solution def add(*args): """the add module will add any number of numbers ...
d82514659192f06b879e4ac5557ed766027da44a
Peggyliu613/mile_to_km_converter
/main.py
668
3.734375
4
from tkinter import * window = Tk() window.title("Mile to Kilogram Converter") window.minsize(200, 100) window.config(padx=20, pady=20) mile_inputted = Entry(width=5) mile_inputted.grid(column=1, row=0) mile_label = Label(text="Miles") mile_label.grid(column=2, row=0) convert_to = Label(text=0) convert_to.grid(col...
0fd6a34b52d092c238cfd65a8296c4bededd81b0
3desinc/YantraBot
/example_programs/simple_light_sensor.py
2,333
4.5625
5
#!/usr/bin/env python3 ## simple_light_sensor.py ## This is an example program designed for 3DES programs ## Writen by Martin Dickie ## this example program will just read a light sensor connected to pin 2 and print either 0 or 1, based on how bright the light is. import RPi.GPIO as G...
148c6d9d37a9fd79e06e4371a30c65a5e36066b2
jtquisenberry/PythonExamples
/Jobs/multiply_large_numbers.py
2,748
4.25
4
import unittest def multiply(num1, num2): len1 = len(num1) len2 = len(num2) # Simulate Multiplication Like this # 1234 # 121 # ---- # 1234 # 2468 # 1234 # # Notice that the product is moved one space to the left each time a digit # of the top number is multip...
0a4de4cf1a193012cc678daa7efa786d713bd22e
aetooc/Practice-Questions-Python
/Test1_part1.py
178
4.03125
4
# My Answer for Question 1 number= int(input('Enter a number:')) Range= int(input('Enter the Range:')) for j in range(1, Range+1): k=number*j print(number,'x',j,'=',k)
494c89ea33244ab5db3066ab7e0662edd34c27b9
IanCBrown/practice_questions
/two_stones.py
224
3.734375
4
def two_stones(state): if state % 2 == 0: return "Bob" else: return "Alice" def main(): start_state = int(input()) print(two_stones(start_state)) if __name__ == "__main__": main()
4fa9c01e77d27a0f21cfd8fc63d7ed31fdc1b56f
hoelzl/L3
/l3/core/dice.py
5,899
3.875
4
import random import re from abc import ABC, abstractmethod from typing import Sequence, Callable, Tuple, List class Die(ABC): @abstractmethod def roll(self) -> None: """" Roll the die and store the value. The rolled value can be accessed by the value property. """ pass...
b99d2d725d0da10ea4d0d02367e7322d743cf28a
Aasthaengg/IBMdataset
/Python_codes/p02909/s116131344.py
134
3.953125
4
s = input() if s == 'Sunny': result = 'Cloudy' elif s == 'Cloudy': result = 'Rainy' else: result = 'Sunny' print(result)
a09384307150c62f613150e3943eeac09388d61a
vighnesh153/ds-algo
/src/arrays/first-and-last-position-of-element-in-sorted-array.py
937
3.75
4
def find_left(arr: [int], target: int): position = float('inf') low = 0 high = len(arr) - 1 while low <= high: mid = (low + high) // 2 if target <= arr[mid]: if arr[mid] == target: position = min(position, mid) high = mid - 1 else: ...
58a2afa51ccad18da54428f0247cf07778debb1f
clturner/algorithms_linked-lists_data-structures
/0x0A-nqueens/0-nqueens.py
2,027
3.5
4
#!/usr/bin/python3 import sys global N board = [] queens = [] first_column = [] sys.setrecursionlimit(18500) if len(sys.argv) is 1: print("Usage: nqueens N") sys.exit(1) N = sys.argv[1] try: int(N) except: print("N must be a number") sys.exit(1) if int(N) < 4: print("N must be at least 4"...
31a6d64dea403d6a7343eb9652577a665f7fd8ca
masyuk/LearnPython
/11_dictionary_1.py
299
3.6875
4
# (----Item----) # (key) (value) enemy = { 'loc_x': 70, 'loc_y': 50, 'color': 'green', 'health': 100, 'name': 'Mudilo' } print(enemy) print(enemy['name']) enemy['rank'] = 'Noob' print(enemy) del enemy['rank'] print(enemy) print('--------------') enemy['loc_x'] += 40
972362f6ecdfacdfc1559075ee82a2f3ed8500ee
JulieZhang0102/MIS3640
/session15/exercise2.py
1,853
4.15625
4
import math class Point: ''' a point with x, y attributes ''' class Circle: ''' Circle with attributes center and radius ''' center = Point() circle = Circle() circle.center.x = 150 circle.center.y = 100 circle.radius = 75 class Rectangle: """Represents a rectangle. attributes:...
670a9bb45e6ce666b8296df4da30c2b14e883641
pflun/learningAlgorithms
/isSubtree.py
1,357
3.9375
4
# Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def isSubtree(self, s, t): res = [] queue = [s] while queue: curr = queue.pop(0) i...
cfb728e4c1ed16e2dc94c3c3544878021e3b6193
arifanf/Python-AllSubjects
/PDP 5/pdp5_7.py
208
3.59375
4
def main(): sumData=0 n=int(input("input bil : ")) while n!= 9999: print(n) sumData+=n n=int(input("Input bil : ")) print("Jumlahan : {}".format(sumData)) if __name__ == '__main__': main()
a2635d0abdf94fa30448166a77a857a520724023
RakeshSuvvari/Joy-of-computing-using-Python
/PointsDistributionMethod.py
2,013
3.609375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed May 19 20:22:33 2021 @author: rakesh """ import networkx as nx import random import matplotlib.pyplot as plt def add_edges(): nodes=list(G.nodes()) for s in nodes: for t in nodes: if s!=t: r=random.random() ...
779e84f66b5b7952863a324ad23de399f27231fa
yanliangchen/ware_house
/技术收藏/learingnote/基础代码/Python练习题 010:分解质因数.py
1,877
3.765625
4
''' 将一个正整数分解质因数。例如:输入90,打印出90=2*3*3*5。 一开始我简单地以为,只要将输入的整数拿个数字列表挨个除一遍,能整除的就可以收为质因数。 但事实上是行不通的,因为这样会连同 4、6、9 这样的数字也收进去,而当质因数有重复时(比如12=2*2*3),就会被遗漏掉。 基于以上的考虑,转换思路:还是将输入的整数(n)拿个数字列表挨个除,但要多除几遍,而且每遍除的时候,一旦出现质因数, 立即把这个数字收了,把输入的数字除以这个质因数并重新赋值给n,然后停止这个循环,进入下一个循环。如此便能解决上述的问题。 最后还有一点需要注意的:如果这个数字已被任意质因数整除过,那么走完所有循环之后,最后的 n 也必然是其中的...
94c900cc7ad12ddf238a58e591f0057d975f8df2
twonds/healthmonger
/healthmonger/memory.py
2,480
3.546875
4
"""In memory data store module """ from collections import defaultdict import config class Store: """Simple in-memory data store. """ def __init__(self): self.data_loaded = False self.time_loaded = None self.data = defaultdict(dict) for table, schema in config.TABLE_SCHEM...
ff6252ff0903b8bdfe57d8ebbe27f58cd1877a4f
mshasan/Python-Computing
/Random number generations/generate normal by Box-muller.py
1,902
3.546875
4
import random import math import numpy as np import pylab as P #============================================================================================================ # 2(d) ------------------------------------------------------------------------------------------------------ # generating Normal(10,25) random sa...
f76b180064b451c4075bc87eee7caf3d66786d9e
thenu97/codewars
/string-split.py
325
3.703125
4
# split string in pair and if odd, pair it with '_' def soluton(s): if len(s) % 2 == 0: l = [s[i:i+2] for i in range(0, len(s), 2)] if len(s) % 2 == 1: l = [s[i:i+2] for i in range(0, len(s) - 1, 2)] l2 = s[-1] + "_" print(l2) #l3 = str(l2) l.append(l2) retu...
2cea947273ac03e10181188665955e52521a5d5c
shan-mathi/InterviewBit
/largest_number_formed.py
331
3.5
4
def arrange(A): li = list(map(str,A)) li.sort() l = len(A) for i in range(l): for j in range(i,l): first = li[i]+li[j] second = li[j]+li[i] if second>first: li[j],li[i]= li[i], li[j] ans = "".join(li) return int(ans) print(arrange([0,...
ec28302363c51db69fadc004239e2d1ac9bf5704
popcorncolonel/Sim
/actuators.py
5,759
3.609375
4
""" TODO: left, right, up, down actuators. """ import sim_tools import random import time class Actuator: """ Only actuates on all organisms. "targets" can be False. """ def __init__(self, sim, org): from sim import Simulation from organism import Organism assert isinstance(sim, Sim...
26cd1ffcb81295cfb5e1ce3884bd37161ba57195
abhay-jindal/Coding-Problems
/Array/Find K Closest Elements.py
1,933
4.15625
4
""" Find K Closest Elements https://leetcode.com/problems/find-k-closest-elements/ Given a sorted integer array arr, two integers k and x, return the k closest integers to x in the array. The result should also be sorted in ascending order. An integer a is closer to x than an integer b if: |a - x| < |b - x|, ...
aa3197fbbbe85ab50cbd541ea43f68ca296a6474
ValentynTroian/Python-Homework
/word_guessing_game.py
4,320
4.21875
4
''' Word guessing game. The game is over if user successfully guessed the word. User can exit the game, reload the word and give up. ''' from sys import exit from random import choice from os import path # Path to file which contains words FILE_PATH = path.join('C:', 'Users', 'Valentyn_Troian', 'Desktop',...
16a77feedf908077f3f74c74a00aa95765f46124
tombstoneghost/Python_Advance
/RandomNumbers.py
1,440
4.25
4
# Working with random numbers import random import secrets import numpy as np # Getting a Random Number a = random.random() print(a) # Specifying a Range a = random.uniform(1, 10) print(a) # Getting a Random Integer a = random.randint(1, 10) # This includes the upperbound where randrange() does not include the uppe...
b3f9556e68beb5f48135ca2ebb211ccdb7e4d280
sSeongJae91/python
/list.py
320
3.84375
4
x = [4,2,3,1] y = ["hello", "world!"] z = ["hello", 1, 2, 3] # print(x + y) # print(x[0]) #len num_elements = len(x) # print(num_elements) #sorted sort = sorted(x) # print(sort) #sum z = sum(x) # print(z) #list + loop # for n in x: # print(n) #list -> index print(y.index("hello")) #find print("hello" in y)
1347c374d065223dfd59abe3cf7b325172acd055
inauski/SistGestEmp
/Tareas/Act08-Listas/ejer06/ejer06.py
327
3.796875
4
from ejer02 import ListaMinusMayus lista = ["Beñat", "Xabi", "Xabi", "María", "Alexander", "Carlos", "Juan", "Imanol", "Pedro", "Uxue", "Javier", "Iker", "Carlos", "Xabi", "Alejandra", "Carolina", "Iñaki", "Asier", "Maria"] l = ListaMinusMayus(lista) l.modificaciones(input("Nombre a buscar: ")) print(list...
8750601391095dc42ba27efea9569bb27ec993f8
lovehhf/LeetCode
/415_字符串相加.py
1,125
3.75
4
# -*- coding:utf-8 -*- __author__ = 'huanghf' """ 给定两个字符串形式的非负整数 num1 和num2 ,计算它们的和。 注意: num1 和num2 的长度都小于 5100. num1 和num2 都只包含数字 0-9. num1 和num2 都不包含任何前导零。 你不能使用任何內建 BigInteger 库, 也不能直接将输入的字符串转换为整数形式。 """ class Solution(object): def addStrings(self, num1, num2): """ 和第二题类似, 取长度大的用于循环能省很多麻烦 ...
4bcb118d7678c090212c7771cbe810edba896317
yzl232/code_training
/mianJing111111/geeksforgeeks/bit/Count number of bits to be flipped to convert A to B.py
684
4.125
4
# encoding=utf-8 ''' Count number of bits to be flipped to convert A to B ''' class Solution: def cntBits(self, n): cnt = 0 while n: cnt+=n&1 n>>=1 return cnt def countFlip(self, a, b): return self.cntBits(a^b) ''' # Turn off the rightmost se...
08ebc24ff841a21244ff4970f7fc7be9d3f042a6
KiselevAleksey/algorithmic_problems
/Square_of_2_rectangles.py
1,027
4.0625
4
""" Площадь прямоугольников. Вам даны координаты противоположных углов двух прямоугольников со сторонами, параллельными осям координат. Необходимо определить площадь пересечения этих прямоугольников. Формат вывода Выведите одно целое число, равное площади пересечения двух прямоугольников. Пример 1 Ввод 1 1 2 2 1...
aec9b7c2357e6e98db30481d19e6a9a453406695
sakateka/atb
/src/course1/week4_divide_and_conquer/_4_number_of_inversions/inversions.py
674
3.59375
4
# Uses python3 import sys def merge(left, right, inv=0): ret = [] while left and right: if left[0] > right[0]: inv += len(left) ret.append(right.pop(0)) else: ret.append(left.pop(0)) ret.extend(left) ret.extend(right) return ret, inv def inv...
af8ddae5bea25e450d3f41f7ac99cdd4b9221ff0
nkukarl/lintcode
/Q110 Minimum Path Sum.py
1,113
3.625
4
''' Thoughts: Dynamic programming Initialise dp to be a two-dimensional array whose size is the same as that of grid, let dp[0][0] = grid[0][0] For the first row and first column of dp, let dp[i][0] = dp[i - 1][0] + grid[i][0] and dp[0][j] = dp[0][j - 1] + grid[0][j] For i ranging from 1 to m and for j ranging from...
dbde982f6a9f252795810681b11e1317257846af
KobrinIsTheBestCityInTheWorld/Python_labs
/task7.py
1,028
3.921875
4
import math import sys import argparse def leonardo(n): """Вычесляет число Леонардо Args: n -- номер числа, которое нужно вычеслить Return: n-ое число Леонардо """ if not isinstance(n, int): raise NameError('n must be int') if n < 0: raise ValueError('n must be positive') if n == 0 or n == 1: return 1...
72077975d6aa0c73548df339c47d941a015400d1
silas-inegbe/AirBnB_clone-1
/tests/test_models/test_city.py
659
3.546875
4
#!/usr/bin/python3 """Test suite for the City class of the models.city module""" import unittest from models.base_model import BaseModel from models.city import City class TestCity(unittest.TestCase): """Test cases for the City class""" def setUp(self): self.city = City() self.attr_list = ["...
b84ac97473ab23460f75b388553849095b4aad4d
nuSapb/basic-python
/Day2/error_handling/error_handling.py
210
3.671875
4
import datetime import random day = random.choice(['Eleventh', 11]) try: date = 'September ' + day except TypeError: date = datetime.date(2018, 9, day) else: day += '2018' finally: print(date)
58d01ac9c8c9e03448dd6b14acda49a9f00e1070
AdamRajoBenson/beginnerSET9
/divmod.py
98
3.515625
4
z,q,y=input().split() x=int(z) w=str(q) e=int(y) if(q=='/'): print(w//e) else: print(w%e)
8fc8ded2f598c11fb225012c563408a52ed71040
edu-athensoft/stem1401python_student
/py210110d_python3a/day09_210307/homework/stem1403a_hw_8_0228_zeyueli.py
614
4.1875
4
""" [Homework] 2021-02-28 Show and Hide a label in a window Due date: By the end of next Sat. """ from tkinter import * root = Tk() root.title("Python GUI - Homework") root.geometry("640x480+0+0") label1 = Label(root, text='Label 1', font=('Times', 25), bg="orange", fg='blue') label2 = Label(root, text='Label 2', fo...
e1af949fb26d93bebc0d0206c709a1e77c1248ab
elinanovo/chewbacca
/exam/task3.py
502
3.734375
4
print("Введите слово") a=input() while a!='': with open("Ozhegov2.txt", encoding="utf-8") as f: for line in f: slovo=line.split('|') if a== slovo[0]: print(slovo[0],'—',slovo[3],'—',slovo[1]) break a=input() #if a!==slo...