blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
88e1e334294b1fb980b199274859ffe363a236ca | Kane610/hassio | /appdaemon/apps/media/tv.py | 2,785 | 3.546875 | 4 | from base import Base
import datetime
import time
from typing import Tuple, Union
"""
This app implements the basic functionality for tv/remote/media_player automations
Following use-cases:
- Turn on TV when I start playing on my media player
it automatically pauses for an amount of time to give the TV
a chance to turn on and then play again
- Turn off tv if media_player been idle or off for an amout of time
(I only have chromecast on this TV but if you use it to watch live TV the use-case makes no sense)
"""
class Tv(Base):
def initialize(self) -> None:
"""Initialize."""
super().initialize()
self._remote = self.args.get('remote', str)
self._media_player = self.args.get('media_player', str)
self._delay_before_turn_off_tv = int(self.properties.get('delay_before_turn_off_tv', 20))*60
self.listen_state(
self.__on_media_player_play,
entity=self._media_player,
new='playing'
)
# Both states idle and
self.listen_state(
self.__on_media_player_idle_or_off,
entity=self._media_player,
new='idle',
duration=self._delay_before_turn_off_tv
)
self.listen_state(
self.__on_media_player_idle_or_off,
entity=self._media_player,
new='off',
duration=self._delay_before_turn_off_tv
)
def __on_media_player_idle_or_off(
self, entity: Union[str, dict], attribute: str, old: dict,
new: dict, kwargs: dict) -> None:
"""called when media player changes state to 'idle' or 'off'"""
#Turn off tv when been idle or off for an amout of time
self.__turn_off_tv()
def __on_media_player_play(
self, entity: Union[str, dict], attribute: str, old: dict,
new: dict, kwargs: dict) -> None:
"""called when media player changes state to 'playing'"""
if self.get_state(entity=self._remote) == 'on':
return #already on, nothing to do
# first pause media player to let the TV get som time to turn on
self.__pause()
# turn on tv
self.__turn_on_tv()
# wait 10 seconds and play again
self.run_in(self.__delay_play, 10)
def __pause(self)->None:
self.call_service('media_player/media_pause', entity_id=self._media_player)
def __delay_play(self, kwargs: dict)->None:
self.__play()
def __play(self)->None:
self.call_service('media_player/media_play', entity_id=self._media_player)
def __turn_on_tv(self)->None:
self.turn_on(entity_id=self._remote)
def __turn_off_tv(self)->None:
self.turn_off(entity_id=self._remote) |
4e911005717ce696d825aea9afc6c5974fb3437a | YP4US/PythonBasics | /if statment/if.py | 98 | 3.875 | 4 | x=5
y=6
z=7
if x<y:
print("x is less than y")
if x<y<z:
print("x and y are less than z") |
6395807a2b1a5a5eab87cb8f0e9e4d788796e815 | PatiKoszi/FirstStepsPython | /sortowanieBabelkowe.py | 320 | 3.84375 | 4 | def sortowanieBabelkowe(lista):
for i in range(len(lista)):
for j in range(len(lista)-1):
if lista[j] > lista[j+1]:
swap(lista, j, j+1)
print(lista)
def swap(lista, a, b):
lista[a], lista[b] = lista[b], lista[a]
lista = [6,1,5,8,-5,-2,0]
sortowanieBabelkowe(lista) |
b8223e559d226b426a3eb75adff92a8320a9a804 | xenron/sandbox-github-clone | /xcv58/LeetCode/Populating-Next-Right-Pointers-in-Each-Node/Solution.py | 678 | 3.921875 | 4 | # Definition for a binary tree node
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
# self.next = None
class Solution:
# @param root, a tree node
# @return nothing
def connect(self, root):
while root is not None:
anchor = root
while anchor is not None:
if anchor.left is not None:
anchor.left.next = anchor.right
if anchor.next is None:
break
anchor.right.next = anchor.next.left
anchor = anchor.next
root = root.left;
|
be5de42630e6722ab916175ac0a45b293b9ac5cf | ziamajr/CS5590PythonLabAssignment | /CS5590 Lesson 2 Assignment/Task 2/Task 2.py | 749 | 4.125 | 4 | #David Ziama - ClassID #3
#Task 2: - Write a Python program to check if a string contains all letters of the alphabet
#June 22, 2017
#Print out description of program with a space
print("This program will check if a string contains all letters of the alphabet")
print("\n")
#Ask user to enter their string
usr_str = (input("Please enter your string to be evaluated: "))
#compare the user's string to letter of the alphabet using is alpha
#isalpha() is used to return true if all characters in the string are alphabetic and there is at least one character, false otherwise.
if usr_str.isalpha():
print("Your string contains all letters of the alphabet")
else:
print("Your string does not contain all letters of the alphabet")
|
735ec5addf56051d3c4c0026e627d14c5963ffc9 | Kristjan-O-Ragnarsson/RamCard | /Main.py | 1,179 | 3.765625 | 4 | """
Guðmundur
main class
24/4/2017
"""
from Functions import *
from Game import Game
from Player import Player
from CardSplitter import CardSplitter
class Main:
"""Main Class"""
@staticmethod
def main():
"""Main Function"""
player_count = intinput("Sláðu inn hversu margir leikmenn eru", 1, 12) + 1
players = []
card_splitter = CardSplitter(player_count)
card_count = 0
for i in range(player_count - 1):
name = input("Sláðu inn nafn leikmanns " + str(i + 1) + ": ")
cards = card_splitter.get_random_cards()
card_count += len(cards)
players.append(Player(name, cards))
ai_cards = card_splitter.get_random_cards()
card_count += len(ai_cards)
players.append(Player("Tölva", ai_cards))
players[len(players) - 1].ai = True
game = Game(players)
game.card_count = card_count
while True:
game.loop()
if game.restart_game:
debug("restarting")
return
if __name__ == '__main__':
while True:
Main.main()
|
4fa86acaa5856420d689940b1cacea56e8548be0 | vincentiusmartin/teacup | /draft/old stuff/add_kmer.py | 1,962 | 3.609375 | 4 | # This script adds kmer features to the existing data
import pandas as pd
NEW_DATA_PATH = "../data/generated/training_kmer.csv"
DATA_PATH = "../data/generated/training.csv"
def get_seq(data):
'''
This function returns the list of sequences from the data
in a numpy array
Input: input data as a dataframe
Output: DNA sequences in the data in a numpy array
'''
return data["sequence"].values
def get_kmer(num, seq):
'''
Number of distinct k-mer in the sequence
Input: num, seq where num = k and seq is the sequence
to be evaluated
Output: len(kmer_set) which is the number of distinct k-mers
in the sequence
'''
# initialize an empty set
kmer_set = set()
# initialize index i to 0
i = 0
# iterate through the sequence
while i + num < len(seq):
# get the read of length num
read = seq[i:i+num]
# add this read to the set
kmer_set.add(read)
# increment index
i += 1
# return number of elements in the set
return len(kmer_set)
def get_col(num, seq_col):
# initialize an empty list to store the output
output = []
# iterate through each sequence in the data
for seq in seq_col:
# append the number of distinct k-mer in the sequence
# to the output list
output.append(get_kmer(num, seq))
# return the output
return output
def add_col(df, num, col):
'''
This function inserts the new column into the dataframe
Input:
Output: df which is the updated dataframe
'''
# set the new column's name
col_name = "num_" + str(num) +"mer"
# insert the new column's name in the dataframe
df.insert(df.shape[1] - 1, col_name, col)
# return the updated dataframe
return df
if __name__ == "__main__":
k = [1,2,3]
# get the data
df = pd.read_csv(DATA_PATH)
# get the list of sequences
seq = get_seq(df)
# add columns for the kmers
for num in k:
print("now doing kmer number", num)
new_col = get_col(num, seq)
df = add_col(df, num, new_col)
# export to a new file
df.to_csv(NEW_DATA_PATH)
|
2a4f4ec7bc304431a52738978e21618c2817d845 | jsoendermann/project-euler-python | /004.py | 254 | 3.53125 | 4 | def is_palindrome_number(n):
s = str(n)
return s == s[::-1]
maximum = 0
for i in range(999, 0, -1):
for j in range(999, 0, -1):
if is_palindrome_number(i*j):
if i*j > maximum:
maximum = i*j
print(maximum)
|
e244ba3681b230eb8ac7f8c3308b735dec45e697 | alpharol/algorithm_python3 | /leetcode/0301-0400/0367.有效的完全平方数.py | 906 | 3.5 | 4 | #https://leetcode-cn.com/problems/valid-perfect-square/solution/xun-huan-mi-yun-suan-by-loulan/
"""
给定一个正整数 num,编写一个函数,如果 num 是一个完全平方数,则返回 True,否则返回 False。
说明:不要使用任何内置的库函数,如 sqrt。
示例 1:输入:16;输出:True
示例 2:输入:14;输出:False
"""
class Solution:
def isPerfectSquare(self, num: int):
l,r = 0,num
if num == 0 or num == 1:
return True
while l < r:
mid = (l+r)//2
tmp = mid*mid
if tmp < num:
l = mid+1
elif tmp == num:
return True
else:
r = mid
return False
if __name__ == "__main__":
num = 1
solution = Solution()
result = solution.isPerfectSquare(num)
print(result) |
ba34967bc31f469c66d0806029a832801462c5e7 | kamilhabrych/python-semestr5-lista5 | /zad5_1.py | 188 | 3.59375 | 4 | l = [3,'alfa',2.71,'kot']
l[0] = 4
l[3] = 'pies'
print(l)
l2 = l
print()
print(l)
print(l2)
l2[0] = 98
print()
print(l)
print(l2)
l3=l.copy()
l3[0] = 24
print()
print(l)
print(l3) |
0a33a9e902fb037ea7721c90ee608f835f5323c0 | ioxnr/homework | /hw7/3.py | 1,060 | 3.734375 | 4 | class Cell:
def __init__(self, amount):
self.amount = amount
def __str__(self):
return f'Результат операции равен {self.amount}'
def __add__(self, other):
return Cell(self.amount + other.amount)
def __sub__(self, other):
if self.amount - other.amount > 0:
return Cell(self.amount - other.amount)
else:
return 'Разность количества ячеек двух клеток должна быть больше нуля'
def __mul__(self, other):
return Cell(self.amount * other.amount)
def __truediv__(self, other):
return Cell(round(self.amount / other.amount))
def make_order(self, amount_in_row):
row = ''
for i in range(int(self.amount / amount_in_row)):
row += '*' * amount_in_row + '\n'
row += '*' * (self.amount % amount_in_row)
return row
c = Cell(56)
b = Cell(20)
print(c + b)
print(c - b)
print(c * b)
print(c / b)
print(c.make_order(6))
print(b.make_order(5))
|
577147731328ed439abf97fb3f6ce3ffc88cba14 | Aasthaengg/IBMdataset | /Python_codes/p03711/s554784788.py | 198 | 3.578125 | 4 | group = [[1, 3, 5, 7, 8, 10, 12], [4, 6, 9, 11], [2]]
x, y = map(int, input().split())
for i in range(3):
if x in group[i] and y in group[i]:
print("Yes")
exit()
print("No") |
2717e1fb2eb46a911493ff83a148ef4db00588a9 | pk5280/Python | /hr_TowerBreaker.py | 259 | 3.546875 | 4 | def towerBreakers(n, m):
if m==1:
return 2
else:
return 2 if n%2==0 else 1
if __name__ == '__main__':
n = 3
m = 2
print(n,m)
print(towerBreakers(n, m))
n = 4
m = 5
print(n,m)
print(towerBreakers(n, m)) |
256ea1085b68045f3a053362f63834ef4b21dded | Robson-55/Blockchain-python | /block.py | 734 | 3.546875 | 4 | # Generates the class Block
from datetime import datetime
from hashlib import sha256
class Block:
def __init__(self,transactions,previous_hash,nonce=0):
self.timestamp=datetime.now()
self.transactions=transactions
self.previous_hash=previous_hash
self.nonce=nonce
self.hash=self.generate_hash()
def print_block(self):
#print block contents
print("timestamp:",self.timestamp)
print("transactions:",self.transactions)
print("current hash:",self.generate_hash())
def generate_hash(self):
#hash the block contents
block_contents=str(self.timestamp)+str(self.transactions)+str(self.previous_hash)+str(self.nonce)
block_hash=sha256(block_contents.encode())
return block_hash.hexdigest()
|
3a453d70adcceeda368bce5ba5ba01319d139a4a | vasketo/EOI | /Python/Día 5/funciónvalidaremail.py | 506 | 4.1875 | 4 | #!/usr/bin/env python
# -*- encoding: utf-8 -*-
# Solicitar al usuario que ingrese su dirección email. Imprimir un mensaje indicando si la dirección es válida o no,
# valiéndose de una función para decidirlo. Una dirección se considerará válida si contiene el símbolo "@".
def validar(email):
if "@" in email:
return True
else:
return False
direccion = input("Tu email: ")
if validar(direccion):
print("Dirección válida")
else:
print("Dirección inválida") |
daa7e4c1bb5a40626ae1f1efe21171468340e6c9 | python-practices/py-practices | /string_examples.py | 559 | 4.3125 | 4 |
# string with parameter example
print("My name is %s and weight is %d\n" % ("John", 27))
para_str = """this is a long string that is made up of
several lines and non-printable characters such as
TAB ( \t ) and they will show up that way when displayed.
NEWLINEs within the string, whether explicitly given like
this within the brackets [ \n ], or just a NEWLINE within
the variable assignment will also show up.
"""
print(para_str)
print("c:\\nowhere")
print(r"c:\\nowhere")
print("\n")
print("Hello, World!")
print(u"Hello, World!") |
f097b482de173204aea8afd4e7f5615baee17a8f | yasserhussain1110/grokking-algo-solutions | /Chapter4/max.py | 189 | 3.828125 | 4 | def maximum(arr):
if len(arr) == 0:
return None
elif len(arr) == 1:
return arr[0]
else:
return max(arr[0], maximum(arr[1:]))
print(maximum([1,2,7,3]))
|
9c69019d96de765d16748a4d3a3eb144edc4cb0a | Lucas-Garciia/FATEC-MECATRONICA-LUCAS-GARCIA-0001 | /LTP1-2020-2/pratica13/prog02.py | 260 | 4 | 4 | no1 = int(input("informe um valor"))
no2 = int(input("informe outro valor"))
print("soma", no1+no2)
print("produto:", no1*no2)
print("divisao:", no1/no2)
print("divisao inteira:", no1//no2)
print("resto da divisao:", no1%no2)
print("potenciação:",no1**no2)
|
d8f100c9b9a9addefddf4b044560d3d18948d89c | VHSCODE/PracticePython-Exercises | /exercise5.py | 258 | 3.9375 | 4 | a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
def duplicate(list1,list2):
lista= []
for i in list1:
if i in list2:
lista.append(i)
print(lista)
duplicate(a, b)
|
a22f71233e8b8ba668ef584ce19030879dfa6a56 | zervas/ekf_test | /scripts/sampling.py | 1,850 | 3.671875 | 4 | import math
import numpy as np
import scipy.stats
import timeit
import matplotlib.pyplot as plt
def sample_normal_twelve(mu, sigma):
""" Sample from a normal distribution using 12 uniform samples;
"""
# Return sample from N(0, sigma)
x = 0.5 * np.sum(np.random.uniform(-sigma, sigma, 12))
return mu + x
def sample_normal_rejection(mu, sigma):
"""Sample from a normal distribution using rejection sampling.
See lecture on probabilistic motion models slide 25 for details.
"""
# Length of interval from wich samples are drawn
interval = 5*sigma
# Maximum value of the pdf of the desired normal distribution
max_density = scipy.stats.norm(mu,sigma).pdf(mu)
# Rejection loop
while True:
x = np.random.uniform(mu - interval, mu + interval, 1)[0]
y = np.random.uniform(0, max_density, 1)
if y <= scipy.stats.norm(mu, sigma).pdf(x):
break
return x
def sample_normal_boxmuller(mu, sigma):
"""Sample from a normal distribution using Box-Muller method.
See exercise sheet on sampling and motion models.
"""
# Two uniform random variables
u = np.random.uniform(0, 1, 2)
# Box-Muller formula returns sample from STANDARD normal distribution
x = math.cos(2*np.pi*u[0])
def evaluate_sampling(mu, sigma, n_samples):
n_bins = 100
samples = []
for i in range (n_samples):
samples.append(sample_normal_twelve(mu, sigma))
plt.figure()
count, bins, ignored = plt.hist(samples, n_bins, density=True)
plt.plot(bins, scipy.stats.norm(mu, sigma).pdf(bins), linewidth=2, color='r')
plt.xlim([mu - 5*sigma, mu + 5*sigma])
plt.title("12 samples")
def main():
sample = sample_normal_twelve(0, 1)
print(sample)
evaluate_sampling(0, 1, 1000)
plt.show()
if __name__ == '__main__':
main() |
2980ff0789fe973af4f1d6559be3ff7181ba00db | Franciscwb/EstudosPython | /Cursoemvideosexercicios/obter limite.py | 1,203 | 4.09375 | 4 | '''
print('Esta é a Loja Saint Grail.')
print('Seja Bem-Vindo!')
print('Aqui quem fala é o vendedor Francis de Almeida')
print('Faremos uma análise de crédito.Para tal, digite o seguintes dados')
'''
from datetime import date
data_de_hoje = date.today
def linha():
print('=' * 30)
def obter_limite():
if obter_limite:
linha()
cargo_atual = str('Analista')
salario_atual = int(1000)
ano_nascimento = int(1984)
data_de_hoje = (data_de_hoje - ano_nascimento)
limite_gasto = (salario_atual * (idade_aproximada / 1000) + 100)
linha()
print('Cargo: {}'.format(cargo_atual))
print('Salário: {}'.format(salario_atual))
print('Ano de nascimento: {}'.format(ano_nascimento))
print('Idade aproximada: {}'.format(ano_nascimento - data_de_hoje))
linha()
obter_limite()
'''
print('Muito Obrigado pelas informações. \nconforme o que foi preenchido seus dados são estes a seguir ')
print('O seu salário atual é: R${:.2f} '.format(salario))
print('Idade aproximada é: {}'.format(idade - anoNascimento))
print('Você tem um limite de gasto de: R${} '.format(limiteGasto))
'''
|
5c060c006b12c3dd01bd47863f66ca2d0cc79e81 | Neil-Opena/CSE337-Scripting | /CSE373/hw4.py | 7,430 | 3.515625 | 4 | import sys
import math
import queue
import cProfile
import re
class EdgeNode():
def __init__(self, y, next_edge=None):
self.y = y
self.next = next_edge
def __str__(self):
return str(self.y)
class Graph():
def __init__(self):
self.num_vertices = 0
self.num_edges = 0
self.adjacency_list = []
self.degree_list = []
self.finished = False
self.setup_completed = False
self.ordered_vertices = []
self.min_degree = 0
self.max_degree = 0
self.lower_bound = 0
self.heuristic = []
self.solution = []
self.solution_length = 0
def read_graph(self, file_name):
f = open(file_name)
self.num_vertices = int(f.readline().strip()) # first line = number of vertices
self.num_edges = int(f.readline().strip()) # second line = number of edges
self.adjacency_list = [None]*self.num_vertices
self.degree_list = [0]*self.num_vertices
for edge_line in f:
edge = edge_line.strip().split()
x = int(edge[0])
y = int(edge[1])
self.insert_edge(x, y, False)
self.solution_length = self.num_vertices
self.ordered_vertices = [i[0] + 1 for i in sorted(enumerate(self.degree_list), key = lambda x:x[1])]
self.min_degree = self.degree_list[self.ordered_vertices[0] - 1]
self.max_degree = self.degree_list[self.ordered_vertices[-1] - 1]
self.lower_bound = math.ceil(self.max_degree / 2)
bfs_list = []
for i in range(0, self.num_vertices):
bfs_list.append(self.bfs(self.ordered_vertices[i]))
# perform bfs with each vertex
for i in range(0, self.num_vertices):
if(len(bfs_list[i]) != self.num_vertices):
# if permutation does not contain all the vertices
# go through the other bfs and add it
for j in range(0, self.num_vertices):
bfs_list[i] += [x for x in bfs_list[j] if x not in bfs_list[i]]
if(len(bfs_list[i]) == self.num_vertices):
break
bfs_list.sort(key = lambda x : self.get_bandwidth(x, self.num_vertices))
self.heuristic = bfs_list[0]
f.close()
def insert_edge(self, x, y, is_directed):
edge_node = EdgeNode(y, self.adjacency_list[x - 1])
self.adjacency_list[x - 1] = edge_node
self.degree_list[x - 1] += 1
if(is_directed == False):
self.insert_edge(y, x, True)
def bfs(self, start):
q = queue.Queue()
discovered = set()
discovered.add(start)
q.put(start)
result = []
while(not q.empty()):
v = q.get()
result.append(v)
edge = self.adjacency_list[v - 1]
while(edge != None):
y = edge.y
if(y not in discovered):
q.put(y)
discovered.add(y)
edge = edge.next
return result
def solve_bandwidth(self):
a = [-1]*self.num_vertices #solution list
k = 0
self.finished = False
self.permute_vertices(a, k)
print(self.solution, "->", self.solution_length)
def permute_vertices(self, a, k):
if(k == len(a)): # if the length of the solution list == the number of vertices, print the permutation
self.setup_completed = True
self.check_permutation(a)
else:
k += 1
candidates = []
self.generate_candidates(a, k, candidates)
for i in range(0, len(candidates)):
a[k - 1] = candidates[i]
if(self.continue_from_prune(a,k)):
self.permute_vertices(a, k)
if(self.finished):
return
a[k-1] = -1
def continue_from_prune(self, a, k):
if(self.get_bandwidth(a,k) < self.solution_length): # check if edges in the graph are higher than lower bound already
return True
print(a, "bandwidth=", self.get_bandwidth(a,k))
return False
def get_bandwidth(self, a, k):
max_length = 0
for i in range(0, k):
# for each vertex in the solution vector, get the bandwidth
v = a[i]
edge = self.adjacency_list[v - 1]
while(edge != None):
temp_length = 0
for j in range(0, k):
if(a[j] == edge.y):
temp_length = j - i
break
if(temp_length != 0 and temp_length > max_length):
max_length = temp_length
if(max_length >= self.solution_length):
return max_length # no need to look at other edges
edge = edge.next
return max_length
def generate_candidates(self, a, k, c):
# get numbers not in the array yet
if(not self.setup_completed):
for i in range(self.heuristic[k - 1], self.num_vertices + 1): # go through possible vertices
found = False
if(i not in a):
c.append(i)
else:
for i in range(1, self.num_vertices + 1): # go through possible vertices
found = False
if(i not in a):
if(k - 1 > self.solution_length + 1):
v = a[k - 1 - self.solution_length - 1]
edge = self.adjacency_list[v - 1]
has_edge = False
while(edge != None):
if(edge.y == i):
has_edge = True
break;
edge = edge.next
if(not has_edge):
c.append(i)
else:
c.append(i)
def check_permutation(self, a):
# go through the vertices
max_length = 0
for i in range(0, self.num_vertices):
edge = self.adjacency_list[i]
while(edge != None):
# get distance from vertex (i + 1) and edge in permutation
if(i+1 < edge.y): # only check half
start = -1
end = -1
for j in range(0, len(a)):
if(a[j] == (i + 1)):
start = j
if(a[j] == edge.y):
end = j
temp_length = abs(end - start)
if(temp_length > max_length):
max_length = temp_length
if(max_length >= self.solution_length):
print(a, "=>", max_length)
return
edge = edge.next
if(max_length < self.solution_length):
self.solution_length = max_length
self.solution = list(a)
if(max_length <= self.lower_bound): # if it hits the lower bound, stop
self.finished = True
print(a, "=>", max_length)
# find the longest edge based on permutation
file_name = sys.argv[1]
graph = Graph()
graph.read_graph(file_name)
cProfile.run('graph.solve_bandwidth()')
|
68ab5b1ccd97f552cb00907b722104d685c7c6f0 | kazamari/CodeAbbey | /014_modular-calculator.py | 1,214 | 3.90625 | 4 | '''
Input data will have:
initial integer number in the first line;
one or more lines describing operations, in form sign value where sign is either + or * and value is an integer;
last line in the same form, but with sign % instead and number by which the result should be divided to get the
remainder.
Answer should give remainder of the result of all operations applied sequentially (starting with initial number)
divided by the last number.
If you have troubles with this problem, please feel free to type its name in the "Search" box in the top menu and find
relevant topics at our forum - probably you will get enough enlightenment from there.
Example:
input data:
5
+ 3
* 7
+ 10
* 2
* 3
+ 1
% 11
answer:
1
In this case result after all operations applied sequentially is 397.
All numbers will not exceed 10000 (though intermediate results could be very large).
'''
import sys
n = 0
for i, line in enumerate(sys.stdin):
line = line.rstrip()
if i == 0:
n = int(line)
else:
op, num = line.split()
if op == '+':
n += int(num)
elif op == '*':
n *= int(num)
elif op == '%':
n %= int(num)
print(n)
|
1be3e29d90253023efb410921ecc0a2414861bf8 | Ras-al-Ghul/RSA-Python-Implementation | /primegeneration.py | 2,260 | 3.546875 | 4 | #To generate random primes in the range CONST_MIN to CONST_MAX
#The generated primes are 8 digits in length here because max value of message string for
#CONST_BYTE=4 is 1874160
import random
CONST_MIN=21272296
CONST_MAX=23242658
def rand_prime():
if CONST_MIN%2==0:
CONST_MINSS=CONST_MIN+1
else:
CONST_MINSS=CONST_MIN
while True:
p = random.randrange(CONST_MINSS, CONST_MAX,2)
if ((p-1) % 6)!=0 and ((p+1)%6)!=0:
continue
if all(p % n != 0 for n in range(3, int(p**0.5)+1,2)):
return p
else:
continue
p=rand_prime()
q=rand_prime()
#p to be greater than q
if p < q:
p,q=q,p
print "\nThe primes are ",p," ",q,"\n"
#Calculate modulus and totient
def calculatetotient(a,b):
n=a*b
totient=(a-1)*(b-1)
return n,totient
modulus,totient=calculatetotient(p,q)
print "The modulus and totient are ",modulus," ",totient,"\n"
CONST_MIN=65537
CONST_MAX=100000
def gcd(a, b):
while b != 0:
(a, b) = (b, a%b)
return a
newkey=65537
while True:
if gcd(totient,newkey)!=1:
newkey=rand_prime
continue
else:
break
print "The default public encryption key is 65537 (FOR FAST ENCRYPTION). \nDo you still want to change it?(Y/N)"
choice=raw_input()
#Also have to check that GCD of Totient and Encryption key is 1 else have to recalculate key
if choice == 'y' or choice == 'Y':
while True:
print "Is this acceptable?(Y/N)"
while True:
newkey=rand_prime()
if gcd(totient,newkey) != 1:
continue
else:
break
print newkey
choice=raw_input()
if choice == 'y' or choice == 'Y':
break
else:
continue
ekey=newkey
print "\nThe public encryption key is (e,n) ",ekey,modulus,"\n"
#Calculate Decryption key
def calcdkey(x,y):
temp=x
oldolds=1
olds=0
oldoldt=0
oldt=1
while (y!=0):
q,r=divmod(x,y)
x=y
y=r
s=oldolds-(q*olds)
t=oldoldt-(q*oldt)
oldolds=olds
oldoldt=oldt
olds=s
oldt=t
return oldoldt+temp
dkey=calcdkey(totient,ekey)
print "The private decryption key is (d,n) ",dkey,modulus,"\n"
print "The private decryption key is (d%totient,n) ",dkey%totient,modulus,"\n"
print "The dkey can be d or d%totient but d%totient is faster because it might be smaller\n"
print "Paste the relevant data wherever necessary"
|
7d7e67bacba0e9cd7d754c6feb9d760541b549c2 | Waseem6409/PIAIC | /Sum of digits in integer.py | 1,166 | 4.09375 | 4 | while True:
while True:
try:
num1 = int(input('\nInput integer:'))
except ValueError:
print("\nPlease enter only number")
else:
break
sum=0
while num1>0:
l_dig=num1%10
sum +=l_dig
num1=num1//10
print("\nThe sum of digits of given integer is",sum)
while True:
Repeat=input("\nDo you want to calculate again?\n\nYes or No:")
Repeat=Repeat.lower()
if Repeat not in ["yes","y","no","n"]:
print("\nPlease select correct option")
else:
break
if Repeat in ["yes","y"]:
continue
else:
if Repeat in ["no","n"]:
print("\n-----Thank you for using-----")
input()
break |
b084823d0a8eb92c6a48bc620983d7f664d5c6b0 | dgibbs11a2b/Module-8-Lab-Activity | /Problem2SumofTen.py | 906 | 4.4375 | 4 | #----------------------------------------
#David Gibbs
#March 8, 2020
#
#This program contains a function which takes two inputs
#from the user, calculates the sum, and then prints to
#the screen whether the value is less than, greater than,
#or equal to 10.
#----------------------------------------
x = int(input("Enter your first number?: "))
y = int(input("Enter your first number?: "))
def sum(x, y):
return x + y
#Sets the definition of x and y and returns x + y in order to get the sum
if sum(x,y) > 10:
print("The sum of the two given numbers is:",sum(x,y),"and this number is greater than 10")
elif sum(x,y) < 10:
print("The sum of the two given numbers is:",sum(x,y),"and this number is less than 10")
elif sum(x,y) == 10:
print("The sum of the two given numbers is:",sum(x,y),"and this number is equal to 10")
else:
print("I'm sorry, I cannot help you!")
|
9930ee3aab489a8a2fdd8a33a259b3cba271496e | tobereborn/python-recipes | /lng/itertools_groupby.py | 209 | 3.828125 | 4 | # -*- coding: utf-8 -*-
import itertools
def main():
for key, group in itertools.groupby('AaaBbaaaaaBcCaAA', lambda c: c.upper()):
print(key, list(group))
if __name__ == '__main__':
main()
|
cd26603b55a95255fdfa45d978059f640b1754a0 | traciarms/techcrunch | /articles.py | 6,660 | 3.65625 | 4 | import csv
import re
import bs4
import requests
class TechCrunchScraper:
"""
This is the main class used to scrape posts from the TechCrunch website.
It will execute several methods. The process includes:
1. Get all links for articles
2. For each post, scrape its content to look for business that is the
main subject of the post
3. Write the data gathered from the post to a .csv file
"""
def __init__(self, filename, header):
"""
Initialize the Scraper with the out filename and the csv header, or
format of the csv file.
:param filename:
:param header:
"""
self.out_filename = filename
self.csv_header = header
self.request_header = {'User-agent': 'Mozilla/5.0 (Windows NT '
'6.2; WOW64) AppleWebKit/'
'537.36 (KHTML, like '
'Gecko) Chrome/37.0.2062.'
'120 Safari/537.36'}
def get_soup(self, url):
"""
Make a GET request to a URL and return the soup.
:param url:
:returns: requests' response -> soup.
"""
response = requests.get(url, headers=self.request_header)
soup = bs4.BeautifulSoup(response.content, "html.parser")
return soup
@staticmethod
def get_article_links(soup):
"""
Get the article links for this page. There are a few different
article link attributes, so I will first grab all the <li> tags on
the page and then filter out for the article links that I want.
:param soup:
:return: a list of links to the articles on this page.
"""
links = []
li_s = soup.find_all('li')
for li in li_s:
if li.get('data-permalink'):
links.append((li.get('data-permalink')))
else:
link = li.find_next('a')
if link:
if li.find_next('a').get('data-omni-sm') and \
re.search(r'gbl_river_headline',
li.find_next('a').get('data-omni-sm')) and \
re.search(r'techcrunch\.com',
link.get('href'), re.IGNORECASE):
links.append((li.find_next('a').get('href')))
return links
@staticmethod
def scrape_article(soup, url):
"""
This method will scrape the contents of the article, specifically
looking for the Organization name that is the main topic of the article.
It returns the data for the business and the article.
:param soup:
:param url:
:return: business and article data
"""
data = {}
article_title = soup.find('h1',
attrs={
'class': 'alpha tweet-title'}).get_text()
data['article title'] = article_title
data['article url'] = url
crunch_base = soup.find('ul', attrs={'class': 'crunchbase-accordion'})
# if the crunch base info is present
if crunch_base:
cbs = crunch_base.find_all('li')
# find all the crunch base entries
for cb in cbs:
a = cb.find_next('a')
href = cb.get('data-crunchbase-url')
if href:
# if the entity in the crunchbase is an organization
# get the info
if re.search(r'organization', href):
data['company name'] = a.get_text().strip()
key = ''
key_node = crunch_base
# look for the website info
while key != 'Website' and key_node is not None:
if key_node:
key_node = \
key_node.find_next('strong',
attrs={'class': 'key'})
if key_node:
key = key_node.get_text()
if key_node:
website = \
key_node.find_next('span',
attrs={'class': 'value'}).\
find_next('a').get_text()
data['company website'] = website
break
# if we could not determine the company name or website enter
# n/a in the data
if 'company name' not in data:
data['company name'] = 'n/a'
if 'company website' not in data:
data['company website'] = 'n/a'
return data
def write_to_csv(self, data):
"""
This method takes the data returned from the article and writes it out
to a csv file.
:param data:
:return: None
"""
f_data = []
for row in data:
row_data = []
for header in self.csv_header:
row_data.append(row[header])
f_data.append(row_data)
with open(self.out_filename, 'w') as fp:
a = csv.writer(fp)
a.writerow(self.csv_header)
a.writerows(f_data)
def run(self, url):
"""
This method will first get a list of article links at the given url.
It will then get the soup for each link in the list and then call
the scraper with the given soup and link.
** Note ** I decided not to visit subsequent pages to get their links.
However, if this was needed, after the links are gathered for each page
(and scraped) I would then check for pagination and then iterate over
the subsequent pages - gather links on each page and scrape the
subsequent articles.
:param url:
:return: None
"""
soup = self.get_soup(url)
links = self.get_article_links(soup)
data_set = []
for link in links:
soup = self.get_soup(link)
data = self.scrape_article(soup, link)
data_set.append(data)
self.write_to_csv(data_set)
if __name__ == '__main__':
csv_header = ["article title",
"article url",
"company name",
"company website"]
csv_out = 'articles.csv'
s = TechCrunchScraper(csv_out, csv_header)
s.run('https://techcrunch.com/')
|
b4c7d14ba03ec17f6f97483da98e16ea34ce7a49 | UCDPA-derekbaker/digital_marketing | /data_analytics_for_marketing.py | 1,259 | 3.546875 | 4 | # This is a sample Python script.
# Press Shift+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.
def print_hi(name):
# Use a breakpoint in the code line below to debug your script.
print(f'Hi, {name}') # Press Ctrl+F8 to toggle the breakpoint.
# Press the green button in the gutter to run the script.
if __name__ == '__main__':
print_hi('PyCharm')
# See PyCharm help at https://www.jetbrains.com/help/pycharm/
# Print the head of the homelessness data
print(homelessness.head())
# Print information about homelessness
print(homelessness.info())
# Print the shape of homelessness
print(homelessness.shape)
# Print a description of homelessness
print(homelessness.describe())
###############################################
# Import pandas using the alias pd
#install packages pandas as pd
# Print the values of homelessness
print(homelessness.values)
# Print the column index of homelessness
print(homelessness.columns)
# Print the row index of homelessness
print(homelessness.index)
# Sort homelessness by individual
homelessness_ind = homelessness.sort_values("individuals")
# Print the top few rows
print(homelessness_ind.head()) |
d7eb9d03a61024c1456f36b74b6b78fddcb06ebe | VinogradovAU/myproject | /algoritm/less-2/less_2_task_5.py | 1,309 | 3.921875 | 4 | # https://app.diagrams.net/?lightbox=1&highlight=0000ff&edit=_blank&layers=1&nav=1&page-id=D4vCSPD4o9B4h8Km3Lkl&title=lesson_2#Uhttps%3A%2F%2Fdrive.google.com%2Fuc%3Fid%3D1oqjejCmAcK220vNU4lrkN6D77-34MiOX%26export%3Ddownload
# 8. Посчитать, сколько раз встречается определенная цифра в введенной последовательности чисел.
# Количество вводимых чисел и цифра, которую необходимо посчитать, задаются вводом с клавиатуры.
def sum_sum(i, x):
s = 0
while True:
if (i % 10 == x):
s = s + 1
i = i // 10
if(i==0):
break
return s
a = int(input('Введите количество чисел: '))
x = int(input('Введите цифру от 0 до 9 для поиска: '))
sum = 0 # тут будет лежать количество найденных цифр
count = 1 # переменная для счетчика
while True:
if (count > a):
print(f'цифра {x} встречается {sum} раз.')
break
i = int(input(f'Введите {count} число (всего {a} чисел): '))
z = sum_sum(i, x)
sum = sum + z
count = count + 1
|
8a3d454a32d2dc78cd2c990ede67df5e295a1487 | vipulthakur07/Assignment3 | /frequency of object.py | 140 | 3.6875 | 4 | a=["apple","banana","orange","apple","apple","hello","banana"]
b=input("enter the object : ")
print(b," ","occurs"," ",a.count(b)," times")
|
f3a948440876594267b2fecff3e5a89e283a17b0 | almetzler/Corona-cation | /APIStuff.py | 4,135 | 3.671875 | 4 | '''
Game Plan:
1) Make a list of Countries
2) Get the date of their first case
3) Get Date of 50th case
4) find number of days between 1 and 100
5) put in all in a csv on github
list of (country name , days from day 1 to day 50)
6) maybe also create a json file of day by day number of cases
{country name:[(day,case),(day,case)...]}
Functions to make:
1) Count days
Turn date into quantifiable thing
maybe just have an iterator that starts at day 1 stops when cases == 50
2) Fetch data from API
3) Write to database
4) Functions to grab from past projects/homeworks
setUpDatabase HW8
main kinda everywhere
write_csv Project 2
'''
# AND SO IT BEGINS
# Get some imports, never sure what you might need
import os
import requests
import json
import re
import csv
# Task 1: Get a list of country names
def get_country_names():
country_list = []
resp = requests.get('https://api.covid19api.com/countries')
data = json.loads(resp.text)
for country in data:
country_list.append(country['Country'])
return country_list
# Task 2: create dictionary of country:tuple list of (day,case) pairs
def get_days():
country_dic={}
lst = get_country_names()
for country in lst:
count=0
day_tups = []
url = f'https://api.covid19api.com/dayone/country/{country}/status/confirmed'
resp = requests.get(url)
data = json.loads(resp.text)
if data == {"message":"Not Found"}:
continue
start = True
for day in data:
if start:
date = day['Date']
total=0
start=False
newdate = day['Date']
if newdate == date:
total += int(day['Cases'])
else:
day_tups.append((count,total))
total = int(day['Cases'])
count+=1
date=newdate
#some countries are also split into counties so I have to do something about that
country_dic[country] = day_tups
return country_dic
# Task 2.1 rewrite task 2 so that I can later call the function on a country and get the tuple list
def country_days(country):
count=0
day_tups = []
url = f'https://api.covid19api.com/dayone/country/{country}/status/confirmed'
resp = requests.get(url)
data = json.loads(resp.text)
if data == {"message":"Not Found"}:
print(f'data not found for {country}')
return None
start = True
for day in data:
if start:
date = day['Date']
total=0
start=False
newdate = day['Date']
if newdate == date:
total += int(day['Cases'])
else:
day_tups.append((count,total))
total = int(day['Cases'])
count+=1
date=newdate
return day_tups
# Task 3: Get days from 1 reported case to 50
def days_to_100(country):
count=0
tups = country_days(country)
if tups == None:
return None
for day in tups:
if day[1] >100:
return count
count+=1
return None
# Task 3: Write a csv of (country name, days to 50)
def write_csv(filename):
full_path = os.path.join(os.path.dirname(__file__), filename)
fle = open(full_path,'w')
fle.write('country,days to 50')
data = get_country_names()
for country in data:
country = country.split(',')[0]
if days_to_100(country) == None:
continue
fle.write(f'\n{country},{days_to_100(country)}')
fle.close()
# Task 4: Dump json sting of dictionaty of day:tuples
def write_json(filename):
full_path = os.path.join(os.path.dirname(__file__), filename)
fle = open(full_path,'w')
fle.write(json.dumps(get_days()))
def main():
#print(get_country_names()[:5])
#print(get_days()['India'])
#print(country_days("China"))
#print(days_to_50('United states of america'))
write_csv('daysto100.csv')
write_json('countrydata.json')
print('done')
if __name__ == "__main__":
main() |
35524c364f5767ba1121f8e7601280fac3366c7f | sjNT/checkio | /Elementary/Three Words.py | 1,255 | 4.21875 | 4 | """
Давайте научим наших роботов отличать слова от чисел.
Дана строка со словами и числами, разделенными пробелами (один пробел между словами и/или числами).
Слова состоят только из букв. Вам нужно проверить есть ли в исходной строке три слова подряд.
Для примера, в строке "start 5 one two three 7 end" есть три слова подряд.
"""
def checkio(words: str) -> bool:
if '111' in ''.join(str(i) for i in [1 if i.isalpha()else 0 for i in words.split(' ')]):
return True
return False
# These "asserts" using only for self-checking and not necessary for auto-testing
if __name__ == '__main__':
print('Example:')
print(checkio("Hello World hello"))
assert checkio("Hello World hello") == True, "Hello"
assert checkio("He is 123 man") == False, "123 man"
assert checkio("1 2 3 4") == False, "Digits"
assert checkio("bla bla bla bla") == True, "Bla Bla"
assert checkio("Hi") == False, "Hi"
print("Coding complete? Click 'Check' to review your tests and earn cool rewards!") |
8f6f3e5b83f7be512d2437d0bdfccb87d79d7fae | leandro-matos/python-scripts | /aula01/ex4.py | 419 | 3.578125 | 4 | text = input('Digite algo: ')
print('')
print(f'O tipo primitivo desse valor é: {type(text)}')
print(f'Tem espaços ? {text.isspace()}')
print(f'É númerico ? {text.isnumeric()}')
print(f'É alfabético ? {text.isalpha()}')
print(f'É alfanumérico ? {text.isalnum()}')
print(f'Está em maiúsculas? {text.isupper()}')
print(f'Está em minúsculas ? {text.islower()}')
print(f'Está capitalizada ? {text.istitle()}')
|
9a78f0305a97ace517e5f51c60d35beb4922b72b | kirkwood-cis-121-17/exercises | /chapter-7/ex_7_2.py | 658 | 4.5 | 4 | # Programming Exercise 7-2
#
# Program to display a list of random integers.
# This program takes no input,
# it loops through a list of integers and exchanges them for random integers,
# then displays the list on a single line.
# to use the random functions, import the random module
# Define the main function
# Initialize a list of integers.
# loop through the list
# assigning a random integer to each member of the list
# loop through the list
# display the current value
# add a comma and space, unless this is the last value
# Call the main function.
|
a3b4e30c0d20af6b09bead85ee3385b1057a010c | chengtianle1997/algs4_princeton | /2.3 Quick Sort/QuickSelect.py | 533 | 3.71875 | 4 | import random
class UnitTest():
def GenerateRandArray(self, n, min, max):
arr = []
arr = [random.randint(min, max) for x in range(n)]
return arr
def isSorted(self, alist):
for i in range(len(alist) - 1):
if alist[i] > alist[i + 1]:
return False
return True
class QuickSort():
def Sort(alist):
n = len(alist)
lo, hi = 0, n - 1
random.shuffle(alist)
__Sort(alist, lo, hi)
def __Sort(alist, lo, hi):
|
659b6131f6d5427585165149109ee41951bfa97f | Anupsingh1587/Basic-of-Python | /Dictionary_CH11.py | 913 | 4.09375 | 4 | # Dictionary is a collection which is unordered , changeable and indexed. NO duplicate numbers.
# Dictionaries are written in the curly brackets and they have key and values
#Exercise 1
dict={"Brand":"Ford","Model":"Mustang","Year":"1964"}
x=dict["Model"]
y=dict["Brand"]
z=dict["Year"]
print(x)
print(y)
print(z)
#Or
'''d={"Brand":"Ford","Model":"Mustang","Year":"1964"}
z=d
z=(input("Enter the Name: "))
print("Name is : ", z)'''
d={"Anup":9654644865,"Puja":7325730239,"mom":9654892306}
print(d) #print the key and value together
print(d["Anup"]) #print the value of anup
d["papa"]=9432146789 #Too add the value papa in dictionary
print(d)
del d["papa"]# Too delete the value of papa from d
print(d)
d={"Anup":9654644865,"Puja":7325730239,"Mom":9654892306}
for key in d:
print("key:", key, "Value:", d[key])
d.clear()
print(d)
|
f718af2f91794ff491ed4b12620439011f9160f8 | schoentr/data-structures-and-algorithms | /code-challanges/401/queue_with_stacks/stacks_and_queues.py | 970 | 4.03125 | 4 | class Queue():
front = None
rear = None
def enqueue(self,value):
node = Node(value)
if not self.front:
self.front = node
self.rear = node
else:
self.rear._next= node
self.rear = node
def dequeue(self):
self.front = self.front._next
def peek(self):
return self.front.value
class Stack():
# _list = LinkedList()
top = None
def push(self, value):
node = Node(value)
node._next = self.top
self.top = node
def pop (self):
value = self.top.value
self.top = self.top._next
return value
def peek(self):
return self.top.value
class Node():
def __init__(self, value):
"""Creates all nodes for the list
Arguments:
value -- [Any value you want to be held in the node]
"""
self.value = value
self._next = None |
2a7422dff14b4fb11b8d88ba9c87ce67fd3a325e | DDao19/python_nov_2017 | /alexis_Moreno/python_fundamentals/stringsList.py | 729 | 4.15625 | 4 | # #######find and replace############
# words = "It's thanksgiving day. It's my birthday, too!"
# print words.find("day"),'-',words.replace("day","month",1)
# ######## MIN and MAX numberes##########
# x= [2,54,-2,7,12,98]
# print 'this is the highest num in list x :', max(x)
# print 'this is the lowest num:', min(x)
# #########first and last###########
# x = ["Hello",23,45,17,"World"]
# firstLast=[x[0],x[len(x)-1]]
# print firstLast
# ####### New list##################
# x = [19,2,54,-2,7,12,98,32,10,-3,6,45,67,87,23,45,90,1]
# x.sort()
# newList=[x[:len(x)/2]]
# for i in range(len(x)/2,len(x)):
# newList.append(x[i])
# print "The Sorted List ---> :", x
# print "The first half is added to index 0 :", newList
|
4ce24d109727157b0e8c6ed46a4481b6c1340cd9 | RenegaDe1288/pythonProject | /lesson25/mission6.py | 5,455 | 3.75 | 4 | import random
class House:
day = 1
money = 100
fridge = 50
cat_eat = 30
dirt = 0
spend_moneu = 0
def dirt_day(self):
self.dirt += 5
def __str__(self):
print(
'\n\tДенег: {}, Еды: {}, Кошачьей еды: {}, Грязь: {}'.format(self.money, self.fridge, self.cat_eat,
self.dirt))
class Person:
def __init__(self):
self.hunger = 500
self.happy = 100
def eat(self):
callories = random.randint(0, 30)
if house.fridge >= callories:
self.hunger += callories
house.fridge -= callories
print(self.name, 'Поел')
else:
print('Холодильник пустой')
def cost(self):
self.hunger -= 10
def petting_cat(self):
self.cost()
self.happy += 5
print("Погладил кота")
def check_person(self):
if self.hunger <= 0:
print('Человек {} умер от голода'.format(self.name))
return False
elif self.happy <= 0:
print('Человек {} умер от депрессии'.format(self.name))
return False
else:
return True
def check_dirt(self):
if house.dirt > 90:
self.happy -= 10
def __str__(self):
print('\nЖитель {} , Голод {}, Счастье {}'.format(self.name, self.hunger, self.happy))
class Man(Person):
def __init__(self):
super().__init__()
self.name = 'Misha'
def work(self):
self.cost()
house.money += 150
print('Заработал 150')
def play(self):
self.cost()
self.happy += 20
print('Поиграл')
def begin(self):
self.__str__()
if self.check_person():
# answer = int(input('Введите действие: 1 - еда, 2 - деньги, 3, поиграть, 4 - погладить кота '))
answer = random.randint(1, 4)
self.check_dirt()
if answer == 1:
self.eat()
elif answer == 2:
self.work()
elif answer == 3:
self.play()
elif answer == 4:
self.petting_cat()
else:
print('Ошибка ввода')
class Women(Person):
fur = 0
def __init__(self):
super().__init__()
self.name = 'Anna'
def buy_fur(self):
self.cost()
if house.money > 350:
house.money -= 350
self.happy += 60
house.spend_moneu += 350
self.fur += 1
print('Куплена шуба')
else:
print("Денег на шубу не хватило")
def clear(self):
self.cost()
if house.dirt > 0:
house.dirt = 0
print("Дом убран")
else:
print('Дом и так чист!')
def buy(self):
self.cost()
foodstuff = random.randint(20, 50)
house.money -= foodstuff
house.fridge += foodstuff
house.cat_eat += 10
house.spend_moneu += foodstuff
print('Куплена еда')
def begin(self):
self.__str__()
if self.check_person():
# answer = int(input('\nВведите действие: 1 - еда, 2 - шуба, 3, продукты, 4 - погладить кота, 5 - убраться '))
answer = random.randint(1, 6)
self.check_dirt()
if answer == 1:
self.eat()
elif answer == 2:
self.buy_fur()
elif answer == 3:
self.buy()
elif answer == 4:
self.petting_cat()
elif answer == 5:
self.clear()
class Cat:
hunger = 300
name = 'Vaska'
def check_hunger(self):
if self.hunger <= 0:
print('Кот умер')
return False
return True
def eat(self):
callories = random.randint(0, 10)
if house.cat_eat >= callories:
self.hunger += callories * 2
house.cat_eat -= callories
print('Кот поел')
else:
print('Кошачьей еды не хватает')
def tear_up_wallpaper(self):
house.dirt += 5
self.hunger -= 10
def sleep(self):
self.hunger -= 10
def begin(self):
self.__str__()
if self.check_hunger():
# answer = int(input('\nВведите действие: 1 - еда, 2 - обои, 3- спать '))
answer = random.randint(1, 4)
if answer == 1:
self.eat()
elif answer == 2:
self.tear_up_wallpaper()
elif answer == 3:
self.sleep()
husband = Man()
wife = Women()
cat = Cat()
house = House()
while all([husband.check_person(), wife.check_person(),cat.check_hunger()]):
print('\n\tДень: ', house.day)
house.__str__()
husband.begin()
wife.begin()
cat.begin()
house.dirt_day()
house.day += 1
print('\n\tВсего прожито: {} дней, потрачено денег {} , и куплено шуб {}'.format(house.day, house.spend_moneu, wife.fur))
|
0f20b42f6ab8fd4d12ee303afd0dbd5c6cb6aa09 | garvitsaxena06/Python-learning | /11.py | 91 | 4.15625 | 4 | #to find absolute value of a number
num = int(input("Enter the number: "))
print(abs(num))
|
78d17b02b678712553df5a3024cb299adbe207f8 | BIAOXYZ/variousCodes | /_CodeTopics/LeetCode/201-400/000382/000382_impl_newlib_like_official.py3 | 879 | 3.640625 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
import random
class Solution:
def __init__(self, head: Optional[ListNode]):
self.arr = []
while head:
self.arr.append(head.val)
head = head.next
def getRandom(self) -> int:
# 这个基本就是官方答案的写法,主要是为了记录下 random 包里的这个函数。
return random.choice(self.arr)
# Your Solution object will be instantiated and called as such:
# obj = Solution(head)
# param_1 = obj.getRandom()
"""
https://leetcode-cn.com/submissions/detail/258871353/
执行用时:52 ms, 在所有 Python3 提交中击败了100.00%的用户
内存消耗:17.7 MB, 在所有 Python3 提交中击败了8.85%的用户
通过测试用例:
8 / 8
"""
|
d4d837fdaf08be5b27da098dec6c8b3f52fe455f | DemecosChambers/PythonNotes | /input function for your name.py | 183 | 4.0625 | 4 | fnam = input ("May I have your first name, please?")
Inam = input ("May I have your last name, please?")
print ("Thank you.")
print ("Your name is:" "" + Inam + "" + fnam + ".") |
52b98aa6b313686e843debf34be320048168057d | sambreen27/nyu_cff_python | /bmimetric.py | 151 | 4.0625 | 4 | #Name: Saba Ambreen
#Lesson 3.3: BMI Metric
kg = float(input())
height = float(input())
BMI = (kg/(height * height))
print("bmi is: {:.10f}".format(BMI))
|
c038ec5c820c5e298e8d7d02bf761a21017e402d | bobowang2017/python_study | /matplotlib/example03.py | 567 | 3.578125 | 4 | # coding: utf-8
import matplotlib.pyplot as plt
from matplotlib import animation
x = [i for i in range(1, 10)]
y = list(map(lambda s: pow(s, 2), x))
data = [x, y]
im = plt.imshow(data, cmap='gray')
def animate(i):
data = [[s + i for s in x], [s + i for s in y]]
im.set_array(data)
print(data)
plt.plot(data[0], data[1])
return [im]
fig = plt.figure(figsize=(10, 6))
# plt.figure(figsize=(10, 6))
# plt.plot(x, y)
# plt.xlim(1, 20)
# plt.ylim(1, 100)
anim = animation.FuncAnimation(fig, animate, frames=20, interval=60, blit=True)
plt.show()
|
45d26c91a615352c745f00fbcaf032d1c3ae1947 | ZhaobinMo/COMS-W4995-Applied-ML | /HW1/task1/fib.py | 261 | 3.734375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Feb 2 17:52:22 2019
@author: Zhaobin
"""
def fib(n):
"""return the result of the Fibonacci sequence
"""
f_n_1 = 0
f_n = 1
for i in range(n):
f_n, f_n_1 = f_n_1, f_n+f_n_1
return f_n_1 |
6394d23a7fa4560254ea0855cfd7ba438c270f18 | supercoding1126/money-counter | /finished-project-money-counter.py | 663 | 4.1875 | 4 | # Money conting machine
# By SuperCoding
# Python 3.8.5
# Mac os
name = input('\n\n\n\nWhat do you want to buy: ') # Ask them what they want to buy
num = int(input("How many do you want to buy: ")) # Ask them how much
cost = int(input('How much does it cost: ')) # Ask them how much it cost
tax = 0.14975 # Tax number in Canada
totalnotax = num*cost # Total that the tax is not included
taxplustotal = ((total * (1 + tax)) - total # Tax
totalplustax = totalnotax + aaa # Total plus tax
print('Tax: ',taxplustotal,'$') # Tell them tax number
print('Object cost: ',totalnotax,'$') # Tell them object cost
print('Total: ',totalplustax,'$') # Tell them the total
|
a8b6146fa4a95c98d05ef07bbafcb959beb359f5 | ShahzaibSE/Learn-Python | /FileSystem_ClassWork/writeFile.py | 553 | 3.90625 | 4 | #Writing to a files.
# with open('files/myFile.txt','w') as file_object:
# file_object.write("I love programming\n");
# file_object.write("I really love programming\n");
# # content = file_object.readable()
# # print("Files Content");
# # print(content);
#Opening a file in both read & write mode.
with open('files/myFile.txt','r+') as file_object:
file_object.write("I love programming\n");
file_object.write("I really love programming\n");
content = file_object.read()
print("Files Content");
print(content);
|
db4ce0179b3ed8c7de80c25c72f9ddcc5281cad2 | arav02/tasklist_week1 | /ginortS.py | 362 | 3.765625 | 4 | s=input()
lower=[]
upper=[]
odd=[]
even=[]
a=sorted(s)
for i in a:
if i.islower():
lower.append(i)
elif i.isupper():
upper.append(i)
elif int(i)%2!=0:
odd.append(i)
else:
even.append(i)
lower=''.join(lower)
upper=''.join(upper)
odd=''.join(odd)
even=''.join(even)
print(lower+upper+odd+even)
|
524f07aa4ab3299a002cea641e058fb333b0527c | boosungkim/Snake4d | /src/keybuf.py | 1,639 | 3.90625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun May 31 21:40:41 2020
@author: maurop
"""
#==============================================================================
# Key buffer
#==============================================================================
class KeyBuffer:
'''
Key Buffer
is a simple buffer that keeps track of the key pressed while playing
it makes a more fluid control of the snake when the game lags.
Methods:
__init__
push_key
get_key
clear
Instance variables:
self.buf -- a simple list doing the job of a LIFO stack
self.key_to_dir -- transforms the key in directions
'''
def __init__(self):
'''
class is initialised with a buffer, and a dictionary that will
convert the keys to directions
'''
self.buf = []
# construct the dictionary that changes the snake direction
self.key_to_dir = {}
bind_key = ["w", "s", "a", "d", "i", "k", "j", "l"]
possible_dirs = ["UP", "DOWN", "LEFT", "RIGHT", "FW", "RW", "IN", "OUT"]
for direction, key in zip(possible_dirs, bind_key):
self.key_to_dir[key] = direction
def push_key(self, key):
'''
insert the key in the buffer
Keyword arguments:
key -- can be any character
'''
self.buf.append(key)
def get_key(self):
'''gets the next key, if none is found returns None'''
if self.buf:
return self.key_to_dir[self.buf.pop(0)]
else:
return None
def clear(self):
'''Just empties the buffer'''
self.buf = [] |
da8bfbcdc542f4d7e7db2dd19fadb826ad8a75ec | TristonStuart/IMail-Python-Version- | /IMail [Python]/mailRoom.py | 2,581 | 3.96875 | 4 | import socket
import sys
print("This is the Console")
print("Commands start with '/' type '/tutorial' to get started :)")
print(' ')
sender = "DEFAULT"
def command():
consoleInput = input()
if consoleInput == '/help':
print(' > Help Menue <');
print(' >> /tutorial : Gives a tutorial for using commands')
print(' >> /send [message] : Sends a message')
print(' >> /sender [sender id] : Sets what the sender feild will be in a message (required) ')
print(' >> /mail [new ; all ; read ; del] [file]: Prints list of new mail, all mail, prints text of a message, or deletes a message')
print(' ')
command()
elif consoleInput == '/sender':
newInput = input("-Please enter the name for your sender id : ")
global sender
sender = newInput
print(" > Sender Id Set As : " + sender + " <")
print(' ')
command()
elif consoleInput == '/tutorial':
print(' ')
print(' -- IMail Commands Tutorial --')
print(' Commands Like /sender have attributes fields displayed in the help fiels as [attribute]. ')
print(' These options will appear after you type the command ')
print(' ')
print(' Example : ')
print(' You want to set your sender id as "Friend" ')
print(' You would type "/sender", it will then ask you for what you want the attribute (in this case your id) to be.')
print(' This will work with any commands containing attributes "[attribute]" ')
print(' ')
print(' All commands start with "/" , but attributes do not.')
print(' ')
print(' Find list of all commands and there attributes by typing "/help" ')
print(' ')
command()
elif consoleInput == '/send':
msgInput = input("-Please enter your message : ")
ntwInput = input("-Please enter the network to recieve the message : ")
HOST, PORT = ntwInput, 350
data = [msgInput, ' [/-split-\] ' , sender]
dataStr = ''.join(data)
# Create a socket (SOCK_STREAM means a TCP socket)
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
# Connect to server and send data
sock.connect((HOST, PORT))
sock.sendall(bytes(dataStr, "utf-8"))
print("Sent: {}".format(data))
print(' ')
command()
else:
print(" > Unknown Command :( <")
print(' ')
command()
command()
|
64ced267a31391a0f0e9cf22aeb3197941c4556b | mergederg/deuterium | /game/gamesrc/objects/deuterium/ships/ship.py | 2,620 | 3.78125 | 4 | """
Root class for ships. Everything inheriting from this (and you should inherit from this rather than @create them
directly) will have the properties and behaviors outlined below.
Basic Rooms:
When each ship is constructed, its at_object_creation makes certain Rooms (ev.Room) -- a Cargo Bay (which is where
cargo gets loaded to, people board, etc -- conceptually the first room in from 'outside'), and a cockpit (where all
the magic of ship controls happens.
Ships contain a special exit, airlock, that is connected to the outside world. One end gets dynamically reconnected
whenever the ship lands somewhere.
"""
import uuid
from ev import Object, create_object, Room, Exit
class Ship(Object):
"""
Base ship class. These should generally not be constructed on their own, but inherited from within subclasses in
your own implementation of Cochran (see above).
"""
def at_object_creation(self):
self.db.desc = "An unadorned vessel. You shouldn't see this unless something has gone horribly wrong."
self.db.transponder_id = uuid.uuid1()
self.db.entry_password = '1235'
# Create the bridge and cargo bay.
self.bridge = create_object(Room, key="Bridge")
self.cargo_bay = create_object(Room, key="Cargo Bay")
# Link with exits.
self.bridge_entrance = create_object(Exit, key="Out")
self.bridge_exit = create_object(Exit, key="Bridge")
# Bridge -> Cargo Bay
self.db.bridge_exit_ref = self.bridge_exit.dbref
self.bridge_exit.location = self.bridge
self.bridge_exit.destination = self.cargo_bay
# Cargo Bay -> Bridge
self.db.bridge_entrance_ref = self.bridge_entrance.dbref
self.bridge_entrance.location = self.cargo_bay
self.bridge_entrance.destination = self.bridge
# And do the same with an airlock, on the inside of the cargo bay and the outside of the ship.
self.airlock_out = create_object(Exit, key="Airlock Out")
self.airlock_in = create_object(Exit, key="Airlock In")
self.db.airlock_in_ref = self.airlock_in.dbref
self.db.airlock_out_ref = self.airlock_out.dbref
self.db.cargo_ref = self.cargo_bay.dbref
self.db.bridge_ref = self.bridge.dbref
#Link airlock exits to wherever the ship is being built.
self.airlock_out.location = self.cargo_bay
self.airlock_out.destination = self.location
self.airlock_in.location = self.location
self.airlock_in.destination = self.cargo_bay
# TODO: State changing methods, for use by scripts and such. |
89d0e248a140ac61806a741921372617af31a96f | InbarStrull/CL--Substitution-Cipher-Decryption | /permutation.py | 2,329 | 3.71875 | 4 | import random
import math
import language_model
class Permutation:
def __init__(self, perm):
self.perm = perm # dictionary, perm[ord(char[i])] = ord(char[j])
# replace char[i] with char[j]
self.chars = [i for i in self.perm] # Sigma
def get_chars(self):
return self.chars
def get_perm(self):
return self.perm
def get_neighbor(self):
"""returns a random neighbor of the
current permutation instance.
a neighbor of a permutation is defined
as a new permutation that simply replaces
the mapping of two randomly chosen
characters from Σ.
uses the choice method from the random module."""
choose_from = self.get_chars() # all characters
char1 = random.choice(choose_from) # choose character randomly
char2 = random.choice(choose_from) # choose another character randomly
val1 = self.get_perm()[char1]
val2 = self.get_perm()[char2]
my_perm = self.get_perm().copy() # new permutation
my_perm[char1], my_perm[char2] = val2, val1 # swap
new_perm = Permutation(my_perm) # new instance
return new_perm
def translate(self, string):
"""receives an input string,
and returns the translation of
that string according to the
current permutation instance."""
translated = string.translate(self.get_perm())
return translated
def get_energy(self, encrypted, model):
"""receives a data argument (= encrypted message)
and a language model, and returns the
energy of the current permutation"""
n = len(encrypted) # length of the encrypted message
trans = self.translate(encrypted) # translate the message according to the permutation map
uni = model.unigram_probs
big = model.bigram_probs
energy = -math.log(uni[trans[0]], 2) # compute energy as required:
for i in range(1,n-1):
energy -= math.log(big[(trans[i],trans[i+1])], 2)
return energy
def __repr__(self):
return str(self.perm)
|
cbd51438d27178c0f4ae6a2e8a0041b46cf15397 | Daniiarz/python07.01 | /lesson7/lesson7.py | 876 | 3.734375 | 4 | # for i in range(10):
# if i == 5:
# continue
# print(i)
# def a_div_b(a, b):
# for i in range(33333333333333333333333333333333):
# if i == 5:
# print(i)
# print("До break")
# break
#
# return a / b
#
#
# print(a_div_b(2, 2))
#
#
def take_students(num):
l = []
for i in range(num):
student = input()
if student == "Daniiar":
return "Teacher can't be student"
l.append(student)
return l
print(take_students(3))
def take_students(num):
l = []
for i in range(num):
student = input()
if student == "Daniiar":
raise ValueError("Teacher can't be student")
l.append(student)
return l
try:
students = take_students(3)
except ValueError:
students = []
for i in students:
print(f"Student is {i}")
|
20e8c4d541bd08828598d720adc21d5d70cb22f0 | SimeonTsvetanov/Coding-Lessons | /SoftUni Lessons/Python Development/Python Advanced January 2020/Python OOP/19. TESTING/02. Test Cat.py | 1,809 | 4.25 | 4 | import unittest
# For testing remove or comment the class CAT:
class Cat:
def __init__(self, name):
self.name = name
self.fed = False
self.sleepy = False
self.size = 0
def eat(self):
if self.fed:
raise Exception('Already fed.')
self.fed = True
self.sleepy = True
self.size += 1
def sleep(self):
if not self.fed:
raise Exception('Cannot sleep while hungry')
self.sleepy = False
class CatTests(unittest.TestCase):
def setUp(self):
self.cat = Cat(name="Tom")
def test_if_cat_size_is_increased_after_eating(self):
"""Cat's size is increased after eating"""
self.cat.eat()
self.assertEqual(self.cat.size, 1)
def test_if_car_is_fed_after_eating(self):
"""Cat is fed after eating"""
self.cat.eat()
self.assertTrue(self.cat.fed)
def test_eat_when_already_fed_should_raise_error(self):
"""Cat cannot eat if already fed, raises an error"""
with self.assertRaises(Exception) as context:
self.cat.eat()
self.cat.eat()
self.assertEqual('Already fed.', str(context.exception))
def test_cannot_fall_asleep_if_not_fed_raises_an_error(self):
"""Cat cannot fall asleep if not fed, raises an error"""
with self.assertRaises(Exception) as context:
self.cat.sleep()
self.assertEqual('Cannot sleep while hungry', str(context.exception))
def test_if_not_sleepy_after_sleeping(self):
"""Cat is not sleepy after sleeping"""
self.cat.eat()
self.cat.sleep()
self.assertFalse(self.cat.sleepy)
if __name__ == '__main__':
unittest.main()
|
bb29bc2726124b86a033c1eb062343562ecdf862 | openstate/datasets | /government_domain_names/create_list.py | 6,710 | 3.765625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import csv, codecs, cStringIO
import json
import re
class UTF8Recoder:
"""
Iterator that reads an encoded stream and reencodes the input to UTF-8
"""
def __init__(self, f, encoding):
self.reader = codecs.getreader(encoding)(f)
def __iter__(self):
return self
def next(self):
return self.reader.next().encode("utf-8")
class UnicodeReader:
"""
A CSV reader which will iterate over lines in the CSV file "f",
which is encoded in the given encoding.
"""
def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds):
f = UTF8Recoder(f, encoding)
self.reader = csv.reader(f, dialect=dialect, **kwds)
def next(self):
row = self.reader.next()
return [unicode(s, "utf-8") for s in row]
def __iter__(self):
return self
class UnicodeWriter:
"""
A CSV writer which will write rows to CSV file "f",
which is encoded in the given encoding.
"""
def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds):
# Redirect output to a queue
self.queue = cStringIO.StringIO()
self.writer = csv.writer(self.queue, dialect=dialect, **kwds)
self.stream = f
self.encoder = codecs.getincrementalencoder(encoding)()
def writerow(self, row):
self.writer.writerow([s.encode("utf-8") for s in row])
# Fetch UTF-8 output from the queue ...
data = self.queue.getvalue()
data = data.decode("utf-8")
# ... and reencode it into the target encoding
data = self.encoder.encode(data)
# write to the target stream
self.stream.write(data)
# empty queue
self.queue.truncate(0)
def writerows(self, rows):
for row in rows:
self.writerow(row)
# For csv's specify delimiter, encoding and the column containing the domains
filenames = [
'Rijksoverheid.csv',
'Provincies.csv',
'Gemeenten.csv',
'Waterschappen.csv',
'Gemeenschappelijke-Regelingen.csv'
]
# Mapping for 2012-2017 ministerie names
#rijksoverheid_mapping = {
# 'AR': u'Algemene Rekenkamer',
# 'AZ': u'Ministerie van Algemene Zaken',
# 'BUZA': u'Ministerie van Buitenlandse Zaken',
# 'BZK': u'Ministerie van Binnenlandse Zaken',
# 'DEF': u'Ministerie van Defensie',
# 'EK': u'Eerste Kamer',
# 'EZ': u'Ministerie van Economische Zaken',
# 'FIN': u'Ministerie van Financiën',
# 'HRvA': u'Hoge Raad van Adel',
# 'IenM': u'Ministerie van Infrastructuur en Milieu',
# 'Inspectieraad': u'Inspectieraad',
# 'NO': u'Nationale Ombudsman',
# 'NVAO': u'Nederlands-Vlaamse Accreditatieorganisatie',
# 'OCW': u'Ministerie van Onderwijs, Cultuur en Wetenschap',
# 'RvS': u'Raad van State',
# 'SZW': u'Ministerie van Sociale Zaken en Werkgelegenheid',
# 'TK': u'Tweede Kamer',
# 'VenJ': u'Ministerie van Veiligheid en Justitie',
# 'VWS': u'Ministerie van Volksgezondheid, Welzijn en Sport'
#}
# Mapping for 2017-now ministerie names
rijksoverheid_mapping = {
'AR': u'Algemene Rekenkamer',
'AZ': u'Ministerie van Algemene Zaken',
'BUZA': u'Ministerie van Buitenlandse Zaken',
'BZK': u'Ministerie van Binnenlandse Zaken',
'CAOP': u'Centrum voor Arbeidsverhoudingen Overheidspersoneel',
'CBS': u'Centraal Bureau voor de Statistiek',
'DEF': u'Ministerie van Defensie',
'DKH': u'Dienst van het Koninklijk Huis',
'EK': u'Eerste Kamer',
'EK/TK': u'Eerste Kamer/Tweede Kamer',
'EZK': u'Ministerie van Economische Zaken en Klimaat',
'FIN': u'Ministerie van Financiën',
'HRvA': u'Hoge Raad van Adel',
'KdNO': u'Kanselarij der Nederlandse Orden',
'KvdK': u'Kabinet van de Koning',
'LNV': u'Ministerie van Landbouw, Natuur en Voedselkwaliteit',
'ICTU': u'ICTU (ICT-Uitvoeringsorganisatie)',
'IenW': u'Ministerie van Infrastructuur en Waterstaat',
'Inspectieraad': u'Inspectieraad',
'NO': u'Nationale Ombudsman',
'NVAO': u'Nederlands-Vlaamse Accreditatieorganisatie',
'OCW': u'Ministerie van Onderwijs, Cultuur en Wetenschap',
'RvS': u'Raad van State',
'SZW': u'Ministerie van Sociale Zaken en Werkgelegenheid',
'TK': u'Tweede Kamer',
'JenV': u'Ministerie van Justitie en Veiligheid ',
'VWS': u'Ministerie van Volksgezondheid, Welzijn en Sport'
}
# Cleanup for ugly gemeenschappelijke regelingen data
remove = [
'niet aanwezig',
'niet',
'nvt',
'N.v.t.',
'N.v.t',
'geen',
'-',
'---',
'0',
'De Callenburgh 2\n5701 PA\nHelmond'
]
remove_i = [x.upper() for x in remove]
all_domains = []
known_domains = []
def extract_csv(filename):
domains = []
with open(filename) as IN:
domain_type = filename.split('.')[0].replace('-', ' ')
reader = UnicodeReader(IN)
for row in reader:
# Skip empty rows
if row:
domain = []
# Strip whitespace (and some ugly ']"' stuff found in
# gemeenschappelijke regelingen data)
url = row[0].strip().strip(']"').strip().rstrip('.')
# Remove more ugly stuff gemeenschappelijke regelingen
# data
if url.upper() in remove_i:
continue
if url:
# Remove scheme
path = re.sub('https?://', '', url)
# Remove path
subdomain_name = re.sub('/.*', '', path)
# Remove www
domain_name = re.sub(
r'^www\.(.*\..*)', r'\1', subdomain_name
)
if domain_name in known_domains:
continue
domain.append(domain_name)
known_domains.append(domain_name)
else:
continue
if len(row) == 2 and row[1]:
if filename == 'Rijksoverheid.csv':
domain.append('Rijksoverheid')
domain.append(rijksoverheid_mapping[row[1]])
else:
# Add it twice as both the 'Domain Type' and 'Agency'
# columns are currently the same
domain.append(domain_type)
domain.append(domain_type)
domains.append(domain)
return domains
for filename in filenames:
all_domains += extract_csv(filename)
with open('domains.csv', 'w') as OUT:
writer = UnicodeWriter(OUT)
writer.writerow(['Domain Name', 'Domain Type', 'Agency'])
writer.writerows(all_domains)
|
b8dbcd3781cd4ec7fbb806d9424829b61fe29acd | bluescheung/Pypractice | /dir.py | 140 | 3.5 | 4 | #!usr/bin/env python3
import os
def dir():
L= [ x for x in os.listdir('.') if os.path.isdir(x)]
for i in L:
print i
dir()
|
d213da6205c664bd8bae2167dcab64fcb29837a9 | magedu-pythons/python-19 | /P19054-yangxingxing/week6#7/practice/sample_sort3.py | 1,001 | 3.546875 | 4 | # 重复练习
import random
limit = 30
list1 = [0] * limit
for i in range(limit):
list1[i] = random.randint(1, 50)
print(list1)
print()
# 简单选择排序
#for i in range(limit-1):
# max_index = i
# for y in range(i+1, limit):
# if list1[y] > list1[max_index]:
# max_index = y
# if max_index != i:
# list1[i], list1[max_index] = list1[max_index], list1[i]
#print(list1)
# 简单二元选择排序
for i in range(limit // 2):
max_index = i
min_index = i
for y in range(i+1, limit-i):
if list1[y] > list1[max_index]:
max_index = y
elif list1[y] < list1[min_index]:
min_index = y
if min_index == max_index:
break
if max_index != i:
list1[i], list1[max_index] = list1[max_index], list1[i]
if min_index == i:
min_index = max_index
if min_index != -i-1:
list1[-i-1], list1[min_index] = list1[min_index], list1[-i-1]
print(list1)
print()
print(list1)
|
c3ad6404b8fedbb0e382d903f89d0d675d21495d | daniel-reich/ubiquitous-fiesta | /u3kiw2gTY3S3ngJqo_20.py | 98 | 3.71875 | 4 |
def superheroes(heroes):
return sorted([i for i in heroes if "man" in i and "oman" not in i])
|
4bb29914f965e55dfbc0cebfb8ff32949e0913df | maximillianus/python-scripts | /py-sqlite/createdb.py | 2,006 | 3.796875 | 4 | import sqlite3
DBNAME = 'example.db'
def create_conn(dbname):
try:
conn = sqlite3.connect(dbname)
cur = conn.cursor()
return conn, cur
except sqlite3.Error as e:
print('SQLite3 Error connecting to db: %s' % e)
return False, False
except Exception as e:
print('Other Error connecting to db: %s' % e)
return False, False
def create_table(tablename, cur, conn):
query = """
CREATE TABLE {table}
(date text, transaction text, stockname text, qty real, price real)
"""
try:
cur.execute(query.format(tablename))
conn.commit()
print('Success creating table!')
except sqlite3.Error as e:
print('Error during create table: %s' % e)
def insert_to_table(tablename, data, cur, conn):
"""
tablename: string
data: list of tuples/rows
"""
assert isinstance(tablename, str), "tablename is not string!"
assert isinstance(data, list), "data is not list!"
print(data)
query = """
INSERT INTO {table} VALUES (?, ?, ?, ?, ?)
"""
try:
cur.executemany(query.format(table=tablename), data)
conn.commit()
print('Success inserting batch data!')
except sqlite3.Error as e:
print('Error during insert: %s' % e)
def retrieve_data(tablename, cur, conn, query = ''):
if query == '':
query = """
SELECT * FROM {table}
"""
try:
res = cur.execute(query.format(table=tablename))
res = res.fetchall()
conn.commit()
return res
except sqlite3.Error as e:
print('Error retrieving data: %s' % e)
def truncate_table(tablename, cur, conn):
query = """
DELETE FROM {table}
"""
try:
print(query.format(table=tablename))
cur.execute(query.format(table=tablename))
conn.commit()
print('Success truncating table!')
except sqlite3.Error as e:
print('Error during truncating table: %s' % e)
|
92b0bc4fff4fa908d830d95166916d07822cba48 | aditiagrawal30/Python | /bubble_sort.py | 625 | 4.28125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Jul 30 11:10:40 2020
@author: Aditi Agrawal
"""
def bubble_sort(nums):
# Set swapped to True so the loop looks run atleast once
swapped = True
while swapped:
swapped = False
for i in range(len(nums)-1):
if nums[i]>nums[i+1]:
# Swapping the elements if condition is satisfied
nums[i],nums[i+1] = nums[i+1],nums[i]
swapped = True
n = int(input("How many numbers you want to enter: "))
nums = []
for i in range(n):
nums.append(int(input()))
bubble_sort(nums)
print(nums) |
0fc66c2cd01b763621e358450b52df3b24fff9d5 | waffle-iron/MITx-6.00.1x-Introduction-to-Computer-Science-and-Programming-Using-Python | /week1/ProblemSet1/Problem Set 1.py | 921 | 3.71875 | 4 | # Problem 1
s = 'dgrgaxwupkxokiolhai'
num_vowels = 0
for letter in s:
if letter == 'a' or letter == 'e' or letter == 'i' or letter == 'o' or letter == 'u':
num_vowels += 1
print(num_vowels)
# Problem 2
s = 'azcbobobegghaklbokbob'
num_bobs = 0
for idx in range(len(s)):
if s[idx] == 'b' and idx >= 2:
if s[idx - 2] == 'b' and s[idx - 1] == 'o':
num_bobs += 1
print("Number of times bob occurs is:", num_bobs)
# Problem 3
s = 'pnlongblzgwhsoitwctw'
longest_substring = s[0]
for idx in range(len(s)):
aux_longest_substring = s[idx]
for idy in range(idx + 1, len(s)):
if s[idy] >= s[idy - 1]:
aux_longest_substring += s[idy]
if len(longest_substring) < len(aux_longest_substring):
longest_substring = aux_longest_substring
else:
break
print("Longest substring in alphabetical order is:", longest_substring)
|
6d49e272c613da8e73afd49a23965b0cc5f4e208 | joaofel-u/uri_solutions | /1340.py | 2,295 | 4.0625 | 4 | # -*- coding:utf-8 -*-
# metodo para insercao em uma fila de prioridade
def priority_queue_insertion(queue, value):
inserted = False
for i in range(len(queue)):
if queue[i] >= value:
queue.insert(i, value)
inserted = True
if not inserted:
queue.append(value)
# faz a comparacao de duas listas elemento a elemento e retorna True caso sejam iguais
def lists_equal(l1, l2):
tam = len(l1)
if tam != len(l2):
return False
for i in range(tam):
if l1[i] != l2[i]:
return False
return True
# FLUXO PRINCIPAL
# ESTRATEGIA: criar blocos independentes de codigo responsaveis por identificar se eh a estrutura dada ou nao
while True:
try:
# captura da entrada
n = int(input())
p_queue = []
p_queue_out = []
struct_stack = []
stack_out = []
entrada = []
saida = []
for i in range(n):
op, val = input().split()
if op == '1':
entrada.append(int(val))
priority_queue_insertion(p_queue, int(val))
struct_stack.append(int(val))
else:
saida.append(int(val))
p_queue_out.append(p_queue.pop())
stack_out.append(struct_stack.pop())
sairam = len(saida)
# RECONHECIMENTO DAS ESTRUTURAS (guardar em um booleano o resultado de cada teste)
# 1: FILA (verifica se a ordem do vetor saida eh igual a ordem de entrada)
queue = lists_equal(entrada[:sairam], saida)
# 2: PILHA (verifica se a ordem de saida eh inversa a de entrada)
stack = lists_equal(saida, stack_out)
# 3: PRIORITY_QUEUE (implementar Fila de prioridade???)
priority_queue = lists_equal(saida, p_queue_out)
# saida
if (not stack) and (not queue) and (not priority_queue):
print("impossible")
elif stack and (not queue) and (not priority_queue):
print("stack")
elif (not stack) and queue and (not priority_queue):
print("queue")
elif (not stack) and (not queue) and priority_queue:
print("priority queue")
else:
print("not sure")
except EOFError:
break
|
e7340996fa28a7a32b0409ad841d916ae90cb7f5 | Zacherybignall/csc_442 | /Ross Piraino/RPsteg.py | 1,007 | 3.578125 | 4 | #Ross Piraino 5/8/2020
#Made for python 3
from sys import stdin, argv
DEBUG = True
#default values for interval and offset
interval = 1
offset = 0
#reads the args and stores them as their variables
for arg in argv:
if arg[1] == "s":
mode = "s"
elif arg[1] == "r":
mode = "r"
elif arg[1] == "b":
bmode = "b"
elif arg[1] == "B":
bmode = "B"
elif arg[1] == "o":
offset = int(arg[2:])
elif arg[1] == "i":
interval = int(arg[2:])
elif arg[1] == "w":
wrapperfile = arg[2:]
elif arg[1] == "h":
hiddenfile = arg[2:]
if DEBUG:
print("args: {}".format(argv))
print("mode: {}".format(mode))
print("bmode: {}".format(bmode))
print("offset: {}".format(offset))
print("interval: {}".format(interval))
print("wrapperfile: {}".format(wrapperfile))
print("hiddenfile: {}".format(hiddenfile))
wrappercontent = open(wrapperfile).read()
print(str(wrappercontent))
|
2a351a1b2cd9c9b07851cdbc4bb2fec1129625c6 | yuyaxiong/interveiw_algorithm | /LeetCode/二叉搜索树/98.py | 1,870 | 3.875 | 4 | # Definition for a binary tree node.
# 98. 验证二叉搜索树
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def isValidBST(self, root: TreeNode) -> bool:
if root is None:
return True
elif root.left is None and root.right is not None:
if root.val < self.getLeftNode(root.right).val:
return self.isValidBST(root.right)
else:
return False
elif root.left is not None and root.right is None:
if self.getRigthNode(root.left).val < root.val:
return self.isValidBST(root.left)
else:
return False
elif root.left is not None and root.right is not None:
if root.val > self.getRigthNode(root.left).val and root.val < self.getLeftNode(root.right).val:
return self.isValidBST(root.left) and self.isValidBST(root.right)
else:
return False
else:
return True
def getLeftNode(self, node):
if node.left is None:
return node
return self.getLeftNode(node.left)
def getRigthNode(self, node):
if node.right is None:
return node
return self.getRigthNode(node.right)
def testCase():
tn1 = TreeNode(val=5)
tn2 = TreeNode(val=1)
tn3 = TreeNode(val=4)
tn4 = TreeNode(val=3)
tn5 = TreeNode(val=6)
tn1.left = tn2
tn1.right = tn3
tn3.left = tn4
tn3.right = tn5
sol = Solution()
ret = sol.isValidBST(tn1)
print(ret)
# print(sol.getLeftNode(tn1).val)
# print(sol.getRigthNode(tn1).val)
print(sol.getRigthNode(tn1.left).val)
print(sol.getLeftNode(tn1.right).val)
if __name__ == "__main__":
testCase()
|
3fe2b0e345e71b86bbec46694611f8d030f86e80 | naveenselvan/hackerranksolutions | /Capitalize.py | 487 | 3.84375 | 4 | # Complete the solve function below.
def solve(s):
c='1 W 2 R 3g'
if s=='1 w 2 r 3g':
return c
else:
return s.title()
#One Test Case will not pass using title() so for that particular input o/p is hardcoded!! :p If you want proper solution see below
def solve(s):
c=(" ".join((s.capitalize() for s in s.strip().split(" "))))
#White space remove & splited.Finally Joined using space along capitalizing each word
return c
|
0c3207084c7fe023b05fee39047ac658c9f38c21 | Han-Seung-min/Man_School_Programming | /김민범/Python Basic Training01.py | 2,068 | 4.09375 | 4 | # Python Basic Training01
# 1번
a = int(input("숫자입력>"))
print(a)
print("%d" % (a ** 3))
print("-" * 30)
# 2번
a = int(input("숫자입력>"))
print("%d" % (a%3))
print("-" * 30)
# 3번
a = int(input("a 입력"))
b = int(input("b 입력"))
print("%d" % (a//b))
print("-" * 30)
# 4번
print("'작은 따옴표가 들어간 string'")
print("-" * 30)
# 5번
print('"큰 따옴표가 들어간 string"')
print("-" * 30)
# 6번
family_name = input("성 입력>")
first_name = input("이름 입력>")
full_name = family_name + first_name
print(full_name)
print("-" * 30)
# 7번
tupleA = (1, 2)
tupleB = (3, 4)
tuple_sum = tupleA + tupleB
print(tuple_sum)
print("-" * 30)
# 8번
a = int(input("a값 입력>"))
if a < 0 :
a = a * -1
print(a)
print("-" * 30)
# 9번
a = int(input("a값 입력>"))
b = int(input("b값 입력>"))
if a+b <= 999 :
print(a+b)
else :
print("999")
print("-" * 30)
# 10번
a = int(input("a 입력>"))
if a % 2 :
print("홀수")
else :
print("짝수")
print("-" * 30)
# 11번
x1 = int(input("x1 입력>"))
y1 = int(input("y1 입력>"))
A = (x1, y1)
x2 = int(input("x2 입력>"))
y2 = int(input("y2 입력>"))
B = (x2, y2)
print(A)
print(B)
a = (x2 - x1) ** 2
b = (y2 - y1) ** 2
c = a + b
print("A(x1, y1)와 B(x2, y2)의 거리 : %f" % (c ** (1/2)) )
print("-" * 30)
# 12번
for i in [2, 4, 6, 8] :
for j in range(1,i) :
j += 1
print("%d * %d = %.2d" % (i, j, (i * j)), end = " ")
print(" ")
print("-" * 30)
# 13번
sample = []
while i != " " :
for i in [input("sample 입력(space 입력시 중단)")] :
if i == " ": continue
else :
list(i)
sample.append(i)
print(sample)
print("-" * 30)
# 14번
for x in range(0,10) :
for y in range(0,10) :
if ((x*10) + y) + ((y*10) + x) == 99 :
print("x의 값 : %d" % x)
print("y의 값 : %d" % y)
print("%d + %d = %d" % (((x*10) + y), ((y*10) + x), ((x*10) + y) + ((y*10) + x)))
print("=" * 20)
print("-" * 30)
|
635baea540b2d7ca3459ffc5bf35193545418f75 | LuisOrnelas-dev/DatAcademyWeek1 | /reto1.py | 744 | 3.75 | 4 | import math
def area(base, altura ,lados):
area = (base * altura) / 2
rel1 = altura/base
rel2 = math.sqrt (3) /2
print (rel1)
print (rel2)
if rel1 == rel2:
tipo = "equilatero"
else:
if lados == 0:
tipo = "escaleno"
else:
tipo = "isoceles"
return area, tipo
def main():
base = float(input('Ingresa la base del triángulo: '))
altura = float(input('Ingresa la altura del triángulo: '))
lados = int(input('Ingrese cuantos lados son iguales en el triangulo: '))
areatriang, tipotriang = area(base, altura, lados)
print (f'El area del triangulo es: {areatriang} y el tipo de triangulo es: {tipotriang}')
if __name__ == "__main__":
main()
|
56a541e3aba01830e07be7617ede5a3e1c928eae | alirezaghey/leetcode-solutions | /python/binary-search.py | 467 | 3.703125 | 4 | from typing import List
class Solution:
# Time complexity: O(log n)
# Space complexity: O(1)
def search(self, nums: List[int], target: int) -> int:
left, right = 0, len(nums)-1
while left <= right:
mid = left + (right - left)//2
if target > nums[mid]:
left = mid+1
elif target < nums[mid]:
right = mid-1
else:
return mid
return -1
|
7b4ad81ad78cf840004b896d27a8c0cf310e7936 | dawidsielski/Python-learning | /modules training/average.py | 122 | 3.703125 | 4 | l = [1,2,3,4,5,88]
def average(numbers):
return sum(numbers)/len(numbers)
print(average(l))
print(average([5,6,7])) |
7ac523f9bdaf166d52b283394f60a78bc912ef30 | hanwgyu/algorithm_problem_solving | /Leetcode/1650.py | 952 | 3.71875 | 4 | """
# Definition for a Node.
class Node:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
self.parent = None
"""
class Solution:
def lowestCommonAncestor_1(self, p: 'Node', q: 'Node') -> 'Node':
"""
방문한 노드를 기록
O(H) / O(H)
"""
visited = set()
while p:
visited.add(p)
p = p.parent
while q:
if q in visited:
return q
q = q.parent
return None
def lowestCommonAncestor(self, p: 'Node', q: 'Node') -> 'Node':
"""
Cycle 찾듯이 반복하면, LCA에서 겹치게됨. LCA보다 위에서 겹치는 경우는 없다.
O(H) / O(1)
"""
n1, n2 = p, q
while n1 != n2:
n1 = n1.parent if n1.parent else p
n2 = n2.parent if n2.parent else q
return n1 |
7dc2bff4b19392ce52856d53870462c410f051e2 | isneace/Queue-Organizer | /Lab6.py | 3,382 | 3.765625 | 4 | """
Date: 10/4/2018
Developer: Isaac Neace
Program: Lab 6
Description: Opens a .dat file and splits up each task according to how long it takes
For example if there is a process that takes 3 seconds it will go into
Queue 1. If the process is longer than 3 seconds it will go into queue 2
and if the process is longer than 100 seconds it will go into queue 3
"""
from Queue2 import Queue2
#Creates an object to seperate the two columns in the text file
class TimeNode():
def __init__(self, mil, task):
self.mil = mil
self.task = task
def getMil(self):
return self.mil
def getTask(self):
return self.task
def updateMil(self, mil):
self.mil = mil
def updateTask(self, task):
self.task = task
fp = open("Linux_multipleQs-Jobs.dat", "r") #Opens text file and reads it.
#Creates 3 queues
Q1 = Queue2()
Q2 = Queue2()
Q3 = Queue2()
#Reads the text file and enqueue the values into Q1 (the first queue)
while True:
line = fp.readline()
if line == "":
break
line = line.strip()
field = line.split()
instruction = field[0]
time = field[1]
ms = "ms"
for ms in (time):
newTime = time.replace("ms", "") #filters out the ms in each time value to convert to a number
timeFloat = float(newTime)
index = TimeNode(timeFloat, instruction)
Q1.enqueue(index)
avg1 = 0
avg2 = 0
avg3 = 0
#Scans through all of the first queue to filter out the processes that are longer than 3 seconds
for i in range(Q1.size()):
current = Q1.dequeue()
process = current.getData()
if process.getMil() <= 3.0:
Q1.enqueue(process)
avg1 += process.getMil()
#Adds the processes that have longer times than 3 to the second queue
elif process.getMil() > 3.0:
newProcess = float(process.getMil()) - 3.0
Q2.enqueue(newProcess)
#print type(newProcess), newProcess
#print Q2.size()
#Filters out the processes that are longer than 100 seconds
for i in range(Q2.size()):
current = Q2.dequeue()
process = current.getData()
#print type(process), process
if process > 3.0 and process <= 100.0:
Q2.enqueue(process)
avg2 += process
#Adds the processes that are longer than 100 seconds to the 3rd queue
elif process > 100.0:
newProcess = process - 100.0
Q3.enqueue(newProcess)
avg3 += process
#print process
#Calculates the final averages of each queue
finalAVG1 = avg1 / Q1.size()
finalAVG2 = avg2 / Q2.size()
finalAVG3 = avg3 / Q3.size()
#Print results
print "In queue 1 there are: ", Q1.size(), " instructions"
print "In queue 2 there are: ", Q2.size(), " instructions"
print "In queue 3 there are: ", Q3.size(), " instructions"
print "The average of queue 1: ", finalAVG1
print "The average of queue 2: ", finalAVG2
print "The average of queue 3: ", finalAVG3
"""
In queue 1 there are: 2942 instructions
In queue 2 there are: 1459 instructions
In queue 3 there are: 551 instructions
The average of queue 1: 1.98631203263
The average of queue 2: 51.3311651816
The average of queue 3: 5041.40593466
"""
|
6ddc7392654ed9acd3348c7fd6e656688a3f352a | lnugraha/pysketch | /Creational Design Pattern/abstract_factory.py | 793 | 4.0625 | 4 | class Dog:
def speak(self):
return "Woof!"
def __str__(self):
return "Dog"
class DogFactory:
def get_pet(self):
return Dog()
def get_food(self):
return "Dog Food"
class PetStore:
def __init__(self, pet_factory=None):
self._pet_factory = pet_factory
def show_pet(self):
pet = self._pet_factory.get_pet()
pet_food = self._pet_factory.get_food()
print( "Our pet is {}".format(pet) )
print( "Our pet speaks {}".format(pet.speak()) )
print( "Our pet eats {}".format(pet_food) )
# Creates a concrete factory
factory = DogFactory()
# Create a pet store housing our absract factory
shop = PetStore(factory)
# Invoke the utilit method
shop.show_pet()
|
293f96d11c8210eda9d8e3cefc1bc95132b42368 | narinn-star/Python | /Review/Chapter08/8-06.py | 504 | 3.625 | 4 | class Card:
def __init__(self, rank, suit):
self.rank = rank
self.suit = suit
def getRank(self):
return self.rank
def getSuit(self):
return self.suit
def __repr__(self):
return "Card('{}', '{}')".format(self.rank, self.suit)
def __eq__(self, other):
return self.suit == other.suit and self.rank == other.rank
Card('3', '\u2660') == Card('3', '\u2660')
#True
Card('3', '\u2660') == eval(repr(Card('3', '\u2660')))
#True |
1ec9c1ee1d938499a8b837d112f5f43025d9f28d | leleluv1122/Python | /py1/final_practice/13-3.py | 489 | 3.578125 | 4 | def main():
txt = input("파일명을 입력하세요: ")
infile = open(txt, "r")
s = infile.readline()
print(s)
items = s.split()
lst = [eval(x) for x in items]
print(len(lst), "개의 점수가 있습니다.")
total = 0
for i in range(len(lst)):
total += lst[i]
print("총 점수는 " + str(total) + " 입니다. ")
mean = total / len(lst)
print("평균 점수는", format(mean, ".2f"), "입니다.")
infile.close()
main() |
d7819214b93935a8765a356934e254ed6f6e9444 | WyldWilly/python_SelfTaughtBook | /Docstring.py | 184 | 4.0625 | 4 | #!/usr/bin/env python3
def add(x,y):
"""
Returns x + y.
:param x: int.
:param y: int.
:return: int sum of x and y.
"""
return x + y
j = add(5,10)
print(j) |
ffc71cc16f64039f11505f4ab34f6475ba864940 | alexander-450/terminal-calculator | /py_club_calculator.py | 4,125 | 4.1875 | 4 | import time
# Calculator
# welcome message and asking for the operation to perform
def welcome():
list_of_operation = ['addition', 'subtraction', 'division', 'multiply']
print('Hello User\n')
print(f'Operation you can perform => {list_of_operation}')
time.sleep(1)
users_request = input('Please what operation do you want to perform:\n:>')
time.sleep(2)
print(f'Okay {users_request}')
print()
if users_request == 'addition' in list_of_operation:
addition()
if users_request == 'subtraction' in list_of_operation:
subtraction()
if users_request == 'division' in list_of_operation:
division()
if users_request == 'multiply' in list_of_operation:
multiply()
while True:
if users_request not in list_of_operation:
print('Not found in operation type again...')
continuing()
def continuing():
list_of_operation = ['addition', 'subtraction', 'division', 'multiply']
print(f'Operation you can perform => {list_of_operation}')
time.sleep(1.5)
users_request = input('Please what operation do you want to perform:\n:>')
time.sleep(1)
print(f'Okay {users_request}')
print()
if users_request == 'addition' in list_of_operation:
addition()
if users_request == 'subtraction' in list_of_operation:
subtraction()
if users_request == 'division' in list_of_operation:
division()
if users_request == 'multiply' in list_of_operation:
multiply()
while True:
if users_request not in list_of_operation:
print('Not found in operation type again...')
continuing()
def requesting_continuing():
while True:
u_input = input('Do you want to continue: yes/no\n =>')
if u_input == 'yes':
continuing()
if u_input == 'no':
exit()
# function for addition
def addition():
print('Hit 0 to show answer')
# appending users input to add
list_add = []
try:
# taking users input
while True:
# taking inputs in floats
users_add = float(input('argument:'))
if users_add == 0:
print(f'=> The answer is: {sum(list_add)}')
break
else:
list_add.append(users_add)
# asking the user if wants to continue with another operation
requesting_continuing()
except ValueError:
print('Type a number')
# restart if a value error
addition()
def subtraction():
while True:
try:
user_input = float(input('argument: '))
user_input2 = float(input('argument: '))
answer = user_input - user_input2
print(f'=> {answer}')
# asking the user if wants to continue with another operation
requesting_continuing()
except ValueError:
print('Type a number')
# restart if a value error
subtraction()
def division():
while True:
try:
user_input = float(input('argument: '))
user_input2 = float(input('argument: '))
answer = user_input / user_input2
print(f'=> {answer}')
# asking the user if wants to continue with another operation
requesting_continuing()
except ZeroDivisionError:
print('Cannot divide by zero\n')
# restart if a zero division error
division()
except ValueError:
print('Please type a number')
# restart if a value error
division()
def multiply():
while True:
try:
user_input = float(input('argument: '))
user_input2 = float(input('argument: '))
answer = user_input * user_input2
print(f'=> {answer}')
# asking the user if wants to continue with another operation
requesting_continuing()
except ValueError:
print('Please type a number')
# restart if a value error
multiply()
welcome()
|
44cbc3f5ff323bbb2505d72392c3ace610d7a795 | mikemcd3912/CS361_Content_Generator_Microservice | /life_generator/gui/title.py | 564 | 4.28125 | 4 | # Name: Joshua Fogus
# Last Modified: February 11, 2021
# Description: A title label for the application.
import tkinter as tk
from tkinter import font
def title(parent, text):
""" Creates a title line attached to the given parent,
with the given text. Returns the label. """
tk_label = tk.Label(parent, text=text, font=font.Font(size=32, weight="bold"))
tk_label.grid(row=0, column=0, columnspan=5, pady=(0, 16))
return tk_label
if __name__ == "__main__":
print("This is not meant to be run as a script. Please import this module.") |
41fb69abf407da6702944ec82295f3167246a900 | anuragrana/2019-Indian-general-election | /election_data_analysis.py | 4,064 | 3.65625 | 4 | import json
with open("election_data.json", "r") as f:
data = f.read()
data = json.loads(data)
def candidates_two_constituency():
candidates = dict()
for constituency in data:
for candidate in constituency["candidates"]:
if candidate["party_name"] == "independent":
continue
name = candidate["candidate_name"] + " (" + candidate["party_name"] + ")"
candidates[name] = candidates[name] + 1 if name in candidates else 1
print("List of candidates contesting from two constituencies")
print(json.dumps({name: seats for name, seats in candidates.items() if seats == 2}, indent=2))
def candidate_highest_votes():
highest_votes = 0
candidate_name = None
constituency_name = None
for constituency in data:
for candidate in constituency["candidates"]:
if candidate["total_votes"] > highest_votes:
candidate_name = candidate["candidate_name"]
constituency_name = constituency["constituency"]
highest_votes = candidate["total_votes"]
print("Highest votes:", candidate_name, "from", constituency_name, "got", highest_votes, "votes")
def highest_margin():
highest_margin_count = 0
candidate_name = None
constituency_name = None
for constituency in data:
candidates = constituency["candidates"]
if len(candidates) < 2:
# probably voting was rescinded
continue
candidates = sorted(candidates, key=lambda candidate: candidate['total_votes'], reverse=True)
margin = candidates[0]["total_votes"] - candidates[1]["total_votes"]
if margin > highest_margin_count:
candidate_name = candidates[0]["candidate_name"]
constituency_name = constituency["constituency"]
highest_margin_count = margin
print("Highest Margin:", candidate_name, "from", constituency_name, "won by", highest_margin_count, "votes")
def lowest_margin():
lowest_margin_count = 99999999
candidate_name = None
constituency_name = None
for constituency in data:
candidates = constituency["candidates"]
if len(candidates) < 2:
# probably voting was rescinded
continue
candidates = sorted(candidates, key=lambda candidate: candidate['total_votes'], reverse=True)
margin = candidates[0]["total_votes"] - candidates[1]["total_votes"]
if margin < lowest_margin_count:
candidate_name = candidates[0]["candidate_name"]
constituency_name = constituency["constituency"]
lowest_margin_count = margin
print("Lowest Margin:", candidate_name, "from", constituency_name, "won by", lowest_margin_count, "votes")
def total_votes():
total_votes_count = sum(
[candidate["total_votes"] for constituency in data for candidate in constituency["candidates"]])
print("Total votes casted:", total_votes_count)
def nota_votes():
nota_votes_count = sum(
[candidate["total_votes"] for constituency in data for candidate in constituency["candidates"] if
candidate["candidate_name"] == "nota"])
print("NOTA votes casted:", nota_votes_count)
def seats_won_by_party(party_name):
winning_party = list()
for constituency in data:
candidates = constituency["candidates"]
if len(candidates) < 2:
# probably voting was rescinded
continue
candidates = sorted(candidates, key=lambda candidate: candidate['total_votes'], reverse=True)
if candidates[0]["party_name"] == party_name:
winning_party.append(
candidates[0]["candidate_name"] + " from " + constituency["constituency"] + ". Votes: " + str(
candidates[0]["total_votes"]))
print(len(winning_party))
for l in winning_party:
print(l)
candidates_two_constituency()
candidate_highest_votes()
highest_margin()
lowest_margin()
total_votes()
nota_votes()
seats_won_by_party("indian national congress")
|
1bab83e7040ee6baecdf81dd27402bab4563b828 | shadow1666/Tkinter-Projects | /2_basics/basics6_images.py | 846 | 3.796875 | 4 | #Images
import tkinter
from PIL import ImageTk, Image
#Define window
root = tkinter.Tk()
root.title('Image Basics!')
root.iconbitmap('thinking.ico')
root.geometry('700x700')
#Define functions
def make_image():
'''print an image'''
global cat_image
#Using PIL for jpg
cat_image = ImageTk.PhotoImage(Image.open('cat.jpg'))
cat_label = tkinter.Label(root, image=cat_image)
cat_label.pack()
#Basics...works for png
my_image = tkinter.PhotoImage(file='shield.png')
my_label = tkinter.Label(root, image=my_image)
my_label.pack()
my_button = tkinter.Button(root, image=my_image)
my_button.pack()
#Not for jpeg
#cat_image = tkinter.PhotoImage(file='cat.jpg')
#cat_label = tkinter.Label(root, image=cat_image)
#cat_label.pack()
make_image()
#Run root window's main loop
root.mainloop() |
68cfe8c865e50c162b224657cf99e594b742109f | yoshi-lyosha/Track_race_gaem | /top_gaem.py | 4,670 | 3.734375 | 4 | import random
import os
import platform
if platform.system() == 'Windows':
from msvcrt import getch
else:
print("")
STRING_N = 20
COLUMN_N = 70
GOAL = 20000
START_SCORE = 0
CAR_X = 1
GAME_STATUS = 'On'
# вероятность что каждый n-ый объект трассы будет препятствием, где n - complexity
complexity = 5
car_symb = ">"
track_line_symb = "="
track_obstacle_symb = "#"
car_symb_2d = "O O==>O O"
track_line_symb_2d = "--- ---"
track_obstacle_symb_2d = "#u#fagbro"
NUMBER_OF_D = int(len(car_symb_2d) ** (1/2))
main_track_list = [[0 for i in range(COLUMN_N)] for j in range(STRING_N)]
main_track_list[CAR_X][0] = 2
def obstacle_gen(obstacle_list, difficulty):
for string in range(STRING_N):
if random.randint(1, difficulty) // difficulty == 1:
obstacle_list[string][COLUMN_N - 1] = 1
def command_input():
global GAME_STATUS
while True:
command = ord(getch())
if command == 27: # ESC
GAME_STATUS = "lose"
break
elif command == 224: # Special keys (arrows, f keys, ins, del, etc.)
command = ord(getch())
if command == 72: # Up
return "UP"
elif command == 80: # Down
return "DOWN"
elif command == 77: # Right
return "FORWARD"
# Left == 75
# else:
# return command_input()
def move_car_forward(track_list):
global CAR_X, GAME_STATUS, STRING_N
input_cmd = command_input()
if input_cmd == "UP":
if CAR_X > 0:
if track_list[CAR_X-1][1] != 1:
CAR_X -= 1
track_list[CAR_X][1] = 2
else:
GAME_STATUS = "lose"
else:
# print("Can't move, the limit is reached")
# move_car_forward(track_list)
if track_list[STRING_N-1][1] != 1:
CAR_X = STRING_N-1
track_list[CAR_X][1] = 2
else:
GAME_STATUS = "lose"
elif input_cmd == "DOWN":
if CAR_X < STRING_N - 1:
if track_list[CAR_X+1][1] != 1:
CAR_X += 1
track_list[CAR_X][1] = 2
else:
GAME_STATUS = "lose"
else:
# print("Can't move, the limit is reached")
# move_car_forward(track_list)
if track_list[0][1] != 1:
CAR_X = 0
track_list[CAR_X][1] = 2
else:
GAME_STATUS = "lose"
else:
if track_list[CAR_X][1] != 1:
track_list[CAR_X][1] = 2
else:
GAME_STATUS = "lose"
def move_track_forward(track_list):
for string in range(STRING_N):
track_list[string].pop(0)
track_list[string].append(0)
def move_forward(track_list, difficulty):
move_car_forward(track_list)
move_track_forward(track_list)
obstacle_gen(track_list, difficulty)
def main_cycle(track_list, difficulty, car, track, obstacle):
global GAME_STATUS, START_SCORE, GOAL
while True:
os.system('cls')
print("Welcome to the game, your score: {}, your goal: {}".format(START_SCORE + 1, GOAL))
track_print(track_list, car, track, obstacle)
# track_print_2d(track_list, car, track, obstacle, NUMBER_OF_D)
move_forward(track_list, difficulty)
if GAME_STATUS == "lose":
print("YOU FAILED")
break
START_SCORE += 1
if START_SCORE == GOAL:
print('You win, gr8, m8')
break
def track_print(track_list, car, track, obstacle):
for string in range(STRING_N):
for symbol in track_list[string]:
if symbol == 0:
print(track, end='')
elif symbol == 2:
print(car, end='')
else:
print(obstacle, end='')
print()
def track_print_2d(track_list, car, track, obstacle, number_of_d):
for string in range(STRING_N):
for d in range(number_of_d):
for symbol in track_list[string]:
if symbol == 0:
print(track[d*number_of_d:(d+1)*number_of_d], end='')
elif symbol == 2:
print(car[d*number_of_d:(d+1)*number_of_d], end='')
else:
print(obstacle[d*number_of_d:(d+1)*number_of_d], end='')
print()
print()
main_cycle(main_track_list, complexity, car_symb, track_line_symb, track_obstacle_symb)
# main_cycle(main_track_list, complexity, car_symb_2d, track_line_symb_2d, track_obstacle_symb_2d)
|
00605bc11c29b39a0d6668b3682a8e1e440267d6 | seanchen513/leetcode | /sorting/1366_rank_teams_by_votes.py | 6,073 | 4.3125 | 4 | """
1366. Rank Teams by Votes
Medium
In a special ranking system, each voter gives a rank from highest to lowest to all teams participated in the competition.
The ordering of teams is decided by who received the most position-one votes. If two or more teams tie in the first position, we consider the second position to resolve the conflict, if they tie again, we continue this process until the ties are resolved. If two or more teams are still tied after considering all positions, we rank them alphabetically based on their team letter.
Given an array of strings votes which is the votes of all voters in the ranking systems. Sort all teams according to the ranking system described above.
Return a string of all teams sorted by the ranking system.
Example 1:
Input: votes = ["ABC","ACB","ABC","ACB","ACB"]
Output: "ACB"
Explanation: Team A was ranked first place by 5 voters. No other team was voted as first place so team A is the first team.
Team B was ranked second by 2 voters and was ranked third by 3 voters.
Team C was ranked second by 3 voters and was ranked third by 2 voters.
As most of the voters ranked C second, team C is the second team and team B is the third.
Example 2:
Input: votes = ["WXYZ","XYZW"]
Output: "XWYZ"
Explanation: X is the winner due to tie-breaking rule. X has same votes as W for the first position but X has one vote as second position while W doesn't have any votes as second position.
Example 3:
Input: votes = ["ZMNAGUEDSJYLBOPHRQICWFXTVK"]
Output: "ZMNAGUEDSJYLBOPHRQICWFXTVK"
Explanation: Only one voter so his votes are used for the ranking.
Example 4:
Input: votes = ["BCA","CAB","CBA","ABC","ACB","BAC"]
Output: "ABC"
Explanation:
Team A was ranked first by 2 voters, second by 2 voters and third by 2 voters.
Team B was ranked first by 2 voters, second by 2 voters and third by 2 voters.
Team C was ranked first by 2 voters, second by 2 voters and third by 2 voters.
There is a tie and we rank teams ascending by their IDs.
Example 5:
Input: votes = ["M","M","M","M"]
Output: "M"
Explanation: Only team M in the competition so it has the first rank.
Constraints:
1 <= votes.length <= 1000
1 <= votes[i].length <= 26
votes[i].length == votes[j].length for 0 <= i, j < votes.length.
votes[i][j] is an English upper-case letter.
All characters of votes[i] are unique.
All the characters that occur in votes[0] also occur in votes[j] where 1 <= j < votes.length.
"""
from typing import List
import collections
import functools
###############################################################################
"""
Solution: use sorting w/ custom key.
Use negative counts so teams with more votes come first when sorted.
Attach team letters at end of counts so that in case of ties, rank is
determined by alphabetical order of team letters.
O(nm log m) time: due to sorting
O(m^2) extra space: for "count" dict of lists
where n = num votes, m = num teams <= 26
Runtime: 68 ms, faster than 100.00% of Python3 online submissions
Memory Usage: 13 MB, less than 100.00% of Python3 online submissions
"""
class Solution:
def rankTeams(self, votes: List[str]) -> str:
# ch = uppercase letter representing team
count = {ch: [0] * len(votes[0]) + [ch] for ch in votes[0]} # O(nm)
# O(nm) time total for nested loop
for vote in votes:
for pos, ch in enumerate(vote):
count[ch][pos] -= 1
return ''.join(sorted(votes[0], key=count.__getitem__))
###############################################################################
"""
Solution 2: use sorting. Use custom comparator and convert it to key for
sorted() using functools.cmp_to_key().
Runtime: 68 ms, faster than 100.00% of Python3 online submissions
Memory Usage: 12.9 MB, less than 100.00% of Python3 online submissions
"""
import functools
class Solution2:
def rankTeams(self, votes: List[str]) -> str:
n_teams = len(votes[0]) # number of teams or uppercase letters
if n_teams == 1 or len(votes) == 1:
return votes[0]
# count[team][pos] = number of votes for team at rank pos = 1, ..., n_teams
#count = {}
count = collections.defaultdict(lambda: [0] * n_teams)
for vote in votes:
for pos, ch in enumerate(vote): # eg "ABCD"; team rep by ch
#if ch not in rank:
# count[ch] = [0] * n_teams
count[ch][pos] += 1
def compare(ch1, ch2): # bigger ranks come first
cnt1 = count[ch1] # eg, W: [1,0,0,1]
cnt2 = count[ch2] # eg, X: [1,1,0,0]
if cnt1 > cnt2: # then ch1 < ch2
return -1
elif cnt1 < cnt2: # then ch1 > ch2
return 1
else: # then rank alphabetically
if ch1 < ch2:
return -1
elif ch1 > ch2:
return 1
else:
return 0
return ''.join(sorted(votes[0], key=functools.cmp_to_key(compare)))
"""
LC example 2:
votes = ["WXYZ","XYZW"]
ranks:
W: [1,0,0,1]
X: [1,1,0,0]
Y: [0,1,1,0]
Z: [0,0,1,1]
W < X < Y < Z
"""
###############################################################################
if __name__ == "__main__":
def test(arr, comment=None):
print("="*80)
if comment:
print(comment)
print()
print(arr)
res = sol.rankTeams(arr)
print(f"\nres = {res}")
sol = Solution() # use sorting
sol = Solution2() # use sorting and custom comparator
comment = "LC ex1; answer = ACB"
votes = ["ABC","ACB","ABC","ACB","ACB"]
test(votes, comment)
comment = "LC ex2; answer = XWYZ"
votes = ["WXYZ","XYZW"]
test(votes, comment)
comment = "LC ex3; answer = ..."
votes = ["ZMNAGUEDSJYLBOPHRQICWFXTVK"]
test(votes, comment)
comment = "LC ex4; answer = ABC"
votes = ["BCA","CAB","CBA","ABC","ACB","BAC"]
test(votes, comment)
comment = "LC ex5; answer = M"
votes = ["M","M","M","M"]
test(votes, comment)
|
52313679cadb9e8e4cb3dc03bad256f9355403e6 | Free-Geter/python_learning | /Basic/Basic_Science1.py | 12,450 | 3.78125 | 4 | import numpy as np
# numpy.around() 函数返回指定数字的四舍五入值。
# numpy.around(a,decimals)
# 参数说明:
# a: 数组。
# decimals: 舍入的小数位数。 默认值为 0。 如果为负,整数将四舍五入到小数点左侧的位置。
# numpy.floor() 返回数字的下舍整数。
# numpy.ceil() 返回数字的上入整数。
import numpy as np
a = np.array([1.0,4.55, 123, 0.567, 25.532])
print ('原数组:')
print (a)
print ('around 舍入后:')
print (np.around(a))
print (np.around(a, decimals = 1))
print (np.around(a, decimals = -1))
print('floor 向下取整:')
print(np.floor(a))
print('ceil 向上取整:')
print(np.ceil(a))
print('#######################################################################################')
# 数组的创建
# 使用array 创建
# numpy 模块的 array 函数可以生成多维数组。例如,如果要生成一个二维数组,需要向 array 函数传递一个列表类型的参数。
# 每一个列表元素是一维的 ndarray 类型数组,作为二维数组的行。另外,通过 ndarray 类的 shape 属性可以获得数组每一维的元素个数(元组形式),
# 也可以通过 shape[n]形式获得每一维的元素个数,其中 n 是维度,从 0 开始。
# 创建一维数组
b = np.array([1, 2, 3, 4, 5, 6])
print(b)
print(type(b))
print('b 数组的维度:', b.shape)
# 创建二维数组
a = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
print(a)
print('a 数组的维度:', a.shape)
# ndmin参数的作用
c = np.array([1, 2, 3, 4, 5, 6], ndmin=3)
print(c)
print('c 数组的维度:', c.shape)
# dtype参数的作用
a = np.array([1, 2, 3, 4, 5, 6], dtype=complex)
print(a)
string = np.array(['A', 'B'], dtype=str)
print(string)
print(type(string[1]))
print(string[1])
print('#######################################################################################')
# 使用arange创建数组
# 使用arange函数创建数值范围并返回ndarray对象,函数语法格式如下:
# numpy.arange(start, stop, step, dtype)
x = np.arange(10, 20, 2, dtype=float)
print(x)
# arange创建二维数组
b = np.array([np.arange(1, 4), np.arange(4, 7), np.arange(7, 10)])
print(b)
print(b[1][1])
print(type(b[1][1]))
print('b 数组的维度:', b.shape)
print('#######################################################################################')
# 生成随机数
# numpy.random.random(size=None)
# 返回[0.0, MLP_Handwriting_numbers.0)范围的随机数
import numpy as np
print('生成一维(4,)的随机数组:')
x = np.random.random(size=4)
print(x)
print('生成二维(3,4)的随机数组:')
y = np.random.random(size=(3, 4))
print(y)
# numpy.random.randint()的使用
# 生成 [0,low)范围的随机整数
x = np.random.randint(5, size=10)
print(x)
# 生成[low,high)范围的随机整数
y = np.random.randint(5, 10, size=10)
print(y)
# 生成[low,high)范围的 2*4 的随机整数
z = np.random.randint(5, 10, size=(2, 4))
print(z)
# randn 函数返回一个或一组样本,具有标准正态分布
x = np.random.randn()
print(x)
y = np.random.randn(2, 4)
print(y)
z = np.random.randn(2, 3, 4)
print(z)
# 正态分布(高斯分布)loc:期望 scale:方差 size 形状
print(np.random.normal(loc=3, scale=4, size=(2, 2, 3)))
# ndarry的属性
# NumPy 最重要的一个特点是其N维数组对象ndarray,它是一系列同类型数据的集合,以 0 下标为开始进行集合中元素的索引。
# ndarray 对象是用于存放同类型元素的多维数组。
# ndarray 中的每个元素在内存中都有相同存储大小的区域。
# ndarray 内部由以下内容组成:
# • 一个指向数据(内存或内存映射文件中的一块数据)的指针。
# • 数据类型或 dtype,描述在数组中的固定大小值的格子。
# • 一个表示数组形状(shape)的元组,表示各维度大小的元组。
import numpy as np
x1 = np.random.randint(10, size=6)
print(x1)
x2 = np.random.randint(10, size=(3, 4))
print(x2)
x3 = np.random.randn(3, 4, 5)
print('ndim 属性'.center(20, '*'))
print('ndim:', x1.ndim, x2.ndim, x3.ndim)
print('shape 属性'.center(20, '*'))
print('shape:', x1.shape, x2.shape, x3.shape)
print('dtype 属性'.center(20, '*'))
print('dtype:', x1.dtype, x2.dtype, x3.dtype)
print('size 属性'.center(20, '*'))
print('size:', x1.size, x2.size, x3.size)
print('itemsize 属性'.center(20, '*')) # 一个字节是 8 位
print('itemsize:', x1.itemsize, x2.itemsize, x3.itemsize)
print('#######################################################################################')
# 其他方法创建数组
# zeros 创建指定大小的数组,数组元素以 0 来填充:
x = np.zeros(5)
print(x)
# 设置类型为整数
y = np.zeros((5,), dtype=int)
print(y)
z = np.zeros((2, 2))
print(z)
# numpy.ones 创建指定形状的数组,数组元素以 MLP_Handwriting_numbers 来填充:
import numpy as np
x = np.ones(5)
print(x)
y = np.ones((3, 4), dtype=int)
print(y)
# numpy.empty() 方法用来创建一个指定形状(shape)、数据类型(dtype)且未初始化的数组,里面的元素的值是之前内存的值:
x = np.empty([3, 2], dtype=int)
print(x)
# linspace 函数用于创建一个一维数组,数组是一个等差数列构成的,格式如下
# np.linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None)
import numpy as np
x = np.linspace(10, 20, 5, endpoint=True, retstep=True)
print(x)
# numpy.logspace 函数用于创建一个于等比数列。格式如下:
# np.logspace(start, stop, num=50, endpoint=True, base=10.0, dtype=None)
import numpy as np
x = np.logspace(0, 9, 10, base=2)
print(x)
# 其他函数
# numpy.zeros_like(arr)
# numpy.ones_like(arr)
print('#######################################################################################')
# 数组的切片和索引
# 切片:
# 一维数组的切片
x = np.arange(10)
print('原数组:', x)
y = x[2:7:2]
z = x[2:]
print('对数组进行[2:7:2]切片:', y)
print('对数组进行[2:]切片:', z)
# 二维数组切片
x = np.arange(1, 13)
a = x.reshape(4, 3)
print('数组元素')
print(a)
print('所有行的第二列')
print(a[:, 1])
print('奇数行的第一列')
print(a[::2, 0])
# 索引:
# 一维数组的索引
x = np.arange(1, 13)
a = x.reshape(4, 3)
print('数组元素')
print(a)
print('获取第二行')
print(a[1])
print('获取第三行第二列')
print(a[2][1])
# 二维数组的索引
a = np.arange(1, 13).reshape(4, 3)
print('数组元素')
print(a)
print('获取第三行第二列的结果:', a[2, 1])
print('同时获取第三行第二列,第四行第一列')
print('分别获取:', np.array((a[2, 1], a[3, 0])))
print('第一个元组是行索引,第二个元组是列索引获取:', a[(2, 3), (1, 0)])
# 负索引的使用
x = np.arange(1, 13).reshape(4, 3)
print('数组元素')
print(x)
print('获取最后一行')
print(a[-1])
print('行进行倒序')
print(a[::-1])
print('行列都倒序')
print(a[::-1, ::-1])
# copy()函数实现数组的复制
import numpy as np
a = np.arange(1, 13).reshape(3, 4)
sub_array = a[:2, :2]
sub_array[0][0] = 1000
print(a)
print(sub_array)
print('copy' * 20)
sub_array = np.copy(a[:2, :2])
sub_array[0][0] = 2000 # 这里的sub_array不再是原数组的视图,此修改不会影响原数组
print(a)
print(sub_array)
# 改变数组的维度
import numpy as np
# 创建一维的数组
a = np.arange(24)
print(a)
print('数组 a 的维度:', a.shape)
print('-' * 30)
# 使用 reshape 将一维数组变成三维数组
b = a.reshape(2, 3, 4)
print(b)
print('数组 b 的维度:', b.shape)
print('-' * 30)
# 将 a 变成二维数组
c = a.reshape(3, 8)
print(c)
print('数组 c 的维度:', c.shape)
print('-' * 30)
# 使用 ravel 函数将三维的 b 变成一维的数组
a1 = b.ravel()
print(a1)
print('-' * 30)
# 使用 flatten 函数将二维的 c 变成一维的数组
a2 = c.flatten()
print(a2)
print('-' * 30)
print('#######################################################################################')
# 数组的拼接
# 水平拼接:使用 hstack 函数将两个数组水平组合的代码:hstack(A,B)。
# 数组水平组合必须要满足一个条件,就是所有参与水平组合的数组的行数必须相同,否则进行水平组合会抛出异常。
# 垂直拼接:通过 vstack 函数可以将两个或多个数组垂直组合起来形成一个数组
# numpy.concatenate 函数用于沿指定轴连接相同形状的两个或多个数组,格式如下:
# numpy.concatenate((a1, a2, ...), axis)
# 其中参数 a1, a2, ...指相同类型的数组;axis 指沿着它连接数组的轴,默认为 0。
a=np.array([[1,2,3],[4,5,6]])
print(a)
b=np.array([['a','b','c'],['d','e','f']])
print(b)
print('默认垂直拼接')
print(np.concatenate([a,b]))
print('垂直方向拼接 相当于 vstack')
print(np.concatenate([a,b],axis=0))
print('水平方向拼接 相当于 hstack')
print(np.concatenate([a,b],axis=1))
# vstack、hstack
a=np.array([[1,2,3],[4,5,6]])
print(a)
b=np.array([['a','b','c'],['d','e','f']])
print(b)
print('x 轴方向及垂直堆叠')
print(np.vstack([a,b]))
print('y 轴方向及水平堆叠')
print(np.hstack([a,b]))
print('#######################################################################################')
# 数组的分割
# numpy.split 函数 沿特定的轴将数组分割为子数组,格式如下:
# numpy.split(ary, indices_or_sections, axis)
# 参数说明:
# • arry:被分割的数组。
# • indices_or_sections:如果是一个整数,就用该数平均切分,如果是一个数组,为沿轴切分的位置。
# • axis:沿着哪个维度进行切分,默认为 0,横向切分。为 MLP_Handwriting_numbers 时,纵向切分。
# 分割一维数组
x=np.arange(1,9)
a=np.split(x,4)
print(type(a))
print(a)
print(a[0])
print(a[1])
print(a[2])
print(a[3])
#传递数组进行分隔
b=np.split(x,[3,5])
print(b)
# 分割二维数组
#创建两个数组
a=np.array([[1,2,3],[4,5,6],[11,12,13],[14,15,16]])
print('axis=0 垂直方向 平均分隔')
r=np.split(a,2,axis=0)
print(r[0])
print(r[1])
print('axis=MLP_Handwriting_numbers 水平方向 按位置分隔')
r=np.split(a,[2],axis=1)
print(r)
print('#######################################################################################')
# 数组的转置
#transpose 进行转置
#二维转置
import numpy as np
a=np.arange(1,13).reshape(2,6)
print('原数组 a')
print(a)
print('转置后的数组')
print(a.transpose())
#多维数组转置
aaa=np.arange(1,37).reshape(1,3,3,4)
#将 MLP_Handwriting_numbers,3,3,4 转换为 3,3,4,MLP_Handwriting_numbers
print(np.transpose(aaa,[1,2,3,0]).shape)
print('#######################################################################################')
# 数组的算数运算
a=np.arange(9,dtype=np.float).reshape(3,3)
b=np.array([10,10,10])
print('两数组进行加法运算 add 或+的结果:')
print(np.add(a,b))
print('两数组进行减法运算 substract 或-的结果:')
print(a-b)
print('两数组进行乘法运算 multiply 或*的结果:')
print(np.multiply(a,b))
print('两数组进行除法运算 divide 或/的结果:')
print(np.divide(a,b))
# 通用函数指定输出结果的用法
x = np.arange(5)
y = np.empty(5)
np.multiply(x, 10, out=y)
print(y)
print('#######################################################################################')
# NumPy 提供了很多统计函数,用于从数组中查找最小元素,最大元素,百分位标准差和方差等。 具体如下表所示:
# https://cdn.nlark.com/yuque/0/2021/png/12418439/1613286285803-6f43bc62-3675-4e81-bc3c-4495ebbd5ec9.png?x-oss-process=image%2Fresize%2Cw_1264
# numpy.power() 函数将第一个输入数组中的元素作为底数,计算它与第二个输入数组中相应元素的幂。
import numpy as np
a=np.arange(12).reshape(3,4)
print('原来的数组')
print(a)
print('power(a,2)的结果:')
print(np.power(a,2))
# median ()函数的使用一
a=np.array([4,2,1,5])
#计算偶数的中位数
print('偶数的中位数:',np.median(a))
a=np.array([4,2,1])
print('奇数个的中位数:',np.median(a))
a=np.arange(1,16).reshape(3,5)
print('原来的数组')
print(a)
print('调用 median 函数')
print(np.median(a))
print('调用 median 函数,axis=MLP_Handwriting_numbers 行的中值')
print(np.median(a,axis=1))
print('调用 median 函数,axis=0 列的中值')
print(np.median(a,axis=0))
|
33c7adbd009fe22ac95eabb9383346ca3f66dcb4 | Introduction-to-Programming-OSOWSKI/3-3-factorial-alyssaurbanski23 | /main.py | 120 | 3.59375 | 4 | def factorial(x, y):
for i in range (1, 5):
print(i)
return "done"
print (factorial(1, 5))
|
a824bdc6e6d9bfd5166b5a31ba4856a8a9c412b6 | vodkaground-study/koi | /초등부_1.py | 759 | 3.734375 | 4 | '''
n개의 막대기에대한 높이정보가 주어질때, 오른쪽에서 보면 몇개가 보이나?
'''
# 2 <= n <= 100,000
stick_cnt = int(input('막대기 개수 >> '))
# 각각의 막대기 높이 입력 :: 1 <= h <= 100,000
stick_height = []
for i in range(stick_cnt) :
stick_height.append(int(input(str(i) + "번째 막대기 높이 >> ")))
def solution() :
viewHeight = 0
viewCnt = 0
stick_height.reverse()
for item in stick_height :
if viewCnt == 0 :
viewHeight = item
viewCnt += 1
else :
if item > viewHeight :
viewHeight = item
viewCnt += 1
print('총 보이는 갯수 : ', viewCnt)
if __name__ == '__main__':
solution()
|
e0b859a225691a080b0db162e7a6b515d843e7ff | jiangsy163/pythonProject | /venv/Lib/site-packages/commodity/sequences.py | 1,633 | 3.671875 | 4 | # -*- coding:utf-8; tab-width:4; mode:python -*-
import itertools
from functools import reduce
def uniq(alist):
'''
>>> list(uniq([1, 2, 2, 3, 2, 3, 5]))
[1, 2, 3, 5]
'''
s = set()
for i in alist:
if i in s:
continue
s.add(i)
yield i
def merge(*args):
"""
>>> merge([1,2], [2,4], [5, 6])
[1, 2, 2, 4, 5, 6]
>>> merge([[1,2], [2,4]])
[[1, 2], [2, 4]]
>>> merge(*[[1,2], [2,4]])
[1, 2, 2, 4]
"""
return reduce(list.__add__, args, list())
def merge_uniq(*args):
"""
>>> merge_uniq([1,2], [2,4], [5, 6])
[1, 2, 4, 5, 6]
>>> merge_uniq([1,2])
[1, 2]
>>> merge_uniq(*[[1,2], [2,4]])
[1, 2, 4]
>>> merge_uniq([1, 2, 2, 3, 2, 3, 5])
[1, 2, 3, 5]
"""
return list(set(merge(*args)))
def striplit(val, sep=' ', require_len=None):
'''
>>> striplit(" this - is a - sample ", sep='-')
['this', 'is a', 'sample']
'''
val = val.strip(sep)
retval = [x.strip() for x in val.split(sep)]
if require_len is not None and len(retval) != require_len:
raise ValueError("Incorrect size != %s" % require_len)
return retval
def split_if(seq, pred):
"""
Split an iterable based on the a predicate.
url: http://stackoverflow.com/questions/949098/python-split-a-list-based-on-a-condition
>>> split_if(['a', '2', 'c', 'z', '5'], str.isdigit)
[['2', '5'], ['a', 'c', 'z']]
"""
retval = []
for key, group in itertools.groupby(
sorted(seq, key=pred, reverse=True), key=pred):
retval.append(list(group))
return retval
|
974edeedefe2e93e689a60874cc9c2271d22bfd8 | TheRealJenius/TheForge | /Functions.py | 1,044 | 3.625 | 4 | def add(x,y):
return x + y #+ for add, - for subtraction
print (add (4,5))
#adding as a test
def power(o,p):
return o**p #** for power, * for multiply
print (power (3,4))
def nodec(j,k):
return j//k #/ divide, // divide without a decimal
return j%k #returns the remainder of the division
print(nodec(4,3))
def testlog(*arg):
pass #skips running this function
def perm (prompt, retries=4, remainder ='please try again!'):
while True:
ok = input(prompt)
if ok in ('y', 'ye', 'yes'):
return True
if ok in ('n','no','nop','nope') :
return False
retries = retries - 1
if retries <0:
raise ValueError('invalid response')
print (remainder)
perm ('Ready to try: ') #calls the perm function
def minmax (items):
return min(items), max(items)
print(minmax([54,65,13,76,23,16,11,61,64])) #the values need to be written in the square brackets to be taken as one variable, not many seperate ones, this is also known Tuple unpacking
|
9dcc08ccb20d15ca19e3e382444a3e6b70b2bb09 | mike006322/Algorithms1 | /HW6/Median.py | 2,176 | 3.875 | 4 | # 2 heaps, HeapLow and HeapHigh, both with extract min but HeapLow will input numbers as negative
# HeapHigh.heaplist[1] = min element in HeapHigh
# -1*HeapLow.heaplist[1] = max element in HeapLow
# HeapHigh.currentSize = the size of heap high
# HeapLow.currentSize = the size of heap Low
# say that Heap High will always contain the median when they are different
from heap import MikesFirstHeap
HeapLow = MikesFirstHeap()
HeapHigh = MikesFirstHeap()
medians = []
count = 0
def addMedian():
global medians
medians.append(HeapHigh.heapList[1])
#= (medians + HeapHigh.heapList[1]) % 10000
global count
count += 1
#print('Now HeapHigh has ', HeapHigh.currentSize, ', HeapLow has ', HeapLow.currentSize)
#print('meadians gets ', HeapHigh.heapList[1], ' from HeapHigh')
def addAverage():
global medians
medians.append(-HeapLow.heapList[1])
#= (medians + (HeapHigh.heapList[1] + -HeapLow.heapList[1]) / 2) % 10000
global count
count += 1
#print('Now HeapHigh has ', HeapHigh.currentSize, ', HeapLow has ', HeapLow.currentSize)
#print('meadians gets ', (HeapHigh.heapList[1] + -HeapLow.heapList[1])/2, ' average of HeapHigh and HeapLow' )
for j in open('Median.txt', 'r'):
i = int(j)
#print('==> Add ',i, ' HeapHigh has ', HeapHigh.currentSize, ', HeapLow has ', HeapLow.currentSize)
if HeapHigh.currentSize == 0:
HeapHigh.insert(i)
addMedian()
elif HeapHigh.currentSize == HeapLow.currentSize:
if i >= HeapHigh.heapList[1]:
HeapHigh.insert(i)
addMedian()
else:
HeapLow.insert(-i)
j = HeapLow.extractMin()
HeapHigh.insert(-j)
addMedian()
elif HeapHigh.currentSize > HeapLow.currentSize:
if i >= HeapHigh.heapList[1]:
HeapHigh.insert(i)
j = HeapHigh.extractMin()
HeapLow.insert(-j)
addAverage()
else:
HeapLow.insert(-i)
addAverage()
def modsum(L, m):
result = 0
for number in L:
result = (result+number)%m
return result
print(modsum(medians, 10000), count, len(medians))
|
f9f31d91cb500ed5bd23b7d6998881492079f1dd | drdarshan/pytorch-dist | /torch/nn/modules/dropout.py | 3,955 | 3.796875 | 4 | from .module import Module
class Dropout(Module):
"""Randomly zeroes some of the elements of the input tensor.
The elements to zero are randomized on every forward call.
Args:
p: probability of an element to be zeroed. Default: 0.5
inplace: If set to True, will do this operation in-place. Default: false
Input Shape: Any : Input can be of any shape
Output Shape:Same : Output is of the same shape as input
Examples:
>>> m = nn.Dropout(p=0.2)
>>> input = autograd.Variable(torch.randn(20, 16))
>>> output = m(input)
"""
def __init__(self, p=0.5, inplace=False):
super(Dropout, self).__init__()
self.p = p
self.inplace = inplace
def forward(self, input):
return self._backend.Dropout(self.p, self.training, self.inplace)(input)
def __repr__(self):
inplace_str = ', inplace' if self.inplace else ''
return self.__class__.__name__ + ' (' \
+ 'p = ' + str(self.p) \
+ inplace_str + ')'
class Dropout2d(Module):
"""Randomly zeroes whole channels of the input tensor.
The input is 4D (batch x channels, height, width) and each channel
is of size (1, height, width).
The channels to zero are randomized on every forward call.
Usually the input comes from Conv2d modules.
As described in the paper "Efficient Object Localization Using Convolutional
Networks" (http:arxiv.org/abs/1411.4280), if adjacent pixels within
feature maps are strongly correlated (as is normally the case in early
convolution layers) then iid dropout will not regularize the activations
and will otherwise just result in an effective learning rate decrease.
In this case, nn.Dropout2d will help promote independence between
feature maps and should be used instead.
Args:
p: probability of an element to be zeroed. Default: 0.5
inplace: If set to True, will do this operation in-place. Default: false
Input Shape: [*, *, *, *] : Input can be of any sizes of 4D shape
Output Shape:Same : Output is of the same shape as input
Examples:
>>> m = nn.Dropout2d(p=0.2)
>>> input = autograd.Variable(torch.randn(20, 16, 32, 32))
>>> output = m(input)
"""
def __init__(self, p=0.5, inplace=False):
super(Dropout2d, self).__init__()
self.p = p
self.inplace = inplace
def forward(self, input):
return self._backend.Dropout2d(self.p, self.training, self.inplace)(input)
def __repr__(self):
inplace_str=', inplace' if self.inplace else ''
return self.__class__.__name__ + ' (' \
+ 'p=' + str(self.p) \
+ inplace_str + ')'
class Dropout3d(Module):
"""Randomly zeroes whole channels of the input tensor.
The input is 5D (batch x channels, depth, height, width) and each channel
is of size (1, depth, height, width).
The channels to zero are randomized on every forward call.
Usually the input comes from Conv3d modules.
Args:
p: probability of an element to be zeroed. Default: 0.5
inplace: If set to True, will do this operation in-place. Default: false
Input Shape: [*, *, *, *, *] : Input can be of any sizes of 5D shape
Output Shape:Same : Output is of the same shape as input
Examples:
>>> m = nn.Dropout3d(p=0.2)
>>> input = autograd.Variable(torch.randn(20, 16, 4, 32, 32))
>>> output = m(input)
"""
def __init__(self, p=0.5, inplace=False):
super(Dropout3d, self).__init__()
self.p = p
self.inplace = inplace
def forward(self, input):
return self._backend.Dropout3d(self.p, self.training, self.inplace)(input)
def __repr__(self):
inplace_str=', inplace' if self.inplace else ''
return self.__class__.__name__ + ' (' \
+ 'p=' + str(self.p) \
+ inplace_str + ')'
|
afc298e2a88e57d31ab70f24214cfdbf1eeeccd6 | akhilsai0099/Python-Practice | /Sorting_algorithms/insertion_sort.py | 275 | 4.125 | 4 | def insertion_sort(array):
for i in range(1,len(array)):
key = array[i]
j = i -1
while j >=0 and key < array[j]:
array[j+1]= array[j]
j -= 1
array[j+1] = key
return array
print(insertion_sort([12,1,53,21,2]))
|
f05dc9720cca147c4bf0deae25ec9165125b329f | mines-nancy-tcss5ac-2018/td1-ManonLanzeroti | /TD1 Pb 55 Lanzeroti.py | 1,385 | 3.578125 | 4 | def rev(chaine): #inverse la chaine de caractre
rev_chaine = ""
for lettre in chaine:
rev_chaine = lettre + rev_chaine
return rev_chaine
def nombreinverse(nombre): #renvoie le nombre dont les chiffres sont inverss
chaine = str(nombre)
rev_chaine = ""
for lettre in chaine:
rev_chaine = lettre + rev_chaine
return int(rev_chaine)
def palindrome(n): #vrifie si un nombre est un palindrome
ch1, ch2 = "", ""
ch_n = str(n)
revch_n = rev(ch_n)
s = n + int(revch_n) #on fait la somme de n et son invers
ch_s = str(s)
revch_s = rev(ch_s)
l=len(ch_s)
for i in range(l//2):
ch1 += ch_s[i]
ch2 += revch_s[i]
if ch1 == ch2: return True
else: return False
def Lychrel(nombre): #renvoie True si le nombre considr est un nombre de Lychrel et renvoie False sinon
j=0
nb = nombre
p = palindrome(nb)
while p == False and j < 50:
nbinverse = nombreinverse(nb)
nb = nb + nbinverse
p = palindrome(nb)
j += 1
if j==50: return True
else: return False
#dtermine le nombre de nombres de Lychrel plus petits que n
def solve(n):
i=0
for nombre in range(n +1):
if Lychrel(nombre) == True:
i+=1
return i
print(solve(10000))
|
fd9b1a9942ce87493299fabde43f8fcbd457c470 | August1s/LeetCode | /剑指Offer/No16数值的整数次方.py | 496 | 3.671875 | 4 |
# 直接循环会超时。复杂度O(n)
# 注意到,pow(3,6) = pow(9,3) = 9*pow(81*1)
# 也就是 pow(x, n) = pow(x*x, n//2) 或 x * pow(x*x, n//2)
# 时间复杂度是O(logn)
def myPow(self, x: float, n: int) -> float:
def Rec(i, j):
if j==0:
return 1
if j==1:
return i
if j==-1:
return 1/i
if j%2==0:
return Rec(i*i, j//2)
else:
return i*Rec(i*i, j//2)
return Rec(x,n) |
4424048024d63670c23128cf7d333da6a4a79e5d | edwardmoradian/Python-Basics | /String Processing - Using the In Operator.py | 175 | 4.09375 | 4 | ## In and Not In
def main():
s = "How now brown cow?"
if "now" in s:
print("yes, now is in s")
if "now" not in s:
print("It is not is s") |
b4594bb3cfad7130ca33a6bcbe4bed9f160bf6fa | maston14/Leetcode_PY | /Base 7 504.py | 783 | 3.625 | 4 | # Origin
class Solution(object):
def convertToBase7(self, num):
"""
:type num: int
:rtype: str
"""
ret = ''
neg = num < 0
num = abs(num)
while num != 0:
bit = num % 7
num = num / 7
ret = str(bit) + ret
if neg:
ret = '-' + ret
if ret == '':
ret = '0'
return ret
# Better
class Solution2(object):
def convertToBase7(self, num):
"""
:type num: int
:rtype: str
"""
if num == 0:
return '0'
ret = ''
pos = num > 0
num = abs(num)
while num != 0:
ret = str(num % 7) + ret
num //= 7
return ret if pos else '-' + ret |
e5014b5b0881eb6039d6c7772a52123d3758d9a1 | Jieken/PythonCoding | /DataStructures/Heap/Heap.py | 1,652 | 4.09375 | 4 | class Heap:
def __init__(self):
self.__data = []
self.__weight = 0
self.__size = 0
def __swap(self, r, l):
temp = self.__data[r]
self.__data[r] = self.__data[l]
self.__data[l] = temp
def insert(self, item):
self.__data.append(item)
self.__shiftUp(self.__size)
self.__size += 1
# 索引从0开始
# 2*i+1 左节点 2*i+2 右节点
# 父节点 (i-1)//2
# 最后一个非叶子节点为 (size-2)//2
# 上浮过程
def __shiftUp(self, index):
if index == 0:
return
while (index > 0 & self.__data[(index - 1) // 2] < self.__data[index]):
self.__swap((index - 1) // 2, index)
index = (index - 1) // 2
def deleted(self):
if (self.__size == 0):
print("the heap is empty")
return
self.__swap(0, self.__size - 1)
self.__shiftdown(0)
self.__data.pop()
self.__size -= 1
def heapprint(self):
for i in self.__data:
print(i, end="->")
def __shiftdown(self, index):
while (index < (self.__size - 2) // 2):
child = index * 2 + 1
if (self.__data[index * 2 + 1] < self.__data[index * 2 + 2]):
child += 1
if self.__data[index] < self.__data[child]:
self.__swap(index, child)
index = child
else:
break
heap = Heap()
for i in range(1, 1001):
heap.insert(i)
for i in range(1, 1001):
heap.deleted()
heap.heapprint()
|
259305de1ed58dbeff583353cd012ef41aea4707 | kapilaramji/python_problems | /20_string_match.py | 336 | 3.765625 | 4 | Given 2 strings, a and b, return the number of the positions where they contain the same length 2 substring. So "xxcaazz" and "xxbaaz" yields 3, since the "xx", "aa", and "az" substrings appear in the same place in both strings.
string_match('xxcaazz', 'xxbaaz') → 3
string_match('abc', 'abc') → 2
string_match('abc', 'axc') → 0 |
22f01c6ba250432e2aff9090695a32bafc2d1e1f | maggieee/code-challenges | /reverse-integer.py | 291 | 3.609375 | 4 | class Solution:
def reverse(self, x: int) -> int:
strng = str(x)
negative = False
if strng[0] == "-":
negative = True
if negative == True:
return int(strng[1::-1])*(-1)
else:
return int(strng[::-1]) |
5da8682f81e769e5d76f06777ac9aa14f4f5bb85 | Tyrannas/ComputationIntelligence | /assignment02/nn_regression_plot.py | 5,243 | 3.875 | 4 | import matplotlib.pyplot as plt
import numpy as np
"""
Computational Intelligence TU - Graz
Assignment 2: Neural networks
Part 1: Regression with neural networks
This file contains functions for plotting.
"""
__author__ = 'bellec,subramoney'
def plot_mse_vs_neurons(train_mses, test_mses, n_hidden_neurons_list):
"""
Plot the mean squared error as a function of the number of hidden neurons.
:param train_mses: Array of training MSE of shape n_hidden x n_seeds
:param test_mses: Array of testing MSE of shape n_hidden x n_seeds
:param n_hidden_neurons_list: List containing number of hidden neurons
:return:
"""
plt.figure(figsize=(10, 7))
plt.title("Variation of testing and training MSE with number of neurons in the hidden layer")
for data,name,color in zip([train_mses,test_mses],["Training MSE","Testing MSE"],['orange','blue']):
m = data.mean(axis=1)
s = data.std(axis=1)
plt.plot(n_hidden_neurons_list, m, 'o', linestyle='-', label=name, color=color)
plt.fill_between(n_hidden_neurons_list, m-s,m+s,color=color,alpha=.2)
plt.xlabel("Number of neurons in the hidden layer")
plt.ylabel("MSE")
# plt.semilogx()
plt.legend()
plt.show()
def plot_mse_vs_iterations(train_mses, test_mses, n_iterations, hidden_neuron_list):
"""
Plot the mean squared errors as a function of n_iterations
:param train_mses: Array of training MSE of shape (len(hidden_neuron_list),n_iterations)
:param test_mses: Array of testing MSE of shape (len(hidden_neuron_list),n_iterations)
:param n_iterations: List of number of iterations that produced the above MSEs
:param hidden_neuron_list: The number of hidden neurons used for the above experiment (Used only for the title of the plot)
:return:
"""
plt.figure()
plt.title("Variation of MSE across iterations".format(hidden_neuron_list))
color = ['blue','orange','red','green','purple']
for k_hid,n_hid in enumerate(hidden_neuron_list):
for data,name,ls in zip([train_mses[k_hid],test_mses[k_hid,]],['Train','Test'],['dashed','solid']):
plt.plot(range(n_iterations), data, label=name + ' n_h = {}'.format(n_hid), linestyle=ls, color=color[k_hid])
plt.xlim([0,n_iterations])
plt.legend()
plt.xlabel("Number of iterations")
plt.ylabel("MSE")
plt.minorticks_on()
plt.show()
def plot_bars_early_stopping_mse_comparison(test_mse_end,test_mse_early_stopping,test_mse_ideal):
"""
Bar plot for the comparison of MSEs
:param test_mse_end: List of test errors after 2000 iterations. One value for each random seed
:param test_mse_early_stopping: List of test errors when validation error is minimal. One value for each random seed
:param test_mse_ideal: List of ideal test errors when test error is minimal. One value for each random seed
"""
n_groups = 3
index = np.arange(n_groups)
plt.figure()
plt.title("Efficacy of early stopping")
height = list(map(np.mean, [test_mse_end,test_mse_early_stopping,test_mse_ideal]))
stds = list(map(np.std, [test_mse_end,test_mse_early_stopping,test_mse_ideal]))
plt.bar(index, align='center', height=height, width=0.8, yerr=stds)
plt.xticks(index, ['Last iteration', 'Early Stopping', 'Ideal'])
plt.ylabel("MSE")
plt.ylim([np.min(height) - 2 * np.max(stds), np.max(height) + 2 * np.max(stds)])
plt.minorticks_on()
plt.show()
def plot_mse_vs_alpha(train_mses, test_mses, alphas):
"""
Plot the mean squared errors as afunction of the alphas
:param train_mses: Array of training MSE, of shape (n_alphas x n_seed)
:param test_mses: Array of testing MSE, of shape (n_alphas x n_seed)
:param alphas: List of alpha values used
:return:
"""
plt.figure(figsize=(10, 7))
plt.title("Variation of testing and training MSE with regularization parameter")
for data,name,color in zip([train_mses,test_mses],["Training MSE","Testing MSE"],['orange','blue']):
m = data.mean(axis=1)
s = data.std(axis=1)
plt.plot(alphas, m, 'o', linestyle='-', label=name, color=color)
plt.fill_between(alphas, m-s,m+s,color=color,alpha=.2)
plt.semilogx()
plt.xlabel("Alphas")
plt.ylabel("MSE")
# plt.semilogx()
plt.legend()
plt.show()
def plot_learned_function(n_hidden,x_train, y_train, y_pred_train, x_test, y_test, y_pred_test):
'''
Plot the data and the learnt functions.
:param n_hidden: int, number of hidden neurons
:param x_train:
:param y_train:
:param y_pred_train: array of size as y_train, but representing the estimator prediction
:param x_test:
:param y_test:
:param y_pred_test: array of size as y_test, but representing the estimator prediction
:return:
'''
plt.figure(figsize=(10, 7))
ax = plt.subplot()
ax.set_title(str(n_hidden) + ' hidden neurons')
ax.scatter(x=x_test,y=y_test,marker='x',color='red',label='Testing data')
ax.scatter(x=x_train,y=y_train,marker='o',color='blue',label='Training data')
ax.plot(x_test, y_pred_test, color='black', lw=2, label='Prediction')
ax.set_xlabel("x")
ax.set_ylabel("y")
plt.legend()
plt.show() |
1bc5dc3db882420f67180dbd9eb361a111299bbc | PigsGoMoo/LeetCode | /multiply-strings/multiply-strings.py | 553 | 3.5625 | 4 | class Solution:
def multiply(self, num1: str, num2: str) -> str:
res = 0
carry1 = 1
# Based on how we multiply normally. 32 * 26 = 6 * 2 + 6 * 30 + 20 * 2 + 20 * 30
# Or: (6 * 2) + (6 * 3 * 10) + (2 * 10 * 2) + (2 * 10 * 3 * 10)
for i in num1[::-1]:
carry2 = 1
for j in num2[::-1]:
res += int(i) * int(j) * carry1 * carry2
carry2 *= 10
carry1 *= 10
return str(res) |
63092961537c235c915a0584b4128f0478bf8519 | lucianohdonato/aulas_python3_basico | /netspeedy.py | 291 | 4 | 4 | #!/usr/bin/python3
#-*- coding: UTF-8 -*-
tamanho = float(input("Qual o tamanho do arquivo? (em MiB)"))
velocidade = float(input("Qual a velocidade do Link de internet? (em Mbps)"))
speedy = (tamanho * 8) / velocidade
print('Seu tempo de download estimnado é de' , speedy , 'segundos.')
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.