blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
fe5f782971ba70eb955258fbb4f56237ed284116
brunofonsousa/python
/pythonbrasil/exercicios/listas/LT resp 13.py
991
4
4
''' Faça um programa que receba a temperatura média de cada mês do ano e armazene-as em uma lista. Após isto, calcule a média anual das temperaturas e mostre todas as temperaturas acima da média anual, e em que mês elas ocorreram (mostrar o mês por extenso: 1 – Janeiro, 2 – Fevereiro, . . . ). ''' mes = ["Janeiro", "F...
a2d441a9f9cd8444ee6f5a67735adb1747210546
ectky/PythonProjects
/Drawing_Figures_with_Loops/Diamond.py
1,241
3.546875
4
import math n = int(input()) minus = 0 star = 0 middle_minus = 0 if n == 1: print('*') elif n%2 == 0: star = 2 minus = (n - star)//2 print('-' * minus + '*' * star + '-' * minus) middle_minus = 2 star = 1 minus -= 1 for i in range(n//2 - 1): print('-' * minus...
cf2b80a84b86a8db8a6c6954456d3cf294bbeef8
EndIFbiu/python-study
/06-列表/03-判断是否存在.py
562
4.1875
4
name_list = ['tom', 'lily', 'rose'] # in print('tom' in name_list) # True print('toms' in name_list) # False # not in print('tom' not in name_list) # False print('toms' not in name_list) # True # 以上字符串也可以使用 # 需求:注册邮箱,根据输入判断账号是否存在 name = input('请输入您的邮箱账号名:') if name in name_list: # 提示用户名存在 print(f'您输入的名字...
dbb53f48d366ce03c8450c94b44d03e809ea0153
jamesaclark1995/jamesaclark1995
/fruit_with_vowels.py
486
4.1875
4
# This is inspired by a Codecademy exercise. The exercise printed off a list # of fruit which put "A" in front of fruit beginning with vowels instead of # "An". This code changes this so it is more grammatically correct. # (Created with Python 2) fruits = ['banana', 'apple', 'orange', 'tomato', 'pear', 'grape'] print...
c9a0a597551c94e8ccc60ec4f1d3c867a218127e
LinaSeveri/r0714556_Lina_Severi_Marvel_API
/r0714556_Lina_Severi_API_Marvel.py
8,768
3.59375
4
import urllib.parse import requests import hashlib #I import this module to put my data in a table. from tabulate import tabulate import datetime from datetime import date import calendar main_api = "http://gateway.marvel.com/v1/public/characters?" public_key = "" # Enter your public key here. private_key = "" # Ent...
e3d5a3a3c18063e0c58b2c306ed0878eceb74ba5
AkiraMisawa/sicp_in_python
/chap1/c1_34.py
398
3.71875
4
def f(g): return g(2) print(f(lambda x:x*x)) print(f(lambda x:x*(x+1))) #print(f(f)) TypeError: 'int' object is not callable # f(g)の宣言でgに2を適用していることから、gの定義域はNumeric Type # g:Numeric->Tの形になる。従ってfは # f:Functor(Numeric->T)->T # の形になる # f自体はFunctor(Numeric->T)の形ではないので、 # f(f)は呼び出せない
932781b753965750254c6af131917bb02a133044
kevinwilde/hackerrank
/hackerrank/ai/alpha-beta-pruning/ticTacToe.py
3,006
3.6875
4
#!/bin/python # Minimax algorithm with alpha-beta pruning # Choose middle box first if possible import random def vertWin(board, player): for i in range(3): if board[0][i] == player and board[1][i] == player and board[2][i] == player: return True return False def horizWin(board, player): ...
af2943e9cfb20a4ec17909d740273fc71bd1fab4
Erynvorn/Training-Python-2019
/tr1.py
554
3.984375
4
print('Hello world') print('What is your name?') myName = input() print(myName) print('It is good to meet you, '+ myName) print('The length of your name is: ') print(len(myName)) print('What is your age?') myAge = input() print('You will be ' +str(int(myAge) +1) + ' in a year.') print('Please enter password :') passwo...
4e52d1336f8c4e25e1024f5e3c692288f5f98c7a
komalsorte/LeetCode
/BinarySearchTree/173_BinarySearchTreeIterator.py
2,218
4.3125
4
__author__ = "Komal Atul Sorte" """ Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the root node of a BST. Calling next() will return the next smallest number in the BST. Example: BSTIterator iterator = new BSTIterator(root); iterator.next(); // return 3 iterato...
660ec847546da073fe353a6208c1960480e97234
ianliu-johnston/interview_prep
/interview_prep/gameoflife.py
2,376
3.859375
4
from copy import deepcopy import logging from typing import Any, List log = logging.getLogger(__name__) alive = 1 dead = 0 def cell_survival(cell: bool, population: int) -> bool: """ control flow for cell survival :param cell: cell to check :param population: how many cells are alive :return: If ...
55cb68df6b64b61685dc825c19c59ab0d2184878
norbertosanchezdichi/TIL
/Python3/Projects/RockPaperScissors/rock_paper_scissors_v2.py
522
3.90625
4
from random import choice print('Rock...') print('Paper...') print('Scissors...') player1 = input('Player 1, make your move: ').lower() player2 = choice(['rock', 'paper', 'scissors']) print(f'Computer plays {player2}') if player1 == player2: print('Its a TIE!') elif player1 == 'rock' and player2 == 'scissors': p...
b736e0f5392bd1bb039bead7fcc1c97b7d3284d2
Dipson7/LabExercise
/Lab2/question_no_9.py
225
4.09375
4
''' Check wheather the given year is leap year or not.If yes print 'Leap year' else print 'Common year' ''' a=int(input("Enter a year: ")) if a % 4 == 0 and a % 100 != 0: print('leap year') else: print('common year')
2f1848c51a6852b6b7e811263d9f409f2b97648e
cloew/KaoHex
/kao_hex/hex_grid_printer.py
2,269
3.703125
4
from .hex_vector import HexVector class HexGridPrinter: """ Helper class to print a hex grid to the console """ def __init__(self, *, rows, cols, cell_length=3, empty=" ", topright=HexVector(0,0), long_row_first=True): """ Initialize the HexGridPrinter with the grid size (in rows/cols) and t...
236f3b513a354140af486abb20dd0960f7d622e1
nhortensioUAL/ualap2021_grupo1
/Lab1/Lab1_Parte5.py
3,083
4.09375
4
import math,sys def menu(): print("Menu") print("Selecione 1 - Fórmula Resolvente") print("Selecione 2 - Valor de Fibonacci de 2020") print("Selecione 9 - Sair") opcao = str(input("Selecione uma opção: ")) menuoptions(opcao) def menuoptions(opcao): if opcao == "1": print("Fórmu...
df15c8b0313294847bedac1875c719cd4de85799
AssiaHristova/SoftUni-Software-Engineering
/Python OOP/solid/entertaiment_system.py
1,430
3.53125
4
from abc import ABC, abstractmethod class Device(ABC): @abstractmethod def plug_in_power(self): pass class HDMIConnectable: def connect_via_hdmi(self, device): pass class RCAConnectable: def connect_via_rca(self, device): pass class EthernetConnectable: def connect_vi...
6c6dc520cb7e5fc508094181e35d4f470f3f39df
vgvcode/sudoku
/square0.py
14,028
3.5
4
def printRow(lov): print lov #nLov = [] #for l in lov: # if l == 0: # nLov.append(".") # else: # nLov.append(l) #print ("%s%s%s %s%s%s %s%s%s") % (nLov[0], nLov[1], nLov[2], nLov[3], nLov[4], nLov[5], nLov[6], nLov[7], nLov[8]) class Cell: def __init__(self, row...
a0addcf9b4a608c831ae33a00d43ea6f1cf9aeb3
ediltwwj/PythonLab
/labsix/one.py
535
4.03125
4
"""实验六第一题""" def mp_sort(arr, length): """对列表进行排序,并输出""" for i in range(0, length): for j in range(0, i): if arr[j] > arr[i]: arr[i], arr[j] = arr[j], arr[i] print("After sorted : ", end="") for i in range(length): print(arr[i], end=" ") if __name__ == "...
2c140cf7d63c367f29634c8ada2473434809922b
kbklingler/python
/plus_one.py
98
3.8125
4
#! /usr/bin/env python3 NumberList = [1,3,5,7,9,11] for Number in NumberList: print(Number + 1)
55a1b910b9b71a8caccceb34d843cabf0c7156e8
Sannidhya127/Complete-Python-Course
/13. Chapter 13/04_format.py
330
3.671875
4
name = "Harry" channel = "CodeWithHarry" type = "Coding" # a = f"This is {name}" # a = "This is {}".format(name) # a = "This is {} and his channel is {}".format(name, channel) # a = "This is {0} and his {2} channel is {1}".format(name, channel, type) a = "This is {} and his {} channel is {}".format(name, channel, type)...
ced7d01a7a2c45aa08e04c9c7b4a55e8ac77aa89
eatradish/LeetCode
/longestCommonPrefix.py
853
3.578125
4
class Solution: def longestCommonPrefix(self, strs): """ :type strs: List[str] :rtype: str """ result = '' tmp = [] if '' in strs or len(strs) == 0: return result min_len = len(strs[0]) for i in range(len(strs)): if len(strs[i]) < m...
b52cd5a16b41ceba5220c71ea00bdaa755a45912
margaridav27/feup-fpro
/REs/RE04/perfect_numbers.py
277
3.71875
4
# -*- coding: utf-8 -*- """ Created on Tue Oct 15 19:22:59 2019 @author: Margarida Viera """ def is_perfect(n): sum = 0 for i in range(1, n): if n % i == 0: sum += i is_perfect = (sum == n) return is_perfect n = int(input()) print(is_perfect(n))
ee11aabb3a714d8930d833f52f72a733c0a92ef3
awpogodin/py-repos
/study/exercises/ex1-23/l1.py
492
3.859375
4
print('Введите количество чисел:') i = int(input()) sum = 0 print('\nВведите последовательность чисел построчно:\n') while i>0: n = int(input()) i-=1 sum +=n print('\nСумма чисел = ', sum) # sum = 0 # n = '0' # print('\nВведите последовательность чисел построчно:\n') # while n!='': # sum += int(n)...
534aaddd28341601bf96ef5930b5545cf739e5a1
rahcosta/Curso_em_Video_Python_3
/Parte 3/11.5. Dividindo valores em várias listas.py
770
3.921875
4
'''Crie um programa que vai ler vários números e colocar em uma lista. Depois disso, crie duas listas extras que vão conter apenas os valores pares e os valores ímpares digitados, respectivamente. Ao final, mostre o conteúdo das três listas geradas.''' lista_geral = list() pares = [] impares = [] while True: n = ...
fb973e7b61098c9542f1f9fac669bb107a12cc24
ProgramminSmarts/accountsDatabase
/main.py
2,096
3.609375
4
import database as db from passlib import ldap_md5 as md5 test = db.database("Accounts") test.addField("Usernames") test.addField("Passwords") test.load() #make directory - creates a directory at path you define q = int(raw_input("Make an account or log in or delete your account? 1 or 2 or 3: ")) def createAcc(): ...
83fe749acef7c345c47fcdcefc76fc66e1df475a
RAJNDR/kickstart
/minimal_hue_control/minimal_hue_control.py
13,145
3.5
4
#!/usr/bin/env python """simple application to easily change the light color from the command line for further information about philips hue, check here: * https://github.com/Q42/hue-libs * http://www.developers.meethue.com/documentation/core-concepts * http://www.developers.meethue.com/documentation/getti...
683c4f57a004cce69b09407c99ce867fd471e32c
erickjsantofimioj/ParcialHerramientasComputacionales
/CalculadoraDescuento.py
763
3.953125
4
print('!!!!!Bienvenido a su cafeteria buen sabor!!!!!') cedula = input('Por favor digite su numero de cedula: (solo números aqui): ') rol = input('Por favor digite su rol (Estudiante o Profesor): ') codigo = input('Digite el codigo del producto: ') cantidad = int(input('Digite la cantidad de unidades que llevará: '...
bc6c257e330be24e555da670b38e0c602fdfb08f
drichardi/Programming1
/ReturnValues.py
2,903
4.3125
4
#Return values #Calling functions generates a return value #which we usually assign to a variable to use as part #of an expression e = math.exp(1.0) height = radius * math.sin(radians) #The functions we have written the most are void, they have no return value; #specifically their return value is None. def area(radi...
3cd0b46f7c1eca712405e66703c026490e746b99
parth04/Data-Structures
/Recursion/SortAnArray(Recursive).py
954
4.09375
4
""" 912. Sort an Array Medium Given an array of integers nums, sort the array in ascending order. Example 1: Input: nums = [5,2,3,1] Output: [1,2,3,5] Example 2: Input: nums = [5,1,1,2,0,0] Output: [0,0,1,1,2,5] """ class Solution: def sortArray(self, nums: List[int]) -> List[int]: if len(nums) == 1: ...
81473f86f45def2200f62ffdebb3b0cf9cfd6023
crrichardson/LiMR_RPi
/push_button.py
281
3.921875
4
import RPi.GPIO as GPIO GPIO.setwarnings(False) GPIO.setmode(GPIO.BOARD) #USe physical pin numbering GPIO.setup(10, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) #set pin10 as input, set initial value as low while True: if GPIO.input(10) == GPIO.HIGH: print("Button pressed!")
0d5c4cdf2a305e7ca2e39db020853a88702f8564
cnorthwood/adventofcode
/2018/09/challenge.py
1,036
3.640625
4
#!/usr/bin/env pypy3 from collections import deque with open('input.txt') as input_file: input_tokens = input_file.read().strip().split() NUM_PLAYERS = int(input_tokens[0]) LAST_MARBLE = int(input_tokens[6]) def simulate(num_players, last_marble): marbles = deque() scores = {player: 0 for playe...
eea30a125fd38a3ea0b1aa675da958716486f6a4
mateusrmoreira/Curso-EM-Video
/desafios/desafio39.py
693
4.125
4
"""25/03/2020 jan Mesu faça um programa que peça o ano de nascimento de uma pessoa Consulte a idade e diga se ele vai precisar se alistar ou se é o ano de se alistar ou se passou a data para se alistar """ from datetime import datetime nascimento = int(input('Qual é seu ano de nascimento? ')) idade = datetime.now().ye...
2872048d6efb0a25c335f30b85cc00604151460b
MarinaGoto/python-basic
/Simple programs/Restaurant Tab Calculation Program.py
1,355
4.0625
4
# Restaurant Tab Calculation Program # This program will calculate a restaurant tab with a gift certificate # initialization tax = 0.08 # program greeting print('This program will calculate restaurant tab for a couple with') print('a gift certificate, with a restaurant tax of ', tax*100, '%\n') # get amount of gift...
2c5293273816a39cc791ccf9defeeca75e668a83
PetriTurpeinen/DiscordBot
/replitdatabase.py
714
3.9375
4
from replit import db #Datbase class is used for storing user information class Database(): #test purpose def delUser(self, user): del db[user] #Add user to db and set his score to 1 if not in db, otherwise increase it by 1. def addUserDB(self, user): keys = db.keys() if user in keys: db...
c44b11df4ff6aecd21947fa79632a0991ed5fa0e
akimi-yano/algorithm-practice
/lc/86.PartitionList.py
1,413
3.984375
4
# 86. Partition List # Medium # 2146 # 393 # Add to List # Share # Given the head of a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x. # You should preserve the original relative order of the nodes in each of the two partitions. # Example 1:...
b80ef5352b4692025ffa87369a696bbc3146013b
guptaraghav01/100DaysOfCode
/day5/highScore.py
656
4.375
4
print("This program will calculate the highest score from the given list.") student_scores = input("Input a list of student scores(separated by spaces): \n").split() for n in range(0, len(student_scores)): student_scores[n] = int(student_scores[n]) print(student_scores) highest_score = 0 for score in student_score...
9aa0ab37632cca3176e9b4ec7cee3920b00c35a1
umatbro/p-tutorials
/python/game of life/testing.py
1,529
3.734375
4
import unittest from board import Board class TestField(unittest.TestCase): def setUp(self): """ x x x x x x x o x x x o o o x x x x o x x x x x o """ self.board = Board((5, 5)) self.board.field.fill(0) self.board.field[1, 2] = 1 ...
9c19a905a8cb60ae6315ee03d6f156bd63cb5f7b
Aasthaengg/IBMdataset
/Python_codes/p02570/s835736271.py
89
3.8125
4
x,y,z = input().split() if ( int(x) / int(y) <= int(z)): print("Yes") else: print("No")
007e9352b9033907ab82ed1d1abb5e6deff05eaf
AilanPaula/Curso_em_video_Python3
/ex095.py
680
4.0625
4
''' Crie um programa que tenha uma função notas() que pode receber várias notas de alunos e vai retornar um dicionário com as seguintes informações: -> Quantidade de notas -> A maior nota -> A menor nota -> A média da turma -> A situação (opcional) ''' def notas(*num, sit=False): d = dict() d['total'] = len(nu...
e25880ad42b577a26e9f94b5a49483cea61f5bbc
hbates00/6.0001-Introduction-to-Computer-Science-Programming-in-Python
/Final Exam/problem2.py
508
4.125
4
def dict_invert(d): ''' d: dict Returns an inverted dictionary according to the instructions above ''' newdict = {} for i in d: if d[i] not in newdict: newdict[d[i]] = [i] elif d[i] in newdict: item = newdict[d[i]] item.append(...
bedf4bf909bf89740142873b2706963df6d900fc
AbhishekSharma51/python
/index.py
711
3.546875
4
from data import DICTIONARY, LETTER_SCORES def load_words(): with open('dictionary.txt', 'r') as dictionary: data = dictionary.read() elsp = data.split() return elsp def calc_word_value(word): finish_count = 0 for k in list(word): count_word = LETTER_SCORES.get(k.upper(), 0) ...
708a428c6f7db7d0e9b59ac16dc3556a74f21402
siriusgithub/dly
/easy/21/0.py
740
3.875
4
TODO mayber work backwords in the number TODO sort number from smallest digit to biggest input number previous = stinrg[0] for pos in stringnumber previous ####################### input number 3259 5612 9832 8913 33333452 3529 6125 9832 9138 33334235 look at first digit 3 5 9 8 first digit = variable 'star...
28224f08f2b1151757e6091f7ddac2cb7d11073f
ChristianChiarulli/Firecode
/Python/duplicate_items.py
183
3.546875
4
def duplicate_items(list_numbers): seen = [] ret = [] for num in list_numbers: if num in seen: ret.append(num) seen.append(num) return ret
414d51933513dcd6dd9902e3f83cd4b02c29ab2f
crystalskull/python-practice
/newton_raphson_square.py
484
4.46875
4
#!/usr/local/bin/python3 ''' Program to find square root of a number using Newton-Raphson method. ''' if __name__ == '__main__': num = int(input("Enter a positive value:")) if num > 0: epsilon = 0.00001 guess = num / 2 while abs(guess ** 2 - num) > epsilon: print(guess) guess = guess - ((gue...
97ffb49afc74eafb21eb08b4f70bf09ba799dcc5
KSarath24/sarathpro
/sp1.py
135
3.828125
4
s=int(input("\nEnter the number:")) a=input("\nEnter the string:") c=list(a) d=0 while s>0: print(c[d],end="") d=d+1 s=s-1
457190d5e9cac5c17c56299f384e96541871c1ab
siddharthcurious/Pythonic3-Feel
/Data-Structures/BST/find_pair_given_sum.py
1,075
3.859375
4
class TreeNode: def __init__(self, val): self.val = val self.left = None self.right = None class BST: def __init__(self): self.inorder_set = set() def inorder(self, root): if not root: return self.inorder(root.left) print(root.val, end="...
1b93ea4833da97007ab27498be9e01bd99212c28
yjh8806/python-2019-July
/11일/13.반복문for/08.문제.py
332
3.796875
4
#최대공약수! max_list = [] MAX = 0 num1, num2 = int(input("첫 번째 : ")), int(input("두 번째 : ")) for i in range(1, min(num1, num2) + 1): if num1 % i == 0 and num2 % i == 0: #공약수 max_list.append(i) MAX = i print("최대공약수 : %d"%MAX) print("최대공약수 : %d"%max(max_list))
a071f2f9dbd8aee0fe56aa84394cfa6b317a0439
alansmello/cursoProgramacaoEmPythonDoBasicoAoAvan-ado
/capitulo 04/Exercicios capitulo 04/exe06.py
375
3.90625
4
""" Leia a temperatura em graus Celsius e apresente-a em graus Fahrenheit. A fórmula de conversão é: F=C*(9.0/9.5)+32.0, sendo F a temperatura em Fahrenheit e C a temperatura em Celsius. """ celsius = float(input('digite a temperatura em graus Celsius: ')) fahrenheit = celsius * (9.0/9.5) + 32.0 print(f'a temperatu...
36c442ef7f57ec1d2dd5051f56b75a02edc58820
yuhangxiaocs/LeetCodePy
/binary_search/FindInsertPosition.py
516
3.59375
4
class Solution(object): # 最后总是返回lo def searchInsert(self, nums, target): if not nums: return mid, lo, hi = 0, 0, len(nums) - 1 while lo <= hi: mid = (lo + hi) // 2 if nums[mid] < target: lo = mid + 1 elif nums[mid] > target: ...
dbfcd43d18d43902dede35889f2cae8cbdb85e5f
wulinlw/leetcode_cn
/leetcode-vscode/521.最长特殊序列-ⅰ.py
1,274
3.640625
4
# # @lc app=leetcode.cn id=521 lang=python3 # # [521] 最长特殊序列 Ⅰ # # https://leetcode-cn.com/problems/longest-uncommon-subsequence-i/description/ # # algorithms # Easy (66.18%) # Likes: 43 # Dislikes: 0 # Total Accepted: 9.5K # Total Submissions: 14.3K # Testcase Example: '"aba"\n"cdc"' # # 给定两个字符串,你需要从这两个字符串中找出最长...
560cd55b1308d91fe585222ccdc6e88730468415
Pelhans/leetcode
/jianzhi/23.py
715
3.8125
4
#!/usr/bin/env python # coding=utf-8 # -*- coding:utf-8 -*- # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def EntryNodeOfLoop(self, pHead): # write code here fast_p = pHead slow_p = pHead if pHead is None: ...
add0d94fe7df1abb086a7302fd714a225c39b621
uwseds-sp18/homework-3-awfuldynne
/src/homework3.py
1,044
3.84375
4
import os import pandas as pd import sqlite3 def create_dataframe(file_path): """ Creates a Pandas DataFrame with three columns (video_id, category_id, and language :param file_path: File path to where the Youtube database is located :return: Pandas DataFrame """ sql_statement = \ "SELECT ...
9f58defb44ef0f3bf84bc83a4274bc470f95229b
JojiKoike/Practice_AlgorithmAndDataStructure_Python
/chapter6/findmaximum.py
379
3.5
4
from typing import List n: int = int(input()) a: List[int] = list(map(int, input().split())) def find_maximum(a: List[int], l: int, r: int) -> int: mid: int = int((l + r) / 2) if l == r - 1: return a[l] else: u = find_maximum(a, l, mid) v = find_maximum(a, mid, r) x = max(...
5c62f9c5a97866b81bb0af622db0a2a11b95650c
barak21-meet/meetyl1
/lab_4.py
747
3.9375
4
import turtle from turtle import Turtle class Ball(Turtle): def __init__(self,r,color,dx,dy): Turtle.__init__(self) self.penup() self.shape="circle" self.size=r/10 self.r=r self.color=color self.dx=dx self.dy=dy def move(self,screen_width,screen_height): current_x=self.xcor() new_x=current_x+self....
b64c17c148bb6512f782b9b6adaa266f8b109bdd
Dominik-Hillmann/pin-maps
/pin_maps/complete_image_transforms/Logo.py
1,965
3.53125
4
# Internal imports from complete_image_transforms.CompleteImageTransform import CompleteImageTransform # External modules from PIL import Image # Python libraries import os # Typing from typing import Tuple class Logo(CompleteImageTransform): """Inserts the Logo into the image.""" __logo_path = os.path.join('...
07ad7cf0224e493de9b3d1c1768330e56c4a7062
tanvidev/python
/assignment1/assignment1_10.py
157
4.09375
4
str = raw_input("Enter a string - "); def checkLength(str): length = len(str); print "The length of the string is - ", length ; checkLength(str);
27ea5fefc0c04eac6d692c2d7198d49a9c4e21d8
namekun/pythonStudy
/ch09_InsertionSort/InsertionSort2.py
359
3.703125
4
# 삽입정렬 # 입력 : 리스트 a # 출력 : 없음 (입력으로 주어지는 a가 정렬된다.) def insSort(a): n = len(a) for i in range(1, n): k = a[i] # key value j = i - 1 while j >= 0 and a[j] > k: a[j + 1] = a[j] j -= 1 a[j + 1] = k d = [2, 4, 5, 1, 3] insSort(d) print(d)
d6f68de1dbf23123408186ff6ea9c0c72b3a2130
algorithm005-class02/algorithm005-class02
/Week_08/G20190343020041/LeetCode_344_0041.py
1,068
3.734375
4
# 编写一个函数,其作用是将输入的字符串反转过来。输入字符串以字符数组 char[] 的形式给出。 # # 不要给另外的数组分配额外的空间,你必须原地修改输入数组、使用 O(1) 的额外空间解决这一问题。 # # 你可以假设数组中的所有字符都是 ASCII 码表中的可打印字符。 # # # # 示例 1: # # 输入:["h","e","l","l","o"] # 输出:["o","l","l","e","h"] # # # 示例 2: # # 输入:["H","a","n","n","a","h"] # 输出:["h","a","n","n","a","H"] # Related Topics 双指针 字符串 # leetc...
bae30bdcd7097cc2c835884735ff0d1ac2f4080b
oobiliuoo/PythonCode
/RegEx/bl_01_re模块的使用.py
573
3.65625
4
""" 1.导入模块 2.通过match()方法,验证正则 3.判断验证是否成功 4.如果成功,获取匹配结果 """ # 1.导入模块 import re # 2.通过match()方法,验证正则 # re.match(正则表达式, 要验证的字符串) # 如果验证成功,返回一个match object 的对象 # 如果验证失败,返回None result = re.match("\w{4,20}@163\.com$", "hello@163.com") # 3.判断验证是否成功 if result: # 4.如果成功,获取匹配结果 print("匹配成功") print("匹配结果:", result...
9d81c59734f8a44cb0681fc8a2e7ce3ff593dfc1
AbrilPal/Lab2_Redes
/ServerCorreccion/Servidor.py
1,046
3.546875
4
# Laboratorio No.2, Server.py # 29/07/2021 # Integrantes: # - Abril Palencia, 18198 # - Cristina Bautista, 161260 # Libreria socket from socket import * from ruido import CorreccionHammingServer r = CorreccionHammingServer() # Puerto del servidor serverPort = 4308 # Socket del servidor serverSocket = socket(AF_I...
5a410ee50e66ba6d11f229c64551978ff74ebeb7
xuechong87/pytests
/pylearn/src/vartypes/FractionTest.py
585
3.53125
4
''' Created on 2013-2-7 定义分数 @author: xuechong ''' import fractions import math def fracTest(): x = fractions.Fraction(1,3); print(x)#result is 1/3 x = x*2 print(x)#result is 2/3 x = None x= fractions.Fraction(6/4)#会自动约分 print(x)#所以结果为3/2 try: x = fractions.Fraction(1/0)#0不能为分...
396daf903f438c18201ce6699f455d95708ddeec
jLoven/tensorflow_test
/test1.py
517
3.5
4
# 10 October 2017 # Jackie Loven import tensorflow as tf # Each node takes zero or more tensors as inputs and produces a tensor as an output sess = tf.Session() # two floating point tensors: node1 = tf.constant(3.0, dtype=tf.float32) node2 = tf.constant(4.0) # also tf.float32 implicitly node3 = tf.add(node...
e16bb8bfee9e0970c98af572c883f615850bf0ab
thebestday/python
/L10/L10.4/coverage_example.py
301
3.75
4
def longest_str(str1, str2): if len(str1) > len(str2): return str1 elif len(str1) == len(str2): return 'Equal' else: return str2 assert longest_str('Volvo', 'Audi') == 'Volvo' assert longest_str('BMW', 'Audi') == 'Audi' assert longest_str('BMW', 'KEA') == 'Equal'
cc4d8ece5db04c93a0b088ceda6b9189088791fe
JosephLevinthal/Research-projects
/5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/226/users/4123/codes/1724_2517.py
128
3.546875
4
h = hf = float(input()) i = 0 while h - 0.5*9.8*i**2>0: hf = h - 0.5*9.8*i**2 print("t = ",i) print("h = ",round(hf,1)) i+=1
52e17574232863b4f96effb4761ceddf5ad61438
SteffanySympson/BLUE-MOD-1
/Desafios/Data por extenso - Comentado.py
2,891
3.578125
4
# Data com mês por extenso. # Construa uma função que receba uma data no formato DD/MM/AAAA e devolva uma string # no formato D de mesPorExtenso de AAAA. # Opcionalmente, valide a data e retorne NULL caso a data seja inválida. # Considere que Fevereiro tem 28 dias e que a cada 4 anos temos ano bisexto, # sendo que n...
8f2806136320a7ae60d6ec17f32ea4bde77d1870
mailund/compthink
/src/divide and conquer/fib-memorise.py
957
3.59375
4
tbl = {} count = 0 def fib(n): global count, tbl count += 1 if n <= 1: return 1 else: if n not in tbl: tbl[n] = fib(n - 1) + fib(n - 2) return tbl[n] print("n fib count") for i in range(1,11): count = 0 tbl = {} print("{} {} {}".format(i, fi...
44954663fa27c37d90be90c64512eeb9a5ca8ae1
binghosh/projects
/Bachelor Thesis/clip.py
879
3.5
4
from tkinter import Tk from time import sleep r = Tk() r.withdraw() while not r.selection_get(selection = "CLIPBOARD"): sleep(0.1) result = r.selection_get(selection = "CLIPBOARD") r.clipboard_clear() #r.clipboard_append('This goes to clipboard') r.destroy() print(result) import serial import time ...
a83dd565beda62bf120e89e88dba63b6a2048534
Sirlanri/Python
/Notes/修饰器/用户验证.py
519
3.53125
4
class User(): def __init__(self, name, email): self.name=name self.email=email class Anony(User): def __init__(self): self.name=None self.email=None def __nonzero__(self): return 0 import functools def requires(func): @functools.wraps def inner(...
6ea8559a604d4473be0cc3ba9fcd4c893fc91f2a
9719966914/python-programs
/water problem.py
203
3.59375
4
r=5 h=10 Vwtr=15 t=eval(input('enter the time')) Vc=3.14*r**2*h Vwtr= 15*t if Vwtr > Vc: print('overflow') elif Vwtr==Vc: print('tank is full') else: print('underflow')
af62ddb3dd47abde577e5885875187f70ba57f76
mariellewalet/DCP
/problem_288.py
1,089
3.765625
4
""" The number 6174 is known as Kaprekar's contant, after the mathematician who discovered an associated property: for all four-digit numbers with at least two distinct digits, repeatedly applying a simple procedure eventually results in this value. The procedure is as follows: For a given input x, create two new numb...
970d50bfa3677291959ed154279d6edac170537d
Blackweather/linear_gradient
/linear.py
3,418
3.609375
4
import matplotlib.pyplot as plt import numpy as np import random def calculateCostSum(function, dataX, dataY, dataCount): toReturn = 0 for i in range(1, dataCount): functionValue = function(dataX[i]) diff = functionValue - dataY[i] diff *= diff toReturn += diff ...
3281be292439ecd565eb57962e6814f0a29eb1f8
WillLuong97/Greedy-Algorithm
/minNumOfOperationsToMoveAllBallToEachBox.py
2,845
3.65625
4
#1769. Minimum Number of Operations to Move All Balls to Each Box ''' You have n boxes. You are given a binary string boxes of length n, where boxes[i] is '0' if the ith box is empty, and '1' if it contains one ball. In one operation, you can move one ball from a box to an adjacent box. Box i is adjacent to box j if ...
aaa86887860b34b54139cf7f87e5ed22ee9749b7
chihsuanbjjh/binder
/師大計算機課程/Python Turtle/心臟線-逆向.py
2,028
3.609375
4
from turtle import * import math hideturtle() speed(0) # tracer(100,10) screen = Screen() screen.colormode(255) #產生圓的點,畫點 def gen_circle_point(step, radius, x_start=0): theta = 0 circle_list = [] step_angle = 2*math.pi/step for i in range(step): circle_list.append( (x_start+radius*...
76a8b90e8dd9b731511da6f22165ccc3769a0b71
simonszuharev/designing-python
/day 21 (Snake Game)/scoreboard.py
1,338
3.828125
4
from turtle import Turtle ALIGNMENT = "center" FONT = ("Comic Sans MS", 25, "normal") class ScoreBoard(Turtle): def __init__(self): super().__init__() self.score = 0 with open("data.txt") as data: self.high_score = int(data.read()) self.hideturtle() self.penup...
0adf0214ab8b141a714c7a26bc0e11cd6bfe3c91
hobbang2/Algorithm
/백준/Silver/11279. 최대 힙/최대 힙.py
1,426
3.71875
4
import sys def heap_insert(myHeap:list, target:int): # index 를 1부터 시작하고 싶음 myHeap.append(target) cur_idx = len(myHeap) - 1 parent = cur_idx // 2 while( parent >= 1 and myHeap[parent] < myHeap[cur_idx]): myHeap[parent],myHeap[cur_idx] = myHeap[cur_idx],myHeap[parent] ...
6978514b3570fa4f96462c35a90d61e7ca1d39bf
effyhuihui/leetcode
/sort/largestNumber.py
3,252
4.125
4
''' Largest Number ''' ''' Given a list of non negative integers, arrange them such that they form the largest number. For example, given [3, 30, 34, 5, 9], the largest formed number is 9534330. Note: The result may be very large, so you need to return a string instead of an integer. compare() takes two string in, r...
1b13d84d29bcd7ffd8d25a7935333ddf448d051f
abhmora1011/PythonSelenium
/PythonBasics/Inheritance.py
326
3.78125
4
from ObjectOrientedProgramming import Calculator class Child(Calculator): num2 = 200 def __init__(self): Calculator.__init__(self, 10, 5) # Call the constructor of the Parent Class def getSomething(self): return self.num + self.num2 + self.subtract() obj = Child() print(obj.getSomethi...
b4a8d10abb143db5a6b6d2a5d0a17a4c7ee2a799
sajalrustagi/Wiki_Of_Words_Using_Pdf_Wiki_Parser
/FileContentParser.py
2,431
3.734375
4
# This class declares classes/function that can be used parse different type of files and # return the text present in the file # if file is of type pdf, it uses PdfContentParser to parse the content of pdf # if file is of type wiki, it uses WikiContentParser to parse the content of wikipedia page import PyPDF2 import...
4b185f1855d075f8eceb2ad560f0a1841ca17ff5
mayurdongaonkar/mayur
/Strobogrammatic.py
399
3.90625
4
maps = {("0", "0"), ("1", "1"), ("6", "9"), ("8", "8"), ("9", "6")} def rotatenum(nums:str): left = 0 right = len(nums)-1 while(left<=right): print(nums[left]) print(nums[right]) if (nums[left],nums[right]) not in maps: return False else: left = ...
432d83332d091f596f75e924bdbc160a72dbc3af
codxse/mitx6001
/2017/week_2/problem_set23.py
2,887
4.21875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Jan 28 08:56:55 2017 @author: Nadiar """ balance = 320000 annualInterestRate = 0.2 """ Monthly interest rate = (Annual interest rate) / 12.0 Monthly payment lower bound = Balance / 12 Monthly payment upper bound = (Balance x (1 + Monthly interest ...
e6eae978cabbfb75974e81c656a6856864554871
JosephLevinthal/Research-projects
/5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/223/users/4480/codes/1667_2320.py
72
3.734375
4
nome = int(input('nome desejado: ')) harry = 2 rony = 3 if (rony>harry):
553ca86368d5f386ee53acbe080fdc31d3cef499
Eliherc1/poo_python
/5- MathDojo.py
884
3.703125
4
import statistics class MathDojo: def __init__(self): self.result = 0 def add(self, num, *nums): # tu código aquí self.result = self.result + num for n in nums: #print(v) self.result = self.result + n return self def subtract(self, num, *nums...
01a4ed8ba5fe40b3152bc8fe89e4afab165be8be
gowthamthaman6/python
/gcd.py
141
3.53125
4
def GCD(x,y): rem=x%y if(rem==0): return y else: return GCD(y,rem) n,m=map(int,input().split()) print(GCD(n,m))
f63b673b5115013d2ca73ba95275c7aa9957f338
almirgon/LabP1
/Unidade-7/ajeita.py
504
3.671875
4
#coding: utf-8 #Crispiniano #Unidade 7: Ajeita Lista de Números Inteiros def ajeita_lista(dados): while True: condicao = False for i in range(len(dados)-1): if dados[i] < dados[i+1]: dados[i], dados[i+1] = dados[i+1], dados[i] condicao = True if not condicao: break for x in range(len(dados)-1,...
2a0b8a270d60bc083d0607469a9421ffc735b679
kbanzai/code_wars
/python/4kyu/sudoku_solution_validator.py
667
3.609375
4
# https://www.codewars.com/kata/529bf0e9bdf7657179000008 def validSolution(board): def check_list(l): for i in l: if not i in range(1, 10): return False return len(set(l)) == 9 # check rows for row in board: if not check_list(row): return Fal...
e2a7be3fe7442d639ffd408215b1861b3399aa13
fwparkercode/IntroGames
/Fa18_student_games/Zoey Snake/why not.py
7,785
3.640625
4
import pygame import random screen_width = 600 screen_height = 400 # Colors BLACK = (0, 0, 0) WHITE = (255, 255, 255) LIGHT_BLUE = (178, 207, 255) PINK = (168, 94, 153) BLUE = (0, 0, 255) PURPLE = (234, 191, 239) TEAL = (128, 191, 183) # Make Snake Blocks segment_width = 10 segment_height = 10 segment_margin = 2 # ...
22c3055563d9ce7a0c97640fa0a2a683f8b2f777
JerryRoc/leetcode
/2.addTwoNumbers.py
4,026
3.65625
4
# -*- coding: utf-8 -*- """ Created on Tue Sep 4 10:31:29 2018 @author: pg255026 """ import json # Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def addTwoNumbers(self, l1, l2): """ :type l1: ListNode ...
6bcb52a18ca9e2f9d61ceb0206a6c146ba673bdd
karlabelazcos/Ejercicios-Python-Guia-de-examen-
/Ejercicio3. Aleatorio.py
484
3.9375
4
#Se utiliza import para elegir un elemento aleatorio de una lista. import random #Los numeros con punto decimal es de tipo (float). numero1=float(10.5) #La funcion es un conjunto de instrucciones. #Una definición de función es una sentencia ejecutable. def miFuncion(): numero2=float(random.randrange(1,10)) #Lo...
7bdb4767297807265399a186f7c1bd5fe185fc6c
tianzhiliang/algorithm
/sort_algorithm/quick_sort.py
1,004
3.609375
4
import sys arr11 = [1,5,2,9,11,-2,10,4,2,7,6,4,9,1,10] arr12 = arr11[:] def partition(array, left, right): signal = array[right] small = [] large = [] # print "len to sort:", len(array[left: right]) for data in array[left: right]: if data > signal: large.append(data) el...
3edd7e7be0427cad2dc5077aea8c64588b35ccf7
juan-1/Python
/pila_almacen.py
867
3.984375
4
pila=[] paquetes=0 print("Sistema de almacen") while True: conta=0 print("Menú") print("1 para ingresar paquetes") print("2 para extraer paquetes") print("3 ver total de paquetes") print("4 ver pila de inventario") print("0 salir") select=input("# ") if(select=='1'): #ingresa paquetes dia=input("Día: ") ...
2358c45c242293acd6d70de10696434943dde961
PrishaTHE-PRO/C-100-
/Car.py
559
3.5
4
class Car (object): def __init__ (self,model,color,company,speed_limit): self.color=color self.model=model self.company=company self.speed_limit=speed_limit def start (self): print('started') def stop (self): print('stopped') def accelerat...
4d176aee66146e1fd7c1cbc5268707ed717faae6
Ashishkapil/python-runs
/custom-dictionary-sort.py
592
3.90625
4
# 1) Sort the input character array based on the dictionary given. # For eg If input word is SHEEP, sorting will make it as EEHPS. # But in the dictionary, E may not be at first. As per the dictionary, if P is first, S followed and E later and finally H. # Then sorted array is PSEEH. from sys import argv, exit adi...
363732ecf0343c4b5866383312b8eb640edf5ad8
kjeelani/YCWCodeFiles
/List Warmups/list1.py
641
3.921875
4
'''Warmup 1: Lists and Dictionaries Error Analysis''' # Objective 1: Print "Jack" to the screen students = ["Jack", "Vladimir", "Zachary", "Corey"] print(students[2]) # Objective 2: Correct the syntax error students = ["Jack", "Vladimir', "Zachary", "Corey"] # Objective 3: Correct the runtime error in the if stateme...
101f6ecdd94d0c1cfab789cca9cc0580cede5c6b
gustavovenuto/ed-not-2021-2
/doubby_linked_list.py
2,045
4.09375
4
""" ESTRUTURA DE DADOS LISTA DUPLAMENTE ENCADEADA - A lista encadeada é uma estrutura de dados formada por unidades de informação chamadas nodos ou nós. - Cada nodo da lista encadeada tem três partes: uma, que armazena a informação; a segunda, que guarda o endereço do nodo...
93611a75432c277a700c55edc510fd3901b90a63
shreshta2000/function_questions
/vote_saral_question.py
207
4.03125
4
def eligible_for_vote(age): if age>=18: result="you are eligible for vote" else: result= "you are not eligible for vote" return (result) age=int(input("entre any age ")) print(eligible_for_vote(age))
3bde8be698117975e9507ed5704c214640030cc3
chao-shi/lclc
/258_add_digits_mod_9_e/main.py
497
3.640625
4
class Solution(object): def addDigits(self, num): """ :type num: int :rtype: int """ # number abcd and a+b+c+d # The different is multiple of 9 # After each round, the new number has the same mod 9 with origin # The final value will be in range of [0, ...
04d49a1be309efdfa448c4a2fc8e5a4a0372b8a6
JamieVic/greeter
/greeter.py
925
4.15625
4
import datetime getDate = datetime.datetime.now() day = getDate.strftime("%A") username = input("Enter Name: ") if day == "Sunday": print("Hello " + username + "! Today is " + day + ", don't panic the weekend isn't over.. yet.") elif day == "Monday": print("Hello " + username + "! Today is " + day + ",...
0b231708bf7f7e522b8df8c8a92741326b06983b
PastorE-ux/datascience-
/Pastor.py
792
3.765625
4
#!/usr/bin/env python # coding: utf-8 # In[4]: import sys bm = [] print('-------Menu------') print('1-----Add Bookmarks') print('2-----Edit Bookmarks') print('3-----Delete Bookmarks') print('4-----View Bookmarks') print('5-----Exit') while True: choose =input("Choose a Number: ") if choose == '1': ...
5cae183bdf686e0905b84da8c35095d999f6a71e
sumitsk1/Old-Python-Codes
/new june 2018/practice/min_max.py
1,223
3.953125
4
# advance min() and max() # numbers = [1,2,4,5,7] # print(min(numbers)) # names = ['Harshit Vashisth', 'Mohit', 'ab', 'z'] # print(max(names, key=lambda item: len(item))) # # students = { # 'harshit': {'score': 50, 'age': 24}, # 'mohit': {'score': 75, 'age': 19}, # 'rohit': {'score': 76, 'age...
f5d2edfdba26448f8c938fa642beb95356015a21
yCanta/yCanta
/convert/higherpraise.py
2,030
3.515625
4
import urllib2 import re def convert(input_url): '''return a dictionary as documented in __init__.py ''' # Example higherpraise.com content # <div aligni="center"><!-- #BeginEditable "1" --> # <table attrs=". . . "> # ... # <h1 align="center"><b><font class="default"><u> # Title text </u...
779981cd53be2b0c4e8d8442528e2227da490aa4
dr-dos-ok/Code_Jam_Webscraper
/solutions_python/Problem_200/4122.py
666
3.640625
4
import sys def magic(number): return int(''.join(str(i) for i in number)) # input() reads a string with a line of input, stripping the '\n' (newline) at the end. # This is all you need for most Google Code Jam problems. nbrlines = int(input()) for k in range(nbrlines): t = input() data = [int(i) for i in t] ...