blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
287bc90d179ddc0c048f9a300937b49cc4b2f81a | DamienAllonsius/TaxiProblem | /environment.py | 4,269 | 3.703125 | 4 | """
This class is the environment in which the agent (here the taxi) evolves.
It is a 2D-discrete grid, which features (geometry, location of the passenger) are written in the file domain/example_domain
"""
import numpy as np
from variables import *
class Environment(object):
def __init__(self):
"""
... |
09510c8f5ec4ff6dce0633fa8fa17df7db9039e4 | maykim51/leetcode | /138.copy-list-with-random-pointer.py | 1,979 | 3.984375 | 4 | """
20.03.11
1. 기존 노드 : 신규 노드 형태의 딕셔너리를 만들어서 제작. 새로운 노드를 만났을 때만 deep copy 하는 방법. O(N)
2. 사이사이에 끼워넣어서 weave 하기 (next, random 등..) (O(N) space만 O(1))
# Definition for a Node.
class Node:
def __init__(self, x: int, next: 'Node' = None, random: 'Node' = None):
self.val = int(x)
self.next = next
... |
f06c6d6020c1467d5a797052189c4f04af479c56 | maykim51/leetcode | /kakao/2020_02.py | 890 | 3.640625 | 4 | '''
잘 풀었고, 맞췄음. 단 시간이 좀 오래 걸렸음.
'''
def solution(p):
answer = ''
if p == '':
return ''
def isRight(c):
cnt = 0
for i in range(len(c)):
cnt = cnt + 1 if c[i] == '(' else cnt - 1
if cnt < 0: return False
return True
def isBalanced(s): return s.count... |
62bc5d7e42b111b28ecd0dba82ae5a5259e122f9 | Nikoletazl/Basics-Python | /cond_stat_add_more/multiply_by_2.py | 235 | 4.0625 | 4 | n = int(input())
for i in range(0, n, n + 1):
current_number = float(input())
if current_number > 0:
positive = current_number * 2
print(f"Result: {positive:2f}")
if current_number < 0:
print("Negative number!")
|
0e3d735dc6703650a300b1085fa0aa9b90c69804 | Nikoletazl/Basics-Python | /exams_2020/cat_walking.py | 425 | 4.09375 | 4 | min_per_day = int(input())
count_walks = int(input())
calories = int(input())
total_min = min_per_day * count_walks
total_calories = total_min * 5
half = 0.5 * calories
if total_calories >= half:
print(f"Yes, the walk for your cat is enough. Burned calories per day: {total_calories}.")
elif total_calories <... |
6baa8d56b8eeae92cc1d6b98aa550399926b7294 | Nikoletazl/Basics-Python | /exams_2020/montain_run.py | 454 | 4.09375 | 4 | record = float(input())
distance = float(input())
time = float(input())
needed_time = 0
import math
goal_time = distance * time
sec = math.floor(distance / 50)
slowing = sec * 30
total_time = goal_time + slowing
if record < total_time or record == total_time:
needed_time = total_time - record
print(f... |
c7328c342c854e37e194adaf431047e01ae05dc0 | Nikoletazl/Basics-Python | /exams_2020/supplies_school.py | 432 | 3.640625 | 4 | pens = 5.80
markers = 7.20
detergent = 1.20
count_pens = int(input())
count_markers = int(input())
derergent_liters = float(input())
percent_discount = int(input())
price_pens = count_pens * pens
price_markers = count_markers * markers
price_detergent = derergent_liters * detergent
sum = price_pens + price_ma... |
381b1d15b74c9fa5f83ff7be8a67e6ad72fe897f | Nikoletazl/Basics-Python | /excersice/literature.py | 172 | 3.671875 | 4 | numbers_pages = int(input())
pages_per_hour = int(input())
days = int(input())
time = numbers_pages / pages_per_hour
hours_per_day = time / days
print(hours_per_day)
|
46e4dede8118d63475e50ea993346cec741225d4 | Nikoletazl/Basics-Python | /additional/vegetables.py | 242 | 3.75 | 4 | kg_vegetables = float(input())
kg_fruits = float(input())
total_vegetables = int(input())
total_fruits = int(input())
everything = kg_vegetables * total_vegetables + kg_fruits * total_fruits
euro = everything / 1.94
print("%.2f" % euro) |
f2c9433a5c7e8b1aee961c6c93599c79dcd50440 | Nikoletazl/Basics-Python | /cond_stat_add_more/car.py | 649 | 3.734375 | 4 | budget = float(input())
season = input()
if budget <= 100:
category = "Economy class"
if season == "Summer":
type_car = "Cabrio"
price = 0.35 * budget
if season == "Winter":
type_car = "Jeep"
price = 0.65 * budget
if 100 < budget <= 500:
category = "Compact cla... |
3db082babce0ec390b2b039178a3f5e6a18ba291 | Nikoletazl/Basics-Python | /exam_march_2020/balls.py | 1,020 | 3.875 | 4 | count_balls = int(input())
points = 0
count_red = 0
count_yellow = 0
count_orange = 0
count_white = 0
count_black = 0
count_others = 0
total_point = 0
import math
for i in range(count_balls):
colours = input()
if colours == "red":
points += 5
count_red += 1
elif colours == "or... |
80e36c03b84d070d513b8f9486e7b4ae838512e5 | Nikoletazl/Basics-Python | /while_exc/holiday.py | 629 | 3.828125 | 4 | need_money = float(input())
current_money = float(input())
count_spend_days = 0
count_days = 0
while current_money < need_money:
actions = input()
count_days += 1
sum = float(input())
if actions == "spend":
count_spend_days += 1
current_money -= sum
if current_money < ... |
b73e88c76917adbfd244a6e07cf9a1d713e6e6e3 | Nikoletazl/Basics-Python | /exam_may_2019/vet_parking.py | 527 | 3.953125 | 4 | count_days = int(input())
count_hours_per_day = int(input())
current_tax = 0
total_tax = 0
for day in range(1, count_days + 1):
for hour in range(1, count_hours_per_day + 1):
if day % 2 == 0 and hour % 2 != 0:
tax = 2.5
elif day % 2 != 0 and hour % 2 == 0:
tax = 1.25... |
3d4f3b282ba61f5227587f8093814f7960f749a5 | Nikoletazl/Basics-Python | /while_more/average_number.py | 208 | 3.9375 | 4 | n = int(input())
number = 0
count = 0
average = 0
for i in range(n):
current_number = int(input())
number += current_number
count += 1
average = number / count
print(f"{average:.2f}") |
f637ba41b3561f04679e3b7b61a867af719d6f3c | Nikoletazl/Basics-Python | /cond_stat_add/transport.py | 640 | 3.734375 | 4 | n = int(input())
price = (input())
if n < 20 and price == "day":
price_taxi = 0.70 + (n * 0.79)
print(f"{price_taxi:.2f}")
elif n < 20 and price == "night":
price_taxi = 0.70 + (n * 0.90)
print(f"{price_taxi:.2f}")
elif n >= 20 and n < 100 and price == "day":
price_bus = n * 0.09
print... |
cff0cb5a2fafebc92af1f3393309e760a5fcfde5 | Nikoletazl/Basics-Python | /exams_2020/care_of_puppy.py | 315 | 3.828125 | 4 | food = int(input()) * 1000
day_food = input()
total = 0
while day_food != "Adopted":
total += int(day_food)
day_food = input()
if total <= food:
print(f"Food is enough! Leftovers: {food - total} grams.")
else:
print(f"Food is no"
f"t enough. You need {total - food} grams more.") |
78fa257e244e655cdf1180422fd444bbfb61e4b1 | eptune/smepycode | /test.py | 408 | 3.921875 | 4 | print "Hello World"
print "The quick brown fox jumped over the lazy dog"
faren = -1000
max_attempts = 6
attempts = 0
while faren < 100 and (attempts < max_attempts):
newfaren = float(raw_input("Enter Temp"))
if newfaren > faren:
print "Hotter"
elif newfaren < faren:
print "Colder"
els... |
b411f979eba5dfd88de7c913816aa090dfe92815 | rajeshsharma98/Machine_Learning | /Regression/1.Linear_Regression/Simple_LR.py | 1,278 | 3.90625 | 4 | #To predict pice of house according to the living area(square_feet)
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
#Importing ther data
dataset = pd.read_csv('kc_house_data.csv')
X = np.array(dataset['sqft_living']).reshape(-1, 1)
y = np.array(dataset['price'])
# Splitting the dataset into the... |
aa9d2a532455ff7366016a11abcc8fb193157837 | yijxiang/string_algorithms | /string_algorithms/trie.py | 1,107 | 3.5 | 4 | class TrieNode():
def __init__(self, is_word=False, *args, **kwargs):
self.children = dict()
self.is_word = is_word
def next(self, char):
return self.children.get(char, None)
def add(self, char, is_word=False, *args, **kwargs):
if char not in self.children:
self... |
00c26c8609e8149cb43d11345218c31ce8bbffef | imx-lk/SP_Online_PY210 | /students/imx-lk/lesson03/mailroom_pt1.py | 7,322 | 4.25 | 4 | #!/usr/bin/env python3
#The original list of donors will sit outside the main function because if it stays inside the fucntion it will replace the names appended in thankyou_new_donor
donor_list = [['Damien Leake', 1000, 3000, 500], ['Andrew Foreman', 375, 2900], ['David Altman', 20, 30000, 54678.50], ['Alex Haldin', 1... |
08a26516aeb57ed8a08ce553dc68d4191f325766 | vivian-ng/snippets | /calc_attendance.py | 7,589 | 4.09375 | 4 | '''
Calculate attendance (working hours?) in a month.
To use:
- Create a StaffRecord to hold the staff's attendance.
- Fill the StaffRecord with timestamps for the staff.
Timestamps should be records of date and time, and either "IN" or "OUT".
- Call@the calc_staff_month_time() function with the required para... |
08436636a21cfc4439389f9a9855c8017978f83d | alexiswl/metagenomic_converter_scripts | /value_counts.py | 488 | 3.640625 | 4 | #!/usr/bin/env python
"""
This picks uo a file with a single column list.
Converts this list into a Series type and outputs a summary.
"""
import pandas
import sys
# Open file and generate list from each line
file_name = sys.argv[1]
file_h = open(file_name, 'r')
# series, list on lines in file.
# Last line is alway... |
a4ff3c57738f3231ccd537dc945e82e5e07f747f | league3236/MyNewAlgorithmStudy | /num_sum.py | 605 | 3.84375 | 4 | # n번째 삼각수(triangle number)는 자연수 11부터 n까지의 합입니다.
# 파라미터로 정수값 n을 받고 nn번째 삼각수를 리턴해주는 재귀 함수 triangle_number를 쓰세요. nn은 11 이상의 자연수라고 가정합시다.
# 함수 안에 반복문은 쓰면 안됩니다!
# 1부터 n까지의 합을 리턴
def triangle_number(n):
if n==1:
return 1
else:
return triangle_number(n-1)+n
# 코드를 입력하세요
# 테스트: triangle_number(1... |
4e1d93858cf302e85e74c93058f51df1833e0408 | league3236/MyNewAlgorithmStudy | /palindrome.py | 357 | 3.921875 | 4 | def is_palindrome(word):
# 코드를 입력하세요.
l = len(word)
for i in range(l):
if word[l-i-1] != word[i]:
return "false"
return "true"
# 테스트
print(is_palindrome("stars"))
print(is_palindrome("stars"))
print(is_palindrome("토마토"))
print(is_palindrome("kayak"))
print(is_palindrome(... |
5ce2b8bca4924208964fc348aeea9e4cf875ae14 | mariano-mora/holistic_simulations | /coordinate_game_opengl.py | 2,673 | 3.5 | 4 | import random
from OpenGL.GL import *
from OpenGL.GLUT import *
from OpenGL.GLU import *
import click
from environment import RandomInitializer, Cell, GridEnvironment
'''
A script to draw an environment in which agents interact
'''
WIDTH=340
HEIGHT=340
grid_env = 0
def create_environment(n_rows=8, n_columns=8)... |
6782d2a3bc938626cc6fd4882c4b9fab44573620 | cenalulu/python_euler_solver | /014/solution.py | 1,318 | 4.03125 | 4 | # encoding: utf8
"""
The following iterative sequence is defined for the set of positive integers:
n → n/2 (n is even)
n → 3n + 1 (n is odd)
Using the rule above and starting with 13, we generate the following sequence:
13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1
It can be seen that this sequence (starting at 13 and ... |
532dbe58139d514c1821828cf219d6fe76918108 | cenalulu/python_euler_solver | /049/solution.py | 1,342 | 3.703125 | 4 | #! encoding: utf8
from profile_decorate import profile
from pyprimes import primes_below, isprime
"""
The arithmetic sequence, 1487, 4817, 8147, in which each of the terms increases by 3330,
is unusual in two ways: (i) each of the three terms are prime, and,
(ii) each of the 4-digit numbers are permutations of one ... |
57526053390dc11dbb888028653134b9352dc976 | cenalulu/python_euler_solver | /041/solution.py | 864 | 3.984375 | 4 | #! encoding: utf8
from profile_decorate import profile
from pyprimes import isprime
from itertools import permutations
"""
We shall say that an n-digit number is pandigital if it
makes use of all the digits 1 to n exactly once.
For example, 2143 is a 4-digit pandigital and is also prime.
What is the largest n-digit p... |
a17563301d8d1da87834a98a2e1135820ca275e6 | cenalulu/python_euler_solver | /063/solution.py | 882 | 4.09375 | 4 | #! encoding: utf8
from profile_decorate import profile
from itertools import count
"""
The 5-digit number, 16807=75, is also a fifth power. Similarly,
the 9-digit number, 134217728=89, is a ninth power.
How many n-digit positive integers exist which are also an nth power?
"""
def find_max_n():
for n in count(1... |
8de3eb98f6c19b2217007a499cf0ac441f0c0c44 | cenalulu/python_euler_solver | /060/solution.py | 3,163 | 3.71875 | 4 | #! encoding: utf8
from profile_decorate import profile
from pyprimes import primes, isprime
from itertools import combinations
from copy import copy
"""
The primes 3, 7, 109, and 673, are quite remarkable. By taking any two primes and concatenating them in any
order the result will always be prime. For example, taking... |
88b4fd1a27bcf35d10494eb136199ee977916529 | cenalulu/python_euler_solver | /030/solution.py | 1,205 | 3.71875 | 4 | from profile_decorate import profile
from itertools import count
"""
Surprisingly there are only three numbers that can be written as the sum of fourth powers of their digits:
1634 = 14 + 64 + 34 + 44
8208 = 84 + 24 + 04 + 84
9474 = 94 + 44 + 74 + 44
As 1 = 14 is not a sum it is not included.
The sum of these number... |
3122f29f535cd5d6c12924b42ac2be7c9c394d0a | cenalulu/python_euler_solver | /040/solution.py | 972 | 3.875 | 4 | #! encoding: utf8
from profile_decorate import profile
from itertools import count
"""
An irrational decimal fraction is created by concatenating the positive integers:
0.123456789101112131415161718192021...
It can be seen that the 12th digit of the fractional part is 1.
If dn represents the nth digit of the fracti... |
287a9618c556706b752ca3dd70d0b481f566752f | PaulDeM/Python | /rhombus.py | 414 | 3.828125 | 4 | def print_stars(stars, diagonal):
spaces_counter = diagonal // 2 - stars
stars_counter = diagonal % 2 + 2 * stars
print(' ' * spaces_counter, '*' * stars_counter)
def draw_rhombus():
diagonal = 11
stars = 0
while stars < diagonal // 2:
print_stars(stars, diagonal)
stars += 1
... |
7778dff5d30424e4f1b98c98fdddd1642f86dfe9 | fangyuandoit/PythonLearnDemo | /菜鸟教程/Python3_05列表.py | 2,271 | 4.3125 | 4 | '''
序列是Python中最基本的数据结构。序列中的每个元素都分配一个数字 - 它的位置,或索引,第一个索引是0,第二个索引是1,依此类推。
Python有6个序列的内置类型,但最常见的是列表和元组。
序列都可以进行的操作包括索引,切片,加,乘,检查成员。
此外,Python已经内置确定序列的长度以及确定最大和最小的元素的方法。
列表是最常用的Python数据类型,它可以作为一个方括号内的逗号分隔值出现。
列表的数据项不需要具有相同的类型
'''
list1 = ['Google', 'Runoob', 1997, 2000];
list2 = [1, 2, 3, 4, 5 ];
list3 = ["a", "b", "c", "... |
f9f5e46bb8b7342cb97deccfcbea3612880a7626 | fangyuandoit/PythonLearnDemo | /网上到处找的爬虫教学/百度/百度贴吧.py | 872 | 3.609375 | 4 |
#爬取java吧的前几页页帖子标题
import re
import requests
urls =[]
headers={
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36"
}
def addUrls(urls):
# url ="http://tieba.baidu.com/f?kw=java&ie=utf-8&pn=100"
for i in range(0,100,50... |
75c5dc339c8eed8d9a6ee40e9add9fdae556f733 | fangyuandoit/PythonLearnDemo | /菜鸟教程/Python3_04字符串.py | 6,811 | 4.28125 | 4 | '''
字符串是 Python 中最常用的数据类型。我们可以使用引号( ' 或 " )来创建字符串。
创建字符串很简单,只要为变量分配一个值即可。例如:
'''
var1 = 'Hello World!'
var2 = "Runoob"
# 访问子字符串,可以使用方括号来截取字符串,如下实例:
print("var1[0]: ", var1[0])
print("var2[1:5]: ", var2[1:5])
'''
Python字符串运算符
下表实例变量a值为字符串 "Hello",b变量值为 "Python":
操作符 描述 实例
+ 字符串连接 a + b 输出结果: HelloPython
* 重复输出字符串 ... |
b92e27dd3e9c85415443cc2daf15fa71cc28e608 | Bobobert/aflow | /flow/envs/multiagent/V2V.py | 4,720 | 3.5625 | 4 | """Environment used to train vehicles to improve traffic on a highway."""
import numpy as np
from gym.spaces.box import Box
from gym.spaces.discrete import Discrete
from gym.spaces.tuple import Tuple
from flow.core.rewards import desired_velocity
from flow.envs.multiagent.base import MultiEnv
# Aditional paramaters fo... |
d14c430062d3870ba60631c92b2fcd5ce551d487 | k-preface/python-beginner | /NumberGuessingGame.py | 637 | 4.09375 | 4 | import random
win = 0
tries = 1
computer_number = random.randint(1,20)
while tries <=3:
user_number = int(input("Enter a number from 1 to 20: "))
if user_number == computer_number:
print("Congratulations! You won the lottery. Contact us to claim your prize.")
win = 1
break
... |
10d3774feb55b2166100ed6ed1e3a1adf53fd388 | DanielDavid48/Exercicios-PY | /ex48.py | 361 | 3.8125 | 4 |
print('\033[32mBem vindo!\033[m')
primeiro_termo = int(input('Insira o comeco do intervalo: '))
segundo_termo = int(input('Insira o final do intervalo: '))
s = 0
cont = 0
for x in range(primeiro_termo, segundo_termo, 2):
if x % 3 == 0:
cont = cont + 1
s += x
print(f'A soma dos {cont} va... |
7a3748257ae3122ee5e000873d55987b676dab76 | DanielDavid48/Exercicios-PY | /ex24.py | 365 | 3.890625 | 4 | print('Seja bem vindo')
print('Essa cidade comeca com Santo?')
nome = input('Nome da cidade: ')
# convertendo a string em minuscula
string = nome.lower()
# encontrando
cidade = string.split()
cidade1 = (cidade[0])
if cidade1 == 'santo':
print('Essa cidade contém Santo no nome.')
else:
prin... |
545cd49c8eb4f62215d65f9054513b46264fe924 | DanielDavid48/Exercicios-PY | /ex101.py | 537 | 3.984375 | 4 | import datetime
def voto():
anos_atual = datetime.date.today().year
nasc = anos_atual - nascimento
if nasc < 16:
return f'Com {nasc} anos: VOTO NEGADO'
elif nasc >= 16 and nasc < 18:
return f'Com {nasc} anos: VOTO OPCIONAL'
elif nasc >= 18 and nasc < 65:
... |
5300b9944a34f18c8303a77be2e61c1a3b925a53 | DanielDavid48/Exercicios-PY | /ex007.py | 952 | 4.03125 | 4 |
print('Seja bem vindo, informe seu nome por gentileza!')
nome_professor = input('Insira seu primeiro nome: ')
print(f'Que bom vê-la (o) novamente por aqui, querida (o) {nome_professor}')
nome_aluno = input('Insira o primeiro nome do aluno: ')
print(f'Ok, achei aqui o aluno {nome_aluno}')
print(f'Agora vamos calc... |
f09901aec3a56dbb7675a4131d01c97ff0173943 | DanielDavid48/Exercicios-PY | /ex14.py | 767 | 4.1875 | 4 | import os
print('Bem vindo ao convertor de temperaturas!')
print(f'Escolha uma das opções abaixo:{os.linesep}A - para converter celsius para fahrenheit{os.linesep}B - para converter fahrenheit para celsius')
opcao = input('Opção escolhida: ')
# Celsius para fahrenheit
# fahrenheit para celsius
if opca... |
893f3e24cc4f76a03c4da1e80a6a528843a230a5 | DanielDavid48/Exercicios-PY | /ex92.py | 2,684 | 3.78125 | 4 | import datetime
print('Seja bem vindo ao \033[33mPosso me aposentar por tempo de trabalho?\033[m do INSS')
dicionario = {}
ano_atual = datetime.date.today().year
nome = dicionario['Nome'] = input('Informe seu nome por gentileza: ')
nascimento = int(input('Insira o ano do seu nascimento: '))
dicionario['Idad... |
4a12fde7b7f54205ea2520c996ba01e62d78d986 | DanielDavid48/Exercicios-PY | /ex11.py | 372 | 3.75 | 4 | print('Bem vindo ao FastWork')
alt = float(input('Insira a altura da parede em metros: '))
largura = float(input('Insira a largura da parede em metros: '))
area = alt * largura
#1L de tinta pintam 2m quadrados de parede
qt_tinta = area / 2
print(f'A sua área é de {area}m² e você precisará de {qt_tinta}L... |
54aa2bc5ce034012bd44360872ef0a8ce115eb76 | DanielDavid48/Exercicios-PY | /Modulariação/numeros.py | 144 | 3.75 | 4 | from uteis import numero
num = int(input('Quer fatorar qual número: '))
fat = numero.fatorial(num)
print(f'O fatorial de {num} é {fat}.') |
ab7a61ee2991a4964a3adda3b4fb1de4697d6bdc | DanielDavid48/Exercicios-PY | /ex20.py | 528 | 3.703125 | 4 | import random
print('Seja bem vindo')
nome_prof = input('Para comecarmos, me informe seu nome, caro professor (a): ')
print(f'Prazer {nome_prof}, vamos sortear a sequência, me informa o nome dos alunos...')
aluno1 = input('Nome aluno 1: ')
aluno2 = input('Nome aluno 2: ')
aluno3 = input('Nome aluno 3: ')
... |
8b6bb2b2ae9e45110c6eac0cc6d561c0ff0bcab4 | DanielDavid48/Exercicios-PY | /ex61.py | 322 | 3.875 | 4 | print('Cálcular progressão aritmética <><><><>')
termo = int(input('Insira o 1° termo: '))
razao = int(input('Insira a razão: '))
qtd = int(input('Quantos termos você quer ver: '))
termoo = termo
cont = 1
while cont <= qtd:
print(termoo)
termoo += razao
cont += 1
print('FIM')
|
7a7d6a1a6069d8e3fdd42f41e3c3f5763f8b8f3a | DanielDavid48/Exercicios-PY | /ex18.py | 327 | 3.765625 | 4 | import math
print('Seja bem vindo')
angulo = float(input('Insira o ângulo: '))
rad = math.radians(angulo)
seno = math.sin(rad)
cos = math.cos(rad)
tang = math.tan(rad)
print(f'O seno de {angulo} é {seno:.2f}')
print(f'O cosseno de {angulo} é {cos:.2f}')
print(f'A tangente de {angulo} é {tang:.2f}')
... |
c8b1645f25612dfc6eb1bbe2f337096e7c31be9d | DanielDavid48/Exercicios-PY | /aulas/Aula 7.py | 11,729 | 4.34375 | 4 | #Ordem de precedência: 1 (); 2 **; 3 * / // %; 4 + -;
# Desafio 1: Faça um programa que leia um número inteiro e mostra na tela o seu sucessor e o seu antecessor.
#n1 = int(input('Digite um número:'))
#conta1 = n1 - 1
#conta2 = n1 + 1
#print(f'O antecessor de {n1} é {conta1} e o sucessor é {conta2}')
######... |
c25fcda125683285d79266d8a4e4a8e03d29f0c6 | Mitrde/artezio_python_course | /Lesson 4/main.py | 239 | 3.734375 | 4 | """You can check is site alive with it"""
from website_alive.check_response import check_url
print("Enter URL")
URL = input()
if check_url(URL):
print("{} is available".format(URL))
else:
print("{} is not available".format(URL))
|
8fb86e61eb6cfd59b57240f906967031455b24f3 | Mitrde/artezio_python_course | /Lesson 1/06.py | 159 | 3.8125 | 4 | n = int(input())
def make_dict(num):
tmp_dict = dict()
for i in range(1, num):
tmp_dict[i] = i*i
return tmp_dict
print(make_dict(n))
|
ea5484d78574bdebc9be0fc8264c10ecb26dbd9f | hirwaraissa/PythonProject | /Median.py | 99 | 3.515625 | 4 | a=87
b=33
c=34
med=0
if a>b and a>c:
if b>c:
med=b
else:
med=c
print(med)
|
ce19b54ed1c989ab6d889e9509f87be5b3a1b57e | hirwaraissa/PythonProject | /print function other ex.py | 392 | 4.03125 | 4 | name = "Alice"
age = 10
s2 = "I am {1} and I am {0} years old.".format(age, name)
print(s2)
name="Alice"
age=10
live="Chatelet"
study="Louvain-La-Neuve"
s2 = "I am {1} and I am {0} years old, I live in {2} but study in {3}.".format(age, name,live,study)
print(s2)
s1 = "Her name is {0} and she's {1} years old!She... |
628d6769ac38740590e50af31881d52b1474df48 | hirwaraissa/PythonProject | /Nombrepremier.py | 171 | 3.703125 | 4 | n=int(input("votre nombre: "))
premier=True
for k in range(2,n):
if n%k==0:
premier=False
if premier:
print(n,"premier")
else :
print(n, "pas premier") |
0d5ea96e8efa47a5e27305e6f8a7c69e029a06a4 | hirwaraissa/PythonProject | /somme des n premiers entiers pairs.py | 275 | 3.75 | 4 | n=int(input(" "))
sum=0
count=0
for x in range (1,n**2):
while count<=n:
if x%2==0:
count+=1
sum=sum+x
print(sum)
while count<=n:
for x in range (1,n**2):
if x%2==0:
count+=1
sum=sum+x
print(sum) |
626bfe83e6aa8e82bdbf7001366c48ff3eb89c79 | hirwaraissa/PythonProject | /Afficher le premier caractère d'une chaine + en majuscule.py | 322 | 3.828125 | 4 | l = "louvain-la-neuve"
print(l[3])
print(l[-1])
print(l[-16])
print(l[0].upper())
print(l[1:15])
print(l[1:])
print(l[0].upper()+l[1:])
indices=[]
for i in range(len(l)):
if l[i]=="_":
indices.append(i)
print(indices)
indices=[]
for i in range(len(l)):
if l[i]=="_":
print(l[:i])
bre... |
24eba4e14882d16f58a28215e80c755e82c28fad | hirwaraissa/PythonProject | /recherche.py | 202 | 3.609375 | 4 | def primes(max):
prime=[]
for i in range (2,max+1):
status=True
for j in prime:
if i%j==0:
status=False
if status:
prime.append(i) |
9d77dde4b9ba8e00a6423b3283258d9e8bddc19d | hirwaraissa/PythonProject | /challenge.py | 429 | 3.625 | 4 | n= int(input("Entrez la valeur du coefficient n : "))
min= int(input("Entrez la valeur minimale pour a, b, c et d: "))
for a in range(1,min):
for b in range(1,min):
for c in range(1,min):
for d in range(1,min):
if a**n + b**n == c**n + d**n:
print("a =", a, "... |
4fb706299ca047c06282464beb8bb46f79c9858c | b-steel/mastermind | /computer.py | 1,444 | 3.546875 | 4 | import random
class Computer():
def __init__(self):
self.first_guess = True
self.possibilities = self.create_posibilities()
self.remaining = self.possibilities.copy()
def create_posibilities(self):
s = []
for a in range(1,10):
for b in range(1,10):
... |
135986fb098b71a18df2cec9b85c7b91dad9e538 | cjriley/holdem_equity_analyzer | /poker_hand.py | 10,599 | 3.84375 | 4 | """Representations and evaluations of Poker hands."""
import card
import collections
import itertools
import re
import hand_ranges
HIGH_CARD = 'High Card'
ONE_PAIR = 'One pair'
TWO_PAIR = 'Two pair'
THREE_OF_A_KIND = 'Three-of-a-kind'
STRAIGHT = 'Straight'
FLUSH = 'Flush'
FULL_HOUSE = 'Full House'
FOUR_OF_A_KIND = '... |
5a32f58371269475a9f87517f9c5e752e08ed04b | burnsnoss/CodingChallenges | /AdventOfCode/2017/Day4/main.py | 1,745 | 3.625 | 4 | '''
main.py - Advent of Code 2017 Day 4
http://adventofcode.com/2017/day/4
'''
import sys
def parseCmdArgs(argv):
''' Parses arguments from command line '''
if len(argv) != 3:
print 'Error: improper command line args'
exit()
filename = argv[1]
if argv[2] == '-part1':
part = 1
elif argv[2] == '-part2':... |
a5439d0ac9026b4c640cce2276dcb5a8a1a4ce43 | burnsnoss/CodingChallenges | /GoogleFoobar/Challenge2/challenge2.py | 3,196 | 4.03125 | 4 | def answer(total_lambs):
# The fibonacci sequence will be the stingiest method of payment
# The most generous will be doubling the previous henchman's pay
# Cast total_lambs as an int just in case
total_lambs_int = int(total_lambs)
# This is the base case for both ways of doing things, tot... |
67ae4c3e52409c949b22f2d4a1ecf7bb1661205e | alexander-dejeu/googleTranslate-Twilio | /googleTranslate.py | 2,225 | 3.640625 | 4 | """ PROJECT SPECS + CHALLENGES
1. Create a Python wrapper function for Translate:
print translate_text) -> translate_text
2. Extended your wrapper function with target language:
print translate(text, language='XX') -> text in XX language
3. Extended your wrapper function to translate multiple strings:
prin... |
ca2562b4dbb3513957716d89b1717b8b30a4bd92 | GAYUGAYA/python-programming | /Beginner level/fibo.py | 276 | 3.859375 | 4 | Number=int(input("enter the number"))
i=0
n1=0
n2=1
while(i < Number):
if(i <= 1):
Next = i
else:
Next=n1+n2
n1=n2
n2=Next
print(Next)
i=i+1
|
5fff1a5031daeefd4882d74b8d53ebc672d0c56b | kylecarter/ict-4370-python-programming | /five/carterk_assignment5_stock.py | 3,982 | 3.765625 | 4 | '''
/**
* Assignment 5 | ICT 4370 | Python Programming
*
* Class for Stocks.
*
* @category Assignment
* @package AssignmentFiveStock
* @author Kyle A. Carter <kyle.carter@du.edu>
* @copyright 2019 Kyle A. Carter
* @license https://opensource.org/licenses/GPL-3.0 GNU General Public License version... |
662ba6e340e968f95adeebeb601083823e26d4ea | EstebanBrito/taller-basico-python | /basics.py | 1,211 | 4.375 | 4 | # VARIABLES EN PYTHON
# No es necesario definir tipo (static, public, etc)
# ni tipo (int, float, etc)
mi_variable = 45
print(mi_variable)
mi_variable = 3.9
print(mi_variable)
mi_variable = True
print(mi_variable)
mi_variable = 'otro valor'
print(mi_variable)
mi_variable = [1, 6, 3, 3]
print(mi_variable)
# Operac... |
42aa92744706772a53cddf2e9d1f839d224eed52 | arichadda/chess_ai | /test_chess.py | 1,131 | 3.515625 | 4 | # Ari Chadda
# 9 October 2020
# Chess AI Assignment CS76 F20
from IterativeDeepeningMinimaxAI import IterativeDeepeningMinimaxAI
from RandomAI import RandomAI
from HumanPlayer import HumanPlayer
from MinimaxAI import MinimaxAI
from AlphaBetaAI import AlphaBetaAI
from ChessGame import ChessGame
if __name__ == "__main__... |
6bb2292e2d8f2a4546186b3a1ec1c60727f31a94 | dongming2016/python_study | /base/examples/example-6-for.py | 645 | 3.890625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# author:35037
# datetime:2019/1/9 21:31
'''
python中的循环有两种
for in
while
'''
for i in [1, 2, 3]:
print(i)
j = 0
while j < 10:
print(j)
j += 1
k = 0
while True:
print('k0:', k)
k += 1
if k > 3:
break # 终止当前层循环
print('\r')
l = 0
while l ... |
7a15508b1dd3d5eb03d2382008b1f9a788ea338a | byronleetinker/two_numbers_task | /main.py | 1,247 | 3.953125 | 4 | from tkinter import *
window = Tk()
first_number = Label(window, text="enter first number")
first_number.grid(column=1, row=1)
second_number = Label(window, text="enter second number")
second_number.grid(column=1, row=2)
answer_label = Label(window, text="your answer")
answer_label.grid(column=1, row=3)
first_number_en... |
fe4ba27c40751233f94c4468944fd300c65ac1f8 | luizpericolo/PythonProjects | /Text/count_words.py | 793 | 4.46875 | 4 | # Count Words in a String - Counts the number of individual words in a string. For added complexity read these strings in from a text file and generate a summary.
string = ''
while string.upper() != 'QUIT':
string = raw_input("Enter a text to get a summary of strings or 'quit' to exit: ")
if string.upper() != 'QUIT'... |
919d8cf57543c20cb417b9704c54a4cf4f9adf52 | melission/leetcode | /Chellenges/2021/July/Isomorphic Strings.py | 816 | 4.03125 | 4 | # https://leetcode.com/explore/challenge/card/july-leetcoding-challenge-2021/609/week-2-july-8th-july-14th/3811/
def isIsomorphic(s: str, t: str) -> bool:
# t.length == s.length and len>1
mapping_dict = {}
mapped_set = ()
length = len(s)
for i in range(length):
test_s = s[i]
test_t... |
54c7954e9b17b56aff806ec9f0ba48216e308f9a | IncapableFury/Triangle_Testing | /triangle.py | 2,034 | 4.25 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Jan 14 13:44:00 2016
Updated Jan 21, 2018
The primary goal of this file is to demonstrate a simple python program to classify triangles
@author: jrr
@author: rk
@
"""
def classify_triangle(side1: int, side2: int, side3: int) -> str:
"""
Your correct code goes here.... |
d0935a48ad03c078bcb50b9adef38fa64e53df8f | cdueltgen/markov_exercise | /markov.py | 1,053 | 4.28125 | 4 | """
markov.py
Reference text: section 13.8, how to think like a computer scientist
Do markov analysis of a text and produce mimic text based off the original.
Markov analysis consists of taking a text, and producing a mapping of prefixes to suffixes. A prefix consists of one or more words, and the next word to follo... |
914c8d54446c025f98e8262011895ac84c9abfc4 | YoonSungLee/Algorithm_python | /이것이 취업을 위한 코딩테스트다 with 파이썬/DFS_BFS/괄호 변환.py | 3,127 | 3.5625 | 4 | ### 기본 코드
# def solution(p):
# answer = ''
# return answer
# book solution
def balanced_index(p):
count = 0 # 왼쪽 괄호의 개수
for i in range(len(p)):
if p[i] == '(':
count += 1
else:
count -= 1
if count == 0:
return i
def check_proper(p):
co... |
dd083d708e8d09d5203cd1427a59468328f6e204 | YoonSungLee/Algorithm_python | /이것이 취업을 위한 코딩테스트다 with 파이썬/Grammar/library_itertools.py | 2,220 | 3.6875 | 4 | # permutations(순열)
# 리스트와 같은 iterable 객체에서 r개의 데이터를 뽑아 일렬로 나열하는 모둔 경우를 계산
# permutations는 클래스이므로 객체 초기화 이후에는 리스트 자료형으로 변환하여 사용
from itertools import permutations
data = ['A', 'B', 'C'] # 데이터 준비
result = list(permutations(data, 3)) # 모든 순열 구하기
print(result)
# combinations(조합)
# 리스트와 같은 iterable 객체에서 r개의 데이터를 뽑아... |
077b260258ea2a1c948a109c8bf3647d1d56c166 | ritambasu61/searching-power-of-2-X-from-a-list | /power2.py | 312 | 3.515625 | 4 | """
created by: Ritam Basu
created on:06/11/19
created for: assignment1.
"""
from math import *
L = [1,2,4,8,16,32,64]
X = 5
j = 0
i = 0
while j< len(L):
if 2**X == L[j]:
print ("at index",j)
i=i+1
j=j+1
if i==0:
print(X,"this value is not found in the list of 2^x")
|
4e4f8d31468662facad3c826e0f916c5085a6ced | brutchm/TeareaInvestigacionArboles | /BL/BPlusNode.py | 2,542 | 4.03125 | 4 | class BPlusNode(object):
"""Base node object.
Each node stores keys and values. Keys are not unique to each value, and as such values are
stored as a list under each key.
Attributes:
order (int): The maximum number of keys each node can hold.
"""
def __init__(self, order):
"""Chi... |
af03fec671a85df59a7ae220bd761ed2cec6dc48 | Ashasrinivas/100programs | /ex_70.py | 142 | 4.0625 | 4 | #“String” like a python expression and returns the result as an integer
expression = input("enter expression : ")
print(eval(expression))
|
09cdf2500b58fae8508e9bdcaa74b5d0c6a0b4c7 | Ashasrinivas/100programs | /ex_38.py | 113 | 3.890625 | 4 | def printlist():
li = []
for i in range(1, 20):
li.append(i ** 2)
print(li[-15:])
printlist() |
2b67b9f65ba52250d00d93be9cb9d4c2314736e9 | Ashasrinivas/100programs | /ex_14.py | 218 | 3.953125 | 4 | s = input(" enter the sentence : ")
up = low = 0
for c in s:
if c.isupper():
up = up+1
elif c.islower():
low = low+1
else:
pass
print("upper letters", up)
print("lower letters", low) |
daa97eda6dff07f3cdab5c839589a543ce500125 | flotpython/slides | /slides-extras/library/pgcd.py | 287 | 3.875 | 4 | #!/usr/bin/env python3
def pgcd(a, b):
"""
Le pgcd de a et b par l'algorithme d'Euclide
>>> pgcd(42, 30)
6
>>> pgcd(30, 42)
6
"""
if b > a :
a, b = b, a
while True:
r = a % b
if r == 0:
return b
a, b = b, r
|
cde85ce64c9720130a4ed66b6305db9073d1c237 | shibdaskumbhakar/number_gussing_game | /guessing_game.py | 601 | 3.859375 | 4 | import random
class guess:
def __init__(self):
self.number=random.randint(10,100)
print("The random number is",self.number)
self.user_input()
def user_input(self):
self.input=int(input("What's your guess"))
self.process()
def process(self):
if self.input>sel... |
e8d0534c04a4de8f26b39966b8c8e9aa9643cd19 | cassiorodrigo/python | /aula16.py | 430 | 3.9375 | 4 | numeros = ('zero', 'um', 'dois', 'três', 'quatro', 'cinco', 'seis', 'sete', 'oito', 'nove', 'dez')
while True:
num = int(input('Digite um numero entre 0 e 10: '))
if num > 10:
num = int(input('Entrada inválida. Tente novamente: Digite um valor entre 0 e 10'))
if num < 0:
num = int(input('Ent... |
fe6674df0c6d1f77e0178de6e10bd6e8c60c7984 | cassiorodrigo/python | /produtos.py | 796 | 3.734375 | 4 | total = 0
count = 0
barato = 0
probarato = ''
procaro = ''
procarocount = 0
while True:
count += 1
produto = str(input('Digite o nome do produto: ')).strip().capitalize()
preco = float(input('Digite o preço do produto'))
total += preco
if count == 1:
barato = preco
elif preco < barato:
... |
d7c1582e72c291ced406a9a47731bae6cbf5cbd8 | cassiorodrigo/python | /aula14.py | 340 | 4.125 | 4 | s = str(input('Digite seu sexo [M/F] ')).strip().upper()[0]
while s not in 'MmFf':
s = str(input('Entrada Invalida, por favor digite [M/F]: ')).strip().upper()[0]
print('Você digitou {}.'.format(s))
'''r = 'S'
while r == 'S':
n = int(input('Digite um numero: '))
r = str(input('Quer continuar: [S/N ')).uppe... |
2ab783039ab2c9b5434a7850ce2bc0456e55cc66 | cassiorodrigo/python | /exe66.py | 217 | 3.78125 | 4 | num = count = soma = 0
while True:
num = int(input(f'Digite um valor (999 para parar): '))
if num == 999:
break
soma += num
count += 1
print(f'A soma dos {count} numeros digitados é: {soma}') |
bda881a47aa0c90b770962d65cd723be8b99a98f | cassiorodrigo/python | /calcpa.py | 369 | 3.9375 | 4 | n = int(input('Digite o termo inicial da PA: '))
raz = int(input('Digite a razão: '))
count = 0
opçao = 10
total = 0
while opçao != 0:
total += opçao
while count <= total:
print('{} -- '.format(n), end='')
n += raz
count += 1
print('Pausa')
opçao = int(input('Quantos termos mais ... |
5129af0aad8a7dae4fb4460c2c41c6b960c269fc | Chaoscz/StudyGit | /study/python/base/map.py | 138 | 3.6875 | 4 | def normalize(name):
n = name.lower().capitalize()
return n
L1 = ['adam', 'LISA', 'barT']
L2 = list(map(normalize, L1))
print(L2)
|
c095480c292660b309dac1e83c3e533a1f541c63 | chavafg/directory-hash-tree | /avlTree.py | 6,627 | 3.65625 | 4 | # -*- coding: utf-8 -*-
from avlNode import avlnode
from item import DirectoryItem
class avltree(object):
def __init__(self):
self.node = None
self.height = -1
self.balance = 0
def insert(self, key, DirectoryItem):
# Create new node
n = avlnode(key, DirectoryItem)
... |
3fb8cee657d9573302bc70d6e5bbd65e189f91d2 | boddachappu/codility | /slit.py | 1,372 | 3.65625 | 4 | """
A non-empty array A consisting of N integers is given. Array A represents numbers on a tape.
Any integer P, such that 0 < P < N, splits this tape into two non-empty parts: A[0], A[1], ..., A[P − 1] and A[P], A[P + 1], ..., A[N − 1].
The difference between the two parts is the value of: |(A[0] + A[1] + ... + ... |
b85e4e19dd9157a38ff2ca2106507ca23c2807b2 | boates/practice | /insight/sorting/heapsort.py | 1,041 | 3.9375 | 4 |
def parent(i):
return (i-1) // 2
#return i // 2
def left(i):
return 2*i + 1
#return 2*i
def right(i):
return left(i) + 1
def max_heapify(a, i, N):
l = left(i)
r = right(i)
#N = len(a)
if l < N and a[l] > a[i]:
L = l
else:
L = i
if ... |
84d4a64ccf6d5a57d3fa57a78b02c0b5d5b28eb5 | yak2525/CP3-Anucha-Boonrojsaree | /Exercise_21_AnuchaB.py | 1,179 | 3.75 | 4 | from tkinter import *
import math
def leftClickButton(event):
result = float(textBoxWeight.get()) / math.pow(float(textBoxHight.get()) / 100, 2)
if result > 30 :
ans = "อ้วนมาก"
elif result > 25 :
ans = "อ้วน"
elif result > 23 :
ans = "น้ำหนักเกิน"
elif result >... |
e4e4d1aa65cca834a26d27edd85da4a0543a96f7 | NYU-Python-Intermediate-Legacy/jarnold-ipy-solutions | /jarnold-2.2.py | 2,270 | 4.15625 | 4 | #usr/bin/python2.7
import os
import sys
def unique_cities(cities):
# get rid of empty items
if cities.has_key(''):
del cities['']
unique_cities = sorted(set(cities.keys()))
return unique_cities
def top_ten_countries(countries):
# get rid of empty items
if countries.has_key(''):
del countries['']
... |
424c14cc7e7547593ae9bf715e78108b363d2cc3 | ZuzaRatajczyk/Zookeeper | /Problems/Lucky ticket/task.py | 466 | 4.125 | 4 | # Save the input in this variable
ticket = (input())
first_digit = int(ticket[0])
second_digit = int(ticket[1])
third_digit = int(ticket[2])
fourth_digit = int(ticket[3])
fifth_digit = int(ticket[4])
sixth_digit = int(ticket[5])
# Add up the digits for each half
half1 = first_digit + second_digit + third_digit
half2 ... |
b246dd8164b6298ffb9c189ffa26e80276e9aa42 | sakshamgautam2001/SDSC_course_project | /Part 4 - Clustering/Section 24 - K-Means Clustering/Kmeans_clustering.py | 1,376 | 3.5625 | 4 |
# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
dataset=pd.read_csv('Mall_Customers.csv')
X=dataset.iloc[:,3:5].values
#feature scaling
#No feature scaling required
#First we find optimal number of centroids Using Elbow method
from sklearn.cluster import KMeans
wcss=... |
7cb38b022d9b439289a377c51bce9bf04573a61e | leopuglia-a/Udemy | /Python/data_structure/queue.py | 475 | 3.90625 | 4 | class Queue(object):
"""docstring for Queue"""
def __init__(self):
self.queue = []
self.len_queue = 0
def push(self, e):
self.queue.append(e)
self.len_queue += 1
def pop(self):
if self.len_queue != 0:
self.queue.pop(0)
self.len_queue -= 1
else:
print("None")
def show(self):
for i in self.... |
720c4296675f52a2d716dcab26c51f069d38b9d4 | HUANGXUANKUN/Introduction-to-Computational-Thinking-and-Data-Science-by-MIT-Exercises | /Quiz/Quiz 3.py | 1,138 | 3.84375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Jun 26 16:31:05 2018
@author: HuangXuankun
"""
def greedySum(L, s):
""" input: s, positive integer, what the sum should add up to
L, list of unique positive integers sorted in descending order
Use the greedy approach where you find the largest mult... |
7d104a83d8f44d57a614a1a5dd964efd1ef9e995 | oldmannt/develop-tips | /python/quick_sort.py | 570 | 3.84375 | 4 |
def swap(a, x, y):
#print "swap {0},{1}".format(x,y)
t = a[x]
a[x] = a[y]
a[y] = t
def part(a, l, r):
i = l
#print "{0}, {1}".format(l, r-1)
for x in xrange(l,r):
#print "x = {0}".format(x)
if a[x]<=a[r]:
swap(a,x,i)
i += 1
swap(a,r,i)
return i
def quickSort(a, s, e):
if s>= e: return
i = part(a... |
378d6395be954c10c89f52492d21951f2f7a9994 | testestzxcv/testbook | /a/test10.py | 1,438 | 3.515625 | 4 | import re
# p = re.compile('[a-z]+')
#
# m = p.match("python")
# print(m)
#
# d = p.match("ab123b")
# print(d)
#
# m = p.match( 'string goes here' )
# m = p.match('9229')
# if m:
# print('Match found: ', m.group())
# else:
# print('No match')
# m = p.search("python")
# print(m)
# m = p.search('0 string goes ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.