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
4c5afa810c04515bf7659fe1f3c50ef29776e132
songdanlee/python_code_basic
/day09/射击.py
4,865
3.546875
4
import time import sys import random # 创建枪对应的类型和弹夹,子弹伤害的关系 DICT_GUN = { "AWM": {"clip": 100, "bullet": 10}, "SRL": {"clip": 150, "bullet": 120}, "K98": {"clip": 80, "bullet": 200}, "Win94": {"clip": 30, "bullet": 50}, } # 封装子弹类 属性:伤害值 class Bullet(): def __init__(self, damage): self.damag...
bbb0397bbbe48de1d8f5bd9d0d2e62a2e29f151f
Kieran-Badesha/Data21Notes
/JSON_files/working_with_json.py
1,016
3.515625
4
import json # pet_data = { # "name": "Bob", # "food": "Carrots" # } # # # with open("new_json_file.json", "w") as jsonfile: # json.dump(pet_data, jsonfile) # # # with open("new_json_file.json") as jsonfile: # pet = json.load(jsonfile) # print(type(pet)) # print(pet) ...
c25839510812e2276a75af10167bfeb55947edd2
rishavhack/Data-Structure-in-Python
/Exception Handling/Exception Handling.py
666
3.703125
4
# IndexError, ImportError, IOError, ZeroDivisionError, TypeError. # Python program to handle simple runtime error a = [1, 2, 3] try: print "Second element = %d"%(a[1]) #Throw Error print "fourth element =%d" %(a[3]) except IndexError: print "An error occured" print "\n" try: a = 3 if a<4: b = a/(a-3) prin...
69aab17feaf121144d9461af42c3a1339cbf6a2e
marciopocebon/abstract-data-types
/python/src/stack/stack_linked_list.py
900
3.796875
4
from stack_interface import StackInterface from src.list.node import Node class StackLinkedList(StackInterface): """ stack implementation using a linked list """ def __init__(self): """ create a new empty stack """ self.head = None self.length = 0 def isEmpty(self): """ verify is the stack is e...
deda1bf39cf777a5df09e6dda7de90e9684ee00a
uzairamer/hello-world
/re/WordAnalysisKit.py
2,150
4.21875
4
import re from collections import defaultdict class WordAnalysis(object): """WordAnalysis consists of static methods that helps in word analysis like checking frequency of each word in a file etc """ def __pretty_print_word_frequency(input_dict): """Private Method: Prints the word and its cou...
fcf8d43024c0e0e223531ff8b9a890e97d84b315
iXploitID/multi
/5.py
218
3.59375
4
def pangkat(x,y): if y == 0: return 1 else: return x * pangkat(x,y-1) x = int(input("Masukan Nilai X : ")) y = int(input("Masukan Nilai Y : ")) print("%d dipangkatkan %d = %d" % (x,y,pangkat(x,y)))
b24b31fa39630f6da95352c5f3e9b788d9a8fd19
tairbr/homework_tms
/homework_9_2.py
410
4
4
# Создать lambda функцию, которая принимает на вход неопределенное количество именных аргументов и выводит словарь с # ключами удвоенной длины. {‘abc’: 5} -> {‘abcabc’: 5} func_1 = lambda **kwargs: {key*2: value for key, value in kwargs.items()} print(func_1(abc=5, chi=8, k=43, rik=12))
29d3487f279d7944b81a56ad719dace90824a0b2
tylergan/veryfirstproject
/Assingment /game_parser.py
3,171
3.84375
4
''' Author: Tyler Gan Date: 22 May 2020 Purpose: This file contains functions that will read my board configuration, strip it, and then output the file as a matrix of objects. ''' from cells import ( Start, End, Air, Wall, Fire, Water, Teleport ) cell_elements = { 'X': Start, 'Y': ...
54f56f3c16dc815eb0a5f06cae68f5780bf4e1ec
wise200/MouseMaze
/main.py
497
3.765625
4
from classes import Maze from random import choice def dfs(maze): mouse = maze.mouse visited = set() stack = [mouse.node] visited.add(mouse.node) count = 0 while len(stack) > 0: cell = stack.pop() mouse.moveTo(cell) if cell.hasCheese: count += 1 mouse.eatCheese() nbs = [nb for nb in cell.neighbors ...
0f83a439536fd3cd9c6531c2ef2ed6166617e925
xiaotdl/NLP
/test.py
246
3.515625
4
N = 5 T = 3 viterbi = [[0 for n in range(T)] for n in range(N+2)] print viterbi for s in range(1,5): print s l = [1,2,3,4,5,6,7,8] print l[::-1] print l.remove(8) print range(N) a = 1.6666666666666666 b = 3.444444444444444 print a*b
b9f7d49add9d9af4021d2e90ba44e7ecad7b5e6a
amanptl/LeetCode
/Easy/Sqrt(x).py
486
3.625
4
def mySqrt(self, x: int) -> int: if x == 0 or x == 1: return x if x == 2: return 1 lo = 0 hi = x - 1 while lo <= hi: mid = (lo+hi)//2 curr = mid * mid if curr == x: return mid ...
0da04b7e64ae14b61c1988cf54fadddb77e281e1
possibleit/LintCode-Algorithm-question
/smallestDifference.py
3,026
3.5625
4
#usr/bin/env python # -*- coding:utf-8 -*- import sys #''' # 二分法求解,但是时间会超。 #''' # def smallestDifference(A, B): # sys.setrecursionlimit(1000000) # tem = sys.maxsize # listA = sorted(A) # listB = sorted(B) # i = len(listA) # j = len(listB) # if i < 2 and j < 2: # return abs(listB[0...
9b9ebeaa45a1e966c3bd1b3d3162e107d3af8f7a
hno3kyoz/Bofo
/input.py
1,124
3.515625
4
# -*- coding: cp936 -*- from tkinter import * root = Tk() root.title("ѯ") root.geometry('300x300') # x * l1 = Label(root, text="˻") l1.pack() # sideԸֵΪLEFT RTGHT TOP BOTTOM xls_text = StringVar() xls = Entry(root, textvariable=xls_text) xls_text.set(" ") xls.pack() l2 = Label(root, text="E-mail") l2.pack() # si...
c8789376e8a6353c1659a34438ae7cad3060af62
chinuteja/100days-of-Code
/Sum of Pairs/solution.py
742
4.03125
4
""" Given an array of integers, and a number ‘sum’, find the number of pairs of integers in the array whose sum is equal to ‘sum’. Input : arr[] = {1, 5, 7, -1}, sum = 6 Output : 2 Pairs with sum 6 are (1, 5) and (7, -1) """ def function(array,sum_): dic = {} for i in array: if i not in dic: dic[i...
2b87a199759fa1a8cc46d15852752f17c5293c96
Knork3/practicepython.org
/practicepython.org/13_fibunacci.py
399
4.03125
4
def fibunacci(i): fib = [1, 1] for element in range(0,i): fib.append(fib[element] + fib[element+1]) return fib fib = [] while True: x = int(input("How many Fibonacci-Numbers to calc? (0 = quit): ")) if x == 0: break else: for element in fibunacci(x-2): if el...
658ae466c1fec64e4be0f02697bf19b9f67e7f92
medishettyabhishek/Abhishek
/Abhishek/tiknter/Frames.py
718
4.3125
4
from tkinter import * # we are importing the tkinter and all other modules here root = Tk() # We are creating the Tk class and assigning that to the root object Frame1 = Frame(root) # This is adding of the frame to the root object Frame1.pack() # this is packing the frame to the Main view Frame2 = Frame(root) Fr...
b2902c2a3a99e9db0882ddaca756e48d70622b6e
louispeters/schoolwork
/drivetest.py
178
3.96875
4
age = int(input("enter your age")) test =(input("have you passed your test")) if age>16 and test=="yes": print("you can drive") else: print("you cant drive")
124aa46d7bc7c9708b6b1c3b67ff148e1fa77658
Riwaly/DWARF-Tensorflow
/external_packages/correlation3D/ops.py
4,302
3.515625
4
''' Correlation 3D in TensorFlow Given a tensor BxHxWxC, Correlation 2D would get back a tensor with shapes BxHxWxD^2, where D is 2d+1 with d=max_displacement. Correlation3D requires to call Correlation2D N times, with N equals to 2*max_depth_displacement+1 All the correlation2D results are concatenated along channel...
d96f513036b3334c9d298c2dc03ff103e5f6ebbd
phanisai22/HackerRank
/Contests/Women Technologists Codesprint/Signal Classification.py
712
3.546875
4
#!/bin/python3 import math import os import random import re import sys # # Complete the 'classifySignals' function below. # # The function is expected to return an INTEGER_ARRAY. # The function accepts following parameters: # 1. INTEGER_ARRAY freq_standard # 2. INTEGER_ARRAY freq_signals # def classify_signals(f...
62a6702431746e15d85a26c02d9e4c505b61ff03
smbenfield/coursera
/course3/chxnotes.py
789
3.9375
4
# Methods = functions that are part of a dictionary # Construct = create empty instance of object breaker = '----------' movies = list() movie1 = dict() movie1['Director'] = 'James Cameron' movie1['Title'] = 'Avatar' movie1['Release Date'] = '18 December 2009' movie1['Running Time'] = '162 Minutes' movie1['Rating'] =...
689f17dfd1427505a7d7febf05dc0de91374a0a0
meetashok/projecteuler
/90-100/problem-91.py
735
3.640625
4
## Problem 91 ## Right triangles with integer coordinates import itertools def right_triangle(coor1, coor2): x1, y1 = coor1 x2, y2 = coor2 a2 = x1**2 + y1**2 b2 = x2**2 + y2**2 c2 = (x2 - x1)**2 + (y2 - y1)**2 return (a2 + b2 == c2) or (b2 + c2 == a2) or (c2 + a2 == b2) def main(): ...
ef535fd5dcf67c81b4029482eba62575c4269eff
CVHS-TYM/Marpaung_Story
/Learning/Warmups/popquiz.py
495
3.703125
4
#1 #2 import random #for a in range(500): # print(random.randint(0,100)) #3 #c = "" #for i in range(100): # a = random.randint(0,100) # if a%2 == 0: # c = "even" # elif a%2 == 1: # c = "odd" # print(str(a)+" is "+c) #4 #accidently pushed lol evens = 0 l_evens = "Evens: " for i in ra...
7cc0e7a73ccf8849ef466c10445b1e2d8c8b4088
dylan-slack/TalkToModel
/explain/actions/what_if.py
2,958
4.25
4
"""The what if operation. This operation updates the data according to some what commands. """ from explain.actions.utils import convert_categorical_bools def is_numeric(feature_name, temp_dataset): return feature_name in temp_dataset['numeric'] def is_categorical(feature_name, temp_dataset): return featur...
ad107f17d0fbb57dc098987b5f8a564cbb9abd47
AlanaRosen/my-python-programs
/Tip Calculator.py
996
4
4
def calculate(check,tip,name): total_check = (check * (tip/100) + check) total_check = round (total_check, 2) print ("\n" + str(name) + ", if you would like to tip ", str(tip) + "%, then your total will be $" + str(total_check) + ".") def others(): while start == "yes": name = input("\nWhat...
bcf7adf4cd80ef503bc18c792d4a489f0f751855
rusalinastaneva/Python-Advanced
/01. Lists as Stacks and Queues/05. Truck Tour.py
259
3.5
4
n = int(input()) start_idx = 0 fuel = 0 for i in range(n): petrol, distance = [int(x) for x in input().split()] fuel += petrol if fuel >= distance: fuel -= distance else: start_idx = i + 1 fuel = 0 print(start_idx)
4474b554f849104f35c03a822a1b23918ea67d15
Exdenta/Algorithms
/Graphs/Shortest Path/dijkstra.py
1,581
4.09375
4
#!/usr/bin/env python3 import sys import numpy as np def Dijkstra(nodes, edges, source): """Dijkstra shortest path algorithm Args: nodes (:obj:`list` of :obj:`str`): names of all nodes. edges (:obj:`list` of :obj:`list`): graph adjacency matrix. source (:obj:`int`): source node inde...
fbccee51b92c1574a05b37c4eff79e69ce1c8441
flavianogjc/uri-online-judge-python
/iniciante/1008/1008.py
180
3.546875
4
if __name__ == '__main__': n = input() horas = input() valorHora = float(raw_input()) print("NUMBER = %d" % n) print("SALARY = U$ %.2f" % (horas * valorHora))
4e53df8b6f36a228ba6e462b93ab536ea16880ce
tjddbs2065/ToyProject
/Trader Tool/test.py
2,447
3.96875
4
''' tick: 몇분봉 데이터인지 avg_moving: 몇일선 데이터를 원하는지 list: 데이터 ''' def get_moving_avg_line(avg_moving, list): tmp_list = [] for position, data in enumerate(list): if position < (avg_moving-1): tmp_list.append(0) else: total = 0 for idx in range(avg_moving): ...
a0fadcdd909bae0f2d915983c5765bdb8e860916
CalBearsGrad/Big-RATINGS-Project
/templates/mike.py
126
3.84375
4
def add_num(x, y): """Adds x and y together""" return x + y x = 9 y = 8 something = add_num(x, y) print something
8c6d3db3dde0e6fe4d7717795015bf9bdc7c3b4e
kevinwei30/CodingProblems
/nQueens.py
579
3.609375
4
n = int(input('Queens N : ')) stack = [] ans_count = 0 def check(col, row): global stack global ans_count # print(stack, col, row) for tmp_col in range(len(stack)): tmp_row = stack[tmp_col] if row == tmp_row: return elif abs(row - tmp_row) == (col - tmp_col): return if col == n - 1: ans_count += 1 ...
0e2186fa4bf83a91c6aeeffdee1cf7bcfbf34076
Glengend/Amazon-test
/amazon.py
2,337
3.90625
4
print('amazon task') from math import * print('This will give 3 different outcomes from predetermined variables ') out_file = open ( 'outputt.txt' , 'w' ) in_file = open("inputt.txt","r") # Find the minimum text = in_file.readline() num_list= text[4:] num_array=num_list[:-1].split(',') min_num=num_ar...
128603f61e6f04cc2c1c8348e194997803c9107f
mattrasband/advent_of_code_2020
/01/day01.py
468
3.546875
4
#!/usr/bin/env python3 import itertools import math def solve(lines, count=2, match=2020): for combo in itertools.combinations(lines, r=count): if sum(combo) == match: return math.prod(combo) print("part1 (test):", solve([1721, 979, 366, 299, 675, 1456])) with open("./input.txt") as f: p...
1e1c35a482bfdc1236b6bbc35bd46e09f5664a00
LiA-zzz/sudoku
/board.py
1,459
3.578125
4
import os, random import solver class board: def __init__(self): self.board = [] #store the orignal board for the reset button of the gui. (resets state back to original board) prefix = os.getcwd() + "\\boards\\" openFile = open(prefix+random.choice(os.listdir("boards")),'r') for li...
620e5773c45e0c617987a0cf4c583f063febbf41
jkbockstael/projecteuler
/euler007-proc.py
631
3.5
4
#!/usr/bin/env python3 # Problem 7: 10001st prime # https://projecteuler.net/problem=7 import sys def is_prime(primes, number): for prime in primes: if number % prime == 0: return False if prime ** 2 > number: break return True def euler007(count): primes = [2] ...
45c0504ef71291bf90225f6063f44862cc747d3b
genken1/python-practice
/extra01/part1/task2.py
379
4.09375
4
import this import antigravity print((True * 2 + False) * -True) print(0.6 + 0.3 == 0.9) # Выражение равно 0.89999. Такова особенность представления чисел в формате float (некоторые числа # нельзя представить в формате с плавающей точкой с основанием 2)
470c2ba3f46ba002cc7574c2fe8201c9925c30ba
anhnguyendepocen/EE-Complexity17
/sol_lab_INTRO/Fibunacci_Andreas.py
559
3.953125
4
# -*- coding: utf-8 -*- """ Created on Sat Aug 5 11:47:27 2017 @author: Andreas Lichtenberger """ # solution new: def fib_number (n): """ Fibunacci function """ if n >=3: x_n2 = 1 x_n1 = 1 i = 3 while i <= n: x_n = x_n2 + x_n1 ...
fc4a8d9178e17eccbea2d57d00bc99aadbf47626
LiliGuimaraes/100-days-of-code
/CURSO-EM-VIDEO-PYTHON3/REPETICOES/WHILE/guanabara_exerc_60.py
399
4.125
4
from math import factorial print("*" * 30) print("-- JOGO DO FATORIAL --") print("*" * 30) number = int(input("\nDigite um número que queira saber o seu fatorial:\n")) # f = factorial(number) # print("O valor de {}! é: {}".format(number, f)) c = number f = 1 while c > 0: print("{}".format(c), end='') print(' ...
f5b61e9688d1a60ef20c63e5d6076ce9050fe522
JacobHayes/Pythagorean-Theorem
/Pythagorean Theorem.py
1,984
4.375
4
# Jacob Robert Hayes # Pythagorean Theorem # C^2 = B^2 + A^2 import math print "This program if for calculating the Pythagorean Theorem." print "If the program crashes, an invalid answer was entered, please restart." Solve_For = raw_input("\nWhich variable are you solving for; A, B, or C? ") while not Solv...
c7327ff76d6d2d866348002a0145cf5ef2d75bbd
fatimantifi/ALGO-DES-K-VOISINS
/Algo-k-plus-proches-voisins-avec-interface-graphique-master/KNN.py
7,651
3.859375
4
""" Presentation Du Projet : Simulation de réfrigérateur a l'aide d'un algorithme style 'k plus proches voisins'// Cette algo a pour but de comparer les réfrigérateurs d'une population par rapport a la votre, votre frigo etant la liste nommé: témoin[]// Pour afficher les réfrigérateurs qui sont comparés au votre press...
baa7aa999a37fd0a522a7515bf05f9af73365f98
kailunfan/lcode
/226.翻转二叉树.py
1,666
3.84375
4
# # @lc app=leetcode.cn id=226 lang=python # # [226] 翻转二叉树 # # https://leetcode-cn.com/problems/invert-binary-tree/description/ # # algorithms # Easy (74.79%) # Likes: 443 # Dislikes: 0 # Total Accepted: 80.1K # Total Submissions: 106.5K # Testcase Example: '[4,2,7,1,3,6,9]' # # 翻转一棵二叉树。 # # 示例: # # 输入: # # ⁠ ...
b8c304ad36de45db8c4ac03f587989726037b218
Akhil-64/python
/23 prog.py
424
3.671875
4
print("enter no") a=int(input()) num=a gh=len(str(a)) b=0 c=0 sum1=0 count=0 '''while(a>0): b=int(a%10) count+=1 a=int(a/10) a=int(input())''' while(num>0): c=int(num%10) # print("rem",c) sum1=sum1+(c**gh) #print("sum",sum1) num=int(num/10) # print("A",a) if(sum1...
c1198eff34a65fb701c825b68825e61f922c9964
cabustillo13/Mallku_Hackathon_2021
/Prediccion/main.py
1,180
3.65625
4
from sklearn.neighbors import KNeighborsClassifier import pandas as pd import matplotlib.pyplot as plt print("######################\n## STOP THE FIRE 4+ ##\n######################\n") """Cargar información""" df = pd.read_csv("Dataset_Excel2.csv", index_col=0) """Armar el dataset -> Variables""" X = [] y...
05f6c76af955c0421199e665bbc710e2eefb3558
HourGlss/Chess
/pieces/rook.py
2,134
3.578125
4
from pieces.piece import Piece class Rook(Piece): def __init__(self, color): super().__init__(color) self.symbol = "R" def is_valid_move(self:Piece, board, startx, starty, endx, endy, evaluate_only=True): tile_is_free = board.is_tile_free(endx,endy) opponents_piece_is_occupyin...
9bf015fced42b47258e162a8b14923e16eaff4d2
wookiekim/CodingPractice
/leetcode/maximum-69-number.py
319
3.546875
4
# Python 3 # https://leetcode.com/problems/maximum-69-number class Solution: def maximum69Number (self, num: int) -> int: numlist = list(str(num)) for i, n in enumerate(numlist): if n == '6': numlist[i] = '9' break return int(''.join(numlist))
346833c07b08f8ca097b51e917a167520f9c7247
13627058973/project
/hello/python 6 循环语句.py
1,845
3.71875
4
#!/usr/bin/env python # -*- coding:utf-8 -*- ''' # while循环 计算1到100的总和 n = 100 sum = 0 counter = 1 while counter <= n: sum = sum + counter counter += 1 print("1 到 %d 之和为: %d" % (n, sum)) #无限循环 var=1 while var ==1: #表达式永远为true num=int(input("你最帅:")) print("你输入的数字是:",num) print("good bye!") # 一直打印 按C...
5532efc53cb6a79416f7636bc35a1a1b7e37a018
garvitsaxena06/Python-learning
/3.py
72
3.671875
4
#convert upper case string = 'This is my string' print(string.upper())
642258b5d5a0ce6f2fce345ee01269775e28aeec
mattjtodd/FDApy
/FDApy/representation/basis.py
12,649
3.875
4
#!/usr/bin/env python # -*-coding:utf8 -* """Basis functions. This module is used to define a Basis class and diverse classes derived from it. These are used to define basis of functions as DenseFunctionalData object. """ import numpy as np import scipy from patsy import bs from .functional_data import DenseFunctio...
09df664d70b6d70591f2e04eb8c0a71c96512725
shuowenwei/LeetCodePython
/Medium/LC2115.py
1,319
3.703125
4
# -*- coding: utf-8 -*- """ @author: Wei, Shuowen https://leetcode.com/problems/find-all-possible-recipes-from-given-supplies/ LC797, LC207, LC210, LC2115 """ class Solution(object): def findAllRecipes(self, recipes, ingredients, supplies): """ :type recipes: List[str] :type ingredients: L...
d3874254a614ad2e6c4bb112f9ed8ae2912d1a55
salma-shaik/python-projects
/ps_511_pf/GrowingLists.py
161
3.96875
4
list1 = [2,12,4] print(list1) list1 += [34,25,1] print(list1) list2 =[5,35,56] list3 = list1 + list2 print(list3) list1.extend([43, 7, 2]) print(list1)
b6f81160353e84ee924636680d11a645371e29c7
sbyeol3/Algorithm-Study
/LeetCode/Q1-Q500/Q2.py
1,063
3.734375
4
# Definition for singly-linked list. class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: head = ListNode() result = head carry = 0 while (l1 or l2 or...
ab693577f530653ec10e13062e271813171dc01a
ElAwbery/Python-Practice
/Lists/w3_lists1-10.py
4,348
4.21875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Aug 5 14:34:39 2018 @author: ElAwbery """ ''' Problems 1 - 10 from w3resource, lists: https://www.w3resource.com/python-exercises/list/ ''' ''' 1. Write a Python program to sum all the items in a list. ''' def items_sum(list): """ Adds the n...
1ba366f4e585f3d0c9705fb05afd232e18c1c675
snaplucas/python_api
/app.py
1,068
3.625
4
from flask import Flask, jsonify app = Flask('python_api') @app.route("/") def hello_world(): return "Hello World! <strong>I am learning Flask</strong>", 200 @app.route("/<name>") def index(name): if name.lower() == "lucas": return "Olá {}".format(name), 200 else: return "Not Found", 40...
e32415e8110a0793b594e02d7ad9b9c1331398ce
mcode36/Code_Examples
/Python/Python_CodingBat/make_bricks.py
1,000
3.90625
4
''' # method 1 def make_bricks(small, big, goal): possible = False i = 0 for i in range(0,big+1): for j in range(0,small+1): # print(i,j,i*5+j) if i*5 + j == goal: possible = True break if possible: break return possible # method 2 def make_bricks(small, big, goal): ...
e4565b5681c197d037aae4d3137c67795a0a1bad
edu-athensoft/stem1401python_student
/py210109b_python3a/day13_210403/homework/stem1403a_homework_11_0327_max_2.py
1,341
3.515625
4
""" Homework 11 """ from tkinter import * numbers = [25, 30, 98, 3150, 93, 260, 205, 57, 10] def response(i): # print("ok") def getlabel(x): Label(root, text=str(x)).pack(anchor=N) # label1['text'] = str(i) # label1.pack() # print(numbers[i]) return lambda:getlabel(i) root...
086589e79ac0a85bfb40541070a60da8da260dd6
wonder2025/validateIdentityNumder
/validateUtil.py
2,837
3.53125
4
from time import * import re class validateUtil: def __init__(self): pass def age(d,m,y): d=int(d) m = int(m) y = int(y) # get the current time in tuple format a = gmtime() # difference in day dd = a[2] - d # difference in month ...
23834d8241a96cae127b117cb495f5f1698e27a1
HackerSpot2001/GUI-Quiz-App-with-Python3
/quiz.py
3,216
3.734375
4
#!/usr/bin/python3 from tkinter import * from tkinter import messagebox from random import randint width = 640 height = 480 serial = 1 quis = { "Which language is used to written my Code":"python", "Name of hero in Iron-Man Movie series":"tony stark", "Who is Created Facebook":"mark zuckerberg",...
82d16a87fe3ebb108ced4f363b573389dc3b9d47
Ukabix/machine-learning
/Machine Learning A-Z/Part 4 - Clustering/Section 24 - K-Means Clustering/run.py
1,745
3.75
4
# K-MEANS CLUSTERING #%reset -f # import libraries import pandas as pd import numpy as np import matplotlib.pyplot as plt # import dataset dataset = pd.read_csv('Mall_Customers.csv') # creating matrix of features [lines:lines,columns:columns] X = dataset.iloc[:, [3,4]].values # not [:,1] bc we want a matrix for X!...
47dfffc749626926e4a03394a3e51c554d1adb65
ckt371461/python
/basic/0.py
237
3.71875
4
x = 23 y = 0 print() try: print(x/y) except ZeroDivisionError as e: print('Not allowed to division by zero') print() else: print('Something else went wrong') finally: print('This is cleanup code') print()
2b9511fcaa0fb6c4a5591527eec3493e3be004e2
hevalenc/Curso_Udemy_Python
/aula_82.py
1,340
3.765625
4
#aula sobre encapsulamento - utilizado para proteger o código """ Na programação orientada o objetos (OOP) public - os dados são públicos, ou seja, estão abertos para todos e pode ser modificado fora da classe protected - os dados são protegidos e não podem ser alterados fora da classe, somente dentro do módulo, usa-...
d449012bbe5fa62db5970a08bd7a7221b3059c2f
wangyendt/LeetCode
/Hard/164. Maximum Gap/Maximum Gap.py
643
3.65625
4
# !/usr/bin/env python # -*- coding: utf-8 -*- # author: wang121ye # datetime: 2019/7/9 17:57 # software: PyCharm class Solution: def maximumGap(self, nums: list) -> int: def radixSort(A): for k in range(10): s = [[] for i in range(10)] for i in A: ...
5b83b4e929b26a43301d586ec9b2ed00660af12a
Isabel-Cumming-Romo/Classify-Falls-ML
/test_fwdprop.py
4,444
3.953125
4
import random # for w's initalizations import numpy # for all matrix calculations import math # for sigmoid import scipy import pandas as pd def sigmoid(x): return 1 / (1 + numpy.exp(-x)) def sigmoidGradient(z): #Parameters: z (a numerical input vector or matrix) #Returns: vector or matrix updated by ret...
0b9cf3ee3faeb966bf88139dfcb45369ea3755f6
raitk3/Python
/ex13_blackjack/blackjack.py
6,805
3.703125
4
"""Simple game of blackjack.""" from textwrap import dedent import requests class Card: """Simple dataclass for holding card information.""" def __init__(self, value: str, suit: str, code: str): """Card properties.""" self.suit = suit self.value = value self.code...
a88781b7d5948b681e01d552603dc7f7e70c0e19
sverm/LibToHttp
/LibToHttp/data_structures.py
483
3.625
4
''' Simple Data Structures ''' class NoDuplicateDict(dict): '''Doesn't allow setting to a key if there's a value for it already ''' # http://stackoverflow.com/a/4999321/3399432 def __setitem__(self, key, value): if key in self.keys(): raise ValueError('{0} already has a value {1}, so ...
4468aa080273759b4ddbc3a6837c66fdf496ddec
godmanvikky/Design-Pattern
/Design Pattern python/SOLID/Decoratory.py
1,384
4.03125
4
import time from abc import ABC,abstractmethod def wrap_func(func): def wrap(): print(time.ctime(time.time())) func() print(time.ctime(time.time())) return wrap @wrap_func def func(): print("Function is here") func() class Shape(ABC): def __str__(self): return '' class ...
8d36e534c56470df0301b8f7cc10e0915614b021
DesignisOrion/Py-Project-Matplotlib
/scatterPlot.py
328
3.75
4
from matplotlib import pyplot as plt x_values = [1, 2, 3, 4] y_values = [5, 4, 6, 2] plt.scatter(x_values, y_values) other_x_values = [1, 2, 3, 4] other_y_values = [4, 2, 3, 9] plt.plot(other_x_values, other_y_values, color="navy") plt.title("sample plot title") plt.xlabel("X Values") plt.ylabel("Y Values") plt...
cb38e51ca9ed9503978e84c23e243e45a16c8da0
ilaydaezengin/textGenerator
/data.py
316
3.515625
4
with open('omerHayyam.txt', 'r') as data: book = data.read() chars = list(set(book)) book_size, vocab_size = len(book), len(chars) print ('data has %d chars, %d unique' % (book_size, vocab_size)) char_to_idx = { ch:idx for idx,ch in enumerate(chars)} idx_to_char = { idx:ch for idx, ch in enumerate(chars)}
020b5b1a23cd1d45dae43d9dcf1b6443b9aa5de8
Lizyll/PY4E_Code
/ch8_ex5.py
297
3.84375
4
fname = input('File name: ') try: fhand = open(fname) except: print('There is an exception.') exit() count = 0 for line in fhand: if not line.startswith('From'): continue count = count + 1 words = line.split() print(words[1]) print('There is ', count, ' From lines.')
d453506cf0f85d65f5e77b78443945e5a931f5c6
Raihan9797/Python-Crash-Course
/chapter_10/10.2_exceptions.py
4,138
4.25
4
## Exceptions print(5/0) # Exception object is created when you make an error # if an exception object is created, try: print(5/0) except ZeroDivisionError: print("you can't divide by zero") ## using exceptions to prevent crashes print("gimme 2 numbers to divide") print("press 'q' to quit") while True: ...
ee7b6c69f66e1c9fa7495a59f35df3ce696454e7
gourav47/Let-us-learn-python
/Assignment 8 q9.py
278
4.15625
4
'''compare two tuples, whether they contain the same element in same order or not''' t1=eval(input("Enter the first tuple: ")) t2=eval(input("Enter the second tuple: ")) if t1==t2: print("Tuples are same and are in same order") else: print("Tuples are not same")
e910ca29e45114a2455a6c2190558bb65054c3eb
Othielgh/Cisco-python-course
/3.1.2.11.py
418
4.1875
4
wordWithoutVovels = "" userWord = input("Please input any word: ") userWord = userWord.upper() for letter in userWord: if letter == 'A': continue elif letter == 'E': continue elif letter == 'I': continue elif letter == 'O': continue elif letter == 'U': cont...
af48c6c5ef73f436596264d8f299470f813a71c7
ranchunju147/jiaocai
/day2/list.py
1,070
3.84375
4
#删除某个 alist=['hhh',33,'你好',5,6,7,8] def listt(): a=alist.pop(2) print(alist) print((a)) #添加 def blist(): blist = [1, '2', 3, 4, 'sfds', 5, 6] blist.append('999') print(blist) blist.append(999) print(blist) clist=[9,8,7,] blist.extend(clist) print(blist) blist.append(cl...
afebcb298818b112abb33aca8b4fa0f937e785a7
alexxxesss/PythonPY1001
/Занятие3/Лабораторные_задания/task2_3/main.py
311
3.625
4
if __name__ == "__main__": def func(str_slov): list_slov = str_slov.split() set_slov = set(list_slov) for word in set_slov: print(word) str_word = input('Введите несколько слов через пробел: ') print("-----") func(str_word)
344dd1dffcc4003708c1fd38c0bde2fbd823f683
samer2point0/uni
/FOC/lab1prog/guess.py
572
3.84375
4
from random import randint n=None while(n==None): key=input("enter e/E for easy, m/M for medium or h/H for hard diffuculty ") if key=='e' or key=='E': n=5; elif key=='m' or key=='M': n=10 elif key=='h' or key=='H': n=100 else: print("invalid entry mate! ") randnum...
bc5dce9943bda683347e6cc112a3e02d51711710
Ibtihel-ouni/HackerRank_Submissions
/30 Days of Code/D6 Let's Review.py
303
3.765625
4
# Enter your code here. Read input from STDIN. Print output to STDOUT num= int(input()) for i in range(num): s=input() even = '' odd = '' for j in range(len(s)): if j%2 == 0: even += s[j] else: odd+= s[j] print('{} {}'.format(even,odd))
fd90b284cdc758dabcea6ea014b32625d6ce159a
wuxvsuizhong/Li_pro
/进程和线程/计算密集型任务切换和不切换.py
759
3.671875
4
import time def f1(): n = 0 for i in range(1000000): n += i def f2(): n = 0 for i in range(1000000): n += 1 start = time.time() f1() f2() end = time.time() print(end-start) # 打印运行时间约为 0.0868065357208252 def ff1(): n = 0 for i in range(1000000): n += i yiel...
34ab11c95b31b0b990f7806057dbc3d8421a66ef
DavidBitner/Aprendizado-Python
/Curso/Challenges/URI/1011Sphere.py
118
3.96875
4
radius = int(input()) volume = (4 / 3) * 3.14159 * (radius * radius * radius) print("VOLUME = {:.3f}".format(volume))
90be877774322f773cc69ce13694242a498450f8
Khachatur86/FredBaptisteUdemy
/iteration_tools/slicing.py
644
3.75
4
import math def factorials(n): for i in range(n): yield math.factorial(i) facts = factorials(100) def slice_(iterable, start, stop): for _ in range(0, start): next(iterable) for _ in range(start, stop): yield next(iterable) from itertools import islice print(list(islice(factorials(100), 0, 10, 5)...
89939d276faccf56b278f24a9b962858d2ed544e
juhyun0/python_except
/raise_again.py
560
3.6875
4
def some_function(): print("1~10 사이의 수를 입력하세요:") num=int(input()) if num<1 or num>10: raise Exception("유효하지 않은 숫자입니다. :{0}".format(num)) else: print("입력한 수는 {0}입니다.".format(num)) def some_function_caller(): try: some_function() except Exception as err: print("1)...
67e752a0b198abd6c1dfe416f734494dff1c492c
nsossamon/100daysofcode
/Day4/Randomization.py
477
4.25
4
# Python uses a Pseudorandom Number Generating Algorithm for generating random numbers # The Python Random module has a bunch of functions for generating random number import random random_integer = random.randint(0, 4) print(random_integer) random_float = random.random() print(random_float) love_score = random.rand...
8d06782bd86e3505fa847b82abc5b5daa6e0e67f
ChandraSiva11/sony-presamplecode
/tasks/final_tasks/dictionary/10.count_freq_word.py
140
3.578125
4
# Python Program to Count the Frequency of Words Appearing in a String Using a Dictionary def main(): if __name__ == '__main__': main()
ac43712ec4bd1eb98b0b8de3dacdafb7812d9d67
Tsukumo3/Algorithm
/Algorithm/最短経路問題/dijkstra.py
6,827
3.921875
4
class Dijkstra(): ''' ダイクストラ法 重み付きグラフにおける単一始点最短路アルゴリズム * 使用条件 - 負のコストがないこと - 有向グラフ、無向グラフともにOK * 計算量はO(E*log(V)) * ベルマンフォード法より高速なので、負のコストがないならばこちらを使うとよい ''' class Edge(): ''' 重み付き有向辺 ''' def __init__(self, _to, _cost): self.to = _to ...
64a7940da747ee71480d257463fc8eafd05afeef
ambosing/PlayGround
/Python/Problem Solving/ETC_algorithm_problem/5-7-2 Curriculum design.py
305
3.515625
4
from collections import deque nec = input() for i in range(int(input())): s = deque(input()) res = "" while s: c = s.popleft() if c in nec and c not in res: res += c if nec == res: print("#%d YES" % (i + 1)) else: print("#%d NO" % (i + 1))
59fb44cf51a1dc891425fca82c20576400c2d6f8
jamalsyed00/LR--FoDS
/final_assignment_2.py
8,953
3.5
4
import random import numpy as np import pandas as pd import matplotlib.pyplot as plt from numpy.linalg import inv """DATASET LOADING AND PREPROCESSING""" df = pd.read_csv("insurance.txt") df.insert(0,'x_0',1) df = df.sample(frac=1) def standardize(num,mu,sd): return (num-mu)/sd def preprocessing_data(df): a...
8b470ba49310265caeddd303fb919d62a241f1ee
surmayi/CodePython
/PythonLearning/Arrays/TwoSumProblem.py
546
3.515625
4
def twoSumProblem(num,target,method): if method==1: for i in range(0,len(num)-1): if target-num[i] in num[i+1:]: return(num[i], target-num[i]) else: f=0 l=len(num)-1 while f<l: if num[f]+num[l]==target: return (num[f],num[l]...
443469228fc99b2bf78f1f4442332c7961c704ef
Sidhus234/Python-Dev-Course
/Codes/Section 11 Modules in Python/GuessGame/main.py
402
4
4
import sys import random min_value = int(sys.argv[1]) max_value = int(sys.argv[2]) print(f'Please guess a number between {min_value} and {max_value}') while(True): print(f"Is your number {random.randint(min_value, max_value)}?") user_input = input("Please enter Y for Yes and N for No") if(user_i...
c6740816fe50007a7f5c1f7064522d20dce3c242
aurelienO/sdia-python
/src/sdia_python/lab2/box_window.py
3,836
3.546875
4
import numpy as np from sdia_python.lab2.utils import get_random_number_generator class BoxWindow: """Representation of a box defines by [a1,b1] x [a2,b2] x ...""" def __init__(self, bounds): """Constructor of a BoxWIndow Args: bounds (numpy.array): The bounds of the box. ...
c48745b0761848d2f0d59fbc5f78314847b5d014
jake94a/PHYS3330
/HW1.3.py
1,737
4.15625
4
""" Description: Find the max common factor of two user-inputted numbers a and b Max factor is the largest number that each a and b are divisible by while the quotient returns an integer (It is possible to use a while loop here, but I elected not to) Example, 15 and 25 have a max common factor of 5 because 15/5=3 ...
7c4ccfe504baed51f8708c7fafdc301b3ce5fbde
Zhaokun1997/UNSW_myDemo
/COMP9021/COMP9021_quiz_4/quiz_4.py
3,056
3.96875
4
# COMP9021 19T3 - Rachid Hamadi # Quiz 4 *** Due Thursday Week 5 # # Prompts the user for an arity (a natural number) n and a word. # Call symbol a word consisting of nothing but alphabetic characters # and underscores. # Checks that the word is valid, in that it satisfies the following # inductive definition: # - a sy...
07ca874705f4e92b5f011bded36b3af2e9602d1a
rinkeigun/linux_module
/python_source/getNikkeiWebPageTitle.py
373
3.515625
4
# -*- coding: utf-8 -*- #import urllib as myurllib from urllib.request import urlopen from bs4 import BeautifulSoup url = "http://www.nikkei.com/" #html = myurllib.urlopen( url ) html = urlopen( url ) #soup = BeautifulSoup( html, "htmlparser" ) soup = BeautifulSoup( html, "html5lib" ) title_tag = soup.title title ...
f19d4075f091a4b8ae76724a2d963ae68b6a0941
vkumar62/practice
/maze.py
1,142
3.75
4
#!/usr/bin/python3 import pdb def get_all_neighbors(maze, cur): neighbors = [] x,y = cur for xo in range(-1, 2): for yo in range(-1, 2): xi = x+xo yi = y+yo if xi < 0 or xi >= len(maze): continue if yi < 0 or yi >= len(maze[0]): ...
c4df7b4195348b0448c3865de9ff3a59657e6e38
UCAS-BigBird/Algorithm
/SA_SLL3.py
852
3.6875
4
#第一种解法的思路看起来很难,实际与前面存在着一定的联系 #这里引入了id函数 #>>>a = 'runoob' #>>> id(a) #4531887632 储存id的值 # Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def hasCycle(self, head): """ :type head: ...
8d69297de0c78b87ce1f03fea54ee848812682e8
GustavoMDantas/My-Studies
/tt.py
269
3.828125
4
n = int(input().strip()) result = n % 2 if result == 0 or range(2, 5): print('Not Weird') if result == 0 and result > 20: print('Not Weird') if result == 0 and range(6,20): print('Weird') elif result == 1: print('Weird')
9e583c8c3b3b2b3e2a5d210ea04ece8029f1b9b1
RacerChen/pythonLearn2
/oop2_vector.py
1,394
4.125
4
from math import hypot class Vector: # 特殊方法一般只有解释器才会调用(eg. x.__bool__) # 唯一例外的是__init__方法,因为一般子类会去调用超类的构造器 def __init__(self, x=0, y=0): # 构造函数和属性定义 self.x = x self.y = y def __repr__(self): # 实现print函数,也可以实现__str__函数 # 但推荐使用本函数,因为__str__会自动被替代 return ...
c5cf30564d1307438e4ce459337a6be219be5144
oneshan/Leetcode
/accepted/159.longest-substring-with-at-most-two-distinct-characters.py
1,347
3.890625
4
# -*- coding: utf8 -*- # # [159] Longest Substring with At Most Two Distinct Characters # # https://leetcode.com/problems/longest-substring-with-at-most-two-distinct-characters # # algorithms # Hard (41.72%) # Total Accepted: 31.1K # Total Submissions: 74.7K # Testcase Example: '"eceba"' # # # Given a string, find ...
ce3ae2eb354d53950fc82fa0896f8e11e083f622
zbay/linear-algebra
/IntersectionQuizzes/GaussianElimination2/vector.py
5,261
3.71875
4
import math from myDecimal import MyDecimal from decimal import Decimal class Vector(object): def __init__(self, coordinates): try: if not coordinates: raise ValueError self.coordinates = coordinates self.dimension = len(coordinates) except Value...
65b59ff90f8b69f99905943526a5f28165441b98
Chenlei-Fu/Interview-Preperation
/Lc_solution_in_python/0110.py
575
3.59375
4
class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def isBalanced(self, root: TreeNode) -> bool: """ method: recursion """ self.check = True self.maxDepth(root) ...
74bdb00be3204e28809b633363dca8e7dd7d0ec1
bmacri/Python-HTTP-Server
/server.py
1,620
3.703125
4
import socket #this library allows Python to interface with the operating system's socket API def get_req(site,port): s=socket.socket() #socket() returns a socket object and assigns it to the variable s s.connect((site,port)) #tells the socket object to connect at a particular socket address s.send('GET / \r\n\r\n'...
a1048fdf29e771d27616e233020ccf40b29bd5aa
XBOOS/leetcode-solutions
/ungly_number_II.py
1,534
4.34375
4
#!/usr/bin/env python # encoding: utf-8 """ Write a program to find the n-th ugly number. Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. For example, 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 is the sequence of the first 10 ugly numbers. Note that 1 is typically treated as an ugly number. Hint: T...
6a9957b768d0ad4a8068e0070e15bbe326dc49e0
dhirensr/Programs
/coins.py
277
3.765625
4
values={} values[0]=0 values[1]=1 def coins(n): if n in values: return values[n] else: values[n] = max(n,coins(n/2)+coins(n/3)+ coins(n/4)) return values[n] try: while True: n = int(input()) print(coins(n)) except: pass
fdf16547c6f1e039b207e5d8f2b1ef294fd03f7a
MewtR/super-duper-invention
/utilities.py
225
3.890625
4
def purge_string(s): #Remove everything that isn't a letter s = ''.join(c for c in s if ((ord(c) > 96 and ord(c) < 123) or (ord(c) > 64 and ord(c) < 91))) #Make it lower case s = s.lower() return s