blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
1e7958e906bb13b7235984e30e5afa2b0278c7b7
ChampionZA/School_ict_backup
/Complete/Python/IGCSE computer science paper 2 october-november 2021.py
4,370
3.625
4
import re homeToStartStation = {'c1':1.50, 'c2':3.00, 'c3':4.50, 'c4':6.00, 'c5':8.00} startStationToEndStation = {'m1':5.75,'m2':12.50,'m3':22.25,'m4':34.50, 'm5':45.00} endStationToDestination = {'f1':1.50,'f2':3.00,'f3':4.50,'f4':6.00,'f5':8.00} bookingDetails = {} accounts = {} stageCodes = [] generatingNumbers ...
71c20f15c95626ddf7801ce2b18d6679eaf61b07
cfawcett100/Trust_Scrape
/csv_handler.py
8,159
3.890625
4
import csv import datetime class csv_handler(object): def __init__(self, file_name): print(datetime.datetime.now()) self._csv_file = file_name print("LOADING FILE...") csv_reader = self.open_csv() self._trust_list = self.create_list(csv_reader) self.to_upper() ...
c053696a0c48e52a2431232d7c53968a58076ba0
nikesh610/Guvi_Codes
/Set5_2.py
79
3.8125
4
x=input().split() if(x[0]==x[1] or x[0]>x[1]): print(x[0]) else: print(x[1])
b87961f70df8cdb6e0f11b3fd6e8844dc81ab536
aguecida/python-playground
/algorithms/binarysearch/binarysearch.py
1,445
4.15625
4
from random import randint def binary_search(range_min, range_max): ''' Performs a binary search to find a randomly selected number between a range of two integers. Args: range_min: The lowest possible value of the randomly selected integer. range_max: The highest possible value of the ran...
d26f9687fd955bb3464eb512ad3f13b2595d01a1
lw2000017/python
/绿城融合系统/测试练习.py
171
3.578125
4
# a={1,2,3,4} # b={1,2,3,4} # c={1,2,3,4} # for j in a: # for k in b: # for l in c: # if j!=k and k!=l and j!=l: # print(j,k,l) #
d7d39535e12121eadbb7f02b23324ff9520610a8
houhailun/algorithm_code
/链表中环的入口结点.py
1,861
3.765625
4
#!/usr/bin/env python # -*- coding:utf-8 -*- """ 题目:链表中环的入口结点 题目描述:给一个链表,若其中包含环,请找出该链表的环的入口结点,否则,输出null 解题思路:对于找链表公共节点,入口节点等问题可以用两个一快一慢的指针 方法1:p1每次走一步,p2循环链表,第一个相同的结点就是入口结点 时间复杂度O(N*N) 方法2:遍历链表,第一个重复的结点就是入口结点 时间复杂度:O(N) 空间复杂度:O(N) 方法3:假设环中有n个结点,那么p1先走n步,然后两个结点一起走,相遇的结点就是入口结点,问题是如何获取环中结点个数: p1每...
c2fec868f5d3e6ada009f6708c25207be6d6193e
nithin-kumar/clrs_algorithms
/stackandQ/queue.py
908
3.703125
4
class Queue: def __init__(self): self.a=[0]*10 self.head=0 self.tail=0 self.length=len(self.a) def queue_full(self): if self.tail+1==self.head: return True return False def queue_empty(self): if self.head==self.tail: return True return False def enqueue(self,x): if self.queue_full(): ...
ff090f5f30811d98c6df19dd4ffeb037d4eb0a44
keshamin/sort-algorithms
/common_sort_utils.py
504
3.5625
4
from collections import Iterable from functools import wraps def iterables_only(func): """ Decorator validates that first argument is iterable :param func: sorting function taking iterable as a first argument :return: decorated function """ @wraps(func) def wrapper(iterable, *args, **kwar...
227bca03f7069184ca0375edc3ece2bb567549f5
neternefer/codewars
/python/longest.py
317
4.09375
4
def longest(s1, s2): """Given two strings, return the longest possible string with each letter from s1 and s2 appearing only once. Sort alphabetically. """ new_str = '' for letter in s1 + s2: if letter not in new_str: new_str += letter return ('').join(sorted(new_str))
fd2096519d43927e9351140271a5431817bd0a2b
adoption-loli/pygame_data_visualization
/readcsvfile.py
1,471
3.546875
4
import csv from pprint import * class data_list(): def __init__(self, filename): self.filename = filename self.datas = [] with open(filename, 'r', encoding='utf-8') as csv_file: self.reader = csv.reader(csv_file) for cell in self.reader: self.datas.a...
ead1e27717db743fbfa14b232a1ca9ef2b0b4895
opedro-c/calculadora
/utilitarios.py
731
3.75
4
from tkinter import messagebox as msg def formatar_expressao(expressao): if '**' in expressao: return expressao.replace('**', '^') elif '*' in expressao: return expressao.replace('*', 'x') return expressao def expressao_ok(expressao): if expressao.find('-') == 0: somente_num_...
fb36aa0e7e65c887559631f20b73b63e7642af42
ArthurSpillere/AulaEntra21_ArthurSpillere
/Exercícios Resolvidos/Aula10/exercicios/exercicio03.py
2,250
4.03125
4
# """Exercício 03 # 3.1) Crie um programa que cadastre o id, nome, sexo e a idade de 5 clientes. # 3.2) Depois mostre os dados dos 5 clientes. # 3.3) Peça para que o usuário escolha um id de um cliente e mostre as informações deste cliente. # 3.4) Crie um filtro que ao digitar um id de um cliente mostre as seguinte...
a8eade4329bbcfa12a1d9392b87ca4c1087c9eeb
Roc-J/LeetCode
/300~399/problem349.py
496
4
4
# -*- coding:utf-8 -*- # Author: Roc-J class Solution(object): def intersection(self, nums1, nums2): """ :type nums1: List[int] :type nums2: List[int] :rtype: List[int] """ result = [] nums1 = list(set(nums1)) nums2 = list(set(nums2)) for item...
db7239c12cf0f22c61df82e08b5ac75f2300d0ee
Rutrle/python-tryouts
/sorting.py
240
4.03125
4
my_list = ['Praha', 'Brno', 'Ostrava'] # sort by second letter my_dict = {} ''' for i in range(len(my_list)): print(my_dict[my_list[i][2]]=) ''' my_list.sort() sorted_vals = sorted(my_list, reverse=True) print(my_list, sorted_vals)
edbe8ec7edd5aa6cc3e30df534ebf942beeacf94
thomascottendin/GeeksforGeeks
/Medium/multiply2Strings.py
562
4.25
4
#Given two numbers as stings s1 and s2 your task is to multiply them. You are required to complete the function multiplyStrings which takes two strings s1 and s2 as its only argument and returns their product as strings. { #Initial Template for Python 3 if __name__ == "__main__": t=int(input()) for i in ...
56a10323c5ab97bafbecc24bf0a20059a47f0711
randyarbolaez/codesignal
/daily-challenges/validTime.py
210
3.84375
4
# Check if the given string is a correct time representation of the 24-hour clock. def validTime(time): hours = int(time[:2]) minutes = int(time[3:]) return hours < 24 > hours and minutes < 60 > minutes
d78c8dcdf8d0a666cbcd2a842ead27f1df53369a
vishnoiprem/pvdata
/lc-all-solutions-master/039.combination-sum/combination-sum.py
820
3.5625
4
class Solution(object): def combinationSum(self, candidates, target): """ :type candidates: List[int] :type target: int :rtype: List[List[int]] """ def dfs(nums, target, path, res): if target == 0: res.append(path + []) retu...
f1740d35afe605a24f251cb478cf8edc05fe25f4
EdwardTatchim/PythonProjects
/hw7_final.py
2,259
3.953125
4
import random class Player: def __init__(self,name): self.name = name self.position = 0 self.playerList = [] self.playerList.append(name) #self.red_start = int(input("How many red players do you want? ")) #self.blue_start = int(input("How many blue players do you want? ")) class RedPl...
f080018db0b2ddf2b1604974417db175a2d852c9
dkarthicks27/ML_Database
/codeforces/rewards.py
752
4.09375
4
from math import ceil if __name__ == '__main__': # lets find out the number of shelves available # so we know the number of medals and number of number of cups # first we check if there are atleast 2 shelves, one for each type # now we first calculate the number of medals, if # if medals = 15 ...
56d4eb892050e457cfaae7e78a0d2a9803ed2aa3
mhcrnl/Phonebook-20
/db_phonebook.py
1,301
4.125
4
import sqlite3 class Contact: def __init__(self): self.contact = input('Enter username: ') self.number = input('Enter phone number: ') class Phonebook: db = sqlite3.connect('Phonebook.sqlite3') c = db.cursor() def __init__(self): pass #self.contacts = Phonebook.c.e...
e31aa8252c0fbb783203e317fb7adc26ec5a88c2
hakanguner67/class2-functions-week04
/reading_number.py
525
4.3125
4
''' Write a function that gives the reading of entered any two-digit number. For example: 28---------------->Twenty Eight ''' small_numbers = ["One","Two","Three","Four","Five","Six","Seven","Eight","Nine"] big_numbers = ["Ten","Twenty","Thirty","Fourty","Fifty","Sixty","Seventy","Eighty","Ninety"] def reading_numbe...
9a5c7031c81722f2c910d31c5be7c1c2f4925caf
choroba/perlweeklychallenge-club
/challenge-181/lubos-kolouch/python/ch-1.py
906
3.765625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- def order_sentence(paragraph: str) -> str: sentences = paragraph.split(".") ordered = [] for sentence in sentences: if sentence.strip() == "": continue words = sorted(sentence.split()) ordered.append(" ".join(words) + ".") ...
4f8d091dff68c6b6ffc80142fd838d5fbe73a1bc
TheAlgorithms/Python
/strings/boyer_moore_search.py
2,742
4.125
4
""" The algorithm finds the pattern in given text using following rule. The bad-character rule considers the mismatched character in Text. The next occurrence of that character to the left in Pattern is found, If the mismatched character occurs to the left in Pattern, a shift is proposed that aligns text block and pa...
294b3b0f33fa9441c74e627c64478d2a6fb9762e
phillipad7/RideCrossRiver
/start_search_ui.py
2,731
3.921875
4
import bunch_outputs def get_num_of_addresses() -> int: ''' Return the number of addresses the search will encounter ''' while True: try: num_of_addresses = int(input()) if num_of_addresses > 1: return num_of_addresses else: ...
b145b007ce225549565552ec9848af78d752f5a6
venkatmanisai/Sosio_tasks
/Sosio/find_angle_MBC.py
119
3.6875
4
import math a = float(input()) b = float(input()) print(str(int(round(math.degrees(math.atan2(a,b)))))+'°')
f3dcd01e01a9b4f5b10b4194793102223ae5b842
jim-huang-nj/BeginningPython
/MagePython/Chapter3/3-9.py
446
3.5625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ @author: Jim Huang @contact:Jim_Huang@trendmicr.com @version: 1.0.0 @license: Apache Licence @file: 3-9.py @time: 2020/12/1 16:31 """ import random import string words = [] counter = {} alpha = string.ascii_lowercase for _ in range(100): words.append(random.choic...
d6fc9277b1232dd4823bd7b8e583ad36e35dff29
friedlich/python
/19年7月/7.13/实例037:排序.py
383
3.71875
4
# 题目 对10个数进行排序。 # 程序分析 同实例005。 raw = [] for i in range(10): num = int(input('int{}:'.format(i))) raw.append(num) for i in range(len(raw)): for j in range(i,len(raw)): if raw[i] > raw[j]: # raw[i]要放前面,因为第一个raw[i]是raw[0],是依照raw[i]来排序的 raw[i],raw[j] = raw[j],raw[i] print(raw)
8175002f0a03ba19ac5fd536af4d62fc58938555
whywhs/Leetcode
/Leetcode409_E.py
493
3.734375
4
# 最长回文串。这个题目就是需要统计偶数次的个数,但是注意的是对于奇数次的不是不统计而是减一即可。 class Solution(object): def longestPalindrome(self, s): """ :type s: str :rtype: int """ l = 0 for i in set(s): num = s.count(i) if num%2==0: l += num else: ...
9be652ba391fc654c3df3cb454ce2f6c293992c9
Rickym270/rickym270.github.io
/data/projects/InterviewStudying/DailyCodingChallenge/April202022.py
2,491
4.21875
4
''' A unival tree (which stands for "universal value") is a tree where all nodes under it have the same value. Given the root to a binary tree, count the number of unival subtrees. For example, the following tree has 5 unival subtrees: 0 / \ 1 0 / \ 1 0 / \ 1...
882a93ac2d818ba1faa047660a5b3045842811a1
adilshivakumar/Raspberry-Pi
/clock.py
503
3.78125
4
import time from datetime import datetime def clock(): """ Display current time on device. """ interval = 0.5 seconds = 5 cl = "" for i in range(int(seconds / interval)): now = datetime.now() cl = cl + now.strftime("%H-%M-%S") + "\n" # calculate blinking dot ...
42e3403c5f66f88146b568daf3da2a879e17fa9f
lokesh-rajendran/python-datastructures-algorithms
/arrays/sorted_squared_array.py
877
4.15625
4
""" Write a function that takes in a non-empty array of integers that are sorted in ascending order and returns a new array of the same length with the squares of the original integers also sorted in ascending order. Sample Input array = [1, 2, 3, 5, 6, 8, 9] Sample Output [1, 4, 9, 25, 36, 64, 81] """ import pytest ...
42e811965908b4f58f0f52d91f9f32c470564b8c
ysung/UCD
/Algorithm/python/twoSum.py
2,811
3.5
4
#!/usr/bin/python Two Sum, Complexity: O(N log N) class Solution: # @return a tuple, (index1, index2) def twoSum(self, num, target): #targetList = [i for i in num if i <= target] numbers = sorted(num) head = 0 tail = len(num)-1 while (numbers[head] + numbers[t...
cdef74d4bebe249c2603bee436a215a6302681ea
parveez1shariff/Python-Testing
/Infi_arug.py
315
3.8125
4
# This code is to create a function with infinite parameter/arguments def mean(*arg): Mn = sum(arg)/len(arg) return Mn print(mean(2,4,9,8)) def str_infi(*arg): st = [] for temp in arg: st.append(str(temp).capitalize()) st.sort() return st print(str_infi("hello", "apple"))
e68c9c91b2204fd09c20beb88acb6d0649655636
hanzhi713/thinkcs-python3-solutions
/Chapter 18/1.py
503
3.59375
4
import turtle Tom = turtle.Turtle() Tom.speed(0) Tom.hideturtle() sc = turtle.Screen() def koch(t, order, size): if order == 0: t.forward(size) else: for angle in [60, -120, 60, 0]: koch(t, order - 1, size / 3) t.left(angle) def shape(t, order, size, sides): for ...
a77746a03ea733d9dcd85830d5ef0bdfdbfe2165
joaopedropinheiro12/IntroPython
/aula8_Joao_Pedro.py
964
3.734375
4
#AULA 8 #JOÃO PEDRO GOMES PINHEIRO #03 de novembro de 2018 import math #EXERCÍCIO 1 print('Exercício 1: ') n = 600 while (n>1): print(n) if n % 2 == 0: n = n/2 elif n % 2 == 1 and n != 1: n=3*n+1 print(n) #EXERCÍCIO 2 print('Exercício 2: ') def counter(n): count = 0 while n!=0: if n % 5 == 0: c...
034fe0cbde4c81adda986b9ec3955acd08aab48b
Kanino19/LearnPython
/operadores.py
885
4.0625
4
# OPERADORES # ----- Datos ----- a = 3 b = 4 c1 = 'Hola' c2 = 'Comida' bT = True bF = False # == : Igualdad # = es de asignación (Guardar información) # La igualdad me brinda boleanos (es decir True o False) print(a==b) print(c1 == c2) print(c1 == 'Hola') print(bT == bF) # Notita: estos pueden ser us...
77acd760c52a24aaf2d9b8d733d681ae6b3f114f
zongyi2020/CMEECourseWork
/week2/code/cfexercises1.py
1,270
4.1875
4
#~!/usr/bin/env python3 """Some functions doing arithmatic.""" __appname__ = 'cfexercises1' __author__ = 'Zongyi Hu (zh2720@ic.ac.uk)' __version__ = '0.0.1' import sys """function sqrt""" def foo_1(x = 1): return x ** 0.5 foo_1(3) foo_1(9) foo_1(49) """function compare two numbers""" def foo_2(x=1, y=1): i...
bc2e151f43088a16e74f43fa5f5c46ddf7e0ce78
redx14/LeftOrRightArrow
/LeftorRightArrow.py
1,420
4.15625
4
#Andrey Ilkiv midterm exam question 2 direction = input("Please enter a direction ( l / r ): ") cols = int(input("Please enter an integer (>=0): ")) while(direction != "l" and direction != "r"): print("Invalid Entry! Try Again!") direction = input("Please enter a direction ( l / r ): ") while(cols...
c686a5ca1fc60b2a9f1de02c1694edc2c5df9eb3
mankamolnar/python-4th-tw-mentors-life-crazy-edition
/llama.py
1,105
3.6875
4
import random from codecool_class import * class Llama: def __init__(self, name, color): self.name = name self.color = color self.softness = 10 def pet(self): self.softness -= 1 self.check_if_dead() def ride(self): self.softness -= 2 self.check_if...
c8943c684bb5f4f0cdbed7f513ee9e01fbb55e1a
csbuja/myCipher
/p1_robot.py
2,906
3.96875
4
import sys class Robot(object): def __init__(self): self.inputString = '' self.x = 0 self.y = 0 self.direction = 'N' def printBot(self): print (str(self.x) + ' ' + str(self.y) + ' ' + self.direction) def readIn(self): self.inputString = sys.stdin.readline().r...
48e69d600998dd9721c49840fd3da124ee6ed3c1
qianlongzju/project_euler
/python/PE055.py
392
3.546875
4
#!/usr/bin/env python def isPalindrome(n): if str(n)[::-1] == str(n): return True return False def isLychrel(n): count = 49 while count > 0: n += int(str(n)[::-1]) if isPalindrome(n): return False count -= 1 return True def main(): print sum(1 for i ...
125b8eac6b573eaa1095fcd47aa1be16d690d813
Nedashkivskyy/NedashkivskyyV
/Лабараторна 3 Недашківський.py
446
4.03125
4
height = int(input("Ваш рост")) weight = int(input("Ваш вес")) bmi = (weight/height**2)*10000 bmi2 = round(bmi,2) print('Ваш индекс массы тела:',bmi2) if bmi2 < 18.5: print('Ваш индекс массы тела ниже нормы') elif bmi2 > 24.9: print('Ваш индекс массы тела выше нормы') else: print('Ваш индекс массы...
426e2da138f2a8536ba201d2100fd5ce9f87ea5d
yiflylian/pythonstuday
/pythonstudy/basic/forandwhile.py
2,599
3.953125
4
#https://www.liaoxuefeng.com/wiki/1016959663602400/1017100774566304 print(r''' Python的循环有两种,一种是for...in循环,依次把list或tuple中的每个元素迭代出来,看例子: names = ['Michael', 'Bob', 'Tracy'] for name in names: print(name) 执行这段代码,会依次打印names的每一个元素: Michael Bob Tracy 所以for x in ...循环就是把每个元素代入变量x,然后执行缩进块的语句。 再比如我们想计算1-10的整数之和,可以用一个su...
ab3022f2d490978ad29a13b9d619d95559c1d0df
sandeepsharma1190/Numpy
/Numpy.py
2,491
4.09375
4
import numpy as np a = np.array([[1,2,3],[4,5,6]]) b = np.array([1,3,5], dtype = 'int16') print(a) a.ndim #to check dimension a.shape #to check shape a.dtype #to check datatype a.itemsize # for item size a.size #to get full size a = np.array([[1,2,3,4], [5,6,7,8]]) p...
3ac21d578e22c759c0a97b5beaec624333f236f9
abhi1540/PythonConceptExamples
/getter_setter.py
2,953
4.0625
4
class Employee(object): def __init__(self, emp_id, first_name, last_name, salary, age): self._emp_id = emp_id self._first_name = first_name self._last_name = last_name self._salary = salary self._age = age @property def emp_id(self): return self._emp_id ...
5b436941757a98c7bc3977f0ac5ac2ba153b881c
RunningLeon/ud120-projects
/text_learning/nltk_stopwords.py
380
3.578125
4
#!/usr/bin/python ###import nltk package and find how many stopwords from nltk.corpus import stopwords # import nltk # nltk.download() sw = stopwords.words("english") print len(sw) # for s in sw : # print s from nltk.stem.snowball import SnowballStemmer stemmer = SnowballStemmer( "english") print stemm...
e6cd92c79492d26c64a03e7b61ab7bed21204655
jennyChing/leetCode
/90_subsets2_recursive.py
1,596
3.78125
4
''' 90. Subsets II Given a collection of integers that might contain duplicates, nums, return all possible subsets. Note: The solution set must not contain duplicate subsets. For example, If nums = [1,2,2], a solution is: [ [2], [1], [1,2,2], [2,2], [1,2], [] ] ''' class Solution(object): def subset...
cbf1c010f7f496445febe0561ef4945c1893ed90
JordanVScher/Hangman-Text
/getWords.py
2,057
3.5625
4
#reads the json file and chooses a word #also responsible for difficulty and category from colorama import * import json import random import sys def getWords(dif = 0, cat = 0): if dif is 0: dif = askDifficulty() if cat is 0: cat = askCategory() return openFile(dif, cat) def openFile(dif...
bdbfc08945c47886350754ec91bbcfdb35a41851
justinm0rgan/python_work
/chp6/polling.py
784
3.9375
4
# Use the code in fav_languages.py # Make a list of people who should take the favorite languages poll. # Include some names that are already in the dictionary and some that are not. # Loop through the list of people who should take the poll. # If they have already taken the poll, print a message thanking them for resp...
bb714a76db3bc5ad360b5eed7e1920d030f2fc11
TsaiRenkun/coffee_machine_python
/Problems/Count up the squares/task.py
208
3.78125
4
# put your python code here number = [] num = 0 squareSum = 0 while True: num = int(input()) squareSum = squareSum + (num ** 2) number.append(num) if sum(number) == 0: print(squareSum) break
6618b693a1d0232df8c02aa63a3ad531ca296da1
madanreddygov/Python-WorkSpace
/Dictionaries and Sets/challenge.py
123
3.71875
4
myText = input("Please enter some text: ") myList = set(myText).difference("aeiou") print(myList) print(sorted(myList))
1202b7d083debdfc861f8a1fc63a0c63c2c860dd
Krushnarajsinh/MyPrograms
/VariableTypesInOops.py
2,035
4.40625
4
#Two types of variables:-(1)class variable AND (2)Instance variable class Student: class_name="A" #The variables define outside the __init__() is called as class or static variables def __init__(self,roll_no,marks): self.roll_no=roll_no #instance variables always define inside __init__()method ...
f8c16333890a876379ed0675e6e552bcb9ce5478
HRDI0/This_is_coding_test
/#This is coding test-imp_6.py
533
3.828125
4
#문자열 재정렬 #알파벳 대문자와 숫자(0~9)가 섞여서 입력된다. 이때 모든 알파벳을 오름차순으로 출력한후 모든 숫자를 더한 값을 뒤에 출력한다. word = input() alpha = [] num = 0 for char in word: if char.isalpha(): alpha.append(char) else: num +=int(char) alpha = sorted(alpha) # print(''.join(alpha),num,sep='') #숫자가 없는 경우 이렇게 하면 뒤에 0이 출력된다. if num ...
ac335d464c0ad3fc2b5168e83771284cf67f4c2d
ConorODonovan/pa2-elevator-project
/Elevator_Project/Building.py
1,606
4.15625
4
from Elevator import Elevator from Customer import Customer import random class Building: def __init__(self, floors): self._floors = floors self._customers_waiting = [] self._customers_arrived = [] def __str__(self): return "Building with {} floors".format(self.f...
468f499b2240e3dde1ca3122b4ec8e27f5b87c4a
massey-high-school/2020-91896-7-assessment-phamm72230
/04_Rectangle_Solver.py
500
4
4
# Rectangle def arearectangle(w, l): # Calculate the area arearectangle = w * l return arearectangle def perimeterrectangle(w, l): # Calculate the perimeter perimeterrectangle = 2 * (w + l) return perimeterrectangle def mainrectangle(): w = float(input('Enter width of Rectangle: ')) l ...
39504847f097369fa955ac01c62abe446eb12f5b
LennyDuan/AlgorithmPython
/56. Merge Intervals/answer_po.py
1,434
3.640625
4
## Possible but too much if else def merge(self, intervals): res = [intervals[0]] for interval in intervals[1:]: c_start, c_end = interval[0], interval[1] for merged in res: print('current: {}'.format(interval)) print('merged: {}'.format(merged)) m_start, m_e...
8e68038743d336dbc4808e603a4fc808d6466f91
kienvu98/thuc_tap
/100 bài code/50_59ex/ex50.py
1,518
3.515625
4
import re import sys import os from signal import signal, SIGPIPE, SIG_DFL signal(SIGPIPE,SIG_DFL) def sent_segment(a_string): sentences = [] regx = re.compile(r'([\.;:\?!])\s+([A-Z])') m = regx.search(a_string) last_pos = 0 pos = m.start() if m != None else None while ( pos != None ): ...
2d1c32c717a4c2483a7ef71cb0582351f47b94bd
jjst/advent-of-code-2017
/day8/day8.py
734
3.5625
4
#!/usr/bin/python3 from collections import defaultdict def execute_instruction(instruction, registers): instr, condition = instruction.split(" if ") condition_register = condition.split(" ")[0] if eval(condition.replace(condition_register, str(registers[condition_register]))): register_to_change, i...
a36e80908a5509eb95316bb0ef3741716c5fe69e
aslastin/Python-Stepik
/04-namespaces/main.py
545
3.5
4
def createNs(d, ns, parent=None): d[ns] = {'Vars': set(), 'Parent': parent} def getNs(d, ns, var): if ns in d: cur = d[ns] if var in cur['Vars']: return ns return getNs(d, cur['Parent'], var) return None n = int(input()) d = {} for i in range(n): op, ns, arg = inp...
0c1069a8bcdf0080df86f31608a22c6749187f06
tiscal404/PyPNB
/Aula02/exercicio-06.py
364
3.609375
4
#! /usr/bin/python3.6 def calctempoviagem(s,vm): try: t = float(s) / float(vm) return 'Tempo estimado da viagem: {}h'.format(t) except: return 'Algo deu errado. Por favor tente novamente!' dist = input('Qual distância irá percorrer?(Km)') vm = input('Qual a velocidade média estimada? (...
be76fab871ad656d0e22374116d1fb3a9370be08
LongNguyen1984/biofx_python
/01_dna/solution5_dict.py
1,835
3.703125
4
#!/usr/bin/env python3 """ Tetranucleotide frequency """ import argparse import os from typing import NamedTuple, Dict class Args(NamedTuple): """ Command-line arguments """ dna: str # -------------------------------------------------- def get_args() -> Args: """ Get command-line arguments """ par...
f6e6c3ed2e0cb328177a8b16076b5138b4819533
JonWofr/nst-methods-quantitative-comparison
/scripts/helper/resize-images.py
2,501
3.65625
4
import os from PIL import Image import argparse parser = argparse.ArgumentParser(description='Script to resize the images. If only one of the two options --smaller-side-size, --larger-side-size is provided the size of the other side will be calculated according to the aspect ratio. If both are provided the smaller sid...
83dcb07649e99b9714bee231748bedd26cbd916c
ArnaudBD/pythonModule00
/ex06/recipe.py
2,933
4.125
4
import sys cookbook = { 'sandwich': {"ingredients": ["ham", "bread", "cheese", "tomatoes"], "course": "lunch", "cookingTime": 10}, 'cake': {"ingredients": {"floor", "sugar", "eggs"}, "course": "dessert", "cookingTime": 60}, 'salad': {"ingredients": {"avocado", "aru...
5fbf63b1c2cc91a5f96d1cc240fd51d9f3f0df92
arthurdamm/algorithms-practice
/interview/fields_and_towers_3.py
794
4.03125
4
#!/usr/bin/env python3 """ Field and Towers interview question algorithm O(n*log(m)) time complexity implementation """ def max_field_3(fields, towers): """ Finds minimum-distant tower for each field with binary search and returns the max of these """ return max([min([abs(field - tower) for tower ...
967425469f06205a8fff3b3852a231c4bb1d735b
MrHamdulay/csc3-capstone
/examples/data/Assignment_3/alhada001/question4.py
357
3.921875
4
number = input("Enter the starting point N:\n") number2 = input("Enter the ending point M:\n") print("The palindromic primes are:") for i in range(eval(number)+1,eval(number2)): f = len(str(i)) number3 = str(i) tnum = "" for p in range (f): tnum = tnum + number3[(f-1)-p] if st...
1962d5604182bc7c8b4b236d54274987230e34fb
SergeiLSL/PYTHON-cribe
/PyCharm на русском/Быстрые клавиши.py
3,121
3.5
4
""" Сочетания клавиш PyCharm Последнее изменение: 9 июня 2021 г. Все сочетания клавиш для распечатки https://resources.jetbrains.com/storage/products/pycharm/docs/PyCharm_ReferenceCard.pdf?_ga=2.62503919.219908342.1625490948-2092108925.1610216984 """ """ PyCharm имеет сочетания клавиш для большинства команд, связанн...
d0c7bcfcc8d3ca4a00617de032012e13a5e7f47d
morzianka/FirstRepo
/venv/common/Main.py
1,540
3.828125
4
from common import AddCommand,Command,DeleteCommand,ShowAllCommand,\ ShowByCategoryCommand,ShowByMinMaxCommand,ShowForDateCommand,ExitCommand import datetime def askOperation(): print("1 - ADD\n" + "2 - SHOW ALL\n" + "3 - SHOW FOR DATE\n" + "4 - SHOW BY CATEGORY\n" + "5 - SHOW B...
47a42ccb4b92175e93f6da724cae41b965f6a094
vids2397/vids2397
/Day 1/exercise7.py
151
3.90625
4
my_list = ["ramu", "shyamu", "kanu", "manu","ramu","radha", "manu"] print("The given list is" +str(my_list)) my_list = my_list(set(my_list)) print("
fcd088e9290335be0a5fc9efb277757f92f62031
Wangsherpa/data-structures---algorithms
/0-Unscramble Computer Science Problems/Task4.py
1,424
4.1875
4
""" TASK 4: The telephone company want to identify numbers that might be doing telephone marketing. Create a set of possible telemarketers: these are numbers that make outgoing calls but never send texts, receive texts or receive incoming calls. Print a message: "These numbers could be telemarketers: " <list of number...
12ae99a77abfca6c7634c7b005a2879cf23c0ea5
mag389/holbertonschool-higher_level_programming
/0x06-python-classes/100-singly_linked_list.py
1,913
3.84375
4
#!/usr/bin/python3 """file for sinlgy linked lists """ class Node: """" Node class for linked lists""" def __init__(self, data, next_node=None): """initializer for node""" self.sdata(data) self.snext_node(next_node) def gdata(self): """ getter for data""" return s...
e0a2a9f73df458f0aa6b3f7c0d61359cb4395639
doingmathwithpython/code
/chapter7/solutions/length_curve.py
812
4.09375
4
''' length_curve.py Find the length of a curve between two points ''' from sympy import Derivative, Integral, Symbol, sqrt, SympifyError, sympify def find_length(fx, var, a, b): deriv = Derivative(fx, var).doit() length = Integral(sqrt(1+deriv**2), (var, a, b)).doit().evalf() return length if __name__ =...
c07a761b82c38b92dc8228afaf33990dc834293e
ZenSorcere/ITC255-SystemsAnalysis-Kiosk-Code
/Kiosk/itemclass.py
1,037
3.578125
4
class Item(): #constructor taking in initial values def __init__(self, name, number, price, weight, restricted): self.name=name self.number=number self.price=price self.weight=weight self.restricted=False #boolean somehow? should it be in init? #get methods...
06573cdd63ffa43e19dd4944e5cd0ae0c3455a7c
jaford/thissrocks
/Python_Class/py3intro3day/EXAMPLES/getting_dict_values.py
736
3.671875
4
#!/usr/bin/env python d1 = dict() airports = {'IAD': 'Dulles', 'SEA': 'Seattle-Tacoma', 'RDU': 'Raleigh-Durham', 'LAX': 'Los Angeles'} d2 = {} d3 = dict(red=5, blue=10, yellow=1, brown=5, black=12) pairs = [('Washington', 'Olympia'), ('Virginia', 'Richmond'), ('Oregon', 'Salem'), ('California',...
316ce359249231c99fbe511ce0518e2cc4374815
sauravgsh16/DataStructures_Algorithms
/g4g/DS/Trees/Binary_Trees/Summation/20_difference_of_sum_between_even_and_odd_levels.py
1,039
3.984375
4
''' Difference between sums of odd level and even level nodes of a Binary Tree ''' class Node(object): def __init__(self, val): self.val = val self.left = None self.right = None # Idea is to do level order traversal def diff_odd_even_levels(root): if not root: return 0 ...
4d46dadf5fedf347b129825382c86d6bad8a7705
StudyForCoding/BEAKJOON
/30_UnionFind/Step03/wowo0709.py
688
3.546875
4
import sys input = sys.stdin.readline def find(x): if not isinstance(parent[x],str) and parent[x] < 0: return x p = find(parent[x]) parent[x] = p return p def union(x,y): x = find(x) y = find(y) if x == y: return if parent[x] < parent[y]: parent[x] += parent[y] ...
b284b2a58e1e27fb765601054577d3ed50751b37
deepakjain61/dj_private
/database.py
654
3.953125
4
import sqlite3 conn = sqlite3.connect('user.db') """ print "Opened database successfully"; conn.execute('''CREATE TABLE user_info (id INTEGER PRIMARY KEY AUTOINCREMENT, user_name TEXT NOT NULL, age INT, country CHAR(50), email_id TEXT, phone_no TEXT, password TE...
b120c6b11b399427775891db4fc59f7f35d49081
DomainRain/civsim
/person.py
5,041
3.734375
4
import names import random import sqlite3 import resources from sqlalchemy import Column, Integer, String from sqlalchemy import ForeignKey from sqlalchemy.orm import relationship from base import Base class Person(Base): __tablename__ = 'people' children = relationship("Children") resources = relationshi...
25afdb4439dbc9173dda71117f164cdc59409dd4
jujujuanpi/Programacion2020-2
/Talleres/Taller3.py
2,980
4.0625
4
# FUNCIONES DE NÚMERO MAYOR a = int (input ("Ingrese el primer número: ")) b = int (input ("Ingrese el segundo número: ")) def numero (numero1, numero2): if a > b: print (f"El primer número, {a}, es mayor que el primer número, {b}.") elif b > a: print (f"El segundo número, {b} es mayor que el ...
c9dd47ec1ab9c69276462e79dcf18a91ac3ecd28
keagyy/tictactoe-xtream
/tictactoe3.py
4,522
3.53125
4
def tic_tac_toe(): board = [1, 2, 3, 11, 12, 13, 21, 22, 23, 4, 5, 6, 14, 15, 16, 24, 25, 26, 7, 8, 9, 17, 18, 19, 27, 28, 29, 31, 32, 33, 41, 42, 43, 51, 52, 53, 34, 35, 36, 44, 45, 46, 54, 55, 56, 37, 38, 39, 47, 48, 49, 57, 58, 59, 61, 62, 63, 71, 72, 73, 81, 82, 83, 64, 65, 66, 74, ...
2abd3789db22f7bc936aa42a352651c04ef2d454
mithro/scheduler-simulator
/scheduler.py
29,531
3.515625
4
#!/bin/env python3 import unittest from collections import deque infinity = float("inf") class bdeque(deque): def front(self): return self[0] def front_pop(self): return self.popleft() def back(self): return self[-1] def back_pop(self): return self.pop() def back_push(self, x): retu...
56b21160ce35e6053c0df0abaa44ff38853c2ab1
librallu/uqac-visu-projet
/test.py
1,855
3.53125
4
file_name = 'off' class Data: """ extracts data from csv. """ def __init__(self, filename): """ filename: string for the csv file """ self.data_fields = {} # name -> int self.data_fields_order = [] self.data = [] with open(filename) as f: ...
180d141afcf454a45d851523b6dd33f1d7cd0a72
eessm01/100-days-of-code
/e_bahit/closures.py
2,657
4.40625
4
"""The Original Hacker No.3. Closures Un closure es una función que define otra función y la retorna al ser invocado. Un closure DEBE tener una razón de ser. De hecho, mi consejo es evitarlos toda vez que sea posible resolver el planteo sin utilizarlos. Pues dificulta la lectura del código y su entendimiento, cuand...
98191417bad7ee69c480cbf8ff9d24956c9783b0
Shakar-Gadirli/hyperskill
/Tic-Tac-Toe/tictactoe/tictactoe.py
2,482
3.859375
4
temp_moves = list(input("Enter cells:")) rows = [[temp_moves[j] for j in range(i, i + 3)] for i in range(0, len(temp_moves), 3)] class Game: def __init__(self, cells): self.cells = cells self.is_finished_state = True self.x_win = False self.y_win = False self.x_count = 0 ...
a302b17af34912d4c12fac477398b821c2affd72
Ahm36/pythonprograms
/CO1/program6.py
168
3.8125
4
#6numofa li=[] c=0 for i in range (3): x=input("enter first names:") li.append(x) for i in li: for j in i: if 'a' in j: c=c+1 print("number of a's :",c)
9470bb76e7432edcf89f5f7a3c78a9e9d63e5da4
Aasthaengg/IBMdataset
/Python_codes/p02263/s396876043.py
238
3.5625
4
data = input().split() operator = ["+", "*", "-"] stack = [] for x in data: if x in operator: a = stack.pop() b = stack.pop() stack.append(str(eval(b + x + a))) else: stack.append(x) print(stack[0])
212ee04b83e8c9c97d42f5eafb4155c4cdb1e02a
rockchalkwushock/pdx-code-labs
/average_numbers.py
429
4.09375
4
nums = [] def avg_nums(nums): running_sum = 0 for num in nums: running_sum += num print(f'The new sum is: {running_sum}.') print(f'The average is: {running_sum / len(nums)}.') while True: query = int(input('1: Enter a number\n2: Average\n\n')) if query == 1: num = int(in...
d79d49b2d719168e64ec938a290afdb28fd3ee02
Sh2rif/python
/condtions.py
190
3.734375
4
username = input ('Please insert your username') password = input ('Please insert your password') if username == 'sharif' and password == '123': print('welcome') else: print('Error')
d81dc05cd8afa0ddec68ffe058a8e44ab4b7e643
DCUniverse1990/01_Recipes
/04_Ingredients_List.py
1,356
4.125
4
# Ingredients list # Not blank Function goes here def not_blank(question, error_msg, num_ok): error = error_msg valid = False while not valid: response = input(question) has_errors = "" if num_ok != "yes": # look at each character in sting and if its a number, complai...
7f43a201f237f0e05ea8470f3691dec182e47f45
wonanut/LeetCode-2020
/src/2020-01/week4/46-permutations.py
555
3.84375
4
""" 46:全排列 链接:https://leetcode-cn.com/problems/permutations/ 难度:中等 标签:dfs 评价:dfs模板,必须掌握! """ class Solution(object): def permute(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ def dfs(nums, path): if not nums: ans.append(path) ...
3787c9aa583d24e924b56df40752ec1eb436cdb9
4evernewb/ReLU-function
/main.py
117
3.78125
4
def relu(a): return max(a,0) i = int(input("Enter a number to find the relu function of it. ")) print(relu(i))
1979004da4a8da3f91a1f07212bb0b5a8d5e00a4
matthew-david-hawkins/python-challenge
/PyBank/main.py
3,218
4.15625
4
# To add a new cell, type '#%%' # To add a new markdown cell, type '#%% [markdown]' #%% #Overview: # In this challenge, you are tasked with creating a Python script for # analyzing the financial records of your company. You will give a # set of financial data called budget_data.csv. The dataset is composed # of two...
ace32b1335f1b0e9e4acdc0e64338799a6bd5ea4
jianhanghp/LeetCode
/102. Binary Tree Level Order Traversal.py
1,664
3.9375
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None # my sol1, using queue # class Solution: # def levelOrder(self, root: TreeNode) -> List[List[int]]: # q = collections.deque() # if root: ...
5eb2cb4485a3c3088ae0c3fce1c9483f7820f371
Coliverfelt/Desafios_Python
/Desafio029.py
493
4.15625
4
# Exercício Python 029: Escreva um programa que leia a velocidade de um carro. # Se ele ultrapassar 80Km/h, mostre uma mensagem dizendo que ele foi multado. # A multa vai custar R$7,00 por cada Km acima do limite. velocidade = float(input('Digite a velocidade (KM): ')) if velocidade > 80: print('Você foi multado ...
765bb20874de208036e97675cf90edf5552b3bd0
tmeasday/phd-code
/Tournaments/Data/Synthetic/edge_crossings.py
1,237
3.609375
4
#!/usr/bin/env python # encoding: utf-8 """ edge_crossings.py Created by Tom Coleman on 2007-08-29. Copyright (c) 2007 The University of Melbourne. All rights reserved. """ import sys import os import random def main(): n_0 = int (sys.argv[1]) m = int (sys.argv[2]) p = float (sys.argv[3]) n_1 = n_0 # could do s...
531d02c12a5beaa55b156528fee372ace35edd19
AnshumaJain/MasteringPython
/Data_structures/add_two_numbers.py
1,720
3.703125
4
""" LeetCode Problem #2. Add Two Numbers You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list. You may assume the two numbers do not contain any leading...
0e52ac561374d89cd4dee17a130416fdd2e9da5a
Andrey-A-K/hw_python_oop
/homework.py
3,625
3.5
4
import datetime as dt class Record: def __init__(self, amount, comment, date=None): self.amount = amount self.comment = comment if date is None: self.date = dt.datetime.now().date() else: self.date = dt.datetime.strptime(date, '%d.%m.%Y').date() class Calc...
ca93590acafd4fe2998867e3d48d2cbbc7c07bb6
badordos/Doliner-labs-Python-2018
/3) Ветвление/task9.py
537
4.15625
4
#Дано трехзначное число. #Cоставьте программу, которая определяет, есть ли среди его цифр одинаковые. x = int(input('Введите трехзначное число')) xn = str(x) res = list(xn) res[0] = int(res[0]) res[1] = int(res[1]) res[2] = int(res[2]) if (res[0]==res[1] or res[0]==res[2] or res[1]==res[2]): print ('В числе есть...
c3fb934aeaf8e5e96b2695f7969ce0ad1ae2a20b
dannycrief/full-stack-web-dev-couse
/Web/B/5/5.10/first.py
743
4.125
4
class Node(object): def __init__(self, value=None, next_node=None): self.value = value self.next = next_node def __str__(self): return f"[Node with value {self.value}]" def print_linked_list(head): cur = head while cur is not None: cur = cur.next return head def ...
8f0c5da89cd31caa7e91268ca9b74c3a08dae54c
hminah0215/pythonTest
/day0420/ex06.py
1,047
3.71875
4
""" n = 0 while True : print("hello") n = n + 1 if n == 3 : break """ # 연습 # 사용자에게 정수를 입력받아 그 수가 몇자리 수 인지 판별하여 출력합니다(이번엔 반복문이용) n = int(input("숫자를 입력하세요 ==> ")) cnt = 0 while True : n = n // 10 cnt = cnt + 1 if n == 0 : break print (cnt) # 연습 # 0~9999 사이의 정수를 입력받아 그 수가 몇자리 ...
643eef8ce7622e1546cdee2f32dfbc1a43223035
tengzejun508/pytestActualCombat
/pythoncode/calculator.py
388
3.6875
4
class Calculator(): def add(self, a, b): return a+b def sub(self, a, b): return a - b def mult(self, a, b): return a * b def divid(self, a, b): try: return a / b except ZeroDivisionError as e: return "除数不能为0" # if __name__ == '__main__...