blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
a9caabb7d64a398881bbc8c2d25fb8413ac8e1ef | AnoopMasterCoder/python-course-docs | /10. Chapter 10/03_classattributes.py | 559 | 4.09375 | 4 | # A very basic sample class
class Employee:
name = "Harry" # A class attribute
marks = 34
center = "Delhi"
def printObj(self):
print(f"The name is {self.name}")
@staticmethod
def greet():
print("good day")
Employee.name = "HarryNew" # Setting a class attribute for Employee
harry = Employee() # A basic object
shyam = Employee() # A basic object
print(harry.name)
print(shyam.name)
shyam.name = "Shyam" # Setting an instance attribute to shyam
print(shyam.name)
print(harry.name)
harry.greet()
Employee.greet() |
1ccd710129f3409d35ad493e4cecb3271daffb7d | n-ramadan/assignment-aug-2020 | /question1.py | 600 | 3.546875 | 4 | # Split a file which has n number of schema def. And store them in a dict of lists(no 3rd party imports)
# File to read: to_read.txt / question1_text.txt
#Set first field value as dictionary key
dic1 = {}
with open("question1_text.txt", "r") as file:
for line in file:
line_split = line.split(',')
line_split = [x.strip(" ").strip("\n") for x in line_split] #clean trailing whitespaces
key = line_split[0]
try:
dic1[key].append(line_split[1:])
except:
dic1[key] = []
dic1[key].append((line_split[1:]))
|
206f6b89072b98935e7076fc1e1d0c1493c6930f | svoges/hw8 | /parks_path.py | 682 | 3.515625 | 4 | def algorithm(G, l, k):
dist = [m][m]
seen = {m}
for each vertex v in V:
dist[v][v] = 0 #distance from v to v is 0
for each edge (u, v) in l:
dist[u][v] = l[u][v]
for a = 1...|V|:
for b = 1...|V|:
for c = 1...|V|:
if dist[b][c] > dist[b][a] + dist[a][c]:
dist[b][c] = dist[b][a] + dist[a][c]
shortest_path = [m - k][k]
for i = 0...m:
for all j = 0...i:
shortest_path[i][j] = 0
for j = i + 1...k:
shortest_path[i][j] = min(l[i - 1][i] + shortest_path[i - 1][j -1], shortest_path[i - 1][j])
return minimum != 0 at column k in shortest_path
|
fb1f7fc1e470e9f0c38cfca9c1f0d8b60a853c86 | YogeshSingla/balia | /3_genetic_algorithms/gen_mln.py | 2,873 | 3.78125 | 4 | import numpy as np
from matplotlib import pyplot as plt
#training set
datasetxor = np.array([
[0,0,0],
[0,1,1],
[1,0,1],
[1,1,0],
]);
def sigmoid(val):
res = 1/(1+np.exp(-val));
return res;
def predict_xor(row, w):
activation = w[0];#for bias
for i in range(len(row)):
activation += w[i+1]*row[i];
activation = sigmoid(activation);
if activation>=0.5:
res = 1;
else:
res = 0;
return activation, res;
def train_perceptron(dataset, lrate, nepoch,w):
y = np.zeros(3);#y0 and y1 for hidden layer and y2 for ouput layer
delta = np.zeros(3);#for three gradients
for epoch in range(nepoch):
for row in dataset:
#forward propagation
y[0], y0b = predict_xor(row[:2], w1);
y[1], y1b = predict_xor(row[:2], w2);
y[2], y2b = predict_xor(y[:2], w3);
error = row[-1]-y[2];
delta[2] = y[2]*(1-y[2])*error;
w3[0] -= lrate*delta[2];#updating bias
for i in range(len(w3)-1):
w3[i+1] += lrate*y[i]*delta[2];
delta[1] = y[1]*(1-y[1])*delta[2]*w3[2];
w2[0] -= lrate*delta[1];
for i in range(len(w2)-1):
w2[i+1] += lrate*row[i]*delta[1];
delta[0] = y[0]*(1-y[0])*delta[2]*w3[1];
w1[0] -= lrate*delta[0];
for i in range(len(w1)-1):
w1[i+1] += lrate*row[i]*delta[0];
w = np.append(w1, w2, axis=0);#to append column wise
w = np.append(w, w3, axis=0);
return w;
def predict(x, w):
w1 = w[:3];#bias is w[0]
w2 = w[3:6];#for hidden layers
w3 = w[6:];#for output layer
y = np.zeros(3);
y[0], y0b = predict_xor(x, w1);
y[1], y1b = predict_xor(x, w2);
y[2], res = predict_xor(y[:2], w3);
print(y[2]);
return res;
def plot_graph_xor(w):
x_intercept = -w[0]/w[1];#for x1 on x-axis
y_intercept = -w[0]/w[2];#for x2
x_cord = [x_intercept, 0];
y_cord = [0, y_intercept];
plt.plot(x_cord, y_cord);
plt.plot(0, 0, 'bo');
plt.plot(0, 1, 'bo');
plt.plot(1, 0, 'bo');
plt.plot(1, 1, 'ro');
plt.xlabel('x1');
plt.ylabel('x2');
plt.title('Classification for XOR gate');
#input processing
ip = '1 1'
x = [int(y) for y in ip.split(' ')];
#training and testing the perceptron
lrate = 0.1
nepoch = 10
#w1 = np.zeros(len(dataset[0]));#bias is w[0]
w1 = np.zeros(3);#bias is w[0]
w2 = np.zeros(3);#for hidden layers
w3 = np.zeros(3);#for output layer
weights = w1 + w2 + w3
w = train_perceptron(datasetxor, lrate, nepoch,weights)
bias = np.array([w[0], w[3], w[6]])
print(bias);
pred = predict(x, w);
print("Predicted XOR output for given input: ", pred)
print(w)
|
3d61c23cf750a552bae4770d67e8f12f587b43b4 | green-fox-academy/Angela93-Shi | /week-03/day-01/paperback_book.py | 821 | 3.640625 | 4 | # It should have the following fields: title, author, release year, page number and weight.
# The weight must be calculated from the number of pages (every page weighs 10 grams) plus the weight of the cover which is 20 grams.
# It must have a method that returns a string which contains the following information about the book: author, title and year.
from book import Book
class Paperback_book(Book):
def __init__(self,author,title,release_year,page_number,weight):
Book.__init__(self,author,title,release_year)
self.page_number = page_number
self.weight = self.get_weight
def toString(self):
return f'author: {self.author}, title: {self.title}, year: {self.release_year}'
def get_weight(self):
weight = self.page_number * 10 + 100 *2
return weight
|
41919dbd3918fdc77ba9d0dde91f941e96154225 | RusyaDeWitt/ICT | /task_1/10.py | 235 | 3.734375 | 4 | import math
a = int(input())
b = int(input())
print("Sum is",a+b)
print("Difference is",a-b)
print("Product is",a*b)
print("Quotient is",a//b)
print("Remainder is",a%b)
print("A log10 is",math.log10(a))
print("A power of b is",a**b)
|
171e248744a609517eea1ec2d7b96400a26bf4c0 | Daniyar-Yerbolat/university-projects | /year 2/semester 1/programming languages/labs/question J - Daniyar Nazarbayev [H00204990].py | 2,318 | 4.125 | 4 | # answers to other questions are in .docx file.
# Question J #5
def even(n):
return [x for x in range(n*2) if x%2==0]
# after thinking for a while i realized that after every even number there is
# and odd number, and after every odd number there is an even number
# and that's how i made the program display first n even numbers.
# i simply multiplied n by 2
# Question J #6
def divide3(llist):
return [x for x in llist if x%3==0]
# Question J #7
def ziplists(list1, list2):
return [(list1[x],list2[x]) for x in range(len(list1))]
# Question J #8
# Low complexity, but can run out of memory when the input is 100,000,000.
def penta_square(bound):
pentagonals = [x*(3*x-1)//2 for x in range(bound)]
squares = set([x*x for x in range(bound)])
return squares.intersection(pentagonals)
# High complexity - O(n2).
def penta_square2(bound):
return [x*(3*x-1)//2 for x in range(bound) for y in range((x*(3*x-1)//2)+1) if x*(3*x-1)//2==y*y]
# Identical to the 2nd function - O(n2).
def penta_square3(bound):
pentagonals = [x*(3*x-1)//2 for x in range(bound)]
return [y*y for x in pentagonals for y in range(x+1) if x==y*y]
# Okaish complexity, O(n).
import math
def penta_square4(bound):
return [x*(3*x-1)//2 for x in range(bound) if (math.sqrt(x*(3*x-1)//2)).is_integer()]
# Question J #9
def nest(n):
if (n==0):
return []
else:
return [nest(n-1)]
def unnest(llist):
counter = 0
while(type(llist) is list and len(llist)>0):
counter = counter + 1
llist = llist[0]
return counter
import copy
def add_nests(list1, list2):
temp1 = copy.copy(list1)
temp2 = copy.copy(list2)
while(len(list2)>0):
emptylist = [] # [].append([[]]) should give [[[]]]
list2 = list2[0]
emptylist.append(list1)
list1 = emptylist[:] # deep copy
output = list1[:]
list1 = temp1
list2 = temp2
return output
def mult_nests(list1, list2):
temp1 = copy.copy(list1)
temp2 = copy.copy(list2)
if(list2==[] or list1==[]):
return []
lcopy = list1[:]
list1 = [] # for multiplying by 1.
while(len(list2)>0):
list2 = list2.pop(0)
list1 = add_nests(list1, lcopy)
output = list1[:]
list1 = temp1
list2 = temp2
return output
|
8a0fecb7a60d22e7c10a43e9546caf655808fac4 | TheSergiox/introprogramacion | /Quiz/QuizGraficod.py | 2,788 | 3.734375 | 4 | import matplotlib.pyplot as plt
#--------Punto 1-------#
#---constantes---#
Saludo = "Hola profe este es mi quiz 4"
Soborno = "profe si gano el quiz nos vamos por unas polas"
despetida = "ahi esta su quiz, *se voltea indignado por la dificultad del quiz*"
Pregunta_snacks = " Ingrese por favor sus snacks favoritos : "
Pregunta_PrecioSnack = "ingrese por favor el valor del snack : "
snacks = []
n=5
#---entrada al codigo---#
print(Saludo)
print(Soborno)
while (n>0):
snack = input (Pregunta_snacks)
snacks.append(snack)
n=n-1
precios = []
n=5
while (n>0):
precio = int(input(Pregunta_PrecioSnack))
precios.append(precio)
n=n-1
plt.bar(snacks,precio, width=0.7, color='b')
#-----------------------
plt.title('Snacks favoritos y precio de estos mismos')
plt.xlabel('Snacks')
plt.ylabel('Valor del snack')
plt.savefig('graficoBSanack.png')
#-----------------------
plt.show()
#-----------Punto 2----------#
Pregunta_Ciudad = "ingrese una ciudad de colombia :"
Pregunta_poblacion = "ingrese la poblacion de esa cidad : "
ciudades = []
n=5
while (n>0):
ciudad = input(Pregunta_Ciudad)
ciudades.append(ciudad)
n=n-1
sizes = []
n=5
while (n>0):
poblacion = int(input(Pregunta_poblacion))
sizes.append(poblacion)
n=n-1
def etiquetarElementosPorcentuales(sizes, labels, indicador= ' ->'):
acumulador = 0
for elemento in sizes :
acumulador +=elemento
for i in range (len(labels)):
ciudades[i] += indicador+str(round(sizes[i]/acumulador*100,2)) + "%"
etiquetarElementosPorcentuales(sizes,ciudades,'-')
plt.pie(sizes,labels=ciudades,shadow=1,counterclock=1)
plt.title("ciudades favoritas" )
plt.savefig("CiudadesTorta.png")
#---------#
maximo = max(sizes)
ubicacion = sizes.index(maximo)
print(ubicacion)
plt.show()
#--------punto3---------#
print ('Punto 3 --- Grafico curvas')
print ('ecg = Un electrocardiograma ECG es un examen que registra la actividad eléctrica del corazón.')
print ('ppg = Es una técnica de pletismografía en la cual se utiliza un haz de luz para determinar el volumen de un órgano')
import pandas as pd
ppgData = pd.read_csv ('ppg.csv', encoding = 'UT8', header = 0, delimiter = ';').to_dict ()
muestras = list (ppgData ['muestra'].values ())
valores = list (ppgData ['valor'].values ())
plt.plot (muestras, valores)
plt.xlabel ('Tiempo (ms)')
plt.ylabel ('Voltaje (mV)')
plt.title ('Fotopletismografia')
plt.savefig ('Grafico ppg.png')
##
ecgData = pd.read_csv ('ecg.csv', encoding = 'UT8', header = 0, delimiter = ';').to_dict ()
muestra1 = list (ecgData ['muestra'].values ())
voltaje = list (ecgData ['valor'].values ())
plt.plot (muestra1, voltaje)
plt.xlabel ('Tiempo (ms)')
plt.ylabel ('Voltaje (mV)')
plt.title ('Electrocardiograma')
plt.savefig ('Grafico ecg.png')
plt.show () |
817d51e2dbece1d2028797d5663cc83000a4ee1b | emanoelmlsilva/ExePythonBR | /Exe.Funçao/Fun.09.py | 221 | 3.953125 | 4 | def inverso(n):
# n = list(str(n))
# n.reverse()
n = str(n)
for i in range(len(n),0,-1):
print(n[i-1],end='')
print()
num = int(input("Digite o numero: "))
#print(inverso(num))
print("Inverso",end=' ')
inverso(num)
|
baecbd435f16d0ac63cc6cf409df86dcc2c38ed2 | EtoKazuki/python_practice | /ex10.py | 663 | 3.890625 | 4 | year = int(input("年>"))
month = int(input("月>"))
day = int(input("日>"))
weekday = (year + (year // 4) - (year // 100) + (year // 400) + ((13*month+8) // 5) + day) % 7
if weekday == 0:
weekday = "日曜日"
elif weekday == 1:
weekday = "月曜日"
elif weekday == 2:
weekday = "火曜日"
elif weekday == 3:
weekday = "水曜日"
elif weekday == 4:
weekday = "木曜日"
elif weekday == 5:
weekday = "金曜日"
elif weekday == 6:
weekday = "土曜日"
if month == 13:
month = month%12
year = year+1
elif month == 14:
month = month%12
year = year+1
print(year,"年",month,"月",day,"日は",weekday,"です。")
|
c7dfba2a6b679a92b9f4f4b5c59196ac13d19771 | SakuraGo/leetcodepython3 | /ZS/ZS158_01.py | 1,135 | 3.859375 | 4 | # 5222. 分割平衡字符串 显示英文描述 我的提交返回竞赛
# 题目难度 Easy
# 在一个「平衡字符串」中,'L' 和 'R' 字符的数量是相同的。
#
# 给出一个平衡字符串 s,请你将它分割成尽可能多的平衡字符串。
#
# 返回可以通过分割得到的平衡字符串的最大数量。
# 输入:s = "RLRRLLRLRL"
# 输出:4
# 解释:s 可以分割为 "RL", "RRLL", "RL", "RL", 每个子字符串中都包含相同数量的 'L' 和 'R'。
class Solution:
def balancedStringSplit(self, s: str) -> int:
lcnt = 0
rcnt = 0
lis = []
preIdx = 0
for idx,c in enumerate(s):
if c == "L":
lcnt+= 1
if lcnt == rcnt:
lis.append(s[preIdx:idx+1])
preIdx = idx+1
lcnt = 0
rcnt = 0
else:
rcnt += 1
if lcnt == rcnt:
lis.append(s[preIdx:idx+1])
preIdx = idx+1
lcnt = 0
rcnt = 0
return len(lis)
|
2a12acb6dd57fb0d0b900657ccd4d3670630fb56 | KevinAS28/Python-Training | /solo7.py | 414 | 3.8125 | 4 | #!/usr/bin/python
print "penggunaan if"
aku = 9
if aku > 7:
print("five")
if aku < 100:
print("buset")
print ' '
print 'pake else'
kamu = 90
if kamu == 900:
print 'pas'
else:
print 'nga pas'
print ' '
print ' '
print "ADVANCED PEMAKAIAN IF DAN ELSE DENGAN CHAIN"
masa = 12
if masa == 90:
print 'sembilan puluh'
else:
if masa == 12:
print 'benar'
else:
if masa == 30:
print 'salah'
|
8f1eaa9413cc70b8769d07a95d5a4b9788f54d34 | katheroine/languagium | /python/scopes/functions_and_scopes.py | 438 | 3.5625 | 4 | #!/usr/bin/python3
# g is in the global namespace
g = 5
print(f"{g}\n")
def some_function():
# f is in the local function namespace
f = 6
# g is readable but not modifiable
print(f"{g}, {f}\n")
def some_nested_function():
# nf is in the nested local function namespace
nf = 7
# g is readable but not modifiable
print(f"{g}, {f}, {nf}\n")
some_nested_function()
some_function()
|
a983bb72ed6cdd239924a307868159c91d329edd | tpt5cu/python-tutorial | /language/python_27/built_in_types/sequence_/list_/comprehension/performance.py | 1,454 | 3.921875 | 4 | # https://portingguide.readthedocs.io/en/latest/iterators.htmo
# https://stackoverflow.com/questions/1247486/list-comprehension-vs-map - gory details
import timeit
numbers = [1, 2, 3, 4, 5, 6, 7]
powers_of_two_map = map(lambda x: 2**x, numbers)
powers_of_two_comp = [2**x for x in numbers]
'''
The results are surprising: using functions is faster than using list comprehensions in Python 3 while the opposite it true for Python 2
- Use comprehensions because they are more readable
'''
def use_functions():
for number in filter(lambda x: x < 20, powers_of_two_map):
#print(number) # 2\n4\n8\n16
number += 1
def use_list_comprehensions():
for number in [x for x in powers_of_two_comp if x < 20]:
#print(number) # 2\n4\n8\n16
number += 1
def time_function_usage():
'''
- Python 2: 1.65262982845
- Python 3: 0.4861466310999999
'''
print(sum(timeit.repeat(
setup='from __main__ import powers_of_two_map, use_functions;',
stmt='use_functions()',
repeat=10
))/10)
def time_list_comprehension_usage():
'''
- Python 2: 0.772179818153
- Python 3: 1.2467536622000002
'''
print(sum(timeit.repeat(
setup='from __main__ import powers_of_two_comp, use_list_comprehensions;',
stmt='use_list_comprehensions()',
repeat=10
))/10)
if __name__ == '__main__':
#time_function_usage()
time_list_comprehension_usage() |
360418d0ae259dbce9f752a7c59814a2606d7c3c | ytreeshan/BeginnerPython | /ShadesofBlue.py | 242 | 3.546875 | 4 | #Name: Treeshan Yeadram
#Date: 9/27/18
import turtle
turtle.colormode(255)
tess = turtle.Turtle()
tess.shape("turtle")
tess.backward(100)
for i in range(0,255,10):
tess.forward(10)
tess.pensize(i)
tess.color(0,0,i)
|
2a0869b85589c5ad7b883fc51775f84f84f7a0ba | EpicureanHeron/courseraIntroPython | /rps.py | 1,726 | 3.8125 | 4 | # http://www.codeskulptor.org/#user29_iZ09AlcCpR_40.py
import random
def name_to_number(name):
if name == "rock":
name_number = 0
return name_number
elif name == "Spock":
name_number = 1
return name_number
elif name == "paper":
name_number = 2
return name_number
elif name == "lizard":
name_number = 3
return name_number
elif name == "scissors":
name_number = 4
return name_number
else:
return "Error in name_to_number"
def number_to_name(number):
if number == 0:
number_name = "rock"
return number_name
elif number == 1:
number_name = "Spock"
return number_name
elif number == 2:
number_name = "paper"
return number_name
elif number == 3:
number_name = "lizard"
return number_name
elif number == 4:
number_name = "scissors"
return number_name
else:
print "Error in number_to_name"
def rpsls(player_choice):
print " "
player_number = name_to_number(player_choice)
comp_number = random.randrange(4)
comp_choice = number_to_name(int(comp_number))
print "Player choses", player_choice
print "Computer choses", comp_choice
difference = (player_number - comp_number)
modulo = difference % 5
if modulo == 0:
print "Player and computer tie!"
elif modulo == 1:
print "Player wins!"
elif modulo == 2:
print "Player wins!"
elif modulo == 3:
print "Computer wins!"
elif modulo == 4:
print "Computer wins!"
rpsls("rock")
rpsls("Spock")
rpsls("paper")
rpsls("lizard")
rpsls("scissors") |
225e0f494add75997fa09e0a1e5c368a26ffbe89 | william-schor/e2eLan | /ecdhe.py | 3,846 | 3.703125 | 4 | #!~/.pyvenvs/elliptic_curve
# -*- coding: utf-8 -*-
"""A simple implementation of Diffie Hellman Elliptic Curve Crypto
Functions
-----------
f(str, int): finds the int in the str and returns the index
"""
import os
import sys
import secrets
import time
# Curve constants
secp256k1_P = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F
secp256k1_A = 0x0
secp256k1_B = 0x7
secp256k1_Gx = 0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798
secp256k1_Gy = 0x483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8
secp256k1_N = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141
secp256k1_H = 0x1
class Point(object):
def __init__(self, x, y):
self.x = x
self.y = y
def __eq__(self, other):
if isinstance(other, self.__class__):
return self.__dict__ == other.__dict__
else:
return False
class CurveParams(object):
"""This class defines the public parameters for the curve"""
def __init__(self, p, a, b, Gx, Gy, n, h):
self.p = p
self.a = a
self.b = b
self.G = Point(Gx, Gy)
self.n = n
self.h = h
self.O = "Origin"
def valid(P, params):
if P == params.O:
return True
else:
return (
(P.y ** 2 - (P.x ** 3 + params.a * P.x + params.b)) % params.p == 0
and 0 <= P.x < params.p
and 0 <= P.y < params.p
)
def inv_mod(x, params):
assert x % params.p != 0
# This is the inverse by Fermat's Little Theorem
return pow(x, params.p - 2, params.p)
def ec_add(P, Q, params):
assert valid(P, params) and valid(Q, params)
if P == params.O:
result = Q
elif Q == params.O:
result = P
elif Q.x == P.x and Q.y != P.y:
result = params.O
else:
dydx = (Q.y - P.y) * inv_mod(Q.x - P.x, params)
x = (dydx ** 2 - P.x - Q.x) % params.p
y = (dydx * (P.x - x) - P.y) % params.p
result = Point(x, y)
assert valid(result, params)
return result
def ec_double(P, params):
assert valid(P, params)
if P == params.O:
result = P
else:
dydx = (3 * P.x ** 2 + params.a) * inv_mod(2 * P.y, params)
x = (dydx ** 2 - P.x - P.x) % params.p
y = (dydx * (P.x - x) - P.y) % params.p
result = Point(x, y)
assert valid(result, params)
return result
# using double and add method for log_2(k) complexity
def ec_mult(P, k, params):
if not (valid(P, params)):
raise ValueError("Invalid Point")
bits = f"{k:b}"[::-1]
Q = params.O
N = P
for bit in bits:
if bit == "1":
Q = ec_add(Q, N, params)
N = ec_double(N, params)
return Q
def get_priv_key(params):
return secrets.randbelow(params.n)
def pp(P):
try:
print(f"({P.x}, {P.y})")
except:
print(P)
# Calculate the value to be sent
def dh_phase_1(priv_key, params):
return ec_mult(params.G, priv_key, params)
# Calculate shared secret with recieved value
def dh_phase_2(priv_key, P, params):
return ec_mult(P, priv_key, params)
# def main(args):
# params = CurveParams(30, secp256k1_A,
# secp256k1_B, secp256k1_Gx, secp256k1_Gy, secp256k1_N, secp256k1_H)
# # Alice
# alice_priv_key = get_priv_key(params)
# send_to_bob = dh_phase_1(alice_priv_key, params)
# # Bob
# bobs_priv_key = get_priv_key(params)
# send_to_alice = dh_phase_1(bobs_priv_key, params)
# # Alice
# shared_secret_alice = dh_phase_2(alice_priv_key, send_to_alice, params)
# # Bob
# shared_secret_bob = dh_phase_2(bobs_priv_key, send_to_bob, params)
# assert (shared_secret_bob == shared_secret_alice)
# # pp(shared_secret_alice)
# print(inv_mod(2, params))
# if __name__ == '__main__':
# sys.exit(main(sys.argv))
|
364e5d94320977aa500266cf1c9acd4817a3e632 | sunwenbo/python | /1.面向对象/类/面向对象第一个类.py | 2,228 | 3.890625 | 4 | #__author: Administrator
#date: 2019/12/8
'''
设计类
类名:见名之意,首字母大写,其他遵循驼峰原则
属性:见名之意,其他遵循驼峰原则
行为(方法/功能):见名之意,其他遵循驼峰原则
创建类
类:一种数据类型,本身并不占内存空间,根所学过的number,string,Boolean等类似。
用类创建实例化对象(变量),对象占内存空间
格式:
class 类名(父类列表):
属性
行为
'''
# object:基类,超类,所有类的父类
#一般没有合适的父类就写object
class Person(object):
#定义属性
name = ""
age = 0
height = 0
weight = 0
#定义方法(定义函数)
#注意:方法的参数必须以self当第一个参数
#self代表类的实例(某个对象)
def run(self):
print("run")
def eat(self, food: object) -> object:
print("eat " + food)
def openDoor(self):
print("我已经打开了冰箱门")
def fillEle(self):
print("我已经把大象装进冰箱了")
def clossDoor(self):
print("我已经关闭了冰箱门")
"""
实例化一个对象
格式:对象名=类名(参数列表)
注意:没有参数,小括号也不能省略
"""
per1 = Person()
print(per1)
print(type(per1))
per2 = Person()
print(per2)
print(type(per2))
# 变量在栈区,对象在堆区
print(id(per1))
print(id(per2))
#访问对象的属性与方法
'''
访问属性
格式:对象名.属性名
赋值:对象名.属性名 = 新值
'''
per1.name = "tom"
per1.age = "18"
per1.height = "170"
per1.weight = "80"
print(per1.name,per1.name,per1.height,per1.weight)
'''
访问方法
格式,对象名.方法名(参数列表)
'''
per1.openDoor()
per1.fillEle()
per1.clossDoor()
per1.eat("苹果")
#问题:目前来看Person创建的所有对象属性都是一样的
#对象的初始状态,构造函数
'''
构造函数: __init__(): 在使用类创建对象的时候自动调用
注意:如果不显示的写出构造函数,默认回自动添加一个空的构造函数
'''
per1 = Person("sunwenbo",24,177,80)
print(per1)
|
3a10df1a353c11fd8bb4ef3105b4e844ca462fc1 | youngheon/DataStructureExample | /src/com/youngheon/stack/Stack.py | 245 | 3.578125 | 4 | #-*- coding:utf-8-*-
__author__ = 'Heon'
def Main():
stack=[] # stack 생성
stack.append(1)
stack.append(2)
stack.append(3)
stack.append(4)
print stack
while stack:
print "POP > ", stack.pop()
Main()
|
f8d690a1c2490517b3ff26bf66356eef88208b6e | nababanyogi/python-OOP | /oop2.py | 714 | 3.625 | 4 | #03 - Class dan Instance variables
class Hero:#template
#class variable
jumlah = 0
def __init__(self,inputName,inputHealth, inputPower, inputArmor):
# instance variable
self.name = inputName
self.health = inputHealth
self.power = inputPower
self.armor = inputArmor
Hero.jumlah+=1
print("membuat Hero dengan nama "+inputName)
hero1 = Hero("Sniper", 100 ,10 ,4)
print(Hero.jumlah)
hero2 = Hero("Sven" , 100 ,15 ,1)
print(Hero.jumlah)
hero3 = Hero("Mirana", 1000,100 ,0)
print(Hero.jumlah)
# print(hero1.__dict__)
# print(hero2.__dict__)
# print(hero3.__dict__)
# print(hero1)
# print(hero2)
# print(hero3)
# print(Hero.__dict__)
|
e4275a8ed2d35e8de70ecb8c68d51506c0742659 | Paprok/Training_Logbook | /log.py | 4,395 | 3.96875 | 4 | # log book - open it when on the gym. PrintOut exercises and get results.
import time
import datetime
import os
class LogBook:
'''This class work as a diary/log book for user. Workout results can be logged in and saved to file.'''
def __init__(self, workout_for_today,):
self.workout_for_today = workout_for_today
self.exercises_list = self.load_file()
self.is_training = True
# Get exercises from file
def load_file(self):
with open(self.workout_for_today) as file:
lines = file.readlines()
exercises = []
for i in range(len(lines)):
exercise = lines[i].replace('\n', '').split('\t')
exercises.append(exercise)
return exercises
# Print workout plan
def print_workout(self):
while self.is_training:
print("\nHello! Today you have following exercises to do:\n")
for i in range(len(self.exercises_list)):
print('Exercise no{0}\n\t{1}. Do {2} sets of {3} repetitions with {5}kg\n\tRest {4}sek between sets.'
'Your tempo should be {6}\n'
.format(i+1, self.exercises_list[i][1], self.exercises_list[i][2], self.exercises_list[i][3],
self.exercises_list[i][4], self.exercises_list[i][5], self.exercises_list[i][6]))
self.start_exercise()
# Ask user if he want to start working out
def start_exercise(self):
corect_input = False
while not corect_input:
try:
lets_start = str.upper(input("Insert Y to start or N to quit to menu: "))
if lets_start == 'Y':
start_workout_time = time.time()
self.get_workout_results(start_workout_time)
corect_input = True
# self.workout_duration(start=True)
elif lets_start == 'N':
print("stop")
self.is_training = False
return self.is_training
# menu.start_module()
else:
raise ValueError('{} is not corect choice.'.format(lets_start))
except ValueError as err:
print('You entered wrong input! {}'.format(err))
# Get result via user input
# recieve time of workout begining and retur duration time to file
def get_workout_results(self, start_workout_time):
for an_excercise in range(len(self.exercises_list)):
print("Do excersise no{}\n\t-{}".format(an_excercise+1, self.load_file()[an_excercise][1]))
no_of_sets = int(self.exercises_list[an_excercise][2])
self.log_result_in(self.exercises_list[an_excercise][1])
for a_set in range(no_of_sets):
corect_input = False
while not corect_input:
try:
result_of_set = int(input('Set no{}. Enter here no of reps: '.format(a_set + 1)))
self.log_result_in(result_of_set)
self.rest_count_down(int(self.exercises_list[an_excercise][4]))
except ValueError:
print("Please enter number of reps!")
else:
corect_input = True
self.log_result_in('\n')
current_time = time.time()
workout_duration_time = round(current_time - start_workout_time)
self.log_result_in('Your workout duration is: ')
self.log_result_in(str(datetime.timedelta(seconds=workout_duration_time)))
self.is_training = False
return self.is_training
def beep(self, seconds, frequency):
return os.system('play --no-show-progress --null --channels 1 synth %s sine %f' % (seconds, frequency))
def rest_count_down(self, time_of_rest):
print("\n\tREST FOR...\n")
for i in range(time_of_rest, 1, -1):
seconds = i
print('{:->10} sec'.format(seconds))
time.sleep(1.0)
self.beep(1, 440)
# Write workout data to file
def log_result_in(self, an_input):
with open('workoout_user_date', 'a') as file:
file.write(str(an_input) + ' ')
def start_module():
working_out = LogBook('training_program.txt')
working_out.print_workout()
#start_module()
|
c9e356140d0ae9d0e56ad62da59503cbdaed62a2 | LiuFang816/SALSTM_py_data | /python/pfnet_chainer/chainer-master/chainer/functions/activation/maxout.py | 1,874 | 3.703125 | 4 | from chainer.functions.array import reshape
from chainer.functions.math import minmax
from chainer.utils import type_check
def maxout(x, pool_size, axis=1):
"""Maxout activation function.
It accepts an input tensor ``x``, reshapes the ``axis`` dimension
(say the size being ``M * pool_size``) into two dimensions
``(M, pool_size)``, and takes maximum along the ``axis`` dimension.
The output of this function is same as ``x`` except that ``axis`` dimension
is transformed from ``M * pool_size`` to ``M``.
Typically, ``x`` is the output of a linear layer or a convolution layer.
The following is the example where we use :func:`maxout` in combination
with a Linear link.
>>> in_size, out_size, pool_size = 100, 100, 100
>>> l = L.Linear(in_size, out_size * pool_size)
>>> x = chainer.Variable(np.zeros((1, in_size), 'f')) # prepare data
>>> x = l(x)
>>> y = F.maxout(x, pool_size)
Args:
x (~chainer.Variable): Input variable. Its first dimension is assumed
to be the *minibatch dimension*. The other dimensions are treated
as one concatenated dimension.
Returns:
~chainer.Variable: Output variable.
.. seealso:: :class:`~chainer.links.Maxout`
"""
if pool_size <= 0:
raise ValueError('pool_size must be a positive integer.')
x_shape = x.shape
if x_shape[axis] % pool_size != 0:
expect = 'x.shape[axis] % pool_size == 0'
actual = 'x.shape[axis]={}, pool_size={}'.format(
x_shape[axis], pool_size)
msg = 'axis dimension must be divided by pool_size'
raise type_check.InvalidType(expect, actual, msg)
shape = (x_shape[:axis] +
(x_shape[axis] // pool_size, pool_size) +
x_shape[axis + 1:])
x = reshape.reshape(x, shape)
return minmax.max(x, axis=axis + 1)
|
ec7835ad3d669c961eed7be9f2f8a057dbfd9488 | Mahirkhan3139/python_code_beginners | /list-demo.py | 1,135 | 3.796875 | 4 | list1 = ["A", "B", "C", "D"]
print(list1)
print(type(list1))
list2 = ["A", "B", 1, 2.0, ["A"], [], list(), True]
print(list2)
print(type(list2))
print(list2[0])
print(list2[-1])
print(list2[:9])
print(list2[::2])
print(list2[4][0])
print(list2[4][-1])
print(type(str(1+1)))
list1[0] = "Y"
print(list1)
del list1[0]
print(list1)
list1.insert(0, "A")
print(list1)
del list1[0]
print(list1)
list1 =["A"] + list1
print(list1)
list1.append("K")
print(list1)
print(min(list1))
print(max(list1))
print(list1.index("C"))
print(list1[list1.index("C")])
list1.reverse()
print(list1)
list1 = list1[::-1]
print(list1)
print(list1.count("A"))
list1.append("A")
print(list1.count("A"))
list1.pop()
print(list1)
list3 = ["O", "L", "M"]
print(list3)
list1.extend(list3)
print(list1)
list4 = [20, 5, 12, 9, 18, 6]
print(list4)
list4.sort()
print(list4)
list4.reverse()
print(list4)
list4.sort(reverse = True)
print(list4)
list5 = list4
print(list5)
list5[0] = "X"
print(list5)
print(list4)
list6 = list3.copy()
print(list6)
list6[0] = 12
print(list6)
print(list3)
list8 = [1, 2, 3]
print(list8)
print(list(map(float, list8))) |
5873a595676623161108971cb893d09d437719e7 | Team-BeanCat/Python-Game | /reader.py | 1,112 | 3.703125 | 4 | from os import path
from json import load, dump
class user(object): #Object for s uer
def __init__(self, username):
self.file = f".\\saves\\{username}.json"
self.read()
def read(self): #Read from the user's json file
if path.exists(self.file):
with open(self.file) as f:
self.data = load(f)
def save(self): #Write the user's current location to the json file
with open(self.file, "w") as f:
dump(self.data, f, indent=4)
def location(self):
return self.data["location"]
class world(object): #Object for a world
def __init__(self, name):
self.file = f".\\worlds\\{name}.json"
self.read()
def read(self):
if path.exists(self.file):
with open(self.file) as f:
self.data = load(f)
def message(self, location):
return self.data[location]["message"]
def options(self, location):
return self.data[location]["options"]
def locations(self, location):
return self.data[location]["locations"] |
fcfaa028a7a766f622fc4db2cf084b30e9ffd642 | omkar-javadwar/Recognition_Module | /speech<->text/text_to_speech_using_pyttsx3.py | 407 | 3.59375 | 4 | # Import the required module for text to speech conversion
import pyttsx3
# init function to get an engine instance for the speech synthesis
engine = pyttsx3.init()
# Taking input from user.
str = input()
print(str)
# say method on the engine that passing input text to be spoken
engine.say(str)
# run and wait method, it processes the voice commands.
engine.runAndWait()
|
6b810fbd255e44b7d0b0f78595f0efd3b3b74e0b | Rahul4269/Python-star | /multilevel inheritance.py | 562 | 3.65625 | 4 | class student:
def getstudent(self):
self.name=input("name :")
self.age=int(input("age :"))
class testMarks (student):
def getMarks(self):
self.english=int(input("English :"))
self.Maths=int(input("Maths :"))
self.physics=int(input("Physics :"))
class result(testMarks):
def display(self):
print("Hello",self.name,"You are",self.age,"Years old.")
print("Your Total marks is ",self.english+self.Maths+self.physics)
re=result()
re.getstudent()
re.getMarks()
re.display() |
a959e2f4f293ec49d9dfab8487f8a6cc24cd948f | MatiwsxD/ayed-2019-1 | /Labinfo_6/punto_3.py | 375 | 3.96875 | 4 | def domino(n):
list_1 = [0] * (n + 1)
list_2 = [0] * (n + 1)
list_1[0] = 1
list_1[1] = 0
list_2[0] = 0
list_2[1] = 1
for i in range(2, n+1):
list_1[i] = list_1[i - 2] + 2 * list_2[i - 1]
list_2[i] = list_1[i - 1] + list_2[i - 2]
return list_1[n]
def main():
n = int(input())
print(domino(n))
main()
|
59b5d2016865f4b96384df2a1a523243ab42a46d | MenonFOSSTest/Python-2 | /KM2MILES.py | 83 | 3.953125 | 4 | km=int(input("Enter Kilometer"))
m1=0.621371*km
print(km,"is equal to",m1,"miles")
|
83fc2c9673aeb2936fb1827eda08dd1875c7c13e | favera/python-course | /string.py | 1,864 | 4.03125 | 4 | string1 = "Cisco Router"
#se puede acceder a los indices de un string, cada caracter representa un indice
#el ultimo caracter de puede acceder con -1
#para leer un string del reves se comineza con -1 y va decrenciendo en negativo
string1[1]
string1[-1]
#para saber el lenght de un caracter usar la funcion len
len(string1)
####### METODOS #######
a = "Cisco Switch"
#Arroja el indice del caracter que se le pasa en el parentesis
a.index("i")
#1
#Arroja el numero de veces que encuentra la letra i en el string
a.count("i")
#2
#Arroja el primer indice del macth que hace con los caracteres que se le pasa en el parentesis
a.find("sco")
#2
#Si no encuentra ningun match arroja -1
a.find("xyz")
#-1
#Metodo para pasar todo a minuscula un string
a.lower()
#'cisco switch'
#Metodo para pasar a mayuscula un string, no interfiere con el string original, o sea mantiene su valor a pesar del metodo
#Metodo para verificar con letra comienza un string, retorna true o false y es casesensitive
a.startswith("c")
False
a.startswith("C")
True
#Metodo para verificar con letra termina un string
a.endswith("h")
True
#Metodo para eliminar lo que esta al inicio y al fin de un string, si no se pasa nada en el parentisis elimina los espacios
b = " Cisco Switch "
b.strip()
'Cisco Switch'
c = "$$$Cisco Switch$$$"
c.strip("$")
'Cisco Switch'
c = "$$$Cisco $$$Switch$$$"
c.strip("$")
'Cisco $$$Switch'
#Metodo para reemplazar un caracter por otro, se pasa primero el caracter que va a ser reemplazado, luego el nuevo valor
b
' Cisco Switch '
b.replace(" ", "")
'CiscoSwitch'
#Crea una lista segun el parametro de split definido
d = "Cisco,Juniper,HP,Avaya,Nortel"
d.split(",")
['Cisco', 'Juniper', 'HP', 'Avaya', 'Nortel']
#Metodo para insertar algo en un string, en este caso inserta entre cada letra un _
a
'Cisco Switch'
"_".join(a)
'C_i_s_c_o_ _S_w_i_t_c_h'
|
ae85144467ed5d9a9ea310e689298a65bf435bb2 | chrispewick/advent_of_code_2020 | /day01/part_2.py | 1,180 | 4.125 | 4 | from typing import Tuple
from utils.performance_utils import get_the_avg_time_to_do_the_thing
SUM_GOAL = 2020
def get_numbers_basic(entries) -> Tuple[int, int, int]:
for index, x in enumerate(entries):
for y in entries[index+1:]:
for z in entries[index+2:]:
if x + y + z == 2020:
return x, y, z
def get_numbers_set(entries) -> Tuple[int, int, int]:
values = set()
for index, x in enumerate(entries):
for y in entries[index+1:]:
target = SUM_GOAL - x - y
if target in values:
return x, y, target
values.add(y)
def find_solution(entries):
try:
first, second, third = get_numbers_set(entries)
print(f"Solution entries: {first} x {second} x {third} = {first * second * third}")
except TypeError:
print("There is no solution!")
if __name__ == "__main__":
input_entries = [int(line) for line in open("input.txt", "r")]
find_solution(input_entries)
avg_time = get_the_avg_time_to_do_the_thing(get_numbers_set, input_entries)
print(f"Average time: {avg_time}")
# Average time: 0.09263489218999993
|
b25a878ed7c7a7e6f60c8de1943f6dd6fcb4b74b | allenwhc/Algorithm | /Company/Google/PeakElement.py | 610 | 3.53125 | 4 | class Solution(object):
def findPeakElement(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if len(nums)<=1:
return 0
return self.binary_search(nums,0,len(nums)-1)
def binary_search(self,nums,s,e):
if s<=e:
mid=(e-s)/2+s
if (mid==0 or nums[mid]>nums[mid-1]) and (mid==len(nums)-1 or nums[mid]>nums[mid+1]):
return mid
if mid>0 and nums[mid]<nums[mid-1]:
return self.binary_search(nums,s,mid)
if mid<len(nums) and nums[mid]<nums[mid+1]:
return self.binary_search(nums,mid+1,e)
return -1
nums=[1,2]
s=Solution()
print "peak element:", s.findPeakElement(nums) |
0bc6bac8d0cc73e7dc07eafa0c0cd5930d2c5bfc | MiniBug/Guess-The-Number | /guess_the_number.py | 2,059 | 4.25 | 4 | # template for "Guess the number" mini-project
# input will come from buttons and an input field
# all output for the game will be printed in the console
import simplegui
import random
# initialize global variables used in your code
num_range = 100
# helper function to start and restart the game
def new_game():
global secret_num, tries_left
tries_left = 7
secret_num = random.randrange(0, num_range)
print "\nNew game. Range is from 0 to", num_range
if num_range == 1000:
tries_left = 10
print "Number of remaining guesses is", tries_left
# define event handlers for control panel
def range100():
global num_range
new_game()
def range1000():
# button that changes range to range [0,1000) and restarts
global num_range
num_range = 1000
tries_left = 10
new_game()
def get_input(guess):
input_field.set_text("")
guessed = False
global tries_left
global secret_num
tries_left -= 1
if tries_left == 0 and guessed == False:
print "\nGuess was", guess,"\nNumber of remaining guesses is", tries_left,"\n","You ran out of guesses. The number was",secret_num
new_game()
return None
elif tries_left >= 0:
guess = int(guess)
print "\nGuess was", guess
print "Number of remaining guesses is", tries_left
if guess == secret_num:
print "Corect!"
guessed = True
if guess < secret_num:
print "Higher!"
if guess > secret_num:
print "Lower!"
if guessed:
new_game()
# create frame
frame = simplegui.create_frame('Riddle Challenge! R U up 2?', 300, 300)
# register event handlers for control elements
frame.add_button("Range is [0, 100)", range100, 200)
frame.add_button("Range is [0, 1000)", range1000, 200)
input_field = frame.add_input('Enter a guess', get_input, 200)
# call new_game and start frame
new_game()
frame.start()
# always remember to check your completed program against the grading rubric
|
92ea6d9cbb37ae2b7147f164867f813125992ef3 | cklat/Particle-Swarm-Optimization | /Code/helper.py | 690 | 3.703125 | 4 | """reads a tsp file and returns a list of vertices and a dict of edges with their corresponding costs"""
def read_tsp(tsp_file):
import xmltodict
vertices = []
edges = {}
with open(tsp_file) as file:
data = xmltodict.parse(file.read(), dict_constructor=dict)
vertices_dict = data["travellingSalesmanProblemInstance"]["graph"]["vertex"]
for i, vertice in enumerate(vertices_dict):
vertices.append(i)
for edge in vertice["edge"]:
edges[(str(i), edge["#text"])] = float(edge["@cost"])
return vertices, edges
|
b9c176c51bd6335deffcc68c0c6c13ea797e733e | karimeSalomon/API_Testing_Diplomado | /RolandoMamani/Python/Practice7_SumAllNumbers.py | 745 | 4.1875 | 4 | """
Practice 7: Write a function sum_to(n) that returns the sum of all integer numbers up to and including only until
any value lower than 35. So sum_to(10)wouldbe1+2+3...+10which would return the value 55,
but if n=40 only until sum to 35 need to be returned. .
"""
def sum_to(n):
result = 0
iterator = 35
if (n <= 35): iterator = n
for i in range(1, iterator+1):
result += i
return result
print(sum_to(int(input("The sum of the numbers will be done, from 1 to the number that you enter \n"
"Note: the entered value should be less than or equal to 35, in the other hand it will applied the sum just until 35\n"
"Please enter the number: ")))) |
d64dd69f6f74792c20a839a15874bc1993a0efdf | BuntyBru/SortingAlgorithms | /mergeSort.py | 513 | 3.796875 | 4 | def mergeSort(alist):
if len(alist) >1:
mid = len(alist)//2
left = alist[:mid]
right = alist[mid:]
mergeSort(left)
mergeSort(right)
i=0
j=0
k=0
while i < len(left) and j < len(right):
if left[i]< right[j]:
alist[k] = left[i]
i=i+1
else:
alist[k] = right[j]
j=j+1
k=k+1
while i<len(left):
alist[k] = left[i]
i=i+1
k=k+1
while j<len(right):
alist[k] = right[j]
j=j+1
k=k+1
alist = [54,26,93,17,77,31,44,55,20]
mergeSort(alist)
print(alist) |
4c4d7323126348dd3a9a60a966fcfef3d382ca80 | nazmosh/data_structures | /CircularLinkedList.py | 2,878 | 3.90625 | 4 | class CircularLinkedList:
def __init__(self):
self.head = None
def append(self, node):
if self.head == None:
self.head = node
self.head.next= self.head
else:
current_node = self.head
while current_node.next != self.head:
current_node = current_node.next
current_node.next = node
node.next = self.head
def prepend(self, new_node, target_node):
if self.head == None:
self.head = new_node
new_node.next = self.head
else:
current_node = self.head
while current_node.next!= target_node:
current_node = current_node.next
current_node.next = new_node
new_node.next = target_node
def __len__(self):
if self.head == None:
return 0
p = self.head
counter = 1
while p.next != self.head:
p = p.next
counter += 1
return counter
def split_in_half (self):
if not self.head:
return None
if len(self) == 0:
return None
half_one = CircularLinkedList()
half_two = CircularLinkedList()
halfway = int(len(self) / 2)
cur_node = self.head
counter = 0
while counter < halfway:
half_one.append(cur_node)
cur_node = cur_node.next
counter = counter + 1
while counter < len(self):
half_two.append(cur_node)
cur_node = cur_node.next
counter = counter + 1
return half_one, half_two
def print_list(self):
current_node = self.head
if self.head!= None:
while current_node:
print("[{}]".format(current_node.data))
current_node = current_node.next
if current_node == self.head:
break
def is_circular_linked_list (self, input_list):
p = input_list.head
while p.next != input_list.head:
if p.next == None:
return False
p = p.next
return True
class Node:
def __init__(self, data):
self.data = data
self.next = None
if __name__ == "__main__":
linked_list = CircularLinkedList()
node1 = Node ("A")
node2 = Node ("B")
node3 = Node ("C")
new_node = Node (4)
linked_list.append(node1)
linked_list.append(node2)
linked_list.append(node3)
linked_list.prepend(new_node, node2)
#linked_list.print_list()
print ("length of the list is {}".format(len(linked_list)))
half_one, half_two = linked_list.split_in_half()
half_one.print_list()
print ("***************")
half_two.print_list()
|
2880b9e2783cf7214f3048af20c0334b1f341943 | VishalGupta2597/batch89 | /evenodd1to10.py | 189 | 4 | 4 | n = 6
if n%2==0:
print("even=",n)
else:
print("odd=", n)
i=1
while i<11:
if i % 2 == 0:
#print("even=", i)
pass
else:
print("odd=", i)
i=i+1
|
cbbc7346250217eb7b744e9fa3eafcf15b93596e | etihW/Sandbox | /Reddit/RPS.py | 1,356 | 4.25 | 4 | import time
from random import randint
def comp_pick():
val = randint(1,3)
if val == 1:
hand = "rock"
elif val == 2:
hand = "scissors"
elif val == 3:
hand = "paper"
return hand
def compare_hands(comp, you):
if comp == you:
winner = "tie"
elif comp == ('rock' and you == 'scissors') or (comp == 'scissors' and you == 'paper')\
or (comp == 'paper' and you == 'rock'):
winner = 'computer'
else:
winner = 'you'
return winner
def main():
playing = True
print("Let's play Scissors, Paper, and rock!\n")
while playing:
print("-\n")
you = input("Type in rock, paper, or scissors. Type quit to end game\n")
you = you.lower()
if you == "quit":
playing = False
elif you == "paper" or you == "rock" or you == "scissors":
comp = comp_pick()
winner = compare_hands(comp, you)
print("The computer played %s, you played %s" % (comp, you))
else:
print("Invalid entry, please try once more\n")
continue
if winner == "tie":
print("You tied\n")
elif winner == "computer":
print("The computer won!\n")
elif winner == "you":
print("A winner is you!\n")
print()
print()
main()
|
809ec304ff7203847ebc5bec10c96006cee3f17c | romanticair/python | /basis/tkinter-demo/tk-color-change-and-grow.py | 1,026 | 3.984375 | 4 | """
Build GUI with tkinter with buttons that change color and grow
"""
import random
from tkinter import *
FontSize = 25
Colors = ['red', 'green', 'blue', 'yellow', 'orange', 'white', 'cyan', 'purple']
def reply(text):
print(text)
popup = Toplevel()
color = random.choice(Colors)
Label(popup, text='Popup', bg='black', fg=color).pack()
L.config(fg=color)
def timer():
L.config(fg=random.choice(Colors))
win.after(250, timer)
def grow():
global FontSize
FontSize += 5
L.config(font=('arial', FontSize, 'italic'))
win.after(100, grow)
if __name__ == '__main__':
win = Tk()
L = Label(win, text='Spam', font=('arial', FontSize, 'italic'), fg='yellow', bg='navy', relief=RAISED)
L.pack(side=TOP, expand=YES, fill=BOTH)
Button(win, text='press', command=(lambda: reply('red'))).pack(side=BOTTOM, fill=X)
Button(win, text='timer', command=timer).pack(side=BOTTOM, fill=X)
Button(win, text='grow', command=grow).pack(side=BOTTOM, fill=X)
win.mainloop()
|
0e413abbc21e5556343d325a8a77411951fe8939 | maxim371/Unit3_Sprint2_Database | /northwind_sprint.py | 1,164 | 3.625 | 4 | #!/usr/bin/env python
import sqlite3
CONN = sqlite3.connect('northwind_small.sqlite3')
def queries():
expensive = 'SELECT * FROM Product ORDER BY UnitPrice DESC LIMIT 10;'
avg_age = 'SELECT AVG(HireDate - BirthDate) FROM Employee;'
city_age = ('SELECT City, AVG(HireDate - BirthDate) FROM Employee '
'GROUP BY City;')
item_supply = ('SELECT p.ProductName, p.UnitPrice, s.CompanyName '
'FROM Product p, Supplier s WHERE p.SupplierId = s.Id '
'ORDER BY p.UnitPrice DESC LIMIT 10;')
query = (expensive, avg_age, city_age, item_supply)
curs = CONN.cursor()
for i in query:
print(curs.execute(i).fetchall())
if __name__ == "__main__":
queries()
'''A document store like MongoDB is appropriate when scalability is important ie. when storing huge amount of databases.
MongoDb is not approriate for soring smaller data like password, bookmarks etc'''
'''NewSQL is a class of relational database management system with a focus on having the scalability of NoSQL whilst
at the same time maintaining the ACID guarantee of traditional database system. ''' |
a45788a86b28033d9b5e615e57904704a4ef063e | Andrey-Strelets/Python_hw | /Practica_1.py | 126 | 3.890625 | 4 | print ("Insert the number")
a = int(input())
if a % 2 == 0:
print("Четное")
else:
print ("Нечетное") |
2e7086888642bce52ab736a07e56b7e160fa1c7c | jong1-alt/Lin | /demo61.py | 388 | 4.125 | 4 | def factorial(number):
if not isinstance(number, int):
raise TypeError("Sorry, number should be integer")
if not number >= 0:
raise ValueError("sorry, number should positive")
def inner_factorial(number):
if number <= 1:
return 1
return number * inner_factorial(number - 1)
return inner_factorial(number)
print(factorial(20))
|
e6c7b82359d241fc68f2690aba4646b9ff26110f | AlexanderIvanofff/Python-Fundamentals | /Lists/declipher_this.py | 589 | 4.09375 | 4 | def parse_to_chr(text):
digits = ''
for digit in text:
if not str(digit).isdigit():
break
digits += digit
ascii_value = int(digits)
chr_value = chr(ascii_value)
new_word = text.replace(digits, chr_value)
return new_word
def replace_in_text(text):
temp = list(text)
temp[1], temp[-1] = temp[-1], temp[1]
return ''.join(temp)
def decipher(text):
res = parse_to_chr(text)
res = replace_in_text(res)
return res
words = input().split(' ')
new_text = [decipher(word) for word in words]
print(' '.join(new_text)) |
315ab03926276c1dcb73dc73f14552a318b72dde | daniel-reich/turbo-robot | /6FaERG8x8Y6MYmoYF_12.py | 1,479 | 4.3125 | 4 | """
Greed is a dice game played with five six-sided dices. Your mission is to
score a throw according to these rules:
Three 1's => 1000 points
Three 6's => 600 points
Three 5's => 500 points
Three 4's => 400 points
Three 3's => 300 points
Three 2's => 200 points
One 1 => 100 points
One 5 => 50 point
See the below examples for a better understanding:
Throw Score
--------- ------------------
5 1 3 4 1 250: 50 (for the 5) + 2 * 100 (for the 1s)
1 1 1 3 1 1100: 1000 (for three 1s) + 100 (for the other 1)
2 4 4 5 4 450: 400 (for three 4s) + 50 (for the 5)
Create a function that takes a list of five six-sided **throw values** and
returns the final calculated **dice score**.
### Examples
dice_score([2, 3, 4, 6, 2]) ➞ 0
dice_score([4, 4, 4, 3, 3]) ➞ 400
dice_score([2, 4, 4, 5, 4]) ➞ 450
### Notes
A single dice can only be counted once in each roll. For example, a given "5"
can only be counted as a part of the triplet (contributing to the 500 points)
or as a single 50 points, but not both in the same roll.
"""
def dice_score(lst):
a = (lst.count(1) == 3) * 1000
b = (lst.count(6) == 3) * 600
c = (lst.count(5) == 3) * 500
d = (lst.count(4) == 3) * 400
e = (lst.count(3) == 3) * 300
f = (lst.count(2) == 3) * 200
g = (0 < lst.count(1) < 3) * 100
h = (0 < lst.count(5) < 3) * 50
return a + b + c + d + e + f + g + h
|
2848df562b787e72ba7c6948b09742935f373330 | shayanbeizaee/python-challenge | /PyBank/main.py | 1,952 | 3.6875 | 4 | #Shayan Beizaee
# Financial Analysis
import os
import csv
csvpath = os.path.join('..', 'Resources', 'budget_data.csv')
with open(csvpath, newline='') as csvfile:
csvreader = csv.reader(csvfile, delimiter=',')
csv_header = next(csvreader)
#Total number of the months included in the datat set
totalMonths = 0
profitloss = []
months = []
for row in csvreader:
totalMonths +=1
profitloss.append(int(row[1]))
months.append(row[0])
change = []
for i in range(totalMonths - 1):
change.append(profitloss[i+1] - profitloss[i])
greatincrease = max(change)
greatdecrease = min(change)
for i in range(totalMonths - 1):
if profitloss[i+1] - profitloss[i] == greatincrease:
monthmax = months[i+1]
if profitloss[i+1] - profitloss[i] == greatdecrease:
monthmin = months[i+1]
average = round(sum(change) / len(change), 2)
print("Financial Analysis")
print("--------------------------------")
print(f"Total Months: {totalMonths}")
print(f"Total: ${sum(profitloss)}")
print(f"Average Change: ${average}")
print(f"Greatest Increase in Profits: {monthmax} (${greatincrease})")
print(f"Greatest Decrease in Profits: {monthmin} (${greatdecrease})")
output_path = os.path.join("..", "PyBank", "PyBank.txt")
with open(output_path, 'w') as txtfile:
txtfile.write("Financial Analysis")
txtfile.write("\n")
txtfile.write("--------------------------------")
txtfile.write("\n")
txtfile.write(f"Total Months: {totalMonths}")
txtfile.write("\n")
txtfile.write(f"Total: ${sum(profitloss)}")
txtfile.write("\n")
txtfile.write(f"Average Change: ${average}")
txtfile.write("\n")
txtfile.write(f"Greatest Increase in Profits: {monthmax} (${greatincrease})")
txtfile.write("\n")
txtfile.write(f"Greatest Decrease in Profits: {monthmin} (${greatdecrease})")
|
c4b02f96e393a0558adadd07e6c2350da97177b2 | noob-cod/DataSturcture-python | /pythonDataStructure/graph.py | 832 | 3.625 | 4 | """
@Date: Friday, March 12, 2021
@Author: Chen Zhang
@Brief: 图数据结构的实现
"""
import numpy as np
class ArrayGraph:
def __init__(self, sourceCollection=None):
self._num = 0
self.graph = np.zeros((self._num, self._num))
def __len__(self):
return self._num
def is_Empty(self):
return len(self) == 0
def __str__(self):
print(self.graph)
def __eq__(self, other):
pass
def add(self, newNode):
new1 = np.zeros((self._num, 1))
self.graph = np.hstack((self.graph, new1))
new2 = np.zeros((1, self._num+1))
self.graph = np.vstack((self.graph, new2))
def clear(self):
self._num = 0
self.graph = np.zeros((self._num, self._num))
def to_linked(self):
"""转化为链表表示"""
pass
|
1aabab5d44535d72abf7da02e8346b7092cfd148 | mcxu/code-sandbox | /PythonSandbox/src/leetcode/lc553_reverse_words_in_string_3.py | 980 | 4.09375 | 4 | '''
https://leetcode.com/problems/reverse-words-in-a-string-iii/
Given a string, you need to reverse the order of characters in each word within
a sentence while still preserving whitespace and initial word order.
Example 1:
Input: "Let's take LeetCode contest"
Output: "s'teL ekat edoCteeL tsetnoc"
Note: In the string, each word is separated by single space and there will not be
any extra space in the string.
'''
class Solution:
def reverseWords(self, s: str) -> str:
sSplit = s.split(" ")
outStr = ""
for word in sSplit:
if word:
outStr += (self.revString(word) + " ")
return outStr[:-1]
def revString(self, s):
sRev = ""
for i in range(len(s)-1, -1, -1):
sRev += s[i]
return sRev
def test1(self, alg):
input = "Let's take LeetCode contest"
res = alg(input)
print("test1 res: ", res)
s = Solution()
alg = s.reverseWords
s.test1(alg) |
0e9d7d2932323728b9a906cd927a4f90ec8474e4 | sanskarlather/100-days-of-code-with-python | /Day 8/better_caeser_cypher.py | 641 | 3.53125 | 4 | from caeser_cypher_logo import logo
print(logo)
n=0
def salad(n):
test=""
if n==3:
print("Thank You for trying this out")
elif n==1:
s=input("Enter the string\n")
a=int(input("by how much\n"))
for i in range(0,len(s)):
if ord(s[i])+a>122:
test+=chr(ord(s[i])+a-26)
else:
test+=chr(ord(s[i])+a)
elif n==2:
s=input("Enter the string\n")
a=int(input("by how much\n"))
for i in range(0,len(s)):
if ord(s[i])-a<96:
test+=chr(ord(s[i])-a+26)
else:
test+=chr(ord(s[i])-a)
return(test)
while n!=3:
n=int(input("Enter\n1. for Encoding\n2. for Decoding\n3. to quit\n"))
print(salad(n))
|
acba88bbacc6f321242325305af66f9af59e35f9 | franciscoG98/ws-python | /ej3.py | 242 | 3.765625 | 4 | # EJERCICIO 3
# Preguntarle al usuario su edad actual e informale la edad que tendra le año que vien(?????????)
userAge = int( input('How old are you?\n'))
newAge = userAge + 1
print('Next year you will have ' + str(newAge) + ' years old') |
4cc251643d5402e0efcf329d49cae419353e212a | AntnvSergey/EpamPython2019 | /13-design-patterns/hw/4-chain_of_responsibility/chain_of_responsibility.py | 2,995 | 4.34375 | 4 | """
С помощью паттерна "Цепочка обязанностей" составьте список покупок для выпечки блинов.
Необходимо осмотреть холодильник и поочередно проверить, есть ли у нас необходимые ингридиенты:
2 яйца
300 грамм муки
0.5 л молока
100 грамм сахара
10 мл подсолнечного масла
120 грамм сливочного масла
В итоге мы должны получить список недостающих ингридиентов.
"""
class BaseHandler:
def __init__(self):
self.next = None
def set_next(self, handler):
self.next = handler
return self.next
class Fridge:
def __init__(self, eggs=0, flour=0, milk=0.0,
sugar=0, sunflower_oil=0, butter=0):
self.eggs = eggs
self.flour = flour
self.milk = milk
self.sugar = sugar
self.sunflower_oil = sunflower_oil
self.butter = butter
class EggsHandler(BaseHandler):
def handle(self, fridge: Fridge):
if fridge.eggs < 2:
print(f'Need {2-fridge.eggs} eggs')
if self.next:
self.next.handle(fridge)
class FlourHandler(BaseHandler):
def handle(self, fridge: Fridge):
if fridge.flour < 300:
print(f'Need {300-fridge.flour} gram of flour')
if self.next:
self.next.handle(fridge)
class MilkHandler(BaseHandler):
def handle(self, fridge: Fridge):
if fridge.milk < 0.5:
print(f'Need {0.5-fridge.milk} liter of milk')
if self.next:
self.next.handle(fridge)
class SugarHandler(BaseHandler):
def handle(self, fridge: Fridge):
if fridge.sugar < 100:
print(f'Need {100-fridge.sugar} gram of sugar')
if self.next:
self.next.handle(fridge)
class SunflowerOilHandler(BaseHandler):
def handle(self, fridge: Fridge):
if fridge.sunflower_oil < 10:
print(f'Need {10-fridge.sunflower_oil} milliliter of '
f'sunflower oil')
if self.next:
self.next.handle(fridge)
class ButterHandler(BaseHandler):
def handle(self, fridge: Fridge):
if fridge.butter < 120:
print(f'Need {120-fridge.butter} gram of butter')
if self.next:
self.next(fridge)
fridge = Fridge()
another_fridge = Fridge(eggs=3, butter=200, milk=0.3)
eggs_handler = EggsHandler()
flour_handler = FlourHandler()
milk_handler = MilkHandler()
sugar_handler = SugarHandler()
sunflower_handler = SunflowerOilHandler()
butter_handler = ButterHandler()
eggs_handler.set_next(flour_handler).set_next(milk_handler)
milk_handler.set_next(sugar_handler).set_next(sunflower_handler)
sunflower_handler.set_next(butter_handler)
eggs_handler.handle(fridge)
print(30*'-')
eggs_handler.handle(another_fridge) |
f8e103d632ba902ff340c732e23432f95b21d0f4 | brandoneng000/LeetCode | /easy/1037.py | 769 | 3.609375 | 4 | from typing import List
class Solution:
def isBoomerang(self, points: List[List[int]]) -> bool:
from math import isclose
first = tuple(points[0])
second = tuple(points[1])
third = tuple(points[2])
if first == second or first == third or second == third:
return False
rise = second[1] - first[1]
run = second[0] - first[0]
slope = rise / run if run else float('inf')
rise = third[1] - first[1]
run = third[0] - first[0]
return not isclose(slope, rise / run if run else float('inf'))
def main():
sol = Solution()
print(sol.isBoomerang([[1,1],[2,3],[3,2]]))
print(sol.isBoomerang([[1,1],[2,2],[3,3]]))
if __name__ == '__main__':
main() |
4e41163bec478ac8781840319fbdaa461b3c6fdd | lenakchen/Hadoop | /project/mapper2.py | 1,110 | 3.6875 | 4 | #!/usr/bin/env python
""" Final Project
Task Two: Post and Answer Length
Find if there is a correlation between the length of a post and the length of answers.
Write a mapreduce program that would process the forum_node data and output the length
of the post and the average answer (just answer, not comment) length for each post.
Dataset: forum_node.tsv
The fields in forum_node that are the most relevant to the task are:
"id" "title" "tagnames" "author_id" "body" "node_type" "parent_id" "abs_parent_id"
"""
import sys
import csv
#import re
reader = csv.reader(sys.stdin, delimiter='\t')
for line in reader:
# find the node id of a forum post
node_id = line[0]
if node_id == 'id':
continue
body = line[4]
node_type = line[5]
##remove html tags
#tags = re.compile('<.*?>')
#body = re.sub(tags, '', body)
post_len = len(body)
if node_type == 'question':
print '{0}\t{1}\t{2}'.format(node_id, 'A', post_len)
if node_type == 'answer':
abs_parent_id = line[7]
print '{0}\t{1}\t{2}'.format(abs_parent_id, 'B', post_len)
|
11525d23678820fedea2e8974c45414254c91f8c | XMK233/Leetcode-Journey | /py-jianzhi-round3/JianzhiOffer34.py | 2,589 | 3.75 | 4 | '''
[剑指 Offer 34. 二叉树中和为某一值的路径 - 力扣(LeetCode)](https://leetcode-cn.com/problems/er-cha-shu-zhong-he-wei-mou-yi-zhi-de-lu-jing-lcof)
输入一棵二叉树和一个整数,打印出二叉树中节点值的和为输入整数的所有路径。从树的根节点开始往下一直到叶节点所经过的节点形成一条路径。
示例:
给定如下二叉树,以及目标和 sum = 22,
5
/ \
4 8
/ / \
11 13 4
/ \ / \
7 2 5 1
返回:
[
[5,4,11,2],
[5,8,4,5]
]
提示:
节点总数 <= 10000
注意:本题与主站 113 题相同:https://leetcode-cn.com/problems/path-sum-ii/
'''
class Solution:
def pathSum(self, root: TreeNode, sum: int) -> List[List[int]]:
res, path = [], []
def dfs(node, sum):
#递归出口:解决子问题
if not node: return #如果没有节点(node = None),直接返回,不向下执行
else: #有节点
path.append(node.val) #将节点值添加到path
sum -= node.val
# 如果节点为叶子节点,并且 sum == 0
if not node.left and not node.right and not sum:
res.append(path[:])
dfs(node.left, sum) #递归处理左边
dfs(node.right, sum) #递归处理右边
path.pop() #处理完一个节点后,恢复初始状态,为node.left, node.right操作
dfs(root, sum)
return res
# 作者:xilepeng
# 链接:https://leetcode-cn.com/problems/er-cha-shu-zhong-he-wei-mou-yi-zhi-de-lu-jing-lcof/solution/dfs-jian-dan-yi-dong-by-xilepeng/
# 来源:力扣(LeetCode)
# 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
## 好好学习一下人家的实现方式. 很好的.
##-----------------------------------------------------------------------------
import os, sys, re
selfName = os.path.basename(sys.argv[0])
id = selfName.replace("JianzhiOffer", "").replace(".py", "")
# id = "57"
round1_dir = "C:/Users/XMK23/Documents/Leetcode-Journey/py-jianzhi-round1"
for f in os.listdir(round1_dir):
if ".py" not in f:
continue
num = re.findall("\d+-*I*", f)
if len(num) == 0:
continue
id_ = num[0]
if id == id_:
with open(os.path.join(round1_dir, f), "r", encoding="utf-8") as rdf:
lines = rdf.readlines()
print(f)
print("".join(lines))
print() |
60775997ad0724710d9c34fd28f8d16bf6eed060 | DeepakSunwal/Daily-Interview-Pro | /solutions/islands.py | 1,093 | 3.859375 | 4 | def is_valid(grid, r, c):
rows, cols = len(grid), len(grid[0])
if r < 0 or c < 0 or r >= rows or c >= cols:
return False
return True
def count_islands(grid):
count = 0
for row in range(len(grid)):
for col in range(len(grid[0])):
if grid[row][col] == 1:
count += 1
linked_points = [point for point in [(row - 1, col), (row + 1, col), (row, col - 1), (row, col + 1)] if
is_valid(grid, point[0], point[1])]
for point in linked_points:
if grid[point[0]][point[1]] == 1:
grid[point[0]][point[1]] = 2
elif grid[point[0]][point[1]] == 2:
count -= 1
print(grid[0], '\n', grid[1], '\n', grid[2], '\n', grid[3], '\n')
return count
def main():
assert count_islands([[1, 1, 0, 0, 0],
[0, 1, 0, 0, 1],
[1, 0, 0, 1, 1],
[0, 0, 0, 0, 0]]) == 3
if __name__ == '__main__':
main()
|
493d6055be9305c5013acaca759c513e079260d7 | bboz862/correlated-cost-online-learning | /Generate_data_cost/Generate_data_cost_logisticregression/rs12.py | 2,916 | 3.609375 | 4 | import random
import numpy as np
from scipy.optimize import brentq
# This is a generalization of RothSchoenebeck12, where we apply our
# importance-weighting framework, but we get the probabilities of
# purchase by drawing prices as prescribed by RothSchoenebeck12.
# RS12 assumes knowledge of the prior distribution on costs and
# tailors the price distribution accordingly.
# Here we assume the cost prior is uniform [0,cmax].
# Computing the pricing distribution:
# With a cost CDF F, PDF f, the pricing distribution of RS12 has the form
# Pr[ price >= x ] = sqrt(alpha f(x) / (F(x) + xf(x))) (or 1 if larger than 1).
# (in general there is smoothing etc, but this isn't needed for the uniform cost case.)
# The uniform[0,cmax] distribution has F(x) = x/cmax and f(x) = 1/cmax.
# Pr[ price >= x ] = sqrt(alpha 1/(2x)).
# = beta sqrt(1/x) by a change of variables.
# So we always set a price in the range [beta^2, cmax] with a point mass at cmax.
# The pricing pdf is g(x) = beta / (2x^1.5).
# To solve for beta, the expected spend per arrival must be B/T.
# So B/T = Pr[price=cmax]*cmax + int_{beta^2}^{cmax} x g(x) F(x) dx,
# which works out to beta*sqrt(cmax) + (1/3)(beta*sqrt(cmax) - beta^4/cmax).
# = (4/3)*beta*sqrt(cmax) - (1/3)*beta^4/cmax
# So we just solve for the beta where this equals B/T.
class RS12Mech(object):
"""
This is the RothSchoenebeck2012 mechanism that draws prices i.i.d. from a fixed
distribution for all arriving data.
Generalized to interact with a learning algorithm by giving its importance
weight.
Assumes the marginal distribution on costs is uniform [0,cmax].
"""
def __init__(self, alg, seed, T=1, B=1, eta=0.1, cmax=1.0):
self.alg = alg
self.randgen = random.Random(seed)
self.reset(eta, T, B, cmax)
super(RS12Mech, self).__init__()
def reset(self, eta, T, B, cmax=1.0):
self.T = T
self.B = B
self.cmax = cmax
if cmax <= B/float(T): # can buy every point
self.factor = 100000000000
else:
self.factor = brentq(lambda x: 4.0*x*(cmax**0.5)/3.0 - (x**4.0)/(3.0*cmax) - B/float(T), 0.0, cmax**0.5)
self.spend = 0.0
self.alg.reset(eta)
# given quantile ~ unif[0,1], return a price such that
# Pr[price >= c] = factor/sqrt(c)
def _get_price(self, quantile):
val = self.factor / quantile
return min(self.cmax, val ** 2.0)
def _prob_exceeds(self, c):
if c == 0.0:
return 1.0
return min(1.0, self.factor / c**0.5)
def train_and_get_err(self, costs, Xtrain, Ytrain, Xtest, Ytest):
for i in xrange(len(Xtrain)):
price = self._get_price(self.randgen.random())
if costs[i] <= price:
self.spend += price
self.alg.data_update(Xtrain[i], Ytrain[i], self._prob_exceeds(costs[i]))
# could cut it off at B, but it's designed to spend B in expectation so don't
# if self.spend >= self.B:
# break
else:
self.alg.null_update()
return self.alg.test_error(Xtest, Ytest)
|
c6a50f0596aa30a62802a92ae7b8095e13b44eef | Madanfeng/JianZhiOffer | /python_offer/53_20~n-1中缺失的数字.py | 787 | 3.625 | 4 | """
一个长度为n-1的递增排序数组中的所有数字都是唯一的,并且每个数字都在范围0~n-1之内。
在范围0~n-1内的n个数字中有且只有一个数字不在该数组中,请找出这个数字。
示例 1:
输入: [0,1,3]
输出: 2
示例 2:
输入: [0,1,2,3,4,5,6,7,9]
输出: 8
限制:
1 <= 数组长度 <= 10000
"""
def missingNumber(nums):
"""
:param nums: List[int]
:return: int
"""
n = len(nums)
left, right = 0, n - 1
while left != right:
mid = left + (right - left) // 2
if mid == nums[mid]:
left = mid + 1
else:
right = mid
if left == nums[left]:
return left + 1
else:
return left
print(missingNumber([0,1,2]))
|
51ae7c3b3d1e9f1b7153c6a2fdfe565ed5eaedcb | Coliverfelt/Desafios_Python | /Desafio063_a.py | 542 | 4.15625 | 4 | # Exercício Python 063: Escreva um programa que leia um número N inteiro qualquer
# e mostre na tela os N primeiros elementos de uma Sequência de Fibonacci.
# Ex: 0 - 1 - 1 - 2 - 3 - 5 - 8
n = int(input('Quantos elementos da sequência de Fibonacci você deseja visualizar?'))
i = 0
while i < n:
if i == 0 or i == 1:
print('{}; '.format(i), end='')
ant = 1
ant2 = 0
else:
fibonacci = ant + ant2
print('{}; '.format(fibonacci), end='')
ant2 = ant
ant = fibonacci
i += 1 |
898893814eda9f044ab6c1e37892271823834c8e | shankars99/willy-wonka | /vanilla ciphers/affine-substitute.py | 747 | 3.734375 | 4 | #compute mod inverse
def modinv(a, m):
mod_inv = pow(a, -1, m)
return mod_inv
def enc(text, key):
return ''.join([chr(((key[0]*(ord(t) - ord('A')) + key[1]) % 26) +
ord('A')) for t in text.upper().replace(' ', '')])
def dec(cipher, key):
return ''.join([chr(((modinv(key[0], 26)*(ord(c) - ord('A') - key[1]))
% 26) + ord('A')) for c in cipher.upper().replace(' ', '')])
option = input("\n1. Encode\n2. Decode\nEnter your option:")
text = input("Enter the text:")
key_raw = (input("Enter the key pair:").split(" "))
key = [int(i) for i in key_raw]
print(key)
if option == '1':
cipher = enc(text, key)
print(cipher)
else:
plain = dec(text, key)
print(plain)
|
dc2030016ca6376458cf7bb8c0675adf0144dc91 | mariajosearias/Esctructura-de-control-selectivas | /ejercicios/E8.py | 348 | 3.890625 | 4 | """
Entradas
valor entero 1-->int-->x
valor entero 2-->int-->y
salidas
valores de x u y
"""
x=int(input("Digite el valor del entero: "))
y=int(input("Digite el valor del entero: "))
expre=(x**3+y**4-2*x**2)
if (expre<=680):
print("X y Y satisfacen la expresión "+str(expre))
elif(expre>=680):
print("la expresion es mayor a 680 ") |
6d2668871e8429c389b08d4781e5fea70dcdfa55 | aiifabbf/leetcode-memo | /528.py | 2,207 | 3.578125 | 4 | """
.. default-role:: math
实现带权采样
大致原理是把给你的权重array ``weights`` 看作是非归一化的概率密度函数,然后积分/前缀和算出非归一化的概率分布函数 ``cdf`` , ``cdf[i + 1] - cdf[i]`` 是取第 `i` 个元素的权重。
采样的时候,在 `[0, \sum w)` 区间里按均匀分布随机取一个整数 `k` ,再去 ``cdf`` 里面找一个 ``cdf[i]`` 使得 `k` 在 ``[cdf[i], cdf[i + 1])`` 区间里。此时 `i` 就是最终要返回的样本。
举个例子,比如权重是 ``[3, 14, 7, 1]`` ,那么非归一化概率分布函数是
::
0, 3, 17, 24, 25
第0个区间是 `[0, 3) ,第1个区间是 `[3, 17)` ,第2个区间是 `[17, 24)` ,第3个区间是 `[24, 25)` 。
现在在 `[0, 25)` 里均匀采样,假设采样得到的是2,2正好在 `[0, 3)` 区间里,所以样本是0。假设采样得到的是10,10正好在 `[3, 17)` 区间里,所以样本是1。假设采样得到24,24在 `[24, 25)` 里,所以样本是3。
所以还是二分搜索的套路。
.. 更详细的推导在497的注释里。
"""
from typing import *
import itertools
import random
class Solution:
def __init__(self, w: List[int]):
self.cdf = [0] + list(itertools.accumulate(w)) # 概率分布函数
def pickIndex(self) -> int:
k = random.randint(0, self.cdf[-1] - 1) # 在[0, sum(weights))里按均匀分布取一个数
# 然后用二分找到这个数属于第几个区间,如果k属于[a_i, a_{i + 1}),那么应该返回i
left = 0
right = len(self.cdf)
while left < right:
middle = (left + right) // 2
if k > self.cdf[middle]:
left = middle + 1
elif k < self.cdf[middle]:
right = middle
else: # 相等的时候,必须往左看,不能往右看,因为可能会有权重是0的数字,如果往右看了的话,会永远取右边的数字
right = middle
if self.cdf[left] == k:
return left
else:
return left - 1
# Your Solution object will be instantiated and called as such:
# obj = Solution(w)
# param_1 = obj.pickIndex() |
85282cc5dffd44f1df84585030b5fb1591c26721 | Jorza/arcade-games-tutorial | /Playground.py | 164 | 3.859375 | 4 | months = "JanFebMarAprMayJunJulAugSepOctNovDec"
n = int(input("Enter a month number: "))
start_index = 3*(n - 1)
print(months[start_index:start_index + 3])
|
db50a687b9cb5d2e557824ecb4c70040eda8f915 | saurabh-pandey/AlgoAndDS | /leetcode/linkedList/singly_linked_list/intersection_a1.py | 3,483 | 3.640625 | 4 | #URL: https://leetcode.com/explore/learn/card/linked-list/214/two-pointer-technique/1214/
# Description
"""
Given the heads of two singly linked-lists headA and headB, return the node at which the two lists
intersect. If the two linked lists have no intersection at all, return null.
For example, the following two linked lists begin to intersect at node c1:
It is guaranteed that there are no cycles anywhere in the entire linked structure.
Note that the linked lists must retain their original structure after the function returns.
Example 1:
Input: intersectVal = 8, listA = [4,1,8,4,5], listB = [5,6,1,8,4,5], skipA = 2, skipB = 3
Output: Intersected at '8'
Explanation: The intersected node's value is 8 (note that this must not be 0 if the two lists
intersect).
From the head of A, it reads as [4,1,8,4,5]. From the head of B, it reads as [5,6,1,8,4,5]. There
are 2 nodes before the intersected node in A; There are 3 nodes before the intersected node in B.
Example 2:
Input: intersectVal = 2, listA = [1,9,1,2,4], listB = [3,2,4], skipA = 3, skipB = 1
Output: Intersected at '2'
Explanation: The intersected node's value is 2 (note that this must not be 0 if the two lists
intersect).
From the head of A, it reads as [1,9,1,2,4]. From the head of B, it reads as [3,2,4]. There are 3
nodes before the intersected node in A; There are 1 node before the intersected node in B.
Example 3:
Input: intersectVal = 0, listA = [2,6,4], listB = [1,5], skipA = 3, skipB = 2
Output: No intersection
Explanation: From the head of A, it reads as [2,6,4]. From the head of B, it reads as [1,5]. Since the two lists do not intersect, intersectVal must be 0, while skipA and skipB can be arbitrary values.
Explanation: The two lists do not intersect, so return null.
Constraints:
The number of nodes of listA is in the m.
The number of nodes of listB is in the n.
0 <= m, n <= 3 * 104
1 <= Node.val <= 105
0 <= skipA <= m
0 <= skipB <= n
intersectVal is 0 if listA and listB do not intersect.
intersectVal == listA[skipA + 1] == listB[skipB + 1] if listA and listB intersect.
Follow up: Could you write a solution that runs in O(n) time and use only O(1) memory?
"""
def nextNode(currNodeA, currNodeB):
if currNodeA._next is None and currNodeB._next is None:
# Reached the tail of both lists
return
elif currNodeA._next is None and currNodeB._next is not None:
# Reached the tail of A so continue diving only in B
nextNode(currNodeA, currNodeB._next)
elif currNodeA._next is not None and currNodeB._next is None:
# Reached the tail of B so continue diving only in A
nextNode(currNodeA._next, currNodeB)
else:
# Still not reached the tail of both A and B continue diving
nextNode(currNodeA._next, currNodeB._next)
def getIntersectionNode(headA, headB):
"""
IDEA 1: The idea is to reach the tail of both the lists and the climb upwards till reaching a
branching point. Probably using recursion.
IDEA 2: Use stack instead of recursion. Try this one first.
"""
stackA = []
nodeA = headA
while nodeA is not None:
stackA.append(nodeA)
nodeA = nodeA._next
stackB = []
nodeB = headB
while nodeB is not None:
stackB.append(nodeB)
nodeB = nodeB._next
intersectedNode = None
while len(stackA) > 0 and len(stackB) > 0:
nodeA = stackA.pop()
nodeB = stackB.pop()
if nodeA is nodeB:
intersectedNode = nodeA
continue
else:
break
return intersectedNode
|
dfb8e76f0fccedb60e1e39eeb3046d19447bd0fb | artazm/practice-python-sol | /exercise_16.py | 578 | 3.65625 | 4 | # Password Generator
# weak (1-3) medium (4-6) strong ()
import random
passw = ['write', 'a', 'password', 'generator', 'python', 'creative', 'mix']
num = list(str(range(0, 10)))
symbols = ['!', '@', '#', '$', '%', '&', '*']
pass_gen = passw + symbols + num
i = 0
strength = input('How strong you want your password: ')
if strength == 'weak':
i = random.randint(1, 3)
elif strength == 'medium':
i = random.randint(4, 6)
elif strength == 'strong':
i = random.randint(7, 9)
gen_pass = random.sample(pass_gen, i)
print(''.join(gen_pass))
|
4b27fb23fd526d509e40dfa0f1626f8914fd21c0 | JACKSUYON/TRABAJO5_PROGRAMACION_1_B | /verificador_16.py | 575 | 4.03125 | 4 | #verificador 16: calcular el tiempo de enuentro
tiempo_encuentro, distancia, velocidad1, velocidad2=0.0, 0.0, 0.0, 0.0
#asigancion de valores
distancia=int(input("mostrar distanccia:"))
velocidad1=int(input("mostrar velocidad:"))
velocidad2=int(input("mostrar velocidad 2"))
#calculo
tiempo_encuentro=(distancia)/(velocidad1 + velocidad2)
verificador=(tiempo_encuentro<=30)
#mostrar valores
print("distancia:",distancia)
print("velocidad:",velocidad1)
print("velocidad:",velocidad2)
print("tiempo de encuentro:",tiempo_encuentro)
print("tiempo de encuentro<=30",verificador)
|
249535b0aee56265f5c5db10b297cdad64127b63 | Junhao-He/PythonUpUp | /Algorithm/isValidSudoku.py | 2,082 | 3.59375 | 4 | # coding = utf-8
# @Time : 2021/7/26 20:04
# @Author : HJH
# @File : isValidSudoku.py
# @Software: PyCharm
class Solution:
def isValidSudoku(self, board) -> bool:
check = []
# for i in board:
# for j in i:
# if not j == '.':
# check.append(j)
# if not len(check) == len(set(check)):
# return False
# else:
# check = []
for i in range(9):
for j in range(9):
if not board[j][i] == '.':
check.append(board[j][i])
if not len(check) == len(set(check)):
return False
else:
check = []
for i in range(9):
for j in range(9):
if not board[i][j] == '.':
check.append(board[i][j])
if not len(check) == len(set(check)):
return False
else:
check = []
starts = [[0, 0], [3, 0], [6, 0], [0, 3], [3, 3], [6, 3], [0, 6], [3, 6], [6, 6]]
for start in starts:
for i in range(3):
for j in range(3):
x = start[0] + i
y = start[1] + j
if not board[x][y] == '.':
check.append(board[x][y])
if not len(check) == len(set(check)):
return False
else:
check = []
return True
if __name__ == '__main__':
so = Solution()
board = [["5", "3", ".", ".", "7", ".", ".", ".", "."]
, ["6", ".", ".", "1", "9", "5", ".", ".", "."]
, [".", "9", "8", ".", ".", ".", ".", "6", "."]
, ["8", ".", ".", ".", "6", ".", ".", ".", "3"]
, ["4", ".", ".", "8", ".", "3", ".", ".", "1"]
, ["7", ".", ".", ".", "2", ".", ".", ".", "6"]
, [".", "6", ".", ".", ".", ".", "2", "8", "."]
, [".", ".", ".", "4", "1", "9", ".", ".", "5"]
, [".", ".", ".", ".", "8", ".", ".", "7", "9"]]
print(so.isValidSudoku(board))
|
567f48193baa3d139cbb3b0f96eedfd4f047e710 | FelixZFB/Python_advanced_learning | /02_Python_advanced_grammar_supplement/001_2_高级语法(装饰器-闭包-args-kwargs)/012-函数闭包_1_闭包定义.py | 3,479 | 3.90625 | 4 | # 闭包的定义
# 定义:闭包是由函数及其相关的引用环境组合而成的实体(即:闭包=函数+引用环境(数据))(# 闭包=函数块+定义函数时的环境)
# 下面这个就是一个简单的闭包函数
def ExFunc(n):
sum = n
def InsFunc():
return sum + 1
return InsFunc
myFunc_1 = ExFunc(10)
print(myFunc_1())
myFunc_2 = ExFunc(20)
print(myFunc_2())
# 函数InsFunc是函数ExFunc的内嵌函数,并且是ExFunc函数的返回值。
# 我们注意到一个问题:内嵌函数InsFunc中 引用到外层函数中的局部变量sum,
# Python会怎么处理这个问题呢?先让我们来看看这段代码的运行结果。
# 当我们调用分别由不同的参数调用ExFunc函数得到的函数时myFunc_1(),myFunc_2()
# 得到的结果是隔离的,也就是说每次调用ExFunc函数后都将生成并保存一个新的局部变量sum。
# 其实这里ExFunc函数返回的就是闭包。
# ExFunc函数只是返回了内嵌函数InsFunc的地址,在执行InsFunc函数时将会由于在其作用域内找不到sum变量而出错。
# 而在函数式语言中,当内嵌函数体内引用到体外的变量时,将会把定义时涉及到的引用环境和函数体打包成一个整体(闭包)返回。
# 现在给出引用环境的定义就容易理解了:引用环境是指在程序执行中的某个点所有处于活跃状态的约束
# (一个变量的名字和其所代表的对象之间的联系)所组成的集合。闭包的使用和正常的函数调用没有区别。
# 由于闭包把函数和运行时的引用环境打包成为一个新的整体,所以就解决了函数编程中的嵌套所引发的问题。
# 如上述代码段中,当每次调用ExFunc函数 时都将返回一个新的闭包实例,这些实例之间是隔离的,分别包含调用时不同的引用环境现场。
# 不同于函数,闭包在运行时可以有多个实例,不同的引用环境和相同的函数组合可以产生不同的实例。
# python中的闭包从表现形式上定义(解释)为:
# 如果在一个内部函数里,对在外部作用域(但不是在全局作用域)的变量进行引用,
# 那么内部函数就被认为是闭包(closure).比如上面的函数:sum就外部局部变量,InsFunc就是内部函数
# 再看一个例子:
# (外层函数传入一个参数a, 内层函数依旧传入一个参数b, 内层函数使用a和b, 最后返回内层函数)
def outer(a):
def inner(b):
return a + b
return inner
c = outer(8)
res = c(10)
# c是一个函数,outer(8)运行结果返回值是函数inner,
# c指向的是outer.inner,外部局部变量a就是8
# c(10)就是outer.inner(10)(但是函数运行不能这么写,该处只是比喻),即b是10
print(type(c))
print(c.__name__) #c函数运行的是inner函数
print(type(res))
print(res)
print(outer(8)(10))
# 结合这段简单的代码和定义来说明闭包:
# 如果在一个内部函数里:inner(y)就是这个内部函数,
# 对在外部作用域(但不是在全局作用域)的变量进行引用:
# a就是被引用的变量,a在外部作用域outer函数里面,但不在全局作用域里,
# 则这个内部函数inner就是一个闭包。
# 再稍微讲究一点的解释是,闭包=函数块+定义函数时的环境,
# 内部函数inner就是函数块,a就是环境,当然这个环境可以有很多,不止一个简单的a。
|
b7affcc6410e3c13833490112976c52ffe8f74d1 | kariane/projectsPython | /project1.py | 238 | 3.875 | 4 | from random import randint
def rand():
return randint(1,6)
rep = True
while rep:
print("came out the value:",rand())
print("would you like to roll the dice again?")
rep = ("yes") in input().lower()
print("Game Over") |
adf81dcf49c70d4fd2e944d41632a014f9ff938e | mastan-vali-au28/My-Code | /coding-challenges/week06/Day03/Q2.py | 564 | 4.15625 | 4 | '''
Given a number , find if the number is a perfect square root or not ?
Also , find Time and space Complexity
example :
Input : n = 4
output : - True
Input : n = 10
output : - False
Explanation : since square root (4) =2 (perfect square ) --true
Square root(10) = 3.35 (Not perfect square) -- false
Sample :
Def find_perfect_square(N):
'''
from math import sqrt
def find_perfect_square(n):
sq_root = int(sqrt(n))
return (sq_root*sq_root) == n
n1=int(input("Enter a number : "))
print (find_perfect_square(n1))
#Time complexity:O(1)
#Space complexity:O(1) |
c702788844f9c09543c08ff75bf0221098d60dd9 | shobhakharpy/CTI-110 | /HDCoockout_Calculator.py | 1,180 | 3.84375 | 4 | # CTI 110
# Shobhakhar Adhikari
# Practice Assignment
# define varaibles and get the input
def HDCookout ():
Num_ppl = int(input("Enter the number of people attending the cookout:"))
# Calculations and decision structure
x = Num_ppl//10 # gives the number without decimal after divided by 10
a = Num_ppl%10 # gives the remainder after divided by 10
y = Num_ppl//8 # gives the number without decimal after divided by 8
b = Num_ppl%8 # gives the remainder after divided by 8
if a < 10 and a > 0:
Num_hotdogsp = x + 1
leftover_hotdogs = 10 - a
else:
Num_hotdogsp = x
leftover_hotdogs = 0
if b < 8 and b >0:
Num_hotdogbunsp = y + 1
leftover_buns = 8 - b
else:
Num_hotdogbunsp = y
leftover_buns = 0
# display output
print("The minimum number of packages of hot dogs required is:",Num_hotdogsp)
print("The minimum number of packages of hot dog buns required is:",Num_hotdogbunsp)
print("The number of hot dogs leftover is:",leftover_hotdogs)
print("The number of hot dog buns leftover is:",leftover_buns)
HDCookout()
|
60edd08e3982f0f93fa3a8258b5ac688038dc406 | secretdsy/programmers | /level2/practice/12949.py | 442 | 3.578125 | 4 | def solution(arr1, arr2):
# 결과 리스트를 0으로 초기화
answer = [[0] * len(arr2[0]) for _ in range(len(arr1))]
# matrix_size = (i,k) * (k,j) = (i,j)
for k in range(len(arr1[0])):
for i in range(len(arr1)):
for j in range(len(arr2[0])):
answer[i][j] += (arr1[i][k] * arr2[k][j])
return answer
ar1=[[1, 4], [3, 2], [4, 1]]
ar2=[[1, 2], [3, 4]]
print(solution(ar1, ar2))
|
27918f7a20e38214c841735e03ae850b58ab1d25 | edisonkolaj/Prework-REPO | /Assignment 1.py | 100 | 3.703125 | 4 | #Edison Kolaj
#Assignement #1
Name = input("Hello User. What is your name?")
print("Welcome", Name)
|
2e09618979b589c36c8dc04fad1e0186d5528810 | quarkgluant/boot-camp-python | /day03/ex02/ScrapBooker.py | 3,691 | 3.640625 | 4 | #!/usr/bin/env python3
# -*-coding:utf-8 -*
import numpy as np
class ScrapBooker:
"""All methods take in a NumPy array and return a new modified one.
We are assuming that all inputs are correct, ie, you don't have to protect your functions
against input errors.
In this exercise, when specifying positions or dimensions, we will assume that the first coordinate is counted
along the vertical axis starting from the TOP, and that the second coordinate is counted along the horizontal axis starting
from the left.Indexing starts from 0."""
def crop(self, array, dimensions, position=(0,0)):
"""crop the image as a rectangle with the given dimensions(meaning, the new height and width for the image),
whose top left corner is given by the position argument.The position should be(0, 0) by default.You have to
consider it an error( and handle said error) if dimensions is larger than the current image size."""
if array.shape[0] < position[0] + dimensions[0] or array.shape[1] < position[1] + dimensions[1]:
raise BaseException(f"the positions {position} + dimensions {dimensions} are greater than the image's dim {array.shape[0:2]}")
return array[position[0]:dimensions[0], position[1]:dimensions[1]]
def thin(self, array, n, axis):
"""delete ever n-th pixel row along the specified axis(0 vertical, 1 horizontal), example below."""
return np.delete(array, [num for num in range(array.shape[axis]) if num % n == 0 and num > 0], axis)
def juxtapose(self, array, n, axis=0):
"""juxtapose n copies of the image along the specified axis (0 vertical, 1 horizontal)."""
# return np.stack([array for _ in range(n)], axis=axis)
if axis == 1:
return np.hstack([array for _ in range(n)])
elif axis == 0:
return np.vstack([array for _ in range(n)])
def mosaic(self, array, dimensions):
"""make a grid with multiple copies of the array.The dimensions argument specifies the dimensions(meaning the
height and width) of the grid (e.g. 2x3)."""
result = self.juxtapose(array, dimensions[0], axis=0)
return self.juxtapose(result, dimensions[1], axis=1)
import matplotlib.image as mpimg
import matplotlib.pyplot as plt
class ImageProcessor:
def load(self, path) :
"""opens the .png file specified by the path argument and returns an array
with the RGB values of the image pixels. It must display a message specifying
the dimensions of the image (e.g. 340 x 500)."""
img = mpimg.imread(path)
# if img.dtype == np.float32: # Si le résultat n'est pas un tableau d'entiers
# img = (img * 255).astype(np.uint8)
print(f"Loading image of dimensions {img.shape[0:2]}")
return img
def display(self, array) :
"""takes a NumPy array as an argument and displays the corresponding RGB image."""
plt.imshow(array)
plt.show()
if __name__ == '__main__':
# from ImageProcessor import ImageProcessor
imp = ImageProcessor()
arr = imp.load("../ressources/42AI.png")
# Loading image of dimensions 200 x 200
imp.display(arr)
print(arr)
sb = ScrapBooker()
imp.display(sb.crop(arr, (100, 100), position=(50, 50)))
# imp.display(sb.crop(arr, (200, 200)))
# try:
# imp.display(sb.crop(arr, (150, 150), position=(60, 50)))
# except BaseException:
# print("Error")
three_times = sb.juxtapose(arr, 3)
print(f"shape of juxtapose: {three_times.shape}")
imp.display(three_times)
mosaic = sb.mosaic(arr, (3,2))
imp.display(mosaic)
|
382c5bc363285cf4ed5d2ee8edcd30e3d33d4fa8 | tonyechen/python-codes | /reduceFunction/main.py | 444 | 4 | 4 | # reduce = apply a function to an iterable and reduce it to a single cumulative value.
# performs function on first two elements and repeats process until 1 value remains
#
# reduce(function, iterable)
import functools
letters = ["H", "E", "L", "L", "O"]
word = functools.reduce(lambda x, y: x + y, letters)
print(type(word), word)
factorial = [5, 4, 3, 2, 1]
result = functools.reduce(lambda x, y : x * y, factorial)
print(result) |
6591cfb2a328efc8a9ac4d4069886d42f4b2adf4 | vincepay/Project_Euler | /python/21-30/Prob29.py | 1,561 | 3.765625 | 4 | ##Consider all integer combinations of a^b for 2 <= a <= 5 and 2 <= b <= 5:
##
## 2^2=4, 2^3=8, 2^4=16, 2^5=32
## 3^2=9, 3^3=27, 3^4=81, 3^5=243
## 4^2=16, 4^3=64, 4^4=256, 4^5=1024
## 5^2=25, 5^3=125, 5^4=625, 5^5=3125
##
##If they are then placed in numerical order, with any repeats removed,
##we get the following sequence of 15 distinct terms:
##
##4, 8, 9, 16, 25, 27, 32, 64, 81, 125, 243, 256, 625, 1024, 3125
##
##How many distinct terms are in the sequence generated
##by a^b for 2 <= a <= 100 and 2 <= b <= 100?
##-----------------------------------------------------------------------
from time import clock
from math import sqrt
def findAllIntComb(a,b):
setOfComb = set([])
cou = 0
for ai in range(2,a+1):
for bi in range(2,b+1):
ax,bx=ai,bi
while True:
if ( (sqrt(ax) <2 ) | (bx*2 >b) | ( (int(sqrt(ax))) **2 !=ax )) :
break
ax = sqrt(ax)
bx = bx*2
#print((ax,bx))
if (ax,bx) in setOfComb:
cou+=1
#print ((ai,bi) , "is",(int(ax),bx), "Whoho!" )
else:
setOfComb.add((int(ax),int(bx)))
return sorted(list(setOfComb)),len(setOfComb),cou, (a -1)**2-cou
def findAllIntCombBrute(a,b):
setOfComb = set([])
for ai in range(2,a+1):
for bi in range(2,b+1):
setOfComb.add(ai**bi)
return setOfComb
start = clock()
res = findAllIntCombBrute(100,100)
print ('Count',len(res), 'Time:', str(clock() - start)+'s')
|
96f6b1ef3e0b9141759a68b2bd6a895de45fc47e | carlos-andrey/programacao-orientada-a-objetos | /listas/lista-de-exercicio-07/questao06.py | 913 | 3.53125 | 4 | class Retangulo:
def __init__(self, base, altura):
self.base = base
self.altura = altura
def mudar_valor_lado(self, nova_base, nova_altura):
self.base = nova_base
self.altura = nova_altura
def retornar_valor_lado(self):
return self.base, self.altura
def calcular_area(self):
self.area = self.altura * self.base
return self.area
def calcular_perimetro(self):
self.perimetro = (self.altura + self.base) * 2
return self.perimetro
base = int(input('Informe, em metros, a primeira medida do local: '))
altura = int(input('Informe, em metros, a segunda medida do local: '))
comodo1 = Retangulo(base, altura)
piso = comodo1.calcular_area()
rodape = comodo1.calcular_perimetro()
print(f'Serão necessarios {piso} metros quadrados para o piso.')
print(f'Serão necessarios {rodape/2} metros quadrados para o rodapé.')
|
93a59e35851ca5d4e4efc2f633942428e173a521 | ErenBtrk/Python-Fundamentals | /Pandas/PandasDataframe/Exercise54.py | 339 | 4.4375 | 4 | '''
54. Write a Pandas program to convert a given list of lists into a Dataframe.
'''
import pandas as pd
my_lists = [['col1', 'col2'], [2, 4], [1, 3]]
# sets the headers as list
headers = my_lists.pop(0)
print("Original list of lists:")
print(my_lists)
df = pd.DataFrame(my_lists, columns = headers)
print("New DataFrame")
print(df) |
0d4883a8d8d46f1e6b5fb5fd1e9647abac80034e | ftahrirc/Snake1 | /snake.py | 752 | 3.859375 | 4 | import turtle,random
class Cell:
def__init__(self,size,t,x,y):
self.x=x
self.y=y
self.t=t
self.size=size
def draw_square(self):
for side in range(4):
self.t.fd(self.size)
self.t.left(90)
def draw_snake()(self)
for side in range(5):
cell=cell(10,turtle.turtle(),i*10,i*10)
cell.draw_square()
cell.draw_snake()
cell=Cell(10,turtle.Turtle(),0,0)
cell.draw_square()
class food:
def__init__(self):
self.cell=Cell(x,y)
class Cell:
def __init__(self,t):
# set initial position
self.x = 0
self.y = 0
# set initial size of a cell
self.cell_size = 10
# set the turtle
self.t = t
|
21fcb74551980e0c9f82758989ed41d42b01c74e | DiegoElizaldeUriarte/Mision_02 | /velocidad.py | 661 | 3.859375 | 4 | # Autor: Diego Raul Elizalde Uriarte, a01748756
# Descripcion: Pregunte la velocidad e imprima las distancias en el tiempo requerido y calcule el tiempo en cierta distancia.
# Escribe tu programa después de esta línea.
#Lectura y calculo de resultados
v = int(input("Dame la velocidad a la que viaja un auto en km/h y en numeros enteros: "))
t = 6
d = (v*t)
T = 3.5
D = (v*T)
dist = 485
tiem = (485/v)
#Imprimir resultados
print("La distancia en km. que recorre en 6 hrs. es de: %.1f" %(d),"km")
print("La distancia en km. que recorre en 3.5 hrs. es de: %.1f" %(D),"km")
print("El tiempo en horas y minutos que requiere para recorrer 485 km. es de: %.1f" % (tiem),"hrs.")
|
74eed9c2864d3389ea6ac02f4794c9c84641eb0f | furkanoruc/furkanoruc.github.io | /Python Programming Practices - Daniel Lyang Book/ch10 copy/10_Furkan_36_linearsearch- check.py | 440 | 3.625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Feb 5 14:38:14 2021
@author: furkanoruc
"""
#Linear Search
n = eval(input("Enter number of integers: "))
lst = []
#counter = [0] * n
for i in range(n):
lst.append(eval(input("Enter the integers, one by one: ")))
key = eval(input("Enter the key to be searched: "))
for i in range(len(lst)):
if key == lst[i]:
ind = i
break
print(lst[ind], ind) |
6f73174520db3b1c3c2b2f394440fe24cb7fca00 | llimllib/personal_code | /python/poker/win_prcnt.py | 1,402 | 3.96875 | 4 | """
Doubts, thoughts:
o We can calculate, with 5 cards left, how many hands add a 3rd or a 3rd
and a 4th to a pocket pair
o We can calculate how many hands add a pair to a non-pair
Things we need to know:
o how many possible hands there are to be dealt
o how many of those have >2 hearts
o how many of those give either hand a straight
o how many of those have >0 A's
o how many of those have a 9 and an 8
-- How many possible hands there are --
o 48 choose 5 = (48*47*46*45*44)/ 5! = 1,712,304
LATER:
read source code for poker evaluator in C.
"""
from cards import *
#we'll use these two hands for testing
hand1 = ["12s", "12c"]
hand2 = ["9h", "8h"]
hands = [hand1, hand2]
def win_percent(deck, hands):
#assumes cards are valid
for hand in hands:
for card in cards:
deck.deal_card(card)
def cond_prob(top, bot):
top_sum = 1
fact = 1
for i in range(bot):
top_sum *= top - i
fact *= i + 1
return top_sum/float(fact)
def test_prob(deck):
ace_count = 0.
try:
deck.deck.remove("12S")
deck.deck.remove("12H")
except ValueError: pass
iter = 100000
n_cards = 3
for i in range(iter):
h = deck.pick_card(n_cards)
for card in h:
if card[:2] == "12":
ace_count += 1
break
print (ace_count/iter) * 100, " percent"
#test_prob(cards())
|
90dc7417a611bcad57aab0ff40c1c8199638a6ed | JeffreyJalal/AdventOfCode | /2015/Day3/PerfectlySphericalHousesInAVacuum.py | 941 | 3.5 | 4 | def getNewLocation(location, direction):
newLocation = location.copy()
if direction == '>':
newLocation[0] += 1
elif direction == '<':
newLocation[0] -= 1
elif direction == '^':
newLocation[1] += 1
else:
newLocation[1] -= 1
return newLocation
currentLocationSanta = [0, 0]
currentLocationRobosanta = [0, 0]
f = open("input.txt", 'r')
directions = f.readline()
visitedLocations = [currentLocationSanta.copy(), currentLocationRobosanta.copy()]
for i in range(0, len(directions), 2):
currentLocationSanta = getNewLocation(currentLocationSanta, directions[i])
currentLocationRobosanta = getNewLocation(currentLocationRobosanta, directions[i+1])
visitedLocations.append(currentLocationSanta.copy())
visitedLocations.append(currentLocationRobosanta.copy())
visitedLocations = set(tuple(i) for i in visitedLocations)
print(visitedLocations)
print(len(visitedLocations))
|
89f838a083b2e8e2df8671345087598baed3bb57 | Aasthaengg/IBMdataset | /Python_codes/p03252/s883010906.py | 273 | 3.546875 | 4 | s = input()
t = input()
f = True
for (s1, s2) in [(s, t), (t, s)]:
d = dict()
for c1, c2 in zip(s1, s2):
if c1 not in d:
d[c1] = c2
elif d[c1] != c2:
f = False
break
if f:
print('Yes')
else:
print('No')
|
a723d8823451f7b2b780fe4858b7adf30e266197 | fxyan/data-structure | /code/剑指/二叉树的下一个节点.py | 1,142 | 4.03125 | 4 | """
给定一棵二叉树的其中一个节点,请找出中序遍历序列的下一个节点。
注意:
如果给定的节点是中序遍历序列的最后一个,则返回空节点;
二叉树一定不为空,且给定的节点一定不是空节点;
样例
假定二叉树是:[2, 1, 3, null, null, null, null], 给出的是值等于2的节点。
则应返回值等于3的节点。
解释:该二叉树的结构如下,2的后继节点是3。
2
/ \
1 3
这里注意当给出的节点没有右节点的时候还有另一种情况。
"""
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
self.father = None
class Solution(object):
def inorderSuccessor(self, q):
"""
:type q: TreeNode
:rtype: TreeNode
"""
if q.right is not None:
r = q.right
while r:
if r.left is not None:
r = r.left
else:
return r
while q.father and q == q.father.right:
q = q.father
return q.father
|
7b8403c1731ec0a1187bd94fa7ef06f56783de7f | psandahl/trio | /trio/tests/utils.py | 801 | 3.640625 | 4 | import math
def equal_matrices(m, n):
"""
Helper function to test if two matrices are somewhat equal.
"""
if m.shape == n.shape and m.dtype == m.dtype and m.ndim > 1:
for row in range(m.shape[0]):
for col in range(m.shape[1]):
if math.fabs(m[row, col] - n[row, col]) > 0.000001:
return False
else:
raise TypeError("m and n are not matrices")
return True
def equal_arrays(m, n):
"""
Helper function to test if two arrays are somewhat equal.
"""
if m.size == n.size and m.dtype == m.dtype and m.ndim == 1:
for i in range(m.size):
if math.fabs(m[i] - n[i]) > 0.000001:
return False
else:
raise TypeError("m and n are not arrays")
return True
|
32c02e161623769b224b135dfdb5bb17e4f55c8a | RichieSong/algorithm | /算法/排序/二分查找.py | 3,720 | 3.96875 | 4 | # coding:utf-8
"""
二分查找的必要条件:
1,必须是数组
2,必须是有序
3,不适合数据量太大或太小的情况,太大可能会申请内存失败(申请内存必须是连续的,而零散的内存会失败),太小没必要,直接遍历即可
"""
# 最简单的二分查找
def bsearch(arr, length, value):
"""
:param length: 数组长度
:param value: 查找的值
:return:
"""
low = 0
high = length - 1
while high >= low: # 注意一定是大于等于
mid = (
low + high) / 2 # 有点问题 如果特别大的话,会导致内存溢出,优化方案:low+(high-low)/2 ,当然也可以用位运算,low+((high-low)>>1)相对于计算机来说位运算比除法会更难快
if arr[mid] == value:
return mid
elif arr[mid] > value:
high = mid - 1
else:
low = mid + 1
return -1
# 常见的二分查找变型问题
# 查找第一个值等于给定的值的元素
def bsearch1(arr, length, value):
"""
:param length: 数组长度
:param value: 查找的值
:return: int
有重复元素
[0,1,2,3,4,5,6,7,8,8,8,8,9,10] 给定值为8 找出下标为8的元素 return 8
"""
low = 0
high = length - 1
while high >= low:
mid = low + ((high - low) >> 1)
if arr[mid] < value:
low = mid + 1
elif arr[mid] > value:
high = mid - 1
else:
if length == 0 or arr[mid - 1] != value:
return mid
else:
high = mid - 1
return -1
# 查找最后一个值等于给定值的元素
def bsearch2(arr, length, value):
"""
:param length: 数组长度
:param value: 查找的值
:return: int
有重复元素
[0,1,2,3,4,5,6,7,8,8,8,8,9,10] 给定值为8 找出下标为11的元素 return 11
"""
low = 0
high = length - 1
while high >= low:
mid = low + ((high - low) >> 1)
if arr[mid] > value:
high = mid - 1
elif arr[mid] < value:
low = mid + 1
else:
if mid == length - 1 or arr[mid + 1] != value:
return mid
else:
low = mid + 1
return -1
# 查找第一个值大于等于给定值的元素
def bsearch3(arr, length, value):
"""
:param length: 数组长度
:param value: 查找的值
:return: int
[0,1,2,3,4,5,7,8,8,8,8,9,10] 给定值为6 找出下标为6的元素 return 6
"""
low = 0
high = length - 1
while high >= low:
mid = low + ((high - low) >> 1)
if arr[mid] < value:
low = mid + 1
else:
if mid == 0 or arr[mid - 1] < value:
return mid
else:
high = mid - 1
return -1
# 查找最后一个值小于等于给定值的元素
def bsearch4(arr, length, value):
"""
:param length: 数组长度
:param value: 查找的值
:return: int
[0,1,2,3,4,5,7,8,8,8,8,9,10] 给定值为6 找出下标为5的元素 return 5
"""
low = 0
high = length - 1
while high >= low:
mid = low + ((high - low) >> 1)
if arr[mid] > value:
high = mid - 1
else:
if mid == length - 1 or arr[mid + 1] > value:
return mid
else:
low = mid + 1
return -1
if __name__ == '__main__':
arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
arr1 = [0, 1, 2, 3, 6, 7, 8, 8, 8, 8, 9, 10]
# print(bsearch(arr, 10, 11))
print(bsearch1(arr1, len(arr1), 8))
print(bsearch2(arr1, len(arr1), 5))
print(bsearch3(arr1, len(arr1), 4))
|
4f7c9801d0e3a31cd6d109dc61b79b05b3629740 | KB-perByte/CodePedia | /Gen2_0_PP/Homeworks/geeksForGeeks_isBInaryNumMulOf3.py | 381 | 3.515625 | 4 | #code
T = int(input())
for i in range(T):
n=list(input())
value=0
for i in range(len(n)):
d=n.pop()
if d=='1':
value=value+pow(2,i)
if(value%3==0):
print("1")
else:
print("0")
''' #TODO
diff btn the cnt of set bits at odd pos and the cnt of
set bits at even pos is a mltipl of 3 then the number is a niltpl of 3
''' |
f5efbc811957fa84134904d78c13444708ab5eb9 | Ideaboy/MyLearnRecord | /algo_learn/insertion_sort.py | 726 | 4.0625 | 4 | #!/usr/bin/python
# -*- coding:utf-8 -*-
# 2019年5月4日14:40:11
# 插入排序
"""
第一个元素设为有序区,选取后面元素,向前遍历比较,
最小的插入在比较元素前。
较大的直接赋值后移,一直比较,直至最小,在上个位置插入赋值即可。
"""
def insertion_sort(dlist):
for i in range(0, len(dlist)):
preindex = i-1
current = dlist[i]
while preindex >= 0 and dlist[preindex] > current:
dlist[preindex+1] = dlist[preindex]
preindex -= 1
dlist[preindex+1] = current
return dlist
if __name__ == "__main__":
slit = [100, 20, 55, 50, 99, 1, -20]
rl = insertion_sort(slit)
print(rl)
|
b51f18c6edf50183d744ac3c3ed62a92fe98d1c9 | jhonatanmaia/python | /study/curso-em-video/exercises/049.py | 125 | 4 | 4 | x=int(input('Digite o nmero da tabuada: '))
print('-'*20)
for a in range(1,11):
print('{} x {} = {}'.format(a,x,a*x)) |
13dfc5ad116239848ab028874c6393f123f22837 | lalit97/DSA | /union-find/z-kruskal.py | 1,581 | 3.984375 | 4 | '''
understanding ->
https://www.hackerearth.com/practice/algorithms/graphs/minimum-spanning-tree/tutorial/
implementation ->
taking help of Graph bfs dfs implementations
union find implementations of mine
https://www.geeksforgeeks.org/kruskals-minimum-spanning-tree-algorithm-greedy-algo-2/
'''
from collections import defaultdict
class Graph:
def __init__(self):
self.graph = defaultdict(list)
def add_edge(self, a, b, weight):
self.graph[weight].append((a, b))
def root(i):
while vertices[i] != i:
i = vertices[i]
return i
def find(a, b):
return root(a) == root(b)
def union(a, b):
root_a = root(a)
root_b = root(b)
if size[root_a] < size[root_b]:
vertices[root_a] = vertices[root_b]
size[root_b] += size[root_a]
else:
vertices[root_b] = vertices[root_a]
size[root_a] += size[root_b]
def kruskal_mst(graph):
sorted_weights = sorted(graph)
count, result = 0, 0
for weight in sorted_weights:
a, b = graph[weight][0] # first item of list
if not find(a, b):
count += 1
result += weight
union(a, b)
if count == n - 1: # MST is complete
break
return result
if __name__ == '__main__':
g = Graph()
g.add_edge(0, 1, 10)
g.add_edge(0, 2, 6)
g.add_edge(0, 3, 5)
g.add_edge(1, 3, 15)
g.add_edge(2, 3, 4)
graph = g.graph
n = 4 # vertices count
vertices = [i for i in range(n)]
size = [1 for i in range(n)]
print(kruskal_mst(graph))
|
19709ffa1d07c85948c54a939cecc8b42d434e91 | RufusKingori/Lecture_2 | /assignment_2_1.py | 403 | 3.953125 | 4 | #This program adds 2 to a and assigns the results to b
#Multiplies b times 4 and assigns the results to a
#Divides a by 3.14 and assigns the results to c
#Subtracts 8 from b and assigns the results to a
def main():
a = int()
b = int()
c = int()
b = 2 + a
print("b:", b)
a = b * 4
print("a:", a)
c = 3.14 / a
print("c:", c)
a = b - 8
print("a:", a)
main()
|
5f54febed1313c99101f8a8c0bb7dc891b6df757 | mfojtak/deco | /deco/sources/dataset.py | 289 | 3.546875 | 4 | from abc import ABC, abstractmethod
class Dataset(ABC):
@abstractmethod
def __iter__(self):
pass
def eval(self):
res = []
for item in self:
res.append(item)
if len(res) == 1:
return res[0]
return res |
4217c935c0ab445132452750ac62c56f19f4aa9c | thkim1011/chess-ai | /tests/test_chess.py | 1,952 | 3.65625 | 4 | import chess
import unittest
class TestBoard(unittest.TestCase):
def test_get_piece(self):
# Basic Tests
board = chess.Board()
rook1 = board.get_piece(chess.locate("a1"))
self.assertEqual(rook1.name, "rook")
rook2 = board.get_piece(chess.locate("a8"))
self.assertEqual(rook2.name, "rook")
pawn1 = board.get_piece(chess.locate("a2"))
self.assertEqual(pawn1.name, "pawn")
pawn2 = board.get_piece(chess.locate("c2"))
self.assertEqual(pawn2.name, "pawn")
pawn3 = board.get_piece(chess.locate("e2"))
self.assertEqual(pawn3.name, "pawn")
pawn4 = board.get_piece(chess.locate("e7"))
self.assertEqual(pawn4.name, "pawn")
# Assuming move_piece works
board.move_piece(pawn3, chess.locate("e4"))
empty = board.get_piece(chess.locate("e2"))
self.assertEqual(empty, None)
pawn5 = board.get_piece(chess.locate("e4"))
self.assertEqual(pawn5.name, "pawn")
def test_move_piece(self):
# General piece movement
board = chess.Board()
def test_get_moves(self):
board = chess.Board()
print(board)
for b in board.get_moves():
print(b)
def test_copy(self):
board = chess.Board()
board.move_piece(board.get_piece(chess.locate("b1")), chess.locate("c3"))
print(board)
def test_en_passant(self):
board = chess.Board()
white_pawn = board.get_piece(chess.locate("e2"))
black_pawn = board.get_piece(chess.locate("d7"))
board.move_piece(white_pawn, chess.locate("e5"))
board.move_piece(black_pawn, chess.locate("d5"))
self.assertTrue(board.en_passant == black_pawn)
self.assertTrue(white_pawn.is_valid(chess.locate("d6"), board))
self.assertTrue(chess.locate("d6") in white_pawn.valid_pos(board))
if __name__ == "__main__":
unittest.main()
|
b421bd9515cf8cef2029adb1b139986ed5224036 | PROFX8008/Python-for-Geeks | /Chapter04/errors/exception2.py | 170 | 3.5 | 4 | #exception2.py
try:
f = open("abc.txt", "w")
except Exception as e:
print("Error:" + e)
else:
f.write("Hello World")
f.write("End")
finally:
f.close() |
91d4caffa5245e68c779cdd68276cecefca8d5a6 | ncterry/CryptoSteganography | /xaaaa_primaryColors.py | 1,047 | 3.90625 | 4 | from Functions import create_image, get_pixel
from main import *
# Create a Primary Colors version of the image
def convert_primary(image):
# Get size
width, height = image.size
# Create new Image and a Pixel Map
new = create_image(width, height)
pixels = new.load()
# Transform to primary
for i in range(width):
for j in range(height):
# Get Pixel
pixel = get_pixel(image, i, j)
# Get R, G, B values (This are int from 0 to 255)
red = pixel[0]
green = pixel[1]
blue = pixel[2]
# Transform to primary
if red > 127:
red = 255
else:
red = 0
if green > 127:
green = 255
else:
green = 0
if blue > 127:
blue = 255
else:
blue = 0
# Set Pixel in new image
pixels[i, j] = (int(red), int(green), int(blue))
# Return new image
return new
|
d095b5b98a05c15b85547c650c2a72e00b321a2c | kgawne/AdventOfCode2017 | /day3.py | 1,478 | 3.734375 | 4 | # day 3
# kgawne
def TestCompare( case, expected, result):
print('Case ' + str(case) + ': ')
if expected == result:
print("\tSuccess! Result: " + str(result))
return True;
else:
print("\tFailed :( Expected: " + str(expected) + " Result: " + str(result))
return False;
def CalcSteps(squareNum):
#generate blocks up to square number
mSquareNum = 1
d = 1
x = 0
y = 0
#coord = [0,0]
foundNum = False
while not foundNum:
if mSquareNum ==squareNum:
break;
dif = d//abs(d)
#print("d = " +str(d))
#print("dif = " + str (dif))
for _ in range(abs(d)):
x += dif
#print("Shift x by 1: " + str((x,y)) + " squareNum = " + str(mSquareNum))
mSquareNum += 1
if mSquareNum == squareNum:
foundNum = True
break
if(not foundNum ):
for _ in range(abs(d)):
y += dif
#print("Shift y by 1: " + str((x,y))+ " squareNum = " + str(mSquareNum))
mSquareNum += 1
if mSquareNum == squareNum:
foundNum = True
break
if d > 0:
d += 1
d *= -1
else:
d *= -1
d += 1
print("Found coordinates: "+str(squareNum) + " is at " + str((x,y)))
#Calculate abs difference of cartesian coordinates
numSteps = abs(x) + abs(y)
return numSteps;
#Test Cases
TestCompare( 1, 0, CalcSteps(1))
TestCompare(12, 3, CalcSteps(12))
TestCompare(23, 2, CalcSteps(23))
TestCompare(1024, 31, CalcSteps(1024))
data = input("What square do you want steps for?")
steps = CalcSteps(int(data))
print("Steps necessary: " + str(steps))
|
f65d8a9a549ead5deff0d953d9a1e795567e6233 | Maavcardoso/Python3.9 | /Aulas/04_modulos.py | 686 | 4.25 | 4 | # Os módulos servem para adiocionar diferentes funções ao programa python
# Como exemplo, usarei o módulo math.
# Podemos chamar o método de duas formas:
import math # Importa todas as funções de Math
from math import sqrt # Importa uma função específica de Math, no caso, raiz quadrada.
n = int(input('Digite um número: '))
raiz = math.sqrt(n)
print(f'Raiz igual a: {raiz}')
# FUNÇÕES UTEIS DO math
# math.ceil(variavel) = arredonda pra cima
# math.floor(variavel) = arredonda pra baixo
# math.sqrt(variavel) = faz raiz quadrada
# https://docs.python.org/3.9/py-modindex.html
# A biblioteca do Python contém inúmeros módulos, como o random
|
a41bb0e9a679083c2a54b98008646f04591869c9 | ozercimilli/clarusway-aws-devops-workshop | /python/coding-challenges/cc-003-find_largest_number/large.py | 443 | 4.53125 | 5 | 3# Python program to find the largest number among the three input numbers
# creating empty list
lis = []
# user enters the number of elements to put in list
#count = int(input('How many numbers? '))
# iterating till count to append all input elements in list
for n in range(1,6):
number = int(input('Enter number: '))
lis.append(number)
# displaying largest element
print("Largest number of the list is :", max(lis)) |
3b8ecdc391fb36f4c478a1bfe31b03174b50299f | exploreshaifali/datastructures | /bst_recursive.py | 2,021 | 3.859375 | 4 | class BSTNode:
def __init__(self, data, left=None, right=None):
self.data = data
self.left = left
self.right = right
class BST:
def __init__(self, data=None):
if data is None:
self.root = None
else:
self.root = BSTNode(data)
def insert(self, data, cur):
if self.root is None:
self.root = BSTNode(data)
return
if cur is None:
return BSTNode(data)
if data > cur.data:
cur.right = self.insert(data, cur.right)
else:
cur.left = self.insert(data, cur.left)
return cur
def travel(self, cur):
if cur is None:
return
print(cur.data)
if cur.left:
self.travel(cur.left)
if cur.right:
self.travel(cur.right)
def search(self, data, cur):
if cur is None:
return False
if data == cur.data:
return True
if data > cur.data:
return self.search(data, cur.right)
else:
return self.search(data, cur.left)
def min(self, cur):
if cur is None:
return
if cur.left is None:
return cur.data
return self.min(cur.left)
def max(self, cur):
if cur is None:
return
if cur.right is None:
return cur.data
return self.min(cur.right)
def get_height(self, cur):
if cur is None:
return -1
return max(self.get_height(cur.left), self.get_height(cur.right)) + 1
def bfs(self):
if self.root is None:
return
temp = self.root
# initialize a queue which will help in level order traversal
q = [temp]
while q:
temp = q.pop(0)
if temp.data:
print(temp.data, end=', ')
if temp.left:
q.append(temp.left)
if temp.right:
q.append(temp.right)
|
82bc9987958295582cb1a2744260bb12826373a5 | CodePanter/pytut | /Book/Dragon realm.py | 2,239 | 4.125 | 4 | import random
import time
def displayIntro():
print('Welcome in a world full of pitbulls , some are scary but some are actually sweet.')
print()
def chooseCave():
cave = ''
# A local scope is created whenever a function is called. Any variables assigned in this function exist within the local scope. Think of a scope as a container for variables. What makes variables in local scopes special is that they are forgotten when the function returns and they will be re-created if the function is called again.
while cave != '1' and cave != '2':
# a While loop repeats as long as a certain condition is true, when the execution reaches a while statement , it evaluates the condition next to the while keyword. If the condition evaluates true , the execution moves inside the following block, called the while block. If the condition evaluates to False , the execution past the while block.
# == & =! are comparison operators, the AND operator is a Boolean operator. The and operator can be used to evaluate any two Boolean expressions.
#The condition has two parts connected by the AND Boolean operator . The condition is True only if both parts are true.
print('Which cave will you go into, 1 or 2?')
cave = input()
return cave
#A return statement appears only inside def blocks where a function(chooseCave) is defined.
def checkCave(chosenCave):
print('You approach the cave....')
time.sleep(2) #Time module has a function called sleep that pauses th program.
print('It is dark and spooky ...')
time.sleep(2)
print('A large pitbull jumps out in front of you! He opens his jaws and ...')
time.sleep(2)
print()
time.sleep(2)
friendlyCave = random.randint(1,2)
#randint function will randomly return either 1 or 2.
if chosenCave == str(friendlyCave):
# Checks whether the player
print('Gives you his treasure')
else:
print('Gobbles you down in one bite!')
playAgain = 'yes'
while playAgain == 'yes' or playAgain == 'y':
displayIntro()
caveNumber = chooseCave()
checkCave(caveNumber)
print('Do you want to play again? (yes or no)')
playAgain = input()
|
bf28667009a14c246e5a85c43e50bfd2b667ab92 | dabuu/FluentPython | /chap2/2.2.py | 1,464 | 3.5625 | 4 | # coding:utf-8
"""
@file: 2.2.py
@time: 2018/8/17 18:19
@contact: dabuwang
"""
__author__ = 'dabuwang'
symbols = '$%&^#()!@' # £$¤¥¨ª'#¥¢¤£ÿ'
def list_comprehension():
for y in symbols:
print ord(y)
print "========"
codes = [ord(x) for x in symbols]
print codes
def list_comprehension_same_value():
x = "ABC"
xlist = [x for x in 'ABC']
print "x: %s, which SHOULD be ABC, python3.x NOT repo" % x
print "l:%s" % xlist
def list_comprehension_vs_map_filter():
beyond_ascii_1 = [ord(x) for x in symbols if ord(x) > 40]
print beyond_ascii_1
beyond_ascii_2 = filter(lambda c: c > 40, map(ord, symbols))
print beyond_ascii_2
def list_comprehension_cartesian_product():
colors = "black white".split()
sizes = "S M X".split()
t_shirts = [(color, size) for color in colors for size in sizes] # same as for & for
print t_shirts
t_shirts = [(color, size) for size in sizes for color in colors]
print t_shirts
def list_comprehension_generator():
print (ord(s) for s in symbols)
print [ord(s) for s in symbols]
print tuple(ord(s) for s in symbols)
import array
print array.array('I', (ord(s) for s in symbols))
def test():
# list_comprehension()
# list_comprehension_same_value()
# list_comprehension_vs_map_filter()
# list_comprehension_cartesian_product()
list_comprehension_generator()
if __name__ == '__main__':
test()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.