blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
7cab92e137d51b21e990888cda4bed535fde9054 | yanivr78/MyProjects | /Python/Nested_Lists+Random_Rock_Paper_Scissors_Game.py | 1,090 | 4.25 | 4 | import random
rock = '''
_______
---' ____)
(_____)
(_____)
(____)
---.__(___)
'''
paper = '''
_______
---' ____)____
______)
_______)
_______)
---.__________)
'''
scissors = '''
_______
---' ____)____
______)
__________)
(____)
... |
3ca270980c8599e6d35ae2dc41b4d289c67d9f15 | Ernest-Sharp/Programming_for_Informatics | /Personal_exercises/chaper_2-05.py | 327 | 4.25 | 4 | # Exercise 2.5 Write a program which prompts the
# user for a Celsius temperature, convert the
# temperature to Fahrenheit, and print out the
# converted temperature.
# Celsius a Fahrenheit (C x 9/5) + 32 = F
celsius = raw_input("Enter temperature in C: ")
fahrenheit = (float(celsius) * 9 / 5) + 32
print "F = ", fahr... |
c935f8cf336b1a6a52af4485d6c2669ae4696862 | Ernest-Sharp/Programming_for_Informatics | /Curso_3-4/02week_01.py | 494 | 4 | 4 | # In this assignment you will read through and parse a
# file with text and numbers. You will extract all the
# numbers in the file and compute the sum of the numbers.
import re
result_list= list()
result = 0
handler = open("regex_sum_206751.txt")
for line in handler:
num_list = re.findall("[0-9]+", line)
resu... |
655ec53d266ab8da4cca77e367ef8c1822489115 | Ernest-Sharp/Programming_for_Informatics | /Curso_3-4/04week_02.py | 979 | 3.84375 | 4 | # The program will use urllib to read the HTML from the data
# files below, extract the href= values from the anchor tags,
# scan for a tag that is in a particular position relative to
# the first name in the list, follow that link and repeat the
# process a number of times and report the last name you find.
import ur... |
7d69ed57a43ed92c43b6ac9f66daa42f6083f4a3 | hsung8/mds-provider | /mds/fake/util.py | 2,185 | 4.09375 | 4 | """
Generating random data of miscellaneous types.
"""
import datetime
import random
import string
def random_date_from(date, min_td=None, max_td=None):
"""
Produces a datetime at a random offset from date.
Parameters:
date: datetime
The reference datetime.
min_td: int, time... |
2abbe83485a379b97c76064f5d660c5d44c93b02 | KawasakiLover26/Proyecto-1 | /sistema de reservacion.py | 2,462 | 3.78125 | 4 |
def MenuAdministrativo():
print ("(4) Gestión de empresas")
print ("(5) Gestión de transporte por empresa")
print ("(6) Gestión de viaje")
print ("(7) Consultar historial de reservaciones")
print ("(8) Estadísticas de viaje")
print ("(9) Retornar")
opc... |
f5e0dee4dfb62897a1952890e9cfd6a3d90a6a74 | ramimanna/whoisteachingwhat | /whoisteachingwhat.py | 1,958 | 3.546875 | 4 | #DATA FOR COURSE 6 ONLY#
# import numpy as np
# import matplotlib.pyplot as plt
# import pandas as pd
# from pandas import DataFrame, Series
import csv, urllib2,re
from BeautifulSoup import *
with open('who-is-teaching-what.csv','rb') as csvfile:
spamreader = csv.reader(csvfile, delimiter=',', quotechar='|')
course... |
35851890a470aa5c942db8b265d81c899e27ae2a | chung2014/unittest | /romantest1.py | 484 | 3.65625 | 4 | import roman1
import unittest
class KnowValues(unittest.TestCase):
know_values = ( (1, 'I'),
(2, 'II'),
(3, 'III'),
(4, 'IV'),
(5, 'V') )
def test_to_roman_known_value(self):
'''to_roman should give known result with known input''... |
e1f3075a4f36afe4485e07f61e57335e2d4f7a77 | Warrior2612/Stock-Market-Data-Visualiser | /util/column_converter.py | 2,148 | 3.640625 | 4 | import pandas as pd
class Column_Converter:
"""
Helps santise the recieved data by converting the strings to the data types they are supposed to represent.
"""
def convert_column_to_float(self, df, columns):
"""
Converts columns from str to float
"""
for column in column... |
06bb3347761ebd0ea366ed6e11fd00dca6270527 | anu-ujin-g/KeepinItReal | /src/_old/tfidf.py | 870 | 3.6875 | 4 | import pandas as pd
from sklearn.feature_extraction.text import TfidfVectorizer
def tfidf(df):
'''
Feature engineering using the TF-IDF method
Input: training and validation set
Output: sparse matrix
'''
tfidfvec = TfidfVectorizer(stop_words='english', binary=True)
# Create a new variable... |
89a754cc3f5259a0c7529ada1729f801627bc9df | Geekoly/urban-spork | /MaktabKhone's Projects/Section 1/Age-range.py | 307 | 3.75 | 4 | age=int(input())
if (0<age) and (age<6):
print("khordsal")
elif (6<=age) and (age<10):
print("koodak")
elif (10<=age) and (age<14):
print("nojavan")
elif (14<=age) and (age<24):
print("javan")
elif (24<=age) and (age<40):
print("bozorgsal")
elif age>=40:
print("miansal") |
578ff3992264256535ae1738c2a4369ab0c4c63a | bmatis/time_tracker_cli | /common_functions.py | 3,658 | 3.765625 | 4 | from datetime import datetime, timedelta
def print_menu(options, header=""):
"""Prints a numbered list of menu options."""
if header != "":
print(header)
print("-" * len(header))
i = 1
for option in options:
print(str(i) + ". " + option)
i += 1
def convert_str_to_timede... |
43916784e32d68c1e9346d196cdc7644a9c8091a | ljxpy/my_py | /2二级练习题/1.1format.py | 422 | 4.3125 | 4 | # 请在______处使用一行代码或表达式替换
#
# 注意:请不要修改其他已给出代码
#1
'''s = input("请输入一个字符串:")
print("{1}{0}{1}".format(s, (10-len(s)//2)*"="))'''
#2
'''s = input("请输入一个字符串:")
print("{:=^20}".format(s))# ^居中 < > '''
#3
s = 3
print("{b}这个数字是{a:+^10}{c}".format(a=s, b='s', c="!"))
print("%c这个数字是%d%c" % ('s', s, "!")) |
f21f61024122d12054c16c8592df0f060f1d0449 | TonyLDS/sort | /bubble.py | 838 | 3.765625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Dec 27 10:19:00 2016
@author: luzhangqin
"""
#排序算法
#冒泡排序
#平均时间O(n^2)
#最差情形O(n^2)
#稳定度:稳定
#额外空间O(1)
#备注:n小时较好
'''
原理是临近的数字两两进行比较,按照从小到大或者从大到小的顺序进行交换,
这样一趟过去后,最大或最小的数字被交换到了最后一位,
然后再从头开始进行两两比较交换,直到倒数第二位时结束,以此类推。
'''
def bubble_sort(nums):
for i in range(len(nums)-1, 0, -... |
3690aba9f9013bc214e51079cab55ff025d37cbf | xXG4briel/CursoPythonGuanabara | /18 - Listas(2)/Desafio 085.py | 322 | 3.671875 | 4 | lista = [[],[],[]] # 0 num, 1 par , 2 impar
for i in range(7):
num= int(input('Digite um valor: '))
lista[0].append(num)
if num % 2 == 0:
lista[1].append(num)
else:
lista[2].append(num)
print(f'Valores digitados {lista[0]}\nValores ímpares {lista[2]}\nValores pares {lista[1]}')
... |
b834d77833601e10889d393265e5f0519aada188 | xXG4briel/CursoPythonGuanabara | /12- Condições Aninhadas/Desafio 039.py | 619 | 3.953125 | 4 | '''Desafio 039
Faça um programa que leia o ano de nascimento de um jovem e informe,de acordo com sua idade:
SE ELE ainda vai se alistar ao serviço militar
Se é a hora de se alistar.
Se já passou do tempo do alistamento
OBS: SEU PROGRAMA TAMBÉM DEVERÁ MOSTRAR O TEMPO QUE FALTA OU QUE PASSOU DO PRAZO'''
f... |
2b0a872850192f8dea3e4c0af74ac4be2159b48d | xXG4briel/CursoPythonGuanabara | /13 - Estrutura de Repetição for/Desafio 052.py | 367 | 3.75 | 4 | #leia um número inteiro e diga se ele é ou não um número primo
num = int(input('Digite um número: '))
cont=int()
for i in range(1,num+1):
if num % i == 0:
cont+=1
print(f'{i:2}', end=' → ')
else:
print(f'{i:2}',end=' → ')
if i% 10 == 0 :
print(' ')
print(('É primo')if cont... |
35d11b1b535840c9d9f6b431b7adf86106b090dc | xXG4briel/CursoPythonGuanabara | /7 - Operadores Aritméticos/Desafio 013.py | 139 | 3.65625 | 4 | s=float(input('Qual o seu salario? '))
print('Não mais!, agora voce recebe {} '.format(s*0.15+s))
print('Parabens pelo aumento de 15% !')
|
f68864008062ebfd1d72fe6a8ccce636dd82e034 | xXG4briel/CursoPythonGuanabara | /12- Condições Aninhadas/Desafio 038.py | 447 | 3.8125 | 4 | '''Desafio 038
Escreva um programa que leia dois números
inteiros e compare-os, mostrando na tela
uma mensagem:
-o primeiro valor é maior
-o segudno valor é maior
-não exite valor maior, os dois são iguais'''
x=float(input('Digite um numero: '))
y=float(input('Digite outro numero: '))
if x>y:
prin... |
70748eb9420032fd3cdecff319232655949940c8 | xXG4briel/CursoPythonGuanabara | /14 - Estrutura de repetição While/Desafio 060.py | 313 | 4.125 | 4 | #faça um porgrama que leia um número qualquer e mostre o seu fatorial
'''x=float(input('Digite um valor: '))
i=x
while i!=1:
i-=1
x=x*i
print(x)'''
x=int(input('Digite um valor: '))
print(x, end=' - ')
for i in range(x,0,-1):
if i<x:
x=x*i
print(i, end=' - ')
print(x)
|
15a6598f5b4924d971b0794cc3c2d5fde1e4ba4c | xXG4briel/CursoPythonGuanabara | /14 - Estrutura de repetição While/Desafio 062.py | 523 | 3.71875 | 4 | var = cont = cont2 = termos2 =0
primeiro_termo = int(input('Digite o primeiro termo: '))
razao = int(input('Digite o segundo termo: '))
termos =10
while var==False:
cont += 1
cont2 +=1
print(f'{primeiro_termo}', end=' → ')
primeiro_termo += razao
if cont==termos:
termos = int(input('Digite ... |
833151127e77c4ea9cfd74f7e2ab7cd1e3f410a1 | xXG4briel/CursoPythonGuanabara | /10 - Condições/Desafio 034.py | 517 | 3.796875 | 4 | """DESAFIO 034
PERGUNTE O SALARIO DE UM FUNCIONARIO E CALCULE O VALOR DO SEU AUMENTO
PARA SALARIOS SUPERIOES A R$1.250,00 CALCULE UM AUMENTO DE 10%
PARA INFERIOES OU IGUAIS, O AUMENTO É DE 15%"""
sal=float(input('Qual seu salário? '))
print('Você ganhou um aumento parabéns!\n\n')
if sal>1250.0:
print('Voce rec... |
1cd3ec74b0ba8cc56442c3a502de75e258cd7ebd | xXG4briel/CursoPythonGuanabara | /14 - Estrutura de repetição While/Desafio 064.py | 187 | 3.96875 | 4 | soma=num=cont=0
while num!=999:
num=int(input('Digite um número: '))
if num !=999:
soma=soma+num
cont+=1
print(f'voce digitou {cont} vezes e a soma foi {soma}')
|
f2eee7055e269a8218eca093790310b7e7e2c67b | xXG4briel/CursoPythonGuanabara | /15 - Interrompendo repetições while/Desafio 067.py | 436 | 3.953125 | 4 | '''faça um programa que faça a tabuada de vários números, um de cada vez,
para cada valor digitado pelo usuário. O programa será interrompido quando o número
solicitado for negativo
'''
while True:
print('-'*20,'\n')
tab = int(input('Digite um valor: '))
if tab<0:
print('-'*25,'\nOperação finali... |
101619822de6d26022854bd7477022e14e21adfe | xXG4briel/CursoPythonGuanabara | /7 - Operadores Aritméticos/Desafio 008.py | 161 | 3.6875 | 4 | metros=int(input('Quantos Metros são para a coversão? '))
print('{} metros equivale a {} centimetros e {} milimetros'.format(metros, metros*100, metros*1000))
|
7ea51863df04d87b69ef5b32e9b434fb188a3b9d | xXG4briel/CursoPythonGuanabara | /18 - Listas(2)/Desafio 086.py | 431 | 3.859375 | 4 | matriz = []
var = []
for i in range(3):
var.append(int(input('Digite um valor: ')))
var.append(int(input('Digite um valor: ')))
var.append(int(input('Digite um valor: ')))
matriz.append(var[:])
var.clear()
for x in range(3):
print(f'( {matriz[0][x]} )', end=' ')
print(' ')
for y in range(3):
... |
c1b83879932626c7246eff59b224fbbd8e8e4f24 | xXG4briel/CursoPythonGuanabara | /7 - Operadores Aritméticos/Desafio 006.py | 169 | 3.90625 | 4 | n=int(input('digite um valor: '))
print('o valor digitado corresponde a {} sendo seu quadrado {} ele ao cubo {} e sua raiz quadrada {}'.format(n, n**2, n**3, n**(1/2)))
|
0f8ca3deaf4c3af16fadb51be12cc3b5922a1f91 | diegollterza/urionline | /exercicio 115.py | 296 | 3.8125 | 4 | res = ""
while True:
point = [int(x) for x in input().split()]
if point[0] == 0 or point[1] == 0:
print(res,end="")
break
if point[0] > 0:
if point[1] > 0:
res += "primeiro\n"
else:
res += "quarto\n"
else:
if point[1] > 0:
res += "segundo\n"
else:
res += "terceiro\n"
|
92bed93c8ddcf1044ad1d6eb9ac81dcff2cc4b26 | diegollterza/urionline | /exercicio 116.py | 213 | 3.71875 | 4 | n = int(input())
res = ""
for _ in range(n):
div = [int(x) for x in input().split()]
if div[1] == 0:
res += "divisao impossivel\n"
else:
res += str(format(div[0]/div[1], '.1f')) + "\n"
print(res, end='')
|
ad7d8f0b364f581745bb32aeb2542cec7f0a2cca | karimjp/firefighters-python | /firefighters/firedispatch.py | 1,860 | 3.84375 | 4 | from abc import ABC, abstractmethod
from typing import List
from firefighters.city import City
from firefighters.city_node import CityNode
from firefighters.firefighter import FireFighter
class FireDispatch(ABC):
@property
@abstractmethod
def firefighters(self) -> List[FireFighter]:
"""
... |
0912d82356eaab888ba20c02d7cf8820eeb10f35 | RULE-MAKER/python | /ifelse.py | 205 | 3.6875 | 4 | a =input('ENTER')
if int(a) == 12 :
print ('nagendra')
elif int(a) == 11:
print('hi')
elif int(a) == 00:
print('1000000000000000000000000000000000000000000000')
else :
print('who are you') |
e068997b35e3920705a2e614354d4bd297c09dac | mwdempse/Neural-Network-by-Hand | /Two_Layer_Neural_Network_with_Keras.py | 788 | 3.5625 | 4 | """
Two Layer Neural Network with Keras
"""
from keras.layers import Dense, Activation
from keras.models import Sequential
import numpy as np
import sklearn
import sklearn.datasets
import sklearn.linear_model
import matplotlib
import matplotlib.pyplot as plt
# Generate a dataset and plot it
np.random.... |
123be4722a10778f4a48fecaedcbcdba348329c4 | kiriappeee/morashon | /py/fest2wav.py | 2,888 | 3.5 | 4 | #!/usr/bin/python
#simple (hah) script to invoke festival on a festive xml file and output a .wav
import sys, os
from xml.dom import minidom
cleanup = []
if len(sys.argv) < 3:
print "fest2wav festival.xml output.wav [voice]"
exit()
fout = sys.argv[2]
voice = None
scm = ""
if len(sys.argv) > 3:
voice = sy... |
986c51c23c002250bab6536db2ce03cd2117f385 | claws425/python-challenge | /PyBank/main.py | 3,756 | 4.09375 | 4 | # Your task is to create a Python script that analyzes the records to calculates each of the following:
# The total number of months included in the dataset
# The net total amount of "Profit/Losses" over the entire period
# Calculate the changes in "Profit/Losses" over the entire period, then find the average of those ... |
74c1e76b9b0a93bfee0bf688f77465f2bf6c088e | felineshadow/ichw-1 | /pyassign2/currency.py | 5,678 | 4.1875 | 4 | #!/usr/bin/env python3
"""Module for currency exchange
This module provides several string parsing functions to implement a
simple currency exchange routine using an online currency service.
The primary function in this module is exchange.
__author__ = "XiongJie"
__pkuid__ = "1700011827"
__email__ = "xiongjie1999@p... |
c433375858a75290c98a0c4bd99ac5230b8fa30d | chaidamu519/2048-Game | /merge_function.py | 1,427 | 3.578125 | 4 | """
Merge function for 2048 game.
"""
def merge(line):
"""
Function that merges a single row or column in 2048.
"""
# replace with your code
result_list = [0] * len(line)
find_merge = False
flag_index = []
# merge same element (from left to right)
for dummy_i in range(len(line)... |
0d14096b45b4f0a98f156b35cfbfb576e43a2874 | gengfeng123/learn-python | /test1_1.py | 586 | 3.53125 | 4 | #-*- encoding:utf-8 -*-
######ѧϢ############
#
#ѧţ1403050105
#༶ͨ14_1
###########Ȩƽ###############
'''
##########################
'''
xuehao=raw_input('ѧ:')
name=raw_input(':')
age=input(':')
gs=input('ɼ:')
yy=input('Ӣɼ:')
zz=input('γɼ:')
jq=gs*0.6 + yy*0.3 + zz*0.1
print 'ѧ:',xuehao, ':', name, ':', age
pr... |
b7fb1c5c67eae6c624a86c1a8cb5fb5587bf0a56 | michelle282/DA-FIn-Datacamp-Projects | /m1c1.py | 1,218 | 4.375 | 4 | # Example 1, do not modify!
print(8 / 2)
# Example 2, do not modify!
print(2**2)
# Addition, no print output
print(10 + 2)
# Multiplication, with print output
print(10 * 2)
# Create the variable total and print the total revenue
revenue_1=500
revenue_2=450
revenue_3=625
total = revenue_1 + revenue_2 + revenue_3
print... |
0e8733b7ebcf110f1cef06e3ece47c0bf4828894 | muhtarudinsiregar/codingbat-exercises | /warmup_2/string_times.py | 215 | 3.921875 | 4 | def string_times(str, n):
return str * n
# alternative
# result = ""
# for i in range(n):
# result += result + str
return result
print(string_times("Hi", 2))
print(string_times("Hi", 10))
|
f1fb11adceffaec626bf31e6ec2cb3cdb1c96704 | muhtarudinsiregar/codingbat-exercises | /warmup_1/front_back.py | 175 | 3.78125 | 4 | def front_back(str):
if len(str) > 1:
return str[-1:]+str[1:-1]+str[:1]
return str
print(front_back('ab'))
print(front_back('a'))
print(front_back('code'))
|
66bbde81f29e69de4ffb92a3f49c01d17fe21533 | muhtarudinsiregar/codingbat-exercises | /list-2/has22.py | 303 | 3.859375 | 4 | def has22(nums):
for i in range(0, len(nums)-1):
if nums[i] == 2 and nums[i+1] == 2:
return True
# another answer
# if nums[i:i+2] == [2, 2]:
# return True
return False
print(has22([1, 2, 2]))
print(has22([1, 2, 1, 2]))
print(has22([2, 1, 2]))
|
5fb0c294dd5b040767bab137baeabc4b6a4f21d7 | davidschlachter/PhraseFrequencyAnalysis | /PhraseFreqAnalysis.py | 2,913 | 3.859375 | 4 | #!/usr/bin/env python3
import os, sys, re
"""
The following method was written by Scott Triglia,
posted on Jan 20th, 2013
from http://locallyoptimal.com/blog/2013/01/20/elegant-n-gram-generation-in-python/
Function will compile a list into a sequence of tuples comprised of
the n consecutive elements in the list
"""
... |
0f2597c98a27c96d0feb9f0efe134eacb73dfd93 | jhladka/KURZY | /currency_converter.py | 3,097 | 3.59375 | 4 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
import requests
from requests.exceptions import ConnectionError
import argparse
import json
import sys
def get_input():
"""
Parse and validate input line.
"""
# Parse input line:
parser = argparse.ArgumentParser(description='Currency converter using da... |
01c7d58ca367d40791c51210f49a60a4cb5598f3 | VSZM/Advent_Of_Code | /2019/day2_2.py | 1,014 | 3.609375 | 4 | from typing import List
import sys
from itertools import product
def runProgram(instructions: List[int]):
i = 0
while instructions[i] != 99:
pos = instructions[i + 3]
a = instructions[instructions[i + 1]]
b = instructions[instructions[i + 2]]
if instructions[i] == 1:
... |
26ff0778471ff404e6c9a32d0cccba15da6237eb | poorforever/exercism | /python/rna-transcription/rna_transcription.py | 206 | 3.703125 | 4 | def to_rna(dna):
rna = ''
for n in dna:
if(n == 'G'):
rna+= 'C'
elif(n == 'C'):
rna+= 'G'
elif(n == 'T'):
rna+= 'A'
elif(n == 'A'):
rna+= 'U'
else:
return ''
return rna
|
303aabb32d29c6b018038677db5897c7bf07ad80 | CN-COTER/python_test | /animal.py | 319 | 3.765625 | 4 | class animal():
def __init__(self, name, sex, age):
self.name = name
self.sex = sex
self.age = age
def eat(self, food):
printf(self.name+"eat"+food)
a = animal('cat', 'male', '30')
b = animal('dog', 'male', '20')
c = animal('bird', 'male', '30')
print(a.name, b.name, c.name)
|
dd7ff9e84e398e96655709bffb6e80ce9f08b174 | CN-COTER/python_test | /t015.py | 357 | 3.75 | 4 | class animal():
def __init__(self, name, sex, age):
self.name = name
self.sex = sex
self.age = age
def eat(self, food):
printf(self.name+"eat"+food)
a = animal('chicken', 'female', '11')
b = animal('dog', 'male', '20')
c = animal('bird', 'male', '30')
... |
3e97c250cef9c594132a37ce7e24d3b7a4ef7973 | OmarShehata11/PingPong-Game | /firstGame.py | 3,879 | 3.53125 | 4 | import turtle
import time
import random
wind = turtle.Screen()
wind.title("ping pong game")
wind.bgcolor("black")
wind.setup(width=800, height=700)
wind.tracer(0)
madrb1 = turtle.Turtle()
madrb1.speed(0)
madrb1.shape("square")
madrb1.color("red")
madrb1.penup()
madrb1.goto(-370, 0)
madrb1.shapesize(stretch_wid=5, str... |
5fec29bb1b00398a458c2c81aabcc9acdf914800 | gvrajesh07/Assignment_3.11438 | /Q_1_2_myfilterfunction.py | 126 | 3.609375 | 4 | def is_even(i):
if i % 2 == 0:
return i
evennumbers=[x for x in range(10) if is_even(x)]
evennumbers
|
99ca44f4715181cea45f21038c38bf3ef7d87839 | kritikakurani/InterviewBit | /Trees/BalancedBinaryTree.py | 641 | 3.734375 | 4 | # Definition for a binary tree node
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
# @param A : root node of tree
# @return an integer
def balanced(self, root):
if root == None:
return (True, 0)
... |
298238483e0b978226d66bbd6d377f4eb8e627c3 | hibathecreator/turtle_crossing | /car_manager.py | 1,011 | 3.9375 | 4 | from turtle import Turtle
import random
from time import sleep
COLORS = ["red", "orange", "yellow", "green", "blue", "purple"]
STARTING_MOVE_DISTANCE = 5
MOVE_INCREMENT = 10
class CarManager():
def __init__(self):
self.cars = []
self.counter = 0
self.speed = 10
def create_car(self):
... |
24d3917e3a200eed4ab92a56a831a0d7f32716c4 | adiasija2011/competitive_coding | /binary_search.py | 441 | 3.578125 | 4 | import math
def binarysort(A,v):
last=len(A)-1
mini=0
mid=round(last/2)
#print(mid)
for i in range(0,round(math.log2(last)+1)):
if(A[mid]==v):
return mid
elif(A[mid]<v):
mini=mid
mid=round((last+mid)/2)
else:
last=m... |
b4dba0c87448329a4cbd511c6cb41b921e951693 | hackzwizz/1-10-game | /1-10 game.py | 1,002 | 4.3125 | 4 | # Random number Game By "Andy q" text me for suggestions
# 239-961-7723
# Welcome, here we will learn how to make a random generator game
# First we need to make sure the computer knows to make a random number
import random
# Now we set the range for the generation, in this case 1-10
x = random.randint(... |
3ba7dab4416a04677aa14d10f613df3f5df65553 | abdurrahmanshidiq/fundamental-python | /PYTHON/function,list/marketlagi.py | 882 | 3.796875 | 4 | fruits = ['Apel', 'Anggur', 'Jeruk']
stock = [5, 7, 8]
price = [1000, 15000, 20000]
# fungsi untuk menampilkan semua data
def showData():
if len(fruits) <= 0:
print ("BELUM ADA DATA")
else:
for indeks in range(len(fruits)):
print ("[%d] %s" % (indeks, fruits[indeks]))
# fungsi untu... |
284b475485b4fae99809d00e02e020c53e48f9e8 | abdurrahmanshidiq/fundamental-python | /PYTHON/Solvit/solvit-5.py | 227 | 3.84375 | 4 | text = input('Masukkan kalimat : ')
text1 = text.lower()
huruf = input('Masukkan karakter yang ingin dihitung : ')
huruf1= huruf.lower()
hitung = text1.count(huruf1)
print('Terdapat karakter '+huruf1+' sebanyak '+str(hitung)) |
c50d4039771dc7f72a485da30b4454a8caf3407e | abdurrahmanshidiq/fundamental-python | /PYTHON/Coretan/coretan.py | 4,858 | 3.765625 | 4 | # number = 25
# for i in range(0,40):
# print(i)
# if i is number:
# print(f'angka ditemuka {i}')
# break
# else:
# print(f'angka tidak ditemukan')
# def disemvowel(word):
# List = list(word)
# Vowels = ["a", "e", "i", "o", "u"]
# for letter in List:
# if lette... |
9f7004d58aae16140b0d82b074b679b191d52f08 | abdurrahmanshidiq/fundamental-python | /PYTHON/filter,lambda,dict/scratchpad6.py.py | 990 | 4.15625 | 4 | # geektechstuff – Pig Latin version 2 (Impractical Python Excercise)
ay = 'ay'
way = 'way'
consonant = ('B','C','D','F','G','H','J','K','L','M','N','P','Q','R','S','T','Y','V','X','Z')
vowel = ('A','E','I','O','U')
user_sentence = input('Enter a sentence to translate to Pig Latin: ')
pig_latin_string =''
words = user_... |
0d8554cf9317eea647f9139eccc52015f0ac36e8 | abdurrahmanshidiq/fundamental-python | /PYTHON/function,list/scratchpad2.py | 248 | 3.984375 | 4 |
# listStr = ['A','C','D','B']
# # listStr.sort()
# # print(listStr)
# listStr.sort(reverse=True)
# print(listStr)
#############################
listInt = [9,5,1,7,3]
# listInt.sort()
# print(listInt)
#
listInt.sort(reverse=True)
print(listInt) |
91fa6977074d533223cf108ff546d85706246644 | CodecoolBP20172/pbwp-2nd-tw-pair-programming-exercises-team_18 | /pbwp-2nd-tw-pair-programming-exercises-team_18-master/years/years_module.py | 301 | 3.765625 | 4 | import datetime
def years(age):
old = 100 - int(age) + 2016
return old
def main():
name = input('What is your name?')
age = input("How old are you?")
print("Hello {} you'll be a hundred yeras in {}".format(name, years(age)))
return
if __name__ == '__main__':
main()
|
cb08d4565aa5bad50a8ccf1ba3625d3b3f917562 | allison-casey/MiscProjects | /python/interview_questions.py | 2,230 | 3.828125 | 4 |
def fizz_buzz(iterations):
"""Fizz Buzz with special rules.
Rule 1: digits add to 9 print Fizz
Rule 2: divisible by 5 print Buzz
"""
def get_digits(val):
digits = []
while val:
digits.append(val % 10)
val /= 10
return digits
for i ... |
c3ad6b02d7cbd14a5786657e34c2aa5584ea9a4f | jelloh/learn-face-detection-and-recognition | /tutorials/face-detection.py | 4,095 | 3.671875 | 4 | '''
Chapter 12: Face Detection and Recognition
Detecting a Face
Aileen Benedict
July 9, 2018
'''
# Import the OpenCV library
import cv2
# Display OpenCV Version :') Need at least 3.1.0
print ('OpenCV Version: ', cv2.__version__)
# Error solution :')
# https://stackoverflow.com/questions/30508922/error-215-empty-in-f... |
fab90575e945f81cc72e44a79a8c8d5d2dd29d8d | alviandk/tpt1 | /source code python/pangkatsemp.py | 219 | 3.703125 | 4 | def pangkat(x,y):
if y==0:
return 1
else
return x * pangkat(x,y-1)
x=input('masukkan bilangan :')
y=input('masukkan pangkat :')
print x,' pangkat ', y,' = ',pangkat(x,y)
|
8127f2f21cc30355522ed08570948d813c30196f | alviandk/tpt1 | /source code python/class4.py | 203 | 3.53125 | 4 | class oop:
def __init__(self):
print 'contructor class oop'
class oop1(oop):
def __init__(self):
print 'constructor class oop1'
oop.__init__(self)
anak=oop1()
|
c170c3ba0da00651e79b857407748b3f6b58d857 | IsseBisse/adventcode19 | /4/SecureContainer.py | 1,212 | 3.828125 | 4 | def has_double(number):
number_string = str(number)
ok = False
for i, char in enumerate(number_string[:-1]):
ok |= char == number_string[i+1]
return ok
def never_lower(number):
number_string = str(number)
ok = True
for i, char in enumerate(number_string[:-1]):
ok &= char <= number_string[i+1]
retur... |
e9628bd96f4b33de47dba0f56a593b23b1f2a942 | nikolaykochkin/python_stepic_trainer | /5.13 Length statistic.py | 535 | 3.609375 | 4 | text = 'Beautiful is better than ugly. Explicit is better than implicit.'
lst = list(map(lambda x: len(x), text.split(' ')))
'''dic = {i: lst.count(i) for i in sorted(set(lst))} # Через генератор словаря
for line in dic.items():
print(line[0], line[1], sep=': ')
'''
lst.sort()
from itertools import groupby
for key... |
2bdb3dfb5318a4cd4eed5df3eb32bcf44d79709f | jackwotherspoon/CompetitiveLearning | /CompLearning.py | 11,156 | 3.546875 | 4 | # Author:Jack Wotherspoon
# Date Created: March 1st, 2019
#import dependencies
from random import random
from csv import reader
import numpy as np
import random
import copy
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
# Load a CSV file
def load_csv(filename):
dataset = list()
with o... |
463aa2305f98a20e566095d1a0f3046bb01c66fd | MarianoCol/um-programacion-i-2020 | /57031-porollan-santiago/tp1/ej10.py | 327 | 3.875 | 4 |
m = {1: "enero", 2: "febrero", 3: "marzo", 4: "abril", 5: "mayo", 6: "junio" ,
7:"julio" ,8:"agosto" ,9:"septiembre", 10: "octubre", 11: "noviembre", 12: "diciembre"}
if __name__ == "__main__":
dia = input("dia: ")
mes = input("mes: ")
año = input("año: ")
print(dia, " de ", m[int(mes)], " de ", ... |
c82568ba08adde215c3729cfbc30c0ef3f790d56 | MarianoCol/um-programacion-i-2020 | /58164-von-Kesselstatt-Philipp/TP1/Objetos/ejercicio11.py | 482 | 3.515625 | 4 | class Curso():
def __init__(self, materias):
self.materias = materias
def getTotal(self):
return sum(self.materias.values())/len(self.materias)
def getMaterias(self):
return self.materias
ejercicio11 = Curso({"Matemáticas": 6, "Física": 4, "Química": 5})
for item in ejercicio11.... |
73b676738c208e56afad7f8e51b4397d444df3d3 | MarianoCol/um-programacion-i-2020 | /58164-von-Kesselstatt-Philipp/TP1/ejercicio9.py | 385 | 4 | 4 | persona = {"nombre": None,
"edad": None,
"dirección": None,
"teléfono": None}
for item in persona:
persona[item] = input("Cual es su " + item + "? ")
print(persona["nombre"] +
" tiene " +
persona["edad"] +
" años, vive en " +
persona["dirección"] +
" ... |
3da65b89d953edde544f083cd3700dfdf0ab3728 | MarianoCol/um-programacion-i-2020 | /58164-von-Kesselstatt-Philipp/TP1/Objetos/ejercicio13.py | 371 | 3.6875 | 4 | import random
class RandomAverage():
def generate(self):
self.randList = [random.randint(1, 10) for n in range(10)]
return self.randList
def average(self):
return sum(self.randList)/len(self.randList)
"""
ejercicio13 = RandomAverage()
for item in ejercicio13.generate():
print(i... |
d533d013c5c96f0b95407a313393944b42aa778c | MarianoCol/um-programacion-i-2020 | /57031-porollan-santiago/tp1/ej6.py | 407 | 3.765625 | 4 |
def es_primo(num):
for x in range(2, num):
if num % x == 0:
return False
return True
if __name__ == "__main__":
while 1:
try:
num = int(input("numero: "))
except:
print("ingrese numero")
else:
break
if es_primo(num)... |
636cb6f9faa1a1f26ced1940a4341944d9b86ca4 | MarianoCol/um-programacion-i-2020 | /59045-Colman,Mariano/TPN°1-59045-Colman,Mariano/ej3.py | 393 | 3.640625 | 4 | class Impares():
def __init__(self):
self.l=[]
def lista (self,n):
if n < 1:
return print("Ingrese un numero entero positivo")
else:
for a in range(1,n+1,2):
self.l.append(a)
def main():
impares = Impares()
n=int(input("Ingrese un num... |
5d9f960ad2ab2aa1518e6386181b3a828034c3fa | MarianoCol/um-programacion-i-2020 | /57031-porollan-santiago/tp1/ej8.py | 654 | 3.84375 | 4 | class Nota():
def __init__(self, nota=None, asignatura=None):
self.nota = nota
self.asignatura = asignatura
self.next = None
if __name__ == "__main__":
alumn = Nota()
first = alumn
while 1:
print("detener con stop")
asignatura = input("asignatura: ")
if a... |
32d32fe86b9f94bb802c80c33bd6cc5d0e239b0c | Ajshannon/numseq | /geo.py | 157 | 3.5625 | 4 | def square(n):
return n*n
def triangle(n):
x = .5
for j in range(n):
x = x + .5
return (n * x)
def cube(n):
return n * n * n
|
4c99f66e52dd327b29e097eb40567fee0232107c | KelseyXu229/Show-me-the-Datastructure | /problem_1.py | 1,595 | 3.703125 | 4 | # -*- coding: utf-8 -*-
class LRU_Cache(object):
def __init__(self, capacity):
# Initialize class variables
self._size = capacity
self._cache = {}
self._keys = []
def get(self, key):
# Retrieve item from provided key. Return -1 if nonexistent.
if key in self._... |
b77a0ae4cb8845c222ffa84e41199b39f33202b5 | berlioz458/python_l_S | /path.py | 192 | 3.546875 | 4 | x = []
a = int(input())
for i in range(1, a + 1):
count = 1
while (count <= i) & (len(x) < a):
x.append(i)
count += 1
for i in range(len(x)):
print(x[i], end=" ")
|
c638631954deefca9baf03cd4a805deb65bb15d5 | schlangguru/advent_of_code_2020 | /day11/simulation.py | 6,265 | 3.828125 | 4 | from typing import List, Tuple
import itertools
OCCUPIED_SEAT = '#'
EMPTY_SEAT = 'L'
FLOOR = '.'
class Seat():
allowed_types = (OCCUPIED_SEAT, EMPTY_SEAT)
def __init__(self, type: chr):
if type not in self.allowed_types:
raise Exception(f"Type {type} not allowed.")
self.is_occup... |
1bf861979dc2544a93bc837be316500adaba345f | schlangguru/advent_of_code_2020 | /day13/bus.py | 447 | 3.59375 | 4 | from typing import List, Generator
import itertools
import math
class Bus():
def __init__(self, id: int):
self.id = id
def departure_times(self) -> Generator[int, None, None]:
"""
Infinite generator for bus departure times.
"""
for i in itertools.count(0, 1):
... |
3c35f51374130a1bd26751e50a2d629e80e13c0e | ishanpatel27/Python-Practice-Codes | /file_remove.py | 579 | 3.859375 | 4 | #__author__ = "ISHAN PATEL"
#__version__ = "3.5.2"
#__email__ = "ishanpatel415@gmail.com"
# Program for Room_number ( file character assignment using user input)
file1=open('test_read.txt','r') #opening the file_1
file2=open('test_new.txt','w') #opening the file_2
no=int(input("Enter the pos... |
7791e26a20b178b5a0c0c8f28eeaae357b924cb4 | bentheiii/Increment | /increment/inc_state.py | 991 | 3.78125 | 4 | # change = (after/before)-1
# after = (change + 1)*before
# before = after/(change + 1)
from increment.__util__ import parse_float
# the calc functions return a tuple of text to display and an optional stylesheet to apply
def num_format(n):
return format(n, ',.2f'), None
def calc_before(before, after, change)... |
bbfbe183b26a5c0432100867ac1aee654e165aac | KETULPADARIYA/Computing-in-Python | /5.2 Control Structures/4 Functions/10 SnowedIn.py | 1,779 | 4.40625 | 4 | #Write a function called snowed_in that will determine
#whether school is closed based on the weather and
#temperature. We'll pretend the school is in Georgia, where
#a little snow or sub-freezing temperatures are enough to
#close down schools!
#
#The function should take three parameters:
#
# - temperature, a float
# ... |
c6f48b49a90720adef5df181e8a665c4eff9e9b7 | KETULPADARIYA/Computing-in-Python | /5.2 Control Structures/3 loops/5 DebugFectorial.py | 383 | 4.46875 | 4 | num = 5
#You may modify the lines of code above, but don't move them!
#When you Submit your code, we'll change these lines to
#assign different values to the variables.
#
#Write some code below that will print the factorial of num.
#Remember to remove any debug statements when you're ready
#to submit for credit.
resu... |
aa6a6a40981bfa9ee93d0781074e438b27ff6530 | KETULPADARIYA/Computing-in-Python | /5.2 Control Structures/5 Error Handling/2 TryExcep2.py | 600 | 4.09375 | 4 | mystery_value = 0
#You may modify the lines of code above, but don't move them!
#When you Submit your code, we'll change these lines to
#assign different values to the variables.
#Create a program that divides 10 by mystery_value and prints
#the result. In the case that mystery_value is equal to 0,
#print "Not possib... |
d3674ec58b01128ff232c045aacd9356acbc3733 | KETULPADARIYA/Computing-in-Python | /5.2 Control Structures/4 Functions/11 HideAndSeek.py | 575 | 4.21875 | 4 | #Write a function called hide_and_seek. The function should
#have no parameters and return no value; instead, when
#called, it should just print the numbers from 1 through 10,
#follow by the text "Ready or not, here I come!". Each
#number and the message at the end should be on its own
#line.
#
#Then, call the function... |
70ad08aea5712181a1f9ae420284ef85f3a936b4 | KETULPADARIYA/Computing-in-Python | /5.3 Data Strucutres/5 Dictionaries/11 PokemonPower.py | 2,215 | 3.984375 | 4 | #In the Pokemon video game series, every Pokemon has six
#stats: HP, Attack, Defense, Special Attack, Special Defense,
#and Speed.
#
#Write a function called total_stats that will take as input
#a list of dictionaries. Each dictionary will have seven
#key-value pairs:
#
# - name: a Pokemon's name
# - hp, attack, defens... |
d84aac01fc79074f2dd61b612780fc5016c860d9 | KETULPADARIYA/Computing-in-Python | /5.1 Fundamentals and Procedural Programming/Chapeter 1/14 PrintsInYourPrints.py | 601 | 4.3125 | 4 | #in several places throughout the code's execution. Fix the
#code so that it behaves as intended: it should print the
#quotient, remainder, then the message, "We're done!"
#
#HINT: There are a couple ways to do this, and some of those
#ways might be a little advanced right now. Note that 17 // 6
#will correctly calcula... |
cb8d357c515e15527cb13935897ce10ac9578fe3 | KETULPADARIYA/Computing-in-Python | /5.2 Control Structures/3 loops/12 ListOfStrings.py | 1,125 | 4.375 | 4 | mystery_list = ["Taylor Swift", "Twenty Two", "Georgia Tech"]
#Above is a list of strings. Don't worry if this syntax is a
#little unfamiliar, we'll talk you through it and then cover
#it more in chapter 4.3.
#Write some code that will count the number of instances of
#the letter 't' in the list of strings. Count both ... |
065bded7c2a0fbbf219319b3868968000b4b7b05 | KETULPADARIYA/Computing-in-Python | /5.2 Control Structures/4 Functions/1 PrintMathSymbol.py | 1,442 | 4.78125 | 5 | #When writing out mathematical equations for younger
#audiences, we usually want to use the traditional division
#and multiplication symbols, ÷ and ×, instead of slashes and
#asterisks. These keys aren't on the keyboard, though. So,
#let's write functions that will print them.
#
#First, write two functions: one called ... |
9fa7889410173eb9b8602ced3b392042d75f44d7 | KETULPADARIYA/Computing-in-Python | /5.2 Control Structures/2 Conditional/6 welcomToMoes.py | 1,093 | 4.40625 | 4 | steak = False
pork = True
guacamole = False
queso = False
#You may modify the lines of code above, but don't move them!
#When you Submit your code, we'll change these lines to
#assign different values to the variables.
#
#Imagine you're writing code for a cash register at a
#restaurant. This restaurant serves burritoe... |
3122771cc89537a47e20b96df637cbfd26dbeb46 | KETULPADARIYA/Computing-in-Python | /5.2 Control Structures/5 Error Handling/9 DividingMysteryValue.py | 899 | 4.375 | 4 | mystery_value = "cat"
#You may modify the lines of code above, but don't move them!
#When you Submit your code, we'll change these lines to
#assign different values to the variables.
#Write a program that divides mystery_value by mystery_value
#and prints the result. If that operation results in an
#error, divide mys... |
95c12e88137c43aef3466f06da7a66c63f637061 | KETULPADARIYA/Computing-in-Python | /5.1 Fundamentals and Procedural Programming/Chapeter 2.2 Logical Operator/3_FiveItemList.py | 791 | 4.65625 | 5 | list_of_fruits = ["grape", "orange", "banana", "kiwi", "pear"]
search_fruit = "kiwi"
#You may modify the lines of code above, but don't move them!
#When you Submit your code, we'll change these lines to
#assign different values to the variables.
#
#We'll learn more about lists in chapter 4.3, but you can
#change the i... |
2b16afdfbf57412f4e20a3fdb0b1e6296f7a4208 | KETULPADARIYA/Computing-in-Python | /5.2 Control Structures/5 Error Handling/7 Getinteger2.py | 1,324 | 4.59375 | 5 | #This exercise is identical to the previous exercise,
#except that instead of printing "Cannot convert!" when my_var
#cannot be converted to an integer, you should instead return
#the error message that results. For a reminder of how to
#access the error message in the except block, check out
#3.5.3, specifically Catch... |
25722446473e218a997851a1269d3b0edabf990b | KETULPADARIYA/Computing-in-Python | /5.2 Control Structures/2 Conditional/8 outFits.py | 658 | 4.5 | 4 | sunny = True
windy = False
#You may modify the lines of code above, but don't move them!
#When you Submit your code, we'll change these lines to
#assign different values to the variables.
#Below, we've gone ahead and written some code that uses a
#conditional to print a message based on the variables above.
#Revise t... |
6ed39fc398d6a9d7993737a2e676ff3117082cce | KETULPADARIYA/Computing-in-Python | /5.2 Control Structures/2 Conditional/11 Valentines.py | 1,213 | 4.0625 | 4 | years = 2
months = 5
days = 24
#Ever been at a loss for what to do for your significant
#other for Valentine's Day? Let's right some code to generate
#a gift recommendation!
#
#The variables above give the length of the relationship in
#number of years, months, and days. Add some code below to
#print a gift recommendat... |
f6b2092b4da24f097f64b9eec15fc2f4f63108cb | KETULPADARIYA/Computing-in-Python | /5.2 Control Structures/Exam/4 PokemonExperience.py | 1,562 | 4.28125 | 4 | #Imagine you're playing a game in which every action you
#take grants you some number of experience points. There is
#an item called a Lucky Egg that, when used, doubles the
#number of experience points you earn. The company behind
#the game also runs occasional events where they increase
#how many experience points yo... |
d3fe191fc9caf3a98533786d12642d8cb306263f | KETULPADARIYA/Computing-in-Python | /5.2 Control Structures/3 loops/8 EveryThird.py | 564 | 4.3125 | 4 | mystery_int = 50
#You may modify the lines of code above, but don't move them!
#When you Submit your code, we'll change these lines to
#assign different values to the variables.
#Write a for loop that prints every third number from 1 to
#mystery_int inclusive (meaning that if mystery_int is 7, it
#prints 1, 4, and 7)... |
2e4c00f06df06eda6623c17a4b48a2455ee6fcd3 | JubindraKc/python_assignment_dec8 | /finding_acceleration.py | 130 | 3.515625 | 4 | print("v = u + at")
def formula(v, u, t):
return (v - u) / t
print("acceleration is {} m/s" .format(formula(25, 0, 10)))
|
f4b8680ffdf5dd1deb4a323f9c7c83896d2df5cd | JustEmpty/algorithms | /problems/is_symmetry.py | 583 | 3.921875 | 4 | # Time complexity: O(n)
#
# Space complexity: O(n)
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def is_symmetry1(root):
if not root:
return True
q = []
q.append([root.left, root.right])
while q:
t1, t2 = q.pop(0)
... |
f2175ea855cf3c5a1317256a307647e3bfa80eb4 | 1459292960/chapter6 | /6-5.py | 321 | 3.96875 | 4 | river_country={'nile':'egypt','yangtse':'China',
'Panama canal':'panama'}
for river,country in river_country.items():
print("The %s runs through %s"%(river.title(),country.title()))
for river in set(river_country.keys()):
print(river)
for country in set(river_country.values()):
print(country)... |
6a77ab678956098124e05210cba49f17994a6d86 | TypAnna/GruProgDD1331 | /Övning6/uppg2Memory.py | 219 | 3.609375 | 4 | def funB(a, b):
a[1]= "hej"
b = ("katt", "lo")
def funA():
a = [[1, 2], [3, 4]]
b = (5, 6)
funB(a, b)
#what does the memory look like here?
print("this is p", a)
print("this is q", b)
funA()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.