blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
3.06M
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
3.06M
d8818472768962f9b25b53298db1103079bdbdda
rzwc/firstroguelike
/venv/entity.py
426
3.671875
4
from typing import Tuple class Entity: """ A generic object to represent players, enemies, items, etc. """ def __init__(self, x: int, y: int, char: str, colour: Tuple[int, int, int]): self.x = x self.y = y self.char = char self.colour = colour def move(self, dx: int...
c2a110d6eb5daca95dc7bd96c496a2f3affd5a48
ericwayman/concourse_ml_workflow_example
/04_pipeline_train_from_data_in_db/dbcredentials.py
1,581
3.828125
4
""" A class to represent the credentials to connect to a postgres database with psycopg2 Credentials are stored in a yaml file with keys: host, port, user, database, password """ import yaml class DBCredentials: def __init__(self,database, host, port, user, password): self.database = database sel...
fa1ba337859a98624867e936d281cf69dfe03df6
Toukir-Hasan/HackerRank_30Days_Python
/day8.py
283
3.65625
4
n=int(input()) d={} f=[] for x in range(n): keys,values=(input().split()) d[keys]=values for y in range(n): z=input() f.append(z) for c in f: if c in d: print(c,end="") print("=",end='') print(d[c]) else: print("Not found")
d79608bb35f40d57ca8483821ac7eab5c6ea3c88
rameezshaik/python
/animal.py
524
3.859375
4
#defining a animal class class animal: def is_aquatic(self): return self.aquatic def get_numberoflegs(self): return self.legs def __init__(self,legs,aquatic,eating_type,bird): self.legs = legs self.aquatic = aquatic self.eating_type = eating_type ...
8ae7109db20182e8e0367a39c03fa9e4dd04dba5
ryanthemanr0x/Python
/Giraffe/Lists.py
561
4.25
4
# Working with lists # Lists can include integers and boolean # friends = ["Kevin", 2, False] friends = ["Kevin", "Karen", "Jim"] print(friends) # Using index friends = ["Kevin", "Karen", "Jim"] # 0 1/-2 2/-1 print(friends[0]) print(friends[2]) print(friends[-1]) print(friends[-2]) print(fri...
6b82f94e0a3149bcb55199f4d3d3d860732aa475
ryanthemanr0x/Python
/Giraffe/if_statements.py
631
4.40625
4
# If Statements is_male = False is_tall = False if is_male or is_tall: print("You are a male or tall or both") else: print("You are neither male nor tall") is_male1 = True is_tall1 = True if is_male1 and is_tall1: print("You are a tall male") else: print("You are either not male or tall or both") i...
aff902fe68cbde48f3f9c98a05733d76f27419d9
cz9025/RF_Script
/RobotKeyworks/fun.py
375
4.03125
4
#coding=utf-8 def add(a, b): try: return int(a)+int(b) except ValueError: raise ValueError("Cannot bu ren shi '%s'and '%s' to an integer." % (a,b)) def extend_to_list(list1, list2): """Adds ``list2`` to the end of ``list1``. """ for value in list2: list1.append(value) ...
0c615e5e57e27148572c3fecd059b89843ec1570
kiyotd/study-py
/src/1_print/main.py
283
3.65625
4
# 文字列のプリント print("test") # test # 変数を使う test = "abc" print(test) # abc # 数値のプリント print(123) # 123 # 数値の計算 print(1 + 2) # 3 print(3 - 1) # 2 print(10 / 2) # 5.0 # 真偽値の出力 print(True) # True print(False) # False
a97dadaf6560e38dafc3078ce3bbc4a849c66431
kiyotd/study-py
/src/6_asterisk/ex1.py
606
4.1875
4
list_ = [0, 1, 2, 3, 4] tuple_ = (0, 1, 2, 3, 4) print(list_) # [0, 1, 2, 3, 4] print(tuple_) # (0, 1, 2, 3, 4) # * # unpack 展開する print(*list_) # 0 1 2 3 4 print(*tuple_) # 0 1 2 3 4 # ** # 辞書などをキーワード引数として渡すことができる my_dict = {"sep": " / "} print(1, 2, 3, **my_dict) # 1 / 2 / 3 print(1, 2, 3, sep=" / ") # と同じ ...
94b27d0f18ccfcf03b102876461e6f1bd74df1d6
realzhengyiming/LocalNews
/LocalNews/tools/setTimeStart.py
984
3.5625
4
#coding=utf-8 #定时开始工作 '''' 这个就是用来设置定时工作的东西的 ,记得服务器的时间比我现在的这儿的时间快两分钟 封装成类 ''' import schedule import time class AutoRunAtTime: def job(self,name): print("her name is : ", name) def startAutoRun(self,timeSet): #24小时制的时间输入 name = "hello" # schedule.every(10).minutes.do(job, n...
ac03c7f898987b2a005722c7aadfcca5d5f4c2d7
realzhengyiming/LocalNews
/LocalNews/tempApplication/sdafs.py
108
3.71875
4
dicta ={'a':"what","b":"about"} if "c" in dicta: print("in inner ") else: print("not in here boy!")
83f7d3333860dac0925592e8a414cd54896795b7
tomreeb/python
/media_copy/media_copy.py
6,165
3.515625
4
#!/usr/bin/env python import os import sys import getopt import readline from shutil import copyfile def main(argv): sourcefile = '' supportedFiletypes = ['mkv', 'avi', 'mp4', 'mov', 'mpg', 'mpeg', 'm4v'] try: opts, args = getopt.getopt(argv, "hm:t:v:f:") except getopt.GetoptError as err: ...
8fac8f5746f6602089739fef0a9e9136d10c9e1c
olavaga/kattis
/modulararithmetic.py
598
3.625
4
#!usr/bin/python3 import sys t = 0 for line in sys.stdin: #print("Evaluating line:", line) if t == 0: #print("t is zero") n, t = line.split() n, t = int(n), int(t) #print("assigned t", t, "and n",n) continue #if t == 0 and n == 0: #print("exiting") # break #print("Splitting line") x, op, y = line...
6f16c2e0ca3a1f7094f2748d01ee9fa8f7d34a55
IrksomeZeus/EmbLin_497
/hw01/etch.py
2,588
3.640625
4
#!/usr/bin/env python # Simple Etch-a-Sketch Program # ECE497 Embedded 32bit Linux @ Rose-Hulman Institute of Technology # Austin Yates Sept. 5, 2016 import curses # initializes the window myscreen = curses.initscr() curses.noecho() curses.cbreak() curses.curs_set(0) x_grid = 8 y_grid = 8 cur_x = 0 cur_y = 0 def ...
812b761e5aacc5c5896a0a2c71cd51b678353cb9
ANnick2908/python-project-lvl1
/brain_games/games/brain_even.py
935
3.828125
4
"""The script of programm brain_even.""" from random import randrange from brain_games.game_logic import logic def instruction(): """Print instruction.""" print('Answer "yes" if number even otherwise answer "no".') def check_even(number): """Check is number even or not. Args: number: numbe...
fdf63a26086cd04efba59c62c57e80ce3873856b
angwhen/factoring
/miller_rabin.py
1,241
3.875
4
import math import random # write n-1 as 2^r*d, d is odd # return r, d def write_as_power_of_two_times_odd_helper(n): d = n-1 r = 0 while d % 2 == 0: d = d/2 r += 1 return r, d # returns True if probably prime, false else def miller_rabin(n, k=5): steps = 0 if n == 1: r...
2d259320a70264f55f837a84741a5a1b2abe6fd5
xhweek/learnpy
/.idea/ly-01.py
525
4.21875
4
#循环打印 #print('* ' * 5) """ for i in range(0,4): for j in range(0,5): print("* ",end=" ") print() """ for i in range(4): for j in range(5): #print(i,"-===========",j) if i == 0 or i == 3 or j == 0 or j == 4: print("* ",end = " ") else: print(" ",end...
ef772cf6033d2ea579ea7eb23351047ade75becc
xhweek/learnpy
/ly-04.py
453
3.5625
4
class student(): def __init__(self,name,age,scores): self.name = name self.age = age self.scores = scores def get_name(self): return self.name def get_age(self): return self.age def get_scores(self): return max(self.scores) if __name__ == '__main__': ...
3e20d0d6ab452b70655c33f5811c112a12df70d2
maxwells-daemons/argsearch
/argsearch/ranges.py
8,701
3.875
4
""" Defines Ranges, which specify how to sample arguments of various types. """ import abc import argparse from typing import List, Union import numbers import random import numpy as np from scipy import stats import skopt def cast_range_argument(arg: str) -> Union[int, float, str]: """ Determine whether a ...
f387bdb1ea2236b7186f01f0fe9f4ba1992c276b
fabiovegar/LLBean_data_science
/Session 2/ejemplo_If.py
437
3.546875
4
pixel= [0.6,0.3,0.4] a=pixel[0]+pixel[1]+pixel[2] n=len(pixel) promedio=a/n print('suma=',a,'n=',n,'promedio=',promedio) #solucion mediante ciclos p=0 for numero in pixel: p+=numero p=p/len(pixel) print('El promedio es',p) #usando sum print('El promedio es:',sum(pixel)/len(pixel)) if(p>0.5): print('el pi...
87db001d1f8c1e047522dd95babf834283bbb305
miangangzhen/MachineLearningTools
/ANNs.py
5,180
3.5
4
#!usr/bin/env python3 # -*- coding:utf-8 -*- from __future__ import division import numpy as np import math np.random.seed(1234) # definition of sigmoid funtion # numpy.exp work for arrays. def sigmoid(x): return 1 / (1 + np.exp(-x)) # definition of sigmoid derivative funtion # input must be sigmoid function's res...
5c02864fb6e1c847a0007eb52b882f9de5ea2a3b
triple6ix/gui_python
/lab2/pyramid.py
1,054
3.765625
4
from card import Card class Pyramid(object): def __init__(self): self.deck_pyramid = [] def right(self, card_numb, row): return card_numb + 1 - row def left(self, card_num, row): return card_num - row def call(self, card_numb): summa = 0 row = ...
41fac57dabe1c3c058e2038232d54bc77110d8f3
twibster/problem-solving
/ras_algorithm_training/day_5/median_of_two_sorted_arrays.py
304
3.515625
4
def findMedianSortedArrays(nums1, nums2): merged = nums1 + nums2 merged.sort() return median(merged) def median(arr): length = len(arr) if length%2 ==0: median = ((arr[length//2] + arr[(length//2)-1])/2) + 0.5 else: median = arr[length//2] return median
ce2769a1f4649b2cd3c69ad6076199c7f1d38bac
twibster/problem-solving
/ras_algorithm_training/day_14/remove_duplicates_from_sorted_list.py
1,101
3.71875
4
class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def deleteDuplicates(self, head): '''this removes any duplicated nodes neglecting any order''' current = head list=[] while current: list.append(curr...
61f9fb1ea03655787531f259d1afc8bdb91668f8
ArmanDashti/My-Personal-Projects
/DS/Stack/stack_reverse_string.py
405
3.859375
4
from stack import Stack def reverse_string(input_str): stack = Stack() for i in range(len(input_str)): stack.push(input_str[i]) rev_str = "" while not stack.is_empty(): rev_str += stack.pop() return rev_str input_str = "Hello" stackx = Stack() stackx.push("a") stackx.push("b") sta...
58297f2780b4ab7590406dec498a96c3a53166c1
ArmanDashti/My-Personal-Projects
/DS/Singly Linked Lists/linked_list.py
8,744
4.03125
4
from node import Node class LinkedList: def __init__(self): self.head = None def print_list(self): current_node = self.head while current_node: print(current_node.data) current_node = current_node.next def append(self, data): new_node = Node(data) ...
e6c308e9b4c6ba71c28748ae49cd630fba1a80e4
ArmanDashti/My-Personal-Projects
/Python Exercises/ex17.py
1,108
3.703125
4
# import the requests Python library for programmatically making HTTP requests # after installing it according to these instructions: # http://docs.python-requests.org/en/latest/user/install/#install import requests # import the BeautifulSoup Python library according to these instructions: # http://www.crummy.com/so...
3d6ac7fa67649c6920b79f7e0fa99edcfd29c7e8
koreshiki/math_with_python
/math_with_python/chap1/ex_gen_multi_table.py
291
3.734375
4
""" Extended generate a multi_table """ def multi_table(a, b): for i in range(1, b + 1): print(f'{a} x {i} = {a * i}') if __name__ == '__main__': a = input('Enter a number: ') b = input('Enter a range number(integer): ') multi_table(float(a), int(b))
6eaa36cd81b91d28af5a008c618c423ea150e800
koreshiki/math_with_python
/math_with_python/chap1/judge_number.py
636
3.8125
4
import sys def judge_number(number): return number % 2 if __name__ == '__main__': num = input('Enter a integer: ') judge = 0 if not num.isdigit(): print('Oops! Error occurred.\n' 'Input a integer please.') sys.exit(1) if judge_number(int(num)): ...
24e5a9a3924942c27eb26a3bf84211a93b05bf8f
ikramsalim/DataCamp
/03-data-manipulation-with-pandas/1-transforming-data/sorting-rows.py
746
3.984375
4
# Sort homelessness by individual homelessness_ind = homelessness.sort_values("individuals") # Print the top few rows print(homelessness_ind.head()) # Sort homelessness by descending family members homelessness_fam = homelessness.sort_values("family_members", ascending= False) # Print the top few rows print(homeless...
be09d834d00440c8f2062b02e58ed9e36e3d7822
ikramsalim/DataCamp
/03-data-manipulation-with-pandas/1-transforming-data/adding-new-columns.py
576
3.859375
4
""" Add a new column to homelessness, named total, containing the sum of the individuals and family_members columns. Add another column to homelessness, named p_individuals, containing the proportion of homeless people in each state who are individuals. """ # Add total col as sum of individuals and family_members homel...
9e0a944f2100cab01f4e4cad3921c8786998681b
ikramsalim/DataCamp
/02-intermediate-python/4-loops/loop-over-lists-of-lists.py
446
4.25
4
"""Write a for loop that goes through each sublist of house and prints out the x is y sqm, where x is the name of the room and y is the area of the room.""" # house list of lists house = [["hallway", 11.25], ["kitchen", 18.0], ["living room", 20.0], ["bedroom", 10.75], ["bathroom", ...
e520799aa77f8aa32e725d800733d762897840b6
BairnOwl/hacktim2017
/createSmallDB.py
1,438
3.609375
4
#!/usr/bin/env python3 import sqlite3 import csv import sys def create(database): conn = sqlite3.connect(database) c = conn.cursor() # Delete table if already exists c.execute('DROP TABLE IF EXISTS "food";') c.execute('PRAGMA foreign_keys = ON;') # Create tables c.execute('''CREATE T...
37a0c4ddaf6cb6db2ebf699a4d1b092d41a42249
ycayir/python-for-everybody
/course1/week5/ex_05_02.py
355
4.0625
4
min = None max = None while True: entry = input('Enter a number: ') if entry == 'done': break try: num = int(entry) if min is None or min > num: min = num if max is None or max < num: max = num except Exception as e: print('Invalid input')...
dcf1b439aa3db2947653f9197e961d4969f92095
ycayir/python-for-everybody
/course2/week5/ex_09_05.py
782
4.25
4
# Exercise 5: This program records the domain name (instead of the # address) where the message was sent from instead of who the mail came # from (i.e., the whole email address). At the end of the program, print # out the contents of your dictionary. # python schoolcount.py # # Enter a file name: mbox-short.txt # {'med...
8731539c4e2200e9272ea6cbdd46e71da461d47b
ycayir/python-for-everybody
/course1/week5/ex_05_01.py
324
3.96875
4
count = 0 total = 0 avg = 0 while True: entry = input('Enter a number: ') if entry == 'done': break try: total = int(entry) + total except Exception as e: print('Invalid input') continue count = count + 1 if count != 0: avg = total / count print(total, count, a...
d6d92b24d4c0026416a0d3e21e89319b709193fe
erkantacli/Python
/Snake/SSP.py
3,191
3.671875
4
import random import sys #Falscheingaben mö def zahl_einlesen(text, min, max): while True: try: zahl = int(input(text)) if zahl < min or zahl > max: print("-> ungültige Eingabe!") continue return zahl except: print("-> ...
714272fe0f36c2a2bd36a8b787a144df88978021
GreekPanda/leetcode
/Search/Search2DMatrixII/Search2DMatrixII.py
468
3.59375
4
class Solution: def search2DMatrixII(self, matrix, target): if matrix is none or matrix[0] is none: return occur = 0 row, col = 0, len(matrix[0]) - 1 while row < len(matrix) and col >= 0: if matrix[row][col] == target: col -= 1 ...
68733e159e98cd60a6d1954a31d909f287468cf6
GreekPanda/leetcode
/String/RotateString/RotateStr.py
796
3.671875
4
class RotateStr: def rotateString(self, s, offset): if s is none and len(s) == 0: return offset %= len(s) self.reverse(s, 0, len(s) - offset -1) self.reverse(s, len(s) - offset, len(s) - 1) self.reverse(s, 0, len(s) - 1) def rev...
b2de3ea0da2e9be24b02c488df0a4575875de8b0
GreekPanda/leetcode
/Tree/BinarySearchTreeIterator/BinarySearchTreeIterator.py
584
3.6875
4
""" class TreeNode: def __init__(self, v): self.val = v self.left, self.right = None, None """ class BSTIterator: def __init__(self, s, root): self.stack = s self.curr = root def hasNext(self): return (curr && stack) def next(self) ...
d06636d80ad26369d00f037053485ee540ca0f37
GreekPanda/leetcode
/List/Add2Numbers/Add2Numbers.py
798
3.5625
4
""" class ListNode: def __init__(self, val): self.val = val self.next = None """ class Solution(object): def add2Number(self, lst1, lst2): if lst1 is None or lst2 is None: return None carry = 0 dummy = prev = ListNode(-1) wh...
8115392c76bc10addce027f36d95057f29df63d5
namansolanki549/LeetCodeDSA
/Longest Common Prefix.py
883
3.859375
4
# Write a function to find the longest common prefix string amongst an array of strings. # If there is no common prefix, return an empty string "". # Example 1: # Input: strs = ["flower","flow","flight"] # Output: "fl" # Example 2: # Input: strs = ["dog","racecar","car"] # Output: "" # Explanation: There is no c...
2454b3698f8ca1d05861ffabaada65a7a35e51d7
aflyk/hello
/pystart/lesson1/l1t6.py
1,226
4
4
""" Спортсмен занимается ежедневными пробежками. В первый день его результат составил a километров. Каждый день спортсмен увеличивал результат на 10 % относительно предыдущего. Требуется определить номер дня, на который результат спортсмена составит не менее b километров. Программа должна принимать значения парам...
5cdde586e393bf88e33c829f3b16e98a36b57250
aflyk/hello
/pystart/lesson1/l1t3.py
335
4
4
""" Узнайте у пользователя число n. Найдите сумму чисел n + nn + nnn. Например, пользователь ввёл число 3. Считаем 3 + 33 + 333 = 369. """ user_num = input("Введите число\n>>>") print(int(user_num) + int(user_num * 2) + int(user_num * 3))
a3d29efc3635b2739d6027f115bc1044b3087be6
aflyk/hello
/pystart/lesson4/l4t5.py
616
3.984375
4
""" Реализовать формирование списка, используя функцию range() и возможности генератора. В список должны войти четные числа от 100 до 1000 (включая границы). Необходимо получить результат вычисления произведения всех элементов списка. Подсказка: использовать функцию reduce(). """ from functools import reduce...
3b001335c93162c45bd9d5f26714a9d43ffff842
aflyk/hello
/pystart/lesson6/l6t5.py
1,702
4.0625
4
""" Реализовать класс Stationery (канцелярская принадлежность). Определить в нем атрибут title (название) и метод draw (отрисовка). Метод выводит сообщение “Запуск отрисовки.” Создать три дочерних класса Pen (ручка), Pencil (карандаш), Handle (маркер). В каждом из классов реализовать переопределение метода draw. ...
16d0cc5afda917ebc335553cc6d338014b19f87b
aflyk/hello
/pystart/lesson1/l1t2.py
467
4.4375
4
""" Пользователь вводит время в секундах. Переведите время в часы, минуты и секунды и выведите в формате чч:мм:сс. Используйте форматирование строк. """ user_time = int(input("Введите кол-во секунд: ")) user_time = user_time % (60*60*24) print(f"{user_time // 3600}:{(user_time % 3600) // 60}:{(user_time % 3600)...
170fd62e5345d7da108030620b1b81ece949b0bc
aflyk/hello
/pystart/lesson3/l3t4.py
1,754
3.578125
4
""" Программа принимает действительное положительное число x и целое отрицательное число y. Необходимо выполнить возведение числа x в степень y. Задание необходимо реализовать в виде функции my_func(x, y). При решении задания необходимо обойтись без встроенной функции возведения числа в степень. """ def my_f...
254210227b8c1c1ce4ddca88fb6a889a1c0e7c47
aflyk/hello
/pystart/lesson6/l6t2.py
1,224
4.3125
4
""" Реализовать класс Road (дорога), в котором определить атрибуты: length (длина), width (ширина). Значения данных атрибутов должны передаваться при создании экземпляра класса. Атрибуты сделать защищенными. Определить метод расчета массы асфальта, необходимого для покрытия всего дорожного полотна. Использовать фор...
95595060e5c7e825c3e3362f9823605a8d79b03e
KeithChesterHCM/regex-cantrip
/regexample2.py
438
3.828125
4
# regexample2.py import sys, re # Consume parameters if len(sys.argv) <= 1: print "Error: No pattern found." print "Usage: python regexample2.py <pattern>" sys.exit(0) pattern = sys.argv[1] print pattern regEx = re.compile(pattern) # create regEx object # begin parsing from stdin for i,line in enumerate(sys.s...
47a92e2a5e9c2cd681b5479ab76db16674f9085a
insanecheck/cpy5C23python
/02_practical/q04_determine_leap_year.py
239
3.859375
4
r = int(input("Enter year: ")) if r % 400 == 0: print("Leap year.") elif r% 4 == 0: if r% 100 == 0: print("Non-leap year.") else: print("Leap year.") print() #Acknowledgements print ("\u00A9"+" Neo Wei Lu 2013")
6e2428974237fab9792198b467163aa2e3bf497a
gananPrabaharan/spending-dashboard
/flask_app/services/date_utilities.py
401
3.59375
4
from datetime import datetime, timedelta import pandas as pd def get_week_start(dt): return dt - timedelta(days=dt.weekday()) def get_month_start(dt): return dt.replace(day=1) def add_dates_to_df(df): df["date"] = pd.to_datetime(df['date']) df["week"] = df["date"].apply(lambda x: get_week_start(x)...
647d96f29277cbc895645cbb1016a520e7541091
stompydragons/stompy-learns
/03_PythonFundementals/airtravel.py
6,152
4.0625
4
"""Model for aircraft flights""" class Flight: def __init__(self, number, aircraft): """A flight with a particular passenger aircraft aircraft.""" if not number[:2].isalpha(): raise ValueError("No airline code in '{0}'".format(number)) if not number[:2].isupper(): ...
f0b56852ecda5adcf7c0a1414911930119b8c10a
CPSC-481-Project/Project-1
/wolfgoatcabbage_fancyprint.py
6,467
3.5625
4
from search import * # Constructor setting initial and goal states class WolfGoatCabbage(Problem): # (F, W, G, C) def __init__(self, initial_state, goal=(1, 1, 1, 1, False)): super().__init__(initial_state, goal) # False --> boat is moving back to the right # True --> boat is moving t...
78698ff6ff846dc59b9cbf1c233658a070984c62
sarahmbaka/py_data_structures_and_algorithms
/challenges/multi_bracket_validation/multi_bracket_validation.py
819
4.0625
4
from ...data_structures.stack.stack import Stack def multi_bracket_validation(string): """Check the brackets to be balanced""" stack = Stack() counter = 0 for element in string: if element == '(' or element == '{' or element == '[': stack.push(element) counter += 1 ...
371fcd940f306ff40a84be036fb6c1a9b05da89c
luca2849/CM1103-Problem-Solving-With-Python
/doomsday.py
581
3.9375
4
year = int(input("Enter a year between 1800 and 2199 >>")) if year in range(1800, 2200): if year in range(1800, 1900): x = 5 elif year in range(1900, 2000): x = 3 elif year in range(2000, 2100): x = 2 else: x = 0 year = str(year) w = year[2:4] w = int(w) a = w // 12 b = w % 12 c = b /...
c3c1bf04376f728f6470a055e56c878ceec2d3b3
mjdall/leet
/spiral_matrix.py
2,106
4.1875
4
def spiral_order(self, matrix): """ Returns the spiral order of the input matrix. I.e. [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ] becomes [1, 2, 3, 6, 9, 8, 7, 4, 5]. :type matrix: List[List[int]] :rtype: List[int] """ if not matrix or matrix is None: return ...
3dd6609f9805f7c8bbf9949b56584a2c044475a3
mjdall/leet
/count_elements.py
668
4.28125
4
def count_elements(arr): """ Given an integer array arr, count element x such that x + 1 is also in arr. If there're duplicates in arr, count them seperately. :type arr: List[int] :rtype: int """ if arr is None or len(arr) == 0: return 0 ...
519796c0837f512d18e7a1047aaea23fb1276ee4
mjdall/leet
/easy/remove_duplicates.py
956
4
4
def remove_duplicates(nums): """ Remove duplicates in place, nums is sorted w/possible duplicates. Return int denoting the length of sorted elements in nums. :type nums: List[int] :rtype: int """ if not nums: return 0 # the n...
5cc4750c2af5cafb8a97777872c8a14c25792ddb
ogrobass/meusEstudos
/CursoPythonCoursera/MinMax.py
1,632
3.9375
4
def MinMax(temperatura): print("A menor temperatura do mês foi: ", minima(temperatura), " C.") print("A maior temperatura do mês foi: ", maxima(temperatura), " C.") def minima(temps): min = temps[0] i = 1 while i < len(temps): if temps[i] < min: min = temps[i] i = i +...
f5469639ac5e526ac810d5744797793b9cc95809
denemorhun/Python-Problems
/Hackerrank/Strings/find_all_permutations_of_substring.py
745
4.0625
4
''' Find all permutations, O(n!), for a string of unique characters such as abcdefgh -> a -> ab, ba -> insert c into all positions -> merge ( (cab, acb, cab), (cba), (bca), (bac) ) Basic approach: Base case: Remove characters recursively from input string until last character no need to pop anymore ...
3cd23d2322b4da29f965da4ee61b74fb510973d8
denemorhun/Python-Problems
/Grokking the Python Interview/Data Structures/Trees/check_if_trees_equal.py
912
3.78125
4
class BinaryTreeNode(): def __init__(self, data): self.left = None self.right = None self.data = data def are_identical(root1, root2): if root1 is None and root2 is None: return True if root1 and root2: # base case, left children, right children return ...
334da6ffae18a403cc33ae03c1600238a6a45ddd
denemorhun/Python-Problems
/Hackerrank/Strings/MatchParanthesis-easy.py
1,891
4.40625
4
# Python3 code to Check for balanced parentheses in an expression # EASY ''' Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. An input string is valid if: Open brackets must be closed by the same type of brackets. Open brackets must be closed in...
bb708c316a2f7041f23c61036ff825153ad424a2
denemorhun/Python-Problems
/Grokking the Python Interview/Data Structures/Stacks and Queues/q_using_stack.py
1,149
4.21875
4
from typing import Deque from stack import MyStack # Push Function => stack.push(int) //Inserts the element at top # Pop Function => stack.pop() //Removes and returns the element at top # Top/Peek Function => stack.get_top() //Returns top element # Helper Functions => stack.is_empty() & stack.isFull() //returns...
a34383ee463d3c9749caf0e52c10e3e114fe02a7
denemorhun/Python-Problems
/AlgoExperts/LinkedList/remove_duplicates_from_linked_list.py
1,693
4.15625
4
''' A Node object has an integer data field, , and a Node instance pointer, , pointing to another node (i.e.: the next node in a list). A removeDuplicates function is declared in your editor, which takes a pointer to the node of a linked list as a parameter. Complete removeDuplicates so that it deletes any duplic...
07bab891b92ca248e39056da104d2a9afdff953c
denemorhun/Python-Problems
/Hackerrank/Arrays/validate_pattern.py
1,708
4.34375
4
'''Validate Pattern from array 1 to array b Given a string sequence of words and a string sequence pattern, return true if the sequence of words matches the pattern otherwise false. Definition of match: A word that is substituted for a variable must always follow that substitution. For example, if "f" is substituted ...
082af15b90fcddb04798fb0dfffd20fa5687fa74
denemorhun/Python-Problems
/Hackerrank/Arrays/2D_array_tricks.py
496
3.625
4
''' 2 dimensional array tricks''' arr = [(1750, 1800), (1990, 2000) , (1840, 1880), (1850, 1890), (1900, 1970), (1905, 1985)] running_sum = 0 arr = sorted(arr) years = {} # print birth and death in tuples # for i in arr: # print(i) #print only the birth years for i in arr: print("birth occurred", i[0]) ...
58ef741a09f738a13b45307456e9473b59187c48
denemorhun/Python-Problems
/Hackerrank/Arrays/min_number_of_swaps_INCOMP.py
515
3.984375
4
''' find the minimum number of swaps required to sort the array in ascending order. HARD. * Don't need to actually sort the array, counting swaps suffices. ''' def find_min_num_swaps(a): pass # Driver Code if __name__ == '__main__': a1 = [-6, -5, -1, 0, 5, 8] a2 = [9, 2, 8, 5] a3 = ...
7d58235629bdaceb57f005dde6376976773e1189
denemorhun/Python-Problems
/Leetcode/FB/Trees and DFS/level_averages.py
2,414
3.984375
4
''' Task Calculate the average of every level in a tree 4 -> 4 / \ 6 10 -> 16 / 2 = 8 \ 2 -> 2 # calculate the average at every level. ''' # This is the class of the input root. Do not edit it. class BinaryTree: def __init__(self, value): ...
c5d07ed142dcd22413e18a7f07f534b52235729a
denemorhun/Python-Problems
/Grokking the Python Interview/Data Structures/Lists/Find_2nd_max.py
563
3.9375
4
# find the 2nd max number in an array # sorting will not work if there are duplicates def find_2nd_max(a): # traverse list and find max m max_n = float('-inf') max_2 = float('-inf') # O(n) for num in a: if num > max_n: max_n = num print('max_n', max_n) # O(n) for...
075cfe2444539fbfa9a166ceda70d6107b07ec78
denemorhun/Python-Problems
/Hackerrank/Recursive and DP/number_of_ways.py
634
3.84375
4
''' Find the number of ways you can partition n objects using parts upto m. m > 0 ''' def waze(n, m): # if our chunk is larger than actual object, limit it to object size # if m > n: # m = n # base case if n == 0: return 1 # if n < m case elif m == 0 or n < 0: return 0 ...
aec5a907e0913a40e14022dd3d3103c51ae47d65
denemorhun/Python-Problems
/Hackerrank/Arrays/maximum_abs_difference.py
310
4
4
''' find the maximum absolute difference between values array ''' def max_abs_difference(numbers) -> int: # sort the array numbers = sorted(numbers) size = len(numbers) max_diff = abs(numbers[size-1] - numbers[0] ) return max_diff print(max_abs_difference([2, 4, 5, -9, 0, 4]))
e2933057bcb3110c24bf4685991e40b3843730c6
denemorhun/Python-Problems
/Hackerrank/Arrays/twosumlessthanK.py
1,274
3.53125
4
''' Two Sum Less Than K ' Given an array A of integers and integer K, ' return the maximum S such that there exists i < j ' with A[i] + A[j] = S and S < K. ' If no i, j exist satisfying this equation, return -1. def twoSumLessThanK(A, K): ans = -1 if len(A)==1: return -1 for i in rang...
bafa978bbb719437cd0d4382d5ecd2a8084ebed0
denemorhun/Python-Problems
/Hackerrank/Arrays/separate_odd_even.py
561
4.0625
4
''' Given an array-  divide odd and even numbers ''' import collections import os import datetime import sys from collections import Counter def divide_even_odd(numbers): if numbers is None: return None list_even = [] list_odd = [] for number in numbers: if number % 2 == 0: ...
b71c6f9a9a72490b983864c8a7f7ccd48ffbc431
denemorhun/Python-Problems
/Leetcode/FB/DP/coin_denom_recursive_dp.py
2,118
3.703125
4
#!/bin/python3 ''' Medium: Calculate the number of ways using DP whether or not target money can be obtained using a denomitor. ETC: 10$ -> denoms{1, 2, 5} ''' def canGetExactChange(n, denoms): print(denoms, "target ->", n) # init array with 0, to return 0 if no denoms are found waze = [0]*(n+1) ...
2e2960d3dee3d05d4b958889c95c81999a8ab51d
denemorhun/Python-Problems
/Grokking the Python Interview/Data Structures/Stacks and Queues/implement_postfix.py
918
3.65625
4
from typing import Type def evaluate_post_fix(string): stack = [] try: for i in string: # if number append to stack if i.isdigit(): stack.append(i) # skip spaces elif i == ' ': continue # if operator is enc...
2849482ebdc30c6f2468b7fd6c3c0bcf48eb3ce4
Agc96/matplotlib-examples
/05-tramas/userinput.py
3,378
3.84375
4
# -*- coding: utf-8 -*- """ Permite el ingreso y visualización de puntos en matplotlib. Si el código se ha ejecutado con anterioridad, permite la opción de usar los puntos declarados anteriormente. """ import os import numpy as np import matplotlib.pyplot as plt def clear_screen(): """ Limpia la terminal. ...
ff9ab4790d40fde9ce2de78bb69f4c994ef954f6
Ilya04P/lesson2
/if_statement_age.py
441
3.984375
4
user_age = int(input('Введи свой возраст: ')) if 0 < user_age < 7: print('Ходишь в детский сад') elif 7 <= user_age < 18: print('Учишся в школе') elif 18 <= user_age < 24: print('Учишся в ВУЗе') elif 24 <= user_age: print('Работаешь') if user_age >= 65: print('ПФР нужны твои деньги') else: ...
40c96b10168f806793f51dad0df58ab6c7e4db46
OzRhodes/Hackerrank
/guessinggame.py
492
4.0625
4
#guessinggame.py import random def guess(guessed_num, answer): if guessed_num > answer: response = 'The number is lower.\n' else: response = 'The number is higher.\n' return response answer = str(random.randint(1,20)) guessed_num = '' while True: guessed_num = input('Enter your Guess...
78e495bb627b8b2346e1517e1714a3fa49c6618e
OzRhodes/Hackerrank
/orderedDict.py
794
3.6875
4
''' test list shopping_list = [['BANANA FRIES', 12],['POTATO CHIPS', 30],['APPLE JUICE', 10],['CANDY', 5],['APPLE JUICE', 10],['CANDY', 5],['CANDY', 5],['CANDY', 5],['POTATO CHIPS', 30]] ''' # Enter your code here. Read input from STDIN. Print output to STDOUT from collections import OrderedDict my_dict = Ordere...
6cc49fc24f0db67a8becdf9acd1a13403831b011
OzRhodes/Hackerrank
/taumBday.py
819
3.828125
4
#taumBday.py # Complete the 'taumBday' function below. # # The function is expected to return a LONG_INTEGER. # The function accepts following parameters: # 1. INTEGER b number of b # 2. INTEGER w number of w # 3. INTEGER bc cost of b # 4. INTEGER wc cost of w # 5. INTEGER z cost of conversion def taumB...
23e2780f387aac1184565427fab26fa6d215c6fe
Fernandarangel23/Activities
/Week 3/Activities/Activity2_CreateVariable.py
207
3.578125
4
name ="Fernanda" country = "Mexico" age = 24 hourly_wage = 200 satisfied = True daily_wage = hourly_wage*8 print(name + country + str(age) + str(hourly_wage)) print(str(daily_wage) + str(satisfied))
1ab018e86da609e330d7dcaba6d74f3ae1c36466
herrsommer7894/Shell-Perl-exercises-comp9041
/lab06/digits.py
307
3.8125
4
#!/usr/bin/python import sys for line in sys.stdin: for word in line: if word.isdigit(): c=int(word) if c>5: line=line.replace(word,'>') if c<5: line=line.replace(word,'<') line=line.strip('\n') print(line)
7ff5903c490ef8c34099db9252ec42918f2e850b
tcano2003/ucsc-python-for-programmers
/code/lab_03_Functions/lab03_5(3)_TC.py
1,028
4.46875
4
#!/usr/bin/env python3 """This is a function that returns heads or tails like the flip of a coin""" import random def FlipCoin(): if random.randrange(0, 2) == 0: return ("tails") return ("heads") def GetHeads(target): """Flips coins until it gets target heads in a row.""" heads = count = ...
8188da57fa12bb1312f0548279e7d34e47d50629
tcano2003/ucsc-python-for-programmers
/code/lab_12_Function_Fancies/lab12_2py3.py
661
4.0625
4
#!/usr/bin/env python3 """ lab12_2.py Write a function that receives a dictionary as an argument, and returns a tuple of two formatted strings. """ def FormatEvent(event_d): """Returns two strings for the event: one formatted for a calendar, one formatted for an invitation. """ calendar = "%(date)s...
3feb1cf94654818093c6f6bae2b3941527c0a5c8
tcano2003/ucsc-python-for-programmers
/code/lab_15_New_Style_Classes/circle_iterpy3.py
1,486
3.90625
4
#!/usr/bin/env python3 """(Optional) Here is the other way to make an iterator, from scratch.""" import new_style_circle_defpy3 as new_style_circle_def class IterCircle(new_style_circle_def.Circle): def __iter__(self): #generator function returns CircleIter(), has a next() in it """Returns an object that...
3b1315a4ffacc91f29a75daa3993a1cb2aab4133
tcano2003/ucsc-python-for-programmers
/code/lab_03_Functions/lab03_6(3).py
2,442
4.46875
4
#!/usr/bin/env python3 """Introspect the random module, and particularly the randrange() function it provides. Use this module to write a "Flashcard" function. Your function should ask the user: What is 9 times 3 where 9 and 3 are any numbers from 0 to 12, randomly chosen. If the user gets the answer right, your f...
16bd53fbe7ac8af81fe30e937697b435de741420
tcano2003/ucsc-python-for-programmers
/code/lab_12_Function_Fancies/lab12_5py3_TC.py
1,343
3.671875
4
#! /usr/bin/env python3 """ Testing dice.py by reading it as a text file, making a little change, and then executing it, via the exec command. """ import sys, os def GetDiceCodeString(): """Read the dice.py file as text and change random.randrange to be doubles_generator_object.next(), and return the text. ...
95f9b18709523da0efce57a02d030475e236efb8
tcano2003/ucsc-python-for-programmers
/code/lab_03_Functions/lab03_5.py
927
4
4
#!/usr/bin/env python3 """Coin flip Experiments, continued. """ from __future__ import division import random def FlipCoin(): """Simulates the flip of a coin.""" if random.randrange(0, 2) == 0: return "tails" return "heads" def GetHeads(target): """Flips coins until it gets target heads in a ...
c0c4afc7439ff9ec1349fb27b17025206178cef5
tcano2003/ucsc-python-for-programmers
/code/lab_02_Input/paint(3).py
867
4.03125
4
#!/usr/bin/env python3 """Demonstrates formatted output, and both uses of '%' 1. string replacement 2. modulo """ PER_GALLON = 200 # A can of paint covers 200 square feet sq_ft = 0 while sq_ft == 0: said = input("Number of square feet to paint: ") if not said: # or if said == '': (This is false) ...
008fa26d54dc77f783b3b60f5e2f85c83535a3fd
tcano2003/ucsc-python-for-programmers
/code/lab_14_Magic/circle_defpy3.py
1,823
4.1875
4
#!/usr/bin/env python3 """A Circle class, acheived by overriding __getitem__ which provides the behavior for indexing, i.e., []. This also provides the correct cyclical behavior whenever an iterator is used, i.e., for, enumerate() and sorted(). reversed() needs __reversed__ defined. """ #need to have def __getitem__(<...
b85ec44dd8818f07225766d707a3fec0916b9d74
kamathrohan/Complexity
/Project/complexity.py
6,664
3.5
4
""" Complexity Project 2018/19. R.K. Kamath 01209729 rkk216@ic.ac.uk """ import numpy as np #some obvious imports import matplotlib.pyplot as plt #from progressbar import ProgressBar class aval: """ Initialise a system with a length L """ def __init__(self, length): self.z = np.zeros(length) ...
dc4b6a662154b72ca7bb8a90ab7862dfd757d48d
ilieandrei98/labs
/python/solutii/monica_vizitiu/tree/tree.py
597
3.5625
4
#!/usr/bin/env python # *-* coding: UTF-8 *-* """Problema tree.""" from __future__ import print_function import os import os.path def tree(director, nivel): """Tree""" linii = "-" linii = linii * nivel lista = os.listdir(director) print(linii + director) for fis in lista: fpath = os.p...
182bd0c6f38c619fb4d82dc353f0581fec3cdf36
ilieandrei98/labs
/python/solutii/alin_corodescu/tree/tree.py
491
3.640625
4
#!/usr/bin/env python # *-* coding: UTF-8 *-* """ Utilitar ce imita "tree" """ import os import sys def tree(path, tabs): """afiseaza folderul ca structura tree""" print "--" * tabs, path.split("/")[-1] for name in os.listdir(path): pathabs = os.path.join(path, name) if os.path.isfile(pa...
1c946011c86ee6d1a0be6a4006606987a72aeaab
ilieandrei98/labs
/python/solutii/cristina_ungureanu/paint/cursor.py
1,334
4.03125
4
#!/usr/bin/env python # *-* coding: UTF-8 *-* """Stabileste distanta si pozitia fata de origine.""" from __future__ import print_function import math def este_instructiune(instr): """Stabileste daca este instructiune.""" dictionar = {'STANGA', 'DREAPTA', 'SUS', 'JOS'} return instr in dictionar def dis...
1e9c6fec7daaf399363926f3f86fe9691e1bbfaf
ilieandrei98/labs
/python/solutii/micu_matei/paranteze/paranteze.py
1,751
3.703125
4
#!/usr/bin/env python # *-* coding: UTF-8 *-* """Tuxy scrie în fiecare zi foarte multe formule matematice. Pentru că formulele sunt din ce în ce mai complicate trebuie să folosească o serie de paranteze și a descoperit că cea mai frecventă problemă a lui este că nu toate parantezele sunt folosite cum trebuie. Pentru...
2c5d385d8eaabe68be13843619829a3e86e62807
ilieandrei98/labs
/python/solutii/iulian_andrei/paint/cursor.py
1,806
3.5625
4
#!/usr/bin/env python # *-* coding: UTF-8 *-* """Tuxy dorește să împlementeze un nou paint pentru consolă. În timpul dezvoltării proiectului s-a izbit de o problemă pe care nu o poate rezolva singur și a apelat la ajutorul tău. Aplicația ține un istoric al tuturor mișcărilor pe care le-a făcut utlizatorul în fișieru...
884e18d38cdebad298e03dd8c2462f535dfb93c3
ilieandrei98/labs
/python/solutii/alin_corodescu/paranteze/paranteze.py
1,699
3.578125
4
#!/usr/bin/env python # *-* coding: UTF-8 *-* """Tuxy scrie în fiecare zi foarte multe formule matematice. Pentru că formulele sunt din ce în ce mai complicate trebuie să folosească o serie de paranteze și a descoperit că cea mai frecventă problemă a lui este că nu toate parantezele sunt folosite cum trebuie. Pentru...
780104b6150ecac31d823afa576abc39ef7ac8f8
ilieandrei98/labs
/python/solutii/stefan_caraiman/tree_representation.py
772
3.921875
4
""" Represent a directory as a tree """ from __future__ import print_function import os def rtree(mdirectory, depth): """ Display a tree :param mdirectory: the main directory :param depth: the depth from where we start :return: prints the whole tree """ files_in_dir = os.listdir(mdirector...
7d0c716e7fe0b87f1b897c7f6d111b4d4587bf8c
lamb003/advent-of-code
/2020/3/day3.py
1,643
3.546875
4
from dataclasses import dataclass import math TREE = "#" OPEN = "." @dataclass class Position: x: int y: int @dataclass class MovementPatern: dy: int dx: int def get_value_from_map(_map: list, location: Position) -> str: try: row = _map[location.y] value = row[location.x] ...