blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
0b1adfa9f65f769f0cba3d76d315d8f1dfbd7c1c
XYangL/CodeJam
/visitTree_ Iterative.py
1,749
4.09375
4
from TreeNode import TreeNode # http://www.gocalf.com/blog/traversing-binary-tree.html # Using iterative/loop to traverse tree in pre/in/post order # need a STACK to store the visited but not printed nodes def visitTree_Iterative(root, order): re = [] if order == 'NLR': # init a stack with root # use a while loo...
d4020ee668ea0b58fa993905662b6ebf65f97a4b
JZ1015/NetworkBandwidthMonitor
/animation.py
994
3.5
4
import pandas as pd import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as ani fig=plt.figure() def animate(i): data=open('monitor.txt','r').read() #file reader dataArray=data.split('\n') #data manipulation, split DateTime=[] #data structure list sent=[] rev=[] for ...
921416a4189a9d91235e3627cba1c58962bf3f04
muhammadhasan01/cp
/Online Judge/TLX/Pemrograman Dasar/5 - If Then Multi.py
52
3.65625
4
a = int(input()) if a > 0 and a%2 == 0: print(a)
bee2e28bd51ee3f7b0390071885856b7ea9801c4
feladie/D04
/HW04_ch08_ex05.py
776
4.3125
4
# Structure this script entirely on your own. # See Chapter 8: Strings Exercise 5 for the task. # Please do provide function calls that test/demonstrate your # function. '''Returns the word with each of its characters rotated n times.''' def rotate_word(word, n): result = '' # Result string for letter in word: new...
cdfc3b709c47a12f60a4a2b221e16b0e8b60d6d3
Kamilla23072001/Lab1
/7.4.py
402
3.546875
4
import random num = random.randint(1,10) while True: tryes = int(input('Введите число:')) if tryes == num: print('Победа') break else: print('Повторите еще раз') """Прогрмма загадывает случайное число лт 1 до 10 и дает пользователю его отгадать"""
13d1c9228ee1b4412d77e0c517b5977dd7cf79eb
adamrodger/google-foobar
/3-3.py
837
3.796875
4
# Sources: # https://en.wikipedia.org/wiki/Partition_(number_theory) # https://en.wikipedia.org/wiki/Partition_function_(number_theory) # https://math.stackexchange.com/questions/146482/the-number-of-ways-to-write-a-positive-integer-as-the-sum-of-distinct-parts-with # http://mathworld.wolfram.com/PartitionFunctionQ.htm...
91d0958fea51e05903e8dd4db09a71200e980d2f
sacsachin/programing
/insertion_sort_list.py
1,590
3.953125
4
# !/usr/bin/python3 """ https://leetcode.com/problems/insertion-sort-list/ Insertion sort list. """ class Node: def __init__(self, val=0, nxt=None): self.val = val self.next = nxt class LinkList: def __init__(self, nodes=None): self.head = None if nodes is not None: ...
aef93a17fbff81e0a74436c2f1ba3a054261fec1
ramchinta/Algorithms
/RandomizedSelect.py
1,510
3.640625
4
def partition(unsorted_array,first_index,last_index): if first_index == last_index: return first_index pivot = unsorted_array[first_index] pivot_index = first_index index_of_last_element= last_index less_than_pivot_index = index_of_last_element greater_than_pivot_index = first_index + ...
db73169228d9d32a39dcc301c936baf85b9437e3
stevalang/Data-Science-Lessons
/statistics/clt.py
1,157
3.671875
4
import random import matplotlib.pyplot as plt import numpy as np import statistics as stats # Create a normal distribution with mu = 5, sd = 2, n = 1000 pop_norm = np.random.normal(5, 2, 10) # Plot frequency histogram plt.hist(pop_norm, bins=20) # plt.show() def subsample_mean(data, n = 50): ''' Creates and...
6fc831ec6e9516fedfc7d645e1b2c7e949800c06
dacioromero/hackerrank
/Python/np-dot-and-cross.py
212
3.640625
4
import numpy def main(): N = int(input()) A, B = [numpy.array([list(map(int, input().split())) for _ in range(N)]) for _ in range(2)] print(numpy.matmul(A, B)) if __name__ == '__main__': main()
a9e6539b223163844a7004ef35b80236cefd7f43
sang-woon/infrean_python1
/section7-1.py
1,747
3.90625
4
# ------------------------------ # State Design Pattern # ------------------------------ # Allow an object to alter its behavior when its internal state changes. # The object will appear to change its class. # https://github.com/rajan2275/Python-Design-Patterns/blob/master/Behavioral/state.py from _ast import expr fro...
e54069ffcdbe5853e0fb43bf655bcc9737047914
sknaht/algorithm
/python/list/LRU.py
1,646
3.5
4
class LRUNode: def __init__(self, key, val): self.key = key self.val = val self.next = None self.prev = None class LRUCache: # @param capacity, an integer def __init__(self, capacity): self.capacity = capacity self.head = LRUNode(0, 0) self.tail = LR...
4a0c600d1b632e384eaa8e2d9fabf5026c40d95b
xlax007/Collection-of-Algorithms
/Binary_search.py
1,745
4
4
# -*- coding: utf-8 -*- """ Created on Fri Mar 13 23:55:19 2020 @author: alexi """ def binary_search(array, target): L = 0 R = len(array)-1 while L <= R: mid = L + int((R-L)/2) if array[mid] == target: return (target,'at position:',mid) ...
cc8477c277c213f869db9fb13365b9b5a6d39d9d
wa57/info108
/Lab3/exercise4.py
439
4.21875
4
if 0: print('0 is true') else: print('0 is false') print() if 1: print('1 is true') else: print('1 is false') print() if -1: print('-1 is true') else: print('-1 is false') extra = 2 if extra < 0: print('small') else: if extra == 0: print('medium') else: print('larg...
7cb64312a4c5593b07eea98d4671615abb4d4ad1
Aasthaengg/IBMdataset
/Python_codes/p00003/s526735685.py
500
3.734375
4
#-*-coding:utf-8-*- def get_input(): for i in range(int(input())): yield "".join(input()) if __name__ == "__main__": array = list(get_input()) for i in range(len(array)): a,b,c = array[i].split() if int(a)**2 + int(b)**2 == int(c)**2: print(u"YES") ...
111b41f412b6c512e29a20e77233dd0c9de7bb65
Ge0dude/PythonCookbook3
/Chapter1/1.7KeepingDictInOrder.py
581
4.03125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon May 15 07:38:31 2017 @author: brendontucker """ from collections import OrderedDict d = OrderedDict() d['grok'] = 4 d['foo'] = 1 d['bar'] = 2 d['spam'] = 3 for key in d: print(key, d[key]) '''is built through a doubly linked list. Keys are...
8802df921be214d87f1a82947bace484d09ba095
melobarros/30-Day-LeetCoding-Challenge
/Week-2/Day09-BackspaceStringCompare.py
1,139
3.734375
4
""" Day 9 - Backspace String Compare Leetcode Easy Problem Given two strings S and T, return if they are equal when both are typed into empty text editors. # means a backspace character. Example 1: Input: S = "ab#c", T = "ad#c" Output: true Explanation: Both S and T become "ac". Example 2: Input: S = "ab##"...
d67cfc77ff248830e3c163958919dc81052bddce
greedy0110/algorithm
/baekjoon/5052.py
768
3.6875
4
import sys import collections def input(): return sys.stdin.readline().strip() class Tries: def __init__(self): self._next = {} self._is_terminal = False def insert(self, word): if not word: self._is_terminal = True return not self._next else: ...
13059e2644c7b98c9f34a2818a8f2eef2cb0e60d
emreozgoz/KodlamaEgzersizleri
/if else/oyuncukayıt.py
505
3.921875
4
username = "emreozgoz" passw= 123456 print("Hoşgeldiniz Lütfen Kullanıcı adınızı ve şifrenizi giriniz") a = input("Kullanıcı adınızı giriniz") b = int(input("Şifrenizi Giriniz ")) if (a!= username and b== passw): print("Kullanıcı adınız hatalı") if (a != username and b != passw): print("Kullanıcı adı ve Par...
1512c5a3c194b873f0fbe54607e558597ee60798
halysl/python_module_study_code
/src/study_checkio/even the last.py
323
3.796875
4
def checkio(array): """ sums even-indexes elements and multiply at the last """ sum = 0 try: for i in array[::2]: print(i) sum += i sum = sum * array[-1] print(sum) except: return 0 array = [0, 1, 2, 3, 4, 5] checkio(arr...
c44715669aa9563fcccba5086cf1061974dd0660
prbarik/My_Py_Proj
/.vscode/pig_latin.py
365
4
4
# PIG LATIN # If word starts with vowel, add 'ay' to the end # If word does not start with vowel, then put first letter to the end and add 'ay' def pig_latin(word): first_letter = word[0] if first_letter in 'aeiou': pig_word = word + 'ay' else: pig_word = word[1:] + first_letter + 'ay' ...
ba91f0c52364ad29b762eefb7d9d2f6b15b82c33
Sixmillion/pycharm
/test/04.数据结构.py
1,551
3.6875
4
#字符串(不可变元素,'...') a='py''thon'#可拼接 b='py'+'thon' #列表(可变元素,[*,*,...]) list=['a'] ex_list=['c','d'] list.append('b') list.extend(ex_list) list.insert(len(list),'e') list.remove('e') list.pop(3)#删除并返回指定位置的值,缺省为最后一个元素 #list.clear()#清楚列表所有元素 list.index('b')#返回指定元素的索引 list.count('a')#返回出现次数 list.sort() list.reverse() print(l...
1144795851de8c5918ecac0d8b1ffd1e902061f4
sphamv/mit-ocw-6.0001
/ps1/ps1a.py
750
3.78125
4
# -*- coding: utf-8 -*- """ Created on Sat Jul 15 00:41:29 2017 Finished: 02:19 AM @author: Dev Jboy Flaga """ # Part A: House Hunting annual_salary = float(input('Enter your annual salary: ')) portion_saved = float(input('Enter the percent of your salary to save, as a decimal: ')) monthly_savings = (annual_salary ...
d8e6ace169f556d2b335dfc8cfa9849469fb774d
aKryuchkova/programming_practice
/week03/exercise13.py
799
4.1875
4
''' Нарисуйте смайлик с помощью написанных функций рисования круга и дуги. ''' import turtle as t def duga(n): for i in range(180): t.forward(n) t.right(1) def krug(n): for i in range(360): t.forward(n) t.left(1) t.color('yellow') t.begin_fill() krug(3) t.end_fill() t.penu...
ff633157875c84c869f5f23fa32b201f75d8f17b
AndreiAniukou/Python-s
/if_elif_else.py
542
3.75
4
''' age = int(input('Enter ur age')) if age <= 4: print('ur ticket is free') elif age <= 18: print('ur ticket cost is 5$') else: print('ur ticket cost 10$') ''' ''' age = int(input('Enter ur age!')) if age <= 4: price = 0 elif age <= 18: price = 5 else: price = 10 print('Ur ticket cost $' + ...
6642bfdc6d5b1014b5d674ad9d57c79783096950
pyroRocket/Python
/Python101/Math.py
389
4
4
# Math print("Math time: ") print(67 + 69) # Add print(67 - 69) # Subtract print(67 * 69) # Multiply print(10 / 5) # Divide print(20 + 20 - 20 * 20 / 20) # PEMDAS (Order of operations) print(20 ** 2) # Exponents (20 ^ 2) print(23 % 4) # Modulo will return the remainder of a division operation print(10 /...
b116930b70f79fdae156095cb25bc3e2475fceb2
Phillyclause89/ISO-8601_time_converter
/time_converter.py
3,094
3.890625
4
# iso_time must be a timestamp string in ISO 8601 format and offset is to change the timezone def time_convert(iso_time, offset=0): # months dict for converting from numerical month representation to name months = {1: "January", 2: "February", 3: "March", 4: "April", 5: "May", 6: "June", ...
a2d75298b2a46e738665629ec32cd00b9eec3247
LichAmnesia/LeetCode
/python/113.py
1,081
3.765625
4
# -*- coding: utf-8 -*- # @Author: Lich_Amnesia # @Email: alwaysxiaop@gmail.com # @Date: 2016-10-07 01:42:15 # @Last Modified time: 2016-10-07 02:02:26 # @FileName: 113.py # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # ...
95524087dc3a9a6a1936f6e83796eb6ac49cac86
Priyansi/pythonPrograms
/chessPieceCanCapture.py
689
3.578125
4
from chessCanMoveToPos import isPosInsideBoard, alphaToNum, pieceFunctions, king, queen, bishop, knight, rook def pawnCapture(pos1, pos2): return int(pos2[1])-int(pos1[1]) == 1 and abs(alphaToNum[pos2[0]]-alphaToNum[pos1[0]]) == 1 def canPieceCapture(piece, pos1, pos2): if pos1 == pos2 or not(len(pos1) == l...
9f1db9e70e36af933abd037a2160a4962bed4b92
hashjaco/PizzaHash
/PizzaEvent.py
4,822
3.515625
4
import numpy as np class PizzaEvent: def __init__(self, file): self.max_slices, self.num_types, self.pizza_weights = getData(file) ''' Return a dictionary of pizza weights a''' def returnPizzaDict(self): pizza_dict = {} for i in range(len(self.pizza_weights)): pizza_di...
d8843676c975e46358544aad75cbd905519d0150
juarezejp/python
/POO/ManipulacionCadenas.py
1,185
4.15625
4
nombre = "Eliadio JP" nombre2 = "eladioJP" numletra = "33k" numeroS = "5555" #devuelve en minusculas la cadena print(nombre.lower()) #devuelve en mayusculas la cadena print(nombre.upper()) #devuelve la cadena el primer caracter en mayuscula print(nombre2.capitalize()) #devuelve true si la cadena es digitos print (numl...
d0592e75e11110e03897386dfce0c62413c4e816
liaogx/python3-cookbook
/第四章:迭代器与生成器/4.10.py
894
3.6875
4
#!/usr/bin/env python # -*- coding:utf-8 -*- # __author__ = 'liao gao xiang' # 你想在迭代一个序列的同时跟踪正在被处理的元素索引, 使用enumerate()函数 from collections import defaultdict my_list = ['a', 'b', 'c'] for n, s in enumerate(my_list, start=1): # start表示开始的计数值 print(n, s) # 这种情况在你遍历文件时想在错误消息中使用行号定位时候非常有用: with open('file.txt', 'r...
139f51d8e67026cc3285627e1bc0ef2693437447
sbasu7241/cryptopals
/Set2/Challenge9.py
530
3.953125
4
#!/usr/bin/env/python def pkcs(data,block_size): """Returns data padded to the supplied block size in PKCS#7 format""" pad_length = block_size - (len(data) % block_size) # if pad_length is 0 it means data is of correct size but we will add extra blocks of padding if pad_length == 0: pad_length = block_size ...
50944898106de08dc5d00b72b84319195fd6cc41
Clarxxon/kluster_analysis
/loadData.py
551
3.53125
4
import numpy as np import pandas as pd import matplotlib.pyplot as plt def read_datafile(file_name): data = pd.read_csv(file_name,delimiter=',', encoding="utf-8-sig") return data # data = read_datafile('winequality-red.csv') data = read_datafile('cars.csv') print(data['brand']) # fig = plt.figure() # ax...
038278c1b3176df4ff30ddc5844c6c274d839cb8
Delia86/2PEP21G01
/c12/part2.py
909
3.5625
4
import tkinter main_window = tkinter.Tk() main_window.title("Text") class TextWindow(): def __init__(self, root_window: tkinter.Tk): self.root_window = root_window self.text = tkinter.Text(self.root_window, height=25, width=80) self.text.pack() self.add_button = tkinter.Button(se...
17835516a96add2241ed9669995a8e7c818aa19a
edaveballard/CS_class_activities
/Python/IteratedTournament/Tournament/player_tit4tat.py
269
3.578125
4
# -*- coding: utf-8 -*- """ Created on Sat Nov 2 16:56:53 2019 @author: evan.ballard """ my_history = [] other_history = [] name = "Tit for Tat" def next_move(): if len(other_history) == 0: return 0 else: return other_history[-1]
689a996c808f2ebcecfddc1145038f6ddded9534
Solbanc/Programacion_python
/Ejercicios python/Ejercicio practico 1.py
1,576
4.0625
4
print("Dias de Vacaciones Correspondientes a los trabajadores de Rappi.\n") print("Clave 1 'Atencion a Clientes'") print("Clave 2 'Logistica'") print("Clave 3 'Gerencia'") nom = input("Cual es el nombre del trabajador: ") clave = int(input("Cual es la clavel del trabajador: " )) tiempo = int(input("Cuanto tiempo ha...
c5fc95f5a95b433bbb69945e8f83c03c400c9f4f
MarceloDL-A/Python
/13-Data_Visualization/Introduction_to_Matplotlib/Line_with_Shaded_Error.py
1,840
4.0625
4
import codecademylib from matplotlib import pyplot as plt hours_reported =[3, 2.5, 2.75, 2.5, 2.75, 3.0, 3.5, 3.25, 3.25, 3.5, 3.5, 3.75, 3.75,4, 4.0, 3.75, 4.0, 4.25, 4.25, 4.5, 4.5, 5.0, 5.25, 5, 5.25, 5.5, 5.5, 5.75, 5.25, 4.75] exam_scores = [52.53, 59.05, 61.15, 61.72, 62.58, 62.98, 64.99, 67.63, 68.52, 70.29, ...
82b446d9f76af685659b432de5f84a2698efcb6e
zopepy/leetcode
/minimumindexsum.py
884
3.84375
4
class Solution: def findRestaurant(self, list1, list2): """ :type list1: List[str] :type list2: List[str] :rtype: List[str] """ list1dict = {} l1 = len(list1) l2 = len(list2) for i in range(0, l1): if list1[i] not in list1dict: ...
bb7556b100c87d3acb3efc291f3cf8465f36a9e7
gil9red/SimplePyScripts
/split_text_by_fragments.py
1,986
3.515625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- __author__ = "ipetrash" def split_text_by_fragments(text: str, fragment_length=50) -> list: """ Функция для разбития текста (<text>) на куски указанной длины (<fragment_length>). """ # Если длина фрагмента больше или равна длине текста, то сразу возвра...
4acf7c52945f382197827765badb714063590047
Julien-Verdun/Project-Euler
/problems/problem56.py
636
3.90625
4
# Problem 56 : Powerful digit sum def digital_sum(number): """ This function calculates the sum of digits of a given number. """ return sum([int(nb) for nb in list(str(number))]) def powerful_digit_sum(): """ This function calculates the maximal sum of power number. """ max_sum = 1 ...
39e5441de5a47bb728a4b4314336188bdeb1d0f6
alfredsusanto/CP1404
/stockPrice.py
752
3.90625
4
import random MAX_INCREASE = 0.175 # 10% MAX_DECREASE = 0.05 # 5% MIN_PRICE = 1 MAX_PRICE = 100 INITIAL_PRICE = 10.0 price = INITIAL_PRICE def format_currency(price): currency= "Starting price: $ {:.2f}".format(price) return currency result = format_currency(price) print(result) def format_currency2(price,d...
168e7d485e22d14e0f0282f11ddd5ba0a753f41a
abbibrunton/python-stuff
/Python stuff/count_vowels.py
282
3.984375
4
word = input("please enter a word: ") word_lower = word.lower() vowels = "aeiou" count = 0 for char in word.lower(): if char in vowels: count += 1 else: continue if count == 1: print("there is 1 vowel in", word) else: print("there are", count, "vowels in", word)
f68e69983505091670add94376e866e748841e58
redsarvesh/OOP-Python
/class/inheritance/fourth.py
292
4.03125
4
#!/usr/bin/python class Person(object): def __init__(self): self.name = "{} {}".format("First","Last") def f(self): self.x=10 class Employee(Person): def introduce(self): print("Hi! My name is {}".format(self.name)) print self.x e = Employee() e.introduce()
e8e7dd9dd87cfff7e0e932e8d67d25499c146054
jordanmiracle/learnpython3thehardway
/ex40.py
588
4.1875
4
class MyStuff(object): def __init__(self): self.tangerine = "And now a thousand years between" def apple(self): print("I am classy apples!") thing = MyStuff() thing.apple() print(thing.tangerine) # Each time you creating a variable and assign it to MyStuff, you are creating a new object...
53be0f978919f374235742059850950a2467c9a5
sandesvitor/code-lessons
/Cod3r (web + python + c#)/exercicios-python/e.py
466
3.59375
4
def dig_pow(n, p): stack: list = [] sum: int = 0 limit: int = n pot: int = p while limit > 0: digit: int = limit % 10 stack.append(digit) limit //= 10 stack.reverse() for num in stack: sum += num ** pot pot += 1 k: int = sum // n if sum...
66622b4a63a78d1b940dd0104aaca7b5c78872a1
fgaurat/python_07122020
/tp1/tp2.py
362
3.8125
4
#!/usr/bin/env python # words =[] # w1 = input("mot 1: ") # words.append(w1) # w2 = input("mot 2: ") # words.append(w2) # w3 = input("mot 3: ") # words.append(w3) # print(50*"-") # print(words) # print(50*"-") # for w in words: # print(w.upper()) # print(50*"-") # for i in range(len(words)): # print(i,words[i])...
9b9001886189ea1246415cd260637e61e7e87115
dsspasov/HackBulgaria
/week0/2-Python-harder-problems-set/problem28_test.py
581
3.5625
4
#problem28_test.py import unittest from problem28 import count_words class TestWordCount(unittest.TestCase): def test_empty_dict(self): self.assertEqual({},count_words({})) def test_not_empty_dict_with_different_elements(self): result = count_words(["apple", "banana", "apple", "pie"]) s...
480e6715772aa7670af4d7404bc5ac5802ddcb04
piyush-bajaj7/substraction_BOT
/main.py
2,445
3.5
4
import time import random level_1_num1 = int(random.randint(100 , 120)) level_2_num1 = int(random.randint(121 , 140)) level_3_num1 = int(random.randint(141 , 160)) level_1_num2 = int(random.randint(30 , 50)) level_2_num2 = int(random.randint(51 , 60)) level_3_num2 = int(random.randint(61 , 90)) num1_randomi...
8c72fbffdb03445ea74b7b75aea9366530942901
Razdeep/PythonSnippets
/SEP06/02.py
144
3.859375
4
# color sorting using dictionaries code={'red':'#ff000','blue':'#ffff','black':'#00000'} for key in sorted(code): print(key,':',code[key])
847ab87cd32c94b7faa9a2f3b8f625e07b61688c
mr-nishanth/PythonDT
/12-While in and For in.py
416
3.90625
4
# While in Subject = ['Tamil', 'English', 'Maths', 'Science', 'Social Science'] Count = 0 while Count < len(Subject): print(Subject[Count]) Count +=1 #print(len(Subject)) --->5 # For in Games = ['Ludo', 'Freefire', 'Shooting', 'Car Raci...
b2a77dd6b8fe303e7c79e4ba2a0ffff00480cfce
Verissimosem2/programacao-orientada-a-objetos
/listas/lista-de-exercicios-03/questão1.py
222
4.09375
4
numero = int (input("Por favor digite o primeiro numero: ")) numero_2 = int (input("Por favor digite o segundo numero: ")) if numero > numero_2: print("Numero maior: ",numero) else: print("Numero maior: ",numero_2)
3d4480d8f0d700bf88d6a752538d51b202f20521
jundongq/emerald-shiner-detector
/utils_/removeGlare.py
1,785
3.546875
4
import cv2 import numpy as np def removeGlare(img, satThreshold = 180, glareThreshold=240): """This function is used to remove light reflection on water surface during experiments, it return a np.ndarray() in shape of (height, width, channel). credit: http://www.amphident.de/en/blog/preprocessing-for-automatic-pat...
3276b6e64537e3b3fb2bef850b968a727ac58f11
xw0220/pythoncourse
/experiment6/test8.py
458
3.5
4
def qiuhe(x): feizhengshuliebiao=[] if x==[]: return "输入不能为空列表" else: for item in x: if type(item)!=int: feizhengshuliebiao.append((item,type(item))) if feizhengshuliebiao==[]: return sum(x) else: print("元素类型错误,要求所有元素都为整数") ...
827a97706612c4b08787293e38e44ad73fceaae9
sakurasakura1996/Leetcode
/alibaba_online_codeing/每周限时赛第一场(内测版)/商品列表.py
1,823
4.03125
4
""" 描述 有一个商品列表,该列表是由L1、L2两个子列表拼接而成。当用户浏览并翻页时,需要从列表L1、L2中获取商品进行展示。 展示规则如下: 1. 用户可以进行多次翻页,用offset表示用户已经浏览过的商品数量。比如,offset是4,表示用户已经看了4个商品。 2. n表示一个页面可以展示的商品数量。 3. 展示商品时首先使用列表L1,如果列表L1不够,再从列表L2中选取商品。 4. 从列表L2中补全商品时,也可能存在数量不足的情况。 给定offset,n,列表L1和L2的长度。 请根据上述规则,计算列表L1和L2中哪些商品在当前页面被展示了。 你需要根据notice里的规则输出两个区间。区间段使用半闭半开区间表示,即包含...
4e5dd83a5bf18543528d65aa75e729c5dd8b675e
FelipePRodrigues/hackerrank-practice
/interview-preparation-kit/string-manipulation/alternating-characters/alternating_characters_test.py
325
3.515625
4
from alternating_characters_solution import alternatingCharacters class TestAlternatingCharacters: def test_one(self): assert alternatingCharacters("AAAA") == 3 def test_two(self): assert alternatingCharacters("ABAB") == 0 def test_three(self): assert alternatingCharacters("AABB")...
bb4b2fa278b9aca268e94de0ad3343d8b188d3f4
JaredRentz/gittest
/statements.py
661
3.78125
4
# if, elif, else Statements ''' if case1: perform action 1 elif case2: perform action 2 else: perform action 3 ''' x = [2,3,4,5,7,8] y = 6 z = 3 ''' if x>y: print(x) elif y>z: print(y) else: print(z) ''' # FOR LOOPS IN PYTHON #for item in x: #print(item) badge_numbers = [1,3,432,43242,432] ''' for x in badge_...
4b67852d9119cc1d51a64abb5ae62a88c11ef325
yashitha985/python
/hunter1.py
183
3.5
4
a=int(input()) b=list(map(int,input().split())) c=[] for i in b: if(b.count(i)>=2 and i not in c): c.append(i) if(len(c)==0): print("unique") else: for i in c: print(i,end="")
9f6b77e4cf889ff94d96548a2fd7162c072c0e4d
danstelian/python_misc
/oop/oop_03_inheritance.py
2,753
3.90625
4
""" Add two subclasses to the curent Employee class """ class Employee: num_of_emp = 0 def __init__(self, first, last, salary): self.first = first self.last = last self.salary = salary Employee.num_of_emp += 1 def __str__(self): return f'{self.first} {self.last}...
cef96eb045f0cf281483a18e4dda1d080f078932
BeckerFelix/KITTI-to-tfrecords
/progress.py
1,249
3.9375
4
# -*- coding: utf-8 -*- # Print iterations progress to the terminal import sys def print_progress_bar(iteration, total, bar_length=50): """ Call in a loop to create terminal progress bar @params: iteration - Required : current iteration (Int) total - Required : total iterations (...
1a5860658e36b1ba322392f11f5057233fa97259
byzhang/conclave
/conclave/rel.py
3,143
3.84375
4
""" Data structures to represent relations (i.e., data sets). """ import conclave.utils as utils class Column: """ Column data structure. """ def __init__(self, rel_name: str, name: str, idx: int, type_str: str, trust_set: set): """ Initialize object. :param rel_name: name of...
890456ed386df13bdf79c4b212b5b3d488be46c4
xelab04/0H-H1-Bot
/0h h1 bot.py
5,050
3.6875
4
array = [] file_dest = "input.txt" with open(file_dest,"r") as file: lines = file.readlines() for line in lines: array.append((line.strip("\n")).split(",")) for row in array: print(row) print("") grid_size = len(array) def output(array): for row in array: print(row) ...
f06b865266ddf2e30345ff92847e23eef83ae733
lxchavez/Yeezy-Taught-Me
/src/MSongsDB/Tasks_Demos/SQLite/list_all_tracks_from_db.py
2,909
3.75
4
""" Thierry Bertin-Mahieux (2010) Columbia University tb2332@columbia.edu This code creates a text file with all track ID, song ID, artist name and song name. Does it from the track_metadata.db format is: trackID<SEP>songID<SEP>artist name<SEP>song title This is part of the Million Song Dataset project from LabROSA (...
06f1818880cc91aaea5f74ec35f532bf4b0c84bc
xwang322/Coding-Interview
/uber/uber_algo/MergeNumsToRanges_UB.py
3,160
3.625
4
/* * 给定一个整数数列比如-2,-1,2,3,返回代表数列的range比如-2--1,2-3 * 给出正确做法(排序+遍历),写了几个testcase * 然后来了个followup,给出range,返回任何一个对应整数数列,遍历硬做就可以了,需要考虑一下横杠的不同情况 **/ def MergeIntToRanges(nums): if not nums: return [] if len(nums) == 1: return [str(nums[0])+'-'+str(nums[0])] nums.sort() answer = [] ...
c356d4ab84c641de5124a874f506405166af84d0
Zikx/Algorithm
/Baekjoon/Sort/2750.py
106
3.5
4
n = int(input()) l = [ int(input()) for i in range(n)] l.sort() for e in l: print(e,end="\n")
6414625d38f35da285cf981150d2f0f60821c948
Munyiwamwangi/politico
/app/tests/test_petition_model.py
1,072
3.59375
4
# petition class tests import unittest from app.api.model.petition import Petition class PetitionModelTestCases(unittest.TestCase): """ Test class for petition model """ def setUp(self): """Create a petition object instance :arg: office, created_by, body, evidence :return: petition...
7809c18f46df54285ba693eac37cc7a86225b417
PierfrancescoArdino/LUS-MidTerm-Project
/compute_output.py
942
3.59375
4
#! /bin/python3 ''' LUS mid-term project, Spring 2017 Student: Pierfrancesco Ardino, 189159 This script simply check if the output concept is in the concept list, if not it means that the output concept is the word itself and so has to be changed into the O concept #### HOW-TO USE#### Do not run this script independen...
dc90049ee28dea522ab3a5aa9a69dfaf65d1ad43
lmhbali16/algorithms
/CTCI/chapter_1/string_compression.py
1,428
4.3125
4
''' Implement a method to perform basic string compression using the counts of repeated characters. For example, the string aabcccccaaa would become a2blc5a3. If the "compressed" string would not become smaller than the original string, your method should return the original string. You can assume the string has only u...
196f6a6bb2c1c4e47139e1da7d4d3e5cd234a477
IagoFrancisco22/listaDeExerciciosPython
/Primeira lista de exercicios Python/exercicio5.py
392
3.921875
4
#enunciado print('''Solicite o preço de uma mercadoria e o percentual de desconto. Exiba o valor do desconto e o preço a pagar.''') m = float(input("Digite o preco da mercadoria:"))#solicitar preço mercadoria(m) d= int(input("Digite a porcentagem de desconto:"))#percentual de desconto (d) p=d/100#porcentagem(p) ...
769b7f34a39cc01986f64c141587f762b938bae2
gabrielalvesfortunato/Formacao-Python-alura-OO
/conta.py
2,280
3.828125
4
# Para se nomear objetos usa-se o padrão Camel Case. class ContaCorrente: # Definindo o Construtor da classe def __init__(self, numero, titular, limite = 1000, saldo = 0): print("Construindo objeto {}".format(self)) self.__numero = numero self.__titular = titular self.__...
d6e90fa15a33a37e2b610436c1ff1c920733150b
proformatique/algo
/mpsi4_23_10.py
1,670
4.09375
4
def somme2(A, B) -> list: '''Calcule la somme terme à terme de A et B. Parameters: ----------- A : list Premier vecteur B : list 2eme vecteur Returns ------- C : list la somme de A + B | ci = ai + bi Examples -------- >>...
e2a8b6dc028f4f0604f2da8a9590cd8a7cfea4f9
Malvado86/Crash_Course_on_python
/Code_Style_rectangle.py
203
3.84375
4
''' Created on 21 de mar de 2020 @author: tsjabrantes ''' def rectangle_area(base, height): z = (base * height) # the area is base*height print("The area is " + str(z)) rectangle_area(5,6)
66633dd3813544e164ff62f2e448e6655b213417
xiaojieluo/savemylink
/lib/util_bak.py
1,068
3.515625
4
#!/usr/bin/env python # coding=utf-8 import datetime import time def convert(data): """ dict bytes key to str value """ if not isinstance(data, dict): return data return dict([(bytes.decode(k), bytes.decode(v)) for k, v in data.items()]) def ago(times, accurate=False): now = int(time....
6a742645d1d438ac2ecc3ee032777451b12be06a
jatinkatyal13/PythonForDataScience
/codes/check_cons_ones.py
204
3.625
4
n=input('enter the binary number: ') k=input('enter the value of K: ') g=0 l=int(k) g='1'*l if(g in n): print("yes there are given no. of consecutive 1's in the binary number") else: print('NO')
4330424b22dcab4225654323d7096aae7c2de33e
YoyinZyc/Leetcode_Python
/Sort/Pro147_Insertion_Sort_List.py
1,122
3.84375
4
''' Sort_Medium 9.19 6:31pm ''' # Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def insertionSortList(self, head): """ :type head: ListNode :rtype: ListNode """ ...
813dd1da95a95bb4170d71e883c047694ca2ace3
ollyhayes/advent-of-code
/src/2019/day03.py
1,731
3.5
4
import os from typing import List, Tuple, Dict, Set def parse_input(input_raw: str) -> List[List[Tuple[str, int]]]: return [ [(command[0], int(command[1:])) for command in path.split(",")] for path in input_raw.split("\n") ] directions: Dict[str, Tuple[int, int]] = { "R": (1,0), "L": (-1,0), "U": (0,1), "...
c6ac1cacde7cc5f5da7faf35f7fbc66e8cdc8805
arsalan2400/HPM573S18_AHMED_HW1
/HW1Problem4.py
840
4.28125
4
#Print ours1 and ours2. Describe how ours1and ours2differfrom each other.# yours = ['Yale','MIT','Berkeley'] mine= ['University of Connecticut','Lousiana State University','Florida State University'] ours1 = yours + mine print(ours1) ours2=[] yours = ['Yale','James Bond College','Berkeley'] ours2.append(yours) ours2.a...
4ef010f37e0122f7e417b05f32956ac5e7111fb8
tpracser/PracserTamas-GF-cuccok
/week-03/day-2/34.py
262
3.546875
4
numbers = [4, 5, 6, 7, 8, 9, 10] kitties = [4, 5, 6, 7, 8, 9, 11] # write your own sum function def sumfunc(num): a = 0 b = 0 while a < len(num): b = b + num[a] a += 1 return (b) print (sumfunc(numbers)) print (sumfunc(kitties))
5aed5bb49e040874e64199f0dad34c9d7b2e79f7
subodhss23/python_small_problems
/easy_probelms/hiding_card_num.py
379
3.78125
4
''' Write a function that takes a credit card number and and only displays the last four characters. The rest of the card number must be replaced by ************.''' def card_hide(card): len_of_astrik = len(card) - 4 return '*' * len_of_astrik + card[-4:] print(card_hide("1234123456785678")) print(card_h...
cdcf764fd7e54952858d0f63518606ca83a81791
SamarthSriv/Sketch_image_using_python
/main.py
596
3.96875
4
# Samarth Srivastava # 18BCE10232 # Animate your photo using opencv library in python import cv2 image = cv2.imread("original.jpg") # this will load the image into image variable from root directory grey_img = cv2.cvtColor(image, cv2.COLOR_BGRA2YUV_YV12) # add grey filter invert = cv2.bitwise_not(grey_img) #...
b4902876438925319b17ef9533d816cd40a538b0
Tibiazak/4300P3
/4300PA3.py
6,576
3.578125
4
import random binary = [0, 1] pop_size = 5 pop_limit = 81920 string_size = 5 string_list = [] recom_prob = 0.6 # A function that checks the fitness for onemax def fitness(string): fit = 0 # initialize accumulator for c in string: # iterate over every element in the string, increment accumulator for each 1 ...
b7da965e05bef1196a57117fb94d3b783cf3ffda
anviaggarwal/assignment-2
/question 6.py
61
3.875
4
r=int(input('enter radius')) pi=3.14 area=pi*r*r print(area)
d4f4cfd377a43a9b4061b2c776455de7edab9e8b
ang-li7/Kattis
/KitchenMeasurements.py
343
3.625
4
def measurements(cups, goal, tot): while cups[0]!=goal: for i in range (1, ) return 0 ss = input().split(" ") cupss = ss[1:-1] cups = [] for n in cupss: cups.append(int(n)) goal = int(ss[-1]) tot = 0 a = measurements(cups, goal, tot) min = a[0] for i in a: if min>i: min = i print(i) #p...
27444e932531920fa25ac0c31755fcbb975134b2
itsolutionscorp/AutoStyle-Clustering
/assignments/python/anagram/src/143.py
243
3.78125
4
def detect_anagrams(str1, str2): str1_list = list(str1) str1_list.sort() for i in str2: str2_list = list(i) str2_list.sort() if str1_list == str2_list: return i #detect_anagrams('ant', 'tan stand at'.split())
23d9d14145bdaff750519d4b910b883bf20d0695
shivaniraut5555/sorting-algorithms
/buuble_python.py
1,187
4.0625
4
''' Bubble sort Some times reffred as sinking sort,is a simple sorting algorithm which sorts n number of elements in the list by comparing the each pair of adjacent items and swaps them if they are in wrong order step1: Starting with the first element (index=0)cpompare the current element wih the next element of the l...
5793fee8fadee8ed9f0c46d0b8c97d783c0573a5
plvankam/Fall_2018
/Object_Oriented/mastering_python/test_env/Circle.py
369
3.625
4
import math class Circle: def __init__(self, radius): self.__radius = radius def setRadius(self, radius): self.__radius = radius def getRadius(self): return self.__radius def getArea(self): return self.__radius * 2 * math.pi def __add__(self, other): ret...
8ad6fec844040645b7fd76bff5747e1130b2f272
JessMadok/EstudoPython
/MaquinadeCafe/main.py
2,496
3.828125
4
MENU = { "espresso": { "ingredients": { "water": 50, "coffee": 18, }, "cost": 1.5, }, "latte": { "ingredients": { "water": 200, "milk": 150, "coffee": 24, }, "cost": 2.5, }, "cappuccino": { ...
6a9ea1baf5a959622be820c22968f129ddeef2f3
AlexisDongMariano/miniProjects
/web scraping/price_tracker.py
2,084
3.59375
4
''' Date: Jun-16-2020 Platform: Windows Description: [BASIC WEB SCRAPING] - sends an email to the hardcoded recipients if the item from a shoe shop has dropped its original price Usage: python price_tracker.py Sections: A ''' #SECTION A import requests from bs4 import BeautifulSoup import smtplib import time #ac...
0afd7dd4a54e66ed9a0726654659d2e2f7976129
kotsurnazariy/HW_soft
/ClassWork1.py
1,373
3.765625
4
#1 # a = 0 # while a < 100: # print (a) # a += 2 # a = 0 # for a in range(0, 100, 2): # print(a) #2 # a = 1 # while a < 100: # print(a) # a += 2 # a = 1 # for a in range(100): # if a % 2 == 0: # continue # print(a, end=' ') #3 # a = [2, 4, 6, 7, 10] # for a in a: # if a % 2 =...
fb08e7693738cda1393834ca5d305d0fe7b5a9ea
VaibhavD143/Coding
/leet_letter_combination_phone_number.py
246
3.5
4
dic = {'2':'abc','3':'def','4':'ghi','5':'jkl','6':'mno','7':'pqrs','8':'tuv','9':'wxyz'} n = "234" res = list(dic[n[0]]) for i in range(1,len(n)): res = [res[j]+dic[n[i]][k] for k in range(len(dic[n[i]])) for j in range(len(res))] print(res)
678ae7d5cef48663509c8a5a58636a86cc736d52
Pshypher/tpocup
/ch06/projects/proj_02b.py
1,773
4.5625
5
# Program designed for the purposes of substring matching with applications # in genetics, such as trying to find a substring of bases ACTG # (adenine, cytosine, thymine and guanine) in a known DNA string, or # reconstructing an unknown DNA string from pieces of nucleotide bases # Unless stated otherwise,all variables...
0dc95f2b65992865eb9c38062a7acb8fd68d5278
alsbhn/CityAnnotation_App
/database.py
1,817
3.703125
4
import os import csv from sqlalchemy import create_engine from sqlalchemy.orm import scoped_session, sessionmaker engine = create_engine("sqlite:////database.db") # database engine object from SQLAlchemy that manages connections to the database # DATABASE_URL is an ...
4ecd7b72fd7bee1795002abd85f026ca2bed74f3
SeitzhagyparovaTE/web
/week_7/1.Informatics/1.3_Loops/1.3.1_For/C.py
151
4.09375
4
import math for number in range(int(input()), int(input()) + 1, 1): if int(math.sqrt(number)) ** 2 == int(number): print(number, end = " ")
9cf9f7e1f6236f559c282683dce320429c9ac261
euclude/PythonFinance
/sim/MarketSimulator.py
4,714
3.59375
4
import pandas as pd from finance.utils import DataAccess from datetime import datetime class MarketSimulator(object): ''' Market Simulator. Receives: 1. Initial cash 2. List of trades (automaticly search and downloads missing information) After simulation: portfolio is a pandas....
31d32802f4cb2c99ee507ffe1f964770ace43a2e
alsomilo/leetcode
/0023-merge-k-sorted-lists/0023-merge-k-sorted-lists.py
1,879
3.875
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]: ''' def mergTwo(l1, l2): if None i...
8146b6579d56606d78c2c9727801ea69d3d2522a
heenach12/pythonpractice
/Stack/stack_using_linkedlist.py
1,281
3.90625
4
class Node: def __init__(self, value): self.value = value self.next = None class Stack: def __init__(self, value): self.head = Node("head") self.size = 0 def __str__(self): cur = self.head.next out = "" while(cur): out += str(cur.value) +...
1c7bec2280216c57985c2c893adf618e48617eb5
dstada/HackerRank.com
/Happy Ladybugs.py
1,185
3.859375
4
def check_happy(b): overall_happy = True for i in range(len(b)): happy = False # If left or right is the same colour bug, then happy: if (i - 1 >= 0 and b[i - 1] == b[i]) or i + 1 < len(b) and b[i + 1] == b[i]: happy = True else: overall_happy = False ...
427bdedcdc4618277388ab98b37e80eb6b2e1ee1
iandioch/solutions
/advent_of_code/2021/12/part2.py
1,066
3.765625
4
import sys from collections import defaultdict, deque def can_move(path, other, is_small): if other == 'start': return False if not is_small[other]: return True if other not in path: return True d = defaultdict(int) for p in path: if not is_small[p]: con...
c015318b470117603990bbf7e5c2eaa0835e0ad3
DredNaut/Python-Unittest
/linked_list.py
1,245
3.90625
4
from node import Node class LinkedList(): def __init__(self): self.list = None def get_head(self): if self.is_empty(): return None else: return self.list def is_empty(self): return True if (self.list == None) else False def get_last_node(self)...
403d7d3f1386a821c277306d90af65b799b5717b
kmsmgsh/python
/Metropolis.py
2,104
3.90625
4
import numpy as np from scipy.stats import norm import matplotlib.pyplot as plt class Metropolis: def __init__(self,IterNa,density,initial,sigma): self.IterNa=IterNa self.density=density self.initial=initial self.Mainprocess(sigma) def printAll(self): print("Num...