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 |
|---|---|---|---|---|---|---|
3a54f084e5fe36e69e530afc74d44dcfb8ae4ee6 | SaiKrishnaBV/python-basics | /userDefinedExceptions.py | 691 | 3.859375 | 4 | '''
User defined Exceptions
'''
class Error(Exception):
''' Base class for other exceptions'''
pass
class ValueTooSmallError(Error):
'''Raised when input value is too small'''
pass
class ValueTooLargeError(Error):
'''Raised when input value is too large'''
pass
number = 10
while True:
try:
guess = int(i... |
20ef9667d80e78e6d8e199d0461d6e024bd94ffb | SaiKrishnaBV/python-basics | /ExceptionHandling.py | 3,327 | 4 | 4 | '''
practice - Exception Handling
1) Syntax error
2) Logic error
3) Exceptions
Assertion Error - When assert statement fails
Attribute Error - When attribute assignment or reference fails
EOF Error - When input() function hits end-of-file condition
FloatingPoint Error - When floating point operation... |
57601ca144fda603bcd1822d4d1971873e23ddbc | SaiKrishnaBV/python-basics | /scopeOfVariable2.py | 656 | 4.34375 | 4 | '''
Understanding the concept of nonlocal variables(enclosed variables) inside nested functions
'''
z = 5
def in_func():
z = 10
print("In_func() --> local: z =",z)
def inner_func():
nonlocal z #to access enclosed variable instead of global variable
z+=1
print("Inner_func() --> z =",z)
def innermost_f... |
c31d58293c15284c7109650b2be9c473cf2611d9 | Likkrid/tenable-CTF | /Stego/Secret Images/sol.py | 449 | 3.53125 | 4 | #!/usr/bin/env python3
from PIL import Image
import numpy as np
# creating a image1 object
im1 = Image.open("crypted1.png")
#.convert("1")
# creating a image2 object
im2 = Image.open("crypted2.png")
#.convert("1")
# Make into Numpy arrays
im1np = np.array(im1)*255
im2np = np.array(im2)*255
# XOR with Numpy
result ... |
5ad895a11edff338df98876eb17f54e125c74cc0 | zrjaa1/Berkeley-CS9H-Projects | /project4_Turtle_Behavior/simple.py | 1,623 | 3.5625 | 4 | # This file is the main driver of the procedure, including the TKinter, Arena and instance of Statue, Mouse, Cat classes.
from Tkinter import * # Import everything from Tkinter
from Arena import Arena # Import our Arena
from WalkingTurtle import WalkingTurtle # Import our T... |
9e3b8d7aac17d3b5cef01341cc8452f9ac52cab6 | zrjaa1/Berkeley-CS9H-Projects | /Project2A_Power Unit Converter/source_to_base.py | 1,260 | 4.34375 | 4 | # Function Name: source_to_base
# Function Description: transfer the source unit into base unit.
# Function Input
# - source_unit: the unit of source, such as mile, cm.
# - source_value: the value in source unit.
# Function Output
# - base_unit: the unit of base, such as m, kg, L
# - base_value: the value in b... |
190318165b61115cdf215c3c918919a76e2c2a57 | MakeSchool-17/twitter-bot-python-KavinSub | /heap_10.py | 3,463 | 4.09375 | 4 | import sys
# Implementation of binary heap with max-heap property
# Left child = 2 * k
# Right child = 2 * k + 1
# Parent = k / 2
class Heap:
def __init__(self):
self.heap = []
self.heap.append(None)
# Inserts the new value
def insert(self, key, value):
# Starts by adding a value a... |
3dfad192fb90b7ba49be15a32422f8feaba865e8 | lcaldara/python3 | /exercicios curso em video/desafio11 - parede, tinta.py | 345 | 3.75 | 4 | alt = float(input('Digite a altura da parede a ser pintada: '))
compr = float(input('Digite o comprimento da parede a ser pintada: '))
area = alt*compr
litros = area/2
print(' ')
print('Será(ão) necessário(s) {:.2f} litro(s) de tinta.'.format(litros))
print('Será(ão) necessário(s) {:.2f} litro(s) de tinta.'.forma... |
ab6bd36a31076965ad0bd5dea47bbdc3157227e8 | lcaldara/python3 | /exercicios curso em video/desafio35 - cond triangulo.py | 764 | 3.953125 | 4 | cores = {}
print('\033[7;37;40mCALCULADORA DE TRIANGULOS\033[m')
r1 = int(input('Digite o comprimento do primeiro segmento de reta: '))
r2 = int(input('Digite o comprimento do segundo segmento de reta: '))
r3 = int(input('Digite o comprimento do terceiro segmento de reta: '))
if abs(r2 - r3) < r1 < (r2 + r3) and a... |
cf792e710ef0ddf7f213599a8fbf92e0374734fb | lcaldara/python3 | /exercicios curso em video/desafio47 - pares 1 a 50.py | 143 | 3.640625 | 4 | #for c in range(0, 51, 2):
# print(c)
#print('Fim')
for c in range(1, 51):
if (c % 2) == 0:
print(c, end=' ')
print('Fim') |
ce1ae261ed12b0df13cd1fb4e58cf3a5d580a9f2 | lcaldara/python3 | /exercicios curso em video/validação de dados.py | 316 | 3.59375 | 4 | valido = False
novo = 0
while not valido:
entrada = str(input('Valor: ')).replace(',', '.').strip()
if entrada.isalpha() or entrada == '':
print(f'\033[0;31mERRO: {entrada} não é um valor válido.\033[m')
else:
valido = True
novo = float(entrada)
print(f'{novo:.2f}')
|
5d0057edf4952ef63a6c0e40f8af7c545ea788dd | lcaldara/python3 | /exercicios curso em video/desafio82 - lista par, impar.py | 555 | 3.734375 | 4 | lista = []
listapar = []
listaimpar = []
while True:
x = int(input('Digite um número para a lista: '))
lista.append(x)
cont = str(input('Deseja continuar? [S/N] ')).upper().strip()
while cont not in 'NS':
cont = str(input('Digite um valor válido: [S/N] ')).upper().strip()
if cont ==... |
13f176abe69ab11002fc1457d5c8231e141741c9 | lcaldara/python3 | /exercicios curso em video/desafio62 - PA while melhorado.py | 286 | 3.9375 | 4 | num = int(input('Digite o primeiro termo da PA: '))
pa = num
c = 0
passo = int(input('Digite o passo da PA: '))
termos = int(input('Quantidade de termos da PA: '))
while c < termos:
print(pa, '→ ' if c < (termos - 1) else 'Fim', end='')
pa = pa + passo
c = c + 1
|
e72729dad950e0769c509b0edccbb9a8a5aa37ee | lcaldara/python3 | /exercicios curso em video/desafio36 - prestacao da casa.py | 422 | 3.8125 | 4 | vlr = float(input('Qual o valor da casa? '))
sal = float(input('Qual o valor do seu salário? '))
nPrest = int(input('Em quantos anos você quer pagar? '))
totPrest = nPrest * 12
parcela = vlr / totPrest
if parcela > (sal*0.3):
print('Seu empréstimo não foi aprovado.')
elif parcela <= (sal*0.3):
print('Se... |
6dbcd6e4d0286352a06c39923b9511573a832330 | lcaldara/python3 | /exercicios curso em video/desafio08 - m cm mm.py | 158 | 3.65625 | 4 | m = float(input('Digite o comprimento em metros: '))
print('O comprimento em centímetros e milimetros respectivamente são: {}, {}'.format(m*100, m*1000))
|
2dee1f33a5d990c5dce12b00d95886497181834d | lcaldara/python3 | /exercicios curso em video/desafio64 - soma while.py | 242 | 3.71875 | 4 | c = 0
s = 0
n = 0
flag = 999
n = int(input('Digite o número a ser somado: '))
while n != flag:
s = s + n
c = c + 1
n = int(input('Digite o número a ser somado: '))
print('A soma dos {} termos foi de {}.'.format(c, s))
|
0dda3ba012b88385bdb255b467809c9deefbe798 | TheBell/HW3 | /HW3_server.py | 1,830 | 3.5 | 4 | #!/usr/bin/env python3
'''
The server program runs indifinitely (or until closed) waiting on users to connect.
It waits for HTTP requests, and serves the client the relevant resource.
'''
__author__ = "Brian Bell"
import _thread as thread
import datetime
import re
from socket import *
SERVER_HOST = '' # All a... |
3f63e0ab3f29e654e3c802e25b9759e77ba13c5e | skreynolds/uta_cse_1309x | /class_work_problems/list5.py | 155 | 3.5625 | 4 | my_list = [12, "cat", 3.4, "dog", 62]
new_list = []
for k in range(5):
if k % 2:
m = my_list.pop(k)
new_list.append(m)
print(new_list)
|
7de174a60aef0702439d4f9dea5d3bb20dc92d16 | skreynolds/uta_cse_1309x | /class_work_problems/list13.py | 148 | 3.84375 | 4 | my_list = []
for m in range(0,2):
new_list = []
for k in range(4,6):
new_list.append(k)
my_list.append(new_list)
print(my_list)
|
6e9a876c815d6223f8fa62931bd3745f08666054 | skreynolds/uta_cse_1309x | /class_work_problems/list2.py | 99 | 3.5 | 4 | def my_fun(x):
for k in range (len(x)):
x.extend(x[:k])
m = [1,5,3]
my_fun(m)
print(m)
|
38f58f1f6d7d497fd31a81f4c3a349e75ba338b2 | skreynolds/uta_cse_1309x | /class_work_problems/count_consonants.py | 145 | 3.671875 | 4 | # Type your code here
def count_consonants(some_string):
return sum([1 for c in some_string.lower() if c not in ['a','e','i','o','u', ' ']])
|
bf2e917f4f13d6a097b7bc4e961a198d92b53ada | skreynolds/uta_cse_1309x | /assignment_3/capitalise_word_in_crossword.py | 1,154 | 3.75 | 4 | def find_word_horizontal(crossword, word):
row = 0
for L in crossword:
chr_string = ''.join(L)
if word in chr_string:
col = chr_string.find(word)
return [row, col]
row += 1
return None
def find_word_vertical(crossword, word):
col = 0
transpose_cross ... |
590e9129b65336da3bf98020faaa05f12066b8dd | skreynolds/uta_cse_1309x | /mid_semester_exam/Test1.py | 84 | 3.5 | 4 | x = ["dog", 2, "cat", 34, 5.8]
m = 0
for i in range(len(x)):
m = m + i
print(m)
|
65dc2f6e16bdf60ad1063eae8f73854f2d73254f | NaveenKudari/Assignment_3 | /Assignment_3.3.py | 242 | 3.890625 | 4 |
# coding: utf-8
# In[15]:
def longest_word(lst):
longestword= lst[0]
for word in lst[1:]:
if len(word)>len(longestword):
longestword=word
return longestword
longest_word(['me','mine','good','very good'])
|
3298294e57238a47a51a2111f748e4279783e1e0 | pavdemesh/exercism | /python/protein-translation/protein_translation.py | 1,320 | 3.703125 | 4 | def proteins(strand):
# Create a list to store decoded proteins
proteins_list = []
# Create and populate dictionary of codon to protein correlations and STOP codons
codons_to_proteins ={"AUG": "Methionine",
"UUU": "Phenylalanine", "UUC": "Phenylalanine",
"... |
3191972f08fb2d8e4a6292c5bdd59aabdcb51688 | alfonso-torres/data_types-operators | /strings&casting.py | 1,937 | 4.65625 | 5 | # Strings and Casting
# Let's have a look at some industry practices
# single and double quotes examples
greetings = 'hello world'
single_quotes = 'single quotes \'WoW\''
double_quotes = "double quotes 'WoW'" # It is more easier to use
print(greetings)
print(single_quotes)
print(double_quotes)
# String slicing
gree... |
4ec0a172bbe8ee67fe86c795d2a78f3e6e565f89 | managedkaos/sample-programs | /archive/p/python/days_since_date.py | 487 | 3.875 | 4 | from datetime import date
from sys import argv
# ENTER THE DAY AS YYYY-MM-DD as a single argument on the command line
# ie, python days_since_date.py 2019-10-25
input_str = argv[1]
input_int = input_str.split('-')
input_int = [int(x) for x in input_int]
start = date(input_int[0], input_int[1], input_int[2])
today = ... |
34ffa350aeea6e0c89a536f2c76ac3be0727490d | fangyansun/PracticalPython_OpenCV | /blurring.py | 1,908 | 3.53125 | 4 | import numpy as np
import argparse
import cv2
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--image", required = True, help = "Path to the image")
args = vars(ap.parse_args())
image = cv2.imread(args["image"])
# cv2.imshow("Original", image)
blurred = np.hstack([image, cv2.blur(image,(3,3)), cv2.blur(image, ... |
55c67882f4c6a90433989dbf6f618e8263772254 | ha-170/python4semExercises | /modules/utils.py | 683 | 3.625 | 4 | def get_file_names(folderpath,out=output.txt):
""" takes a path to a folder and writes all filenames in the folder to a specified output file"""
def get_all_file_names(folderpath,out=output.txt):
"""takes a path to a folder and write all filenames recursively (files of all sub folders to)"""
def print_line_on... |
bf88f5ef4db0f0fe6e0690fe56b83b1fa850b2d5 | nhomble/mazeDancing | /src/config/enums.py | 4,206 | 3.734375 | 4 | #!/usr/bin/env python2
# ===================== enums ===================================
'''
FORWARD
LEFT RIGHT
BACKWARD
'''
# python2 enums
class Direction(object):
LEFT = 0,
RIGHT = 1,
FORWARD = 2,
BACKWARD = 3,
ERROR = 4
TURN = {
# LEFT
(0,):{
# LEFT turn --> BACKWARD
(0,): (3,),
# RIGHT tur... |
38322c01d2c410b06440fae9ce02faf2c8e045c4 | JamesPiggott/Python-Software-Engineering-Interview | /Sort/Insertionsort.py | 880 | 4.1875 | 4 | '''
Insertionsort.
This is the Python implementation of the Insertionsort sorting algorithm as it applies to an array of Integer values.
Running time: ?
Data movement: ?
@author James Piggott.
'''
import sys
import timeit
class Insertionsort(object):
def __init__(self):
print()
def ins... |
8c2262c02d97b2ce5d9fe65e6f2fc8cdef7941a5 | mstange22/HackerRank | /python/tree.py | 794 | 3.9375 | 4 | """ Node is defined as
class node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
"""
def left(root, parent_data):
if root == None:
return True
if root.data >= parent_data:
return False
return left(root.left, root.data) and left(root.left, ... |
7a25d72e6a90603b908ec1e9d48f6c74c98d39b1 | ohveloper/python-alogorithm | /Inflearn/PreCourse/2depth_list.py | 309 | 4.125 | 4 |
a = [0] * 3
print(a)
# 2차원 list 만들기
b = [[0] * 3 for _ in range(3)]
print(b)
# 2차원 리스트 값에 접근
b[0][1] = 1
print(b)
b[1][2] = 2
print(b)
# 2차원 리스트를 표처럼 보이게 출력
for x in b:
print(x)
for x in b:
for y in x:
print(y, end=' ')
print() |
1bf9794ddf5f2cb1ef2c3c30725518fb8037e85e | ohveloper/python-alogorithm | /Inflearn/PreCourse/py_lambda.py | 308 | 4.1875 | 4 |
def plus_one(x):
return x+1
x = plus_one(1)
print(x)
# lambda 표현식으로 작성
plus_two = lambda x:x+2
print(plus_two(1))
# list와 map을 활용
a=[1,2,3]
print(list(map(plus_one,a)))
# list와 map에 lambda 활용
a=[1,2,3]
print(list(map(lambda x:x+2, a)))
print(list(map(int, ["1","2"]))) |
aa224541ad5bfb1d25ed5e7a243dbec07a3f8b7b | JordanPottruff/ml-evolutionary-algs | /src/training/genetic.py | 10,378 | 3.65625 | 4 | # genetic.py
# Implements genetic algorithm with neural networks
import random
import itertools
from functools import reduce
import math
import numpy
import numpy as np
from src.network import Network
# Search space for the neural network weights, tunable
LOWER_BOUND = -100000
UPPER_BOUND = 100000
# The amount of fi... |
0c54a30b5564cf4fce07a4a22d90f2fee61fd27c | Caelifield/calculator-2 | /calculator.py | 1,170 | 4.21875 | 4 | """CLI application for a prefix-notation calculator."""
from arithmetic import (add, subtract, multiply, divide, square, cube,
power, mod, )
# Replace this with your code
def calculator():
while True:
input_string = input('Enter string:')
token = input_string.split(' ')
... |
434710ff9be66e5dd2770ed8f04e5520221f7c57 | lucas-serafim/La-cipher | /LetterAccent.py | 622 | 4.0625 | 4 | def remove(letter):
if letter in ('á', 'ã', 'â', 'Á', 'Ã', 'Â'):
return "A" if letter.isupper() else "a"
elif letter in ('é', 'ê', 'É', 'Ê'):
return "E" if letter.isupper() else "e"
elif letter in ('í', 'î', 'Í', 'Î'):
return "I" if letter.isupper() else "i"
elif letter in ('ó',... |
a6bb90330076c2f3d9b148f5271a64ca236c37cf | naseefnaseer/SDGP | /Machine Learning/ml_rajeev/Turkish Dataset Models/updrs_score_prediction/artificial_neural_network.py | 3,755 | 3.625 | 4 | # Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Importing the dataset.
dataset = pd.read_csv('Train Data with UPDRS.csv')
X = dataset.iloc[:, 1: 27].values #matrix of independent features
y = dataset.iloc[:, 27].values #dependent variable
y = y.reshape(y.shape[0], 1)
... |
97593a1f63ed7bdd77ef82f9ea16d6064fca7534 | FGolOV/monotonic | /monotonic.py | 452 | 3.65625 | 4 | from random import randint
n = int(input())
nums = [randint(1, n) for i in range(n)]
def is_monotonic(nums):
res= False
dec=0
inc=0
for i in range(len(nums) - 1):
if nums[i] > nums[i + 1]:
dec += 1
elif nums[i] < nums[i + 1]:
inc += 1
if dec == 0... |
a717c5e18749199e8fa1dc6d18b4a48e64ce508c | 2000Nezox/Atcoder | /AOJ/FindingMissingCards.py | 531 | 3.578125 | 4 | def judge0(icon1, lst):
if not lst:
for i in range(1, 14):
print(icon1, i)
else:
[print(icon1, x) for x in range(1, 14) if not (x in lst)]
n = int(input())
S, H, C, D = [], [], [], []
for i in range(n):
icon, number = input().split()
if icon == 'S':
S.append(int(num... |
8a7ee6cb932576d44753cc8997ca6463769dea3d | 2000Nezox/Atcoder | /AOJ/FindingaWord.py | 215 | 3.75 | 4 | count = 0
w = input()
while True:
tmp = list(input().split())
if 'END_OF_TEXT' in tmp:
break
for i in tmp:
x = str.lower(i)
if x == w:
count = count + 1
print(count)
|
74ac3bbbccb933424dd6f213c6c522ba6db4a90c | 2000Nezox/Atcoder | /ABC111/A.py | 134 | 3.609375 | 4 | n = list(input())
for i,data in enumerate(n):
if data == "1":
n[i] = "9"
else:
n[i] = "1"
print("".join(n))
|
b1bbc5e2158e0d8e1eea17f14dee80fb04ce0477 | 2000Nezox/Atcoder | /ABC104/B.py | 201 | 3.734375 | 4 | s = input()
ans = "WA"
if s[0] == "A" and s[2:-1].count("C") == 1 and s[1] != "C" and s[-1] != "C":
s2 = s.replace("A","a").replace("C","c")
if s2 == s.lower():
ans = "AC"
print(ans)
|
e0478a82b1e3ab2412660fd1a894de2eb102e5f4 | 2000Nezox/Atcoder | /ABC077/A.py | 140 | 3.796875 | 4 | c1_1 = input()
c1_2 = input()
c2_1 = c1_1[::-1]
c2_2 = c1_2[::-1]
if c1_1 == c2_2 and c1_2 == c2_1:
print("YES")
else:
print("NO")
|
d61d6c08331eaeddc3429c56536afcc3857c4d34 | 2000Nezox/Atcoder | /ABC055/B.py | 82 | 3.734375 | 4 | import math
N = int(input())
result = math.factorial(N)
print(result%(10**9+7))
|
170a84b05450afe3cfdb69e8f97412eacca69f67 | 2000Nezox/Atcoder | /ABC088/A.py | 104 | 3.53125 | 4 | N = int(input())
A = int(input())
amari = N%500
if amari <= A:
print("Yes")
else:
print("No")
|
204462c7d2e433cbb38fd5d0d1942cda5303b939 | VIPULKAM/python-scripts-windows | /count_lines.py | 759 | 4.21875 | 4 |
file_path='c:\\Python\\pledge.txt'
def count_lines(handle):
'''
This function returns the line count in the file.
'''
offset = 0
for line in handle:
if line:
offset += 1
continue
return offset
def count_occurnace(handle, word):
'''
This function returns... |
838b7bda78ad80db676413fd048241326ee780e5 | unstoppableforce96/Conditional-Statements | /vowelorconsonant.py | 156 | 4.125 | 4 | # character is vowel or consonant
ch = input()
vowels = 'aeiouAEIOU'
if(ch in vowels):
print(ch, 'is vowel')
else:
print(ch, 'is consonant')
|
e4ac76125238474f5b2bce5ddd606a3271202958 | sebnoh1113/Seb_SKKU_data1 | /seb_week1_dice.py | 1,100 | 3.609375 | 4 | # # 문제1
#
# def die1(x):
# print(die2)
#
# def die2(x,y):
# print(die3)
#
# def die3(x,y,z):
# if x+y+z==N
# return (x,y,z)
#
# N=input("3~18 사이의 숫자를 입력해 주세요:")
# int(N)
# for x in range(1,2,3,4,5,6):
# print(die1(x))
# 문제2
#
# N = int(input("양의 정수 N을 입력하세요:"))
# M = int(input("양의 정수 M을 입력하세요:"... |
856fe2fb92ed8abfbd6dd7faec97da88a3b153f6 | sebnoh1113/Seb_SKKU_data1 | /seb_week9_heapQ2 with .py | 8,365 | 4.03125 | 4 | # # min/max
# # down/up
# # 삽입식(upheap 방식을 사용)
# # 비삽입식
# # bottom-up : downheap 작동을 bottom up 방향으로 반복 수행
# # topdown 더 좋은가?
# 1. 코딩스타일 (클래스 대문자 / 설명적 변수명 / implicit error avoidance / 풍부한 주석) 2. 검증 코드
import random
import math
import sys
#
# class Bottom_up_Heap():
# def __init__ (self, heap):
# sel... |
2467aa99d5fb66970ef197136df1f8349a71f8b5 | vbmendes/pattern-search | /pattern_search/nary_search_tree.py | 768 | 3.828125 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
class Node(object):
def __init__(self):
self.items = []
self.children = {}
def add_item(self, item):
self.items.append(item)
class Tree(object):
def __init__(self):
self.root = Node()
def push(self, pattern, i... |
bac831c282e58e99cf2b7b5f6c82ee0cb3c8ab7f | liquidmetal/algorithms | /python/problems/ugly-numbers/solution.py | 426 | 3.703125 | 4 | #!/usr/bin/python
# Problem: https://leetcode.com/problems/ugly-number/
import math
def is_ugly(num):
"""2, 3, 5 are the only prime factors"""
if num == 0:
return False
if num == 1:
return True
for i in [2, 3, 5]:
import pdb; pdb.set_trace()
while num % i == 0:
... |
35fa6e9f65ff32c780a1709fb2dda2e9d7896746 | liquidmetal/algorithms | /python/problems/bit-range-and/solution.py | 539 | 3.546875 | 4 | #!/usr/bin/python
# https://leetcode.com/problems/bitwise-and-of-numbers-range/
def total_and_naive(m, n):
ret = 0xffffffff
for i in xrange(m, n+1):
ret &= i
return ret
def total_and(m, n):
num_bits = 32
ret = 0
for i in xrange(num_bits):
if m-n > 1:
# We have a z... |
13a57d3008b88c4d3974af2c154c50e6781caacd | liquidmetal/algorithms | /python/problems/flipping-bits/solution.py | 233 | 3.546875 | 4 | #!/usr/bin/python
# Original problem
# https://www.hackerrank.com/challenges/flipping-bits
import math
num_bits = 32
T = input()
upper = math.pow(2, num_bits)
for i in xrange(T):
num = input()
print(int(upper - num - 1))
|
9742795be2e86cbfd3e300d3beae55b069531262 | liquidmetal/algorithms | /python/problems/max-robber/solution.py | 243 | 3.515625 | 4 | #!/usr/bin/python
cached = {}
def rob(nums):
if len(nums) == 0:
return 0
if len(nums) == 1:
return nums[0]
p1 = rob(nums[:-2]) + nums[-1]
p2 = rob(nums[:-1])
return max(p1, p2)
print rob([2,4,8,9,9,3])
|
b02178bf6ff976373dd60d648da6b66b26edc7bd | Telurt/python-fundamentos | /Poo/poo_composicao.py | 1,169 | 4.03125 | 4 | """
Relação de composição -> a classe principal (todo) cria
uma instância da outra classe(parte), que se torna parte dela.
Quando a classe principal for destruída, sua instância da outra classe
também será
"""
class Usuario:
def __init__(self, nome):
self.nome = nome
self.enderecos = []
def ... |
d719fab0559e9cf8ef40916a3eec6cea0ac5dd85 | Telurt/python-fundamentos | /funcoes.py | 957 | 3.921875 | 4 | """
Funções
"""
#Media do Telson
# totalNotas = 10 + 7 + 8
# media = totalNotas/3
# print(f'Média do Telson é {media}')
#media da Maria
# totalNotas = 7 + 7 + 5
# media = totalNotas/3
# print(f'Média da Maria é {media}')
# def calcular_media(nota1, nota2, nota3):
# totalNotas = nota1 + nota2 + nota3
# media ... |
e1448d1b43f246b4cbe30483462d2bee55cb20c4 | Telurt/python-fundamentos | /interpolacao_texto.py | 625 | 3.765625 | 4 | carro = "fusca"
preco = 1200.58
#print("carro: " + carro +", preco: " + str(preco)) concatenando o texto com as variaveis, str transforma em string o valor numerico
#Versões mais antigas
#print('carro: %s, preco: %.2f' %(carro,preco)) %s para string %d para numeros inteiros e %f para float .2 para duas casas decimais... |
b6c9c3e78e9072babc666ddb7bf9a4e97bbbd0d6 | Telurt/python-fundamentos | /funcoes_primeira_classe_ordem.py | 935 | 4.4375 | 4 | """
Funções como objeto de primeira classe, são funçòes que se
comportam como qualquer tipo nativo de uma determinada linguagem
"""
def somar(a, b):
return a + b
def subtrair(a, b):
return a - b
# lista = [somar, subtrair]
# for funcao in lista:
# print(funcao(1,2))
# a = somar
# print(a(1,2))
"""
Funçõ... |
96203f09871b480021d4ec8706e217c5e44ddabf | ThaisAngelo119113617/ThaisAngelo_FerreiradeOliveira_P2 | /Q1.py | 1,336 | 3.59375 | 4 | #Questao 1 retificada:
#letra a:
def lerdata(data):
# recebe a data no formato AAAA/MM/DD
lista_split = data.split('/')
dia = int(lista_split[2])
mes = int(lista_split[1])
ano = int(lista_split[0])
data_dic = {'Ano': ano, 'Mes': mes, 'Dia': dia}
return data_dic
#letra b:
def ... |
854838cba4d9a2f2abddfb86bccd1237e9140a4c | jofro9/algorithms | /assignment1/question3.py | 2,458 | 4.1875 | 4 | # Joe Froelicher
# CSCI 3412 - Algorithms
# Dr. Mazen al Borno
# 9/8/2020
# Assignment 1
import math
# Question 3
class UnitCircle:
def __init__(self):
self.TARGET_AREA_ = 3.14
self.RADIUS_ = 1.
self.triangles_ = 4.
self.iter = 0
### member functions for use throughout code ##... |
3f588ddfab202707d5e3208bc505ecc481fc8d99 | tabish606/python | /sum_of_list_element.py | 176 | 3.921875 | 4 | n = int(input("enter the order of list : "))
l = [int(input()) for i in range(n)]
print(l)
sum = 0
for i in l:
sum = sum + i
print("sum of elements = " ,sum) |
731beff49555f623448ce5cb13188586fa850201 | tabish606/python | /comp_list.py | 665 | 4.53125 | 5 | #list comprehension
#simple list example
#creat a list of squares
squares = []
for i in range(1,11):
squares.append(i**2)
print(squares)
#using list comprehension
squares1 = []
squares1 = [i**2 for i in range(1,11)]
print(squares1)
#NOTE : in list comprehension method the data is to be... |
077f37a82c31021b049710be0f385af0a202df8b | tabish606/python | /lamda.py | 610 | 4.15625 | 4 | #normal function
def add(a,b):
return a+b
print(add(4,3))
#lambda expression
add2 = lambda a,b : a+b #lambda function does not need name of function
print(add2(2,3))
multiply = lambda a,b : a*b
print(multiply(2,3))
# is even check
#def is_even(a):
# return a%2 == 0 #it return True if even ... |
0139e339dd0585d64d3c7b5fa32e83b85107f517 | tabish606/python | /funlargenum.py | 213 | 3.84375 | 4 | def checknum(num1,num2):
if num1>num2:
return f"{num1} is large"
return f"{num2} is large"
a = int(input("enter first number : "))
b = int(input("enter second number :"))
print(checknum(a,b)) |
d40b63496cdc9891cd2b64bdcc6d1764fb912b26 | tabish606/python | /dict_practice.py | 535 | 3.8125 | 4 | name = input("what is your name :")
age = input("what is your age ;")
f_name = input("what is your father name : ")
m_name = input("what is your mother name : ")
user_info1 = {}
user_info1["name"] = name
user_info1["age"] = age
user_info2 = {}
user_info2["father name"] = f_name
user_info2['mother name'] = m_... |
9b9e0bd9b4787a24bfc333e1f440ee144073f4bf | tabish606/python | /identity_matrix.py | 645 | 4.15625 | 4 | #print identity matrix for example
# 1 0 0
# 0 1 0
# 0 0 1
m = int(input('enter the order of matrix : '))
#list comprehension
#mat = [[] for i in range (0,m)]
#mat = [[0 for j in range(0,m) for i in range(0,m)]]
#mat = [[int(input()) for i in range(0,m)] for i in range(0,m)]
mat = []
for i in range(0... |
7d6b7ba3ac0bf3ee292dfa0178f6414549ececb3 | ycw786369470/PythonTest | /算法/快速排序/快排.py | 885 | 4.15625 | 4 |
def quick_sort(list1, left, right):
#左右下标
if left >= right:
return None
n = left
m = right
#基准值
base = list1[n]
while n < m:
#从右边往左边找一个比base小的
while list1[m]>=base and n < m:
m -= 1
if n == m:
list1[n] = base
else:
... |
0384000aaaedfd61cf915234cc419e4d9deff281 | kadamsagar039/pythonPrograms | /pythonProgramming/bridgelabzNewProject/calender.py | 653 | 4.15625 | 4 | """Calender Program
This program is used to take month and year from user and print corresponding Calender
Author:
Sagar<kadamsagar039@gmail.com>
Since:
31 DEC,2018
"""
from ds_utilities.data_structure_util import Logic
def calender_runner():
"""
This method act as runner for calender_queue(month, y... |
6affe42bb0be32fb4ca4b64c3687ba59487f91a6 | kadamsagar039/pythonPrograms | /pythonProgramming/bridgelabzNewProject/ordered_list.py | 1,429 | 3.96875 | 4 | """OrderedList File Program
This program is used to take input from file and user can see the content of file
then user can search for data that he is looking for .if the user data is found then
that data will be removed from OrderedList and saves into file and vice versa
and at last user can see the updated content o... |
3d6ceb92d9631fcbfc0d9130e874d162d4b01cfb | kadamsagar039/pythonPrograms | /pythonProgramming/bridgelabzNewProject/Functional_programs/Flipcoin.py | 171 | 4 | 4 | from Utilities import Utility
n=int(input("Enter number of times want to flip a coin:"))
if(n > 0):
Utility.flipCoins(n)
else:
print("Enter positive number...")
|
58c0d5da395a9e55fdfd2f9af8ac73221df25837 | kadamsagar039/pythonPrograms | /pythonProgramming/bridgelabzNewProject/data_structure_util.py | 34,659 | 4.34375 | 4 | from Utilities import Utility
class Node:
"""
This class is used to create Node
"""
def __init__(self, data, next=None):
"""
This is the constructor of Node class .
:param data:user given value will be stored in this variable
:param next: this variable keeps the addres... |
e6fdf0001086a9c7345c4d70199c157549bf5a82 | kadamsagar039/pythonPrograms | /pythonProgramming/bridgelabzNewProject/Algorithm_programs/Anagram.py | 128 | 3.765625 | 4 | from Utilities import Utility
s1=str(input("Enter 1st String:"))
s2=str(input("Enter 2nd String:"))
Utility.checkAnagram(s1,s2) |
d389e3a7ad0bd05f8ec5f50d0c9b3d192859f41a | StudentDevs/examples | /week1/2.py | 1,958 | 4.8125 | 5 | """
Tutorials on sqlite (quickly grabbed off google, there may be better ones):
https://stackabuse.com/a-sqlite-tutorial-with-python/
https://pynative.com/python-sqlite/
"""
import sqlite3
def main():
print('Connecting')
conn = sqlite3.connect(':memory:')
# Configure the connection so we can use the res... |
0b078774ed902e0d5c08bc84fa18b763b3eeb613 | Pranavs05/recruiting-exercises | /inventory-allocator/src/InventoryAllocator.py | 2,514 | 3.640625 | 4 | def allocation(order,inventory_distribution):
"""
:param order: dict
:param inventory_distribution: List[dict]
:return: bestshipment : List[dict]
"""
bestshipment=[] # Stores the final best shipment
temp=dict() ... |
1a44293b978f43028654cadbcf811f77e69ea8b0 | karenarcoverde/copa-do-mundo | /karen-arcoverde.py | 15,997 | 4.03125 | 4 | # Programa karen-arcoverde.py
# Autora: Karen dos Anjos Arcoverde
# Data: 13/06/2018
#
# Programa que contem um banco de dados da Copa do Mundo
#
########################## Funcoes ###################################
def criar_selecao(selecao):
selecoes = open('selecoes.txt','r+')
conteudo_selecoes = selecoes.readl... |
8335057a0bf207e2d95ad0f4d36f924c32501228 | nkacirek1/Algorithms | /Topological_Sort/TopologicalSort.py | 4,197 | 3.8125 | 4 | from Topological_Sort.helpers import graph
def read_topo_sort_from_file(filename):
"""This reads the first line of the file. In a topological sort solution file,
the first line holds the nodes in topological sort order on the first line,
separated by whitespace."""
with open(filename) as f:
... |
a268b45504f17b58cdf3e5537a47f68ec6e9faa3 | 3NCRY9T3R/H4CKT0B3RF3ST | /Programs/Python/bellman_ford.py | 1,438 | 4.1875 | 4 | #This function utilizes Bellman-Ford's algorithm to find the shortest path from the chosen vertex to the others.
def bellman_ford(matrix, nRows, nVertex):
vertex = nVertex - 1
listDist = []
estimation = float("inf")
for i in range(nRows):
if (i == vertex):
listDist.append(0)
... |
d321c892fa7ecac652c4c7e2c7f77e08fb1aa594 | 3NCRY9T3R/H4CKT0B3RF3ST | /Programs/Python/happynumber.py | 778 | 3.90625 | 4 | #isHappyNumber() will determine whether a number is happy or not
def isHappyNumber(num):
rem = sum = 0;
#Calculates the sum of squares of digits
while(num > 0):
rem = num%10;
sum = sum + (rem*rem);
num = num//10;
return sum;
... |
e88ec4fae5e08106e2a7d629541fd769d4fde289 | 3NCRY9T3R/H4CKT0B3RF3ST | /Programs/Python/quick-sort.py | 865 | 3.859375 | 4 | #quick sort
x=[5,7,1,9,2,7,3,6]
lowest=0
highest=(len(x)-1)
def partition(arr,low,high):
i=low-1
pivot=arr[high] #setting the last element as pivot
for j in range(low,high): # j is the loop variable
if arr[j]<pivot:
i=i+1 #i is the count of the greater number , that nee... |
442271b97e0a30d58c9e2a03a58a6e119112524a | jefflike/python_advance | /packet/006.鸭子类型与多态.py | 2,597 | 4.125 | 4 | '''
__title__ = '006.鸭子类型与多态.py'
__author__ = 'Jeffd'
__time__ = '4/14/18 4:39 PM'
'''
'''
tips:鸭子类型就是,当看到一只鸟走起来像鸭子,游泳像鸭子,叫起来也像鸭子
那么这只鸟就可以称作鸭子
python的多态性就是基于鸭子类型的
'''
# 在python中具有同样的方法的类我们可以把他归并成一类事物
class turtle:
def swim(self):
print('turtle swimming')
class duck:
def swim(self):
print('... |
b8558ca601120ba1eedcbcb6db3bdd9478a17b9d | patrickcollins24/python1 | /list2.py | 338 | 3.625 | 4 | power_rangers =[]
#Recruit a group of teenagers with attitude!! - Zordon
# Trini, Billy, Zack, Kim
power_rangers.append("Jason")
power_rangers.append("Trini")
power_rangers.append("Billy")
power_rangers.append("Zack")
power_rangers.append("Kim")
index = 0
while index < len(power_rangers):
print(power_rangers[inde... |
8b8177c2acb317808a8e4808293cdc8b690f230f | NirajPatel07/Algorithms-Python | /insertionSort.py | 376 | 4.125 | 4 | def insertionSort(list1):
for i in range(1,len(list1)):
curr=list1[i]
pos=i
while curr<=list1[pos-1] and pos>0:
list1[pos]=list1[pos-1]
pos-=1
list1[pos]=curr
list1=list(map(int, input("Enter Elements:\n").split()))
print("Before Sorting:\n",list1)
... |
60cdccf5b76829f8a98ae05336df7044550b4392 | SamelaBruna/Curso-Python | /ex024.py | 120 | 3.5 | 4 | cidade = input('Digite a cidade que você nasceu: ')
cidadeSep = cidade.title().split()
print('Santo' in cidadeSep[0]) |
e754bfff41db1996f18d8ad270aaa3481c20a7ee | SamelaBruna/Curso-Python | /ex029.py | 289 | 3.671875 | 4 | print('RADAR ELETRÔNICO! ')
vel = int(input('Velocidade do carro: '))
if vel > 80:
multa = (vel - 80)* 7.00
print('Sua velocidade ultrapassou os 80km/h, você foi multado, sua multa é de R$ {:.2f} '.format(multa))
else:
print('Sua velocidade foi de {}km/h'.format(vel)) |
ac99d81a69d360cd715c4bb6ac10981b150228b7 | SamelaBruna/Curso-Python | /ex010.py | 178 | 3.765625 | 4 | dinheiro = float(input('Quanto você tem de dinheiro na carteira? '))
moedaDesej = 5.06
print('Com {:.2f} você pode comprar US$ {:.2f}'.format(dinheiro,dinheiro/moedaDesej))
|
20318ce25f055480c57aff6bfbd41d7e269a0997 | SamelaBruna/Curso-Python | /ex066v2.py | 163 | 3.859375 | 4 | num = 0
cont = 0
sum = 0
while True:
num = int(input('Digite um numero: '))
if num == 999:
break
cont += 1
sum += num
print(sum)
|
53343a0933a77a1e5b4f2f12fd7c70cd14e8766e | SamelaBruna/Curso-Python | /ex003.py | 202 | 3.890625 | 4 | numeroA = input('Digite o primeiro numero: ')
numeroB = input('Digite o segundo numero: ')
soma = int(numeroA) + int(numeroB)
print('A soma entre {} e {} é: {}'.format(numeroA, numeroB, soma))
|
f349e649d2c87c3891f709ce5b78a7ee26d6b4f5 | SamelaBruna/Curso-Python | /ex082.py | 486 | 3.84375 | 4 | lista = []
listaPar = []
listaImpar = []
while True:
num = int(input('Digite um número: '))
lista.append(num)
opc = str(input('Deseja continuar? [S/N]: ')).upper()
if num % 2 == 0:
listaPar.append(num)
else:
listaImpar.append(num)
while opc != 'S' and opc != 'N':
opc = str(in... |
16ae8195faab5379006baf3be4b26565de85a5dc | SamelaBruna/Curso-Python | /ex009.py | 521 | 4.0625 | 4 | num = int(input('Digite um numero pra ver sua tabuada: '))
print('--------------')
print(' {} x 1 = {}'.format(num, num*1))
print(' {} x 2 = {}'.format(num,num*2))
print(' {} x 3 = {}'.format(num,num*3))
print(' {} x 4 = {}'.format(num,num*4))
print(' {} x 5 = {}'.format(num,num*5))
print(' {} x 6 = {}'.format(n... |
f32deef1d9a71bdad29b89dc928bda1b963b0bb3 | SamelaBruna/Curso-Python | /ex061.py | 241 | 3.890625 | 4 | p1 = int(input('Digite o primeiro termo: '))
r = int(input('Digite a razao: '))
contador = 0
termo = p1
nTermos = 10
while contador <= 10:
print('{}'.format(termo), end=' -> ')
termo += r
contador += 1
print('FIM')
|
cdf399206f9dd21c472bbf08fe51a82fb3a20258 | SamelaBruna/Curso-Python | /ex093.py | 679 | 3.640625 | 4 | jogador = {}
listaGols = []
sumGols = 0
jogador['Nome'] = input('Nome: ')
numPar = int(input(f'Quantas partidas {jogador["Nome"]} jogou? '))
for i in range (0,numPar) :
numGol = int(input(f'Quantos gols na partida {i}? '))
listaGols.append(numGol)
sumGols += numGol
jogador['Gols'] = listaGols... |
e5b1189151ef857dfda9da457356be0cb03c63c6 | kleopatra999/pyxels | /recursive/main.py | 16,081 | 3.609375 | 4 | """
Recursive Shapes 0.2
Ben Fisher, 2007
This program draws recursively-defined shapes.
A blog post at Half Hour Hacks (halfhourhacks.blogspot.com) explains it further.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free ... |
740aa285250f8241c81d301158af8393f2a47c91 | Shiv359/QuickSort | /QuickSort.py | 500 | 3.75 | 4 | def partition(arr,low,high):
i=(low-1)
pivot=arr[high]
for j in range(low,high):
if arr[j]<=pivot:
i=i+1
arr[i],arr[j]=arr[j],arr[i]
arr[i+1],arr[high]=arr[high],arr[i+1]
return(i+1)
def quicksort(arr,low,high):
if len(arr)==1:
return arr
if low<high:
pi=partition(arr,low,high)
quicks... |
c1d5499ca3fc402d84809e7b55db4d5e814b1f69 | yukijuki/DtoCcoin | /DtoCcoin/tagsaction.py | 768 | 3.5 | 4 | from collections import OrderedDict
from utility.printable import Printable
class Tagsaction(Printable):
"""A Tagsaction which can be added to a block in the blockchain.
Attributes:
:sender: The sender of the coins.
:recipient: The recipient of the coins.
:signature: The sig... |
b869e1c798c63937fcee3b818ed0417a8feb00cd | topromulan/SimScreenGrab | /afi_steps_problem_YES20120104.py | 626 | 3.546875 | 4 |
sol2=[[1,1], [2]]
def solution(total_steps):
assert total_steps >= 2
current_step = 2
working_set = sol2
while current_step < total_steps:
old_set = working_set
working_set = []
current_step += 1
for path in old_set:
working_set += [[1] + path]
... |
a96e699c30e9e2bb52b736b068c10ef240940fde | CameronMBrown/Pirple-Python-Course | /uniqueList.py | 1,127 | 3.609375 | 4 | """
Pirple Python Assignment 4 - lists
my instict would be to write a loop that checks for matches at each index then appends to the
correct array. However, at this point in the course loops have not been introduced.
Nicely, the "in" operator results in a much more consice function, however relying apon it for
m... |
12a7bdba654ee30f3e40af39d60aa297c0d8494b | guhan23/zoho1 | /zoho1.py | 438 | 3.796875 | 4 | def printPattern(string1):
m = len(string1)//2
n= len(string1)
newStr = string1[m:] + string1[:m]
for i in range(0,n):
k=n-1-i
while(k):
print(' ',end='')
k-=1
j=0
while(j<i+1):
print(newStr[j],end='')
j+=1
... |
2241b60854f0b0934168686e7307409b23ad992d | naveenramees/python-pro | /greatpowof2.py | 301 | 3.6875 | 4 | w = int(input())
if w < 2:
print "2"
if w >=2 and w < 4:
print "4"
if w >=4 and w < 8:
print "8"
if w >=8 and w < 16:
print "16"
if w >=16 and w < 32:
print "32"
if w >=32 and w < 64:
print "64"
if w >=64 and w < 128:
print "128"
if w >=128 and w < 256:
print "256"
|
6b09250162ecaf282460a6c1dedf1e27a7802937 | naveenramees/python-pro | /countdigit.py | 241 | 3.828125 | 4 | box = int(input("Enter the number:"))
if box < 10:
print "1"
if box > 9 and box < 100:
print "2"
if box > 99 and box < 1000:
print "3"
if box > 999 and box < 10000:
print "4"
if box > 9999 and box < 100000:
print "5"
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.