blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
92adc354aecbc916df9e6c9a5872491972a21c79 | esmirna21/Practicas-Python | /Practica_4/5.py | 764 | 3.890625 | 4 | '''5- Cree una clase Carro, con un campo llamado _cantidadCombustible y un
método que se llame Encender el cual en base a la gasolina disponible
mostrara si el carro pudo o no avanzar. Cada vez que el método se ejecute,
deberá restarse 1 a la gasolina disponible. La cantidad de gasolina debe
establecerse al momento de ... |
87c4d4f123081391c89fdd53c97b93638fed0006 | esmirna21/Practicas-Python | /practica_2/4.py | 785 | 3.703125 | 4 | """4- Realizar un programa que reciba
por teclado el sueldo de un empleado y
le aplique los cálculos de ISR (ver tabla DGII),
ARS, y AFP (investigar porcentajes)"""
top1 = 416220.00
top2 = 624329.00
top3 = 867123.00
sueldo = (float(input("ingrese su sueldo: ")))
salario_anual = sueldo * 12
isr = 0;
if salario_anual... |
ea78d5a14886b403387aca187c4a4a7d2c6ba2fc | siraom15/coffee-to-code | /Python/slothPete7773.py | 149 | 3.90625 | 4 | coffee = 'coffee'
word = [char for char in coffee]
word = list(filter(lambda char: char in ['c', 'o'], word))
word.append('de')
print("".join(word))
|
0683f69688ce3dc244574a6edac38d588c2b4b86 | Rhylan2333/Python35_work | /chapter_e_a.py | 588 | 3.953125 | 4 | """
Python 实现isNum函数,参数作为一个字符串,
如果这个字符串属于整数、浮点数、或复数的表示,
则返回True,否则返回False。
"""
msg = input("请输入一个字符串(属于整数、浮点数、或复数):")
def isNum(string) :
try :
num = eval(string)
if type(num) == float\
or type(num) == int\
or type(num) == complex :
return True
else :
... |
3b7c18cd464999ae45f1cb27a76585ec7f0764e9 | Rhylan2333/Python35_work | /精品试卷 - 01/基本操作题 3:比赛成绩计算.py | 365 | 3.6875 | 4 | """
基本操作题 3:比赛成绩计算
"""
#在…处填写多行代码
#不允许修改其他代码、
score = [[87,79,90],[99,83,93],[90,75,89],[89,87,94],[95,85,84]]
for i in range(len(score)) :
a1 = score[i][0]
a2 = score[i][1]
a3 = score[i][2]
final = a1*0.6 + a2*0.3 + a3*0.1
print('the {} final score is {}'.format(i+1, int(final)))
|
eb6f4bafd4d99fa352fe72ceab4a6656611b80ec | Rhylan2333/Python35_work | /精品试卷 - 01/简单应用题 2:员工工资表.py | 784 | 3.875 | 4 | """
简单应用题 2:员工工资表
"""
#请在____处写一行表达式
#请在…处写多行代码
#可以修改其他代码
members = {'张三':['人力部',5500],
'李四':['后勤部',4500],
'王三':['市场部',6500],
'赵六':['开发部',8500]
}
sal_dep = {}
for key in members : # 只遍历key,不输出value
name = key
salary = members[key][1]
department = members[key... |
bbf4d860751ccba074f1c9ca1b9f1231c95570dc | Rhylan2333/Python35_work | /精品试卷 - 05/基本操作题 1:信息输出.py | 108 | 3.515625 | 4 | # 在_____处填写一行代码
ls= input().split(",")
print(ls[-1]*int(ls[0]) + ls[0] + ls[-1]*int(ls[0]))
|
2989f0fa125bbf6233c0f25a50579b0105681c27 | Rhylan2333/Python35_work | /Backwards_Fluently_a.py | 123 | 3.625 | 4 | # Backwards_Fluently
s = input("请输入一段文本:")
i = len(s) - 1
while i > 0 :
print(s[i], end='')
i -= 1
|
41308b19a447c27b9a8f403c2e0615e0d02e52a2 | Rhylan2333/Python35_work | /精品试卷 - 05/基本操作题 2:课程分数排序输出.py | 696 | 3.703125 | 4 | # 在_____处填写一行代码
# 不得修改其他代码
# -*- coding:utf-8 -*-
studs= [{'sid':'103','Chinese': 90},{'sid':'101','Chinese': 80},{'sid':'102','Chinese': 70}]
scores = {}
k = None
for stud in studs:
sv = stud.items()
for it in sv:
if it[0] =='sid': #第一次访问:it = ('sid','103')
k = it[1] # k = '103'
e... |
19c50a8c65bb16d73779f604d0ebb37aa4d7533c | Rhylan2333/Python35_work | /chapter_c_e.py | 499 | 3.828125 | 4 | # 输入一个十进制整数,分别输出其二进制、八进制、十六进制字符串
num = eval(input("输入一个十进制数,我将分别为你输出其二进制、八进制、十六进制\n:"))
print("十六进制:" + hex(num))
print("八进制:"+ oct(num))
# 接下来换算二进制
msg = ''
while num > 1 : # 用“除二法”求十进制数的二进制表示
num, rem = divmod(num, 2) # rem非0即1
msg += str(rem)
msg = '1' + msg
print('二进制:' + msg)
|
63029a5c37a66c02d421f990088df7c8b63b7713 | Rhylan2333/Python35_work | /chapter_e_d.py | 597 | 4.1875 | 4 | #编写一个函数,打印200以内的所有素数,以空格分隔
def isPrime(num) :
"""
: para num: 输入的整数
: return: 质数返回True,否则返回False
"""
if num < 2 :
return False
for i in range(2, num) :
if num % i == 0 :
return False
return True
def printPrime() :
"""用一下isPrime(),输出小于200的质数"""
print("小于200的素数如... |
a0743abe6a8daed59c5744756532aee34f417d24 | Rhylan2333/Python35_work | /精品试卷 - 04/基本操作题 2:计算总成绩.py | 231 | 3.59375 | 4 | #请在__________上补充完成一行代码
#不改变已有的编程框架内容
with open("data.txt","r",encoding="utf-8") as fi:
line = fi.readline().split(',')
sum = 0
for i in line[1:]:
sum += int(i)
print(sum)
|
049edf15ce601504a15d2c56b2c6c7f991436d12 | Rhylan2333/Python35_work | /chapter_i_a.py | 1,275 | 3.671875 | 4 | # 使用turtle库绘制一个蜂窝状六边形
import turtle
turtle.setup(1080, 720, None, None)
r = 50 # 定半径
x0 = -300
y0 = 50
def draw_Agon() :
for i in range(2,12,2) :
turtle.penup()
turtle.goto(x0+i*r, y0)
turtle.pendown()
turtle.circle(r, extent=360) # 画圆
turtle.penup()
turtle.goto(x... |
b271afc467593e9051788cb688ab4e38d0bdfd4f | fatemehmakki13/CIS2001-Winter2017 | /Lab2/Lab2/Lab2.py | 1,652 | 3.578125 | 4 | from Item import Item
class BulkItem(Item):
def __init__(self, name, sku, price_per_pound, number_of_pounds):
super().__init__( "(Bulk) " + name, sku, price_per_pound * number_of_pounds )
self.price_per_pound = price_per_pound
self.number_of_pounds = number_of_pounds
class TaxableItem(Item... |
f720136968ba147184115f9017d7d74946860e4e | Jfeng3/careercup | /LeetCode/tank.py | 1,827 | 3.890625 | 4 | #2. In a cartesian plane, there are N tanks and M objects placed. Tanks can fire in 4 directions (N, S, E, W). Position of tanks and objects are given as input and are fixed. We have to find a way to give directions to N tanks such that they will not hit any object and any other tanks. If a tank can fire in 2 direction... |
8eddcff2fc4e6b4ec4c47322655574cbad3991f6 | Jfeng3/careercup | /LeetCode/divide_two_integers.py | 850 | 3.734375 | 4 | class Solution:
# @return an integer
def divide(self, dividend, divisor):
if divisor ==0:
return MAX_INT
elif dividend == 0:
return 0
sign = 1
if dividend>0 and divisor<0 :
sign = 0
divisor = -divisor
elif dividend<0 and di... |
1bcc6f5be44456ea3c4484d11880015916d42df3 | phoebelxd/LearningPython | /circumference.py | 126 | 4.1875 | 4 | #!/usr/bin/python
pi = 3.14159
radius = 3
print("The circumference of a circle of radius 3 is " + str (pi * radius * 2.0))
|
69f17bc8c5a109d513a621ea6e5233d267b7060f | ironnerves/Lousy-Multi-Language-Encryptor | /Lousy python encryptor 2.py | 3,287 | 3.734375 | 4 | #Hey! Stop looking at my code!
#Well, this is a lousy piece of shit code,
#So do whatever you want to this crap.
print("Please type the message you want to encrypt. Please, no spaces.")
a = input()
avaliable_letters = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x",... |
ac04ea05f8b775ee5396c251f97b9bfca34001c6 | prem17101996/GFG-PROBLEMS | /Geek and Books.py | 462 | 3.5625 | 4 | #code
for i in range(int(input())):
n=int(input())
str2=""
lst=[]
for i in range(n):
str1=input()
if str1[:5]=="place":
str1=str1.split()
lst.append(str1[-1])
elif str1[:6]=="remove":
if len(lst)<1:
str2=str2+"-1"+" "
... |
f66886dd51afc78ea7f2a1669803780403b6e85c | Beomus/py-dsa | /ds/BST/tests/bst_construction_test.py | 2,723 | 3.546875 | 4 | import unittest
from ..bst_construction import BST_Iterative, BST_Recursive
class TestBST(unittest.TestCase):
def setUp(self) -> None:
self.BST = [BST_Iterative, BST_Recursive]
def test_case_1(self):
for BST in self.BST:
root = BST(10)
root.left = BST(5)
r... |
2445b1faef96f2184d424a515fc6d7c3ff62c7c1 | Beomus/py-dsa | /problems/arrays/validate_subsequence.py | 779 | 4 | 4 | """
Validate Subsequence
Given two non-empty arrays of integers, write a function that determines whether
the second array is a subsequence of the first one.
A subsequence of an array is a set of numbers that aren't necessarily adjacent in
the array but that are in the same order as they appear in the array. For inst... |
bbdc715bcb12bb2d53d218e70e9193f6c6833f3c | Beomus/py-dsa | /problems/arrays/tests/two_sum_test.py | 774 | 3.546875 | 4 | import unittest
from ..two_sum import twoSum
class TestTwoSum(unittest.TestCase):
def test_case_1(self):
array = [3, 5, -4, 8, 11, 1, -1, 6]
target = 10
result = twoSum(array, target)
self.assertCountEqual(result, (11, -1))
def test_case_2(self):
array = [4, 6]
... |
132165ed9c45c8df461fd1eb7010416750bdc697 | MLyons97/Data24Repo | /Week5/WorkingWithFiles/WritingToFinal.py | 328 | 4.0625 | 4 | def write_to_file(file, order_item):
try:
with open(file, "a") as file:
file.write(order_item+"\n")
except FileNotFoundError:
print("The file "+file+" does not exist") #While there is the "w" in open, this error won't show as "w" creates the file
write_to_file("writing_test.txt", "... |
6ae9e483daba449fb047e9c6d34537944e0fe78c | MLyons97/Data24Repo | /Week 4/Python/Variables/Sets.py | 399 | 3.78125 | 4 | ##Sets can't have repeated values BUT are mutable
##unless you make it as a frozen set (x=frozenset(set,stuff,goes,in,here)
Car_Parts = {"Wheels", "Engine", "Gearbox", "Doors", "Windscreen"}
print(Car_Parts)
Car_Parts.add("Wing mirrors")
print(Car_Parts)
#As they can't have repeated values, can be used to test anagram... |
e3be704916fd4d167740bd94cda5aa85209276e7 | MLyons97/Data24Repo | /Week 4/Python/OOP/HangmanGame.py | 8,266 | 4.25 | 4 | # Gets the initial word which will attempt to be guessed
def get_initial_word() -> str:
parser = True # A 'parser' variable here used with the while loop to ensure
while parser: # that all inputs are on... |
27b034cf6125ca4096a7e38a95fa42db288998c7 | MLyons97/Data24Repo | /Week 4/Python/OOP/Calculator.py | 693 | 3.875 | 4 | import math
def add(*multiargs) -> float:
total = 0
for arg in multiargs:
total += arg
return total
def subtract(*multiargs) ->float:
total = multiargs[0]
for arg in range(1, len(multiargs), 1):
total -= multiargs[arg]
return total
def multiply(*multiargs) ->float:
tota... |
053664c12cb3c1c63096d81540ab1e4e6c8fb17b | MLyons97/Data24Repo | /Week 5/PipSaving/LambdasQuestions.py | 1,104 | 4.3125 | 4 | print("\nQ1a\n")
# Q1a: Replicate the following functions as lambda
# A1a: answers shown below functions
def square(n):
return n*n
lsquare = lambda n: n*n
def percentage(n):
return n/100
lper = lambda n: n/100
def multiplier(n, m):
return n*m
lmult = lambda n, m: n*m
def addition(a, b, c):
... |
5a89de4060adac652b1e04ad45175190771092b1 | TatterTott/CS3030-Fall2019 | /statRoller.py | 2,051 | 3.8125 | 4 | import random
class StatRoller():
def rollForStats(character):
shouldRoll = input("Would you like the program to randomly roll your stats?").lower()
if shouldRoll == "yes":
roller(character)
badRoll= True
while badRoll:
isBad = input("Would you li... |
f76afb5dcc20725615fee59b8adceb4ad3a7a711 | antonypap/IEEEXTREME12.0 | /TelescopeScheduling.py | 845 | 3.640625 | 4 | # a simple parser for python. use get_number() and get_word() to read
def parser():
while 1:
data = list(input().split(' '))
for number in data:
if len(number) > 0:
yield(number)
input_parser = parser()
def get_word():
global input_parser
return next... |
9cddc517dcc21df2e27d0c7db6646250f161869d | sinvalfelisberto/python_curso_video | /aula07/ex008.py | 244 | 3.953125 | 4 | numero = int(input('Digite um numero: '))
dobro = numero * 2
triplo = numero * 3
raiz_quadrada = numero ** (1/2)
print(f'O dobro de {numero} é {dobro} \nO triplo de {numero} é {triplo} \nA raiz quadrada de {numero} é {raiz_quadrada:.1f}')
|
1f636e9bb031ee3c6ffacf2a801144efe1d77bb3 | sinvalfelisberto/python_curso_video | /aula07/ex010.py | 232 | 4.1875 | 4 | """
Convertendo um valor em metro para cm e mm
"""
valor = float(input('Digite um valor: '))
centimetro = int(valor * 100)
milimetro = int(valor * 1000)
print(f'O medida de {valor} m corresponde a {centimetro}cm e {milimetro}mm!') |
1bf4a0e3018b23f3a4133e413568ea7e97f38c17 | sinvalfelisberto/python_curso_video | /aula13/desafios/ex052_corrigido.py | 415 | 3.859375 | 4 | numero = int(input('Digite um número: '))
total = 0
for c in range(1, numero + 1):
if numero % c == 0:
print(f'\033[1;31m{c}\033[m',end=' ')
total += 1
else:
print(f'\033[1;33m{c}\033[m', end=' ')
print(f'\nO número {numero} tem {total} múltiplos!', end=' ')
if total == 2:
print(f'Po... |
f71743fc367b776f0f2a41615620f62111b8069c | sinvalfelisberto/python_curso_video | /aula13/desafios/ex051.py | 278 | 3.828125 | 4 | primeiro_termo = int(input('Digite o primeiro termo da PA: '))
razao = int(input('Digite a razão da PA: '))
termos = []
for c in range(primeiro_termo, (primeiro_termo+(10 * razao)), razao):
termos.append(c)
for i in range(0, 10):
print(f'{i + 1}º termo: {termos[i]}')
|
48b93c811d49fae24895c0c76c8439f25939d9a9 | sinvalfelisberto/python_curso_video | /aula07/ex005.py | 426 | 3.90625 | 4 | print('Módulo de Habitação')
meses = int(input('Digite a quantidade de meses restantes do seu contrato: '))
anos = meses // 12
restoMeses = meses % 12
if restoMeses > 0:
print('Restam {} anos e {} meses para o fim do seu contrato!'.format(anos, restoMeses))
else:
print('Restam {} anos para o fim do seu contrat... |
470b6b4905642eeb046f1f53a9a469e479a1b21e | sinvalfelisberto/python_curso_video | /aula12/desafios/desafio38.py | 333 | 4.0625 | 4 | numero1 = int(input('Digite o primeiro valor: '))
numero2 = int(input('Digite o segundo valor: '))
if numero1 == numero2:
print('Os valores são iguais!')
elif numero1 > numero2:
print(f'O número {numero1}, que é o primeiro valor, é o maior!')
else:
print(f'O número {numero2}, que é o segundo valor, é o mai... |
fa9029a21f795ca9d8c6751225a5576404a0d785 | sinvalfelisberto/python_curso_video | /aula12/desafios/desafio43.py | 776 | 3.796875 | 4 | from math import pow
peso = float(input('Digite seu peso: '))
altura = float(input('Digite sua altura: '))
#tanto faz altura em centimetros ou metros
if altura > 3:
altura /= 100.0
imc = peso / (pow(altura, 2))
if imc < 18.5:
print(f'\033[1m\033[7;31mIMC: {imc:.2f} Você está abaixo do peso ideal!\033[m')
elif... |
21f49cb442d8dbaee0fff308dcc065c53d244062 | stevegcarpenter/hackerrank-problems-python | /the-minion-game.py | 498 | 3.75 | 4 | #!/usr/bin/env python3
# https://www.hackerrank.com/challenges/the-minion-game/problem
def minion_game(string):
vowels = {'A', 'E', 'I', 'O', 'U'}
score_k, score_s, ln = (0, 0, len(s))
for i in range(ln):
if s[i] in vowels:
score_k += (ln - i)
else:
score_s += (ln ... |
c397ad7a5ec151830e032629799002ecd4e6d76f | Lakshya0744/tuts | /.ipynb_checkpoints/02_loan_predict_log-checkpoint.py | 1,429 | 3.53125 | 4 | import logging
logging.basicConfig(filename='02_logs.log',
format='%(asctime)s::%(levelname)s::%(message)s::',
level=logging.INFO)
def predict_loan(income, married, age):
"""Given the income, marital status and age of a person this function will predict the loan am... |
c2932a39ef8ea131f4916254e7b2e1c00165a5f3 | RoboBeats/Ev3-tictactoe | /logic.py | 3,133 | 3.53125 | 4 | from copy import deepcopy
def player_won(board, occupant):
for i in range(len(board)):
if board[i] == [occupant, occupant, occupant]:
return True
diagonal_win = 0
diagonal_win2 = 0
for i in range(len(board)):
if board[i][i] == occupant:
diagonal_win += 1
... |
323c17e1c828629f8e9eb40aaf2f5e598afe484b | kleimkuhler/snippets | /Python/acyclicity.py | 1,027 | 3.734375 | 4 | from utils import *
name = 'acyclicity'
def adjacency_list(elf):
"Create an adjacency list from edge-list format."
adjlist = defaultdict(list)
for edge in elf[1:]:
adjlist[edge[0]].append(edge[1])
return adjlist
def cyclic(root, adjlist, visited):
"Determine if a path of nodes through an ... |
af76082eb3e5539d34d69d7714637655912c5ecf | Dishvater/sda_pycharm_python | /python podstawy d2/d2/python_basic/python_basic/tut/p09_factorial.py | 262 | 4.125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
def factorial(x):
if x == 0:
return 1
else:
return x * factorial(x-1)
if __name__ == '__main__':
value = 6
result = factorial(value)
print(f'Factorial of {value} is {result}')
|
1e4110237cfcfc5b13d13fe6f5b247d9219e24be | sintocos/Xiaomi_OJ | /2_challenge/16_arithmetic.py | 2,314 | 3.625 | 4 | # -*- coding: UTF-8 -*-
# description: 实现一个算法,可以进行任意非负整数的加减乘除组合四则运算。注意运算符的优先级。
#
# example: input:3 + 5 (输入为一行算式,使用空格分隔数字与运算符。数字为任意非负整数,运算符为+ - * /,不考虑括号。)
# output:8 (输出算式的结果。如果是小数,向下取整(包含中间步骤结果)。如果出现“除0异常”,输出err)
"""
@param string line 为单行测试数据
@return string 处理后的结果
"""
def solution(line): # 用栈来实现
d... |
3831c2aa5d6856a141cf6c81a8211e7bea892467 | sintocos/Xiaomi_OJ | /2_challenge/50_largest_rectangle.py | 1,038 | 4 | 4 | # -*- coding: UTF-8 -*-
# description: 在一个平面图上,有多个宽度固定为1,高度不同的矩形并列排着,在这些矩形所组成的图形中,能够切割出的最大矩形的面积是多少?
# 举例:高度为2,3,2的三个矩形所组成的图形,能够切割出的最大的矩形面积为6。
#
# example: input:5,6,7,8,3 (一组正整数,分别用逗号隔开,表示每个矩形的高度,0<高度<100)
# output:20 (一个整数,表示组合成的最大的矩形面积)
"""
@param string line 为单行测试数据
@return st... |
3c3903775daf270f0629b9c799a66ec1046acc09 | sintocos/Xiaomi_OJ | /1_easy/11_short_string.py | 1,039 | 3.671875 | 4 | # description:给定任意一个较短的子串,和另一个较长的字符串,判断短的字符串是否能够由长字符串中的字符组合出来,且长串中的每个字符只能用一次。
# example: input:uak areuok (一行数据包括一个较短的字符串和一个较长的字符串,用一个空格分隔,如: ab aab bb abc aa cccc uak areuok)
# output:true (如果短的字符串可以由长字符串中的字符组合出来,返回字符串 “true”,否则返回字符串 "false",注意返回字符串类型而不是布尔型。)
"""
@param string line 为单行测试数据
@return string 处理后... |
8bde203f081a91b3e083b0f0351aa8bb7877ac17 | sintocos/Xiaomi_OJ | /2_challenge/7_positive_missing_M.py | 2,508 | 3.65625 | 4 | # -*- coding: UTF-8 -*-
# description: 给出一个无序的数列,找出其中缺失的第一个正数,要求复杂度为 O(n)
# 如:[1,2,0],第一个缺失为3。 如:[3,4,-1,1],第一个缺失为2。
# example: input:1,2,0 // 3,4,-1,1 // -1,-3,-5 // 1,2,3 // -1,-10,0
# output:3 // 2 // 1 // 4 // 1
"""
@param string line 为单行测试数据
@return string 处理后的结果
"""
... |
29134e8b9bb9ee3e4ba875aac818b81599a50584 | sintocos/Xiaomi_OJ | /2_challenge/43_find_normalization_number.py | 2,499 | 4.0625 | 4 | # -*- coding: UTF-8 -*-
# description: 有一类正整数我们叫做归一数字,对于任意一个归一数字 N,满足以下特性:
# N的每一位的平方和组成一个数,新数字的平方和再组成一个新数字,如此往复运算,直到最终结果为1。
# 若一个数字能最终归一成 1,则该数字为归一数字,否则不是归一数字。
# 举例: 82可以分解为8^2+2^2=68,68继续分解为6^2+8^2=100,100可以分解为1^2+0^2+0^2=1。所以82可以归一。
#
# example: input:50 (一个正整数N(0<N<100000... |
7f63446221afdb9288f292cf2be9409aef1fff4a | sintocos/Xiaomi_OJ | /2_challenge/85_robbery.py | 1,937 | 3.921875 | 4 | # -*- coding: UTF-8 -*-
# description: 你是一名专业劫匪,并且正在计划抢劫一条街道上的所有房子。每个房子有一定数量的现金。
# 唯一能够阻止你的就是安保系统被触发,当有两个相邻的房子在同一晚被劫时,安保系统才会自动触发。
# 现在给你一个正整数数组表示每家现金数,请求出这一晚你能在不触发安保系统时抢到的最大金额。
#
# example: input:1,2 (由逗号分隔的一串正整数,表示这一条街上每个房子内的现金数。)
# output:2 (一个正整数,表示你能抢到的最大金额。)
"""
@param... |
2104fb5cae9b87ee0398050d4015d06cfcb53558 | sintocos/Xiaomi_OJ | /1_easy/67_count_off.py | 884 | 3.625 | 4 | # description:有 500 个小孩围成一圈,编号从 1 到 500,从第一个开始报数:1,2,3,1,2,3,1,2,3,……每次报到 3 的小孩退出。
# 问第 n 个被淘汰的小孩,在最开始 500 人里是的编号是几?
# example: input:206 (正整数N,表示要计算的为第 N 个淘汰的小孩的编号,0 < N <= 500)
# output:176 (第N个淘汰的小孩的编号)
"""
@param string line 为单行测试数据
@return string 处理后的结果
"""
def solution(line):
n = in... |
e752427abc01add4c37c473c2a029605ce16f2d1 | sintocos/Xiaomi_OJ | /4_difficult/8_min_exchange.py | 938 | 4 | 4 | # -*- coding: UTF-8 -*-
# description: 给出一个无序数列,每次只能交换相邻两个元素,求将原数列变成递增数列的最少交换次数。
# 如:数列:2,3,1,交换3和1后变成:2,1,3;交换1和2之后变成:1,2,3。总共交换2次。。
# example: input:2,3,1 (逗号隔开的正整数数列)
# output:2 (正整数)
"""
@param string line 为单行测试数据
@return string 处理后的结果
"""
def solution(line):
number = [int(x) for x ... |
c899c4c4dc0200d70488d93751f9e57a2f0c7a9e | akankaku1998/Number-Guessing-Game | /main.py | 876 | 4.15625 | 4 | from art import logo
from random import randint
def guess(attempt, level, computer):
while(attempt != 0):
print(f"You have {attempt} attempts remaining to guess the number.")
num = int(input("Make a guess: "))
if num == computer:
print(f"You got it! The answer was {num}.")
return
elif nu... |
cd171156d3d643e390fb65bc7d92c5069edec2f3 | RejwanaRetu/Python-Problems | /1..py | 187 | 3.8125 | 4 |
# coding: utf-8
# In[13]:
x = float(input("Enput length in centimeter: "))
y = float(x/100)
print('Length in meter is: ', y)
z = float(x/100000)
print('Length in kilometer is: ', z)
|
75f0b80fcaaf11cf9a40d44bcf0bd2a15804dd9e | RejwanaRetu/Python-Problems | /7..py | 90 | 3.78125 | 4 |
# coding: utf-8
# In[4]:
x = (input('Enter a number: '))
print('length is:' ,len(x))
|
2fbf8b5ca01d869902bf30c52222a285fac3f16a | thiagomtt/codecademy | /python/censor_dispenser/censor_dispenser.py | 2,551 | 3.96875 | 4 | # These are the emails you will be censoring. The open() function is opening the text file that the emails are
# contained in and the .read() method is allowing us to save their contexts to the following variables:
email_one = open("email_one.txt", "r").read()
email_two = open("email_two.txt", "r").read()
email_three =... |
c99f2c49405f2d9095bd8138a898b43ed2631d25 | yellowRanger1111/Algorithm-and-Data-Structures | /GIT/Algorithm/Radix Sort/Radix Sort.py | 5,089 | 4.0625 | 4 | import random
import timeit
def count_sort_radix(array, index_to_sort, base):
'''
this function will sort a certain digit(index to sort) in base 10 or at the same logic in any base but might not be a certain digit
param array, the power number, base
return stable sorted array ... |
a83f31f395483a1e4803ffec91f243232336e291 | yellowRanger1111/Algorithm-and-Data-Structures | /GIT/Data Structures/Tree/Trie.py | 5,671 | 3.828125 | 4 | '''
Author = Owen Austin Oei
17/05/2020
'''
# ENABLE_COMPLEXITY_TEST = True
class Trie:
'''
class of trie
function = store words
'''
#ord a = 97
def __init__(self, text):
'''
this function will initiaize the class and fill with all word in text
param ... |
8ce29d2d6ca782130533f553763ed9f5d5e409d1 | Monikabandal/My-Python-codes | /Find the closest pair from two sorted arrays.py | 755 | 3.828125 | 4 | """
int ar1[] = {1, 4, 5, 7};
int ar2[] = {10, 20, 30, 40};
"""
def closest_pair(arr1,arr2,val,arr1L,arr2L):
distance=99999999
low=0
high=arr2L-1
res1=low
res2=high
while(low<arr1L and high>=0):
if(abs(arr1[low]+arr2[high]-val)<distance):
distance=abs(arr1[... |
2afd5e2c2e6131b13d07725fb78ff0a89761c34e | Monikabandal/My-Python-codes | /word break problem.py | 493 | 3.546875 | 4 | l=['this','is','famous','word','break','problem','problems','words']
string='wordsbreakproblems'
dict={}
for i in l:
dict[i]=1
def word_break_problem(dict,string,out):
if len(string)==0:
print out
for i in range(1,len(string)+1):
z=string[0:i]
key=''.join(z)
... |
e5c8ddf8de9631042ddf0a9977d8545172944aa1 | Monikabandal/My-Python-codes | /Duplicate element within K distance.py | 471 | 3.828125 | 4 | def check_k_distance(distance,z):
dict=set()
for i in range(0,len(z)):
if z[i] in dict:
return True
dict.add(z[i])
if(i>=distance):
dict.remove(z[i-distance])
print dict
return False
Number_of_elements= input()
z=[]
for i in r... |
8eab5be2b8cecbd903f71f98690c034392d4c447 | Monikabandal/My-Python-codes | /Lowest Common Ancestor in a Binary Tree.py | 1,572 | 3.78125 | 4 | __author__ = 'pjha'
class Tree(object):
def __init__(self,data):
self.right=None
self.left=None
self.data=data
def insert(root,data):
if(root==None):
return Tree(data)
if(data<root.data):
root.left=insert(root.left,data)
else:
root.righ... |
9c09c06b4151bd390681bef95ef6dfe87c0518d6 | Monikabandal/My-Python-codes | /Number of Interest.py | 402 | 3.625 | 4 | def fib_to(n,x,y):
fibs=[]
for i in range(0,x):
fibs.append(y)
if(len(fibs)==2):
fibs.append(fibs[-1]+fibs[-2])
for j in range(x, n):
fibs.append(fibs[-1] + fibs[-2]+fibs[-3])
return fibs
x=input()
for i in range(0,x):
a=map(int,raw_input().split())
... |
e62cdc53bc66dfbbcf9ddcf3fdcca8d457ccdeeb | Monikabandal/My-Python-codes | /string reduction quiick.py | 695 | 3.546875 | 4 | def stringReduction(a):
total_a=len(a.replace('b','').replace('c',''))
total_b=len(a.replace('c','').replace('a',''))
total_c=len(a.replace('a','').replace('b',''))
if total_b==0 and total_c == 0 and total_a !=0:
return total_a
if total_a == 0 and total_c == 0 and total_b != 0:
... |
442fccfc03027e607e37d4790b8012f7668051ea | Monikabandal/My-Python-codes | /Hamming.py | 199 | 3.734375 | 4 | def hamming2(s1, s2):
return sum(c1 != c2 for c1, c2 in zip(s1, s2))
x=input()
for i in range(0,x):
a=map(int,raw_input().split())
A=bin(a[0])
B=bin(a[1])
print hamming2(A,B)
|
06f86770b3e9362f0576b996d6227315642c2d96 | Monikabandal/My-Python-codes | /Pravin ,Saddam and their Aptitude question.py | 420 | 3.59375 | 4 | __author__ = 'pjha'
def main():
N=input()
for i in range(0,N):
x=raw_input()
X=x.split()
A=int(X[0])
B=int(X[1])
product=0
for i in range(A,B+1):
product=product+fact(i)
print product%10
def fact(i):
if i==0:
... |
a1930a13707b0210964176f911261eaad47a29aa | Monikabandal/My-Python-codes | /Unenrolled Linked List.py | 591 | 3.96875 | 4 | class node:
def __init__(self,V):
self.array=[]
self.elements=V
self.next=None
def print_list(head,size):
while(head is not None):
for i in range(0,size):
print head.array[i]
head=head.next
head=node(3)
second=node(3)
third=node(3)
head.... |
a4b0c79ba79832e4608d0658a8af79bcad9cdd6a | Monikabandal/My-Python-codes | /Dynamic problem coin change.py | 332 | 3.65625 | 4 | def numberofways(coin_set,sum,len):
if sum==0:
return 1
if sum<0:
return 0
if len<0 and sum>0:
return 0
return numberofways(coin_set,sum-coin_set[len],len) + numberofways(coin_set,sum,len-1)
coin_set=[1,2,3]
sum=6
print numberofways(coin_set,sum,len(coin... |
7b310a7ce225e97f3240cba6b34164df7a1d1a77 | Monikabandal/My-Python-codes | /Print all subarrays with 0 sum.py | 541 | 3.625 | 4 | def print_all_subarray(arr):
sum=0
suba=[]
Hash={}
for i in range(0,len(arr)):
sum=sum+arr[i]
if sum==0:
suba.append([0,i])
if sum in Hash.keys():
for j in Hash[sum]:
suba.append([j+1,i])
try:
Hash[sum]... |
71eba5bd109e669a56277e23b2f883c023533757 | Monikabandal/My-Python-codes | /dictionary using trie.py | 2,287 | 3.71875 | 4 | class node:
def __init__(self):
self.children=[None]*26
self.count=0
self.leaf=False
class Trie:
def __init__(self):
self.root=self.getNode()
def getNode(self):
return node()
def return_index(self,ch):
return ord(ch)-ord('a')
def in... |
65dfc9c77b7c3895b0686da753a335b902626d62 | Monikabandal/My-Python-codes | /CODExJEC.py | 534 | 3.640625 | 4 | __author__ = 'pjha'
for i in range(0,input()):
y=0
x=input()
if(x%8==0 and y==0):
print 'Side Upper'
y=1
if(x in(7,15,23,31,39,47,55,63,71) and y==0):
print 'Side Lower'
y=1
if(x in (1, 4, 9, 12, 17, 20, 25 ,28, 33, 36, 41, 44, 49, 52, 57, 60, 65, 68)and y... |
05d639a7a5e22b441b4a8b3ac506e8cc71a08435 | Monikabandal/My-Python-codes | /prime probability.py | 502 | 3.671875 | 4 | __author__ = 'pjha'
def count_prime(a,b):
num=a
count=0
while(a<=b):
if(num>1):
i=2
while(i<num):
if(num%i==0):
break
else:
count=count+1
i=i+1
a=a+1
return ... |
291d2f638599f0f1cfd68f90e5d105abe2220929 | Monikabandal/My-Python-codes | /Link list.py | 525 | 3.921875 | 4 | class Node(object):
def __init__(self, data, next_node=None):
self.data = data
self.next_node = next_node
def get_data(self):
return self.data
def get_next(self):
return self.next_node
def set_next(self, new_next):
self.next_node = new_next
return new_next
def ... |
7c786bdab79b16fe625a71014dd04f7c3d9059cf | Monikabandal/My-Python-codes | /The celebrity Problem.py | 588 | 3.734375 | 4 | """
{{0, 0, 1, 0},
{0, 0, 1, 0},
{0, 0, 0, 0},
{0, 0, 1, 0}};
"""
def isknows(a,b,list):
return list[a][b]==1
def celebrity_problem(list):
length=len(list[0])
a=0
b=length-1
while(a<b):
if(isknows(a,b,list)):
a=a+1
else:
b=b-1
fo... |
11b1332c12b4f7d893423dd43746babab6927888 | Monikabandal/My-Python-codes | /contacts.py | 2,213 | 3.796875 | 4 | class node:
def __init__(self):
self.children = [None] * 26
self.count = 0
self.leaf = False
class Trie:
def __init__(self):
self.count = 0
self.root = self.getNode()
def getNode(self):
return node()
def return_index(self, ch):
... |
06a333ec76a778fac2a067973446fde11436e54b | Monikabandal/My-Python-codes | /Maximum difference betwwen node and it's descendant.py | 750 | 3.65625 | 4 | import sys
class node:
def __init__(self,val):
self.data=val
self.right=None
self.left=None
def inorder(root):
if root:
inorder(root.left)
print root.data,
inorder(root.right)
def maxabsdiff(root):
if root is None:
return sys.maxin... |
c6e4f7f41e2bbf4f7babce298aa8b447796a768c | saisurajpydi/Python | /Python/Set.py | 563 | 3.875 | 4 | # set is a unordered and unindexed
# but set is changeable
# it is given in { }
hset = {"hello","world","this","is","chitti","the","robo"}
print(hset)
# add and update are used
hset.add("vasikar")
print(hset)
hset.update("mehh")
print(hset)
hset.update(["mehh"])
print(hset)
# for length
print(len(hset))
# to remove... |
6b989c5ce7dc3c8ead2f291ef3f5b2ae27e99806 | moustafa2121/PHTimeTracker | /Tracker.py | 3,345 | 3.578125 | 4 | import time
from auxFile import State, Color
#containers contain a state and the
#informations necessary for it
class Container:
def __init__(self, state):
self.state = state
self.startTime = time.time()
self.endTime = -1
def getState(self):
return self.state
#called when th... |
0bd8d806bbff76c96893692dc5a22ebb32d8f9d8 | ss820938ss/pythonProject_numpy | /01/02.py | 422 | 3.53125 | 4 | import numpy as np
# arange
print('# arange 1')
arr1 = np.arange(64)
print(arr1)
print('--------------------------------')
# reshape : 2차원 배열로 바꿔줌
print('# reshape 2')
arr2 = arr1.reshape(4, 16)
print(arr2)
print('--------------------------------')
# reshape : 3차원 배열로 바꿔줌
print('# reshape 3')
arr3 = arr1.r... |
536f39a713bfd3e40b1facdd798bba4e0087e9c4 | AbuTalha777/Natural-Language-Processing-Using-fastText | /imdb movie data/training data/imdb ready data.py | 590 | 3.53125 | 4 | import pandas as pd
import numpy as np
imdbmovies=pd.read_csv("~/Downloads/movie_metadata.csv") #read the movie data downloaded from kaggle
data=""
#print(imdbmovies.loc[1,])
for index, row in imdbmovies.iterrows():
genre=row['genres'].split('|') #using the genres as the tags
for g in genre:
data = data... |
fb792dbc4c9211b140de48ea0033347efaf25bb3 | ivyhappy/leetcode | /25 Reverse Nodes in k-Group.py | 1,060 | 3.59375 | 4 | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def reverseKGroup(self, head, k):
"""
:type head: ListNode
:type k: int
:rtype: ListNode
"""
if not h... |
6776a3ea27e805ded8016b3ce3cfbf7cba62700c | outdoorsole/tweet-generator | /10-creating-corpus/scrape-text.py | 1,182 | 3.6875 | 4 | import re
def output_file():
# open file
with open('nature.txt', 'r') as file:
# read individual line
book_string = file.read()
# Split the Introduction apart from the content of the book.
book_array = book_string.split('INTRODUCTION.\n\n')
# This is the content of the book.
book_string_wo_int... |
86520bf9d2496f10e8af8fb14600d58098aac02e | Shailendre/simplilearn-python-training | /section1 - basic python/lesson3.py | 840 | 4.09375 | 4 |
#functions
def example():
print("example")
# paramaters
# giving default parameters values
def addition(a = 0,b = 0):
return a + b
# will be called be default values in method definition
print(addition())
# passing with variable name
print(addition(b=10,a=10))
# global nad local variable
x = 10
def examp... |
675d86dc02fd03803192d75b9ccb0fb3b54d82b3 | Shailendre/simplilearn-python-training | /section1 - basic python/test-so.py | 171 | 3.859375 | 4 | # list
ll = [2,4,1,7,3,9,3,8,6,4,0]
ll.append(67)
print("list.append(67)", ll)
ll.insert(5, 23)
print("list.insert(5,23)", ll)
ll.reverse()
print("why not reverse?", ll)
|
fe4f4056fb3dfc42ea06f2637b0cd93469fe96bc | marco-zietzling/advent-of-code-2018 | /day03/day03.py | 1,279 | 3.859375 | 4 | print("advent of code 2018 - day 3")
with open("input.txt") as file:
lines = [line.strip() for line in file]
def parse_line(line):
line_id = int(line.split("#")[1].split("@")[0])
pos_x = int(line.split("@")[1].split(",")[0])
pos_y = int(line.split(",")[1].split(":")[0])
len_x = int(line.split(":"... |
945a791125c9db6183fcc24706c52d6497580c64 | tshardey/DQ_Coursework | /MachineLearning/machine-learning-intermediate/Introduction to evaluating binary classifiers-22.py | 2,505 | 3.828125 | 4 | ## 1. Introduction to the Data ##
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.linear_model import LogisticRegression
admissions = pd.read_csv("admissions.csv")
model = LogisticRegression()
model.fit(admissions[["gpa"]], admissions["admit"])
labels = model.predict(admissions[["gpa"]])
admissions... |
e2026afc08b18f165f51a11b6219b947cd885039 | vertden/Calculator- | /final_task/check.py | 4,800 | 3.984375 | 4 | """This module checks the correctness of the entered expression."""
import re
import core
from constants import *
from core import comma_count
def check_brackets(expr):
"""Get expression. Check brackets balance"""
if expr.count('(') != expr.count(')'):
print("ERROR: brackets are not balanced")
... |
58b434bab3224563f9bb4f1d976fd056f68168a1 | helagro/coding-challenges | /nails.py | 1,129 | 3.78125 | 4 | nailsNeeded = []
nailsOwned = []
def applyNails():
global nailsNeeded
global nailsOwned
nailsNeeded.sort(reverse=True)
nailsOwned.sort(reverse=False)
print(nailsNeeded, nailsOwned)
nailsToBuy = []
for nailNeeded in nailsNeeded:
foundNail = False
for i, nailOwned in enume... |
9dd07c738d169d72b46741e5d7b378ce2aa101f9 | PaoloPy/ADM-HW1 | /ARIS_SUBMISSION_1798233.py | 30,213 | 4.40625 | 4 | #CODES FOR THE DIFFERENT EXERCISES (HOMEWORK ORDER)
#I USED PYPY FOR UNKOWN REASONS (DIDN'T KNOW I COULD SWITCH) UNTIL HALFWAY THROUGH
#1 -- Say "Hello, World!" With Python
if __name__ == '__main__':
print("Hello, World!")
#2 -- Python If-Else
import math
import os
import random
import re
import sys... |
47dce32ef0748efe68352e2071a13d23cb8f6f90 | atg-abhijay/LeetCode_problems | /reverse_string_344.py | 506 | 4.09375 | 4 | """
URL of problem:
https://leetcode.com/problems/reverse-string/description/
"""
def main(string):
"""
main method for running the program.
Argument:
string - any sort of string
Prints:
Reverse of given string
"""
# convert the string to
# a list, reverse the list
# an... |
00284616a6d1c0594b4c32455595f9bb834b8f83 | atg-abhijay/LeetCode_problems | /robot_return_to_origin_657.py | 613 | 3.765625 | 4 | """
URL of problem:
https://leetcode.com/problems/robot-return-to-origin/description/
"""
def main(moves):
moves_list = list(moves)
x = 0
y = 0
for move in moves_list:
if move == 'U':
y += 1
elif move == 'D':
y -= 1
elif move == 'R':
x += 1
... |
14f49d671b7f047fa4fa367900bec0d903ed5073 | atg-abhijay/LeetCode_problems | /number_of_islands_200.py | 2,627 | 3.84375 | 4 | """
URL of problem:
https://leetcode.com/problems/number-of-islands/
"""
from typing import List
class GridPiece(object):
def __init__(self, is_land, row, column):
self.is_land = is_land
self.row = row
self.column = column
self.island_number = 0
class Solution(object):
def n... |
2298776add71e7cfc3de44c541c27229608f3bd3 | atg-abhijay/LeetCode_problems | /projection_area_3d_shapes_883.py | 2,818 | 3.96875 | 4 | """
URL of problem:
https://leetcode.com/problems/projection-area-of-3d-shapes/description/
"""
def main(grid):
"""
main method for running the program.
Argument:
grid - a 2D grid with grid[i][j] = height of tower
Prints:
Total projection area
"""
dimension = len(grid)
# d... |
9cc97abc634ef54709d7f6c2ebe52cb6df1d4537 | atg-abhijay/LeetCode_problems | /array_partition_i_561.py | 812 | 3.796875 | 4 | """
URL of problem:
https://leetcode.com/problems/array-partition-i/description/
"""
def main(nums):
# the way to achieve the
# maximum sum is to -
# sort the numbers and take
# the sum of alternate numbers
# starting from the very first number
# our ideal sum would have been the
# sum of... |
248eab15c2d71ebd8d10a7fe2aa1203aa8929905 | atg-abhijay/LeetCode_problems | /sorted_array_to_BST_108a.py | 1,134 | 3.890625 | 4 | """
URL of problem:
https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/
"""
# ## RECURSIVE SOLUTION ## #
from math import floor
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class ... |
fa03d0f4422ed2ccc73c085b0dff50d5c5faa590 | smspillaz/fair-technical-interview-questions | /python/closure.py | 965 | 3.828125 | 4 | #!/usr/bin/env python
#
# This code defines an object which is really only for a single use.
# Can you rewrite it so that it only uses a functions?
from threading import Thread
from queue import Queue
class Processor(object):
"""Prepare to process something on a callback of some sort."""
def __init__(self, d... |
eb45d72d4267dc513c354492e49c3bc799a75cda | vektorelpython20/pythontemelleri | /Nursen/arayuz.py | 776 | 3.75 | 4 | from tkinter import *
pencere = Tk()
pencere.geometry("400x400+200+200")
#-----------------------------------------------
etiket = Label(pencere,text="Python'da ilk arayüz elemanım")
etiket.grid(column=0,row=0)
def tiklandi():
etiket["text"] = "TIKLANDI"
dugme = Button(pencere,text="TIKLA",command=tiklandi,wid... |
dcd69af7c0b4ebf33250d2b943a50c4f463da8a0 | vektorelpython20/pythontemelleri | /Ugur/GUI.py | 688 | 3.75 | 4 | from tkinter import *
pencere = Tk()
pencere.geometry("600x400+200+200")
#-----------------------------
etiket = Label(pencere,text="Python'da ilk arayüz elemanım")
etiket.grid(column=0,row=0)
def tiklandi():
etiket["text"] = "TIKLANDI"
dugme = Button(pencere,text="TIKLANDI",command = tiklandi,width=50)
dugme.grid... |
e235ee612ebf8257181624e6a6baddfd1548ec5a | vektorelpython20/pythontemelleri | /OOP/Polymorphism.py | 1,001 | 4.125 | 4 | # Çokbiçimlilik
# overload
# override
# built in polymorphic functions
metin = "Python"
liste = [1,2,3,4]
print(len(metin))
print(len(liste))
# user defined polymorphic functions
def Fonk(a,b,c=4):
return a+b+c
print(Fonk(1,2))
print(Fonk(1,2,3))
# Polymorphism with class methods
class A:
def foo():
pri... |
6f26df78e794fd37d135f11ebd608f9ddb22ab02 | ZeyadAl/small-python-programs | /square_root/square_root.py | 342 | 3.734375 | 4 | #first you need to start with a guess, g
import random
g= random.randint(1,1000)
#choose a number to find its root, say x
while (1>0):
x= int(input('Choose a number '))
while (g!=(g+x/g)/2):
g=(g+x/g)/2
print(g)
print(x**(1/2))
#accuracy test num... |
dde8a62eef0a38fc5b6485a404380559f34efc42 | ZeyadAl/small-python-programs | /avg_dist.py | 353 | 3.9375 | 4 | """
We want to know what's the average of the distances if we took two random points on a segment of length 1.
"""
import random
from statistics import mean
m=[]
h = int(input('insert: '))
for i in range(h):
x1=random.random()
x2=random.random()
y1=random.random()
y2=random.random()
m.append(((x1-x2)**2 + (y1... |
afe84cc349b21d50aff626fe2874b8c93e6b24e0 | rjorth/Algorithms-and-Data-Structures | /pascalsTriangle.py | 445 | 3.953125 | 4 | def generate(num_rows):
#result is an array of rows
result = []
#first/last num of each row is always 1
for num in range(num_rows):
row = [None for _ in range(num + 1)] #fills every space with 'None'
row[0], row[-1] = 1, 1
for j in range(1, len(row)-1):
#vals are equal to sum of upper left and uppe... |
b0c0c60aeff6d4732167ad1a91f0285ef8aefafc | rjorth/Algorithms-and-Data-Structures | /powerOfThree.py | 218 | 3.953125 | 4 | def powerOfThree(n):
#if it's a power, then it should be divisble by zero until n is 1
if n < 1:
return False #or else time limit exceeded
while (n % 3 == 0):
n /= 3
return n == 1
print(powerOfThree(45)) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.