blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
6bc780d508f837ca9c0428fa160e72932b2060c8 | futurice/PythonInBrowser | /examples/session1/square.py | 837 | 4.5625 | 5 | # Let's draw a square on the canvas
import turtle
##### INFO #####
# Your goal is to make the turtle to walk a square on the
# screen. Let's go through again turtle commands.
# this line creates a turtle to screen
t = turtle.Turtle()
# this line tells that we want to see a turtle shape
t.shape("turtle")
# this lin... |
2700036147f7310b4c7a8b6bd6237500f825f98b | TesLake/btc_strategy_simulation | /src/reports.py | 824 | 3.640625 | 4 | def print_results(
bank,
initial_bank,
profits_history,
biggest_trade_percent,
positive_trades,
negative_trades,
):
if bank > initial_bank:
percent_change = ((bank - initial_bank) / initial_bank) * 100
else:
percent_change = (((initial_bank - bank) / initial_bank) * 100) ... |
79ce1e0713b2f86a92c57db171d4ca7f19e3cb9f | frankShih/TimeSeriesVectorization | /vectorization/rdp.py | 2,913 | 3.75 | 4 | # -*- coding: utf-8 -*-
"""
The Ramer-Douglas-Peucker algorithm roughly ported from the pseudo-code provided
by http://en.wikipedia.org/wiki/Ramer-Douglas-Peucker_algorithm
"""
from math import sqrt
def distance(a, b):
return sqrt((a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2)
def point_line_distance(point, start, e... |
a821e7e410b90e805e1722d9b369da31034774ab | UWPCE-PythonCert-ClassRepos/Python210_Fall2019 | /students/jammy_chong/lesson04/dict_lab.py | 789 | 3.65625 | 4 | #Dictionaries 1
dict1 = {'name':"Chris", 'city':"Seattle", 'cake':"Chocolate"}
print(dict1)
dict1.pop('cake')
print(dict1)
dict1['fruit'] = "Mango"
print(dict1.keys())
print(dict1.values())
print('cake' in dict1.keys())
print('Mango' in dict1.values())
#Dictionaries 2
dict1 = {'name':"Chris", 'city':"Seattle", 'cake... |
7e6f7d3700097adec5cf6d71449f851c5575fef9 | jncinlee/Python_gadget | /Multiprocessing.py | 3,614 | 3.546875 | 4 | # -*- coding: utf-8 -*-
##2 multiproccessing
import multiprocessing as mp
import threading as td
import time
def job(a,d):
print('aaa')
if __name__=='__main__': #in this frame by demand
p1 = mp.Process(target=job,args=(1,2)) #job()步對
p1.start()
p1.join() #almost same as threading
... |
8597989651664171dc04e45ab7920273ec1aa6ee | csetarun/coding_questions | /polindrome.py | 172 | 4.0625 | 4 | word= 'aba'
length = len(word)
check = 1
for i in range(length/2):
if(word[i]!=word[length-i-1]):
check=0
if(check==1):
print 'Polindrome'
else:
print 'Not Polindrome' |
4b45142446beafd541578a3c3f413be9f9f952e2 | supvolume/codewars_solution | /5kyu/increment_string.py | 720 | 3.984375 | 4 | """ solution for String incrementer challenge
increase the number at the end of the given string"""
def increment_string(strng):
input_list = list(strng)
digit_index_start = len(input_list)
for i in range(len(input_list)-1,-1,-1):
if input_list[i].isdigit() == False:
break
digit... |
9158d24739d932fd1f26359e7afbe67b6a4605a0 | ebellocchia/bip_utils | /examples/bip38_no_ec.py | 1,569 | 3.984375 | 4 | """Example of private key encryption/decryption without EC multiplication using BIP38."""
import binascii
from bip_utils import Bip38Decrypter, Bip38Encrypter, WifDecoder, WifEncoder
# BIP38 passphrase
passphrase = "DummyPassphrase"
# WIF private key correspondent to a compressed public key
priv_key_wif = "Kx2nc8C... |
6363d46489e331d24a8087ab58e893d95f43d9c8 | buglenka/python-exercises | /LetterCasePerm.py | 1,249 | 4.3125 | 4 | #!/usr/local/bin/python3.7
"""Letter Case Permutation
Given a string S, we can transform every letter individually
to be lowercase or uppercase to create another string.
Return a list of all possible strings we could create.
Examples:
Input: S = "a1b2"
Output: ["a1b2", "a1B2", "A1b2", "A1B2"]
Input: S = "3z4"
Ou... |
2ec57df4da4ccfb86347ba2ebe42ef8b00cc3ba4 | nehasutay/Technical_Test_4 | /que_25.py | 122 | 3.75 | 4 | dictionary={}
dictionary[1]=1
dictionary['1']=2
dictionary[1]+=1
sum=0
for k in dictionary:
sum+=dictionary[k]
print(sum) |
488f2a40ec8e70f6f6218fc98f8fd6480aa47d3b | fredrick12/MachaGrades | /grades.py | 405 | 3.796875 | 4 | science_grades = [50, 40, 30, 14, 90, 100, 100, 100, 80]
science_avg = 0
for g in science_grades:
science_avg += g
science_avg /= len(science_grades)
print("Frederick's science average is: %.2f" % science_avg)
math_grades = [100, 100, 100, 14, 90, 100, 100, 100, 80]
math_avg = 0
for g in math_grades:
math_avg += g... |
0f0c7db015d9d75de26154a3eba212f0fa74a43a | kdh7575070/taeha-kang | /자율과제형/4 머신러닝 개인 공부/tf_3-1.py | 777 | 3.546875 | 4 | import tensorflow as tf
x_train = [1,2,3]
y_train = [1,2,3]
#변수설정
W = tf.Variable(tf.random_normal([1]), name='weight')
X = tf.placeholder(tf.float32)
Y = tf.placeholder(tf.float32)
#H(x)=Wx 모델구현, 코스트정의
hypothesis = X * W
cost = tf.reduce_sum(tf.square(hypothesis - Y))
#Gradient descent 풀어서 정의해보자
lea... |
041e5470d31c98ae2e9e663de080c933374a4c60 | VictorSpini/SEII-VictorSpini | /Semana 02 - Python - Victor Spini/exerc03.py | 1,913 | 4.15625 | 4 | # Lists, Tuples and Set
courses = ['Física', 'Literatura', 'Geografia', 'Informatica']
print(courses)
print(len(courses))
print(courses[0])
print(courses[-1])
print(courses[0:2])
print(courses[1:])
courses.append("Artes")
print(courses)
courses.insert(0, "Psicologia")
print(courses)
courses_2 = ["Matematica", "Por... |
d3bb7c08cb4c35bac0c7c22e3e900da42ea3f079 | Javi-uria98/ejerciciossge | /directory/ejercicio7.py | 509 | 3.796875 | 4 | import random
n = random.randint(0, 10)
respuesta = int(input("Trate de adivinar el número"))
intentos = 1
while respuesta != n:
intentos = intentos + 1
if respuesta > n:
print("El número introducido es mayor del correcto, vuelva a probar")
respuesta = int(input())
else:
print("El n... |
f458f592b960c757ba06be65ae45e4c93fbd3e6c | cabanasd9464/CTI110 | /P4HW4_Cabanas.py | 712 | 4.375 | 4 | # Creating a star using a nested loop
# March 18, 2019
# CTI-110 P4HW4 - Nested Loops
# Drake Cabanas
#
def main():
import turtle # Allows us to use turtles
win = turtle.Screen() # Creates a playground for turtles
t = turtle.Turtle() # Create a turtle, assign to t
t.pensize... |
b3ddabf7ff01a1e9e153cc7826a7d7ceb68b38ec | xuefengCrown/Files_01_xuef | /all_xuef/code/sicp_code_python/1.2/fact.py | 273 | 4 | 4 | """
线性递归与迭代
"""
def fac_iter(N, counter, product):
"迭代法计算阶乘"
if counter == N+1:
return product
else:
return fac_iter(N, counter+1, product*counter)
def factorial(N):
return fac_iter(N, 1, 1)
print(factorial(6))
|
a9289958d597c59841b6e94a8fa0e17f52a12f25 | fb779/cidei | /backend/lab_1/lab1-1/lab1_1.py | 732 | 3.671875 | 4 | # -*- coding: utf-8 -*-
"""
programa: lab1_1.py
author: Fabian Forero
calcular la tasa de impuesto de un alimento
1. declracion de variables
tax - tasa de impuesto
tax_one - tasa de impuesto adicional
2. Entradas
valordel alimento
numero de aliments
3. Computaciones
tasa de entrada = suma de ... |
80e66e4849597b8a97ad75210f6a4660a76cb5fd | ethan-haynes/coding-problems | /python/src/flatten.py | 373 | 3.78125 | 4 | def flatten(root):
head = None
def traverse(root):
"""
:type root: TreeNode
:rtype: void Do not return anything, modify root in-place instead.
"""
if root:
traverse(root.right)
traverse(root.left)
root.right = head
root.lef... |
7fcb67768afd74abff7220222f97ed7c3609fcdc | JamesMcColl/Grudius-X | /Assignment4/powerupTest.py | 2,040 | 3.5625 | 4 | """ Author: James McColl
Create power-ups and add scrolling
"""
import pygame, random
pygame.init()
screen = pygame.display.set_mode((640, 480))
class Ship(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load("ship.g... |
215ede84d1a3d9f692c4278143f08f15083277ab | rashmitallam/PythonPrograms | /squares_dict.py | 527 | 4.0625 | 4 | #WAP to accept a number from user and return a dict of squares from 1 to that number
def GenerateSquares(n):
res=dict()
for i in range(1,n+1):
res[i] = i*i
return res
def main():
n=input('Enter a number:')
s=GenerateSquares(n)
print s
if __name__ == '__main__':
... |
8bb38d3b963c4b2e43ffae3b6e3afdc8ee7dbcc0 | ljingchen/covid-20 | /scripts/step1_mx.py | 7,184 | 3.578125 | 4 | """
This script downloads the Mexican dataset and its catalog.
It then merges them and cleans them into a new dataset.
"""
import csv
import io
import os
import zipfile
import requests
from openpyxl import load_workbook
DATA_URL = "http://187.191.75.115/gobmx/salud/datos_abiertos/datos_abiertos_covid19.zip"
DATA_FI... |
dadb4575771ea257b81818112a01a9780a16d4c6 | xxLin97/Math-Tutor | /quiz.py | 710 | 3.953125 | 4 | import random
questions = {} #initiaize a dictionary
score=0
#randomly pick a math problem from 1 to 10
for i in range(10):
int_a = random.randint(0,10)
int_b = random.randint(0,10)
operators = ['+','-','*']
operator_value = random.choice(operators)
question = str(int_a)+" "+operator_value+" "+str... |
180342d56159ddcd722e7b4745042d47e8f7e84f | paulaaraujo11/Desafios_CEV_Py3 | /dsf005.py | 304 | 4.09375 | 4 | #Faça um programa que leia um número inteiro e mostre na tela
#o seu sucessor e seu antecessor
print('============Desafio 05==============')
n = int(input('Digite um número: '))
a = n - 1
s = n + 1
print('O antecessor vale {} e o sucessor vale {}. O número digitado foi {}'.format(a,s,n))
|
0bcfe09b663de2ccf28a4a988ce277a39d6f9758 | akshat14714/BomberMan | /walls.py | 544 | 3.890625 | 4 | #!/usr/bin/env python
""" This method is for walls on board """
from __future__ import print_function
from bricks import Brick
BRICK = Brick()
class Walls(object):
""" This init for encapsulation """
def __init__(self):
self.size = 4
self._struct = [[' ' for _ in range(4)] for _ in range(2)... |
9ab959b929acfe03e99a281d4cb09f5506f85556 | aimeelaplant/Hacker-Rank-Solutions | /Algorithms/Strings/StringConstruction.py | 221 | 3.515625 | 4 | # https://www.hackerrank.com/challenges/string-construction
#!/bin/python
import sys
n = int(raw_input().strip())
for a0 in xrange(n):
s = list(raw_input().strip())
string_set = set(s)
print len(string_set)
|
556af98533b0cc0dc0e823251c89f5826c69b249 | gabriellaec/desoft-analise-exercicios | /backup/user_009/ch120_2020_03_30_19_32_31_272194.py | 683 | 3.53125 | 4 | import random
din = 100
while din <0:
val = int(input('quanto quer apostar?'))
if val == 0:
break
tipo = input('digite o tipo da aposta [n ou p]')
num = random.randint(36)
if tipo == 'n':
chute = int(input('digite um n de 1 a 36'))
if chute ==num:
di... |
73ec8078ed0f4e646191dd463ef1bb83a2d4b64e | Jyotirm0y/kattis | /zebrasocelots.py | 102 | 3.515625 | 4 | n = int(input())
x = 0
for _ in range(n):
x *= 2
x += int(input() == 'Z')
print(2**n - 1 - x)
|
4c6e1d63fa3be1bfd72564bf2b21c0b4c4aa1e20 | shobhit10058/Hate-Speech-Detection | /task/ReadingAndPreprocessingData.py | 1,695 | 3.640625 | 4 | import pandas as pd
import numpy as np
import os,string
# This function helps to read a TSV file
def ReadTsv(path):
# input file
inp_f = open(path, 'r')
# reading the columns and
# removing the next line character
c = inp_f.readline()[:-1].split()
# making a empty data frame with
# th... |
dc44298bc540b1d704fedcb58bdfeafc4c0f060a | cesium12/solver-tools | /solvertools/model/numbers.py | 1,040 | 4 | 4 | from math import log, pow
def is_numeric(word):
try:
int(word)
return True
except ValueError:
return False
def lg(n):
return log(n) / log(2)
def number_logprob(n):
"""
A kind of arbitrary power-law distribution for how common a number should
be. Obeys Benford's Law and... |
862c7dc2cc7e441ade8728651a15f18f815156fb | douglaswender/python | /aula4/exec5.py | 185 | 3.546875 | 4 | total = 0
def somalista(lista):
total = 0
for i in range(0, len(lista), 1):
total=lista[i]+total
return total
list = [2,3,5]
total = somalista(list)
print(total) |
9cba21e243923f784ec859b13407fe40bf00d7a1 | shubhamsahu02/Cspp1-practise | /M3/iterate_even_reverse.py | 57 | 3.9375 | 4 | print("Hello!")
i=10
while 2<=i:
print(i)
i=i-2
|
7d2d96d7c9211aee997782e1fb9ead6bd918bcf8 | UltiRequiem/oop-algorithms-python-platzi | /src/17_complejidadalgoritmica.py | 604 | 3.578125 | 4 | import time
import sys
def factorial(n):
response = 1
while n > 1:
response = response * n
n = n - 1
return response
def factorial_recursive(n):
if n == 1:
return 1
return n * factorial_recursive(n - 1)
if __name__ == "__main__":
n = 200000
sys.setrecursionli... |
d116d775268b2c62bf1cbccc7639de029e091b34 | gabriellaec/desoft-analise-exercicios | /backup/user_108/ch47_2020_03_27_02_17_41_627505.py | 598 | 3.546875 | 4 | def estritamente_crescente(lista):
crescente = lista
esta_crescente = False
i = 0
proximo = False
while not esta_crescente:
for x in range(i,len(crescente)):
if crescente[i] > crescente[x]:
valor = crescente.pop(x)
crescente.insert(i,valor)
... |
b5f4b36ef97cac6481da13d0d78d6c702cd0fdec | Aunik97/LISTS | /tast 1.py | 1,069 | 4.375 | 4 | first_student = input(print("Please enter the name of the first student:"))
second_student = input(print("Please enter the name of the second student: "))
third_student = input(print("Please enter the name of the third student: "))
fourth_student = input(print("Please enter the name of the fourth student: "))
fifth... |
02bcc4151ecdeeaf623a5dddc4909cc3f69804ca | PythonCollections/Pyth-Lnk-Bytes | /00PrimeNumbers.py | 833 | 3.890625 | 4 |
def G_get_prime_number(a):
print("Given Input is {0}".format(a))
primenumbers = [2,3,5,7]
factors = []
for i in primenumbers:
print("Current Operator is {}".format(i))
print("Result of the Operator is {}".format(a % i))
if(a % i == 0):
print("Entered the Loop")
... |
31b15838f98609905ac4302e1a7f06c3958aa0d3 | alexandraback/datacollection | /solutions_5709773144064000_0/Python/arturasl/code.py | 497 | 3.609375 | 4 | from fractions import Fraction
def time(start, speed, x):
return (x - start) / speed
for t in range(1, int(input()) + 1):
factory_cost, factory_speed, x = [float(i) for i in input().strip().split()]
answer, best, speed = 0, time(0, 2, x), 2
while True:
answer += time(0, speed, factory_cost)
... |
f7a6796334ea586ac854a7737616085723823673 | sasadangelo/pythonbyexamples | /examples/functions/functions.py | 1,417 | 4.96875 | 5 | #This function simply print the message "Hello Function !!!"
def hello_func():
print("Hello Function !!!")
# A function can take in input one or more parameters. It is not
# necessary specify their type, because Python infer them from
# the arguments passed.
def hello_msgs(msg1, msg2):
print(msg1, msg2)
# Pyt... |
923315501c225921a4b9aa6b6f2f89307b7f580b | melany202/programaci-n-2020 | /talleres/taller_tipo_parcial.py | 3,857 | 3.84375 | 4 | #cree una funcion para cada uno de los puntos
print('punto1')
def listaNum (lista):
mayor = max(lista)
menor = min(lista)
suma=0
for elemento in (lista):
suma += elemento
promedio=suma/len(lista)
print(f'el numero mayor en la lista es el {mayor},el numero menor es el {menor} y el p... |
6a68e7fed196be5fb404b20bf99e4fd7e5ab011b | Hoyci/validador_CPF_CNPJ | /validador_CNPJ.py | 918 | 3.53125 | 4 | def calcular_primeiro(cnpj):
it = 5
soma = 0
for i in cnpj:
mult = int(i) * it
if it == 2:
it = 10
it -= 1
soma += mult
resultado = 11 - (soma % 11)
if resultado > 9:
resultado = 0
print(resultado)
return cnpj + str(resultado)
def calcula... |
c27ea05c3268fbefa0b6cc27413fba420aa9f979 | apsz/python-learning | /Third Chapter/generate_test_names_2.py | 892 | 3.578125 | 4 | #!/usr/bin/python3
import random
def main():
forenames, surnames = get_forenames_and_surnames()
fh = open('generated_names2.txt', mode='w')
limit = 100
years = tuple(range(1970, 2013))*3
for name, surname, year in zip(
random.sample(forenames, limit),
... |
f9cd7d15d66bbda6fa251bc269cd15f240f519f5 | Tuchev/Python-Basics---september---2020 | /06.Nested_Loops/01.Labs/07. Cinema Tickets.py | 943 | 3.796875 | 4 | film_name = input()
free_spaces = int(input())
command = input()
student_tickets = 0
standard_tickets = 0
kid_tickets = 0
sold_tickets = 0
while film_name != "Finish":
while command != "End":
if command == "student":
sold_tickets += 1
student_tickets += 1
elif... |
ee36f401309d19ad08d0dd74c2ed0ddd42f0785e | ddmin/CodeSnippets | /PY/DailyProgrammer/easy2.py | 418 | 4.21875 | 4 | # [Easy] Challenge 2
print("== Newton's Second Law Calculator ==")
print("Omit the variable to solve for.")
print()
print("Force:")
f = input("> ")
print()
print("Mass:")
m = input("> ")
print()
print("Acceleration:")
a = input("> ")
print()
if not f:
print('f = ' + str(float(m) * float(a)))
elif not m:
p... |
5729c5e0cd2afd99bb581e6304241c0dbb6f8b05 | sandy4405/python_practices | /Data_structure.py | 4,783 | 3.515625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Aug 17 23:49:27 2021
@author: sande
"""
#sending email
# =============================================================================
# import getpass
# import smtplib
# smtp_object = smtplib.SMTP('smtp.gmail.com',587)
# (smtp_object.ehlo())
# (smtp_object.starttls())
# pass... |
f2bac554f5be4f247b41e4291187f93b97d9cb8b | LAOR10/sge | /Capitulo05/dam/sge/ejemplos/HerenciaMultiple.py | 436 | 3.75 | 4 | # -*- coding: utf-8 -*-
'''
Created on 21/10/2014
@author: Luismi
'''
class B(object):
'''
classdocs
'''
def __init__(self, val1):
'''
Constructor
'''
#print val1
class C(object):
def __init__(self):
'''
Constructor
'''
... |
a3ee01052b139fd911a2ffc6091d711869b470f4 | WeiS49/leetcode | /Solution/二叉树/遍历/计算/路径/257. 二叉树的所有路径/模拟递归.py | 1,157 | 3.796875 | 4 | #
# @lc app=leetcode.cn id=257 lang=python3
#
# [257] 二叉树的所有路径
#
# @lc code=start
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
from typing import AnyStr
class Solution:
... |
dfbf470f56d8f72baa043aa8b4b65481cada6a45 | bartvm/myia | /myia/prim/ops.py | 1,914 | 3.71875 | 4 | """Primitive operations.
Primitive operations are handled as constants in the intermediate
representation, with the constant's value being an instance of a `Primitive`
subclass.
"""
from ..utils import Named
class Primitive(Named):
"""Base class for primitives."""
pass
##############
# Arithmetic #
###... |
fd7d9d1e0368e32b60447ba8457cd23e8f66f64a | sliucll/py | /PY4E/CH6/6.15. Mixed-up Code Questions.py | 1,720 | 3.828125 | 4 | #Q-1: The following segment should print the statement, "So happy 4 you!".
emotion = "So happy "
print(emotion + str(4) + " you!")
#Q-2: The following program segment should print the phrase, "My new book cost $12".
item = "new book"
price = "12"
print("My " + item + " cost $" + price)
#Q-3: The following program seg... |
9fc7eadf10537d253b39ee5f8087b9cb8f39aaa9 | eianlee1124/daily-practice | /programmers/list_of_numbers.py | 465 | 3.921875 | 4 | #!/usr/bin/env python3
def solution(phone_book):
phone_book.sort()
for p1, p2 in zip(phone_book, phone_book[1:]):
if p2.startswith(p1):
return False
return True
if __name__ == "__main__":
pb1 = ['119', '94674223', '1195524421']
pb2 = ['123', '456', '789']
pb3 = ['12', '1... |
d838778c3d86fd3bfbb395a60717d3b77949f288 | rcsolis/data_algs_python | /dictbases.py | 1,254 | 4.0625 | 4 | print("DICTIONARIES")
print("Key/Value pairs, are Unordered")
print("create dicts with {}")
x = {"name":"Rafael", "age":35, "job":"Software Engineer", 10:"Ten"}
print(x, type(x))
del x
print("Create using dict with list of key/value tuples")
x = dict([
("name", "Rafael"),
("age", 35),
("job", "Software eng... |
dcd0e431356b3b389289a1284c04c018f32b2d2b | mebinjohnson/Basic-Python-Programs | /student.py | 2,055 | 3.9375 | 4 | student={}# empty dictionary
def addEntry():
name=raw_input('enter the name ')
rollno=int(raw_input('enter the rollno '))
age=int(raw_input('enter the age '))
Class=raw_input('enter the class ')
student[rollno]=[name,age,Class]
def removeEntry():
rollno=int(raw_input('enter the roll no to be d... |
34c8f995c6d26e1adcfee06848a3c900d15287cf | alamyrjunior/pythonExercises | /ex048.py | 203 | 3.734375 | 4 | s = 0
count = 0
for c in range(1,501,2):
if c % 3 == 0:
s += c
count += 1
print('A soma dos {} números entre 1 e 500 que são múltiplos de três é {}.'.format(count,s))
|
3784d7095396c71b91720690eb5070b15940e736 | IceBlueX/py | /3-高级特性/迭代-最值.py | 549 | 3.765625 | 4 | def findMinAndMax(L):
if L[:1]:
max=L[0]
min=L[0]
for num in L:
if num>max:
max=num
if num<min:
min=num
return (min,max)
else:
return (None,None)
if findMinAndMax([]) != (None, None):
print('测试失败!')
elif findMin... |
97a262e3f1d37c0f2ea1a1456abc8940c347e95a | jec-apostol/kaizend | /1_basic/exercise2.py | 416 | 4.34375 | 4 | # If Statements and Comments Exercise
# Make an if-else statement if year is between 2000 and 2100
# (including both numbers), then print out:
# "Welcome to the 21st century"
# Else print out:
# "You are before or after the 21st century"
year = 1830
number = input("Enter a year: ")
if number >= 2000 and 2100:
pri... |
ee6bd93206293f117da1fc4702acc81494d4c019 | istrupin/python-practice | /src/stack/brackets.py | 557 | 3.5 | 4 |
def is_valid(text: str) -> bool:
openers = ['(', '{', '[', '|']
closers = [')', '}', ']', '|']
o_set = set(openers)
c_set = set(closers)
bracket_map = dict(zip(closers, openers))
stack = []
for c in text:
if c in o_set:
stack.append(c)
if c in c_set:
... |
d23620ced35b71e5418e975d87eff5e1a3f7d688 | lmacionis/Exercises | /11. Lists/Exercise_8.py | 1,312 | 4.15625 | 4 | """
Extra challenge for the mathematically inclined: Write a function cross_product(u, v)
that takes two lists of numbers of length 3 and returns their cross product. You should write your own tests.
"""
import sys
def cross_product(u, v):
s = []
for i in range(len(u)):
if i == 0:
j,k = 1,... |
470daeecb293ad32e9d0693e76c79cf820f16626 | CyrusVader/DTS-SF-Project-API | /script.py | 2,715 | 3.5625 | 4 | # Foreign exchange rate API tool
# Import required Modules / Packages
import json
import requests
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import datetime
# Links to the Curerency api
historical_url = 'https://api.exchangeratesapi.io/history'
def validate(date_text):
# Check that dat... |
c71ec26ddf8106f85329ff911046b2d6d0a79856 | dg5921096/Books-solutions | /Python-For-Everyone-Horstmann/Chapter4-Loops/P4.18.py | 384 | 4.125 | 4 | # Write a program that prints a multiplication table, like this:
# 1 2 3 4 5 6 7 8 9 10
# 2 4 6 8 10 12 14 16 18 20
# 3 6 9 12 15 18 21 24 27 30
# . . .
# 10 20 30 40 50 60 70 80 90 100
for i in range(1, 11):
for j in range(1, 11):
... |
a3009861c4719e4f943847cea8bec0bc24b17923 | rajasekaran36/GE8151-PSPP-2020-Examples | /unit3/illus-bin.py | 811 | 4.09375 | 4 | def bin_search(numbers,key):
len_of_numbers = len(numbers)
if(len_of_numbers==0):
return 'empty'
elif(len_of_numbers==1):
if(key==numbers[0]):
return 0
else:
return 'not found'
else:
low = 0
high = len_of_numbers-1
while(not (low>hi... |
a1ec94047af356519671032460ff1723efd16d53 | patel/Advent-of-code | /2016/p3/solution.py | 905 | 3.828125 | 4 | import itertools
def find_number_valid_triangles(input_str):
return len(filter(lambda (a, b, c): a + b > c,
map(lambda x: sorted(map(int, filter(lambda z: z != '', x.split(' ')))), input_str.split('\n'))))
def find_number_valid_triangles_vertically(x):
columns = []
for line in x.s... |
7a761d868808e120bd1ea1314fd6082f4f46b092 | Divya23789/PythonLab | /Basic1/specified value is contained in a group of values.py | 509 | 4.4375 | 4 | #Write a Python program to check whether a specified value is contained in a group of values.
print("Enter some numbers")
n = input()
print("Enter a number to check in list")
m = input()
if m in n:
print("The number is in the list")
else:
print("The number is not in the list")
# def is_group_member(group_data... |
3d10c7aec4718174727f5ae1384885f01642a6dc | khromov-heaven/pyBursaGit | /L3/dz3_6.py | 201 | 3.59375 | 4 | from math import sqrt
limit = 100
for number in xrange(1, limit + 1):
for mult in xrange(2, int(sqrt(number)+1)):
if number % mult == 0:
break
else:
print number
|
707c7870e82c9835f89aa2ee01d9794c80574adb | AndreySkryl/Codewars | /Python/5 kyu/Primes in numbers/main.py | 826 | 3.6875 | 4 | from collections import defaultdict
def is_prime(number):
return 2 in [number, 2 ** number % number]
def prime_factors(number):
primes = list(filter(is_prime, range(2, int(number ** 0.5) + 1)))
decompositions = defaultdict(int)
for prime in primes:
while number % prime == 0:
deco... |
e2420b1d2170c61216645bda4e4531f4b284d9c5 | Jeevankv/LearnPython | /zFunction.py | 347 | 3.71875 | 4 | # Functions and DocType
a=10
b=20
c=sum((a,b))
print(c)
def function1():
print("its function1")
print(function1())
function1()
def Average(a,b):
"""This function is to calculate the average of the two numbers"""
average= (a+b)/2
return average
print(Average.__doc__)
x= int(Average(a,b)... |
2b1dde51e05b2a14e8f57fff32ebbbd68fb9b2f9 | manmeet1049/DSA | /DSA/stack_ll.py | 1,672 | 4.125 | 4 | class Node:
def __init__(self,data):
self.data =data
self.next=None
class Stack:
def __init__(self):
self.head=None
def push(self,data):
new_node=Node(data)
if self.head==None:
self.head=new_node
else:
te... |
01267ca678cd9723737cb69fd9107fec4d7586e8 | aledgu/alex_sense-mail.ru | /lesson1/HomeTask1_5.py | 698 | 4 | 4 | revenue = int(input('Введите сумму выручки: '))
cost = int(input('Введите сумму издержек: '))
if revenue > cost:
profit = int(((revenue - cost)/revenue)*100)
print(f'Ваша рентабельность составила {profit}%')
officer = int(input('Введите количество сотрудников: '))
profit_to_one_officer = int((revenue -... |
5f1ea371ec092d0a5e2152ef85d7df385c303b75 | poipiii/data-structures-and-algorithms-mini-project | /challengeQn.py | 1,198 | 4.0625 | 4 | #use hashtable to find the 2 numbers thqat add up to target
# we check if the target value - number at index is a key in the dictonary if it is we end the program and return the results
seq = [2, 38, 8, 10, 15, 16, 23, 28]
def challenge(seq, target):
hashtable = {}
#sort the array and remove all numbers ... |
f86cbd9d306ec6e329b241622fd532bf48f51070 | thehalfspace/coursework | /Clasp410/Lab01/src/forest-fire-model.py | 5,489 | 3.578125 | 4 | ###################################################
#
# FOREST FIRE MODEL
#
# Author: Prithvi Thakur
# Written in: Python v3.6.6
# Last Modified: 09-08-2018
#
# Clasp 410 Lab 1: In a two dimensional forest
# with some trees and some bare
# land, initiate and spread fire
#... |
9172485a4b8ac0b38cb9b7d13601ad71ff752ca6 | Bruception/advent-of-code-2020 | /day02/part1.py | 605 | 3.6875 | 4 | import sys
import re
class PasswordField:
def __init__(self, line):
match = re.match(r'^([0-9]+)-([0-9]+)\s([a-z]{1}):\s([a-z]+)$', line)
self.min = int(match.group(1))
self.max = int(match.group(2))
self.char = match.group(3)
self.password = match.group(4)
count = se... |
82d8c8c8f62375e2d10f24751499d0ac42ef377c | DmitryVlaznev/leetcode | /1663-smallest-string-with-a-given-numeric-value.py | 2,038 | 4.03125 | 4 | # 1663. Smallest String With A Given Numeric Value
# Medium
# The numeric value of a lowercase character is defined as its position
# (1-indexed) in the alphabet, so the numeric value of a is 1, the
# numeric value of b is 2, the numeric value of c is 3, and so on.
# The numeric value of a string consisting of lower... |
b46be8fe365e738a7544dca97ba9b5834e046260 | fjfhfjfjgishbrk/AE401-Python | /zerojudge/b330.py | 260 | 3.515625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Apr 10 10:36 2020
@author: fdbfvuie
"""
a = input().split()
n = a[0]
x = a[1]
count = 0
for i in range(int(n)):
for j in str(i + 1):
if j == x:
count += 1
print(count) |
ccb1f5c436e97b2ec3b9d01c2879723a8faa9867 | IZOBRETATEL777/Python-labs | /Lesson-10/sort_by_avg.py | 548 | 3.59375 | 4 | a = []
s = 0
inp = 1
print('Введите целые числа (каждое в новой строке). Для остановки введите 0.')
while True:
inp = int(input())
if inp == 0:
break
s += inp
a.append(inp)
print()
avg = s / len(a)
print(f'Среднее арифметическое: {avg:g}')
print('Больше среднего:')
for i in a:
if i > avg:
... |
821d74cc1726fb8c02a03a6f8116b17546cddbbb | Vostbur/cracking-the-coding-interview-6th | /python/chapter_1/09_string_shift.py | 1,090 | 3.765625 | 4 | """Допустим, что существует метод isSubstring, проверяющий,
является ли одно слово подстрокой другого. Для двух строк s1 и s2 напишите код,
который проверяет, получена ли строка s2 циклическим сдвигом s1,
используя только один вызов метода isSubstring
(пример: слово waterbottle получено циклическим сдвигом erbottlewat)... |
93ff567695715ac694823b00ace55e4b43f28b19 | talitheterrific/awitw | /awitw.py | 13,086 | 3.625 | 4 | # A Walk in the Woods
import random
merch_stats = [1, 0, 0, 0, 2, 3]
war_stats = [3, 1, 2, 0, 0, 0]
wiz_stats = [0, 0, 0, 3, 1, 2]
def start():
print('You find yourself alone on a winding cobblestone street,')
print('the woods around you humming with summer life. The only')
print('light comes ... |
c8ccd8648f93253039fc68de5a2f3f606b15074c | John-Rey-Pial/Python-Baby-Steps | /exer10.py | 180 | 4.0625 | 4 | terms = int(input("Input the number of terms: "))
for term in range(1,terms+1):
answer = term*term*term;
print(f"Number is: {term} and cube of {term} is {answer}")
|
44464b84189dd11e87b75af6f87a6dae65518de9 | kadegar/realpy_projects | /sql/sql_join.py | 388 | 4.09375 | 4 | import sqlite3
with sqlite3.connect("new.db") as connection:
c=connection.cursor()
c.execute("""SELECT DISTINCT population.city,population.population,regions.region FROM population,regions WHERE population.city=regions.city ORDER BY population.city ASC""")
rows=c.fetchall()
for r in rows:
print "City: "+r[0]
p... |
74d049e7897e200e1d1307eb5857e4ed9f1adead | wapj/coding-exercise | /leetcode/median-of-two-sorted-arrays.py | 1,326 | 3.734375 | 4 | """
https://leetcode.com/problems/median-of-two-sorted-arrays/
Input: nums1 = [1,3], nums2 = [2]
Output: 2.00000
Explanation: merged array = [1,2,3] and median is 2.
좀 더 빠르게 할 수 있을것 같은데 쉽지 않다.
"""
from typing import List
class Solution:
def median(self, nums1: List[int], nums2: List[int]) -> float:
nums ... |
da8b14e6b258b8a2d3d10c3b1595a54947dacbf5 | adyates/advent-2015 | /day11/solution.py | 1,612 | 3.8125 | 4 | CURRENT_PASSWORD = 'hepxxyzz'
class SantaPassword(object):
MAX_CHAR = ord('z')
MIN_CHAR = ord('a')
def __init__(self, text):
self.password = [ord(letter) for letter in text]
def __str__(self):
return ''.join([chr(letter) for letter in self.password])
def hasRunRequirement(self):... |
63b4a704aa041774592146cf392ab341947c5e3d | navpandey9491/Desktop-Assistant | /python assitant.py | 2,315 | 3.875 | 4 | import time
answer =input ("hello! : ")
if answer == "hi":
print("good morning sir ! ")
for pause_in_second in [2]:
time.sleep(pause_in_second )
print("My name is Jarvis ")
time.sleep(pause_in_second )
print("And i am your AI assitant")
time.sleep(pause_in_second )
answe... |
3096efe3983a14567065008dfd31092397cc483e | Tarun-Sharma9168/Python-Programming | /IstheStringInorder.py | 242 | 4.03125 | 4 | def is_in_order(txt):
old_list=list(txt)
new_list=sorted(txt)
if new_list == old_list:
return True
else:
return False
print(is_in_order("abc"))
print(is_in_order("edabit"))
print(is_in_order("123"))
print(is_in_order("xyzz")) |
a1c76e27553390637a386103f563e2db5e666356 | nickeita/su2021_is601_project2 | /src/calculator/calculator.py | 1,155 | 3.5 | 4 | from calculator.addition import addition
from calculator.subtraction import subtraction
from calculator.multiplication import multiplication
from calculator.division import division
from calculator.nthPower import nth_power
from calculator.nthRoot import nth_root
from calculator.nSquared import n_squared
from calculato... |
d322849e81c7e2d3a525b5dc84038df45c799d96 | sol83/python-code_in_place-section3 | /running_total.py | 795 | 4.15625 | 4 | """
Running Total
Write a program that asks a user to continuously enter numbers and print out the running total,
the sum of all the numbers so far.
Once you get the program working, see if you can modify it so that the program stops when the user enters a 0.
Enter a value: 7
Running total is 7
Enter a value: 3
Ru... |
bda01d669bf549a711f25b5688a755963161ef06 | sherwinyu/class | /201_spring2012/lisp1.py | 619 | 3.734375 | 4 | def cdr(x):
return x[1:]
def car(x):
return x[0]
def pieces(x):
return f(x, str(x))
def f(x, path):
if type(x) == list:
if len(x) == 0:
return str(x) + " " + path
else:
return cons(str(x) + " " + path, cons( f(car(x), "car "+path), f(cdr(x), "cdr "+path)) )
else:
return str(x) + " "... |
c477339f6df74db09346b1fb0cfbb59057de3aca | syurskyi/Algorithms_and_Data_Structure | /_algorithms_challenges/codeabbey/codeabbeyPrograms-master/weighted_sum_of_digits.py | 808 | 3.75 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Apr 28 08:05:10 2016
@author: rajan gyawali
Problem #13
Weighted sum of digits
This program resembles more complex algorithms for calculation CRC
and other checksums and also hash-functions on character strings.
wsd(1776) = 1 * 1 + 7 * 2 + 7 * 3 + 6 * 4 = 60
"""
print... |
376e1648cb26381f5223e519c8b31d027345bba4 | wush13/ilovepython | /classification/lr.py | 2,167 | 3.53125 | 4 | from dataset import Dataset
import math
import numpy as np
class Logistic:
weights_x = []
rate = 0.0
iteration_cnt = 0
#string_dict = {}
def __init__(self, rate, length, iteration_cnt ):
"""
Initialize your data structure here.
"""
self.rate = rate
self.weigh... |
161200326cd136b24657a74985fcd38318899aa9 | PhoebeCooney/CA116 | /func_sum_range.py | 488 | 3.671875 | 4 | import func_bsearch
def sum_range(a, low, high):
low = func_bsearch.bsearch(a, low)
no = 0
while low < len(a) and a[low] < high:
no = no +int(a[low])
low = low + 1
return no
def main():
print sum_range([2,3,6,6,7,8], 3, 7) # 15
print sum_range([2,3,6,6,7,8], 3, 8) # 22
print sum... |
4b89dfe4f1a74b8172a7337adfdc26e4f29de8a8 | jczhangwei/leetcode_py | /_912_sort_an_array.py | 1,080 | 3.9375 | 4 |
import math
class Solution:
def mergeSort(self, nums, start, end):
s = end - start
if s <= 0:
return nums
elif s <= 1:
if nums[start] > nums[end]:
nums[start], nums[end] = nums[end], nums[start]
return nums
m = math.floor((e... |
88b28123478dc7eb6660dd26cf168d55bb32ecf6 | rodrigobraga/Mars-Rover-Challenge | /tests.py | 2,986 | 3.5 | 4 | # coding: utf-8
"""
Tests to Mars Rover.
"""
import unittest
import mock
from rover import Heading, Command, Plateau, Rover
class TestPlateau(unittest.TestCase):
"""
Verifies if after landed, the rover can navigate on the plateau.
"""
def setUp(self):
self.plateau = Plateau(5, 5)
def t... |
6e99b35868325e00f5ad7eabfc69339f55d27693 | kqg13/LeetCode | /Backtracking/getHappyString.py | 1,685 | 3.859375 | 4 | # LeetCode Problem 1415: The k-th Lexographical String of All Happy Strings of Length n
# A happy string is a string that:
#
# consists only of letters of the set ['a', 'b', 'c'].
# s[i] != s[i + 1] for all vals of i from 1 to s.length - 1 (string is 1-indexed).
# For example, strings "abc", "ac", "b" and "abcbabcbcb"... |
043bf3601351dd8d200f071172a3e327eae80919 | wmahoney52/Algorithms-DataStructures | /Unit0_PythonPrimer/monteCarlo.py | 2,568 | 4.25 | 4 | """
Monte Carlo Estimation of π
A program that uses the Monte Carlo technique to estimate a value for π (3.1415926...).
The program generates and stores a user-specified number of (x, y) points for the estimation.
Then, using the given formula, an estimation of pi is generated. Each time the estimation runs,
the use... |
eff83c070447c15602c6be74edf6d6023069d89f | SatishGodaPearl/gameprogrammingpatterns | /Behavioral/Type_Object/6_dynamic-editing-loading.py | 3,710 | 4.1875 | 4 | """
Each monster in the game is simply an instance of class Monster
The Breed class contains the information that's shared between all the monsters of the same breed
- Starting Health
- Attack String
Each Monster instance is given a reference to a Breed object containing the information for that breed.
Defi... |
2948bcf060c8f83a431e44699ba760cfebaa2a2f | cwilkins-8/7 | /7.2.py | 481 | 4.25 | 4 | #7.2 Restaurant Seating
#seating = input("How many people are in your dinner group? ")
#seating = int(seating)
#if seating <= 8:
#print("\n We have a table avaible for you")
#else:
# print("Sorry, you will have to wait for a table.")
#7.3 Multiples of Ten
number = input("Please enter a numbe... |
f342f794c450cf4271b5f51e062c8c98626cf4d3 | ksayee/programming_assignments | /python/CodingExercises/OccurencesCharTogether.py | 935 | 4.0625 | 4 | # Check if all occurrences of a character appear together
# Given a string s and a character c, find if all occurrences of c appear together in s or not. If the character c does not appear in the string at all, the answer is true.
def OccurencesCharTogether(ary,c):
lst=list(ary)
seenFlg=False
for i in ran... |
512de34057ab08b326509fa9c575efd404aac5b3 | roblg/project-euler | /python/problem54.py | 5,277 | 3.71875 | 4 |
import os.path
def card_value_int(card):
v = value_from_card(card)
if v == 'A':
return 14
if v == 'K':
return 13
if v == 'Q':
return 12
if v == 'J':
return 11
if v == 'T':
return 10
return ord(v) - ord('0')
def value_from_card(c):
"Extract the v... |
a1277db14a36a84a7e9dad5019049205d6d79fd2 | kate-simonova/RefFasta | /scripts/statistic_AA | 7,726 | 3.625 | 4 | #!/usr/bin/python3
# this script is used to get statistics about protein sequence
# importing necessary modules
import sys
from string import printable
# variables used in script
seq_list = []
AA_codes = ['C', 'D', 'Q', 'I', 'A', 'Y', 'W', 'H', 'L', 'R', 'V', 'E', 'F', 'G', 'M', 'N', 'P', 'S', 'K', 'T', 'P',
... |
43a6ddfc0d65e21f8afcdff6fa1ade993e8bbb7a | willnight/PythonHomeWork | /task6_4.py | 2,508 | 3.953125 | 4 | direction = {"left": "вправо", "right": "влево"}
def colored_sting(text, color):
return f"{colors.get(color)}{text}{colors.get('off')}"
colors = {
'yellow': '\033[1;33m',
'green': '\033[1;32m',
'red': '\033[1;31m',
'purple': '\033[1;35m',
'blue': '\033[1;34m',
'off': '\033[0m'
}
class ... |
fcd6e18433ac921d27cca4af0bb97140cb452b9f | suddencode/pythontutor_2018 | /6.16.py | 169 | 3.65625 | 4 | a = int(input())
buf1 = 0
buf2 = 0
while a != 0:
b = int(input())
if a == b:
buf1 += 1
if buf1>buf2:
buf2=buf1
else:
buf1=0
a=b
print(buf2+1)
|
d2c3fe0b9a24a709ffe085cd75d6e1c6f867c70a | nnzzll/leetcode | /二叉树/872.py | 1,286 | 3.859375 | 4 | # Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def leafSimilar(self, root1: TreeNode, root2: TreeNode) -> bool:
res1 = []
res2 = []
def dfs... |
fc62be061e45231de161307ba4bca0790e876f2e | MukhammedDinaev/python-project-lvl1 | /brain_games/games/even.py | 322 | 3.53125 | 4 | from random import randint
task = "Answer yes if the number is even, otherwise answer no."
def is_even(number):
return number % 2 == 0
def get_round_data():
question = randint(0, 100)
if is_even(question):
true_answer = 'yes'
else:
true_answer = 'no'
return question, true_answe... |
7794bbd954a8c59ebf52475ea8cc45b25f1072d5 | whozghiar/mbcrump-twitch | /src/defendtheweb/rotsolver.py | 961 | 3.765625 | 4 | #!/usr/bin/python3
"""Brute-forces a ROT cipher
http://cmattoon.com/infosec-institute-ctf-level-4/
"""
def rot(text, n):
"""Rotates 'text' by 'n' positions"""
output = ''
for char in text.lower(): # don't use uppercase values
x = ord(char)
if (x >= ord('a') and x <= ord('z')):
... |
cadd4499651989370f361ee6e393a62cbc6957ef | forrestv/pyable | /test/extendedif.py | 100 | 3.96875 | 4 | x = 5
if x == 0:
x = 20
elif x == 5:
x = 2
elif x == 2:
x = 3
else:
x = 9
print x
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.