blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
04dbf5bed84307be97d3d79497059d11d313adcc
kev0960/ProjectEuler
/14/14.py
682
3.640625
4
collatz = {} longest = 1 longest_cnt = 1 for i in range(1, 1000000): cur = i current_chain = [cur] last_step = -1 while cur != 1: if cur in collatz: last_step = collatz[cur] break if cur % 2 == 0: cur = cur // 2 else: cur = 3 * cur...
d3b9a8641104d1f2c6a8e9f3981894b696bbbd51
elenildo1/pythonProject
/Aula2 - Vaiaveis.py
555
4.0625
4
#Variaveis a = float(input("Entre com o primeiro numero :")) b = float(input("Entre com o segundo numero :")) soma = a + b #soma subtracao = a - b multiplicacao = a * b divisao = a / b resto = a % b #resto print("A soma de ", a, " + ", b," = " , soma) print("A subtracao de ", a, "-", b, "=" , subtracao) print("A D...
7f281afb8635e411fd3f5feba9973b2e321733f1
guillermd/Python
/Learning Projects Python/Ejercicios/Funciones/ejercicios2.py
1,239
3.84375
4
''' Escriba una funcion es_bisiesto() que determine si un año determinado es un año bisiesto.Un año bisiesto es divisible por 4, pero no por 100. =================================================== def es_bisiesto(anyo): if(anyo%4==0 and anyo%4!=100): return("El año es bisiesto") return("El año no es...
6d5d7ac1da17a69f901812babfdd3d3f3a0f221a
ArthurBrito1/MY-SCRIPTS-PYTHON
/Desafios/desafio27.py
356
3.90625
4
import random print('A maquina esta pensando em um numero de 0 a 5... adivinhe se for capaz hehehehe') numero = random.randint(0,5) digite = int(input('Digite um numero de 0 a 5 seuu lixo:')) if numero: print('DROGAA!! mizeravel gurreiro voçê passou pelo desafio!') else: print('Voçê é um fracassoe e será...
dc8afd52235100312fffaa0e68e0e2be8565d40b
chlloyd/maya-model-asset-checker
/assetchecks/image/filesize.py
693
3.609375
4
import os def image_file_size(sourceimages_path, min_image_size=100000): # File size, small being useless file """ Args: sourceimages_path:Path for sourceimages folder min_image_size:Defaulting to 10000 bytes (100KB), this sets the minimum image size. Returns:A list of all images with p...
583ccaead0a51dac74d9d4b0a6037fcee94c6ec0
juliakyrychuk/python-for-beginners-resources
/final-code/debugging/functions.py
208
3.875
4
def add(x, y): """Add two numbers together and return result.""" result = x + y return result output_prefix = 'Total:' total = add(7, 3) message = f'{output_prefix} {total}' print(message)
6aad83aafd452319c09635ba4b99b1f3cfb87122
Nadine-Waggoner/Python
/TextAdventure.py
5,448
4.21875
4
start = input("Type 'start' to begin adventure. Type anything else to exit. ") if start == "start": print(""" You find yourself standing in a foot of murky black water. Dim green light comes from a source somewhere behind you. You're wearing boots, a thick waterproof coat, and at your waist is a sheath...
1b06ddc7dc6f4e14ec69665d1b6ba3f1d318d155
aly22/cspython
/week1/circle_area.py
134
4.4375
4
pi=3.14159 radius=(float(input("Please enter the radius of the circle: "))) area=radius**2*pi print("The area of the circle is:",area)
e96eeeb67d8ced9462532592660918841aea3715
lotterombaut/LotteRombaut_Oefeningen_BasicProgr
/OefQWeek/Week05/Oef01.py
371
4.03125
4
#Maak volgende tuplesaan: # tuple1 # met de elementen 1NMCT, 2NMCT, 3NMCT # -tuple2 # met de elementen 1Devine, 2Devine,3Devine # -tuple3 # met elementen van verschillende datatypes: “test”, True, 3.2 , 1 tuple1 = ("1NMCT", "2NMCT", "3NMCT") tuple2= ("1Devine", "2Devine","3Devine") tuple3 = ("test", True, 3.2 , 1) pr...
bd9f2c8045f8957dca20747de0a803937e687a38
sphinx2001/gb-python-course
/lesson1/task3.py
338
4.09375
4
''' 3. Узнайте у пользователя число n. Найдите сумму чисел n + nn + nnn. Например, пользователь ввёл число 3. Считаем 3 + 33 + 333 = 369. ''' n = int(input("Введите n: ")) # сократим формулу :) num = 3 * n + n * 20 + n * 100 print(num)
c8a2dc5529def788ce82c280d266c942d439b61e
Dioclesiano/Estudos_sobre_Python
/Exercícios/ex028 - Usando Random e Sleep.py
1,672
4.40625
4
''' Escreva um programa que faça o computador "pensar" em um número inteiro entre 0 e 5 e peça para o usuário tentar descobrir qual foi o número escolhido pelo computador. O programa deverá escrever na tela se o usuário venceu ou perdeu. import random n = int(input('Digite o número do seu bilhete: ')) c = random.randi...
9948b8a163196deb629f55697810272ea29781ec
gregfabian/PythonNIIT
/NIIT.py
5,729
4.40625
4
'''convert celsius to fahrenheit''' # celsius=float(input("Enter temperature in celsius: ")) '''calculate tempersture in fahrenheit''' # fahrenheit= (celsius*1.8)+32 # print("%.2f celsius= %0.2f fahrenheit"%(celsius,fahrenheit)) # name = input("What is your name?: ") # print("Hello,",name,"you are welcome back!" ...
11baeb950fb3a978507fc81b2560359d0bd3c7ac
swain-s/lc
/-二叉树-二叉搜索树与双向链表.py
2,296
3.59375
4
# 问题描述:输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。要求不能创建任何新的结点,只能调整树中结点指针的指向 # 模板: 7 # 3 10 # 1 5 9 12 # 4 14 # from a_bin_tree import root, tin_travel class TreeNode(object): def __init__(self, val): self.val = val self.left = None ...
062d6ebb9850a8a608584e6c20e03dc01d975337
edoakes/bittorrent-simulator
/jellyfish_sampling.py
2,581
3.515625
4
import random import argparse parser = argparse.ArgumentParser(description='Simulate incrementally generating a random graph') parser.add_argument('--n', default=50, type=int, help='number of vertices') parser.add_argument('--k', default=10, type=int, help='edges per vertex') class Node(object): def __init__(self...
fd62663410da8d044ce8fda279b5df74007fa998
bgoonz/UsefulResourceRepo2.0
/_MY_ORGS/Web-Dev-Collaborative/blog-research/Data-Structures/1-Python/strings/domain_extractor.py
941
4.40625
4
""" Write a function that when given a URL as a string, parses out just the domain name and returns it as a string. Examples: domain_name("http://github.com/SaadBenn") == "github" domain_name("http://www.zombie-bites.com") == "zombie-bites" domain_name("https://www.cnet.com") == "cnet" Note: The idea is not to use ...
0e96f0088a883bb97cd51012977631c0e9b4d4d6
AhmedBreak-HM/Python
/python.py
417
3.703125
4
# helpe function # to get any information in python help(print) # first commit print('hello python','hello world') # change seprator print('python','sep',sep='>>>>>') # write in file # f=open('demofile.txt','w') # print('write in file', 'test',sep='***',file=f) # Variables # Variables is ref type to call new obj x=...
c91e9eaa751e33d380e8c5bcb31795681fa426fe
tsar0720/HW_python
/HW17/HW17.py
961
3.546875
4
""" Написать скрипт, который будет вытаскивать gps данные из фотографии (jpg файл) и передавать их на вход программе из hw16.txt """ """ pip3 install piexif pip3 install gpsphoto python3 -m pip install --upgrade Pillow """ from GPSPhoto import gpsphoto from HW16 import HW16 # использую модуль GPSPhoto data_one = gpsph...
aa3dbfe8cf83fc3c9d6dea0e9ee0c96dd1a0b97f
kvnrd/Heap-Sort
/Heap.py
4,555
4.15625
4
''' Created by: Kevin Rodriguez Last Modified: November, 26 Professor: Diego Aguirre Purpose: In this lab, I had to finish the class for a Min Heap. We had to create a function that will create the min heap as well as being able to create a function that extracts the min and keep the Min_Heap property. By using the e...
63c5fa630e59632cef33c2ea392ef2eec0826d78
ushanirtt55/python
/Python Basics/Python_proj/String/reverse_str.py
163
4.125
4
def reverse(input): print input if len(input) <= 1: return input return reverse(input[1:]) + input[0] s = 'reverse' print(reverse(s))
82685290d923fdbf731cde29fd6397cc1758ad10
ASAD2723/Rani.ai
/Rani.ai/python_program_to_reverse_a_list.py
122
3.5
4
def Reverse(lst): mod_lst = lst[::-1] return mod_lst lst = [1, 76, 14, 10, 24, 31] print(Reverse(lst))
b669c7eeddeb4363afbfbe31d3e3b5147409e28d
melardev/PythonAlgorithmSnippets
/reverse_words_sentence.py
279
4.125
4
sentence = "If you wait, all that happens is you get older ." # split by spaces, get list of strings words = sentence.split() # reverse each item in the list and concatenate the items between them with space reversed_sentence = " ".join(reversed(words)) print(reversed_sentence)
132a10bee355b0773e11854eb991d47ae6242198
NotaCSstudent/leetcode
/python/linkedlist.py
593
3.984375
4
class Node: def __init__(self,data): self.data = data self.next = None def Insert_Node(root, data): if(root == None): root = Node(data) return root root.next = Insert_Node(root.next,data) return root def Remove_Node(root): if(root.next == None) head = None head = In...
2fb332b397f6d0d995951f02337be0f45a785ea4
pyq881120/pn
/pnwtl/pypn/scripts3k/pypn/utils/documentfile.py
2,572
3.75
4
import pn, scintilla class DocumentFile(object): """file-like interface to new Scintilla document editor DocumentFile() -> file object Open a file on a new Scintilla document editor. Provide the ability to add text to a new document editor using the python file idiom. Also allows you to t...
7037eed7ecc8216fc525e2793f39975ccc057192
Mohanskarri/MyPython
/CI,Dice,Coins,Temperature using_if.py
3,999
3.984375
4
# coding: utf-8 # In[1]: #this program calculates the compound intrest print('calculate the compound intrest') P = float(input('Enter the value of the principle amount : ')) r = float(input('Enter the rate of intrest: ')) R = float(r/100) n = int(input('enter the coumpound intrest frequency :1 ,2 , 4, 12 :')) T = f...
10c23bab8fea24f8303f4aa9f357d010787c95f4
WikiWikiWasp/ascii-crush
/ascii_crush.py
2,147
3.734375
4
######################################## # ASCII CRUSH # Author: Jason Flinn # Date: September 11th 2018 ######################################## import sys #terminal text colors BLUE = '\033[0;34m' RED = '\033[0;31m' GREEN = '\033[;32m' NC = '\033[0m' #no color def title(): print('='*30) print('-'*7 + ' ASC...
7f0f617b72833ada86f344ea45df7d7e69709ac3
cryoMike90s/Daily_warm_up
/Basic_Part_I/ex_14_number_od_days_between.py
412
4.03125
4
from datetime import datetime def day_difference(two_dates): _daty = [] for date in two_dates: date = datetime.strptime(date, '%d/%m/%Y').date() _daty.append(date) difference = abs((_daty[0] - _daty[1]).days) return print("Between {} and {} there are {} days difference".format(_daty[0],...
dd91988031b3f659a0df46244e87f57fa9e9987f
shuihan0555/100-days-of-python
/day004/main.py
1,067
3.875
4
"""Day 004 - Everything can be an iterable. This example covers how to make iterable an non built-in class. """ from fruits import FruitPack from random import choice def run(): fruit_pack = FruitPack() print("All fruits: ") for fruit in fruit_pack: print(fruit) # >>> All fruits: ...
278afc75760720906ed04346c169e7ffa86bd34f
shomikg/The-Complete-Python-Developer-Course
/Variables/variables4.py
570
3.59375
4
parrot = "Norwegian Blue" print(parrot) print(parrot[0]) print(parrot[3]) print(parrot[-1]) print(parrot[0:6]) print(parrot[:6]) print(parrot[6:]) print(parrot[-4:-2]) print(parrot[0:6:2]) print(parrot[0:6:3]) number = "9,223,372,036,854,775,807" print(number[1::4]) numbers = "1, 2, 3, 4, 5, 6, 7, 8, 9" print(numbers[...
9934eeb6311b3d239cb0c880411ca28318d9a50b
johncmk/Python
/Divide_and_Conquer/closest_unsorted.py
895
3.53125
4
import random def closest_unsorted(li,x, k): if li == [] or len(li) == k: return li p_adr = random.randrange(0,len(li)) pivot = abs(x-li[p_adr]) l,eq,r = [],[],[] for i in range(len(li)): if i == p_adr: continue else: temp = abs(x-li[i]) ...
97a42a77c3f85710f8ea665e8c43cd1463f059ea
srikanthpragada/PYTHON_10_JULY_2020
/demo/libdemo/list_broken_links.py
682
3.609375
4
import requests from bs4 import BeautifulSoup website = "http://www.srikanthtechnologies.com" # Website we want to use resp = requests.get(website) bs = BeautifulSoup(resp.text, "html.parser") anchors = bs.find_all("a") for a in anchors: if 'href' in a.attrs: url = a['href'] if url == "#": # ig...
58e3cc00491d7a598ff0ce31f9a1e9c7e9fbd236
Skishta/Project-5-Employee-Psitions-using-regression
/Project 5 (Employee Psitions and salaries) using sheet excel of real employees.py
3,846
4
4
'''بسم الله الرحمن الرحيم''' #Project 5 (Employee Psitions and salaries) using sheet excel of real employees ##ANOTHER PROJECT FOR POLYNOMIAL REGRESSION #Import all liberaries import pandas as pd import numpy as np import matplotlib.pyplot as plt #Import Sklearn with ...
1b33e8ac94e8beb1365eb01513a0c4648a4059d4
harshilphs/AkashTechnolabInternshipTasks
/Day-3_27-05-21/break_continue.py
172
4.0625
4
print("break---->") for i in range(1,6): if i == 3: break print(i) print("continue---->") for i in range(1,6): if i == 3: continue print(i)
39f6de220e518f7f9bab8870a399b9f587369b37
lucashsouza/Desafios-Python
/CursoEmVideo/Aula22/ex110/moeda.py
2,521
3.78125
4
def aumentar(preco, taxa=0, formatado=False): """ Função com o objetivo de calcular o aumento de determinada porcentagem parametrizada. :param preco: Valor a ser calculado :param taxa: Porcentagem a ser calculada :param formatado: Valor será apresentado com o formato(R$00,00) ou não? :retu...
343c0f44c05302445634cc99c1147dfa0c3dd13c
ne1son172/GB2-algo-and-data-structures
/HW1/task8.py
498
4.0625
4
# Определить, является ли год, который ввел пользователем, високосным или не високосным while True: year = input('Enter q for quit or enter some year >>> ') if year == 'Q' or year == 'q': break else: year = int(year) temp = year % 4 if temp == 0: print('{} year i...
a08a9cc05a4c91a8d58642577eca38596d83c3cf
Choijonghun/jhchoi_gitTest
/연습_src/0421_cordingStemp/practice_3.py
702
3.578125
4
#0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 22, 33, 44, 55, 66, 77, 88, 99, 101, 111, ... 과 같이, 0 이상의 앞뒤가 같은 수를 크기 순으로 나열할 때, n 번째 수를 계산하는 프로그램을 작성하라. '''count = int(input("시작\n")) pal_list=[] num = 0 def dec_pal(num): a = list(str(num)) b = list(reversed(a)) if a==b: pal_list.append(num) while len(pal_list) < count...
88f8018380404a76f38e852176d7a00ca3da835b
shaozhenyu/pythontool
/leetcode/solution.py
304
3.515625
4
#!/bin/python def moveZeroes(nums): # length = len(nums) # i = 0 # num = 0 # while i < length: # if nums[i] == 0 and i < length - num: # del nums[i] # nums.append(0) # num += 1 # else: # i += 1 nums.sort(key=lambda x:x==0) nums = [0, 1, 0, 2, 0, 0, 4, 4, 4, 0] moveZeroes(nums) print nums
9426b194c83afee4d37f7e8bc1e8507516af6dfe
zbyszek111/python_bootcamp
/zjazd1/podstawy_zad07.py
191
3.640625
4
print('podal liczbę A:') A = int(input('liczba A:')) print(A%2==0 and A%3==0 \ and A>10 or A==7) # do obcięcia linii kodu stosowany jest \ print((A%2==0) & (A%3==0) \ & (A>10) | (A==7))
36a48f14c8b4315e618033d6a671e08d086b4759
BIAOXYZ/variousCodes
/_CodeTopics/LeetCode/1-200/000048/000048.py
1,444
3.703125
4
class Solution(object): def rotate(self, matrix): """ :type matrix: List[List[int]] :rtype: None Do not return anything, modify matrix in-place instead. """ # 通过观察可以发现,替换的规律是这样的: ## (旧的)第 i 行会变成(新的)第 n-1-i 列;(旧的)第 j 列会变成(新的)第 j 行。 # 比如例子里那个四阶矩阵: ## 第0...
8e8836389ab4d005e066dd97d87e07c34129e9fa
amitesh1201/python_training
/for_loop3.py
626
4.375
4
#!/usr/bin/python # Declaration of list list1 = ["one", "two", "three", "four", "five"] print (list1) # Print the value in 2nd position print (list1[2]) # Print the index of two index = list1.index('two') print ("Index of two: ", index) print("") for x in list1: print ("The index of ",x,": ",list1.index(x)) #...
09d4827626d3be94d010782ba8b2eb5fd78825f3
axetang/AxePython
/60days/19.py
3,898
4.0625
4
from math import ceil ''' 直观理解 yield 要想通俗理解 yield,可结合函数的返回值关键字 return,yield 是一种特殊的 return。 说是特殊的 return,是因为执行遇到 yield 时,立即返回,这是与 return 的相似之处。 不同之处在于:下次进入函数时直接到 yield 的下一个语句,而 return 后再进入函数, 还是从函数体的第一行代码开始执行。带 yield 的函数是生成器,通常与 next 函数结合用。 下次进入函数,意思是使用 next 函数进入到函数体内。 ''' def f(): print("enter f()...") yield ...
d2a3fe523551a05c22b96507a170e1a16e085887
shamim-21/fsdp2019
/day6/height.py
875
3.921875
4
# -*- coding: utf-8 -*- """ Created on Tue May 14 10:19:14 2019 @author: Sammu """ people = [{'name': 'Mary', 'height': 160}, {'name': 'Isla', 'height': 80},{'name': 'Mary', 'height': 150}, {'name': 'Isla', 'height': 20} ,{'name': 'Sam'} ] # #height_total = 0 #height_count = 0 #for perso...
78c650860cfef1eb7306bcf91c6193ede054f8ec
lakshmi2812/dive_into_python
/late_ride.py
611
3.53125
4
def late_ride(n): #coding and coding.. hrs = n//60 mins = n%60 hrs_str = str(hrs) mins_str = str(mins) hrs_list = list(hrs_str) mins_list = list(mins_str) time1 = 0 for i in hrs_list: time1 = time1 + int(i) time2 = 0 for j in mins_list: time2 = time2 + int(j) ...
3b37213485d2bcf83d1812868992cfffe7c9364d
pedrolp85/Python_test_repo
/python_test_repo/test.py
903
3.9375
4
"""def aprobados(alumnos): decision = [] suspendido= False for alumno in alumnos: if alumno.alumno_aprobado(): decision.append(False) else: decision.append(True) return(decision) """ class Alumno(): def __init__(self, nombre, nota, clase): self._no...
fcebe3b1f1549b702fd4a4fdb6fdd6d763ccea70
anikoszo/code_sample
/random/palindrom.py
235
3.984375
4
class Palindrome: @staticmethod def is_palindrome(word): if word.lower() == word.lower()[::-1]: return "true" else: return "false" word = input() print(Palindrome.is_palindrome(word))
f88e893a8b0513a35a597e88a4c7d228b689dc57
headsoft-mikhail/adpy_01
/iterators_generators/main.py
588
3.625
4
import iterator import hashlib filename = 'countries.json' countries_iterator = iterator.CountriesIterator(filename, start=0, stop=3) filename = filename.replace('.json', '.txt') with open(filename, 'w', encoding='utf-8') as write_file: for item in countries_iterator: write_file.writelines(item +...
570b39242fc618cea05c78f3079f8b65f59d6a8c
akhilavemuganti/HelloWorld
/CSV.py
1,299
3.984375
4
import csv # Display all the Column Names # # with open("School_Nutrition.csv") as csv_file: # csv_reader=csv.reader(csv_file) # print("Column names are") # i=next(csv_reader) # print(i) column_names=['ProgramYear', 'ReportType', 'CEID', 'CEName', 'CECounty', 'ESC'] # Display first 10 column names i...
e95e049464e634bdea48137a8d8a3f1568954041
naamikaze/ejercicio-py-fundamentos-2021
/Estructuras de control/ej1.py
328
3.734375
4
#EJERCICIO 1 num1 = int(input('Ingrese el primer nro: ')) num2 = int(input('Ingrese el segundo nro: ')) num3 = int(input('Ingrese el tercer nro: ')) num4 = int(input('Ingrese el cuarto nro: ')) num5 = int(input('Ingrese el quinto nro: ')) suma = num1+num2+num3+num4+num5 promedio = suma/5 print('El promedio es: ', pr...
82e4e5e00f44ecc223f533ef3b26ef0420af77b0
yueoka/python_exercises
/04_class/yueoka_ex04.py
691
3.8125
4
# -*- coding: utf-8 -*- import unittest class Bot(): def __init__(self, owner_name): self.owner_name=name """ WRITE YOUR CODE HERE """ def reply(self, call): if call=="Hello": print("Hi, I'm Bill.aaa") elif call=="Hello my Boss!": print(...
daff7c1704d372e01f67d404b57840a6128de5b3
iamakkkhil/DailyCoding
/Day_16.py
1,782
4
4
""" DAY 16 : Different Operations on Matrices. https://www.geeksforgeeks.org/different-operation-matrices/ QUESTION : Perform Addititon, Subtraction and Multiplication on given Matrices. """ def add(matrix1, matrix2, n1, m1, n2, m2): # n = no of rows # m = no of columns add = [] if n1 =...
d6743b2a0c42455c8347c3f87376bee074550fea
fengt/py-leetcode
/src/77. Combinations.py
535
3.546875
4
# Approach 1: Recursive class Solution: def combine(self, n: int, k: int) -> List[List[int]]: if k == 1: return [[i] for i in range(1, n + 1)] elif k == n: return [[i for i in range(1, n + 1)]] else: rs = [] rs += self.combine(n - 1, k) ...
5eca61765f62ccb5cf66bbcb8f09b6907ae74cc6
benLbishop/chess
/chess_game/pieces/queen.py
644
3.96875
4
"""Module containing the Queen class.""" from .piece import Piece class Queen(Piece): """class for the queen Piece.""" def can_reach_square(self, start, end): """checks to see if movement from start_square to end_square is possible for a queen, pretending that no other pieces exist on the b...
0109fa9d727393cc6d1c737d4d99a3d7e103e718
dashwaiss20/dashwaiss-python
/Unit2BLab/Unit2BLab.py
677
3.9375
4
numGrade=input('what grade did you get? ') print(numGrade) if int(numGrade)>=90: print('yahoo you got an A!') elif int(numGrade)>=80: print('good you got a B') elif int(numGrade)>=70: print('Okay you got a C') else: print('you need to study more') color=input('what is your favorite color? ') print(color...
902b948eed20696404843fd33044702771e79b6f
jaywin2u/practices
/obits.py
200
3.875
4
#!/usr/bin/env python num = int(input('Input a number: ')) if num//10000: print("5") elif num//1000: print("4") elif num//100: print("3") elif num//10: print("2") else: print("1")
52a34757efac717687a65ad2f47233d020521c77
rifanarasheed/PythonDjangoLuminar
/FILEIO/filewordcount.py
486
3.84375
4
read = open("demo","r") # to read file dict = {} # creating an empty dictionary for counting words for line in read: # iterating each line words = line.rstrip("\n").split(" ") for wrd in words: # iterating each word of each line if(wrd not in dict): ...
8ea8b9a8a9b42bca81b2e850cedd495611c8de15
heikalb/sql-cats-dogs
/explore_data.py
2,393
4.375
4
""" Perform data exploration on the database. Heikal Badrulhisham, 2020 <heikal93@gmail.com> """ import sqlite3 def main(): # Create database conn = sqlite3.connect('shelter_animals.db') c = conn.cursor() # Show sample data c.execute("SELECT * FROM animals") print('Showing sample data') ...
05de7da9a732f3954d21a44c9aaab60283b2d03b
fares-ds/Algorithms_and_data_structures
/02_stacks_queues_deques/queue.py
572
4.0625
4
class Queue: def __init__(self): self.items = [] def is_empty(self): return self.items == [] def enqueue(self, item): self.items.insert(0, item) def dequeue(self): return self.items.pop() def size(self): return len(self.items) def __str__(self): ...
dcd4d901ba2b63a79f7c3eef5c9ae229c8eff108
licornes-fluos/Robot-Wars
/old/main files/main3.1.py
10,768
3.671875
4
import pygame import random import time pygame.init() #initialises the window size = (800, 600) # width,height screen = pygame.display.set_mode(size) #sets size of popup window pygame.display.set_caption("Robot Wars") # sets title of game window # Defining some colors BLACK = ( 0, 0, 0) WHITE = ( 255, 2...
0bb34c6d9971caca886ebad79a06d7b20f44f3bd
nzkim1234/Codeup_Python
/086.py
101
3.5
4
a = int(input()) s = 0 c = 1 while True: s += c c += 1 if s >= a: break print(s)
a9fc299165599aa32223e598aebf5006658a8e41
xuhyang/algo-practice
/sequence/queue.py
5,306
4.21875
4
class Queue: """ 22. Flatten List https://www.lintcode.com/problem/flatten-list/description Given a list, each element in the list can be a list or integer. flatten it into a simply list with integers. """ def flatten(self, a): ans, q = [], collections.deque(a) while q: e = q.popleft() ...
910efd6c56ff43635e4efaa034a3c4fe6061e297
Antohnio123/Python
/Practice/n.emelin/lesson9/1.py
1,839
3.546875
4
import datetime import threading import multiprocessing class Timer: t1=0 def __enter__(self): self.t1=datetime.datetime.now() def __exit__(self, exc_type, exc_val, exc_tb): t2 = datetime.datetime.now() print("Время выполнения = "+str(t2-self.t1)) def find_primes(start,end): #### п...
8a4bb51922f2adcca558e3f43f0360c7a3534a91
Draster51/Py_basics
/listas.py
1,134
4.03125
4
my_list = [1,2,3] ##Definir una lista print(my_list[0]) ##Llamar un elemento print(my_list[1:]) ##Llamar una serie de elementos segun posicion my_list.append(4) ##Agregar un elemento al final de la lista print(my_list) ##imprimir toda la lista my_list[0] = 'a' ##Mod...
4a304aec2d376a60798d79cf43f3940e47849980
Preetpalkaur3701/python-programmes
/mycalendar.py
389
4.40625
4
import calendar #(calendar.textcalendar),this means that we want written calendar where as calendar sunday means that we want our calendar to start from sunday. c = calendar.TextCalendar(calendar.SUNDAY) # we can change the year and month as we want by giving required information. year = input("Enter the year") month ...
14568370dd895d5119bb3aacbf5a2c0c8fd3f38b
AlexLemesPiva/Programas
/funciones_con_argumentos2.py
450
3.921875
4
''' script que retorne conversión de horas a minutos e segundos. deve retornar o equivalente em segndos e segundos ''' def hor_segundo(horas): return h * 3600 def hor_minuto(minuto): return h * 60 print('Conversor de Horas a minutos e segundos') h = int(input('Ingrese a quantidade de horas: ')) print(f'El ...
d44a7617911c2dd65a2cdf91ae7473596c311c92
JScarlet/leetcode
/rough_solution/506_find_relative_ranks.py
821
3.578125
4
class Solution: def findRelativeRanks(self, nums): """ :type nums: List[int] :rtype: List[str] """ nums_dict = {} sorted_nums = sorted(nums, reverse=True) for i in range(0, len(sorted_nums)): nums_dict[sorted_nums[i]] = i+1 result = [] ...
d665317db1b78e8e8849418ec149ea2676b1116b
cococonuts/leetcode
/154_Find_Minimum_in_Rotated_Sorted_Array_II.py
1,513
3.9375
4
""" Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. (i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]). Find the minimum element. The array may contain duplicates. Example 1: Input: [1,3,5] Output: 1 Example 2: Input: [2,2,2,0,1] Output: 0 Note: This is a follow...
509c645ee145bc057f4b186d68067585c4fce261
sakuya13/Study
/python/py/exercises/6.6_displayPattern.py
322
4.0625
4
def displayPattern(n): for i in range(1, n + 1): for j in range(n, 0, -1): if j > i: print(format(" ", "3s"), end="") else: print(format(j, "3d"), end="") print() def main(): n = int(input("Enter a number: ")) displayPattern(n) main()...
1f247c0a6af0d37ae568c4e0d349ec2a09166e5a
DoMinhTri/OpenCV-Python
/opencv-python-examples-master/11_webcam_features.py
677
3.546875
4
""" Example: Detect corners from a webcam video stream. """ import cv2 cap = cv2.VideoCapture(0) # Check if the webcam is opened correctly if not cap.isOpened(): raise IOError("Cannot open webcam") while True: ret, img = cap.read() if not ret: break gray = cv2.cvtColor(img, cv2.COLOR_BGR2G...
0666b07659198d35cae96f9b55ca00825ba23edb
eroneko/yihleego
/Python/listAndTuple.py
1,768
4.1875
4
classmates = ['Michael', 'Bob', 'Tracy'] print(classmates) print('classmate length:',len(classmates)) print(classmates[0]) print(classmates[1]) print(classmates[2]) #索引超出了范围 #print(classmates[3]) # -1做索引 直接获取最后一个元素 print(classmates[-1]) #以此类推,可以获取倒数第2个、倒数第3个 print(classmates[-2]) print(classmates[-3]) #list是一个可变...
ca6da4ae7b0f8e28f743ae9d404089149ada6492
tazuddinleton/basic_algorithms_and_data_structures
/hackerrank/interview_preparation_kit/arrays/left_rotation.py
218
3.75
4
def rotLeft(a, d): for i in range(0, d): a.append(a.pop(0)) return a print(rotLeft([1, 2, 3, 4, 5], 2)) print(rotLeft([33, 47, 70, 37, 8, 53, 13, 93, 71, 72, 51, 100, 60, 87, 97], 13))
29a2d6e1f86c891f4a000ad810ad1919f9088e36
whldk/study_py
/day02/tryc.py
1,345
3.65625
4
# coding:utf-8 """ 常用的异常类型集合 :exception 通用异常类型(基类) :ZeroDivisionError 不能为0 AttributeError 对象没有这个属性 IOError 输入输出 自定义抛出异常函数 --raise 用法: raise 异常类型(msg) """ def test(): try: print("upupup") except (ZeroDivisionError, NameError) as e: print(e) except Excepti...
25d4b7055d381cc3d4c7c7456013d976290caabf
Twest19/prg105
/6-2_sales_totals.py
1,058
4.25
4
""" Open the file sales_totals download in read mode Read in all the lines using a loop Strip the newline symbol and convert each line to a float Add each number to the running total Count the number of lines Format and display each number Outside of the loop format and display the to...
e04ee1520cd65cab03de8c6fa54585c962181eb5
Chuckboliver/Data-structure-and-Algorithms
/lab06/lab6_g_4.py
893
3.546875
4
def display(A,B,C,i ): if i < 0: return poleA = list(*filter(lambda x:x[0] == 'A',(A,B,C)))[1] poleB = list(*filter(lambda x:x[0] == 'B',(A,B,C)))[1] poleC = list(*filter(lambda x:x[0] == 'C',(A,B,C)))[1] print(poleA[i] if i < len(poleA) else "|",end=" ") print(poleB[i] if i < len(poleB...
68234e41260fb6fa337206cfb879eadc77bcc540
mathankrish/Infy-Programs
/InfyTq Basic Programming/Practice Programs/Level 3/Pro 45.py
703
3.8125
4
# PF-Prac-45 def longest_common_substring(string1, string2): # start writing your code here l1 = [string2[i2:j2] for i2 in range(len(string2)) for j2 in range(i2+1, len(string2)+1)] l2 = [string1[i1:j1] for i1 in range(len(string1)) for j1 in range(i1+1, len(string1)+1)] l3, l4 = sorted(l2, k...
68f0ee983c2a48cd5154e297cc6be36a20d21e68
AdamZhouSE/pythonHomework
/Code/CodeRecords/2189/60692/266383.py
470
3.5625
4
def square(m): str_m = str(m) res = 0 for i in str_m: res += int(i) ** 2 return res def ishappy(x): x = square(x) list1 = [] while x != 1: if x not in list1: list1.append(x) else: return False x = square(x) return True num = int...
ae23deeed78740ff742b3c59f4b39cde697607b5
porrametict/learningSpace
/PythonWithChulalondkorn/string_method2.py
545
3.640625
4
#strip / trim def strio_demoo(): s = "Thailand" t = " Thailand " u = t.strip()#del spaecbar before str and After str print(s==t) print(s==u) def demo_isdigit(p): total = 0 for c in p : #print(c) if c.isdigit(): # print(c) total += int(c) return to...
69c383f8f357ff277ad7903a45c7f876509f6b9b
mattkosi/small-projects
/games/hangman/game.py
1,203
3.671875
4
from hangmantextart import hangmanPics, wordToBlanks import random selection = random.choice(list(open('phrases.txt'))) lowerCase = selection.lower() blanks = list(wordToBlanks(selection)) i = 0 alreadyGuessed = [] while(True): if '-' not in blanks: print('\n' + "".join(blanks).capitalize() + '\...
90a6e95832b2614542e1a7c38b05e367914efe6b
frsilent/challenges
/frequency_count.py
744
4.1875
4
#Given N terms, your task is to find the k most frequent terms from given N terms. #Output format : #Print the k most frequent terms in descending order of their frequency. If two terms have same frequency print them in lexicographical order. f = open('test_data/ft_input01.txt') terms = [] for x in range(min(int(f.rea...
e6b14d5459d2fc17e3fb8cedc2a787b3e2aa4fcd
texttest/storytext-selftest
/swing/text_field/target_ui.py
1,077
3.515625
4
from java.awt import BorderLayout from javax.swing import JFrame, JLabel, JPanel, JButton, JTextField, JSeparator class MyTextFieldSubClass(JTextField): pass class TextFieldApp: def make_ui(self): frame = JFrame("Text field demo") frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE) ...
706acc49291a872862e9653b58f965a8a62c45a3
litichevskiydv/PythonStudies
/functions_composition.py
457
3.53125
4
def f(x): return x + 2 def g(x): return x - 3 def compose(f, g): return lambda x: f(g(x)) class Composable(object): def __init__(self, fn): self.fn = fn def __call__(self, *args, **kwargs): return self.fn(*args, **kwargs) def __and__(self, other): return Composabl...
a7d5ae6dbb20291f9437460f0fc6e1e3bbeeea9a
aroraakshit/coding_prep
/valid_parentheses.py
1,042
3.703125
4
class Solution: # 36ms def isValid(self, s: str) -> bool: stack = [] closing = [']','}',')'] opening = ['[','{','('] for i in s: if i in closing: if stack != [] and opening[closing.index(i)] == stack[-1]: stack.pop() els...
9229dbf2de5856bd02cf222209ca96bf573722e4
shifty049/LeetCode_Practice
/Medium/429. N-ary Tree Level Order Traversal.py
839
3.734375
4
class Solution: def levelOrder(self, root: 'Node') -> List[List[int]]: if not root: return root queue = [root] level = 0 level_list = [] while queue: level_list.append([]) next_queue = [] for node in...
ff6a9a35482f6531760115c159718283591b1309
Rohithyeravothula/Artificial-Intelligence-Projects
/lizards_java/scripts/generator.py
1,089
3.640625
4
import random #max board size n = 10 #max num of trees t = 3 methods = ["DFS", "BFS", "SA"] class Node(object): def __init__(self, board, size, lizCount, methodName): self.board = board self.size = size self.lizCount = lizCount self.methodName = methodName def write_board_to_file(node): l = len(node.boa...
55990bcfd4e67c4fb3162f619405a81bfa734e93
gspeiliu/MITx6001x
/statements/practice.py
1,284
4.0625
4
low = 0 high = 100 half = 50 print 'Please think of a number between 0 and 100!' print 'Is your secret number 50?' print "Enter 'h' to indicate the guess is too high.\ Enter 'l' to indicate the guess is too low. Enter 'c'\ to indicate I guessed correctly." , charin = str(raw_input()) while True: if charin == 'h':...
abc14400c14af8721116249f29b3ec427aa4b95c
mglaros/Python-Data-Structures-and-Algorithms-Udemy-Course
/avl.py
3,037
3.84375
4
class Node: def __init__(self, data): self.data = data self.height = 0 self.leftChild = None self.rightChild = None class AVL: def __init__(self): self.root = None def insert(self, data): self.root = self.insertNode(data, self.root) def insertNode(self, data, node): if not node: return Node(data...
777c4775dcf9b8ab708274816ed2733861ed8147
j1hwang/doodles
/py-data-structure/binary-search.py
533
4.03125
4
def binary_search(input_array, value): first = 0 last = len(input_array)-1 found = -1 while first<=last: mid = (first + last)//2 if input_array[mid] == value: return mid else: if value < input_array[mid]: last = mid-1 ...
3a2f25b9a3edb79d439852cf7c5739261a4dae65
victorsemenov1980/MIT_6.0001_6.0002
/2/PS1/temp.py
2,997
3.890625
4
# #!/usr/bin/env python3 # # -*- coding: utf-8 -*- # """ # Created on Mon Apr 20 12:53:58 2020 # @author: user # """ # from ps1_partition import get_partitions # import time # import timeit # cows={} # with open('ps1_cow_data.txt','r') as file: # for row in file: # text=row.split(sep=',') # cows.up...
22dcdb4ad7bcab03891102c9318d7035de806924
vipulwairagade/IVP
/Assignment 2/Histogram/hist.py
972
3.5625
4
import sys # For taking argument through terminal import numpy as np import matplotlib.pyplot as plt # Plotting of Histogram import cv2 # Taking Argument Through Terminal and Validating if len(sys.argv)>1: fname = sys.argv[1] else : print("usage : python hist.py <image_file>") im = cv2.imread...
54b3176e700e4202b846a5c297b55f7565b89ba1
nerdpollyanna/Natural_language_processing_book_100_knock
/answer10.py
924
3.90625
4
#hightemp.txtは,日本の最高気温の記録を「都道府県」「地点」「℃」「日」のタブ区切り形式で格納したファイルである. # 以下の処理を行うプログラムを作成し,hightemp.txtを入力ファイルとして実行せよ. # さらに,同様の処理をUNIXコマンドでも実行し,プログラムの実行結果を確認せよ. #10. 行数のカウント #行数をカウントせよ.確認にはwcコマンドを用いよ. #coding:utf-8 import os.path as path def count_number(filename): #入力はファイル名 #出力は、行数のcount数 return_count=0 ...
9bc31ad18d550e8f302026bf46d54be55633eea6
Soham2020/Python-basic
/lists/printDuplicate.py
89
3.984375
4
x = [1,2,3,5,3,2] y = [] for a in x: if not a in y: y.append(a) print(a)
a279162d261e204b05d50a490fd89aa08340a627
Netra-Bahadur-khatri/Python_Geeks_For_Geeks
/GFG_06_Sets.py
389
3.984375
4
""" Set is an undordered collection of data type that is iterable mutable and has no duplicate elements. """ # Creating an sets string = "Hello, this is Netra kc" set1 = set(string) print(set1) a = 4 b = 5 set_add = set() set_add.add(a) set_add.add(b) print(set_add) # update() --> takes elements as list # remove()...
b7335fb30b822050372934bed00d33dd815d72b1
RyanRasi/Python-Sudoku-Solver
/gui.py
5,870
3.640625
4
from tkinter import * # Start of GUI win = Tk () win.title("Sudoku Solved!") win.geometry("475x470") win.resizable(0, 0) w = Canvas(win, width=475, height=470) # w.create_rectangle(50, 0, 100, 50, fill="white", outline = 'black') bOne = 1 for x in range(3): # First Row of Boxes w.crea...
7087bb73910aa057c02bd3734efa0387ddd147f4
cruecker/programmieren_lernen
/kurs-python-lernen/for.py
207
3.625
4
#for entspricht for-each in ps #zv ist keine zählvariable daher kein i zitat = "werft den purschen zu poden" zv = 0 for x in zitat: zv += 1 print("Zeichen ", zv, ":\t", x) print("Schleife beendet")
f784ca35f272ce466c8a4576108be5326419370a
happylay-cloud/python
/code/Set.py
758
4.25
4
# 声明集合:set s1 = set() # 创建空集合,只能使用set() s2 = {1,2,3} # 字典{key:value} 集合{元素} print(type(s1)) print(type(s2)) list1 = [1,2,3,4,5,3,4,5] s3 = set(list1) print(s3) # 增加一个元素 s1.add('hello') s1.add('lay') t1 = ('hello','world') # 添加多个元素 s1.update(t1) s1.add(t1) print('--->',s1) s3.discard(1) print(s3) set1 = {1,2,3} s...
186fdc9484d2e7a5972013b0fdcf14681dfb5d20
ANASTANSIA/PythonRepo
/02.py
353
3.96875
4
""" Prints Letter A """ size=eval(input('Height:')) for i in range(size): for j in range((size//2)): if((j == 0 or j== size//2) and i !=0 or i==0 and j!=0 and j !=size//2 or i==size//2): print("*", end = "") else: print("" ,end= "") print() ...
4254ea42c2be99e0884cd961380320c17a8f45c7
Cpzty/proy1-compis
/abtreelist.py
1,266
3.828125
4
class Tree(): def __init__(self): self.nodes = [] self.count = 0 def add_entree(self, left, op, right): if len(self.nodes) == 0: if right == ' ': node = [left, op] elif right == ' ' and left == ' ': #node = [self.count, op] ...
5e589a8a6e823f1abcf5f4d041d6e8be418eb509
1363653611/zbcn-py
/algorithm/duplicate_data_test.py
966
3.90625
4
def swap(nums, i, j): """ 将第i个元素的值,复制到第i个元素上 :param nums: :param i: :param j: :return: null """ temp = nums[i] nums[i] = nums[j] nums[j] = temp def duplicate(nums, duplication): """ 长度为n的数组里的所有数字都在0到n-1的范围内。查出数组中某个重复的数据 :param nums: :param duplication: :retu...
06cef42ac056d6e25185bbe62ca4af0431e76e35
dennis-omoding3/firstPython
/operators.py
789
4.21875
4
# arithmetic operators # + addition # -subtraction # *multiplication # /division print(2**3) # **used in exponential # % modulo operator returns the remainder of the division print(10%3) print(48%2) # // floor dividion truncates the answer. print(49//3) # assignment operators # = assigns to an identifier add=2+2 # add...
45a2623530d919e8ed7486957523824edd530de8
mercurium/proj_euler
/test160.py
702
3.890625
4
import time start = time.time() from math import factorial as fact def fa(n): if n == 0 or n == 1: return 1 prod = 1 for i in xrange(2,n+1): prod *= i while prod % 10 == 0: prod /= 10 prod = prod % (10**5) return prod val = fa(10**5) #last 4 digits of factorial(10**5) are 2496 print val ...
bb6a448843cddd66bd70e5beb4a4cdba5780c52a
makhmudislamov/coding_challanges_python3
/module_6/bubble_sort.py
1,693
4.40625
4
""" Given an unsorted list of integers, sort those integers using the Bubble Sort algorithm. Return the number of swaps required to sort the list. Bubble Sort is a simple sorting algorithm that works as follows: 1. Start at the beginning of the list, and traverse through each element. 2. For each element, if the elem...
2376fde0641b55e1bfd4ecf8e5aa16c5ff649a6d
ttnguyen2203/code-problems-python
/contains_duplicates.py
649
4.125
4
''' Given an array of integers, find if the array contains any duplicates. Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct. Difficult: Easy Solution Notes: 1. Use the property of sets (unique). 2. Alternatively, use a hash m...