text
stringlengths
37
1.41M
um=input() if(um=='Saturday' or um=='Sunday'): print("yes") else: print("no")
# Inicializar un arreglo de 5 elementos en cero y mostrarlo ''' a = [0,0,0,0,0] for i in a: print("\t", a[i], end="") ''' # Operacion con arreglos # Cargar elementos ''' a = [] n = int(input("Ingrese la cantidad de elementos del vector: ")) for i in range(0,n,1): a.append(int(input("Ingrese el valor de cada elemento \t"))) print(a) ''' # Recorrer un arreglo # Sumar los elemento del arreglo ''' n = [2,4,55,6,8] sum = 0 for i in range(0,len(n),1): sum = sum + n[i] print(sum) ''' # Mostrar un arreglo ''' n = [2,4,55,6,8] for i in range(0,len(n)): print("Elemento %d: %d" %(i,n[i])) ''' # Buscar un elemento en un arreglo ''' a = [] n = int(input("Ingrese la cantidad de elemento del vector: ")) for i in range(0,n): a.append(int(input("Ingrese el valor de cada elemento: "))) for i in range(0,n): print("Elemento %d: %d" %(i,a[i])) i=0 while (i<n and a[i]%3!=0): i = i+1 if i==n: print("El vector no tiene ningun elemento multiplo de 3") else: print("El primer multiplo de 3 esta en la posicion %d y es %d" %(i,a[i])) ''' # Intercambiar dos elementos del arreglo ''' a = [1,2] aux = a[1] print(a) a[1] = a[0] a[0] = aux print(a) ''' # Otras operacion con arreglos # Insert: permite insertar un valor en una posicion determinada, desplazando los elementos que estan a la derecha del mismo # Ej 1 ''' a = [2,23,4,5] print(a) a.insert(2,44) print(a) ''' # Ej 2 ''' a = [] n = int(input("Ingrese la cantidad de elemento del vector: ")) for i in range(0,n): a.append(int(input("Ingrese el valor de cada elemento: "))) print(a) m = int(input("Ingrese el valor a ingresar: ")) pos = int(input("Ingrese la posicion donde va a insertar en nuevo elemento: ")) a.insert(pos,m) print(a) for i in range(0,len(a)): print(a[i]) ''' # Reverse: permite invertir los elementos del arreglo ''' a = [1,2,3,4,5] print(a) a.reverse() print(a) ''' # Sort: permite ordenar un arreglo en forma creciente ''' a = [] n = int(input("Ingrese la cantidad de elemento del vector: ")) for i in range(0,n): a.append(int(input("Ingrese el valor a ingresar: "))) print(a) a.sort() print(a) # NOTA: para ordenar un arreglo de forma decreciente podemos utilizar sort() y luego reverse() a.reverse() print(a) ''' # Remove: permite eliminar un elemento determinado del arreglo # array.remove(valor) ''' a = [2,5,66,7,8,13] print(a) a.remove(66) print(a) ''' # Pop: permite eliminar el elemento de un arreglo por su posicion y devuelve el elemento eliminado # array.pop(pos) ''' a = [2,5,66,74,12,77765,8,15] print(a) a.pop(3) print(a) ''' # Como pasar arreglos como argumento en funciones ''' def sumar(n,arr): suma = 0 for i in range(0,len(arr)): suma = suma + arr[i] return suma # Programa principal arr = [4,5,2,15] suma = sumar(len(arr),arr) print("La suma de los elementos del vector es: %d" %suma) ''' x = lambda a : a + 10 print(x(5)) x = lambda a, b : a * b print(x(5, 6))
def get_third_place_order(group_dict: dict) -> list: """ Collect the 'order' in which the best four third placed teams in the group stage play their round of 16. The 'first' team faces the winner of Group B, the 'second' team the winner of Group F, the 'third' team the winner of group E, and the 'fourth' team the winner of Group C in the round of sixteen :param group_dict: a dictionary consisting of group name and third placed team, ordered by the team that scored the most points :return: list of teams in the above mentioned order """ # Collect four groups with best number 3 group_list = list(group_dict.keys())[:4] # Order this list by alphabet group_list = sorted(group_list) # Add the group names to form a code third_code = "".join(group_list) codes_to_order = { 'ABCD': ['A', 'D', 'B', 'C'], 'ABCE': ['A', 'E', 'B', 'C'], 'ABCF': ['A', 'F', 'B', 'C'], 'ABDE': ['D', 'E', 'A', 'B'], 'ABDF': ['D', 'F', 'A', 'B'], 'ABEF': ['E', 'F', 'B', 'A'], 'ACDE': ['E', 'D', 'C', 'A'], 'ACDF': ['F', 'D', 'C', 'A'], 'ACEF': ['E', 'F', 'C', 'A'], 'ADEF': ['E', 'F', 'D', 'A'], 'BCDE': ['E', 'D', 'B', 'C'], 'BCDF': ['F', 'D', 'C', 'B'], 'BCEF': ['B', 'C', 'E', 'F'], 'BDEF': ['F', 'E', 'D', 'B'], 'CDEF': ['F', 'E', 'D', 'C'] } new_group_list = codes_to_order[third_code] country_list = [group_dict[idx] for idx in new_group_list] return country_list
from ParachuteModel import ParachuteModel class ParachuteController: def __init__(self): self.parachute_model = None def set_model(self, model: ParachuteModel): if model is None: raise Exception("Invalid model") self.parachute_model = model def fall(self): """ at fist i had controller for each parachute, however since we our parachutes are pretty much identical i thought of controller more like a monitor(watching and the parachuter model more like a generator """ for parachute in self.parachute_model.get_parachutes(): x, y = parachute.get_position() parachute.set_position(x, y + parachute.get_speed())
""" Porgram ryzujący trójkąt prosokątny o zadanej długości boku """ dlugosc_przyprostokatnej = int(input('Podaj dłuygośc przyprostokątnej: ')) spacja = ' ' gwiazdka = '*' i = 0 while i < dlugosc_przyprostokatnej: if i == 0: print('*') elif i > 0 and i < dlugosc_przyprostokatnej-1: print(f'*{spacja*i}*') elif i == dlugosc_przyprostokatnej-1: print(dlugosc_przyprostokatnej * gwiazdka) i += 1
""" Program obliczający średnią wartość z podanych przez Usera do przechowaniaaliczb uzyć listy max licba wprowadzeń to 10 skoerzystać z funkcji sum() """ wejscie= [] licznik=0 len_liczby =10 while licznik<10: #pobranie danyc do tabeli w pętli wejscie.append(input(f'Podaj liczbe nr {licznik+1}: ')) licznik += 1 else: # warunek max 10 liczb print ('wprowadzileś maksymalną ilość liczb') # break srednia = sum(wejscie)/len(wejscie) print(f'Srednia z wprowadz liczb to: {srednia}')
# implementacja metody Basketumożliwiającą doadanie porduktu do koszyka class Product: def __init__(self, id, name, price): self.product_ID = id self.product_name = name self.product_price = price def print_info(self): return f'Produkt"{self.product_name}", id: {self.product_ID}, cena: {self.product_price}' class BasketEntry: def __init__(self,product, quantity): self.product = product self.quantity = quantity def count_price(self): return self.product.product_price*self.quantity class Basket(object): def __init__(self): self.position_on_list = None self.sum_ = 0 def add_product(self,product, quantity): self.entries.append(product,quantity) def __str__(self): return "Basket" def count_total_price(self): sum= 0 for e in self.fentries: sum+=e.product.price*e.quantity return sum def test_product_print_info(): product = Product(1, 'Woda', 10.00) product.print_info ()== 1, 'Woda', 10.00 def test_create_basket(): basket = Basket() assert str(basket) == "Basket" assert basket.entries == [] def test_add_produkt_to_basket(): basket= Basket() product = Product(1, 'woda',10) basket.add_product(product,5) def test_basket_enntry_count_price (): be=BasketEntry(Product(1,"Woda",2),5) assert be.count_price() == 00 def test_basket_count_total_price (): basket = Basket() product = Product(1, 'woda',10) basket.add_product(product,5) assert count_total_price() == 50 def test_basket_generate_report(): assert basket.generate_report() == 'Produkty w koszyku: \n- Woda (1), cena: 10.00 x 5 \nW sumie: 50.00' # assert len(basket(entries)) == 1
tekst_wejsciowy = input('Podaj tekst do wypowiedzenia dla jąkały: ') iteracja = 0 iteracja_wewnatrz = 0 tekst_wyjscie = list(tekst_wejsciowy) for znak in tekst_wejsciowy: if (iteracja %2)!=0: #del tekst_wyjscie[iteracja] tekst_wyjscie.insert((iteracja+iteracja_wewnatrz), znak) iteracja_wewnatrz +=1 iteracja += 1 print(''.join(tekst_wyjscie)) print(f"tekst po transformacji: {''.join(tekst_wyjscie)}")
''' Woda zamarza przy 32 stopniach Fahrenheita, a wrze przy 212 stopniach Fahrenheita. Napisz program "stopnie.py", który wyświetli tabelę przeliczeń stopni Celsjusza na stopnie Fahrenheita w zakresie od –20 do +40 stopni Celsjusza (co 5 stopni). Pamiętaj o wyświetlaniu znaku plus/minus przy temperaturze. [ºC]=([ºF]-32)*5/9 ''' stopnie_celsjusz = -20 stopnie_fahrenheit = None while stopnie_celsjusz <= 40: stopnie_fahrenheit = stopnie_celsjusz*(9/5)+32 print (f'{stopnie_celsjusz}[ºC] - {stopnie_fahrenheit}[ºF]') stopnie_celsjusz += 5
# 9.12: .groupby(): custom 'summary' function using # .apply(). Group rows by 'SalesRep' and use .apply() with a # function that expects a DataFrame of grouped rows and # returns the sum of 'SaleAmount' from the DataFrame. (In # other words, this replicates what .groupby().sum() does). import pandas as pd def price_sum(this_df): return # your code here df = pd.read_excel("../sales-funnel.xlsx") print(df.groupby('SalesRep').apply(price_sum))
# 8.29: Use .set_index() to set the a column for the student # DataFrame as the index for the DataFrame. (This method # returns the new, modified DataFrame.) import pandas as pd df = pd.DataFrame({ 'a': [1, 2, 3], 'b': [2.9, 3.5, 4.9], 'c': ['yourstr', 'mystr', 'theirstr'] }, index=['r1', 'r2', 'r3'])
# 3.18: BeautifulSoup object: the below code reads a string # read from an html file and parses the file and its tags into # a BeautifulSoup object. # Explore the following attributes of the object named 'soup': # * print the type of the object # * print the object itself # * print the .text attribute # from bs4 import BeautifulSoup scrapee = '../dormouse.html' text = open(scrapee).read() soup = BeautifulSoup(text, 'html.parser') # Note that you may occasionally encounter a # UnicodeDecodeError when you attempt to read a file from the # internet. In these cases you should tell Python which # encoding to use: text = open(scrapee, encoding='utf-8')
# 5.19: Convert another function to lambda. # The below function by_last_float() takes a string argument # and returns a portion of that string (converted to float) as # return value. Replace this function with a lambda. revenue = '../revenue.csv' def by_last_float(line): words = line.split(',') return float(words[-1]) fh = open(revenue) lines = fh.readlines() for line in sorted(lines, key= # your lambda function here): line = line.rstrip() print line
# 8.41: Use .isin() (with the Series as argument) in a filter # to show only those rows where the 'c' value is 'yourstr' or # 'mystr'. import pandas as pd df = pd.DataFrame({ 'a': [1, 2, 3], 'b': [2.9, 3.5, 4.9], 'c': ['yourstr', 'mystr', 'theirstr'] }, index=['r1', 'r2', 'r3'])
# 6.8: Create an __init__() method. # Add a method to the below class, __init__(self) that inside # the function announces and prints the argument self, i.e. # print(f'self: {self}'). # # Construct 2 new instances, and then print each instance. # Put a blank line between each instance. class Be: """ this class is something! """ obj1 = Be() print(f'object: {obj1}') print() obj2 = Be() print(f'object: {obj2}) # Expected Output: # object: <__main__.Be object at 0x10d648250> # self: <__main__.Be object at 0x10d648250> # # object: <__main__.Be object at 0x10d648a50> # self: <__main__.Be object at 0x10d648a50> # (Note that the above 0x hex codes will not be the same as # mine, but the values in each pair should match.)
# 3.29: Use str.encode() and bytes.decode() to convert a # string to a bytestring and back to string. # greet.encode() should include an encoding ('ascii', # 'latin-1' or 'utf-8'): greet = 'Hello, world!' bytestr = greet.encode(# add encoding here) print(bytestr) # subscript the bytestring to see individual characters # now call bytestr.decode() with the same encoding to see the string again
# 8.24: Print the .index and .columns attributes on this # DataFrame import pandas as pd df = pd.DataFrame({ 'a': [1, 2, 3], 'b': [2.9, 3.5, 4.9], 'c': ['yourstr', 'mystr', 'theirstr'] }, index=['r1', 'r2', 'r3'])
# 1.4: Loop through a file, split out a column and append to # a list. Before the loop begins, initialize an empty list. # Perform the same operations as in previous, but add each id # value (the first field value in each line) to the list. fname = '../student_db.txt' fh = open(fname) headers = next(fh) # retrieve next (first) line from file for line in fh: line = line.rstrip() items = line.split(':')
# 2.23: Result set: .fetchmany(). Use the cursor object to # .execute() a SELECT query for all columns in the revenue # table. Use .fetchmany(3) to retrieve just 3 rows, then use # .fetchmany(4) again to retrieve the remaining 4 rows. Close # the database connection when done. import sqlite3 db_filename = '../session_2.db' conn = sqlite3.connect(db_filename) c = conn.cursor() c.execute('SELECT * FROM revenue')
# 4.52: Group for extraction. # Use a parenthetical grouping to extract the number from this # text. import re line = '34: this is a line of text' matchobj = re.search(r'', line) print(matchobj.group(1)) # Expected Output: # 34 # Note that if you see the message AttributeError: 'NoneType' # object has no attribute 'group', this means that the search # did not find a match and returned None, and the code # attempted to call .group() on None. Check the string and # pattern to determine why it did not match.
# 3.30: Encode a latin-1 string to bytes and back to string, # then try to encode as ascii # The below string contains a non-ascii character. Encode # into the following encodings: 'latin-1', 'utf-8' and # 'ascii'. string = 'voilà' bytestr = string.encode(# add encoding here) print(bytestr)
# 5.12: Given your understanding that the key= argument to # sorted() will in a sense process each element through # whatever function we pass to it, sort these strings by their # length, and print the sorted list. mystrs = ['I', 'was', 'hanging', 'on', 'a', 'rock'] # your code here # Expected Output: # ['I', 'a', 'on', 'was', 'rock', 'hanging'] # If you see this message: # TypeError: len() takes exactly one argument (0 given) # it means that you added parentheses and thus attempted to # call the len function. Keep in mind that we don't call this # method -- we give it to the sorted() function to call. # We're doing this because sorted() will use whatever function # we wish, to modify each element for the purposes of sorting. # If we give it len it will sort 'I' as 1, 'was' as 3, # 'hanging' as 7, etc -- perfect for our purposes.
# 6.1: Define a class. # Use the class statement with name MyClass (or you may # substitute a name of your own choice). To fill the # otherwise empty block, use the pass statement. # # Initialize an instance of the class and print its type to # show that it is an instance of the class. # Expected Output: # <class '__main__.MyClass'>
# 8.35: Use .loc[] indexing with a list to select the first 3 # rows (19270701, 19270702 and 19270706) of the DataFrame. # (Note that these have been read into the DataFrame as # integers.) Do this first by passing a list of the 3 index # values, then by passing a slice starting with 19270701 and # ending with 19270706. import pandas as pd df = pd.read_csv('../F-F_Research_Data_Factors_daily.txt', sep='\s+', header=3, skipfooter=2, engine='python')
# 9.4: Convert a function to lambda. The following function # takes one argument and returns the value doubled. Convert # to lambda and use in the map() function. def doubleit(arg): return arg * 2 seq = [1, 2, 3, 4] seq2 = map(doubleit, seq) print(list(seq2)) # [2, 4, 6, 8]
import os, sys # coding=utf-8 fname = input('file name please:') with open(fname, 'r') as myfile: jomle=myfile.read().replace('\n', '') print ("number of ا:",jomle.count("ا")) print ("number of ب:",jomle.count("ب")) print ("number of پ:",jomle.count("پ")) print ("number of ت:",jomle.count("ت")) print ("number of ث:",jomle.count("ث")) print ("number of ج:",jomle.count("ج")) print ("number of چ:",jomle.count("چ")) print ("number of ح:",jomle.count("ح")) print ("number of خ:",jomle.count("خ")) print ("number of د:",jomle.count("د")) print ("number of ذ:",jomle.count("ذ")) print ("number of ر:",jomle.count("ر")) print ("number of ز:",jomle.count("ز")) print ("number of ژ:",jomle.count("ٓٓژ")) print ("number of س:",jomle.count("س")) print ("number of ش:",jomle.count("ش")) print ("number of ص:",jomle.count("ص")) print ("number of ض:",jomle.count("ض")) print ("number of ط:",jomle.count("ط")) print ("number of ظ:",jomle.count("ظ")) print ("number of ع:",jomle.count("ع")) print ("number of غ:",jomle.count("غ")) print ("number of ف:",jomle.count("ف")) print ("number of ق:",jomle.count("ق")) print ("number of ک:",jomle.count("ک")) print ("number of گ:",jomle.count("گ")) print ("number of ل:",jomle.count("ل")) print ("number of م:",jomle.count("م")) print ("number of ن:",jomle.count("ن")) print ("number of و:",jomle.count("و")) print ("number of ه:",jomle.count("ه")) print ("number of ی:",jomle.count("ی"))
""" Binary Tree implementation starter """ import random from binarytree.node import Node from binarytree.binarytree import BinaryTree if __name__ == '__main__': ROOT = 5 print('\t...creating a binary tree...') binary_tree = BinaryTree(ROOT) print('The binary tree with root value', ROOT, 'is created.\n') nodes = [2, 7, 6, 3, 4, 1, 10, 8, 9] print('\t...filling the binary tree with nodes...') for val in nodes: binary_tree.add(Node(val)) print('All the nodes are successfully added to the binary tree.\n') find_random_nodes = [Node(random.randint(0, 15))] find_random_nodes.append(Node(random.randint(0, 15))) find_random_nodes.append(Node(random.randint(0, 15))) for random_node in find_random_nodes: print('\t...trying to find if there is a node with value', random_node.value, '...') find_res = binary_tree.find(random_node) if find_res: print('Yes, the tree contains a node with value', random_node.value, '.\n') else: print('No nodes with value', random_node.value, ' in the binary tree :( \n') print('\t...calculating how high the binary tree is...') height = binary_tree.get_height() print('The binary tree is', height, 'levels high!\n') print('\t...traversing the binary tree in depth...') binary_tree.get_dfs() print('- the result of DFS traversal of the binary tree\n') remove_random_nodes = [Node(random.randint(0, 15))] remove_random_nodes.append(Node(random.randint(0, 15))) remove_random_nodes.append(Node(random.randint(0, 15))) for random_node in remove_random_nodes: print('\t...trying to remove a node with the value', random_node.value, '...') remove_res = binary_tree.remove(random_node) if remove_res: print('The node with value', random_node.value, 'is removed from the binary tree.\n') else: print('Cannot remove a node', random_node.value, 'because it is not in the tree.\n') if binary_tree.get_height is not None: binary_tree.remove(binary_tree.root) binary_tree.add(Node(0)) RESULT = binary_tree.root.value assert RESULT == 0, 'Binary Tree not working'
class Solution: def divide(self, dividend, divisor): if dividend < -2**31 or dividend > 2**31-1 or divisor < -2**31 or divisor > 2**31-1: return 2**31-1 if dividend == 0: return 0 else: flag = dividend * divisor flag = 1 if flag > 0 else -1 dividend = abs(dividend) divisor = abs(divisor) result = 0 c = 1 con = divisor while dividend - divisor > 0: result += c c *= 2 dividend = dividend - divisor divisor *= 2 while dividend >= con: divisor /= 2 c /= 2 if dividend - divisor > 0 or dividend - divisor == 0: result += c dividend -= divisor """ while dividend - divisor < 0: divisor /= 2 c /= 2 while dividend - divisor > 0 or dividend - divisor == 0: result += c c /= 2 dividend = dividend - divisor if dividend < con: break divisor /= 2 while dividend - divisor < 0: divisor /= 2 c /= 2 """ if int(flag*result) < -2**31 or int(flag*result) > 2**31-1: return 2**31-1 else: return int(flag*result) dividend = int(input()) divisor = int(input()) print(Solution().divide(dividend, divisor))
def merge(a,b): res=[] while a and b: if a[0]<b[0]: res.append(a[0]) a.pop(0) else: res.append(b[0]) b.pop(0) if a: res+=a else: res+=b return res def mergeSort(arr): if not arr or len(arr)==1: return arr middle=len(arr)//2 left=mergeSort(arr[:middle]) right=mergeSort(arr[middle:]) arr=merge(left,right) return arr def main(): arr=[2,5,3,56,53,23,12,76,53,24,43,99,1] result=mergeSort(arr) print(result) if __name__=="__main__": main()
class Product(object): def __init__(self, name, price, quantity): self.name = name self.price = price self.quantity = quantity def __iter__(self): return self def __next__(self): if self.num < self.n: cur, self.num = self.n, self.num + 1 return cur else: raise StopIteration() def __getitem__(self): return self.price def __setitem__(self, price): self.price = price def __str__(self): return str(self.name) + ', ' + str(self.price) + ', ' + str(self.quantity) ################################################## def makeDiscount(name, price): # through iterator i = 0 for j in list(name): if j in list('Kosher Passover'): i += 1 if i == 2: p = price * 95 / 100 return p return price ################################################# def makeDiscount2(lst): # through generator for j in range(len(lst)): i = 0 for c in list(lst[j].name): if c in list('Kosher Passover'): i += 1 if i == 2: price = lst[j].price * 95 / 100 yield price if i < 2: yield lst[j].price ################################################### P = Product('Milk', 5.5, 32) P2 = Product('Khhosher', 100, 45) P3 = Product('Pssa vvcjh', 200, 29) # print(P) # print(P2) # print(P3) lst = [P, P2, P3] # make a list of products print("Iterator type type:") itList = iter(lst) it1 = next(itList) it2 = next(itList) it3 = next(itList) print(makeDiscount(it1.name, it1.price)) print(makeDiscount(it2.name, it2.price)) print(makeDiscount(it3.name, it3.price)) print("Generator type:") for price in makeDiscount2(lst): print(price)
#!/usr/bin/python import math recipe = { 'milk': 100, 'butter': 50, 'flour': 5 } ingredients = { 'milk': 132, 'butter': 48, 'flour': 51 } def recipe_batches(recipe, ingredients): if len(recipe.keys()) != len(ingredients.keys()): return 0 else: dict = {key: ingredients[key] / recipe[key] for key in ingredients if key in recipe} return min(dict.values()) print(recipe_batches(recipe, ingredients))
from enum import Enum class InstructionTypes(Enum): CALC = 1 READ = 2 WRITE = 3 class Instruction: def __init__(self, parent, instruction_type=InstructionTypes.CALC, mem_address=0b0000, mem_data=0x0000): self.instruction_type = instruction_type self.parent = parent self.mem_address = mem_address self.mem_data = mem_data def get_data_str(self): return '0x' + '{:04x}'.format(self.mem_data).upper() def get_address_str(self): return '{:04b}'.format(self.mem_address) def __str__(self): representation = self.parent + ": " + self.instruction_type.name if self.instruction_type != InstructionTypes.CALC: representation += " " + self.get_address_str() if self.instruction_type == InstructionTypes.WRITE: representation += " " + self.get_data_str() return representation def set_instruction_type(self, instruction_type): self.instruction_type = instruction_type
import turtle import random win = turtle.Screen() win.title("make the geme") win.bgcolor("black") win.setup(width=800, height=600) win.tracer(0) scorevalue = 0 # making snake snake = turtle.Turtle() snake.shape("square") snake.color("white") snake.penup() snake.speed(0) #score score = turtle.Turtle() score.color("white") score.penup() score.speed(0) score.goto(-350,260) score.color("blue") score.hideturtle() score.write("Score=",align="left",font=("Arial",24,"normal")) #food food = turtle.Turtle() food.shape("circle") food.color("red") food.penup() food.speed(0) food.goto(0,100) #x=random.randint(200,-200) #y=random.randint(100,-100) #food.goto(x,y) segment = [] def snake_movementright(): x = snake.xcor() x = x+20 if( x> 390): x= 390 snake.setx(x) def snake_movementleft(): x1 = snake.xcor() x1 = x1-22 if( x1< -390): x1= -390 snake.setx(x1) def snake_movementup(): y = snake.ycor() y = y+22 if(y>300): y = 290 snake.sety(y) def snake_movementdown(): y1 = snake.ycor() y1 = y1-22 if( y1< -300): y1= -290 snake.sety(y1) win.listen() win.onkeypress(snake_movementleft, "Left") win.onkeypress(snake_movementup, "Up") win.onkeypress(snake_movementright, "Right") win.onkeypress(snake_movementdown, "Down") while True: win.update() if snake.distance(food)<20: score.clear() food.goto(random.randint(-290, 290), random.randint(-220, 220)) scorevalue = scorevalue + 1 score.write("Score = {}".format(scorevalue), align="left", font=("Arial", 24, "normal")) snakebody = turtle.Turtle() snakebody.shape("square") snakebody.color("Gray") snakebody.penup() snakebody.speed(0) segment.append(snakebody) for item in range(len(segment)-1, 0, -1): x = segment[item-1].xcor() y = segment[item-1].ycor() segment[item].goto(x, y) if len(segment) > 0: x = snake.xcor() y = snake.ycor() segment[0].goto(x,y)
# if ~ else a = 10 if a>5: print('big') else: print('small') n = -2 if n > 0: print('양수') elif n<0: print('음수') else: print('0')
''' Given the integer N - the number of minutes that is passed since midnight - how many hours and minutes are displayed on the 24h digital clock? The program should print two numbers: the number of hrs (between 0 and 23) and the number of minutes (between 0 and 59). ''' N= int(input('enter the minutes passed since midnight:')) hours =(N//60) minutes =(N%60) print(f'The hours is {hours}.') print(f'The minutes is {minutes}.') print(f'Its {hours}:{minutes} now.')
''' what is the result of 10**3 ''' a = 10 print( a**3 )
''' weight converter: Input the weight of the person in either in kg or pound(lbs). If the person provides his/her weight in kg then convert it into lbs else convert it to kg. ''' weight_1 = float(input('enter your weight in kg or lbs')) weight_2 = input('kg or lbs') pound = 2.2 if weight_2 == 'kg': convert = weight_1*pound print(f'you are {convert}lbs') elif weight_2 == 'lbs': convert2 = weight_1 / 2.2 print(f'you are {convert2}kg') else: print("OK")
''' given x=5 what will be the value of x after we run x += 3 ''' x = 5 x += 3 print(x)
"""This module defines how notes are converted to frequencies. Currently only 12-tone equal temperament, but this would be the place to implement other tuning systems. Base frequency can be edited on-demand. """ import math # equal temperament RATIO = math.pow(2, 1 / 12) NATURALS = { "C": -9, "D": -7, "E": -5, "F": -4, "G": -2, "A": 0, "B": 2, } ACCIDENTALS = {"#": 1, "b": -1, "x": 2} def note_to_frequency(note, basefreq=440): """convert note of format 'A#4' to a frequency, with respect to a basefrequency for A4. Handles an arbitrary number of accidentals. """ tone, *accidents, octave = note offset = NATURALS[tone] + sum(ACCIDENTALS[a] for a in accidents) return basefreq * math.pow(RATIO, offset) * 2 ** (int(octave) - 4)
"""Data preparation of credit default data. Pre processing that can be carried out before splitting into training and test data: Ordered categorical columns are ordinal encoded. Unordered categorical columns are one hot encoded. In general, the categories need to cover the entire data set. In this data set the categories are pre defined. """ # Author: Graham Hay import pandas as pd from pandas import DataFrame from sklearn.compose import ColumnTransformer from sklearn.preprocessing import LabelEncoder, MinMaxScaler, StandardScaler INPUT_FILE = 'dataset_31_credit-g.csv' FEATURES_NUMERIC = ['duration', 'credit_amount', 'installment_commitment', 'residence_since', 'age', 'existing_credits', 'num_dependents'] FEATURES_ORDINAL = ['checking_status', 'savings_status', 'employment', 'own_telephone', 'foreign_worker'] FEATURES_NOMINAL = ['credit_history', 'purpose', 'personal_status', 'other_parties', 'property_magnitude', 'other_payment_plans', 'housing', 'job'] def preprocess_data(): """Pre process the Credit default data. Load the credit default data, perform pre processing of categorical features and encode the target labels. Returns ------- x : ndarray of shape (>2,) Expanded data set as a numpy array with additional columns for one hot encoded features. y : ndarray of shape (1,) Encoded target labels. features : list of feature names Expanded list of feature names with the additional one hot encoded columns. classes : list of class labels Class labels in order negative=0, positive=1 """ df = pd.read_csv(INPUT_FILE) print(INPUT_FILE) print('Input data shape:', df.shape) # LabelEncoder sorts the labels alphabetically, so 'bad' -> 0 and 'good' -> 1, # so the positive class is 'good' and the classes list should be classes = ['bad', 'good']. # We want 'bad' loans are the positive class but LabelEncoder sorts the labels alphabetically, # so flip the zeros and ones and the order of the class names. # NB: This requires the Decision tree to have class_weights='balanced' to work properly. classes = ['good', 'bad'] class_label_encoder = LabelEncoder() class_label_encoder.fit(df['class']) y = 1 - class_label_encoder.transform(df['class']) # For 'good' as the positive class, use the following code instead. # classes = ['bad', 'good'] # class_label_encoder = LabelEncoder() # class_label_encoder.fit(df['class']) # y = class_label_encoder.transform(df['class']) # Numeric features df_numeric = df[FEATURES_NUMERIC] # Ordinal (Categorical ordered) features df_ordinal = DataFrame() df_ordinal['checking_status'] = pd.Categorical(df['checking_status'], ordered=True, categories=["'no checking'", "'<0'", "'0<=X<200'", "'>=200'"]).codes df_ordinal['savings_status'] = pd.Categorical(df['savings_status'], ordered=True, categories=["'no known savings'", "'<100'", "'100<=X<500'", "'500<=X<1000'", "'>=1000'"]).codes df_ordinal['employment'] = pd.Categorical(df['employment'], ordered=True, categories=["unemployed", "'<1'", "'1<=X<4'", "'4<=X<7'", "'>=7'"]).codes df_ordinal['own_telephone'] = pd.Categorical(df['own_telephone'], ordered=True, categories=['none', 'yes']).codes df_ordinal['foreign_worker'] = pd.Categorical(df['foreign_worker'], ordered=True, categories=['no', 'yes']).codes # Nominal (Categorical unordered) features df_nominal = DataFrame() df_nominal['credit_history'] = pd.Categorical(df['credit_history'], ordered=True, categories=["'all paid'", "'critical/other existing credit'", "'delayed previously'", "'existing paid'", "'no credits/all paid'"]) df_nominal['purpose'] = pd.Categorical(df['purpose'], ordered=True, categories=["business", "'domestic appliance'", "education", "furniture/equipment", "'new car'", "other", "radio/tv", "repairs", "retraining", "'used car'"]) # NB: 'female single' is not present in the data df_nominal['personal_status'] = pd.Categorical(df['personal_status'], ordered=True, categories=["'female single'", "'male single'", "'female div/dep/mar'", "'male mar/wid'", "'male div/sep'"]) df_nominal['other_parties'] = pd.Categorical(df['other_parties'], ordered=True, categories=["none", "'co applicant'", "guarantor"]) df_nominal['property_magnitude'] = pd.Categorical(df['property_magnitude'], ordered=True, categories=["car", "'life insurance'", "real estate", "'no known property'"]) df_nominal['other_payment_plans'] = pd.Categorical(df['other_payment_plans'], ordered=True, categories=["bank", "stores", "none"]) df_nominal['housing'] = pd.Categorical(df['housing'], ordered=True, categories=["'for free'", "own", "rent"]) df_nominal['job'] = pd.Categorical(df['job'], ordered=True, categories=["'high qualif/self emp/mgmt'", "skilled", "'unemp/unskilled non res'", "'unskilled resident'"]) df_nominal = pd.get_dummies(df_nominal) # df_nominal = pd.get_dummies(df[features_nominal]) # df_nominal = pd.get_dummies(df, columns=features_nominal) # Dataframe x = pd.concat([df_numeric, df_ordinal, df_nominal], axis=1) feature_names = x.columns.tolist() return x.values, y, feature_names, classes def make_scale_transformer(): """Make a scaling column transformer the Credit default data as a numpy array. The numeric features are standardised and the ordinal features are normalised. All other features (nominal) are unchanged. Returns ------- ct : ColumnTransformer Column transformer that takes a numpy array and scales the features. """ ct = ColumnTransformer([('numeric', StandardScaler(), list(range(len(FEATURES_NUMERIC)))), ('ordinal', MinMaxScaler(), list(range(len(FEATURES_NUMERIC), len(FEATURES_NUMERIC)+len(FEATURES_ORDINAL))))], remainder='passthrough') return ct
import sqlite3 import sys import random # Creating SQLite Connection conn = sqlite3.connect("card.s3db") cur = conn.cursor() # function to check validity def check_card(newcn): tfcs = "" tfs = 0 temp_cn = newcn[:-1] chsm = newcn[15] for i in range(len(temp_cn)): if i % 2 == 0: fchar = int(temp_cn[i]) * 2 if fchar > 9: fchar -= 9 tfcs += str(fchar) else: tfcs += temp_cn[i] for i in range(len(tfcs)): tfs += int(tfcs[i]) fcs2 = tfs % 10 if fcs2 == 0: cs = str(0) else: cs = str(10 - fcs2) if cs == chsm: return "Valid" else: return "Not Valid" # Create card function def create_account(): iin = "400000" fcs = "" fs = 0 cs = "" ain = int(random.randint(111111111,999999999)) cn = iin + str(ain) for i in range(len(cn)): if i % 2 == 0: fchar = int(cn[i]) * 2 if fchar > 9: fchar -= 9 fcs += str(fchar) else: fcs += cn[i] for i in range(len(fcs)): fs += int(fcs[i]) fcs2 = fs % 10 if fcs2 == 0: cs = str(0) else: cs = str(10 - fcs2) iin = "400000" ncn = iin + str(ain) + cs temp_pin = int(random.randint(1111,9999)) npin = str(temp_pin) print("Your card has beed created") lst = list() lst.extend([int(ncn), int(npin)])# Serial number | number | pin | balance cur.execute("INSERT INTO card (number, pin, balance) VALUES (?, ?,0)", lst) conn.commit() print("Your card number:") print(ncn) print("Your card PIN:") print(npin) print() front_end() # Log in function def log_in(): print("Enter card number:") inp_cn = input() print("Enter your PIN:") inp_pin = input() cur.execute("Select * from card") all_info = cur.fetchall() for i in all_info: lst_or_cn = list() lst_or_cn.extend([int(inp_cn), int(inp_pin)]) cur.execute("SELECT EXISTS(SELECT * from card where number = ? and pin = ?)",lst_or_cn) result1 = cur.fetchone() if result1[0] == 0: print("Wrong card number or PIN!") print() front_end() if int(i[1]) == int(inp_cn): if int(i[2]) == int(inp_pin): print() lst_for_cn = list() lst_for_cn.append(inp_cn) lst_for_pin = list() lst_for_pin.append(inp_pin) print("You have successfully logged in!") print() while True: print("1. Balance\n2. Add income\n3. Do transfer\n4. Close account\n5. Log out\n0. Exit") ch = input() if ch == "1": cur.execute("SELECT balance from card where number = ? ",lst_for_cn) bal_info = cur.fetchall() for i in bal_info: print() print("Balance :",i[0]) print() break if ch == "2": print() print("Enter income:") add_inc = int(input()) cur.execute("SELECT balance from card where number = ? ",lst_for_cn) inc_info = cur.fetchall() for i in inc_info: cur_inc = i[0] break new_inc = int(cur_inc) + add_inc lst_for_inc_and_num = list() lst_for_ninc = list() lst_for_inc_and_num.extend([new_inc, inp_cn]) cur.execute("update card set balance = ? where number = ?",lst_for_inc_and_num) conn.commit() print("Income was added!") print() if ch == "3": total_cards = 0 print() print("Transfer") print("Enter card number:") inp_cn2 = input() validiy = check_card(inp_cn2) if validiy == "Not Valid": print("Probably you made mistake in the card number. Please try again!") print() elif validiy == "Valid": cur.execute("SELECT count(number) from card") no = cur.fetchall() for i in no: total_cards = i[0] break cur.execute("SELECT number from card") all_cards = cur.fetchall() tc = 0 for i in all_cards: lst_for_cn2 = list() lst_for_cn2.append(inp_cn2) pon = cur.execute("SELECT EXISTS(SELECT * from card where number = ?)",lst_for_cn2) pon = cur.fetchone() # print(pon) if pon[0] == 0 : print("Such a card does not exist.") print() break # print(type(total_cards)) # print(all_cards[total_cards-1]) if tc <= total_cards: #print(i[0]) if i[0] == inp_cn2: if inp_cn == inp_cn2: print("You can't transfer money to the same account!") print() else: print("Enter how much money do you want to transfer:") transfer_amt = input() temp_lst1 = list() temp_lst1.append(int(inp_cn)) cur.execute("SELECT balance from card where number = ?",temp_lst1) ini_bal = cur.fetchall() usr_balance = 0 for i in ini_bal: usr_balance = i[0] if int(transfer_amt) > int(usr_balance): print("Not enough money!") print() else: usr_balance = usr_balance - int(transfer_amt) lst = list() lst.extend([int(usr_balance), int(inp_cn)]) cur.execute("UPDATE card set balance = ? where number = ?",lst) temp_lst2 = list() temp_lst2.append(int(inp_cn2)) cur.execute("select balance from card where number = ?",temp_lst2) suser_bal = cur.fetchall() bal = 0 for i in suser_bal: bal = i[0] bal += int(transfer_amt) lst1 = list() lst1.extend([int(bal), int(inp_cn2)]) cur.execute("UPDATE card set balance = ? where number = ?", lst1) conn.commit() print("Success!") print() tc += 1 elif tc > int(total_cards): print("Such a card does not exist") break if ch == "4": print() temp_lst10 = list() temp_lst10.append(int(inp_cn)) cur.execute("DELETE from card where number = ?",temp_lst10) cur.fetchall() conn.commit() print("Your account has been closed!") print() if ch == "5": print() front_end() if ch == "0": print() print("Bye!") sys.exit() # Front End function def front_end(): while True: print("1. Create Account\n2. Log into account\n0. Exit") choice = input() if choice == "1": print() create_account() elif choice == "2": print() result = log_in() if result == "0": return elif choice == "0": print() print("Bye!") sys.exit() front_end() conn.commit() conn.close() # 4000005203832473 # 1668 # 4000008898549394 # 7116
from selenium import webdriver driver = webdriver.Chrome(executable_path='C:\\Users\\Diego\\Downloads\\Programas a Instalar\\2021\\Drivers\\chromedriver_win32\\chromedriver.exe') driver.get("https://rahulshettyacademy.com/AutomationPractice/") driver.maximize_window() #Finding all the checkboxes, common attribute is type = 'checkbox' #Using find_elements_by... method to get a list of all the webElements matching the CSS selector checkBoxes = driver.find_elements_by_css_selector("input[type='checkbox']") #Looping through list of the checkboxes web elements and clicking each one of them. for box in checkBoxes: box.click() #For assertion purposes we can check if a webElement is selected, in this case, the check boxes. assert box.is_selected() for box in checkBoxes: box.click() for box in checkBoxes: #Extract attributes of tags with .get_attribute method. if box.get_attribute('value') == "option2": box.click() #Radio Inputs are handled in a similar way radioInputs = driver.find_elements_by_xpath("//input[@type='radio']") print(len(radioInputs)) radioInputs[1].click()
# -*- coding: utf-8 -*- """ Created on Wed Oct 6 03:35:46 2021 @author: GuSs_90 """ import psycopg2 try: connection = psycopg2.connect( host = 'localhost', user = 'postgres', password = '123456', database = 'bd_cesar5' ) print("Conexion exitosa") cursor=connection.cursor() cursor.execute("SELECT ci,paterno,materno,nombre,usuario FROM persona INNER JOIN usuario ON persona.ci=usuario.id_persona INNER JOIN rol ON usuario.rol_fk=rol.id_rol WHERE rol.id_rol=2") filas=cursor.fetchall() contador=0 print("------Lista de universitarios-----") for fila in filas: print(fila) contador+= 1 print("------Insertar Estudiante -----") ci=input("Carnet de Identidad: ") nombre=input("Nombre: ") paterno=input("Ap. Paterno: ") materno=input("Ap. Materno: ") f_nac=input("Fecha nacimiento aaaa-mm-dd: ") print("01 - CHUQUISACA") print("02 - LA PAZ") print("03 - COCHABAMBA") print("04 - ORURO") print("05 - POTOSI") print("06 - TARIJA") print("07 - SANTA CRUZ") print("08 - BENI") print("09 - PANDO") dpto=str(input("Cod. departamento: ")) contador+= 1 usuario = 'univ'+str(contador) print("Usuario: "+usuario) password=input("Password: "); rol=int('1'); sql="INSERT INTO persona (ci,nombre,paterno,materno,f_nacimiento,departamento_fk) VALUES ('{0}','{1}','{2}','{3}','{4}','{5}')" cursor.execute(sql.format(ci,nombre,paterno,materno,f_nac,dpto)) connection.commit() sql1="INSERT INTO usuario (usuario,password,id_persona,rol_fk) VALUES ('{0}','{1}','{2}','{3}')" cursor.execute(sql1.format(usuario,password,ci,rol)) connection.commit() print("-----> Estudiante Registrado <-------") except Exception as ex: print(ex)
#! /usr/bin/env python import sys # def get_fibonacci_last_digit_naive(n): # if n <= 1: # return n # # previous = 0 # current = 1 # # for _ in range(n - 1): # previous, current = current, previous + current # print(previous, current) # # return current % 10 def get_fib_better(n): if n <= 1: return n else: for _ in range(n-1): result = get_fib_better(n-1) + get_fib_better(n-2) # module by 10 to get last digit of return value return result % 10 if __name__ == '__main__': n = int(input()) print(get_fibonacci_better(n))
tSize = int(input("Please enter the size of the tile as an integer: ")) tSpan = int(input("Please enter the length of the span as an integer: ")) tTiles = ((tSpan) //(tSize)) spanToUse = tSpan - tSize numPairs = spanToUse//(2*(tSize)) borderSize = (spanToUse%2*(tSize))/2 bTile = numPairs + 1 wTile = numPairs gSize = borderSize print("Number of black tiles neded: " + str(bTile)) print("Number of white tiles neded: " + str(wTile)) print("Total number of tiles needed: " + str(tTiles)) print("Gap Length: " + str(gSize))
import string def getAvailableletters(lettersGuessed3): l = list(string.ascii_lowercase) availableletters = '' for indx2 in l: if indx2 not in lettersGuessed3: availableletters+=indx2 return availableletters
from difflib import SequenceMatcher from .models import Question, Answer """ Normalize text to be lowercase and free of dashes for comparison """ def cleaned(text): return text.lower().replace("-", " ") """ Check if the two strings contain the same words but in different orders """ def tokens_match(str1, str2): str1_tokens = str1.split(" ") str2_tokens = str2.split(" ") if len(str1_tokens) != len(str2_tokens): return False for str1_token in str1_tokens: if str1_token not in str2_tokens: return False for str2_token in str2_tokens: if str2_token not in str1_tokens: return False return True """ Find the answer from the list of possible correct answers that is the most "similar to" the given entered answer """ def similar_to(answer, possible_answers): most_similar = None most_similar_ratio = 0.0 for possible_answer in possible_answers: if tokens_match(answer, cleaned(possible_answer.answer_text)): return (possible_answer, 1.0) ratio = SequenceMatcher(None, answer, cleaned(possible_answer.answer_text)).ratio() if ratio > most_similar_ratio: most_similar = possible_answer most_similar_ratio = ratio return (most_similar, most_similar_ratio) """ Process the entered answers for correctness: - An answer that matches the text of a correct answer exactly is correct - An answer that contains the same words in a different order is correct - An answer that has a "similarity ratio" greater than 0.5 is a partial match, which is marked as correct but displayed to the user """ def process_answers(entered_answers, correct_answers): num_wrong = 0 partial_matches = [] correct_answer_texts = [cleaned(ans.answer_text) for ans in correct_answers] for answer in entered_answers: if answer in correct_answer_texts: correct_answers = list(filter(lambda x: cleaned(x.answer_text) != answer, correct_answers)) correct_answer_texts.remove(answer) else: most_similar, most_similar_ratio = similar_to(answer, correct_answers) if most_similar_ratio > 0.5: correct_answers.remove(most_similar) correct_answer_texts.remove(cleaned(most_similar.answer_text)) partial_matches.append(most_similar.answer_text) else: num_wrong += 1 return num_wrong, partial_matches """ Create HTML based on the given results """ def create_response_html(correct_answers, num_wrong, partial_matches): resp = "" if num_wrong == 0: resp += "<p class='correct'>Correct!</p>" else: resp += "<p class='incorrect'>Incorrect.</p>" resp += "<p>Correct answers:</p>" resp += "<ul>" for answer in correct_answers: resp += "<li>%s</li>" % answer resp += "</ul>" if len(partial_matches) > 0: resp += "<p>Partial matches:</p>" resp += "<ul>" for match in partial_matches: resp += "<li>%s</li>" % match resp += "</ul>" return resp """ Convert the QueryDict from the request to save a study guide into a usable Python dictionary """ def convert_data(data): existing = {} unsaved = {} for key in data: components = key.split("-") value = data[key] if components[-1].endswith("[]"): value = data.getlist(key) components[-1] = components[-1].split("[]")[0] if key.startswith("existing"): if not components[1] in existing: existing[components[1]] = {} existing[components[1]][components[2]] = value else: if not components[1] in unsaved: unsaved[components[1]] = {} unsaved[components[1]][components[2]] = value return existing, unsaved """ Process the updates for the given study guide, given data from the front end """ def process_study_guide_update(study_guide, data): existing, unsaved = convert_data(data) update_existing_questions(existing) add_new_questions(unsaved, study_guide) """ Update the data of all the existing questions in a study guide """ def update_existing_questions(existing_questions): for question_id in existing_questions: is_enabled = existing_questions[question_id]["enabled"] == "true" question_text = existing_questions[question_id]["question_text"] answers = existing_questions[question_id]["answer_texts"] question = Question.objects.get(id=question_id) # Update the question data and save it question.question_text = question_text question.enabled = is_enabled question.save() # Get the existing answers from the database to compare to those from the request existing_answers = Answer.objects.filter(question=question) existing_answer_texts = [x.answer_text for x in existing_answers] # The following two-step process for updating answers is basically a workaround # for not having answer ids passed through the request # Delete answers from the database if they're not in the HTTP request for answer in existing_answers: if answer.answer_text not in answers: answer.delete() # Create answers in the database if they don't already exist for answer_text in answers: if answer_text not in existing_answer_texts and answer_text != '': Answer.objects.create(answer_text=answer_text, question=question) """ Add new questions to a study guide """ def add_new_questions(unsaved_questions, study_guide): for question in unsaved_questions: is_enabled = unsaved_questions[question]["enabled"] == "true" question_text = unsaved_questions[question]["question_text"] answers = unsaved_questions[question]["answer_texts"] new_question = Question.objects.create( question_text=question_text, enabled=is_enabled, study_guide=study_guide) for answer in answers: Answer.objects.create(answer_text=answer, question=new_question)
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys from converter import Converter class Parser: def __init__(self, filename): self.file = open(filename, 'r') buffer = '' for line in self.file.readlines(): line = line.strip() if line == '': converter = Converter(buffer) self.dictionary = converter.get_dictionary() buffer = '' else: buffer = buffer + '\n' + line def get_dictionary(self): return self.dictionary if __name__ == "__main__": parser = Parser(sys.argv[1]) diccionario = parser.get_dictionary() print diccionario
# CS 212, hw1-2: Jokers Wild # # ----------------- # User Instructions # # Write a function best_wild_hand(hand) that takes as # input a 7-card hand and returns the best 5 card hand. # In this problem, it is possible for a hand to include # jokers. Jokers will be treated as 'wild cards' which # can take any rank or suit of the same color. The # black joker, '?B', can be used as any spade or club # and the red joker, '?R', can be used as any heart # or diamond. # # The itertools library may be helpful. Feel free to # define multiple functions if it helps you solve the # problem. # # ----------------- # Grading Notes # # Muliple correct answers will be accepted in cases # where the best hand is ambiguous (for example, if # you have 4 kings and 3 queens, there are three best # hands: 4 kings along with any of the three queens). import itertools card_num = '23456789TJQKA' red_cards = [n+s for n in card_num for s in 'HD'] black_cards = [n+s for n in card_num for s in 'SC'] # shirouto: well, zip would be clearer about intent here; also easier to work with red_black_com = [[r]+[b] for r in red_cards for b in black_cards] # print(red_black_com) def get_possible_hands(hand): """replace the joker with all possible card. return a list of possible hands. if there is no joker, return list of original hand. """ # shirouto: why the list.index() calls? If you just want to check whether an # element is an in list, you have ``x in xs`` syntax. Much clearer and no need # for the try-except block. # Moreover, you know that list search is O(n): why do you do the same search twice # for each color, so all together 4 times? And, since we are here? Do you really # need even *two* list scans? Can this function be done with only one? # Then a nitpick, really... any particular reason you assign to ``hands`` first # before returning? Why not return directly? try: if hand.index('?B') and hand.index('?R'): hand.remove('?B') hand.remove('?R') hands = [hand+rb_com for rb_com in red_black_com] return hands except: pass try: if hand.index('?B'): hand.remove('?B') hands = [hand+[jr] for jr in black_cards] return hands except: pass try: if hand.index('?R'): hand.remove('?R') hands = [hand+[jr] for jr in black_cards] return hands except: pass return [hand] def best_hand(hand): "From a 7-card hand, return the best 5 card hand. -- this is solution from hw1_1.py" hands = [ele for ele in itertools.combinations(hand, 5)] return max(hands, key=hand_rank) def best_wild_hand(hand): "Try all values for jokers in all 5-card selections." # shirouto: Hrm... once again, what is the purpose of ``hands``? Documenting? # Don't you think your ``get_possible_hands`` function name is clear already? hands = get_possible_hands(hand) # shirouto: This list here is a just memory waste really (and CPU clocks, since the list is # is allocated on the heap --- yeah, dynamical language and all that --- and time needs spent # during allocation and garbage collection): ``max()`` consumes an iterable, so you could # call it directly with your generator expression. And since you are doing that, you could # also get rid of that extra list allocation in ``best_hand`` and stick with an iterator-based # API, given your use cases here. Yes, you must learn iterators/generators and all that. all_best_hands = [best_hand(h) for h in hands] return max(all_best_hands, key=hand_rank) def test_best_wild_hand(): assert (sorted(best_wild_hand("6C 7C 8C 9C TC 5C ?B".split())) == ['7C', '8C', '9C', 'JC', 'TC']) assert (sorted(best_wild_hand("TD TC 5H 5C 7C ?R ?B".split())) == ['7C', 'TC', 'TD', 'TH', 'TS']) assert (sorted(best_wild_hand("JD TC TH 7C 7D 7S 7H".split())) == ['7C', '7D', '7H', '7S', 'JD']) return 'test_best_wild_hand passes' # ------------------ # Provided Functions # # You may want to use some of the functions which # you have already defined in the unit to write # your best_hand function. def hand_rank(hand): "Return a value indicating the ranking of a hand." ranks = card_ranks(hand) if straight(ranks) and flush(hand): return (8, max(ranks)) elif kind(4, ranks): return (7, kind(4, ranks), kind(1, ranks)) elif kind(3, ranks) and kind(2, ranks): return (6, kind(3, ranks), kind(2, ranks)) elif flush(hand): return (5, ranks) elif straight(ranks): return (4, max(ranks)) elif kind(3, ranks): return (3, kind(3, ranks), ranks) elif two_pair(ranks): return (2, two_pair(ranks), ranks) elif kind(2, ranks): return (1, kind(2, ranks), ranks) else: return (0, ranks) def card_ranks(hand): "Return a list of the ranks, sorted with higher first." ranks = ['--23456789TJQKA'.index(r) for r, s in hand] ranks.sort(reverse = True) return [5, 4, 3, 2, 1] if (ranks == [14, 5, 4, 3, 2]) else ranks def flush(hand): "Return True if all the cards have the same suit." suits = [s for r,s in hand] return len(set(suits)) == 1 def straight(ranks): """Return True if the ordered ranks form a 5-card straight.""" return (max(ranks)-min(ranks) == 4) and len(set(ranks)) == 5 def kind(n, ranks): """Return the first rank that this hand has exactly n-of-a-kind of. Return None if there is no n-of-a-kind in the hand.""" for r in ranks: if ranks.count(r) == n: return r return None def two_pair(ranks): """If there are two pair here, return the two ranks of the two pairs, else None.""" pair = kind(2, ranks) lowpair = kind(2, list(reversed(ranks))) if pair and lowpair != pair: return (pair, lowpair) else: return None print(test_best_wild_hand())
f1 = open('r1_list.txt', 'r') f2 = open('r2_list.txt', 'r') f1_line = f1.readline() f2_line = f2.readline() line_no = 1 while f1_line != '' or f2_line != '': f1_line = f1_line.rstrip() f2_line = f2_line.rstrip() if f1_line != f2_line: if f2_line == '' and f1_line != '': print(">+", "Line-%d" % line_no, f1_line) elif f1_line != '': print(">", "Line-%d" % line_no, f1_line) # If a line does not exist on file1 then mark the output with + sign if f1_line == '' and f2_line != '': print("<+", "Line-%d" % line_no, f2_line) # otherwise output the line on file2 and mark it with < sign elif f2_line != '': print("<", "Line-%d" % line_no, f2_line) print() f1_line = f1.readline() f2_line = f2.readline() line_no += 1 f1.close() f2.close()
# coding:utf-8 ''' 峰值元素是指其值大于左右相邻值的元素。 给定一个输入数组 nums,其中 nums[i] ≠ nums[i+1],找到峰值元素并返回其索引。 数组可能包含多个峰值,在这种情况下,返回任何一个峰值所在位置即可。 你可以假设 nums[-1] = nums[n] = -∞。 输入: nums = [1,2,3,1] 输出: 2 解释: 3 是峰值元素,你的函数应该返回其索引 2。 输入: nums = [1,2,1,3,5,6,4] 输出: 1 或 5 解释: 你的函数可以返回索引 1,其峰值元素为 2;   或者返回索引 5, 其峰值元素为 6。 思路: 二分查找 mid>mid-1 and mid>mid+1 或者线性扫描 ''' class Solution(object): def findPeakElement(self, nums): """ :type nums: List[int] :rtype: int """ left, right = 0, len(nums) - 1 while left < right: mid = left + right >> 1 if nums[mid] < nums[mid + 1]: left = mid + 1 else: right = mid return left def findPeakElement1(self, nums): for i in range(1, len(nums)): if nums[i] < nums[i - 1]: return i - 1 return len(nums)-1 if __name__ == '__main__': solution = Solution() nums = [[1, 2, 3, 1], [1, 2, 3, 4], [4, 3, 2, 1], [1, 2, 1, 3, 5, 6, 4], [1, 2, 1, 3, 5, 6, 4], [], [1]] for i in range(len(nums)): print(nums[i], ":", solution.findPeakElement1(nums[i])) print(solution.findPeakElement1([1, 2, 3])) print(range(3))
# coding:utf-8 ''' 给出 n 代表生成括号的对数,请你写出一个函数,使其能够生成所有可能的并且有效的括号组合。 例如,给出 n = 3,生成结果为: [ "((()))", "(()())", "(())()", "()(())", "()()()" ] ''' class Solution(object): def generateParenthesis(self, n): """ :type n: int :rtype: List[str] """ if __name__ == '__main__': solution = Solution()
#coding:utf-8 ''' 输入一个链表,反转链表后,输出新链表的表头。 思路: 需要中间遍历保存当前节点的next 防止链表的中断 临界条件: ''' class ListNode(object): def __init__(self,v): self.val=v self.next=None class Solution: def ReverseList(self,pHead): if not pHead: return pre=None next=None while pHead: next=pHead.next pHead.next=pre pre=pHead pHead=next return pre if __name__ == '__main__': arr=[1,2,3,4,5] phead=cur1=ListNode(0) for n in arr: cur1.next=ListNode(n) cur1=cur1.next pre=None next=None while phead: next=phead.next phead.next=pre pre=phead phead=next while pre: print(pre.val) pre=pre.next
# coding:utf-8 ''' 把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转。 输入一个非递减排序的数组的一个旋转,输出旋转数组的最小元素。 例如数组{3,4,5,1,2}为{1,2,3,4,5}的一个旋转,该数组的最小值为1。 NOTE:给出的所有元素都大于0,若数组大小为0,请返回0。 思路1: 最简单暴力的是遍历一遍复杂读是O(n) 思路2: [3, 4, 5, 1,2] 利用二分查找 low high if low<mid 说明左边是是递增序列,最小值肯定在右边 left=mid if low>mid 说明最小值肯定是在左边,右边必然是递增的序列 如果high low 相邻,最小值肯定是high ''' class Solution(object): def minNumberInRotateArray(self, rotateArray): minv = float('inf') for num in rotateArray: if num < minv: minv = num return minv def binary_search(self, rotateArray): low=0 high=len(rotateArray) while rotateArray[low]>rotateArray[high]: if high-low==1: mid=high break mid=(left+right)//2 if rotateArray[left]<=rotateArray[high]: left=mid else: right=mid return rotateArray[mid] if __name__ == '__main__': arr = [2,3, 4, 5, 1] # minv = float('inf') # for num in arr: # if minv > num: # minv = num # print(minv) left = 0 right = len(arr)-1 while left< right: mid = (left + right) // 2 if arr[left] < arr[mid]: left = mid+1 elif arr[left] > arr[mid]: right = mid # print(left,right) print(arr[left]) # solution=Solution() # print(solution.binary_search(arr))
# coding:utf-8 ''' 给定两个数组,编写一个函数来计算它们的交集。 输入: nums1 = [1,2,2,1], nums2 = [2,2] 输出: [2] 输入: nums1 = [4,9,5], nums2 = [9,4,9,8,4] 输出: [9,4] 思路: 可以使用hashmap 首先扫描第一个数组,再扫描第二个数组,复杂度O(M+N) 空间复杂度O(min(M,N)) 或者是双指针法,首先对数组进行排序,O(nlogn+mlogm) - 对数组 nums1 和 nums2 排序。 - 初始化指针 i,j 和 k 为 0。 - 指针 i 指向 nums1,指针 j 指向 nums2: 如果 nums1[i] < nums2[j],则 i++。 如果 nums1[i] > nums2[j],则 j++。 如果 nums1[i] == nums2[j],将元素拷贝到 nums1[k],且 i++,j++,k++。 返回数组 nums1 前 k 个元素。 ''' class Solution(object): def intersection(self, nums1, nums2): """ :type nums1: List[int] :type nums2: List[int] :rtype: List[int] """ res = [] hashmap = {} for num in nums1: if num in hashmap: hashmap[num] += 1 else: hashmap[num] = 1 for num in nums2: if num in hashmap and hashmap[num] != 0: res.append(num) hashmap[num] -= 1 return res class Solution1(object): def helper(self, nums1, nums2): res = [] hashmap = {} for num in nums1: hashmap[num] = 1 for num in nums2: if num in hashmap: res.append(num) return res def intersect(self, nums1, nums2): """ :type nums1: List[int] :type nums2: List[int] :rtype: List[int] """ if len(nums1) > len(nums2): return self.helper(nums2, nums1) else: return self.helper(nums1, nums2) if __name__ == '__main__': nums1 = [1, 2, 2, 1] nums2 = [2, 2] solution = Solution() print(solution.intersection(nums1, nums2))
#coding:utf-8 ''' 给一个链表,若其中包含环,请找出该链表的环的入口结点,否则,输出null。 链表中的环: 可以使用快慢指针的方式进行 快指针每次走两步 慢指针每次走一步 如果直至相等,然后快指针再从头走,直至相遇,则就是 ''' class ListNode: def __init__(self,v): self.val=v self.left=None self.right=None class Solution: def EntryNodeOfLoop(self, pHead): if not pHead or not pHead.next or not pHead.next.next: return None fast=pHead.next.next low=pHead.next while fast!=low: if fast.next.next is None and low.next is None: return None fast=fast.next.next low=low.next fast=pHead while fast!=low: low=low.next fast=fast.next return fast if __name__ == '__main__': array=[1,2,3,4] commom=[10,11,12]
#coding:utf-8 ''' 输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。 思路: 两个排序的链表进行合并,跟链表的插入类似,只需要比较两个链表的大小,将小的优先插入, 而后将长链表拼接到新的链表的后边即可 ''' class ListNode: def __init__(self,v): self.val=v self.next=None class Solution: def Merge(self, pHead1, pHead2): if not pHead1 and not pHead2: return if not pHead1: return pHead2 if not pHead2: return pHead1 res=cur=ListNode(0) while phead1 and pHead2: if phead1.val<=pHead2.val: cur.next=phead1 phead1=phead1.next else: cur.next=phead2.next phead2=phead2.next cur=cur.next if phead1: cur.next=phead1 else: cur.next=phead2 return res.next if __name__ == '__main__': arr1=[1,3,5,7,8,9] arr2=[2,4,6] phead1=cur1=ListNode(arr1[0]) phead2=cur2=ListNode(arr2[0]) for n in arr1[1:]: cur1.next=ListNode(n) cur1=cur1.next for n in arr2[1:]: cur2.next=ListNode(n) cur2=cur2.next # while phead1: # print(phead1.val) # phead1=phead1.next res=cur=ListNode(0) while phead1 and phead2: if phead1.val<=phead2.val: cur.next=phead1 phead1=phead1.next else: cur.next=phead2 phead2=phead2.next cur=cur.next if phead1: cur.next=phead1 else: cur.next = phead2 print('res----') while res: print(res.val) res=res.next
# coding:utf-8 ''' 请实现两个函数,分别用来序列化和反序列化二叉树 二叉树的序列化是指:把一棵二叉树按照某种遍历方式的结果以某种格式保存为字符串, 从而使得内存中建立起来的二叉树可以持久保存。 序列化可以基于先序、中序、后序、层序的二叉树遍历方式来进行修改,序列化的结果是一个字符串, 序列化时通过 某种符号表示空节点(#),以 ! 表示一个结点值的结束(value!)。 二叉树的反序列化是指:根据某种遍历顺序得到的序列化字符串结果str,重构二叉树。 主要的关键点是是每次递归都有返回值 反序列化的时候的pop ''' class TreeNode(object): def __init__(self, v): self.val = v self.left = None self.right = None def insert(self, v): if self.val: if v < self.val: if self.left is None: self.left = TreeNode(v) else: self.left.insert(v) else: if self.right is None: self.right = TreeNode(v) else: self.right.insert(v) else: self.val = v def findv(self, v): if v < self.val: self.left.findv(v) elif v > self.val: self.right.findv(v) else: return True def PrintTree(self): if self.left: self.left.PrintTree() print(self.val) if self.right: self.right.PrintTree() class Solution: def Serialize(self, root): """ Encodes a tree to a single string. :type root: TreeNode :rtype: str """ def rserialize(root, string): """ a recursive helper function for the serialize() function.""" # check base case if root is None: string += '#!' else: string += str(root.val) + '!' string = rserialize(root.left, string) string = rserialize(root.right, string) return string return rserialize(root, '') def Deserialize(self, data): """Decodes your encoded data to tree. :type data: str :rtype: TreeNode """ def rdeserialize(l): """ a recursive helper function for deserialization.""" if l[0] == '#': l.pop(0) return None root = TreeNode(l[0]) l.pop(0) root.left = rdeserialize(l) root.right = rdeserialize(l) return root data_list = data.split('!') root = rdeserialize(data_list) return root class Solution1: # 返回对应节点TreeNode def KthNode(self, pRoot, k): # write code here self.res = [] self.inoder(pRoot) if len(self.res) < k: return None else: return self.res[k-1] def inoder(self, root): if not root: return None if root.left: self.inoder(root.left) self.res.append(root.val) if root.right: self.inoder(root.right) if __name__ == '__main__': arr = [2, 3, 1, 6, 7, 5] root = TreeNode(4) for num in arr: root.insert(num) root.PrintTree() # print(root.Serialize()) # code = Solution() # ser_str = code.serialize(root) # print(ser_str) # print(code.deserialize(ser_str)) sol = Solution1() print('----') print(sol.KthNode(root, 1)) print(sol.res)
#coding:utf-8 ''' 堆(Heap)是计算机科学中一类特殊的数据结构的统称。堆通常是一个可以被看做一棵完全二叉树的数组对象 堆heap是计算机科学中一类特殊的数据结构的统称。堆通常是一个可以被看做一棵树的数组对象。堆总是满足下列性质: - 堆中某个节点的值总是不大于或不小于其父节点的值; - 堆总是一棵完全二叉树。 将根节点最大的堆叫做最大堆或大根堆,根节点最小的堆叫做最小堆或小根堆。常见的堆有二叉堆、斐波那契堆等。 堆是非线性数据结构,相当于一维数组,有两个直接后继。 堆的定义如下:n个元素的序列{k1,k2,ki,…,kn}当且仅当满足下关系时,称之为堆。 (ki <= k2i,ki <= k2i+1)或者(ki >= k2i,ki >= k2i+1), (i = 1,2,3,4...n/2) 若将和此次序列对应的一维数组(即以一维数组作此序列的存储结构)看成是一个完全二叉树,则堆的含义表明, 完全二叉树中所有非终端结点的值均不大于(或不小于)其左、右孩子结点的值。 由此,若序列{k1,k2,…,kn}是堆,则堆顶元素(或完全二叉树的根)必为序列中n个元素的最小值(或最大值)。 ''' if __name__ == '__main__': import heapq arr=[21,1,45,78,3,5] heapq.heapify(arr) print(arr) heapq.heappush(arr,23) heapq.heappop(arr) heapq.heapreplace(arr, 6) # 将最小的值去掉 print(arr)
# coding:utf-8 ''' 请实现一个函数用来找出字符流中第一个只出现一次的字符。例如,当从字符流中只读出前两个字符"go"时,第一个只出现一次的字符是"g"。 当从该字符流中读出前六个字符“google"时,第一个只出现一次的字符是"l"。 如果当前字符流没有存在出现一次的字符,返回#字符。 思路: 用hashmap 保存字符的出现的次数, 用s保存是字符的顺序,然后查找顺序查找第一个出现一次的字符 ''' class Solution: # 返回对应char def __init__(self): self.s = [] self.hashmap = {} def FirstAppearingOnce(self): # write code here for i in self.s: if self.hashmap[i] == 1: return i return "#" def Insert(self, char): # write code here self.s.append(char) if char in self.hashmap: self.hashmap[char] += 1 else: self.hashmap[char] = 1 if __name__ == '__main__': s = "google" solution=Solution() for i in s: solution.Insert(i) print(i,solution.FirstAppearingOnce())
# coding:utf-8 ''' 给出一个完全二叉树,求出该树的节点个数。 说明: 完全二叉树的定义如下:在完全二叉树中,除了最底层节点可能没填满外, 其余每层节点数都达到最大值,并且最下面一层的节点都集中在该层最左边的若干位置。 若最底层为第 h 层,则该层包含 1~ 2h 个节点。 ''' class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def countNodes(self, root): return 1 + self.countNodes(root.right) + self.countNodes(root.left) if root else 0 if __name__ == '__main__': solution = Solution()
from Puzzle import Puzzle from PuzzleSolver import PuzzleSolver import utils file = "data/board2.txt" p = Puzzle(utils.board_from_file(file)) logs = open("data/test.txt", "a") solver = PuzzleSolver(p) print(p) y = input("Solve puzzle? (y/n): ") if y == 'y' and p.is_solvable(): solution = solver.a_star() for s in reversed(solution): logs.write(str(s)) logs.write("\n\n") logs.write("Puzzle solved with " + str(len(solution)) + " steps.") logs.close() print("Puzzle solved.") elif y != 'y': print("Solver quit.") else: print("Puzzle is not solvable.")
# na2degrees.py # matthew johnson 18 january 2017 ##################################################### """ We will define graphs as dictionaries where the keys are the nodes and the values are sets containing all neighbours. Here is an example digraph (we can define graphs in the same way --- just need to ensure symmetry) """ ################################################### EXAMPLE = {0: {1, 4, 5, 8}, 1: {4, 6}, 2: {3, 7, 9}, 3: {7}, 4: {2}, 5: {1}, 6: {}, 7: {3}, 8: {1, 2}, 9: {0, 3, 4, 5, 6, 7}} def compute_in_degrees(digraph): """Takes a directed graph and computes the in-degrees for the nodes in the graph. Returns a dictionary with the same set of keys (nodes) and the values are the in-degrees.""" # initialize in-degrees dictionary with zero values for all vertices in_degree = {} for vertex in digraph: in_degree[vertex] = 0 # consider each vertex for vertex in digraph: # amend in_degree[w] for each outgoing edge from v to w for neighbour in digraph[vertex]: in_degree[neighbour] += 1 return in_degree def in_degree_distribution(digraph): """Takes a directed graph and computes the unnormalized distribution of the in-degrees of the graph. Returns a dictionary whose keys correspond to in-degrees of nodes in the graph and values are the number of nodes with that in-degree. In-degrees with no corresponding nodes in the graph are not included in the dictionary.""" # find in_degrees in_degree = compute_in_degrees(digraph) # initialize dictionary for degree distribution degree_distribution = {} # consider each vertex for vertex in in_degree: # update degree_distribution if in_degree[vertex] in degree_distribution: degree_distribution[in_degree[vertex]] += 1 else: degree_distribution[in_degree[vertex]] = 1 return degree_distribution if __name__ == "__main__": print(compute_in_degrees(EXAMPLE)) print(in_degree_distribution(EXAMPLE))
import sqlite3 from sqlite3.dbapi2 import connect from werkzeug.security import check_password_hash, generate_password_hash import logging def encrypt_password(password): """ Function used to encrypt a user's password. :param password: string :return: type: string returns the encrypted password """ return generate_password_hash(password=password) def validate_password(encrypted_password, password): """ Function that receives the encrypted password from the db and the plaintext password entered by the user. It encrypts the plaintext password and compares it with the one stored in the db. :param encrypted_password: string :param password: string :return: type: boolean """ return check_password_hash(encrypted_password, password) def check_user_existence(username): """ Function used to check if the user chosen at the time of registration is already stored in the database. :param username: string :return: type: boolean """ conn = connect(database="DataBase.db") user_exist = False try: cur = conn.cursor() cur.execute("SELECT * FROM users") for i in cur.fetchall(): if i[1] == username: user_exist = True return user_exist except sqlite3.OperationalError as error: print(error) conn.close() def register_user(username, password): """ Function used to register a new user in the database. :param username: string :param password: string :return: type: boolean """ conn = connect(database="DataBase.db") user_register = False try: cur = conn.cursor() password_encrypted = encrypt_password(password) if not check_user_existence(username=username): cur.execute("INSERT INTO users (user_name, password, operator) " f"VALUES ('{username}', '{password_encrypted}', False)") conn.commit() logging.warning('<< REGISTER >> ' + ' USERNAME: ' + username + ' - ' + 'ROL: client') user_register = True return user_register except sqlite3.OperationalError as error: print(error) conn.close() def login_user(username, password): """ Function used for user login. :param username: string :param password: string :return: type: tuple(boolean, boolean) """ conn = connect(database="DataBase.db") validate_user = False is_operator = False try: cur = conn.cursor() cur.execute("SELECT * FROM users") for i in cur.fetchall(): if i[1] == username: if validate_password(i[2], password): if i[3]: is_operator = True logging.warning('<< LOGIN >> ' + ' USERNAME: ' + username + ' - ' + 'ROL: operator') else: logging.warning('<< LOGIN >> ' + ' USERNAME: ' + username + ' - ' + 'ROL: client') validate_user = True return validate_user, is_operator except sqlite3.OperationalError as error: print(error) conn.close()
#!/usr/bin/env python # coding: utf-8 # In[1]: def new_name(): numbers=[] names=[] nam1= input("enter name") num= int(input("enter number")) name=names.append(nam) number=numbers.append(num) return name # In[ ]: new_name() # In[ ]: def new_name(): numbers=[] names=[] names.append(input("enter name")) num= int(input("enter number")) numbers.append(num) return names return numbers # In[15]: def newuser(): global users users=['shrey'] global password password=['hola'] users.append(input('enter your user name')) password.append(input('enter the exces password')) # In[ ]: # In[22]: global users users=['shrey'] global password password=['hola'] # In[19]: newuser() # In[20]: len(users) # In[4]: print('Hello Welcome To All In One Management System') goti= True users=['shrey'] password=['hola'] numbers=[] names=[] leng=len(users)+1 def usercheck(): a=0 while a<leng: if input('enter user id') ==users[a]: if input('enter passcode')== password[a]: return 'ok' else: print('Access Denied ') a+=1 def newuser(): password=['hola'] users.append(input('enter your user name')) password.append(input('enter the exces password')) def newname(): names.append(input("enter name")) num=int(input("enter number")) numbers.append(num) def again(): if input('if you want to run again press y').upper()=='Y': return shrey() else: print ('THANKS!!!! Come back again') def shrey(): if input('do you have an account enter yes or no').upper()=='YES': if usercheck()=='ok': if input('to enter a new number to contact enter ...new... else anything to view the list of contacts').upper()=='NEW': newname() else: x=0 while x<leng: print("{} ".format(names)) print("{} ".format(numbers)) x+=1 else: for m in range(0,20): print('ACCESS DENIED') return shrey() else: newuser() return shrey() shrey() again() # In[3]: shrey() again() # In[ ]:
class Node: def __init__ (self, value): self.value = value self.next = None class SLL: def __init__ (self): self.head = None def addToFront(self, value): new_node = Node(value) new_node.next = self.head self.head = new_node return self def addToBack(self, value): if self.head == None: self.addToFront(value) else: runner = self.head while runner.next: runner = runner.next runner.next = Node(value) return self # def addToBack(self,value): # newNode = Node(value) # if self.head == None: # addToFront(value) # return self # runne = self.head # while runner.next != None: # runner = runner.next # runner.next = Node(value) # return self def displaySLL(self): runner = self.head # display_string = "" # while runner: # display_string += str(runner.value), "-->" # runner = runner.next # print(display_string) while runner: print(runner.value) runner = runner.next #while runner: # print(runner.value, "-->") # runner = runner.next # print (runner.value) # print(runner.next) # print(runner.next.value) # print(runner.next.next) # print(runner.next.next.value) # print(runner.next.next.next) return self def contains (self, value): runner = self.head while runner: if runner.value == value: print("Does it contain this " +int(value)+"?") return True runner = runner.next return False sll1= SLL() sll1.addToFront(9).addToFront(7).addToFront(5).addToBack(40) sll1.displaySLL() print(sll1.contains(9)) # print(sll1)
#Programming Challenge #Elevators in a building #Number_of_elevators = 2 #Number_of_floors = 3 floors >= 1 and <= number_of_floors #I would first create each elevator as an object #elevator1 #properties #floor = #door = open or closed #status = occupied or unoccupied (this would represent elevator moving or not moving) #total_trips = #floors_traveled = #elevator2 #properties #floor = #door = open or closed #status = occupied or unoccupied #total_trips = #floors_traveled = #Would also need to provide for scaling the number of Elevators #I would need to create an object called controller to initiate a call button to summon the elevator #It can't change any property of the elevators but can interact with them #controller def call () #or #create a variable to represent the floor the call is made from call_floor call_floor = input("Select the floor: ") #call button is pushed on call_floor #each elevator would need to relay what floor it is currently on #each elevator would need to relay what status it is in #when call is made, each elevator would respond with its location and status #utilize if statments to prioritize which elevator responds #if elevator status == unoccupied and it is on the floor closest to call_floor, then elevator floor = call_floor #need to create a variable to determine which elevator is closer to the call_floor #if call_floor == elevator_floor and elevator_status == unoccupied, elevator1 = call_floor if elevator_status == occupied: if elevator1_floor > call_floor or elevator1_floor < call_floor: #elevator will not respond to the call #total_trips will not increment #floors traveled will not increment #the other elevator will respond elevator2_floor = call_floor #this represents the elevator moving to the call_floor #This logic will need to be improved to scale for more than 2 elevators in alternate scenarios #This is priority 1 if status == "unoccupied" and elevator_floor == call_floor: total_trips += 1 #increment total_trips floors_traveled += 1 #increment floors_traveled else: #no change to elevator position #the occupied elevator responds if it is at the call floor #This is priority 2 if status == "occupied" and evalator_floor == call_floor: total_trips += 1 #increment total_trips floors_traveled += 1 #increment floors_traveled else: #no change to elevator position #need to handle maxium elevator trips and maintenance #when total_trips >= 100, elevator is no longer available to respond to calls #need to create a way to remove the elevator from #if total_trips >= 100, the elevator will no longer respond to call_floor #not sure how to break the logic here beside moving it out of bounds of the floor (making it 0)
# 装饰器 def log(func): def wrapper(*args, **kwargs): print("log func {}".format(func.__name__)) print(type(args), args) print(type(kwargs), kwargs) return func(*args, **kwargs) return wrapper @log def print_func(*args, **kwargs): print("this is func") print_func(1, 2, 3, a=1, b=2, c=3) ''' log func print_func <class 'tuple'> (1, 2, 3) <class 'dict'> {'a': 1, 'b': 2, 'c': 3} this is func ''' def logs(level): def decorator(func): def wrapper(*args, **kwargs): if level == 'info': print('info') elif level == 'error': print('error') return func(*args, **kwargs) return wrapper return decorator @logs(level='error') def print_logs(): print('start') print_logs() # 类装饰器 class LogCls(object): def __init__(self, func): self.func = func def __call__(self, *args, **kwargs): print('logloglog') self.func(*args, **kwargs) @LogCls def print_log_cls(): print('log_cls') print_log_cls()
with open("input.txt", encoding="utf-8") as file: valid_passwords = 0 for line in file: position = 0 positions, password = line.split(":") min, max_letter = positions.split("-") max, letter = max_letter.split(" ") password = password.strip() if password[int(min) - 1] == letter: position += 1 if password[int(max) - 1] == letter: position += 1 if position == 1: valid_passwords += 1 print(valid_passwords)
import heapq def main(): puzzleType = input("Welcome to Maaz Mohamedy's 8-puzzle solver.\nType '1' to use default puzzle," + " or '2' to enter your own puzzle. \n") if puzzleType == '1': puzzle = pickDefaultArrangement() if puzzleType == '2': puzzle = pickCustomArrangement() algo = input("\tEnter your choice of algorithm" + "\n\t\t1. Uniform Cost Search" "\n\t\t2. A* with the Misplaced Tile heuristic." + "\n\t\t3. A* with the Manhattan distance heuristic.\n\n") print() generalSearch(puzzle,algo) def generalSearch(puzzle, algo): goalState = [[1,2,3],[4,5,6],[7,8,0]] failure = False; maxQueueLen = 0; nodes = [] numExpanded = 0 first = '' for i in range(0,len(puzzle[0])): if puzzle[0][i] != 0: first=first+' '+str(puzzle[0][i]) else: first=first+' '+'b' print("Expanding state " + first, end =" ") printExpansion(puzzle[1:], True, 0, 0) first_expansion = True #total cost, puzzle, depth, h(n) heapq.heappush(nodes, (0, puzzle, 0,0) ) while(True): if len(nodes) == 0: #if nodes is empty, return failure print("Failure") return #Updating the maximum length of queue if maxQueueLen < len(nodes): maxQueueLen = len(nodes) currNode = heapq.heappop(nodes) if currNode[1] == goalState: print("\nGoal!! \n") print("To solve this problem the search algorithm expanded a total of " + str(numExpanded) + " nodes.") print("The maximum number of nodes in the queue at any one time was " + str(maxQueueLen) + ".") print("The depth of the goal node was " + str(currNode[2])) return currNode; if not first_expansion: printExpansion(currNode[1],False,currNode[3], currNode[2]) first_expansion = False numExpanded = numExpanded + 1 children = expand(currNode, algo) for child in children: heapq.heappush(nodes, child) return def misplacedTileHeuristic(puzzle): numMisplaced = 0; val = 1 for i in range(0,len(puzzle)): for j in range(0,len(puzzle[i])): if val == 9: val = 0 if puzzle[i][j] != val and puzzle[i][j] != 0: numMisplaced = numMisplaced + 1 val = val + 1 return numMisplaced def manhattanDistanceHeuristic(puzzle): val = 1 manhattanSum = 0 for i in range(0,len(puzzle)): for j in range(0,len(puzzle[i])): if val == 9: val = 0 if puzzle[i][j] != val and puzzle[i][j] != 0: x,y = findIndicesOfGoalState(puzzle[i][j]) horizontal = abs(j - x) vertical = abs(i - y) moves = horizontal + vertical manhattanSum = manhattanSum + moves val = val + 1 return manhattanSum def findIndicesOfGoalState(val): goal = [[1,2,3], [4,5,6], [7,8,0]] for i in range(0,len(goal)): for j in range(0,len(goal[i])): if goal[i][j] == val: return(j,i) def calculateHeuristic(algo, puzzle): if algo == "1": return 0 if algo == "2": return misplacedTileHeuristic(puzzle) if algo == "3": return manhattanDistanceHeuristic(puzzle) def expand(node, algo): children = [] currPuzzle = node[1] i,j = 0,0 x,y = 0,0 #find blank position of blank space for i in range(0, len(node[1])): for j in range(0, len(node[1][i]) ): if node[1][i][j] == 0: x,y = i,j break if x+1 < (len(node[1])): # shift blank space down shiftDown = list(map(list, node[1],)) shiftDown[x][y], shiftDown[x+1][y] = shiftDown[x+1][y] , shiftDown[x][y] # calculate hn and gn hOfN = calculateHeuristic(algo, shiftDown) gOfN = node[2] + 1 updatedCost = gOfN + hOfN children.append((updatedCost,shiftDown,gOfN,hOfN)) if y-1 >= 0: # shift blank space left shiftLeft = list(map(list, node[1],)) shiftLeft[x][y], shiftLeft[x][y-1] = shiftLeft[x][y-1] , shiftLeft[x][y] # calculate hn and gn hOfN = calculateHeuristic(algo, shiftLeft) gOfN = node[2] + 1 updatedCost = gOfN + hOfN children.append((updatedCost,shiftLeft,gOfN,hOfN)) if x-1 >= 0: # shift blank space up shiftUp = list(map(list, node[1],)) shiftUp[x][y], shiftUp[x-1][y] = shiftUp[x-1][y] , shiftUp[x][y] # calculate hn and gn hOfN = calculateHeuristic(algo, shiftUp) gOfN = node[2] + 1 updatedCost = gOfN + hOfN children.append((updatedCost,shiftUp,gOfN,hOfN)) if y+1 < (len(node[1])): # shift blank space right shiftRight = list(map(list, node[1],)) shiftRight[x][y], shiftRight[x][y+1] = shiftRight[x][y+1] , shiftRight[x][y] # calculate hn and gn hOfN = calculateHeuristic(algo, shiftRight) gOfN = node[2] + 1 updatedCost = gOfN + hOfN children.append((updatedCost,shiftRight,gOfN,hOfN)) return children def printExpansion(puzzle,first,hOfN, gOfN): print() row = '' if not first: print('The best state to expand with a g(n) = ' + str(gOfN)+ ' and h(n) = ' + str(hOfN) + ' is...') for i in range(0,len(puzzle)): for j in range(0,len(puzzle[i])): if puzzle[i][j] != 0: row = row + ' '+ str(puzzle[i][j]) else: row=row+' '+'b' row = '\t\t' + row if first == False and i == 2: row = row + ' Expanding this node...' print(row) row = '' def pickCustomArrangement(): puzzle = [] print("\tEnter your puzzle, use a zero to represent the blank") row1 = input("\tEnter the first row, use space or tabs between numbers\t").split() row2 = input("\tEnter the second row, use space or tabs between numbers\t").split() row3 = input("\tEnter the third row, use space or tabs between numbers\t").split() print() for i in range(0, 3): row1[i] = int(row1[i]) row2[i] = int(row2[i]) row3[i] = int(row3[i]) puzzle.append(row1) puzzle.append(row2) puzzle.append(row3) return puzzle def pickDefaultArrangement(): level = input("Which level of difficulty do you want? \nType '1' for Trivial, '2' for Very Easy," + " '3' for Easy, '4' for doable, '5' for Oh Boy, '6' for impossible. \n") #trivial if level == '1': trivial = [[1,2,3], [4,5,6], [7,8,0]] return trivial; #Very Easy if level == '2': veryEasy = [[1,2,3], [4,5,6], [7,0,8]] return veryEasy; #Easy if level == '3': easy = [[1,2,0], [4,5,3], [7,8,6]] return easy; #doable if level == '4': doable = [[0,1,2], [4,5,3], [7,8,6]] return doable; #Oh Boyy if level == '5': ohBoy = [[8,7,1], [6,0,2], [5,4,3]] return ohBoy; #IMPOSSIBLE if level == '6': impossible = [[1,2,3], [4,5,6], [8,7,0]] return impossible; if __name__ == "__main__": main()
list_a = [10, 20, 30] list_b = [10, 20, 30] if list_a is list_b: print('list_a is list_b') else: print('list_a is not list_b') print('list_a 는{}'.format(id(list_a))) print('list_b 는{}'.format(id(list_b))) num_a = {"a":1, "b":1} num_b = {"a":1, "b":1} if num_a is num_b: print('num_a is num_b') else: print('num_a is not num_b') num_a = (1, 2, 3) num_b = (1, 2, 3) if num_a is not num_b: print('num_a is num_b') else: print('num_a is not num_b') #if 3 is not 3: # print('list_a is list_b') #else: # print('list_a is not list_b') #if list_a == list_b: # print('list_a is list_b') #else: # print('list_a is not list_b')
#coding:utf-8 ''' try语句按照如下方式工作; 首先,执行try子句(在关键字try和关键字except之间的语句) 如果没有异常发生,忽略except子句,try子句执行后结束。 如果在执行try子句的过程中发生了异常,那么try子句余下的部分将被忽略。如果异常的类型和 except 之后的名称相符,那么对应的except子句将被执行。最后执行 try 语句之后的代码。 如果一个异常没有与任何的except匹配,那么这个异常将会传递给上层的try中。 ''' if __name__=="__main__": print("python异常") ''' while True: try: x = input("请输入一个数字:") try: a = int(x) print("你输入的数字是整数:", a) except: try: a = float(x) print("你输入的数字是浮点数:", a) except: a = complex(x) print("你输入的数字是复数:", a) except: print("你输入的不是数字!") else: goon = input("是否继续?Y/N") if str(goon).upper() == 'N': break ''' print("raise抛出异常") if True: try: raise NameError("异常测试") except NameError as e: print(e) print("自定义异常") #自定义异常类 class MyTestError(Exception): def __init__(self, value): self.value = value def __str__(self): return repr(self.value) #finally 无论是否有异常都会执行 try: try: raise MyTestError("test") finally: print("finally test") except MyTestError as e: print(e) #定义预清理行为 #在文件操作用with open(file,mode) as f 中,无论后续处理文件是否有异常都会close掉打开的文件 ######################################################################## ''' assert 断言 assert expression 等价于: if not expression raise AssertionError assert 后面也可以紧跟参数: assert expression [, arguments] if not expression: raise AssertionError(arguments) ''' print("assert Test") try: assert 1==2 except AssertionError as e: print("assert1", e) try: assert 1==2, "当断言失败时,异常描述信息" except AssertionError as e: print("assert2", e)
# -*- coding:utf-8 -*- ''' 斐波那契数列,下一个数为前两个数之和 ''' if __name__ == "__main__": a, b = 0, 1 while(b<10): a, b = b, a+b #print(b) print(b, end=" ")
# -*- coding:utf-8 -*- ''' 元组Tuple:与列表list类似,但是无法修改其中的元素 ''' if __name__ == '__main__': print("元组测试") tuple1 = ('a', 1 , 1.2, ['b', 4],('c',5)) #访问具体元素 print(tuple1[3]) #访问第2个到第4个元素 print(tuple1[1:4]) #访问第2个到最后一个元素 print(tuple1[1:]) #访问第1个到倒数第二个元素 print(tuple1[:-1]) #访问全部元素 print(tuple1) print(tuple1[:]) #以步长为2的方式访问元素 print(tuple1[::2]) #倒序输出 print(tuple1[::-1]) #重复输出元素 print(tuple1 * 2) #元组拼接 print(tuple1 + tuple1[2:4]) #修改元组中的元素是非法的 print("修改元组中的元素是非法的") #以下执行报错 ''' Traceback (most recent call last): File "D:/IDEA/workspace-github-whq/whq-python-base/python-base/com/whq/python/base/basic_datatype_tuple.py", line 40, in <module> tuple1[1] = 2 TypeError: 'tuple' object does not support item assignment ''' #tuple1[1] = 2 print(tuple1) #但是可以修改元组中的列表中的元素 #将['b', 4] 改成 ['', 4] tuple1[3][0] = "c" print(tuple1) print("单个元素的元组声明") tuple2 = () print("空元组 ", tuple2) ''' Traceback (most recent call last): File "D:/IDEA/workspace-github-whq/whq-python-base/python-base/com/whq/python/base/basic_datatype_tuple.py", line 53, in <module> print("单个元素的元组,声明时未加逗号 ", tuple3[0]) TypeError: 'int' object is not subscriptable ''' tuple3 = (1) #print("单个元素的元组,声明时未加逗号 ", tuple3[0]) tuple4 = (2,) print("单个元素的元组,声明时加逗号 ", tuple4[0])
class Solution: def is_palindrome(self, x): import math if x <= 0: return x == 0 log_answer = math.log10(x) total_digits = math.floor(log_answer) + 1 msd_mask = math.pow(10, total_digits - 1) for i in range(total_digits // 2): most_sig_digit = x // msd_mask ones_place_digit = x % 10 if most_sig_digit != ones_place_digit: return False x %= msd_mask # remove most sig digit x //= 10 # remove last sig digit msd_mask //= 100 # remove two zero's from the mask return True if __name__ == '__main__': test_cases = [(9232, False), (12321, True), (1, True), (-121, False)] for tc in test_cases: assert tc[1] == Solution().is_palindrome(tc[0])
print("we are going to look for greater or lower or equal number ") x = int(input("X: ")) y = int(input("Y: ")) if x < y: print("x is less than Y") elif x > y: print("X is greter than Y") else: print("X is equal to Y") print("Thank You For playing") print("this is to make life easy")
def readFile(input_name): return [l.strip() for l in open(input_name, "r").readlines()] def shouldChange(limit, seat, adj): if seat == "#" and adj.count("#") >= limit: return "L" if seat == "L" and not "#" in adj: return "#" return seat # Could be more than 2x faster. Was lazy to do it def part1(d): rlength = len(d[0]) + 2 prev = ["*" * rlength] * 2 for x in d: prev.insert(-1, "*" + x + "*") change = True while change: actuall, occupied = ["*" * rlength] * 2, 0 for i in range(1, len(prev) - 1): row = "*" for j in range(1, rlength - 1): row += shouldChange(4, prev[i][j], [prev[i+1][j], prev[i-1][j], prev[i][j+1], prev[i][j-1], prev[i+1][j+1], prev[i-1][j-1], prev[i+1][j-1], prev[i-1][j+1]]) row += "*" occupied += row.count("#") actuall.insert(-1, row) if prev == actuall: change = False prev = actuall return occupied def notEmpty(seat): return seat == "L" or seat == "#" or seat == "*" #In Hungary, this what's called a lumberjack solution.. It's not a positive saying def part2(d): rlength = len(d[0]) + 2 prev = ["*" * rlength] * 2 for x in d: prev.insert(-1, "*" + x + "*") change = True while change: actuall, occupied = ["*" * rlength] * 2, 0 for i in range(1, len(prev) - 1): row = "*" for j in range(1, rlength - 1): can_see = [] for r in range(j+1, rlength): if notEmpty(prev[i][r]): can_see.append(prev[i][r]) break for l in range(j-1, 0, -1): if notEmpty(prev[i][l]): can_see.append(prev[i][l]) break for d in range(i+1, len(prev)): if notEmpty(prev[d][j]): can_see.append(prev[d][j]) break for u in range(i-1, 0, -1): if notEmpty(prev[u][j]): can_see.append(prev[u][j]) break se = i for rd in range(j+1, rlength): se += 1 if notEmpty(prev[se][rd]): can_see.append(prev[se][rd]) break se = i for ru in range(j+1, rlength): se -= 1 if notEmpty(prev[se][ru]): can_see.append(prev[se][ru]) break se = i for ld in range(j-1, 0, -1): se += 1 if notEmpty(prev[se][ld]): can_see.append(prev[se][ld]) break se = i for lu in range(j-1, 0, -1): se -= 1 if notEmpty(prev[se][lu]): can_see.append(prev[se][lu]) break row += shouldChange(5, prev[i][j], can_see) row += "*" occupied += row.count("#") actuall.insert(-1, row) if prev == actuall: change = False prev = actuall return occupied def main(): data = readFile("day11.txt") print(part1(data)) print(part2(data)) if __name__ == "__main__": main()
def readFile(input_name): with open(input_name) as f: return [line.strip()[:-1].split(" (contains ") for line in f] def allergenList(d): alergen_list = [] for ingredients, allergens in d: ingredients, allergens = ingredients.split(" "), allergens.split(", ") for allergen in allergens: alergen_list.append([allergen, ingredients]) return sorted(alergen_list) def removeDuplicates(dlist): dlist = {ale: ing for ale, ing in sorted(dlist, key = lambda x: len(x[1]))} for x in dlist: for y in dlist: actual = dlist[x][0] if len(dlist[x]) > 1 else dlist[x] if x != y: dlist[y] = [ing for ing in dlist[y] if ing not in actual] return ["".join(dlist[z]) for z in sorted(dlist.keys())] def part1(d, dangerous): counter = 0 for x in d: for y in x[0].split(" "): if y not in dangerous: counter += 1 return counter def part2(d): allergen_list, dangerous = allergenList(d), [] common_allergens, prev_ingredients = allergen_list[0][0], allergen_list[0][1] for allergen, ingredients in allergen_list: if allergen == common_allergens: prev_ingredients = list(set(ingredients).intersection(prev_ingredients)) else: dangerous.append([common_allergens, sorted(prev_ingredients, reverse = True)]) common_allergens, prev_ingredients = allergen, ingredients dangerous.append([common_allergens, prev_ingredients]) return removeDuplicates(dangerous) def main(): data = readFile("day21.txt") p2 = part2(data) print(part1(data, p2)) print(",".join(x for x in p2)) if __name__ == "__main__": main()
import sqlite3 # create a new database if the database doesn't already exist with sqlite3.connect("new.db") as connection: c = connection.cursor() c.execute("INSERT INTO population VALUES('New York City', 'NY', 8400000)") c.execute("INSERT INTO population VALUES('San Francisco', 'CA', 800000)")
''' generates a bunch of random data calculates the largest learning rate to use then tries to fit the following line to that data y=w1*x + w2 to it lots of cheesy plotting ''' import random import constants import utils import numpy as np import matplotlib.pyplot as plt def gettotalerror_vectorize(w,x,y): ''' returns the total regressed error over the dataset x,y for the given params w1,w2 :param x: :param y: :param w :return: ''' return np.sum((1 / 2) * (y - w @ x) ** 2, axis=1) / len(x[0]) def main_vectorize(x,y,w,lr): ''' dynamically plot linear regression :param x: :param y: :param w1: :param w2: :param lr: learning rate, calculate from LR_finder :return: ''' plt.ion() #interactive on fig = plt.figure() ax = fig.add_subplot(111) cnt = 0 for epoch_num in range(constants.NUM_EPOCHS): w = backprop_vectorize(lr, w, x, y) tot_error = np.sum((1/2)*(y-w@x)**2, axis=1)/len(x[0]) if(cnt%5==0): utils.plotdata(x[0,:],y,w[0,0],w[0,1], lr, tot_error[0],epoch_num) # print(f"w1={w[0,0]} w2={w[0,1]} totalerror={tot_error}") # if(cnt%40 == 0): # # see if learning rate has changed # lr = utils.find_learning_rate_vectorize(x, y, w, backprop_vectorize,gettotalerror_vectorize plt_lrs = False) cnt+=1 plt.ioff() plt.show() def backprop_vectorize(lr, w, x, y): ''' backprop over errorfunction to adjust w1 and w2 :param lr: learning rate :param w: weight vector (same size as x, add 1 to end if necessary) :param x: values vector dependent :param y: results vector independent :return: ''' #the first param has all the values, get the number of columns for the number of samples numb_samples=len(x[0]) # sum derivatives total = np.sum(-(y - w @ x) * x, axis=1) # divide by numb_samples grad_w = total / numb_samples # adjust w1 and w2 w = w - np.transpose(lr * grad_w) return w if __name__=="__main__": np.random.seed(1) #repeatability x, y = utils.gendata() # create random data w1, w2 = constants.INITIAL_WEIGHTS # initial weights w = np.array([[w1, w2]]) x = np.asarray(x) x = np.vstack((x, np.ones((x.shape[0]), dtype=x.dtype))) # first find the largest learning rate that allows model convergence best_lr = utils.find_learning_rate_vectorize(x, y, w, backprop_vectorize,gettotalerror_vectorize, plt_lrs=True) #run the regressor main_vectorize(x, y, w, lr=best_lr)
""" The evaluation module contains all classes used to evaluate expressions. """ from printing import Printer from expressions import Function, Sequence, Symbol, Bindings class Kernel: """ This class is provides the context for the evaluation of expressions. It manages the rule set, substitution environments and the the assigned attributes. """ def __init__(self, printer=None): if printer is None: printer = Printer() self.printer = printer self.rules = [] def add_rule(self, rule): """ Add a rule to the kernel rule set. **Parameters:** *rule* - The rule to add. **Returns:** ``None`` """ self.rules.append(rule) def print(self, expression): """ Prints the expression using the registered printer. **Parameters:** *expression* - The expression to print. **Returns:** ``None`` """ print(self.printer.to_string(expression)) def evaluate(self, expression): """ Evaluate the expression using the kernel rules set. Evaluation works by repeatedly applying all rules until the output no longer changes. Since rewriting system are turing complete it is impossible to know whether this will lead to an infinite loop. So the system keeps track of the number of replacements that have been made and when this number exceeds some threshold the kernel stops the evaluation and returns the expression it got. **Parameters:** *expression* - The expression to evaluate. **Returns:** The evaluated expression. """ # FIXME: Somehow this function doesn't really do what it should. It calls itself more often than needed. changed = True old_expression = expression while changed: changed = False for rule in self.rules: c, expression = rule.apply(expression) changed = changed or c if changed: # print(rule) print(old_expression, '->', expression) # print() break # FIXME: This code is very slow. There has to be a better way! if isinstance(expression, Function): new_head = expression.head new_head = self.evaluate(new_head) new_arguments = [] for argument in expression.argument_sequence.expressions: new_arguments.append(self.evaluate(argument)) expression = Function(new_head, Sequence(new_arguments)) if old_expression != expression: return self.evaluate(expression) return expression def evaluate_and_print(self, expression): """ First evaluates the expression and then prints the evaluated expression using the registered printer. **Parameters:** *expression* - The expression to evaluate and print. **Returns:** ``None`` """ self.print(self.evaluate(expression)) kernel = Kernel() class Rule: """ Base class for all rules. """ def apply(self, expression): """ Applies this rule to the given expression. This method should be overwritten by anyone subclassing this class. **Parameters:** *expression* - The expression the rule is applied to. **Returns:** ``None`` """ pass class SubstitutionRule(Rule): """ A SubstitutionRule consists of a pattern, a substitution expression and zero or more guards. When applied it will check whether the given expression matches its pattern and substitute the matching expressions by the substitution expression. """ def __init__(self, pattern, substitution, guards=None): if guards is None: guards = [] self.guards = guards self.pattern = pattern self.substitution = substitution self.guards = guards def apply(self, expression): bindings = Bindings() for match in self.pattern.match(expression, bindings): bindings = match.bindings for guard in self.guards: if not kernel.evaluate(guard.substitute(bindings)) == Symbol('True'): return False, expression return True, self.substitution.substitute(bindings) return False, expression def __str__(self): return str(self.pattern) + ' -> ' + str(self.substitution) class LambdaRule(Rule): """ A LambdaRule consists of a pattern, a lambda function and zero or more guards. When applied it will check whether the given expression matches its pattern and call the lambda function on the matching expressions. This rule is often used for addition and multiplication of integers which is hard to expression only using :py:class:`~evaluation.SubstitutionRule`. """ def __init__(self, pattern, code, guards=None): if guards is None: guards = [] self.guards = guards self.pattern = pattern self.code = code def apply(self, expression): bindings = Bindings() for match in self.pattern.match(expression, bindings): bindings = match.bindings guards_satisfied = True for guard in self.guards: if not kernel.evaluate(guard.substitute(bindings)) == Symbol('True'): guards_satisfied = False if guards_satisfied: return True, self.code(bindings).substitute(bindings) return False, expression
# -*- coding: utf-8 -*- #-the in keyword can also be used to checl #to see if one string is 'in' another string #-the in expression is a logical expression and returns #true or false and can be used in an if statement fruit = 'banana' 'n' in fruit 'm' in fruit 'nan' in fruit if 'a' in fruit : print 'found it!'
largest_so_far = -1 print 'before:', largest_so_far for the_num in [9, 41, 12, 3, 74, 15]: if the_num > largest_so_far : largest_so_far = the_num print 'new largest | numbers:' print largest_so_far, '|', the_num print 'so, the largest number is:', largest_so_far # -*- coding: utf-8 -*- #We make a variable that contains the largest value we have seen so far. #If the current number we are looking at is larger, #it is the new largest value we have seen so far.
# -*- coding: utf-8 -*- def test(a, b, c, d): a += 1 b = 'Alice' c.append(2) d['age'] = 16 q = 5 w = 'hello' e = [] r = {} test(q, w, e, r) print(q) print(w) print(e) print(r) s = r s['age'] = 17 print(s) print(r) d = w d = 'Alice' print(w) print(d) h = q h = 6 print(h) print(q)
# -*- coding: utf-8 -*- #An average just combines the counting and sum patterns #and divides when the loop is done #把之前的算几个loop,和loop值的sum,加在一个程序,计算average #average = sum(总值) 除于 count(数量) # # # count = 0 sum = 0 print 'before', count, sum for value in [9,41, 12, 3, 74, 15]: count = count + 1 sum = sum + value print 'count | sum | value' print count,',', sum,',', value print 'after', count,',', sum,',', float(sum / count)
from drawman import * from time import sleep def f(x): return x*x print(drawman_scale) drawman_scale(100) x = -5.0 to_point(x, f(x)) pen_down() while x <= 5: to_point(x, f(x)) x += 0.1 pen_up() sleep(7)
#!/usr/bin/python3.8 # 1: Даны два произвольные списка. Удалите из первого списка элементы присутствующие во втором списке. my_list_1 = [2, 5, 8, 2, 12, 12, 4] my_list_2 = [2, 7, 12, 3] temp_list = [] for num_list1 in my_list_1: if num_list1 not in my_list_2: temp_list.append(num_list1) print(temp_list)
def ex1(): string1= raw_input("Digite uma palavra: ") tam = len(string1) print "A palavra dada tem tamanho:",tam
import numpy def pythagoreanTheorem(length_a, length_b): length_c = numpy.sqrt(numpy.square(length_a) + numpy.square(length_b)) print(length_c) def list_mangler(list_in): list_out = list() for x in list_in: if x%2==0 : list_out.append(x*2) else : list_out.append(x*3) print(list_out) def grade_calc(grades_in, to_drop): grades_in.sort(reverse=True) grades_in = grades_in[0:-to_drop] total = 0 grade = 0 for x in grades_in: total = total + x grade = total/len(grades_in) if grade >= 90: print("A") elif grade >= 80: print("B") elif grade >= 70: print("C") elif grade >= 60: print("D") else : print("F") def odd_even_filter(numbers): odd_numbers = list() even_numbers = list() for x in numbers: if(x%2==0) : even__numbers.append(x) else : odd_numbers.append(x) numbers.clear() numbers.append(even_numbers) numbers.append(odd_numbers) print(numbers) if __name__ == "__main__": print("in main") list_mangler([1,2,3,4]) list_mangler([2,3,4,5]) list_mangler([3,4,5,6]) grade_calc([100, 90, 80, 95], 2) grade_calc([80,80,80,80], 2) grade_calc([70,70,70,70], 2) odd_even_filter([1, 2, 3, 4, 5, 6, 7, 8, 9]) odd_even_filter([3, 9, 43, 7]) odd_even_filter([71, 39, 98, 79, 5, 89, 50, 90, 2, 56])
# -*- coding: utf-8 -*- """ Created on Tue Dec 6 18:20:07 2016 @author: Egor """ class Tree: def __init__(self): self.nodes = list() # negative result self.nodes.append(dict({0: None, 1: None, 2: None})) # positive result self.nodes.append(dict({0: None, 1: None, 2: None})) def addNode(self, rules, pred=[], succ=1): if (type(rules) == set): rules = list([rules]) self.nodes.append(dict({0: 1 - succ, 1: succ, 2: rules})) if (len(pred) > 0): self.nodes[pred[0]][pred[1]] = len(self.nodes) - 1 def walkDownTheTree(self, attribute, start_with=2): if (start_with < 2): return start_with for i in self.nodes[start_with][2]: if (len(attribute - (attribute & i)) == 0): result = 1 break else: result = 0 return self.walkDownTheTree(attribute, self.nodes[start_with][result])
#You can download the sample data at http://www.pythonlearn.com/code/mbox-short.txt when you are testing below enter mbox-short.txt as the file name. # Use the file name mbox-short.txt as the file name def openfile(): fname = raw_input("Enter file name: ") try: fh = open(fname, 'r') except: print "Error opening file", fname quit() return fh def computeAverage(fh): average = None count = 0 for line in fh: if line.startswith("X-DSPAM-Confidence:") : count = count + 1 columnPos = line.find(":") number = line[columnPos+1::1] snumber = number.lstrip() if average is None: average = 0 snumber = float(snumber.rstrip()) average = ( (average * ((count -1)) + snumber) / count ) #print "new average", average return average fh = openfile() print "Average spam confidence:", computeAverage(fh)
import numpy as np import pandas as pd numbers = [1, 2, 3, 4, 5] #mean print np.mean(numbers) #median print np.median(numbers) #standard devation print np.std(numbers) #Series: one dimensional object like a list or column in database, 0 to n-1 indices series = pd.Series(['Shamikh', 'Hossain', 'Duke', 19, 223], index = ['First Name', 'Last Name', 'College', 'Age', 'Room Number']) print series print series['First Name'] print series[1] #normal index notation print cuteness = pd.Series([1, 2, 3, 4, 5], index=['Cockroach', 'Fish', 'Mini Pig','Puppy', 'Kitten']) print cuteness > 3 #prints booleans! print cuteness[cuteness > 3] #prints values data = {'year': [2010, 2011, 2012, 2011, 2012, 2010, 2011, 2012], 'team': ['Bears', 'Bears', 'Bears', 'Packers', 'Packers', 'Lions','Lions', 'Lions'], 'wins': [11, 8, 10, 15, 11, 6, 10, 4], 'losses': [5, 8, 6, 1, 5, 10, 6, 12] } football = pd.DataFrame(data) print football print football.dtypes #data types for each column print "" print football.describe() #basic statistics print "" print football.head() #first five rows print "" print football.tail() #last five rows ################# # DataFrame Syntax Reminder: # # The following code would create a two-column pandas DataFrame # named df with columns labeled 'name' and 'age': # # people = ['Sarah', 'Mike', 'Chrisna'] # ages = [28, 32, 25] # df = DataFrame({'name' : Series(people), # 'age' : Series(ages)}) countries = ['Russian Fed.', 'Norway', 'Canada', 'United States', 'Netherlands', 'Germany', 'Switzerland', 'Belarus', 'Austria', 'France', 'Poland', 'China', 'Korea', 'Sweden', 'Czech Republic', 'Slovenia', 'Japan', 'Finland', 'Great Britain', 'Ukraine', 'Slovakia', 'Italy', 'Latvia', 'Australia', 'Croatia', 'Kazakhstan'] gold = [13, 11, 10, 9, 8, 8, 6, 5, 4, 4, 4, 3, 3, 2, 2, 2, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0] silver = [11, 5, 10, 7, 7, 6, 3, 0, 8, 4, 1, 4, 3, 7, 4, 2, 4, 3, 1, 0, 0, 2, 2, 2, 1, 0] bronze = [9, 10, 5, 12, 9, 5, 2, 1, 5, 7, 1, 2, 2, 6, 2, 4, 3, 1, 2, 1, 0, 6, 2, 1, 0, 1] # your code here olympics = pd.DataFrame({'country_name': pd.Series(countries), 'gold' : pd.Series(gold), 'silver' : pd.Series(silver), 'bronze' : pd.Series(bronze)}) print olympics print olympics[['gold', 'country_name']] print olympics.loc[1] #all countries with at least one medal print olympics[olympics['gold'] >= 1] print olympics['gold'].map(lambda x: x >= 1) print olympics.applymap(lambda x: x >= 1) avg = np.mean(olympics['bronze'][olympics['gold'] >= 1]) print avg #take mean print olympics['gold'].apply(np.mean) numbers = [1, 2, 3, 4, 5] numbers_2 = [6, 7, 8, 9, 10] dotproduct = np.dot(numbers, numbers_2) print dotproduct #dot product is each index of each vector multiplied with the other, and then added a = [1, 2] b = [[2, 4, 6], [3, 5, 7]] print np.dot(a, b) medal_counts = olympics[['gold', 'silver', 'bronze']] #selecting specific columns from a dataframe points = np.dot(medal_counts, [4, 2, 1]) #dot product for each country olympic_points = pd.DataFrame({'country_name': pd.Series(countries), 'points' : pd.Series(points)}) print olympic_points
from collections import Counter #Opening a file in read mode fp=open("sample.txt","r") count=0 #Split each line into words and store it in w #Counting the number of words which is the length of w and adding it to a variable for j in fp: w=j.split() print(w) print(len(w)) count=count+len(w) print("The number of words:",count) #Output ''' ['What', 'can', 'Python', 'do?'] 4 ['Python', 'can', 'be', 'used', 'on', 'a', 'server', 'to', 'create', 'web', 'applications.'] 11 ['Python', 'can', 'be', 'used', 'alongside', 'software', 'to', 'create', 'workflows.'] 9 ['Python', 'can', 'connect', 'to', 'database', 'systems.', 'It', 'can', 'also', 'read', 'and', 'modify', 'files.'] 13 ['Python', 'can', 'be', 'used', 'to', 'handle', 'big', 'data', 'and', 'perform', 'complex', 'mathematics.'] 12 ['Python', 'can', 'be', 'used', 'for', 'rapid', 'prototyping,', 'or', 'for', 'production-ready', 'software', 'development.'] 12 The number of words: 61 '''
str1="This is Python " str2="75 challenge" #Printing the variables by combining them. + operator is used to combine print(str1+str2) #Output #This is Python 75 challenge
from collections import deque class Graph: """ Graph Class Represents a directed or undirected graph. """ def __init__(self, is_directed=True): """ Initialize a graph object with an empty vertex dictionary. Parameters: is_directed (boolean): Whether the graph is directed (edges go in only one direction). """ self.vertex_dict = {} # id -> list of neighbor ids self.is_directed = is_directed def add_vertex(self, vertex_id): """ Add a new vertex object to the graph with the given key. Parameters: vertex_id (string): The unique identifier for the new vertex. """ if self.contains_vertex(vertex_id): return # self.vertex_dict[vertex_id] = Vertex(vertex_id).get_neighbors_ids() self.vertex_dict[vertex_id] = [] def add_edge(self, start_id, end_id): """ Add an edge from vertex with id `start_id` to vertex with id `end_id`. Parameters: start_id (string): The unique identifier of the first vertex. end_id (string): The unique identifier of the second vertex. """ self.add_vertex(start_id) self.add_vertex(end_id) self.vertex_dict[start_id].append(end_id) if not self.is_directed: self.vertex_dict[end_id].append(start_id) def contains_vertex(self, vertex_id): """Return True if the vertex is contained in the graph.""" if vertex_id in self.vertex_dict: return True return False def contains_edge(self, start_id, end_id): """ Return True if the edge is contained in the graph from vertex `start_id` to vertex `end_id`. Parameters: start_id (string): The unique identifier of the first vertex. end_id (string): The unique identifier of the second vertex.""" if not self.contains_vertex(start_id): return False for neighbor_id in self.vertex_dict[start_id]: if neighbor_id == end_id: return True return False def get_vertices(self): """ Return all vertices in the graph. Returns: list<string>: The vertex ids contained in the graph. """ return list(self.vertex_dict.keys()) def get_neighbors(self, start_id): """ Return a list of neighbors to the vertex `start_id`. Returns: list<string>: The neigbors of the start vertex. """ return self.vertex_dict[start_id] def __str__(self): """Return a string representation of the graph.""" graph_repr = [f'{vertex} -> {self.vertex_dict[vertex]}' for vertex in self.vertex_dict.keys()] return f'Graph with vertices: \n' +'\n'.join(graph_repr) def __repr__(self): """Return a string representation of the graph.""" return self.__str__() def bfs_traversal(self, start_id): """ Traverse the graph using breadth-first search. """ if start_id not in self.vertex_dict: raise KeyError("The start vertex is not in the graph!") # Keep a set to denote which vertices we've seen before seen = set() seen.add(start_id) # Keep a queue so that we visit vertices in the appropriate order queue = deque() queue.append(start_id) path = [] while queue: current_vertex_id = queue.popleft() path.append(current_vertex_id) # Process current node print('Processing vertex {}'.format(current_vertex_id)) # Add its neighbors to the queue for neighbor_id in self.get_neighbors(current_vertex_id): if neighbor_id not in seen: seen.add(neighbor_id) queue.append(neighbor_id) return path def find_shortest_path(self, start_id, target_id): """ Find and return the shortest path from start_id to target_id. Parameters: start_id (string): The id of the start vertex. target_id (string): The id of the target (end) vertex. Returns: list<string>: A list of all vertex ids in the shortest path, from start to end. """ if not self.contains_vertex(start_id) and not self.contains_vertex(target_id): raise KeyError("The start and/or target vertex is not in the graph!") vertex_id_to_path = {start_id: [start_id]} #keeps track of the vertices we’ve seen so far, and stores their shortest paths queue = deque() queue.append(start_id) while queue: current_vertex_id = queue.popleft() if current_vertex_id == target_id: break for neighbor_id in self.get_neighbors(current_vertex_id): if neighbor_id not in vertex_id_to_path: vertex_id_to_path[neighbor_id] = vertex_id_to_path[current_vertex_id] + [neighbor_id] queue.append(neighbor_id) if target_id not in vertex_id_to_path: return None return vertex_id_to_path[target_id] def find_vertices_n_away(self, start_id, target_distance): """ Find and return all vertices n distance away. Arguments: start_id (string): The id of the start vertex. target_distance (integer): The distance from the start vertex we are looking for Returns: list<string>: All vertex ids that are `target_distance` away from the start vertex Psedocode make an empty list called n_distance_vertices make a dictionary vertices key start_id vertex: value distance away from start_id vertex make a queue add start_id to queue while queue is not empthy make variable current vertex equal to queue popped if value for curreent vertex in vertices is equal to target distance append it to n_distance_vertices for neighbor in neighbors of current vertex if neighbor is not in vertices add neighbor to vertices equal to current vertex of vertices plus 1 add neighbor to queue return n_distance_vertices """ n_distance_vertices = [] vertices = {start_id: 0} queue = deque() queue.append(start_id) while queue: current_vertex_id = queue.popleft() if vertices[current_vertex_id] == target_distance: n_distance_vertices.append(current_vertex_id) for neighbor_id in self.get_neighbors(current_vertex_id): if neighbor_id not in vertices: vertices[neighbor_id] = vertices[current_vertex_id] + 1 queue.append(neighbor_id) return n_distance_vertices def is_bipartite(self): """ Return True if the graph is bipartite, and False otherwise Psedocode make a variable v1 equal to the item at index 0 of get_vertices() make a dictionary vertex_id_group with v1 as key and 0 as value make a queue and append v1 to it while queue is not empty set a variable current_vertex_id equal to queue popped for neighbor in current_vertex_id's neighbors if neighbor is not in vertex_id_group add neighbor to vertex_id_group with current_vertex_id's key plus 1 append the neighbor to queue for vertex in vertex_id_group for neighbor in vertex's neighbors if the value of vertex in vertex_id_group is even if value of neighbor in vertex_id_group is even return false if the value of vertex in vertex_id_group is odd if value of neighbor in vertex_id_group is odd return false return true """ # if len(self.get_vertices()) == 3: # raise KeyError("naw mate") v1 = self.get_vertices()[0] vertex_id_group = {v1: 0} queue = deque() queue.append(v1) while queue: current_vertex_id = queue.popleft() for neighbor_id in self.get_neighbors(current_vertex_id): if neighbor_id not in vertex_id_group: vertex_id_group[neighbor_id] = vertex_id_group[current_vertex_id] + 1 queue.append(neighbor_id) for v in vertex_id_group: for neighbor in self.get_neighbors(v): if vertex_id_group[v] % 2 == 0: if vertex_id_group[neighbor] % 2 == 0: return False # if vertex_id_group[v] % 2 != 0: else: if vertex_id_group[neighbor] % 2 != 0: return False return True def get_connected(self, start_id, visit): visited = set() queue = deque() queue.append(start_id) visited.add(start_id) while queue: v = queue.popleft() for vertex in self.get_neighbors(v): if vertex not in visited: queue.append(vertex) visited.add(vertex) visit(vertex) return list(visited) def find_connected_components(self): """ Return a list of all connected components, with each connected component represented as a list of vertex ids. """ visited = set() connected_components = [] for vertex in self.get_vertices(): if vertex not in visited: visited.add(vertex) connected_components.append(self.get_connected(vertex, visited.add)) return connected_components def find_path_dfs_iter(self, start_id, target_id): """ Use DFS with a stack to find a path from start_id to target_id. """ if not self.contains_vertex(start_id) and not self.contains_vertex(target_id): raise KeyError("The start vertex and/or target vertex are/is not in the graph!") seen = set() seen.add(start_id) stack = [start_id] path = [] while stack: current_vertex = stack.pop() path.append(current_vertex) if target_id == current_vertex: return path for neighbor in self.get_neighbors(current_vertex): stack.append(neighbor) raise KeyError("Path does not exist") def dfs_traversal(self, start_id): """Visit each vertex, starting with start_id, in DFS order.""" visited = set() # set of vertices we've visited so far path = [] def dfs_traversal_recursive(start_vertex): print(f'Visiting vertex {start_vertex}') # recurse for each vertex in neighbors for neighbor in self.get_neighbors(start_vertex): if neighbor not in visited: visited.add(neighbor) path.append(neighbor) dfs_traversal_recursive(neighbor) return path visited.add(start_id) path.append(start_id) return dfs_traversal_recursive(start_id) def contains_cycle(self): """ Return True if the directed graph contains a cycle, False otherwise. """ current_path = set() def contains_cycle_dfs(start_id, path): for neighbor in self.get_neighbors(start_id): if neighbor in path: return True path.add(neighbor) return contains_cycle_dfs(neighbor, path) return False start_id = self.get_vertices()[0] current_path.add(start_id) return contains_cycle_dfs(start_id, current_path) def topological_sort_dfs(self, start_id, visited): for neighbor in self.get_neighbors(start_id): if neighbor not in visited: visited.add(neighbor) self.topological_sort_dfs(neighbor, visited) def topological_sort(self): """ Return a valid ordering of vertices in a directed acyclic graph. If the graph contains a cycle, throw a ValueError. """ # TODO: Create a stack to hold the vertex ordering. # TODO: For each unvisited vertex, execute a DFS from that vertex. # TODO: On the way back up the recursion tree (that is, after visiting a # vertex's neighbors), add the vertex to the stack. # TODO: Reverse the contents of the stack and return it as a valid ordering. if self.contains_cycle(): raise ValueError('graph contains a cycle') visited = set() stack = [] for vertex in self.get_vertices(): visited.add(vertex) self.topological_sort_dfs(vertex, visited) stack.append(vertex) v = stack.pop() stack.insert(0, v) return stack
from random import randint magic=randint(0,9) input ('') print (randint(0,9)) if magic==1: print ("You will be okay") if magic==2: print ("Soon you will find out but not today") if magic==3: print ("Yes") if magic==4: print ("No") if magic==5: print ("You are wise and will give the advice") if magic==6: print ("WHY ARE YOU DOING THIS") if magic==7: print ("You are not wise") if magic==8: print ("Family is the key") if magic==9: print ("Hello")
# 204101 sec 002 # Lab Homework 02 ข้อ 2 # Anurak Boonyaritpanit # 560510680 # ฟังก์ชั่นสำหรับแปลงค่าอุณภูมิจากองศา เซลเซียส -> ฟาเรนไฮต์ def convertTempCelsiusToFahrenheit( celsius ): fahrenheit = float((celsius * 9/5) + 32) return fahrenheit # ฟังก์ชั่นหลัก ทำงานที่นี่เป็นที่แรก def main(): celsius = float(input("Input temperature in Celsius: ")) fahrenheit = convertTempCelsiusToFahrenheit(celsius) print("{:0.2f} Celsius = {:0.2f} Fahrenheit".format(celsius, fahrenheit)) if __name__ == "__main__": # execute only if run as a script main()
# 204101 sec 002 # Lab Homework 7 assignment 2 # Anurak Boonyaritpanit # 560510680 # In this case to show use "for" loop ============================================================================================================================ # uncomment code below to show # DEFINE initial value mySum = 0 n = int(input("n: ")) for x in range(n): num = float(input("Input number: ")) # Input number # DEFINE initial value if( x == 0): myMax = num myMin = num # Compare value of number if(num < myMin): myMin = num if(num > myMax): myMax = num mySum = mySum + num # Find sum: x=0-> mySum= 0+num myMean = mySum/n # Find x bar # myMean is floating point. And You want convert 2 digits ex. 11.2345687 -> 11.23 use round(number, ndigits) ปัดเศษนั่นเอง # myMean = round(myMean, 2) # Display value in terminal/cmd/console # print("mySum =",mySum) print("min =",myMin) print("max =",myMax) # If you use round() function. The .format() unnessessary -> print("myMean =",myMean) print("mean = {:0.2f}".format(myMean)) # In this case to show use "while" loop And define initial min max mean sum to first number of input==================================================================================================================================== # uncomment code below to show # n = int(input("n: ")) # num = float(input("Input number: ")) # # DEFINE initial value # myMax = num # myMin = num # mySum = num # x=0 # dont forget to start point value # while(x < n-1): # # Input number # num = float(input("Input number: ")) # # Compare value of number # if(num < myMin): # myMin = num # if(num > myMax): # myMax = num # mySum = mySum + num # Find sum: x=0-> mySum= 0+num # x = x+1 # increment x +1 for control loop # myMean = mySum/n # Find x bar # # Display value in terminal/cmd/console # # print("mySum =",mySum) # print("min =",myMin) # print("max =",myMax) # print("mean = {:0.2f}".format(myMean))
# 204101 sec 002 # Lab Homework 6 ข้อ 2 # Anurak Boonyaritpanit # 560510680 num = int(input("num = ")) factorial = 1 if( num == 0): factorial = 0 else: for n in range(1,num+1): factorial = factorial*n print("{}!={}".format(num,factorial))
class NPC: def __init__(self, name, items, money, phrase): self.name = name self.items = items self.money = money self.phrase = phrase def talk(self): print(self.phrase) def sell(self, char): c = 1 for i in self.items: print(str(c) + ". " + i.name + ": " + str(i.cost)) c += 1 print("or 0 to quit") choice = input("Choose an item to buy: ") while choice == "": choice = input("Choose: ") while not choice.isdigit(): choice = input("Choose a number: ") choice = int(choice) - 1 if choice == -1: return item = self.items[choice] if char.money >= item.cost: if item.type == "weapon" or item.type == "staff": print("You can only have one weapon at a time.") print("Do you want to trade weapons?") print("1. Yes") print("2. No") val = str(input("Well? ")) if val == "1": char.money += char.items["weapon"].cost char.money -= item.cost self.money += item.cost char.items["weapon"] = item print("You have bought the {}!".format(item.name)) return self.money, self.items, char.items, char.money elif val == "2": print("Okay, that's fine.") else: return elif item.type == "armor": print("You can only have one armor at a time.") print("Do you want to trade armors?") print("1. Yes") print("2. No") val = str(input("Well? ")) if val == "1": char.money += char.items["armor"].cost char.money -= item.cost self.money += item.cost char.items["armor"] = item print("You have bought the {}!".format(item.name)) return self.money, self.items, char.items, char.money elif val == "2": print("Okay, that's fine.") else: return else: temp_var = char.items["items"] temp_var.append(item) char.items["items"] = temp_var char.money -= item.cost self.money += item.cost print("You have bought a {}!".format(item.name)) return self.money, self.items, char.items, char.money else: print("You don't have enough gold!") int(input("Choose an item to buy: ")) - 1 def buy(self, char): c = 1 for i in char.items["items"]: print(str(c) + ". " + i.name + ": " + str(i.cost)) c += 1 print("or 0 to quit") choice = input("Choose an item to sell: ") while choice == "": choice = input("Choose: ") while not choice.isdigit(): choice = input("Choose a number: ") choice = int(choice) - 1 if choice == -1: return item = char.items["items"][choice] char.money += item.cost self.money -= item.cost del char.items["items"][choice] return self.money, self.items, char.items, char.money def sell_drink(self, char, drink): temp_var = char.items["items"] temp_var.append(drink) char.items["items"] = temp_var char.money -= drink.cost self.money += drink.cost print("You have bought a {}!".format(drink.name)) return self.money, self.items, char.items, char.money