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
61048636c092d7e01ee28c913938b59ae939a235
Malonk/unemployment_stats
/data/move_script.py
678
3.765625
4
import os """Script to move files from folders (a, b, c, ...) to folder x.""" old = "old" base = os.path.abspath(os.path.join(os.path.dirname(__file__), old)) # Create list of directories to process dirs = [x for x in os.listdir(base) if os.path.isdir(os.path.join(base, x))] # Creat new dir if it doesn't al...
7da09559f7aa445eec24035de91f901c9328d3d4
karolSuszczynski/GamesName
/units/attack_and_defence.py
1,710
3.640625
4
from enum import Enum class AttackType(Enum): BLUNT=0 PIERCE=1, SLASH=2, HEAT=3 COLD=4 POISON=5 MAGIC=6 ELECTRIC=7 class SingleParams: def __init__(self, value, type=AttackType.BLUNT): self.value = value self.type = type class Attack: def __init__(self, single...
743350e00f5ce1a81701f34e5c539c908ec1c50b
jang1563/2010_Python_class
/Homework/Homework3/templete.py
12,361
3.640625
4
from cs1graphics import * ################################# # Global variables index_list = [ ( 0, (0, 0) ), ( 1, (0, 2) ), ( 2, (2, 0) ), ( 3, (2, 4) ), ( 4, (4, 2) ) ] word_list = [ ( 'ACROSS', 0, (0, 0), 3, 'BAA' ), ( 'ACROSS', 2, (2, 0), 5, 'SOLID' ), ( 'ACROSS', 4, (4, 2), 3, 'WIT' ), ( 'DOWN', 0, (...
ebfd35ab13d1b55fe3b78f1974a512a1dccb7a4d
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/921 Minimum Add to Make Parentheses Valid.py
1,116
4.21875
4
#!/usr/bin/python3 """ Given a string S of '(' and ')' parentheses, we add the minimum number of parentheses ( '(' or ')', and in any positions ) so that the resulting parentheses string is valid. Formally, a parentheses string is valid if and only if: It is the empty string, or It can be written as AB (A concatenate...
33cabbc93635f4f0ab7d0c877f8e1c979d542c47
JoelSchott/MST
/constant_acceleration.py
285
4.15625
4
x_0 = input('What is the initial x? :') v_0 = input('What is the initial velocity? :') a = input('What is the constant acceleration? :') max_x = input('What is the max x? :') zero_x = input("When is x zero? :") def get_position(x, v, a, t): return x + (v*t) + float(1/2)*a*(t**2)
f12d8a32252ec655f8c016e345d440082517b3d3
daniel-reich/ubiquitous-fiesta
/wsCshmu5zkN5BfeAC_17.py
227
3.546875
4
def divisible_by_left(n): s = str(n) return [f(s,i, x) for i, x in enumerate(s)] ​ def f(s, i, x): if i == 0: return False if s[i-1] == '0': return False return int(x) % int(s[i-1]) == 0
e31d64b03e79270c662765ba2c780c401de7c272
huit-sys/progAvanzada
/72.py
581
4.1875
4
# Ejercicio 72 #Una cadena es un palíndromo si es idéntica hacia adelante y hacia atrás. #Por ejemplo, "anna", "civic", "level" y "hannah" son ejemplos de palabras palindrómicas. #Escriba un programa que lea una cadena del usuario y use un bucle para determinar si es o no un palíndromo. #Muestra el resultado, in...
4ea3ebaf35be9ca8fb38fdae52a9abdb0ddf693b
2q45/Python-crash-course
/7-9.py
392
3.734375
4
import random Poll = [] active = True while active: prompt = "Enter your name Here" name = input("Input your name for the lottery") age = input("input your age for the lottery") if age < 69: print("You're not poggers enough") else: Poll.append(name) if active == False: def winn...
0d19a9af0227f60dcec5317c8c4d4ecf9869b43c
jimhendy/AoC
/2020/06/a.py
750
3.828125
4
import os def run(inputs): total = 0 data = set() # Use a set to store the answers from each group for line in inputs.split(os.linesep): if not len(line.strip()): # Reaching an empty line means a new group so add the current total and reset total += len(data) d...
464cfcccd48b3597164737d4478f559ca070fbb3
hermanschaaf/advent-of-code-2017
/day16.py
1,688
3.625
4
class Circle(object): def __init__(self, values): self.head = 0 self.A = values self.m = len(values) def spin(self, n): self.head = (self.head - n) % self.m def exchange(self, a, b): a = (self.head + a) % self.m b = (self.head + b) % self.m self.A[a...
893cbe38fd79d9136100b2bb3fc77c8b77e3f361
Priyansh-Kedia/MLMastery
/23_identify_outliers.py
3,875
4.1875
4
# An outlier is an observation that is unlike the other observations. # It is rare, or distinct, or does not fit in some way. from numpy.random import seed, randn from numpy import mean, std from matplotlib import pyplot as plt # seed the random number generator seed(1) # generate univariate observations data = 5 * r...
9445f1b97dfaff8cfab0c3d5b4d567fa14e539d1
EduardoCastro15/Algoritmos-Geneticos
/Practicas/Pracs/GENETIC_ALGORITHMS/SimpleAG/GA_Project.py
35,056
3.640625
4
import random from tkinter import * from tkinter import Checkbutton, Entry, messagebox import matplotlib.pyplot as plt from sympy import * from sympy.combinatorics.graycode import bin_to_gray import math import cmath class GUI(): def partition(self, arr, low, high): i = (low-1) # inde...
ca68570c93575630df409f216e5b26235bd53721
harshraijiwala/python-
/quick.py
669
3.734375
4
def partition(a,start,end): pivot = a[end] pindex=start for i in range(start, end): if a[i] <= pivot: t=a[pindex] a[pindex] = a[i] a[i]=t pindex = pindex+1 t = a[pindex] a[pindex] = pivot a[end] = t print(a) print("pivot") print(pivot) print("pindex") print(pindex) return pindex def...
472acaa67e05ce05d20d85d1d1815d18a93989f3
Mahendran-Nadesan/LoLStatsAnal
/tryexcept_test.py
618
3.84375
4
# Test script for try...except ##def main(name, mydict): ## print "Checking if data exists..." ## try: ## is_data(name, mydict) ## except: ## print "Not found..." ## ## ##def is_data(name, mydict): ## if name in mydict: ## print "Name found!" ## ## ## ##x = {} ##x['a'] = 3 ##main('...
8b473ccb6315120ca87783d87e0ebfda07f42030
wwtang/code02
/wordcount3.py
2,308
4.1875
4
""" The problem in you code: 1, you read the whole file one time, that will be slow for the large file 2, you have another method to sort the dict by its values 3, you do not have the clear train of thought Here is the train of thought(algorithm) first, do the base, derive a dict from the file secondly, define the two ...
fb749aea8930eca69d3ce510e4276edf91a2ae24
happiness11/Twitter_Api
/fridaychallange.py
2,035
4.125
4
// #friday challange solution // https://richardadalton.github.io/HTML_Notes/practical_python/file_io/07_walkthrough_quiz_game.html def show_menu(): print("Menu") print() print("1. Add a person") print("2. View People") print("3. Stats") print("4. Exit") option = input("Enter Option\n>") ...
e16ed5cbb254b1c179470e91814aa2b1fc7773ab
minhhoangbui/CEA_Internship
/training/neural_network.py
2,812
3.578125
4
import numpy as np import random # not done def sigmoid(z): return 1.0 / (1.0 + np.exp(-z)) def sigmoid_prime(z): return sigmoid(z) / (1 - sigmoid(z)) class Network(): """ A self-defined class which helps to initialize Neural network """ def __init__(self, size): self.num_layers = l...
48c5beab9235bf6abfda10100ca48cbbe47e5345
sfeng77/myleetcode
/sortCharactersByFreq.py
1,049
4.09375
4
# Given a string, sort it in decreasing order based on the frequency of characters. # # Example 1: # # Input: # "tree" # # Output: # "eert" # # Explanation: # 'e' appears twice while 'r' and 't' both appear once. # So 'e' must appear before both 'r' and 't'. Therefore "eetr" is also a valid answer. # # Example 2: # # I...
40237368c60caffa4172f59a735faf2a1ef04c81
upasek/python-learning
/conditional_statements_and_loops/csl_type.py
308
4.25
4
#Write a Python program that prints each item and its corresponding type from the following list. datalist = [1452, 11.23, 1+2j, True, 'w3resource', (0, -1), [5, 12], {"class":'V', "section":'A'}] print("Original list :",datalist,"\n") for m in datalist: print("Type of {} is {} ".format(m, type(m)))
db786ab71e89c22bfcc5a347f0789ff1cb0cc6c4
syn7hgg/ejercicios-python
/1_6/4_prof.py
2,489
3.53125
4
nombre = "solo_dolar.txt" def archivo_ver(nombre): archivo = open(nombre, "r") datos = archivo.readlines() print("Inicio Lectura de Archivo ", nombre) for reg in datos: i = reg.split("\t") j = i[0] m = i[1] print("Para la fecha: ", j, " el valor del dólar es: ", m...
4abe8cccad0100f755e30e09b64f95bb0af9009f
Qiumy/leetcode
/Python/50Pow(x, n).py
701
3.703125
4
# Implement pow(x, n). # x^n = x ^ (n /2) * x ^(n / 2) (n %2 == 0)或者x^n = x ^ (n /2) * x ^(n / 2) * x(n %2 == 1)。 # n < 0 的时候,x ^ n =1 / (x ^(-n)) class Solution(object): def myPow(self, x, n): """ :type x: float :type n: int :rtype: float """ if n < 0:...
47a5b7728bb1feb396e0ca35cfffec5711dfe8f8
satyar3/PythonLearning
/PythonPractice/ClassConcept_2.py
721
4.25
4
class Employee: def __init__(self, arg_name, arg_salary, arg_age): self.name = arg_name self.salary = arg_salary self.age = arg_age def print_name(self): print(f'Employee name is {self.name}, salary is {self.salary}, and age is {self.age}') # Without Constructor # rohan = Emp...
69d190a72f8cd5d62aea0fdd7d8d51db6b77ec5f
equals-zero/adventure
/props.py
4,041
3.890625
4
class Inventory(object): """ Inventar - Kann Inventar von Spieler oder Objekt Initialisierung: InventarName = Inventory((int)Inventargroesse) """ def __init__(self, maxsize): super(Inventory, self).__init__() self.Inventory = [] self.MaxSpace = maxsize def showAllC...
f24cbb910d3733725580c6c296f27c465f93371c
SensationS/Robotframework-CassandraLibrary
/test/csvlibrary.py
1,012
3.96875
4
#-*- coding: utf-8 -*- import sys import csv from time import localtime, strftime reload(sys) sys.setdefaultencoding('utf-8') def write_CSV_file(filename,*itemlist): """ This Keyword saves list to 'csv' File with timestamp.\n If you input file name like "query" and then output file name will be "Test....
e2fb0febbe02e8f4a58d9da56898e34f80abc64a
ankurjain8448/leetcode
/search-insert-position.py
692
3.53125
4
#https://leetcode.com/problems/search-insert-position/description/ class Solution(object): def searchInsert(self, nums, target): """ :type nums: List[int] :type target: int :rtype: int """ start = 0 end = len(nums) - 1 s = 0 e = len(nums)-1 index = -1 if target < nums[0]: index = 0 elif targ...
c5a171a634a7c6108434b93f61c7983735bb55a7
matejbolta/project-euler
/Problems/07.py
1,095
3.984375
4
''' By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13. What is the 10 001st prime number? ''' # def je_deljivo_s_katerim_od(n, seznam): # if seznam == []: # return False # else: # return n % seznam[0] == 0 or je_deljivo_s_katerim_od(n, ...
f3649882869a3ee962ff4a6fc1776f4558200438
RJEGR/IIIBSS
/python/scripts/exploring_np_plt-2.py
5,653
3.609375
4
#!/usr/bin/python # -*- coding: utf-8 -*- # #------------------------------ # # @uthor: acph - dragopoot@gmail.com # Licence: GNU GENERAL PUBLIC LICENSE, Version 3, 29 June 2007 # # This file contains code that helps to explore numpy and matplotlib modules # # WARNING: This file is not intend to be executed as...
c2934ff8199ef89788561ea6c892ff7617290be0
huanglesi0605/room-seeker
/ourRecommendationAlgorithms/files/src/ballTree.py
3,973
3.515625
4
# encoding=utf-8 """ Description : class for ballTree """ import numpy as np import heapq from collections import Counter import random class BallTreeNode(object): """ treeNode class """ def __init__(self, val, radius, leafs): """ Args: val : vector value for user or item radius : float ra...
b94de9029c2d5934121b17f9b81b9223894ddddb
krishppuria/Regex
/uk_postcode_check.py
1,121
3.515625
4
import re example_codes = ["SW1A 0AA", # House of Commons "SW1A 1AA", # Buckingham Palace "SW1A 2AA", # Downing Street "BX3 2BB", # Barclays Bank "DH98 1BT", # British Telecom "N1 9GU", # Guardian Newspaper "E98 1TT",...
31866cacff287714f2c36a8f99c02f6da7925df2
wuzy361/machine-learning
/explore_enron_data.py
1,138
3.796875
4
#coding:utf-8 #!/usr/bin/python """ Starter code for exploring the Enron dataset (emails + finances); loads up the dataset (pickled dict of dicts). The dataset has the form: enron_data["LASTNAME FIRSTNAME MIDDLEINITIAL"] = { features_dict } {features_dict} is a dictionary of features associated w...
779b5a22bb5004e9bc143ee59642249a341a2b05
guocheng45/Projects
/Python_Basic/decorators.py
3,903
4.4375
4
''' def hi(name="yasoob"): return "hi " + name print(hi()) # output: 'hi yasoob' # 我们甚至可以将一个函数赋值给一个变量,比如 greet = hi # 我们这里没有在使用小括号,因为我们并不是在调用hi函数 # 而是在将它放在greet变量里头。我们尝试运行下这个 print(greet()) # output: 'hi yasoob' # 如果我们删掉旧的hi函数,看看会发生什么! del hi print(hi()) # outputs: NameError print(greet()) # outputs: 'hi yaso...
a2747a2e6ea046c43888c675ccf5369dcbacd105
TanushreeVedula14/18031J0068_Python
/Python/Module 2/Assignment 1_PS_B_7.py
214
4.15625
4
# When two integer lists 'a' and 'b' are given, create a new list containing # middle elements of the given lists 'a' and 'b'. list1 = [1,3,5,7,9] list2 = [2,4,6,8,10] list3 = list1[1:4]+list2[1:4] print(list3)
7cc0383ff6c395fd13704ab261b34c7f7e1be530
ozcayci/python_examples
/examples_07/q1.py
499
4.125
4
# -*- coding: utf-8 -*- import string def caesar_encryption(number_of_letters_to_scroll, text: str): text = text.lower() letters = string.ascii_lowercase result = "" for letter in text: if letter.isalpha(): new_letter = letters[(letters.index(letter) + number_of_l...
8788613503f42ffb480018c1f90871bfdd559a88
siddheshsule/100_days_of_code_python_new
/day_1/length_of_a_string.py
189
4.28125
4
# This program prints length of a string. name = input("Enter any name: ") print(len(name)) # OPTION 2: # letter_count = 0 # for i in name: # letter_count += 1 # print(letter_count)
66b185abdabced55b1cb9ba8b9b87197e3e0e2a9
ziyeZzz/python
/machine_learning/02_gradient_descent.py
2,085
3.546875
4
# -*- coding: utf-8 -*- # 梯度下降和随机梯度下降法求解 # Q:argmin1/2*[(x1+x2-4)^2 + (2x1+3x2-7)^2 + (4x1+x2-9)^2] import random # 要最小化的函数 def f(x1, x2): return 1/2 * ((x1 + x2 - 4) ** 2 + (2 * x1 + 3 * x2 - 7) ** 2 + (4 * x1 + x2 - 9) ** 2) # x1的偏导 def f_x1(x1, x2): return (x1+x2-4)*1 + (2*x1+3*x2-7)*2 + (4*x1+x2-9)*4 # x2...
818c49cf2490eb1f7b9d0fa083e974ee6a718334
hjorthjort/advent2020
/day1/1.py
639
3.609375
4
with open('input.txt', 'r') as f: input = f.readlines() def get_pair(nums, base): needs = {} for n in nums: if n in needs: m = base - n return (n, m) needs[(base - n)] = True return None nums = list(map(lambda x: int(x), input)) base = 2020 (n, m) = get_pair(...
749be04d4d853c6086f65c5bf4b0ecf98a044128
Bayoslav/Libraria
/Users.py
958
3.53125
4
import datetime from peewee import * db = SqliteDatabase('books.db') class User(Model): Name = CharField() Age = IntegerField() Adress = CharField() Phone = IntegerField() Datet = DateField() def addbook(self,num): pass #f=open('users.dat','r') def cita(self): citad ...
a69ae3f8092673ce18eeda7d40e69d060317d45e
Santhoshkumard11/Day_2_Day_Python
/alphabet_detect.py
730
4.125
4
# Program to check the alphabets in the given string print("Enter the string:") strin = str(input()) alp= ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'] i,j=0,0 # Finding the letters in the given string while(i<(len(...
6ce856cfe418b177feaddf31bbe6f4ca18f57f3c
Berteun/adventofcode2020
/day03/part02.py
539
3.921875
4
def read_board(): f = open('input') return [l.strip() for l in f] def count_trees(board, down, right): width = len(board[0]) trees = 0 pos = 0 while pos < len(board): trees += board[pos][((pos//down) * right) % width] == '#' pos += down return trees def main(): board = ...
8d9d4c38e62e4087d317edac939154fb750aa8fc
KwonAndy/SP2018-Python220-Accelerated
/Student/AndyKwon/Lesson03/locke.py
3,025
4.59375
5
# Andy K # Lesson03 # Context Manager """ Write a context manager class Locke to simulate the overall functioning of the system. When the locke is entered it stops the pumps, opens the doors, closes the doors, and restarts the pumps. Likewise when the locke is exited it runs through the same steps: it stops the pumps...
f0142a718ea8a37ea888bfcff8a3f7aaec0d9a9b
lutece-awesome/spartan
/src/input/parser.py
2,971
3.5
4
import json from abc import ABC, abstractmethod from src.conf.config import Setting from .type import RunningData class DataParser(ABC): setting: Setting def __init__(self, setting: Setting): self.setting = setting @abstractmethod def parse(self, input_data: str) -> RunningData: pas...
ab2d9d1070a92c891a724e254b8fde927617accc
alanbeavan/impractical_python_problems
/4/projects/automating_possible_keys/all_possible_keys.py
975
4.25
4
#!/usr/bin/env python3.6 """Enumerate possible keys for a route cipher given a number of columns.""" import itertools def key_permutations(ncol): """Return a list of possible keys for the number of columns. Returns a list of lists. """ cols = list(range(1, ncol + 1)) initial_perms = list(iter...
06397603b0f11eeb41c82da8ce844b3114019ff4
MaT1g3R/csc148
/exercises/ex6/ex6_test.py
3,020
3.53125
4
"""CSC148 Exercise 6: Binary Search Trees === CSC148 Fall 2016 === Diane Horton and David Liu Department of Computer Science, University of Toronto === Module description === This module contains sample tests for Exercise 6. Warning: This is an extremely incomplete set of tests! Add your own to practice writing test...
5fda1720f60d151273233cf82c3fdfc92a205792
daniel-reich/turbo-robot
/RX6eLpSqZENJcGAWf_8.py
337
3.859375
4
""" Create a function whose return value always passes equality checks. ### Examples equals() == 0 ➞ True equals() == [] ➞ True equals() == (lambda: 1) ➞ True ### Notes The challenge is passable. """ class AlwaysTrue: def __eq__(self,other): return True ​ def equals(): return Alway...
12f58cc8e808964c86277a8304c2e97f22cd7a33
priyaSNHU/Practice-Questions
/Algorithmanalysis/Stacks/infix_postfix.py
904
3.5
4
from classtak import Stack def infix_postfix(exp): prec = {} prec["*"] = 3 prec["/"] = 3 prec["+"] = 2 prec["-"] = 2 prec["("] = 1 s = Stack() postfix_list = [] infix_list = exp.split() for ch in infix_list: if ch in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" or ch in "0123456789": ...
6888a5cd26822f95ffbd32431d2d2114256e6b7d
askachen/LeetCode
/Python/LC344.py
790
3.921875
4
import time class Solution(object): def reverseString(self, s): """ :type s: str :rtype: str """ #SOLUTION 1 #return s[::-1] #SOLUTION 2 rs = list("") length = len(s) for i in range(length): rs.append(s[leng...
60ae7c4c24a3e48d2e516c9c40703e268779257e
EllaHunt/Lucky_Unicorn
/00_LU_base_v_01.py
1,341
4.15625
4
# function goes here... def yes_no(question): valid = False while not valid: response = input(question).lower() if response == "yes" or response == "y": response = "yes" return response elif response == "no" or response =="n": response = "no" ...
112ce9cf35489c17fba6183a85fc84ed06ece61d
MarceloBritoWD/URI-online-judge-responses
/Estruturas e Bibliotecas/1259.py
349
3.84375
4
vezes = int(input()); cont = 0; numerosPares = []; numerosImpares = []; while (cont < vezes): valor = int(input()); if (valor%2) == 0: numerosPares.append(valor); else: numerosImpares.append(valor); cont += 1; numerosPares.sort() numerosImpares.sort(reverse=True); for i in numerosPares: print(i); for i ...
8bc635369878e5b487dd391637cc796933ecf8e7
niksm7/Data-Structures-Implementation
/Trees/TreeFromInorderPreoder.py
4,703
4.21875
4
class Node: def __init__(self, data): self.val = data self.left = None self.right = None class Tree: preIndex = 0 ''' This function may be called recursively and will help us to construct the tree''' def createTree(self,inOrder,preOrder,inStart,inEnd): if inStart > in...
48964a1ea312f9bee0ccac0f7cbce15049362ae9
conversekuang/GoF23
/singleton2.py
850
3.578125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ @author: converse @version: 1.0.0 @file: singleton2.py @time: 2021/9/3 15:25 """ # 函数实现装饰器,来修饰单例的类。 import threading import time def singleton(cls): _instance = {} _lock = threading.Lock() def _inner(): if cls not in _instance: wit...
0b5f4c07fb474db8d6166451fff4edd250ec6ccb
principia12/Algorithm-Lickers
/Seungwoo/binary_tree_maximum_sum_path.py
2,578
3.578125
4
# Definition for a binary tree node. from pprint import pprint def stringToTreeNode(input): input = input.strip() input = input[1:-1] if not input: return None inputValues = [s.strip() for s in input.split(',')] root = TreeNode(int(inputValues[0])) nodeQueue = [root] front = 0 ...
ab469b2c744e3a34041de30c4c03915cf6bbb915
FilipovichSv/PythonHomeTasks
/Task4Variant1.2.py
486
3.90625
4
a = [1,2,3,4] point = 5 for a[0] in a: for a[1] in a: x=(a[0] + a[1]) if x == point: print(x) else: print('not found') for a[1] in a: for a[2] in a: x=(a[1] + a[2]) if x == point: print(x) else: print(...
151bba65c82c2b256b92183f36fcf7a241e5d7cf
ElenaVasyltseva/Beetroot-Homework
/lesson_ 4/task_4_1.py
866
4.3125
4
# Task 1 # The Guessing Game. # Write a program that generates a random number between 1 and 10 # and lets the user guess what number was generated. # The result should be sent back to the user via a print statement. import random print('I thought of a number, from 1 to 10, guess what?') print('You have...
b1fcdcdd547fd81fb79feaa41314b85afa173855
satishrn/DiscardChatBotApp
/DiscordChatBot/Data_storage.py
804
4.09375
4
import sqlite3 class DataStoreSqlite(object): """ Database class to create , insert and fetch the data """ def __init__(self): self.conn = sqlite3.connect('search.sqlite') # connecting to database and creating table self.cur = self.conn.cursor() self.table = self.cur.execute('CREATE ...
f84fcd128d6dac48545f9828e2c26e4907bedeb0
adityamhatre/DCC
/dcc #6/double_linked_list_with_xor.py
5,260
4.4375
4
import unittest """ An XOR linked list is a more memory efficient doubly linked list. Instead of each node holding next and prev fields, it holds a field named both, which is an XOR of the next node and the previous node. Implement an XOR linked list; it has an add(element) which adds the element to the end, and a g...
a7ff57694d4ee056fabbd309879818508c7463fa
ksaubhri12/ds_algo
/practice_450/graph/13_topological_sorting.py
600
3.609375
4
def topological_sorting(v, adj_graph: [[]]): data_stack = [] visited = [False] * v for i in range(v): if not visited[i]: dfs_util(i, visited, data_stack, adj_graph) return list(reversed(data_stack)) def dfs_util(vertex: int, visited: [], data_stack: [], graph: [[]]): if visited...
2016c31d837c5bcdd7c9eb851fb82d7a8bcb99ad
Banti374/Sorting-Algorithms
/heapsort.py
770
4
4
from array import * def heapify(arr, n, i): largest = i l = 2 * i + 1 r = 2 * i + 2 if l < n and arr[i] < arr[l]: largest = l if r < n and arr[largest] < arr[r]: largest = r if largest != i: arr[i],arr[largest] = arr[largest],arr[i] def heapSort(arr):...
b75ce2600829c3b65ea40f999948d667386e5138
HNoorazar/Public
/My-Image-Analysis-Codes/imageanalysis/play_movie.py
724
3.578125
4
import scipy.io as sio import matplotlib.pyplot as plt import matplotlib.animation as animation import matplotlib.image as mpimg from time import sleep import glob import os def play_movie(image_matrix, time_range=[0, 59], color_map = 'Greys', pause_time=0.01): """ This function takes a 3D matrix and plays it ...
ca7de5833c1f6f1705b15c2c5455677511a0f855
gaurava45/PythonProjectRepo
/dictionary.py
504
3.734375
4
d1 = {} print(type(d1)) d2 = {"harry":"burger", "rohan":"fish", "shubham":{"B":"maggi","L":"roti","D":"chicken"}} print(d2["shubham"]["L"]) name = "harry" d3 = {name:"burger", "rohan":"fish", "shubham":{"B":"maggi","L":"roti","D":"chicken"}} name = "shubham" print(d3[name]) d3[420] = "kebabs" print(d3) del d3[4...
3113c83136fb51002505d1e2a1ce88d51db13023
arthurDz/algorithm-studies
/bloomberg/first_missing_positive.py
577
3.671875
4
# Given an unsorted integer array, find the smallest missing positive integer. # Example 1: # Input: [1,2,0] # Output: 3 # Example 2: # Input: [3,4,-1,1] # Output: 2 # Example 3: # Input: [7,8,9,11,12] # Output: 1 # Note: # Your algorithm should run in O(n) time and uses constant extra space. def firstMissingPosi...
39cff26197a0dbf4730ac65b05afb666c620afd7
busraeskiyurt/Python-projects
/prime number.py
602
4.125
4
number1=int(input("please enter to number for learn your want number if your number is prime or not.")) #ı wanted you enter a number here counter=0 # I create a variable ı wanted you enter a number here for i in range(2, number1+1): # If the number is prime, the counter must be 1. if number...
5d1da33b871daa3b0f42896355d4176a6d9f4b78
RobertoLocatelli02/Python-Learning
/Estrutura sequencial/TintaPorMetroQuadrado.py
410
3.78125
4
import math metrosQuadrados = float(input("Informe quantos metros quadrados serão pintados: ")) litrosTinta = metrosQuadrados / 3 latasTinta = math.ceil(litrosTinta / 18) totalAPagar = latasTinta * 80 print(f"Metros quadrados a serem pintados: {metrosQuadrados} \nLitros de tinta a serem precisos: {litrosTinta} \nQuanti...
d46d6cea6ae94baffda547171a30223c3d714471
codecell/pythonAlgos
/strings/firstUnique.py
456
3.703125
4
# Q. https://leetcode.com/explore/interview/card/top-interview-questions-easy/127/strings/881/ ''' Runtime - O(n) space complexity - O(1) ''' from collections import defaultdict def firstUniqChar(s): d = defaultdict(int) for char in s: d[char] += 1 for x in d: if d[x] == 1: ...
9f12608ff303537235804a58cc734c0c03fe6d75
mrxuying/apitest
/Python/flightwar/property.py
1,090
4.0625
4
##class Num(object): ## def __init__(self): ## self.__num = 100 ## ## @property ## def num(self): ## ## print('-----getter------') ## return self.__num ## ## @num.setter ## def num(self,new_num): ...
ce8565b135ec253695787ea9078fd1f90add6a57
ganjianfeng96/review
/q2/ut_fibonacci.py
801
3.640625
4
import unittest from fibonacci import * class SzTestCase(unittest.TestCase): def setUp(self): print "test path_parse start" def tearDown(self): print "test path_parse stop" def test_fibonacci_0(self): #self.assertTrue('./test.txt', parse_path(path, name)) self.assertEqual([0]...
0e10cf435f85393a795701132e17821a85449ad4
AbderrahimAI/Projects-portfolio
/Sorting algorithm/algorithmes_animes-master/main.py
1,800
3.640625
4
#Main file import tkinter as tk from tkinter import font as tkfont from startpage import StartPage from display import Display from compare import Compare import tkinter.font as tkFont from tkinter import ttk #Class implements the basic architecture of the app class App(tk.Tk): def __init__(self, *args, **kwargs)...
886c0ee16aca8503f8b6cca1a174f233e4b78d93
Clementol/Python
/Even_Odd/Even_Odd.py
1,061
4.34375
4
""" By Clement Phone: 08167515092 """ all_numbers = [] #Empty list of all numbers #To enter the length of numbers n = int(input("How many numbers: ")) #To print the length of numbers print("Enter any", n, "numbers") #Loop To input the arrays of numbers according to the length and #put it in all_numbers list for i in...
db01e618b8428be95c672fa6daef04604cabf7fe
turab45/Travel-Python-to-Ml-Bootcamp
/Day 1/fibonacci.py
350
3.921875
4
# Author: Muhammad Turab size = 100 # first two terms n1, n2 = 0, 1 count = 0 if size == 1: print("Fibonacci sequence in range ", size, ":") print(n1) else: print("Fibonacci sequence is :") while count < size: print(n1, end=" ") nth = n1 + n2 # update values n1 = n2 ...
bbb48f22620d7f9b6be015d20e8a5bf6c0a82c68
AChen24562/Python-QCC
/Homework/Homework-wk-6-ifStatements/test/overtimePay.py
388
3.96875
4
hourlywage = float(input("Enter hourly wage: ")) hoursWorked = float(input("Enter number of hours worked: ")) if(hoursWorked > 40): overtimeWage = (40 * hourlywage) + (1.5 * hourlywage * (hoursWorked - 40)) print(f"Gross pay for week is: ${overtimeWage:.2f}") elif(hoursWorked < 40): weeklypay = hourlywage ...
69b50757cef4990993b898161526cef5e1f428fa
mariane-sm/python_scripts
/e06-12.py
329
3.9375
4
def primes(n): primes = [] for number in range(2,n): if number % 2 != 0: is_prime = True for divisor in range(2, ((number/2) + 1)): if number % divisor == 0: is_prime = False if is_prime == True: primes.append(number) return primes #2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43 print p...
2bacece6b82e5e442d68e9c4b5b8f42e817d104f
JianboTang/a2c
/a2c.py
2,500
3.5625
4
# -*- coding: utf-8 -*- """ Convert to Chinese numerals """ # Define exceptions class NotIntegerError(Exception): pass def to_chinese(number): """ convert integer to Chinese numeral """ chinese_numeral_dict = { '0': '零', '1': '一', '2': '二', '3': '三', '4': '四', ...
d22be8a58071b30c3a7e4f228b7b276d24b7f0d6
Dinesh-Sunny/sdesworkshop
/week3/python/elapsed.py
319
3.75
4
def elapsed(str1, str2): """Get elapsed time between two times""" list1 = str1.split(':') list2 = str2.split(':') hrdiff = int(list1[0]) - int(list2[0]) mindiff =int(list1[1]) - int(list2[1]) secdiff =int(list1[2]) - int(list2[2]) seconds = hrdiff * 3600 + mindiff * 60 + secdiff return abs(seconds)
96251d4cd0106e2810ffe86b9231da09b449b403
RIMEL-UCA/RIMEL-UCA.github.io
/chapters/2023/Qualité logicielle dans les notebooks Jupyter/assets/python-scripts/NLP_C1_W4_lecture_nb_02.py
9,366
4.5625
5
#!/usr/bin/env python # coding: utf-8 # # Hash functions and multiplanes # # # In this lab, we are going to practice the most important concepts related to the hash functions explained in the videos. You will be using these in this week's assignment. # # A key point for the lookup using hash functions is the calcul...
e19e1d4de0ec402b49f7c199b4870b7cd61c48dd
danikav/gym_management_project
/tests/booking_test.py
560
3.5
4
import unittest from models.booking import Booking from models.member import Member from models.gymclass import Gymclass class TestBooking(unittest.TestCase): def setUp(self): member = Member("Dani") gymclass = Gymclass("Zumba", "12/03/21", "19:00", "Exercise and dance and have fun!") sel...
66c43babf5869eff183dc6d52b3e3a15584da641
ThiagoMourao/Python-POO
/pessoa/pessoa.py
1,759
3.78125
4
from datetime import datetime from random import randint class Pessoa: ano_atual = int(datetime.strftime(datetime.now(), '%Y')) def __init__(self, nome, idade, comendo=False, falando=False): self.nome = nome self.idade = idade self.comendo = comendo self.falando = falando ...
5b27502a57a5dfe0d0a76f71d121d288f472e29f
BrunoCaputo/ac309-pyExercises
/Exercises2/Q3.py
1,685
3.90625
4
# Crie um programa que leia nome, sexo e idade de várias pessoas, # guardando os dados de cada pessoa em um dicionário e todos os dicionários em uma lista. # No final, mostre: # a. Quantas pessoas foram cadastradas; # b. A média de idade do grupo; # c. Uma lista com todas as mulheres; # d. Uma lista com todas as pe...
4f9c8830c4c6f789a36c4deea6e20e8d4bfd4604
yuzhenbo/leetcode
/leetcode/self/13_RomanToInteger.py
861
3.6875
4
class Solution: def romanToInt(self, s): symbols_integer = {'I':1, 'V':5, 'X':10, 'L':50, 'C':100, 'D':500, 'M':1000, 'IV':4, 'IX':9, 'XL':40, 'XC':90, 'CD':400, 'CM':900} length = len(s) integer = 0 isP...
2688b8148bf5272e6f6e82f61a4c5fc004674234
chohan3036/algo_study
/Simulation/64061_크레인 인형뽑기 게임.py
912
3.578125
4
from collections import deque def solution(board, moves): # board 를 접근하기 쉽게 조작 # 접근을 쉽게 하기 위해 전치행렬로 만듦 # 빈 공간을 없애 바로 popleft 할 수 있게 만듦 trans_board = [list(x) for x in zip(*board)] final_board = deque([]) for i in range(len(board)): final_board.append(deque(map(int, [x for x in trans_bo...
30e7c5c9f78ebf6446e056b534f6e998cc564fa4
mraduldubey/HackerRank-Python-Challenge
/Basic Data Types/l9.py
752
3.859375
4
if __name__ == '__main__': N = int(raw_input()) lists = [] while N: st = raw_input() action = str(st.split(" ")[0]) if action == "insert": i,j = map(int,st.split(" ")[1:]) lists.insert(i,j) elif action == "print": print lists elif a...
0474b321b92fa02a39d502466f9485c1aaabe45c
Aasthaengg/IBMdataset
/Python_codes/p03486/s216036231.py
319
3.53125
4
s=list(input()) t=list(input()) s.sort() t.sort(reverse=True) s="".join(s) t="".join(t) for i in range(min(len(s),len(t))): if ord(s[i])==ord(t[i]): continue elif ord(s[i])<ord(t[i]): print("Yes") break else: print("No") break else: if len(s)<len(t): print("Yes") else: print("No")
2d1ae9a8cb7c613f2dfa0f4d4e0f849ad254815f
kersky98/stud
/coursera/pythonHse/fifth/23.py
1,170
3.671875
4
# Дан список целых чисел, число k и значение C. Необходимо вставить в список на # позицию с индексом k элемент, равный C, сдвинув все элементы, имевшие индекс # не менее k, вправо. Поскольку при этом количество элементов в списке # увеличивается, после считывания списка в его конец нужно будет добавить новый # элем...
5fcb91a8970dd97373bb42dc8c993fd13b692d01
gssxgss/leetcode-solutions
/python3/189_rotate_array.py
491
3.546875
4
# https://leetcode.com/problems/rotate-array/description/ class Solution: def rotate(self, nums, k): """ :type nums: List[int] :type k: int :rtype: void Do not return anything, modify nums in-place instead. """ if not nums or not k or len(nums) == 1: ret...
363a4146c5c0f243339068cf6a449fbed3ff1f57
maximkavm/algorithms-and-data-structures
/part-1/06-recursia-dinamic-task-soldier/task-3.py
1,945
3.71875
4
''' Одномерная динамика Оловянный солдатик Он ходит по шахматной доске. В начале пути он стоит на линии 1 (не важно на какой вертикали, букве). У солдатика ограничена длина шага в клетках - d. Каждый шаг солдатик делает случайной длины в диапазоне [1,d]. Пусть дана размерность доски, например - 4 клетки (доска 4х4) и ...
7299f3962e50caed2be460df8e42f5c9eb186597
MikBom/mikbom-github.io
/Python/Chapter 12 - Tehtävä 1.py
244
3.890625
4
lista = [] lista.append("Sininen") lista.append("Punainen") lista.append("Keltainen") lista.append("Vihreä") print("Listan ensimmäinen alkio on:",lista[0]) print("Lista tulostettuna alkio kerrallaan:") for i in lista: print(i)
4e1fa0a22578573f9ac5878c8bd999f757d7f54a
atmfaisal/assignment
/Problem1/main.py
9,147
3.75
4
import sqlite3 conn = sqlite3.connect('db.sqlite') cur = conn.cursor() sql_command = """ DROP TABLE IF EXISTS student; DROP TABLE IF EXISTS subject; CREATE TABLE student ( id INTEGER, name VARCHAR, current_class INTEGER, status INTEGER DEFAULT 1, PRIMARY KEY(id)); CREATE TABLE subject ( id I...
a5e04c8c20eff1ff31b0ec035f9766b0cd5e906b
ecarlosfonseca/HackerRank
/Collections_ordereddict.py
525
3.5
4
from collections import OrderedDict d = {} for i in range(int(input())): article = input().split() product = '' price = 0 for v in article: if v.isdigit(): price += int(v) else: product += v + ' ' if product[:-1] not in d: d[product[:-1]] = int(price)...
f77556af118932d86d12508ac6b4fef5ded6a4f9
testdata6/python-test
/python3/python_numbers.py
468
4.15625
4
#!/usr/bin/python ## Printing numbers print(2) print(2.0) print(-2.0) print(2+2) ## Correct method to do arithmetic operation. print(2*(2+2)) ## Correct method print(2*2+2) ## Incorrect method ## Convert interger to string value. b=10 print(type(b)) print(str(b) + " is a Value of b") ## Print and convert absulate ...
249362a977c2644321431698268abe2b7bf3cfbc
NateRiehl/Python-Data-Structures
/LinkNode.py
186
3.578125
4
# Linked list node implementation class LinkNode: def __init__(self, next, data): self.next = next self.data = data def __str__(self): return "Link Node: " + str(self.data)
7a05ab4e5bb99b46d76330e989e16acab52468a0
lingyun666/algorithms-tutorial
/leetcode/MajorityElement/majority_element.py
3,225
3.921875
4
# coding:utf8 ''' LeetCode: 169. Majority Element Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times. You may assume that the array is non-empty and the majority element always exist in the array. 题目大意: 给定一个大小为 n 的数组, 找一个特定的元素, 这个元素满足在这个数组至少出...
7f34d63e66dedfd9b2ae8e56ed04ff567e4bba4e
tamaragmnunes/Exerc-cios-extra---curso-python
/Desafio026.py
226
3.96875
4
'''Faça um programa que leia uma frase pelo teclado e mostre: 1. Quantas vezes aparece a letra 'A' ''' frase = str(input('Digite uma frase qualquer: ')) print('A letra A aparece {} vezes.'.format(frase.count('A')))
b2018d69022289e49c0300681437fc78f2d02446
fabian017/MisionTIC
/CICLO 1 - PYTHON/Listas y Diccionarios/ejercicio2.py
730
3.75
4
'''Diseñe un algoritmo que pida un número al usuario un número de mes(por ejemplo, el 5) y diga cuántos días tiene(por ejemplo, 31)y el nombre del mes. Debes usar listas. Para simplificarlo vamos a suponer que febrero tiene 28 días''' meses = ["enero","Febrero","Marzo","Abril", "Mayo", "Junio", "Julio", "Agosto",...
22a7f70868785a9c803020224aae1a5aabd74069
cvchakradharreddy/coursera
/week1/MaxPairwiseProduct_bkp.py
530
3.84375
4
size = int(input()) numbers = [int(x) for x in input().split()] def get_max_pairwise_product(): max_one_ind = 0 max_two_ind = 0 max_one = 0 max_two = 0 for i in range(0, size): if numbers[i] > max_one: max_one = numbers[i] max_one_ind = i for i in range(0, size...
e10adc110308c34e22a034f5aacb49275a2fb777
raulgfc/Estudos_Python
/guppe/7.Tipo_Booleano.py
785
3.828125
4
""" Tipo Booleano Algebra booleana, criada por George Boole 2 constantes, Verdadeiro ou Falso OBS: Sempre com a inicial maiúscula Errado: true or false Correto: True or False """ ativo = False print(ativo) ################################# ################################# """ OPERAÇÕES BÁSICAS: """ #################...
5b3c6c0cb800365fd74e94ba237da98ed6ac19cd
abdullahf97/Lab-05
/Program 1, Lab -05, Abdullah Farooq, 18B-104-CS-A.py
312
3.703125
4
print('Abdullah Farooq') print('18B-104-CS-A') print('Lab-05, 24-11-2018') print('Program 1') count=0 f=eval(input("Enter your final condition where you want to break the loop: ")) while(count<f): print("The value of count:",count) count = count+1 print("I am using while loop", count, "time.") ...
acc65db5b94e798fd3354463faf4a6f79e17e45c
EruDev/Learn_Algorithms
/算法图解/chapter-10/10.py
418
3.84375
4
# coding: utf-8 """ 有一个长度为n序列,移除掉里面的重复元素,对于每个相同的元素保留最后出现的那个 示例: 1,8,7,3,8,3,1 输出: 7,8,3,1 """ def find_last(seq): li = list() for i in seq: if i not in li: li.append(i) else: li.remove(i) li.append(i) return li if __name__ == '__main__': seq = [1, 1, 7, 1, 8, 3, 1, 7, 8] # 3,1,7,8 print(find_...
0cab6617a873cc1b33d0d48f50a3c606ff2b2879
alvas-education-foundation/ECE-2year-Code-Challenge
/Securitycode(Vishwesh V Bhat).py
817
3.921875
4
#Objective: WAP to verify Username and Password, Username = 'Micheal' and Password = 'e3$WT89x', and with just 3 attempts for the user. user_name = "Micheal" user_input = input("Enter username : ".upper()) if user_input == user_name: for Attempts in range(3): password = 'x' pas_i...
f686111df92233823618a2433fff7fa4c50d56e0
UCDavisLibrary/scribeAPI
/project/label_this/tools/rotate_exif.py
817
3.5
4
from PIL import Image, ExifTags import os import sys import traceback import pprint def rotate(filename): try : image=Image.open(os.path.join(filename)) for orientation in ExifTags.TAGS.keys() : if ExifTags.TAGS[orientation]=='Orientation' : break exif=dict(image._getexif().it...
5f3c51a4a7959c6be38c6b809e6403dc14efdd2e
rafaelperazzo/programacao-web
/moodledata/vpl_data/303/usersdata/283/82729/submittedfiles/testes.py
183
3.875
4
# -*- coding: utf-8 -*- #COMECE AQUI ABAIXO a=float(input('Constante 1: ')) b=float(input('Constante 2: ')) Constante3=c (1/c) == (1/a) + (1/b) print("Constante 3: c")
1b57bdcacb28845c0c1083c79a11376d28a521a3
alexanderbart/EulerProject
/euler28.py
1,525
3.796875
4
import numpy as np '''Euler 28''' def spiral_diag(N): ''' Starting at the middle, we move down the row once, then column once. Then we go up row twice, up column twice. Then up row thrice, column thrice. So even numbers of moves increase column and row. Odd numbers of moves decrease column and row. The final piece...
aae1af1f3439baedab4d111f482abb97237d31e4
Mengeroshi/Python-Crash-Course-exercises
/classes/9.5_login_attempts.py
922
3.578125
4
class User: def __init__(self, first_name, last_name, age): self.first_name = first_name self.last_name = last_name self.age = age self.loggin_attempts = 0 def describre_user(self): print(f"Name: {self.first_name.title()}") print(f"Last Name: {self.last_name....