blob_id
string | repo_name
string | path
string | length_bytes
int64 | score
float64 | int_score
int64 | text
string |
---|---|---|---|---|---|---|
19ffc6c86b80cfe45d9bf4daaa32f08a26f67be1
|
jacquerie/leetcode
|
/leetcode/1470_shuffle_the_array.py
| 515 | 3.6875 | 4 |
# -*- coding: utf-8 -*-
from typing import List
class Solution:
def shuffle(self, nums: List[int], n: int) -> List[int]:
return [
(nums[i // 2] if i % 2 == 0 else nums[i // 2 + n]) for i in range(2 * n)
]
if __name__ == "__main__":
solution = Solution()
assert [2, 3, 5, 4, 1, 7] == solution.shuffle([2, 5, 1, 3, 4, 7], 3)
assert [1, 4, 2, 3, 3, 2, 4, 1] == solution.shuffle([1, 2, 3, 4, 4, 3, 2, 1], 4)
assert [1, 2, 1, 2] == solution.shuffle([1, 1, 2, 2], 2)
|
af961afa4d66fb0cc00f0bbf5dcf8ca4558e6995
|
johmarpc/Python_Homeworks
|
/Practica4.py
| 2,303 | 3.859375 | 4 |
# Practica IV: Python
# 1- Modele tres entidades del mundo real, colocar por lo menos 3 características distintivas.
Invoice = ("Costos ", "Ingresos ", "deudas")
Account = ("Acceso ", "Informacion ", "Conatabilidad ")
Customers = ("Persona ", "Comapañia ", "Organizacion ")
# 2- Crear una clase llamada Estudiante con un campo llamado promedio, el cual solo podrá ser accedido mediante un metodo.
# El valor del promedio no puede estar por encima de 100 que es la nota máxima.
class Student:
def __init__(self, promedio):
self.promedio = promedio
promedio > 100
# 3- Hacer una clase llamada Aritmética, que contenga métodos para cada una de las operaciones aritméticas básicas.
class Aritmetica:
def Math(self, Add, Sub, Mul):
pass
def self.add:
1 + 1
def self.Sub:
1 - 1
def self.Mul:
1 * 1
# 4- Cree una clase llamada Personaje con los métodos de instancia MoverArriba, MoverAbajo, MoverDerecha y MoverIzquierda.
# Cree una clase llamada Mario y otra clase llamada Koopa que herede las funcionalidades de la clase Personaje.
class Personaje:
moveUp
moveDown
moveLeft
moveRight
class Mario(Personaje):
Personaje.moveUp
Personaje.moveDown
Personaje.moveLeft
Personaje.moveRight
class Koopa(Personaje): #Bowser
Personaje.moveUp
Personaje.moveDown
Personaje.moveLeft
Personaje.moveRight
# 5- Cree una clase Carro, con un campo llamado _cantidadCombustible y un método que se llame Encender el cual en base
# a la gasolina disponible mostrara si el carro pudo o no avanzar. Cada vez que el método se ejecute,
# deberá restarse 1 a la gasolina disponible. La cantidad de gasolina debe establecerse al momento de instanciar
# un objeto de del tipo de la clase.
class Car:
def __init__(self, galones):
self.cantidadCombustible = galones
def Encender(self):
if self.encedido == False and self.cantidadCombustible > 0:
self.encedido = True
print("Start Car")
def Apagar(self):
if self.encendido:
self.encedido = False
def Acelerar(self):
if self.encedido:
self.cantidadCombustible = 1
def Frenar(self):
print("Stop")
|
16606f3d18cda760153cca99839de2b709c38cac
|
hbcelebi/leetcode
|
/#67_ Add_Binary/main.py
| 1,156 | 3.8125 | 4 |
"""
Created on Mon May 3 14:40:08 2021
@author: hbc
"""
# This is a O(N) computational complexity and O(1) space complexity solution to the problem
from typing import List
class Solution:
def addBinary(self, a: str, b: str) -> str:
num_carry = 0
str_result = []
len_a, len_b = len(a)-1, len(b)-1
# do the binary adition inside the loop
while len_a >= 0 or len_b >= 0:
num_sum = num_carry
if len_a >= 0:
num_sum += int(a[len_a])
len_a -= 1
if len_b >= 0:
num_sum += int(b[len_b])
len_b -= 1
# update the carry
num_carry = num_sum // 2
# append the binary result
str_result.append(str(num_sum%2))
# the loop is done. if carry = 1, append it
if num_carry:
str_result.append(str(1))
# reverse the list and convert it to string and return
return ''.join(reversed(str_result))
s = Solution()
result = s.addBinary("1010", "1011")
print(result)
|
05c2a2175f497ff9886707f520c2ed0584da0048
|
gbroiles/hashext
|
/mh.py
| 1,080 | 3.578125 | 4 |
#! /usr/bin/env python3
import argparse
import hashlib
def create_parse():
""" set up parser options """
parser = argparse.ArgumentParser(description="file hashing utility")
parser.add_argument("target", help="one or more files to be hashed", nargs="+")
return parser
def Many_Hash(filename):
""" calculate hashes for given filename """
with open(filename, "rb") as f:
data = f.read()
md5 = hashlib.md5(data).hexdigest()
sha1 = hashlib.sha1(data).hexdigest()
sha256 = hashlib.sha256(data).hexdigest()
sha512 = hashlib.sha512(data).hexdigest()
return len(data), md5, sha1, sha256, sha512
def main():
""" main event loop """
parser = create_parse()
args = parser.parse_args()
targets = args.target
for target in targets:
size, md5, sha1, sha256, sha512 = Many_Hash(target)
print(
"Name: {}\nSize: {:,}\nMD5: {}\nSHA1: {}\nSHA256: {}\nSHA512: {}\n".format(
target, size, md5, sha1, sha256, sha512
)
)
if __name__ == "__main__":
main()
|
22a722a3f4aa9626a78de5448a07d935b219a66e
|
sarinac/reuters-21578-text-categorization
|
/src/modules/preprocessing/vectorizer.py
| 2,646 | 3.953125 | 4 |
"""Functions for generating bag of words."""
from collections import Counter
import numpy as np
def generate_bow(tokens_list: list, max_vocab=10000) -> dict:
"""Convert tokenized words into bag of words.
This will be used to keep track of word count in the train data.
Parameters
----------
tokens_list : list
list of token lists -> [["example", "sentence"], ["apple"]]
max_vocab: int, default 10000
maximum number of words in bag of words
Returns
-------
dict
dict of {token: frequency} in descending order
"""
frequency = Counter()
for tokens in tokens_list:
frequency.update(tokens)
print(f"""
The most common words from {len(frequency)} documents are
{", ".join([f"{word[0]} ({word[1]})" for word in frequency.most_common(5)])}.
""")
frequency = dict(sorted(frequency.items(), key=lambda item: -item[1]))
# Truncate to max vocab size
original_length = len(frequency)
frequency = dict(list(frequency.items())[:min(max_vocab, len(frequency))])
print(f"Truncated word dictionary from {original_length} to {min(max_vocab, len(frequency))} words.")
return frequency
def encode_and_pad(word_dict, sentence, pad=800):
"""Convert a sentence into a padded vector of numerical encodings.
Parameters
----------
word_dict : dictionary
word dictionary for bag of words
sentence : str
body text
pad : int
size of vector (default=800)
Returns
-------
list
vectorized sentence
"""
NOWORD = 0 # 0 = no word in document
INFREQ = 1 # 1 = word in document but not in word dictionary
working_sentence = [NOWORD] * (pad)
for word_index, word in enumerate(sentence[:pad]):
working_sentence[word_index] = word_dict.get(word, INFREQ)
return working_sentence
def vectorize_data(word_dict, data, pad=800):
"""Convert all sentences in the dataset into a padded vector
of numerical encodings. The length of the sentence will be
the 0th element and the sentence will start on the 1st element.
Parameters
----------
word_dict : dictionary
word dictionary for bag of words
data : list
list of sentences (list of words)
pad : int
size of vector (default=800)
Returns
-------
np.array
numpy array (matrix) of each processed sentence
"""
result = []
for sentence in data:
vectorized_sentence = encode_and_pad(word_dict, sentence, pad)
result.append(vectorized_sentence)
return np.array(result)
|
b9463c1231de0e4b87edb2966e541cb9eb2b97bc
|
efraesco/Python
|
/Reto-4.py
| 2,455 | 3.578125 | 4 |
def crear_usuarios (empleados: list):
usuarios_codigo=[]
usuarios_nombre=[]
lista_usuarios=[]
for empleado in empleados:
cadena=[]
usuarios_codigo.append(empleado['cod_empleado'])
cadena.append(empleado['nombre1'][0])
if empleado['nombre2'] == '':
cadena.append(empleado['nombre1'][1])
else:
cadena.append(empleado['nombre2'][0])
cadena.append(empleado['fecha_nacimiento'][-2:])
cadena.append(empleado['apellido1'][0])
if empleado['apellido2'] == '':
cadena.append(empleado['apellido1'][1])
else:
cadena.append(empleado['apellido2'][0])
buscar_cadena=''.join(cadena)
buscar_cadena=''.join((map(lambda x: x.upper(), buscar_cadena)))
for usuario in lista_usuarios:
contador=0
while usuario == buscar_cadena:
contador += 1
buscar_cadena=''.join(cadena)+str(contador)
lista_usuarios.append(buscar_cadena)
usuarios_nombre.append((empleado['cod_empleado'],buscar_cadena))
print("##")
print("------------------------")
print(lista_usuarios)
print("------------------------")
print("##")
return usuarios_nombre
empleados1=[{'cod_empleado': 'EMPL_001', 'nombre1':'Rodrigo', 'nombre2': 'Andres', 'apellido1':'Estupiñan', 'apellido2': 'Zapata','fecha_nacimiento': '23-10-1993'},
{'cod_empleado': 'EMPL_002', 'nombre1':'Ramiro', 'nombre2': 'Alberto', 'apellido1':'Espitia', 'apellido2': 'Zambrano','fecha_nacimiento': '01-02-1993'},
{'cod_empleado': 'EMPL_003', 'nombre1':'Rene', 'nombre2': 'Alejandro', 'apellido1':'Echavarria', 'apellido2': 'Zamudio','fecha_nacimiento': '02-09-1993'}]
empleados2=[{'cod_empleado': 'EMPL_001', 'nombre1':'Rodrigo', 'nombre2': 'Andres', 'apellido1':'Estupiñan', 'apellido2': 'Zapata','fecha_nacimiento': '23-10-1993'},
{'cod_empleado': 'EMPL_002', 'nombre1':'Javier', 'nombre2': '', 'apellido1': 'Guzman','apellido2': '', 'fecha_nacimiento': '01-02-1987'},
{'cod_empleado': 'EMPL_003', 'nombre1': 'Rene', 'nombre2': 'Alejandro', 'apellido1': 'Echavarria', 'apellido2':'Zamudio', 'fecha_nacimiento': '02-09-1982'}]
print(crear_usuarios(empleados1))
print(crear_usuarios(empleados2))
|
f936f3e3f079aa7a3cd88403d0071dca68c059b0
|
cristan563/practicas
|
/pares.py
| 140 | 3.9375 | 4 |
x = input("ingresa un numero \n")
y = int(x)
if (y % 2) == 0:
print('el numero es par')
else:
print('el numero es impar')
|
ea5b51b5e8b30cbfc8961c7865d696e135d52437
|
bscalera/Illuminate
|
/ColorLibrary.py
| 1,144 | 3.703125 | 4 |
class Colors:
#we can add more colors here
def returnRGBVal(self, color):
if color == 'yellow':
return "225,225,0"
elif color == 'red':
return "225,0,0"
elif color == 'lime':
return "0,225,0"
elif color == 'blue':
return "0,0,225"
elif color == 'green':
return "0,128,0"
elif color == 'purple':
return "128,0,128"
elif color == 'navy':
return "0,0,128"
else:
return 'not a valid color'
#Get colors from http://www.cloford.com/resources/colours/500col.htm
if color == 'indian red':
return "176,23,31"
elif color == 'crimson':
return "220,20,60"
elif color == 'lightpink':
return "255,182,193"
elif color == 'lightpink 1':
return "255,174,185"
elif color == 'lightpink 2':
return "238,162,173"
elif color == 'lightpink 3':
return "205,140,149"
elif color == 'lightpink 4':
return "139,95,101"
else:
return 'not a valid color'
#process string
def returnRed(self,RGBVal):
return int(RGBVal.split(",")[0])
def returnGreen(self,RGBVal):
return int(RGBVal.split(",")[1])
def returnBlue(self, RGBVal):
return int(RGBVal.split(",")[2])
|
32295d3c8e89207837d108173351697ec669379c
|
perperperperper/realPythonTCPServer
|
/venv/Include/realPythonServ2.py
| 874 | 3.609375 | 4 |
#!/usr/bin/env python3
# TCP server. Will listen and receive data until client closes connection
# Adapted by Per dahlstrøm
import socket # Fetch the socket module
HOST = '127.0.0.1' # Standard loopback interface address (localhost)
PORT = 65432 # Port to listen on (non-privileged ports are > 1023)
DataCommingIn = True
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen()
print('Awaiting connection on IP: ',s.getsockname()[0],\
' Port: ',s.getsockname()[1])
connection, fromAddress = s.accept() # Wait and create connection object
print('Connection from:', fromAddress)
while DataCommingIn:
receivedData = connection.recv(16)
print(receivedData.decode('utf-8'))
if not receivedData:
DataCommingIn = False
connection.close()
print('Connection closed')
s.close()
print('Socket closed')
|
9627a96bde35c0aa127290c7f204f0da081d1aae
|
jskd/ProgComp
|
/defis/0/viaud/anagram.py
| 1,527 | 3.9375 | 4 |
# Viaud
# Python 2
import sys
def open_file(filename):
f = open(filename, 'r')
return f
def populate_dict(word, dictionary):
for char in word:
# On pourrait utiliser une ternaire ici mais je laisse volontairement
# comme ca pour la lisibilite !
if char in dictionary:
dictionary[char] += 1
else:
dictionary[char] = 1
def are_anagrams(word1, word2):
wd1 = {}
wd2 = {}
populate_dict(word1, wd1)
populate_dict(word2, wd2)
return cmp(wd1, wd2) == 0
# Plus lent hehe !
def are_anagrams_2(word1, word2):
return sorted(list(word1.lower())) == sorted(list(word2.lower()))
def compute(file, anagrams):
for line in file:
sanitized = line.replace('\n', '')
for word in sys.argv[2:]:
if are_anagrams(word.lower(), sanitized.lower()):
if word in anagrams:
anagrams[word].append(sanitized)
else:
anagrams[word] = [sanitized]
# Affiche les anagrams a partir du dictionnaire
# Cles = Mots, Valeurs = liste de mots
def print_anagrams(anagrams):
if len(anagrams) == 0:
print "No anagrams found!"
else:
for word in anagrams:
print word + ":"
for anagram in anagrams[word]:
print anagram
try:
filename = sys.argv[1]
f = open_file(filename)
anagrams = {}
compute(f, anagrams)
print_anagrams(anagrams)
except:
sys.exit("Please provide a valid dictionary.")
|
6b0e1adb8df74dc432fab96cdcf43af67a20fa61
|
claraj/ProgrammingLogic1150Examples
|
/3_if_statements/quiz_3.py
| 493 | 4.4375 | 4 |
"""
Quiz program, version 3. This prints a message if the user gets the
answer right or wrong.
It also converts the user's answer to lowercase and compares it to the
lowercase version of the right answer, so the user can answer in any case,
Madison and MADISON and madison are all right.
"""
print('Quiz program!')
answer = input('What is the capital of Wisconsin? ') # It's Madison
if answer.lower() == 'madison':
print('Correct!')
else:
print('Sorry, the answer is Madison.')
|
6c5975fe77b1403ac53b1e7b7b9f8324b2678821
|
lw2000017/ibuy_test
|
/没事练习/test_1_水仙花.py
| 1,076 | 3.796875 | 4 |
# -*- coding:utf-8 -*-
# @Time :2019/5/15 11:28
# @Author :LW
# @File :test_1_水仙花.py
def narcissistic_number_1(num):
length = len(str(num))
count = length
num_sum = 0
while count:
num_sum += ((num // 10 ** (count - 1)) % 10) ** length
count -= 1
else:
if num_sum == num:
print("%d is %d bit narcissistic_number" % (num, length))
else:
print("%d is not a narcissistic_number" % num)
narcissistic_number_1(153)
str1 = '100'
if str1.endswith('00'):
str1 = f'{str1[:-2]}.{str1[-2:]}'
print(str1)
elif str1.endswith('0'):
str1 = f'{str1[:-2]}.{str1[-2:-1]}'
print(str1)
else:
str1 = f'{str1[:-2]}.{str1[-2:]}'
print(str1)
name = 'jackfrued'
fruits = ['apple', 'orange', 'grape']
owners = {'1001': '骆昊', '1002': '王大锤'}
if name and fruits and owners:
print('I love fruits!')
fruits = ['orange', 'grape', 'pitaya', 'blueberry']
for index, fruit in enumerate(fruits):
print(index, ':', fruit)
|
217d306748ae4982f8804a3c1a4d9e18bbb7b2ee
|
ChastityAM/Python
|
/Python-sys/simpleCalculator.py
| 443 | 4.09375 | 4 |
#This will take input from the user
a = int(input("Please enter a number: "))
b = int(input("Please enter another number. NOT ZERO: "))
#This will add
def add(a, b):
sum = a + b
return sum
#This will subtract
def sub(a, b):
dif = a - b
return dif
sum = add(a, b)
dif = sub(a, b)
#This will print the lines you wanna see
print("The sum of your two numbers is", sum)
print("The difference of your two numbers is", dif)
|
0e93f1733b79e7a4d545c36a3c9e303711b9fef8
|
RiddhiDamani/Python
|
/Ch9/immutable_start.py
| 613 | 4.3125 | 4 |
# Python Object Oriented Programming by Joe Marini course example
# Creating immutable data classes - data cannot be changed
from dataclasses import dataclass
@dataclass(frozen=True) # TODO: "The "frozen" parameter makes the class immutable
class ImmutableClass:
value1: str = "Value 1"
value2: int = 0
def somefunc(self, newval):
self.value2 = newval
obj = ImmutableClass()
print(obj.value1)
# TODO: attempting to change the value of an immutable class throws an exception
obj.value1 = "Ana"
print(obj.value1)
# TODO: even functions within the class can't change anything
obj.somefunc(20)
|
7f61454d02531685fa0c9881b884a46ec67aba4a
|
janFrancoo/Project-Euler
|
/problem21/p21.py
| 611 | 3.5625 | 4 |
import math
def sum_of_divisors(number):
total = 1
for i in range(2, int(math.sqrt(number)) + 1):
if number % i == 0:
total += i + (number//i)
return total
def amicable_numbers(limit):
result = 0
number_list = [sum_of_divisors(i) for i in range(limit + 1)]
for i in range(1, limit):
if 0 < number_list[i] < limit:
if i == number_list[number_list[i]]:
if i != number_list[i]:
result += i + number_list[i]
number_list[number_list[i]] = 0
return result
print(amicable_numbers(10000))
|
df56894482226dab4bd705a918383082359c33eb
|
MickysxD/EDD_1S2019_P1_201700543
|
/Pila/Pila.py
| 668 | 3.546875 | 4 |
class Pila():
def __init__ (self):
self.cima = None
self.contador = 0
def push(self, comida):
snack = comida
if (self.cima == None):
self.cima = snack
self.contador += 1
else:
snack.abajo = self.cima
self.cima = snack
self.contador += 1
def pop(self):
if (self.cima == None):
self.cima = None
else:
temp = self.cima
nuevo = self.cima.abajo
self.cima = nuevo
temp.abajo = None
self.contador -= 1
return temp
def peek(self):
return self.cima
|
599966911ef42c9f62bfe461ad8be0dd99a89d3d
|
itzelot/CYPItzelOT
|
/libro/ejemplo1_14.py
| 173 | 3.96875 | 4 |
NUM = int(input("Ingresa un número entero positivo:"))
CUA = NUM * NUM
CUB = NUM ** 3
print(f"El cuadrado del número {NUM} es {CUA} y el cubo del número {NUM} es {CUB}")
|
e87d6005e1e1b8df1409c7ce36b49b922c5c22a2
|
itsuttida/Python
|
/for2.py
| 132 | 4.0625 | 4 |
count = int(input("ใส่จำนวนรอบ : "))
for i in range(10 , count ,-3) :
print("รอบที่ : ", i)
|
0cbd2216035ac628638863adc8c72b5b60d2d642
|
lucianhaj/CS362_HW4
|
/Volume.py
| 766 | 3.90625 | 4 |
def volume(l, w, h):
try:
x = float(l) * float(w) * float(h)
except FloatingPointError:
return "error with your input(s) type"
except ArithmeticError:
return "invalid input(s) type"
except ValueError:
return "One of inputs was not a float"
except SyntaxError:
return "Arguments not of the correct format"
else:
if float(l) == 0 or float(w) == 0 or float(h) == 0:
if float(l) < 0 or float(w) < 0 or float(h) < 0:
return "Error: negative value"
else:
return "No volume"
elif float(l) < 0 or float(w) < 0 or float(h) < 0:
return "Error: negative value"
else:
return x
|
4d64bb801d175aaab673e1cb1b21acee390ad87e
|
alex-ta/Fontinator
|
/DataGenerator/libs/WordDict.py
| 1,616 | 4.1875 | 4 |
import random as rand
class WordDict:
"""
Allows creating a random sentence.
"""
def __init__(self, word_dict: list):
"""
Creates an WordDict object from a list of words.
which will be used as random word source
:param word_dict: A list of words
"""
self._ger_word_dict = word_dict
def load_from_textfile(input_file_path: str, enc="UTF8"):
"""
Creates an WordDict object from an text file.
:param input_file_path: The path to the text file
:param enc: The encoding of the text file.
:return: A WordDict object
"""
ger_word_dict = []
with open(input_file_path, encoding=enc) as f:
for line in f:
words = line.split(sep=' ')
words[len(words) - 1] = words[len(words) - 1].replace('\n', '')
ger_word_dict.extend(words)
return WordDict(ger_word_dict)
def get_sentence(self, word_count: int):
"""
Creates an sentence with <word_count> words
:param word_count: The number of words in the returned sentence
:return: A string containing random words
"""
sentence = ""
for i in range(word_count):
r_int = rand.randint(0, len(self._ger_word_dict) - 1)
rand_word = self._ger_word_dict[r_int]
sentence += rand_word + " "
return sentence
def get_word_count(self):
"""
Returns the size of word dict
:return: The size of words in the WordDict
"""
return len(self._ger_word_dict)
|
7c9475b68de9fba85e73edf8471b752db11aa8b3
|
scottherold/python_refresher_8
|
/createDB/checkdb.py
| 415 | 4.09375 | 4 |
# quick check for the contacts table
import sqlite3
conn = sqlite3.connect("contacts.sqlite")
# user input
user_name = input("Please enter your name ")
# example of passing a single argument to a tuple; you must include the
# trailing comma, or it will turn the single value provided into a tuple
for row in conn.execute("SELECT * FROM contacts WHERE name LIKE ?",
(user_name,)):
print(row)
conn.close()
|
17e6bf662cfd7977b77c494df70ca83605351c76
|
atulmkamble/100DaysOfCode
|
/Day 34 - Quizzler Game/ui.py
| 2,396 | 3.671875 | 4 |
"""
This file implements the QuizInterface class for UI of Quizzler game
"""
import tkinter as tk
from quiz_brain import QuizBrain
THEME_COLOR = "#375362"
class QuizInterface:
def __init__(self, quiz_brain: QuizBrain):
self.quiz = quiz_brain
self.window = tk.Tk()
self.window.title('Quizzler')
self.window.config(padx=20, pady=20, bg=THEME_COLOR)
self.canvas = tk.Canvas(width=300, height=250, bg='white')
self.question_text = self.canvas.create_text(
150,
125,
text='Hello',
font=('Arial', 20, 'italic'),
fill=THEME_COLOR,
width=280
)
self.canvas.grid(row=1, column=0, columnspan=2, pady=50)
correct_image = tk.PhotoImage(file='./images/true.png')
self.btn_correct = tk.Button(image=correct_image, highlightthickness=0, command=self.check_correct)
self.btn_correct.grid(row=2, column=0)
wrong_image = tk.PhotoImage(file='./images/false.png')
self.btn_wrong = tk.Button(image=wrong_image, highlightthickness=0, command=self.check_wrong)
self.btn_wrong.grid(row=2, column=1)
self.lbl_score = tk.Label(text=f'Score: {0}', fg='white', bg=THEME_COLOR)
self.lbl_score.grid(row=0, column=1)
self.get_next_question()
self.window.mainloop()
def get_next_question(self):
self.canvas.config(bg='white')
if self.quiz.still_has_questions():
self.lbl_score.config(text=f'Score: {self.quiz.score}/{len(self.quiz.question_list)}')
q_text = self.quiz.next_question()
self.canvas.itemconfig(self.question_text,
text=f'{q_text}')
else:
self.canvas.itemconfig(
self.question_text,
text=f'You have reached the end of quiz.'
)
self.btn_correct.config(state='disabled')
self.btn_wrong.config(state='disabled')
def check_correct(self):
self.give_feedback(self.quiz.check_answer('true'))
def check_wrong(self):
self.give_feedback(self.quiz.check_answer('false'))
def give_feedback(self, is_right: bool):
if is_right:
self.canvas.config(bg='green')
else:
self.canvas.config(bg='red')
self.window.after(1000, self.get_next_question)
|
0ada5c86b51baee59c887739970529db4cf19a14
|
sealanguage/pythonExercisesDataSci
|
/nested_loops.py
| 112 | 3.734375 | 4 |
for number in range(1, 11) :
print(" ")
for count in range(0, number) :
print(number, end = " ")
|
365a3b8eb04eaaf4957ab01509b8e359daba52e8
|
Fendo5242/semana-7
|
/Nueva carpeta/5.py
| 177 | 3.609375 | 4 |
a=0
b=1
n = int(input("Ingrese el límite: "))
suma=0
for number in range (1,n ,1) :
c=a+b
a=b
b=c
print(b)
suma += b
print("La suma es :", suma)
|
d26b7c70f3dc60a7283fe04e2acf8cfa7714234e
|
Jin-SukKim/Algorithm
|
/Problem_Solving/leetcode/linear_data_structure/Arrangement/42_Trapping_Rain_Winter/rain_drop_v2.py
| 955 | 3.5 | 4 |
# stack을 활용한 풀이
def trap(self, height: List[int]) -> int:
stack = []
volume = 0
for i in range(len(height)):
# 현재 높이가 이전 높이보다 높을 떄,
# 즉 꺽이는 부분 변곡점(Inflection Point)을 기준으로
# 격차만큼 물 높이(volume)를 채운다.
while stack and height [i] > height[[stack[-1]]]:
# 변곡점을 만나면 스택에서 꺼낸다
top = stack.pop()
if not len(stack):
break
# 이전과의 차이만큼 물 높이를 채운다
distance = i - stack[-1] - 1
waters = min(height[i], height[stack[-1]]) - height[top]
volume += distance * waters
# 높이는 고정된 형태가 아니라 들쑥날쑥하기 때문에 계속 스택으로 채워 나간다.
stack.append(i)
return volume
|
a0277106e43dd6d5d0015b408922bc595628f5a3
|
greatabel/PythonRepository
|
/04Python workbook/ch4function/82taxifare.py
| 234 | 3.9375 | 4 |
import math
def fare(distance):
return 0.25 * (distance/140) + 4
line = input("Enter distance:(km):")
while line != "":
distance = float(line)
print('distance fare=%0.2f' % fare(distance*1000))
line = input("Enter distance:")
|
4368b11a93f1807e7a8bc7614acb699351c5cbf8
|
asymmetry/leetcode
|
/0038_count_and_say/solution_1.py
| 715 | 3.625 | 4 |
#!/usr/bin/env python3
class Solution:
def countAndSay(self, n):
"""
:type n: int
:rtype: str
"""
if n == 1:
return '1'
if n == 2:
return '11'
s = self.countAndSay(n - 1)
result = ''
count = 1
old_char = s[0]
for _, char in enumerate(s[1:]):
if char == old_char:
count += 1
else:
result += str(count) + old_char
old_char = char
count = 1
result += str(count) + old_char
return result
if __name__ == '__main__':
print(Solution().countAndSay(1))
print(Solution().countAndSay(4))
|
5630f1fdcfcc11190aeee693715672fd087b24ac
|
Toufikkk/tpPython
|
/JOUR3/Forme1.py
| 567 | 3.640625 | 4 |
#TP geometrie
class Form:
def __init__(self, x,y):
self.x = x
self.y = y
def calculer_distance(self):
print('je calcule la distance')
def calculer_perimetre(self):
print('je calcule le calculer_perimetre')
def afficher(self):
print('je calcule le perimètre')
class Rectangle(Form):
def __init__(self,x,y):
Form.__init__(self,x,y)
def calculer_perimetre(self):
perimetre = self.x * self.y
return 'le perimetre est {}'.format(perimetre)
def __str__(self):
print('les coordonnées du rectangle sont {} {}'.format(self.x, self.y))
|
cacc60c4dbd036a6009893e4b55ed0c0286c1612
|
samikshasadana/python_codes
|
/16aug.py
| 402 | 3.53125 | 4 |
'''f=open("rk.txt",'w')
f.write("hi rishi \n")
print('\n')
f=open("rk.txt",'a')
f.write(" by rishi for you \n" )
f=open("rk.txt",'r')
print(f.read())
f=open("rk.txt",'r')
print(f.read(5))
print(f.readline())
f=open("rk.txt",'a')
f.write(" by rishi for you agin \n at your service \n" )'''
f=open("rk.txt",'r')
print(f.read(10))
print(f.seek(3,2))
print(f.read(5))
|
e0df7563acbe458a927dd8ddbf063d1c6ec085ed
|
panwarsandeep/LC
|
/lc_1190_rev_substr_bw_each_parenthesis.py
| 1,227 | 3.71875 | 4 |
from collections import defaultdict
class Solution:
'''
The idea is if the string is at even index (assuming index starting from 0),
in the final output it'll be reversed else not.
keep this in mind while appending the string (i.e. reverse or regular order)
once encounter ')', append this string to the below one (in the stack) but again keeping in mind
if the index is even or odd.
final string will be at the bottom of the stack
'''
def reverseParentheses(self, S):
stack = defaultdict(str)
stk_ptr = -1
def ins_stack(sp, val):
if sp % 2 == 0:
stack[sp] = val + stack[sp]
else:
stack[sp] += val
for s in S:
if s == '(':
stk_ptr += 1
elif s == ')':
stk_ptr -= 1
ins_stack(stk_ptr, stack[stk_ptr + 1])
stack[stk_ptr + 1] = ""
else:
ins_stack(stk_ptr, s)
return stack[stk_ptr]
if __name__ == '__main__':
sol = Solution()
s = "(abcd)"
s = "(ed(et(oc))el)"
#s = "(u(love)i)"
#s = "(abcd)"
print(s)
r = sol.reverseParentheses(s)
print(r)
|
dd9a86f9328c5cde9a5b2c10e321730c1dc6e1b6
|
MehradShahmiri/Python-class
|
/Ex6_ 050 Mehrad Shahmiri.py
| 243 | 3.953125 | 4 |
s=int(input('enter number betwenn 10 and 20: '))
while s<10 or s>20:
if s<10:
print('Too low')
s=int(input('try again: '))
else:
print('Too high')
s=int(input('try again: '))
print('Thank you')
|
152429cb954da8eba410b4cab83ad1d148c9f9b9
|
jedzej/tietopythontraining-basic
|
/students/grzegorz_kowalik/lesson_02_flow_control/knight_move.py
| 284 | 3.890625 | 4 |
begin_row = int(input())
begin_col = int(input())
target_row = int(input())
target_col = int(input())
d_rows = abs(begin_row - target_row)
d_cols = abs(begin_col - target_col)
if (d_cols == 2 and d_rows == 1) or (d_rows == 2 and d_cols == 1):
print("YES")
else:
print("NO")
|
f666c74c83483ba3e51e46e07713082abc9e881b
|
ChrisClear/Coding_Dojo_Coursework
|
/Python/Python_Fundamentals/Fund_Completed/funwithfunctions.py
| 2,132 | 4.40625 | 4 |
""" Fun with functions project
by: Troy Center [email protected]
Assignment: Fun with Functions
Create a series of functions based on the below descriptions.
Odd/Even:
Create a function called odd_even that counts from 1 to 2000. As your loop executes
have your program print the number of that iteration and specify whether it's an odd or even number.
Your program output should look like below:
"""
#pylint: disable=E1101
def odd_even():
"""This is a function to check 1 to 1000 and print if the
number is odd or even.
"""
currnum = 0
while currnum <= 1000:
if is_even(currnum):
print "Number is "+str(currnum)+". This is an even number."
currnum += 1
else:
print "Number is "+str(currnum)+". THis is an odd number."
currnum += 1
def is_even(number):
"""is_even will return True if the number is even
"""
if number % 2 == 0:
return True
else: return False
odd_even()
def multiply(valuestomultiply):
""" Multiply:
Create a function called 'multiply' that iterates through each value in a list
and returns a list where each value has been multiplied by 5.
The function should multiply each value in the list by the second argument.
"""
newlist = []
for each in valuestomultiply:
newlist.append(each*each)
print newlist
return newlist
multiply([2, 4, 6, 9])
"""
#I did not finish this one. Not understanding it. The multiply
#function I built cannot handle two input types... moving on...
Hacker Challenge:
Write a function that takes the multiply function call as an argument.
Your new function should return the multiplied list as a two-dimensional list.
Each internal list should contain the number of 1's as the number in the original list.
# output
>>>[[1,1,1,1,1,1],[1,1,1,1,1,1,1,1,1,1,1,1],[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]]
def layered_multiples(arr)
return new_array
x = layered_multiples(multiply([2,4,5],3))
def returnones(num):
i = 0
temp_arr = []
while i < num:
temp_arr.append(1)
i += 1
print temp_arr
return temp_arr
"""
|
d3b16d607ac116a36f8f2d59ddbb4b45c5d624ed
|
myousufkhan360/Python-basic
|
/python basics/part 2/l2-t3.py
| 312 | 3.96875 | 4 |
list_name = ["Huma" , "Hina" , "Alina" , "Serat"]
print("Hello "+str(list_name[0])+" You are invited to a Dinner")
print("Hello "+str(list_name[1])+" You are invited to a Dinner")
print("Hello "+str(list_name[2])+" You are invited to a Dinner")
print("Hello "+str(list_name[3])+" You are invited to a Dinner")
|
90f2ca3dea8371168cfa10ca322dac0e5f03670e
|
RumorsHackerSchool/PythonChallengesSolutions
|
/Guy/edX/MITx:6.00.1xIntroductionToComputerScienceAndProgrammingUsingPython/vara varb.py
| 213 | 3.78125 | 4 |
None
varA = 'asd'
varB = 10
if type(varA)==str or type(varB)==str:
print ("string involved")
elif varA > varB:
print("bigger")
elif varA == varB:
print("equal")
elif varA < varB:
print ("smaller")
|
fffbbf1a79b9c8f069d523813a579bd846d2e6af
|
realpython/materials
|
/python-doctest/calculations/calculations.py
| 1,092 | 4.28125 | 4 |
"""Provide several sample math calculations.
This module allows the user to make mathematical calculations.
Module-level tests:
>>> add(2, 4)
6.0
>>> subtract(5, 3)
2.0
>>> multiply(2.0, 4.0)
8.0
>>> divide(4.0, 2)
2.0
"""
def add(a, b):
"""Compute and return the sum of two numbers.
Tests for add():
>>> add(4.0, 2.0)
6.0
>>> add(4, 2)
6.0
"""
return float(a + b)
def subtract(a, b):
"""Calculate the difference of two numbers.
Tests for subtract():
>>> subtract(4.0, 2.0)
2.0
>>> subtract(4, 2)
2.0
"""
return float(a - b)
def multiply(a, b):
"""Compute and return the product of two numbers.
Tests for multiply():
>>> multiply(4.0, 2.0)
8.0
>>> multiply(4, 2)
8.0
"""
return float(a * b)
def divide(a, b):
"""Compute and return the quotient of two numbers.
Tests for divide():
>>> divide(4.0, 2.0)
2.0
>>> divide(4, 2)
2.0
>>> divide(4, 0)
Traceback (most recent call last):
ZeroDivisionError: division by zero
"""
return float(a / b)
|
0b29bd1054aefc1d101a5ec43f395c2f38ac3a98
|
everdein/CS320-Programming-Languages
|
/Python/Assignment3/grammar_generator.py
| 1,606 | 4.0625 | 4 |
# This class is a grammar generator.
class GrammarGenerator:
# Asks the user what file to read.
@staticmethod
def get_file_name():
print("What is the file name?")
# file_name = input()
file_name = "simple.txt"
# file_name = "sentence.txt"
g.read_file(file_name)
# Stores dictionary of non-terminals and then a dictionary of terminals
@staticmethod
def read_file(file_name):
d1 = {}
with open(file_name) as file:
for line in file:
(key, val) = line.split('::=')
d1[str(key)] = {}
stripped_val = val.strip()
for stripped in stripped_val.split('|'):
d1[str(key)][stripped] = stripped
print(d1)
for val in d1.values():
print(val)
# g.get_user_input(d1)
# Informs the user what symbols are available in the dictionary
# and asks the user what to generate and how many.
@staticmethod
def get_user_input(d1):
print("Available symbols to generate are:")
print(list(d1.keys()))
print("What do you want to generate (Enter to quit) ?")
generate = input()
print("How many do you want me to generate?")
num = input()
g.recursion_formula(generate, num)
# Recursion formula to iterate through non-terminal and terminal grammar
@staticmethod
def recursion_formula(generate, num):
print(generate, num)
# Calls methods in GrammarGenerator.
if __name__ == '__main__':
g = GrammarGenerator
g.get_file_name()
|
9636226e7a2ee985b4572001aa1245aae1262d48
|
yhx52385/leetcode-in-home
|
/part2-linkedList/19-remove-nth-node-from-end-of-list.py
| 849 | 3.875 | 4 |
# @Time : 2021/5/1 9:35
# @Author : yhx52385
# @Email : [email protected]
# @File : 19-remove-nth-node-from-end-of-list.py
# @software: PyCharm
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
dummy = ListNode()
dummy.next = head
count = 0
now = dummy
while(count<n and now):
count += 1
now = now.next
start = dummy
end = now
before = None
while(end):
before = start
start = start.next
end = end.next
if(before is not None):
before.next = start.next
return dummy.next
else:
return None
|
de4636ff8cafcc6bffdb0b6e3eb5348fa7b4af88
|
sandeepshiven/python-practice
|
/object oriented programming/oops2/deck2.py
| 2,038 | 3.90625 | 4 |
import random
class Card():
def __init__(self,suit,value):
self.suit = suit
self.value = value
def __repr__(self):
return f"{self.value} of {self.suit}"
def __str__(self):
return f"{self.value} of {self.suit}"
class Deck():
suits = ["Hearts","Diamonds","Clubs","Spades"]
values = ["A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"]
def __init__(self):
self.no_of_cards = 52
self.cards = []
# self.cards = [Card(value,suit) for suit in suts for value in values] easy way
for suit in Deck.suits:
for value in Deck.values:
self.cards.append(Card(suit,value))
def count(self):
self.no_of_cards = len(self.cards)
return self.no_of_cards
def __repr__(self):
return f"Deck of {self.no_of_cards} cards"
def _deal(self,num):
count = self.count()
cards_dealt = []
if count is 0:
raise ValueError("All cards has been dealt.")
elif num > count:
for _ in self.cards:
cards_dealt.append(self.cards.pop())
self.no_of_cards -= 1
return cards_dealt
else:
for _ in range(num):
cards_dealt.append(self.cards.pop())
self.no_of_cards -= 1
return cards_dealt
''' a easy way
def _deal(self, num):
count = self.count()
actual = min([count,num])
if count == 0:
raise ValueError("All cards have been dealt")
cards = self.cards[-actual:]
self.cards = self.cards[:-actual]
return cards
'''
def shuffle(self):
if self.no_of_cards < 52:
raise ValueError("Only full decks can be shuffled")
random.shuffle(self.cards)
def deal_card(self):
return self._deal(1)[0]
def deal_hand(self,hands):
return self._deal(hands)
dec = Deck()
ca = dec.deal_card()
print(isinstance(ca,Card))
|
3c4cb6f630a5b768e70261dcfa7760b387af2b76
|
EscapeB/LeetCode
|
/Longest Substring Without Repeating Characters.py
| 1,748 | 3.8125 | 4 |
# Given a string, find the length of the longest substring without repeating characters.
#
# Example 1:
#
# Input: "abcabcbb"
# Output: 3
# Explanation: The answer is "abc", with the length of 3.
# Example 2:
#
# Input: "bbbbb"
# Output: 1
# Explanation: The answer is "b", with the length of 1.
# Example 3:
#
# Input: "pwwkew"
# Output: 3
# Explanation: The answer is "wke", with the length of 3.
#
# Note that the answer must be a substring, "pwke" is a subsequence and not a substring.
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
op = [0] * (len(s) + 1)
substr = ""
for i in range(len(s) - 1, -1, -1):
index = substr.find(s[i])
if index < 0:
op[i] = op[i + 1] + 1
substr = s[i] + substr
else:
substr = s[i] + substr[0:index]
op[i] = len(substr)
return max(op)
def lengthOfLongestSubstring(self, s: str) -> int:
i = 0
j = 0
answer = 0
n = len(s)
charDic = {}
while i < n and j < n:
if charDic.get(s[j]) is not None:
# print(j, i)
answer = max(j - i, answer)
i = charDic.get(s[j]) + 1
charDic.clear()
j = i
elif j == n - 1:
answer = max(j - i + 1, answer)
j = j + 1
else:
charDic[s[j]] = j
j = j + 1
return answer
solution = Solution()
print(solution.lengthOfLongestSubstring("abcabcbb"))
print(solution.lengthOfLongestSubstring(" "))
print(solution.lengthOfLongestSubstring("dvdf"))
print(solution.lengthOfLongestSubstring("abddcaswbas"))
|
21a60dcd1d55a7a940cddff4065cd10da724257f
|
cptn3m0grv/Python-Hackerrank
|
/Itertools/itertools-combinations-with-replacement.py
| 190 | 3.515625 | 4 |
# itertools-combinations-with-replacement
from itertools import combinations_with_replacement as cwr
word, size = input().split()
for i in cwr(sorted(word), int(size)):
print(''.join(i))
|
84541c4b976c37721060b76ac2acf32dc5f3e8d7
|
PdxCodeGuild/class_crow
|
/Code/jesse_pena/labs/lab_25.py
| 3,138 | 4.09375 | 4 |
class ATM(object):
def __init__(self, name = '', balance = 0, transaction_list = []):
self.name = name
self.balance = balance
self.transaction_list = []
def check_balance(self, name):
return self.balance
def deposit(self, deposit_amount):
self.balance += deposit_amount
self.transaction_list.append(f'You deposited ${deposit_amount}')
return self.balance
def check_withdrawal(self, balance, withdrawal_amount):
new_balance = self.balance-withdrawal_amount
if new_balance > 0:
print('You are safe to withdraw')
return True
else:
print('You will overdraw your account')
return False
def withdrawal(self, balance, withdrawal_amount):
self.balance -= withdrawal_amount
self.transaction_list.append(f'You withdrew ${withdrawal_amount}')
return self.balance
def calc_interest(self, balance, interest_rate = 0.1):
self.interest_rate = interest_rate
account_interest = self.balance*self.interest_rate
return account_interest
def print_transactions(self):
counter = 0
for transaction in self.transaction_list:
counter += 1
print (f'{counter}. {transaction}')
return self.transaction_list
def interact():
start_name = input('What is the name of the account? ')
start_amount = int(input('What is the starting amount of the account? '))
user_account = ATM(start_name, start_amount)
while True:
user_input = input('what would you like to do (deposit, withdraw, check balance, history, done)? ')
if user_input == 'deposit':
deposit_amount = int(input('How much are you depositing? '))
user_account.deposit(deposit_amount)
if user_input == 'withdraw':
withdrawal_amount = int(input('How much are you withdrawing? '))
user_account.check_withdrawal(user_account.balance, withdrawal_amount)
will_continue = input('Would you like to continue with the withdrawal? y/n? ' )
if will_continue == 'y':
user_account.withdrawal(user_account.balance, withdrawal_amount)
if will_continue == 'n':
print('balance', user_account.balance)
if user_input == 'check balance':
print('balance', user_account.balance)
if user_input == 'history':
user_account.print_transactions()
if user_input == 'done':
return False
if __name__ == "__main__":
interact()
# jesse_account = ATM('jesse', 100)
# print('balance', jesse_account.balance)
# print('account name', jesse_account.name)
# print('deposit ', jesse_account.deposit(jesse_account.balance, 100))
# print('withdrawal ', jesse_account.withdrawal(jesse_account.balance, 20))
# print('Am I safe to withdraw? ', jesse_account.check_withdrawal(jesse_account.balance, 20))
# print('Amount of interest calculated on account ', jesse_account.calc_interest(jesse_account.balance))
# print(jesse_account.print_transactions())
|
28ebf7b8953288ca3dae13e9994605d1402c6cbf
|
soroush-mim/AUT_Pattern_Recognition
|
/4/code/P3/c.py
| 2,345 | 3.515625 | 4 |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
def pca(data , n_component):
"""performs PCA on a given dataset and return reduced data
Args:
data (m*n numpy array): [m samples that each has n faetures]
n_component ([int]): [num of pca components to keep]
Returns:
[m * n_component numpy array]: [reduced data]
"""
# computing mean of data set
mu = data.mean(axis = 0)
mu = mu.reshape(data.shape[1] , 1).T
#subtracting mean from data samples
data = data - mu
#computing scatter matrix
S = np.cov(data.T)*(data.shape[0]-1)
#computing eigen values and eigen vectors of scatter matrix
eigen_values , eigen_vecs = np.linalg.eig(S)
#selecting eigen vectors corresponding to first biggest n_component
ind = eigen_values.argsort()[-n_component:][::-1]
E = eigen_vecs[ : , ind ]
#computing reduced data
reduced_data = E.T @ data.T
return reduced_data.T
#reading data
df = pd.read_csv('doughs.dat' , sep = ' ')
data = df.drop(['Restaurant'] , axis = 1).to_numpy()
#adding a column to dataset to check if sample is from naples or not
df['Naples'] = df.apply(lambda x: 0 if x['Restaurant'] in [1,2,3,4] else 1 , axis = 1)
reduced_data = pca(data , 3)
print(reduced_data)
#plotting 3d scatter plot for first 3 PCAs
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
scatter = ax.scatter(reduced_data[: , 0], reduced_data[: , 1], reduced_data[: , 2], marker='o' , c=df['Naples'], cmap=plt.cm.Set1,edgecolor='k')
plt.xlabel('first pca')
plt.ylabel('sec pca')
ax.set_zlabel('third pca')
handles = scatter.legend_elements()[0]
labels = list(df['Naples'].unique())
legend1 = ax.legend(handles, labels, title="Naples")
plt.savefig('3c-3D.png')
plt.clf()
#plotting scatter plots for different pairs of first 3 PCAs
for i , j in [[0,1],[0,2],[1,2]]:
fig, ax = plt.subplots()
scatter = ax.scatter(reduced_data[: , i] ,reduced_data[: , j] ,c=df['Naples'], cmap=plt.cm.Set1,edgecolor='k')
handles = scatter.legend_elements()[0]
labels = list(df['Naples'].unique())
legend1 = ax.legend(handles, labels,loc="upper left", title="Naples")
plt.xlabel('pca num: '+str(i+1))
plt.ylabel('pca num: '+str(j+1))
ax.add_artist(legend1)
plt.savefig('3c-2D' + str(i+1) + str(j+1)+'png')
plt.clf()
|
5da2fe9919ab118e4988dd958429def6cac58d4b
|
inka000/projet_python
|
/bin/distance_calculation.py
| 492 | 3.671875 | 4 |
'''distance_calculation module
distance_calculation module allows to calculate distance between two Atomes instances
'''
#!/usr/bin/python3
from math import sqrt
from pdb_reader import *
from classes import *
def distance(atom1, atom2):
'''
Calculates and returns the distance between two Atome instances based on coordinates, using sqrt function from math module
'''
d=sqrt((atom1.xpos-atom2.xpos)**2+(atom1.ypos-atom2.ypos)**2+(atom1.zpos-atom2.zpos)**2)
return d
|
4a73915049c20e93743dc8a9cc2054d230d11477
|
thesinbio/RepoUNLa
|
/Seminario de Lenguajes/Práctica/01.programarcadegames/Práctica20 Bucles avanzado.py
| 1,373 | 4 | 4 |
# Triángulo de números
x = 10
y = 11
for i in range(y):
for k in range(x-i,0,-1):
print(" ", end=" ")
for j in range(1,i):
print(j, end=" ")
for k in range(i-2,0,-1):
print(k, end=" ")
print("")
print("")
# Triángulo de números
x = 10
y = 10
for i in range(y):
for k in range(x-i,0,-1):
print(" ", end=" ")
for j in range(1,i+1):
print(j, end=" ")
for k in range(i-1,0,-1):
print(k, end=" ")
print("")
print("")
# Triángulo de números 1 caras + 1/2
x = 10
y = 10
for i in range(y):
for k in range(x-i,0,-1):
print(" ", end=" ")
for j in range(1,i+1):
print(j, end=" ")
for k in range(i-1,0,-1):
print(k, end=" ")
print("")
for i in range(y):
for k in range(i+2):
print(" ", end=" ")
for j in range(1,x-i-1):
print(j, end=" ")
print("")
print("")
# Triángulo de números dos caras
x = 10
y = 10
for i in range(y):
for k in range(x-i,0,-1):
print(" ", end=" ")
for j in range(1,i+1):
print(j, end=" ")
for k in range(i-1,0,-1):
print(k, end=" ")
print("")
for i in range(y):
for k in range(i+2):
print(" ", end=" ")
for j in range(1,x-i-1):
print(j, end=" ")
for k in range(x-i-3,0,-1):
print(k, end=" ")
print("")
print("")
|
b45279d03fcb4920113bad0cc4743db01790700e
|
Smithmichaeltodd/Learning-Python
|
/Chaos.py
| 397 | 4.03125 | 4 |
def main():
loop = 'True'
while True:
print("Welcome to the chaos program\n")
x = eval(input("Please chose a number between 0 and 1: "))
y = eval(input("Please chose a 2nd number between 0 and 1: "))
n = eval(input("Please chose a number of iterations: "))
for i in range (n):
x = 3.0*x*(1-x)
y = 3.0*y*(1-y)
print(x,y)
main()
|
ef3709eb86293abbf78f3a775f8da3fb800805f5
|
Andchenn/Lshi
|
/day03/bud.py
| 261 | 3.78125 | 4 |
# 定义不定长位置参数
def show_msg(*args):
print(args)
# 定义不定长位置参数
def show(*args):
# print(args, type(args))
print(args)
# 解决办法:对元组进行拆包
show_msg(*args)
# show_msg(args)
show(1, 2)
|
03f31c352bf45e7bebd8ddfbac460a6f56e8f3f6
|
KULDEEPMALIKM41/Practices
|
/Python/Python Basics/9.typecompatibility.py
| 441 | 3.78125 | 4 |
#Type compatibility =>we are check compatibility on two or more different different
# data type. if datatype is compatible so code is execute successfully.
# but data type is not compatible than code is generate Error.
a='hello' #string
b='world' #string
c=a+b #execute
print(c) #print
a='10' #string
b=20 #int
#c=a+b #Error
#print(c)
a=10 #int
b='kuldeep' #string
#c=a+b #error
#print(c)
|
ab538571fb089d83a89d4c069885b14f44cf4d5f
|
skollr34p3r/UdemyCourses
|
/Python3_Bootcamp/Loops/rpsv3.py
| 4,744 | 4.34375 | 4 |
# This is the third iteration of the automated version of RPS where a user battles a "computer"
# opponent in a game. I added looping to allow a best x out of x approach. The variable winning_score
# determines the amount of wins necessary by the computer or player to exit the program
from random import randint
game = 0
player_wins = 0
comp_wins = 0
winning_score = 2
print("You are playing a game of rock, paper, scissors with a computer opponent")
print("First to win " + str(winning_score) + " battles wins the game!")
print()
print("Rock...")
print("Paper...")
print("Scissors...")
print("SHOOT!")
print()
p1_name = input("Please enter your name: ")
print()
while p1_name == "":
p1_name = input(
"No name detected. Please enter your name, or a fake one (give me something to work with here xD): ")
# adding loop to allow 3 plays (best 2/3)
while player_wins < winning_score and comp_wins < winning_score:
comp = randint(0, 2)
game += 1
print("*************************************************************************")
game_num = "Battle: " + str(game)
print(game_num)
p1 = input(
p1_name + ", please make your move. Choose 'rock', 'paper', or 'scissors': ").lower()
if p1 == "quit" or p1 == "q":
print()
print("+---------------------------------+")
print(f"| Your Score: {player_wins} Computer Score: {comp_wins} |")
print("+---------------------------------+")
break
print()
# For Computer random play
# 0 = rock
# 1 = paper
# 2 = scissors
# If computer chooses rock
if comp == 0:
computer = "rock"
if p1 == "rock":
print("The computer also chose rock.")
print("It's a tie!")
elif p1 == "paper":
print("The computer chose rock.")
print("Paper covers rock; " + p1_name + " wins!")
player_wins += 1
elif p1 == "scissors":
print("The computer chose rock.")
print("Rock crushes scissors; Better luck next time!")
comp_wins += 1
elif p1 == "":
print(
"You didn't make a choice! Please play again and choose one of the 3 options.")
else:
print("- Something went wrong; Maybe check spelling?")
# If computer chooses paper
elif comp == 1:
if p1 == "paper":
print("The computer also chose paper.")
print("It's a tie!")
elif p1 == "rock":
print("The computer chose paper.")
print("Paper covers rock; Better luck next time!")
comp_wins += 1
elif p1 == "scissors":
print("The computer chose paper.")
print("Scissors cuts paper; " + p1_name + " wins!")
player_wins += 1
elif p1 == "":
print(
"You didn't make a choice! Please play again and choose one of the 3 options.")
else:
print("- Something went wrong; Maybe check spelling?")
# If computer chooses scissors
elif comp == 2:
if p1 == "scissors":
print("The computer also chose scissors.")
print("It's a tie!")
elif p1 == "rock":
print("The computer chose scissors.")
print("Rock crushes scissors; " + p1_name + " wins!")
player_wins += 1
elif p1 == "paper":
print("The computer chose scissors.")
print("Scissors cuts paper; Better luck next time!")
comp_wins += 1
elif p1 == "":
print(
"You didn't make a choice! Please play again and choose one of the 3 options.")
else:
print("- Something went wrong; Maybe check spelling?")
print()
print()
print()
print("+---------------------------------+")
print(f"| Your Score: {player_wins} Computer Score: {comp_wins} |")
print("+---------------------------------+")
if player_wins > comp_wins:
print()
print()
print("*************************************************************************")
print("!!!!!!!!!!!!!!!!!!!!!!! " + p1_name.upper() +
" WINS THE GAME !!!!!!!!!!!!!!!!!!!!!!!")
elif player_wins < comp_wins:
print()
print()
print("*************************************************************************")
print("!!!!!!!!!!!!!!! THE COMPUTER WINS THE GAME. TRY AGAIN !!!!!!!!!!!!!!!")
else:
print()
print()
print("*************************************************************************")
print("!!!!!!!!!!!!!!! IT'S A TIE !!!!!!!!!!!!!!!")
|
d4a7adabdadd3e793a38ec7b37afb3932d2d4556
|
james-sorrell/spr
|
/src/GameController.py
| 3,905 | 3.640625 | 4 |
import threading
import time
import config as c
class GameController():
""" Game Controller Class
This class controls the game logic,
it is passed in the ui controller
through it's constructor and uses it
to interface with the ui.
"""
def __init__(self, uic):
# UI Controller
self.uic = uic
def start(self):
""" Function will begin the game """
self.numGames = self.uic.queryNumberOfGames()
self.playerScore = 0
self.cpuScore = 0
# We need to run the Match in seperate thread
# so that the UI can still be used by the player
gameThread = threading.Thread(target=self.runMatch)
gameThread.start()
def runMatch(self):
""" Run through the provided number of games and control UI elements """
c.debugPrint("Beginning the games!", 0)
for g in range(self.numGames):
c.debugPrint("Starting game {}.".format(g), 1)
self.runGame()
# Sleep a little so that the next game doesn't start abruptly
time.sleep(2)
# End the match and display end splash
self.endMatch()
def runGame(self):
""" Ensures one game is run properly """
# UI Game Control - Begin Game
self.uic.setToStartState()
self.uic.beginCountdown()
# Wait for the player to throw something
# TODO: Polling isn't ideal
while self.uic.playerThrow is None:
c.debugPrint("Waiting for player to select a throw...", 2)
time.sleep(0.1)
# Set the UI to the post-game state
self.uic.setToPostGame()
# Check who won
self.checkResults()
self.uic.setMiddleLabel(self.gameState)
# Update the scoreboard in the ui
self.uic.setScoreboard(self.playerScore, self.cpuScore)
def endMatch(self):
""" Check who won and display end screen """
# Game is over, determine the overall winner
if self.playerScore > self.cpuScore:
c.debugPrint("Player is the big winner!", 0)
self.uic.setFinalScreen("win")
elif self.playerScore == self.cpuScore:
c.debugPrint("It was all a draw!", 0)
self.uic.setFinalScreen("draw")
else:
c.debugPrint("CPU wins! At least you're on the podium!", 0)
self.uic.setFinalScreen("loss")
def checkResults(self):
""" Determine who won, the player or the cpu """
# This code is a big more difficult to understand but
# the principle is simple,
#
# Rock = 2
# Paper = 1
# Scissors = 0
#
# Note smaller number always beats the larger number
# therefore, if we subtract one from one class and
# the numberas are the same, the class we subtracted
# from would have lost. The modulus exists such that
# we can 'wrap' the scissors class back to 2 -> (0-1)%3=2
#
# Now we only need to check for two other states, draw
# and the other player winning. Since it is easy to check
# for a draw (classes are same) we should do this, then
# all remaining states will be from the third class which
# is CPU winning (as I checked for player winning first).
#
# Scores are updated on class variables
#
if (self.uic.cpuThrow-1) % 3 == self.uic.playerThrow:
c.debugPrint("Player Wins!", 0)
self.gameState="win"
self.playerScore += 1
elif self.uic.cpuThrow == self.uic.playerThrow:
c.debugPrint("Draw", 0)
self.gameState="draw"
else:
c.debugPrint("Cpu Wins!", 0)
self.gameState="loss"
self.cpuScore += 1
|
45256313555c47de3f12f261b53d1b45fff13396
|
llv22/pyalgorithm
|
/03_linkedlist/Intersection_Two_Linked_Lists.py
| 3,590 | 3.734375 | 4 |
# -*- coding: utf-8 -*-
# ---
# jupyter:
# jupytext:
# formats: ipynb,py:light
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.3'
# jupytext_version: 0.8.2
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# language_info:
# codemirror_mode:
# name: ipython
# version: 3
# file_extension: .py
# mimetype: text/x-python
# name: python
# nbconvert_exporter: python
# pygments_lexer: ipython3
# version: 3.6.7
# ---
# # 160. Intersection of Two Linked Lists
# Write a program to find the node at which the intersection of two singly linked lists begins.
#
#
# For example, the following two linked lists:
#
# ```bash
# A: a1 → a2
# ↘
# c1 → c2 → c3
# ↗
# B: b1 → b2 → b3
# ```
#
# begin to intersect at node c1.
#
#
# Notes:
#
# * If the two linked lists have no intersection at all, return null.
# * The linked lists must retain their original structure after the function returns.
# * You may assume there are no cycles anywhere in the entire linked structure.
# * Your code should preferably run in O(n) time and use only O(1) memory.
#
# Status: Passed - 192 ms
# Analysis:
#
# <img src="analysis.jpg"/>
# +
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def getIntersectionNode(self, headA, headB):
"""
:type head1, head1: ListNode
:rtype: ListNode
"""
if not headA or not headB:
return None
# check if they are on the same node, when reaching the tail
p1=headA; p2=headB
while p1.next:
p1=p1.next
while p2.next:
p2=p2.next
if p1!=p2:
return None
# now to check the intersection part, they will definitely meet for 2 intersection, refer to my prove in
p1=headA; p2=headB
while p1!=p2:
p1=p1.next
if not p1:
# then redirect to headB
p1=headB
p2=p2.next
if not p2:
# then redirect to headA
p2=headA
# after x1 step after first intersection, they will meet
return p1
# -
def stringToListNode(input):
# Generate list from the input
numbers = json.loads(input)
# Now convert that list into linked list
dummyRoot = ListNode(0)
ptr = dummyRoot
for number in numbers:
ptr.next = ListNode(number)
ptr = ptr.next
ptr = dummyRoot.next
return ptr
def listNodeToString(node):
if not node:
return "[]"
result = ""
while node:
result += str(node.val) + ", "
node = node.next
return "[" + result[:-2] + "]"
def main():
import sys
def readlines():
for line in sys.stdin:
yield line.strip('\n')
lines = readlines()
while True:
try:
# fix issue, metioned in https://blog.csdn.net/gaifuxi9518/article/details/81059938
line = lines.__next__()
headA = stringToListNode(line)
line = lines.__next__()
headB = stringToListNode(line)
ret = Solution().getIntersectionNode(headA, headB)
out = listNodeToString(ret)
print(out)
except StopIteration:
break
if __name__ == '__main__':
main()
|
2cad28b71f6b4f1588618831923c9b58f621cd75
|
homg93/PS
|
/workbook Edition pt.1/2902.py
| 134 | 3.6875 | 4 |
name = input()
len_name = len(name)
for i in range(len_name):
if ord(name[i]) >= 65 and ord(name[i]) <= 90:
print(name[i],end='')
|
091f8ce5ddbdf9e319ac87502ec7ed6b3599165d
|
Kyeongrok/python_algorithm
|
/etc/geeks_of_geek/02_easy/02_string_after_backspace.py
| 193 | 3.546875 | 4 |
str = "###abc#de#f#ghi#jklmn#op#"
result = []
for chr in str:
if chr == "#":
if len(result) != 0: result.pop()
else:
result.append(chr)
print(result)
print(result)
|
ca96a1c1f7373009bec11f2abab75c54bc7a70f5
|
nilsso/challenge-solutions
|
/euler/python/02/02-v02.py
| 452 | 3.625 | 4 |
# Number 2, v2
# Prompt: By considering the terms in the Fibonacci sequence whose values do
# not exceed four million, find the sum of the even-valued terms.
from math import sqrt
phi = (1+sqrt(5))/2
evenPhi = 2*phi+1 # = phi**3
def evenFib(lim):
n = 2
while n < lim:
yield n
n = round(n * evenPhi)
if __name__ == "__main__":
from sys import argv
print(sum(evenFib(int(argv[1]) if len(argv) > 1 else 4000000)))
|
e1e1cc59cdee48765f8e5f2308f881bdd0c5e06a
|
joshuap233/algorithms
|
/leetcode/hot100/581.py
| 2,053 | 3.6875 | 4 |
# https://leetcode-cn.com/problems/shortest-unsorted-continuous-subarray/
# 581. 最短无序连续子数组
from typing import List
class Solution:
"""
进阶:你可以设计一个时间复杂度为 O(n) 的解决方案吗?
思路: 很明显是双指针
设置双指针 left,right
例子:
[2, 6, 4, 8, 10, 9, 15]
6, 4, 8, 10, 9
6 之前的元素与 9 之后的元素必然递增
因此移动 left 指针时,nums[left] 必定为
left ~ end 中最小的一个, right 指针同理,
题目转化为怎么判断 num[left] 是最小的一个
可以左边遍历,直到序列非递增,记录索引 left
从右边往左遍历,直到非递增,记录,right,
在 left ~ end 与 0- right 之间查找比
num[left] 小的数, 比 num[right] 大的数,
然后再次遍历,可以找到边界....
好复杂的逻辑......一写就错,看来需要简化思路
这题的边界太恶心了.....
"""
def findUnsortedSubarray(self, nums: List[int]) -> int:
left, right = 0, 0
maxi, mini = float('-inf'), float('inf')
for i, v in enumerate(nums):
if v < maxi:
right = i
else:
maxi = v
for i in reversed(range(len(nums))):
if nums[i] > mini:
left = i
else:
mini = nums[i]
return 0 if right == left else right - left + 1
s = Solution()
s.findUnsortedSubarray([1, 2, 3, 4])
class Solution1:
"""
暴力解简单,先排序,然后 设置 left,right 指针比较即可
"""
def findUnsortedSubarray(self, nums: List[int]) -> int:
n = len(nums)
tmp = sorted(nums[:])
left, right = 0, n - 1
while left < n and nums[left] == tmp[left]:
left += 1
while right >= 0 and nums[right] == tmp[right]:
right -= 1
return 0 if right < left else right - left + 1
|
263ac07627d71f95773efa9b82ab129592bf161a
|
ItsMrTurtle/PythonChris
|
/Unit 8 Libraries/Lesson36 GUI Random Color Button.py
| 839 | 4.03125 | 4 |
# -*- coding: utf-8 -*-
"""
Created on Mon Jun 1 15:57:28 2020
@author: Christopher Cheng
"""
import tkinter
import random
def changeColors():
r = random.random()
if r < 1/3:
window.configure(background = "red")
window.update()
elif 1/3 <= r < 2/3:
window.configure(background = "green")
window.update()
else:
window.configure(background = "blue")
window.update()
window = tkinter.Tk()
window.geometry("800x600")
window.title("Color Randomizer Widget")
window.configure(background = "pink")
""" label to instruct the user"""
lbl = tkinter.Label(window, text="Click to change colors!")
lbl.pack()
""" Button that starts the countdown, calls the function when pressed"""
count = tkinter.Button(window, text = "Color Change!", command = changeColors)
count.pack()
window.mainloop()
|
d5e6e9cc5e0c6af95f45b57b1655066f99efb887
|
Miguelpellegrino/Test
|
/drops.py
| 920 | 3.890625 | 4 |
def retornos(retornos):
# print para observar los valores
return print(retornos)
def plic_plac_ploc(numero):
if type(numero) == int:
#Cree un diccionario para trabajar por Clave Valor
gotas = {3:'Plic', 5:'Plac', 7:'Ploc'}
#Cree un mensaje que por defecto esta vacicio
mensaje = ''
#hago un ciclo for para poder sacar el factor del numero
#utilizando la clave del diccionario
for i in gotas.keys():
if(numero % i == 0):
#concateno el texto "Plic, Plac, Ploc" si cumnple la condicion
mensaje += gotas[i]
#Si el texto sigue vacio es porque el numero no cumple
#con las condiciones y entonces le agrego el numero evaluado
if mensaje == '':
mensaje = str(numero)
retornos(mensaje)
else: return print('El argumento no es un numero')
plic_plac_ploc(30000)
|
07b6e218ad64d813c3093547268a3f2258a6079b
|
jfriend08/LeetCode
|
/LowestCommonAncestorofaBinaryTree.py
| 1,900 | 3.765625 | 4 |
'''
My Submissions Question Solution
Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.
According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes v and w as the lowest node in T that has both v and w as descendants (where we allow a node to be a descendant of itself).”
_______3______
/ \
___5__ ___1__
/ \ / \
6 _2 0 8
/ \
7 4
For example, the lowest common ancestor (LCA) of nodes 5 and 1 is 3. Another example is LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself according to the LCA definition.
'''
# 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 __init__(self):
self.val1AncList = []
self.val2AncList = []
def travel(self, root, p, q, path):
if not root:
return
path.append(root.val)
if root.val == p.val:
self.val1AncList = path[:]
if root.val == q.val:
self.val2AncList = path[:]
self.travel(root.left,p,q,path)
self.travel(root.right,p,q,path)
path.pop(-1)
def getLCA(self):
print self.val1AncList
print self.val2AncList
if not self.val1AncList or not self.val2AncList:
return
sameVal = None
for idx in range(min(len(self.val1AncList), len(self.val2AncList))):
if self.val1AncList[idx] == self.val2AncList[idx]:
sameVal = self.val1AncList[idx]
return sameVal
def lowestCommonAncestor(self, root, p, q):
if p == root or q == root:
return root
self.travel(root,p,q,[])
return self.getLCA()
|
56c43655bc93c236f8b07d6439257717f6269f83
|
FelixOnduru1/100-Days-of-Code
|
/Day63/library-start/main.py
| 2,461 | 3.5 | 4 |
from flask import Flask, render_template, request, redirect, url_for
from flask_sqlalchemy import SQLAlchemy
# import sqlite3
app = Flask(__name__)
# Creates a new database called books-collection
# db = sqlite3.connect("books-collection.db")
# Creates a cursor that modifies the database
# cursor = db.cursor()
# This Code creates the database
# cursor.execute("CREATE TABLE books"
# " (id INTEGER PRIMARY KEY, title varchar(250) NOT NULL UNIQUE,"
# " author varchar(250) NOT NULL,"
# " rating FLOAT NOT NULL)")
# Adding a new row and committing
# cursor.execute("INSERT INTO books VALUES(1, 'Harry Potter', 'J. K. Rowling', '9.3')")
# db.commit()
app.config['SQLALCHEMY_DATABASE_URI'] = "sqlite:///new-books-collection.db"
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
# Create Table
class Books(db.Model):
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(250), unique=True, nullable=False)
author = db.Column(db.String(250), nullable=False)
review = db.Column(db.Float, nullable=False)
# Allows each book to be identified by its title when printed
def __repr__(self):
return f"<Book {self.title}>"
db.create_all()
@app.route('/')
def home():
all_books = db.session.query(Books).all()
return render_template('index.html', books=all_books)
@app.route("/add", methods=['GET', 'POST'])
def add():
if request.method == 'POST':
new_book = Books(title=request.form['title'],
author=request.form['author'],
review=float(request.form['rating'])
)
db.session.add(new_book)
db.session.commit()
return redirect(url_for('home'))
else:
return render_template('add.html')
@app.route("/edit/<int:book_id>", methods=['GET', 'POST'])
def edit(book_id):
book_to_update = Books.query.get(book_id)
if request.method == 'POST':
book_to_update.review = request.form['rating']
db.session.commit()
return redirect(url_for('home'))
else:
return render_template('edit.html', book=book_to_update)
@app.route('/delete')
def delete():
book_id = request.args.get('book_id')
book_to_delete = Books.query.get(book_id)
db.session.delete(book_to_delete)
db.session.commit()
return redirect(url_for('home'))
if __name__ == "__main__":
app.run(debug=True)
|
dc2b6655b0bd62cd140c34f9adc554ac5d2ca732
|
Shwaubh/HackerrankSolutions
|
/easy/string/Mars Exploration.py
| 327 | 3.578125 | 4 |
import textwrap as t
def num_change(s):
if s=='SOS':
return 0
else:
x = 0
if s[0]!='S':
x+=1
if s[1]!='O':
x+=1
if s[2]!='S':
x+=1
return x
s = t.wrap(input(),3)
x = 0
for i in s:
x = x + num_change(i)
print(x)
|
9d07e49e52bcdc31d5fd67def815154300ebd795
|
zhengjiani/pyAlgorithm
|
/leetcodeDay/April/prac1111.py
| 1,103 | 3.8125 | 4 |
# -*- encoding: utf-8 -*-
"""
@File : prac1111.py
@Time : 2020/4/1 9:35 上午
@Author : zhengjiani
@Email : [email protected]
@Software: PyCharm
划分出最大嵌套深度最小的分组
"""
class Solution:
"""用抽象栈进行括号匹配,奇偶分组"""
def maxDepthAfterSplit(self, seq):
ans = []
d = 0
for c in seq:
if c == '(':
d += 1
ans.append(d%2)
if c == ')':
ans.append(d%2)
d -= 1
return ans
class Solution1:
"""奇偶分组"""
def maxDepthAfterSplit(self, seq):
"""
左括号 ( 的下标编号与嵌套深度的奇偶性相反
右括号 ) 的下标编号与嵌套深度的奇偶性相同
:param seq:
:return:
"""
ans = list()
for i,ch in enumerate(seq):
if ch == '(':
ans.append(i%2)
else:
ans.append(1-i%2)
return ans
if __name__ == '__main__':
seq = "()(())()"
s = Solution1()
print(s.maxDepthAfterSplit(seq))
|
f772a60f1eb382a7f9b9309416d8b2e7151835f4
|
sunnysoni97/csv_parser_py
|
/csv_parser.py
| 3,139 | 3.5 | 4 |
import os
def print_line():
sz = os.get_terminal_size()[0]
for i in range(sz):
print('-',end='')
print('')
def ret_metrics(data, attr):
cols = len(attr)
rows = len(data)
return (cols,rows)
def check_validity(data,cols,rows):
flag = True
for i in range(rows):
colt = len(data[i])
if(colt!=cols):
flag = False
break
return flag
def sort_func(data, attr):
flag = str(input("Do you want to sort the data?(Y/N) : ")).upper()
if(flag=="N"):
return
try:
print_line()
print ("List of columns : ")
print_line()
for col in attr:
print(col)
print_line()
col_name = str(input("Enter the column according to which the data will be sorted : "))
col_index = attr.index(col_name)
data.sort(key=lambda col: col[col_index])
except ValueError:
print("Column Name not found!")
def disp_data(data,attr,cols):
print_line()
print ("Data : ")
print_line()
for i in range(cols):
print(attr[i], end=" | ")
print('')
for i in range(len(data)):
for j in range(cols):
print(data[i][j], end=" | ")
print('')
print_line()
def add_data(data, attr, cols, rows):
flag = str(input("Do you want to add new entry ? (Y/N) : ")).upper()
if(flag=="N"):
return rows
try:
print_line()
print("Enter data for the new entry : ")
print_line()
new_row=[]
for col in attr:
temp = str(input(str(col)+" : "))
new_row.append(temp)
print_line()
data.append(new_row)
rows+=1
sort_func(data,attr)
disp_data(data,attr,cols)
return rows
except Exception:
print("Couldnt add new entry!")
def write_sort_data(file, data, attr, cols, rows):
flag = str(input("Do you want to write the changes to csv file ? (Y/N) : ")).upper()
if(flag=="N"):
return
try:
file.seek(0,0)
for temp in attr:
if(temp.find(',')!=(-1)):
temp = str('\"'+temp+'\"')
file.write(temp+",")
file.seek(file.tell()-1,0)
file.write('\n')
for i in range(rows):
for j in range(cols):
if(data[i][j].find(',')!=(-1)):
data[i][j] = str('\"'+data[i][j]+'\"')
file.write(data[i][j]+",")
file.seek(file.tell()-1,0)
file.write('\n')
except Exception:
print("Couldnt write data onto the file!")
def read_file(filaname):
try:
file = open(filename,"r+")
temp = ""
data = []
row = []
while(True):
ch = file.read(1)
if(len(ch) < 1):
break
else:
if(ch==','):
row.append(temp)
temp=""
elif(ch=='\n'):
row.append(temp)
data.append(row)
row=[]
temp=""
elif(ch=='"'):
temp = ""
while(True):
ch = file.read(1)
if((len(ch)<1) or ch=='"'):
break
else:
temp+=ch
else:
temp+=ch
return (file, data)
except FileNotFoundError:
print("File couldnt be found!")
filename = str(input("Enter the name of the csv file to parse (including file extension): "))
(file,data) = read_file(filename)
attr = data[0]
del data[0]
(cols, rows) = ret_metrics(data,attr)
if(check_validity(data, cols, rows)):
sort_func(data, attr)
disp_data(data, attr, cols)
rows = add_data(data,attr,cols,rows)
write_sort_data(file,data,attr,cols,rows)
else:
print ("Invalid CSV File!")
file.close()
|
14e47c497589264cb3e6dea8b9a655c03d66fbe6
|
bitnahian/info1110_s2_2019
|
/week03/odds_reversed.py
| 165 | 3.65625 | 4 |
i = 100 # Initialise your counter
while i > 0: # Set proper while condition
if i % 2 == 1: # Do something
print(i)
i -= 1 # Decrement your counter
|
f78ca56001c44dc0fbb39b024c552d0498b56463
|
GraydonHall42/Python-For-Data-Scientists-University-of-Calgary-ENSF-592
|
/assignment-3-encryption-GraydonHall42/encryption.py
| 2,760 | 4.25 | 4 |
# encryption.py
# Graydon Hall
#
# A terminal-based encryption application capable of both encoding and decoding text when given a specific cipher.
# Detailed specifications are provided via the Assignment 3 git repository.
# You must include the main listed below. You may add your own additional classes, functions, variables, etc.
# You may import any modules from the standard Python library.
# Remember to include docstrings and comments.
from EncoderDecoder import EncoderDecoder
from UserPrompter import UserPrompter
import re
def main():
"""
Main function used to run our encryption program. In this program, user is prompted to either encode
or decode a message. They enter their message as a string, along with a 26 character cypher. An encoded or decoded
message is then returned to them.
"""
print("ENSF 592 Encryption Program")
prompter = UserPrompter() # Creat prompter object
choice = prompter.user_greeting() # get encode or decode choice
if (choice == 1): # user wants to encode
message = prompter.get_encoding_message() # get message from user
cipher = prompter.get_user_cipher() # get cipher
encoder_decoder = EncoderDecoder(cipher) # build our encoder_decoder
encoded_message = encoder_decoder.encode_message(message) # encoded version of message
print(f"Your encoded message is {encoded_message}") # present to user
elif (choice == 2): # user wants to decode
message = prompter.get_decoding_message() # get message from user
cipher = prompter.get_user_cipher() # get cipher
encoder_decoder = EncoderDecoder(cipher) # build our encoder_decoder
decoded_message = encoder_decoder.decode_message(message) # decoded version of message
print(f"Your decoded message is {decoded_message}") # present to user.
def test_encode_decode():
"""
Method provided for testing purposes on the encoder/decoder.
A test string is encoded and then decoded using a test cipher.
"""
test_cipher = '123456ijkfmnopqrstuvwxyzab'
test_message = '(1) Solution contains at least one regular expression'.lower()
print(f"Your test mesasge is {test_message}")
test_formatted_message = re.sub(r'[^a-z]', '', test_message) # remove anything now a letter
print(f"Your formatted test mesasge is {test_formatted_message}")
encoder_decoder = EncoderDecoder(test_cipher)
encoded_message = encoder_decoder.encode_message(test_formatted_message)
print(f"your encoded message is: {encoded_message}")
decoded_message = encoder_decoder.decode_message(encoded_message)
print(f"your encoded message is: {decoded_message}")
if __name__ == '__main__':
main()
# test_encode_decode()
|
b58b607eba9c73a053d315f906e33063af0154ad
|
zeppertrek/my-python-sandpit
|
/python-training-courses/pfc-sample-programs/func_example_001_a_with_its_use.py
| 537 | 3.75 | 4 |
# func_example_001_a_with_its_use.py
# Please refer to func_example_001_without_its_use.py
#
# Use def to create a function
#
# Note - This function does not return any value
# Three arguments/parameters are being passed from the calling program to this function
def printthreelines (firstlinechar, middlelinechar, thirdlinechar):
print (firstlinechar * 21)
print (" " * 10 + middlelinechar + " " * 10 )
print (thirdlinechar * 21)
printthreelines("#", "X", "#")
printthreelines("X", "X", "X")
|
2e88a8de3b8367bdf669bac54c2c56a994955605
|
PrtagonistOne/Beetroot_Academy
|
/lesson_28/task_1.py
| 823 | 4.15625 | 4 |
"""
Task 1
Implement binary search using recursion.
"""
from typing import Iterable, Union
def search(seq: Iterable[Union[int, str]], item: Union[int, str]) -> int:
"""Return index of the item if present, otherwise returns -1"""
def binary_search(sequence, start, stop):
if stop >= start:
middle = start + (stop - start) // 2
if sequence[middle] == item:
return middle
if sequence[middle] > item:
return binary_search(sequence, start, middle - 1)
return binary_search(sequence, middle + 1, stop)
else:
return -1
return binary_search(seq, 0, len(seq) - 1)
if __name__ == '__main__':
print(search([1, 2, 3], 3))
print(search([1, 2, 3], 4))
print(search(list(range(10)), 3))
|
21eb58e90c6f28a9dc765364646fdb424e4db278
|
monalan/myGitProject
|
/tryforPython/hello_world.py
| 547 | 3.78125 | 4 |
message="Hello python world!"
print(message)
message = "hello python crash course world!"
print(message.title())
class Dog():
def __init__(self,name,age):
self.name = name
self.age = age
def Squat(self):
print(self.name + ": hello")
my_dog = Dog('lucy',1111)
print("name:",my_dog.name,"age:",my_dog.age)
my_dog.Squat()
my_dog_2 = Dog('lily',12)
print("name:",my_dog_2.name,"age:",my_dog_2.age)
my_dog_2.Squat()
with open('test.txt') as file_object:
contents = file_object.read()
print(contents.strip())
|
4429414286493652206bbad544bcae05b5c4faf0
|
MarceloVasselai/pythonDesafios
|
/Ex020.py
| 351 | 3.734375 | 4 |
from random import shuffle
aluno1 = str(input ('Informe o nome do aluno 1: '))
aluno2 = str(input ('Informe o nome do aluno 2: '))
aluno3 = str(input ('Informe o nome do aluno 3: '))
aluno4 = str(input ('Informe o nome do aluno 4: '))
alunos = [aluno1,aluno2,aluno3,aluno4]
shuffle(alunos)
print ('A nova ordem de apresentação: ',format(alunos))
|
2e1c4239a32807810638df01132dff3404d2d74b
|
AndyLee0310/108-1_Programming
|
/HW002.py
| 665 | 3.625 | 4 |
"""
一元二次方程式
一元二次方程式,aX^2 + bx + c = 0,輸入a, b, c, 求 方程式的兩個實根。
---------------
輸入說明
第一個數(int) a
第二個數(int) b
第三個數(int) c
---------------
輸出說明
第一個實根 x1 = ((-b)+sqrt(b*b-4*a*c))/(2*a)
第二個實根 x2 = ((-b)-sqrt(b*b-4*a*c))/(2*a)
x1, x2 輸出到小數點第一位
print("%.1f" %x1);
---------------
Input
1
-2
1
Output
1.0
1.0
"""
import math
a=int(input())
b=int(input())
c=int(input())
x1=format((((-b)+math.sqrt(b*b-4*a*c))/(2*a)),".1f")
x2=format((((-b)-math.sqrt(b*b-4*a*c))/(2*a)),".1f")
print(x1);
print(x2);
|
36bfbf77dbe9192161412c46b262cfae7e0c044c
|
justinzuo/myp
|
/day1/myrandom.py
| 1,121 | 4 | 4 |
import random
# random.choice()随机选取参数中的子元素
if __name__ == '__main__':
mstr = "abcdefghijklmn"
# 临时存储
tstr = ""
#循环六次,取出六个字符
for i in range(6) :
v = random.choice(mstr)
#拼接成字符串
tstr+= v
print(tstr)
random.shuffle将传入的参数的子元素随机打乱位置
if __name__ == '__main__':
#创建一个列表
ystr = ["zhenshi", "didi", "xingwei"]
#shuffle会将传入的参数的子元素随机打乱位置,没有返回值
random.shuffle(ystr)
print("after {0}".format(ystr))
if __name__ == '__main__':
#循环三次利用random.randint()中间传两个参数,取它们范围内的整数值
for i in range(3) :
i = random.randint(10, 20)
print(i)
# random.uriform()使用
if __name__ == '__main__':
i = 2
j = 4
#random.uniform()在里面传两个整形参数,返回这两个数范围内的浮点型数值
val = random.uniform(i,j)
print(val)
if __name__ == '__main__':
i = 0
j = 9
val = random.randrange(i,j,3)
print(val)
|
08af2fb7db6c809de13734929af5f4c452e0e612
|
youngvoice/myLeetcode_python
|
/calculate.py
| 12,924 | 3.5625 | 4 |
# 227. Basic calculate II
'''
class Solution:
def calculate(self, s: str) -> int:
slist = self.get_legal_list(s)
pass
# remove whitespace and composite multible bit number
def get_legal_list(self, s):
ret = []
temp = ""
for c in s:
if c == " ":
continue
elif c.isnumeric():
temp += c
else:
ret.append(int(temp))
temp = ""
ret.append(c)
ret.append(int(temp))
return ret
'''
# 224 basic calculate
'''
class Solution:
def calculate(self, s: str) -> int:
sufExp = []
optStack = []
status = False
for c in s:
if c == " ":
continue
else:
if c.isnumeric():
#num += c
if not status:
sufExp.append(c)
else:
word = sufExp.pop()
word += c
sufExp.append(word)
status = True
else:
status = False
if not optStack:
optStack.append(c)
else:
#c > optStack[-1]
if c == "(":
optStack.append(c)
elif c == ")":
while True:
o = optStack.pop()
if o != "(":
sufExp.append(o)
else:
break
elif optStack[-1] == "(":
optStack.append(c)
else:
sufExp.append(optStack.pop())
optStack.append(c)
while optStack:
sufExp.append(optStack.pop())
print(sufExp)
#sufExp
res = []
for c in sufExp:
if c.isnumeric():
res.append(int(c))
elif c == "+":
b = res.pop()
a = res.pop()
res.append(a + b)
elif c == "-":
b = res.pop()
a = res.pop()
res.append(a - b)
else:
pass
return res.pop()
'''
#####################################################
'''
OperandType EvaluateExpression() {
InitStack(OPTR); Push(OPTR, '#');
InitStack(OPND);
while
c = getchar()
# operand
if c not in OP:
push(c)
# operator
else:
switch(precede(gettop(operator), c)):
case '<':
case '=':
case '>':
}
'''
'''
OperandType EvaluateExpression() {
InitStack(OPTR); Push(OPTR, '#');
InitStack(OPND);
c = getchar()
while gettop(OPTR) == # and c == #
# operand
if c not in OP:
OPND.push(c)
# operator
else:
switch(precede(gettop(OPTR), c)):
case '<':
OPTR.push(c)
case '=':
OPTR.pop()
case '>':
opnd2 = OPND.pop()
optr = OPTR.pop()
opnd1 = OPND.pop()
res = calc(opnd1, optr, opnd2)
OPND.push(res)
continue
c = getchar()
}
'''
'''
class Solution:
def calculate(self, s: str) -> int:
def precede(opt1, opt2):
optDic = {"+":0, "-":1, "*":2, "/":3, "(":4, ")":5, "#":6}
orderTable = [
[">", ">", "<", "<", "<", ">", ">"],
[">", ">", "<", "<", "<", ">", ">"],
[">", ">", ">", ">", "<", ">", ">"],
[">", ">", ">", ">", "<", ">", ">"],
["<", "<", "<", "<", "<", "=", " "],
[">", ">", ">", ">", " ", ">", ">"],
["<", "<", "<", "<", "<", " ", "="],
]
return orderTable[optDic[opt1]][optDic[opt2]]
def calc(opnd1, optr, opnd2):
if optr == "+":
return opnd1 + opnd2
elif optr == "-":
return opnd1 - opnd2
elif optr == "*":
return opnd1 * opnd2
elif optr == "/":
return opnd1 // opnd2
else:
pass
OPTR = []
OPND = []
OPTR.append("#")
s+="#"
optDic = {"+":0, "-":1, "*":2, "/":3, "(":4, ")":5, "#":6}
index = 0
c = s[index]
index += 1
flag = False
while OPTR[-1] != "#" or c != "#":
if c == " ":
c = s[index]
index += 1
continue
if c not in optDic:
if flag: # in num
num = 10 * num + int(c)
else:
flag = True
num = int(c)
else:
if flag:
OPND.append(num)
flag = False
order = precede(OPTR[-1], c)
if order == "<":
OPTR.append(c)
elif order == "=":
OPTR.pop()
elif order == ">":
opnd2 = OPND.pop()
optr = OPTR.pop()
opnd1 = OPND.pop()
res = calc(opnd1, optr, opnd2)
OPND.append(res)
continue
else:
pass
c = s[index]
index += 1
return OPND.pop()
'''
# 实现的算符优先算法
'''
class Solution:
def calculate(self, s: str) -> int:
def precede(opt1, opt2):
optDic = {"+":0, "-":1, "*":2, "/":3, "(":4, ")":5, "#":6}
orderTable = [
[">", ">", "<", "<", "<", ">", ">"],
[">", ">", "<", "<", "<", ">", ">"],
[">", ">", ">", ">", "<", ">", ">"],
[">", ">", ">", ">", "<", ">", ">"],
["<", "<", "<", "<", "<", "=", " "],
[">", ">", ">", ">", " ", ">", ">"],
["<", "<", "<", "<", "<", " ", "="],
]
return orderTable[optDic[opt1]][optDic[opt2]]
def calc(opnd1, optr, opnd2):
if optr == "+":
return opnd1 + opnd2
elif optr == "-":
return opnd1 - opnd2
elif optr == "*":
return opnd1 * opnd2
elif optr == "/":
return opnd1 // opnd2
else:
pass
OPTR = []
OPND = []
OPTR.append("#")
s+="#"
optDic = {"+":0, "-":1, "*":2, "/":3, "(":4, ")":5, "#":6}
index = 0
c = s[index]
index += 1
flag = False
while OPTR[-1] != "#" or c != "#":
if c == " ":
c = s[index]
index += 1
continue
if c not in optDic:
if flag: # in num
num = OPND.pop()
num = 10 * num + int(c)
else:
flag = True
num = int(c)
OPND.append(num)
else:
if flag:
flag = False
order = precede(OPTR[-1], c)
if order == "<":
OPTR.append(c)
elif order == "=":
OPTR.pop()
elif order == ">":
opnd2 = OPND.pop()
optr = OPTR.pop()
opnd1 = OPND.pop()
res = calc(opnd1, optr, opnd2)
OPND.append(res)
continue
else:
pass
c = s[index]
index += 1
return OPND.pop()
'''
# 后缀表达式算法
#####################################################################
# + - * / --->input c
# + > > < <
# - > > < <
# * > > > >
# / > > > >
#
# top
'''
EvaluateExpression()
{
InitStack(OPTR)
InitStack(OPND)
index = 0
while(True)
{
c = input[index]
if (!In(c,OP))
{
Push(OPND, c)
index += 1
}
else{
if (isEmpty(OPTR))
{
Push(OPTR, c)
index += 1
}
else if(c == '(')
{
Push(OPTR, c)
index += 1
}
else if(c == ')')
{
top = Pop(OPTR)
if (top != '(')
{
Push(OPND, top)
}
else
{
pass
}
}
else {
top = gettop(OPTR)
if (top == '(')
{
Push(OPTR, c)
index += 1
}
else
{
order = precede(gettop(OPTR), c)
if (order == '>'){
top = Pop(OPTR)
Push(OPND, top)
}
elif (order == '='){
pass
}
elif (order == '<'){
Push(OPTR, c)
index += 1
}
else pass
}
}
}
}
}
'''
class Solution:
def calculate(self, s: str) -> int:
optList = {"+": 0, "-": 1, "*": 2, "/": 3}
def precede(top, c):
# + - * /
nonlocal optList
orderTable = [
[">", ">", "<", "<"],
[">", ">", "<", "<"],
[">", ">", ">", ">"],
[">", ">", ">", ">"],
]
return orderTable[optList[top]][optList[c]]
OPTR = []
OPND = []
index = 0
flag = False
while True:
if index == len(s):
break
c = s[index]
if c == " ":
index += 1
continue
#if c not in optList:
if c.isdigit():
if flag == True: # in number
num = OPND.pop()
num = num * 10 + int(c)
else:
num = int(c)
flag = True
print(num, "c is ",c)
OPND.append(num)
#OPND.append(c)
index += 1
else:
flag = False
if not OPTR or c == "(":
OPTR.append(c)
index += 1
elif c == ")":
top = OPTR.pop()
if top != "(":
OPND.append(top)
else:
index += 1
else:
top = OPTR[-1]
if top == "(":
OPTR.append(c)
index += 1
else:
order = precede(OPTR[-1], c)
if order == ">":
top = OPTR.pop()
OPND.append(top)
elif order == "=":
pass
elif order == "<":
OPTR.append(c)
index += 1
else:
pass
while OPTR:
OPND.append(OPTR.pop())
print(OPND)
# OPND is
def calculate(num1, opt, num2):
if opt == "+":
return num1 + num2
elif opt == "-":
return num1 - num2
elif opt == "*":
return num1 * num2
elif opt == "/":
return num1 // num2
else:
pass
temp = []
for c in OPND:
if c in optList:
num2 = temp.pop()
num1 = temp.pop()
temp.append(calculate(num1, c, num2))
else:
temp.append(c)
return temp.pop()
|
68a19592105b3349f1f231046775131b2c0431ad
|
TolgaGolet/Random_LSB_Steganography
|
/RandomLSB.py
| 5,305 | 3.734375 | 4 |
import binascii, cv2
import numpy as np
import sewar
from matplotlib import pyplot as plt
import random
def convertStringToBinary(string):
return bin(int.from_bytes(string.encode(), 'big'))
def convertBinaryToString(binary):
n = int(binary, 2)
return n.to_bytes((n.bit_length() + 7) // 8, 'big').decode()
print("\nThis code is going to hide data into 'photo.bmp'.(3 channels random LSB). If you don't want this photo to hide your data, add your own photo and rename it as 'photo.bmp'\n")
imageName = 'photo.bmp'
originalImage = cv2.imread(imageName)
image = cv2.imread(imageName)
height, width = image.shape[:2]
bitsCapacity = (height * width) * 3
bytesCapacity = bitsCapacity / 8
print('You can hide', bitsCapacity, 'bits( ~', int(bytesCapacity), 'character(s) ) into this image.\n')
message = input('Enter a message to hide: ')
# with open('message.txt', 'r') as file:
# message = file.read()
# print(message)
binaryMessage = convertStringToBinary(message)
#Calculating message size in bits
bitsMessageSize = 0
for i in binaryMessage[2::]:
bitsMessageSize += 1
if bitsMessageSize > bitsCapacity:
print('\nError: Message size is greater than the image capacity.')
exit()
key = -1
while key <= 0 or key >999:
key = int(input('\nEnter a key to encrypt. It should be an integer and maximum 3 digits long\n: '))
print('Binary encoded message:', binaryMessage[2::], '\n')
random.seed(key) #The same random numbers every time
#Unique numbers
randomLocations = random.sample(range(height * width), k = int(bitsMessageSize / 3) + 1)
#print("lenrandomLocations:", len(randomLocations))
#Pixel locations of random locations
pixelLocations = []
for randomLocation in randomLocations:
pixelLocations.append(int(randomLocation / height) % height) #i
pixelLocations.append(randomLocation % width) #j
#print("lenpixelLocations:", len(pixelLocations))
index = 0 #Loop index
messageIndex = 2
writtenBits = 0
percentPart = 100 / bitsMessageSize
percentage = 0
print(str(int(percentage))+"% complete", end="\r")
for w in range(0, len(pixelLocations), 2):
if w <= len(pixelLocations)-2:
i = pixelLocations[w]
j = pixelLocations[w + 1]
if index >= bitsMessageSize:
#print('İkinci ife girdi')
break
pixelValues = image[i,j]
#print('Original pixel values:', 'h:', i, 'w:', j, ':', pixelValues)
#BGR
for l in range(3):
if (messageIndex - 2) >= bitsMessageSize:
#print('Üçüncü ife girdi')
break
elif l == 0:
print(str(int(percentage))+"% complete", end="\r")
#print('Orig:', bin(image[i, j][0]))
if binaryMessage[messageIndex] == '1':
image[i, j][0] = image[i, j][0] | int('0b1', 2)
else:
image[i, j][0] = image[i, j][0] & int('0b11111110', 2)
#print('Chan:', bin(image[i, j][0]))
writtenBits += 1
percentage += percentPart
elif l == 1:
print(str(int(percentage))+"% complete", end="\r")
#print('Orig:', bin(image[i, j][1]))
if binaryMessage[messageIndex] == '1':
image[i, j][1] = image[i, j][1] | int('0b1', 2)
else:
image[i, j][1] = image[i, j][1] & int('0b11111110', 2)
#print('Chan:', bin(image[i, j][1]))
writtenBits += 1
percentage += percentPart
elif l == 2:
print(str(int(percentage))+"% complete", end="\r")
#print('Orig:', bin(image[i, j][2]))
if binaryMessage[messageIndex] == '1':
image[i, j][2] = image[i, j][2] | int('0b1', 2)
else:
image[i, j][2] = image[i, j][2] & int('0b11111110', 2)
#print('Chan:', bin(image[i, j][2]))
writtenBits += 1
percentage += percentPart
messageIndex += 1
else:
#print('ilk ife giremedi')
index += 1
pixelValues = image[i, j]
#print('Changed pixel values:', pixelValues)
print("100% complete")
print("writtenBits:", writtenBits)
print('You hid', bitsMessageSize, 'bits')
cv2.imwrite('hidden.bmp', image)
#Calculating the metrics
print('MSE:', round(sewar.mse(originalImage, image), 5))
print('PSNR:', round(sewar.psnr(originalImage, image), 5))
print('UIQI:', round(sewar.uqi(originalImage, image), 5))
(ssimValue, csValue) = sewar.ssim(originalImage, image)
print('SSIM:', round(ssimValue, 5))
numpy_horizontal = np.hstack((originalImage, image))
cv2.namedWindow("Original vs Hidden", cv2.WINDOW_NORMAL)
cv2.imshow('Original vs Hidden', numpy_horizontal)
cv2.waitKey()
#Plotting histograms
color = ('b','g','r')
plt.figure(figsize = (11, 5))
plt.subplot(1, 2, 1)
for i,col in enumerate(color):
histr = cv2.calcHist([originalImage],[i],None,[256],[0,256])
plt.plot(histr,color = col)
plt.xlim([0,256])
plt.grid()
plt.tight_layout()
plt.subplot(1, 2, 2)
for i,col in enumerate(color):
histr = cv2.calcHist([image],[i],None,[256],[0,256])
plt.plot(histr,color = col)
plt.xlim([0,256])
plt.grid()
plt.tight_layout()
plt.show()
|
e4255295a354bfd8222b0a9f25ea4a9bec42b9a7
|
pauljs/HotColdData
|
/replacementAlgorithms.py
| 9,197 | 3.828125 | 4 |
'''LRUQueue.py'''
from Queue import PriorityQueue
from Queue import Queue
import time
import calendar
from abc import ABCMeta
import random
'''class for least recently used algorithm'''
class ReplacementQueue(object):
'''
Checks whether the ReplacementQueue is full.
Returns True if it is full and false otherwise.
'''
def isFull(self):
pass
'''
Adds object to this ReplacementQueue. If ReplacementQueue
is full then new object will replace an old object
based on the replacement algorithm. If the ReplacementQueue
is not full, then will add the new object, without removing another,
depending on the ReplacementQueue algorithm for enqueue'''
def enqueue(self, id):
pass
'''
Deletes an object if it is in the ReplacementQueue.
Returns True if object was deleted in the ReplacementQueue, else False.
'''
def delete(self, id):
pass
'''
Checks to see if object is in the ReplacementQueue.
Returns True if so, else False.
'''
def contains(self, id):
pass
'''
Prints the contents of the ReplacementQueue
as well as other informational data pertaining to each
replacement algorithm
'''
def printContents(self):
pass
class PriorityQueueContain(PriorityQueue):
def __delete__(self, id):
with self.mutex:
for tuple in self.queue:
if(id == tuple[1]):
self.queue.remove(tuple)
return True
return False
def __printContents__(self):
print 'Length: ' + str(len(self.queue))
for id in self.queue:
print id
class QueueContain(Queue):
def __contains__(self, id):
with self.mutex:
for temp in self.queue:
if(temp == id):
return True
return False
def __delete__(self, id):
with self.mutex:
for temp in self.queue:
if(id == temp):
self.queue.remove(temp)
return True
return False
def __printContents__(self):
print 'Length: ' + str(len(self.queue))
for id in self.queue:
print id
class LRUQueue:
def __init__(self, maxsize):
self.maxsize = maxsize
self.queue = PriorityQueueContain(maxsize)
def clear(self):
self.queue = PriorityQueueContain(self.maxsize)
def isFull(self):
return self.queue.full()
def enqueue(self, id):
item = (-1, -1)
if(self.isFull()):
item = self.queue.get()
self.queue.put((int(time.time()*100000), id))
return item[1]
def contains(self, id):
isContained = self.delete(id)
if(isContained):
self.enqueue(id)
return isContained
def delete(self, id):
return self.queue.__delete__(id)
def printContents(self):
self.queue.__printContents__()
class FIFOQueue(ReplacementQueue):
def __init__(self, maxsize):
self.maxsize = maxsize
self.queue = QueueContain(maxsize)
def clear(self):
self.queue = QueueContain(self.maxsize)
def isFull(self):
return self.queue.full()
def enqueue(self, id):
item = -1
if(self.isFull()):
item = self.queue.get()
self.queue.put(id)
return item
def contains(self, id):
return self.queue.__contains__(id)
def delete(self, id):
return self.queue.__delete__(id)
def printContents(self):
self.queue.__printContents__()
class ClockStaticQueue(ReplacementQueue):
def __init__(self, maxsize):
self.maxsize = maxsize
self.queueTracker = Queue(maxsize)
for i in range (0, maxsize):
self.queueTracker.put(i)
self.clock = [None] * maxsize
self.hand = 0
def clear(self):
maxsize = self.maxsize
self.queueTracker = Queue(maxsize)
for i in range (0, maxsize):
self.queueTracker.put(i)
self.clock = [None] * maxsize
self.hand = 0
def isFull(self):
return not self.queueTracker.empty()
def incrementHand(self):
self.hand = (self.hand + 1) % self.maxsize
def enqueue(self, id):
item = (-1, -1)
if(self.contains(id)):
return item[1]
elif(self.isFull()):
nextEmptyIndex = self.queueTracker.get()
self.clock[nextEmptyIndex] = (1, id)
else:
'''clock is full'''
while(True):
if(self.clock[self.hand] is None):
self.incrementHand()
continue
if(self.clock[self.hand][0] == 0):
break
self.clock[self.hand] = (0, self.clock[self.hand][1])
self.incrementHand()
item = self.clock[self.hand]
self.clock[self.hand] = (1, id)
self.incrementHand()
return item[1]
def delete(self, id):
for i in range(0, self.maxsize):
if(self.clock[i] and self.clock[i][1] == id):
self.clock[i] = None
self.queueTracker.put(i)
if(self.hand == i):
self.incrementHand()
return True
return False
def contains(self, id):
for tuple in self.clock:
if(tuple is None):
continue
if(tuple[1] == id):
tuple = (1, id)
return True
return False
def printContents(self):
print "Hand: " + str(self.hand)
for tuple in self.clock:
print tuple
class ClockDynamicQueue(ReplacementQueue):
def __init__(self, maxsize):
self.maxsize = maxsize
self.clock = []
self.hand = 0
def clear(self):
self.clock = []
self.hand = 0
def incrementHand(self):
if(len(self.clock) == 0 or self.hand == len(self.clock)):
'''second or is edge case for when delete last element in list'''
self.hand = 0
self.hand = (self.hand + 1) % len(self.clock)
def isFull(self):
return len(self.clock) == self.maxsize
def enqueue(self, id):
item = (-1, -1)
if(self.contains(id)):
return item[1]
elif(not self.isFull()):
self.clock.append((1, id))
else:
'''clock is full'''
while(self.clock[self.hand][0] == 1):
self.clock[self.hand] = (0, self.clock[self.hand][1])
self.incrementHand()
item = self.clock[self.hand]
self.clock[self.hand] = (1, id)
self.incrementHand()
return item[1]
def delete(self, id):
for i in range(0, self.maxsize):
if(self.clock[i][1] == id):
del self.clock[i]
if(self.hand == len(self.clock)):
self.incrementHand()
return True
return False
def contains(self, id):
for tuple in self.clock:
if(tuple is None):
continue
if(tuple[1] == id):
return True
return False
def printContents(self):
print "Hand:" + str(self.hand)
for tuple in self.clock:
print tuple
class RandomQueue(ReplacementQueue):
def __init__(self, maxsize):
self.maxsize = maxsize
self.clock = []
def clear(self):
self.clock = []
def isFull(self):
return len(self.clock) == self.maxsize
def enqueue(self, id):
item = -1
if(self.contains(id)):
return item
elif(not self.isFull()):
self.clock.append(id)
else:
'''clock is full'''
removalIndex = random.randint(0, self.maxsize - 1)
item = self.clock[removalIndex]
del self.clock[removalIndex]
self.clock.append(id)
return item
def delete(self, id):
for i in range(0, self.maxsize):
if(self.clock[i] == id):
del self.clock[i]
return True
return False
def contains(self, id):
for temp in self.clock:
if(temp == id):
return True
return False
def printContents(self):
print "Length: " + str(len(self.clock))
for i in range(0, len(self.clock)):
print self.clock[i]
'''Used for Testing Purposes'''
def main():
queue = ClockStaticQueue(4)
print "\n"
print queue.printContents()
queue.enqueue(1)
print "\n"
print queue.printContents()
queue.enqueue(2)
print "\n"
print queue.printContents()
queue.enqueue(3)
print "\n"
print queue.printContents()
queue.enqueue(4)
print "\n"
print queue.printContents()
queue.enqueue(5)
print "\n"
print queue.printContents()
print queue.delete(1)
print queue.delete(3)
print queue.printContents()
queue.enqueue(6)
print "\n", queue.printContents()
if __name__ == '__main__':
main()
|
719fb0755cda5056b5a8342b93b244a49f95985d
|
tonper19/PythonDemos
|
/basic/infinite_loop.py
| 199 | 4.15625 | 4 |
name = ''
# while name != 'Toffee':
# name = input('Enter a name: ')
for numero in range(1,10):
print(numero)
numero = 0
while numero < 10:
print(numero)
numero = numero + 1
|
f1a94721f6ac3894efc667461130e8ae55c1e59b
|
diegodpgs/ViajandoEmBytes
|
/Perceptron/perceptron.py
| 2,160 | 3.546875 | 4 |
import math
class Perceptron:
"""
DATA FORMAT
data = [[xa1,xa2,xa3,xa4...xan,ay],
[xb1,xb2,xb3,xb4...xbn,by],
.
.
.
[xz1,xz2,xz3,xz4...xzn,zy]]
where xn is a feature and y is the target expected.
Both have to be numeric.
"""
def __init__(self,data):
self.data = data
self.targets = [x[-1] for x in data]
self.features = [x[0:-1] for x in data]
self.weights = None
self.bias = None
def updateWeights(self,X,y):
for feature in xrange(len(X)):
self.weights[feature] += (y * X[feature])
#@max_interaction the value of interactions
def train(self,max_interaction):
M = len(self.features[0]) #number of features/dimensions
N = len(self.data) # number of train samples
self.weights = [0 for i in xrange(M)]
self.bias = 0 #bias
for i in xrange(max_interaction):
for index in xrange(N):
y = self.predict(self.features[index])
if y != self.targets[index]:
self.updateWeights(self.features[index],self.targets[index])
self.bias = self.bias + y
print 'WEIGHTS',self.weights
#@X : sample test X = [x1,x2..xn]
def predict(self,X):
N = len(X) #number of features
score = sum([self.weights[j]*X[j] for j in xrange(N)]) + self.bias
if score >= 0:
return 1
return -1
if "__main__":
data = [(0,1,-1),(1,0,-1),(0,0,1),(1,1,1)]
p = Perceptron(data)
p.train(10)
#peking, shangai, shangai, tokyo, tshishuan, yokohama:c
#peking, osaka, shangai, tokyo, kyoto, yokohama:j
#baidu, shangai, peking, kyoto, tshishuan, yokohama:c
#osaka, osaka, shangai, yoto, osaka:j
#peking, peking, peking, osaka, osaka:c
#yokohama, kyoto, shangai, baidu tshishuan:c
#----
#osaka, baidu, baidu, baidu, osaka:c
#kyoto, osaka, osaka, kyoto, peking:j
#peking, baidu, shangai, tokyo,tshishuan, yokohama,osaka,kyoto
data = [(1, 0, 2, 1, 1, 1, 0, 0, 1),
(1, 0, 1, 1, 0, 1, 1, 1, -1),
(1, 1, 1, 0, 1, 1, 0, 1, 1),
(0, 0, 1, 0, 0, 0, 3, 0, -1),
(3, 0, 0, 0, 0, 0, 2, 0, 1),
(0, 1, 1, 0, 1, 1, 1, 1, 1)]
testX = [(0, 3, 0, 0, 0, 0, 1, 1),
(1, 0, 0, 0, 0, 0, 2, 2)]
testY = [1,-1]
print p.features
|
889988d941927bc0cd15d1c9fac04677956ed854
|
askdjango/snu-web-2016-09
|
/class-20160928/report/정동휘_식품생명공학과/googoodan.py
| 263 | 3.765625 | 4 |
number = int(input("구구단: "))
if number < 10 and 1 < number:
for i in range(1,10):
result = number*i
print('{a} * {b} = {c}'.format(a=str(number), b=str(i), c=str(result)))
else:
print("구구단은 2부터 9까지입니다 :)")
|
7057c2c487b8f8c0f3684a6e90f05a023f8ddcae
|
dgonzalo05/M5.Pt2
|
/M5.Pt2/P11_cerca1caracter.py
| 379 | 4.09375 | 4 |
# encoding: utf-8
# Programa que cerca si un caràcter es troba a o no (a una frase) i el mostra per pantalla.
st = raw_input("Escriu alguna cosa: ")
put = raw_input("Escriu un caràcter: ")
con = 0
while con < len(st):
if put == st[con]:
result = "El caràcter '"+put+"' apareix a "+st
break
else:
result = "El caràcter '"+put+"' no apareix a "+st
con+=1
print result
|
d4e9f804d27a719ae37470d82a6411024003626f
|
MashuAjmera/Algorithms
|
/hamiltonian.py
| 1,044 | 3.765625 | 4 |
# Problem: Hamiltonian Cycle
# Author: Mashu Ajmera
# Approach: Backtracking
# Time Complexity:
# Space Complexity:
# GFG: https://www.geeksforgeeks.org/hamiltonian-cycle-backtracking-6/
def check(s,g,n,vis):
ans=0
for i in range(1,n):
if vis[i]==-1:
ans+=1
if g[s][i]==1:
vis[i]=s
check(i,g,n,vis)
if ans==0 and g[s][0]==1:
res=[s]
while res[-1]!=0:
res.append(vis[res[-1]])
print(res)
vis[s]=-1
def hamiltonian(g):
n=len(g)
vis=[-1 for i in range(n)]
check(0,g,n,vis)
if __name__=="__main__":
g=[ [0, 1, 0, 1, 0], [1, 0, 1, 1, 1],
[0, 1, 0, 0, 1,], [1, 1, 0, 0, 1],
[0, 1, 1, 1, 0], ] # [1, 2, 4, 3, 0]
# g=[ [0, 1, 0, 1, 0], [1, 0, 1, 1, 1],
# [0, 1, 0, 0, 1,], [1, 1, 0, 0, 0],
# [0, 1, 1, 0, 0], ] # no solution
# g=[ [0, 1, 0, 1, 0], [1, 0, 1, 1, 1],
# [0, 1, 0, 0, 1,],[1, 1, 0, 0, 1],
# [0, 1, 1, 1, 0], ] # [1, 2, 4, 3, 0]
hamiltonian(g)
|
650211ab1eada678de322b0ccc1521bd856fea52
|
kaci65/Nichola_Lacey_Python_By_Example_BOOK
|
/Numeric_Arrays/num_range.py
| 367 | 4.21875 | 4 |
#!/usr/bin/python3
"""Array: numbers must be between 10 and 20"""
from array import *
numArray = array('i', [])
for i in range(0, 5):
num = int(input("Please enter a number between 10 and 20: "))
if num >= 10 and num <= 20:
numArray.append(num)
else:
print("Outside the range")
print()
print("Thank you")
for i in numArray:
print(i)
|
bc0fc63d25c493630368859093d129f523e88418
|
Yousef497/Python-for-Everbody-Specialization
|
/Course_2 (Python Data Structures)/Chapter_9/Exercise_9_04.py
| 545 | 3.734375 | 4 |
fname = input("Enter file name: ")
try:
fhand = open(fname)
except:
print("File cannot be found:",fname)
quit()
counts = dict()
for line in fhand:
line.rstrip()
if line.startswith("From "):
if len(line) < 1:
continue
words = line.split()
counts[words[1]] = counts.get(words[1],0) + 1
bigcount = None
mail = None
for word,count in counts.items():
if bigcount == None or count > bigcount:
bigcount = count
mail = word
print(mail, bigcount)
|
c2478945f23be1aa190f5c73bc10259f6b922b5e
|
Eason13245/AE401-Python-
|
/2020. 6. 2 回家作業.py
| 361 | 3.703125 | 4 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Jun 2 21:03:53 2020
@author: gaoyixun
"""
import turtle
Ray = turtle.Turtle()
Ray.color('blue')
Ray.shape('turtle')
canvas = turtle.Screen()
canvas.title('Turtle window')
canvas.bgcolor('white')
for x in range(0,60,2):
Ray.forward(x)
Ray.left(20)
turtle.done()
turtle.bye()
|
ea6951d9a926a86230c5f9f283d0ad796f0be401
|
MrBenjaminLeb/viirs-data
|
/src/eumetsat/common/geo_utils.py
| 1,070 | 4.03125 | 4 |
# -*- coding: utf-8 -*-
'''
Created on Feb 9, 2011
@author: [email protected]
'''
import math
def deg_to_rad(val):
""" convert degree values in radians """
return (val * math.pi)/180.00
def rad_to_deg(value):
""" convert radians to degrees """
(value * 180.00)/ math.pi
def distance(lat1, lon1, lat2, lon2):
""" calculate distance between 2 points using the haversine formula
R = earth’s radius (mean radius = 6,371km)
Δlat = lat2− lat1
Δlong = long2− long1
a = sin²(Δlat/2) + cos(lat1).cos(lat2).sin²(Δlong/2)
c = 2.atan2(√a, √(1−a))
d = R.c
"""
R = 6371
d_lat = deg_to_rad(lat2 - lat1)
d_lon = deg_to_rad(lon2 - lon1)
a = math.sin(d_lat/2) * math.sin(d_lat/2) + \
math.cos(deg_to_rad(lat1)) * math.cos(deg_to_rad(lat2)) * \
math.sin(d_lon/2) * math.sin(d_lon/2)
c = 2 * math.atan2(math.sqrt(a), math.sqrt(1-a))
return R * c
if __name__ == '__main__':
print(deg_to_rad(65.45674723))
|
1e8b04c3607c17ccb13e28b1090e222ff3bb8b7f
|
anassinator/ecse543
|
/as1/rectangle.py
| 1,852 | 3.859375 | 4 |
class Rectangle(object):
def __init__(self, width, height, bottom_left_x, bottom_left_y):
self._width = float(width)
self._height = float(height)
self._center_x = float(bottom_left_x) + width / 2.0
self._center_y = float(bottom_left_y) + height / 2.0
self._top = bottom_left_y + self._height
self._bottom = bottom_left_y
self._right = bottom_left_x + self._width
self._left = bottom_left_x
def __repr__(self):
return "Rectangle{s.shape} @ {s.center}".format(s=self)
def __str__(self):
return self.__repr__()
def __contains__(self, coord):
if isinstance(coord, tuple):
x, y = coord
return (self._left <= x <= self._right and
self._bottom <= y <= self._top)
raise NotImplementedError()
def on_edge(self, coord):
x, y = coord
return (x in (self._left, self._right) or
y in (self._bottom, self._top))
@property
def width(self):
return self._width
@property
def height(self):
return self._height
@property
def shape(self):
return self._width, self._height
@property
def center(self):
return self._center_x, self._center_y
@property
def top(self):
return self._top
@property
def bottom(self):
return self._bottom
@property
def right(self):
return self._right
@property
def left(self):
return self._left
@property
def top_right(self):
return self._top, self._right
@property
def top_left(self):
return self._top, self._left
@property
def bottom_right(self):
return self._bottom, self._right
@property
def bottom_left(self):
return self._bottom, self._left
|
7687550be9be737e0f60c7501669a60a455c8791
|
matthewlootens/sort_search_algorithms
|
/merge_sort.py
| 2,144 | 4.1875 | 4 |
def mergesort(input_list):
"""
input_list: a list of any n integers, duplicates allowed
Returns a tuple:
sorted list in non-decreasing order;
and a count of inversions.
"""
def merge(left_list, right_list):
nonlocal inversion_count#Allows for this function to have closure
sortedlist = []
i, j = 0, 0
while True:
if left_list[i] <= right_list[j]:
sortedlist.append(left_list[i])
if i < len(left_list) - 1:#prevents falling off list
i += 1
else:#If left is empty, append right directly.
sortedlist += right_list[j:]
break
else:
sortedlist.append(right_list[j])
inversion_count += len(left_list) - i#Count inversions
if j < len(right_list) - 1:
j += 1
else:
sortedlist += left_list[i:]
break
return sortedlist
#####
#Basecase and empty list
#####
if len(input_list) <= 1:
inversion_count = 0
return input_list, inversion_count#pass inversion_count up the tree
#####
#Recursive calls and book-keeping
#####
else:
left_list, inversion_count = mergesort(input_list[:len(input_list) // 2])
#Need the 'right_list_tuple' variable as a temp holder so that inversion_
#count can be incremented.
right_list_tuple = mergesort(input_list[len(input_list) // 2:])
right_list = right_list_tuple[0]
inversion_count += right_list_tuple[1]
sorted_list = merge(left_list, right_list)
return sorted_list, inversion_count#pass up the inversion_count the tree
def main():
"""
Test suite based on data in 'inversion_data.txt', a list of first 100,000
integers in random order.
"""
filename = 'inversion_data.txt'
with open(filename) as f:
datalist = []
for line in f:
datalist.append(int(line))
print(mergesort(datalist)[1])
if __name__ == '__main__':
main()
|
4d143034781509f170b7ba87d3ab803e98db01b0
|
JayIvhen/StudyRepoPython2014
|
/home_work/lesson3/Diykstra.py
| 2,043 | 3.765625 | 4 |
#!usr/bin/python
"""Diykstra algorithm"""
__author__ = "JayIvhen"
def search_function(room, x, y, path):
print x, y, room[x][y]['path_length']
path.append((x,y))
if room[x][y]['x'] == 10 and room[x][y]['y'] ==10:
print 'Finish!!'
global path = path
return
if room[x][y]['UP_check'] == False:
room[x][y]['UP_check'] = True
if room[x][y]['x'] != 0 and room[x-1][y]['simbol'] != '#':
room[x-1][y]['DOWN_check'] = True
room[x-1][y]['path_length'] = room[x][y]['path_length'] + 1
search_function(room, x-1, y)
if room[x][y]['DOWN_check'] == False:
room[x][y]['DOWN_check'] = True
if room[x][y]['x'] != 10 and room[x+1][y]['simbol'] != '#':
room[x+1][y]['UP_check'] = True
room[x+1][y]['path_length'] = room[x][y]['path_length'] + 1
search_function(room, x+1, y)
if room[x][y]['LEFT_check'] == False:
room[x][y]['LEFT_check'] = True
if room[x][y]['y'] != 0 and room[x][y-1]['simbol'] != '#':
room[x][y-1]['RIGHT_check'] = True
room[x][y-1]['path_length'] = room[x][y]['path_length'] + 1
search_function(room, x, y-1)
if room[x][y]['RIGHT_check'] == False:
room[x][y]['RIGHT_check'] = True
if room[x][y]['y'] != 10 and room[x][y+1]['simbol'] != '#':
room[x][y+1]['LEFT_check'] = True
room[x][y+1]['path_length'] = room[x][y]['path_length'] + 1
search_function(room, x, y+1)
if room[x][y]['x'] == 0 and room[x][y]['y'] == 0 and room[x][y]['path_length'] == 1:
print 'YOOU SHELL NOT PASS!!! There is no escape!'
return
def input_read():
lab_map = []
labirinth = []
room = []
while True:
b = raw_input()
if b == '':
break
lab_map.append(b)
for i in range(len(lab_map)):
room.append([])
for j in range(len(lab_map[i])):
room[i].append(dict(simbol = lab_map[i][j],
x = i,
y = j,
path_length = 1,
UP_check = False,
DOWN_check = False,
LEFT_check = False,
RIGHT_check = False))
x, y = input('Enter star point x, y: ')
return room, x, y
path = []
room, x, y = input_read()
search_function(room, x, y)
print path
|
830e22e15f52ce5d1d0eb65a39c1ea345caadf5a
|
gokarna123/Gokarna
|
/classwork.py
| 333 | 4.125 | 4 |
from datetime import time
num=[]
x=int(input("Enter the number:"))
for i in range(1,x+1):
value=int(input(" Please Enter the number: "))
num.append(value)
num.sort()
print(num)
num=[]
x=int(input("Enter the number:"))
for i in range(1,x+1):
value=int(input(" Please Enter the number: "))
num.reverse()
print(num)
|
969f2679ef804d582202829a9d216accd056da4b
|
Mindo-Joseph/ProjectEuler100Challenge
|
/multiples3and5.py
| 169 | 3.984375 | 4 |
def multiples3and5(number):
total = 0
for i in range(number):
if i%3 == 0 or i%5 == 0:
total+=i
return total
print(multiples3and5(19564))
|
8563ff08b1cdda9f463b5856aac896f9cd3dc1d1
|
hpine19/Purple-cheesecakes
|
/problem3 copy.py
| 867 | 3.796875 | 4 |
#robotx= 0
#roboty= 0
#north= 2
#south= 3
#west= 4
#east= 5
#random(2,5)
#if 2
#move robot 2 coordinates north
#if 3
#move robot 3 coordinates south
#if 4
#move robot 4 coordinates west
#if 5
#move robot 5 coordinates east
import random
def twoDRandomWalk(n= 100, printOn= False):
n= 0
location= 0
count= 0
x= 0
y= 0
while abs(location) != n:
step= random.randint(3, 6)
if step== 3:
step= x- 1
elif step== 4:
step= x+ 1
elif step== 5:
step= y- 1
elif step== 6:
step= y+ 1
location= location+ step
print location
count= count+ 1
return count
print (twoDRandomWalk(n= 100, printOn= False))
'''
robotx= 0
roboty= 0
north= 2
south= 3
east= 4
west= 5
ran_direction= [north,south,east,west]
if north:
roboty= roboty+ 1
if south:
roboty= roboty- 1
if east:
robotx= robotx+ 1
if west:
robotx= robotx- 1
'''
|
1b44ff7a01a4998b83f75778925b8b09ffe7e3ca
|
tiredant/challenge-solutions
|
/romans.py
| 1,348 | 3.546875 | 4 |
import sys
def romans(x):
marker = 0
bench = []
while marker < int(x):
difference = int(x) - marker
if difference >= 1000:
marker += 1000
bench.append("M")
elif 1000 > difference >= 900:
marker += 900
bench.append("CM")
elif 900 > difference >= 500:
marker += 500
bench.append("D")
elif 500 > difference >= 100:
marker += 100
bench.append("C")
elif 100 > difference >= 90:
marker += 90
bench.append("XC")
elif 90 > difference >= 50:
marker += 50
bench.append("L")
elif 50 > difference >= 40:
marker += 40
bench.append("XL")
elif 40 > difference >= 10:
marker += 10
bench.append("X")
elif 10 > difference >= 9:
marker += 9
bench.append("IX")
elif 9 > difference >= 5:
marker += 5
bench.append("V")
elif 5 > difference >= 4:
marker += 4
bench.append("IV")
elif 4 > difference >= 1:
marker += 1
bench.append("I")
else:
pass
print "".join(bench)
with open(sys.argv[1], "r") as f:
for each in f:
romans(each)
|
9227a9c005d41eaed7b244a53c2187229d014c3f
|
jakehoare/leetcode
|
/python_1_to_1000/883_Projection_Area_of_3D_Shapes.py
| 1,371 | 3.921875 | 4 |
_author_ = 'jake'
_project_ = 'leetcode'
# https://leetcode.com/problems/projection-area-of-3d-shapes/
# On a N * N grid, we place some 1 * 1 * 1 cubes that are axis-aligned with the x, y, and z axes.
# Each value v = grid[i][j] represents a tower of v cubes placed on top of grid cell (i, j).
# Now we view the projection of these cubes onto the xy, yz, and zx planes.
# A projection is like a shadow, that maps our 3 dimensional figure to a 2 dimensional plane.
# Here, we are viewing the "shadow" when looking at the cubes from the top, the front, and the side.
# Return the total area of all three projections.
# Base area is the count of all cells with height > 0. Side areas are the sums of maximum heights by column and by
# row respectively.
# Time - O(mn)
# Space - O(m + n)
class Solution(object):
def projectionArea(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
n = len(grid)
row_heights, col_heights = [0] * n, [0] * n
base_area = 0
for row in range(n):
for col in range(n):
if grid[row][col] != 0:
base_area += 1
row_heights[row] = max(row_heights[row], grid[row][col])
col_heights[col] = max(col_heights[col], grid[row][col])
return base_area + sum(row_heights) + sum(col_heights)
|
a6391e05468eb3a42dca978a4a0aa015a77d770e
|
DannyHalstead/Ch.07_Graphics
|
/7.1_Flag.py
| 1,537 | 3.65625 | 4 |
'''
FLAG PROJECT
---------------
Make your flag 260 pixels tall
Use the scaling image on the website to determine other dimensions
The hexadecimal colors for the official flag are red:#BF0A30 and blue:#002868
Title the window, "The Stars and Stripes"
I used a draw_text command and used 20 pt. asterisks for the stars.
We will have a competition to see who can make this flag in the least lines of code.
The record is 16! You will have to use some loops to achieve this.
'''
import arcade #Setup and White Background
arcade.open_window(494,260, "The Stars and Stripes")
arcade.set_background_color(arcade.color.WHITE)
arcade.start_render()
for y in range(10,251,40): #Red Stripes
arcade.draw_rectangle_filled(247, y, 494,20, (191, 10, 48))
arcade.draw_rectangle_filled(99, 190, 198, 140, (0, 40, 104)) #Top Left Blue Box
y = 235 #White Stars First Part
for StarRows in range(9):
if StarRows%2==0:
x=16.38
for Star in range(6):
if Star==0:
arcade.draw_text("*",x,y,arcade.color.WHITE,20)
else:
arcade.draw_text("*", x, y, arcade.color.WHITE, 20)
x+=32.76
y-=15
y = 220 #Offset White Stars
for StarRows in range(9):
if StarRows%2==0:
x=32.76
for Star in range(5):
if Star==0:
arcade.draw_text("*",x,y,arcade.color.WHITE,20)
else:
arcade.draw_text("*", x, y, arcade.color.WHITE, 20)
x+=32.76
y-=15
arcade.finish_render() #Runs Arcade
arcade.run()
|
bc4e5e8af3ea7569bf39dcf4074f823ce02ba01b
|
HannahW432/new
|
/module1.py
| 554 | 4.0625 | 4 |
def change_frequency(frequency_changes):
current_frequency = 0;
for change in frequency_changes:
if (change[:1] == "+"):
current_frequency = current_frequency + change[1:]
else:
current_frequency = current_frequency + change[1:]
print (str(current_frequency))
def main():
frequency_changes = list()
for i in range(int(input("enter the amount of changes in the frequency"))):
frequency_changes.append(input("enter the next frequency change"))
change_frequency(frequency_changes)
|
d7df371297fc8c0aa1fc8cbca47ccd30603688e8
|
Risto97/simple-sat
|
/src/sudoku/sudoku.py
| 5,542 | 3.578125 | 4 |
import numpy as np
# https://github.com/MorvanZhou/sudoku
def generate_sudoku(mask_rate=0.5):
while True:
n = 9
m = np.zeros((n, n), np.int)
rg = np.arange(1, n + 1)
m[0, :] = np.random.choice(rg, n, replace=False)
try:
for r in range(1, n):
for c in range(n):
col_rest = np.setdiff1d(rg, m[:r, c])
row_rest = np.setdiff1d(rg, m[r, :c])
avb1 = np.intersect1d(col_rest, row_rest)
sub_r, sub_c = r // 3, c // 3
avb2 = np.setdiff1d(
np.arange(0, n + 1),
m[sub_r * 3:(sub_r + 1) * 3, sub_c * 3:(sub_c + 1) *
3].ravel())
avb = np.intersect1d(avb1, avb2)
m[r, c] = np.random.choice(avb, size=1)
break
except ValueError:
pass
mm = m.copy()
mm[np.random.choice([True, False],
size=m.shape,
p=[mask_rate, 1 - mask_rate])] = 0
return mm.tolist()
def parse_solution(solution):
solution = solution.split(" ")
board = np.zeros([9, 9], dtype=np.int8)
for literal in solution:
if "~" not in literal:
p = literal.find('p')
col, row = literal[p + 1:-1]
val = int(literal[-1])
board[int(col) - 1][int(row) - 1] = val
return board
# https://stackoverflow.com/questions/45471152/how-to-create-a-sudoku-puzzle-in-python
def draw_sudoku(board):
base = 3 # Will generate any size of random sudoku board in O(n^2) time
side = base * base
# for line in board: print(line)
def expandLine(line):
return line[0] + line[5:9].join(
[line[1:5] * (base - 1)] * base) + line[9:13]
line0 = expandLine("╔═══╤═══╦═══╗")
line1 = expandLine("║ . │ . ║ . ║")
line2 = expandLine("╟───┼───╫───╢")
line3 = expandLine("╠═══╪═══╬═══╣")
line4 = expandLine("╚═══╧═══╩═══╝")
symbol = " 1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ"
nums = [[""] + [symbol[n] for n in row] for row in board]
print(line0)
for r in range(1, side + 1):
print("".join(n + s for n, s in zip(nums[r - 1], line1.split("."))))
print([line2, line3, line4][(r % side == 0) + (r % base == 0)])
# https://scipython.com/book/chapter-6-numpy/examples/checking-a-sudoku-grid-for-validity/
def check_sudoku(grid):
""" Return True if grid is a valid Sudoku square, otherwise False. """
for i in range(9):
# j, k index top left hand corner of each 3x3 tile
j, k = (i // 3) * 3, (i % 3) * 3
if len(set(grid[i,:])) != 9 or len(set(grid[:,i])) != 9\
or len(set(grid[j:j+3, k:k+3].ravel())) != 9:
return False
return True
def gen_sudoku_sat(sudoku, fn="sudoku_tmp.in"):
dim = (9, 9)
f = open(fn, "w+")
# --------- Pre filled -------------
for row, line in enumerate(sudoku):
for col, val in enumerate(line):
if val != 0:
print(f"p{row+1}{col+1}{val}", file=f)
# -------- Individual Cell Clauses -----------
# at least one number in each cell
for row in range(1, dim[0] + 1):
for col in range(1, dim[1] + 1):
for i in range(1, 10):
print(f"p{row}{col}{i}", end=' ', file=f)
print(f"\n", end='', file=f)
# every cell can contain only one value
for row in range(1, dim[0] + 1):
for col in range(1, dim[1] + 1):
for i in range(1, 10):
for j in range(i + 1, 10):
print(f"~p{row}{col}{i} ~p{row}{col}{j}", file=f)
# ----------- Row Clauses ---------------------
# every row contains at least one of every value
for row in range(1, dim[0] + 1):
for i in range(1, 10):
for col in range(1, dim[1] + 1):
print(f"p{row}{col}{i}", end=' ', file=f)
print(f"\n", end='', file=f)
# row does not contain more than one of value
for i in range(1, 10):
for row in range(1, dim[0] + 1):
for col in range(1, dim[1] + 1):
for sub_col in range(col + 1, dim[1] + 1):
print(f"~p{row}{col}{i} ~p{row}{sub_col}{i}", file=f)
# -------------- Col Clauses -----------------------
# every col contains at least one of every value
for col in range(1, dim[1] + 1):
for i in range(1, 10):
for row in range(1, dim[0] + 1):
print(f"p{row}{col}{i}", end=' ', file=f)
print(f"\n", end='', file=f)
# col does not contain more than one of value
for i in range(1, 10):
for col in range(1, dim[1] + 1):
for row in range(1, dim[0] + 1):
for sub_row in range(row + 1, dim[1] + 1):
print(f"~p{row}{col}{i} ~p{sub_row}{col}{i}", file=f)
# ---------- Block Clauses ---------------------------
for block_row in [0, 1, 2]:
for block_col in [0, 1, 2]:
for i in range(1, 10):
for row in [1, 2, 3]:
for col in [1, 2, 3]:
print(
f"p{row+block_row*3}{col+block_col*3}{i}",
end=' ',
file=f)
print(f"\n", end='', file=f)
f.close()
|
b92dea7810c42718b32ec1689708dd9b5df21282
|
aftabanjum4451/Python-kick-Start-Repo
|
/Python Practice Question/Practice mod17.py
| 4,140 | 4.03125 | 4 |
# -*- coding: utf-8 -*-
"""
Created on Sat Aug 22 11:02:49 2020
@author: aftab
"""
#Q Create a function called mult that has two parameters, the first is required and should be an integer, the second is an optional parameter that can either be a number or a string but whose default is 6. The function should return the first parameter multiplied by the second.
intitia=6
def mult(x, y=intitia):
result=x*y
return result
mult(25)
#Q
def sum(intx,intz=5):
return intz + intx
#Q The following function, greeting, does not work. Please fix the code so that it runs without error. This only requires one change in the definition of the function.
def greeting(name,greeting="Hello ", excl="!"):
return greeting + name + excl
print(greeting("Bob"))
print(greeting(""))
print(greeting("Bob", excl="!!!"))
'''
Write a function, test, that takes in three parameters:
a required integer, an optional boolean whose default value is True,
and an optional dictionary, called dict1, whose default value is {2:3, 4:5, 6:8}.
If the boolean parameter is True, the function should test to see
if the integer is a key in the dictionary. The value of that key should then be returned.
If the boolean parameter is False, return the boolean value “False”.
'''
c=True
z={ 5:4, 2:1}
def test(a,boolieln=c,dict1=z):
if boolieln==True:
for item in dict1:
if isinstance(item, int)==True:
return dict1[item]
break
else:
return False
test(5,dict1 = {5:4, 2:1})
#Q
'''
Write a function called checkingIfIn that takes three parameters. The first is a required parameter,
which should be a string. The second is an optional parameter called direction with a default value of True.
The third is an optional parameter called d that has a default value of {'apple': 2, 'pear': 1, 'fruit': 19, 'orange': 5, 'banana': 3, 'grapes': 2, 'watermelon': 7}.
Write the function checkingIfIn so that when the second parameter is True, it checks to see if the first parameter is a key in the third parameter; if it is, return True, otherwise return False.
But if the second paramter is False,
then the function should check to see
if the first parameter is not a key of the third.
If it’s not, the function should return True in this case,
and if it is, it should return False.
'''
def checkingIfIn(a, direction = True, d = {'apple': 2, 'pear': 1, 'fruit': 19, 'orange': 5, 'banana': 3, 'grapes': 2, 'watermelon': 7}):
if direction == True:
if a in d:
return True
else:
return False
else:
if a not in d:
return True
else:
return False
checkingIfIn('ali')
#
'''
We have provided the function checkingIfIn such that if the first input parameter is in the third, dictionary, input parameter, then the function returns that value, and otherwise, it returns False. Follow the instructions in the active code window for specific variable assignmemts.
'''
def checkingIfIn(a, direction = True, d = {'apple': 2, 'pear': 1, 'fruit': 19, 'orange': 5, 'banana': 3, 'grapes': 2, 'watermelon': 7}):
if direction == True:
if a in d:
return d[a]
else:
return False
else:
if a not in d:
return True
else:
return d[a]
# Call the function so that it returns False and assign that function call to the variable c_false
c_false=checkingIfIn(2)
print(c_false)
# Call the fucntion so that it returns True and assign it to the variable c_true
c_true=checkingIfIn('apple2',direction = False)
print(c_true)
# Call the function so that the value of fruit is assigned to the variable fruit_ans
fruit_ans=checkingIfIn('watermelon')
print(fruit_ans)
# Call the function using the first and third parameter so that the value 8 is assigned to the variable param_check
param_check=checkingIfIn('cow',d = {'apple': 2, 'pear': 1, 'fruit': 19, 'orange': 5, 'banana': 3, 'grapes': 2, 'watermelon': 7, 'cow':8})
print(param_check)
|
51f83e8f423b4ed7b7252d3f7a394586b1825cd0
|
TemirT27/webdev2019
|
/week8/infromatics/arrays/g.py
| 141 | 3.53125 | 4 |
m = int(input())
arr = [int(a) for a in input().split()][:m]
reverse_a = arr[::-1]
for i in range(0, m):
print(reverse_a[i], end=' ')
|
f8a7e1e3b2401bb9c4e79a266a523ffb4040f63b
|
ckpmumbai/python
|
/1.2.py
| 121 | 3.84375 | 4 |
Firstname=input("enter firstname:")
Lastname=input("enter lastname:")
wholename =firstname+lastname
print(wholename)
|
876698a96fe413952c0332cac440276320d6c751
|
Botany-Downs-Secondary-College/speedingticket-ChrisLiangBDSC
|
/speeding_ticket.py
| 3,755 | 3.96875 | 4 |
speed = 0
speed_limit = 0
wanted_list = ["Jones", "Eric", "Dylan"]
fines = []
summary_list = []
over_limit = 0
statement = ""
user_answer = ""
def user_inputs():
global speed
global speed_limit
while True:
try:
speed = int(input("\nWhat was the speed you were going at? : "))
if speed <= 0:
print("Please enter proper numbers\n")
else:
while True:
try:
speed_limit = int(input("\nWhat was the speed limit? : "))
if speed_limit <= 0:
print("Please enter proper numbers\n")
else:
break
except ValueError:
print("Please enter valid intergers\n")
break
except ValueError:
print("Please enter valid intergers\n")
def calculate_fine(x, y):
global over_limit
over_limit = x - y
def fine_checker(x):
global statement
if x > 0 and x < 50:
statement = "The speed of your Vechile going at was {}kms^1 and the Limit was {}; \nYou are {}km^-1 OVER the speeding limit you MUST pay a fine of {:.2f}".format(x * 10)
elif x >= 50 and x <= 80:
statement = "The speed of your Vechile going at was {}kms^1 and the Limit was {}; \nYou are {}km^-1 OVER the speeding limit you MUST hand in your liscence".format(speed, speed_limit ,over_limit)
elif x > 80:
statement = "The speed of your Vechile going at was {}kms^1 and the Limit was {}; \nYou are {}km^-1 WELL beyond the speeding limit you MUST spend time in jail".format(speed, speed_limit ,over_limit)
else:
statement = "The speed of your Vechile going at was {}kms^1 and the Limit was {}; \nYou are {}km^-1 BELOW the speeding limit you do not have to pay or do anything!".format(speed, speed_limit ,over_limit * -1)
print(statement)
def summary_manager():
global summary_list
summary_list.append(["\nName: {}\n".format(name.lower().capitalize()),"Your speed: {}\n".format(speed), "The speed limit: {}".format(speed_limit),"\nSummary: {}".format(statement)])
user_answer = input("\nWould you like to take a look at your list of records? (Y/N): ").strip().lower()
while True:
if user_answer == "y":
while True:
try:
user_answer = int(input("\nWhich record would you like to read?\nPlease enter from 1-{} for corrisponding record : ".format(len(summary_list))))
if user_answer <= len(summary_list) and user_answer >= 1:
print(''.join(summary_list[user_answer - 1]))
break
elif user_answer <= 0 or isinstance(user_answer, float):
print("\nPlease enter valid whole numbers")
except ValueError:
print("\nPlease enter valid numbers")
elif user_answer == "n":
break
else:
print("Please answer valid input Y or N")
break
while True:
name = input("Please enter your name: ")
for i in range(0, len(wanted_list)):
if name.upper().capitalize() == wanted_list[i]:
print("{} is wanted for arrest".format(name.lower().capitalize()))
user_inputs()
calculate_fine(speed, speed_limit)
fine_checker(over_limit)
summary_manager()
user_answer = input("\nWould you like to enter another record? (Y/N): ").lower().strip()
if user_answer == "y":
continue
elif user_answer == "n":
break
else:
print("Please enter Y or N")
|
68a9f0c50395c900413dbec89737a22e155fd0d6
|
ayushig-29/91Docial-Task
|
/3.py
| 305 | 3.90625 | 4 |
#: Write a Python program to convert the Python dictionary object (sort by key) to
#JSON data. Print the object members with indent level 4
import json
str = {'a': 5, 'c': 7, 'b': 3, 'd': 4}
print("Original String:")
print(str)
print("JSON data:")
print(json.dumps(str, sort_keys=True, indent=4))
|
93f592fc315c339ba8e15679dd434a29235a1a08
|
omoh09/Python_First_Task
|
/AOC.py
| 522 | 4.25 | 4 |
#Create Basic Calculator for Area of a Circle
import math
from math import pi
while True:
try:
print('''
Write a Python program which accepts the radius
of a circle from the user and computes the area.
''')
radius = float(input ("Input the radius of the circle : "))
cal = float(pi * radius**2)
print ("The area of the circle with radius ", radius, "is: ", round(cal,2), "\n")
except ValueError:
print("Must be a digit")
quit();
|
26baf45d4f39d6f5a38f845730866b71ee4dd84a
|
20130353/Leetcode
|
/target_offer/二叉树/二叉树的右视图.py
| 798 | 3.71875 | 4 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @File : 二叉树的右视图.py
# @Author: smx
# @Date : 2020/2/18
# @Desc :
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def rightSideView(self, root):
if not root:
return []
queue = [root]
ans = []
while queue:
length = len(queue)
while length:
top = queue.pop(0)
if top.left:
queue.append(top.left)
if top.right:
queue.append(top.right)
if length == 1:
ans.append(top.val)
length -= 1
return ans
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.