text stringlengths 37 1.41M |
|---|
'''
Count-combination features in Pandas.
Intended for use on Amazon access data.
'''
import pandas as pd
import itertools as it
def get_counts(df, fields):
'''
Create value-count features for combinations of fields in a data frame.
Counts are taken over combinations of the values in fields.
Args:
df: input data frame
fields: list of column names in df
Returns:
1-column data frame of counts of combinations of values in fields
'''
gp = df.groupby(fields)
field_name = '_'.join(fields + ['ct'])
return pd.DataFrame({field_name: gp.size()})
def apply_counts(df, cts):
'''
Applies counts of combinations of values to a data frame.
If combinations occur in df that were not in cts, these are 0-filled.
Args:
df: input data frame
cts: 1-column data frame of counts of occurrances of combinations
Returns:
the input data frame, df, with the counts joined on
'''
fields = cts.index.names
out = df.merge(cts, how='left', left_on=fields, right_index=True)
ct_field = cts.columns[0]
return out[ct_field].fillna(0).astype(int)
def count_combinations(df_in, df_out, n):
'''
Produces count features for all n-combinations of columns in df_in.
Applies them to df_out (without changing df_out). The frames df_in and df_out
can be the same, in which case this is like fit_transform from the sklearn API.
NB: df_in and df_out should have the same column names.
Args:
df_in: input data frame for collecting counts
df_out: data frame to which counts are applied
n_val: int. Produces all n-combinations of the columns.
Returns:
Pandas DataFrame with the counts applied to df_out.
'''
out = pd.DataFrame(index=df_out.index)
field_combos = it.combinations(df_in.columns, n)
for fields in field_combos:
cts = get_counts(df_in, list(fields))
ct_field = cts.columns[0]
out[ct_field] = apply_counts(df_out, cts)
return out
def range_counts(df_in, df_out, kmax):
'''
Computes value-count features for k-combinations of columns in df_in/df_out
for all k in n_vals.
Args:
df_in: input data frame for collecting counts
df_out: data frame to which counts are applied
kmax: int, produces counts for 1...kmax combinations of the columns
Returns:
Pandas DataFrame with the counts applied to df_out.
'''
chunks = [count_combinations(df_in, df_out, n) for n in range(1, kmax + 1)]
return pd.concat(chunks, axis=1)
|
import time
import secrets
# Helper Functions:
# This function parses a string into an array of bytes
def toBytes(s:str):
return s.encode("utf-8")
# This function converts an array of bytes back to a String
def toString(b):
return b.decode("utf-8")
# These functions take care of user input and prompt user for a correct answer
def encryption_test(target):
while True:
num = input("Put the ciphertext you have found here (in hex): \n")
try:
decimal = int(num, 16)
if (target.hex() == format(decimal,'x')):
print("That's correct!")
print("Message sent...")
time.sleep(3)
return
else:
print("That's not correct. Try Again!")
except ValueError:
print("You did not enter a hexdecimal number")
def decryption_test(target):
while True:
num = input("What is the message? Put your answer here (in a String): \n")
if (num == target):
print("That's correct! \n You've cleared the challenge!")
return
else:
print("That's not the message, try again!")
# For every encryption algorithm, we need at least 3 functions
# Generate a random key for OTP
# The key is only for One time use
# reusing a key will make the encryption not secure
#
# Parameter:
# - length: number of bits of the plaintext being encrypted
#
# Return:
# Key that has the same length as the plaintext being encrypted
def key_gen(length):
return secrets.token_bytes(length)
# Encrypt the message provided
# Will generate a random key of the same length (in bits) as the msg
#
# Parameter:
# - msg: the message to be encrypted, in string
# - key: a key, in bytes, of the same length as msg
#
# Return:
# 1. Key used to encrypt the message, in bytes
# 2. ciphertext/encrypted message, in bytes
def encrypt(msg, key=None):
bits = toBytes(msg)
if (key == None or len(key) != len(bits)):
key = key_gen(len(bits))
cipher = bytes([a ^ b for (a,b) in zip(bits, key)])
return key, cipher
# Decrypt a message provided
#
# Parameter:
# - cipher: ciphertext to be decrypted, in bytes
# - key : key used to decrypt the ciphertext, in bytes
#
# Return:
# The decrypted message in String, or None if the length of cipher != length of key
def decrypt(cipher, key):
if (len(key) != len(cipher)):
return None
plain = bytes([a ^ b for (a,b) in zip(cipher, key)])
return toString(plain) |
# 1.3 URLify
# Write a method to replace all spaces in a string with '%20'. You may assume that the string has sufficient space at the end to hold the additional characters, and that you are given the 'true' length of the string. (Note: if implementing in Java, please use a character array so that you can perform this operation in place.)
# Ex. Input: 'Mr John Smith ', 13
# Ouput: 'Mr%20John%20Smith'
import re
# built in py module solution
def builtIn_urlify(foo, truelen):
# strip leading and trailing whitespace
foo = foo.strip()
return foo.replace(' ', '%20')
# regex solution
def regex_urlify(foo, truelen):
foo = foo.strip()
return re.sub('\s', '%20', foo)
def urlify(truelen):
# set foo to modify global variable
global foo
# convert foo to character array
foo = list(foo)
spaces = 0
for char in foo[:truelen]:
if char == ' ':
spaces += 1
# truelen includes single spaces, each of which will be two more chars when replaced with '%20'
i = truelen + spaces*2
# tag end of char array
if truelen < len(foo): foo[truelen] = '\0'
for char in reversed(foo[:truelen]):
if char == ' ':
foo[i-1] = '0'
foo[i-2] = '2'
foo[i-3] = '%'
i -= 3
else:
foo[i-1] = char
i -= 1
# convert char array back to string foo
foo = ''.join(foo)
foo = 'Mr John Smith '
def tests():
urlify(13)
assert foo == 'Mr%20John%20Smith'
print('tests pass')
tests() |
import matplotlib.pyplot as plt
class FenetreCourbe(object):
"à partir de listes de valeurs (les tailles des populations relevées à intervalles réguliers) affiche des courbes d'évolution de ces population en fonction du temps"
def __init__(self,donnees=[24,58,65,69,32,14,78,25,3,8]): ## Cette liste ne sert qu'à initialiser, on pourra la changer ou la supprimer
def afficheCourbe(self):
nb_donnees=len(self.donnees)
uniteTemps=[]
for i in range (nb_donnees):
uniteTemps.append(i)
plt.plot(uniteTemps,self.donnees)
plt.show()
####################################################################
#
# Pour l'utilisation, on procédera ainsi :
#
# f1=FenetreCourbe([31,45,54,50,38]) (par exemple...)
# f1.afficheCourbe()
#
####################################################################
|
def foo(x, y, result):
if result is None:
return (y + 1) ^ x ^ 1337
elif x is None:
return result ^ (y + 1) ^ 1337
elif y is None:
return (result ^ x ^ 1337) - 1
def bar(x, y, z, result):
if result is None:
return (z + 1) * y + x
elif x is None:
return result - (z + 1) * y
elif y is None:
return (result - x) // (z + 1)
elif z is None:
return (result - x) // y - 1
|
list=["maria", "pepe", "Marta", "Antonio"]
print(list[:])
print(list[3])
print(list[-2])
#cuando utilizamos el - empieza desde atras y el primer elemento es -1; en lugar 0
print(list[0:3])
#porciones, incluye el primer elemento y omite el ultimo indicado en el print
print(list[2:])
#ejecuta desde el valor indicado inclusive en adelante -->
list.append("Javi")
#agrega valor al final de la lista
list.insert(2,"Javi")
#insertar en posicion especifica
print(list)
list.extend(["Sandra", "Ana", "Lucia"])
#extender
print(list)
print(list.index("Javi"))
#en que indice esta x? devuelve posicion ò indice del valor buscado
print("Javi" in list)
#devuelve true o false en caso que el valor buscado este en la lista
list.remove("Ana")
print(list)
list.pop()
#elimina el ultimo elemento de la lista
print(list)
list2=["angel", "carlitos"]*3
list3=list+list2
#Sumar listas
print(list3)
#listas pueden multiplicarse EJ = list(xx)*3
#TUPLAS. Son listas inmutables, no podemos modificarla, añadir (append) , mover, eliminar elementos (remove)
#Son mas rapidas, menos espacio, formatean strings, pueden utilizarse como claves en un diccionario
#Permiten extraer porciones siendo el resultado una tupla nueva
#Permiten comprobar si un elemento se encuentra en la tupla y buscarlo (index)
#Van entre () a diferencia de las listas que van en [], aunque son opcionales
tupla=("Juan", 13,1,1995)
tupla=tuple(tupla)
print(tupla[0])
print(tupla)
#List y tuple funciones para convertir una lista en tupla y viceversa
#Funcion count consulta cuantos valores hay
print(tupla.count(13))
#Funcion len consulta la longitud de elementos en tupla
nombre, dia, mes, agno=tupla
print(nombre)
print(dia)
print(agno)
print(mes)
#Desempaquetado de Tuplas.
|
#Continue, Pass y else
#Continue: indica a donde continuar la intruccion y bucle. Salta a la sig interaccion de bucle
#Pass se usa para definir clases (ej: nulas) y casos concretos. Devuelve "null" como si no ejecutara
#Pass cuando quieres desarrollar algo despues y usas este pass para continuar trabajando
for letra in"Python":
if letra=="h":
continue
print("viendo la letra: "+ letra)
#Cuando se da la condicion, el continue salta la linea siguiente, en este caso el print.
#CONTADOR CON BUCLE CONTINUE. CUENTA DE CARACTERES
nombre="Pildoras Informaticas"
contador=0
for i in nombre:
if i==" ":
continue
contador+=1
print(contador)
|
#Generate hashes of string data using 3 Algorithms from hashlib
import hashlib
str1="Ambar Mittal"
#Using sha1 Algorithm
Hashed_1=hashlib.sha1(str1.encode()).hexdigest()
print("Hashed Password using sha1:",Hashed_1)
#Using blake2b Algorithm
Hashed_2=hashlib.blake2b(str1.encode()).hexdigest()
print("Hashed Password using blake2b:",Hashed_2)
#Using sha3_224 Algorithm
Hashed_3=hashlib.sha3_224(str1.encode()).hexdigest()
print("Hashed password using sha3_224:",Hashed_3)
|
### Project Description ###
# The project will be a Kinect-supported game called "Shape-Matching Game".
# A shape formed by connecting multiple circles will be displayed on the screen,
# and the player gains points by touch all circles simultaneously with their
# hands, feet, and/or head. The game will also support multi-player and
# include a level-editor.
### Competitive Analysis ###
### Structual Plan ###
# __main__.py
# class Main()
# function __init__
# function drawKinectFrame; getJointPos
# function runMain
# end of file calls runStartScreen, then runMain
# startScreen.py
# function drawStartScreen
# function buttonTouched
# function runStartScreen
# exits if play button touched
# calls runLevelEditor if make level button touched
# circleClass.py
# object Circle
# attribute position
# function draw
# function isHit
# object targetCircle inherits from Circle
# object bodyCircle inherits from Circle
# function generateTargetCircles; generateBodyCircles
# function checkCollisions; isShapeComplete
# function drawAll
# levelEditor.py
# function drawLevelEditor
# function addShape
### ALgorithmic Plan ###
# for creating targets, checking overlap, and generating levels
# step 1: generate targets
# randomly placed and from pre-made levels
# single player:
# random.choice 2, 3, or 4 targets
# 1/4 of the time pre-made levels (weigh choice somehow?)
# targets must be fully on screen and cannot overlap
# 100 pixels < seperation < 1000 pixels
# two-player:
# 5 or more targets
# 1/2 pre-made levels to avoid getting messy
# step 2: generate body circles
# converts joint locations to color-frame locations
# draws five dots at head, left/right hand, and left/right food
# smaller than targets, different fill
# maybe add elbows too for complexity
# step 3: check collisions
# loop through each target and each bodyCircle
# if they overlap
# change bodyCircle color
# change status of target to hit
# if all targets hit, increment score + back to step 1
### Timeline Plan ###
###Version Control Plan###
# backup code using github: https://github.com/xiranw/112-Term-Project
###Module List###
# Kinect
# Pygame |
''' REPLACING ALL SPECIAL CHARACTERS'''
STR1 = input()
STR2 = " "
for i in STR1:
if i in "!@#$%^&*":
STR1 = ""
else:
STR2 += i
print(STR2)
|
'''GIVEN A NUMBER, FIND THE PRODUCT OF THE DIGITS'''
NUM = int(input())
COUNT = 0
PROD = 1
COUNT2 = 0
if NUM == 1:
print(1)
if NUM == 2:
print(2)
if NUM == 3:
print(3)
if NUM == 4:
print(4)
if NUM == 5:
print(5)
if NUM == 6:
print(6)
if NUM == 7:
print(7)
if NUM == 8:
print(8)
if NUM == 9:
print(9)
else:
while NUM != 0 and NUM > 9 or NUM < 0:
REM = NUM%10
if REM == 0:
COUNT = COUNT+1
break
else:
PROD = PROD*REM
NUM = NUM//10
COUNT2 = COUNT2 + 1
if NUM == 0:
print(0)
if COUNT > 0:
print(0)
elif COUNT2 > 0:
print(PROD)
|
import json
import urllib.request as jur
j_url = input("Enter location: ")
data = jur.urlopen(j_url).read().decode()
print('Retrieving', j_url)
print('Retrieved', len(data), 'characters')
info = json.loads(data)
print('User count:', len(info))
sum=0
total=0
for comment in info["comments"]:
sum = sum + int(comment["count"])
total = total + 1
print('Count:', total)
print('Sum:', sum)
|
>>> 'a' in 'banana'
True
>>> 'seed' in 'banana'
False
--
>>> line.lower()
'have a nice day'
>>> line.lower().startswith('h')
True
print('Hi There'.lowe())
>>>hi there
---
**************
stuff = "Hello World"
>>> dir(stuff)
['capitalize', 'casefold', 'center', 'count', 'encode',
'endswith', 'expandtabs', 'find', 'format', 'format_map',
'index', 'isalnum', 'isalpha', 'isdecimal', 'isdigit',
'isidentifier', 'islower', 'isnumeric', 'isprintable',
'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower',
'lstrip', 'maketrans', 'partition', 'replace', 'rfind',
'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip',
'split', 'splitlines', 'startswith', 'strip', 'swapcase',
'title', 'translate', 'upper', 'zfill']
***********
---
>>> data = 'From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008'
>>> atpos = data.find('@')
>>> print(atpos)
21
--
>>>greet = "Hello Bob"
>>>nstr = greet.replace("Bob","Onur")
>>>print(nstr)
Hello Onur
|
import re
x = "My 2 favorite numbers are 19 and 42"
y = re.findall("[0-9]+",x)
print(y)
o<<<['2', '19', '42']
|
"""
File: slotmachine.py
Author: David
Python Final Project (9/23/19)
Create a Slot Machine GUI-based application
This application should be GUI-based and contain the following features:
- A label that serves as the title of your app
- A command button that will run the application
- Fields and labels for the output as described below
- The application should randomly generate three integers between 0 and 9 (like a slot machine)
- If the player gets all three numbers the same, a JACKPOT is awarded
- If the player gets 2 of the three numbers the same, a TWO OF A KIND is awarded
- Any other combination of numbers is a LOSS
- The random numbers will need to be displayed in the GUI as well as a message describing the game outcome
"""
from breezypythongui import EasyFrame
import random
class SlotMachine(EasyFrame):
def __init__(self):
# Adding window and widgets
EasyFrame.__init__(self, title = "Slot Machine!")
self.setResizable(False);
# Create a panel for everything to exist on
dataPanel = self.addPanel(row = 0, column = 0, columnspan = 3, background = "plum")
bgPanel = self.addPanel(row = 1, column = 0, columnspan = 3, background = "cornflowerblue")
bgSlot1 = bgPanel.addPanel(row = 5, column = 0, background = "gold")
bgSlot2 = bgPanel.addPanel(row = 5, column = 1, background = "gold")
bgSlot3 = bgPanel.addPanel(row = 5, column = 2, background = "gold")
# Adding introductory fields
self.title = dataPanel.addLabel(text = "Lucky Slots!!!", row = 0, column = 0,columnspan = 3, sticky = "NSEW")
self.title["background"] = "plum"
self.instruction = dataPanel.addLabel(text = "Each time you lost it will cost 10 points.\nIf you win TWO OF A KIND you will win 30 points.\nIf you win the JACKPOT you will win 50.", row = 1, column = 0, columnspan = 3, sticky = "NSEW")
self.instruction["background"] = "plum"
# Adding score keeping fields
self.bettingPool = bgPanel.addLabel("Points:", row = 2, column = 0, sticky = "NSEW", background = "orange")
self.points = bgPanel.addIntegerField(value = 100, row = 2, column = 1)
self.points["background"] = "orange"
bgPanel.addLabel(" ", row = 2, column = 2, background = "cornflowerblue")
# Adding fields for the Slots
# Output Label
self.output = bgPanel.addTextField(text = "", row = 4, column = 0, columnspan = 3, sticky = "NSEW")
# Slot Labels
self.slotLabel1 = bgSlot1.addLabel(text = "Slot 1", row = 5, column = 0, sticky = "NSEW")
self.slotLabel1["background"] = "gold"
self.slotLabel2 = bgSlot2.addLabel(text = "Slot 2", row = 5, column = 1, sticky = "NSEW")
self.slotLabel2["background"] = "gold"
self.slotLabel3 = bgSlot3.addLabel(text = "Slot 3", row = 5, column = 2, sticky = "NSEW")
self.slotLabel3["background"] = "gold"
# Adding IntegerFields for Slots
self.firstSlot = bgSlot1.addIntegerField(value = 0, row = 6, column = 0, sticky = "NSEW")
self.firstSlot["background"] = "gold"
self.secondSlot = bgSlot2.addIntegerField(value = 0, row = 6, column = 1, sticky = "NSEW")
self.secondSlot["background"] = "gold"
self.thirdSlot = bgSlot3.addIntegerField(value = 0, row = 6, column = 2, sticky = "NSEW")
self.thirdSlot["background"] = "gold"
# Adding Command Buttons
# Play the slots games
self.slotsButton = bgPanel.addButton("Play Slots!", row = 7, column = 0, columnspan = 2, command = self.playSlots)
self.slotsButton["background"] = "limegreen"
# Reset the Points to play again
self.resetButton = bgPanel.addButton("Reset", row = 7, column = 1, columnspan = 2, command = self.reset)
self.resetButton["background"] = "limegreen"
# Method that sets up all the data for the running of the slots game
def playSlots(self):
# Points Pool Variable
adjPoints = self.points.getNumber()
# Text Output
messages = ["WINNER! JACKPOT!!!",
"WINNER! TWO OF A KIND!!",
"Sorry, no matches. Try again?!",
"Sorry, no more points to play..."]
# Randomly Generated Slots
slot1 = random.randint(0, 9)
slot2 = random.randint(0, 9)
slot3 = random.randint(0, 9)
# Setting Numbers to the slot IntegerFields
self.firstSlot.setNumber(slot1)
self.secondSlot.setNumber(slot2)
self.thirdSlot.setNumber(slot3)
# If none of the slots match one another then the player loses
if slot1 != slot2 and slot1 != slot3 and slot2 != slot3:
adjPoints = adjPoints - 10
self.points.setNumber(adjPoints)
self.output.setText(messages[2])
self.output["background"] = "tomato"
self.firstSlot["background"] = "white"
self.secondSlot["background"] = "white"
self.thirdSlot["background"] = "white"
# Check to see if the player has anymore points
if adjPoints == 0:
# If not then display message and disable the button
self.output.setText(messages[3])
self.slotsButton["state"] = "disabled"
# Else Check all the slots for equality
else:
self.checkSlots(slot1, slot2, slot3, adjPoints, messages)
self.checkSlots(slot1, slot3, slot2, adjPoints, messages)
self.checkSlots(slot2, slot1, slot3, adjPoints, messages)
# Method that checks the equality of all the slot numbers
def checkSlots(self, slot1, slot2, slot3, adjPoints, messages):
# If the first and second slot are the same
if slot1 == slot2:
# And the second and third are the same
if slot2 == slot3:
# Then we have a Jackpot!
adjPoints = adjPoints + 50
self.points.setNumber(adjPoints)
self.output.setText(messages[0])
self.output["background"] = "forestgreen"
self.firstSlot["background"] = "forestgreen"
self.secondSlot["background"] = "forestgreen"
self.thirdSlot["background"] = "forestgreen"
# Else we have a 2 of a kind
else:
adjPoints = adjPoints + 30
self.points.setNumber(adjPoints)
self.output.setText(messages[1])
self.output["background"] = "forestgreen"
self.firstSlot["background"] = "forestgreen"
self.secondSlot["background"] = "forestgreen"
self.thirdSlot["background"] = "forestgreen"
# Method that reenstates the 'Play Again' button and resets some variables and panels
def reset(self):
resetPoints = self.points.getNumber()
resetPoints = 100
self.points.setNumber(resetPoints)
self.output.setText("")
self.output["background"] = "white"
self.slotsButton["state"] = "normal"
def main():
SlotMachine().mainloop()
main() |
import re
def testPasswordStrength(password):
eightCharsLongRegex = re.compile(r'[\w\d\s\W\D\S]{8,}')
upperCaseRegex = re.compile(r'[A-Z]+')
lowerCaseRegex = re.compile(r'[a-z]+')
oneOrMoreDigitRegex = re.compile(r'\d+')
if not eightCharsLongRegex.search(password):
return False
elif not upperCaseRegex.search(password):
return False
elif not lowerCaseRegex.search(password):
return False
elif not oneOrMoreDigitRegex.search(password):
return False
return True
if __name__ == "__main__":
password = '594'
print(testPasswordStrength(password)) |
# -*- coding: utf-8 -*-
"""
Created on Mon Nov 18 12:41:33 2019
@author: Gabriel Silva, 100451
Vertex cover algorithm:
Initialize all possible solutions
while there are solutions
Check if current solution is valid:
if valid:
count the number of vertices used
return the lowest count value
"""
import itertools
class VertexCover():
def validity_check(self,cover, graph, operations):
is_valid = True
for i in range(len(graph)):
operations += 1
for j in range(i+1, len(graph[i])):
operations += 1
if graph[i][j] == 1 and cover[i] != '1' and cover[j] != '1': #check if the given solution is valid according to the graph
operations += 1
return False, operations
return is_valid, operations
def min_vertex_cover(self,graph):
n = len(graph)
minimum_cover = n
num_edge = list(itertools.product(*["01"] * n)) #initialize every possible solution
print(len(num_edge))
operations = 0
for i in num_edge: #go through every solution and check if they're valid.
operations += 1
valid, operations = self.validity_check(i,graph,operations)
if valid:
counter = 0
for value in i:
operations += 1
if value == '1':
operations += 1
counter += 1
minimum_cover = min(counter, minimum_cover) #check if the solution is better than the current solution
return minimum_cover, operations
|
"""
Translate a RNA into peptides
Calculate a peptides could be translated from in total how many RNAs
"""
codon_table_file =open('RNA_codon_table.txt')
CODON_TABLE = {}
REVERSE_CODON_TABLE ={}
for line in codon_table_file.readlines():
# Construct CONDON TABLE dict
entry = line.split()
if len(entry) > 1:
CODON_TABLE[entry[0]] = entry[1]
# REVERSE_CODON_TABLE.update([entry[1], entry[0]])
else:
CODON_TABLE[entry[0]] = ''
#print REVERSE_CODON_TABLE
def translation(rna_seq):
peptide = ''
while len(rna_seq) > 0:
aa = CODON_TABLE[rna_seq[0:3]]
if aa == '':
return peptide
peptide += aa
rna_seq = rna_seq[3:]
return peptide
print translation('CCCAGUACCGAGAUGAAU')
def possibility(peptide):
# Calculate the peptides could be translated from in total how many RNAs
times = 1
for aa in peptide:
i = 0
for key in CODON_TABLE:
if CODON_TABLE[key] == aa:
i += 1
times *= i
return times
#print possibility('G') # should be 4
#print possibility('GAE') # 32
print possibility('SYNGE')
|
"""
Calulates simple equations for use in basic electrical engineering
"""
def main():
print "Welcome!"
print ""
print "--------------------"
print "1: Calculate using Ohm's Law"
print "2: Calculate a resistor's value"
print "--------------------"
print ""
choice = int(raw_input("Enter the value for which function you wish to perform: "))
if choice == 1:
calculateOhms()
elif choice == 2:
calculateResist()
else:
errorHandler("Not a valid selection!")
def calculateOhms():
print("Welcome to EE Helper")
print("Let's calculate some values with Ohm's Law!")
units = ["Volts", "Amps", "Ohms"]
v = raw_input("Enter the voltage: ")
vunits = raw_input("Enter the units for Voltage (V, mV): ")
while (vunits.upper() != "V" and vunits.upper() != "MV"):
vunits = raw_input("Enter the units for Voltage (V, mV): ")
if vunits.upper() == "MV" and v != "":
v = float(v)/1000
elif vunits.upper() == "V" and v != "":
v = float(v)
i = raw_input("Enter the current: ")
iunits = raw_input("Enter the units for Amps (A, mA): ")
while (iunits.upper() != "A" and iunits.upper() != "MA"):
iunits = raw_input("Enter the units for Amps (A, mA): ")
if iunits.upper() == "MA" and i != "":
i = float(i)/1000
elif iunits.upper() == "A" and i != "":
i = float(i)
r = raw_input("Enter the resistance: ")
runits = raw_input("Enter the units for Resistance(Ohm, kOhm): ")
while (runits.upper() != "OHM" and runits.upper() != "KOHM"):
runits = raw_input("Enter the units for Resistance (Ohm, kOhm): ")
if runits.upper() == "KOHM" and r != "":
r = float(r)*1000
elif runits.upper() == "OHM" and r != "":
r = float(r)
# Units and values are now validated
missing = findSolve(v, i ,r)
result = calulateMissing(missing, v, i, r)
displayResults(units[missing], result, [v, i, r], units, missing)
# print(units[missing], result)
def findSolve(v, i, r):
if v == "":
return(0)
elif i == "":
return(1)
elif r == "":
return(2)
else:
errorHandler("No values were left empty!")
def calulateMissing(missing, v, i, r):
if missing == 0:
return i*r
elif missing == 1:
return v/r
elif missing == 2:
return v/i
else:
errorHandler("Values are not properly set up!")
def displayResults(unit, answer, initialVals, units, missing):
# print(units)
# print(answer)
# print(initialVals)
print "--------------------"
for i in range(len(initialVals)):
if initialVals[i] != "":
print units[i] + ": " + str(initialVals[i])
else:
print unit + ": " + str(answer)
print "--------------------"
initialVals[missing] = answer
print "Power: " + str(initialVals[0]*initialVals[1]) + " Watts"
print "--------------------"
# Ask to restart
rerun = raw_input("Would you like to start do another? (Y/N) ")
while rerun.upper() != "Y" and rerun.upper() != "N":
rerun = raw_input("Would you like to do another? (Y/N) ")
if rerun.upper() == "Y":
calculateOhms()
else:
exit()
def errorHandler(e):
print("Oops! The follwing error occured:")
print(e)
rerun = raw_input("Would you like to start over? (Y/N) ")
while rerun.upper() != "Y" and rerun.upper() != "N":
rerun = raw_input("Would you like to start over? (Y/N) ")
if rerun.upper() == "Y":
main()
else:
exit()
def calculateResist():
print("Calculating Resistance!")
bands = []
for i in range(4):
print "Band " + str(i+1)
color = raw_input("Enter the color of the band: ")
bands.append(getColorVals(color, i+1))
bandValue = 0
bandValue = str(bands[0])+str(bands[1])
bandValue = int(bandValue)*float(bands[2])
print("--------------------")
print str(bandValue) + " Ohms"
print "Tolerance: " + str(bands[3])+"%"
print("--------------------")
# Ask to restart
rerun = raw_input("Would you like to do another? (Y/N) ")
while rerun.upper() != "Y" and rerun.upper() != "N":
rerun = raw_input("Would you like to do another? (Y/N) ")
if rerun.upper() == "Y":
calculateResist()
else:
exit()
def getColorVals(color, bandNum):
if bandNum == 1 or bandNum == 2:
if color.lower() == "black":
return 0
elif color.lower() == "brown":
return 1
elif color.lower() == "red":
return 2
elif color.lower() == "orange":
return 3
elif color.lower() == "yellow":
return 4
elif color.lower() == "green":
return 5
elif color.lower() == "blue":
return 6
elif color.lower() == "purple" or color.lower() == "violet":
return 7
elif color.lower() == "grey":
return 8
elif color.lower() == "white":
return 9
else:
errorHandler("Incorrect value entered for the band!")
elif bandNum == 3:
if color.lower() == "black":
return 1
elif color.lower() == "brown":
return 10
elif color.lower() == "red":
return 100
elif color.lower() == "orange":
return 1000
elif color.lower() == "yellow":
return 10000
elif color.lower() == "green":
return 100000
elif color.lower() == "blue":
return 1000000
elif color.lower() == "purple" or color.lower() == "violet":
return 10000000
elif color.lower() == "gold":
return 0.1
elif color.lower() == "silver":
return 0.01
else:
errorHandler("Incorrect value entered for the band!")
elif bandNum == 4:
if color.lower() == "brown":
return 1
elif color.lower() == "red":
return 2
elif color.lower() == "green":
return 0.5
elif color.lower() == "blue":
return 0.25
elif color.lower() == "purple" or color.lower() == "violet":
return 0.10
elif color.lower() == "grey":
return 0.05
elif color.lower() == "gold":
return 5
elif color.lower() == "silver":
return 10
else:
errorHandler("Incorrect value entered for the band!")
main()
|
删除排序链表中的重复元素
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def deleteDuplicates(self, head: ListNode) -> ListNode:
h = head
if h == None:
return []
while h.next:
if h.next.val == h.val:
h.next = h.next.next
else:
h = h.next
return head
|
生命游戏
class Solution:
def gameOfLife(self, board):
"""
:type board: List[List[int]]
:rtype: void Do not return anything, modify board in-place instead.
"""
q = copy.deepcopy(board)
hang = len(board)
lie = len(board[0])
for i in range(hang):
for j in range(lie):
li = []
if i-1 >=0:
li.append(board[i - 1][j])
if i-1>=0 and j -1>=0:
li.append(board[i - 1][j - 1])
if i-1>=0 and j +1 < lie:
li.append(board[i - 1][j + 1])
if j -1 >=0:
li.append(board[i][j - 1])
if j +1 <lie:
li.append(board[i][j + 1])
if i+1<hang and j+1 < lie:
li.append(board[i + 1][j + 1])
if i+1<hang and j-1 >=0:
li.append(board[i + 1][j - 1])
if i+1 <hang:
li.append(board[i + 1][j])
cont = li.count(1)
if cont == 3:
q[i][j] = 1
if cont > 3:
q[i][j] = 0
if cont < 2:
q[i][j] = 0
for i in range(hang):
for j in range(lie):
board[i][j] = q[i][j]
|
下降路径最小和
class Solution:
def minFallingPathSum(self, A: List[List[int]]) -> int:
row = len(A[0])
res = [[1000 for i in range(row)] for j in range(len(A))]
for i in range(row):
res[0][i] = A[0][i]
for i in range(1,len(A)):
for j in range(row):
if j-1 >=0 and j+1 < row:
res[i][j] = A[i][j] + min(res[i-1][j-1],res[i-1][j],res[i-1][j+1])
elif j-1 >=0 and j+1 >= row:
res[i][j] = A[i][j] + min(res[i-1][j-1],res[i-1][j])
elif j-1 < 0 and j+1 <row:
res[i][j] = A[i][j] + min(res[i-1][j],res[i-1][j+1])
return min(res[-1])
|
两个数组的交集 II
class Solution:
def intersect(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
list1 = []
for i in nums1:
if i in nums2:
list1.append(i)
nums2.pop(nums2.index(i))
return list1
|
子域名访问计数
class Solution:
def subdomainVisits(self, cpdomains):
"""
:type cpdomains: List[str]
:rtype: List[str]
"""
dict = {}
for i in range(len(cpdomains)):
left,right = cpdomains[i].split(" ")
list = []
list = right.split(".")
for j in range(len(list)):
s = list[j]
if j != len(list)-1:
for q in range(j+1,len(list)):
s = s+"."+list[q]
if s in dict.keys():
dict[s] = dict[s] + int(left)
else:
dict[s] = int(left)
list = []
s = ""
for i,j in dict.items():
s = str(j)+" "+i
list.append(s)
s = ""
return list
|
打家劫舍 III
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def rob(self, root: TreeNode) -> int:
def dp(root):
if not root:
return [0,0]
left = dp(root.left)
right = dp(root.right)
res = [left[1]+right[1],max(left[1]+right[1],right[0]+left[0]+root.val)]
return res
return dp(root)[-1]
|
二叉搜索树的最小绝对差
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def getMinimumDifference(self, root: TreeNode) -> int:
res = []
def dp(root):
if root != None:
dp(root.left)
res.append(root.val)
dp(root.right)
dp(root)
import sys
min1 = sys.maxsize
for i in range(1,len(res)):
min1 = min(min1,res[i]-res[i-1])
return min1
|
斐波那契数
class Solution:
def fib(self, N: int) -> int:
if N == 0:
return 0
if N == 1:
return 1
list1 = [0,1]
for i in range(2,N+1):
list1.append(list1[i-1] + list1[i-2])
return list1[-1]
|
两数之和 II - 输入有序数组
class Solution:
def twoSum(self, numbers: List[int], target: int) -> List[int]:
len1 = len(numbers)
import bisect
s = set()
for i in range(0,len1):
if numbers[i] in s:
continue
for j in range(i+1,len1):
if numbers[i] + numbers[j] == target:
return i+1,j+1
s.add(numbers[i])
|
比特位计数
class Solution:
def countBits(self, num):
"""
:type num: int
:rtype: List[int]
"""
list1 = [0 for i in range(num+1)]
for i in range(1,num+1):
n = i
cont = 0
if list1[i] == 0:
while n:
n = n & (n-1)
cont += 1
while i <num+1:
list1[i] = cont
i = i << 2
return list1
|
4的幂
class Solution:
def isPowerOfFour(self, num):
"""
:type num: int
:rtype: bool
"""
j = 1
for i in range(32):
if j == num:
return True
elif j > num:
return False
j = j * 4
|
递增子序列
class Solution:
def findSubsequences(self, nums: List[int]) -> List[List[int]]:
res = set()
len1 = len(nums)
def dfs(nums,a):
if len(a) >=2:
res.add(tuple(a[::]))
for j in range(len(nums)):
if nums[j] >= a[-1]:
a.append(nums[j])
dfs(nums[j+1:],a)
a.pop()
for i in range(len1):
dfs(nums[i+1:],[nums[i]])
return list(res)
|
字符串中的第一个唯一字符
class Solution:
def firstUniqChar(self, s):
"""
:type s: str
:rtype: int
"""
q = list(set(s))
lis = []
for i in range(len(q)):
if s.count(q[i]) == 1:
lis.append(s.index(q[i]))
if lis:
return min(lis)
else:
return -1
|
反转链表 II
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def reverseBetween(self, head: ListNode, m: int, n: int) -> ListNode:
sum1 = 0
x = head
flag = ListNode(0)
flag.next = head
res = 0
while x != None:
sum1 += 1
if sum1 == m-1:
res = 1
flag = x
x = x.next
elif m <= sum1 < n:
q = ListNode(x.next.val)
q.next = flag.next
flag.next = q
x.next = x.next.next
else:
x = x.next
return head if res == 1 else flag.next
|
print("DISCLAIMER: Only merge sort works with string arrays.")
#import statements
import time
from generate import gen
from importing import importlist
from msort import mergesort
from bubble import bubblesort
from insertion import insertionsort
from linearsearch import linearsearch
from binarysearchtree import btsearch
from binarysearch import binsearch
# generate/import array
startingarrgen = input(
'''\nEnter 1 if you want to generate an array of number.\nEnter 2 if you want to import numbers from a text file: ''')
# validation
while startingarrgen not in ["1", "2"]:
print("Invalid")
startingarrgen = input(
'''\nEnter 1 if you want the program to generate an array of number.\nEnter 2 if you want to import numbers from a text file: ''')
listtype = "int"
startarray = []
if startingarrgen == "1":
n = input("\nHow many integers would you like to generate: ")
x = input("What is the minimum value of integers: ")
y = input("What is the maximum value of integers: ")
while not n.isdigit() or not x.isdigit or not y.isdigit() or int(n) < 0 or y < x:
print("\nInvalid input")
n = input("\nHow many integers would you like to generate: ")
x = input("What is the minimum value of integers: ")
y = input("What is the maximum value of integers: ")
startarray = gen(int(n), int(x), int(y))
else:
print("\nYou can import txt or csv files. Please see README for formatting.")
filename = input("\nEnter the file name please: ")
while ".txt" not in filename and ".csv" not in filename:
print("\nInvalid extension.")
filename = input("\nEnter the file name please: ")
listtype = input(
"\nEnter str if the list is of string. Enter int if list is of numbers: ")
while listtype not in ["int", "str"]:
print("Invalid")
listtype = input(
"\nEnter str if the list is of string. Enter int if list is of numbers: ")
try:
startarray = importlist(filename, listtype)
except FileNotFoundError:
print("Sorry. No such file. Goodbye")
exit(1)
# Sorting functions
def sort(arr):
sortedarr = []
starttime = time.time()
whichsort = input(
"Enter 1 for bubblesort or 2 for insertion sort 3 for mergesort: ")
while whichsort not in ["1", "2","3"]:
print("Invalid")
whichsort = input(
"Enter 1 for bubblesort or 2 for insertion sort 3 for mergesort: ")
if whichsort == "1":
if listtype == "int":
starttime = time.time()
sortedarr = bubblesort(startarray)
print("Time taken for bubblesort: ", round(
(time.time() - starttime) * 1000, 2), "milliseconds. Comparisons:", sortedarr[1], "Big O: n squared. Omega: n.")
else:
print("Sorry bubble sort only works with integers")
sortedarr=[0,0]
elif whichsort == "2":
if listtype == "int":
starttime = time.time()
sortedarr = insertionsort(startarray)
print("Time taken for insertion sort: ", round(
(time.time() - starttime) * 1000, 2), "milliseconds. Comparisons:", sortedarr[1], "Big O: n squared. Omega: n.")
else:
print("Sorry insertion sort only works with integers")
sortedarr=[0,0]
else:
starttime = time.time()
sortedarr = mergesort(startarray)
print("Time taken for mergesort: ", round(
(time.time() - starttime) * 1000, 2), "milliseconds. Comparisons:", sortedarr[1], "Big O: n log n. Omega: n log n.")
z = input("Enter anything if you want to see the array. Enter nothing if you do not.")
if z == "":
return sortedarr[0]
else:
print(sortedarr[0])
return sortedarr[0]
# Searching functions
def search(arr):
starttime = time.time()
whichsearch = input(
"Enter 1 for linear search or 2 for binary search or 3 for binary tree search: ")
while whichsearch not in ["1", "2", "3"]:
print("Invalid")
whichsearch = input(
"Enter 1 for linear search or 2 for binary search or 3 for binary tree search: ")
if whichsearch == "1":
comparisons = linearsearch(arr, listtype)
elif whichsearch == "2":
print("The list must be sorted first.")
arr = sort(arr)
binsearch(arr, listtype)
else:
btsearch(arr, listtype)
#keep asking for sort/search
choice = "0"
while choice != "3":
choice = input("\nEnter 1 to sort.\nEnter 2 to search.\nEnter 3 to quit: ")
while choice not in ["1", "2", "3"]:
print("Invalid")
choice = input(
"\nEnter 1 to sort.\nEnter 2 to search.\nEnter 3 to quit: ")
if choice == "1":
sort(startarray)
elif choice == "2":
search(startarray)
|
'''
uzatılmış öklidi fonksiyonu ile d hesalıyoruz
Bir sayı hangi sayı ile çarpılırsa totient fonk değerinin modu 1 olur
d*e=1modT
'''
def u_oklid(a, b):
if a == 0:
return (b, 0, 1)
else:
g, y, x = u_oklid(b % a, a)
return (g, x - (b // a) * y, y)
'''
en büyük ortak bölen
'''
def obeb(a, b):
while b != 0:
a, b = b, a % b
return a
'''
numaranın asal sayı olup olmadığı kontrol ediyoruz
'''
def asal_mi(num):
if num == 2:
return True
if num < 2 or num % 2 == 0:
return False
for n in range(3, int(num**0.5)+2, 2):
if num % n == 0:
return False
return True
def anahtar_olustur():
#1.adım p ve q değeri veriyoruz
p,q=61,53
#2.Adım n değerini buluyoruz
n = p*q
#Adım 3 totient fonksiyonu hesaplıyoruz
'''phi(n) = phi(p)*phi(q)
totient fonksiyonu
'''
toti = (p-1) * (q-1)
print("totient fonksiyonu ",toti)
#Adım 4 e yi bulma
'''totient fonk>e>1 ve totient ile aralarında asal bir sayı seçiyoruz'''
e = 151
'''
Yani basitçe de = 1 mod toti denklemini bilinen bir d ve p sayısı için çözmektir.
Başka bir ifadeyle bir sayının bir modda hangi sayıyla çarpılınca 1 sonucunu verdiğini bulmaktır.
'''
d = u_oklid(e, toti)[1]
'''d nin negatif ise onu pozitif yapıyoruz'''
d = d % toti
if(d < 0):
d += toti
#private ve public key olarak gönderiyoruz
return ((e,n),(d,n))
def sifre_coz(ctext,private_key):
'''
m = c^d mod n
'''
try:
key,n = private_key
text = [chr(pow(char,key,n)) for char in ctext]
return "".join(text)
except TypeError as e:
print(e)
def sifrele(text,public_key):
'''
c = m^e mod n
'''
key,n = public_key
ctext = [pow(ord(char),key,n) for char in text]
return ctext
if __name__ == '__main__':
#anahtarları ayarlıyoruz
public_key,private_key = anahtar_olustur()
print("Public Anahtar: ",public_key)
print("Private Anahtar: ",private_key)
smetin = sifrele("enver",public_key)
print("Şifrelenmiş =",smetin)
print(smetin)
cmetin = sifre_coz(smetin, private_key)
print("Çözülmüş =",cmetin)
|
#List comprehensions
squares = [x**2 for x in range(10)]
print(squares)
print([(x, y) for x in [1, 2, 3] for y in [3, 1, 4] if x != y])
#Create a list with values doubled
vec = [-4, -2, 0, 2,4]
print([x*2 for x in vec])
#Filter the -ve numbers from list
print([x for x in vec if x >= 0])
# Call a method on each element of array
freshfruit = ['banana', 'loganberry', 'passion fruit']
print([(x, len(x)) for x in freshfruit])
# List of number and its square
print([(x, x**2) for x in range(1, 10)])
#Flattening multiple lists into one list
vec = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
print([num for elem in vec for num in elem])
|
#car pooling question asked in VArious commapnies
# GOOGLE , AMAZON , UBER , Microsoft
class Solution:
def carPooling(self, trips,capacity):
timestamp = [0] * 1001
for trip in trips:
timestamp[trip[1]] += trip[0]
timestamp[trip[2]] -= trip[0]
used_capacity = 0
for passenger_change in timestamp:
used_capacity += passenger_change
if used_capacity > capacity:
return False
return True
p = Solution()
result = p.carPooling(trips=[[2,1,5],[3,3,7]],capacity=6)
print(result) |
# This Question is asked by uber for sde Role
#Pig Latin
# If string contain aeiou add ma to end
# if constrant remove frist element and add to the end with ma
# add a for every element
class Solution():
def toGoatLatin(self,S):
temp = S.split(" ")
counter = 1
result = []
vowels = ("a","e","i","o","u")
for i in temp:
if i[0].lower() in vowels:
x = i + "ma" + ('a'*counter)
else:
x = i[1:] + i[0] + "ma" + ('a'*counter)
counter += 1
result.append(x)
return " ".join(c for c in result)
p = Solution()
result = p.toGoatLatin("oello my name is Ajeet")
print(result)
|
#You are given an array of k linked-lists lists, each linked-list is sorted in ascending order.
#Merge all the linked-lists into one sorted linked-list and return it.
#Example 1
#Input: lists = [[1,4,5],[1,3,4],[2,6]]
#Output: [1,1,2,3,4,4,5,6]
#Explanation: The linked-lists are:
#[
# 1->4->5,
# 1->3->4,
# 2->6
#]
#merging them into one sorted list:
# output = 1->1->2->3->4->4->5->6
class Linkedlist:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def mergeKLists(self, lists):
self.ans = []
head = value = lists[0]
for l in lists:
while l:
self.ans.append(l.val)
l = l.next
for x in sorted(self.ans):
value.next = Linkedlist(x)
value = value.next
return head.next
p = Linkedlist()
p.mergeKLists([[1,4,5],[1,3,4],[2,6]]) |
# Task: check if Linked List is a Palindrome
class Node(object):
"""Node in a linked list."""
def __init__(self, data):
self.data = data
self.next = None
class LinkedList(object):
"""Linked List using head and tail."""
def __init__(self):
self.head = None
self.tail = None
def append(self, data):
"""Append node with data to end of list."""
new_node = Node(data)
if self.head is None:
self.head = new_node
if self.tail is not None:
# Did list start as empty?
self.tail.next = new_node
self.tail = new_node
def is_palindrome(head):
"""Determine if linked list is a palindrome. Return True if so."""
# PSEUDOCODE:
# need to know if linked list is odd/even using runners
# if fast.next is none, means list is EVEN + slow is on MIDDLE item
# if fast is none, means list is ODD + slow is on MIDDLE item
# as we traverse, need to keep a list of node's DATA
# Even: once slow is on middle (and list filled), use stack by popping off
# last item on list after each check
# Odd: same as even except pop off last item in list before the check
# create runners
slow = head
fast = head
# keep track of letters in first half of the LL
stack = []
# traverse LL until slow in middle
while fast is not None and fast.next is not None:
stack.append(slow.data)
slow = slow.next
fast = fast.next.next
# account for odd number of items in LL
if fast is not None:
slow = slow.next
# compare each letter in 2nd half of list to letters in 1st half
while slow is not None:
if slow.data != stack.pop():
return False
slow = slow.next
return True
|
print("Determina o mdc de dois números n > 0 e m > 0\n")
# leia o valor de n
n = int(input("Digite o valor de n (n > 0): "))
# leia o valor de m
m = int(input("Digite o valor de m (m > 0): "))
# aqui começa o algoritmo de Euclides
anterior = n
atual = m
resto = anterior % atual
while resto != 0:
anterior = atual
atual = resto
resto = anterior % atual
print("MDC(%d,%d)=%d" %(n,m,atual)) |
# Узнайте у пользователя число n.
# Найдите сумму чисел n + nn + nnn.
# Например, пользователь ввёл число 3. Считаем 3 + 33 + 333 = 369.
num = (input("Введите число: "))
n_1 = int(num)
n_2 = int(num + num)
n_3 = int(num + num + num)
rez = n_1 + n_2 + n_3
print(rez)
|
from tkinter import *
import tkinter
from tkinter import ttk
#frame raising function
def raise_frame(frame):
frame.tkraise()
window = Tk()
f1 = Frame(window,bg='#05386B')
f2 = Frame(window,bg='#05386B')
f3 = Frame(window,bg='#05386B')
window.rowconfigure(0,weight=1)
window.columnconfigure(0,weight=1)
for frame in (f1, f2, f3):
frame.grid(row=0, column=0, sticky='news')
#selected fluid data dictionary which will be updated
fld = {"w":0.012,
"pC":45.99 * 10**5,
"tC" :190.6,
"R":8.31}#pressure is in pascal and temp is in K
#frame 1 code
calZV = Button(f1, text='CALCULATE Z AND V',font=("Courier", 16), command=lambda:raise_frame(f2))
calZP = Button(f1, text='CALCULATE Z AND P',font=("Courier", 16), command=lambda:raise_frame(f3))
calZV.place(x=125,y=230)
calZP.place(x=125,y=280)
head = Label(f1, text="CALCULATE Z, MOLAR VOLUME, \nPRESSURE USING PITZER \nSECOND VIRIAL COEFFICIENT ",font=("Courier", 15))
head.place(x=50,y=10)
head.config(height = 6,width=35)
bottom = Label(f1,text= "Project by:\n Himanshu Khadatkar ",font=("Courier", 12))
bottom.place(x=150,y=400)
#frame 2 code
Button(f2, text='HOME PAGE',font=("Courier", 12), command=lambda:raise_frame(f1)).pack(side=BOTTOM)
Button(f2, text='CALCULATE Z AND P',font=("Courier", 12), command=lambda:raise_frame(f3)).pack(side=BOTTOM)
#background and heading
heading = Label(f2, text="CALCULATE Z AND MOLAR VOLUME",font=("Courier", 15))
heading.place(x=80,y=10)
#select fluid
h1 = Label(f2, text="Select Fluid",font=("Courier", 14))
h1.place(x=200,y=50)
#selecting fluid combobox
lb = Label(f2, text=" Fluid ")
lb.place(x=180,y=100)
fluid_d= StringVar()
fluid_data=('Methane','Ethane','Propane','n-Butane','n-Pentane','n-Hexane',
'Isobutane','Methanol','Ethanol','Acetone','Carbon dioxide','Ammonia'
)
fluid_d.set('Methane')
cb=ttk.Combobox(f2, values=fluid_data,state="readonly")
cb.place(x=250, y=100)
cb.current(0)
#sselect units
h1 = Label(f2, text="Select Units",font=("Courier", 14))
h1.place(x=200,y=150)
#pressure units
lbl1=Label(f2, text="Unit Of Pressure to be entered")
lbl1.place(x=60, y=200)
pressureUnits = StringVar()
data1=('Pascal','Barr','MM of Hg','Atm')
pressureUnits.set("Pascal")
cb1=ttk.Combobox(f2, values=data1,state="readonly")
cb1.place(x=300, y=200)
cb1.current(0)
#temperature units
lbl2=Label(f2, text="Unit Of Temperature to be entered")
lbl2.place(x=60, y=230)
TempUnits = StringVar()
data2=('Kelvin','Celsius')
TempUnits.set('kelvin')
cb2=ttk.Combobox(f2, values=data2,state="readonly")
cb2.place(x=300, y=230)
cb2.current(0)
#volume units
lbl3=Label(f2, text="Unit Of Volume to be obtained")
lbl3.place(x=60, y=260)
VolUnits = StringVar()
data3=('cubic meter per mole ','Litre per mole')
VolUnits.set('cubic meter per mole')
cb3=ttk.Combobox(f2, values=data3,state="readonly")
cb3.current(0)
cb3.place(x=300, y=260)
##data entry
h2 = Label(f2, text="Enter Data",font=("Courier", 14))
h2.place(x=200,y=310)
#pressure entry
lb4 = Label(f2, text="Pressure ")
lb4.place(x=60,y=360)
pressure =Entry(f2,textvariable=IntVar())
pressure.place(x=150,y=360)
#temperature entry
lb5 = Label(f2, text="Temperature ")
lb5.place(x=60,y=390)
temperature=Entry(f2,textvariable=IntVar())
temperature.place(x=150,y=390)
#result label
msg1 = Label(f2)
def getOutput():
#updating fld dictionary based on selected fluid
import pandas as pd
fdata = pd.read_csv('fluid_dataset.csv')
temp={}
for i in range(0,fdata.shape[0]):
if(fdata.iloc[i]['fluid']==cb.get()):
temp['w'] =float(fdata.iloc[i]['w'])
temp['tC']=float(fdata.iloc[i]['tC'])
temp['pC']=float(fdata.iloc[i]['pC'])
temp['R'] =float(fdata.iloc[i]['R'])
fld.update(temp)
press=float(pressure.get())
#('Pascal','Barr','MM of Hg','Atm')
if cb1.get()=="Barr":
press = press*100000
elif cb1.get()=="MM of Hg":
press = press*133.322
elif cb1.get()=="Atm":
press = press*101325
temp =float(temperature.get())
#'Kelvin','Celsius'
if cb2.get()=="Celsius":
temp=temp+273.3
if(press!=0 and temp!=0):
if(verifyP(press,temp)):
inst = calculateZV(press,temp)
z = round(inst.calculateZ(),5)
v = inst.calculateV()
#'cubic meter per mole ','Litre per mole'
if cb3.get()=="Litre per mole":
v = v*1000
v = round(v,5)
t = f'Compression factor: {z}\n Molar Volume : {v} '
msg1.config(text=t,font=("Arial", 11))
msg1.place(x=155,y=490)
else:
t='Pitzer corelation for the second virial coefficient will not \n appropriate for the given pressure and temperature'
msg1.config(text=t,font=("Arial", 11))
msg1.place(x=80,y=490)
else:
t='Enter positive values for pressure and temperature '
msg1.config(text=t,font=("Arial", 11))
msg1.place(x=90,y=490)
def verifyP(press,temp):
tr = temp/fld['tC']
pr = press/fld['pC']
if (tr>3):
return True
else:
pmax = 1.983856 + (0.2237026 - 1.983856)/(1 + (tr/1.238929)**10.93594)
if(pr<=pmax):
return True
else:
return False
#results button
results = Button(f2,text="Calculate Z and V",font=("Courier", 14),command=getOutput)
results.place(x=155,y=440)
results['background']='#8EE4AF'
#hover the button
def onEnter(event):
results.config(bg='#CAFAFE')
def onLeave(event):
results.config(bg='#8EE4AF')
results.bind('<Enter>', onEnter)
results.bind('<Leave>',onLeave)
class calculateZV():
def __init__(obj,pressure,temperature):
obj.pressure = pressure
obj.temperature = temperature
def calculateZ(instance):
pR = instance.pressure/fld.get('pC')
tR = instance.temperature/fld.get('tC')
w = fld.get('w')
b0 = 0.083-(0.422/tR**1.6)
b1 = 0.139-(0.172/tR**4.2)
Z0 = 1+b0*pR/tR
Z1 = b1*pR/tR
global Z
Z = Z0 + w*Z1
return Z
def calculateV(instance):
V = (fld.get('R') * Z * instance.temperature)/instance.pressure
return V
#frame 3 code
Button(f3, text='HOME PAGE',font=("Courier", 12), command=lambda:raise_frame(f1)).pack(side=BOTTOM)
Button(f3, text='CALCULATE Z AND VOLUME',font=("Courier", 12), command=lambda:raise_frame(f2)).pack(side=BOTTOM)
#background and heading
heading = Label(f3, text=" CALCULATE Z AND PRESSURE ",font=("Courier", 15))
heading.place(x=80,y=10)
#select fluid
h1 = Label(f3, text="Select Fluid",font=("Courier", 14))
h1.place(x=200,y=50)
#selecting fluid combobox
lb = Label(f3, text=" Fluid ")
lb.place(x=180,y=100)
fluid_d= StringVar()
fluid_data=('Methane','Ethane','Propane','n-Butane','n-Pentane','n-Hexane',
'Isobutane','Methanol','Ethanol','Acetone','Carbon dioxide','Ammonia'
)
fluid_d.set('Methane')
cb=ttk.Combobox(f3, values=fluid_data,state="readonly")
cb.place(x=250, y=100)
cb.current(0)
#sselect units
h1 = Label(f3, text="Select Units",font=("Courier", 14))
h1.place(x=200,y=150)
#volume units
lbl1=Label(f3, text="Unit Of Volume to be entered")
lbl1.place(x=60, y=200)
VolumeUnits = StringVar()
data1=('cubic meter per mole ','Litre per mole')
VolumeUnits.set('cubic meter per mole')
cb1=ttk.Combobox(f3, values=data1,state="readonly")
cb1.place(x=300, y=200)
cb1.current(0)
#temperature units
lbl2=Label(f3, text="Unit Of Temperature to be entered")
lbl2.place(x=60, y=230)
TempUnits = StringVar()
data2=('Kelvin','Celsius')
TempUnits.set('kelvin')
cb2=ttk.Combobox(f3, values=data2,state="readonly")
cb2.place(x=300, y=230)
cb2.current(0)
#pressure units
lbl3=Label(f3, text="Unit Of Pressure to be obtained")
lbl3.place(x=60, y=260)
VolUnits = StringVar()
data3=('Pascal','Barr','MM of Hg','Atm')
VolUnits.set('Pascal')
cb3=ttk.Combobox(f3, values=data3,state="readonly")
cb3.current(0)
cb3.place(x=300, y=260)
##data entry
h2 = Label(f3, text="Enter Data",font=("Courier", 14))
h2.place(x=200,y=310)
#pressure entry
lb4 = Label(f3, text="Volume ")
lb4.place(x=60,y=360)
volume =Entry(f3,textvariable=IntVar())
volume.place(x=150,y=360)
#temperature entry
lb5 = Label(f3, text="Temperature ")
lb5.place(x=60,y=390)
temperature=Entry(f3,textvariable=IntVar())
temperature.place(x=150,y=390)
#result label
msg2 = Label(f3)
def getOutput():
#updating fld dictionary based on selected fluid
import pandas as pd
fdata = pd.read_csv('fluid_dataset.csv')
temp={}
for i in range(0,fdata.shape[0]):
if(fdata.iloc[i]['fluid']==cb.get()):
temp['w'] =float(fdata.iloc[i]['w'])
temp['tC']=float(fdata.iloc[i]['tC'])
temp['pC']=float(fdata.iloc[i]['pC'])
temp['R'] =float(fdata.iloc[i]['R'])
fld.update(temp)
vol=float(volume.get())
#'cubic meter per mole ','Litre per mole'
if cb1.get()=="Litre per mole":
vol = vol*0.001
temp =float(temperature.get())
#'Kelvin','Celsius'
if cb2.get()=="Celsius":
temp=temp+273.3
if(vol!=0 and temp!=0):
if(verifyP(vol,temp)):
inst = calculateZP(vol,temp)
z = round(inst.calculateZ(),5)
p = inst.calculateP()
#('Pascal','Barr','MM of Hg','Atm')
if cb3.get()=="Barr":
p = p*0.00001
elif cb3.get()=="MM of Hg":
p = p*0.00750062
elif cb1.get()=="Atm":
p = p*0.000009869
p = round(p,5)
t = f'Compression factor: {z}\n Pressure : {p} '
msg2.config(text=t,font=("Arial", 11))
msg2.place(x=155,y=490)
else:
t='Pitzer corelation for the second virial coefficient will not \n appropriate for the given pressure and temperature'
msg2.config(text=t,font=("Arial", 11))
msg2.place(x=80,y=490)
else:
t='Enter positive values for Volume and temperature '
msg2.config(text=t,font=("Arial", 11))
msg2.place(x=90,y=490)
def verifyP(vol,temp):
press = (8.314*temp)/(vol)
tr = temp/fld['tC']
pr = press/fld['pC']
if (tr>3):
return True
else:
pmax = 1.983856 + (0.2237026 - 1.983856)/(1 + (tr/1.238929)**10.93594)
if(pr<=pmax):
return True
else:
return False
#results button
results = Button(f3,text="Calculate Z and P",font=("Courier", 14),command=getOutput)
results.place(x=155,y=440)
results['background']='#8EE4AF'
#hover the button
def onEnter(event):
results.config(bg='#CAFAFE')
def onLeave(event):
results.config(bg='#8EE4AF')
results.bind('<Enter>', onEnter)
results.bind('<Leave>',onLeave)
class calculateZP():
def __init__(obj,volume,temperature):
obj.volume = volume
obj.temperature = temperature
def calculateP(instance):
v = instance.volume
t = instance.temperature
tC = fld.get('tC')
tR = t/tC
pC = fld.get('pC')
w = fld.get('w')
b0 = 0.083-(0.422/tR**1.6)
b1 = 0.139-(0.172/tR**4.2)
B = b0 + w*b1
b = B*8.314*tC/pC
p = 8.314*t/(v-b)
return p
def calculateZ(instance):
p = instance.calculateP()
Z = (p * instance.volume)/(instance.temperature*8.314)
return Z
raise_frame(f1)
window.title('Second Virial Corelation for Z V P T')
window.geometry("500x600+100+100")
window.mainloop() |
# Циклический сдвиг влево
# Пример 1
# 1 2 3 4 5
# 2 3 4 5 1
import random as r
n = int(input())
a = [r.randint(-10, 10) for i in range(n)]
print(*a)
t = a[0]
for i in range(n - 1):
a[i] = a[i + 1]
a[-1] = t
print(*a) |
from control import Control
import tkinter as tk
import time
# port = "COM5"
# cont = Control(port)
# These functions use the control class to send data through the com port
def forward(event):
cont.send("1")
def back(event):
cont.send("0")
def leftu(event):
cont.send("3")
def leftd(event):
cont.send("5")
def rightu(event):
cont.send("4")
def rightd(event):
cont.send("4")
def stop(event):
cont.send("!")
def quit_app():
exit()
class Window(tk.Frame):
def __init__(self, master=None):
tk.Frame.__init__(self, master)
self.master = master
self.init_window()
# Creates the buttons on the gui
def init_window(self):
self.master.title("GUI")
self.pack(fill="both", expand=1)
forward_button = tk.Button(self, text="forward")
forward_button.place(relx=0.5, rely=0.45, anchor="center")
forward_button.bind('<ButtonPress-1>', forward)
forward_button.bind('<ButtonRelease-1>', stop)
reverse_button = tk.Button(self, text="reverse")
reverse_button.place(relx=0.5, rely=0.55, anchor="center")
reverse_button.bind('<ButtonPress-1>', back)
reverse_button.bind('<ButtonRelease-1>', stop)
left_button = tk.Button(self, text="front left")
left_button.place(relx=0.38, rely=0.45, anchor="center")
left_button.bind('<ButtonPress-1>', leftu)
left_button.bind('<ButtonRelease-1>', stop)
left_button = tk.Button(self, text="back left")
left_button.place(relx=0.38, rely=0.55, anchor="center")
left_button.bind('<ButtonPress-1>', leftd)
left_button.bind('<ButtonRelease-1>', stop)
right_button = tk.Button(self, text="front right")
right_button.place(relx=0.62, rely=0.45, anchor="center")
right_button.bind('<ButtonPress-1>', rightu)
right_button.bind('<ButtonRelease-1>', stop)
right_button = tk.Button(self, text="back right")
right_button.place(relx=0.62, rely=0.55, anchor="center")
right_button.bind('<ButtonPress-1>', rightd)
right_button.bind('<ButtonRelease-1>', stop)
quit_button = tk.Button(self, text="quit", command=quit_app)
quit_button.place(relx=0.5, rely=0.9, anchor="center")
def main():
root = tk.Tk()
root.geometry("500x500")
root.title("Car Controller")
root.configure(bg='red')
app = Window(root)
root.mainloop()
main()
|
#!user/bin/env python
import string
import keyword
alphas = string.letters + '_'
nums = string.digits
kwlist = keyword.kwlist
print 'Welcome to the Identifier Checker v1.0'
myInput = raw_input('Identifier to test?')
if myInput[0] not in alphas:
print '''invalid:first symbol must be alphabetic'''
else:
for otherChar in myInput[1:]:
if otherChar not in alphas+nums:
print '''invalid:remaining symbols must be alphanumeric'''
break
else:
print "okay as an identifier"
if myInput in kwlist:
print "but it is a kewword!" |
#-*-coding:UTF-8 -*-
class Employee:
'ԱĻ'
empCount = 0
def __ini__(self,name,salary):
self.name = name
self.salary =salary
Employee.empCount += 1
def displayCount(self):
print "Total Employee %d" %Employee.empCount
def displayEmploy(self):
print "Name: " ,self.name,",Salary: ",self.salary
print "Employee.__doc__:",Employee.__doc__
print "Employee.__name__:",Employee.__name__
print "Employee.__module__:",Employee.__module__
print "Employee.__bases__:",Employee.__bases__
print "Employee.__dict__:",Employee.__dict__ |
class Stack:
def __init__(self):
self.stack = []
def push(self, item): # положить элемент в стек
self.stack.append(item)
def isEmpty(self): # вернуть True, если стек пуст, иначе вернуть False
if self.stack == []:
return True
return False
def pop(self): # удалить элемент из стека и вернуть его значение
if not self.isEmpty():
return self.stack.pop()
return None
def peek(self): # вернуть значение последнего элемента стека (не удаляя его)
if not self.isEmpty():
return self.stack[-1]
return None
class MyQueue:
def __init__(self): # !!!Вероятно, ошибка вот здесь, потому что TypeError: enqueue() missing 1 required positional argument: 'item'
self.stack_in = Stack()
self.stack_out = Stack()
def move(self): #перемещает из первого стека во второй
while self.stack_in.peek():
self.stack_out.push(self.stack_in.pop())
print(self.stack_out.stack)
def enqueue(self, item): # положить элемент в очередь
self.stack_in.push(item)
def dequeue(self): # удалить элемент из очереди и вернуть его значение
if self.stack_out.isEmpty():
if self.stack_in.isEmpty():
return None
self.move()
return self.stack_out.pop()
return self.stack_out.pop()
def peek(self): # вернуть значение первого элемента очереди (не удаляя его)
if self.stack_out.isEmpty():
if self.stack_in.isEmpty():
return None
self.move()
return self.stack_out.peek()
return self.stack_out.peek()
def isEmpty(self): # вернуть True, если стек пуст, иначе вернуть False
if self.stack_in.isEmpty() and self.stack_out.isEmpty():
return True
return False
queue = MyQueue()
queue.enqueue(1)
queue.enqueue(2)
queue.enqueue(3)
queue.enqueue(4)
|
# Módulo criado para o exercício 107.
def aumentar(valor, taxa):
'''
=> Função que calcula um valor com aumento.
:param valor: Valor informado pelo usuário.
:param taxa: Taxa de aumento (Ex.: Para calcular um aumento de 10%, digitar 10.
:return: Retorna o valor acrescido do aumento.
'''
aumento = valor + (valor * (taxa / 100))
return f"Com aumento de {taxa}%, temos R${aumento}"
def diminuir(valor, taxa):
'''
=> Função que calcula um valor com desconto.
:param valor: Valor informado pelo usuário.
:param taxa: Taxa de desconto (Ex.: Para calcular um desconto de 10%, digitar 10.
:return: Retorna o valor com o desconto.
'''
desconto = valor - (valor * (taxa / 100))
return f"Com desconto de {taxa}%, temos R${desconto}"
def dobro(valor):
'''
=> Função que calcula o dobro de um valor.
:param valor: Valor a ser dobrado.
:return: Retorna o dobro do valor informado
'''
return f"O dobro de R${valor} é R${valor * 2}"
def metade(valor):
'''
=> Função que calcula a metade de um valor.
:param valor: Valor a ser dividido.
:return: Retorna a metade do valor informado
'''
return f"A metade de R${valor} é R${valor / 2}"
|
# Faça um programa que leia o peso de cinco pessoas. No final, mostre qual
# foi o maior e o menor peso lidos.
maior = 0
menor = 0
for pessoa in range(1, 6):
peso = float(input(f"Digite o peso da {pessoa}ª pessoa (kg): "))
if pessoa == 1:
maior = peso
menor = peso
else:
if peso > maior:
maior = peso
if peso < menor:
menor = peso
print(f"O maior peso lido foi: {maior}kg")
print(f"O menor peso lido foi: {menor}kg")
|
# Crie um programa que leia dois valores e mostre um menu na tela:
# [ 1 ] somar
# [ 2 ] multiplicar
# [ 3 ] maior
# [ 4 ] novos números
# [ 5 ] sair do programa
# Seu programa deverá realizar a operação solicitada em cada caso.
from time import sleep
num_01 = int(input("Digite o primeiro número: "))
num_02 = int(input("Digite o segundo valor: "))
opcao = 0
while opcao != 5:
print(f"\nVocê digitou os números {num_01} e {num_02}.\nO que deseja fazer com eles?")
print('''[ 1 ] Somar
[ 2 ] Multiplicar
[ 3 ] Maior
[ 4 ] Digitar novos números
[ 5 ] Sair do programa''')
opcao = int(input("\033[1mDigite a opção desejada: \033[m"))
if opcao == 1:
print(f"{num_01} + {num_02} = {num_01 + num_02}")
elif opcao == 2:
print(f"{num_01} x {num_02} = {num_01 * num_02}")
elif opcao == 3:
if num_01 > num_02:
print(f"{num_01} é maior que {num_02}.")
else:
print(f"{num_02} é maior que {num_01}.")
elif opcao == 4:
print("\nDigite dois novos números. ")
num_01 = int(input("Digite o primeiro número: "))
num_02 = int(input("Digite o segundo valor: "))
elif opcao == 5:
print("Finalizando...")
sleep(2)
else:
print("\nOpção inválida. ")
num_01 = int(input("Digite o primeiro número: "))
num_02 = int(input("Digite o segundo valor: "))
print("Você saiu do programa.")
|
# Escreva um programa que leia um valor em metros e o exiba convertido em centímetros e milímetros.
m = float(input("Digite o valor em metros: "))
dm = m * 10
cm = m * 100
mm = m * 1000
dam = m / 10
hm = m / 100
km = m / 1000
print(f"{m} m equivale a:\n{dm} dm\n{cm} cm\n{mm} mm\n{dam} dam\n{hm} hm\n{km} km")
|
# Escreva um programa em Python que leia um número inteiro qualquer e peça
# para o usuário escolher qual será a base de conversão: 1 para binário, 2
# para octal e 3 para hexadecimal.
print("\033[7mBem vindo ao conversor de bases numéricas!\033[m")
num = int(input("Digite um número: "))
print('''Escolha uma opção:
1 - Para converter o número para BINÁRIO
2 - Para converter o número para OCTAL
3 - Para converter o número para HEXADECIMAL''')
opcao = int(input("Digite a opção escolhida: "))
if opcao == 1:
print(f"O número {num} em BINÁRIO é: {bin(num)[2:]}")
elif opcao == 2:
print(f"O número {num} em OCTAL é: {oct(num)[2:]}")
elif opcao == 3:
print(f"O número {num} em HEXADECIMAL é: {hex(num)[2:]}")
else:
print("Opção inválida. Tente novamente.")
|
# Faça um programa que tenha uma função chamada contador(), que receba
# três parâmetros: início, fim e passo. Seu programa tem que realizar
# três contagens através da função criada:
# a) de 1 até 10, de 1 em 1
# b) de 10 até 0, de 2 em 2
# c) uma contagem personalizada
from time import sleep
def contador(inicio, fim, passo):
sleep(2.5)
if passo == 0:
passo = 1
if inicio < fim:
if passo < 0:
passo = -(passo)
for num in range(inicio, fim + 1, passo):
sleep(.5)
print(f"{num}", end=" ")
print("FIM!")
else:
if passo > 0:
passo = -(passo)
for num in range(inicio, fim - 1, passo):
sleep(.5)
print(f"{num}", end=" ")
print("FIM!")
def escreva(string):
tamanho = len(string)
print("-" * tamanho)
print(string)
print("-" * len(string))
escreva("Contagem de 1 a 10, de 1 em 1:")
contador(1, 10, 1)
sleep(1)
escreva("Contagem de 10 a 0, de 2 em 2:")
contador(10, 0, -2)
sleep(1)
print("\nAgora é a sua vez de personalizar a contagem: ")
i = int(input("Início: "))
f = int(input("Fim: "))
p = int(input("Passo: "))
escreva(f"Contagem de {i} a {f}, de {p} em {p}:")
contador(i, f, p)
|
# Melhore o DESAFIO 61, perguntando para o usuário se ele quer mostrar
# mais alguns termos. O programa encerrará quando ele disser que quer
# mostrar 0 termos.
primeiro = int(input("\033[1mDigite o primeiro termo da PA: \033[m"))
razao = int(input("\033[1mDigite o valor da razão: \033[m"))
termo_init = 1
while termo_init < 11: # Enquanto o número de termos for menor que 11 (para mostrar até o décimo termo)
print(primeiro, end=" ") # Imprime o valor do primeiro termo
primeiro += razao # Adiciona o valor da razão ao termo
termo_init += 1 # Adiciona 1 ao contador de termos
termo_add = int(input("\n\033[1mQuantos termos você deseja ver a mais? \033[m"))
termo_init = 1
while termo_add != 0:
termo_init = 1
while termo_init < termo_add + 1:
print(primeiro, end=" ")
primeiro += razao
termo_init += 1
termo_add = int(input("\n\033[1mQuantos termos você deseja ver a mais? \033[m"))
print("\033[1mFIM\033[m")
|
# Aprimore o desafio 93 para que ele funcione com vários jogadores,
# incluindo um sistema de visualização de detalhes do aproveitamento
# de cada jogador.
from time import sleep
time = list()
while True:
i = 0
gols = []
jogador = {"nome": str(input("\nNome do jogador: ")).strip().upper(),
"partidas": int(input("Nº de partidas: "))}
for partida in range(jogador["partidas"]):
gols.append(int(input(f"- Nº de gols na {partida + 1}ª partida: ")))
jogador["gols/partida"] = gols
jogador["total"] = sum(gols)
print("=-" * 50)
print(jogador)
print("=-" * 50)
print(f'O jogador {jogador["nome"]} jogou {jogador["partidas"]} partidas.')
for partida in range(jogador["partidas"]):
if jogador["gols/partida"][i] == 1:
print(f' => Na {partida + 1}ª partida fez {jogador["gols/partida"][i]} gol.')
else:
print(f' => Na {partida + 1}ª partida fez {jogador["gols/partida"][i]} gols.')
i += 1
print(f'Total de gols no campeonato: {jogador["total"]}')
time.append(jogador.copy())
jogador.clear()
continuar = str(input("\n- Continuar? [S ou N]: ")).strip().upper()[0]
while continuar not in "SsNn":
print("Opção inválida.")
continuar = str(input("\n- Continuar? [S ou N]: ")).strip().upper()[0]
if continuar in "Nn":
break
print()
print("-" * 75)
print(f"{'Nº':<4}{'Nome':<10}{'Gols/partida':<20}{'Total de gols':<20}")
print("-" * 75)
for i, v in enumerate(time):
print(f"{i + 1:<4}{v['nome']:<10}{str(v['gols/partida']):<20}{str(v['total']):<20}")
print("-" * 75)
codigo = int(input("=> Digite o nº do jogador para ver seu desempenho (999 encerra o programa): "))
for i, v in enumerate(time):
while codigo == (i + 1):
print(f'\nO jogador {v["nome"]} jogou {v["partidas"]} partidas.')
for p, gols in enumerate(v['gols/partida']):
print(f" => Total de gols na {p + 1}ª partida: {gols}")
print(f'Total de gols no campeonato: {v["total"]}')
print("-" * 75)
codigo = int(input("\n=> Digite o nº do jogador para ver seu desempenho (999 encerra o programa): "))
while codigo > len(time):
print("Opção inválida.")
codigo = int(input("\n=> Digite o nº do jogador para ver seu desempenho (999 encerra o programa): "))
if codigo == 999:
print("\nSaindo...")
sleep(2)
break
|
# Desenvolva um programa que leia o nome, idade e sexo de 4 pessoas.
# No final do programa, mostre: a média de idade do grupo, qual é o nome
# do homem mais velho e quantas mulheres têm menos de 20 anos.
soma_idades = 0
velho = 0
novo = 0
menos_20 = 0
nome_velho = ""
nome_novo = ""
for pessoa in range(1, 5):
print(f"\033[1mDados da {pessoa}ª pessoa\033[m")
nome = str(input("Nome: "))
idade = int(input("Idade: "))
sexo = str(input("Sexo (M/F): ")).strip().upper()
print("*" * 20)
soma_idades += idade # Para verificar a média de idades
# Verificar quem é o homem mais novo e quem é o mais velho
if pessoa == 1:
velho = idade
novo = idade
else:
if idade > velho and sexo == "M":
velho = idade
nome_velho = nome
if idade < novo and sexo == "M":
novo = idade
nome_novo = nome
# Verificar quantas mulheres têm menos de 20 anos
if sexo == "F" and idade < 20:
menos_20 += 1
print(f"A média de idade desse grupo é de {soma_idades / 4:.1f} anos.")
print(f"{nome_novo} é o homem mais novo e tem {novo} anos.")
print(f"{nome_velho} é o homem mais velho e tem {velho} anos.")
print(f"Número de mulheres com menos de 20 anos: {menos_20}")
|
# Reescreva a função leiaInt() que fizemos no desafio 104, incluindo agora a
# possibilidade da digitação de um número de tipo inválido. Aproveite e crie
# também uma função leiaFloat() com a mesma funcionalidade.
def leiaInt(valor):
while True:
try:
inteiro = int(input(valor))
except:
print("\033[31mErro => Você não digitou um \033[1;31mint\033[m \033[m")
else:
return inteiro
def leiaFloat(valor):
while True:
try:
valor_float = float(input(valor))
except:
print("\033[31mErro => Você não digitou um \033[1;31mfloat\033[m \033[m")
else:
return valor_float
n1 = leiaInt('Digite um valor do tipo \033[33mint\033[m: ')
n2 = leiaFloat('Digite um valor do tipo \033[34mfloat\033[m: ')
print(f'=> {n1} é \033[33mint\033[m')
print(f'=> {n2} é \033[34mfloat\033[m')
|
# Faça um programa que leia nome e peso de várias pessoas,
# guardando tudo em uma lista. No final, mostre:
# A) Quantas pessoas foram cadastradas.
# B) Uma listagem com as pessoas mais pesadas.
# C) Uma listagem com as pessoas mais leves.
pessoas = list()
dados = list()
maior = menor = 0
while True:
dados.append(str(input("Nome: ")))
dados.append(float(input("Peso: ")))
if len(pessoas) == 0:
maior = menor = dados[1]
else:
if dados[1] > maior:
maior = dados[1]
if dados[1] < menor:
menor = dados[1]
pessoas.append(dados[:])
dados.clear()
continuar = str(input("- Continuar? [S/N]: ")).strip().upper()[0]
while continuar not in "SsNn":
continuar = str(input("- Opção inválida. Digite S ou N: "))
if continuar in "Nn":
break
print(f"Total de pessoas cadastradas: {len(pessoas)}")
print(f"Maior peso: {maior}kg")
for lista in pessoas:
if lista[1] == maior:
print(f"- {lista[0]}")
print(f"Menor peso: {menor}kg")
for lista in pessoas:
if lista[1] == menor:
print(f"- {lista[0]}")
|
# Faça um programa que mostre na tela uma contagem regressiva para o estouro
# de fogos de artifício, indo de 10 até 0, com uma pausa de 1 segundo entre eles.
from time import sleep
for cont in range (10, 0, -1):
print(cont)
sleep(1)
print("Feliz Ano Novo!") |
# Um professor quer sortear um dos seus quatro alunos para apagar o quadro.
# Faça um programa que ajude ele, lendo o nome dos alunos e escrevendo na tela
# o nome do escolhido.
from random import choice
print("Digite o nome dos alunos:")
aluno01 = str(input("Aluno 1: "))
aluno02 = str(input("Aluno 2: "))
aluno03 = str(input("Aluno 3: "))
aluno04 = str(input("Aluno 4: "))
print(f"O aluno sorteado foi: {choice([aluno01, aluno02, aluno03, aluno04])}.")
|
# Escreva um programa que pergunte a quantidade de Km percorridos por um carro
# alugado e a quantidade de dias pelos quais ele foi alugado. Calcule o preço a
# pagar, sabendo que o carro custa R$60 por dia e R$0,15 por Km rodado.
print("Vamos calcular o preço do aluguel do veículo.")
km = float(input("Digite a quantidade de quilômetros percorridos: "))
dias = float(input("Digite o número de dias do aluguel: "))
print(f"Valor a pagar = R${(60 * dias) + (0.15 * km):.2f}")
|
from typing import Dict, List
def get_student_marks() -> List[float]:
n = int(input())
student_marks: Dict[str, List[float]] = {}
for _ in range(n):
name, *line = input().split()
student_marks[name] = list(map(float, line))
query_name: str = input().strip()
return student_marks[query_name]
def calculate_student_average(marks: List[float]) -> str:
average: float = sum(marks) / len(marks)
return '{:.2f}'.format(average)
def main() -> None:
marks = get_student_marks()
average = calculate_student_average(marks)
print(average)
if __name__ == '__main__':
main() |
# -*- coding: UTF-8 –*-
# 上面这一行是python头文件的声明
# 缺省情况下程序需要用ascii码书写,但如果其中写中文的话,python解释器会报错
from scipy.misc import imread, imresize
import imageio
from PIL import Image
import numpy
'''
直接使用pip安装misc会报错 ImportError:cannot import name 'imread' from 'scipy.misc'
原因在于包的版本问题,新版本的scipy.misc没有这一个方法
为了对照文档,我们卸载并重新安装:pip3 install scipy==1.2.0
但是依然无法解决问题,发现是我们下错版本了,要用1.0的才行,不过我们不会管这个问题了,
因为我们使用imageio和PIL来作为解决方案,详见我的个人博客
'''
# Read an JPEG image into a numpy array
img = imageio.imread('assets/cat.jpg')
print(img.dtype, img.shape) # Prints "uint8 (400, 248, 3)"
# We can tint the image by scaling each of the color channels
# by a different scalar constant. The image has shape (400, 248, 3);
# we multiply it by the array [1, 0.95, 0.9] of shape (3,);
# numpy broadcasting means that this leaves the red channel unchanged,
# and multiplies the green and blue channels by 0.95 and 0.9
# respectively.
img_tinted = img * [1, 0.95, 0.9]
# Resize the tinted image to be 300 by 300 pixels.
#img_tinted = imresize(img_tinted, (300, 300))
img_tinted = numpy.array(Image.fromarray(img).resize((300,300)))
#成功将图片保存
# Write the tinted image back to disk
imageio.imwrite('assets/cat_tinted.jpg', img_tinted)
|
import socket
s = socket.socket()
s.connect(("localhost", 9999))
validacion=False
# comprueba si el email es valido
def comprobarEmail(email):
comprobacion=False
if "@" in email:
nuevo_email=email.split('@')
resto=nuevo_email[1]
if "." in resto:
comprobacion=True
return comprobacion
def menu(correoC):
while(True):
print("1.(Listar competiciones)")
print("2.(Inscribir grupo)")
print("3.(Mostrar preguntas)")
print("4.(Enviar respuesta)")
print("5.(Cerrar sesion): ")
opcion=int(input("Seleccione una opcion: ").strip())
# comprueba la opcion que ha elegido el usuario
if(opcion==1):
s.send("L".encode())
nombre=input("Introduce el nombre del grupo: ")
s.send(nombre.encode())
print("Listando Competiciones...")
competiciones=(s.recv(1024).decode()).split("|")
for linea in competiciones:
print(linea)
elif(opcion==2):
# envia la opcion
s.send("I".encode())
competiciones=s.recv(1024).decode()
nombre=input("introduce el nombre del grupo: ").strip()
nombre+=";"
# concatena con el nombre del grupo el correo del usuario conectado
nombre += (correoC+":")
num_participantes=0
# mientras que no se hayan introducido a todos los integrantes sigue el bucle
while(num_participantes<2):
correo=input("Introduce el correo de los demas participantes: ").strip()
# comprueba que el email introducido sea valido
if(comprobarEmail(correo)):
# si es el ultimo correo termina en ;
if(num_participantes==1):
nombre+=(correo+";")
# si no termina en :
else:
nombre+=(correo+":")
num_participantes +=1
else:
print("Correo no valido")
while(True):
cont=0
compe=competiciones.split("-")
print (compe)
con=0
for linea in compe:
if( not con==(len(compe)-1)):
datos=linea.split(";")
print(datos)
mostrar=datos[0]+" Hora de inicio: "+datos[1]+" "+datos[2]
print(str(cont)+" = "+mostrar)
cont +=1
con+=1
inscribir=int(input("Elige una opcion: ").strip())
if(inscribir>=len(competiciones) or inscribir < 0):
print("Dicha competicion no existe")
else:
nombre+=str(inscribir)+";"
break
s.send(nombre.encode())
print("enviando datos...")
# envia la informacion y espera respuesta
s.send(nombre.encode())
# divide la respuesta
respuesta=s.recv(1024).decode().split(";")
tipo=respuesta[0]
cadena=respuesta[1]
# mira si se ha podido realizar la opcion o no, e informa de ello
if (tipo == 'A'):
print (cadena)
print(s.recv(1024).decode())
else:
print (cadena)
elif(opcion==3):
s.send("M".encode())
#Vemos si puede entrar en la competicion
entrar=s.recv(1024).decode()
if(entrar=="entra"):
#Si entra mandamos todas las preguntas
preguntas=s.recv(1024).decode()
print(preguntas)
elif(opcion==4):
s.send("E".encode())
pregunt=s.recv(1024).decode()
selecPre = input(pregunt)
s.send(selecPre.encode())
pregunta=s.recv(1024).decode()
if(pregunta.split(";")[0]=="FF"):
print("Porfavor seleccione una respuesta que no este respondida")
else:
print(pregunta)
opciones=s.recv(1024).decode()
continuar=True
while(continuar):
print(opciones)
# print("Seleccione una opcion 1 2 3 ")
numPre= input("Seleccione una opcion 1 2 3 ")
if(int(numPre)<=3):
s.send(numPre.encode())
continuar=False
else:
print("Solucion incorrecta, por favor poner solo 1, 2 o 3")
elif(opcion==5):
s.send("C".encode())
print("Cerrando Sesion...")
break
else:
print("Opcion no valida")
correoC=""
while(not validacion):
opcion=int(input("Seleccione una accion: 1.(Iniciar Sesion) 2.(Registrar una cuenta nueva) 3.(salir): ").strip())
# comprueba el tipo de opcion que ha escogido el cliente
if ( opcion==1):
correo=input("Introduzca una direccion de correo: ").strip()
# si el correo es valido lo envia al servidor esperando respuesta
if (comprobarEmail(correo)):
s.send(("I;"+correo).encode())
respuesta=s.recv(1024).decode()
dato=respuesta.split(";")
tipo=dato[0]
cadena=dato[1]
# si la respuesta es afirmativa, sale del bucle, imprime el mensaje y guarda el correo
if(tipo=="A"):
validacion=True
correoC = correo
print(cadena)
menu(correoC)
break
else:
print(cadena)
else:
print("Correo no valido")
elif( opcion==2):
correo=input("Introduzca una direccion de correo: ").strip()
# si el correo es valido lo envia al servidor y espera respuesta
if (comprobarEmail(correo)):
s.send(("R;"+correo).encode())
respuesta=s.recv(1024).decode()
dato=respuesta.split(";")
tipo=dato[0]
cadena=dato[1]
# si la respuesta es afirmativa, vuelve a mostrar el menu por si quiere registrar a otro usuario o iniciar sesion
if(tipo=='A'):
print(cadena)
else:
print(cadena)
else:
print("Correo no valido")
# si quiere salir, envia el mensaje al servidor y cierra conexion
elif(opcion==3):
s.send("S; ".encode())
s.close()
break
# si la opcion no esta entre las esperadas muestra el mensaje
else:
print("La opcion elegida no es correcta")
# mientras que el cliente no quiera salir muestra el menu
# opcion=s.recv(1024).decode()
# fin_partida=True
# while fin_partida:
# letra = input("Letra a buscar >> ")
# s.send(letra.encode())
# existe=s.recv(1024).decode()
# if(existe=='s'):
# print("La letra "+letra+" existe en la palabra.")
# else:
# print("La letra "+letra+" no existe en la palabra.")
# datos=s.recv(1024).decode().split(";")
# oculta=datos[0]
# intentos=int(datos[1])
# mensaje=datos[2]
# palabra=datos[3]
# print("Palabra: "+oculta)
# print("Intentos: "+str(6-int(intentos)))
# if(mensaje=='G'):
# print("Has ganado la partida en "+str(6-int(intentos))+" intentos. La palabra era "+palabra)
# fin_partida=False
# elif (intentos==0):
# print("Has perdido la partida. La palabra era "+palabra)
# fin_partida=False
# s.close()
|
import random
def strong():
a = random.randint(20, 40)
s = ''
print(a)
for i in range(1, a):
aa = random.randint(0, 2)
aaa = random.randint(1, 100)
c = random.choice("aertuiopqsdfghjklmcvbn")
c2 = random.choice("aertuizyxopqsdfghjklmcvbn")
if aa == 0:
if aaa > a:
i = aaa-a
else:
i = a-aaa
s = s+c + c2 + str(i)
else:
s += c+c2
print(s)
def medium():
a = random.randint(12, 20)
s = ''
print(a)
for i in range(1, a):
aa = random.randint(0, 2)
aaa = random.randint(1, 50)
c = random.choice("aertuiopqsdfghjklmcvbn")
if aa == 0:
if aaa > a:
i = aaa - a
else:
i = a - aaa
s = s + c + str(i)
else:
s += c
print(s)
def weak():
a = random.randint(6, 10)
s = ''
print(a)
for i in range(1, a):
aa = random.randint(0, 2)
aaa = random.randint(1, 20)
c = random.choice("aertuiopqsdfghjklmcvbn")
if aa == 0:
if aaa > a:
i = aaa - a
else:
i = a - aaa
s = s + c + str(i)
else:
s += c
print(s)
a = input("Strong, Medium or a Weak Password")
if a =="strong":
strong()
elif a=="medium":
medium()
elif a=="weak":
weak()
|
from decimal import DivisionByZero
from sys import exc_info
from traceback import print_exc, print_exception
def main():
print("Learning Exceptions")
'''
Try can be with catch and multi catch
'''
try:
x = 5/0
# x = int("potato")
'''
If I purposefully raise an exception in the try block unconditionally then in that case,
the else block will never be executed which is understandable since
the try block is always going raise and exception
'''
# raise BaseException("Hello this is a exception of type base")
except ValueError as error:
print("Error in the value")
except DivisionByZero as e:
'''
Since I come from a Java Background, I understand why this is an okay way if not better than
the one below this block
'''
print(f'{e.args} {print_exception()}')
except (Exception, BaseException) as e:
'''
This block depicts how I can catch multiple exceptions in a single except block
'''
except:
'''
For when we don't know what error is going to be thrown by the logical block.
This is considered a bad practice since this will usually catch almost all the errors and
exceptions that we may not want to catch at all.
'''
print(exc_info()[0])
else:
'''
This block is actually executed only when there is no exception
'''
print('Hooray! My program executed successfully')
finally:
print("This block is exected irrespective of what exception is thrown from above")
if __name__ == "__main__":
main() |
def add(num1: float = 1, num2: float = 0):
# A function's doc string will always be inside it rather than on top of it
'''
This function will add the two numbers passed to it
'''
return num1 + num2
def subtract(num1: float = 1, num2: float = 0):
return num1 - num2
def multiply(num1: float = 2, num2: float = 0):
return num1 * num2
def divide(num1: float = 0, num2: float = 0):
return num1 / num2
def test_passing_function_as_arguments(funct1, funct2):
print(funct1(1,2))
print(funct2(1,3))
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
print(add(num1, num2))
print(subtract(num1, num2))
print(multiply(num1, num2))
print(divide(num1, num2))
# Do not pass any value to the function here
print(add())
# Pass the value to specific parameter
print(add(num2=45))
# Named arguments for function, due to which order of the parameters passed doesn't matter
print(add(num2=55, num1= 5))
# Print the docstring for a function
# help(add)
test_passing_function_as_arguments(add, subtract) # We can pass functions to another function for execution
# We can assign a function to another variable and then call it using that since functions
# in python are essentially objects
# https://medium.com/python-pandemonium/function-as-objects-in-python-d5215e6d1b0d
renamed_add_function = add
print(renamed_add_function(85, 10))
# In python, immutable objects like list are pass by reference when passed to a function
# Values like integer and string are immutable and hence, are passed by value
def passByValue(randomNumber):
randomNumber = 15
print(randomNumber)
return
def passByReference(listOfNames):
listOfNames[0] = "Bunny"
print(f"The list of names in reference is {listOfNames}")
return
# Variable length argument list. They are always pass by reference
# Variable length arguments are in essence tuples.
# Traditionally preferred to be called args rather than any other name.
# This is for the sake of convention
def multiArgFunc(*parameter_list):
print(type(parameter_list), parameter_list)
parameter_list[0][0] = 15
# If the parameter_list is passed as independent values, then in that case,
# the values in the tuple will not be changeable if those are primitives only
# if they are a mix then the ones that are mutable like list and dictionary
# will be updated if one tries to change it in all other cases it will throw error
# parameter_list[0] = 15
return
# Here the notation ** indicates that the argument is a dictionary
# Standards specify that if we want to use a dictionary as an argument,
# then in that case we need to ideally name it as kwargs indicating that it
# is a dictionary
def key_word_args_func(**kwargs):
for k in kwargs:
print("The capital of {} is {}".format(k, kwargs[k]))
return
def main():
number = 11
print(f"The value of 'number' is {number}")
passByValue(number)
print(f"The value of 'number' has not changed and is {number}")
listOfNames = ["Tortoise", "Rabbit", "Horse"]
print(f"The list of names before passing around is {listOfNames}")
passByReference(listOfNames)
print(f"The list of names post passing around is {listOfNames}")
one = 1
two = 2
three = 3
simple_Array = [one, two, three]
multiArgFunc(simple_Array, 15)
# To pass the entire list as an argument, simply pass it using '*'
# multiArgFunc(*simple_Array)
# The above will lead to the value turning to be immutable
print(f"Value of simple_Array post call {simple_Array}")
# kwargs function
dic = dict(India = "Delhi", China = "Beijing", Britain = "London")
key_word_args_func(**dic)
return
# Python script is read from top to bottom, so any function that needs to be called,
# needs to be defined before the statement for it's call appears in the script.
if __name__ == "__main__":
'''
This check is similar to how main function behaves in many of the other languages
But since python is a scripting language, it doesn't really have a main function or
a so called starting point of execution
If a file is not in a module or imported in a module, then the __name__ will always
return __main__ indicating that it is either the first file that was executed
or it was the only file that was executed
'''
main()
# All functions in python return a value. When no specific value is returned,
# The special None value is returned as seen below
print(key_word_args_func())
|
class ShippingOperator:
def __init__(self, shipping_network_data):
# basic data structures
self.shipping_time = dict() # (<port-a>, <port-b>) -> <number-of-traveling-days>
self.shipping_graph = dict() # <port-a> -> <port-b>
for route in shipping_network_data:
self.shipping_time[route[:2]] = route[2]
try:
self.shipping_graph[route[0]].add(route[1])
except:
self.shipping_graph[route[0]] = set([route[1]])
# memoization data structures
self.routes_le_stops = dict() # (<port-a>, <port-b>, <max-stops> + 1) -> <number-of-routes>
self.routes_le_days = dict() # (<port-a>, <port-b>, <max-days>) -> <number-of-routes>
# get the time for direct route of a sequence of ports
def get_journey_time(self, *journey):
total_days = 0
for i in xrange(len(journey)-1):
try:
total_days += self.shipping_time[journey[i:i+2]]
except:
return "Journey %s is invalid because there is no direct connection from %s to %s" \
% (journey, journey[i], journey[i+1])
return total_days
# find the time of the shortest journey
def find_shortest_journey_time(self, port_a, port_b):
visited = set()
eventualy_shortest_time = {port_a: 0}
curr_port = port_a
while curr_port != port_b:
visited.add(curr_port)
curr_time = eventualy_shortest_time[curr_port]
del eventualy_shortest_time[curr_port]
if curr_port in self.shipping_graph:
ports_to_go = self.shipping_graph[curr_port]
else:
ports_to_go = []
for port in ports_to_go:
if port in visited:
continue
port_time = curr_time + self.shipping_time[(curr_port, port)]
if port not in eventualy_shortest_time \
or eventualy_shortest_time[port] > port_time:
eventualy_shortest_time[port] = port_time
if len(eventualy_shortest_time) == 0:
return "there is no connection from %s to %s" % (port_a, port_b)
curr_port = min(eventualy_shortest_time, key = lambda p: eventualy_shortest_time[p])
return eventualy_shortest_time[port_b]
# find the number of routes from port_a to port_b with no more stops than max_stops
# port_a in the beginning and port_b in the end are not counted as stops
# If port_a and port_b are the same then it counts the route of going nowhere
def count_routes_le_stops(self, port_a, port_b, max_stops):
route_limit = max_stops + 1
direct_distance = lambda a, b: 1
memoization = self.routes_le_stops
return self._count_routes(port_a, port_b, route_limit, direct_distance, memoization)
# find the number of routes from port_a to port_b with exactly a number of stops
def count_routes_eq_stops(self, port_a, port_b, exact_stops):
return self.count_routes_le_stops(port_a, port_b, exact_stops) - \
self.count_routes_le_stops(port_a, port_b, exact_stops-1)
# find the number of routes from port_a to port_b with exactly a number of days
def count_routes_le_days(self, port_a, port_b, max_days):
route_limit = max_days
direct_distance = lambda a, b: self.shipping_time[(a, b)]
memoization = self.routes_le_days
return self._count_routes(port_a, port_b, route_limit, direct_distance, memoization)
def _count_routes(self, port_a, port_b, route_limit, direct_distance, memoization):
if route_limit < 0:
return 0
if (port_a, port_b, route_limit) in memoization:
return memoization[(port_a, port_b, route_limit)]
elif port_a == port_b:
memoization[(port_a, port_b, route_limit)] = 1
else:
memoization[(port_a, port_b, route_limit)] = 0
if route_limit == 0:
return memoization[(port_a, port_b, route_limit)]
if port_a in self.shipping_graph:
ports_to_go = self.shipping_graph[port_a]
else:
ports_to_go = []
for port in ports_to_go:
d = direct_distance(port_a, port)
memoization[(port_a, port_b, route_limit)] += \
self._count_routes(port, port_b, route_limit - d, direct_distance, memoization)
return memoization[(port_a, port_b, route_limit)]
|
# key value pair
# keyword - dict
dict1 = { 'name' : 'ad', 'age' :2}
print('dictionary dict1 -',dict1)
#get specific value from dict
print('get the value of the name key from dict1 -',dict1['name'])
# create new item in dictionary
dict1['address'] = 'address1'
print('updated dictionary dict1 -',dict1)
#get list of keys
print('keys of the dict1 -', dict1.keys())
#get list of values
print('values of the dict1 -',dict1.values())
# = assignment assigns the ref not the value - shallow copy
dict2 = dict1
print('dictionary dict2 -', dict2)
print('compare dictionaries dict1 and dict2 -' , dict2 == dict1)
# modify dict1 - but it updates in dict2 as well
dict1['age'] = 1000
print('modified dict1 - ', dict1)
print('through ref dict2 also gets changed based on dict1 - ', dict2)
print('compare again the dictionaries dict1 and dict2 -' , dict2 == dict1) |
#从视频零基础学习爬虫写的
#用的是 suop获取的图片地址
import requests,urllib.request
from bs4 import BeautifulSoup
url = 'http://tieba.baidu.com/p/5149504613?pn=1'
url2 = 'http://desk.zol.com.cn/bizhi/7244_89635_2.html'
header = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.146 Safari/537.36',
'Cookie': '_ga=GA1.2.2002481844.1517997105; _gid=GA1.2.1153317059.1520845821'}
source_code = requests.get(url,headers=header)
plain_text = source_code.text
soup = BeautifulSoup(plain_text)
download_links = [] #创建一个列表list 储存图片
download_path = 'E://download soup/'
for pic_tag in soup.find_all('img'): # 观察图片规则 遍历数据 获取图片链接
pic_link = pic_tag.get('style')
download_links.append(pic_link)
print(download_links)
# for item in download_links:
# urllib.request.urlretrieve(item,download_path + item[-10:])
# print('Done')
|
# 함수 functions : 코드를 간략하고 쉽게 짜기 위한 툴
# 입력값 parameters, 반환값 return <반환값이 있어야 변수에 담을 수 있다
# def > 데피니션
def hello_friends(nam):
print("hello, {}".format(nam))
name1 = "강윤"
name2 = "은혜"
name3 = "맥스"
name4 = "크림"
hello_friends(name1)
hello_friends(name2)
hello_friends(name3)
hello_friends(name4)
# 입력값 있고, 반환값 있고
def sum(a, b):
return a + b
# 입력값 있고, 반환값 없고
def hello_friends(nam):
print("hello, {}".format(nam))
# 입력값 없고, 반환값 있고
def return_1():
return 1
# 입력값 없고, 반환값 없고
def hello_world():
print("hello world")
num_1 = return_1()
print(num_1)
# "반환값이 있다는 건 리턴을 한다는 이야기고,
# 리턴을 한다는 것은 변수에 담을 수 있다"
|
alpha = ' abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZабвгдеєжзиіїйклмнопрстуфхцчшщьюяАБВГДЕЄЖЗИІЇКЛМНОПРСТУФХЦЧШЩЬЮЯ0123456789'
step = 2
step1 = 1
text = input("Please write your text ").strip()
res = ''
digit=''
for c in text:
if c.isalpha():
if digit:
res += str(int(digit)+int(step1))
digit = ''
res += alpha[(alpha.index(c) + step) % len(alpha)]
elif c.isnumeric():
digit += c
else:
res += c
if digit:
res += str(int(digit)+int(step1))
print("Result: " + res + "") |
#배열 arr가 주어집니다.
# 배열 arr의 각 원소는 숫자 0부터 9까지로 이루어져 있습니다.
# 이때, 배열 arr에서 연속적으로 나타나는 숫자는 하나만 남기고 전부 제거하려고 합니다.
# 단, 제거된 후 남은 수들을 반환할 때는 배열 arr의 원소들의 순서를 유지해야 합니다. 예를 들면,
# arr = [1, 1, 3, 3, 0, 1, 1] 이면 [1, 3, 0, 1] 을 return 합니다.
# arr = [4, 4, 4, 3, 3] 이면 [4, 3] 을 return 합니다.
# 배열 arr에서 연속적으로 나타나는 숫자는 제거하고 남은 수들을 return 하는 solution 함수를 완성해 주세요.
def solution(arr):
answer = list()
for i in range(len(arr) - 1):
if arr[i] != arr[i + 1]:
answer.append(arr[i])
answer.append(arr[-1])
return answer
# arr = [1,1,3,3,0,1,1] answer = [1,3,0,1]
# arr = [4,4,4,3,3] answer = [4,3]
|
class Cone():
def __init__(self, Radius, Height):
self.radius = Radius
self.height = Height
def Volume(self):
r = self.radius
h = self.height
V = int((3.14 * (r*r)*h) / 3)
print("Volume is ", V)
def Surface_area(self):
r = self.radius
h = self.height
a = 3.14*r
from math import sqrt
b = (h*h) + (r*r)
c = sqrt(b)
d = r + c
e = int(d*a)
print("Surface area is: ", e)
p = int(input("Enter Radius: "))
q = int(input("Entre Height: "))
coco = Cone(p,q)
coco.Volume()
coco.Surface_area()
|
str = "hey this is sai, I am in mumbai,...."
ls =[]
print(str)
#function
def strcap(String):
lst = list(str.split())
for i in lst:
a = i.capitalize()
ls.append(a)
for i in ls:
print(i, end=" ")
strcap(str)
|
from AlertCreators.alert_creator import AlertCreator
from datetime import datetime, time
import re
class NosyNeighbor(AlertCreator):
"""
It's an AlertCreator
It has a constructor __init__(name, bed_time, wake_up_time) . I believe the name is self-explenatory, and the rest of the properties are explained later.
It has a method check_suspicious_activity(where, what, time) that takes the parameters where , what, time. Once again, similar to detect_movement, this is an 'endpoint' for our simulation, so the where and what are just strings we are going to be passing manually, nothing more.
It has two properties bed_time and wake_up_time. Both of these properties are of type datetime.
Calling check_suspicious_activity with time set to something wake_up_time and bed_time results in creating level 3 alert, with the specified where and what . Take a look in the camera implementation for inspiration.
Calling check_suspicious_activity with time set to something bed_time and wake_up_time throws an exception saying 'Neighbor asleep'.
datetime and datetime diffrence to be implemented for more robust feature"""
def __init__(self, name, bed_time, wake_up_time):
if name == "":
raise ValueError("Should not be empty")
if re.search("[^A-Za-z. ]", name):
raise ValueError("Should be alphabetic")
self.__name = name
self.bed_time = bed_time
self.wake_up_time = wake_up_time
@property
def name(self):
return self.__name
def time_check(self, currentTime, time_range):
if time_range[1] < time_range[0]:
return currentTime >= time_range[0] or currentTime <= time_range[1]
return time_range[0] <= currentTime <= time_range[1]
def check_suspicious_activity(self, where, what, datetime):
self.currentHour = datetime.strftime("%H:%M")
# print(self.bed_time, self.currentHour, self.wake_up_time)
checkHour = self.time_check(
self.currentHour, (self.bed_time, self.wake_up_time)
)
if checkHour is True:
raise Exception("Wellknown neighbor is sleeping")
else:
self.create_alert(where, what, 3)
|
import MapReduce
import sys
"""
Asymmetric Friends in the Simple Python MapReduce Framework
Given an input record as a 2-element list [personA, personB], returns the
list of all one-way friendships, i.e. personA is friends with personB, but
personB is not friends with personA
"""
mr = MapReduce.MapReduce()
# =============================
# Do not modify above this line
def mapper(record):
# key: person
# value: friend
person = record[0]
friend = record[1]
mr.emit_intermediate(person, friend)
mr.emit_intermediate(friend, person)
def reducer(key, list_of_values):
# key: person
# value: list of friends
for friend in list_of_values:
if list_of_values.count(friend) < 2:
mr.emit((key, friend))
# Do not modify below this line
# =============================
if __name__ == '__main__':
inputdata = open(sys.argv[1])
mr.execute(inputdata, mapper, reducer)
|
#Paulo = Necessário assistir a aula para colocar em ordem
from random import randint
from operator import itemgetter
dados = dict()
maior = 0
for c in range(1, 5):
dados[f'Jogador {c}'] = randint(1, 6,)
print(f'O jogador 1 tirou {dados["Jogador 1"]}\n'
f'O jogador 2 tirou {dados["Jogador 2"]}\n'
f'O jogador 3 tirou {dados["Jogador 3"]}\n'
f'O jogador 4 tirou {dados["Jogador 4"]}')
print('-='*30)
print('Ranking dos jogadores:')
ranking = dict()
ranking = sorted(dados.items(), key=itemgetter(1), reverse=True)
for r in range(1, 5):
print(f'{r}º {ranking[r-1]}')
#Guanabara
'''from random import randint
from time import sleep
from operator import itemgetter
jogo = {'jogador1': randint(1, 6),
'jogador2': randint(1, 6),
'jogador3': randint(1, 6),
'jogador4': randint(1, 6)}
ranking = list()
print('Valores sorteados:')
for k, v in jogo.items():
print(f'{k} tirou {v} no dado')
sleep(1)
ranking = sorted(jogo.items(), key=itemgetter(1), reverse=True)
print('-='*30)
print(' == RANKING DOS JOGADORES == ')
for i, v in enumerate(ranking):
print(f' {i+1}º lugar: {v[0]} com {v[1]}.')
sleep(1)''' |
#PAULO - OK
'''contidade = conthomem = contmulher20 = 0
while True:
idade = int(input('Digite sua idade: '))
sexo = str(input('Digite seu sexo [M/F]: ')).upper().strip()
continua = str(input('Quer continuar [S/N]? ')).upper().strip()
if idade >= 18:
contidade += 1
if sexo == 'M':
conthomem += 1
if sexo == 'F':
if idade < 20:
contmulher20 += 1
if continua == 'N':
break
if contidade > 1:
print(f'Há {contidade} pessoas maior de 18 anos.')
else:
print(f'Há {contidade} pessoa maior de 18 anos.')
if conthomem > 1:
print(f'Foram cadastrados {conthomem} homens.')
else:
print(f'Foi cadastrado {conthomem} homem.')
if contmulher20 > 1:
print(f'Foram cadastradas {contmulher20} mulheres com menos de 20 anos.')
else:
print(f'Foi cadastrada {contmulher20} mulher com menos de 20 anos.')'''
#GUANABARA
tot18 = totH = totM20 = 0
while True:
idade = int(input('Idade: '))
sexo = ' '
while sexo not in 'FM':
sexo = str(input('Sexo: [M/F] ')).strip().upper()[0]
if idade > 18:
tot18 += 1
if sexo == 'M':
totH += 1
if sexo == 'F' and idade < 20:
totM20 += 1
cont = ' '
while cont not in 'SN':
cont = str(input('Quer continuar? [S/N] ')).strip().upper()[0]
if cont == 'N':
break
print(f'Toatl de pessoas com mais de 18 anos é de {tot18}')
print(f'Ao todo temos {totH} homens cadastrados')
print(f'E temos {totM20} mulheres com menos de 20 anos')
|
#Não consegui fazer sozinho, necessário estudar esse tipo de exercício!
valor = int(input('Qual valor deseja sacar: R$ '))
cédula = 100
total = valor
contcéd = 0
while True:
if total >= cédula:
total -= cédula
contcéd += 1
else:
if contcéd > 0:
print(f'Toatal de \033[1;34m{contcéd}\033[m de notas de R$ {cédula}')
if cédula == 100:
cédula = 50
elif cédula == 50:
cédula = 20
elif cédula == 20:
cédula = 10
elif cédula == 10:
cédula = 5
elif cédula == 5:
cédula = 2
elif cédula == 2:
cédula = 1
contcéd = 0
if total == 0:
break
#Código praticamente copiado do GUANABARA! |
#Paulo
def área(a, b):
cálculo = a * b
print(f'A área de um terreno {a}x{b} é de {cálculo}m²')
print(' Controle de terrenos')
print('-'*30)
largura = float(input('Digite a LARGURA (m): '))
comprimento = float(input('Digite o COMPRIMENTO (m): '))
área(largura, comprimento)
#Guanabara
'''def área(larg, comp):
a = larg * comp
print(f'A área de um terreno {larg}x{comp} é de {a}')
#Programa Principal
print(' Controel de Terrenos')
print('-' * 20)
l = float(input('LARGURA (m): '))
c = float(input('COMPRIMENTO (m): '))
área(l, c)
''' |
#Paulo
'''n = 0
cont = 0
s = 0
while n != 999:
n = int(input('digite um número e digite 999 para parar: '))
s = s + n
cont = cont + 1
print(f'Você digitou {cont-1} e a soma dos números é de {s-999}')'''
|
# --------------
#Importing header files
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
#Path of the file is stored in the variable path
#Code starts here
# Data Loading
data=pd.read_csv(path)
data.rename(columns={'Total':'Total_Medals'},inplace=True)
print(data.head(10))
# Summer or Winter
data['Better_Event']=np.where(data['Total_Summer']>data['Total_Winter'],'Summer','Winter')
data.loc[data['Total_Summer']==data['Total_Winter'], 'Better_Event'] = 'Both'
better_event=data['Better_Event'].value_counts(ascending=False).index[0]
# Top 10
top_countries=data[['Country_Name','Total_Summer', 'Total_Winter','Total_Medals']]
top_countries.drop(146,axis=0,inplace=True)
def top_ten(df,col):
country_list=list(df.nlargest(10,col)['Country_Name'])
return country_list
top_10_summer=top_ten(top_countries,'Total_Summer')
top_10_winter=top_ten(top_countries,'Total_Winter')
top_10=top_ten(top_countries,'Total_Medals')
common=list(set(top_10_summer).intersection(set(top_10_winter)).intersection(set(top_10)))
# Plotting top 10
summer_df=data[data['Country_Name'].isin(top_10_summer)]
winter_df=data[data['Country_Name'].isin(top_10_winter)]
top_df=data[data['Country_Name'].isin(top_10)]
fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2,figsize=(20,20))
summer_df.plot.bar('Country_Name','Total_Summer',ax=ax1)
winter_df.plot.bar('Country_Name','Total_Winter',ax=ax2)
top_df.plot.bar('Country_Name','Total_Medals',ax=ax3)
# Top Performing Countries
summer_df['Golden_Ratio']=summer_df['Gold_Summer']/summer_df['Total_Summer']
summer_max_ratio=summer_df['Golden_Ratio'].max()
summer_country_gold=summer_df[summer_df['Golden_Ratio']==summer_max_ratio]['Country_Name'].values[0]
winter_df['Golden_Ratio']=winter_df['Gold_Winter']/winter_df['Total_Winter']
winter_max_ratio=winter_df['Golden_Ratio'].max()
winter_country_gold=winter_df[winter_df['Golden_Ratio']==winter_max_ratio]['Country_Name'].values[0]
top_df['Golden_Ratio']=top_df['Gold_Total']/top_df['Total_Medals']
top_max_ratio=top_df['Golden_Ratio'].max()
top_country_gold=top_df[top_df['Golden_Ratio']==top_max_ratio]['Country_Name'].values[0]
# Best in the world
data_1=data.drop(146,axis=0)
data_1['Total_Points']=data_1['Gold_Total']*3+data_1['Silver_Total']*2+data_1['Bronze_Total']
most_points=data_1['Total_Points'].max()
best_country=data_1[data_1['Total_Points']==most_points]['Country_Name'].values[0]
# Plotting the best
best=data[data['Country_Name']==best_country]
best=best[['Gold_Total','Silver_Total','Bronze_Total']]
best.plot.bar(stacked=True,ax=ax4)
plt.xlabel('United States')
plt.ylabel('Medals Tally')
plt.xticks(rotation=45)
|
n, d = int(input()), {}
for i in range(n):
x = int(input())
if not x in d:
d[x] = f(x)
print(d[x])
''' Решение со Степика
a=[int(input()) for i in range(int(input()))]
b={x:f(x) for x in set(a)}
for i in a:
print(b[i])
''' |
my_list = [
{
'a' : [1,2,3],
'b' : 2,
'c' : 'Hello',
'd' : True
},
{
'a' : [4,5,6],
'b' : 'hello',
'c' : False
}
]
print(my_list[0]['a'][1]) #2
my_dict = {
123 : [1,2,3],
True : 'Hello'
}
print(123 in my_dict) #True
print(my_dict.get('age')) #None
print('size' in my_dict) #False
print(True in my_dict) #True
print('Hello' in my_dict.values()) #True
print(my_dict.items()) #dict_items([(123, [1, 2, 3]), (True, 'Hello')])
my_dict2 = my_dict.copy()
my_dict.clear()
print(my_dict) #{}
print(my_dict2) #{123: [1, 2, 3], True: 'Hello'}
my_dict2.pop(123)
print(my_dict2) #{True: 'Hello'}
my_dict2.update({True: "World"})
print(my_dict2) #{True: "World"}
my_dict2.update({'name' : 'Roberto'})
print(my_dict2) #{True: 'World', 'name': 'Roberto'}
|
from claseProyecto import Proyecto
class ManejadorProyectos:
__proyectos=None
def __init__(self):
self.__proyectos = []
def agregarProyecto(self, proyecto):
'''recibe un objeto proyecto a agregar a la colección'''
if type(proyecto) == Proyecto:
self.__proyectos.append(proyecto)
def mostrarProyectos(self):
'''recorre la colección de proyectos, muestra los datos de proyecto y personas integrantes'''
for li in self.__proyectos:
print(li)
def buscarProyectoPorId(self, idProyecto):
'''dado un idProyecto, lo busca en la colección, si lo encuentra devuelve el proyecto, si no lo encuentra, devuelve una referencia None'''
proy = None
i = 0
while i < len(self.__proyectos) and proy == None:
if self.__proyectos[i].getIdProyecto() == idProyecto:
proy = self.__proyectos[i]
i += 1
return proy
def agregarPersonaProyecto(self, idProyecto, persona):
'''recibe un idProyecto, y una persona a agregar a dicho Proyecto'''
'''hace uso del método buscarProyectoPorId para buscar el Proyecto'''
proy = self.buscarProyectoPorId(idProyecto)
if proy != None:
proy.agregarIntegrante(persona)
def calcularPuntajeProyectos(self):
'''para cada Proyecto de la colección, calcula el puntaje según reglas de negocio'''
for i in self.__proyectos:
i.calcularPuntaje()
def ordenarProyectosPorPuntaje(self):
'''invoca a la función sort de las lista, que hace uso del operador sobrecargado en la clase Proyecto __gt__'''
self.__proyectos.sort() |
class IntervalTree:
def __init__(self, intervals):
# sort the full list of intervals by begin and build the tree
self.root = self.split_intervals(sort_by_begin(intervals))
# build the interval tree by recursively splitting the intervals into:
# - intervals overlapping with the node center (to be stored in the current node)
# - intervals whose end is less than the node center (to be forwarded to the left node)
# - intervals whose begin is higher than node center (to be forwarded to the right node)
def split_intervals(self, intervals):
if not intervals:
return None
x_center = self.center(intervals)
s_center = []
s_left = []
s_right = []
for k in intervals:
if k.get_end() < x_center:
s_left.append(k)
elif k.get_begin() > x_center:
s_right.append(k)
else:
s_center.append(k)
return Node(x_center, s_center, self.split_intervals(s_left), self.split_intervals(s_right))
# find the node center (begin of the interval in the middle of the sorted list of intervals)
def center(self, intervals):
return intervals[int(len(intervals)/2)].get_begin()
# count the intervals overlapping with x by traversing the tree
def overlap_counts(self, node, x):
if(node == None):
return 0
if x == node.x_center:
return len(node.s_center_begin_sorted)
else:
count = 0
if x < node.x_center: # check into the center list then recurse into the left child
for n in node.s_center_begin_sorted:
if n.get_begin() <= x:
count = count + 1
else:
break
return count + self.overlap_counts(node.left_node, x)
else: # check into the center list then recurse into the right child
for n in node.s_center_end_sorted:
if n.get_end() >= x:
count = count + 1
else:
break
return count + self.overlap_counts(node.right_node, x)
class Interval:
def __init__(self, begin, end):
self.begin = begin
self.end = end
def get_begin(self):
return self.begin
def get_end(self):
return self.end
class Node:
def __init__(self, x_center, s_center, left_node, right_node):
self.x_center = x_center # node center
self.s_center_begin_sorted = s_center # s_center is already sorted by begin
self.s_center_end_sorted = sort_by_end(s_center) # store a copy of center list by ending reverse order to speed up the counting
self.left_node = left_node
self.right_node = right_node
#
# utility functions to sort the list of intervals by begin (asc) or end (desc)
#
def sort_by_begin(intervals):
return sorted(intervals, key=lambda x: x.get_begin())
def sort_by_end(intervals):
return sorted(intervals, key=lambda x: x.get_end(), reverse = True) |
import string
file = 'AlicesAdventuresinWonderland_text.txt'
text = open(file, 'r')
word_counts = {}
for line in text:
data = line.strip().split(' ')
for value in data:
key = value.translate(str.maketrans('','',string.punctuation)).lower()
if key in word_counts.keys():
word_counts[key] += 1
else:
word_counts.update({key : 1})
print(word_counts)
|
i = 0 #Verify variable 'i'
for i in range(0, 10):#Repeat under code from 'i'=0 until 'i'=7.
'''
Calculator.py 참조
'''
cal = input("계산하고 싶은 숫자 2개를 입력해주세요.\n")
fir = int(cal.split(' ')[0])
sec = int(cal.split(' ')[1])
f = cal.split(' ')[0]
s = cal.split(' ')[1]
oper = input("연산자를 입력해주세요.\n")
if oper == '+':
plus = fir+sec
print(f+" + "+s+" = "+str(plus)+"이다.")
elif oper == '-':
minus = fir-sec
print(f+" - "+s+" = "+str(minus)+"이다.")
elif oper == '*':
mul = fir*sec
print(f+" * "+s+" = "+str(mul)+"이다.")
elif oper == '/':
div = fir/sec
print(f+" / "+s+" = "+str(div)+"이다.")
else:
print("nope") |
# Strings
print("String", 'Another String '
'He\'s Right ' # Escaping characters with the backspace (\)
""" He's Right"""
)
long_string = """Here's a new line:
...
... It's right there!"""
print(long_string)
# You can add strings together with plus sign
print(
"string1 " + "string2"
)
# You can add and multiply strings, but you are not able to subtract or divide
status_message = "Hey we have {} people using the sight right now"
# The {} represent where we will put the value in our variable template
# we use the format method (str.format) to put the value inside our variable
print(status_message.format(39))
|
class node(object):
def __init__(self, value, children = []):
self.value = value
self.children = children
def __repr__(self, level=0):
ret = "\t"*level+repr(self.value)+"\n"
for child in self.children:
ret += child.__repr__(level+1)
return ret
tree = node("grandmother", [
node("daughter", [
node("granddaughter"),
node("grandson")]),
node("son", [
node("granddaughter"),
node("grandson")])
]);
print tree
# class test():
# def __init__(self,name):
# self.name = name
#
# def __repr__(self):
# return self.name
#
#
# test = test('kostas')
# print test.name
|
"""
Environment File
"""
import os
import json
from pathlib import Path
def get_variable(variable_name, default=None, required=False):
"""
Loads an environment variable.
Falls back to check in the user's home directory for an env file.
It will load the variable from that file if it exists.
"""
value = os.environ.get(variable_name)
if value is not None:
try:
env_dir = os.path.join(str(Path.home()), 'ENV.json')
except AttributeError:
env_dir = None
if env_dir:
with open(env_dir) as data_file:
data = json.load(data_file)
value = data.get(variable_name)
if value is None:
value = default
if value is None and required:
raise Exception(
'The environment variable %s is required '
'for this application to run.' % (
variable_name,
)
)
return value
|
import time
file_loc = ".\\notes.txt"
def take_note():
note = raw_input('Enter Note --->')
note_file = open(file_loc, 'a')
note_file.write('---' + time.strftime(' %c: ') + note + '\n')
note_file.close()
def view_notes():
note_file = open(file_loc, 'r')
print("Your Notes:")
print(note_file.read())
note_file.close()
def run():
print(' [1] View Notes')
print(' [2] Take Note')
print(' [e] Exit')
select = raw_input('Enter Selection --->')
if(select == '1'):
view_notes()
elif(select == '2'):
take_note()
else:
return False
return True
while(run()):
continue
|
year=int(input("please enter the year number you wish:"))
if((year %400==0)or(year %4==0) and (year %100!=0)):
print("%d is a leap year"%year)
else:
print("%d is not the leap year"%year)
|
# Varun Shourie, CIS345, Tuesday/Thursday, 12:00PM-1:15PM, A6
from tkinter import *
import math
def add_number(button):
"""When the user presses a numerical button, this function will check if the button pressed is a number or decimal
point. If a decimal, the function will check to see another decimal is not present in the number before adding
another decimal. If a number, the function will check to see if the output so far is either a zero, negative zero,
or non-zero value and append the output accordingly. """
global output, calculation_done_recently
# Objects used to validate the expression and check for decimals and characteristics of output.
numbers = ("0", "1", "2", "3", "4", "5", "6", "7", "8", "9")
add_decimal = True
operator_present = False
index = -1
if calculation_done_recently:
output.set("0")
calculation_done_recently = False
# Scope of this variable is altered to allow for validation above.
current_output = output.get()
if button == ".":
while index >= -1 * len(current_output) and add_decimal:
# If a decimal is present before an operator is found, the number in question already has a decimal.
if current_output[index] in operators:
operator_present = True
elif current_output[index] == button and not operator_present:
add_decimal = False
index -= 1
if add_decimal:
output.set(f"{current_output}.")
elif button in numbers:
if current_output != "0" and current_output != "-0":
output.set(f"{current_output}{button}")
elif current_output == "-0":
output.set(f"-{button}")
else:
output.set(f"{button}")
def append_operator(button):
"""When the user presses an operator, this function will perform validation on the mathematical expression
to see if (1) the button provided is an operator, and (2) an operator is already not present in the math expression
at the point of insertion. """
global output, calculation_done_recently, operators
current_output = output.get()
add_operator = True
if calculation_done_recently:
calculation_done_recently = False
if button in operators:
# If there is already an operator separated by a space before the current position in output, or an operator
# at the current position in input, do not add an operator whatsoever.
if (len(current_output) >= 2 and current_output[-2] in operators and current_output[-1] == " "
or current_output[-1] in operators):
add_operator = False
if add_operator:
output.set(f"{current_output} {button} ")
def perform_calculation(button):
"""When the user presses the equals button, the function will evaluate the math expression and round results
to 10 decimal places to offset calculation error. If the user presses the sqrt button, the calculator will
evaluate the existing formula and then take the square root of that answer. If the calculation result can be a whole
number, then it'll be rounded down. Furthermore, this function prevents program crashing from bad user input."""
global output, calculation_done_recently
current_output = output.get()
if button == "sqrt" or button == "=":
try:
# Rounding is necessary to overcome error from floating point variables.
calculation = round(eval(current_output), 10)
if button == "sqrt":
calculation = math.sqrt(calculation)
if calculation == int(calculation):
calculation = int(calculation)
output.set(f"{calculation}")
# Handles when the user divides by zero, enters an invalid expression, or attempts to sqrt a negative value.
except (ZeroDivisionError, SyntaxError, ValueError):
output.set("Error")
finally:
calculation_done_recently = True
def perform_utility(button):
"""When the user clicks a utility, the function will alter the mathematical expression as stated below:
Pressing clear resets the expression to zero.
Pressing plus/minus toggles the most recently entered number between positive and negative signs, even
when the last input entered was an operator.
Pressing backspace deletes one character at a time, until the character count reaches 2. If there is a negative
number, removing the second to last character makes output a zero. If not, characters will be removed as normal.
"""
global output, calculation_done_recently, operators
current_output = output.get()
if calculation_done_recently:
calculation_done_recently = False
if button == "AC":
output.set("0")
elif button == "+/-":
# Objects used to modularize the math expression into digestible pieces of operators and numbers.
expression_parts = list(current_output.split(" "))
number_not_found = True
toggled_string = str()
index = -1
# Toggles the most recently found number in the expression to positive or negative depending on its sign.
while number_not_found and index >= -1 * len(expression_parts):
if expression_parts[index] not in operators and not expression_parts[index] == "":
number_not_found = False
if "-" not in expression_parts[index]:
expression_parts[index] = f"-{expression_parts[index]}"
else:
expression_parts[index] = f"{expression_parts[index][1:]}"
index -= 1
# Rewrites the entire math expression to include the toggled value.
for part in expression_parts:
if part in operators:
toggled_string += f" {part} "
else:
toggled_string += f"{part}"
output.set(toggled_string)
elif button == "-->":
# The output also needs to be checked if there's only a negative single digit number to backspace correctly.
if len(current_output) == 1 or len(current_output) == 2 and "-" in current_output:
output.set("0")
else:
output.set(f"{current_output[:-1]}")
# Configures the window object for later usage.
window = Tk()
window.config(bg="dim gray")
window.geometry("245x330")
window.title("Calculator")
# Objects used to ensure correct functionality and display of numbers throughout the program, including functions.
calculation_done_recently = False
operators = ("*", "/", "+", "-")
output = StringVar()
output.set("0")
# Frame which holds the contents of the calculator and helps simulate design of a calculator as shown in requirements.
calculator_frame = Frame(window, background="dark blue", width=40)
calculator_frame.pack(pady=5)
# Text box object for the calculator which shows program output.
output_entry = Entry(calculator_frame, width=34, justify=RIGHT, textvariable=output)
output_entry.pack(pady=10, ipady=10)
output_entry.bind("<KeyPress>", lambda x: "break")
# Label with all buttons created inside to delineate sections for input/output in the calculator.
button_section_label = Label(calculator_frame, background="dark blue")
button_section_label.pack(padx=5)
# First row of buttons are created below in the calculator.
clear_button = Button(button_section_label, bg="red", text="AC", fg="white", width=5, height=2,
command=lambda: perform_utility("AC"))
clear_button.grid(row=1, column=0, padx=5)
backspace_button = Button(button_section_label, bg="dark gray", text="-->", fg="white", width=5, height=2,
command=lambda: perform_utility("-->"))
backspace_button.grid(row=1, column=1, padx=5, pady=5)
plus_minus_button = Button(button_section_label, bg="dark gray", text="+/-", fg="white", width=5, height=2,
command=lambda: perform_utility("+/-"))
plus_minus_button.grid(row=1, column=2, padx=5, pady=5)
sqrt_button = Button(button_section_label, bg="dark gray", text="sqrt", fg="white", width=5, height=2,
command=lambda: perform_calculation("sqrt"))
sqrt_button.grid(row=1, column=3, padx=5, pady=5)
# Second row of buttons are inserted into the calculator.
seven_button = Button(button_section_label, bg="black", text="7", fg="white", width=5, height=2,
command=lambda: add_number("7"))
seven_button.grid(row=2, column=0, pady=5)
eight_button = Button(button_section_label, bg="black", text="8", fg="white", width=5, height=2,
command=lambda: add_number("8"))
eight_button.grid(row=2, column=1, pady=5)
nine_button = Button(button_section_label, bg="black", text="9", fg="white", width=5, height=2,
command=lambda: add_number("9"))
nine_button.grid(row=2, column=2, pady=5)
divide_button = Button(button_section_label, bg="gray", text="/", fg="white", width=5, height=2,
command=lambda: append_operator("/"))
divide_button.grid(row=2, column=3, pady=5)
# Third row of buttons are inserted into the calculator.
four_button = Button(button_section_label, bg="black", text="4", fg="white", width=5, height=2,
command=lambda: add_number("4"))
four_button.grid(row=3, column=0, pady=5)
five_button = Button(button_section_label, bg="black", text="5", fg="white", width=5, height=2,
command=lambda: add_number("5"))
five_button.grid(row=3, column=1, pady=5)
six_button = Button(button_section_label, bg="black", text="6", fg="white", width=5, height=2,
command=lambda: add_number("6"))
six_button.grid(row=3, column=2, pady=5)
multiplication_button = Button(button_section_label, bg="gray", text="*", fg="white", width=5, height=2,
command=lambda: append_operator("*"))
multiplication_button.grid(row=3, column=3, pady=5)
# Fourth row of buttons are inserted into the calculator.
one_button = Button(button_section_label, bg="black", text="1", fg="white", width=5, height=2,
command=lambda: add_number("1"))
one_button.grid(row=4, column=0, pady=5)
two_button = Button(button_section_label, bg="black", text="2", fg="white", width=5, height=2,
command=lambda: add_number("2"))
two_button.grid(row=4, column=1, pady=5)
three_button = Button(button_section_label, bg="black", text="3", fg="white", width=5, height=2,
command=lambda: add_number("3"))
three_button.grid(row=4, column=2, pady=5)
subtract_button = Button(button_section_label, bg="gray", text="-", fg="white", width=5, height=2,
command=lambda: append_operator("-"))
subtract_button.grid(row=4, column=3, pady=5)
# Fifth and final row of buttons are inserted into the calculator.
zero_button = Button(button_section_label, bg="black", text="0", fg="white", width=5, height=2,
command=lambda: add_number("0"))
zero_button.grid(row=5, column=0, pady=5)
decimal_button = Button(button_section_label, bg="black", text=".", fg="white", width=5, height=2,
command=lambda: add_number("."))
decimal_button.grid(row=5, column=1, pady=5)
equals_button = Button(button_section_label, bg="green", text="=", fg="white", width=5, height=2,
command=lambda: perform_calculation("="))
equals_button.grid(row=5, column=2, pady=5)
add_button = Button(button_section_label, bg="gray", text="+", fg="white", width=5, height=2,
command=lambda: append_operator("+"))
add_button.grid(row=5, column=3, pady=5)
window.mainloop()
|
def generator():
x = 0
while True:
y = yield x
if y is None:
x = x + 1
else:
x = y
g= generator()
print(next(g))
print('cos innego')
print(next(g))
print(next(g))
print('cos innego')
print(next(g))
print(g.send(12))
print(next(g)) |
x = input("podaj x:")
y = input("podaj y:")
print('x =', x)
print('y =', y)
print('Wynik dodawania:',int(x) + int(y))
print('Wynik odejmowania:', int(x) - int(y))
print('Wynik mnożenia:', int(x) * int(y))
print('wynik dzielenia:', int(x) / int(y))
print('wynik dzielenia całkowitego:', int(x) // int(y))
print('wynik reszty z dzielenia:', int(x) % int(y))
print('wynik potęęgowania:', int(x) ** int(y)) |
"""--- Part Two ---
Out of curiosity, the debugger would also like to know the size of the loop:
starting from a state that has already been seen, how many block redistribution
cycles must be performed before that same state is seen again?
In the example above, 2 4 1 2 is seen again after four cycles, and so the answer
in that example would be 4.
How many cycles are in the infinite loop that arises from the configuration in
your puzzle input?
"""
def test_steps_to_repetition():
assert steps_to_repetition([0, 2, 7, 0]) == 4
"""FOLLOWED APPROACH
The approach followed here is very similar to the one used in part 1. The
main difference is that now we'll use a dictionary to store all the configurations.
As the value, we'll use the amount of steps that we had done when we got that
configuration. Then, when we find it again, we'll just have to substract that
value to the current number of steps.
Another difference is that, as we can't use an array as a dict's key (as it isn't
a hashable element), we'll convert it to a comma-separated string first"""
def get_max(configuration):
max_index, max_value = max(enumerate(configuration), key=lambda x: x[1])
return max_value, max_index
def hashable_configuration(configuration):
"""Converts the configuration array to a string.
This we'll let us use it as a dict key"""
return ",".join(str(num) for num in configuration)
def steps_to_repetition(initial_configuration):
configuration = list(initial_configuration)
length = len(configuration)
steps = 0
configurations = {}
while True:
# Getting the index of the maximum value
max_value, max_index = get_max(configuration)
configuration[max_index] = 0
next_index = (max_index + 1) % length
# If the reallocation hasn't finished, we increase the corresponding value,
# find which is the next index to update (circular increase by 1) and
# reduce by one the amount of blocks left
while max_value > 0:
configuration[next_index] += 1
next_index = (next_index + 1) % length
max_value -= 1
# After finishing the distribution, we store the current configuration
# If it's already in the dict, we'll finish the execution and return
# the current number of steps - the value of the dict for that configuration
steps += 1
hashed_configuration = hashable_configuration(configuration)
if hashed_configuration in configurations:
return steps - configurations[hashed_configuration]
else:
configurations[hashed_configuration] = steps
if __name__ == '__main__':
input_path = 'input.txt'
input = open(input_path).read()
input = [int(num) for num in input.split()]
print(steps_to_repetition(input)) |
"""--- Part Two ---
There are more programs than just the ones in the group containing program ID 0.
The rest of them have no way of reaching that group, and still might have no
way of reaching each other.
A group is a collection of programs that can all communicate via pipes either
directly or indirectly. The programs you identified just a moment ago are all
part of the same group. Now, they would like you to determine the total number
of groups.
In the example above, there were 2 groups: one consisting of programs
0,2,3,4,5,6, and the other consisting solely of program 1.
How many groups are there in total?
"""
def test_count_groups():
example = """
0 <-> 2
1 <-> 1
2 <-> 0, 3, 4
3 <-> 2, 4
4 <-> 2, 3, 6
5 <-> 6
6 <-> 4, 5
"""
assert count_groups(example) == 2
def parse_programs(programs_diagram):
programs_array = programs_diagram.strip().splitlines()
programs = {}
for program in programs_array:
root_str, connected_to_str = program.split(' <-> ')
root = int(root_str)
connected_to = [int(num) for num in connected_to_str.split(',')]
programs[root] = connected_to
return programs
def count_groups(programs_diagram):
programs = parse_programs(programs_diagram)
groups = 0
already_classified = set()
# We can do this because we know that the keys are a list of consecutive
# integers. Otherwise, we'll have to use another approach
programs_keys = range(len(programs))
keys_not_visited = set(programs_keys)
while len(already_classified) != len(programs):
keys_visited = set()
keys_to_visit = {keys_not_visited.pop()}
while keys_to_visit:
key_to_visit = keys_to_visit.pop()
programs_connected = programs[key_to_visit]
for program in programs_connected:
if program not in keys_visited:
keys_to_visit.add(program)
keys_visited.add(program)
already_classified.add(program)
groups += 1
keys_not_visited = keys_not_visited.difference(keys_visited)
return groups
if __name__ == '__main__':
with open('input.txt') as input_file:
input_content = input_file.read()
result = count_groups(input_content)
print(f"GROUPS: {result}") |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.