blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
3375164586e3df90f30bd6c9256be13e49cb2aa2
justsimransingh/Python-List-Questions
/03.py
263
4.03125
4
''' 3. Write a Python program to change the position of every n-th value with the (n+1)th in a list. Sample list: [0,1,2,3,4,5] Expected Output: [1, 0, 3, 2, 5, 4] ''' l=[0,1,2,3,4,5] for i in range(0,len(l)-1,2): l[i],l[i+1]=l[i+1],l[i] print(l)
2097310d0955849fc042da9a21a3d4a4b2f7bf6f
ghostlyman/python_demos
/syntax/function/imooc_mh_20180126/demo_05.py
451
3.578125
4
# -*- coding:utf-8 -*- def dec(func): print('call dec') def in_dec(*args): print('in dec args =', args) if len(args) == 0: return 0 for val in args: if not isinstance(val, int): return 0 return func(*args) print('return in_dec') ...
e458136850f6ae76157a7ac3967261b08e62d865
ghostlyman/python_demos
/syntax/function/blog_sr_20180126/demo_11.py
187
3.6875
4
# -*- coding:utf-8 -*- a_var = 2 def a_func(some_var): return 2 ** 3 # 通过函数返回值改变全局变量, 而不是在函数内部修改 a_var = a_func(a_var) print(a_var)
404a13fb0defb805471a150d9c6cc0ed2e311c10
ghostlyman/python_demos
/syntax/function/imooc_mh_20180126/demo_04.py
630
3.828125
4
# -*- coding:utf-8 -*- def my_sum(*args): return sum(args) def my_average(*args): return sum(args) / len(args) def dec(func): def in_dec(*args): # 参数预处理 print('in dec args =', args) if len(args) == 0: return 0 for val in args: if not isinstance(va...
35443c3c2b1440d7c0f0ba3a8da4b50c3751f461
ghostlyman/python_demos
/syntax/oop/imooc_jugg_20180125/3-1.py
295
3.546875
4
# -*- coding:utf-8 -*- # Python3 中都是新式类 class NewStyle(object): def __init__(self, name, desc): self.name = name self.desc = desc if __name__ == '__main__': new = NewStyle('new', 'new style class') print(new) print(type(new)) print(dir(new))
43c4257cd852c9134e1c13f17b8cd50d226539ac
jovalle/advent-of-code
/2021/day/2/dive2.py
572
3.5625
4
import sys import os if __name__ == "__main__": odometer = 0 depth = 0 aim = 0 with open(os.path.join(sys.path[0], 'input.txt'), 'r') as moves: for move in moves: direction, units = move.split(" ") units = int(units) if direction == "forward": odometer += units depth += a...
9441f974f6bdfdad13461e17f596862fab08060a
mateuscmartins-1/Paciencia-Acordeao
/Paciencia_Acordeao.py
18,850
3.703125
4
#Importamos as bibliotecas para embaralhar o baralho e utilizar cores para os naipes import random from colorama import Fore, Back, Style #Função para criar baralho def cria_baralho(): naipes = ["♠", "♥", "♦", "♣"] valor_carta = ["2","3","4","5","6","7","8","9","10","J","Q", "K", "A"] baralho = [] i ...
ad9ac0e8544dffa485da193863f30a6a6e6ccac4
Lmgarcia8/PR2-ProgAvBio
/FibonacciPython/code/test/fibonacciTest.py
1,299
4
4
import unittest from code.fibonacci import Fibonacci class test_fibonacci(unittest.TestCase): def setUp(self): self.fibonacci = Fibonacci() def test_should_fibonacci_number_of_months_one_and_pairs_produced_three_return_one(self): self.assertEqual(1, self.fibonacci.compute(1, 3)) def tes...
06181797a0dfa68381567f51b1d116b3d3ec2f0e
fpigeonjr/PythonBasics
/masterticket.py
1,339
4.3125
4
TICKET_PRICE = 10 tickets_remaining = 100 # run this code while we have tickets while tickets_remaining : # output how many tickets are available print("There are {} tickets remaining".format(tickets_remaining)) # gather user's name and assign it to a new variable name = input("Please input your name? ") ...
92bb6f429d952c7e142135014cfcc437351c1bd6
burtonrj/IDWT
/ProjectBevan/sql/schema.py
3,092
3.625
4
import sqlite3 import os def _schema(): """ Generates list of SQL queries for generating standard tables for sqlite3 database Returns ------- list List of string values containing SQL queries for each table """ patients = """ CREATE TABLE Patients( patient_id TEXT ...
037ff817b4ea0a29b5a1c35e0557e1568acc534a
shellawk/simplePythonCodes
/25.py
284
4.03125
4
import calendar def user_interface(): year = int(input('Enter the year: ')) month = int(input('Enter the month: ')) if year>0 and month < 12 and month > 0: print(calendar.month(year, month)) else: print('Invalid input!! TRY AGAIN.') user_interface()
54e2a25d5c7bb1c49deb42516a0e1f8ca5e5c656
shellawk/simplePythonCodes
/23.py
551
4.1875
4
import datetime current_year = datetime.date.today().year def user_interface(): age = int(input('How old are you: ')) maximum_human_lifesapn = 160 #according to wikipedia if age>=0 and age <= maximum_human_lifesapn: get_year_of_birth(current_year, age) else: print('Invalid input.') ...
a3fa7c219c1b3b96cec0bf755ba9a061a339b0d2
shellawk/simplePythonCodes
/10.py
396
4.0625
4
def user_interface(): print('Enter the range of odd numbers to be displayed') min_num = int(input('Enter the lower limit: ')) max_num = int(input('Enter the upper limit: ')) get_odd_numbers(min_num, max_num) def get_odd_numbers(lower_limit, upper_limit): upper_limit += 1 for i in range(lower_li...
16b1c071023a454fb652d8755c493c2ed75fb57b
dothedung1982/ds-program-2
/PycharmProjects/alc/object/line.py
1,093
3.640625
4
import alc.object.machine as myMachine class Line: list_machine = [] def __init__(self, id): """constructor""" self.id = id # class instance (data) attribute def add_machine(self, machine): self.list_machine.append(machine) def is_machine_exists(self, machine_id): r...
f690bd3188bcf5d7a41c0d3653f370d209e2f4a5
Fraznist/prefect
/src/prefect/schedules/filters.py
5,648
4.0625
4
""" Schedule filters are functions that accept a candidate `datetime` and return `True` if the candidate is valid, and `False` otherwise. Filters have the signature `Callable[[datetime], bool]`. """ from datetime import datetime, time from typing import Callable import pendulum def on_datetime(dt: datetime) -> Cal...
4fa93f756b20367e02d82306a94b66be32199705
Fraznist/prefect
/src/prefect/tasks/database/sqlite.py
3,469
3.515625
4
import sqlite3 as sql from contextlib import closing from typing import Any, cast from prefect import Task from prefect.utilities.tasks import defaults_from_attrs class SQLiteQuery(Task): """ Task for executing a single query against a sqlite3 database; returns the result (if any) from the query. Ar...
24c108885fd67e9ab7e2866fa46031516eed80ba
Fraznist/prefect
/src/prefect/tasks/templates/strings.py
1,844
3.5
4
from typing import Any import prefect from prefect import Task class StringFormatter(Task): """ This task contains a template which is formatted with the results of any upstream tasks and returned. Variables from `prefect.context` are also available for formatting. Args: - template (str...
99872b6ff19315349e57acbf427d3562d8e03f1a
Fraznist/prefect
/src/prefect/utilities/datetimes.py
2,031
3.71875
4
import datetime from typing import Any, Callable def retry_delay( interval: datetime.timedelta = None, *args: Any, exponential_backoff: bool = False, max_delay: datetime.timedelta = datetime.timedelta(hours=2), **kwargs: Any ) -> Callable: """ A helper function for generating task retry de...
b26d2122e122b88ca6a8f32446a7a31fb89df89e
Jipolie01/TheQuestToTheBestWorkout
/codev3/main.py
20,545
3.515625
4
# importing al the nessesairy library's import RPi.GPIO as GPIO import RPiGPIO_keypad_edited as GPIO_KEYPAD import MFRC522 import threading import tkMessageBox as message from Tkinter import * from time import sleep import Rowing_Machine import Treadmill import Spinning_Machine import Weightlifting import Climbing_stai...
2d125e08003a5d08868d55a20eca2e3c9ac358e8
jerkchickenandrice/CS-Project
/Theatre Sort.py
1,167
3.953125
4
# -*- coding: utf-8 -*- """ Created on Sat Dec 9 23:29:23 2017 @author: Family """ #Theatre def add_seats(row): i = 0 seat_num = 0 row_num = ['A','B','C','D','E','F','G','H','I','J'] allocated = [] row_chosen = 0 change_seat = False while True: change_seat = False num_tickets = 0 ...
d319d56583b6d408150cc221ca803bd055ed3e35
pefoley2/cmsc424-fall2015
/python-notebooks/fds.py
6,625
3.546875
4
from itertools import chain, combinations # A class to encapsulate a Functional Dependency, and some helper functions class FD: def __init__(self, lhs, rhs): self.lhs = frozenset(list(lhs)) self.rhs = frozenset(list(rhs)) def __str__(self): return ''.join(self.lhs) + " -> " + ''.join(self.rhs) def __eq__(self...
fb158213a1efbcb198f6072b3efe1076c202c798
GaryZ700/QM_UCI
/hartree_fock/hf.py
1,975
3.734375
4
#hartree fock master control file from basis import basis as Basis Basis = Basis() ############################################### #important functions go here ############################################### def ui(): #gets atom charges and coordinates from user atomicNumbers = [] coord = [] charges = [] ...
f89cce0672c715ee2a7034558c6e19c04a897012
jahnaviancha/Python_Task
/Python_Task6/task6.py
1,840
4.1875
4
# Question_1 # Write a program in Python to allow the error of syntax to go in exception. try: print(x) except: print("Hey please check again, I didn't see any value of 'x") # Output: Syntax error # Question_2 from sys import argv NameOfProgram=argv print("Name of the program is: ", NameOfProgram) NameOfFi...
8e11bb937b957558f68342fd3df4e6f329fbbdb3
xp-zhao/learn-python
/pandas_test/pandas_test.py
1,345
3.65625
4
from pandas import Series, DataFrame import pandas as pd obj = Series([4, 5, 6, -7]) print(obj) print(obj.index) print(obj.values) obj2 = Series([4, 5, 6, 7], index=['a', 'b', 'c', 'd']) print(obj2) obj2['c'] = -6 print(obj2) data = {"a": 1, "b": 2, "c": 3} obj3 = Series(data) print(obj3) data_frame = {"city": ["cd...
6ab919a72f3bd4d58050c6b6d837fce6ef252a48
xp-zhao/learn-python
/function/func_test.py
834
3.6875
4
# def how_long(first, *other): # # print(1 * len(other)) # # # # # # how_long(1) # # # # for i in range(10, 20, 2): # # print(i) # # # # # # def f_range(start, stop, step): # # x = start # # while x < stop: # # yield x # # x += step # # # for i in f_range(10, 20, 0.5): # print(i) # #...
78ff34390441f2f3ee38acf0cf382d145183966c
xp-zhao/learn-python
/leetcode/array/twoNum.py
241
3.53125
4
nums = [2, 7, 11, 15] target = 9 def two_sum(nums, target): d = {} for i, v in enumerate(nums): n = target - v if n in d: return i, d.get(n) d[v] = i return [] print(two_sum(nums, target))
467462dbee9eba17138851806c64d39375703caf
xp-zhao/learn-python
/leetcode/tree/sortedArrayToBST.py
490
3.578125
4
from leetcode.tree.TreeNode import TreeNode class Solution: def sortedArrayToBST(self, nums: list) -> TreeNode: if not nums: return None mid = len(nums) // 2 root = TreeNode(nums[mid]) root.left = self.sortedArrayToBST(nums[:mid]) root.right = self.sortedArrayTo...
cf688ddd3cbcbc90253af9f8053aacd1943fed12
xp-zhao/learn-python
/algorithm/leecode/two_sum.py
600
3.6875
4
# 求两数之和, 双重循环暴力求值时间复杂度太高, 可以使用哈希表减少时间复杂度 class Solution: def twoSum(self, nums: list, target: int) -> list: num_dict = {} for index, value in enumerate(nums): num_dict[value] = index print(num_dict) for index, value in enumerate(nums): diff = target - value ...
4c9f0a68c7547e4eb9ce708151288861fc0e12c4
xp-zhao/learn-python
/leetcode/linked/removeDuplicates.py
290
3.75
4
from leetcode.linked.Node import Node def remove(node): cur = node while cur and cur.next: if cur.val == cur.next.val: cur.next = cur.next.next else: cur = cur.next linked = Node.init_by_list([1, 1, 2, 3, 3]) remove(linked) print(linked)
4de8f4738806e95a352857235f82e0ce7f099ef5
xp-zhao/learn-python
/leetcode/tree/validBST.py
1,007
3.796875
4
from leetcode.tree.TreeNode import TreeNode class Solution: pre = None def isValidBST(self, root: TreeNode) -> bool: if root: if not self.isValidBST(root.left): return False if self.pre and root.val <= self.pre.val: return False self...
25c0a6955fd9fd49c83e4844c8f74a3e448bfc40
MDCGP105-1718/portfolio-IablonschiEduard
/ex4.py
562
4.21875
4
my_name = 'Iablonschi Eduard' my_age = 19 my_height = 180 # centimeters, I don't know my height in inches my_weight = 90 # kilograms, I don't know my weight in pounds either my_eyes = 'Brown' my_hair = 'Black' is_heavy = my_weight > 3000 print(f"Let's talk about {my_name}.") print(f"He is {my_height} inches tall.") pr...
ee887714b7e6a9b995d02066277f3bcc45b89915
Shubham531995/word-meaning
/test.py
2,403
3.703125
4
import requests import json import csv #API key and file inofrmation at global scope app_id = '53bbf52b' app_key = '99fdd7529dd0cb81f7f97e94d0247a1f' file_name = 'dict.csv' # Calls Oxford Dictionary API using requests and returns a list of meanings # Source: https://developer.oxforddictionaries.com/documentation de...
374ec26522e20746299b53355c98686ee6e29c30
setiawansopan/belajar-python
/PYTHONINDO/sum_natural_number.py
165
3.9375
4
num = 16 if num < 0: print('masukkan bilangan positif : ') else: sum = 0 while(num > 0): sum += num num -= 1 print('jumlah : ',sum)
8f23cb2c00b8199c8a86a44a9e9aef1f33d170d9
setiawansopan/belajar-python
/PYTHONINDO/perkalian_dua_dengan_lambda.py
169
3.65625
4
terms = 10 result = list(map(lambda x: 2 ** x, range(terms))) print('Total terms adalah : ',terms) for i in range(terms): print('2 pangkat ',i,'adalah ',result[i])
e02bea8d86dc2a10dd180cbcbde2e3b13410896e
RandomMemorandum/radiohead-text-analysis
/lyric-scraper.py
1,273
3.5
4
from bs4 import BeautifulSoup import numpy as np import pandas as pd import re import requests import urllib3 radiohead_url = 'https://www.azlyrics.com/r/radiohead.html' response = requests.get(radiohead_url) html_content = response.text # scrape song names, albums, relevant dates # identify what html elements cont...
4907a1d4b9332709f782f5e34790da612e093fcb
pranayreddy604/gitam-2019
/Searching.py
2,696
4.0625
4
#!/usr/bin/env python # coding: utf-8 # In[ ]: def binarySearch(a,index1,index2,item): while index1<=index2: mindex=index1+(index2-index1)//2 if(a[mindex]==item): return mindex if(a[mindex]>item): index2=mindex-1 else: index1=mindex+1 return...
0fda4da5cf5258a0f410620572fd08c9e5ccd8a7
PolinaKoval/2048A3C
/env2048/grid.py
1,139
3.546875
4
import random import numpy as np class Grid(object): def __init__(self, size): self.size = size self.cells = [[Tile(x, y, 0) for x in range(size)] for y in range(size)] def __getitem__(self, item): return self.cells[item] def available_cells(self): cells = [] for r...
b1efb6c1d107fbc8d9953581e5eef2de39184260
CleverProgrammer/coursera
/iipp1/guess_the_number.py
3,271
3.78125
4
# Guess the number import math import simplegui import random #Intializing global variables global secret_number, number_of_tries, num_range secret_number, number_of_tries, num_range = 0,0,0 # START AND STOP THE GAME [HELPER] def new_game(): global secret_number, number_of_tries, num_range secret_number, numb...
b37630dbc5e0f721136da5f6d3adab5a4c204346
CleverProgrammer/coursera
/poc2/week3/binary_tree.py
1,296
4.28125
4
""" creating a binary tree class and its methods """ class BinaryTreeNode: def __init__(self, data): self.data = data self.left = None self.right = None def setData(self, data): self.data = data def getData(self): return self.data def getLeft(self): ...
6218185ef6442da9256a238f3f3a58c3295bdf64
alvyn279/COMP472_NLP
/language.py
396
3.90625
4
import string LANGUAGES = ['eu', 'ca', 'gl', 'es', 'en', 'pt'] LANGUAGE_DICT = { 'eu': 'basque', 'ca': 'catalan', 'gl': 'galacian', 'es': 'spanish', 'en': 'english', 'pt': 'portuguese' } def add_alphabet_to_ocurrence_dict(is_uppercase: bool, occ_dict): for letter in string.ascii_uppercas...
104c41fb85f8605c65bc21cd45725654e5c17617
Darren-Li/Python
/Web Scraping/others/抓取墨迹天气网所有县级的天气情况.py
4,276
3.578125
4
# 抓取墨迹天气网所有县级的天气情况,并绘图 import requests from bs4 import BeautifulSoup import os import csv import time def get_soup(url): """ 获取解析好的HTML文档树 :param url: 想要获取数据的页面链接 :return: 解析好的HTML文档树 """ try: resp = requests.get(url) except requests.exceptions.ConnectionError as e: print(...
349bc2f1418445c3aa512593bf656d3454599fe6
zamoraricardo15/Word_Count
/LinkedList.py
2,796
3.875
4
from Node import Node class LinkedList: def __init__( self ): self.head = None def insertLast( self, val ): newNode = Node( val ) if self.head == None: self.head = newNode else: current = self.head while current.next != None: ...
982fef0e369b52f027d272b717d8444709259dd3
toshitanian/leetcode
/python/add-two-numbers/carry.py
2,133
3.703125
4
# I'm solving this after watching solutions. # 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: """ """ first_node = ...
24a1ab70fb273dd2e231fb802f5622a8fb2785df
sebastianpinedaar/machine-learning-codes
/master-labs-1S/ExerciseSheet1/ExerciseSheet1.py
11,213
4.28125
4
# coding: utf-8 # Machine Learning Lab - Exercise Sheet 1 # Author: Sebastian Pineda Arango # ID: 246098 # Universität Hildesheim - Data Analytics Master # # # ### Word Count Program # # # The objective in this part is to count the words in a text. To do that we have divided the task in different tasks, which ...
8cdc2d71339d906d0cc108c07e20748c3240b508
movingname/security_exp
/crypto/toy_implementations/robin_miller_primality_test.py
892
3.671875
4
# HW3-4 Version 1 # # Implement the Rabin Miller test for primality # from random import randrange def rabin_miller(n, target=128): """returns True if prob(`n` is composite) <= 2**(-`target`)""" # Based on the psudo code in # https://en.wikipedia.org/wiki/Miller%E2%80%93Rabin_primality_test # This c...
451d9597cb1a61fdefec4bc87cd0286d3445e270
Alirido/sos-game-bot
/sosBoard.py
558
3.546875
4
class SosBoard: def __init__(self): self.board = [['_' for _ in range(8)] for _ in range(8)] self.count = 0 def fill(self, row, col, act): self.board[row][col] = act self.count += 1 def get(self, row, col): return self.board[row][col] def isComplete(self): return self.count == 64 def i...
58e4e154fb65333dee6fd3317dccf30ea2099019
ukates/CodingBat
/WarmupOne/near_hundred.py
210
3.65625
4
# Given and int, return True if it is within 10 of 100 or 200 def near_hundred(n): return abs(n - 200) <= 10 or abs(n - 100) <= 10 print(near_hundred(93)) print(near_hundred(90)) print(near_hundred(89))
97a4374ec64e3b9eaa7297b1f461cb4869d00716
darthsuogles/phissenschaft
/algo/leetcode_121.py
471
3.78125
4
''' Best time to buy and sell stock (only once) ''' def maxProfit(prices): n = len(prices) if n <= 1: return 0 # cannot do two transactions # Need largest of current value min_price = prices[0] max_profit = 0 for curr_price in prices[1:]: max_profit = max(curr_price - min_price, max_pr...
3d4841852bc2a60bef84eb08a83cfd181220cca8
darthsuogles/phissenschaft
/algo/sorted_matrix_search.py
2,447
3.703125
4
''' Search in a row/column sorted matrix ''' def bisect_left(nums, a): if nums is None: return None n = len(nums) if 0 == n: return 0 i = 0; j = n-1 while i + 1 < j: k = (i + j) // 2 v = nums[k] if a == v: while k >= 0: if nums[k] != a: ...
72e60f18e5bb69b2d2c375122654f8797d7e65fc
darthsuogles/phissenschaft
/algo/ib_max_non_negative_subarray.py
843
3.546875
4
''' ''' def maxset(A): if not A: return [] n = len(A) i = 0 while i < n: if A[i] >= 0: break i += 1 if n == i: return [] max_sum = -1 max_subarr = [] curr = [] curr_sum = 0 while i < n: a = A[i]; i += 1 if a < 0: if curr...
7f63a465f16c90cc3e214132fbc1bbf2d16bb263
darthsuogles/phissenschaft
/algo/leetcode_54.py
2,466
3.515625
4
''' Matrix manipulations ''' def spiralOrderRot(matrix): ''' Take the first row and rotate the rest ''' if not matrix: return [] row = list(matrix.pop(0)) A_rot = list(zip(*matrix))[::-1] return row + spiralOrder(A_rot) def spiralOrder(matrix): if not matrix: return [] m = len...
383cb1ec22f2d455f6ccdda73c096a11677389e0
darthsuogles/phissenschaft
/algo/str_match_one_missing.py
1,069
3.71875
4
''' Match against a dictionary when at most one char can be missing ''' def match_with_missing(query, text): ''' Can delete any number of characters ''' if not query or not text: return 0 m = len(query); n = len(text) i = 0; j = 0 while i < m and j < n: a = query[i]; b = text[j] ...
a654a10139496e204197f4bc6aedbe171f7d3dc2
darthsuogles/phissenschaft
/algo/leetcode_179.py
471
3.921875
4
""" Largest number """ def largestNumber(nums): if not nums: return "" import functools def concat(a, b): return int(str(a) + str(b)) def cmp_fn(a, b): return concat(a, b) - concat(b, a) num_ord = sorted(nums, key=functools.cmp_to_key(cmp_fn), reverse=True) for idx, num in enumerate(num_ord): i...
95974618287b8879d350c457ccef0a12cffcccc4
darthsuogles/phissenschaft
/algo/leetcode_624.py
928
3.546875
4
""" Largest distance """ def maxDistance(arrays): if not arrays: return 0 n = len(arrays) _min, _max = arrays[0][0], arrays[0][-1] excl_min = [None] * n excl_max = [None] * n for i in range(1, n): elems = arrays[i] excl_min[i] = _min excl_max[i] = _max _min = mi...
e31cbc6b810dd3a55e5dccda0f9a68ccd654b135
darthsuogles/phissenschaft
/algo/algebra_ops.py
727
3.65625
4
def compute_fraction(a, b): ''' Compute a fraction representation of a / b ''' tbl = {} # existing solutions for loops s_repr = [] if a > b: s_repr.append(str(a // b)) a = a % b s_repr.append('.') while a != 0: if a in tbl: i = tbl[a] ...
50b9df5ea002d6f3936b900df4a10836386024e4
darthsuogles/phissenschaft
/proj_kleio/research_article.py
5,089
3.5625
4
import logging class Article(object): """ A class representing articles listed on Google Scholar. The class provides basic dictionary-like behavior. """ mandatory_fields = set(['title', 'author', 'id', 'year']) def __init__(self): self.attrs = {} ## Setup logging options ...
b9831a6605c338eb5acd763f05a5b0f0a352d73a
darthsuogles/phissenschaft
/algo/leetcode_617.py
448
3.546875
4
""" Merge Twi Binary Trees """ from lib_arbortem import TreeNode def mergeTrees(t1, t2): def merge(t1, t2): if not t1: return t2 if not t2: return t1 root = TreeNode(t1.val + t2.val) root.left = merge(t1.left, t2.left) root.right = merge(t1.right, t2.right) return r...
10ef8cc79717603c88ce3de3e8000365d96bc64d
darthsuogles/phissenschaft
/algo/leetcode_26.py
277
3.734375
4
''' Remove duplicates ''' def removeDuplicates(nums): if not nums: return 0 n = len(nums) if n < 2: return n i = 1; j = 1 while j < n: if nums[j] != nums[j-1]: nums[i] = nums[j] i += 1 j += 1 return i
e5082d57caeb035a90e24b10f7f089ace6ac74e6
darthsuogles/phissenschaft
/algo/decode_number.py
1,660
3.78125
4
''' Parse number from string (atoi/f) ''' def parse_number(s): if not s: return 0 i = 0 n = len(s) # Skip spaces while i < n: if ' ' != s[i]: break i += 1 # Initial char: '+', '-', '.' or digit ch = s[i] sign = 1 float_i = None if '+' == ch: sign = 1 ...
3bd23001d22e3f39185d61cc11ac828ec8438aca
darthsuogles/phissenschaft
/algo/array_pos_neg_sep.py
443
3.671875
4
''' Separating positive and negative elements O(1) ''' def sep_pos_neg(arr): if not arr: return None n = len(arr) for i in range(n-1, -1, -1): if arr[i] >= 0: continue j = i + 1 for j in range(i+1, n): if arr[j] < 0: break tmp = arr[j-1] arr[j-1] ...
d911ab26998b859b466c8ba034e7c4bd8659e22b
darthsuogles/phissenschaft
/algo/leetcode_301.py
1,679
3.75
4
''' Remove invalid parentheses ''' def rmInvalidOne(s): ''' Using a more direct method ''' if not s: return s stack = [] for i, a in enumerate(s): if '(' == a: stack.append(i) continue if ')' == a: if not stack: # found first extra right ...
e8294150775bf438b0a1132a2247f9833f704758
darthsuogles/phissenschaft
/algo/leetcode_749.py
878
3.84375
4
""" Find shortest word matching license plates """ def shortestCompletingWord(licensePlate, words): wc = [0] * 26 for ch in licensePlate: ch = ch.lower() if ch < 'a' or ch > 'z': continue wc[ord(ch) - ord('a')] += 1 min_word = None for word in words: if min_word is not ...
86994fceedd0e3943c5c0d232839db4b02876461
darthsuogles/phissenschaft
/algo/leetcode_138.py
876
3.515625
4
""" Copy list with random pointers """ class RandomListNode(object): def __init__(self, x): self.label = x self.next = None self.random = None def copyRandomList(head): """ :type head: RandomListNode :rtype: RandomListNode """ if not head: return head node_old2new ...
b64dc1ef603e9d4c33e6ee2ed1b5cd3358dea833
darthsuogles/phissenschaft
/algo/meeting_rooms_ii.py
2,400
3.90625
4
""" Find the minimum number of rooms needed to host all meetings """ def find_min_rooms_stack(meetings): n = len(meetings) if 0 == n: return 0 meetings = sorted(meetings) # This one has good intuitive explanation. import heapq rooms = [] def add_room_with_end_time(v): heapq.heappus...
9ca85c1793958fefe8d8fb155511d341672ee550
GAstraeus/George-Diwan-CS-432-Project-1
/part3.py
338
3.5625
4
def getRandomArray(n): from random import random d = {} i = 0 while i < n: rNum = int(random()*n) if rNum not in d: d[rNum] = 1 i = i + 1 return list(d.keys()) def getSortedArray(n): lst = [] for i in range(n,0,-1): lst.append(i)...
1cb1e4a76f558a25e2d182363035e1021ca52f17
sylguzi/IS211_Assignment7
/pig.py
3,889
3.828125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- """Assignment 7 pig game""" from abc import ABCMeta, abstractmethod import argparse #import sys import random ROLL = 'r' HOLD = 'h' VALID_CHOICE = [ROLL, HOLD] END_OF_GAME_SCORE = 100 random.seed(0) class Die(object): def roll(self): return random.ran...
fc8451f627b353812af93d1feccb05c1c68a155d
fhca/Complejidad2-2020
/redes/ralas.py
766
3.84375
4
__author__ = 'fhca' import networkx as nx # pip3 install networkx import matplotlib.pyplot as plt import matplotlib matplotlib.use('TkAgg') # para que pycharm saque la grafica en ventana nueva def linea(n): "L_{n}, también llamada cadena" G = nx.Graph() #G.add_nodes_from(range(n)) #G.add_edges_from...
9933ff48179b8811cd8279f7aaaaefa5e42e1d17
espehannila/FSDD
/korp/stopwords/stopwords.py
792
3.609375
4
# -*- coding: utf-8 -*- # Stopwords module import os fname = 'stopwords.txt' this_file = os.path.abspath(__file__) this_dir = os.path.dirname(this_file) wanted_file = os.path.join(this_dir, fname) def removeFromStr(str): # remove stopwords from given string u...
b3b4cf0f9c9ad6b03aabbbaae71c194d784c1f51
yotam097/Covid-Project
/covidstats.py
3,609
3.5
4
from selenium import webdriver from webdriver_manager.chrome import ChromeDriverManager import pandas as pd import matplotlib.pyplot as plt def update_data_table(): """ Updating the desirable data (DataFrame type). Takes the official website url as a parameter. """ # Official Ministry Of Healt...
ecef3fb606aac0c54ac9a73c8fabd0267f9626f8
jesshyt/avoidthebin
/test.py
648
3.84375
4
people = [{'food': u'Onion', 'name': 'Jess', 'postcode': u'EC1N 2TD'}, {'food': u'Banana', 'name': u'Ben', 'postcode': u'S12d'}, {'food': u'Cheese', 'name': 'Jess', 'postcode': u'EC1N 3TD'}, {'food': u'Onion', 'name': 'Tom', 'postcode': u'EP18 0FR'}] def getuniquefood(): i = 0 x = [] while i < len(people): if peo...
9b0ce696334f45411565a3b98e96e94801975fc1
Matlmr/Artificial-Intelligence
/recherche/graphe.py
1,538
3.546875
4
from copy import copy class Graphe: """ Graphe non-dirige avec poids sur les arcs """ def __init__(self, noeuds=None, arcs=None): """ :param list noeuds: Une liste de Noeuds :param list arcs: Une liste de paires de Noeuds (sous forme de tuples (a, b, poids)) """ if noeud...
70de1ace3a22ffe3b343d598e51a10523e623879
Tzufung/WebScraping
/Requests/requests_cert.py
373
3.578125
4
# 证书验证 import requests # response = requests.get("https://www.12306.cn") # requests.exceptions.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:749) # response = requests.get("https://www.12306.cn", verify=False) response = requests.get("https://www.12306.cn", cert=("证书路径")) # 导入本地证书 pri...
a444dc3672a658004da6dfd4ad663a708590b03f
jakubkriz/currency_converter
/tests/test_parser.py
1,870
3.5
4
# -*- coding: utf-8 -*- import unittest import argparse import strings from helpers.parser import Parser class TestParser(unittest.TestCase): def test_currency_type(self): # USD must be marked a valid currency type input_str = 'USD' self.assertTrue(Parser.currency_type(input_str)) ...
cd7f873f38105a537b0a8f8f4f3cd511c3d9e811
heman-oliver/chess
/bishop.py
3,141
3.625
4
import pygame from color import Color from constants import SQUARE_SIZE class Bishop(object): def __init__(self, row, col, board): self.row = row self.col = col self.board = board self.side = self.board.chess_board[row][col][0] if self.side == 'w': self.opposite_...
e8486f45b283262ece88299a0459fb41e2d26412
d2525456d/okbrau
/CTDLGT_Python/BT02_UocSoChungLonNhat.py
185
3.5625
4
a = int(input('nhap a = ')) b = int(input('nhap b = ')) def uscln(a, b): if (b == 0): return a; return uscln(b, a % b); print('UCLN của',a,'và',b,'là:',uscln(a,b))
51aea16cd5cd7c145afb94cc4b3c67e95ad22ed1
reeceap124/Graphs
/projects/ancestor/ancestor.py
2,005
4
4
class Stack(): def __init__(self): self.stack = [] self.last = self.size() - 1 def push(self, value): self.stack.append(value) def pop(self): if self.size() > 0: return self.stack.pop() else: return None def size(self): return len(...
36de0afe24d7f7989c4f8664153b6660c421288d
nobregagui/Guicodigo1
/lavarlouça2.py
266
3.703125
4
from random import choice n1 = input('Primeiro nome: ') n2 = input('Segundo nome: ') n3 = input('Terceiro nome: ') n4 = input('Quarto nome: ') lista = [n1, n2, n3, n4] escolhido = choice(lista) print('Quem vai lavar a louça domingão será: {}'.format(escolhido))
20fad477bea2f917b4f972db81c72cab13009495
nobregagui/Guicodigo1
/aula7ex010.py
130
3.71875
4
d = float(input('Digite a sua quantia de dinheiro:')) print('Sabendo que você tem {}R$, você tera {} $'.format(d, (d/5.70)))
03a0fe04b65fb295636c5570371990a622ebcbe6
nobregagui/Guicodigo1
/ex016.py
151
4
4
import math n = float(input('Digite um número: ')) print('Como o seu número desejado é {} o arredondamento dele será {}'.format(n, math.floor(n)))
f90a5e0eb3769dce75e774c6caa095f068ded044
nobregagui/Guicodigo1
/teste.py
631
4.0625
4
nome = str(input('Digite um nome: ')).strip().lower() n1 = print('silva' in nome.lower()) n2 = print(nome[:6].upper() in 'SANTOS') n3 = nome.split() l1 = print('A letra o aparece pela primeira vez em {}'.format(nome.find('o'))) l2 = print('A letra o aparece pela ultima vez na {} posição'.format(nome.rfind('o'))) l3 = p...
8bbad758bde65facb7bfb461291c9614b8c1c938
nobregagui/Guicodigo1
/aula10ex34.py
273
3.734375
4
s = float(input('Digite o seu salário: ')) if s > 1250: print('Parabéns você recebeu um aumento de 10%, seu salário agora é R$: {}'.format((s*0.10)+s)) else: print('Parabéns, vocÊ ganhou um salário de 15%, seu salário agora é R$: {}'.format((s*0.15)+s))
172d7628b6852cedbc94d23a097bb057171577ce
ameyaditya/FaceDetection_FaceRecognition
/test1.1.py
2,837
3.96875
4
#importing the the opencv package here import cv2 #go to C:->Users-><username>->Anaconda3/4->Library->etc->haarcascades #haarcascade is a object detection algorithm mainly used to detect faces eyes etc #we will see how to code our own cascades later #following is an example of face detection algorithm #importing the ...
77d305af26c45a54fd6ba41b7d3aca8c1a44471a
PaulCharp/PyRat-IMT-Atlantique
/Perso/Dijkstra Antoine.py
1,000
3.6875
4
def djikstra(maze_map,initial): """ renvois un couple (distance, table de routage) """ route={initial:[0,None]}#table de routage aVisiter=[(0,initial)]#pile visiter=[] while(aVisiter!=[]):#tant que l'algorithme n'est pas fini neud=heapq.heappop(aVisiter)[1] voisin=...
e42726bbc6d5b5997a035fdc3ad578eb7fd80504
fkdkdsj/tools
/json2csv.py
919
3.640625
4
import sys, os import pandas as pd def json2csv(): try: json_file = input('请输入要解析的json文件名,json文件必须和当前程序同一目录下:') + '.json' if os.path.exists(sys.path[0] + '/' + json_file) == True: data = pd.read_json(json_file, encoding="utf8") # 编码很重要,否则会报到错 else: print('当前目录并没有...
22ac102bad71a22730b3418e042610613ddbbad7
GarvinChanderia/SpiralAnimationTurtle
/Spiral Animation.py
946
3.953125
4
import turtle turtle.bgcolor("black") tur= turtle.Turtle() width = 5 height = 7 dot_distance=25 tur.setpos(-250,250) tur.color("white") def spiral(m,n): k=0 #index of starting row l=0 #index of starting column f=0 while k<m and l<n: if(f==1): tur.right(90) ...
2ab1cb4a2a4cc2be842138c81f8326f38a5f8e17
JeroenKnoops/TextSimilarityProcessor
/test/test_unit.py
3,172
3.796875
4
""" This file does the Unit test of the "Text similarity processor core cosine algorithm """ import unittest from collections import Counter import similarity_processor.similarity_core as cc class MyUnitTestCase(unittest.TestCase): """This class verifies the individual functionality of the units: get_cosine()...
b61c48991d19a24c8a36a74ff4a0c57142625b53
victorhugodias/testePerformance1Python
/exercicio1.py
207
4.09375
4
ajuda = 0 soma = 0 numero = int(input("Digite um número: ")) while ajuda <= numero: if(ajuda % 2 != 0): soma += ajuda ajuda = ajuda + 1 print(f'A soma dos números ímpares são: {soma}')
72713f255bf87fef9ac73836838152df44578406
newcombh5629/CTI110
/P5T2_FeetToInches_HoiNewcomb.py
455
4.25
4
# Write a function named feet_to_inches converts feet to inches # 3/21/2019 # CTI-110 P5T2_FeetToInches # Hoi Newcomb # # conversion rule inches_per_foot = 12 # main function def main(): feet = int(input('Enter a number for feet: ')) # conversion print(feet, 'equal to', feet_to_inches(feet),...
2af4df02d10ea338f714864aa65f20ea0be8b8b3
newcombh5629/CTI110
/P5HW1_RandomNumber_HoiNewcomb.py
1,438
4.34375
4
# Write a program generates a random number range 1 to 100 and ask user to guess a number. # 3/30/2019 # CTI-110 P5HW1 - Random Number # Hoi Newcomb def main(): # allow to use import module import random # generate a random number computer_num = random.randint(1, 100) ...
9fc2440f4f8bacb74ee40ac45091e15f81587179
Irene-Busah/holbertonschool-higher_level_programming-1
/0x0B-python-input_output/5-to_json_string.py
193
3.5
4
#!/usr/bin/python3 """ Function to convert to json string """ import json def to_json_string(my_obj): """ Using json.dumps """ obj = json.dumps(my_obj, sort_keys=True) return obj
e1881b874a1849b1df3cd178a48c7c480b337bbe
Irene-Busah/holbertonschool-higher_level_programming-1
/0x01-python-if_else_loops_functions/8-uppercase.py
291
4.15625
4
#!/usr/bin/python3 def uppercase(str): for char in range(len(str)): if ord(str[char]) >= 97 and ord(str[char]) <= 123: letter = chr(ord(str[char]) - 32) else: letter = chr(ord(str[char])) print("{:s}".format(letter), end="") print("")
c86a2173e87dcb4c66028df577cef5bf2a3f46dc
Irene-Busah/holbertonschool-higher_level_programming-1
/0x0C-python-almost_a_circle/models/square.py
1,447
3.71875
4
#!/usr/bin/python3 """ Class Square """ from models.rectangle import Rectangle class Square(Rectangle): """ Class Constructor """ def __init__(self, size, x=0, y=0, id=None): super().__init__(size, size, x, y, id) @property def size(self): """ Getter for size """ return self.w...
8acbe9ba7f4b40a39617a37b37f6d52da795ae97
Irene-Busah/holbertonschool-higher_level_programming-1
/0x04-python-more_data_structures/0-square_matrix_simple.py
214
3.546875
4
#!/usr/bin/python3 def square_matrix_simple(matrix=[]): square_matrix = [] for spot in range(0, len(matrix)): square_matrix.append(list(map(lambda x: x * x, matrix[spot]))) return square_matrix
aa2a1348a039d4ffaee066e7660c13e38c078cb7
RainbowUnicode/project_euler_genie
/euler_problems/24_euler_lexicographic_permutations.py
722
4
4
""" A permutation is an ordered arrangement of objects. For example, 3124 is one possible permutation of the digits 1,2,3 and 4. If all permutations are listed numerically or alphabetically, we call it lexicographic order. The lexicographic permutations of 0,1, and 2 are 012, 021, 102, 120, 201, 210. What is the mi...
b2273cc6001e9679fb38668b27765077c84a0295
DeviAyyagari/interviewPrep
/recursion/foundation_algos/print_combinations.py
1,602
3.953125
4
""" Problem Statement: Given a set S of n distinct numbers, print all its subsets. Intuition: In the recursive tree, at root node, you choose to either include the element or exclude the element from the subset. There are 2 choices to make for every node at every level. Every node at every ...
69b729da0a8ea2b741eeecb984a8fd6d2bb84542
DeviAyyagari/interviewPrep
/recursion/foundation_algos/factorial.py
711
4.28125
4
""" Compute factorial of any integer Factorial(n) is defined as n(n-1)(n-2).....1 Space complexity: O(n) - At any point in time, there are n activation records on the call stack Time complexity: O(n) - The recursion tree has one node at each level, and there are ...
44c9fd5909d5e9515ee767159321796305fee882
surajkawadkar/vita
/PYTHON/Assignment_1/trigo.py
528
3.734375
4
#python does not support switch case import math print('''S – sin (x) C – cos (x) T – tan (x) X – quit''') choice=input("enter alphabet correspond to operation: ") if choice=='S': x=float(input("enter the number: ")) print(math.sin(x)) elif choice=='C': x=float(input("enter the number: ")) ...
ff0636f08e0a99f16501bb79d896f22b0b107559
surajkawadkar/vita
/PYTHON/Exercise/one_ten.py
2,096
4.46875
4
# 2. Write a Python program to get the Python version you are using. # import sys # print(sys.version) # 3. Write a Python program to display the current date and time. # import datetime # print(datetime.datetime.now()) # 4. Write a Python program which accepts the radius of a circle from the user and compute the ...
e9c737c943ef799c62b536d2e79ddb48a0c6a0c0
surajkawadkar/vita
/PYTHON/Bank.py
2,193
4.25
4
class Bank: account_no=202100 def create_account(self): Bank.account_no+=1 self.accno=Bank.account_no print("Your account created: ",self.accno) self.name=input("Enter name: ") while True: self.amount=float(input("Enter amount to start account: ")) if self.amount<2000: print(...
bf0f4300ce9563b2e2c2eb229e0bc505c50a9d37
surajkawadkar/vita
/PYTHON/Assignment_1/temp_small_program.py
285
3.765625
4
start= int(input()) end= int(input()) for num in range(start,end): temp_num=num power=len(str(num)) sum=0 while(num>0): last_digit=num%10 sum+=last_digit**power num=num//10 if sum==temp_num: print(temp_num,end=',')