text
stringlengths 37
1.41M
|
---|
def intervalo(numero):
if (numero >= 0 and numero <= 25):
return "Intervalo [0,25]"
elif (numero >25 and numero <=50):
return "Intervalo [25,50]"
elif (numero>50 and numero<=75):
return "Intervalo [50,75]"
elif (numero>75 and numero<=100):
return "Intervalo[75,100]"
else:
return "Fora de intervalo"
numero = float(input())
print(intervalo(numero))
|
# #day01通过代码获取两段内容,并且计算他们长度的和
# a = len(input("请输入a的值:"))
# print("a的长度:",a)
# b = len(input("请输入b的值:"))
# print("b的长度:",b)
# print("字段长度和",a+b)
#day02在字典里输入name、age、sex
d = {}
print(d)
a= input("请输入姓名:")
b = input("请输入年龄:")
c = input("请输入性别:")
d.update(name=a)
d.update(age=b)
d.update(sex=c)
print(d)
|
#Stephen Bowen 2020
import string
asciiString = string.ascii_lowercase
alternatives = ('0','1','2','3','4','5','6','7','8','9','!','@','#','$','%','^','&','*','(',')','-','=','<','>','?','=')
masterCipher = {asciiString[i] : alternatives[i] for i in range(len(asciiString))}
inverseCipher = {y : x for x , y in masterCipher.items()}
def Encode():
global masterCipher
string = str(input("\nEnter a message to encode: "))
result = ''
for char in string:
try:
result += masterCipher[char]
except:
result += char
print("Encoded message: {}\n".format(result))
def Decode():
global inverseCipher
string = str(input("\nEnter a message to encode: "))
result = ''
for char in string:
try:
result += inverseCipher[char]
except:
result += char
print("Decoded message: {}\n".format(result))
def Main(selection):
if selection == 1:
Encode()
elif selection == 2:
Decode()
elif selection == 3:
return False
if __name__ == "__main__":
loop = True
while loop != False:
print("Welcome to the Secret Message Encoder/Decoder\n1. Encode a message\n2. Decode a message\n3. Exit\n")
while True:
try:
selection = int(input("What would you like to do? "))
except ValueError:
print("Please enter a number between 1 and 3")
else:
if 1 <= selection <= 3:
loop = Main(selection)
break
else:
print("{} is not a valid selection. Please try again".format(selection))
|
#Stephen Bowen 2020
def display_list(SortOrder, foodList):
print(SortOrder)
print(*foodList, sep='\n')
foods = ['pizza','salad','hamburger','steak','apple','orange']
display_list("foods in original order:", foods)
foods.sort()
display_list("foods in ascending alphabetical order:", foods)
foods.sort(reverse=True)
display_list("foods in descending alphabetical order:", foods)
foods2 = sorted(foods)
display_list("foods2 in ascending alphabetical order:", foods2)
display_list("foods still in descending alphabetical order:", foods)
foods.reverse()
display_list("foods in ascending alphabetical order:", foods)
foods.append('carrots')
foods.append('milk')
display_list("sorted foods with carrots and milk appended to end:", foods)
foods.sort()
display_list("foods in ascending alphabetical order:", foods)
pizza_index = foods.index('pizza')
print("Pizza is at {}".format(pizza_index))
foods.insert(pizza_index, 'fries')
pizza_index = foods.index('pizza')
print("Pizza is now at {}".format(pizza_index))
|
name = input("Cual es tu primer nombre?")
name += " " + input("Cual es tu segundo nombre?")
name += " " + input("Cual es tu primer apellido?")
name += " " + input("Cual es tu segundo apellido?")
year = input("En que año naciste?")
print("Hola " + name)
print("Probablemente tienes " + str(2019-int(year)) + " años")
|
#!/usr/bin/env python
#!coding=utf-8
print('''
\t \t *** CALCULADORA ***
Ingresa la letra que corresponda a la opcion deseada
\t a. Sumar
\t b. Restar
\t c. Dividir
\t d. Multiplicar
''')
option = input()
if not((option == 'a') or (option =='b') or (option =='c') or (option =='d')):
# print(type (option), print)
print('Por favor introduce una opción VÁLIDA e intentalo nuevamente')
quit()
print('Ingresa el 1er valor')
value_A = int(input())
print('\n Ingresa el 2do valor')
value_B = int(input())
if (option == 'a'):
# print('Suma')
print( '\n \t Resultado: '+ str(value_A + value_B))
elif (option == 'b'):
# print('Resta')
print( '\n \t Resultado: '+ str(value_A - value_B))
elif (option == 'c'):
# print('División')
print( '\n \t Resultado: '+ str(value_A / value_B))
elif (option == 'd'):
# print('Multiplicacion')
print( '\n \t Resultado: '+ str(value_A * value_B))
|
name = "Monika"
age = 34
fav_color = "green"
print("My name is {}".format(name))
print("I am {} years old".format(age))
print("My favourite color is {}".format(fav_color))
#oprion 2
print("My favourite color is " + fav_color)
|
#!/usr/bin/env python3
# GS-Shapley Algorithm
# Created by: Akshay Singh and
# Date: 09/20/2017
# Purpose: It creates pairs of men and women
# using gale-shapley alroithm.
# INPUT(S): None
# OUTPUT(S): Participants
# Preferences
# Pairing
# CPU Time and CLock Time
# EXAMPLES:
# Sahr :Erik ,Oman ,Jack ,John ,Kirk ,Amos ,Kapi ,Yaz ,Jim ,Rhys ,
# John proposes to Sam
# John engaged to Sam
# Pairing :
# Jack - Cath
import time
import sys
from random import randrange
guyIndex = {0: "John", 1:"Jack", 2:"Jim", 3:"Kapi", 4:"Rhys", 5:"Oman", 6:"Kirk", 7:"Erik", 8:"Yaz", 9:"Amos"}
guyPrefer = {}
girlPrefer = {}
girlIndex = {0:'Ele', 1:'Ema', 2:'Cath', 3:'Kate', 4:'Sara', 5:"Ivy", 6:"Hope", 7:"Kim", 8:"Sam", 9:"Sahr"}
"""
This function accepts girlIndex and guyIndex keys
and return the keys that are shuffled using Knuth Shuffle.
"""
def knuth_shuffle(shuffle):
for i in range(len(shuffle)-1, 0, -1):
z = randrange(i + 1)
shuffle[i], shuffle[z] = shuffle[z], shuffle[i]
return shuffle
"""
Function accepts a list freeMen,
#that has all the guys who are not engaged.
"""
def free_Men(fm):
for man in guyPrefer.keys():
fm.append(man)
"""
This is the main macthing function
that does all the stable matching.
It accepts FreeMen list, engaged dictionary
and girlEngaged dictionary
It returns engaged dictionary that has the
pairs and it return the process time that is
used to show the CPU time
"""
def matching(fm,engaged,girlEngaged):
t1 = time.time()
t = time.process_time()
while(len(fm) > 0):
for man in guyPrefer.keys():
#print(guyIndex[man],"proposes to"," ", end="")
for woman in guyPrefer[man]:
print(guyIndex[man],"proposes to"," ",girlIndex[woman])
if(woman not in girlEngaged):
engaged[man] = woman
girlEngaged[woman] = man
fm.remove(man)
print(guyIndex[man], " engaged to ", girlIndex[woman])
break
else:
currentGuy = girlEngaged[woman]
currentGuyIndex = girlPrefer[woman].index(currentGuy)
newGuyIndex = girlPrefer[woman].index(man)
if(currentGuyIndex > newGuyIndex):
engaged[man] = woman
girlEngaged[woman] = man
fm.remove(man)
del engaged[currentGuy]
fm.append(currentGuy)
print(girlIndex[woman]," dumps", guyIndex[currentGuy])
print(guyIndex[man], " engaged to ", girlIndex[woman])
break
break
return engaged,(time.process_time() - t), (time.time()-t1)
"""
This is the main function that calls all the functions
"""
def main():
freeMen = []
engaged = {}
girlEngaged = {}
for key, value in guyIndex.items():
guyPrefer[key] = list(knuth_shuffle(list(girlIndex.keys())))
for key, value in girlIndex.items():
girlPrefer[key] = list(knuth_shuffle(list(guyIndex.keys())))
print("Participants:")
for key, value in guyPrefer.items():
print(guyIndex[key]," ", end="")
print("\n")
for key, value in girlPrefer.items():
print(girlIndex[key]," ", end="")
print("\n")
print("Preferences:")
for key, value in guyPrefer.items():
print(guyIndex[key],":", end="")
for i in value:
print(girlIndex[i], ",", end="")
print("")
free_Men(freeMen)
print("\n")
for key, value in girlPrefer.items():
print(girlIndex[key],":", end="")
for i in value:
print(guyIndex[i], ",", end="")
print("")
engaged,timeProcess,timeClock = matching(freeMen, engaged, girlEngaged)
print("Pairing :")
for key, value in engaged.items():
print(" ",guyIndex[key],"-", girlIndex[value])
#print(engaged)
print("Elapsed wall clock time: ", timeClock)
print("Elapsed CPU time: ", timeProcess)
print("Stable matchup")
#Taking User Input
person = input('Another trial? (y)es, (n)o ')
while(person != 'n'):
#person = input("Another trial? (yes), (n)o")
main()
main()
|
l1=[1,5,7,3,9]
l2=[2,4,8,1,9]
a=set(l1)
b=set(l2)
c=a.intersection(b)
if(c!=0):
print("values occur in both the list are ",c)
|
import csv
f=open("flowers.csv","w")
writer=csv.DictWriter(f,fieldnames=["flower","count"])
writer.writeheader()#writeheader() write headers to the csvfile
writer.writerow({"flower":"rose","count":"1"})
writer.writerow({"flower":"lilly","count":"2"})
writer.writerow({"flower":"lotus","count":"3"})
writer.writerow({"flower":"sunflower","count":"4"})
f.close()
c=0
f=open("flowers.csv")
reader=csv.DictReader(f)
for row in reader:
if c==0:
print(f'{" ".join(row)}')
print(f'{row["flower"]},{row["count"]}')
f.close()
|
s1=str(input("enter 1st string : "))
s2=input("enter 2nd string : ")
a=s1[1:]
b=s2[1:]
print("The new string formed : ",s2[0]+a+" "+s1[0]+b)
|
#!/usr/bin/env python3
# return input
def load_data(filename):
file = open(filename, "r")
data = 0
for line in file:
data = int(line)
file.close()
return data
# return tuple (digit of tens, digit of ones)
def get_digits(number):
return (int(number / 10) % 10, number % 10) if number > 9 else [number]
# return beginning index of found sequence in given list
def find_sequence(seq, tab):
return [i for i in range(len(tab)) if tab[i:i + len(seq)] == seq]
def part_1(number_of_recipes):
e1 = 0 # recipe index of first elf
e2 = 1 # recipe index of second elf
recipes = [3, 7]
while len(recipes) < number_of_recipes + 10:
recipe = list(get_digits(recipes[e1] + recipes[e2]))
recipes += recipe
if e1 == (e1 + recipes[e1] + 1) % len(recipes) or e2 == (e2 + recipes[e2] + 1) % len(recipes):
recipes += recipe
e1 += recipes[e1] + 1
e2 += recipes[e2] + 1
e1 = e1 % len(recipes)
e2 = e2 % len(recipes)
return recipes
def part_2(sequence):
e1 = 0 # recipe index of first elf
e2 = 1 # recipe index of second elf
offset = 0
recipes = [3, 7]
while True:
recipe = list(get_digits(recipes[e1] + recipes[e2]))
recipes += recipe
if e1 == (e1 + recipes[e1] + 1) % len(recipes) or e2 == (e2 + recipes[e2] + 1) % len(recipes):
recipes += recipe
e1 += recipes[e1] + 1
e2 += recipes[e2] + 1
e1 = e1 % len(recipes)
e2 = e2 % len(recipes)
index = find_sequence(sequence, recipes[offset:])
if index:
return index[0] + offset
else:
offset += len(recipe)
def main():
data = load_data("input.txt")
sequence = [int(x) for x in str(data)]
print('Part 1:', ''.join(map(str, part_1(data)[data:data + 10])))
print('Part 2:', part_2(sequence))
if __name__ == "__main__":
main()
|
def eggs(eggs_of_gold, eggs_not_of_gold):
print(f"You have {eggs_of_gold} golden eggs!")
print(f"You have {eggs_not_of_gold} eggs to eat!")
print("Golden geese what a pain\n" )
print("We can just give the function numbers directly:")
eggs(1, 900)
print("Or, we can use variables from our script:")
eggs_of_gold = 25
eggs_not_of_gold = 45
eggs(eggs_of_gold, eggs_not_of_gold)
print("We can even do math inside too:")
eggs(10 +20, 5 +6)
print("And we can combine the two, variables and math:")
eggs(eggs_of_gold + 100, eggs_not_of_gold + 1000)
eggs(eggs_of_gold + 25 - 45, eggs_not_of_gold - 2 + 200)
|
def save_file(results, file_path):
# Create File Object
f = open (file_path, 'w')
# Write Results
f.write (results)
# Close File Object
f.close ()
def open_file(file_path):
# Create File Object
f = open (file_path, 'r')
# Read File Contents
file_contents = f.read ()
# Close File Object
f.close ()
return file_contents
def calculate_key(key):
results = 0
counter = 0
# Convert each Character into an INT and added to results
for char in key:
counter += 1
results += ord (char)
# Return the results divided by the number of Characters in the key
return int (results / counter)
def decrypt(file_path, key):
# Get Encrypted Text data
file_contents = open_file (file_path)
# Calculate the Key
key_calc = calculate_key (key)
dec_results = ''
for line in file_contents:
for wrd in line:
for char in wrd:
# Subtract from the Key Results
int_char = ord (char) - key_calc
# Append Results
dec_results += chr (int_char)
save_file (dec_results, file_path)
print '[!] Finished Decryption'
def encrypt(file_path, key):
# Get Clear Text data
file_contents = open_file (file_path)
# Calculate the Key
key_calc = calculate_key (key)
enc_results = ''
for line in file_contents:
for wrd in line:
for char in wrd:
# Add to the Key Results
int_char = ord (char) + key_calc
enc_results += chr (int_char)
save_file (enc_results, file_path)
print '[!] Finished Encryption'
def main():
print 'Please Choose One Of The Following:\n 1]Encrypt\n 2]Decrypt'
choice = raw_input ('>')
print 'Enter the File Path'
file_path = raw_input ('>')
print 'Enter the Secret Key'
key = raw_input ('>')
# Encrypt
if choice == "1":
encrypt (file_path, key)
# Decrypt
elif choice == "2":
decrypt (file_path, key)
else:
print 'Invalid Choice'
if __name__ == '__main__':
main ()
|
# Prompt the user for input
j = input('Enter a value for j: ')
for k in range(((j + 13) / 27), 11, 1):
i = 3 * k - 1
print ('i: ' + str(i))
|
# Enter your code here. Read input from STDIN. Print output to STDOUT
num = raw_input()
array = raw_input()
array = array.split()
sum1 = 0
array = map(int,array)
print sum(array)
|
#! /usr/bin/python
import numpy as np
from scipy import linalg as la
class Molecule:
"""
implements the basic properties of a molecule
"""
def __init__(self, geom_str, units="Angstrom"):
self.read(geom_str)
self.units = units
def read(self, geom_str):
"""
Read in the geometry (as a list of strings, by readlines() ), and store 2 class variables:
1. self.atoms (a list of labels of the N atoms)
2. self.geom (an Nx3 numpy array of the x,y,z coordinates of each of the atoms)
"""
self.atoms = []
geom = []
for line in geom_str.split('\n')[2:]:
if line.strip() == '':
continue
atom, x, y, z = line.split()[:4]
self.atoms.append(atom)
geom.append([float(x),float(y),float(z)])
self.geom = np.array(geom)
def __str__(self):
"""
Print the molecule in a nice format
"""
out = "{:d}\n{:s}\n".format(len(self),self.units)
for atom, xyz in zip(self.atoms, self.geom):
out += "{:2s} {: >15.10f} {: >15.10f} {: >15.10f}\n".format(atom, *xyz)
return out
def __len__(self):
"""
return the length of the molecule (think of as the # of atoms, N)
"""
return len(self.geom)
def bohr(self):
"""
return the geometry in bohr
"""
if self.units == "Angstrom":
self.geom *= 1.889725989
self.units == "Bohr"
return self.geom
def angs(self):
"""
return the geometry in Angstroms
"""
if self.units == "Bohr":
self.geom /= 1.889725989
self.units = "Angstrom"
return self.geom
def copy(self):
return Molecule(str(self),self.units)
#### Example of an input
f = open("../../1/extra-files/molecule.xyz","r")
f = f.read()
mol = Molecule(f)
#print(mol.geom)
#print(mol.atoms)
#print( mol.__len__() )
#print( mol.__str__() )
#print( mol.angs() )
#print( mol.bohr() )
#print( mol.copy() )
|
''' Linear Search '''
def linearSearch(list, target):
for i in range(len(list) -1):
# if the target is int the ith element, return True
if list[i] == target:
return True
return False # If not found, return false
list = [12, 5, 13, 8, 9, 65]
print linearSearch(list, 5)
|
# Linked-List Queues #
def Enqueue(top_sentinel, new_value):
# Make a cell to hold the new value
new_cell = New Cell
new_cell.value = new_value
# Add the new cell to the linked list
new_cell.next = top_sentinel.next
top_sentinel.next = new_cell
new_cell.prev = top_sentinel
def Dequeue(bottom_sentinel):
# Make sure there is an item to dequeue
if (bottom_sentinel.prev == top.sentinel):
return "Already Empty"
else:
# Get the bottom cell's value
result = bottom_sentinel.prev.value
# Remove the bottom cell from the linked list
bottom_sentinel.prev = bottom_sentinel.prev.prev
bottom_sentinel.prev.next = bottom_sentinel
# Returns the result
return result
|
# Randomizing Arrays
import random
def RandomizeArray(myList): # Needs to take list
max_i = myList[len(myList) - 1]
print(myList)
print(max_i)
print(len(myList))
i = 0
for i in range(len(myList)):
j = random.randint(i,(len(myList) - 1))
temp = myList[i]
myList[i] = myList[j]
myList[j] = temp
return myList
# It is working
|
# One Dimensional Arrays(Lists in Python):
''' In Python there is no specific data structures called arrays '''
''' We are using lists instead of arrays '''
''' Finding Items in List '''
def IndexOf(list, target):
for i in range(len(list)):
if list[i] == target:
return i
# Returns False means target not in the list
return False
# O(N) Efficiency
''' Finding Minimum value in the list '''
def FindMin(list):
minimum = list[0]
for i in list:
if list[i] < minimum:
minimum = list[i]
return minimum
''' Finding Maximum value in the list '''
def FindMax(list):
maximum = list[0]
for i in list:
if list[i] > maximum:
maximum = list[i]
return maximum
''' Finding Average of the list '''
def FindAverage(list):
total = 0
for i in list:
total += list[i]
return total / len(list)
''' Finding the median of the List '''
def FindMedian(list):
for i in list:
# Finding the number of values greater than and less than array[i]
num_smaller = 0
num_greater = 0
for j in list:
if(list[j] < list[i]):
num_smaller += 1
elif(list[j] > list[i]):
num_greater += 1
else:
pass
if num_smaller == num_greater:
return list[i]
# O(NxN) Efficiency
''' Inserting an element to the end of the list '''
def InsertToEnd(list):
# Taking value from the user
value = raw_input()
# Appending to the end of the list
list.append(value)
''' Copying the list to another using append: '''
ar = [] # Make an empty list
for i in list:
ar.append(i)
print ar
return None
def InsertToIndex(list):
# Taking value from the user
value = raw_input()
# Ask user for index
index = raw_input()
# Add value to specific index
list.insert(index, value)
|
''' Implementation of the Map ADT using closed hashing and a probe with double hashing '''
from arrays import Array
class HashMap:
# Define constants to represent the status of each table entry.
UNUSED = None
EMPTY = _MapEntry(None, None)
# Creates an empty map instance.
def __init__(self):
self._table = Array(7)
self._count = 0
self._maxCount = len(self._table) - len(self._table) // 3
# Returns the number of entries in the map.
def __len__(self):
return self._count
# Determines if the map contains the given key.
def __contains__(self, key):
slot = self._findSlot(key, False)
return slot is not None
# Adds a new entry to the map if the key does not exist. Otherwise, the
# new value replaces the current value associated with the key.
def add(self, key, value):
if key in self:
slot = self._findSlot(key, False)
self._table[slot].value = value
return False
else:
slot = self._findSlot(key, True)
self._table[slot] = _MapEntry(key, value)
self._count += 1
if self._count == self._maxCount:
self._rehash()
return False
# Return the value associated with the key.
def valueOf(self, key):
slot = self._findSlot(key, False)
assert slot is not None, "Invalid map key."
return self._table[slot].value
# Removes the entry associated with the key
def remove(self, key):
# Returns and iterator for traversing the keys in the map.
def __iter__(self):
# Finds the slot containing the key or where the key can be added.
# forInsert indicates if the search is for an insertion, which locates
# the slot into which the new key can be added
def _findSlot(self, key, forInsert):
# Compute the home slot and the step size.
slot = self._hash1(key)
step = self._hash2(key)
# Probe for the key
M = len(self._table)
while self._table[slot] is not UNUSED:
if forInsert and \
(self._table[slot] is UNUSED or self._table[slot] is EMPTY):
return slot
elif not forInsert and \
(self._table[slot] is not EMPTY and self._table[slot].key == key):
return slot
else:
slot = (slot + step) % M
# Rebuilds the hash table
def _rehash(self):
# Create a new larger table.
origTable = self._table
newSize = len(self._table) * 2 + 1
self._table = Array(newSize)
# Modify the size attributes.
self._count = 0
self._maxCount = newSize - newSize // 3
# Add the keys from the original array to the new table.
for entry in origTable:
if entry is not UNUSED and entry is not EMPTY:
slot =self._findSlot(key, True)
self._table[slot] = entry
self._count += 1
# The main hash fucntion for mapping keys to table etries.
def _hash1(self, key):
return abs(hash(key)) % len(self._table)
# The second hash function used with double hashing probes
def _hash2(self, key):
return 1 + abs(hash(key)) % (len(self._table) - 2)
# Storage class for holding the key/value pairs.
class _MapEntry:
def __init__(self, key, value):
self.key = key
self.value = value
|
# Using Python
# This is for already defined 2 values
'''def GCD(a, b):
while (b != 0):
remainder = a % b
a = b
b = remainder
return a
'''
# We are asking user to put input
a = input()
b = input()
# Returns the greatest common divisor of two numbers
def GCD(a,b):
while(b != 0):
remainder = a % b
a = b
b = remainder
return a
# Returns only two numbers least common multiplier
def LCM(a,b):
return ((a * b) / GCD(a,b))
# Returns many different numbers' least common multiplier
def LCMM(*args):
return reduce(GCDLCM, args)
print (GCD(a,b))
print (LCM(a,b))
|
author: @nadide
from math import sqrt
def FindPrimes (max_number):
is_composite = []
for i in range(4,max_number+1,2):
is_composite[i] = True
next_prime = 3
stop_at = int(sqrt(max_number))
while (next_prime < stop_at):
#print next_prime
for i in range(next_prime*2,max_number+1,next_prime):
is_composite[i] = True
next_prime += 2
while (next_prime <= max_number and is_composite[next_prime]):
next_prime += 2
primes = []
for i in range(2,max_number+1):
if (not is_composite[i]):
primes.append(i)
return primes
|
# Copied from internet, Author name is below:
__author__ = "Adam Traub"
__date__="2/16/2011"
class LinkedList:
'''Linked List'''
class __Node:
'''
private node object. Node's consist of an element
and a pointer to the previous and next Node'''
def __init__(self, element=None):
self.__element = element
self.__next = None
self.__previous = None
self.__toMove = (self.getPrevious,self.getNext)
def __str__(self):
'''string representation of Node'''
return str(self.__element)
def hasNext(self):
'''returns true if the Node has a next Node'''
return self.__next != None
def getNext(self):
'''get next Node'''
return self.__next
def setNext(self,nextItem):
'''set the next Node of the Node'''
self.__next = nextItem
def hasPrevious(self):
'''returns true if the Node has a previous Node'''
return self.__previous != None
def getPrevious(self):
'''get previous Node'''
return self.__previous
def setPrevious(self,previousItem):
'''set the previous Node of the Node'''
self.__previous = previousItem
def getPreviousAndNext(self):
'''gets previous and next Nodes'''
return self.__previous,self.__next
def setPreviousAndNext(self, previousItem, nextItem):
'''set the previous and Next Node of the Node'''
self.__previous = previousItem
self.__next = nextItem
def getElement(self):
'''get the element of the Node'''
return self.__element
def setElement(self, element):
'''set the element of the current Node'''
self.__element = element
def get(self,gettingNextElement):
'''Get element based on a boolean. True for next. False for previous'''
return self.__toMove[int(gettingNextElement)]()
def __init__(self):
'''Creates the LinkedList'''
self.__first = LinkedList.__Node()
self.__last = self.__first
self.__length = 0
def __len__(self):
'''returns the length of the list O(1)'''
return self.__length
def count(self):
'''returns the length of the list O(1)'''
return self.__length
def isEmpty(self):
'''returns true if the list is empty'''
return self.__length == 0
def append(self, element):
'''Add element to last position of the list'''
self.__handleLinking(LinkedList.__Node(element),self.__last,None,False)
def pop(self, index =None):
'''Removes and returns an element in the list. last element by default.'''
if self.__length == 0:
raise IndexError("pop from empty list")
#utilize default parameter
if index ==None:
index = self.__length-1
toRemove = self.__getNodeAtPosition(self.__checkIndex(index))
self.__handleLinking(toRemove,toRemove.getPrevious(),toRemove.getNext(),True)
return toRemove.getElement()
def insert(self, index, element):
'''inserts an element to the given index'''
toMove = self.__getNodeAtPosition(self.__checkIndex(index))
self.__handleLinking(LinkedList.__Node(element),toMove.getPrevious(),toMove,False)
def extend(self, toAdd):
'''extend current list by adding an iterable structure to the end'''
for value in toAdd:
self.append(value)
def index(self, x):
'''Find index of first ocurrence of a given value'''
for dex,value in enumerate(self):
if x == value:
return dex
raise ValueError("LinkedList.index(x): x not in list")
def reverse(self):
'''reverse the linked list'''
for index in range(self.__length-1,-1,-1):
self.append(self.pop(index))
def __getitem__(self, index):
'''Allows for indexing, index must be an integer'''
#accounts for slicing
if type(index) == slice:
return self.__sliceList(index)
return self.__getNodeAtPosition(self.__checkIndex(index)).getElement()
def __add__(self, other):
'''adds a an iterable data structure to the linked list'''
retList = LinkedList()
for item in self:
retList.append(item)
for item in other:
retList.append(item)
return retList
def __setitem__(self, index, element):
'''Sets the item at a given index to a new element.'''
self.__getNodeAtPosition(self.__checkIndex(index)).setElement(element)
def __str__(self):
'''returns a string representation of the list'''
if self.__length == 0:
return '[]'
retString = "["
currentElement = self.__first.getNext()
for i in range(self.__length):
retString += str(currentElement) +", "
currentElement = currentElement.getNext()
return retString[:-2] + ']'
#Private functions
def __handleLinking(self, center, previous, nextNode, isRemoving):
'''takes care of linking Nodes on inserts and removals'''
def updateLinks(center, previous, nextNode, newNext, newLast, newPrevious, toAdd):
'''A nested function to reduce repeated code in setting links'''
if previous != None:
previous.setNext(newNext)
if nextNode == None:
self.__last = newLast
else:
nextNode.setPrevious(newPrevious)
self.__length += toAdd
if isRemoving:
updateLinks(center, previous, nextNode, nextNode, previous, previous, -1)
else:
center.setPreviousAndNext(previous,nextNode)
updateLinks(center, previous, nextNode, center, center, center, 1)
def __sliceList(self,theSlice):
'''(Private) function to handle slicing. Returns a Linked List'''
def determineStartStopStep(valToCheck, step, positiveStep, negativeStep):
'''nested function to reduce repeated code in determining slicing handling'''
if valToCheck == None:
if step > 0:
return positiveStep
else:
return negativeStep
else:
return valToCheck
retList = LinkedList()
#Following conditions handles the x[start:stop:step] notation
step = determineStartStopStep(theSlice.step,1,1,1)
start = determineStartStopStep(theSlice.start,step,0,self.__length-1)
stop = determineStartStopStep(theSlice.stop,step,self.__length,-1)
currentNode = self.__getNodeAtPosition(start)
gettingNext = step > 0
absStep = abs(step)
for eachItem in range(start,stop,step):
retList.append(currentNode)
if eachItem + step <= stop:#prevents step from going out of bounds
for i in range(absStep):
currentNode = currentNode.get(gettingNext)
return retList
def __getNodeAtPosition(self, index):
'''(Private) Gets a Node at a given index'''
movingForward = index < (self.__length//2)-1
if movingForward:
currentNode = self.__first
toAdd = 1
else:
currentNode = self.__last
index = (self.__length-1) - index
toAdd = 0
"""
Putting the for loop inside the condition would reduce the amount
of times the conditon must be evaluated, increasing efficiency
But would also simultaneously increase the amount of repeated code
"""
for i in range(index+toAdd):
currentNode = currentNode.get(movingForward)
return currentNode
def __checkIndex(self, index):
'''(Private) check if the index is an acceptable value. Index only changes if negative'''
if type(index) != int:
raise TypeError("Index must be an integer or a slice not a "+str(type(index)).split("'")[1])
#handles negative indices.
if index < 0:
index += self.__length
#If the index is out of bounds
if index >= self.__length or index < 0:
raise IndexError("Index out of bounds")
return index
if __name__ == "__main__":
import random
def advanceWMessage(message):
input(message+" press enter to continue")
def printList(theList):
print("Current List:"+str(theList))
x = LinkedList()
for i in range(30):
x.append(i)
printList(x)
advanceWMessage("Testing slicing")
for i in range(10):
val1 = random.randint(0,len(x)//2)
val2 = random.randint(len(x)//2,len(x))
val3 = random.randint(1,len(x)//10)
print("\n\nstart: "+str(val1))
print("stop: "+str(val2))
print("step: "+str(val3))
print(x[val1:val2:val3])
advanceWMessage("Insert -1 at beginning")
x.insert(0,-1)
printList(x)
|
import webbrowser
webbrowser.open("http://www.codeskulptor.org/#user40_RrB5gcTvcf0aDLs.py")
# Rock-paper-scissors-lizard-Spock
# In our first mini-project, we will build a Python function rpsls(name) that takes
# as input the string name, which is one of "rock", "paper", "scissors", "lizard",
# or "Spock". The function then simulates playing a round of
# Rock-paper-scissors-lizard-Spock by generating its own random choice from
# these alternatives and then determining the winner using a simple rule that
# we will next describe.
#
# While Rock-paper-scissor-lizard-Spock has a set of ten rules that logically
# determine who wins a round of RPSLS, coding up these rules would require a
# large number (5x5=25) of if/elif/else clauses in your mini-project code
# In this expanded list, each choice wins against the preceding two choices and
# loses against the following two choices (if rock and scissors are thought of as
# being adjacent using modular arithmetic)
|
'''
Given a singly linked list L: L0→L1→…→Ln-1→Ln,
reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→…
You may not modify the values in the list's nodes, only nodes itself may be changed.
Example 1:
Given 1->2->3->4, reorder it to 1->4->2->3.
Example 2:
Given 1->2->3->4->5, reorder it to 1->5->2->4->3.
'''
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def reorderList(self, head):
"""
:type head: ListNode
:rtype: void Do not return anything, modify head in-place instead.
"""
if not head:
return True
elif not head.next:
return False
fast, slow = head.next, head
while fast:
if fast == slow:
return True
head = head.next
return False
|
"""
Given the pointer/reference to the head of a singly linked list, reverse it and return the pointer/reference to the head of reversed linked list.
Consider the following linked list.
head -> 7 -> 14 -> 21 -> 28 -> NULL
Return pointer to the reversed linked list as shown in the figure.
head -> 28 -> 21 -> 14 -> 7 -> NULL
# Iterative way
If linked list only contains 0 or 1 nodes, then the current list can be returned as it is. If there are two or more nodes,
then iterative solution starts with 2 pointers.
reversed: A pointer to already reversed linked list (initialized to head).
list_to_do: A pointer to the remaining list (initialized to head->next).
We then set the reversed->next to NULL. This becomes the last node in the reversed linked list. reversed will always point to the head
of the newly reversed linked list.
At each iteration, the list_to_do pointer moves forward (until it reaches NULL). The current node becomes the head of the new reversed linked
list and starts pointing to the previous head of the reversed linked list.
The loop terminates when list_to_do becomes NULL and reversed pointer is pointing to the new head at the termination of the loop.
# Recursive way
First thing to remember (and to mention to the interviewer as well) is that the recursive version uses stack. OS allocates stack memory and this solution
can run out of memory for really large linked lists (think billions of items).
We recursively visit each node in the linked list until we reach the last node. This last node will become the new head of this list. On the return path,
each node is going to append itself to the end of partially reverse linked list.
Here's how recursive reversal works. If you have a reversed linked list of all the nodes to the left of current node and you know the last node of the reversed
inked list, then inserting the current node as the next of the last node will create the new reversed linked list. Then return the head of the new linked list.
The trick here is that you don't explicitly need to track the last node. The next pointer in the current node is already pointing to the last node
in the partially reversed linked list. Confused? An example might help. Here's our favorite linked list at the start when recursive reverse function is called.
"""
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
# Iterative
def reverseList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if head == None or head.next == None:
return head
todo = head.next
reverse = head
reverse.next = None
while (todo != None):
temp = todo
todo = todo.next
temp.next = reverse
reverse = temp
return reverse
# Time: O(n)
# Memory: O(1)
# Recursive
def reverseList(self, head):
if head == None or head.next == None:
return head
reverse = self.reverseList(head.next)
head.next.next = head
head.next = None
return reverse
# Time: O(n)
# Memory: O(n)
|
'''
Given a linked list, remove the n-th node from the end of list and return its head.
Note that the given n will always be valid.
Example:
Given 1->2->3->4->5, and n = 2.
Return 1->2->3->5
'''
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def Palindrome(self, head):
"""
:type head: ListNode
:rtype: void Do not return anything, modify head in-place instead.
"""
|
'''
Given an almost sorted array, in which each number is less than m spots array from its correctly sorted position, and
the value m, write an algorithmn that will return an array with the element properly sorted.
An example input would be the list [3, 2, 1, 4, 6, 5] and m = 3. In the example, each element in the array is less than 3
spots array from its position in a sorted array.
The snippet below is a buggy solution to the problem above. Fix the buggy solution such that it solves the problem
'''
def sort_list(almost_sorted_list, m):
min_heap, result = [], []
for elem in almost_sorted_list[:m]:
heapq.heappush(min_heap, elem)
for elem in almost_sorted_list:
heapq.heappush(min_heap, elem)
result.append(heapq.heappop(min_heap))
for i in range(len(min_heap)):
result.append(heapq.heappop(min_heap))
output = []
for i in result:
if i not in output:
output.append(i)
return output
|
# Write a function that takes a string as input and returns the string reversed.
# Example:
# Given s = "hello", return "olleh".
class Solution(object):
def reverseString(self, s):
"""
:type s: str
:rtype: str
"""
def reverse(arr):
start, end = 0, len(arr) - 1
while start < end:
temp = arr[start]
arr[start] = arr[end]
arr[end] = temp
start, end = start + 1, end - 1
cArr = list(s)
reverse(cArr)
return ''.join(cArr)
|
"""
Given the head of a singly linked list and 'N', swap the head with Nth node. Return the head of the new linked list.
Original linked list: 7 -> 14 -> 21 -> 28 -> 35 -> 42 -> Null
N = 4
After swaping: 28 -> 14 -> 21 -> 7 -> 35 -> 42 -> Null
Hint: Find (N-1)th node
"""
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def swap_Head_with_Nth(self, head, n):
prev = None
current = head
# Default check if head is none and n not greater than 1
if head == None or n == 1:
return head
count = 1
while current != None and count < n:
prev = current # Prev is N-1
current = current.next
count += 1
if current == None:
return head
# Current is pointing to nth node
# Let's swap nth node with head
prev.next = head
temp = head.next
head.next = current.next
current.next = temp
return current
# Time: O(n)
# Memory: O(1)
|
'''
Write a heap class that represents a minimum heap using an array. Implement the insert method for this min heap class.
min_heap = MinHeap()
min_heap.insert(2)
min_heap.insert(4)
min_heap.insert(1)
# Underlying array should look like: [1, 4, 2]
If time permits, implement the delete_min() method.
'''
# class MinHeap:
# def __init__(self):
# self.heap_list = []
# def insert(self, new_element):
# self.heap_list.append(new_element)
# self.bubble_up(len(self.heap_list) - 1)
# def bubble_up(self, curr_index):
# parent_index = (curr_index - 1) // 2
# while parent_index >= 0:
# curr_element, parent_element = self.heap_list[curr_index], self.heap_list[parent_index]
# if curr_element < parent_element:
# self.heap_list[parent_index] = curr_element
# self.heap_list[curr_index] = parent_element
# curr_index = parent_index
# parent_index = (parent_index - 1) // 2
# else:
# break
#
#
#
class minHeap:
def __init__(self):
self.heap_list = []
def insert(self, new_element):
self.heap_list.append(new_element)
self.bubble_up(len(self.heap_list) - 1)
def bubble_up(self, curr_index):
parent_index = (curr_index - 1) // 2
while parent_index >= 0:
curr_element, parent_element = self.heap_list[curr_index], self.heap_list[parent_index]
if curr_element < parent_element:
self.heap_list[parent_index]
|
# Given a string, determine if it is a palindrome, considering only alphanumeric
# characters and ignoring cases.
# For example,
# "A man, a plan, a canal: Panama" is a palindrome.
# "race a car" is not a palindrome.
# Note:
# Have you consider that the string might be empty? This is a good question to ask
# during an interview.
# For the purpose of this problem, we define empty string as valid palindrome.
# By recursive
import re
class Solution:
def isPalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
s = re.sub('[^0-9a-zA-Z]', '', s).lower()
return self.palindromeRecur(s)
def palindromeRecur(self, string):
if len(string) == 0 or len(string) == 1:
out = True
else:
if string[0] == string[len(string)-1]:
out = self.palindromeRecur(string[1:len(string)-1])
else:
out = False
return out
# By loop
import re
class Solution:
def isPalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
s = re.sub('[^0-9a-zA-Z]', '', s).lower()
i = 0
j = len(s) - 1
if len(s) == 0 or len(s) == 1:
return True
while i < len(s):
if s[i] == s[j]:
i += 1
j -= 1
else:
return False
return True
|
# You are climbing a stair case. It takes n steps to reach to the top.
# Each time you can either climb 1 or 2 steps. In how many distinct
# ways can you climb to the top?
# Note: Given n will be a positive integer.
# Example 1:
# Input: 2
# Output: 2
# Explanation: There are two ways to climb to the top.
# 1. 1 step + 1 step
# 2. 2 steps
# Example 2:
# Input: 3
# Output: 3
# Explanation: There are three ways to climb to the top.
# 1. 1 step + 1 step + 1 step
# 2. 1 step + 2 steps
# 3. 2 steps + 1 step
# DP, timeO(n), space O(n)
class Solution:
def climbStairs(self, n):
"""
:type n: int
:rtype: int
"""
if n == 1:
return 1
arr = [0] * (n+1)
arr[1] = 1
arr[2] = 2
for i in range(3,n+1):
arr[i] = arr[i-1] + arr[i-2]
return arr[n]
# Fibonacci , time O(n) , space O(1)
class Solution:
def climbStairs(self, n):
"""
:type n: int
:rtype: int
"""
if n == 1:
return 1
first = 1
last = 2
mid = 0
for i in range(3, n + 1):
mid = first + last
first = last
last = mid
return last
|
string=input()#Enter your statement
count1=0
count2=0
for i in string:
if(i.isupper()):
count2=count2+1
elif(i.islower()):
count1=count1+1
print(count2,count1)#print no of uppercase in your statement
#print(count1)#print no of lowercase in your statement
|
import matplotlib.pyplot as plt
plt.bar([0.25,1.25,2.25,3.25,4.25],[50,40,70,80,20],
label="BMW",color='b',width=0.5)
plt.bar([0.75,1.75,2.75,3.75,4.75],[80,20,20,50,60],
label="AUDI",color='r',width=0.5)
plt.legend()
plt.xlabel("Days")
plt.ylabel("Distance(kms)")
plt.title("Information")
plt.show()
|
# meow.c
# for i in range(3):
# meow()
# def meow():
# print("meow")
# this (above) is the incorrect because python doesn't know the
# function before it is called.
# the proper way is to
def main():
for i in range(3):
meow()
def meow():
print("meow")
main()
|
import requests
import json
userDetails = [["hit","[email protected]",855,"pkg","Hitesh Subnani"],["kj","[email protected]",966,"kj","Karina Jangir"]]
def location():
place = input("Search a Place : ").strip().lower()
place = place.replace(' ','%20')
url = 'https://maps.googleapis.com/maps/api/geocode/json?key=AIzaSyDMIBY1H3RBPhmjLRO6zmh3-jWe9eJZZsc&address={}'.format(place)
print('url = ',url)
page = requests.get(url)
data = page.json()
a = data['results']
lat = a[0]['geometry']['location']['lat']
lng = a[0]['geometry']['location']['lng']
print(lat,lng)
def login():
flag = False
userName = input("Enter your username")
passWord = input("Enter your Password")
for i in userDetails:
if userName == i[0] and passWord == i[3]:
print(f'Welcome {i[4]} to Weather App')
flag = True
break
if flag:
location()
else:
print("UserName or PassWord Incorrect")
def signup():
userName = input("Enter a UserName")
email = input("Enter your Email")
number = input("Enter your mobile number")
password = input("Enter a PassWord")
name = input("Enter your Name")
userDetails.append([userName,email,password,number,name])
print("\n-----------Login to continue------------\n")
login()
def abc():
n = int(input("Enter Your Choice"))
if n ==1 :
login()
elif n == 2:
signup()
else :
print("-->Invalid Input Please Enter Again")
abc()
print('-----------------Welcome to my weather App-------------------')
print("Please login/signup to continue")
print("Press 1 to Login")
print("press 2 to Signup")
abc()
|
import random
dataset= [['Name','Item','Amount','Unit_Price']]
customers = ['Bettison, Elnora',
'Doro, Jeffrey',
'Idalia, Craig',
'Conyard, Phil',
'Skupinski, Wilbert',
'McShee, Glenn',
'Pate, Ashley',
'Woodison, Annie']
products = [('DROXIA', 33.86),('WRINKLESS PLUS',23.55),
('Claravis', 9.85), ('Nadolol', 12.35),
('Quinapril', 34.89), ('Doxycycline Hyclate', 23.43),
('Metolazone', 43.06), ('PAXIL', 14.78)]
def generate_dataset(num_rows):
for i in range(num_rows):
name = random.choice(customers)
item, price= random.choice(products)
amount = random.randint(1,100)
total_price = amount * price
row = [name,item, amount, price, total_price]
dataset.append(row)
return dataset
print(generate_dataset(5))
|
# Write a script that will find and print only elements using a suitable operator or method:
# # Common - which have string01 and string02 common.
# Unique - which characters are present in string01 but not in string02.
string01 = 'Bratislava'
string02 = 'Budapest'
common = set(string01) & set(string02)
unique = set(string01) - set(string02)
print(f'Common characters: {list(common)}')
print(f'Unique characters: {list(unique)}')
|
import os.path
path = os.path.dirname(__file__)
# function for read row number
def read_specific_line(file_path, line_number: int) -> None:
with open(file_path) as handler:
current_line = None
current_line_number = 0
while current_line_number < line_number:
current_line = handler.readline()
current_line_number += 1
print(current_line)
read_specific_line(path + '/text.txt', 3)
with open(path + '/text.txt') as handler:
print(handler.readline())
print(handler.tell())
print(handler.readline())
print(handler.tell())
print(handler.readline())
print(handler.tell())
print(handler)
|
import datetime # import library datetime
# Greet the client
print("=" * 80)
print("Welcome in Destination \na place to choose a holiday!!!")
print("=" * 80)
# Offer destinations
print("Offer of holiday destinations:")
print("=" * 80)
print("1 - Prague | 1000\n2 - Wien | 1100\n3 - Brno | 2000\n4 - Svitavy | 1500\n5 - Zlin | 2300\n6 - Ostrava "
"| 3400")
print("=" * 80)
# Get input from user about destination
user_choise = input("Select destination: ")
# Assign variables appropriate data
offers = {
1: {"city": "Prague", "cost": 1000},
2: {"city": "Wien", "cost": 1100},
3: {"city": "Brno", "cost": 2000},
4: {"city": "Svitavy", "cost": 1500},
5: {"city": "Zlín", "cost": 2300},
6: {"city": "Ostrava", "cost": 3400}
}
# Get data from variables based on user's input
user_choise = int(user_choise)
city = offers[user_choise]["city"]
cost = offers[user_choise]["cost"]
# For destinations Svitavy and Ostrava we offer a special discount of 25%. We cannot provide our services to clients:
if city == "Svitavy" or city == "Ostrava":
cost = cost * 0.75
print(f"Good choice, we have a 25% discount for this destination")
else:
cost = cost
# Introduce registration
print("_" * 80)
print("Please register to complete your order:")
print("_" * 80)
# Get input from user about personal data
first_name = input("Name: ")
second_name = input("Second name: ")
year_birth = input("Year of birth: ")
year = datetime.date.today().year # extract actual year
age = year - int(year_birth)
if age <= 14:
print("Only for ages 15 and older, game over!")
exit()
email = input("email: ")
if not "@" in email:
print("Incorrect email!")
exit()
password: str = input("Password: ")
num_password = len(password)
if num_password < 8: # password min. 8 characters
print("Min. 8 characters pls.")
exit()
first_password = password[0]
last_password = password[-1]
first_password_ok = first_password.isnumeric() # first character cannot be a number!
last_password_ok = last_password.isnumeric() # last character cannot be a number!
a1z_password_ok = password.isalnum() # password must contain number(s) and letter(s)!
if first_password_ok: # if True - exit
print("Password error")
exit()
if last_password_ok: # if True - exit
print("Password error")
exit()
if not a1z_password_ok: # if not True - exit
print("Password error")
exit()
print("=" * 80)
# Thank user by the input name and inform him/her about the reservation made
print(f"Thank you for registering, Mr / Mrs {first_name} {second_name}")
print(f"Your reservation {city} and price {cost}")
|
# ask the user for a number
# split the given number in halves (e.g. 123456 -> split to 123 and 456, 12345 -> 12 and 345)
# convert both halves into an integer
# if both halves are an even integer, print: 'Success' - e.g. 12 and 34
# if only the first part is even, print: 'First' - e.g. 12 and 345
# if the second part is even, print: 'Second' - e.g. 123 and 456
# if neither of the numbers is even print: 'Neither' - 123 and 455
# if nothing has been entered (the user just hit Enter), print: 'No input provided'
input_number = input("Please, give me a number: ")
if len(input_number) == 0:
print("Not input provided")
else:
half_number = int(len(input_number)) // 2 #integer division
first_half = int(input_number[:half_number])
second_half = int(input_number[half_number:])
if len(input_number) == 0:
pass
elif first_half % 2 == 0 and second_half % 2 == 0:
print("Succsee")
elif first_half % 2 == 0 and second_half % 2 != 0:
print("First")
elif first_half % 2 != 0 and second_half % 2 == 0:
print("Second")
else:
print("Neither")
|
#test
a = 1
if a == 0:
print("a je 1")
quit()
else: print("a není 1")
print("End")
"""
# In the Python window you already have Mercedes and Rolls-Royce prices listed (don't forget to covert
# string to integer!). In addition, you have to create a variable that will ask the user for the extra cost.
# Then you will need to calculate:
#
# The price for two Mercedes,
# The Mercedes and Rolls-Royce prices,
# The price of two Rolls-Royce with extra equipment (each),
# Price for Mercedes with optional equipment.
# Finally, the program should print down everything clearly. Go ahead!
# """
# # Prices
# mercedes_cost = 150
# rolls_royce_cost = int('400')
#
# extra_cost = 0.95
# # extra cost (discount) fo two or more cars
#
# extra_equipment = 1.25
# # extra equipment on request
#
# order_car = input("You prefer Mercedes (1) or Rolls-Royce (2)? ")
# print(f"You order is {order_car}")
#
# order_car = int(order_car)
#
# if order_car > 1:
# order_cost = rolls_royce_cost
# else:
# order_cost = mercedes_cost
#
# count_car = int(input("How many cars? "))
#
# if count_car > 1:
# order_cost = order_cost * count_car * extra_cost
# else:
# order_cost = order_cost * count_car
#
# print(f"Price {count_car} cars is {order_cost}")
#
# equipment = input("Do you need better equipment? (1/0) ")
# equipment = int(equipment)
#
# if equipment == 1:
# total_cost = order_cost * extra_equipment
# else:
# total_cost = order_cost
#
#
# print(f"Total price of your cars is {total_cost}!")
|
#class Zdravic:
# """ Třída reprezentuje zdravič, který slouží ke zdravení uživatelů
# """
# def __init__(self):
# self.text = None
#
# def pozdrav(self, jmeno):
# """
# Vrátí pozdrav uživatele s nastaveným textem a jeho jménem.
# """
# return '{0} {1}!'.format(self.text, jmeno)
#
#zdravic = Zdravic()
#zdravic.text = 'Ahoj uzivateli'
#print(zdravic.pozdrav('Karel'))
#print(zdravic.pozdrav('Petr'))
#zdravic.text = 'Vitej programatore'
#print(zdravic.pozdrav('Ivo'))
#input()
class Clovek:
def __init__(self, jmeno: str, rok_narozeni: int, pohlavi = 'Muz', narodnost = 'Cech' ):
self.__jmeno = jmeno
self.__rok_narozeni = rok_narozeni
self.__pohlavi = pohlavi
self.__narodnost = narodnost
def vrat_datum_narozeni(self):
return self.__rok_narozeni
def vrat_pohlavi(self):
return self.__pohlavi
aneta = Clovek('Aneta', 1991, pohlavi='Zena')
ivo = Clovek('Ivo', 1965)
hana = Clovek('Hana', 1965, pohlavi='Zena')
print(aneta.vrat_datum_narozeni())
print(Clovek.vrat_datum_narozeni(aneta))
print(ivo.vrat_datum_narozeni())
print(hana.vrat_pohlavi(), hana.vrat_datum_narozeni())
|
#!python
import anagram_trie
from anagram_trie import AnagramTrie, AnagramTrieNode
class WordScrambleSolver():
"""A class for solving word scambles using an anagram trie"""
def __init__(self, path_to_anagram_trie):
"""Initalize this words scample solver"""
self.anagram_trie = anagram_trie.load_from_file(path_to_anagram_trie)
def unscramble(self, text=None, letters=None):
"""Retuns a list of the given text's anagrams"""
if text is not None:
return self.anagram_trie.find_anagrams(sorted(text))
if letters is not None:
unscambled_words = []
for text in letters:
sorted_text = self.unscramble(sorted(text))
unscambled_words.append(sorted_text)
return unscambled_words
if __name__ == '__main__':
scramble_solver = WordScrambleSolver('usrs_trie_solver.pkl')
print(scramble_solver.unscramble(letters=['dgo', 'eevasl']))
|
#!python
class Node(object):
def __init__(self, data):
"""Initialize this node with the given data"""
self.data = data
self.prev = None
self.next = None
def __repr__(self):
"""Return a string representation of this node"""
return 'Node({!r})'.format(self.data)
class DoublyLinkedList(object):
def __init__(self, iterable=None):
"""Initialize the linked list and append the given items, if any"""
self.head = None
self.tail = None
self.size = 0
if iterable is not None:
for item in iterable:
self.append(item)
def __str__(self):
"""Return a formatted string representation of this linked list."""
items = ['({!r})'.format(item) for item in self.items()]
return '[{}]'.format(' <-> '.join(items))
def __repr__(self):
"""Return a string representation of this linked list."""
return 'LinkedList({!r})'.format(self.items())
def items(self):
"""Returns all the items in the doubly linked list"""
result = []
node = self.head
while node is not None:
result.append(node.data)
node = node.next
return result
def is_empty(self):
"""Returns True is list is empty and False if not"""
return True if self.head is None else False
def length(self):
"""Returns the lenght(size) if the list"""
return self.size
def get_at_index(self, index):
"""Returns the item at the index or rases a value error if
index exceeds the size of the list"""
if not (0 <= index < self.size):
raise ValueError('List index out of range: {}'.format(index))
node = self.head
while index > 0:
node = node.next
index -= 1
return node.data
def insert_at_index(self, index, item):
"""Inserts an item into the list at a given index or rases a
value error is index is greater that the size of the list or
less that 0"""
node = self.head
new_node = Node(item)
if not (0 <= index <= self.size):
raise ValueError('List index out of range: {}'.format(index))
if self.size > 0:
while index > 1:
node = node.next
index -= 1
if node.prev is not None:
if node.next is None:
self.tail = new_node
node.prev.next = new_node
new_node.prev = node.prev
if node.prev is None:
self.head = new_node
new_node.next = node
node.prev = new_node
else:
self.head, self.tail = new_node, new_node
self.size += 1
def append(self, item):
"""Intert a given item at the end of the list"""
new_node = Node(item)
if self.is_empty():
self.head = new_node
else:
self.tail.next = new_node
new_node.prev = self.tail
self.tail = new_node
self.size += 1
def prepend(self, item):
"""Insert a given item at the beging of the list"""
new_node = Node(item)
if self.is_empty():
self.tail = new_node
else:
new_node.next = self.head
self.head.prev = new_node
self.head = new_node
self.size += 1
def find(self, quality):
"""Return an item based on the quality or None if no item was
found with the quality"""
node = self.head
while node is not None:
if quality(node.data):
return node.data
node = node.next
return None
def replace(self, old_item, new_item):
"""Replaces the node's data that holds the old data with the new data
or None if there is no node that holds old data"""
node = self.head
while node is not None:
if node.data == old_item:
node.data = new_item
break
node = node.next
else: raise ValueError('Item not found in list')
def delete(self, item):
"""Delete the given item from the list, or raise a value error"""
node = self.head
found = False
while not found and node is not None:
if node.data == item:
found = True
else:
node = node.next
if found:
if node is not self.head and node is not self.tail:
if node.next is not None:
node.next.prev = node.prev
node.prev.next = node.next
node.prev = None
node.next = None
if node is self.head:
if self.head is not None:
self.head.prev = None
self.head = node.next
node.next = None
if node is self.tail:
self.tail = node.prev
if node.prev is not None:
node.prev.next = None
node.prev = None
self.size -= 1
break
else:
raise ValueError('Item not found: {}'.format(item))
def test_doubly_linked_list():
ll = DoublyLinkedList()
print(ll)
print('Appending items:')
ll.append('A')
print(ll)
ll.append('B')
print(ll)
ll.append('C')
print(ll)
print('head: {}'.format(ll.head))
print('tail: {}'.format(ll.tail))
print('size: {}'.format(ll.size))
print('length: {}'.format(ll.length()))
print('Getting items by index:')
for index in range(ll.size):
item = ll.get_at_index(index)
print('get_at_index({}): {!r}'.format(index, item))
print('Deleting items:')
ll.delete('B')
print(ll)
ll.delete('C')
print(ll)
ll.delete('A')
print(ll)
print('head: {}'.format(ll.head))
print('tail: {}'.format(ll.tail))
print('size: {}'.format(ll.size))
print('length: {}'.format(ll.length()))
if __name__ == '__main__':
test_doubly_linked_list()
|
import random
def quicksort(in_list):
if len(in_list) <= 1:
return in_list # an in_list of zero or one elements is already sorted
less = []
more = []
pivot = random.choice(in_list)
in_list.remove(pivot)
for x in in_list:
if x <= pivot:
less.append(x)
else:
more.append(x)
return quicksort(less)+[pivot]+quicksort(more) # two recursive calls
sort_me = [random.randint(0,100) for x in range(0,100)]
print sort_me
print quicksort(sort_me)
|
import os
import sys
import importlib
import inspect
from abc import abstractmethod
import chess
from .types import *
from .history import GameHistory
class Player(object):
"""
Base class of a player of Recon Chess. Implementation of a player is done by sub classing this class, and
implementing each of the methods detailed below. For examples see `examples`.
The order in which each of the methods are called looks roughly like this:
#. :meth:`handle_game_start()`
#. :meth:`handle_opponent_move_result()`
#. :meth:`choose_sense()`
#. :meth:`handle_sense_result()`
#. :meth:`choose_move()`
#. :meth:`handle_move_result()`
#. :meth:`handle_game_end()`
Note that the :meth:`handle_game_start()` and :meth:`handle_game_end()` methods are only called at the start and
the end of the game respectively. The rest are called repeatedly for each of your turns.
"""
@abstractmethod
def handle_game_start(self, color: Color, board: chess.Board, opponent_name: str):
"""
Provides a place to initialize game wide structures like boards, and initialize data that depends on what
color you are playing as.
Called when the game starts.
The board is provided to allow starting a game from different board positions.
:param color: The color that you are playing as. Either :data:`chess.WHITE` or :data:`chess.BLACK`.
:param board: The initial board of the game. See :class:`chess.Board`.
:param opponent_name: The name of your opponent.
"""
pass
@abstractmethod
def handle_opponent_move_result(self, captured_my_piece: bool, capture_square: Optional[Square]):
"""
Provides information about what happened on the opponents turn.
Called at the start of your turn.
Example implementation: ::
def handle_opponent_move_result(self, captured_my_piece: bool, capture_square: Optional[Square]):
if captured_my_piece:
self.board.remove_piece_at(capture_square)
:param captured_my_piece: If the opponent captured one of your pieces, then `True`, otherwise `False`.
:param capture_square: If a capture occurred, then the :class:`Square` your piece was captured on,
otherwise `None`.
"""
pass
@abstractmethod
def choose_sense(self, sense_actions: List[Square], move_actions: List[chess.Move], seconds_left: float) -> \
Optional[Square]:
"""
The method to implement your sensing strategy. The chosen sensing action should be returned from this function.
I.e. the value returned is the square at the center of the 3x3 sensing area you want to sense. The returned
square must be one of the squares in the `sense_actions` parameter.
You can pass instead of sensing by returning `None` from this function.
Move actions are provided through `move_actions` in case you want to sense based on a potential move.
Called after :meth:`handle_opponent_move_result()`.
Example implementation: ::
def choose_sense(self, sense_actions: List[Square], move_actions: List[chess.Move], seconds_left: float) -> Square:
return random.choice(sense_actions)
:param sense_actions: A :class:`list` containing the valid squares to sense over.
:param move_actions: A :class:`list` containing the valid moves that can be returned in :meth:`choose_move()`.
:param seconds_left: The time in seconds you have left to use in the game.
:return: a :class:`Square` that is the center of the 3x3 sensing area you want to get information about.
"""
pass
@abstractmethod
def handle_sense_result(self, sense_result: List[Tuple[Square, Optional[chess.Piece]]]):
"""
Provides the result of the sensing action. Each element in `sense_result` is a square and the corresponding
:class:`chess.Piece` found on that square. If there is no piece on the square, then the piece will be `None`.
Called after :meth:`choose_sense()`.
Example implementation: ::
def handle_sense_result(self, sense_result: List[Tuple[Square, Optional[chess.Piece]]]):
for square, piece in sense_result:
if piece is None:
self.board.remove_piece_at(square)
else:
self.board.set_piece_at(square, piece)
:param sense_result: The result of the sense. A `list` of :class:`Square` and an optional :class:`chess.Piece`.
"""
pass
@abstractmethod
def choose_move(self, move_actions: List[chess.Move], seconds_left: float) -> Optional[chess.Move]:
"""
The method to implement your movement strategy. The chosen movement action should be returned from this function.
I.e. the value returned is the move to make. The returned move must be one of the moves in the `move_actions`
parameter.
The pass move is legal, and is executed by returning `None` from this method.
Called after :meth:`handle_sense_result()`.
Example implementation: ::
def choose_move(self, move_actions: List[chess.Move], seconds_left: float) -> Optional[chess.Move]:
return random.choice(move_actions)
:param move_actions: A `list` containing the valid :class:`chess.Move` you can choose.
:param seconds_left: The time in seconds you have left to use in the game.
:return: The :class:`chess.Move` to make.
"""
pass
@abstractmethod
def handle_move_result(self, requested_move: Optional[chess.Move], taken_move: Optional[chess.Move],
captured_opponent_piece: bool, capture_square: Optional[Square]):
"""
Provides the result of the movement action. The `requested_move` is the move returned from :meth:`choose_move()`,
and is provided for ease of use. `taken_move` is the move that was actually performed. Note that `taken_move`,
can be different from `requested_move`, due to the uncertainty aspect.
Called after :meth:`choose_move()`.
Example implementation: ::
def handle_move_result(self, requested_move: chess.Move, taken_move: chess.Move,
captured_opponent_piece: bool, capture_square: Optional[Square]):
if taken_move is not None:
self.board.push(taken_move)
Note: In the case of playing games on a server, this method is invoked during your opponents turn. This means
in most cases this method will not use your play time. However if the opponent finishes their turn before
this method completes, then time will be counted against you.
:param requested_move: The :class:`chess.Move` you requested in :meth:`choose_move()`.
:param taken_move: The :class:`chess.Move` that was actually applied by the game if it was a valid move,
otherwise `None`.
:param captured_opponent_piece: If `taken_move` resulted in a capture, then `True`, otherwise `False`.
:param capture_square: If a capture occurred, then the :class:`Square` that the opponent piece was taken on,
otherwise `None`.
"""
pass
@abstractmethod
def handle_game_end(self, winner_color: Optional[Color], win_reason: Optional[WinReason],
game_history: GameHistory):
"""
Provides the results of the game when it ends. You can use this for post processing the results of the game.
:param winner_color: If the game was a draw, then `None`, otherwise, the color of the player who won the game.
:param win_reason: If the game was a draw, then `None`, otherwise the reason the game ended specified as
:class:`WinReason`
:param game_history: :class:`GameHistory` object for the game, from which you can get the actions
each side has taken over the course of the game.
"""
pass
def load_player(source_path: str) -> Tuple[str, Type[Player]]:
"""
Loads a subclass of the Player class that is contained in a python source file or python module.
There should only be 1 such subclass in the file or module. If there are more than 1 subclasses, then you have
to define a function named `get_player` in the same module that returns the subclass to use.
Example of single class definition: ::
# this will import fine
class MyBot(Player):
...
Example of multiple class definition: ::
class MyBot1(Player):
...
class MyBot2(Player):
...
# need to define this function!
def get_player():
return MyBot1
Example of another situation where you may need to define `get_player`: ::
from my_helper_module import MyPlayerBaseClass
class MyBot1(MyPlayerBaseClass):
...
# you need to define this because both MyBot1 and MyPlayerBaseClass are subclasses of Player
def get_player():
return MyBot1
Example usage: ::
name, cls = load_player('my_player.py')
player = cls()
name, cls = load_player('reconchess.bots.random_bot')
player = cls()
:param source_path: the path to the source file to load
:return: Tuple where the first element is the name of the loaded class, and the second element is the class type
"""
if os.path.exists(source_path):
# get the path to the main source file
abs_source_path = os.path.abspath(source_path)
# insert the directory of the bot source file into system path so we can import it
# note: insert it first so we know we are searching this first
sys.path.insert(0, os.path.dirname(abs_source_path))
# import_module expects a module name, so remove the extension
module_name = os.path.splitext(os.path.basename(abs_source_path))[0]
else:
module_name = source_path
module = importlib.import_module(module_name)
players = inspect.getmembers(module, lambda o: inspect.isclass(o) and issubclass(o, Player) and o != Player)
get_player_fns = inspect.getmembers(module, lambda o: inspect.isfunction(o) and o.__name__ == 'get_player')
if len(players) == 0:
raise RuntimeError('{} did not contain any subclasses of {}'.format(source_path, Player))
elif len(players) > 1 and len(get_player_fns) != 1:
msg = '{} contained multiple subclasses of {}: {}'.format(source_path, Player, players)
msg += ', but no get_player function was defined. See documentation for reconchess.load_player'
raise RuntimeError(msg)
if len(players) == 1:
return players[0]
else:
_, get_player_fn = get_player_fns[0]
cls = get_player_fn()
return cls.__name__, cls
|
class Coche():
# Propiedades.
Largo = 250
Ancho = 120
Ruedas = 4
Encendido = False
# Metodos.
def Arrancar(self):
self.Encendido = True
def Estado(self):
if self.Encendido == True:
return "El Coche esta encendido."
else:
return "El Coche esta Apagado."
# Instanciando al objeto 1.
coche1 = Coche()
# Mostrar propiedades del objeto 1.
print(f"El Coche 1 tiene un largo de {coche1.Largo}cm")
print(f"El Coche 1 tiene un ancho de {coche1.Ancho}cm")
print(f"El Coche 1 tiene un total de {coche1.Ruedas} ruedas")
# Aplicando metodos al objeto 1.
coche1.Arrancar() # name.method
# > cambia el Estado a True.
print(coche1.Estado()) #name.method
# > muestra el estado del coche.
print(30*"-") # ---------------
# Instanciando al objeto 2.
coche2 = Coche()
# Mostrar propiedades del objeto 2.
print(f"El Coche 2 tiene un largo de {coche2.Largo}cm")
print(f"El Coche 2 tiene un ancho de {coche2.Ancho}cm")
print(f"El Coche 2 tiene un total de {coche2.Ruedas} ruedas")
# Aplicando metodos al objeto 1.
coche2.Arrancar() # name.method
# > cambia el Estado a True.
print(coche2.Estado()) #name.method
# > muestra el estado del coche.
|
print ("I will now calculate the area of a triangle:")
print ("The area of a triangle(base=4, height=6):", 0.5*4*6 )
|
import pandas as pd
import numpy as np
import random
import csv
def calculate_euclidean_distance(point_1, point_2):
"""
Given two points (np.array), calculate Euclidean distance
"""
delta = point_1 - point_2
return sum(delta**2)**0.5
def input_reader(filename):
"""
Read input csv file and return the input dataset as a numpy array
"""
dataset = [[1, 2, 3], [10, 30, 50], [100, 600, 700]]
df = pd.read_csv(filename, header=None)
return df.to_numpy()
def save(clusters_assignment, filename="output.csv"):
"""
Taking a cluster assignment Dict and storing in a CSV file.
"""
if not clusters_assignment:
return
cluster_ids = list(clusters_assignment.keys())
point_dimension = clusters_assignment[cluster_ids[0]][0].shape[0]
header = ['dim_' + str(inx) for inx in range(point_dimension)]
header += ['cluster_id']
# save clusters into a csv file
with open(filename, mode='w') as csv_file:
writer = csv.writer(csv_file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
writer.writerow(header)
for cluster_id, points in clusters_assignment.items():
for point in points:
point_list = list(point) + [cluster_id]
writer.writerow(point_list)
|
# -.- coding:utf-8 -.-
'''
Created on 2015年11月16日
@author: chenyitao
'''
import random
class CookiesManager(object):
'''
Cookies管理器
'''
def __init__(self):
'''
Constructor
'''
self.cookies = {}
self.history = []
def set_cookies(self, attr_id, action=0, cookies=None):
'''
设置平台cookies
action:0 replace 1 extend
'''
if attr_id == 1:
self.history.extend(cookies)
self.history = list(set(self.history))
if action:
self.cookies[attr_id] = cookies
else:
if attr_id not in self.cookies.keys():
self.cookies[attr_id] = []
self.cookies[attr_id].extend(cookies)
def get_cookie(self, attr_id, is_pop=True):
'''
get a cookie
'''
if attr_id not in self.cookies.keys():
return None
if not is_pop and len(self.cookies[attr_id]):
return random.choice(self.cookies[attr_id])
elif len(self.cookies[attr_id]):
return self.cookies[attr_id].pop(0)
def get_cookies(self, attr_id, is_pop=True):
'''
is_pop:False get cookies
is_pop:True pop cookies
'''
if attr_id not in self.cookies.keys():
return None
if not is_pop:
return self.cookies[attr_id]
return self.cookies.pop(attr_id)
def get_cookie_random(self, attr_id):
'''
获取随机cookie
'''
if attr_id not in self.cookies.keys():
return None
cookies = self.cookies[attr_id]
if not len(cookies):
return None
return random.choice(cookies)
cookies_manager = CookiesManager()
|
def filter_long_words(words:list,length:int):
list_of_words:list = []
for word in words:
if len(word) > length:
list_of_words.append(word)
return list_of_words
print(filter_long_words(['testing','ohyeah','ohno'],3))
|
girls = ['younghee', 'chulsoo', 'hooni', 'subi', 'chanwoo', 'hyunwoo']
def hi(name):
print('Hi ' + name + '!')
for name in girls:
hi(name)
print('Next girl')
|
class BST():
def __init__(self,data):
self.data = data
self.left=None
self.right=None
# self.root=None
def Insert(self,data):
if data==self.data:
#as bst doesnt allow duplicate values
return
elif data<self.data:
# add the data into left sub tree
if self.left:
#not an empty left node
self.left.Insert(data)
else:
#left sub-tree is empty
self.left=BST(data)
else:
if self.right:
self.right.Insert(data)
else:
self.right=BST(data)
def printt(self):
#inorder traversal
element=[]
if self.left:
# traversing through the right sub-tree
element+=self.left.printt()
element.append(self.data) #appending the base note
if self.right:
element+=self.right.printt()
# print(len(element))
return element
if __name__ == '__main__':
# tree=BST()
while True:
print("1=> CREATE A BST\n2=> DISPLAY\n3=> EXIT")
ch=int(input("ENTER YOUR CHOICE: "))
if ch==1:
n=int(input('HOW MANY ENTRIES? '))
r_data=int(input("enter the root data here:"))
tree=BST(r_data)
for i in range(n-1):
data=int(input('ENTER THE DATA HERE: '))
tree.Insert(data)
if ch==2:
print(tree.printt())
if ch==100:
exit()
|
class Node:
def __init__(self,data):
self.data =data
self.next=None
class Stack:
def __init__(self):
self.head=None
def push(self,data):
new_node=Node(data)
if self.head==None:
self.head=new_node
else:
temp=self.head
while temp.next!=None:
temp=temp.next
temp.next=new_node
new_node.next=None
def pop(self):
temp=self.head
if self.head==None:
print('STACK IS EMPTY! ')
elif self.head.next==None:
print(self.head.data +' popped')
self.head=None
else:
while temp.next.next!=None:
temp=temp.next
print(temp.next.data +' popped')
temp2=temp.next
temp2.next=None
temp.next=None
def print(self):
if self.head==None:
print('STACK IS EMPTY! ')
else:
temp=self.head
while temp.next!=None:
print(temp.data)
temp=temp.next
print(temp.data)
if __name__ == '__main__':
stck=Stack()
while True:
print('1=> PUSH\n2=> DISPLAY\n3=> POP\n100=> EXIT')
ch=int(input('ENTER YOUR CHOICE HERE: '))
if ch==1:
data=input('ENTER THE DATA HERE: ')
stck.push(data)
if ch==2:
stck.print()
if ch==3:
stck.pop()
if ch==100:
exit()
|
# This is interval-exchange-o-matic by Marc Culler and Nathan Dunfield
# (mostly all Marc's work). Written for Maryam Mizakhani 2005/2/4
#
# To use, in Terminal go to the directory containing this file, and type
# "python maryam.py" (w/o the quotes).
#
import os, sys, re, random, math, time
# return a parition where each segement has randomly choosen length
# between 1 and 2 N/n
def square_random_partition(N, n):
lengths = [ random.randrange(1, 2 * N//n) for i in range(n) ]
spaces = [ sum(lengths[:i]) for i in range(n+1) ]
return [ [spaces[i] + 1, spaces[i+1]] for i in range(n) ]
# a random partition of [1..N] into n pieces
def basic_random_partition(N, n):
spaces = random.sample(xrange(1, N), n-1) + [0, N]
spaces.sort()
return [ [spaces[i] + 1, spaces[i+1]] for i in range(n) ]
# choose a partition into n piece among all such with total length < N.
# compute choice of length using volumes of simplices in R^n
def random_partition(N, n):
M = int( math.floor( random.random()**(1.0/n) * (N - n)) + n)
return basic_random_partition(M, n)
def create_pseudogroup(perm, partition):
n = len(perm)
lengths = [ x[1] - x[0] + 1 for x in partition]
permlengths = [ lengths[perm.index(i)] for i in range(n)]
spaces = [ sum(permlengths[:i]) for i in range(n+1) ]
permimages = [ [spaces[i] + 1, spaces[i+1]] for i in range(n) ]
return Pseudogroup(
[Shift( partition[i], permimages[perm[i]]) for i in range(len(perm))],
Interval(partition[0][0], partition[-1][-1]))
def random_interval_exchange( perm, N ):
return create_pseudogroup(perm, random_partition(N, len(perm)))
def run_trials(perm, N, num_trials, outfile_name):
f = open(outfile_name, "a")
for i in range(num_trials):
p = random_interval_exchange(perm, N)
f.write( "%s\t%s\t%d\n" % (perm, N, p.reduce2()))
# this command assumes all guys in the file correspond to the same
# permutation
def examine_trials(file_name):
ans = load_trials(file_name)
keys = ans.keys()
keys.sort()
for N in keys:
print_stats(ans[N], N)
def print_stats(data, N):
num_trials = sum(data.values())
probone = (data[1]*1.0)/num_trials
ave =(1.0/num_trials) * sum( [i * data[i] for i in data.keys()] )
sigma = math.sqrt(probone* (1 - probone)/num_trials)
print "N = %d numtrials = %d Prob conn: %f Ave num components: %f Std. Dev %f" % (N, num_trials, probone, ave, sigma)
probs = []
for n in data.keys():
p = data[n]/(num_trials*1.0)
if p > 3 * math.sqrt(p* (1 - p)/num_trials):
probs.append( (n, p) )
probs.sort()
for n, p in probs:
print "%d: %f " % (n,p),
print
def load_trials(file_name):
ans = {}
for line in open(file_name).xreadlines():
perm, N, components = map(eval, line.split("\t"))
if not N in ans.keys():
ans[N] = {components:1}
else:
if components not in ans[N].keys():
ans[N][components] = 1
else:
ans[N][components] += 1
return ans
# Here's the interactive code
#
def get_permutation():
found = 0
while not found:
try:
ans = raw_input( "Enter permuation as list of images, e.g. 3 1 2 : ")
ans = [ int(a) - 1 for a in ans.split()]
check = ans[:]
check.sort()
if not check == range(len(ans)):
print "Not a bijection of [1, 2, ..., n]"
elif len(ans) > 0:
found = 1
except:
print "Invalid input"
return ans
def run_trials(perm, N, trials):
completed_trials = 0
data = {}
last_print_time = time.time()
while completed_trials < trials:
exch = random_interval_exchange(perm, N)
components = exch.reduce()
if components not in data.keys():
data[components] = 1
else:
data[components] += 1
if time.time() - last_print_time > 30:
print_stats(data, N)
last_print_time = time.time()
completed_trials += 1
print_stats(data, N)
def main():
print "Welcome to interval-exchange-o-matic\n by Marc Culler and Nathan Dunfield\n "
while 1:
perm = get_permutation()
N = int(raw_input("Enter the max points for the interval: "))
trials = int(raw_input("Enter number of trials: "))
print "\nStaring computation, will output intermediate results every 30 seconds\n Hit ctrl-C to stop at any time"
try:
run_trials(perm, N, trials)
except KeyboardInterrupt:
print "You asked me to stop\n"
ans = raw_input("\nDo you want to do another compuation? (y/n)")
if ans[0] != "y":
break
print "Bye!"
#--------------
#
# Below code is orbits.py by Marc Culler, version of 2005/2/10
#
#-------------------
from types import IntType, LongType
Illegal = "Illegal Operation"
def gcd(x, y):
if x == 0:
if y == 0:
raise ValueError, "gcd(0,0) is undefined."
else:
return abs(y)
x = abs(x)
y = abs(y)
while y != 0:
r = x%y
x = y
y = r
return x
class Interval:
"""
A finite subinterval of the integers.
"""
def __init__(self, a, b):
self.start = min(a,b)
self.end = max(a,b)
self.width = self.end - self.start + 1
def __repr__(self):
return '[%d, %d]'%(self.start, self.end)
def __cmp__(self, other):
"""
Intervals are ordered by (start, end) in lex order.
"""
if self.start != other.start:
return cmp(self.start, other.start)
return cmp(self.end, other.end)
def __contains__(self, x):
"""
True if the Interval contains the integer or Interval argument.
"""
if type(x) == IntType or type(x) == LongType :
return self.start <= x <= self.end
else:
return self.start <= x.start and x.end <= self.end
def __xor__(self, other):
"""
Intersection of two intervals
"""
start = max(self.start, other.start)
end = min(self.end, other.end)
if end < start:
return None
else:
return Interval(start, end)
def set_end(self, end):
self.end = end
self.width = self.end - self.start + 1
def set_start(self, start):
self.start = start
self.width = self.end - self.start + 1
def ToInterval(x):
"""
Converts an integer or a 2-tuple to an Interval.
"""
if x.__class__ == Interval:
return x
if type(x) == IntType or type(x) == LongType :
return Interval(x,x)
else:
return Interval(x[0],x[1])
class Isometry:
"""
An element of the infinite dihedral group acting on the integers.
"""
def __init__(self, shift, flip=0):
self.shift, self.flip = shift, flip
def __repr__(self):
if self.flip:
return 'x -> -x + %d'%self.shift
else:
return 'x -> x + %d'%self.shift
def __mul__(self, other):
"""
Composition operator for Isometries.
"""
flip = self.flip ^ other.flip
if self.flip:
shift = self.shift - other.shift
else:
shift = other.shift + self.shift
return Isometry(shift, flip)
def __pow__(self, n):
"""
Power operator for Isometries.
"""
if self.flip:
if n%2 != 0:
return Isometry(self.shift, self.flip)
else:
return Isometry(0,0)
else:
return Isometry(n*self.shift, self.flip)
def __invert__(self):
"""
Inversion operator for Isometries.
"""
if self.flip:
return Isometry(self.shift, self.flip)
else:
return Isometry(-self.shift, self.flip)
def __call__(self, x):
"""
An Isometry as a mapping (of an integer or an interval).
"""
if type(x) == IntType or type(x) == LongType:
if self.flip:
return -x + self.shift
else:
return x + self.shift
if x.__class__ == Interval:
return Interval(self(x.start), self(x.end))
class Pairing:
"""
The restriction of an isometry to a finite interval.
"""
def __init__(self, domain, isometry):
self.domain, self.isometry = domain, isometry
self.range = self(self.domain)
def __repr__(self):
if self.isometry.flip:
op = ' ~> '
else:
op = ' -> '
return str(self.domain) + op + str(self.range)
def __call__(self, x):
"""
A Pairing as a mapping.
"""
if not x in self.domain:
raise Illegal, "Operand is not contained in domain."
else:
return self.isometry(x)
def __cmp__(self, other):
"""
Linear ordering of Pairings.
"""
if self.range.end != other.range.end:
return cmp(other.range.end, self.range.end)
if self.domain.width != other.domain.width:
return cmp(other.domain.width, self.domain.width)
if self.domain.start != other.domain.start:
return cmp(self.domain.start, other.domain.start)
return cmp(self.isometry.flip, other.isometry.flip)
def __contains__(self,x):
"""
True if the argument is contained in either the domain or range.
"""
return x in self.domain or x in self.range
def is_preserving(self):
"""
True if the Pairing is orientation preserving.
"""
return self.isometry.flip == 0 or self.domain.width == 1
def is_periodic(self):
"""
True if the Pairing is orientation preserving, and
its domain and range meet.
"""
return self.is_preserving() and self.domain ^ self.range
def is_trivial(self):
"""
True if the Pairing is restriction of the identity map.
"""
return (self.is_preserving and self.isometry.shift == 0 or
self.domain.width == 1 and self.domain == self.range)
def contract(self,I):
"""
Adjust the Pairing to account for removal of a static interval.
"""
I = ToInterval(I)
if I ^ self.domain or I ^ self.range:
raise Illegal, "Contraction interval is not static."
shift = Isometry( -I.width )
if I.end < self.domain.start:
return Pairing(shift(self.domain), shift * self.isometry * ~shift)
elif I.end < self.range.start:
return Pairing(self.domain, shift * self.isometry)
else:
return self
def trim(self):
"""
Trim an orientation reversing pairing so that its domain and
range become disjoint.
"""
if self.is_preserving():
return self
else:
intersection = self.domain ^ self.range
if intersection:
middle = (self.domain.start + self.range.end - 1)/2
domain = Interval(self.domain.start, middle)
return Pairing(domain, self.isometry)
else:
return self
def merge(self, other):
"""
Merge a periodic Pairing with an overlapping orientation
preserving Pairing.
"""
if self.is_periodic() and other.is_preserving():
R = Interval(self.domain.start, self.range.end)
I = R ^ other.domain
shift = gcd(self.isometry.shift, other.isometry.shift)
if (other(I) ^ R).width >= self.isometry.shift :
domain = Interval(R.start, R.end - shift)
isometry = Isometry(shift)
return Pairing(domain, isometry)
else:
return None
else:
raise Illegal, "Pairing cannot be merged."
def transmit(self, other):
"""
Left shift the domain and range of another Pairing as far as possible.
"""
trim = self.trim()
if other.range not in trim.range:
return other
domain = other.domain
if not trim.is_preserving():
isometry = trim.isometry * other.isometry
if domain in trim.range:
isometry = isometry * trim.isometry
domain = trim.isometry(domain)
else:
shift = trim.isometry.shift
post = -(1 + (other.range.start - trim.range.start)/shift)
isometry = (trim.isometry**post) * other.isometry
if domain in trim.range:
pre = 1 + (other.domain.start - trim.range.start)/shift
isometry = isometry * (trim.isometry**pre)
domain = (trim.isometry**(-pre))(domain)
range = isometry(domain)
if range.start < domain.start:
isometry = isometry**(-1)
domain = range
return Pairing(domain, isometry)
def Shift(domain, range):
"""
Constructor for an orientation preserving pairing, given the domain
and range.
"""
if domain.__class__ != Interval:
domain = Interval(domain[0], domain[1])
if range.__class__ != Interval:
range = Interval(range[0], range[1])
if domain.width != range.width:
raise Illegal, "The domain and range must have the same width."
if range.start < domain.start:
domain, range = range, domain
isometry = Isometry(range.start - domain.start)
return Pairing(domain, isometry)
def Flip(domain, range):
"""
Constructor for an orientation reversing pairing, given the domain
and range.
"""
if domain.__class__ != Interval:
domain = Interval(domain[0], domain[1])
if range.__class__ != Interval:
range = Interval(range[0], range[1])
if domain.width != range.width:
raise Illegal, "The domain and range must have the same width."
if range.start < domain.start:
domain, range = range, domain
isometry = Isometry(range.end + domain.start, 1)
return Pairing(domain, isometry)
class Pseudogroup:
"""
Pseudogroup(P,U) is the pseudogroup of maps of the interval U which
is generated by the Pairings in the list P.
"""
def __init__(self, pairings, universe=None):
self.pairings = pairings
start = min([p.domain.start for p in self.pairings])
end = max([p.range.end for p in self.pairings])
if universe:
universe = ToInterval(universe)
if start < universe.start or end > universe.end:
raise ValueError, 'Universe must contain all domains and ranges.'
self.universe = universe
else:
self.universe = Interval(start, end)
def __repr__(self):
result = 'Pseudogroup on %s:\n'%str(self.universe)
if self.pairings:
self.pairings.sort()
for pairing in self.pairings:
result += str(pairing) + '\n'
return result
def clean(self):
"""
Get rid of trivial Pairings.
"""
self.pairings = [p for p in self.pairings if not p.is_trivial()]
def trim(self):
"""
Trim all orientation reversing pairings.
"""
self.pairings = [p.trim() for p in self.pairings]
def static(self):
"""
Find a static interval.
"""
if len(self.pairings) == 0:
return self.universe
intervals = [p.domain for p in self.pairings]
intervals += [p.range for p in self.pairings]
intervals.sort()
I = intervals.pop(0)
start, end = I.start, I.end
if start > 1:
return Interval(1, start - 1)
for interval in intervals:
if end < interval.start - 1:
return Interval(end+1, interval.start-1)
end = max(end,interval.end)
if end < self.universe.end:
return Interval(end + 1, self.universe.end)
return None
def contract(self):
"""
Remove all static intervals. Return the total size.
"""
result = 0
I = self.static()
while I:
result += I.width
if I.end != self.universe.end:
self.pairings = [p.contract(I) for p in self.pairings ]
self.universe.set_end(self.universe.end - I.width)
I = self.static()
return result
def merge(self):
"""
Merge periodic pairing whenever possible.
"""
if len(self.pairings) < 2:
return
done=0
while not done:
periodics = [p for p in self.pairings if p.is_periodic()]
done=1
for p in periodics[:-1]:
for q in periodics[1+periodics.index(p):]:
g = None
try:
g = p.merge(q)
except: pass
if g:
self.pairings.remove(p)
self.pairings.remove(q)
self.pairings.append(g)
done=0
break
def transmit(self):
"""
Use the largest Pairing to transmit others.
"""
self.pairings.sort()
g = self.pairings[0]
self.pairings = [g] + [ g.transmit(p) for p in self.pairings[1:] ]
def truncate(self):
"""
Truncate the largest pairing.
"""
self.pairings.sort()
g = self.pairings.pop(0)
if len(self.pairings) > 0:
support_end = self.pairings[0].range.end
else:
support_end = g.range.start - 1
if support_end < g.range.start:
self.universe.set_end(support_end)
return
if not g.is_preserving():
g.trim()
self.universe.set_end(support_end)
range = Interval(g.range.start, support_end)
domain = (~g.isometry)(range)
self.pairings = [Pairing(domain, g.isometry)] + self.pairings
def simplify(self):
"""
Do one cycle of the orbit counting reduction algorithm due
to Agol, Hass and Thurston.
"""
self.clean()
if len(self.pairings) == 0:
self.pairings = None
return self.universe.width
# print "cleaned\n", self
count = self.contract()
# print "contracted\n", self
self.trim()
# print "trimmed\n", self
self.merge()
# print "merged\n", self
self.transmit()
# print "transmitted\n", self
self.truncate()
# print "truncated\n", self
# print 'count = ', count
return count
def reduce(self):
"""
Reduce the pseudogroup to nothing. Return the number of orbits.
"""
count = 0
while self.pairings != None:
count += self.simplify()
return count
#--------- end Marcs code ------
if __name__ == "__main__":
main()
|
import sqlite3
import sys
# sys.argv is a list of the passed in args from the command line
print(sys.argv)
super_db = '/Users/andrewherring/nss/Backend/python/notes/superheroes.db'
def get_supers():
# shorthand for creating a connection
with sqlite3.connect(super_db) as conn:
cursor = conn.cursor()
# cursor runs a SQL query against the database
# pass execute SQl commands
# row is taco, what we are calling the information coming back
# for row in cursor.execute('SELECT * FROM Superheroes'):
# print(row)
# Another way to do the same thing
cursor.execute('SELECT * FROM Superheroes')
supers = cursor.fetchall()
print(supers)
def get_super(super):
with sqlite3.connect(super_db) as conn:
cursor = conn.cursor()
# s.* gets all of the superheores but not all of the information from the other tables
cursor.execute(f"""SELECT s.*, side.Name
FROM SUPERHEROES s
JOIN Sidekicks side
ON s.SuperheroId = side.SuperheroId
Where s.Name = '{super}'
""")
super = cursor.fetchone()
print(super)
return super
def addSuper(super):
with sqlite3.connect(super_db) as conn:
cursor = conn.cursor()
try:
cursor.execute(
'''
INSERT INTO Superheroes
Values(?,?,?,?,?)
''', (None, super["name"], super["gender"], super["secret"], None)
)
except sqlite3.OperationalError as err:
print("oops", err)
if __name__ == "__main__":
get_supers()
get_super(sys.argv[1])
addSuper({
"name": "Captain Derp",
"gender": "sure",
"secret": "Larry Smith"
})
get_supers()
|
class Animal:
def say_animal(self):
return "I am an animal"
class Animal_Friend:
def say_friend(self):
return "My friend is Mr. Farmer"
class Cow(Animal, Animal_Friend):
def say_cow_thing(self):
print(f"{self.say_animal()} and {self.say_friend()}")
# "I am an animal and my friend is Mr. Farmer"
# class Lion(Animal): would not inherit from animal_friend
bossie = Cow()
bossie.say_cow_thing()
# ========================
class Flying:
def __init__(self):
self.can_fly = True
@property
def wings(self):
try:
return self.__wing_count
except AttributeError:
return 2
@wings.setter
def wings(self, count):
if isinstance(count, int):
self.__wing_count = count
else:
raise TypeError("wing count must be a number")
def fly(self):
print("I can fly!")
class Swimming:
def __init__(self):
self.can_swim = True
def swim(self):
print("I can swim!")
class Running:
def __init__(self, leg_length):
self.can_run = True
self.run_speed = 2.0
self.leg_length = leg_length
def run(self):
if self.leg_length < 10 and self.run_speed <= 2.0:
return "I'm waddling as fast as I can"
elif self.leg_length < 20:
return "I'm running now, but get closer and I'll fly instead"
else:
return "Catch me if you can"
class Bat(Flying):
def __init__(self, species):
self.has_feathers = False
self.species = species
class Bird:
def __init__(self, species, nest="tree"):
self.has_feathers = True
self.species = species
self.nest = nest
def lay_egg(self):
if self.nest == "tree":
return("Push! Breathe! Push!")
else:
return("Push! Breathe! Watch your step, please!")
class Penguin(Bird, Running, Swimming):
def __init__(self, species, nest="ground", leg_length=5):
self.color = "black and white"
Bird.__init__(self, species, nest)
Swimming.__init__(self)
Running.__init__(self, leg_length)
def __str__(self):
return f"can_run: {self.can_run}, can_swim: {self.can_swim}, has_feathers: {self.has_feathers}"
emperor_penguin = Penguin("Emperor Penguin")
print("Our running, simming, feathery penguin", emperor_penguin)
|
print("This is used to convert miles to kilometers. Please enter the number of miles.")
num = int(input("Please enter a number: "))
kilometercalc = (num * 1.609344)
print("The number of kilometers from what you typed is: ", round(kilometercalc, 2))
|
text = input ("The given text: ")
print("The # of a: ", text.count('a'))
print("The # of b: ", text.count('b'))
print("The # of c: ", text.count('c'))
print("The # of d: ", text.count('d'))
print("The # of e: ", text.count('e'))
|
class Solution(object):
def threeSumClosest(self, nums, target):
nums = sorted(nums)
lens = len(nums)
mindist = float("inf")
for i in range(lens-1):
if i != 0 and nums[i] == nums[i-1]: continue
j,k = i+1,lens-1
while j < k:
print i,j,k
dist = nums[i] + nums[j] + nums[k] - target
if abs(dist) < abs(mindist): mindist = dist
if dist < 0: j += 1
elif dist > 0: k -= 1
else: return target
return mindist + target
if __name__ == '__main__':
s = Solution()
# nums = [1,2,4,8,16,32,64,128]
nums = [0,1,1,1]
target = 82
print s.threeSumClosest(nums,target)
|
#Objective
#In this challenge, we learn about normal distributions. Check out the Tutorial tab for learning materials!
#Task
#In a certain plant, the time taken to assemble a car is a random variable, X, having a normal distribution with a mean of 20 hours and a standard deviation of 2 hours. What is the #probability that a car can be assembled at this plant in:
#Less than 19.5 hours?
#Between 20 and 22 hours?
# Enter your code here. Read input from STDIN. Print output to STDOUT
import sys
from math import exp,factorial,sqrt,pi,erf
#def normdist(x,segma,mu):
# return (1/(segma*sqrt(2*pi)))*exp(-(x-2)**2/(2*segma**2))
def cumulNormDist(x,segma,mu):
z=(x-mu)/(segma*sqrt(2))
return 0.5+0.5*(erf(z))
ls=[]
for line in sys.stdin:
for j in line.rstrip().split():
ls.append(float(j))
segma=ls[1]
mu=ls[0]
x1=ls[2]
x2=ls[3]
y2=ls[4]
p1=cumulNormDist(x1,segma,mu)
p2=cumulNormDist(y2,segma,mu)-cumulNormDist(x2,segma,mu)
print(format(p1,".3f"))
print(format(p2,".3f"))
#Seconde challenge
import sys
from math import exp,factorial,sqrt,pi,erf
#def normdist(x,segma,mu):
# return (1/(segma*sqrt(2*pi)))*exp(-(x-2)**2/(2*segma**2))
def cumulNormDist(x,segma,mu):
z=(x-mu)/(segma*sqrt(2))
return 0.5+0.5*(erf(z))
ls=[]
for line in sys.stdin:
for j in line.rstrip().split():
ls.append(float(j))
segma=ls[1]
mu=ls[0]
x1=ls[2]
x2=ls[3]
p1=1-cumulNormDist(x1,segma,mu)
p2=1-cumulNormDist(x2,segma,mu)
p3=1-p2
print(format(p1*100,".2f"))
print(format(p2*100,".2f"))
print(format(p3*100,".2f"))
|
# A=B-3
a = int(input())
for i in range(a):
b, c = input().split()
b = int(b)
c = int(c)
print(b+c)
|
# 평균
# 세준이의 성적을 위의 방법대로 새로 계산했을 때,
# 새로운 평균을 구하는 프로그램을 작성하시오.
# 점수 list를 생성하고 list 중 최댓값을 추출 = list_score, max_score
# 일반적인 평균과 세준이의 계산법을 적용한 후 평균을 구한다. = before, after_average
# after_average 출력
N = int(input())
list_score = list(map(int, input().split()))
max_score = max(list_score)
before_average = sum(list_score) / N
after_average = before_average * 100 / max_score
print(after_average)
|
from search import ROUTE_API
def get_statements_with_value_path(issue_uid: int, search_value: str = '') -> str:
"""
Create the query string to get statements matching a certain string.
This method contains all parameters used in search(service).
:param issue_uid: uid of the issue to search in
:param search_value: text to be searched for
:return: query satisfied the requirements of search(service) to get statements fitting search_value
"""
suffix = '/statements?id={}&search={}'.format(issue_uid, search_value)
return ROUTE_API + suffix
def get_duplicates_or_reasons_path(issue_uid: int, statement_uid: int, search_value: str = '') -> str:
"""
Create the query string to get duplicates or reasons matching a certain string.
This method contains all parameters used in search(service).
:param issue_uid: uid of the issue to search in
:param statement_uid: uid of the statement which is supposed to be a duplicate or reason
:param search_value: text to be searched for
:return: query satisfied the requirements of search(service) to get duplicates or reasons fitting search_value
"""
suffix = '/duplicates_reasons?id={}&statement_uid={}&search={}'.format(issue_uid, statement_uid, search_value)
return ROUTE_API + suffix
def get_edits_path(issue_uid: int, statement_uid: int, search_value: str = '') -> str:
"""
Create the query string to get edits matching a certain string to a given statement uid.
This method contains all parameters used in search(service).
:param issue_uid: uid of the issue to search in
:param statement_uid: uid of the statement which had some edits
:param search_value: text to be searched for
:return: query satisfied the requirements of search(service) to get edits fitting search_value
"""
suffix = '/edits?id={}&statement_uid={}&search={}'.format(issue_uid, statement_uid, search_value)
return ROUTE_API + suffix
def get_suggestions_path(issue_uid: int, position: bool, search_value: str = '') -> str:
"""
Create the query string to get suggestions matching a certain string of a given issue.
This method contains all parameters used in search(service).
:param issue_uid: uid of the issue to search in
:param position: position of the statement
:param search_value: text to be searched for
:return: query satisfied the requirements of search(service) to get suggestions fitting search_value
"""
suffix = '/suggestions?id={}&position={}&search={}'.format(issue_uid, position, search_value)
return ROUTE_API + suffix
|
#!/usr/bin/python
class Replacee(object):
def __init__(self, value):
self.value = value
def GetValue(self):
return self.value
r = Replacee(2)
print r.value
print r.GetValue()
Replacee.GetValue = lambda _: 3
print r.value
print r.GetValue()
|
class BinaryNode:
left = None
right = None
value = 0
def __init__(self, value):
self.value = value
def getBinaryTree():
root = BinaryNode(20)
# left
nodel = BinaryNode(8)
nodell = BinaryNode(5)
nodelll = BinaryNode(3)
nodellr = BinaryNode(6)
nodell.left = nodelll
nodell.right = nodellr
nodel.left = nodell
nodelr = BinaryNode(11)
nodelrl = BinaryNode(9)
nodelrr = BinaryNode(12)
nodelr.left = nodelrl
nodelr.right = nodelrr
nodel.right = nodelr
# right
noder = BinaryNode(40)
noderl = BinaryNode(30)
noderll = BinaryNode(25)
noderlr = BinaryNode(32)
noderl.left = noderll
noderl.right = noderlr
noder.left = noderl
noderr = BinaryNode(50)
noderrl = BinaryNode(45)
noderrr = BinaryNode(55)
noderr.left = noderrl
noderr.right = noderrr
noder.right = noderr
root.left = nodel
root.right = noder
return root
|
cities = {}
city_0 = {'country': 'China', 'popu': '13min', 'fact': 'good'}
city_1 = {'country': 'ina', 'popu': '13min', 'fact': 'good'}
city_2 = {'country': 'Ca', 'popu': '13min', 'fact': 'good'}
cities['0'] = city_0
cities['1'] = city_1
cities['2'] = city_2
for city_name in cities.keys():
city_info = cities[city_name]
print("city_info is " + city_name)
for info,ins in city_info.items():
print(info + ":" + ins)
|
def switcher(choice):
case = ""
if choice.islower():
case = "lower"
elif choice.isupper():
case = "upper"
elif choice.isdigit():
case = "digit"
switcher_dict = {
'lower': 'lowercase letter',
'upper': 'uppercase letter',
'digit': 'digit letter'
}
return switcher_dict.get(case, "others")
print(switcher('a'))
print(switcher('A'))
print(switcher('2'))
|
def get_list_intersection(list_1, list_2):
return_list = []
for i in list_1:
for j in list_2:
if i == j:
return_list.append(i)
return return_list
list_1 = [1, 2, 3, 4, 5]
list_2 = [3, 4, 5, 6, 7]
print(get_list_intersection(list_1, list_2))
|
foods = ('rice', 'noodle', 'dumplings', 'burger', 'steak')
for food in foods:
print(food)
foods = ('rice', 'chicken', 'fish', 'burger', 'steak')
for food in foods:
print(food)
|
# for i in range(1, 21):
# print(i)
# max_list = list(range(1, 1000000))
# print(min(max_list))
# print(max(max_list))
# print(sum(max_list))
# odd_list = []
# for i in range(1,21,2):
# odd_list.append(i)
# for i in odd_list:
# print(i)
# div_list = []
# for i in range(3,31,3):
# div_list.append(i)
# print(div_list)
cube_list = [i**3 for i in range(1,11)]
print(cube_list)
|
import csv
# create function to put each col into list
def list_importer(lst, csv_file, col_name):
with open(csv_file) as insurance_file:
insurance_data = csv.DictReader(insurance_file)
for row in insurance_data:
lst.append(row[col_name])
return lst
# In my Python file I create empty lists for the various attributes in insurance.csv
ages = []
sexes = []
bmis = []
num_children = []
smoker_statuses = []
regions = []
insurance_charges = []
list_importer(ages, 'insurance.csv', 'age')
list_importer(sexes, 'insurance.csv', 'sex')
list_importer(bmis, 'insurance.csv', 'bmi')
list_importer(num_children, 'insurance.csv', 'children')
list_importer(smoker_statuses, 'insurance.csv', 'smoker')
list_importer(regions, 'insurance.csv', 'region')
list_importer(insurance_charges, 'insurance.csv', 'charges')
# average age of the patients = analyse_ages
# number of men vs. women counted in the dataset = analyse_sex_ratio
# geographical regions of patients within the dataset = analyse_location
# average yearly medical charges of the patients = analyse_charges
# creating a dictionary that contains all patient information = create_dictionary
# Create class Patient info with methods to perform above tasks
class PatientsInfo:
def __init__(self, patients_ages, patients_sexes, patients_bmis, patients_num_children,
patients_smoker_statuses, patients_regions, patients_charges):
self.patients_ages = patients_ages
self.patients_sexes = patients_sexes
self.patients_bmis = patients_bmis
self.patients_num_children = patients_num_children
self.patients_smoker_statuses = patients_smoker_statuses
self.patients_regions = patients_regions
self.patients_charges = patients_charges
def analyse_ages(self):
total_age = 0
for age in self.patients_ages:
total_age += int(age)
return "Average Patient Age: " + str(round(total_age / len(self.patients_ages), 2)) + " years"
def analyse_sex_ratio(self):
total_men = 0
total_women = 0
for sex in self.patients_sexes:
if sex == 'male':
total_men += 1
elif sex == 'female':
total_women += 1
print("Number of females: ", total_women)
print("Number of males: ", total_men)
def analyse_location(self):
locations = []
for location in self.patients_regions:
if location not in locations:
locations.append(location)
return locations
def analyse_charges(self):
total_charges = 0
for charge in self.patients_charges:
total_charges += float(charge)
return ("Average Yearly Medical Insurance Charges: " +
str(round(total_charges / len(self.patients_charges), 2)) + " dollars.")
def create_dictionary(self):
self.patient_dictionary = {}
self.patient_dictionary["age"] = [int(age) for age in self.patients_ages]
self.patient_dictionary["sex"] = [self.patients_ages]
self.patient_dictionary["bmi"] = [self.patients_bmis]
self.patient_dictionary["children"] = [self.patients_num_children]
self.patient_dictionary["smoker"] = [self.patients_smoker_statuses]
self.patient_dictionary["regions"] = [self.patients_regions]
self.patient_dictionary["charges"] = [self.patients_charges]
return self.patient_dictionary
# create instance of PatientInfo class and run methods
patient_info = PatientsInfo(ages, sexes, bmis, num_children, smoker_statuses, regions, insurance_charges)
print(patient_info.analyse_ages())
patient_info.analyse_sex_ratio()
print(patient_info.analyse_location())
print(patient_info.analyse_charges())
print(patient_info.create_dictionary())
|
import random
def add_node(graph, node, S):
if graph.get(node) is None:
graph[node] = [node in S, []]
def add_edge(graph, n1, n2):
graph[n1][1] += [n2]
graph[n2][1] += [n1]
# Question 9.a
def create_fb_graph(S, filename="facebook_combined.txt"):
with open(filename) as f:
lines = f.readlines()
# {node : [
# bool,
# [ neighbors(int) ]
# ] }
graph = dict()
for line in lines:
nodes = line.split()
n1, n2 = nodes[0], nodes[1]
add_node(graph, n1, S)
add_node(graph, n2, S)
add_edge(graph, n1, n2)
# print(graph)
return graph
def create_graph(network, S):
graph = dict()
for node, neighbors in network.items():
add_node(graph, node, S)
for neighbor in neighbors:
add_node(graph, neighbor, S)
add_edge(graph, node, neighbor)
return graph
|
# -*- coding: utf-8 -*-
"""
Created on Fri Oct 16 14:22:57 2020
@author: wangjingxian
"""
#232. 用栈实现队列
'''
使用栈实现队列的下列操作:
push(x) -- 将一个元素放入队列的尾部。
pop() -- 从队列首部移除元素。
peek() -- 返回队列首部的元素。
empty() -- 返回队列是否为空。
示例:
MyQueue queue = new MyQueue();
queue.push(1);
queue.push(2);
queue.peek(); // 返回 1
queue.pop(); // 返回 1
queue.empty(); // 返回 false
说明:
你只能使用标准的栈操作 -- 也就是只有 push to top, peek/pop from top, size, 和 is empty 操作是合法的。
你所使用的语言也许不支持栈。你可以使用 list 或者 deque(双端队列)来模拟一个栈,只要是标准的栈操作即可。
假设所有操作都是有效的 (例如,一个空的队列不会调用 pop 或者 peek 操作)。
'''
'''
因为python没有栈的数据结构,所以我们用list来模拟栈操作,append操作代表栈顶加入元素,pop操作代表弹出栈顶元素,
此外还可以使用len函数计算栈的元素个数,其他的列表操作均不可以使用!
(1)初始化两个栈结构,stack1为主栈,stack2为辅助栈
(2)push往stack1末尾添加元素,利用append即可实现
(3)pop时候,先将stack1元素向stack2转移,知道stack1只剩下一个元素时候(这就是我们要返回的队列首部元素),
然后我们再把stack2中的元素转移回stack1中即可
(4)类似于步骤(3)的操作,唯一不同是这里我们需要将elenment先添加回stack2,
然后再将stack2的元素转移回stack1中,因为peek操作不需要删除队列首部元素
(5)empty判断stack1尺寸即可
'''
class MyQueue:
def __init__(self):
"""
Initialize your data structure here.
"""
self.stack1 = [] # 主栈
self.stack2 = [] # 辅助栈
def push(self, x: int) -> None:
"""
Push element x to the back of queue.
"""
self.stack1.append(x)
def pop(self) -> int:
"""
Removes the element from in front of queue and returns that element.
"""
while len(self.stack1) > 1:
self.stack2.append(self.stack1.pop())
element = self.stack1.pop()
while len(self.stack2) > 0:
self.stack1.append(self.stack2.pop())
return element
def peek(self) -> int:
"""
Get the front element.
"""
while len(self.stack1) > 1:
self.stack2.append(self.stack1.pop())
element = self.stack1.pop()
self.stack2.append(element)
while len(self.stack2) > 0:
self.stack1.append(self.stack2.pop())
return element
def empty(self) -> bool:
"""
Returns whether the queue is empty.
"""
return len(self.stack1) == 0
# Your MyQueue object will be instantiated and called as such:
# obj = MyQueue()
# obj.push(x)
# param_2 = obj.pop()
# param_3 = obj.peek()
# param_4 = obj.empty()
|
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 13 10:25:18 2020
@author: wangjingxian
"""
#189. 旋转数组
'''
给定一个数组,将数组中的元素向右移动 k 个位置,其中 k 是非负数。
示例 1:
输入: [1,2,3,4,5,6,7] 和 k = 3
输出: [5,6,7,1,2,3,4]
解释:
向右旋转 1 步: [7,1,2,3,4,5,6]
向右旋转 2 步: [6,7,1,2,3,4,5]
向右旋转 3 步: [5,6,7,1,2,3,4]
示例 2:
输入: [-1,-100,3,99] 和 k = 2
输出: [3,99,-1,-100]
解释:
向右旋转 1 步: [99,-1,-100,3]
向右旋转 2 步: [3,99,-1,-100]
说明:
尽可能想出更多的解决方案,至少有三种不同的方法可以解决这个问题。
要求使用空间复杂度为 O(1) 的 原地 算法。
'''
#思路一:插入
class Solution:
def rotate(self, nums: List[int], k: int) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
n = len(nums)
k %= n
for _ in range(k):
nums.insert(0, nums.pop())
#思路二:拼接
class Solution:
def rotate(self, nums: List[int], k: int) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
n = len(nums)
k %= n
nums[:] = nums[-k:] + nums[:-k]
#思路三:三个翻转 , 整体翻转, 前k翻转,后k翻转
class Solution:
def rotate(self, nums: List[int], k: int) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
n = len(nums)
k %= n
nums[:] = nums[::-1]
nums[:k] = nums[:k][::-1]
#print(nums)
nums[k:] = nums[k:][::-1]
#print(nums)
#思路四:模拟过程
class Solution:
def rotate(self, nums: List[int], k: int) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
n = len(nums)
k %= n
if k == 0:return
start = 0
tmp = nums[start]
cnt = 0
while cnt < n:
nxt = (start + k) % n
while nxt != start:
nums[nxt], tmp = tmp, nums[nxt]
nxt = (nxt+k) % n
cnt += 1
nums[nxt] = tmp
start += 1
tmp = nums[start]
cnt += 1
|
from string import ascii_lowercase
from string import punctuation
import collections
alphabets = ''.join(list(ascii_lowercase))
monoKey = "hljfrtzyqscnbexvumpaokwdgi" # should converted to user input in gui
length=26
#Should be changed to input in gui
text="one way to solve a encrypted message if we know its language is to find different plaintext of the very same language long enough to fill one sheet or so and then we count the occurrences of each letter we call the most frequently occurring letter the first the next most occurring letter the second the following most occurring letter the third and so on until we account for all different letters in the plaintext sample then we look at the cipher text we want to solve and we also classify its symbols we find the most occurring symbol and change it to the form of the first letter of the plaintext sample the next most common symbol is changed to the form of the second letter and the following most common symbol is changed to the form of the third letter and so on until we account for all symbols of the cryptogram we want to solve"
text = text.lower()
no_punc = ""
for char in text:
if char not in punctuation and char not in " ":
no_punc += char
toEncrypt = no_punc
#This function takes in two parameters and returns two values
# parameter 1 -> Character to perform monoalphabetic substitution
# parameter 2 -> If the substitution is for encryption or decryption (encrypt=1, decrypt= -1 or any other value)
# Return value 1 -> Character after substitution
# Return value 2 -> key/number based on index (value limited between 1-25)
def monoAlphabeticSubstitution(charToSubstitute, action):
#Checking if encryption or decryption
if action==1:
indexAlphabets = alphabets.index(charToSubstitute) #finding the character index in alphabets
#Encrypting the character based on monoalphabetic substitution key
indexMonoKey = monoKey.index(charToSubstitute)
charMonoKey = monoKey[(indexMonoKey+1)%length]
else:
#Decrypting character based on monoalphabtic substituion key
indexMonoKey = monoKey.index(charToSubstitute)
charMonoKey = monoKey[(indexMonoKey-1)%length]
#Finding the index of the decrypted character in the alphabets
indexAlphabets = alphabets.index(charMonoKey)
value = indexAlphabets%(length-1)+1 #Determining value for key(or number of characters) based on index of plain text. The value is limited between 1-25
return (charMonoKey,value)
#This function takes in three parameters and returns one value
# parameter 1 -> Character to perform ceaser cipher substitution
# parameter 2 -> Key for ceaser cipher
# parameter 3 -> If the substitution is for encryption or decryption (encrypt=1, decrypt= -1 or any other value)
# Return value 1 -> Character after substitution
def ceaserCipherSubstitution(charToSubstitute, key, action):
if action != 1:
key = key*-1 #Converting key to negative number if decryption
currentIndex = alphabets.index(charToSubstitute)
newIndex = (currentIndex + key) % length
substitutedChar = alphabets[newIndex]
return substitutedChar
i = 0
encrypted = ""
#Looping through each character in the text to encrypt
while i < len(toEncrypt):
encryptedChar,key = monoAlphabeticSubstitution(toEncrypt[i],1)
encrypted += encryptedChar
i += 1 #Increasing counter
if i < len(toEncrypt): #Making sure that there are characters left in the plain text
encryptedChar, numCharToEncrypt = monoAlphabeticSubstitution(toEncrypt[i],1)
encrypted+=encryptedChar
i += 1
# Encrypting the required number of characters
for x in range(numCharToEncrypt):
if i < len(toEncrypt): #making sure that there are charcaters to encrypt
encryptedChar = ceaserCipherSubstitution(toEncrypt[i], key, 1)
encrypted += encryptedChar
i += 1 #Increasing counter
else:
break
print(encrypted)
toDecrypt = encrypted
i = 0
decrypted=""
#Looping through each character in the text to decrypt
while i < len(toDecrypt):
decryptedChar, key = monoAlphabeticSubstitution(toDecrypt[i],-1) #finding key and decrypted character
decrypted += decryptedChar #adding decrypted character to decrypted text
i += 1 #Updating counter
if i < len(toEncrypt): #Making sure that there are characters left to encrypt
decryptedChar, numCharToDecrypt = monoAlphabeticSubstitution(toDecrypt[i],-1) #finding number of characters to decrypt and decrypted character
decrypted += decryptedChar
i += 1 #updating counter
# decrypting the required number of characters
for x in range(numCharToDecrypt):
if i < len(toDecrypt):
#Finding decrypted character and adding it to the decrypted text
decryptedChar = ceaserCipherSubstitution(toDecrypt[i], key, -1)
decrypted += decryptedChar
i += 1
else:
break
print(decrypted)
|
#Напишите программу,
# которая выводит чётные числа из заданного списка и останавливается, если встречает число 237.
import random
a=random.randint(88,300)
list_1=list(range(1,a))
list_1.append(237)
random.shuffle(list_1)
print(list_1)
for i in list_1:
if i % 2 ==0:
print(i)
elif i==237:
print('237 The end!')
break
|
# listas
colores = ["Azul", "Rojo", "Verde", "Amarillo"]
# print(colores)
# imprimir una posicion determinada
# print(colores[1])
# imprimir el ultimo item de la lista
# print(colores[-1])
# imprimir desde la posicion 1 hasta la 3
# print(colores[1:3])
# imprimir desde la posicion 2 hasta el final
# print(colores[2:])
colores[2] = "Indigo"
# print(colores)
# Todas las formas de impresion mas NO DE EDICION de las listas tambien sirven para los str
texto = "Ya son las 12"
# print(texto[3:])
# Metodos de Edicion de listas
colores.append("Violeta")
# print(colores)
# Metodo para quitar un elemento de la lista
colores.remove("Indigo")
# print(colores)
# Metodo para limpiar toda la lista, elimina todos los items
colores.clear()
# print(colores)
# Teniendo la siguiente lista
combinada = [1, "Eduardo", 14.5, True, "Arequipa"]
# se dese saber cuantos elementos son int, float, str y bool y al final limpiar la lista
# Rpta => en la lista hay 1 int, 1 float, 2 str, 1 bool
# Hint => use el metodo type()
entero = 0
flotante = 0
booleano = 0
string = 0
otro_dato = 0
for elemento in combinada:
if (type(elemento) == int):
entero += 1
elif (type(elemento) == float):
flotante += 1
elif (type(elemento) == bool):
booleano += 1
elif (type(elemento) == str):
string += 1
else:
otro_dato += 1
# print("en la lista hay {} enteros, {} flotantes, {} booleanos, {} string y {} elementos de otro tipo de dato".format(entero,flotante,booleano,string,otro_dato))
# a = 5
# print(type(a))
# if (type(a) == str):
# print("Es entero")
# Tuplas => coleccion de elementos ordenada QUE NO SE PUEDE MODIFICAR, es inalterable y sirve para usar elementos que nunca se van a modificar
tupla_datos = (18, 3.1415, "root", True, 18)
# print(tupla_datos[1])
# Para sacar la longitud de la tupa
# print(len(tupla_datos))
# Para ver cuantas veces repetidas hay un dato
# print(tupla_datos.count("root"))
# print(type(tupla_datos))
# Conjuntos => Coleccion de elementos DESORDENADA, osea, no tiene indice para acceder a sus elementos
temporadas = {"otoño", "invierno", "primavera", "verano"}
# for temporada in temporadas:
# print(temporada)
# temporadas.add("otra temporada")
# print(temporadas)
# Diccionarios => por que tiene una gran similitud con los JSON (JavaScript Object Notation) SOAP y es la mejor forma de pasar los datos del frontend al backend, son colecciones de datos INDEXADOS, tiene una llave y un valor, no estan ordenados y se puede modificar sus valores
dias_semana= {
"lunes" : "aburrido",
"martes" : "cine",
"miercoles" : "pollo frito",
"jueves" : "pizza",
"viernes" : "fiesta",
"sabado" : "codigo",
"domingo" : "repaso"
}
print(dias_semana)
# para ver el valor de una clave en especifico
print(dias_semana["lunes"])
# para ver todas sus llaves (keys)
print(dias_semana.keys())
# para ver todos sus valores (values)
print(dias_semana.values())
# para agregar una nueva llave y su valor
dias_semana["otro_dia"]="No hay no existe"
print(dias_semana)
print(dias_semana.items())
for llave, valor in dias_semana.items():
print("El dia de la semana es {} y significa {}".format(llave, valor))
|
import time
import random
def print_pause(message):
print(message)
time.sleep(2)
# print and sleep 2 sec
def intro():
name = input("What is your name?\n")
# save the random choice to use it later
print_pause("You have arrived at your friend Mohammed's house")
print_pause("You knock on the door")
print_pause("Your friend asked who is there?")
print_pause("So you answered him I'm " + name)
print_pause("Mohammed: Hello, "+name+", welcome to my home")
print_pause("Come with me")
# introduction
def choice_drink(rooms, meals, choice_room, counter):
meals[1] = input("What do you want to drink?:\n"
"Water\n"
"Soda\n"
"Coffee\n").lower()
print_pause("After a few seconds ..")
if "water" == meals[1]:
print_pause("This is your water!")
elif "coffee" == meals[1]:
print_pause("This is your coffee!")
elif "soda" == meals[1]:
print_pause("This is your soda!")
else:
print_pause("Sorry, but I don’t have it")
choice_drink(rooms, meals, choice_room, counter)
# ask you about your drink and save it in meals[1]
def choice_dish(rooms, meals, choice_room, counter):
meals[0] = input("What do you prefer:\n"
"Pie\n"
"Sandwich?\n").lower()
print_pause("After a few seconds, ")
if "pie" == meals[0]:
print_pause("This is your Pie")
elif "sandwich" == meals[0]:
print_pause("This is your Sandwich")
else:
print_pause("Sorry, but I didn't prepare this meal")
choice_dish(rooms, meals, choice_room, counter)
# ask you about you meal then save it in meals[0]
def lights():
light = input("Do you prefer the light:\n"
"off\n"
"on\n").lower()
if "on" == light:
print_pause("Ok, I will keep it")
elif "off" == light:
print_pause("Ok, I turn it off")
else:
lights()
# ask you if you want a lights off or on
def living_room(rooms, meals, choice_room, counter):
print_pause("You are in the living room")
print_pause("Please sit down")
choice_drink(rooms, meals, choice_room, counter)
change_room(rooms, meals, choice_room, counter)
# You will stay in the livig room then go to the Kitchen
def kitchen(rooms, meals, choice_room, counter):
print_pause("You are in the Kitchen")
print_pause("Welcome, I prepared delicious meals for you")
choice_dish(rooms, meals, choice_room, counter)
choice_drink(rooms, meals, choice_room, counter)
change_room(rooms, meals, choice_room, counter)
# take a meal then go to the bedroom
def stairs(rooms, meals, choice_room, counter):
print_pause("Let's go upstairs")
print_pause("I know that you are tired after traveling")
print_pause("I have prepared the bedroom for you to take a rest")
print_pause("This is the bedroom")
lights()
change_room(rooms, meals, choice_room, counter)
# You will go to bedroom then to the living room
def rotation(rooms, meals, choice_room, counter):
if choice_room == "living_room":
living_room(rooms, meals, choice_room, counter)
elif choice_room == "stairs":
stairs(rooms, meals, choice_room, counter)
elif choice_room == "kitchen":
kitchen(rooms, meals, choice_room, counter)
# take you to the first room in your visit
def change_room(rooms, meals, choice_room, counter):
counter += 1
if choice_room == "living_room" and counter < 3:
choice_room = "kitchen"
kitchen(rooms, meals, choice_room, counter)
elif choice_room == "stairs" and counter < 3:
choice_room = "living_room"
living_room(rooms, meals, choice_room, counter)
elif choice_room == "kitchen" and counter < 3:
choice_room = "stairs"
stairs(rooms, meals, choice_room, counter)
else:
stay = input("Do you want to stay at home?:\n"
"Yes\n"
"No\n").lower()
if "yes" == stay:
counter = 0
rotation(rooms, meals, choice_room, counter)
elif "no" == stay:
print_pause("Ok, good bye!")
else:
change_room(rooms, meals, choice_room, counter)
# change your room
def visit_friend():
rooms = ["living_room", "stairs", "kitchen"]
meals = ["", ""]
choice_room = random.choice(rooms)
counter = 0
intro()
rotation(rooms, meals, choice_room, counter)
visit_friend()
|
import sys # importing system function for exit with error
from math import * # importing math functions
import matplotlib
import matplotlib.pyplot as plt #imprting graph functions
import numpy as np
#main function
def fit_linear(fileName): # main function. this function input is a text file of data and output is a fitting parametes and a saved graph
fileData = reading_file(fileName) # calling readig data function
dataDict = prepareInput(fileData) #calling the function that makes dictionary from the data
dataDict = calcAllParametes(dataDict) #calling the function that calculate the parameters and adds them to the Dict
printAllParameters(dataDict) #calling the function that prints the parameters
drawLine(dataDict) #calling the function that save the graph
#functions for part 1
#this function reads the data from notepad. input is a file name as a string including .filetype and output is a list of strings
def reading_file(file_input):
file_pointer=open(file_input)
data=file_pointer.readlines()
file_pointer.close()
final=[]
for string in data:
string_1=string.lower()[:] #taking only small letters
string_2=string_1.replace("\n","")[:] # removing \n
final.append(string_2)
return final
#this function creats the data dictionary, input is list of strings and output is a dictionary
def prepareInput(data):
temp = stringToList(data) #calling the function that makes the strings to lists
if (isDataMissing(temp)): #checking that each row of data as the same length
exitOnError("Input file error: Data lists are not the same length.")
else:
if isDataCols(temp): # taking data for cols input
dataDict = prepareDataFromCols(temp)
else: # taking data for rows input
dataDict = prepareDataFromRows(temp)
dataDict = addLabelsOfAxis(data, dataDict) #adding the labels
if isErrorZero(dataDict): #checking that thera are no none positve error
exitOnError("Input file error: Not all uncertainties are positive.")
return dataDict
#this function turns the strings into lists input data as a list
def stringToList(data):
temp=[]
for x in range(0,len(data)-3):
split_1=data[x].split(" ")
real_split=[]
for y in split_1: #remove extra spaces
if y!='':
real_split.append(y)
temp.append(real_split)
return temp
#this function check if there is data missing. input is data before it's a dict
def isDataMissing(data):
isMissing = False
dataLength = len(data[0])
for x in data:
if len(x) != dataLength:
isMissing = True
break
return isMissing
# this function Checkes if dx or dy are non positive
def isErrorZero(dataDict):
hasNonPositive = False
for x in dataDict['dx']:
if x <= 0:
hasNonPositive = True
break
if not hasNonPositive:
for x in dataDict['dy']:
if x <= 0:
hasNonPositive = True
break
return hasNonPositive
#this function Checks the structure of the data
def isDataCols(data):
if data[0][1]=='dx' or data[0][1]=='dy' or data[0][1]=='x' or data[0][1]=='y':
return True
else:
return False;
#this function creats dict from the data if the stracture is cols
def prepareDataFromCols(data):
data_dict={}
for y in [0, 1, 2, 3]:
list_values = [] # temporary var
for x in range(1, len(data)):
value = float(data[x][y])
list_values.append(value)
data_dict[data[0][y]] = list_values
return data_dict
#this function creats dict from the data if the stracture is rows
def prepareDataFromRows(data):
data_dict={}
for x in data:
list_values = [] # temporary var
for y in range(1, len(x)):
value = float(x[y])
list_values.append(value)
data_dict[x[0]] = list_values
return data_dict
#this function adds the axis names to the dict
def addLabelsOfAxis(data, data_dict):
x_axis = data[len(data) - 2][8:] # keep the x axis
y_axis = data[len(data) - 1][8:] # keep the y axis
data_dict["x_axis"] = x_axis # appendig to dict
data_dict["y_axis"] = y_axis # apendding to dict
return data_dict
#this function ouput error message. input is a string
def exitOnError(errorDescription):
sys.exit(errorDescription) #this is a function from phyton libary
#functions for part 2
#this functin takes list of values and list of errors and return the bar of the list
def xBar(x,dy):
sum_1=0
for z in range(0,len(x)):
sum_1=sum_1+x[z]/((dy[z]*dy[z]))
sum_2=0
for z in range(0,len(x)):
sum_2=sum_2+1/((dy[z]*dy[z]))
xbar=sum_1/sum_2
return xbar
#this function takes two lists with the same length and returns a list of the multplyiction of every elemnt in each list
def list_mult(x,y):
output=[]
for z in range(0,len(x)):
temp=x[z]*y[z]
output.append(temp)
return output
#this functin calculates a parmeter in the linear function y=ax +b.
def calc_a(x,y,dy):
xy=list_mult(x,y)
x_2=list_mult(x,x)
x_bar=xBar(x,dy)
x_2_bar=xBar(x_2,dy)
xy_bar=xBar(xy,dy)
y_bar=xBar(y,dy)
a=(xy_bar-x_bar*y_bar)/(x_2_bar-x_bar*x_bar)
return a
#this function calculates b parmeter in the linear functio y=ax +b.
def calc_b(x,y,dy):
y_bar=xBar(y,dy)
x_bar=xBar(x,dy)
a=calc_a(x,y,dy)
b=y_bar-a*x_bar
return b
#this function calculates the error in the parameter a
def calc_da(x,dy):
dy_2=list_mult(dy,dy)
x_2=list_mult(x,x)
x_2_bar=xBar(x_2,dy)
dy_2_bar=xBar(dy_2,dy)
x_bar=xBar(x,dy)
da=sqrt(dy_2_bar/(len(x)*(x_2_bar-x_bar*x_bar)))
return da
#this function calculates the error in the parameter b
def calc_db(x,dy):
dy_2=list_mult(dy,dy)
x_2=list_mult(x,x)
x_2_bar=xBar(x_2,dy)
dy_2_bar=xBar(dy_2,dy)
x_bar=xBar(x,dy)
db=sqrt((dy_2_bar*x_2_bar)/(len(x)*(x_2_bar-x_bar*x_bar)))
return db
#this function calculates the chi squere - for a and b.
def calc_chi(a,b,x,y,dy):
s=0
for z in range(0,len(x)):
s=s+((y[z]-a*x[z]-b)/dy[z])**2
return s
#this function calculates reduce chi
def calc_chi_red(chi,x):
chi_red=chi/(len(x)-2)
return chi_red
#this function calculates all needed parametes and adds them to the data dictionary
def calcAllParametes(dataDict):
x=dataDict['x']
y=dataDict['y']
dy=dataDict['dy']
a=calc_a(x,y,dy)
b = calc_b(x, y, dy)
da=calc_da(x,dy)
db = calc_db(x, dy)
chi=calc_chi(a,b,x,y,dy)
chi_red=calc_chi_red(chi,x)
dataDict['a']=a
dataDict['b']=b
dataDict['da']=da
dataDict['db']=db
dataDict['chi']=chi
dataDict['chi_red']=chi_red
return dataDict
#this function print all of the parameters
def printAllParameters(datDict):
print('a=',datDict['a'],'+-',datDict['da'],sep='')
print('b=',datDict['b'],'+-',datDict['db'],sep='')
print('chi2=',datDict['chi'],sep='')
print('chi2_reduced=',datDict['chi_red'],sep='')
#functions for part 3
#this function draws the graph and saves it
def drawLine(dataDict):
x = np.linspace(min(dataDict['x']),max(dataDict['x'])) #creating a line space for the length of the data
y = dataDict['a']*x+dataDict['b'] #calc y according to the parameters
plt.xlabel(dataDict['x_axis']) #plotting labels
plt.ylabel(dataDict['y_axis'])
plt.plot(x, y,color='red') #plot the line
x = dataDict['x']
y = dataDict['y']
dy = dataDict['dy']
dx = dataDict['dx']
plt.errorbar(x, y,xerr=dx, yerr=dy, fmt='b,') #plotting error bars
plt.savefig('linear_fit.SVG') #saving the data
|
'''
Crie um programa que leia dois valores e mostre um menu como abaixo:
[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
menu = 0
n1 = 0
n2 = 0
n1 = int(input('Digite um numero: '))
n2 = int(input('Digite outro numero: '))
while menu != 5:
sleep(2)
menu = int(input(''' \n [1] SOMAR \n [2] MULTIPLICAR \n [3] MAIOR \n [4] NOVOS NÚMEROS \n [5] SAIR DO PROGRAMA \n '''))
if menu == 1:
soma = n1 + n2
print('A soma entre {} + {} é {}.'.format(n1, n2, soma))
elif menu == 2:
multiplica = n1 * n2
print('A multiplição de {} x {} é {}.'.format(n1, n2, multiplica))
elif menu == 3:
if n1 > n2:
maior = n1
else:
maior = n2
print('O númeiro maior entre {} e {} é {}'.format(n1, n2, maior))
elif menu == 4:
n1 = int(input('Digite um número: '))
n2 = int(input('Digite outro número: \n'))
else:
if menu != 5:
print('Função inválida! Digite novamente.')
print('Finalizando...')
sleep(2)
print('Obrigado! Volte sempre!')
|
'''
Crie um programa que leia vários números inteiros pelo teclado. No final da execução, mostre a média entre todos
os valores e qual foi o maior e o menor valor lido. O programa deve perguntar ao usuário se ele quer ou não continuar
a digitar valores.
'''
continua = True
soma = media = cont = maior = menor = 0
opcao = ''
while continua == True:
numero = int(input('Digite um número: '))
cont += 1
soma += numero
if cont == 1: # Não esquecer este flag
maior = menor = numero
else:
if numero > maior:
maior = numero
elif numero < menor:
menor = numero
opcao = str(input('Deseja continuar [S/N]: ').upper()).strip()[0] # Consideta só a primeira letra
if opcao == 'N':
continua = False
media = soma / cont
print('A média dos {} valores digitados é {}'.format(cont, media))
print('O maior valor digitado foi {} e o menor foi {}'.format(maior, menor))
|
'''
Refaça o Desafio 035 dos triângulos, acrescetando o recurso de mostrar que tipo de triângulo será formado:
- Equilátero: todos os lados iguais
- Isósceles: doios lados iguais
- Escaleno: todos os lados diferentes
'''
r1 = float(input('Digite o primeiro segmento da reta: '))
r2 = float(input('Digitel o segundo segmento da reta: '))
r3 = float(input('Digite o terceiro segmento da reta: '))
if r1 < (r2 + r3) and r2 < (r1 + r3) and r3 < (r2 + r1):
print('As retas {}, {} e {} formam um triângulo'.format(r1, r2, r3), end=' ')
if r1 == r2 == r3:
print('EQUILATERO')
elif r1 != r2 != r3 != r1:
print('ESCALENO')
else:
print('ISÓSCELES')
else:
print('As retas acima NÂO podem formar um triângulo!')
|
'''
Crie um programa que vai ler vários números e colocar em uma lista. Depois disso, crie duas lista extras que vão
contar apenas os valores pares e os valores ímpares digitados, respectivamente. Ao final, mostre o conteúdo das
três listas geradas.
'''
numeros = list()
impar = list()
par = list()
while True:
numeros.append(int(input('Digite um número:')))
sn = ' '
while sn not in 'SN':
sn = str(input('Deseja continuar? [S/N]')).upper().strip()[0]
if sn == 'N':
break
for i, v in enumerate(numeros):
if v % 2 == 0:
par.append(v)
else:
impar.append(v)
print(f'A lista digitada foi {numeros}')
print(f'A lista de números pares é {par}')
print(f'A lista de númeors ímpares é {impar}')
|
''' Faça um programa que calcule a soma entre todos os números impares que são múltiplos de três e que se
encontram no intervalo de 1 até 500. '''
soma = 0
conta = 0
for count in range(1, 501, 2):
if count % 3 == 0:
conta += 1
soma += count
print('A soma de todos os valores {} solicitados é {}'.format(conta, soma))
|
''' Desenvolva um programa que leia o primeiro termo e a razão de uma PA.
No final, mostre os 10 primeiros termos dessa progressão '''
primeiro = int(input('Digite o primeiro termo: '))
razao = int(input('Digite a razão: '))
décimo = primeiro + (10 - 1) * razao
for c in range(primeiro, décimo + razao, razao):
print('{}'.format(c), end=' -> ')
print('ACABOU')
|
# Faça um programa que leia um número interio e mostre na tela o seu sucessor e seu antecessor.
n1 = int(input('Digite um numero: '))
#print('O numero digitado foi {}'.format(n1))
#print('Seu sucessor é {} e seu antecessor é {}'.format((n1 + 1), (n1 - 1)))
print('Analisando o numero digitado {}, o seu antecessor é {} e o seu sucesso é {}'.format((n1), (n1-1), (n1+ 1)))
|
'''
Faça um programa que leia o ano de nascimento de um jovem e informe, de acordo com sua idade, se ele ainda vai se alistar ao serviço militar,
se é a hora de se alista ou se já passou do tempo de alistamento.
Seu programa também deverá mostrar o tempo que falta ou que passsou do prazo.
'''
from datetime import date
dt_nascto = int(input('Informe o ano do seu nascimento: '))
sexo = str(input('Informe o seu sexo: '))
dt_atual = date.today().year
idade = dt_atual - dt_nascto
if sexo == 'Feminino':
print('Voce é mulher e não presica se alistar! Tenna um bom dia!')
elif idade < 18:
print('Voce ainda tem {} anos, e seu alistamento será daqui a {} anos.'.format(idade, 18 - idade))
elif idade == 18:
print('Você já tem {} anos, se deverá se alistar ainda este ano!'.format(idade))
else:
print('Você ja tem {} anos, e deveria ter se alistado a {} anos atrás'.format(idade, idade - 18))
|
''' Escvreva um programa para aprovar o empréstimo bancário para a compra de uma casa. Pergunte o valor da casa, o salário do comprador e em
quantos anos ele vai pagar.
A prestação não pode exceder 30% do salário ou então o empréstimo será negado.
'''
vlr_casa = float(input('Qual o valor da casa R$ '))
salario = float(input('Qual o seu salário R$ '))
anos = int(input('Em quantos anos você irá pagar? '))
prestacao = salario * 30 /100
financiamanto = vlr_casa / (anos * 12)
if financiamanto > prestacao:
print('Financiamento NEGADO!')
else:
print('Financiamento APROVADO')
|
#CTI 110
#M6T1 Kilometer Converter
#Jeffrey Lee
# Oct 24 2017
#Write a program that asks the user to enter a distance in kilometers
#then converts that distance to miles
#the conversion formula:Miles = Kilometers * 0.6214
#create two functions for this program
#main() function
#show_miles()function that takes km as a parameter
#converts to miles, and prints the answer
CONVERSION_FACTOR = 0.6214
def main():
kilometers = float(input('Enter distance in kilometers: '))
show_miles(kilometers)
def show_miles(km):
miles = km * CONVERSION_FACTOR
print(km, 'kilometers equals', miles, 'miles.')
main()
|
#CTI 110
#M6Lab Age and name
#Jeffrey Lee
#1 Nov 2017
#Write a program that will ask the user their name and then ask their age.
#The program should then greet them by name, and tell them their age
#infant, child, teenager, or adult
#main() which is a void function
#greet(name) which is a void function
#ageCategory(age) which returns a string
name = input("what is your name? ")
Age = int( input( "Please enter your age: " ))
def hello():
print('Hello!')
hello()
def print_welcome(name):
print('Welcome', name)
print_welcome(name)
print("Nice to meet you")
if Age <= 1:
print( "You are an infant" )
elif Age < 13:
print( "You are a child" )
elif Age < 20:
print( "You are a teenager" )
elif Age >= 20:
print( "You are an adult" )
|
import csv, json
import tkinter as tk
from tkinter import ttk
from tkinter import filedialog as fd
from tkinter.messagebox import showinfo
# root window
root = tk.Tk()
root.title('CSV to JSON File Dialog')
root.resizable(False, False)
root.geometry('300x150')
def convert(file):
with open(file, encoding='utf-8') as csvfile, open('csv_converted.json', 'w', encoding='utf-8') as jsonfile:
json_data = []
csv_reader = csv.DictReader(csvfile, delimiter=';')
for line in csv_reader:
json_data.append(line)
json.dump(json_data, jsonfile, sort_keys=True, indent=4, ensure_ascii=False, separators=(',', ': '))
def select_file():
filetypes = (
('csv files', '*.csv'),
('All files', '*.*')
)
filename = fd.askopenfilename(
title = 'Open a file',
initialdir = '/Users/Carl_/Desktop/python-elective/ses11_context-managers/',
filetypes = filetypes
)
showinfo(
title = 'Converting Selected File',
message=filename,
command=convert(filename)
)
return filename
open_button = ttk.Button(
root,
text = 'Open a File',
command = select_file
)
open_button.pack(expand=True)
root.mainloop()
|
"""
Based on this list of tuples: [(1,2),(2,2),(3,2),(2,1),(2,2),(1,5), (10,4), (10, 1), (3, 1)]
Sort the list so the result looks like this: [(2, 1), (3, 1), (10, 1), (1, 2), (2, 2), (2, 2), (3, 2), (10, 4), (1, 5)]
"""
t = [(1,2),(2,2),(3,2),(2,1),(2,2),(1,5), (10,4), (10, 1), (3, 1)]
# sorting first by last value of tuple, then by first value of tuple
print(sorted(t, key = lambda x: (x[-1], x[0])))
|
# %%
# From 2 lists, using a list comprehension, create a list containing:
# [('Black', 's'), ('Black', 'm'), ('Black', 'l'), ('Black', 'xl'),
# ('White', 's'), ('White', 'm'), ('White', 'l'), ('White', 'xl')]
# colors = ['Black', 'White']
# sizes = ['s', 'm', 'l', 'xl']
colors = ['Black', 'White']
sizes = ['s', 'm', 'l', 'xl']
[ (c, s) for c in colors for s in sizes ]
# %%
# If the tuple pair is in the following list, it should not be added to the comprehension generated list.
# soled_out = [('Black', 'm'), ('White', 's')]
soled_out = [('Black', 'm'), ('White', 's')]
[ (c, s) for c in colors for s in sizes if (c, s) not in soled_out ]
# %%
|
import time
""" Create a decorator function that slows down your code by 1 second for
each step. Call this function slowdown()
For this you should use the ‘time’ module.
When you got the ‘slowdown code’ working on this recursive function,
try to create a more (for you) normal function that does the
countdown using a loop, and see what happens if you
decorate that function with you slowdown() function. """
def slowdown(func):
def wrapper(n):
time.sleep(1)
return func(n)
return wrapper
@slowdown
def countdown(n):
if not n: # 0 is false, not false is true
return n
else:
print(n, end=' ')
return countdown(n-1) # call the same function with n as one less
@slowdown
def countdown_iter(n):
for i in reversed(range(n+1)):
print(i, end=' ')
|
#######################################################################################################################
"""
------------------
DATA PREPROCESSING
------------------
"""
#######################################################################################################################
# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Importing the training set
dataset_train = pd.read_csv('Google_Stock_Price_Train.csv')
training_set = dataset_train.iloc[:, 1:2].values # we take range 1:2 because we want a numpy array not just a vector
# For simplicity we use just 1 data column but also check out: https://www.udemy.com/deeplearning/learn/v4/questions/3554002
# Feature Scaling
# We use Normalisation in RNNs especially if the activation function is a sigmoid
from sklearn.preprocessing import MinMaxScaler
sc = MinMaxScaler(feature_range = (0, 1))
training_set_scaled = sc.fit_transform(training_set) # we use a new var so that we can keep the original dataset
# Creating a data structure with 60 timesteps and 1 output
"""
• At each time T the RNN is going to look at the 60 stock prices before time T and based on the trends
that is capturing during these 60 previous time steps it's going to predixct the next step
• 60 is something we can up after testing, 1 would be overfitting etc.
• https://www.udemy.com/deeplearning/learn/v4/t/lecture/8374802?start=0
"""
X_train = []
y_train = []
for i in range(60, 1258):
X_train.append(training_set_scaled[i-60:i, 0])
y_train.append(training_set_scaled[i, 0])
X_train, y_train = np.array(X_train), np.array(y_train) # we make the vars numpy arrays so they'll be accepted by the RNN
# Reshaping - adding a new dimension to the numpy array
"""
• X_train.shape[0] is the number of rows in the dataset
• X_train.shape[1] is the number of columns in the dataset.
"""
X_train = np.reshape(X_train, (X_train.shape[0], X_train.shape[1], 1))
#######################################################################################################################
"""
------------------------------
RECURRENT NEURAL NETWORK (RNN)
------------------------------
• https://www.superdatascience.com/the-ultimate-guide-to-recurrent-neural-networks-rnn/
• https://www.superdatascience.com/ppt-the-ultimate-guide-to-recurrent-neural-networks-rnn/
• Used for time series analysis
• It's a supervised learning method, it's like a short term memory
• Applications: https://i.imgur.com/xHp8eD6.png (one to many, many to one, many to many)
VANISHING GRADIENT
------------------
• https://www.udemy.com/deeplearning/learn/v4/t/lecture/6820148?start=0
• https://i.imgur.com/iag13pq.png
• When unrevaling the temporal loop the further you go through your network the lower the gradient is and it's harder to train the weights
• Solutions for the problem:
Exploding Gradient
Truncated Backpropagation
Penalties
Gradient clipoing
Vanishing Gradient
Weight initialization
Echo state networks
LSTM
LONG SHORT-TERM MEMORY (LSTM)
-----------------------------
• https://www.udemy.com/deeplearning/learn/v4/t/lecture/6820150?start=0
• Visual: https://i.imgur.com/xJnVxiE.png
• http://colah.github.io/posts/2015-08-Understanding-LSTMs/
• Practical intuition: https://www.udemy.com/deeplearning/learn/v4/t/lecture/6820154?start=0
• https://arxiv.org/pdf/1506.02078.pdf
• http://karpathy.github.io/2015/05/21/rnn-effectiveness/
LSTM VARIATIONS
---------------
• https://www.udemy.com/deeplearning/learn/v4/t/lecture/6820164?start=0
• Adding peepholes
• Connecting Forget Valve and Memory Valve
• Gated recurring units (GRUs) - quite popular - getting rid of the memory cell
"""
#######################################################################################################################
# Importing the Keras libraries and packages
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import LSTM
from keras.layers import Dropout
# Initialising the RNN
regressor = Sequential()
"""
Dropout regularisation is to prevent overfitting: https://www.udemy.com/deeplearning/learn/v4/questions/2597526
units = number of LSTM cells
return_sequences = True (for the last layer we need to set it to False but False is the default value so we can leave it out)
input_shape = input shape in 3D - see reshape from above (we emit the first value)
"""
# Adding the first LSTM layer and some Dropout regularisation
regressor.add(LSTM(units = 50, return_sequences = True, input_shape = (X_train.shape[1], 1)))
regressor.add(Dropout(0.2))
# Adding a second LSTM layer and some Dropout regularisation
regressor.add(LSTM(units = 50, return_sequences = True))
regressor.add(Dropout(0.2))
# Adding a third LSTM layer and some Dropout regularisation
regressor.add(LSTM(units = 50, return_sequences = True))
regressor.add(Dropout(0.2))
# Adding a fourth LSTM layer and some Dropout regularisation
regressor.add(LSTM(units = 50))
regressor.add(Dropout(0.2))
# Adding the output layer
regressor.add(Dense(units = 1))
# Compiling the RNN
regressor.compile(optimizer = 'adam', loss = 'mean_squared_error')
# Fitting the RNN to the Training set
regressor.fit(X_train, y_train, epochs = 100, batch_size = 32)
# Making the predictions and visualising the results
# Getting the real stock price of 2017
dataset_test = pd.read_csv('Google_Stock_Price_Test.csv')
real_stock_price = dataset_test.iloc[:, 1:2].values
# Getting the predicted stock price of 2017
# https://www.udemy.com/deeplearning/learn/v4/t/lecture/8374820?start=0
dataset_total = pd.concat((dataset_train['Open'], dataset_test['Open']), axis = 0) # axis = concat on vertical axis, horizontal is 1
inputs = dataset_total[len(dataset_total) - len(dataset_test) - 60:].values
inputs = inputs.reshape(-1,1) # we haven't used the iloc so we need this formating/reshaping step
inputs = sc.transform(inputs) # scaling
X_test = []
for i in range(60, 80):
X_test.append(inputs[i-60:i, 0])
X_test = np.array(X_test)
X_test = np.reshape(X_test, (X_test.shape[0], X_test.shape[1], 1))
predicted_stock_price = regressor.predict(X_test)
predicted_stock_price = sc.inverse_transform(predicted_stock_price) #inversing the scaled values
# Visualising the results
plt.plot(real_stock_price, color = 'red', label = 'Real Google Stock Price')
plt.plot(predicted_stock_price, color = 'blue', label = 'Predicted Google Stock Price')
plt.title('Google Stock Price Prediction')
plt.xlabel('Time')
plt.ylabel('Google Stock Price')
plt.legend()
plt.show()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.