blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
fedbb5b10af9f51fd983fd6ab762f39632e2a41c | jorgebaier/iic1103-s4-2016 | /clase1108/selection_sort.py | 557 | 3.625 | 4 | def selection_sort(L):
i = 0
while i < len(L) - 1:
minimo = L[i]
indice_minimo = i
j = i + 1
while j < len(L): # busca el elemento más pequeño en L[i:]
if L[j] < minimo:
minimo = L[j]
indice_minimo = j
j += 1
L[indic... |
abf5a593009d1343c08f3d763e0b0555b882bf72 | JessicaHamilton/PHYS-3210 | /Week 01/Exercise_01.py | 756 | 4.0625 | 4 | # -*- coding: utf-8 -*-
"""
Exercise: Chapter 01, Kinder & Nelson
Download and run this script, or enter each line into an IPython console.
There are a few errors in the script. Try to find and correct them. Make
note of each error and explain (1) why it's an error, and (2) how to fix
it.
... |
3c56a7098ea5da4ab093851600b2e0cae274e6fc | liruileay/data_structure_in_python | /data_structure_python/question/chapter3_binary_tree/question22.py | 2,045 | 3.5625 | 4 | """
先序,中序,后序数组两两结合重构二叉树
题目:
已知一颗二叉树的所有节点值都是不相同,给定这颗树二叉树正确的先序,中序,后序数组。
请分别用三个函数实现任意连个数组结合重构原来的二叉树,并返回重构二叉树的头节点
"""
from development.chapter10.ChainHashMap import ChainHashMap
from question.chapter1_stack_queue_question.question9 import Node
def pre_in(p, pi, pj, n, ni, nj, hash_map):
"""先序和中序重构过程"""
if pi > ... |
bde2ea63ac57d76a786cb4a1e46719c9d9ee7978 | Philtesting/Exercice-Python | /3eme cours/Exemple/Exemple10-1-3.py | 348 | 3.75 | 4 | nom = 'Jacqueline'
index = 0
while index < len(nom):
print (nom[index] + ' *')
index = index +1
for caract in nom:
print (caract + ' *')
liste = ['chien','chat','crocodile']
for animal in liste:
print ('longueur de la chaîne', animal, '=', len(animal))
divers = ['cheval', 3, 17.25, [5, 'Jean']]
for e... |
e4fe43530af9fb8de6ab5f1205086bfe07f03736 | aldotele/the_python_workbook | /decision_making/ex52_bis.py | 989 | 4.125 | 4 | # exercise 52: Letter Grade to Grade Points
def lett_to_point(grade):
try:
grade = grade.upper()
except:
raise ValueError('please enter a letter grade')
if grade == "F":
points = 0
elif grade == "D":
points = 1
elif grade == "D+":
points = 1.3
elif grade... |
f86a3eb6ceaec2db4b736e3de47602d86a415fed | rduvvi/MyPythonWorks | /DataStructureExcercise.py | 3,076 | 3.90625 | 4 | #List in DataType
# Tuple - sequence,Immutable but members of objects may be mutable
#Constructor
x=() #no-item tuple
x=(1,2,3)
x=1,2,3 #Parenthesis are optional
#x=2, #single-tem tuple
# x=tuple(list) tuple from list
print(x)
#immutable but member object may be mutable
x=([1,3],5)
del(x[0][1])
print(x)
#SETS
x={... |
13d96db98246767c6c32769606991a5e0a65d769 | JamesLaverack/one-max-GA | /one_max_GA.py | 4,217 | 3.9375 | 4 | import argparse
import random
def weighted_choice(elements, weights):
'''Picks a value from a list of elements, weighted by a list of weights.
Such that the element 'elements[i]' has weighting 'weights[i]'. It is
assumed that the weightings are integers and are not normalised.'''
value = random.randin... |
416821a65e4bae6322b132225e817f5c0f1b5794 | MrHamdulay/csc3-capstone | /examples/data/Assignment_9/sttbar001/question1.py | 1,123 | 3.828125 | 4 | """analyse student marks read in from a file and determine which students need to see a student advisor
barak setton
11/05/2014"""
import math
file = input("Enter the marks filename: \n")
# reading from file
f = open(file,"r")
count = 0
stand =0
totmark =0
listmark =[]
listname =[]
line = f.readline()
... |
bc80659bc73f24b2c42c6172a079de27813961be | qiuchen100/advanced-python | /chapter12/yield_from_example.py | 938 | 3.75 | 4 | # -*- coding: utf-8 -*-
final_result = {}
def sales_sum(prod_name):
print(f'sales_sum: {prod_name}')
total = 0
nums = []
while True:
x = yield
if not x:
break
print(f'{prod_name}的销量是: {x}')
total += x
nums.append(x)
return total, nums
def midd... |
7d7badbc9132f8737f66d1534ba9e5bb459ca4fb | JamesNowak/3.4-practice | /3.4.py | 236 | 4.25 | 4 | age = int(input("What is your age?: "))
if age <= 1:
print("You are an infant.")
elif 2 < age < 13:
print("You are a child.")
elif 13 <= age < 20:
print("You are a teenager.")
else:
print("You are an adult.")
|
f4fd5554b85ee3601c97343a6cd8be868dfe8144 | bpayami/FinalProject17 | /DeprecatedFiles/text_based_game_2.6_temporarily_removed_code.py | 9,375 | 3.53125 | 4 |
# These direction commands have a long (i.e. north) and show (i.e. n) form.
# Since the code is basically the same, I put it in the moveDirection()
# function.
def do_forward(self, arg):
"""Goes to the room forward if possible."""
moveDirection('forward')
def do_south(self, arg):
... |
8d80dd28c42e7b38ffbb4487497338279d8e76b4 | eilenee/python-practice | /chapter 8/Practice2.py | 165 | 3.765625 | 4 | number = int(raw_input('Which table would you like? '))
print 'Here is your table:'
i = 1
while i <= 10:
print number, 'times', i, '=', number * i
i = i + 1
|
0018b27ee5f200edf605e278ce68c462c5172dd6 | 75evo/python | /list_comp2.py | 150 | 3.6875 | 4 | l1=[1,2,3,4,5]
l2=list([x**2 for x in l1])
print(l2)
l3=[1,2,3,4,5]
l4=[3,4,5,6,7]
set1=set(l3)
set2=set(l4)
set3=set1.intersection(set2)
print(set3) |
21d00cebd057183fc91f2f41f6477d852e848260 | ReenyDavidson/assignment | /solid_2_py/person.py | 724 | 3.53125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Nov 29 14:09:45 2019
@author: Ewa
"""
class Person:
def __init__(self, name, gender, fatherName, motherName):
self.name = name
self.gender = gender
self.fatherName = fatherName
self.motherName = motherName
self.role ... |
2a945cafb81b1187873aae8a2f86b7946b14344a | lixiang2017/leetcode | /leetcode-cn/0429.0_N-ary_Tree_Level_Order_Traversal.py | 2,489 | 3.53125 | 4 | '''
approach: BFS
Time: O(N)
Space: O(N)
执行用时:44 ms, 在所有 Python 提交中击败了48.84%的用户
内存消耗:15.9 MB, 在所有 Python 提交中击败了64.53%的用户
'''
"""
# Definition for a Node.
class Node(object):
def __init__(self, val=None, children=None):
self.val = val
self.children = children
"""
class Solution(object):
def l... |
a64ebc555d5957df6ec5d9d6e939b8050aef2a6b | kanishk19/Competitive-Coding | /SPOJ/8-Fennyman.py | 127 | 3.59375 | 4 | user_input = int(input())
while user_input!=0:
n = user_input
ans = (n*(n+1)*(2*n+1))/6
print ans
user_input = int(input()) |
58f026e820330b207bc8d0e4055a8aa180ff2392 | johannbzh/Cracking-The-Coding-Interview-Python-Solutions | /recursion_and_dp/booleanEvaluation.py | 1,380 | 3.78125 | 4 | def countEval(s, val):
def strToBoolean(s):
return s == "1"
def countEvalHelper(s, val, memo):
if not s :
return 0
if len(s) == 1 :
return strToBoolean(s) == val
#place to put the paren
if str(val) + s in memo :
return memo[str(val) + ... |
711a1db2aebbf52019140e71b72a0d2572676002 | sornaami/luminarproject | /Flow Controls/looping stmnts/program calculate cube.py | 175 | 4.03125 | 4 | #123=1*1*1+2*2*2+3*3*3=36
number=int(input("enter number"))
res=0
while(number!=0):#5
digit=number%10 #5%10
res=(res)+(digit**3)
number=number//10
print(res)
|
7fac7fe92f19c1d085ea5be414f0b1201cf26496 | Sonnenlicht/ProjectEuler | /51-100/Q66.py | 1,550 | 3.546875 | 4 | #Diophantine equation
#Problem 66
#Consider quadratic Diophantine equations of the form:
#x2 – Dy2 = 1
#For example, when D=13, the minimal solution in x is 6492 – 13×1802 = 1.
#It can be assumed that there are no solutions in positive integers when D is square.
#By finding minimal solutions in x for D = {2, 3, 5, ... |
a77c1e7f50013cc1a705fb5d3ea2f64cd05b8afb | anaerobeth/python-koans | /koans/triangle.py | 1,059 | 4.1875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Triangle Project Code.
# triangle(a, b, c) analyzes the lengths of the sides of a triangle
# (represented by a, b and c) and returns the type of triangle.
#
# It returns:
# 'equilateral' if all sides are equal
# 'isosceles' if exactly 2 sides are equal
# 'sca... |
77dbf5067039edcaa7aa44a1655d807c532fc6dd | frankpiva/leetcode | /problemset/668.py | 1,123 | 3.765625 | 4 | """
668. Kth Smallest Number in Multiplication Table
Hard
1418
41
Add to List
Share
Nearly everyone has used the Multiplication Table. The multiplication table of size m x n is an integer matrix mat where mat[i][j] == i * j (1-indexed).
Given three integers m, n, and k, return the kth smallest element in the m x n... |
b5f2bba1103904def7d570251d1084b332cf0d62 | yashika0810/test | /assign.py | 491 | 3.671875 | 4 | import random as r
FName = input("Enter your first Name")
LName = input("Enter your last Name")
x = r.randint(1,20)
print("The OTP is",x)
count = 0
while (count < 4):
UNum = int(input("Enter your OTP"))
if UNum > 20 or UNum < 1:
print("Wrong Input, Try Again!!")
break
else:
if UNum == x:
print("... |
ca1bcc20087af90a58c4cea9653f167e3a90855f | FadelBerakdar/OSTpythonCourse | /Python3/01_Testing/Project/thirdTry/adder.py | 576 | 4.15625 | 4 | #!/usr/bin/env python
# Function returns the sum of two objects if they r integers
# adder.py
# By: Fadel Berakdar
# Date: 6 Oct 2015
def supper_adder(a, b):
"""
take two objects and add them together only if they are both of the
integer type, Raise type error otherwise.
"""... |
7cd6f8a6d0b7c57af13e398cf1c111a7309141c7 | ysbecca/imagepy-toolkit | /ysb-display-images.py | 1,212 | 4.09375 | 4 | '''
@author ysbecca Rebecca Stone
Two simple functions which display images using matplotlib.pyplot (http://matplotlib.org/api/pyplot_api.html)
Any image in a format readable by matplotlib.pyplot's imshow() function is good.
'''
import matplotlib.pyplot as plt
def show_images(images, per_row, per_column):
'''... |
4e0e5d6bdbe92c957594f844fe1240c99f90303c | Ayush6459/Simple_Calculator_package | /src/Calculator.py | 192 | 3.5625 | 4 | def add_num(num1, num2):
return num1+num2
def sub_num(num1,num2):
return num1-num2
def multi_num(num1, num2):
return num1*num2
def div_num(num1,num2):
return num1/num2
|
d67abfc7ce37bea38e51a6cd273fcbb40678d27d | cernyjan/Game-of-life | /cell.py | 1,067 | 3.546875 | 4 | class Cell(object):
def __init__(self, alive):
self.set_life(alive)
self.neighbors = 0
def validate_type(self, var, varType):
if isinstance(var, varType):
return True
else:
re... |
75acd58b66a8438eb6c4bbcbe0a62cdb6e216084 | themoat/Socket-Proramming | /sockets.py | 1,412 | 3.59375 | 4 | #putting the sockets.py file(server side socket program) here
import socket
import threading
"""Since this file is for server socket, so we are focusing on that, and we will be dealing with s
while on the client socket side we deal with c"""
PORT=5050
SERVER = "192.168.#"
ADDR = (SERVER, PORT)
HEADER=64
FORMAT='utf-8'... |
77ba72bbba6cfd9a4fe7abf8e0a0b70f9c22357d | ozthegnp/ozthegnp | /1 - python/censor.py | 239 | 3.765625 | 4 | def censor(text, word):
split_text = text.split()
for i in range(len(split_text)):
if split_text[i] == word:
split_text[i] = '*' * len(word)
return " ".join(split_text)
print censor('what the marshmello', 'marshmello')
|
abaebe52c615109ff2594ab9159c2d935d1996dd | andreysenchenko30/tms_homeworks | /HW7/task_7_2.py | 613 | 4.21875 | 4 | def count_lower_and_upper(some_string: str):
if not some_string.isalpha():
return 'Wrong input. Please enter only letters'
else:
number_of_lower = 0
number_of_upper = 0
new_dict = {}
for symbol in some_string:
if symbol.islower():
number_of_low... |
bbdfa9798dba15ef687a278ac026f8f75d2cc644 | jakedent/Matrix-Encryption | /plaintext_algorithm.py | 3,249 | 3.625 | 4 | #!/usr/bin/env python3
# This test implements encryption and key permutation rounds and user interaction.
# Further work in test004.py will implement file encryption.
import numpy as np
# User input function, takes input and converts to alpha-numeric values.
def user_input_handler():
global message, message_outpu... |
7ce973d22e634edc17450963478c47c6f38b38bb | JosephLevinthal/Research-projects | /5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/226/users/4138/codes/1675_1950.py | 326 | 3.90625 | 4 | T = float(input("insira a temperatura:"))
v = float(input("insira a velocidade do vento:"))
A = 13.12 + (0.6215 * T) -(11.37 * (v ** 0.16)) +(0.3965 * T * (v ** 0.16))
if(v > 4.8):
if(T >= -50 and T <= 10):
print(round(A,4))
elif(T < -50 or T > 10):
print("Temperatura invalida")
else:
print("Velocidade invali... |
6a180cae1c60c50bfd64901e8c6ff271aa8ec816 | beatorizu/dojo-campinas | /2011_01_18_NomesAutoresObrasBibliograficas/nomes_autores.py | 579 | 3.953125 | 4 |
def converte (nome):
aux_nome = nome.split(" ")
if len(aux_nome) == 1:
return nome.upper()
if len(aux_nome) == 2:
aux_nome = aux_nome[-1].upper() + ", " + aux_nome[0]
else:
parentesco = ['FILHO', 'JUNIOR', 'SOBRINHO', 'NETO', 'FILHA', 'NETA', 'SOBRINHA']
if aux_nome[-1]... |
ffe006ba01cfd2ba08cbbd68ba89bba4bc032db6 | yujinK/TIL | /Algorithm/BOJ/Python/BOJ_2720.py | 224 | 3.5 | 4 | T = int(input())
for i in range(T):
C = int(input())
quarter = C // 25
C = C % 25
dime = C // 10
C = C % 10
nickel = C // 5
C = C % 5
penny = C // 1
print(quarter, dime, nickel, penny) |
81d721b7a0d2e8728825bf4b491d4817d1e1a862 | Halal375657/Graph-Theory | /Topological_Sorting.py | 1,483 | 4.03125 | 4 |
#
# Topological Sorting Algorithm.
#
# O(V + E)
#
from collections import defaultdict
graph = {}
Graph = defaultdict(list)
# Add edge of directed graph.
def addEdges(u, v):
Graph[u].append(v)
# Adding in-degree.
def addDegree(u, v):
try:
graph[v] += 1
except KeyError:
graph[v] = 1
... |
ec08162ac9f287d7b1abda789a400c7a83589cbe | renatomak/trybe-exercises | /CC/bloco_34/dia_4/ex02.py | 699 | 4.03125 | 4 | # string = 'HOME-SWEET-HOME'
string = 'MY-MISERABLE-JOB'
string = 'The quick brown fox jumps over the lazy dog'
def translate_expression_to_numbers(string):
result = ''
for s in string:
if s in 'ABC':
result += '2'
elif s in 'DEF':
result += '3'
elif s in 'GHI':
result += '4'
elif... |
6c7b8074da916ebfb8cec71e27dbf3b66278cc81 | krismaz/dailyprogrammer | /dailyprogrammer/3/easy.py | 630 | 3.828125 | 4 | #Simple Caesar cypher.
from string import *
from collections import deque
def key(n): #Slightly round-about way of generating the lookup-table, in order to preserve case
lower = deque(ascii_lowercase)
upper = deque(ascii_uppercase)
lower.rotate(n)
upper.rotate(n)
return list(lower)+list(upper)
def encrypt(s, n)... |
7271914e77ab6cac97840f9980d2dbfbe49f7c26 | zurgis/academicplan | /plan.py | 2,648 | 3.515625 | 4 | import xml.etree.ElementTree as xml
from os import remove
from structure import Stack
class Plan:
"""Класс отвечающий за создание, сохранение, загрузку и удаления
плана обучения
"""
def __init__(self, name):
self.plan = Stack(name)
def getName(self):
return self.plan.name
de... |
6e747fd0a971afdf9101c4feab5767b273cd555b | southwall93/pycharm_project1 | /ch07data/ch07_05dictionary.py | 1,254 | 3.671875 | 4 | #dictionary -> {key:value[, key:value]} ->js : json 형식
#마지막 키 값이 적용
dic1={1:'a',2:'b',3:'c',3:'e'}
print(dic1,type(dic1))
#학생 딕셔너리 생성
student={"학번":1000, "이름":"홍길동", "학과":"파이썬학과"}
print(student, type(student))
#학생의 이름 데이터 가져오기(순수한 리스트는 아님)
print(student["이름"])
print(student.get("이름"))
#모든 키를 출력해보자
keylist=student... |
65ac6834d07619126d4afcd38e345f2ec0794d97 | UkraintsevAleksey/pythonProject | /4.py | 524 | 4.1875 | 4 | # Пользователь вводит целое положительное число. Найдите самую большую цифру в числе.
# Для решения используйте цикл while и арифметические операции.
a = input('Введите число ')
a = int(a)
max_figure: int = 0
while a > 0:
last_figure = a % 10
if last_figure > max_figure:
max_figure = last_figure
a =... |
d22e5f559c86f10043401365b3e36a950e148620 | KosinskiJ/numbers2text | /numbers_converter/services.py | 825 | 3.671875 | 4 | # -*- coding: utf-8 -*-
from numbers_converter import utils
from numbers_converter.exceptions import TooBigNumberException
class ConverterService:
@staticmethod
def number_to_text(number):
word = ''
minus = 0
if type(number) is not int:
return False
if number == 0... |
3fa52970083b14f2df0e946a53565af7a629c4e8 | j-tyler/holbertonschool-higher_level_programming | /0x04-python-more_data_structures/102-complex_delete.py | 143 | 3.515625 | 4 | #!/usr/bin/python3
def complex_delete(my_dict, value):
my_dict = dict({k: v for k, v in my_dict.items() if v != value})
return my_dict
|
0f90a2e61184187379533edf9e769a9fd904d629 | jeffarrubla/Python-Bootcamp | /03/12.py | 795 | 3.703125 | 4 | # I/O
myfile = open('myfile.txt')
#myfile = open('opp')
print(myfile.read())
print(myfile.read())
print(myfile.seek(0))
contents = myfile.read()
print(contents)
print(myfile.seek(0))
print(myfile.readlines())
myfile.close()
with open('myfile.txt') as my_new_file:
contents = my_new_file.read()
print(... |
88c9b6b6c92859c7c188478ead68ec953a48edab | hikarocarvalho/Python_Wiki | /Exercises/02-Decision-Structure/ex11.py | 1,716 | 4.5 | 4 | # As Organizações Tabajara resolveram dar um aumento de salário aos seus colaboradores e lhe
# contraram para desenvolver o programa que calculará os reajustes.
# Faça um programa que recebe o salário de um colaborador e o reajuste
# segundo o seguinte critérios, baseado no salário atual:
# salários até R$ 280,00 (inc... |
dbc6425c23c28f99ad352bf9859133ee7eff1d31 | BoyYongXin/algorithm | /Problemset/add-two-numbers-ii/add-two-numbers-ii.py | 928 | 3.546875 | 4 |
# @Title: 两数相加 II (Add Two Numbers II)
# @Author: 18015528893
# @Date: 2021-02-04 22:41:36
# @Runtime: 80 ms
# @Memory: 14.6 MB
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def addTwoNumbers(self, l1: ListNod... |
2df9b5e610a69061733a822f73e7776474f5452d | snehalvartak/AI-as-Search | /a0.py | 5,941 | 4.40625 | 4 | #!/usr/bin/env python
# nrooks.py : Solve the N-Rooks problem!
# D. Crandall, 2016
# Updated by Zehua Zhang, 2017
# Modified by Snehal Chemburkar Vartak 10 Sep 2017
# The N-rooks problem is: Given an empty NxN chessboard, place N rooks on the board so that no rooks
# can take any other, i.e. such that no two rooks sh... |
657f81be1b269fb80b41b7f857cf7af5a507937c | stevensc9277/Assessment | /fix_draw.py | 1,465 | 3.875 | 4 | import math
import turtle
import time
# draws a triangle using given parameters
def triangle(displacement, angle):
# initialise turtles
# Set up the window and its attributes
wn = turtle.Screen()
# This just makes the screen full screen without the user having to touch the maximize button repeatedly
wn.setu... |
4a0723d49dbb739a8f740c0a5b9c6939f7537ae7 | limaries30/leet_code | /String/String Without AAA or BBB.py | 639 | 3.578125 | 4 | """
https://leetcode.com/problems/string-without-aaa-or-bbb/
"""
class Solution:
def strWithout3a3b(self, a: int, b: int) -> str:
return self.main("a", "b", a, b) if a > b else self.main("b", "a", b, a)
def main(self, big_word, small_word, big, small):
if big == 2 * small:
retur... |
d0fae263143c23a4d8d75836b84e9b95a8c08d6d | diegolinkk/exercicios-python-brasil | /estrutura-de-repeticao/exercicio28.py | 573 | 3.875 | 4 | #Faça um programa que calcule o valor total investido por um colecionador em sua coleção de CDs e o valor médio gasto em cada um deles.
# O usuário deverá informar a quantidade de CDs e o valor para em cada um.
quantidade_de_cds = int(input("Digite a quantidade de cds: "))
valor_total = 0
contador_cd = 0
for cd in r... |
af6bd484dbed5622ab6f4e04d62aee1bd566c4bb | Aasthaengg/IBMdataset | /Python_codes/p02772/s435146284.py | 300 | 3.546875 | 4 |
def main():
n = int(input())
a = list(map(int, input().split(" ")))
x = []
for i in a:
if i % 2 == 0:
if not(i % 3 == 0 or i % 5 == 0):
print("DENIED")
return
print("APPROVED")
return
if __name__ == "__main__":
main() |
c7c6eb9a27b44046736e3546ea01af4b581b382a | iiseeland/quant_ghl | /py27_standard/chapter1/builtin/builtin-compile-example-3.py | 1,139 | 3.859375 | 4 | # -*- coding:utf-8 -*-
# Example 1-22. 简单的代码生成工具
# write 方法用于添加代码, indent 和 dedent 方法用于控制缩进结构. 其他部分交给类来处理
import sys, string
class CodeGeneratorBackend:
"Simple code generator for Python"
def begin(self, tab="\t"):
self.code = []
self.tab = tab
self.level = 0
def end(se... |
1bfa6911246189872fe13405313ae676b3f4b09c | LuisClavero/buclesfor | /for03.py | 376 | 3.890625 | 4 | #coding: utf-8
cont=0
cant=input("Cuantos valores va a introducir?")
while (cant<=0):
cant=input("Error, introduzca otra cantidad de valores superior a 0:")
cant1=float(input("Introduzca un numero:"))
for i in range(0,cant+1):
cant2=float(input("Introduzca un numero mayor que "+str(cant1)+":"))
if (cant1>cant2):
p... |
c866cf9acb41be617fc0b28b668bb276b50ecc84 | zain08816/Coding-Problems | /Set #1 Problems/Dailys/#001 largestNumber.py | 101 | 3.640625 | 4 | def largestNumber(n):
num = ''
for i in range(n):
num = num + '9'
return int(num) |
0924dff75dbe7302eb04f9f2704e66bcd382313d | shree233/algorithm | /BinarySearch.py | 839 | 3.84375 | 4 | def binarySearch(list, item):
'''二分查找.
运用二分法查找给定有序数组中某元素的位置(如果它存在的话)
Args:
list: 给定有序数组.
item: 给定元素.
Returns:
如果该元素存在则返回索引,不存在则返回-1.
Forexample:
print(binarySearch(test_list,6))
#3
print(binarySearch(test_list,10))
#-1
Raises:
... |
1c763a8fe63dd1a7c0e1a6d337c402779204dc7e | shisaq/learnpythonthehardway | /exp5.py | 720 | 3.578125 | 4 | # -*- coding: utf-8 -*-
my_name = 'Haiquan Li'
my_age = 27
my_height = 182
my_weight = 71
my_eyes = 'Dark brown'
my_teeth = 'White'
my_hair = 'Black'
my_weight_pounds = my_weight * 2.20462
my_height_inches = my_height * 0.393701
print "Let's talk about %s." % my_name
print "He's %dcm tall." % my_height
print "换算成inch... |
259d621eb1f6ec8335a5ddfc1af7e425dcdf82d9 | shailenn/CG-Project | /Final Version/Binary Representation.py | 2,509 | 4 | 4 | from tkinter import *
from BinaryTree import *
from time import sleep
#The White board on which binary tree is generated
CanvasHeight = 600
CanvasWidth = 950
word = ('arial',18,'bold')
X = int(CanvasHeight//1.5 + 60)
Y = 50
offset = 30
def clear_DrawBoard():
inputEntry.delete(0,END)
DrawBoard.delete('all'... |
8ab1794c9b28495d35cb9af08a8a50d3fc5b9d61 | zaoyuaner/Learning-materials | /python1901/1_python基础/day08/3.回调函数.py | 685 | 3.5 | 4 | #!/usr/bin/env python
#-*- coding: utf-8 -*-
# author:zhangjiao
print()
'''
回调函数:把函数当作参数,传递到另外一个函数中,当这个函数【在传递的函数中】
被调用的时候,我们称这个函数为回调函数。
'''
import functools
int2 = functools.partial(int,base=2)
# int2("111")
#
# def outer(func):
# def inner():
# pass
# return func()
# return inner
def wake_on... |
53cfc156100e39ebb527d6e4f21dd49d4c97b494 | nizzolivittoria/compiti | /es 14.py | 253 | 3.9375 | 4 | numeroa = int(input("scrivi numero a"))
numerob = int(input("scrivi numero b"))
prodotto = numeroa * numerob
if prodotto > 10 :
print(numeroa - numerob)
elif prodotto < 10:
print( numeroa + numerob)
else :
print( numeroa + numerob)
|
3811095bcc1d2ea7da9b0b8e4a2384973054ab33 | jetli123/python_files | /Python基础教程/linux-diff.py | 1,287 | 3.9375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""This is diffrent two file"""
import difflib
import sys
def main1():
# create file test1
test1 = """test1:
I love you
OK, I know, thank you very much!
Please go to my home tonight folow me.
"""
test1_lines = test1.splitlines()
# create... |
dde0d934fbde2389907f473bc6e14741f43342a7 | marhong2/Circe | /Circe/FGcalc.py | 1,192 | 3.671875 | 4 | from graphics import*
def finalGrade():
win = GraphWin()
entry = Entry(Point(200,20), 10)
entry2 = Entry(Point(200, 40), 10)
entry3 = Entry(Point(200, 60), 10)
txt = Text(Point(100, 20), "Current Grade")
txt2 = Text(Point(100, 40), "Aceptible grade")
txt3 = Text(Point(100, 60), "final weight... |
e88d88456dbc454e2262fe85cd57dbfd4104dbea | poojitha2002/The-Complete-FAANG-Preparation | /3]. Competitive Programming/03]. HackerRank/1]. Practice/10]. 30 Days of Code/Python/Day_25.py | 399 | 3.734375 | 4 | # 26th Solution
#----------------------------------------------------------
from itertools import count, islice
n = int(input())
for i in range(n):
x, prime = int(input()), True
sq = int(x**0.5)-1
if x<2:
prime = False
else:
for num in islice(count(2), sq):
if not x%num:
... |
ce338384b31bfbb481056992460811e2aab7b67a | d-millard/rec-rep | /FUNDEMENTALS/Module 4/mod_four_strt.py | 7,791 | 4.40625 | 4 | # INTRODUCTION
# references to objects
# EX:
"""
x = 1000
python creates an int object of 1000 and sets it to the reference of x
"""
# int objects are immutable and cant be changed
# EX:
"""
x = 500
the int object of 1000 isn't changed but another int object of 500 is created and x
is now assigned to refer... |
69747d4dffe0f7effbb290fea81da46bbbd4e23f | juancarpio27/MachineLearning | /Helper.py | 692 | 3.625 | 4 | ##########################################
#
# Helper.py
# Juan Andres Carpio
# Naomi Serfaty
#
##########################################
#Function to read data from a text file
#In:
#file: name of the text file with the data
#Out:
#data: matrix where every row correspond to a line of data from file
def readfile(file... |
587ca978348e62c545db2b549c0f7b97f4df585d | tuhiniris/Python-ShortCodes-Applications | /basic program/print the multiplication table of a given number in a friendly way.py | 752 | 4.34375 | 4 | #Python Program to print the table of a given number.
while 1:
n=int(input("Enter the number to print the tables for: "))
for i in range(1,21):
print(n,"X",i,"= ",n*i)
option = input("\nDo you wish to continue if so press y else n: ")
if option == "y" :
print("---------------------------------------... |
45f3a1e2d53389698239102a3e843567843b1631 | vietqnguyen7/ProjectEuler | /Python/5.py | 259 | 3.5625 | 4 | def mod(x): return x%2
if __name__ == '__main__':
number_list = range(1,20)
check = False
num = 1
while check == False:
num += 1
new_num = list(filter(lambda x: num%x, number_list))
if len(new_num) == 0:
check = True
print(new_num)
print(num) |
e86ef5169d3980826170ac9187905a79a4e543c0 | jakipatryk/aoc-2019 | /day-4/secure.py | 890 | 3.65625 | 4 | def is_good(password):
sequence = []
current = password
for i in range(6):
sequence.insert(0, current % 10)
current = current // 10
was_two_consecutive = False
many_in_row = False
for i in range(1, 6):
if sequence[i] < sequence[i-1]:
return False
if se... |
c5f37852e60433372d87aac59a493ce9af00d4cb | yuktigarg10/data-challenge | /my_solution/solution.py | 2,038 | 3.90625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Feb 9 21:40:27 2020
@author: Yukti Garg
This script reads the input csv file and writes cleaned output to another csv and database
To use this script:
python solution.py <input_csv_file> <output_csv_file> <desired_db_name> <desired_table_name>
... |
fb23d1b0db0619ef64427d0d2baf880e0039c013 | lisac-usds/dsnap_rules | /dsnap_rules/rules.py | 2,314 | 3.84375 | 4 | class Result:
""" A Result object encapsulates a `bool` indicator of success, a list of
findings, and any metrics that were computed by the executed results.
"""
def __init__(self, successful, findings, metrics=None):
if metrics is None:
metrics = {}
self.successful = success... |
47ac5cb15616d13f47ea3da6449cce4d59a2dd6e | ilanasufrin/dsa | /priorityQueues/priorityQueue.py | 2,238 | 4.1875 | 4 | """
This class is an implementation of a (minimum) priority queue using an array backing.
It holds on to data as a list of tuples: (data, priority)
"""
from collections import deque
class PriorityQueue():
def __init__(self):
self.queue = []
"""Push item onto heap, maintaining the heap invariant aft... |
54c8efd9f2089ce4b52178f9ce06a0c667a83210 | krodrig91/intro-to-prog-python | /Homework/hw4_pascals_triangle/hw4_sol.py | 673 | 3.875 | 4 | '''
Created on Feb 23, 2015
@author: Kelvin Rodriguez
'''
# helper function for pascal_row()
def helper(L):
'''returns a list of sums of adjacent elements within list L'''
if len(L) == 1 : return []
return [L[0] + L[1]] + helper(L[1:])
def pascal_row(n):
'''returns a list of elements found in a certain row of
Pa... |
bc7784f8e61b0ad6ea67df5fec2547dc940f83d9 | javpelle/ComputerGeometry | /scprits .py/Fisher.py | 6,695 | 3.765625 | 4 | import numpy as np
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
class Fisher:
'''
Least Square classification algorithm class.
----------
Attributes
----------
- w: Linear vector associated to linear application.
- c: Real. if w(x) < c then x belongs ... |
b5f977fe4b70abaa44c53a3b251edb153b83a1e7 | poolen1/Statistics | /statcalc.py | 803 | 3.5 | 4 | import stats
#sample = open('sample.txt','r').read()
data = stats.Sample('sample.txt')
data.read()
#print(data.sample)
basics = stats.Basic_Stats(data.sample)
frequency = stats.Frequency(data.sample)
#print(basics.elements)
basics.calc_mean()
basics.calc_median()
basics.calc_variance()
basics.calc_stddev()
#print(dat... |
938cfdaf6aa59b6fbbf385b9c47e99dd6cc39b3e | JanhaviNandish/Python | /changecase.py | 167 | 3.921875 | 4 | n=input()
for i in n:
if i==i.upper():
print(i.lower(),end=' ')
elif i==i.lower():
print(i.upper(),end=' ')
else:
print(i)
|
833f6b97dc9a347b726438711ac10381e23feb81 | lichkingwulaa/Codewars | /5 kyu/5_kyu_Valid_Parentheses.py | 758 | 4.03125 | 4 | """
https://www.codewars.com/kata/valid-parentheses/train/python
"""
def valid_parentheses(string):
string = list(string)
if len(string) == 0:
return True
i = 0
while True:
if string[i] != '(' and string[i] != ')':
del string[i]
i = 0
else:
i += 1
for j in range(len(string)):
if string[j] != '('... |
90f17dc968b8f971c0d9764e9edeb311fddb0a63 | huilizhou/Leetcode-pyhton | /algorithms/sort/shell_sort.py | 1,929 | 3.546875 | 4 | # 希尔排序
"""
20190117 恪穆整理
希尔排序,也称递减增量排序算法,是插入排序的一种更高效的改进版本。
希尔排序是非稳定排序算法。
希尔排序是基于插入排序的以下两点性质而提出改进方法的:
插入排序在对几乎已经排好序的数据操作时,效率高,即可以达到线性排序的效率
但插入排序一般来说是低效的,因为插入排序每次只能将数据移动一位。
所谓的基本有序,就是小的关键字基本在前面,大的关键字基本在后面,不大不小的基本在中间。
采取跳跃分割的策略:将相距某个“增量”的记录组成一个子序列,
这样才能保证在子序列内分别进行插入排序后得到的结果是基本有序而不是局部有序的。
希尔排序的关键并不是随便分组后各自排序,而是将相隔某个“增... |
10fb11ece710f9ca97649bde78dc603dc1d50124 | skanda9927/year2020 | /5_Printing_ten_odd_or_even_numbers.py | 1,596 | 4.46875 | 4 | #program to print ten odd or ten even numbers
#PSEUDOCODE
#step1:create a varible number and enter the number from that even or odd numbers to be printed
#step2: input number 1 for odd numbers to be printed \n input number 2 for even numbers to be printed
... |
ab64fb5fc39f4029eed9eea5554dc6b0fcf27f2c | andreluismoreira/Codigos-em-Python | /letraN.py | 834 | 3.859375 | 4 | def main01():
posicao = int(input("digite sua posicao: "))
tempoAtendimento = 0
for i in range(0, posicao - 1):
tempoEspera = float(input("Digite o tempo medio de espera do cliente {}: ".format(i + 1)))
tempoAtendimento += tempoEspera
tempoMedio = tempoAtendimento / posicao
print("O ... |
93934f5808409f2725606c0318ed96cc3e0b6e52 | fndalemao/Python | /Desafios/desafio065.py | 472 | 4.03125 | 4 | conti = 'S'
i = maior = menor = soma = 0
while conti == 'S':
num = float(input('Digite um número: '))
i += 1
soma += num
if i == 1:
maior = menor = num
else:
if num > maior:
maior = num
if num < menor:
menor = num
conti = str(input('Quer continuar?... |
0951504911d88c62d3b2339b65550a733ea2ac1d | RohanDeySarkar/DSA | /arrays/4_move_element_to_end/moveElementToEnd.py | 399 | 3.65625 | 4 | # O(n) time | O(1) space
def moveElementToEnd(arr, toMove):
left = 0
right = len(arr) - 1
while left < right:
while left < right and arr[right] == toMove:
right -= 1
if arr[left] == toMove:
arr[left], arr[right] = arr[right], arr[left]
left += 1
retu... |
d1722f959c574f44cd96eb600d6f4f4f9b286541 | slavisha84/Homework_Mission_to_Mars | /scrape_mars.py | 4,393 | 3.5 | 4 | # Using Jupyter notebook working code, i will turn it into scraper app to Scrape Web Data about Mars and return Library to collect all scared Data
# Importing dependencies required for entire code below
import os
import time
import shutil
import requests
import numpy
from splinter import Browser
import pandas as pd
fr... |
03a3ef8562599e546fcf71ee6d2d2a8d1d49926e | bintehoor/python-assignmenyt | /loop.py | 6,268 | 4.0625 | 4 | # word assignment answers of question (24 to 43)
print("-------------------------%((24)FIRST 10 POSITIVE INTEGERS )%-------------------------------------")
n = int(input("Enter a Number : "))
f = 0
for i in range(n+1):
print(i)
f += i
print("Sum of the First",n," Positive Integers are :",f)
print("---... |
96842e53515f49048c9ff5db6a2b5a505d304771 | maywanting/algame | /leetcode/80removeDuplicates/Solution.py | 577 | 3.625 | 4 | class Solution(object):
def removeDuplicates(self, nums):
p, num = 0, 1
for q in range(1, len(nums)):
if nums[p] == nums[q]:
if num < 2: # p move
num += 1
p += 1
nums[p] = nums[q]
else: # p move and ... |
dfd0f772751d8d6624e55651d998f9eaca53c6f5 | EgorPashkevich/pythontutorRU | /pythontutorRU/lesson2_if_else/zad4_Leap year.py | 96 | 3.65625 | 4 | a = int(input())
print('yes') if (a % 4 == 0 or a % 100 != 0) and a % 400 == 0 else print('no')
|
7a692e7996d7181a82e83af53ffc00a48ab3d6f2 | dimitardd/Mitko_python_ver1 | /Homework/H_3/Homework_1_5.py | 554 | 3.859375 | 4 | # Homework 1.5 Dimitar Dimitrov
import random
list_10 = random.sample(range(0, 100), 10)
#print('List is : {}'.format(list_10))
a = int(input('Please insert number from 0 ro 100 : '))
if a in list_10:
print('Found {} in list {}'. format(a, list_10))
else:
print('Not found {} in list {}'. format(a, list_10))
de... |
6e3d0e04276e2fd8f04aa46f4f8fbfb1d06d1656 | Carson-Banash/UOFC_assignments | /assignment#3.py | 10,455 | 3.984375 | 4 | #Carson Banash (30085955)
#Lab B06
#imports all of the simple graphics library
from SimpleGraphics import *
#handleInput holds all of the logic for the users choice, including asking the for a choice as-well as re-asking if the input doesn't fit
#there are no parameters
#there is only one return, that being the integ... |
82a99f35c74e54868ee217dccf6d71a9b8d1d3f1 | vinayakvarshney31/vowel | /vowels_occurance.py | 453 | 3.734375 | 4 | a=['A','E','I','O','U']
p=input("enter the text\n")
l=[]
s=p.upper()
c=list(s)
for i in range(len(c)):
for j in range(len(a)):
if c[i]==a[j]:
l.append(c[i])
print('repetation of vowel A',l.count('A'))
print('repetation of vowel E',l.count('E'))
print('repetation of vowel I',l.count('I'))
print... |
0ffac809c2efd881ea8c75a1470737ee1d9194e7 | alijafargholi/code_puzzles | /puzzle_01/rectangle_rotation.py | 1,414 | 4.0625 | 4 | """
Source
^^^^^^
https://www.codewars.com/kata/simple-fun-number-27-rectangle-rotation/train/python
A rectangle with sides equal to even integers a and b is drawn on the Cartesian
plane. Its center (the intersection point of its diagonals) coincides with the
point (0, 0), but the sides of the rectangle are not parall... |
ae0e371313a45fe789b91ddb9cfcd6ce987c5344 | chavli/HetCMP-Codebase | /Python/models/modelEvaluator.py | 3,021 | 3.609375 | 4 | """
modelEvaluator.py
Cha Li
19 May 2012
This class contains convenient methods used to calculate the performance of
a learning model. Performance is measured using misclassification rates and
confusion matrices.
Currently, only binary classification tasks are handled by this class.
variable naming:... |
10c1eb8771f766ccd4845260a48c5a8e71218831 | sneidermendoza/Ejercicio_ciclo_while | /ejrcicio_1.py | 951 | 3.65625 | 4 | # De n numeros primos contenidos en un intervalo (por ejemplo los numeros
# primos del 1 al 100), calcule la sumatoria, la productoria y el promedio.
def es_primo(numero):
contador = 0
for i in range(1, numero + 1):
if i == 1 or i == numero:
continue
if numero % i == 0:
... |
e7a6f8f556dcfa6014d7566bd77209a7368e56d4 | DJAVernon/AIND-Isolation | /AIND-Isolation/practise/gamestate.py | 4,479 | 3.59375 | 4 | from copy import deepcopy
xlim, ylim = 3, 2 # board dimension constants
class GameState:
"""
Attributes
----------
_board: list(list)
Represent the board with a 2d array _board[x][y]
where open spaces are 0 and closed spaces are 1
and a coordinate system where [0][0] ... |
ba8d3c1b2eba6f4564b2818f0af159c1fb6532c4 | daniel-reich/turbo-robot | /vnzjuqjCf4MFHGLJp_2.py | 748 | 4.125 | 4 | """
Create a function that takes a string and shifts the letters to the right by
an amount `n` **but not the whitespace**.
### Examples
shift_letters("Boom", 2) ➞ "omBo"
shift_letters("This is a test", 4) ➞ "test Th i sisa"
shift_letters("A B C D E F G H", 5) ➞ "D E F G H A B C"
### Notes
... |
70d3e4d224aecef823fae100f09213129d74e4d1 | Berbet16/PG1926 | /PG1926KAMPI_BETÜLBERNASOYLU/Python/hesap_makinesi.py | 601 | 4 | 4 | def cal(x, y, ops):
if ops not in '+-/*':
return 'choose operator: "+. -, /, *"'
if ops == '+':
return(str(x) + ' ' + ops + ' ' + str(y) + '=' + str(x+y))
if ops == '-':
return(str(x) + ' ' + ops + ' ' + str(y) + '=' + str(x-y))
if ops == '*':
return(str(x) + ' ' + ops + ' ' + str(y) +... |
bd0e9ce2622bc916d7001a6d9043552afa16b89c | Inflearn-everyday/study | /hysKim1/4673.py | 271 | 3.53125 | 4 | #4673 셀프넘버
def self_number(num):
self_num = num
while num != 0:
self_num += num % 10
num //= 10
return self_num
result = []
for i in list(range(1, 10001)):
result.append(self_number(i))
if i not in result:
print(i) |
7818668322a938ce2a202e6683ac2c04d09c3916 | mgcarbonell/30-Days-of-Python | /07_split_join_slice.py | 5,330 | 4.5 | 4 | numbers = [1, 2, 3, 4, 5]
numbers = str(numbers)
# we get [1, 2, 3, 4, 5] (except they're strings)
# if we pass to print we may notice we get the same
# that's because print converts the list to a string.
# "[1, 2, 3, 4, 5]"
# What if we want just 1, 2, 3, 4, 5?
# What if I want...
# The people who worked on this proje... |
96a992f9a604781686eead4330a73f0eb8f90254 | rahul-erc/bank_function | /bank.py | 8,337 | 3.828125 | 4 | import random
def main():
print(" ******Welcome To ERC Banking System******\n")
name_list, acc_num_list, acc_blc_list = read_file()
option = 0
while option != 5:
# displaying option menu
banking_menu = [" 1. Open Account", " 2. Withdraw Money",
... |
1fa302657da634fdd4be21295513161dd838fc4a | gamapedro77/he4rtoberfest-2020 | /challenges/3-area-trapezio/python/luizeduardobp/trapezio.py | 366 | 3.875 | 4 | try:
maior = int(input("Digite o valor da base maior: "))
menor = int(input("Digite o valor da base menor: "))
altura = int(input("Digite o valor da altura: "))
area = ((menor + maior) * altura) / 2
print("A area do trapezio é: {}".format(area))
except ValueError:
print("Uma das entradas não c... |
abca991947c2544513ef13eba739a5d8be818446 | vastech73/Algorithms | /find_missing.py | 451 | 3.984375 | 4 | def find_missing(lst,array_size):
array_sum = sum(lst)
array_sum_orig = array_size * (array_size + 1) / 2
print("Sum of given array:{}".format( array_sum))
print('Sum of Original array:{}'.format(array_sum_orig))
missing_number = array_sum_orig - array_sum
if len(lst) > array_size:
missing_number = array_sum - ... |
abf0625c40b821dfc40f2c51d91c34698764fdcb | tainenko/Leetcode2019 | /leetcode/editor/en/[737]Sentence Similarity II.py | 3,570 | 4.0625 | 4 | # We can represent a sentence as an array of words, for example, the sentence
# "I am happy with leetcode" can be represented as arr = ["I","am",happy","with",
# "leetcode"].
#
# Given two sentences sentence1 and sentence2 each represented as a string
# array and given an array of string pairs similarPairs where s... |
54391ed1abc9713d4db095a6b8d26cb12153645d | JeeVeeVee/univ | /1steBachelor/AlgoritmenEnDatastructuren/SorteerAlgoritmen/QuickSort.py | 1,426 | 3.5625 | 4 | import random
import datetime
def quicksort(rij):
if len(rij) <= 1:
return rij
else:
rechts = []
links = []
spillen = []
spil = 0
#print(spil, rij)
for i in range(len(rij)):
if rij[i] < rij[spil]:
links.append(rij[i])
... |
9baf803bb1fc4c57ec047a182fa65f0a688eae53 | mrparkonline/py_basics | /solutions/ageProgram.py | 303 | 4.21875 | 4 | '''
Exercise 4: Develop an Instruction Set that calculates your age based on the current year.
'''
# input section
current_year = int(input('Enter the current year: '))
birth_year = int(input('Enter your birth year: '))
# processing
age = current_year - birth_year
# output
print('Your age is:', age) |
0280177b0c0387c85553b56a780e20fa9a1b57b0 | JosephLevinthal/Research-projects | /5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/222/users/4066/codes/1642_869.py | 309 | 3.71875 | 4 | # Teste seu código aos poucos.
# Não teste tudo no final, pois fica mais difícil de identificar erros.
# Use as mensagens de erro para corrigir seu código.
compra = float(input("Valor da compra: "))
desconto = compra*(5/100)
if(compra >= 200):
print(round(compra - desconto,2))
else:
print(compra) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.