blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
1010491a2e598931545a8544c9e24f85efa2f061 | AndersonANascimento/curso_python | /ex_agreg.py | 2,135 | 3.5 | 4 | #-*- encoding=UTF-8 -*-
import pandas as pd
import numpy as np
# Dados das eleições primárias dos EUA
eleicoes = pd.read_csv('./datasets/primary-results.csv')
# print eleicoes.head()
# No aggregate, analisamos a coluna 'votes', aplicando 3 funções
# print eleicoes.groupby('candidate').aggregate({'votes':[min, np.mean, max]})
# Onde Hillary Clinton teve 590502 ?
# print eleicoes[eleicoes['votes']==590502]
# print eleicoes.groupby('candidate').aggregate({'votes':[min, np.mean, max], 'fraction_votes':[min, np.mean, max]})
# print eleicoes[eleicoes['fraction_votes']==1]
# print eleicoes[(eleicoes['fraction_votes']==1) & (eleicoes['candidate']=='Hillary Clinton')][-10:]
def votes_filter(x):
return x['votes'].sum() > 1000000
# print eleicoes.groupby('state').filter(votes_filter)
# alabama = eleicoes[eleicoes['state_abbreviation']=='AL']
# print alabama['votes'].sum()
# print eleicoes[(eleicoes['state_abbreviation']=='WI') &
# (eleicoes['candidate']=='Hillary Clinton')]['votes'].sum()
# print eleicoes.groupby(['state_abbreviation', 'candidate'])
# print eleicoes.groupby(['state_abbreviation', 'candidate']).aggregate({'votes':[sum], 'fraction_votes':[sum]})
print eleicoes.groupby(['state', 'party', 'candidate']).aggregate({'votes':[np.sum]}).head(7)
tab = pd.pivot_table(eleicoes, index=['state', 'party', 'candidate'], values=['votes'], aggfunc={'votes':np.sum}).head(7)
print tab
grupo = eleicoes.groupby(['county', 'party'])
print 'type(grupo):', type(grupo)
eleicoes['rank'] = grupo['votes'].rank(ascending=False)
print 'eleicoes["rank"]:', type(eleicoes['rank'])
print eleicoes[eleicoes['county']=='Los Angeles']
grupo = eleicoes.groupby(['state', 'party', 'candidate']).sum()
print grupo.head()
del grupo['fips']
del grupo['fraction_votes']
print grupo.head()
grupo.reset_index(inplace=True)
print grupo.head(10)
grupo['rank'] = grupo.groupby(['state', 'party'])['votes'].rank(ascending=False)
print grupo.head(7)
print pd.pivot_table(grupo, index=['state','party','candidate'],values=['rank','votes']).head()
print grupo[grupo['rank']==1].head()
print grupo[grupo['rank']==1]['candidate'].value_counts() |
67ad34d4159f06772fbd39e04165ba2a320c659e | akalya23/gkj | /71.py | 68 | 3.6875 | 4 | n2=input()
a2=n2[::-1]
if(n2==a2):
print('yes')
else:
print('no')
|
6c0dfa87461d062d42a0904e8752309f6c98be50 | charlesjhlee/mitx_6.00.1x | /gcdIter.py | 506 | 3.96875 | 4 |
def gcdIter(a, b):
'''
a, b: positive integers
returns: a positive integer, the greatest common divisor of a & b.
'''
# Your code here
smallest = min(a,b);
gcd = 0;
if (a%smallest == 0 and b%smallest == 0):
return smallest;
while (smallest > 1):
if (a%smallest == 0 and b%smallest == 0):
gcd = max(gcd,smallest);
smallest = smallest - 1;
else:
smallest = smallest - 1;
return gcd |
1a0e4c19544437c449721380cf18b7291c3a1ae4 | KKira/KKira.github.io | /static/images/euler/code/advent/2019/day1.py | 419 | 3.59375 | 4 | def readfile():
with open("day1.txt") as fp:
contents = fp.read().strip()
all_rows = []
for row in contents.split('\n'):
all_rows.append(int(row))
return all_rows
instructions = readfile()
total_fuel = 0
for module_mass in instructions:
fuel = int(module_mass/3) - 2
total_fuel += fuel
while fuel > 0:
fuel = int(fuel/3) - 2
if fuel < 0:
continue
else:
total_fuel += fuel
print(total_fuel) |
81a6cd972a43e3c8068b4966c4318cabb227b28e | 8v10/eprussas | /1_LogicaDeProgramacao/0_Python/1_Python_Parte1/1 - Introdução/5 - Math.py | 63 | 3.5625 | 4 | x=5
y=10
print (x+y)
print (x*y)
print (y-x)
print (y/x)
|
7060ad71868ff7c9cc5346db70d88629f242f38a | UoLPythonGroup/training | /PROJECTS/benchmarking/Parallelising/Parallel(shared_memory)_MC_calculation_of_pi.py | 1,157 | 3.53125 | 4 | from multiprocessing import Process,Queue,Manager,Value,Lock
from random import random
from sys import argv
def get_pi(N,pi,lock):
"""Monte Carlo method of calculating pi the first argument is the number of samples to use, the second one in this case it for the return value."""
n=0
while n<N:
x=random()
y=random()
n+=1
if x*x+y*y<=1.0:
with lock: #this bit is very important, it makes sure that two threads don't access pi at the same time.
pi.value+=1
if __name__ == '__main__':#needs to be used because on widows all processes start from the beginning due to the lack of the fork() function. This ensures on the master process runs this bit
N=int(argv[1])#Number of samples
manager = Manager()
pi=manager.Value('i',0)
lock=Lock()
cores=int(argv[2])#Number of cores to use
p=[]#Empty lists for processes
for i in range(0,cores,1):#start all processes
p.append(Process(target=get_pi,args=(N/cores,pi,lock)))#create the process
p[i].start()#start the process
for i in range(0,cores,1):
p[i].join()#wait until all processes get to here
print 4.0*float(pi.value)/float(N)#print the average
|
74d11483870ca425de5d9c5150cfbe55e18900d0 | Rafaellinos/learning_python | /exercises/fibonacci_numbers.py | 1,338 | 4.09375 | 4 | from time import time
def performance(func):
def wrap_func(*args, **kw):
t1 = time()
result = func(*args, **kw)
t2 = time()
print(f'took {t2-t1} s')
return result
return wrap_func
# not a generator, just prints the number
@performance
def fib(n):
a = 1
b = 0
for x in range(n+1):
if x < 2:
print(x)
else:
tmp = a
a = a+b
print(a)
b = tmp
### generator using yield, return a for each next()
@performance
def fib2(n):
a = 0
b = 1
for i in range(n):
yield a
#when the function has yield, is that number that the generator will return
tmp = a
a = b
b = tmp + b
# not a generator, just return a list
@performance
def fib3(n):
fibs = [0,1]
for i in range(n):
fibs.append(fibs[-2] + fibs[-1])
return fibs
fib(2000)
for x in fib2(2000):
x = x
fib3(2000)
"""
the advantage of the generator without list is that the numbers isn't store in memory,
for each next() the previous number is replaced for the new one.
If you give a huge amount of number to fib genator, the performance will be better.
Or not??
output:
took 0.11019325256347656 s
took 3.337860107421875e-06 s
took 0.0008633136749267578 s
"""
|
372162f426507a981eec9e7e85425b2314f68009 | Sebas1130/Python_Ejemplos | /proyecto4/stack.py | 1,033 | 3.953125 | 4 | """
Code used for the class 'Crear un stack'.
"""
class Node:
def __init__(self, data=None):
self.data = data
self.next = None
class Stack:
def __init__(self):
self.top = None
self.size = 0
def push(self, data):
""" Appends an element on top. """
node = Node(data)
if self.top:
node.next = self.top
self.top = node
else:
self.top = node
self.size += 1
def pop(self):
""" Removes and returns the element on top. """
if self.top:
data = self.top.data
self.size -= 1
if self.top.next:
self.top = self.top.next
else:
self.top = None
return data
else:
return "The stack is empty"
def peek(self):
if self.top:
return self.top.data
else:
return "The stack is empty"
def clear(self):
while self.top:
self.pop() |
ba78aaa5b8ed535d6ae91aeea2243f242ceafe87 | as1014/Daily-Code_Problem | /Problem1.py | 961 | 3.78125 | 4 | #problem 1
#Given a list of numbers and a number k
#Return whether any two numbers from the list add up to k
#test values
l = [15, 13, 10 , 7]
k = 17
#get length of list
l_len = len(l)
def sum(lst, k):
#loop through the list
for i in range(l_len):
lst_len = len(lst)
base_num = lst[0]
sum_num = 0
#pop the first item in list
lst.pop(0)
#refresh the list without the first one
lst_len = len(lst)
for j in range(lst_len):
sum_num = base_num + lst[j]
# print(base_num, lst, lst_len, sum_num)
if sum_num == k:
#return the values used to match the k value
print("there's a match with k = ", k, "and ", base_num, " + ", lst[j])
return base_num, lst[j]
#return false if nothing matches
return False
r = sum(l, k)
if not r:
print("No matches found!")
else:
print("End!") |
841e146c2274841d4722abe24376b748e69a3397 | JLowborn/CS50 | /pset6/mario/less/mario.py | 274 | 3.953125 | 4 | #!/usr/bin/env python3
# -*- encoding: utf-8 -*-
from cs50 import get_int
from cs50 import get_string
height = 0
while height < 1 or height > 8:
height = get_int("Height: ")
for i in range(height):
print(f" " * (height - 1 - i), end="")
print(f"#" * (i + 1)) |
9e4661e4f27f1d713c65923e0a5e3fd46a098aaf | sdzx1985/Project | /Practice/Web_Scraping_Practice/Web_Scraping_Practice #1/4_Re.py | 760 | 3.578125 | 4 | import re
p = re.compile("ca.e")
# . (ca.e) : one word > care, cafe, case | caffe
# ^ (^de) : start point > desk, destinatio | fade
# $ (se$) : end point > case, base | face
def print_match(m):
if m:
print(m.group()) # matchs string
print(m.string) # inserted string
print(m.start()) # matched string's starting index
print(m.end()) # matched string's ending index
print(m.span()) # matched string's starting / ending index
else:
print("No matching")
# 1.
# m = p.match("case") # match : check from the start
# print_match(m)
# 2.
# m = p.search("good care") # search : check among the string
# print_match(m)
# 3.
lst = p.findall("careless") # findall : return every matched as a list
print (lst)
|
893e4306cb5d7254f573bd82d1f07d1e97d745b1 | jlittle576/jlittle576.github.io | /articles/data_parsing/technique_examples/string_methods/string_methods_demo.py | 979 | 3.640625 | 4 | # File are arrays of sting, so naturally,
# the built in method for arrays any strings are critical to data file parsing
# String methods
# there is no str.remove(), use replace instead
print '233.4, 232.33, 342.34'.replace(' ', '')
# >>> 233.4,232.33,342.34
# line from files will have trailing EOL and often padded space chars
# tis can be removes with str.rstrip()
print ' data = 2,3,4,5 \n'.rstrip()
# >>> data = 2,3,4,5
# lstrip() is the same but for leading chars
print ' data = 2,3,4,5'
# >>> data = 2,3,4,5
# lines can be split into arrays using split()
line = '233.4,232.33,342.34'
print line.split(',')
# >>> ['233.4', '232.33', '342.34']
# string can stacked to perform several operation at once
line = 'center_of_mass = 1.3, 23.4, 23.4 \n'
print line.rstrip().split('=')[1].lstrip().split(',')
# >>> ['1.3', ' 23.4', ' 23.4']
# using split, strip and remove in combinatoin, we get the line "clean"
line = 'center_of_mass = 1.3, 23.4, 23.4 '
|
cd60b5cd27ee91f01b075c050a06b1d76a52fa0d | oliveirajonathas/python_estudos | /pacote-download/pythonProject/exercicios_python_guanabara/ex011.py | 293 | 3.78125 | 4 | largura = float(input('Qual a largura, em metros, da parede? '))
altura = float(input('Qual a altura, em metros, da parede? '))
area = largura * altura
litros_de_tinta = area/2
print('Você precisará de {} litros de tinta para pintar a sua parede de {}m²'.format(litros_de_tinta, area))
|
bd9e96e3af0016a1302c469b1ba25edebfa79dad | roguewei/python_yspc | /demo/spider.py | 2,366 | 3.640625 | 4 | # 引入Python内置的http操作库
from urllib import request
# 引入re正则表达式包
import re
# 爬虫框架可以使用BeautifulSoup,Scrapy
class Spider:
# 需要爬取的网页地址
url = 'https://www.huya.com/g/lol'
root_pattern = '<span class="txt">([\s\S]*?</span>[\s]*<span class="num">[\s\S]*?</span>[\s]*)</span>'
name_pattern = '<i class="nick" title="[\s\S]*?">([\s\S]*?)</i>'
num_pattern = '<span class="num">[\s]*<i class="num-icon"></i>[\s]*<i class="js-num">([\s\S]*?)</i></span>'
# 定义私有方法(获取网页内容)
def __fetch__content(self):
# request.urlopen用以发送http请求
r = request.urlopen(Spider.url)
htmls = r.read()
htmls = str(htmls, encoding='utf-8')
return htmls
# 定义私有方法(分析网页内容)
def __analysis(self, htmls):
# 根据正则获取爬取页面的需要数据
root_html = re.findall(Spider.root_pattern, htmls)
anchors = []
for x in root_html:
root_name = re.findall(Spider.name_pattern, x)
root_num = re.findall(Spider.num_pattern, x)
anchor = {'name': root_name, 'num': root_num}
anchors.append(anchor)
return anchors
# 精简爬取得数据
def __refine(self, anchors):
l = lambda anchor: {
'name': anchor['name'][0].strip(),
'num': anchor['num'][0]
}
return map(l, anchors)
# 排序
def __sort(self, anchors):
anchors = sorted(anchors, key=self.__sort_seed, reverse=True)
return anchors
def __sort_seed(self, anchor):
r = re.findall('\d*', anchor['num'])
number = float(r[0])
if '万' in anchor['num']:
number *= 10000
return number
# 展示数据
def __show(self, anchors):
# for anchor in anchors:
# print(anchor['name'] + '-------' + anchor['num'])
for rank in range(0, len(anchors)):
print('rank: ' + str(rank + 1) + '---' + anchors[rank]['name'] + '---' + anchors[rank]['num'])
def go(self):
hails = self.__fetch__content()
anchors = self.__analysis(hails)
anchors = list(self.__refine(anchors))
anchors = self.__sort(anchors)
self.__show(anchors)
spider = Spider()
spider.go()
|
a95043d658ea4ec83ef5fa3032b642e004cb948c | morristech/cipherama | /substitution.py | 1,307 | 3.734375 | 4 | import sys
import argparse
alphabet = ["a","b","c","d","e","f","g","h","i","j","k","l","m",
"n","o","p","q","r","s","t","u","v","w","x","y","z",
" ",",", "!","?", ".", "'", "\n", ";",":", "’"]
class SubstitutionCipher:
def __init__(self, key, offset = 0):
self.original_alphabet = alphabet
self.key = key
self.cipher_alphabet = []
#add the key as the first letters to scramble cipher alphabet
tmp_alphabet = self.original_alphabet.copy()
for letter in key:
if letter in tmp_alphabet:
tmp_alphabet.remove(letter)
if not letter in self.cipher_alphabet:
self.cipher_alphabet.append(letter)
self.cipher_alphabet.extend(tmp_alphabet)
def encrypt_message(self, message):
message = message.lower()
encrypted = ""
for letter in message:
index = self.original_alphabet.index(letter)
encrypted += self.cipher_alphabet[index]
return encrypted
def decrypt_message(self, message):
decrypted = ""
message = message.lower()
for letter in message:
index = self.cipher_alphabet.index(letter)
decrypted += self.original_alphabet[index]
return decrypted
|
e338f16108191b9066f7047b06f3dd5aa6f1196d | mkskyring/PIAIC-136742- | /Numpy _Task1.py | 2,949 | 4.40625 | 4 | #!/usr/bin/env python
# coding: utf-8
# # Reading Recipes
#
# Note: Data file is recipes.csv Attached with jupyter notebook
1. Start by importing NumPy as np
# In[3]:
#type your code here
import numpy as np
# 2. All of Alize’s recipes call for milk, eggs, sugar, flour, and butter. For example, her cupcake recipe calls for:
#
# Flour Sugar Eggs Milk Butter 2 cups 0.75 cups 2 eggs 1 cups 0.5 cups Create a NumPy array that represents this data. Each element should be a number (i.e., 2 for “2 cups”). Save this array as cupcakes.
# In[4]:
#type your code here
##creating array for ingrediants of cupcakes :
import numpy as np
cupcakes = np.array([2, 0.75, 2, 1, 0.5])
cupcakes
# 3. Alize’s assistant has compiled all of her recipes into a csv (comma-separated variable) file called recipes.csv. Load this file into a variable called recipes.
#
# ###########Explore yourselves how to load a csv file in numpy#######
# In[6]:
#type your code here
import pandas as pd
recipes = pd.read_table('recipes.csv', sep=',',header=None)
# 4.Display recipes using print.
# Display recipes using print.
#
#
# Each row represents a different recipe. Each column represents a different ingredient.
#
# Recipe Cups of Flour Cups of Sugar Eggs Cups of Milk Cups of Butter
#
# Cupcakes … … … … …
#
# Pancake … … … … …
#
# Cookie … … … … …
#
# Bread … … … … …
# In[7]:
#type your code here
recipes
# 5.The 3rd column represents the number of eggs that each recipe needs.
#
# Select all elements from the 3rd column and save them to the variable eggs.
# In[8]:
#type your code here
## here eacheggs contains al elements of 3rd coloumn :
eggs= recipes[recipes.columns[2]]
# 6.Which recipes require exactly 1 egg? Use a logical statement to get True or False for each value of eggs.
# In[9]:
eggs == 1
# 7.Alize is going to make 2 batches of cupcakes (1st row) and 1 batch of cookies (3rd row).
#
# You already have a variable for cupcakes. Create a variable for cookies with the data from the 3rd row.
#
# In[17]:
#type your code here
## here we have variable cookies !
cookies = recipes[2:3]
cookies
# 8.
# Get the number of ingredients for a double batch of cupcakes by using multiplication on cupcakes. Save your new variable to double_batch.
# In[20]:
#type your code here
## for doubling cupcakes we use function 'multiply' :
double_batch = np.multiply(cupcakes, cupcakes)
double_batch
# 9.
# Create a new variable called grocery_list by adding cookies and double_batch.
# In[22]:
#type your code here
## for adding we simply perform addition !
grocery_list = cookies + double_batch
grocery_list
# In[ ]:
|
27e44127f2ab7bbfd56eef0a227d0c4d167c316e | dexapier/python-regex | /address_book.py | 2,829 | 4.375 | 4 | # coding:"utf-8"
# \w -> cualquier unicode letra por letra
# \W -> lo que no sea unicode
# \s -> whitespace, space, tabs, etc
# \S -> lo que no sea whitespace, tabs, space, etc
# \d -> número 0 al 9
# \D -> lo que no sea número
# \b -> extremo de la palabra
# \B -> no en el extremo de la palabra
# {3} -> cuenta exactamente 3 ocurrencias del patron
# {,3} -> cuenta de 0 a 3 ocurrencias del patron, igual que slicing
# ? -> opcional, de 0 a 1 vez
# * -> al menos 0 veces
# + -> al menos una vez
# [] -> define un set
# [a-z] -> set con rango, vale para minusculas, mayusculas y números
# [^a-d] -> el techito implica no encontrar esos carateres
# Flags, pasadas como parametro extra
# | -> permite pasar más flags flags
# re.IGNORECASE, re.I -> ignora mayusculas y minusculas
# re.VERBOSE , re.X-> multiple lines
import re
with open("names.txt", encoding="utf-8") as names_file:
data = names_file.read()
last_name = r'Love'
first_name = r'Kenneth'
#Python offers two different primitive operations based on regular expressions: re.match() checks for a match only at the beginning of the string, while re.search() checks for a match anywhere in the string
# Match encuentra la primera ocurrencia del caso
print(re.match(last_name, data))
# Search busca en cualquier posición del string
print(re.search(first_name, data))
# buscamos un patron específico de números, retornamos la primera ocurrencia
print(re.search(r'\d\d\d-\d\d\d\d', data))
# repetimos pero con tamaños variables y parentesis opcionales, findall encuentra todos
print(re.findall(r'\(?\d{3}\)?-?\s?\d{3}-\d{4}', data))
# Buscamos nombres de manera específica
print(re.search(r'\w+, \w+', data))
# Encuentra todos los nombres pero también las profesiones
print(re.findall(r'\w+, \w+', data))
# Encuentra también los nombres sin apellido
print(re.findall(r'\w*, \w+', data))
# Encuentra los emails de manera burda
# [todos los álpha, los números, los simbolos "+", "-" y "." ]en varias ocurrencias @ [lo mismo pero sin "-"]
print(re.findall(r'[-\w\d+.]+@[-\w\d.]+', data))
# Encuentra todas las ocurrencias de la palabra treehouse aunque está este en mayus o minus
print(re.findall(r'\b[trehous]{9}\b', data, re.I))
# Todos los dominios de email pero sin la extension gov si la encuentra
print(re.findall(r"""
\b@[-\w\d.]* # Primero un limite de palabra, luego un "@" y por último cualquier cantidad de palabras
[^gov\t]+ # Ignora una o mas instancias de las letras "g","o" o "v" y los tabs
\b
""" , data, re.VERBOSE | re.I))
# Nombres y trabajo
print(re.findall(r"""
\b[-\w]*, # limite, 1+ guion o caracter y una coma
\s # 1 espacio, usamos este ya que re.X ignora los " " que no están en sets
[-\w ]+ # 1+ guion y caracter y un espacio explícito
[^\t\n] # ignora tabs y nuevas lineas
"""
, data, re.X ))
|
407c3708cf5ac04bbd1013c529883e6f7b75919d | krenevych/algo | /source/T3_Find_Search/P1_Search/L6_binary_continuous.py | 1,151 | 3.65625 | 4 | import math
def binary_continuous(f, c, a, b):
""" Для монотонної на відрізку [a, b] функції f розв'язує рівняння
f(x) = c
:param f: Монотонна функція
:param c: Шукане значення
:param a: Ліва межа проміжку на якому здійснюється пошук
:param b: Права межа проміжку на якому здійснюється пошук
:return: Розв'язок рівняння
"""
left = a # лівий кінець відрізка
right = b # правий кінець відрізка
m = (left + right) / 2.0 # середина відрізка [left,right]
while left != m and m != right:
if f(m) < c:
left = m # [left,right] = [x,right]
else:
right = m # [left,right] = [left,x]
m = (left + right) / 2.0 # середина відрізка [left,right]
return left
if __name__ == "__main__":
print(binary_continuous(lambda x: math.tan(x) - 2.0 * x, 0, 0.5, 1.5))
|
2c12e848f86cf9bc4c16264040f5f9bc712d5fe6 | jack-x/HackerEarthCode | /E_BobAnIdiot.py | 728 | 3.609375 | 4 |
def main():
N=int(input())
alphadict = dict()
for character in 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz':
alphadict[character] = character
for x in range(0,N):
i=input()
inp = i.upper()
inp2 = i.lower()
temp = alphadict[inp[0]]
alphadict[inp[0]] = alphadict[inp[2]]
alphadict[inp[2]] = temp
temp = alphadict[inp2[0]]
alphadict[inp2[0]] = alphadict[inp2[2]]
alphadict[inp2[2]] = temp
alphadict2=dict()
for key in alphadict.keys():
alphadict2[alphadict[key]] = key
try:
inp = input()
while inp!='':
for s in inp:
if(s == ' '):
print(' ',end='')
else:
print(alphadict2[s],end='')
inp=input()
except:
return
if __name__ == "__main__": main()
|
cfee29e770dfe259a68da4c0e125d64205b213f5 | leobalestra/pyhton-aulas-alura | /AulasPython/ContaCorrente.py | 855 | 3.828125 | 4 | class ContaCorente:
def __init__(self, codigo):
self.codigo = codigo
self.saldo = 0
def deposita(self, valor):
self.saldo += valor
def __str__(self):
return (f"Código: {self.codigo} saldo: {self.saldo}")
conta_leo = ContaCorente(292)
conta_lari = ContaCorente(666)
conta_lari.deposita(1000)
contas = [conta_leo, conta_lari]
for conta in contas:
print(conta)
print("\n***Salário de 100 pila caiu***")
def deposita_todas_contas(contas):
for conta in contas:
conta.deposita(100)
contas = [conta_leo, conta_lari]
deposita_todas_contas(contas)
for conta in contas:
print(conta)
#tuplas: imutáveis
leonardo = ('Leonardo', 21, 1998)
daniele = ('Daniele', 18, 2001)
#lista de tuplas
usuarios = [leonardo, daniele]
print(usuarios)
usuarios.append(('Paulo', 20, 2000))
print(usuarios) |
ab4864820d500672d1db47af423140366ccc9e5d | weltonvaz/Zumbis | /exercicio02_welton_02.py | 326 | 3.671875 | 4 | # coding:utf8
#
# Determine se um ano é bissexto. Verifique no Google como fazer isso...
#
import os
os.system("clear") # Limpando a tela
bissexto = int(input("Digite o Ano com 4 digitos, ex: 1968 : "))
if bissexto % 400 == 0 or bissexto % 4 == 0:
print ("Este ano é bissexto")
else:
print ("Este ano NÃO é bissexto")
|
b6bb619cf72498f3da1dbb3597f012024bd993bc | IrinaVladimirTkachenko/Python_IdeaProjects_Course_EDU | /Python3/ClassMethods/methods.py | 1,327 | 3.890625 | 4 | #class Car:
# wheels_number = 4
# def __init__(self, name, color, year, is_crashed):
# self.name = name
# self.color = color
# self.year = year
# self.is_crashed = is_crashed
#def drive(self, city):
# print(self.name + ' is driving to ' + city)
#def change_color(self, new_color):
# self.color = new_color
#opel_car = Car('Opel Tigra', 'grey', '1999', True)
#opel_car.drive('London')
#mazda_car = Car('Mazda CX7', 'black', '2014', False)
#mazda_car.drive('Paris')
#mazda_car.change_color('yellow')
#print(mazda_car.color)
#print(opel_car.drive)
#print(opel_car.wheels_number)
#print(opel_car.name)
#print(opel_car.color)
#print(opel_car.year)
#print(opel_car.is_crashed)
class Circle:
pi = 3.14
def __init__(self, radius=1):
self.radius = radius
self.circumference = 2 * Circle.pi * self.radius
def get_area(self):
return self.pi * (self.radius ** 2)
#def get_circumference(self):
# return 2 * self.pi * self.radius
circle_1 = Circle(5)
print(circle_1.get_area())
print(circle_1.circumference)
#print(circle_1.get_area())
#circle_2 = Circle(3)
#print(circle_2.get_area())
#print(circle_2.get_circumference())
#circle_3 = Circle(5)
#circle_area = circle_3.get_area()
#print(circle_area)
#print(circle_3.get_circumference()) |
f1ab95f58476c480e8ef999b492265356dea98ad | bgoonz/UsefulResourceRepo2.0 | /MY_REPOS/DATA_STRUC_PYTHON_NOTES/python-prac/projects-DS/data_struct_and_algo/max_in_array.py | 219 | 3.796875 | 4 | def find_max(arr, l):
temp = arr[0]
for i in range(l):
if temp < arr[i]:
temp = arr[i]
return temp
arr = [1, 2, 3, 4, 5, 6, 55, 6, 7, 8, 8, 8]
max = find_max(arr, len(arr))
print(max)
|
180d63381575ad8399a416e91c868e2036bde8b9 | aryanvichare/eco.life | /basic.py | 1,523 | 3.53125 | 4 | import matplotlib.pyplot as plt
import numpy as np
from sklearn import datasets, linear_model
from sklearn.metrics import mean_squared_error, r2_score
# Load the dataset
# emissions_X, emissions_y = datasets.load_emissions(return_X_y=True)
f = open("emissions.csv")
f.readline() # skip the header
data = np.load(f)
emissions_X = data[:, 1:]
emissions_y = data[:, 0]
# Use only one feature
emissions_X = emissions_X[:, np.newaxis, 2]
# Split the data into training/testing sets
emissions_X_train = emissions_X[:-20]
emissions_X_test = emissions_X[-20:]
# Split the targets into training/testing sets
emissions_y_train = emissions_y[:-20]
emissions_y_test = emissions_y[-20:]
# Create linear regression object
regr = linear_model.LinearRegression()
# Train the model using the training sets
regr.fit(emissions_X_train, emissions_y_train)
# Make predictions using the testing set
emissions_y_pred = regr.predict(emissions_X_test)
# The coefficients
print('Coefficients: \n', regr.coef_)
# The mean squared error
print('Mean squared error: %.2f'
% mean_squared_error(emissions_y_test, emissions_y_pred))
# The coefficient of determination: 1 is perfect prediction
print('Coefficient of determination: %.2f'
% r2_score(emissions_y_test, emissions_y_pred))
# Plot outputs
plt.scatter(emissions_X_test, emissions_y_test, color='black')
plt.plot(emissions_X_test, emissions_y_pred, color='blue', linewidth=3)
plt.xticks(())
plt.yticks(())
plt.show() |
f39969d020ebf95d8ce11ce09166b8ecc65a726b | qlccks789/Web-Study | /17_python/part3-control/test04_for3.py | 214 | 3.546875 | 4 | # 구구단
index = [1, 2, 3, 4, 5, 6, 7, 8, 9]
for i in index[1:]:
for j in index:
print(str(i) + " * " + str(j) + " = " + str(i*j))
print()
"""
2 * 1 = 2
2 * 2 = 4
....
9 * 8 = 72
9 * 9 = 81
"""
|
49760cdbfea03ddfad8965303863ac1761bb1577 | ramondfdez/57Challenges | /2_Calculations/8_PizzaParty.py | 1,114 | 4.65625 | 5 | # Division isn’t always exact, and sometimes you’ll write
# programs that will need to deal with the leftovers as a whole
# number instead of a decimal.
# Write a program to evenly divide pizzas. Prompt for the
# number of people, the number of pizzas, and the number of
# slices per pizza. Ensure that the number of pieces comes out
# even. Display the number of pieces of pizza each person
# should get. If there are leftovers, show the number of leftover
# pieces.
#
# Example Output
# How many people? 8
# How many pizzas do you have? 2
# 8 people with 2 pizzas
# Each person gets 2 pieces of pizza.
# There are 0 leftover pieces.
import math
people = input("How many people? ")
pizzas = input("How many pizzas do you have? ")
slices_per_pizza = input("How many slices per pizza? ")
print( people + " people with " + pizzas + " pizzas")
slices = int(pizzas) * int(slices_per_pizza)
slice_per_person = math.floor(int(slices) / int(people))
rest = slices % slice_per_person
print("Each person gets " + str(slice_per_person) + " pieces of pizza. ")
print("There are " + str(rest) + " leftover pieces. ") |
62bcf01bc4aedf276fff05e52a684ba789d35e26 | youkaede77/Data-Structure-and-Algorithm | /剑指offer/32. 从上到下打印二叉树(不分行).py | 1,440 | 3.859375 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
# author: wdf
# datetime: 2/9/2020 1:23 PM
# software: PyCharm
# project name: Data Structure and Algorithm
# file name: 32. 从上到下打印二叉树(不分行)
# description: 层序遍历、不分行
# usage:
# 队列实现层序遍历
class Node(object):
'''节点类 '''
def __init__(self, value=None, lchild=None, rchild=None):
self.value = value
self.lchild = lchild
self.rchild = rchild
def layer_order(root):
# 层序遍历,不分行,队列实现
if root is None:
return
queue = [root] # python 可以用列表实现queue
while queue:
node = queue.pop(0)
print(node.value, end=' ')
# 每访问一个节点,都先把他的左右子节点放进队列
if node.lchild is not None:
queue.append(node.lchild)
if node.rchild is not None:
queue.append(node.rchild)
def main():
root = Node('D',
Node('B', Node('A'), Node('C')),
Node('E', rchild=Node('G', Node('F'))))
print('层序遍历,不分行', end=' ')
layer_order(root)
print()
root = Node('D',
Node('B', Node('A')),
Node('E', rchild=Node('G')))
print('层序遍历,不分行', end=' ')
layer_order(root)
if __name__ == '__main__':
main()
|
171e5c83d3a61c95eb52ab73f82ece6d517086f8 | eng-lenin/Python | /ex13.py | 165 | 3.65625 | 4 | s=float(input('Digite o salário do funcinário: R$ '))
r=s*1.15
print('O funcionário recebia {} R$, com o reajuste passou a receber {:.2f} R$.'.format(s,r)
) |
c5b67543f2bf0db5ca426c7ce655426874b2b006 | fanliugen/Hello-world | /generatorTest.py | 282 | 3.796875 | 4 | #yield 装入数据,产出generator object,使用next释放
def fun3():
for i in range(1,5):
yield i
if __name__ == '__main__':
gob = fun3()
print(gob)
print(next(gob))
print(next(gob))
print(next(gob))
print(next(gob))
print(next(gob)) |
236d4a267f73cba94998aae8f9585877a28157f2 | mabdulul/DigitalCrafts_Week2 | /ex3.py | 416 | 4.03125 | 4 | '''Write a letter_histogram program that asks the user for input, and prints a dictionary
containing the tally of how many times each letter in the alphabet was used in the word. '''
words = input(" The words? ").upper()
letters_count_dict = {}
count = 0
for i in words:
if not i in letters_count_dict:
letters_count_dict[i] = 1
else:
letters_count_dict[i] += 1
print(letters_count_dict)
|
70e03ad7088f74beeea70adb0fff694fb8131da0 | bradelement/coding_exercise | /leetcode-master/060/main.py | 606 | 3.6875 | 4 | import math
class Solution(object):
def get_permutation(self, n, k, arr):
if k == 0: return ''.join(arr)
prev = math.factorial(n-1)
cur = k / prev
return arr[cur] + self.get_permutation(n-1, k%prev, arr[0:cur] + arr[cur+1:])
def getPermutation(self, n, k):
"""
:type n: int
:type k: int
:rtype: str
"""
return self.get_permutation(n, k-1, [str(i+1) for i in xrange(n)])
s = Solution()
for i in xrange(6):
print s.getPermutation(3, i+1)
|
cb136aee077e057fdcbdb552ef8714413dcd0bc1 | songyqdevote/Python-100-Days-Practisetice | /Day01-15/code/Day08/printnum2.py | 718 | 3.65625 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
# @FileName :printnum2.py
# @Time :2021/6/14 20:29
# @Author :宋业强
import threading
import time
def threada():
with con:
for i in range(1, 10, 2):
time.sleep(0.2)
print(threading.current_thread().name, i)
con.wait()
con.notify()
def threadb():
with con:
for i in range(2, 10, 2):
time.sleep(0.2)
print(threading.current_thread().name, i)
con.notify()
con.wait()
if __name__ == "__main__":
con = threading.Condition()
ta = threading.Thread(None, threada)
tb = threading.Thread(None, threadb)
ta.start()
tb.start()
|
e24b614100421b1ab4e8774f3204b8636e641abd | hack1973/web-caesar | /caesar.py | 1,243 | 4.0625 | 4 | def alphabet_position(letter):
alphabet = 'abcdefghijklmnopqrstuvwxyz'
letter_index = ''
letter = letter.lower()
for char in alphabet:
letter_index = alphabet.index(letter)
if char == letter:
return letter_index
return letter_index
#print(alphabet_position("Z"))
def rotate_character(char, rot):
alphabet = 'abcdefghijklmnopqrstuvwxyz'
upper_alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
is_alpha = "False"
is_upper = "False"
index = 0
new_index = 0
if char.isalpha() == False:
print
return char #,("not alpha")
else:
if char.isupper() == True:
index = alphabet_position(char)
new_index = (index + rot) % 26
rotate_character = upper_alphabet[new_index]
return rotate_character #,("is upper"), index, new_index
else:
index = alphabet_position(char)
new_index = (index + rot) % 26
rotate_character = alphabet[new_index]
return rotate_character #,("is lower"), index, new_index
def encrypt(message, rot):
encrypted = ''
for char in message:
encrypted = encrypted + rotate_character(char, rot)
return encrypted #,text, rot
|
8288f649569bcc95c5f80631e8d8b4648f369663 | H-Bouhlel/H-Bouhlel | /Memoire_Haithem/Code/file.py | 455 | 3.515625 | 4 | import csv
def create_file(path,file_name):
with open(path+file_name, mode='w',newline='') as file:
writer = csv.writer(file, delimiter=';', quotechar='"', quoting=csv.QUOTE_MINIMAL)
return
def add_row(path,file_name,col1,col2,col3):
with open(path+file_name, mode='w',newline='') as file:
writer = csv.writer(file, delimiter=';', quotechar='"', quoting=csv.QUOTE_MINIMAL)
writer.writerow([col1,col2,col3])
return |
ffac43e3d69573dfd688d316883eab54b118c3e1 | xiaokongkong/some-tricks-about-python | /刷题/剑指offer/字符串/翻转单词顺序 VS 左旋转字符串.py | 517 | 4.25 | 4 | # 翻转单词顺序
# 要求:翻转一个英文句子中的单词顺序,标点和普通字符一样处理
# 思路: Python中字符串是不可变对象,不能用书中的方法,可以直接转化成列表然后转回去
def reverse_words(sentence):
tmp = sentence.split()
return ''.join(tmp[::-1])
# 左旋转字符串
# 思路: 把字符串的前面的若干位移到字符串的后面
def rotate_string(sentence,n):
if not sentence:
return ''
return sentence[n:] + sentence[:n] |
06c541c88b5c467465be4e0aa870abc49acb5081 | A-fil/repeating_algorithms_python | /sorting/heap_sort.py | 1,059 | 3.984375 | 4 | # IN PROGRESS
from typing import List, Any
from test_data.sorting_data import UNSORTED_NUMERICAL_SEQUENCE
from utils.array_utils import swap
def parent_index(index: int):
return int((index - 1) / 2)
def left_index(index: int):
return 2 * index + 1
def right_index(index: int):
return 2 * index + 2
def build_max_heap(target_list: List[Any], heap_size: int, root_index: int):
start = parent_index(heap_size)
if left <=
def heap_sort(target_list: List[Any]):
"""
Bubble Sort algorithm
Worst case O(n^2)
:param target_list: Target to sort
:return: Sorted list
"""
heap_size = len(target_list)
for i in range(int(heap_size / 2 - 1), -1, -1):
build_max_heap(target_list, heap_size, i)
for i in range(int(heap_size - 1), -1, -1):
swap(target_list, 0, i)
build_max_heap(target_list, i, 0)
build_max_heap(target_list)
return target_list
print("Unsorted: {}".format(UNSORTED_NUMERICAL_SEQUENCE))
print("Sorted: {}".format(heap_sort(UNSORTED_NUMERICAL_SEQUENCE)))
|
1359614d9ebebc008bc2d2f0858f02dea31b4619 | Dayook/Algorithm | /python/divide_and_conquer/consecutive_sum.py | 326 | 3.671875 | 4 | # 1부터 n까지 더하기
def consecutive_sum(start, end):
mid = (start + end)// 2
if start == end:
return start
return consecutive_sum(start, mid) + consecutive_sum(mid + 1, end)
print(consecutive_sum(1, 10))
print(consecutive_sum(1, 100))
print(consecutive_sum(1, 253))
print(consecutive_sum(1, 388)) |
a32e36770f5c2974a1bd1c288a808e1d78d885a5 | ozcayci/01_python | /gun10/draw_a_box.py | 658 | 4.28125 | 4 | ## Draw a box outlined with asterisks and filled with spaces.
# @param width the width of the box
# @param height the height of the box
def drawBox(width, height):
# A box that is smaller than 2x2 cannot be drawn by this function
if width < 2 or height < 2:
print("Error: The width or height is too small.")
quit()
# Draw the top of the box
print("*" * width*2)
# Draw the sides of the box
for i in range(height - 2):
print("*" + " " * (width - 2) + "*")
# Draw the bottom of the box
print("*" * width*2)
def main():
drawBox(10, 10)
if __name__ == "__main__":
main()
|
fb47bc86a8e53d015aae0fadda87b9764e55817c | MxMossy/aoc2017 | /3_day.py | 462 | 3.828125 | 4 | number = int(input("What number: "))
#construct spiral
spiral = []
spiral.append([1])
ring_lev = 1
num = 2
while num <= number:
ring = []
while len(ring) < ring_lev * 8:
ring.append(num)
num += 1
ring_lev += 1
spiral.append(ring)
def Manhat_Dis(a):
for i in a:
if number in i:
x = a.index(i)
y = i.index(number)+1
return x + abs((x) - ((y) % (x*2)))
print(Manhat_Dis(spiral))
|
843475ced4ee5fefaf2a40a42139b16493882d8d | dinobobo/Leetcode | /346_moving_average_data_stream.py | 702 | 3.8125 | 4 | from collections import deque
class MovingAverage:
def __init__(self, size: int):
"""
Initialize your data structure here.
"""
self.size = size
self.count = 0
self.q = deque([])
def next(self, val: int) -> float:
if self.count < self.size:
self.q.append(val)
self.count += 1
return sum(self.q)/self.count
else:
self.q.popleft()
self.q.append(val)
return sum(self.q)/self.size
# You don't even need to pop the elements, since it won't affect the
# average outcome.
# Also keep track of the sum so that we only need to operations to find
# the average.
|
d49e579592993517fa84815aa9a92a2b5f46004b | sudheeramya/python | /ifelseconditon3.py | 133 | 3.640625 | 4 | is_hot = True
is_cold = False
if is_hot:
print('It is Summer')
elif is_cold:
print ('It is Cold')
print('It is ENJOY DAY ')
|
3bf086b5ec3521b977f7f9c831c2080a6c6fd5b3 | RHaran98/data-mining | /k_means.py | 2,350 | 3.625 | 4 | import random as r
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.pylab as pl
k = int(input("Enter number of clusters : ")) #Number of clusters
epochs = int(input("Enter number of epochs : "))
ipf = int(input("How would you like your points?\n1. Random gen\n2. CSV File \n3. Type in the points yourself\nTell me : "))
if ipf not in [1,2,3]:
print("Invalid choice")
exit()
points = []
if ipf is 1:
for i in range(900):
x = r.random()*100
y = r.random()*100
points.append([x, y])
elif ipf is 2:
f_name = input("Enter file name : ")
with open(f_name, 'r') as f:
for line in f:
line = line.strip()
x, y = map(int, line.split(','))
points.append([x, y])
elif ipf is 3:
n = input("Enter number of points : ")
for i in range(n):
x = float(input("Enter x coordinate of point "+str(i)+" : "))
y = float(input("Enter y coordinate of point " + str(i) + " : "))
points.append([x, y])
if k > len(points):
print("Too many clusters!")
exit()
c = []
clusters = []
colors = pl.cm.jet(np.linspace(0,1,k))
def dist(p1,p2):
return ((p1[0]- p2[0])**2 + (p1[1]-p2[1])**2)**0.5
def get_cluster(c, k, points):
clusters = [[] for i in range(k)]
for p in points :
d = []
for i in range(k):
d.append(dist(p,c[i]))
min_index = 0
for i in range(k):
if d[min_index] > d[i] :
min_index = i
clusters[min_index].append(p)
return clusters
def cluster_mean(cluster):
x,y = 0,0
for a,b in cluster:
x += a
y += b
x /= len(cluster)
y /= len(cluster)
return [x,y]
for i in range(k):
choice = r.choice(points)
while choice in c:
choice = r.choice(points)
c.append(r.choice(points))
clusters = get_cluster(c, k, points)
print("Start")
print(c)
for i in clusters:
print(i)
print()
for i in range(epochs):
for i in range(k):
c[i] = cluster_mean(clusters[i])
clusters = get_cluster(c, k, points)
print("Finish")
print(c)
for i in clusters:
print(i)
for i in range(k):
if clusters[i]:
plt.scatter(*zip(*clusters[i]), color=colors[i])
plt.show()
|
926bfb54be334af3ee648d7a68e7fdff66eae656 | 3Nakajugo/challenge2 | /numbersq.py | 287 | 4.25 | 4 | from datetime import date
def age():
yob = int(input('Please Enter your year of Birth:'))
today= date.today().year
age = today- yob
if (age < 18):
print('Minor')
elif (age >= 18 and age < 36):
print('Youth')
else:
print ('elder')
age()
|
eb6b3878c32abb66eca58ed04bf4101a8e826649 | d-m/project-euler | /007.py | 676 | 3.9375 | 4 | """
Project Euler Problem 7
=======================
By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see
that the 6th prime is 13.
What is the 10001st prime number?
"""
import math
def is_prime(number):
if number <= 1:
return False
elif number <= 3:
return True
elif number % 2 == 0:
return False
else:
for divisor in range(3, math.floor(math.sqrt(number)) + 1, 2):
if number % divisor == 0:
return False
return True
def primes():
number = 2
while True:
if is_prime(number):
yield number
number += 1
for i, prime in enumerate(primes()):
if i == 10000:
print(prime)
break |
779bb639636c70792b3d6a063153986245eec38c | henryscala/leetcode | /py/p75_sort_colors.py | 1,738 | 3.765625 | 4 | # problem 75 of leetcode
class Solution:
def sortColors(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
leftindex = 0
rightindex = len(nums)-1
while leftindex < rightindex:
while leftindex < rightindex and nums[leftindex] == 0:
leftindex += 1
while leftindex < rightindex and nums[rightindex] != 0:
rightindex -= 1
if leftindex < rightindex:
tmp = nums[leftindex]
nums[leftindex] = nums[rightindex]
nums[rightindex] = tmp
leftindex += 1
rightindex -= 1
#after the above steps, all 0s are in the correct positions,
#and leftindex is correct
#after the below steps, all 1s and 2s are in the correct positions, too
#print("middle",leftindex,rightindex,nums)
rightindex = len(nums)-1
while leftindex < rightindex:
while leftindex < rightindex and nums[leftindex] != 2:
leftindex += 1
while leftindex < rightindex and nums[rightindex] == 2:
rightindex -= 1
if leftindex < rightindex:
tmp = nums[leftindex]
nums[leftindex] = nums[rightindex]
nums[rightindex] = tmp
leftindex += 1
rightindex -= 1
if __name__ == '__main__':
a = [1,2,0,1,0,2]
s = Solution()
s.sortColors(a)
print(a)
a = [1,0,0]
s.sortColors(a)
print(a)
a = [2,0,0]
s.sortColors(a)
print(a)
a = [2,1,1]
s.sortColors(a)
print(a)
|
0eca322d4c353a80a7899430ce105872c963b691 | TatianaMatveeva/Learning_Python | /OPPC 1.10/C10_4/PartyforEverybody.py | 656 | 3.703125 | 4 | class Guests:
def __init__(self, name, location, status):
self.name = name
self.location = location
self.status = status
class Human(Guests):
def get_person(self):
return f'''{self.name}, {self.location}, stile IN life "{self.status}"'''
Vol1 = Human('Джони пуля в зубах', 'Москва', 'Киллер')
Vol2 = Human('Адель черная душа', 'Смольный', 'Черный Риэлтор')
Vol3 = Human('Один раз не программист', 'Зеленоград', 'Голодный студент')
volunteers = [Vol1, Vol2,Vol3]
for i in volunteers:
print(i.get_person()) |
2e1cebb79c7daa8071803397697aac48e6acf615 | Acid2510/Python | /suff/week3/while_exercise.py | 142 | 4.03125 | 4 | Word=raw_input('Input a word:')
num=input('how many times:')
loop=0
while loop<num:
print ('{0} {1}'.format(Word,loop+1))
loop=loop+1
|
7c269d2af52f620210f373214fe2580cd5a2e5c1 | subbbbbb/Python-Archives | /1st Semester/caesarCipher.py | 3,139 | 4.4375 | 4 |
# getMode() is a getter method that either prints out decrypt/encrypt, or tells you to do it over again if invalid input
def getMode(): # defines the specific mode that you want
# converts single letters to lowercase to preventp roblems later
mode = input("do you want to encrypt or decrypt?").lower()
# loop that is always true (as long as the user enters an input)
while True:
if(mode == "encrypt" or mode == "decrypt"): # if the user types in an input correctly
return mode # don't print, but return what they type
else:
# if not, make them try again by using the mode line from earlier
print("Spell it correctly and try again")
mode = input("Spell it right and try again::").lower()
print(getMode()) # outside of the function, make sure to test it to see if it works
# getMessage() is a getter method that returns what method you want (same as getMode)
def getMessage():
# remember to use return statements inside of the functions instead of print statements
return input("Encrypt or Decrypt")
print(getMessage()) # use the print statement outside of the function to check
# another getter method that simply gives you the key that you enter, as long as it is between 1 and 25
def getKey():
# asking for a key and convert to int
key = int(input("Enter a number betwen -25 and 25"))
while True: # while the user provides some kind of input --
if key >= -25 and key <= 25:
return key
else:
key = int(input("I need a number 1-25"))
print(getKey())
def getTranslatedMessage(mode, message, key): # parameter list
if mode[0] == 'd': # if first letter in mode variable is d grab part of string
key = -key # switch key for decryption
translated = ""
for letter in message:
num = ord(letter)
num = num + key
translated += chr(num)
return translated
print(getTranslatedMessage("encrypt", "Hello", 1))
print(getTranslatedMessage("decrypt", "Ifmmp", 1))
print(getTranslatedMessage("encrypt", "Sub", 2))
# getMode() is a getter method that either prints out decrypt/encrypt, or tells you to do it over again if invalid input
# defines the specific mode that you want
# converts single letters to lowercase to prevent problems later
# loop that is always true (as long as the user enters an input)
# if the user types in an input correctly
# don't print, but return what they type
# if not, make them try again by using the mode line from earlier
# outside of the function, make sure to test it to see if it works
# getMessage() is a getter method that returns what method you want (same as getMode)
# remember to use return statements inside of the functions instead of print statements
# use the print statement outside of the function to check
# another getter method that simply gives you the key that you enter, as long as it is between 1 and 25
# asking for a key and convert to int
# while the user provides some kind of input --
# parameter list
# if first letter in mode variable is d grab part of string
# switch key for decryption
|
0622cbd52fd5f2ec4958c9bdce5bc1d03ad6362d | dotslash-web/PY4E | /Course 3 - Using Python to Access Web Data/Chapter 11/Lecture Material/RegularExpressions.py | 2,941 | 4.3125 | 4 | ''' Regular Expressions-
Regular expressions are a language unto themselves. It's an "old school" language
In computing , a regular expression, also referred to as "regex" or "regexp", provides
a concise and flexible means for matching strings of text, such as particular characters,
words, or patterns of characters. A regular expression is written in a formal language
that can be interpreted by a regular expression processor.
Really clever "wild card" expressions for matching and parsing strings.
'Regular Expression Quick Guide'
^ matches the beginning of a line
$ matcges the end of the line
. matches any character
\s matches whitespace
\S matches any non-whitespace character
* repeats a character zero or more times
*? repeats a character zero or more times (non-greedy)
+ repeats a character one or more times
+? repeats a character one or more times (non-greedy)
[aeiou] matches a single character in the listed set
[^XYZ] matches a single character not in the listed set
[a-z0-9] the set of characters can include a range
( indicates where string extraction is to start
) indicates where string extraction is to end
--The Regular Expression Module--
Before you can use regular expressions in your program, you must
import the library using "import re"
You can use re.search() to see if a string matches a regular expression,
similar to using the find() method for strings
You can use re.findall() to extract portions of a string that match
your regular expression, similar to a combination of find() and slicing: var[5:10] '''
'Using re.search() Like find()'
#Find()
hand = open('mbox-short.txt')
for line in hand :
line = line.rstrip()
if line.find('From:') >= 0 :
print(line)
#re.search()
import re
hand = open('mbox-short.txt')
for line in hand :
line = line.rstrip()
if re.search('From:', line) : #string we are searching for, line we that we are searching within
print(line)
'Using re.search() Like startswith()'
#startswith()
for line in hand :
line = line.rstrip()
if line.startswith('From: ') :
print(line)
#re.search()
import re
for line in hand :
line = line.rstrip()
if re.search('^From:', line) :
print(line)
'Wild-Card Characters'
#the dot character matches any character
#if you add the asterisk character, the character is "any number of times"
# ^X.*: "I'm looking for lines that have an X in the beginning, followed by any number of characters, followed by colon"
#X-Sieve: CMU Sieve 2.3 <-- this would be matched
'Fine-Tuning Your Match'
#Depending on how "clean" your data is and the purpose of your application, you may want to narrow your match down a bit
# ^X-\S+: "I want matches that start with X, followed by a dash, followed by any non-whitespace character=greater than
# or equal to one or more non-line character, followed by a colon"
|
d332fe3eda2383dced74cc9c47475abf55990856 | LucasLeone/tp1-algoritmos | /estructura_secuencial/es4.py | 306 | 3.59375 | 4 | '''
Teniendo como dato el lado de un cuadrado,
calcular e imprimir la superficie y perímetro.
'''
lado_cuadrado = float(input('Cuantos cm mide el lado del cuadrado? '))
print('La superficie del cuadrado es: ', lado_cuadrado*lado_cuadrado)
print('El perimeto del cuadrado es: ', lado_cuadrado*4) |
c1a019da9107d704a098cb778a4b2d49cb985e2a | Graver75/python_study | /pack_1/problem1_0.py | 431 | 4.09375 | 4 | def shift_list_for(arr, n):
for i in range(n):
arr.insert(0, arr.pop(len(arr) - 1))
return arr
def get_list():
return list(input('Enter list: ').split())
print('Moving lists')
arr = get_list()
try:
shift = int(input('Enter value for move: ')) % len(arr)
print('Your new list: ', shift_list_for(arr, shift))
except Exception:
print('List should be not empty and value for move should be integer!')
|
895d5b8ac85f2890c710c7c14daa76c6d96e95dc | jamwyatt/simpleProgrammingChallenges | /python/nthPrimeNumber.py | 827 | 4.0625 | 4 |
import sys
def findPrimePositional(primePos):
primeCount = 0
n = 2
while True:
isPrime = True
max = n/2+1
if (n>2) and (n%2 == 0):
# Even above two are not primes
isPrime = False
elif n%3 == 0:
isPrime = False
else:
x = 3
while x < max:
if n % x == 0:
isPrime = False
break # Not prime
x += 1
if isPrime:
primeCount += 1
if primeCount == primePos:
return n;
n += 1
if len(sys.argv) != 2:
print "Missing target positional prime number"
sys.exit(-1)
positionalPrime = findPrimePositional(int(sys.argv[1]))
print "Positional Prime for ",sys.argv[1], " is ", positionalPrime
|
c1af35363798f3dce977a99ae491696db32e87da | KeeJoonYoung/keras | /keras30_split2_DNN.py | 685 | 3.5 | 4 | # 30_split 커피
import numpy as np
a = np.array(range(1,11)) # 뒤에꺼 하나 뺀거까지
size = 6
print(a) # [ 1 2 3 4 5 6 7 8 9 10]
def split_x(seq, size):
aaa = []
for i in range(len(seq) - size + 1):
subset = seq[i : (i+size)]
aaa.append(subset)
print(type(aaa))
return np.array(aaa)
dataset = split_x(a, size)
print(dataset)
x = dataset[:, :size-1] # 모든 행, 4번째 데이터까지 즉 4개의 열을 가져오겠다
y = dataset[:, size-1] # 4지정
print(x)
print(y)
x_pred = [[6,7,8,9,10]]
#2. 모델
#3. 컴파일, 훈련
#4. 평가, 예측
# 실습 Dense으로 만들기 |
49dcfb8f1d5c0304ecb7e13f08aeb570aea8ec71 | chatsuboctf/chatsubo | /app/helpers/rand.py | 510 | 3.671875 | 4 | import string
import random
def randstr(length=8):
"""
Generates a random password having the specified length
:length -> length of password to be generated. Defaults to 8
if nothing is specified.
:returns string <class 'str'>
"""
letters = string.ascii_letters
numbers = string.digits
punctuations = string.punctuation
dico = list(f'{letters}{numbers}{punctuations}')
random.shuffle(dico)
blob = ''.join(random.choices(dico, k=length))
return blob
|
fefd85a88a9e00562de1eba2765ac583a6cc2cd8 | minaazol/CP3-Meena-Kittikunsiri | /Lecutre71_Meena_K.py | 387 | 3.8125 | 4 | menuList = []
priceList = []
def bill():
print("------My Shop------")
for i in range(len(priceList)):
print(menuList[i], priceList[i])
print("Total :",sum(priceList))
while True:
menu = input("Please enter menu : ")
if menu.lower() == 'exit':
break
else:
price = int(input("Please enter price : "))
menuList.append(menu)
priceList.append(price)
bill()
|
6442953bed319234789b4ba580b3de6d04421671 | ramamohanraju/RPi | /led/led_blink.py | 700 | 3.84375 | 4 | # This program will Blink the LED connected to GPIO 7.
import RPi.GPIO as GPIO # import RPi.GPIO module
from time import sleep # lets us have a delay
GPIO.setmode(GPIO.BCM) # choose BCM or BOARD
GPIO.setup(7, GPIO.OUT) # set GPIO7 as an output
try:
while True:
GPIO.output(7, 1) # set GPIO7 to 1/GPIO.HIGH/True
sleep(1) # wait a second
GPIO.output(7, 0) # set GPIO7 to 0/GPIO.LOW/False
sleep(1) # wait a second
except KeyboardInterrupt: # trap a CTRL+C keyboard interrupt
GPIO.cleanup() # resets all GPIO ports used by this program
|
4ddfb7af82bf9d7b2ad258e2a242558b8d9ce899 | runningcost2/Learning_Python_from_Zero | /22. oneline_for.py | 482 | 3.890625 | 4 | # Changing attendance number. ex)1, 2, 3, 4 => 101, 102, 103, 104
students = [1,2,3,4,5]
print(students)
students = [i+100 for i in students] #loading every i in students and add 100 each
print(students)
# changing name to length of name
students1 = ["Zeus", "Hestia", "Poseidon", "Julius Caesar"]
students1 = [len(i) for i in students1]
print(students1)
# Making uppper letters name
students2 = ["Robert", "Chris", "Natasha"]
students2 = [i.upper() for i in students2]
print(students2) |
50a98ba589183b8630fa8d5b60dc55b98d567711 | skp96/DS-Algos | /Leetcode/Trees and Graphs/build_tree.py | 1,873 | 3.796875 | 4 | class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def __init__(self, preorder_idx=0):
self.preorder_idx = preorder_idx # keep track of preorder position
def build_tree(self, preorder, inorder):
# instead of having to scan inorder, we create an inorder dictionary so we can use preorder elements to lookup the respective index in inorder
inorder_dict = {val: idx for idx, val in enumerate(inorder)}
return self.build_tree_helper(preorder, inorder_dict, 0, len(inorder) - 1, self.preorder_idx)
def build_tree_helper(self, preorder, inorder_dict, beg, end, preorder_idx):
if beg > end return None # instead of slicing arrays and having to check for a base case of empty array, we check if beg > end which would represent an empty array
# take preorder element and create a tree node
root = TreeNode(preorder[self.preorder_idx])
# find index value of element in inorder
index = inorder_dict[root.val]
self.preorder_idx += 1 # increment position in preorder array
# instead of having to create subarrays of elements to the left and right of element, we pass in pointer values representing beg and end of subarrays
root.left = self.build_tree_helper(
preorder, inorder_dict, beg, index - 1, self.preorder_idx)
root.right = self.build_tree_helper(
preorder, inorder_dict, index + 1, end, self.preorder_idx)
return root
# Time Complexity: O(m + n), where m represents having to create an inorder dictionary, and n represents having to iterate through the preorder array
# Space Complexity: O(m + n), where m represents the size of the inorder dictionary, and n represents the recursive calls in the call stack
|
b961ebd12eb25a3b8479053e140f0183de7a25ce | swjjxyxty/study-python | /base/each.py | 394 | 3.53125 | 4 | # -*_ coding:utf-8 -*-
names = ["1", "2", "3"]
for name in names:
print(name)
sum = 0
for x in range(101):
sum += x
print(sum)
sum = 0
n = 99
while n > 0:
sum += n
n -= 2
print(sum)
n = 1
while n < 1000:
if n > 10:
break
print(n)
n = n + 1
print("END")
n = 1
while n < 1000:
n = n + 1
if n % 2 == 0:
continue
print(n)
print("END")
|
d287f9b94043561998bcf729d996c923778cc01b | jadenpadua/ICPC | /Python/sorting/selection-sort.py | 890 | 3.859375 | 4 | # Idea, iterate through an array with a pointer on each index, find min element and swap with that index
# O(n^2) time | O(1) space
def selectionSort(array):
# Idx that will iterate through our array
currentIdx = 0
# Breaks when array is fully traversed
while currentIdx < len(array) - 1:
# At each iteration, initially smallest idx to current idx
smallestIdx = currentIdx
# Now iterate from our pointer index to the end of the array
for i in range(currentIdx + 1, len(array)):
# Update value of smallestIdx when we encounter a smaller element
if array[smallestIdx] > array[i]:
smallestIdx = i
# Now after smallestIdx is found, prform a swap
swap(currentIdx, smallestIdx, array)
# Increment our pointer for current index
currentIdx += 1
return array
|
a32f336b6d5746d5377ad4e231ba1fc19919a334 | minhyeong-joe/coding-interview | /Graph/Dijkstra.py | 1,903 | 4.0625 | 4 | # Given a weighted graph, a source vertex and a goal vertex,
# find the shortest distance from the source vertex to the goal vertex.
# Assume there IS a path between the source and the goal.
# Using Dijkstra's Algorithm:
from queue import PriorityQueue
from Graph import ListGraph
def dijkstra(graph, src, goal):
visited = dict()
minHeap = dict() # minHeap simulation only
# insert the src with 0 distance to minHeap
minHeap[src] = 0
while minHeap:
# simulate minHeap by manually sorting with Python's array sorting O(n log n)
minHeap = {vertex: distance for vertex, distance in sorted(
minHeap.items(), key=lambda pair: pair[1])}
min = list(minHeap.items())[0]
minHeap.pop(min[0])
closestVertex = min[0]
traveledSoFar = min[1]
visited[closestVertex] = traveledSoFar
for neighbor in graph.neighbors(closestVertex):
if neighbor not in visited.keys():
distance = graph.getDistance(
closestVertex, neighbor) + traveledSoFar
if neighbor in minHeap.keys():
if distance < minHeap.get(neighbor):
minHeap[neighbor] = distance
else:
minHeap[neighbor] = distance
print("visited:", visited)
return visited.get(goal, -1)
# test driver
# rough graph visualization:
# A -(6)- B
# | / | \(5)
# (1) (2) (2) C
# | / | /(5)
# D -(1)- E
graph = ListGraph(directed=False)
graph.addVertex('A')
graph.addVertex('B')
graph.addVertex('C')
graph.addVertex('D')
graph.addVertex('E')
graph.addEdge('A', 'B', 6)
graph.addEdge('A', 'D', 1)
graph.addEdge('B', 'C', 5)
graph.addEdge('B', 'D', 2)
graph.addEdge('B', 'E', 2)
graph.addEdge('C', 'E', 5)
graph.addEdge('D', 'E', 1)
print(graph)
print("shortest distance from 'A' to 'C' is:", dijkstra(graph, 'A', 'C'))
|
6bc04717059fc803deb222b41e3351501e544669 | nowstartboy/my_code_new | /the_exam/weiruan3.py | 598 | 3.578125 | 4 | def maxStipend2(numOfDays,taskList,state):
if not taskList or not numOfDays:
return 0
if state==1: #前一天工作了
max1=taskList[0][0]+maxStipend2(numOfDays-1,taskList[1:],1)
else:
max1=taskList[0][1]+maxStipend2(numOfDays-1,taskList[1:],1)
max2 = maxStipend2(numOfDays - 1, taskList[1:], 0)
return max(max1,max2)
def maxStipend(numOfDays,taskList):
max0=0
max1=maxStipend2(numOfDays-1,taskList[1:],1)+taskList[0][1]
max2=maxStipend2(numOfDays-1,taskList[1:],0)
return max(max1,max2)
print (maxStipend(4,[[7,10],[6,7],[4,6],[6,7]])) |
3a5d1991ff1a3e59260746c3edc712f47dc3ba07 | cmhedrick/mysticquest | /mysticquest.py | 1,973 | 3.703125 | 4 | class Room:
def __init__(self, id, name, desc, doors):
self.id = int(id)
self.name = name
self.desc = desc
self.doors = doors
def __str__(self):
return "{0}\n{1}\n{2}\n{3}\n".format(self.id, self.name, self.desc, self.doors)
class House:
def __init__(self):
self.rooms = []
def __str__(self):
rooms_desc = ""
for room in self.rooms:
rooms_desc += room.__str__()
return rooms_desc
def get_room_by_id(self, id):
for room in self.rooms:
if room.id == id:
return room
def add_room(self, room):
self.rooms.append(room)
class Hero:
def __init__(self, name, house, room):
self.name = name
self.house = house
self.location = house.get_room_by_id(room)
def __str__(self):
if self.location:
return "{0} Room\n{1}".format(self.location.name, self.location.desc)
return "My name is {0} and I'm lost in the void.".format(self.name)
def go_north(self):
if 'N' not in self.location.doors:
return False
north_room_id = self.location.doors['N']
self.location = self.house.get_room_by_id(north_room_id)
return True
def go_south(self):
if 'S' not in self.location.doors:
return False
south_room_id = self.location.doors['S']
self.location = self.house.get_room_by_id(south_room_id)
return True
def go_west(self):
if 'W' not in self.location.doors:
return False
west_room_id = self.location.doors['W']
self.location = self.house.get_room_by_id(west_room_id)
return True
def go_east(self):
if 'E' not in self.location.doors:
return False
east_room_id = self.location.doors['E']
self.location = self.house.get_room_by_id(east_room_id)
return True
|
8d4d46aa87d3e133b3695e554a89c0497dde9391 | v-72/go_play | /algo/rain_water_1.py | 565 | 3.609375 | 4 | def findWater(arr):
low = 0
high = len(arr) - 1
left_max = 0
right_max = 0
water = 0
while(low < high):
if arr[low] < arr[high]:
if arr[low] > left_max:
left_max = arr[low]
else:
water += left_max - arr[low]
low += 1
else:
if arr[high] > right_max:
right_max = arr[high]
else:
water += right_max - arr[high]
high -=1
return water
print(findWater([0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2,1])) |
fbd6fd869278bc065fbe77c72315798d717b49c3 | xiongxiong109/algorithm_study | /py/algorithm/radix_sort.py | 1,221 | 3.515625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# 定义一个模块需要上面的声明, 这样才可以被其他模块执行
# 使用队列实现基数排序 py
from queue import Queue
from math import floor
def radix(args=[]):
# 创建10个队列 bin0 - bin10
bin_arr = []
data_arr = []
for i in range(10):
bin_item = {
'id': 'bin%s' % i,
'queue': Queue()
}
bin_arr.append(bin_item)
# 对数组中对个位数进行一次入队排序
for item in args:
cur_item = item % 10 # 取余数
cur_arr = bin_arr[cur_item] # bin0, bin1
cur_arr['queue'].put(item)
# 第一次排序后依次出队,得到第一次排序的结果
data_arr = pop_arr(bin_arr)
# 对数组对十位数再进行一次入队排序
for item in data_arr:
cur_item = floor(item / 10) # 取十位数
cur_arr = bin_arr[cur_item] # bin0, bin1
cur_arr['queue'].put(item)
data_arr = pop_arr(bin_arr)
return data_arr
def pop_arr(bin_arr=[]):
single_arr = []
for bin_x in bin_arr:
while bin_x['queue'].qsize():
single_arr.append(bin_x['queue'].get())
return single_arr
|
83a65ee2a97e3e4f7291d326f2e1c90234eda3c7 | UWPCE-PythonCert-ClassRepos/SP_Online_Course2_2018 | /students/Craig_Morton/Lesson04/json_save/json_save/saveables.py | 6,601 | 3.546875 | 4 | #!/usr/bin/env python
"""
The Saveable objects used by both the metaclass and decorator approach.
"""
import ast
# import json
# import json.import.xy
# import.json.element.xy
# import.rh.ty.element
# import.ty.rh.identity.x
# import.identity.name.space.x.json
__all__ = ['Bool',
'Dict',
'Float',
'Int',
'List',
'Saveable',
'String',
'Tuple',
]
class Saveable():
"""
Base class for all saveable types
"""
default = None
ALL_SAVEABLES = {}
@staticmethod
def to_json_compat(val):
"""
returns a json-compatible version of val
should be overridden in saveable types that are not json compatible.
"""
return val
@staticmethod
def to_python(val):
"""
convert from a json compatible version to the python version
Must be overridden if not a one-to-one match
This is where validation could be added as well.
"""
return val
class String(Saveable):
"""
A Saveable string
Strings are the same in JSON as Python, so nothing to do here
"""
default = ""
class Bool(Saveable):
"""
A Saveable boolean
Booleans are pretty much the same in JSON as Python, so nothing to do here
"""
default = False
class Int(Saveable):
"""
A Saveable integer
Integers are a little different in JSON than Python. Strictly speaking
JSON only has "numbers", which can be integer or float, so a little to
do here to make sure we get an int in Python.
"""
default = 0
@staticmethod
def to_python(val):
"""
Convert a number to a python integer
"""
return int(val)
class Float(Saveable):
"""
A Saveable floating point number
floats are a little different in JSON than Python. Strictly speaking
JSON only has "numbers", which can be integer or float, so a little to
do here to make sure we get a float in Python.
"""
default = 0.0
@staticmethod
def to_python(val):
"""
Convert a number to a python float
"""
return float(val)
# Container types: these need to hold Saveable objects.
class Tuple(Saveable):
"""
This assumes that whatever is in the tuple is Saveable or a "usual"
type: numbers, strings.
"""
default = ()
@staticmethod
def to_python(val):
"""
Convert a list to a tuple -- json only has one array type,
which matches to a list.
"""
# simply uses the List to_python method -- that part is the same.
return tuple(List.to_python(val))
class List(Saveable):
"""
This assumes that whatever is in the list is Saveable or a "usual"
type: numbers, strings.
"""
default = []
@staticmethod
def to_json_compat(val):
lst = []
for item in val:
try:
lst.append(item.to_json_compat())
except AttributeError:
lst.append(item)
return lst
@staticmethod
def to_python(val):
"""
Convert an array to a list.
Complicated because list may contain non-json-compatible objects
"""
# try to reconstitute using the obj method
new_list = []
for item in val:
try:
obj_type = item["__obj_type"]
obj = Saveable.ALL_SAVEABLES[obj_type].from_json_dict(item)
new_list.append(obj)
except (TypeError, KeyError):
new_list.append(item)
return new_list
class Dict(Saveable):
"""
This assumes that whatever in the dict is Saveable as well.
This supports non-string keys, but all keys must be the same type.
"""
default = {}
@staticmethod
def to_json_compat(val):
d = {}
# first key, arbitrarily
key_type = type(next(iter(val.keys())))
if key_type is not str:
# need to add key_type to json
d['__key_not_string'] = True
key_not_string = True
else:
key_not_string = False
for key, item in val.items():
kis = type(key) is str
if (kis and key_not_string) or (not (kis or key_not_string)):
raise TypeError("dict keys must be all strings or no strings")
if key_type is not str:
# convert key to string
s_key = repr(key)
# make sure it can be reconstituted
if ast.literal_eval(s_key) != key:
raise ValueError(f"json save cannot save dicts with key:{key}")
else:
s_key = key
try:
d[s_key] = item.to_json_compat()
except AttributeError:
d[s_key] = item
return d
@staticmethod
def to_python_ext_value_recursion(val):
"""Value that defines the recursive identity of the abstraction model"""
d = {}
key_type = type(next(iter(val.keys())))
if key_type is not str:
d['__key_not_string'] = True
key_not_string = True
else:
key_not_string = False
for key, item in val.items():
kis = type(key) is str
if (kis and key_not_string) or (not (kis or key_not_string)):
raise TypeError("dict keys must be all strings or no strings")
if key_type is not str:
s_key = repr(key)
if ast.literal_eval(s_key) != key:
raise ValueError(f"json save cannot save dicts with key:{key}")
else:
s_key = key
try:
d[s_key] = item.to_json_compat()
except AttributeError:
d[s_key] = item
return d
@staticmethod
def to_python(val):
"""
Convert a json object to a dict
Complicated because object may contain non-json-compatible objects
"""
# try to reconstitute using the obj method
new_dict = {}
key_not_string = val.pop('__key_not_string', False)
for key, item in val.items():
if key_not_string:
key = ast.literal_eval(key)
try:
obj_type = item["__obj_type"]
obj = Saveable.ALL_SAVEABLES[obj_type].from_json_dict(item)
new_dict[key] = obj
except (KeyError, TypeError):
new_dict[key] = item
return new_dict
|
b899e93387e05a12f52fef5d6a90ebd98f01c2c3 | khushboojain123/python-code | /armstrong in an interval.py | 760 | 4.15625 | 4 | # program to display all the armstrong number in which interval which is given by user
# take input from user
def arm():
return()
def main():
lower = int(input("enter lower range:"))
upper= int(input("enter upper range:"))
for num in range(lower, upper+1):
sum=0
temp = num
while temp > 0:
digit = temp % 10
sum +=digit **3
temp//=10
if num == sum:
print(num)
if __name__ == "__main__":
main()
while True:
again =input("do you want to continue y/n").lower()
if again == 'y':
main()
else:
print("thank you,you are exiting from the program")
exit()
|
8242561d5e671fa9c15323f3696db9c577805bd5 | drewherron/class_sheep | /Code/charlie/python/lab20.py | 2,326 | 4.25 | 4 |
def credit_number_check(user_input):
#this while statement allows the user to input a list of numbers until they are input 'done'
while True:
credit_number = input("enter your credit card number\n:")
if credit_number == 'done':
break
credit_number = int(credit_number)
credit_number_list.append(credit_number)
# print(f"credit number is {credit_number_list}")
# i pop the last integer and set that value to the check_digit variable. I print the check digit and the list without the check digit.
check_digit = credit_number_list.pop((len(credit_number_list)-1))
# print(f"credit number list without the check number is {credit_number_list}")
# print(f"check digit is {check_digit}")
#str.reverse will reverse the credit number
credit_number_list.reverse()
# print(f" credit number reveresed is {credit_number_list}")
#the for loop will insert an if statement for every indicie between 0 and the length of the list. if the if statement is true, the value and the index will be multiplied by 2.
for index in range(len(credit_number_list)):
if index % 2 == 0:
credit_number_list[index] *= 2
print(credit_number_list)
#this for loop will check each indice whether the value is above 9. if it is, 9 will be removed from the value.
for index in range(len(credit_number_list)):
if credit_number_list[index] > 9:
credit_number_list[index] -= 9
# print(f"this is the list after 9 was removed from values above 9, {credit_number_list}")
#this for loop will take each value in the list and then set it to a new variable, sum_credit_num, and continue to add to itself.
sum_credit_num = 0
for value in credit_number_list:
sum_credit_num += value
print(sum_credit_num)
#i find the last number in the sum of the credit by determining the length of the string, and subtracting 1 to find the index.
sum_credit_num = str(sum_credit_num)
last_number = sum_credit_num[len(sum_credit_num)-1]
last_number = int(last_number)
if last_number == check_digit:
print('Valid!')
return True
else:
print("Invalid!")
return False
credit_number_list = []
credit_number = ' '
credit_number_check(credit_number_list)
|
90cc0a3662896b3a2d33718c8519573b4c5a85bd | kamyu104/LeetCode-Solutions | /Python/construct-the-longest-new-string.py | 277 | 3.671875 | 4 | # Time: O(1)
# Space: O(1)
# constructive algorithms, math
class Solution(object):
def longestString(self, x, y, z):
"""
:type x: int
:type y: int
:type z: int
:rtype: int
"""
return ((min(x, y)*2+int(x != y))+z)*2
|
3ea50073baefb984e73aec23f2ef86b0c9a2fdef | Chizzy-gem/My_python_class | /square2.py | 1,423 | 4.375 | 4 | # Homework
# Read more about if statement
# Implement option for B to compute the perimeter of the square
# Implement option AP, calculate both Area and Perimeter
# Implement for anything that is not A or B or AB let this end the program
# Create square2.py and do the homework there
#ANSWER
# Ask the user for username
username = input ("Enter Your Username: ")
# Display a welcome page
print ("Welcome", username)
# Ask the user to enter age
Age = int(input ("Please Enter Your Age: "))
# Ask the user for length of square
length = float(input ("Please enter the length of the square: "))
# Ask the user to select A or B for area or perimeter of square respectively
option = input("Enter A to calculate Area, B to calculate Perimeter or AB to calculate both Area and Perimeter: ")
# Caculate the area (A) and perimeter (B) using the input of the length
if option == "A":
area = length * length
print("Area: ",area)
elif option == "B":
perimeter = 4 * length
print ("Perimeter: ",perimeter)
elif option == "AB":
area = length * length
perimeter = 4 * length
print("Area: ",area,"\n","Perimeter: ",perimeter)
else:
exit()
#Answer 2
def factorial(x):
if x==0:
return 1
else:
return x * factorial (x-1)
x=int(input("Enter a number to compute factorial: "))
print ("Factorial of ",x," is: ",factorial(x))
#Answer 3
|
4546c9cf4b86764564e9416271da97cb68c6c7d6 | masterfung/LPTHW | /ex14.py | 790 | 3.828125 | 4 | from sys import argv
script, user_name = argv
prompt = '-****->>> '
print "Hi awesome %s, I'm the %s script." % (user_name, script)
print "I'd like to ask you a few short questions."
print "Do you like me %s?" % user_name
likes = raw_input(prompt)
print "Where is your residence %s?" % user_name
lives = raw_input(prompt)
print "What kind of computer do you have?"
computer = raw_input(prompt)
print 'What is your favorite city of all time?'
city = raw_input(prompt)
print """
My favorability with you is %r, and I find that response fascinating!
Your residential location is %r. That is a great place to live in :).
And you have a %r computer. Nice! I do too.
The brotherhood of computer love your response on %r being the best city of all time!
""" % (likes, lives, computer, city) |
c22bd7923f484cbf7c73d5737ecd9d6d28013c6f | nmante/cracking | /chap-3/python/stack.py | 711 | 3.5625 | 4 | """
Nii Mante
Stack implementation
"""
from node import Node
class Stack:
def __init__(self, data):
self.top = Node(data)
def __str__(self):
tmp = self.top
out_str = "Stack\n"
out_str = out_str + "====\n"
while tmp:
out_str = out_str + str(tmp.data) + "\n"
tmp = tmp.next_node
out_str = out_str + "\n====\n"
return out_str
def pop(self):
if self.top:
result = self.top
self.top = self.top.next_node
return result
return None
def push(self, data):
new_node = Node(data)
new_node.next_node = self.top
self.top = new_node
|
83cf3c375cf7f2942c6ded20ed34bad43b5bdb45 | Lights19/Python | /Python_introductory/exceptions.py | 959 | 4.40625 | 4 | #'exceptions' are the errors detected at the time of program execution
# #handling the exception, by using "try and except"shuld be in the part of program where exception is
#expected to occur
x=input("Enter a number1: ")
y=input("Enter a number2: ")
try:
z=int(x)/int(y)
except ZeroDivisionError as e:
print("Division by Zero exception:",e)
z=None # initializing z as None if cannot be divided
print("Division is: ",z)
# general format for taking detour or handeling exception
try:
while road_is_clear():
drive()
except Accident as e:
take_detour()
#handeling multiple exception or unknown type of error
x=input("Enter a number1: ")
y=input("Enter a number2: ")
try:
z=int(x)/int(y)
except ZeroDivisionError as e:
print("Division by Zero exception:")
z=None # initializing z as None if cannot be divided
except ValueError as e:
print("Type error:",type(e).__name__,)
z=None
print("Division is: ",z)
|
b489e48634ed1bdd7286e8b46978c7fccbd556b0 | tuouo/selfstudy | /learnfromBook/PythonCookbook/DataStructure/about_priority_queue | 919 | 3.984375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import heapq
class PriorityQueue:
def __init__(self):
self._queue = []
self._index = 0
def push(self, item, priority):
heapq.heappush(self._queue, (-priority, self._index, item))
self._index += 1
def pop(self):
return heapq.heappop(self._queue)[-1]
class Item:
def __init__(self, name):
self.name = name
def __repr__(self):
return 'Item({!r})'.format(self.name)
a = Item('foo')
b = Item('bar')
c = Item('zoo')
q = PriorityQueue()
q.push(a, 1)
q.push(b, 2)
q.push(c, 5)
q.push(Item('tank'), 2)
q.push(Item('mike'), 3)
print(q.pop())
print(q.pop())
print(q.pop())
print(q.pop())
print(q.pop())
# print(a < b) TypeError: unorderable types: Item() < Item()
aa = (1, a)
bb = (1, b)
# print(aa < bb) TypeError: unorderable types: Item() < Item()
bb = (2, b)
print(aa < bb) # True
|
7f2dff0b06bc40e2e55cc38a57b75ca5335cfacd | ReeseAEJones/CatanAI | /src/core.py | 2,835 | 3.75 | 4 | import enum
import math
import random
class TileTypes(enum.Enum):
sheep = 1
wheat = 2
wood = 3
clay = 4
ore = 5
desert = 6
class PlayerColors(enum.Enum):
red = 1
blue = 2
orange = 3
white = 4
class Tile:
# Uses Cube coordinates
def __init__(self, x, y, z, tile_type):
self.x = x
self.y = y
self.z = z
self.type = tile_type
# Determines if two tiles are next to one another
def is_neighbor(self, tile):
amnt = 0
if self.x == tile.x:
amnt += 1
if self.y == tile.y:
amnt += 1
if self.z == tile.z:
amnt += 1
return amnt == 1
def get_resource(self):
return self.type
class Road:
# The line between tiles
def __init__(self, tile1, tile2, owner):
if not tile1.is_neighbor(tile2):
raise Exception("There was a road that was created two tiles that are not neighbors.")
self.tile1 = tile1
self.tile2 = tile2
self.owner = owner
class Settlement:
# A node between 3 tiles, could represent a settlement or city
def __init__(self, tile1, tile2, tile3, owner):
if not (tile1.is_neighbor(tile2) and tile1.is_neighbor(tile3) and tile2.is_neighbor(tile3)):
raise Exception("There was a road that was created three tiles that are not neighbors.")
self.tiles = (tile1, tile2, tile3)
self.owner = owner
self.is_city = False
# Upgrades a settlement to a city
def upgrade_to_city(self):
self.is_city = True
# Returns a list of the tile types that surround the settlement, if it is a city then the resources are doubled
def get_resources(self):
res = [t.get_resource() for t in self.tiles]
if self.is_city:
res = 2 * res
return res
class Board:
def __init__(self, radius, tile_type_collection):
if radius > 0:
self.tile_amnt = 1 + 6 * math.factorial(radius)
else:
raise Exception("The radius of the boards was less than one, the boards was unable to be constructed.")
self.tiles = self.generate_tiles(radius, tile_type_collection)
# Generates the tiles for the board
def generate_tiles(self, radius, tile_type_collection):
tiles = dict()
# Fill the remain tiles, and shuffle them
while len(tile_type_collection) < self.tile_amnt:
tile_type_collection.append(TileTypes.desert)
random.shuffle(tile_type_collection)
# Make the tiles in the board
for x in range(-radius, radius):
for y in range(-radius, radius):
for z in range(-radius, radius):
tiles[(x, y, z)] = Tile(x, y, z, tile_type_collection.pop())
return tiles
|
2f8bb126e66e403953cf4f827d0f45256e384a2d | xx-m-h-u-xx/Python-Exercises | /Python-Getters-Setters.py | 731 | 3.671875 | 4 | class MyClass:
def __init__(self, lst):
self.my_list = lst
@property
def my_list(self): # getter
return self._my_list
@my_list.setter
def my_list(self, value): # setter
self._my_list = value
''' Different approach '''
class MyProperty:
def __set__(self, instance, value):
instance.__dict__[self.name] = value
def __get__(self, instance, owner):
if instance is None:
return self
return instance.__dict__[self.name]
def __set_name__(self, owner, name):
self.name = name
class MyClass:
my_list = MyProperty()
def __init__(self, lst):
my_list = lst |
36db69a2a886e230e7408a752a385dc27deb863d | simozhou/data_structure | /bst.py | 5,039 | 3.890625 | 4 | # Binary Search Tree
class TreeNode(object):
def __init__(self, key, value, left=None, right=None, parent=None):
self.key = key
self.payload = value
self.leftChild = left
self.rightChild = right
self.parent = parent
def has_left_child(self):
return self.leftChild
def has_right_child(self):
return self.rightChild
def has_any_children(self):
return self.rightChild or self.leftChild
def has_both_children(self):
return self.rightChild and self.leftChild
def is_left_child(self):
return self.parent and self.parent.leftChild == self
def is_right_child(self):
return self.parent and self.parent.rightChild == self
def is_root(self):
return not self.parent
def is_leaf(self):
return not self.has_any_children()
def replace_node(self, key, value, lc, rc):
self.key = key
self.payload = value
self.leftChild = lc
self.rightChild = rc
if self.has_left_child():
self.leftChild.parent = self
if self.has_right_child():
self.rightChild.parent = self
class BinarySearchTree(object):
def __init__(self):
self.root = None
self.size = 0
def __len__(self):
return self.size
def put(self, key, value):
if self.root:
self._put(key, value, self.root)
else:
self.root = TreeNode(key, value)
self.size += 1
def _put(self, key, value, current_node):
if key < current_node.key:
if current_node.has_left_child():
self._put(key, value, current_node.leftChild)
else:
current_node.leftChild = TreeNode(key, value, parent=current_node)
if current_node.has_right_child():
self._put(key, value, current_node.rightChild)
else:
current_node.rightChild = TreeNode(key, value, parent=current_node)
def get(self, key):
if self.root:
res = self._get(key, self.root)
if res:
return res.payload
else:
return None
else:
return None
def _get(self, key, current_node):
if not current_node:
return None
elif current_node.key == key:
return current_node
elif key < current_node.key:
return self._get(key, current_node.leftChild)
else:
return self._get(key, current_node.rightChild)
def remove(self, current_node):
if current_node.is_leaf():
if current_node == current_node.parent.left_child:
current_node.parent.left_child = None
else:
current_node.parent.right_child = None
else: # this node has one child
if current_node.has_left_child():
if current_node.is_left_child():
current_node.left_child.parent = current_node.parent
current_node.parent.left_child = current_node.left_child
elif current_node.is_right_child():
current_node.left_child.parent = current_node.parent
current_node.parent.right_child = current_node.left_child
else:
current_node.replace_node(current_node.left_child.key,
current_node.left_child.payload,
current_node.left_child.left_child,
current_node.left_child.right_child)
else:
if current_node.is_left_child():
current_node.rightChild.parent = current_node.parent
current_node.parent.left_child = current_node.right_child
elif current_node.is_right_child():
current_node.right_child.parent = current_node.parent
current_node.parent.right_child = current_node.right_child
else:
current_node.replace_node(current_node.right_child.key,
current_node.rightChild.payload,
current_node.right_child.left_child,
current_node.right_child.right_child)
def find_successor(self):
succ = None
if self.has_right_child():
succ = self.rightChild.find_min()
else:
if self.parent:
if self.is_left_child():
succ = self.parent
else:
self.parent.rightChild = None
succ = self.parent.find_successor()
self.parent.rightChild = self
return succ
def find_min(self):
current = self
while current.has_left_child():
current = current.left_child
return current |
74456c81ec3924009193c3d5da7bddeb4953f57b | kartiktanksali/Data-Structures | /CircularLinkedList.py | 4,030 | 4.1875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Mar 31 10:07:23 2019
@author: kartiktanksali
"""
class Node:
def __init__(self,data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
self.tail = None
def push(self,data):
new_node = Node(data)
if self.head == None:
self.head = new_node
self.tail = new_node
self.tail.next = self.head
else:
new_node.next = self.head
self.head = new_node
self.tail.next = new_node
def append(self,data):
new_node = Node(data)
if self.head == None:
self.head = new_node
self.tail = new_node
self.tail.next = self.head
else:
self.tail.next = new_node
self.tail = new_node
self.tail.next = self.head
def deleteFront(self):
if self.head == None:
print("No elements present to delete")
elif self.head == self.tail:
self.head = None
print("Element deleted and also the linked list is empty")
else:
self.head = self.head.next
self.tail.next = self.head
print("Element Deleted")
def deleteRear(self):
if self.head == None:
print("No elements present to delete")
elif self.head == self.tail:
self.head = None
print("Element deleted and also the linked is empty")
else:
temp = self.head
while(temp.next!=self.tail):
temp = temp.next
temp.next = self.head
self.tail = temp
self.tail.next = self.head
print("Element Deleted")
def insertPos(self,pos,data):
new_node = Node(data)
if self.head == None:
self.head = new_node
self.tail = new_node
self.tail.next = self.head
else:
temp = self.head
for _ in range(pos):
temp = temp.next
if temp == self.tail:
self.append(data)
else:
new_node.next = temp.next
temp.next = new_node
print("Element inserted")
def printList(self):
if self.head==None:
print("No elements present to print")
else:
temp = self.head
while(temp):
print(temp.data)
if temp.next==self.head:
return
temp = temp.next
if __name__ == "__main__":
llist = LinkedList()
ch=0
while(ch<7):
print("1) Push an element")
print("2) Append an element")
print("3) Delete an element in the front")
print("4) Delete an element from the rear")
print("5) Insert at a position")
print("6) Print list")
ch = int(input("Enter your choice: "))
print()
if ch==1:
ele = int(input("Enter the element you want to push: "))
llist.push(ele)
elif ch==2:
ele = int(input("Enter the element you want to append: "))
llist.append(ele)
elif ch==3:
llist.deleteFront()
elif ch==4:
llist.deleteRear()
elif ch==5:
ele = int(input("Enter the element to be inserted: "))
pos = int(input("Enter the position: "))
llist.insertPos(pos,ele)
elif ch==6:
llist.printList()
|
4e045126a66aa199ece057e4b1517df997ca61e2 | B10532021/Information_Security_Class | /hw4/B10532030_楊博惟/Rsa.py | 3,957 | 3.8125 | 4 | from math import gcd
import random
def extend_gcd(a, b):
"""
compute extend_gcd: ax + by = gcd(a, b) to generate x, y, gcd(a, b)
:param a: coefficient
:param b: coefficient
:return: x, y, gcd(a, b)
"""
if b == 0: # find gcd
return 1, 0, a
else:
x, y, g = extend_gcd(b, a % b)
return y, (x - (a // b) * y), g
def modulo_inverse(base, modulus):
x, y, g = extend_gcd(base, modulus)
if g != 1: # not coprime
raise Exception('Inverse does not exist')
else:
return x % modulus
def square_and_multiply(base, exponent, modulus) -> int:
"""
compute a^b in square with square-and-multiply algorithm
"""
if exponent < 0:
raise ValueError("Can't compute negative exponent")
binary = bin(exponent).lstrip("0b")
ret = 1
for i in binary:
ret = ret * ret % modulus
if i == '1':
ret = ret * base % modulus
return ret
def miller_rabin_test(p, times=20):
if p == 2 or p & 1 == 0:
return False
def find_components(n):
u = 0
while (n & 1 == 0):
n >>= 1
u += 1
return u, n
k, m = find_components(p - 1)
for i in range(times):
a = random.randrange(2, p - 2)
b = square_and_multiply(a, m, p)
if b != 1 and b != p - 1:
for i in range(k - 1):
if b == p - 1:
break
b = b * b % p
if b == 1:
return False
if b != p - 1:
return False
return True
def get_prime(bits=512):
while (True):
n = random.getrandbits(bits)
if miller_rabin_test(n):
return n
def generate_key(bits=1024, e=65537):
'''
generate RSA key
'''
if bits & 1 == 1:
raise ValueError("Don't use an odd number of bits for the key")
p = get_prime()
q = get_prime()
n = p * q
phi_n = (p - 1) * (q - 1)
assert gcd(e, phi_n) == 1
d = modulo_inverse(e, phi_n)
return p, q, n, e, d
def encrypt(n, e, plaintext: str):
"""
use prime n and e to encrypt plaintext by RSA algorithm
:return: ciphertext after RSA encrypt
"""
hex_str = plaintext.encode('ascii').hex()
num = int(hex_str, 16)
if num > n:
raise Exception("RSA can't encrypt too long plaintext")
ciphertext = square_and_multiply(num, e, n)
return hex(ciphertext)
def decrypt(n, d, ciphertext: str):
num = int(ciphertext, 16)
plaintext_hex = f"{square_and_multiply(num, d, n):x}"
plaintext = bytes.fromhex(plaintext_hex).decode('ascii')
return plaintext
def main():
while True:
print(
"1: generate key\n"
"2: encrypt a plaintext\n"
"3: decrypt a ciphertext\n"
)
option = int(input("select your choice: "))
if option == 1:
bits = int(input("key length(1024 bits is recommended): "))
p, q, n, e, d = generate_key(bits)
print(f"p: {hex(p)}\n"
f"q: {hex(q)}\n"
f"n: {hex(n)}\n"
f"e: {hex(e)}\n"
f"d: {hex(d)}")
elif option == 2:
n = int(input("n(hex string expected): "), 16)
e = int(input("e(hex string expected): "), 16)
plaintext = input("plaintext(must be shorter than the size of n): ")
ciphertext = encrypt(n, e, plaintext)
print(f"ciphertext(hex string): {ciphertext}")
elif option == 3:
n = int(input("n(hex string expected): "), 16)
d = int(input("d(hex string expected): "), 16)
ciphertext = input("ciphertext: ")
plaintext = decrypt(n, d, ciphertext)
print(f"plaintext: {plaintext}")
else:
print("select!!!!!!!!!")
print('-'*100)
if __name__ == '__main__':
main()
|
2988f8f8b94a9efcbbb0ce87aeaeecb2a4cb32f5 | Damns99/4BreviLezioniDiPython | /errori python.py | 1,288 | 3.5625 | 4 | ###Errori comuni
##sintax error
#syntax error è l'errore che appare ogni qualvolta che un comando viene scritto male o viene usato un carattere sbagliato, qui sono riportati alcuni esempi
#print("ciao')
'''
d=5
print("f=%f", %d)
'''
#impord numpy
'''
import numpy
a=numpy.array(dtype=int , [1,1,1,1,1,1,1])
'''
'''
import numpy
a=numpy.array([1,1,1,1,1,1,1], dtype=2 ,dtype=2)
'''
##dividere per zero
'''
import numpy
a=numpy.array([1,2,5,9,0,7,3])
b=1/a
'''
##array di diverse lunghezze
'''
import numpy
a=numpy.array([1,2,5,9,8,7,3])
b=numpy.array([15,8,6,7])
c=a+b
'''
##File not found
'''
import pylab
x, Dx, y, Dy = pylab.loadtxt('dati4.txt', unpack=True)
'''
## index out of bound
'''
import numpy
a=numpy.array([1,1,1,1,1,1,1,1,1,1,1,1])
n=a[12]
'''
## indentation error
'''
def funzione(x, a, b):
return a*x+b
def funzione(x, a, b):m
return a*x+b
n=5
f=9
x=3
h=funzione(x,n,f)
print(h)
'''
## errori di scrittura
'''
import numpy
import pylab
plt.figure(1)
def f(x):
return x**3
x = np.linspace(-1, 1, 1000)
plt.plot(x, f(x))
plt.show(figure=1)
'''
'''
import numpy
a=numpy.array([1,1,1,1,1,1,1], dtype=6)
'''
'''
import numpy
a=numpy.array([1,1,1,1,1,1,1], unpack=True)
'''
##errori di definizione
'''
x=3
b=x+g
print(b)
'''
|
00aebb104e812449f195fb009691e26c94c3e129 | DilipBDabahde/PythonExample | /RP/count_digits.py | 422 | 4 | 4 | '''
9. Write a program which accept number from user and return number of digits in that number.
input: 3235545
output: 7
input: 10
output: 2
'''
def count_digits(no):
icnt = 0;
while no != 0 :
no = no//10;
icnt = icnt + 1;
return icnt;
def main():
ival = int(input("Enter number: "));
result = count_digits(ival);
print("Number of digits are: ", result)
if __name__ == "__main__":
main();
|
24d79e35d709ee9b312f274c3c4b544c917cc782 | sreekar7/LearningPython | /while.py | 253 | 3.9375 | 4 | # Simple demonstration on while loop
i,j = 1,1
while i < 5:
print("hello ", end="") # end="" will stays on the same line
j = 1
while j < 4:
print("Srikar ", end="")
j += 1
i += 1;
print() #Simply prints the newline |
a37193215baacfcfc1576c4e50390235bdfd54a3 | dmiruke/HackerRank-Python | /chocolateFeast.py | 401 | 3.765625 | 4 | #!/bin/python3
# Complete the chocolateFeast function below.
def chocolateFeast(n, c, m):
w = n//c
feast = n//c
while w >= m:
bought = w//m
feast += bought
w = (w - bought*m) + bought
return feast
t = int(input())
for _ in range(t):
ncm = input().split()
n = int(ncm[0])
c = int(ncm[1])
m = int(ncm[2])
print(chocolateFeast(n, c, m))
|
0ce414fbc2c894ae708dfe670f58f6e11211aa36 | QiuHongHao123/Algorithm-Practise | /Suanfa/Saunfa2_2.py | 429 | 3.609375 | 4 | #使子序列中最大值的和最小
from typing import List
def minsmax(nums:List[int],B:int)->int:
lenth=len(nums)
if lenth==1:
return nums[0]
sum=0
minmax=float('inf')
for i in range(lenth-1,-1,-1):
sum=sum+nums[i]
if sum<=B:
minmax=min(max(nums[i:])+minsmax(nums[:i],B),minmax)
else:
break
return minmax
print(minsmax([2,2,2,8,1,8,2,1],20)) |
0aa0d1c6b9578d6357240b1d83b3657e09d86318 | k1oShd/WEB2021SPRING | /lab7/CodingBat/warmup_1/7.py | 233 | 3.671875 | 4 | def pos_neg(a, b, negative):
if(a>0 and b<0 and negative == False):
return True
if(a<0 and b>0 and negative == False):
return True
if(a<0 and b<0 and negative == True):
return True
else:
return False
|
bf9dfbe1eb376e38f059b629312086cda8a91b7c | waitingFat/pythonNotes | /listToCouple.py | 192 | 3.625 | 4 | def ListToCouple():
listFirst = ["zhangsan", "lisi", "wangwu"]
listSecond = ["23", "43", "19"]
print list(zip(listFirst, listSecond))
if __name__ == '__main__':
ListToCouple() |
3767109cdb69487fa54cc24e299487f7c657bf09 | MengSunS/daily-leetcode | /lintcode_578_LCA_iii.py | 1,447 | 3.921875 | 4 | """
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
this.val = val
this.left, this.right = None, None
"""
class Solution:
"""
@param: root: The root of the binary tree.
@param: A: A TreeNode
@param: B: A TreeNode
@return: Return the LCA of the two nodes.
"""
def lowestCommonAncestor3(self, root, A, B):
# write your code here
if not root:
return None
lca, a_exist, b_exist= self.helper(root, A, B)
if a_exist and b_exist:
return lca
else:
return None
def helper(self, root, A, B):
if not root:
return None, 0, 0
left_lca, a_exist_left, b_exist_left= self.helper(root.left, A, B)
right_lca, a_exist_right, b_exist_right= self.helper(root.right, A, B)
a_exist= a_exist_left or a_exist_right or A==root
b_exist= b_exist_left or b_exist_right or B==root
# if not (a_exist and b_exist):
# return None, a_exist, b_exist
if root==A or root==B:
return root, a_exist, b_exist
if left_lca and right_lca:
return root, a_exist, b_exist
if left_lca:
return left_lca, a_exist, b_exist
if right_lca:
return right_lca, a_exist, b_exist
else:
return None, a_exist,b_exist
|
240c92b4570aa350a94ba42cb2a5ca45e9eeaab1 | eDerek/LeetCodeProblems | /Basic Calculator.py | 1,804 | 4.15625 | 4 | # Implement a basic calculator to evaluate a simple expression string.
# The expression string may contain open ( and closing parentheses ), the plus + or minus sign -, non-negative integers and empty spaces .
# Example 1:
# Input: "1 + 1"
# Output: 2
# Example 2:
# Input: " 2-1 + 2 "
# Output: 3
# Example 3:
# Input: "(1+(4+5+2)-3)+(6+8)"
# Output: 23
# Note:
# You may assume that the given expression is always valid.
# Do not use the eval built-in library function.
import re
class Solution:
flag = False
def calculate(self, s: str) -> int:
if not self.flag:
s = s.replace(' ','')
self.flat = True
subEs = re.findall(r'\([\d+-]+\)', s)
if len(subEs) == 0:
return self.simpleExpress(s)
for sub in subEs:
valStr = str(self.simpleExpress(sub.replace('(','').replace(')','')))
s = s.replace(sub, valStr, 1).replace('+-','-', 1).replace('--','+',1)
# print(s)
return self.calculate(s)
def simpleExpress(self, s:str) -> int:
# print(s)
sArray = list(s)
result = 0
currOpt = 1
currVal = 0
for c in sArray:
if c=='+':
# print(currVal)
result += currOpt*currVal
currVal = 0
currOpt = 1
elif c=='-':
result += currOpt*currVal
currVal = 0
currOpt = -1
else:
currVal = currVal*10+int(c)
result += currOpt*currVal
# print(result)
return result
print(Solution().calculate('1 + 1'))
print(Solution().calculate('2-1 + 2'))
print(Solution().calculate('4+5+2'))
print(Solution().calculate('(1+(4+5+2)-3)+(6+8)'))
print(Solution().calculate('2-(5-6)')) |
7f3aff70c21664a5ac05bc4ff76066c95efab97a | Mporzier/piscine-python | /day00/ex04/operations.py | 921 | 3.96875 | 4 | import sys
if (len(sys.argv) != 3):
if (len(sys.argv) > 3):
print("InputError: too many arguments")
print("Usage: python operations.py")
print("Example:")
print(" python operations.py 10 3")
sys.exit()
test1 = sys.argv[1].replace('-', '', 1)
test2 = sys.argv[2].replace('-', '', 1)
if (not test1.isdigit()) or (not test2.isdigit()):
print("InputError: only numbers")
print("Usage: python operations.py")
print("Example:")
print(" python operations.py 10 3")
sys.exit()
first = int(sys.argv[1])
second = int(sys.argv[2])
print("Sum: ", first + second)
print("Difference: ", first - second)
print("Product: ", first * second)
print("Quotient: ", end='')
if second == 0:
print("ERROR (div by zero)")
else:
print(first / second)
print("Remainder: ", end='')
if second == 0:
print("ERROR (modulo by zero)")
else:
print(first % second)
|
895f2bc52fb4d9c5913329470786bad0f2649642 | Stanels42/python-data-structures-and-algorithms | /challenges/quick_sort/quick_sort.py | 954 | 4.0625 | 4 | from copy import deepcopy
from random import randint
def shuffle(lst):
"""
Takes in a list and returns a deep copy with all values in shuffled positions.
In: List
Out: Shuffled (new) List
"""
new_lst = deepcopy(lst)
for i in range(len(new_lst)):
rand = randint(i, len(new_lst) - 1)
new_lst[i], new_lst[rand] = new_lst[rand], new_lst[i]
return new_lst
def quick_sort(arr):
"""
Takes in a list and sorts in place according to the quick sort algorithm
In: List of numbers
Out: Sorted list of numbers
"""
def partition(arr, low, high):
i = low
pivot = arr[high]
for j in range(low, high):
if arr[j] < pivot:
arr[i], arr[j] = arr[j], arr[i]
i += 1
arr[i], arr[high] = arr[high], arr[i]
return i
def recurse(arr, low, high):
if low < high:
pi = partition(arr, low, high)
recurse(arr, low, pi-1)
recurse(arr, pi+1, high)
recurse(arr, 0, len(arr)-1)
|
e79b561f4f71cd9b5bba58b15e38f922e294bc22 | kaviraj333/python | /pb79.py | 147 | 3.59375 | 4 | import math
ammu,abhi=map(int,raw_input().split(' '))
n1=ammu*abhi
if math.sqrt(n1)==int( math.sqrt(n1)):
print ("yes")
else:
print ("no")
|
77998abd2c9dd8c677f450e4f8d4bcd92c98a027 | rafaelperazzo/programacao-web | /moodledata/vpl_data/380/usersdata/332/101158/submittedfiles/principal.py | 157 | 3.578125 | 4 | # -*- coding: utf-8 -*-
#COMECE AQUI ABAIXO
D={'Júlia':(10,9),'Davi':(10,8),'João':(10,7)}
print('dicionario=',D)
D.keys()
print('Chaves do diconario:',D) |
15e88757e99a4285445e4641ff9e86df0c9ff134 | ARWA-ALraddadi/python-tutorial-for-beginners | /03-Workshop/Workshop-Solutions/fun_with_flags.py | 1,564 | 4.28125 | 4 | #--------------------------------------------------------------------
#
# Fun With Flags
#
# In the lecture demonstration program "stars and stripes" we saw
# how function definitions allowed us to reuse code that drew a
# star and a rectangle (stripe) multiple times to create a copy of
# the United States flag.
#
# As a further example of the way functions allow us to reuse code,
# in this exercise we will import the flag_elements module into
# this program and create a different flag. In the PDF document
# accompanying this file you will find several flags which can be
# constructed easily using the "star" and "stripe" functions already
# defined. Choose one of these and try to draw it.
#
# First we import the two functions we need (make sure a copy of file
# flag_elements.py is in the same folder as this one)
from flag_elements import star, stripe
# Import the turtle graphics functions
from turtle import *
# Here we draw the Panamanian flag as an illustration.
#
# Comment: Since this is such a small example, we've hardwired all
# the numeric constants below. For non-trivial programs, however,
# such "magic numbers" (i.e., unexplained numeric values) are best
# avoided. Named, fixed values should be defined instead.
# Set up the drawing environment
setup(600, 400)
bgcolor("white")
title("Panama")
penup()
# Draw the two rectangles
goto(0, 200)
stripe(300, 200, "red")
goto(-300, 0)
stripe(300, 200, "blue")
# Draw the two stars
goto(-150, 140)
star(80, "blue")
goto(150, -60)
star(80, "red")
# Exit gracefully
hideturtle()
done()
|
91da7b96bad9b6280617aaa4e1a49104b45d5b4d | gauthamp10/100DaysOfCode | /005/replace_with_alphabet_pos_6kyu.py | 1,030 | 4.125 | 4 | """In this kata you are required to, given a string, replace every letter with
its position in the alphabet.If anything in the text isn't a letter, ignore it
and don't return it."""
import string
from random import randint
def alphabet_position(text):
"""Function to return alphabet pos"""
alpha_dict = dict(zip(list(string.ascii_lowercase), range(1,27)))
return " ".join([str(alpha_dict[char]) for char in text.lower() if char.isalpha()]) \
if not text.isdigit() else ""
def test_cases():
"""Test cases"""
assert alphabet_position("The sunset sets at twelve o' clock.") \
== "20 8 5 19 21 14 19 5 20 19 5 20 19 1 20 20 23 5 12 22 5 15 3 12 15 3 11"
assert alphabet_position("The narwhal bacons at midnight.") \
== "20 8 5 14 1 18 23 8 1 12 2 1 3 15 14 19 1 20 13 9 4 14 9 7 8 20"
number_test = ""
for item in range(10):
number_test += str(randint(1, 9))
assert alphabet_position(number_test) == ""
print("Test Success!")
test_cases()
|
1da8a353e8ee468c142132a81af6de95052c901d | lilsweetcaligula/sandbox-codewars | /solutions/python/390.py | 203 | 3.515625 | 4 | def logical_calc(array, op):
import operator, functools
op = (op == "AND" and operator.and_
or op == "OR" and operator.or_
or operator.xor)
return functools.reduce(op, array) |
59a875cc48207fc5bee788111de22ee25c114bda | VCloser/CodingInterviewChinese2-python | /50_01_FirstNotRepeatingChar.py | 326 | 3.828125 | 4 | def first_not_repeating_char(s):
maps = {}
for i in s:
if i not in maps:
maps[i] = 1
else:
maps[i] += 1
for i in s:
if maps[i] == 1:
return i
return None
if __name__ == '__main__':
res = first_not_repeating_char("qwertytrewqf")
print(res) |
bd50c455079eaab37332233a6d2b76ba8813d679 | aston-github/CS101 | /F19-Assign4-Hangman/CheckMyFunctions.py | 1,377 | 3.859375 | 4 | '''
This module is for you to use to test your implemention of the functions in Hangman.py
@author: ksm
'''
import random
import Hangman
if __name__ == '__main__':
print('Testing createDisplayString')
lettersGuessed = ['a', 'e', 'i', 'o', 's', 'u']
misses = 4
hangmanWord = list('s___oo_')
s = Hangman.createDisplayString(lettersGuessed, misses, hangmanWord)
print(s)
print()
print('Testing updateHangmanWord')
guessedLetter = 'a'
secretWord = 'cat'
hangmanWord = ['c', '_', '_']
expected = ['c', 'a', '_']
print('Next line should be: ' + str(expected))
print(Hangman.updateHangmanWord(guessedLetter, secretWord, hangmanWord))
print()
print('Testing createDisplayString')
lettersGuessed = ['a', 'e', 'i', 'o', 's', 'u']
missesLeft = 4
hangmanWord = ['s','_','_','_','o','o','_']
print(Hangman.createDisplayString(lettersGuessed, missesLeft, hangmanWord))
print()
def getWord(words, length):
chosen_words = [word for word in words if len(word) == length]
return random.choice(chosen_words)
length = random.randint(5,10)
file = open('lowerwords.txt', 'r')
words = [line.strip() for line in file.readlines()]
secretWord = getWord(words, length)
print(words)
print(length)
print(secretWord) |
ffe61fdb7752ab81cf7cb79940ad1f054871c107 | iRaM-sAgOr/road_accident | /main.py | 360 | 3.546875 | 4 | import random
start = 0
end = 0
digit = ''
for i in range(1, 11):
start = (start * 10) + 1
end = (end * 10) + 9
print("start and end is ", start, end)
for j in range(1, 101):
k = random.randint(start, end)
print(j, k)
digit=digit +'\n'+ str(k)
with open("number.txt", "w") as text_file:
text_file.write(str(digit)) |
38769d6450d8f9bf199776ebfc34bb215829b4d1 | Rohini-Vaishnav/list | /log4.py | 195 | 3.8125 | 4 | a=["A","B"]
b=[]
i=1
n=int(input("enter the number"))
while i<=n:
j=0
while j<len(a):
b=b+[a[j]+str(i)]
j=j+1
i=i+1
print(b)
#Logical questions output: user 2 de to ["A1","B1","A2","B2"] |
7a31bed90fb97e497f1220929302bd69323ddc6d | Miloloaf/Automate-The-Boring-Stuff | /chapter_9/prefixadder | 764 | 4.09375 | 4 | #! python3
#! Adds specified prefix to start of all file names in the directory
import os, shutil
os.chdir(r"Directory") #Insert new directory here
items_list = os.listdir(os.getcwd())
appendage = str(input("Please enter a prefix to files: \n"))
remove = str(input("Would you like to remove the original files (y/n)?: "))
for item in items_list:
new_name = appendage + item
print (new_name)
orig_file = os.path.join(os.getcwd(),item)
new_file = os.path.join(os.getcwd(),new_name)
if remove == "y":
shutil.move(orig_file, new_file)
elif remove == "n":
shutil.copy(orig_file,new_file)
#
else:
print("You have not inputted a valid paramiter for remove, please try again")
break
# os.path.isfile()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.