blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
b920019199c9638f6f143b3d70c0da6c70a4c0ca | bmolenaar/MiscProjects | /GuessingGame.py | 1,720 | 4.1875 | 4 | from random import randrange
#Get the player's name from input and print greeting message
plyrName = str(input("Please enter your name: "))
print("Hi, " + plyrName + "!")
numToGuess = randrange(1, 101)
numOfGuesses = randrange(1, 7)
#Function to verify that the player's guess is within the bounds and display the appropriate message and call
#the read/write functions
def checkGuess():
amtOfGuesses = 0
win = ""
while amtOfGuesses <= numOfGuesses:
guess = int(input("Guess a whole number between 1 and 100!"))
if guess < 100 and guess > 0:
if guess < numToGuess:
print("Too low, bro. You have " + str((numOfGuesses - amtOfGuesses)) + " guesses left!")
win = "loss"
elif guess > numToGuess:
print("Too high, guy. You have " + str((numOfGuesses - amtOfGuesses)) + " guesses left!")
win = "loss"
else:
print("You guessed it!")
amtOfGuesses += 1
win = "win"
break
else:
print("Your number is out of range")
amtOfGuesses += 1
writeScores(plyrName, win, amtOfGuesses)
print(readScores())
#Function to write the player's name, result and amount of guesses to a text file
def writeScores(name, result, guesses):
txt = open("Statistics.txt", "a")
txt.write(str(name) + " | " + str(result) + " | " + str(guesses) + "\n")
txt.close()
#Function to read the results written to the text file
def readScores():
txt = open("Statistics.txt", "r")
scores = txt.read()
return scores
checkGuess()
input("Press enter to close") |
80dcd83053f2a9ec1e937e90549bd5f974f794ef | robert1ridley/chinese-segmentation-tool | /helper_methods/dictionary_methods.py | 823 | 3.53125 | 4 | def createDictionary(filename):
word_dict = {}
dataFile = open(filename, "r", encoding='utf-8')
for row in dataFile:
row = row.split(',')
word_dict[row[0]] = row[0]
return word_dict
def is_word_in_dictionary(word, chinese_dictionary):
dictSearch = chinese_dictionary.get(word, False)
if dictSearch:
return True
return False
def remove_last_char(word):
word_with_final_char_removed = word[:-1]
return word_with_final_char_removed
def remove_first_char(word):
word_with_first_char_removed = word[1:]
return word_with_first_char_removed
def remove_first_word(term_to_remove, full_string):
full_string = full_string[len(term_to_remove):]
return full_string
def remove_last_word(term_to_remove, full_string):
full_string = full_string[:-len(term_to_remove)]
return full_string |
525bea426bd338a87b1c0b2a76c833fd2eedae49 | CHENHERNGSHYUE/pythonTest | /class.py | 566 | 3.578125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Jan 5 15:33:44 2019
@author: chenmth
"""
class Calculator: #class名稱第一個字母要大寫
Name = 'kenny'
def add_function(a,b):
return a+b
def minus_function(a,b):
return a-b
def times_function(a,b):
return a*b
def divide_function(a,b):
return a//b
add = Calculator.add_function(10,10)
minus = Calculator.minus_function(10,10)
times = Calculator.times_function(10,10)
divide = Calculator.divide_function(10,10)
print(add)
print(minus)
print(times)
print(divide) |
377bd903a96912bcfc9d8bb346f103b210dc1bde | DanielMalheiros/geekuniversity_programacao_em_python_essencial | /Exercicios/secao07_colecoes_python_parte1/exercicio31.py | 694 | 4.03125 | 4 | """Faça um programa que leia dois vetores de 10 elementos. Crie um vetor que seja a união entre
os dois vetores anteriores, ou seja, que contenha os números dos dois vetores. Não deve conter números
repetidos."""
contador = 0
vetor1 = []
vetor2 = []
while contador < 10:
valor = int(input(f"Digite um valor para o primeiro vetor ({contador+1}/10): "))
vetor1.append(valor)
contador += 1
contador = 0
while contador < 10:
valor = int(input(f"Digite um valor para o segundo vetor ({contador+1}/10): "))
vetor2.append(valor)
contador += 1
set1 = set(vetor1)
set2 = set(vetor2)
print(f"A união entre os valores do primeiro e segundo vetor é {set1.union(set2)}")
|
3b8a55850ff47194987a7f125df387cb13048502 | yshshadow/Leetcode | /101-150/108.py | 1,484 | 4.09375 | 4 | # Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
#
# For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
#
# Example:
#
# Given the sorted array: [-10,-3,0,5,9],
#
# One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST:
#
# 0
# / \
# -3 9
# / /
# -10 5
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def sortedArrayToBST(self, nums):
"""
:type nums: List[int]
:rtype: TreeNode
"""
if not nums:
return None
mid = (0 + len(nums)-1) // 2
root = TreeNode(nums[mid])
self.helper(nums, 0, mid - 1, root, True)
self.helper(nums, mid + 1, len(nums)-1, root, False)
return root
def helper(self, nums, start, end, root, lchild):
if start > end:
return
mid = (start + end) // 2
node = TreeNode(nums[mid])
if lchild:
root.left = node
else:
root.right = node
self.helper(nums, start, mid - 1, node, True)
self.helper(nums, mid + 1, end, node, False)
s = Solution()
nums = [-10, -3, 0, 5, 9]
root = s.sortedArrayToBST(nums)
print(root.val)
|
9516f43f295325efd75821d8f455964b6b7b5f20 | Rinkikumari19/codechef_questions | /min_fifteen_ten.py | 98 | 3.578125 | 4 | a=-15
b=-(a)
print(b)
while a<=-10:
print(a)
b=b-1
a=-(b)
# it will print -15 to -10 |
2ad98fc70aadafa9a994960bc30b85b3684e3d47 | rafaelperazzo/programacao-web | /moodledata/vpl_data/74/usersdata/165/34951/submittedfiles/lecker.py | 1,080 | 4.09375 | 4 | # -*- coding: utf-8 -*-
import math
a=float(input('digite um numero:'))
b=float(input('digite um numero:'))
c=float(input('digite um numero:'))
d=float(input('digite um numero:'))
if a!=b!=c!=d:
if a<b>c:
if c>d:
print('S')
else:
print('N')
elif b<c>d:
if a<b:
print('S')
else:
print('N')
elif a>b:
if c<b and d<b:
print('S')
else:
print('N')
elif d>c:
if a<c and b<c:
print('S')
else:
print('N')
else:
if a!=b and a!=c and a!=d:
if a>b and b>=c and b>=d:
print('S')
else:
print('n')
elif b!=a and b!=c and b!=d:
if a<b>c and d<=c:
print('S')
else:
print('N')
elif c!=a and c!=b and c!=d:
if b<c>d and a<=b:
print('S')
else:
print('N')
elif d!=a and d!=b and d!=c:
if d>c and c>=b>=a:
print('S')
else:
print('N')
|
d3d479ad1bf3fd71635e464af871cff899ca2ca8 | majsylw/Introduction-to-programming-in-python | /Laboratory 11/5. Pole kwadratu.py | 749 | 4.21875 | 4 | '''
Napisz program, wyznaczający pole kwadratu. Program jako dane (długość boku)
powinien przyjmować wyłącznie liczby dodatnie. Jeśli użytkownik poda liczbę
niedodatnią, to powinien zostać poinformowany, że wymagana jest
liczba dodatnia i poproszony o wykonanie kolejnej próby. Próbę wczytywania
liczby powtarzamy dopóty, dopóki użytkownik nie poda poprawnej odpowiedzi.
W przypadku poprawnej odpowiedzi wyświetl na ekranie wyliczone pole kwadratu.
'''
def main():
bok = float(input("Podaj długość boku kwadratu: "))
while bok <= 0:
bok = float(input("Podałeś niepoprawną wartość, podana liczba musi być dodatnia. Podaj długość boku kwadratu: "))
print("Pole kwadratu wyniesie: ", bok**2)
main()
|
db6692e34dddec95706a5a47e1ff280394086edf | dusunge27/python | /game.py | 2,790 | 4.09375 | 4 | from sys import exit
def gold_room():
print "This room is full of gold. How much do you take?"
choice = raw_input("Write any number from 0 to 100> ") # variable
if "0" in choice or "1" in choice: # could be 0, 1, 10, 11:19, 20, 21, 30, 31, 40, 41, 50, 51, etc.
how_much = int(choice) # variable
else:
dead("Man, learn to type a number.") # launch function dead
if how_much < 50:
print "Nice, you're not greedy, you win!"
exit(0) # launch system function exit
else:
dead("You greedy bastard!") # launch function dead
def bear_room():
print "There is bear here."
print "The bear has a bunch of honey."
print "The fat bear is in front of another door."
print "How are you going to move the bear?"
bear_moved = False # variable
while True: # infinite loop, run until it finds a right answer
choice = raw_input("Write 'take honey', 'taunt bear' or 'open door'> ") # variable
if choice == "take honey": # variable check
dead("The bear looks at you then slaps your face off.") # launch function dead
elif choice == "taunt bear" and not bear_moved: # double variables check
print "The bear has moved from the door. You can go thought it now."
bear_moved = True # change the variable
elif choice == "taunt bear" and bear_moved:
dead("The bear gets pissed off and chews your leg off.")
elif choice == "open door" and bear_moved: # variable check
gold_room() # launch function gold_room
else:
print "I got no idea what that means."
def cthulhu_room():
print "Here you see the great evil Cthulhu."
print "He, it, whatever stares at you and you go insane."
print "Do you flee your life or eat your head?"
choice = raw_input("Write 'flee' or 'head'> ") # variable
if "flee" in choice: # variable check
start() # launch function start
elif "head" in choice:
dead("Well that was tasty!")
else:
cthulhu_room() # launch function
def dead(why):
print why, "Good job!"
exit(0) # launch system function exit
# exit(0) is neutral
# exit(1) is an error, could be a useful warning
# exit(2) or others like exit(100) are other warnings, or different messages
def start():
print "You are in a dark room."
print "There is a door to your right and left."
print "Which one do you take: left or right?"
choice = raw_input("Write 'left' or 'right'> ") # variable
if choice == "left": # variable check, exact
bear_room() # launch function bear_room
elif choice == "right": # variable check, exact
cthulhu_room()
else:
dead("You stumble around the room until you starve.")
|
c74451954a4010ff2aaa597743079c9b29e457ad | eriamavro/python-recipe-src | /src/095/recipe_095_01.py | 425 | 3.5625 | 4 | def div_num(a, b):
try:
val = a / b
print(val)
except TypeError:
print("演算できない引数が指定されました。処理を行いません。")
except ZeroDivisionError:
print("ゼロで除算を行おうとしています。処理を行いません。")
except Exception:
print("不明な例外が発生しました。")
div_num("abcdefg", 2)
div_num(7, 0)
|
fad7c7ee0477b0e54494631b87b84330497b242e | natallia-bonadia/dev-studies | /Lets Code/Coding Tank - Python/Python/Lets Code/Aula 16 - Dicionários - Parte 2.py | 4,893 | 4.15625 | 4 | ### EXERCÍCIOS AULA 16 - DICIONÁRIOS (PARTE 2) ###
'''
1) Faça um script usando dicionários que peça para um usuário digitar um número entre 0 e 9 e imprima o número por extenso.
Exemplo
input: 3
output: três
d = {0: 'zero', 1: 'um', 2: 'dois', 3: 'três', 4: 'quatro', 5:'cinco', 6: 'seis', 7: 'sete', 8: 'oito', 9: 'nove'}
n = int(input('Digite um número de 0 a 9: '))
print(f'Por extenso esse número é \033[1m{d[n]}\033[m.')
----------
2) Faça um script que leia uma frase do usuário e use um dicionário que apresente as letras
e a frequência de aparição desta letra na frase.
Exemplo
input: coding tank
output: {'c':1, 'o':1, 'd':1, 'i':1, 'n':2, 'g':1, 't':1, 'a':1, 'k':1}
dicionario = {}
frase = str(input('Digite uma frase qualquer: '))
frase_minuscula = frase.lower()
frase_semespaço = frase_minuscula.replace(' ', '')
for letra in frase_semespaço:
dic_quantidade = frase_semespaço.count(letra)
dic_letra = letra
dicionario.update({dic_letra:dic_quantidade})
print(dicionario)
----------
3) Faça um script que leia uma frase do usuário e use um dicionário que apresente as palavras
e a frequêcia de sua aparição na frase.
Exemplo
input: bom dia dia
output: {'bom':1 'dia':2}
dicionario = {}
frase = str(input('Digite uma frase qualquer: '))
frase_minuscula = frase.lower()
lista = frase_minuscula.split()
for palavra in lista:
dic_quantidade = lista.count(palavra)
dic_palavra = palavra
dicionario.update({dic_palavra:dic_quantidade})
print(dicionario)
----------
4) Dado o dicionário abaixo, descubra as médias de "homework", "quizzes" e "tests" dos três alunos.
Ao final, apresente quem foi aprovado (caso média de "tests" maior que 65)
lloyd = {
"name": "Lloyd",
"homework": [90.0,97.0,75.0,92.0],
"quizzes": [88.0,40.0,94.0],
"tests": [75.0,90.0]
}
alice = {
"name": "Alice",
"homework": [100.0, 92.0, 98.0, 100.0],
"quizzes": [82.0, 83.0, 91.0],
"tests": [89.0, 97.0]
}
tyler = {
"name": "Tyler",
"homework": [0.0, 87.0, 75.0, 22.0],
"quizzes": [0.0, 75.0, 78.0],
"tests": [100.0, 100.0]
}
print('-'*30)
media_lloyd = (sum(lloyd["homework"])/len(lloyd["homework"]) + \
sum(lloyd["quizzes"])/len(lloyd["quizzes"]) + \
sum(lloyd["tests"])/len(lloyd["tests"]))/3
if media_lloyd > 65:
a = 'APROVADO'
else:
a = 'REPROVADO'
print(f'A média de Lloyd é {media_lloyd:.2f} e o aluno está {a}.')
print('-'*30)
media_alice = (sum(alice["homework"])/len(alice["homework"]) + \
sum(alice["quizzes"])/len(alice["quizzes"]) + \
sum(alice["tests"])/len(alice["tests"]))/3
if media_alice > 65:
a = 'APROVADA'
else:
a = 'REPROVADA'
print(f'A média de Alice é {media_alice:.2f} e a aluna está {a}.')
print('-'*30)
media_tyler = (sum(tyler["homework"])/len(tyler["homework"]) + \
sum(tyler["quizzes"])/len(tyler["quizzes"]) + \
sum(tyler["tests"])/len(tyler["tests"]))/3
if media_tyler > 65:
a = 'APROVADO'
else:
a = 'REPROVADO'
print(f'A média de Tyler é {media_tyler:.2f} e o aluno está {a}.')
print('-'*30)
----------
5) Faça um programa de cadastro de clientes. O usuário pode escolher entre 1 - Cadastrar,
2 - Visualizar os cadastrados e 3 - Buscar um cadastro específico.
Se o usuário digitar 1, o programa deve cadastrar um novo usuário inserindo cpf, nome e email
e deve guardar esse cadastro em um dicionário cuja chave será o CPF da pessoa.
Quando o usuário digitar 2, o programa deve imprimir os usuários cadastrados; e se o usuário
digitar 3, procure um determinado usuário pelo seu CPF.
Seu sistema deve encerrar somente quando o usuário digitar 4.
Exemplo do dicionário:
‘987.654.321-00’: {‘nome’: Maria, ‘idade’: 20, ‘email’ : maria@ig.com}
# CABEÇALHO E OPÇÃO
print('='*35)
print(f'{"CADASTRO DE CLIENTES":^35}')
print('='*35)
print('[ 1 ] Cadastrar \n[ 2 ] Visualizar os cadastros \n[ 3 ] Buscar um cadastro \n[ 4 ] Finalizar')
opçao = int(input('> Escolha uma das opções acima: '))
# LISTA E DICIONÁRIO UTILIZADOS
cadastro = list()
dados = dict()
while opçao != 4:
if opçao == 1:
dados.clear()
dados['CPF'] = int(input('CPF: '))
dados['Nome'] = str(input('Nome: ')).strip().upper()
dados['Idade'] = int(input('Idade: '))
dados['E-mail'] = str(input('E-mail: ')).strip().lower()
cadastro.append(dados.copy())
print('>> CADASTRO ATUALIZADO COM SUCESSO <<')
if opçao == 2:
print(cadastro)
if opçao == 3:
busca = int(input('Qual CPF deseja pesquisar? '))
print(dados[busca])
print()
print('='*35)
print(f'{"CADASTRO DE CLIENTES":^35}')
print('='*35)
print('[ 1 ] Cadastrar \n[ 2 ] Visualizar os cadastros \n[ 3 ] Buscar um cadastro \n[ 4 ] Finalizar')
opçao = int(input('> Escolha uma das opções acima: '))
print('Sessão Finalizada.')
''' |
8d51cf117a79dc3bcfe3faf2776d9277122a1e1a | ramakrishnan1993/PowerGrASP | /powergrasp/edge_filtering.py | 1,632 | 3.625 | 4 | """Routines implementing edge filtering on input graphs,
knowing the bounds on the size of the motif to search in it.
All routines follow the following interface:
- arguments are the graph and the bounds
- yield valid edges as pairs of nodes
"""
import networkx as nx
def for_biclique(graph:nx.Graph, lowerbound:int, upperbound:int) -> [(str, str)]:
"""
Remove any edge that the product of its nodes degrees is inferior to lowerbound.
"""
def ok_to_go(edge:tuple) -> bool:
one, two = edge
degone, degtwo = map(graph.degree, edge)
return degone * degtwo >= lowerbound
for edge in graph.edges:
if ok_to_go(edge):
yield edge
def for_star(graph:nx.Graph, lowerbound:int, upperbound:int) -> [(str, str)]:
"""
"""
def ok_to_go(edge:tuple) -> bool:
one, two = edge
degone, degtwo = map(graph.degree, edge)
return not all((
degone < lowerbound,
degtwo < lowerbound,
))
for edge in graph.edges:
if ok_to_go(edge):
yield edge
def for_clique(graph:nx.Graph, lowerbound:int, upperbound:int) -> [(str, str)]:
"""
Remove an edge when one participating node has a clustering coefficient equal to 0.
"""
clusterings = {} # node -> clustering coefficient
def clustering_of(node:str) -> float:
if node in clusterings:
return clusterings[node]
else:
return clusterings.setdefault(node, nx.clustering(graph, node))
for edge in graph.edges:
if any(clustering_of(node) > 0. for node in edge):
yield edge
|
1bf7a3764b6ed326c539c8d6141dc8becbfd1be3 | BlaiseMarvin/Face-detection-and-recognition-using-facenet | /deepLearningforFaceDetection.py | 341 | 3.5 | 4 | #face detection using mtcnn on a photograph
from matplotlib import pyplot
from mtcnn.mtcnn import MTCNN
#load image from file
filename='test1.jpg'
pixels=pyplot.imread(filename)
#create the detector using default weights
detector=MTCNN()
#detect faces in the image
faces=detector.detect_faces(pixels)
for face in faces:
print(face)
|
56cbbae5a4bb3f8518ff637d34b556f941aae957 | shin99921/Python- | /chapter3/chapter3.2.py | 1,165 | 3.765625 | 4 | # else 문
print("1","-"*50)
num = int(input("input number: "))
if num%2 == 0:
print("{}는(은) 짝수 입니다.".format(num))
else:
print("{}는(은) 홀수 입니다.".format(num))
print("\n")
# elif 구문
print("2","-"*50)
import datetime
now = datetime.datetime.now()
month = now.month
if 3 <= month <=5:
print("지금은 봄")
elif 6 <= month <=8:
print("지금은 여름")
elif 9 <= month <=11:
print("지금은 가을")
else:
print("지금은 겨울")
print("\n")
# 0과 빈문자열은 False 로 나온다.
print("3","-"*50)
if 0:
print("0은 True로 변환됩니다. ")
else:
print("0은 False로 변환됩니다.")
print()
if 0:
print("빈 문자열은 True로 변환됩니다. ")
else:
print("빈 문자열은 False로 변환됩니다.")
print("\n")
# 프로그램 중간에 pass 를 입력해 놓으면 그냥 지나간다.
print("4","-"*50)
number = int(input("input : "))
if number > 0:
pass
else:
pass
print("\n")
# raise 를 사용하면 강제로 오류를 발생시킨다.
print("5","-"*50)
number = int(input("input : "))
if number > 0:
raise
else:
raise
print("\n")
|
50bf945f0caf3b1132dab3e5ee1da003d58dce8e | andresbernaciak/project_euler | /problem2.py | 907 | 3.828125 | 4 | #projecteuler.net
#
#problem2
#========
#
#Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
#
#1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
#
#By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.
i = 1
f_series = [1,2]
f_number = 0
sum_even_numbers = 2
while f_number <= 4000000:
i += 1
f_number = (f_series[i-1]+f_series[i-2])
f_series.append(f_number)
if f_number % 2 == 0:
sum_even_numbers += f_number
print(sum_even_numbers)
# another way by generating only the even fibonacci numbers
f = 0
f_2 = 2
f_1 = 8
accum = f_1 + f_2
while True:
f = f_1*4 + f_2
if f < 4000000:
accum += f
f_2, f_1 = f_1, f
else:
break
print(accum)
|
5cb7b4a840db8392ff247d0afe70f1bd21fcf6c3 | zaid-sayyed602/Python-OOPS-concept | /vehicle_class.py | 793 | 3.796875 | 4 |
class vehicle:
def asktype(self):
self.name=input("Enter the name of the vehicle\n")
self.vehicletype=input("Enter the type of the vehicle\n")
self.colour=input("Enter the colour of the vehicle\n")
self.model=input("Enter the model of the vehicle\n")
def print(self):
print(self.name)
print(self.vehicletype)
print(self.colour)
print(self.model)
def updatename(self):
self.name=input("Enter the name of the vehicle\n")
def updatetype(self):
self.vehicletype=input("Enter the type of the vehicle\n")
def updatecolour(self):
self.colour=input("Enter the colour of the vehicle\n")
def updatemodel(self):
self.model=input("Enter the model of the vehicle\n
|
5aac15c9b237e2a7a265e273ffd74ba1ec79cb24 | NikiDimov/SoftUni-Python-Fundamentals | /list_advanced/the office.py | 533 | 3.671875 | 4 | employees_happiness = [int(el) for el in input().split()]
factor = int(input())
factored_happiness = list(map(lambda x: x * factor, employees_happiness))
filtered_happiness = list(filter(lambda x: x >= sum(factored_happiness) / len(factored_happiness), factored_happiness))
if len(filtered_happiness) >= len(factored_happiness)/2:
print(f"Score: {len(filtered_happiness)}/{len(factored_happiness)}. Employees are happy!")
else:
print(f"Score: {len(filtered_happiness)}/{len(factored_happiness)}. Employees are not happy!")
|
43e9ba9facf94cfb16189389ee283cb304ee4aa5 | linuxww/hello-world | /sample.py | 2,078 | 3.71875 | 4 | #!/usr/bin/env python
#test test test test
from string import digits
from random import randint, choice
count = 0
print ("""random number to play 2A1B""")
numStr = '0123456789'
randNum = ''
for i in range(4) :
n = choice(numStr)
randNum = randNum + n
numStr = numStr.replace(n, '')
#print ('Debug >> randNum',randNum)
def isallnumber(num):
for ch in num :
if ch not in digits :
return False
return True
def hasSameDigit(sameNum) :
for i in range(len(sameNum)):
if (sameNum[0]==sameNum[1]) or (sameNum[0]==sameNum[2]) or (sameNum[0]==sameNum[3]) or (sameNum[1]==sameNum[2]) or (sameNum[1]==sameNum[3]) or (sameNum[2]==sameNum[3]):
return True
return False
userNums = []
results = []
Winner = 0
while Winner == 0:
num = []
number = 0
while (number == 0):
num = input('infput four number')
if (isallnumber(num) == False) :
print ('***wrong:not number')
exit
elif (hasSameDigit(num) == True):
print ('***wrong:please input different number')
elif (len(num) != 4) :
print ('***wrong pleae input four number')
exit
else:
number +=1
userNum = num
userNums.append(userNum)
#print ('Debug >> userNum',userNum)
seatA = 0
seatB = 0
count +=1
for i in range(4) :
if userNum[i] in randNum :
if i == randNum.find(userNum[i]) :
seatA += 1
else :
seatB += 1
if seatA == 4:
print ("you win!!")
Winner = 1
else:
exit
result = '%dA%dB' % (seatA, seatB)
results.append(result)
print ('-' * 20)
for i in range(count) :
print ('(%d)/%s/%s' % (i + 1, userNums[i], results[i]))
print ('-' * 20)
if Winner == 1 :
print ('Total: %d times' % count)
print ('Congratulations Your are winner')
|
0bbfc3d2ee607e042a9d8d280adfbf81ed8480bf | OlexandrGamchuk1/Homework-13 | /Exercise 1.py | 511 | 3.65625 | 4 | class MinusPriceException(Exception):
def __init__(self, message):
super().__init__()
self.message = message
def get_exception_message(self):
return self.message
try:
price = float(input('Enter the price: '))
if 0 > price:
raise MinusPriceException('The price cannot be less than 0!')
except MinusPriceException as err:
print(err.get_exception_message())
except ValueError:
print('The price must be in numbers only!')
else:
print(f'Price: {price}') |
8685949dd4d06710e819c3ef7dc8f4a0d4a34b5c | FrankieWei727/python-note | /HelloPython/note15.py | 500 | 3.890625 | 4 | # class
class Point:
# Constructors
def __init__(self, x, y):
self.x = x
self.y = y
def move(self):
print("move")
def draw(self):
print("draw")
# point1 = Point()
# point1.move()
# point1.x = 10
# print(point1.x)
point2 = Point(10, 20)
print(point2.x)
# inheritance
class Mammal:
def walk(self):
print('walk')
class Dog(Mammal):
def sit(self):
print('sit')
class Cat(Mammal):
pass
dog1 = Dog()
dog1.walk()
|
7ef05116be08d29e0c376e636760361124fbfe27 | ivolazy/dashmips | /dashmips/syscalls/file_syscalls.py | 1,869 | 3.515625 | 4 | """Syscalls for accessing files."""
import os
from . import mips_syscall
from ..utils import intify
from ..models import MipsProgram
@mips_syscall(13)
def open_file(program: MipsProgram):
"""Open file. $a0 = address of null-terminated string containing filename $a1 = flags."""
# https://docs.python.org/3/library/os.html#os.open
filename = program.memory.read_str(program.registers["$a0"])
flags = program.registers["$a1"]
# mode = program.registers["$a2"]
try:
program.registers["$v0"] = os.open(filename, flags)
except FileNotFoundError as ex:
print(ex)
program.registers["$v0"] = -1 # TODO: This should be an E* value
@mips_syscall(14)
def read_file(program: MipsProgram):
"""Read from file. $a0 = file descriptor $a1 = address of input buffer $a2 = n bytes to read."""
# https://docs.python.org/3/library/os.html#os.read
fd = program.registers["$a0"]
address = program.registers["$a1"]
n = program.registers["$a2"]
data_in = os.read(fd, n)
program.memory.write_str(address, data_in)
program.registers["$v0"] = len(data_in)
@mips_syscall(15)
def write_file(program: MipsProgram):
"""Write to file. $a0 = file descriptor $a1 = address of input buffer $a2 = n bytes to read."""
# https://docs.python.org/3/library/os.html#os.write
fd = program.registers["$a0"]
address = program.registers["$a1"]
n = program.registers["$a2"]
data_out = bytes([intify(program.memory.read08(address + offset)) for offset in range(0, n)])
written = os.write(fd, data_out)
program.registers["$v0"] = written
@mips_syscall(16)
def close_file(program: MipsProgram):
"""Close file. $a0 = file descriptor."""
# https://docs.python.org/3/library/os.html#os.close
fd = program.registers["$a0"]
os.close(fd)
program.registers["$v0"] = 0
|
aa740e9232fcbead2cece64cfc3bb931977ec40f | legna96/UAMIRepo | /Concurrente/P6-ordenar-matriz-hilos-python/Parte_I.py | 2,016 | 3.609375 | 4 | import random
import time
def aleatMatriz(M,n,m):
for i in range(n):
for j in range(m):
M[i][j]= random.randint(0, 100)
def impMatriz(M,n,m):
for i in range(n):
for j in range(m):
print " "+ str(M[i][j])+ "\t",
print "\n"
def TDaplicar(M, n, m):
a=[]
for i in range(0, n):
r=[]
for j in range(0, m):
r.append(g(M[i][j]))
a.append(r)
return a
def TDaplicar2(M,n,m):
matriz=[ [ g(M[i][j]) for j in range(m) ] for i in range(n) ]
return matriz
def g(x):
return x**2
def approachA():
l=[]
for x in range(10000):
#print l
l.extend(tomaSiguienteLista())
def approachB():
l=[]
for x in range(10000):
#print l
l=l+tomaSiguienteLista()
def tomaSiguienteLista():
return [1,2,3,4]
def main():
####### SLICE ##############################################
print "Hola Mundo"
Lista1 = [1,2,3,4,5,6,7,8,9]
print Lista1
print "(a) El tercero hasta sexto, incluyendo los extremos de la lista"
print Lista1[3:6]
print "(b) Todos menos el ultimo elemento"
print Lista1[:8]
print "(c) Toda la lista"
print Lista1[:]
########### INICIALIZAR MATRIZ ################################
n= int(raw_input("dame las filas\n"))
m= int(raw_input("dame las columnas\n"))
M = [range(m) for i in range(n)]
aleatMatriz(M,n,m)
########## Primer matriz #########################
print "\nPrimer Matriz\n"
impMatriz(M,n,m)
########## Segunda matriz #########################
print "utilizando TDaplicar()"
print "Segunda Matriz\n"
M2=TDaplicar(M,n,m)
impMatriz(M2,n,m)
########## Tercer matriz #########################
print "utilizando TDaplicar2()"
print "Tercera Matriz\n"
M3=TDaplicar2(M,n,m)
impMatriz(M3,n,m)
########## Funciones approach #########################
tiempo1= time.time()
approachA()
tiempo2= time.time()
print "-----", tiempo2-tiempo1,"segundos----- "
tiempo3= time.time()
approachB()
tiempo4= time.time()
print "-----", tiempo4-tiempo3,"segundos----- "
if __name__ == '__main__':
main() |
2d8215935435a4f62019ebf0c8acc684d86afe44 | JIA-Chao/ICS-Project | /RSA_Prime.py | 3,284 | 3.671875 | 4 | """
Author: Jia Zhao
"""
# -*- coding: UTF-8 -*-
import math
import random
def egcd(a, b):
"""Extended Euclidean algorithm; get int x and int y such that gcd(a,b) = ax + by."""
if a == 0:
return b, 0, 1
else:
g, x, y = egcd(b % a, a)
return g, y - (b // a) * x, x
def mod_inverse(b, n):
"""Modulo Multiplicative Inverse; find a "c" such that (bc - 1) | n, or say n % bc = 1."""
g, x, _ = egcd(b, n)
if g == 1:
return x % n
else:
raise Exception('Modular inverse does not exist!')
def quick_pow_mod(a, b, c):
"""
Quick power mod; convert b into binary, traverse its binary; to get the modulo
Time complexity: O(logN)
"""
cond1, cond2 = False, False # set condition for text en/de; and if it starts with '0'.
if type(a) is str:
cond1 = True
if a[0] == '0':
cond2 = True
a = int(a)
# print('a:', a, 'c:', c)
a = a % c
result = 1
while b != 0:
if b & 1:
result = (result * a) % c
b >>= 1
a = (a % c) * (a % c)
# print('r:', result)
if cond1 and not cond2:
return str(result)
if cond2:
result = '0' + str(result)
# print('result with 0:', result)
return result
return result
def miller_rabin(a, n):
"""Miller Rabin Algorithm; test if "n" is a prime."""
if n == 1:
return False
if n == 2:
return True
k = n - 1
q = int(math.floor(math.log(k, 2)))
m = 0
while q > 0:
m = k / 2 ** q
if k % 2 ** q == 0 and m % 2 == 1:
break
q = q - 1
if quick_pow_mod(a, k, n) != 1:
return False
m = int(m)
b1 = quick_pow_mod(a, m, n)
for i in range(q):
if b1 == n - 1 or b1 == 1:
return True
b2 = b1 ** 2 % n
b1 = b2
if b1 == 1:
return True
return False
def prime_test_mr(n, k=8):
"""Generally, test Miller Rabin 8 times."""
for i in range(k):
a = random.randint(1, n - 1)
if not miller_rabin(a, n):
return False
return True
def prime_each(num, prime_l):
"""Test if num have no common factors with each prime in prime_list."""
for prime in prime_l:
r = num % prime # r is remainder
if r == 0:
return False
return True
def prime_l(start, end):
"""Return a prime list from start to end."""
to_return = []
for i in range(start, end+1):
if is_prime(i):
to_return.append(i)
return to_return
def is_prime(num):
"""Return if num if a prime."""
sqrt = int(math.sqrt(num))
for i in range(2, sqrt + 1):
if num % i == 0:
return False
return True
def prime_pair(count=2):
"""Generate a prime pair as pub and pri keys for RSA."""
l = prime_l(2, 100000)
prime_pair = []
for i in range(count):
num = random.randint(pow(10, 15), pow(10, 16))
if num % 2 == 0:
num += 1
cond = True
while cond:
if prime_each(num, l) and prime_test_mr(num):
if num not in prime_pair:
prime_pair.append(num)
cond = False
num += 2
return prime_pair
|
80c4a13e26c9690eb2a7b386841c7b122ebf2176 | superpupervlad/ITMO | /1 Семестр/Алгоритмы и структуры данных/3 Лаба/3.1 Двоичный поиск.py | 1,169 | 3.6875 | 4 | def bin_search_left(arr, right, x):
left = 0
count = 0
while left < right:
count += 1
mid = (left + right)//2
if arr[mid] < x:
left = mid + 1
else:
right = mid
if count == 100:
break
if arr[left] == x:
print(left + 1, end=' ', file=fout)
else:
print("-1", end=' ', file=fout)
def bin_search_right(arr, right, x):
left = 0
if arr[-1] == x:
print(len(arr), file=fout)
return
while left < right:
mid = (left + right)//2
if arr[mid] > x:
right = mid
else:
left = mid + 1
if arr[left - 1] == x:
print(left, file=fout)
else:
print("-1", file=fout)
fin = open("binsearch.in")
fout = open("binsearch.out", "w")
n = map(int, fin.readline().split())
array = list(map(int, fin.readline().split()))
m = map(int, fin.readline().split())
elements = list(map(int, fin.readline().split()))
for elem in elements:
bin_search_left(array, len(array) - 1, elem)
bin_search_right(array, len(array) - 1, elem)
fout.close()
|
62b19c427d51ab8aa2e5eb31b8c03ff7a878e702 | shubhamgupta0706/demopygit | /practice1.py | 269 | 4.03125 | 4 | weight = input('Weight: ')
unit = input('(L)bs or (K)g : ')
weight = float(weight)
if unit.upper() == 'L':
weight = weight * 0.45
print('Your weight in Kg is ' + str(weight))
else :
weight = weight/0.45
print('Your weight in pound is ' + str(weight))
|
aec08162da5bd832ee9d83431f4a6f3bf18804d6 | venkataganeshkona/geeksforgeeks | /for1.py | 392 | 4.4375 | 4 | #This code explains the concept of for loops in python
a=[1,2,3,4,5,6,7,8,9,10]
for m in a:
print m
#second example of for
marks=[1,2,3,4,5,6,7,8,9]
sum=0
for n in marks:
sum=sum+n
print "The sum is =", sum
#third example of for
table_12=[12,24,36,48,60,72,84,96,108,120]
table_13=[]
z=1
for i in table_12:
table_13.append(i+z)
z=z+1
print "The table of 13 is \n ",table_13
|
720d71bbe68f35d3b7efc5afe28fb102c0beb046 | gunit84/Code_Basics | /Code Basics Beginner/ex32_Multiprocessing_lock.py | 1,059 | 3.9375 | 4 | #!python3
"""Python3 Multiprocessing Lock... """
__author__ = "Gavin Jones"
import multiprocessing
import time
def deposit(balance, lock):
for i in range(100):
time.sleep(0.01)
# puts lock on process
lock.acquire()
balance.value += 1
# releases lock on process
lock.release()
def withdraw(balance, lock):
for i in range(100):
time.sleep(0.01)
# puts lock on process
lock.acquire()
balance.value -= 1
# releases lock on process
lock.release()
if __name__ == '__main__':
# define the values for the process
balance = multiprocessing.Value("i", 200)
# Create a Lock
lock = multiprocessing.Lock()
# define the processes and there functions
d = multiprocessing.Process(target=deposit, args=(balance, lock))
w = multiprocessing.Process(target=withdraw, args=(balance, lock))
# start the processes
d.start()
w.start()
# wait till the processes have stopped.
d.join()
w.join()
print(balance.value)
|
42558719acc91a67b98b0f0a1af9db07757b1a5c | NandaGopal56/Programming | /PROGRAMMING/python practice/string rotation check-2.py | 437 | 3.75 | 4 | #check rotation in two given string
s1='ABCDE'
s2='CDEAB'
count=0
diff=abs(s1.index(s1[0])-s2.index(s1[0]))
#print(diff)
for i in range(len(s1)):
if i+diff <= len(s1)-1:
if s1[i] == s2[i+diff]:
count+=1
#print(count)
else:
if s1[i] == s2[i+diff-len(s1)]:
count+=1
#print(count)
if count==len(s1):
print('True')
else:
print('False') |
feb3ff3ee6437eb822d18bf8e65bbadf9723f12f | IanDarwin/pysrc | /strings/str-slice.py | 541 | 4.4375 | 4 | #!/usr/bin/env python
# Shows various ways of splitting a sequence such as a string.
# Also shows an alternate way of printing: list unpacking with
# printf-style format codes instead of {name}
# And yes, we could have just used string.split() :-)
name = "Ian Darwin"
first = name[0:3]
last = name[4:]
print("Name split by slice: %s, %s" % (last, first))
sp = name.find(' ')
first = name[0:sp]
last = name[sp+1:]
print("Name split by find: %s, %s" % (last, first))
print("Sliced and diced:", name[4:-2:2])
print("Backwards", name[::-1])
|
1597aa9419e712d26451c1424b5de986c0025040 | AB1RAME/Date21Notes | /class.py | 1,818 | 3.9375 | 4 | # class AmazingDog:
# animal_kind='canine'
# def bark(self):
# print(self.animal_kind)
# return 'woof!'
# Bob=AmazingDog()
# Bob.animal_kind='dolphin'
# print(Bob.animal_kind)
# class Person:
# def __init__(self,name,age):
# self.name=name
# self.age=age
# p=Person('John',36)
# print(p.name)
# print(p.age)
# class Car:
# def setMax(self,maxspeed):
# self.__maxspeed=maxspeed
# def getMax(self):
# return self.__maxspeed
# def setBrake(self,braketime):
# self.__braketime=braketime
# def getBrake(self,braketime):
# return self.__braketime
# def setAccelerations(self,acceleration):
# self.__acceleration=acceleration
# def getAcceleration(self,acceleration):
# return self.__acceleration
# def __init__(self,brand,colour):
# self.brand=brand
# self.colour=colour
# def currentspeed(self,acceleration,braketime):
# return acceleration*braketime
class Car:
def __init__(self,brand,colour,acceleration,time,maxspeed):
self.brand=brand
self.colour=colour
self.acceleration=acceleration
self.time=time
self.__maxspeed=maxspeed
def set_Max(self,maxspeed):
self.__maxspeed=maxspeed
def get_Max(self,maxspeed):
return self.__maxspeed
def currentSpeed(self,acceleration,time):
self.speed=0
self.speed=self.speed+self.acceleration*self.time
if self.speed>self.__maxspeed:
self.speed==self.__maxspeed
elif self.speed<0:
self.speed=0
return self.speed
def __repr__(self):
return(f"The {self.colour} {self.brand} is travelling at high speed with a maximum speed of {self.__maxspeed}")
c=Car('bmw','black',10,0.5,200)
print(c)
|
730ff6d096493219e100e07cd4b7ff0bc9577761 | ueong/head_first_python | /chapter1/4_for_loop.py | 331 | 4 | 4 | fav_movies = ["The Holy Grail", "The Life of Brian"]
print('# we don\'t want to work like this')
print(fav_movies[0])
print(fav_movies[1])
print('\n# use for loop')
for each_flick in fav_movies:
print(each_flick)
print('\n# use while loop')
count = 0
while count < len(fav_movies):
print(fav_movies[count])
count = count + 1
|
d21b141b369ddca6842762839cf073fabe8c8ce1 | jaruwitteng/6230401856-oop-labs | /jaruwit-6230401856-lab5/Problem4.py | 564 | 4.21875 | 4 | def factorial(digit):
if digit < 0:
print("Please enter a positive integer. {} is not a positive integer".format(digit))
quit()
if digit == 0:
print("factorial(0) is 1")
quit()
if digit == 1:
return 1
else:
return (digit * factorial(digit - 1))
try:
digit = int(input("Enter an integer:"))
print("factorial({}) is {}".format(digit, factorial(digit)))
except ValueError as err:
print("Please enter a positive integer.%s" % err )
|
b94d662c31854b41f334765126c1c65f47473308 | JosephLevinthal/Research-projects | /5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/223/users/4472/codes/1807_2568.py | 402 | 3.75 | 4 | metade = int(input("metade dos asteriscos na primeira linha")) * 2
ast = "*"
linha_1 = ast * metade
QA2 = (len(linha_1)- 2)//2
oo = "oo"
mult = 1
print(linha_1)
ll = (ast * QA2 ) + (oo * mult ) + (ast * QA2 )
for ch in range(0,len(linha_1)):
if (QA2 <= len(ll)-1 and (mult <= (len(linha_1) - 2)/2)):
ll = (ast * QA2 ) + (oo * mult ) + (ast * QA2 )
print(ll)
QA2 = QA2 - 1
mult = mult + 1 |
8a2953c62f9dd580fc367b301e79a0d18307abaa | Aasthaengg/IBMdataset | /Python_codes/p00001/s611267236.py | 138 | 3.9375 | 4 | Height = [0]*10
for i in range (10):
Height[i] = int(input())
Height.sort()
Height.reverse()
for j in range(3):
print(Height[j])
|
127392a55f3a953a94fa1941465e285299c674dc | huanghehg/DataStructAndAlgorithm | /LeetCode/876 middle-of-the-linked-list.py | 2,230 | 4.125 | 4 | # 给定一个带有头结点 head 的非空单链表,返回链表的中间结点。
#
# 如果有两个中间结点,则返回第二个中间结点。
#
# 示例 1:
#
# 输入:[1,2,3,4,5]
# 输出:此列表中的结点 3 (序列化形式:[3,4,5])
# 返回的结点值为 3 。 (测评系统对该结点序列化表述是 [3,4,5])。
# 注意,我们返回了一个 ListNode 类型的对象 ans,这样:
# ans.val = 3, ans.next.val = 4, ans.next.next.val = 5, 以及 ans.next.next.next = NULL.
# 示例 2:
#
# 输入:[1,2,3,4,5,6]
# 输出:此列表中的结点 4 (序列化形式:[4,5,6])
# 由于该列表有两个中间结点,值分别为 3 和 4,我们返回第二个结点。
#
# 提示:
#
# 给定链表的结点数介于 1 和 100 之间。
#
# 来源:力扣(LeetCode)
# 链接:https://leetcode-cn.com/problems/middle-of-the-linked-list
# 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
#
# 1->1 2->2 3->2 4->3 5->3 6->4 7->4 ------> 2->2 4->3 6->4 8->5
#
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def __str__(self):
head = self
des = ''
while head is not None:
des = des + head.val + ' -> '
head = head.next
des += "NULL"
return des
class Solution:
def middleNode(self, head: ListNode) -> ListNode:
if head is None: return None
if head.next is None: return head
slowNodePointer = head
fastNodePointer = head
while fastNodePointer is not None and fastNodePointer.next is not None:
slowNodePointer = slowNodePointer.next
fastNodePointer = fastNodePointer.next.next
return slowNodePointer
if __name__ == '__main__':
node1 = ListNode("1")
node2 = ListNode("2")
node3 = ListNode("3")
node4 = ListNode("4")
node5 = ListNode("5")
node6 = ListNode("6")
node7 = ListNode("7")
node1.next = node2
node2.next = node3
node3.next = node4
node4.next = node5
node5.next = node6
node6.next = node7
print(node1)
print(Solution().middleNode(node1)) |
f7a6ea6bc6fb591dec6904c3bf176bb06a0965db | jqnv/python_challenges_Bertelsmann_Technology_Scholarship | /maximum_integer.py | 816 | 4.3125 | 4 | # Option 2: This exercise examines the process of identifying the maximum value
# in a collection of integers. Each of the integers will be randomly selected
# from the numbers between 1 and 100. The collection of integers may contain
# duplicate values, and some of the integers between 1 and 100 may not be present...
from random import randint
def maximum_integer():
max_value = randint(1, 100)
print(f"{max_value} <--- initial value")
counter = 0
for i in range(99):
value = randint(1, 100)
if value <= max_value:
print(value)
else:
print(f"{value} <--- update")
max_value = value
counter += 1
print(f"The maximum value encountered is {max_value} after update {counter} times the max value")
maximum_integer()
|
f1027777387ac4d6d3277d64fe9c515b6907702e | SR2k/leetcode | /5/239.滑动窗口最大值.py | 1,693 | 3.5 | 4 | #
# @lc app=leetcode.cn id=239 lang=python3
#
# [239] 滑动窗口最大值
#
# https://leetcode.cn/problems/sliding-window-maximum/description/
#
# algorithms
# Hard (49.95%)
# Likes: 1672
# Dislikes: 0
# Total Accepted: 304.3K
# Total Submissions: 609.2K
# Testcase Example: '[1,3,-1,-3,5,3,6,7]\n3'
#
# 给你一个整数数组 nums,有一个大小为 k 的滑动窗口从数组的最左侧移动到数组的最右侧。你只可以看到在滑动窗口内的 k
# 个数字。滑动窗口每次只向右移动一位。
#
# 返回 滑动窗口中的最大值 。
#
#
#
# 示例 1:
#
#
# 输入:nums = [1,3,-1,-3,5,3,6,7], k = 3
# 输出:[3,3,5,5,6,7]
# 解释:
# 滑动窗口的位置 最大值
# --------------- -----
# [1 3 -1] -3 5 3 6 7 3
# 1 [3 -1 -3] 5 3 6 7 3
# 1 3 [-1 -3 5] 3 6 7 5
# 1 3 -1 [-3 5 3] 6 7 5
# 1 3 -1 -3 [5 3 6] 7 6
# 1 3 -1 -3 5 [3 6 7] 7
#
#
# 示例 2:
#
#
# 输入:nums = [1], k = 1
# 输出:[1]
#
#
#
#
# 提示:
#
#
# 1 <= nums.length <= 10^5
# -10^4 <= nums[i] <= 10^4
# 1 <= k <= nums.length
#
#
#
# @lc code=start
from collections import deque
class Solution:
def maxSlidingWindow(self, nums: list[int], k: int) -> list[int]:
result = []
queue = deque()
for i, n in enumerate(nums):
while queue and nums[queue[-1]] <= n:
queue.pop()
queue.append(i)
while queue[0] <= i - k:
queue.popleft()
if i >= k - 1:
result.append(nums[queue[0]])
return result
# @lc code=end
|
b8e44b5fea4a56da31921ee13f74215e4d30b9a4 | msznajder/allen_downey_think_python | /ch13.py | 554 | 4.375 | 4 | ## Chapter 13 Case study: data structure selection
## 13.2 Random numbers
# The function random returns a random float between 0.0 and 1.0 (including 0.0 but not 1.0).
# Each time you call random, you get the next number in a long series.
import random
for i in range(10):
x = random.random()
print(x)
# The function randint takes parameters low and high and returns an integer between low and high (including both).
random.randint(5, 10)
# To choose an element from a sequence at random, you can use choice.
t = [1, 2, 3]
random.choice(t)
|
758e8c4a474c5cf083e969bdb6fea449ed77c126 | narhirep/Python-Deep-Learning | /ICP1/sourcecode/ICP1_3.py | 285 | 4.4375 | 4 | String = input('Please enter a sentence:') #Taking any string as a input which contains python word
A = String
print(A) #Printing sentence as it is
print(A.replace('python', 'pythons')) #Replacing every python word with pythons
|
c6bd612b52a21966f4a9d63ead5911ea3fd482a2 | amindazad/lambdata-12 | /my_lambdata/my_script.py | 165 | 3.578125 | 4 | import pandas as pd
form my_lambdata.my_mod import enlarge
print ('Hello World')
df = pd.DataFrame({"state": ["CT", "CO", "CA", "TX"]})
x = 5
print(enlarge(x))
|
8a7ecd49f0d881655ff5b3e4df852a41cef2a657 | divyanshu-95/python_codes | /passlist.py | 304 | 3.953125 | 4 | def count(list):
even=0
odd=0
for i in list:
if i%2==0:
even+=1
else:
odd+=1
return even,odd
list=[20,21,22,55,85,36,56,96]
even,odd=count(list)
#print('even',even)
#print('odd',odd)
print('even : {} and odd : {}'.format(even,odd))
|
60aa936492a58e4c1a0f58b4c7980a5e86c62b5c | ravi-adroll/Email-format-validator | /temp1.py | 2,348 | 4 | 4 | import csv
import re
# FILENAME=input("Enter a CSV filename to check the format")
rows=[]
b=set()
unique=[]
error_mails=list()
dup_email=[]
row3=[]
TOTAL_LINE=0
# line_no=0
## READ FILE
def read_file(filename):
##### ==> to prevent appending when refresh
global TOTAL_LINE
dup_email.clear()
error_mails.clear()
rows.clear()
unique.clear()
b.clear()
##### ==> to prevent appending when refresh ====> finish
with open(filename, 'r') as csvfile:
csvreader = csv.reader(csvfile)
for row in csvreader:
rows.append(row)
TOTAL_LINE=csvreader.line_num
# print(TOTAL_LINE)
print("Total no. of rows: %d"%(csvreader.line_num))
# print(rows)
## CHECK UNIQUE
def find_unique(check_field):
if check_field not in b:
unique.append(check_field)
b.add(check_field)
return 1
else:
return 0
## CHECK FORMAT
def check_format():
for row in rows:
field=str(row)
field=field[1:-1]
x=re.search("\w+@\w+.\w+",field)
if(x.string[1:-1]==x.group()):
valid=x.group()
# print()
is_unique=find_unique(valid)
if is_unique==0:
# print(valid, " >>> remove this duplicate email")
dup_email.append(field)
# print(rows.index(valid))
# print(rows.index(valid)
else:
# print(field," >>>> this email has an error")
error_mails.append(field)
# return 0
def printall():
for row1 in rows:
row2=str(row1)
row2=row2[2:-2]
# print(row2)
row3.append(row2)
# print(rows.index(row1[2:-2]))
# if row2 in dup_email:
# print(row2)
# else:
# print("a")
print("==== LIST OF DUPLICATE EMAILS ====")
for x in dup_email:
if x[1:-1] in row3:
set1=set()
# print(set1)
if x[1:-1] not in set1:
set1.add(x[1:-1])
line_no=row3.index(x[1:-1])
print(x)
print("==== LIST OF INVALID EMAILS WITH INDEX ====")
for x in error_mails:
if x[1:-1] in row3:
line_no=row3.index(x[1:-1])
print(line_no+1,' ',x)
def exec_csv(FILENAME):
read_file(FILENAME) #2sldkfj@dlkjs.com
check_format()
# printall()
# return dup_email,error_mails
# print()
# print("List of Duplicate Emails")
# print(dup_email)
# print()
# print("List of Emails which contains error")
# print(error_mails)
# print()
# print(TOTAL_LINE)
# exec_csv('CRM_test.csv')
# print(TOTAL_LINE) |
466baf473b5b435c59c92e785ce53f6a55b37d7b | shubhambisht1/100-pattern-program | /8.py | 151 | 3.515625 | 4 | #dddd
#cccc
#bbbb
#aaaa
n=int(input("enter the row:"))
for i in range(1,n+1):
for j in range(1,n+1):
print(chr(65+n-i),end="")
print()
|
b8d58f0ea95acbc38f8f4c743e0f23355d5f04c5 | engenmt/Lingo | /main.py | 2,224 | 3.796875 | 4 | from setup import words
def response(guess, correct):
"""Return the information received upon guessing the word `guess` into the word `correct`."""
guess = list(guess)
correct = list(correct)
known = []
misplaced = []
for idx in range(5):
if guess[idx] == correct[idx]:
known.append(idx)
guess[idx] = None
correct[idx] = None
for idx in range(5):
if (char_guess := guess[idx]) is not None and char_guess in correct:
misplaced.append(idx)
correct[correct.index(char_guess)] = None
return (tuple(known), tuple(misplaced))
def score(*guesses):
"""Return the score of a sequence of guesses. The score is proportional to how good the guesses are.
Consider all correct words. Each correct word gives information (1) the first letter and
(2) the sequence of responses based on the guessed words. There is an equivalence relation
on the set of correct words, where two words are equivalent with respect to the guesses if
their information returned is identical. The probability that you guess correctly given
a sequence of guesses is proportional to the number of equivalence classes, so this function
returns the number of equivalence classes.
"""
return len(set(
sum((response(guess, correct) for guess in guesses), (correct[0],)) for correct in words
))
def best_addition(*guesses):
"""Given a sequence of guesses, return the best guessed word to add on."""
return max(words, key = lambda w: score(w, *guesses))
if __name__ == '__main__':
guesses = [
('blocs', 'fumed', 'garth', 'pinky']), # 8211
('blots', 'cager', 'dinky', 'whump']), # 8238
('chomp', 'furan', 'gybed', 'kilts']), # 8239
('bumpy', 'cadge', 'knits', 'whorl']), # 8240
('clipt', 'gybed', 'khoum', 'warns']), # 8246 # Mine
('bumpy', 'cares', 'klong', 'width']), # 8268
('bares', 'clomp', 'gunky', 'width']), # 8272
('blink', 'chomp', 'gudes', 'warty']), # 8282
('bints', 'cloak', 'gyred', 'whump']), # 8287
]
for g in sorted(guesses, key = lambda t: score(*t)):
print(g, score(*g))
|
4bc78b5674bd0543839e0b7f76e4cbdec8ee3dd6 | cliverlonglsi/hello_world_1_crl | /tempxx.py | 148 | 3.5 | 4 | for idx in range (1 , 5):
print("This is my second program")
print("change made in VS")
x = input("Please press enter to end program ")
|
786d76e1d8e00efd85194b588ed6c75983eafb55 | Lee-Jae-heun/python_pr | /baekjoon/2753.py | 170 | 3.65625 | 4 | year = int(input())
if 1 <= year <= 4000:
if year%4 == 0 and year%100 != 0:
print("1")
elif year%400 == 0:
print("1")
else:
print("0") |
ec113e969859952eebef346f82a4366e4b07db32 | FabricioVargas/Curso-de-Python | /graficos/radioButton.py | 510 | 3.65625 | 4 | from tkinter import *
root = Tk()
varOpcion=IntVar()
def imprimir():
if varOpcion.get()==1:
etiqueta.config(text="has elegido masculino")
else:
etiqueta.config(text="has elegido femenino")
Label(root, text="Genero").pack()
Radiobutton(root,text="Masculino", variable=varOpcion, value=1, command=imprimir).pack()
Radiobutton(root,text="Femenino", variable=varOpcion, value=2,command=imprimir).pack()
etiqueta=Label(root)
etiqueta.pack()
#Como obtener los botones
root.mainloop()
|
dadde4757cdecb2ceaae59e2a773eddbff1da1fa | y0ssi10/leetcode | /python/middle_of_the_linked_list/solution.py | 554 | 3.859375 | 4 | # Problem:
# Given a non-empty, singly linked list with head node head, return a middle node of linked list.
# If there are two middle nodes, return the second middle node.
#
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def middleNode(self, head: ListNode) -> ListNode:
arr = {}
index = 0
while head:
arr[index] = head
index += 1
head = head.next
keys = list(arr.keys())
return arr[keys[len(keys) // 2]]
|
ec02cb5876426fa36a233a638029d2730132763b | JoyiS/Leetcode | /crackfun/211. Add and Search Word - Data structure design.py | 2,179 | 4.03125 | 4 | '''
Design a data structure that supports the following two operations:
void addWord(word)
bool search(word)
search(word) can search a literal word or a regular expression string containing only letters a-z or .. A . means it can represent any one letter.
For example:
addWord("bad")
addWord("dad")
addWord("mad")
search("pad") -> false
search("bad") -> true
search(".ad") -> true
search("b..") -> true
'''
# Method 1 : HashTable
class WordDictionary(object):
def __init__(self):
self.word_dict = collections.defaultdict(list)
def addWord(self, word):
if word:
self.word_dict[len(word)].append(word)
def search(self, word):
if not word:
return False
if '.' not in word:
return word in self.word_dict[len(word)]
for v in self.word_dict[len(word)]:
# match xx.xx.x with yyyyyyy
for i, ch in enumerate(word):
if ch != v[i] and ch != '.':
break
else:
return True
return False
# Your WordDictionary object will be instantiated and called as such:
# obj = WordDictionary()
# obj.addWord(word)
# param_2 = obj.search(word)
# Method 2: Trie Tree
class TrieNode(object):
def __init__(self):
self.word = False
self.children = {}
class WordDictionary(object):
def __init__(self):
self.root = TrieNode()
def addWord(self, word):
node = self.root
for c in word:
if c not in node.children:
node.children[c] = TrieNode()
node = node.children[c]
node.word = True
def search(self, word):
return self.searchFrom(self.root, word)
def searchFrom(self, node, word):
for i in range(len(word)):
c = word[i]
if c == '.':
for k in node.children:
if self.searchFrom(node.children[k], word[i+1:]):
return True
return False
elif c not in node.children:
return False
node = node.children[c]
return node.word |
64c3421f9bd3cd8a21648c74399acb6edc75f5b3 | lzhang1/python30 | /sample/student.py | 835 | 3.828125 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
class Student(object):
def __init__(self,name,score):
self.__name = name
self.__score = score
def print_info(self):
print ("Name:%s Score:%s"%(self.__name,self.__score))
def get_grade(self):
if self.__score > 90:
return 'A'
elif self.__score > 60:
return 'B'
else:
return 'C'
def get_name(self):
return self.__name
def get_score(self):
return self.__score
def set_score(self,score):
if 0 <= score <= 100:
self.__score = score
else:
raise ValueError('bad score')
if __name__ == "__main__":
A = Student("Michael",80)
B = Student("Mike",100)
A.print_info()
B.print_info()
print (A.get_grade())
|
8ef4b2a200af553690be1159d76afae8a99e9ffd | feermorales/PracticaKevin | /operaciones.py | 576 | 3.921875 | 4 | n1 = float(input("Ingresa el primer número: "))
n2 = float(input("Ingresa el segundo número: "))
def suma(val1=0, val2=0):
return val1 + val2
def resta(val1=0, val2=0):
return val1 - val2
def multi(val1=0, val2=0):
return val * val2
def operacion(funcion, val1=0, val2=0):
return funcion(val1, val2)
funcion_suma = suma
resultado_sum = operacion(funcion_suma, n1, n2)
funcion_resta = resta
resultado_res = operacion(funcion_resta, n1, n2)
print("\nEl resultado de la SUMA es: ", resultado_sum)
print("\nEl resultado de la RESTA es: ", resultado_res)
|
18b16e2504d7f63bdeb9d42defcc932796bd147f | tauseef-dev/PYTHON-EXPERIMENTS | /EXP05/exp501.py | 2,698 | 3.5625 | 4 | '''
EXPERIMENT No. : 5 PROGRAM : 01
Name : TAUSEEF MUSHTAQUE ALI SHAIKH
Roll No : 18CO63 Batch : B-3
Aim : Program to perform file operatiobn in Python.
'''
def readf():
'''
A METHOD TO READ A FILE.
'''
try:
f = open(input('ENTER FILE NAME: '))
s = f.readlines()
for l in s:
print(l,end = '')
except:
print('THE FILE NAME: DOES NOT EXIST, ENTER A VALID FILE NAME!')
f = open(input('ENTER FILE NAME: '))
s = f.readlines()
for l in s:
print(l,end = '')
f.close()
def writef():
'''
A METHOD TO CREATE OR REPLACE (WRITE) A FILE.
'''
f = open(input('ENTER FILE NAME: '), 'w+')
while True:
data = input('ENTER DATA: ')
f.write(data + '\n')
ch = input('WANT TO ENTER MORE DATA (Y/N): ')
if (ch == 'y' or ch == 'Y'):
continue
else:
break
f.close
def appendf():
'''
A METHOD TO APPEND INFROMATION INTO AN EXISTING FILE.
'''
f = open(input('ENTER FILE NAME: '), 'a')
while True:
data = input('ENTER DATA: ')
f.write(data + '\n')
ch = input('WANT TO ENTER MORE DATA (Y/N): ')
if (ch == 'y' or ch == 'Y'):
continue
else:
break
f.close
def main():
'''
A MAIN METHOD WHCH WILL BE EXECUTED ONLY WHEN THE FILE IS EXECUTED BY ITSELF AND NOT IMPORTED.
'''
while True:
print('\t\t\tMENU')
print('\n 1. DISPLAY CONTAINS OF FILE\n 2. WRITE A FILE\n 3. APPPEND FILE\n 0. QUIT')
ch = int(input('ENTER YOUR CHOICE: '))
if ch == 0:
break
elif ch == 1:
readf()
elif ch == 2:
writef()
elif ch == 3:
appendf()
else:
print('PLEASE ENTER A VALID CHOICE!')
if __name__ == '__main__':
main()
'''
OUTPUT:
MENU
1. DISPLAY CONTAINS OF FILE
2. WRITE A FILE
3. APPPEND FILE
0. QUIT
ENTER YOUR CHOICE: 2
ENTER FILE NAME: exp501sam.txt
ENTER DATA: TAUSEEF MUSHTAQUE ALI SHAIKH
WANT TO ENTER MORE DATA (Y/N): Y
ENTER DATA: SE [CO]
WANT TO ENTER MORE DATA (Y/N): n
MENU
1. DISPLAY CONTAINS OF FILE
2. WRITE A FILE
3. APPPEND FILE
0. QUIT
ENTER YOUR CHOICE: 3
ENTER FILE NAME: exp501sam.txt
ENTER DATA: 18CO63
WANT TO ENTER MORE DATA (Y/N): N
MENU
1. DISPLAY CONTAINS OF FILE
2. WRITE A FILE
3. APPPEND FILE
0. QUIT
ENTER YOUR CHOICE: 1
ENTER FILE NAME: exp501sam.txt
TAUSEEF MUSHTAQUE ALI SHAIKH
SE [CO]
18CO63
MENU
1. DISPLAY CONTAINS OF FILE
2. WRITE A FILE
3. APPPEND FILE
0. QUIT
ENTER YOUR CHOICE: 0
''' |
c5e4efa01aefe467efcfe701163b92585a0555a6 | cosmologist10/Fractals | /fractals/sierpinski_gasket.py | 1,392 | 3.5 | 4 | #!/usr/bin/python
# Import Image and ImageDraw for creating new images and retouching existing images
from PIL import Image, ImageDraw
def fractal(steps):
def sierpinski_display(values):
update_image.line((values[0], values[1]))
update_image.line((values[1], values[2]))
update_image.line((values[0], values[2]))
def sierpinski_compute(values):
x1 = (values[0][0] + values[1][0]) / 2
y1 = (values[0][1] + values[1][1]) / 2
x2 = (values[1][0] + values[2][0]) / 2
y2 = (values[1][1] + values[2][1]) / 2
x3 = (values[2][0] + values[0][0]) / 2
y3 = (values[2][1] + values[0][1]) / 2
values2 = [[x1, y1], [x2, y2], [x3, y3]]
p=[values[0], values2[0], values2[2]]
q=[values[1], values2[0], values2[1]]
r=[values[2], values2[1], values2[2]]
sierpinski_display(values)
if x<=steps:
sierpinski_display(p)
sierpinski_display(q)
sierpinski_display(r)
sierpinski_compute(p)
sierpinski_compute(q)
sierpinski_compute(r)
x+=1
def draw(image):
return ImageDraw.Draw(image)
p=[]
q=[]
r=[]
x = 1
values = [[0, 500], [500, 500], [250, 0]]
size = values[1]
picture = Image.new('1', size, color="white")
update_image = draw(picture)
imagename = "gasket1.png"
picture.save(imagename)
if __name__ == "__main_":
fractal(10)
|
a24528048860bdcdc1b6b9165848bb18ee562b28 | cristearadu/CodeWars--Python | /unique_in_order.py | 521 | 3.6875 | 4 | def unique_in_order(iterable):
lst_final = []
for ch in iterable:
if lst_final:
if lst_final[-1] != ch:
lst_final.append(ch)
else:
lst_final.append(ch)
return lst_final
print(unique_in_order('AAAABBBCCDAABBB'))
def unique_in_order(iterable):
result = []
prev = None
for ch in iterable:
if ch != prev:
result.append(ch)
prev = ch
return result
print(unique_in_order('AAAABBBCCDAABBB'))
|
ed35738368d6753e6ceaa35fe362425e0ad1439e | tarunyadav1997/Algorithmic-Toolbox | /ch02/fibonacci.py | 286 | 3.578125 | 4 | # Uses python2
def calc_fib(n):
fib=[]
fib.append(0)
fib.append(1)
if(n>=2):
for i in xrange(2,n+1):
fib.append(fib[i-1]+fib[i-2])
return fib[i]
elif(n==1):
return 1
else:
return 0
n = int(input())
print(calc_fib(n))
|
c8ce92759aba604e218339c6ebb07725752e8d4c | calpuche/CollegeAssignments | /software2project/Python/FloatingPointTest.py | 2,229 | 3.65625 | 4 | # StorageTest.py
# Purpose: This aims to test the Storage of the SuT by attempting to successfully perform floating point arithmetic.
# Post: On successful generation, the console returns with "SUCCESS"; If an issue occurs, "ERROR: " will be printed to the console
import sys
import random
from datetime import datetime
LOG_PATH = "log.txt"
def main() :
result = ""
try :
result = run()
except KeyError as ke :
result = str(ke)
except IndexError as ie :
result = str(ie)
except RuntimeError as re :
result = str(re)
finally: # finally is optional and always executes
try:
logResult(result)
except IOError as ioe:
print("%s" % str(ioe))
else:
print(result)
#====================================================================================
# run()
# Runs the test. Returns SUCCESS if the test is successful, and ERROR with a message
# if it fails
#====================================================================================
def run():
try:
computeFloats()
except RuntimeError as re:
result = "ERROR: RuntimeError caught in FloatingPointTest.py" + str(re)
raise RuntimeError(result)
except FloatingPointError as fpe:
result = "ERROR: FloatingPointError caught in FloatingPointTest.py" + str(fpe)
raise FloatingPointError(result)
return "SUCCESS: FloatingPointTest.py"
def validateFloatSum(sum):
if sum > 0:
return True
def computeFloats():
temp = 0.0
for num in range(0, 1000):
temp = num
rand = random.randrange(1,9)
num = (float(num)/float(rand))
temp = temp + num
if validateFloatSum(temp):
return True
else:
raise Exception
def logResult(result) :
testDateTime = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
# Create a new file
try :
file = open(LOG_PATH, "a")
message = str(testDateTime) + " " + result + "\n"
file.write(message)
except IOError as x:
message = "ERROR: Cannot open file " + LOG_PATH + " for append"
raise IOError(message)
if __name__ == '__main__':
main() |
51573ae8bb078316787c03d306d2b8bdef705123 | sugambh/cp | /next_greater_element.py | 321 | 3.75 | 4 | ## http://www.geeksforgeeks.org/next-greater-element/
numbers=[0,1]
for i in range(0,len(numbers)):
flag=False
if (i!=len(numbers)-1):
for j in range(i+1,len(numbers)):
if numbers[j]>numbers[i]:
flag=True
break
j=j+1
if j>=len(numbers):
print -1
else:
print numbers[j]
else:
print -1
i=i+1 |
96e87ee38072e46e095257588d45a05692aea613 | johndeanossowski/PythonCourse | /NiceMeanGame.py | 3,473 | 4.09375 | 4 | '''
Python: 3.5.2
Authored by: Daniel A. Christie, Instructor
Interpreted by: John Ossowski, Student
Purpose: Tech Academy Drill number 35, Python course. This game demonstrates
how to pass variables from function to function.
'''
def start(nice = 0, mean = 0, name = ""): #initial conditions
#get user's name
name = describe_game(name)
nice,mean,name = nice_OR_mean(nice, mean, name)
#the following function gets user's name (if name = "") and describes the game for the first time
def describe_game(name):
if name != "": #if name has a value, don't get name again, keep playing.
print("\nThank you for playing again, {}".format(name))
else:
stop = True
while stop: #this loop works to make sure user gives some input for name
if name == "":
name = input("\nWhat's your name? ").capitalize()
if name != "":
print("\nWelcome, {}".format(name))
print("\nIn this game, you will be greeted by several different people. \nYou can be nice or mean.")
print("\nAt the end of the game, your fate will be influenced by your actions.")
stop = False
return name
#this is the function responsible for the game play, it obtains user input about the choice to be nice or mean
def nice_OR_mean(nice, mean, name):
stop = True
while stop:
show_score(nice, mean, name)
pick = input("\nA stranger approaches you for a conversation. \nWill you be nice or mean? (n/m)").lower()
if pick == "n":
print("\nThey smile, wave and walk away...")
nice+=1
stop = False
if pick == "m":
print("\nThey scowl at you and stomp off...")
mean+=1
stop = False
score(nice, mean, name)
#this function displays the user's nice and mean points
def show_score(nice, mean, name):
print("\n{}, you currently have ({}, Nice) and ({}, Mean) points.".format(name, nice, mean))
#this function determines a win, loss or continued play based on points
def score(nice, mean, name):
if nice > 5:
win(nice, mean, name)
if mean > 5:
lose(nice, mean, name)
else:
nice_OR_mean(nice, mean, name)
#score will call this function if nice > 5, a win
def win(nice, mean, name):
print("\nNice job {}, you win! \nEveryone loves you!".format(name))
playAgain(nice, mean, name)
#score will call this function if mean > 5, a loss
def lose(nice, mean, name):
print("\nToo bad {}, you lose! \nEveryone dislikes you intensely!".format(name))
playAgain(nice, mean, name)
#in either a win or loss situation, the user is asked to if s/he wants to play again
def playAgain(nice, mean, name):
stop = True
while stop:
choice = input("\n{}, do you want to play again? y/n ".format(name)).lower()
if choice == "y":
stop = False
reset(nice, mean, name)
if choice == "n":
print("\nThanks for playing, {}!".format(name))
stop = False
exit()
else:
print("\nPlease enter 'y' for YES or 'n' for NO ...")
#if user wants to play game again, nice and mean are set to zero but name is perserved
def reset(nice, mean, name):
nice = 0
mean = 0
start(nice, mean, name)
if __name__ == "__main__":
start()
|
978cc1dd38b67f2f4c5f4187a93d404ada4faa97 | leonardoo/challenge_ubi | /challenge2/challenge.py | 1,032 | 4 | 4 | def find_peaks(array):
peaks = 0
valleys = 0
i = 0
while i < len(array):
data = array[i]
left = array[i - 1] if i > 0 else None
rigth = array[i + 1] if i < len(array) - 1 else None
if check_index_is_peak(data, left, rigth):
peaks += 1
if left:
valleys += 1
if rigth:
valleys += 1
i += 1
return peaks, valleys
def check_index_is_peak(data, left, rigth):
is_left = True
if left:
is_left = data > left
is_rigth = True
if rigth:
is_rigth = data > rigth
if not left and not rigth:
return False
return is_rigth and is_left
if __name__ == "__main__":
data = input("add the array separated by comma: ")
array = [int(i.strip()) for i in data.split(",")]
if array > 0 and array < 500:
peaks, valleys = find_peaks(array)
print("the arrays has: {} peaks and {} valleys".format(peaks, valleys))
else:
print("not valid array")
|
2e8bdbcf129ff6f92206e7b4058d899e74e02eda | rid47/python_basic_book | /exponent.py | 163 | 4.28125 | 4 | base = float(input("Enter a base "))
exponent = float(input("Enter a exponent "))
result = base ** exponent
print(f"{base} to the power of {exponent} = {result}")
|
517a186ec68d562a1e8ddb8bf86d739db9256fee | yair19-meet/astroids-game | /asteroids /astroids.py | 1,106 | 3.9375 | 4 | from turtle import Turtle
class Asteroids(Turtle):
def __init__(self,x,y,dy,r,color):
Turtle.__init__(self)
self.penup()
self.goto(x, y)
self.dy = dy
self.x = x
self.r = r
self.color(color)
self.shape("circle")
def move():
current_y = self.ycor()
new_y = current_y + self.dy
down_side_asteroids = new_y - self.r
if(down_side_asteroids == -SCREEN_HEIGHT):
self.goto(self.x,SCREEN_HEIGHT)
self.goto(new_x,new_y)
SCREEN_WIDTH = turtle.getcanvas().winfo_width()/2
SCREEN_HEIGHT = turtle.getcanvas().winfo_height()/2
ASTEROIDS=[]
for i in range(NUMBER_OF_BALLS):
x = random.randint(int(-SCREEN_WIDTH) + MAXIMUM_BALL_RADIUS ,int(SCREEN_WIDTH)- MAXIMUM_BALL_RADIUS)
y = screen_height
dy =random.randint(MINIMUM_BALL_Dy, MAXIMUM_BALL_Dy)
radius =random.randint(MINIMUM_BALL_RADIUS, MAXIMUM_BALL_RADIUS)
color =(random.random(),random.random(),random.random())
New_Asteroids = Asteroids(x,y,dy,radius, color)
ASTEROIDS.append(new_asteroid)
|
ead4a681fbb2067c58bfeff97650e0915c14ea53 | Sebastian-MG/EJERCICIOS_PYTHON1 | /70.coordenadas.py | 447 | 4.0625 | 4 | import math
def distancia(x1, y1, x2, y2):
x = pow(x2 - x1, 2)
y = pow(y2 - y1, 2)
d = x + y
d = math.sqrt(d)
return d
def main():
x1 = int(input("coprdenada X1: "))
y1 = int(input("Coordenada Y1: "))
x2 = int(input("Coordenada X2: "))
y2 = int(input("Coordenada Y2: "))
s = distancia(x1, y1, x2, y2)
print("la distancia entre los dos puntos es: {}".format(s))
if __name__ == "__main__":
main()
|
2cd5217613f3a3ee840a4a4defb18bb42a972ffc | RobRcx/algorithm-design-techniques | /greedy/coin_change_greedy.py | 780 | 3.609375 | 4 | # Copyright (c) June 02, 2017 CareerMonk Publications and others.
# E-Mail : info@careermonk.com
# Creation Date : 2017-06-02 06:15:46
# Last modification : 2017-06-02
# Modified by : Narasimha Karumanchi
# Book Title : Algorithm Design Techniques
# Warranty : This software is provided "as is" without any
# warranty; without even the implied warranty of
# merchantability or fitness for a particular purpose.
def make_change(C):
denominations = [10, 5, 1] # must be sorted
coins_count = 0
for coin in denominations:
# Update coins_count with the number of denominations 'are held' in the C.
coins_count += C // coin
# Put remainder to the residuary C.
C %= coin
return coins_count
print make_change(40)
|
1584bd1d857166ed5f0f83db7ac218a1bded4e0f | oscar-mx/notes | /Python/Python语言基础1:语法入门/2.数据类型/03格式化字符串.py | 647 | 4.0625 | 4 | # 格式化字符串
# 字符串连接
a = 'abc' + 'def'
print(a)
# 字符串不能和其他类型的值拼接
print('a = ' + a)# 不常用的写法
# 常用写法,可拼接其他类型
a = 123
print('a = ', a)
# 指定占位符
# %s 表示任意字符串
# %f 表示任意浮点数
# %d 表示任意整数
b = 'hello %s'%'world'
b = 'hello %s 你好 %s'%('world','python')
b = 'hello %3.5s'%'world'# %3.5s 表示字符串长度限制在3-5个字符
b = 'hello %.2f'%132.567 #.2f表示取两位小数
b = 'hello %d'%132.5
print(b)
# 通过在字符串前添加f创建格式化字符串,可以直接签入变量
c = f'hello {a} {b}'
print(c) |
d03089a04839c6b779db3d379416b1d73fb228fb | judgedreadnaught/IntroToFinance | /Ameritrade Proj/Ameritrade API Stock Screener.py | 2,226 | 3.5625 | 4 | # Goes and finds companies that match a certain criteria, ex: p/e ratio of less than 30
import pandas_datareader as pdr
import pandas as pd
import datetime as dt
from yahoo_fin import stock_info as si
tickers = si.tickers_sp500() # tickers in the sp500
start = dt.datetime.now() - dt.timedelta(days=365) # 365 days from now, specifying the time frame we are looking at
end = dt.datetime.now()
# Loading data frame of sp500, info of sp500, and then compare it to the individual stocks in sp500,
# we are trying to see which stocks in the sp500 have beated the sp500
sp500_df = pdr.DataReader('^GSPC', 'yahoo', start, end)
# Calculating percentage change
sp500_df['Per Change'] = sp500_df['Adj Close'].pct_change() # Creating a new column called Per Change
# Calculating returns of sp500, cumprod()[-1] gets the cumulative product of the entire column up to the last row
sp500_return = (sp500_df['Per Change'] + 1).cumprod()[-1]
# Now we will repeat for every single stock in the sp500 and then compare the returns to the sp500
# Creating our data frame that will store the below info about each stock in the sp500
return_list = []
final_df = pd.DataFrame(columns=["Ticker", "Latest Price", "Score", "PE_Ratio", "PEG_Ratio", "SMA_150",
"SMA_200", "52_Week_Low", "52_Week_High"])
# Score is how the stock compares to the sp500 returns
for ticker in tickers:
df = pdr.DataReader(ticker, "yahoo", start, end)
#df.to_csv(f'stock_data/{ticker}.csv') # formatting
df['Per Change'] = df['Adj Close'].pct_change()
stock_return = (df['Per Change'] + 1).cumprod()[-1]
returns_compared = round((stock_return / sp500_return), 2)
return_list.append(returns_compared)
# Finding the best performers of all the tickers
best_performers = pd.DataFrame(list(zip(tickers, return_list)), columns=["Ticker", "Returns Compared"])
# Rank method ranks the best performers, pct means percentage
best_performers['Score'] = best_performers['Returns Compared'].rank(pct=True) * 100
# Now we only leave the best performers and cut out the rest, quantile(80) means you are picking the top 20%
best_performers = best_performers[best_performers["Score"] >= best_performers['Score'].quantile(70)]
|
c9f011ffe049e7b633e552d3a8d5d4928322e774 | JoseALermaIII/python-tutorials | /pythontutorials/books/AutomateTheBoringStuff/Ch03/Projects/P2_inputValidation.py | 751 | 4.34375 | 4 | """Input validation
This program adds input validation to :py:mod:`.P01_make_collatz_seq`
Add try and except statements to the previous project to detect whether
the user types in a noninteger string. Normally, the :obj:`int` function will
raise a :class:`ValueError` error if it is passed a noninteger string, as in `int('puppy')`.
In the except clause, print a message to the user saying they must enter an integer.
"""
def main():
from .P1_makeCollatzSeq import collatz
try:
n = int(input("Input a number: "))
while n != 1:
print(n)
n = collatz(n)
print(n) # When n == 1
except ValueError:
print("Error: Input must be an integer.")
if __name__ == "__main__":
main()
|
c3a296385768265cb8e0d0bca023b97538c2b813 | tompko/praxis | /python/oban-numbers.py | 1,809 | 3.734375 | 4 | import unittest
def write(n):
"""Writes a number n (< 1000000) in words"""
assert(n < 1000000)
ret = ""
if n > 1000:
ret = write(n / 1000)
ret += " thousand "
n = n % 1000
if n > 0 and n < 100:
ret += "and "
if n >= 100:
ret += write(n / 100)
ret += " hundred "
n = n % 100
if n > 0:
ret += "and "
if n >= 20:
tens = {9: "ninety", 8: "eighty", 7: "seventy",
6: "sixty", 5: "fifty", 4: "forty",
3: "thirty", 2: "twenty"}
ret += tens[n / 10]
n = n % 10
if n > 0:
ret += "-"
if n > 0:
units = {1: "one", 2: "two", 3: "three", 4: "four", 5: "five",
6: "six", 7: "seven", 8: "eight", 9: "nine", 10: "ten",
11: "eleven", 12: "twelve", 13: "thirteen", 14: "fourteen",
15: "fifteen", 16: "sixteen", 17: "seventeen",
18: "eighteen", 19: "nineteen"}
ret += units[n]
n = 0
return ret
def oban_numbers():
ret = []
for i in range(1, 1000):
if write(i).find("o") == -1:
ret.append(i)
return ret
class TestWrittenNumbers(unittest.TestCase):
def test_write(self):
self.assertEquals(write(5), "five")
self.assertEquals(write(10), "ten")
self.assertEquals(write(25), "twenty-five")
self.assertEquals(write(65), "sixty-five")
self.assertEquals(write(145), "one hundred and forty-five")
self.assertEquals(write(267), "two hundred and sixty-seven")
self.assertEquals(write(783), "seven hundred and eighty-three")
self.assertEquals(write(1934), "one thousand nine hundred and thirty-four")
if __name__ == "__main__":
unittest.main()
|
d4faefc4c7b01ec21b7928c25177320aa920b7bf | Christian-Schultz/dirstruct | /dirstruct/dirstruct.py | 3,309 | 3.703125 | 4 | #!/usr/bin/env python3
import argparse
import os
import sys
__version__ = 0.1
"""This python3 script will recursively create a directory structure as defined from a file. Each directory should be
separated by newlines. Execute the script with -h to see the different options. """
def parse_args():
description = 'Create a directory structure from file. Directories in the definition file should be separated by ' \
'newlines and should follow the UNIX path convention. \n' \
'The root directory of the directory structure can be controlled by the --root parameter.'
epilog = "Example:" \
"\n" \
"If the input dirfile contains the following:" \
"\ndir1/subdir1/" \
"\ndir2/subdir2/\n" \
'Then "dirstruct dirfile" will create dir1/subdir1 and dir2/subdir2 in the current directory.'
call_path = os.getcwd()
parser = argparse.ArgumentParser(prog='dirstruct', description=description, epilog=epilog,
formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument('dirfile', type=str, help='the file containing the directory structure.')
parser.add_argument('--root', '-r', dest='root', action='store', default=call_path,
help='the root path where the directory structure should be created. Will be created if it '
'does not exist Default: Current directory.')
parser.add_argument('--verbose', '-v', action='store_true', help='verbose mode', default=False)
parser.add_argument('--debug', action='store_true', help='print debug information. Will also toggle verbose mode.',
default=False)
parser.add_argument('--version', action='version', version='%(prog)s {version}'.format(version=__version__))
parser.add_argument('--remove', action='store_true', help='Inverse - remove directories instead of creating them. '
'Will not remove recursively. Default false.', default=False)
return parser.parse_args()
def main(args):
if args.debug:
print("Debug mode engaged")
print("Arguments received:")
for arg in vars(args):
print(arg, getattr(args, arg))
print("")
dirfile = os.path.realpath(args.dirfile)
verbose = args.verbose or args.debug
root = os.path.expanduser(args.root)
if not os.path.exists(root):
os.mkdir(root)
os.chdir(root)
with open(dirfile, 'r') as f:
for line in f:
d = line.strip()
if not args.remove:
if os.path.exists(d):
if verbose:
print("%s already exists, skipping" % d)
continue
if verbose:
print("mkdir %s" % d)
if not args.debug:
os.makedirs(d)
else:
if verbose:
print("rm -r %s" % d)
if not args.debug:
os.rmdir(d)
if __name__ == '__main__':
args = parse_args()
main(args)
sys.exit()
else:
raise ImportError("This python module is not importable. Run as python %s.py." %__name__)
|
1fbec90818a7747d4b86414b340918c57b82be56 | ssarangi/algorithms | /firecode.io/level7/fraction_to_decimal.py | 291 | 3.78125 | 4 | def divide(numerator,denominator):
result = ""
import unittest
class UnitTest(unittest.TestCase):
def testDivide(self):
self.assertEqual(divide(2, 5), "0.4")
self.assertEqual(divide(-8, 7), "-1.[142857]")
if __name__ == "__main__":
unittest.main() |
5ba4c3c84ea65303d2255c1dc1bdf0c03b79d427 | victor-erazo/ciclo_python | /Reto1-leo/ayuda-dayro.py | 1,194 | 3.53125 | 4 | prod = {
'proCodigo':'T00194',
'proNombre':'Televisor Smart TV',
'proCantidad': 50,
'proCosto': 2500000
}
def ingresoProducto (prod : dict)-> str:
proNombre = prod['proNombre']
proCodigo = prod['proCodigo']
proUtilidad = 1.19
proMinstock = 10
proMaxstock = 500
proPrecio = prod['proCosto']*proUtilidad
proTotprecio = proPrecio*prod['proCantidad']
#"{}-{}={}".format(var_1, var_2, rta1)
if prod['proCantidad'] < proMinstock:
return ("El Producto {} condigo {} se encuentra fuera del rango min stock".format(proNombre,proCodigo))
elif prod['proCantidad'] > proMaxstock:
return ("El Producto {} condigo {} se encuentra fuera del rango max stock".format(proNombre,proCodigo))
else:
#return ("El producto " + prod['proNombre'] + " código " + prod['proCodigo'] + " tiene un precio " + str(proPrecio) + " y su precio total es " + str(proTotprecio) + " ha sido ingresado correctamente")
return ("El producto {} código {} tiene un precio {} y su precio total es {} ha sido ingresado correctamente".format(proNombre,proCodigo,proPrecio,proTotprecio))
print(ingresoProducto(prod)) |
4a5f5c375273585f043fc29dd92e510047b8a6b1 | viveganandan/leetcode | /prob227.py | 843 | 3.53125 | 4 | import operator
class Solution(object):
def calculate(self, s):
"""
:type s: str
:rtype: int
"""
def pushn(stack, op, n):
n = int(n)
# Use rank to determine if previous equation can be evaluated
while len(stack) > 1 and rank[op] <= rank[stack[-1]]:
n = ops[stack.pop()](stack.pop(), n)
stack += [n, op]
if s:
stack = []
rank = {'+':0, '-':0, '*':1, '/':1, '':-1}
ops = {'+':operator.add, '-':operator.sub, '*':operator.mul, '/':operator.div}
j = 0
for i in range(len(s)):
if s[i] in ops:
pushn(stack, s[i], s[j : i])
j = i + 1
pushn(stack, '', s[j : ])
return stack[0]
return 0
|
b7d17fda55b06b2409bd64c338222edc1f859198 | Vipamp/pythondemo | /com/heqingsong/Basic/ControlStatement/Condition.py | 1,612 | 3.96875 | 4 | # -*- coding: utf-8 -*-
'''
@Author:HeQingsong
@Date:2018/9/19 18:42
@File Name:Condition.py
@Python Version: 3.6 by Anaconda
@Description:条件语句
'''
'''
布尔值:
False、None,0,"",(),[],{}都表示False
其他都为True
条件语句:
1、if-else;
2、if-elif-else;(可以多次使用elif)
3、if语句块内允许嵌套
注意:
1、每个条件后面要使用冒号(:),表示接下来是满足条件后要执行的语句块。
2、使用缩进来划分语句块,相同缩进数的语句在一起组成一个语句块。
3、没有switch – case语句。
'''
# 一般的if语句
if 10 == int("10"):
print("10==int('10')")
# 简单条件语句:if-else
inputNum = int(input("请输入一个数"))
if inputNum == 0:
print("你输入的数为0")
else:
print("你输入的数不是0")
# 复杂条件语句:if-elif-else
inputNum = int(input("\n请输入一个数"))
if inputNum == 0:
print("你输入的数为0")
elif inputNum > 0:
print("你输入的数大于0")
else:
print("你输入的数小于0")
# 嵌套条件语句
num = int(input("\n请输入一个数"))
if num % 2 == 0:
if num % 3 == 0:
print("你输入的数字可以整除 2 和 3")
else:
print("你输入的数字可以整除 2,但不能整除 3")
else:
if num % 3 == 0:
print("你输入的数字可以整除 3,但不能整除 2")
else:
print("你输入的数字不能整除 2 和 3")
|
7642a7c18c5875ab24de9f61435faf080631ce13 | ZiqiNanguo/Python_Crash_Course | /Chapter5/magic_number.py | 181 | 3.546875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Jun 3 20:45:36 2018
@author: xinguang
"""
answer = 17
if answer != 42:
print("That is not the correct answer. Please try again!") |
93f4495f50ffa9c216278bdcc26b391e3e2217b9 | AbhiniveshP/CodeBreakersCode | /2 - Fundamentals/ReversePolishNotation.py | 1,548 | 4.09375 | 4 | '''
Time Complexity: O(n)
Space Complexity: O(n)
'''
class RPN:
def __compute(self, num1, num2, operator):
if (operator == '+'):
return num1 + num2
elif (operator == '-'):
return num1 - num2
elif (operator == '*'):
return num1 * num2
else:
return int(num1 / num2)
def evalRPN(self, tokens: List[str]) -> int:
# edge case check
if (tokens == None or len(tokens) == 0):
return 0
# store the set of operators in a set
operators = set([ '+', '-', '*', '/' ])
# initialize stack
stack = []
# for each token, perform the valid task
for token in tokens:
# if the token is an operator => pop top 2 numbers, perform the corresponding operation and
# then push the result to the stack
if (token in operators):
num2 = stack.pop()
num1 = stack.pop()
# helper function to perform the corresponding operation
newNumber = self.__compute(num1, num2, token)
stack.append(newNumber)
# if the token is a number => directly push it to the stack
else:
stack.append(int(token))
# return the value remaining in the stack
return stack[0] |
b6f859dea04358e922be028b8c0067468113672f | jdCarew/LD31 | /LD31.py | 5,584 | 3.625 | 4 | import sys, pygame,random
pygame.init()
##Gravity Ain't The Same (No, It Ain't!)
##By: jdCarew
##Ludum Dare 31
size = width, height= 600,400
square_width=40#size of blocks
images=["red2.bmp", "blue.bmp", "green.bmp", "yellow.bmp"]
g=0
started=0
black=0,0,0
for index, col in enumerate(images):
images[index]=pygame.image.load(col)
imagescount=len(images)
maxx=int(width/square_width)
maxy=int(height/square_width)
score=0
myfont = pygame.font.SysFont("monospace", 18)
board=[[] for i in range(maxx)]
squares=[[] for i in range(maxx)]
for r in range(maxx):
for c in range(int(height/square_width)):
board[r].append(random.randint(1,imagescount))#0 reserve for empty
screen=pygame.display.set_mode(size)
label=myfont.render("Score: 0",1,(255,255,255))
def print_board():#debug: prints board to shell as image indices
for j in range(maxy):
for i in range(maxx):
print (board[i][j], end=" ")
print()
def count_similar(x,y,b):#count around a coordinate to find
result=1 #number that are connected that share color
c=b[x][y]
b[x][y]=-1
if x<maxx-1 and b[x+1][y]==c:
result+=count_similar(x+1,y,b)
if x> 0 and b[x-1][y]==c:
result+=count_similar(x-1,y,b)
if y<maxy-1 and b[x][y+1]==c:
result+=count_similar(x,y+1,b)
if y> 0 and b[x][y-1]==c:
result+=count_similar(x,y-1,b)
return result
def check_click(x,y):
if board[x][y] > 0:
c=board[x][y]
result=count_similar(x,y,board)
if result>=3:
for i, row in enumerate(board):
for j, item in enumerate(row):
if board[i][j]== -1:
board[i][j] = 0
return score + (2 ** result)
else:
for i, row in enumerate(board):
for j, item in enumerate(row):
if board[i][j]==-1:
board[i][j] = c
return score
def gravity():
if g==0:
gravity_down()
elif g==1:
gravity_left()
elif g==2:
gravity_up()
elif g==3:
gravity_right()
screen.fill(black)
def gravity_down():
for i in range(maxx):
for j in range(maxy)[::-1]:
offset=0
while board[i][j-offset]==0:
offset+=1
if j-offset<0:
offset=0
break
if offset > 0:
board[i][j]=board[i][j-offset]
board[i][j-offset]=0
def gravity_right():
for j in range(maxy):
for i in range(maxx)[::-1]:
offset=0
while board[i-offset][j]==0:
offset+=1
if i-offset<0:
offset=0
break
if offset > 0:
board[i][j]=board[i-offset][j]
board[i-offset][j]=0
def gravity_up():
for i in range(maxx):
for j in range(maxy):
offset=0
while board[i][j+offset]==0:
offset+=1
if offset+j==maxy:
offset=0
break
if offset > 0:
board[i][j]=board[i][j+offset]
board[i][j+offset]=0
def gravity_left():
for j in range(maxy):
for i in range(maxx):
offset=0
while board[i+offset][j]==0:
offset+=1
if offset+i==maxx:
offset=0
break
if offset > 0:
board[i][j]=board[i+offset][j]
board[i+offset][j]=0
while started ==0:
Title = myfont.render("Gravity Ain't The Same (No, It Ain't!)", 1, (255,255,255))
Signoff = myfont.render("By: jdCarew", 1, (255,255,255))
ld = myfont.render("Ludum Dare 31", 1, (255,255,255))
instr = myfont.render("Click a box that is connected to at least two others", 1, (255,255,255))
instr2 = myfont.render("of the same color to score points.", 1, (255,255,255))
instr3 = myfont.render("Arrow keys control direction of gravity", 1, (255,255,255))
instr4 = myfont.render("Click anywhere to begin", 1, (255,255,255))
screen.blit(Title, (10, 50))
screen.blit(Signoff, (10, 100))
screen.blit(ld, (10, 150))
screen.blit(instr, (10, 200))
screen.blit(instr2, (10, 250))
screen.blit(instr3, (10, 300))
screen.blit(instr4, (10, 350))
pygame.display.flip()
for event in pygame.event.get():
if event.type == pygame.MOUSEBUTTONUP:
started=1
while 1:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_DOWN:
g= 0
if event.key == pygame.K_LEFT:
g= 1
if event.key == pygame.K_UP:
g= 2
if event.key == pygame.K_RIGHT:
g= 3
if event.key == pygame.K_ESCAPE:
sys.exit()
gravity()
if event.type == pygame.MOUSEBUTTONUP:
pos = pygame.mouse.get_pos()
score=check_click(int(pos[0]/40),int(pos[1]/40))
label = myfont.render("Score: "+str(score), 1, (255,255,255))
gravity()
##draws
for r, row in enumerate(board):
for c, item in enumerate(row):
if item>=1:
screen.blit(images[item-1],pygame.Rect(square_width*r,square_width*c,10,10))
screen.blit(label, (10, 10))
pygame.display.flip()
|
5d2f9ea3fb0894bc8dff5cf1eaa6349a91c725ea | gleverett/CSDS338HW2 | /FIFO1.py | 5,071 | 4 | 4 | import random
class page:
#initializes the page with a given name for the page number
def __init__(self, pgNum):
self.pageNumber = pgNum
#returns page number
def getPageNumber(self):
return self.pageNumber
#sets page number to given value
def setPageNumber(self, tmpPgNum):
self.pageNumber = tmpPgNum
class FIFO:
'''
pageList = []
capacity = 0
pageFaults = 0
'''
#initializes FIFO memory system with a given list and capacity
def __init__(self, pageList, cap):
self.pageList = []
self.capacity = cap
self.pageFaults = 0
#returns list associated with FIFO
def getPageList(self):
return self.pageList
#returns capacity of list
def getCapacity(self):
return self.capacity
#returns number of page faults
def getPageFaults(self):
return self.pageFaults
def setCapacity(self, cap):
self.capacity = cap
#checks whether or not the list is full
def full(self):
#if the length of the list is equal to the capacity value...
if(len(self.pageList)==self.getCapacity()):
print("Memory is full.")
return True
else:
return False
#finds if a given page number is already in the list
def find(self, number):
# If the page we are searching for is already in the queue, this method will return true
for i in self.pageList:
if(i.getPageNumber()==number):
return True
return False
#adds a given page to the list
def addPage(self, tmpPage):
print("swapping in page " + str(tmpPage.getPageNumber()) +"...")
tmpPageNum = tmpPage.getPageNumber()
#runs find method to see if page being added is already in memory
if(self.find(tmpPageNum)):
print("page " + str(tmpPage.getPageNumber()) + " is already in memory.")
return False
#runs full method to see if list is full and must swap out a page
if(self.full()):
self.removePage()
self.pageList.append(tmpPage)
#adds page fault
self.pageFaults+=1
print("page " + str(tmpPage.getPageNumber()) + " was added.")
print("total page faults: " + str(self.getPageFaults()))
return True
#removes page from list of memory
def removePage(self):
removedPage = self.pageList.pop(0)
print("page " + str(removedPage.getPageNumber()) + " has been removed.")
#initialize 10 different pages
page0 = page(0)
page1 = page(1)
page2 = page(2)
page3 = page(3)
page4 = page(4)
page5 = page(5)
page6 = page(6)
page7 = page(7)
page8 = page(8)
page9 = page(9)
#add all pages to an array that pages will be randomly chosen from to add to memory
files = [page(1), page(2), page(3), page(4), page(5), page(6), page(7), page(8), page(9)]
#initialize a new memory list for FIFO algorithm and initialize FIFO for random distribution
memoryList = []
FIFO1 = FIFO(memoryList, 3)
length = len(files)
#random distribution
print("\nFIFO IN RANDOM DISTRIBUTION:")
#adds a random page to FIFO memory 10 times to test random distribution
for i in range(0,length):
ranNum = random.randint(0,length-1)
FIFO1.addPage(files[ranNum])
#strongly biased towards lower numbers
print("\nFIFO BIASED TOWARDS LOWER NUMBERS:")
memoryList2 = []
FIFO2 = FIFO(memoryList2, 3)
#adds files more as their number gets lower
files2 = []
for i in range(0,512):
if (i==0):
files2.append(page9)
elif(i<=2):
files2.append(page8)
elif(i<=4):
files2.append(page7)
elif(i<=8):
files2.append(page6)
elif(i<=16):
files2.append(page5)
elif(i<=32):
files2.append(page4)
elif(i<=64):
files2.append(page3)
elif(i<=128):
files2.append(page2)
elif(i<=256):
files2.append(page1)
elif(i<=512):
files2.append(page0)
length2 = len(files2)
for i in range(0,10):
ranNum = random.randint(0,length2-1)
FIFO2.addPage(files2[ranNum])
#strongly biased towards 3<k<10, otherwise exponential (0 will be added the same amount as 3<k<10)
print("\nFIFO BIASED TOWARDS 3<K<10:")
memoryList3 = []
FIFO3 = FIFO(memoryList3, 3)
#adds files exponentially again, but for pages 3<k<10, they will all be added as much as page 0
files3 = []
for i in range(0,30):
if(i<=16):
files3.append(page0)
files3.append(page4)
files3.append(page5)
files3.append(page6)
files3.append(page7)
files3.append(page8)
files3.append(page9)
elif(i<=24):
files3.append(page1)
elif(i<=28):
files3.append(page2)
elif(i<=30):
files3.append(page3)
length3 = len(files3)
for i in range(0,10):
ranNum = random.randint(0,length3-1)
FIFO3.addPage(files3[ranNum])
|
0257b4044a9c3c1636cc3ab45948e54923f89180 | bibongbong/pythonCookBook | /src/4.3.CreateIteratorByGenerator.py | 959 | 4.28125 | 4 | '''
问题:实现一个自定义迭代模式,跟普通的内置函数range(), reversed()不一样
方案:使用一个生成器函数来定义一个新的迭代模式
'''
def frange(start, stop, step):
x = start
while x < stop:
yield x
x += step
for n in frange(0, 4, 0.5):
print(n)
'''
一个函数中需要一个yield语句即可转换为一个生成器。
跟普通函数不同的是,生成器只能用于迭代操作。
生成器函数的主要特征:它只会回应在迭代中使用到next操作
一旦生成器函数返回退出,迭代终止。
'''
def countdown(n):
print('starting to count from', n)
while n > 0:
yield n
n -= 1
print('Done!')
c = countdown(3)
print(next(c))
print(next(c))
print(next(c))
print(next(c))
'''
starting to count from 3
3
2
1
Traceback (most recent call last):
File "C:\github\pythonCookBook\src\4.3.CreateIteratorByGenerator.py", line 31, in <module>
print(next(c))
StopIteration
''' |
a53717378c0eac6d31235b68ecdc8890acdf949b | charlie-lyc/iamalso_python_basic | /29_super_pass.py | 1,297 | 3.671875 | 4 | # pass 이용
# 일반 유닛
class Unit:
def __init__(self, name, hp):
self.name = name
self.hp = hp
# 건물 짓기
class BuildingUnit(Unit):
def __init__(self, name, hp, location):
pass # 아무것도 작성되지 않았지만 코드 실행시 이상이 없는 것으로 취급하고 넘어감
# 서플라이 디폿 : 건물, 1개일때 8 유닛 생산 가능
supply_depot = BuildingUnit('서플라이디폿', 500, '7시') # 실행시 이상 없음
# print(supply_depot.name, supply_depot.hp, supply_depot.location) # AttributeError: 'BuildingUnit' object has no attribute 'name'
print('>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>')
def game_start():
print('[알림] 새로운 게임을 시작합니다.')
def game_over():
pass
game_start()
game_over()
print('>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>')
# super() 이용
# 건물 짓기
class BuildingUnit(Unit):
def __init__(self, name, hp, location):
##################################
# Unit.__init__(self, name, hp)
## 또는
super().__init__(name, hp)
##################################
self.location = location
supply_depot = BuildingUnit('서플라이디폿', 500, '7시')
print(supply_depot.name, supply_depot.hp, supply_depot.location) |
d03caa03fb3fbf6ab46585f2cd145a5ffd4a74af | jserra99/Joe-Python-Stuff | /artism.py | 2,267 | 3.90625 | 4 | #Importing necessary modules
import pygame as pg
#Asking for some user input
pen_colors = ['white', 'red', 'green', 'blue', 'yellow', 'orange', 'purple', 'black']
background = input("What color would you like the canvas background color to be? : ")
pen_option = pen_colors.index(input("Which color would you like? {} : ".format(pen_colors)))
#Setting up the game
pg.init()
size = width, height = 600, 600
screen = pg.display.set_mode(size)
screen.fill(background)
pg.display.set_caption("Artism")
pensize = 5
#Giving some instructions to the artist
print("Hold Left Click to draw and Right Click to erase.")
print("Press 1 & 2 to cycle pen colors.")
print("Press W & S to increase or decrease the pensize.")
#While loop that constantly checks for events
while True:
for event in pg.event.get():
if event.type == pg.QUIT:
pg.quit()
quit()
#Mouse events
elif pg.mouse.get_pressed() == (1, 0, 0):
mouse_pos = pg.mouse.get_pos()
pg.draw.circle(screen, pen_colors[pen_option], mouse_pos, pensize)
elif pg.mouse.get_pressed() == (0, 0, 1):
mouse_pos = pg.mouse.get_pos()
pg.draw.circle(screen, background, mouse_pos, (pensize * 2))
#Keyboard events
if event.type == pg.KEYDOWN:
if event.key == pg.K_1:
if pen_option == 0:
pen_option = (len(pen_colors) - 1)
else:
pen_option -= 1
print("Your new color is:", pen_colors[pen_option])
elif event.key == pg.K_2:
if pen_option == (len(pen_colors) - 1):
pen_option = 0
else:
pen_option += 1
print("Your new color is:", pen_colors[pen_option])
elif event.key == pg.K_w:
pensize += 1
print("Pensize increased by 1.")
elif event.key == pg.K_s:
if pensize != 1:
pensize -= 1
print("Pensize decreased by 1.")
else:
print("Pensize already at maximum smallest width.")
pg.display.update() |
613a87395ca55e2362fd49393505c1c9b7b6e62c | toba101/CS101 | /week07/work.py | 213 | 3.984375 | 4 | n=int(input('Please enter a positive integer between 1 and 15: '))
number = ""
for row in range(1, n + 1):
for col in range(1, n + 1):
number = number + 10
print(row*col, end="\t")
print() |
99a8d3897bdce1c04ab54ffd8d382588040bb594 | mr-zhouzhouzhou/LeetCodePython | /面试-2020-7-12/数组/数组中的逆序对.py | 7,061 | 3.796875 | 4 | """
题目描述
在数组中的两个数字,如果前面一个数字大于后面的数字,则这两个数字组成一个逆序对。
输入一个数组,求出这个数组中的逆序对的总数P。并将P对1000000007取模的结果输出。 即输出P%1000000007
输入描述:
题目保证输入的数组中没有的相同的数字
数据范围:
对于%50的数据,size<=10^4
对于%75的数据,size<=10^5
对于%100的数据,size<=2*10^5
1,2,3,4,5,6,7,0
7
"""
class Solution:
def __init__(self):
self.count = 0
self.tmp = None
def InversePairs(self, data):
self.tmp = [0] * len(data)
self.mergeSort(data, 0, len(data)-1)
return self.count
def mergeSort(self, data, low, high):
if low == high:
return
middle = (low + high) // 2
self.mergeSort(data, low, middle)
self.mergeSort(data, middle + 1, high)
self.merge(data, low, middle, high)
return self.count
def merge(self, data, low, middle, high):
left_data = [data[index] for index in range(low, middle+1)]
right_data = [data[index] for index in range(middle+1, high+1)]
left_index = 0
right_index = 0
data_index = low
length = 0
while left_index < len(left_data) and right_index < len(right_data):
if left_data[left_index] < right_data[right_index]:
data[data_index] = left_data[left_index]
flag = 0
while left_data[left_index] > right_data[flag]:
flag += 1
length += 1
if flag >= len(right_data):
break
data_index += 1
left_index += 1
else:
data[data_index] = right_data[right_index]
data_index += 1
right_index += 1
while left_index < len(left_data):
data[data_index] = left_data[left_index]
flag = 0
while left_data[left_index] > right_data[flag]:
flag += 1
length += 1
if flag >= len(right_data):
break
data_index += 1
left_index += 1
while right_index < len(right_data):
data[data_index] = right_data[right_index]
data_index += 1
right_index += 1
self.count += length
data = [364,637,341,406,747,995,234,971,571,219,993,407,416,366,315,301,601,650,418,355,460,505,360,965,516,648,727,667,465,849,455,181,486,149,588,233,144,174,557,67,746,550,474,162,268,142,463,221,882,576,604,739,288,569,256,936,275,401,497,82,935,983,583,523,697,478,147,795,380,973,958,115,773,870,259,655,446,863,735,784,3,671,433,630,425,930,64,266,235,187,284,665,874,80,45,848,38,811,267,575]
#data = [1,2,3,4,5,6,7,0]
#data = [364, 637, 341, 406, 747, 995, 234, 971, 571, 219, 993, 407, 416, 366, 315, 301, 601]
sSolution = Solution()
length = sSolution.InversePairs(data)
#
# # -*- coding:utf-8 -*-
# class Solution:
# def __init__(self):
# self.count = 0
# def InversePairs(self, data):
# low = 0
# high = len(data) - 1
# temp = [0] * len(data)
# count = [0]
# self.mergerSort(data, low, high, temp, count)
#
# def mergerSort(self,data, low, high, temp, count):
# if low >= high:
# return
# middle = (low + high) // 2
# self.mergerSort(data, low, middle, temp, count)
# self.mergerSort(data, middle + 1, high, temp, count)
# self.sort(data, low, middle, high, temp, count)
#
#
# def sort(self, data, low, middle, high, temp, count):
#
# if low >= high:
# return
# index_a = middle
# index_b = high
# index_temp = high
# # print("##################")
# # print(low,middle)
# #
# # print(data[low:middle+1])
# # print(middle+1, high)
# # print(data[middle+1:high+1])
# # print("#")
# while index_a >= low and index_b > middle:
# if data[index_a] >= data[index_b]:
# temp[index_temp] = data[index_a]
# length = index_b - middle
# flag = index_b
# while data[flag] == data[index_a]:
# length -= 1
# flag -= 1
# self.count += length
#
# index_a -= 1
# index_temp -= 1
# else:
# temp[index_temp] = data[index_b]
# index_b -= 1
# index_temp -= 1
# if index_a >= low:
# temp[index_temp] = data[index_a]
# index_temp -= 1
# index_a -= 1
# if index_b > middle:
# temp[index_temp] = data[index_b]
# index_b -= 1
# index_temp -= 1
# for index in range(low, high+1):
# data[index] = temp[index]
# import sys
# n = map(int, sys.stdin.readline().strip().split())
#
# for item in n:
#
# print(item)
#
#
# hangshu = 3
# a,b,c=[int(i) for i in input().split()]
# list=[]
# for i in range(hangshu):
# list.append([int(i) for i in input().split()])
# print(list)
#
# a,b,c=[int(i) for i in input().split()]
# list=[]
# for i in range(hangshu):
# list.extend([int(i) for i in input().split()])
# print(list)
#
# def convert():
# res = ""
# str = input()
# str = str.lower()
# if str[0].isalnum():
# str = str
# else:
# str = str[1:]
# flag = 0
# for i in range(0, len(str)):
# if str[i].isalnum():
# if flag == 0:
# res+= str[i]
# else:
# res += str[i].upper()
# flag = 0
# else:
# if i+1 < len(str):
# flag = 1
# print(res)
# convert()
#
#
def findNext(nums):
if len(nums) == 1:
return nums
right = len(nums) - 1
left = right - 1
hasBigger = False
while left >= 0:
if nums[right] < nums[left]:
k = right + 1
hasBigger = True
while k < len(nums):
if nums[k] >= nums[left]:
break
nums[k - 1], nums[left] = nums[left], nums[k-1]
left += 1
right -= 1
left -= 1
if not hasBigger:
left = 0
leftPart = nums[:left]
rightPart = nums[left:]
rightPart.sort()
return leftPart+rightPart
def solution(number):
numsStr = str(number)
nums = list(numsStr)
resultList = findNext(nums)
result = "".join(resultList)
return int(result)
def f(num):
nums = list(str(num))
length = len(nums) - 1
Flag = False
for index in range(length, 0, -1):
if nums[index] < nums[index-1]:
Flag = True
nums[index], nums[index-1] = nums[index-1], nums[index]
break
if Flag:
return int("".join(nums))
else:
return 0
print(f(0)) |
fb5e10f27fc4f6616b0e1740bb43da34e5656c09 | carlhinderer/python-exercises | /daily-coding-problems/problem261.py | 953 | 3.5625 | 4 | # Problem 261
# Easy
# Asked by Amazon
#
# Huffman coding is a method of encoding characters based on their frequency. Each letter
# is assigned a variable-length binary string, such as 0101 or 111110, where shorter
# lengths correspond to more common letters. To accomplish this, a binary tree is built
# such that the path from the root to any leaf uniquely maps to a character. When traversing
# the path, descending to a left child corresponds to a 0 in the prefix, while descending
# right corresponds to 1.
#
# Here is an example tree (note that only the leaf nodes have letters):
#
# *
# / \
# * *
# / \ / \
# * a t *
# / \
# c s
#
# With this encoding, cats would be represented as 0000110111.
#
# Given a dictionary of character frequencies, build a Huffman tree, and use it to determine a
# mapping between characters and their encoded binary strings.
# |
d1964a0a38896a55ac56618813737fc006541123 | azaman13/Research | /geo-alcohol/tests/testNameGenderConverter.py | 2,763 | 3.546875 | 4 | """
This is the module that tests different functions in the nameGenderConverter.py
"""
from nameGenderConverter import get_gender
import unittest
class TestGenderConverterMethods(unittest.TestCase):
# Dictionary of name as key and gender as value
FEMALE_NAMES={
"Emma" : "female","Olivia" : "female","Sophia" : "female",
"Isabella" : "female","Ava" : "female","Mia" : "female","Emily" : "female",
"Abigail" : "female","Madison" : "female","Charlotte" : "female",
"Harper" : "female","Sofia" : "female","Avery" : "female",
"Elizabeth" : "female","Amelia" : "female","Evelyn" : "female",
"Ella" : "female","Chloe" : "female","Victoria" : "female","Aubrey" : "female",
"Grace" : "female","Zoey" : "female","Natalie" : "female","Addison" : "female",
"Lillian" : "female","Brooklyn" : "female","Lily" : "female","Hannah" : "female",
"Layla" : "female","Scarlett" : "female","Aria" : "female","Zoe" : "female",
"Samantha" : "female","Anna" : "female","Leah" : "female","Audrey" : "female",
"Ariana" : "female","Allison" : "female","Savannah" : "female","Arianna" : "female",
"Camila" : "female","Penelope" : "female","Gabriella" : "female","Claire" : "female",
"Aaliyah" : "female","Sadie" : "female","Riley" : "female","Skylar" : "female",
"Nora" : "female","Sarah" : "female","Hailey" : "female","Kaylee" : "female","Paisley" : "female",
"Kennedy" : "female","Ellie" : "female","Peyton" : "female","Annabelle" : "female",
"Caroline" : "female","Madelyn" : "female","Serenity" : "female",
"Aubree" : "female","Lucy" : "female","Alexa" : "female","Alexis" : "female",
"Nevaeh" : "female","Stella" : "female","Violet" : "female",
"Genesis" : "female","Mackenzie" : "female","Bella" : "female",
"Autumn" : "female","Mila" : "female","Kylie" : "female","Maya" : "female",
"Piper" : "female","Alyssa" : "female","Taylor" : "female","Eleanor" : "female",
"Melanie" : "female","Naomi" : "female","Faith" : "female","Eva" : "female",
"Katherine" : "female","Lydia" : "female","Brianna" : "female","Julia" : "female",
"Ashley" : "female","Khloe" : "female","Madeline" : "female","Ruby" : "female",
"Sophie" : "female","Alexandra" : "female","London" : "female","Lauren" : "female",
"Gianna" : "female","Isabelle" : "female","Alice" : "female","Vivian" : "female",
"Hadley" : "female", "Jasmine": "female"
}
def test_first_names(self):
for name, gender in self.FEMALE_NAMES.iteritems():
result = get_gender(name)
self.assertEquals(result.get('gender'), 'female')
if __name__ == '__main__':
unittest.main() |
a9b3c52f98159ddb1feebc50de0489a8298beea5 | bartlesy/algo-puzzles | /twosumtwo.py | 977 | 3.953125 | 4 | # Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number.
#
# The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2.
#
# Note:
#
# Your returned answers (both index1 and index2) are not zero-based.
# You may assume that each input would have exactly one solution and you may not use the same element twice.
# Example:
#
# Input: numbers = [2,7,11,15], target = 9
# Output: [1,2]
# Explanation: The sum of 2 and 7 is 9. Therefore index1 = 1, index2 = 2.
#
class Solution:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
seen = {}
for i, x in enumerate(nums):
diff = target - x
if diff in seen:
return seen[diff] + 1, i + 1
seen[x] = i
return
|
c1343dfe8004415f7d7388083edfd2d6313269f2 | sierrajulietromeo/unit24_basicbooking | /test_booking.py | 4,303 | 3.875 | 4 | import pandas as pd #For read/write to the file.
import os
#main program menu
def main():
print("Welcome to the Ada Booking System")
print("=================================")
print("Please select from the following options")
print("1: View room bookings for Tuesday")
print("2: View room bookings for Wednesday")
print("3: View all free rooms")
try:
mainMenuSelection = int(input("Enter selection: "))
os.system("cls") #Only works on Windows machines
except ValueError:
os.system("cls") #Only works on Windows machines
main()
if(mainMenuSelection == 1):
selectedDay = "Tuesday"
viewRoomBookings(selectedDay)
elif(mainMenuSelection == 2):
selectedDay = "Wednesday"
viewRoomBookings(selectedDay)
elif(mainMenuSelection == 3):
viewFreeRooms()
else:
main()
def viewRoomBookings(selectedDay):
print("VIEW ROOM BOOKINGS FOR:",selectedDay)
print("=================================")
print("Please select from the following rooms")
print("1: SPUTNIK")
print("2: ENDEAVOUR")
print("3: VOYAGER")
viewSelection = int(input("Enter selection: "))
os.system("cls") #Only works on Windows machines
if(viewSelection == 1):
roomName = "Sputnik"
displayRoomBookings(roomName,selectedDay)
elif(viewSelection == 2):
displayRoomBookings(selectedDay)
elif(viewSelection == 3):
print("3")
else:
main()
def displayRoomBookings(roomName,selectedDay):
df = pd.read_csv("room_bookings.csv")
print(selectedDay +" Bookings")
#dayDataFrame = df[(df.Room == roomName) & (df.Day == selectedDay)]
df.set_index("Period", inplace=True)
#dayDataFrame.set_index("Period")
#print (dayDataFrame)
print(df[(df.Room == roomName) & (df.Day == selectedDay)])
#print(df[(df.Room == roomName) & (df.Day == selectedDay)] )
print("Enter the period number you wish to book, or enter any other character to go back.")
try:
periodNumber = int(input("?"))
except ValueError:
#os.system("cls") #Only works on Windows machines
main()
try:
if(periodNumber == 1 or 2 or 3 or 4 or 5 or 6 or 7):
bookRoom(roomName, periodNumber, selectedDay)
else:
os.system("cls") #Only works on Windows machines
main()
except KeyError:
main()
def bookRoom(roomName, periodNumber, selectedDay):
df = pd.read_csv("room_bookings.csv")
if(roomName == "Sputnik" and selectedDay == "Wednesday"):
periodNumber += 7
else:
periodNumber
periodNumber -= 1 #to get the right place in the array because counting starts at 0
# print(df.loc[[1]])
#if(df.loc[periodNumber] != "FREE"): #Trying to work out a more elegant solution for selecting.
if (df.at[periodNumber, "Name"] != "FREE"):
os.system("cls") #Only works on Windows machines
print ('\a')
print("Sorry, this room is already booked for that period by:", (df.at[periodNumber, "Name"]) )
print(" ")
displayRoomBookings(roomName, selectedDay)
else:
name = input("Enter name to book room under: ")
df.at[periodNumber, "Name"] = name
df.to_csv("room_bookings.csv", index=False)
if(roomName == "Sputnik" and selectedDay == "Wednesday"):
periodNumber -= 7
else:
periodNumber
periodNumber += 1 #to get the right place in the array because counting starts at 0
#os.system("cls") #Only works on Windows machines
print("Room is now booked for you at period:", periodNumber, "on", selectedDay)
print(" ")
#Loopthroughheretoseeifitsfree
main()
def viewFreeRooms():
print("FREE ROOMS")
df = pd.read_csv("room_bookings.csv")
df.set_index("Period", inplace=True)
print(df[df.Name == "FREE"] )
main()
def editRoomBooking():
#df.at[1, "Name"] = "John"
df.to_csv("room_bookings.csv", index=False)
#Sequential Code
main()
|
3789320d3e6baa5249b6a73e4c725fd24494572a | jason-padilla/DSFundamentals | /Leetcode/Blind75/23H-MergeKSortedLists.py | 763 | 4.15625 | 4 | '''
You are given an array of k linked-lists lists, each linked-list is sorted in ascending order.
Merge all the linked-lists into one sorted linked-list and return it.
Input: lists = [[1,4,5],[1,3,4],[2,6]]
Output: [1,1,2,3,4,4,5,6]
Explanation: The linked-lists are:
[ 1->4->5,
1->3->4,
2->6 ]
merging them into one sorted list:
1->1->2->3->4->4->5->6
'''
class Solution:
def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]:
values = []
for i in lists:
curr = i
while curr:
values.append(curr.val)
curr = curr.next
values.sort()
head = runner = ListNode(0)
for i in values:
runner.next = ListNode(i)
runner = runner.next
return head.next |
70ae1be3c8289800661fed9c3c096b1abe40b3f8 | aviranjan2050/share1 | /BMI.py | 186 | 3.890625 | 4 | import function_argument
def BMI(W, H):
BMI = W/(pow(H, 2))
return BMI
Weight = float(input('enter weight'))
Height = float(input('enter height'))
print(BMI(Weight, Height))
|
6f13303b572cee2d9b0f4bdeece6d64f5b9648d1 | tejamupparaju/LeetCode_Python | /leet_code902.py | 1,719 | 4.15625 | 4 | """
902. Numbers At Most N Given Digit Set
We have a sorted set of digits D, a non-empty subset of {'1','2','3','4','5','6','7','8','9'}. (Note that '0' is not included.)
Now, we write numbers using these digits, using each digit as many times as we want. For example, if D = {'1','3','5'},
we may write numbers such as '13', '551', '1351315'.
Return the number of positive integers that can be written (using the digits of D) that are less than or equal to N.
Example 1:
Input: D = ["1","3","5","7"], N = 100
Output: 20
Explanation:
The 20 numbers that can be written are:
1, 3, 5, 7, 11, 13, 15, 17, 31, 33, 35, 37, 51, 53, 55, 57, 71, 73, 75, 77.
Example 2:
Input: D = ["1","4","9"], N = 1000000000
Output: 29523
Explanation:
We can write 3 one digit numbers, 9 two digit numbers, 27 three digit numbers,
81 four digit numbers, 243 five digit numbers, 729 six digit numbers,
2187 seven digit numbers, 6561 eight digit numbers, and 19683 nine digit numbers.
In total, this is 29523 integers that can be written using the digits of D.
Note:
D is a subset of digits '1'-'9' in sorted order.
1 <= N <= 10^9
"""
# LUP Solution
class Solution(object):
def atMostNGivenDigitSet(self, D, N):
"""
:type D: List[str]
:type N: int
:rtype: int
"""
N = str(N)
result, nsize, dsize = 0, len(N), len(D)
for i in range(1, nsize):
result += dsize ** i
dp = [0] * nsize + [1]
for i in xrange(nsize - 1, -1, -1):
for d in D:
if d < N[i]:
dp[i] += len(D) ** (nsize - i - 1)
elif d == N[i]:
dp[i] += dp[i + 1]
return result + dp[0]
|
e9f56d96cd0ac14bbc4abc217a49896827430cb6 | zhh-3/python_study | /Python_code/demo3/demo2.py | 311 | 3.65625 | 4 | a = 100
def test1():
# a = 300 # name 'a' is assigned to before global declaration:全局变量生命应在其实用之前
global a # 定义a 为全局变量,修改后,全局变量也被修改了
print(a)
a = 200
print(a)
def test2():
print(a)
test1()
test2() |
37451c41a1a53dbdb07e9357c663721c525feb54 | bcorey85/python-basics | /highest_even.py | 219 | 4 | 4 | def highest_even(li):
highest = 0
for item in li:
if (item % 2 == 0 and item > highest):
highest = item
return highest
print(highest_even([10, 2, 3, 4, 8, 5, 1, 5, 2, 3, 1, 20, 12]))
|
0d7036d56e20828e8e2a346c3e1a7552fb3ab751 | tthtlc/sansagraphics | /random_graphics.py | 1,656 | 3.71875 | 4 | # random circles in Tkinter
# a left mouse click will idle action for 5 seconds
# tested with Python24 vegaseat 14sep2005
from Tkinter import *
import random
import time
##def idle5(dummy):
## """freeze the action for 5 seconds"""
## root.title("Idle for 5 seconds")
## time.sleep(5)
## root.title("Happy Circles ...")
# create the window form
def idle5(event=None):
"""freeze the action for 5 seconds and save image file"""
root.title("Idle for 5 seconds")
time.sleep(5)
root.title("Happy Circles ...")
# cv.postscript(file="circles.eps") # save canvas as encapsulated postscript
# child = SP.Popen("circles.eps", shell=True) # convert eps to jpg with ImageMagick
# child.wait()
cv.postscript(file="circles.eps")
from PIL import Image
img = Image.open("circles.eps")
img.save("circles.png", "png")
print "save"
root = Tk()
# window title text
root.title("Happy Circles ...")
# set width and height
w = 640
h = 480
# create the canvas for drawing
cv = Canvas(width=w, height=h, bg='black')
cv.pack()
# list of colors to pick from
colorList = ["blue", "red", "green", "white", "yellow", "magenta", "orange"]
# endless loop to draw the random circles
while 1:
# random center (x,y) and radius r
x = random.randint(0, w)
y = random.randint(0, h)
r = random.randint(5, 50)
# pick the color
color = random.choice(colorList)
# now draw the circle
cv.create_oval(x, y, x+r, y+r, fill=color)
# update the window
root.update()
# bind left mouse click, idle for 5 seconds
cv.bind('<Button-1>', idle5)
# start the program's event loop
root.mainloop()
|
04cc0c60ab1c23005523b95dc29cb9557ad3574e | WorasitSangjan/afs505_u1 | /assignment3/ex15_1.py | 554 | 3.734375 | 4 | # Import 'argv' from 'sys'library
from sys import argv
# Declare the file for 'argv'
script, filename = argv
# Open the input file
txt = open(filename)
# Display the input filename
print(f"Here's your file {filename}:")
# Read and display the information in inputfile
print(txt.read())
txt.close()
# Display information
print("Type the filename again")
# Ask for the input filename
file_again = input(">")
# Opent the input file
txt_again = open(file_again)
# Read and dispaly the information in inputfile
print(txt_again.read())
tex_again.close()
|
67c5fc691ab63ffd3ad502547f5fc1865999877d | SusanaMG/CursoPython1 | /08-condicionales-1.py | 1,266 | 3.71875 | 4 | # CÓDIGO CONDICIONAL
# Operadores para evaluar una operación en Pyhton
# Revisar si una condición es mayor a
balance = 500
if balance > 0:
print('Puedes pagar')
balance2 = 0
if balance2 > 0:
print('Puedes pagar')
else:
print('No tienes saldo')
# Likes
likes = 200
if likes == 200:
print('Excelente, 200 likes')
else:
print('Casi llegas a los 200')
likes2 = 200
if likes2 >= 200:
print('Excelente, 200 likes')
else:
print('Casi llegas a los 200')
# IF con texto
lenguaje = 'Python'
if lenguaje == 'Python':
print('Excelente decisión')
color = 'Blanco'
if not color == 'Blanco':
print('No es de color blanco')
else:
print('Es de color blanco')
# Evaluar un Boolean
usuario_autenticado = True
if usuario_autenticado:
print('Acceso al sistema')
else:
print('Debes iniciar sesión')
# IF ANIDADOS
# Evaluar un elemento de una lista
lenguajes = ['Python', 'Kotlin', 'Java', 'JavaScript']
if 'PHP' in lenguajes:
print('PHP sí existe')
else:
print('No, no está en la lista')
# If anidados
usuario_autenticado = True
usuario_admin = False
if usuario_autenticado:
if usuario_admin:
print('ACCESO TOTAL')
else:
print('Acceso al sistema')
else:
print('Debes iniciar sesión')
|
e37d449d0a64403136b28770a27c7abc5064f55c | chng3/Python_work | /Chapter_10_Files and Exceptions/division.py | 638 | 4.15625 | 4 | # 10.3 异常
# 10.3.1 处理ZeroDivisionError 异常
# print(5/0)
# 10.3.2 使用try_except 代码块
try:
print(5/0)
except ZeroDivisionError:
print("You can't divide by zero!")
# 10.3.3 使用异常避免崩溃
print("Give me two numbers, and I'll divide them.")
print("Enter 'q' to quit.")
while True:
first_number = input("\nFirst number: ")
if first_number == 'q':
break
second_number = input("Second number: ")
if second_number == 'q':
break
# 10.3.4 else代码块
try:
answer = int(first_number) / int(second_number)
except ZeroDivisionError:
print("You can't divide by 0!")
else:
print(answer)
|
4f9d2f105add521bd14e18189721ab9824ac284c | samuelzaleta/PythonBasico-Intermedio | /Modulo3.py | 702 | 4.25 | 4 | '''
#lee dos números
numero1 = int (input("Ingresa el primer número:"))
numero2 = int (input("Ingresa el segundo número:"))
#elegir el número más grande
if numero1> numero2:
nmasGrande = numero1
else:
nmasGrande = numero2
#imprimir el resultado
print("El número más grande es:", nmasGrande)
'''
'''
# lee tres números
numero1 = int(input("Ingresa el primer número:"))
numero2 = int(input("Ingresa el segundo número:"))
numero3 = int(input("Ingresa el tercer número:"))
# verifica cuál de los números es el mayor
# y pásalo a la variable de mayor número
numeroMayor = max(numero1,numero2,numero3)
# imprimir el resultado
print("El número más grande es:", numeroMayor)
''' |
f2ef4037e332ee211048f193d251fd001cf58867 | sxu11/Algorithm_Design | /Array/2dSearch/P4_MedianofTwoSortedArrays.py | 2,180 | 4.1875 | 4 | '''
There are two sorted arrays nums1 and nums2 of size m and n respectively.
Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).
You may assume nums1 and nums2 cannot be both empty.
Example 1:
nums1 = [1, 3]
nums2 = [2]
The median is 2.0
Example 2:
nums1 = [1, 2]
nums2 = [3, 4]
The median is (2 + 3)/2 = 2.5
'''
class Solution(object):
def findMedianSortedArrays(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: float
"""
m, n = len(nums1), len(nums2)
if n == 0:
if m % 2 == 0:
return (nums1[m / 2] + nums1[m / 2 - 1]) / 2.
else:
return nums1[m / 2]
if m == 0:
if n % 2 == 0:
return (nums2[n / 2] + nums2[n / 2 - 1]) / 2.
else:
return nums2[n / 2]
'''
the cnt of left nums is (m+n+1)/2
'''
i_min, i_max = 0, m - 1
while True:
i = (i_min + i_max) / 2 # mid, or right-to-mid
j = (m + n + 1) / 2 - (i + 1) - 1
#
if j < -1 or (j<n-1 and i >=0 and nums1[i] > nums2[j + 1]):
'''
j is too small. i too big.
'''
i_max = i - 1
elif j >= n or (i<m-1 and j>=0 and nums2[j] > nums1[i + 1]):
'''
i is too small. j too big.
'''
i_min = i + 1
else:
if j == n - 1:
min_of_right = nums1[i + 1]
elif i == m - 1:
min_of_right = nums2[j + 1]
else:
min_of_right = min(nums1[i + 1], nums2[j + 1])
if j == -1:
max_of_left = nums1[i]
elif i == -1:
max_of_left = nums2[j]
else:
max_of_left = max(nums1[i], nums2[j])
if (m + n) % 2 == 0:
return (max_of_left + min_of_right) / 2.
else:
return max_of_left |
465082fc7e6c13969f17aa38a294978b59cc5a68 | pshobbit/ejerciciosPython | /UMDC/03/04.py | 625 | 4.21875 | 4 | """
Ejercicio 04
Escribir una función que reciba un número entero e imprima su descomposición en factores primos.
>>> factoresPrimos(24)
1
2
2
2
3
>>> factoresPrimos(100)
1
2
2
5
5
>>> factoresPrimos(12)
1
2
2
3
>>> factoresPrimos(11)
1
11
>>> factoresPrimos(1)
1
>>> factoresPrimos(0)
1
"""
def factoresPrimos(n):
if n < 2:
print(1)
else:
i = 2
print(1)
while (n / 2 + 1) > i:
if n % i == 0:
print(i)
n //= i
else:
i += 1
print(n)
if __name__ == '__main__':
import doctest
doctest.testmod()
|
f3c2ef8255ee30e346fd1b62ca717d96a8af38a7 | acc-cosc-1336/cosc-1336-fall-2017-mmontemayor1 | /Homework12.py | 9,493 | 3.5 | 4 | from school_db import SchoolDB
class Person:
def __init__(self, first_name, last_name):
self.first_name = first_name
self.last_name = last_name
class Student(Person):
def __init__(self, student_id, first_name, last_name, enroll_date):
Person.__init__(self, first_name, last_name)
self.student_id = student_id
self.enroll_date = enroll_date
class Professor(Person):
def __init__(self, professor_id, first_name, last_name, hire_date):
Person.__init__(self, first_name, last_name)
self.hire_date = hire_date
self.professor_id = professor_id
class Course:
def __init__(self, course_id, title, cred_hr, professor):
self.course_id = course_id
self.title = title
self.cred_hr = cred_hr
self.professor = professor
class Enrollment:
def __init__(self, enroll_id, student, course):
self.enroll_id = enroll_id
self.course = course
self.student = student
self.grade = ''
def display(self):
print(self.enroll_id, format(self.student.first_name, '10'), format(self.student.last_name, '16'),
format(self.course.title, '20'), format(self.grade, '20'))
class Transcript:
def __init__(self, enrollments):
self.enrollments = enrollments
def print_transcript(self, student):
self.letter_grades = ['A', 'B', 'C', 'D', 'F']
print("Student: ", student.first_name, student.last_name)
credit_points = 0
grade_points = 0
total_grade_pts = 0
total_cred_hrs = 0
print("Course", " "*10, "Credit Hours ", "Credit Points ", "Grade Points ", "Grade")
for c in self.enrollments.values():
if c.student.student_id == student.student_id:
if c.grade in self.letter_grades:
total_cred_hrs += c.course.cred_hr
credit_points = self.grade_to_points(c.grade)
grade_points = c.course.cred_hr * credit_points
total_grade_pts += grade_points
print(format(c.course.title, '15'), format(c.course.cred_hr, '14'), format(credit_points, '13'),
format(grade_points, '14'), c.grade)
print(" "*28, total_cred_hrs, " "*26, total_grade_pts)
if total_cred_hrs >= 1:
gpa = total_grade_pts / total_cred_hrs
print("GPA: ", format(gpa, '.2f'))
def grade_to_points(self, letter_grade):
credit_points = 0
if letter_grade == 'A':
credit_points = 4
elif letter_grade == 'B':
credit_points = 3
elif letter_grade == 'C':
credit_points = 2
elif letter_grade == 'D':
credit_points = 1
return credit_points
class GradeBook:
def __init__(self, school_db):
self.school_db = school_db
self.enrollments = school_db.enrollments
self.students = school_db.schoolinitializer.students
def main(self):
choice = ''
while choice != 'e':
choice = self.display_menu()
if choice == '1':
student_key = int(input("Enter enroll id: "))
if student_key in self.enrollments:
confirm = self.enrollments.get(student_key)
student_grade = input("Enter a grade: ")
confirm.grade = student_grade
else:
print("Invalid enroll id.")
elif choice == '2':
student_key = int(input("Enter student ID: "))
if student_key in self.students:
student = self.students.get(student_key)
script = Transcript(self.enrollments)
script.print_transcript(student)
else:
print("Invalid student ID.")
elif choice == '3':
for enrollment in self.enrollments.values():
enrollment.display()
elif choice == '4':
self.school_db.save_data()
def display_menu(self):
print("Academics")
print()
print("1) Update Grade")
print("2) Print Student GPA")
print("3) Print All Enrollments")
print("4) Save Data")
print()
return input("Enter 1, 2, 3, or e to exit")
class Schoolinitializer:
def __init__(self):
self.students = {}
#add to student dictionary
s = Student(1, "Carson", "Alexande#r", "09012005")
self.students[s.student_id] = s
s = Student(2, "Meredith", "Alonso", "09022002")
self.students[s.student_id] = s
s = Student(3, "Arturo", "Anand", "09032003")
self.students[s.student_id] = s
s = Student(4, "Gytis", "Barzdukas", "09012001")
self.students[s.student_id] = s
s = Student(5, "Peggy", "Justice", "09012001")
self.students[s.student_id] = s
s = Student(6, "Laura", "Norman", "09012003")
self.students[s.student_id] = s
s = Student(7, "Nino", "Olivetto", "09012005")
self.students[s.student_id] = s
self.professors = {}
#professor_id first_name last_name hire_date
p = Professor(1, "Kim", "Abercrombie", "1995-03-11")
self.professors[p.professor_id] = p
p = Professor(2, "Fadi", "Fakhouri", "2002-07-06")
self.professors[p.professor_id] = p
p = Professor(3, "Roger", "Harui", "1998-07-01")
self.professors[p.professor_id] = p
p = Professor(4, "Candace", "Kapoor", "2001-01-15")
self.professors[p.professor_id] = p
p = Professor(5, "Roger", "Zheng", "2004-02-12")
self.professors[p.professor_id] = p
self.courses = {}
#add to course dictionary
c = Course(1050, "Chemistry", 3, self.professors[1])
self.courses[c.course_id] = c
c = Course(4022, "Microeconomics", 3, self.professors[5])
self.courses[c.course_id] = c
c = Course(4041, "Macroeconomics", 3, self.professors[5])
self.courses[c.course_id] = c
c = Course(1045, "Calculus", 4, self.professors[3])
self.courses[c.course_id] = c
c = Course(3141, "Trigonometry", 4, self.professors[4])
self.courses[c.course_id] = c
c = Course(2021, "Composition", 3, self.professors[2])
self.courses[c.course_id] = c
c = Course(2042, "Literature", 4, self.professors[2])
self.courses[c.course_id] = c
self.enrollments = {}
#add enrolled students into courses
enroll_id = 11050 #combine student id + chemistry id
enrollment = Enrollment(enroll_id, self.students[1], self.courses[1050])
self.enrollments[enroll_id] = enrollment
enroll_id = 14022 #combine student id + chemistry id
enrollment = Enrollment(enroll_id, self.students[1], self.courses[4022])
self.enrollments[enroll_id] = enrollment
enroll_id = 14041 #combine student id + chemistry id
enrollment = Enrollment(enroll_id, self.students[1], self.courses[4041])
self.enrollments[enroll_id] = enrollment
enroll_id = 21045 #combine student id + chemistry id
enrollment = Enrollment(enroll_id, self.students[2], self.courses[1045])
self.enrollments[enroll_id] = enrollment
enroll_id = 23141 #combine student id + chemistry id
enrollment = Enrollment(enroll_id, self.students[2], self.courses[3141])
self.enrollments[enroll_id] = enrollment
enroll_id = 22021 #combine student id + chemistry id
enrollment = Enrollment(enroll_id, self.students[2], self.courses[4041])
self.enrollments[enroll_id] = enrollment
enroll_id = 31050 #combine student id + chemistry id
enrollment = Enrollment(enroll_id, self.students[3], self.courses[1050])
self.enrollments[enroll_id] = enrollment
enroll_id = 41050 #combine student id + chemistry id
enrollment = Enrollment(enroll_id, self.students[4], self.courses[1050])
self.enrollments[enroll_id] = enrollment
enroll_id = 44022 #combine student id + chemistry id
enrollment = Enrollment(enroll_id, self.students[4], self.courses[4022])
self.enrollments[enroll_id] = enrollment
enroll_id = 54041 #combine student id + chemistry id
enrollment = Enrollment(enroll_id, self.students[5], self.courses[2021])
self.enrollments[enroll_id] = enrollment
enroll_id = 61045 #combine student id + chemistry id
enrollment = Enrollment(enroll_id, self.students[6], self.courses[1045])
self.enrollments[enroll_id] = enrollment
enroll_id = 73141 #combine student id + chemistry id
enrollment = Enrollment(enroll_id, self.students[7], self.courses[3141])
self.enrollments[enroll_id] = enrollment
init = SchoolDB(Schoolinitializer())
done = GradeBook(init)
done.main()
|
9985307b9d4002eeb893c81fb67ce9c796fd4870 | e-loq/eloq-api | /image_processing.py | 7,693 | 3.5 | 4 | import numpy as np
import matplotlib.pyplot as plt
import cv2
def show_images(images, cols=1, titles=None):
"""Display a list of images in a single figure with matplotlib.
Parameters
---------
images: List of np.arrays compatible with plt.imshow.
cols (Default = 1): Number of columns in figure (number of rows is
set to np.ceil(n_images/float(cols))).
titles: List of titles corresponding to each image. Must have
the same length as titles.
"""
assert ((titles is None) or (len(images) == len(titles)))
n_images = len(images)
if titles is None: titles = ['Image (%d)' % i for i in range(1, n_images + 1)]
fig = plt.figure()
for n, (image, title) in enumerate(zip(images, titles)):
a = fig.add_subplot(cols, np.ceil(n_images / float(cols)), n + 1)
if image.ndim == 2:
plt.gray()
plt.imshow(image)
a.set_title(title)
fig.set_size_inches(np.array(fig.get_size_inches()) * n_images)
plt.show()
def plot_two_images(img1, img2, title):
plt.subplot(121), plt.imshow(img1, cmap='gray')
plt.title('Original Image'), plt.xticks([]), plt.yticks([])
plt.subplot(122), plt.imshow(img2, cmap='gray')
plt.title(title), plt.xticks([]), plt.yticks([])
plt.show()
def show_image(img, title = ''):
plt.imshow(img, cmap='gray')
plt.show()
resolution = 100
filename = f'data/image_{resolution}_floorincluded'
input_img = cv2.imread(filename + f'.png')
# images = []
# titles = []
# images.append(input_img)
# titles.append("Input img")
# Morphology
# for x in [3,5,7,9,11,13,15,17,19,21,23,25]:
print(f'Applying morphological operations...')
kernel = np.ones((7, 7), np.uint8)
morph_img = cv2.dilate(input_img, kernel, iterations=1)
morph_img = cv2.morphologyEx(morph_img, cv2.MORPH_OPEN, kernel)
morph_img = cv2.morphologyEx(morph_img, cv2.MORPH_CLOSE, kernel)
# kernel = np.ones((6, 6), np.uint8)
# morph_img = cv2.dilate(morph_img, kernel, iterations=1)
print(f'.. done.')
cv2.imwrite(filename + f'_morph.png', morph_img)
# img_blur = cv2.medianBlur(morph_img, 3)
# cv2.imwrite(f'data/img_blur.png', img_blur)
#images.append(morph_img)
#titles.append("Img after morph")
'''
images = []
for x in [3, 5, 7, 9, 11, 13]:
kernel = np.ones((5, 5), np.uint8)
closing = cv2.morphologyEx(input_img, cv2.MORPH_CLOSE, kernel)
images.append(closing)
show_images(images)
'''
# plot_two_images(input_img, erosion, 'Erosion')
# plot_two_images(input_img, dilation, 'Dilation')
# plot_two_images(input_img, opening, 'Opening')
# plot_two_images(input_img, closing, 'Closing')
# play with different values for threshold1 and threshold2
'''
running canny with variing threshold values --> didnt change anything...
for i in np.arange(200, 1000, 100):
canny = cv2.Canny(closing, 200, i)
cv2.imwrite(f'data/canny/img_canny_{i}.png', canny)
'''
'''
for x in [3,5,7]:
canny = cv2.Canny(closing, 200, 400, apertureSize=x, L2gradient=True)
cv2.imwrite(f'data/canny_apertureSize_{x}_L2gradient.png', canny)
'''
# edge detection
canny_img = cv2.Canny(morph_img, 75, 250, apertureSize=3, L2gradient=True)
cv2.imwrite(filename + f'_canny.png', canny_img)
spacing = np.zeros((), np.uint8)
final_img = np.vstack((input_img, spacing, morph_img, spacing, canny_img))
cv2.imwrite(f'data/img_all_combined', final_img)
exit(0)
gftt_img = np.zeros((canny_img.shape[0], canny_img.shape[1]), np.uint8)
corners = cv2.goodFeaturesToTrack(canny_img, 25, 0.01, 10)
corners = np.int0(corners)
for i in corners:
x, y = i.ravel()
cv2.circle(gftt_img, (x,y), 3, 255, -1)
cv2.imwrite(f'data/img_gftt.png', canny_img)
# Harris Corner Detector
thresh = 255
# Detector parameters
blockSize = 2
apertureSize = 3
k = 0.04
img_harris = cv2.cornerHarris(canny_img, blockSize, apertureSize, k)
# cv2.imwrite(f'data/img_harris.png', img_harris)
# normalize
img_harris_norm = np.empty(img_harris.shape, dtype=np.float32)
cv2.normalize(img_harris, img_harris_norm, alpha=0, beta=255, norm_type=cv2.NORM_MINMAX)
img_harris_scaled = cv2.convertScaleAbs(img_harris_norm)
cv2.imwrite(f'data/img_harris_norm.png', img_harris_scaled)
# Drawing a circle around corners
print(img_harris.shape)
for i in range(1000):
for j in range(100):
if int(img_harris[i, j]) > thresh:
cv2.circle(img_harris, (j, i), 10, 255, 2)
cv2.imwrite(f'data/img_harris_drawn.png', img_harris)
exit(0)
# contouring
'''
contour_img = np.zeros((canny_img.shape[0], canny_img.shape[1]), np.uint8)
contour_img_2 = np.zeros((canny_img.shape[0], canny_img.shape[1]), np.uint8)
cv::RETR_EXTERNAL = 0,
cv::RETR_LIST = 1,
cv::RETR_CCOMP = 2,
cv::RETR_TREE = 3,
cv::RETR_FLOODFILL = 4
cv::CHAIN_APPROX_NONE = 1,
cv::CHAIN_APPROX_SIMPLE = 2,
cv::CHAIN_APPROX_TC89_L1 = 3,
cv::CHAIN_APPROX_TC89_KCOS = 4
contours, hierarchy = cv2.findContours(canny_img, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_SIMPLE)
cv2.drawContours(contour_img, contours, -1, 255, 3)
cv2.imwrite(f'data/contours/img_contours.png', contour_img)
histo_data = []
contours_remove = []
print(len(contours))
for i in range(len(contours)):
contourArea = cv2.contourArea(contours[i])
histo_data.append(contourArea)
if contourArea < 20:
contours_remove.append(i)
for i in range(len(contours_remove), 0, -1):
del contours[contours_remove[i-1]]
del histo_data[contours_remove[i-1]]
print(len(contours))
cv2.drawContours(contour_img_2, contours, -1, 255, 3)
cv2.imwrite(f'data/contours/img_contours_2.png', contour_img_2)
'''
# laplacian = cv2.Laplacian(morph_img, cv2.CV_8U)
# sobel = cv2.Sobel(morph_img, cv2.CV_64F, 1, 1, ksize=5) # try 1,1 instead of 1,0 or 0,1
# sobelx = cv2.Sobel(morph_img, cv2.CV_64F, 1, 0, ksize=5) # try 1,1 instead of 1,0 or 0,1
# sobely = cv2.Sobel(morph_img, cv2.CV_64F, 0, 1, ksize=5) # also change kernel size
#images.append(canny)
#titles.append("Canny img")
# blurring
#blur = cv2.blur(canny, (3, 3))
#gaussian_blur = cv2.GaussianBlur(canny, (3, 3), 1)
#median_blur = cv2.medianBlur(canny, 3)
#bilateral_blur = cv2.bilateralFilter(canny, 9, 9 * 2, 9. / 2)
# cv2.imwrite('data/img_canny.png', canny)
# cv2.imwrite('data/img_laplacian.png', laplacian)
# cv2.imwrite('data/img_sobelx.png', sobelx)
# cv2.imwrite('data/img_sobely.png', sobely)
# plot_two_images(input_img, canny, 'Canny')
# plot_two_images(input_img, laplacian, 'Laplacian')
# plot_two_images(input_img, sobelx, 'SobelX')
# plot_two_images(input_img, sobely, 'SobelY')
# Hough Line Transform
'''
img_hough = np.zeros((canny_img.shape[0], canny_img.shape[1]), np.uint8)
lines = cv2.HoughLines(canny_img, 1, np.pi / 180, 200, None, 0, 0)
print(len(lines))
if lines is not None:
for i in range(0, len(lines)):
rho = lines[i][0][0]
theta = lines[i][0][1]
a = math.cos(theta)
b = math.sin(theta)
x0 = a * rho
y0 = b * rho
pt1 = (int(x0 + 1000 * (-b)), int(y0 + 1000 * (a)))
pt2 = (int(x0 - 1000 * (-b)), int(y0 - 1000 * (a)))
cv2.line(img_hough, pt1, pt2, 255, 3, cv2.LINE_AA)
cv2.imwrite(f'data/img_hough.png', img_hough)
# Hough Line P Transform
# for x in range(1, 20):
img_houghp = np.zeros((canny_img.shape[0], canny_img.shape[1]), np.uint8)
linesP = cv2.HoughLinesP(image=canny_img, rho=1, theta=np.pi / 180, threshold=40, minLineLength=10, maxLineGap=10)
print(len(linesP))
if linesP is not None:
for i in range(0, len(linesP)):
l = linesP[i][0]
cv2.line(img_houghp, (l[0], l[1]), (l[2], l[3]), 255, 3, cv2.LINE_AA)
# cv2.imwrite(f'data/houghp_test/img_houghp_{x}.png', img_houghp)
cv2.imwrite(f'data/img_houghp.png', img_houghp)
''' |
48818fc5a9906cfecfb6198ddd279f84f19173fd | Raghav14200/python | /1month/first_exercise.py | 117 | 3.859375 | 4 | dict={'go':'come','I':'You','play':'played'}
x=input('Enter the word u are searching for')
print(dict[x])
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.